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/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/strings/replace.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_replace * @{ * @file */ /** * @brief Replaces target string within each string with the specified * replacement string. * * This function searches each string in the column for the target string. * If found, the target string is replaced by the repl string within the * input string. If not found, the output entry is just a copy of the * corresponding input string. * * Specifying an empty string for repl will essentially remove the target * string if found in each string. * * Null string entries will return null output string entries. * * @code{.pseudo} * Example: * s = ["hello", "goodbye"] * r1 = replace(s,"o","OOO") * r1 is now ["hellOOO","gOOOOOOdbye"] * r2 = replace(s,"oo","") * r2 is now ["hello","gdbye"] * @endcode * * @throw cudf::logic_error if target is an empty string. * * @param input Strings column for this operation * @param target String to search for within each string * @param repl Replacement string if target is found * @param maxrepl Maximum times to replace if target appears multiple times in the input string. * Default of -1 specifies replace all occurrences of target in each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> replace( strings_column_view const& input, string_scalar const& target, string_scalar const& repl, cudf::size_type maxrepl = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief This function replaces each string in the column with the provided * repl string within the [start,stop) character position range. * * Null string entries will return null output string entries. * * Position values are 0-based meaning position 0 is the first character * of each string. * * This function can be used to insert a string into specific position * by specifying the same position value for start and stop. The repl * string can be appended to each string by specifying -1 for both * start and stop. * * @code{.pseudo} * Example: * s = ["abcdefghij","0123456789"] * r = s.replace_slice(s,2,5,"z") * r is now ["abzfghij", "01z56789"] * @endcode * * @throw cudf::logic_error if start is greater than stop. * * @param input Strings column for this operation. * @param repl Replacement string for specified positions found. * Default is empty string. * @param start Start position where repl will be added. * Default is 0, first character position. * @param stop End position (exclusive) to use for replacement. * Default of -1 specifies the end of each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> replace_slice( strings_column_view const& input, string_scalar const& repl = string_scalar(""), size_type start = 0, size_type stop = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Replaces substrings matching a list of targets with the corresponding * replacement strings. * * For each string in strings, the list of targets is searched within that string. * If a target string is found, it is replaced by the corresponding entry in the repls column. * All occurrences found in each string are replaced. * * This does not use regex to match targets in the string. * * Null string entries will return null output string entries. * * The repls argument can optionally contain a single string. In this case, all * matching target substrings will be replaced by that single string. * * @code{.pseudo} * Example: * s = ["hello", "goodbye"] * tgts = ["e","o"] * repls = ["EE","OO"] * r1 = replace(s,tgts,repls) * r1 is now ["hEEllO", "gOOOOdbyEE"] * tgts = ["e","oo"] * repls = ["33",""] * r2 = replace(s,tgts,repls) * r2 is now ["h33llo", "gdby33"] * @endcode * * @throw cudf::logic_error if targets and repls are different sizes except * if repls is a single string. * @throw cudf::logic_error if targets or repls contain null entries. * * @param input Strings column for this operation * @param targets Strings to search for in each string * @param repls Corresponding replacement strings for target strings * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> replace( strings_column_view const& input, strings_column_view const& targets, strings_column_view const& repls, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/strings/repeat_strings.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_copy * @{ * @file * @brief Strings APIs for copying strings. */ /** * @brief Repeat the given string scalar a given number of times * * An output string scalar is generated by repeating the input string by a number of times given by * the `repeat_times` parameter. * * In special cases: * - If `repeat_times` is not a positive value, an empty (valid) string scalar will be returned. * - An invalid input scalar will always result in an invalid output scalar regardless of the * value of `repeat_times` parameter. * * @code{.pseudo} * Example: * s = '123XYZ-' * out = repeat_strings(s, 3) * out is '123XYZ-123XYZ-123XYZ-' * @endcode * * @throw std::overflow_error if the size of the output string scalar exceeds the maximum value that * can be stored by the scalar: `input.size() * repeat_times > max of size_type` * * @param input The scalar containing the string to repeat * @param repeat_times The number of times the input string is repeated * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned string scalar * @return New string scalar in which the input string is repeated */ std::unique_ptr<string_scalar> repeat_string( string_scalar const& input, size_type repeat_times, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Repeat each string in the given strings column a given number of times * * An output strings column is generated by repeating each string from the input strings column by * the number of times given by the `repeat_times` parameter. * * In special cases: * - If `repeat_times` is not a positive number, a non-null input string will always result in * an empty output string. * - A null input string will always result in a null output string regardless of the value of the * `repeat_times` parameter. * * @code{.pseudo} * Example: * strs = ['aa', null, '', 'bbc'] * out = repeat_strings(strs, 3) * out is ['aaaaaa', null, '', 'bbcbbcbbc'] * @endcode * * @param input The column containing strings to repeat * @param repeat_times The number of times each input string is repeated * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned strings column * @return New column containing the repeated strings */ std::unique_ptr<column> repeat_strings( strings_column_view const& input, size_type repeat_times, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Repeat each string in the given strings column by the numbers of times given in another * numeric column * * An output strings column is generated by repeating each of the input string by a number of times * given by the corresponding row in a `repeat_times` numeric column. * * In special cases: * - Any null row (from either the input strings column or the `repeat_times` column) will always * result in a null output string. * - If any value in the `repeat_times` column is not a positive number and its corresponding input * string is not null, the output string will be an empty string. * * @code{.pseudo} * Example: * strs = ['aa', null, '', 'bbc-'] * repeat_times = [ 1, 2, 3, 4 ] * out = repeat_strings(strs, repeat_times) * out is ['aa', null, '', 'bbc-bbc-bbc-bbc-'] * @endcode * * @throw cudf::logic_error if the input `repeat_times` is not an integer type * @throw cudf::logic_error if the input columns have different sizes. * * @param input The column containing strings to repeat * @param repeat_times The column containing numbers of times that the corresponding input strings * for each row are repeated * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned strings column * @return New column containing the repeated strings. */ std::unique_ptr<column> repeat_strings( strings_column_view const& input, column_view const& repeat_times, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/strings/padding.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/side_type.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_modify * @{ * @file */ /** * @brief Add padding to each string using a provided character. * * If the string is already `width` or more characters, no padding is performed. * Also, no strings are truncated. * * Null string entries result in corresponding null entries in the output column. * * @code{.pseudo} * Example: * s = ['aa','bbb','cccc','ddddd'] * r = pad(s,4) * r is now ['aa ','bbb ','cccc','ddddd'] * @endcode * * @param input Strings instance for this operation * @param width The minimum number of characters for each string * @param side Where to place the padding characters; * Default is pad right (left justify) * @param fill_char Single UTF-8 character to use for padding; * Default is the space character * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with padded strings */ std::unique_ptr<column> pad( strings_column_view const& input, size_type width, side_type side = side_type::RIGHT, std::string_view fill_char = " ", rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Add '0' as padding to the left of each string. * * This is equivalent to `pad(width,left,'0')` but preserves the sign character * if it appears in the first position. * * If the string is already width or more characters, no padding is performed. * No strings are truncated. * * Null rows in the input result in corresponding null rows in the output column. * * @code{.pseudo} * Example: * s = ['1234','-9876','+0.34','-342567', '2+2'] * r = zfill(s,6) * r is now ['001234','-09876','+00.34','-342567', '0002+2'] * @endcode * * @param input Strings instance for this operation * @param width The minimum number of characters for each string * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of strings */ std::unique_ptr<column> zfill( strings_column_view const& input, size_type width, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/char_types/char_cases.hpp
/* * 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. */ #pragma once namespace cudf { namespace strings { namespace detail { /** * @brief Regenerates the special case mapping tables used to handle non-trivial unicode * character case conversions. * * 'special' cased characters are those defined as not having trivial single->single character * mappings when having upper(), lower() or titlecase() operations applied. Typically this is * for cases where a single character maps to multiple, but there are also cases of * non-reversible mappings, where: codepoint != lower(upper(code_point)). */ void generate_special_mapping_hash_table(); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/char_types/char_types.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/char_types/char_types_enum.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_types * @{ * @file */ /** * @brief Returns a boolean column identifying strings entries in which all * characters are of the type specified. * * The output row entry will be set to false if the corresponding string element * is empty or has at least one character not of the specified type. If all * characters fit the type then true is set in that output row entry. * * To ignore all but specific types, set the `verify_types` to those types * which should be checked. Otherwise, the default `ALL_TYPES` will verify all * characters match `types`. * * @code{.pseudo} * Example: * s = ['ab', 'a b', 'a7', 'a B'] * b1 = s.all_characters_of_type(s,LOWER) * b1 is [true, false, false, false] * b2 = s.all_characters_of_type(s,LOWER,LOWER|UPPER) * b2 is [true, true, true, false] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param types The character types to check in each string * @param verify_types Only verify against these character types. * Default `ALL_TYPES` means return `true` * iff all characters match `types`. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> all_characters_of_type( strings_column_view const& input, string_character_types types, string_character_types verify_types = string_character_types::ALL_TYPES, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Filter specific character types from a column of strings. * * To remove all characters of a specific type, set that type in * `types_to_remove` and set `types_to_keep` to `ALL_TYPES`. * * To filter out characters NOT of a select type, specify `ALL_TYPES` for * `types_to_remove` and which types to not remove in `types_to_keep`. * * @code{.pseudo} * Example: * s = ['ab', 'a b', 'a7bb', 'A7B234'] * s1 = s.filter_characters_of_type(s,NUMERIC,"",ALL_TYPES) * s1 is ['ab', 'a b', 'abb', 'AB'] * s2 = s.filter_characters_of_type(s,ALL_TYPES,"-",LOWER) * s2 is ['ab', 'a-b', 'a-bb', '------'] * @endcode * * In `s1` all NUMERIC types have been removed. * In `s2` all non-LOWER types have been replaced. * * One but not both parameters `types_to_remove` and `types_to_keep` must * be set to `ALL_TYPES`. * * Any null row results in a null entry for that row in the output column. * * @throw cudf::logic_error if neither or both `types_to_remove` and * `types_to_keep` are set to `ALL_TYPES`. * * @param input Strings instance for this operation * @param types_to_remove The character types to check in each string. * Use `ALL_TYPES` here to specify `types_to_keep` instead. * @param replacement The replacement character to use when removing characters * @param types_to_keep Default `ALL_TYPES` means all characters of * `types_to_remove` will be filtered. * @param mr Device memory resource used to allocate the returned column's device memory * @param stream CUDA stream used for device memory operations and kernel launches * @return New column of boolean results for each string */ std::unique_ptr<column> filter_characters_of_type( strings_column_view const& input, string_character_types types_to_remove, string_scalar const& replacement = string_scalar(""), string_character_types types_to_keep = string_character_types::ALL_TYPES, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/char_types/char_types_enum.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cstdint> #include <type_traits> namespace cudf { namespace strings { /** * @addtogroup strings_types * @{ * @file */ /** * @brief Character type values. * These types can be or'd to check for any combination of types. * * This cannot be turned into an enum class because or'd entries can * result in values that are not in the class. For example, * combining NUMERIC|SPACE is a valid, reasonable combination but * does not match to any explicitly named enumerator. */ enum string_character_types : uint32_t { DECIMAL = 1 << 0, ///< all decimal characters NUMERIC = 1 << 1, ///< all numeric characters DIGIT = 1 << 2, ///< all digit characters ALPHA = 1 << 3, ///< all alphabetic characters SPACE = 1 << 4, ///< all space characters UPPER = 1 << 5, ///< all upper case characters LOWER = 1 << 6, ///< all lower case characters ALPHANUM = DECIMAL | NUMERIC | DIGIT | ALPHA, ///< all alphanumeric characters CASE_TYPES = UPPER | LOWER, ///< all case-able characters ALL_TYPES = ALPHANUM | CASE_TYPES | SPACE ///< all character types }; /** * @brief OR operator for combining string_character_types * * @param lhs left-hand side of OR operation * @param rhs right-hand side of OR operation * @return combined string_character_types */ constexpr string_character_types operator|(string_character_types lhs, string_character_types rhs) { return static_cast<string_character_types>( static_cast<std::underlying_type_t<string_character_types>>(lhs) | static_cast<std::underlying_type_t<string_character_types>>(rhs)); } /** * @brief Compound assignment OR operator for combining string_character_types * * @param lhs left-hand side of OR operation * @param rhs right-hand side of OR operation * @return Reference to `lhs` after combining `lhs` and `rhs` */ constexpr string_character_types& operator|=(string_character_types& lhs, string_character_types rhs) { lhs = static_cast<string_character_types>( static_cast<std::underlying_type_t<string_character_types>>(lhs) | static_cast<std::underlying_type_t<string_character_types>>(rhs)); return lhs; } /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/gather.cuh
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_factories.hpp> #include <cudf/detail/sizes_to_offsets_iterator.cuh> #include <cudf/detail/utilities/cuda.cuh> #include <cudf/strings/detail/utilities.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/advance.h> #include <thrust/binary_search.h> #include <thrust/distance.h> #include <thrust/execution_policy.h> #include <thrust/functional.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> namespace cudf { namespace strings { namespace detail { // Helper function for loading 16B from a potentially unaligned memory location to registers. __forceinline__ __device__ uint4 load_uint4(char const* ptr) { auto const offset = reinterpret_cast<std::uintptr_t>(ptr) % 4; auto const* aligned_ptr = reinterpret_cast<unsigned int const*>(ptr - offset); auto const shift = offset * 8; uint4 regs = {aligned_ptr[0], aligned_ptr[1], aligned_ptr[2], aligned_ptr[3]}; uint tail = 0; if (shift) tail = aligned_ptr[4]; regs.x = __funnelshift_r(regs.x, regs.y, shift); regs.y = __funnelshift_r(regs.y, regs.z, shift); regs.z = __funnelshift_r(regs.z, regs.w, shift); regs.w = __funnelshift_r(regs.w, tail, shift); return regs; } /** * @brief Gather characters from the input iterator, with string parallel strategy. * * This strategy assigns strings to warps so that each warp can cooperatively copy from the input * location of the string to the corresponding output location. Large datatype (uint4) is used for * stores. This strategy is best suited for large strings. * * @tparam StringIterator Iterator should produce `string_view` objects. * @tparam MapIterator Iterator for retrieving integer indices of the `StringIterator`. * * @param strings_begin Start of the iterator to retrieve `string_view` instances. * @param out_chars Output buffer for gathered characters. * @param out_offsets The offset values associated with the output buffer. * @param string_indices Start of index iterator. * @param total_out_strings Number of output strings to be gathered. */ template <typename StringIterator, typename MapIterator> __global__ void gather_chars_fn_string_parallel(StringIterator strings_begin, char* out_chars, cudf::device_span<int32_t const> const out_offsets, MapIterator string_indices, size_type total_out_strings) { constexpr size_t out_datatype_size = sizeof(uint4); constexpr size_t in_datatype_size = sizeof(uint); int global_thread_id = blockIdx.x * blockDim.x + threadIdx.x; int global_warp_id = global_thread_id / cudf::detail::warp_size; int warp_lane = global_thread_id % cudf::detail::warp_size; int nwarps = gridDim.x * blockDim.x / cudf::detail::warp_size; auto const alignment_offset = reinterpret_cast<std::uintptr_t>(out_chars) % out_datatype_size; uint4* out_chars_aligned = reinterpret_cast<uint4*>(out_chars - alignment_offset); for (size_type istring = global_warp_id; istring < total_out_strings; istring += nwarps) { auto const out_start = out_offsets[istring]; auto const out_end = out_offsets[istring + 1]; // This check is necessary because string_indices[istring] may be out of bound. if (out_start == out_end) continue; char const* in_start = strings_begin[string_indices[istring]].data(); // Both `out_start_aligned` and `out_end_aligned` are indices into `out_chars`. // `out_start_aligned` is the first 16B aligned memory location after `out_start + 4`. // `out_end_aligned` is the last 16B aligned memory location before `out_end - 4`. Characters // between `[out_start_aligned, out_end_aligned)` will be copied using uint4. // `out_start + 4` and `out_end - 4` are used instead of `out_start` and `out_end` to avoid // `load_uint4` reading beyond string boundaries. int32_t out_start_aligned = (out_start + in_datatype_size + alignment_offset + out_datatype_size - 1) / out_datatype_size * out_datatype_size - alignment_offset; int32_t out_end_aligned = (out_end - in_datatype_size + alignment_offset) / out_datatype_size * out_datatype_size - alignment_offset; for (size_type ichar = out_start_aligned + warp_lane * out_datatype_size; ichar < out_end_aligned; ichar += cudf::detail::warp_size * out_datatype_size) { *(out_chars_aligned + (ichar + alignment_offset) / out_datatype_size) = load_uint4(in_start + ichar - out_start); } // Tail logic: copy characters of the current string outside `[out_start_aligned, // out_end_aligned)`. if (out_end_aligned <= out_start_aligned) { // In this case, `[out_start_aligned, out_end_aligned)` is an empty set, and we copy the // entire string. for (int32_t ichar = out_start + warp_lane; ichar < out_end; ichar += cudf::detail::warp_size) { out_chars[ichar] = in_start[ichar - out_start]; } } else { // Copy characters in range `[out_start, out_start_aligned)`. if (out_start + warp_lane < out_start_aligned) { out_chars[out_start + warp_lane] = in_start[warp_lane]; } // Copy characters in range `[out_end_aligned, out_end)`. int32_t ichar = out_end_aligned + warp_lane; if (ichar < out_end) { out_chars[ichar] = in_start[ichar - out_start]; } } } } /** * @brief Gather characters from the input iterator, with char parallel strategy. * * This strategy assigns characters to threads, and uses binary search for getting the string * index. To improve the binary search performance, fixed number of strings per threadblock is * used. This strategy is best suited for small strings. * * @tparam StringIterator Iterator should produce `string_view` objects. * @tparam MapIterator Iterator for retrieving integer indices of the `StringIterator`. * * @param strings_begin Start of the iterator to retrieve `string_view` instances. * @param out_chars Output buffer for gathered characters. * @param out_offsets The offset values associated with the output buffer. * @param string_indices Start of index iterator. * @param total_out_strings Number of output strings to be gathered. */ template <int strings_per_threadblock, typename StringIterator, typename MapIterator> __global__ void gather_chars_fn_char_parallel(StringIterator strings_begin, char* out_chars, cudf::device_span<int32_t const> const out_offsets, MapIterator string_indices, size_type total_out_strings) { __shared__ int32_t out_offsets_threadblock[strings_per_threadblock + 1]; // Current thread block will process output strings starting at `begin_out_string_idx`. size_type begin_out_string_idx = blockIdx.x * strings_per_threadblock; // Number of strings to be processed by the current threadblock. size_type strings_current_threadblock = min(strings_per_threadblock, total_out_strings - begin_out_string_idx); if (strings_current_threadblock <= 0) return; // Collectively load offsets of strings processed by the current thread block. for (size_type idx = threadIdx.x; idx <= strings_current_threadblock; idx += blockDim.x) { out_offsets_threadblock[idx] = out_offsets[idx + begin_out_string_idx]; } __syncthreads(); for (int32_t out_ibyte = threadIdx.x + out_offsets_threadblock[0]; out_ibyte < out_offsets_threadblock[strings_current_threadblock]; out_ibyte += blockDim.x) { // binary search for the string index corresponding to out_ibyte auto const string_idx_iter = thrust::prev(thrust::upper_bound(thrust::seq, out_offsets_threadblock, out_offsets_threadblock + strings_current_threadblock, out_ibyte)); size_type string_idx = thrust::distance(out_offsets_threadblock, string_idx_iter); // calculate which character to load within the string int32_t icharacter = out_ibyte - out_offsets_threadblock[string_idx]; size_type in_string_idx = string_indices[begin_out_string_idx + string_idx]; out_chars[out_ibyte] = strings_begin[in_string_idx].data()[icharacter]; } } /** * @brief Returns a new chars column using the specified indices to select * strings from the input iterator. * * This uses a character-parallel gather CUDA kernel that performs very * well on a strings column with long strings (e.g. average > 64 bytes). * * @tparam StringIterator Iterator should produce `string_view` objects. * @tparam MapIterator Iterator for retrieving integer indices of the `StringIterator`. * * @param strings_begin Start of the iterator to retrieve `string_view` instances. * @param map_begin Start of index iterator. * @param map_end End of index iterator. * @param offsets The offset values to be associated with the output chars column. * @param chars_bytes The total number of bytes for the output chars column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New chars column fit for a strings column. */ template <typename StringIterator, typename MapIterator> std::unique_ptr<cudf::column> gather_chars(StringIterator strings_begin, MapIterator map_begin, MapIterator map_end, cudf::device_span<int32_t const> const offsets, size_type chars_bytes, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto const output_count = std::distance(map_begin, map_end); if (output_count == 0) return make_empty_column(type_id::INT8); auto chars_column = create_chars_child_column(chars_bytes, stream, mr); auto const d_chars = chars_column->mutable_view().template data<char>(); constexpr int warps_per_threadblock = 4; // String parallel strategy will be used if average string length is above this threshold. // Otherwise, char parallel strategy will be used. constexpr size_type string_parallel_threshold = 32; size_type average_string_length = chars_bytes / output_count; if (average_string_length > string_parallel_threshold) { constexpr int max_threadblocks = 65536; gather_chars_fn_string_parallel<<< min((static_cast<int>(output_count) + warps_per_threadblock - 1) / warps_per_threadblock, max_threadblocks), warps_per_threadblock * cudf::detail::warp_size, 0, stream.value()>>>(strings_begin, d_chars, offsets, map_begin, output_count); } else { constexpr int strings_per_threadblock = 32; gather_chars_fn_char_parallel<strings_per_threadblock> <<<(output_count + strings_per_threadblock - 1) / strings_per_threadblock, warps_per_threadblock * cudf::detail::warp_size, 0, stream.value()>>>(strings_begin, d_chars, offsets, map_begin, output_count); } return chars_column; } /** * @brief Returns a new strings column using the specified indices to select * elements from the `strings` column. * * Caller must update the validity mask in the output column. * * ``` * s1 = ["a", "b", "c", "d", "e", "f"] * map = [0, 2] * s2 = gather<true>( s1, map.begin(), map.end() ) * s2 is ["a", "c"] * ``` * * @tparam NullifyOutOfBounds If true, indices outside the column's range are nullified. * @tparam MapIterator Iterator for retrieving integer indices of the column. * * @param strings Strings instance for this operation. * @param begin Start of index iterator. * @param end End of index iterator. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column containing the gathered strings. */ template <bool NullifyOutOfBounds, typename MapIterator> std::unique_ptr<cudf::column> gather(strings_column_view const& strings, MapIterator begin, MapIterator end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto const output_count = std::distance(begin, end); if (output_count == 0) return make_empty_column(type_id::STRING); // build offsets column auto const d_strings = column_device_view::create(strings.parent(), stream); auto const d_in_offsets = !strings.is_empty() ? strings.offsets_begin() : nullptr; auto offsets_itr = thrust::make_transform_iterator( begin, [d_strings = *d_strings, d_in_offsets] __device__(size_type idx) { if (NullifyOutOfBounds && (idx < 0 || idx >= d_strings.size())) { return 0; } if (not d_strings.is_valid(idx)) { return 0; } return d_in_offsets[idx + 1] - d_in_offsets[idx]; }); auto [out_offsets_column, total_bytes] = cudf::detail::make_offsets_child_column(offsets_itr, offsets_itr + output_count, stream, mr); // build chars column auto const offsets_view = out_offsets_column->view(); auto out_chars_column = gather_chars( d_strings->begin<string_view>(), begin, end, offsets_view, total_bytes, stream, mr); return make_strings_column(output_count, std::move(out_offsets_column), std::move(out_chars_column), 0, // caller sets these rmm::device_buffer{}); } /** * @brief Returns a new strings column using the specified indices to select * elements from the `strings` column. * * Caller must update the validity mask in the output column. * * ``` * s1 = ["a", "b", "c", "d", "e", "f"] * map = [0, 2] * s2 = gather( s1, map.begin(), map.end(), true ) * s2 is ["a", "c"] * ``` * * @tparam MapIterator Iterator for retrieving integer indices of the column. * * @param strings Strings instance for this operation. * @param begin Start of index iterator. * @param end End of index iterator. * @param nullify_out_of_bounds If true, indices outside the column's range are nullified. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column containing the gathered strings. */ template <typename MapIterator> std::unique_ptr<cudf::column> gather(strings_column_view const& strings, MapIterator begin, MapIterator end, bool nullify_out_of_bounds, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { if (nullify_out_of_bounds) return gather<true>(strings, begin, end, stream, mr); return gather<false>(strings, begin, end, stream, mr); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/strings_column_factories.cuh
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/detail/nvtx/ranges.hpp> #include <cudf/detail/valid_if.cuh> #include <cudf/strings/detail/gather.cuh> #include <cudf/strings/detail/strings_children.cuh> #include <cudf/utilities/error.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/copy.h> #include <thrust/distance.h> #include <thrust/for_each.h> #include <thrust/functional.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/pair.h> #include <thrust/transform.h> #include <thrust/tuple.h> namespace cudf { namespace strings { namespace detail { /** * @brief Basic type expected for iterators passed to `make_strings_column` that represent string * data in device memory. */ using string_index_pair = thrust::pair<char const*, size_type>; /** * @brief Average string byte-length threshold for deciding character-level * vs. row-level parallel algorithm. * * This value was determined by running the factory_benchmark against different * string lengths and observing the point where the performance is faster for * long strings. */ constexpr size_type FACTORY_BYTES_PER_ROW_THRESHOLD = 64; /** * @brief Create a strings-type column from iterators of pointer/size pairs * * @tparam IndexPairIterator iterator over type `pair<char const*,size_type>` values * * @param begin First string row (inclusive) * @param end Last string row (exclusive) * @param stream CUDA stream used for device memory operations * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ template <typename IndexPairIterator> std::unique_ptr<column> make_strings_column(IndexPairIterator begin, IndexPairIterator end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { CUDF_FUNC_RANGE(); size_type strings_count = thrust::distance(begin, end); if (strings_count == 0) return make_empty_column(type_id::STRING); // build offsets column from the strings sizes auto offsets_transformer = [] __device__(string_index_pair item) -> size_type { return (item.first != nullptr ? static_cast<size_type>(item.second) : size_type{0}); }; auto offsets_transformer_itr = thrust::make_transform_iterator(begin, offsets_transformer); auto [offsets_column, bytes] = cudf::detail::make_offsets_child_column( offsets_transformer_itr, offsets_transformer_itr + strings_count, stream, mr); auto offsets_view = offsets_column->view(); // create null mask auto validator = [] __device__(string_index_pair const item) { return item.first != nullptr; }; auto new_nulls = cudf::detail::valid_if(begin, end, validator, stream, mr); auto const null_count = new_nulls.second; auto null_mask = (null_count > 0) ? std::move(new_nulls.first) : rmm::device_buffer{0, stream, mr}; // build chars column std::unique_ptr<column> chars_column = [offsets_view, bytes = bytes, begin, strings_count, null_count, stream, mr] { auto const avg_bytes_per_row = bytes / std::max(strings_count - null_count, 1); // use a character-parallel kernel for long string lengths if (avg_bytes_per_row > FACTORY_BYTES_PER_ROW_THRESHOLD) { auto const d_data = offsets_view.template data<size_type>(); auto const d_offsets = device_span<size_type const>{d_data, static_cast<std::size_t>(offsets_view.size())}; auto const str_begin = thrust::make_transform_iterator(begin, [] __device__(auto ip) { return string_view{ip.first, ip.second}; }); return gather_chars(str_begin, thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(strings_count), d_offsets, bytes, stream, mr); } else { // this approach is 2-3x faster for a large number of smaller string lengths auto chars_column = create_chars_child_column(bytes, stream, mr); auto d_chars = chars_column->mutable_view().template data<char>(); auto copy_chars = [d_chars] __device__(auto item) { string_index_pair const str = thrust::get<0>(item); size_type const offset = thrust::get<1>(item); if (str.first != nullptr) memcpy(d_chars + offset, str.first, str.second); }; thrust::for_each_n(rmm::exec_policy(stream), thrust::make_zip_iterator( thrust::make_tuple(begin, offsets_view.template begin<int32_t>())), strings_count, copy_chars); return chars_column; } }(); return make_strings_column(strings_count, std::move(offsets_column), std::move(chars_column), null_count, std::move(null_mask)); } /** * @brief Create a strings-type column from iterators to chars, offsets, and bitmask. * * @tparam CharIterator iterator over character bytes (int8) * @tparam OffsetIterator iterator over offset values (size_type) * * @param chars_begin First character byte (inclusive) * @param chars_end Last character byte (exclusive) * @param offset_begin First offset value (inclusive) * @param offset_end Last offset value (exclusive) * @param null_count Number of null rows * @param null_mask The validity bitmask in Arrow format * @param stream CUDA stream used for device memory operations * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ template <typename CharIterator, typename OffsetIterator> std::unique_ptr<column> make_strings_column(CharIterator chars_begin, CharIterator chars_end, OffsetIterator offsets_begin, OffsetIterator offsets_end, size_type null_count, rmm::device_buffer&& null_mask, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { CUDF_FUNC_RANGE(); size_type strings_count = thrust::distance(offsets_begin, offsets_end) - 1; size_type bytes = std::distance(chars_begin, chars_end) * sizeof(char); if (strings_count == 0) return make_empty_column(type_id::STRING); CUDF_EXPECTS(bytes >= 0, "invalid offsets data"); // build offsets column -- this is the number of strings + 1 auto offsets_column = make_numeric_column( data_type{type_to_id<size_type>()}, strings_count + 1, mask_state::UNALLOCATED, stream, mr); auto offsets_view = offsets_column->mutable_view(); thrust::transform(rmm::exec_policy(stream), offsets_begin, offsets_end, offsets_view.data<int32_t>(), [] __device__(auto offset) { return static_cast<int32_t>(offset); }); // build chars column auto chars_column = strings::detail::create_chars_child_column(bytes, stream, mr); auto chars_view = chars_column->mutable_view(); thrust::copy(rmm::exec_policy(stream), chars_begin, chars_end, chars_view.data<char>()); return make_strings_column(strings_count, std::move(offsets_column), std::move(chars_column), null_count, std::move(null_mask)); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/fill.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief Returns a strings column replacing a range of rows * with the specified string. * * If the value parameter is invalid, the specified rows are filled with * null entries. * * @throw cudf::logic_error if [begin,end) is outside the range of the input column. * * @param strings Strings column to fill. * @param begin First row index to include the new string. * @param end Last row index (exclusive). * @param value String to use when filling the range. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column. */ std::unique_ptr<column> fill(strings_column_view const& strings, size_type begin, size_type end, string_scalar const& value, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/utilities.cuh
/* * 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. */ #pragma once #include <cudf/strings/string_view.cuh> #include <cudf/utilities/error.hpp> #include <thrust/copy.h> #include <thrust/execution_policy.h> #include <mutex> #include <unordered_map> namespace cudf { namespace strings { namespace detail { /** * @brief Copies input string data into a buffer and increments the pointer by the number of bytes * copied. * * @param buffer Device buffer to copy to * @param input Data to copy from * @param bytes Number of bytes to copy * @return Pointer to the end of the output buffer after the copy */ __device__ inline char* copy_and_increment(char* buffer, char const* input, size_type bytes) { // this can be slightly faster than memcpy thrust::copy_n(thrust::seq, input, bytes, buffer); return buffer + bytes; } /** * @brief Copies input string data into a buffer and increments the pointer by the number of bytes * copied. * * @param buffer Device buffer to copy to. * @param d_string String to copy. * @return Pointer to the end of the output buffer after the copy. */ __device__ inline char* copy_string(char* buffer, string_view const& d_string) { return copy_and_increment(buffer, d_string.data(), d_string.size_bytes()); } // This template is a thin wrapper around per-context singleton objects. // It maintains a single object for each CUDA context. template <typename TableType> class per_context_cache { public: // Find an object cached for a current CUDA context. // If there is no object available in the cache, it calls the initializer // `init` to create a new one and cache it for later uses. template <typename Initializer> TableType* find_or_initialize(Initializer const& init) { int device_id; CUDF_CUDA_TRY(cudaGetDevice(&device_id)); auto finder = cache_.find(device_id); if (finder == cache_.end()) { TableType* result = init(); cache_[device_id] = result; return result; } else return finder->second; } private: std::unordered_map<int, TableType*> cache_; }; // This template is a thread-safe version of per_context_cache. template <typename TableType> class thread_safe_per_context_cache : public per_context_cache<TableType> { public: template <typename Initializer> TableType* find_or_initialize(Initializer const& init) { std::lock_guard<std::mutex> guard(mutex); return per_context_cache<TableType>::find_or_initialize(init); } private: std::mutex mutex; }; } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/utilities.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_uvector.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief Create a chars column to be a child of a strings column. * * This will return the properly sized column to be filled in by the caller. * * @param bytes Number of bytes for the chars column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return The chars child column for a strings column. */ std::unique_ptr<column> create_chars_child_column(size_type bytes, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Creates a string_view vector from a strings column. * * @param strings Strings column instance. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned vector's device memory. * @return Device vector of string_views */ rmm::device_uvector<string_view> create_string_vector_from_column( cudf::strings_column_view const strings, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/copying.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief Returns a new strings column created from a subset of * of the strings column. * * The subset of strings selected is between * start (inclusive) and end (exclusive). * * @code{.pseudo} * Example: * s1 = ["a", "b", "c", "d", "e", "f"] * s2 = copy_slice( s1, 2 ) * s2 is ["c", "d", "e", "f"] * s2 = copy_slice( s1, 1, 3 ) * s2 is ["b", "c"] * @endcode * * @param strings Strings instance for this operation. * @param start Index to first string to select in the column (inclusive). * @param end Index to last string to select in the column (exclusive). * Default -1 indicates the last element. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column of size (end-start)/step. */ std::unique_ptr<cudf::column> copy_slice(strings_column_view const& strings, size_type start, size_type end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Returns a new strings column created by shifting the rows by a specified offset. * * @code{.pseudo} * Example: * s = ["a", "b", "c", "d", "e", "f"] * r1 = shift(s, 2, "_") * r1 is now ["_", "_", "a", "b", "c", "d"] * r2 = shift(s, -2, "_") * r2 is now ["c", "d", "e", "f", "_", "_"] * @endcode * * The caller should set the validity mask in the output column. * * @param input Strings instance for this operation. * @param offset The offset by which to shift the input. * @param fill_value Fill value for indeterminable outputs. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column. */ std::unique_ptr<column> shift(strings_column_view const& input, size_type offset, scalar const& fill_value, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/strings_children.cuh
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/detail/sizes_to_offsets_iterator.cuh> #include <cudf/strings/detail/utilities.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> #include <stdexcept> namespace cudf { namespace strings { namespace detail { /** * @brief Creates child offsets and chars columns by applying the template function that * can be used for computing the output size of each string as well as create the output * * @throws std::overflow_error if the output strings column exceeds the column size limit * * @tparam SizeAndExecuteFunction Function must accept an index and return a size. * It must also have members d_offsets and d_chars which are set to * memory containing the offsets and chars columns during write. * * @param size_and_exec_fn This is called twice. Once for the output size of each string * and once again to fill in the memory pointed to by d_chars. * @param exec_size Number of rows for executing the `size_and_exec_fn` function. * @param strings_count Number of strings. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned columns' device memory. * @return offsets child column and chars child column for a strings column */ template <typename SizeAndExecuteFunction> auto make_strings_children(SizeAndExecuteFunction size_and_exec_fn, size_type exec_size, size_type strings_count, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto offsets_column = make_numeric_column( data_type{type_to_id<size_type>()}, strings_count + 1, mask_state::UNALLOCATED, stream, mr); auto offsets_view = offsets_column->mutable_view(); auto d_offsets = offsets_view.template data<int32_t>(); size_and_exec_fn.d_offsets = d_offsets; // This is called twice -- once for offsets and once for chars. // Reducing the number of places size_and_exec_fn is inlined speeds up compile time. auto for_each_fn = [exec_size, stream](SizeAndExecuteFunction& size_and_exec_fn) { thrust::for_each_n(rmm::exec_policy(stream), thrust::make_counting_iterator<size_type>(0), exec_size, size_and_exec_fn); }; // Compute the output sizes for_each_fn(size_and_exec_fn); // Convert the sizes to offsets auto const bytes = cudf::detail::sizes_to_offsets(d_offsets, d_offsets + strings_count + 1, d_offsets, stream); CUDF_EXPECTS(bytes <= std::numeric_limits<size_type>::max(), "Size of output exceeds the column size limit", std::overflow_error); // Now build the chars column std::unique_ptr<column> chars_column = create_chars_child_column(static_cast<size_type>(bytes), stream, mr); // Execute the function fn again to fill the chars column. // Note that if the output chars column has zero size, the function fn should not be called to // avoid accidentally overwriting the offsets. if (bytes > 0) { size_and_exec_fn.d_chars = chars_column->mutable_view().template data<char>(); for_each_fn(size_and_exec_fn); } return std::pair(std::move(offsets_column), std::move(chars_column)); } /** * @brief Creates child offsets and chars columns by applying the template function that * can be used for computing the output size of each string as well as create the output. * * @tparam SizeAndExecuteFunction Function must accept an index and return a size. * It must also have members d_offsets and d_chars which are set to * memory containing the offsets and chars columns during write. * * @param size_and_exec_fn This is called twice. Once for the output size of each string * and once again to fill in the memory pointed to by d_chars. * @param strings_count Number of strings. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned columns' device memory. * @return offsets child column and chars child column for a strings column */ template <typename SizeAndExecuteFunction> auto make_strings_children(SizeAndExecuteFunction size_and_exec_fn, size_type strings_count, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { return make_strings_children(size_and_exec_fn, strings_count, strings_count, stream, mr); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/merge.cuh
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_factories.hpp> #include <cudf/detail/merge.hpp> #include <cudf/detail/null_mask.hpp> #include <cudf/strings/detail/strings_children.cuh> #include <cudf/strings/string_view.cuh> #include <cudf/strings/strings_column_view.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/tuple.h> namespace cudf { namespace strings { namespace detail { /** * @brief Merges two strings columns. * * Caller must set the validity mask in the output column. * * @tparam row_order_iterator This must be an iterator for type thrust::tuple<side,size_type>. * * @param lhs First column. * @param rhs Second column. * @param row_order Indexes for each column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column. */ template <typename index_type, typename row_order_iterator> std::unique_ptr<column> merge(strings_column_view const& lhs, strings_column_view const& rhs, row_order_iterator begin, row_order_iterator end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { using cudf::detail::side; size_type strings_count = static_cast<size_type>(std::distance(begin, end)); if (strings_count == 0) return make_empty_column(type_id::STRING); auto lhs_column = column_device_view::create(lhs.parent(), stream); auto d_lhs = *lhs_column; auto rhs_column = column_device_view::create(rhs.parent(), stream); auto d_rhs = *rhs_column; // caller will set the null mask rmm::device_buffer null_mask{0, stream, mr}; size_type null_count = lhs.null_count() + rhs.null_count(); if (null_count > 0) null_mask = cudf::detail::create_null_mask(strings_count, mask_state::ALL_VALID, stream, mr); // build offsets column auto offsets_transformer = [d_lhs, d_rhs] __device__(auto index_pair) { auto const [side, index] = index_pair; if (side == side::LEFT ? d_lhs.is_null(index) : d_rhs.is_null(index)) return 0; auto d_str = side == side::LEFT ? d_lhs.element<string_view>(index) : d_rhs.element<string_view>(index); return d_str.size_bytes(); }; auto offsets_transformer_itr = thrust::make_transform_iterator(begin, offsets_transformer); auto [offsets_column, bytes] = cudf::detail::make_offsets_child_column( offsets_transformer_itr, offsets_transformer_itr + strings_count, stream, mr); auto d_offsets = offsets_column->view().template data<int32_t>(); // create the chars column auto chars_column = strings::detail::create_chars_child_column(bytes, stream, mr); // merge the strings auto d_chars = chars_column->mutable_view().template data<char>(); thrust::for_each_n(rmm::exec_policy(stream), thrust::make_counting_iterator<size_type>(0), strings_count, [d_lhs, d_rhs, begin, d_offsets, d_chars] __device__(size_type idx) { auto const [side, index] = begin[idx]; if (side == side::LEFT ? d_lhs.is_null(index) : d_rhs.is_null(index)) return; auto d_str = side == side::LEFT ? d_lhs.element<string_view>(index) : d_rhs.element<string_view>(index); memcpy(d_chars + d_offsets[idx], d_str.data(), d_str.size_bytes()); }); return make_strings_column(strings_count, std::move(offsets_column), std::move(chars_column), null_count, std::move(null_mask)); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/copy_range.cuh
/* * 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. */ #pragma once #include <cudf/column/column_device_view.cuh> #include <cudf/detail/valid_if.cuh> #include <cudf/strings/detail/strings_children.cuh> #include <cudf/strings/string_view.cuh> #include <cudf/strings/strings_column_view.hpp> #include <cudf/types.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/device_ptr.h> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> namespace { template <bool source_has_nulls, bool target_has_nulls, typename SourceValueIterator, typename SourceValidityIterator> struct compute_element_size { SourceValueIterator source_value_begin; SourceValidityIterator source_validity_begin; cudf::column_device_view d_target; cudf::size_type target_begin; cudf::size_type target_end; __device__ cudf::size_type operator()(cudf::size_type idx) { if (idx >= target_begin && idx < target_end) { if (source_has_nulls) { return *(source_validity_begin + (idx - target_begin)) ? (*(source_value_begin + (idx - target_begin))).size_bytes() : 0; } else { return (*(source_value_begin + (idx - target_begin))).size_bytes(); } } else { if (target_has_nulls) { return d_target.is_valid_nocheck(idx) ? d_target.element<cudf::string_view>(idx).size_bytes() : 0; } else { return d_target.element<cudf::string_view>(idx).size_bytes(); } } } }; } // namespace namespace cudf { namespace strings { namespace detail { /** * @brief Internal API to copy a range of string elements out-of-place from * source iterators to a target column. * * Creates a new column as if an in-place copy was performed into @p target. * The elements indicated by the indices [@p target_begin, @p target_end) were * replaced with the elements retrieved from source iterators; * *(@p source_value_begin + idx) if *(@p source_validity_begin + idx) is true, * invalidate otherwise (where idx = [0, @p target_end - @p target_begin)). * Elements outside the range are copied from @p target into the new target * column to return. * * @throws cudf::logic_error for invalid range (if @p target_begin < 0, * target_begin >= @p target.size(), or @p target_end > @p target.size()). * * @tparam SourceValueIterator Iterator for retrieving source values * @tparam SourceValidityIterator Iterator for retrieving source validities * @param source_value_begin Start of source value iterator * @param source_validity_begin Start of source validity iterator * @param target The strings column to copy from outside the range. * @param target_begin The starting index of the target range (inclusive) * @param target_end The index of the last element in the target range * (exclusive) * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return std::unique_ptr<column> The result target column */ template <typename SourceValueIterator, typename SourceValidityIterator> std::unique_ptr<column> copy_range(SourceValueIterator source_value_begin, SourceValidityIterator source_validity_begin, strings_column_view const& target, size_type target_begin, size_type target_end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { CUDF_EXPECTS( (target_begin >= 0) && (target_begin < target.size()) && (target_end <= target.size()), "Range is out of bounds."); if (target_end == target_begin) { return std::make_unique<column>(target.parent(), stream, mr); } else { auto p_target_device_view = column_device_view::create(target.parent(), stream); auto d_target = *p_target_device_view; // create resulting null mask std::pair<rmm::device_buffer, size_type> valid_mask{}; if (target.has_nulls()) { // check validities for both source & target valid_mask = cudf::detail::valid_if( thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(target.size()), [source_validity_begin, d_target, target_begin, target_end] __device__(size_type idx) { return (idx >= target_begin && idx < target_end) ? *(source_validity_begin + (idx - target_begin)) : d_target.is_valid_nocheck(idx); }, stream, mr); } else { // check validities for source only valid_mask = cudf::detail::valid_if( thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(target.size()), [source_validity_begin, d_target, target_begin, target_end] __device__(size_type idx) { return (idx >= target_begin && idx < target_end) ? *(source_validity_begin + (idx - target_begin)) : true; }, stream, mr); } auto null_count = valid_mask.second; rmm::device_buffer null_mask{0, stream, mr}; if (target.parent().nullable() || null_count > 0) { null_mask = std::move(valid_mask.first); } // build offsets column std::unique_ptr<column> p_offsets_column{nullptr}; size_type chars_bytes = 0; if (target.has_nulls()) { // check validities for both source & target auto string_size_begin = thrust::make_transform_iterator( thrust::make_counting_iterator(0), compute_element_size<true, true, SourceValueIterator, SourceValidityIterator>{ source_value_begin, source_validity_begin, d_target, target_begin, target_end}); std::tie(p_offsets_column, chars_bytes) = cudf::detail::make_offsets_child_column( string_size_begin, string_size_begin + target.size(), stream, mr); } else if (null_count > 0) { // check validities for source only auto string_size_begin = thrust::make_transform_iterator( thrust::make_counting_iterator(0), compute_element_size<true, false, SourceValueIterator, SourceValidityIterator>{ source_value_begin, source_validity_begin, d_target, target_begin, target_end}); std::tie(p_offsets_column, chars_bytes) = cudf::detail::make_offsets_child_column( string_size_begin, string_size_begin + target.size(), stream, mr); } else { // no need to check validities auto string_size_begin = thrust::make_transform_iterator( thrust::make_counting_iterator(0), compute_element_size<false, false, SourceValueIterator, SourceValidityIterator>{ source_value_begin, source_validity_begin, d_target, target_begin, target_end}); std::tie(p_offsets_column, chars_bytes) = cudf::detail::make_offsets_child_column( string_size_begin, string_size_begin + target.size(), stream, mr); } // create the chars column auto p_offsets = thrust::device_pointer_cast(p_offsets_column->view().template data<size_type>()); auto p_chars_column = strings::detail::create_chars_child_column(chars_bytes, stream, mr); // copy to the chars column auto p_chars = (p_chars_column->mutable_view()).template data<char>(); thrust::for_each(rmm::exec_policy(stream), thrust::make_counting_iterator(0), thrust::make_counting_iterator(target.size()), [source_value_begin, source_validity_begin, d_target, target_begin, target_end, p_offsets, p_chars] __device__(size_type idx) { if (p_offsets[idx + 1] - p_offsets[idx] > 0) { const auto source = (idx >= target_begin && idx < target_end) ? *(source_value_begin + (idx - target_begin)) : d_target.element<string_view>(idx); memcpy(p_chars + p_offsets[idx], source.data(), source.size_bytes()); } }); return make_strings_column(target.size(), std::move(p_offsets_column), std::move(p_chars_column), null_count, std::move(null_mask)); } } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/utf8.hpp
/* * 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. */ #pragma once #include <cudf/types.hpp> /** * @file * @brief Standalone string functions. */ namespace cudf { using char_utf8 = uint32_t; ///< UTF-8 characters are 1-4 bytes namespace strings { namespace detail { /** * @brief This will return true if passed a continuation byte of a UTF-8 character. * * @param chr Any single byte from a valid UTF-8 character * @return true if this is not the first byte of the character */ constexpr bool is_utf8_continuation_char(unsigned char chr) { // The (0xC0 & 0x80) bit pattern identifies a continuation byte of a character. return (chr & 0xC0) == 0x80; } /** * @brief This will return true if passed the first byte of a UTF-8 character. * * @param chr Any single byte from a valid UTF-8 character * @return true if this the first byte of the character */ constexpr bool is_begin_utf8_char(unsigned char chr) { return not is_utf8_continuation_char(chr); } /** * @brief This will return true if the passed in byte could be the start of * a valid UTF-8 character. * * This differs from is_begin_utf8_char(uint8_t) in that byte may not be valid * UTF-8, so a more rigorous check is performed. * * @param byte The byte to be tested * @return true if this can be the first byte of a character */ constexpr bool is_valid_begin_utf8_char(uint8_t byte) { // to be the first byte of a valid (up to 4 byte) UTF-8 char, byte must be one of: // 0b0vvvvvvv a 1 byte character // 0b110vvvvv start of a 2 byte character // 0b1110vvvv start of a 3 byte character // 0b11110vvv start of a 4 byte character return (byte & 0x80) == 0 || (byte & 0xE0) == 0xC0 || (byte & 0xF0) == 0xE0 || (byte & 0xF8) == 0xF0; } /** * @brief Returns the number of bytes in the specified character. * * @param character Single character * @return Number of bytes */ constexpr size_type bytes_in_char_utf8(char_utf8 character) { return 1 + static_cast<size_type>((character & 0x0000'FF00u) > 0) + static_cast<size_type>((character & 0x00FF'0000u) > 0) + static_cast<size_type>((character & 0xFF00'0000u) > 0); } /** * @brief Returns the number of bytes used to represent the provided byte. * * This could be 0 to 4 bytes. 0 is returned for intermediate bytes within a * single character. For example, for the two-byte 0xC3A8 single character, * the first byte would return 2 and the second byte would return 0. * * @param byte Byte from an encoded character. * @return Number of bytes. */ constexpr size_type bytes_in_utf8_byte(uint8_t byte) { return 1 + static_cast<size_type>((byte & 0xF0) == 0xF0) // 4-byte character prefix + static_cast<size_type>((byte & 0xE0) == 0xE0) // 3-byte character prefix + static_cast<size_type>((byte & 0xC0) == 0xC0) // 2-byte character prefix - static_cast<size_type>((byte & 0xC0) == 0x80); // intermediate byte } /** * @brief Convert a char array into a char_utf8 value. * * @param str String containing encoded char bytes. * @param[out] character Single char_utf8 value. * @return The number of bytes in the character */ constexpr size_type to_char_utf8(char const* str, char_utf8& character) { size_type const chr_width = bytes_in_utf8_byte(static_cast<uint8_t>(*str)); character = static_cast<char_utf8>(*str++) & 0xFF; if (chr_width > 1) { character = character << 8; character |= (static_cast<char_utf8>(*str++) & 0xFF); // << 8; if (chr_width > 2) { character = character << 8; character |= (static_cast<char_utf8>(*str++) & 0xFF); // << 16; if (chr_width > 3) { character = character << 8; character |= (static_cast<char_utf8>(*str++) & 0xFF); // << 24; } } } return chr_width; } /** * @brief Place a char_utf8 value into a char array. * * @param character Single character * @param[out] str Output array. * @return The number of bytes in the character */ constexpr inline size_type from_char_utf8(char_utf8 character, char* str) { size_type const chr_width = bytes_in_char_utf8(character); for (size_type idx = 0; idx < chr_width; ++idx) { str[chr_width - idx - 1] = static_cast<char>(character) & 0xFF; character = character >> 8; } return chr_width; } /** * @brief Converts a single UTF-8 character into a code-point value that * can be used for lookup in the character flags or the character case tables. * * @param utf8_char Single UTF-8 character to convert. * @return Code-point for the UTF-8 character. */ constexpr uint32_t utf8_to_codepoint(cudf::char_utf8 utf8_char) { uint32_t unchr = 0; if (utf8_char < 0x0000'0080) // single-byte pass thru unchr = utf8_char; else if (utf8_char < 0x0000'E000) // two bytes { unchr = (utf8_char & 0x1F00) >> 2; // shift and unchr |= (utf8_char & 0x003F); // unmask } else if (utf8_char < 0x00F0'0000) // three bytes { unchr = (utf8_char & 0x0F'0000) >> 4; // get upper 4 bits unchr |= (utf8_char & 0x00'3F00) >> 2; // shift and unchr |= (utf8_char & 0x00'003F); // unmask } else if (utf8_char <= 0xF800'0000u) // four bytes { unchr = (utf8_char & 0x0300'0000) >> 6; // upper 3 bits unchr |= (utf8_char & 0x003F'0000) >> 4; // next 6 bits unchr |= (utf8_char & 0x0000'3F00) >> 2; // next 6 bits unchr |= (utf8_char & 0x0000'003F); // unmask } return unchr; } /** * @brief Converts a character code-point value into a UTF-8 character. * * @param unchr Character code-point to convert. * @return Single UTF-8 character. */ constexpr cudf::char_utf8 codepoint_to_utf8(uint32_t unchr) { cudf::char_utf8 utf8 = 0; if (unchr < 0x0000'0080) // single byte utf8 utf8 = unchr; else if (unchr < 0x0000'0800) // double byte utf8 { utf8 = (unchr << 2) & 0x1F00; // shift bits for utf8 |= (unchr & 0x3F); // utf8 encoding utf8 |= 0x0000'C080; } else if (unchr < 0x0001'0000) // triple byte utf8 { utf8 = (unchr << 4) & 0x0F'0000; // upper 4 bits utf8 |= (unchr << 2) & 0x00'3F00; // next 6 bits utf8 |= (unchr & 0x3F); // last 6 bits utf8 |= 0x00E0'8080; } else if (unchr < 0x0011'0000) // quadruple byte utf8 { utf8 = (unchr << 6) & 0x0700'0000; // upper 3 bits utf8 |= (unchr << 4) & 0x003F'0000; // next 6 bits utf8 |= (unchr << 2) & 0x0000'3F00; // next 6 bits utf8 |= (unchr & 0x3F); // last 6 bits utf8 |= 0xF080'8080u; } return utf8; } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/char_tables.hpp
/* * 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. */ #pragma once #include <cstdint> namespace cudf { namespace strings { namespace detail { // Type for the character flags table. using character_flags_table_type = std::uint8_t; /** * @brief Returns pointer to device memory that contains the static * characters flags table. On first call, this will copy the table into * device memory and is guaranteed to be thread-safe. * * This table is used to check the type of character like * alphanumeric, decimal, etc. * * @return Device memory pointer to character flags table. */ character_flags_table_type const* get_character_flags_table(); // utilities to dissect a character-table flag constexpr uint8_t IS_DECIMAL(uint8_t x) { return ((x) & (1 << 0)); } constexpr uint8_t IS_NUMERIC(uint8_t x) { return ((x) & (1 << 1)); } constexpr uint8_t IS_DIGIT(uint8_t x) { return ((x) & (1 << 2)); } constexpr uint8_t IS_ALPHA(uint8_t x) { return ((x) & (1 << 3)); } constexpr uint8_t IS_SPACE(uint8_t x) { return ((x) & (1 << 4)); } constexpr uint8_t IS_UPPER(uint8_t x) { return ((x) & (1 << 5)); } constexpr uint8_t IS_LOWER(uint8_t x) { return ((x) & (1 << 6)); } constexpr uint8_t IS_SPECIAL(uint8_t x) { return ((x) & (1 << 7)); } constexpr uint8_t IS_ALPHANUM(uint8_t x) { return ((x) & (0x0F)); } constexpr uint8_t IS_UPPER_OR_LOWER(uint8_t x) { return ((x) & ((1 << 5) | (1 << 6))); } constexpr uint8_t ALL_FLAGS = 0xFF; // Type for the character cases table. using character_cases_table_type = uint16_t; /** * @brief Returns pointer to device memory that contains the static * characters case table. On first call, this will copy the table into * device memory and is guaranteed to be thread-safe. * * This table is used to map upper and lower case characters with * their counterpart. * * @return Device memory pointer to character cases table. */ character_cases_table_type const* get_character_cases_table(); /** * @brief Case mapping structure for special characters. * * This is used for special mapping of a small set of characters that do not * fit in the character-cases-table. * * @see cpp/src/strings/char_types/char_cases.h */ struct special_case_mapping { uint16_t num_upper_chars; uint16_t upper[3]; uint16_t num_lower_chars; uint16_t lower[3]; }; /** * @brief Returns pointer to device memory that contains the special * case mapping table. On first call, this will copy the table into * device memory and is guaranteed to be thread-safe. * * This table is used to handle special case character mappings that * don't trivially work with the normal character cases table. * * @return Device memory pointer to the special case mapping table */ const struct special_case_mapping* get_special_case_mapping_table(); /** * @brief Get the special mapping table index for a given code-point. * * @see cpp/src/strings/char_types/char_cases.h */ constexpr uint16_t get_special_case_hash_index(uint32_t code_point) { constexpr uint16_t special_case_prime = 499; // computed from generate_special_mapping_hash_table return static_cast<uint16_t>(code_point % special_case_prime); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/strip.cuh
/* * 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. */ #pragma once #include <cudf/strings/side_type.hpp> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { /** * @brief Strips a specified character from the either or both ends of a string * * @param d_str Input string to strip * @param d_to_strip String containing the character to strip; * only the first character is used * @param side Which ends of the input string to strip from * @return New string excluding the stripped ends */ __device__ cudf::string_view strip(cudf::string_view const d_str, cudf::string_view const d_to_strip, side_type side = side_type::BOTH) { if (d_str.empty()) { return cudf::string_view{}; } // sanitize empty return auto is_strip_character = [d_to_strip](char_utf8 chr) -> bool { if (d_to_strip.empty()) return chr <= ' '; // whitespace check for (auto c : d_to_strip) { if (c == chr) return true; } return false; }; auto const left_offset = [&] { if (side != side_type::LEFT && side != side_type::BOTH) return 0; for (auto itr = d_str.begin(); itr < d_str.end(); ++itr) { if (!is_strip_character(*itr)) return itr.byte_offset(); } return d_str.size_bytes(); }(); auto const right_offset = [&] { if (side != side_type::RIGHT && side != side_type::BOTH) return d_str.size_bytes(); for (auto itr = d_str.end(); itr > d_str.begin(); --itr) { if (!is_strip_character(*(itr - 1))) return itr.byte_offset(); } return 0; }(); auto const bytes = (right_offset > left_offset) ? right_offset - left_offset : 0; return cudf::string_view{d_str.data() + left_offset, bytes}; } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/combine.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/combine.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @copydoc concatenate(table_view const&,string_scalar const&,string_scalar * const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> concatenate(table_view const& strings_columns, string_scalar const& separator, string_scalar const& narep, separator_on_nulls separate_nulls, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc join_strings(table_view const&,string_scalar const&,string_scalar * const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> join_strings(strings_column_view const& strings, string_scalar const& separator, string_scalar const& narep, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc join_list_elements(table_view const&,string_scalar const&,string_scalar * const&,separator_on_nulls,output_if_empty_list,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> join_list_elements(lists_column_view const& lists_strings_column, string_scalar const& separator, string_scalar const& narep, separator_on_nulls separate_nulls, output_if_empty_list empty_list_policy, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/concatenate.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief Returns a single column by vertically concatenating the given vector of * strings columns. * * ``` * s1 = ['aa', 'bb', 'cc'] * s2 = ['dd', 'ee'] * r = concatenate_vertically([s1,s2]) * r is now ['aa', 'bb', 'cc', 'dd', 'ee'] * ``` * * @param columns List of string columns to concatenate. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New column with concatenated results. */ std::unique_ptr<column> concatenate(host_span<column_view const> columns, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/split_utils.cuh
/* * 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. */ #pragma once #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { constexpr bool is_whitespace(char_utf8 ch) { return ch <= ' '; } /** * @brief Count tokens delimited by whitespace * * @param d_str String to tokenize * @param max_tokens Maximum number of tokens to count * @return Number of tokens delimited by whitespace */ __device__ inline size_type count_tokens_whitespace( string_view d_str, size_type const max_tokens = std::numeric_limits<size_type>::max()) { auto token_count = size_type{0}; auto spaces = true; auto itr = d_str.data(); auto const end = itr + d_str.size_bytes(); while (itr < end && token_count < max_tokens) { cudf::char_utf8 ch = 0; auto const chr_width = cudf::strings::detail::to_char_utf8(itr, ch); if (spaces == is_whitespace(ch)) { itr += chr_width; } else { token_count += static_cast<size_type>(spaces); spaces = !spaces; } } return token_count; } // JIT has trouble including thrust/pair.h struct position_pair { size_type first; size_type second; }; /** * @brief Instantiated for each string to manage navigating tokens from * the beginning or the end of that string. */ struct whitespace_string_tokenizer { /** * @brief Identifies the position range of the next token in the given * string at the specified iterator position. * * Tokens are delimited by one or more whitespace characters. * * @return true if a token has been found */ __device__ bool next_token() { if (start_position >= d_str.size_bytes()) { return false; } auto const src_ptr = d_str.data(); if (current_position != 0) { current_position += cudf::strings::detail::bytes_in_char_utf8(src_ptr[current_position]); start_position = current_position; } if (start_position >= d_str.size_bytes()) { return false; } // continue search for the next token end_position = d_str.size_bytes(); while (current_position < d_str.size_bytes()) { cudf::char_utf8 ch = 0; auto const chr_width = cudf::strings::detail::to_char_utf8(src_ptr + current_position, ch); if (spaces == is_whitespace(ch)) { current_position += chr_width; if (spaces) { start_position = current_position; } else { end_position = current_position; } continue; } spaces = !spaces; if (spaces) { end_position = current_position; break; } current_position += chr_width; } return start_position < end_position; } /** * @brief Identifies the position range of the previous token in the given * string at the specified iterator position. * * Tokens are delimited by one or more whitespace characters. * * @return true if a token has been found */ __device__ bool prev_token() { end_position = start_position - 1; --itr; if (end_position <= 0) return false; // continue search for the next token start_position = 0; for (; itr >= d_str.begin(); --itr) { if (spaces == (*itr <= ' ')) { if (spaces) end_position = itr.byte_offset(); else start_position = itr.byte_offset(); continue; } spaces = !spaces; if (spaces) { start_position = (itr + 1).byte_offset(); break; } } return start_position < end_position; } __device__ position_pair get_token() const { return position_pair{start_position, end_position}; } __device__ whitespace_string_tokenizer(string_view const& d_str, bool reverse = false) : d_str{d_str}, spaces(true), start_position{reverse ? d_str.size_bytes() + 1 : 0}, end_position{d_str.size_bytes()}, itr{reverse ? d_str.end() : d_str.begin()}, current_position{0} { } private: string_view const d_str; bool spaces; // true if current position is whitespace cudf::string_view::const_iterator itr; size_type start_position; size_type end_position; size_type current_position; }; } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/pad_impl.cuh
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/detail/utf8.hpp> #include <cudf/strings/detail/utilities.cuh> #include <cudf/strings/side_type.hpp> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { /** * @brief Return the size in bytes of padding d_str to width characters using a fill character * with byte length of fill_char_size * * Pad does not perform truncation. That is, If `d_str.length() > width` then `d_str.size_bytes()` * is returned. * * @param d_str String to pad * @param width Number of characters for the padded string result * @param fill_char_size Size of the fill character in bytes * @return The number of bytes required for the pad */ __device__ size_type compute_padded_size(string_view d_str, size_type width, size_type fill_char_size) { auto const length = d_str.length(); auto bytes = d_str.size_bytes(); if (width > length) // no truncating; bytes += fill_char_size * (width - length); // add padding return bytes; } /** * @brief Pad d_str with fill_char into output up to width characters * * Pad does not perform truncation. That is, If `d_str.length() > width` then * then d_str is copied into output. * * @tparam side Specifies where fill_char is added to d_str * @param d_str String to pad * @param width Number of characters for the padded string result * @param fill_char Size of the fill character in bytes * @param output Device memory to copy the padded string into */ template <side_type side = side_type::RIGHT> __device__ void pad_impl(cudf::string_view d_str, cudf::size_type width, cudf::char_utf8 fill_char, char* output) { auto length = d_str.length(); if constexpr (side == side_type::LEFT) { while (length++ < width) { output += from_char_utf8(fill_char, output); } copy_string(output, d_str); } if constexpr (side == side_type::RIGHT) { output = copy_string(output, d_str); while (length++ < width) { output += from_char_utf8(fill_char, output); } } if constexpr (side == side_type::BOTH) { auto const pad_size = width - length; // an odd width will right-justify auto right_pad = (width % 2) ? pad_size / 2 : (pad_size - pad_size / 2); auto left_pad = pad_size - right_pad; // e.g. width=7: "++foxx+"; width=6: "+fox++" while (left_pad-- > 0) { output += from_char_utf8(fill_char, output); } output = copy_string(output, d_str); while (right_pad-- > 0) { output += from_char_utf8(fill_char, output); } } } /** * @brief Prepend d_str with '0' into output up to width characters * * Pad does not perform truncation. That is, If `d_str.length() > width` then * then d_str is copied into output. * * If d_str starts with a sign character ('-' or '+') then '0' padding * starts after the sign. * * @param d_str String to pad * @param width Number of characters for the padded string result * @param output Device memory to copy the padded string into */ __device__ void zfill_impl(cudf::string_view d_str, cudf::size_type width, char* output) { auto length = d_str.length(); auto in_ptr = d_str.data(); // if the string starts with a sign, output the sign first if (!d_str.empty() && (*in_ptr == '-' || *in_ptr == '+')) { *output++ = *in_ptr++; d_str = cudf::string_view{in_ptr, d_str.size_bytes() - 1}; } while (length++ < width) *output++ = '0'; // prepend zero char copy_string(output, d_str); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/converters.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @copydoc to_integers(strings_column_view const&,data_type,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> to_integers(strings_column_view const& strings, data_type output_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_integers(strings_column_view const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_integers(column_view const& integers, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc to_floats(strings_column_view const&,data_type,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> to_floats(strings_column_view const& strings, data_type output_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_floats(strings_column_view const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_floats(column_view const& floats, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc to_booleans(strings_column_view const&,string_scalar * const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> to_booleans(strings_column_view const& strings, string_scalar const& true_string, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_booleans(strings_column_view const&,string_scalar const&,string_scalar * const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_booleans(column_view const& booleans, string_scalar const& true_string, string_scalar const& false_string, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc to_timestamps(strings_column_view const&,data_type,std::string_view, * rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<cudf::column> to_timestamps(strings_column_view const& strings, data_type timestamp_type, std::string_view format, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_timestamps(strings_column_view const&,std::string_view, * strings_column_view const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_timestamps(column_view const& timestamps, std::string_view format, strings_column_view const& names, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc to_durations(strings_column_view const&,data_type,std::string_view, * rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> to_durations(strings_column_view const& strings, data_type duration_type, std::string_view format, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_durations(strings_column_view const&,std::string_view. * rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_durations(column_view const& durations, std::string_view format, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc to_fixed_point(strings_column_view const&,data_type,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> to_fixed_point(strings_column_view const& strings, data_type output_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc from_fixed_point(strings_column_view const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> from_fixed_point(column_view const& integers, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/scatter.cuh
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column_factories.hpp> #include <cudf/strings/detail/utilities.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/distance.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/scatter.h> namespace cudf { namespace strings { namespace detail { /** * @brief Scatters strings into a copy of the target column * according to a scatter map. * * The scatter is performed according to the scatter iterator such that row * `scatter_map[i]` of the output column is replaced by the source string. * All other rows of the output column equal corresponding rows of the target table. * * If the same index appears more than once in the scatter map, the result is * undefined. * * The caller must update the null mask in the output column. * * @tparam SourceIterator must produce string_view objects * @tparam MapIterator must produce index values within the target column. * * @param source The iterator of source strings to scatter into the output column. * @param scatter_map Iterator of indices into the output column. * @param target The set of columns into which values from the source column * are to be scattered. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column. */ template <typename SourceIterator, typename MapIterator> std::unique_ptr<column> scatter(SourceIterator begin, SourceIterator end, MapIterator scatter_map, strings_column_view const& target, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { if (target.is_empty()) return make_empty_column(type_id::STRING); // create vector of string_view's to scatter into rmm::device_uvector<string_view> target_vector = create_string_vector_from_column(target, stream, rmm::mr::get_current_device_resource()); // this ensures empty strings are not mapped to nulls in the make_strings_column function auto const size = thrust::distance(begin, end); auto itr = thrust::make_transform_iterator( begin, [] __device__(string_view const sv) { return sv.empty() ? string_view{} : sv; }); // do the scatter thrust::scatter( rmm::exec_policy_nosync(stream), itr, itr + size, scatter_map, target_vector.begin()); // build the output column auto sv_span = cudf::device_span<string_view const>(target_vector); return make_strings_column(sv_span, string_view{nullptr, 0}, stream, mr); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/copy_if_else.cuh
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/detail/valid_if.cuh> #include <cudf/strings/detail/strings_children.cuh> #include <cudf/strings/strings_column_view.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/optional.h> namespace cudf { namespace strings { namespace detail { /** * @brief Returns a new strings column using the specified Filter to select * strings from the lhs iterator or the rhs iterator. * * ``` * output[i] = filter_fn(i) ? lhs(i) : rhs(i) * ``` * * @tparam StringIterLeft A random access iterator whose value_type is * `thrust::optional<string_view>` where the `optional` has a value iff the element is valid. * @tparam StringIterRight A random access iterator whose value_type is * `thrust::optional<string_view>` where the `optional` has a value iff the element is valid. * @tparam Filter Functor that takes an index and returns a boolean. * * @param lhs_begin Start of first set of data. Used when `filter_fn` returns true. * @param lhs_end End of first set of data. * @param rhs_begin Strings of second set of data. Used when `filter_fn` returns false. * @param filter_fn Called to determine which iterator to use for a specific row. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column. */ template <typename StringIterLeft, typename StringIterRight, typename Filter> std::unique_ptr<cudf::column> copy_if_else(StringIterLeft lhs_begin, StringIterLeft lhs_end, StringIterRight rhs_begin, Filter filter_fn, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto strings_count = std::distance(lhs_begin, lhs_end); if (strings_count == 0) return make_empty_column(type_id::STRING); // create null mask auto valid_mask = cudf::detail::valid_if( thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(strings_count), [lhs_begin, rhs_begin, filter_fn] __device__(size_type idx) { return filter_fn(idx) ? lhs_begin[idx].has_value() : rhs_begin[idx].has_value(); }, stream, mr); size_type null_count = valid_mask.second; auto null_mask = (null_count > 0) ? std::move(valid_mask.first) : rmm::device_buffer{}; // build offsets column auto offsets_transformer = [lhs_begin, rhs_begin, filter_fn] __device__(size_type idx) { auto const result = filter_fn(idx) ? lhs_begin[idx] : rhs_begin[idx]; return result.has_value() ? result->size_bytes() : 0; }; auto offsets_transformer_itr = thrust::make_transform_iterator( thrust::make_counting_iterator<size_type>(0), offsets_transformer); auto [offsets_column, bytes] = cudf::detail::make_offsets_child_column( offsets_transformer_itr, offsets_transformer_itr + strings_count, stream, mr); auto d_offsets = offsets_column->view().template data<int32_t>(); // build chars column auto chars_column = create_chars_child_column(bytes, stream, mr); auto d_chars = chars_column->mutable_view().template data<char>(); // fill in chars thrust::for_each_n( rmm::exec_policy(stream), thrust::make_counting_iterator<size_type>(0), strings_count, [lhs_begin, rhs_begin, filter_fn, d_offsets, d_chars] __device__(size_type idx) { auto const result = filter_fn(idx) ? lhs_begin[idx] : rhs_begin[idx]; if (!result.has_value()) return; auto const d_str = *result; memcpy(d_chars + d_offsets[idx], d_str.data(), d_str.size_bytes()); }); return make_strings_column(strings_count, std::move(offsets_column), std::move(chars_column), null_count, std::move(null_mask)); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/replace.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief The type of algorithm to use for a replace operation. */ enum class replace_algorithm { AUTO, ///< Automatically choose the algorithm based on heuristics ROW_PARALLEL, ///< Row-level parallelism CHAR_PARALLEL ///< Character-level parallelism }; /** * @copydoc cudf::strings::replace(strings_column_view const&, string_scalar const&, * string_scalar const&, int32_t, rmm::mr::device_memory_resource*) * * @tparam alg Replacement algorithm to use * @param[in] stream CUDA stream used for device memory operations and kernel launches. */ template <replace_algorithm alg = replace_algorithm::AUTO> std::unique_ptr<column> replace(strings_column_view const& strings, string_scalar const& target, string_scalar const& repl, int32_t maxrepl, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::strings::replace_slice(strings_column_view const&, string_scalar const&, * size_type. size_type, rmm::mr::device_memory_resource*) * * @param[in] stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> replace_slice(strings_column_view const& strings, string_scalar const& repl, size_type start, size_type stop, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::strings::replace(strings_column_view const&, strings_column_view const&, * strings_column_view const&, rmm::mr::device_memory_resource*) * * @param[in] stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> replace(strings_column_view const& strings, strings_column_view const& targets, strings_column_view const& repls, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Replaces any null string entries with the given string. * * This returns a strings column with no null entries. * * @code{.pseudo} * Example: * s = ["hello", nullptr, "goodbye"] * r = replace_nulls(s,"**") * r is now ["hello", "**", "goodbye"] * @endcode * * @param strings Strings column for this operation. * @param repl Replacement string for null entries. Default is empty string. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New strings column. */ std::unique_ptr<column> replace_nulls(strings_column_view const& strings, string_scalar const& repl, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/scan.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/column/column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace strings { namespace detail { /** * @brief Scan function for strings * * Called by cudf::scan() with only min and max aggregates. * * @tparam Op Either DeviceMin or DeviceMax operations * * @param input Input strings column * @param mask Mask for scan * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ template <typename Op> std::unique_ptr<column> scan_inclusive(column_view const& input, bitmask_type const* mask, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/is_float.cuh
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { /** * @brief Returns true if input contains the not-a-number string. * * The following are valid for this function: "NAN" and "NaN" * @param d_str input string * @return true if input is as valid NaN string. */ inline __device__ bool is_nan_str(string_view const& d_str) { auto const ptr = d_str.data(); return (d_str.size_bytes() == 3) && (ptr[0] == 'N' || ptr[0] == 'n') && (ptr[1] == 'A' || ptr[1] == 'a') && (ptr[2] == 'N' || ptr[2] == 'n'); } /** * @brief Returns true if input contains the infinity string. * * The following are valid for this function: "INF", "INFINITY", and "Inf" * @param d_str input string * @return true if input is as valid Inf string. */ inline __device__ bool is_inf_str(string_view const& d_str) { auto const ptr = d_str.data(); auto const size = d_str.size_bytes(); if (size != 3 && size != 8) return false; auto const prefix_valid = (ptr[0] == 'I' || ptr[0] == 'i') && (ptr[1] == 'N' || ptr[1] == 'n') && (ptr[2] == 'F' || ptr[2] == 'f'); return prefix_valid && ((size == 3) || ((ptr[3] == 'I' || ptr[3] == 'i') && (ptr[4] == 'N' || ptr[4] == 'n') && (ptr[5] == 'I' || ptr[5] == 'i') && (ptr[6] == 'T' || ptr[6] == 't') && (ptr[7] == 'Y' || ptr[7] == 'y'))); } /** * @brief Returns `true` if all characters in the string * are valid for conversion to a float type. * * Valid characters are in [-+0-9eE.]. The sign character (+/-) * is optional but if present must be the first character. * The sign character may also optionally appear right after the 'e' or 'E' * if the string is formatted with scientific notation. * The decimal character can appear only once and never after the * 'e' or 'E' character. * An empty string returns `false`. * No bounds checking is performed to verify if the value would fit * within a specific float type. * The following strings are also allowed and will return true: * "NaN", "NAN", "Inf", "INF", "INFINITY" * * @param d_str String to check. * @return true if string has valid float characters */ inline __device__ bool is_float(string_view const& d_str) { if (d_str.empty()) return false; bool decimal_found = false; bool exponent_found = false; size_type bytes = d_str.size_bytes(); char const* data = d_str.data(); // sign character allowed at the beginning of the string size_type ch_idx = (*data == '-' || *data == '+') ? 1 : 0; bool result = ch_idx < bytes; // check for nan and infinity strings if (result && data[ch_idx] > '9') { auto const inf_nan = string_view(data + ch_idx, bytes - ch_idx); if (is_nan_str(inf_nan) || is_inf_str(inf_nan)) return true; } // check for float chars [0-9] and a single decimal '.' // and scientific notation [eE][+-][0-9] for (; ch_idx < bytes; ++ch_idx) { auto chr = data[ch_idx]; if (chr >= '0' && chr <= '9') continue; if (!decimal_found && chr == '.') { decimal_found = true; // no more decimals continue; } if (!exponent_found && (chr == 'e' || chr == 'E')) { if (ch_idx + 1 < bytes) chr = data[ch_idx + 1]; if (chr == '-' || chr == '+') ++ch_idx; decimal_found = true; // no decimal allowed in exponent exponent_found = true; // no more exponents continue; } return false; } return result; } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/string_to_int.cuh
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { /** * @brief Converts a single string into an integer. * * The '+' and '-' are allowed but only at the beginning of the string. * The string is expected to contain base-10 [0-9] characters only. * Any other character will end the parse. * Overflow of the int64 type is not detected. */ __device__ inline int64_t string_to_integer(string_view const& d_str) { int64_t value = 0; size_type bytes = d_str.size_bytes(); if (bytes == 0) return value; char const* ptr = d_str.data(); int sign = 1; if (*ptr == '-' || *ptr == '+') { sign = (*ptr == '-' ? -1 : 1); ++ptr; --bytes; } for (size_type idx = 0; idx < bytes; ++idx) { char chr = *ptr++; if (chr < '0' || chr > '9') break; value = (value * 10) + static_cast<int64_t>(chr - '0'); } return value * static_cast<int64_t>(sign); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/string_to_float.cuh
/* * 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/detail/convert/is_float.cuh> #include <cudf/strings/string_view.cuh> #include <cmath> #include <limits> namespace cudf { namespace strings { namespace detail { /** * @brief This function converts the given string into a * floating point double value. * * This will also map strings containing "NaN", "Inf", etc. * to the appropriate float values. * * This function will also handle scientific notation format. */ __device__ inline double stod(string_view const& d_str) { char const* in_ptr = d_str.data(); char const* end = in_ptr + d_str.size_bytes(); if (end == in_ptr) return 0.0; double sign{1.0}; if (*in_ptr == '-' || *in_ptr == '+') { sign = (*in_ptr == '-' ? -1 : 1); ++in_ptr; } #ifndef CUDF_JIT_UDF constexpr double infinity = std::numeric_limits<double>::infinity(); constexpr uint64_t max_holding = (std::numeric_limits<uint64_t>::max() - 9L) / 10L; #else constexpr double infinity = (1.0 / 0.0); constexpr uint64_t max_holding = (18446744073709551615UL - 9UL) / 10UL; #endif // special strings: NaN, Inf if ((in_ptr < end) && *in_ptr > '9') { auto const inf_nan = string_view(in_ptr, static_cast<size_type>(end - in_ptr)); if (is_nan_str(inf_nan)) return nan(""); if (is_inf_str(inf_nan)) return sign * infinity; } // Parse and store the mantissa as much as we can, // until we are about to exceed the limit of uint64_t uint64_t digits = 0; int exp_off = 0; bool decimal = false; while (in_ptr < end) { char ch = *in_ptr; if (ch == '.') { decimal = true; ++in_ptr; continue; } if (ch < '0' || ch > '9') break; if (digits > max_holding) exp_off += (int)!decimal; else { digits = (digits * 10L) + static_cast<uint64_t>(ch - '0'); if (digits > max_holding) { digits = digits / 10L; exp_off += (int)!decimal; } else exp_off -= (int)decimal; } ++in_ptr; } if (digits == 0) return sign * static_cast<double>(0); // check for exponent char int exp_ten = 0; int exp_sign = 1; if (in_ptr < end) { char ch = *in_ptr++; if (ch == 'e' || ch == 'E') { if (in_ptr < end) { ch = *in_ptr; if (ch == '-' || ch == '+') { exp_sign = (ch == '-' ? -1 : 1); ++in_ptr; } while (in_ptr < end) { ch = *in_ptr++; if (ch < '0' || ch > '9') break; exp_ten = (exp_ten * 10) + (int)(ch - '0'); } } } } int const num_digits = static_cast<int>(log10(static_cast<double>(digits))) + 1; exp_ten *= exp_sign; exp_ten += exp_off; exp_ten += num_digits - 1; if (exp_ten > std::numeric_limits<double>::max_exponent10) { return sign > 0 ? infinity : -infinity; } double base = sign * static_cast<double>(digits); exp_ten += 1 - num_digits; // If 10^exp_ten would result in a subnormal value, the base and // exponent should be adjusted so that 10^exp_ten is a normal value auto const subnormal_shift = std::numeric_limits<double>::min_exponent10 - exp_ten; if (subnormal_shift > 0) { // Handle subnormal values. Ensure that both base and exponent are // normal values before computing their product. base = base / exp10(static_cast<double>(num_digits - 1 + subnormal_shift)); exp_ten += num_digits - 1; // adjust exponent auto const exponent = exp10(static_cast<double>(exp_ten + subnormal_shift)); return base * exponent; } double const exponent = exp10(static_cast<double>(std::abs(exp_ten))); return exp_ten < 0 ? base / exponent : base * exponent; } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/int_to_string.cuh
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/detail/utilities/integer_utils.hpp> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace detail { /** * @brief Converts an integer into string * * @tparam IntegerType integer type to convert from * @param value integer value to convert * @param d_buffer character buffer to store the converted string */ template <typename IntegerType> __device__ inline size_type integer_to_string(IntegerType value, char* d_buffer) { if (value == 0) { *d_buffer = '0'; return 1; } bool const is_negative = cuda::std::is_signed<IntegerType>() ? (value < 0) : false; constexpr IntegerType base = 10; // largest 64-bit integer is 20 digits; largest 128-bit integer is 39 digits constexpr int MAX_DIGITS = cuda::std::numeric_limits<IntegerType>::digits10 + 1; char digits[MAX_DIGITS]; // place-holder for digit chars int digits_idx = 0; while (value != 0) { assert(digits_idx < MAX_DIGITS); digits[digits_idx++] = '0' + cudf::util::absolute_value(value % base); // next digit value = value / base; } size_type const bytes = digits_idx + static_cast<size_type>(is_negative); char* ptr = d_buffer; if (is_negative) *ptr++ = '-'; // digits are backwards, reverse the string into the output while (digits_idx-- > 0) *ptr++ = digits[digits_idx]; return bytes; } /** * @brief Counts number of digits in a integer value including '-' sign * * @tparam IntegerType integer type of input value * @param value input value to count the digits of * @return size_type number of digits in input value */ template <typename IntegerType> constexpr size_type count_digits(IntegerType value) { if (value == 0) return 1; bool const is_negative = cuda::std::is_signed<IntegerType>() ? (value < 0) : false; // abs(std::numeric_limits<IntegerType>::min()) is negative; // for all integer types, the max() and min() values have the same number of digits value = (value == cuda::std::numeric_limits<IntegerType>::min()) ? cuda::std::numeric_limits<IntegerType>::max() : cudf::util::absolute_value(value); auto const digits = [value] { // largest 8-byte unsigned value is 18446744073709551615 (20 digits) // largest 16-byte unsigned value is 340282366920938463463374607431768211455 (39 digits) auto constexpr max_digits = cuda::std::numeric_limits<IntegerType>::digits10 + 1; size_type digits = 1; __int128_t pow10 = 10; for (; digits < max_digits; ++digits, pow10 *= 10) if (value < pow10) break; return digits; }(); return digits + static_cast<size_type>(is_negative); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/fixed_point.cuh
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/fixed_point/temporary.hpp> #include <thrust/optional.h> #include <thrust/pair.h> #include <cuda/std/type_traits> namespace cudf { namespace strings { namespace detail { /** * @brief Return the integer component of a decimal string. * * This reads everything up to the exponent 'e' notation. * The return includes the integer digits and any exponent offset. * * @tparam UnsignedDecimalType The unsigned version of the desired decimal type. * Use the `std::make_unsigned_t` to create the * unsigned type from the storage type. * * @param[in,out] iter Start of characters to parse * @param[in] end End of characters to parse * @return Integer component and exponent offset. */ template <typename UnsignedDecimalType> __device__ inline thrust::pair<UnsignedDecimalType, int32_t> parse_integer( char const*& iter, char const* iter_end, char const decimal_pt_char = '.') { // highest value where another decimal digit cannot be appended without an overflow; // this preserves the most digits when scaling the final result for this type constexpr UnsignedDecimalType decimal_max = (std::numeric_limits<UnsignedDecimalType>::max() - 9L) / 10L; __uint128_t value = 0; // for checking overflow int32_t exp_offset = 0; bool decimal_found = false; while (iter < iter_end) { auto const ch = *iter++; if (ch == decimal_pt_char && !decimal_found) { decimal_found = true; continue; } if (ch < '0' || ch > '9') { --iter; break; } if (value > decimal_max) { exp_offset += static_cast<int32_t>(!decimal_found); } else { value = (value * 10) + static_cast<UnsignedDecimalType>(ch - '0'); exp_offset -= static_cast<int32_t>(decimal_found); } } return {value, exp_offset}; } /** * @brief Return the exponent of a decimal string. * * This should only be called after the exponent 'e' notation was detected. * The return is the exponent (base-10) integer and can only be * invalid if `check_only == true` and invalid characters are found or the * exponent overflows an int32. * * @tparam check_only Set to true to verify the characters are valid and the * exponent value in the decimal string does not overflow int32 * @param[in,out] iter Start of characters to parse * (points to the character after the 'E' or 'e') * @param[in] end End of characters to parse * @return Integer value of the exponent */ template <bool check_only = false> __device__ thrust::optional<int32_t> parse_exponent(char const* iter, char const* iter_end) { constexpr uint32_t exponent_max = static_cast<uint32_t>(std::numeric_limits<int32_t>::max()); // get optional exponent sign int32_t const exp_sign = [&iter] { auto const ch = *iter; if (ch != '-' && ch != '+') { return 1; } ++iter; return (ch == '-' ? -1 : 1); }(); // parse exponent integer int32_t exp_ten = 0; while (iter < iter_end) { auto const ch = *iter++; if (ch < '0' || ch > '9') { if (check_only) { return thrust::nullopt; } break; } uint32_t exp_check = static_cast<uint32_t>(exp_ten * 10) + static_cast<uint32_t>(ch - '0'); if (check_only && (exp_check > exponent_max)) { return thrust::nullopt; } // check overflow exp_ten = static_cast<int32_t>(exp_check); } return exp_ten * exp_sign; } /** * @brief Converts the string in the range [iter, iter_end) into a decimal. * * @tparam DecimalType The decimal type to be returned * @param iter The beginning of the string * @param iter_end The end of the characters to parse * @param scale The scale to be applied * @return */ template <typename DecimalType> __device__ DecimalType parse_decimal(char const* iter, char const* iter_end, int32_t scale) { auto const sign = [&] { if (iter_end <= iter) { return 0; } if (*iter == '-') { return -1; } if (*iter == '+') { return 1; } return 0; }(); // if string begins with a sign, continue with next character if (sign != 0) ++iter; using UnsignedDecimalType = cuda::std::make_unsigned_t<DecimalType>; auto [value, exp_offset] = parse_integer<UnsignedDecimalType>(iter, iter_end); if (value == 0) { return DecimalType{0}; } // check for exponent int32_t exp_ten = 0; if ((iter < iter_end) && (*iter == 'e' || *iter == 'E')) { ++iter; if (iter < iter_end) { exp_ten = parse_exponent<false>(iter, iter_end).value(); } } exp_ten += exp_offset; // shift the output value based on the exp_ten and the scale values auto const shift_adjust = abs(scale - exp_ten) > cuda::std::numeric_limits<UnsignedDecimalType>::digits10 ? cuda::std::numeric_limits<UnsignedDecimalType>::max() : numeric::detail::exp10<UnsignedDecimalType>(abs(scale - exp_ten)); value = exp_ten < scale ? value / shift_adjust : value * shift_adjust; return static_cast<DecimalType>(value) * (sign == 0 ? 1 : sign); } } // namespace detail } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail
rapidsai_public_repos/cudf/cpp/include/cudf/strings/detail/convert/fixed_point_to_string.cuh
/* * 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/strings/detail/convert/int_to_string.cuh> namespace cudf::strings::detail { /** * @brief Returns the number of digits in the given fixed point number. * * @param value The value of the fixed point number * @param scale The scale of the fixed point number * @return int32_t The number of digits required to represent the fixed point number */ __device__ inline int32_t fixed_point_string_size(__int128_t const& value, int32_t scale) { if (scale >= 0) return count_digits(value) + scale; auto const abs_value = numeric::detail::abs(value); auto const exp_ten = numeric::detail::exp10<__int128_t>(-scale); auto const fraction = count_digits(abs_value % exp_ten); auto const num_zeros = std::max(0, (-scale - fraction)); return static_cast<int32_t>(value < 0) + // sign if negative count_digits(abs_value / exp_ten) + // integer 1 + // decimal point num_zeros + // zeros padding fraction; // size of fraction } /** * @brief Converts the given fixed point number to a string. * * Caller is responsible for ensuring that the output buffer is large enough. The required output * buffer size can be obtained by calling `fixed_point_string_size`. * * @param value The value of the fixed point number * @param scale The scale of the fixed point number * @param out_ptr The pointer to the output string */ __device__ inline void fixed_point_to_string(__int128_t const& value, int32_t scale, char* out_ptr) { if (scale >= 0) { out_ptr += integer_to_string(value, out_ptr); thrust::generate_n(thrust::seq, out_ptr, scale, []() { return '0'; }); // add zeros return; } // scale < 0 // write format: [-]integer.fraction // where integer = abs(value) / (10^abs(scale)) // fraction = abs(value) % (10^abs(scale)) if (value < 0) *out_ptr++ = '-'; // add sign auto const abs_value = numeric::detail::abs(value); auto const exp_ten = numeric::detail::exp10<__int128_t>(-scale); auto const num_zeros = std::max(0, (-scale - count_digits(abs_value % exp_ten))); out_ptr += integer_to_string(abs_value / exp_ten, out_ptr); // add the integer part *out_ptr++ = '.'; // add decimal point thrust::generate_n(thrust::seq, out_ptr, num_zeros, []() { return '0'; }); // add zeros out_ptr += num_zeros; integer_to_string(abs_value % exp_ten, out_ptr); // add the fraction part } } // namespace cudf::strings::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/split/split_re.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { struct regex_program; /** * @addtogroup strings_split * @{ * @file */ /** * @brief Splits strings elements into a table of strings columns * using a regex_program's pattern to delimit each string * * Each element generates a vector of strings that are stored in corresponding * rows in the output table -- `table[col,row] = token[col] of strings[row]` * where `token` is a substring between delimiters. * * The number of rows in the output table will be the same as the number of * elements in the input column. The resulting number of columns will be the * maximum number of tokens found in any input row. * * The `pattern` is used to identify the delimiters within a string * and splitting stops when either `maxsplit` or the end of the string is reached. * * An empty input string will produce a corresponding empty string in the * corresponding row of the first column. * A null row will produce corresponding null rows in the output table. * * The regex_program's regex_flags are ignored. * * @code{.pseudo} * s = ["a_bc def_g", "a__bc", "_ab cd", "ab_cd "] * p1 = regex_program::create("[_ ]") * s1 = split_re(s, p1) * s1 is a table of strings columns: * [ ["a", "a", "", "ab"], * ["bc", "", "ab", "cd"], * ["def", "bc", "cd", ""], * ["g", null, null, null] ] * p2 = regex_program::create("[ _]") * s2 = split_re(s, p2, 1) * s2 is a table of strings columns: * [ ["a", "a", "", "ab"], * ["bc def_g", "_bc", "ab cd", "cd "] ] * @endcode * * @throw cudf::logic_error if `pattern` is empty. * * @param input A column of string elements to be split * @param prog Regex program instance * @param maxsplit Maximum number of splits to perform. * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return A table of columns of strings */ std::unique_ptr<table> split_re( strings_column_view const& input, regex_program const& prog, size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Splits strings elements into a table of strings columns using a * regex_program's pattern to delimit each string starting from the end of the string * * Each element generates a vector of strings that are stored in corresponding * rows in the output table -- `table[col,row] = token[col] of string[row]` * where `token` is the substring between each delimiter. * * The number of rows in the output table will be the same as the number of * elements in the input column. The resulting number of columns will be the * maximum number of tokens found in any input row. * * Splitting occurs by traversing starting from the end of the input string. * The `pattern` is used to identify the delimiters within a string * and splitting stops when either `maxsplit` or the beginning of the string * is reached. * * An empty input string will produce a corresponding empty string in the * corresponding row of the first column. * A null row will produce corresponding null rows in the output table. * * The regex_program's regex_flags are ignored. * * @code{.pseudo} * s = ["a_bc def_g", "a__bc", "_ab cd", "ab_cd "] * p1 = regex_program::create("[_ ]") * s1 = rsplit_re(s, p1) * s1 is a table of strings columns: * [ ["a", "a", "", "ab"], * ["bc", "", "ab", "cd"], * ["def", "bc", "cd", ""], * ["g", null, null, null] ] * p2 = regex_program::create("[ _]") * s2 = rsplit_re(s, p2, 1) * s2 is a table of strings columns: * [ ["a_bc def", "a_", "_ab", "ab"], * ["g", "bc", "cd", "cd "] ] * @endcode * * @throw cudf::logic_error if `pattern` is empty. * * @param input A column of string elements to be split * @param prog Regex program instance * @param maxsplit Maximum number of splits to perform. * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return A table of columns of strings */ std::unique_ptr<table> rsplit_re( strings_column_view const& input, regex_program const& prog, size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Splits strings elements into a list column of strings * using the given regex_program to delimit each string * * Each element generates an array of strings that are stored in an output * lists column -- `list[row] = [token1, token2, ...] found in input[row]` * where `token` is a substring between delimiters. * * The number of elements in the output column will be the same as the number of * elements in the input column. Each individual list item will contain the * new strings for that row. The resulting number of strings in each row can vary * from 0 to `maxsplit + 1`. * * The `pattern` is used to identify the delimiters within a string * and splitting stops when either `maxsplit` or the end of the string is reached. * * An empty input string will produce a corresponding empty list item output row. * A null row will produce a corresponding null output row. * * The regex_program's regex_flags are ignored. * * @code{.pseudo} * s = ["a_bc def_g", "a__bc", "_ab cd", "ab_cd "] * p1 = regex_program::create("[_ ]") * s1 = split_record_re(s, p1) * s1 is a lists column of strings: * [ ["a", "bc", "def", "g"], * ["a", "", "bc"], * ["", "ab", "cd"], * ["ab", "cd", ""] ] * p2 = regex_program::create("[ _]") * s2 = split_record_re(s, p2, 1) * s2 is a lists column of strings: * [ ["a", "bc def_g"], * ["a", "_bc"], * ["", "ab cd"], * ["ab", "cd "] ] * @endcode * * @throw cudf::logic_error if `pattern` is empty. * * See the @ref md_regex "Regex Features" page for details on patterns supported by this API. * * @param input A column of string elements to be split * @param prog Regex program instance * @param maxsplit Maximum number of splits to perform. * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return Lists column of strings */ std::unique_ptr<column> split_record_re( strings_column_view const& input, regex_program const& prog, size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Splits strings elements into a list column of strings using the given * regex_program to delimit each string starting from the end of the string * * Each element generates a vector of strings that are stored in an output * lists column -- `list[row] = [token1, token2, ...] found in input[row]` * where `token` is a substring between delimiters. * * The number of elements in the output column will be the same as the number of * elements in the input column. Each individual list item will contain the * new strings for that row. The resulting number of strings in each row can vary * from 0 to `maxsplit + 1`. * * Splitting occurs by traversing starting from the end of the input string. * The `pattern` is used to identify the separation points within a string * and splitting stops when either `maxsplit` or the beginning of the string * is reached. * * An empty input string will produce a corresponding empty list item output row. * A null row will produce a corresponding null output row. * * The regex_program's regex_flags are ignored. * * @code{.pseudo} * s = ["a_bc def_g", "a__bc", "_ab cd", "ab_cd "] * p1 = regex_program::create("[_ ]") * s1 = rsplit_record_re(s, p1) * s1 is a lists column of strings: * [ ["a", "bc", "def", "g"], * ["a", "", "bc"], * ["", "ab", "cd"], * ["ab", "cd", ""] ] * p2 = regex_program::create("[ _]") * s2 = rsplit_record_re(s, p2, 1) * s2 is a lists column of strings: * [ ["a_bc def", "g"], * ["a_", "bc"], * ["_ab", "cd"], * ["ab_cd", ""] ] * @endcode * * See the @ref md_regex "Regex Features" page for details on patterns supported by this API. * * @throw cudf::logic_error if `pattern` is empty. * * @param input A column of string elements to be split * @param prog Regex program instance * @param maxsplit Maximum number of splits to perform. * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return Lists column of strings */ std::unique_ptr<column> rsplit_record_re( strings_column_view const& input, regex_program const& prog, size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/split/split.hpp
/* * 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. */ #pragma once #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_split * @{ * @file */ /** * @brief Returns a list of columns by splitting each string using the * specified delimiter. * * The number of rows in the output columns will be the same as the * input column. The first column will contain the first tokens of * each string as a result of the split. Subsequent columns contain * the next token strings. Null entries are added for a row where * split results have been exhausted. The total number of columns * will equal the maximum number of splits encountered on any string * in the input column. * * Any null string entries return corresponding null output columns. * * @param strings_column Strings instance for this operation * @param delimiter UTF-8 encoded string indicating the split points in each string; * Default of empty string indicates split on whitespace. * @param maxsplit Maximum number of splits to perform; * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned table's device memory * @return New table of strings columns */ std::unique_ptr<table> split( strings_column_view const& strings_column, string_scalar const& delimiter = string_scalar(""), size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a list of columns by splitting each string using the * specified delimiter starting from the end of each string. * * The number of rows in the output columns will be the same as the * input column. The first column will contain the first tokens encountered * in each string as a result of the split. Subsequent columns contain * the next token strings. Null entries are added for a row where * split results have been exhausted. The total number of columns * will equal the maximum number of splits encountered on any string * in the input column. * * Any null string entries return corresponding null output columns. * * @param strings_column Strings instance for this operation * @param delimiter UTF-8 encoded string indicating the split points in each string; * Default of empty string indicates split on whitespace. * @param maxsplit Maximum number of splits to perform; * Default of -1 indicates all possible splits on each string. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned table's device memory * @return New strings columns. */ std::unique_ptr<table> rsplit( strings_column_view const& strings_column, string_scalar const& delimiter = string_scalar(""), size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Splits individual strings elements into a list of strings. * * Each element generates an array of strings that are stored in an output * lists column. * * The number of elements in the output column will be the same as the number of * elements in the input column. Each individual list item will contain the * new strings for that row. The resulting number of strings in each row can vary * from 0 to `maxsplit + 1`. * * The `delimiter` is searched within each string from beginning to end * and splitting stops when either `maxsplit` or the end of the string is reached. * * If a delimiter is not whitespace and occurs adjacent to another delimiter, * an empty string is produced for that split occurrence. Likewise, a non-whitespace * delimiter produces an empty string if it appears at the beginning or the end * of a string. * * @code{.pseudo} * s = ["a_bc_def_g", "a__bc", "_ab_cd", "ab_cd_"] * s1 = split_record(s, "_") * s1 is a lists column of strings: * [ ["a", "bc", "def", "g"], * ["a", "", "bc"], * ["", "ab", "cd"], * ["ab", "cd", ""] ] * s2 = split_record(s, "_", 1) * s2 is a lists column of strings: * [ ["a", "bc_def_g"], * ["a", "_bc"], * ["", "ab_cd"], * ["ab", "cd_"] ] * @endcode * * A whitespace delimiter produces no empty strings. * @code{.pseudo} * s = ["a bc def", "a bc", " ab cd", "ab cd "] * s1 = split_record(s, "") * s1 is a lists column of strings: * [ ["a", "bc", "def"], * ["a", "bc"], * ["ab", "cd"], * ["ab", "cd"] ] * s2 = split_record(s, "", 1) * s2 is a lists column of strings: * [ ["a", "bc def"], * ["a", "bc"], * ["ab", "cd"], * ["ab", "cd "] ] * @endcode * * A null string element will result in a null list item for that row. * * @throw cudf:logic_error if `delimiter` is invalid. * * @param strings A column of string elements to be split * @param delimiter The string to identify split points in each string; * Default of empty string indicates split on whitespace. * @param maxsplit Maximum number of splits to perform; * Default of -1 indicates all possible splits on each string * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return Lists column of strings; * Each row of the lists column holds splits from a single row * element of the input column. */ std::unique_ptr<column> split_record( strings_column_view const& strings, string_scalar const& delimiter = string_scalar(""), size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Splits individual strings elements into a list of strings starting * from the end of each string. * * Each element generates an array of strings that are stored in an output * lists column. * * The number of elements in the output column will be the same as the number of * elements in the input column. Each individual list item will contain the * new strings for that row. The resulting number of strings in each row can vary * from 0 to `maxsplit + 1`. * * The `delimiter` is searched from end to beginning within each string * and splitting stops when either `maxsplit` or the beginning of the string * is reached. * * If a delimiter is not whitespace and occurs adjacent to another delimiter, * an empty string is produced for that split occurrence. Likewise, a non-whitespace * delimiter produces an empty string if it appears at the beginning or the end * of a string. * * Note that `rsplit_record` and `split_record` produce equivalent results for * the default `maxsplit` value. * * @code{.pseudo} * s = ["a_bc_def_g", "a__bc", "_ab_cd", "ab_cd_"] * s1 = rsplit_record(s, "_") * s1 is a lists column of strings: * [ ["a", "bc", "def", "g"], * ["a", "", "bc"], * ["", "ab", "cd"], * ["ab", "cd", ""] ] * s2 = rsplit_record(s, "_", 1) * s2 is a lists column of strings: * [ ["a_bc_def", "g"], * ["a_", "bc"], * ["_ab", "cd"], * ["ab_cd", ""] ] * @endcode * * A whitespace delimiter produces no empty strings. * @code{.pseudo} * s = ["a bc def", "a bc", " ab cd", "ab cd "] * s1 = rsplit_record(s, "") * s1 is a lists column of strings: * [ ["a", "bc", "def"], * ["a", "bc"], * ["ab", "cd"], * ["ab", "cd"] ] * s2 = rsplit_record(s, "", 1) * s2 is a lists column of strings: * [ ["a bc", "def"], * ["a", "bc"], * [" ab", "cd"], * ["ab", "cd"] ] * @endcode * * A null string element will result in a null list item for that row. * * @throw cudf:logic_error if `delimiter` is invalid. * * @param strings A column of string elements to be split * @param delimiter The string to identify split points in each string; * Default of empty string indicates split on whitespace. * @param maxsplit Maximum number of splits to perform; * Default of -1 indicates all possible splits on each string * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned result's device memory * @return Lists column of strings; * Each row of the lists column holds splits from a single row * element of the input column. */ std::unique_ptr<column> rsplit_record( strings_column_view const& strings, string_scalar const& delimiter = string_scalar(""), size_type maxsplit = -1, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/split/partition.hpp
/* * 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. */ #pragma once #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_split * @{ * @file strings/split/partition.hpp * @brief Strings partition APIs */ /** * @brief Returns a set of 3 columns by splitting each string using the * specified delimiter. * * The number of rows in the output columns will be the same as the * input column. The first column will contain the first tokens of * each string as a result of the split. The second column will contain * the delimiter. The third column will contain the remaining characters * of each string after the delimiter. * * Any null string entries return corresponding null output columns. * * @code{.pseudo} * Example: * s = ["ab_cd","def_g_h"] * r = partition(s,"_") * r[0] is ["ab","def"] * r[1] is ["_","_"] * r[2] is ["cd","g_h"] * @endcode * * @param input Strings instance for this operation * @param delimiter UTF-8 encoded string indicating where to split each string. * Default of empty string indicates split on whitespace. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned table's device memory * @return New table of strings columns */ std::unique_ptr<table> partition( strings_column_view const& input, string_scalar const& delimiter = string_scalar(""), rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a set of 3 columns by splitting each string using the * specified delimiter starting from the end of each string. * * The number of rows in the output columns will be the same as the * input column. The first column will contain the characters of * each string before the last delimiter found. The second column will contain * the delimiter. The third column will contain the remaining characters * of each string after the delimiter. * * Any null string entries return corresponding null output columns. * * @code{.pseudo} * Example: * s = ["ab_cd","def_g_h"] * r = rpartition(s,"_") * r[0] is ["ab","def_g"] * r[1] is ["_","_"] * r[2] is ["cd","h"] * @endcode * * @param input Strings instance for this operation * @param delimiter UTF-8 encoded string indicating where to split each string. * Default of empty string indicates split on whitespace. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned table's device memory * @return New strings columns */ std::unique_ptr<table> rpartition( strings_column_view const& input, string_scalar const& delimiter = string_scalar(""), rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/regex/flags.hpp
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cstdint> namespace cudf { namespace strings { /** * @addtogroup strings_regex * @{ */ /** * @brief Regex flags. * * These types can be or'd to combine them. * The values are chosen to leave room for future flags * and to match the Python flag values. */ enum regex_flags : uint32_t { DEFAULT = 0, ///< default MULTILINE = 8, ///< the '^' and '$' honor new-line characters DOTALL = 16, ///< the '.' matching includes new-line characters ASCII = 256 ///< use only ASCII when matching built-in character classes }; /** * @brief Returns true if the given flags contain MULTILINE. * * @param f Regex flags to check * @return true if `f` includes MULTILINE */ constexpr bool is_multiline(regex_flags const f) { return (f & regex_flags::MULTILINE) == regex_flags::MULTILINE; } /** * @brief Returns true if the given flags contain DOTALL. * * @param f Regex flags to check * @return true if `f` includes DOTALL */ constexpr bool is_dotall(regex_flags const f) { return (f & regex_flags::DOTALL) == regex_flags::DOTALL; } /** * @brief Returns true if the given flags contain ASCII. * * @param f Regex flags to check * @return true if `f` includes ASCII */ constexpr bool is_ascii(regex_flags const f) { return (f & regex_flags::ASCII) == regex_flags::ASCII; } /** * @brief Capture groups setting * * For processing a regex pattern containing capture groups. * These can be used to optimize the generated regex instructions * where the capture groups do not require extracting the groups. */ enum class capture_groups : uint32_t { EXTRACT, ///< Capture groups processed normally for extract NON_CAPTURE ///< Convert all capture groups to non-capture groups }; /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/regex/regex_program.hpp
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/regex/flags.hpp> #include <cudf/types.hpp> #include <memory> #include <string> namespace cudf { namespace strings { /** * @addtogroup strings_regex * @{ */ /** * @brief Regex program class * * Create an instance from a regex pattern and use it to call the appropriate * strings APIs. An instance can be reused. * * See the @ref md_regex "Regex Features" page for details on patterns and APIs that support regex. */ struct regex_program { struct regex_program_impl; /** * @brief Create a program from a pattern * * @throw cudf::logic_error If pattern is invalid or contains unsupported features * * @param pattern Regex pattern * @param flags Regex flags for interpreting special characters in the pattern * @param capture Controls how capture groups in the pattern are used * @return Instance of this object */ static std::unique_ptr<regex_program> create(std::string_view pattern, regex_flags flags = regex_flags::DEFAULT, capture_groups capture = capture_groups::EXTRACT); /** * @brief Move constructor * * @param other Object to move from */ regex_program(regex_program&& other); /** * @brief Move operator assignment * * @param other Object to move from * @return this object */ regex_program& operator=(regex_program&& other); /** * @brief Return the pattern used to create this instance * * @return regex pattern as a string */ std::string pattern() const; /** * @brief Return the regex_flags used to create this instance * * @return regex flags setting */ regex_flags flags() const; /** * @brief Return the capture_groups used to create this instance * * @return capture groups setting */ capture_groups capture() const; /** * @brief Return the number of instructions in this instance * * @return Number of instructions */ int32_t instructions_count() const; /** * @brief Return the number of capture groups in this instance * * @return Number of groups */ int32_t groups_count() const; /** * @brief Return the size of the working memory for the regex execution * * @param num_strings Number of strings for computation * @return Size of the working memory in bytes */ std::size_t compute_working_memory_size(int32_t num_strings) const; ~regex_program(); private: regex_program() = delete; std::string _pattern; regex_flags _flags; capture_groups _capture; std::unique_ptr<regex_program_impl> _impl; /** * @brief Constructor * * Called by create() */ regex_program(std::string_view pattern, regex_flags flags, capture_groups capture); friend struct regex_device_builder; }; /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_floats.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new numeric column by parsing float values from each string * in the provided strings column. * * Any null entries will result in corresponding null entries in the output column. * * Only characters [0-9] plus a prefix '-' and '+' and decimal '.' are recognized. * Additionally, scientific notation is also supported (e.g. "-1.78e+5"). * * @throw cudf::logic_error if output_type is not float type. * * @param strings Strings instance for this operation * @param output_type Type of float numeric column to return * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with floats converted from strings */ std::unique_ptr<column> to_floats( strings_column_view const& strings, data_type output_type, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting the float values from the * provided column into strings. * * Any null entries will result in corresponding null entries in the output column. * * For each float, a string is created in base-10 decimal. * Negative numbers will include a '-' prefix. * Numbers producing more than 10 significant digits will produce a string that * includes scientific notation (e.g. "-1.78e+15"). * * @throw cudf::logic_error if floats column is not float type. * * @param floats Numeric column to convert * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column with floats as strings */ std::unique_ptr<column> from_floats( column_view const& floats, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to floats. * * The output row entry will be set to `true` if the corresponding string element * has at least one character in [-+0-9eE.]. * * @code{.pseudo} * Example: * s = ['123', '-456', '', 'A', '+7', '8.9' '3.7e+5'] * b = s.is_float(s) * b is [true, true, false, false, true, true, true] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_float( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_booleans.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new BOOL8 column by parsing boolean values from the strings * in the provided strings column. * * Any null entries will result in corresponding null entries in the output column. * * @param input Strings instance for this operation * @param true_string String to expect for true. Non-matching strings are false * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New BOOL8 column converted from strings */ std::unique_ptr<column> to_booleans( strings_column_view const& input, string_scalar const& true_string, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting the boolean values from the * provided column into strings. * * Any null entries will result in corresponding null entries in the output column. * * @throw cudf::logic_error if the input column is not BOOL8 type. * * @param booleans Boolean column to convert * @param true_string String to use for true in the output column * @param false_string String to use for false in the output column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> from_booleans( column_view const& booleans, string_scalar const& true_string, string_scalar const& false_string, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_durations.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new duration column converting a strings column into * durations using the provided format pattern. * * The format pattern can include the following specifiers: * "%%,%n,%t,%D,%H,%I,%M,%S,%p,%R,%T,%r,%OH,%OI,%OM,%OS" * * | Specifier | Description | Range | * | :-------: | ----------- | ---------------- | * | %% | A literal % character | % | * | \%n | A newline character | \\n | * | \%t | A horizontal tab character | \\t | * | \%D | Days | -2,147,483,648 to 2,147,483,647 | * | \%H | 24-hour of the day | 00 to 23 | * | \%I | 12-hour of the day | 00 to 11 | * | \%M | Minute of the hour | 00 to 59 | * | \%S | Second of the minute | 00 to 59.999999999 | * | \%OH | same as %H but without sign | 00 to 23 | * | \%OI | same as %I but without sign | 00 to 11 | * | \%OM | same as %M but without sign | 00 to 59 | * | \%OS | same as %S but without sign | 00 to 59 | * | \%p | AM/PM designations associated with a 12-hour clock | 'AM' or 'PM' | * | \%R | Equivalent to "%H:%M" | | * | \%T | Equivalent to "%H:%M:%S" | | * | \%r | Equivalent to "%OI:%OM:%OS %p" | | * * Other specifiers are not currently supported. * * Invalid formats are not checked. If the string contains unexpected * or insufficient characters, that output row entry's duration value is undefined. * * Any null string entry will result in a corresponding null row in the output column. * * The resulting time units are specified by the `duration_type` parameter. * * @throw cudf::logic_error if duration_type is not a duration type. * * @param input Strings instance for this operation * @param duration_type The duration type used for creating the output column * @param format String specifying the duration format in strings * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New duration column */ std::unique_ptr<column> to_durations( strings_column_view const& input, data_type duration_type, std::string_view format, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting a duration column into * strings using the provided format pattern. * * The format pattern can include the following specifiers: * "%%,%n,%t,%D,%H,%I,%M,%S,%p,%R,%T,%r,%OH,%OI,%OM,%OS" * * | Specifier | Description | Range | * | :-------: | ----------- | ---------------- | * | %% | A literal % character | % | * | \%n | A newline character | \\n | * | \%t | A horizontal tab character | \\t | * | \%D | Days | -2,147,483,648 to 2,147,483,647 | * | \%H | 24-hour of the day | 00 to 23 | * | \%I | 12-hour of the day | 00 to 11 | * | \%M | Minute of the hour | 00 to 59 | * | \%S | Second of the minute | 00 to 59.999999999 | * | \%OH | same as %H but without sign | 00 to 23 | * | \%OI | same as %I but without sign | 00 to 11 | * | \%OM | same as %M but without sign | 00 to 59 | * | \%OS | same as %S but without sign | 00 to 59 | * | \%p | AM/PM designations associated with a 12-hour clock | 'AM' or 'PM' | * | \%R | Equivalent to "%H:%M" | | * | \%T | Equivalent to "%H:%M:%S" | | * | \%r | Equivalent to "%OI:%OM:%OS %p" | | * * No checking is done for invalid formats or invalid duration values. Formatting sticks to * specifications of `std::formatter<std::chrono::duration>` as much as possible. * * Any null input entry will result in a corresponding null entry in the output column. * * The time units of the input column influence the number of digits in decimal of seconds. * It uses 3 digits for milliseconds, 6 digits for microseconds and 9 digits for nanoseconds. * If duration value is negative, only one negative sign is written to output string. The specifiers * with signs are "%H,%I,%M,%S,%R,%T". * * @throw cudf::logic_error if `durations` column parameter is not a duration type. * * @param durations Duration values to convert * @param format The string specifying output format. * Default format is ""%D days %H:%M:%S". * @param mr Device memory resource used to allocate the returned column's device memory * @param stream CUDA stream used for device memory operations and kernel launches * @return New strings column with formatted durations */ std::unique_ptr<column> from_durations( column_view const& durations, std::string_view format = "%D days %H:%M:%S", rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_fixed_point.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new fixed-point column parsing decimal values from the * provided strings column. * * Any null entries result in corresponding null entries in the output column. * * The expected format is `[sign][integer][.][fraction]`, where the sign is either * not present, `-` or `+`, The decimal point `[.]` may or may not be present, and * `integer` and `fraction` are comprised of zero or more digits in [0-9]. * An invalid data format results in undefined behavior in the corresponding * output row result. * * @code{.pseudo} * Example: * s = ['123', '-876', '543.2', '-0.12'] * datatype = {DECIMAL32, scale=-2} * fp = to_fixed_point(s, datatype) * fp is [123400, -87600, 54320, -12] * @endcode * * Overflow of the resulting value type is not checked. * The scale in the `output_type` is used for setting the integer component. * * @throw cudf::logic_error if `output_type` is not a fixed-point decimal type. * * @param input Strings instance for this operation * @param output_type Type of fixed-point column to return including the scale value * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of `output_type` */ std::unique_ptr<column> to_fixed_point( strings_column_view const& input, data_type output_type, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting the fixed-point values * into a strings column. * * Any null entries result in corresponding null entries in the output column. * * For each value, a string is created in base-10 decimal. * Negative numbers include a '-' prefix in the output string. * The column's scale value is used to place the decimal point. * A negative scale value may add padded zeros after the decimal point. * * @code{.pseudo} * Example: * fp is [110, 222, 3330, -440, -1] with scale = -2 * s = from_fixed_point(fp) * s is now ['1.10', '2.22', '33.30', '-4.40', '-0.01'] * @endcode * * @throw cudf::logic_error if the `input` column is not a fixed-point decimal type. * * @param input Fixed-point column to convert * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> from_fixed_point( column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to fixed-point. * * The sign and the exponent is optional. The decimal point may only appear once. * Also, the integer component must fit within the size limits of the * underlying fixed-point storage type. The value of the integer component * is based on the scale of the `decimal_type` provided. * * @code{.pseudo} * Example: * s = ['123', '-456', '', '1.2.3', '+17E30', '12.34', '.789', '-0.005] * b = is_fixed_point(s) * b is [true, true, false, false, true, true, true, true] * @endcode * * Any null entries result in corresponding null entries in the output column. * * @throw cudf::logic_error if the `decimal_type` is not a fixed-point decimal type. * * @param input Strings instance for this operation * @param decimal_type Fixed-point type (with scale) used only for checking overflow * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_fixed_point( strings_column_view const& input, data_type decimal_type = data_type{type_id::DECIMAL64}, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_urls.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Decodes each string using URL encoding. * * Converts mostly non-ascii characters and control characters into UTF-8 hex code-points * prefixed with '%'. For example, the space character must be converted to characters '%20' where * the '20' indicates the hex value for space in UTF-8. Likewise, multi-byte characters are * converted to multiple hex characters. For example, the é character is converted to characters * '%C3%A9' where 'C3A9' is the UTF-8 bytes 0xC3A9 for this character. * * Any null entries will result in corresponding null entries in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> url_encode( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Encodes each string using URL encoding. * * Converts all character sequences starting with '%' into character code-points * interpreting the 2 following characters as hex values to create the code-point. * For example, the sequence '%20' is converted into byte (0x20) which is a single * space character. Another example converts '%C3%A9' into 2 sequential bytes * (0xc3 and 0xa9 respectively) which is the é character. Overall, 3 characters * are converted into one char byte whenever a '%%' (single percent) character * is encountered in the string. * * Any null entries will result in corresponding null entries in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> url_decode( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_lists.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Convert a list column of strings into a formatted strings column. * * The `separators` column should contain 3 strings elements in the following order: * - element separator (default is comma `,`) * - left-hand enclosure (default is `[`) * - right-hand enclosure (default is `]`) * * @code{.pseudo} * l1 = { [[a,b,c], [d,e]], [[f,g], [h]] } * s1 = format_list_column(l1) * s1 is now ["[[a,b,c],[d,e]]", "[[f,g],[h]]"] * * l2 = { [[a,b,c], [d,e]], [NULL], [[f,g], NULL, [h]] } * s2 = format_list_column(l1, '-', [':', '{', '}']) * s2 is now ["{{a:b:c}:{d:e}}", "{-}", "{{f:g}:-:{h}}"] * @endcode * * @throw cudf::logic_error if the input column is not a LIST type with a STRING child. * * @param input Lists column to format * @param na_rep Replacement string for null elements * @param separators Strings to use for enclosing list components and separating elements * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> format_list_column( lists_column_view const& input, string_scalar const& na_rep = string_scalar(""), strings_column_view const& separators = strings_column_view(column_view{ data_type{type_id::STRING}, 0, nullptr, nullptr, 0}), rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_integers.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new integer numeric column parsing integer values from the * provided strings column. * * Any null entries will result in corresponding null entries in the output column. * * Only characters [0-9] plus a prefix '-' and '+' are recognized. * When any other character is encountered, the parsing ends for that string * and the current digits are converted into an integer. * * Overflow of the resulting integer type is not checked. * Each string is converted using an int64 type and then cast to the * target integer type before storing it into the output column. * If the resulting integer type is too small to hold the value, * the stored value will be undefined. * * @throw cudf::logic_error if output_type is not integral type. * * @param input Strings instance for this operation * @param output_type Type of integer numeric column to return * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with integers converted from strings */ std::unique_ptr<column> to_integers( strings_column_view const& input, data_type output_type, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting the integer values from the * provided column into strings. * * Any null entries will result in corresponding null entries in the output column. * * For each integer, a string is created in base-10 decimal. * Negative numbers will include a '-' prefix. * * @throw cudf::logic_error if integers column is not integral type. * * @param integers Numeric column to convert * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column with integers as strings */ std::unique_ptr<column> from_integers( column_view const& integers, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to integers. * * The output row entry will be set to `true` if the corresponding string element * have all characters in [-+0-9]. The optional sign character must only be in the first * position. Notice that the integer value is not checked to be within its storage limits. * For strict integer type check, use the other `is_integer()` API which accepts `data_type` * argument. * * @code{.pseudo} * Example: * s = ['123', '-456', '', 'A', '+7'] * b = s.is_integer(s) * b is [true, true, false, false, true] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_integer( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to integers. * * The output row entry will be set to `true` if the corresponding string element * has all characters in [-+0-9]. The optional sign character must only be in the first * position. Also, the integer component must fit within the size limits of the underlying * storage type, which is provided by the int_type parameter. * * @code{.pseudo} * Example: * s = ['123456', '-456', '', 'A', '+7'] * * output1 = s.is_integer(s, data_type{type_id::INT32}) * output1 is [true, true, false, false, true] * * output2 = s.is_integer(s, data_type{type_id::INT8}) * output2 is [false, false, false, false, true] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param int_type Integer type used for checking underflow and overflow * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_integer( strings_column_view const& input, data_type int_type, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new integer numeric column parsing hexadecimal values from the * provided strings column. * * Any null entries will result in corresponding null entries in the output column. * * Only characters [0-9] and [A-F] are recognized. * When any other character is encountered, the parsing ends for that string. * No interpretation is made on the sign of the integer. * * Overflow of the resulting integer type is not checked. * Each string is converted using an int64 type and then cast to the * target integer type before storing it into the output column. * If the resulting integer type is too small to hold the value, * the stored value will be undefined. * * @throw cudf::logic_error if output_type is not integral type. * * @param input Strings instance for this operation * @param output_type Type of integer numeric column to return * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with integers converted from strings */ std::unique_ptr<column> hex_to_integers( strings_column_view const& input, data_type output_type, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to integers from hex. * * The output row entry will be set to `true` if the corresponding string element * has at least one character in [0-9A-Za-z]. Also, the string may start * with '0x'. * * @code{.pseudo} * Example: * s = ['123', '-456', '', 'AGE', '+17EA', '0x9EF' '123ABC'] * b = is_hex(s) * b is [true, false, false, false, false, true, true] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_hex( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting integer columns to hexadecimal * characters. * * Any null entries will result in corresponding null entries in the output column. * * The output character set is '0'-'9' and 'A'-'F'. The output string width will * be a multiple of 2 depending on the size of the integer type. A single leading * zero is applied to the first non-zero output byte if it less than 0x10. * * @code{.pseudo} * Example: * input = [1234, -1, 0, 27, 342718233] // int32 type input column * s = integers_to_hex(input) * s is [ '04D2', 'FFFFFFFF', '00', '1B', '146D7719'] * @endcode * * The example above shows an `INT32` type column where each integer is 4 bytes. * Leading zeros are suppressed unless filling out a complete byte as in * `1234 -> '04D2'` instead of `000004D2` or `4D2`. * * @throw cudf::logic_error if the input column is not integral type. * * @param input Integer column to convert to hex * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column with hexadecimal characters */ std::unique_ptr<column> integers_to_hex( column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_ipv4.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Converts IPv4 addresses into integers. * * The IPv4 format is 1-3 character digits [0-9] between 3 dots * (e.g. 123.45.67.890). Each section can have a value between [0-255]. * * The four sets of digits are converted to integers and placed in 8-bit fields inside * the resulting integer. * ``` * i0.i1.i2.i3 -> (i0 << 24) | (i1 << 16) | (i2 << 8) | (i3) * ``` * * No checking is done on the format. If a string is not in IPv4 format, the resulting * integer is undefined. * * The resulting 32-bit integer is placed in an int64_t to avoid setting the sign-bit * in an int32_t type. This could be changed if cudf supported a UINT32 type in the future. * * Any null entries will result in corresponding null entries in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New INT64 column converted from strings */ std::unique_ptr<column> ipv4_to_integers( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Converts integers into IPv4 addresses as strings. * * The IPv4 format is 1-3 character digits [0-9] between 3 dots * (e.g. 123.45.67.890). Each section can have a value between [0-255]. * * Each input integer is dissected into four integers by dividing the input into 8-bit sections. * These sub-integers are then converted into [0-9] characters and placed between '.' characters. * * No checking is done on the input integer value. Only the lower 32-bits are used. * * Any null entries will result in corresponding null entries in the output column. * * @throw cudf::logic_error if the input column is not INT64 type. * * @param integers Integer (INT64) column to convert * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column */ std::unique_ptr<column> integers_to_ipv4( column_view const& integers, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a boolean column identifying strings in which all * characters are valid for conversion to integers from IPv4 format. * * The output row entry will be set to `true` if the corresponding string element * has the following format `xxx.xxx.xxx.xxx` where `xxx` is integer digits * between 0-255. * * @code{.pseudo} * Example: * s = ['123.255.0.7', '127.0.0.1', '', '1.2.34' '123.456.789.10'] * b = s.is_ipv4(s) * b is [true, true, false, false, true] * @endcode * * Any null row results in a null entry for that row in the output column. * * @param input Strings instance for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column of boolean results for each string */ std::unique_ptr<column> is_ipv4( strings_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/strings
rapidsai_public_repos/cudf/cpp/include/cudf/strings/convert/convert_datetime.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <string> #include <vector> namespace cudf { namespace strings { /** * @addtogroup strings_convert * @{ * @file */ /** * @brief Returns a new timestamp column converting a strings column into * timestamps using the provided format pattern. * * The format pattern can include the following specifiers: "%Y,%y,%m,%d,%H,%I,%p,%M,%S,%f,%z" * * | Specifier | Description | * | :-------: | ----------- | * | \%d | Day of the month: 01-31 | * | \%m | Month of the year: 01-12 | * | \%y | Year without century: 00-99. [0,68] maps to [2000,2068] and [69,99] maps to [1969,1999] | * | \%Y | Year with century: 0001-9999 | * | \%H | 24-hour of the day: 00-23 | * | \%I | 12-hour of the day: 01-12 | * | \%M | Minute of the hour: 00-59 | * | \%S | Second of the minute: 00-59. Leap second is not supported. | * | \%f | 6-digit microsecond: 000000-999999 | * | \%z | UTC offset with format ±HHMM Example +0500 | * | \%j | Day of the year: 001-366 | * | \%p | Only 'AM', 'PM' or 'am', 'pm' are recognized | * | \%W | Week of the year with Monday as the first day of the week: 00-53 | * | \%w | Day of week: 0-6 = Sunday-Saturday | * | \%U | Week of the year with Sunday as the first day of the week: 00-53 | * | \%u | Day of week: 1-7 = Monday-Sunday | * * Other specifiers are not currently supported. * * Invalid formats are not checked. If the string contains unexpected * or insufficient characters, that output row entry's timestamp value is undefined. * * Any null string entry will result in a corresponding null row in the output column. * * The resulting time units are specified by the `timestamp_type` parameter. * The time units are independent of the number of digits parsed by the "%f" specifier. * The "%f" supports a precision value to read the numeric digits. Specify the * precision with a single integer value (1-9) as follows: * use "%3f" for milliseconds, "%6f" for microseconds and "%9f" for nanoseconds. * * Although leap second is not supported for "%S", no checking is performed on the value. * The cudf::strings::is_timestamp can be used to verify the valid range of values. * * If "%W"/"%w" (or "%U/%u") and "%m"/"%d" are both specified, the "%W"/%U and "%w"/%u values * take precedent when computing the date part of the timestamp result. * * @throw cudf::logic_error if timestamp_type is not a timestamp type. * * @param input Strings instance for this operation * @param timestamp_type The timestamp type used for creating the output column * @param format String specifying the timestamp format in strings * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New datetime column */ std::unique_ptr<column> to_timestamps( strings_column_view const& input, data_type timestamp_type, std::string_view format, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Verifies the given strings column can be parsed to timestamps using the provided format * pattern. * * The format pattern can include the following specifiers: "%Y,%y,%m,%d,%H,%I,%p,%M,%S,%f,%z" * * | Specifier | Description | * | :-------: | ----------- | * | \%d | Day of the month: 01-31 | * | \%m | Month of the year: 01-12 | * | \%y | Year without century: 00-99. [0,68] maps to [2000,2068] and [69,99] maps to [1969,1999] | * | \%Y | Year with century: 0001-9999 | * | \%H | 24-hour of the day: 00-23 | * | \%I | 12-hour of the day: 01-12 | * | \%M | Minute of the hour: 00-59| * | \%S | Second of the minute: 00-59. Leap second is not supported. | * | \%f | 6-digit microsecond: 000000-999999 | * | \%z | UTC offset with format ±HHMM Example +0500 | * | \%j | Day of the year: 001-366 | * | \%p | Only 'AM', 'PM' or 'am', 'pm' are recognized | * | \%W | Week of the year with Monday as the first day of the week: 00-53 | * | \%w | Day of week: 0-6 = Sunday-Saturday | * | \%U | Week of the year with Sunday as the first day of the week: 00-53 | * | \%u | Day of week: 1-7 = Monday-Sunday | * * Other specifiers are not currently supported. * The "%f" supports a precision value to read the numeric digits. Specify the * precision with a single integer value (1-9) as follows: * use "%3f" for milliseconds, "%6f" for microseconds and "%9f" for nanoseconds. * * Any null string entry will result in a corresponding null row in the output column. * * This will return a column of type BOOL8 where a `true` row indicates the corresponding * input string can be parsed correctly with the given format. * * @param input Strings instance for this operation * @param format String specifying the timestamp format in strings * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New BOOL8 column */ std::unique_ptr<column> is_timestamp( strings_column_view const& input, std::string_view format, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Returns a new strings column converting a timestamp column into * strings using the provided format pattern. * * The format pattern can include the following specifiers: "%Y,%y,%m,%d,%H,%I,%p,%M,%S,%f,%z,%Z" * * | Specifier | Description | * | :-------: | ----------- | * | \%d | Day of the month: 01-31 | * | \%m | Month of the year: 01-12 | * | \%y | Year without century: 00-99 | * | \%Y | Year with century: 0001-9999 | * | \%H | 24-hour of the day: 00-23 | * | \%I | 12-hour of the day: 01-12 | * | \%M | Minute of the hour: 00-59| * | \%S | Second of the minute: 00-59 | * | \%f | 6-digit microsecond: 000000-999999 | * | \%z | Always outputs "+0000" | * | \%Z | Always outputs "UTC" | * | \%j | Day of the year: 001-366 | * | \%u | ISO weekday where Monday is 1 and Sunday is 7 | * | \%w | Weekday where Sunday is 0 and Saturday is 6 | * | \%U | Week of the year with Sunday as the first day: 00-53 | * | \%W | Week of the year with Monday as the first day: 00-53 | * | \%V | Week of the year per ISO-8601 format: 01-53 | * | \%G | Year based on the ISO-8601 weeks: 0000-9999 | * | \%p | AM/PM from `timestamp_names::am_str/pm_str` | * | \%a | Weekday abbreviation from the `names` parameter | * | \%A | Weekday from the `names` parameter | * | \%b | Month name abbreviation from the `names` parameter | * | \%B | Month name from the `names` parameter | * * Additional descriptions can be found here: * https://en.cppreference.com/w/cpp/chrono/system_clock/formatter * * No checking is done for invalid formats or invalid timestamp values. * All timestamps values are formatted to UTC. * * Any null input entry will result in a corresponding null entry in the output column. * * The time units of the input column do not influence the number of digits written by * the "%f" specifier. The "%f" supports a precision value to write out numeric digits * for the subsecond value. Specify the precision with a single integer value (1-9) * between the "%" and the "f" as follows: use "%3f" for milliseconds, use "%6f" for * microseconds and use "%9f" for nanoseconds. If the precision is higher than the * units, then zeroes are padded to the right of the subsecond value. If the precision * is lower than the units, the subsecond value may be truncated. * * If the "%a", "%A", "%b", "%B" specifiers are included in the format, the caller * should provide the format names in the `names` strings column using the following * as a guide: * * @code{.pseudo} * ["AM", "PM", // specify the AM/PM strings * "Sunday", "Monday", ..., "Saturday", // Weekday full names * "Sun", "Mon", ..., "Sat", // Weekday abbreviated names * "January", "February", ..., "December", // Month full names * "Jan", "Feb", ..., "Dec"] // Month abbreviated names * @endcode * * The result is undefined if the format names are not provided for these specifiers. * * These format names can be retrieved for specific locales using the `nl_langinfo` * functions from C++ `clocale` (std) library or the Python `locale` library. * * The following code is an example of retrieving these strings from the locale * using c++ std functions: * * @code{.cpp} * #include <clocale> * #include <langinfo.h> * * // note: install language pack on Ubuntu using 'apt-get install language-pack-de' * { * // set to a German language locale for date settings * std::setlocale(LC_TIME, "de_DE.UTF-8"); * * std::vector<std::string> names({nl_langinfo(AM_STR), nl_langinfo(PM_STR), * nl_langinfo(DAY_1), nl_langinfo(DAY_2), nl_langinfo(DAY_3), nl_langinfo(DAY_4), * nl_langinfo(DAY_5), nl_langinfo(DAY_6), nl_langinfo(DAY_7), * nl_langinfo(ABDAY_1), nl_langinfo(ABDAY_2), nl_langinfo(ABDAY_3), nl_langinfo(ABDAY_4), * nl_langinfo(ABDAY_5), nl_langinfo(ABDAY_6), nl_langinfo(ABDAY_7), * nl_langinfo(MON_1), nl_langinfo(MON_2), nl_langinfo(MON_3), nl_langinfo(MON_4), * nl_langinfo(MON_5), nl_langinfo(MON_6), nl_langinfo(MON_7), nl_langinfo(MON_8), * nl_langinfo(MON_9), nl_langinfo(MON_10), nl_langinfo(MON_11), nl_langinfo(MON_12), * nl_langinfo(ABMON_1), nl_langinfo(ABMON_2), nl_langinfo(ABMON_3), nl_langinfo(ABMON_4), * nl_langinfo(ABMON_5), nl_langinfo(ABMON_6), nl_langinfo(ABMON_7), nl_langinfo(ABMON_8), * nl_langinfo(ABMON_9), nl_langinfo(ABMON_10), nl_langinfo(ABMON_11), nl_langinfo(ABMON_12)}); * * std::setlocale(LC_TIME,""); // reset to default locale * } * @endcode * * @throw cudf::logic_error if `timestamps` column parameter is not a timestamp type. * @throw cudf::logic_error if the `format` string is empty * @throw cudf::logic_error if `names.size()` is an invalid size. Must be 0 or 40 strings. * * @param timestamps Timestamp values to convert * @param format The string specifying output format. * Default format is "%Y-%m-%dT%H:%M:%SZ". * @param names The string names to use for weekdays ("%a", "%A") and months ("%b", "%B") * Default is an empty `strings_column_view`. * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New strings column with formatted timestamps */ std::unique_ptr<column> from_timestamps( column_view const& timestamps, std::string_view format = "%Y-%m-%dT%H:%M:%SZ", strings_column_view const& names = strings_column_view(column_view{ data_type{type_id::STRING}, 0, nullptr, nullptr, 0}), rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/dictionary_factories.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { /** * @addtogroup column_factories Factories * @{ * @file */ /** * @brief Construct a dictionary column by copying the provided `keys` * and `indices`. * * It is expected that `keys_column.has_nulls() == false`. * It is assumed the elements in `keys_column` are unique and * are in a strict, total order. Meaning, `keys_column[i]` is ordered before * `keys_column[i+1]` for all `i in [0,n-1)` where `n` is the number of keys. * * The indices values must be in the range [0,keys_column.size()). * * The null_mask and null count for the output column are copied from the indices column. * If element `i` in `indices_column` is null, then element `i` in the returned dictionary column * will also be null. * * ``` * k = ["a","c","d"] * i = [1,0,null,2,2] * d = make_dictionary_column(k,i) * d is now {["a","c","d"],[1,0,undefined,2,2]} bitmask={1,1,0,1,1} * ``` * * The null_mask and null count for the output column are copied from the indices column. * * @throw cudf::logic_error if keys_column contains nulls * @throw cudf::logic_error if indices_column type is not INT32 * * @param keys_column Column of unique, ordered values to use as the new dictionary column's keys. * @param indices_column Indices to use for the new dictionary column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> make_dictionary_column( column_view const& keys_column, column_view const& indices_column, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Construct a dictionary column by taking ownership of the provided keys * and indices columns. * * The keys_column and indices columns must contain no nulls. * It is assumed the elements in `keys_column` are unique and * are in a strict, total order. Meaning, `keys_column[i]` is ordered before * `keys_column[i+1]` for all `i in [0,n-1)` where `n` is the number of keys. * * The indices values must be in the range [0,keys_column.size()). * * @throw cudf::logic_error if keys_column or indices_column contains nulls * @throw cudf::logic_error if indices_column type is not an unsigned integer type * * @param keys_column Column of unique, ordered values to use as the new dictionary column's keys. * @param indices_column Indices to use for the new dictionary column. * @param null_mask Null mask for the output column. * @param null_count Number of nulls for the output column. * @return New dictionary column. */ std::unique_ptr<column> make_dictionary_column(std::unique_ptr<column> keys_column, std::unique_ptr<column> indices_column, rmm::device_buffer&& null_mask, size_type null_count); /** * @brief Construct a dictionary column by taking ownership of the provided keys * and indices columns. * * The `keys_column` must contain no nulls and is assumed to have elements * that are unique and are in a strict, total order. Meaning, `keys_column[i]` * is ordered before `keys_column[i+1]` for all `i in [0,n-1)` where `n` is the * number of keys. * * The `indices_column` can be any integer type and should contain the null-mask * to be used for the output column. * The indices values must be in the range [0,keys_column.size()). * * @throw cudf::logic_error if keys_column contains nulls * * @param keys_column Column of unique, ordered values to use as the new dictionary column's keys. * @param indices_column Indices values and null-mask to use for the new dictionary column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> make_dictionary_column( std::unique_ptr<column> keys_column, std::unique_ptr<column> indices_column, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/update_keys.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/utilities/span.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace dictionary { /** * @addtogroup dictionary_update * @{ * @file */ /** * @brief Create a new dictionary column by adding the new keys elements * to the existing dictionary_column. * * The indices are updated if any of the new keys are sorted * before any of the existing dictionary elements. * * @code{.pseudo} * d1 = { keys=["a", "c", "d"], indices=[2, 0, 1, 0, 1]} * d2 = add_keys( d1, ["b", "c"] ) * d2 is now {keys=["a", "b", "c", "d"], indices=[3, 0, 2, 0, 2]} * @endcode * * The output column will have the same number of rows as the input column. * Null entries from the input column are copied to the output column. * No new null entries are created by this operation. * * @throw cudf_logic_error if the new_keys type does not match the keys type in * the dictionary_column. * @throw cudf_logic_error if the new_keys contain nulls. * * @param dictionary_column Existing dictionary column. * @param new_keys New keys to incorporate into the dictionary_column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> add_keys( dictionary_column_view const& dictionary_column, column_view const& new_keys, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a new dictionary column by removing the specified keys * from the existing dictionary_column. * * The output column will have the same number of rows as the input column. * Null entries from the input column and copied to the output column. * The indices are updated to the new positions of the remaining keys. * Any indices pointing to removed keys sets that row to null. * * @code{.pseudo} * d1 = {keys=["a", "c", "d"], indices=[2, 0, 1, 0, 2]} * d2 = remove_keys( d1, ["b", "c"] ) * d2 is now {keys=["a", "d"], indices=[1, 0, x, 0, 1], valids=[1, 1, 0, 1, 1]} * @endcode * Note that "a" has been removed so output row[2] becomes null. * * @throw cudf_logic_error if the keys_to_remove type does not match the keys type in * the dictionary_column. * @throw cudf_logic_error if the keys_to_remove contain nulls. * * @param dictionary_column Existing dictionary column. * @param keys_to_remove The keys to remove from the dictionary_column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> remove_keys( dictionary_column_view const& dictionary_column, column_view const& keys_to_remove, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a new dictionary column by removing any keys * that are not referenced by any of the indices. * * The indices are updated to the new position values of the remaining keys. * * @code{.pseudo} * d1 = {["a","c","d"],[2,0,2,0]} * d2 = remove_unused_keys(d1) * d2 is now {["a","d"],[1,0,1,0]} * @endcode * * @param dictionary_column Existing dictionary column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> remove_unused_keys( dictionary_column_view const& dictionary_column, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a new dictionary column by applying only the specified keys * to the existing dictionary_column. * * Any new elements found in the keys parameter are added to the output dictionary. * Any existing keys not in the keys parameter are removed. * * The number of rows in the output column will be the same as the number of rows * in the input column. Existing null entries are copied to the output column. * The indices are updated to reflect the position values of the new keys. * Any indices pointing to removed keys sets those rows to null. * * @code{.pseudo} * d1 = {keys=["a", "b", "c"], indices=[2, 0, 1, 2, 1]} * d2 = set_keys(existing_dict, ["b","c","d"]) * d2 is now {keys=["b", "c", "d"], indices=[1, x, 0, 1, 0], valids=[1, 0, 1, 1, 1]} * @endcode * * @throw cudf_logic_error if the keys type does not match the keys type in * the dictionary_column. * @throw cudf_logic_error if the keys contain nulls. * * @param dictionary_column Existing dictionary column. * @param keys New keys to use for the output column. Must not contain nulls. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> set_keys( dictionary_column_view const& dictionary_column, column_view const& keys, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create new dictionaries that have keys merged from the input dictionaries. * * This will concatenate the keys for each dictionary and then call `set_keys` on each. * The result is a vector of new dictionaries with a common set of keys. * * @param input Dictionary columns to match keys. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary columns. */ std::vector<std::unique_ptr<column>> match_dictionaries( cudf::host_span<dictionary_column_view const> input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/search.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. */ #pragma once #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace dictionary { /** * @addtogroup dictionary_search * @{ * @file */ /** * @brief Return the index value for a given key. * * If the key does not exist in the dictionary the returned scalar will have `is_valid()==false` * * @throw cudf::logic_error if `key.type() != dictionary.keys().type()` * * @param dictionary The dictionary to search for the key. * @param key The value to search for in the dictionary keyset. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned scalar's device memory. * @return Numeric scalar index value of the key within the dictionary. */ std::unique_ptr<scalar> get_index( dictionary_column_view const& dictionary, scalar const& key, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/encode.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace dictionary { /** * @addtogroup dictionary_encode * @{ * @file * @brief Dictionary column encode and decode APIs */ /** * @brief Construct a dictionary column by dictionary encoding an existing column * * The output column is a DICTIONARY type with a keys column of non-null, unique values * that are in a strict, total order. Meaning, `keys[i]` is _ordered before * `keys[i+1]` for all `i in [0,n-1)` where `n` is the number of keys. * The output column has a child indices column that is of integer type and with * the same size as the input column. * * The null mask and null count are copied from the input column to the output column. * * @throw cudf::logic_error if indices type is not an unsigned integer type * @throw cudf::logic_error if the column to encode is already a DICTIONARY type * * @code{.pseudo} * c = [429, 111, 213, 111, 213, 429, 213] * d = encode(c) * d now has keys [111, 213, 429] and indices [2, 0, 1, 0, 1, 2, 1] * @endcode * * @param column The column to dictionary encode * @param indices_type The integer type to use for the indices * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return Returns a dictionary column */ std::unique_ptr<column> encode( column_view const& column, data_type indices_type = data_type{type_id::UINT32}, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a column by gathering the keys from the provided * dictionary_column into a new column using the indices from that column. * * @code{.pseudo} * d1 = {["a", "c", "d"], [2, 0, 1, 0]} * s = decode(d1) * s is now ["d", "a", "c", "a"] * @endcode * * @param dictionary_column Existing dictionary column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with type matching the dictionary_column's keys */ std::unique_ptr<column> decode( dictionary_column_view const& dictionary_column, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/dictionary_column_view.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> /** * @file * @brief Class definition for cudf::dictionary_column_view */ namespace cudf { /** * @addtogroup dictionary_classes * @{ */ /** * @brief A wrapper class for operations on a dictionary column. * * A dictionary column contains a set of keys and a column of indices. * The keys are a sorted set of unique values for the column. * The indices represent the corresponding positions of each element's * value in the keys. */ class dictionary_column_view : private column_view { public: /** * @brief Construct a new dictionary column view object from a column view. * * @param dictionary_column The column view to wrap */ dictionary_column_view(column_view const& dictionary_column); dictionary_column_view(dictionary_column_view&&) = default; ///< Move constructor dictionary_column_view(dictionary_column_view const&) = default; ///< Copy constructor ~dictionary_column_view() = default; /** * @brief Move assignment operator * * @return The reference to this dictionary column */ dictionary_column_view& operator=(dictionary_column_view const&) = default; /** * @brief Copy assignment operator * * @return The reference to this dictionary column */ dictionary_column_view& operator=(dictionary_column_view&&) = default; /// Index of the indices column of the dictionary column static constexpr size_type indices_column_index{0}; /// Index of the keys column of the dictionary column static constexpr size_type keys_column_index{1}; using column_view::has_nulls; using column_view::is_empty; using column_view::null_count; using column_view::null_mask; using column_view::offset; using column_view::size; /** * @brief Returns the parent column. * * @return The parent column */ [[nodiscard]] column_view parent() const noexcept; /** * @brief Returns the column of indices * * @return The indices column */ [[nodiscard]] column_view indices() const noexcept; /** * @brief Returns a column_view combining the indices data * with offset, size, and nulls from the parent. * * @return A sliced indices column view with nulls from the parent */ [[nodiscard]] column_view get_indices_annotated() const noexcept; /** * @brief Returns the column of keys * * @return The keys column */ [[nodiscard]] column_view keys() const noexcept; /** * @brief Returns the cudf::data_type of the keys child column. * * @return The cudf::data_type of the keys child column */ [[nodiscard]] data_type keys_type() const noexcept; /** * @brief Returns the number of rows in the keys column. * * @return The number of rows in the keys column */ [[nodiscard]] size_type keys_size() const noexcept; }; /** @} */ // end of group //! Dictionary column APIs. namespace dictionary { // defined here for doxygen output } } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/iterator.cuh
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column_device_view.cuh> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/dictionary_column_view.hpp> #include <thrust/pair.h> namespace cudf { namespace dictionary { namespace detail { /** * @brief Accessor functor for returning a dictionary key element in a dictionary iterator. * * @tparam KeyType The type of the dictionary's key element. */ template <typename KeyType> struct dictionary_access_fn { dictionary_access_fn(column_device_view const& d_dictionary) : d_dictionary{d_dictionary} {} __device__ KeyType operator()(size_type idx) const { if (d_dictionary.is_null(idx)) return KeyType{}; auto keys = d_dictionary.child(dictionary_column_view::keys_column_index); return keys.element<KeyType>(static_cast<size_type>(d_dictionary.element<dictionary32>(idx))); }; private: column_device_view const d_dictionary; }; /** * @brief Create dictionary iterator that produces key elements. * * The iterator returns `keys[indices[i]]` where the `keys` are the dictionary's key * elements and the `indices` are the dictionary's index elements. * * @throw cudf::logic_error if `dictionary_column` is not a dictionary column. * * @tparam KeyType The type of the dictionary's key element. * @param dictionary_column The dictionary device view to iterate. * @return Iterator */ template <typename KeyType> auto make_dictionary_iterator(column_device_view const& dictionary_column) { CUDF_EXPECTS(is_dictionary(dictionary_column.type()), "Dictionary iterator is only for dictionary columns"); return cudf::detail::make_counting_transform_iterator( size_type{0}, dictionary_access_fn<KeyType>{dictionary_column}); } /** * @brief Accessor functor for returning a dictionary pair iterator. * * @tparam KeyType The type of the dictionary's key element. * * @throw cudf::logic_error if `has_nulls==true` and `d_dictionary` is not nullable. */ template <typename KeyType> struct dictionary_access_pair_fn { dictionary_access_pair_fn(column_device_view const& d_dictionary, bool has_nulls = true) : d_dictionary{d_dictionary}, has_nulls{has_nulls} { if (has_nulls) { CUDF_EXPECTS(d_dictionary.nullable(), "unexpected non-nullable column"); } } __device__ thrust::pair<KeyType, bool> operator()(size_type idx) const { if (has_nulls && d_dictionary.is_null(idx)) return {KeyType{}, false}; auto keys = d_dictionary.child(dictionary_column_view::keys_column_index); return {keys.element<KeyType>(static_cast<size_type>(d_dictionary.element<dictionary32>(idx))), true}; }; private: column_device_view const d_dictionary; bool has_nulls; }; /** * @brief Create dictionary iterator that produces key and valid element pair. * * The iterator returns a pair where the `first` value is * `dictionary_column.keys[dictionary_column.indices[i]]` * The `second` pair member is a `bool` which is set to * `dictionary_column.is_valid(i)`. * * @throw cudf::logic_error if `dictionary_column` is not a dictionary column. * * @tparam KeyType The type of the dictionary's key element. * * @param dictionary_column The dictionary device view to iterate. * @param has_nulls Set to `true` if the `dictionary_column` has nulls. * @return Pair iterator with `{value,valid}` */ template <typename KeyType> auto make_dictionary_pair_iterator(column_device_view const& dictionary_column, bool has_nulls = true) { CUDF_EXPECTS(is_dictionary(dictionary_column.type()), "Dictionary iterator is only for dictionary columns"); return cudf::detail::make_counting_transform_iterator( 0, dictionary_access_pair_fn<KeyType>{dictionary_column, has_nulls}); } } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/update_keys.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @copydoc cudf::dictionary::add_keys(dictionary_column_view const&,column_view * const&,mm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> add_keys(dictionary_column_view const& dictionary_column, column_view const& new_keys, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::dictionary::remove_keys(dictionary_column_view const&,column_view * const&,mm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> remove_keys(dictionary_column_view const& dictionary_column, column_view const& keys_to_remove, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::dictionary::remove_unused_keys(dictionary_column_view * const&,mm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> remove_unused_keys(dictionary_column_view const& dictionary_column, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::dictionary::set_keys(dictionary_column_view * const&,mm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> set_keys(dictionary_column_view const& dictionary_column, column_view const& keys, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc * cudf::dictionary::match_dictionaries(std::vector<cudf::dictionary_column_view>,mm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::vector<std::unique_ptr<column>> match_dictionaries( cudf::host_span<dictionary_column_view const> input, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Create new dictionaries that have keys merged from dictionary columns * found in the provided tables. * * The result includes a vector of new dictionary columns along with a * vector of table_views with corresponding updated column_views. * And any column_views in the input tables that are not dictionary type * are simply copied. * * Merging the dictionary keys also adjusts the indices appropriately in the * output dictionary columns. * * Any null rows are left unchanged. * * @param input Vector of cudf::table_views that include dictionary columns to be matched. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary columns and updated cudf::table_views. */ std::pair<std::vector<std::unique_ptr<column>>, std::vector<table_view>> match_dictionaries( std::vector<table_view> tables, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/search.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @copydoc cudf::dictionary::get_index(dictionary_column_view const&,scalar * const&,rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<scalar> get_index(dictionary_column_view const& dictionary, scalar const& key, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Get the index for a key if it were added to the given dictionary. * * The actual index is returned if the `key` is already part of the dictionary's key set. * * @code{.pseudo} * d1 = {["a","c","d"],[2,0,1,0]} * idx = get_insert_index(d1,"b") * idx is 1 * @endcode{.pseudo} * * @throw cudf::logic_error if `key.type() != dictionary.keys().type()` * * @param dictionary The dictionary to search for the key. * @param key The value to search for in the dictionary keyset. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return Numeric scalar index value of the key within the dictionary */ std::unique_ptr<scalar> get_insert_index(dictionary_column_view const& dictionary, scalar const& key, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/merge.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/detail/merge.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @brief Merges two dictionary columns. * * The keys of both dictionary columns are expected to be already matched. * Otherwise, the result is undefined behavior. * * Caller must set the validity mask in the output column. * * @param lcol First column. * @param rcol Second column. * @param row_order Indexes for each column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column. */ std::unique_ptr<column> merge(dictionary_column_view const& lcol, dictionary_column_view const& rcol, cudf::detail::index_vector const& row_order, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/encode.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @brief Construct a dictionary column by dictionary encoding an existing column. * * The output column is a DICTIONARY type with a keys column of non-null, unique values * that are in a strict, total order. Meaning, `keys[i]` is ordered before * `keys[i+1]` for all `i in [0,n-1)` where `n` is the number of keys. * The output column has a child indices column that is of integer type and with * the same size as the input column. * * The null_mask and null count are copied from the input column to the output column. * * @throw cudf::logic_error if indices_type is not INT32 * * ``` * c = [429,111,213,111,213,429,213] * d = make_dictionary_column(c) * d now has keys [111,213,429] and indices [2,0,1,0,1,2,1] * ``` * * @param column The column to dictionary encode. * @param indices_type The integer type to use for the indices. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return Returns a dictionary column. */ std::unique_ptr<column> encode(column_view const& column, data_type indices_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Create a column by gathering the keys from the provided * dictionary_column into a new column using the indices from that column. * * ``` * d1 = {["a","c","d"],[2,0,1,0]} * s = decode(d1) * s is now ["d","a","c","a"] * ``` * * @param dictionary_column Existing dictionary column. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New column with type matching the dictionary_column's keys. */ std::unique_ptr<column> decode(dictionary_column_view const& dictionary_column, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Return minimal integer type for the given number of elements. * * @param keys_size Number of elements in the keys * @return Minimal type that can hold `keys_size` values */ data_type get_indices_type_for_size(size_type keys_size); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/concatenate.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @brief Returns a single column by vertically concatenating the given vector of * dictionary columns. * * @throw cudf::logic_error if `columns.size()==0` * @throw cudf::logic_error if dictionary column keys are not all the same type. * * @param columns Vector of dictionary columns to concatenate. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New column with concatenated results. */ std::unique_ptr<column> concatenate(host_span<column_view const> columns, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary
rapidsai_public_repos/cudf/cpp/include/cudf/dictionary/detail/replace.hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace dictionary { namespace detail { /** * @brief Create a new dictionary column by replacing nulls with values * from a second dictionary. * * @throw cudf::logic_error if the keys type of both dictionaries do not match. * @throw cudf::logic_error if the column sizes do not match. * * @param input Column with nulls to replace. * @param replacement Column with values to use for replacing. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column with null rows replaced. */ std::unique_ptr<column> replace_nulls(dictionary_column_view const& input, dictionary_column_view const& replacement, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Create a new dictionary column by replacing nulls with a * specified scalar. * * @throw cudf::logic_error if the keys type does not match the replacement type. * * @param input Column with nulls to replace. * @param replacement Value to use for replacing. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New dictionary column with null rows replaced. */ std::unique_ptr<column> replace_nulls(dictionary_column_view const& input, scalar const& replacement, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace dictionary } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/hashing.hpp
/* * 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. */ #pragma once #include <cudf/hashing.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <cstddef> #include <functional> namespace cudf { namespace hashing { namespace detail { std::unique_ptr<column> murmurhash3_x86_32(table_view const& input, uint32_t seed, rmm::cuda_stream_view, rmm::mr::device_memory_resource* mr); std::unique_ptr<table> murmurhash3_x64_128(table_view const& input, uint64_t seed, rmm::cuda_stream_view, rmm::mr::device_memory_resource* mr); std::unique_ptr<column> spark_murmurhash3_x86_32(table_view const& input, uint32_t seed, rmm::cuda_stream_view, rmm::mr::device_memory_resource* mr); std::unique_ptr<column> md5(table_view const& input, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); std::unique_ptr<column> xxhash_64(table_view const& input, uint64_t seed, rmm::cuda_stream_view, rmm::mr::device_memory_resource* mr); /* Copyright 2005-2014 Daniel James. * * Use, modification and distribution is subject to the Boost Software * License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /** * @brief Combines two hash values into a single hash value. * * Taken from the Boost hash_combine function. * https://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html * * @param lhs The first hash value * @param rhs The second hash value * @return Combined hash value */ constexpr uint32_t hash_combine(uint32_t lhs, uint32_t rhs) { return lhs ^ (rhs + 0x9e37'79b9 + (lhs << 6) + (lhs >> 2)); } /* Copyright 2005-2014 Daniel James. * * Use, modification and distribution is subject to the Boost Software * License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /** * @brief Combines two hash values into a single hash value. * * Adapted from Boost hash_combine function and modified for 64-bit. * https://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html * * @param lhs The first hash value * @param rhs The second hash value * @return Combined hash value */ constexpr std::size_t hash_combine(std::size_t lhs, std::size_t rhs) { return lhs ^ (rhs + 0x9e37'79b9'7f4a'7c15 + (lhs << 6) + (lhs >> 2)); } } // namespace detail } // namespace hashing } // namespace cudf // specialization of std::hash for cudf::data_type namespace std { template <> struct hash<cudf::data_type> { std::size_t operator()(cudf::data_type const& type) const noexcept { return cudf::hashing::detail::hash_combine( std::hash<int32_t>{}(static_cast<int32_t>(type.id())), std::hash<int32_t>{}(type.scale())); } }; } // namespace std
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/hash_functions.cuh
/* * Copyright (c) 2017-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/utilities/traits.hpp> #include <limits> namespace cudf::hashing::detail { /** * Normalization of floating point NaNs, passthrough for all other values. */ template <typename T> T __device__ inline normalize_nans(T const& key) { if constexpr (cudf::is_floating_point<T>()) { if (std::isnan(key)) { return std::numeric_limits<T>::quiet_NaN(); } } return key; } /** * Normalization of floating point NaNs and zeros, passthrough for all other values. */ template <typename T> T __device__ inline normalize_nans_and_zeros(T const& key) { if constexpr (cudf::is_floating_point<T>()) { if (key == T{0.0}) { return T{0.0}; } } return normalize_nans(key); } __device__ inline uint32_t rotate_bits_left(uint32_t x, uint32_t r) { // This function is equivalent to (x << r) | (x >> (32 - r)) return __funnelshift_l(x, x, r); } __device__ inline uint64_t rotate_bits_left(uint64_t x, uint32_t r) { return (x << r) | (x >> (64 - r)); } __device__ inline uint32_t rotate_bits_right(uint32_t x, uint32_t r) { // This function is equivalent to (x >> r) | (x << (32 - r)) return __funnelshift_r(x, x, r); } __device__ inline uint64_t rotate_bits_right(uint64_t x, uint32_t r) { return (x >> r) | (x << (64 - r)); } } // namespace cudf::hashing::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/murmurhash3_x86_32.cuh
/* * Copyright (c) 2017-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/fixed_point/fixed_point.hpp> #include <cudf/hashing.hpp> #include <cudf/hashing/detail/hash_functions.cuh> #include <cudf/lists/list_view.hpp> #include <cudf/strings/string_view.cuh> #include <cudf/structs/struct_view.hpp> #include <cudf/types.hpp> #include <cstddef> namespace cudf::hashing::detail { // MurmurHash3_x86_32 implementation from // https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp //----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. // Note - The x86 and x64 versions do _not_ produce the same results, as the // algorithms are optimized for their respective platforms. You can still // compile and run any of them on any platform, but your performance with the // non-native version will be less than optimal. template <typename Key> struct MurmurHash3_x86_32 { using result_type = hash_value_type; constexpr MurmurHash3_x86_32() = default; constexpr MurmurHash3_x86_32(uint32_t seed) : m_seed(seed) {} [[nodiscard]] __device__ inline uint32_t fmix32(uint32_t h) const { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } [[nodiscard]] __device__ inline uint32_t getblock32(std::byte const* data, cudf::size_type offset) const { // Read a 4-byte value from the data pointer as individual bytes for safe // unaligned access (very likely for string types). auto const block = reinterpret_cast<uint8_t const*>(data + offset); return block[0] | (block[1] << 8) | (block[2] << 16) | (block[3] << 24); } [[nodiscard]] result_type __device__ inline operator()(Key const& key) const { return compute(normalize_nans_and_zeros(key)); } template <typename T> result_type __device__ inline compute(T const& key) const { return compute_bytes(reinterpret_cast<std::byte const*>(&key), sizeof(T)); } result_type __device__ inline compute_remaining_bytes(std::byte const* data, cudf::size_type len, cudf::size_type tail_offset, result_type h) const { // Process remaining bytes that do not fill a four-byte chunk. uint32_t k1 = 0; switch (len % 4) { case 3: k1 ^= std::to_integer<uint8_t>(data[tail_offset + 2]) << 16; [[fallthrough]]; case 2: k1 ^= std::to_integer<uint8_t>(data[tail_offset + 1]) << 8; [[fallthrough]]; case 1: k1 ^= std::to_integer<uint8_t>(data[tail_offset]); k1 *= c1; k1 = rotate_bits_left(k1, rot_c1); k1 *= c2; h ^= k1; }; return h; } result_type __device__ compute_bytes(std::byte const* data, cudf::size_type const len) const { constexpr cudf::size_type BLOCK_SIZE = 4; cudf::size_type const nblocks = len / BLOCK_SIZE; cudf::size_type const tail_offset = nblocks * BLOCK_SIZE; result_type h = m_seed; // Process all four-byte chunks. for (cudf::size_type i = 0; i < nblocks; i++) { uint32_t k1 = getblock32(data, i * BLOCK_SIZE); k1 *= c1; k1 = rotate_bits_left(k1, rot_c1); k1 *= c2; h ^= k1; h = rotate_bits_left(h, rot_c2); h = h * 5 + c3; } h = compute_remaining_bytes(data, len, tail_offset, h); // Finalize hash. h ^= len; h = fmix32(h); return h; } private: uint32_t m_seed{cudf::DEFAULT_HASH_SEED}; static constexpr uint32_t c1 = 0xcc9e2d51; static constexpr uint32_t c2 = 0x1b873593; static constexpr uint32_t c3 = 0xe6546b64; static constexpr uint32_t rot_c1 = 15; static constexpr uint32_t rot_c2 = 13; }; template <> hash_value_type __device__ inline MurmurHash3_x86_32<bool>::operator()(bool const& key) const { return compute(static_cast<uint8_t>(key)); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<float>::operator()(float const& key) const { return compute(normalize_nans_and_zeros(key)); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<double>::operator()(double const& key) const { return compute(normalize_nans_and_zeros(key)); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<cudf::string_view>::operator()( cudf::string_view const& key) const { auto const data = reinterpret_cast<std::byte const*>(key.data()); auto const len = key.size_bytes(); return compute_bytes(data, len); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<numeric::decimal32>::operator()( numeric::decimal32 const& key) const { return compute(key.value()); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<numeric::decimal64>::operator()( numeric::decimal64 const& key) const { return compute(key.value()); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<numeric::decimal128>::operator()( numeric::decimal128 const& key) const { return compute(key.value()); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<cudf::list_view>::operator()( cudf::list_view const& key) const { CUDF_UNREACHABLE("List column hashing is not supported"); } template <> hash_value_type __device__ inline MurmurHash3_x86_32<cudf::struct_view>::operator()( cudf::struct_view const& key) const { CUDF_UNREACHABLE("Direct hashing of struct_view is not supported"); } } // namespace cudf::hashing::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/murmurhash3_x64_128.cuh
/* * 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/hashing/detail/hash_functions.cuh> #include <cudf/strings/string_view.cuh> #include <thrust/pair.h> namespace cudf::hashing::detail { // MurmurHash3_x64_128 implementation from // https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp //----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. // Note - The x86 and x64 versions do _not_ produce the same results, as the // algorithms are optimized for their respective platforms. You can still // compile and run any of them on any platform, but your performance with the // non-native version will be less than optimal. template <typename Key> struct MurmurHash3_x64_128 { using result_type = thrust::pair<uint64_t, uint64_t>; constexpr MurmurHash3_x64_128() = default; constexpr MurmurHash3_x64_128(uint64_t seed) : m_seed(seed) {} __device__ inline uint32_t getblock32(std::byte const* data, cudf::size_type offset) const { // Read a 4-byte value from the data pointer as individual bytes for safe // unaligned access (very likely for string types). auto block = reinterpret_cast<uint8_t const*>(data + offset); return block[0] | (block[1] << 8) | (block[2] << 16) | (block[3] << 24); } __device__ inline uint64_t getblock64(std::byte const* data, cudf::size_type offset) const { uint64_t result = getblock32(data, offset + 4); result = result << 32; return result | getblock32(data, offset); } __device__ inline uint64_t fmix64(uint64_t k) const { k ^= k >> 33; k *= 0xff51afd7ed558ccdUL; k ^= k >> 33; k *= 0xc4ceb9fe1a85ec53UL; k ^= k >> 33; return k; } result_type __device__ inline operator()(Key const& key) const { return compute(key); } template <typename T> result_type __device__ inline compute(T const& key) const { return compute_bytes(reinterpret_cast<std::byte const*>(&key), sizeof(T)); } result_type __device__ inline compute_remaining_bytes(std::byte const* data, cudf::size_type len, cudf::size_type tail_offset, result_type h) const { // Process remaining bytes that do not fill a 8-byte chunk. uint64_t k1 = 0; uint64_t k2 = 0; auto const tail = reinterpret_cast<uint8_t const*>(data) + tail_offset; switch (len & (BLOCK_SIZE - 1)) { case 15: k2 ^= static_cast<uint64_t>(tail[14]) << 48; case 14: k2 ^= static_cast<uint64_t>(tail[13]) << 40; case 13: k2 ^= static_cast<uint64_t>(tail[12]) << 32; case 12: k2 ^= static_cast<uint64_t>(tail[11]) << 24; case 11: k2 ^= static_cast<uint64_t>(tail[10]) << 16; case 10: k2 ^= static_cast<uint64_t>(tail[9]) << 8; case 9: k2 ^= static_cast<uint64_t>(tail[8]) << 0; k2 *= c2; k2 = rotate_bits_left(k2, 33); k2 *= c1; h.second ^= k2; case 8: k1 ^= static_cast<uint64_t>(tail[7]) << 56; case 7: k1 ^= static_cast<uint64_t>(tail[6]) << 48; case 6: k1 ^= static_cast<uint64_t>(tail[5]) << 40; case 5: k1 ^= static_cast<uint64_t>(tail[4]) << 32; case 4: k1 ^= static_cast<uint64_t>(tail[3]) << 24; case 3: k1 ^= static_cast<uint64_t>(tail[2]) << 16; case 2: k1 ^= static_cast<uint64_t>(tail[1]) << 8; case 1: k1 ^= static_cast<uint64_t>(tail[0]) << 0; k1 *= c1; k1 = rotate_bits_left(k1, 31); k1 *= c2; h.first ^= k1; }; return h; } result_type __device__ compute_bytes(std::byte const* data, cudf::size_type const len) const { auto const nblocks = len / BLOCK_SIZE; uint64_t h1 = m_seed; uint64_t h2 = m_seed; // Process all four-byte chunks. for (cudf::size_type i = 0; i < nblocks; i++) { uint64_t k1 = getblock64(data, (i * BLOCK_SIZE)); // 1st 8 bytes uint64_t k2 = getblock64(data, (i * BLOCK_SIZE) + (BLOCK_SIZE / 2)); // 2nd 8 bytes k1 *= c1; k1 = rotate_bits_left(k1, 31); k1 *= c2; h1 ^= k1; h1 = rotate_bits_left(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = rotate_bits_left(k2, 33); k2 *= c1; h2 ^= k2; h2 = rotate_bits_left(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } thrust::tie(h1, h2) = compute_remaining_bytes(data, len, nblocks * BLOCK_SIZE, {h1, h2}); // Finalize hash. h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; return {h1, h2}; } private: uint64_t m_seed{}; static constexpr uint32_t BLOCK_SIZE = 16; // 2 x 64-bit = 16 bytes static constexpr uint64_t c1 = 0x87c37b91114253d5UL; static constexpr uint64_t c2 = 0x4cf5ad432745937fUL; }; template <> MurmurHash3_x64_128<bool>::result_type __device__ inline MurmurHash3_x64_128<bool>::operator()( bool const& key) const { return compute<uint8_t>(key); } template <> MurmurHash3_x64_128<float>::result_type __device__ inline MurmurHash3_x64_128<float>::operator()( float const& key) const { return compute(normalize_nans(key)); } template <> MurmurHash3_x64_128<double>::result_type __device__ inline MurmurHash3_x64_128<double>::operator()( double const& key) const { return compute(normalize_nans(key)); } template <> MurmurHash3_x64_128<cudf::string_view>::result_type __device__ inline MurmurHash3_x64_128<cudf::string_view>::operator()( cudf::string_view const& key) const { auto const data = reinterpret_cast<std::byte const*>(key.data()); auto const len = key.size_bytes(); return compute_bytes(data, len); } template <> MurmurHash3_x64_128<numeric::decimal32>::result_type __device__ inline MurmurHash3_x64_128<numeric::decimal32>::operator()( numeric::decimal32 const& key) const { return compute(key.value()); } template <> MurmurHash3_x64_128<numeric::decimal64>::result_type __device__ inline MurmurHash3_x64_128<numeric::decimal64>::operator()( numeric::decimal64 const& key) const { return compute(key.value()); } template <> MurmurHash3_x64_128<numeric::decimal128>::result_type __device__ inline MurmurHash3_x64_128<numeric::decimal128>::operator()( numeric::decimal128 const& key) const { return compute(key.value()); } } // namespace cudf::hashing::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/hash_allocator.cuh
/* * Copyright (c) 2017-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 <new> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/mr/device/device_memory_resource.hpp> #include <rmm/mr/device/managed_memory_resource.hpp> #include <rmm/mr/device/per_device_resource.hpp> template <class T> struct default_allocator { using value_type = T; rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource(); default_allocator() = default; template <class U> constexpr default_allocator(default_allocator<U> const&) noexcept { } T* allocate(std::size_t n, rmm::cuda_stream_view stream = cudf::get_default_stream()) const { return static_cast<T*>(mr->allocate(n * sizeof(T), stream)); } void deallocate(T* p, std::size_t n, rmm::cuda_stream_view stream = cudf::get_default_stream()) const { mr->deallocate(p, n * sizeof(T), stream); } }; template <class T, class U> bool operator==(default_allocator<T> const&, default_allocator<U> const&) { return true; } template <class T, class U> bool operator!=(default_allocator<T> const&, default_allocator<U> const&) { return false; }
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/default_hash.cuh
/* * 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/hashing/detail/murmurhash3_x86_32.cuh> namespace cudf::hashing::detail { /** * @brief The default hash algorithm for use within libcudf internal functions * * This is declared here so it may be changed to another algorithm without modifying * all those places that use it. Internal function implementations are encourage to * use the `cudf::hashing::detail::default_hash` where possible. * * @tparam Key The key type for use by the hash class */ template <typename Key> using default_hash = MurmurHash3_x86_32<Key>; } // namespace cudf::hashing::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/hashing
rapidsai_public_repos/cudf/cpp/include/cudf/hashing/detail/helper_functions.cuh
/* * Copyright (c) 2017-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/types.hpp> #include <thrust/pair.h> constexpr int64_t DEFAULT_HASH_TABLE_OCCUPANCY = 50; /** * @brief Compute requisite size of hash table. * * Computes the number of entries required in a hash table to satisfy * inserting a specified number of keys to achieve the specified hash table * occupancy. * * @param num_keys_to_insert The number of keys that will be inserted * @param desired_occupancy The desired occupancy percentage, e.g., 50 implies a * 50% occupancy * @return size_t The size of the hash table that will satisfy the desired * occupancy for the specified number of insertions */ inline size_t compute_hash_table_size(cudf::size_type num_keys_to_insert, uint32_t desired_occupancy = DEFAULT_HASH_TABLE_OCCUPANCY) { assert(desired_occupancy != 0); assert(desired_occupancy <= 100); double const grow_factor{100.0 / desired_occupancy}; // Calculate size of hash map based on the desired occupancy size_t hash_table_size{static_cast<size_t>(std::ceil(num_keys_to_insert * grow_factor))}; return hash_table_size; } template <typename pair_type> __forceinline__ __device__ pair_type load_pair_vectorized(pair_type const* __restrict__ const ptr) { if (sizeof(uint4) == sizeof(pair_type)) { union pair_type2vec_type { uint4 vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0, 0, 0, 0}; converter.vec_val = *reinterpret_cast<uint4 const*>(ptr); return converter.pair_val; } else if (sizeof(uint2) == sizeof(pair_type)) { union pair_type2vec_type { uint2 vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0, 0}; converter.vec_val = *reinterpret_cast<uint2 const*>(ptr); return converter.pair_val; } else if (sizeof(int) == sizeof(pair_type)) { union pair_type2vec_type { int vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0}; converter.vec_val = *reinterpret_cast<int const*>(ptr); return converter.pair_val; } else if (sizeof(short) == sizeof(pair_type)) { union pair_type2vec_type { short vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0}; converter.vec_val = *reinterpret_cast<short const*>(ptr); return converter.pair_val; } else { return *ptr; } } template <typename pair_type> __forceinline__ __device__ void store_pair_vectorized(pair_type* __restrict__ const ptr, pair_type const val) { if (sizeof(uint4) == sizeof(pair_type)) { union pair_type2vec_type { uint4 vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0, 0, 0, 0}; converter.pair_val = val; *reinterpret_cast<uint4*>(ptr) = converter.vec_val; } else if (sizeof(uint2) == sizeof(pair_type)) { union pair_type2vec_type { uint2 vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0, 0}; converter.pair_val = val; *reinterpret_cast<uint2*>(ptr) = converter.vec_val; } else if (sizeof(int) == sizeof(pair_type)) { union pair_type2vec_type { int vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0}; converter.pair_val = val; *reinterpret_cast<int*>(ptr) = converter.vec_val; } else if (sizeof(short) == sizeof(pair_type)) { union pair_type2vec_type { short vec_val; pair_type pair_val; }; pair_type2vec_type converter = {0}; converter.pair_val = val; *reinterpret_cast<short*>(ptr) = converter.vec_val; } else { *ptr = val; } } template <typename value_type, typename size_type, typename key_type, typename elem_type> __global__ void init_hashtbl(value_type* __restrict__ const hashtbl_values, size_type const n, key_type const key_val, elem_type const elem_val) { size_type const idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < n) { store_pair_vectorized(hashtbl_values + idx, thrust::make_pair(key_val, elem_val)); } } template <typename T> struct equal_to { using result_type = bool; using first_argument_type = T; using second_argument_type = T; __forceinline__ __host__ __device__ constexpr bool operator()( first_argument_type const& lhs, second_argument_type const& rhs) const { return lhs == rhs; } }; template <typename Iterator> class cycle_iterator_adapter { public: using value_type = typename std::iterator_traits<Iterator>::value_type; using difference_type = typename std::iterator_traits<Iterator>::difference_type; using pointer = typename std::iterator_traits<Iterator>::pointer; using reference = typename std::iterator_traits<Iterator>::reference; using iterator_type = Iterator; cycle_iterator_adapter() = delete; __host__ __device__ explicit cycle_iterator_adapter(iterator_type const& begin, iterator_type const& end, iterator_type const& current) : m_begin(begin), m_end(end), m_current(current) { } __host__ __device__ cycle_iterator_adapter& operator++() { if (m_end == (m_current + 1)) m_current = m_begin; else ++m_current; return *this; } __host__ __device__ cycle_iterator_adapter const& operator++() const { if (m_end == (m_current + 1)) m_current = m_begin; else ++m_current; return *this; } __host__ __device__ cycle_iterator_adapter& operator++(int) { cycle_iterator_adapter<iterator_type> old(m_begin, m_end, m_current); if (m_end == (m_current + 1)) m_current = m_begin; else ++m_current; return old; } __host__ __device__ cycle_iterator_adapter const& operator++(int) const { cycle_iterator_adapter<iterator_type> old(m_begin, m_end, m_current); if (m_end == (m_current + 1)) m_current = m_begin; else ++m_current; return old; } __host__ __device__ bool equal(cycle_iterator_adapter<iterator_type> const& other) const { return m_current == other.m_current && m_begin == other.m_begin && m_end == other.m_end; } __host__ __device__ reference& operator*() { return *m_current; } __host__ __device__ reference const& operator*() const { return *m_current; } __host__ __device__ const pointer operator->() const { return m_current.operator->(); } __host__ __device__ pointer operator->() { return m_current; } private: iterator_type m_current; iterator_type m_begin; iterator_type m_end; }; template <class T> __host__ __device__ bool operator==(cycle_iterator_adapter<T> const& lhs, cycle_iterator_adapter<T> const& rhs) { return lhs.equal(rhs); } template <class T> __host__ __device__ bool operator!=(cycle_iterator_adapter<T> const& lhs, cycle_iterator_adapter<T> const& rhs) { return !lhs.equal(rhs); }
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/json/json.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <thrust/optional.h> namespace cudf { /** * @addtogroup json_object * @{ * @file */ /** * @brief Settings for `get_json_object()`. */ class get_json_object_options { // allow single quotes to represent strings in JSON bool allow_single_quotes = false; // individual string values are returned with quotes stripped. bool strip_quotes_from_single_strings = true; // Whether to return nulls when an object does not contain the requested field. bool missing_fields_as_nulls = false; public: /** * @brief Default constructor. */ explicit get_json_object_options() = default; /** * @brief Returns true/false depending on whether single-quotes for representing strings * are allowed. * * @return true if single-quotes are allowed, false otherwise. */ [[nodiscard]] CUDF_HOST_DEVICE inline bool get_allow_single_quotes() const { return allow_single_quotes; } /** * @brief Returns true/false depending on whether individually returned string values have * their quotes stripped. * * When set to true, if the return value for a given row is an individual string * (not an object, or an array of strings), strip the quotes from the string and return only the * contents of the string itself. Example: * * @code{.pseudo} * * With strip_quotes_from_single_strings OFF: * Input = {"a" : "b"} * Query = $.a * Output = "b" * * With strip_quotes_from_single_strings ON: * Input = {"a" : "b"} * Query = $.a * Output = b * * @endcode * * @return true if individually returned string values have their quotes stripped. */ [[nodiscard]] CUDF_HOST_DEVICE inline bool get_strip_quotes_from_single_strings() const { return strip_quotes_from_single_strings; } /** * @brief Whether a field not contained by an object is to be interpreted as null. * * When set to true, if an object is queried for a field it does not contain, a null is returned. * * @code{.pseudo} * * With missing_fields_as_nulls OFF: * Input = {"a" : [{"x": "1", "y": "2"}, {"x": "3"}]} * Query = $.a[*].y * Output = ["2"] * * With missing_fields_as_nulls ON: * Input = {"a" : [{"x": "1", "y": "2"}, {"x": "3"}]} * Query = $.a[*].y * Output = ["2", null] * * @endcode * * @return true if missing fields are interpreted as null. */ [[nodiscard]] CUDF_HOST_DEVICE inline bool get_missing_fields_as_nulls() const { return missing_fields_as_nulls; } /** * @brief Set whether single-quotes for strings are allowed. * * @param _allow_single_quotes bool indicating desired behavior. */ void set_allow_single_quotes(bool _allow_single_quotes) { allow_single_quotes = _allow_single_quotes; } /** * @brief Set whether individually returned string values have their quotes stripped. * * @param _strip_quotes_from_single_strings bool indicating desired behavior. */ void set_strip_quotes_from_single_strings(bool _strip_quotes_from_single_strings) { strip_quotes_from_single_strings = _strip_quotes_from_single_strings; } /** * @brief Set whether missing fields are interpreted as null. * * @param _missing_fields_as_nulls bool indicating desired behavior. */ void set_missing_fields_as_nulls(bool _missing_fields_as_nulls) { missing_fields_as_nulls = _missing_fields_as_nulls; } }; /** * @brief Apply a JSONPath string to all rows in an input strings column. * * Applies a JSONPath string to an incoming strings column where each row in the column * is a valid json string. The output is returned by row as a strings column. * * https://tools.ietf.org/id/draft-goessner-dispatch-jsonpath-00.html * Implements only the operators: $ . [] * * * @throw std::invalid_argument if provided an invalid operator or an empty name * * @param col The input strings column. Each row must contain a valid json string * @param json_path The JSONPath string to be applied to each row * @param options Options for controlling the behavior of the function * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Resource for allocating device memory * @return New strings column containing the retrieved json object strings */ std::unique_ptr<cudf::column> get_json_object( cudf::strings_column_view const& col, cudf::string_scalar const& json_path, get_json_object_options options = get_json_object_options{}, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/filling.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <memory> namespace cudf::lists { /** * @addtogroup lists_filling * @{ * @file * @brief Column APIs for individual list sequence */ /** * @brief Create a lists column in which each row contains a sequence of values specified by a tuple * of (`start`, `size`) parameters. * * Create a lists column in which each row is a sequence of values starting from a `start` value, * incrementing by one, and its cardinality is specified by a `size` value. The `start` and `size` * values used to generate each list is taken from the corresponding row of the input @p starts and * @p sizes columns. * * - @p sizes must be a column of integer types. * - All the input columns must not have nulls. * - If any row of the @p sizes column contains negative value, the output is undefined. * * @code{.pseudo} * starts = [0, 1, 2, 3, 4] * sizes = [0, 2, 2, 1, 3] * * output = [ [], [1, 2], [2, 3], [3], [4, 5, 6] ] * @endcode * * @throws cudf::logic_error if @p sizes column is not of integer types. * @throws cudf::logic_error if any input column has nulls. * @throws cudf::logic_error if @p starts and @p sizes columns do not have the same size. * @throws std::overflow_error if the output column would exceed the column size limit. * * @param starts First values in the result sequences. * @param sizes Numbers of values in the result sequences. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return The result column containing generated sequences. */ std::unique_ptr<column> sequences( column_view const& starts, column_view const& sizes, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a lists column in which each row contains a sequence of values specified by a tuple * of (`start`, `step`, `size`) parameters. * * Create a lists column in which each row is a sequence of values starting from a `start` value, * incrementing by a `step` value, and its cardinality is specified by a `size` value. The values * `start`, `step`, and `size` used to generate each list is taken from the corresponding row of the * input @p starts, @p steps, and @p sizes columns. * * - @p sizes must be a column of integer types. * - @p starts and @p steps columns must have the same type. * - All the input columns must not have nulls. * - If any row of the @p sizes column contains negative value, the output is undefined. * * @code{.pseudo} * starts = [0, 1, 2, 3, 4] * steps = [2, 1, 1, 1, -3] * sizes = [0, 2, 2, 1, 3] * * output = [ [], [1, 2], [2, 3], [3], [4, 1, -2] ] * @endcode * * @throws cudf::logic_error if @p sizes column is not of integer types. * @throws cudf::logic_error if any input column has nulls. * @throws cudf::logic_error if @p starts and @p steps columns have different types. * @throws cudf::logic_error if @p starts, @p steps, and @p sizes columns do not have the same size. * @throws std::overflow_error if the output column would exceed the column size limit. * * @param starts First values in the result sequences. * @param steps Increment values for the result sequences. * @param sizes Numbers of values in the result sequences. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return The result column containing generated sequences. */ std::unique_ptr<column> sequences( column_view const& starts, column_view const& steps, column_view const& sizes, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace cudf::lists
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/gather.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { /** * @addtogroup lists_gather * @{ * @file */ /** * @brief Segmented gather of the elements within a list element in each row of a list column. * * `source_column` with any depth and `gather_map_list` with depth 1 are only supported. * * @code{.pseudo} * source_column : [{"a", "b", "c", "d"}, {"1", "2", "3", "4"}, {"x", "y", "z"}] * gather_map_list : [{0, 1, 3, 2}, {1, 3, 2}, {}] * * result : [{"a", "b", "d", "c"}, {"2", "4", "3"}, {}] * @endcode * * @throws cudf::logic_error if `gather_map_list` size is not same as `source_column` size. * @throws std::invalid_argument if gather_map contains null values. * @throws cudf::logic_error if gather_map is not list column of an index type. * * If indices in `gather_map_list` are outside the range `[-n, n)`, where `n` is the number of * elements in corresponding row of the source column, the behavior is as follows: * 1. If `bounds_policy` is set to `DONT_CHECK`, the behavior is undefined. * 2. If `bounds_policy` is set to `NULLIFY`, the corresponding element in the list row * is set to null in the output column. * * @code{.pseudo} * source_column : [{"a", "b", "c", "d"}, {"1", "2", "3", "4"}, {"x", "y", "z"}] * gather_map_list : [{0, -1, 4, -5}, {1, 3, 5}, {}] * * result_with_nullify : [{"a", "d", null, null}, {"2", "4", null}, {}] * @endcode * * @param source_column View into the list column to gather from * @param gather_map_list View into a non-nullable list column of integral indices that maps the * element in list of each row in the source columns to rows of lists in the destination columns. * @param bounds_policy Can be `DONT_CHECK` or `NULLIFY`. Selects whether or not to nullify the * output list row's element, when the gather index falls outside the range `[-n, n)`, * where `n` is the number of elements in list row corresponding to the gather-map row. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource to allocate any returned objects * @return column with elements in list of rows gathered based on `gather_map_list` * */ std::unique_ptr<column> segmented_gather( lists_column_view const& source_column, lists_column_view const& gather_map_list, out_of_bounds_policy bounds_policy = out_of_bounds_policy::DONT_CHECK, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/lists_column_device_view.cuh
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cuda_runtime.h> #include <cudf/column/column_device_view.cuh> #include <cudf/lists/lists_column_view.hpp> #include <cudf/types.hpp> namespace cudf { namespace detail { /** * @brief Given a column_device_view, an instance of this class provides a * wrapper on this compound column for list operations. * Analogous to list_column_view. */ class lists_column_device_view : private column_device_view { public: lists_column_device_view() = delete; ~lists_column_device_view() = default; lists_column_device_view(lists_column_device_view const&) = default; ///< Copy constructor lists_column_device_view(lists_column_device_view&&) = default; ///< Move constructor /** * @brief Copy assignment operator * * @return The reference to this lists column device view */ lists_column_device_view& operator=(lists_column_device_view const&) = default; /** * @brief Move assignment operator * * @return The reference to this lists column device view */ lists_column_device_view& operator=(lists_column_device_view&&) = default; /** * @brief Construct a new lists column device view object from a column device view. * * @param underlying_ The column device view to wrap */ CUDF_HOST_DEVICE lists_column_device_view(column_device_view const& underlying_) : column_device_view(underlying_) { #ifdef __CUDA_ARCH__ cudf_assert(underlying_.type().id() == type_id::LIST and "lists_column_device_view only supports lists"); #else CUDF_EXPECTS(underlying_.type().id() == type_id::LIST, "lists_column_device_view only supports lists"); #endif } using column_device_view::is_null; using column_device_view::nullable; using column_device_view::offset; using column_device_view::size; /** * @brief Fetches the offsets column of the underlying list column. * * @return The offsets column of the underlying list column */ [[nodiscard]] __device__ inline column_device_view offsets() const { return column_device_view::child(lists_column_view::offsets_column_index); } /** * @brief Fetches the list offset value at a given row index while taking column offset into * account. * * @param idx The row index to fetch the list offset value at * @return The list offset value at a given row index while taking column offset into account */ [[nodiscard]] __device__ inline size_type offset_at(size_type idx) const { return offsets().size() > 0 ? offsets().element<size_type>(offset() + idx) : 0; } /** * @brief Fetches the child column of the underlying list column. * * @return The child column of the underlying list column */ [[nodiscard]] __device__ inline column_device_view child() const { return column_device_view::child(lists_column_view::child_column_index); } /** * @brief Fetches the child column of the underlying list column with offset and size applied * * @return The child column sliced relative to the parent's offset and size */ [[nodiscard]] __device__ inline column_device_view get_sliced_child() const { auto start = offset_at(0); auto end = offset_at(size()); return child().slice(start, end - start); } }; } // namespace detail } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/list_view.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. */ #pragma once /** * @file list_view.hpp * @brief Class definition for cudf::list_view. */ namespace cudf { /** * @brief A non-owning, immutable view of device data that represents * a list of elements of arbitrary type (including further nested lists). */ class list_view {}; } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/stream_compaction.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/device_memory_resource.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf::lists { /** * @addtogroup lists_filtering * @{ * @file */ /** * @brief Filters elements in each row of `input` LIST column using `boolean_mask` * LIST of booleans as a mask. * * Given an input `LIST` column and a list-of-bools column, the function produces * a new `LIST` column of the same type as `input`, where each element is copied * from the input row *only* if the corresponding `boolean_mask` is non-null and `true`. * * E.g. * @code{.pseudo} * input = { {0,1,2}, {3,4}, {5,6,7}, {8,9} }; * boolean_mask = { {0,1,1}, {1,0}, {1,1,1}, {0,0} }; * results = { {1,2}, {3}, {5,6,7}, {} }; * @endcode * * `input` and `boolean_mask` must have the same number of rows. * The output column has the same number of rows as the input column. * An element is copied to an output row *only* if the corresponding boolean_mask element is `true`. * An output row is invalid only if the input row is invalid. * * @throws cudf::logic_error if `boolean_mask` is not a "lists of bools" column * @throws cudf::logic_error if `input` and `boolean_mask` have different number of rows * * @param input The input list column view to be filtered * @param boolean_mask A nullable list of bools column used to filter `input` elements * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned table's device memory * @return List column of the same type as `input`, containing filtered list rows */ std::unique_ptr<column> apply_boolean_mask( lists_column_view const& input, lists_column_view const& boolean_mask, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a new list column without duplicate elements in each list. * * Given a lists column `input`, distinct elements of each list are copied to the corresponding * output list. The order of lists is preserved while the order of elements within each list is not * guaranteed. * * Example: * @code{.pseudo} * input = { {0, 1, 2, 3, 2}, {3, 1, 2}, null, {4, null, null, 5} } * result = { {0, 1, 2, 3}, {3, 1, 2}, null, {4, null, 5} } * @endcode * * @param input The input lists column * @param nulls_equal Flag to specify whether null elements should be considered as equal * @param nans_equal Flag to specify whether floating-point NaNs should be considered as equal * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned object * @return The resulting lists column containing lists without duplicates */ std::unique_ptr<column> distinct( lists_column_view const& input, null_equality nulls_equal = null_equality::EQUAL, nan_equality nans_equal = nan_equality::ALL_EQUAL, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace cudf::lists
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/reverse.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <memory> namespace cudf::lists { /** * @addtogroup lists_modify * @{ * @file */ /** * @brief Reverse the element order within each list of the input column. * * Any null input row will result in a corresponding null row in the output column. * * @code{.pseudo} * Example: * s = [ [1, 2, 3], [], null, [4, 5, null] ] * r = reverse(s) * r is now [ [3, 2, 1], [], null, [null, 5, 4] ] * @endcode * * @param input Lists column for this operation * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New lists column with reversed lists */ std::unique_ptr<column> reverse( lists_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of doxygen group } // namespace cudf::lists
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/list_device_view.cuh
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cuda_runtime.h> #include <cudf/detail/iterator.cuh> #include <cudf/lists/lists_column_device_view.cuh> #include <cudf/types.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/pair.h> namespace cudf { /** * @brief A non-owning, immutable view of device data that represents * a list of elements of arbitrary type (including further nested lists). */ class list_device_view { using lists_column_device_view = cudf::detail::lists_column_device_view; public: list_device_view() = default; /** * @brief Constructs a list_device_view from a list column and index. * * @param lists_column list column device view containing the list to view * @param row_index index of the list row to view */ __device__ inline list_device_view(lists_column_device_view const& lists_column, size_type const& row_index) : lists_column(lists_column), _row_index(row_index) { column_device_view const& offsets = lists_column.offsets(); cudf_assert(row_index >= 0 && row_index < lists_column.size() && row_index < offsets.size() && "row_index out of bounds"); begin_offset = offsets.element<size_type>(row_index + lists_column.offset()); cudf_assert(begin_offset >= 0 && begin_offset <= lists_column.child().size() && "begin_offset out of bounds."); _size = offsets.element<size_type>(row_index + 1 + lists_column.offset()) - begin_offset; } ~list_device_view() = default; /** * @brief Fetches the offset in the list column's child that corresponds to * the element at the specified list index. * * Consider the following lists column: * [ * [0,1,2], * [3,4,5], * [6,7,8] * ] * * The list's internals would look like: * offsets: [0, 3, 6, 9] * child : [0, 1, 2, 3, 4, 5, 6, 7, 8] * * The second list row (i.e. row_index=1) is [3,4,5]. * The third element (i.e. idx=2) of the second list row is 5. * * The offset of this element as stored in the child column (i.e. 5) * may be fetched using this method. * * @param idx The list index of the element to fetch the offset for * @return The offset of the element at the specified list index */ [[nodiscard]] __device__ inline size_type element_offset(size_type idx) const { cudf_assert(idx >= 0 && idx < size() && "idx out of bounds"); return begin_offset + idx; } /** * @brief Fetches the element at the specified index within the list row. * * @tparam T The type of the list's element. * @param idx The index into the list row * @return The element at the specified index of the list row. */ template <typename T> __device__ inline T element(size_type idx) const { return lists_column.child().element<T>(element_offset(idx)); } /** * @brief Checks whether the element is null at the specified index in the list * * @param idx The index into the list row * @return `true` if the element is null at the specified index in the list row */ [[nodiscard]] __device__ inline bool is_null(size_type idx) const { cudf_assert(idx >= 0 && idx < size() && "Index out of bounds."); auto element_offset = begin_offset + idx; return lists_column.child().is_null(element_offset); } /** * @brief Checks whether this list row is null. * * @return `true` if this list is null */ [[nodiscard]] __device__ inline bool is_null() const { return lists_column.is_null(_row_index); } /** * @brief Fetches the number of elements in this list row. * * @return The number of elements in this list row */ [[nodiscard]] __device__ inline size_type size() const { return _size; } /** * @brief Returns the row index of this list in the original lists column. * * @return The row index of this list */ [[nodiscard]] __device__ inline size_type row_index() const { return _row_index; } /** * @brief Fetches the lists_column_device_view that contains this list. * * @return The lists_column_device_view that contains this list */ [[nodiscard]] __device__ inline lists_column_device_view const& get_column() const { return lists_column; } template <typename T> struct pair_accessor; template <typename T> struct pair_rep_accessor; /// const pair iterator for the list template <typename T> using const_pair_iterator = thrust::transform_iterator<pair_accessor<T>, thrust::counting_iterator<cudf::size_type>>; /// const pair iterator type for the list template <typename T> using const_pair_rep_iterator = thrust::transform_iterator<pair_rep_accessor<T>, thrust::counting_iterator<cudf::size_type>>; /** * @brief Fetcher for a pair iterator to the first element in the list_device_view. * * Dereferencing the returned iterator yields a `thrust::pair<T, bool>`. * * If the element at index `i` is valid, then for `p = iter[i]`, * 1. `p.first` is the value of the element at `i` * 2. `p.second == true` * * If the element at index `i` is null, * 1. `p.first` is undefined * 2. `p.second == false` * * @return A pair iterator to the first element in the list_device_view and whether or not the * element is valid */ template <typename T> [[nodiscard]] __device__ inline const_pair_iterator<T> pair_begin() const { return const_pair_iterator<T>{thrust::counting_iterator<size_type>(0), pair_accessor<T>{*this}}; } /** * @brief Fetcher for a pair iterator to one position past the last element in the * list_device_view. * * @return A pair iterator to one past the last element in the list_device_view and whether or not * that element is valid */ template <typename T> [[nodiscard]] __device__ inline const_pair_iterator<T> pair_end() const { return const_pair_iterator<T>{thrust::counting_iterator<size_type>(size()), pair_accessor<T>{*this}}; } /** * @brief Fetcher for a pair iterator to the first element in the list_device_view. * * Dereferencing the returned iterator yields a `thrust::pair<rep_type, bool>`, * where `rep_type` is `device_storage_type_t<T>`, the type used to store the value * on the device. * * If the element at index `i` is valid, then for `p = iter[i]`, * 1. `p.first` is the value of the element at `i` * 2. `p.second == true` * * If the element at index `i` is null, * 1. `p.first` is undefined * 2. `p.second == false` * * @return A pair iterator to the first element in the list_device_view and whether or not that * element is valid */ template <typename T> [[nodiscard]] __device__ inline const_pair_rep_iterator<T> pair_rep_begin() const { return const_pair_rep_iterator<T>{thrust::counting_iterator<size_type>(0), pair_rep_accessor<T>{*this}}; } /** * @brief Fetcher for a pair iterator to one position past the last element in the * list_device_view. * * @return A pair iterator one past the last element in the list_device_view and whether or not * that element is valid */ template <typename T> [[nodiscard]] __device__ inline const_pair_rep_iterator<T> pair_rep_end() const { return const_pair_rep_iterator<T>{thrust::counting_iterator<size_type>(size()), pair_rep_accessor<T>{*this}}; } private: lists_column_device_view const& lists_column; size_type _row_index{}; // Row index in the Lists column vector. size_type _size{}; // Number of elements in *this* list row. size_type begin_offset; // Offset in list_column_device_view where this list begins. /** * @brief pair accessor for elements in a `list_device_view` * * This unary functor returns a pair of: * 1. data element at a specified index * 2. boolean validity flag for that element * * @tparam T The element-type of the list row */ template <typename T> struct pair_accessor { list_device_view const& list; ///< The list_device_view to access /** * @brief constructor * * @param _list The `list_device_view` whose rows are being accessed. */ explicit CUDF_HOST_DEVICE inline pair_accessor(list_device_view const& _list) : list{_list} {} /** * @brief Accessor for the {data, validity} pair at the specified index * * @param i Index into the list_device_view * @return A pair of data element and its validity flag. */ __device__ inline thrust::pair<T, bool> operator()(cudf::size_type i) const { return {list.element<T>(i), !list.is_null(i)}; } }; /** * @brief pair rep accessor for elements in a `list_device_view` * * Returns a `pair<rep_type, bool>`, where `rep_type` = `device_storage_type_t<T>`, * the type used to store the value on the device. * * This unary functor returns a pair of: * 1. rep element at a specified index * 2. boolean validity flag for that element * * @tparam T The element-type of the list row */ template <typename T> struct pair_rep_accessor { list_device_view const& list; ///< The list_device_view whose rows are being accessed using rep_type = device_storage_type_t<T>; ///< The type used to store the value on the device /** * @brief constructor * * @param _list The `list_device_view` whose rows are being accessed. */ explicit CUDF_HOST_DEVICE inline pair_rep_accessor(list_device_view const& _list) : list{_list} { } /** * @brief Accessor for the {rep_data, validity} pair at the specified index * * @param i Index into the list_device_view * @return A pair of data element and its validity flag. */ __device__ inline thrust::pair<rep_type, bool> operator()(cudf::size_type i) const { return {get_rep<T>(i), !list.is_null(i)}; } private: template <typename R, std::enable_if_t<std::is_same_v<R, rep_type>, void>* = nullptr> __device__ inline rep_type get_rep(cudf::size_type i) const { return list.element<R>(i); } template <typename R, std::enable_if_t<not std::is_same_v<R, rep_type>, void>* = nullptr> __device__ inline rep_type get_rep(cudf::size_type i) const { return list.element<R>(i).value(); } }; }; /** * @brief Returns the size of the list by row index * */ struct list_size_functor { detail::lists_column_device_view const d_column; ///< The list column to access /** * @brief Constructor * * @param d_col The cudf::lists_column_device_view whose rows are being accessed */ CUDF_HOST_DEVICE inline list_size_functor(detail::lists_column_device_view const& d_col) : d_column(d_col) { } /** * @brief Returns size of the list by row index * * @param idx row index * @return size of the list */ __device__ inline size_type operator()(size_type idx) { if (d_column.is_null(idx)) return size_type{0}; return d_column.offset_at(idx + 1) - d_column.offset_at(idx); } }; /** * @brief Makes an iterator that returns size of the list by row index * * Example: * For a list_column_device_view with 3 rows, `l = {[1, 2, 3], [4, 5], [6, 7, 8, 9]}`, * @code{.cpp} * auto it = make_list_size_iterator(l); * assert(it[0] == 3); * assert(it[1] == 2); * assert(it[2] == 4); * @endcode * * @param c The list_column_device_view to iterate over * @return An iterator that returns the size of the list by row index */ CUDF_HOST_DEVICE auto inline make_list_size_iterator(detail::lists_column_device_view const& c) { return detail::make_counting_transform_iterator(0, list_size_functor{c}); } } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/combine.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { //! Lists column APIs namespace lists { /** * @addtogroup lists_combine * @{ * @file */ /** * @brief Flag to specify whether a null list element will be ignored from concatenation, or the * entire concatenation result involving null list elements will be a null element. */ enum class concatenate_null_policy { IGNORE, NULLIFY_OUTPUT_ROW }; /** * @brief Row-wise concatenating multiple lists columns into a single lists column. * * The output column is generated by concatenating the elements within each row of the input * table. If any row of the input table contains null elements, the concatenation process will * either ignore those null elements, or will simply set the entire resulting row to be a null * element. * * @code{.pseudo} * s1 = [{0, 1}, {2, 3, 4}, {5}, {}, {6, 7}] * s2 = [{8}, {9}, {}, {10, 11, 12}, {13, 14, 15, 16}] * r = lists::concatenate_rows(s1, s2) * r is now [{0, 1, 8}, {2, 3, 4, 9}, {5}, {10, 11, 12}, {6, 7, 13, 14, 15, 16}] * @endcode * * @throws cudf::logic_error if any column of the input table is not a lists column. * @throws cudf::logic_error if all lists columns do not have the same type. * * @param input Table of lists to be concatenated. * @param null_policy The parameter to specify whether a null list element will be ignored from * concatenation, or any concatenation involving a null element will result in a null list. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return A new column in which each row is a list resulted from concatenating all list elements in * the corresponding row of the input table. */ std::unique_ptr<column> concatenate_rows( table_view const& input, concatenate_null_policy null_policy = concatenate_null_policy::IGNORE, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Concatenating multiple lists on the same row of a lists column into a single list. * * Given a lists column where each row in the column is a list of lists of entries, an output lists * column is generated by concatenating all the list elements at the same row together. If any row * contains null list elements, the concatenation process will either ignore those null elements, or * will simply set the entire resulting row to be a null element. * * @code{.pseudo} * l = [ [{1, 2}, {3, 4}, {5}], [{6}, {}, {7, 8, 9}] ] * r = lists::concatenate_list_elements(l); * r is [ {1, 2, 3, 4, 5}, {6, 7, 8, 9} ] * @endcode * * @throws std::invalid_argument if the input column is not at least two-level depth lists column * (i.e., each row must be a list of lists). * * @param input The lists column containing lists of list elements to concatenate. * @param null_policy The parameter to specify whether a null list element will be ignored from * concatenation, or any concatenation involving a null element will result in a null list. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return A new column in which each row is a list resulted from concatenating all list elements in * the corresponding row of the input lists column. */ std::unique_ptr<column> concatenate_list_elements( column_view const& input, concatenate_null_policy null_policy = concatenate_null_policy::IGNORE, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/set_operations.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/types.hpp> #include <rmm/mr/device/device_memory_resource.hpp> namespace cudf::lists { /** * @addtogroup set_operations * @{ * @file */ /** * @brief Check if lists at each row of the given lists columns overlap. * * Given two input lists columns, each list row in one column is checked if it has any common * elements with the corresponding row of the other column. * * A null input row in any of the input lists columns will result in a null output row. * * @throw cudf::logic_error if the input lists columns have different sizes. * @throw cudf::logic_error if children of the input lists columns have different data types. * * Example: * @code{.pseudo} * lhs = { {0, 1, 2}, {1, 2, 3}, null, {4, null, 5} } * rhs = { {1, 2, 3}, {4, 5}, {null, 7, 8}, {null, null} } * result = { true, false, null, true } * @endcode * * @param lhs The input lists column for one side * @param rhs The input lists column for the other side * @param nulls_equal Flag to specify whether null elements should be considered as equal, default * to be `UNEQUAL` which means only non-null elements are checked for overlapping * @param nans_equal Flag to specify whether floating-point NaNs should be considered as equal * @param mr Device memory resource used to allocate the returned object * @param stream CUDA stream used for device memory operations and kernel launches * @return A column of type BOOL containing the check results */ std::unique_ptr<column> have_overlap( lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal = null_equality::EQUAL, nan_equality nans_equal = nan_equality::ALL_EQUAL, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a lists column of distinct elements common to two input lists columns. * * Given two input lists columns `lhs` and `rhs`, an output lists column is created in a way such * that each of its row `i` contains a list of distinct elements that can be found in both `lhs[i]` * and `rhs[i]`. * * The order of distinct elements in the output rows is unspecified. * * A null input row in any of the input lists columns will result in a null output row. * * @throw cudf::logic_error if the input lists columns have different sizes. * @throw cudf::logic_error if children of the input lists columns have different data types. * * Example: * @code{.pseudo} * lhs = { {2, 1, 2}, {1, 2, 3}, null, {4, null, 5} } * rhs = { {1, 2, 3}, {4, 5}, {null, 7, 8}, {null, null} } * result = { {1, 2}, {}, null, {null} } * @endcode * * @param lhs The input lists column for one side * @param rhs The input lists column for the other side * @param nulls_equal Flag to specify whether null elements should be considered as equal * @param nans_equal Flag to specify whether floating-point NaNs should be considered as equal * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned object * @return A lists column containing the intersection results */ std::unique_ptr<column> intersect_distinct( lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal = null_equality::EQUAL, nan_equality nans_equal = nan_equality::ALL_EQUAL, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a lists column of distinct elements found in either of two input lists columns. * * Given two input lists columns `lhs` and `rhs`, an output lists column is created in a way such * that each of its row `i` contains a list of distinct elements that can be found in either * `lhs[i]` or `rhs[i]`. * * The order of distinct elements in the output rows is unspecified. * * A null input row in any of the input lists columns will result in a null output row. * * @throw cudf::logic_error if the input lists columns have different sizes. * @throw cudf::logic_error if children of the input lists columns have different data types. * * Example: * @code{.pseudo} * lhs = { {2, 1, 2}, {1, 2, 3}, null, {4, null, 5} } * rhs = { {1, 2, 3}, {4, 5}, {null, 7, 8}, {null, null} } * result = { {1, 2, 3}, {1, 2, 3, 4, 5}, null, {4, null, 5} } * @endcode * * @param lhs The input lists column for one side * @param rhs The input lists column for the other side * @param nulls_equal Flag to specify whether null elements should be considered as equal * @param nans_equal Flag to specify whether floating-point NaNs should be considered as equal * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned object * @return A lists column containing the union results */ std::unique_ptr<column> union_distinct( lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal = null_equality::EQUAL, nan_equality nans_equal = nan_equality::ALL_EQUAL, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a lists column of distinct elements found only in the left input column. * * Given two input lists columns `lhs` and `rhs`, an output lists column is created in a way such * that each of its row `i` contains a list of distinct elements that can be found in `lhs[i]` but * are not found in `rhs[i]`. * * The order of distinct elements in the output rows is unspecified. * * A null input row in any of the input lists columns will result in a null output row. * * @throw cudf::logic_error if the input lists columns have different sizes. * @throw cudf::logic_error if children of the input lists columns have different data types. * * Example: * @code{.pseudo} * lhs = { {2, 1, 2}, {1, 2, 3}, null, {4, null, 5} } * rhs = { {1, 2, 3}, {4, 5}, {null, 7, 8}, {null, null} } * result = { {}, {1, 2, 3}, null, {4, 5} } * @endcode * * @param lhs The input lists column of elements that may be included * @param rhs The input lists column of elements to exclude * @param nulls_equal Flag to specify whether null elements should be considered as equal * @param nans_equal Flag to specify whether floating-point NaNs should be considered as equal * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned object * @return A lists column containing the difference results */ std::unique_ptr<column> difference_distinct( lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal = null_equality::EQUAL, nan_equality nans_equal = nan_equality::ALL_EQUAL, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace cudf::lists
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/lists_column_view.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <rmm/cuda_stream_view.hpp> /** * @file * @brief Class definition for cudf::lists_column_view */ namespace cudf { /** * @addtogroup lists_classes * @{ */ /** * @brief Given a column-view of lists type, an instance of this class * provides a wrapper on this compound column for list operations. */ class lists_column_view : private column_view { public: /** * @brief Construct a new lists column view object from a column view. * * @param lists_column The column view to wrap */ lists_column_view(column_view const& lists_column); lists_column_view(lists_column_view&&) = default; ///< Move constructor lists_column_view(lists_column_view const&) = default; ///< Copy constructor ~lists_column_view() = default; /** * @brief Copy assignment operator * * @return The reference to this lists column */ lists_column_view& operator=(lists_column_view const&) = default; /** * @brief Move assignment operator * * @return The reference to this lists column */ lists_column_view& operator=(lists_column_view&&) = default; static constexpr size_type offsets_column_index{0}; ///< The index of the offsets column static constexpr size_type child_column_index{1}; ///< The index of the child column using column_view::child_begin; using column_view::child_end; using column_view::has_nulls; using column_view::is_empty; using column_view::null_count; using column_view::null_mask; using column_view::offset; using column_view::size; using offset_iterator = size_type const*; ///< Iterator type for offsets /** * @brief Returns the parent column. * * @return The parent column */ [[nodiscard]] column_view parent() const; /** * @brief Returns the internal column of offsets * * @throw cudf::logic error if this is an empty column * @return The internal column of offsets */ [[nodiscard]] column_view offsets() const; /** * @brief Returns the internal child column * * @throw cudf::logic error if this is an empty column * @return The internal child column */ [[nodiscard]] column_view child() const; /** * @brief Returns the internal child column, applying any offset from the root. * * Slice/split offset values are only stored at the root level of a list column. * So when doing computations on them, we need to apply that offset to * the child columns when recursing. Most functions operating in a recursive manner * on lists columns should be using `get_sliced_child()` instead of `child()`. * * @throw cudf::logic error if this is an empty column * @param stream CUDA stream used for device memory operations and kernel launches * @return A sliced child column view */ [[nodiscard]] column_view get_sliced_child(rmm::cuda_stream_view stream) const; /** * @brief Return first offset (accounting for column offset) * * @return Pointer to the first offset */ [[nodiscard]] offset_iterator offsets_begin() const noexcept { return offsets().begin<size_type>() + offset(); } /** * @brief Return pointer to the position that is one past the last offset * * This function return the position that is one past the last offset of the lists column. * Since the current lists column may be a sliced column, this offsets_end() iterator should not * be computed using the size of the offsets() child column, which is also the offsets of the * entire original (non-sliced) lists column. * * @return Pointer to one past the last offset */ [[nodiscard]] offset_iterator offsets_end() const noexcept { return offsets_begin() + size() + 1; } }; /** @} */ // end of group } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/contains.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { /** * @addtogroup lists_contains * @{ * @file */ /** * @brief Create a column of `bool` values indicating whether the specified scalar * is an element of each row of a list column. * * The output column has as many elements as the input `lists` column. * Output `column[i]` is set to true if the lists row `lists[i]` contains the value * specified in `search_key`. Otherwise, it is set to false. * * Output `column[i]` is set to null if one or more of the following are true: * 1. The search key `search_key` is null * 2. The list row `lists[i]` is null * * @param lists Lists column whose `n` rows are to be searched * @param search_key The scalar key to be looked up in each list row * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return BOOL8 column of `n` rows with the result of the lookup */ std::unique_ptr<column> contains( cudf::lists_column_view const& lists, cudf::scalar const& search_key, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a column of `bool` values indicating whether the list rows of the first * column contain the corresponding values in the second column * * The output column has as many elements as the input `lists` column. * Output `column[i]` is set to true if the lists row `lists[i]` contains the value * in `search_keys[i]`. Otherwise, it is set to false. * * Output `column[i]` is set to null if one or more of the following are true: * 1. The row `search_keys[i]` is null * 2. The list row `lists[i]` is null * * @param lists Lists column whose `n` rows are to be searched * @param search_keys Column of elements to be looked up in each list row. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return BOOL8 column of `n` rows with the result of the lookup */ std::unique_ptr<column> contains( cudf::lists_column_view const& lists, cudf::column_view const& search_keys, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a column of `bool` values indicating whether each row in the `lists` column * contains at least one null element. * * The output column has as many elements as the input `lists` column. * Output `column[i]` is set to null if the row `lists[i]` is null. * Otherwise, `column[i]` is set to a non-null boolean value, depending on whether that list * contains a null element. * * A row with an empty list will always return false. * Nulls inside non-null nested elements (such as lists or structs) are not considered. * * @param lists Lists column whose `n` rows are to be searched. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return BOOL8 column of `n` rows with the result of the lookup */ std::unique_ptr<column> contains_nulls( cudf::lists_column_view const& lists, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Option to choose whether `index_of()` returns the first or last match * of a search key in a list row */ enum class duplicate_find_option : int32_t { FIND_FIRST = 0, ///< Finds first instance of a search key in a list row. FIND_LAST ///< Finds last instance of a search key in a list row. }; /** * @brief Create a column of values indicating the position of a search key * within each list row in the `lists` column * * The output column has as many elements as there are rows in the input `lists` column. * Output `column[i]` contains a 0-based index indicating the position of the search key * in each list, counting from the beginning of the list. * Note: * 1. If the `search_key` is null, all output rows are set to null. * 2. If the row `lists[i]` is null, `output[i]` is also null. * 3. If the row `lists[i]` does not contain the `search_key`, `output[i]` is set to `-1`. * 4. In all other cases, `output[i]` is set to a non-negative `size_type` index. * * If the `find_option` is set to `FIND_FIRST`, the position of the first match for * `search_key` is returned. * If `find_option == FIND_LAST`, the position of the last match in the list row is * returned. * * @throw cudf::data_type_error If `search_keys` type does not match the element type in `lists` * * @param lists Lists column whose `n` rows are to be searched * @param search_key The scalar key to be looked up in each list row * @param find_option Whether to return the position of the first match (`FIND_FIRST`) or * last (`FIND_LAST`) * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return column of `n` rows with the location of the `search_key` */ std::unique_ptr<column> index_of( cudf::lists_column_view const& lists, cudf::scalar const& search_key, duplicate_find_option find_option = duplicate_find_option::FIND_FIRST, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a column of values indicating the position of a search key * row within the corresponding list row in the `lists` column * * The output column has as many elements as there are rows in the input `lists` column. * Output `column[i]` contains a 0-based index indicating the position of each search key * row in its corresponding list row, counting from the beginning of the list. * Note: * 1. If `search_keys[i]` is null, `output[i]` is also null. * 2. If the row `lists[i]` is null, `output[i]` is also null. * 3. If the row `lists[i]` does not contain `search_key[i]`, `output[i]` is set to `-1`. * 4. In all other cases, `output[i]` is set to a non-negative `size_type` index. * * If the `find_option` is set to `FIND_FIRST`, the position of the first match for * `search_key` is returned. * If `find_option == FIND_LAST`, the position of the last match in the list row is * returned. * * @throw cudf::logic_error If `search_keys` does not match `lists` in its number of rows * @throw cudf::data_type_error If `search_keys` type does not match the element type in `lists` * * @param lists Lists column whose `n` rows are to be searched * @param search_keys A column of search keys to be looked up in each corresponding row of * `lists` * @param find_option Whether to return the position of the first match (`FIND_FIRST`) or * last (`FIND_LAST`) * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return column of `n` rows with the location of the `search_key` */ std::unique_ptr<column> index_of( cudf::lists_column_view const& lists, cudf::column_view const& search_keys, duplicate_find_option find_option = duplicate_find_option::FIND_FIRST, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/count_elements.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { /** * @addtogroup lists_elements * @{ * @file */ /** * @brief Returns a numeric column containing the number of rows in * each list element in the given lists column. * * The output column will have the same number of rows as the * input lists column. Each `output[i]` will be `input[i].size()`. * * @code{.pseudo} * l = { {1, 2, 3}, {4}, {5, 6} } * r = count_elements(l) * r is now {3, 1, 2} * @endcode * * Any null input element will result in a corresponding null entry * in the output column. * * @param input Input lists column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory * @return New column with the number of elements for each row */ std::unique_ptr<column> count_elements( lists_column_view const& input, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of lists_elements group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/sorting.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { /** * @addtogroup lists_sort * @{ * @file */ /** * @brief Segmented sort of the elements within a list in each row of a list column. * * `source_column` with depth 1 is only supported. * * * @code{.pseudo} * source_column : [{4, 2, 3, 1}, {1, 2, NULL, 4}, {-10, 10, 0}] * * Ascending, Null After : [{1, 2, 3, 4}, {1, 2, 4, NULL}, {-10, 0, 10}] * Ascending, Null Before : [{1, 2, 3, 4}, {NULL, 1, 2, 4}, {-10, 0, 10}] * Descending, Null After : [{4, 3, 2, 1}, {NULL, 4, 2, 1}, {10, 0, -10}] * Descending, Null Before : [{4, 3, 2, 1}, {4, 2, 1, NULL}, {10, 0, -10}] * @endcode * * @param source_column View of the list column of numeric types to sort * @param column_order The desired sort order * @param null_precedence The desired order of null compared to other elements in the list * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource to allocate any returned objects * @return list column with elements in each list sorted. * */ std::unique_ptr<column> sort_lists( lists_column_view const& source_column, order column_order, null_order null_precedence, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Segmented sort of the elements within a list in each row of a list column using stable * sort. * * @copydoc cudf::lists::sort_lists */ std::unique_ptr<column> stable_sort_lists( lists_column_view const& source_column, order column_order, null_order null_precedence, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/extract.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { /** * @addtogroup lists_extract * @{ * @file */ /** * @brief Create a column where each row is the element at position `index` from the corresponding * sublist in the input `lists_column`. * * Output `column[i]` is set from element `lists_column[i][index]`. * If `index` is larger than the size of the sublist at `lists_column[i]` * then output `column[i] = null`. * * @code{.pseudo} * l = { {1, 2, 3}, {4}, {5, 6} } * r = extract_list_element(l, 1) * r is now {2, null, 6} * @endcode * * The `index` may also be negative in which case the row retrieved is offset * from the end of each sublist. * * @code{.pseudo} * l = { {"a"}, {"b", "c"}, {"d", "e", "f"} } * r = extract_list_element(l, -1) * r is now {"a", "c", "f"} * @endcode * * Any input where `lists_column[i] == null` will produce * output `column[i] = null`. Also, any element where * `lists_column[i][index] == null` will produce * output `column[i] = null`. * * @param lists_column Column to extract elements from. * @param index The row within each sublist to retrieve. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return Column of extracted elements. */ std::unique_ptr<column> extract_list_element( lists_column_view const& lists_column, size_type index, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Create a column where each row is a single element from the corresponding sublist * in the input `lists_column`, selected using indices from the `indices` column. * * Output `column[i]` is set from element `lists_column[i][indices[i]]`. * If `indices[i]` is larger than the size of the sublist at `lists_column[i]` * then output `column[i] = null`. * Similarly, if `indices[i]` is `null`, then `column[i] = null`. * * @code{.pseudo} * l = { {1, 2, 3}, {4}, {5, 6} } * r = extract_list_element(l, {0, null, 2}) * r is now {1, null, null} * @endcode * * `indices[i]` may also be negative, in which case the row retrieved is offset * from the end of each sublist. * * @code{.pseudo} * l = { {"a"}, {"b", "c"}, {"d", "e", "f"} } * r = extract_list_element(l, {-1, -2, -4}) * r is now {"a", "b", null} * @endcode * * Any input where `lists_column[i] == null` produces output `column[i] = null`. * Any input where `lists_column[i][indices[i]] == null` produces output `column[i] = null`. * * @param lists_column Column to extract elements from. * @param indices The column whose rows indicate the element index to be retrieved from each list * row. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return Column of extracted elements. * @throws cudf::logic_error If the sizes of `lists_column` and `indices` do not match. */ std::unique_ptr<column> extract_list_element( lists_column_view const& lists_column, column_view const& indices, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/lists/explode.hpp
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <rmm/mr/device/per_device_resource.hpp> #include <memory> namespace cudf { /** * @addtogroup column_reshape * @{ * @file * @brief Column APIs for explore list columns */ /** * @brief Explodes a list column's elements. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. Example: * ``` * [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * returns * [5, 100], * [10, 100], * [15, 100], * [20, 200], * [25, 200], * [30, 300], * ``` * * Nulls and empty lists propagate in different ways depending on what is null or empty. *``` * [[5,null,15], 100], * [null, 200], * [[], 300], * returns * [5, 100], * [null, 100], * [15, 100], * ``` * Note that null lists are not included in the resulting table, but nulls inside * lists and empty lists will be represented with a null entry for that column in that row. * * @param input_table Table to explode. * @param explode_column_idx Column index to explode inside the table. * @param mr Device memory resource used to allocate the returned column's device memory. * * @return A new table with explode_col exploded. */ std::unique_ptr<table> explode( table_view const& input_table, size_type explode_column_idx, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Explodes a list column's elements and includes a position column. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. A position * column is added that has the index inside the original list for each row. Example: * ``` * [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * returns * [0, 5, 100], * [1, 10, 100], * [2, 15, 100], * [0, 20, 200], * [1, 25, 200], * [0, 30, 300], * ``` * * Nulls and empty lists propagate in different ways depending on what is null or empty. *``` * [[5,null,15], 100], * [null, 200], * [[], 300], * returns * [0, 5, 100], * [1, null, 100], * [2, 15, 100], * ``` * Note that null lists are not included in the resulting table, but nulls inside * lists and empty lists will be represented with a null entry for that column in that row. * * @param input_table Table to explode. * @param explode_column_idx Column index to explode inside the table. * @param mr Device memory resource used to allocate the returned column's device memory. * * @return A new table with exploded value and position. The column order of return table is * [cols before explode_input, explode_position, explode_value, cols after explode_input]. */ std::unique_ptr<table> explode_position( table_view const& input_table, size_type explode_column_idx, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Explodes a list column's elements retaining any null entries or empty lists inside. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. Example: * ``` * [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * returns * [5, 100], * [10, 100], * [15, 100], * [20, 200], * [25, 200], * [30, 300], * ``` * * Nulls and empty lists propagate as null entries in the result. *``` * [[5,null,15], 100], * [null, 200], * [[], 300], * returns * [5, 100], * [null, 100], * [15, 100], * [null, 200], * [null, 300], * ``` * * @param input_table Table to explode. * @param explode_column_idx Column index to explode inside the table. * @param mr Device memory resource used to allocate the returned column's device memory. * * @return A new table with explode_col exploded. */ std::unique_ptr<table> explode_outer( table_view const& input_table, size_type explode_column_idx, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Explodes a list column's elements retaining any null entries or empty lists and includes a *position column. * * Any list is exploded, which means the elements of the list in each row are expanded into new rows * in the output. The corresponding rows for other columns in the input are duplicated. A position * column is added that has the index inside the original list for each row. Example: * ``` * [[5,10,15], 100], * [[20,25], 200], * [[30], 300], * returns * [0, 5, 100], * [1, 10, 100], * [2, 15, 100], * [0, 20, 200], * [1, 25, 200], * [0, 30, 300], * ``` * * Nulls and empty lists propagate as null entries in the result. *``` * [[5,null,15], 100], * [null, 200], * [[], 300], * returns * [0, 5, 100], * [1, null, 100], * [2, 15, 100], * [0, null, 200], * [0, null, 300], * ``` * * @param input_table Table to explode. * @param explode_column_idx Column index to explode inside the table. * @param mr Device memory resource used to allocate the returned column's device memory. * * @return A new table with explode_col exploded. */ std::unique_ptr<table> explode_outer_position( table_view const& input_table, size_type explode_column_idx, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/gather.cuh
/* * 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. */ #pragma once #include <cudf/column/column_factories.hpp> #include <cudf/detail/get_value.cuh> #include <cudf/detail/sizes_to_offsets_iterator.cuh> #include <cudf/lists/lists_column_view.hpp> #include <cudf/utilities/bit.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/functional.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/transform.h> namespace cudf { namespace lists { namespace detail { /** * @brief The information needed to create an iterator to gather level N+1 * * @ref make_gather_data */ struct gather_data { // The offsets column from our parent list (level N) std::unique_ptr<column> offsets; // For each offset in the above offsets column, the original offset value // prior to being gathered. // Example: // If the offsets[3] == 6 (representing row 3 of the new column) // And the original value it was itself gathered from was 15, then // base_offsets[3] == 15 rmm::device_uvector<int32_t> base_offsets; // size of the gather map that will be generated from this data size_type gather_map_size; }; /** * @copydoc cudf::make_gather_data(cudf::lists_column_view const& source_column, * MapItType gather_map, * size_type gather_map_size, * rmm::cuda_stream_view stream, * rmm::mr::device_memory_resource* mr) * * @param prev_base_offsets The buffer backing the base offsets used in the gather map. We can * free this buffer before allocating the new one to keep peak memory * usage down. */ template <bool NullifyOutOfBounds, typename MapItType> gather_data make_gather_data(cudf::lists_column_view const& source_column, MapItType gather_map, size_type gather_map_size, rmm::device_uvector<int32_t>&& prev_base_offsets, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { // size of the gather map is the # of output rows size_type output_count = gather_map_size; // offsets of the source column int32_t const* src_offsets{source_column.offsets().data<int32_t>() + source_column.offset()}; size_type const src_size = source_column.size(); auto const source_column_nullmask = source_column.null_mask(); auto sizes_itr = cudf::detail::make_counting_transform_iterator( 0, [source_column_nullmask, source_column_offset = source_column.offset(), gather_map, output_count, src_offsets, src_size] __device__(int32_t index) -> int32_t { int32_t offset_index = index < output_count ? gather_map[index] : 0; // if this is an invalid index, this will be a NULL list if (NullifyOutOfBounds && ((offset_index < 0) || (offset_index >= src_size))) { return 0; } // If the source row is null, the output row size must be 0. if (source_column_nullmask != nullptr && not cudf::bit_is_set(source_column_nullmask, source_column_offset + offset_index)) { return 0; } // the length of this list return src_offsets[offset_index + 1] - src_offsets[offset_index]; }); auto [dst_offsets_c, map_size] = cudf::detail::make_offsets_child_column(sizes_itr, sizes_itr + output_count, stream, mr); // handle sliced columns size_type const shift = source_column.offset() > 0 ? cudf::detail::get_value<size_type>(source_column.offsets(), source_column.offset(), stream) : 0; // generate the base offsets rmm::device_uvector<int32_t> base_offsets = rmm::device_uvector<int32_t>(output_count, stream); thrust::transform( rmm::exec_policy_nosync(stream), gather_map, gather_map + output_count, base_offsets.data(), [source_column_nullmask, source_column_offset = source_column.offset(), src_offsets, src_size, shift] __device__(int32_t index) { // if this is an invalid index, this will be a NULL list if (NullifyOutOfBounds && ((index < 0) || (index >= src_size))) { return 0; } // If the source row is null, the output row size must be 0. if (source_column_nullmask != nullptr && not cudf::bit_is_set(source_column_nullmask, source_column_offset + index)) { return 0; } return src_offsets[index] - shift; }); // Retrieve size of the resulting gather map for level N+1 (the last offset) auto const child_gather_map_size = static_cast<size_type>(map_size); return {std::move(dst_offsets_c), std::move(base_offsets), child_gather_map_size}; } /** * @brief Generates the data needed to create a `gather_map` for the next level of * recursion in a hierarchy of list columns. * * Gathering from a single level of a list column is similar to gathering from * a string column. Each row represents a list bounded by offsets. * * @code{.pseudo} * Example: * Level 0 : List<List<int>> * Size : 3 * Offsets : [0, 2, 5, 10] * * This represents a column with 3 rows. * Row 0 has 2 elements (bounded by offsets 0,2) * Row 1 has 3 elements (bounded by offsets 2,5) * Row 2 has 5 elements (bounded by offsets 5,10) * * If we wanted to gather rows 0 and 2 the offsets for our outgoing column * would be the compacted ranges (0,2) and (5,10). The level 1 column * then looks like * * Level 1 : List<int> * Size : 2 * Offsets : [0, 2, 7] * * However, we need to then gather one level further, because at the bottom we have * a column of integers. We cannot gather the elements in the ranges (0, 2) and (2, 7). * Instead, we have to gather elements in the ranges from the Level 0 column (0, 2) and (5, 10). * So our gather_map iterator will need to know these "base" offsets to index properly. * Specifically: * * Offsets : [0, 2, 7] The offsets for Level 1 * Base Offsets : [0, 5] The corresponding base offsets from Level 0 * * Using this we can create an iterator that generates the sequence which properly indexes the * final integer values we want to gather. * * [0, 1, 5, 6, 7, 8, 9] * @endcode * * Thinking generally, this means that to produce a gather_map for level N+1, we need to use the * offsets from level N and the "base" offsets from level N-1. So we are always carrying along * one extra buffer of these "base" offsets which keeps our memory usage well controlled. * * @code{.pseudo} * Example: * * "column of lists of lists of ints" * { * { * {2, 3}, {4, 5} * }, * { * {6, 7, 8}, {9, 10, 11}, {12, 13, 14} * }, * { * {15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18} * } * } * * List<List<int32_t>>: * Length : 3 * Offsets : 0, 2, 5, 10 * Children : * List<int32_t>: * Length : 10 * Offsets : 0, 2, 4, 7, 10, 13, 15, 17, 19, 21, 23 * Children : * 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 17, 18, 17, 18, 17, 18 * * Final column, doing gather([0, 2]) * * { * { * {2, 3}, {4, 5} * }, * { * {15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18} * } * } * * List<List<int32_t>>: * Length : 2 * Offsets : 0, 2, 7 * Children : * List<int32_t>: * Length : 7 * Offsets : 0, 2, 4, 6, 8, 10, 12, 14 * Children : * 2, 3, 4, 5, 15, 16, 17, 18, 17, 18, 17, 18, 17, 18 * @endcode * * @tparam MapItType Iterator type to access the incoming column. * @tparam NullifyOutOfBounds Nullify values in `gather_map` that are out of bounds * @param source_column View into the column to gather from * @param gather_map Iterator access to the gather map for `source_column` map * @param gather_map_size Size of the gather map. * @param stream CUDA stream on which to execute kernels * @param mr Memory resource to use for all allocations * * @returns The gather_data struct needed to construct the gather map for the * next level of recursion. */ template <bool NullifyOutOfBounds, typename MapItType> gather_data make_gather_data(cudf::lists_column_view const& source_column, MapItType gather_map, size_type gather_map_size, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { return make_gather_data<NullifyOutOfBounds, MapItType>( source_column, gather_map, gather_map_size, rmm::device_uvector<int32_t>{0, stream, mr}, stream, mr); } /** * @brief Gather a list column from a hierarchy of list columns. * * The recursion continues from here at least 1 level further. * * @param list View into the list column to gather from * @param gd The gather_data needed to construct a gather map iterator for this level * @param stream CUDA stream on which to execute kernels * @param mr Memory resource to use for all allocations * * @returns column with elements gathered based on `gather_data` */ std::unique_ptr<column> gather_list_nested(lists_column_view const& list, gather_data& gd, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Gather a leaf column from a hierarchy of list columns. * * The recursion terminates here. * * @param column View into the column to gather from * @param gd The gather_data needed to construct a gather map iterator for this level * @param stream CUDA stream on which to execute kernels * @param mr Memory resource to use for all allocations * * @returns column with elements gathered based on `gather_data` */ std::unique_ptr<column> gather_list_leaf(column_view const& column, gather_data const& gd, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::segmented_gather(lists_column_view const& source_column, * lists_column_view const& gather_map_list, * out_of_bounds_policy bounds_policy, * rmm::mr::device_memory_resource* mr) * * @param stream CUDA stream on which to execute kernels */ std::unique_ptr<column> segmented_gather(lists_column_view const& source_column, lists_column_view const& gather_map_list, out_of_bounds_policy bounds_policy, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/copying.hpp
/* * Copyright (c) 2020-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 <cudf/lists/lists_column_view.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @brief Returns a new lists column created from a subset of the * lists column. The subset of lists selected is between start (inclusive) * and end (exclusive). * * @code{.pseudo} * Example: * s1 = {{1, 2, 3}, {4, 5}, {6, 7}, {}, {8, 9}} * s2 = slice( s1, 1, 4) * s2 is {{4, 5}, {6, 7}, {}} * @endcode * * @param lists Lists instance for this operation. * @param start Index to first list to select in the column * @param end One past the index to last list to select in the column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory. * @return New lists column of size (end - start) */ std::unique_ptr<cudf::column> copy_slice(lists_column_view const& lists, size_type start, size_type end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/scatter_helper.cuh
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/lists/list_device_view.cuh> #include <cudf/lists/lists_column_view.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <memory> namespace cudf { namespace lists { namespace detail { /** * @brief Holder for a list row's positional information, without * also holding a reference to the list column. * * Analogous to the list_view, this class is default constructable, * and can thus be stored in rmm::device_uvector. It is used to represent * the results of a `scatter()` operation; a device_uvector may hold * several instances of unbound_list_view, each with a flag indicating * whether it came from the scatter source or target. Each instance * may later be "bound" to the appropriate source/target column, to * reconstruct the list_view. */ struct unbound_list_view { /** * @brief Flag type, indicating whether this list row originated from * the source or target column, in `scatter()`. */ enum class label_type : bool { SOURCE, TARGET }; using lists_column_device_view = cudf::detail::lists_column_device_view; using list_device_view = cudf::list_device_view; unbound_list_view() = default; unbound_list_view(unbound_list_view const&) = default; unbound_list_view(unbound_list_view&&) = default; unbound_list_view& operator=(unbound_list_view const&) = default; unbound_list_view& operator=(unbound_list_view&&) = default; /** * @brief __device__ Constructor, for use from `scatter()`. * * @param scatter_source_label Whether the row came from source or target * @param lists_column The actual source/target lists column * @param row_index Index of the row in lists_column that this instance represents */ __device__ inline unbound_list_view(label_type scatter_source_label, cudf::detail::lists_column_device_view const& lists_column, size_type const& row_index) : _label{scatter_source_label}, _row_index{row_index} { _size = list_device_view{lists_column, row_index}.size(); } /** * @brief __device__ Constructor, for use when constructing the child column * of a scattered list column * * @param scatter_source_label Whether the row came from source or target * @param row_index Index of the row that this instance represents in the source/target column * @param size The number of elements in this list row */ __device__ inline unbound_list_view(label_type scatter_source_label, size_type const& row_index, size_type const& size) : _label{scatter_source_label}, _row_index{row_index}, _size{size} { } /** * @brief Returns number of elements in this list row. */ [[nodiscard]] __device__ inline size_type size() const { return _size; } /** * @brief Returns whether this row came from the `scatter()` source or target */ [[nodiscard]] __device__ inline label_type label() const { return _label; } /** * @brief Returns the index in the source/target column */ [[nodiscard]] __device__ inline size_type row_index() const { return _row_index; } /** * @brief Binds to source/target column (depending on SOURCE/TARGET labels), * to produce a bound list_view. * * @param scatter_source Source column for the scatter operation * @param scatter_target Target column for the scatter operation * @return A (bound) list_view for the row that this object represents */ [[nodiscard]] __device__ inline list_device_view bind_to_column( lists_column_device_view const& scatter_source, lists_column_device_view const& scatter_target) const { return list_device_view(_label == label_type::SOURCE ? scatter_source : scatter_target, _row_index); } private: // Note: Cannot store reference to list column, because of storage in device_uvector. // Only keep track of whether this list row came from the source or target of scatter. label_type _label{ label_type::SOURCE}; // Whether this list row came from the scatter source or target. size_type _row_index{}; // Row index in the Lists column. size_type _size{}; // Number of elements in *this* list row. }; std::unique_ptr<column> build_lists_child_column_recursive( data_type child_column_type, rmm::device_uvector<unbound_list_view> const& list_vector, cudf::column_view const& list_offsets, cudf::lists_column_view const& source_lists_column_view, cudf::lists_column_view const& target_lists_column_view, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/dremel.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <rmm/device_uvector.hpp> namespace cudf::detail { /** * @brief Device view for `dremel_data`. * * @see the `dremel_data` struct for more info. */ struct dremel_device_view { size_type const* offsets; uint8_t const* rep_levels; uint8_t const* def_levels; size_type const leaf_data_size; uint8_t const max_def_level; }; /** * @brief Dremel data that describes one nested type column * * @see get_dremel_data() for more info. */ struct dremel_data { rmm::device_uvector<size_type> dremel_offsets; rmm::device_uvector<uint8_t> rep_level; rmm::device_uvector<uint8_t> def_level; size_type const leaf_data_size; uint8_t const max_def_level; operator dremel_device_view() const { return dremel_device_view{ dremel_offsets.data(), rep_level.data(), def_level.data(), leaf_data_size, max_def_level}; } }; /** * @brief Get the dremel offsets and repetition and definition levels for a LIST column * * Dremel is a query system created by Google for ad hoc data analysis. The Dremel engine is * described in depth in the paper "Dremel: Interactive Analysis of Web-Scale * Datasets" (https://research.google/pubs/pub36632/). One of the key components of Dremel * is an encoding that converts record-like data into a columnar store for efficient memory * accesses. The Parquet file format uses Dremel encoding to handle nested data, so libcudf * requires some facilities for working with this encoding. Furthermore, libcudf leverages * Dremel encoding as a means for performing lexicographic comparisons of nested columns. * * Dremel encoding is built around two concepts, the repetition and definition levels. * Since describing them thoroughly is out of scope for this docstring, here are a couple of * blogs that provide useful background: * * http://www.goldsborough.me/distributed-systems/2019/05/18/21-09-00-a_look_at_dremel/ * https://akshays-blog.medium.com/wrapping-head-around-repetition-and-definition-levels-in-dremel-powering-bigquery-c1a33c9695da * https://blog.twitter.com/engineering/en_us/a/2013/dremel-made-simple-with-parquet * * The remainder of this documentation assumes familiarity with the Dremel concepts. * * Dremel offsets are the per row offsets into the repetition and definition level arrays for a * column. * Example: * ``` * col = {{1, 2, 3}, { }, {5, 6}} * dremel_offsets = { 0, 3, 4, 6} * rep_level = { 0, 1, 1, 0, 0, 1} * def_level = { 1, 1, 1, 0, 1, 1} * ``` * * The repetition and definition level values are ideally computed using a recursive call over a * nested structure but in order to better utilize GPU resources, this function calculates them * with a bottom up merge method. * * Given a LIST column of type `List<List<int>>` like so: * ``` * col = { * [], * [[], [1, 2, 3], [4, 5]], * [[]] * } * ``` * We can represent it in cudf format with two level of offsets like this: * ``` * Level 0 offsets = {0, 0, 3, 5, 6} * Level 1 offsets = {0, 0, 3, 5, 5} * Values = {1, 2, 3, 4, 5} * ``` * The desired result of this function is the repetition and definition level values that * correspond to the data values: * ``` * col = {[], [[], [1, 2, 3], [4, 5]], [[]]} * def = { 0 1, 2, 2, 2, 2, 2, 1 } * rep = { 0, 0, 0, 2, 2, 1, 2, 0 } * ``` * * Since repetition and definition levels arrays contain a value for each empty list, the size of * the rep/def level array can be given by * ``` * rep_level.size() = size of leaf column + number of empty lists in level 0 * + number of empty lists in level 1 ... * ``` * * We start with finding the empty lists in the penultimate level and merging it with the indices * of the leaf level. The values for the merge are the definition and repetition levels * ``` * empties at level 1 = {0, 5} * def values at 1 = {1, 1} * rep values at 1 = {1, 1} * indices at leaf = {0, 1, 2, 3, 4} * def values at leaf = {2, 2, 2, 2, 2} * rep values at leaf = {2, 2, 2, 2, 2} * ``` * * merged def values = {1, 2, 2, 2, 2, 2, 1} * merged rep values = {1, 2, 2, 2, 2, 2, 1} * * The size of the rep/def values is now larger than the leaf values and the offsets need to be * adjusted in order to point to the correct start indices. We do this with an exclusive scan over * the indices of offsets of empty lists and adding to existing offsets. * ``` * Level 1 new offsets = {0, 1, 4, 6, 7} * ``` * Repetition values at the beginning of a list need to be decremented. We use the new offsets to * scatter the rep value. * ``` * merged rep values = {1, 2, 2, 2, 2, 2, 1} * scatter (1, new offsets) * new offsets = {0, 1, 4, 6, 7} * new rep values = {1, 1, 2, 2, 1, 2, 1} * ``` * * Similarly we merge up all the way till level 0 offsets * * STRUCT COLUMNS : * In case of struct columns, we don't have to merge struct levels with their children because a * struct is the same size as its children. e.g. for a column `struct<int, float>`, if the row `i` * is null, then the children columns `int` and `float` are also null at `i`. They also have the * null entry represented in their respective null masks. So for any case of strictly struct based * nesting, we can get the definition levels merely by iterating over the nesting for the same row. * * In case struct and lists are intermixed, the definition levels of all the contiguous struct * levels can be constructed using the aforementioned iterative method. Only when we reach a list * level, we need to do a merge with the subsequent level. * * So, for a column like `struct<list<int>>`, we are going to merge between the levels `struct<list` * and `int`. * For a column like `list<struct<int>>`, we are going to merge between `list` and `struct<int>`. * * In general, one nesting level is the list level and any struct level that precedes it. * * A few more examples to visualize the partitioning of column hierarchy into nesting levels: * (L is list, S is struct, i is integer(leaf data level), angle brackets omitted) * ``` * 1. LSi = L Si * - | -- * * 2. LLSi = L L Si * - | - | -- * * 3. SSLi = SSL i * --- | - * * 4. LLSLSSi = L L SL SSi * - | - | -- | --- * ``` * * @param input Column of LIST type * @param nullability Pre-determined nullability at each list level. Empty means infer from * `input` * @param output_as_byte_array if `true`, then any nested list level that has a child of type * `uint8_t` will be considered as the last level * @param stream CUDA stream used for device memory operations and kernel launches. * @return A struct containing dremel data */ dremel_data get_dremel_data(column_view input, std::vector<uint8_t> nullability, bool output_as_byte_array, rmm::cuda_stream_view stream); /** * @brief Get Dremel offsets, repetition levels, and modified definition levels to be used for * lexicographical comparators. The modified definition levels are produced by treating * each nested column in the input as nullable * * @param input Column of LIST type * @param nullability Pre-determined nullability at each list level. Empty means infer from * `input` * @param output_as_byte_array if `true`, then any nested list level that has a child of type * `uint8_t` will be considered as the last level * @param stream CUDA stream used for device memory operations and kernel launches. * @return A struct containing dremel data */ dremel_data get_comparator_data(column_view input, std::vector<uint8_t> nullability, bool output_as_byte_array, rmm::cuda_stream_view stream); } // namespace cudf::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/interleave_columns.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/table/table_view.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @brief Returns a single column by interleaving rows of the given table of list elements. * * @code{.pseudo} * s1 = [{0, 1}, {2, 3, 4}, {5}, {}, {6, 7}] * s2 = [{8}, {9}, {}, {10, 11, 12}, {13, 14, 15, 16}] * r = lists::interleave_columns(s1, s2) * r is now [{0, 1}, {8}, {2, 3, 4}, {9}, {5}, {}, {}, {10, 11, 12}, {6, 7}, {13, 14, 15, 16}] * @endcode * * @throws cudf::logic_error if any column of the input table is not a lists columns. * @throws cudf::logic_error if any lists column contains nested typed entry. * @throws cudf::logic_error if all lists columns do not have the same entry type. * * @param input Table containing lists columns to interleave. * @param has_null_mask A boolean flag indicating that the input columns have a null mask. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return The interleaved columns as a single column. */ std::unique_ptr<column> interleave_columns(table_view const& input, bool has_null_mask, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/stream_compaction.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <rmm/mr/device/device_memory_resource.hpp> namespace cudf::lists::detail { /** * @copydoc cudf::lists::apply_boolean_mask(lists_column_view const&, lists_column_view const&, * rmm::mr::device_memory_resource*) * * @param stream CUDA stream used for device memory operations and kernel launches */ std::unique_ptr<column> apply_boolean_mask(lists_column_view const& input, lists_column_view const& boolean_mask, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::list::distinct * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> distinct(lists_column_view const& input, null_equality nulls_equal, nan_equality nans_equal, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace cudf::lists::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/lists_column_factories.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/mr/device/per_device_resource.hpp> namespace cudf { namespace lists { namespace detail { /** * @brief Internal API to construct a lists column from a `list_scalar`, for public * use, use `cudf::make_column_from_scalar`. * * @param[in] value The `list_scalar` to construct from * @param[in] size The number of rows for the output column. * @param[in] stream CUDA stream used for device memory operations and kernel launches. * @param[in] mr Device memory resource used to allocate the returned column's device memory. */ std::unique_ptr<cudf::column> make_lists_column_from_scalar(list_scalar const& value, size_type size, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Create an empty lists column. * * A list column requires a child type and so cannot be created with `make_empty_column`. * * @param child_type The type used for the empty child column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory */ std::unique_ptr<column> make_empty_lists_column(data_type child_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @brief Create a lists column with all null rows. * * @param size Size of the output lists column * @param child_type The type used for the empty child column * @param stream CUDA stream used for device memory operations and kernel launches * @param mr Device memory resource used to allocate the returned column's device memory */ std::unique_ptr<column> make_all_nulls_lists_column(size_type size, data_type child_type, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/reverse.hpp
/* * 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. */ #pragma once #include <cudf/lists/reverse.hpp> namespace cudf::lists::detail { /** * @copydoc cudf::lists::reverse * @param stream CUDA stream used for device memory operations and kernel launches */ std::unique_ptr<column> reverse(lists_column_view const& input, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace cudf::lists::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/combine.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/combine.hpp> #include <cudf/lists/lists_column_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @copydoc cudf::lists::concatenate_rows * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> concatenate_rows(table_view const& input, concatenate_null_policy null_policy, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::concatenate_list_elements * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> concatenate_list_elements(column_view const& input, concatenate_null_policy null_policy, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/set_operations.hpp
/* * 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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/types.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/mr/device/device_memory_resource.hpp> namespace cudf::lists::detail { /** * @copydoc cudf::list::have_overlap * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> have_overlap(lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal, nan_equality nans_equal, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::list::intersect_distinct * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> intersect_distinct(lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal, nan_equality nans_equal, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::list::union_distinct * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> union_distinct(lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal, nan_equality nans_equal, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::list::difference_distinct * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> difference_distinct(lists_column_view const& lhs, lists_column_view const& rhs, null_equality nulls_equal, nan_equality nans_equal, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** @} */ // end of group } // namespace cudf::lists::detail
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/concatenate.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. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @brief Returns a single column by concatenating the given vector of * lists columns. * * @code{.pseudo} * s1 = [{0, 1}, {2, 3, 4, 5, 6}] * s2 = [{7, 8, 9}, {10, 11}] * r = concatenate(s1, s2) * r is now [{0, 1}, {2, 3, 4, 5, 6}, {7, 8, 9}, {10, 11}] * @endcode * * @param columns Vector of lists columns to concatenate. * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory. * @return New column with concatenated results. */ std::unique_ptr<column> concatenate(host_span<column_view const> columns, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/contains.hpp
/* * 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. */ #pragma once #include <cudf/lists/contains.hpp> #include <cudf/lists/lists_column_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @copydoc cudf::lists::index_of(cudf::lists_column_view const&, * cudf::scalar const&, * duplicate_find_option, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> index_of(cudf::lists_column_view const& lists, cudf::scalar const& search_key, cudf::lists::duplicate_find_option find_option, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::index_of(cudf::lists_column_view const&, * cudf::column_view const&, * duplicate_find_option, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> index_of(cudf::lists_column_view const& lists, cudf::column_view const& search_keys, cudf::lists::duplicate_find_option find_option, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::contains(cudf::lists_column_view const&, * cudf::scalar const&, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> contains(cudf::lists_column_view const& lists, cudf::scalar const& search_key, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::contains(cudf::lists_column_view const&, * cudf::column_view const&, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> contains(cudf::lists_column_view const& lists, cudf::column_view const& search_keys, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/sorting.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/lists/lists_column_view.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @copydoc cudf::lists::sort_lists * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> sort_lists(lists_column_view const& input, order column_order, null_order null_precedence, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::stable_sort_lists * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> stable_sort_lists(lists_column_view const& input, order column_order, null_order null_precedence, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/scatter.cuh
/* * 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. */ #pragma once #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/null_mask.hpp> #include <cudf/lists/detail/scatter_helper.cuh> #include <cudf/lists/list_device_view.cuh> #include <cudf/strings/detail/strings_children.cuh> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_checks.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/distance.h> #include <thrust/iterator/constant_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/scatter.h> #include <thrust/sequence.h> #include <thrust/transform.h> #include <cinttypes> namespace cudf { namespace lists { namespace detail { template <typename IndexIterator> rmm::device_uvector<unbound_list_view> list_vector_from_column( unbound_list_view::label_type label, cudf::detail::lists_column_device_view const& lists_column, IndexIterator index_begin, IndexIterator index_end, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto n_rows = thrust::distance(index_begin, index_end); auto vector = rmm::device_uvector<unbound_list_view>(n_rows, stream, mr); thrust::transform(rmm::exec_policy_nosync(stream), index_begin, index_end, vector.begin(), [label, lists_column] __device__(size_type row_index) { return unbound_list_view{label, lists_column, row_index}; }); return vector; } /** * @brief General implementation of scattering into list column * * Scattering `source` into `target` according to `scatter_map`. * The view order of `source` and `target` can be specified by * `source_vector` and `target_vector` respectively. * * @tparam MapIterator must produce index values within the target column. * * @param source_vector A vector of `unbound_list_view` into source column * @param target_vector A vector of `unbound_list_view` into target column * @param scatter_map_begin Start iterator of scatter map * @param scatter_map_end End iterator of scatter map * @param source Source column view * @param target Target column view * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return New lists column. */ template <typename MapIterator> std::unique_ptr<column> scatter_impl(rmm::device_uvector<unbound_list_view> const& source_vector, rmm::device_uvector<unbound_list_view>& target_vector, MapIterator scatter_map_begin, MapIterator scatter_map_end, column_view const& source, column_view const& target, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { CUDF_EXPECTS(column_types_equal(source, target), "Mismatched column types."); auto const child_column_type = lists_column_view(target).child().type(); // Scatter. thrust::scatter(rmm::exec_policy_nosync(stream), source_vector.begin(), source_vector.end(), scatter_map_begin, target_vector.begin()); auto const source_lists_column_view = lists_column_view(source); // Checks that this is a list column. auto const target_lists_column_view = lists_column_view(target); // Checks that target is a list column. auto list_size_begin = thrust::make_transform_iterator( target_vector.begin(), [] __device__(unbound_list_view l) { return l.size(); }); auto offsets_column = std::get<0>(cudf::detail::make_offsets_child_column( list_size_begin, list_size_begin + target.size(), stream, mr)); auto child_column = build_lists_child_column_recursive(child_column_type, target_vector, offsets_column->view(), source_lists_column_view, target_lists_column_view, stream, mr); std::vector<std::unique_ptr<column>> children; children.emplace_back(std::move(offsets_column)); children.emplace_back(std::move(child_column)); auto null_mask = target.has_nulls() ? cudf::detail::copy_bitmask(target, stream, mr) : rmm::device_buffer{0, stream, mr}; // The output column from this function only has null masks copied from the target columns. // That is still not a correct final null mask for the scatter result. // In addition, that null mask may overshadow the non-null rows (lists) scattered from the source // column. Thus, avoid using `cudf::make_lists_column` since it calls `purge_nonempty_nulls`. return std::make_unique<column>(data_type{type_id::LIST}, target.size(), rmm::device_buffer{}, std::move(null_mask), target.null_count(), std::move(children)); } /** * @brief Scatters lists into a copy of the target column * according to a scatter map. * * The scatter is performed according to the scatter iterator such that row * `scatter_map[i]` of the output column is replaced by the source list-row. * All other rows of the output column equal corresponding rows of the target table. * * If the same index appears more than once in the scatter map, the result is * undefined. * * The caller must update the null mask in the output column. * * @tparam MapIterator must produce index values within the target column. * * @param source Source column view * @param scatter_map_begin Start iterator of scatter map * @param scatter_map_end End iterator of scatter map * @param target Target column view * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return New lists column. */ template <typename MapIterator> std::unique_ptr<column> scatter(column_view const& source, MapIterator scatter_map_begin, MapIterator scatter_map_end, column_view const& target, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto const num_rows = target.size(); if (num_rows == 0) { return cudf::empty_like(target); } auto const source_device_view = column_device_view::create(source, stream); auto const scatter_map_size = thrust::distance(scatter_map_begin, scatter_map_end); auto const source_vector = list_vector_from_column(unbound_list_view::label_type::SOURCE, cudf::detail::lists_column_device_view(*source_device_view), thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(scatter_map_size), stream, mr); auto const target_device_view = column_device_view::create(target, stream); auto target_vector = list_vector_from_column(unbound_list_view::label_type::TARGET, cudf::detail::lists_column_device_view(*target_device_view), thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(num_rows), stream, mr); return scatter_impl( source_vector, target_vector, scatter_map_begin, scatter_map_end, source, target, stream, mr); } /** * @brief Scatters list scalar (a single row) into a copy of the target column * according to a scatter map. * * Returns a copy of the target column where every row specified in the `scatter_map` * is replaced by the row value. * * If the same index appears more than once in the scatter map, the result is * undefined. * * The caller must update the null mask in the output column. * * @tparam MapIterator must produce index values within the target column. * * @param slr Source scalar, specifying row data * @param scatter_map_begin Start iterator of scatter map * @param scatter_map_end End iterator of scatter map * @param target Target column view * @param stream CUDA stream used for device memory operations and kernel launches. * @param mr Device memory resource used to allocate the returned column's device memory * @return New lists column. */ template <typename MapIterator> std::unique_ptr<column> scatter(scalar const& slr, MapIterator scatter_map_begin, MapIterator scatter_map_end, column_view const& target, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr) { auto const num_rows = target.size(); if (num_rows == 0) { return cudf::empty_like(target); } auto lv = static_cast<list_scalar const*>(&slr); bool slr_valid = slr.is_valid(stream); rmm::device_buffer null_mask = slr_valid ? cudf::detail::create_null_mask(1, mask_state::UNALLOCATED, stream, mr) : cudf::detail::create_null_mask(1, mask_state::ALL_NULL, stream, mr); auto offset_column = make_numeric_column(data_type{type_to_id<size_type>()}, 2, mask_state::UNALLOCATED, stream, mr); thrust::sequence(rmm::exec_policy_nosync(stream), offset_column->mutable_view().begin<size_type>(), offset_column->mutable_view().end<size_type>(), 0, lv->view().size()); auto wrapped = column_view(data_type{type_id::LIST}, 1, nullptr, static_cast<bitmask_type const*>(null_mask.data()), slr_valid ? 0 : 1, 0, {offset_column->view(), lv->view()}); auto const source_device_view = column_device_view::create(wrapped, stream); auto const scatter_map_size = thrust::distance(scatter_map_begin, scatter_map_end); auto const source_vector = list_vector_from_column(unbound_list_view::label_type::SOURCE, cudf::detail::lists_column_device_view(*source_device_view), thrust::make_constant_iterator<size_type>(0), thrust::make_constant_iterator<size_type>(0) + scatter_map_size, stream, mr); auto const target_device_view = column_device_view::create(target, stream); auto target_vector = list_vector_from_column(unbound_list_view::label_type::TARGET, cudf::detail::lists_column_device_view(*target_device_view), thrust::make_counting_iterator<size_type>(0), thrust::make_counting_iterator<size_type>(num_rows), stream, mr); return scatter_impl( source_vector, target_vector, scatter_map_begin, scatter_map_end, wrapped, target, stream, mr); } } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf/lists
rapidsai_public_repos/cudf/cpp/include/cudf/lists/detail/extract.hpp
/* * 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. */ #pragma once #include <cudf/lists/extract.hpp> #include <cudf/lists/lists_column_view.hpp> namespace cudf { namespace lists { namespace detail { /** * @copydoc cudf::lists::extract_list_element(lists_column_view, size_type, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> extract_list_element(lists_column_view lists_column, size_type const index, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); /** * @copydoc cudf::lists::extract_list_element(lists_column_view, column_view const&, * rmm::mr::device_memory_resource*) * @param stream CUDA stream used for device memory operations and kernel launches. */ std::unique_ptr<column> extract_list_element(lists_column_view lists_column, column_view const& indices, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace lists } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/tdigest/tdigest_column_view.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column_view.hpp> #include <cudf/lists/lists_column_view.hpp> namespace cudf { namespace tdigest { /** * @brief Given a column_view containing tdigest data, an instance of this class * provides a wrapper on the compound column for tdigest operations. * * A tdigest is a "compressed" set of input scalars represented as a sorted * set of centroids (https://arxiv.org/pdf/1902.04023.pdf). * This data can be queried for quantile information. Each row in a tdigest * column represents an entire tdigest. * * The column has the following structure: * * struct { * // centroids for the digest * list { * struct { * double // mean * double // weight * } * } * // these are from the input stream, not the centroids. they are used * // during the percentile_approx computation near the beginning or * // end of the quantiles * double // min * double // max * } */ class tdigest_column_view : private column_view { public: tdigest_column_view(column_view const&); ///< Construct tdigest_column_view from a column_view tdigest_column_view(tdigest_column_view&&) = default; ///< Move constructor tdigest_column_view(tdigest_column_view const&) = default; ///< Copy constructor ~tdigest_column_view() = default; /** * @brief Copy assignment operator * * @return this object after copying the contents of the other object (copy) */ tdigest_column_view& operator=(tdigest_column_view const&) = default; /** * @brief Move assignment operator * * @return this object after moving the contents of the other object (transfer ownership) */ tdigest_column_view& operator=(tdigest_column_view&&) = default; using column_view::size; using offset_iterator = size_type const*; ///< Iterator over offsets // mean and weight column indices within tdigest inner struct columns static constexpr size_type mean_column_index{0}; ///< Mean column index static constexpr size_type weight_column_index{1}; ///< Weight column index // min and max column indices within tdigest outer struct columns static constexpr size_type centroid_column_index{0}; ///< Centroid column index static constexpr size_type min_column_index{1}; ///< Min column index static constexpr size_type max_column_index{2}; ///< Max column index /** * @brief Returns the parent column. * * @return The parent column */ [[nodiscard]] column_view parent() const; /** * @brief Returns the column of centroids * * @return The list column of centroids */ [[nodiscard]] lists_column_view centroids() const; /** * @brief Returns the internal column of mean values * * @return The internal column of mean values */ [[nodiscard]] column_view means() const; /** * @brief Returns the internal column of weight values * * @return The internal column of weight values */ [[nodiscard]] column_view weights() const; /** * @brief Returns the first min value for the column. Each row corresponds * to the minimum value for the accompanying digest. * * @return const pointer to the first min value for the column */ [[nodiscard]] double const* min_begin() const; /** * @brief Returns the first max value for the column. Each row corresponds * to the maximum value for the accompanying digest. * * @return const pointer to the first max value for the column */ [[nodiscard]] double const* max_begin() const; }; } // namespace tdigest } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/detail/groupby.hpp
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/groupby.hpp> #include <cudf/types.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <memory> #include <utility> namespace cudf { namespace groupby { namespace detail { namespace hash { /** * @brief Indicates if a set of aggregation requests can be satisfied with a * hash-based groupby implementation. * * @param requests The set of columns to aggregate and the aggregations to * perform * @return true A hash-based groupby can be used * @return false A hash-based groupby cannot be used */ bool can_use_hash_groupby(host_span<aggregation_request const> requests); // Hash-based groupby std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby( table_view const& keys, host_span<aggregation_request const> requests, null_policy include_null_keys, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace hash } // namespace detail } // namespace groupby } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/include/cudf
rapidsai_public_repos/cudf/cpp/include/cudf/detail/transpose.hpp
/* * 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. */ #pragma once #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> namespace cudf { namespace detail { /** * @copydoc cudf::transpose * * @param stream CUDA stream used for device memory operations and kernel launches. */ std::pair<std::unique_ptr<column>, table_view> transpose(table_view const& input, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr); } // namespace detail } // namespace cudf
0