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/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/strings/contains_test.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <cudf/strings/contains.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <string>
class StringsContainsTest : public cudf::test::BaseFixture {};
TEST_F(StringsContainsTest, Contains)
{
auto input = cudf::test::strings_column_wrapper({"Héllo", "thesé", "tést strings", ""});
auto view = cudf::strings_column_view(input);
auto const pattern = std::string("[a-z]");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::contains_re(view, *prog, cudf::test::get_default_stream());
cudf::strings::matches_re(view, *prog, cudf::test::get_default_stream());
cudf::strings::count_re(view, *prog, cudf::test::get_default_stream());
}
TEST_F(StringsContainsTest, Like)
{
auto input = cudf::test::strings_column_wrapper({"Héllo", "thesés", "tést", ""});
auto view = cudf::strings_column_view(input);
auto const pattern = cudf::string_scalar("%és", true, cudf::test::get_default_stream());
auto const escape = cudf::string_scalar("%", true, cudf::test::get_default_stream());
cudf::strings::like(view, pattern, escape, cudf::test::get_default_stream());
auto const patterns = cudf::test::strings_column_wrapper({"H%", "t%s", "t", ""});
cudf::strings::like(
view, cudf::strings_column_view(patterns), escape, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/strings/find_test.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/strings/find.hpp>
#include <cudf/strings/find_multiple.hpp>
#include <cudf/strings/findall.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <string>
class StringsFindTest : public cudf::test::BaseFixture {};
TEST_F(StringsFindTest, Find)
{
auto input = cudf::test::strings_column_wrapper({"Héllo", "thesé", "tést strings", ""});
auto view = cudf::strings_column_view(input);
auto const target = cudf::string_scalar("é", true, cudf::test::get_default_stream());
cudf::strings::find(view, target, 0, -1, cudf::test::get_default_stream());
cudf::strings::rfind(view, target, 0, -1, cudf::test::get_default_stream());
cudf::strings::find(view, view, 0, cudf::test::get_default_stream());
cudf::strings::find_multiple(view, view, cudf::test::get_default_stream());
cudf::strings::contains(view, target, cudf::test::get_default_stream());
cudf::strings::starts_with(view, target, cudf::test::get_default_stream());
cudf::strings::starts_with(view, view, cudf::test::get_default_stream());
cudf::strings::ends_with(view, target, cudf::test::get_default_stream());
cudf::strings::ends_with(view, view, cudf::test::get_default_stream());
auto const pattern = std::string("[a-z]");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::findall(view, *prog, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/strings/split_test.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/split/partition.hpp>
#include <cudf/strings/split/split.hpp>
#include <cudf/strings/split/split_re.hpp>
#include <string>
class StringsSplitTest : public cudf::test::BaseFixture {};
TEST_F(StringsSplitTest, SplitPartition)
{
auto input = cudf::test::strings_column_wrapper({"Héllo thesé", "tést strings", ""});
auto view = cudf::strings_column_view(input);
auto const delimiter = cudf::string_scalar("é", true, cudf::test::get_default_stream());
cudf::strings::split(view, delimiter, -1, cudf::test::get_default_stream());
cudf::strings::rsplit(view, delimiter, -1, cudf::test::get_default_stream());
cudf::strings::split_record(view, delimiter, -1, cudf::test::get_default_stream());
cudf::strings::rsplit_record(view, delimiter, -1, cudf::test::get_default_stream());
cudf::strings::partition(view, delimiter, cudf::test::get_default_stream());
cudf::strings::rpartition(view, delimiter, cudf::test::get_default_stream());
auto const pattern = std::string("\\s");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::split_re(view, *prog, -1, cudf::test::get_default_stream());
cudf::strings::split_record_re(view, *prog, -1, cudf::test::get_default_stream());
cudf::strings::rsplit_re(view, *prog, -1, cudf::test::get_default_stream());
cudf::strings::rsplit_record_re(view, *prog, -1, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/strings/strings_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/strings/padding.hpp>
#include <cudf/strings/slice.hpp>
#include <cudf/strings/strip.hpp>
#include <cudf/strings/wrap.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <string>
class StringsTest : public cudf::test::BaseFixture {};
TEST_F(StringsTest, Strip)
{
auto input = cudf::test::strings_column_wrapper({" aBc ", " ", "aaaa ", "\tb"});
auto view = cudf::strings_column_view(input);
auto const strip = cudf::string_scalar(" ", true, cudf::test::get_default_stream());
auto const side = cudf::strings::side_type::BOTH;
cudf::strings::strip(view, side, strip, cudf::test::get_default_stream());
}
TEST_F(StringsTest, Pad)
{
auto input = cudf::test::strings_column_wrapper({"333", "", "4444", "1"});
auto view = cudf::strings_column_view(input);
auto const side = cudf::strings::side_type::BOTH;
cudf::strings::pad(view, 6, side, " ", cudf::test::get_default_stream());
cudf::strings::zfill(view, 6, cudf::test::get_default_stream());
}
TEST_F(StringsTest, Wrap)
{
auto input = cudf::test::strings_column_wrapper({"the quick brown fox jumped"});
auto view = cudf::strings_column_view(input);
cudf::strings::wrap(view, 6, cudf::test::get_default_stream());
}
TEST_F(StringsTest, Slice)
{
auto input = cudf::test::strings_column_wrapper({"hello", "these", "are test strings"});
auto view = cudf::strings_column_view(input);
auto start = cudf::numeric_scalar(2, true, cudf::test::get_default_stream());
auto stop = cudf::numeric_scalar(5, true, cudf::test::get_default_stream());
auto step = cudf::numeric_scalar(1, true, cudf::test::get_default_stream());
cudf::strings::slice_strings(view, start, stop, step, cudf::test::get_default_stream());
auto starts = cudf::test::fixed_width_column_wrapper<cudf::size_type>({1, 2, 3});
auto stops = cudf::test::fixed_width_column_wrapper<cudf::size_type>({4, 5, 6});
cudf::strings::slice_strings(view, starts, stops, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/strings/replace_test.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/replace.hpp>
#include <cudf/strings/replace_re.hpp>
#include <string>
class StringsReplaceTest : public cudf::test::BaseFixture {};
TEST_F(StringsReplaceTest, Replace)
{
auto input = cudf::test::strings_column_wrapper({"Héllo", "thesé", "tést strings", ""});
auto view = cudf::strings_column_view(input);
auto const target = cudf::string_scalar("é", true, cudf::test::get_default_stream());
auto const repl = cudf::string_scalar(" ", true, cudf::test::get_default_stream());
cudf::strings::replace(view, target, repl, -1, cudf::test::get_default_stream());
cudf::strings::replace(view, view, view, cudf::test::get_default_stream());
cudf::strings::replace_slice(view, repl, 1, 2, cudf::test::get_default_stream());
auto const pattern = std::string("[a-z]");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::replace_re(view, *prog, repl, 1, cudf::test::get_default_stream());
cudf::test::strings_column_wrapper repls({"1", "a", " "});
cudf::strings::replace_re(view,
{pattern, pattern, pattern},
cudf::strings_column_view(repls),
cudf::strings::regex_flags::DEFAULT,
cudf::test::get_default_stream());
}
TEST_F(StringsReplaceTest, ReplaceRegex)
{
auto input = cudf::test::strings_column_wrapper({"Héllo", "thesé", "tést strings", ""});
auto view = cudf::strings_column_view(input);
auto const repl = cudf::string_scalar(" ", true, cudf::test::get_default_stream());
auto const pattern = std::string("[a-z]");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::replace_re(view, *prog, repl, 1, cudf::test::get_default_stream());
cudf::test::strings_column_wrapper repls({"1", "a", " "});
cudf::strings::replace_re(view,
{pattern, pattern, pattern},
cudf::strings_column_view(repls),
cudf::strings::regex_flags::DEFAULT,
cudf::test::get_default_stream());
}
TEST_F(StringsReplaceTest, ReplaceRegexBackref)
{
auto input = cudf::test::strings_column_wrapper({"Héllo thesé", "tést strings"});
auto view = cudf::strings_column_view(input);
auto const repl_template = std::string("\\2-\\1");
auto const pattern = std::string("(\\w) (\\w)");
auto const prog = cudf::strings::regex_program::create(pattern);
cudf::strings::replace_with_backrefs(
view, *prog, repl_template, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/text/edit_distance_test.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 <nvtext/edit_distance.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
class TextEditDistanceTest : public cudf::test::BaseFixture {};
TEST_F(TextEditDistanceTest, EditDistance)
{
auto const input = cudf::test::strings_column_wrapper({"dog", "cat", "mouse", "pupper"});
auto const input_view = cudf::strings_column_view(input);
auto const target = cudf::test::strings_column_wrapper({"hog", "cake", "house", "puppy"});
auto const target_view = cudf::strings_column_view(target);
nvtext::edit_distance(input_view, target_view, cudf::test::get_default_stream());
nvtext::edit_distance_matrix(input_view, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/text/stemmer_test.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 <nvtext/stemmer.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
class TextStemmerTest : public cudf::test::BaseFixture {};
TEST_F(TextStemmerTest, IsLetter)
{
auto const input =
cudf::test::strings_column_wrapper({"abbey", "normal", "creates", "yearly", "trouble"});
auto const view = cudf::strings_column_view(input);
auto const delimiter = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
nvtext::is_letter(view, nvtext::letter_type::VOWEL, 0, cudf::test::get_default_stream());
auto const indices = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 3, 5, 4});
nvtext::is_letter(view, nvtext::letter_type::VOWEL, indices, cudf::test::get_default_stream());
}
TEST_F(TextStemmerTest, Porter)
{
auto const input =
cudf::test::strings_column_wrapper({"abbey", "normal", "creates", "yearly", "trouble"});
auto const view = cudf::strings_column_view(input);
nvtext::porter_stemmer_measure(view, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/text/ngrams_test.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 <nvtext/generate_ngrams.hpp>
#include <nvtext/ngrams_tokenize.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
class TextNGramsTest : public cudf::test::BaseFixture {};
TEST_F(TextNGramsTest, GenerateNgrams)
{
auto const input =
cudf::test::strings_column_wrapper({"the", "fox", "jumped", "over", "thé", "dog"});
auto const separator = cudf::string_scalar{"_", true, cudf::test::get_default_stream()};
nvtext::generate_ngrams(
cudf::strings_column_view(input), 3, separator, cudf::test::get_default_stream());
}
TEST_F(TextNGramsTest, GenerateCharacterNgrams)
{
auto const input =
cudf::test::strings_column_wrapper({"the", "fox", "jumped", "over", "thé", "dog"});
nvtext::generate_character_ngrams(
cudf::strings_column_view(input), 3, cudf::test::get_default_stream());
}
TEST_F(TextNGramsTest, HashCharacterNgrams)
{
auto input =
cudf::test::strings_column_wrapper({"the quick brown fox", "jumped over the lazy dog."});
nvtext::hash_character_ngrams(
cudf::strings_column_view(input), 5, cudf::test::get_default_stream());
}
TEST_F(TextNGramsTest, NgramsTokenize)
{
auto input =
cudf::test::strings_column_wrapper({"the quick brown fox", "jumped over the lazy dog."});
auto const delimiter = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
auto const separator = cudf::string_scalar{"_", true, cudf::test::get_default_stream()};
nvtext::ngrams_tokenize(
cudf::strings_column_view(input), 2, delimiter, separator, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/text/tokenize_test.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 <nvtext/tokenize.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
class TextTokenizeTest : public cudf::test::BaseFixture {};
TEST_F(TextTokenizeTest, Tokenize)
{
auto const input = cudf::test::strings_column_wrapper({"the fox jumped", "over thé dog"});
auto const view = cudf::strings_column_view(input);
auto const delimiter = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
nvtext::tokenize(view, delimiter, cudf::test::get_default_stream());
nvtext::count_tokens(view, delimiter, cudf::test::get_default_stream());
auto const delimiters = cudf::test::strings_column_wrapper({" ", "o", "é"});
nvtext::tokenize(view, cudf::strings_column_view(delimiters), cudf::test::get_default_stream());
nvtext::count_tokens(
view, cudf::strings_column_view(delimiters), cudf::test::get_default_stream());
}
TEST_F(TextTokenizeTest, CharacterTokenize)
{
auto const input =
cudf::test::strings_column_wrapper({"the", "fox", "jumped", "over", "thé", "dog"});
nvtext::character_tokenize(cudf::strings_column_view(input), cudf::test::get_default_stream());
}
TEST_F(TextTokenizeTest, Detokenize)
{
auto const input =
cudf::test::strings_column_wrapper({"the", "fox", "jumped", "over", "thé", "dog"});
auto const view = cudf::strings_column_view(input);
auto const indices = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 0, 1, 1, 1});
auto const separator = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
nvtext::detokenize(view, indices, separator, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/text/replace_test.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <nvtext/normalize.hpp>
#include <nvtext/replace.hpp>
class TextReplaceTest : public cudf::test::BaseFixture {};
TEST_F(TextReplaceTest, Replace)
{
auto const input = cudf::test::strings_column_wrapper({"the fox jumped over the dog"});
auto const targets = cudf::test::strings_column_wrapper({"the", "dog"});
auto const repls = cudf::test::strings_column_wrapper({"_", ""});
auto const delimiter = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
nvtext::replace_tokens(cudf::strings_column_view(input),
cudf::strings_column_view(targets),
cudf::strings_column_view(repls),
delimiter,
cudf::test::get_default_stream());
}
TEST_F(TextReplaceTest, Filter)
{
auto const input = cudf::test::strings_column_wrapper({"one two three", "four five six"});
auto const delimiter = cudf::string_scalar{" ", true, cudf::test::get_default_stream()};
auto const repl = cudf::string_scalar{"_", true, cudf::test::get_default_stream()};
nvtext::filter_tokens(
cudf::strings_column_view(input), 1, delimiter, repl, cudf::test::get_default_stream());
}
TEST_F(TextReplaceTest, NormalizeSpaces)
{
auto input =
cudf::test::strings_column_wrapper({"the\tquick brown\nfox", "jumped\rover the lazy\r\t\n"});
nvtext::normalize_spaces(cudf::strings_column_view(input), cudf::test::get_default_stream());
}
TEST_F(TextReplaceTest, NormalizeCharacters)
{
auto input = cudf::test::strings_column_wrapper({"abc£def", "éè â îô\taeio", "\tĂĆĖÑ Ü"});
nvtext::normalize_characters(
cudf::strings_column_view(input), false, cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/io/csv_test.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/io/csv.hpp>
#include <cudf/io/detail/csv.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <cudf_test/iterator_utilities.hpp>
#include <string>
#include <vector>
auto const temp_env = static_cast<cudf::test::TempDirTestEnvironment*>(
::testing::AddGlobalTestEnvironment(new cudf::test::TempDirTestEnvironment));
class CSVTest : public cudf::test::BaseFixture {};
TEST_F(CSVTest, CSVWriter)
{
constexpr auto num_rows = 10;
std::vector<size_t> zeros(num_rows, 0);
std::vector<size_t> ones(num_rows, 1);
auto col6_data = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return numeric::decimal128{ones[i], numeric::scale_type{12}};
});
auto col7_data = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return numeric::decimal128{ones[i], numeric::scale_type{-12}};
});
cudf::test::fixed_width_column_wrapper<bool> col0(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int8_t> col1(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int16_t> col2(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int32_t> col3(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<float> col4(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<double> col5(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<numeric::decimal128> col6(col6_data, col6_data + num_rows);
cudf::test::fixed_width_column_wrapper<numeric::decimal128> col7(col7_data, col7_data + num_rows);
std::vector<std::string> col8_data(num_rows, "rapids");
cudf::test::strings_column_wrapper col8(col8_data.begin(), col8_data.end());
cudf::table_view tab({col0, col1, col2, col3, col4, col5, col6, col7, col8});
auto const filepath = temp_env->get_temp_dir() + "multicolumn.csv";
auto w_options = cudf::io::csv_writer_options::builder(cudf::io::sink_info{filepath}, tab)
.include_header(false)
.inter_column_delimiter(',');
cudf::io::write_csv(w_options.build(), cudf::test::get_default_stream());
}
TEST_F(CSVTest, CSVReader)
{
constexpr auto num_rows = 10;
std::vector<size_t> zeros(num_rows, 0);
std::vector<size_t> ones(num_rows, 1);
auto col6_data = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return numeric::decimal128{ones[i], numeric::scale_type{12}};
});
auto col7_data = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return numeric::decimal128{ones[i], numeric::scale_type{-12}};
});
cudf::test::fixed_width_column_wrapper<bool> col0(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int8_t> col1(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int16_t> col2(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<int32_t> col3(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<float> col4(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<double> col5(zeros.begin(), zeros.end());
cudf::test::fixed_width_column_wrapper<numeric::decimal128> col6(col6_data, col6_data + num_rows);
cudf::test::fixed_width_column_wrapper<numeric::decimal128> col7(col7_data, col7_data + num_rows);
std::vector<std::string> col8_data(num_rows, "rapids");
cudf::test::strings_column_wrapper col8(col8_data.begin(), col8_data.end());
cudf::table_view tab({col0, col1, col2, col3, col4, col5, col6, col7, col8});
auto const filepath = temp_env->get_temp_dir() + "multicolumn.csv";
auto w_options = cudf::io::csv_writer_options::builder(cudf::io::sink_info{filepath}, tab)
.include_header(false)
.inter_column_delimiter(',');
cudf::io::write_csv(w_options.build(), cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/streams
|
rapidsai_public_repos/cudf/cpp/tests/streams/io/json_test.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/io/detail/json.hpp>
#include <cudf/io/json.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_wrapper.hpp>
#include <cudf_test/default_stream.hpp>
#include <cudf_test/iterator_utilities.hpp>
#include <string>
#include <vector>
class JSONTest : public cudf::test::BaseFixture {};
TEST_F(JSONTest, JSONreader)
{
std::string data = "[1, 1.1]\n[2, 2.2]\n[3, 3.3]\n";
cudf::io::json_reader_options in_options =
cudf::io::json_reader_options::builder(cudf::io::source_info{data.data(), data.size()})
.dtypes(std::vector<cudf::data_type>{cudf::data_type{cudf::type_id::INT32},
cudf::data_type{cudf::type_id::FLOAT64}})
.lines(true)
.legacy(true);
cudf::io::table_with_metadata result =
cudf::io::read_json(in_options, cudf::test::get_default_stream());
}
TEST_F(JSONTest, JSONwriter)
{
cudf::test::strings_column_wrapper col1{"a", "b", "c"};
cudf::test::strings_column_wrapper col2{"d", "e", "f"};
cudf::test::fixed_width_column_wrapper<int> col3{1, 2, 3};
cudf::test::fixed_width_column_wrapper<float> col4{1.5, 2.5, 3.5};
cudf::test::fixed_width_column_wrapper<int16_t> col5{{1, 2, 3},
cudf::test::iterators::nulls_at({0, 2})};
cudf::table_view tbl_view{{col1, col2, col3, col4, col5}};
cudf::io::table_metadata mt{{{"col1"}, {"col2"}, {"int"}, {"float"}, {"int16"}}};
std::vector<char> out_buffer;
auto destination = cudf::io::sink_info(&out_buffer);
auto options_builder = cudf::io::json_writer_options_builder(destination, tbl_view)
.include_nulls(true)
.metadata(mt)
.lines(false)
.na_rep("null");
cudf::io::write_json(options_builder.build(), cudf::test::get_default_stream());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/labeling/label_bins_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/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/labeling/label_bins.hpp>
#include <cudf/types.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/type_list_utilities.hpp>
#include <cudf_test/type_lists.hpp>
#include <algorithm>
#include <limits>
#include <numeric>
#include <vector>
namespace {
template <typename T>
using fwc_wrapper = cudf::test::fixed_width_column_wrapper<T>;
template <typename T>
using fpc_wrapper = cudf::test::fixed_point_column_wrapper<T>;
// TODO: Should we move these into type_lists? They seem generally useful.
using cudf::test::FixedPointTypes;
using cudf::test::FloatingPointTypes;
using NumericTypesNotBool =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, FloatingPointTypes>;
using SignedNumericTypesNotBool =
cudf::test::Types<int8_t, int16_t, int32_t, int64_t, float, double>;
struct BinTestFixture : public cudf::test::BaseFixture {};
/*
* Test error cases.
*
* Most of these are not parameterized by type to avoid unnecessary test overhead.
*/
// Left edges type check.
TEST(BinColumnErrorTests, TestInvalidLeft)
{
fwc_wrapper<double> left_edges{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> right_edges{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fwc_wrapper<float> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
// Right edges type check.
TEST(BinColumnErrorTests, TestInvalidRight)
{
fwc_wrapper<float> left_edges{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<double> right_edges{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fwc_wrapper<float> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
// Input type check.
TEST(BinColumnErrorTests, TestInvalidInput)
{
fwc_wrapper<float> left_edges{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> right_edges{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fwc_wrapper<double> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
// Number of left and right edges must match.
TEST(BinColumnErrorTests, TestMismatchedEdges)
{
fwc_wrapper<float> left_edges{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> right_edges{1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
// Left edges with nulls.
TEST(BinColumnErrorTests, TestLeftEdgesWithNullsBefore)
{
fwc_wrapper<float> left_edges{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
fwc_wrapper<float> right_edges{1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
// Right edges with nulls.
TEST(BinColumnErrorTests, TestRightEdgesWithNullsBefore)
{
fwc_wrapper<float> left_edges{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
fwc_wrapper<float> right_edges{{1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
fwc_wrapper<float> input{0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
EXPECT_THROW(
cudf::label_bins(input, left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO),
cudf::logic_error);
};
/*
* Valid exceptional cases.
*/
template <typename T>
struct GenericExceptionCasesBinTestFixture : public BinTestFixture {
void test(fwc_wrapper<T> input,
fwc_wrapper<cudf::size_type> expected,
fwc_wrapper<T> left_edges,
fwc_wrapper<T> right_edges)
{
auto result =
cudf::label_bins(input, left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
};
template <typename T>
struct ExceptionCasesBinTestFixture : public GenericExceptionCasesBinTestFixture<T> {};
TYPED_TEST_SUITE(ExceptionCasesBinTestFixture, NumericTypesNotBool);
// Empty input must return an empty output.
TYPED_TEST(ExceptionCasesBinTestFixture, TestEmptyInput)
{
this->test({}, {}, {0, 2, 4, 6, 8}, {2, 4, 6, 8, 10});
};
// If no edges are provided, the bin for all inputs is null.
TYPED_TEST(ExceptionCasesBinTestFixture, TestEmptyEdges)
{
this->test({1, 1}, {{0, 0}, {0, 0}}, {}, {});
};
// Values outside the bounds should be labeled NULL.
TYPED_TEST(ExceptionCasesBinTestFixture, TestOutOfBoundsInput)
{
this->test({7, 9, 11, 13}, {{3, 4, 0, 0}, {1, 1, 0, 0}}, {0, 2, 4, 6, 8}, {2, 4, 6, 8, 10});
};
// Null inputs must map to nulls.
TYPED_TEST(ExceptionCasesBinTestFixture, TestInputWithNulls)
{
this->test(
{{1, 3, 5, 7}, {0, 1, 0, 1}}, {{0, 1, 0, 3}, {0, 1, 0, 1}}, {0, 2, 4, 6, 8}, {2, 4, 6, 8, 10});
};
// Test that nan values are assigned the NULL label.
template <typename T>
struct NaNBinTestFixture : public GenericExceptionCasesBinTestFixture<T> {};
TYPED_TEST_SUITE(NaNBinTestFixture, FloatingPointTypes);
TYPED_TEST(NaNBinTestFixture, TestNaN)
{
if (std::numeric_limits<TypeParam>::has_quiet_NaN) {
this->test(
{std::numeric_limits<TypeParam>::quiet_NaN()}, {{0}, {0}}, {0, 2, 4, 6, 8}, {2, 4, 6, 8, 10});
}
}
/*
* Test inclusion options.
*/
template <typename T>
struct BoundaryExclusionBinTestFixture : public BinTestFixture {
void test(cudf::inclusive left_inc,
cudf::inclusive right_inc,
fwc_wrapper<cudf::size_type> expected)
{
fwc_wrapper<T> left_edges{0, 2, 4, 6, 8};
fwc_wrapper<T> right_edges{2, 4, 6, 8, 10};
fwc_wrapper<T> input{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto result = cudf::label_bins(input, left_edges, left_inc, right_edges, right_inc);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
};
TYPED_TEST_SUITE(BoundaryExclusionBinTestFixture, NumericTypesNotBool);
// Boundary points when both bounds are excluded should be labeled null.
TYPED_TEST(BoundaryExclusionBinTestFixture, TestNoIncludes)
{
this->test(cudf::inclusive::NO,
cudf::inclusive::NO,
{{0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5}, {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}});
};
// Boundary point 1 should be in bin 1 [1, 2).
TYPED_TEST(BoundaryExclusionBinTestFixture, TestIncludeLeft)
{
this->test(cudf::inclusive::YES,
cudf::inclusive::NO,
{{0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}});
};
// Boundary point 1 should be in bin 0 (0, 1].
TYPED_TEST(BoundaryExclusionBinTestFixture, TestIncludeRight)
{
this->test(cudf::inclusive::NO,
cudf::inclusive::YES,
{{0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}});
};
/*
* Test real data.
*/
// Test numeric data of reasonable size with noncontiguous bins.
template <typename T>
struct RealDataBinTestFixture : public BinTestFixture {
void test(unsigned int num_elements = 512,
unsigned int inputs_per_bin = 4,
T left_edge_start_val = 0)
{
// Avoid testing numbers that are larger than the current type supports.
const T largest_value = (num_elements / inputs_per_bin) * 4;
num_elements = std::min(std::numeric_limits<T>::max(), largest_value);
unsigned int num_edges = num_elements / inputs_per_bin;
std::vector<T> left_edge_vector(num_edges);
std::vector<T> right_edge_vector(num_edges);
std::vector<T> partial_input_vector(num_edges);
std::vector<T> input_vector;
std::vector<cudf::size_type> partial_expected_vector(num_edges);
std::vector<cudf::size_type> expected_vector;
std::vector<unsigned int> expected_validity(num_elements, 1);
std::iota(left_edge_vector.begin(), left_edge_vector.end(), left_edge_start_val);
// Create noncontiguous bins of width 2 separate by 2, and place inputs in the middle of each
// bin.
std::transform(
left_edge_vector.begin(), left_edge_vector.end(), left_edge_vector.begin(), [](T val) {
return val * 4;
});
std::transform(
left_edge_vector.begin(), left_edge_vector.end(), right_edge_vector.begin(), [](T val) {
return val + 2;
});
std::transform(
left_edge_vector.begin(), left_edge_vector.end(), partial_input_vector.begin(), [](T val) {
return val + 1;
});
std::iota(partial_expected_vector.begin(), partial_expected_vector.end(), 0);
// Create vector containing duplicates of all the inputs.
input_vector.reserve(num_elements);
expected_vector.reserve(num_elements);
for (unsigned int i = 0; i < inputs_per_bin; ++i) {
input_vector.insert(
input_vector.end(), partial_input_vector.begin(), partial_input_vector.end());
expected_vector.insert(
expected_vector.end(), partial_expected_vector.begin(), partial_expected_vector.end());
}
// Column wrappers are necessary inputs for the function.
fwc_wrapper<T> left_edges(left_edge_vector.begin(), left_edge_vector.end());
fwc_wrapper<T> right_edges(right_edge_vector.begin(), right_edge_vector.end());
fwc_wrapper<T> input(input_vector.begin(), input_vector.end());
fwc_wrapper<cudf::size_type> expected(
expected_vector.begin(), expected_vector.end(), expected_validity.begin());
auto result =
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
};
TYPED_TEST_SUITE(RealDataBinTestFixture, NumericTypesNotBool);
TYPED_TEST(RealDataBinTestFixture, TestRealData256) { this->test(256); };
TYPED_TEST(RealDataBinTestFixture, TestRealData512) { this->test(512); };
TYPED_TEST(RealDataBinTestFixture, TestRealData1024) { this->test(1024); };
// Test negative numbers for signed types.
template <typename T>
struct NegativeNumbersBinTestFixture : public RealDataBinTestFixture<T> {
void test(unsigned int num_elements = 512, unsigned int inputs_per_bin = 4)
{
RealDataBinTestFixture<T>::test(
num_elements, inputs_per_bin, -static_cast<T>(num_elements / 2));
}
};
TYPED_TEST_SUITE(NegativeNumbersBinTestFixture, SignedNumericTypesNotBool);
TYPED_TEST(NegativeNumbersBinTestFixture, TestNegativeNumbers256) { this->test(256); };
TYPED_TEST(NegativeNumbersBinTestFixture, TestNegativeNumbers512) { this->test(512); };
TYPED_TEST(NegativeNumbersBinTestFixture, TestNegativeNumbers1024) { this->test(1024); };
/*
* Test fixed point types.
*/
template <typename T>
struct FixedPointBinTestFixture : public BinTestFixture {};
TYPED_TEST_SUITE(FixedPointBinTestFixture, FixedPointTypes);
TYPED_TEST(FixedPointBinTestFixture, TestFixedPointData)
{
using fpc_type_wrapper = fpc_wrapper<cudf::device_storage_type_t<TypeParam>>;
fpc_type_wrapper left_edges{{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}, numeric::scale_type{0}};
fpc_type_wrapper right_edges{{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, numeric::scale_type{0}};
fpc_type_wrapper input{{25, 25, 25, 25, 25, 25, 25, 25, 25, 25}, numeric::scale_type{0}};
auto result =
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO);
// Check that every element is placed in bin 2.
fwc_wrapper<cudf::size_type> expected{{2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
};
/*
* Test strings.
*/
// Basic test of strings of lowercase alphanumerics.
TEST(TestStringData, SimpleStringTest)
{
cudf::test::strings_column_wrapper left_edges{"a", "b", "c", "d", "e"};
cudf::test::strings_column_wrapper right_edges{"b", "c", "d", "e", "f"};
cudf::test::strings_column_wrapper input{"abc", "bcd", "cde", "def", "efg"};
auto result =
cudf::label_bins(input, left_edges, cudf::inclusive::YES, right_edges, cudf::inclusive::NO);
fwc_wrapper<cudf::size_type> expected{{0, 1, 2, 3, 4}, {1, 1, 1, 1, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
};
// Test non-ASCII characters.
TEST(TestStringData, NonAsciiStringTest)
{
cudf::test::strings_column_wrapper left_edges{"A"};
cudf::test::strings_column_wrapper right_edges{"z"};
cudf::test::strings_column_wrapper input{"Héllo",
"thesé",
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
auto result =
cudf::label_bins(input, left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO);
fwc_wrapper<cudf::size_type> expected{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
// Test sliced non-ASCII characters.
TEST(TestStringData, SlicedNonAsciiStringTest)
{
cudf::test::strings_column_wrapper left_edges{"A"};
cudf::test::strings_column_wrapper right_edges{"z"};
cudf::test::strings_column_wrapper input{"Héllo",
"thesé",
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
auto sliced_inputs = cudf::slice(input, {1, 5, 5, 11});
{
auto result = cudf::label_bins(
sliced_inputs[0], left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO);
fwc_wrapper<cudf::size_type> expected{{0, 0, 0, 0}, {1, 1, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
{
auto result = cudf::label_bins(
sliced_inputs[1], left_edges, cudf::inclusive::NO, right_edges, cudf::inclusive::NO);
fwc_wrapper<cudf::size_type> expected{{0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
}
} // anonymous namespace
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/experimental_row_operator_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 "row_operator_tests_utilities.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 <cudf/table/experimental/row_operators.cuh>
#include <rmm/cuda_stream_view.hpp>
template <typename T>
struct TypedTableViewTest : public cudf::test::BaseFixture {};
using NumericTypesNotBool =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(TypedTableViewTest, NumericTypesNotBool);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> self_comparison(cudf::table_view input,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_comparison(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_equality(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> sorted_order(
std::shared_ptr<cudf::experimental::row::lexicographic::preprocessed_table> preprocessed_input,
cudf::size_type num_rows,
bool has_nested,
PhysicalElementComparator comparator,
rmm::cuda_stream_view stream);
TYPED_TEST(TypedTableViewTest, TestLexicographicalComparatorTwoTables)
{
using T = TypeParam;
auto const col1 = cudf::test::fixed_width_column_wrapper<T>{{1, 2, 3, 4}};
auto const col2 = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 4, 3}};
auto const column_order = std::vector{cudf::order::DESCENDING};
auto const lhs = cudf::table_view{{col1}};
auto const rhs = cudf::table_view{{col2}};
auto const expected = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 0, 1}};
auto const got = two_table_comparison(
lhs, rhs, column_order, cudf::experimental::row::lexicographic::physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
auto const sorting_got = two_table_comparison(
lhs,
rhs,
column_order,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, sorting_got->view());
}
TYPED_TEST(TypedTableViewTest, TestLexicographicalComparatorSameTable)
{
using T = TypeParam;
auto const col1 = cudf::test::fixed_width_column_wrapper<T>{{1, 2, 3, 4}};
auto const column_order = std::vector{cudf::order::DESCENDING};
auto const input_table = cudf::table_view{{col1}};
auto const expected = cudf::test::fixed_width_column_wrapper<bool>{{0, 0, 0, 0}};
auto const got =
self_comparison(input_table,
column_order,
cudf::experimental::row::lexicographic::physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
auto const sorting_got =
self_comparison(input_table,
column_order,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, sorting_got->view());
}
TYPED_TEST(TypedTableViewTest, TestSortSameTableFromTwoTables)
{
using data_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>;
auto const col1 = data_col{5, 2, 7, 1, 3};
auto const col2 = data_col{}; // empty
auto const lhs = cudf::table_view{{col1}};
auto const empty_rhs = cudf::table_view{{col2}};
auto const stream = cudf::get_default_stream();
auto const test_sort = [stream](auto const& preprocessed,
auto const& input,
auto const& comparator,
auto const& expected) {
auto const order = sorted_order(
preprocessed, input.num_rows(), cudf::detail::has_nested_columns(input), comparator, stream);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, order->view());
};
auto const test_sort_two_tables = [&](auto const& preprocessed_lhs,
auto const& preprocessed_empty_rhs) {
auto const expected_lhs = int32s_col{3, 1, 4, 0, 2};
test_sort(preprocessed_lhs,
lhs,
cudf::experimental::row::lexicographic::physical_element_comparator{},
expected_lhs);
test_sort(preprocessed_lhs,
lhs,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{},
expected_lhs);
auto const expected_empty_rhs = int32s_col{};
test_sort(preprocessed_empty_rhs,
empty_rhs,
cudf::experimental::row::lexicographic::physical_element_comparator{},
expected_empty_rhs);
test_sort(preprocessed_empty_rhs,
empty_rhs,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{},
expected_empty_rhs);
};
// Generate preprocessed data for both lhs and lhs at the same time.
// Switching order of lhs and rhs tables then sorting them using their preprocessed data should
// produce exactly the same result.
{
auto const [preprocessed_lhs, preprocessed_empty_rhs] =
cudf::experimental::row::lexicographic::preprocessed_table::create(
lhs, empty_rhs, std::vector{cudf::order::ASCENDING}, {}, stream);
test_sort_two_tables(preprocessed_lhs, preprocessed_empty_rhs);
}
{
auto const [preprocessed_empty_rhs, preprocessed_lhs] =
cudf::experimental::row::lexicographic::preprocessed_table::create(
empty_rhs, lhs, std::vector{cudf::order::ASCENDING}, {}, stream);
test_sort_two_tables(preprocessed_lhs, preprocessed_empty_rhs);
}
}
TYPED_TEST(TypedTableViewTest, TestSortSameTableFromTwoTablesWithListsOfStructs)
{
using data_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>;
using strings_col = cudf::test::strings_column_wrapper;
using structs_col = cudf::test::structs_column_wrapper;
auto const col1 = [] {
auto const get_structs = [] {
auto child0 = data_col{0, 3, 0, 2};
auto child1 = strings_col{"a", "c", "a", "b"};
return structs_col{{child0, child1}};
};
return cudf::make_lists_column(
2, int32s_col{0, 2, 4}.release(), get_structs().release(), 0, {});
}();
auto const col2 = [] {
auto const get_structs = [] {
auto child0 = data_col{};
auto child1 = strings_col{};
return structs_col{{child0, child1}};
};
return cudf::make_lists_column(0, int32s_col{}.release(), get_structs().release(), 0, {});
}();
auto const column_order = std::vector{cudf::order::ASCENDING};
auto const lhs = cudf::table_view{{*col1}};
auto const empty_rhs = cudf::table_view{{*col2}};
auto const stream = cudf::get_default_stream();
auto const test_sort = [stream](auto const& preprocessed,
auto const& input,
auto const& comparator,
auto const& expected) {
auto const order = sorted_order(
preprocessed, input.num_rows(), cudf::detail::has_nested_columns(input), comparator, stream);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, order->view());
};
auto const test_sort_two_tables = [&](auto const& preprocessed_lhs,
auto const& preprocessed_empty_rhs) {
auto const expected_lhs = int32s_col{1, 0};
test_sort(preprocessed_lhs,
lhs,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{},
expected_lhs);
auto const expected_empty_rhs = int32s_col{};
test_sort(preprocessed_empty_rhs,
empty_rhs,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{},
expected_empty_rhs);
EXPECT_THROW(test_sort(preprocessed_lhs,
lhs,
cudf::experimental::row::lexicographic::physical_element_comparator{},
expected_lhs),
cudf::logic_error);
EXPECT_THROW(test_sort(preprocessed_empty_rhs,
empty_rhs,
cudf::experimental::row::lexicographic::physical_element_comparator{},
expected_empty_rhs),
cudf::logic_error);
};
// Generate preprocessed data for both lhs and lhs at the same time.
// Switching order of lhs and rhs tables then sorting them using their preprocessed data should
// produce exactly the same result.
{
auto const [preprocessed_lhs, preprocessed_empty_rhs] =
cudf::experimental::row::lexicographic::preprocessed_table::create(
lhs, empty_rhs, std::vector{cudf::order::ASCENDING}, {}, stream);
test_sort_two_tables(preprocessed_lhs, preprocessed_empty_rhs);
}
{
auto const [preprocessed_empty_rhs, preprocessed_lhs] =
cudf::experimental::row::lexicographic::preprocessed_table::create(
empty_rhs, lhs, std::vector{cudf::order::ASCENDING}, {}, stream);
test_sort_two_tables(preprocessed_lhs, preprocessed_empty_rhs);
}
}
template <typename T>
struct NaNTableViewTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(NaNTableViewTest, cudf::test::FloatingPointTypes);
TYPED_TEST(NaNTableViewTest, TestLexicographicalComparatorTwoTableNaNCase)
{
using T = TypeParam;
auto const col1 = cudf::test::fixed_width_column_wrapper<T>{{T(NAN), T(NAN), T(1), T(1)}};
auto const col2 = cudf::test::fixed_width_column_wrapper<T>{{T(NAN), T(1), T(NAN), T(1)}};
auto const column_order = std::vector{cudf::order::DESCENDING};
auto const lhs = cudf::table_view{{col1}};
auto const rhs = cudf::table_view{{col2}};
auto const expected = cudf::test::fixed_width_column_wrapper<bool>{{0, 0, 0, 0}};
auto const got = two_table_comparison(
lhs, rhs, column_order, cudf::experimental::row::lexicographic::physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
auto const sorting_expected = cudf::test::fixed_width_column_wrapper<bool>{{0, 1, 0, 0}};
auto const sorting_got = two_table_comparison(
lhs,
rhs,
column_order,
cudf::experimental::row::lexicographic::sorting_physical_element_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorting_expected, sorting_got->view());
}
TYPED_TEST(NaNTableViewTest, TestEqualityComparatorTwoTableNaNCase)
{
using T = TypeParam;
auto const col1 = cudf::test::fixed_width_column_wrapper<T>{{T(NAN), T(NAN), T(1), T(1)}};
auto const col2 = cudf::test::fixed_width_column_wrapper<T>{{T(NAN), T(1), T(NAN), T(1)}};
auto const column_order = std::vector{cudf::order::DESCENDING};
auto const lhs = cudf::table_view{{col1}};
auto const rhs = cudf::table_view{{col2}};
auto const expected = cudf::test::fixed_width_column_wrapper<bool>{{0, 0, 0, 1}};
auto const got = two_table_equality(
lhs, rhs, column_order, cudf::experimental::row::equality::physical_equality_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
auto const nan_equal_expected = cudf::test::fixed_width_column_wrapper<bool>{{1, 0, 0, 1}};
auto const nan_equal_got =
two_table_equality(lhs,
rhs,
column_order,
cudf::experimental::row::equality::nan_equal_physical_equality_comparator{});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(nan_equal_expected, nan_equal_got->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/row_operators_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_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/sorting.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/type_lists.hpp>
#include <vector>
struct RowOperatorTestForNAN : public cudf::test::BaseFixture {};
TEST_F(RowOperatorTestForNAN, NANEquality)
{
cudf::test::fixed_width_column_wrapper<double> col1{{1., double(NAN), 3., 4.}, {1, 1, 0, 1}};
cudf::test::fixed_width_column_wrapper<double> col2{{1., double(NAN), 3., 4.}, {1, 1, 0, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(col1, col2);
}
TEST_F(RowOperatorTestForNAN, NANSorting)
{
// NULL Before
cudf::test::fixed_width_column_wrapper<double> input{
{0.,
double(NAN),
-1.,
7.,
std::numeric_limits<double>::infinity(),
1.,
-1 * std::numeric_limits<double>::infinity()},
{1, 1, 1, 0, 1, 1, 1, 1}};
cudf::test::fixed_width_column_wrapper<int32_t> expected1{{3, 6, 2, 0, 5, 4, 1}};
std::vector<cudf::order> column_order{cudf::order::ASCENDING};
std::vector<cudf::null_order> null_precedence_1{cudf::null_order::BEFORE};
cudf::table_view input_table{{input}};
auto got1 = cudf::sorted_order(input_table, column_order, null_precedence_1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, got1->view());
// NULL After
std::vector<cudf::null_order> null_precedence_2{cudf::null_order::AFTER};
cudf::test::fixed_width_column_wrapper<int32_t> expected2{{6, 2, 0, 5, 4, 1, 3}};
auto got2 = cudf::sorted_order(input_table, column_order, null_precedence_2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, got2->view());
}
TEST_F(RowOperatorTestForNAN, NANSortingNonNull)
{
cudf::test::fixed_width_column_wrapper<double> input{
{0.,
double(NAN),
-1.,
7.,
std::numeric_limits<double>::infinity(),
1.,
-1 * std::numeric_limits<double>::infinity()}};
cudf::table_view input_table{{input}};
auto result = cudf::sorted_order(input_table, {cudf::order::ASCENDING});
cudf::test::fixed_width_column_wrapper<int32_t> expected_asc{{6, 2, 0, 5, 3, 4, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_asc, result->view());
auto sorted_result = cudf::sort(input_table, {cudf::order::ASCENDING});
auto gather_result = cudf::gather(input_table, result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(sorted_result->view().column(0),
gather_result->view().column(0));
result = cudf::sorted_order(input_table, {cudf::order::DESCENDING});
cudf::test::fixed_width_column_wrapper<int32_t> expected_desc{{1, 4, 3, 5, 0, 2, 6}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_desc, result->view());
sorted_result = cudf::sort(input_table, {cudf::order::DESCENDING});
gather_result = cudf::gather(input_table, result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(sorted_result->view().column(0),
gather_result->view().column(0));
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/table_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.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.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/table_utilities.hpp>
#include <memory>
#include <random>
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;
struct TableTest : public cudf::test::BaseFixture {};
TEST_F(TableTest, EmptyColumnedTable)
{
std::vector<column_view> cols{};
TView input(cols);
cudf::size_type expected = 0;
EXPECT_EQ(input.num_columns(), expected);
}
TEST_F(TableTest, ValidateConstructorTableViewToTable)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int8_t> col2{{1, 2, 3, 4}};
CVector cols;
cols.push_back(col1.release());
cols.push_back(col2.release());
Table input_table(std::move(cols));
Table out_table(input_table.view());
EXPECT_EQ(input_table.num_columns(), out_table.num_columns());
EXPECT_EQ(input_table.num_rows(), out_table.num_rows());
}
TEST_F(TableTest, GetTableWithSelectedColumns)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int16_t> col2{{1, 2, 3, 4}};
column_wrapper<int32_t> col3{{4, 5, 6, 7}};
column_wrapper<int64_t> col4{{4, 5, 6, 7}};
CVector cols;
cols.push_back(col1.release());
cols.push_back(col2.release());
cols.push_back(col3.release());
cols.push_back(col4.release());
Table t(std::move(cols));
cudf::table_view selected_tview = t.select(std::vector<cudf::size_type>{2, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(t.view().column(2), selected_tview.column(0));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(t.view().column(3), selected_tview.column(1));
}
TEST_F(TableTest, SelectingOutOfBounds)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int16_t> col2{{1, 2, 3, 4}};
CVector cols;
cols.push_back(col1.release());
cols.push_back(col2.release());
Table t(std::move(cols));
EXPECT_THROW(cudf::table_view selected_tview = t.select(std::vector<cudf::size_type>{0, 1, 2}),
std::out_of_range);
}
TEST_F(TableTest, SelectingNoColumns)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int16_t> col2{{1, 2, 3, 4}};
CVector cols;
cols.push_back(col1.release());
cols.push_back(col2.release());
Table t(std::move(cols));
TView selected_table = t.select(std::vector<cudf::size_type>{});
EXPECT_EQ(selected_table.num_columns(), 0);
}
TEST_F(TableTest, CreateFromViewVector)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int16_t> col2{{1, 2, 3, 4}};
std::vector<TView> views;
views.emplace_back(std::vector<column_view>{col1});
views.emplace_back(std::vector<column_view>{col2});
TView final_view{views};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(final_view.column(0), views[0].column(0));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(final_view.column(1), views[1].column(0));
}
TEST_F(TableTest, CreateFromViewVectorRowsMismatch)
{
column_wrapper<int8_t> col1{{1, 2, 3, 4}};
column_wrapper<int16_t> col2{{1, 2, 3}};
std::vector<TView> views;
views.emplace_back(std::vector<column_view>{col1});
views.emplace_back(std::vector<column_view>{col2});
EXPECT_THROW(TView{views}, cudf::logic_error);
}
TEST_F(TableTest, CreateFromViewVectorEmptyTables)
{
std::vector<TView> views;
views.emplace_back(std::vector<column_view>{});
views.emplace_back(std::vector<column_view>{});
TView final_view{views};
EXPECT_EQ(final_view.num_columns(), 0);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/row_operator_tests_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 "row_operator_tests_utilities.hpp"
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/sequence.h>
#include <thrust/sort.h>
#include <thrust/transform.h>
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> self_comparison(cudf::table_view input,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator)
{
rmm::cuda_stream_view stream{cudf::get_default_stream()};
auto const table_comparator =
cudf::experimental::row::lexicographic::self_comparator{input, column_order, {}, stream};
auto output = cudf::make_numeric_column(
cudf::data_type(cudf::type_id::BOOL8), input.num_rows(), cudf::mask_state::UNALLOCATED);
if (cudf::detail::has_nested_columns(input)) {
thrust::transform(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(input.num_rows()),
thrust::make_counting_iterator(0),
output->mutable_view().data<bool>(),
table_comparator.less<true>(cudf::nullate::NO{}, comparator));
} else {
thrust::transform(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(input.num_rows()),
thrust::make_counting_iterator(0),
output->mutable_view().data<bool>(),
table_comparator.less<false>(cudf::nullate::NO{}, comparator));
}
return output;
}
using physical_comparator_t = cudf::experimental::row::lexicographic::physical_element_comparator;
using sorting_comparator_t =
cudf::experimental::row::lexicographic::sorting_physical_element_comparator;
template std::unique_ptr<cudf::column> self_comparison<physical_comparator_t>(
cudf::table_view input,
std::vector<cudf::order> const& column_order,
physical_comparator_t comparator);
template std::unique_ptr<cudf::column> self_comparison<sorting_comparator_t>(
cudf::table_view input,
std::vector<cudf::order> const& column_order,
sorting_comparator_t comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_comparison(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator)
{
rmm::cuda_stream_view stream{cudf::get_default_stream()};
auto const table_comparator = cudf::experimental::row::lexicographic::two_table_comparator{
lhs, rhs, column_order, {}, stream};
auto const lhs_it = cudf::experimental::row::lhs_iterator(0);
auto const rhs_it = cudf::experimental::row::rhs_iterator(0);
auto output = cudf::make_numeric_column(
cudf::data_type(cudf::type_id::BOOL8), lhs.num_rows(), cudf::mask_state::UNALLOCATED);
if (cudf::detail::has_nested_columns(lhs) || cudf::detail::has_nested_columns(rhs)) {
thrust::transform(rmm::exec_policy(stream),
lhs_it,
lhs_it + lhs.num_rows(),
rhs_it,
output->mutable_view().data<bool>(),
table_comparator.less<true>(cudf::nullate::NO{}, comparator));
} else {
thrust::transform(rmm::exec_policy(stream),
lhs_it,
lhs_it + lhs.num_rows(),
rhs_it,
output->mutable_view().data<bool>(),
table_comparator.less<false>(cudf::nullate::NO{}, comparator));
}
return output;
}
template std::unique_ptr<cudf::column> two_table_comparison<physical_comparator_t>(
cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
physical_comparator_t comparator);
template std::unique_ptr<cudf::column> two_table_comparison<sorting_comparator_t>(
cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
sorting_comparator_t comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> sorted_order(
std::shared_ptr<cudf::experimental::row::lexicographic::preprocessed_table> preprocessed_input,
cudf::size_type num_rows,
bool has_nested,
PhysicalElementComparator comparator,
rmm::cuda_stream_view stream)
{
auto output = cudf::make_numeric_column(cudf::data_type(cudf::type_to_id<cudf::size_type>()),
num_rows,
cudf::mask_state::UNALLOCATED,
stream);
auto const out_begin = output->mutable_view().begin<cudf::size_type>();
thrust::sequence(rmm::exec_policy(stream), out_begin, out_begin + num_rows, 0);
auto const table_comparator =
cudf::experimental::row::lexicographic::self_comparator{preprocessed_input};
if (has_nested) {
auto const comp = table_comparator.less<true>(cudf::nullate::NO{}, comparator);
thrust::stable_sort(rmm::exec_policy(stream), out_begin, out_begin + num_rows, comp);
} else {
auto const comp = table_comparator.less<false>(cudf::nullate::NO{}, comparator);
thrust::stable_sort(rmm::exec_policy(stream), out_begin, out_begin + num_rows, comp);
}
return output;
}
template std::unique_ptr<cudf::column> sorted_order<physical_comparator_t>(
std::shared_ptr<cudf::experimental::row::lexicographic::preprocessed_table> preprocessed_input,
cudf::size_type num_rows,
bool has_nested,
physical_comparator_t comparator,
rmm::cuda_stream_view stream);
template std::unique_ptr<cudf::column> sorted_order<sorting_comparator_t>(
std::shared_ptr<cudf::experimental::row::lexicographic::preprocessed_table> preprocessed_input,
cudf::size_type num_rows,
bool has_nested,
sorting_comparator_t comparator,
rmm::cuda_stream_view stream);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_equality(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator)
{
rmm::cuda_stream_view stream{cudf::get_default_stream()};
auto const table_comparator =
cudf::experimental::row::equality::two_table_comparator{lhs, rhs, stream};
auto const lhs_it = cudf::experimental::row::lhs_iterator(0);
auto const rhs_it = cudf::experimental::row::rhs_iterator(0);
auto output = cudf::make_numeric_column(
cudf::data_type(cudf::type_id::BOOL8), lhs.num_rows(), cudf::mask_state::UNALLOCATED);
if (cudf::detail::has_nested_columns(lhs) or cudf::detail::has_nested_columns(rhs)) {
auto const equal_comparator =
table_comparator.equal_to<true>(cudf::nullate::NO{}, cudf::null_equality::EQUAL, comparator);
thrust::transform(rmm::exec_policy(stream),
lhs_it,
lhs_it + lhs.num_rows(),
rhs_it,
output->mutable_view().data<bool>(),
equal_comparator);
} else {
auto const equal_comparator =
table_comparator.equal_to<false>(cudf::nullate::NO{}, cudf::null_equality::EQUAL, comparator);
thrust::transform(rmm::exec_policy(stream),
lhs_it,
lhs_it + lhs.num_rows(),
rhs_it,
output->mutable_view().data<bool>(),
equal_comparator);
}
return output;
}
using physical_equality_t = cudf::experimental::row::equality::physical_equality_comparator;
using nan_equality_t = cudf::experimental::row::equality::nan_equal_physical_equality_comparator;
template std::unique_ptr<cudf::column> two_table_equality<physical_equality_t>(
cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
physical_equality_t comparator);
template std::unique_ptr<cudf::column> two_table_equality<nan_equality_t>(
cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
nan_equality_t comparator);
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/table_view_tests.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/type_lists.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/table/row_operators.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform.h>
#include <vector>
// Compares two tables row by row, if table1 row is less than table2, then corresponding row value
// in `output` would be `true`/1 else `false`/0.
struct TableViewTest : public cudf::test::BaseFixture {};
void row_comparison(cudf::table_view input1,
cudf::table_view input2,
cudf::mutable_column_view output,
std::vector<cudf::order> const& column_order)
{
rmm::cuda_stream_view stream{cudf::get_default_stream()};
auto device_table_1 = cudf::table_device_view::create(input1, stream);
auto device_table_2 = cudf::table_device_view::create(input2, stream);
auto d_column_order = cudf::detail::make_device_uvector_sync(
column_order, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto comparator = cudf::row_lexicographic_comparator(
cudf::nullate::NO{}, *device_table_1, *device_table_2, d_column_order.data());
thrust::transform(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(input1.num_rows()),
thrust::make_counting_iterator(0),
output.data<int8_t>(),
comparator);
}
TEST_F(TableViewTest, EmptyColumnedTable)
{
std::vector<cudf::column_view> cols{};
cudf::table_view input(cols);
cudf::size_type expected = 0;
EXPECT_EQ(input.num_columns(), expected);
}
TEST_F(TableViewTest, TestLexicographicalComparatorTwoTableCase)
{
cudf::test::fixed_width_column_wrapper<int16_t> col1{{1, 2, 3, 4}};
cudf::test::fixed_width_column_wrapper<int16_t> col2{{0, 1, 4, 3}};
std::vector<cudf::order> column_order{cudf::order::DESCENDING};
cudf::table_view input_table_1{{col1}};
cudf::table_view input_table_2{{col2}};
auto got = cudf::make_numeric_column(
cudf::data_type(cudf::type_id::INT8), input_table_1.num_rows(), cudf::mask_state::UNALLOCATED);
cudf::test::fixed_width_column_wrapper<int8_t> expected{{1, 1, 0, 1}};
row_comparison(input_table_1, input_table_2, got->mutable_view(), column_order);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(TableViewTest, TestLexicographicalComparatorSameTable)
{
cudf::test::fixed_width_column_wrapper<int16_t> col1{{1, 2, 3, 4}};
std::vector<cudf::order> column_order{cudf::order::DESCENDING};
cudf::table_view input_table_1{{col1}};
auto got = cudf::make_numeric_column(
cudf::data_type(cudf::type_id::INT8), input_table_1.num_rows(), cudf::mask_state::UNALLOCATED);
cudf::test::fixed_width_column_wrapper<int8_t> expected{{0, 0, 0, 0}};
row_comparison(input_table_1, input_table_1, got->mutable_view(), column_order);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(TableViewTest, Select)
{
using cudf::test::fixed_width_column_wrapper;
fixed_width_column_wrapper<int8_t> col1{{1, 2, 3, 4}};
fixed_width_column_wrapper<int16_t> col2{{1, 2, 3, 4}};
fixed_width_column_wrapper<int32_t> col3{{4, 5, 6, 7}};
fixed_width_column_wrapper<int64_t> col4{{4, 5, 6, 7}};
cudf::table_view t{{col1, col2, col3, col4}};
cudf::table_view selected = t.select({2, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(t.column(2), selected.column(0));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(t.column(3), selected.column(1));
}
TEST_F(TableViewTest, SelectOutOfBounds)
{
using cudf::test::fixed_width_column_wrapper;
fixed_width_column_wrapper<int8_t> col1{{1, 2, 3, 4}};
fixed_width_column_wrapper<int16_t> col2{{1, 2, 3, 4}};
fixed_width_column_wrapper<int32_t> col3{{4, 5, 6, 7}};
fixed_width_column_wrapper<int64_t> col4{{4, 5, 6, 7}};
cudf::table_view t{{col1, col2}};
EXPECT_THROW((void)t.select({2, 3, 4}), std::out_of_range);
}
TEST_F(TableViewTest, SelectNoColumns)
{
using cudf::test::fixed_width_column_wrapper;
fixed_width_column_wrapper<int8_t> col1{{1, 2, 3, 4}};
fixed_width_column_wrapper<int16_t> col2{{1, 2, 3, 4}};
fixed_width_column_wrapper<int32_t> col3{{4, 5, 6, 7}};
fixed_width_column_wrapper<int64_t> col4{{4, 5, 6, 7}};
cudf::table_view t{{col1, col2, col3, col4}};
cudf::table_view selected = t.select({});
EXPECT_EQ(selected.num_columns(), 0);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/table/row_operator_tests_utilities.hpp
|
/*
* 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.
*/
#pragma once
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_view.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <vector>
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> self_comparison(cudf::table_view input,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_comparison(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> two_table_equality(cudf::table_view lhs,
cudf::table_view rhs,
std::vector<cudf::order> const& column_order,
PhysicalElementComparator comparator);
template <typename PhysicalElementComparator>
std::unique_ptr<cudf::column> sorted_order(
std::shared_ptr<cudf::experimental::row::lexicographic::preprocessed_table> preprocessed_input,
cudf::size_type num_rows,
bool has_nested,
PhysicalElementComparator comparator,
rmm::cuda_stream_view stream);
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/replace/replace_nulls_tests.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018 BlazingDB, Inc.
* Copyright 2018 Alexander Ocsa <[email protected]>
*
* 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/dictionary/encode.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/replace.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
using namespace cudf::test::iterators;
struct ReplaceErrorTest : public cudf::test::BaseFixture {};
// Error: old-values and new-values size mismatch
TEST_F(ReplaceErrorTest, SizeMismatch)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4},
{0, 0, 1, 1, 1, 1, 1, 1}};
cudf::test::fixed_width_column_wrapper<int32_t> values_to_replace_column{{10, 11, 12, 13}};
ASSERT_THROW(cudf::replace_nulls(input_column, values_to_replace_column), cudf::logic_error);
}
// Error: column type mismatch
TEST_F(ReplaceErrorTest, TypeMismatch)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4},
{0, 0, 1, 1, 1, 1, 1, 1}};
cudf::test::fixed_width_column_wrapper<float> values_to_replace_column{
{10, 11, 12, 13, 14, 15, 16, 17}};
EXPECT_THROW(cudf::replace_nulls(input_column, values_to_replace_column), cudf::logic_error);
}
// Error: column type mismatch
TEST_F(ReplaceErrorTest, TypeMismatchScalar)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4},
{0, 0, 1, 1, 1, 1, 1, 1}};
cudf::numeric_scalar<float> replacement(1);
EXPECT_THROW(cudf::replace_nulls(input_column, replacement), cudf::logic_error);
}
struct ReplaceNullsStringsTest : public cudf::test::BaseFixture {};
TEST_F(ReplaceNullsStringsTest, SimpleReplace)
{
std::vector<std::string> input{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> input_v{0, 0, 0, 0, 0, 0, 0, 0};
std::vector<std::string> replacement{"a", "b", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> replacement_v{1, 1, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper replacement_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
cudf::test::strings_column_wrapper expected_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, replacement_w));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
TEST_F(ReplaceNullsStringsTest, ReplaceWithNulls)
{
std::vector<std::string> input{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> input_v{0, 0, 0, 0, 0, 0, 0, 0};
std::vector<std::string> replacement{"", "", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> replacement_v{0, 0, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper replacement_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
cudf::test::strings_column_wrapper expected_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, replacement_w));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
TEST_F(ReplaceNullsStringsTest, ReplaceWithAllNulls)
{
std::vector<std::string> input{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> input_v{0, 0, 0, 0, 0, 0, 0, 0};
std::vector<std::string> replacement{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> replacement_v{0, 0, 0, 0, 0, 0, 0, 0};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper replacement_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
cudf::test::strings_column_wrapper expected_w{input.begin(), input.end(), input_v.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, replacement_w));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
TEST_F(ReplaceNullsStringsTest, ReplaceWithAllEmpty)
{
std::vector<std::string> input{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> input_v{0, 0, 0, 0, 0, 0, 0, 0};
std::vector<std::string> replacement{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> replacement_v{1, 1, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper replacement_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
cudf::test::strings_column_wrapper expected_w{input.begin(), input.end(), replacement_v.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, replacement_w));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
TEST_F(ReplaceNullsStringsTest, ReplaceNone)
{
std::vector<std::string> input{"a", "b", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> input_v{1, 1, 1, 1, 1, 1, 1, 1};
std::vector<std::string> replacement{"z", "a", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> replacement_v{0, 0, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper replacement_w{
replacement.begin(), replacement.end(), replacement_v.begin()};
cudf::test::strings_column_wrapper expected_w{input.begin(), input.end()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, replacement_w));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected_w);
}
TEST_F(ReplaceNullsStringsTest, SimpleReplaceScalar)
{
std::vector<std::string> input{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> input_v{0, 0, 0, 0, 0, 0, 0, 0};
std::unique_ptr<cudf::scalar> repl = cudf::make_string_scalar("rep");
repl->set_valid_async(true, cudf::get_default_stream());
std::vector<std::string> expected{"rep", "rep", "rep", "rep", "rep", "rep", "rep", "rep"};
cudf::test::strings_column_wrapper input_w{input.begin(), input.end(), input_v.begin()};
cudf::test::strings_column_wrapper expected_w{expected.begin(), expected.end()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input_w, *repl));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
struct ReplaceNullsPolicyStringTest : public cudf::test::BaseFixture {};
TEST_F(ReplaceNullsPolicyStringTest, PrecedingFill)
{
cudf::test::strings_column_wrapper input({"head", "", "", "mid", "mid", "", "tail"},
{1, 0, 0, 1, 1, 0, 1});
cudf::test::strings_column_wrapper expected({"head", "head", "head", "mid", "mid", "mid", "tail"},
no_nulls());
auto result = cudf::replace_nulls(input, cudf::replace_policy::PRECEDING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(ReplaceNullsPolicyStringTest, FollowingFill)
{
cudf::test::strings_column_wrapper input({"head", "", "", "mid", "mid", "", "tail"},
{1, 0, 0, 1, 1, 0, 1});
cudf::test::strings_column_wrapper expected({"head", "mid", "mid", "mid", "mid", "tail", "tail"},
no_nulls());
auto result = cudf::replace_nulls(input, cudf::replace_policy::FOLLOWING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(ReplaceNullsPolicyStringTest, PrecedingFillLeadingNulls)
{
cudf::test::strings_column_wrapper input({"", "", "", "mid", "mid", "", "tail"},
{0, 0, 0, 1, 1, 0, 1});
cudf::test::strings_column_wrapper expected({"", "", "", "mid", "mid", "mid", "tail"},
{0, 0, 0, 1, 1, 1, 1});
auto result = cudf::replace_nulls(input, cudf::replace_policy::PRECEDING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(ReplaceNullsPolicyStringTest, FollowingFillTrailingNulls)
{
cudf::test::strings_column_wrapper input({"head", "", "", "mid", "mid", "", ""},
{1, 0, 0, 1, 1, 0, 0});
cudf::test::strings_column_wrapper expected({"head", "mid", "mid", "mid", "mid", "", ""},
{1, 1, 1, 1, 1, 0, 0});
auto result = cudf::replace_nulls(input, cudf::replace_policy::FOLLOWING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
template <typename T>
struct ReplaceNullsTest : public cudf::test::BaseFixture {};
using test_types = cudf::test::NumericTypes;
TYPED_TEST_SUITE(ReplaceNullsTest, test_types);
template <typename T>
void ReplaceNullsColumn(cudf::test::fixed_width_column_wrapper<T> input,
cudf::test::fixed_width_column_wrapper<T> replacement_values,
cudf::test::fixed_width_column_wrapper<T> expected)
{
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input, replacement_values));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result);
}
template <typename T>
void ReplaceNullsScalar(cudf::test::fixed_width_column_wrapper<T> input,
cudf::scalar const& replacement_value,
cudf::test::fixed_width_column_wrapper<T> expected)
{
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nulls(input, replacement_value));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result);
}
TYPED_TEST(ReplaceNullsTest, ReplaceColumn)
{
auto const inputColumn =
cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto const inputValid =
cudf::test::make_type_param_vector<cudf::valid_type>({0, 0, 0, 0, 0, 1, 1, 1, 1, 1});
auto const replacementColumn =
cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
ReplaceNullsColumn<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>(
inputColumn.begin(), inputColumn.end(), inputValid.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
replacementColumn.begin(), replacementColumn.end()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
replacementColumn.begin(), replacementColumn.end()));
}
TYPED_TEST(ReplaceNullsTest, ReplaceColumn_Empty)
{
ReplaceNullsColumn<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{});
}
TYPED_TEST(ReplaceNullsTest, ReplaceScalar)
{
auto const inputColumn =
cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto const inputValid =
cudf::test::make_type_param_vector<cudf::valid_type>({0, 0, 0, 0, 0, 1, 1, 1, 1, 1});
auto const expectedColumn =
cudf::test::make_type_param_vector<TypeParam>({1, 1, 1, 1, 1, 5, 6, 7, 8, 9});
cudf::numeric_scalar<TypeParam> replacement(1);
ReplaceNullsScalar<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>(
inputColumn.begin(), inputColumn.end(), inputValid.begin()),
replacement,
cudf::test::fixed_width_column_wrapper<TypeParam>(
expectedColumn.begin(), expectedColumn.end()));
}
TYPED_TEST(ReplaceNullsTest, ReplacementHasNulls)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const replace_column = cudf::test::make_type_param_vector<T>({4, 5, 6, 7, 8, 9, 0, 1});
auto const result_column = cudf::test::make_type_param_vector<T>({4, 5, 6, 3, 1, 2, 8, 4});
auto const input_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({0, 0, 1, 1, 1, 1, 1, 1});
auto const replace_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({1, 0, 1, 1, 1, 1, 1, 1});
auto const result_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({1, 0, 1, 1, 1, 1, 1, 1});
ReplaceNullsColumn<T>(cudf::test::fixed_width_column_wrapper<T>(
input_column.begin(), input_column.end(), input_valid.begin()),
cudf::test::fixed_width_column_wrapper<T>(
replace_column.begin(), replace_column.end(), replace_valid.begin()),
cudf::test::fixed_width_column_wrapper<T>(
result_column.begin(), result_column.end(), result_valid.begin()));
}
TYPED_TEST(ReplaceNullsTest, LargeScale)
{
std::vector<TypeParam> inputColumn(10000);
for (size_t i = 0; i < inputColumn.size(); i++)
inputColumn[i] = i % 2;
std::vector<cudf::valid_type> inputValid(10000);
for (size_t i = 0; i < inputValid.size(); i++)
inputValid[i] = i % 2;
std::vector<TypeParam> expectedColumn(10000);
for (size_t i = 0; i < expectedColumn.size(); i++)
expectedColumn[i] = 1;
ReplaceNullsColumn<TypeParam>(
cudf::test::fixed_width_column_wrapper<TypeParam>(
inputColumn.begin(), inputColumn.end(), inputValid.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(expectedColumn.begin(), expectedColumn.end()),
cudf::test::fixed_width_column_wrapper<TypeParam>(expectedColumn.begin(),
expectedColumn.end()));
}
TYPED_TEST(ReplaceNullsTest, LargeScaleScalar)
{
std::vector<TypeParam> inputColumn(10000);
for (size_t i = 0; i < inputColumn.size(); i++)
inputColumn[i] = i % 2;
std::vector<cudf::valid_type> inputValid(10000);
for (size_t i = 0; i < inputValid.size(); i++)
inputValid[i] = i % 2;
std::vector<TypeParam> expectedColumn(10000);
for (size_t i = 0; i < expectedColumn.size(); i++)
expectedColumn[i] = 1;
cudf::numeric_scalar<TypeParam> replacement(1);
ReplaceNullsScalar<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>(
inputColumn.begin(), inputColumn.end(), inputValid.begin()),
replacement,
cudf::test::fixed_width_column_wrapper<TypeParam>(
expectedColumn.begin(), expectedColumn.end()));
}
template <typename T>
struct ReplaceNullsPolicyTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ReplaceNullsPolicyTest, test_types);
template <typename T>
void TestReplaceNullsWithPolicy(cudf::test::fixed_width_column_wrapper<T> input,
cudf::test::fixed_width_column_wrapper<T> expected,
cudf::replace_policy policy)
{
auto result = cudf::replace_nulls(input, policy);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected);
}
TYPED_TEST(ReplaceNullsPolicyTest, PrecedingFill)
{
auto const col = cudf::test::make_type_param_vector<TypeParam>({42, 2, 1, -10, 20, -30});
auto const mask = cudf::test::make_type_param_vector<cudf::valid_type>({1, 0, 0, 1, 0, 1});
auto const expect_col =
cudf::test::make_type_param_vector<TypeParam>({42, 42, 42, -10, -10, -30});
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(col.begin(), col.end(), mask.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
expect_col.begin(), expect_col.end(), no_nulls()),
cudf::replace_policy::PRECEDING);
}
TYPED_TEST(ReplaceNullsPolicyTest, FollowingFill)
{
auto const col = cudf::test::make_type_param_vector<TypeParam>({42, 2, 1, -10, 20, -30});
auto const mask = cudf::test::make_type_param_vector<cudf::valid_type>({1, 0, 0, 1, 0, 1});
auto const expect_col =
cudf::test::make_type_param_vector<TypeParam>({42, -10, -10, -10, -30, -30});
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(col.begin(), col.end(), mask.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
expect_col.begin(), expect_col.end(), no_nulls()),
cudf::replace_policy::FOLLOWING);
}
TYPED_TEST(ReplaceNullsPolicyTest, PrecedingFillLeadingNulls)
{
auto const col = cudf::test::make_type_param_vector<TypeParam>({1, 2, 3, 4, 5});
auto const mask = cudf::test::make_type_param_vector<cudf::valid_type>({0, 0, 1, 0, 1});
auto const expect_col = cudf::test::make_type_param_vector<TypeParam>({1, 2, 3, 3, 5});
auto const expect_mask = cudf::test::make_type_param_vector<cudf::valid_type>({0, 0, 1, 1, 1});
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(col.begin(), col.end(), mask.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
expect_col.begin(), expect_col.end(), expect_mask.begin()),
cudf::replace_policy::PRECEDING);
}
TYPED_TEST(ReplaceNullsPolicyTest, FollowingFillTrailingNulls)
{
auto const col = cudf::test::make_type_param_vector<TypeParam>({1, 2, 3, 4, 5});
auto const mask = cudf::test::make_type_param_vector<cudf::valid_type>({1, 0, 1, 0, 0});
auto const expect_col = cudf::test::make_type_param_vector<TypeParam>({1, 3, 3, 4, 5});
auto const expect_mask = cudf::test::make_type_param_vector<cudf::valid_type>({1, 1, 1, 0, 0});
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(col.begin(), col.end(), mask.begin()),
cudf::test::fixed_width_column_wrapper<TypeParam>(
expect_col.begin(), expect_col.end(), expect_mask.begin()),
cudf::replace_policy::FOLLOWING);
}
TYPED_TEST(ReplaceNullsPolicyTest, PrecedingFillLargeArray)
{
cudf::size_type const sz = 1000;
// Source: 0, null, null...
auto src_begin = thrust::make_counting_iterator(0);
auto src_end = src_begin + sz;
auto nulls_idx_begin = thrust::make_counting_iterator(1);
auto nulls_idx_end = nulls_idx_begin + sz - 1;
// Expected: 0, 0, 0, ...
auto expected_begin = thrust::make_constant_iterator(0);
auto expected_end = expected_begin + sz;
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(
src_begin, src_end, nulls_at(nulls_idx_begin, nulls_idx_end)),
cudf::test::fixed_width_column_wrapper<TypeParam>(expected_begin, expected_end, no_nulls()),
cudf::replace_policy::PRECEDING);
}
TYPED_TEST(ReplaceNullsPolicyTest, FollowingFillLargeArray)
{
cudf::size_type const sz = 1000;
// Source: null, ... null, 999
auto src_begin = thrust::make_counting_iterator(0);
auto src_end = src_begin + sz;
auto nulls_idx_begin = thrust::make_counting_iterator(0);
auto nulls_idx_end = nulls_idx_begin + sz - 1;
// Expected: 999, 999, 999, ...
auto expected_begin = thrust::make_constant_iterator(sz - 1);
auto expected_end = expected_begin + sz;
TestReplaceNullsWithPolicy(
cudf::test::fixed_width_column_wrapper<TypeParam>(
src_begin, src_end, nulls_at(nulls_idx_begin, nulls_idx_end)),
cudf::test::fixed_width_column_wrapper<TypeParam>(expected_begin, expected_end, no_nulls()),
cudf::replace_policy::FOLLOWING);
}
template <typename T>
struct ReplaceNullsFixedPointTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ReplaceNullsFixedPointTest, cudf::test::FixedPointTypes);
TYPED_TEST(ReplaceNullsFixedPointTest, ReplaceColumn)
{
auto const scale = numeric::scale_type{0};
auto const sz = std::size_t{1000};
auto data_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return TypeParam{i, scale};
});
auto valid_begin =
cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return i % 3 ? 1 : 0; });
auto replace_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return TypeParam{-2, scale};
});
auto expected_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
int val = i % 3 ? static_cast<int>(i) : -2;
return TypeParam{val, scale};
});
ReplaceNullsColumn<TypeParam>(
cudf::test::fixed_width_column_wrapper<TypeParam>(data_begin, data_begin + sz, valid_begin),
cudf::test::fixed_width_column_wrapper<TypeParam>(replace_begin, replace_begin + sz),
cudf::test::fixed_width_column_wrapper<TypeParam>(expected_begin, expected_begin + sz));
}
TYPED_TEST(ReplaceNullsFixedPointTest, ReplaceColumn_Empty)
{
ReplaceNullsColumn<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{});
}
TYPED_TEST(ReplaceNullsFixedPointTest, ReplaceScalar)
{
auto const scale = numeric::scale_type{0};
auto const sz = std::size_t{1000};
auto data_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return TypeParam{i, scale};
});
auto valid_begin =
cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return i % 3 ? 1 : 0; });
auto expected_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
int val = i % 3 ? static_cast<int>(i) : -2;
return TypeParam{val, scale};
});
cudf::fixed_point_scalar<TypeParam> replacement{-2, scale};
ReplaceNullsScalar<TypeParam>(
cudf::test::fixed_width_column_wrapper<TypeParam>(data_begin, data_begin + sz, valid_begin),
replacement,
cudf::test::fixed_width_column_wrapper<TypeParam>(expected_begin, expected_begin + sz));
}
TYPED_TEST(ReplaceNullsFixedPointTest, ReplacementHasNulls)
{
auto const scale = numeric::scale_type{0};
auto const sz = std::size_t{1000};
auto data_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return TypeParam{i, scale};
});
auto data_valid_begin =
cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return i % 3 ? 1 : 0; });
auto replace_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
return TypeParam{-2, scale};
});
auto replace_valid_begin =
cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return i % 2 ? 1 : 0; });
auto expected_begin = cudf::detail::make_counting_transform_iterator(0, [&](auto i) {
int val = i % 3 ? static_cast<int>(i) : -2;
return TypeParam{val, scale};
});
auto expected_valid_begin =
cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return i % 6 ? 1 : 0; });
ReplaceNullsColumn<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>(
data_begin, data_begin + sz, data_valid_begin),
cudf::test::fixed_width_column_wrapper<TypeParam>(
replace_begin, replace_begin + sz, replace_valid_begin),
cudf::test::fixed_width_column_wrapper<TypeParam>(
expected_begin, expected_begin + sz, expected_valid_begin));
}
template <typename T>
struct ReplaceNullsPolicyFixedPointTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ReplaceNullsPolicyFixedPointTest, cudf::test::FixedPointTypes);
TYPED_TEST(ReplaceNullsPolicyFixedPointTest, PrecedingFill)
{
using fp = TypeParam;
auto const s = numeric::scale_type{0};
auto col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{42, s}, fp{2, s}, fp{1, s}, fp{-10, s}, fp{20, s}, fp{-30, s}}, {1, 0, 0, 1, 0, 1});
auto expect_col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{42, s}, fp{42, s}, fp{42, s}, fp{-10, s}, fp{-10, s}, fp{-30, s}}, {1, 1, 1, 1, 1, 1});
TestReplaceNullsWithPolicy(
std::move(col), std::move(expect_col), cudf::replace_policy::PRECEDING);
}
TYPED_TEST(ReplaceNullsPolicyFixedPointTest, FollowingFill)
{
using fp = TypeParam;
auto const s = numeric::scale_type{0};
auto col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{42, s}, fp{2, s}, fp{1, s}, fp{-10, s}, fp{20, s}, fp{-30, s}}, {1, 0, 0, 1, 0, 1});
auto expect_col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{42, s}, fp{-10, s}, fp{-10, s}, fp{-10, s}, fp{-30, s}, fp{-30, s}}, {1, 1, 1, 1, 1, 1});
TestReplaceNullsWithPolicy(
std::move(col), std::move(expect_col), cudf::replace_policy::FOLLOWING);
}
TYPED_TEST(ReplaceNullsPolicyFixedPointTest, PrecedingFillLeadingNulls)
{
using fp = TypeParam;
auto const s = numeric::scale_type{0};
auto col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{1, s}, fp{2, s}, fp{3, s}, fp{4, s}, fp{5, s}}, {0, 0, 1, 0, 1});
auto expect_col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{1, s}, fp{2, s}, fp{3, s}, fp{3, s}, fp{5, s}}, {0, 0, 1, 1, 1});
TestReplaceNullsWithPolicy(
std::move(col), std::move(expect_col), cudf::replace_policy::PRECEDING);
}
TYPED_TEST(ReplaceNullsPolicyFixedPointTest, FollowingFillTrailingNulls)
{
using fp = TypeParam;
auto const s = numeric::scale_type{0};
auto col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{1, s}, fp{2, s}, fp{3, s}, fp{4, s}, fp{5, s}}, {1, 0, 1, 0, 0});
auto expect_col = cudf::test::fixed_width_column_wrapper<TypeParam>(
{fp{1, s}, fp{3, s}, fp{3, s}, fp{4, s}, fp{5, s}}, {1, 1, 1, 0, 0});
TestReplaceNullsWithPolicy(
std::move(col), std::move(expect_col), cudf::replace_policy::FOLLOWING);
}
struct ReplaceDictionaryTest : public cudf::test::BaseFixture {};
TEST_F(ReplaceDictionaryTest, ReplaceNulls)
{
cudf::test::strings_column_wrapper input_w({"c", "", "", "a", "d", "d", "", ""},
{1, 0, 0, 1, 1, 1, 0, 0});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper replacement_w({"c", "c", "", "a", "d", "d", "b", ""},
{1, 1, 0, 1, 1, 1, 1, 0});
auto replacement = cudf::dictionary::encode(replacement_w);
cudf::test::strings_column_wrapper expected_w({"c", "c", "", "a", "d", "d", "b", ""},
{1, 1, 0, 1, 1, 1, 1, 0});
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(input->view(), replacement->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected->view());
}
TEST_F(ReplaceDictionaryTest, ReplaceNullsWithScalar)
{
cudf::test::strings_column_wrapper input_w({"c", "", "", "a", "d", "d", "", ""},
{1, 0, 0, 1, 1, 1, 0, 0});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper expected_w({"c", "b", "b", "a", "d", "d", "b", "b"});
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(input->view(), cudf::string_scalar("b"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected->view());
}
TEST_F(ReplaceDictionaryTest, ReplaceNullsError)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_w({1, 1, 2, 2}, {1, 0, 0, 1});
auto input = cudf::dictionary::encode(input_w);
cudf::test::fixed_width_column_wrapper<int64_t> replacement_w({1, 2, 3, 4});
auto replacement = cudf::dictionary::encode(replacement_w);
EXPECT_THROW(cudf::replace_nulls(input->view(), replacement->view()), cudf::logic_error);
EXPECT_THROW(cudf::replace_nulls(input->view(), cudf::string_scalar("x")), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> input_one_w({1}, {0});
auto input_one = cudf::dictionary::encode(input_one_w);
auto dict_input = cudf::dictionary_column_view(input_one->view());
auto dict_repl = cudf::dictionary_column_view(replacement->view());
EXPECT_THROW(cudf::replace_nulls(input->view(), replacement->view()), cudf::logic_error);
}
TEST_F(ReplaceDictionaryTest, ReplaceNullsEmpty)
{
cudf::test::fixed_width_column_wrapper<int64_t> input_empty_w({});
auto input_empty = cudf::dictionary::encode(input_empty_w);
auto result = cudf::replace_nulls(input_empty->view(), input_empty->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), input_empty->view());
}
TEST_F(ReplaceDictionaryTest, ReplaceNullsNoNulls)
{
cudf::test::fixed_width_column_wrapper<int8_t> input_w({1, 1, 1});
auto input = cudf::dictionary::encode(input_w);
auto result = cudf::replace_nulls(input->view(), input->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), input->view());
result = cudf::replace_nulls(input->view(), cudf::numeric_scalar<int8_t>(0, false));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), input->view());
}
struct ReplaceNullsPolicyDictionaryTest : public cudf::test::BaseFixture {};
TEST_F(ReplaceNullsPolicyDictionaryTest, PrecedingFill)
{
cudf::test::strings_column_wrapper input_w({"head", "", "", "mid1", "mid2", "tail", "", ""},
{1, 0, 0, 1, 1, 1, 0, 0});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper expected_w(
{"head", "head", "head", "mid1", "mid2", "tail", "tail", "tail"}, no_nulls());
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(*input, cudf::replace_policy::PRECEDING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected->view());
}
TEST_F(ReplaceNullsPolicyDictionaryTest, FollowingFill)
{
cudf::test::strings_column_wrapper input_w({"head", "", "", "mid1", "mid2", "", "", "tail"},
{1, 0, 0, 1, 1, 0, 0, 1});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper expected_w(
{"head", "mid1", "mid1", "mid1", "mid2", "tail", "tail", "tail"}, no_nulls());
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(*input, cudf::replace_policy::FOLLOWING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected->view());
}
TEST_F(ReplaceNullsPolicyDictionaryTest, PrecedingFillLeadingNulls)
{
cudf::test::strings_column_wrapper input_w({"", "", "", "mid1", "mid2", "", "", "tail"},
{0, 0, 0, 1, 1, 0, 0, 1});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper expected_w(
{"", "", "", "mid1", "mid2", "mid2", "mid2", "tail"}, {0, 0, 0, 1, 1, 1, 1, 1});
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(*input, cudf::replace_policy::PRECEDING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected->view());
}
TEST_F(ReplaceNullsPolicyDictionaryTest, FollowingFillTrailingNulls)
{
cudf::test::strings_column_wrapper input_w({"head", "", "", "mid", "tail", "", "", ""},
{1, 0, 0, 1, 1, 0, 0, 0});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper expected_w({"head", "mid", "mid", "mid", "tail", "", "", ""},
{1, 1, 1, 1, 1, 0, 0, 0});
auto expected = cudf::dictionary::encode(expected_w);
auto result = cudf::replace_nulls(*input, cudf::replace_policy::FOLLOWING);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected->view());
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/replace/replace_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 <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/replace.hpp>
#include <cudf/scalar/scalar.hpp>
struct ReplaceNaNsErrorTest : public cudf::test::BaseFixture {};
// Error: old-values and new-values size mismatch
TEST_F(ReplaceNaNsErrorTest, SizeMismatch)
{
cudf::test::fixed_width_column_wrapper<float> input_column{7, 5, 6, 3, 1, 8, 4};
cudf::test::fixed_width_column_wrapper<float> replacement_column{{10, 11, 12, 13}};
EXPECT_THROW(cudf::replace_nans(input_column, replacement_column), cudf::logic_error);
}
// Error : column type mismatch
TEST_F(ReplaceNaNsErrorTest, TypeMismatch)
{
cudf::test::fixed_width_column_wrapper<float> input_column{7, 5, 6, 3, 1, 2, 8, 4};
cudf::test::fixed_width_column_wrapper<double> replacement_column{10, 11, 12, 13, 14, 15, 16, 17};
EXPECT_THROW(cudf::replace_nans(input_column, replacement_column), cudf::logic_error);
}
// Error: column type mismatch
TEST_F(ReplaceNaNsErrorTest, TypeMismatchScalar)
{
cudf::test::fixed_width_column_wrapper<double> input_column{7, 5, 6, 3, 1, 2, 8, 4};
cudf::numeric_scalar<float> replacement(1);
EXPECT_THROW(cudf::replace_nans(input_column, replacement), cudf::logic_error);
}
// Error: column type mismatch
TEST_F(ReplaceNaNsErrorTest, NonFloatType)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{7, 5, 6, 3, 1, 2, 8, 4};
cudf::numeric_scalar<float> replacement(1);
EXPECT_THROW(cudf::replace_nans(input_column, replacement), cudf::logic_error);
}
template <typename T>
struct ReplaceNaNsTest : public cudf::test::BaseFixture {};
using test_types = cudf::test::Types<float, double>;
TYPED_TEST_SUITE(ReplaceNaNsTest, test_types);
template <typename T>
void ReplaceNaNsColumn(cudf::test::fixed_width_column_wrapper<T> input,
cudf::test::fixed_width_column_wrapper<T> replacement_values,
cudf::test::fixed_width_column_wrapper<T> expected)
{
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nans(input, replacement_values));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result);
}
template <typename T>
void ReplaceNaNsScalar(cudf::test::fixed_width_column_wrapper<T> input,
cudf::scalar const& replacement_value,
cudf::test::fixed_width_column_wrapper<T> expected)
{
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::replace_nans(input, replacement_value));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result);
}
TYPED_TEST(ReplaceNaNsTest, ReplaceColumn)
{
using T = TypeParam;
auto nan = std::numeric_limits<double>::quiet_NaN();
auto inputColumn =
cudf::test::make_type_param_vector<T>({nan, 1.0, nan, 3.0, 4.0, nan, nan, 7.0, 8.0, 9.0});
auto replacement =
cudf::test::make_type_param_vector<T>({0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
ReplaceNaNsColumn<T>(
cudf::test::fixed_width_column_wrapper<T>(inputColumn.begin(), inputColumn.end()),
cudf::test::fixed_width_column_wrapper<T>(replacement.begin(), replacement.end()),
cudf::test::fixed_width_column_wrapper<T>(replacement.begin(), replacement.end()));
}
TYPED_TEST(ReplaceNaNsTest, ReplaceColumnNullable)
{
using T = TypeParam;
auto nan = std::numeric_limits<double>::quiet_NaN();
auto inputColumn =
cudf::test::make_type_param_vector<T>({nan, 1.0, nan, 3.0, 4.0, nan, nan, 7.0, 8.0, 9.0});
auto inputValid = std::vector<int>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1};
auto replacement =
cudf::test::make_type_param_vector<T>({0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
// Nulls should be untouched as they are considered not nan.
ReplaceNaNsColumn<T>(
cudf::test::fixed_width_column_wrapper<T>(
inputColumn.begin(), inputColumn.end(), inputValid.begin()),
cudf::test::fixed_width_column_wrapper<T>(replacement.begin(), replacement.end()),
cudf::test::fixed_width_column_wrapper<T>(
replacement.begin(), replacement.end(), inputValid.begin()));
}
TYPED_TEST(ReplaceNaNsTest, ReplacementHasNulls)
{
using T = TypeParam;
auto nan = std::numeric_limits<double>::quiet_NaN();
auto input_column =
cudf::test::make_type_param_vector<T>({7.0, nan, 6.0, 3.0, nan, 2.0, 8.0, 4.0});
auto replace_data =
cudf::test::make_type_param_vector<T>({4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 1.0});
auto replace_valid = std::vector<int>{1, 0, 1, 1, 1, 1, 1, 1};
auto result_data =
cudf::test::make_type_param_vector<T>({7.0, 5.0, 6.0, 3.0, 8.0, 2.0, 8.0, 4.0});
auto result_valid = std::vector<int>{1, 0, 1, 1, 1, 1, 1, 1};
ReplaceNaNsColumn<T>(
cudf::test::fixed_width_column_wrapper<T>(input_column.begin(), input_column.end()),
cudf::test::fixed_width_column_wrapper<T>(
replace_data.begin(), replace_data.end(), replace_valid.begin()),
cudf::test::fixed_width_column_wrapper<T>(
result_data.begin(), result_data.end(), result_valid.begin()));
}
TYPED_TEST(ReplaceNaNsTest, ReplaceColumn_Empty)
{
ReplaceNaNsColumn<TypeParam>(cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{},
cudf::test::fixed_width_column_wrapper<TypeParam>{});
}
TYPED_TEST(ReplaceNaNsTest, ReplaceScalar)
{
using T = TypeParam;
auto nan = std::numeric_limits<double>::quiet_NaN();
auto input_data =
cudf::test::make_type_param_vector<T>({nan, 1.0, nan, 3.0, 4.0, nan, nan, 7.0, 8.0, 9.0});
auto input_valid = std::vector<int>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1};
auto expect_data =
cudf::test::make_type_param_vector<T>({0.0, 1.0, 2.0, 3.0, 4.0, 1.0, 1.0, 7.0, 8.0, 9.0});
cudf::numeric_scalar<T> replacement(1);
ReplaceNaNsScalar<T>(cudf::test::fixed_width_column_wrapper<T>(
input_data.begin(), input_data.end(), input_valid.begin()),
replacement,
cudf::test::fixed_width_column_wrapper<T>(
expect_data.begin(), expect_data.end(), input_valid.begin()));
}
TYPED_TEST(ReplaceNaNsTest, ReplaceNullScalar)
{
using T = TypeParam;
auto nan = std::numeric_limits<double>::quiet_NaN();
auto input_data =
cudf::test::make_type_param_vector<T>({nan, 1.0, nan, 3.0, 4.0, nan, nan, 7.0, 8.0, 9.0});
auto input_valid = std::vector<int>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1};
auto expect_data =
cudf::test::make_type_param_vector<T>({0.0, 1.0, 2.0, 3.0, 4.0, 1.0, 1.0, 7.0, 8.0, 9.0});
auto expect_valid = std::vector<int>{0, 0, 0, 0, 0, 0, 0, 1, 1, 1};
cudf::numeric_scalar<T> replacement(1, false);
ReplaceNaNsScalar<T>(cudf::test::fixed_width_column_wrapper<T>(
input_data.begin(), input_data.end(), input_valid.begin()),
replacement,
cudf::test::fixed_width_column_wrapper<T>(
expect_data.begin(), expect_data.end(), expect_valid.begin()));
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/replace/clamp_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/iterator.cuh>
#include <cudf/dictionary/encode.hpp>
#include <cudf/replace.hpp>
#include <cudf/scalar/scalar_factories.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 <gtest/gtest.h>
#include <thrust/iterator/counting_iterator.h>
struct ClampErrorTest : public cudf::test::BaseFixture {};
TEST_F(ClampErrorTest, MisMatchingScalarTypes)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT64));
hi->set_valid_async(true);
cudf::test::fixed_width_column_wrapper<int32_t> input({1, 2, 3, 4, 5, 6});
EXPECT_THROW(cudf::clamp(input, *lo, *hi), cudf::logic_error);
}
TEST_F(ClampErrorTest, MisMatchingInputAndScalarTypes)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(true);
cudf::test::fixed_width_column_wrapper<int64_t> input({1, 2, 3, 4, 5, 6});
EXPECT_THROW(cudf::clamp(input, *lo, *hi), cudf::logic_error);
}
TEST_F(ClampErrorTest, MisMatchingReplaceScalarTypes)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(true);
auto lo_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT64));
lo_replace->set_valid_async(true);
auto hi_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi_replace->set_valid_async(true);
cudf::test::fixed_width_column_wrapper<int64_t> input({1, 2, 3, 4, 5, 6});
EXPECT_THROW(cudf::clamp(input, *lo, *lo_replace, *hi, *hi_replace), cudf::logic_error);
}
TEST_F(ClampErrorTest, InValidCase1)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(true);
auto lo_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo_replace->set_valid_async(false);
auto hi_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi_replace->set_valid_async(true);
cudf::test::fixed_width_column_wrapper<int64_t> input({1, 2, 3, 4, 5, 6});
EXPECT_THROW(cudf::clamp(input, *lo, *lo_replace, *hi, *hi_replace), cudf::logic_error);
}
TEST_F(ClampErrorTest, InValidCase2)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(true);
auto lo_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo_replace->set_valid_async(true);
auto hi_replace = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi_replace->set_valid_async(false);
cudf::test::fixed_width_column_wrapper<int64_t> input({1, 2, 3, 4, 5, 6});
EXPECT_THROW(cudf::clamp(input, *lo, *lo_replace, *hi, *hi_replace), cudf::logic_error);
}
struct ClampEmptyCaseTest : public cudf::test::BaseFixture {};
TEST_F(ClampEmptyCaseTest, BothScalarEmptyInvalid)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(false);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(false);
cudf::test::fixed_width_column_wrapper<int32_t> input({1, 2, 3, 4, 5, 6});
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, got->view());
}
TEST_F(ClampEmptyCaseTest, EmptyInput)
{
auto lo = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
lo->set_valid_async(true);
auto hi = cudf::make_numeric_scalar(cudf::data_type(cudf::type_id::INT32));
hi->set_valid_async(true);
cudf::test::fixed_width_column_wrapper<int32_t> input({});
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, got->view());
}
template <class T>
struct ClampTestNumeric : public cudf::test::BaseFixture {
std::unique_ptr<cudf::column> run_clamp(cudf::host_span<T const> input,
cudf::host_span<cudf::size_type const> input_validity,
T lo,
bool lo_validity,
T hi,
bool hi_validity,
T lo_replace,
bool lo_replace_validity,
T hi_replace,
bool hi_replace_validity)
{
using ScalarType = cudf::scalar_type_t<T>;
std::unique_ptr<cudf::scalar> lo_scalar{nullptr};
std::unique_ptr<cudf::scalar> hi_scalar{nullptr};
std::unique_ptr<cudf::scalar> lo_replace_scalar{nullptr};
std::unique_ptr<cudf::scalar> hi_replace_scalar{nullptr};
if (cudf::is_numeric<T>()) {
lo_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
lo_replace_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_replace_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
} else if (cudf::is_timestamp<T>()) {
lo_scalar =
cudf::make_timestamp_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_scalar =
cudf::make_timestamp_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
lo_replace_scalar =
cudf::make_timestamp_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_replace_scalar =
cudf::make_timestamp_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
} else if (cudf::is_duration<T>()) {
lo_scalar =
cudf::make_duration_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_scalar =
cudf::make_duration_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
lo_replace_scalar =
cudf::make_duration_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
hi_replace_scalar =
cudf::make_duration_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
}
static_cast<ScalarType*>(lo_scalar.get())->set_value(lo);
static_cast<ScalarType*>(lo_scalar.get())->set_valid_async(lo_validity);
static_cast<ScalarType*>(lo_replace_scalar.get())->set_value(lo_replace);
static_cast<ScalarType*>(lo_replace_scalar.get())->set_valid_async(lo_replace_validity);
static_cast<ScalarType*>(hi_scalar.get())->set_value(hi);
static_cast<ScalarType*>(hi_scalar.get())->set_valid_async(hi_validity);
static_cast<ScalarType*>(hi_replace_scalar.get())->set_value(hi_replace);
static_cast<ScalarType*>(hi_replace_scalar.get())->set_valid_async(hi_replace_validity);
if (input.size() == input_validity.size()) {
cudf::test::fixed_width_column_wrapper<T> input_column(
input.begin(), input.end(), input_validity.begin());
return cudf::clamp(
input_column, *lo_scalar, *lo_replace_scalar, *hi_scalar, *hi_replace_scalar);
} else {
cudf::test::fixed_width_column_wrapper<T> input_column(input.begin(), input.end());
return cudf::clamp(
input_column, *lo_scalar, *lo_replace_scalar, *hi_scalar, *hi_replace_scalar);
}
}
};
using Types = cudf::test::FixedWidthTypesWithoutFixedPoint;
TYPED_TEST_SUITE(ClampTestNumeric, Types);
TYPED_TEST(ClampTestNumeric, WithNoNull)
{
using T = TypeParam;
T lo(cudf::test::make_type_param_scalar<T>(2));
T hi(cudf::test::make_type_param_scalar<T>(8));
auto input = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
auto got = this->run_clamp(input, {}, lo, true, hi, true, lo, true, hi, true);
cudf::test::fixed_width_column_wrapper<T, int32_t> expected({2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampTestNumeric, LowerNull)
{
using T = TypeParam;
T lo(cudf::test::make_type_param_scalar<T>(2));
T hi(cudf::test::make_type_param_scalar<T>(8));
auto input = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
auto got = this->run_clamp(input, {}, lo, false, hi, true, lo, false, hi, true);
cudf::test::fixed_width_column_wrapper<T, int32_t> expected({0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampTestNumeric, UpperNull)
{
using T = TypeParam;
T lo(cudf::test::make_type_param_scalar<T>(2));
T hi(cudf::test::make_type_param_scalar<T>(8));
auto input = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
auto got = this->run_clamp(input, {}, lo, true, hi, false, lo, true, hi, false);
cudf::test::fixed_width_column_wrapper<T, int32_t> expected({2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampTestNumeric, InputNull)
{
using T = TypeParam;
T lo(cudf::test::make_type_param_scalar<T>(2));
T hi(cudf::test::make_type_param_scalar<T>(8));
auto input = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
std::vector<cudf::size_type> input_validity({0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0});
auto got = this->run_clamp(input, input_validity, lo, true, hi, true, lo, true, hi, true);
cudf::test::fixed_width_column_wrapper<T, int32_t> expected({2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8},
{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampTestNumeric, InputNulliWithReplace)
{
using T = TypeParam;
T lo(cudf::test::make_type_param_scalar<T>(2));
T hi(cudf::test::make_type_param_scalar<T>(8));
T lo_replace(cudf::test::make_type_param_scalar<T>(16));
T hi_replace(cudf::test::make_type_param_scalar<T>(32));
auto input = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
std::vector<cudf::size_type> input_validity({0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0});
auto got =
this->run_clamp(input, input_validity, lo, true, hi, true, lo_replace, true, hi_replace, true);
cudf::test::fixed_width_column_wrapper<T, int32_t> expected({16, 16, 2, 3, 4, 5, 6, 7, 8, 32, 32},
{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
template <typename T>
struct ClampFloatTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ClampFloatTest, cudf::test::FloatingPointTypes);
TYPED_TEST(ClampFloatTest, WithNANandNoNull)
{
using T = TypeParam;
using ScalarType = cudf::scalar_type_t<T>;
cudf::test::fixed_width_column_wrapper<T> input(
{T(8.0), T(6.0), T(NAN), T(3.0), T(4.0), T(5.0), T(1.0), T(NAN), T(2.0), T(9.0)});
auto lo_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
auto hi_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
static_cast<ScalarType*>(lo_scalar.get())->set_value(2.0);
static_cast<ScalarType*>(lo_scalar.get())->set_valid_async(true);
static_cast<ScalarType*>(hi_scalar.get())->set_value(6.0);
static_cast<ScalarType*>(hi_scalar.get())->set_valid_async(true);
auto got = cudf::clamp(input, *lo_scalar, *hi_scalar);
cudf::test::fixed_width_column_wrapper<T> expected(
{T(6.0), T(6.0), T(NAN), T(3.0), T(4.0), T(5.0), T(2.0), T(NAN), T(2.0), T(6.0)});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampFloatTest, WithNANandNull)
{
using T = TypeParam;
using ScalarType = cudf::scalar_type_t<T>;
cudf::test::fixed_width_column_wrapper<T> input(
{T(8.0), T(6.0), T(NAN), T(3.0), T(4.0), T(5.0), T(1.0), T(NAN), T(2.0), T(9.0)},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 1});
auto lo_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
auto hi_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
static_cast<ScalarType*>(lo_scalar.get())->set_value(2.0);
static_cast<ScalarType*>(lo_scalar.get())->set_valid_async(true);
static_cast<ScalarType*>(hi_scalar.get())->set_value(6.0);
static_cast<ScalarType*>(hi_scalar.get())->set_valid_async(true);
auto got = cudf::clamp(input, *lo_scalar, *hi_scalar);
cudf::test::fixed_width_column_wrapper<T> expected(
{T(6.0), T(6.0), T(NAN), T(3.0), T(4.0), T(5.0), T(2.0), T(NAN), T(2.0), T(6.0)},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TYPED_TEST(ClampFloatTest, SignOfAFloat)
{
using T = TypeParam;
using ScalarType = cudf::scalar_type_t<T>;
cudf::test::fixed_width_column_wrapper<T> input(
{T(2.0), T(0.0), T(NAN), T(4.0), T(-0.5), T(-1.0), T(1.0), T(NAN), T(0.5), T(9.0)},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 1});
auto lo_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
auto lo_replace_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
auto hi_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
auto hi_replace_scalar =
cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()}));
static_cast<ScalarType*>(lo_scalar.get())->set_value(0.0);
static_cast<ScalarType*>(lo_scalar.get())->set_valid_async(true);
static_cast<ScalarType*>(hi_scalar.get())->set_value(0.0);
static_cast<ScalarType*>(hi_scalar.get())->set_valid_async(true);
static_cast<ScalarType*>(lo_replace_scalar.get())->set_value(-1.0);
static_cast<ScalarType*>(lo_replace_scalar.get())->set_valid_async(true);
static_cast<ScalarType*>(hi_replace_scalar.get())->set_value(1.0);
static_cast<ScalarType*>(hi_replace_scalar.get())->set_valid_async(true);
auto got = cudf::clamp(input, *lo_scalar, *lo_replace_scalar, *hi_scalar, *hi_replace_scalar);
cudf::test::fixed_width_column_wrapper<T> expected(
{T(1.0), T(0.0), T(NAN), T(4.0), T(-1.0), T(-1.0), T(1.0), T(NAN), T(1.0), T(1.0)},
{1, 1, 1, 0, 1, 1, 1, 0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
struct ClampStringTest : public cudf::test::BaseFixture {};
TEST_F(ClampStringTest, WithNullableColumn)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
std::vector<bool> valids{1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end(), valids.begin());
auto lo = cudf::make_string_scalar("B");
auto hi = cudf::make_string_scalar("e");
lo->set_valid_async(true);
hi->set_valid_async(true);
std::vector<std::string> expected_strings{"B", "b", "c", "D", "e", "F", "G", "H", "i", "e", "B"};
cudf::test::strings_column_wrapper expected(
expected_strings.begin(), expected_strings.end(), valids.begin());
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(ClampStringTest, WithNonNullableColumn)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end());
auto lo = cudf::make_string_scalar("B");
auto hi = cudf::make_string_scalar("e");
lo->set_valid_async(true);
hi->set_valid_async(true);
std::vector<std::string> expected_strings{"B", "b", "c", "D", "e", "F", "G", "H", "e", "e", "B"};
cudf::test::strings_column_wrapper expected(expected_strings.begin(), expected_strings.end());
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(ClampStringTest, WithNullableColumnNullLow)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
std::vector<bool> valids{1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end(), valids.begin());
auto lo = cudf::make_string_scalar("B");
auto hi = cudf::make_string_scalar("e");
lo->set_valid_async(false);
hi->set_valid_async(true);
std::vector<std::string> expected_strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "e", "B"};
cudf::test::strings_column_wrapper expected(
expected_strings.begin(), expected_strings.end(), valids.begin());
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(ClampStringTest, WithNullableColumnNullHigh)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
std::vector<bool> valids{1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end(), valids.begin());
auto lo = cudf::make_string_scalar("B");
auto hi = cudf::make_string_scalar("e");
lo->set_valid_async(true);
hi->set_valid_async(false);
std::vector<std::string> expected_strings{"B", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
cudf::test::strings_column_wrapper expected(
expected_strings.begin(), expected_strings.end(), valids.begin());
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
TEST_F(ClampStringTest, WithNullableColumnBothLoAndHiNull)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
std::vector<bool> valids{1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end(), valids.begin());
auto lo = cudf::make_string_scalar("B");
auto hi = cudf::make_string_scalar("e");
lo->set_valid_async(false);
hi->set_valid_async(false);
auto got = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, got->view());
}
TEST_F(ClampStringTest, WithReplaceString)
{
std::vector<std::string> strings{"A", "b", "c", "D", "e", "F", "G", "H", "i", "j", "B"};
std::vector<bool> valids{1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(strings.begin(), strings.end(), valids.begin());
auto lo = cudf::make_string_scalar("B");
auto lo_replace = cudf::make_string_scalar("Z");
auto hi = cudf::make_string_scalar("e");
auto hi_replace = cudf::make_string_scalar("z");
lo->set_valid_async(true);
lo_replace->set_valid_async(true);
hi->set_valid_async(true);
hi_replace->set_valid_async(true);
std::vector<std::string> expected_strings{"Z", "b", "c", "D", "e", "F", "G", "H", "z", "z", "B"};
cudf::test::strings_column_wrapper expected(
expected_strings.begin(), expected_strings.end(), valids.begin());
auto got = cudf::clamp(input, *lo, *lo_replace, *hi, *hi_replace);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got->view());
}
struct ClampDictionaryTest : public cudf::test::BaseFixture {};
TEST_F(ClampDictionaryTest, WithNullableColumn)
{
cudf::test::strings_column_wrapper input_s({"a", "b", "c", "d", "", "d", "c", "b", "a"},
{1, 1, 1, 1, 0, 1, 1, 1, 1});
auto input = cudf::dictionary::encode(input_s);
auto results = cudf::clamp(input->view(), cudf::string_scalar("b"), cudf::string_scalar("c"));
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::strings_column_wrapper expected({"b", "b", "c", "c", "", "c", "c", "b", "b"},
{1, 1, 1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(ClampDictionaryTest, WithNonNullableColumn)
{
cudf::test::fixed_width_column_wrapper<int8_t> input_s({3, 3, 1, 1, 2, 2, 4, 4});
auto input = cudf::dictionary::encode(input_s);
auto results =
cudf::clamp(input->view(), cudf::numeric_scalar<int8_t>(2), cudf::numeric_scalar<int8_t>(3));
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<int8_t> expected({3, 3, 2, 2, 2, 2, 3, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(ClampDictionaryTest, NullLowHi)
{
cudf::test::fixed_width_column_wrapper<int16_t> input_s({200, 100, 0, 300, 300, 400, 100, 200, 0},
{1, 1, 0, 1, 1, 1, 1, 1, 0});
auto input = cudf::dictionary::encode(input_s);
{
auto results = cudf::clamp(
input->view(), cudf::numeric_scalar<int16_t>(0, false), cudf::numeric_scalar<int16_t>(300));
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<int16_t> expected(
{200, 100, 0, 300, 300, 300, 100, 200, 0}, {1, 1, 0, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
{
auto results = cudf::clamp(
input->view(), cudf::numeric_scalar<int16_t>(200), cudf::numeric_scalar<int16_t>(0, false));
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<int16_t> expected(
{200, 200, 0, 300, 300, 400, 200, 200, 0}, {1, 1, 0, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
{
auto results = cudf::clamp(input->view(),
cudf::numeric_scalar<int16_t>(0, false),
cudf::numeric_scalar<int16_t>(0, false));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input->view(), results->view());
}
}
TEST_F(ClampDictionaryTest, WithReplace)
{
cudf::test::fixed_width_column_wrapper<int64_t> input_s({1, 2, 3, 4, 0, 4, 3, 2, 1},
{1, 1, 1, 1, 0, 1, 1, 1, 1});
auto input = cudf::dictionary::encode(input_s);
auto results = cudf::clamp(input->view(),
cudf::numeric_scalar<int64_t>(2),
cudf::numeric_scalar<int64_t>(2000),
cudf::numeric_scalar<int64_t>(3),
cudf::numeric_scalar<int64_t>(3000));
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<int64_t> expected({2000, 2, 3, 3000, 0, 3000, 3, 2, 2000},
{1, 1, 1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
template <typename T>
struct FixedPointTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(FixedPointTest, cudf::test::FixedPointTypes);
TYPED_TEST(FixedPointTest, ZeroScale)
{
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 scale = scale_type{0};
auto const lo = cudf::make_fixed_point_scalar<decimalXX>(2, scale);
auto const hi = cudf::make_fixed_point_scalar<decimalXX>(8, scale);
auto const input = fp_wrapper{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, scale};
auto const expected = fp_wrapper{{2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 8}, scale};
auto const result = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointTest, LargeTest)
{
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 scale = scale_type{-3};
auto const lo = cudf::make_fixed_point_scalar<decimalXX>(1000, scale);
auto const hi = cudf::make_fixed_point_scalar<decimalXX>(2000, scale);
auto begin = thrust::make_counting_iterator(-1000);
auto clamp = [](int e) { return e < 1000 ? 1000 : e > 2000 ? 2000 : e; };
auto begin2 = cudf::detail::make_counting_transform_iterator(-1000, clamp);
auto const input = fp_wrapper{begin, begin + 5000, scale};
auto const expected = fp_wrapper{begin2, begin2 + 5000, scale};
auto const result = cudf::clamp(input, *lo, *hi);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointTest, MismatchedScalarScales)
{
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 scale = scale_type{0};
auto const lo = cudf::make_fixed_point_scalar<decimalXX>(2, scale_type{-1});
auto const hi = cudf::make_fixed_point_scalar<decimalXX>(8, scale);
auto const input = fp_wrapper{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, scale};
EXPECT_THROW(cudf::clamp(input, *lo, *hi), cudf::logic_error);
}
TYPED_TEST(FixedPointTest, MismatchedColumnScalarScale)
{
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 scale = scale_type{0};
auto const lo = cudf::make_fixed_point_scalar<decimalXX>(2, scale);
auto const hi = cudf::make_fixed_point_scalar<decimalXX>(8, scale);
auto const input = fp_wrapper{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, scale_type{-4}};
EXPECT_THROW(cudf::clamp(input, *lo, *hi), cudf::logic_error);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/replace/replace_tests.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018 BlazingDB, Inc.
* Copyright 2018 Cristhian Alberto Gonzales Castillo <[email protected]>
*
* 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/detail/iterator.cuh>
#include <cudf/dictionary/encode.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/replace.hpp>
#include <thrust/host_vector.h>
#include <thrust/iterator/transform_iterator.h>
#include <cstdlib>
#include <cudf/types.hpp>
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
struct ReplaceErrorTest : public cudf::test::BaseFixture {};
// Error: old-values and new-values size mismatch
TEST_F(ReplaceErrorTest, SizeMismatch)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4}};
cudf::test::fixed_width_column_wrapper<int32_t> values_to_replace_column{{10, 11, 12, 13}};
cudf::test::fixed_width_column_wrapper<int32_t> replacement_values_column{{15, 16, 17}};
EXPECT_THROW(
cudf::find_and_replace_all(input_column, values_to_replace_column, replacement_values_column),
cudf::logic_error);
}
// Error: column type mismatch
TEST_F(ReplaceErrorTest, TypeMismatch)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4}};
cudf::test::fixed_width_column_wrapper<float> values_to_replace_column{{10, 11, 12}};
cudf::test::fixed_width_column_wrapper<int32_t> replacement_values_column{{15, 16, 17}};
EXPECT_THROW(
cudf::find_and_replace_all(input_column, values_to_replace_column, replacement_values_column),
cudf::logic_error);
}
// Error: nulls in old-values
TEST_F(ReplaceErrorTest, NullInOldValues)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_column{{7, 5, 6, 3, 1, 2, 8, 4}};
cudf::test::fixed_width_column_wrapper<int32_t> values_to_replace_column{{10, 11, 12, 13},
{0, 1, 0, 1}};
cudf::test::fixed_width_column_wrapper<int32_t> replacement_values_column{{15, 16, 17, 18}};
EXPECT_THROW(
cudf::find_and_replace_all(input_column, values_to_replace_column, replacement_values_column),
cudf::logic_error);
}
struct ReplaceStringsTest : public cudf::test::BaseFixture {};
// Strings test
TEST_F(ReplaceStringsTest, Strings)
{
std::vector<std::string> input{"a", "b", "c", "d", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{"a"};
std::vector<std::string> replacement{"z"};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{replacement.begin(), replacement.end()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
std::vector<std::string> expected{"z", "b", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 1, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsReplacementNulls)
{
std::vector<std::string> input{"a", "b", "c", "d", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"z", ""};
std::vector<cudf::valid_type> replacement_valid{1, 0};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{
replacement.begin(), replacement.end(), replacement_valid.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
std::vector<std::string> expected{"z", "", "c", "d", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 0, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsResultAllNulls)
{
std::vector<std::string> input{"b", "b", "b", "b", "b", "b", "b", "b"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"a", ""};
std::vector<cudf::valid_type> replacement_valid{1, 0};
std::vector<std::string> expected{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> ex_valid{0, 0, 0, 0, 0, 0, 0, 0};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{
replacement.begin(), replacement.end(), replacement_valid.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsResultAllEmpty)
{
std::vector<std::string> input{"b", "b", "b", "b", "b", "b", "b", "b"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"a", ""};
std::vector<cudf::valid_type> replacement_valid{1, 1};
std::vector<std::string> expected{"", "", "", "", "", "", "", ""};
std::vector<cudf::valid_type> ex_valid{1, 1, 1, 1, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{
replacement.begin(), replacement.end(), replacement_valid.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsInputNulls)
{
std::vector<std::string> input{"a", "b", "", "", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"z", "y"};
std::vector<cudf::valid_type> input_valid{1, 1, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end(), input_valid.begin()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{replacement.begin(), replacement.end()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
std::vector<std::string> expected{"z", "y", "", "", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 1, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsInputAndReplacementNulls)
{
std::vector<std::string> input{"a", "b", "", "", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"z", ""};
std::vector<cudf::valid_type> replacement_valid{1, 0};
std::vector<cudf::valid_type> input_valid{1, 1, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end(), input_valid.begin()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{
replacement.begin(), replacement.end(), replacement_valid.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
std::vector<std::string> expected{"z", "", "", "", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 0, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsEmptyReplacement)
{
std::vector<std::string> input{"a", "b", "", "", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{};
std::vector<std::string> replacement{};
std::vector<cudf::valid_type> input_valid{1, 1, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper input_wrapper{input.begin(), input.end(), input_valid.begin()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{replacement.begin(), replacement.end()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
std::vector<std::string> expected{"a", "b", "", "", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 1, 0, 0, 1, 1, 1, 1};
cudf::test::strings_column_wrapper expected_wrapper{
expected.begin(), expected.end(), ex_valid.begin()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
// Strings test
TEST_F(ReplaceStringsTest, StringsLargeScale)
{
std::vector<std::string> input{"a", "b", "", "", "e", "f", "g", "h"};
std::vector<std::string> values_to_replace{"a", "b"};
std::vector<std::string> replacement{"z", ""};
std::vector<cudf::valid_type> replacement_valid{1, 0};
std::vector<cudf::valid_type> input_valid{1, 1, 0, 0, 1, 1, 1, 1};
std::vector<std::string> expected{"z", "", "", "", "e", "f", "g", "h"};
std::vector<cudf::valid_type> ex_valid{1, 0, 0, 0, 1, 1, 1, 1};
std::vector<std::string> big_input{};
std::vector<cudf::valid_type> big_input_valid{};
std::vector<std::string> big_expected{};
std::vector<cudf::valid_type> big_ex_valid{};
for (int i = 0; i < 10000; i++) {
int ind = i % input.size();
big_input.push_back(input[ind]);
big_input_valid.push_back(input_valid[ind]);
big_expected.push_back(expected[ind]);
big_ex_valid.push_back(ex_valid[ind]);
}
cudf::test::strings_column_wrapper expected_wrapper{
big_expected.begin(), big_expected.end(), big_ex_valid.begin()};
cudf::test::strings_column_wrapper input_wrapper{
big_input.begin(), big_input.end(), big_input_valid.begin()};
cudf::test::strings_column_wrapper values_to_replace_wrapper{values_to_replace.begin(),
values_to_replace.end()};
cudf::test::strings_column_wrapper replacement_wrapper{
replacement.begin(), replacement.end(), replacement_valid.begin()};
std::unique_ptr<cudf::column> result;
ASSERT_NO_THROW(result = cudf::find_and_replace_all(
input_wrapper, values_to_replace_wrapper, replacement_wrapper));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_wrapper);
}
//// This is the main test feature
template <class T>
struct ReplaceTest : cudf::test::BaseFixture {
ReplaceTest()
{
// Use constant seed so the pseudo-random order is the same each time
// Each time the class is constructed a new constant seed is used
static size_t number_of_instantiations{0};
std::srand(number_of_instantiations++);
}
~ReplaceTest() override {}
};
/**
* @brief Main method for testing.
* Initializes the input columns with the given values. Then compute the actual
* resultant column by invoking `cudf::find_and_replace_all()` and then
* compute the expected column.
*
* @param input_column The original values
* @param values_to_replace_column The values that will be replaced
* @param replacement_values_column The new values
* @param input_column_valid The mask for replace column
* @param replacement_values_valid The mask for new values
* @param print Optionally print the set of columns for debug
*/
template <typename T>
void test_replace(cudf::host_span<T const> input_column,
cudf::host_span<T const> values_to_replace_column,
cudf::host_span<T const> replacement_values_column,
cudf::host_span<cudf::valid_type const> input_column_valid = {},
cudf::host_span<cudf::valid_type const> replacement_values_valid = {},
bool print = false)
{
cudf::test::fixed_width_column_wrapper<T> _input_column(input_column.begin(), input_column.end());
if (input_column_valid.size() > 0) {
_input_column = cudf::test::fixed_width_column_wrapper<T>(
input_column.begin(), input_column.end(), input_column_valid.begin());
}
cudf::test::fixed_width_column_wrapper<T> _values_to_replace_column(
values_to_replace_column.begin(), values_to_replace_column.end());
cudf::test::fixed_width_column_wrapper<T> _replacement_values_column(
replacement_values_column.begin(), replacement_values_column.end());
if (replacement_values_valid.size() > 0) {
_replacement_values_column =
cudf::test::fixed_width_column_wrapper<T>(replacement_values_column.begin(),
replacement_values_column.end(),
replacement_values_valid.begin());
}
/* getting the actual result*/
std::unique_ptr<cudf::column> actual_result;
ASSERT_NO_THROW(actual_result = cudf::find_and_replace_all(
_input_column, _values_to_replace_column, _replacement_values_column));
/* computing the expected result */
thrust::host_vector<T> reference_result(input_column.begin(), input_column.end());
thrust::host_vector<bool> isReplaced(reference_result.size(), false);
thrust::host_vector<cudf::valid_type> expected_valid(input_column_valid.begin(),
input_column_valid.end());
if (replacement_values_valid.size() > 0 && 0 == input_column_valid.size()) {
expected_valid.assign(input_column.size(), true);
}
bool const input_has_nulls = (input_column_valid.size() > 0);
bool const replacement_has_nulls = (replacement_values_valid.size() > 0);
for (size_t i = 0; i < values_to_replace_column.size(); i++) {
size_t k = 0;
auto pred = [=, &k, &reference_result, &expected_valid, &isReplaced](T element) {
bool toBeReplaced = false;
if (!isReplaced[k]) {
if (!input_has_nulls || expected_valid[k]) {
if (element == values_to_replace_column[i]) {
toBeReplaced = true;
isReplaced[k] = toBeReplaced;
if (replacement_has_nulls && !replacement_values_valid[i]) {
if (print) std::cout << "clearing bit at: " << k << "\n";
expected_valid[k] = false;
}
}
}
}
++k;
return toBeReplaced;
};
std::replace_if(
reference_result.begin(), reference_result.end(), pred, replacement_values_column[i]);
}
cudf::test::fixed_width_column_wrapper<T> expected(reference_result.begin(),
reference_result.end());
if (expected_valid.size() > 0)
expected = cudf::test::fixed_width_column_wrapper<T>(
reference_result.begin(), reference_result.end(), expected_valid.begin());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual_result);
}
using Types = cudf::test::NumericTypes;
TYPED_TEST_SUITE(ReplaceTest, Types);
// Simple test, replacing all even replacement_values_column
TYPED_TEST(ReplaceTest, ReplaceEvenPosition)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({1, 2, 3, 4, 5, 6, 7, 8});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({2, 6, 4, 8});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({0, 4, 2, 6});
test_replace<T>(input_column, values_to_replace_column, replacement_values_column);
}
// Similar test as ReplaceEvenPosition, but with unordered data
TYPED_TEST(ReplaceTest, Unordered)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({2, 6, 4, 8});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({0, 4, 2, 6});
test_replace<T>(input_column, values_to_replace_column, replacement_values_column);
}
// Testing with Nothing To Replace
TYPED_TEST(ReplaceTest, NothingToReplace)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({10, 11, 12});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({15, 16, 17});
test_replace<T>(input_column, values_to_replace_column, replacement_values_column);
}
// Testing with empty Data
TYPED_TEST(ReplaceTest, EmptyData)
{
using T = TypeParam;
thrust::host_vector<T> input_column{{}};
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({10, 11, 12});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({15, 16, 17});
test_replace<T>(input_column, values_to_replace_column, replacement_values_column);
}
// Testing with empty Replace
TYPED_TEST(ReplaceTest, EmptyReplace)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
thrust::host_vector<T> values_to_replace_column{};
thrust::host_vector<T> replacement_values_column{};
test_replace<T>(input_column, values_to_replace_column, replacement_values_column);
}
// Testing with input column containing nulls
TYPED_TEST(ReplaceTest, NullsInData)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const input_column_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({1, 1, 1, 0, 0, 1, 1, 1});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({2, 6, 4, 8});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({0, 4, 2, 6});
test_replace<T>(
input_column, values_to_replace_column, replacement_values_column, input_column_valid);
}
// Testing with replacement column containing nulls
TYPED_TEST(ReplaceTest, NullsInNewValues)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({2, 6, 4, 8});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({0, 4, 2, 6});
auto const replacement_values_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({0, 1, 1, 1});
test_replace<TypeParam>(input_column,
values_to_replace_column,
replacement_values_column,
{},
replacement_values_valid);
}
// Testing with both replacement and input column containing nulls
TYPED_TEST(ReplaceTest, NullsInBoth)
{
using T = TypeParam;
auto const input_column = cudf::test::make_type_param_vector<T>({7, 5, 6, 3, 1, 2, 8, 4});
auto const input_column_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({1, 1, 1, 0, 0, 1, 1, 1});
auto const values_to_replace_column = cudf::test::make_type_param_vector<T>({2, 6, 4, 8});
auto const replacement_values_column = cudf::test::make_type_param_vector<T>({0, 4, 2, 6});
auto const replacement_values_valid =
cudf::test::make_type_param_vector<cudf::valid_type>({1, 1, 0, 1});
test_replace<TypeParam>(input_column,
values_to_replace_column,
replacement_values_column,
input_column_valid,
replacement_values_valid);
}
// Test with much larger data sets
TYPED_TEST(ReplaceTest, LargeScaleReplaceTest)
{
const size_t DATA_SIZE = 1000000;
const size_t REPLACE_SIZE = 10000;
thrust::host_vector<TypeParam> input_column(DATA_SIZE);
std::generate(std::begin(input_column), std::end(input_column), [REPLACE_SIZE]() {
return std::rand() % (REPLACE_SIZE);
});
std::vector<TypeParam> values_to_replace_column(REPLACE_SIZE);
std::vector<TypeParam> replacement_values_column(REPLACE_SIZE);
size_t count = 0;
for (size_t i = 0; i < 7; i++) {
for (size_t j = 0; j < REPLACE_SIZE; j += 7) {
if (i + j < REPLACE_SIZE) {
values_to_replace_column[i + j] = count;
count++;
replacement_values_column[i + j] = count;
}
}
}
cudf::test::fixed_width_column_wrapper<TypeParam> _input_column(input_column.begin(),
input_column.end());
cudf::test::fixed_width_column_wrapper<TypeParam> _values_to_replace_column(
values_to_replace_column.begin(), values_to_replace_column.end());
cudf::test::fixed_width_column_wrapper<TypeParam> _replacement_values_column(
replacement_values_column.begin(), replacement_values_column.end());
std::unique_ptr<cudf::column> actual_result;
ASSERT_NO_THROW(actual_result = cudf::find_and_replace_all(
_input_column, _values_to_replace_column, _replacement_values_column));
std::for_each(input_column.begin(), input_column.end(), [](TypeParam& d) { d += 1; });
cudf::test::fixed_width_column_wrapper<TypeParam> expected(input_column.begin(),
input_column.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual_result);
}
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, FixedPointReplace)
{
using namespace numeric;
using decimalXX = TypeParam;
auto const ONE = decimalXX{1, scale_type{0}};
auto const TWO = decimalXX{2, scale_type{0}};
auto const sz = std::size_t{1000};
auto mod2 = [&](auto e) { return e % 2 ? ONE : TWO; };
auto transform_begin = cudf::detail::make_counting_transform_iterator(0, mod2);
auto const vec1 = std::vector<decimalXX>(transform_begin, transform_begin + sz);
auto const vec2 = std::vector<decimalXX>(sz, TWO);
auto const to_replace = std::vector<decimalXX>{ONE};
auto const replacement = std::vector<decimalXX>{TWO};
auto const input_w = wrapper<decimalXX>(vec1.begin(), vec1.end());
auto const to_replace_w = wrapper<decimalXX>(to_replace.begin(), to_replace.end());
auto const replacement_w = wrapper<decimalXX>(replacement.begin(), replacement.end());
auto const expected_w = wrapper<decimalXX>(vec2.begin(), vec2.end());
auto const result = cudf::find_and_replace_all(input_w, to_replace_w, replacement_w);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected_w);
}
struct ReplaceDictionaryTest : public cudf::test::BaseFixture {};
TEST_F(ReplaceDictionaryTest, StringsKeys)
{
cudf::test::strings_column_wrapper input_w({"a", "b", "a", "c", "b", "a", "c", "b"});
auto input = cudf::dictionary::encode(input_w);
cudf::test::strings_column_wrapper values_to_replace_w({"a"});
auto values_to_replace = cudf::dictionary::encode(values_to_replace_w);
cudf::test::strings_column_wrapper replacements_w({"z"});
auto replacements = cudf::dictionary::encode(replacements_w);
auto result =
cudf::find_and_replace_all(input->view(), values_to_replace->view(), replacements->view());
auto decoded = cudf::dictionary::decode(result->view());
cudf::test::strings_column_wrapper expected({"z", "b", "z", "c", "b", "z", "c", "b"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected);
}
TEST_F(ReplaceDictionaryTest, InputAndReplacementNulls)
{
cudf::test::fixed_width_column_wrapper<int32_t> input_w({1, 2, 1, 2, 0, 3, 4, 4, 3},
{1, 1, 1, 1, 0, 1, 1, 1, 1});
auto input = cudf::dictionary::encode(input_w);
cudf::test::fixed_width_column_wrapper<int32_t> values_to_replace_w({2, 3});
auto values_to_replace = cudf::dictionary::encode(values_to_replace_w);
cudf::test::fixed_width_column_wrapper<int32_t> replacements_w({5, 0}, {1, 0});
auto replacements = cudf::dictionary::encode(replacements_w);
auto result =
cudf::find_and_replace_all(input->view(), values_to_replace->view(), replacements->view());
auto decoded = cudf::dictionary::decode(result->view());
cudf::test::fixed_width_column_wrapper<int32_t> expected({1, 5, 1, 5, 0, 0, 4, 4, 0},
{1, 1, 1, 1, 0, 0, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected);
}
TEST_F(ReplaceDictionaryTest, EmptyReplacement)
{
cudf::test::fixed_width_column_wrapper<double> input_w(
{1.0, 2.0, 1.0, 2.0, 0.0, 3.0, 4.0, 4.0, 3.0}, {1, 1, 1, 1, 0, 1, 1, 1, 1});
auto input = cudf::dictionary::encode(input_w);
cudf::test::fixed_width_column_wrapper<double> empty_w({});
auto empty = cudf::dictionary::encode(empty_w);
auto result = cudf::find_and_replace_all(input->view(), empty->view(), empty->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, *input);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/replace/normalize_replace_tests.cpp
|
/*
* Copyright (c) 2018-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/replace.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
// This is the main test fixture
struct ReplaceTest : public cudf::test::BaseFixture {};
template <typename T>
void normalize_nans_and_zeros_test_internal(
cudf::test::fixed_width_column_wrapper<T> const& test_data_in,
cudf::column_view const& test_data_comp)
{
// mutable overload
{
cudf::column test_data(test_data_in);
cudf::mutable_column_view mutable_view = test_data;
cudf::normalize_nans_and_zeros(mutable_view);
// compare bitwise
CUDF_TEST_EXPECT_EQUAL_BUFFERS(
mutable_view.head(), test_data_comp.head(), mutable_view.size() * sizeof(T));
}
// returned column overload
{
cudf::column test_data(test_data_in);
cudf::column_view view = test_data;
auto out = cudf::normalize_nans_and_zeros(view);
auto out_view = out->view();
// compare bitwise
CUDF_TEST_EXPECT_EQUAL_BUFFERS(
out_view.head(), test_data_comp.head(), out_view.size() * sizeof(T));
}
}
// Test for normalize_nans_and_nulls
TEST_F(ReplaceTest, NormalizeNansAndZerosFloat)
{
// bad data
cudf::test::fixed_width_column_wrapper<float> f_test_data{
32.5f, -0.0f, 111.0f, -NAN, NAN, 1.0f, 0.0f, 54.3f};
// good data
cudf::test::fixed_width_column_wrapper<float> f_test_data_comp{
32.5f, 0.0f, 111.0f, NAN, NAN, 1.0f, 0.0f, 54.3f};
//
normalize_nans_and_zeros_test_internal<float>(f_test_data, f_test_data_comp);
}
// Test for normalize_nans_and_nulls
TEST_F(ReplaceTest, NormalizeNansAndZerosDouble)
{
// bad data
cudf::test::fixed_width_column_wrapper<double> d_test_data{
32.5, -0.0, 111.0, double(-NAN), double(NAN), 1.0, 0.0, 54.3};
// good data
cudf::test::fixed_width_column_wrapper<double> d_test_data_comp{
32.5, 0.0, 111.0, double(NAN), double(NAN), 1.0, 0.0, 54.3};
//
normalize_nans_and_zeros_test_internal<double>(d_test_data, d_test_data_comp);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/urls_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/strings/convert/convert_urls.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <random>
#include <vector>
struct StringsConvertTest : public cudf::test::BaseFixture {};
TEST_F(StringsConvertTest, UrlEncode)
{
std::vector<char const*> h_strings{"www.nvidia.com/rapids?p=é",
"/_file-7.txt",
"a b+c~d",
"e\tfgh\\jklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
" \t\f\n",
nullptr,
""};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.cbegin(),
[](auto const str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::url_encode(strings_view);
std::vector<char const*> h_expected{"www.nvidia.com%2Frapids%3Fp%3D%C3%A9",
"%2F_file-7.txt",
"a%20b%2Bc~d",
"e%09fgh%5Cjklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"0123456789",
"%20%09%0C%0A",
nullptr,
""};
cudf::test::strings_column_wrapper expected(
h_expected.cbegin(),
h_expected.cend(),
thrust::make_transform_iterator(h_expected.cbegin(),
[](auto const str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, UrlDecode)
{
std::vector<char const*> h_strings{"www.nvidia.com/rapids/%3Fp%3D%C3%A9",
"/_file-1234567890.txt",
"a%20b%2Bc~defghijklmnopqrstuvwxyz",
"%25-accent%c3%a9d",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"01234567890",
nullptr,
""};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.cbegin(),
[](auto const str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::url_decode(strings_view);
std::vector<char const*> h_expected{"www.nvidia.com/rapids/?p=é",
"/_file-1234567890.txt",
"a b+c~defghijklmnopqrstuvwxyz",
"%-accentéd",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"01234567890",
nullptr,
""};
cudf::test::strings_column_wrapper expected(
h_expected.cbegin(),
h_expected.cend(),
thrust::make_transform_iterator(h_expected.cbegin(),
[](auto const str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, UrlDecodeNop)
{
std::vector<char const*> h_strings{"www.nvidia.com/rapids/abc123",
"/_file-1234567890.txt",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ%",
"0123456789%0",
nullptr,
""};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.cbegin(),
[](auto const str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::url_decode(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, strings);
}
TEST_F(StringsConvertTest, UrlDecodeSliced)
{
std::vector<char const*> h_strings{"www.nvidia.com/rapids/%3Fp%3D%C3%A9%",
"01/_file-1234567890.txt",
"a%20b%2Bc~defghijklmnopqrstuvwxyz",
"%25-accent%c3%a9d",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ%0",
"01234567890",
nullptr,
""};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.cbegin(),
[](auto const str) { return str != nullptr; }));
std::vector<char const*> h_expected{"www.nvidia.com/rapids/?p=é%",
"01/_file-1234567890.txt",
"a b+c~defghijklmnopqrstuvwxyz",
"%-accentéd",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ%0",
"01234567890",
nullptr,
""};
cudf::test::strings_column_wrapper expected(
h_expected.cbegin(),
h_expected.cend(),
thrust::make_transform_iterator(h_expected.cbegin(),
[](auto const str) { return str != nullptr; }));
std::vector<cudf::size_type> slice_indices{0, 3, 3, 6, 6, 8};
auto sliced_strings = cudf::slice(strings, slice_indices);
auto sliced_expected = cudf::slice(expected, slice_indices);
for (size_t i = 0; i < sliced_strings.size(); ++i) {
auto strings_view = cudf::strings_column_view(sliced_strings[i]);
auto results = cudf::strings::url_decode(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, sliced_expected[i]);
}
}
TEST_F(StringsConvertTest, UrlDecodeLargeStrings)
{
constexpr int string_len = 35000;
std::vector<char> string_encoded;
string_encoded.reserve(string_len * 3);
std::vector<char> string_plain;
string_plain.reserve(string_len + 1);
std::random_device rd;
std::mt19937 random_number_generator(rd());
std::uniform_int_distribution<int> distribution(0, 4);
for (int character_idx = 0; character_idx < string_len; character_idx++) {
switch (distribution(random_number_generator)) {
case 0:
string_encoded.push_back('a');
string_plain.push_back('a');
break;
case 1:
string_encoded.push_back('b');
string_plain.push_back('b');
break;
case 2:
string_encoded.push_back('c');
string_plain.push_back('c');
break;
case 3:
string_encoded.push_back('%');
string_encoded.push_back('3');
string_encoded.push_back('F');
string_plain.push_back('?');
break;
case 4:
string_encoded.push_back('%');
string_encoded.push_back('3');
string_encoded.push_back('D');
string_plain.push_back('=');
break;
}
}
string_encoded.push_back('\0');
string_plain.push_back('\0');
std::vector<char const*> h_strings{string_encoded.data()};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.cbegin(),
[](auto const str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::url_decode(strings_view);
std::vector<char const*> h_expected{string_plain.data()};
cudf::test::strings_column_wrapper expected(
h_expected.cbegin(),
h_expected.cend(),
thrust::make_transform_iterator(h_expected.cbegin(),
[](auto const str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, ZeroSizeUrlStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results = cudf::strings::url_encode(zero_size_strings_column);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::url_decode(zero_size_strings_column);
cudf::test::expect_column_empty(results->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/reverse_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_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf/column/column.hpp>
#include <cudf/copying.hpp>
#include <cudf/strings/reverse.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <vector>
struct StringsReverseTest : public cudf::test::BaseFixture {};
TEST_F(StringsReverseTest, Reverse)
{
auto input = cudf::test::strings_column_wrapper(
{"abcdef", "12345", "", "", "aébé", "A é Z", "X", "é"}, {1, 1, 1, 0, 1, 1, 1, 1});
auto results = cudf::strings::reverse(cudf::strings_column_view(input));
auto expected = cudf::test::strings_column_wrapper(
{"fedcba", "54321", "", "", "ébéa", "Z é A", "X", "é"}, {1, 1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
auto sliced = cudf::slice(input, {1, 7}).front();
results = cudf::strings::reverse(cudf::strings_column_view(sliced));
expected =
cudf::test::strings_column_wrapper({"54321", "", "", "ébéa", "Z é A", "X"}, {1, 1, 0, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReverseTest, EmptyStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results = cudf::strings::reverse(cudf::strings_column_view(zero_size_strings_column));
auto view = results->view();
cudf::test::expect_column_empty(results->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/fill_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/column/column_factories.hpp>
#include <cudf/filling.hpp>
#include <cudf/scalar/scalar.hpp>
#include <vector>
struct StringsFillTest : public cudf::test::BaseFixture {};
TEST_F(StringsFillTest, Fill)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper input(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
{
auto results = cudf::fill(input, 1, 5, cudf::string_scalar("zz"));
std::vector<char const*> h_expected{"eee", "zz", "zz", "zz", "zz", "bbb", "ééé"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::fill(input, 2, 4, cudf::string_scalar("", false));
std::vector<char const*> h_expected{"eee", "bb", nullptr, nullptr, "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::fill(input, 5, 5, cudf::string_scalar("zz"));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, input);
}
{
auto results = cudf::fill(input, 0, 7, cudf::string_scalar(""));
cudf::test::strings_column_wrapper expected({"", "", "", "", "", "", ""},
{1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::fill(input, 0, 7, cudf::string_scalar("", false));
cudf::test::strings_column_wrapper expected({"", "", "", "", "", "", ""},
{0, 0, 0, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
}
TEST_F(StringsFillTest, ZeroSizeStringsColumns)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results = cudf::fill(zero_size_strings_column, 0, 0, cudf::string_scalar(""));
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsFillTest, FillRangeError)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper input(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
EXPECT_THROW(cudf::fill(input, 5, 1, cudf::string_scalar("")), cudf::logic_error);
EXPECT_THROW(cudf::fill(input, 5, 9, cudf::string_scalar("")), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/case_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/column/column.hpp>
#include <cudf/strings/capitalize.hpp>
#include <cudf/strings/case.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsCaseTest : public cudf::test::BaseFixture {};
TEST_F(StringsCaseTest, ToLower)
{
std::vector<char const*> h_strings{
"Éxamples aBc", "123 456", nullptr, "ARE THE", "tést strings", ""};
std::vector<char const*> h_expected{
"éxamples abc", "123 456", nullptr, "are the", "tést strings", ""};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_lower(strings_view);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, ToUpper)
{
std::vector<char const*> h_strings{
"Éxamples aBc", "123 456", nullptr, "ARE THE", "tést strings", ""};
std::vector<char const*> h_expected{
"ÉXAMPLES ABC", "123 456", nullptr, "ARE THE", "TÉST STRINGS", ""};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_upper(strings_view);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, Swapcase)
{
std::vector<char const*> h_strings{
"Éxamples aBc", "123 456", nullptr, "ARE THE", "tést strings", ""};
std::vector<char const*> h_expected{
"éXAMPLES AbC", "123 456", nullptr, "are the", "TÉST STRINGS", ""};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::swapcase(strings_view);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, Capitalize)
{
cudf::test::strings_column_wrapper strings(
{"SȺȺnich xyZ", "Examples aBc", "thesé", "", "ARE\tTHE", "tést\tstrings", ""},
{1, 1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::capitalize(strings_view);
cudf::test::strings_column_wrapper expected(
{"Sⱥⱥnich xyz", "Examples abc", "Thesé", "", "Are\tthe", "Tést\tstrings", ""},
{1, 1, 1, 0, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::capitalize(strings_view, std::string(" "));
cudf::test::strings_column_wrapper expected(
{"Sⱥⱥnich Xyz", "Examples Abc", "Thesé", "", "Are\tthe", "Tést\tstrings", ""},
{1, 1, 1, 0, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::capitalize(strings_view, std::string(" \t"));
cudf::test::strings_column_wrapper expected(
{"Sⱥⱥnich Xyz", "Examples Abc", "Thesé", "", "Are\tThe", "Tést\tStrings", ""},
{1, 1, 1, 0, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsCaseTest, Title)
{
cudf::test::strings_column_wrapper input(
{"SȺȺnich", "Examples aBc", "thesé", "", "ARE THE", "tést strings", "", "n2viDIA corp"},
{1, 1, 1, 0, 1, 1, 1, 1});
auto strings_view = cudf::strings_column_view(input);
auto results = cudf::strings::title(strings_view);
cudf::test::strings_column_wrapper expected(
{"Sⱥⱥnich", "Examples Abc", "Thesé", "", "Are The", "Tést Strings", "", "N2Vidia Corp"},
{1, 1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::title(strings_view, cudf::strings::string_character_types::ALPHANUM);
cudf::test::strings_column_wrapper expected2(
{"Sⱥⱥnich", "Examples Abc", "Thesé", "", "Are The", "Tést Strings", "", "N2vidia Corp"},
{1, 1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected2);
}
TEST_F(StringsCaseTest, IsTitle)
{
cudf::test::strings_column_wrapper input({"Sⱥⱥnich",
"Examples Abc",
"Thesé Strings",
"",
"Are The",
"Tést strings",
"",
"N2Vidia Corp",
"SNAKE",
"!Abc",
" Eagle",
"A Test",
"12345",
"Alpha Not Upper Or Lower: ƻC",
"one More"},
{1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
auto results = cudf::strings::is_title(cudf::strings_column_view(input));
cudf::test::fixed_width_column_wrapper<bool> expected(
{1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0}, {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, MultiCharUpper)
{
cudf::test::strings_column_wrapper strings{"\u1f52 \u1f83", "\u1e98 \ufb05", "\u0149"};
cudf::test::strings_column_wrapper expected{
"\u03a5\u0313\u0300 \u1f0b\u0399", "\u0057\u030a \u0053\u0054", "\u02bc\u004e"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_upper(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::capitalize(strings_view, std::string(" "));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::title(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, MultiCharLower)
{
// there's only one of these
cudf::test::strings_column_wrapper strings{"\u0130"};
cudf::test::strings_column_wrapper expected{"\u0069\u0307"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_lower(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCaseTest, Ascii)
{
// triggering the ascii code path requires some long-ish strings
cudf::test::strings_column_wrapper input{
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=-"};
auto view = cudf::strings_column_view(input);
auto expected = cudf::test::strings_column_wrapper{
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=-"};
auto results = cudf::strings::to_lower(view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
expected = cudf::test::strings_column_wrapper{
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-"};
results = cudf::strings::to_upper(view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::to_upper(cudf::strings_column_view(cudf::slice(input, {1, 3}).front()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, cudf::slice(expected, {1, 3}).front());
}
TEST_F(StringsCaseTest, LongStrings)
{
// average string length >= AVG_CHAR_BYTES_THRESHOLD as defined in case.cu
cudf::test::strings_column_wrapper input{
"ABCDÉFGHIJKLMNOPQRSTUVWXYZabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=-"};
auto view = cudf::strings_column_view(input);
auto expected = cudf::test::strings_column_wrapper{
"abcdéfghijklmnopqrstuvwxyzabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdéfghijklmnopqrstuvwxyzabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdéfghijklmnopqrstuvwxyzabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=- ",
"abcdéfghijklmnopqrstuvwxyzabcdéfghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+=-"};
auto results = cudf::strings::to_lower(view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
expected = cudf::test::strings_column_wrapper{
"ABCDÉFGHIJKLMNOPQRSTUVWXYZABCDÉFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZABCDÉFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZABCDÉFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=- ",
"ABCDÉFGHIJKLMNOPQRSTUVWXYZABCDÉFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+=-"};
results = cudf::strings::to_upper(view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::to_upper(cudf::strings_column_view(cudf::slice(input, {1, 3}).front()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, cudf::slice(expected, {1, 3}).front());
}
TEST_F(StringsCaseTest, EmptyStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::to_lower(strings_view);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::to_upper(strings_view);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::swapcase(strings_view);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::capitalize(strings_view);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::title(strings_view);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsCaseTest, ErrorTest)
{
cudf::test::strings_column_wrapper input{"the column intentionally left blank"};
auto view = cudf::strings_column_view(input);
EXPECT_THROW(cudf::strings::capitalize(view, cudf::string_scalar("", false)), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/chars_types_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.hpp>
#include <cudf/strings/char_types/char_types.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 <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsCharsTest : public cudf::test::BaseFixture {};
class CharsTypes : public StringsCharsTest,
public testing::WithParamInterface<cudf::strings::string_character_types> {};
TEST_P(CharsTypes, AllTypes)
{
std::vector<char const*> h_strings{"Héllo",
"thesé",
nullptr,
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
bool expecteds[] = {false, false, false, false, false, false, false, false,
false, false, false, false, false, true, false, false, // decimal
false, false, false, false, false, false, false, false,
false, true, false, true, false, true, false, false, // numeric
false, false, false, false, false, false, false, false,
false, false, false, true, false, true, false, false, // digit
true, true, false, true, false, false, false, false,
false, false, false, false, false, false, true, false, // alpha
false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, true, // space
false, false, false, true, false, false, false, false,
false, false, false, false, false, false, false, false, // upper
false, true, false, false, false, false, false, false,
false, false, false, false, false, false, true, false}; // lower
auto is_parm = GetParam();
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::all_characters_of_type(strings_view, is_parm);
int x = static_cast<int>(is_parm);
int index = 0;
int strings_count = static_cast<int>(h_strings.size());
while (x >>= 1)
++index;
bool* sub_expected = &expecteds[index * strings_count];
cudf::test::fixed_width_column_wrapper<bool> expected(
sub_expected,
sub_expected + strings_count,
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
INSTANTIATE_TEST_CASE_P(StringsCharsTest,
CharsTypes,
testing::ValuesIn(std::array<cudf::strings::string_character_types, 7>{
cudf::strings::string_character_types::DECIMAL,
cudf::strings::string_character_types::NUMERIC,
cudf::strings::string_character_types::DIGIT,
cudf::strings::string_character_types::ALPHA,
cudf::strings::string_character_types::SPACE,
cudf::strings::string_character_types::UPPER,
cudf::strings::string_character_types::LOWER}));
TEST_F(StringsCharsTest, LowerUpper)
{
cudf::test::strings_column_wrapper strings({"a1", "A1", "a!", "A!", "!1", "aA"});
auto strings_view = cudf::strings_column_view(strings);
auto verify_types =
cudf::strings::string_character_types::LOWER | cudf::strings::string_character_types::UPPER;
{
auto results = cudf::strings::all_characters_of_type(
strings_view, cudf::strings::string_character_types::LOWER, verify_types);
cudf::test::fixed_width_column_wrapper<bool> expected({1, 0, 1, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::all_characters_of_type(
strings_view, cudf::strings::string_character_types::UPPER, verify_types);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 1, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsCharsTest, Alphanumeric)
{
std::vector<char const*> h_strings{"Héllo",
"thesé",
nullptr,
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::all_characters_of_type(
strings_view, cudf::strings::string_character_types::ALPHANUM);
std::vector<bool> h_expected{1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCharsTest, AlphaNumericSpace)
{
std::vector<char const*> h_strings{"Héllo",
"thesé",
nullptr,
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
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 strings_view = cudf::strings_column_view(strings);
auto types =
cudf::strings::string_character_types::ALPHANUM | cudf::strings::string_character_types::SPACE;
auto results = cudf::strings::all_characters_of_type(
strings_view, (cudf::strings::string_character_types)types);
std::vector<bool> h_expected{1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCharsTest, Numerics)
{
std::vector<char const*> h_strings{"Héllo",
"thesé",
nullptr,
"HERE",
"tést strings",
"",
"1.75",
"-34",
"+9.8",
"17¼",
"x³",
"2³",
" 12⅝",
"1234567890",
"de",
"\t\r\n\f "};
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 strings_view = cudf::strings_column_view(strings);
auto types = cudf::strings::string_character_types::DIGIT |
cudf::strings::string_character_types::DECIMAL |
cudf::strings::string_character_types::NUMERIC;
auto results = cudf::strings::all_characters_of_type(
strings_view, (cudf::strings::string_character_types)types);
std::vector<bool> h_expected{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCharsTest, EmptyStrings)
{
cudf::test::strings_column_wrapper strings({"", "", ""});
auto strings_view = cudf::strings_column_view(strings);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 0, 0});
auto results = cudf::strings::all_characters_of_type(
strings_view, cudf::strings::string_character_types::ALPHANUM);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsCharsTest, FilterCharTypes)
{
// The example strings are based on issue 5520
cudf::test::strings_column_wrapper strings(
{"abc£def", "01234 56789", "℉℧ is not alphanumeric", "but Αγγλικά is", ""});
auto results =
cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::ALL_TYPES,
cudf::string_scalar(" "),
cudf::strings::string_character_types::ALPHANUM);
{
cudf::test::strings_column_wrapper expected(
{"abc def", "01234 56789", " is not alphanumeric", "but Αγγλικά is", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
results = cudf::strings::filter_characters_of_type(
cudf::strings_column_view(strings), cudf::strings::string_character_types::ALPHANUM);
{
cudf::test::strings_column_wrapper expected({"£", " ", "℉℧ ", " ", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
results = cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::SPACE);
{
cudf::test::strings_column_wrapper expected(
{"abc£def", "0123456789", "℉℧isnotalphanumeric", "butΑγγλικάis", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
results =
cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::ALL_TYPES,
cudf::string_scalar("+"),
cudf::strings::string_character_types::SPACE);
{
cudf::test::strings_column_wrapper expected(
{"+++++++", "+++++ +++++", "++ ++ +++ ++++++++++++", "+++ +++++++ ++", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
results = cudf::strings::filter_characters_of_type(
cudf::strings_column_view(strings), cudf::strings::string_character_types::NUMERIC);
{
cudf::test::strings_column_wrapper expected(
{"abc£def", " ", "℉℧ is not alphanumeric", "but Αγγλικά is", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
results =
cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::ALL_TYPES,
cudf::string_scalar(""),
cudf::strings::string_character_types::NUMERIC);
{
cudf::test::strings_column_wrapper expected({"", "0123456789", "", "", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsCharsTest, FilterCharTypesErrors)
{
cudf::test::strings_column_wrapper strings({"strings left intentionally blank"});
EXPECT_THROW(
cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::ALL_TYPES,
cudf::string_scalar(""),
cudf::strings::string_character_types::ALL_TYPES),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::filter_characters_of_type(cudf::strings_column_view(strings),
cudf::strings::string_character_types::ALPHANUM,
cudf::string_scalar(""),
cudf::strings::string_character_types::NUMERIC),
cudf::logic_error);
}
TEST_F(StringsCharsTest, EmptyStringsColumn)
{
cudf::test::strings_column_wrapper strings;
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::all_characters_of_type(
strings_view, cudf::strings::string_character_types::ALPHANUM);
EXPECT_EQ(cudf::type_id::BOOL8, results->view().type().id());
EXPECT_EQ(0, results->view().size());
results = cudf::strings::filter_characters_of_type(
strings_view, cudf::strings::string_character_types::NUMERIC);
EXPECT_EQ(cudf::type_id::STRING, results->view().type().id());
EXPECT_EQ(0, results->view().size());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/like_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/strings/contains.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>
struct StringsLikeTests : public cudf::test::BaseFixture {};
TEST_F(StringsLikeTests, Basic)
{
cudf::test::strings_column_wrapper input({"abc", "a bc", "ABC", "abcd", " abc", "", "", "áéêú"},
{1, 1, 1, 1, 1, 1, 0, 1});
auto const sv = cudf::strings_column_view(input);
auto const pattern = std::string("abc");
auto const results = cudf::strings::like(sv, pattern);
cudf::test::fixed_width_column_wrapper<bool> expected(
{true, false, false, false, false, false, false, false}, {1, 1, 1, 1, 1, 1, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsLikeTests, Leading)
{
cudf::test::strings_column_wrapper input({"a", "aa", "aaa", "b", "bb", "bba", "", "áéêú"});
auto const sv = cudf::strings_column_view(input);
{
auto const results = cudf::strings::like(sv, std::string("a%"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{true, true, true, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("__a%"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, true, false, false, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("á%"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
}
TEST_F(StringsLikeTests, Trailing)
{
cudf::test::strings_column_wrapper input({"a", "aa", "aaa", "b", "bb", "bba", "", "áéêú"});
auto const sv = cudf::strings_column_view(input);
{
auto results = cudf::strings::like(sv, std::string("%a"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{true, true, true, false, false, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
results = cudf::strings::like(sv, std::string("%a%"));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("%_a"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, true, true, false, false, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("%_êú"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
}
TEST_F(StringsLikeTests, Place)
{
cudf::test::strings_column_wrapper input({"a", "aa", "aaa", "bab", "ab", "aba", "", "éaé"});
auto const sv = cudf::strings_column_view(input);
{
auto const results = cudf::strings::like(sv, std::string("a_"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, true, false, false, true, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("_a_"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, true, true, false, false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("__a"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, true, false, false, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const results = cudf::strings::like(sv, std::string("é_é"));
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
}
TEST_F(StringsLikeTests, Escape)
{
cudf::test::strings_column_wrapper input(
{"10%-20%", "10-20", "10%%-20%", "a_b", "b_a", "___", "", "aéb"});
auto const sv = cudf::strings_column_view(input);
{
auto const pattern = std::string("10\\%-20\\%");
auto const escape = std::string("\\");
auto const results = cudf::strings::like(sv, pattern, escape);
cudf::test::fixed_width_column_wrapper<bool> expected(
{true, false, false, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const pattern = std::string("\\__\\_");
auto const escape = std::string("\\");
auto const results = cudf::strings::like(sv, pattern, escape);
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const pattern = std::string("10%%%%-20%%");
auto const escape = std::string("%");
auto const results = cudf::strings::like(sv, pattern, escape);
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, true, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const pattern = std::string("_%__");
auto const escape = std::string("%");
auto const results = cudf::strings::like(sv, pattern, escape);
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, true, true, true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
{
auto const pattern = std::string("a__b");
auto const escape = std::string("_");
auto const results = cudf::strings::like(sv, pattern, escape);
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, true, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
}
TEST_F(StringsLikeTests, MultiplePatterns)
{
cudf::test::strings_column_wrapper input({"abc", "a1a2b3b4c", "aaabbb", "bbbc", "", "áéêú"});
cudf::test::strings_column_wrapper patterns({"a%b%c", "a%c", "a__b", "b__c", "", "áéêú"});
auto const sv_input = cudf::strings_column_view(input);
auto const sv_patterns = cudf::strings_column_view(patterns);
auto const results = cudf::strings::like(sv_input, sv_patterns);
cudf::test::fixed_width_column_wrapper<bool> expected({true, true, false, true, true, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsLikeTests, Empty)
{
cudf::test::strings_column_wrapper input({"ooo", "20%", ""});
auto sv = cudf::strings_column_view(input);
auto results = cudf::strings::like(sv, std::string(""));
auto expected = cudf::test::fixed_width_column_wrapper<bool>({false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
auto empty = cudf::make_empty_column(cudf::type_id::STRING);
sv = cudf::strings_column_view(empty->view());
results = cudf::strings::like(sv, std::string("20%"));
auto expected_empty = cudf::make_empty_column(cudf::type_id::BOOL8);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected_empty->view());
results = cudf::strings::like(sv, sv);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected_empty->view());
}
TEST_F(StringsLikeTests, Errors)
{
auto const input = cudf::test::strings_column_wrapper({"3", "33"});
auto const sv = cudf::strings_column_view(input);
auto const invalid_str = cudf::string_scalar("", false);
EXPECT_THROW(cudf::strings::like(sv, invalid_str), cudf::logic_error);
EXPECT_THROW(cudf::strings::like(sv, std::string("3"), invalid_str), cudf::logic_error);
auto patterns = cudf::test::strings_column_wrapper({"3", ""}, {1, 0});
auto const sv_patterns = cudf::strings_column_view(patterns);
EXPECT_THROW(cudf::strings::like(sv, sv_patterns), cudf::logic_error);
EXPECT_THROW(cudf::strings::like(sv, sv, invalid_str), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/contains_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/detail/utilities/vector_factories.hpp>
#include <cudf/strings/contains.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/host_vector.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <algorithm>
#include <vector>
struct StringsContainsTests : public cudf::test::BaseFixture {};
TEST_F(StringsContainsTests, ContainsTest)
{
std::vector<char const*> h_strings{"5",
"hej",
"\t \n",
"12345",
"\\",
"d",
"c:\\Tools",
"+27",
"1c2",
"1C2",
"0:00:0",
"0:0:00",
"00:0:0",
"00:00:0",
"00:0:00",
"0:00:00",
"00:00:00",
"Hello world !",
"Hello world! ",
"Hello worldcup !",
"0123456789",
"1C2",
"Xaa",
"abcdefghxxx",
"ABCDEFGH",
"abcdefgh",
"abc def",
"abc\ndef",
"aa\r\nbb\r\ncc\r\n\r\n",
"abcabc",
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; }));
auto strings_view = cudf::strings_column_view(strings);
std::vector<std::string> patterns{"\\d",
"\\w+",
"\\s",
"\\S",
"^.*\\\\.*$",
"[1-5]+",
"[a-h]+",
"[A-H]+",
"[a-h]*",
"\n",
"b.\\s*\n",
".*c",
"\\d\\d:\\d\\d:\\d\\d",
"\\d\\d?:\\d\\d?:\\d\\d?",
"[Hh]ello [Ww]orld",
"\\bworld\\b",
".*"};
std::vector<bool> h_expecteds_std{
// strings.size x patterns.size
true, false, false, true, false, false, false, true, true, true, true, true, true,
true, true, true, true, false, false, false, true, true, false, false, false, false,
false, false, false, false, false, false, true, true, false, true, 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, false, false, false,
false, true, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, true, true, true, false, false, false, false, false, false, true,
true, true, false, false, false, true, true, 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, false, false, false, false,
false, false, true, false, true, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, true, false, false, true, false, false, false, true, true,
true, false, false, false, false, false, false, false, false, false, false, true, true,
false, false, false, false, false, false, false, false, false, false, false, true, false,
false, false, true, true, false, true, false, false, false, false, false, false, false,
false, true, true, true, false, false, true, true, false, true, true, true, true,
true, false, false, false, false, false, false, false, false, false, false, false, true,
false, false, false, false, false, false, false, true, true, true, false, true, false,
false, true, false, false, false, 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, true, true,
false, true, false, false, true, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, true, true, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, true, true, false, false,
false, false, false, false, false, false, false, true, false, true, false, false, false,
false, false, false, false, false, false, false, true, false, false, false, true, false,
true, true, true, true, true, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, true, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, true, true, true,
true, true, true, true, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, true, true, true,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, true, true, false, false, false, false, false, false, false, false,
false, 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, true, true, false, true};
thrust::host_vector<bool> h_expecteds(h_expecteds_std);
for (int idx = 0; idx < static_cast<int>(patterns.size()); ++idx) {
std::string ptn = patterns[idx];
bool* h_expected = h_expecteds.data() + (idx * h_strings.size());
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected,
h_expected + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto prog = cudf::strings::regex_program::create(ptn);
auto results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, MatchesTest)
{
std::vector<char const*> h_strings{
"The quick brown @fox jumps", "ovér the", "lazy @dog", "1234", "00:0:00", 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; }));
auto strings_view = cudf::strings_column_view(strings);
{
auto const pattern = std::string("lazy");
bool h_expected[] = {false, false, true, false, false, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected,
h_expected + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto const pattern = std::string("\\d+");
bool h_expected[] = {false, false, false, true, true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected,
h_expected + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto const pattern = std::string("@\\w+");
bool h_expected[] = {false, false, false, false, false, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected,
h_expected + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto const pattern = std::string(".*");
bool h_expected[] = {true, true, true, true, true, false, true};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected,
h_expected + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, MatchesIPV4Test)
{
cudf::test::strings_column_wrapper strings({"5.79.97.178",
"1.2.3.4",
"5",
"5.79",
"5.79.97",
"5.79.97.178.100",
"224.0.0.0",
"239.255.255.255",
"5.79.97.178",
"127.0.0.1"});
auto strings_view = cudf::strings_column_view(strings);
{ // is_ip: 58 instructions
std::string pattern =
"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
"$";
cudf::test::fixed_width_column_wrapper<bool> expected(
{true, true, false, false, false, false, true, true, true, true});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected);
}
{ // is_loopback: 72 instructions
std::string pattern =
"^127\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))"
"\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))"
"\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$";
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, false, false, false, false, true});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected);
}
{ // is_multicast: 79 instructions
std::string pattern =
"^(2(2[4-9]|3[0-9]))\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))"
"\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))"
"\\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$";
cudf::test::fixed_width_column_wrapper<bool> expected(
{false, false, false, false, false, false, true, true, false, false});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::matches_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected);
}
}
TEST_F(StringsContainsTests, OctalTest)
{
cudf::test::strings_column_wrapper strings({"A3", "B", "CDA3EY", "", "99", "\a\t\r"});
auto strings_view = cudf::strings_column_view(strings);
auto expected = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 1, 0, 0, 0});
auto pattern = std::string("\\101");
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("\\1013");
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("D*\\101\\063");
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("\\719");
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 1, 0});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("[\\7][\\11][\\15]");
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 0, 1});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsContainsTests, HexTest)
{
std::vector<char> ascii_chars( // all possible matchable chars
{thrust::make_counting_iterator<char>(0), thrust::make_counting_iterator<char>(127)});
auto const count = static_cast<cudf::size_type>(ascii_chars.size());
std::vector<cudf::size_type> offsets(
{thrust::make_counting_iterator<cudf::size_type>(0),
thrust::make_counting_iterator<cudf::size_type>(0) + count + 1});
auto d_chars = cudf::detail::make_device_uvector_sync(
ascii_chars, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto d_offsets = cudf::detail::make_device_uvector_sync(
offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto input = cudf::make_strings_column(d_chars, d_offsets, {}, 0);
auto strings_view = cudf::strings_column_view(input->view());
for (auto ch : ascii_chars) {
std::stringstream str;
str << "\\x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<int32_t>(ch);
std::string pattern = str.str();
// only one element in the input should match ch
auto true_dat = cudf::detail::make_counting_transform_iterator(
0, [ch](auto idx) { return ch == static_cast<char>(idx); });
cudf::test::fixed_width_column_wrapper<bool> expected(true_dat, true_dat + count);
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
// also test hex character appearing in character class brackets
pattern = "[" + pattern + "]";
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, EmbeddedNullCharacter)
{
std::vector<std::string> data(10);
std::generate(data.begin(), data.end(), [n = 0]() mutable {
char first = static_cast<char>('A' + n++);
char raw_data[] = {first, '\0', 'B'};
return std::string{raw_data, 3};
});
cudf::test::strings_column_wrapper input(data.begin(), data.end());
auto strings_view = cudf::strings_column_view(input);
auto pattern = std::string("A");
auto expected = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 0, 0, 0, 0, 0, 0, 0, 0});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("B");
expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("J\\0B");
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 0, 0, 0, 0, 0, 1});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("[G-J][\\0]B");
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 0, 0, 1, 1, 1, 1});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
pattern = std::string("[A-D][\\x00]B");
expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 0, 0, 0, 0, 0, 0});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::contains_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsContainsTests, Errors)
{
EXPECT_THROW(cudf::strings::regex_program::create("(3?)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("(?:3?)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("3?+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("{3}a"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("aaaa{1234,5678}"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("aaaa{123,5678}"), cudf::logic_error);
}
TEST_F(StringsContainsTests, CountTest)
{
std::vector<char const*> h_strings{
"The quick brown @fox jumps ovér the", "lazy @dog", "1:2:3:4", "00:0:00", nullptr, ""};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto strings_view = cudf::strings_column_view(strings);
{
auto pattern = std::string("[tT]he");
cudf::test::fixed_width_column_wrapper<int32_t> expected(
{2, 0, 0, 0, 0, 0}, cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto pattern = std::string("@\\w+");
cudf::test::fixed_width_column_wrapper<int32_t> expected(
{1, 1, 0, 0, 0, 0}, cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto pattern = std::string("\\d+:\\d+");
cudf::test::fixed_width_column_wrapper<int32_t> expected(
{0, 0, 2, 1, 0, 0}, cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, FixedQuantifier)
{
auto input = cudf::test::strings_column_wrapper({"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"});
auto sv = cudf::strings_column_view(input);
{
// exact match
auto pattern = std::string("a{3}");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 0, 1, 1, 1, 2});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// range match (greedy quantifier)
auto pattern = std::string("a{3,5}");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 0, 1, 1, 1, 1});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// minimum match (greedy quantifier)
auto pattern = std::string("a{2,}");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 1, 1, 1, 1, 1});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// range match (lazy quantifier)
auto pattern = std::string("a{2,4}?");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 1, 1, 2, 2, 3});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// minimum match (lazy quantifier)
auto pattern = std::string("a{1,}?");
cudf::test::fixed_width_column_wrapper<int32_t> expected({1, 2, 3, 4, 5, 6});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// zero match
auto pattern = std::string("aaaa{0}");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 0, 1, 1, 1, 2});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
// poorly formed
auto pattern = std::string("aaaa{n,m}");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 0, 0, 0, 0, 0});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, QuantifierErrors)
{
EXPECT_THROW(cudf::strings::regex_program::create("^+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("$+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("(^)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("($)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("\\A+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("\\Z+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("(\\A)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("(\\Z)+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("(^($))+"), cudf::logic_error);
EXPECT_NO_THROW(cudf::strings::regex_program::create("(^a($))+"));
EXPECT_NO_THROW(cudf::strings::regex_program::create("(^(a$))+"));
}
TEST_F(StringsContainsTests, OverlappedClasses)
{
auto input = cudf::test::strings_column_wrapper({"abcdefg", "defghí", "", "éééééé", "ghijkl"});
auto sv = cudf::strings_column_view(input);
{
auto pattern = std::string("[e-gb-da-c]");
cudf::test::fixed_width_column_wrapper<int32_t> expected({7, 4, 0, 0, 1});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto pattern = std::string("[á-éê-ú]");
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 1, 0, 6, 0});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, NegatedClasses)
{
auto input = cudf::test::strings_column_wrapper({"abcdefg", "def\tghí", "", "éeé\néeé", "ABC"});
auto sv = cudf::strings_column_view(input);
{
auto pattern = std::string("[^a-f]");
cudf::test::fixed_width_column_wrapper<int32_t> expected({1, 4, 0, 5, 3});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto pattern = std::string("[^a-eá-é]");
cudf::test::fixed_width_column_wrapper<int32_t> expected({2, 5, 0, 1, 3});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::count_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, IncompleteClassesRange)
{
auto input = cudf::test::strings_column_wrapper({"abc-def", "---", "", "ghijkl", "-wxyz-"});
auto sv = cudf::strings_column_view(input);
{
cudf::test::fixed_width_column_wrapper<bool> expected({1, 0, 0, 1, 1});
auto prog = cudf::strings::regex_program::create("[a-z]");
auto results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
prog = cudf::strings::regex_program::create("[a-m-z]"); // same as [a-z]
results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<bool> expected({1, 1, 0, 1, 1});
auto prog = cudf::strings::regex_program::create("[g-]");
auto results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
prog = cudf::strings::regex_program::create("[-k]");
results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<bool> expected({1, 1, 0, 0, 1});
auto prog = cudf::strings::regex_program::create("[-]");
auto results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
prog = cudf::strings::regex_program::create("[+--]");
results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
prog = cudf::strings::regex_program::create("[a-c-]");
results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
prog = cudf::strings::regex_program::create("[-d-f]");
results = cudf::strings::contains_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsContainsTests, MultiLine)
{
auto input = cudf::test::strings_column_wrapper(
{"abé\nfff\nabé", "fff\nabé\nlll", "abé", "", "abé\n", "abe\nabé\n"});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("^abé$");
auto prog = cudf::strings::regex_program::create(pattern);
auto prog_ml =
cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::MULTILINE);
auto expected_contains = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 0, 1, 1});
auto results = cudf::strings::contains_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
expected_contains = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 0, 1, 0});
results = cudf::strings::contains_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
auto expected_matches = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 1, 0, 1, 0});
results = cudf::strings::matches_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_matches);
expected_matches = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 0, 1, 0});
results = cudf::strings::matches_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_matches);
auto expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({2, 1, 1, 0, 1, 1});
results = cudf::strings::count_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 1, 0, 1, 0});
results = cudf::strings::count_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
}
TEST_F(StringsContainsTests, EndOfString)
{
auto input = cudf::test::strings_column_wrapper(
{"abé\nfff\nabé", "fff\nabé\nlll", "abé", "", "abé\n", "abe\nabé\n"});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("\\Aabé\\Z");
auto prog = cudf::strings::regex_program::create(pattern);
auto prog_ml =
cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::MULTILINE);
auto results = cudf::strings::contains_re(view, *prog);
auto expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::contains_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::matches_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::matches_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::count_re(view, *prog);
auto expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 1, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
results = cudf::strings::count_re(view, *prog_ml);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
}
TEST_F(StringsContainsTests, DotAll)
{
auto input = cudf::test::strings_column_wrapper({"abc\nfa\nef", "fff\nabbc\nfff", "abcdef", ""});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("a.*f");
auto prog = cudf::strings::regex_program::create(pattern);
auto prog_dotall =
cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::DOTALL);
auto expected_contains = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 0});
auto results = cudf::strings::contains_re(view, *prog_dotall);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
expected_contains = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 0});
results = cudf::strings::contains_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
auto expected_matches = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 1, 0});
results = cudf::strings::matches_re(view, *prog_dotall);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_matches);
expected_matches = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 0});
results = cudf::strings::matches_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_matches);
pattern = std::string("a.*?f");
prog = cudf::strings::regex_program::create(pattern);
prog_dotall = cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::DOTALL);
auto expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({2, 1, 1, 0});
results = cudf::strings::count_re(view, *prog_dotall);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 1, 0});
results = cudf::strings::count_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
auto both_flags = static_cast<cudf::strings::regex_flags>(cudf::strings::regex_flags::DOTALL |
cudf::strings::regex_flags::MULTILINE);
expected_count = cudf::test::fixed_width_column_wrapper<int32_t>({2, 1, 1, 0});
auto prog_both = cudf::strings::regex_program::create(pattern, both_flags);
results = cudf::strings::count_re(view, *prog_both);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_count);
}
TEST_F(StringsContainsTests, ASCII)
{
auto input = cudf::test::strings_column_wrapper({"abc \t\f\r 12", "áé ❽❽", "aZ ❽4", "XYZ 8"});
auto view = cudf::strings_column_view(input);
std::string patterns[] = {"\\w+[\\s]+\\d+",
"[^\\W]+\\s+[^\\D]+",
"[\\w]+[^\\S]+[\\d]+",
"[\\w]+\\s+[\\d]+",
"\\w+\\s+\\d+"};
for (auto ptn : patterns) {
auto expected_contains = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 0, 0});
auto prog = cudf::strings::regex_program::create(ptn, cudf::strings::regex_flags::ASCII);
auto results = cudf::strings::contains_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
expected_contains = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1});
prog = cudf::strings::regex_program::create(ptn);
results = cudf::strings::contains_re(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_contains);
}
}
TEST_F(StringsContainsTests, MediumRegex)
{
// This results in 95 regex instructions and falls in the 'medium' range.
std::string medium_regex =
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com";
auto prog = cudf::strings::regex_program::create(medium_regex);
std::vector<char const*> h_strings{
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com thats all",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
"5678901234567890",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop"
"qrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::contains_re(strings_view, *prog);
bool h_expected[] = {true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::strings::matches_re(strings_view, *prog);
bool h_expected[] = {true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::strings::count_re(strings_view, *prog);
int32_t h_expected[] = {1, 0, 0};
cudf::test::fixed_width_column_wrapper<int32_t> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
}
TEST_F(StringsContainsTests, LargeRegex)
{
// This results in 115 regex instructions and falls in the 'large' range.
std::string large_regex =
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz";
auto prog = cudf::strings::regex_program::create(large_regex);
std::vector<char const*> h_strings{
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
"5678901234567890",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop"
"qrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::contains_re(strings_view, *prog);
bool h_expected[] = {true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::strings::matches_re(strings_view, *prog);
bool h_expected[] = {true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto results = cudf::strings::count_re(strings_view, *prog);
int32_t h_expected[] = {1, 0, 0};
cudf::test::fixed_width_column_wrapper<int32_t> expected(h_expected,
h_expected + h_strings.size());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
}
TEST_F(StringsContainsTests, ExtraLargeRegex)
{
// This results in 321 regex instructions which is above the 'large' range.
std::string data(320, '0');
cudf::test::strings_column_wrapper strings({data, data, data, data, data, "00"});
auto prog = cudf::strings::regex_program::create(data);
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::contains_re(strings_view, *prog);
cudf::test::fixed_width_column_wrapper<bool> expected({true, true, true, true, true, false});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::matches_re(strings_view, *prog);
cudf::test::fixed_width_column_wrapper<bool> expected({true, true, true, true, true, false});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::count_re(strings_view, *prog);
cudf::test::fixed_width_column_wrapper<int32_t> expected({1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/array_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/copying.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/sorting.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/table/table_view.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsColumnTest : public cudf::test::BaseFixture {};
TEST_F(StringsColumnTest, Sort)
{
// cannot initialize std::string with a nullptr so use "<null>" as a place-holder
cudf::test::strings_column_wrapper h_strings({"eee", "bb", "<null>", "", "aa", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
cudf::test::strings_column_wrapper h_expected({"<null>", "", "aa", "bb", "bbb", "eee", "ééé"},
{0, 1, 1, 1, 1, 1, 1});
auto results =
cudf::sort(cudf::table_view({h_strings}), {cudf::order::ASCENDING}, {cudf::null_order::BEFORE});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), h_expected);
}
TEST_F(StringsColumnTest, SortZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results = cudf::sort(cudf::table_view({zero_size_strings_column}));
cudf::test::expect_column_empty(results->view().column(0));
}
class SliceParmsTest : public StringsColumnTest,
public testing::WithParamInterface<cudf::size_type> {};
TEST_P(SliceParmsTest, Slice)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper input(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
cudf::size_type start = 3;
cudf::size_type end = GetParam();
auto scol = cudf::slice(input, {start, end});
auto results = std::make_unique<cudf::column>(scol.front());
cudf::test::strings_column_wrapper expected(
h_strings.begin() + start,
h_strings.begin() + end,
thrust::make_transform_iterator(h_strings.begin() + start,
[](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_P(SliceParmsTest, SliceAllNulls)
{
std::vector<char const*> h_strings{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
cudf::test::strings_column_wrapper input(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
cudf::size_type start = 3;
cudf::size_type end = GetParam();
auto scol = cudf::slice(input, {start, end});
auto results = std::make_unique<cudf::column>(scol.front());
cudf::test::strings_column_wrapper expected(
h_strings.begin() + start,
h_strings.begin() + end,
thrust::make_transform_iterator(h_strings.begin() + start,
[](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_P(SliceParmsTest, SliceAllEmpty)
{
std::vector<char const*> h_strings{"", "", "", "", "", "", ""};
cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end());
cudf::size_type start = 3;
cudf::size_type end = GetParam();
auto scol = cudf::slice(input, {start, end});
auto results = std::make_unique<cudf::column>(scol.front());
cudf::test::strings_column_wrapper expected(h_strings.begin() + start, h_strings.begin() + end);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
INSTANTIATE_TEST_CASE_P(StringsColumnTest,
SliceParmsTest,
testing::ValuesIn(std::array<cudf::size_type, 3>{5, 6, 7}));
TEST_F(StringsColumnTest, SliceZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto scol = cudf::slice(zero_size_strings_column, {0, 0});
auto results = std::make_unique<cudf::column>(scol.front());
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsColumnTest, Gather)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
cudf::test::fixed_width_column_wrapper<int32_t> gather_map{{4, 1}};
auto results = cudf::gather(cudf::table_view{{strings}}, gather_map)->release();
std::vector<char const*> h_expected{"aa", "bb"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results.front()->view(), expected);
}
TEST_F(StringsColumnTest, GatherZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
cudf::column_view map_view(cudf::data_type{cudf::type_id::INT32}, 0, nullptr, nullptr, 0);
auto results = cudf::gather(cudf::table_view{{zero_size_strings_column}}, map_view)->release();
cudf::test::expect_column_empty(results.front()->view());
}
TEST_F(StringsColumnTest, GatherTooBig)
{
std::vector<int8_t> h_chars(3000000);
cudf::test::fixed_width_column_wrapper<int8_t> chars(h_chars.begin(), h_chars.end());
cudf::test::fixed_width_column_wrapper<cudf::size_type> offsets({0, 3000000});
auto input = cudf::column_view(
cudf::data_type{cudf::type_id::STRING}, 1, nullptr, nullptr, 0, 0, {offsets, chars});
auto map = thrust::constant_iterator<int8_t>(0);
cudf::test::fixed_width_column_wrapper<int8_t> gather_map(map, map + 1000);
EXPECT_THROW(cudf::gather(cudf::table_view{{input}}, gather_map), std::overflow_error);
}
TEST_F(StringsColumnTest, Scatter)
{
cudf::test::strings_column_wrapper target({"eee", "bb", "", "", "aa", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
cudf::test::strings_column_wrapper source({"1", "22"});
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({4, 1});
auto results = cudf::scatter(cudf::table_view({source}), scatter_map, cudf::table_view({target}));
cudf::test::strings_column_wrapper expected({"eee", "22", "", "", "1", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected);
}
TEST_F(StringsColumnTest, ScatterScalar)
{
cudf::test::strings_column_wrapper target({"eee", "bb", "", "", "aa", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({0, 5});
cudf::string_scalar scalar("__");
auto source = std::vector<std::reference_wrapper<const cudf::scalar>>({scalar});
auto results = cudf::scatter(source, scatter_map, cudf::table_view({target}));
cudf::test::strings_column_wrapper expected({"__", "bb", "", "", "aa", "__", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected);
}
TEST_F(StringsColumnTest, ScatterZeroSizeStringsColumn)
{
auto const source = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto const target = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto const scatter_map = cudf::make_empty_column(cudf::type_id::INT8)->view();
auto results = cudf::scatter(cudf::table_view({source}), scatter_map, cudf::table_view({target}));
cudf::test::expect_column_empty(results->view().column(0));
cudf::string_scalar scalar("");
auto scalar_source = std::vector<std::reference_wrapper<const cudf::scalar>>({scalar});
results = cudf::scatter(scalar_source, scatter_map, cudf::table_view({target}));
cudf::test::expect_column_empty(results->view().column(0));
}
TEST_F(StringsColumnTest, OffsetsBeginEnd)
{
cudf::test::strings_column_wrapper input({"eee", "bb", "", "", "aa", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<int32_t> expected({0, 5});
auto scv = cudf::strings_column_view(input);
EXPECT_EQ(std::distance(scv.offsets_begin(), scv.offsets_end()),
static_cast<std::ptrdiff_t>(scv.size() + 1));
scv = cudf::strings_column_view(cudf::slice(input, {1, 5}).front());
EXPECT_EQ(std::distance(scv.offsets_begin(), scv.offsets_end()),
static_cast<std::ptrdiff_t>(scv.size() + 1));
EXPECT_EQ(std::distance(scv.chars_begin(), scv.chars_end()), 16L);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/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_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/slice.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/host_vector.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/sequence.h>
#include <string>
#include <vector>
struct StringsSliceTest : public cudf::test::BaseFixture {};
TEST_F(StringsSliceTest, Substring)
{
std::vector<char const*> h_strings{"Héllo", "thesé", nullptr, "ARE THE", "tést strings", ""};
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_expected({"llo", "esé", nullptr, "E T", "st ", ""});
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto strings_column = static_cast<cudf::strings_column_view>(strings);
auto results = cudf::strings::slice_strings(strings_column, 2, 5);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
class Parameters : public StringsSliceTest, public testing::WithParamInterface<cudf::size_type> {};
TEST_P(Parameters, Substring)
{
std::vector<std::string> h_strings{"basic strings", "that can", "be used", "with STL"};
cudf::size_type start = GetParam();
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_column = cudf::strings_column_view(strings);
auto results = cudf::strings::slice_strings(strings_column, start);
std::vector<std::string> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr)
h_expected.push_back((*itr).substr(start));
cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_P(Parameters, Substring_From)
{
std::vector<std::string> h_strings{"basic strings", "that can", "be used", "with STL"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_column = cudf::strings_column_view(strings);
auto param_index = GetParam();
thrust::host_vector<int32_t> starts(h_strings.size());
thrust::sequence(starts.begin(), starts.end(), param_index);
cudf::test::fixed_width_column_wrapper<int32_t> starts_column(starts.begin(), starts.end());
thrust::host_vector<int32_t> stops(h_strings.size());
thrust::sequence(stops.begin(), stops.end(), param_index + 2);
cudf::test::fixed_width_column_wrapper<int32_t> stops_column(stops.begin(), stops.end());
auto results = cudf::strings::slice_strings(strings_column, starts_column, stops_column);
std::vector<std::string> h_expected;
for (size_t idx = 0; idx < h_strings.size(); ++idx)
h_expected.push_back(h_strings[idx].substr(starts[idx], stops[idx] - starts[idx]));
cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_P(Parameters, SubstringStopZero)
{
cudf::size_type start = GetParam();
cudf::test::strings_column_wrapper input({"abc", "défgh", "", "XYZ"});
auto view = cudf::strings_column_view(input);
auto results = cudf::strings::slice_strings(view, start, 0);
cudf::test::strings_column_wrapper expected({"", "", "", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
auto starts =
cudf::test::fixed_width_column_wrapper<cudf::size_type>({start, start, start, start});
auto stops = cudf::test::fixed_width_column_wrapper<cudf::size_type>({0, 0, 0, 0});
results = cudf::strings::slice_strings(view, starts, stops);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_P(Parameters, AllEmpty)
{
std::vector<std::string> h_strings{"", "", "", ""};
cudf::size_type start = GetParam();
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_column = cudf::strings_column_view(strings);
auto results = cudf::strings::slice_strings(strings_column, start);
std::vector<std::string> h_expected(h_strings);
cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
thrust::host_vector<int32_t> starts(h_strings.size(), 1);
cudf::test::fixed_width_column_wrapper<int32_t> starts_column(starts.begin(), starts.end());
thrust::host_vector<int32_t> stops(h_strings.size(), 2);
cudf::test::fixed_width_column_wrapper<int32_t> stops_column(stops.begin(), stops.end());
results = cudf::strings::slice_strings(strings_column, starts_column, stops_column);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_P(Parameters, AllNulls)
{
std::vector<char const*> h_strings{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 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::size_type start = GetParam();
auto strings_column = cudf::strings_column_view(strings);
auto results = cudf::strings::slice_strings(strings_column, start);
std::vector<char const*> h_expected(h_strings);
cudf::test::strings_column_wrapper expected(
h_strings.begin(),
h_strings.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
thrust::host_vector<int32_t> starts(h_strings.size(), 1);
cudf::test::fixed_width_column_wrapper<int32_t> starts_column(starts.begin(), starts.end());
thrust::host_vector<int32_t> stops(h_strings.size(), 2);
cudf::test::fixed_width_column_wrapper<int32_t> stops_column(stops.begin(), stops.end());
results = cudf::strings::slice_strings(strings_column, starts_column, stops_column);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
INSTANTIATE_TEST_CASE_P(StringsSliceTest,
Parameters,
testing::ValuesIn(std::array<cudf::size_type, 3>{1, 2, 3}));
TEST_F(StringsSliceTest, NegativePositions)
{
cudf::test::strings_column_wrapper strings{
"a", "bc", "def", "ghij", "klmno", "pqrstu", "vwxyz", ""};
auto strings_column = cudf::strings_column_view(strings);
{
auto results = cudf::strings::slice_strings(strings_column, -1);
cudf::test::strings_column_wrapper expected{"a", "c", "f", "j", "o", "u", "z", ""};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(strings_column, 0, -1);
cudf::test::strings_column_wrapper expected{"", "b", "de", "ghi", "klmn", "pqrst", "vwxy", ""};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(strings_column, 7, -2, -1);
cudf::test::strings_column_wrapper expected{"a", "c", "f", "j", "o", "u", "z", ""};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(strings_column, 7, -7, -1);
cudf::test::strings_column_wrapper expected{
"a", "cb", "fed", "jihg", "onmlk", "utsrqp", "zyxwv", ""};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(strings_column, -3, -1);
cudf::test::strings_column_wrapper expected{"", "b", "de", "hi", "mn", "st", "xy", ""};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsSliceTest, NullPositions)
{
cudf::test::strings_column_wrapper strings{"a", "bc", "def", "ghij", "klmno", "pqrstu", "vwxyz"};
auto strings_column = cudf::strings_column_view(strings);
{
auto results = cudf::strings::slice_strings(strings_column,
cudf::numeric_scalar<cudf::size_type>(0, false),
cudf::numeric_scalar<cudf::size_type>(0, false),
-1);
cudf::test::strings_column_wrapper expected{
"a", "cb", "fed", "jihg", "onmlk", "utsrqp", "zyxwv"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(strings_column,
cudf::numeric_scalar<cudf::size_type>(0, false),
cudf::numeric_scalar<cudf::size_type>(0, false),
2);
cudf::test::strings_column_wrapper expected{"a", "b", "df", "gi", "kmo", "prt", "vxz"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(
strings_column, 0, cudf::numeric_scalar<cudf::size_type>(0, false), -1);
cudf::test::strings_column_wrapper expected{"a", "b", "d", "g", "k", "p", "v"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(
strings_column, cudf::numeric_scalar<cudf::size_type>(0, false), -2, -1);
cudf::test::strings_column_wrapper expected{"a", "c", "f", "j", "o", "u", "z"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::slice_strings(
strings_column, cudf::numeric_scalar<cudf::size_type>(0, false), -1, 2);
cudf::test::strings_column_wrapper expected{"", "b", "d", "gi", "km", "prt", "vx"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsSliceTest, MaxPositions)
{
cudf::test::strings_column_wrapper strings{"a", "bc", "def", "ghij", "klmno", "pqrstu", "vwxyz"};
auto strings_column = cudf::strings_column_view(strings);
cudf::test::strings_column_wrapper expected{"", "", "", "", "", "", ""};
auto results = cudf::strings::slice_strings(strings_column, 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(strings_column, 0, -10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(
strings_column, cudf::numeric_scalar<cudf::size_type>(0, false), -10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(strings_column, 10, 19);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(strings_column, 10, 19, 9);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(strings_column, -10, -19);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::slice_strings(strings_column, -10, -19, -1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsSliceTest, Error)
{
cudf::test::strings_column_wrapper strings{"this string intentionally left blank"};
auto strings_view = cudf::strings_column_view(strings);
EXPECT_THROW(cudf::strings::slice_strings(strings_view, 0, 0, 0), cudf::logic_error);
auto indexes = cudf::test::fixed_width_column_wrapper<int32_t>({1, 2});
EXPECT_THROW(cudf::strings::slice_strings(strings_view, indexes, indexes), cudf::logic_error);
auto indexes_null = cudf::test::fixed_width_column_wrapper<int32_t>({1}, {0});
EXPECT_THROW(cudf::strings::slice_strings(strings_view, indexes_null, indexes_null),
cudf::logic_error);
auto indexes_bad = cudf::test::fixed_width_column_wrapper<float>({1});
EXPECT_THROW(cudf::strings::slice_strings(strings_view, indexes_bad, indexes_bad),
cudf::logic_error);
}
TEST_F(StringsSliceTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::slice_strings(strings_view, 1, 2);
cudf::test::expect_column_empty(results->view());
auto const starts_column = cudf::make_empty_column(cudf::type_id::INT32)->view();
auto const stops_column = cudf::make_empty_column(cudf::type_id::INT32)->view();
results = cudf::strings::slice_strings(strings_view, starts_column, stops_column);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsSliceTest, AllEmpty)
{
auto strings_col = cudf::test::strings_column_wrapper({"", "", "", "", ""});
auto strings_view = cudf::strings_column_view(strings_col);
auto exp_results = cudf::column_view(strings_col);
auto results = cudf::strings::slice_strings(strings_view, 0, -1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results);
results = cudf::strings::slice_strings(strings_view, 0, -1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/pad_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/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/strings/padding.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/strings/wrap.hpp>
#include <cudf/utilities/error.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsPadTest : public cudf::test::BaseFixture {};
TEST_F(StringsPadTest, Padding)
{
std::vector<char const*> h_strings{"eee ddd", "bb cc", nullptr, "", "aa", "bbb", "ééé", "o"};
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::size_type width = 6;
std::string phil = "+";
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::pad(strings_view, width, cudf::strings::side_type::RIGHT, phil);
std::vector<char const*> h_expected{
"eee ddd", "bb cc+", nullptr, "++++++", "aa++++", "bbb+++", "ééé+++", "o+++++"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::pad(strings_view, width, cudf::strings::side_type::LEFT, phil);
std::vector<char const*> h_expected{
"eee ddd", "+bb cc", nullptr, "++++++", "++++aa", "+++bbb", "+++ééé", "+++++o"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::pad(strings_view, width, cudf::strings::side_type::BOTH, phil);
std::vector<char const*> h_expected{
"eee ddd", "bb cc+", nullptr, "++++++", "++aa++", "+bbb++", "+ééé++", "++o+++"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsPadTest, PaddingBoth)
{
cudf::test::strings_column_wrapper strings({"koala", "foxx", "fox", "chameleon"});
std::string phil = "+";
auto strings_view = cudf::strings_column_view(strings);
{ // even width left justify
auto results = cudf::strings::pad(strings_view, 6, cudf::strings::side_type::BOTH, phil);
cudf::test::strings_column_wrapper expected({"koala+", "+foxx+", "+fox++", "chameleon"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{ // odd width right justify
auto results = cudf::strings::pad(strings_view, 7, cudf::strings::side_type::BOTH, phil);
cudf::test::strings_column_wrapper expected({"+koala+", "++foxx+", "++fox++", "chameleon"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsPadTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::pad(strings_view, 5);
cudf::test::expect_column_empty(results->view());
}
class PadParameters : public StringsPadTest, public testing::WithParamInterface<cudf::size_type> {};
TEST_P(PadParameters, Padding)
{
std::vector<std::string> h_strings{"eee ddd", "bb cc", "aa", "bbb", "fff", "", "o"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
cudf::size_type width = GetParam();
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::pad(strings_view, width, cudf::strings::side_type::RIGHT);
std::vector<std::string> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr) {
std::string str = *itr;
cudf::size_type size = str.size();
if (size < width) str.insert(size, width - size, ' ');
h_expected.push_back(str);
}
cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
INSTANTIATE_TEST_CASE_P(StringsPadTest,
PadParameters,
testing::ValuesIn(std::array<cudf::size_type, 3>{5, 6, 7}));
TEST_F(StringsPadTest, ZFill)
{
std::vector<char const*> h_strings{
"654321", "-12345", nullptr, "", "-5", "0987", "4", "+8.5", "éé", "+abé", "é+a", "100-"};
cudf::test::strings_column_wrapper input(
h_strings.begin(),
h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(input);
auto results = cudf::strings::zfill(strings_view, 6);
std::vector<char const*> h_expected{"654321",
"-12345",
nullptr,
"000000",
"-00005",
"000987",
"000004",
"+008.5",
"0000éé",
"+00abé",
"000é+a",
"00100-"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsPadTest, Wrap1)
{
std::vector<char const*> h_strings{"12345", "thesé", nullptr, "ARE THE", "tést strings", ""};
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::size_type width = 3;
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::wrap(strings_view, width);
std::vector<char const*> h_expected{"12345", "thesé", nullptr, "ARE\nTHE", "tést\nstrings", ""};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsPadTest, Wrap2)
{
std::vector<char const*> h_strings{"the quick brown fox jumped over the lazy brown dog",
"hello, world"};
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::size_type width = 12;
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::wrap(strings_view, width);
std::vector<char const*> h_expected{"the quick\nbrown fox\njumped over\nthe lazy\nbrown dog",
"hello, world"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsPadTest, WrapExpectFailure)
{
std::vector<char const*> h_strings{"12345", "thesé", nullptr, "ARE THE", "tést strings", ""};
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::size_type width = 0; // this should trigger failure
auto strings_view = cudf::strings_column_view(strings);
EXPECT_THROW(cudf::strings::wrap(strings_view, width), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/booleans_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/strings/convert/convert_booleans.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsConvertTest : public cudf::test::BaseFixture {};
TEST_F(StringsConvertTest, ToBooleans)
{
std::vector<char const*> h_strings{"false", nullptr, "", "true", "True", "False"};
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 strings_view = cudf::strings_column_view(strings);
auto true_scalar = cudf::string_scalar("true");
auto results = cudf::strings::to_booleans(strings_view, true_scalar);
std::vector<bool> h_expected{false, false, false, true, false, false};
cudf::test::fixed_width_column_wrapper<bool> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, FromBooleans)
{
std::vector<char const*> h_strings{"true", nullptr, "false", "true", "true", "false"};
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<bool> h_column{true, false, false, true, true, false};
cudf::test::fixed_width_column_wrapper<bool> column(
h_column.begin(),
h_column.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto true_scalar = cudf::string_scalar("true");
auto false_scalar = cudf::string_scalar("false");
auto results = cudf::strings::from_booleans(column, true_scalar, false_scalar);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, strings);
}
TEST_F(StringsConvertTest, ZeroSizeStringsColumnBoolean)
{
auto const zero_size_column = cudf::make_empty_column(cudf::type_id::BOOL8)->view();
auto true_scalar = cudf::string_scalar("true");
auto false_scalar = cudf::string_scalar("false");
auto results = cudf::strings::from_booleans(zero_size_column, true_scalar, false_scalar);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConvertTest, ZeroSizeBooleansColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto true_scalar = cudf::string_scalar("true");
auto results = cudf::strings::to_booleans(zero_size_strings_column, true_scalar);
EXPECT_EQ(0, results->size());
}
TEST_F(StringsConvertTest, BooleanError)
{
auto int_column = cudf::test::fixed_width_column_wrapper<int32_t>({1, 2, 3});
auto true_scalar = cudf::string_scalar("true");
auto false_scalar = cudf::string_scalar("false");
EXPECT_THROW(cudf::strings::from_booleans(int_column, true_scalar, false_scalar),
cudf::logic_error);
auto bool_column = cudf::test::fixed_width_column_wrapper<bool>({1, 0, 1});
auto null_scalar = cudf::string_scalar("", false);
EXPECT_THROW(cudf::strings::from_booleans(bool_column, null_scalar, false_scalar),
cudf::logic_error);
EXPECT_THROW(cudf::strings::from_booleans(bool_column, true_scalar, null_scalar),
cudf::logic_error);
auto empty_scalar = cudf::string_scalar("", true);
EXPECT_THROW(cudf::strings::from_booleans(int_column, empty_scalar, false_scalar),
cudf::logic_error);
EXPECT_THROW(cudf::strings::from_booleans(int_column, true_scalar, empty_scalar),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/translate_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/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/strings/translate.hpp>
#include <cudf/utilities/error.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsTranslateTest : public cudf::test::BaseFixture {};
std::pair<cudf::char_utf8, cudf::char_utf8> make_entry(char const* from, char const* to)
{
cudf::char_utf8 in = 0;
cudf::char_utf8 out = 0;
cudf::strings::detail::to_char_utf8(from, in);
if (to) cudf::strings::detail::to_char_utf8(to, out);
return std::pair(in, out);
}
TEST_F(StringsTranslateTest, Translate)
{
std::vector<char const*> h_strings{"eee ddd", "bb cc", nullptr, "", "aa", "débd"};
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 strings_view = cudf::strings_column_view(strings);
std::vector<std::pair<cudf::char_utf8, cudf::char_utf8>> translate_table{
make_entry("b", 0), make_entry("a", "A"), make_entry("é", "E"), make_entry("e", "_")};
auto results = cudf::strings::translate(strings_view, translate_table);
std::vector<char const*> h_expected{"___ ddd", " cc", nullptr, "", "AA", "dEd"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsTranslateTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
std::vector<std::pair<cudf::char_utf8, cudf::char_utf8>> translate_table;
auto results = cudf::strings::translate(strings_view, translate_table);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::filter_characters(strings_view, translate_table);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsTranslateTest, FilterCharacters)
{
std::vector<char const*> h_strings{"eee ddd", "bb cc", nullptr, "", "12309", "débd"};
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);
auto strings_view = cudf::strings_column_view(strings);
std::vector<std::pair<cudf::char_utf8, cudf::char_utf8>> filter_table{
make_entry("a", "c"), make_entry("é", "ú"), make_entry("0", "9")};
{
auto results = cudf::strings::filter_characters(strings_view, filter_table);
cudf::test::strings_column_wrapper expected({"", "bbcc", "", "", "12309", "éb"}, validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::filter_characters(
strings_view, filter_table, cudf::strings::filter_type::REMOVE);
cudf::test::strings_column_wrapper expected({"eee ddd", " ", "", "", "", "dd"}, validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::filter_characters(
strings_view, filter_table, cudf::strings::filter_type::KEEP, cudf::string_scalar("_"));
cudf::test::strings_column_wrapper expected({"_______", "bb_cc", "", "", "12309", "_éb_"},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::filter_characters(
strings_view, filter_table, cudf::strings::filter_type::REMOVE, cudf::string_scalar("++"));
cudf::test::strings_column_wrapper expected(
{"eee ddd", "++++ ++++", "", "", "++++++++++", "d++++d"}, validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsTranslateTest, ErrorTest)
{
cudf::test::strings_column_wrapper h_strings({"string left intentionally blank"});
auto strings_view = cudf::strings_column_view(h_strings);
std::vector<std::pair<cudf::char_utf8, cudf::char_utf8>> filter_table;
EXPECT_THROW(
cudf::strings::filter_characters(
strings_view, filter_table, cudf::strings::filter_type::KEEP, cudf::string_scalar("", false)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/replace_regex_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/strings/regex/regex_program.hpp>
#include <cudf/strings/replace_re.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsReplaceRegexTest : public cudf::test::BaseFixture {};
TEST_F(StringsReplaceRegexTest, ReplaceRegexTest)
{
std::vector<char const*> h_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"thé result does not include the value in the sum in",
"",
nullptr};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto strings_view = cudf::strings_column_view(strings);
std::vector<char const*> h_expected{"= quick brown fox jumps over = lazy dog",
"= fat cat lays next to = other accénted cat",
"a slow moving turtlé cannot catch = bird",
"which can be composéd together to form a more complete",
"thé result does not include = value in = sum in",
"",
nullptr};
auto pattern = std::string("(\\bthe\\b)");
auto repl = cudf::string_scalar("=");
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_re(strings_view, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceMultiRegexTest)
{
std::vector<char const*> h_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"thé result does not include the value in the sum in",
"",
nullptr};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto strings_view = cudf::strings_column_view(strings);
std::vector<char const*> h_expected{" quick brown fox jumps over lazy dog",
" fat cat lays next to other accénted cat",
"** slow moving turtlé cannot catch bird",
"which can be composéd together to form ** more complete",
"thé result does not include value N sum N",
"",
nullptr};
std::vector<std::string> patterns{"\\bthe\\b", "\\bin\\b", "\\ba\\b"};
std::vector<std::string> h_repls{"", "N", "**"};
cudf::test::strings_column_wrapper repls(h_repls.begin(), h_repls.end());
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace_re(strings_view, patterns, repls_view);
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, InvalidRegex)
{
// these are quantifiers that do not have a preceding character/class
EXPECT_THROW(cudf::strings::regex_program::create("*"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("|"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("+"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("ab(*)"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("\\"), cudf::logic_error);
EXPECT_THROW(cudf::strings::regex_program::create("\\p"), cudf::logic_error);
}
TEST_F(StringsReplaceRegexTest, WithEmptyPattern)
{
std::vector<char const*> h_strings{"asd", "xcv"};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto strings_view = cudf::strings_column_view(strings);
auto empty_pattern = std::string("");
auto repl = cudf::string_scalar("bbb");
std::vector<std::string> patterns({empty_pattern});
cudf::test::strings_column_wrapper repls({"bbb"});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace_re(strings_view, patterns, repls_view);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, strings);
auto prog = cudf::strings::regex_program::create(empty_pattern);
results = cudf::strings::replace_re(strings_view, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, strings);
}
TEST_F(StringsReplaceRegexTest, MultiReplacement)
{
cudf::test::strings_column_wrapper input({"aba bcd aba", "abababa abababa"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("aba");
auto repl = cudf::string_scalar("_");
cudf::test::strings_column_wrapper expected({"_ bcd _", "_b_ abababa"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_re(sv, *prog, repl, 2);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::replace_re(sv, *prog, repl, 0);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, input);
}
TEST_F(StringsReplaceRegexTest, WordBoundary)
{
cudf::test::strings_column_wrapper input({"aba bcd\naba", "zéz", "A1B2-é3", "e é", "_", "a_b"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("\\b");
auto repl = cudf::string_scalar("X");
auto expected = cudf::test::strings_column_wrapper(
{"XabaX XbcdX\nXabaX", "XzézX", "XA1B2X-Xé3X", "XeX XéX", "X_X", "Xa_bX"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
pattern = std::string("\\B");
expected = cudf::test::strings_column_wrapper(
{"aXbXa bXcXd\naXbXa", "zXéXz", "AX1XBX2-éX3", "e é", "_", "aX_Xb"});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, Alternation)
{
cudf::test::strings_column_wrapper input(
{"16 6 brr 232323 1 hello 90", "123 ABC 00 2022", "abé123 4567 89xyz"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("(^|\\s)\\d+(\\s|$)");
auto repl = cudf::string_scalar("_");
auto expected =
cudf::test::strings_column_wrapper({"__ brr __ hello _", "_ABC_2022", "abé123 _ 89xyz"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
pattern = std::string("(\\s|^)\\d+($|\\s)");
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ZeroLengthMatch)
{
cudf::test::strings_column_wrapper input({"DD", "zéz", "DsDs", ""});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("D*");
auto repl = cudf::string_scalar("_");
auto expected = cudf::test::strings_column_wrapper({"__", "_z_é_z_", "__s__s_", "_"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
pattern = std::string("D?s?");
expected = cudf::test::strings_column_wrapper({"___", "_z_é_z_", "___", "_"});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, Multiline)
{
auto const multiline = cudf::strings::regex_flags::MULTILINE;
cudf::test::strings_column_wrapper input({"bcd\naba\nefg", "aba\naba abab\naba", "aba"});
auto sv = cudf::strings_column_view(input);
// single-replace
auto pattern = std::string("^aba$");
auto repl = cudf::string_scalar("_");
cudf::test::strings_column_wrapper expected_ml({"bcd\n_\nefg", "_\naba abab\n_", "_"});
auto prog = cudf::strings::regex_program::create(pattern, multiline);
auto results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_ml);
cudf::test::strings_column_wrapper expected({"bcd\naba\nefg", "aba\naba abab\naba", "_"});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_re(sv, *prog, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
// multi-replace
std::vector<std::string> patterns({"aba$", "^aba"});
cudf::test::strings_column_wrapper repls({">", "<"});
results = cudf::strings::replace_re(sv, patterns, cudf::strings_column_view(repls), multiline);
cudf::test::strings_column_wrapper multi_expected_ml({"bcd\n>\nefg", ">\n< abab\n>", ">"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, multi_expected_ml);
results = cudf::strings::replace_re(sv, patterns, cudf::strings_column_view(repls));
cudf::test::strings_column_wrapper multi_expected({"bcd\naba\nefg", "<\naba abab\n>", ">"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, multi_expected);
// backref-replace
auto repl_template = std::string("[\\1]");
pattern = std::string("(^aba)");
cudf::test::strings_column_wrapper br_expected_ml(
{"bcd\n[aba]\nefg", "[aba]\n[aba] abab\n[aba]", "[aba]"});
prog = cudf::strings::regex_program::create(pattern, multiline);
results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, br_expected_ml);
cudf::test::strings_column_wrapper br_expected(
{"bcd\naba\nefg", "[aba]\naba abab\naba", "[aba]"});
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, br_expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsRegexTest)
{
std::vector<char const*> h_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"thé result does not include the value in the sum in",
"",
nullptr};
cudf::test::strings_column_wrapper strings(
h_strings.begin(), h_strings.end(), cudf::test::iterators::nulls_from_nullptrs(h_strings));
auto sv = cudf::strings_column_view(strings);
std::vector<char const*> h_expected{"the-quick-brown-fox-jumps-over-the-lazy-dog",
"the-fat-cat-lays-next-to-the-other-accénted-cat",
"a-slow-moving-turtlé-cannot-catch-the-bird",
"which-can-be-composéd-together-to-form-a more-complete",
"thé-result-does-not-include-the-value-in-the-sum-in",
"",
nullptr};
auto pattern = std::string("(\\w) (\\w)");
auto repl_template = std::string("\\1-\\2");
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsRegexAltIndexPatternTest)
{
cudf::test::strings_column_wrapper input({"12-3 34-5 67-89", "0-99: 777-888:: 5673-0"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("(\\d+)-(\\d+)");
auto repl_template = std::string("${2} X ${1}0");
cudf::test::strings_column_wrapper expected(
{"3 X 120 5 X 340 89 X 670", "99 X 00: 888 X 7770:: 0 X 56730"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsRegexReversedTest)
{
cudf::test::strings_column_wrapper strings(
{"A543", "Z756", "", "tést-string", "two-thréé four-fivé", "abcd-éfgh", "tést-string-again"});
auto sv = cudf::strings_column_view(strings);
auto pattern = std::string("([a-z])-([a-zé])");
auto repl_template = std::string("X\\2+\\1Z");
cudf::test::strings_column_wrapper expected({"A543",
"Z756",
"",
"tésXs+tZtring",
"twXt+oZhréé fouXf+rZivé",
"abcXé+dZfgh",
"tésXs+tZtrinXa+gZgain"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, BackrefWithGreedyQuantifier)
{
cudf::test::strings_column_wrapper input(
{"<h1>title</h1><h2>ABC</h2>", "<h1>1234567</h1><h2>XYZ</h2>"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("<h1>(.*)</h1><h2>(.*)</h2>");
auto repl_template = std::string("<h2>\\1</h2><p>\\2</p>");
cudf::test::strings_column_wrapper expected(
{"<h2>title</h2><p>ABC</p>", "<h2>1234567</h2><p>XYZ</p>"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
pattern = std::string("<h1>([a-z\\d]+)</h1><h2>([A-Z]+)</h2>");
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsRegexZeroIndexTest)
{
cudf::test::strings_column_wrapper strings(
{"TEST123", "TEST1TEST2", "TEST2-TEST1122", "TEST1-TEST-T", "TES3"});
auto sv = cudf::strings_column_view(strings);
auto pattern = std::string("(TEST)(\\d+)");
auto repl_template = std::string("${0}: ${1}, ${2}; ");
cudf::test::strings_column_wrapper expected({
"TEST123: TEST, 123; ",
"TEST1: TEST, 1; TEST2: TEST, 2; ",
"TEST2: TEST, 2; -TEST1122: TEST, 1122; ",
"TEST1: TEST, 1; -TEST-T",
"TES3",
});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
// https://github.com/rapidsai/cudf/issues/13404
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsWithEmptyCapture)
{
cudf::test::strings_column_wrapper input({"one\ntwo", "three\n\n", "four\r\n"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("(\r\n|\r)?$");
auto repl_template = std::string("[\\1]");
cudf::test::strings_column_wrapper expected({"one\ntwo[]", "three\n[]\n[]", "four[\r\n][]"});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::replace_with_backrefs(sv, *prog, repl_template);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsReplaceRegexTest, ReplaceBackrefsRegexErrorTest)
{
cudf::test::strings_column_wrapper strings({"this string left intentionally blank"});
auto view = cudf::strings_column_view(strings);
// group index(3) exceeds the group count(2)
auto prog = cudf::strings::regex_program::create("(\\w).(\\w)");
EXPECT_THROW(cudf::strings::replace_with_backrefs(view, *prog, "\\3"), cudf::logic_error);
prog = cudf::strings::regex_program::create("");
EXPECT_THROW(cudf::strings::replace_with_backrefs(view, *prog, "\\1"), cudf::logic_error);
prog = cudf::strings::regex_program::create("(\\w)");
EXPECT_THROW(cudf::strings::replace_with_backrefs(view, *prog, ""), cudf::logic_error);
}
TEST_F(StringsReplaceRegexTest, MediumReplaceRegex)
{
// This results in 95 regex instructions and falls in the 'medium' range.
std::string medium_regex =
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com";
auto prog = cudf::strings::regex_program::create(medium_regex);
std::vector<char const*> h_strings{
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com thats all",
"12345678901234567890",
"abcdefghijklmnopqrstuvwxyz"};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::replace_re(strings_view, *prog);
std::vector<char const*> h_expected{
" thats all", "12345678901234567890", "abcdefghijklmnopqrstuvwxyz"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceRegexTest, LargeReplaceRegex)
{
// This results in 117 regex instructions and falls in the 'large' range.
std::string large_regex =
"hello @abc @def world The (quick) brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz";
auto prog = cudf::strings::regex_program::create(large_regex);
std::vector<char const*> h_strings{
"zzzz hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz",
"12345678901234567890",
"abcdefghijklmnopqrstuvwxyz"};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::replace_re(strings_view, *prog);
std::vector<char const*> h_expected{
"zzzz ", "12345678901234567890", "abcdefghijklmnopqrstuvwxyz"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/find_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.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/attributes.hpp>
#include <cudf/strings/find.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 <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsFindTest : public cudf::test::BaseFixture {};
TEST_F(StringsFindTest, Find)
{
cudf::test::strings_column_wrapper strings({"Héllo", "thesé", "", "lest", "tést strings", ""},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
{
auto const target = cudf::string_scalar("é");
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({1, 4, -1, -1, 1, -1},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, target);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::rfind(strings_view, target);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({3, -1, -1, 0, -1, -1},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::rfind(strings_view, cudf::string_scalar("l"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto const target = cudf::string_scalar("es");
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({-1, 2, -1, 1, -1, -1},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, target);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::rfind(strings_view, target);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({0, 0, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({5, 5, 0, 4, 12, 0},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::rfind(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto const targets = cudf::test::strings_column_wrapper({"l", "t", "", "x", "é", "o"});
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({2, 0, 0, -1, 1, -1},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, cudf::strings_column_view(targets));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({0, 0, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsFindTest, FindWithNullTargets)
{
cudf::test::strings_column_wrapper input({"hello hello", "thesé help", "", "helicopter", "", "x"},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(input);
auto const targets = cudf::test::strings_column_wrapper(
{"lo he", "", "hhh", "cop", "help", "xyz"}, {1, 0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({3, -1, -1, 4, -1, -1},
{1, 0, 0, 1, 1, 1});
auto results = cudf::strings::find(strings_view, cudf::strings_column_view(targets));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFindTest, FindLongStrings)
{
cudf::test::strings_column_wrapper input(
{"Héllo, there world and goodbye",
"quick brown fox jumped over the lazy brown dog; the fat cats jump in place without moving",
"the following code snippet demonstrates how to use search for values in an ordered range",
"it returns the last position where value could be inserted without violating the ordering",
"algorithms execution is parallelized as determined by an execution policy. t",
"he this is a continuation of previous row to make sure string boundaries are honored",
""});
auto view = cudf::strings_column_view(input);
auto results = cudf::strings::find(view, cudf::string_scalar("the"));
auto expected =
cudf::test::fixed_width_column_wrapper<cudf::size_type>({7, 28, 0, 11, -1, -1, -1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
auto targets =
cudf::test::strings_column_wrapper({"the", "the", "the", "the", "the", "the", "the"});
results = cudf::strings::find(view, cudf::strings_column_view(targets));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::rfind(view, cudf::string_scalar("the"));
expected = cudf::test::fixed_width_column_wrapper<cudf::size_type>({7, 48, 0, 77, -1, -1, -1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
targets = cudf::test::strings_column_wrapper({"there", "cat", "the", "", "the", "are", "dog"});
results = cudf::strings::find(view, cudf::strings_column_view(targets));
expected = cudf::test::fixed_width_column_wrapper<cudf::size_type>({7, 56, 0, 0, -1, 73, -1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsFindTest, Contains)
{
cudf::test::strings_column_wrapper strings({"Héllo", "thesé", "", "lease", "tést strings", ""},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
{
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 1, 0, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::contains(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::strings_column_wrapper targets({"Hello", "é", "e", "x", "", ""},
{1, 1, 1, 1, 1, 0});
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 1, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::contains(strings_view, cudf::strings_column_view(targets));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsFindTest, ContainsLongStrings)
{
cudf::test::strings_column_wrapper strings(
{"Héllo, there world and goodbye",
"quick brown fox jumped over the lazy brown dog; the fat cats jump in place without moving",
"the following code snippet demonstrates how to use search for values in an ordered range",
"it returns the last position where value could be inserted without violating the ordering",
"algorithms execution is parallelized as determined by an execution policy. t",
"he this is a continuation of previous row to make sure string boundaries are honored",
""});
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::contains(strings_view, cudf::string_scalar("e"));
cudf::test::fixed_width_column_wrapper<bool> expected({1, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::contains(strings_view, cudf::string_scalar(" the "));
cudf::test::fixed_width_column_wrapper<bool> expected2({0, 1, 0, 1, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected2);
}
TEST_F(StringsFindTest, StartsWith)
{
cudf::test::strings_column_wrapper strings({"Héllo", "thesé", "", "lease", "tést strings", ""},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
{
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 1, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::starts_with(strings_view, cudf::string_scalar("t"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_targets{"éa", "th", "e", "ll", "tést strings", ""};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 1, 1}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::starts_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::starts_with(strings_view, cudf::string_scalar("thesé"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_targets{"éa", "th", "e", "ll", nullptr, ""};
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 targets_view = cudf::strings_column_view(targets);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::starts_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsFindTest, EndsWith)
{
cudf::test::strings_column_wrapper strings({"Héllo", "thesé", "", "lease", "tést strings", ""},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
{
cudf::test::fixed_width_column_wrapper<bool> expected({0, 0, 0, 1, 0, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::ends_with(strings_view, cudf::string_scalar("se"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_targets{"éa", "sé", "th", "ll", "tést strings", ""};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 1, 1}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::ends_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::ends_with(strings_view, cudf::string_scalar("thesé"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_targets{"éa", "sé", "th", nullptr, "tést strings", ""};
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 targets_view = cudf::strings_column_view(targets);
cudf::test::fixed_width_column_wrapper<bool> expected({0, 1, 0, 0, 1, 1}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::ends_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsFindTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::find(strings_view, cudf::string_scalar("é"));
EXPECT_EQ(results->size(), 0);
results = cudf::strings::rfind(strings_view, cudf::string_scalar("é"));
EXPECT_EQ(results->size(), 0);
results = cudf::strings::contains(strings_view, cudf::string_scalar("é"));
EXPECT_EQ(results->size(), 0);
results = cudf::strings::starts_with(strings_view, cudf::string_scalar("é"));
EXPECT_EQ(results->size(), 0);
results = cudf::strings::ends_with(strings_view, cudf::string_scalar("é"));
EXPECT_EQ(results->size(), 0);
results = cudf::strings::starts_with(strings_view, strings_view);
EXPECT_EQ(results->size(), 0);
results = cudf::strings::ends_with(strings_view, strings_view);
EXPECT_EQ(results->size(), 0);
}
TEST_F(StringsFindTest, EmptyTarget)
{
cudf::test::strings_column_wrapper strings({"Héllo", "thesé", "", "lease", "tést strings", ""},
{1, 1, 0, 1, 1, 1});
auto strings_view = cudf::strings_column_view(strings);
cudf::test::fixed_width_column_wrapper<bool> expected({1, 1, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 1});
auto results = cudf::strings::contains(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::starts_with(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::ends_with(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_find({0, 0, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 1});
results = cudf::strings::find(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_find);
auto expected_rfind = cudf::strings::count_characters(strings_view);
results = cudf::strings::rfind(strings_view, cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, *expected_rfind);
}
TEST_F(StringsFindTest, AllEmpty)
{
std::vector<std::string> h_strings{"", "", "", "", ""};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
std::vector<cudf::size_type> h_expected32(h_strings.size(), -1);
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected32(h_expected32.begin(),
h_expected32.end());
std::vector<bool> h_expected8(h_strings.size(), 0);
cudf::test::fixed_width_column_wrapper<bool> expected8(h_expected8.begin(), h_expected8.end());
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::find(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected32);
results = cudf::strings::rfind(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected32);
results = cudf::strings::contains(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::starts_with(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::ends_with(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
std::vector<std::string> h_targets{"abc", "e", "fdg", "g", "p"};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
results = cudf::strings::starts_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::ends_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
}
TEST_F(StringsFindTest, AllNull)
{
std::vector<char const*> h_strings{nullptr, nullptr, nullptr, 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; }));
std::vector<cudf::size_type> h_expected32(h_strings.size(), -1);
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected32(
h_expected32.begin(),
h_expected32.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
std::vector<bool> h_expected8(h_strings.size(), -1);
cudf::test::fixed_width_column_wrapper<bool> expected8(
h_expected8.begin(),
h_expected8.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::find(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected32);
results = cudf::strings::rfind(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected32);
results = cudf::strings::contains(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::starts_with(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::ends_with(strings_view, cudf::string_scalar("e"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
std::vector<std::string> h_targets{"abc", "e", "fdg", "p"};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
results = cudf::strings::starts_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
results = cudf::strings::ends_with(strings_view, targets_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected8);
}
TEST_F(StringsFindTest, ErrorCheck)
{
cudf::test::strings_column_wrapper strings({"1", "2", "3", "4", "5", "6"});
auto strings_view = cudf::strings_column_view(strings);
cudf::test::strings_column_wrapper targets({"1", "2", "3", "4", "5"});
auto targets_view = cudf::strings_column_view(targets);
EXPECT_THROW(cudf::strings::contains(strings_view, targets_view), cudf::logic_error);
EXPECT_THROW(cudf::strings::starts_with(strings_view, targets_view), cudf::logic_error);
EXPECT_THROW(cudf::strings::ends_with(strings_view, targets_view), cudf::logic_error);
EXPECT_THROW(cudf::strings::find(strings_view, cudf::string_scalar(""), 2, 1), cudf::logic_error);
EXPECT_THROW(cudf::strings::rfind(strings_view, cudf::string_scalar(""), 2, 1),
cudf::logic_error);
EXPECT_THROW(cudf::strings::find(strings_view, targets_view), cudf::logic_error);
EXPECT_THROW(cudf::strings::find(strings_view, strings_view, -1), cudf::logic_error);
}
class FindParmsTest : public StringsFindTest,
public testing::WithParamInterface<cudf::size_type> {};
TEST_P(FindParmsTest, Find)
{
std::vector<std::string> h_strings{"hello", "", "these", "are stl", "safe"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
cudf::size_type position = GetParam();
auto strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::find(strings_view, cudf::string_scalar("e"), position);
std::vector<cudf::size_type> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr)
h_expected.push_back(static_cast<cudf::size_type>((*itr).find("e", position)));
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected(h_expected.begin(),
h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::rfind(strings_view, cudf::string_scalar("e"), 0, position + 1);
std::vector<cudf::size_type> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr)
h_expected.push_back(static_cast<cudf::size_type>((*itr).rfind("e", position)));
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected(h_expected.begin(),
h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto begin = static_cast<cudf::size_type>(position);
auto results = cudf::strings::find(strings_view, cudf::string_scalar(""), begin);
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected(
{begin, (begin > 0 ? -1 : 0), begin, begin, begin});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
auto end = static_cast<cudf::size_type>(position + 1);
results = cudf::strings::rfind(strings_view, cudf::string_scalar(""), 0, end);
cudf::test::fixed_width_column_wrapper<cudf::size_type> rexpected({end, 0, end, end, end});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, rexpected);
}
{
std::vector<std::string> h_targets({"l", "", "", "l", "s"});
std::vector<cudf::size_type> h_expected;
for (std::size_t i = 0; i < h_strings.size(); ++i)
h_expected.push_back(static_cast<cudf::size_type>(h_strings[i].find(h_targets[i], position)));
cudf::test::fixed_width_column_wrapper<cudf::size_type> expected(h_expected.begin(),
h_expected.end());
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto results = cudf::strings::find(strings_view, cudf::strings_column_view(targets), position);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
INSTANTIATE_TEST_CASE_P(StringsFindTest,
FindParmsTest,
testing::ValuesIn(std::array<cudf::size_type, 4>{0, 1, 2, 3}));
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/durations_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/strings/convert/convert_durations.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/wrappers/durations.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsDurationsTest : public cudf::test::BaseFixture {};
TEST_F(StringsDurationsTest, FromToDurations)
{
using T = cudf::duration_s;
std::vector<cudf::duration_s> h_durations{
T{131246625}, T{1563399277}, T{0}, T{1553085296}, T{1582934400}, T{-1545730073}, T{-86399}};
std::vector<char const*> h_expected{"1519 days 01:23:45",
"18094 days 21:34:37",
nullptr,
"17975 days 12:34:56",
"18321 days 00:00:00",
"-17890 days 09:27:53",
"-0 days 23:59:59"};
cudf::test::fixed_width_column_wrapper<cudf::duration_s> durations(
h_durations.begin(),
h_durations.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::from_durations(durations);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
//
auto new_durations = cudf::strings::to_durations(cudf::strings_column_view(expected),
cudf::data_type(cudf::type_to_id<T>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
}
// Note: ISO format does not have leading zeros. This test does.
TEST_F(StringsDurationsTest, ISOFormat)
{
using T = cudf::duration_s;
cudf::test::fixed_width_column_wrapper<T> durations{
T{1530705600L}, T{1582934461L}, T{1451430122L}, T{1318302183L}, T{-6105994200L}};
auto results = cudf::strings::from_durations(durations, "P%DDT%HH%MM%SS");
cudf::test::strings_column_wrapper expected{"P17716DT12H00M00S",
"P18321DT00H01M01S",
"P16798DT23H02M02S",
"P15258DT03H03M03S",
"P-70671DT05H30M00S"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
//
cudf::test::strings_column_wrapper string_iso{
"P17716DT12H0M0S", "P18321DT0H1M1S", "P16798DT23H2M2S", "P15258DT3H3M3S", "P-70671DT5H30M0S"};
auto new_durations = cudf::strings::to_durations(cudf::strings_column_view(string_iso),
cudf::data_type(cudf::type_to_id<T>()),
"P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
new_durations = cudf::strings::to_durations(
cudf::strings_column_view(expected), cudf::data_type(cudf::type_to_id<T>()), "P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
}
TEST_F(StringsDurationsTest, ISOFormatDaysOnly)
{
using T = cudf::duration_D;
cudf::test::fixed_width_column_wrapper<T> durations{
T{17716L}, T{18321L}, T{16798L}, T{15258L}, T{-70672L}};
auto results1 = cudf::strings::from_durations(durations, "P%DDT%HH%MM%SS");
cudf::test::strings_column_wrapper expected1{"P17716DT00H00M00S",
"P18321DT00H00M00S",
"P16798DT00H00M00S",
"P15258DT00H00M00S",
"P-70672DT00H00M00S"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results1, expected1);
auto results2 = cudf::strings::from_durations(durations, "P%DD");
cudf::test::strings_column_wrapper expected2{
"P17716D", "P18321D", "P16798D", "P15258D", "P-70672D"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results2, expected2);
//
cudf::test::strings_column_wrapper string_iso{
"P17716DT0H0M0S", "P18321DT0H0M0S", "P16798DT0H0M0S", "P15258DT0H0M0S", "P-70672DT0H0M0S"};
auto new_durations1 = cudf::strings::to_durations(cudf::strings_column_view(string_iso),
cudf::data_type(cudf::type_to_id<T>()),
"P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations1, durations);
new_durations1 = cudf::strings::to_durations(
cudf::strings_column_view(expected1), cudf::data_type(cudf::type_to_id<T>()), "P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations1, durations);
auto new_durations2 = cudf::strings::to_durations(
cudf::strings_column_view(expected2), cudf::data_type(cudf::type_to_id<T>()), "P%DD");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations2, durations);
}
TEST_F(StringsDurationsTest, ISOFormatSubseconds)
{
using T = cudf::duration_ns;
cudf::test::fixed_width_column_wrapper<T> durations{T{0L},
T{7000000000L},
T{11L},
T{10L},
T{17716L},
T{18321L},
T{16798L},
T{15258L},
T{15258000L},
T{-70672L}};
auto results = cudf::strings::from_durations(durations, "P%DDT%HH%MM%SS");
cudf::test::strings_column_wrapper expected{"P0DT00H00M00S",
"P0DT00H00M07S",
"P0DT00H00M00.000000011S",
"P0DT00H00M00.000000010S",
"P0DT00H00M00.000017716S",
"P0DT00H00M00.000018321S",
"P0DT00H00M00.000016798S",
"P0DT00H00M00.000015258S",
"P0DT00H00M00.015258000S",
"P-0DT00H00M00.000070672S"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
// fully isoformat compliant.
cudf::test::strings_column_wrapper string_iso{"P0DT0H0M0S",
"P0DT0H0M7S",
"P0DT0H0M0.000000011S",
"P0DT0H0M0.00000001S",
"P0DT0H0M0.000017716S",
"P0DT0H0M0.000018321S",
"P0DT0H0M0.000016798S",
"P0DT0H0M0.000015258S",
"P0DT0H0M0.015258S",
"P-0DT0H0M0.000070672S"};
auto new_durations = cudf::strings::to_durations(cudf::strings_column_view(string_iso),
cudf::data_type(cudf::type_to_id<T>()),
"P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
new_durations = cudf::strings::to_durations(
cudf::strings_column_view(expected), cudf::data_type(cudf::type_to_id<T>()), "P%DDT%HH%MM%SS");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
}
TEST_F(StringsDurationsTest, DurationSeconds)
{
using T = cudf::duration_s;
cudf::test::fixed_width_column_wrapper<T> durations{
T{0L}, // 0 days 00:00:00
T{1L}, // 0 days 00:00:01
T{118800L}, // 1 days 09:00:00
T{31568404L}, // 365 days 09:00:04
T{-118800L}, // -1 days 09:00:00
T{-31568404L}, // -366 days +14:59:56
};
auto results = cudf::strings::from_durations(durations, "%D days %H:%M:%S");
cudf::test::strings_column_wrapper expected{"0 days 00:00:00",
"0 days 00:00:01",
"1 days 09:00:00",
"365 days 09:00:04",
"-1 days 09:00:00",
"-365 days 09:00:04"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
auto new_durations = cudf::strings::to_durations(cudf::strings_column_view(expected),
cudf::data_type(cudf::type_to_id<T>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
}
TEST_F(StringsDurationsTest, DurationDays)
{
using T = cudf::duration_D;
cudf::test::fixed_width_column_wrapper<T> durations{
T{0L}, // 0 days 00:00:00
T{1L}, // 1 days 00:00:00
T{-1L}, // -1 days 00:00:00
T{800L}, // 800 days 00:00:00
T{-800L}, // -800 days 00:00:00
T{2147483647L}, // 2147483647 days 00:00:00
T{-2147483648L}, // -2147483648 days 00:00:00
};
auto results = cudf::strings::from_durations(durations, "%D days %H:%M:%S");
cudf::test::strings_column_wrapper expected{"0 days 00:00:00",
"1 days 00:00:00",
"-1 days 00:00:00",
"800 days 00:00:00",
"-800 days 00:00:00",
"2147483647 days 00:00:00",
"-2147483648 days 00:00:00"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
auto new_durations = cudf::strings::to_durations(cudf::strings_column_view(expected),
cudf::data_type(cudf::type_to_id<T>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*new_durations, durations);
}
TEST_F(StringsDurationsTest, DurationMilliseconds)
{
using ms = cudf::duration_ms;
cudf::test::fixed_width_column_wrapper<cudf::duration_ms> durations_ms{ms{-60000},
ms{1530705600123},
ms{1582934461007},
ms{1451430122420},
ms{1451430122400},
ms{1451430122000},
ms{1318302183999},
ms{-6106017600047}};
cudf::test::strings_column_wrapper expected_ms_3f{"-0 days 00:01:00.000",
"17716 days 12:00:00.123",
"18321 days 00:01:01.007",
"16798 days 23:02:02.420",
"16798 days 23:02:02.400",
"16798 days 23:02:02.000",
"15258 days 03:03:03.999",
"-70671 days 12:00:00.047"};
cudf::test::strings_column_wrapper expected_ms_6f{"-0 days 00:01:00.000000",
"17716 days 12:00:00.123000",
"18321 days 00:01:01.007000",
"16798 days 23:02:02.420000",
"16798 days 23:02:02.400000",
"16798 days 23:02:02.000000",
"15258 days 03:03:03.999000",
"-70671 days 12:00:00.047000"};
cudf::test::strings_column_wrapper expected_ms{"-0 days 00:01:00",
"17716 days 12:00:00.123",
"18321 days 00:01:01.007",
"16798 days 23:02:02.420",
"16798 days 23:02:02.400",
"16798 days 23:02:02",
"15258 days 03:03:03.999",
"-70671 days 12:00:00.047"};
auto results = cudf::strings::from_durations(durations_ms, "%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms);
//
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ms_3f),
cudf::data_type(cudf::type_to_id<ms>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ms);
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ms_6f),
cudf::data_type(cudf::type_to_id<ms>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ms);
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ms),
cudf::data_type(cudf::type_to_id<ms>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ms);
}
TEST_F(StringsDurationsTest, DurationMicroseconds)
{
using us = cudf::duration_us;
cudf::test::fixed_width_column_wrapper<cudf::duration_us> durations_us{us{-60000},
us{1530705600123},
us{1582934461007},
us{1451430122420},
us{1451430122400},
us{1451430122000},
us{1318302183999},
us{-6106017600047}};
cudf::test::strings_column_wrapper expected_us_3f{"-0 days 00:00:00.060",
"17 days 17:11:45.600",
"18 days 07:42:14.461",
"16 days 19:10:30.122",
"16 days 19:10:30.122",
"16 days 19:10:30.122",
"15 days 06:11:42.183",
"-70 days 16:06:57.600"};
cudf::test::strings_column_wrapper expected_us_6f{"-0 days 00:00:00.060000",
"17 days 17:11:45.600123",
"18 days 07:42:14.461007",
"16 days 19:10:30.122420",
"16 days 19:10:30.122400",
"16 days 19:10:30.122000",
"15 days 06:11:42.183999",
"-70 days 16:06:57.600047"};
cudf::test::strings_column_wrapper expected_us{"-0 days 00:00:00.060000",
"17 days 17:11:45.600123",
"18 days 07:42:14.461007",
"16 days 19:10:30.122420",
"16 days 19:10:30.122400",
"16 days 19:10:30.122000",
"15 days 06:11:42.183999",
"-70 days 16:06:57.600047"};
auto results = cudf::strings::from_durations(durations_us, "%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_us);
//
cudf::test::fixed_width_column_wrapper<cudf::duration_us> durations_us_3f{us{-60000},
us{1530705600000},
us{1582934461000},
us{1451430122000},
us{1451430122000},
us{1451430122000},
us{1318302183000},
us{-6106017600000}};
results = cudf::strings::to_durations(cudf::strings_column_view(expected_us_3f),
cudf::data_type(cudf::type_to_id<us>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_us_3f);
results = cudf::strings::to_durations(cudf::strings_column_view(expected_us_6f),
cudf::data_type(cudf::type_to_id<us>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_us);
results = cudf::strings::to_durations(cudf::strings_column_view(expected_us),
cudf::data_type(cudf::type_to_id<us>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_us);
}
TEST_F(StringsDurationsTest, DurationNanoseconds)
{
using ns = cudf::duration_ns;
cudf::test::fixed_width_column_wrapper<cudf::duration_ns> durations_ns{ns{1530705600123456789},
ns{1582934461007008009},
ns{1451430122421310209},
ns{1318302183999777550},
ns{-6106017600047047047}};
auto results = cudf::strings::from_durations(durations_ns, "%D days %H:%M:%S");
cudf::test::strings_column_wrapper expected_ns_9f{"17716 days 12:00:00.123456789",
"18321 days 00:01:01.007008009",
"16798 days 23:02:02.421310209",
"15258 days 03:03:03.999777550",
"-70671 days 12:00:00.047047047"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns_9f);
cudf::test::strings_column_wrapper expected_ns_6f{"17716 days 12:00:00.123456",
"18321 days 00:01:01.007008",
"16798 days 23:02:02.421310",
"15258 days 03:03:03.999777",
"-70671 days 12:00:00.047047"};
cudf::test::strings_column_wrapper expected_ns{"17716 days 12:00:00.123456789",
"18321 days 00:01:01.007008009",
"16798 days 23:02:02.421310209",
"15258 days 03:03:03.99977755",
"-70671 days 12:00:00.047047047"};
//
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ns_9f),
cudf::data_type(cudf::type_to_id<ns>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ns);
cudf::test::fixed_width_column_wrapper<cudf::duration_ns> durations_ns_6f{
ns{1530705600123456000},
ns{1582934461007008000},
ns{1451430122421310000},
ns{1318302183999777000},
ns{-6106017600047047000}};
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ns_6f),
cudf::data_type(cudf::type_to_id<ns>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ns_6f);
results = cudf::strings::to_durations(cudf::strings_column_view(expected_ns),
cudf::data_type(cudf::type_to_id<ns>()),
"%D days %H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, durations_ns);
}
// Hour, Minute, Seconds 0,+,-
TEST_F(StringsDurationsTest, ParseSingle)
{
cudf::test::strings_column_wrapper string_src{"00",
"-00",
"01",
"-01",
"23",
"-23",
"59",
"-59",
"999",
"-999",
"", // error
"01",
""}; // error
auto size = cudf::column_view(string_src).size();
int32_t expected_v[]{0, 0, 1, -1, 23, -23, 59, -59, 99, -99, 0, 1, 0};
auto it1 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i * 3600}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s1(it1, it1 + size);
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%H");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
auto it2 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i * 60}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s2(it2, it2 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%M");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s2);
auto it3 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s3(it3, it3 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s3);
auto it4 = thrust::make_transform_iterator(expected_v,
[](auto i) { return cudf::duration_ms{i * 60000}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_ms> expected_ms(it4, it4 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_ms>()),
"%M");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms);
}
// Hour, Minute, Seconds
TEST_F(StringsDurationsTest, ParseMultiple)
{
cudf::test::strings_column_wrapper string_src{"00:00:00",
"-00:00:00",
"-00:00:01",
"-01:01:01",
"23:00:01",
"-23:00:01",
"59:00:00",
"-59:00:00",
"999:00:00",
"-999:00:00",
"", // error
"01:01:01",
""}; // error
auto size = cudf::column_view(string_src).size();
int32_t expected_v[]{0,
0,
-1,
-(3600 + 60 + 1),
23 * 3600 + 1,
-(23 * 3600 + 1),
59 * 3600,
-59 * 3600,
99 * 3600,
-99 * 3600,
0,
3661,
0};
auto it1 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s1(it1, it1 + size);
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
auto it2 = thrust::make_transform_iterator(
expected_v, [](auto i) { return cudf::duration_D{i / (24 * 3600)}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_D> expected_D2(it2, it2 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_D>()),
"%H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_D2);
cudf::test::fixed_width_column_wrapper<cudf::duration_us> expected_us3(it1, it1 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_us>()),
"%H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_us3);
}
// 0,+,- on DHMSs
// subsecond=0,1,2,3,4,5,6,8,9,digits, also leading zeros. subsecond with/without zero HMS.
TEST_F(StringsDurationsTest, ParseSubsecond)
{
cudf::test::strings_column_wrapper string_src{"00:00:00.000000000",
"-00:00:00.123456789",
"-00:00:01.000666999", // leading zeros
"-01:01:01.100000000",
"23:00:01.00000008", // trailing zero missing
"-23:00:01.123000000", // trailing zeros
"59:00:00",
"-59:00:00",
"999:00:00",
"-999:00:00",
"", // error
"01:01:01",
""}; // error
auto size = cudf::column_view(string_src).size();
int64_t expected_v[]{0,
-123456789L,
-1000666999L,
-((3600 + 60 + 1) * 1000000000L + 100000000L),
(23 * 3600 + 1) * 1000000000L + 80L,
-((23 * 3600 + 1) * 1000000000L + 123000000L),
(59 * 3600) * 1000000000L,
-(59 * 3600) * 1000000000L,
(99 * 3600) * 1000000000L,
-(99 * 3600) * 1000000000L,
0,
(3661) * 1000000000L,
0};
auto it1 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_ns{i}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_ns> expected_ns1(it1, it1 + size);
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_ns>()),
"%H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns1);
auto it2 = thrust::make_transform_iterator(expected_v,
[](auto i) { return cudf::duration_ms{i / 1000000}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_ms> expected_ms2(it2, it2 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_ms>()),
"%H:%M:%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms2);
}
// AM/PM 0,+,- on DHMSs
TEST_F(StringsDurationsTest, ParseAMPM)
{
cudf::test::strings_column_wrapper string_src{"00:00:00 AM",
"00:00:00 PM",
"-00:00:00 AM",
"-00:00:00 PM",
"-00:00:01 AM",
"-00:00:01 PM",
"-01:01:01 AM",
"-01:01:01 PM",
"11:59:59 AM",
"11:59:59 PM",
"-11:59:59 AM",
"-11:59:59 PM",
"09:00:00", // error
"-09:00:00", // error
"", // error
"01:01:01", // error
""}; // error
auto size = cudf::column_view(string_src).size();
int32_t expected_v[]{0,
0 + 12 * 3600,
0,
0 - 12 * 3600,
-1,
-1 - 12 * 3600,
-(3600 + 60 + 1),
-(3600 + 60 + 1) - 12 * 3600,
11 * 3600 + 59 * 60 + 59,
11 * 3600 + 59 * 60 + 59 + 12 * 3600,
-(11 * 3600 + 59 * 60 + 59),
-(11 * 3600 + 59 * 60 + 59 + 12 * 3600),
0,
0,
0,
0,
0};
auto it1 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s1(it1, it1 + size);
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%H:%M:%S %p");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
auto it2 = thrust::make_transform_iterator(
expected_v, [](auto i) { return cudf::duration_D{i / (24 * 3600)}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_D> expected_D2(it2, it2 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_D>()),
"%H:%M:%S %p");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_D2);
cudf::test::fixed_width_column_wrapper<cudf::duration_us> expected_us3(it1, it1 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_us>()),
"%H:%M:%S %p");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_us3);
}
// R, T, r
TEST_F(StringsDurationsTest, ParseCompoundSpecifier)
{
// %r
cudf::test::strings_column_wrapper string_src{"00:00:00 AM",
"00:00:00 PM",
"00:00:01 AM",
"00:00:01 PM",
"01:01:01 AM",
"01:01:01 PM",
"11:59:59 AM",
"11:59:59 PM",
"09:00:00", // error
"", // error
"01:01:01", // error
""}; // error
auto size = cudf::column_view(string_src).size();
int32_t expected_v[]{0,
0 + 12 * 3600,
1,
1 + 12 * 3600,
(3600 + 60 + 1),
(3600 + 60 + 1) + 12 * 3600,
11 * 3600 + 59 * 60 + 59,
11 * 3600 + 59 * 60 + 59 + 12 * 3600,
0,
0,
0,
0};
auto it1 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_s{i}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_s> expected_s1(it1, it1 + size);
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%r");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%OI:%OM:%OS %p");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
auto it2 =
thrust::make_transform_iterator(expected_v, [](auto i) { return cudf::duration_ms{i * 1000}; });
cudf::test::fixed_width_column_wrapper<cudf::duration_ms> expected_s2(it2, it2 + size);
results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_ms>()),
"%r");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s2);
// %T, %R
cudf::test::strings_column_wrapper string_src2{"00:00:00",
"12:00:00",
"20:44:01",
"-20:44:01",
"08:01:01",
"-08:01:01",
"11:59:59",
"-11:59:59 AM",
"09:00 AM", // error
"", // error
"01:01:01",
""}; // error
cudf::test::fixed_width_column_wrapper<cudf::duration_s, int64_t> expected_s3(
{0,
12 * 3600,
(20 * 3600 + 44 * 60 + 1),
-(20 * 3600 + 44 * 60 + 1),
(8 * 3600 + 60 + 1),
-(8 * 3600 + 60 + 1),
(11 * 3600 + 59 * 60 + 59),
-(11 * 3600 + 59 * 60 + 59),
9 * 3600,
0,
3661,
0});
results = cudf::strings::to_durations(cudf::strings_column_view(string_src2),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%T");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s3);
cudf::test::fixed_width_column_wrapper<cudf::duration_s, int64_t> expected_s4(
{0,
12 * 3600,
(20 * 3600 + 44 * 60),
-(20 * 3600 + 44 * 60),
(8 * 3600 + 60),
-(8 * 3600 + 60),
(11 * 3600 + 59 * 60),
-(11 * 3600 + 59 * 60),
9 * 3600,
0,
3660,
0});
results = cudf::strings::to_durations(cudf::strings_column_view(string_src2),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%R");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s4);
}
// Escape characters %% %n %t
// Mixed (for checking only one negative sign)
TEST_F(StringsDurationsTest, ParseEscapeCharacters)
{
cudf::test::strings_column_wrapper string_src{
"00:00%00", "01:01%01", "11:59%59", "11:-59%59", "09:00%00"};
cudf::test::fixed_width_column_wrapper<cudf::duration_s, int64_t> expected_s1(
{0, 3661, (11 * 3600 + 59 * 60 + 59), -(11 * 3600 + 59 * 60 + 59), 9 * 3600});
auto results = cudf::strings::to_durations(cudf::strings_column_view(string_src),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%OH:%M%%%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
results = cudf::strings::from_durations(expected_s1, "%OH:%M%%%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, string_src);
cudf::test::strings_column_wrapper string_src2{
"00\t00\n00", "01\t01\n01", "11\t59\n59", "11\t-59\n59", "09\t00\n00"};
results = cudf::strings::to_durations(cudf::strings_column_view(string_src2),
cudf::data_type(cudf::type_to_id<cudf::duration_s>()),
"%OH%t%M%n%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_s1);
results = cudf::strings::from_durations(expected_s1, "%OH%t%M%n%S");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, string_src2);
}
TEST_F(StringsDurationsTest, ZeroSizeStringsColumn)
{
auto const zero_size_column = cudf::make_empty_column(cudf::type_id::DURATION_SECONDS)->view();
auto results = cudf::strings::from_durations(zero_size_column);
cudf::test::expect_column_empty(results->view());
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
results = cudf::strings::to_durations(cudf::strings_column_view(zero_size_strings_column),
cudf::data_type{cudf::type_id::DURATION_SECONDS},
"%S");
EXPECT_EQ(0, results->size());
}
TEST_F(StringsDurationsTest, Errors)
{
cudf::test::strings_column_wrapper strings{"this column intentionally left blank"};
cudf::strings_column_view view(strings);
EXPECT_THROW(cudf::strings::to_durations(view, cudf::data_type{cudf::type_id::INT64}, "%D"),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_durations(view, cudf::data_type{cudf::type_id::DURATION_SECONDS}, ""),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_durations(view, cudf::data_type{cudf::type_id::DURATION_SECONDS}, "%2H"),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_durations(view, cudf::data_type{cudf::type_id::DURATION_SECONDS}, "%g"),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_durations(view, cudf::data_type{cudf::type_id::DURATION_SECONDS}, "%Op"),
cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> invalid_durations{1530705600};
EXPECT_THROW(cudf::strings::from_durations(invalid_durations), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<cudf::duration_s> durations{cudf::duration_s{1530705600}};
EXPECT_THROW(cudf::strings::from_durations(durations, ""), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/integers_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/type_lists.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/strings/convert/convert_integers.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <thrust/host_vector.h>
#include <thrust/iterator/transform_iterator.h>
#include <string>
#include <vector>
// Using an alias variable for the null elements
// This will make the code looks cleaner
constexpr auto NULL_VAL = 0;
struct StringsConvertTest : public cudf::test::BaseFixture {};
TEST_F(StringsConvertTest, IsIntegerBasicCheck)
{
cudf::test::strings_column_wrapper strings1(
{"+175", "-34", "9.8", "17+2", "+-14", "1234567890", "67de", "", "1e10", "-", "++", ""});
auto results = cudf::strings::is_integer(cudf::strings_column_view(strings1));
cudf::test::fixed_width_column_wrapper<bool> expected1({1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected1);
cudf::test::strings_column_wrapper strings2(
{"0", "+0", "-0", "1234567890", "-27341132", "+012", "023", "-045"});
results = cudf::strings::is_integer(cudf::strings_column_view(strings2));
cudf::test::fixed_width_column_wrapper<bool> expected2({1, 1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected2);
}
TEST_F(StringsConvertTest, ZeroSizeIsIntegerBasicCheck)
{
cudf::test::strings_column_wrapper strings;
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::is_integer(strings_view);
EXPECT_EQ(cudf::type_id::BOOL8, results->view().type().id());
EXPECT_EQ(0, results->view().size());
}
TEST_F(StringsConvertTest, IsIntegerBoundCheckNoNull)
{
auto strings = cudf::test::strings_column_wrapper(
{"+175", "-34", "9.8", "17+2", "+-14", "1234567890", "67de", "", "1e10", "-", "++", ""});
auto results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
auto expected =
cudf::test::fixed_width_column_wrapper<bool>({1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
strings = cudf::test::strings_column_wrapper(
{"0", "+0", "-0", "1234567890", "-27341132", "+012", "023", "-045"});
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, IsIntegerBoundCheckWithNulls)
{
std::vector<char const*> const h_strings{
"eee", "1234", nullptr, "", "-9832", "93.24", "765é", nullptr};
auto const strings = cudf::test::strings_column_wrapper(
h_strings.begin(),
h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
auto const results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
// Input has null elements then the output should have the same null mask
auto const expected = cudf::test::fixed_width_column_wrapper<bool>(
std::initializer_list<int8_t>{0, 1, NULL_VAL, 0, 1, 0, 0, NULL_VAL},
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, ZeroSizeIsIntegerBoundCheck)
{
// Empty input
auto strings = cudf::test::strings_column_wrapper{};
auto results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
EXPECT_EQ(cudf::type_id::BOOL8, results->view().type().id());
EXPECT_EQ(0, results->view().size());
}
TEST_F(StringsConvertTest, IsIntegerBoundCheckSmallNumbers)
{
auto strings = cudf::test::strings_column_wrapper(
{"-200", "-129", "-128", "-120", "0", "120", "127", "130", "150", "255", "300", "500"});
auto results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT8});
auto expected =
cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::UINT8});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
strings = cudf::test::strings_column_wrapper(
{"-40000", "-32769", "-32768", "-32767", "-32766", "32765", "32766", "32767", "32768"});
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT16});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 1, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::UINT16});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 0, 0, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, IsIntegerBoundCheckLargeNumbers)
{
auto strings =
cudf::test::strings_column_wrapper({"-2147483649", // std::numeric_limits<int32_t>::min() - 1
"-2147483648", // std::numeric_limits<int32_t>::min()
"-2147483647", // std::numeric_limits<int32_t>::min() + 1
"2147483646", // std::numeric_limits<int32_t>::max() - 1
"2147483647", // std::numeric_limits<int32_t>::max()
"2147483648", // std::numeric_limits<int32_t>::max() + 1
"4294967294", // std::numeric_limits<uint32_t>::max() - 1
"4294967295", // std::numeric_limits<uint32_t>::max()
"4294967296"}); // std::numeric_limits<uint32_t>::max() + 1
auto results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
auto expected = cudf::test::fixed_width_column_wrapper<bool>({0, 1, 1, 1, 1, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::UINT32});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
strings = cudf::test::strings_column_wrapper(
{"-9223372036854775809", // std::numeric_limits<int64_t>::min() - 1
"-9223372036854775808", // std::numeric_limits<int64_t>::min()
"-9223372036854775807", // std::numeric_limits<int64_t>::min() + 1
"9223372036854775806", // std::numeric_limits<int64_t>::max() - 1
"9223372036854775807", // std::numeric_limits<int64_t>::max()
"9223372036854775808", // std::numeric_limits<int64_t>::max() + 1
"18446744073709551614", // std::numeric_limits<uint64_t>::max() - 1
"18446744073709551615", // std::numeric_limits<uint64_t>::max()
"18446744073709551616"}); // std::numeric_limits<uint64_t>::max() + 1
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT64});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 1, 1, 1, 1, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_integer(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::UINT64});
expected = cudf::test::fixed_width_column_wrapper<bool>({0, 0, 0, 1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, ToInteger)
{
std::vector<char const*> h_strings{"eee",
"1234",
nullptr,
"",
"-9832",
"93.24",
"765é",
nullptr,
"-1.78e+5",
"2147483647",
"-2147483648",
"2147483648"};
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 = cudf::strings::to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT16});
auto const expected_i16 = cudf::test::fixed_width_column_wrapper<int16_t>(
std::initializer_list<int16_t>{0, 1234, NULL_VAL, 0, -9832, 93, 765, NULL_VAL, -1, -1, 0, 0},
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_i16);
results = cudf::strings::to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
auto const expected_i32 = cudf::test::fixed_width_column_wrapper<int32_t>(
std::initializer_list<int32_t>{
0, 1234, NULL_VAL, 0, -9832, 93, 765, NULL_VAL, -1, 2147483647, -2147483648, -2147483648},
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_i32);
results = cudf::strings::to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::UINT32});
auto const expected_u32 = cudf::test::fixed_width_column_wrapper<uint32_t>(
std::initializer_list<uint32_t>{0,
1234,
NULL_VAL,
0,
4294957464,
93,
765,
NULL_VAL,
4294967295,
2147483647,
2147483648,
2147483648},
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_u32);
}
TEST_F(StringsConvertTest, FromInteger)
{
int32_t minint = std::numeric_limits<int32_t>::min();
int32_t maxint = std::numeric_limits<int32_t>::max();
std::vector<int32_t> h_integers{100, 987654321, 0, 0, -12761, 0, 5, -4, maxint, minint};
std::vector<char const*> h_expected{
"100", "987654321", nullptr, "0", "-12761", "0", "5", "-4", "2147483647", "-2147483648"};
cudf::test::fixed_width_column_wrapper<int32_t> integers(
h_integers.begin(),
h_integers.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::from_integers(integers);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, ZeroSizeStringsColumn)
{
auto const zero_size_column = cudf::make_empty_column(cudf::type_id::INT32)->view();
auto results = cudf::strings::from_integers(zero_size_column);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConvertTest, ZeroSizeIntegersColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results =
cudf::strings::to_integers(zero_size_strings_column, cudf::data_type{cudf::type_id::INT32});
EXPECT_EQ(0, results->size());
}
TEST_F(StringsConvertTest, EmptyStringsColumn)
{
cudf::test::strings_column_wrapper strings({"", "", ""});
auto results = cudf::strings::to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT64});
cudf::test::fixed_width_column_wrapper<int64_t> expected{0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected);
}
template <typename T>
class StringsIntegerConvertTest : public StringsConvertTest {};
TYPED_TEST_SUITE(StringsIntegerConvertTest, cudf::test::IntegralTypesNotBool);
TYPED_TEST(StringsIntegerConvertTest, FromToInteger)
{
thrust::host_vector<TypeParam> h_integers(255);
std::iota(h_integers.begin(), h_integers.end(), -(TypeParam)(h_integers.size() / 2));
h_integers.push_back(std::numeric_limits<TypeParam>::min());
h_integers.push_back(std::numeric_limits<TypeParam>::max());
auto d_integers = cudf::detail::make_device_uvector_sync(
h_integers, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto integers = cudf::make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()},
(cudf::size_type)d_integers.size());
auto integers_view = integers->mutable_view();
CUDF_CUDA_TRY(cudaMemcpy(integers_view.data<TypeParam>(),
d_integers.data(),
d_integers.size() * sizeof(TypeParam),
cudaMemcpyDefault));
integers_view.set_null_count(0);
// convert to strings
auto results_strings = cudf::strings::from_integers(integers->view());
// copy back to host
h_integers = cudf::detail::make_host_vector_sync(d_integers, cudf::get_default_stream());
std::vector<std::string> h_strings;
for (auto itr = h_integers.begin(); itr != h_integers.end(); ++itr)
h_strings.push_back(std::to_string(*itr));
cudf::test::strings_column_wrapper expected(h_strings.begin(), h_strings.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results_strings, expected);
// convert back to integers
auto strings_view = cudf::strings_column_view(results_strings->view());
auto results_integers =
cudf::strings::to_integers(strings_view, cudf::data_type(cudf::type_to_id<TypeParam>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results_integers, integers->view());
}
//
template <typename T>
class StringsFloatConvertTest : public StringsConvertTest {};
using FloatTypes = cudf::test::Types<float, double>;
TYPED_TEST_SUITE(StringsFloatConvertTest, FloatTypes);
TYPED_TEST(StringsFloatConvertTest, FromToIntegerError)
{
auto dtype = cudf::data_type{cudf::type_to_id<TypeParam>()};
auto column = cudf::make_numeric_column(dtype, 100);
EXPECT_THROW(cudf::strings::from_integers(column->view()), cudf::logic_error);
cudf::test::strings_column_wrapper strings{"this string intentionally left blank"};
EXPECT_THROW(cudf::strings::to_integers(column->view(), dtype), cudf::logic_error);
}
TEST_F(StringsConvertTest, HexToInteger)
{
std::vector<char const*> h_strings{
"1234", nullptr, "98BEEF", "1a5", "CAFE", "2face", "0xAABBCCDD", "112233445566"};
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<int32_t> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr) {
if (*itr == nullptr)
h_expected.push_back(0);
else
h_expected.push_back(static_cast<int>(std::stol(std::string(*itr), 0, 16)));
}
auto results = cudf::strings::hex_to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT32});
cudf::test::fixed_width_column_wrapper<int32_t> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<int64_t> h_expected;
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr) {
if (*itr == nullptr)
h_expected.push_back(0);
else
h_expected.push_back(std::stol(std::string(*itr), 0, 16));
}
auto results = cudf::strings::hex_to_integers(cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::INT64});
cudf::test::fixed_width_column_wrapper<int64_t> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsConvertTest, IsHex)
{
std::vector<char const*> h_strings{"",
"1234",
nullptr,
"98BEEF",
"1a5",
"2face",
"0xAABBCCDD",
"112233445566",
"XYZ",
"0",
"0x",
"x"};
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::fixed_width_column_wrapper<bool> expected({0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0},
{1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1});
auto results = cudf::strings::is_hex(cudf::strings_column_view(strings));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TYPED_TEST(StringsIntegerConvertTest, IntegerToHex)
{
std::vector<TypeParam> h_integers(255);
std::generate(h_integers.begin(), h_integers.end(), []() {
static TypeParam data = 0;
return data++ << (sizeof(TypeParam) - 1) * 8;
});
cudf::test::fixed_width_column_wrapper<TypeParam> integers(h_integers.begin(), h_integers.end());
std::vector<std::string> h_expected(255);
std::transform(h_integers.begin(), h_integers.end(), h_expected.begin(), [](auto v) {
if (v == 0) { return std::string("00"); }
// special handling for single-byte types
if constexpr (std::is_same_v<TypeParam, int8_t> || std::is_same_v<TypeParam, uint8_t>) {
char const hex_digits[16] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
std::string str;
str += hex_digits[(v & 0xF0) >> 4];
str += hex_digits[(v & 0x0F)];
return str;
}
// all other types work with this
std::stringstream str;
str << std::setfill('0') << std::setw(sizeof(TypeParam) * 2) << std::hex << std::uppercase << v;
return str.str();
});
cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end());
auto results = cudf::strings::integers_to_hex(integers);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, IntegerToHexWithNull)
{
cudf::test::fixed_width_column_wrapper<int32_t> integers(
{123456, -1, 0, 0, 12, 12345, 123456789, -123456789}, {1, 1, 1, 0, 1, 1, 1, 1});
cudf::test::strings_column_wrapper expected(
{"01E240", "FFFFFFFF", "00", "", "0C", "3039", "075BCD15", "F8A432EB"},
{1, 1, 1, 0, 1, 1, 1, 1});
auto results = cudf::strings::integers_to_hex(integers);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, IntegerConvertErrors)
{
cudf::test::fixed_width_column_wrapper<bool> bools(
{true, true, false, false, true, true, false, true});
cudf::test::fixed_width_column_wrapper<double> floats(
{123456.0, -1.0, 0.0, 0.0, 12.0, 12345.0, 123456789.0});
EXPECT_THROW(cudf::strings::integers_to_hex(bools), cudf::logic_error);
EXPECT_THROW(cudf::strings::integers_to_hex(floats), cudf::logic_error);
EXPECT_THROW(cudf::strings::from_integers(bools), cudf::logic_error);
EXPECT_THROW(cudf::strings::from_integers(floats), cudf::logic_error);
auto input = cudf::test::strings_column_wrapper({"123456", "-1", "0"});
auto view = cudf::strings_column_view(input);
EXPECT_THROW(cudf::strings::to_integers(view, cudf::data_type(cudf::type_id::BOOL8)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::to_integers(view, cudf::data_type(cudf::type_id::FLOAT32)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::to_integers(view, cudf::data_type(cudf::type_id::TIMESTAMP_SECONDS)),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_integers(view, cudf::data_type(cudf::type_id::DURATION_MILLISECONDS)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::to_integers(view, cudf::data_type(cudf::type_id::DECIMAL32)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/strip_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/column/column.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/strings/strip.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsStripTest : public cudf::test::BaseFixture {};
TEST_F(StringsStripTest, StripLeft)
{
std::vector<char const*> h_strings{" aBc ", " ", nullptr, "aaaa ", "b", "\tccc ddd"};
std::vector<char const*> h_expected{"aBc ", "", nullptr, "aaaa ", "b", "ccc ddd"};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::strip(strings_view, cudf::strings::side_type::LEFT);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsStripTest, StripRight)
{
std::vector<char const*> h_strings{" aBc ", " ", nullptr, "aaaa ", "b", "\tccc ddd"};
std::vector<char const*> h_expected{" aBc", "", nullptr, "", "b", "\tccc ddd"};
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 strings_view = cudf::strings_column_view(strings);
auto results =
cudf::strings::strip(strings_view, cudf::strings::side_type::RIGHT, cudf::string_scalar(" a"));
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsStripTest, StripBoth)
{
std::vector<char const*> h_strings{" aBc ", " ", nullptr, "ééé ", "b", " ccc dddé"};
std::vector<char const*> h_expected{"aBc", "", nullptr, "", "b", "ccc ddd"};
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 strings_view = cudf::strings_column_view(strings);
auto results =
cudf::strings::strip(strings_view, cudf::strings::side_type::BOTH, cudf::string_scalar(" é"));
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsStripTest, EmptyStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::strip(strings_view);
auto view = results->view();
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsStripTest, AllEmptyStrings)
{
auto input = cudf::test::strings_column_wrapper({"", "", "", "", "", ""}, {1, 1, 0, 1, 1});
auto results =
cudf::strings::strip(cudf::strings_column_view(input), cudf::strings::side_type::BOTH);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
}
TEST_F(StringsStripTest, InvalidParameter)
{
std::vector<char const*> h_strings{"string left intentionally blank"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_view = cudf::strings_column_view(strings);
EXPECT_THROW(cudf::strings::strip(
strings_view, cudf::strings::side_type::BOTH, cudf::string_scalar("", false)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/attrs_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/strings/attributes.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 <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsAttributesTest : public cudf::test::BaseFixture {};
TEST_F(StringsAttributesTest, CodePoints)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
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 strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::code_points(strings_view);
cudf::test::fixed_width_column_wrapper<int32_t> expected{
101, 101, 101, 98, 98, 97, 97, 98, 98, 98, 50089, 50089, 50089};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsAttributesTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
cudf::column_view expected_column(cudf::data_type{cudf::type_id::INT32}, 0, nullptr, nullptr, 0);
auto results = cudf::strings::count_bytes(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected_column);
results = cudf::strings::count_characters(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected_column);
results = cudf::strings::code_points(strings_view);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected_column);
}
TEST_F(StringsAttributesTest, StringsLengths)
{
std::vector<char const*> h_strings{
"eee", "bb", nullptr, "", "aa", "ééé", "something a bit longer than 32 bytes"};
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 strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::count_characters(strings_view);
std::vector<int32_t> h_expected{3, 2, 0, 0, 2, 3, 36};
cudf::test::fixed_width_column_wrapper<int32_t> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::count_bytes(strings_view);
std::vector<int32_t> h_expected{3, 2, 0, 0, 2, 6, 36};
cudf::test::fixed_width_column_wrapper<int32_t> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsAttributesTest, StringsLengthsLong)
{
std::vector<std::string> h_strings(
40000, "something a bit longer than 32 bytes ééé ééé ééé ééé ééé ééé ééé");
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::count_characters(strings_view);
std::vector<int32_t> h_expected(h_strings.size(), 64);
cudf::test::fixed_width_column_wrapper<int32_t> expected(h_expected.begin(), h_expected.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/datetime_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/strings/convert/convert_datetime.hpp>
#include <cudf/strings/convert/convert_durations.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/unary.hpp>
#include <cudf/wrappers/durations.hpp>
#include <cudf/wrappers/timestamps.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsDatetimeTest : public cudf::test::BaseFixture {};
TEST_F(StringsDatetimeTest, ToTimestamp)
{
std::vector<char const*> h_strings{"1974-02-28T01:23:45Z",
"2019-07-17T21:34:37Z",
nullptr,
"",
"2019-03-20T12:34:56Z",
"2020-02-29T00:00:00Z",
"1921-01-07T14:32:07Z",
"1969-12-31T23:59:45Z"};
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<cudf::timestamp_s::rep> h_expected{
131246625, 1563399277, 0, 0, 1553085296, 1582934400, -1545730073, -15};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, "%Y-%m-%dT%H:%M:%SZ");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%dT%H:%M:%SZ");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 0, 0, 1, 1, 1, 1},
{1, 1, 0, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampAmPm)
{
cudf::test::strings_column_wrapper strings{"1974-02-28 01:23:45 PM",
"2019-07-17 02:34:56 AM",
"2019-03-20 12:34:56 PM",
"2020-02-29 12:00:00 AM",
"1925-02-07 02:55:08 PM"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, "%Y-%m-%d %I:%M:%S %p");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> expected{
131289825, 1563330896, 1553085296, 1582934400, -1416819892};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %I:%M:%S %p");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampMicrosecond)
{
cudf::test::strings_column_wrapper strings{"1974-02-28 01:23:45.987000",
"2019-07-17 02:34:56.001234",
"2019-03-20 12:34:56.100100",
"2020-02-29 00:00:00.555777",
"1969-12-31 00:00:01.000055",
"1944-07-21 11:15:09.333444"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_MILLISECONDS}, "%Y-%m-%d %H:%M:%S.%6f");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> expected_ms{
131246625987, 1563330896001, 1553085296100, 1582934400555, -86399000L, -803047490667L};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms);
results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_NANOSECONDS}, "%Y-%m-%d %H:%M:%S.%6f");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> expected_ns{
131246625987000000,
1563330896001234000,
1553085296100100000,
1582934400555777000,
-86398999945000,
-803047490666556000};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %H:%M:%S.%6f");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampMillisecond)
{
cudf::test::strings_column_wrapper strings{"2018-07-04 12:00:00.123",
"2020-04-06 13:09:00.555",
"1969-12-31 00:00:00.000",
"1956-01-23 17:18:19.000"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_MICROSECONDS}, "%Y-%m-%d %H:%M:%S.%3f");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_us, cudf::timestamp_us::rep> expected_us{
1530705600123000, 1586178540555000, -86400000000, -439886501000000};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_us);
results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_NANOSECONDS}, "%Y-%m-%d %H:%M:%S.%3f");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> expected_ns{
1530705600123000000, 1586178540555000000, -86400000000000, -439886501000000000};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %H:%M:%S.%3f");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampTimezone)
{
cudf::test::strings_column_wrapper strings{"1974-02-28 01:23:45+0100",
"2019-07-17 02:34:56-0300",
"2019-03-20 12:34:56+1030",
"2020-02-29 12:00:00-0500",
"2022-04-07 09:15:00Z",
"1938-11-23 10:28:49+0700"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, "%Y-%m-%d %H:%M:%S%z");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> expected{
131243025, 1563341696, 1553047496, 1582995600, 1649322900, -981664271};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %H:%M:%S%z");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampSingleSpecifier)
{
cudf::test::strings_column_wrapper strings{"12", "10", "09", "05"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}, "%d");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> expected_days{
11, 9, 8, 4};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_days);
results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}, "%m");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> expected_months{
334, 273, 243, 120};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_months);
results = cudf::strings::is_timestamp(strings_view, "%m");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results,
cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1});
}
TEST_F(StringsDatetimeTest, ToTimestampVariableFractions)
{
cudf::test::strings_column_wrapper test1{"01:02:03.000001000",
"01:02:03.000001",
"01:02:03.1",
"01:02:03.01",
"01:02:03.0098700",
"01:02:03.0023456"};
auto strings_view = cudf::strings_column_view(test1);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_NANOSECONDS}, "%H:%M:%S.%9f");
auto durations =
cudf::cast(results->view(), cudf::data_type{cudf::type_id::DURATION_NANOSECONDS});
cudf::test::fixed_width_column_wrapper<cudf::duration_ns> expected1{
cudf::duration_ns{3723000001000},
cudf::duration_ns{3723000001000},
cudf::duration_ns{3723100000000},
cudf::duration_ns{3723010000000},
cudf::duration_ns{3723009870000},
cudf::duration_ns{3723002345600}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*durations, expected1);
results = cudf::strings::is_timestamp(strings_view, "%H:%M:%S.%f");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results,
cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 1, 1});
cudf::test::strings_column_wrapper test2{"01:02:03.100001Z",
"01:02:03.001Z",
"01:02:03.1Z",
"01:02:03.01Z",
"01:02:03.0098Z",
"01:02:03.00234Z"};
strings_view = cudf::strings_column_view(test2);
results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_MICROSECONDS}, "%H:%M:%S.%6f%Z");
durations = cudf::cast(results->view(), cudf::data_type{cudf::type_id::DURATION_MICROSECONDS});
cudf::test::fixed_width_column_wrapper<cudf::duration_us> expected2{
cudf::duration_us{3723100001},
cudf::duration_us{3723001000},
cudf::duration_us{3723100000},
cudf::duration_us{3723010000},
cudf::duration_us{3723009800},
cudf::duration_us{3723002340}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*durations, expected2);
}
TEST_F(StringsDatetimeTest, ToTimestampYear)
{
cudf::test::strings_column_wrapper strings{
"28/02/74", "17/07/68", "20/03/19", "29/02/20", "07/02/69"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}, "%d/%m/%y");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> expected{
1519, 35992, 17975, 18321, -328};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(strings_view, "%d/%m/%y");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampWeeks)
{
cudf::test::strings_column_wrapper input{
"2012-01/3", "2012-04/4", "2023-01/1", "2012-52/5", "2020-44/2", "1960-20/0", "1986-04/6"};
auto format = std::string("%Y-%W/%w");
auto results = cudf::strings::to_timestamps(
cudf::strings_column_view(input), cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}, format);
auto expected = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{
15343, 15365, 19359, 15702, 18569, -3511, 5875};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(cudf::strings_column_view(input), format);
auto is_expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
cudf::test::strings_column_wrapper input_iso{
"2012-01/3", "2012-04/4", "2023-01/1", "2012-52/5", "2020-44/2", "1960-20/7", "1986-04/6"};
format = std::string("%Y-%U/%u");
results = cudf::strings::to_timestamps(
cudf::strings_column_view(input_iso), cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}, format);
expected = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{
15342, 15364, 19358, 15701, 18568, -3512, 5874};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::is_timestamp(cudf::strings_column_view(input_iso), format);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
is_expected = cudf::test::fixed_width_column_wrapper<bool>({1, 1, 1, 1, 1, 0, 1});
results = cudf::strings::is_timestamp(cudf::strings_column_view(input), format);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, ToTimestampSingleDigits)
{
cudf::test::strings_column_wrapper strings{"1974-2-28 01:23:45.987000123",
"2019-7-17 2:34:56.001234567",
"2019-3-20 12:34:56.100100100",
"2020-02-2 00:00:00.555777999",
"1969-12-1 00:00:01.000055000",
"1944-07-21 11:15:09.333444000",
"2021-9-8 12:07:30.000000000"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_timestamps(
strings_view, cudf::data_type{cudf::type_id::TIMESTAMP_NANOSECONDS}, "%Y-%m-%d %H:%M:%S.%9f");
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> expected_ns{
131246625987000123,
1563330896001234567,
1553085296100100100,
1580601600555777999,
-2678398999945000,
-803047490666556000,
1631102850000000000};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns);
results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %H:%M:%S.%6f");
cudf::test::fixed_width_column_wrapper<bool> is_expected({1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, is_expected);
}
TEST_F(StringsDatetimeTest, IsTimestamp)
{
cudf::test::strings_column_wrapper strings{"2020-10-07 13:02:03 1PM +0130",
"2020:10:07 01-02-03 1AM +0130",
"2020-10-7 11:02:03 11AM -1025",
"2020-13-07 01:02:03 1AM +0000",
"2020-10-32 01:32:03 1AM +0000",
"2020-10-07 25:02:03 1AM +0000",
"2020-10-07 01:62:03 1AM +0000",
"2020-10-07 01:02:63 1AM +0000",
"2020-02-29 01:32:03 1AM +0000",
"2020-02-30 01:32:03 01AM +0000",
"2020-00-31 01:32:03 1AM +0000",
"2020-02-00 02:32:03 2AM +0000",
"2022-08-24 02:32:60 2AM +0000",
"2020-2-9 9:12:13 9AM +1111"};
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::is_timestamp(strings_view, "%Y-%m-%d %H:%M:%S %I%p %z");
CUDF_TEST_EXPECT_COLUMNS_EQUAL(
*results,
cudf::test::fixed_width_column_wrapper<bool>{1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1});
}
TEST_F(StringsDatetimeTest, FromTimestamp)
{
std::vector<cudf::timestamp_s::rep> h_timestamps{
131246625, 1563399277, 0, 1553085296, 1582934400, -1545730073, -86399};
std::vector<char const*> h_expected{"1974-02-28T01:23:45Z",
"2019-07-17T21:34:37Z",
nullptr,
"2019-03-20T12:34:56Z",
"2020-02-29T00:00:00Z",
"1921-01-07T14:32:07Z",
"1969-12-31T00:00:01Z"};
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps(
h_timestamps.begin(),
h_timestamps.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::from_timestamps(timestamps);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, FromTimestampAmPm)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
1530705600L, 1582934461L, 1451430122L, 1318302183L, -6105994200L};
auto results = cudf::strings::from_timestamps(timestamps, "%Y-%m-%d %I:%M:%S %p");
cudf::test::strings_column_wrapper expected{"2018-07-04 12:00:00 PM",
"2020-02-29 12:01:01 AM",
"2015-12-29 11:02:02 PM",
"2011-10-11 03:03:03 AM",
"1776-07-04 06:30:00 PM"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, FromTimestampMillisecond)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> timestamps_ms{
1530705600123, 1582934461007, 1451430122421, 1318302183999, -6106017600047, 128849018880000};
auto results = cudf::strings::from_timestamps(timestamps_ms, "%Y-%m-%d %H:%M:%S.%3f");
cudf::test::strings_column_wrapper expected_ms{"2018-07-04 12:00:00.123",
"2020-02-29 00:01:01.007",
"2015-12-29 23:02:02.421",
"2011-10-11 03:03:03.999",
"1776-07-04 11:59:59.953",
"6053-01-23 02:08:00.000"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms);
results = cudf::strings::from_timestamps(timestamps_ms, "%Y-%m-%d %H:%M:%S.%f");
cudf::test::strings_column_wrapper expected_ms_6f{"2018-07-04 12:00:00.123000",
"2020-02-29 00:01:01.007000",
"2015-12-29 23:02:02.421000",
"2011-10-11 03:03:03.999000",
"1776-07-04 11:59:59.953000",
"6053-01-23 02:08:00.000000"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ms_6f);
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> timestamps_ns{
1530705600123456789,
1582934461007008009,
1451430122421310209,
1318302183999777555,
-6106017600047047047};
results = cudf::strings::from_timestamps(timestamps_ns, "%Y-%m-%d %H:%M:%S.%9f");
cudf::test::strings_column_wrapper expected_ns{"2018-07-04 12:00:00.123456789",
"2020-02-29 00:01:01.007008009",
"2015-12-29 23:02:02.421310209",
"2011-10-11 03:03:03.999777555",
"1776-07-04 11:59:59.952952953"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns);
results = cudf::strings::from_timestamps(timestamps_ns, "%Y-%m-%d %H:%M:%S.%f");
cudf::test::strings_column_wrapper expected_ns_6f{"2018-07-04 12:00:00.123456",
"2020-02-29 00:01:01.007008",
"2015-12-29 23:02:02.421310",
"2011-10-11 03:03:03.999777",
"1776-07-04 11:59:59.952952"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_ns_6f);
}
TEST_F(StringsDatetimeTest, FromTimestampTimezone)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
1530705600L, 1582934461L, 1451430122L, 1318302183L, -2658802500L};
auto results = cudf::strings::from_timestamps(timestamps, "%m/%d/%y %H%M%S%z");
cudf::test::strings_column_wrapper expected{"07/04/18 120000+0000",
"02/29/20 000101+0000",
"12/29/15 230202+0000",
"10/11/11 030303+0000",
"09/29/85 194500+0000"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, FromTimestampDayOfYear)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
118800L, // 1970-01-02 09:00:00
1293901860L, // 2011-01-01 17:11:00
318402000L, // 1980-02-03 05:00:00
604996200L, // 1989-03-04 06:30:00
1270413572L, // 2010-04-04 20:39:32
1588734621L, // 2020-05-06 03:10:21
2550814152L, // 2050-10-31 07:29:12
4102518778L, // 2100-01-01 20:32:58
702696234L, // 1992-04-08 01:23:54
6516816203L, // 2176-07-05 02:43:23
26472091292L, // 2808-11-12 22:41:32
4133857172L, // 2100-12-30 01:39:32
1560948892L, // 2019-06-19 12:54:52
4115217600L, // 2100-05-28 20:00:00
-265880250L, // 1961-07-29 16:22:30
};
auto results = cudf::strings::from_timestamps(timestamps, "%d/%m/%Y %j");
cudf::test::strings_column_wrapper expected{"02/01/1970 002",
"01/01/2011 001",
"03/02/1980 034",
"04/03/1989 063",
"04/04/2010 094",
"06/05/2020 127",
"31/10/2050 304",
"01/01/2100 001",
"08/04/1992 099",
"05/07/2176 187",
"12/11/2808 317",
"30/12/2100 364",
"19/06/2019 170",
"28/05/2100 148",
"29/07/1961 210"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
// Format names used for some specifiers in from_timestamps
// clang-format off
cudf::test::strings_column_wrapper format_names() {
return cudf::test::strings_column_wrapper({"AM", "PM",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December",
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"});
}
// clang-format on
TEST_F(StringsDatetimeTest, FromTimestampDayOfWeekOfYear)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
1645059720L, // 2022-02-17
1647167880L, // 2022-03-13
1649276040L, // 2022-04-06
1588734621L, // 2020-05-06
1560948892L, // 2019-06-19
-265880250L, // 1961-07-29
1628194442L, // 2021-08-05
1632410760L, // 2021-09-23
1633464842L, // 2021-10-05
1636100042L, // 2021-11-05
// These are a sequence of dates which are particular to the ISO week and
// year numbers which shift through Monday and Thursday and nicely includes
// a leap year (1980). https://en.wikipedia.org/wiki/ISO_week_date
220924800L, // 1977-01-01
221011200L, // 1977-01-02
252374400L, // 1977-12-31
252460800L, // 1978-01-01
252547200L, // 1978-01-02
283910400L, // 1978-12-31
283996800L, // 1979-01-01
315360000L, // 1979-12-30
315446400L, // 1979-12-31
315532800L, // 1980-01-01
346809600L, // 1980-12-28
346896000L, // 1980-12-29
346982400L, // 1980-12-30
347068800L, // 1980-12-31
347155200L, // 1981-01-01
378604800L, // 1981-12-31
378691200L, // 1982-01-01
378777600L, // 1982-01-02
378864000L // 1982-01-03
};
cudf::test::strings_column_wrapper expected(
{"[Thu 17, Feb 2022 4 07 4 07 2022 07]", "[Sun 13, Mar 2022 0 10 7 11 2022 10]",
"[Wed 06, Apr 2022 3 14 3 14 2022 14]", "[Wed 06, May 2020 3 18 3 18 2020 19]",
"[Wed 19, Jun 2019 3 24 3 24 2019 25]", "[Sat 29, Jul 1961 6 30 6 30 1961 30]",
"[Thu 05, Aug 2021 4 31 4 31 2021 31]", "[Thu 23, Sep 2021 4 38 4 38 2021 38]",
"[Tue 05, Oct 2021 2 40 2 40 2021 40]", "[Fri 05, Nov 2021 5 44 5 44 2021 44]",
"[Sat 01, Jan 1977 6 00 6 00 1976 53]", "[Sun 02, Jan 1977 0 00 7 01 1976 53]",
"[Sat 31, Dec 1977 6 52 6 52 1977 52]", "[Sun 01, Jan 1978 0 00 7 01 1977 52]",
"[Mon 02, Jan 1978 1 01 1 01 1978 01]", "[Sun 31, Dec 1978 0 52 7 53 1978 52]",
"[Mon 01, Jan 1979 1 01 1 00 1979 01]", "[Sun 30, Dec 1979 0 52 7 52 1979 52]",
"[Mon 31, Dec 1979 1 53 1 52 1980 01]", "[Tue 01, Jan 1980 2 00 2 00 1980 01]",
"[Sun 28, Dec 1980 0 51 7 52 1980 52]", "[Mon 29, Dec 1980 1 52 1 52 1981 01]",
"[Tue 30, Dec 1980 2 52 2 52 1981 01]", "[Wed 31, Dec 1980 3 52 3 52 1981 01]",
"[Thu 01, Jan 1981 4 00 4 00 1981 01]", "[Thu 31, Dec 1981 4 52 4 52 1981 53]",
"[Fri 01, Jan 1982 5 00 5 00 1981 53]", "[Sat 02, Jan 1982 6 00 6 00 1981 53]",
"[Sun 03, Jan 1982 0 00 7 01 1981 53]"});
auto results = cudf::strings::from_timestamps(timestamps,
"[%a %d, %b %Y %w %W %u %U %G %V]",
cudf::strings_column_view(format_names()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, FromTimestampWeekdayMonthYear)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
1642951560L, // 2022-01-23 15:26:00 Sunday
1645059720L, // 2022-02-17 01:02:00 Thursday
1647167880L, // 2022-03-13 10:38:00 Sunday
1649276040L, // 2022-04-06 20:14:00 Wednesday
1588734621L, // 2020-05-06 03:10:21 Wednesday
1560948892L, // 2019-06-19 12:54:52 Wednesday
-265880250L, // 1961-07-29 16:22:30 Saturday
1628194442L, // 2021-08-05 20:14:02 Thursday
1632410760L, // 2021-09-23 15:26:00 Thursday
1633464842L, // 2021-10-05 20:14:02 Tuesday
1636100042L, // 2021-11-05 08:14:02 Friday
1638757202L // 2021-12-06 02:20:00 Monday
};
cudf::test::strings_column_wrapper expected({"[Sunday January 23, 2022: 03 PM]",
"[Thursday February 17, 2022: 01 AM]",
"[Sunday March 13, 2022: 10 AM]",
"[Wednesday April 06, 2022: 08 PM]",
"[Wednesday May 06, 2020: 03 AM]",
"[Wednesday June 19, 2019: 12 PM]",
"[Saturday July 29, 1961: 04 PM]",
"[Thursday August 05, 2021: 08 PM]",
"[Thursday September 23, 2021: 03 PM]",
"[Tuesday October 05, 2021: 08 PM]",
"[Friday November 05, 2021: 08 AM]",
"[Monday December 06, 2021: 02 AM]"});
auto results = cudf::strings::from_timestamps(
timestamps, "[%A %B %d, %Y: %I %p]", cudf::strings_column_view(format_names()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, FromTimestampAllSpecifiers)
{
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> input{
1645059720000000001L,
1647167880000001000L,
1649276040001000000L,
1588734621123456789L,
1560948892987654321L,
-265880250010203040L,
1628194442090807060L,
1632410760500400300L,
1633464842000000000L,
1636100042999999999L};
auto results = cudf::strings::from_timestamps(
input,
"[%d/%m/%y/%Y %H:%I:%M:%S.%f %z:%Z %j %u %U %W %V %G %p %a %A %b %B]",
cudf::strings_column_view(format_names()));
// clang-format off
cudf::test::strings_column_wrapper expected({
"[17/02/22/2022 01:01:02:00.000000 +0000:UTC 048 4 07 07 07 2022 AM Thu Thursday Feb February]",
"[13/03/22/2022 10:10:38:00.000001 +0000:UTC 072 7 11 10 10 2022 AM Sun Sunday Mar March]",
"[06/04/22/2022 20:08:14:00.001000 +0000:UTC 096 3 14 14 14 2022 PM Wed Wednesday Apr April]",
"[06/05/20/2020 03:03:10:21.123456 +0000:UTC 127 3 18 18 19 2020 AM Wed Wednesday May May]",
"[19/06/19/2019 12:12:54:52.987654 +0000:UTC 170 3 24 24 25 2019 PM Wed Wednesday Jun June]",
"[29/07/61/1961 16:04:22:29.989796 +0000:UTC 210 6 30 30 30 1961 PM Sat Saturday Jul July]",
"[05/08/21/2021 20:08:14:02.090807 +0000:UTC 217 4 31 31 31 2021 PM Thu Thursday Aug August]",
"[23/09/21/2021 15:03:26:00.500400 +0000:UTC 266 4 38 38 38 2021 PM Thu Thursday Sep September]",
"[05/10/21/2021 20:08:14:02.000000 +0000:UTC 278 2 40 40 40 2021 PM Tue Tuesday Oct October]",
"[05/11/21/2021 08:08:14:02.999999 +0000:UTC 309 5 44 44 44 2021 AM Fri Friday Nov November]"});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsDatetimeTest, ZeroSizeStringsColumn)
{
auto const zero_size_column = cudf::make_empty_column(cudf::type_id::TIMESTAMP_SECONDS)->view();
auto results = cudf::strings::from_timestamps(zero_size_column);
cudf::test::expect_column_empty(results->view());
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
results = cudf::strings::to_timestamps(cudf::strings_column_view(zero_size_strings_column),
cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS},
"%Y");
EXPECT_EQ(0, results->size());
}
TEST_F(StringsDatetimeTest, Errors)
{
cudf::test::strings_column_wrapper strings{"this column intentionally left blank"};
cudf::strings_column_view view(strings);
EXPECT_THROW(cudf::strings::to_timestamps(view, cudf::data_type{cudf::type_id::INT64}, "%Y"),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_timestamps(view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, ""),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_timestamps(view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, "%2Y"),
cudf::logic_error);
EXPECT_THROW(
cudf::strings::to_timestamps(view, cudf::data_type{cudf::type_id::TIMESTAMP_SECONDS}, "%g"),
cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> invalid_timestamps{1530705600};
EXPECT_THROW(cudf::strings::from_timestamps(invalid_timestamps), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> timestamps{
1530705600};
EXPECT_THROW(cudf::strings::from_timestamps(timestamps, ""), cudf::logic_error);
EXPECT_THROW(cudf::strings::from_timestamps(timestamps, "%A %B", view), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/factories_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/column/column_factories.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/strings/string_view.cuh>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/execution_policy.h>
#include <thrust/host_vector.h>
#include <thrust/pair.h>
#include <thrust/transform.h>
#include <cstring>
#include <vector>
struct StringsFactoriesTest : public cudf::test::BaseFixture {};
TEST_F(StringsFactoriesTest, CreateColumnFromPair)
{
std::vector<char const*> h_test_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"thé result does not include the value in the sum in",
"",
nullptr,
"absent stop words"};
cudf::size_type memsize = 0;
for (auto itr = h_test_strings.begin(); itr != h_test_strings.end(); ++itr)
memsize += *itr ? (cudf::size_type)strlen(*itr) : 0;
cudf::size_type count = (cudf::size_type)h_test_strings.size();
thrust::host_vector<char> h_buffer(memsize);
rmm::device_uvector<char> d_buffer(memsize, cudf::get_default_stream());
thrust::host_vector<thrust::pair<char const*, cudf::size_type>> strings(count);
thrust::host_vector<cudf::size_type> h_offsets(count + 1);
cudf::size_type offset = 0;
cudf::size_type nulls = 0;
h_offsets[0] = 0;
for (cudf::size_type idx = 0; idx < count; ++idx) {
char const* str = h_test_strings[idx];
if (!str) {
strings[idx] = thrust::pair<char const*, cudf::size_type>{nullptr, 0};
nulls++;
} else {
auto length = (cudf::size_type)strlen(str);
memcpy(h_buffer.data() + offset, str, length);
strings[idx] = thrust::pair<char const*, cudf::size_type>{d_buffer.data() + offset, length};
offset += length;
}
h_offsets[idx + 1] = offset;
}
auto d_strings = cudf::detail::make_device_uvector_sync(
strings, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
CUDF_CUDA_TRY(cudaMemcpy(d_buffer.data(), h_buffer.data(), memsize, cudaMemcpyDefault));
auto column = cudf::make_strings_column(d_strings);
EXPECT_EQ(column->type(), cudf::data_type{cudf::type_id::STRING});
EXPECT_EQ(column->null_count(), nulls);
if (nulls) {
EXPECT_TRUE(column->nullable());
EXPECT_TRUE(column->has_nulls());
}
EXPECT_EQ(2, column->num_children());
cudf::strings_column_view strings_view(column->view());
EXPECT_EQ(strings_view.size(), count);
EXPECT_EQ(strings_view.offsets().size(), count + 1);
EXPECT_EQ(strings_view.chars().size(), memsize);
// check string data
auto h_chars_data = cudf::detail::make_std_vector_sync(
cudf::device_span<char const>(strings_view.chars().data<char>(), strings_view.chars().size()),
cudf::get_default_stream());
auto h_offsets_data = cudf::detail::make_std_vector_sync(
cudf::device_span<cudf::size_type const>(
strings_view.offsets().data<cudf::size_type>() + strings_view.offset(),
strings_view.size() + 1),
cudf::get_default_stream());
EXPECT_EQ(memcmp(h_buffer.data(), h_chars_data.data(), h_buffer.size()), 0);
EXPECT_EQ(
memcmp(h_offsets.data(), h_offsets_data.data(), h_offsets.size() * sizeof(cudf::size_type)), 0);
}
TEST_F(StringsFactoriesTest, CreateColumnFromOffsets)
{
std::vector<char const*> h_test_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"thé result does not include the value in the sum in",
"",
nullptr,
"absent stop words"};
cudf::size_type memsize = 0;
for (auto itr = h_test_strings.begin(); itr != h_test_strings.end(); ++itr)
memsize += *itr ? (cudf::size_type)strlen(*itr) : 0;
cudf::size_type count = (cudf::size_type)h_test_strings.size();
std::vector<char> h_buffer(memsize);
std::vector<cudf::size_type> h_offsets(count + 1);
cudf::size_type offset = 0;
h_offsets[0] = offset;
cudf::bitmask_type h_null_mask = 0;
cudf::size_type null_count = 0;
for (cudf::size_type idx = 0; idx < count; ++idx) {
h_null_mask = (h_null_mask << 1);
char const* str = h_test_strings[idx];
if (str) {
auto length = (cudf::size_type)strlen(str);
memcpy(h_buffer.data() + offset, str, length);
offset += length;
h_null_mask |= 1;
} else
null_count++;
h_offsets[idx + 1] = offset;
}
std::vector<cudf::bitmask_type> h_nulls{h_null_mask};
auto d_buffer = cudf::detail::make_device_uvector_sync(
h_buffer, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto d_offsets = cudf::detail::make_device_uvector_sync(
h_offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto d_nulls = cudf::detail::make_device_uvector_sync(
h_nulls, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto column = cudf::make_strings_column(d_buffer, d_offsets, d_nulls, null_count);
EXPECT_EQ(column->type(), cudf::data_type{cudf::type_id::STRING});
EXPECT_EQ(column->null_count(), null_count);
EXPECT_EQ(2, column->num_children());
cudf::strings_column_view strings_view(column->view());
EXPECT_EQ(strings_view.size(), count);
EXPECT_EQ(strings_view.offsets().size(), count + 1);
EXPECT_EQ(strings_view.chars().size(), memsize);
// check string data
auto h_chars_data = cudf::detail::make_std_vector_sync(
cudf::device_span<char const>(strings_view.chars().data<char>(), strings_view.chars().size()),
cudf::get_default_stream());
auto h_offsets_data = cudf::detail::make_std_vector_sync(
cudf::device_span<cudf::size_type const>(
strings_view.offsets().data<cudf::size_type>() + strings_view.offset(),
strings_view.size() + 1),
cudf::get_default_stream());
EXPECT_EQ(memcmp(h_buffer.data(), h_chars_data.data(), h_buffer.size()), 0);
EXPECT_EQ(
memcmp(h_offsets.data(), h_offsets_data.data(), h_offsets.size() * sizeof(cudf::size_type)), 0);
}
TEST_F(StringsFactoriesTest, CreateScalar)
{
std::string value = "test string";
auto s = cudf::make_string_scalar(value);
auto string_s = static_cast<cudf::string_scalar*>(s.get());
EXPECT_EQ(string_s->to_string(), value);
EXPECT_TRUE(string_s->is_valid());
EXPECT_TRUE(s->is_valid());
}
TEST_F(StringsFactoriesTest, EmptyStringsColumn)
{
rmm::device_uvector<char> d_chars{0, cudf::get_default_stream()};
auto d_offsets = cudf::detail::make_zeroed_device_uvector_sync<cudf::size_type>(
1, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
rmm::device_uvector<cudf::bitmask_type> d_nulls{0, cudf::get_default_stream()};
auto results = cudf::make_strings_column(d_chars, d_offsets, d_nulls, 0);
cudf::test::expect_column_empty(results->view());
rmm::device_uvector<thrust::pair<char const*, cudf::size_type>> d_strings{
0, cudf::get_default_stream()};
results = cudf::make_strings_column(d_strings);
cudf::test::expect_column_empty(results->view());
}
namespace {
using string_pair = thrust::pair<char const*, cudf::size_type>;
struct string_view_to_pair {
__device__ string_pair operator()(thrust::pair<cudf::string_view, bool> const& p)
{
return (p.second) ? string_pair{p.first.data(), p.first.size_bytes()} : string_pair{nullptr, 0};
}
};
} // namespace
TEST_F(StringsFactoriesTest, StringPairWithNullsAndEmpty)
{
cudf::test::strings_column_wrapper data(
{"", "this", "is", "", "a", "", "column", "of", "strings", "", ""},
{0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1});
auto d_column = cudf::column_device_view::create(data);
rmm::device_uvector<string_pair> pairs(d_column->size(), cudf::get_default_stream());
thrust::transform(rmm::exec_policy(cudf::get_default_stream()),
d_column->pair_begin<cudf::string_view, true>(),
d_column->pair_end<cudf::string_view, true>(),
pairs.data(),
string_view_to_pair{});
auto result = cudf::make_strings_column(pairs);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), data);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/findall_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/strings/findall.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsFindallTests : public cudf::test::BaseFixture {};
TEST_F(StringsFindallTests, FindallTest)
{
bool valids[] = {1, 1, 1, 1, 1, 0, 1, 1};
cudf::test::strings_column_wrapper input(
{"3-A", "4-May 5-Day 6-Hay", "12-Dec-2021-Jan", "Feb-March", "4 ABC", "", "", "25-9000-Hal"},
valids);
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("(\\d+)-(\\w+)");
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"3-A"},
LCW{"4-May", "5-Day", "6-Hay"},
LCW{"12-Dec", "2021-Jan"},
LCW{},
LCW{},
LCW{},
LCW{},
LCW{"25-9000"}},
valids);
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::findall(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsFindallTests, Multiline)
{
cudf::test::strings_column_wrapper input({"abc\nfff\nabc", "fff\nabc\nlll", "abc", "", "abc\n"});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("(^abc$)");
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"abc", "abc"}, LCW{"abc"}, LCW{"abc"}, LCW{}, LCW{"abc"}});
auto prog = cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::MULTILINE);
auto results = cudf::strings::findall(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsFindallTests, DotAll)
{
cudf::test::strings_column_wrapper input({"abc\nfa\nef", "fff\nabbc\nfff", "abcdéf", ""});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("(b.*f)");
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"bc\nfa\nef"}, LCW{"bbc\nfff"}, LCW{"bcdéf"}, LCW{}});
auto prog = cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::DOTALL);
auto results = cudf::strings::findall(view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsFindallTests, MediumRegex)
{
// This results in 15 regex instructions and falls in the 'medium' range.
std::string medium_regex = "(\\w+) (\\w+) (\\d+)";
auto prog = cudf::strings::regex_program::create(medium_regex);
cudf::test::strings_column_wrapper input({"first words 1234 and just numbers 9876", "neither"});
auto strings_view = cudf::strings_column_view(input);
auto results = cudf::strings::findall(strings_view, *prog);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"first words 1234", "just numbers 9876"}, LCW{}});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsFindallTests, LargeRegex)
{
// This results in 115 regex instructions and falls in the 'large' range.
std::string large_regex =
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz";
auto prog = cudf::strings::regex_program::create(large_regex);
cudf::test::strings_column_wrapper input(
{"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012"
"34"
"5678901234567890",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"
"op"
"qrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"});
auto strings_view = cudf::strings_column_view(input);
auto results = cudf::strings::findall(strings_view, *prog);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{large_regex.c_str()}, LCW{}, LCW{}});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/find_multiple_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.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/strings/find_multiple.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 <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsFindMultipleTest : public cudf::test::BaseFixture {};
TEST_F(StringsFindMultipleTest, FindMultiple)
{
std::vector<char const*> h_strings{"Héllo", "thesé", nullptr, "lease", "test strings", ""};
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 strings_view = cudf::strings_column_view(strings);
std::vector<char const*> h_targets{"é", "a", "e", "i", "o", "u", "es"};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
auto results = cudf::strings::find_multiple(strings_view, targets_view);
using LCW = cudf::test::lists_column_wrapper<int32_t>;
LCW expected({LCW{1, -1, -1, -1, 4, -1, -1},
LCW{4, -1, 2, -1, -1, -1, 2},
LCW{-1, -1, -1, -1, -1, -1, -1},
LCW{-1, 2, 1, -1, -1, -1, -1},
LCW{-1, -1, 1, 8, -1, -1, 1},
LCW{-1, -1, -1, -1, -1, -1, -1}});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFindMultipleTest, ZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
std::vector<char const*> h_targets{""};
cudf::test::strings_column_wrapper targets(h_targets.begin(), h_targets.end());
auto targets_view = cudf::strings_column_view(targets);
auto results = cudf::strings::find_multiple(strings_view, targets_view);
EXPECT_EQ(results->size(), 0);
}
TEST_F(StringsFindMultipleTest, ErrorTest)
{
cudf::test::strings_column_wrapper strings({"this string intentionally left blank"}, {0});
auto strings_view = cudf::strings_column_view(strings);
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto empty_view = cudf::strings_column_view(zero_size_strings_column);
// targets must have at least one string
EXPECT_THROW(cudf::strings::find_multiple(strings_view, empty_view), cudf::logic_error);
// targets cannot have nulls
EXPECT_THROW(cudf::strings::find_multiple(strings_view, strings_view), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/concatenate_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/column/column_factories.hpp>
#include <cudf/concatenate.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <vector>
struct StringsConcatenateTest : public cudf::test::BaseFixture {};
TEST_F(StringsConcatenateTest, Concatenate)
{
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());
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
std::vector<cudf::column_view> strings_columns;
strings_columns.push_back(strings1);
strings_columns.push_back(zero_size_strings_column);
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(StringsConcatenateTest, ZeroSizeStringsColumns)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
std::vector<cudf::column_view> strings_columns;
strings_columns.push_back(zero_size_strings_column);
strings_columns.push_back(zero_size_strings_column);
strings_columns.push_back(zero_size_strings_column);
auto results = cudf::concatenate(strings_columns);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConcatenateTest, ZeroSizeStringsPlusNormal)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
std::vector<cudf::column_view> strings_columns;
strings_columns.push_back(zero_size_strings_column);
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() + h_strings.size());
strings_columns.push_back(strings1);
auto results = cudf::concatenate(strings_columns);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, strings1);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/fixed_point_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/fixed_point/fixed_point.hpp>
#include <cudf/strings/convert/convert_fixed_point.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <limits>
struct StringsConvertTest : public cudf::test::BaseFixture {};
template <typename T>
class StringsFixedPointConvertTest : public StringsConvertTest {};
TYPED_TEST_SUITE(StringsFixedPointConvertTest, cudf::test::FixedPointTypes);
TYPED_TEST(StringsFixedPointConvertTest, ToFixedPoint)
{
using DecimalType = TypeParam;
using RepType = cudf::device_storage_type_t<DecimalType>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
cudf::test::strings_column_wrapper strings(
{"1.234E3", "-876", "543.2", "-0.12", ".25", "-2E-3", "-.0027", "", "-0.0"});
auto results = cudf::strings::to_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_to_id<DecimalType>(), numeric::scale_type{-3}});
auto const expected =
fp_wrapper{{1234000, -876000, 543200, -120, 250, -2, -2, 0, 0}, numeric::scale_type{-3}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::to_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_to_id<DecimalType>(), numeric::scale_type{2}});
auto const expected_scaled = fp_wrapper{{12, -8, 5, 0, 0, 0, 0, 0, 0}, numeric::scale_type{2}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_scaled);
cudf::test::strings_column_wrapper strings_nulls(
{"1234", "-876", "543", "900000", "25E5", "", ""}, {1, 1, 1, 1, 1, 1, 0});
results = cudf::strings::to_fixed_point(cudf::strings_column_view(strings_nulls),
cudf::data_type{cudf::type_to_id<DecimalType>()});
auto const expected_nulls = fp_wrapper{
{1234, -876, 543, 900000, 2500000, 0, 0}, {1, 1, 1, 1, 1, 1, 0}, numeric::scale_type{0}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected_nulls);
}
TYPED_TEST(StringsFixedPointConvertTest, ToFixedPointVeryLarge)
{
using DecimalType = TypeParam;
using RepType = cudf::device_storage_type_t<DecimalType>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto const strings = cudf::test::strings_column_wrapper({"1234000000000000000000",
"-876000000000000000000",
"5432e+17",
"-12E016",
"250000000000000000",
"-2800000000000000",
"",
"-0.0"});
auto const results = cudf::strings::to_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_to_id<DecimalType>(), numeric::scale_type{20}});
auto const expected = fp_wrapper{{12, -8, 5, 0, 0, 0, 0, 0}, numeric::scale_type{20}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsConvertTest, ToFixedPointDecimal128)
{
using namespace numeric;
using RepType = cudf::device_storage_type_t<decimal128>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto const strings = cudf::test::strings_column_wrapper(
{"1234000000000000000000",
"-876000000000000000000",
"5432e+17",
"-12E016",
"250000000000000000",
"-2800000000000000",
"",
"-0.0",
"170141183460469231731687303715884105727",
"17014118346046923173168730371588410572700000000000000000000"});
auto const scale = scale_type{20};
auto const type = cudf::data_type{cudf::type_to_id<decimal128>(), scale};
auto const results = cudf::strings::to_fixed_point(cudf::strings_column_view(strings), type);
auto const max = cuda::std::numeric_limits<__int128_t>::max();
auto const expected = fp_wrapper{{12, -8, 5, 0, 0, 0, 0, 0, 1701411834604692317, max}, scale};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsConvertTest, ToFixedPointLargeScale)
{
using namespace numeric;
using RepType = cudf::device_storage_type_t<decimal128>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto const strings = cudf::test::strings_column_wrapper({"0.05", "0.06", "0.50", "5.01"});
auto const scale = scale_type{-25};
auto const type = cudf::data_type{cudf::type_to_id<decimal128>(), scale};
auto const results = cudf::strings::to_fixed_point(cudf::strings_column_view(strings), type);
auto const expected = fp_wrapper{{5, 6, 50, 501}, scale_type{-2}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TEST_F(StringsConvertTest, FromFixedPointDecimal128)
{
using namespace numeric;
using RepType = cudf::device_storage_type_t<decimal128>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto constexpr max = cuda::std::numeric_limits<__int128_t>::max();
{
auto const input = fp_wrapper{{110, max}, numeric::scale_type{-2}};
auto results = cudf::strings::from_fixed_point(input);
auto const expected =
cudf::test::strings_column_wrapper({"1.10", "1701411834604692317316873037158841057.27"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto const input = fp_wrapper{{max}, numeric::scale_type{-38}};
auto results = cudf::strings::from_fixed_point(input);
auto const expected =
cudf::test::strings_column_wrapper({"1.70141183460469231731687303715884105727"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto const input = fp_wrapper({110, max}, numeric::scale_type{2});
auto results = cudf::strings::from_fixed_point(input);
auto const expected =
cudf::test::strings_column_wrapper({"11000", "17014118346046923173168730371588410572700"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
auto const input = fp_wrapper({-222}, numeric::scale_type{0});
auto results = cudf::strings::from_fixed_point(input);
auto const expected = cudf::test::strings_column_wrapper({"-222"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
}
TYPED_TEST(StringsFixedPointConvertTest, ToFixedPointVerySmall)
{
using DecimalType = TypeParam;
using RepType = cudf::device_storage_type_t<DecimalType>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto const strings = cudf::test::strings_column_wrapper({"0.00000000000000001234",
"-0.0000000000000000876",
"543.2e-20",
"-12E-18",
"+.000000000000000025",
"-.00000000002147483647",
"",
"+0.0"});
auto const results = cudf::strings::to_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_to_id<DecimalType>(), numeric::scale_type{-20}});
auto const expected =
fp_wrapper{{1234, -8760, 543, -1200, 2500, -2147483647, 0, 0}, numeric::scale_type{-20}};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
TYPED_TEST(StringsFixedPointConvertTest, FromFixedPoint)
{
using DecimalType = TypeParam;
using RepType = cudf::device_storage_type_t<DecimalType>;
using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>;
auto const negative_scale = fp_wrapper{{110, 222, 3330, 4444, -550, -6}, numeric::scale_type{-2}};
auto results = cudf::strings::from_fixed_point(negative_scale);
cudf::test::strings_column_wrapper negative_expected(
{"1.10", "2.22", "33.30", "44.44", "-5.50", "-0.06"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, negative_expected);
auto const positive_scale =
fp_wrapper({110, -222, 3330, 4, -550, 0}, {1, 1, 1, 1, 1, 0}, numeric::scale_type{2});
results = cudf::strings::from_fixed_point(positive_scale);
cudf::test::strings_column_wrapper positive_expected(
{"11000", "-22200", "333000", "400", "-55000", ""}, {1, 1, 1, 1, 1, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, positive_expected);
auto const zero_scale =
fp_wrapper({0, -222, 3330, 4, -550, 0}, {0, 1, 1, 1, 1, 1}, numeric::scale_type{0});
results = cudf::strings::from_fixed_point(zero_scale);
cudf::test::strings_column_wrapper zero_expected({"", "-222", "3330", "4", "-550", "0"},
{0, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, zero_expected);
}
TEST_F(StringsConvertTest, ZeroSizeStringsColumnFixedPoint)
{
auto zero_size_column = cudf::make_empty_column(cudf::data_type{cudf::type_id::DECIMAL32});
auto results = cudf::strings::from_fixed_point(zero_size_column->view());
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConvertTest, ZeroSizeFixedPointColumn)
{
auto zero_size_column = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING});
auto results = cudf::strings::to_fixed_point(zero_size_column->view(),
cudf::data_type{cudf::type_id::DECIMAL32});
EXPECT_EQ(0, results->size());
results = cudf::strings::is_fixed_point(zero_size_column->view());
EXPECT_EQ(0, results->size());
}
TEST_F(StringsConvertTest, FromToFixedPointError)
{
auto dtype = cudf::data_type{cudf::type_id::INT32};
auto column = cudf::make_numeric_column(dtype, 100);
EXPECT_THROW(cudf::strings::from_fixed_point(column->view()), cudf::logic_error);
cudf::test::strings_column_wrapper strings{"this string intentionally left blank"};
cudf::strings_column_view strings_view(strings);
EXPECT_THROW(cudf::strings::to_fixed_point(strings_view, dtype), cudf::logic_error);
EXPECT_THROW(cudf::strings::is_fixed_point(strings_view, dtype), cudf::logic_error);
}
TEST_F(StringsConvertTest, IsFixedPoint)
{
cudf::test::strings_column_wrapper strings(
{"1234", "+876", "543.2", "-00.120", "1E34", "1.0.02", "", "-0.0"});
auto results = cudf::strings::is_fixed_point(cudf::strings_column_view(strings));
auto const expected = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, true, true, false, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::is_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::DECIMAL32, numeric::scale_type{-1}});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
results = cudf::strings::is_fixed_point(
cudf::strings_column_view(strings),
cudf::data_type{cudf::type_id::DECIMAL32, numeric::scale_type{1}});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
cudf::test::strings_column_wrapper big_numbers({"2147483647",
"-2147483647",
"2147483648",
"9223372036854775807",
"-9223372036854775807",
"9223372036854775808",
"9223372036854775808000",
"100E2147483648",
"170141183460469231731687303715884105727",
"170141183460469231731687303715884105728"});
results = cudf::strings::is_fixed_point(cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL32});
auto const expected32 = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, false, false, false, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected32);
results = cudf::strings::is_fixed_point(cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL64});
auto const expected64 = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, true, true, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected64);
results = cudf::strings::is_fixed_point(cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL128});
auto const expected128 = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, true, true, true, true, false, true, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected128);
results = cudf::strings::is_fixed_point(
cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL32, numeric::scale_type{10}});
auto const expected32_scaled = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, true, true, true, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected32_scaled);
results = cudf::strings::is_fixed_point(
cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL64, numeric::scale_type{10}});
auto const expected64_scaled_positive = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, true, true, true, true, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected64_scaled_positive);
results = cudf::strings::is_fixed_point(
cudf::strings_column_view(big_numbers),
cudf::data_type{cudf::type_id::DECIMAL64, numeric::scale_type{-5}});
auto const expected64_scaled = cudf::test::fixed_width_column_wrapper<bool>(
{true, true, true, false, false, false, false, false, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected64_scaled);
}
#ifdef NDEBUG
TEST_F(StringsConvertTest, FixedPointStringConversionOperator)
#else
TEST_F(StringsConvertTest, DISABLED_FixedPointStringConversionOperator)
#endif
{
auto const max = cuda::std::numeric_limits<__int128_t>::max();
auto const x = numeric::decimal128{max, numeric::scale_type{-10}};
EXPECT_EQ(static_cast<std::string>(x), "17014118346046923173168730371.5884105727");
auto const y = numeric::decimal128{max, numeric::scale_type{10}};
EXPECT_EQ(static_cast<std::string>(y), "170141183460469231731687303710000000000");
auto const z = numeric::decimal128{numeric::scaled_integer{max, numeric::scale_type{10}}};
EXPECT_EQ(static_cast<std::string>(z), "1701411834604692317316873037158841057270000000000");
auto const a = numeric::decimal128{numeric::scaled_integer{max, numeric::scale_type{40}}};
EXPECT_EQ(static_cast<std::string>(a),
"1701411834604692317316873037158841057270000000000000000000000000000000000000000");
auto const b = numeric::decimal128{numeric::scaled_integer{max, numeric::scale_type{-20}}};
EXPECT_EQ(static_cast<std::string>(b), "1701411834604692317.31687303715884105727");
auto const c = numeric::decimal128{numeric::scaled_integer{max, numeric::scale_type{-38}}};
EXPECT_EQ(static_cast<std::string>(c), "1.70141183460469231731687303715884105727");
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/floats_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/strings/convert/convert_floats.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
struct StringsConvertTest : public cudf::test::BaseFixture {};
TEST_F(StringsConvertTest, IsFloat)
{
cudf::test::strings_column_wrapper strings;
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::is_float(strings_view);
EXPECT_EQ(cudf::type_id::BOOL8, results->view().type().id());
EXPECT_EQ(0, results->view().size());
cudf::test::strings_column_wrapper strings1({"+175",
"-9.8",
"7+2",
"+-4",
"6.7e17",
"-1.2e-5",
"e",
".e",
"1.e+-2",
"00.00",
"1.0e+1.0",
"1.2.3",
"+",
"--",
""});
results = cudf::strings::is_float(cudf::strings_column_view(strings1));
cudf::test::fixed_width_column_wrapper<bool> expected1(
{1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected1);
cudf::test::strings_column_wrapper strings2(
{"-34", "9.8", "1234567890", "-917.2e5", "INF", "NAN", "-Inf", "INFINITY"});
results = cudf::strings::is_float(cudf::strings_column_view(strings2));
cudf::test::fixed_width_column_wrapper<bool> expected2({1, 1, 1, 1, 1, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected2);
}
TEST_F(StringsConvertTest, ToFloats32)
{
std::vector<char const*> h_strings{
"1234", nullptr, "-876", "543.2",
"-0.12", ".25", "-.002", "",
"-0.0", "1.2e4", "NAN", "abc123",
"123abc", "456e", "-1.78e+5", "-122.33644782123456789",
"12e+309", "3.4028236E38", "INF", "Infinity"};
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<float> h_expected;
std::for_each(h_strings.begin(), h_strings.end(), [&](char const* str) {
h_expected.push_back(str ? std::atof(str) : 0);
});
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_floats(strings_view, cudf::data_type{cudf::type_id::FLOAT32});
cudf::test::fixed_width_column_wrapper<float> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
}
TEST_F(StringsConvertTest, FromFloats32)
{
std::vector<float> h_floats{100,
654321.25,
-12761.125,
0,
5,
-4,
std::numeric_limits<float>::quiet_NaN(),
839542223232.79,
-0.0};
std::vector<char const*> h_expected{
"100.0", "654321.25", "-12761.125", "0.0", "5.0", "-4.0", "NaN", "8.395422433e+11", "-0.0"};
cudf::test::fixed_width_column_wrapper<float> floats(
h_floats.begin(),
h_floats.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::from_floats(floats);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
}
TEST_F(StringsConvertTest, ToFloats64)
{
// clang-format off
std::vector<const char*> h_strings{
"1234", nullptr, "-876", "543.2", "-0.12", ".25",
"-.002", "", "-0.0", "1.28e256", "NaN", "abc123",
"123abc", "456e", "-1.78e+5", "-122.33644782", "12e+309", "1.7976931348623159E308",
"-Inf", "-INFINITY", "1.0", "1.7976931348623157e+308", "1.7976931348623157e-307",
// subnormal numbers: v--- smallest double v--- result is 0
"4e-308", "3.3333333333e-320", "4.940656458412465441765688e-324", "1.e-324" };
// clang-format on
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<double> h_expected;
std::for_each(h_strings.begin(), h_strings.end(), [&](char const* str) {
h_expected.push_back(str ? std::atof(str) : 0);
});
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::to_floats(strings_view, cudf::data_type{cudf::type_id::FLOAT64});
cudf::test::fixed_width_column_wrapper<double> expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
}
TEST_F(StringsConvertTest, FromFloats64)
{
std::vector<double> h_floats{100,
654321.25,
-12761.125,
0,
5,
-4,
std::numeric_limits<double>::quiet_NaN(),
839542223232.794248339,
-0.0};
std::vector<char const*> h_expected{
"100.0", "654321.25", "-12761.125", "0.0", "5.0", "-4.0", "NaN", "8.395422232e+11", "-0.0"};
cudf::test::fixed_width_column_wrapper<double> floats(
h_floats.begin(),
h_floats.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::from_floats(floats);
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
}
TEST_F(StringsConvertTest, ZeroSizeStringsColumnFloat)
{
cudf::column_view zero_size_column(
cudf::data_type{cudf::type_id::FLOAT32}, 0, nullptr, nullptr, 0);
auto results = cudf::strings::from_floats(zero_size_column);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConvertTest, ZeroSizeFloatsColumn)
{
cudf::column_view zero_size_column(
cudf::data_type{cudf::type_id::STRING}, 0, nullptr, nullptr, 0);
auto results =
cudf::strings::to_floats(zero_size_column, cudf::data_type{cudf::type_id::FLOAT32});
EXPECT_EQ(0, results->size());
}
TEST_F(StringsConvertTest, FromToFloatsError)
{
auto dtype = cudf::data_type{cudf::type_id::INT32};
auto column = cudf::make_numeric_column(dtype, 100);
EXPECT_THROW(cudf::strings::from_floats(column->view()), cudf::logic_error);
cudf::test::strings_column_wrapper strings{"this string intentionally left blank"};
EXPECT_THROW(cudf::strings::to_floats(column->view(), dtype), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/repeat_strings_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/scalar/scalar.hpp>
#include <cudf/strings/repeat_strings.hpp>
#include <cudf/strings/strings_column_view.hpp>
using namespace cudf::test::iterators;
namespace {
using strs_col = cudf::test::strings_column_wrapper;
using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>;
constexpr int32_t null{0}; // mark for null elements in a column of int32_t values
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR};
} // namespace
struct RepeatStringsTest : public cudf::test::BaseFixture {};
template <typename T>
struct RepeatStringsTypedTest : public cudf::test::BaseFixture {};
// Test for signed types only, as we will need to use non-positive values.
using TypesForTest = cudf::test::Types<int8_t, int16_t, int32_t, int64_t>;
TYPED_TEST_SUITE(RepeatStringsTypedTest, TypesForTest);
TYPED_TEST(RepeatStringsTypedTest, InvalidStringScalar)
{
auto const str = cudf::string_scalar("", false);
auto const result = cudf::strings::repeat_string(str, 3);
EXPECT_EQ(result->is_valid(), false);
}
TYPED_TEST(RepeatStringsTypedTest, ZeroSizeStringScalar)
{
auto const str = cudf::string_scalar("");
auto const result = cudf::strings::repeat_string(str, 3);
EXPECT_EQ(result->is_valid(), true);
EXPECT_EQ(result->size(), 0);
}
TYPED_TEST(RepeatStringsTypedTest, ValidStringScalar)
{
auto const str = cudf::string_scalar("abc123xyz-");
{
auto const result = cudf::strings::repeat_string(str, 3);
auto const expected_strs = cudf::string_scalar("abc123xyz-abc123xyz-abc123xyz-");
CUDF_TEST_EXPECT_EQUAL_BUFFERS(expected_strs.data(), result->data(), expected_strs.size());
}
// Repeat once.
{
auto const result = cudf::strings::repeat_string(str, 1);
CUDF_TEST_EXPECT_EQUAL_BUFFERS(str.data(), result->data(), str.size());
}
// Zero repeat times.
{
auto const result = cudf::strings::repeat_string(str, 0);
EXPECT_EQ(result->is_valid(), true);
EXPECT_EQ(result->size(), 0);
}
// Negative repeat times.
{
auto const result = cudf::strings::repeat_string(str, -10);
EXPECT_EQ(result->is_valid(), true);
EXPECT_EQ(result->size(), 0);
}
// Repeat too many times.
{
EXPECT_THROW(cudf::strings::repeat_string(str, std::numeric_limits<int32_t>::max() / 2),
std::overflow_error);
}
}
TYPED_TEST(RepeatStringsTypedTest, ZeroSizeStringsColumnWithScalarRepeatTimes)
{
auto const strs = strs_col{};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, ZeroSizeStringsColumnWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{};
auto const repeat_times = ints_col{};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, AllEmptyStringsColumnWithScalarRepeatTimes)
{
auto const strs = strs_col{"", "", "", "", ""};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, AllEmptyStringsColumnWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{"", "", "", "", ""};
auto const repeat_times = ints_col{-2, -1, 0, 1, 2};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, AllNullStringsColumnWithScalarRepeatTimes)
{
auto const strs = strs_col{{"" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, all_nulls()};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, AllNullStringsColumnWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{{"" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, all_nulls()};
auto const strs_cv = cudf::strings_column_view(strs);
// The repeat_times column contains all valid numbers.
{
auto const repeat_times = ints_col{-1, 0, 1};
auto const results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// The repeat_times column also contains some nulls and some valid numbers.
{
auto const repeat_times = ints_col{{null, 1, null}, nulls_at({0, 2})};
auto const results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// The repeat_times column also contains all nulls.
{
auto const repeat_times = ints_col{{null, null, null}, all_nulls()};
auto const results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, StringsColumnWithAllNullColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{"ABC", "abc", "xyz"};
auto const repeat_times = ints_col{{null, null, null}, all_nulls()};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), repeat_times);
auto const expected_strs = strs_col{{"" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, all_nulls()};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, ZeroSizeAndNullStringsColumnWithScalarRepeatTimes)
{
auto const strs =
strs_col{{"" /*NULL*/, "", "" /*NULL*/, "", "", "" /*NULL*/}, nulls_at({0, 2, 5})};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TYPED_TEST(RepeatStringsTypedTest, ZeroSizeAndNullStringsColumnWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs =
strs_col{{"" /*NULL*/, "", "" /*NULL*/, "", "", "" /*NULL*/}, nulls_at({0, 2, 5})};
auto const repeat_times = ints_col{1, 2, 3, 4, 5, 6};
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(strs), 10);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
TEST_F(RepeatStringsTest, StringsColumnWithColumnRepeatTimesInvalidInput)
{
auto const strs = strs_col{"abc", "xyz"};
auto const strs_cv = cudf::strings_column_view(strs);
// Sizes mismatched between strings column and repeat_times column.
{
auto const repeat_times = int32s_col{1, 2, 3, 4, 5, 6};
EXPECT_THROW(cudf::strings::repeat_strings(strs_cv, repeat_times), cudf::logic_error);
}
// Invalid data type for repeat_times column.
{
auto const repeat_times = cudf::test::fixed_width_column_wrapper<float>{1, 2, 3, 4, 5, 6};
EXPECT_THROW(cudf::strings::repeat_strings(strs_cv, repeat_times), cudf::logic_error);
}
// Invalid data type for repeat_times column.
{
auto const repeat_times = strs_col{"xxx", "xxx"};
EXPECT_THROW(cudf::strings::repeat_strings(strs_cv, repeat_times), cudf::logic_error);
}
}
TEST_F(RepeatStringsTest, StringsColumnWithColumnRepeatTimesOverflowOutput)
{
auto const strs = strs_col{"1", "12", "123", "1234", "12345", "123456", "1234567"};
auto const strs_cv = cudf::strings_column_view(strs);
auto const half_max = std::numeric_limits<int32_t>::max() / 2;
auto const repeat_times =
int32s_col{half_max, half_max, half_max, half_max, half_max, half_max, half_max};
EXPECT_THROW(cudf::strings::repeat_strings(strs_cv, repeat_times), std::overflow_error);
}
TYPED_TEST(RepeatStringsTypedTest, StringsColumnNoNullWithScalarRepeatTimes)
{
auto const strs = strs_col{"0a0b0c", "abcxyz", "xyzééé", "ááá", "íí"};
auto const strs_cv = cudf::strings_column_view(strs);
{
auto const results = cudf::strings::repeat_strings(strs_cv, 2);
auto const expected_strs =
strs_col{"0a0b0c0a0b0c", "abcxyzabcxyz", "xyzéééxyzééé", "áááááá", "íííí"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Repeat once.
{
auto const results = cudf::strings::repeat_strings(strs_cv, 1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// Non-positive repeat times.
{
auto const expected_strs = strs_col{"", "", "", "", ""};
auto results = cudf::strings::repeat_strings(strs_cv, 0);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
results = cudf::strings::repeat_strings(strs_cv, -100);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, StringsColumnNoNullWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{"0a0b0c", "abcxyz", "xyzééé", "ááá", "íí"};
auto const strs_cv = cudf::strings_column_view(strs);
// Repeat once.
{
auto const repeat_times = ints_col{1, 1, 1, 1, 1};
auto const results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// repeat_times column has negative values.
{
auto const repeat_times = ints_col{1, 2, 3, -1, -2};
auto const expected_strs = strs_col{"0a0b0c", "abcxyzabcxyz", "xyzéééxyzéééxyzééé", "", ""};
auto results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// repeat_times column has nulls.
{
auto const repeat_times = ints_col{{1, null, 3, 2, null}, nulls_at({1, 4})};
auto const expected_strs = strs_col{
{"0a0b0c", "" /*NULL*/, "xyzéééxyzéééxyzééé", "áááááá", "" /*NULL*/}, nulls_at({1, 4})};
auto results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, SlicedStringsColumnNoNullWithScalarRepeatTimes)
{
auto const strs = strs_col{"0a0b0c", "abcxyz", "xyzééé", "ááá", "íí"};
// Sliced the first half of the column.
{
auto const sliced_strs = cudf::slice(strs, {0, 3})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{"0a0b0c0a0b0c", "abcxyzabcxyz", "xyzéééxyzééé"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the middle of the column.
{
auto const sliced_strs = cudf::slice(strs, {1, 3})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{"abcxyzabcxyz", "xyzéééxyzééé"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the second half of the column.
{
auto const sliced_strs = cudf::slice(strs, {2, 5})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{"xyzéééxyzééé", "áááááá", "íííí"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, SlicedStringsColumnNoNullWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{"0a0b0c", "abcxyz", "xyzééé", "ááá", "íí"};
auto const repeat_times = ints_col{1, 2, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Sliced the first half of the column.
{
auto const sliced_strs = cudf::slice(strs, {0, 3})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {0, 3})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{"0a0b0c", "abcxyzabcxyz", "xyzéééxyzéééxyzééé"};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the middle of the column.
{
auto const sliced_strs = cudf::slice(strs, {1, 3})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {1, 3})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{"abcxyzabcxyz", "xyzéééxyzéééxyzééé"};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the second half of the column.
{
auto const sliced_strs = cudf::slice(strs, {2, 5})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {2, 5})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{"xyzéééxyzéééxyzééé", "áááááá", "íííííí"};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, StringsColumnWithNullsWithScalarRepeatTimes)
{
auto const strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"abcxyz",
"" /*NULL*/,
"xyzééé",
"" /*NULL*/,
"ááá",
"íí",
"",
"Hello World"},
nulls_at({1, 3, 5})};
auto const strs_cv = cudf::strings_column_view(strs);
{
auto const results = cudf::strings::repeat_strings(strs_cv, 2);
auto const expected_strs = strs_col{{"0a0b0c0a0b0c",
"" /*NULL*/,
"abcxyzabcxyz",
"" /*NULL*/,
"xyzéééxyzééé",
"" /*NULL*/,
"áááááá",
"íííí",
"",
"Hello WorldHello World"},
nulls_at({1, 3, 5})};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Repeat once.
{
auto const results = cudf::strings::repeat_strings(strs_cv, 1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// Non-positive repeat times.
{
auto const expected_strs = strs_col{
{"", "" /*NULL*/, "", "" /*NULL*/, "", "" /*NULL*/, "", "", "", ""}, nulls_at({1, 3, 5})};
auto results = cudf::strings::repeat_strings(strs_cv, 0);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
results = cudf::strings::repeat_strings(strs_cv, -100);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, StringsColumnWithNullsWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"abcxyz",
"" /*NULL*/,
"xyzééé",
"" /*NULL*/,
"ááá",
"íí",
"",
"Hello World"},
nulls_at({1, 3, 5})};
auto const strs_cv = cudf::strings_column_view(strs);
// Repeat once.
{
auto const repeat_times = ints_col{1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
auto const results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strs, *results, verbosity);
}
// repeat_times column has negative values.
{
auto const repeat_times = ints_col{1, 2, 3, -1, -2, 1, 2, 3, -5, 0};
auto const expected_strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"abcxyzabcxyzabcxyz",
"" /*NULL*/,
"",
"" /*NULL*/,
"áááááá",
"íííííí",
"",
""},
nulls_at({1, 3, 5})};
auto results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// repeat_times column has nulls.
{
auto const repeat_times =
ints_col{{1, 2, null, -1, null, 1, 2, null, -5, 0}, nulls_at({2, 4, 7})};
auto const expected_strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"" /*NULL*/,
"" /*NULL*/,
"" /*NULL*/,
"" /*NULL*/,
"áááááá",
"" /*NULL*/,
"",
""},
nulls_at({1, 2, 3, 4, 5, 7})};
auto results = cudf::strings::repeat_strings(strs_cv, repeat_times);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, SlicedStringsColumnWithNullsWithScalarRepeatTimes)
{
auto const strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"abcxyz",
"" /*NULL*/,
"xyzééé",
"" /*NULL*/,
"ááá",
"íí",
"",
"Hello World"},
nulls_at({1, 3, 5})};
// Sliced the first half of the column.
{
auto const sliced_strs = cudf::slice(strs, {0, 3})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{{"0a0b0c0a0b0c", "" /*NULL*/, "abcxyzabcxyz"}, null_at(1)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the middle of the column.
{
auto const sliced_strs = cudf::slice(strs, {2, 7})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{
{"abcxyzabcxyz", "" /*NULL*/, "xyzéééxyzééé", "" /*NULL*/, "áááááá"}, nulls_at({1, 3})};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the second half of the column.
{
auto const sliced_strs = cudf::slice(strs, {6, 10})[0];
auto const results = cudf::strings::repeat_strings(cudf::strings_column_view(sliced_strs), 2);
auto const expected_strs = strs_col{"áááááá", "íííí", "", "Hello WorldHello World"};
// The results strings column may have a bitmask with all valid values.
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_strs, *results, verbosity);
}
}
TYPED_TEST(RepeatStringsTypedTest, SlicedStringsColumnWithNullsWithColumnRepeatTimes)
{
using ints_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const strs = strs_col{{"0a0b0c",
"" /*NULL*/,
"abcxyz",
"" /*NULL*/,
"xyzééé",
"" /*NULL*/,
"ááá",
"íí",
"",
"Hello World"},
nulls_at({1, 3, 5})};
auto const repeat_times =
ints_col{{1, 2, null, -1, null, 1, 2, null, -5, 0, 6, 7, 8, 9, 10}, nulls_at({2, 4, 7})};
// Sliced the first half of the column.
{
auto const sliced_strs = cudf::slice(strs, {0, 3})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {0, 3})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{{"0a0b0c", "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2})};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the middle of the column.
{
auto const sliced_strs = cudf::slice(strs, {2, 7})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {2, 7})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{
{"" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "áááááá"}, nulls_at({0, 1, 2, 3})};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the second half of the column, output has nulls.
{
auto const sliced_strs = cudf::slice(strs, {6, 10})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {6, 10})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{{"áááááá", "" /*NULL*/, "", ""}, null_at(1)};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_strs, *results, verbosity);
}
// Sliced the second half of the column, output does not have null.
// Since the input has nulls, the output column is nullable (but doesn't have nulls).
{
auto const sliced_strs = cudf::slice(strs, {8, 10})[0];
auto const sliced_rtimes = cudf::slice(repeat_times, {8, 10})[0];
auto const sliced_strs_cv = cudf::strings_column_view(sliced_strs);
auto const expected_strs = strs_col{"", ""};
auto results = cudf::strings::repeat_strings(sliced_strs_cv, sliced_rtimes);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_strs, *results, verbosity);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/format_lists_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/iterator_utilities.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/convert/convert_lists.hpp>
struct StringsFormatListsTest : public cudf::test::BaseFixture {};
TEST_F(StringsFormatListsTest, EmptyList)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input = STR_LISTS{};
auto const view = cudf::lists_column_view(input);
auto results = cudf::strings::format_list_column(view);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsFormatListsTest, EmptyNestedList)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input = STR_LISTS{STR_LISTS{STR_LISTS{}, STR_LISTS{}}, STR_LISTS{STR_LISTS{}}};
auto const view = cudf::lists_column_view(input);
auto results = cudf::strings::format_list_column(view);
auto expected = cudf::test::strings_column_wrapper({"[[],[]]", "[[]]"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFormatListsTest, WithNulls)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input = STR_LISTS{{STR_LISTS{{"a", "", "ccc"}, cudf::test::iterators::null_at(1)},
STR_LISTS{},
STR_LISTS{{"", "bb", "ddd"}, cudf::test::iterators::null_at(0)},
STR_LISTS{"zzz", "xxxxx"},
STR_LISTS{{"v", "", "", "w"}, cudf::test::iterators::null_at(2)}},
cudf::test::iterators::null_at(1)};
auto const view = cudf::lists_column_view(input);
auto null_scalar = cudf::string_scalar("NULL");
auto results = cudf::strings::format_list_column(view, null_scalar);
auto expected = cudf::test::strings_column_wrapper(
{"[a,NULL,ccc]", "NULL", "[NULL,bb,ddd]", "[zzz,xxxxx]", "[v,,NULL,w]"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFormatListsTest, CustomParameters)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input =
STR_LISTS{STR_LISTS{{STR_LISTS{{"a", "", "ccc"}, cudf::test::iterators::null_at(1)},
STR_LISTS{},
STR_LISTS{"ddd", "ee", "f"}},
cudf::test::iterators::null_at(1)},
{STR_LISTS{"gg", "hhh"}, STR_LISTS{"i", "", "", "jj"}}};
auto const view = cudf::lists_column_view(input);
auto separators = cudf::test::strings_column_wrapper({": ", "{", "}"});
auto results = cudf::strings::format_list_column(
view, cudf::string_scalar("null"), cudf::strings_column_view(separators));
auto expected = cudf::test::strings_column_wrapper(
{"{{a: null: ccc}: null: {ddd: ee: f}}", "{{gg: hhh}: {i: : : jj}}"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFormatListsTest, NestedList)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input =
STR_LISTS{{STR_LISTS{"a", "bb", "ccc"}, STR_LISTS{}, STR_LISTS{"ddd", "ee", "f"}},
{STR_LISTS{"gg", "hhh"}, STR_LISTS{"i", "", "", "jj"}}};
auto const view = cudf::lists_column_view(input);
auto results = cudf::strings::format_list_column(view);
auto expected =
cudf::test::strings_column_wrapper({"[[a,bb,ccc],[],[ddd,ee,f]]", "[[gg,hhh],[i,,,jj]]"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsFormatListsTest, SlicedLists)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
auto const input =
STR_LISTS{{STR_LISTS{{"a", "", "bb"}, cudf::test::iterators::null_at(1)},
STR_LISTS{},
STR_LISTS{{"", "ccc", "dddd"}, cudf::test::iterators::null_at(0)},
STR_LISTS{"zzz", ""},
STR_LISTS{},
STR_LISTS{{"abcdef", "012345", "", ""}, cudf::test::iterators::null_at(2)},
STR_LISTS{{"", "11111", "00000"}, cudf::test::iterators::null_at(0)},
STR_LISTS{"hey hey", "way way"},
STR_LISTS{},
STR_LISTS{"ééé", "12345abcdef"},
STR_LISTS{"www", "12345"}},
cudf::test::iterators::nulls_at({1, 4, 8})};
// matching expected strings
auto const h_expected = std::vector<std::string>({"[a,NULL,bb]",
"NULL",
"[NULL,ccc,dddd]",
"[zzz,]",
"NULL",
"[abcdef,012345,NULL,]",
"[NULL,11111,00000]",
"[hey hey,way way]",
"NULL",
"[ééé,12345abcdef]",
"[www,12345]"});
auto null_scalar = cudf::string_scalar("NULL");
// set of slice intervals: covers slicing the front, back, and middle
std::vector<std::pair<int32_t, int32_t>> index_pairs({{0, 11}, {0, 4}, {3, 8}, {5, 11}});
for (auto indexes : index_pairs) {
auto sliced = cudf::lists_column_view(cudf::slice(input, {indexes.first, indexes.second})[0]);
auto results = cudf::strings::format_list_column(sliced, null_scalar);
auto expected = cudf::test::strings_column_wrapper(h_expected.begin() + indexes.first,
h_expected.begin() + indexes.second);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsFormatListsTest, Errors)
{
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
cudf::test::lists_column_wrapper<int32_t> invalid({1, 2, 3});
EXPECT_THROW(cudf::strings::format_list_column(cudf::lists_column_view(invalid)),
cudf::logic_error);
auto const input = STR_LISTS{STR_LISTS{}, STR_LISTS{}};
auto const view = cudf::lists_column_view(input);
auto separators = cudf::test::strings_column_wrapper({"{", "}"});
EXPECT_THROW(cudf::strings::format_list_column(
view, cudf::string_scalar(""), cudf::strings_column_view(separators)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::format_list_column(view, cudf::string_scalar("", false)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/replace_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/column/column.hpp>
#include <cudf/strings/detail/replace.hpp>
#include <cudf/strings/replace.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
using algorithm = cudf::strings::detail::replace_algorithm;
struct StringsReplaceTest : public cudf::test::BaseFixture {
cudf::test::strings_column_wrapper build_corpus()
{
std::vector<char const*> h_strings{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"The result does not include the value in the sum in",
"",
nullptr};
return cudf::test::strings_column_wrapper(
h_strings.begin(),
h_strings.end(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
}
};
TEST_F(StringsReplaceTest, Replace)
{
auto input = build_corpus();
auto strings_view = cudf::strings_column_view(input);
// replace all occurrences of 'the ' with '++++ '
std::vector<char const*> h_expected{"++++ quick brown fox jumps over ++++ lazy dog",
"++++ fat cat lays next to ++++ other accénted cat",
"a slow moving turtlé cannot catch ++++ bird",
"which can be composéd together to form a more complete",
"The result does not include ++++ value in ++++ sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("the "), cudf::string_scalar("++++ "));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("the "), cudf::string_scalar("++++ "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("the "), cudf::string_scalar("++++ "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceTest, ReplaceReplLimit)
{
auto input = build_corpus();
auto strings_view = cudf::strings_column_view(input);
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
// only remove the first occurrence of 'the '
std::vector<char const*> h_expected{"quick brown fox jumps over the lazy dog",
"fat cat lays next to the other accénted cat",
"a slow moving turtlé cannot catch bird",
"which can be composéd together to form a more complete",
"The result does not include value in the sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("the "), cudf::string_scalar(""), 1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("the "), cudf::string_scalar(""), 1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("the "), cudf::string_scalar(""), 1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceTest, ReplaceReplLimitInputSliced)
{
auto input = build_corpus();
// replace first two occurrences of ' ' with '--'
std::vector<char const*> h_expected{"the--quick--brown fox jumps over the lazy dog",
"the--fat--cat lays next to the other accénted cat",
"a--slow--moving turtlé cannot catch the bird",
"which--can--be composéd together to form a more complete",
"The--result--does not include the value in the sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
std::vector<cudf::size_type> slice_indices{0, 2, 2, 3, 3, 7};
auto sliced_strings = cudf::slice(input, slice_indices);
auto sliced_expected = cudf::slice(expected, slice_indices);
for (size_t i = 0; i < sliced_strings.size(); ++i) {
auto strings_view = cudf::strings_column_view(sliced_strings[i]);
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar(" "), cudf::string_scalar("--"), 2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, sliced_expected[i]);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar(" "), cudf::string_scalar("--"), 2, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, sliced_expected[i]);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar(" "), cudf::string_scalar("--"), 2, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, sliced_expected[i]);
}
}
TEST_F(StringsReplaceTest, ReplaceTargetOverlap)
{
auto corpus = build_corpus();
auto corpus_view = cudf::strings_column_view(corpus);
// replace all occurrences of 'the ' with '+++++++ '
auto input = cudf::strings::replace(
corpus_view, cudf::string_scalar("the "), cudf::string_scalar("++++++++ "));
auto strings_view = cudf::strings_column_view(*input);
// replace all occurrences of '+++' with 'plus '
std::vector<char const*> h_expected{
"plus plus ++ quick brown fox jumps over plus plus ++ lazy dog",
"plus plus ++ fat cat lays next to plus plus ++ other accénted cat",
"a slow moving turtlé cannot catch plus plus ++ bird",
"which can be composéd together to form a more complete",
"The result does not include plus plus ++ value in plus plus ++ sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("+++"), cudf::string_scalar("plus "));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("+++"), cudf::string_scalar("plus "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("+++"), cudf::string_scalar("plus "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceTest, ReplaceTargetOverlapsStrings)
{
auto input = build_corpus();
auto strings_view = cudf::strings_column_view(input);
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
// replace all occurrences of 'dogthe' with '+'
// should not replace anything unless it incorrectly matches across a string boundary
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("dogthe"), cudf::string_scalar("+"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("dogthe"), cudf::string_scalar("+"), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("dogthe"), cudf::string_scalar("+"), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
}
TEST_F(StringsReplaceTest, ReplaceNullInput)
{
std::vector<char const*> h_null_strings(128);
auto input = cudf::test::strings_column_wrapper(
h_null_strings.begin(), h_null_strings.end(), thrust::make_constant_iterator(false));
auto strings_view = cudf::strings_column_view(input);
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
// replace all occurrences of '+' with ''
// should not replace anything as input is all null
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("+"), cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("+"), cudf::string_scalar(""), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("+"), cudf::string_scalar(""), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, input);
}
TEST_F(StringsReplaceTest, ReplaceEndOfString)
{
auto input = build_corpus();
auto strings_view = cudf::strings_column_view(input);
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
// replace all occurrences of 'in' with ' '
std::vector<char const*> h_expected{"the quick brown fox jumps over the lazy dog",
"the fat cat lays next to the other accénted cat",
"a slow mov g turtlé cannot catch the bird",
"which can be composéd together to form a more complete",
"The result does not clude the value the sum ",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(), h_expected.end(), cudf::test::iterators::nulls_from_nullptrs(h_expected));
auto results =
cudf::strings::replace(strings_view, cudf::string_scalar("in"), cudf::string_scalar(" "));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<cudf::strings::detail::replace_algorithm::CHAR_PARALLEL>(
strings_view, cudf::string_scalar("in"), cudf::string_scalar(" "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<cudf::strings::detail::replace_algorithm::ROW_PARALLEL>(
strings_view, cudf::string_scalar("in"), cudf::string_scalar(" "), -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceTest, ReplaceAdjacentMultiByteTarget)
{
auto input = cudf::test::strings_column_wrapper({"ééééééé", "eéeéeée", "eeeeeee"});
auto strings_view = cudf::strings_column_view(input);
// replace all occurrences of 'é' with 'e'
cudf::test::strings_column_wrapper expected({"eeeeeee", "eeeeeee", "eeeeeee"});
auto stream = cudf::get_default_stream();
auto mr = rmm::mr::get_current_device_resource();
auto target = cudf::string_scalar("é", true, stream);
auto repl = cudf::string_scalar("e", true, stream);
auto results = cudf::strings::replace(strings_view, target, repl);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::CHAR_PARALLEL>(
strings_view, target, repl, -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
results = cudf::strings::detail::replace<algorithm::ROW_PARALLEL>(
strings_view, target, repl, -1, stream, mr);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsReplaceTest, ReplaceSlice)
{
std::vector<char const*> h_strings{"Héllo", "thesé", nullptr, "ARE THE", "tést strings", ""};
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 strings_view = cudf::strings_column_view(strings);
{
auto results = cudf::strings::replace_slice(strings_view, cudf::string_scalar("___"), 2, 3);
std::vector<char const*> h_expected{
"Hé___lo", "th___sé", nullptr, "AR___ THE", "té___t strings", "___"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::replace_slice(strings_view, cudf::string_scalar("||"), 3, 3);
std::vector<char const*> h_expected{
"Hél||lo", "the||sé", nullptr, "ARE|| THE", "tés||t strings", "||"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::replace_slice(strings_view, cudf::string_scalar("x"), -1, -1);
std::vector<char const*> h_expected{
"Héllox", "theséx", nullptr, "ARE THEx", "tést stringsx", "x"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsReplaceTest, ReplaceSliceError)
{
cudf::test::strings_column_wrapper input({"Héllo", "thesé", "are not", "important", ""});
EXPECT_THROW(
cudf::strings::replace_slice(cudf::strings_column_view(input), cudf::string_scalar(""), 4, 1),
cudf::logic_error);
}
TEST_F(StringsReplaceTest, ReplaceMulti)
{
auto input = build_corpus();
auto strings_view = cudf::strings_column_view(input);
cudf::test::strings_column_wrapper targets({"the ", "a ", "to "});
auto targets_view = cudf::strings_column_view(targets);
{
cudf::test::strings_column_wrapper repls({"_ ", "A ", "2 "});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace(strings_view, targets_view, repls_view);
std::vector<char const*> h_expected{"_ quick brown fox jumps over _ lazy dog",
"_ fat cat lays next 2 _ other accénted cat",
"A slow moving turtlé cannot catch _ bird",
"which can be composéd together 2 form A more complete",
"The result does not include _ value in _ sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::strings_column_wrapper repls({"* "});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace(strings_view, targets_view, repls_view);
std::vector<char const*> h_expected{"* quick brown fox jumps over * lazy dog",
"* fat cat lays next * * other accénted cat",
"* slow moving turtlé cannot catch * bird",
"which can be composéd together * form * more complete",
"The result does not include * value in * sum in",
"",
nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsReplaceTest, ReplaceMultiLong)
{
// The length of the strings are to trigger the code path governed by the AVG_CHAR_BYTES_THRESHOLD
// setting in the multi.cu.
auto input = cudf::test::strings_column_wrapper(
{"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions.",
"012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012"
"345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
"678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
"901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"
"2345678901234567890123456789",
"012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012"
"345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345"
"678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
"901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"
"2345678901234567890123456789",
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá",
"",
""},
{1, 1, 1, 1, 0, 1});
auto strings_view = cudf::strings_column_view(input);
auto targets = cudf::test::strings_column_wrapper({"78901", "bananá", "ápple", "78"});
auto targets_view = cudf::strings_column_view(targets);
{
cudf::test::strings_column_wrapper repls({"x", "PEAR", "avocado", "$$"});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace(strings_view, targets_view, repls_view);
cudf::test::strings_column_wrapper expected(
{"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions.",
"0123456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456"
"x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x"
"23456x23456x23456x23456x23456x23456x23456x23456x23456x23456$$9",
"0123456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456"
"x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x23456x"
"23456x23456x23456x23456x23456x23456x23456x23456x23456x23456$$9",
"Test string for overlap check: bananaavocado PEAR avocadoPEAR banavocado avocado PEAR "
"Test string for overlap check: bananaavocado PEAR avocadoPEAR banavocado avocado PEAR "
"Test string for overlap check: bananaavocado PEAR avocadoPEAR banavocado avocado PEAR "
"Test string for overlap check: bananaavocado PEAR avocadoPEAR banavocado avocado PEAR "
"Test string for overlap check: bananaavocado PEAR avocadoPEAR banavocado avocado PEAR",
"",
""},
{1, 1, 1, 1, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
cudf::test::strings_column_wrapper repls({"*"});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace(strings_view, targets_view, repls_view);
cudf::test::strings_column_wrapper expected(
{"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions.",
"0123456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*"
"23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*"
"23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*9",
"0123456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*"
"23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*"
"23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*23456*9",
"Test string for overlap check: banana* * ** ban* * * Test string for overlap check: "
"banana* * ** ban* * * Test string for overlap check: banana* * ** ban* * * Test string for "
"overlap check: banana* * ** ban* * * Test string for overlap check: banana* * ** ban* * *",
"",
""},
{1, 1, 1, 1, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
targets =
cudf::test::strings_column_wrapper({"01234567890123456789012345678901234567890123456789012345"
"6789012345678901234567890123456789012"
"34567890123456789012345678901234567890123456789012345678"
"9012345678901234567890123456789012345"
"67890123456789012345678901234567890123456789012345678901"
"2345678901234567890123456789012345678"
"90123456789012345678901234567890123456789012345678901234"
"5678901234567890123456789012345678901"
"2345678901234567890123456789",
"78"});
targets_view = cudf::strings_column_view(targets);
auto repls = cudf::test::strings_column_wrapper({""});
auto repls_view = cudf::strings_column_view(repls);
auto results = cudf::strings::replace(strings_view, targets_view, repls_view);
cudf::test::strings_column_wrapper expected(
{"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions. "
"This string needs to be very long to trigger the long-replace internal functions.",
"",
"",
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá "
"Test string for overlap check: bananaápple bananá ápplebananá banápple ápple bananá",
"",
""},
{1, 1, 1, 1, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsReplaceTest, EmptyStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::replace(
strings_view, cudf::string_scalar("not"), cudf::string_scalar("pertinent"));
auto view = results->view();
cudf::test::expect_column_empty(results->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/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 <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/column/column_factories.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/split/partition.hpp>
#include <cudf/strings/split/split.hpp>
#include <cudf/strings/split/split_re.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/table/table.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsSplitTest : public cudf::test::BaseFixture {};
TEST_F(StringsSplitTest, Split)
{
std::vector<char const*> h_strings{
"Héllo thesé", nullptr, "are some", "tést String", "", "no-delimiter"};
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);
std::vector<char const*> h_expected1{"Héllo", nullptr, "are", "tést", "", "no-delimiter"};
cudf::test::strings_column_wrapper expected1(
h_expected1.begin(),
h_expected1.end(),
thrust::make_transform_iterator(h_expected1.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected2{"thesé", nullptr, "some", "String", nullptr, nullptr};
cudf::test::strings_column_wrapper expected2(
h_expected2.begin(),
h_expected2.end(),
thrust::make_transform_iterator(h_expected2.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view, cudf::string_scalar(" "));
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, SplitWithMax)
{
cudf::test::strings_column_wrapper strings(
{"Héllo::thesé::world", "are::some", "tést::String:", ":last::one", ":::", "x::::y"});
cudf::strings_column_view strings_view(strings);
cudf::test::strings_column_wrapper expected1({"Héllo", "are", "tést", ":last", "", "x"});
cudf::test::strings_column_wrapper expected2(
{"thesé::world", "some", "String:", "one", ":", "::y"});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view, cudf::string_scalar("::"), 1);
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, SplitWhitespace)
{
std::vector<char const*> h_strings{
"Héllo thesé", nullptr, "are\tsome", "tést\nString", " ", " a b ", ""};
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);
std::vector<char const*> h_expected1{"Héllo", nullptr, "are", "tést", nullptr, "a", nullptr};
cudf::test::strings_column_wrapper expected1(
h_expected1.begin(),
h_expected1.end(),
thrust::make_transform_iterator(h_expected1.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected2{"thesé", nullptr, "some", "String", nullptr, "b", nullptr};
cudf::test::strings_column_wrapper expected2(
h_expected2.begin(),
h_expected2.end(),
thrust::make_transform_iterator(h_expected2.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view);
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, SplitWhitespaceWithMax)
{
cudf::test::strings_column_wrapper strings(
{"a bc d", "a bc d", " ab cd e", "ab cd e ", " ab cd e "});
cudf::strings_column_view strings_view(strings);
cudf::test::strings_column_wrapper expected1({"a", "a", "ab", "ab", "ab"});
cudf::test::strings_column_wrapper expected2({"bc d", "bc d", "cd e", "cd e ", "cd e "});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::split(strings_view, cudf::string_scalar(""), 1);
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RSplit)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b ", " a bbb c"};
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);
std::vector<char const*> h_expected1{
"héllo", nullptr, "a", "a", "", "ab", "", " a b ", " a bbb c"};
cudf::test::strings_column_wrapper expected1(
h_expected1.begin(),
h_expected1.end(),
thrust::make_transform_iterator(h_expected1.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected2{
nullptr, nullptr, "bc", "", "ab", "cd", nullptr, nullptr, nullptr};
cudf::test::strings_column_wrapper expected2(
h_expected2.begin(),
h_expected2.end(),
thrust::make_transform_iterator(h_expected2.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected3{
nullptr, nullptr, "déf", "bc", "cd", "", nullptr, nullptr, nullptr};
cudf::test::strings_column_wrapper expected3(
h_expected3.begin(),
h_expected3.end(),
thrust::make_transform_iterator(h_expected3.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE(results->num_columns() == 3);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RSplitWithMax)
{
cudf::test::strings_column_wrapper strings(
{"Héllo::thesé::world", "are::some", "tést::String:", ":last::one", ":::", "x::::y"});
cudf::strings_column_view strings_view(strings);
cudf::test::strings_column_wrapper expected1(
{"Héllo::thesé", "are", "tést", ":last", ":", "x::"});
cudf::test::strings_column_wrapper expected2({"world", "some", "String:", "one", "", "y"});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view, cudf::string_scalar("::"), 1);
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RSplitWhitespace)
{
std::vector<char const*> h_strings{"héllo", nullptr, "a_bc_déf", "", " a\tb ", " a\r bbb c"};
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);
std::vector<char const*> h_expected1{"héllo", nullptr, "a_bc_déf", nullptr, "a", "a"};
cudf::test::strings_column_wrapper expected1(
h_expected1.begin(),
h_expected1.end(),
thrust::make_transform_iterator(h_expected1.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected2{nullptr, nullptr, nullptr, nullptr, "b", "bbb"};
cudf::test::strings_column_wrapper expected2(
h_expected2.begin(),
h_expected2.end(),
thrust::make_transform_iterator(h_expected2.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_expected3{nullptr, nullptr, nullptr, nullptr, nullptr, "c"};
cudf::test::strings_column_wrapper expected3(
h_expected3.begin(),
h_expected3.end(),
thrust::make_transform_iterator(h_expected3.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view);
EXPECT_TRUE(results->num_columns() == 3);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RSplitWhitespaceWithMax)
{
cudf::test::strings_column_wrapper strings(
{"a bc d", "a bc d", " ab cd e", "ab cd e ", " ab cd e "});
cudf::strings_column_view strings_view(strings);
cudf::test::strings_column_wrapper expected1({"a bc", "a bc", " ab cd", "ab cd", " ab cd"});
cudf::test::strings_column_wrapper expected2({"d", "d", "e", "e", "e"});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
auto results = cudf::strings::rsplit(strings_view, cudf::string_scalar(""), 1);
EXPECT_TRUE(results->num_columns() == 2);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, SplitRecord)
{
std::vector<char const*> h_strings{" Héllo thesé", nullptr, "are some ", "tést String", ""};
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);
auto result =
cudf::strings::split_record(cudf::strings_column_view(strings), cudf::string_scalar(" "));
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected(
{LCW{"", "Héllo", "thesé"}, LCW{}, LCW{"are", "some", "", ""}, LCW{"tést", "String"}, LCW{""}},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, SplitRecordWithMaxSplit)
{
std::vector<char const*> h_strings{" Héllo thesé", nullptr, "are some ", "tést String", ""};
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);
auto result =
cudf::strings::split_record(cudf::strings_column_view(strings), cudf::string_scalar(" "), 1);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected(
{LCW{"", "Héllo thesé"}, LCW{}, LCW{"are", "some "}, LCW{"tést", "String"}, LCW{""}},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, SplitRecordWhitespace)
{
std::vector<char const*> h_strings{
" Héllo thesé", nullptr, "are\tsome ", "tést\nString", " "};
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);
auto result = cudf::strings::split_record(cudf::strings_column_view(strings));
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"Héllo", "thesé"}, LCW{}, LCW{"are", "some"}, LCW{"tést", "String"}, LCW{}},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, SplitRecordWhitespaceWithMaxSplit)
{
std::vector<char const*> h_strings{
" Héllo thesé ", nullptr, "are\tsome ", "tést\nString", " "};
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);
auto result =
cudf::strings::split_record(cudf::strings_column_view(strings), cudf::string_scalar(""), 1);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"Héllo", "thesé "}, LCW{}, LCW{"are", "some "}, LCW{"tést", "String"}, LCW{}},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, MultiByteDelimiters)
{
// Overlapping delimiters
auto input =
cudf::test::strings_column_wrapper({"u::", "w:::x", "y::::z", "::a", ":::b", ":::c:::"});
auto view = cudf::strings_column_view(input);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
{
auto result = cudf::strings::split_record(view, cudf::string_scalar("::"));
auto expected_left = LCW({LCW{"u", ""},
LCW{"w", ":x"},
LCW{"y", "", "z"},
LCW{"", "a"},
LCW{"", ":b"},
LCW{"", ":c", ":"}});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected_left);
result = cudf::strings::rsplit_record(view, cudf::string_scalar("::"));
auto expected_right = LCW({LCW{"u", ""},
LCW{"w:", "x"},
LCW{"y", "", "z"},
LCW{"", "a"},
LCW{":", "b"},
LCW{":", "c:", ""}});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected_right);
}
{
auto result = cudf::strings::split(view, cudf::string_scalar("::"));
auto c0 = cudf::test::strings_column_wrapper({"u", "w", "y", "", "", ""});
auto c1 = cudf::test::strings_column_wrapper({"", ":x", "", "a", ":b", ":c"});
auto c2 = cudf::test::strings_column_wrapper({"", "", "z", "", "", ":"}, {0, 0, 1, 0, 0, 1});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(c0.release());
expected_columns.push_back(c1.release());
expected_columns.push_back(c2.release());
auto expected_left = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*result, *expected_left);
result = cudf::strings::rsplit(view, cudf::string_scalar("::"));
c0 = cudf::test::strings_column_wrapper({"u", "w:", "y", "", ":", ":"});
c1 = cudf::test::strings_column_wrapper({"", "x", "", "a", "b", "c:"});
c2 = cudf::test::strings_column_wrapper({"", "", "z", "", "", ""}, {0, 0, 1, 0, 0, 1});
expected_columns.push_back(c0.release());
expected_columns.push_back(c1.release());
expected_columns.push_back(c2.release());
auto expected_right = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*result, *expected_right);
}
// Delimiters that span across adjacent strings
input = cudf::test::strings_column_wrapper({"{a=1}:{b=2}:", "{c=3}", ":{}:{}"});
view = cudf::strings_column_view(input);
{
auto result = cudf::strings::split_record(view, cudf::string_scalar("}:{"));
auto expected = LCW({LCW{"{a=1", "b=2}:"}, LCW{"{c=3}"}, LCW{":{", "}"}});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
result = cudf::strings::rsplit_record(view, cudf::string_scalar("}:{"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
{
auto result = cudf::strings::split(view, cudf::string_scalar("}:{"));
auto c0 = cudf::test::strings_column_wrapper({"{a=1", "{c=3}", ":{"});
auto c1 = cudf::test::strings_column_wrapper({"b=2}:", "", "}"}, {1, 0, 1});
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(c0.release());
expected_columns.push_back(c1.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*result, *expected);
result = cudf::strings::rsplit(view, cudf::string_scalar("}:{"));
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*result, *expected);
}
}
TEST_F(StringsSplitTest, SplitRegex)
{
std::vector<char const*> h_strings{" Héllo thesé", nullptr, "are some ", "tést String", ""};
auto validity =
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; });
cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end(), validity);
auto sv = cudf::strings_column_view(input);
{
auto pattern = std::string("\\s+");
cudf::test::strings_column_wrapper col0({"", "", "are", "tést", ""}, validity);
cudf::test::strings_column_wrapper col1({"Héllo", "", "some", "String", ""}, {1, 0, 1, 1, 0});
cudf::test::strings_column_wrapper col2({"thesé", "", "", "", ""}, {1, 0, 1, 0, 0});
auto expected = cudf::table_view({col0, col1, col2});
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
// rsplit == split when using default parameters
result = cudf::strings::rsplit_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
}
{
auto pattern = std::string("[eé]");
cudf::test::strings_column_wrapper col0({" H", "", "ar", "t", ""}, validity);
cudf::test::strings_column_wrapper col1({"llo th", "", " som", "st String", ""},
{1, 0, 1, 1, 0});
cudf::test::strings_column_wrapper col2({"s", "", " ", "", ""}, {1, 0, 1, 0, 0});
cudf::test::strings_column_wrapper col3({"", "", "", "", ""}, {1, 0, 0, 0, 0});
auto expected = cudf::table_view({col0, col1, col2, col3});
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
// rsplit == split when using default parameters
result = cudf::strings::rsplit_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
}
}
TEST_F(StringsSplitTest, SplitRecordRegex)
{
std::vector<char const*> h_strings{" Héllo thesé", nullptr, "are some ", "tést String", ""};
auto validity =
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; });
cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end(), validity);
auto sv = cudf::strings_column_view(input);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
{
auto pattern = std::string("\\s+");
LCW expected(
{LCW{"", "Héllo", "thesé"}, LCW{}, LCW{"are", "some", ""}, LCW{"tést", "String"}, LCW{""}},
validity);
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
// rsplit == split when using default parameters
result = cudf::strings::rsplit_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
}
{
auto pattern = std::string("[eé]");
LCW expected({LCW{" H", "llo th", "s", ""},
LCW{},
LCW{"ar", " som", " "},
LCW{"t", "st String"},
LCW{""}},
validity);
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
// rsplit == split when using default parameters
result = cudf::strings::rsplit_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
}
}
TEST_F(StringsSplitTest, SplitRegexWithMaxSplit)
{
std::vector<char const*> h_strings{" Héllo\tthesé", nullptr, "are\nsome ", "tést\rString", ""};
auto validity =
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; });
cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end(), validity);
auto sv = cudf::strings_column_view(input);
{
auto pattern = std::string("\\s+");
cudf::test::strings_column_wrapper col0({"", "", "are", "tést", ""}, {1, 0, 1, 1, 1});
cudf::test::strings_column_wrapper col1({"Héllo\tthesé", "", "some ", "String", ""},
{1, 0, 1, 1, 0});
auto expected = cudf::table_view({col0, col1});
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_re(sv, *prog, 1);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
// split everything is the same output as maxsplit==2 for the test input column here
result = cudf::strings::split_re(sv, *prog, 2);
auto expected2 = cudf::strings::split_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected2->view());
result = cudf::strings::split_re(sv, *prog, 3);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected2->view());
}
{
auto pattern = std::string("\\s");
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected1(
{LCW{"", "Héllo\tthesé"}, LCW{}, LCW{"are", "some "}, LCW{"tést", "String"}, LCW{""}},
validity);
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_record_re(sv, *prog, 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected1);
result = cudf::strings::split_record_re(sv, *prog, 2);
LCW expected2(
{LCW{"", "Héllo", "thesé"}, LCW{}, LCW{"are", "some", " "}, LCW{"tést", "String"}, LCW{""}},
validity);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected2);
// split everything is the same output as maxsplit==3 for the test input column here
result = cudf::strings::split_record_re(sv, *prog, 3);
auto expected0 = cudf::strings::split_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected0->view());
result = cudf::strings::split_record_re(sv, *prog, 3);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected0->view());
}
}
TEST_F(StringsSplitTest, SplitRegexWordBoundary)
{
cudf::test::strings_column_wrapper input({"a", "ab", "-+", "e\né"});
auto sv = cudf::strings_column_view(input);
{
auto pattern = std::string("\\b");
cudf::test::strings_column_wrapper col0({"", "", "-+", ""});
cudf::test::strings_column_wrapper col1({"a", "ab", "", "e"}, {1, 1, 0, 1});
cudf::test::strings_column_wrapper col2({"", "", "", "\n"}, {1, 1, 0, 1});
cudf::test::strings_column_wrapper col3({"", "", "", "é"}, {0, 0, 0, 1});
cudf::test::strings_column_wrapper col4({"", "", "", ""}, {0, 0, 0, 1});
auto expected = cudf::table_view({col0, col1, col2, col3, col4});
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_re(sv, *prog);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
}
{
auto pattern = std::string("\\B");
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"a"}, LCW{"a", "b"}, LCW{"", "-", "+", ""}, LCW{"e\né"}});
auto prog = cudf::strings::regex_program::create(pattern);
auto result = cudf::strings::split_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
}
}
TEST_F(StringsSplitTest, RSplitRecord)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b ", " a bbb c"};
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);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"héllo"},
LCW{},
LCW{"a", "bc", "déf"},
LCW{"a", "", "bc"},
LCW{"", "ab", "cd"},
LCW{"ab", "cd", ""},
LCW{""},
LCW{" a b "},
LCW{" a bbb c"}},
validity);
auto result =
cudf::strings::rsplit_record(cudf::strings_column_view(strings), cudf::string_scalar("_"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, RSplitRecordWithMaxSplit)
{
std::vector<char const*> h_strings{"héllo",
nullptr,
"a_bc_déf",
"___a__bc",
"_ab_cd_",
"ab_cd_",
"",
" a b ___",
"___ a bbb c"};
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);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"héllo"},
LCW{},
LCW{"a", "bc", "déf"},
LCW{"___a", "", "bc"},
LCW{"_ab", "cd", ""},
LCW{"ab", "cd", ""},
LCW{""},
LCW{" a b _", "", ""},
LCW{"_", "", " a bbb c"}},
validity);
auto result =
cudf::strings::rsplit_record(cudf::strings_column_view(strings), cudf::string_scalar("_"), 2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, RSplitRecordWhitespace)
{
std::vector<char const*> h_strings{"héllo", nullptr, "a_bc_déf", "", " a\tb ", " a\r bbb c"};
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);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"héllo"}, LCW{}, LCW{"a_bc_déf"}, LCW{}, LCW{"a", "b"}, LCW{"a", "bbb", "c"}},
validity);
auto result = cudf::strings::rsplit_record(cudf::strings_column_view(strings));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, RSplitRecordWhitespaceWithMaxSplit)
{
std::vector<char const*> h_strings{
" héllo Asher ", nullptr, " a_bc_déf ", "", " a\tb ", " a\r bbb c"};
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);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected(
{LCW{" héllo", "Asher"}, LCW{}, LCW{"a_bc_déf"}, LCW{}, LCW{" a", "b"}, LCW{" a\r bbb", "c"}},
validity);
auto result =
cudf::strings::rsplit_record(cudf::strings_column_view(strings), cudf::string_scalar(""), 1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected);
}
TEST_F(StringsSplitTest, RSplitRegexWithMaxSplit)
{
std::vector<char const*> h_strings{" Héllo\tthesé", nullptr, "are some\n ", "tést\rString", ""};
auto validity =
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; });
cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end(), validity);
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("\\s+");
auto prog = cudf::strings::regex_program::create(pattern);
{
cudf::test::strings_column_wrapper col0({" Héllo", "", "are some", "tést", ""}, validity);
cudf::test::strings_column_wrapper col1({"thesé", "", "", "String", ""}, {1, 0, 1, 1, 0});
auto expected = cudf::table_view({col0, col1});
auto result = cudf::strings::rsplit_re(sv, *prog, 1);
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result->view(), expected);
}
{
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected(
{LCW{" Héllo", "thesé"}, LCW{}, LCW{"are some", ""}, LCW{"tést", "String"}, LCW{""}},
validity);
auto result = cudf::strings::rsplit_record_re(sv, *prog, 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected);
// split everything is the same output as any maxsplit > 2 for the test input column here
result = cudf::strings::rsplit_record_re(sv, *prog, 3);
auto expected0 = cudf::strings::rsplit_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected0->view());
result = cudf::strings::rsplit_record_re(sv, *prog, 3);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected0->view());
}
}
TEST_F(StringsSplitTest, SplitZeroSizeStringsColumns)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto prog = cudf::strings::regex_program::create("\\s");
auto results = cudf::strings::split(zero_size_strings_column);
EXPECT_TRUE(results->num_columns() == 1);
EXPECT_TRUE(results->num_rows() == 0);
results = cudf::strings::rsplit(zero_size_strings_column);
EXPECT_TRUE(results->num_columns() == 1);
EXPECT_TRUE(results->num_rows() == 0);
results = cudf::strings::split_re(zero_size_strings_column, *prog);
EXPECT_TRUE(results->num_columns() == 1);
EXPECT_TRUE(results->num_rows() == 0);
results = cudf::strings::rsplit_re(zero_size_strings_column, *prog);
EXPECT_TRUE(results->num_columns() == 1);
EXPECT_TRUE(results->num_rows() == 0);
auto target = cudf::string_scalar(" ");
auto list_result = cudf::strings::split_record(zero_size_strings_column);
EXPECT_TRUE(list_result->size() == 0);
list_result = cudf::strings::rsplit_record(zero_size_strings_column);
EXPECT_TRUE(list_result->size() == 0);
list_result = cudf::strings::split_record(zero_size_strings_column, target);
EXPECT_TRUE(list_result->size() == 0);
list_result = cudf::strings::rsplit_record(zero_size_strings_column, target);
EXPECT_TRUE(list_result->size() == 0);
list_result = cudf::strings::split_record_re(zero_size_strings_column, *prog);
EXPECT_TRUE(list_result->size() == 0);
list_result = cudf::strings::rsplit_record_re(zero_size_strings_column, *prog);
EXPECT_TRUE(list_result->size() == 0);
}
// This test specifically for https://github.com/rapidsai/custrings/issues/119
TEST_F(StringsSplitTest, AllNullsCase)
{
cudf::test::strings_column_wrapper input({"", "", ""}, {0, 0, 0});
auto sv = cudf::strings_column_view(input);
auto prog = cudf::strings::regex_program::create("-");
auto results = cudf::strings::split(sv);
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
results = cudf::strings::split(sv, cudf::string_scalar("-"));
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
results = cudf::strings::rsplit(sv);
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
results = cudf::strings::rsplit(sv, cudf::string_scalar("-"));
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
results = cudf::strings::split_re(sv, *prog);
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
results = cudf::strings::rsplit_re(sv, *prog);
EXPECT_TRUE(results->num_columns() == 1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->get_column(0).view(), input);
auto target = cudf::string_scalar(" ");
auto list_result = cudf::strings::split_record(sv);
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{}, LCW{}, LCW{}}, cudf::test::iterators::all_nulls());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
list_result = cudf::strings::rsplit_record(sv);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
list_result = cudf::strings::split_record(sv, target);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
list_result = cudf::strings::rsplit_record(sv, target);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
list_result = cudf::strings::split_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
list_result = cudf::strings::rsplit_record_re(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_result->view(), expected);
}
TEST_F(StringsSplitTest, Partition)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b "};
std::vector<char const*> h_expecteds{
"héllo", nullptr, "a", "a", "", "ab", "", " a b ", "", nullptr, "_", "_",
"_", "_", "", "", "", nullptr, "bc_déf", "_bc", "ab_cd", "cd_", "", ""};
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);
auto results = cudf::strings::partition(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE(results->num_columns() == 3);
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, PartitionWhitespace)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a bc déf", "a bc", " ab cd", "ab cd ", "", "a_b"};
std::vector<char const*> h_expecteds{"héllo", nullptr, "a", "a", "", "ab", "", "a_b",
"", nullptr, " ", " ", " ", " ", "", "",
"", nullptr, "bc déf", " bc", "ab cd", "cd ", "", ""};
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);
auto results = cudf::strings::partition(strings_view);
EXPECT_TRUE(results->num_columns() == 3);
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RPartition)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a_bc_déf", "a__bc", "_ab_cd", "ab_cd_", "", " a b "};
std::vector<char const*> h_expecteds{"", nullptr, "a_bc", "a_", "_ab", "ab_cd", "", "",
"", nullptr, "_", "_", "_", "_", "", "",
"héllo", nullptr, "déf", "bc", "cd", "", "", " a b "};
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);
auto results = cudf::strings::rpartition(strings_view, cudf::string_scalar("_"));
EXPECT_TRUE(results->num_columns() == 3);
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, RPartitionWhitespace)
{
std::vector<char const*> h_strings{
"héllo", nullptr, "a bc déf", "a bc", " ab cd", "ab cd ", "", "a_b"};
std::vector<char const*> h_expecteds{"", nullptr, "a bc", "a ", " ab", "ab cd", "", "",
"", nullptr, " ", " ", " ", " ", "", "",
"héllo", nullptr, "déf", "bc", "cd", "", "", "a_b"};
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);
auto results = cudf::strings::rpartition(strings_view);
EXPECT_TRUE(results->num_columns() == 3);
auto exp_itr = h_expecteds.begin();
cudf::test::strings_column_wrapper expected1(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected2(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
exp_itr += h_strings.size();
cudf::test::strings_column_wrapper expected3(
exp_itr,
exp_itr + h_strings.size(),
thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> expected_columns;
expected_columns.push_back(expected1.release());
expected_columns.push_back(expected2.release());
expected_columns.push_back(expected3.release());
auto expected = std::make_unique<cudf::table>(std::move(expected_columns));
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, *expected);
}
TEST_F(StringsSplitTest, PartitionZeroSizeStringsColumns)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results = cudf::strings::partition(zero_size_strings_column);
EXPECT_TRUE(results->num_columns() == 0);
results = cudf::strings::rpartition(zero_size_strings_column);
EXPECT_TRUE(results->num_columns() == 0);
}
TEST_F(StringsSplitTest, InvalidParameter)
{
cudf::test::strings_column_wrapper input({"string left intentionally blank"});
auto strings_view = cudf::strings_column_view(input);
auto prog = cudf::strings::regex_program::create("");
EXPECT_THROW(cudf::strings::split(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::rsplit(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::split_record(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::rsplit_record(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::split_re(strings_view, *prog), cudf::logic_error);
EXPECT_THROW(cudf::strings::split_record_re(strings_view, *prog), cudf::logic_error);
EXPECT_THROW(cudf::strings::rsplit_re(strings_view, *prog), cudf::logic_error);
EXPECT_THROW(cudf::strings::rsplit_record_re(strings_view, *prog), cudf::logic_error);
EXPECT_THROW(cudf::strings::partition(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
EXPECT_THROW(cudf::strings::rpartition(strings_view, cudf::string_scalar("", false)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/extract_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/detail/iterator.cuh>
#include <cudf/strings/extract.hpp>
#include <cudf/strings/regex/regex_program.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/table/table_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsExtractTests : public cudf::test::BaseFixture {};
TEST_F(StringsExtractTests, ExtractTest)
{
std::vector<char const*> h_strings{
"First Last", "Joe Schmoe", "John Smith", "Jane Smith", "Beyonce", "Sting", 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; }));
auto strings_view = cudf::strings_column_view(strings);
std::vector<char const*> h_expecteds{"First",
"Joe",
"John",
"Jane",
nullptr,
nullptr,
nullptr,
nullptr,
"Last",
"Schmoe",
"Smith",
"Smith",
nullptr,
nullptr,
nullptr,
nullptr};
std::string pattern = "(\\w+) (\\w+)";
cudf::test::strings_column_wrapper expected1(
h_expecteds.data(),
h_expecteds.data() + h_strings.size(),
thrust::make_transform_iterator(h_expecteds.begin(), [](auto str) { return str != nullptr; }));
cudf::test::strings_column_wrapper expected2(
h_expecteds.data() + h_strings.size(),
h_expecteds.data() + h_expecteds.size(),
thrust::make_transform_iterator(h_expecteds.data() + h_strings.size(),
[](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> columns;
columns.push_back(expected1.release());
columns.push_back(expected2.release());
cudf::table expected(std::move(columns));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::extract(strings_view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
}
TEST_F(StringsExtractTests, ExtractDomainTest)
{
cudf::test::strings_column_wrapper strings({"http://www.google.com",
"gmail.com",
"github.com",
"https://pandas.pydata.org",
"http://www.worldbank.org.kg/",
"waiterrant.blogspot.com",
"http://forums.news.cnn.com.ac/",
"http://forums.news.cnn.ac/",
"ftp://b.cnn.com/",
"a.news.uk",
"a.news.co.uk",
"https://a.news.co.uk",
"107-193-100-2.lightspeed.cicril.sbcglobal.net",
"a23-44-13-2.deploy.static.akamaitechnologies.com"});
auto strings_view = cudf::strings_column_view(strings);
std::string pattern = "([\\w]+[\\.].*[^/]|[\\-\\w]+[\\.].*[^/])";
cudf::test::strings_column_wrapper expected1({
"www.google.com",
"gmail.com",
"github.com",
"pandas.pydata.org",
"www.worldbank.org.kg",
"waiterrant.blogspot.com",
"forums.news.cnn.com.ac",
"forums.news.cnn.ac",
"b.cnn.com",
"a.news.uk",
"a.news.co.uk",
"a.news.co.uk",
"107-193-100-2.lightspeed.cicril.sbcglobal.net",
"a23-44-13-2.deploy.static.akamaitechnologies.com",
});
cudf::table_view expected{{expected1}};
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::extract(strings_view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
}
TEST_F(StringsExtractTests, ExtractEventTest)
{
std::vector<std::string> patterns({"(^[0-9]+\\.?[0-9]*),",
"search_name=\"([0-9A-Za-z\\s\\-\\(\\)]+)",
"message.ip=\"([\\w\\.]+)",
"message.hostname=\"([\\w\\.]+)",
"message.user_name=\"([\\w\\.\\@]+)",
"message\\.description=\"([\\w\\.\\s]+)"});
cudf::test::strings_column_wrapper strings(
{"15162388.26, search_name=\"Test Search Name\", orig_time=\"1516238826\", "
"info_max_time=\"1566346500.000000000\", info_min_time=\"1566345300.000000000\", "
"info_search_time=\"1566305689.361160000\", message.description=\"Test Message Description\", "
"message.hostname=\"msg.test.hostname\", message.ip=\"100.100.100.123\", "
"message.user_name=\"[email protected]\", severity=\"info\", urgency=\"medium\"'"});
auto strings_view = cudf::strings_column_view(strings);
std::vector<std::string> expecteds({"15162388.26",
"Test Search Name",
"100.100.100.123",
"msg.test.hostname",
"[email protected]",
"Test Message Description"});
for (std::size_t idx = 0; idx < patterns.size(); ++idx) {
auto pattern = patterns[idx];
cudf::test::strings_column_wrapper expected({expecteds[idx]});
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::extract(strings_view, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view().column(0), expected);
}
}
TEST_F(StringsExtractTests, MultiLine)
{
auto input = cudf::test::strings_column_wrapper(
{"abc\nfff\nabc", "fff\nabc\nlll", "abc", "", "abc\n", "abé\nabc\n"});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("(^[a-c]+$)");
cudf::test::strings_column_wrapper expected_multiline({"abc", "abc", "abc", "", "abc", "abc"},
{1, 1, 1, 0, 1, 1});
auto expected = cudf::table_view{{expected_multiline}};
auto prog = cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::MULTILINE);
auto results = cudf::strings::extract(view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
pattern = std::string("^([a-c]+)$");
cudf::test::strings_column_wrapper expected_default({"", "", "abc", "", "abc", ""},
{0, 0, 1, 0, 1, 0});
expected = cudf::table_view{{expected_default}};
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::extract(view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
}
TEST_F(StringsExtractTests, DotAll)
{
auto input = cudf::test::strings_column_wrapper({"abc\nfa\nef", "fff\nabbc\nfff", "abcdef", ""});
auto view = cudf::strings_column_view(input);
auto pattern = std::string("(a.*f)");
cudf::test::strings_column_wrapper expected_dotall({"abc\nfa\nef", "abbc\nfff", "abcdef", ""},
{1, 1, 1, 0});
auto expected = cudf::table_view{{expected_dotall}};
auto prog = cudf::strings::regex_program::create(pattern, cudf::strings::regex_flags::DOTALL);
auto results = cudf::strings::extract(view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
cudf::test::strings_column_wrapper expected_default({"", "", "abcdef", ""}, {0, 0, 1, 0});
expected = cudf::table_view{{expected_default}};
prog = cudf::strings::regex_program::create(pattern);
results = cudf::strings::extract(view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, expected);
}
TEST_F(StringsExtractTests, EmptyExtractTest)
{
std::vector<char const*> h_strings{nullptr, "AAA", "AAA_A", "AAA_AAA_", "A__", ""};
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 strings_view = cudf::strings_column_view(strings);
auto pattern = std::string("([^_]*)\\Z");
std::vector<char const*> h_expected{nullptr, "AAA", "A", "", "", ""};
cudf::test::strings_column_wrapper expected(
h_expected.data(),
h_expected.data() + h_strings.size(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
std::vector<std::unique_ptr<cudf::column>> columns;
columns.push_back(expected.release());
cudf::table table_expected(std::move(columns));
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::extract(strings_view, *prog);
CUDF_TEST_EXPECT_TABLES_EQUAL(*results, table_expected);
}
TEST_F(StringsExtractTests, ExtractAllTest)
{
std::vector<char const*> h_input(
{"123 banana 7 eleven", "41 apple", "6 péar 0 pair", nullptr, "", "bees", "4 paré"});
auto validity =
thrust::make_transform_iterator(h_input.begin(), [](auto str) { return str != nullptr; });
cudf::test::strings_column_wrapper input(h_input.begin(), h_input.end(), validity);
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("(\\d+) (\\w+)");
bool valids[] = {true, true, true, false, false, false, true};
using LCW = cudf::test::lists_column_wrapper<cudf::string_view>;
LCW expected({LCW{"123", "banana", "7", "eleven"},
LCW{"41", "apple"},
LCW{"6", "péar", "0", "pair"},
LCW{},
LCW{},
LCW{},
LCW{"4", "paré"}},
valids);
auto prog = cudf::strings::regex_program::create(pattern);
auto results = cudf::strings::extract_all_record(sv, *prog);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected);
}
TEST_F(StringsExtractTests, Errors)
{
cudf::test::strings_column_wrapper input({"this column intentionally left blank"});
auto sv = cudf::strings_column_view(input);
auto pattern = std::string("\\w+");
auto prog = cudf::strings::regex_program::create(pattern);
EXPECT_THROW(cudf::strings::extract(sv, *prog), cudf::logic_error);
EXPECT_THROW(cudf::strings::extract_all_record(sv, *prog), cudf::logic_error);
}
TEST_F(StringsExtractTests, MediumRegex)
{
// This results in 95 regex instructions and falls in the 'medium' range.
std::string medium_regex =
"hello @abc @def (world) The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com";
auto prog = cudf::strings::regex_program::create(medium_regex);
std::vector<char const*> h_strings{
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com thats all",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
"5678901234567890",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop"
"qrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::extract(strings_view, *prog);
std::vector<char const*> h_expected{"world", nullptr, nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->get_column(0), expected);
}
TEST_F(StringsExtractTests, LargeRegex)
{
// This results in 115 regex instructions and falls in the 'large' range.
std::string large_regex =
"hello @abc @def world The (quick) brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz";
auto prog = cudf::strings::regex_program::create(large_regex);
std::vector<char const*> h_strings{
"hello @abc @def world The quick brown @fox jumps over the lazy @dog hello "
"http://www.world.com I'm here @home zzzz",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234"
"5678901234567890",
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop"
"qrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"};
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 strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::extract(strings_view, *prog);
std::vector<char const*> h_expected{"quick", nullptr, nullptr};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->get_column(0), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/strings/ipv4_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/strings/convert/convert_ipv4.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <vector>
struct StringsConvertTest : public cudf::test::BaseFixture {};
TEST_F(StringsConvertTest, IPv4ToIntegers)
{
std::vector<char const*> h_strings{
nullptr, "", "hello", "41.168.0.1", "127.0.0.1", "41.197.0.1", "192.168.0.1"};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.begin(),
[](auto const str) { return str != nullptr; }));
auto strings_view = cudf::strings_column_view(strings);
auto results = cudf::strings::ipv4_to_integers(strings_view);
std::vector<int64_t> h_expected{0, 0, 0, 698875905, 2130706433, 700776449, 3232235521};
cudf::test::fixed_width_column_wrapper<int64_t> expected(
h_expected.cbegin(),
h_expected.cend(),
thrust::make_transform_iterator(h_strings.begin(),
[](auto const str) { return str != nullptr; }));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(StringsConvertTest, IntegersToIPv4)
{
std::vector<char const*> h_strings{
"192.168.0.1", "10.0.0.1", nullptr, "0.0.0.0", "41.186.0.1", "41.197.0.1"};
cudf::test::strings_column_wrapper strings(
h_strings.cbegin(),
h_strings.cend(),
thrust::make_transform_iterator(h_strings.begin(),
[](auto const str) { return str != nullptr; }));
std::vector<int64_t> h_column{3232235521, 167772161, 0, 0, 700055553, 700776449};
cudf::test::fixed_width_column_wrapper<int64_t> column(
h_column.cbegin(),
h_column.cend(),
thrust::make_transform_iterator(h_strings.begin(),
[](auto const str) { return str != nullptr; }));
auto results = cudf::strings::integers_to_ipv4(column);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, strings);
}
TEST_F(StringsConvertTest, ZeroSizeStringsColumnIPV4)
{
auto const zero_size_column = cudf::make_empty_column(cudf::type_id::INT64)->view();
auto results = cudf::strings::integers_to_ipv4(zero_size_column);
cudf::test::expect_column_empty(results->view());
results = cudf::strings::ipv4_to_integers(results->view());
EXPECT_EQ(0, results->size());
}
TEST_F(StringsConvertTest, IPv4Error)
{
auto column = cudf::make_numeric_column(cudf::data_type{cudf::type_id::INT32}, 100);
EXPECT_THROW(cudf::strings::integers_to_ipv4(column->view()), cudf::logic_error);
}
TEST_F(StringsConvertTest, IsIPv4)
{
std::vector<char const*> h_strings{"",
"123.456.789.10",
nullptr,
"0.0.0.0",
".111.211.113",
"127:0:0:1",
"255.255.255.255",
"192.168.0.",
"1...1",
"127.0.A.1",
"9.1.2.3.4",
"8.9"};
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::fixed_width_column_wrapper<bool> expected({0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1});
auto results = cudf::strings::is_ipv4(cudf::strings_column_view(strings));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/strings
|
rapidsai_public_repos/cudf/cpp/tests/strings/combine/join_strings_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/column/column_factories.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/combine.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/types.hpp>
#include <thrust/iterator/transform_iterator.h>
struct JoinStringsTest : public cudf::test::BaseFixture {};
TEST_F(JoinStringsTest, Join)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "zzzz", "", "aaa", "ééé"};
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 view1 = cudf::strings_column_view(strings);
{
auto results = cudf::strings::join_strings(view1);
cudf::test::strings_column_wrapper expected{"eeebbzzzzaaaééé"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results = cudf::strings::join_strings(view1, cudf::string_scalar("+"));
cudf::test::strings_column_wrapper expected{"eee+bb+zzzz++aaa+ééé"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
auto results =
cudf::strings::join_strings(view1, cudf::string_scalar("+"), cudf::string_scalar("___"));
cudf::test::strings_column_wrapper expected{"eee+bb+___+zzzz++aaa+ééé"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(JoinStringsTest, JoinLongStrings)
{
std::string data(200, '0');
cudf::test::strings_column_wrapper input({data, data, data, data});
auto results =
cudf::strings::join_strings(cudf::strings_column_view(input), cudf::string_scalar("+"));
auto expected_data = data + "+" + data + "+" + data + "+" + data;
cudf::test::strings_column_wrapper expected({expected_data});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
TEST_F(JoinStringsTest, JoinZeroSizeStringsColumn)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto strings_view = cudf::strings_column_view(zero_size_strings_column);
auto results = cudf::strings::join_strings(strings_view);
cudf::test::expect_column_empty(results->view());
}
TEST_F(JoinStringsTest, JoinAllNullStringsColumn)
{
cudf::test::strings_column_wrapper strings({"", "", ""}, {0, 0, 0});
auto results = cudf::strings::join_strings(cudf::strings_column_view(strings));
cudf::test::strings_column_wrapper expected1({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected1);
results = cudf::strings::join_strings(
cudf::strings_column_view(strings), cudf::string_scalar(""), cudf::string_scalar("3"));
cudf::test::strings_column_wrapper expected2({"333"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected2);
results = cudf::strings::join_strings(
cudf::strings_column_view(strings), cudf::string_scalar("-"), cudf::string_scalar("*"));
cudf::test::strings_column_wrapper expected3({"*-*-*"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected3);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/strings
|
rapidsai_public_repos/cudf/cpp/tests/strings/combine/join_list_elements_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/scalar/scalar.hpp>
#include <cudf/strings/combine.hpp>
#include <cudf/strings/strings_column_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>
using namespace cudf::test::iterators;
struct StringsListsConcatenateTest : public cudf::test::BaseFixture {};
namespace {
using STR_LISTS = cudf::test::lists_column_wrapper<cudf::string_view>;
using STR_COL = cudf::test::strings_column_wrapper;
using INT_LISTS = cudf::test::lists_column_wrapper<int32_t>;
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR};
} // namespace
TEST_F(StringsListsConcatenateTest, InvalidInput)
{
// Invalid list type
{
auto const string_lists = INT_LISTS{{1, 2, 3}, {4, 5, 6}}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
EXPECT_THROW(cudf::strings::join_list_elements(string_lv), cudf::logic_error);
}
// Invalid scalar separator
{
auto const string_lists =
STR_LISTS{STR_LISTS{""}, STR_LISTS{"", "", ""}, STR_LISTS{"", ""}}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
EXPECT_THROW(cudf::strings::join_list_elements(string_lv, cudf::string_scalar("", false)),
cudf::logic_error);
}
// Invalid column separators
{
auto const string_lists =
STR_LISTS{STR_LISTS{""}, STR_LISTS{"", "", ""}, STR_LISTS{"", ""}}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
auto const separators = STR_COL{"+++"}.release(); // size doesn't match with lists column size
EXPECT_THROW(cudf::strings::join_list_elements(string_lv, separators->view()),
cudf::logic_error);
}
}
TEST_F(StringsListsConcatenateTest, EmptyInput)
{
auto const string_lists = STR_LISTS{}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
auto const expected = STR_COL{};
auto results = cudf::strings::join_list_elements(string_lv);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
auto const separators = STR_COL{}.release();
results = cudf::strings::join_list_elements(string_lv, separators->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
TEST_F(StringsListsConcatenateTest, ZeroSizeStringsInput)
{
auto const string_lists =
STR_LISTS{STR_LISTS{""}, STR_LISTS{"", "", ""}, STR_LISTS{"", ""}, STR_LISTS{}}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
// Empty list results in empty string
{
auto const expected = STR_COL{"", "", "", ""};
auto results = cudf::strings::join_list_elements(string_lv);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
auto const separators = STR_COL{"", "", "", ""}.release();
results = cudf::strings::join_list_elements(string_lv, separators->view());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, verbosity);
}
// Empty list results in null
{
auto const expected = STR_COL{{"", "", "", "" /*NULL*/}, null_at(3)};
auto results =
cudf::strings::join_list_elements(string_lv,
cudf::string_scalar(""),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO,
cudf::strings::output_if_empty_list::NULL_ELEMENT);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
auto const separators = STR_COL{"", "", "", ""}.release();
results = cudf::strings::join_list_elements(string_lv,
separators->view(),
cudf::string_scalar(""),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO,
cudf::strings::output_if_empty_list::NULL_ELEMENT);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
TEST_F(StringsListsConcatenateTest, ColumnHasEmptyListAndNullListInput)
{
auto const string_lists =
STR_LISTS{{STR_LISTS{"abc", "def", ""}, STR_LISTS{} /*NULL*/, STR_LISTS{}, STR_LISTS{"gh"}},
null_at(1)}
.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
// Empty list results in empty string
{
auto const expected = STR_COL{{"abc-def-", "" /*NULL*/, "", "gh"}, null_at(1)};
auto results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("-"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
auto const separators = STR_COL{"-", "", "", ""}.release();
results = cudf::strings::join_list_elements(string_lv, separators->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Empty list results in null
{
auto const expected = STR_COL{{"abc-def-", "" /*NULL*/, "" /*NULL*/, "gh"}, nulls_at({1, 2})};
auto results =
cudf::strings::join_list_elements(string_lv,
cudf::string_scalar("-"),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO,
cudf::strings::output_if_empty_list::NULL_ELEMENT);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
auto const separators = STR_COL{"-", "", "", ""}.release();
results = cudf::strings::join_list_elements(string_lv,
separators->view(),
cudf::string_scalar(""),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO,
cudf::strings::output_if_empty_list::NULL_ELEMENT);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
TEST_F(StringsListsConcatenateTest, AllNullsStringsInput)
{
auto const string_lists = STR_LISTS{
STR_LISTS{{""}, all_nulls()},
STR_LISTS{{"", "", ""}, all_nulls()},
STR_LISTS{{"", ""},
all_nulls()}}.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
auto const expected = STR_COL{{"", "", ""}, all_nulls()};
auto results = cudf::strings::join_list_elements(string_lv);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
auto const separators = STR_COL{{"", "", ""}, all_nulls()}.release();
results = cudf::strings::join_list_elements(string_lv, separators->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
TEST_F(StringsListsConcatenateTest, ScalarSeparator)
{
auto const string_lists = STR_LISTS{{STR_LISTS{{"a", "bb" /*NULL*/, "ccc"}, null_at(1)},
STR_LISTS{}, /*NULL*/
STR_LISTS{{"ddd" /*NULL*/, "efgh", "ijk"}, null_at(0)},
STR_LISTS{"zzz", "xxxxx"},
STR_LISTS{{"v", "", "", "w"}, nulls_at({1, 2})}},
null_at(1)}
.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
// No null replacement
{
auto const results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("+++"));
std::vector<char const*> h_expected{nullptr, nullptr, nullptr, "zzz+++xxxxx", nullptr};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// With null replacement
{
auto const results = cudf::strings::join_list_elements(
string_lv, cudf::string_scalar("+++"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{
"a+++___+++ccc", nullptr, "___+++efgh+++ijk", "zzz+++xxxxx", "v+++___+++___+++w"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Turn off separator-on-nulls
{
auto const results = cudf::strings::join_list_elements(string_lv,
cudf::string_scalar("+++"),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
std::vector<char const*> h_expected{"a+++ccc", nullptr, "efgh+++ijk", "zzz+++xxxxx", "v+++w"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
TEST_F(StringsListsConcatenateTest, SlicedListsWithScalarSeparator)
{
auto const string_lists = STR_LISTS{
{STR_LISTS{{"a", "bb" /*NULL*/, "ccc"}, null_at(1)},
STR_LISTS{}, /*NULL*/
STR_LISTS{{"ddd" /*NULL*/, "efgh", "ijk"}, null_at(0)},
STR_LISTS{"zzz", "xxxxx"},
STR_LISTS{"11111", "11111", "11111", "11111", "11111"}, /*NULL*/
STR_LISTS{{"abcdef", "012345", "" /*NULL*/, "xxx000"}, null_at(2)},
STR_LISTS{{"xyz" /*NULL*/, "11111", "00000"}, null_at(0)},
STR_LISTS{"0a0b0c", "5x5y5z"},
STR_LISTS{"xxx"}, /*NULL*/
STR_LISTS{"ééé", "12345abcdef"},
STR_LISTS{"aaaééébbbéééccc", "12345"}},
cudf::detail::make_counting_transform_iterator(0, [](auto i) {
return i != 1 && i != 4 && i != 8;
})}.release();
// Sliced the entire lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 11})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("+++"));
std::vector<char const*> h_expected{nullptr,
nullptr,
nullptr,
"zzz+++xxxxx",
nullptr,
nullptr,
nullptr,
"0a0b0c+++5x5y5z",
nullptr,
"ééé+++12345abcdef",
"aaaééébbbéééccc+++12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the entire lists column, with null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 11})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, cudf::string_scalar("+++"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"a+++___+++ccc",
nullptr,
"___+++efgh+++ijk",
"zzz+++xxxxx",
nullptr,
"abcdef+++012345+++___+++xxx000",
"___+++11111+++00000",
"0a0b0c+++5x5y5z",
nullptr,
"ééé+++12345abcdef",
"aaaééébbbéééccc+++12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the first half of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 4})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("+++"));
std::vector<char const*> h_expected{nullptr, nullptr, nullptr, "zzz+++xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the first half of the lists column, with null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 4})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, cudf::string_scalar("+++"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{
"a+++___+++ccc", nullptr, "___+++efgh+++ijk", "zzz+++xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the second half of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {5, 11})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("+++"));
std::vector<char const*> h_expected{
nullptr, nullptr, "0a0b0c+++5x5y5z", nullptr, "ééé+++12345abcdef", "aaaééébbbéééccc+++12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the second half of the lists column, with null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {5, 11})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, cudf::string_scalar("+++"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"abcdef+++012345+++___+++xxx000",
"___+++11111+++00000",
"0a0b0c+++5x5y5z",
nullptr,
"ééé+++12345abcdef",
"aaaééébbbéééccc+++12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the middle part of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {3, 8})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, cudf::string_scalar("+++"));
std::vector<char const*> h_expected{
"zzz+++xxxxx", nullptr, nullptr, nullptr, "0a0b0c+++5x5y5z"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the middle part of the lists column, with null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {3, 8})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, cudf::string_scalar("+++"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"zzz+++xxxxx",
nullptr,
"abcdef+++012345+++___+++xxx000",
"___+++11111+++00000",
"0a0b0c+++5x5y5z"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
TEST_F(StringsListsConcatenateTest, ColumnSeparators)
{
auto const string_lists = STR_LISTS{{STR_LISTS{{"a", "bb" /*NULL*/, "ccc"}, null_at(1)},
STR_LISTS{}, /*NULL*/
STR_LISTS{"0a0b0c", "xyzééé"},
STR_LISTS{{"ddd" /*NULL*/, "efgh", "ijk"}, null_at(0)},
STR_LISTS{{"ééé" /*NULL*/, "ááá", "ííí"}, null_at(0)},
STR_LISTS{"zzz", "xxxxx"}},
null_at(1)}
.release();
auto const string_lv = cudf::lists_column_view(string_lists->view());
auto const separators = STR_COL{
{"+++", "***", "!!!" /*NULL*/, "$$$" /*NULL*/, "%%%", "^^^"},
cudf::detail::make_counting_transform_iterator(0, [](auto i) {
return i != 2 && i != 3;
})}.release();
// No null replacement
{
auto const results = cudf::strings::join_list_elements(string_lv, separators->view());
std::vector<char const*> h_expected{nullptr, nullptr, nullptr, nullptr, nullptr, "zzz^^^xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// With null replacement for separators
{
auto const results =
cudf::strings::join_list_elements(string_lv, separators->view(), cudf::string_scalar("|||"));
std::vector<char const*> h_expected{
nullptr, nullptr, "0a0b0c|||xyzééé", nullptr, nullptr, "zzz^^^xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// With null replacement for strings
{
auto const results = cudf::strings::join_list_elements(
string_lv, separators->view(), cudf::string_scalar("", false), cudf::string_scalar("XXXXX"));
std::vector<char const*> h_expected{
"a+++XXXXX+++ccc", nullptr, nullptr, nullptr, "XXXXX%%%ááá%%%ííí", "zzz^^^xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// With null replacement for both separators and strings
{
auto const results = cudf::strings::join_list_elements(
string_lv, separators->view(), cudf::string_scalar("|||"), cudf::string_scalar("XXXXX"));
std::vector<char const*> h_expected{"a+++XXXXX+++ccc",
nullptr,
"0a0b0c|||xyzééé",
"XXXXX|||efgh|||ijk",
"XXXXX%%%ááá%%%ííí",
"zzz^^^xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Turn off separator-on-nulls
{
auto const results = cudf::strings::join_list_elements(string_lv,
separators->view(),
cudf::string_scalar("+++"),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
std::vector<char const*> h_expected{
"a+++ccc", nullptr, "0a0b0c+++xyzééé", "efgh+++ijk", "ááá%%%ííí", "zzz^^^xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
TEST_F(StringsListsConcatenateTest, SlicedListsWithColumnSeparators)
{
auto const string_lists = STR_LISTS{
{STR_LISTS{{"a", "bb" /*NULL*/, "ccc"}, null_at(1)},
STR_LISTS{}, /*NULL*/
STR_LISTS{{"ddd" /*NULL*/, "efgh", "ijk"}, null_at(0)},
STR_LISTS{"zzz", "xxxxx"},
STR_LISTS{"11111", "11111", "11111", "11111", "11111"}, /*NULL*/
STR_LISTS{{"abcdef", "012345", "" /*NULL*/, "xxx000"}, null_at(2)},
STR_LISTS{{"xyz" /*NULL*/, "11111", "00000"}, null_at(0)},
STR_LISTS{"0a0b0c", "5x5y5z"},
STR_LISTS{"xxx"}, /*NULL*/
STR_LISTS{"ééé", "12345abcdef"},
STR_LISTS{"aaaééébbbéééccc", "12345"}},
cudf::detail::make_counting_transform_iterator(0, [](auto i) {
return i != 1 && i != 4 && i != 8;
})}.release();
auto const separators = STR_COL{
{"+++", "***", "!!!" /*NULL*/, "$$$" /*NULL*/, "%%%", "^^^", "~!~", "###", "&&&", "-+-", "=+="},
cudf::detail::make_counting_transform_iterator(0, [](auto i) {
return i != 2 && i != 3;
})}.release();
// Sliced the entire lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 11})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {0, 11})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, sep_col);
std::vector<char const*> h_expected{nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
"0a0b0c###5x5y5z",
nullptr,
"ééé-+-12345abcdef",
"aaaééébbbéééccc=+=12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the entire lists column, with null replacements
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 11})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {0, 11})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, sep_col, cudf::string_scalar("|||"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"a+++___+++ccc",
nullptr,
"___|||efgh|||ijk",
"zzz|||xxxxx",
nullptr,
"abcdef^^^012345^^^___^^^xxx000",
"___~!~11111~!~00000",
"0a0b0c###5x5y5z",
nullptr,
"ééé-+-12345abcdef",
"aaaééébbbéééccc=+=12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the first half of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 4})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {0, 4})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, sep_col);
std::vector<char const*> h_expected{nullptr, nullptr, nullptr, nullptr};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the first half of the lists column, with null replacements
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {0, 4})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {0, 4})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, sep_col, cudf::string_scalar("|||"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{
"a+++___+++ccc", nullptr, "___|||efgh|||ijk", "zzz|||xxxxx"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the second half of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {5, 11})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {5, 11})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, sep_col);
std::vector<char const*> h_expected{
nullptr, nullptr, "0a0b0c###5x5y5z", nullptr, "ééé-+-12345abcdef", "aaaééébbbéééccc=+=12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the second half of the lists column, with null replacements
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {5, 11})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {5, 11})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, sep_col, cudf::string_scalar("|||"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"abcdef^^^012345^^^___^^^xxx000",
"___~!~11111~!~00000",
"0a0b0c###5x5y5z",
nullptr,
"ééé-+-12345abcdef",
"aaaééébbbéééccc=+=12345"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the middle part of the lists column, no null replacement
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {3, 8})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {3, 8})[0]);
auto const results = cudf::strings::join_list_elements(string_lv, sep_col);
std::vector<char const*> h_expected{nullptr, nullptr, nullptr, nullptr, "0a0b0c###5x5y5z"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
// Sliced the middle part of the lists column, with null replacements
{
auto const string_lv = cudf::lists_column_view(cudf::slice(string_lists->view(), {3, 8})[0]);
auto const sep_col = cudf::strings_column_view(cudf::slice(separators->view(), {3, 8})[0]);
auto const results = cudf::strings::join_list_elements(
string_lv, sep_col, cudf::string_scalar("|||"), cudf::string_scalar("___"));
std::vector<char const*> h_expected{"zzz|||xxxxx",
nullptr,
"abcdef^^^012345^^^___^^^xxx000",
"___~!~11111~!~00000",
"0a0b0c###5x5y5z"};
auto const expected =
STR_COL{h_expected.begin(), h_expected.end(), nulls_from_nullptrs(h_expected)};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected, verbosity);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/strings
|
rapidsai_public_repos/cudf/cpp/tests/strings/combine/concatenate_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/column/column_factories.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/combine.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/table/table.hpp>
#include <cudf/types.hpp>
#include <thrust/iterator/transform_iterator.h>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
struct StringsCombineTest : public cudf::test::BaseFixture {};
TEST_F(StringsCombineTest, Concatenate)
{
std::vector<char const*> h_strings1{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
cudf::test::strings_column_wrapper strings1(
h_strings1.begin(),
h_strings1.end(),
thrust::make_transform_iterator(h_strings1.begin(), [](auto str) { return str != nullptr; }));
std::vector<char const*> h_strings2{"xyz", "abc", "d", "éa", "", nullptr, "f"};
cudf::test::strings_column_wrapper strings2(
h_strings2.begin(),
h_strings2.end(),
thrust::make_transform_iterator(h_strings2.begin(), [](auto str) { return str != nullptr; }));
std::vector<cudf::column_view> strings_columns;
strings_columns.push_back(strings1);
strings_columns.push_back(strings2);
cudf::table_view table(strings_columns);
{
std::vector<char const*> h_expected{"eeexyz", "bbabc", nullptr, "éa", "aa", nullptr, "éééf"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::concatenate(table);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_expected{
"eee:xyz", "bb:abc", nullptr, ":éa", "aa:", nullptr, "ééé:f"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results = cudf::strings::concatenate(table, cudf::string_scalar(":"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_expected{"eee:xyz", "bb:abc", "_:d", ":éa", "aa:", "bbb:_", "ééé:f"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results =
cudf::strings::concatenate(table, cudf::string_scalar(":"), cudf::string_scalar("_"));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
{
std::vector<char const*> h_expected{"eeexyz", "bbabc", "d", "éa", "aa", "bbb", "éééf"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto results =
cudf::strings::concatenate(table, cudf::string_scalar(""), cudf::string_scalar(""));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected);
}
}
TEST_F(StringsCombineTest, ConcatenateSkipNulls)
{
cudf::test::strings_column_wrapper strings1({"eee", "", "", "", "aa", "bbb", "ééé"},
{1, 0, 0, 1, 1, 1, 1});
cudf::test::strings_column_wrapper strings2({"xyz", "", "d", "éa", "", "", "f"},
{1, 0, 1, 1, 1, 0, 1});
cudf::test::strings_column_wrapper strings3({"q", "", "s", "t", "u", "", "w"},
{1, 1, 1, 1, 1, 0, 1});
cudf::table_view table({strings1, strings2, strings3});
{
cudf::test::strings_column_wrapper expected(
{"eee+xyz+q", "++", "+d+s", "+éa+t", "aa++u", "bbb++", "ééé+f+w"});
auto results = cudf::strings::concatenate(table,
cudf::string_scalar("+"),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::YES);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
cudf::test::strings_column_wrapper expected(
{"eee+xyz+q", "", "d+s", "+éa+t", "aa++u", "bbb", "ééé+f+w"});
auto results = cudf::strings::concatenate(table,
cudf::string_scalar("+"),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
cudf::test::strings_column_wrapper expected(
{"eee+xyz+q", "", "", "+éa+t", "aa++u", "", "ééé+f+w"}, {1, 0, 0, 1, 1, 0, 1});
auto results = cudf::strings::concatenate(table,
cudf::string_scalar("+"),
cudf::string_scalar("", false),
cudf::strings::separator_on_nulls::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
{
cudf::test::strings_column_wrapper sep_col({"+", "-", ".", "@", "*", "^^", "#"});
auto results = cudf::strings::concatenate(table,
cudf::strings_column_view(sep_col),
cudf::string_scalar(""),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
cudf::test::strings_column_wrapper expected(
{"eee+xyz+q", "", "d.s", "@éa@t", "aa**u", "bbb", "ééé#f#w"});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected);
}
}
TEST_F(StringsCombineTest, ConcatZeroSizeStringsColumns)
{
auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view();
std::vector<cudf::column_view> strings_columns;
strings_columns.push_back(zero_size_strings_column);
strings_columns.push_back(zero_size_strings_column);
cudf::table_view table(strings_columns);
auto results = cudf::strings::concatenate(table);
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsCombineTest, SingleColumnErrorCheck)
{
auto const col0 = cudf::make_empty_column(cudf::type_id::STRING);
EXPECT_THROW(cudf::strings::concatenate(cudf::table_view{{col0->view()}}), cudf::logic_error);
}
struct StringsConcatenateWithColSeparatorTest : public cudf::test::BaseFixture {};
TEST_F(StringsConcatenateWithColSeparatorTest, ExceptionTests)
{
// Exception tests
// 0. 0 columns passed
// 1. > 0 columns passed; some using non string data types
// 2. separator column of different size to column size
{
EXPECT_THROW(cudf::strings::concatenate(cudf::table_view{},
cudf::strings_column_view{cudf::column_view{}}),
cudf::logic_error);
}
{
auto const col0 = cudf::make_empty_column(cudf::type_id::STRING)->view();
cudf::test::fixed_width_column_wrapper<int64_t> col1{{1}};
EXPECT_THROW(
cudf::strings::concatenate(cudf::table_view{{col0, col1}}, cudf::strings_column_view(col0)),
cudf::logic_error);
}
{
auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto sep_col = cudf::test::strings_column_wrapper({"", ""}, {true, false});
EXPECT_THROW(
cudf::strings::concatenate(cudf::table_view{{col0}}, cudf::strings_column_view(sep_col)),
cudf::logic_error);
}
}
TEST_F(StringsConcatenateWithColSeparatorTest, ZeroSizedColumns)
{
auto const col0 = cudf::make_empty_column(cudf::type_id::STRING)->view();
auto results =
cudf::strings::concatenate(cudf::table_view{{col0}}, cudf::strings_column_view(col0));
cudf::test::expect_column_empty(results->view());
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnEmptyAndNullStringsNoReplacements)
{
auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto sep_col = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, true});
auto exp_results =
cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, false});
auto results =
cudf::strings::concatenate(cudf::table_view{{col0}}, cudf::strings_column_view(sep_col));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnEmptyAndNullStringsSeparatorReplacement)
{
auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto sep_col = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, true});
auto sep_rep = cudf::string_scalar("");
auto exp_results =
cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0}}, cudf::strings_column_view(sep_col), sep_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnEmptyAndNullStringsColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto sep_col = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, true});
auto col_rep = cudf::string_scalar("");
auto exp_results =
cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, true});
auto results = cudf::strings::concatenate(cudf::table_view{{col0}},
cudf::strings_column_view(sep_col),
cudf::string_scalar("", false),
col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest,
SingleColumnEmptyAndNullStringsSeparatorAndColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false});
auto sep_col = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, false, true});
auto sep_rep = cudf::string_scalar("");
auto col_rep = cudf::string_scalar("");
auto exp_results = cudf::test::strings_column_wrapper({"", "", "", ""});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0}}, cudf::strings_column_view(sep_col), sep_rep, col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnStringMixNoReplacements)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "bbabc", "invalid", "d", "éa", "invalid", "bbb", "éééf"},
{true, false, true, true, false, true, true, false, true, true});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~", "!", "@", "#", "$", "%", "^", "&", "*"},
{false, false, true, true, true, true, true, false, true, true});
auto exp_results = cudf::test::strings_column_wrapper(
{"", "", "", "bbabc", "", "d", "éa", "", "bbb", "éééf"},
{false, false, true, true, false, true, true, false, true, true});
auto results =
cudf::strings::concatenate(cudf::table_view{{col0}}, cudf::strings_column_view(sep_col));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnStringMixSeparatorReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "bbabc", "invalid", "d", "éa", "invalid", "bbb", "éééf"},
{true, false, true, true, false, true, true, false, true, true});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~", "!", "@", "#", "$", "%", "^", "&", "*"},
{false, false, false, true, true, true, true, false, true, true});
auto sep_rep = cudf::string_scalar("-");
auto exp_results = cudf::test::strings_column_wrapper(
{"eeexyz", "", "", "bbabc", "", "d", "éa", "", "bbb", "éééf"},
{true, false, true, true, false, true, true, false, true, true});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0}}, cudf::strings_column_view(sep_col), sep_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnStringMixColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "bbabc", "invalid", "d", "éa", "invalid", "bbb", "éééf"},
{true, false, true, true, false, true, true, false, true, true});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~", "!", "@", "#", "$", "%", "^", "&", "*"},
{false, false, false, true, true, true, true, false, true, true});
auto col_rep = cudf::string_scalar("goobly");
auto exp_results = cudf::test::strings_column_wrapper(
{"", "", "", "bbabc", "goobly", "d", "éa", "", "bbb", "éééf"},
{false, false, false, true, true, true, true, false, true, true});
auto results = cudf::strings::concatenate(cudf::table_view{{col0}},
cudf::strings_column_view(sep_col),
cudf::string_scalar("", false),
col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, SingleColumnStringMixSeparatorAndColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "bbabc", "invalid", "d", "éa", "invalid", "bbb", "éééf"},
{true, false, true, true, false, true, true, false, true, true});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~", "!", "@", "#", "$", "%", "^", "&", "*"},
{false, false, false, true, true, true, true, false, true, true});
auto sep_rep = cudf::string_scalar("-");
auto col_rep = cudf::string_scalar("goobly");
// All valid, as every invalid element is replaced - a non nullable column
auto exp_results = cudf::test::strings_column_wrapper(
{"eeexyz", "goobly", "", "bbabc", "goobly", "d", "éa", "goobly", "bbb", "éééf"});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0}}, cudf::strings_column_view(sep_col), sep_rep, col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnEmptyAndNullStringsNoReplacements)
{
auto col0 = cudf::test::strings_column_wrapper(
{"", "", "", "", "", "", "", ""}, {false, false, true, true, true, true, false, false});
auto col1 = cudf::test::strings_column_wrapper(
{"", "", "", "", "", "", "", ""}, {false, false, true, true, false, false, true, true});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "", "", "", "", "", "", ""}, {true, false, true, false, true, false, true, false});
auto exp_results1 = cudf::test::strings_column_wrapper(
{"", "", "", "", "", "", "", ""}, {false, false, true, false, false, false, false, false});
auto results =
cudf::strings::concatenate(cudf::table_view{{col0, col1}}, cudf::strings_column_view(sep_col));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results1, verbosity);
auto exp_results2 = cudf::test::strings_column_wrapper(
{"", "", "", "", "", "", "", ""}, {true, false, true, false, true, false, true, false});
results = cudf::strings::concatenate(cudf::table_view{{col0, col1}},
cudf::strings_column_view(sep_col),
cudf::string_scalar("", false),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results2, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnStringMixNoReplacements)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "éééf", "éa", "", "", "invalid", "null", "NULL", "-1", ""},
{true, true, true, true, true, true, false, false, false, false, false, false});
auto col1 = cudf::test::strings_column_wrapper(
{"foo", "", "éaff", "", "invalid", "NULL", "éaff", "valid", "doo", "", "<null>", "-1"},
{true, true, true, false, false, false, true, true, true, false, false, false});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~~~", "", "@", "", "", "", "^^^^", "", "--", "*****", "######"},
{true, true, false, true, false, true, false, true, true, true, true, true});
auto exp_results1 = cudf::test::strings_column_wrapper(
{"eeexyzfoo", "<null>~~~", "", "", "", "", "", "", "", "", "", ""},
{true, true, false, false, false, false, false, false, false, false, false, false});
auto results =
cudf::strings::concatenate(cudf::table_view{{col0, col1}}, cudf::strings_column_view(sep_col));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results1, verbosity);
auto exp_results2 = cudf::test::strings_column_wrapper(
{"eeexyzfoo", "<null>~~~", "", "éééf", "", "", "", "valid", "doo", "", "", ""},
{true, true, false, true, false, true, false, true, true, true, true, true});
results = cudf::strings::concatenate(cudf::table_view{{col0, col1}},
cudf::strings_column_view(sep_col),
cudf::string_scalar("", false),
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results2, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnStringMixSeparatorReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "éééf", "éa", "", "", "invalid", "null", "NULL", "-1", ""},
{true, true, true, true, true, true, false, false, false, false, false, false});
auto col1 = cudf::test::strings_column_wrapper(
{"foo", "", "éaff", "", "invalid", "NULL", "éaff", "valid", "doo", "", "<null>", "-1"},
{true, true, true, false, false, false, true, true, true, false, false, false});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~~~", "", "@", "", "", "", "^^^^", "", "--", "*****", "######"},
{true, true, false, true, false, true, false, true, true, true, true, true});
auto sep_rep = cudf::string_scalar("!!!!!!!");
auto exp_results1 = cudf::test::strings_column_wrapper(
{"eeexyzfoo", "<null>~~~", "!!!!!!!éaff", "éééf", "éa", "", "éaff", "valid", "doo", "", "", ""},
{true, true, true, false, false, false, false, false, false, false, false, false});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0, col1}}, cudf::strings_column_view(sep_col), sep_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results1, verbosity);
auto exp_results2 = cudf::test::strings_column_wrapper(
{"eeexyzfoo", "<null>~~~", "!!!!!!!éaff", "éééf", "éa", "", "éaff", "valid", "doo", "", "", ""},
{true, true, true, true, true, true, true, true, true, true, true, true});
results = cudf::strings::concatenate(cudf::table_view{{col0, col1}},
cudf::strings_column_view(sep_col),
sep_rep,
cudf::string_scalar(""),
cudf::strings::separator_on_nulls::NO);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results2, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnStringMixColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "éééf", "éa", "", "", "invalid", "null", "NULL", "-1", ""},
{true, true, true, true, true, true, false, false, false, false, false, false});
auto col1 = cudf::test::strings_column_wrapper(
{"foo", "", "éaff", "", "invalid", "NULL", "éaff", "valid", "doo", "", "<null>", "-1"},
{true, true, true, false, false, false, true, true, true, false, false, false});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~~~", "", "@", "", "", "", "^^^^", "", "--", "*****", "######"},
{true, true, false, true, false, true, false, true, true, true, true, true});
auto col_rep = cudf::string_scalar("_col_replacement_");
auto exp_results = cudf::test::strings_column_wrapper(
{"eeexyzfoo",
"<null>~~~",
"",
"éééf@_col_replacement_",
"",
"_col_replacement_",
"",
"_col_replacement_^^^^valid",
"_col_replacement_doo",
"_col_replacement_--_col_replacement_",
"_col_replacement_*****_col_replacement_",
"_col_replacement_######_col_replacement_"},
{true, true, false, true, false, true, false, true, true, true, true, true});
auto results = cudf::strings::concatenate(cudf::table_view{{col0, col1}},
cudf::strings_column_view(sep_col),
cudf::string_scalar("", false),
col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnStringMixSeparatorAndColumnReplacement)
{
auto col0 = cudf::test::strings_column_wrapper(
{"eeexyz", "<null>", "", "éééf", "éa", "", "", "invalid", "null", "NULL", "-1", ""},
{true, true, true, true, true, true, false, false, false, false, false, false});
auto col1 = cudf::test::strings_column_wrapper(
{"foo", "", "éaff", "", "invalid", "NULL", "éaff", "valid", "doo", "", "<null>", "-1"},
{true, true, true, false, false, false, true, true, true, false, false, false});
auto sep_col = cudf::test::strings_column_wrapper(
{"", "~~~", "", "@", "", "", "", "^^^^", "", "--", "*****", "######"},
{true, true, false, true, false, true, false, true, true, true, true, true});
auto sep_rep = cudf::string_scalar("!!!!!!!!!!");
auto col_rep = cudf::string_scalar("_col_replacement_");
// Every null item (separator/column) is replaced - a non nullable column
auto exp_results =
cudf::test::strings_column_wrapper({"eeexyzfoo",
"<null>~~~",
"!!!!!!!!!!éaff",
"éééf@_col_replacement_",
"éa!!!!!!!!!!_col_replacement_",
"_col_replacement_",
"_col_replacement_!!!!!!!!!!éaff",
"_col_replacement_^^^^valid",
"_col_replacement_doo",
"_col_replacement_--_col_replacement_",
"_col_replacement_*****_col_replacement_",
"_col_replacement_######_col_replacement_"});
auto results = cudf::strings::concatenate(
cudf::table_view{{col0, col1}}, cudf::strings_column_view(sep_col), sep_rep, col_rep);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, exp_results, verbosity);
}
TEST_F(StringsConcatenateWithColSeparatorTest, MultiColumnNonNullableStrings)
{
auto col0 =
cudf::test::strings_column_wrapper({"eeexyz", "<null>", "éaff", "éééf", "", "", "", ""});
auto col1 = cudf::test::strings_column_wrapper({"foo", "nan", "", "", "NULL", "éaff", "", ""});
auto sep_col = cudf::test::strings_column_wrapper({"", "~~~", "", "@", "", "+++", "", "^^^^"});
// Every item (separator/column) is used, as everything is valid producing a non nullable column
auto exp_results = cudf::test::strings_column_wrapper(
{"eeexyzfoo", "<null>~~~nan", "éaff", "éééf@", "NULL", "+++éaff", "", "^^^^"});
auto results =
cudf::strings::concatenate(cudf::table_view{{col0, col1}}, cudf::strings_column_view(sep_col));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, exp_results, verbosity);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/interop/dlpack_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/interop.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 <dlpack/dlpack.h>
#include <thrust/host_vector.h>
struct dlpack_deleter {
void operator()(DLManagedTensor* tensor) { tensor->deleter(tensor); }
};
using unique_managed_tensor = std::unique_ptr<DLManagedTensor, dlpack_deleter>;
template <typename T>
DLDataType get_dtype()
{
uint8_t const bits{sizeof(T) * 8};
uint16_t const lanes{1};
if (std::is_floating_point_v<T>) {
return DLDataType{kDLFloat, bits, lanes};
} else if (std::is_signed_v<T>) {
return DLDataType{kDLInt, bits, lanes};
} else if (std::is_unsigned_v<T>) {
return DLDataType{kDLUInt, bits, lanes};
} else {
static_assert(true, "unsupported type");
}
}
template <typename T>
void validate_dtype(DLDataType const& dtype)
{
switch (dtype.code) {
case kDLInt: EXPECT_TRUE(std::is_integral_v<T> && std::is_signed_v<T>); break;
case kDLUInt: EXPECT_TRUE(std::is_integral_v<T> && std::is_unsigned_v<T>); break;
case kDLFloat: EXPECT_TRUE(std::is_floating_point_v<T>); break;
default: FAIL();
}
EXPECT_EQ(1, dtype.lanes);
EXPECT_EQ(sizeof(T) * 8, dtype.bits);
}
class DLPackUntypedTests : public cudf::test::BaseFixture {};
TEST_F(DLPackUntypedTests, EmptyTableToDlpack)
{
cudf::table_view empty(std::vector<cudf::column_view>{});
// No type information to construct a correct empty dlpack object
EXPECT_EQ(nullptr, cudf::to_dlpack(empty));
}
TEST_F(DLPackUntypedTests, EmptyColsToDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col1({});
cudf::test::fixed_width_column_wrapper<int32_t> col2({});
cudf::table_view input({col1, col2});
unique_managed_tensor tensor(cudf::to_dlpack(input));
validate_dtype<int32_t>(tensor->dl_tensor.dtype);
EXPECT_NE(nullptr, tensor);
EXPECT_EQ(nullptr, tensor->dl_tensor.data);
EXPECT_EQ(2, tensor->dl_tensor.ndim);
EXPECT_EQ(0, tensor->dl_tensor.strides[0]);
EXPECT_EQ(0, tensor->dl_tensor.strides[1]);
EXPECT_EQ(0, tensor->dl_tensor.shape[0]);
EXPECT_EQ(2, tensor->dl_tensor.shape[1]);
EXPECT_EQ(kDLCUDA, tensor->dl_tensor.device.device_type);
auto result = cudf::from_dlpack(tensor.get());
CUDF_TEST_EXPECT_TABLES_EQUAL(input, result->view());
}
TEST_F(DLPackUntypedTests, NullTensorFromDlpack)
{
EXPECT_THROW(cudf::from_dlpack(nullptr), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, MultipleTypesToDlpack)
{
cudf::test::fixed_width_column_wrapper<int16_t> col1({1, 2, 3, 4});
cudf::test::fixed_width_column_wrapper<int32_t> col2({1, 2, 3, 4});
cudf::table_view input({col1, col2});
EXPECT_THROW(cudf::to_dlpack(input), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, InvalidNullsToDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col1({1, 2, 3, 4});
cudf::test::fixed_width_column_wrapper<int32_t> col2({1, 2, 3, 4}, {1, 0, 1, 1});
cudf::table_view input({col1, col2});
EXPECT_THROW(cudf::to_dlpack(input), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, StringTypeToDlpack)
{
cudf::test::strings_column_wrapper col({"foo", "bar", "baz"});
cudf::table_view input({col});
EXPECT_THROW(cudf::to_dlpack(input), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedDeviceTypeFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an unsupported device type
tensor->dl_tensor.device.device_type = kDLOpenCL;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, InvalidDeviceIdFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof the wrong device ID
tensor->dl_tensor.device.device_id += 1;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedDimsFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an unsupported number of dims
tensor->dl_tensor.ndim = 3;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, TooManyRowsFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof too many rows
constexpr int64_t max_size_type{std::numeric_limits<int32_t>::max()};
tensor->dl_tensor.shape[0] = max_size_type + 1;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), std::overflow_error);
}
TEST_F(DLPackUntypedTests, TooManyColsFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col1({1, 2, 3, 4});
cudf::test::fixed_width_column_wrapper<int32_t> col2({5, 6, 7, 8});
cudf::table_view input({col1, col2});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof too many cols
constexpr int64_t max_size_type{std::numeric_limits<int32_t>::max()};
tensor->dl_tensor.shape[1] = max_size_type + 1;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), std::overflow_error);
}
TEST_F(DLPackUntypedTests, InvalidTypeFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an invalid data type
tensor->dl_tensor.dtype.code = 3;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedIntBitsizeFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an unsupported bitsize
tensor->dl_tensor.dtype.bits = 7;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedFloatBitsizeFromDlpack)
{
cudf::test::fixed_width_column_wrapper<float> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an unsupported bitsize
tensor->dl_tensor.dtype.bits = 7;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedLanesFromDlpack)
{
cudf::test::fixed_width_column_wrapper<int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Spoof an unsupported number of lanes
tensor->dl_tensor.dtype.lanes = 2;
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedBroadcast1DTensorFromDlpack)
{
using T = float;
constexpr int ndim = 1;
// Broadcasted (stride-0) 1D tensor
auto const data = cudf::test::make_type_param_vector<T>({1});
int64_t shape[ndim] = {5};
int64_t strides[ndim] = {0};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = ndim;
tensor.dl_tensor.byte_offset = 0;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = strides;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
EXPECT_THROW(cudf::from_dlpack(&tensor), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedStrided1DTensorFromDlpack)
{
using T = float;
constexpr int ndim = 1;
// Strided 1D tensor
auto const data = cudf::test::make_type_param_vector<T>({1, 2, 3, 4});
int64_t shape[ndim] = {2};
int64_t strides[ndim] = {2};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = ndim;
tensor.dl_tensor.byte_offset = 0;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = strides;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
EXPECT_THROW(cudf::from_dlpack(&tensor), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedImplicitRowMajor2DTensorFromDlpack)
{
using T = float;
constexpr int ndim = 2;
// Row major 2D tensor
auto const data = cudf::test::make_type_param_vector<T>({1, 2, 3, 4});
int64_t shape[ndim] = {2, 2};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = ndim;
tensor.dl_tensor.byte_offset = 0;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = nullptr;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
EXPECT_THROW(cudf::from_dlpack(&tensor), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedExplicitRowMajor2DTensorFromDlpack)
{
using T = float;
constexpr int ndim = 2;
// Row major 2D tensor with explicit strides
auto const data = cudf::test::make_type_param_vector<T>({1, 2, 3, 4});
int64_t shape[ndim] = {2, 2};
int64_t strides[ndim] = {2, 1};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = ndim;
tensor.dl_tensor.byte_offset = 0;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = strides;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
EXPECT_THROW(cudf::from_dlpack(&tensor), cudf::logic_error);
}
TEST_F(DLPackUntypedTests, UnsupportedStridedColMajor2DTensorFromDlpack)
{
using T = float;
constexpr int ndim = 2;
// Column major, but strided in fastest dimension
auto const data = cudf::test::make_type_param_vector<T>({1, 2, 3, 4, 5, 6, 7, 8});
int64_t shape[ndim] = {2, 2};
int64_t strides[ndim] = {2, 4};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = ndim;
tensor.dl_tensor.byte_offset = 0;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = strides;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
EXPECT_THROW(cudf::from_dlpack(&tensor), cudf::logic_error);
}
template <typename T>
class DLPackTimestampTests : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(DLPackTimestampTests, cudf::test::ChronoTypes);
TYPED_TEST(DLPackTimestampTests, ChronoTypesToDlpack)
{
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4});
cudf::table_view input({col});
EXPECT_THROW(cudf::to_dlpack(input), cudf::logic_error);
}
template <typename T>
class DLPackNumericTests : public cudf::test::BaseFixture {};
// The list of supported types comes from DLDataType_to_data_type() in cpp/src/dlpack/dlpack.cpp
// TODO: Replace with `NumericTypes` when unsigned support is added. Issue #5353
using SupportedTypes =
cudf::test::RemoveIf<cudf::test::ContainedIn<cudf::test::Types<bool>>, cudf::test::NumericTypes>;
TYPED_TEST_SUITE(DLPackNumericTests, SupportedTypes);
TYPED_TEST(DLPackNumericTests, ToDlpack1D)
{
// Test nullable column with no nulls
cudf::test::fixed_width_column_wrapper<TypeParam> col({1, 2, 3, 4}, {1, 1, 1, 1});
auto const col_view = static_cast<cudf::column_view>(col);
EXPECT_FALSE(col_view.has_nulls());
EXPECT_TRUE(col_view.nullable());
cudf::table_view input({col});
unique_managed_tensor result(cudf::to_dlpack(input));
auto const& tensor = result->dl_tensor;
validate_dtype<TypeParam>(tensor.dtype);
EXPECT_EQ(kDLCUDA, tensor.device.device_type);
EXPECT_EQ(1, tensor.ndim);
EXPECT_EQ(uint64_t{0}, tensor.byte_offset);
EXPECT_EQ(nullptr, tensor.strides);
EXPECT_NE(nullptr, tensor.data);
EXPECT_NE(nullptr, tensor.shape);
// Verify that data matches input column
constexpr cudf::data_type type{cudf::type_to_id<TypeParam>()};
cudf::column_view const result_view(
type, tensor.shape[0], tensor.data, col_view.null_mask(), col_view.null_count());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(col_view, result_view);
}
TYPED_TEST(DLPackNumericTests, ToDlpack2D)
{
using T = TypeParam;
auto const col1_tmp = cudf::test::make_type_param_vector<T>({1, 2, 3, 4});
auto const col2_tmp = cudf::test::make_type_param_vector<T>({4, 5, 6, 7});
std::vector<cudf::test::fixed_width_column_wrapper<TypeParam>> cols;
cols.push_back(
cudf::test::fixed_width_column_wrapper<TypeParam>(col1_tmp.cbegin(), col1_tmp.cend()));
cols.push_back(
cudf::test::fixed_width_column_wrapper<TypeParam>(col2_tmp.cbegin(), col2_tmp.cend()));
std::vector<cudf::column_view> col_views;
std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](auto const& col) {
return static_cast<cudf::column_view>(col);
});
cudf::table_view input(col_views);
unique_managed_tensor result(cudf::to_dlpack(input));
auto const& tensor = result->dl_tensor;
validate_dtype<TypeParam>(tensor.dtype);
EXPECT_EQ(kDLCUDA, tensor.device.device_type);
EXPECT_EQ(2, tensor.ndim);
EXPECT_EQ(uint64_t{0}, tensor.byte_offset);
EXPECT_NE(nullptr, tensor.data);
EXPECT_NE(nullptr, tensor.shape);
EXPECT_NE(nullptr, tensor.strides);
EXPECT_EQ(1, tensor.strides[0]);
EXPECT_EQ(tensor.shape[0], tensor.strides[1]);
// Verify that data matches input columns
cudf::size_type offset{0};
for (auto const& col : input) {
constexpr cudf::data_type type{cudf::type_to_id<TypeParam>()};
cudf::column_view const result_view(type, tensor.shape[0], tensor.data, nullptr, 0, offset);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(col, result_view);
offset += tensor.strides[1];
}
}
TYPED_TEST(DLPackNumericTests, FromDlpack1D)
{
// Use to_dlpack to generate an input tensor
cudf::test::fixed_width_column_wrapper<TypeParam> col({1, 2, 3, 4});
cudf::table_view input({col});
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Verify that from_dlpack(to_dlpack(input)) == input
auto result = cudf::from_dlpack(tensor.get());
CUDF_TEST_EXPECT_TABLES_EQUAL(input, result->view());
}
TYPED_TEST(DLPackNumericTests, FromDlpack2D)
{
// Use to_dlpack to generate an input tensor
using T = TypeParam;
auto const col1 = cudf::test::make_type_param_vector<T>({1, 2, 3, 4});
auto const col2 = cudf::test::make_type_param_vector<T>({4, 5, 6, 7});
std::vector<cudf::test::fixed_width_column_wrapper<TypeParam>> cols;
cols.push_back(cudf::test::fixed_width_column_wrapper<T>(col1.cbegin(), col1.cend()));
cols.push_back(cudf::test::fixed_width_column_wrapper<T>(col2.cbegin(), col2.cend()));
std::vector<cudf::column_view> col_views;
std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](auto const& col) {
return static_cast<cudf::column_view>(col);
});
cudf::table_view input(col_views);
unique_managed_tensor tensor(cudf::to_dlpack(input));
// Verify that from_dlpack(to_dlpack(input)) == input
auto result = cudf::from_dlpack(tensor.get());
CUDF_TEST_EXPECT_TABLES_EQUAL(input, result->view());
}
TYPED_TEST(DLPackNumericTests, FromDlpackCpu)
{
// Host buffer with stride > rows and byte_offset > 0
using T = TypeParam;
auto const data = cudf::test::make_type_param_vector<T>({0, 1, 2, 3, 4, 0, 5, 6, 7, 8, 0});
uint64_t const offset{sizeof(T)};
int64_t shape[2] = {4, 2};
int64_t strides[2] = {1, 5};
DLManagedTensor tensor{};
tensor.dl_tensor.device.device_type = kDLCPU;
tensor.dl_tensor.dtype = get_dtype<T>();
tensor.dl_tensor.ndim = 2;
tensor.dl_tensor.byte_offset = offset;
tensor.dl_tensor.shape = shape;
tensor.dl_tensor.strides = strides;
thrust::host_vector<T> host_vector(data.begin(), data.end());
tensor.dl_tensor.data = host_vector.data();
cudf::test::fixed_width_column_wrapper<TypeParam> col1({1, 2, 3, 4});
cudf::test::fixed_width_column_wrapper<TypeParam> col2({5, 6, 7, 8});
cudf::table_view expected({col1, col2});
auto result = cudf::from_dlpack(&tensor);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result->view());
}
TYPED_TEST(DLPackNumericTests, FromDlpackEmpty1D)
{
// Use to_dlpack to generate an input tensor
cudf::table_view input(std::vector<cudf::column_view>{});
unique_managed_tensor tensor(cudf::to_dlpack(input));
EXPECT_EQ(nullptr, tensor.get());
EXPECT_THROW(cudf::from_dlpack(tensor.get()), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/interop/to_arrow_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.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.hpp>
#include <cudf/interop.hpp>
#include <cudf/scalar/scalar_factories.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 <tests/interop/arrow_utils.hpp>
#include <thrust/iterator/counting_iterator.h>
using vector_of_columns = std::vector<std::unique_ptr<cudf::column>>;
std::pair<std::unique_ptr<cudf::table>, std::shared_ptr<arrow::Table>> get_tables(
cudf::size_type length)
{
std::vector<int64_t> int64_data(length);
std::vector<bool> bool_data(length);
std::vector<std::string> string_data(length);
std::vector<uint8_t> validity(length);
std::vector<bool> bool_validity(length);
std::vector<uint8_t> bool_data_validity;
cudf::size_type length_of_individual_list = 3;
cudf::size_type length_of_list = length_of_individual_list * length;
std::vector<int64_t> list_int64_data(length_of_list);
std::vector<uint8_t> list_int64_data_validity(length_of_list);
std::vector<int32_t> list_offsets(length + 1);
std::vector<std::unique_ptr<cudf::column>> columns;
std::generate(int64_data.begin(), int64_data.end(), []() { return rand() % 500000; });
std::generate(list_int64_data.begin(), list_int64_data.end(), []() { return rand() % 500000; });
auto validity_generator = []() { return rand() % 7 != 0; };
std::generate(
list_int64_data_validity.begin(), list_int64_data_validity.end(), validity_generator);
// cudf::size_type n = 0;
std::generate(
list_offsets.begin(), list_offsets.end(), [length_of_individual_list, n = 0]() mutable {
return (n++) * length_of_individual_list;
});
std::generate(bool_data.begin(), bool_data.end(), validity_generator);
std::generate(
string_data.begin(), string_data.end(), []() { return rand() % 7 != 0 ? "CUDF" : "Rocks"; });
std::generate(validity.begin(), validity.end(), validity_generator);
std::generate(bool_validity.begin(), bool_validity.end(), validity_generator);
std::transform(bool_validity.cbegin(),
bool_validity.cend(),
std::back_inserter(bool_data_validity),
[](auto val) { return static_cast<uint8_t>(val); });
columns.emplace_back(cudf::test::fixed_width_column_wrapper<int64_t>(
int64_data.begin(), int64_data.end(), validity.begin())
.release());
columns.emplace_back(
cudf::test::strings_column_wrapper(string_data.begin(), string_data.end(), validity.begin())
.release());
auto col4 = cudf::test::fixed_width_column_wrapper<int64_t>(
int64_data.begin(), int64_data.end(), validity.begin());
auto dict_col = cudf::dictionary::encode(col4);
columns.emplace_back(std::move(cudf::dictionary::encode(col4)));
columns.emplace_back(cudf::test::fixed_width_column_wrapper<bool>(
bool_data.begin(), bool_data.end(), bool_validity.begin())
.release());
auto list_child_column = cudf::test::fixed_width_column_wrapper<int64_t>(
list_int64_data.begin(), list_int64_data.end(), list_int64_data_validity.begin());
auto list_offsets_column =
cudf::test::fixed_width_column_wrapper<int32_t>(list_offsets.begin(), list_offsets.end());
auto [list_mask, list_nulls] = cudf::bools_to_mask(cudf::test::fixed_width_column_wrapper<bool>(
bool_data_validity.begin(), bool_data_validity.end()));
columns.emplace_back(cudf::make_lists_column(length,
list_offsets_column.release(),
list_child_column.release(),
list_nulls,
std::move(*list_mask)));
auto int_column = cudf::test::fixed_width_column_wrapper<int64_t>(
int64_data.begin(), int64_data.end(), validity.begin())
.release();
auto str_column =
cudf::test::strings_column_wrapper(string_data.begin(), string_data.end(), validity.begin())
.release();
vector_of_columns cols;
cols.push_back(move(int_column));
cols.push_back(move(str_column));
auto [null_mask, null_count] = cudf::bools_to_mask(cudf::test::fixed_width_column_wrapper<bool>(
bool_data_validity.begin(), bool_data_validity.end()));
columns.emplace_back(
cudf::make_structs_column(length, std::move(cols), null_count, std::move(*null_mask)));
auto int64array = get_arrow_array<int64_t>(int64_data, validity);
auto string_array = get_arrow_array<cudf::string_view>(string_data, validity);
cudf::dictionary_column_view view(dict_col->view());
auto keys = cudf::test::to_host<int64_t>(view.keys()).first;
auto indices = cudf::test::to_host<uint32_t>(view.indices()).first;
auto dict_array = get_arrow_dict_array(std::vector<int64_t>(keys.begin(), keys.end()),
std::vector<int32_t>(indices.begin(), indices.end()),
validity);
auto boolarray = get_arrow_array<bool>(bool_data, bool_validity);
auto list_array = get_arrow_list_array<int64_t>(
list_int64_data, list_offsets, list_int64_data_validity, bool_data_validity);
arrow::ArrayVector child_arrays({int64array, string_array});
std::vector<std::shared_ptr<arrow::Field>> fields = {
arrow::field("integral", int64array->type(), int64array->null_count() > 0),
arrow::field("string", string_array->type(), string_array->null_count() > 0)};
auto dtype = std::make_shared<arrow::StructType>(fields);
std::shared_ptr<arrow::Buffer> mask_buffer =
arrow::internal::BytesToBits(static_cast<std::vector<uint8_t>>(bool_data_validity))
.ValueOrDie();
auto struct_array =
std::make_shared<arrow::StructArray>(dtype, length, child_arrays, mask_buffer);
std::vector<std::shared_ptr<arrow::Field>> schema_vector = {
arrow::field("a", int64array->type()),
arrow::field("b", string_array->type()),
arrow::field("c", dict_array->type()),
arrow::field("d", boolarray->type()),
arrow::field("e", list_array->type()),
arrow::field("f", struct_array->type())};
auto schema = std::make_shared<arrow::Schema>(schema_vector);
return std::pair(
std::make_unique<cudf::table>(std::move(columns)),
arrow::Table::Make(
schema, {int64array, string_array, dict_array, boolarray, list_array, struct_array}));
}
struct ToArrowTest : public cudf::test::BaseFixture {};
template <typename T>
struct ToArrowTestDurationsTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ToArrowTestDurationsTest, cudf::test::DurationTypes);
TEST_F(ToArrowTest, EmptyTable)
{
auto tables = get_tables(0);
auto cudf_table_view = tables.first->view();
auto expected_arrow_table = tables.second;
auto struct_meta = cudf::column_metadata{"f"};
struct_meta.children_meta = {{"integral"}, {"string"}};
auto got_arrow_table =
cudf::to_arrow(cudf_table_view, {{"a"}, {"b"}, {"c"}, {"d"}, {"e"}, struct_meta});
ASSERT_EQ(expected_arrow_table->Equals(*got_arrow_table, true), true);
}
TEST_F(ToArrowTest, DateTimeTable)
{
auto data = {1, 2, 3, 4, 5, 6};
auto col =
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep>(data);
cudf::table_view input_view({col});
std::shared_ptr<arrow::Array> arr;
arrow::TimestampBuilder timestamp_builder(timestamp(arrow::TimeUnit::type::MILLI),
arrow::default_memory_pool());
ASSERT_TRUE(timestamp_builder.AppendValues(std::vector<int64_t>{1, 2, 3, 4, 5, 6}).ok());
ASSERT_TRUE(timestamp_builder.Finish(&arr).ok());
std::vector<std::shared_ptr<arrow::Field>> schema_vector({arrow::field("a", arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input_view, {{"a"}});
ASSERT_EQ(expected_arrow_table->Equals(*got_arrow_table, true), true);
}
TYPED_TEST(ToArrowTestDurationsTest, DurationTable)
{
using T = TypeParam;
auto data = {T{1}, T{2}, T{3}, T{4}, T{5}, T{6}};
auto col = cudf::test::fixed_width_column_wrapper<T>(data);
cudf::table_view input_view({col});
std::shared_ptr<arrow::Array> arr;
arrow::TimeUnit::type arrow_unit;
switch (cudf::type_to_id<TypeParam>()) {
case cudf::type_id::DURATION_SECONDS: arrow_unit = arrow::TimeUnit::type::SECOND; break;
case cudf::type_id::DURATION_MILLISECONDS: arrow_unit = arrow::TimeUnit::type::MILLI; break;
case cudf::type_id::DURATION_MICROSECONDS: arrow_unit = arrow::TimeUnit::type::MICRO; break;
case cudf::type_id::DURATION_NANOSECONDS: arrow_unit = arrow::TimeUnit::type::NANO; break;
case cudf::type_id::DURATION_DAYS: return;
default: CUDF_FAIL("Unsupported duration unit in arrow");
}
arrow::DurationBuilder duration_builder(duration(arrow_unit), arrow::default_memory_pool());
ASSERT_TRUE(duration_builder.AppendValues(std::vector<int64_t>{1, 2, 3, 4, 5, 6}).ok());
ASSERT_TRUE(duration_builder.Finish(&arr).ok());
std::vector<std::shared_ptr<arrow::Field>> schema_vector({arrow::field("a", arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input_view, {{"a"}});
ASSERT_EQ(expected_arrow_table->Equals(*got_arrow_table, true), true);
}
TEST_F(ToArrowTest, NestedList)
{
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 3 != 0; });
auto col = cudf::test::lists_column_wrapper<int64_t>(
{{{{{1, 2}, valids}, {{3, 4}, valids}, {5}}, {{6}, {{7, 8, 9}, valids}}}, valids});
cudf::table_view input_view({col});
auto list_arr = get_arrow_list_array<int64_t>({6, 7, 8, 9}, {0, 1, 4}, {1, 0, 1, 1});
std::vector<int32_t> offset{0, 0, 2};
auto mask_buffer = arrow::internal::BytesToBits({0, 1}).ValueOrDie();
auto nested_list_arr = std::make_shared<arrow::ListArray>(arrow::list(list(arrow::int64())),
offset.size() - 1,
arrow::Buffer::Wrap(offset),
list_arr,
mask_buffer);
std::vector<std::shared_ptr<arrow::Field>> schema_vector(
{arrow::field("a", nested_list_arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto expected_arrow_table = arrow::Table::Make(schema, {nested_list_arr});
auto got_arrow_table = cudf::to_arrow(input_view, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
TEST_F(ToArrowTest, StructColumn)
{
// Create cudf table
auto nested_type_field_names =
std::vector<std::vector<std::string>>{{"string", "integral", "bool", "nested_list", "struct"}};
auto str_col =
cudf::test::strings_column_wrapper{
"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"}
.release();
auto str_col2 =
cudf::test::strings_column_wrapper{{"CUDF", "ROCKS", "EVERYWHERE"}, {0, 1, 0}}.release();
int num_rows{str_col->size()};
auto int_col = cudf::test::fixed_width_column_wrapper<int32_t, int32_t>{{48, 27, 25}}.release();
auto int_col2 =
cudf::test::fixed_width_column_wrapper<int32_t, int32_t>{{12, 24, 47}, {1, 0, 1}}.release();
auto bool_col = cudf::test::fixed_width_column_wrapper<bool>{{true, true, false}}.release();
auto list_col =
cudf::test::lists_column_wrapper<int64_t>({{{1, 2}, {3, 4}, {5}}, {{{6}}}, {{7}, {8, 9}}})
.release();
vector_of_columns cols2;
cols2.push_back(std::move(str_col2));
cols2.push_back(std::move(int_col2));
auto [null_mask, null_count] =
cudf::bools_to_mask(cudf::test::fixed_width_column_wrapper<bool>{{true, true, false}});
auto sub_struct_col =
cudf::make_structs_column(num_rows, std::move(cols2), null_count, std::move(*null_mask));
vector_of_columns cols;
cols.push_back(std::move(str_col));
cols.push_back(std::move(int_col));
cols.push_back(std::move(bool_col));
cols.push_back(std::move(list_col));
cols.push_back(std::move(sub_struct_col));
auto struct_col = cudf::make_structs_column(num_rows, std::move(cols), 0, {});
cudf::table_view input_view({struct_col->view()});
// Create name metadata
auto sub_metadata = cudf::column_metadata{"struct"};
sub_metadata.children_meta = {{"string2"}, {"integral2"}};
auto metadata = cudf::column_metadata{"a"};
metadata.children_meta = {{"string"}, {"integral"}, {"bool"}, {"nested_list"}, sub_metadata};
// Create Arrow table
std::vector<std::string> str{"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"};
std::vector<std::string> str2{"CUDF", "ROCKS", "EVERYWHERE"};
auto str_array = get_arrow_array<cudf::string_view>(str);
auto int_array = get_arrow_array<int32_t>({48, 27, 25});
auto str2_array = get_arrow_array<cudf::string_view>(str2, {0, 1, 0});
auto int2_array = get_arrow_array<int32_t>({12, 24, 47}, {1, 0, 1});
auto bool_array = get_arrow_array<bool>({true, true, false});
auto list_arr = get_arrow_list_array<int64_t>({1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 2, 4, 5, 6, 7, 9});
std::vector<int32_t> offset{0, 3, 4, 6};
auto nested_list_arr = std::make_shared<arrow::ListArray>(
arrow::list(list(arrow::int64())), offset.size() - 1, arrow::Buffer::Wrap(offset), list_arr);
std::vector<std::shared_ptr<arrow::Array>> child_arrays2({str2_array, int2_array});
auto fields2 = std::vector<std::shared_ptr<arrow::Field>>{
std::make_shared<arrow::Field>("string2", str2_array->type(), str2_array->null_count() > 0),
std::make_shared<arrow::Field>("integral2", int2_array->type(), int2_array->null_count() > 0)};
auto dtype2 = std::make_shared<arrow::StructType>(fields2);
std::shared_ptr<arrow::Buffer> mask_buffer = arrow::internal::BytesToBits({1, 1, 0}).ValueOrDie();
auto struct_array2 = std::make_shared<arrow::StructArray>(
dtype2, static_cast<int64_t>(input_view.num_rows()), child_arrays2, mask_buffer);
std::vector<std::shared_ptr<arrow::Array>> child_arrays(
{str_array, int_array, bool_array, nested_list_arr, struct_array2});
std::vector<std::shared_ptr<arrow::Field>> fields;
std::transform(child_arrays.cbegin(),
child_arrays.cend(),
nested_type_field_names[0].cbegin(),
std::back_inserter(fields),
[](auto const array, auto const name) {
return std::make_shared<arrow::Field>(
name, array->type(), array->null_count() > 0);
});
auto dtype = std::make_shared<arrow::StructType>(fields);
auto struct_array = std::make_shared<arrow::StructArray>(
dtype, static_cast<int64_t>(input_view.num_rows()), child_arrays);
std::vector<std::shared_ptr<arrow::Field>> schema_vector(
{arrow::field("a", struct_array->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto expected_arrow_table = arrow::Table::Make(schema, {struct_array});
auto got_arrow_table = cudf::to_arrow(input_view, {metadata});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
template <typename T>
using fp_wrapper = cudf::test::fixed_point_column_wrapper<T>;
TEST_F(ToArrowTest, FixedPoint64Table)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const col = fp_wrapper<int64_t>({-1, 2, 3, 4, 5, 6}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const expect_data = std::vector<int64_t>{-1, -1, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0};
auto const arr = make_decimal128_arrow_array(expect_data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint128Table)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const col = fp_wrapper<__int128_t>({-1, 2, 3, 4, 5, 6}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const expect_data = std::vector<__int128_t>{-1, 2, 3, 4, 5, 6};
auto const arr = make_decimal128_arrow_array(expect_data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint64TableLarge)
{
using namespace numeric;
auto constexpr BIT_WIDTH_RATIO = 2; // Array::Type:type::DECIMAL (128) / int64_t
auto constexpr NUM_ELEMENTS = 1000;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const iota = thrust::make_counting_iterator(1);
auto const col = fp_wrapper<int64_t>(iota, iota + NUM_ELEMENTS, scale_type{scale});
auto const input = cudf::table_view({col});
auto const every_other = [](auto i) { return i % 2 == 0 ? i / 2 : 0; };
auto const transform = cudf::detail::make_counting_transform_iterator(2, every_other);
auto const expect_data =
std::vector<int64_t>{transform, transform + NUM_ELEMENTS * BIT_WIDTH_RATIO};
auto const arr = make_decimal128_arrow_array(expect_data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint128TableLarge)
{
using namespace numeric;
auto constexpr NUM_ELEMENTS = 1000;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const iota = thrust::make_counting_iterator(1);
auto const col = fp_wrapper<__int128_t>(iota, iota + NUM_ELEMENTS, scale_type{scale});
auto const input = cudf::table_view({col});
auto const expect_data = std::vector<__int128_t>{iota, iota + NUM_ELEMENTS};
auto const arr = make_decimal128_arrow_array(expect_data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint64TableNullsSimple)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const data = std::vector<int64_t>{1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 0, 0, 0, 0};
auto const validity = std::vector<int32_t>{1, 1, 1, 1, 1, 1, 0, 0};
auto const col =
fp_wrapper<int64_t>({1, 2, 3, 4, 5, 6, 0, 0}, {1, 1, 1, 1, 1, 1, 0, 0}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(data, validity, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint128TableNullsSimple)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const data = std::vector<__int128_t>{1, 2, 3, 4, 5, 6, 0, 0};
auto const validity = std::vector<int32_t>{1, 1, 1, 1, 1, 1, 0, 0};
auto const col =
fp_wrapper<__int128_t>({1, 2, 3, 4, 5, 6, 0, 0}, {1, 1, 1, 1, 1, 1, 0, 0}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(data, validity, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint64TableNulls)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const col = fp_wrapper<int64_t>(
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 0, 1, 0, 1, 0, 1, 0, 1, 0}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const expect_data =
std::vector<int64_t>{1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0};
auto const validity = std::vector<int32_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
auto arr = make_decimal128_arrow_array(expect_data, validity, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
TEST_F(ToArrowTest, FixedPoint128TableNulls)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const col = fp_wrapper<__int128_t>(
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 0, 1, 0, 1, 0, 1, 0, 1, 0}, scale_type{scale});
auto const input = cudf::table_view({col});
auto const expect_data = std::vector<__int128_t>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto const validity = std::vector<int32_t>{1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
auto arr = make_decimal128_arrow_array(expect_data, validity, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const expected_arrow_table = arrow::Table::Make(schema, {arr});
auto const got_arrow_table = cudf::to_arrow(input, {{"a"}});
ASSERT_TRUE(expected_arrow_table->Equals(*got_arrow_table, true));
}
}
struct ToArrowTestSlice
: public ToArrowTest,
public ::testing::WithParamInterface<std::tuple<cudf::size_type, cudf::size_type>> {};
TEST_P(ToArrowTestSlice, SliceTest)
{
auto tables = get_tables(10000);
auto cudf_table_view = tables.first->view();
auto arrow_table = tables.second;
auto const [start, end] = GetParam();
auto sliced_cudf_table = cudf::slice(cudf_table_view, {start, end})[0];
auto expected_arrow_table = arrow_table->Slice(start, end - start);
auto struct_meta = cudf::column_metadata{"f"};
struct_meta.children_meta = {{"integral"}, {"string"}};
auto got_arrow_table =
cudf::to_arrow(sliced_cudf_table, {{"a"}, {"b"}, {"c"}, {"d"}, {"e"}, struct_meta});
ASSERT_EQ(expected_arrow_table->Equals(*got_arrow_table, true), true);
}
INSTANTIATE_TEST_CASE_P(ToArrowTest,
ToArrowTestSlice,
::testing::Values(std::make_tuple(0, 10000),
std::make_tuple(100, 3000),
std::make_tuple(0, 0),
std::make_tuple(0, 3000)));
template <typename T>
struct ToArrowNumericScalarTest : public cudf::test::BaseFixture {};
using NumericTypesNotBool =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(ToArrowNumericScalarTest, NumericTypesNotBool);
TYPED_TEST(ToArrowNumericScalarTest, Basic)
{
TypeParam const value{42};
auto const cudf_scalar = cudf::make_fixed_width_scalar<TypeParam>(value);
cudf::column_metadata const metadata{""};
auto const arrow_scalar = cudf::to_arrow(*cudf_scalar, metadata);
auto const ref_arrow_scalar = arrow::MakeScalar(value);
EXPECT_TRUE(arrow_scalar->Equals(*ref_arrow_scalar));
}
struct ToArrowDecimalScalarTest : public cudf::test::BaseFixture {};
// Only testing Decimal128 because that's the only size cudf and arrow have in common.
TEST_F(ToArrowDecimalScalarTest, Basic)
{
auto const value{42};
auto const precision =
cudf::detail::max_precision<__int128_t>(); // cudf will convert to the widest-precision Arrow
// scalar of the type
int32_t const scale{4};
auto const cudf_scalar =
cudf::make_fixed_point_scalar<numeric::decimal128>(value, numeric::scale_type{scale});
cudf::column_metadata const metadata{""};
auto const arrow_scalar = cudf::to_arrow(*cudf_scalar, metadata);
auto const maybe_ref_arrow_scalar =
arrow::MakeScalar(arrow::decimal128(precision, -scale), value);
if (!maybe_ref_arrow_scalar.ok()) { CUDF_FAIL("Failed to construct reference scalar"); }
auto const ref_arrow_scalar = *maybe_ref_arrow_scalar;
EXPECT_TRUE(arrow_scalar->Equals(*ref_arrow_scalar));
}
struct ToArrowStringScalarTest : public cudf::test::BaseFixture {};
TEST_F(ToArrowStringScalarTest, Basic)
{
std::string const value{"hello world"};
auto const cudf_scalar = cudf::make_string_scalar(value);
cudf::column_metadata const metadata{""};
auto const arrow_scalar = cudf::to_arrow(*cudf_scalar, metadata);
auto const ref_arrow_scalar = arrow::MakeScalar(value);
EXPECT_TRUE(arrow_scalar->Equals(*ref_arrow_scalar));
}
struct ToArrowListScalarTest : public cudf::test::BaseFixture {};
TEST_F(ToArrowListScalarTest, Basic)
{
std::vector<int64_t> const host_values = {1, 2, 3, 5, 6, 7, 8};
std::vector<bool> const host_validity = {true, true, true, false, true, true, true};
cudf::test::fixed_width_column_wrapper<int64_t> const col(
host_values.begin(), host_values.end(), host_validity.begin());
auto const cudf_scalar = cudf::make_list_scalar(col);
cudf::column_metadata const metadata{""};
auto const arrow_scalar = cudf::to_arrow(*cudf_scalar, metadata);
arrow::Int64Builder builder;
auto const status = builder.AppendValues(host_values, host_validity);
auto const maybe_array = builder.Finish();
auto const array = *maybe_array;
auto const ref_arrow_scalar = arrow::ListScalar(array);
EXPECT_TRUE(arrow_scalar->Equals(ref_arrow_scalar));
}
struct ToArrowStructScalarTest : public cudf::test::BaseFixture {};
TEST_F(ToArrowStructScalarTest, Basic)
{
int64_t const value{42};
auto const field_name{"a"};
cudf::test::fixed_width_column_wrapper<int64_t> const col{value};
cudf::table_view const tbl({col});
auto const cudf_scalar = cudf::make_struct_scalar(tbl);
cudf::column_metadata metadata{""};
metadata.children_meta.emplace_back(field_name);
auto const arrow_scalar = cudf::to_arrow(*cudf_scalar, metadata);
auto const underlying_arrow_scalar = arrow::MakeScalar(value);
auto const field = arrow::field(field_name, underlying_arrow_scalar->type, false);
auto const arrow_type = arrow::struct_({field});
auto const ref_arrow_scalar = arrow::StructScalar({underlying_arrow_scalar}, arrow_type);
EXPECT_TRUE(arrow_scalar->Equals(ref_arrow_scalar));
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/interop/from_arrow_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.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.hpp>
#include <cudf/interop.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 <thrust/iterator/counting_iterator.h>
#include <tests/interop/arrow_utils.hpp>
std::unique_ptr<cudf::table> get_cudf_table()
{
std::vector<std::unique_ptr<cudf::column>> columns;
columns.emplace_back(
cudf::test::fixed_width_column_wrapper<int32_t>({1, 2, 5, 2, 7}, {1, 0, 1, 1, 1}).release());
columns.emplace_back(cudf::test::fixed_width_column_wrapper<int64_t>({1, 2, 3, 4, 5}).release());
columns.emplace_back(
cudf::test::strings_column_wrapper({"fff", "aaa", "", "fff", "ccc"}, {1, 1, 1, 0, 1})
.release());
auto col4 = cudf::test::fixed_width_column_wrapper<int32_t>({1, 2, 5, 2, 7}, {1, 0, 1, 1, 1});
columns.emplace_back(std::move(cudf::dictionary::encode(col4)));
columns.emplace_back(
cudf::test::fixed_width_column_wrapper<bool>({true, false, true, false, true}, {1, 0, 1, 1, 0})
.release());
// columns.emplace_back(cudf::test::lists_column_wrapper<int>({{1, 2}, {3, 4}, {}, {6}, {7, 8,
// 9}}).release());
return std::make_unique<cudf::table>(std::move(columns));
}
struct FromArrowTest : public cudf::test::BaseFixture {};
template <typename T>
struct FromArrowTestDurationsTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(FromArrowTestDurationsTest, cudf::test::DurationTypes);
TEST_F(FromArrowTest, EmptyTable)
{
auto tables = get_tables(0);
auto expected_cudf_table = tables.first->view();
auto arrow_table = tables.second;
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_cudf_table, got_cudf_table->view());
}
TEST_F(FromArrowTest, DateTimeTable)
{
auto data = std::vector<int64_t>{1, 2, 3, 4, 5, 6};
auto col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep>(
data.begin(), data.end());
cudf::table_view expected_table_view({col});
std::shared_ptr<arrow::Array> arr;
arrow::TimestampBuilder timestamp_builder(arrow::timestamp(arrow::TimeUnit::type::MILLI),
arrow::default_memory_pool());
ASSERT_TRUE(timestamp_builder.AppendValues(data).ok());
ASSERT_TRUE(timestamp_builder.Finish(&arr).ok());
std::vector<std::shared_ptr<arrow::Field>> schema_vector({arrow::field("a", arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table_view, got_cudf_table->view());
}
TYPED_TEST(FromArrowTestDurationsTest, DurationTable)
{
using T = TypeParam;
auto data = {T{1}, T{2}, T{3}, T{4}, T{5}, T{6}};
auto col = cudf::test::fixed_width_column_wrapper<T>(data);
std::shared_ptr<arrow::Array> arr;
cudf::table_view expected_table_view({col});
arrow::TimeUnit::type arrow_unit;
switch (cudf::type_to_id<TypeParam>()) {
case cudf::type_id::DURATION_SECONDS: arrow_unit = arrow::TimeUnit::type::SECOND; break;
case cudf::type_id::DURATION_MILLISECONDS: arrow_unit = arrow::TimeUnit::type::MILLI; break;
case cudf::type_id::DURATION_MICROSECONDS: arrow_unit = arrow::TimeUnit::type::MICRO; break;
case cudf::type_id::DURATION_NANOSECONDS: arrow_unit = arrow::TimeUnit::type::NANO; break;
case cudf::type_id::DURATION_DAYS: return;
default: CUDF_FAIL("Unsupported duration unit in arrow");
}
arrow::DurationBuilder duration_builder(duration(arrow_unit), arrow::default_memory_pool());
ASSERT_TRUE(duration_builder.AppendValues(std::vector<int64_t>{1, 2, 3, 4, 5, 6}).ok());
ASSERT_TRUE(duration_builder.Finish(&arr).ok());
std::vector<std::shared_ptr<arrow::Field>> schema_vector({arrow::field("a", arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table_view, got_cudf_table->view());
}
TEST_F(FromArrowTest, NestedList)
{
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 3 != 0; });
auto col = cudf::test::lists_column_wrapper<int64_t>(
{{{{{1, 2}, valids}, {{3, 4}, valids}, {5}}, {{6}, {{7, 8, 9}, valids}}}, valids});
cudf::table_view expected_table_view({col});
auto list_arr = get_arrow_list_array<int64_t>({6, 7, 8, 9}, {0, 1, 4}, {1, 0, 1, 1});
std::vector<int32_t> offset{0, 0, 2};
auto mask_buffer = arrow::internal::BytesToBits({0, 1}).ValueOrDie();
auto nested_list_arr = std::make_shared<arrow::ListArray>(arrow::list(list(arrow::int64())),
offset.size() - 1,
arrow::Buffer::Wrap(offset),
list_arr,
mask_buffer);
std::vector<std::shared_ptr<arrow::Field>> schema_vector(
{arrow::field("a", nested_list_arr->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto arrow_table = arrow::Table::Make(schema, {nested_list_arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table_view, got_cudf_table->view());
}
TEST_F(FromArrowTest, StructColumn)
{
using vector_of_columns = std::vector<std::unique_ptr<cudf::column>>;
// Create cudf table
auto nested_type_field_names =
std::vector<std::vector<std::string>>{{"string", "integral", "bool", "nested_list", "struct"}};
auto str_col =
cudf::test::strings_column_wrapper{
"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"}
.release();
auto str_col2 =
cudf::test::strings_column_wrapper{{"CUDF", "ROCKS", "EVERYWHERE"}, {0, 1, 0}}.release();
int num_rows{str_col->size()};
auto int_col = cudf::test::fixed_width_column_wrapper<int32_t, int32_t>{{48, 27, 25}}.release();
auto int_col2 =
cudf::test::fixed_width_column_wrapper<int32_t, int32_t>{{12, 24, 47}, {1, 0, 1}}.release();
auto bool_col = cudf::test::fixed_width_column_wrapper<bool>{{true, true, false}}.release();
auto list_col =
cudf::test::lists_column_wrapper<int64_t>({{{1, 2}, {3, 4}, {5}}, {{{6}}}, {{7}, {8, 9}}})
.release();
vector_of_columns cols2;
cols2.push_back(std::move(str_col2));
cols2.push_back(std::move(int_col2));
auto [null_mask, null_count] =
cudf::bools_to_mask(cudf::test::fixed_width_column_wrapper<bool>{{true, true, false}});
auto sub_struct_col =
cudf::make_structs_column(num_rows, std::move(cols2), null_count, std::move(*null_mask));
vector_of_columns cols;
cols.push_back(std::move(str_col));
cols.push_back(std::move(int_col));
cols.push_back(std::move(bool_col));
cols.push_back(std::move(list_col));
cols.push_back(std::move(sub_struct_col));
auto struct_col = cudf::make_structs_column(num_rows, std::move(cols), 0, {});
cudf::table_view expected_cudf_table({struct_col->view()});
// Create Arrow table
std::vector<std::string> str{"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"};
std::vector<std::string> str2{"CUDF", "ROCKS", "EVERYWHERE"};
auto str_array = get_arrow_array<cudf::string_view>(str);
auto int_array = get_arrow_array<int32_t>({48, 27, 25});
auto str2_array = get_arrow_array<cudf::string_view>(str2, {0, 1, 0});
auto int2_array = get_arrow_array<int32_t>({12, 24, 47}, {1, 0, 1});
auto bool_array = get_arrow_array<bool>({true, true, false});
auto list_arr = get_arrow_list_array<int64_t>({1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 2, 4, 5, 6, 7, 9});
std::vector<int32_t> offset{0, 3, 4, 6};
auto nested_list_arr = std::make_shared<arrow::ListArray>(
arrow::list(list(arrow::int64())), offset.size() - 1, arrow::Buffer::Wrap(offset), list_arr);
std::vector<std::shared_ptr<arrow::Array>> child_arrays2({str2_array, int2_array});
auto fields2 = std::vector<std::shared_ptr<arrow::Field>>{
std::make_shared<arrow::Field>("string2", str2_array->type(), str2_array->null_count() > 0),
std::make_shared<arrow::Field>("integral2", int2_array->type(), int2_array->null_count() > 0)};
std::shared_ptr<arrow::Buffer> mask_buffer = arrow::internal::BytesToBits({1, 1, 0}).ValueOrDie();
auto dtype2 = std::make_shared<arrow::StructType>(fields2);
auto struct_array2 = std::make_shared<arrow::StructArray>(
dtype2, static_cast<int64_t>(expected_cudf_table.num_rows()), child_arrays2, mask_buffer);
std::vector<std::shared_ptr<arrow::Array>> child_arrays(
{str_array, int_array, bool_array, nested_list_arr, struct_array2});
std::vector<std::shared_ptr<arrow::Field>> fields;
std::transform(child_arrays.cbegin(),
child_arrays.cend(),
nested_type_field_names[0].cbegin(),
std::back_inserter(fields),
[](auto const array, auto const name) {
return std::make_shared<arrow::Field>(
name, array->type(), array->null_count() > 0);
});
auto dtype = std::make_shared<arrow::StructType>(fields);
auto struct_array = std::make_shared<arrow::StructArray>(
dtype, static_cast<int64_t>(expected_cudf_table.num_rows()), child_arrays);
std::vector<std::shared_ptr<arrow::Field>> schema_vector(
{arrow::field("a", struct_array->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto input = arrow::Table::Make(schema, {struct_array});
auto got_cudf_table = cudf::from_arrow(*input);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_cudf_table, got_cudf_table->view());
}
TEST_F(FromArrowTest, DictionaryIndicesType)
{
auto array1 =
get_arrow_dict_array<int64_t, int8_t>({1, 2, 5, 7}, {0, 1, 2, 1, 3}, {1, 0, 1, 1, 1});
auto array2 =
get_arrow_dict_array<int64_t, int16_t>({1, 2, 5, 7}, {0, 1, 2, 1, 3}, {1, 0, 1, 1, 1});
auto array3 =
get_arrow_dict_array<int64_t, int64_t>({1, 2, 5, 7}, {0, 1, 2, 1, 3}, {1, 0, 1, 1, 1});
std::vector<std::shared_ptr<arrow::Field>> schema_vector({arrow::field("a", array1->type()),
arrow::field("b", array2->type()),
arrow::field("c", array3->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto arrow_table = arrow::Table::Make(schema, {array1, array2, array3});
std::vector<std::unique_ptr<cudf::column>> columns;
auto col = cudf::test::fixed_width_column_wrapper<int64_t>({1, 2, 5, 2, 7}, {1, 0, 1, 1, 1});
columns.emplace_back(std::move(cudf::dictionary::encode(col)));
columns.emplace_back(std::move(cudf::dictionary::encode(col)));
columns.emplace_back(std::move(cudf::dictionary::encode(col)));
cudf::table expected_table(std::move(columns));
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table.view(), got_cudf_table->view());
}
TEST_F(FromArrowTest, ChunkedArray)
{
auto int64array = get_arrow_array<int64_t>({1, 2, 3, 4, 5});
auto int32array_1 = get_arrow_array<int32_t>({1, 2}, {1, 0});
auto int32array_2 = get_arrow_array<int32_t>({5, 2, 7}, {1, 1, 1});
auto string_array_1 = get_arrow_array<cudf::string_view>({
"fff",
"aaa",
"",
});
auto string_array_2 = get_arrow_array<cudf::string_view>(
{
"fff",
"ccc",
},
{0, 1});
auto dict_array1 = get_arrow_dict_array({1, 2, 5, 7}, {0, 1, 2}, {1, 0, 1});
auto dict_array2 = get_arrow_dict_array({1, 2, 5, 7}, {1, 3});
auto int64_chunked_array = std::make_shared<arrow::ChunkedArray>(int64array);
auto int32_chunked_array = std::make_shared<arrow::ChunkedArray>(
std::vector<std::shared_ptr<arrow::Array>>{int32array_1, int32array_2});
auto string_chunked_array = std::make_shared<arrow::ChunkedArray>(
std::vector<std::shared_ptr<arrow::Array>>{string_array_1, string_array_2});
auto dict_chunked_array = std::make_shared<arrow::ChunkedArray>(
std::vector<std::shared_ptr<arrow::Array>>{dict_array1, dict_array2});
auto boolean_array = get_arrow_array<bool>({true, false, true, false, true}, {1, 0, 1, 1, 0});
auto boolean_chunked_array = std::make_shared<arrow::ChunkedArray>(boolean_array);
std::vector<std::shared_ptr<arrow::Field>> schema_vector(
{arrow::field("a", int32_chunked_array->type()),
arrow::field("b", int64array->type()),
arrow::field("c", string_array_1->type()),
arrow::field("d", dict_chunked_array->type()),
arrow::field("e", boolean_chunked_array->type())});
auto schema = std::make_shared<arrow::Schema>(schema_vector);
auto arrow_table = arrow::Table::Make(schema,
{int32_chunked_array,
int64_chunked_array,
string_chunked_array,
dict_chunked_array,
boolean_chunked_array});
auto expected_cudf_table = get_cudf_table();
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_cudf_table->view(), got_cudf_table->view());
}
struct FromArrowTestSlice
: public FromArrowTest,
public ::testing::WithParamInterface<std::tuple<cudf::size_type, cudf::size_type>> {};
TEST_P(FromArrowTestSlice, SliceTest)
{
auto tables = get_tables(10000);
auto cudf_table_view = tables.first->view();
auto arrow_table = tables.second;
auto const [start, end] = GetParam();
auto sliced_cudf_table = cudf::slice(cudf_table_view, {start, end})[0];
auto expected_cudf_table = cudf::table{sliced_cudf_table};
auto sliced_arrow_table = arrow_table->Slice(start, end - start);
auto got_cudf_table = cudf::from_arrow(*sliced_arrow_table);
// This has been added to take-care of empty string column issue with no children
if (got_cudf_table->num_rows() == 0 and expected_cudf_table.num_rows() == 0) {
CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected_cudf_table.view(), got_cudf_table->view());
} else {
CUDF_TEST_EXPECT_TABLES_EQUAL(expected_cudf_table.view(), got_cudf_table->view());
}
}
template <typename T>
using fp_wrapper = cudf::test::fixed_point_column_wrapper<T>;
TEST_F(FromArrowTest, FixedPoint128Table)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const data = std::vector<__int128_t>{1, 2, 3, 4, 5, 6};
auto const col = fp_wrapper<__int128_t>(data.cbegin(), data.cend(), scale_type{scale});
auto const expected = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got_cudf_table->view());
}
}
TEST_F(FromArrowTest, FixedPoint128TableLarge)
{
using namespace numeric;
auto constexpr NUM_ELEMENTS = 1000;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto iota = thrust::make_counting_iterator(1);
auto const data = std::vector<__int128_t>(iota, iota + NUM_ELEMENTS);
auto const col = fp_wrapper<__int128_t>(iota, iota + NUM_ELEMENTS, scale_type{scale});
auto const expected = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(data, std::nullopt, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got_cudf_table->view());
}
}
TEST_F(FromArrowTest, FixedPoint128TableNulls)
{
using namespace numeric;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto const data = std::vector<__int128_t>{1, 2, 3, 4, 5, 6, 0, 0};
auto const validity = std::vector<int32_t>{1, 1, 1, 1, 1, 1, 0, 0};
auto const col =
fp_wrapper<__int128_t>({1, 2, 3, 4, 5, 6, 0, 0}, {1, 1, 1, 1, 1, 1, 0, 0}, scale_type{scale});
auto const expected = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(data, validity, scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got_cudf_table->view());
}
}
TEST_F(FromArrowTest, FixedPoint128TableNullsLarge)
{
using namespace numeric;
auto constexpr NUM_ELEMENTS = 1000;
for (auto const scale : {3, 2, 1, 0, -1, -2, -3}) {
auto every_other = [](auto i) { return i % 2 ? 0 : 1; };
auto validity = cudf::detail::make_counting_transform_iterator(0, every_other);
auto iota = thrust::make_counting_iterator(1);
auto const data = std::vector<__int128_t>(iota, iota + NUM_ELEMENTS);
auto const col = fp_wrapper<__int128_t>(iota, iota + NUM_ELEMENTS, validity, scale_type{scale});
auto const expected = cudf::table_view({col});
auto const arr = make_decimal128_arrow_array(
data, std::vector<int32_t>(validity, validity + NUM_ELEMENTS), scale);
auto const field = arrow::field("a", arr->type());
auto const schema_vector = std::vector<std::shared_ptr<arrow::Field>>({field});
auto const schema = std::make_shared<arrow::Schema>(schema_vector);
auto const arrow_table = arrow::Table::Make(schema, {arr});
auto got_cudf_table = cudf::from_arrow(*arrow_table);
CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got_cudf_table->view());
}
}
INSTANTIATE_TEST_CASE_P(FromArrowTest,
FromArrowTestSlice,
::testing::Values(std::make_tuple(0, 10000),
std::make_tuple(2912, 2915),
std::make_tuple(100, 3000),
std::make_tuple(0, 0),
std::make_tuple(0, 3000),
std::make_tuple(10000, 10000)));
template <typename T>
struct FromArrowNumericScalarTest : public cudf::test::BaseFixture {};
using NumericTypesNotBool =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(FromArrowNumericScalarTest, NumericTypesNotBool);
TYPED_TEST(FromArrowNumericScalarTest, Basic)
{
TypeParam const value{42};
auto const arrow_scalar = arrow::MakeScalar(value);
auto const cudf_scalar = cudf::from_arrow(*arrow_scalar);
auto const cudf_numeric_scalar =
dynamic_cast<cudf::numeric_scalar<TypeParam>*>(cudf_scalar.get());
if (cudf_numeric_scalar == nullptr) { CUDF_FAIL("Attempted to test with a non-numeric type."); }
EXPECT_EQ(cudf_numeric_scalar->type(), cudf::data_type(cudf::type_to_id<TypeParam>()));
EXPECT_EQ(cudf_numeric_scalar->value(), value);
}
struct FromArrowDecimalScalarTest : public cudf::test::BaseFixture {};
// Only testing Decimal128 because that's the only size cudf and arrow have in common.
TEST_F(FromArrowDecimalScalarTest, Basic)
{
auto const value{42};
auto const precision{8};
auto const scale{4};
auto arrow_scalar = arrow::Decimal128Scalar(value, arrow::decimal128(precision, -scale));
auto cudf_scalar = cudf::from_arrow(arrow_scalar);
// Arrow offers a minimum of 128 bits for the Decimal type.
auto const cudf_decimal_scalar =
dynamic_cast<cudf::fixed_point_scalar<numeric::decimal128>*>(cudf_scalar.get());
EXPECT_EQ(cudf_decimal_scalar->type(),
cudf::data_type(cudf::type_to_id<numeric::decimal128>(), scale));
EXPECT_EQ(cudf_decimal_scalar->value(), value);
}
struct FromArrowStringScalarTest : public cudf::test::BaseFixture {};
TEST_F(FromArrowStringScalarTest, Basic)
{
auto const value = std::string("hello world");
auto const arrow_scalar = arrow::StringScalar(value);
auto const cudf_scalar = cudf::from_arrow(arrow_scalar);
auto const cudf_string_scalar = dynamic_cast<cudf::string_scalar*>(cudf_scalar.get());
EXPECT_EQ(cudf_string_scalar->type(), cudf::data_type(cudf::type_id::STRING));
EXPECT_EQ(cudf_string_scalar->to_string(), value);
}
struct FromArrowListScalarTest : public cudf::test::BaseFixture {};
TEST_F(FromArrowListScalarTest, Basic)
{
std::vector<int64_t> host_values = {1, 2, 3, 5, 6, 7, 8};
std::vector<bool> host_validity = {true, true, true, false, true, true, true};
arrow::Int64Builder builder;
auto const status = builder.AppendValues(host_values, host_validity);
auto const maybe_array = builder.Finish();
auto const array = *maybe_array;
auto const arrow_scalar = arrow::ListScalar(array);
auto const cudf_scalar = cudf::from_arrow(arrow_scalar);
auto const cudf_list_scalar = dynamic_cast<cudf::list_scalar*>(cudf_scalar.get());
EXPECT_EQ(cudf_list_scalar->type(), cudf::data_type(cudf::type_id::LIST));
cudf::test::fixed_width_column_wrapper<int64_t> const lhs(
host_values.begin(), host_values.end(), host_validity.begin());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(lhs, cudf_list_scalar->view());
}
struct FromArrowStructScalarTest : public cudf::test::BaseFixture {};
TEST_F(FromArrowStructScalarTest, Basic)
{
int64_t const value{42};
auto const underlying_arrow_scalar = arrow::MakeScalar(value);
auto const field = arrow::field("", underlying_arrow_scalar->type);
auto const arrow_type = arrow::struct_({field});
auto const arrow_scalar = arrow::StructScalar({underlying_arrow_scalar}, arrow_type);
auto const cudf_scalar = cudf::from_arrow(arrow_scalar);
auto const cudf_struct_scalar = dynamic_cast<cudf::struct_scalar*>(cudf_scalar.get());
EXPECT_EQ(cudf_struct_scalar->type(), cudf::data_type(cudf::type_id::STRUCT));
cudf::test::fixed_width_column_wrapper<int64_t> const col({value});
cudf::table_view const lhs({col});
CUDF_TEST_EXPECT_TABLES_EQUAL(lhs, cudf_struct_scalar->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/interop/arrow_utils.hpp
|
/*
* 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 <arrow/util/bitmap_builders.h>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/interop.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.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/cudf_gtest.hpp>
#include <cudf_test/type_lists.hpp>
#pragma once
template <typename T>
std::enable_if_t<cudf::is_fixed_width<T>() and !std::is_same_v<T, bool>,
std::shared_ptr<arrow::Array>>
get_arrow_array(std::vector<T> const& data, std::vector<uint8_t> const& mask = {})
{
std::shared_ptr<arrow::Buffer> data_buffer;
arrow::BufferBuilder buff_builder;
CUDF_EXPECTS(buff_builder.Append(data.data(), sizeof(T) * data.size()).ok(),
"Failed to append values");
CUDF_EXPECTS(buff_builder.Finish(&data_buffer).ok(), "Failed to allocate buffer");
std::shared_ptr<arrow::Buffer> mask_buffer =
mask.empty() ? nullptr : arrow::internal::BytesToBits(mask).ValueOrDie();
return cudf::detail::to_arrow_array(cudf::type_to_id<T>(), data.size(), data_buffer, mask_buffer);
}
template <typename T>
std::enable_if_t<cudf::is_fixed_width<T>() and !std::is_same_v<T, bool>,
std::shared_ptr<arrow::Array>>
get_arrow_array(std::initializer_list<T> elements, std::initializer_list<uint8_t> validity = {})
{
std::vector<T> data(elements);
std::vector<uint8_t> mask(validity);
return get_arrow_array<T>(data, mask);
}
template <typename T>
std::enable_if_t<std::is_same_v<T, bool>, std::shared_ptr<arrow::Array>> get_arrow_array(
std::vector<bool> const& data, std::vector<bool> const& mask = {})
{
std::shared_ptr<arrow::BooleanArray> boolean_array;
arrow::BooleanBuilder boolean_builder;
if (mask.empty()) {
CUDF_EXPECTS(boolean_builder.AppendValues(data).ok(),
"Failed to append values to boolean builder");
} else {
CUDF_EXPECTS(boolean_builder.AppendValues(data, mask).ok(),
"Failed to append values to boolean builder");
}
CUDF_EXPECTS(boolean_builder.Finish(&boolean_array).ok(), "Failed to create arrow boolean array");
return boolean_array;
}
template <typename T>
std::enable_if_t<std::is_same_v<T, bool>, std::shared_ptr<arrow::Array>> get_arrow_array(
std::initializer_list<bool> elements, std::initializer_list<bool> validity = {})
{
std::vector<bool> mask(validity);
std::vector<bool> data(elements);
return get_arrow_array<T>(data, mask);
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::string_view>, std::shared_ptr<arrow::Array>>
get_arrow_array(std::vector<std::string> const& data, std::vector<uint8_t> const& mask = {})
{
std::shared_ptr<arrow::StringArray> string_array;
arrow::StringBuilder string_builder;
CUDF_EXPECTS(string_builder.AppendValues(data, mask.data()).ok(),
"Failed to append values to string builder");
CUDF_EXPECTS(string_builder.Finish(&string_array).ok(), "Failed to create arrow string array");
return string_array;
}
template <typename T>
std::enable_if_t<std::is_same_v<T, cudf::string_view>, std::shared_ptr<arrow::Array>>
get_arrow_array(std::initializer_list<std::string> elements,
std::initializer_list<uint8_t> validity = {})
{
std::vector<uint8_t> mask(validity);
std::vector<std::string> data(elements);
return get_arrow_array<T>(data, mask);
}
template <typename KEY_TYPE, typename IND_TYPE>
std::shared_ptr<arrow::Array> get_arrow_dict_array(std::vector<KEY_TYPE> const& keys,
std::vector<IND_TYPE> const& ind,
std::vector<uint8_t> const& validity = {})
{
auto keys_array = get_arrow_array<KEY_TYPE>(keys);
auto indices_array = get_arrow_array<IND_TYPE>(ind, validity);
return std::make_shared<arrow::DictionaryArray>(
arrow::dictionary(indices_array->type(), keys_array->type()), indices_array, keys_array);
}
template <typename KEY_TYPE, typename IND_TYPE>
std::shared_ptr<arrow::Array> get_arrow_dict_array(std::initializer_list<KEY_TYPE> keys,
std::initializer_list<IND_TYPE> ind,
std::initializer_list<uint8_t> validity = {})
{
auto keys_array = get_arrow_array<KEY_TYPE>(keys);
auto indices_array = get_arrow_array<IND_TYPE>(ind, validity);
return std::make_shared<arrow::DictionaryArray>(
arrow::dictionary(indices_array->type(), keys_array->type()), indices_array, keys_array);
}
// Creates only single layered list
template <typename T>
std::shared_ptr<arrow::Array> get_arrow_list_array(std::vector<T> data,
std::vector<int32_t> offsets,
std::vector<uint8_t> data_validity = {},
std::vector<uint8_t> list_validity = {})
{
auto data_array = get_arrow_array<T>(data, data_validity);
std::shared_ptr<arrow::Buffer> offset_buffer;
arrow::BufferBuilder buff_builder;
CUDF_EXPECTS(buff_builder.Append(offsets.data(), sizeof(int32_t) * offsets.size()).ok(),
"Failed to append values to buffer builder");
CUDF_EXPECTS(buff_builder.Finish(&offset_buffer).ok(), "Failed to allocate buffer");
return std::make_shared<arrow::ListArray>(
arrow::list(data_array->type()),
offsets.size() - 1,
offset_buffer,
data_array,
list_validity.empty() ? nullptr : arrow::internal::BytesToBits(list_validity).ValueOrDie());
}
template <typename T>
std::shared_ptr<arrow::Array> get_arrow_list_array(
std::initializer_list<T> data,
std::initializer_list<int32_t> offsets,
std::initializer_list<uint8_t> data_validity = {},
std::initializer_list<uint8_t> list_validity = {})
{
std::vector<T> data_vector(data);
std::vector<int32_t> ofst(offsets);
std::vector<uint8_t> data_mask(data_validity);
std::vector<uint8_t> list_mask(list_validity);
return get_arrow_list_array<T>(data_vector, ofst, data_mask, list_mask);
}
std::pair<std::unique_ptr<cudf::table>, std::shared_ptr<arrow::Table>> get_tables(
cudf::size_type length = 10000);
template <typename T>
[[nodiscard]] auto make_decimal128_arrow_array(std::vector<T> const& data,
std::optional<std::vector<int>> const& validity,
int32_t scale) -> std::shared_ptr<arrow::Array>
{
auto constexpr BIT_WIDTH_RATIO = sizeof(__int128_t) / sizeof(T);
std::shared_ptr<arrow::Array> arr;
arrow::Decimal128Builder decimal_builder(arrow::decimal(cudf::detail::max_precision<T>(), -scale),
arrow::default_memory_pool());
for (T i = 0; i < static_cast<T>(data.size() / BIT_WIDTH_RATIO); ++i) {
if (validity.has_value() and not validity.value()[i]) {
CUDF_EXPECTS(decimal_builder.AppendNull().ok(), "Failed to append");
} else {
CUDF_EXPECTS(
decimal_builder.Append(reinterpret_cast<uint8_t const*>(data.data() + BIT_WIDTH_RATIO * i))
.ok(),
"Failed to append");
}
}
CUDF_EXPECTS(decimal_builder.Finish(&arr).ok(), "Failed to build array");
return arr;
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-verify-input-test.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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/binaryop.hpp>
struct BinopVerifyInputTest : public cudf::test::BaseFixture {};
TEST_F(BinopVerifyInputTest, Vector_Scalar_ErrorOutputVectorType)
{
auto lhs = cudf::scalar_type_t<int64_t>(1);
auto rhs = cudf::test::fixed_width_column_wrapper<int64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
EXPECT_THROW(
cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::NUM_TYPE_IDS)),
cudf::logic_error);
}
TEST_F(BinopVerifyInputTest, Vector_Vector_ErrorSecondOperandVectorZeroSize)
{
auto lhs = cudf::test::fixed_width_column_wrapper<int64_t>{1};
auto rhs = cudf::test::fixed_width_column_wrapper<int64_t>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
EXPECT_THROW(cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT64)),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-compiled-fixed_point-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/type_lists.hpp>
#include <cudf/binaryop.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/types.hpp>
#include <cudf/unary.hpp>
#include <thrust/iterator/counting_iterator.h>
template <typename T>
struct FixedPointCompiledTest : public cudf::test::BaseFixture {};
template <typename T>
using wrapper = cudf::test::fixed_width_column_wrapper<T>;
TYPED_TEST_SUITE(FixedPointCompiledTest, cudf::test::FixedPointTypes);
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd)
{
using namespace numeric;
using decimalXX = TypeParam;
auto const sz = std::size_t{1000};
auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto i) {
return decimalXX{i, scale_type{0}};
});
auto const vec1 = std::vector<decimalXX>(begin, begin + sz);
auto const vec2 = std::vector<decimalXX>(sz, decimalXX{2, scale_type{0}});
auto expected = std::vector<decimalXX>(sz);
std::transform(std::cbegin(vec1),
std::cend(vec1),
std::cbegin(vec2),
std::begin(expected),
std::plus<decimalXX>());
auto const lhs = wrapper<decimalXX>(vec1.begin(), vec1.end());
auto const rhs = wrapper<decimalXX>(vec2.begin(), vec2.end());
auto const expected_col = wrapper<decimalXX>(expected.begin(), expected.end());
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_col, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiply)
{
using namespace numeric;
using decimalXX = TypeParam;
auto const sz = std::size_t{1000};
auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto i) {
return decimalXX{i, scale_type{0}};
});
auto const vec1 = std::vector<decimalXX>(begin, begin + sz);
auto const vec2 = std::vector<decimalXX>(sz, decimalXX{2, scale_type{0}});
auto expected = std::vector<decimalXX>(sz);
std::transform(std::cbegin(vec1),
std::cend(vec1),
std::cbegin(vec2),
std::begin(expected),
std::multiplies<decimalXX>());
auto const lhs = wrapper<decimalXX>(vec1.begin(), vec1.end());
auto const rhs = wrapper<decimalXX>(vec2.begin(), vec2.end());
auto const expected_col = wrapper<decimalXX>(expected.begin(), expected.end());
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MUL,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MUL, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_col, result->view());
}
template <typename T>
using fp_wrapper = cudf::test::fixed_point_column_wrapper<T>;
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiply2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{110, 220, 330, 440, 550}, scale_type{-1}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MUL,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MUL, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{2, 7, 12, 17}, scale_type{-1}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::DIV,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{-2}};
auto const expected = fp_wrapper<RepType>{{2, 7, 12, 17}, scale_type{1}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::DIV,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv3)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(12, scale_type{-1});
auto const expected = fp_wrapper<RepType>{{0, 2, 4, 5}, scale_type{0}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv4)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 11; });
auto result_begin =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i * 11) / 12; });
auto const lhs = fp_wrapper<RepType>(begin, begin + 1000, scale_type{-1});
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(12, scale_type{-1});
auto const expected = fp_wrapper<RepType>(result_begin, result_begin + 1000, scale_type{0});
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 400, 500}, scale_type{-2}};
auto const expected = fp_wrapper<RepType>{{210, 420, 630, 840, 1050}, scale_type{-2}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd3)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{1100, 2200, 3300, 4400, 5500}, scale_type{-3}};
auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 400, 500}, scale_type{-2}};
auto const expected = fp_wrapper<RepType>{{2100, 4200, 6300, 8400, 10500}, scale_type{-3}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd4)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(100, scale_type{-2});
auto const expected = fp_wrapper<RepType>{{210, 320, 430, 540, 650}, scale_type{-2}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd5)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = cudf::make_fixed_point_scalar<decimalXX>(100, scale_type{-2});
auto const rhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{210, 320, 430, 540, 650}, scale_type{-2}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::ADD, lhs->type(), static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd6)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col = fp_wrapper<RepType>{{30, 4, 5, 6, 7, 8}, scale_type{0}};
auto const expected1 = fp_wrapper<RepType>{{60, 8, 10, 12, 14, 16}, scale_type{0}};
auto const expected2 = fp_wrapper<RepType>{{6, 0, 1, 1, 1, 1}, scale_type{1}};
auto const type1 = cudf::data_type{cudf::type_to_id<decimalXX>(), 0};
auto const type2 = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result1 = cudf::binary_operation(col, col, cudf::binary_operator::ADD, type1);
auto const result2 = cudf::binary_operation(col, col, cudf::binary_operator::ADD, type2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointCast)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col = fp_wrapper<RepType>{{6, 8, 10, 12, 14, 16}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{0, 0, 1, 1, 1, 1}, scale_type{1}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result = cudf::cast(col, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiplyScalar)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(100, scale_type{-1});
auto const expected = fp_wrapper<RepType>{{1100, 2200, 3300, 4400, 5500}, scale_type{-2}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::MUL, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MUL, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpSimplePlus)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{150, 200}, scale_type{-2}};
auto const rhs = fp_wrapper<RepType>{{2250, 1005}, scale_type{-3}};
auto const expected = fp_wrapper<RepType>{{3750, 3005}, scale_type{-3}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const trues = std::vector<bool>(4, true);
auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, scale_type{0}};
auto const col2 = fp_wrapper<RepType>{{100, 200, 300, 400}, scale_type{-2}};
auto const expected = wrapper<bool>(trues.begin(), trues.end());
auto const result = cudf::binary_operation(
col1, col2, cudf::binary_operator::EQUAL, cudf::data_type{cudf::type_id::BOOL8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale0)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const trues = std::vector<bool>(4, true);
auto const col = fp_wrapper<RepType>{{1, 2, 3, 4}, scale_type{0}};
auto const expected = wrapper<bool>(trues.begin(), trues.end());
auto const result = cudf::binary_operation(
col, col, cudf::binary_operator::EQUAL, cudf::data_type{cudf::type_id::BOOL8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale0Null)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, {1, 1, 1, 1}, scale_type{0}};
auto const col2 = fp_wrapper<RepType>{{1, 2, 3, 4}, {0, 0, 0, 0}, scale_type{0}};
auto const expected = wrapper<bool>{{0, 1, 0, 1}, {0, 0, 0, 0}};
auto const result = cudf::binary_operation(
col1, col2, cudf::binary_operator::EQUAL, cudf::data_type{cudf::type_id::BOOL8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale2Null)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, {1, 1, 1, 1}, scale_type{-2}};
auto const col2 = fp_wrapper<RepType>{{1, 2, 3, 4}, {0, 0, 0, 0}, scale_type{0}};
auto const expected = wrapper<bool>{{0, 1, 0, 1}, {0, 0, 0, 0}};
auto const result = cudf::binary_operation(
col1, col2, cudf::binary_operator::EQUAL, cudf::data_type{cudf::type_id::BOOL8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualLessGreater)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const sz = std::size_t{1000};
// TESTING binary op ADD
auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto e) { return e * 1000; });
auto const vec1 = std::vector<RepType>(begin, begin + sz);
auto const vec2 = std::vector<RepType>(sz, 0);
auto const iota_3 = fp_wrapper<RepType>(vec1.begin(), vec1.end(), scale_type{-3});
auto const zeros_3 = fp_wrapper<RepType>(vec2.begin(), vec2.end(), scale_type{-1});
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD,
static_cast<cudf::column_view>(iota_3).type(),
static_cast<cudf::column_view>(zeros_3).type());
auto const iota_3_after_add =
cudf::binary_operation(zeros_3, iota_3, cudf::binary_operator::ADD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(iota_3, iota_3_after_add->view());
// TESTING binary op EQUAL, LESS, GREATER
auto const trues = std::vector<bool>(sz, true);
auto const true_col = wrapper<bool>(trues.begin(), trues.end());
auto const btype = cudf::data_type{cudf::type_id::BOOL8};
auto const equal_result =
cudf::binary_operation(iota_3, iota_3_after_add->view(), cudf::binary_operator::EQUAL, btype);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, equal_result->view());
auto const less_result =
cudf::binary_operation(zeros_3, iota_3_after_add->view(), cudf::binary_operator::LESS, btype);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, less_result->view());
auto const greater_result = cudf::binary_operation(
iota_3_after_add->view(), zeros_3, cudf::binary_operator::GREATER, btype);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, greater_result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullMaxSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col1 = fp_wrapper<RepType>{{40, 30, 20, 10, 0}, {1, 0, 1, 1, 0}, scale_type{-2}};
auto const col2 = fp_wrapper<RepType>{{10, 20, 30, 40, 0}, {1, 1, 1, 0, 0}, scale_type{-2}};
auto const expected = fp_wrapper<RepType>{{40, 20, 30, 10, 0}, {1, 1, 1, 1, 0}, scale_type{-2}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::NULL_MAX,
static_cast<cudf::column_view>(col1).type(),
static_cast<cudf::column_view>(col2).type());
auto const result = cudf::binary_operation(col1, col2, cudf::binary_operator::NULL_MAX, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullMinSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col1 = fp_wrapper<RepType>{{40, 30, 20, 10, 0}, {1, 1, 1, 0, 0}, scale_type{-1}};
auto const col2 = fp_wrapper<RepType>{{10, 20, 30, 40, 0}, {1, 0, 1, 1, 0}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{10, 30, 20, 40, 0}, {1, 1, 1, 1, 0}, scale_type{-1}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::NULL_MIN,
static_cast<cudf::column_view>(col1).type(),
static_cast<cudf::column_view>(col2).type());
auto const result = cudf::binary_operation(col1, col2, cudf::binary_operator::NULL_MIN, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullEqualsSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col1 = fp_wrapper<RepType>{{400, 300, 300, 100}, {1, 1, 1, 0}, scale_type{-2}};
auto const col2 = fp_wrapper<RepType>{{40, 200, 20, 400}, {1, 0, 1, 0}, scale_type{-1}};
auto const expected = wrapper<bool>{{1, 0, 0, 1}, {1, 1, 1, 1}};
auto const result = cudf::binary_operation(
col1, col2, cudf::binary_operator::NULL_EQUALS, cudf::data_type{cudf::type_id::BOOL8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{100, 300, 500, 700}, scale_type{-2}};
auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{25, 75, 125, 175}, scale_type{-2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), -2};
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{100000, 300000, 500000, 700000}, scale_type{-3}};
auto const rhs = fp_wrapper<RepType>{{20, 20, 20, 20}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{5000, 15000, 25000, 35000}, scale_type{-2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), -2};
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div3)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10000, 30000, 50000, 70000}, scale_type{-2}};
auto const rhs = fp_wrapper<RepType>{{3, 9, 3, 3}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{3333, 3333, 16666, 23333}, scale_type{-2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), -2};
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div4)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(3, scale_type{0});
auto const expected = fp_wrapper<RepType>{{3, 10, 16, 23}, scale_type{1}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div6)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = cudf::make_fixed_point_scalar<decimalXX>(3000, scale_type{-3});
auto const rhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{300, 100, 60, 42}, scale_type{-2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), -2};
auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div7)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = cudf::make_fixed_point_scalar<decimalXX>(1200, scale_type{0});
auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 500, 600, 800, 1200, 1300}, scale_type{-2}};
auto const expected = fp_wrapper<RepType>{{12, 6, 4, 2, 2, 1, 1, 0}, scale_type{2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 2};
auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div8)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{4000, 6000, 80000}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(5000, scale_type{-3});
auto const expected = fp_wrapper<RepType>{{0, 1, 16}, scale_type{2}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 2};
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div9)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{10, 20, 30}, scale_type{2}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(7, scale_type{1});
auto const expected = fp_wrapper<RepType>{{1, 2, 4}, scale_type{1}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div10)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{100, 200, 300}, scale_type{1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(7, scale_type{0});
auto const expected = fp_wrapper<RepType>{{14, 28, 42}, scale_type{1}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div11)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{1000, 2000, 3000}, scale_type{1}};
auto const rhs = fp_wrapper<RepType>{{7, 7, 7}, scale_type{0}};
auto const expected = fp_wrapper<RepType>{{142, 285, 428}, scale_type{1}};
auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1};
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpThrows)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const col = fp_wrapper<RepType>{{100, 300, 500, 700}, scale_type{-2}};
auto const non_bool_type = cudf::data_type{cudf::type_to_id<decimalXX>(), -2};
EXPECT_THROW(cudf::binary_operation(col, col, cudf::binary_operator::LESS, non_bool_type),
cudf::data_type_error);
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpModSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10, 10, 10, 10}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{-3, -2, -1, 1, 2, 3, 4, 5}, scale_type{-1}};
auto const type =
cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MOD,
static_cast<cudf::column_view>(lhs).type(),
static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MOD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModSimple)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10, 10, 10, 10}, scale_type{-1}};
auto const expected = fp_wrapper<RepType>{{7, 8, 9, 1, 2, 3, 4, 5}, scale_type{-1}};
for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) {
auto const type = cudf::binary_operation_fixed_point_output_type(
op, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type());
auto const result = cudf::binary_operation(lhs, rhs, op, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpModSimple2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(10, scale_type{-1});
auto const expected = fp_wrapper<RepType>{{-3, -2, -1, 1, 2, 3, 4, 5}, scale_type{-1}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::MOD, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MOD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModAndPyModSimple2)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(10, scale_type{-1});
auto const expected = fp_wrapper<RepType>{{7, 8, 9, 1, 2, 3, 4, 5}, scale_type{-1}};
for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) {
auto const type = cudf::binary_operation_fixed_point_output_type(
op, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, op, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMod)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto constexpr N = 1000;
for (auto scale : {-1, -2, -3}) {
auto const iota = thrust::make_counting_iterator(-500);
auto const lhs = fp_wrapper<RepType>{iota, iota + N, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(7, scale_type{scale});
auto const factor = static_cast<int>(std::pow(10, -1 - scale));
auto const f = [factor](auto i) { return (i * factor) % 7; };
auto const exp_iter = cudf::detail::make_counting_transform_iterator(-500, f);
auto const expected = fp_wrapper<RepType>{exp_iter, exp_iter + N, scale_type{scale}};
auto const type = cudf::binary_operation_fixed_point_output_type(
cudf::binary_operator::MOD, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MOD, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
}
TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModAndPyMod)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
auto constexpr N = 1000;
for (auto const scale : {-1, -2, -3}) {
auto const iota = thrust::make_counting_iterator(-500);
auto const lhs = fp_wrapper<RepType>{iota, iota + N, scale_type{-1}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(7, scale_type{scale});
auto const factor = static_cast<int>(std::pow(10, -1 - scale));
auto const f = [factor](auto i) { return (((i * factor) % 7) + 7) % 7; };
auto const exp_iter = cudf::detail::make_counting_transform_iterator(-500, f);
auto const expected = fp_wrapper<RepType>{exp_iter, exp_iter + N, scale_type{scale}};
for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) {
auto const type = cudf::binary_operation_fixed_point_output_type(
op, static_cast<cudf::column_view>(lhs).type(), rhs->type());
auto const result = cudf::binary_operation(lhs, *rhs, op, type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
}
}
template <typename T>
struct FixedPointTest_64_128_Reps : public cudf::test::BaseFixture {};
using Decimal64And128Types = cudf::test::Types<numeric::decimal64, numeric::decimal128>;
TYPED_TEST_SUITE(FixedPointTest_64_128_Reps, Decimal64And128Types);
TYPED_TEST(FixedPointTest_64_128_Reps, FixedPoint_64_128_ComparisonTests)
{
using namespace numeric;
using decimalXX = TypeParam;
using RepType = cudf::device_storage_type_t<decimalXX>;
for (auto const rhs_value : {10000000000000000, 100000000000000000}) {
auto const lhs = fp_wrapper<RepType>{{33041, 97290, 36438, 25379, 48473}, scale_type{2}};
auto const rhs = cudf::make_fixed_point_scalar<decimalXX>(rhs_value, scale_type{0});
auto const trues = wrapper<bool>{{1, 1, 1, 1, 1}};
auto const falses = wrapper<bool>{{0, 0, 0, 0, 0}};
auto const bool_type = cudf::data_type{cudf::type_id::BOOL8};
auto const a = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::LESS, bool_type);
auto const b = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::LESS_EQUAL, bool_type);
auto const c = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::GREATER, bool_type);
auto const d =
cudf::binary_operation(lhs, *rhs, cudf::binary_operator::GREATER_EQUAL, bool_type);
auto const e = cudf::binary_operation(*rhs, lhs, cudf::binary_operator::GREATER, bool_type);
auto const f =
cudf::binary_operation(*rhs, lhs, cudf::binary_operator::GREATER_EQUAL, bool_type);
auto const g = cudf::binary_operation(*rhs, lhs, cudf::binary_operator::LESS, bool_type);
auto const h = cudf::binary_operation(*rhs, lhs, cudf::binary_operator::LESS_EQUAL, bool_type);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(a->view(), trues);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(b->view(), trues);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(c->view(), falses);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(d->view(), falses);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e->view(), trues);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(f->view(), trues);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(g->view(), falses);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(h->view(), falses);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-generic-ptx-test.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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/binaryop/assert-binops.h>
#include <tests/binaryop/binop-fixture.hpp>
#include <tests/binaryop/util/operation.h>
#include <tests/binaryop/util/runtime_support.h>
#include <cudf/binaryop.hpp>
struct BinaryOperationGenericPTXTest : public BinaryOperationTest {
protected:
void SetUp() override
{
if (!can_do_runtime_jit()) { GTEST_SKIP() << "Skipping tests that require 11.5 runtime"; }
}
};
TEST_F(BinaryOperationGenericPTXTest, CAdd_Vector_Vector_FP32_FP32_FP32)
{
// c = a*a*a + b
char const* ptx =
R"***(
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-26218862
// Cuda compilation tools, release 10.1, V10.1.168
// Based on LLVM 3.4svn
//
.version 6.4
.target sm_70
.address_size 64
// .globl _ZN8__main__7add$241Eff
.common .global .align 8 .u64 _ZN08NumbaEnv8__main__7add$241Eff;
.common .global .align 8 .u64 _ZN08NumbaEnv5numba7targets7numbers13int_power$242Efx;
.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
)
{
.reg .f32 %f<5>;
.reg .b32 %r<2>;
.reg .b64 %rd<2>;
ld.param.u64 %rd1, [_ZN8__main__7add$241Eff_param_0];
ld.param.f32 %f1, [_ZN8__main__7add$241Eff_param_1];
ld.param.f32 %f2, [_ZN8__main__7add$241Eff_param_2];
mul.f32 %f3, %f1, %f1;
fma.rn.f32 %f4, %f3, %f1, %f2;
st.f32 [%rd1], %f4;
mov.u32 %r1, 0;
st.param.b32 [func_retval0+0], %r1;
ret;
}
)***";
using TypeOut = float;
using TypeLhs = float;
using TypeRhs = float;
auto CADD = [](TypeLhs a, TypeRhs b) { return a * a * a + b; };
auto lhs = make_random_wrapped_column<TypeLhs>(500);
auto rhs = make_random_wrapped_column<TypeRhs>(500);
auto out = cudf::binary_operation(lhs, rhs, ptx, cudf::data_type(cudf::type_to_id<TypeOut>()));
// pow has a max ULP error of 2 per CUDA programming guide
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, CADD, NearEqualComparator<TypeOut>{2});
}
TEST_F(BinaryOperationGenericPTXTest, CAdd_Vector_Vector_INT64_INT32_INT32)
{
// c = a*a*a + b
char const* ptx =
R"***(
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: CL-26218862
// Cuda compilation tools, release 10.1, V10.1.168
// Based on LLVM 3.4svn
//
.version 6.4
.target sm_70
.address_size 64
// .globl _ZN8__main__7add$241Eii
.common .global .align 8 .u64 _ZN08NumbaEnv8__main__7add$241Eii;
.common .global .align 8 .u64 _ZN08NumbaEnv5numba7targets7numbers14int_power_impl12$3clocals$3e13int_power$242Exx;
.visible .func (.param .b32 func_retval0) _ZN8__main__7add$241Eii(
.param .b64 _ZN8__main__7add$241Eii_param_0,
.param .b32 _ZN8__main__7add$241Eii_param_1,
.param .b32 _ZN8__main__7add$241Eii_param_2
)
{
.reg .b32 %r<3>;
.reg .b64 %rd<7>;
ld.param.u64 %rd1, [_ZN8__main__7add$241Eii_param_0];
ld.param.u32 %r1, [_ZN8__main__7add$241Eii_param_1];
cvt.s64.s32 %rd2, %r1;
mul.wide.s32 %rd3, %r1, %r1;
mul.lo.s64 %rd4, %rd3, %rd2;
ld.param.s32 %rd5, [_ZN8__main__7add$241Eii_param_2];
add.s64 %rd6, %rd4, %rd5;
st.u64 [%rd1], %rd6;
mov.u32 %r2, 0;
st.param.b32 [func_retval0+0], %r2;
ret;
}
)***";
using TypeOut = int64_t;
using TypeLhs = int32_t;
using TypeRhs = int32_t;
auto CADD = [](TypeLhs a, TypeRhs b) { return a * a * a + b; };
auto lhs = make_random_wrapped_column<TypeLhs>(500);
auto rhs = make_random_wrapped_column<TypeRhs>(500);
auto out = cudf::binary_operation(lhs, rhs, ptx, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, CADD);
}
TEST_F(BinaryOperationGenericPTXTest, CAdd_Vector_Vector_INT64_INT32_INT64)
{
// c = a*a*a + b*b
char const* ptx =
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$241Eix
.common .global .align 8 .u64 _ZN08NumbaEnv8__main__7add$241Eix;
.common .global .align 8 .u64 _ZN08NumbaEnv5numba7targets7numbers14int_power_impl12$3clocals$3e13int_power$242Exx;
.visible .func (.param .b32 func_retval0) _ZN8__main__7add$241Eix(
.param .b64 _ZN8__main__7add$241Eix_param_0,
.param .b32 _ZN8__main__7add$241Eix_param_1,
.param .b64 _ZN8__main__7add$241Eix_param_2
)
{
.reg .b32 %r<3>;
.reg .b64 %rd<8>;
ld.param.u64 %rd1, [_ZN8__main__7add$241Eix_param_0];
ld.param.u32 %r1, [_ZN8__main__7add$241Eix_param_1];
ld.param.u64 %rd2, [_ZN8__main__7add$241Eix_param_2];
cvt.s64.s32 %rd3, %r1;
mul.wide.s32 %rd4, %r1, %r1;
mul.lo.s64 %rd5, %rd4, %rd3;
mul.lo.s64 %rd6, %rd2, %rd2;
add.s64 %rd7, %rd6, %rd5;
st.u64 [%rd1], %rd7;
mov.u32 %r2, 0;
st.param.b32 [func_retval0+0], %r2;
ret;
}
)***";
using TypeOut = int64_t;
using TypeLhs = int32_t;
using TypeRhs = int64_t;
auto CADD = [](TypeLhs a, TypeRhs b) { return a * a * a + b * b; };
auto lhs = make_random_wrapped_column<TypeLhs>(500);
auto rhs = make_random_wrapped_column<TypeRhs>(500);
auto out = cudf::binary_operation(lhs, rhs, ptx, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, CADD);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-null-test.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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/binaryop/util/runtime_support.h>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/iterator_utilities.hpp>
#include <cudf/binaryop.hpp>
struct BinaryOperationNullTest : public cudf::test::BaseFixture {
protected:
void SetUp() override
{
if (!can_do_runtime_jit()) { GTEST_SKIP() << "Skipping tests that require 11.5 runtime"; }
}
};
TEST_F(BinaryOperationNullTest, Scalar_Null_Vector_Valid)
{
auto lhs = cudf::scalar_type_t<int32_t>(0);
lhs.set_valid_async(false);
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
cudf::test::iterators::no_nulls());
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
auto expected = cudf::test::fixed_width_column_wrapper<int32_t>(
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, cudf::test::iterators::all_nulls());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected);
}
TEST_F(BinaryOperationNullTest, Scalar_Valid_Vector_NonNullable)
{
auto lhs = cudf::scalar_type_t<int32_t>(1);
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
auto expected = cudf::test::fixed_width_column_wrapper<int32_t>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected);
}
TEST_F(BinaryOperationNullTest, Scalar_Null_Vector_NonNullable)
{
auto lhs = cudf::scalar_type_t<int32_t>(0);
lhs.set_valid_async(false);
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
auto expected = cudf::test::fixed_width_column_wrapper<int32_t>(
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, cudf::test::iterators::all_nulls());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected);
}
TEST_F(BinaryOperationNullTest, Vector_Null_Scalar_Valid)
{
auto lhs = cudf::scalar_type_t<int32_t>(1);
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
cudf::test::iterators::all_nulls());
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), rhs);
}
TEST_F(BinaryOperationNullTest, Vector_Null_Vector_Valid)
{
auto lhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
cudf::test::iterators::all_nulls());
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
cudf::test::iterators::no_nulls());
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), lhs);
}
TEST_F(BinaryOperationNullTest, Vector_Null_Vector_NonNullable)
{
auto lhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
cudf::test::iterators::all_nulls());
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), lhs);
}
TEST_F(BinaryOperationNullTest, Vector_Valid_Vector_NonNullable)
{
auto lhs = cudf::test::fixed_width_column_wrapper<int32_t>({9, 8, 7, 6, 5, 4, 3, 2, 1, 0},
cudf::test::iterators::no_nulls());
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
auto expected = cudf::test::fixed_width_column_wrapper<int32_t>(
{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, cudf::test::iterators::no_nulls());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected);
}
TEST_F(BinaryOperationNullTest, Vector_NonNullable_Vector_NonNullable)
{
auto lhs = cudf::test::fixed_width_column_wrapper<int32_t>({9, 8, 7, 6, 5, 4, 3, 2, 1, 0});
auto rhs = cudf::test::fixed_width_column_wrapper<int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ADD, cudf::data_type(cudf::type_id::INT32));
auto expected = cudf::test::fixed_width_column_wrapper<int32_t>({9, 9, 9, 9, 9, 9, 9, 9, 9, 9});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-fixture.hpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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/detail/iterator.cuh>
#include <string>
#include <type_traits>
struct BinaryOperationTest : public cudf::test::BaseFixture {
BinaryOperationTest() {}
static constexpr int r_min = 1;
static constexpr int r_max = 10;
template <typename T>
static auto make_data_iter(cudf::test::UniformRandomGenerator<T>& rand_gen)
{
return cudf::detail::make_counting_transform_iterator(
0, [&](auto row) { return rand_gen.generate(); });
}
static auto make_validity_iter()
{
cudf::test::UniformRandomGenerator<uint8_t> rand_gen(r_min, r_max);
uint8_t mod_base = rand_gen.generate();
return cudf::detail::make_counting_transform_iterator(
0, [mod_base](auto row) { return (row % mod_base) > 0; });
}
template <typename T>
static auto make_random_wrapped_column(cudf::size_type size)
{
cudf::test::UniformRandomGenerator<T> rand_gen(r_min, r_max);
auto data_iter = make_data_iter(rand_gen);
auto validity_iter = make_validity_iter();
return cudf::test::fixed_width_column_wrapper<T>(data_iter, data_iter + size, validity_iter);
}
template <typename T, std::enable_if_t<!std::is_same_v<T, std::string>>* = nullptr>
auto make_random_wrapped_scalar()
{
cudf::test::UniformRandomGenerator<T> rand_gen(r_min, r_max);
return cudf::scalar_type_t<T>(rand_gen.generate());
}
template <typename T, std::enable_if_t<std::is_same_v<T, std::string>>* = nullptr>
auto make_random_wrapped_scalar()
{
cudf::test::UniformRandomGenerator<uint8_t> rand_gen(r_min, r_max);
uint8_t size = rand_gen.generate();
std::string str{"ஔⒶbc⁂∰ൠ \tنж水✉♪✿™"};
return cudf::scalar_type_t<T>(str.substr(0, size));
}
};
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/binop-compiled-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 <tests/binaryop/assert-binops.h>
#include <tests/binaryop/binop-fixture.hpp>
#include <tests/binaryop/util/operation.h>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/type_lists.hpp>
#include <cudf/binaryop.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/types.hpp>
#include <cudf/unary.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <limits>
#include <type_traits>
template <typename T>
auto lhs_random_column(cudf::size_type size)
{
return BinaryOperationTest::make_random_wrapped_column<T>(size);
}
template <>
auto lhs_random_column<std::string>(cudf::size_type size)
{
return cudf::test::strings_column_wrapper({"eee", "bb", "<null>", "", "aa", "bbb", "ééé"},
{1, 1, 0, 1, 1, 1, 1});
}
template <typename T>
auto rhs_random_column(cudf::size_type size)
{
return BinaryOperationTest::make_random_wrapped_column<T>(size);
}
template <>
auto rhs_random_column<std::string>(cudf::size_type size)
{
return cudf::test::strings_column_wrapper({"ééé", "bbb", "aa", "", "<null>", "bb", "eee"},
{1, 1, 1, 1, 0, 1, 1});
}
// combinations to test
// n t d
// n n.n n.t n.d
// t t.n t.t t.d
// d d.n d.t d.d
constexpr cudf::size_type col_size = 10000;
template <typename T>
struct BinaryOperationCompiledTest : public BinaryOperationTest {
using TypeOut = cudf::test::GetType<T, 0>;
using TypeLhs = cudf::test::GetType<T, 1>;
using TypeRhs = cudf::test::GetType<T, 2>;
template <template <typename... Ty> class FunctorOP>
void test(cudf::binary_operator op)
{
using OPERATOR = FunctorOP<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto out = cudf::binary_operation(lhs, rhs, op, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, OPERATOR());
auto s_lhs = this->template make_random_wrapped_scalar<TypeLhs>();
auto s_rhs = this->template make_random_wrapped_scalar<TypeRhs>();
s_lhs.set_valid_async(true);
s_rhs.set_valid_async(true);
out = cudf::binary_operation(lhs, s_rhs, op, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, s_rhs, OPERATOR());
out = cudf::binary_operation(s_lhs, rhs, op, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, s_lhs, rhs, OPERATOR());
s_lhs.set_valid_async(false);
s_rhs.set_valid_async(false);
out = cudf::binary_operation(lhs, s_rhs, op, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, s_rhs, OPERATOR());
out = cudf::binary_operation(s_lhs, rhs, op, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, s_lhs, rhs, OPERATOR());
}
};
// ADD
// n t d
// n n + n
// t t + d
// d d + t d + d
using namespace numeric;
using Add_types =
cudf::test::Types<cudf::test::Types<bool, bool, float>,
cudf::test::Types<int16_t, double, uint8_t>,
cudf::test::Types<cudf::timestamp_s, cudf::timestamp_s, cudf::duration_s>,
cudf::test::Types<cudf::timestamp_ns, cudf::duration_ms, cudf::timestamp_us>,
cudf::test::Types<cudf::duration_us, cudf::duration_us, cudf::duration_D>,
// cudf::test::Types<duration_s, int16_t, int64_t>, //valid
cudf::test::Types<decimal32, decimal32, decimal32>,
cudf::test::Types<decimal64, decimal64, decimal64>,
cudf::test::Types<decimal128, decimal128, decimal128>,
cudf::test::Types<int, decimal32, decimal32>,
cudf::test::Types<int, decimal64, decimal64>,
cudf::test::Types<int, decimal128, decimal128>,
// Extras
cudf::test::Types<cudf::duration_D, cudf::duration_D, cudf::duration_D>,
cudf::test::Types<cudf::timestamp_D, cudf::timestamp_D, cudf::duration_D>,
cudf::test::Types<cudf::timestamp_s, cudf::timestamp_D, cudf::duration_s>,
cudf::test::Types<cudf::timestamp_ms, cudf::timestamp_ms, cudf::duration_s>,
cudf::test::Types<cudf::timestamp_ns, cudf::timestamp_ms, cudf::duration_ns>>;
template <typename T>
struct BinaryOperationCompiledTest_Add : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Add, Add_types);
TYPED_TEST(BinaryOperationCompiledTest_Add, Vector_Vector)
{
this->template test<cudf::library::operation::Add>(cudf::binary_operator::ADD);
}
// SUB
// n t d
// n n - n
// t t - t t - d
// d d - d
using Sub_types = cudf::test::Types<
cudf::test::Types<int32_t, bool, float>, // n - n
cudf::test::Types<cudf::duration_D, cudf::timestamp_D, cudf::timestamp_D>, // t - t
cudf::test::Types<cudf::timestamp_s, cudf::timestamp_D, cudf::duration_s>, // t - d
cudf::test::Types<cudf::duration_ns, cudf::duration_us, cudf::duration_s>, // d - d
cudf::test::Types<cudf::duration_us, cudf::duration_us, cudf::duration_s>, // d - d
cudf::test::Types<decimal32, decimal32, decimal32>,
cudf::test::Types<decimal64, decimal64, decimal64>,
cudf::test::Types<decimal128, decimal128, decimal128>,
cudf::test::Types<int, decimal32, decimal32>,
cudf::test::Types<int, decimal64, decimal64>,
cudf::test::Types<int, decimal128, decimal128>>;
template <typename T>
struct BinaryOperationCompiledTest_Sub : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Sub, Sub_types);
TYPED_TEST(BinaryOperationCompiledTest_Sub, Vector_Vector)
{
this->template test<cudf::library::operation::Sub>(cudf::binary_operator::SUB);
}
// MUL
// n t d
// n n * n n * d
// t
// d d * n
using Mul_types =
cudf::test::Types<cudf::test::Types<int32_t, u_int64_t, float>,
cudf::test::Types<cudf::duration_s, u_int64_t, cudf::duration_s>,
cudf::test::Types<cudf::duration_ms, cudf::duration_D, int16_t>,
cudf::test::Types<cudf::duration_ns, cudf::duration_us, uint8_t>,
cudf::test::Types<decimal32, decimal32, decimal32>,
cudf::test::Types<decimal64, decimal64, decimal64>,
cudf::test::Types<decimal128, decimal128, decimal128>,
cudf::test::Types<int, decimal32, decimal32>,
cudf::test::Types<int, decimal64, decimal64>,
cudf::test::Types<int, decimal128, decimal128>,
cudf::test::Types<decimal32, int, int>,
cudf::test::Types<decimal64, int, int>,
cudf::test::Types<decimal128, int, int>>;
template <typename T>
struct BinaryOperationCompiledTest_Mul : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Mul, Mul_types);
TYPED_TEST(BinaryOperationCompiledTest_Mul, Vector_Vector)
{
this->template test<cudf::library::operation::Mul>(cudf::binary_operator::MUL);
}
// DIV
// n t d
// n n / n
// t
// d d / n d / d
using Div_types =
cudf::test::Types<cudf::test::Types<int16_t, u_int64_t, u_int64_t>,
cudf::test::Types<double, int8_t, int64_t>,
cudf::test::Types<cudf::duration_ms, cudf::duration_s, u_int32_t>,
cudf::test::Types<cudf::duration_ns, cudf::duration_D, int16_t>,
cudf::test::Types<double, cudf::duration_D, cudf::duration_ns>,
cudf::test::Types<float, cudf::duration_ms, cudf::duration_ns>,
cudf::test::Types<u_int64_t, cudf::duration_us, cudf::duration_ns>,
cudf::test::Types<decimal32, decimal32, decimal32>,
cudf::test::Types<decimal64, decimal64, decimal64>,
cudf::test::Types<decimal128, decimal128, decimal128>,
cudf::test::Types<int, decimal32, decimal32>,
cudf::test::Types<int, decimal64, decimal64>,
cudf::test::Types<int, decimal128, decimal128>>;
template <typename T>
struct BinaryOperationCompiledTest_Div : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Div, Div_types);
TYPED_TEST(BinaryOperationCompiledTest_Div, Vector_Vector)
{
this->template test<cudf::library::operation::Div>(cudf::binary_operator::DIV);
}
// TRUE-DIV
// n t d
// n n / n
// t
// d
using TrueDiv_types = cudf::test::Types<cudf::test::Types<int16_t, u_int64_t, u_int64_t>,
cudf::test::Types<double, int8_t, int64_t>,
cudf::test::Types<int8_t, bool, u_int32_t>,
cudf::test::Types<u_int64_t, float, int16_t>>;
template <typename T>
struct BinaryOperationCompiledTest_TrueDiv : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_TrueDiv, TrueDiv_types);
TYPED_TEST(BinaryOperationCompiledTest_TrueDiv, Vector_Vector)
{
this->template test<cudf::library::operation::TrueDiv>(cudf::binary_operator::TRUE_DIV);
}
// FLOOR_DIV
// n t d
// n n / n
// t
// d
TYPED_TEST(BinaryOperationCompiledTest_TrueDiv, FloorDiv_Vector_Vector)
{
this->template test<cudf::library::operation::FloorDiv>(cudf::binary_operator::FLOOR_DIV);
}
// MOD
// n t d
// n n % n
// t
// d d % n d % d
using Mod_types =
cudf::test::Types<cudf::test::Types<int16_t, u_int64_t, u_int64_t>,
cudf::test::Types<double, int8_t, int64_t>,
cudf::test::Types<cudf::duration_ms, cudf::duration_s, u_int32_t>,
cudf::test::Types<cudf::duration_D, cudf::duration_D, int16_t>,
cudf::test::Types<cudf::duration_ns, cudf::duration_D, int16_t>,
cudf::test::Types<cudf::duration_ns, cudf::duration_us, cudf::duration_ns>>;
template <typename T>
struct BinaryOperationCompiledTest_Mod : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Mod, Mod_types);
TYPED_TEST(BinaryOperationCompiledTest_Mod, Vector_Vector)
{
this->template test<cudf::library::operation::Mod>(cudf::binary_operator::MOD);
}
// PYMOD
// n t d
// n n % n
// t
// d d % d
using PyMod_types =
cudf::test::Types<cudf::test::Types<int16_t, u_int64_t, u_int64_t>,
cudf::test::Types<double, int8_t, int64_t>,
cudf::test::Types<double, double, double>,
cudf::test::Types<cudf::duration_ns, cudf::duration_us, cudf::duration_ns>>;
template <typename T>
struct BinaryOperationCompiledTest_PyMod : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_PyMod, PyMod_types);
TYPED_TEST(BinaryOperationCompiledTest_PyMod, Vector_Vector)
{
this->template test<cudf::library::operation::PyMod>(cudf::binary_operator::PYMOD);
}
// POW
// n t d
// n n ^ n
// t
// d
using Pow_types = cudf::test::Types<cudf::test::Types<double, int64_t, int64_t>,
cudf::test::Types<float, float, float>,
cudf::test::Types<int, int32_t, float>,
cudf::test::Types<float, int, int>,
cudf::test::Types<double, int64_t, int32_t>,
cudf::test::Types<double, double, double>,
cudf::test::Types<double, float, double>,
cudf::test::Types<double, int32_t, int64_t>>;
template <typename T>
struct BinaryOperationCompiledTest_FloatOps : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_FloatOps, Pow_types);
TYPED_TEST(BinaryOperationCompiledTest_FloatOps, Pow_Vector_Vector)
{
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using POW = cudf::library::operation::Pow<TypeOut, TypeLhs, TypeRhs>;
auto lhs = []() {
// resulting value can not be represented by the target type => behavior is undefined
// -2147483648 in host, 2147483647 in device
if constexpr (std::is_same_v<TypeOut, int>) {
auto elements =
cudf::detail::make_counting_transform_iterator(1, [](auto i) { return i % 5; });
return cudf::test::fixed_width_column_wrapper<TypeLhs>(elements, elements + 100);
}
return lhs_random_column<TypeLhs>(100);
}();
auto rhs = rhs_random_column<TypeRhs>(100);
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::POW, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, POW(), NearEqualComparator<TypeOut>{2});
}
// LOG_BASE
// n t d
// n log(n, n)
// t
// d
TYPED_TEST(BinaryOperationCompiledTest_FloatOps, LogBase_Vector_Vector)
{
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using LOG_BASE = cudf::library::operation::LogBase<TypeOut, TypeLhs, TypeRhs>;
// Make sure there are no zeros
auto elements = cudf::detail::make_counting_transform_iterator(
1, [](auto i) { return sizeof(TypeLhs) > 4 ? std::pow(2, i) : i + 30; });
cudf::test::fixed_width_column_wrapper<TypeLhs> lhs(elements, elements + 50);
// Find log to the base 7
auto rhs_elements = cudf::detail::make_counting_transform_iterator(0, [](auto) { return 7; });
cudf::test::fixed_width_column_wrapper<TypeRhs> rhs(rhs_elements, rhs_elements + 50);
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::LOG_BASE, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, LOG_BASE());
}
// ATAN2
// n t d
// n ATan2(n, n)
// t
// d
TYPED_TEST(BinaryOperationCompiledTest_FloatOps, ATan2_Vector_Vector)
{
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using ATAN2 = cudf::library::operation::ATan2<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto out = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::ATAN2, cudf::data_type(cudf::type_to_id<TypeOut>()));
ASSERT_BINOP<TypeOut, TypeLhs, TypeRhs>(*out, lhs, rhs, ATAN2(), NearEqualComparator<TypeOut>{2});
}
TYPED_TEST(BinaryOperationCompiledTest_FloatOps, PMod_Vector_Vector)
{
this->template test<cudf::library::operation::PMod>(cudf::binary_operator::PMOD);
}
using IntPow_types = cudf::test::Types<cudf::test::Types<int32_t, int32_t, int32_t>,
cudf::test::Types<int64_t, int64_t, int64_t>>;
template <typename T>
struct BinaryOperationCompiledTest_IntPow : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_IntPow, IntPow_types);
TYPED_TEST(BinaryOperationCompiledTest_IntPow, IntPow_SpecialCases)
{
// This tests special values for which integer powers are required. Casting
// to double and casting the result back to int results in floating point
// losses, like 3**1 == 2.
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
auto lhs = cudf::test::fixed_width_column_wrapper<TypeLhs>({3, -3, 8, -8});
auto rhs = cudf::test::fixed_width_column_wrapper<TypeRhs>({1, 1, 7, 7});
auto expected = cudf::test::fixed_width_column_wrapper<TypeOut>({3, -3, 2097152, -2097152});
auto result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::INT_POW, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TEST(BinaryOperationCompiledTestFloorDivInt64, FloorDivInt64Positive)
{
// This tests special values for which integer floor division is
// incorrect if round-tripped through casting to double precision.
// Double precision floating point does not have enough resolution
// to represent these integers distinctly, so if we were to cast to
// double, we would get three identical results (all wrong!).
auto lhs =
cudf::test::fixed_width_column_wrapper<int64_t>({std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max() - 10,
std::numeric_limits<int64_t>::max() - 100});
auto rhs = cudf::test::fixed_width_column_wrapper<int64_t>({10, 10, 10});
auto expected = cudf::test::fixed_width_column_wrapper<int64_t>(
{std::numeric_limits<int64_t>::max() / 10,
(std::numeric_limits<int64_t>::max() - 10) / 10,
(std::numeric_limits<int64_t>::max() - 100) / 10});
auto result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::FLOOR_DIV, cudf::data_type(cudf::type_to_id<int64_t>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TEST(BinaryOperationCompiledTestFloorDivInt64, FloorDivInt64RoundNegativeInf)
{
// Floor division should round towards negative infinity. Which is
// distinct from default integral division in C++ which rounds
// towards zero (truncation)
auto lhs =
cudf::test::fixed_width_column_wrapper<int64_t>({std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::min() + 10,
std::numeric_limits<int64_t>::min() + 100});
auto rhs = cudf::test::fixed_width_column_wrapper<int64_t>({10, 10, 10});
// int64_t::min() is not divisible by 10, so there is a non-zero
// remainder which should be rounded down.
auto expected = cudf::test::fixed_width_column_wrapper<int64_t>(
{std::numeric_limits<int64_t>::min() / 10 - 1,
(std::numeric_limits<int64_t>::min() + 10) / 10 - 1,
(std::numeric_limits<int64_t>::min() + 100) / 10 - 1});
auto result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::FLOOR_DIV, cudf::data_type(cudf::type_to_id<int64_t>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
// Bit Operations
// n t d
// n n . n
// t
// d
// i.i, i.u, u.i, u.u -> i
// i.i, i.u, u.i, u.u -> u
using Bit_types = cudf::test::Types<cudf::test::Types<int16_t, int8_t, int16_t>,
cudf::test::Types<int64_t, int32_t, uint16_t>,
cudf::test::Types<int64_t, uint64_t, int64_t>,
cudf::test::Types<int16_t, uint32_t, uint8_t>,
// cudf::test::Types<bool, int8_t, uint8_t>, // valid
cudf::test::Types<uint16_t, int8_t, int16_t>,
cudf::test::Types<uint64_t, int32_t, uint16_t>,
cudf::test::Types<uint64_t, uint64_t, int64_t>,
cudf::test::Types<uint16_t, uint8_t, uint32_t>>;
template <typename T>
struct BinaryOperationCompiledTest_Bit : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Bit, Bit_types);
TYPED_TEST(BinaryOperationCompiledTest_Bit, BitwiseAnd_Vector_Vector)
{
this->template test<cudf::library::operation::BitwiseAnd>(cudf::binary_operator::BITWISE_AND);
}
TYPED_TEST(BinaryOperationCompiledTest_Bit, BitwiseOr_Vector_Vector)
{
this->template test<cudf::library::operation::BitwiseOr>(cudf::binary_operator::BITWISE_OR);
}
TYPED_TEST(BinaryOperationCompiledTest_Bit, BitwiseXor_Vector_Vector)
{
this->template test<cudf::library::operation::BitwiseXor>(cudf::binary_operator::BITWISE_XOR);
}
TYPED_TEST(BinaryOperationCompiledTest_Bit, ShiftLeft_Vector_Vector)
{
this->template test<cudf::library::operation::ShiftLeft>(cudf::binary_operator::SHIFT_LEFT);
}
TYPED_TEST(BinaryOperationCompiledTest_Bit, ShiftRight_Vector_Vector)
{
this->template test<cudf::library::operation::ShiftRight>(cudf::binary_operator::SHIFT_RIGHT);
}
TYPED_TEST(BinaryOperationCompiledTest_Bit, ShiftRightUnsigned_Vector_Vector)
{
this->template test<cudf::library::operation::ShiftRightUnsigned>(
cudf::binary_operator::SHIFT_RIGHT_UNSIGNED);
}
// Logical Operations
// n t d
// n n . n
// t
// d
using Logical_types = cudf::test::Types<cudf::test::Types<bool, int8_t, int16_t>,
cudf::test::Types<bool, int32_t, uint16_t>,
cudf::test::Types<bool, uint64_t, double>,
cudf::test::Types<bool, int8_t, int16_t>,
cudf::test::Types<bool, float, uint16_t>,
cudf::test::Types<bool, uint64_t, int64_t>,
cudf::test::Types<bool, uint8_t, uint32_t>,
cudf::test::Types<bool, uint64_t, int64_t>>;
template <typename T>
struct BinaryOperationCompiledTest_Logical : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Logical, Logical_types);
TYPED_TEST(BinaryOperationCompiledTest_Logical, LogicalAnd_Vector_Vector)
{
this->template test<cudf::library::operation::LogicalAnd>(cudf::binary_operator::LOGICAL_AND);
}
TYPED_TEST(BinaryOperationCompiledTest_Logical, LogicalOr_Vector_Vector)
{
this->template test<cudf::library::operation::LogicalOr>(cudf::binary_operator::LOGICAL_OR);
}
template <typename T>
using column_wrapper = std::conditional_t<std::is_same_v<T, std::string>,
cudf::test::strings_column_wrapper,
cudf::test::fixed_width_column_wrapper<T>>;
template <typename TypeOut, typename TypeLhs, typename TypeRhs, class OP>
auto NullOp_Result(cudf::column_view lhs, cudf::column_view rhs)
{
auto [lhs_data, lhs_mask] = cudf::test::to_host<TypeLhs>(lhs);
auto [rhs_data, rhs_mask] = cudf::test::to_host<TypeRhs>(rhs);
std::vector<TypeOut> result(lhs.size());
std::vector<bool> result_mask;
std::transform(thrust::make_counting_iterator(0),
thrust::make_counting_iterator(lhs.size()),
result.begin(),
[&lhs_data, &lhs_mask, &rhs_data, &rhs_mask, &result_mask](auto i) -> TypeOut {
auto lhs_valid = lhs_mask.data() and cudf::bit_is_set(lhs_mask.data(), i);
auto rhs_valid = rhs_mask.data() and cudf::bit_is_set(rhs_mask.data(), i);
bool output_valid = lhs_valid or rhs_valid;
auto result = OP{}(lhs_data[i], rhs_data[i], lhs_valid, rhs_valid, output_valid);
result_mask.push_back(output_valid);
return result;
});
return column_wrapper<TypeOut>(result.cbegin(), result.cend(), result_mask.cbegin());
}
TYPED_TEST(BinaryOperationCompiledTest_Logical, NullLogicalAnd_Vector_Vector)
{
using TypeOut = bool;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using NULL_AND = cudf::library::operation::NullLogicalAnd<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_AND>(lhs, rhs);
auto const result = cudf::binary_operation(lhs,
rhs,
cudf::binary_operator::NULL_LOGICAL_AND,
cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(BinaryOperationCompiledTest_Logical, NullLogicalOr_Vector_Vector)
{
using TypeOut = bool;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using NULL_OR = cudf::library::operation::NullLogicalOr<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_OR>(lhs, rhs);
auto const result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::NULL_LOGICAL_OR, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
// Comparison Operations ==, !=, <, >, <=, >=
// n<!=>n, t<!=>t, d<!=>d, s<!=>s, dc<!=>dc
using Comparison_types =
cudf::test::Types<cudf::test::Types<bool, int8_t, int16_t>,
cudf::test::Types<bool, uint32_t, uint16_t>,
cudf::test::Types<bool, uint64_t, double>,
cudf::test::Types<bool, cudf::timestamp_D, cudf::timestamp_s>,
cudf::test::Types<bool, cudf::timestamp_ns, cudf::timestamp_us>,
cudf::test::Types<bool, cudf::duration_ns, cudf::duration_ns>,
cudf::test::Types<bool, cudf::duration_us, cudf::duration_s>,
cudf::test::Types<bool, std::string, std::string>,
cudf::test::Types<bool, decimal32, decimal32>,
cudf::test::Types<bool, decimal64, decimal64>,
cudf::test::Types<bool, decimal128, decimal128>>;
template <typename T>
struct BinaryOperationCompiledTest_Comparison : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_Comparison, Comparison_types);
TYPED_TEST(BinaryOperationCompiledTest_Comparison, Equal_Vector_Vector)
{
this->template test<cudf::library::operation::Equal>(cudf::binary_operator::EQUAL);
}
TYPED_TEST(BinaryOperationCompiledTest_Comparison, NotEqual_Vector_Vector)
{
this->template test<cudf::library::operation::NotEqual>(cudf::binary_operator::NOT_EQUAL);
}
TYPED_TEST(BinaryOperationCompiledTest_Comparison, Less_Vector_Vector)
{
this->template test<cudf::library::operation::Less>(cudf::binary_operator::LESS);
}
TYPED_TEST(BinaryOperationCompiledTest_Comparison, Greater_Vector_Vector)
{
this->template test<cudf::library::operation::Greater>(cudf::binary_operator::GREATER);
}
TYPED_TEST(BinaryOperationCompiledTest_Comparison, LessEqual_Vector_Vector)
{
this->template test<cudf::library::operation::LessEqual>(cudf::binary_operator::LESS_EQUAL);
}
TYPED_TEST(BinaryOperationCompiledTest_Comparison, GreaterEqual_Vector_Vector)
{
this->template test<cudf::library::operation::GreaterEqual>(cudf::binary_operator::GREATER_EQUAL);
}
// Null Operations NullMax, NullMin
// Min(n,n) , Min(t,t), Min(d, d), Min(s, s), Min(dc, dc), Min(n,dc), Min(dc, n)
// n t d s dc
// n . .
// t .
// d .
// s .
// dc . .
using Null_types =
cudf::test::Types<cudf::test::Types<int16_t, int8_t, int16_t>,
cudf::test::Types<uint16_t, uint32_t, uint16_t>,
cudf::test::Types<double, uint64_t, double>,
cudf::test::Types<cudf::timestamp_s, cudf::timestamp_D, cudf::timestamp_s>,
cudf::test::Types<cudf::duration_ns, cudf::duration_us, cudf::duration_s>,
// cudf::test::Types<std::string, std::string, std::string>, // only fixed-width
cudf::test::Types<decimal32, decimal32, decimal32>,
cudf::test::Types<decimal64, decimal64, decimal64>,
cudf::test::Types<decimal128, decimal128, decimal128>,
cudf::test::Types<decimal32, uint32_t, decimal32>,
cudf::test::Types<decimal64, uint32_t, decimal64>,
cudf::test::Types<decimal128, uint32_t, decimal128>,
cudf::test::Types<int64_t, decimal32, decimal32>,
cudf::test::Types<int64_t, decimal64, decimal64>,
cudf::test::Types<int64_t, decimal128, decimal128>>;
template <typename T>
struct BinaryOperationCompiledTest_NullOps : public BinaryOperationCompiledTest<T> {};
TYPED_TEST_SUITE(BinaryOperationCompiledTest_NullOps, Null_types);
TYPED_TEST(BinaryOperationCompiledTest_NullOps, NullEquals_Vector_Vector)
{
using TypeOut = bool;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using NULL_EQUALS = cudf::library::operation::NullEquals<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_EQUALS>(lhs, rhs);
auto const result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::NULL_EQUALS, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
using BinaryOperationCompiledTest_NullOpsString =
BinaryOperationCompiledTest_NullOps<cudf::test::Types<std::string, std::string, std::string>>;
TEST_F(BinaryOperationCompiledTest_NullOpsString, NullEquals_Vector_Vector)
{
using TypeOut = bool;
using TypeLhs = std::string;
using TypeRhs = std::string;
using NULL_EQUALS = cudf::library::operation::NullEquals<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_EQUALS>(lhs, rhs);
auto const result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::NULL_EQUALS, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(BinaryOperationCompiledTest_NullOps, NullMax_Vector_Vector)
{
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using NULL_MAX = cudf::library::operation::NullMax<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_MAX>(lhs, rhs);
auto const result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::NULL_MAX, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TYPED_TEST(BinaryOperationCompiledTest_NullOps, NullMin_Vector_Vector)
{
using TypeOut = typename TestFixture::TypeOut;
using TypeLhs = typename TestFixture::TypeLhs;
using TypeRhs = typename TestFixture::TypeRhs;
using NULL_MIN = cudf::library::operation::NullMin<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_MIN>(lhs, rhs);
auto const result = cudf::binary_operation(
lhs, rhs, cudf::binary_operator::NULL_MIN, cudf::data_type(cudf::type_to_id<TypeOut>()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view());
}
TEST_F(BinaryOperationCompiledTest_NullOpsString, NullMax_Vector_Vector)
{
using TypeOut = std::string;
using TypeLhs = std::string;
using TypeRhs = std::string;
using NULL_MAX = cudf::library::operation::NullMax<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_MAX>(lhs, rhs);
auto const result =
cudf::binary_operation(lhs,
rhs,
cudf::binary_operator::NULL_MAX,
cudf::data_type(cudf::type_to_id<cudf::string_view>()));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->view());
}
TEST_F(BinaryOperationCompiledTest_NullOpsString, NullMin_Vector_Vector)
{
using TypeOut = std::string;
using TypeLhs = std::string;
using TypeRhs = std::string;
using NULL_MIN = cudf::library::operation::NullMin<TypeOut, TypeLhs, TypeRhs>;
auto lhs = lhs_random_column<TypeLhs>(col_size);
auto rhs = rhs_random_column<TypeRhs>(col_size);
auto const expected = NullOp_Result<TypeOut, TypeLhs, TypeRhs, NULL_MIN>(lhs, rhs);
auto const result =
cudf::binary_operation(lhs,
rhs,
cudf::binary_operator::NULL_MIN,
cudf::data_type(cudf::type_to_id<cudf::string_view>()));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->view());
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/assert-binops.h
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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/cudf_gtest.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/utilities/traits.hpp>
#include <limits>
// This is used to convert the expected binop result computed by the test utilities and the
// result returned by the binop operation into string, which is then used for display purposes
// when the values do not match.
struct stringify_out_values {
template <typename TypeOut>
std::string operator()(cudf::size_type i, TypeOut lhs, TypeOut rhs) const
{
std::stringstream out_str;
out_str << "[" << i << "]:\n";
if constexpr (cudf::is_fixed_point<TypeOut>()) {
out_str << "lhs: " << std::string(lhs) << "\nrhs: " << std::string(rhs);
} else if constexpr (cudf::is_timestamp<TypeOut>()) {
out_str << "lhs: " << lhs.time_since_epoch().count()
<< "\nrhs: " << rhs.time_since_epoch().count();
} else if constexpr (cudf::is_duration<TypeOut>()) {
out_str << "lhs: " << lhs.count() << "\nrhs: " << rhs.count();
} else {
out_str << "lhs: " << lhs << "\nrhs: " << rhs;
}
return out_str.str();
}
};
// This comparator can be used to compare two values that are within a max ULP error.
// This is typically used to compare floating point values computed on CPU and GPU which is
// expected to be *near* equal, or when computing large numbers can yield ULP errors
//
// TODO: This should not be used in favor of the built-in one in column_utilities
template <typename TypeOut>
struct NearEqualComparator {
double ulp_;
NearEqualComparator(double ulp) : ulp_(ulp) {}
bool operator()(TypeOut const& lhs, TypeOut const& rhs) const
{
return (std::fabs(lhs - rhs) <=
std::numeric_limits<TypeOut>::epsilon() * std::fabs(lhs + rhs) * ulp_ ||
std::fabs(lhs - rhs) < std::numeric_limits<TypeOut>::min());
}
};
template <typename TypeOut,
typename TypeLhs,
typename TypeRhs,
typename TypeOp,
typename ValueComparator = std::equal_to<TypeOut>,
typename ScalarType = cudf::scalar_type_t<TypeLhs>>
void ASSERT_BINOP(cudf::column_view const& out,
cudf::scalar const& lhs,
cudf::column_view const& rhs,
TypeOp&& op,
ValueComparator const& value_comparator = ValueComparator())
{
auto lhs_h = static_cast<ScalarType const&>(lhs).operator TypeLhs();
auto rhs_h = cudf::test::to_host<TypeRhs>(rhs);
auto rhs_data = rhs_h.first;
auto out_h = cudf::test::to_host<TypeOut>(out);
auto out_data = out_h.first;
ASSERT_EQ(out_data.size(), rhs_data.size());
for (size_t i = 0; i < out_data.size(); ++i) {
auto lhs = out_data[i];
auto rhs = (TypeOut)(op(lhs_h, rhs_data[i]));
// TODO: This is incorrectly comparing row values that may be null
EXPECT_TRUE(value_comparator(lhs, rhs)) << stringify_out_values{}(i, lhs, rhs);
}
if (rhs.nullable()) {
EXPECT_TRUE(out.nullable());
auto rhs_valid = rhs_h.second;
auto out_valid = out_h.second;
uint32_t lhs_valid = (lhs.is_valid() ? std::numeric_limits<cudf::bitmask_type>::max() : 0);
ASSERT_EQ(out_valid.size(), rhs_valid.size());
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], (lhs_valid & rhs_valid[i]));
}
} else {
if (lhs.is_valid()) {
EXPECT_FALSE(out.nullable());
} else {
auto out_valid = out_h.second;
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], cudf::bitmask_type{0});
}
}
}
}
template <typename TypeOut,
typename TypeLhs,
typename TypeRhs,
typename TypeOp,
typename ValueComparator = std::equal_to<TypeOut>,
typename ScalarType = cudf::scalar_type_t<TypeRhs>>
void ASSERT_BINOP(cudf::column_view const& out,
cudf::column_view const& lhs,
cudf::scalar const& rhs,
TypeOp&& op,
ValueComparator const& value_comparator = ValueComparator())
{
auto rhs_h = static_cast<ScalarType const&>(rhs).operator TypeRhs();
auto lhs_h = cudf::test::to_host<TypeLhs>(lhs);
auto lhs_data = lhs_h.first;
auto out_h = cudf::test::to_host<TypeOut>(out);
auto out_data = out_h.first;
ASSERT_EQ(out_data.size(), lhs_data.size());
for (size_t i = 0; i < out_data.size(); ++i) {
auto lhs = out_data[i];
auto rhs = (TypeOut)(op(lhs_data[i], rhs_h));
// TODO: This is incorrectly comparing row values that may be null
EXPECT_TRUE(value_comparator(lhs, rhs)) << stringify_out_values{}(i, lhs, rhs);
}
if (lhs.nullable()) {
EXPECT_TRUE(out.nullable());
auto lhs_valid = lhs_h.second;
auto out_valid = out_h.second;
uint32_t rhs_valid = (rhs.is_valid() ? std::numeric_limits<cudf::bitmask_type>::max() : 0);
ASSERT_EQ(out_valid.size(), lhs_valid.size());
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], (rhs_valid & lhs_valid[i]));
}
} else {
if (rhs.is_valid()) {
EXPECT_FALSE(out.nullable());
} else {
auto out_valid = out_h.second;
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], cudf::bitmask_type{0});
}
}
}
}
template <typename TypeOut,
typename TypeLhs,
typename TypeRhs,
typename TypeOp,
typename ValueComparator = std::equal_to<TypeOut>>
void ASSERT_BINOP(cudf::column_view const& out,
cudf::column_view const& lhs,
cudf::column_view const& rhs,
TypeOp&& op,
ValueComparator const& value_comparator = ValueComparator())
{
auto lhs_h = cudf::test::to_host<TypeLhs>(lhs);
auto lhs_data = lhs_h.first;
auto rhs_h = cudf::test::to_host<TypeRhs>(rhs);
auto rhs_data = rhs_h.first;
auto out_h = cudf::test::to_host<TypeOut>(out);
auto out_data = out_h.first;
ASSERT_EQ(out_data.size(), lhs_data.size());
ASSERT_EQ(out_data.size(), rhs_data.size());
for (size_t i = 0; i < out_data.size(); ++i) {
auto lhs = out_data[i];
auto rhs = (TypeOut)(op(lhs_data[i], rhs_data[i]));
// TODO: This is incorrectly comparing row values that may be null
EXPECT_TRUE(value_comparator(lhs, rhs)) << stringify_out_values{}(i, lhs, rhs);
}
if (lhs.nullable() and rhs.nullable()) {
EXPECT_TRUE(out.nullable());
auto lhs_valid = lhs_h.second;
auto rhs_valid = rhs_h.second;
auto out_valid = out_h.second;
ASSERT_EQ(out_valid.size(), lhs_valid.size());
ASSERT_EQ(out_valid.size(), rhs_valid.size());
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], (lhs_valid[i] & rhs_valid[i]));
}
} else if (not lhs.nullable() and rhs.nullable()) {
EXPECT_TRUE(out.nullable());
auto rhs_valid = rhs_h.second;
auto out_valid = out_h.second;
ASSERT_EQ(out_valid.size(), rhs_valid.size());
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], rhs_valid[i]);
}
} else if (lhs.nullable() and not rhs.nullable()) {
EXPECT_TRUE(out.nullable());
auto lhs_valid = lhs_h.second;
auto out_valid = out_h.second;
ASSERT_EQ(out_valid.size(), lhs_valid.size());
for (cudf::size_type i = 0; i < cudf::num_bitmask_words(out_data.size()); ++i) {
EXPECT_EQ(out_valid[i], lhs_valid[i]);
}
} else {
EXPECT_FALSE(out.nullable());
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/binaryop
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/util/runtime_support.h
|
/*
* Copyright (c) 2021, 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 <cuda_runtime.h>
inline bool can_do_runtime_jit()
{
// We require a CUDA NVRTC of 11.5+ to do runtime jit
// as we need support for __int128
int runtime = 0;
auto error_value = cudaRuntimeGetVersion(&runtime);
return (error_value == cudaSuccess) && (runtime >= 11050);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests/binaryop
|
rapidsai_public_repos/cudf/cpp/tests/binaryop/util/operation.h
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Copyright 2018-2019 BlazingDB, Inc.
* Copyright 2018 Christian Noboa Mardini <[email protected]>
*
* 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 <cmath>
#include <cstdint>
#include <cudf/utilities/traits.hpp>
#include <type_traits>
namespace cudf {
namespace library {
namespace operation {
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Add {
// Allow sum between chronos only when both input and output types
// are chronos. Unsupported combinations will fail to compile
template <typename OutT = TypeOut,
std::enable_if_t<cudf::is_chrono<OutT>() && cudf::is_chrono<TypeLhs>() &&
cudf::is_chrono<TypeRhs>(),
void>* = nullptr>
OutT operator()(TypeLhs lhs, TypeRhs rhs) const
{
return lhs + rhs;
}
template <typename OutT = TypeOut,
std::enable_if_t<!cudf::is_chrono<OutT>() || !cudf::is_chrono<TypeLhs>() ||
!cudf::is_chrono<TypeRhs>(),
void>* = nullptr>
OutT operator()(TypeLhs lhs, TypeRhs rhs) const
{
using TypeCommon = typename std::common_type<OutT, TypeLhs, TypeRhs>::type;
return static_cast<OutT>(static_cast<TypeCommon>(lhs) + static_cast<TypeCommon>(rhs));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Sub {
// Allow difference between chronos only when both input and output types
// are chronos. Unsupported combinations will fail to compile
template <typename OutT = TypeOut,
std::enable_if_t<cudf::is_chrono<OutT>() && cudf::is_chrono<TypeLhs>() &&
cudf::is_chrono<TypeRhs>(),
void>* = nullptr>
OutT operator()(TypeLhs lhs, TypeRhs rhs) const
{
return lhs - rhs;
}
template <typename OutT = TypeOut,
std::enable_if_t<!cudf::is_chrono<OutT>() || !cudf::is_chrono<TypeLhs>() ||
!cudf::is_chrono<TypeRhs>(),
void>* = nullptr>
OutT operator()(TypeLhs lhs, TypeRhs rhs) const
{
using TypeCommon = typename std::common_type<OutT, TypeLhs, TypeRhs>::type;
return static_cast<OutT>(static_cast<TypeCommon>(lhs) - static_cast<TypeCommon>(rhs));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Mul {
template <typename OutT = TypeOut,
std::enable_if_t<!cudf::is_duration_t<OutT>::value, void>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) const
{
using TypeCommon = typename std::common_type<TypeOut, TypeLhs, TypeRhs>::type;
return static_cast<TypeOut>(static_cast<TypeCommon>(lhs) * static_cast<TypeCommon>(rhs));
}
template <typename OutT = TypeOut,
std::enable_if_t<cudf::is_duration_t<OutT>::value, void>* = nullptr>
TypeOut operator()(TypeLhs x, TypeRhs y) const
{
return DurationProduct<TypeOut>(x, y);
}
template <typename OutT,
typename LhsT,
typename RhsT,
std::enable_if_t<(cudf::is_duration_t<LhsT>::value && std::is_integral_v<RhsT>) ||
(cudf::is_duration_t<RhsT>::value && std::is_integral_v<LhsT>),
void>* = nullptr>
OutT DurationProduct(LhsT x, RhsT y) const
{
return x * y;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Div {
template <typename LhsT = TypeLhs,
std::enable_if_t<!cudf::is_duration_t<LhsT>::value, void>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
using TypeCommon = typename std::common_type<TypeOut, TypeLhs, TypeRhs>::type;
return static_cast<TypeOut>(static_cast<TypeCommon>(lhs) / static_cast<TypeCommon>(rhs));
}
template <typename LhsT = TypeLhs,
std::enable_if_t<cudf::is_duration_t<LhsT>::value, void>* = nullptr>
TypeOut operator()(TypeLhs x, TypeRhs y) const
{
return DurationDivide<TypeOut>(x, y);
}
template <
typename OutT,
typename LhsT,
typename RhsT,
std::enable_if_t<(std::is_integral_v<RhsT> || cudf::is_duration<RhsT>()), void>* = nullptr>
OutT DurationDivide(LhsT x, RhsT y) const
{
return x / y;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct TrueDiv {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(static_cast<double>(lhs) / static_cast<double>(rhs));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct FloorDiv {
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(std::is_integral_v<std::common_type_t<LhsT, RhsT>> and
std::is_signed_v<std::common_type_t<LhsT, RhsT>>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
if ((lhs ^ rhs) >= 0) {
return lhs / rhs;
} else {
auto const quotient = lhs / rhs;
auto const remainder = lhs % rhs;
return quotient - !!remainder;
}
}
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(std::is_integral_v<std::common_type_t<LhsT, RhsT>> and
!std::is_signed_v<std::common_type_t<LhsT, RhsT>>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return lhs / rhs;
}
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(std::is_same_v<std::common_type_t<LhsT, RhsT>, float>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(std::floor(lhs / rhs));
}
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(std::is_same_v<std::common_type_t<LhsT, RhsT>, double>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(std::floor(lhs / rhs));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Mod {
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<
(std::is_integral_v<typename std::common_type<OutT, LhsT, RhsT>::type>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
using TypeCommon = typename std::common_type<TypeOut, TypeLhs, TypeRhs>::type;
return static_cast<TypeOut>(static_cast<TypeCommon>(lhs) % static_cast<TypeCommon>(rhs));
}
template <typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(
std::is_same_v<typename std::common_type<OutT, LhsT, RhsT>::type, float>)>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(fmod(static_cast<float>(lhs), static_cast<float>(rhs)));
}
template <
typename OutT = TypeOut,
typename LhsT = TypeLhs,
typename RhsT = TypeRhs,
std::enable_if_t<(std::is_same_v<typename std::common_type<OutT, LhsT, RhsT>::type, double>)>* =
nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(fmod(static_cast<double>(lhs), static_cast<double>(rhs)));
}
// Mod with duration types - duration % (integral or a duration) = duration
template <typename LhsT = TypeLhs,
typename OutT = TypeOut,
std::enable_if_t<cudf::is_duration_t<LhsT>::value &&
cudf::is_duration_t<OutT>::value>* = nullptr>
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return lhs % rhs;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Pow {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(pow(static_cast<double>(lhs), static_cast<double>(rhs)));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Equal {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x == y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NotEqual {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x != y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Less {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x < y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct Greater {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x > y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct LessEqual {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x <= y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct GreaterEqual {
TypeOut operator()(TypeLhs x, TypeRhs y) { return (x >= y); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct BitwiseAnd {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return (lhs & rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct BitwiseOr {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return (lhs | rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct BitwiseXor {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return (lhs ^ rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct LogicalAnd {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return static_cast<TypeOut>(lhs && rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct LogicalOr {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return static_cast<TypeOut>(lhs || rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct ShiftLeft {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return static_cast<TypeOut>(lhs << rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct ShiftRight {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs) { return static_cast<TypeOut>(lhs >> rhs); }
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct ShiftRightUnsigned {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(static_cast<std::make_unsigned_t<TypeLhs>>(lhs) >> rhs);
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct LogBase {
TypeOut operator()(TypeLhs lhs, TypeRhs rhs)
{
return static_cast<TypeOut>(std::log(static_cast<double>(lhs)) /
std::log(static_cast<double>(rhs)));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct PMod {
using CommonArgsT = typename std::common_type<TypeLhs, TypeRhs>::type;
TypeOut operator()(TypeLhs x, TypeRhs y) const
{
CommonArgsT xconv{static_cast<CommonArgsT>(x)};
CommonArgsT yconv{static_cast<CommonArgsT>(y)};
auto rem = std::fmod(xconv, yconv);
if (rem < 0) rem = std::fmod(rem + yconv, yconv);
return static_cast<TypeOut>(rem);
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct ATan2 {
TypeOut operator()(TypeLhs x, TypeRhs y) const
{
return static_cast<TypeOut>(std::atan2(static_cast<double>(x), static_cast<double>(y)));
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct PyMod {
TypeOut operator()(TypeLhs x, TypeRhs y) const
{
if constexpr (std::is_floating_point_v<TypeLhs> or std::is_floating_point_v<TypeRhs>) {
double x1 = static_cast<double>(x);
double y1 = static_cast<double>(y);
return fmod(fmod(x1, y1) + y1, y1);
} else {
return ((x % y) + y) % y;
}
return {};
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NullLogicalAnd {
TypeOut operator()(TypeLhs x, TypeRhs y, bool lhs_valid, bool rhs_valid, bool& output_valid) const
{
if (lhs_valid && !x) {
output_valid = true;
return false;
}
if (rhs_valid && !y) {
output_valid = true;
return false;
}
if (lhs_valid && rhs_valid) {
output_valid = true;
return true;
}
output_valid = false;
return false;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NullLogicalOr {
TypeOut operator()(TypeLhs x, TypeRhs y, bool lhs_valid, bool rhs_valid, bool& output_valid) const
{
if (lhs_valid && x) {
output_valid = true;
return true;
}
if (rhs_valid && y) {
output_valid = true;
return true;
}
if (lhs_valid && rhs_valid) {
output_valid = true;
return false;
}
output_valid = false;
return false;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NullEquals {
TypeOut operator()(TypeLhs x, TypeRhs y, bool lhs_valid, bool rhs_valid, bool& output_valid) const
{
output_valid = true;
if (!lhs_valid && !rhs_valid) return true;
using common_t = std::common_type_t<TypeLhs, TypeRhs>;
if (lhs_valid && rhs_valid) return static_cast<common_t>(x) == static_cast<common_t>(y);
return false;
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NullMax {
TypeOut operator()(TypeLhs x, TypeRhs y, bool lhs_valid, bool rhs_valid, bool& output_valid) const
{
output_valid = lhs_valid or rhs_valid;
if (lhs_valid or rhs_valid) {
return (lhs_valid and (!rhs_valid or static_cast<TypeOut>(x) > static_cast<TypeOut>(y)))
? static_cast<TypeOut>(x)
: static_cast<TypeOut>(y);
} else
return TypeOut{};
}
};
template <typename TypeOut, typename TypeLhs, typename TypeRhs>
struct NullMin {
TypeOut operator()(TypeLhs x, TypeRhs y, bool lhs_valid, bool rhs_valid, bool& output_valid) const
{
output_valid = lhs_valid or rhs_valid;
if (lhs_valid or rhs_valid) {
return (lhs_valid and (!rhs_valid or static_cast<TypeOut>(x) < static_cast<TypeOut>(y)))
? static_cast<TypeOut>(x)
: static_cast<TypeOut>(y);
} else
return TypeOut{};
}
};
} // namespace operation
} // namespace library
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/fill_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/filling.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionaryFillTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryFillTest, StringsColumn)
{
cudf::test::strings_column_wrapper strings(
{"fff", "aaa", "", "bbb", "ccc", "ccc", "ccc", "fff", "aaa", ""});
auto dictionary = cudf::dictionary::encode(strings);
cudf::string_scalar fv("___");
auto results = cudf::fill(dictionary->view(), 1, 4, fv);
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::strings_column_wrapper expected(
{"fff", "___", "___", "___", "ccc", "ccc", "ccc", "fff", "aaa", ""});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
TEST_F(DictionaryFillTest, WithNulls)
{
cudf::test::fixed_width_column_wrapper<int64_t> input({9, 8, 7, 6, 4}, {0, 1, 1, 0, 1});
auto dictionary = cudf::dictionary::encode(input);
cudf::numeric_scalar<int64_t> fv(-10);
auto results = cudf::fill(dictionary->view(), 0, 2, fv);
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<int64_t> expected({-10, -10, 7, 6, 4}, {1, 1, 1, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
TEST_F(DictionaryFillTest, FillWithNull)
{
cudf::test::fixed_width_column_wrapper<double> input({1.2, 8.5, 7.75, 6.25, 4.125},
{1, 1, 1, 0, 1});
auto dictionary = cudf::dictionary::encode(input);
cudf::numeric_scalar<double> fv(0, false);
auto results = cudf::fill(dictionary->view(), 1, 3, fv);
auto decoded = cudf::dictionary::decode(results->view());
cudf::test::fixed_width_column_wrapper<double> expected({1.2, 0.0, 0.0, 0.0, 4.125},
{1, 0, 0, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
TEST_F(DictionaryFillTest, Empty)
{
auto dictionary = cudf::make_empty_column(cudf::data_type{cudf::type_id::DICTIONARY32});
cudf::numeric_scalar<int64_t> fv(-10);
auto results = cudf::fill(dictionary->view(), 0, 0, fv);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), dictionary->view());
}
TEST_F(DictionaryFillTest, Errors)
{
cudf::test::strings_column_wrapper input{"this string intentionally left blank"};
auto dictionary = cudf::dictionary::encode(input);
cudf::numeric_scalar<int64_t> fv(-10); // mismatched key
EXPECT_THROW(cudf::fill(dictionary->view(), 1, 2, fv), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/encode_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_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionaryEncodeTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryEncodeTest, EncodeStringColumn)
{
cudf::test::strings_column_wrapper strings(
{"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"});
auto dictionary = cudf::dictionary::encode(strings);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::strings_column_wrapper keys_expected({"aaa", "bbb", "ccc", "ddd", "eee"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
cudf::test::fixed_width_column_wrapper<uint32_t> indices_expected({4, 0, 3, 1, 2, 2, 2, 4, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), indices_expected);
}
TEST_F(DictionaryEncodeTest, EncodeFloat)
{
cudf::test::fixed_width_column_wrapper<float> input{4.25, 7.125, 0.5, -11.75, 7.125, 0.5};
auto dictionary = cudf::dictionary::encode(input);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::fixed_width_column_wrapper<float> keys_expected{-11.75, 0.5, 4.25, 7.125};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
cudf::test::fixed_width_column_wrapper<uint32_t> expected{2, 3, 1, 0, 3, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), expected);
}
TEST_F(DictionaryEncodeTest, EncodeWithNull)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{{444, 0, 333, 111, 222, 222, 222, 444, 000},
{1, 1, 1, 1, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(input);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::fixed_width_column_wrapper<int64_t> keys_expected{0, 111, 222, 333, 444};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
cudf::test::fixed_width_column_wrapper<uint32_t> expected{4, 0, 3, 1, 2, 5, 2, 4, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), expected);
}
TEST_F(DictionaryEncodeTest, InvalidEncode)
{
cudf::test::fixed_width_column_wrapper<int16_t> input{0, 1, 2, 3, -1, -2, -3};
EXPECT_THROW(cudf::dictionary::encode(input, cudf::data_type{cudf::type_id::INT16}),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/set_keys_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/dictionary/update_keys.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 DictionarySetKeysTest : public cudf::test::BaseFixture {};
TEST_F(DictionarySetKeysTest, StringsKeys)
{
cudf::test::strings_column_wrapper strings{
"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
auto dictionary = cudf::dictionary::encode(strings);
cudf::test::strings_column_wrapper new_keys{"aaa", "ccc", "eee", "fff"};
auto result = cudf::dictionary::set_keys(dictionary->view(), new_keys);
std::vector<char const*> h_expected{
"eee", "aaa", nullptr, nullptr, "ccc", "ccc", "ccc", "eee", "aaa"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto decoded = cudf::dictionary::decode(result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected);
}
TEST_F(DictionarySetKeysTest, FloatKeys)
{
cudf::test::fixed_width_column_wrapper<float> input{4.25, 7.125, 0.5, -11.75, 7.125, 0.5};
auto dictionary = cudf::dictionary::encode(input);
cudf::test::fixed_width_column_wrapper<float> new_keys{0.5, 1.0, 4.25, 7.125};
auto result = cudf::dictionary::set_keys(dictionary->view(), new_keys);
cudf::test::fixed_width_column_wrapper<float> expected{{4.25, 7.125, 0.5, 0., 7.125, 0.5},
{1, 1, 1, 0, 1, 1}};
auto decoded = cudf::dictionary::decode(result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected);
}
TEST_F(DictionarySetKeysTest, WithNulls)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{{444, 0, 333, 111, 222, 222, 222, 444, 0},
{1, 1, 1, 1, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(input);
cudf::test::fixed_width_column_wrapper<int64_t> new_keys{0, 222, 333, 444};
auto result = cudf::dictionary::set_keys(dictionary->view(), new_keys);
cudf::test::fixed_width_column_wrapper<int64_t> expected{
{444, 0, 333, 111, 222, 222, 222, 444, 0}, {1, 1, 1, 0, 1, 0, 1, 1, 1}};
auto decoded = cudf::dictionary::decode(result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected);
}
TEST_F(DictionarySetKeysTest, Errors)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{1, 2, 3};
auto dictionary = cudf::dictionary::encode(input);
cudf::test::fixed_width_column_wrapper<float> new_keys{1.0, 2.0, 3.0};
EXPECT_THROW(cudf::dictionary::set_keys(dictionary->view(), new_keys), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> null_keys{{1, 2, 3}, {1, 0, 1}};
EXPECT_THROW(cudf::dictionary::set_keys(dictionary->view(), null_keys), cudf::logic_error);
}
TEST_F(DictionarySetKeysTest, MatchDictionaries)
{
cudf::test::dictionary_column_wrapper<int32_t> col1{5, 0, 4, 1, 2, 2, 2, 5, 0};
cudf::test::dictionary_column_wrapper<int32_t> col2{1, 0, 3, 1, 4, 5, 6, 5, 0};
auto input = std::vector<cudf::dictionary_column_view>(
{cudf::dictionary_column_view(col1), cudf::dictionary_column_view(col2)});
auto results = cudf::dictionary::match_dictionaries(input);
auto keys1 = cudf::dictionary_column_view(results[0]->view()).keys();
auto keys2 = cudf::dictionary_column_view(results[1]->view()).keys();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(keys1, keys2);
auto result1 = cudf::dictionary::decode(cudf::dictionary_column_view(results[0]->view()));
auto result2 = cudf::dictionary::decode(cudf::dictionary_column_view(results[1]->view()));
auto expected1 = cudf::dictionary::decode(cudf::dictionary_column_view(col1));
auto expected2 = cudf::dictionary::decode(cudf::dictionary_column_view(col2));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result1->view(), expected1->view());
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result2->view(), expected2->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/add_keys_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/dictionary/update_keys.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionaryAddKeysTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryAddKeysTest, StringsColumn)
{
cudf::test::strings_column_wrapper strings(
{"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "fff", "aaa"});
cudf::test::strings_column_wrapper new_keys({"ddd", "bbb", "eee"});
auto dictionary = cudf::dictionary::encode(strings);
auto result =
cudf::dictionary::add_keys(cudf::dictionary_column_view(dictionary->view()), new_keys);
cudf::dictionary_column_view view(result->view());
cudf::test::strings_column_wrapper keys_expected({"aaa", "bbb", "ccc", "ddd", "eee", "fff"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
cudf::test::fixed_width_column_wrapper<uint8_t> indices_expected({5, 0, 3, 1, 2, 2, 2, 5, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), indices_expected);
}
TEST_F(DictionaryAddKeysTest, FloatColumn)
{
cudf::test::fixed_width_column_wrapper<float> input{4.25, 7.125, 0.5, -11.75, 7.125, 0.5};
cudf::test::fixed_width_column_wrapper<float> new_keys{4.25, -11.75, 5.0};
auto dictionary = cudf::dictionary::encode(input);
auto result =
cudf::dictionary::add_keys(cudf::dictionary_column_view(dictionary->view()), new_keys);
cudf::dictionary_column_view view(result->view());
cudf::test::fixed_width_column_wrapper<float> keys_expected{-11.75, 0.5, 4.25, 5.0, 7.125};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
cudf::test::fixed_width_column_wrapper<uint8_t> expected{2, 4, 1, 0, 4, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), expected);
}
TEST_F(DictionaryAddKeysTest, WithNull)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{{555, 0, 333, 111, 222, 222, 222, 555, 0},
{1, 1, 1, 0, 1, 1, 1, 1, 1}};
cudf::test::fixed_width_column_wrapper<int64_t> new_keys{0, 111, 444, 777};
auto dictionary = cudf::dictionary::encode(input);
auto result =
cudf::dictionary::add_keys(cudf::dictionary_column_view(dictionary->view()), new_keys);
auto decoded = cudf::dictionary::decode(result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), input); // new keys should not change anything
}
TEST_F(DictionaryAddKeysTest, Errors)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{1, 2, 3};
auto dictionary = cudf::dictionary::encode(input);
cudf::test::fixed_width_column_wrapper<float> new_keys{1.0, 2.0, 3.0};
EXPECT_THROW(cudf::dictionary::add_keys(dictionary->view(), new_keys), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> null_keys{{1, 2, 3}, {1, 0, 1}};
EXPECT_THROW(cudf::dictionary::add_keys(dictionary->view(), null_keys), cudf::logic_error);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/slice_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/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.hpp>
#include <cudf/dictionary/update_keys.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionarySliceTest : public cudf::test::BaseFixture {};
TEST_F(DictionarySliceTest, SliceColumn)
{
cudf::test::strings_column_wrapper strings{
{"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"}, {1, 1, 1, 1, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(strings);
std::vector<cudf::size_type> splits{1, 6};
auto result = cudf::slice(dictionary->view(), splits);
auto output = cudf::dictionary::decode(cudf::dictionary_column_view(result.front()));
cudf::test::strings_column_wrapper expected{{"aaa", "ddd", "bbb", "ccc", ""}, {1, 1, 1, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output);
{
auto defragged =
cudf::dictionary::remove_unused_keys(cudf::dictionary_column_view(result.front()));
output = cudf::dictionary::decode(cudf::dictionary_column_view(*defragged));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output); // should be the same output
}
{
cudf::test::strings_column_wrapper new_keys{"000", "bbb"};
auto added = cudf::dictionary::add_keys(cudf::dictionary_column_view(result.front()), new_keys);
output = cudf::dictionary::decode(cudf::dictionary_column_view(*added));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output);
}
{
cudf::test::strings_column_wrapper new_keys{"aaa", "bbb", "ccc", "ddd", "000"};
auto added = cudf::dictionary::set_keys(cudf::dictionary_column_view(result.front()), new_keys);
output = cudf::dictionary::decode(cudf::dictionary_column_view(*added));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output);
}
{
// check new column is created correctly from sliced view (issue 5768)
cudf::column new_col(result.front());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.front(), new_col.view());
}
}
TEST_F(DictionarySliceTest, SplitColumn)
{
cudf::test::fixed_width_column_wrapper<float> input{{4.25, 7.125, 0.5, 0., -11.75, 7.125, 0.5},
{1, 1, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(input);
std::vector<cudf::size_type> splits{2, 6};
auto results = cudf::split(dictionary->view(), splits);
cudf::test::fixed_width_column_wrapper<float> expected1{{4.25, 7.125}, {1, 1}};
auto output1 = cudf::dictionary::decode(cudf::dictionary_column_view(results[0]));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, output1->view());
cudf::test::fixed_width_column_wrapper<float> expected2{{0.5, 0., -11.75, 7.125}, {1, 0, 1, 1}};
auto output2 = cudf::dictionary::decode(cudf::dictionary_column_view(results[1]));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, output2->view());
cudf::test::fixed_width_column_wrapper<float> expected3({0.5}, {1});
auto output3 = cudf::dictionary::decode(cudf::dictionary_column_view(results[2]));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, output3->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/factories_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/dictionary_factories.hpp>
#include <cudf/null_mask.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>
struct DictionaryFactoriesTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryFactoriesTest, CreateFromColumnViews)
{
cudf::test::strings_column_wrapper keys({"aaa", "ccc", "ddd", "www"});
cudf::test::fixed_width_column_wrapper<uint32_t> values{2, 0, 3, 1, 2, 2, 2, 3, 0};
auto dictionary = cudf::make_dictionary_column(keys, values);
cudf::dictionary_column_view view(dictionary->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), values);
}
TEST_F(DictionaryFactoriesTest, ColumnViewsWithNulls)
{
cudf::test::fixed_width_column_wrapper<float> keys{-11.75, 4.25, 7.125, 0.5, 12.0};
std::vector<uint32_t> h_values{1, 3, 2, 0, 1, 4, 1};
cudf::test::fixed_width_column_wrapper<uint32_t> indices(
h_values.begin(), h_values.end(), thrust::make_transform_iterator(h_values.begin(), [](auto v) {
return v > 0;
}));
auto dictionary = cudf::make_dictionary_column(keys, indices);
cudf::dictionary_column_view view(dictionary->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys);
cudf::test::fixed_width_column_wrapper<uint32_t> values_expected(h_values.begin(),
h_values.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), values_expected);
}
TEST_F(DictionaryFactoriesTest, CreateFromColumns)
{
std::vector<std::string> h_keys{"pear", "apple", "fruit", "macintosh"};
cudf::test::strings_column_wrapper keys(h_keys.begin(), h_keys.end());
std::vector<uint32_t> h_values{1, 2, 3, 1, 2, 3, 0};
cudf::test::fixed_width_column_wrapper<uint32_t> values(h_values.begin(), h_values.end());
auto dictionary =
cudf::make_dictionary_column(keys.release(), values.release(), rmm::device_buffer{}, 0);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::strings_column_wrapper keys_expected(h_keys.begin(), h_keys.end());
cudf::test::fixed_width_column_wrapper<uint32_t> values_expected(h_values.begin(),
h_values.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), values_expected);
}
TEST_F(DictionaryFactoriesTest, ColumnsWithNulls)
{
std::vector<int64_t> h_keys{-1234567890, -987654321, 0, 19283714};
cudf::test::fixed_width_column_wrapper<int64_t> keys(h_keys.begin(), h_keys.end());
std::vector<uint32_t> h_values{1, 2, 3, 1, 2, 3, 0};
cudf::test::fixed_width_column_wrapper<uint32_t> values(h_values.begin(), h_values.end());
auto size = static_cast<cudf::size_type>(h_values.size());
rmm::device_buffer null_mask = create_null_mask(size, cudf::mask_state::ALL_NULL);
auto dictionary =
cudf::make_dictionary_column(keys.release(), values.release(), std::move(null_mask), size);
cudf::dictionary_column_view view(dictionary->view());
EXPECT_EQ(size, view.size());
EXPECT_EQ(size, view.null_count());
cudf::test::fixed_width_column_wrapper<int64_t> keys_expected(h_keys.begin(), h_keys.end());
cudf::test::fixed_width_column_wrapper<uint32_t> values_expected(h_values.begin(),
h_values.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.keys(), keys_expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view.indices(), values_expected);
}
TEST_F(DictionaryFactoriesTest, KeysWithNulls)
{
cudf::test::fixed_width_column_wrapper<int32_t> keys{{0, 1, 2, 3, 4}, {1, 1, 1, 0, 1}};
cudf::test::fixed_width_column_wrapper<uint32_t> indices{5, 4, 3, 2, 1, 0};
EXPECT_THROW(cudf::make_dictionary_column(keys, indices), cudf::logic_error);
}
TEST_F(DictionaryFactoriesTest, IndicesWithNulls)
{
cudf::test::fixed_width_column_wrapper<int32_t> keys{0, 1, 2, 3, 4};
cudf::test::fixed_width_column_wrapper<uint32_t> indices{{5, 4, 3, 2, 1, 0}, {1, 1, 1, 0, 1, 0}};
EXPECT_THROW(
cudf::make_dictionary_column(keys.release(), indices.release(), rmm::device_buffer{}, 0),
cudf::logic_error);
}
TEST_F(DictionaryFactoriesTest, InvalidIndices)
{
cudf::test::fixed_width_column_wrapper<int32_t> keys{0, 1, 2, 3, 4};
cudf::test::fixed_width_column_wrapper<int16_t> indices{5, 4, 3, 2, 1, 0};
EXPECT_THROW(cudf::make_dictionary_column(keys, indices), cudf::logic_error);
EXPECT_THROW(
cudf::make_dictionary_column(keys.release(), indices.release(), rmm::device_buffer{}, 0),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/remove_keys_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/copying.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.hpp>
#include <cudf/dictionary/update_keys.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 DictionaryRemoveKeysTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryRemoveKeysTest, StringsColumn)
{
cudf::test::strings_column_wrapper strings{
"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
cudf::test::strings_column_wrapper del_keys{"ddd", "bbb", "fff"};
auto const dictionary = cudf::dictionary::encode(strings);
// remove keys
{
auto const result =
cudf::dictionary::remove_keys(cudf::dictionary_column_view(dictionary->view()), del_keys);
std::vector<char const*> h_expected{
"eee", "aaa", nullptr, nullptr, "ccc", "ccc", "ccc", "eee", "aaa"};
cudf::test::strings_column_wrapper expected(
h_expected.begin(),
h_expected.end(),
thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; }));
auto const decoded = cudf::dictionary::decode(result->view());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
// remove_unused_keys
{
cudf::test::fixed_width_column_wrapper<int32_t> gather_map{0, 4, 3, 1};
auto const table_result =
cudf::gather(cudf::table_view{{dictionary->view()}}, gather_map)->release();
auto const result = cudf::dictionary::remove_unused_keys(table_result.front()->view());
auto const decoded = cudf::dictionary::decode(result->view());
cudf::test::strings_column_wrapper expected{"eee", "ccc", "bbb", "aaa"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
}
TEST_F(DictionaryRemoveKeysTest, FloatColumn)
{
cudf::test::fixed_width_column_wrapper<float> input{4.25, 7.125, 0.5, -11.75, 7.125, 0.5};
cudf::test::fixed_width_column_wrapper<float> del_keys{4.25, -11.75, 5.0};
auto const dictionary = cudf::dictionary::encode(input);
{
auto const result =
cudf::dictionary::remove_keys(cudf::dictionary_column_view(dictionary->view()), del_keys);
auto const decoded = cudf::dictionary::decode(result->view());
cudf::test::fixed_width_column_wrapper<float> expected{{0., 7.125, 0.5, 0., 7.125, 0.5},
{0, 1, 1, 0, 1, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
{
cudf::test::fixed_width_column_wrapper<int32_t> gather_map{0, 2, 3, 1};
auto const table_result =
cudf::gather(cudf::table_view{{dictionary->view()}}, gather_map)->release();
auto const result = cudf::dictionary::remove_unused_keys(table_result.front()->view());
auto const decoded = cudf::dictionary::decode(result->view());
cudf::test::fixed_width_column_wrapper<float> expected{{4.25, 0.5, -11.75, 7.125}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
}
TEST_F(DictionaryRemoveKeysTest, WithNull)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{{444, 0, 333, 111, 222, 222, 222, 444, 0},
{1, 1, 1, 1, 1, 0, 1, 1, 1}};
cudf::test::fixed_width_column_wrapper<int64_t> del_keys{0, 111, 777};
auto const dictionary = cudf::dictionary::encode(input);
{
auto const result =
cudf::dictionary::remove_keys(cudf::dictionary_column_view(dictionary->view()), del_keys);
auto const decoded = cudf::dictionary::decode(result->view());
cudf::test::fixed_width_column_wrapper<int64_t> expected{{444, 0, 333, 0, 222, 0, 222, 444, 0},
{1, 0, 1, 0, 1, 0, 1, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
{
cudf::test::fixed_width_column_wrapper<int32_t> gather_map{0, 2, 3, 1};
auto const table_result =
cudf::gather(cudf::table_view{{dictionary->view()}}, gather_map)->release();
auto const result = cudf::dictionary::remove_unused_keys(table_result.front()->view());
auto const decoded = cudf::dictionary::decode(result->view());
cudf::test::fixed_width_column_wrapper<int64_t> expected{{444, 333, 111, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(decoded->view(), expected);
}
}
TEST_F(DictionaryRemoveKeysTest, Errors)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{1, 2, 3};
auto const dictionary = cudf::dictionary::encode(input);
cudf::test::fixed_width_column_wrapper<float> del_keys{1.0, 2.0, 3.0};
EXPECT_THROW(cudf::dictionary::remove_keys(dictionary->view(), del_keys), cudf::logic_error);
cudf::test::fixed_width_column_wrapper<int64_t> null_keys{{1, 2, 3}, {1, 0, 1}};
EXPECT_THROW(cudf::dictionary::remove_keys(dictionary->view(), null_keys), cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/decode_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_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionaryDecodeTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryDecodeTest, StringColumn)
{
std::vector<char const*> h_strings{"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto dictionary = cudf::dictionary::encode(strings);
auto output = cudf::dictionary::decode(cudf::dictionary_column_view(dictionary->view()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strings, *output);
}
TEST_F(DictionaryDecodeTest, FloatColumn)
{
cudf::test::fixed_width_column_wrapper<float> input{4.25, 7.125, 0.5, -11.75, 7.125, 0.5};
auto dictionary = cudf::dictionary::encode(input);
auto output = cudf::dictionary::decode(cudf::dictionary_column_view(dictionary->view()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *output);
}
TEST_F(DictionaryDecodeTest, ColumnWithNull)
{
cudf::test::fixed_width_column_wrapper<int64_t> input{{444, 0, 333, 111, 222, 222, 222, 444, 000},
{1, 1, 1, 1, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(input);
auto output = cudf::dictionary::decode(cudf::dictionary_column_view(dictionary->view()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *output);
}
TEST_F(DictionaryDecodeTest, EmptyColumn)
{
cudf::test::fixed_width_column_wrapper<int16_t> input;
auto dictionary = cudf::dictionary::encode(input);
auto output = cudf::dictionary::decode(cudf::dictionary_column_view(dictionary->view()));
// check empty
EXPECT_EQ(output->size(), 0);
EXPECT_EQ(output->type().id(), cudf::type_id::EMPTY);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/gather_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/copying.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.hpp>
#include <cudf/sorting.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <vector>
struct DictionaryGatherTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryGatherTest, Gather)
{
cudf::test::strings_column_wrapper strings{
"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
auto dictionary = cudf::dictionary::encode(strings);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::fixed_width_column_wrapper<int32_t> gather_map{0, 4, 3, 1};
auto table_result = cudf::gather(cudf::table_view{{view.parent()}}, gather_map)->release();
auto result = cudf::dictionary_column_view(table_result.front()->view());
cudf::test::strings_column_wrapper expected{"eee", "ccc", "bbb", "aaa"};
auto decoded = cudf::dictionary::decode(result);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(DictionaryGatherTest, GatherWithNulls)
{
cudf::test::fixed_width_column_wrapper<int64_t> data{{1, 5, 5, 3, 7, 1}, {0, 1, 0, 1, 1, 1}};
auto dictionary = cudf::dictionary::encode(data);
cudf::dictionary_column_view view(dictionary->view());
cudf::test::fixed_width_column_wrapper<int16_t> gather_map{{4, 1, 2, 4}};
auto table_result = cudf::gather(cudf::table_view{{dictionary->view()}}, gather_map);
auto result = cudf::dictionary_column_view(table_result->view().column(0));
cudf::test::fixed_width_column_wrapper<int64_t> expected{{7, 5, 5, 7}, {1, 1, 0, 1}};
auto result_decoded = cudf::dictionary::decode(result);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result_decoded->view());
}
TEST_F(DictionaryGatherTest, SortStrings)
{
std::vector<std::string> h_strings{"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end());
auto dictionary = cudf::dictionary::encode(strings);
cudf::dictionary_column_view view(dictionary->view());
auto result = cudf::sort(cudf::table_view{{dictionary->view()}},
std::vector<cudf::order>{cudf::order::ASCENDING})
->release();
std::sort(h_strings.begin(), h_strings.end());
auto result_decoded = cudf::dictionary::decode(result.front()->view());
cudf::test::strings_column_wrapper expected(h_strings.begin(), h_strings.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result_decoded->view());
}
TEST_F(DictionaryGatherTest, SortFloat)
{
std::vector<double> h_data{1.25, -5.75, 8.125, 1e9, 9.7};
cudf::test::fixed_width_column_wrapper<double> data(h_data.begin(), h_data.end());
auto dictionary = cudf::dictionary::encode(data);
cudf::dictionary_column_view view(dictionary->view());
auto result = cudf::sort(cudf::table_view{{dictionary->view()}},
std::vector<cudf::order>{cudf::order::ASCENDING})
->release();
std::sort(h_data.begin(), h_data.end());
auto result_decoded = cudf::dictionary::decode(result.front()->view());
cudf::test::fixed_width_column_wrapper<double> expected(h_data.begin(), h_data.end());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result_decoded->view());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/scatter_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/copying.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/encode.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 <vector>
struct DictionaryScatterTest : public cudf::test::BaseFixture {};
TEST_F(DictionaryScatterTest, Scatter)
{
cudf::test::strings_column_wrapper strings_source{"xxx", "bbb", "aaa", "ccc"};
auto source = cudf::dictionary::encode(strings_source);
cudf::test::strings_column_wrapper strings_target{
"eee", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "eee", "aaa"};
auto target = cudf::dictionary::encode(strings_target);
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map{0, 2, 3, 7};
auto table_result =
cudf::scatter(
cudf::table_view{{source->view()}}, scatter_map, cudf::table_view{{target->view()}})
->release();
auto decoded =
cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
cudf::test::strings_column_wrapper expected{
"xxx", "aaa", "bbb", "aaa", "ccc", "ccc", "ccc", "ccc", "aaa"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
// empty map test
cudf::test::fixed_width_column_wrapper<int32_t> empty_map{};
table_result =
cudf::scatter(cudf::table_view{{source->view()}}, empty_map, cudf::table_view{{target->view()}})
->release();
decoded = cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(strings_target, decoded->view());
// empty target test
cudf::test::strings_column_wrapper empty_target;
auto empty_dictionary = cudf::dictionary::encode(empty_target);
table_result = cudf::scatter(cudf::table_view{{empty_dictionary->view()}},
empty_map,
cudf::table_view{{empty_dictionary->view()}})
->release();
decoded = cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
EXPECT_EQ(0, decoded->size());
}
TEST_F(DictionaryScatterTest, ScatterScalar)
{
cudf::test::strings_column_wrapper strings_target{
"eee", "aaa", "ddd", "ccc", "ccc", "ccc", "eee", "aaa"};
auto target = cudf::dictionary::encode(strings_target);
std::vector<std::reference_wrapper<const cudf::scalar>> source;
const cudf::string_scalar source_scalar = cudf::string_scalar("bbb");
std::reference_wrapper<const cudf::string_scalar> slr_wrapper = std::ref(source_scalar);
source.emplace_back(slr_wrapper);
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map{0, 2, 3, 7};
auto table_result =
cudf::scatter(source, cudf::column_view{scatter_map}, cudf::table_view({target->view()}))
->release();
auto decoded =
cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
cudf::test::strings_column_wrapper expected{
"bbb", "aaa", "bbb", "bbb", "ccc", "ccc", "eee", "bbb"};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(DictionaryScatterTest, WithNulls)
{
cudf::test::fixed_width_column_wrapper<int64_t> data_source{{1, 5, 7, 9}, {0, 1, 1, 1}};
auto source = cudf::dictionary::encode(data_source);
cudf::test::fixed_width_column_wrapper<int64_t> data_target{{1, 5, 5, 3, 7, 1, 4, 2},
{0, 1, 0, 1, 1, 1, 1, 1}};
auto target = cudf::dictionary::encode(data_target);
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map{7, 2, 3, 1};
auto table_result =
cudf::scatter(
cudf::table_view{{source->view()}}, scatter_map, cudf::table_view{{target->view()}})
->release();
auto decoded =
cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
cudf::test::fixed_width_column_wrapper<int64_t> expected{{1, 9, 5, 7, 7, 1, 4, 1},
{0, 1, 1, 1, 1, 1, 1, 0}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(DictionaryScatterTest, ScalarWithNulls)
{
cudf::test::fixed_width_column_wrapper<int64_t> data_target{{1, 5, 5, 3, 7, 1, 4, 2},
{0, 1, 0, 1, 1, 1, 1, 1}};
auto target = cudf::dictionary::encode(data_target);
std::vector<std::reference_wrapper<const cudf::scalar>> source;
const cudf::numeric_scalar<int64_t> source_slr = cudf::test::make_type_param_scalar<int64_t>(100);
std::reference_wrapper<const cudf::numeric_scalar<int64_t>> slr_wrapper = std::ref(source_slr);
source.emplace_back(slr_wrapper);
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map{7, 2, 3, 1, -3};
auto table_result =
cudf::scatter(source, scatter_map, cudf::table_view{{target->view()}})->release();
auto decoded =
cudf::dictionary::decode(cudf::dictionary_column_view(table_result.front()->view()));
cudf::test::fixed_width_column_wrapper<int64_t> expected{{1, 100, 100, 100, 7, 100, 4, 100},
{0, 1, 1, 1, 1, 1, 1, 1}};
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, decoded->view());
}
TEST_F(DictionaryScatterTest, Error)
{
cudf::test::strings_column_wrapper strings_source{"this string intentionally left blank"};
auto source = cudf::dictionary::encode(strings_source);
cudf::test::fixed_width_column_wrapper<int64_t> integers_target({1, 2, 3});
auto target = cudf::dictionary::encode(integers_target);
cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({0});
EXPECT_THROW(
cudf::scatter(
cudf::table_view{{source->view()}}, scatter_map, cudf::table_view{{target->view()}}),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/dictionary/search_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/detail/search.hpp>
#include <cudf/dictionary/search.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
struct DictionarySearchTest : public cudf::test::BaseFixture {};
TEST_F(DictionarySearchTest, StringsColumn)
{
cudf::test::dictionary_column_wrapper<std::string> dictionary(
{"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "", ""}, {1, 1, 1, 1, 1, 1, 1, 1, 0});
auto result = cudf::dictionary::get_index(dictionary, cudf::string_scalar("ccc"));
EXPECT_TRUE(result->is_valid());
auto n_result = dynamic_cast<cudf::numeric_scalar<uint32_t>*>(result.get());
EXPECT_EQ(uint32_t{3}, n_result->value());
result = cudf::dictionary::get_index(dictionary, cudf::string_scalar("eee"));
EXPECT_FALSE(result->is_valid());
result = cudf::dictionary::detail::get_insert_index(dictionary,
cudf::string_scalar("eee"),
cudf::get_default_stream(),
rmm::mr::get_current_device_resource());
n_result = dynamic_cast<cudf::numeric_scalar<uint32_t>*>(result.get());
EXPECT_EQ(uint32_t{5}, n_result->value());
}
TEST_F(DictionarySearchTest, WithNulls)
{
cudf::test::dictionary_column_wrapper<int64_t> dictionary({9, 8, 7, 6, 4}, {0, 1, 1, 0, 1});
auto result = cudf::dictionary::get_index(dictionary, cudf::numeric_scalar<int64_t>(4));
EXPECT_TRUE(result->is_valid());
auto n_result = dynamic_cast<cudf::numeric_scalar<uint32_t>*>(result.get());
EXPECT_EQ(uint32_t{0}, n_result->value());
result = cudf::dictionary::get_index(dictionary, cudf::numeric_scalar<int64_t>(5));
EXPECT_FALSE(result->is_valid());
result = cudf::dictionary::detail::get_insert_index(dictionary,
cudf::numeric_scalar<int64_t>(5),
cudf::get_default_stream(),
rmm::mr::get_current_device_resource());
n_result = dynamic_cast<cudf::numeric_scalar<uint32_t>*>(result.get());
EXPECT_EQ(uint32_t{1}, n_result->value());
}
TEST_F(DictionarySearchTest, EmptyColumn)
{
cudf::test::dictionary_column_wrapper<int64_t> dictionary{};
cudf::numeric_scalar<int64_t> key(7);
auto result = cudf::dictionary::get_index(dictionary, key);
EXPECT_FALSE(result->is_valid());
result = cudf::dictionary::detail::get_insert_index(
dictionary, key, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
EXPECT_FALSE(result->is_valid());
}
TEST_F(DictionarySearchTest, Errors)
{
cudf::test::dictionary_column_wrapper<int64_t> dictionary({1, 2, 3});
cudf::numeric_scalar<double> key(7);
EXPECT_THROW(cudf::dictionary::get_index(dictionary, key), cudf::logic_error);
EXPECT_THROW(
cudf::dictionary::detail::get_insert_index(
dictionary, key, cudf::get_default_stream(), rmm::mr::get_current_device_resource()),
cudf::logic_error);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/hashing/spark_murmurhash3_x86_32_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/iterator.cuh>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/hashing.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/type_lists.hpp>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
template <typename T>
class SparkMurmurHashTestTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(SparkMurmurHashTestTyped, cudf::test::FixedWidthTypes);
TYPED_TEST(SparkMurmurHashTestTyped, Equality)
{
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> const col{0, 127, 1, 2, 8};
auto const input = cudf::table_view({col});
// Hash of same input should be equal
auto const spark_output1 = cudf::hashing::spark_murmurhash3_x86_32(input, 0);
auto const spark_output2 = cudf::hashing::spark_murmurhash3_x86_32(input);
EXPECT_EQ(input.num_rows(), spark_output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(spark_output1->view(), spark_output2->view());
}
TYPED_TEST(SparkMurmurHashTestTyped, EqualityNulls)
{
using T = TypeParam;
// Nulls with different values should be equal
cudf::test::fixed_width_column_wrapper<T, int32_t> const col1({0, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<T, int32_t> const col2({1, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
auto const input1 = cudf::table_view({col1});
auto const input2 = cudf::table_view({col2});
auto const spark_output1 = cudf::hashing::spark_murmurhash3_x86_32(input1, 0);
auto const spark_output2 = cudf::hashing::spark_murmurhash3_x86_32(input2);
EXPECT_EQ(input1.num_rows(), spark_output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(spark_output1->view(), spark_output2->view());
}
template <typename T>
class SparkMurmurHashTestFloatTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(SparkMurmurHashTestFloatTyped, cudf::test::FloatingPointTypes);
TYPED_TEST(SparkMurmurHashTestFloatTyped, TestExtremes)
{
using T = TypeParam;
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
T nan = std::numeric_limits<T>::quiet_NaN();
T inf = std::numeric_limits<T>::infinity();
cudf::test::fixed_width_column_wrapper<T> const col(
{T(0.0), T(100.0), T(-100.0), min, max, nan, inf, -inf});
cudf::test::fixed_width_column_wrapper<T> const col_neg_zero(
{T(-0.0), T(100.0), T(-100.0), min, max, nan, inf, -inf});
cudf::test::fixed_width_column_wrapper<T> const col_neg_nan(
{T(0.0), T(100.0), T(-100.0), min, max, -nan, inf, -inf});
auto const table_col = cudf::table_view({col});
auto const table_col_neg_zero = cudf::table_view({col_neg_zero});
auto const table_col_neg_nan = cudf::table_view({col_neg_nan});
// Spark hash is sensitive to 0 and -0
auto const spark_col = cudf::hashing::spark_murmurhash3_x86_32(table_col, 0);
auto const spark_col_neg_nan = cudf::hashing::spark_murmurhash3_x86_32(table_col_neg_nan);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*spark_col, *spark_col_neg_nan);
}
class SparkMurmurHashTest : public cudf::test::BaseFixture {};
TEST_F(SparkMurmurHashTest, MultiValueNulls)
{
// Nulls with different values should be equal
cudf::test::strings_column_wrapper const strings_col1(
{"",
"The quick brown fox",
"jumps over the lazy dog.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"},
{0, 1, 1, 0, 1});
cudf::test::strings_column_wrapper const strings_col2(
{"different but null",
"The quick brown fox",
"jumps over the lazy dog.",
"I am Jack's complete lack of null value",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"},
{0, 1, 1, 0, 1});
// Nulls with different values should be equal
using limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col1(
{0, 100, -100, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col2(
{0, -200, 200, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
// Nulls with different values should be equal
// Different truth values should be equal
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 0, 1, 1}, {1, 1, 0, 0, 1});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 2, 1, 0, 255}, {1, 1, 0, 0, 1});
// Nulls with different values should be equal
using ts = cudf::timestamp_s;
cudf::test::fixed_width_column_wrapper<ts, ts::duration> const secs_col1(
{ts::duration::zero(),
static_cast<ts::duration>(100),
static_cast<ts::duration>(-100),
ts::duration::min(),
ts::duration::max()},
{1, 0, 0, 1, 1});
cudf::test::fixed_width_column_wrapper<ts, ts::duration> const secs_col2(
{ts::duration::zero(),
static_cast<ts::duration>(-200),
static_cast<ts::duration>(200),
ts::duration::min(),
ts::duration::max()},
{1, 0, 0, 1, 1});
auto const input1 = cudf::table_view({strings_col1, ints_col1, bools_col1, secs_col1});
auto const input2 = cudf::table_view({strings_col2, ints_col2, bools_col2, secs_col2});
auto const spark_output1 = cudf::hashing::spark_murmurhash3_x86_32(input1, 0);
auto const spark_output2 = cudf::hashing::spark_murmurhash3_x86_32(input2);
EXPECT_EQ(input1.num_rows(), spark_output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(spark_output1->view(), spark_output2->view());
}
TEST_F(SparkMurmurHashTest, MultiValueWithSeeds)
{
// The hash values were determined by running the following Scala code in Apache Spark.
// Note that Spark >= 3.2 normalizes the float/double value of -0. to +0. and both values hash
// to the same result. This is normalized in the calling code (Spark RAPIDS plugin) for Spark
// >= 3.2. However, the reference values for -0. below must be obtained with Spark < 3.2 and
// libcudf will continue to implement the Spark < 3.2 behavior until Spark >= 3.2 is required and
// the workaround in the calling code is removed. This also affects the combined hash values.
/*
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.util.DateTimeUtils
val schema = new StructType()
.add("structs", new StructType()
.add("a", IntegerType)
.add("b", StringType)
.add("c", new StructType()
.add("x", FloatType)
.add("y", LongType)))
.add("strings", StringType)
.add("doubles", DoubleType)
.add("timestamps", TimestampType)
.add("decimal64", DecimalType(18, 7))
.add("longs", LongType)
.add("floats", FloatType)
.add("dates", DateType)
.add("decimal32", DecimalType(9, 3))
.add("ints", IntegerType)
.add("shorts", ShortType)
.add("bytes", ByteType)
.add("bools", BooleanType)
.add("decimal128", DecimalType(38, 11))
val data = Seq(
Row(Row(0, "a", Row(0f, 0L)), "", 0.toDouble,
DateTimeUtils.toJavaTimestamp(0), BigDecimal(0), 0.toLong, 0.toFloat,
DateTimeUtils.toJavaDate(0), BigDecimal(0), 0, 0.toShort, 0.toByte,
false, BigDecimal(0)),
Row(Row(100, "bc", Row(100f, 100L)), "The quick brown fox", -(0.toDouble),
DateTimeUtils.toJavaTimestamp(100), BigDecimal("0.00001"), 100.toLong, -(0.toFloat),
DateTimeUtils.toJavaDate(100), BigDecimal("0.1"), 100, 100.toShort, 100.toByte,
true, BigDecimal("0.000000001")),
Row(Row(-100, "def", Row(-100f, -100L)), "jumps over the lazy dog.", -Double.NaN,
DateTimeUtils.toJavaTimestamp(-100), BigDecimal("-0.00001"), -100.toLong, -Float.NaN,
DateTimeUtils.toJavaDate(-100), BigDecimal("-0.1"), -100, -100.toShort, -100.toByte,
true, BigDecimal("-0.00000000001")),
Row(Row(0x12345678, "ghij", Row(Float.PositiveInfinity, 0x123456789abcdefL)),
"All work and no play makes Jack a dull boy", Double.MinValue,
DateTimeUtils.toJavaTimestamp(Long.MinValue/1000000), BigDecimal("-99999999999.9999999"),
Long.MinValue, Float.MinValue, DateTimeUtils.toJavaDate(Int.MinValue/100),
BigDecimal("-999999.999"), Int.MinValue, Short.MinValue, Byte.MinValue, true,
BigDecimal("-9999999999999999.99999999999")),
Row(Row(-0x76543210, "klmno", Row(Float.NegativeInfinity, -0x123456789abcdefL)),
"!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\ud720\ud721", Double.MaxValue,
DateTimeUtils.toJavaTimestamp(Long.MaxValue/1000000), BigDecimal("99999999999.9999999"),
Long.MaxValue, Float.MaxValue, DateTimeUtils.toJavaDate(Int.MaxValue/100),
BigDecimal("999999.999"), Int.MaxValue, Short.MaxValue, Byte.MaxValue, false,
BigDecimal("99999999999999999999999999.99999999999")))
val df = spark.createDataFrame(sc.parallelize(data), schema)
df.columns.foreach(c => println(s"$c => ${df.select(hash(col(c))).collect.mkString(",")}"))
println(s"combined => ${df.select(hash(col("*"))).collect.mkString(",")}")
*/
cudf::test::fixed_width_column_wrapper<int32_t> const hash_structs_expected(
{-105406170, 90479889, -678041645, 1667387937, 301478567});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_strings_expected(
{142593372, 1217302703, -715697185, -2061143941, -111635966});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_doubles_expected(
{-1670924195, -853646085, -1281358385, 1897734433, -508695674});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_timestamps_expected(
{-1670924195, 1114849490, 904948192, -1832979433, 1752430209});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_decimal64_expected(
{-1670924195, 1114849490, 904948192, 1962370902, -1795328666});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_longs_expected(
{-1670924195, 1114849490, 904948192, -853646085, -1604625029});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_floats_expected(
{933211791, 723455942, -349261430, -1225560532, -338752985});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_dates_expected(
{933211791, 751823303, -1080202046, -1906567553, -1503850410});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_decimal32_expected(
{-1670924195, 1114849490, 904948192, -1454351396, -193774131});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_ints_expected(
{933211791, 751823303, -1080202046, 723455942, 133916647});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_shorts_expected(
{933211791, 751823303, -1080202046, -1871935946, 1249274084});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_bytes_expected(
{933211791, 751823303, -1080202046, 1110053733, 1135925485});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_bools_expected(
{933211791, -559580957, -559580957, -559580957, 933211791});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_decimal128_expected(
{-783713497, -295670906, 1398487324, -52622807, -1359749815});
cudf::test::fixed_width_column_wrapper<int32_t> const hash_combined_expected(
{401603227, 588162166, 552160517, 1132537411, -326043017});
using double_limits = std::numeric_limits<double>;
using long_limits = std::numeric_limits<int64_t>;
using float_limits = std::numeric_limits<float>;
using int_limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> a_col{0, 100, -100, 0x1234'5678, -0x7654'3210};
cudf::test::strings_column_wrapper b_col{"a", "bc", "def", "ghij", "klmno"};
cudf::test::fixed_width_column_wrapper<float> x_col{
0.f, 100.f, -100.f, float_limits::infinity(), -float_limits::infinity()};
cudf::test::fixed_width_column_wrapper<int64_t> y_col{
0L, 100L, -100L, 0x0123'4567'89ab'cdefL, -0x0123'4567'89ab'cdefL};
cudf::test::structs_column_wrapper c_col{{x_col, y_col}};
cudf::test::structs_column_wrapper const structs_col{{a_col, b_col, c_col}};
cudf::test::strings_column_wrapper const strings_col(
{"",
"The quick brown fox",
"jumps over the lazy dog.",
"All work and no play makes Jack a dull boy",
"!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\ud720\ud721"});
cudf::test::fixed_width_column_wrapper<double> const doubles_col(
{0., -0., -double_limits::quiet_NaN(), double_limits::lowest(), double_limits::max()});
cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> const
timestamps_col({0L, 100L, -100L, long_limits::min() / 1000000, long_limits::max() / 1000000});
cudf::test::fixed_point_column_wrapper<int64_t> const decimal64_col(
{0L, 100L, -100L, -999999999999999999L, 999999999999999999L}, numeric::scale_type{-7});
cudf::test::fixed_width_column_wrapper<int64_t> const longs_col(
{0L, 100L, -100L, long_limits::min(), long_limits::max()});
cudf::test::fixed_width_column_wrapper<float> const floats_col(
{0.f, -0.f, -float_limits::quiet_NaN(), float_limits::lowest(), float_limits::max()});
cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> dates_col(
{0, 100, -100, int_limits::min() / 100, int_limits::max() / 100});
cudf::test::fixed_point_column_wrapper<int32_t> const decimal32_col(
{0, 100, -100, -999999999, 999999999}, numeric::scale_type{-3});
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col(
{0, 100, -100, int_limits::min(), int_limits::max()});
cudf::test::fixed_width_column_wrapper<int16_t> const shorts_col({0, 100, -100, -32768, 32767});
cudf::test::fixed_width_column_wrapper<int8_t> const bytes_col({0, 100, -100, -128, 127});
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 1, 1, 0});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 1, 2, 255, 0});
cudf::test::fixed_point_column_wrapper<__int128_t> const decimal128_col(
{static_cast<__int128>(0),
static_cast<__int128>(100),
static_cast<__int128>(-1),
(static_cast<__int128>(0xFFFF'FFFF'FCC4'D1C3u) << 64 | 0x602F'7FC3'1800'0001u),
(static_cast<__int128>(0x0785'EE10'D5DA'46D9u) << 64 | 0x00F4'369F'FFFF'FFFFu)},
numeric::scale_type{-11});
auto const hash_structs =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({structs_col}), 42);
auto const hash_strings =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({strings_col}), 42);
auto const hash_doubles =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({doubles_col}), 42);
auto const hash_timestamps =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({timestamps_col}), 42);
auto const hash_decimal64 =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({decimal64_col}), 42);
auto const hash_longs =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({longs_col}), 42);
auto const hash_floats =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({floats_col}), 42);
auto const hash_dates =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({dates_col}), 42);
auto const hash_decimal32 =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({decimal32_col}), 42);
auto const hash_ints = cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({ints_col}), 42);
auto const hash_shorts =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({shorts_col}), 42);
auto const hash_bytes =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({bytes_col}), 42);
auto const hash_bools1 =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({bools_col1}), 42);
auto const hash_bools2 =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({bools_col2}), 42);
auto const hash_decimal128 =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({decimal128_col}), 42);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_structs, hash_structs_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_strings, hash_strings_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_doubles, hash_doubles_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_timestamps, hash_timestamps_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_decimal64, hash_decimal64_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_longs, hash_longs_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_floats, hash_floats_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_dates, hash_dates_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_decimal32, hash_decimal32_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_ints, hash_ints_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_shorts, hash_shorts_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_bytes, hash_bytes_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_bools1, hash_bools_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_bools2, hash_bools_expected, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_decimal128, hash_decimal128_expected, verbosity);
auto const combined_table = cudf::table_view({structs_col,
strings_col,
doubles_col,
timestamps_col,
decimal64_col,
longs_col,
floats_col,
dates_col,
decimal32_col,
ints_col,
shorts_col,
bytes_col,
bools_col2,
decimal128_col});
auto const hash_combined = cudf::hashing::spark_murmurhash3_x86_32(combined_table, 42);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_combined, hash_combined_expected, verbosity);
}
TEST_F(SparkMurmurHashTest, StringsWithSeed)
{
// The hash values were determined by running the following Scala code in Apache Spark:
// val strs = Seq("", "The quick brown fox",
// "jumps over the lazy dog.",
// "All work and no play makes Jack a dull boy",
// "!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\ud720\ud721")
// println(strs.map(org.apache.spark.unsafe.types.UTF8String.fromString)
// .map(org.apache.spark.sql.catalyst.expressions.Murmur3HashFunction.hash(
// _, org.apache.spark.sql.types.StringType, 314)))
cudf::test::fixed_width_column_wrapper<int32_t> const hash_strings_expected_seed_314(
{1467149710, 723257560, -1620282500, -2001858707, 1588473657});
cudf::test::strings_column_wrapper const strings_col(
{"",
"The quick brown fox",
"jumps over the lazy dog.",
"All work and no play makes Jack a dull boy",
"!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\ud720\ud721"});
auto const hash_strings =
cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({strings_col}), 314);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_strings, hash_strings_expected_seed_314, verbosity);
}
TEST_F(SparkMurmurHashTest, ListValues)
{
/*
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, IntegerType, StructType}
import org.apache.spark.sql.Row
val schema = new StructType()
.add("lists",ArrayType(ArrayType(IntegerType)))
val data = Seq(
Row(null),
Row(List(null)),
Row(List(List())),
Row(List(List(1))),
Row(List(List(1, 2))),
Row(List(List(1, 2, 3))),
Row(List(List(1, 2), List(3))),
Row(List(List(1), List(2, 3))),
Row(List(List(1), List(null, 2, 3))),
Row(List(List(1, 2), List(3), List(null))),
Row(List(List(1, 2), null, List(3))),
)
val df = spark.createDataFrame(
spark.sparkContext.parallelize(data), schema)
val df2 = df.selectExpr("lists", "hash(lists) as hash")
df2.printSchema()
df2.show(false)
*/
auto const null = -1;
auto nested_list =
cudf::test::lists_column_wrapper<int>({{},
{1},
{1, 2},
{1, 2, 3},
{1, 2},
{3},
{1},
{2, 3},
{1},
{{null, 2, 3}, cudf::test::iterators::nulls_at({0})},
{1, 2},
{3},
{{null}, cudf::test::iterators::nulls_at({0})},
{1, 2},
{},
{3}},
cudf::test::iterators::nulls_at({0, 14}));
auto offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 16};
auto list_validity = cudf::test::iterators::nulls_at({0});
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(list_validity, list_validity + 11);
auto list_column = cudf::make_lists_column(
11, offsets.release(), nested_list.release(), null_count, std::move(null_mask));
auto expect = cudf::test::fixed_width_column_wrapper<int32_t>{42,
42,
42,
-559580957,
-222940379,
-912918097,
-912918097,
-912918097,
-912918097,
-912918097,
-912918097};
auto output = cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({*list_column}), 42);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
}
TEST_F(SparkMurmurHashTest, StructOfListValues)
{
/*
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, IntegerType, StructType}
import org.apache.spark.sql.Row
val schema = new StructType()
.add("structs", new StructType()
.add("a", ArrayType(IntegerType))
.add("b", ArrayType(IntegerType)))
val data = Seq(
Row(Row(List(), List())),
Row(Row(List(0), List(0))),
Row(Row(List(1, null), null)),
Row(Row(List(1, null), List())),
Row(Row(List(), List(null, 1))),
Row(Row(null, List(1))),
Row(Row(List(2, 3), List(4, 5))),
)
val df = spark.createDataFrame(
spark.sparkContext.parallelize(data), schema)
val df2 = df.selectExpr("lists", "hash(lists) as hash")
df2.printSchema()
df2.show(false)
*/
auto const null = -1;
auto col1 =
cudf::test::lists_column_wrapper<int>({{},
{0},
{{1, null}, cudf::test::iterators::nulls_at({1})},
{{1, null}, cudf::test::iterators::nulls_at({1})},
{},
{} /*NULL*/,
{2, 3}},
cudf::test::iterators::nulls_at({5}));
auto col2 = cudf::test::lists_column_wrapper<int>(
{{}, {0}, {} /*NULL*/, {}, {{null, 1}, cudf::test::iterators::nulls_at({0})}, {1}, {4, 5}},
cudf::test::iterators::nulls_at({2}));
auto struct_column = cudf::test::structs_column_wrapper{{col1, col2}};
auto expect = cudf::test::fixed_width_column_wrapper<int32_t>{
42, 59727262, -559580957, -559580957, -559580957, -559580957, 170038658};
auto output = cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({struct_column}), 42);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
}
TEST_F(SparkMurmurHashTest, ListOfStructValues)
{
/*
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, IntegerType, StructType}
import org.apache.spark.sql.Row
val schema = new StructType()
.add("lists", ArrayType(new StructType()
.add("a", IntegerType)
.add("b", IntegerType)))
val data = Seq(
Row(List(Row(0, 0))),
Row(List(null)),
Row(List(Row(null, null))),
Row(List(Row(1, null))),
Row(List(Row(null, 1))),
Row(List(Row(null, 1), Row(2, 3))),
Row(List(Row(2, 3), null)),
Row(List(Row(2, 3), Row(4, 5))),
)
val df = spark.createDataFrame(
spark.sparkContext.parallelize(data), schema)
val df2 = df.selectExpr("lists", "hash(lists) as hash")
df2.printSchema()
df2.show(false)
*/
auto const null = -1;
auto col1 = cudf::test::fixed_width_column_wrapper<int32_t>(
{0, null, null, 1, null, null, 2, 2, null, 2, 4},
cudf::test::iterators::nulls_at({1, 2, 4, 5, 8}));
auto col2 = cudf::test::fixed_width_column_wrapper<int32_t>(
{0, null, null, null, 1, 1, 3, 3, null, 3, 5}, cudf::test::iterators::nulls_at({1, 2, 3, 8}));
auto struct_column =
cudf::test::structs_column_wrapper{{col1, col2}, {1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1}};
auto offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 1, 2, 3, 4, 5, 7, 9, 11};
auto list_nullmask = std::vector<bool>(1, 8);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(list_nullmask.begin(), list_nullmask.end());
auto list_column = cudf::make_lists_column(
8, offsets.release(), struct_column.release(), null_count, std::move(null_mask));
// TODO: Lists of structs are not yet supported. Once support is added,
// remove this EXPECT_THROW and uncomment the rest of this test.
EXPECT_THROW(cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({*list_column}), 42),
cudf::logic_error);
/*
auto expect = cudf::test::fixed_width_column_wrapper<int32_t>{
59727262, 42, 42, -559580957, -559580957, -912918097, 1092624418, 170038658};
auto output = cudf::hashing::spark_murmurhash3_x86_32(cudf::table_view({*list_column}), 42);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
*/
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/hashing/murmurhash3_x64_128_test.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/table_utilities.hpp>
#include <cudf_test/type_lists.hpp>
#include <cudf/hashing.hpp>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
using NumericTypesNoBools =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
template <typename T>
class MurmurHash3_x64_128_TestTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(MurmurHash3_x64_128_TestTyped, NumericTypesNoBools);
TYPED_TEST(MurmurHash3_x64_128_TestTyped, TestNumeric)
{
using T = TypeParam;
auto col1 = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{-1, -1, 0, 2, 22, 0, 11, 12, 116, 32, 0, 42, 7, 62, 1, -22, 0, 0},
{1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}};
auto col2 = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{-1, -1, 0, 2, 22, 1, 11, 12, 116, 32, 0, 42, 7, 62, 1, -22, 1, -22},
{1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}};
auto output1 = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col1}));
auto output2 = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col2}));
CUDF_TEST_EXPECT_TABLES_EQUAL(output1->view(), output2->view());
output1 = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col1}), 7);
output2 = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col2}), 7);
CUDF_TEST_EXPECT_TABLES_EQUAL(output1->view(), output2->view());
}
class MurmurHash3_x64_128_Test : public cudf::test::BaseFixture {};
TEST_F(MurmurHash3_x64_128_Test, StringType)
{
auto col1 = cudf::test::strings_column_wrapper(
{"The",
"quick",
"brown fox",
"jumps over the lazy dog.",
"I am Jack's complete lack of null value",
"A very long (greater than 128 bytes/characters) to test a very long string. "
"2nd half of the very long string to verify the long string hashing happening.",
"Some multi-byte characters here: ééé",
"ééé",
"ééé ééé",
"ééé ééé ééé ééé",
"",
"!@#$%^&*(())",
"0123456789",
"{}|:<>?,./;[]=-"});
auto output = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col1}));
// these were generated using the CPU compiled
// https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp
auto expected = cudf::test::fixed_width_column_wrapper<uint64_t>({3481043174314896794ul,
1981901315483788749ul,
1418748153263580713ul,
11224732510765974842ul,
10813495276579975748ul,
8563282101401420087ul,
7289234017606107350ul,
225672801045596944ul,
14927688838032769435ul,
7513581995808204968ul,
0ul,
14163495587303857889ul,
4581940570640870180ul,
18164432652839101653ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view().column(0), expected);
auto const seed = uint64_t{7};
output = cudf::hashing::murmurhash3_x64_128(cudf::table_view({col1}), seed);
expected = cudf::test::fixed_width_column_wrapper<uint64_t>({5091211404759866125ul,
12948345853121693662ul,
14974420008081159223ul,
4475830656132398742ul,
15724398074328467356ul,
4091324140202743991ul,
7130403777725115865ul,
11087585763075301159ul,
12568262854562899547ul,
2679775340886828858ul,
17582832888865278351ul,
5264478748926531221ul,
8863578460974333747ul,
11176802453047055260ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view().column(0), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/hashing/murmurhash3_x86_32_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/iterator.cuh>
#include <cudf/hashing.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/type_lists.hpp>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
class MurmurHashTest : public cudf::test::BaseFixture {};
TEST_F(MurmurHashTest, MultiValue)
{
cudf::test::strings_column_wrapper const strings_col(
{"",
"The quick brown fox",
"jumps over the lazy dog.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"});
using limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col(
{0, 100, -100, limits::min(), limits::max()});
// Different truth values should be equal
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 1, 1, 0});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 1, 2, 255, 0});
using ts = cudf::timestamp_s;
cudf::test::fixed_width_column_wrapper<ts, ts::duration> const secs_col(
{ts::duration::zero(),
static_cast<ts::duration>(100),
static_cast<ts::duration>(-100),
ts::duration::min(),
ts::duration::max()});
auto const input1 = cudf::table_view({strings_col, ints_col, bools_col1, secs_col});
auto const input2 = cudf::table_view({strings_col, ints_col, bools_col2, secs_col});
auto const output1 = cudf::hashing::murmurhash3_x86_32(input1);
auto const output2 = cudf::hashing::murmurhash3_x86_32(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TEST_F(MurmurHashTest, MultiValueNulls)
{
// Nulls with different values should be equal
cudf::test::strings_column_wrapper const strings_col1(
{"",
"The quick brown fox",
"jumps over the lazy dog.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"},
{0, 1, 1, 0, 1});
cudf::test::strings_column_wrapper const strings_col2(
{"different but null",
"The quick brown fox",
"jumps over the lazy dog.",
"I am Jack's complete lack of null value",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"},
{0, 1, 1, 0, 1});
// Nulls with different values should be equal
using limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col1(
{0, 100, -100, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col2(
{0, -200, 200, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
// Nulls with different values should be equal
// Different truth values should be equal
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 0, 1, 1}, {1, 1, 0, 0, 1});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 2, 1, 0, 255}, {1, 1, 0, 0, 1});
// Nulls with different values should be equal
using ts = cudf::timestamp_s;
cudf::test::fixed_width_column_wrapper<ts, ts::duration> const secs_col1(
{ts::duration::zero(),
static_cast<ts::duration>(100),
static_cast<ts::duration>(-100),
ts::duration::min(),
ts::duration::max()},
{1, 0, 0, 1, 1});
cudf::test::fixed_width_column_wrapper<ts, ts::duration> const secs_col2(
{ts::duration::zero(),
static_cast<ts::duration>(-200),
static_cast<ts::duration>(200),
ts::duration::min(),
ts::duration::max()},
{1, 0, 0, 1, 1});
auto const input1 = cudf::table_view({strings_col1, ints_col1, bools_col1, secs_col1});
auto const input2 = cudf::table_view({strings_col2, ints_col2, bools_col2, secs_col2});
auto const output1 = cudf::hashing::murmurhash3_x86_32(input1);
auto const output2 = cudf::hashing::murmurhash3_x86_32(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TEST_F(MurmurHashTest, BasicList)
{
using LCW = cudf::test::lists_column_wrapper<uint64_t>;
using ICW = cudf::test::fixed_width_column_wrapper<uint32_t>;
auto const col = LCW{{}, {}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}};
auto const input = cudf::table_view({col});
auto const expect = ICW{1607593296,
1607593296,
-636010097,
-132459357,
-636010097,
-2008850957,
-1023787369,
761197503,
761197503,
1340177511,
-1023787369,
-1023787369};
auto const output = cudf::hashing::murmurhash3_x86_32(input);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
auto const expect_seeded = ICW{1607594268u,
1607594268u,
1576790066u,
1203671017u,
1576790066u,
2107478077u,
1756855002u,
2228938758u,
2228938758u,
3491134126u,
1756855002u,
1756855002u};
auto const seeded_output = cudf::hashing::murmurhash3_x86_32(input, 15);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_seeded, seeded_output->view(), verbosity);
}
TEST_F(MurmurHashTest, NullableList)
{
using LCW = cudf::test::lists_column_wrapper<uint64_t>;
using ICW = cudf::test::fixed_width_column_wrapper<uint32_t>;
auto const valids = std::vector<bool>{1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0};
auto const col =
LCW{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {}, {2, 2}, {2, 2}, {}}, valids.begin()};
auto expect = ICW{-2023148619,
-2023148619,
-31671896,
-31671896,
-1205248335,
1865773848,
1865773848,
-2023148682,
-1205248335,
-1205248335,
-2023148682};
auto const output = cudf::hashing::murmurhash3_x86_32(cudf::table_view({col}));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
auto const expect_seeded = ICW{2271820643u,
2271820643u,
1038318696u,
1038318696u,
595138041u,
3027840870u,
3027840870u,
2271820578u,
595138041u,
595138041u,
2271820578u};
auto const seeded_output = cudf::hashing::murmurhash3_x86_32(cudf::table_view({col}), 31);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_seeded, seeded_output->view(), verbosity);
}
TEST_F(MurmurHashTest, ListOfStruct)
{
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::make_lists_column(
17, offsets.release(), struct_col.release(), null_count, std::move(null_mask));
auto expect = cudf::test::fixed_width_column_wrapper<uint32_t>{83451479,
83451479,
83455332,
83455332,
-759684425,
-959632766,
-959632766,
-959632766,
-959636527,
-656998704,
613652814,
1902080426,
1902080426,
2061025592,
2061025592,
-319840811,
-319840811};
auto const output = cudf::hashing::murmurhash3_x86_32(cudf::table_view({*list_column}));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
auto expect_seeded = cudf::test::fixed_width_column_wrapper<uint32_t>{81710442u,
81710442u,
81729816u,
81729816u,
3532787573u,
3642097855u,
3642097855u,
3642097855u,
3642110391u,
3889855760u,
1494406307u,
103934081u,
103934081u,
3462063680u,
3462063680u,
1696730835u,
1696730835u};
auto const seeded_output =
cudf::hashing::murmurhash3_x86_32(cudf::table_view({*list_column}), 619);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_seeded, seeded_output->view(), verbosity);
}
TEST_F(MurmurHashTest, 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<uint32_t>{2271818677u,
2271818677u,
2271818614u,
2271818614u,
3954409013u,
3954409013u,
3954409013u,
2295666275u,
2295666275u,
2295666276u,
2295666276u,
3954409052u,
3954409052u};
auto output = cudf::hashing::murmurhash3_x86_32(cudf::table_view({*list_column}));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
}
TEST_F(MurmurHashTest, 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<uint32_t>{
2271818677u, 2271818677u, 2271818614u, 2271818614u};
auto output = cudf::hashing::murmurhash3_x86_32(cudf::table_view({*list_column}));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, output->view(), verbosity);
}
template <typename T>
class MurmurHashTestTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(MurmurHashTestTyped, cudf::test::FixedWidthTypes);
TYPED_TEST(MurmurHashTestTyped, Equality)
{
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> const col{0, 127, 1, 2, 8};
auto const input = cudf::table_view({col});
// Hash of same input should be equal
auto const output1 = cudf::hashing::murmurhash3_x86_32(input);
auto const output2 = cudf::hashing::murmurhash3_x86_32(input);
EXPECT_EQ(input.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TYPED_TEST(MurmurHashTestTyped, EqualityNulls)
{
using T = TypeParam;
// Nulls with different values should be equal
cudf::test::fixed_width_column_wrapper<T, int32_t> const col1({0, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<T, int32_t> const col2({1, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
auto const input1 = cudf::table_view({col1});
auto const input2 = cudf::table_view({col2});
auto const output1 = cudf::hashing::murmurhash3_x86_32(input1);
auto const output2 = cudf::hashing::murmurhash3_x86_32(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
template <typename T>
class MurmurHashTestFloatTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(MurmurHashTestFloatTyped, cudf::test::FloatingPointTypes);
TYPED_TEST(MurmurHashTestFloatTyped, TestExtremes)
{
using T = TypeParam;
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
T nan = std::numeric_limits<T>::quiet_NaN();
T inf = std::numeric_limits<T>::infinity();
cudf::test::fixed_width_column_wrapper<T> const col(
{T(0.0), T(100.0), T(-100.0), min, max, nan, inf, -inf});
cudf::test::fixed_width_column_wrapper<T> const col_neg_zero(
{T(-0.0), T(100.0), T(-100.0), min, max, nan, inf, -inf});
cudf::test::fixed_width_column_wrapper<T> const col_neg_nan(
{T(0.0), T(100.0), T(-100.0), min, max, -nan, inf, -inf});
auto const table_col = cudf::table_view({col});
auto const table_col_neg_zero = cudf::table_view({col_neg_zero});
auto const table_col_neg_nan = cudf::table_view({col_neg_nan});
auto const hash_col = cudf::hashing::murmurhash3_x86_32(table_col);
auto const hash_col_neg_zero = cudf::hashing::murmurhash3_x86_32(table_col_neg_zero);
auto const hash_col_neg_nan = cudf::hashing::murmurhash3_x86_32(table_col_neg_nan);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_col, *hash_col_neg_zero, verbosity);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*hash_col, *hash_col_neg_nan, verbosity);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/hashing/xxhash_64_test.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/detail/iterator.cuh>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/hashing.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/type_lists.hpp>
using NumericTypesNoBools =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
template <typename T>
class XXHash_64_TestTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(XXHash_64_TestTyped, NumericTypesNoBools);
TYPED_TEST(XXHash_64_TestTyped, TestAllNumeric)
{
using T = TypeParam;
auto col1 = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{-1, -1, 0, 2, 22, 0, 11, 12, 116, 32, 0, 42, 7, 62, 1, -22, 0, 0},
{1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}};
auto col2 = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{-1, -1, 0, 2, 22, 1, 11, 12, 116, 32, 0, 42, 7, 62, 1, -22, 1, -22},
{1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}};
auto output1 = cudf::hashing::xxhash_64(cudf::table_view({col1}));
auto output2 = cudf::hashing::xxhash_64(cudf::table_view({col2}));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
constexpr uint64_t seed = 7;
output1 = cudf::hashing::xxhash_64(cudf::table_view({col1}), seed);
output2 = cudf::hashing::xxhash_64(cudf::table_view({col2}), seed);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
class XXHash_64_Test : public cudf::test::BaseFixture {};
TEST_F(XXHash_64_Test, TestInteger)
{
auto col1 =
cudf::test::fixed_width_column_wrapper<int32_t>{{-127,
-70000,
0,
200000,
128,
std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::lowest()}};
auto const output = cudf::hashing::xxhash_64(cudf::table_view({col1}));
// these were generated using the CPU compiled version of the cuco xxhash_64 source
// https://github.com/NVIDIA/cuCollections/blob/dev/include/cuco/detail/hash_functions/xxhash.cuh
auto expected = cudf::test::fixed_width_column_wrapper<uint64_t>({4827426872506142937ul,
13867166853951622683ul,
4246796580750024372ul,
17339819992360460003ul,
7292178400482025765ul,
2971168436322821236ul,
9380524276503839603ul,
9380524276503839603ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), expected);
}
TEST_F(XXHash_64_Test, TestDouble)
{
auto col1 =
cudf::test::fixed_width_column_wrapper<double>{{-127.,
-70000.125,
0.0,
200000.5,
128.5,
-0.0,
std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::min(),
std::numeric_limits<double>::lowest()}};
auto const output = cudf::hashing::xxhash_64(cudf::table_view({col1}));
// these were generated using the CPU compiled version of the cuco xxhash_64 source
// https://github.com/NVIDIA/cuCollections/blob/dev/include/cuco/detail/hash_functions/xxhash.cuh
auto expected = cudf::test::fixed_width_column_wrapper<uint64_t>({16892115221677838993ul,
1686446903308179321ul,
3803688792395291579ul,
18250447068822614389ul,
3511911086082166358ul,
4558309869707674848ul,
18031741628920313605ul,
16838308782748609196ul,
3127544388062992779ul,
1692401401506680154ul,
13770442912356326755ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), expected);
}
TEST_F(XXHash_64_Test, StringType)
{
// clang-format off
auto col1 = cudf::test::strings_column_wrapper(
{"The",
"quick",
"brown fox",
"jumps over the lazy dog.",
"I am Jack's complete lack of null value",
"A very long (greater than 128 bytes/characters) to test a very long string. "
"2nd half of the very long string to verify the long string hashing happening.",
"Some multi-byte characters here: ééé",
"ééé",
"ééé ééé",
"ééé ééé ééé ééé",
"",
"!@#$%^&*(())",
"0123456789",
"{}|:<>?,./;[]=-"});
// clang-format on
auto output = cudf::hashing::xxhash_64(cudf::table_view({col1}));
// these were generated using the CPU compiled version of the cuco xxhash_64 source
// https://github.com/NVIDIA/cuCollections/blob/dev/include/cuco/detail/hash_functions/xxhash.cuh
// Also verified these with https://pypi.org/project/xxhash/
// using xxhash.xxh64(bytes(s,'utf-8')).intdigest()
auto expected = cudf::test::fixed_width_column_wrapper<uint64_t>({4686269239494003989ul,
6715983472207430822ul,
8148134898123095730ul,
17291005374665645904ul,
2631835514925512071ul,
4181420602165187991ul,
8749004388517322364ul,
17701789113925815768ul,
8612485687958712810ul,
5148645515269989956ul,
17241709254077376921ul,
7379359170906687646ul,
4566581271137380327ul,
17962149534752128981ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), expected);
}
TEST_F(XXHash_64_Test, TestFixedPoint)
{
auto const col1 = cudf::test::fixed_point_column_wrapper<int32_t>(
{0, 100, -100, -999999999, 999999999}, numeric::scale_type{-3});
auto const output = cudf::hashing::xxhash_64(cudf::table_view({col1}));
// these were generated using the CPU compiled version of the cuco xxhash_64 source
// https://github.com/NVIDIA/cuCollections/blob/dev/include/cuco/detail/hash_functions/xxhash.cuh
// and passing the 'value' of each input (without the scale) as the decimal-type
auto expected = cudf::test::fixed_width_column_wrapper<uint64_t>({4246796580750024372ul,
5959467639951725378ul,
4122185689695768261ul,
3249245648192442585ul,
8009575895491381648ul});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/hashing/md5_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/iterator.cuh>
#include <cudf/hashing.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/type_lists.hpp>
constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS};
class MD5HashTest : public cudf::test::BaseFixture {};
TEST_F(MD5HashTest, MultiValue)
{
cudf::test::strings_column_wrapper const strings_col(
{"",
"A 60 character string to test MD5's message padding algorithm",
"A very long (greater than 128 bytes/char string) to test a multi hash-step data point in the "
"MD5 hash function. This string needed to be longer.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"});
cudf::test::strings_column_wrapper const md5_string_results1(
{"d41d8cd98f00b204e9800998ecf8427e",
"682240021651ae166d08fe2a014d5c09",
"3669d5225fddbb34676312ca3b78bbd9",
"c61a4185135eda043f35e92c3505e180",
"52da74c75cb6575d25be29e66bd0adde"});
cudf::test::strings_column_wrapper const md5_string_results2(
{"d41d8cd98f00b204e9800998ecf8427e",
"e5a5682e82278e78dbaad9a689df7a73",
"4121ab1bb6e84172fd94822645862ae9",
"28970886501efe20164213855afe5850",
"6bc1b872103cc6a02d882245b8516e2e"});
using limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col(
{0, 100, -100, limits::min(), limits::max()});
// Different truth values should be equal
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 1, 1, 0});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 1, 2, 255, 0});
auto const string_input1 = cudf::table_view({strings_col});
auto const string_input2 = cudf::table_view({strings_col, strings_col});
auto const md5_string_output1 = cudf::hashing::md5(string_input1);
auto const md5_string_output2 = cudf::hashing::md5(string_input2);
EXPECT_EQ(string_input1.num_rows(), md5_string_output1->size());
EXPECT_EQ(string_input2.num_rows(), md5_string_output2->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(md5_string_output1->view(), md5_string_results1);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(md5_string_output2->view(), md5_string_results2);
auto const input1 = cudf::table_view({strings_col, ints_col, bools_col1});
auto const input2 = cudf::table_view({strings_col, ints_col, bools_col2});
auto const md5_output1 = cudf::hashing::md5(input1);
auto const md5_output2 = cudf::hashing::md5(input2);
EXPECT_EQ(input1.num_rows(), md5_output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(md5_output1->view(), md5_output2->view());
}
TEST_F(MD5HashTest, MultiValueNulls)
{
// Nulls with different values should be equal
cudf::test::strings_column_wrapper const strings_col1(
{"",
"Different but null!",
"A very long (greater than 128 bytes/char string) to test a multi hash-step data point in the "
"MD5 hash function. This string needed to be longer.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"},
{1, 0, 0, 1, 0});
cudf::test::strings_column_wrapper const strings_col2(
{"",
"A 60 character string to test MD5's message padding algorithm",
"Very different... but null",
"All work and no play makes Jack a dull boy",
""},
{1, 0, 0, 1, 1}); // empty string is equivalent to null
// Nulls with different values should be equal
using limits = std::numeric_limits<int32_t>;
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col1(
{0, 100, -100, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
cudf::test::fixed_width_column_wrapper<int32_t> const ints_col2(
{0, -200, 200, limits::min(), limits::max()}, {1, 0, 0, 1, 1});
// Nulls with different values should be equal
// Different truth values should be equal
cudf::test::fixed_width_column_wrapper<bool> const bools_col1({0, 1, 0, 1, 1}, {1, 1, 0, 0, 1});
cudf::test::fixed_width_column_wrapper<bool> const bools_col2({0, 2, 1, 0, 255}, {1, 1, 0, 0, 1});
auto const input1 = cudf::table_view({strings_col1, ints_col1, bools_col1});
auto const input2 = cudf::table_view({strings_col2, ints_col2, bools_col2});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TEST_F(MD5HashTest, StringListsNulls)
{
auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0; });
cudf::test::strings_column_wrapper const strings_col(
{"",
"A 60 character string to test MD5's message padding algorithm",
"A very long (greater than 128 bytes/char string) to test a multi hash-step data point in the "
"MD5 hash function. This string needed to be longer. It needed to be even longer.",
"All work and no play makes Jack a dull boy",
R"(!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~)"});
cudf::test::lists_column_wrapper<cudf::string_view> strings_list_col(
{{""},
{{"NULL", "A 60 character string to test MD5's message padding algorithm"}, validity},
{"A very long (greater than 128 bytes/char string) to test a multi hash-step data point in "
"the "
"MD5 hash function. This string needed to be longer.",
" It needed to be even longer."},
{"All ", "work ", "and", " no", " play ", "makes Jack", " a dull boy"},
{"!\"#$%&\'()*+,-./0123456789:;<=>?@[\\]^_`", "{|}~"}});
auto const input1 = cudf::table_view({strings_col});
auto const input2 = cudf::table_view({strings_list_col});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
template <typename T>
class MD5HashTestTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(MD5HashTestTyped, cudf::test::NumericTypes);
TYPED_TEST(MD5HashTestTyped, Equality)
{
cudf::test::fixed_width_column_wrapper<TypeParam> const col({0, 127, 1, 2, 8});
auto const input = cudf::table_view({col});
// Hash of same input should be equal
auto const output1 = cudf::hashing::md5(input);
auto const output2 = cudf::hashing::md5(input);
EXPECT_EQ(input.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TYPED_TEST(MD5HashTestTyped, EqualityNulls)
{
using T = TypeParam;
// Nulls with different values should be equal
cudf::test::fixed_width_column_wrapper<T> const col1({0, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
cudf::test::fixed_width_column_wrapper<T> const col2({1, 127, 1, 2, 8}, {0, 1, 1, 1, 1});
auto const input1 = cudf::table_view({col1});
auto const input2 = cudf::table_view({col2});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
TEST_F(MD5HashTest, TestBoolListsWithNulls)
{
cudf::test::fixed_width_column_wrapper<bool> const col1({0, 255, 255, 16, 27, 18, 100, 1, 2},
{1, 0, 0, 0, 1, 1, 1, 0, 0});
cudf::test::fixed_width_column_wrapper<bool> const col2({0, 255, 255, 32, 81, 68, 3, 101, 4},
{1, 0, 0, 1, 0, 1, 0, 1, 0});
cudf::test::fixed_width_column_wrapper<bool> const col3({0, 255, 255, 64, 49, 42, 5, 6, 102},
{1, 0, 0, 1, 1, 0, 0, 0, 1});
auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; });
cudf::test::lists_column_wrapper<bool> const list_col(
{{0, 0, 0}, {1}, {}, {{1, 1, 1}, validity}, {1, 1}, {1, 1}, {1}, {1}, {1}}, validity);
auto const input1 = cudf::table_view({col1, col2, col3});
auto const input2 = cudf::table_view({list_col});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
template <typename T>
class MD5HashListTestTyped : public cudf::test::BaseFixture {};
using NumericTypesNoBools =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(MD5HashListTestTyped, NumericTypesNoBools);
TYPED_TEST(MD5HashListTestTyped, TestListsWithNulls)
{
using T = TypeParam;
cudf::test::fixed_width_column_wrapper<T> const col1({0, 255, 255, 16, 27, 18, 100, 1, 2},
{1, 0, 0, 0, 1, 1, 1, 0, 0});
cudf::test::fixed_width_column_wrapper<T> const col2({0, 255, 255, 32, 81, 68, 3, 101, 4},
{1, 0, 0, 1, 0, 1, 0, 1, 0});
cudf::test::fixed_width_column_wrapper<T> const col3({0, 255, 255, 64, 49, 42, 5, 6, 102},
{1, 0, 0, 1, 1, 0, 0, 0, 1});
auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; });
cudf::test::lists_column_wrapper<T> const list_col(
{{0, 0, 0}, {127}, {}, {{32, 127, 64}, validity}, {27, 49}, {18, 68}, {100}, {101}, {102}},
validity);
auto const input1 = cudf::table_view({col1, col2, col3});
auto const input2 = cudf::table_view({list_col});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
EXPECT_EQ(input1.num_rows(), output1->size());
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view());
}
template <typename T>
class MD5HashTestFloatTyped : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(MD5HashTestFloatTyped, cudf::test::FloatingPointTypes);
TYPED_TEST(MD5HashTestFloatTyped, TestExtremes)
{
using T = TypeParam;
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
T nan = std::numeric_limits<T>::quiet_NaN();
T inf = std::numeric_limits<T>::infinity();
cudf::test::fixed_width_column_wrapper<T> const col1(
{T(0.0), T(100.0), T(-100.0), min, max, nan, inf, -inf});
cudf::test::fixed_width_column_wrapper<T> const col2(
{T(-0.0), T(100.0), T(-100.0), min, max, -nan, inf, -inf});
auto const input1 = cudf::table_view({col1});
auto const input2 = cudf::table_view({col2});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view(), verbosity);
}
TYPED_TEST(MD5HashTestFloatTyped, TestListExtremes)
{
using T = TypeParam;
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
T nan = std::numeric_limits<T>::quiet_NaN();
T inf = std::numeric_limits<T>::infinity();
cudf::test::lists_column_wrapper<T> const col1(
{{T(0.0)}, {T(100.0), T(-100.0)}, {min, max, nan}, {inf, -inf}});
cudf::test::lists_column_wrapper<T> const col2(
{{T(-0.0)}, {T(100.0), T(-100.0)}, {min, max, -nan}, {inf, -inf}});
auto const input1 = cudf::table_view({col1});
auto const input2 = cudf::table_view({col2});
auto const output1 = cudf::hashing::md5(input1);
auto const output2 = cudf::hashing::md5(input2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1->view(), output2->view(), verbosity);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/json/json_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/json/json.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/strings/replace.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <stdexcept>
// reference: https://jsonpath.herokuapp.com/
// clang-format off
std::string json_string{
"{"
"\"store\": {""\"book\": ["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"],"
"\"bicycle\": {"
"\"color\": \"red\","
"\"price\": 19.95"
"}"
"},"
"\"expensive\": 10"
"}"
};
// clang-format on
std::unique_ptr<cudf::column> drop_whitespace(cudf::column_view const& col)
{
cudf::test::strings_column_wrapper whitespace{"\n", "\r", "\t"};
cudf::test::strings_column_wrapper repl{"", "", ""};
cudf::strings_column_view strings(col);
cudf::strings_column_view targets(whitespace);
cudf::strings_column_view replacements(repl);
return cudf::strings::replace(strings, targets, replacements);
}
struct JsonPathTests : public cudf::test::BaseFixture {};
TEST_F(JsonPathTests, GetJsonObjectRootOp)
{
// root
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
auto expected = drop_whitespace(input);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
TEST_F(JsonPathTests, GetJsonObjectChildOp)
{
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"{"
"\"book\": ["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"],"
"\"bicycle\": {"
"\"color\": \"red\","
"\"price\": 19.95"
"}"
"}"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"]"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectWildcardOp)
{
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.*");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"["
"["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"],"
"{"
"\"color\": \"red\","
"\"price\": 19.95"
"}"
"]"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("*");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"["
"{"
"\"book\": ["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"],"
"\"bicycle\": {"
"\"color\": \"red\","
"\"price\": 19.95"
"}"
"},"
"10"
"]"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectSubscriptOp)
{
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[2]");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"}"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store['bicycle']");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"{"
"\"color\": \"red\","
"\"price\": 19.95"
"}"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[*]");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
// clang-format off
cudf::test::strings_column_wrapper expected_raw{
"["
"{"
"\"category\": \"reference\","
"\"author\": \"Nigel Rees\","
"\"title\": \"Sayings of the Century\","
"\"price\": 8.95"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Evelyn Waugh\","
"\"title\": \"Sword of Honour\","
"\"price\": 12.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"Herman Melville\","
"\"title\": \"Moby Dick\","
"\"isbn\": \"0-553-21311-3\","
"\"price\": 8.99"
"},"
"{"
"\"category\": \"fiction\","
"\"author\": \"J. R. R. Tolkien\","
"\"title\": \"The Lord of the Rings\","
"\"isbn\": \"0-395-19395-8\","
"\"price\": 22.99"
"}"
"]"
};
// clang-format on
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectFilter)
{
// queries that result in filtering/collating results (mostly meaning - generates new
// json instead of just returning parts of the existing string
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[*]['isbn']");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw{R"(["0-553-21311-3","0-395-19395-8"])"};
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[*].category");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw{
R"(["reference","fiction","fiction","fiction"])"};
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[*].title");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw{
R"(["Sayings of the Century","Sword of Honour","Moby Dick","The Lord of the Rings"])"};
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book.*.price");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw{"[8.95,12.99,8.99,22.99]"};
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
{
// spark behavioral difference.
// standard: "fiction"
// spark: fiction
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[2].category");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw{"fiction"};
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectNullInputs)
{
{
std::string str("{\"a\" : \"b\"}");
cudf::test::strings_column_wrapper input({str, str, str, str}, {1, 0, 1, 0});
std::string json_path("$.a");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw({"b", "", "b", ""}, {1, 0, 1, 0});
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectEmptyQuery)
{
// empty query -> null
{
cudf::test::strings_column_wrapper input{R"({"a" : "b"})"};
std::string json_path("");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectEmptyInputsAndOutputs)
{
// empty string input -> null
{
cudf::test::strings_column_wrapper input{""};
std::string json_path("$");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
// slightly different from "empty output". in this case, we're
// returning something, but it happens to be empty. so we expect
// a valid, but empty row
{
cudf::test::strings_column_wrapper input{R"({"store": { "bicycle" : "" } })"};
std::string json_path("$.store.bicycle");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {1});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, GetJsonObjectEmptyInput)
{
cudf::test::strings_column_wrapper input{};
std::string json_path("$");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, input);
}
// badly formed JSONpath strings
TEST_F(JsonPathTests, GetJsonObjectIllegalQuery)
{
// can't have more than one root operator, or a root operator anywhere other
// than the beginning
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$$");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), cudf::logic_error);
}
// invalid index
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$[auh46h-]");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), cudf::logic_error);
}
// invalid index
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$[[]]");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), cudf::logic_error);
}
// negative index
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$[-1]");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), cudf::logic_error);
}
// child operator with no name specified
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path(".");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), std::invalid_argument);
}
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("][");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), std::invalid_argument);
}
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("6hw6,56i3");
auto query = [&]() {
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
};
EXPECT_THROW(query(), std::invalid_argument);
}
}
// queries that are legal, but reference invalid parts of the input
TEST_F(JsonPathTests, GetJsonObjectInvalidQuery)
{
// non-existent field
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$[*].c");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
// non-existent field
{
cudf::test::strings_column_wrapper input{R"({"a": "b"})"};
std::string json_path("$[*].c[2]");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
// non-existent field
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book.price");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
// out of bounds index
{
cudf::test::strings_column_wrapper input{json_string};
std::string json_path("$.store.book[4]");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
cudf::test::strings_column_wrapper expected({""}, {0});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, MixedOutput)
{
// various queries on:
// clang-format off
std::vector<std::string> input_strings {
"{\"a\": {\"b\" : \"c\"}}",
"{"
"\"a\": {\"b\" : \"c\"},"
"\"d\": [{\"e\":123}, {\"f\":-10}]"
"}",
"{"
"\"b\": 123"
"}",
"{"
"\"a\": [\"y\",500]"
"}",
"{"
"\"a\": \"\""
"}",
"{"
"\"a\": {"
"\"z\": {\"i\": 10, \"j\": 100},"
"\"b\": [\"c\",null,true,-1]"
"}"
"}"
};
// clang-format on
cudf::test::strings_column_wrapper input(input_strings.begin(), input_strings.end());
{
std::string json_path("$.a");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
// clang-format off
cudf::test::strings_column_wrapper expected({
R"({"b" : "c"})",
R"({"b" : "c"})",
"",
"[\"y\",500]",
"",
"{"
"\"z\": {\"i\": 10, \"j\": 100},"
"\"b\": [\"c\",null,true,-1]"
"}"
},
{1, 1, 0, 1, 1, 1});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
{
std::string json_path("$.a[1]");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
// clang-format off
cudf::test::strings_column_wrapper expected({
"",
"",
"",
"500",
"",
"",
},
{0, 0, 0, 1, 0, 0});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
{
std::string json_path("$.a.b");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
// clang-format off
cudf::test::strings_column_wrapper expected({
"c",
"c",
"",
"",
"",
"[\"c\",null,true,-1]"},
{1, 1, 0, 0, 0, 1});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
{
std::string json_path("$.a[*]");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
// clang-format off
cudf::test::strings_column_wrapper expected({
"[\"c\"]",
"[\"c\"]",
"",
"[\"y\",500]",
"[]",
"["
"{\"i\": 10, \"j\": 100},"
"[\"c\",null,true,-1]"
"]" },
{1, 1, 0, 1, 1, 1});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
{
std::string json_path("$.a.b[*]");
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path);
// clang-format off
cudf::test::strings_column_wrapper expected({
"[]",
"[]",
"",
"",
"",
"[\"c\",null,true,-1]"},
{1, 1, 0, 0, 0, 1});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, StripQuotes)
{
// we normally expect our outputs here to be
// b (no quotes)
// but with string_quotes_from_single_strings false, we expect
// "b" (with quotes)
{
std::string str("{\"a\" : \"b\"}");
cudf::test::strings_column_wrapper input({str, str});
cudf::get_json_object_options options;
options.set_strip_quotes_from_single_strings(false);
std::string json_path("$.a");
auto result_raw = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
auto result = drop_whitespace(*result_raw);
cudf::test::strings_column_wrapper expected_raw({"\"b\"", "\"b\""});
auto expected = drop_whitespace(expected_raw);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected);
}
// a valid, but empty row
{
cudf::test::strings_column_wrapper input{R"({"store": { "bicycle" : "" } })"};
std::string json_path("$.store.bicycle");
cudf::get_json_object_options options;
options.set_strip_quotes_from_single_strings(true);
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
cudf::test::strings_column_wrapper expected({""});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, AllowSingleQuotes)
{
// Tests allowing single quotes for strings.
// Note: this flag allows a mix of single and double quotes. it doesn't explicitly require
// single-quotes only.
// various queries on:
std::vector<std::string> input_strings{
// clang-format off
"{\'a\': {\'b\' : \'c\'}}",
"{"
"\'a\': {\'b\' : \"c\"},"
"\'d\': [{\"e\":123}, {\'f\':-10}]"
"}",
"{"
"\'b\': 123"
"}",
"{"
"\"a\": [\'y\',500]"
"}",
"{"
"\'a\': \"\""
"}",
"{"
"\"a\": {"
"\'z\': {\'i\': 10, \'j\': 100},"
"\'b\': [\'c\',null,true,-1]"
"}"
"}",
"{"
"\'a\': \"abc'def\""
"}",
"{"
"\'a\': \"'abc'def'\""
"}",
// clang-format on
};
cudf::test::strings_column_wrapper input(input_strings.begin(), input_strings.end());
{
std::string json_path("$.a");
cudf::get_json_object_options options;
options.set_allow_single_quotes(true);
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
// clang-format off
cudf::test::strings_column_wrapper expected({
R"({'b' : 'c'})",
R"({'b' : "c"})",
"",
"[\'y\',500]",
"",
"{"
"\'z\': {\'i\': 10, \'j\': 100},"
"\'b\': [\'c\',null,true,-1]"
"}",
"abc'def",
"'abc'def'"
},
{1, 1, 0, 1, 1, 1, 1, 1});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, StringsWithSpecialChars)
{
// make sure we properly handle strings containing special characters
// like { } [ ], etc
// various queries on:
{
std::vector<std::string> input_strings{
// clang-format off
"{\"item\" : [{\"key\" : \"value[\"}]}",
// clang-format on
};
cudf::test::strings_column_wrapper input(input_strings.begin(), input_strings.end());
{
std::string json_path("$.item");
cudf::get_json_object_options options;
options.set_allow_single_quotes(true);
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
// clang-format off
cudf::test::strings_column_wrapper expected({
R"([{"key" : "value["}])",
});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
{
std::vector<std::string> input_strings{
// clang-format off
"{\"a\" : \"[}{}][][{[\\\"}}[\\\"]\"}",
// clang-format on
};
cudf::test::strings_column_wrapper input(input_strings.begin(), input_strings.end());
{
std::string json_path("$.a");
cudf::get_json_object_options options;
options.set_allow_single_quotes(true);
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
// clang-format off
cudf::test::strings_column_wrapper expected({
R"([}{}][][{[\"}}[\"])",
});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
}
TEST_F(JsonPathTests, EscapeSequences)
{
// valid escape sequences in JSON include
// \" \\ \/ \b \f \n \r \t
// \uXXXX where X is a valid hex digit
std::vector<std::string> input_strings{
// clang-format off
"{\"a\" : \"\\\" \\\\ \\/ \\b \\f \\n \\r \\t\"}",
"{\"a\" : \"\\u1248 \\uacdf \\uACDF \\u10EF\"}"
// clang-format on
};
cudf::test::strings_column_wrapper input(input_strings.begin(), input_strings.end());
{
std::string json_path("$.a");
cudf::get_json_object_options options;
options.set_allow_single_quotes(true);
auto result = cudf::get_json_object(cudf::strings_column_view(input), json_path, options);
// clang-format off
cudf::test::strings_column_wrapper expected({
R"(\" \\ \/ \b \f \n \r \t)",
R"(\u1248 \uacdf \uACDF \u10EF)"
});
// clang-format on
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected);
}
}
TEST_F(JsonPathTests, MissingFieldsAsNulls)
{
std::string input_string{
// clang-format off
"{"
"\"tup\":"
"["
"{\"id\":\"1\",\"array\":[1,2]},"
"{\"id\":\"2\"},"
"{\"id\":\"3\",\"array\":[3,4]},"
"{\"id\":\"4\", \"a\": {\"x\": \"5\", \"y\": \"6\"}}"
"]"
"}"
// clang-format on
};
auto do_test = [&input_string](auto const& json_path_string,
auto const& default_output,
auto const& missing_fields_output,
bool default_valid = true) {
cudf::test::strings_column_wrapper input{input_string};
cudf::get_json_object_options options;
// Test default behavior
options.set_missing_fields_as_nulls(false);
auto const default_result =
cudf::get_json_object(cudf::strings_column_view(input), {json_path_string}, options);
cudf::test::strings_column_wrapper default_expected({default_output}, {default_valid});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(default_expected, *default_result);
// Test with missing fields as null
options.set_missing_fields_as_nulls(true);
auto const missing_fields_result =
cudf::get_json_object(cudf::strings_column_view(input), {json_path_string}, options);
cudf::test::strings_column_wrapper missing_fields_expected({missing_fields_output}, {1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(missing_fields_expected, *missing_fields_result);
};
do_test("$.tup[1].array", "", "null", false);
do_test("$.tup[*].array", "[[1,2],[3,4]]", "[[1,2],null,[3,4],null]");
do_test("$.x[*].array", "", "null", false);
do_test("$.tup[*].a.x", "[\"5\"]", "[null,null,null,\"5\"]");
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/lists_column_wrapper_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/detail/iterator.cuh>
#include <cudf/lists/lists_column_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/cudf_gtest.hpp>
#include <cudf_test/type_lists.hpp>
#include <rmm/device_buffer.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
struct ListColumnWrapperTest : public cudf::test::BaseFixture {};
template <typename T>
struct ListColumnWrapperTestTyped : public cudf::test::BaseFixture {
ListColumnWrapperTestTyped() {}
auto data_type() { return cudf::data_type{cudf::type_to_id<T>()}; }
};
using FixedWidthTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool,
cudf::test::FloatingPointTypes,
cudf::test::DurationTypes,
cudf::test::TimestampTypes>;
TYPED_TEST_SUITE(ListColumnWrapperTestTyped, FixedWidthTypesNotBool);
TYPED_TEST(ListColumnWrapperTestTyped, List)
{
using T = TypeParam;
// List<T>, 1 row
//
// List<T>:
// Length : 1
// Offsets : 0, 2
// Children :
// 2, 3
//
{
cudf::test::lists_column_wrapper<T, int32_t> list{2, 3};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 2);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({2, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
// List<T>, 1 row
//
// List<T>:
// Length : 1
// Offsets : 0, 2
// Children :
// 2, 3
//
{
cudf::test::lists_column_wrapper<T, int32_t> list{{2, 3}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 2);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({2, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, ListWithValidity)
{
using T = TypeParam;
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<T>, 1 row
//
// List<T>:
// Length : 1
// Offsets : 0, 2
// Children :
// 2, NULL
//
{
cudf::test::lists_column_wrapper<T, int32_t> list{{{2, 3}, valids}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 2);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({2, 3}, valids);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
// List<T>, 3 rows
//
// List<T>:
// Length : 3
// Offsets : 0, 2, 4, 7
// Children :
// 2, NULL, 4, NULL, 6, NULL, 8
{
cudf::test::lists_column_wrapper<T, int32_t> list{
{{2, 3}, valids}, {{4, 5}, valids}, {{6, 7, 8}, valids}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 4, 7});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 7);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({2, 3, 4, 5, 6, 7, 8}, valids);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, ListFromIterator)
{
using T = TypeParam;
// List<T>, 1 row
//
// List<T>:
// Length : 1
// Offsets : 0, 5
// Children :
// 0, 1, 2, 3, 4
//
auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; });
cudf::test::lists_column_wrapper<T, typename decltype(sequence)::value_type> list{sequence,
sequence + 5};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 5);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({0, 1, 2, 3, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
TYPED_TEST(ListColumnWrapperTestTyped, ListFromIteratorWithValidity)
{
using T = TypeParam;
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<int>, 1 row
//
// List<int32_t>:
// Length : 1
// Offsets : 0, 5
// Children :
// 0, NULL, 2, NULL, 4
//
auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; });
cudf::test::lists_column_wrapper<T, typename decltype(sequence)::value_type> list{
sequence, sequence + 5, valids};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 5);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_data({0, 0, 2, 0, 4}, valids);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
TYPED_TEST(ListColumnWrapperTestTyped, ListOfLists)
{
using T = TypeParam;
// List<List<T>>, 1 row
//
// List<List<T>>:
// Length : 1
// Offsets : 0, 2
// Children :
// List<T>:
// Length : 2
// Offsets : 0, 2, 4
// Children :
// 2, 3, 4, 5
{
cudf::test::lists_column_wrapper<T, int32_t> list{{{2, 3}, {4, 5}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 4);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({2, 3, 4, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
// List<List<T>> 3 rows
//
// List<List<T>>:
// Length : 3
// Offsets : 0, 2, 5, 6
// Children :
// List<T>:
// Length : 6
// Offsets : 0, 2, 4, 7, 8, 9, 11
// Children :
// 1, 2, 3, 4, 5, 6, 7, 0, 8, 9, 10
{
cudf::test::lists_column_wrapper<T, int32_t> list{
{{1, 2}, {3, 4}}, {{5, 6, 7}, {0}, {8}}, {{9, 10}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 5, 6});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 6);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 7);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 4, 7, 8, 9, 11});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 11);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data(
{1, 2, 3, 4, 5, 6, 7, 0, 8, 9, 10});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, ListOfListsWithValidity)
{
using T = TypeParam;
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<List<T>>, 1 row
//
// List<List<T>>:
// Length : 1
// Offsets : 0, 2
// Children :
// List<T>:
// Length : 2
// Offsets : 0, 2, 4
// Children :
// 2, NULL, 4, NULL
{
// equivalent to { {2, NULL}, {4, NULL} }
cudf::test::lists_column_wrapper<T, int32_t> list{{{{2, 3}, valids}, {{4, 5}, valids}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 4);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({2, 3, 4, 5}, valids);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
// List<List<T>> 3 rows
//
// List<List<T>>:
// Length : 3
// Offsets : 0, 2, 5, 6
// Children :
// List<T>:
// Length : 6
// Offsets : 0, 2, 2, 5, 5, 6, 8
// Null count: 2
// 110101
// Children :
// 1, 2, 5, 6, 7, 8, 9, 10
{
// equivalent to { {{1, 2}, NULL}, {{5, 6, 7}, NULL, {8}}, {{9, 10}} }
cudf::test::lists_column_wrapper<T, int32_t> list{
{{{1, 2}, {3, 4}}, valids}, {{{5, 6, 7}, {0}, {8}}, valids}, {{{9, 10}}, valids}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 5, 6});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 6);
EXPECT_EQ(childv.null_count(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 7);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 2, 5, 5, 6, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 8);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({1, 2, 5, 6, 7, 8, 9, 10});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, ListOfListOfListsWithValidity)
{
using T = TypeParam;
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<List<List<T>>>, 2 rows
//
// List<List<List<T>>>:
// Length : 2
// Offsets : 0, 2, 4
// Children :
// List<List<T>>:
// Length : 4
// Offsets : 0, 2, 2, 4, 6
// Null count: 1
// 1101
// Children :
// List<T>:
// Length : 6
// Offsets : 0, 2, 4, 6, 8, 11, 12
// Children :
// 1, 2, 3, 4, 10, 20, 30, 40, 50, 60, 70, 0
{
// equivalent to { {{{1, 2}, {3, 4}}, NULL}, {{{10, 20}, {30, 40}}, {{50, 60, 70}, {0}}} }
cudf::test::lists_column_wrapper<T, int32_t> list{
{{{{1, 2}, {3, 4}}, {{5, 6, 7}, {0}}}, valids}, {{{10, 20}, {30, 40}}, {{50, 60, 70}, {0}}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 2);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 4);
EXPECT_EQ(childv.null_count(), 1);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 5);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 2, 4, 6});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 6);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 7);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets(
{0, 2, 4, 6, 8, 11, 12});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
auto child_child_data = child_childv.child();
EXPECT_EQ(child_child_data.size(), 12);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_child_data(
{1, 2, 3, 4, 10, 20, 30, 40, 50, 60, 70, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_data, child_child_data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, EmptyLists)
{
using T = TypeParam;
// 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, int32_t>;
// List<T>, empty
//
// List<T>:
// Length : 0
// Offsets :
// Children :
{
// equivalent to {}
cudf::test::lists_column_wrapper<T> list{};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 0);
}
// List<T>, 1 row
//
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
// equivalent to {}
cudf::test::lists_column_wrapper<T, int32_t> list{LCW{}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
}
// List<T>, 2 rows
//
// List<T>:
// Length : 2
// Offsets : 0, 0, 0
// Children :
{
// equivalent to {}
cudf::test::lists_column_wrapper<T, int32_t> list{LCW{}, LCW{}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 2);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
}
// List<L>, mixed
//
// List<T>:
// Length : 3
// Offsets : 0, 2, 2, 4
// Children :
// 1, 2, 3, 4
{
// equivalent to {{1, 2}, {}, {3, 4}}
cudf::test::lists_column_wrapper<T, int32_t> list{{1, 2}, LCW{}, {3, 4}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 2, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child_data = lcv.child();
EXPECT_EQ(child_data.size(), 4);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({1, 2, 3, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
// List<List<T>>, mixed
//
// List<List<T>>:
// Length : 3
// Offsets : 0, 1, 4, 7
// Children :
// List<int32_t>:
// Length : 7
// Offsets : 0, 0, 2, 2, 4, 4, 8, 8
// Children :
// 1, 2, 3, 4, 5, 6, 7, 8
{
// equivalent to { {{}}, {{1, 2}, {}, {3, 4}}, {{}, {5, 6, 7, 8}, {}} }
cudf::test::lists_column_wrapper<T, int32_t> list{
{LCW{}}, {{1, 2}, LCW{}, {3, 4}}, {LCW{}, {5, 6, 7, 8}, LCW{}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 4, 7});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 7);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 8);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets(
{0, 0, 2, 2, 4, 4, 8, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 8);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({1, 2, 3, 4, 5, 6, 7, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, EmptyListsWithValidity)
{
using T = TypeParam;
// 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, int32_t>;
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<T>, 2 rows
//
// List<T>:
// Length : 2
// Offsets : 0, 0, 0
// Null count: 1
// 01
// Children :
{
// equivalent to {{}, NULL}
cudf::test::lists_column_wrapper<T, int32_t> list{{LCW{}, LCW{}}, valids};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 2);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
}
// List<T>, 3 rows
//
// List<T>:
// Length : 3
// Offsets : 0, 0, 0, 0
// Null count: 1
// 101
// Children :
{
// equivalent to {{}, NULL, {}}
cudf::test::lists_column_wrapper<T, int32_t> list{{LCW{}, {1, 2, 3}, LCW{}}, valids};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
}
// List<T>, 3 rows
//
// List<T>:
// Length : 3
// Offsets : 0, 0, 0, 3
// Null count: 1
// 101
// Children :
// 1, 2, 3
{
// equivalent to {{}, NULL, {1, 2, 3}}
cudf::test::lists_column_wrapper<T, int32_t> list{{LCW{}, LCW{}, {1, 2, 3}}, valids};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
}
// List<List<T>>, mixed
//
// List<List<T>>:
// Length : 3
// Offsets : 0, 1, 1, 4
// Null count: 1
// 101
// Children :
// List<T>:
// Length : 4
// Offsets : 0, 0, 0, 4, 4
// Children :
// 5, 6, 7, 8
{
// equivalent to { {{}}, NULL, {{}, {5, 6, 7, 8}, {}} }
cudf::test::lists_column_wrapper<T, int32_t> list{
{{LCW{}}, {{1, 2}, LCW{}, {3, 4}}, {LCW{}, {5, 6, 7, 8}, LCW{}}}, valids};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 1, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 4);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 5);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 0, 0, 4, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 4);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_data({5, 6, 7, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, IncompleteHierarchies)
{
using T = TypeParam;
// 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, int32_t>;
// List<List<List<T>>>:
// Length : 3
// Offsets : 0, 1, 2, 2
// Children :
// List<List<T>>:
// Length : 2
// Offsets : 0, 1, 1
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
cudf::test::lists_column_wrapper<T, int32_t> list{{{LCW{}}}, {LCW{}}, LCW{}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 2, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 1);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
auto child_child_data = child_childv.child();
EXPECT_EQ(child_child_data.size(), 0);
}
// List<List<List<T>>>:
// Length : 3
// Offsets : 0, 0, 1, 2
// Children :
// List<List<T>>:
// Length : 2
// Offsets : 0, 0, 1
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
cudf::test::lists_column_wrapper<T, int32_t> list{LCW{}, {LCW{}}, {{LCW{}}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 1, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 1);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
auto child_child_data = child_childv.child();
EXPECT_EQ(child_child_data.size(), 0);
}
// List<List<List<T>>>:
// Length : 3
// Offsets : 0, 0, 1, 2
// Children :
// List<List<T>>:
// Length : 2
// Offsets : 0, 1, 1
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 3
// Children :
// 1, 2, 3
{
// { {}, {{{1,2,3}}}, {{}} }
cudf::test::lists_column_wrapper<T, int32_t> list{LCW{}, {{{1, 2, 3}}}, {LCW{}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 1, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 1);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
auto child_child_data = child_childv.child();
EXPECT_EQ(child_child_data.size(), 3);
cudf::test::fixed_width_column_wrapper<T, int32_t> e_child_child_data({1, 2, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_data, child_child_data);
}
// List<List<List<T>>>:
// Length : 3
// Offsets : 0, 1, 2, 2
// Null count: 1
// 011
// Children :
// List<List<T>>:
// Length : 2
// Offsets : 0, 1, 1
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
// { {{{}}}, {{}}, null }
std::vector<bool> valids{true, true, false};
cudf::test::lists_column_wrapper<T, int32_t> list{{{{LCW{}}}, {LCW{}}, LCW{}}, valids.begin()};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 2, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 1);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
}
// List<List<List<T>>>:
// Length : 3
// Offsets : 0, 1, 1, 2
// Null count: 1
// 101
// Children :
// List<List<T>>:
// Length : 1
// Offsets : 0, 1
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
// { {{{}}}, null, {} }
std::vector<bool> valids{true, false, true};
cudf::test::lists_column_wrapper<T, int32_t> list{{{{LCW{}}}, {LCW{}}, LCW{}}, valids.begin()};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 1);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 1);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
}
// List<List<T>>:
// Length : 3
// Offsets : 0, 0, 1, 1
// Null count: 1
// 110
// Children :
// List<T>:
// Length : 1
// Offsets : 0, 0
// Children :
{
// { null, {{}}, {} }
std::vector<bool> valids{false, true, true};
cudf::test::lists_column_wrapper<T, int32_t> list{{{{LCW{}}}, {LCW{}}, LCW{}}, valids.begin()};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 1, 1});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 1);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
}
// List<List<>>:
// Length : 3
// Offsets : 0, 0, 0, 0
// Null count: 3
// 000
// Children :
// List<>:
// Length : 0
// Offsets :
// Children :
{
// { null, null, null }
std::vector<bool> valids{false, false, false};
cudf::test::lists_column_wrapper<T, int32_t> list{{{{LCW{}}}, {LCW{}}, LCW{}}, valids.begin()};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 0);
}
// List<List<>>:
// Length : 3
// Offsets : 0, 0, 0, 0
// Null count: 3
// 000
// Children :
// List<>:
// Length : 0
// Offsets :
// Children :
{
// { null, null, null }
std::vector<bool> valids{false, false, false};
cudf::test::lists_column_wrapper<T, int32_t> list{{LCW{}, {{LCW{}}}, {LCW{}}}, valids.begin()};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
EXPECT_EQ(lcv.null_count(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 0);
}
// List<List<List<>>>:
// Length : 3
// Offsets : 0, 1, 2, 2
// Children :
// List<List<>>:
// Length : 2
// Offsets : 0, 0, 0
// Null count: 1
// 10
// Children :
// List<>:
// Length : 0
// Offsets :
// Children :
{
// { {null}, {{}}, {} }
std::vector<bool> valids{false};
cudf::test::lists_column_wrapper<T, int32_t> list{{{{LCW{}}}, valids.begin()}, {LCW{}}, LCW{}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 2, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 2);
EXPECT_EQ(childv.null_count(), 1);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 0, 0});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 0);
}
// big mix of truncated stuff
// List<List<List<T>
// Length : 4
// Offsets : 0, 1, 3, 3, 5
// Children :
// List<List<T>>:
// Length : 5
// Offsets : 0, 2, 2, 3, 3, 3
// Children :
// List<T>:
// Length : 3
// Offsets : 0, 3, 5, 5
// Children :
// 1, 2, 3, 4, 5
{
// { {{{1, 2, 3}, {4, 5}}}, {{}, {{}}}, {}, {{}, {}} }
cudf::test::lists_column_wrapper<T, int32_t> list{
{{{1, 2, 3}, {4, 5}}}, {LCW{}, {LCW{}}}, LCW{}, {LCW{}, LCW{}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 4);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 5);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 1, 3, 3, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 5);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 6);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 2, 3, 3, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child = childv.child();
cudf::lists_column_view child_childv(child_child);
EXPECT_EQ(child_childv.size(), 3);
auto child_child_offsets = child_childv.offsets();
EXPECT_EQ(child_child_offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_offsets({0, 3, 5, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_offsets, child_child_offsets);
auto child_child_data = child_childv.child();
EXPECT_EQ(child_child_data.size(), 5);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_child_data({1, 2, 3, 4, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_data, e_child_child_data);
}
}
TEST_F(ListColumnWrapperTest, ListOfStrings)
{
// List<string>, 2 rows
//
// List<cudf::string_view>:
// Length : 2
// Offsets : 0, 2, 5
// Children :
// one, two, three, four, five
{
cudf::test::lists_column_wrapper<cudf::string_view> list{{"one", "two"},
{"three", "four", "five"}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 2);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 5});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 5);
cudf::test::strings_column_wrapper e_data({"one", "two", "three", "four", "five"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
}
TEST_F(ListColumnWrapperTest, ListOfListOfStrings)
{
// List<List<string>>, 2 rows
//
// List<List<cudf::string_view>>:
// Length : 2
// Offsets : 0, 2, 4
// Children :
// List<cudf::string_view>:
// Length : 4
// Offsets : 0, 2, 5, 6, 8
// Children :
// one, two, three, four, five, eight, nine, ten
{
cudf::test::lists_column_wrapper<cudf::string_view> list{
{{"one", "two"}, {"three", "four", "five"}}, {{"eight"}, {"nine", "ten"}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 2);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 3);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 4});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 4);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 5);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 5, 6, 8});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_data = childv.child();
EXPECT_EQ(child_data.size(), 8);
cudf::test::strings_column_wrapper e_child_data(
{"one", "two", "three", "four", "five", "eight", "nine", "ten"});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_data, child_data);
}
}
TEST_F(ListColumnWrapperTest, ListOfBools)
{
// List<bool>, 1 row
//
// List<bool>:
// Length : 1
// Offsets : 0, 2
// Children :
// 1, 0
//
{
cudf::test::lists_column_wrapper<bool> list{true, false};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 2);
cudf::test::fixed_width_column_wrapper<bool> e_data({true, false});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
// List<bool>, 1 row
//
// List<bool>:
// Length : 1
// Offsets : 0, 3
// Children :
// 1, 0, 0
//
{
cudf::test::lists_column_wrapper<bool> list{{true, false, false}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 1);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 2);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 3});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 3);
cudf::test::fixed_width_column_wrapper<bool> e_data({true, false, false});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
}
TEST_F(ListColumnWrapperTest, ListOfBoolsWithValidity)
{
auto valids =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; });
// List<bool>, 3 rows
//
// List<bool>:
// Length : 3
// Offsets : 0, 2, 4, 7
// Children :
// 1, NULL, 0, NULL, 0, NULL, 0
{
cudf::test::lists_column_wrapper<bool> list{
{{true, true}, valids}, {{false, true}, valids}, {{false, true, false}, valids}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 4, 7});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto data = lcv.child();
EXPECT_EQ(data.size(), 7);
cudf::test::fixed_width_column_wrapper<bool> e_data(
{true, true, false, true, false, true, false}, valids);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_data, data);
}
}
TEST_F(ListColumnWrapperTest, ListOfListOfBools)
{
// List<List<bool>> 3 rows
//
// List<List<bool>>:
// Length : 3
// Offsets : 0, 2, 5, 6
// Children :
// List<bool>:
// Length : 6
// Offsets : 0, 2, 4, 7, 8, 9, 11
// Children :
// 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
{
cudf::test::lists_column_wrapper<bool> list{
{{false, true}, {true, true}}, {{true, false, true}, {true}, {true}}, {{false, true}}};
cudf::lists_column_view lcv(list);
EXPECT_EQ(lcv.size(), 3);
auto offsets = lcv.offsets();
EXPECT_EQ(offsets.size(), 4);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets({0, 2, 5, 6});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_offsets, offsets);
auto child = lcv.child();
cudf::lists_column_view childv(child);
EXPECT_EQ(childv.size(), 6);
auto child_offsets = childv.offsets();
EXPECT_EQ(child_offsets.size(), 7);
cudf::test::fixed_width_column_wrapper<cudf::size_type> e_child_offsets({0, 2, 4, 7, 8, 9, 11});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_offsets, child_offsets);
auto child_child_data = childv.child();
EXPECT_EQ(child_child_data.size(), 11);
cudf::test::fixed_width_column_wrapper<bool> e_child_child_data(
{false, true, true, true, true, false, true, true, true, false, true});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(e_child_child_data, child_child_data);
}
}
TEST_F(ListColumnWrapperTest, MismatchedHierarchies)
{
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>;
// trying to build a column out of a List<List<int>> column, and a List<int> column
// is not valid if the leaf lists are not empty.
{
auto expect_failure = []() { LCW list{{{1, 2, 3}}, {4, 5}}; };
EXPECT_THROW(expect_failure(), cudf::logic_error);
}
}
TYPED_TEST(ListColumnWrapperTestTyped, ListsOfStructs)
{
using T = TypeParam;
auto num_struct_rows = 8;
auto numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 4, 5, 6, 7, 8};
auto bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto struct_column = cudf::test::structs_column_wrapper{{numeric_column, bool_column}}.release();
EXPECT_EQ(struct_column->size(), num_struct_rows);
EXPECT_TRUE(!struct_column->nullable());
auto lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 8}.release();
auto num_lists = lists_column_offsets->size() - 1;
auto lists_column =
make_lists_column(num_lists, std::move(lists_column_offsets), std::move(struct_column), 0, {});
// Check if child column is unchanged.
auto expected_numeric_column =
cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 4, 5, 6, 7, 8};
auto expected_bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto expected_struct_column =
cudf::test::structs_column_wrapper{{expected_numeric_column, expected_bool_column}}.release();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_struct_column,
cudf::lists_column_view(*lists_column).child());
}
TYPED_TEST(ListColumnWrapperTestTyped, ListsOfStructsWithValidity)
{
using T = TypeParam;
auto num_struct_rows = 8;
auto numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{1, 2, 3, 4, 5, 6, 7, 8}, {1, 1, 1, 1, 0, 0, 0, 0}};
auto bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto struct_column = cudf::test::structs_column_wrapper{{numeric_column, bool_column}}.release();
EXPECT_EQ(struct_column->size(), num_struct_rows);
EXPECT_TRUE(!struct_column->nullable());
auto lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 8}.release();
auto list_null_mask = {1, 1, 0};
auto num_lists = lists_column_offsets->size() - 1;
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(list_null_mask.begin(), list_null_mask.end());
auto lists_column = cudf::make_lists_column(num_lists,
std::move(lists_column_offsets),
std::move(struct_column),
null_count,
std::move(null_mask));
// Check if child column is unchanged.
auto expected_numeric_column =
cudf::test::fixed_width_column_wrapper<T, int32_t>{{1, 2, 3, 4}, {1, 1, 1, 1}};
auto expected_bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1};
auto expected_struct_column =
cudf::test::structs_column_wrapper{{expected_numeric_column, expected_bool_column}}.release();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_struct_column,
cudf::lists_column_view(*lists_column).child());
}
TYPED_TEST(ListColumnWrapperTestTyped, ListsOfListsOfStructs)
{
using T = TypeParam;
auto num_struct_rows = 8;
auto numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 4, 5, 6, 7, 8};
auto bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto struct_column = cudf::test::structs_column_wrapper{{numeric_column, bool_column}}.release();
EXPECT_EQ(struct_column->size(), num_struct_rows);
EXPECT_TRUE(!struct_column->nullable());
auto lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 8}.release();
auto num_lists = lists_column_offsets->size() - 1;
auto lists_column =
make_lists_column(num_lists, std::move(lists_column_offsets), std::move(struct_column), 0, {});
auto lists_of_lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 3}.release();
auto num_lists_of_lists = lists_of_lists_column_offsets->size() - 1;
auto lists_of_lists_of_structs_column = make_lists_column(
num_lists_of_lists, std::move(lists_of_lists_column_offsets), std::move(lists_column), 0, {});
// Check if child column is unchanged.
auto expected_numeric_column =
cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 4, 5, 6, 7, 8};
auto expected_bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto expected_struct_column =
cudf::test::structs_column_wrapper{{expected_numeric_column, expected_bool_column}}.release();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(
*expected_struct_column,
cudf::lists_column_view{cudf::lists_column_view{*lists_of_lists_of_structs_column}.child()}
.child());
}
TYPED_TEST(ListColumnWrapperTestTyped, ListsOfListsOfStructsWithValidity)
{
using T = TypeParam;
auto num_struct_rows = 8;
auto numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{
{1, 2, 3, 4, 5, 6, 7, 8}, {1, 1, 1, 1, 0, 0, 0, 0}};
auto bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1, 0, 0, 0, 0};
auto struct_column = cudf::test::structs_column_wrapper{{numeric_column, bool_column}}.release();
EXPECT_EQ(struct_column->size(), num_struct_rows);
EXPECT_TRUE(!struct_column->nullable());
auto lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 8}.release();
auto num_lists = lists_column_offsets->size() - 1;
auto list_null_mask = {1, 1, 0};
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(list_null_mask.begin(), list_null_mask.end());
auto lists_column = cudf::make_lists_column(num_lists,
std::move(lists_column_offsets),
std::move(struct_column),
null_count,
std::move(null_mask));
auto lists_of_lists_column_offsets =
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 3}.release();
auto num_lists_of_lists = lists_of_lists_column_offsets->size() - 1;
auto list_of_lists_null_mask = {1, 0};
std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(
list_of_lists_null_mask.begin(), list_of_lists_null_mask.end());
auto lists_of_lists_of_structs_column =
cudf::make_lists_column(num_lists_of_lists,
std::move(lists_of_lists_column_offsets),
std::move(lists_column),
null_count,
std::move(null_mask));
// Check if child column is unchanged.
auto expected_numeric_column =
cudf::test::fixed_width_column_wrapper<T, int32_t>{{1, 2, 3, 4}, {1, 1, 1, 1}};
auto expected_bool_column = cudf::test::fixed_width_column_wrapper<bool>{1, 1, 1, 1};
auto expected_struct_column =
cudf::test::structs_column_wrapper{{expected_numeric_column, expected_bool_column}}.release();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(
*expected_struct_column,
cudf::lists_column_view{cudf::lists_column_view{*lists_of_lists_of_structs_column}.child()}
.child());
}
TYPED_TEST(ListColumnWrapperTestTyped, LargeListsOfStructsWithValidity)
{
using T = TypeParam;
auto num_struct_rows = 10000;
// Creating Struct<Numeric, Bool>.
auto numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(num_struct_rows),
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 1; })};
auto bool_iterator =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 3 == 0; });
auto bool_column =
cudf::test::fixed_width_column_wrapper<bool>(bool_iterator, bool_iterator + num_struct_rows);
auto struct_validity_iterator =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 5 == 0; });
auto struct_column =
cudf::test::structs_column_wrapper{
{numeric_column, bool_column},
std::vector<bool>(struct_validity_iterator, struct_validity_iterator + num_struct_rows)}
.release();
EXPECT_EQ(struct_column->size(), num_struct_rows);
// Now, use struct_column to create a list column.
// Each list has 50 elements.
auto num_list_rows = num_struct_rows / 50;
auto list_offset_iterator =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 50; });
auto list_offset_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>(
list_offset_iterator, list_offset_iterator + num_list_rows + 1)
.release();
auto lists_column = make_lists_column(
num_list_rows, std::move(list_offset_column), std::move(struct_column), 0, {});
// List construction succeeded.
// Verify that the child is unchanged.
auto expected_numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(num_struct_rows),
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 1; })};
auto expected_bool_column =
cudf::test::fixed_width_column_wrapper<bool>(bool_iterator, bool_iterator + num_struct_rows);
auto expected_struct_column =
cudf::test::structs_column_wrapper{
{expected_numeric_column, expected_bool_column},
std::vector<bool>(struct_validity_iterator, struct_validity_iterator + num_struct_rows)}
.release();
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_struct_column,
cudf::lists_column_view(*lists_column).child());
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/type_list_tests.cpp
|
/*
* Copyright (c) 2019-2021, 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/cudf_gtest.hpp>
#include <cudf_test/type_list_utilities.hpp>
using namespace cudf::test; // this will make reading code way easier
namespace {
// Work around to remove parentheses surrounding a type
template <typename T>
struct argument_type;
template <typename T, typename U>
struct argument_type<T(U)> {
using type = U;
};
} // namespace
/**
* @brief Performs a compile-time check that two types are equivalent.
*
* @note In order to work around commas in macros, any type containing commas
* should be wrapped in parentheses.
*
* Example:
* ```
* EXPECT_SAME_TYPE(int, int);
*
* EXPECT_SAME_TYPE(int, float); // compile error
*
* // Parentheses around types with commas
* EXPECT_SAME_TYPE((std::map<int, float>), (std::map<int, float>));
* ```
*/
#define EXPECT_SAME_TYPE(expected, actual) \
static_assert( \
std::is_same_v<argument_type<void(expected)>::type, argument_type<void(actual)>::type>, "");
/**
* @brief Return a string of the demangled name of a type `T`
*
* This is useful for debugging Type list utilities.
*
* @tparam T The type whose name is returned as a string
* @return std::string The demangled name of `T`
*/
template <typename T>
std::string type_name()
{
int status;
char* realname;
realname = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
std::string name{realname};
free(realname);
return name;
}
TEST(TypeList, GetSize)
{
static_assert(GetSize<Types<>> == 0, "");
static_assert(GetSize<Types<int>> == 1, "");
static_assert(GetSize<Types<int, int>> == 2, "");
static_assert(GetSize<Types<int, void>> == 2, "");
}
TEST(TypeList, GetType)
{
EXPECT_SAME_TYPE((GetType<int, 0>), int);
EXPECT_SAME_TYPE((GetType<Types<int, float, double>, 0>), int);
EXPECT_SAME_TYPE((GetType<Types<int, float, double>, 1>), float);
EXPECT_SAME_TYPE((GetType<Types<int, float, double>, 2>), double);
}
TEST(TypeList, Concat)
{
EXPECT_SAME_TYPE(Concat<>, Types<>);
EXPECT_SAME_TYPE((Concat<Types<long, void*, char*>>), (Types<long, void*, char*>));
EXPECT_SAME_TYPE((Concat<Types<long, void*, char*>, Types<float, char, double>>),
(Types<long, void*, char*, float, char, double>));
EXPECT_SAME_TYPE(
(Concat<Types<long, void*, char*>, Types<float, char, double>, Types<int*, long*, unsigned>>),
(Types<long, void*, char*, float, char, double, int*, long*, unsigned>));
}
TEST(TypeList, Flatten)
{
EXPECT_SAME_TYPE(Flatten<Types<>>, Types<>);
EXPECT_SAME_TYPE(Flatten<Types<int>>, Types<int>);
EXPECT_SAME_TYPE((Flatten<Types<int, double>>), (Types<int, double>));
EXPECT_SAME_TYPE((Flatten<Types<Types<int, double>, float>>), (Types<int, double, float>));
EXPECT_SAME_TYPE((Flatten<Types<Types<int, Types<double>>, float>>), (Types<int, double, float>));
}
TEST(TypeList, CrossProduct)
{
EXPECT_SAME_TYPE(CrossProduct<>, Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<>, Types<int>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<>, Types<int, double>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<>, Types<int, double>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<>, Types<>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<int>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<>>), Types<>);
EXPECT_SAME_TYPE((CrossProduct<Types<int>, Types<int>>), (Types<Types<int, int>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<int>>),
(Types<Types<int, int>, Types<double, int>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int>, Types<double, char>>),
(Types<Types<int, double>, Types<int, char>>));
EXPECT_SAME_TYPE(
(CrossProduct<Types<int, double>, Types<short, char>>),
(Types<Types<int, short>, Types<int, char>, Types<double, short>, Types<double, char>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<int>, Types<float>>),
(Types<Types<int, int, float>, Types<double, int, float>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<int>, Types<float, char>>),
(Types<Types<int, int, float>,
Types<int, int, char>,
Types<double, int, float>,
Types<double, int, char>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int, double>, Types<int, short>, Types<float, char>>),
(Types<Types<int, int, float>,
Types<int, int, char>,
Types<int, short, float>,
Types<int, short, char>,
Types<double, int, float>,
Types<double, int, char>,
Types<double, short, float>,
Types<double, short, char>>));
EXPECT_SAME_TYPE((CrossProduct<Types<int, float>, int>),
(Types<Types<int, int>, Types<float, int>>));
EXPECT_SAME_TYPE((CrossProduct<int, Types<int, float>>),
(Types<Types<int, int>, Types<int, float>>));
}
TEST(TypeList, AllSame)
{
static_assert(AllSame::Call<Types<int, int>>::value, "");
static_assert(AllSame::Call<Types<int, int>>::value, "");
static_assert(!AllSame::Call<Types<bool, int>>::value, "");
static_assert(AllSame::Call<int, int>::value, "");
static_assert(!AllSame::Call<int, bool>::value, "");
static_assert(AllSame::Call<int, int, int>::value, "");
static_assert(!AllSame::Call<int, float, int>::value, "");
static_assert(!AllSame::Call<int, int, float>::value, "");
}
TEST(TypeList, Exists)
{
static_assert(Exists<int, Types<int, char, float>>, "");
static_assert(!Exists<int, Types<double, char, float>>, "");
static_assert(!Exists<int, Types<>>, "");
static_assert(Exists<int, Types<double, char, float, int>>, "");
static_assert(!Exists<int, Types<double>>, "");
static_assert(Exists<int, Types<int>>, "");
}
TEST(TypeList, ContainedIn)
{
static_assert(ContainedIn<Types<Types<int, char>>>::Call<Types<int, char>>::value, "");
static_assert(!ContainedIn<Types<Types<int, char>>>::Call<Types<int, float>>::value, "");
static_assert(!ContainedIn<Types<>>::Call<Types<int, float>>::value, "");
static_assert(
ContainedIn<Types<Types<int, float>, Types<char, char>>>::Call<Types<int, float>>::value, "");
static_assert(
!ContainedIn<Types<Types<int, float>, Types<char, char>>>::Call<Types<int, double>>::value, "");
static_assert(ContainedIn<Types<Types<int, float>, Types<>>>::Call<Types<>>::value, "");
static_assert(!ContainedIn<Types<Types<int, float>, Types<int>>>::Call<Types<>>::value, "");
}
TEST(TypeList, RemoveIf)
{
EXPECT_SAME_TYPE((RemoveIf<AllSame, Types<>>), Types<>);
EXPECT_SAME_TYPE((RemoveIf<AllSame, Types<Types<int, int, int>>>), Types<>);
EXPECT_SAME_TYPE((RemoveIf<AllSame, Types<Types<int, float, int>>>),
(Types<Types<int, float, int>>));
EXPECT_SAME_TYPE(
(RemoveIf<AllSame,
Types<Types<int, float, char>, Types<int, int, int>, Types<int, int, char>>>),
(Types<Types<int, float, char>, Types<int, int, char>>));
EXPECT_SAME_TYPE(
(RemoveIf<AllSame,
Types<Types<int, float, char>, Types<int, float, char>, Types<int, int, char>>>),
(Types<Types<int, float, char>, Types<int, float, char>, Types<int, int, char>>));
EXPECT_SAME_TYPE((RemoveIf<ContainedIn<Types<Types<int, char>, Types<float, int>>>,
Types<Types<char, char>, Types<float, int>, Types<int, int>>>),
(Types<Types<char, char>, Types<int, int>>));
}
TEST(TypeList, Transform)
{
EXPECT_SAME_TYPE((Transform<Repeat<2>, Types<int, float>>),
(Types<Types<int, int>, Types<float, float>>));
EXPECT_SAME_TYPE((Transform<Repeat<1>, Types<int, float>>), (Types<Types<int>, Types<float>>));
EXPECT_SAME_TYPE((Transform<Repeat<0>, Types<int, float>>), (Types<Types<>, Types<>>));
EXPECT_SAME_TYPE((Transform<Repeat<2>, Types<int>>), (Types<Types<int, int>>));
EXPECT_SAME_TYPE((Transform<Repeat<1>, Types<int>>), Types<Types<int>>);
EXPECT_SAME_TYPE((Transform<Repeat<0>, Types<>>), Types<>);
}
TEST(TypeList, Append)
{
EXPECT_SAME_TYPE(Append<Types<>>, Types<>);
EXPECT_SAME_TYPE((Append<Types<>, int>), Types<int>);
EXPECT_SAME_TYPE(Append<Types<int>>, Types<int>);
EXPECT_SAME_TYPE((Append<Types<int>, float>), (Types<int, float>));
EXPECT_SAME_TYPE((Append<Types<int>, float, char>), (Types<int, float, char>));
}
TEST(TypeList, Remove)
{
EXPECT_SAME_TYPE((Remove<Types<int, float, char>, 1>), (Types<int, char>));
EXPECT_SAME_TYPE((Remove<Types<int, float, char>, 0, 2>), Types<float>);
EXPECT_SAME_TYPE((Remove<Types<int, char>>), (Types<int, char>));
EXPECT_SAME_TYPE((Remove<Types<int>, 0>), Types<>);
EXPECT_SAME_TYPE((Remove<Types<int, char>, 0, 1>), Types<>);
EXPECT_SAME_TYPE(Remove<Types<>>, Types<>);
}
TEST(TypeList, Unique)
{
EXPECT_SAME_TYPE(Unique<Types<>>, Types<>);
EXPECT_SAME_TYPE((Unique<Types<int, char, float>>), (Types<int, char, float>));
EXPECT_SAME_TYPE((Unique<Types<int, int, float>>), (Types<int, float>));
EXPECT_SAME_TYPE((Unique<Types<int, char, char, float>>), (Types<int, char, float>));
EXPECT_SAME_TYPE((Unique<Types<int, char, float, float>>), (Types<int, char, float>));
EXPECT_SAME_TYPE((Unique<Types<int, float, int, float>>), (Types<int, float>));
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/column_wrapper_tests.cpp
|
/*
* Copyright (c) 2019-2021, 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/detail/iterator.cuh>
template <typename T>
struct FixedWidthColumnWrapperTest : public cudf::test::BaseFixture,
cudf::test::UniformRandomGenerator<cudf::size_type> {
FixedWidthColumnWrapperTest() : cudf::test::UniformRandomGenerator<cudf::size_type>{1000, 5000} {}
auto size() { return this->generate(); }
auto data_type() { return cudf::data_type{cudf::type_to_id<T>()}; }
};
TYPED_TEST_SUITE(FixedWidthColumnWrapperTest, cudf::test::FixedWidthTypes);
TYPED_TEST(FixedWidthColumnWrapperTest, EmptyIterator)
{
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> col(
sequence, sequence);
cudf::column_view view = col;
EXPECT_EQ(view.size(), 0);
EXPECT_EQ(view.head(), nullptr);
EXPECT_EQ(view.type(), this->data_type());
EXPECT_FALSE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, EmptyList)
{
cudf::test::fixed_width_column_wrapper<TypeParam> col{};
cudf::column_view view = col;
EXPECT_EQ(view.size(), 0);
EXPECT_EQ(view.head(), nullptr);
EXPECT_EQ(view.type(), this->data_type());
EXPECT_FALSE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NonNullableIteratorConstructor)
{
auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; });
auto size = this->size();
cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> col(
sequence, sequence + size);
cudf::column_view view = col;
EXPECT_EQ(view.size(), size);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_FALSE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NonNullableListConstructor)
{
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4, 5});
cudf::column_view view = col;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_FALSE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullableIteratorConstructorAllValid)
{
auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; });
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
auto size = this->size();
cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> col(
sequence, sequence + size, all_valid);
cudf::column_view view = col;
EXPECT_EQ(view.size(), size);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullableListConstructorAllValid)
{
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4, 5}, all_valid);
cudf::column_view view = col;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullableIteratorConstructorAllNull)
{
auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; });
auto all_null = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return false; });
auto size = this->size();
cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> col(
sequence, sequence + size, all_null);
cudf::column_view view = col;
EXPECT_EQ(view.size(), size);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_TRUE(view.has_nulls());
EXPECT_EQ(view.null_count(), size);
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullableListConstructorAllNull)
{
auto all_null = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return false; });
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4, 5}, all_null);
cudf::column_view view = col;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_TRUE(view.has_nulls());
EXPECT_EQ(view.null_count(), 5);
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullablePairListConstructorAllNull)
{
using p = std::pair<int32_t, bool>;
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col(
{p{1, false}, p{2, false}, p{3, false}, p{4, false}, p{5, false}});
cudf::column_view view = col;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_TRUE(view.has_nulls());
EXPECT_EQ(view.null_count(), 5);
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, NullablePairListConstructorAllNullMatch)
{
auto odd_valid =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 != 0; });
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> match_col({1, 2, 3, 4, 5}, odd_valid);
cudf::column_view match_view = match_col;
using p = std::pair<int32_t, bool>;
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({p{1, odd_valid[0]},
p{2, odd_valid[1]},
p{3, odd_valid[2]},
p{4, odd_valid[3]},
p{5, odd_valid[4]}});
cudf::column_view view = col;
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view, match_view);
}
TYPED_TEST(FixedWidthColumnWrapperTest, ReleaseWrapperAllValid)
{
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4, 5}, all_valid);
auto colPtr = col.release();
cudf::column_view view = *colPtr;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(FixedWidthColumnWrapperTest, ReleaseWrapperAllNull)
{
auto all_null = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return false; });
cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({1, 2, 3, 4, 5}, all_null);
auto colPtr = col.release();
cudf::column_view view = *colPtr;
EXPECT_EQ(view.size(), 5);
EXPECT_NE(nullptr, view.head());
EXPECT_EQ(view.type(), this->data_type());
EXPECT_TRUE(view.nullable());
EXPECT_TRUE(view.has_nulls());
EXPECT_EQ(view.null_count(), 5);
EXPECT_EQ(view.offset(), 0);
}
template <typename T>
struct StringsColumnWrapperTest : public cudf::test::BaseFixture,
cudf::test::UniformRandomGenerator<cudf::size_type> {
auto data_type() { return cudf::data_type{cudf::type_to_id<T>()}; }
};
TYPED_TEST_SUITE(StringsColumnWrapperTest, cudf::test::StringTypes);
TYPED_TEST(StringsColumnWrapperTest, EmptyList)
{
cudf::test::strings_column_wrapper col;
cudf::column_view view = col;
EXPECT_EQ(view.size(), 0);
EXPECT_EQ(view.head(), nullptr);
EXPECT_EQ(view.type(), this->data_type());
EXPECT_FALSE(view.nullable());
EXPECT_FALSE(view.has_nulls());
EXPECT_EQ(view.offset(), 0);
}
TYPED_TEST(StringsColumnWrapperTest, NullablePairListConstructorAllNull)
{
using p = std::pair<std::string, bool>;
cudf::test::strings_column_wrapper col(
{p{"a", false}, p{"string", false}, p{"test", false}, p{"for", false}, p{"nulls", false}});
cudf::strings_column_view view = cudf::column_view(col);
constexpr auto count = 5;
EXPECT_EQ(view.size(), count);
EXPECT_EQ(view.offsets().size(), count + 1);
// all null entries results in no data allocated to chars
EXPECT_EQ(nullptr, view.chars().head());
EXPECT_NE(nullptr, view.offsets().head());
EXPECT_TRUE(view.has_nulls());
EXPECT_EQ(view.null_count(), 5);
}
TYPED_TEST(StringsColumnWrapperTest, NullablePairListConstructorAllNullMatch)
{
auto odd_valid =
cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 != 0; });
cudf::test::strings_column_wrapper match_col({"a", "string", "", "test", "for", "nulls"},
odd_valid);
cudf::column_view match_view = match_col;
using p = std::pair<std::string, bool>;
cudf::test::strings_column_wrapper col({p{"a", odd_valid[0]},
p{"string", odd_valid[1]},
p{"", odd_valid[2]},
p{"test", odd_valid[3]},
p{"for", odd_valid[4]},
p{"nulls", odd_valid[5]}});
cudf::column_view view = col;
CUDF_TEST_EXPECT_COLUMNS_EQUAL(view, match_view);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/column_utilities_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/strings/strings_column_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/type_lists.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <type_traits>
template <typename T>
struct ColumnUtilitiesTest : public cudf::test::BaseFixture {
cudf::test::UniformRandomGenerator<cudf::size_type> random;
ColumnUtilitiesTest() : random{1000, 5000} {}
auto size() { return random.generate(); }
auto data_type() { return cudf::data_type{cudf::type_to_id<T>()}; }
};
template <typename T>
struct ColumnUtilitiesTestIntegral : public cudf::test::BaseFixture {};
template <typename T>
struct ColumnUtilitiesTestFloatingPoint : public cudf::test::BaseFixture {};
template <typename T>
struct ColumnUtilitiesTestFixedPoint : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ColumnUtilitiesTest, cudf::test::FixedWidthTypes);
TYPED_TEST_SUITE(ColumnUtilitiesTestIntegral, cudf::test::IntegralTypes);
TYPED_TEST_SUITE(ColumnUtilitiesTestFloatingPoint, cudf::test::FloatingPointTypes);
TYPED_TEST_SUITE(ColumnUtilitiesTestFixedPoint, cudf::test::FixedPointTypes);
TYPED_TEST(ColumnUtilitiesTest, NonNullableToHost)
{
auto sequence = cudf::detail::make_counting_transform_iterator(
0, [](auto i) { return cudf::test::make_type_param_scalar<TypeParam>(i); });
auto size = this->size();
std::vector<TypeParam> data(sequence, sequence + size);
cudf::test::fixed_width_column_wrapper<TypeParam> col(data.begin(), data.end());
auto host_data = cudf::test::to_host<TypeParam>(col);
EXPECT_TRUE(std::equal(data.begin(), data.end(), host_data.first.begin()));
}
TYPED_TEST(ColumnUtilitiesTest, NonNullableToHostWithOffset)
{
auto sequence = cudf::detail::make_counting_transform_iterator(
0, [](auto i) { return cudf::test::make_type_param_scalar<TypeParam>(i); });
auto const size = this->size();
auto const split = 2;
auto data = std::vector<TypeParam>(sequence, sequence + size);
auto expected_data = std::vector<TypeParam>(sequence + split, sequence + size);
auto col = cudf::test::fixed_width_column_wrapper<TypeParam>(data.begin(), data.end());
auto const splits = std::vector<cudf::size_type>{split};
auto result = cudf::split(col, splits);
auto host_data = cudf::test::to_host<TypeParam>(result.back());
EXPECT_TRUE(std::equal(expected_data.begin(), expected_data.end(), host_data.first.begin()));
}
TYPED_TEST(ColumnUtilitiesTest, NullableToHostWithOffset)
{
auto sequence = cudf::detail::make_counting_transform_iterator(
0, [](auto i) { return cudf::test::make_type_param_scalar<TypeParam>(i); });
auto split = 2;
auto size = this->size();
auto valid = cudf::detail::make_counting_transform_iterator(
0, [&split](auto i) { return i <= 10 and i > split; });
std::vector<TypeParam> data(sequence, sequence + size);
std::vector<TypeParam> expected_data(sequence + split, sequence + size);
cudf::test::fixed_width_column_wrapper<TypeParam> col(data.begin(), data.end(), valid);
std::vector<cudf::size_type> splits{split};
std::vector<cudf::column_view> result = cudf::split(col, splits);
auto host_data = cudf::test::to_host<TypeParam>(result.back());
EXPECT_TRUE(std::equal(expected_data.begin(), expected_data.end(), host_data.first.begin()));
auto masks = std::get<0>(cudf::test::detail::make_null_mask_vector(valid + split, valid + size));
EXPECT_TRUE(cudf::test::validate_host_masks(masks, host_data.second, expected_data.size()));
}
TYPED_TEST(ColumnUtilitiesTest, NullableToHostAllValid)
{
auto sequence = cudf::detail::make_counting_transform_iterator(
0, [](auto i) { return cudf::test::make_type_param_scalar<TypeParam>(i); });
auto all_valid = thrust::make_constant_iterator<bool>(true);
auto size = this->size();
std::vector<TypeParam> data(sequence, sequence + size);
cudf::test::fixed_width_column_wrapper<TypeParam> col(data.begin(), data.end(), all_valid);
auto host_data = cudf::test::to_host<TypeParam>(col);
EXPECT_TRUE(std::equal(data.begin(), data.end(), host_data.first.begin()));
auto masks = std::get<0>(cudf::test::detail::make_null_mask_vector(all_valid, all_valid + size));
EXPECT_TRUE(cudf::test::validate_host_masks(masks, host_data.second, size));
}
struct ColumnUtilitiesEquivalenceTest : public cudf::test::BaseFixture {};
TEST_F(ColumnUtilitiesEquivalenceTest, DoubleTest)
{
cudf::test::fixed_width_column_wrapper<double> col1{10. / 3, 22. / 7};
cudf::test::fixed_width_column_wrapper<double> col2{31. / 3 - 21. / 3, 19. / 7 + 3. / 7};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(col1, col2);
}
TEST_F(ColumnUtilitiesEquivalenceTest, NullabilityTest)
{
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
cudf::test::fixed_width_column_wrapper<double> col1{1, 2, 3};
cudf::test::fixed_width_column_wrapper<double> col2({1, 2, 3}, all_valid);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(col1, col2);
}
struct ColumnUtilitiesStringsTest : public cudf::test::BaseFixture {};
TEST_F(ColumnUtilitiesStringsTest, StringsToHost)
{
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
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 host_data = cudf::test::to_host<std::string>(strings);
auto result_itr = host_data.first.begin();
for (auto itr = h_strings.begin(); itr != h_strings.end(); ++itr, ++result_itr) {
if (*itr) { EXPECT_TRUE((*result_itr) == (*itr)); }
}
}
TEST_F(ColumnUtilitiesStringsTest, StringsToHostAllNulls)
{
std::vector<char const*> h_strings{nullptr, nullptr, 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; }));
auto host_data = cudf::test::to_host<std::string>(strings);
auto results = host_data.first;
EXPECT_EQ(std::size_t{3}, host_data.first.size());
EXPECT_TRUE(std::all_of(results.begin(), results.end(), [](auto s) { return s.empty(); }));
}
TYPED_TEST(ColumnUtilitiesTestFixedPoint, NonNullableToHost)
{
using namespace numeric;
using decimalXX = TypeParam;
using rep = cudf::device_storage_type_t<decimalXX>;
auto const scale = scale_type{-2};
auto to_fp = [&](auto i) { return decimalXX{i, scale}; };
auto to_rep = [](auto i) { return i * 100; };
auto fps = cudf::detail::make_counting_transform_iterator(0, to_fp);
auto reps = cudf::detail::make_counting_transform_iterator(0, to_rep);
auto const size = 1000;
auto const expected = std::vector<decimalXX>(fps, fps + size);
auto const col = cudf::test::fixed_point_column_wrapper<rep>(reps, reps + size, scale);
auto const host_data = cudf::test::to_host<decimalXX>(col);
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), host_data.first.begin()));
}
TYPED_TEST(ColumnUtilitiesTestFixedPoint, NonNullableToHostWithOffset)
{
using namespace numeric;
using decimalXX = TypeParam;
using rep = cudf::device_storage_type_t<decimalXX>;
auto const scale = scale_type{-2};
auto to_fp = [&](auto i) { return decimalXX{i, scale}; };
auto to_rep = [](auto i) { return i * 100; };
auto fps = cudf::detail::make_counting_transform_iterator(0, to_fp);
auto reps = cudf::detail::make_counting_transform_iterator(0, to_rep);
auto const size = 1000;
auto const split = cudf::size_type{2};
auto const expected = std::vector<decimalXX>(fps + split, fps + size);
auto const col = cudf::test::fixed_point_column_wrapper<rep>(reps, reps + size, scale);
auto const splits = std::vector<cudf::size_type>{split};
auto result = cudf::split(col, splits);
auto host_data = cudf::test::to_host<decimalXX>(result.back());
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), host_data.first.begin()));
}
struct ColumnUtilitiesListsTest : public cudf::test::BaseFixture {};
TEST_F(ColumnUtilitiesListsTest, Equivalence)
{
// list<int>, nullable vs. non-nullable
{
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
cudf::test::lists_column_wrapper<int> a{{1, 2, 3}, {5, 6}, {8, 9}, {10}, {14, 15}};
cudf::test::lists_column_wrapper<int> b{{{1, 2, 3}, {5, 6}, {8, 9}, {10}, {14, 15}}, all_valid};
// properties
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUIVALENT(a, b);
EXPECT_FALSE(cudf::test::detail::expect_column_properties_equal(
a, b, cudf::test::debug_output_level::QUIET));
// values
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(a, b);
EXPECT_FALSE(
cudf::test::detail::expect_columns_equal(a, b, cudf::test::debug_output_level::QUIET));
}
// list<list<int>>, nullable vs. non-nullable
{
auto all_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; });
cudf::test::lists_column_wrapper<int> a{{{1, 2, 3}, {5, 6}}, {{8, 9}, {10}}, {{14, 15}}};
cudf::test::lists_column_wrapper<int> b{{{{1, 2, 3}, {5, 6}}, {{8, 9}, {10}}, {{14, 15}}},
all_valid};
// properties
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUIVALENT(a, b);
EXPECT_FALSE(cudf::test::detail::expect_column_properties_equal(
a, b, cudf::test::debug_output_level::QUIET));
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(a, b);
EXPECT_FALSE(
cudf::test::detail::expect_columns_equal(a, b, cudf::test::debug_output_level::QUIET));
}
}
TEST_F(ColumnUtilitiesListsTest, DifferingRowCounts)
{
cudf::test::fixed_width_column_wrapper<int> a{1, 1, 1, 1};
cudf::test::fixed_width_column_wrapper<int> b{1, 1, 1, 1, 1};
EXPECT_FALSE(
cudf::test::detail::expect_columns_equal(a, b, cudf::test::debug_output_level::QUIET));
EXPECT_FALSE(cudf::test::detail::expect_column_properties_equal(
a, b, cudf::test::debug_output_level::QUIET));
EXPECT_FALSE(
cudf::test::detail::expect_columns_equivalent(a, b, cudf::test::debug_output_level::QUIET));
EXPECT_FALSE(cudf::test::detail::expect_column_properties_equivalent(
a, b, cudf::test::debug_output_level::QUIET));
}
TEST_F(ColumnUtilitiesListsTest, UnsanitaryLists)
{
// unsanitary
//
// List<int32_t>:
// Length : 1
// Offsets : 0, 3
// Null count: 1
// 0
// 0, 1, 2
std::vector<std::unique_ptr<cudf::column>> children;
children.emplace_back(
std::move(cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 3}.release()));
children.emplace_back(std::move(cudf::test::fixed_width_column_wrapper<int>{0, 1, 2}.release()));
auto l0 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::LIST},
1,
rmm::device_buffer{},
cudf::create_null_mask(1, cudf::mask_state::ALL_NULL),
1,
std::move(children));
// sanitary
//
// List<int32_t>:
// Length : 1
// Offsets : 0, 0
// Null count: 1
// 0
auto l1 = cudf::test::lists_column_wrapper<int>::make_one_empty_row_column(false);
// equivalent, but not equal
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*l0, l1);
EXPECT_FALSE(
cudf::test::detail::expect_columns_equal(*l0, l1, cudf::test::debug_output_level::QUIET));
}
TEST_F(ColumnUtilitiesListsTest, DifferentPhysicalStructureBeforeConstruction)
{
// list<int>
{
std::vector<bool> valids = {0, 0, 1, 0, 1, 0, 0};
cudf::test::fixed_width_column_wrapper<int> c0_offsets{0, 3, 6, 8, 11, 14, 16, 19};
cudf::test::fixed_width_column_wrapper<int> c0_data{
1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7};
auto [null_mask, null_count] = cudf::test::detail::make_null_mask(valids.begin(), valids.end());
auto c0 = make_lists_column(
7, c0_offsets.release(), c0_data.release(), null_count, std::move(null_mask));
cudf::test::fixed_width_column_wrapper<int> c1_offsets{0, 0, 0, 2, 2, 5, 5, 5};
cudf::test::fixed_width_column_wrapper<int> c1_data{3, 3, 5, 5, 5};
auto c1 = make_lists_column(
7,
c1_offsets.release(),
c1_data.release(),
null_count,
std::get<0>(cudf::test::detail::make_null_mask(valids.begin(), valids.end())));
// properties
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(*c0, *c1);
// values
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*c0, *c1);
}
// list<list<struct<int, float>>>
{
std::vector<bool> level1_valids = {0, 0, 1, 0, 1, 0, 0};
cudf::test::fixed_width_column_wrapper<int> c0_l1_offsets{0, 1, 2, 4, 4, 7, 7, 7};
cudf::test::fixed_width_column_wrapper<int> c0_l2_offsets{0, 1, 2, 5, 6, 7, 10, 14};
cudf::test::fixed_width_column_wrapper<int> c0_l3_ints{
1, 1, -1, -2, -3, 1, 1, -4, -5, -6, -7, -8, -9, -10};
cudf::test::fixed_width_column_wrapper<float> c0_l3_floats{
1, 1, 10, 20, 30, 1, 1, 40, 50, 60, 70, 80, 90, 100};
cudf::test::structs_column_wrapper c0_l2_data({c0_l3_ints, c0_l3_floats});
std::vector<bool> c0_l2_valids = {1, 1, 1, 0, 0, 1, 1};
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(c0_l2_valids.begin(), c0_l2_valids.end());
auto c0_l2 = make_lists_column(
7, c0_l2_offsets.release(), c0_l2_data.release(), null_count, std::move(null_mask));
std::tie(null_mask, null_count) =
cudf::test::detail::make_null_mask(level1_valids.begin(), level1_valids.end());
auto c0 = make_lists_column(
7, c0_l1_offsets.release(), std::move(c0_l2), null_count, std::move(null_mask));
cudf::test::fixed_width_column_wrapper<int> c1_l1_offsets{0, 0, 0, 2, 2, 5, 5, 5};
cudf::test::fixed_width_column_wrapper<int> c1_l2_offsets{0, 3, 3, 3, 6, 10};
cudf::test::fixed_width_column_wrapper<int> c1_l3_ints{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10};
cudf::test::fixed_width_column_wrapper<float> c1_l3_floats{
10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
cudf::test::structs_column_wrapper c1_l2_data({c1_l3_ints, c1_l3_floats});
std::vector<bool> c1_l2_valids = {1, 0, 0, 1, 1};
std::tie(null_mask, null_count) =
cudf::test::detail::make_null_mask(c1_l2_valids.begin(), c1_l2_valids.end());
auto c1_l2 = make_lists_column(
5, c1_l2_offsets.release(), c1_l2_data.release(), null_count, std::move(null_mask));
std::tie(null_mask, null_count) =
cudf::test::detail::make_null_mask(level1_valids.begin(), level1_valids.end());
auto c1 = make_lists_column(
7, c1_l1_offsets.release(), std::move(c1_l2), null_count, std::move(null_mask));
// properties
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(*c0, *c1);
// values
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*c0, *c1);
}
}
struct ColumnUtilitiesStructsTest : public cudf::test::BaseFixture {};
TEST_F(ColumnUtilitiesStructsTest, Properties)
{
cudf::test::strings_column_wrapper s0_scol0{"mno", "jkl", "ghi", "def", "abc"};
cudf::test::fixed_width_column_wrapper<float> s0_scol1{5, 4, 3, 2, 1};
cudf::test::strings_column_wrapper s0_sscol0{"5555", "4444", "333", "22", "1"};
cudf::test::fixed_width_column_wrapper<float> s0_sscol1{50, 40, 30, 20, 10};
cudf::test::lists_column_wrapper<int> s0_sscol2{{1, 2}, {3, 4}, {5}, {6, 7, 8}, {12, 12}};
cudf::test::structs_column_wrapper s0_scol2({s0_sscol0, s0_sscol1, s0_sscol2});
cudf::test::structs_column_wrapper s_col0({s0_scol0, s0_scol1, s0_scol2});
auto all_valid = thrust::make_constant_iterator<bool>(true);
cudf::test::strings_column_wrapper s1_scol0{"mno", "jkl", "ghi", "def", "abc"};
cudf::test::fixed_width_column_wrapper<float> s1_scol1{5, 4, 3, 2, 1};
cudf::test::strings_column_wrapper s1_sscol0{"5555", "4444", "333", "22", "1"};
cudf::test::fixed_width_column_wrapper<float> s1_sscol1{50, 40, 30, 20, 10};
cudf::test::lists_column_wrapper<int> s1_sscol2{{{1, 2}, {3, 4}, {5}, {6, 7, 8}, {12, 12}},
all_valid};
cudf::test::structs_column_wrapper s1_scol2({s1_sscol0, s1_sscol1, s1_sscol2});
cudf::test::structs_column_wrapper s_col1({s1_scol0, s1_scol1, s1_scol2});
// equivalent, but not equal
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUIVALENT(s_col0, s_col1);
EXPECT_FALSE(cudf::test::detail::expect_column_properties_equal(
s_col0, s_col1, cudf::test::debug_output_level::QUIET));
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(s_col0, s_col0);
CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(s_col1, s_col1);
}
TEST_F(ColumnUtilitiesStructsTest, Values)
{
cudf::test::strings_column_wrapper s0_scol0{"mno", "jkl", "ghi", "def", "abc"};
cudf::test::fixed_width_column_wrapper<float> s0_scol1{5, 4, 3, 2, 1};
cudf::test::strings_column_wrapper s0_sscol0{"5555", "4444", "333", "22", "1"};
cudf::test::fixed_width_column_wrapper<float> s0_sscol1{50, 40, 30, 20, 10};
cudf::test::lists_column_wrapper<int> s0_sscol2{{1, 2}, {3, 4}, {5}, {6, 7, 8}, {12, 12}};
cudf::test::structs_column_wrapper s0_scol2({s0_sscol0, s0_sscol1, s0_sscol2});
cudf::test::structs_column_wrapper s_col0({s0_scol0, s0_scol1, s0_scol2});
auto all_valid = thrust::make_constant_iterator<bool>(true);
cudf::test::strings_column_wrapper s1_scol0{"mno", "jkl", "ghi", "def", "abc"};
cudf::test::fixed_width_column_wrapper<float> s1_scol1{5, 4, 3, 2, 1};
cudf::test::strings_column_wrapper s1_sscol0{"5555", "4444", "333", "22", "1"};
cudf::test::fixed_width_column_wrapper<float> s1_sscol1{50, 40, 30, 20, 10};
cudf::test::lists_column_wrapper<int> s1_sscol2{{{1, 2}, {3, 4}, {5}, {6, 7, 8}, {12, 12}},
all_valid};
cudf::test::structs_column_wrapper s1_scol2({s1_sscol0, s1_sscol1, s1_sscol2});
cudf::test::structs_column_wrapper s_col1({s1_scol0, s1_scol1, s1_scol2});
// equivalent, but not equal
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(s_col0, s_col1);
EXPECT_FALSE(cudf::test::detail::expect_columns_equal(
s_col0, s_col1, cudf::test::debug_output_level::QUIET));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(s_col0, s_col0);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(s_col1, s_col1);
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/logger_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/detail/utilities/logger.hpp>
#include <spdlog/sinks/ostream_sink.h>
#include <string>
class LoggerTest : public cudf::test::BaseFixture {
std::ostringstream oss;
spdlog::level::level_enum prev_level;
std::vector<spdlog::sink_ptr> prev_sinks;
public:
LoggerTest() : prev_level{cudf::logger().level()}, prev_sinks{cudf::logger().sinks()}
{
cudf::logger().sinks() = {std::make_shared<spdlog::sinks::ostream_sink_mt>(oss)};
cudf::logger().set_formatter(
std::unique_ptr<spdlog::formatter>(new spdlog::pattern_formatter("%v")));
}
~LoggerTest()
{
cudf::logger().set_level(prev_level);
cudf::logger().sinks() = prev_sinks;
}
void clear_sink() { oss.str(""); }
std::string sink_content() { return oss.str(); }
};
TEST_F(LoggerTest, Basic)
{
cudf::logger().critical("crit msg");
ASSERT_EQ(this->sink_content(), "crit msg\n");
}
TEST_F(LoggerTest, DefaultLevel)
{
cudf::logger().trace("trace");
cudf::logger().debug("debug");
cudf::logger().info("info");
cudf::logger().warn("warn");
cudf::logger().error("error");
cudf::logger().critical("critical");
ASSERT_EQ(this->sink_content(), "warn\nerror\ncritical\n");
}
TEST_F(LoggerTest, CustomLevel)
{
cudf::logger().set_level(spdlog::level::warn);
cudf::logger().info("info");
cudf::logger().warn("warn");
ASSERT_EQ(this->sink_content(), "warn\n");
this->clear_sink();
cudf::logger().set_level(spdlog::level::debug);
cudf::logger().trace("trace");
cudf::logger().debug("debug");
ASSERT_EQ(this->sink_content(), "debug\n");
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/span_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/detail/utilities/vector_factories.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/span.hpp>
#include <io/utilities/hostdevice_vector.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/cudf_gtest.hpp>
#include <cudf_test/type_lists.hpp>
#include <rmm/device_buffer.hpp>
#include <rmm/device_vector.hpp>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <cstddef>
#include <cstring>
#include <string>
using cudf::device_span;
using cudf::host_span;
using cudf::detail::device_2dspan;
using cudf::detail::host_2dspan;
using cudf::detail::hostdevice_2dvector;
template <typename T>
void expect_equivalent(host_span<T> a, host_span<T> b)
{
EXPECT_EQ(a.size(), b.size());
EXPECT_EQ(a.data(), b.data());
}
template <typename T>
void expect_equivalent(cudf::detail::hostdevice_span<T> a, cudf::detail::hostdevice_span<T> b)
{
EXPECT_EQ(a.size(), b.size());
EXPECT_EQ(a.host_ptr(), b.host_ptr());
}
template <typename Iterator1, typename T>
void expect_match(Iterator1 expected, size_t expected_size, host_span<T> input)
{
EXPECT_EQ(expected_size, input.size());
for (size_t i = 0; i < expected_size; i++) {
EXPECT_EQ(*(expected + i), *(input.begin() + i));
}
}
template <typename T>
void expect_match(std::string expected, host_span<T> input)
{
return expect_match(expected.begin(), expected.size(), input);
}
template <typename T>
void expect_match(std::string expected, cudf::detail::hostdevice_span<T> input)
{
return expect_match(expected.begin(), expected.size(), host_span<T>(input));
}
std::string const hello_world_message = "hello world";
std::vector<char> create_hello_world_message()
{
return std::vector<char>(hello_world_message.begin(), hello_world_message.end());
}
class SpanTest : public cudf::test::BaseFixture {};
TEST(SpanTest, CanCreateFullSubspan)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
expect_equivalent(message_span, message_span.subspan(0, message_span.size()));
}
TEST(SpanTest, CanTakeFirst)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
expect_match("hello", message_span.first(5));
}
TEST(SpanTest, CanTakeLast)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
expect_match("world", message_span.last(5));
}
TEST(SpanTest, CanTakeSubspanFull)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
expect_match("hello world", message_span.subspan(0, 11));
}
TEST(SpanTest, CanTakeSubspanPartial)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
expect_match("lo w", message_span.subspan(3, 4));
}
TEST(SpanTest, CanGetFront)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
EXPECT_EQ('h', message_span.front());
}
TEST(SpanTest, CanGetBack)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
EXPECT_EQ('d', message_span.back());
}
TEST(SpanTest, CanGetData)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
EXPECT_EQ(message.data(), message_span.data());
}
TEST(SpanTest, CanDetermineEmptiness)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
auto const empty_span = host_span<char>();
EXPECT_FALSE(message_span.empty());
EXPECT_TRUE(empty_span.empty());
}
TEST(SpanTest, CanGetSize)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
auto const empty_span = host_span<char>();
EXPECT_EQ(static_cast<size_t>(11), message_span.size());
EXPECT_EQ(static_cast<size_t>(0), empty_span.size());
}
TEST(SpanTest, CanGetSizeBytes)
{
auto doubles = std::vector<double>({6, 3, 2});
auto const doubles_span = host_span<double>(doubles.data(), doubles.size());
auto const empty_span = host_span<double>();
EXPECT_EQ(static_cast<size_t>(24), doubles_span.size_bytes());
EXPECT_EQ(static_cast<size_t>(0), empty_span.size_bytes());
}
TEST(SpanTest, CanCopySpan)
{
auto message = create_hello_world_message();
host_span<char> message_span_copy;
{
auto const message_span = host_span<char>(message.data(), message.size());
message_span_copy = message_span;
}
EXPECT_EQ(message.data(), message_span_copy.data());
EXPECT_EQ(message.size(), message_span_copy.size());
}
TEST(SpanTest, CanSubscriptRead)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
EXPECT_EQ('o', message_span[4]);
}
TEST(SpanTest, CanSubscriptWrite)
{
auto message = create_hello_world_message();
auto const message_span = host_span<char>(message.data(), message.size());
message_span[4] = 'x';
EXPECT_EQ('x', message_span[4]);
}
TEST(SpanTest, CanConstructFromHostContainers)
{
auto std_vector = std::vector<int>(1);
auto h_vector = thrust::host_vector<int>(1);
(void)host_span<int>(std_vector);
(void)host_span<int>(h_vector);
auto const std_vector_c = std_vector;
auto const h_vector_c = h_vector;
(void)host_span<int const>(std_vector_c);
(void)host_span<int const>(h_vector_c);
}
// This test is the only place in libcudf's test suite where using a
// thrust::device_vector (and therefore the CUDA default stream) is acceptable
// since we are explicitly testing conversions from thrust::device_vector.
TEST(SpanTest, CanConstructFromDeviceContainers)
{
auto d_thrust_vector = thrust::device_vector<int>(1);
auto d_vector = rmm::device_vector<int>(1);
auto d_uvector = rmm::device_uvector<int>(1, cudf::get_default_stream());
(void)device_span<int>(d_thrust_vector);
(void)device_span<int>(d_vector);
(void)device_span<int>(d_uvector);
auto const& d_thrust_vector_c = d_thrust_vector;
auto const& d_vector_c = d_vector;
auto const& d_uvector_c = d_uvector;
(void)device_span<int const>(d_thrust_vector_c);
(void)device_span<int const>(d_vector_c);
(void)device_span<int const>(d_uvector_c);
}
__global__ void simple_device_kernel(device_span<bool> result) { result[0] = true; }
TEST(SpanTest, CanUseDeviceSpan)
{
auto d_message = cudf::detail::make_zeroed_device_uvector_async<bool>(
1, cudf::get_default_stream(), rmm::mr::get_current_device_resource());
auto d_span = device_span<bool>(d_message.data(), d_message.size());
simple_device_kernel<<<1, 1, 0, cudf::get_default_stream().value()>>>(d_span);
ASSERT_TRUE(d_message.element(0, cudf::get_default_stream()));
}
class MdSpanTest : public cudf::test::BaseFixture {};
TEST(MdSpanTest, CanDetermineEmptiness)
{
auto const vector = hostdevice_2dvector<int>(1, 2, cudf::get_default_stream());
auto const no_rows_vector = hostdevice_2dvector<int>(0, 2, cudf::get_default_stream());
auto const no_columns_vector = hostdevice_2dvector<int>(1, 0, cudf::get_default_stream());
EXPECT_FALSE(host_2dspan<int const>{vector}.is_empty());
EXPECT_FALSE(device_2dspan<int const>{vector}.is_empty());
EXPECT_TRUE(host_2dspan<int const>{no_rows_vector}.is_empty());
EXPECT_TRUE(device_2dspan<int const>{no_rows_vector}.is_empty());
EXPECT_TRUE(host_2dspan<int const>{no_columns_vector}.is_empty());
EXPECT_TRUE(device_2dspan<int const>{no_columns_vector}.is_empty());
}
__global__ void readwrite_kernel(device_2dspan<int> result)
{
if (result[5][6] == 5) {
result[5][6] *= 6;
} else {
result[5][6] = 5;
}
}
TEST(MdSpanTest, DeviceReadWrite)
{
auto vector = hostdevice_2dvector<int>(11, 23, cudf::get_default_stream());
readwrite_kernel<<<1, 1, 0, cudf::get_default_stream().value()>>>(vector);
readwrite_kernel<<<1, 1, 0, cudf::get_default_stream().value()>>>(vector);
vector.device_to_host_sync(cudf::get_default_stream());
EXPECT_EQ(vector[5][6], 30);
}
TEST(MdSpanTest, HostReadWrite)
{
auto vector = hostdevice_2dvector<int>(11, 23, cudf::get_default_stream());
auto span = host_2dspan<int>{vector};
span[5][6] = 5;
if (span[5][6] == 5) { span[5][6] *= 6; }
EXPECT_EQ(vector[5][6], 30);
}
TEST(MdSpanTest, CanGetSize)
{
auto const vector = hostdevice_2dvector<int>(1, 2, cudf::get_default_stream());
EXPECT_EQ(host_2dspan<int const>{vector}.size(), vector.size());
EXPECT_EQ(device_2dspan<int const>{vector}.size(), vector.size());
}
TEST(MdSpanTest, CanGetCount)
{
auto const vector = hostdevice_2dvector<int>(11, 23, cudf::get_default_stream());
EXPECT_EQ(host_2dspan<int const>{vector}.count(), 11ul * 23);
EXPECT_EQ(device_2dspan<int const>{vector}.count(), 11ul * 23);
}
auto get_test_hostdevice_vector()
{
auto v = cudf::detail::hostdevice_vector<char>(0, 11, cudf::get_default_stream());
for (auto c : create_hello_world_message()) {
v.push_back(c);
}
return v;
}
TEST(HostDeviceSpanTest, CanCreateFullSubspan)
{
auto message = get_test_hostdevice_vector();
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
expect_equivalent(message_span, message.subspan(0, message_span.size()));
}
TEST(HostDeviceSpanTest, CanCreateHostSpan)
{
auto message = get_test_hostdevice_vector();
auto const message_span = host_span<char>(message.host_ptr(), message.size());
auto const hd_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
expect_equivalent(message_span, cudf::host_span<char>(hd_span));
}
TEST(HostDeviceSpanTest, CanTakeSubspanFull)
{
auto message = get_test_hostdevice_vector();
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
expect_match("hello world", message.subspan(0, 11));
expect_match("hello world", message_span.subspan(0, 11));
}
TEST(HostDeviceSpanTest, CanTakeSubspanPartial)
{
auto message = get_test_hostdevice_vector();
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
expect_match("lo w", message.subspan(3, 4));
expect_match("lo w", message_span.subspan(3, 4));
}
TEST(HostDeviceSpanTest, CanGetData)
{
auto message = get_test_hostdevice_vector();
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
EXPECT_EQ(message.host_ptr(), message_span.host_ptr());
}
TEST(HostDeviceSpanTest, CanGetSize)
{
auto message = get_test_hostdevice_vector();
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
auto const empty_span = cudf::detail::hostdevice_span<char>();
EXPECT_EQ(static_cast<size_t>(11), message_span.size());
EXPECT_EQ(static_cast<size_t>(0), empty_span.size());
}
TEST(HostDeviceSpanTest, CanGetSizeBytes)
{
auto doubles = std::vector<double>({6, 3, 2});
auto doubles_hdv = cudf::detail::hostdevice_vector<double>(0, 3, cudf::get_default_stream());
for (auto d : doubles) {
doubles_hdv.push_back(d);
}
auto const doubles_span = cudf::detail::hostdevice_span<double>(doubles_hdv);
auto const empty_span = cudf::detail::hostdevice_span<double>();
EXPECT_EQ(static_cast<size_t>(24), doubles_span.size_bytes());
EXPECT_EQ(static_cast<size_t>(0), empty_span.size_bytes());
}
TEST(HostDeviceSpanTest, CanCopySpan)
{
auto message = get_test_hostdevice_vector();
cudf::detail::hostdevice_span<char> message_span_copy;
{
auto const message_span =
cudf::detail::hostdevice_span<char>(message.host_ptr(), message.device_ptr(), message.size());
message_span_copy = message_span;
}
EXPECT_EQ(message.host_ptr(), message_span_copy.host_ptr());
EXPECT_EQ(message.device_ptr(), message_span_copy.device_ptr());
EXPECT_EQ(message.size(), message_span_copy.size());
}
TEST(HostDeviceSpanTest, CanSendToDevice)
{
auto message = get_test_hostdevice_vector();
message.host_to_device_sync(cudf::get_default_stream());
char d_message[12];
cudaMemcpy(d_message, message.device_ptr(), 11, cudaMemcpyDefault);
d_message[11] = '\0';
EXPECT_EQ(11, strlen(d_message));
EXPECT_EQ(std::string(d_message), hello_world_message);
}
__global__ void simple_device_char_kernel(device_span<char> result)
{
char const* str = "world hello";
for (int offset = 0; offset < result.size(); ++offset) {
result.data()[offset] = str[offset];
}
}
TEST(HostDeviceSpanTest, CanGetFromDevice)
{
auto message = get_test_hostdevice_vector();
message.host_to_device_sync(cudf::get_default_stream());
simple_device_char_kernel<<<1, 1, 0, cudf::get_default_stream()>>>(message);
message.device_to_host_sync(cudf::get_default_stream());
expect_match("world hello", cudf::detail::hostdevice_span<char>(message));
}
CUDF_TEST_PROGRAM_MAIN()
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/default_stream_tests.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/utilities/default_stream.hpp>
#include <cudf_test/cudf_gtest.hpp>
#ifdef CUDA_API_PER_THREAD_DEFAULT_STREAM
TEST(DefaultStreamTest, PtdsIsEnabled) { EXPECT_TRUE(cudf::is_ptds_enabled()); }
#else
TEST(DefaultStreamTest, PtdsIsNotEnabled) { EXPECT_FALSE(cudf::is_ptds_enabled()); }
#endif
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/column_debug_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/strings/strings_column_view.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/cudf_gtest.hpp>
#include <cudf_test/debug_utilities.hpp>
#include <cudf_test/type_lists.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <type_traits>
template <typename T>
struct ColumnDebugTestIntegral : public cudf::test::BaseFixture {};
template <typename T>
struct ColumnDebugTestFloatingPoint : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ColumnDebugTestIntegral, cudf::test::IntegralTypes);
TYPED_TEST_SUITE(ColumnDebugTestFloatingPoint, cudf::test::FloatingPointTypes);
TYPED_TEST(ColumnDebugTestIntegral, PrintColumnNumeric)
{
char const* delimiter = ",";
cudf::test::fixed_width_column_wrapper<TypeParam> cudf_col({1, 2, 3, 4, 5});
auto std_col = cudf::test::make_type_param_vector<TypeParam>({1, 2, 3, 4, 5});
std::stringstream tmp;
auto string_iter =
thrust::make_transform_iterator(std::begin(std_col), [](auto e) { return std::to_string(e); });
std::copy(string_iter,
string_iter + std_col.size() - 1,
std::ostream_iterator<std::string>(tmp, delimiter));
tmp << std::to_string(std_col.back());
EXPECT_EQ(cudf::test::to_string(cudf_col, delimiter), tmp.str());
}
TYPED_TEST(ColumnDebugTestIntegral, PrintColumnWithInvalids)
{
char const* delimiter = ",";
cudf::test::fixed_width_column_wrapper<TypeParam> cudf_col{{1, 2, 3, 4, 5}, {1, 0, 1, 0, 1}};
auto std_col = cudf::test::make_type_param_vector<TypeParam>({1, 2, 3, 4, 5});
std::ostringstream tmp;
tmp << std::to_string(std_col[0]) << delimiter << "NULL" << delimiter
<< std::to_string(std_col[2]) << delimiter << "NULL" << delimiter
<< std::to_string(std_col[4]);
EXPECT_EQ(cudf::test::to_string(cudf_col, delimiter), tmp.str());
}
TYPED_TEST(ColumnDebugTestFloatingPoint, PrintColumnNumeric)
{
char const* delimiter = ",";
cudf::test::fixed_width_column_wrapper<TypeParam> cudf_col(
{10001523.25, 2.0, 3.75, 0.000000034, 5.3});
auto expected = std::is_same_v<TypeParam, double>
? "10001523.25,2,3.75,3.4e-08,5.2999999999999998"
: "10001523,2,3.75,3.39999993e-08,5.30000019";
EXPECT_EQ(cudf::test::to_string(cudf_col, delimiter), expected);
}
TYPED_TEST(ColumnDebugTestFloatingPoint, PrintColumnWithInvalids)
{
char const* delimiter = ",";
cudf::test::fixed_width_column_wrapper<TypeParam> cudf_col(
{10001523.25, 2.0, 3.75, 0.000000034, 5.3}, {1, 0, 1, 0, 1});
auto expected = std::is_same_v<TypeParam, double>
? "10001523.25,NULL,3.75,NULL,5.2999999999999998"
: "10001523,NULL,3.75,NULL,5.30000019";
EXPECT_EQ(cudf::test::to_string(cudf_col, delimiter), expected);
}
struct ColumnDebugStringsTest : public cudf::test::BaseFixture {};
TEST_F(ColumnDebugStringsTest, PrintColumnDuration)
{
char const* delimiter = ",";
cudf::test::fixed_width_column_wrapper<cudf::duration_s, int32_t> cudf_col({100, 0, 7, 140000});
auto expected = "100 seconds,0 seconds,7 seconds,140000 seconds";
EXPECT_EQ(cudf::test::to_string(cudf_col, delimiter), expected);
}
TEST_F(ColumnDebugStringsTest, StringsToString)
{
char const* delimiter = ",";
std::vector<char const*> h_strings{"eee", "bb", nullptr, "", "aa", "bbb", "ééé"};
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::ostringstream tmp;
tmp << h_strings[0] << delimiter << h_strings[1] << delimiter << "NULL" << delimiter
<< h_strings[3] << delimiter << h_strings[4] << delimiter << h_strings[5] << delimiter
<< h_strings[6];
EXPECT_EQ(cudf::test::to_string(strings, delimiter), tmp.str());
}
TEST_F(ColumnDebugStringsTest, PrintEscapeStrings)
{
char const* delimiter = ",";
cudf::test::strings_column_wrapper input({"e\te\ne", "é\bé\ré", "e\vé\fé\abell"});
std::string expected{"e\\te\\ne,é\\bé\\ré,e\\vé\\fé\\abell"};
EXPECT_EQ(cudf::test::to_string(input, delimiter), expected);
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/utilities_tests/type_check_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/fixed_point/fixed_point.hpp>
#include <cudf/utilities/type_checks.hpp>
#include <cudf/wrappers/durations.hpp>
#include <cudf/wrappers/timestamps.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/type_lists.hpp>
namespace cudf {
namespace test {
template <typename T>
struct ColumnTypeCheckTestTyped : public cudf::test::BaseFixture {};
struct ColumnTypeCheckTest : public cudf::test::BaseFixture {};
TYPED_TEST_SUITE(ColumnTypeCheckTestTyped, cudf::test::FixedWidthTypes);
TYPED_TEST(ColumnTypeCheckTestTyped, SameFixedWidth)
{
fixed_width_column_wrapper<TypeParam> lhs{1, 1}, rhs{2};
EXPECT_TRUE(column_types_equal(lhs, rhs));
}
TEST_F(ColumnTypeCheckTest, SameString)
{
strings_column_wrapper lhs{{'a', 'a'}}, rhs{{'b'}};
EXPECT_TRUE(column_types_equal(lhs, rhs));
strings_column_wrapper lhs2{}, rhs2{{'b'}};
EXPECT_TRUE(column_types_equal(lhs2, rhs2));
strings_column_wrapper lhs3{}, rhs3{};
EXPECT_TRUE(column_types_equal(lhs3, rhs3));
}
TEST_F(ColumnTypeCheckTest, SameList)
{
using LCW = lists_column_wrapper<int32_t>;
LCW lhs{}, rhs{};
EXPECT_TRUE(column_types_equal(lhs, rhs));
LCW lhs2{{1, 2, 3}}, rhs2{{4, 5}};
EXPECT_TRUE(column_types_equal(lhs2, rhs2));
LCW lhs3{{LCW{1}, LCW{2, 3}}}, rhs3{{LCW{4, 5}}};
EXPECT_TRUE(column_types_equal(lhs3, rhs3));
LCW lhs4{{LCW{1}, LCW{}, LCW{2, 3}}}, rhs4{{LCW{4, 5}, LCW{}}};
EXPECT_TRUE(column_types_equal(lhs4, rhs4));
}
TYPED_TEST(ColumnTypeCheckTestTyped, SameDictionary)
{
using DCW = dictionary_column_wrapper<TypeParam>;
DCW lhs{1, 1, 2, 3}, rhs{5, 5};
EXPECT_TRUE(column_types_equal(lhs, rhs));
DCW lhs2{}, rhs2{};
EXPECT_TRUE(column_types_equal(lhs2, rhs2));
}
TEST_F(ColumnTypeCheckTest, SameStruct)
{
using SCW = structs_column_wrapper;
using FCW = fixed_width_column_wrapper<int32_t>;
using StringCW = strings_column_wrapper;
using LCW = lists_column_wrapper<int32_t>;
using DCW = dictionary_column_wrapper<int32_t>;
FCW lf1{1, 2, 3}, rf1{0, 1};
StringCW lf2{"a", "bb", ""}, rf2{"cc", "d"};
LCW lf3{LCW{1, 2}, LCW{}, LCW{4}}, rf3{LCW{1}, LCW{2}};
DCW lf4{5, 5, 5}, rf4{9, 9};
SCW lhs{lf1, lf2, lf3, lf4}, rhs{rf1, rf2, rf3, rf4};
EXPECT_TRUE(column_types_equal(lhs, rhs));
}
TEST_F(ColumnTypeCheckTest, DifferentBasics)
{
fixed_width_column_wrapper<int32_t> lhs1{1, 1};
strings_column_wrapper rhs1{"a", "bb"};
EXPECT_FALSE(column_types_equal(lhs1, rhs1));
lists_column_wrapper<string_view> lhs2{{"hello"}, {"world", "!"}};
strings_column_wrapper rhs2{"", "kk"};
EXPECT_FALSE(column_types_equal(lhs2, rhs2));
fixed_width_column_wrapper<int32_t> lhs3{1, 1};
dictionary_column_wrapper<int32_t> rhs3{2, 2};
EXPECT_FALSE(column_types_equal(lhs3, rhs3));
lists_column_wrapper<int32_t> lhs4{{8, 8, 8}, {10, 10}};
structs_column_wrapper rhs4{rhs2, rhs3};
EXPECT_FALSE(column_types_equal(lhs4, rhs4));
}
TEST_F(ColumnTypeCheckTest, DifferentFixedWidth)
{
fixed_width_column_wrapper<int32_t> lhs1{1, 1};
fixed_width_column_wrapper<int64_t> rhs1{2};
EXPECT_FALSE(column_types_equal(lhs1, rhs1));
fixed_width_column_wrapper<float> lhs2{1, 1};
fixed_width_column_wrapper<double> rhs2{2};
EXPECT_FALSE(column_types_equal(lhs2, rhs2));
fixed_width_column_wrapper<timestamp_ms> lhs3{1, 1};
fixed_width_column_wrapper<timestamp_us> rhs3{2};
EXPECT_FALSE(column_types_equal(lhs3, rhs3));
fixed_width_column_wrapper<duration_D> lhs4{};
fixed_width_column_wrapper<duration_us> rhs4{42};
EXPECT_FALSE(column_types_equal(lhs4, rhs4));
// Same rep, different scale
fixed_point_column_wrapper<int32_t> lhs5({10000}, numeric::scale_type{-3});
fixed_point_column_wrapper<int32_t> rhs5({10000}, numeric::scale_type{0});
EXPECT_FALSE(column_types_equal(lhs5, rhs5));
EXPECT_TRUE(column_types_equivalent(lhs5, rhs5));
// Different rep, same scale
fixed_point_column_wrapper<int32_t> lhs6({10000}, numeric::scale_type{-1});
fixed_point_column_wrapper<int64_t> rhs6({4200}, numeric::scale_type{-1});
EXPECT_FALSE(column_types_equal(lhs6, rhs6));
}
TEST_F(ColumnTypeCheckTest, DifferentDictionary)
{
dictionary_column_wrapper<int32_t, uint32_t> lhs1{1, 1, 1, 2, 2, 3};
dictionary_column_wrapper<int64_t, uint32_t> rhs1{0, 0, 42, 42};
EXPECT_FALSE(column_types_equal(lhs1, rhs1));
dictionary_column_wrapper<double, uint32_t> lhs2{3.14, 3.14, 5.00};
dictionary_column_wrapper<int64_t, uint32_t> rhs2{0, 0, 42, 42};
EXPECT_FALSE(column_types_equal(lhs2, rhs2));
dictionary_column_wrapper<int32_t, uint32_t> lhs3{1, 1, 1, 2, 2, 3};
dictionary_column_wrapper<duration_s, uint32_t> rhs3{8, 8};
EXPECT_FALSE(column_types_equal(lhs3, rhs3));
dictionary_column_wrapper<int32_t, uint32_t> lhs4{1, 1, 2, 3}, rhs4{};
EXPECT_FALSE(column_types_equal(lhs4, rhs4));
}
TEST_F(ColumnTypeCheckTest, DifferentLists)
{
using LCW_i = lists_column_wrapper<int32_t>;
using LCW_f = lists_column_wrapper<float>;
// Different nested level
LCW_i lhs1{LCW_i{1, 1, 2, 3}, LCW_i{}, LCW_i{42, 42}};
LCW_i rhs1{LCW_i{LCW_i{8, 8, 8}, LCW_i{9, 9}}, LCW_i{LCW_i{42, 42}}};
EXPECT_FALSE(column_types_equal(lhs1, rhs1));
// Different base column type
LCW_i lhs2{LCW_i{1, 1, 2, 3}, LCW_i{}, LCW_i{42, 42}};
LCW_f rhs2{LCW_f{9.0, 9.1}, LCW_f{3.14}, LCW_f{}};
EXPECT_FALSE(column_types_equal(lhs2, rhs2));
}
TEST_F(ColumnTypeCheckTest, DifferentStructs)
{
fixed_width_column_wrapper<int32_t> lf1{1, 1, 1};
fixed_width_column_wrapper<int64_t> rf1{2, 2};
structs_column_wrapper lhs1{lf1};
structs_column_wrapper rhs1{rf1};
EXPECT_FALSE(column_types_equal(lhs1, rhs1));
fixed_width_column_wrapper<int32_t> lf2{1, 1, 1};
fixed_width_column_wrapper<int32_t> rf2{2, 2};
strings_column_wrapper lf3{"a", "b", "c"};
structs_column_wrapper lhs2{lf2, lf3};
structs_column_wrapper rhs2{rf2};
EXPECT_FALSE(column_types_equal(lhs2, rhs2));
}
} // namespace test
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/lists/reverse_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_utilities.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/copying.hpp>
#include <cudf/lists/reverse.hpp>
#include <cudf/null_mask.hpp>
using namespace cudf::test::iterators;
auto constexpr null{0}; // null at current level
auto constexpr XXX{0}; // null pushed down from parent level
using ints_lists = cudf::test::lists_column_wrapper<int32_t>;
using ints_col = cudf::test::fixed_width_column_wrapper<int32_t>;
using strings_col = cudf::test::strings_column_wrapper;
using structs_col = cudf::test::structs_column_wrapper;
struct ListsReverseTest : public cudf::test::BaseFixture {};
template <typename T>
struct ListsReverseTypedTest : public cudf::test::BaseFixture {};
using TestTypes =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(ListsReverseTypedTest, TestTypes);
TEST_F(ListsReverseTest, EmptyInput)
{
// Empty column.
{
auto const input = ints_lists{};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
// Empty lists.
{
auto const input = ints_lists{ints_lists{}, ints_lists{}, ints_lists{}};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
// Empty nested lists.
{
auto const input = ints_lists{ints_lists{ints_lists{}}, ints_lists{}, ints_lists{}};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
}
TYPED_TEST(ListsReverseTypedTest, SimpleInputNoNulls)
{
using lists_col = cudf::test::lists_column_wrapper<TypeParam>;
auto const input_original = lists_col{{}, {1, 2, 3}, {}, {4, 5}, {6, 7, 8}, {9}};
{
auto const expected = lists_col{{}, {3, 2, 1}, {}, {5, 4}, {8, 7, 6}, {9}};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input_original));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected = lists_col{{3, 2, 1}, {}, {5, 4}};
auto const input = cudf::slice(input_original, {1, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected = lists_col{lists_col{}};
auto const input = cudf::slice(input_original, {2, 3})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected = lists_col{{}, {5, 4}};
auto const input = cudf::slice(input_original, {2, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
}
TYPED_TEST(ListsReverseTypedTest, SimpleInputWithNulls)
{
using lists_col = cudf::test::lists_column_wrapper<TypeParam>;
auto const input_original = lists_col{{lists_col{},
lists_col{1, 2, 3},
lists_col{} /*null*/,
lists_col{{4, 5, null}, null_at(2)},
lists_col{6, 7, 8},
lists_col{9}},
null_at(2)};
{
auto const expected = lists_col{{lists_col{},
lists_col{3, 2, 1},
lists_col{} /*null*/,
lists_col{{null, 5, 4}, null_at(0)},
lists_col{8, 7, 6},
lists_col{9}},
null_at(2)};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input_original));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected = lists_col{
{lists_col{3, 2, 1}, lists_col{} /*null*/, lists_col{{null, 5, 4}, null_at(0)}}, null_at(1)};
auto const input = cudf::slice(input_original, {1, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected = lists_col{{lists_col{} /*null*/}, null_at(0)};
auto const input = cudf::slice(input_original, {2, 3})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const expected =
lists_col{{lists_col{} /*null*/, lists_col{{null, 5, 4}, null_at(0)}}, null_at(0)};
auto const input = cudf::slice(input_original, {2, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *results);
}
{
auto const input = cudf::slice(input_original, {4, 6})[0];
auto const expected = lists_col{{8, 7, 6}, {9}};
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
// The result doesn't have nulls, but it is nullable.
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results);
}
}
TYPED_TEST(ListsReverseTypedTest, InputListsOfListsNoNulls)
{
using lists_col = cudf::test::lists_column_wrapper<TypeParam>;
auto const input_original = [] {
auto child =
lists_col{{1, 2, 3}, {4, 5, 6}, {7}, {4, 5}, {}, {4, 5, 6}, {}, {6, 7, 8}, {}, {9}}.release();
auto offsets = ints_col{0, 0, 3, 3, 6, 9, 10, 10, 10}.release();
return cudf::make_lists_column(8, std::move(offsets), std::move(child), 0, {});
}();
{
auto const expected = [] {
auto child =
lists_col{{7}, {4, 5, 6}, {1, 2, 3}, {4, 5, 6}, {}, {4, 5}, {}, {6, 7, 8}, {}, {9}}
.release();
auto offsets = ints_col{0, 0, 3, 3, 6, 9, 10, 10, 10}.release();
return cudf::make_lists_column(8, std::move(offsets), std::move(child), 0, {});
}();
auto const results = cudf::lists::reverse(cudf::lists_column_view(*input_original));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
{
auto const expected = [] {
auto child = lists_col{{7}, {4, 5, 6}, {1, 2, 3}, {4, 5, 6}, {}, {4, 5}}.release();
auto offsets = ints_col{0, 3, 3, 6}.release();
return cudf::make_lists_column(3, std::move(offsets), std::move(child), 0, {});
}();
auto const input = cudf::slice(*input_original, {1, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
{
auto const input = cudf::slice(*input_original, {2, 3})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
{
auto const expected = [] {
auto child = lists_col{{4, 5, 6}, {}, {4, 5}}.release();
auto offsets = ints_col{0, 0, 3}.release();
return cudf::make_lists_column(2, std::move(offsets), std::move(child), 0, {});
}();
auto const input = cudf::slice(*input_original, {2, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
}
TYPED_TEST(ListsReverseTypedTest, InputListsOfListsWithNulls)
{
using lists_col = cudf::test::lists_column_wrapper<TypeParam>;
auto const input_original = [] {
auto child = lists_col{{{1, 2, 3},
{4, 5, 6},
{7},
{4, 5},
{} /*null*/,
{4, 5, 6},
{},
{6, 7, 8},
{} /*null*/,
{9}},
nulls_at({4, 8})}
.release();
auto offsets = ints_col{0, 0, 3, 3, 6, 9, 10, 10, 10}.release();
auto null_mask = cudf::create_null_mask(8, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 2, 3, false);
return cudf::make_lists_column(
8, std::move(offsets), std::move(child), 1, std::move(null_mask));
}();
{
auto const expected = [] {
auto child = lists_col{{{7},
{4, 5, 6},
{1, 2, 3},
{4, 5, 6},
{} /*null*/,
{4, 5},
{} /*null*/,
{6, 7, 8},
{},
{9}},
nulls_at({4, 6})}
.release();
auto offsets = ints_col{0, 0, 3, 3, 6, 9, 10, 10, 10}.release();
auto null_mask = cudf::create_null_mask(8, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 2, 3, false);
return cudf::make_lists_column(
8, std::move(offsets), std::move(child), 1, std::move(null_mask));
}();
auto const results = cudf::lists::reverse(cudf::lists_column_view(*input_original));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
{
auto const expected = [] {
auto child = lists_col{{7}, {4, 5, 6}, {1, 2, 3}}.release();
auto offsets = ints_col{0, 3}.release();
return cudf::make_lists_column(1, std::move(offsets), std::move(child), 0, {});
}();
auto const input = cudf::slice(*input_original, {0, 1})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
{
auto const expected = [] {
auto child =
lists_col{{{7}, {4, 5, 6}, {1, 2, 3}, {4, 5, 6}, {} /*null*/, {4, 5}}, null_at(4)}
.release();
auto offsets = ints_col{0, 3, 3, 6}.release();
auto null_mask = cudf::create_null_mask(3, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 1, 2, false);
return cudf::make_lists_column(
3, std::move(offsets), std::move(child), 1, std::move(null_mask));
}();
auto const input = cudf::slice(*input_original, {1, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
{
auto const expected = [] {
auto child = lists_col{{{4, 5, 6}, {} /*null*/, {4, 5}}, null_at(1)}.release();
auto offsets = ints_col{0, 0, 3}.release();
auto null_mask = cudf::create_null_mask(2, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 0, 1, false);
return cudf::make_lists_column(
2, std::move(offsets), std::move(child), 1, std::move(null_mask));
}();
auto const input = cudf::slice(*input_original, {2, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
// The result doesn't have nulls, but it is nullable.
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results);
}
}
TYPED_TEST(ListsReverseTypedTest, InputListsOfStructsWithNulls)
{
using data_col = cudf::test::fixed_width_column_wrapper<TypeParam>;
auto const input_original = [] {
auto child = [] {
auto grandchild1 = data_col{{
1, XXX, null, XXX, XXX, 2, 3, 4, // list1
5, 6, 7, 8, 9, 10, null, 11, // list2
null, null, 12, 13, 14, 15, 16, 17 // list3
},
nulls_at({2, 14, 16, 17})};
auto grandchild2 = strings_col{{
// begin list1
"Banana",
"YYY", /*NULL*/
"Apple",
"XXX", /*NULL*/
"YYY", /*NULL*/
"Banana",
"Cherry",
"Kiwi", // end list1
// begin list2
"Bear",
"Duck",
"Cat",
"Dog",
"Panda",
"Bear",
"" /*NULL*/,
"Panda", // end list2
// begin list3
"ÁÁÁ",
"ÉÉÉÉÉ",
"ÍÍÍÍÍ",
"ÁBC",
"" /*NULL*/,
"ÁÁÁ",
"ÁBC",
"XYZ" // end list3
},
nulls_at({14, 20})};
return structs_col{{grandchild1, grandchild2}, nulls_at({1, 3, 4})}.release();
}();
auto offsets = ints_col{0, 0, 8, 16, 16, 16, 24}.release();
auto null_mask = cudf::create_null_mask(6, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 0, 1, false);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 4, 5, false);
return cudf::make_lists_column(
6, std::move(offsets), std::move(child), 2, std::move(null_mask));
}();
{
auto const expected = [] {
auto child = [] {
auto grandchild1 = data_col{{
4, 3, 2, null, null, null, null, 1, // list1
11, null, 10, 9, 8, 7, 6, 5, // list2
17, 16, 15, 14, 13, 12, null, null, // list3
},
nulls_at({3, 4, 5, 6, 9, 22, 23})};
auto grandchild2 = strings_col{{
// begin list1
"Kiwi",
"Cherry",
"Banana",
"", /*NULL*/
"", /*NULL*/
"Apple",
"", /*NULL*/
"Banana", // end list1
// begin list2
"Panda",
"" /*NULL*/,
"Bear",
"Panda",
"Dog",
"Cat",
"Duck",
"Bear", // end list2
// begin list3
"XYZ",
"ÁBC",
"ÁÁÁ",
"" /*NULL*/,
"ÁBC",
"ÍÍÍÍÍ",
"ÉÉÉÉÉ",
"ÁÁÁ" // end list3
},
nulls_at({3, 4, 6, 9, 19})};
return structs_col{{grandchild1, grandchild2}, nulls_at({3, 4, 6})}.release();
}();
auto offsets = ints_col{0, 0, 8, 16, 16, 16, 24}.release();
auto null_mask = cudf::create_null_mask(6, cudf::mask_state::ALL_VALID);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 0, 1, false);
cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 4, 5, false);
return cudf::make_lists_column(
6, std::move(offsets), std::move(child), 2, std::move(null_mask));
}();
auto const results = cudf::lists::reverse(cudf::lists_column_view(*input_original));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *results);
}
{
auto const expected = [] {
auto child = [] {
auto grandchild1 = data_col{{
4,
3,
2,
null,
null,
null,
null,
1, // end list1
11,
null,
10,
9,
8,
7,
6,
5 // end list2
},
nulls_at({3, 4, 5, 6, 9})};
auto grandchild2 = strings_col{{
// begin list1
"Kiwi",
"Cherry",
"Banana",
"", /*NULL*/
"", /*NULL*/
"Apple",
"", /*NULL*/
"Banana", // end list1
// begin list2
"Panda",
"" /*NULL*/,
"Bear",
"Panda",
"Dog",
"Cat",
"Duck",
"Bear" // end list2
},
nulls_at({3, 4, 6, 9})};
return structs_col{{grandchild1, grandchild2}, nulls_at({3, 4, 6})}.release();
}();
auto offsets = ints_col{0, 8, 16, 16}.release();
return cudf::make_lists_column(3, std::move(offsets), std::move(child), 0, {});
}();
auto const input = cudf::slice(*input_original, {1, 4})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
// The result doesn't have nulls, but it is nullable.
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results);
}
{
auto const input = cudf::slice(*input_original, {4, 5})[0];
auto const results = cudf::lists::reverse(cudf::lists_column_view(input));
CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, *results);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/lists/contains_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/column/column_factories.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/lists/contains.hpp>
#include <cudf/scalar/scalar_factories.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/type_lists.hpp>
namespace {
template <typename T, std::enable_if_t<cudf::is_numeric<T>(), void>* = nullptr>
auto create_scalar_search_key(T const& value)
{
auto search_key = cudf::make_numeric_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(true);
static_cast<cudf::scalar_type_t<T>*>(search_key.get())->set_value(value);
return search_key;
}
template <typename T, std::enable_if_t<std::is_same_v<T, std::string>, void>* = nullptr>
auto create_scalar_search_key(std::string const& value)
{
return cudf::make_string_scalar(value);
}
template <typename T, std::enable_if_t<cudf::is_timestamp<T>(), void>* = nullptr>
auto create_scalar_search_key(typename T::rep const& value)
{
auto search_key = cudf::make_timestamp_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(true);
static_cast<cudf::scalar_type_t<typename T::rep>*>(search_key.get())->set_value(value);
return search_key;
}
template <typename T, std::enable_if_t<cudf::is_duration<T>(), void>* = nullptr>
auto create_scalar_search_key(typename T::rep const& value)
{
auto search_key = cudf::make_duration_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(true);
static_cast<cudf::scalar_type_t<typename T::rep>*>(search_key.get())->set_value(value);
return search_key;
}
template <typename... Args>
auto make_struct_scalar(Args&&... args)
{
return cudf::struct_scalar(std::vector<cudf::column_view>{std::forward<Args>(args)...});
}
template <typename T, std::enable_if_t<cudf::is_numeric<T>(), void>* = nullptr>
auto create_null_search_key()
{
auto search_key = cudf::make_numeric_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(false);
return search_key;
}
template <typename T, std::enable_if_t<cudf::is_timestamp<T>(), void>* = nullptr>
auto create_null_search_key()
{
auto search_key = cudf::make_timestamp_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(false);
return search_key;
}
template <typename T, std::enable_if_t<cudf::is_duration<T>(), void>* = nullptr>
auto create_null_search_key()
{
auto search_key = cudf::make_duration_scalar(cudf::data_type{cudf::type_to_id<T>()});
search_key->set_valid_async(false);
return search_key;
}
} // namespace
auto constexpr X = int32_t{0}; // Placeholder for nulls.
auto constexpr ABSENT = cudf::size_type{-1}; // Index when key is not found in a list.
auto constexpr FIND_FIRST = cudf::lists::duplicate_find_option::FIND_FIRST;
auto constexpr FIND_LAST = cudf::lists::duplicate_find_option::FIND_LAST;
using bools_col = cudf::test::fixed_width_column_wrapper<bool, int32_t>;
using indices_col = cudf::test::fixed_width_column_wrapper<cudf::size_type>;
using cudf::test::iterators::all_nulls;
using cudf::test::iterators::null_at;
using cudf::test::iterators::nulls_at;
using ContainsTestTypes = cudf::test::
Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::ChronoTypes>;
struct ContainsTest : public cudf::test::BaseFixture {};
template <typename T>
struct TypedContainsTest : public ContainsTest {};
TYPED_TEST_SUITE(TypedContainsTest, ContainsTestTypes);
TYPED_TEST(TypedContainsTest, ScalarKeyWithNoNulls)
{
using T = TypeParam;
auto const search_space_col = cudf::test::lists_column_wrapper<T, int32_t>{{0, 1, 2, 1},
{3, 4, 5},
{6, 7, 8},
{9, 0, 1, 3, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 1, 3},
{}};
auto const search_space = cudf::lists_column_view{search_space_col};
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(search_space, *search_key_one);
auto expected = bools_col{1, 0, 0, 1, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(search_space);
auto expected = bools_col{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space, *search_key_one, FIND_FIRST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space, *search_key_one, FIND_LAST);
auto expected = indices_col{3, ABSENT, ABSENT, 4, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsTest, ScalarKeyWithNullLists)
{
// Test List columns that have NULL list rows.
using T = TypeParam;
auto const search_space_col = cudf::test::lists_column_wrapper<T, int32_t>{{{0, 1, 2, 1},
{3, 4, 5},
{6, 7, 8},
{},
{9, 0, 1, 3, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 2, 3},
{}},
nulls_at({3, 10})};
auto const search_space = cudf::lists_column_view{search_space_col};
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(search_space, *search_key_one);
auto expected = bools_col{{1, 0, 0, X, 1, 0, 0, 0, 0, 1, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(search_space);
auto expected = bools_col{{0, 0, 0, X, 0, 0, 0, 0, 0, 0, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space, *search_key_one, FIND_FIRST);
auto expected = indices_col{{1, ABSENT, ABSENT, X, 2, ABSENT, ABSENT, ABSENT, ABSENT, 0, X},
nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space, *search_key_one, FIND_LAST);
auto expected = indices_col{{3, ABSENT, ABSENT, X, 4, ABSENT, ABSENT, ABSENT, ABSENT, 0, X},
nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsTest, SlicedLists)
{
// Test sliced List columns.
using T = TypeParam;
auto search_space = cudf::test::lists_column_wrapper<T, int32_t>{{{0, 1, 2, 1},
{3, 4, 5},
{6, 7, 8},
{},
{9, 0, 1, 3, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 1, 3},
{}},
nulls_at({3, 10})};
{
// First Slice.
auto sliced_column_1 =
cudf::detail::slice(search_space, {1, 8}, cudf::get_default_stream()).front();
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(sliced_column_1, *search_key_one);
auto expected_result = bools_col{{0, 0, X, 1, 0, 0, 0}, null_at(2)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(sliced_column_1);
auto expected_result = bools_col{{0, 0, X, 0, 0, 0, 0}, null_at(2)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(sliced_column_1, *search_key_one, FIND_FIRST);
auto expected_result =
indices_col{{ABSENT, ABSENT, 0, 2, ABSENT, ABSENT, ABSENT}, null_at(2)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// FIND_LAST
auto result = cudf::lists::index_of(sliced_column_1, *search_key_one, FIND_LAST);
auto expected_result =
indices_col{{ABSENT, ABSENT, 0, 4, ABSENT, ABSENT, ABSENT}, null_at(2)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
}
{
// Second Slice.
auto sliced_column_2 =
cudf::detail::slice(search_space, {3, 10}, cudf::get_default_stream()).front();
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(sliced_column_2, *search_key_one);
auto expected_result = bools_col{{X, 1, 0, 0, 0, 0, 1}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(sliced_column_2);
auto expected_result = bools_col{{X, 0, 0, 0, 0, 0, 0}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(sliced_column_2, *search_key_one, FIND_FIRST);
auto expected_result = indices_col{{0, 2, ABSENT, ABSENT, ABSENT, ABSENT, 0}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
{
// FIND_LAST
auto result = cudf::lists::index_of(sliced_column_2, *search_key_one, FIND_LAST);
auto expected_result = indices_col{{0, 4, ABSENT, ABSENT, ABSENT, ABSENT, 2}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result, result->view());
}
}
}
TYPED_TEST(TypedContainsTest, ScalarKeyNonNullListsWithNullValues)
{
// Test List columns that have no NULL list rows, but NULL elements in some list rows.
using T = TypeParam;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 2, X, 4, 5, X, 7, 8, X, X, 1, 2, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto search_space = cudf::make_lists_column(
8, indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(), numerals.release(), 0, {});
// Search space: [ [x], [1,2], [x,4,5,x], [], [], [7,8,x], [x], [1,2,x,1] ]
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_one);
auto expected = bools_col{0, 1, 0, 0, 0, 0, 0, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(search_space->view());
auto expected = bools_col{1, 0, 1, 0, 0, 1, 1, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_FIRST);
auto expected = indices_col{ABSENT, 0, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_LAST);
auto expected = indices_col{ABSENT, 0, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 3};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsTest, ScalarKeysWithNullsInLists)
{
using T = TypeParam;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 2, X, 4, 5, X, 7, 8, X, X, 1, 2, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(8,
indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
numerals.release(),
null_count,
std::move(null_mask));
// Search space: [ [x], [1,2], [x,4,5,x], [], x, [7,8,x], [x], [1,2,x,1] ]
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS.
auto result = cudf::lists::contains(search_space->view(), *search_key_one);
auto expected = bools_col{{0, 1, 0, 0, X, 0, 0, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS.
auto result = cudf::lists::contains_nulls(search_space->view());
auto expected = bools_col{{1, 0, 1, 0, X, 1, 1, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_FIRST);
auto expected = indices_col{{ABSENT, 0, ABSENT, ABSENT, X, ABSENT, ABSENT, 0}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_LAST);
auto expected = indices_col{{ABSENT, 0, ABSENT, ABSENT, X, ABSENT, ABSENT, 3}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, BoolScalarWithNullsInLists)
{
using T = bool;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 1, X, 1, 1, X, 1, 1, X, X, 1, 1, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(
8,
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
numerals.release(),
null_count,
std::move(null_mask));
// Search space: [ [x], [1,1], [x,1,1,x], [], x, [1,1,x], [x], [1,1,x,1] ]
auto search_key_one = create_scalar_search_key<T>(1);
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_one);
auto expected = bools_col{{0, 1, 1, 0, X, 1, 0, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(search_space->view());
auto expected = bools_col{{1, 0, 1, 0, X, 1, 1, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_FIRST);
auto expected = indices_col{{ABSENT, 0, 1, ABSENT, X, 0, ABSENT, 0}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_LAST);
auto expected = indices_col{{ABSENT, 1, 2, ABSENT, X, 1, ABSENT, 3}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, StringScalarWithNullsInLists)
{
using T = std::string;
auto strings = cudf::test::strings_column_wrapper{
{"X", "1", "2", "X", "4", "5", "X", "7", "8", "X", "X", "1", "2", "X", "1"},
nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(8,
indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
strings.release(),
null_count,
std::move(null_mask));
// Search space: [ [x], [1,2], [x,4,5,x], [], x, [7,8,x], [x], [1,2,x,1] ]
auto search_key_one = create_scalar_search_key<T>("1");
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_one);
auto expected = bools_col{{0, 1, 0, 0, X, 0, 0, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto result = cudf::lists::contains_nulls(search_space->view());
auto expected = bools_col{{1, 0, 1, 0, X, 1, 1, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_FIRST);
auto expected = indices_col{{ABSENT, 0, ABSENT, ABSENT, X, ABSENT, ABSENT, 0}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST.
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_LAST);
auto expected = indices_col{{ABSENT, 0, ABSENT, ABSENT, X, ABSENT, ABSENT, 3}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsTest, ScalarNullSearchKey)
{
using T = TypeParam;
auto search_space = cudf::test::lists_column_wrapper<T, int32_t>{{{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{},
{9, 0, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 3},
{}},
nulls_at({3, 10})}
.release();
auto search_key_null = create_null_search_key<T>();
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_null);
auto expected = bools_col{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, all_nulls()};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), *search_key_null, FIND_FIRST);
auto expected = indices_col{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, all_nulls()};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), *search_key_null, FIND_LAST);
auto expected = indices_col{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, all_nulls()};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, ScalarTypeRelatedExceptions)
{
{
// Nested types unsupported.
auto list_of_lists = cudf::test::lists_column_wrapper<int32_t>{
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3},
{4, 5, 6}}}.release();
auto skey = create_scalar_search_key<int32_t>(10);
EXPECT_THROW(cudf::lists::contains(list_of_lists->view(), *skey), cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_lists->view(), *skey, FIND_FIRST),
cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_lists->view(), *skey, FIND_LAST),
cudf::data_type_error);
}
{
// Search key must match list elements in type.
auto list_of_ints =
cudf::test::lists_column_wrapper<int32_t>{
{0, 1, 2},
{3, 4, 5},
}
.release();
auto skey = create_scalar_search_key<std::string>("Hello, World!");
EXPECT_THROW(cudf::lists::contains(list_of_ints->view(), *skey), cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), *skey, FIND_FIRST),
cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), *skey, FIND_LAST),
cudf::data_type_error);
}
}
template <typename T>
struct TypedVectorContainsTest : public ContainsTest {};
using VectorTestTypes =
cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>;
TYPED_TEST_SUITE(TypedVectorContainsTest, VectorTestTypes);
TYPED_TEST(TypedVectorContainsTest, VectorKeysWithNoNulls)
{
using T = TypeParam;
auto search_space = cudf::test::lists_column_wrapper<T, int32_t>{
{0, 1, 2, 1},
{3, 4, 5},
{6, 7, 8},
{9, 0, 1, 3, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 3, 3},
{}}.release();
auto search_key =
cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 1, 2, 3, 1, 2, 3, 1};
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_key);
auto expected = bools_col{1, 0, 0, 1, 1, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_key, FIND_FIRST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, 0, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_key, FIND_LAST);
auto expected = indices_col{3, ABSENT, ABSENT, 4, 0, ABSENT, ABSENT, ABSENT, 3, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedVectorContainsTest, VectorWithNullLists)
{
// Test List columns that have NULL list rows.
using T = TypeParam;
auto search_space = cudf::test::lists_column_wrapper<T, int32_t>{{{0, 1, 2, 1},
{3, 4, 5},
{6, 7, 8},
{},
{9, 0, 1, 3, 1},
{2, 3, 4},
{5, 6, 7},
{8, 9, 0},
{},
{1, 2, 3, 3},
{}},
nulls_at({3, 10})}
.release();
auto search_keys =
cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2};
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{{1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{{1, ABSENT, ABSENT, X, ABSENT, 1, ABSENT, ABSENT, ABSENT, 0, X},
nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{{3, ABSENT, ABSENT, X, ABSENT, 1, ABSENT, ABSENT, ABSENT, 0, X},
nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedVectorContainsTest, VectorNonNullListsWithNullValues)
{
// Test List columns that have no NULL list rows, but NULL elements in some list rows.
using T = TypeParam;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 2, X, 4, 5, X, 7, 8, X, X, 1, 2, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto search_space = cudf::make_lists_column(
8, indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(), numerals.release(), 0, {});
// Search space: [ [x], [1,2], [x,4,5,x], [], [], [7,8,x], [x], [1,2,x,1] ]
auto search_keys = cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 1, 2, 3, 1, 1};
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{0, 1, 0, 0, 0, 0, 0, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{ABSENT, 1, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{ABSENT, 1, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 3};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedVectorContainsTest, VectorWithNullsInLists)
{
using T = TypeParam;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 2, X, 4, 5, X, 7, 8, X, X, 1, 2, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(8,
indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
numerals.release(),
null_count,
std::move(null_mask));
// Search space: [ [x], [1,2], [x,4,5,x], [], x, [7,8,x], [x], [1,2,x,1] ]
auto search_keys = cudf::test::fixed_width_column_wrapper<T, int32_t>{1, 2, 3, 1, 2, 3, 1, 1};
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{{0, 1, 0, 0, X, 0, 0, 1}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{{ABSENT, 1, ABSENT, ABSENT, X, ABSENT, ABSENT, 0}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{{ABSENT, 1, ABSENT, ABSENT, X, ABSENT, ABSENT, 3}, null_at(4)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedVectorContainsTest, ListContainsVectorWithNullsInListsAndInSearchKeys)
{
using T = TypeParam;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 1, 2, X, 4, 5, X, 7, 8, X, X, 1, 2, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(8,
indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
numerals.release(),
null_count,
std::move(null_mask));
// Search space: [ [x], [1,2], [x,4,5,x], [], x, [7,8,x], [x], [1,2,x,1] ]
auto search_keys =
cudf::test::fixed_width_column_wrapper<T, int32_t>{{1, 2, 3, X, 2, 3, 1, 1}, null_at(3)};
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{{0, 1, 0, X, X, 0, 0, 1}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 0}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 3}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, BoolKeyVectorWithNullsInListsAndInSearchKeys)
{
using T = bool;
auto numerals = cudf::test::fixed_width_column_wrapper<T>{
{X, 0, 1, X, 1, 1, X, 1, 1, X, X, 0, 1, X, 1}, nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(8,
indices_col{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
numerals.release(),
null_count,
std::move(null_mask));
auto search_keys =
cudf::test::fixed_width_column_wrapper<T, int32_t>{{0, 1, 0, X, 0, 0, 1, 1}, null_at(3)};
// Search space: [ [x], [0,1], [x,1,1,x], [], x, [1,1,x], [x], [0,1,x,1] ]
// Search keys : [ 0, 1, 0, x, 0, 0, 1, 1 ]
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{{0, 1, 0, X, X, 0, 0, 1}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 1}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 3}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, StringKeyVectorWithNullsInListsAndInSearchKeys)
{
auto strings = cudf::test::strings_column_wrapper{
{"X", "1", "2", "X", "4", "5", "X", "7", "8", "X", "X", "1", "2", "X", "1"},
nulls_at({0, 3, 6, 9, 10, 13})};
auto input_null_mask_iter = null_at(4);
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(input_null_mask_iter, input_null_mask_iter + 8);
auto search_space = cudf::make_lists_column(
8,
cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 1, 3, 7, 7, 7, 10, 11, 15}.release(),
strings.release(),
null_count,
std::move(null_mask));
auto search_keys =
cudf::test::strings_column_wrapper{{"1", "2", "3", "X", "2", "3", "1", "1"}, null_at(3)};
// Search space: [ [x], [1,2], [x,4,5,x], [], x, [7,8,x], [x], [1,2,x,1] ]
// Search keys: [ 1, 2, 3, X, 2, 3, 1, 1]
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys);
auto expected = bools_col{{0, 1, 0, X, X, 0, 0, 1}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_FIRST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 0}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys, FIND_LAST);
auto expected = indices_col{{ABSENT, 1, ABSENT, X, X, ABSENT, ABSENT, 3}, nulls_at({3, 4})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TEST_F(ContainsTest, VectorTypeRelatedExceptions)
{
{
// Nested types unsupported.
auto list_of_lists = cudf::test::lists_column_wrapper<int32_t>{
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3},
{4, 5, 6}}}.release();
auto skey = cudf::test::fixed_width_column_wrapper<int32_t>{0, 1, 2};
EXPECT_THROW(cudf::lists::contains(list_of_lists->view(), skey), cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_lists->view(), skey, FIND_FIRST),
cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_lists->view(), skey, FIND_LAST),
cudf::data_type_error);
}
{
// Search key must match list elements in type.
auto list_of_ints =
cudf::test::lists_column_wrapper<int32_t>{
{0, 1, 2},
{3, 4, 5},
}
.release();
auto skey = cudf::test::strings_column_wrapper{"Hello", "World"};
EXPECT_THROW(cudf::lists::contains(list_of_ints->view(), skey), cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), skey, FIND_FIRST),
cudf::data_type_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), skey, FIND_LAST),
cudf::data_type_error);
}
{
// Search key column size must match lists column size.
auto list_of_ints =
cudf::test::lists_column_wrapper<int32_t>{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}.release();
auto skey = cudf::test::fixed_width_column_wrapper<int32_t>{0, 1, 2, 3};
EXPECT_THROW(cudf::lists::contains(list_of_ints->view(), skey), cudf::logic_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), skey, FIND_FIRST), cudf::logic_error);
EXPECT_THROW(cudf::lists::index_of(list_of_ints->view(), skey, FIND_LAST), cudf::logic_error);
}
}
template <typename T>
struct TypedContainsNaNsTest : public ContainsTest {};
TYPED_TEST_SUITE(TypedContainsNaNsTest, cudf::test::FloatingPointTypes);
namespace {
template <typename T>
T get_nan(char const* nan_contents)
{
return std::nan(nan_contents);
}
template <>
float get_nan<float>(char const* nan_contents)
{
return std::nanf(nan_contents);
}
} // namespace
TYPED_TEST(TypedContainsNaNsTest, ListWithNaNsScalar)
{
using T = TypeParam;
auto nan_1 = get_nan<T>("1");
auto nan_2 = get_nan<T>("2");
auto nan_3 = get_nan<T>("3");
auto search_space = cudf::test::lists_column_wrapper<T>{
{0.0, 1.0, 2.0},
{3, 4, 5},
{6, 7, 8},
{9, 0, 1},
{nan_1, 3.0, 4.0},
{5, 6, 7},
{8, nan_2, 0},
{},
{1, 2, 3},
{}}.release();
auto search_key_nan = create_scalar_search_key<T>(nan_3);
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_nan);
auto expected = bools_col{0, 0, 0, 0, 1, 0, 1, 0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), *search_key_nan, FIND_FIRST);
auto expected =
indices_col{ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT, 1, ABSENT, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), *search_key_nan, FIND_LAST);
auto expected =
indices_col{ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT, 1, ABSENT, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsNaNsTest, ListWithNaNsContainsVector)
{
// Test that different bit representations of NaN values
// are recognized as NaN.
// Also checks that a null handling is not broken by the
// presence of NaN values:
// 1. If the search key is null, null is still returned.
// 2. If the list contains a null, and the non-null search
// key is not found:
// a) contains() returns `null`.
// b) index_of() returns -1.
using T = TypeParam;
auto nan_1 = get_nan<T>("1");
auto nan_2 = get_nan<T>("2");
auto nan_3 = get_nan<T>("3");
auto search_space = cudf::test::lists_column_wrapper<T>{
{0.0, 1.0, 2.0},
{{3, 4, 5}, null_at(2)}, // i.e. {3, 4, ∅}.
{6, 7, 8},
{9, 0, 1},
{nan_1, 3.0, 4.0},
{5, 6, 7},
{8, nan_2, 0},
{},
{1, 2, 3},
{}}.release();
auto search_key_values = std::vector<T>{1.0, 2.0, 3.0, nan_3, nan_3, nan_3, 0.0, nan_3, 2.0, 0.0};
{
// With nulls in the search key rows. (At index 2.)
auto search_keys =
cudf::test::fixed_width_column_wrapper<T>{
search_key_values.begin(), search_key_values.end(), null_at(2)}
.release();
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys->view());
auto expected = bools_col{{1, 0, 0, 0, 1, 0, 1, 0, 1, 0}, null_at(2)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys->view(), FIND_FIRST);
auto expected =
indices_col{{1, ABSENT, X, ABSENT, 0, ABSENT, 2, ABSENT, 1, ABSENT}, nulls_at({2})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys->view(), FIND_LAST);
auto expected =
indices_col{{1, ABSENT, X, ABSENT, 0, ABSENT, 2, ABSENT, 1, ABSENT}, nulls_at({2})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
{
// No nulls in the search key rows.
auto search_keys =
cudf::test::fixed_width_column_wrapper<T>(search_key_values.begin(), search_key_values.end())
.release();
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_keys->view());
auto expected = bools_col{1, 0, 0, 0, 1, 0, 1, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_keys->view(), FIND_FIRST);
auto expected = indices_col{1, ABSENT, ABSENT, ABSENT, 0, ABSENT, 2, ABSENT, 1, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_keys->view(), FIND_LAST);
auto expected = indices_col{1, ABSENT, ABSENT, ABSENT, 0, ABSENT, 2, ABSENT, 1, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
}
template <typename T>
struct TypedContainsDecimalsTest : public ContainsTest {};
TYPED_TEST_SUITE(TypedContainsDecimalsTest, cudf::test::FixedPointTypes);
TYPED_TEST(TypedContainsDecimalsTest, ScalarKey)
{
using T = TypeParam;
auto const search_space = [] {
auto const values = std::vector<typename T::rep>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3};
auto decimals = cudf::test::fixed_point_column_wrapper<typename T::rep>{
values.begin(), values.end(), numeric::scale_type{0}};
auto list_offsets = indices_col{0, 3, 6, 9, 12, 15, 18, 21, 21, 24, 24};
return cudf::make_lists_column(10, list_offsets.release(), decimals.release(), 0, {});
}();
auto search_key_one =
cudf::make_fixed_point_scalar<T>(typename T::rep{1}, numeric::scale_type{0});
// Search space: [[0,1,2], [3,4,5], [6,7,8], [9,0,1], [2,3,4], [5,6,7], [8,9,0], [], [1,2,3], []]
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), *search_key_one);
auto expected = bools_col{1, 0, 0, 1, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_FIRST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), *search_key_one, FIND_LAST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedContainsDecimalsTest, VectorKey)
{
using T = TypeParam;
auto const search_space = [] {
auto const values = std::vector<typename T::rep>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3};
auto decimals = cudf::test::fixed_point_column_wrapper<typename T::rep>{
values.begin(), values.end(), numeric::scale_type{0}};
auto list_offsets = indices_col{0, 3, 6, 9, 12, 15, 18, 21, 21, 24, 24};
return cudf::make_lists_column(10, list_offsets.release(), decimals.release(), 0, {});
}();
auto search_key = cudf::test::fixed_point_column_wrapper<typename T::rep>{
{1, 2, 3, 1, 2, 3, 1, 2, 3, 1},
numeric::scale_type{
0}}.release();
// Search space: [ [0,1,2], [3,4,5], [6,7,8], [9,0,1], [2,3,4], [5,6,7], [8,9,0], [], [1,2,3], []
// ] Search keys: [ 1, 2, 3, 1, 2, 3, 1, 2, 3, 1 ]
{
// CONTAINS
auto result = cudf::lists::contains(search_space->view(), search_key->view());
auto expected = bools_col{1, 0, 0, 1, 1, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto result = cudf::lists::index_of(search_space->view(), search_key->view(), FIND_FIRST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, 0, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto result = cudf::lists::index_of(search_space->view(), search_key->view(), FIND_LAST);
auto expected = indices_col{1, ABSENT, ABSENT, 2, 0, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
template <typename T>
struct TypedStructContainsTest : public ContainsTest {};
TYPED_TEST_SUITE(TypedStructContainsTest, ContainsTestTypes);
TYPED_TEST(TypedStructContainsTest, EmptyInputTest)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto offsets = indices_col{};
auto data = tdata_col{};
auto child = cudf::test::structs_column_wrapper{{data}};
return cudf::make_lists_column(0, offsets.release(), child.release(), 0, {});
}();
auto const scalar_key = [] {
auto child = tdata_col{0};
return make_struct_scalar(child);
}();
auto const column_key = [] {
auto child = tdata_col{};
return cudf::test::structs_column_wrapper{{child}};
}();
auto const result1 = cudf::lists::contains(lists->view(), scalar_key);
auto const result2 = cudf::lists::contains(lists->view(), column_key);
auto const expected = bools_col{};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result1);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result2);
}
TYPED_TEST(TypedStructContainsTest, ScalarKeyNoNullLists)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto offsets = indices_col{0, 4, 7, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, 1, 2, 1,
3, 4, 5,
6, 7, 8,
9, 0, 1, 3, 1,
2, 3, 4,
5, 6, 7,
8, 9, 0,
1, 2, 1, 3
};
auto data2 = tdata_col{0, 1, 2, 3,
0, 1, 2,
0, 1, 2,
1, 1, 2, 2, 2,
0, 1, 2,
0, 1, 2,
0, 1, 2,
1, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}};
return cudf::make_lists_column(10, offsets.release(), child.release(), 0, {});
}();
auto const key = [] {
auto child1 = tdata_col{1};
auto child2 = tdata_col{1};
return make_struct_scalar(child1, child2);
}();
{
// CONTAINS
auto const result = cudf::lists::contains(lists->view(), key);
auto const expected = bools_col{1, 0, 0, 0, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(lists->view());
auto const expected = bools_col{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_FIRST);
auto const expected =
indices_col{1, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_LAST);
auto const expected =
indices_col{1, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, ScalarKeyWithNullLists)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto offsets = indices_col{0, 4, 7, 10, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, 1, 2, 1,
3, 4, 5,
6, 7, 8,
9, 0, 1, 3, 1,
2, 3, 4,
5, 6, 7,
8, 9, 0,
1, 2, 1, 3
};
auto data2 = tdata_col{0, 1, 2, 3,
0, 1, 2,
0, 1, 2,
1, 1, 2, 2, 2,
0, 1, 2,
0, 1, 2,
0, 1, 2,
1, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}};
auto const validity_iter = nulls_at({3, 10});
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(validity_iter, validity_iter + 11);
return cudf::make_lists_column(
11, offsets.release(), child.release(), null_count, std::move(null_mask));
}();
auto const key = [] {
auto child1 = tdata_col{1};
auto child2 = tdata_col{1};
return make_struct_scalar(child1, child2);
}();
{
// CONTAINS
auto const result = cudf::lists::contains(lists->view(), key);
auto const expected = bools_col{{1, 0, 0, X, 0, 0, 0, 0, 0, 1, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(lists->view());
auto const expected = bools_col{{0, 0, 0, X, 0, 0, 0, 0, 0, 0, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_FIRST);
auto const expected = indices_col{
{1, ABSENT, ABSENT, X, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_LAST);
auto const expected = indices_col{
{1, ABSENT, ABSENT, X, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, X}, nulls_at({3, 10})};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, SlicedListsColumnNoNulls)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists_original = [] {
auto offsets = indices_col{0, 4, 7, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, 1, 2, 1,
3, 4, 5,
6, 7, 8,
9, 0, 1, 3, 1,
2, 3, 4,
5, 6, 7,
8, 9, 0,
1, 2, 1, 3
};
auto data2 = tdata_col{0, 1, 2, 3,
0, 1, 2,
0, 1, 2,
1, 1, 2, 2, 2,
0, 1, 2,
0, 1, 2,
0, 1, 2,
1, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}};
return cudf::make_lists_column(10, offsets.release(), child.release(), 0, {});
}();
auto const lists = cudf::slice(lists_original->view(), {3, 10})[0];
auto const key = [] {
auto child1 = tdata_col{1};
auto child2 = tdata_col{1};
return make_struct_scalar(child1, child2);
}();
{
// CONTAINS
auto const result = cudf::lists::contains(lists, key);
auto const expected = bools_col{0, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(lists);
auto const expected = bools_col{0, 0, 0, 0, 0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists, key, FIND_FIRST);
auto const expected = indices_col{ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists, key, FIND_LAST);
auto const expected = indices_col{ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, ScalarKeyNoNullListsWithNullStructs)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto offsets = indices_col{0, 4, 7, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, X, 2, 1,
3, 4, 5,
6, 7, 8,
X, 0, 1, 3, 1,
X, 3, 4,
5, 6, 7,
8, 9, 0,
X, 2, 1, 3
};
auto data2 = tdata_col{0, X, 2, 1,
0, 1, 2,
0, 1, 2,
X, 1, 2, 2, 2,
X, 1, 2,
0, 1, 2,
0, 1, 2,
X, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}, nulls_at({1, 10, 15, 24})};
return cudf::make_lists_column(10, offsets.release(), child.release(), 0, {});
}();
auto const key = [] {
auto child1 = tdata_col{1};
auto child2 = tdata_col{1};
return make_struct_scalar(child1, child2);
}();
{
// CONTAINS
auto const result = cudf::lists::contains(lists->view(), key);
auto const expected = bools_col{1, 0, 0, 0, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(lists->view());
auto const expected = bools_col{1, 0, 0, 1, 1, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_FIRST);
auto const expected =
indices_col{3, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists->view(), key, FIND_LAST);
auto const expected =
indices_col{3, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, ColumnKeyNoNullLists)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto offsets = indices_col{0, 4, 7, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, 1, 2, 1,
3, 4, 3,
6, 7, 8,
9, 0, 1, 3, 1,
2, 3, 4,
5, 6, 7,
8, 9, 0,
1, 2, 1, 3
};
auto data2 = tdata_col{0, 1, 2, 3,
0, 0, 0,
0, 1, 2,
1, 1, 2, 2, 2,
0, 1, 2,
0, 1, 2,
0, 1, 2,
1, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}};
return cudf::make_lists_column(10, offsets.release(), child.release(), 0, {});
}();
auto const keys = [] {
auto child1 = tdata_col{1, 3, 1, 1, 2, 1, 0, 0, 1, 0};
auto child2 = tdata_col{1, 0, 1, 1, 2, 1, 0, 0, 1, 0};
return cudf::test::structs_column_wrapper{{child1, child2}};
}();
{
// CONTAINS
auto const result = cudf::lists::contains(lists->view(), keys);
auto const expected = bools_col{1, 1, 0, 0, 0, 0, 0, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists->view(), keys, FIND_FIRST);
auto const expected =
indices_col{1, 0, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists->view(), keys, FIND_LAST);
auto const expected =
indices_col{1, 2, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, ColumnKeyWithSlicedListsNoNulls)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists_original = [] {
auto offsets = indices_col{0, 4, 7, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, 1, 2, 1,
3, 4, 3,
6, 7, 8,
9, 0, 1, 3, 1,
2, 3, 4,
5, 6, 7,
8, 9, 0,
1, 2, 1, 3
};
auto data2 = tdata_col{0, 1, 2, 3,
0, 0, 0,
0, 1, 2,
1, 1, 2, 2, 2,
0, 1, 2,
0, 1, 2,
0, 1, 2,
1, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}};
return cudf::make_lists_column(10, offsets.release(), child.release(), 0, {});
}();
auto const keys_original = [] {
auto child1 = tdata_col{1, 9, 1, 6, 2, 1, 0, 0, 1, 0};
auto child2 = tdata_col{1, 1, 1, 1, 2, 1, 0, 0, 1, 0};
return cudf::test::structs_column_wrapper{{child1, child2}};
}();
auto const lists = cudf::slice(lists_original->view(), {3, 7})[0];
auto const keys = cudf::slice(keys_original, {1, 5})[0];
{
// CONTAINS
auto const result = cudf::lists::contains(lists, keys);
auto const expected = bools_col{1, 0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists, keys, FIND_FIRST);
auto const expected = indices_col{0, ABSENT, 1, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists, keys, FIND_LAST);
auto const expected = indices_col{0, ABSENT, 1, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
TYPED_TEST(TypedStructContainsTest, ColumnKeyWithSlicedListsHavingNulls)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists_original = [] {
auto offsets = indices_col{0, 4, 7, 10, 10, 15, 18, 21, 24, 24, 28, 28};
// clang-format off
auto data1 = tdata_col{0, X, 2, 1,
3, 4, 5,
6, 7, 8,
X, 0, 1, 3, 1,
X, 3, 4,
5, 6, 6,
8, 9, 0,
X, 2, 1, 3
};
auto data2 = tdata_col{0, X, 2, 1,
0, 1, 2,
0, 1, 2,
X, 1, 2, 2, 2,
X, 1, 2,
0, 1, 1,
0, 1, 2,
X, 0, 1, 1
};
// clang-format on
auto child = cudf::test::structs_column_wrapper{{data1, data2}, nulls_at({1, 10, 15, 24})};
auto const validity_iter = nulls_at({3, 10});
auto [null_mask, null_count] =
cudf::test::detail::make_null_mask(validity_iter, validity_iter + 11);
return cudf::make_lists_column(
11, offsets.release(), child.release(), null_count, std::move(null_mask));
}();
auto const keys_original = [] {
auto child1 = tdata_col{{1, X, 1, 6, X, 1, 0, 0, 1, 0, 1}, null_at(4)};
auto child2 = tdata_col{{1, X, 1, 1, X, 1, 0, 0, 1, 0, 1}, null_at(4)};
return cudf::test::structs_column_wrapper{{child1, child2}, null_at(1)};
}();
auto const lists = cudf::slice(lists_original->view(), {4, 8})[0];
auto const keys = cudf::slice(keys_original, {1, 5})[0];
{
// CONTAINS
auto const result = cudf::lists::contains(lists, keys);
auto const expected = bools_col{{X, 0, 1, 0}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(lists, keys, FIND_FIRST);
auto const expected = indices_col{{X, ABSENT, 1, ABSENT}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(lists, keys, FIND_LAST);
auto const expected = indices_col{{X, ABSENT, 2, ABSENT}, null_at(0)};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
template <typename T>
struct TypedListContainsTest : public ContainsTest {};
TYPED_TEST_SUITE(TypedListContainsTest, ContainsTestTypes);
TYPED_TEST(TypedListContainsTest, ScalarKeyLists)
{
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 lists_no_nulls = lists_col{lists_col{{0, 1, 2}, // list0
{3, 4, 5},
{0, 1, 2},
{9, 0, 1, 3, 1}},
lists_col{{2, 3, 4}, // list1
{3, 4, 5},
{8, 9, 0},
{}},
lists_col{{0, 2, 1}, // list2
{}}};
auto const lists_have_nulls = lists_col{lists_col{{{0, 1, 2}, // list0
{} /*NULL*/,
{0, 1, 2},
{9, 0, 1, 3, 1}},
null_at(1)},
lists_col{{{} /*NULL*/, // list1
{3, 4, 5},
{8, 9, 0},
{}},
null_at(0)},
lists_col{{0, 2, 1}, // list2
{}}};
auto const key = [] {
auto const child = tdata_col{0, 1, 2};
return cudf::list_scalar(child);
}();
auto const do_test = [&](auto const& lists, bool has_nulls) {
{
// CONTAINS
auto const result = cudf::lists::contains(cudf::lists_column_view{lists}, key);
auto const expected = bools_col{1, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(cudf::lists_column_view{lists});
auto const expected = has_nulls ? bools_col{1, 1, 0} : bools_col{0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_FIRST);
auto const expected = indices_col{0, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_LAST);
auto const expected = indices_col{2, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
};
do_test(lists_no_nulls, false);
do_test(lists_have_nulls, true);
}
TYPED_TEST(TypedListContainsTest, SlicedListsColumn)
{
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 lists_no_nulls_original = lists_col{lists_col{{0, 0, 0}, // list-2 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}},
lists_col{{0, 0, 0}, // list-1 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}},
lists_col{{0, 1, 2}, // list0
{3, 4, 5},
{0, 1, 2},
{9, 0, 1, 3, 1}},
lists_col{{2, 3, 4}, // list1
{3, 4, 5},
{8, 9, 0},
{}},
lists_col{{0, 2, 1}, // list2
{}},
lists_col{{0, 0, 0}, // list3 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}},
lists_col{{0, 0, 0}, // list4 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}}};
auto const lists_have_nulls_original = lists_col{lists_col{{0, 0, 0}, // list-1 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}},
lists_col{{{0, 1, 2}, // list0
{} /*NULL*/,
{0, 1, 2},
{9, 0, 1, 3, 1}},
null_at(1)},
lists_col{{{} /*NULL*/, // list1
{3, 4, 5},
{8, 9, 0},
{}},
null_at(0)},
lists_col{{0, 2, 1}, // list2
{}},
lists_col{{0, 0, 0}, // list3 (don't care)
{0, 1, 2},
{0, 1, 2},
{0, 0, 0}}};
auto const lists_no_nulls = cudf::slice(lists_no_nulls_original, {2, 5})[0];
auto const lists_have_nulls = cudf::slice(lists_have_nulls_original, {1, 4})[0];
auto const key = [] {
auto const child = tdata_col{0, 1, 2};
return cudf::list_scalar(child);
}();
auto const do_test = [&](auto const& lists, bool has_nulls) {
{
// CONTAINS
auto const result = cudf::lists::contains(cudf::lists_column_view{lists}, key);
auto const expected = bools_col{1, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(cudf::lists_column_view{lists});
auto const expected = has_nulls ? bools_col{1, 1, 0} : bools_col{0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_FIRST);
auto const expected = indices_col{0, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_LAST);
auto const expected = indices_col{2, ABSENT, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
};
do_test(lists_no_nulls, false);
do_test(lists_have_nulls, true);
}
TYPED_TEST(TypedListContainsTest, ColumnKeyLists)
{
using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>;
auto constexpr null = int32_t{0};
auto const lists_no_nulls = lists_col{lists_col{{0, 0, 2}, // list0
{3, 4, 5},
{0, 0, 2},
{9, 0, 1, 3, 1}},
lists_col{{2, 3, 4}, // list1
{3, 4, 5},
{2, 3, 4},
{}},
lists_col{{0, 2, 0}, // list2
{0, 2, 0},
{3, 4, 5},
{}}};
auto const lists_have_nulls = lists_col{lists_col{{lists_col{{0, null, 2}, null_at(1)}, // list0
lists_col{} /*NULL*/,
lists_col{{0, null, 2}, null_at(1)},
lists_col{9, 0, 1, 3, 1}},
null_at(1)},
lists_col{{lists_col{} /*NULL*/, // list1
lists_col{3, 4, 5},
lists_col{2, 3, 4},
lists_col{}},
null_at(0)},
lists_col{lists_col{0, 2, 1}, // list2
lists_col{{0, 2, null}, null_at(2)},
lists_col{3, 4, 5},
lists_col{}}};
auto const key = lists_col{
lists_col{{0, null, 2}, null_at(1)}, lists_col{2, 3, 4}, lists_col{{0, 2, null}, null_at(2)}};
auto const do_test = [&](auto const& lists, bool has_nulls) {
{
// CONTAINS
auto const result = cudf::lists::contains(cudf::lists_column_view{lists}, key);
auto const expected = has_nulls ? bools_col{1, 1, 1} : bools_col{0, 1, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// CONTAINS NULLS
auto const result = cudf::lists::contains_nulls(cudf::lists_column_view{lists});
auto const expected = has_nulls ? bools_col{1, 1, 0} : bools_col{0, 0, 0};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_FIRST);
auto const expected = has_nulls ? indices_col{0, 2, 1} : indices_col{ABSENT, 0, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result = cudf::lists::index_of(cudf::lists_column_view{lists}, key, FIND_LAST);
auto const expected = has_nulls ? indices_col{2, 2, 1} : indices_col{ABSENT, 2, ABSENT};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
};
do_test(lists_no_nulls, false);
do_test(lists_have_nulls, true);
}
TYPED_TEST(TypedListContainsTest, ColumnKeyWithListsOfStructsNoNulls)
{
using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>;
auto const lists = [] {
auto child_offsets = indices_col{0, 3, 6, 9, 14, 17, 20, 23, 23};
// clang-format off
auto data1 = tdata_col{0, 0, 2,
3, 4, 5,
0, 0, 2,
9, 0, 1, 3, 1,
0, 2, 0,
0, 0, 2,
3, 4, 5
};
auto data2 = tdata_col{10, 10, 12,
13, 14, 15,
10, 10, 12,
19, 10, 11, 13, 11,
10, 12, 10,
10, 10, 12,
13, 14, 15
};
// clang-format on
auto structs = cudf::test::structs_column_wrapper{{data1, data2}};
auto child = cudf::make_lists_column(8, child_offsets.release(), structs.release(), 0, {});
auto offsets = indices_col{0, 4, 8};
return cudf::make_lists_column(2, offsets.release(), std::move(child), 0, {});
}();
auto const key = [] {
auto data1 = tdata_col{0, 0, 2};
auto data2 = tdata_col{10, 10, 12};
auto const child = cudf::test::structs_column_wrapper{{data1, data2}};
return cudf::list_scalar(child);
}();
{
// CONTAINS
auto const result = cudf::lists::contains(cudf::lists_column_view{lists->view()}, key);
auto const expected = bools_col{1, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_FIRST
auto const result =
cudf::lists::index_of(cudf::lists_column_view{lists->view()}, key, FIND_FIRST);
auto const expected = indices_col{0, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
{
// FIND_LAST
auto const result =
cudf::lists::index_of(cudf::lists_column_view{lists->view()}, key, FIND_LAST);
auto const expected = indices_col{2, 1};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *result);
}
}
| 0 |
rapidsai_public_repos/cudf/cpp/tests
|
rapidsai_public_repos/cudf/cpp/tests/lists/sort_lists_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/lists/sorting.hpp>
template <typename T>
using LCW = cudf::test::lists_column_wrapper<T, int32_t>;
auto generate_sorted_lists(cudf::lists_column_view const& input,
cudf::order column_order,
cudf::null_order null_precedence)
{
return std::pair{cudf::lists::sort_lists(input, column_order, null_precedence),
cudf::lists::stable_sort_lists(input, column_order, null_precedence)};
}
template <typename T>
struct SortLists : public cudf::test::BaseFixture {};
using TypesForTest = cudf::test::Concat<cudf::test::NumericTypes, cudf::test::FixedPointTypes>;
TYPED_TEST_SUITE(SortLists, TypesForTest);
TYPED_TEST(SortLists, NoNull)
{
using T = TypeParam;
// List<T>
LCW<T> list{{3, 2, 1, 4}, {5}, {10, 8, 9}, {6, 7}};
// Ascending
// LCW<int> order{{2, 1, 0, 3}, {0}, {1, 2, 0}, {0, 1}};
LCW<T> expected{{1, 2, 3, 4}, {5}, {8, 9, 10}, {6, 7}};
{
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::ASCENDING, cudf::null_order::AFTER);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::ASCENDING, cudf::null_order::BEFORE);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
// Descending
// LCW<int> order{{3, 0, 1, 2}, {0}, {0, 1, 2}, {1, 0}};
LCW<T> expected2{{4, 3, 2, 1}, {5}, {10, 9, 8}, {7, 6}};
{
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::DESCENDING, cudf::null_order::AFTER);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected2);
}
{
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::DESCENDING, cudf::null_order::BEFORE);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected2);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected2);
}
}
TYPED_TEST(SortLists, Null)
{
using T = TypeParam;
if (std::is_same_v<T, bool>) return;
std::vector<bool> valids_o{1, 1, 0, 1};
std::vector<bool> valids_a{1, 1, 1, 0};
std::vector<bool> valids_b{0, 1, 1, 1};
// List<T>
LCW<T> list{{{3, 2, 4, 1}, valids_o.begin()}, {5}, {10, 8, 9}, {6, 7}};
// LCW<int> order{{2, 1, 3, 0}, {0}, {1, 2, 0}, {0, 1}};
{
LCW<T> expected{{{1, 2, 3, 4}, valids_a.begin()}, {5}, {8, 9, 10}, {6, 7}};
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::ASCENDING, cudf::null_order::AFTER);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
LCW<T> expected{{{4, 1, 2, 3}, valids_b.begin()}, {5}, {8, 9, 10}, {6, 7}};
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::ASCENDING, cudf::null_order::BEFORE);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
// Descending
// LCW<int> order{{3, 0, 1, 2}, {0}, {0, 1, 2}, {1, 0}};
{
LCW<T> expected{{{4, 3, 2, 1}, valids_b.begin()}, {5}, {10, 9, 8}, {7, 6}};
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::DESCENDING, cudf::null_order::AFTER);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
LCW<T> expected{{{3, 2, 1, 4}, valids_a.begin()}, {5}, {10, 9, 8}, {7, 6}};
auto const [sorted_lists, stable_sorted_lists] = generate_sorted_lists(
cudf::lists_column_view{list}, cudf::order::DESCENDING, cudf::null_order::BEFORE);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
}
using SortListsInt = SortLists<int>;
TEST_F(SortListsInt, Empty)
{
using T = int;
{
LCW<T> l{};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
{
LCW<T> l{LCW<T>{}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
{
LCW<T> l{LCW<T>{}, LCW<T>{}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
}
TEST_F(SortListsInt, Single)
{
using T = int;
{
LCW<T> l{1};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
{
LCW<T> l{{1, 2, 3}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
}
TEST_F(SortListsInt, NullRows)
{
using T = int;
std::vector<int> valids{0, 1, 0};
LCW<T> l{{{1, 2, 3}, {4, 5, 6}, {7}}, valids.begin()}; // offset 0, 0, 3, 3
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{l}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), l);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), l);
}
// Disabling this test.
// Reason: After this exception "cudaErrorAssert device-side assert triggered", further tests fail
TEST_F(SortListsInt, DISABLED_Depth)
{
using T = int;
LCW<T> l1{LCW<T>{{1, 2}, {3}}, LCW<T>{{4, 5}}};
// device exception
EXPECT_THROW(cudf::lists::sort_lists(cudf::lists_column_view{l1}, {}, {}), std::exception);
}
TEST_F(SortListsInt, Sliced)
{
using T = int;
LCW<T> l{{3, 2, 1, 4}, {7, 5, 6}, {8, 9}, {10}};
{
auto const sliced_list = cudf::slice(l, {0, 4})[0];
auto const expected = LCW<T>{{1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{sliced_list}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
auto const sliced_list = cudf::slice(l, {1, 4})[0];
auto const expected = LCW<T>{{5, 6, 7}, {8, 9}, {10}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{sliced_list}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
auto const sliced_list = cudf::slice(l, {1, 2})[0];
auto const expected = LCW<T>{{5, 6, 7}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{sliced_list}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
{
auto const sliced_list = cudf::slice(l, {0, 2})[0];
auto const expected = LCW<T>{{1, 2, 3, 4}, {5, 6, 7}};
auto const [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{sliced_list}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUAL(stable_sorted_lists->view(), expected);
}
}
using SortListsDouble = SortLists<double>;
TEST_F(SortListsDouble, InfinityAndNaN)
{
auto constexpr NaN = std::numeric_limits<double>::quiet_NaN();
auto constexpr Inf = std::numeric_limits<double>::infinity();
using LCW = cudf::test::lists_column_wrapper<double>;
{
LCW input{-0.0, -NaN, -NaN, NaN, Inf, -Inf, 7, 5, 6, NaN, Inf, -Inf, -NaN, -NaN, -0.0};
auto [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{input}, {}, {});
LCW expected{-Inf, -Inf, -0, -0, 5, 6, 7, Inf, Inf, -NaN, -NaN, NaN, NaN, -NaN, -NaN};
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(stable_sorted_lists->view(), expected);
}
// This data includes a row with over 200 elements to test the
// radix sort is not used in the logic path in segmented_sort.
// Technically radix sort is not expected to be used in either case.
{
// clang-format off
LCW input{0.0, -0.0, -NaN, -NaN, NaN, Inf, -Inf,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
NaN, Inf, -Inf, -NaN, -NaN, -0.0, 0.0};
LCW expected{-Inf, -Inf, 0.0, -0.0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
Inf, Inf, -NaN, -NaN, NaN, NaN, -NaN, -NaN};
// clang-format on
auto [sorted_lists, stable_sorted_lists] =
generate_sorted_lists(cudf::lists_column_view{input}, {}, {});
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(sorted_lists->view(), expected);
CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(stable_sorted_lists->view(), expected);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.