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/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/join.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport make_unique, unique_ptr
from libcpp.pair cimport pair
from libcpp.utility cimport move
from rmm._lib.device_buffer cimport device_buffer
cimport cudf._lib.cpp.join as cpp_join
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport data_type, size_type, type_id
from cudf._lib.utils cimport table_view_from_columns
# The functions below return the *gathermaps* that represent
# the join result when joining on the keys `lhs` and `rhs`.
@acquire_spill_lock()
def join(list lhs, list rhs, how=None):
cdef pair[cpp_join.gather_map_type, cpp_join.gather_map_type] c_result
cdef table_view c_lhs = table_view_from_columns(lhs)
cdef table_view c_rhs = table_view_from_columns(rhs)
if how == "inner":
with nogil:
c_result = move(cpp_join.inner_join(c_lhs, c_rhs))
elif how == "left":
with nogil:
c_result = move(cpp_join.left_join(c_lhs, c_rhs))
elif how == "outer":
with nogil:
c_result = move(cpp_join.full_join(c_lhs, c_rhs))
else:
raise ValueError(f"Invalid join type {how}")
cdef Column left_rows = _gather_map_as_column(move(c_result.first))
cdef Column right_rows = _gather_map_as_column(move(c_result.second))
return left_rows, right_rows
@acquire_spill_lock()
def semi_join(list lhs, list rhs, how=None):
# left-semi and left-anti joins
cdef cpp_join.gather_map_type c_result
cdef table_view c_lhs = table_view_from_columns(lhs)
cdef table_view c_rhs = table_view_from_columns(rhs)
if how == "leftsemi":
with nogil:
c_result = move(cpp_join.left_semi_join(c_lhs, c_rhs))
elif how == "leftanti":
with nogil:
c_result = move(cpp_join.left_anti_join(c_lhs, c_rhs))
else:
raise ValueError(f"Invalid join type {how}")
cdef Column left_rows = _gather_map_as_column(move(c_result))
return left_rows, None
cdef Column _gather_map_as_column(cpp_join.gather_map_type gather_map):
# help to convert a gather map to a Column
cdef device_buffer c_empty
cdef size_type size = gather_map.get()[0].size()
cdef unique_ptr[column] c_col = move(make_unique[column](
data_type(type_id.INT32),
size,
gather_map.get()[0].release(), move(c_empty), 0))
return Column.from_unique_ptr(move(c_col))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/labeling.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool as cbool
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.labeling cimport inclusive, label_bins as cpp_label_bins
# Note that the parameter input shadows a Python built-in in the local scope,
# but I'm not too concerned about that since there's no use-case for actual
# input in this context.
@acquire_spill_lock()
def label_bins(Column input, Column left_edges, cbool left_inclusive,
Column right_edges, cbool right_inclusive):
cdef inclusive c_left_inclusive = \
inclusive.YES if left_inclusive else inclusive.NO
cdef inclusive c_right_inclusive = \
inclusive.YES if right_inclusive else inclusive.NO
cdef column_view input_view = input.view()
cdef column_view left_edges_view = left_edges.view()
cdef column_view right_edges_view = right_edges.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_label_bins(
input_view,
left_edges_view,
c_left_inclusive,
right_edges_view,
c_right_inclusive,
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/partitioning.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.pair cimport pair
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.partitioning cimport partition as cpp_partition
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.utils cimport columns_from_unique_ptr, table_view_from_columns
from cudf._lib.reduce import minmax
from cudf._lib.stream_compaction import distinct_count as cpp_distinct_count
cimport cudf._lib.cpp.types as libcudf_types
@acquire_spill_lock()
def partition(list source_columns, Column partition_map,
object num_partitions):
"""Partition source columns given a partitioning map
Parameters
----------
source_columns: list[Column]
Columns to partition
partition_map: Column
Column of integer values that map each row in the input to a
partition
num_partitions: Optional[int]
Number of output partitions (deduced from unique values in
partition_map if None)
Returns
-------
Pair of reordered columns and partition offsets
Raises
------
ValueError
If the partition map has invalid entries (not all in [0,
num_partitions)).
"""
if num_partitions is None:
num_partitions = cpp_distinct_count(partition_map, ignore_nulls=True)
cdef int c_num_partitions = num_partitions
cdef table_view c_source_view = table_view_from_columns(source_columns)
cdef column_view c_partition_map_view = partition_map.view()
cdef pair[unique_ptr[table], vector[libcudf_types.size_type]] c_result
if partition_map.size > 0:
lo, hi = minmax(partition_map)
if lo < 0 or hi >= num_partitions:
raise ValueError("Partition map has invalid values")
with nogil:
c_result = move(
cpp_partition(
c_source_view,
c_partition_map_view,
c_num_partitions
)
)
return (
columns_from_unique_ptr(move(c_result.first)), list(c_result.second)
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/utils.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
import numpy as np
import pyarrow as pa
import cudf
from cython.operator cimport dereference
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column, column_view
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport size_type
try:
import ujson as json
except ImportError:
import json
from cudf.api.types import (
is_categorical_dtype,
is_decimal_dtype,
is_list_dtype,
is_struct_dtype,
)
from cudf.utils.dtypes import np_dtypes_to_pandas_dtypes, np_to_pa_dtype
PARQUET_META_TYPE_MAP = {
str(cudf_dtype): str(pandas_dtype)
for cudf_dtype, pandas_dtype in np_dtypes_to_pandas_dtypes.items()
}
cdef table_view table_view_from_columns(columns) except*:
"""Create a cudf::table_view from an iterable of Columns."""
cdef vector[column_view] column_views
cdef Column col
for col in columns:
column_views.push_back(col.view())
return table_view(column_views)
cdef table_view table_view_from_table(tbl, ignore_index=False) except*:
"""Create a cudf::table_view from a Table.
Parameters
----------
ignore_index : bool, default False
If True, don't include the index in the columns.
"""
return table_view_from_columns(
tbl._index._data.columns + tbl._data.columns
if not ignore_index and tbl._index is not None
else tbl._data.columns
)
cdef vector[column_view] make_column_views(object columns):
cdef vector[column_view] views
views.reserve(len(columns))
for col in columns:
views.push_back((<Column> col).view())
return views
cdef vector[string] get_column_names(object tbl, object index):
cdef vector[string] column_names
if index is not False:
if isinstance(tbl._index, cudf.core.multiindex.MultiIndex):
for idx_name in tbl._index.names:
column_names.push_back(str.encode(idx_name))
else:
if tbl._index.name is not None:
column_names.push_back(str.encode(tbl._index.name))
for col_name in tbl._column_names:
column_names.push_back(str.encode(col_name))
return column_names
cpdef generate_pandas_metadata(table, index):
col_names = []
types = []
index_levels = []
index_descriptors = []
# Columns
for name, col in table._data.items():
col_names.append(name)
if is_categorical_dtype(col):
raise ValueError(
"'category' column dtypes are currently not "
+ "supported by the gpu accelerated parquet writer"
)
elif (
is_list_dtype(col)
or is_struct_dtype(col)
or is_decimal_dtype(col)
):
types.append(col.dtype.to_arrow())
else:
# A boolean element takes 8 bits in cudf and 1 bit in
# pyarrow. To make sure the cudf format is interperable
# in arrow, we use `int8` type when converting from a
# cudf boolean array.
if col.dtype.type == np.bool_:
types.append(pa.int8())
else:
types.append(np_to_pa_dtype(col.dtype))
# Indexes
if index is not False:
for level, name in enumerate(table._index.names):
if isinstance(table._index, cudf.core.multiindex.MultiIndex):
idx = table.index.get_level_values(level)
else:
idx = table.index
if isinstance(idx, cudf.core.index.RangeIndex):
if index is None:
descr = {
"kind": "range",
"name": table.index.name,
"start": table.index.start,
"stop": table.index.stop,
"step": table.index.step,
}
else:
# When `index=True`, RangeIndex needs to be materialized.
materialized_idx = cudf.Index(idx._values, name=idx.name)
descr = \
_index_level_name(
index_name=materialized_idx.name,
level=level,
column_names=col_names
)
index_levels.append(materialized_idx)
else:
descr = \
_index_level_name(
index_name=idx.name,
level=level,
column_names=col_names
)
if is_categorical_dtype(idx):
raise ValueError(
"'category' column dtypes are currently not "
+ "supported by the gpu accelerated parquet writer"
)
elif is_list_dtype(idx):
types.append(col.dtype.to_arrow())
else:
# A boolean element takes 8 bits in cudf and 1 bit in
# pyarrow. To make sure the cudf format is interperable
# in arrow, we use `int8` type when converting from a
# cudf boolean array.
if idx.dtype.type == np.bool_:
types.append(pa.int8())
else:
types.append(np_to_pa_dtype(idx.dtype))
index_levels.append(idx)
col_names.append(name)
index_descriptors.append(descr)
metadata = pa.pandas_compat.construct_metadata(
columns_to_convert=[
col
for col in table._columns
],
df=table,
column_names=col_names,
index_levels=index_levels,
index_descriptors=index_descriptors,
preserve_index=index,
types=types,
)
md_dict = json.loads(metadata[b"pandas"])
# correct metadata for list and struct and nullable numeric types
for col_meta in md_dict["columns"]:
if (
col_meta["name"] in table._column_names
and table._data[col_meta["name"]].nullable
and col_meta["numpy_type"] in PARQUET_META_TYPE_MAP
and col_meta["pandas_type"] != "decimal"
):
col_meta["numpy_type"] = PARQUET_META_TYPE_MAP[
col_meta["numpy_type"]
]
if col_meta["numpy_type"] in ("list", "struct"):
col_meta["numpy_type"] = "object"
return json.dumps(md_dict)
def _index_level_name(index_name, level, column_names):
"""
Return the name of an index level or a default name
if `index_name` is None or is already a column name.
Parameters
----------
index_name : name of an Index object
level : level of the Index object
Returns
-------
name : str
"""
if index_name is not None and index_name not in column_names:
return index_name
else:
return f"__index_level_{level}__"
cdef columns_from_unique_ptr(
unique_ptr[table] c_tbl
):
"""Convert a libcudf table into list of columns.
Parameters
----------
c_tbl : unique_ptr[cudf::table]
The libcudf table whose columns will be extracted
Returns
-------
list[Column]
A list of columns.
"""
cdef vector[unique_ptr[column]] c_columns = move(c_tbl.get().release())
cdef vector[unique_ptr[column]].iterator it = c_columns.begin()
cdef size_t i
columns = [Column.from_unique_ptr(move(dereference(it+i)))
for i in range(c_columns.size())]
return columns
cdef columns_from_pylibcudf_table(tbl):
"""Convert a pylibcudf table into list of columns.
Parameters
----------
tbl : pylibcudf.Table
The pylibcudf table whose columns will be extracted
Returns
-------
list[Column]
A list of columns.
"""
return [Column.from_pylibcudf(plc) for plc in tbl.columns()]
cdef data_from_unique_ptr(
unique_ptr[table] c_tbl, column_names, index_names=None
):
"""Convert a libcudf table into a dict with an index.
This method is intended to provide the bridge between the columns returned
from calls to libcudf APIs and the cuDF Python Frame objects, which require
named columns and a separate index.
Since cuDF Python has an independent representation of a table as a
collection of columns, this function simply returns a dict of columns
suitable for conversion into data to be passed to cuDF constructors.
This method returns the columns of the table in the order they are
stored in libcudf, but calling code is responsible for partitioning and
labeling them as needed.
Parameters
----------
c_tbl : unique_ptr[cudf::table]
The libcudf table whose columns will be extracted
column_names : iterable
The keys associated with the columns in the output data.
index_names : iterable, optional
If provided, an iterable of strings that will be used to label the
corresponding first set of columns into a (Multi)Index. If this
argument is omitted, all columns are assumed to be part of the output
table and no index is constructed.
Returns
-------
tuple(Dict[str, Column], Optional[Index])
A dict of the columns in the output table.
"""
columns = columns_from_unique_ptr(move(c_tbl))
# First construct the index, if any
index = (
# TODO: For performance, the _from_data methods of Frame types assume
# that the passed index object is already an Index because cudf.Index
# and cudf.as_index are expensive. As a result, this function is
# currently somewhat inconsistent in returning a dict of columns for
# the data while actually constructing the Index object here (instead
# of just returning a dict for that as well). As we clean up the
# Frame factories we may want to look for a less dissonant approach
# that does not impose performance penalties. The same applies to
# data_from_table_view below.
cudf.core.index._index_from_data(
{
name: columns[i]
for i, name in enumerate(index_names)
}
)
if index_names is not None
else None
)
n_index_columns = len(index_names) if index_names is not None else 0
data = {
name: columns[i + n_index_columns]
for i, name in enumerate(column_names)
}
return data, index
cdef columns_from_table_view(
table_view tv,
object owners,
):
"""
Given a ``cudf::table_view``, constructs a list of columns from it,
along with referencing an owner Python object that owns the memory
lifetime. owner must be either None or a list of column. If owner
is a list of columns, the owner of the `i`th ``cudf::column_view``
in the table view is ``owners[i]``. For more about memory ownership,
see ``Column.from_column_view``.
"""
return [
Column.from_column_view(
tv.column(i), owners[i] if isinstance(owners, list) else None
) for i in range(tv.num_columns())
]
cdef data_from_table_view(
table_view tv,
object owner,
object column_names,
object index_names=None
):
"""
Given a ``cudf::table_view``, constructs a Frame from it,
along with referencing an ``owner`` Python object that owns the memory
lifetime. If ``owner`` is a Frame we reach inside of it and
reach inside of each ``cudf.Column`` to make the owner of each newly
created ``Buffer`` underneath the ``cudf.Column`` objects of the
created Frame the respective ``Buffer`` from the relevant
``cudf.Column`` of the ``owner`` Frame
"""
cdef size_type column_idx = 0
table_owner = isinstance(owner, cudf.core.frame.Frame)
# First construct the index, if any
index = None
if index_names is not None:
index_columns = []
for _ in index_names:
column_owner = owner
if table_owner:
column_owner = owner._index._columns[column_idx]
index_columns.append(
Column.from_column_view(
tv.column(column_idx),
column_owner
)
)
column_idx += 1
index = cudf.core.index._index_from_data(
dict(zip(index_names, index_columns)))
# Construct the data dict
cdef size_type source_column_idx = 0
data_columns = []
for _ in column_names:
column_owner = owner
if table_owner:
column_owner = owner._columns[source_column_idx]
data_columns.append(
Column.from_column_view(tv.column(column_idx), column_owner)
)
column_idx += 1
source_column_idx += 1
return dict(zip(column_names, data_columns)), index
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/copying.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
import pickle
from libc.stdint cimport int32_t, uint8_t, uintptr_t
from libcpp cimport bool
from libcpp.memory cimport make_shared, shared_ptr, unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
from rmm._lib.device_buffer cimport DeviceBuffer
import cudf
from cudf._lib import pylibcudf
from cudf.core.buffer import Buffer, acquire_spill_lock, as_buffer
from cudf._lib.column cimport Column
from cudf._lib.scalar import as_device_scalar
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.utils cimport table_view_from_columns, table_view_from_table
from cudf._lib.reduce import minmax
from cudf.core.abc import Serializable
from libcpp.functional cimport reference_wrapper
from libcpp.memory cimport make_unique
cimport cudf._lib.cpp.contiguous_split as cpp_contiguous_split
cimport cudf._lib.cpp.copying as cpp_copying
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view, mutable_column_view
from cudf._lib.cpp.lists.gather cimport (
segmented_gather as cpp_segmented_gather,
)
from cudf._lib.cpp.lists.lists_column_view cimport lists_column_view
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport size_type
from cudf._lib.utils cimport (
columns_from_pylibcudf_table,
columns_from_table_view,
columns_from_unique_ptr,
data_from_table_view,
table_view_from_columns,
)
# workaround for https://github.com/cython/cython/issues/3885
ctypedef const scalar constscalar
def _gather_map_is_valid(
gather_map: "cudf.core.column.ColumnBase",
nrows: int,
check_bounds: bool,
nullify: bool,
) -> bool:
"""Returns true if gather map is valid.
A gather map is valid if empty or all indices are within the range
``[-nrows, nrows)``, except when ``nullify`` is specified.
"""
if not check_bounds or nullify or len(gather_map) == 0:
return True
gm_min, gm_max = minmax(gather_map)
return gm_min >= -nrows and gm_max < nrows
@acquire_spill_lock()
def copy_column(Column input_column):
"""
Deep copies a column
Parameters
----------
input_columns : column to be copied
Returns
-------
Deep copied column
"""
cdef unique_ptr[column] c_result
cdef column_view input_column_view = input_column.view()
with nogil:
c_result = move(make_unique[column](input_column_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def _copy_range_in_place(Column input_column,
Column target_column,
size_type input_begin,
size_type input_end,
size_type target_begin):
cdef column_view input_column_view = input_column.view()
cdef mutable_column_view target_column_view = target_column.mutable_view()
cdef size_type c_input_begin = input_begin
cdef size_type c_input_end = input_end
cdef size_type c_target_begin = target_begin
with nogil:
cpp_copying.copy_range_in_place(
input_column_view,
target_column_view,
c_input_begin,
c_input_end,
c_target_begin)
def _copy_range(Column input_column,
Column target_column,
size_type input_begin,
size_type input_end,
size_type target_begin):
cdef column_view input_column_view = input_column.view()
cdef column_view target_column_view = target_column.view()
cdef size_type c_input_begin = input_begin
cdef size_type c_input_end = input_end
cdef size_type c_target_begin = target_begin
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_copying.copy_range(
input_column_view,
target_column_view,
c_input_begin,
c_input_end,
c_target_begin)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def copy_range(Column source_column,
Column target_column,
size_type source_begin,
size_type source_end,
size_type target_begin,
size_type target_end,
bool inplace):
"""
Copy a contiguous range from a source to a target column
Notes
-----
Expects the source and target ranges to have been sanitised to be
in-range for the source and target column respectively. For
example via ``slice.indices``.
"""
msg = "Source and target ranges must be same length"
assert source_end - source_begin == target_end - target_begin, msg
if target_end >= target_begin and inplace:
# FIXME: Are we allowed to do this when inplace=False?
return target_column
if inplace:
_copy_range_in_place(source_column, target_column,
source_begin, source_end, target_begin)
else:
return _copy_range(source_column, target_column,
source_begin, source_end, target_begin)
@acquire_spill_lock()
def gather(
list columns,
Column gather_map,
bool nullify=False
):
tbl = pylibcudf.copying.gather(
pylibcudf.Table([col.to_pylibcudf(mode="read") for col in columns]),
gather_map.to_pylibcudf(mode="read"),
pylibcudf.copying.OutOfBoundsPolicy.NULLIFY if nullify
else pylibcudf.copying.OutOfBoundsPolicy.DONT_CHECK
)
return columns_from_pylibcudf_table(tbl)
cdef scatter_scalar(list source_device_slrs,
column_view scatter_map,
table_view target_table):
cdef vector[reference_wrapper[constscalar]] c_source
cdef DeviceScalar d_slr
cdef unique_ptr[table] c_result
c_source.reserve(len(source_device_slrs))
for d_slr in source_device_slrs:
c_source.push_back(
reference_wrapper[constscalar](d_slr.get_raw_ptr()[0])
)
with nogil:
c_result = move(
cpp_copying.scatter(
c_source,
scatter_map,
target_table,
)
)
return columns_from_unique_ptr(move(c_result))
cdef scatter_column(list source_columns,
column_view scatter_map,
table_view target_table):
cdef table_view c_source = table_view_from_columns(source_columns)
cdef unique_ptr[table] c_result
with nogil:
c_result = move(
cpp_copying.scatter(
c_source,
scatter_map,
target_table,
)
)
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def scatter(list sources, Column scatter_map, list target_columns,
bool bounds_check=True):
"""
Scattering source into target as per the scatter map.
`source` can be a list of scalars, or a list of columns. The number of
items in `sources` must equal the number of `target_columns` to scatter.
"""
# TODO: Only single column scatter is used, we should explore multi-column
# scatter for frames for performance increase.
if len(sources) != len(target_columns):
raise ValueError("Mismatched number of source and target columns.")
if len(sources) == 0:
return []
cdef column_view scatter_map_view = scatter_map.view()
cdef table_view target_table_view = table_view_from_columns(target_columns)
if bounds_check:
n_rows = len(target_columns[0])
if not (
(scatter_map >= -n_rows).all()
and (scatter_map < n_rows).all()
):
raise IndexError(
f"index out of bounds for column of size {n_rows}"
)
if isinstance(sources[0], Column):
return scatter_column(
sources, scatter_map_view, target_table_view
)
else:
source_scalars = [as_device_scalar(slr) for slr in sources]
return scatter_scalar(
source_scalars, scatter_map_view, target_table_view
)
@acquire_spill_lock()
def column_empty_like(Column input_column):
cdef column_view input_column_view = input_column.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_copying.empty_like(input_column_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def column_allocate_like(Column input_column, size=None):
cdef size_type c_size = 0
cdef column_view input_column_view = input_column.view()
cdef unique_ptr[column] c_result
if size is None:
with nogil:
c_result = move(cpp_copying.allocate_like(
input_column_view,
cpp_copying.mask_allocation_policy.RETAIN)
)
else:
c_size = size
with nogil:
c_result = move(cpp_copying.allocate_like(
input_column_view,
c_size,
cpp_copying.mask_allocation_policy.RETAIN)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def columns_empty_like(list input_columns):
cdef table_view input_table_view = table_view_from_columns(input_columns)
cdef unique_ptr[table] c_result
with nogil:
c_result = move(cpp_copying.empty_like(input_table_view))
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def column_slice(Column input_column, object indices):
cdef column_view input_column_view = input_column.view()
cdef vector[size_type] c_indices
c_indices.reserve(len(indices))
cdef vector[column_view] c_result
cdef int index
for index in indices:
c_indices.push_back(index)
with nogil:
c_result = move(
cpp_copying.slice(
input_column_view,
c_indices)
)
num_of_result_cols = c_result.size()
result = [
Column.from_column_view(
c_result[i],
input_column) for i in range(num_of_result_cols)]
return result
@acquire_spill_lock()
def columns_slice(list input_columns, list indices):
"""
Given a list of input columns, return columns sliced by ``indices``.
Returns a list of list of columns. The length of return is
`len(indices) / 2`. The `i`th item in return is a list of columns sliced
from ``input_columns`` with `slice(indices[i*2], indices[i*2 + 1])`.
"""
cdef table_view input_table_view = table_view_from_columns(input_columns)
cdef vector[size_type] c_indices = indices
cdef vector[table_view] c_result
with nogil:
c_result = move(
cpp_copying.slice(
input_table_view,
c_indices)
)
return [
columns_from_table_view(
c_result[i], input_columns
) for i in range(c_result.size())
]
@acquire_spill_lock()
def column_split(Column input_column, object splits):
cdef column_view input_column_view = input_column.view()
cdef vector[size_type] c_splits
c_splits.reserve(len(splits))
cdef vector[column_view] c_result
cdef int split
for split in splits:
c_splits.push_back(split)
with nogil:
c_result = move(
cpp_copying.split(
input_column_view,
c_splits)
)
num_of_result_cols = c_result.size()
result = [
Column.from_column_view(
c_result[i],
input_column
) for i in range(num_of_result_cols)
]
return result
@acquire_spill_lock()
def columns_split(list input_columns, object splits):
cdef table_view input_table_view = table_view_from_columns(input_columns)
cdef vector[size_type] c_splits = splits
cdef vector[table_view] c_result
with nogil:
c_result = move(
cpp_copying.split(
input_table_view,
c_splits)
)
return [
columns_from_table_view(
c_result[i], input_columns
) for i in range(c_result.size())
]
def _copy_if_else_column_column(Column lhs, Column rhs, Column boolean_mask):
cdef column_view lhs_view = lhs.view()
cdef column_view rhs_view = rhs.view()
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_copying.copy_if_else(
lhs_view,
rhs_view,
boolean_mask_view
)
)
return Column.from_unique_ptr(move(c_result))
def _copy_if_else_scalar_column(DeviceScalar lhs,
Column rhs,
Column boolean_mask):
cdef const scalar* lhs_scalar = lhs.get_raw_ptr()
cdef column_view rhs_view = rhs.view()
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_copying.copy_if_else(
lhs_scalar[0],
rhs_view,
boolean_mask_view
)
)
return Column.from_unique_ptr(move(c_result))
def _copy_if_else_column_scalar(Column lhs,
DeviceScalar rhs,
Column boolean_mask):
cdef column_view lhs_view = lhs.view()
cdef const scalar* rhs_scalar = rhs.get_raw_ptr()
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_copying.copy_if_else(
lhs_view,
rhs_scalar[0],
boolean_mask_view
)
)
return Column.from_unique_ptr(move(c_result))
def _copy_if_else_scalar_scalar(DeviceScalar lhs,
DeviceScalar rhs,
Column boolean_mask):
cdef const scalar* lhs_scalar = lhs.get_raw_ptr()
cdef const scalar* rhs_scalar = rhs.get_raw_ptr()
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_copying.copy_if_else(
lhs_scalar[0],
rhs_scalar[0],
boolean_mask_view
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def copy_if_else(object lhs, object rhs, Column boolean_mask):
if isinstance(lhs, Column):
if isinstance(rhs, Column):
return _copy_if_else_column_column(lhs, rhs, boolean_mask)
else:
return _copy_if_else_column_scalar(
lhs, as_device_scalar(rhs), boolean_mask)
else:
if isinstance(rhs, Column):
return _copy_if_else_scalar_column(
as_device_scalar(lhs), rhs, boolean_mask)
else:
if lhs is None and rhs is None:
return lhs
return _copy_if_else_scalar_scalar(
as_device_scalar(lhs), as_device_scalar(rhs), boolean_mask)
def _boolean_mask_scatter_columns(list input_columns, list target_columns,
Column boolean_mask):
cdef table_view input_table_view = table_view_from_columns(input_columns)
cdef table_view target_table_view = table_view_from_columns(target_columns)
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[table] c_result
with nogil:
c_result = move(
cpp_copying.boolean_mask_scatter(
input_table_view,
target_table_view,
boolean_mask_view
)
)
return columns_from_unique_ptr(move(c_result))
def _boolean_mask_scatter_scalar(list input_scalars, list target_columns,
Column boolean_mask):
cdef vector[reference_wrapper[constscalar]] input_scalar_vector
input_scalar_vector.reserve(len(input_scalars))
cdef DeviceScalar scl
for scl in input_scalars:
input_scalar_vector.push_back(reference_wrapper[constscalar](
scl.get_raw_ptr()[0]))
cdef table_view target_table_view = table_view_from_columns(target_columns)
cdef column_view boolean_mask_view = boolean_mask.view()
cdef unique_ptr[table] c_result
with nogil:
c_result = move(
cpp_copying.boolean_mask_scatter(
input_scalar_vector,
target_table_view,
boolean_mask_view
)
)
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def boolean_mask_scatter(list input_, list target_columns,
Column boolean_mask):
"""Copy the target columns, replacing masked rows with input data.
The ``input_`` data can be a list of columns or as a list of scalars.
A list of input columns will be used to replace corresponding rows in the
target columns for which the boolean mask is ``True``. For the nth ``True``
in the boolean mask, the nth row in ``input_`` is used to replace. A list
of input scalars will replace all rows in the target columns for which the
boolean mask is ``True``.
"""
if len(input_) != len(target_columns):
raise ValueError("Mismatched number of input and target columns.")
if len(input_) == 0:
return []
if isinstance(input_[0], Column):
return _boolean_mask_scatter_columns(
input_,
target_columns,
boolean_mask
)
else:
scalar_list = [as_device_scalar(i) for i in input_]
return _boolean_mask_scatter_scalar(
scalar_list,
target_columns,
boolean_mask
)
@acquire_spill_lock()
def shift(Column input, int offset, object fill_value=None):
cdef DeviceScalar fill
if isinstance(fill_value, DeviceScalar):
fill = fill_value
else:
fill = as_device_scalar(fill_value, input.dtype)
cdef column_view c_input = input.view()
cdef int32_t c_offset = offset
cdef const scalar* c_fill_value = fill.get_raw_ptr()
cdef unique_ptr[column] c_output
with nogil:
c_output = move(
cpp_copying.shift(
c_input,
c_offset,
c_fill_value[0]
)
)
return Column.from_unique_ptr(move(c_output))
@acquire_spill_lock()
def get_element(Column input_column, size_type index):
cdef column_view col_view = input_column.view()
cdef unique_ptr[scalar] c_output
with nogil:
c_output = move(
cpp_copying.get_element(col_view, index)
)
return DeviceScalar.from_unique_ptr(
move(c_output), dtype=input_column.dtype
)
@acquire_spill_lock()
def segmented_gather(Column source_column, Column gather_map):
cdef shared_ptr[lists_column_view] source_LCV = (
make_shared[lists_column_view](source_column.view())
)
cdef shared_ptr[lists_column_view] gather_map_LCV = (
make_shared[lists_column_view](gather_map.view())
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_segmented_gather(
source_LCV.get()[0], gather_map_LCV.get()[0])
)
result = Column.from_unique_ptr(move(c_result))
return result
cdef class _CPackedColumns:
@staticmethod
def from_py_table(input_table, keep_index=True):
"""
Construct a ``PackedColumns`` object from a ``cudf.DataFrame``.
"""
import cudf.core.dtypes
cdef _CPackedColumns p = _CPackedColumns.__new__(_CPackedColumns)
if keep_index and (
not isinstance(input_table.index, cudf.RangeIndex)
or input_table.index.start != 0
or input_table.index.stop != len(input_table)
or input_table.index.step != 1
):
input_table_view = table_view_from_table(input_table)
p.index_names = input_table._index_names
else:
input_table_view = table_view_from_table(
input_table, ignore_index=True)
p.column_names = input_table._column_names
p.column_dtypes = {}
for name, col in input_table._data.items():
if isinstance(col.dtype, cudf.core.dtypes._BaseDtype):
p.column_dtypes[name] = col.dtype
p.c_obj = move(cpp_contiguous_split.pack(input_table_view))
return p
@property
def gpu_data_ptr(self):
return int(<uintptr_t>self.c_obj.gpu_data.get()[0].data())
@property
def gpu_data_size(self):
return int(<size_t>self.c_obj.gpu_data.get()[0].size())
def serialize(self):
header = {}
frames = []
gpu_data = as_buffer(
data=self.gpu_data_ptr,
size=self.gpu_data_size,
owner=self,
exposed=True
)
data_header, data_frames = gpu_data.serialize()
header["data"] = data_header
frames.extend(data_frames)
header["column-names"] = self.column_names
header["index-names"] = self.index_names
if self.c_obj.metadata.get()[0].data() != NULL:
header["metadata"] = list(
<uint8_t[:self.c_obj.metadata.get()[0].size()]>
self.c_obj.metadata.get()[0].data()
)
column_dtypes = {}
for name, dtype in self.column_dtypes.items():
dtype_header, dtype_frames = dtype.serialize()
column_dtypes[name] = (
dtype_header,
(len(frames), len(frames) + len(dtype_frames)),
)
frames.extend(dtype_frames)
header["column-dtypes"] = column_dtypes
return header, frames
@staticmethod
def deserialize(header, frames):
cdef _CPackedColumns p = _CPackedColumns.__new__(_CPackedColumns)
gpu_data = Buffer.deserialize(header["data"], frames)
dbuf = DeviceBuffer(
ptr=gpu_data.get_ptr(mode="write"),
size=gpu_data.nbytes
)
cdef cpp_contiguous_split.packed_columns data
data.metadata = move(
make_unique[vector[uint8_t]](
move(<vector[uint8_t]>header.get("metadata", []))
)
)
data.gpu_data = move(dbuf.c_obj)
p.c_obj = move(data)
p.column_names = header["column-names"]
p.index_names = header["index-names"]
column_dtypes = {}
for name, dtype in header["column-dtypes"].items():
dtype_header, (start, stop) = dtype
column_dtypes[name] = pickle.loads(
dtype_header["type-serialized"]
).deserialize(dtype_header, frames[start:stop])
p.column_dtypes = column_dtypes
return p
def unpack(self):
output_table = cudf.DataFrame._from_data(*data_from_table_view(
cpp_contiguous_split.unpack(self.c_obj),
self,
self.column_names,
self.index_names
))
for name, dtype in self.column_dtypes.items():
output_table._data[name] = (
output_table._data[name]._with_type_metadata(dtype)
)
return output_table
class PackedColumns(Serializable):
"""
A packed representation of a Frame, with all columns residing
in a single GPU memory buffer.
"""
def __init__(self, data):
self._data = data
def __reduce__(self):
return self.deserialize, self.serialize()
@property
def __cuda_array_interface__(self):
return {
"data": (self._data.gpu_data_ptr, False),
"shape": (self._data.gpu_data_size,),
"strides": None,
"typestr": "|u1",
"version": 0
}
def serialize(self):
header, frames = self._data.serialize()
header["type-serialized"] = pickle.dumps(type(self))
return header, frames
@classmethod
def deserialize(cls, header, frames):
return cls(_CPackedColumns.deserialize(header, frames))
@classmethod
def from_py_table(cls, input_table, keep_index=True):
return cls(_CPackedColumns.from_py_table(input_table, keep_index))
def unpack(self):
return self._data.unpack()
def pack(input_table, keep_index=True):
"""
Pack the columns of a cudf Frame into a single GPU memory buffer.
"""
return PackedColumns.from_py_table(input_table, keep_index)
def unpack(packed):
"""
Unpack the results of packing a cudf Frame returning a new
cudf Frame in the process.
"""
return packed.unpack()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/scalar.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
import copy
import numpy as np
import pandas as pd
import pyarrow as pa
from libc.stdint cimport int64_t
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
import cudf
from cudf._lib import pylibcudf
from cudf._lib.types import LIBCUDF_TO_SUPPORTED_NUMPY_TYPES
from cudf.core.dtypes import (
ListDtype,
StructDtype,
is_list_dtype,
is_struct_dtype,
)
from cudf.core.missing import NA, NaT
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.cpp.scalar.scalar cimport (
duration_scalar,
list_scalar,
scalar,
struct_scalar,
timestamp_scalar,
)
from cudf._lib.cpp.wrappers.durations cimport (
duration_ms,
duration_ns,
duration_s,
duration_us,
)
from cudf._lib.cpp.wrappers.timestamps cimport (
timestamp_ms,
timestamp_ns,
timestamp_s,
timestamp_us,
)
from cudf._lib.types cimport dtype_from_column_view, underlying_type_t_type_id
def _replace_nested(obj, check, replacement):
if isinstance(obj, list):
for i, item in enumerate(obj):
if check(item):
obj[i] = replacement
elif isinstance(item, (dict, list)):
_replace_nested(item, check, replacement)
elif isinstance(obj, dict):
for k, v in obj.items():
if check(v):
obj[k] = replacement
elif isinstance(v, (dict, list)):
_replace_nested(v, check, replacement)
def gather_metadata(dtypes):
"""Convert a dict of dtypes to a list of ColumnMetadata objects.
The metadata is constructed recursively so that nested types are
represented as nested ColumnMetadata objects.
Parameters
----------
dtypes : dict
A dict mapping column names to dtypes.
Returns
-------
List[ColumnMetadata]
A list of ColumnMetadata objects.
"""
out = []
for name, dtype in dtypes.items():
v = pylibcudf.interop.ColumnMetadata(name)
if is_struct_dtype(dtype):
v.children_meta = gather_metadata(dtype.fields)
elif is_list_dtype(dtype):
# Offsets column is unnamed and has no children
v.children_meta.append(pylibcudf.interop.ColumnMetadata(""))
v.children_meta.extend(
gather_metadata({"": dtype.element_type})
)
out.append(v)
return out
cdef class DeviceScalar:
# TODO: I think this should be removable, except that currently the way
# that from_unique_ptr is implemented is probably dereferencing this in an
# invalid state. See what the best way to fix that is.
def __cinit__(self, *args, **kwargs):
self.c_value = pylibcudf.Scalar()
def __init__(self, value, dtype):
"""
Type representing an *immutable* scalar value on the device
Parameters
----------
value : scalar
An object of scalar type, i.e., one for which
`np.isscalar()` returns `True`. Can also be `None`,
to represent a "null" scalar. In this case,
dtype *must* be provided.
dtype : dtype
A NumPy dtype.
"""
dtype = dtype if dtype.kind != 'U' else cudf.dtype('object')
if cudf.utils.utils.is_na_like(value):
value = None
else:
# TODO: For now we always deepcopy the input value to avoid
# overwriting the input values when replacing nulls. Since it's
# just host values it's not that expensive, but we could consider
# alternatives.
value = copy.deepcopy(value)
_replace_nested(value, cudf.utils.utils.is_na_like, None)
if isinstance(dtype, cudf.core.dtypes._BaseDtype):
pa_type = dtype.to_arrow()
elif pd.api.types.is_string_dtype(dtype):
# Have to manually convert object types, which we use internally
# for strings but pyarrow only supports as unicode 'U'
pa_type = pa.string()
else:
pa_type = pa.from_numpy_dtype(dtype)
pa_scalar = pa.scalar(value, type=pa_type)
data_type = None
if isinstance(dtype, cudf.core.dtypes.DecimalDtype):
tid = pylibcudf.TypeId.DECIMAL128
if isinstance(dtype, cudf.core.dtypes.Decimal32Dtype):
tid = pylibcudf.TypeId.DECIMAL32
elif isinstance(dtype, cudf.core.dtypes.Decimal64Dtype):
tid = pylibcudf.TypeId.DECIMAL64
data_type = pylibcudf.DataType(tid, -dtype.scale)
self.c_value = pylibcudf.Scalar.from_arrow(pa_scalar, data_type)
self._dtype = dtype
def _to_host_scalar(self):
is_datetime = self.dtype.kind == "M"
is_timedelta = self.dtype.kind == "m"
null_type = NaT if is_datetime or is_timedelta else NA
metadata = gather_metadata({"": self.dtype})[0]
ps = self.c_value.to_arrow(metadata)
if not ps.is_valid:
return null_type
# TODO: The special handling of specific types below does not currently
# extend to nested types containing those types (e.g. List[timedelta]
# where the timedelta would overflow). We should eventually account for
# those cases, but that will require more careful consideration of how
# to traverse the contents of the nested data.
if is_datetime or is_timedelta:
time_unit, _ = np.datetime_data(self.dtype)
# Cast to int64 to avoid overflow
ps_cast = ps.cast('int64').as_py()
out_type = np.datetime64 if is_datetime else np.timedelta64
ret = out_type(ps_cast, time_unit)
elif cudf.api.types.is_numeric_dtype(self.dtype):
ret = ps.type.to_pandas_dtype()(ps.as_py())
else:
ret = ps.as_py()
_replace_nested(ret, lambda item: item is None, NA)
return ret
@property
def dtype(self):
"""
The NumPy dtype corresponding to the data type of the underlying
device scalar.
"""
return self._dtype
@property
def value(self):
"""
Returns a host copy of the underlying device scalar.
"""
return self._to_host_scalar()
cdef const scalar* get_raw_ptr(self) except *:
return self.c_value.c_obj.get()
cpdef bool is_valid(self):
"""
Returns if the Scalar is valid or not(i.e., <NA>).
"""
return self.c_value.is_valid()
def __repr__(self):
if cudf.utils.utils.is_na_like(self.value):
return (
f"{self.__class__.__name__}"
f"({self.value}, {repr(self.dtype)})"
)
else:
return f"{self.__class__.__name__}({repr(self.value)})"
@staticmethod
cdef DeviceScalar from_unique_ptr(unique_ptr[scalar] ptr, dtype=None):
"""
Construct a Scalar object from a unique_ptr<cudf::scalar>.
"""
cdef DeviceScalar s = DeviceScalar.__new__(DeviceScalar)
cdef libcudf_types.data_type cdtype
s.c_value = pylibcudf.Scalar.from_libcudf(move(ptr))
cdtype = s.get_raw_ptr()[0].type()
if dtype is not None:
s._dtype = dtype
elif cdtype.id() in {
libcudf_types.type_id.DECIMAL32,
libcudf_types.type_id.DECIMAL64,
libcudf_types.type_id.DECIMAL128,
}:
raise TypeError(
"Must pass a dtype when constructing from a fixed-point scalar"
)
elif cdtype.id() == libcudf_types.type_id.STRUCT:
struct_table_view = (<struct_scalar*>s.get_raw_ptr())[0].view()
s._dtype = StructDtype({
str(i): dtype_from_column_view(struct_table_view.column(i))
for i in range(struct_table_view.num_columns())
})
elif cdtype.id() == libcudf_types.type_id.LIST:
if (
<list_scalar*>s.get_raw_ptr()
)[0].view().type().id() == libcudf_types.type_id.LIST:
s._dtype = dtype_from_column_view(
(<list_scalar*>s.get_raw_ptr())[0].view()
)
else:
s._dtype = ListDtype(
LIBCUDF_TO_SUPPORTED_NUMPY_TYPES[
<underlying_type_t_type_id>(
(<list_scalar*>s.get_raw_ptr())[0]
.view().type().id()
)
]
)
else:
s._dtype = LIBCUDF_TO_SUPPORTED_NUMPY_TYPES[
<underlying_type_t_type_id>(cdtype.id())
]
return s
# TODO: Currently the only uses of this function and the one below are in
# _create_proxy_nat_scalar. See if that code path can be simplified to excise
# or at least simplify these implementations.
cdef _set_datetime64_from_np_scalar(unique_ptr[scalar]& s,
object value,
object dtype,
bool valid=True):
value = value if valid else 0
if dtype == "datetime64[s]":
s.reset(
new timestamp_scalar[timestamp_s](<int64_t>np.int64(value), valid)
)
elif dtype == "datetime64[ms]":
s.reset(
new timestamp_scalar[timestamp_ms](<int64_t>np.int64(value), valid)
)
elif dtype == "datetime64[us]":
s.reset(
new timestamp_scalar[timestamp_us](<int64_t>np.int64(value), valid)
)
elif dtype == "datetime64[ns]":
s.reset(
new timestamp_scalar[timestamp_ns](<int64_t>np.int64(value), valid)
)
else:
raise ValueError(f"dtype not supported: {dtype}")
cdef _set_timedelta64_from_np_scalar(unique_ptr[scalar]& s,
object value,
object dtype,
bool valid=True):
value = value if valid else 0
if dtype == "timedelta64[s]":
s.reset(
new duration_scalar[duration_s](<int64_t>np.int64(value), valid)
)
elif dtype == "timedelta64[ms]":
s.reset(
new duration_scalar[duration_ms](<int64_t>np.int64(value), valid)
)
elif dtype == "timedelta64[us]":
s.reset(
new duration_scalar[duration_us](<int64_t>np.int64(value), valid)
)
elif dtype == "timedelta64[ns]":
s.reset(
new duration_scalar[duration_ns](<int64_t>np.int64(value), valid)
)
else:
raise ValueError(f"dtype not supported: {dtype}")
def as_device_scalar(val, dtype=None):
if isinstance(val, (cudf.Scalar, DeviceScalar)):
if dtype == val.dtype or dtype is None:
if isinstance(val, DeviceScalar):
return val
else:
return val.device_value
else:
raise TypeError("Can't update dtype of existing GPU scalar")
else:
return cudf.Scalar(val, dtype=dtype).device_value
def _is_null_host_scalar(slr):
if cudf.utils.utils.is_na_like(slr):
return True
elif isinstance(slr, (np.datetime64, np.timedelta64)) and np.isnat(slr):
return True
else:
return False
def _create_proxy_nat_scalar(dtype):
cdef DeviceScalar result = DeviceScalar.__new__(DeviceScalar)
dtype = cudf.dtype(dtype)
if dtype.char in 'mM':
nat = dtype.type('NaT').astype(dtype)
if dtype.type == np.datetime64:
_set_datetime64_from_np_scalar(result.c_value.c_obj, nat, dtype, True)
elif dtype.type == np.timedelta64:
_set_timedelta64_from_np_scalar(result.c_value.c_obj, nat, dtype, True)
return result
else:
raise TypeError('NAT only valid for datetime and timedelta')
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/timezone.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.optional cimport make_optional
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf._lib.cpp.io.timezone cimport (
make_timezone_transition_table as cpp_make_timezone_transition_table,
)
from cudf._lib.cpp.table.table cimport table
from cudf._lib.utils cimport columns_from_unique_ptr
def make_timezone_transition_table(tzdir, tzname):
cdef unique_ptr[table] c_result
cdef string c_tzdir = tzdir.encode()
cdef string c_tzname = tzname.encode()
with nogil:
c_result = move(
cpp_make_timezone_transition_table(
make_optional[string](c_tzdir),
c_tzname
)
)
return columns_from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/json.pyx
|
# Copyright (c) 2019-2023, NVIDIA CORPORATION.
# cython: boundscheck = False
import io
import os
from collections import abc
import cudf
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool
from libcpp.map cimport map
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
cimport cudf._lib.cpp.io.types as cudf_io_types
from cudf._lib.cpp.io.data_sink cimport data_sink
from cudf._lib.cpp.io.json cimport (
json_reader_options,
json_writer_options,
read_json as libcudf_read_json,
schema_element,
write_json as libcudf_write_json,
)
from cudf._lib.cpp.io.types cimport (
column_name_info,
compression_type,
sink_info,
table_metadata,
table_with_metadata,
)
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport data_type, size_type
from cudf._lib.io.utils cimport (
make_sink_info,
make_source_info,
update_struct_field_names,
)
from cudf._lib.types cimport dtype_to_data_type
from cudf._lib.utils cimport data_from_unique_ptr, table_view_from_table
from cudf.api.types import is_list_dtype, is_struct_dtype
from cudf._lib.column cimport Column
cpdef read_json(object filepaths_or_buffers,
object dtype,
bool lines,
object compression,
object byte_range,
bool legacy,
bool keep_quotes):
"""
Cython function to call into libcudf API, see `read_json`.
See Also
--------
cudf.io.json.read_json
cudf.io.json.to_json
"""
# If input data is a JSON string (or StringIO), hold a reference to
# the encoded memoryview externally to ensure the encoded buffer
# isn't destroyed before calling libcudf `read_json()`
for idx in range(len(filepaths_or_buffers)):
if isinstance(filepaths_or_buffers[idx], io.StringIO):
filepaths_or_buffers[idx] = \
filepaths_or_buffers[idx].read().encode()
elif isinstance(filepaths_or_buffers[idx], str) and \
not os.path.isfile(filepaths_or_buffers[idx]):
filepaths_or_buffers[idx] = filepaths_or_buffers[idx].encode()
# Setup arguments
cdef vector[data_type] c_dtypes_list
cdef map[string, schema_element] c_dtypes_schema_map
cdef cudf_io_types.compression_type c_compression
# Determine byte read offsets if applicable
cdef size_type c_range_offset = (
byte_range[0] if byte_range is not None else 0
)
cdef size_type c_range_size = (
byte_range[1] if byte_range is not None else 0
)
cdef bool c_lines = lines
if compression is not None:
if compression == 'gzip':
c_compression = cudf_io_types.compression_type.GZIP
elif compression == 'bz2':
c_compression = cudf_io_types.compression_type.BZIP2
elif compression == 'zip':
c_compression = cudf_io_types.compression_type.ZIP
else:
c_compression = cudf_io_types.compression_type.AUTO
else:
c_compression = cudf_io_types.compression_type.NONE
is_list_like_dtypes = False
if dtype is False:
raise ValueError("False value is unsupported for `dtype`")
elif dtype is not True:
if isinstance(dtype, abc.Mapping):
for k, v in dtype.items():
c_dtypes_schema_map[str(k).encode()] = \
_get_cudf_schema_element_from_dtype(v)
elif isinstance(dtype, abc.Collection):
is_list_like_dtypes = True
c_dtypes_list.reserve(len(dtype))
for col_dtype in dtype:
c_dtypes_list.push_back(
_get_cudf_data_type_from_dtype(
col_dtype))
else:
raise TypeError("`dtype` must be 'list like' or 'dict'")
cdef json_reader_options opts = move(
json_reader_options.builder(make_source_info(filepaths_or_buffers))
.compression(c_compression)
.lines(c_lines)
.byte_range_offset(c_range_offset)
.byte_range_size(c_range_size)
.legacy(legacy)
.build()
)
if is_list_like_dtypes:
opts.set_dtypes(c_dtypes_list)
else:
opts.set_dtypes(c_dtypes_schema_map)
opts.enable_keep_quotes(keep_quotes)
# Read JSON
cdef cudf_io_types.table_with_metadata c_result
with nogil:
c_result = move(libcudf_read_json(opts))
meta_names = [info.name.decode() for info in c_result.metadata.schema_info]
df = cudf.DataFrame._from_data(*data_from_unique_ptr(
move(c_result.tbl),
column_names=meta_names
))
update_struct_field_names(df, c_result.metadata.schema_info)
return df
@acquire_spill_lock()
def write_json(
table,
object path_or_buf=None,
object na_rep="null",
bool include_nulls=True,
bool lines=False,
bool index=False,
int rows_per_chunk=1024*64, # 64K rows
):
"""
Cython function to call into libcudf API, see `write_json`.
See Also
--------
cudf.to_json
"""
cdef table_view input_table_view = table_view_from_table(
table, ignore_index=True
)
cdef unique_ptr[data_sink] data_sink_c
cdef sink_info sink_info_c = make_sink_info(path_or_buf, data_sink_c)
cdef string na_c = na_rep.encode()
cdef bool include_nulls_c = include_nulls
cdef bool lines_c = lines
cdef int rows_per_chunk_c = rows_per_chunk
cdef string true_value_c = 'true'.encode()
cdef string false_value_c = 'false'.encode()
cdef table_metadata tbl_meta
num_index_cols_meta = 0
cdef column_name_info child_info
for i, name in enumerate(table._column_names, num_index_cols_meta):
child_info.name = name.encode()
tbl_meta.schema_info.push_back(child_info)
_set_col_children_metadata(
table[name]._column,
tbl_meta.schema_info[i]
)
cdef json_writer_options options = move(
json_writer_options.builder(sink_info_c, input_table_view)
.metadata(tbl_meta)
.na_rep(na_c)
.include_nulls(include_nulls_c)
.lines(lines_c)
.rows_per_chunk(rows_per_chunk_c)
.true_value(true_value_c)
.false_value(false_value_c)
.build()
)
try:
with nogil:
libcudf_write_json(options)
except OverflowError:
raise OverflowError(
f"Writing JSON file with rows_per_chunk={rows_per_chunk} failed. "
"Consider providing a smaller rows_per_chunk argument."
)
cdef schema_element _get_cudf_schema_element_from_dtype(object dtype) except *:
cdef schema_element s_element
cdef data_type lib_type
if cudf.api.types.is_categorical_dtype(dtype):
raise NotImplementedError(
"CategoricalDtype as dtype is not yet "
"supported in JSON reader"
)
dtype = cudf.dtype(dtype)
lib_type = dtype_to_data_type(dtype)
s_element.type = lib_type
if isinstance(dtype, cudf.StructDtype):
for name, child_type in dtype.fields.items():
s_element.child_types[name.encode()] = \
_get_cudf_schema_element_from_dtype(child_type)
elif isinstance(dtype, cudf.ListDtype):
s_element.child_types["offsets".encode()] = \
_get_cudf_schema_element_from_dtype(cudf.dtype("int32"))
s_element.child_types["element".encode()] = \
_get_cudf_schema_element_from_dtype(dtype.element_type)
return s_element
cdef data_type _get_cudf_data_type_from_dtype(object dtype) except *:
if cudf.api.types.is_categorical_dtype(dtype):
raise NotImplementedError(
"CategoricalDtype as dtype is not yet "
"supported in JSON reader"
)
dtype = cudf.dtype(dtype)
return dtype_to_data_type(dtype)
cdef _set_col_children_metadata(Column col,
column_name_info& col_meta):
cdef column_name_info child_info
if is_struct_dtype(col):
for i, (child_col, name) in enumerate(
zip(col.children, list(col.dtype.fields))
):
child_info.name = name.encode()
col_meta.children.push_back(child_info)
_set_col_children_metadata(
child_col, col_meta.children[i]
)
elif is_list_dtype(col):
for i, child_col in enumerate(col.children):
col_meta.children.push_back(child_info)
_set_col_children_metadata(
child_col, col_meta.children[i]
)
else:
return
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/binaryop.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from enum import IntEnum
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf._lib.binaryop cimport underlying_type_t_binary_operator
from cudf._lib.column cimport Column
from cudf._lib.scalar import as_device_scalar
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.types import SUPPORTED_NUMPY_TO_LIBCUDF_TYPES
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.types cimport data_type, type_id
from cudf._lib.types cimport dtype_to_data_type, underlying_type_t_type_id
from cudf.api.types import is_scalar
from cudf.core.buffer import acquire_spill_lock
cimport cudf._lib.cpp.binaryop as cpp_binaryop
from cudf._lib.cpp.binaryop cimport binary_operator
import cudf
class BinaryOperation(IntEnum):
ADD = (
<underlying_type_t_binary_operator> binary_operator.ADD
)
SUB = (
<underlying_type_t_binary_operator> binary_operator.SUB
)
MUL = (
<underlying_type_t_binary_operator> binary_operator.MUL
)
DIV = (
<underlying_type_t_binary_operator> binary_operator.DIV
)
TRUEDIV = (
<underlying_type_t_binary_operator> binary_operator.TRUE_DIV
)
FLOORDIV = (
<underlying_type_t_binary_operator> binary_operator.FLOOR_DIV
)
MOD = (
<underlying_type_t_binary_operator> binary_operator.PYMOD
)
POW = (
<underlying_type_t_binary_operator> binary_operator.POW
)
INT_POW = (
<underlying_type_t_binary_operator> binary_operator.INT_POW
)
EQ = (
<underlying_type_t_binary_operator> binary_operator.EQUAL
)
NE = (
<underlying_type_t_binary_operator> binary_operator.NOT_EQUAL
)
LT = (
<underlying_type_t_binary_operator> binary_operator.LESS
)
GT = (
<underlying_type_t_binary_operator> binary_operator.GREATER
)
LE = (
<underlying_type_t_binary_operator> binary_operator.LESS_EQUAL
)
GE = (
<underlying_type_t_binary_operator> binary_operator.GREATER_EQUAL
)
AND = (
<underlying_type_t_binary_operator> binary_operator.BITWISE_AND
)
OR = (
<underlying_type_t_binary_operator> binary_operator.BITWISE_OR
)
XOR = (
<underlying_type_t_binary_operator> binary_operator.BITWISE_XOR
)
L_AND = (
<underlying_type_t_binary_operator> binary_operator.LOGICAL_AND
)
L_OR = (
<underlying_type_t_binary_operator> binary_operator.LOGICAL_OR
)
GENERIC_BINARY = (
<underlying_type_t_binary_operator> binary_operator.GENERIC_BINARY
)
NULL_EQUALS = (
<underlying_type_t_binary_operator> binary_operator.NULL_EQUALS
)
cdef binaryop_v_v(Column lhs, Column rhs,
binary_operator c_op, data_type c_dtype):
cdef column_view c_lhs = lhs.view()
cdef column_view c_rhs = rhs.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_binaryop.binary_operation(
c_lhs,
c_rhs,
c_op,
c_dtype
)
)
return Column.from_unique_ptr(move(c_result))
cdef binaryop_v_s(Column lhs, DeviceScalar rhs,
binary_operator c_op, data_type c_dtype):
cdef column_view c_lhs = lhs.view()
cdef const scalar* c_rhs = rhs.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_binaryop.binary_operation(
c_lhs,
c_rhs[0],
c_op,
c_dtype
)
)
return Column.from_unique_ptr(move(c_result))
cdef binaryop_s_v(DeviceScalar lhs, Column rhs,
binary_operator c_op, data_type c_dtype):
cdef const scalar* c_lhs = lhs.get_raw_ptr()
cdef column_view c_rhs = rhs.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_binaryop.binary_operation(
c_lhs[0],
c_rhs,
c_op,
c_dtype
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def binaryop(lhs, rhs, op, dtype):
"""
Dispatches a binary op call to the appropriate libcudf function:
"""
# TODO: Shouldn't have to keep special-casing. We need to define a separate
# pipeline for libcudf binops that don't map to Python binops.
if op not in {"INT_POW", "NULL_EQUALS"}:
op = op[2:-2]
op = BinaryOperation[op.upper()]
cdef binary_operator c_op = <binary_operator> (
<underlying_type_t_binary_operator> op
)
cdef data_type c_dtype = dtype_to_data_type(dtype)
if is_scalar(lhs) or lhs is None:
s_lhs = as_device_scalar(lhs, dtype=rhs.dtype if lhs is None else None)
result = binaryop_s_v(
s_lhs,
rhs,
c_op,
c_dtype
)
elif is_scalar(rhs) or rhs is None:
s_rhs = as_device_scalar(rhs, dtype=lhs.dtype if rhs is None else None)
result = binaryop_v_s(
lhs,
s_rhs,
c_op,
c_dtype
)
else:
result = binaryop_v_v(
lhs,
rhs,
c_op,
c_dtype
)
return result
@acquire_spill_lock()
def binaryop_udf(Column lhs, Column rhs, udf_ptx, dtype):
"""
Apply a user-defined binary operator (a UDF) defined in `udf_ptx` on
the two input columns `lhs` and `rhs`. The output type of the UDF
has to be specified in `dtype`, a numpy data type.
Currently ONLY int32, int64, float32 and float64 are supported.
"""
cdef column_view c_lhs = lhs.view()
cdef column_view c_rhs = rhs.view()
cdef type_id tid = (
<type_id> (
<underlying_type_t_type_id> (
SUPPORTED_NUMPY_TO_LIBCUDF_TYPES[cudf.dtype(dtype)]
)
)
)
cdef data_type c_dtype = data_type(tid)
cdef string cpp_str = udf_ptx.encode("UTF-8")
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_binaryop.binary_operation(
c_lhs,
c_rhs,
cpp_str,
c_dtype
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings_udf.pyx
|
# Copyright (c) 2022-2023, NVIDIA CORPORATION.
from libc.stdint cimport uint8_t, uint16_t, uintptr_t
from cudf._lib.cpp.strings_udf cimport (
get_character_cases_table as cpp_get_character_cases_table,
get_character_flags_table as cpp_get_character_flags_table,
get_special_case_mapping_table as cpp_get_special_case_mapping_table,
)
import numpy as np
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import as_buffer
from rmm._lib.device_buffer cimport DeviceBuffer, device_buffer
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column, column_view
from cudf._lib.cpp.strings_udf cimport (
column_from_udf_string_array as cpp_column_from_udf_string_array,
free_udf_string_array as cpp_free_udf_string_array,
to_string_view_array as cpp_to_string_view_array,
udf_string,
)
def column_to_string_view_array(Column strings_col):
cdef unique_ptr[device_buffer] c_buffer
cdef column_view input_view = strings_col.view()
with nogil:
c_buffer = move(cpp_to_string_view_array(input_view))
db = DeviceBuffer.c_from_unique_ptr(move(c_buffer))
return as_buffer(db, exposed=True)
def column_from_udf_string_array(DeviceBuffer d_buffer):
cdef size_t size = int(d_buffer.c_size() / sizeof(udf_string))
cdef udf_string* data = <udf_string*>d_buffer.c_data()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_column_from_udf_string_array(data, size))
cpp_free_udf_string_array(data, size)
result = Column.from_unique_ptr(move(c_result))
return result
def get_character_flags_table_ptr():
cdef const uint8_t* tbl_ptr = cpp_get_character_flags_table()
return np.uintp(<uintptr_t>tbl_ptr)
def get_character_cases_table_ptr():
cdef const uint16_t* tbl_ptr = cpp_get_character_cases_table()
return np.uintp(<uintptr_t>tbl_ptr)
def get_special_case_mapping_table_ptr():
cdef const void* tbl_ptr = cpp_get_special_case_mapping_table()
return np.uintp(<uintptr_t>tbl_ptr)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/orc.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
import cudf
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool, int
from libcpp.map cimport map
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
from collections import OrderedDict
cimport cudf._lib.cpp.lists.lists_column_view as cpp_lists_column_view
try:
import ujson as json
except ImportError:
import json
cimport cudf._lib.cpp.io.types as cudf_io_types
from cudf._lib.column cimport Column
from cudf._lib.cpp.io.data_sink cimport data_sink
from cudf._lib.cpp.io.orc cimport (
chunked_orc_writer_options,
orc_chunked_writer,
orc_reader_options,
orc_writer_options,
read_orc as libcudf_read_orc,
write_orc as libcudf_write_orc,
)
from cudf._lib.cpp.io.orc_metadata cimport (
raw_orc_statistics,
read_raw_orc_statistics as libcudf_read_raw_orc_statistics,
)
from cudf._lib.cpp.io.types cimport (
column_in_metadata,
compression_type,
sink_info,
source_info,
table_input_metadata,
table_with_metadata,
)
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport data_type, size_type, type_id
from cudf._lib.io.datasource cimport NativeFileDatasource
from cudf._lib.io.utils cimport (
make_sink_info,
make_source_info,
update_column_struct_field_names,
)
from cudf._lib.types import SUPPORTED_NUMPY_TO_LIBCUDF_TYPES
from cudf._lib.types cimport underlying_type_t_type_id
from cudf._lib.utils cimport data_from_unique_ptr, table_view_from_table
from pyarrow.lib import NativeFile
from cudf._lib.utils import _index_level_name, generate_pandas_metadata
from cudf.api.types import is_list_dtype, is_struct_dtype
cpdef read_raw_orc_statistics(filepath_or_buffer):
"""
Cython function to call into libcudf API, see `read_raw_orc_statistics`.
See Also
--------
cudf.io.orc.read_orc_statistics
"""
# Handle NativeFile input
if isinstance(filepath_or_buffer, NativeFile):
filepath_or_buffer = NativeFileDatasource(filepath_or_buffer)
cdef raw_orc_statistics raw = (
libcudf_read_raw_orc_statistics(make_source_info([filepath_or_buffer]))
)
return (raw.column_names, raw.file_stats, raw.stripes_stats)
cpdef read_orc(object filepaths_or_buffers,
object columns=None,
object stripes=None,
object skip_rows=None,
object num_rows=None,
bool use_index=True,
object timestamp_type=None):
"""
Cython function to call into libcudf API, see `read_orc`.
See Also
--------
cudf.read_orc
"""
cdef orc_reader_options c_orc_reader_options = make_orc_reader_options(
filepaths_or_buffers,
columns,
stripes or [],
get_size_t_arg(skip_rows, "skip_rows"),
get_size_t_arg(num_rows, "num_rows"),
(
type_id.EMPTY
if timestamp_type is None else
<type_id>(
<underlying_type_t_type_id> (
SUPPORTED_NUMPY_TO_LIBCUDF_TYPES[
cudf.dtype(timestamp_type)
]
)
)
),
use_index,
)
cdef table_with_metadata c_result
with nogil:
c_result = move(libcudf_read_orc(c_orc_reader_options))
names = [info.name.decode() for info in c_result.metadata.schema_info]
actual_index_names, col_names, is_range_index, reset_index_name, \
range_idx = _get_index_from_metadata(c_result.metadata.user_data,
names,
skip_rows,
num_rows)
data, index = data_from_unique_ptr(
move(c_result.tbl),
col_names if columns is None else names,
actual_index_names
)
if is_range_index:
index = range_idx
elif reset_index_name:
index.names = [None] * len(index.names)
data = {
name: update_column_struct_field_names(
col, c_result.metadata.schema_info[i]
)
for i, (name, col) in enumerate(data.items())
}
return data, index
cdef compression_type _get_comp_type(object compression):
if compression is None or compression is False:
return compression_type.NONE
elif compression == "snappy":
return compression_type.SNAPPY
elif compression == "ZLIB":
return compression_type.ZLIB
elif compression == "ZSTD":
return compression_type.ZSTD
else:
raise ValueError(f"Unsupported `compression` type {compression}")
cdef tuple _get_index_from_metadata(
map[string, string] user_data,
object names,
object skip_rows,
object num_rows):
json_str = user_data[b'pandas'].decode('utf-8')
meta = None
index_col = None
is_range_index = False
reset_index_name = False
range_idx = None
if json_str != "":
meta = json.loads(json_str)
if 'index_columns' in meta and len(meta['index_columns']) > 0:
index_col = meta['index_columns']
if isinstance(index_col[0], dict) and \
index_col[0]['kind'] == 'range':
is_range_index = True
else:
index_col_names = OrderedDict()
for idx_col in index_col:
for c in meta['columns']:
if c['field_name'] == idx_col:
index_col_names[idx_col] = \
c['name'] or c['field_name']
if c['name'] is None:
reset_index_name = True
actual_index_names = None
if index_col is not None and len(index_col) > 0:
if is_range_index:
range_index_meta = index_col[0]
range_idx = cudf.RangeIndex(
start=range_index_meta['start'],
stop=range_index_meta['stop'],
step=range_index_meta['step'],
name=range_index_meta['name']
)
if skip_rows is not None:
range_idx = range_idx[skip_rows:]
if num_rows is not None:
range_idx = range_idx[:num_rows]
else:
actual_index_names = list(index_col_names.values())
names = names[len(actual_index_names):]
return (
actual_index_names,
names,
is_range_index,
reset_index_name,
range_idx
)
cdef cudf_io_types.statistics_freq _get_orc_stat_freq(object statistics):
"""
Convert ORC statistics terms to CUDF convention:
- ORC "STRIPE" == CUDF "ROWGROUP"
- ORC "ROWGROUP" == CUDF "PAGE"
"""
statistics = str(statistics).upper()
if statistics == "NONE":
return cudf_io_types.statistics_freq.STATISTICS_NONE
elif statistics == "STRIPE":
return cudf_io_types.statistics_freq.STATISTICS_ROWGROUP
elif statistics == "ROWGROUP":
return cudf_io_types.statistics_freq.STATISTICS_PAGE
else:
raise ValueError(f"Unsupported `statistics_freq` type {statistics}")
@acquire_spill_lock()
def write_orc(
table,
object path_or_buf,
object compression="snappy",
object statistics="ROWGROUP",
object stripe_size_bytes=None,
object stripe_size_rows=None,
object row_index_stride=None,
object cols_as_map_type=None,
object index=None
):
"""
Cython function to call into libcudf API, see `cudf::io::write_orc`.
See Also
--------
cudf.read_orc
"""
cdef compression_type compression_ = _get_comp_type(compression)
cdef unique_ptr[data_sink] data_sink_c
cdef sink_info sink_info_c = make_sink_info(path_or_buf, data_sink_c)
cdef table_input_metadata tbl_meta
cdef map[string, string] user_data
user_data[str.encode("pandas")] = str.encode(generate_pandas_metadata(
table, index)
)
if index is True or (
index is None and not isinstance(table._index, cudf.RangeIndex)
):
tv = table_view_from_table(table)
tbl_meta = table_input_metadata(tv)
for level, idx_name in enumerate(table._index.names):
tbl_meta.column_metadata[level].set_name(
str.encode(
_index_level_name(idx_name, level, table._column_names)
)
)
num_index_cols_meta = len(table._index.names)
else:
tv = table_view_from_table(table, ignore_index=True)
tbl_meta = table_input_metadata(tv)
num_index_cols_meta = 0
if cols_as_map_type is not None:
cols_as_map_type = set(cols_as_map_type)
for i, name in enumerate(table._column_names, num_index_cols_meta):
tbl_meta.column_metadata[i].set_name(name.encode())
_set_col_children_metadata(
table[name]._column,
tbl_meta.column_metadata[i],
(cols_as_map_type is not None)
and (name in cols_as_map_type),
)
cdef orc_writer_options c_orc_writer_options = move(
orc_writer_options.builder(
sink_info_c, tv
).metadata(tbl_meta)
.key_value_metadata(move(user_data))
.compression(compression_)
.enable_statistics(_get_orc_stat_freq(statistics))
.build()
)
if stripe_size_bytes is not None:
c_orc_writer_options.set_stripe_size_bytes(stripe_size_bytes)
if stripe_size_rows is not None:
c_orc_writer_options.set_stripe_size_rows(stripe_size_rows)
if row_index_stride is not None:
c_orc_writer_options.set_row_index_stride(row_index_stride)
with nogil:
libcudf_write_orc(c_orc_writer_options)
cdef size_type get_size_t_arg(object arg, str name) except*:
if name == "skip_rows":
arg = 0 if arg is None else arg
if not isinstance(arg, int) or arg < 0:
raise TypeError(f"{name} must be an int >= 0")
else:
arg = -1 if arg is None else arg
if not isinstance(arg, int) or arg < -1:
raise TypeError(f"{name} must be an int >= -1")
return <size_type> arg
cdef orc_reader_options make_orc_reader_options(
object filepaths_or_buffers,
object column_names,
object stripes,
size_type skip_rows,
size_type num_rows,
type_id timestamp_type,
bool use_index
) except*:
for i, datasource in enumerate(filepaths_or_buffers):
if isinstance(datasource, NativeFile):
filepaths_or_buffers[i] = NativeFileDatasource(datasource)
cdef vector[vector[size_type]] strps = stripes
cdef orc_reader_options opts
cdef source_info src = make_source_info(filepaths_or_buffers)
opts = move(
orc_reader_options.builder(src)
.stripes(strps)
.skip_rows(skip_rows)
.timestamp_type(data_type(timestamp_type))
.use_index(use_index)
.build()
)
if num_rows >= 0:
opts.set_num_rows(num_rows)
cdef vector[string] c_column_names
if column_names is not None:
c_column_names.reserve(len(column_names))
for col in column_names:
c_column_names.push_back(str(col).encode())
opts.set_columns(c_column_names)
return opts
cdef class ORCWriter:
"""
ORCWriter lets you you incrementally write out a ORC file from a series
of cudf tables
See Also
--------
cudf.io.orc.to_orc
"""
cdef bool initialized
cdef unique_ptr[orc_chunked_writer] writer
cdef sink_info sink
cdef unique_ptr[data_sink] _data_sink
cdef cudf_io_types.statistics_freq stat_freq
cdef compression_type comp_type
cdef object index
cdef table_input_metadata tbl_meta
cdef object cols_as_map_type
def __cinit__(self,
object path,
object index=None,
object compression="snappy",
object statistics="ROWGROUP",
object cols_as_map_type=None):
self.sink = make_sink_info(path, self._data_sink)
self.stat_freq = _get_orc_stat_freq(statistics)
self.comp_type = _get_comp_type(compression)
self.index = index
self.cols_as_map_type = cols_as_map_type \
if cols_as_map_type is None else set(cols_as_map_type)
self.initialized = False
def write_table(self, table):
""" Writes a single table to the file """
if not self.initialized:
self._initialize_chunked_state(table)
keep_index = self.index is not False and (
table._index.name is not None or
isinstance(table._index, cudf.core.multiindex.MultiIndex)
)
tv = table_view_from_table(table, not keep_index)
with nogil:
self.writer.get()[0].write(tv)
def close(self):
if not self.initialized:
return
with nogil:
self.writer.get()[0].close()
def __dealloc__(self):
self.close()
def _initialize_chunked_state(self, table):
"""
Prepare all the values required to build the
chunked_orc_writer_options anb creates a writer"""
cdef table_view tv
num_index_cols_meta = 0
self.tbl_meta = table_input_metadata(
table_view_from_table(table, ignore_index=True),
)
if self.index is not False:
if isinstance(table._index, cudf.core.multiindex.MultiIndex):
tv = table_view_from_table(table)
self.tbl_meta = table_input_metadata(tv)
for level, idx_name in enumerate(table._index.names):
self.tbl_meta.column_metadata[level].set_name(
(str.encode(idx_name))
)
num_index_cols_meta = len(table._index.names)
else:
if table._index.name is not None:
tv = table_view_from_table(table)
self.tbl_meta = table_input_metadata(tv)
self.tbl_meta.column_metadata[0].set_name(
str.encode(table._index.name)
)
num_index_cols_meta = 1
for i, name in enumerate(table._column_names, num_index_cols_meta):
self.tbl_meta.column_metadata[i].set_name(name.encode())
_set_col_children_metadata(
table[name]._column,
self.tbl_meta.column_metadata[i],
(self.cols_as_map_type is not None)
and (name in self.cols_as_map_type),
)
cdef map[string, string] user_data
pandas_metadata = generate_pandas_metadata(table, self.index)
user_data[str.encode("pandas")] = str.encode(pandas_metadata)
cdef chunked_orc_writer_options args
with nogil:
args = move(
chunked_orc_writer_options.builder(self.sink)
.metadata(self.tbl_meta)
.key_value_metadata(move(user_data))
.compression(self.comp_type)
.enable_statistics(self.stat_freq)
.build()
)
self.writer.reset(new orc_chunked_writer(args))
self.initialized = True
cdef _set_col_children_metadata(Column col,
column_in_metadata& col_meta,
list_column_as_map=False):
if is_struct_dtype(col):
for i, (child_col, name) in enumerate(
zip(col.children, list(col.dtype.fields))
):
col_meta.child(i).set_name(name.encode())
_set_col_children_metadata(
child_col, col_meta.child(i), list_column_as_map
)
elif is_list_dtype(col):
if list_column_as_map:
col_meta.set_list_column_as_map()
_set_col_children_metadata(
col.children[cpp_lists_column_view.child_column_index],
col_meta.child(cpp_lists_column_view.child_column_index),
list_column_as_map
)
else:
return
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/lists.pyx
|
# Copyright (c) 2021-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool
from libcpp.memory cimport make_shared, shared_ptr, unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.lists.combine cimport (
concatenate_list_elements as cpp_concatenate_list_elements,
concatenate_null_policy,
concatenate_rows as cpp_concatenate_rows,
)
from cudf._lib.cpp.lists.contains cimport contains, index_of as cpp_index_of
from cudf._lib.cpp.lists.count_elements cimport (
count_elements as cpp_count_elements,
)
from cudf._lib.cpp.lists.explode cimport explode_outer as cpp_explode_outer
from cudf._lib.cpp.lists.extract cimport extract_list_element
from cudf._lib.cpp.lists.lists_column_view cimport lists_column_view
from cudf._lib.cpp.lists.sorting cimport sort_lists as cpp_sort_lists
from cudf._lib.cpp.lists.stream_compaction cimport distinct as cpp_distinct
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport (
nan_equality,
null_equality,
null_order,
order,
size_type,
)
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.utils cimport columns_from_unique_ptr, table_view_from_columns
@acquire_spill_lock()
def count_elements(Column col):
# shared_ptr required because lists_column_view has no default
# ctor
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_count_elements(list_view.get()[0]))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def explode_outer(
list source_columns, int explode_column_idx
):
cdef table_view c_table_view = table_view_from_columns(source_columns)
cdef size_type c_explode_column_idx = explode_column_idx
cdef unique_ptr[table] c_result
with nogil:
c_result = move(cpp_explode_outer(c_table_view, c_explode_column_idx))
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def distinct(Column col, bool nulls_equal, bool nans_all_equal):
"""
nulls_equal == True indicates that libcudf should treat any two nulls as
equal, and as unequal otherwise.
nans_all_equal == True indicates that libcudf should treat any two
elements from {-nan, +nan} as equal, and as unequal otherwise.
"""
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef null_equality c_nulls_equal = (
null_equality.EQUAL if nulls_equal else null_equality.UNEQUAL
)
cdef nan_equality c_nans_equal = (
nan_equality.ALL_EQUAL if nans_all_equal else nan_equality.NANS_UNEQUAL
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_distinct(list_view.get()[0],
c_nulls_equal,
c_nans_equal)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def sort_lists(Column col, bool ascending, str na_position):
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef order c_sort_order = (
order.ASCENDING if ascending else order.DESCENDING
)
cdef null_order c_null_prec = (
null_order.BEFORE if na_position == "first" else null_order.AFTER
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_sort_lists(list_view.get()[0], c_sort_order, c_null_prec)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def extract_element_scalar(Column col, size_type index):
# shared_ptr required because lists_column_view has no default
# ctor
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(extract_list_element(list_view.get()[0], index))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def extract_element_column(Column col, Column index):
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef column_view index_view = index.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(extract_list_element(list_view.get()[0], index_view))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def contains_scalar(Column col, object py_search_key):
cdef DeviceScalar search_key = py_search_key.device_value
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef const scalar* search_key_value = search_key.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(contains(
list_view.get()[0],
search_key_value[0],
))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def index_of_scalar(Column col, object py_search_key):
cdef DeviceScalar search_key = py_search_key.device_value
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef const scalar* search_key_value = search_key.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_index_of(
list_view.get()[0],
search_key_value[0],
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def index_of_column(Column col, Column search_keys):
cdef column_view keys_view = search_keys.view()
cdef shared_ptr[lists_column_view] list_view = (
make_shared[lists_column_view](col.view())
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_index_of(
list_view.get()[0],
keys_view,
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def concatenate_rows(list source_columns):
cdef unique_ptr[column] c_result
cdef table_view c_table_view = table_view_from_columns(source_columns)
with nogil:
c_result = move(cpp_concatenate_rows(
c_table_view,
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def concatenate_list_elements(Column input_column, dropna=False):
cdef concatenate_null_policy policy = (
concatenate_null_policy.IGNORE if dropna
else concatenate_null_policy.NULLIFY_OUTPUT_ROW
)
cdef column_view c_input = input_column.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_concatenate_list_elements(
c_input,
policy
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/hash.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.pair cimport pair
from libcpp.utility cimport move
from libcpp.vector cimport vector
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.hash cimport hash as cpp_hash, hash_id as cpp_hash_id
from cudf._lib.cpp.partitioning cimport hash_partition as cpp_hash_partition
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.utils cimport columns_from_unique_ptr, table_view_from_columns
@acquire_spill_lock()
def hash_partition(list source_columns, object columns_to_hash,
int num_partitions):
cdef vector[libcudf_types.size_type] c_columns_to_hash = columns_to_hash
cdef int c_num_partitions = num_partitions
cdef table_view c_source_view = table_view_from_columns(source_columns)
cdef pair[unique_ptr[table], vector[libcudf_types.size_type]] c_result
with nogil:
c_result = move(
cpp_hash_partition(
c_source_view,
c_columns_to_hash,
c_num_partitions
)
)
return (
columns_from_unique_ptr(move(c_result.first)),
list(c_result.second)
)
@acquire_spill_lock()
def hash(list source_columns, str method, int seed=0):
cdef table_view c_source_view = table_view_from_columns(source_columns)
cdef unique_ptr[column] c_result
cdef cpp_hash_id c_hash_function
if method == "murmur3":
c_hash_function = cpp_hash_id.HASH_MURMUR3
elif method == "md5":
c_hash_function = cpp_hash_id.HASH_MD5
else:
raise ValueError(f"Unsupported hash function: {method}")
with nogil:
c_result = move(
cpp_hash(
c_source_view,
c_hash_function,
seed
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/replace.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.api.types import is_scalar
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.scalar import as_device_scalar
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view, mutable_column_view
from cudf._lib.cpp.replace cimport (
clamp as cpp_clamp,
find_and_replace_all as cpp_find_and_replace_all,
normalize_nans_and_zeros as cpp_normalize_nans_and_zeros,
replace_nulls as cpp_replace_nulls,
replace_policy as cpp_replace_policy,
)
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def replace(Column input_col, Column values_to_replace,
Column replacement_values):
"""
Replaces values from values_to_replace with corresponding value from
replacement_values in input_col
Parameters
----------
input_col : Column whose value will be updated
values_to_replace : Column with values which needs to be replaced
replacement_values : Column with values which will replace
"""
cdef column_view input_col_view = input_col.view()
cdef column_view values_to_replace_view = values_to_replace.view()
cdef column_view replacement_values_view = replacement_values.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_find_and_replace_all(input_col_view,
values_to_replace_view,
replacement_values_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_nulls_column(Column input_col, Column replacement_values):
"""
Replaces null values in input_col with corresponding values from
replacement_values
Parameters
----------
input_col : Column whose value will be updated
replacement_values : Column with values which will replace nulls
"""
cdef column_view input_col_view = input_col.view()
cdef column_view replacement_values_view = replacement_values.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_replace_nulls(input_col_view,
replacement_values_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_nulls_scalar(Column input_col, DeviceScalar replacement_value):
"""
Replaces null values in input_col with replacement_value
Parameters
----------
input_col : Column whose value will be updated
replacement_value : DeviceScalar with value which will replace nulls
"""
cdef column_view input_col_view = input_col.view()
cdef const scalar* replacement_value_scalar = replacement_value\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_replace_nulls(input_col_view,
replacement_value_scalar[0]))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_nulls_fill(Column input_col, object method):
"""
Replaces null values in input_col with replacement_value
Parameters
----------
input_col : Column whose value will be updated
method : 'ffill' or 'bfill'
"""
cdef column_view input_col_view = input_col.view()
cdef unique_ptr[column] c_result
cdef cpp_replace_policy policy = (
cpp_replace_policy.PRECEDING
if method == 'ffill'
else cpp_replace_policy.FOLLOWING
)
with nogil:
c_result = move(cpp_replace_nulls(input_col_view, policy))
return Column.from_unique_ptr(move(c_result))
def replace_nulls(
Column input_col,
object replacement=None,
object method=None,
object dtype=None
):
"""
Calls one of the version of replace_nulls depending on type
of replacement
"""
if replacement is None and method is None:
raise ValueError("Must specify a fill 'value' or 'method'.")
if replacement and method:
raise ValueError("Cannot specify both 'value' and 'method'.")
if method:
return replace_nulls_fill(input_col, method)
elif is_scalar(replacement):
return replace_nulls_scalar(
input_col,
as_device_scalar(replacement, dtype=dtype)
)
else:
return replace_nulls_column(input_col, replacement)
@acquire_spill_lock()
def clamp(Column input_col, DeviceScalar lo, DeviceScalar lo_replace,
DeviceScalar hi, DeviceScalar hi_replace):
"""
Clip the input_col such that values < lo will be replaced by lo_replace
and > hi will be replaced by hi_replace
Parameters
----------
input_col : Column whose value will be updated
lo : DeviceScalar value for clipping lower values
lo_replace : DeviceScalar value which will replace clipped with lo
hi : DeviceScalar value for clipping upper values
lo_replace : DeviceScalar value which will replace clipped with hi
"""
cdef column_view input_col_view = input_col.view()
cdef const scalar* lo_value = lo.get_raw_ptr()
cdef const scalar* lo_replace_value = lo_replace.get_raw_ptr()
cdef const scalar* hi_value = hi.get_raw_ptr()
cdef const scalar* hi_replace_value = hi_replace.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_clamp(
input_col_view, lo_value[0],
lo_replace_value[0], hi_value[0], hi_replace_value[0]))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def clamp(Column input_col, DeviceScalar lo, DeviceScalar hi):
"""
Clip the input_col such that values < lo will be replaced by lo
and > hi will be replaced by hi
Parameters
----------
input_col : Column whose value will be updated
lo : DeviceScalar value for clipping lower values
hi : DeviceScalar value for clipping upper values
"""
cdef column_view input_col_view = input_col.view()
cdef const scalar* lo_value = lo.get_raw_ptr()
cdef const scalar* hi_value = hi.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_clamp(input_col_view, lo_value[0], hi_value[0]))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def clip(Column input_col, object lo, object hi):
"""
Clip the input_col such that values < lo will be replaced by lo
and > hi will be replaced by hi
"""
lo_scalar = as_device_scalar(lo, dtype=input_col.dtype)
hi_scalar = as_device_scalar(hi, dtype=input_col.dtype)
return clamp(input_col, lo_scalar, hi_scalar)
@acquire_spill_lock()
def normalize_nans_and_zeros_inplace(Column input_col):
"""
Inplace normalizing
"""
cdef mutable_column_view input_col_view = input_col.mutable_view()
with nogil:
cpp_normalize_nans_and_zeros(input_col_view)
@acquire_spill_lock()
def normalize_nans_and_zeros_column(Column input_col):
"""
Returns a new normalized Column
"""
cdef column_view input_col_view = input_col.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_normalize_nans_and_zeros(input_col_view))
return Column.from_unique_ptr(move(c_result))
def normalize_nans_and_zeros(Column input_col, in_place=False):
"""
Normalize the NaN and zeros in input_col
Convert -NaN -> NaN
Convert -0.0 -> 0.0
Parameters
----------
input_col : Column that needs to be normalized
in_place : boolean whether to normalize in place or return new column
"""
if in_place is True:
normalize_nans_and_zeros_inplace(input_col)
else:
return normalize_nans_and_zeros_column(input_col)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/unary.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from enum import IntEnum
from cudf.api.types import is_decimal_dtype
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
import numpy as np
cimport cudf._lib.cpp.unary as libcudf_unary
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.types cimport data_type
from cudf._lib.cpp.unary cimport unary_operator, underlying_type_t_unary_op
from cudf._lib.types cimport dtype_to_data_type
class UnaryOp(IntEnum):
SIN = <underlying_type_t_unary_op> unary_operator.SIN
COS = <underlying_type_t_unary_op> unary_operator.COS
TAN = <underlying_type_t_unary_op> unary_operator.TAN
ASIN = <underlying_type_t_unary_op> unary_operator.ARCSIN
ACOS = <underlying_type_t_unary_op> unary_operator.ARCCOS
ATAN = <underlying_type_t_unary_op> unary_operator.ARCTAN
SINH = <underlying_type_t_unary_op> unary_operator.SINH
COSH = <underlying_type_t_unary_op> unary_operator.COSH
TANH = <underlying_type_t_unary_op> unary_operator.TANH
ARCSINH = <underlying_type_t_unary_op> unary_operator.ARCSINH
ARCCOSH = <underlying_type_t_unary_op> unary_operator.ARCCOSH
ARCTANH = <underlying_type_t_unary_op> unary_operator.ARCTANH
EXP = <underlying_type_t_unary_op> unary_operator.EXP
LOG = <underlying_type_t_unary_op> unary_operator.LOG
SQRT = <underlying_type_t_unary_op> unary_operator.SQRT
CBRT = <underlying_type_t_unary_op> unary_operator.CBRT
CEIL = <underlying_type_t_unary_op> unary_operator.CEIL
FLOOR = <underlying_type_t_unary_op> unary_operator.FLOOR
ABS = <underlying_type_t_unary_op> unary_operator.ABS
RINT = <underlying_type_t_unary_op> unary_operator.RINT
INVERT = <underlying_type_t_unary_op> unary_operator.BIT_INVERT
NOT = <underlying_type_t_unary_op> unary_operator.NOT
@acquire_spill_lock()
def unary_operation(Column input, object op):
cdef column_view c_input = input.view()
cdef unary_operator c_op = <unary_operator>(<underlying_type_t_unary_op>
op)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
libcudf_unary.unary_operation(
c_input,
c_op
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_null(Column input):
cdef column_view c_input = input.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(libcudf_unary.is_null(c_input))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_valid(Column input):
cdef column_view c_input = input.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(libcudf_unary.is_valid(c_input))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def cast(Column input, object dtype=np.float64):
cdef column_view c_input = input.view()
cdef data_type c_dtype = dtype_to_data_type(dtype)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(libcudf_unary.cast(c_input, c_dtype))
result = Column.from_unique_ptr(move(c_result))
if is_decimal_dtype(result.dtype):
result.dtype.precision = dtype.precision
return result
@acquire_spill_lock()
def is_nan(Column input):
cdef column_view c_input = input.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(libcudf_unary.is_nan(c_input))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_non_nan(Column input):
cdef column_view c_input = input.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(libcudf_unary.is_not_nan(c_input))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/exception_handler.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
# See
# https://github.com/cython/cython/blob/master/Cython/Utility/CppSupport.cpp
# for the original Cython exception handler.
cdef extern from *:
"""
#include <Python.h>
#include <cudf/utilities/error.hpp>
#include <ios>
#include <stdexcept>
namespace {
/**
* @brief Exception handler to map C++ exceptions to Python ones in Cython
*
* This exception handler extends the base exception handler provided by
* Cython. In addition to the exceptions that Cython itself supports, this
* file adds support for additional exceptions thrown by libcudf that need
* to be mapped to specific Python exceptions.
*
* Since this function interoperates with Python's exception state, it
* does not throw any C++ exceptions.
*/
void cudf_exception_handler()
{
// Catch a handful of different errors here and turn them into the
// equivalent Python errors.
try {
if (PyErr_Occurred())
; // let latest Python exn pass through and ignore the current one
throw;
} catch (const std::bad_alloc& exn) {
PyErr_SetString(PyExc_MemoryError, exn.what());
} catch (const std::bad_cast& exn) {
PyErr_SetString(PyExc_TypeError, exn.what());
} catch (const std::domain_error& exn) {
PyErr_SetString(PyExc_ValueError, exn.what());
} catch (const cudf::data_type_error& exn) {
// Catch subclass (data_type_error) before parent (invalid_argument)
PyErr_SetString(PyExc_TypeError, exn.what());
} catch (const std::invalid_argument& exn) {
PyErr_SetString(PyExc_ValueError, exn.what());
} catch (const std::ios_base::failure& exn) {
// Unfortunately, in standard C++ we have no way of distinguishing EOF
// from other errors here; be careful with the exception mask
PyErr_SetString(PyExc_IOError, exn.what());
} catch (const std::out_of_range& exn) {
// Change out_of_range to IndexError
PyErr_SetString(PyExc_IndexError, exn.what());
} catch (const std::overflow_error& exn) {
PyErr_SetString(PyExc_OverflowError, exn.what());
} catch (const std::range_error& exn) {
PyErr_SetString(PyExc_ArithmeticError, exn.what());
} catch (const std::underflow_error& exn) {
PyErr_SetString(PyExc_ArithmeticError, exn.what());
// The below is the default catch-all case.
} catch (const std::exception& exn) {
PyErr_SetString(PyExc_RuntimeError, exn.what());
} catch (...) {
PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
}
}
} // anonymous namespace
"""
cdef void cudf_exception_handler()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/column.pyi
|
# Copyright (c) 2021, NVIDIA CORPORATION.
from __future__ import annotations
from typing import Dict, Optional, Tuple
from typing_extensions import Self
from cudf._typing import Dtype, DtypeObj, ScalarLike
from cudf.core.buffer import Buffer
from cudf.core.column import ColumnBase
class Column:
_data: Optional[Buffer]
_mask: Optional[Buffer]
_base_data: Optional[Buffer]
_base_mask: Optional[Buffer]
_dtype: DtypeObj
_size: int
_offset: int
_null_count: int
_children: Tuple[ColumnBase, ...]
_base_children: Tuple[ColumnBase, ...]
_distinct_count: Dict[bool, int]
def __init__(
self,
data: Optional[Buffer],
size: int,
dtype: Dtype,
mask: Optional[Buffer] = None,
offset: Optional[int] = None,
null_count: Optional[int] = None,
children: Tuple[ColumnBase, ...] = (),
) -> None: ...
@property
def base_size(self) -> int: ...
@property
def dtype(self) -> DtypeObj: ...
@property
def size(self) -> int: ...
@property
def base_data(self) -> Optional[Buffer]: ...
@property
def data(self) -> Optional[Buffer]: ...
@property
def data_ptr(self) -> int: ...
def set_base_data(self, value: Buffer) -> None: ...
@property
def nullable(self) -> bool: ...
def has_nulls(self, include_nan: bool = False) -> bool: ...
@property
def base_mask(self) -> Optional[Buffer]: ...
@property
def mask(self) -> Optional[Buffer]: ...
@property
def mask_ptr(self) -> int: ...
def set_base_mask(self, value: Optional[Buffer]) -> None: ...
def set_mask(self, value: Optional[Buffer]) -> Self: ...
@property
def null_count(self) -> int: ...
@property
def offset(self) -> int: ...
@property
def base_children(self) -> Tuple[ColumnBase, ...]: ...
@property
def children(self) -> Tuple[ColumnBase, ...]: ...
def set_base_children(self, value: Tuple[ColumnBase, ...]) -> None: ...
def _mimic_inplace(
self, other_col: ColumnBase, inplace=False
) -> Optional[Self]: ...
# TODO: The val parameter should be Scalar, not ScalarLike
@staticmethod
def from_scalar(val: ScalarLike, size: int) -> ColumnBase: ...
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/__init__.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
import numpy as np
from . import (
avro,
binaryop,
concat,
copying,
csv,
datetime,
expressions,
filling,
groupby,
hash,
interop,
join,
json,
labeling,
merge,
null_mask,
nvtext,
orc,
parquet,
partitioning,
pylibcudf,
quantiles,
reduce,
replace,
reshape,
rolling,
round,
search,
sort,
stream_compaction,
string_casting,
strings,
strings_udf,
text,
timezone,
transpose,
unary,
)
MAX_COLUMN_SIZE = np.iinfo(np.int32).max
MAX_COLUMN_SIZE_STR = "INT32_MAX"
MAX_STRING_COLUMN_BYTES = np.iinfo(np.int32).max
MAX_STRING_COLUMN_BYTES_STR = "INT32_MAX"
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/column.pxd
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from typing import Literal
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from rmm._lib.device_buffer cimport device_buffer
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view, mutable_column_view
from cudf._lib.cpp.types cimport size_type
cdef class Column:
cdef public:
cdef int _offset
cdef int _size
cdef object _dtype
cdef object _base_children
cdef object _base_data
cdef object _base_mask
cdef object _children
cdef object _data
cdef object _mask
cdef object _null_count
cdef object _distinct_count
cdef column_view _view(self, size_type null_count) except *
cdef column_view view(self) except *
cdef mutable_column_view mutable_view(self) except *
cpdef to_pylibcudf(self, mode: Literal["read", "write"])
@staticmethod
cdef Column from_unique_ptr(
unique_ptr[column] c_col, bint data_ptr_exposed=*
)
@staticmethod
cdef Column from_column_view(column_view, object)
cdef size_type compute_null_count(self) except? 0
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/concat.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport make_unique, unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column, column_view
from cudf._lib.cpp.concatenate cimport (
concatenate_columns as libcudf_concatenate_columns,
concatenate_masks as libcudf_concatenate_masks,
concatenate_tables as libcudf_concatenate_tables,
)
from cudf._lib.cpp.table.table cimport table, table_view
from cudf._lib.utils cimport (
data_from_unique_ptr,
make_column_views,
table_view_from_table,
)
from cudf.core.buffer import acquire_spill_lock, as_buffer
from rmm._lib.device_buffer cimport DeviceBuffer, device_buffer
cpdef concat_masks(object columns):
cdef device_buffer c_result
cdef unique_ptr[device_buffer] c_unique_result
cdef vector[column_view] c_views = make_column_views(columns)
with nogil:
c_result = move(libcudf_concatenate_masks(c_views))
c_unique_result = move(make_unique[device_buffer](move(c_result)))
return as_buffer(
DeviceBuffer.c_from_unique_ptr(move(c_unique_result))
)
@acquire_spill_lock()
def concat_columns(object columns):
cdef unique_ptr[column] c_result
cdef vector[column_view] c_views = make_column_views(columns)
with nogil:
c_result = move(libcudf_concatenate_columns(c_views))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def concat_tables(object tables, bool ignore_index=False):
cdef unique_ptr[table] c_result
cdef vector[table_view] c_views
c_views.reserve(len(tables))
for tbl in tables:
c_views.push_back(table_view_from_table(tbl, ignore_index))
with nogil:
c_result = move(libcudf_concatenate_tables(c_views))
return data_from_unique_ptr(
move(c_result),
column_names=tables[0]._column_names,
index_names=None if ignore_index else tables[0]._index_names
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/rolling.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.aggregation cimport RollingAggregation, make_rolling_aggregation
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.rolling cimport rolling_window as cpp_rolling_window
from cudf._lib.cpp.types cimport size_type
@acquire_spill_lock()
def rolling(Column source_column,
Column pre_column_window,
Column fwd_column_window,
window,
min_periods,
center,
op,
agg_params):
"""
Rolling on input executing operation within the given window for each row
Parameters
----------
source_column : input column on which rolling operation is executed
pre_column_window : prior window for each element of source_column
fwd_column_window : forward window for each element of source_column
window : Size of the moving window, can be integer or None
min_periods : Minimum number of observations in window required to have
a value (otherwise result is null)
center : Set the labels at the center of the window
op : operation to be executed
agg_params : dict, parameter for the aggregation (e.g. ddof for VAR/STD)
Returns
-------
A Column with rolling calculations
"""
cdef size_type c_min_periods = min_periods
cdef size_type c_window = 0
cdef size_type c_forward_window = 0
cdef unique_ptr[column] c_result
cdef column_view source_column_view = source_column.view()
cdef column_view pre_column_window_view
cdef column_view fwd_column_window_view
cdef RollingAggregation cython_agg
if callable(op):
cython_agg = make_rolling_aggregation(
op, {'dtype': source_column.dtype})
else:
cython_agg = make_rolling_aggregation(op, agg_params)
if window is None:
if center:
# TODO: we can support this even though Pandas currently does not
raise NotImplementedError(
"center is not implemented for offset-based windows"
)
pre_column_window_view = pre_column_window.view()
fwd_column_window_view = fwd_column_window.view()
with nogil:
c_result = move(
cpp_rolling_window(
source_column_view,
pre_column_window_view,
fwd_column_window_view,
c_min_periods,
cython_agg.c_obj.get()[0])
)
else:
c_min_periods = min_periods
if center:
c_window = (window // 2) + 1
c_forward_window = window - (c_window)
else:
c_window = window
c_forward_window = 0
with nogil:
c_result = move(
cpp_rolling_window(
source_column_view,
c_window,
c_forward_window,
c_min_periods,
cython_agg.c_obj.get()[0])
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/search.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
cimport cudf._lib.cpp.search as cpp_search
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.utils cimport table_view_from_columns
@acquire_spill_lock()
def search_sorted(
list source, list values, side, ascending=True, na_position="last"
):
"""Find indices where elements should be inserted to maintain order
Parameters
----------
source : list of columns
List of columns to search in
values : List of columns
List of value columns to search for
side : str {'left', 'right'} optional
If 'left', the index of the first suitable location is given.
If 'right', return the last such index
"""
cdef unique_ptr[column] c_result
cdef vector[libcudf_types.order] c_column_order
cdef vector[libcudf_types.null_order] c_null_precedence
cdef libcudf_types.order c_order
cdef libcudf_types.null_order c_null_order
cdef table_view c_table_data = table_view_from_columns(source)
cdef table_view c_values_data = table_view_from_columns(values)
# Note: We are ignoring index columns here
c_order = (libcudf_types.order.ASCENDING
if ascending
else libcudf_types.order.DESCENDING)
c_null_order = (
libcudf_types.null_order.AFTER
if na_position=="last"
else libcudf_types.null_order.BEFORE
)
c_column_order = vector[libcudf_types.order](len(source), c_order)
c_null_precedence = vector[libcudf_types.null_order](
len(source), c_null_order
)
if side == 'left':
with nogil:
c_result = move(
cpp_search.lower_bound(
c_table_data,
c_values_data,
c_column_order,
c_null_precedence,
)
)
elif side == 'right':
with nogil:
c_result = move(
cpp_search.upper_bound(
c_table_data,
c_values_data,
c_column_order,
c_null_precedence,
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def contains(Column haystack, Column needles):
"""Check whether column contains multiple values
Parameters
----------
column : NumericalColumn
Column to search in
needles :
A column of values to search for
"""
cdef unique_ptr[column] c_result
cdef column_view c_haystack = haystack.view()
cdef column_view c_needles = needles.view()
with nogil:
c_result = move(
cpp_search.contains(
c_haystack,
c_needles,
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/avro.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.cpp.io.avro cimport (
avro_reader_options,
read_avro as libcudf_read_avro,
)
from cudf._lib.cpp.io.types cimport table_with_metadata
from cudf._lib.cpp.types cimport size_type
from cudf._lib.io.utils cimport make_source_info
from cudf._lib.utils cimport data_from_unique_ptr
cpdef read_avro(datasource, columns=None, skip_rows=-1, num_rows=-1):
"""
Cython function to call libcudf read_avro, see `read_avro`.
See Also
--------
cudf.io.avro.read_avro
"""
num_rows = -1 if num_rows is None else num_rows
skip_rows = 0 if skip_rows is None else skip_rows
if not isinstance(num_rows, int) or num_rows < -1:
raise TypeError("num_rows must be an int >= -1")
if not isinstance(skip_rows, int) or skip_rows < -1:
raise TypeError("skip_rows must be an int >= -1")
cdef vector[string] c_columns
if columns is not None and len(columns) > 0:
c_columns.reserve(len(columns))
for col in columns:
c_columns.push_back(str(col).encode())
cdef avro_reader_options options = move(
avro_reader_options.builder(make_source_info([datasource]))
.columns(c_columns)
.skip_rows(<size_type> skip_rows)
.num_rows(<size_type> num_rows)
.build()
)
cdef table_with_metadata c_result
with nogil:
c_result = move(libcudf_read_avro(options))
names = [info.name.decode() for info in c_result.metadata.schema_info]
return data_from_unique_ptr(move(c_result.tbl), column_names=names)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/aggregation.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from enum import Enum, IntEnum
import pandas as pd
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.types import SUPPORTED_NUMPY_TO_LIBCUDF_TYPES, NullHandling
from cudf.utils import cudautils
from cudf._lib.types cimport (
underlying_type_t_interpolation,
underlying_type_t_null_policy,
underlying_type_t_type_id,
)
from numba.np import numpy_support
from cudf._lib.types import Interpolation
cimport cudf._lib.cpp.aggregation as libcudf_aggregation
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.cpp.aggregation cimport (
underlying_type_t_correlation_type,
underlying_type_t_rank_method,
)
import cudf
class AggregationKind(Enum):
SUM = libcudf_aggregation.aggregation.Kind.SUM
PRODUCT = libcudf_aggregation.aggregation.Kind.PRODUCT
MIN = libcudf_aggregation.aggregation.Kind.MIN
MAX = libcudf_aggregation.aggregation.Kind.MAX
COUNT = libcudf_aggregation.aggregation.Kind.COUNT_VALID
SIZE = libcudf_aggregation.aggregation.Kind.COUNT_ALL
ANY = libcudf_aggregation.aggregation.Kind.ANY
ALL = libcudf_aggregation.aggregation.Kind.ALL
SUM_OF_SQUARES = libcudf_aggregation.aggregation.Kind.SUM_OF_SQUARES
MEAN = libcudf_aggregation.aggregation.Kind.MEAN
VAR = libcudf_aggregation.aggregation.Kind.VARIANCE
STD = libcudf_aggregation.aggregation.Kind.STD
MEDIAN = libcudf_aggregation.aggregation.Kind.MEDIAN
QUANTILE = libcudf_aggregation.aggregation.Kind.QUANTILE
ARGMAX = libcudf_aggregation.aggregation.Kind.ARGMAX
ARGMIN = libcudf_aggregation.aggregation.Kind.ARGMIN
NUNIQUE = libcudf_aggregation.aggregation.Kind.NUNIQUE
NTH = libcudf_aggregation.aggregation.Kind.NTH_ELEMENT
RANK = libcudf_aggregation.aggregation.Kind.RANK
COLLECT = libcudf_aggregation.aggregation.Kind.COLLECT
UNIQUE = libcudf_aggregation.aggregation.Kind.COLLECT_SET
PTX = libcudf_aggregation.aggregation.Kind.PTX
CUDA = libcudf_aggregation.aggregation.Kind.CUDA
CORRELATION = libcudf_aggregation.aggregation.Kind.CORRELATION
COVARIANCE = libcudf_aggregation.aggregation.Kind.COVARIANCE
class CorrelationType(IntEnum):
PEARSON = (
<underlying_type_t_correlation_type>
libcudf_aggregation.correlation_type.PEARSON
)
KENDALL = (
<underlying_type_t_correlation_type>
libcudf_aggregation.correlation_type.KENDALL
)
SPEARMAN = (
<underlying_type_t_correlation_type>
libcudf_aggregation.correlation_type.SPEARMAN
)
class RankMethod(IntEnum):
FIRST = libcudf_aggregation.rank_method.FIRST
AVERAGE = libcudf_aggregation.rank_method.AVERAGE
MIN = libcudf_aggregation.rank_method.MIN
MAX = libcudf_aggregation.rank_method.MAX
DENSE = libcudf_aggregation.rank_method.DENSE
cdef class RollingAggregation:
"""A Cython wrapper for rolling window aggregations.
**This class should never be instantiated using a standard constructor,
only using one of its many factories.** These factories handle mapping
different cudf operations to their libcudf analogs, e.g.
`cudf.DataFrame.idxmin` -> `libcudf.argmin`. Additionally, they perform
any additional configuration needed to translate Python arguments into
their corresponding C++ types (for instance, C++ enumerations used for
flag arguments). The factory approach is necessary to support operations
like `df.agg(lambda x: x.sum())`; such functions are called with this
class as an argument to generation the desired aggregation.
"""
@property
def kind(self):
return AggregationKind(self.c_obj.get()[0].kind).name
@classmethod
def sum(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_sum_aggregation[rolling_aggregation]())
return agg
@classmethod
def min(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_min_aggregation[rolling_aggregation]())
return agg
@classmethod
def max(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_max_aggregation[rolling_aggregation]())
return agg
@classmethod
def idxmin(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_argmin_aggregation[
rolling_aggregation]())
return agg
@classmethod
def idxmax(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_argmax_aggregation[
rolling_aggregation]())
return agg
@classmethod
def mean(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_mean_aggregation[rolling_aggregation]())
return agg
@classmethod
def var(cls, ddof=1):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_variance_aggregation[rolling_aggregation](
ddof
)
)
return agg
@classmethod
def std(cls, ddof=1):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_std_aggregation[rolling_aggregation](ddof)
)
return agg
@classmethod
def count(cls, dropna=True):
cdef libcudf_types.null_policy c_null_handling
if dropna:
c_null_handling = libcudf_types.null_policy.EXCLUDE
else:
c_null_handling = libcudf_types.null_policy.INCLUDE
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_count_aggregation[rolling_aggregation](
c_null_handling
))
return agg
@classmethod
def size(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_count_aggregation[rolling_aggregation](
<libcudf_types.null_policy><underlying_type_t_null_policy>(
NullHandling.INCLUDE)
))
return agg
@classmethod
def collect(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_collect_list_aggregation[
rolling_aggregation]())
return agg
@classmethod
def from_udf(cls, op, *args, **kwargs):
cdef RollingAggregation agg = cls()
cdef libcudf_types.type_id tid
cdef libcudf_types.data_type out_dtype
cdef string cpp_str
# Handling UDF type
nb_type = numpy_support.from_dtype(kwargs['dtype'])
type_signature = (nb_type[:],)
compiled_op = cudautils.compile_udf(op, type_signature)
output_np_dtype = cudf.dtype(compiled_op[1])
cpp_str = compiled_op[0].encode('UTF-8')
if output_np_dtype not in SUPPORTED_NUMPY_TO_LIBCUDF_TYPES:
raise TypeError(
"Result of window function has unsupported dtype {}"
.format(op[1])
)
tid = (
<libcudf_types.type_id> (
<underlying_type_t_type_id> (
SUPPORTED_NUMPY_TO_LIBCUDF_TYPES[output_np_dtype]
)
)
)
out_dtype = libcudf_types.data_type(tid)
agg.c_obj = move(
libcudf_aggregation.make_udf_aggregation[rolling_aggregation](
libcudf_aggregation.udf_type.PTX, cpp_str, out_dtype
))
return agg
# scan aggregations
# TODO: update this after adding per algorithm aggregation derived types
# https://github.com/rapidsai/cudf/issues/7106
cumsum = sum
cummin = min
cummax = max
@classmethod
def cumcount(cls):
cdef RollingAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_count_aggregation[rolling_aggregation](
libcudf_types.null_policy.INCLUDE
))
return agg
cdef class GroupbyAggregation:
"""A Cython wrapper for groupby aggregations.
**This class should never be instantiated using a standard constructor,
only using one of its many factories.** These factories handle mapping
different cudf operations to their libcudf analogs, e.g.
`cudf.DataFrame.idxmin` -> `libcudf.argmin`. Additionally, they perform
any additional configuration needed to translate Python arguments into
their corresponding C++ types (for instance, C++ enumerations used for
flag arguments). The factory approach is necessary to support operations
like `df.agg(lambda x: x.sum())`; such functions are called with this
class as an argument to generation the desired aggregation.
"""
@property
def kind(self):
return AggregationKind(self.c_obj.get()[0].kind).name
@classmethod
def sum(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_sum_aggregation[groupby_aggregation]())
return agg
@classmethod
def min(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_min_aggregation[groupby_aggregation]())
return agg
@classmethod
def max(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_max_aggregation[groupby_aggregation]())
return agg
@classmethod
def idxmin(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_argmin_aggregation[
groupby_aggregation]())
return agg
@classmethod
def idxmax(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_argmax_aggregation[
groupby_aggregation]())
return agg
@classmethod
def mean(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_mean_aggregation[groupby_aggregation]())
return agg
@classmethod
def count(cls, dropna=True):
cdef libcudf_types.null_policy c_null_handling
if dropna:
c_null_handling = libcudf_types.null_policy.EXCLUDE
else:
c_null_handling = libcudf_types.null_policy.INCLUDE
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_count_aggregation[groupby_aggregation](
c_null_handling
))
return agg
@classmethod
def size(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_count_aggregation[groupby_aggregation](
<libcudf_types.null_policy><underlying_type_t_null_policy>(
NullHandling.INCLUDE)
))
return agg
@classmethod
def collect(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_collect_list_aggregation[groupby_aggregation]())
return agg
@classmethod
def nunique(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_nunique_aggregation[groupby_aggregation]())
return agg
@classmethod
def nth(cls, libcudf_types.size_type size):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_nth_element_aggregation[groupby_aggregation](size))
return agg
@classmethod
def product(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_product_aggregation[groupby_aggregation]())
return agg
prod = product
@classmethod
def sum_of_squares(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_sum_of_squares_aggregation[groupby_aggregation]()
)
return agg
@classmethod
def var(cls, ddof=1):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_variance_aggregation[groupby_aggregation](ddof))
return agg
@classmethod
def std(cls, ddof=1):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_std_aggregation[groupby_aggregation](ddof))
return agg
@classmethod
def median(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_median_aggregation[groupby_aggregation]())
return agg
@classmethod
def quantile(cls, q=0.5, interpolation="linear"):
cdef GroupbyAggregation agg = cls()
if not pd.api.types.is_list_like(q):
q = [q]
cdef vector[double] c_q = q
cdef libcudf_types.interpolation c_interp = (
<libcudf_types.interpolation> (
<underlying_type_t_interpolation> (
Interpolation[interpolation.upper()]
)
)
)
agg.c_obj = move(
libcudf_aggregation.make_quantile_aggregation[groupby_aggregation](
c_q, c_interp)
)
return agg
@classmethod
def unique(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_collect_set_aggregation[groupby_aggregation]())
return agg
@classmethod
def first(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_nth_element_aggregation[groupby_aggregation](
0,
<libcudf_types.null_policy><underlying_type_t_null_policy>(
NullHandling.EXCLUDE
)
)
)
return agg
@classmethod
def last(cls):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_nth_element_aggregation[groupby_aggregation](
-1,
<libcudf_types.null_policy><underlying_type_t_null_policy>(
NullHandling.EXCLUDE
)
)
)
return agg
@classmethod
def corr(cls, method, libcudf_types.size_type min_periods):
cdef GroupbyAggregation agg = cls()
cdef libcudf_aggregation.correlation_type c_method = (
<libcudf_aggregation.correlation_type> (
<underlying_type_t_correlation_type> (
CorrelationType[method.upper()]
)
)
)
agg.c_obj = move(
libcudf_aggregation.
make_correlation_aggregation[groupby_aggregation](
c_method, min_periods
))
return agg
@classmethod
def cov(
cls,
libcudf_types.size_type min_periods,
libcudf_types.size_type ddof=1
):
cdef GroupbyAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_covariance_aggregation[groupby_aggregation](
min_periods, ddof
))
return agg
cdef class GroupbyScanAggregation:
"""A Cython wrapper for groupby scan aggregations.
**This class should never be instantiated using a standard constructor,
only using one of its many factories.** These factories handle mapping
different cudf operations to their libcudf analogs, e.g.
`cudf.DataFrame.idxmin` -> `libcudf.argmin`. Additionally, they perform
any additional configuration needed to translate Python arguments into
their corresponding C++ types (for instance, C++ enumerations used for
flag arguments). The factory approach is necessary to support operations
like `df.agg(lambda x: x.sum())`; such functions are called with this
class as an argument to generation the desired aggregation.
"""
@property
def kind(self):
return AggregationKind(self.c_obj.get()[0].kind).name
@classmethod
def sum(cls):
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_sum_aggregation[groupby_scan_aggregation]())
return agg
@classmethod
def min(cls):
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_min_aggregation[groupby_scan_aggregation]())
return agg
@classmethod
def max(cls):
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_max_aggregation[groupby_scan_aggregation]())
return agg
@classmethod
def count(cls, dropna=True):
cdef libcudf_types.null_policy c_null_handling
if dropna:
c_null_handling = libcudf_types.null_policy.EXCLUDE
else:
c_null_handling = libcudf_types.null_policy.INCLUDE
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_count_aggregation[groupby_scan_aggregation](c_null_handling))
return agg
@classmethod
def size(cls):
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_count_aggregation[groupby_scan_aggregation](
<libcudf_types.null_policy><underlying_type_t_null_policy>(
NullHandling.INCLUDE)
))
return agg
@classmethod
def cumcount(cls):
cdef GroupbyScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_count_aggregation[groupby_scan_aggregation](
libcudf_types.null_policy.INCLUDE
))
return agg
# scan aggregations
# TODO: update this after adding per algorithm aggregation derived types
# https://github.com/rapidsai/cudf/issues/7106
cumsum = sum
cummin = min
cummax = max
@classmethod
def rank(cls, method, ascending, na_option, pct):
cdef GroupbyScanAggregation agg = cls()
cdef libcudf_aggregation.rank_method c_method = (
<libcudf_aggregation.rank_method> (
<underlying_type_t_rank_method> (
RankMethod[method.upper()]
)
)
)
agg.c_obj = move(
libcudf_aggregation.
make_rank_aggregation[groupby_scan_aggregation](
c_method,
(libcudf_types.order.ASCENDING if ascending else
libcudf_types.order.DESCENDING),
(libcudf_types.null_policy.EXCLUDE if na_option == "keep" else
libcudf_types.null_policy.INCLUDE),
(libcudf_types.null_order.BEFORE
if (na_option == "top") == ascending else
libcudf_types.null_order.AFTER),
(libcudf_aggregation.rank_percentage.ZERO_NORMALIZED
if pct else
libcudf_aggregation.rank_percentage.NONE)
))
return agg
cdef class ReduceAggregation:
"""A Cython wrapper for reduce aggregations.
**This class should never be instantiated using a standard constructor,
only using one of its many factories.** These factories handle mapping
different cudf operations to their libcudf analogs, e.g.
`cudf.DataFrame.idxmin` -> `libcudf.argmin`. Additionally, they perform
any additional configuration needed to translate Python arguments into
their corresponding C++ types (for instance, C++ enumerations used for
flag arguments). The factory approach is necessary to support operations
like `df.agg(lambda x: x.sum())`; such functions are called with this
class as an argument to generation the desired aggregation.
"""
@property
def kind(self):
return AggregationKind(self.c_obj.get()[0].kind).name
@classmethod
def sum(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_sum_aggregation[reduce_aggregation]())
return agg
@classmethod
def product(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_product_aggregation[
reduce_aggregation]())
return agg
prod = product
@classmethod
def min(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_min_aggregation[reduce_aggregation]())
return agg
@classmethod
def max(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_max_aggregation[reduce_aggregation]())
return agg
@classmethod
def any(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_any_aggregation[reduce_aggregation]())
return agg
@classmethod
def all(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_all_aggregation[reduce_aggregation]())
return agg
@classmethod
def sum_of_squares(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_sum_of_squares_aggregation[
reduce_aggregation]()
)
return agg
@classmethod
def mean(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_mean_aggregation[reduce_aggregation]())
return agg
@classmethod
def var(cls, ddof=1):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_variance_aggregation[
reduce_aggregation](ddof))
return agg
@classmethod
def std(cls, ddof=1):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_std_aggregation[reduce_aggregation](ddof))
return agg
@classmethod
def median(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_median_aggregation[reduce_aggregation]())
return agg
@classmethod
def quantile(cls, q=0.5, interpolation="linear"):
cdef ReduceAggregation agg = cls()
if not pd.api.types.is_list_like(q):
q = [q]
cdef vector[double] c_q = q
cdef libcudf_types.interpolation c_interp = (
<libcudf_types.interpolation> (
<underlying_type_t_interpolation> (
Interpolation[interpolation.upper()]
)
)
)
agg.c_obj = move(
libcudf_aggregation.make_quantile_aggregation[reduce_aggregation](
c_q, c_interp)
)
return agg
@classmethod
def nunique(cls):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_nunique_aggregation[reduce_aggregation]())
return agg
@classmethod
def nth(cls, libcudf_types.size_type size):
cdef ReduceAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_nth_element_aggregation[
reduce_aggregation](size))
return agg
cdef class ScanAggregation:
"""A Cython wrapper for scan aggregations.
**This class should never be instantiated using a standard constructor,
only using one of its many factories.** These factories handle mapping
different cudf operations to their libcudf analogs, e.g.
`cudf.DataFrame.idxmin` -> `libcudf.argmin`. Additionally, they perform
any additional configuration needed to translate Python arguments into
their corresponding C++ types (for instance, C++ enumerations used for
flag arguments). The factory approach is necessary to support operations
like `df.agg(lambda x: x.sum())`; such functions are called with this
class as an argument to generation the desired aggregation.
"""
@property
def kind(self):
return AggregationKind(self.c_obj.get()[0].kind).name
@classmethod
def sum(cls):
cdef ScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_sum_aggregation[scan_aggregation]())
return agg
@classmethod
def product(cls):
cdef ScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.make_product_aggregation[scan_aggregation]())
return agg
prod = product
@classmethod
def min(cls):
cdef ScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_min_aggregation[scan_aggregation]())
return agg
@classmethod
def max(cls):
cdef ScanAggregation agg = cls()
agg.c_obj = move(
libcudf_aggregation.
make_max_aggregation[scan_aggregation]())
return agg
# scan aggregations
# TODO: update this after adding per algorithm aggregation derived types
# https://github.com/rapidsai/cudf/issues/7106
cumsum = sum
cummin = min
cummax = max
cdef RollingAggregation make_rolling_aggregation(op, kwargs=None):
r"""
Parameters
----------
op : str or callable
If callable, must meet one of the following requirements:
* Is of the form lambda x: x.agg(*args, **kwargs), where
`agg` is the name of a supported aggregation. Used to
to specify aggregations that take arguments, e.g.,
`lambda x: x.quantile(0.5)`.
* Is a user defined aggregation function that operates on
group values. In this case, the output dtype must be
specified in the `kwargs` dictionary.
\*\*kwargs : dict, optional
Any keyword arguments to be passed to the op.
Returns
-------
RollingAggregation
"""
if kwargs is None:
kwargs = {}
cdef RollingAggregation agg
if isinstance(op, str):
agg = getattr(RollingAggregation, op)(**kwargs)
elif callable(op):
if op is list:
agg = RollingAggregation.collect()
elif "dtype" in kwargs:
agg = RollingAggregation.from_udf(op, **kwargs)
else:
agg = op(RollingAggregation)
else:
raise TypeError(f"Unknown aggregation {op}")
return agg
cdef GroupbyAggregation make_groupby_aggregation(op, kwargs=None):
r"""
Parameters
----------
op : str or callable
If callable, must meet one of the following requirements:
* Is of the form lambda x: x.agg(*args, **kwargs), where
`agg` is the name of a supported aggregation. Used to
to specify aggregations that take arguments, e.g.,
`lambda x: x.quantile(0.5)`.
* Is a user defined aggregation function that operates on
group values. In this case, the output dtype must be
specified in the `kwargs` dictionary.
\*\*kwargs : dict, optional
Any keyword arguments to be passed to the op.
Returns
-------
GroupbyAggregation
"""
if kwargs is None:
kwargs = {}
cdef GroupbyAggregation agg
if isinstance(op, str):
agg = getattr(GroupbyAggregation, op)(**kwargs)
elif callable(op):
if op is list:
agg = GroupbyAggregation.collect()
elif "dtype" in kwargs:
agg = GroupbyAggregation.from_udf(op, **kwargs)
else:
agg = op(GroupbyAggregation)
else:
raise TypeError(f"Unknown aggregation {op}")
return agg
cdef GroupbyScanAggregation make_groupby_scan_aggregation(op, kwargs=None):
r"""
Parameters
----------
op : str or callable
If callable, must meet one of the following requirements:
* Is of the form lambda x: x.agg(*args, **kwargs), where
`agg` is the name of a supported aggregation. Used to
to specify aggregations that take arguments, e.g.,
`lambda x: x.quantile(0.5)`.
* Is a user defined aggregation function that operates on
grouped, scannable values. In this case, the output dtype must be
specified in the `kwargs` dictionary.
\*\*kwargs : dict, optional
Any keyword arguments to be passed to the op.
Returns
-------
GroupbyScanAggregation
"""
if kwargs is None:
kwargs = {}
cdef GroupbyScanAggregation agg
if isinstance(op, str):
agg = getattr(GroupbyScanAggregation, op)(**kwargs)
elif callable(op):
if op is list:
agg = GroupbyScanAggregation.collect()
elif "dtype" in kwargs:
agg = GroupbyScanAggregation.from_udf(op, **kwargs)
else:
agg = op(GroupbyScanAggregation)
else:
raise TypeError(f"Unknown aggregation {op}")
return agg
cdef ReduceAggregation make_reduce_aggregation(op, kwargs=None):
r"""
Parameters
----------
op : str or callable
If callable, must meet one of the following requirements:
* Is of the form lambda x: x.agg(*args, **kwargs), where
`agg` is the name of a supported aggregation. Used to
to specify aggregations that take arguments, e.g.,
`lambda x: x.quantile(0.5)`.
* Is a user defined aggregation function that operates on
reducible values. In this case, the output dtype must be
specified in the `kwargs` dictionary.
\*\*kwargs : dict, optional
Any keyword arguments to be passed to the op.
Returns
-------
ReduceAggregation
"""
if kwargs is None:
kwargs = {}
cdef ReduceAggregation agg
if isinstance(op, str):
agg = getattr(ReduceAggregation, op)(**kwargs)
elif callable(op):
if op is list:
agg = ReduceAggregation.collect()
elif "dtype" in kwargs:
agg = ReduceAggregation.from_udf(op, **kwargs)
else:
agg = op(ReduceAggregation)
else:
raise TypeError(f"Unknown aggregation {op}")
return agg
cdef ScanAggregation make_scan_aggregation(op, kwargs=None):
r"""
Parameters
----------
op : str or callable
If callable, must meet one of the following requirements:
* Is of the form lambda x: x.agg(*args, **kwargs), where
`agg` is the name of a supported aggregation. Used to
to specify aggregations that take arguments, e.g.,
`lambda x: x.quantile(0.5)`.
* Is a user defined aggregation function that operates on
scannable values. In this case, the output dtype must be
specified in the `kwargs` dictionary.
\*\*kwargs : dict, optional
Any keyword arguments to be passed to the op.
Returns
-------
ScanAggregation
"""
if kwargs is None:
kwargs = {}
cdef ScanAggregation agg
if isinstance(op, str):
agg = getattr(ScanAggregation, op)(**kwargs)
elif callable(op):
if op is list:
agg = ScanAggregation.collect()
elif "dtype" in kwargs:
agg = ScanAggregation.from_udf(op, **kwargs)
else:
agg = op(ScanAggregation)
else:
raise TypeError(f"Unknown aggregation {op}")
return agg
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/column.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from typing import Literal
import cupy as cp
import numpy as np
import rmm
import cudf
import cudf._lib as libcudf
from cudf._lib import pylibcudf
from cudf.api.types import is_categorical_dtype, is_datetime64tz_dtype
from cudf.core.buffer import (
Buffer,
ExposureTrackedBuffer,
SpillableBuffer,
acquire_spill_lock,
as_buffer,
cuda_array_interface_wrapper,
)
from cudf.utils.dtypes import _get_base_dtype
from cpython.buffer cimport PyObject_CheckBuffer
from libc.stdint cimport uintptr_t
from libcpp.memory cimport make_unique, unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
from rmm._lib.device_buffer cimport DeviceBuffer
from cudf._lib.types cimport (
dtype_from_column_view,
dtype_to_data_type,
dtype_to_pylibcudf_type,
)
from cudf._lib.null_mask import bitmask_allocation_size_bytes
from cudf._lib.types import dtype_from_pylibcudf_column
cimport cudf._lib.cpp.types as libcudf_types
cimport cudf._lib.cpp.unary as libcudf_unary
from cudf._lib.cpp.column.column cimport column, column_contents
from cudf._lib.cpp.column.column_factories cimport (
make_column_from_scalar as cpp_make_column_from_scalar,
make_numeric_column,
)
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.null_mask cimport null_count as cpp_null_count
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.scalar cimport DeviceScalar
cdef class Column:
"""
A Column stores columnar data in device memory.
A Column may be composed of:
* A *data* Buffer
* One or more (optional) *children* Columns
* An (optional) *mask* Buffer representing the nullmask
The *dtype* indicates the Column's element type.
"""
def __init__(
self,
object data,
int size,
object dtype,
object mask=None,
int offset=0,
object null_count=None,
object children=()
):
self._size = size
self._distinct_count = {}
self._dtype = dtype
self._offset = offset
self._null_count = null_count
self.set_base_children(children)
self.set_base_data(data)
self.set_base_mask(mask)
@property
def base_size(self):
return int(self.base_data.size / self.dtype.itemsize)
@property
def dtype(self):
return self._dtype
@property
def size(self):
return self._size
@property
def base_data(self):
return self._base_data
@property
def data(self):
if self.base_data is None:
return None
if self._data is None:
start = self.offset * self.dtype.itemsize
end = start + self.size * self.dtype.itemsize
self._data = self.base_data[start:end]
return self._data
@property
def data_ptr(self):
if self.data is None:
return 0
else:
return self.data.get_ptr(mode="write")
def set_base_data(self, value):
if value is not None and not isinstance(value, Buffer):
raise TypeError(
"Expected a Buffer or None for data, "
f"got {type(value).__name__}"
)
self._data = None
self._base_data = value
@property
def nullable(self):
return self.base_mask is not None
def has_nulls(self, include_nan=False):
return int(self.null_count) != 0
@property
def base_mask(self):
return self._base_mask
@property
def mask(self):
if self._mask is None:
if self.base_mask is None or self.offset == 0:
self._mask = self.base_mask
else:
self._mask = libcudf.null_mask.copy_bitmask(self)
return self._mask
@property
def mask_ptr(self):
if self.mask is None:
return 0
else:
return self.mask.get_ptr(mode="write")
def set_base_mask(self, value):
"""
Replaces the base mask buffer of the column inplace. This does not
modify size or offset in any way, so the passed mask is expected to be
compatible with the current offset.
"""
if value is not None and not isinstance(value, Buffer):
raise TypeError(
"Expected a Buffer or None for mask, "
f"got {type(value).__name__}"
)
if value is not None:
# bitmask size must be relative to offset = 0 data.
required_size = bitmask_allocation_size_bytes(self.base_size)
if value.size < required_size:
error_msg = (
"The Buffer for mask is smaller than expected, "
f"got {value.size} bytes, expected {required_size} bytes."
)
if self.offset > 0 or self.size < self.base_size:
error_msg += (
"\n\nNote: The mask is expected to be sized according "
"to the base allocation as opposed to the offsetted or"
" sized allocation."
)
raise ValueError(error_msg)
self._mask = None
self._children = None
self._base_mask = value
self._clear_cache()
def _clear_cache(self):
self._distinct_count = {}
try:
del self.memory_usage
except AttributeError:
# `self.memory_usage` was never called before, So ignore.
pass
self._null_count = None
def set_mask(self, value):
"""
Replaces the mask buffer of the column and returns a new column. This
will zero the column offset, compute a new mask buffer if necessary,
and compute new data Buffers zero-copy that use pointer arithmetic to
properly adjust the pointer.
"""
mask_size = bitmask_allocation_size_bytes(self.size)
required_num_bytes = -(-self.size // 8) # ceiling divide
error_msg = (
"The value for mask is smaller than expected, got {} bytes, "
"expected " + str(required_num_bytes) + " bytes."
)
if value is None:
mask = None
elif hasattr(value, "__cuda_array_interface__"):
if value.__cuda_array_interface__["typestr"] not in ("|i1", "|u1"):
if isinstance(value, Column):
value = value.data_array_view(mode="write")
value = cp.asarray(value).view('|u1')
mask = as_buffer(value)
if mask.size < required_num_bytes:
raise ValueError(error_msg.format(str(value.size)))
if mask.size < mask_size:
dbuf = rmm.DeviceBuffer(size=mask_size)
dbuf.copy_from_device(value)
mask = as_buffer(dbuf)
elif hasattr(value, "__array_interface__"):
value = np.asarray(value).view("u1")[:mask_size]
if value.size < required_num_bytes:
raise ValueError(error_msg.format(str(value.size)))
dbuf = rmm.DeviceBuffer(size=mask_size)
dbuf.copy_from_host(value)
mask = as_buffer(dbuf)
elif PyObject_CheckBuffer(value):
value = np.asarray(value).view("u1")[:mask_size]
if value.size < required_num_bytes:
raise ValueError(error_msg.format(str(value.size)))
dbuf = rmm.DeviceBuffer(size=mask_size)
dbuf.copy_from_host(value)
mask = as_buffer(dbuf)
else:
raise TypeError(
"Expected a Buffer object or None for mask, "
f"got {type(value).__name__}"
)
return cudf.core.column.build_column(
data=self.data,
dtype=self.dtype,
mask=mask,
size=self.size,
offset=0,
children=self.children
)
@property
def null_count(self):
if self._null_count is None:
self._null_count = self.compute_null_count()
return self._null_count
@property
def offset(self):
return self._offset
@property
def base_children(self):
return self._base_children
@property
def children(self):
if (self.offset == 0) and (self.size == self.base_size):
self._children = self.base_children
if self._children is None:
if self.base_children == ():
self._children = ()
else:
children = Column.from_unique_ptr(
move(make_unique[column](self.view()))
).base_children
dtypes = [
base_child.dtype for base_child in self.base_children
]
self._children = [
child._with_type_metadata(dtype) for child, dtype in zip(
children, dtypes
)
]
return self._children
def set_base_children(self, value):
if not isinstance(value, tuple):
raise TypeError("Expected a tuple of Columns for children, got " +
type(value).__name__)
for child in value:
if not isinstance(child, Column):
raise TypeError(
"Expected each of children to be a Column, got " +
type(child).__name__
)
self._children = None
self._base_children = value
def _mimic_inplace(self, other_col, inplace=False):
"""
Given another column, update the attributes of this column to mimic an
inplace operation. This does not modify the memory of Buffers, but
instead replaces the Buffers and other attributes underneath the column
object with the Buffers and attributes from the other column.
"""
if inplace:
self._offset = other_col.offset
self._size = other_col.size
self._dtype = other_col._dtype
self.set_base_data(other_col.base_data)
self.set_base_children(other_col.base_children)
self.set_base_mask(other_col.base_mask)
else:
return other_col
cdef libcudf_types.size_type compute_null_count(self) except? 0:
with acquire_spill_lock():
if not self.nullable:
return 0
return cpp_null_count(
<libcudf_types.bitmask_type*><uintptr_t>(
self.base_mask.get_ptr(mode="read")
),
self.offset,
self.offset + self.size
)
cdef mutable_column_view mutable_view(self) except *:
if is_categorical_dtype(self.dtype):
col = self.base_children[0]
data_dtype = col.dtype
elif is_datetime64tz_dtype(self.dtype):
col = self
data_dtype = _get_base_dtype(col.dtype)
else:
col = self
data_dtype = col.dtype
cdef libcudf_types.data_type dtype = dtype_to_data_type(data_dtype)
cdef libcudf_types.size_type offset = self.offset
cdef vector[mutable_column_view] children
cdef void* data
if col.base_data is None:
data = NULL
else:
data = <void*><uintptr_t>(
col.base_data.get_ptr(mode="write")
)
cdef Column child_column
if col.base_children:
for child_column in col.base_children:
children.push_back(child_column.mutable_view())
cdef libcudf_types.bitmask_type* mask
if self.nullable:
mask = <libcudf_types.bitmask_type*><uintptr_t>(
self.base_mask.get_ptr(mode="write")
)
else:
mask = NULL
null_count = self._null_count
if null_count is None:
null_count = 0
cdef libcudf_types.size_type c_null_count = null_count
self._mask = None
self._null_count = None
self._children = None
self._data = None
return mutable_column_view(
dtype,
self.size,
data,
mask,
c_null_count,
offset,
children)
cdef column_view view(self) except *:
null_count = self.null_count
if null_count is None:
null_count = 0
cdef libcudf_types.size_type c_null_count = null_count
return self._view(c_null_count)
cdef column_view _view(self, libcudf_types.size_type null_count) except *:
if is_categorical_dtype(self.dtype):
col = self.base_children[0]
data_dtype = col.dtype
elif is_datetime64tz_dtype(self.dtype):
col = self
data_dtype = _get_base_dtype(col.dtype)
else:
col = self
data_dtype = col.dtype
cdef libcudf_types.data_type dtype = dtype_to_data_type(data_dtype)
cdef libcudf_types.size_type offset = self.offset
cdef vector[column_view] children
cdef void* data
if col.base_data is None:
data = NULL
else:
data = <void*><uintptr_t>(col.base_data.get_ptr(mode="read"))
cdef Column child_column
if col.base_children:
for child_column in col.base_children:
children.push_back(child_column.view())
cdef libcudf_types.bitmask_type* mask
if self.nullable:
mask = <libcudf_types.bitmask_type*><uintptr_t>(
self.base_mask.get_ptr(mode="read")
)
else:
mask = NULL
cdef libcudf_types.size_type c_null_count = null_count
return column_view(
dtype,
self.size,
data,
mask,
c_null_count,
offset,
children)
# TODO: Consider whether this function should support some sort of `copy`
# parameter. Not urgent until this functionality is moved up to the Frame
# layer and made public. This function will also need to mark the
# underlying buffers as exposed before this function can itself be exposed
# publicly. User requests to convert to pylibcudf must assume that the
# data may be modified afterwards.
cpdef to_pylibcudf(self, mode: Literal["read", "write"]):
"""Convert this Column to a pylibcudf.Column.
This function will generate a pylibcudf Column pointing to the same
data, mask, and children as this one.
Parameters
----------
mode : str
Supported values are {"read", "write"} If "write", the data pointed
to may be modified by the caller. If "read", the data pointed to
must not be modified by the caller. Failure to fulfill this
contract will cause incorrect behavior.
Returns
-------
pylibcudf.Column
A new pylibcudf.Column referencing the same data.
"""
# TODO: Categoricals will need to be treated differently eventually.
# There is no 1-1 correspondence between cudf and libcudf for
# categoricals because cudf supports ordered and unordered categoricals
# while libcudf supports only unordered categoricals (see
# https://github.com/rapidsai/cudf/pull/8567).
if is_categorical_dtype(self.dtype):
col = self.base_children[0]
else:
col = self
dtype = dtype_to_pylibcudf_type(col.dtype)
data = None
if col.base_data is not None:
cai = cuda_array_interface_wrapper(
ptr=col.base_data.get_ptr(mode=mode),
size=col.base_data.size,
owner=col.base_data,
)
data = pylibcudf.gpumemoryview(cai)
mask = None
if self.nullable:
# TODO: Are we intentionally use self's mask instead of col's?
# Where is the mask stored for categoricals?
cai = cuda_array_interface_wrapper(
ptr=self.base_mask.get_ptr(mode=mode),
size=self.base_mask.size,
owner=self.base_mask,
)
mask = pylibcudf.gpumemoryview(cai)
cdef Column child_column
children = []
if col.base_children:
for child_column in col.base_children:
children.append(child_column.to_pylibcudf(mode=mode))
return pylibcudf.Column(
dtype,
self.size,
data,
mask,
self.null_count,
self.offset,
children,
)
@staticmethod
cdef Column from_unique_ptr(
unique_ptr[column] c_col, bint data_ptr_exposed=False
):
"""Create a Column from a column
Typically, this is called on the result of a libcudf operation.
If the data of the libcudf result has been exposed, set
`data_ptr_exposed=True` to expose the memory of the returned Column
as well.
"""
cdef column_view view = c_col.get()[0].view()
cdef libcudf_types.type_id tid = view.type().id()
cdef libcudf_types.data_type c_dtype
cdef size_type length = view.size()
cdef libcudf_types.mask_state mask_state
if tid == libcudf_types.type_id.TIMESTAMP_DAYS:
c_dtype = libcudf_types.data_type(
libcudf_types.type_id.TIMESTAMP_SECONDS
)
with nogil:
c_col = move(libcudf_unary.cast(view, c_dtype))
elif tid == libcudf_types.type_id.EMPTY:
c_dtype = libcudf_types.data_type(libcudf_types.type_id.INT8)
mask_state = libcudf_types.mask_state.ALL_NULL
with nogil:
c_col = move(make_numeric_column(c_dtype, length, mask_state))
size = c_col.get()[0].size()
dtype = dtype_from_column_view(c_col.get()[0].view())
null_count = c_col.get()[0].null_count()
# After call to release(), c_col is unusable
cdef column_contents contents = move(c_col.get()[0].release())
data = as_buffer(
DeviceBuffer.c_from_unique_ptr(move(contents.data)),
exposed=data_ptr_exposed
)
if null_count > 0:
mask = as_buffer(
DeviceBuffer.c_from_unique_ptr(move(contents.null_mask)),
exposed=data_ptr_exposed
)
else:
mask = None
cdef vector[unique_ptr[column]] c_children = move(contents.children)
children = []
if c_children.size() != 0:
# Because of a bug in Cython, we cannot set the optional
# `data_ptr_exposed` argument within a comprehension.
for i in range(c_children.size()):
child = Column.from_unique_ptr(
move(c_children[i]),
data_ptr_exposed=data_ptr_exposed
)
children.append(child)
return cudf.core.column.build_column(
data,
dtype=dtype,
mask=mask,
size=size,
null_count=null_count,
children=tuple(children)
)
# TODO: Actually support exposed data pointers.
@staticmethod
def from_pylibcudf(
col, bint data_ptr_exposed=False
):
"""Create a Column from a pylibcudf.Column.
This function will generate a Column pointing to the provided pylibcudf
Column. It will directly access the data and mask buffers of the
pylibcudf Column, so the newly created object is not tied to the
lifetime of the original pylibcudf.Column.
Parameters
----------
col : pylibcudf.Column
The object to copy.
data_ptr_exposed : bool
This parameter is not yet supported
Returns
-------
pylibcudf.Column
A new pylibcudf.Column referencing the same data.
"""
dtype = dtype_from_pylibcudf_column(col)
return cudf.core.column.build_column(
data=as_buffer(col.data().obj) if col.data() is not None else None,
dtype=dtype,
size=col.size(),
mask=as_buffer(
col.null_mask().obj
) if col.null_mask() is not None else None,
offset=col.offset(),
null_count=col.null_count(),
children=tuple([
Column.from_pylibcudf(child)
for child in col.children()
])
)
@staticmethod
cdef Column from_column_view(column_view cv, object owner):
"""
Given a ``cudf::column_view``, constructs a ``cudf.Column`` from it,
along with referencing an ``owner`` Python object that owns the memory
lifetime. If ``owner`` is a ``cudf.Column``, we reach inside of it and
make the owner of each newly created ``Buffer`` the respective
``Buffer`` from the ``owner`` ``cudf.Column``.
If ``owner`` is ``None``, we allocate new memory for the resulting
``cudf.Column``.
"""
column_owner = isinstance(owner, Column)
mask_owner = owner
if column_owner and is_categorical_dtype(owner.dtype):
owner = owner.base_children[0]
size = cv.size()
offset = cv.offset()
dtype = dtype_from_column_view(cv)
dtype_itemsize = getattr(dtype, "itemsize", 1)
data_ptr = <uintptr_t>(cv.head[void]())
data = None
base_size = size + offset
data_owner = owner
if column_owner:
data_owner = owner.base_data
mask_owner = mask_owner.base_mask
base_size = owner.base_size
base_nbytes = base_size * dtype_itemsize
if data_ptr:
if data_owner is None:
data = as_buffer(
rmm.DeviceBuffer(ptr=data_ptr,
size=(size+offset) * dtype_itemsize)
)
elif (
column_owner and
isinstance(data_owner, ExposureTrackedBuffer)
):
data = as_buffer(
data=data_ptr,
size=base_nbytes,
owner=data_owner,
exposed=False,
)
elif (
# This is an optimization of the most common case where
# from_column_view creates a "view" that is identical to
# the owner.
column_owner and
isinstance(data_owner, SpillableBuffer) and
# We check that `data_owner` is spill locked (not spillable)
# and that it points to the same memory as `data_ptr`.
not data_owner.spillable and
data_owner.memory_info() == (data_ptr, base_nbytes, "gpu")
):
data = data_owner
else:
# At this point we don't know the relationship between data_ptr
# and data_owner thus we mark both of them exposed.
# TODO: try to discover their relationship and create a
# SpillableBufferSlice instead.
data = as_buffer(
data=data_ptr,
size=base_nbytes,
owner=data_owner,
exposed=True,
)
if isinstance(data_owner, ExposureTrackedBuffer):
# accessing the pointer marks it exposed permanently.
data_owner.mark_exposed()
elif isinstance(data_owner, SpillableBuffer):
if data_owner.is_spilled:
raise ValueError(
f"{data_owner} is spilled, which invalidates "
f"the exposed data_ptr ({hex(data_ptr)})"
)
# accessing the pointer marks it exposed permanently.
data_owner.mark_exposed()
else:
data = as_buffer(
rmm.DeviceBuffer(ptr=data_ptr, size=0)
)
mask = None
mask_ptr = <uintptr_t>(cv.null_mask())
if mask_ptr:
if mask_owner is None:
if column_owner:
# if we reached here, it means `owner` is a `Column`
# that does not have a null mask, but `cv` thinks it
# should have a null mask. This can happen in the
# following sequence of events:
#
# 1) `cv` is constructed as a view into a
# `cudf::column` that is nullable (i.e., it has
# a null mask), but contains no nulls.
# 2) `owner`, a `Column`, is constructed from the
# same `cudf::column`. Because `cudf::column`
# is memory owning, `owner` takes ownership of
# the memory owned by the
# `cudf::column`. Because the column has a null
# count of 0, it may choose to discard the null
# mask.
# 3) Now, `cv` points to a discarded null mask.
#
# TL;DR: we should not include a null mask in the
# result:
mask = None
else:
mask = as_buffer(
rmm.DeviceBuffer(
ptr=mask_ptr,
size=bitmask_allocation_size_bytes(base_size)
)
)
else:
mask = as_buffer(
data=mask_ptr,
size=bitmask_allocation_size_bytes(base_size),
owner=mask_owner,
exposed=True
)
if cv.has_nulls():
null_count = cv.null_count()
else:
null_count = 0
children = []
for child_index in range(cv.num_children()):
child_owner = owner
if column_owner:
child_owner = owner.base_children[child_index]
children.append(
Column.from_column_view(
cv.child(child_index),
child_owner
)
)
children = tuple(children)
result = cudf.core.column.build_column(
data=data,
dtype=dtype,
mask=mask,
size=size,
offset=offset,
null_count=null_count,
children=tuple(children)
)
return result
@staticmethod
def from_scalar(py_val, size_type size):
cdef DeviceScalar val = py_val.device_value
cdef const scalar* c_val = val.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_make_column_from_scalar(c_val[0], size))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/datetime.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
cimport cudf._lib.cpp.datetime as libcudf_datetime
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.filling cimport calendrical_month_sequence
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def add_months(Column col, Column months):
# months must be int16 dtype
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
cdef column_view months_view = months.view()
with nogil:
c_result = move(
libcudf_datetime.add_calendrical_months(
col_view,
months_view
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def extract_datetime_component(Column col, object field):
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
with nogil:
if field == "year":
c_result = move(libcudf_datetime.extract_year(col_view))
elif field == "month":
c_result = move(libcudf_datetime.extract_month(col_view))
elif field == "day":
c_result = move(libcudf_datetime.extract_day(col_view))
elif field == "weekday":
c_result = move(libcudf_datetime.extract_weekday(col_view))
elif field == "hour":
c_result = move(libcudf_datetime.extract_hour(col_view))
elif field == "minute":
c_result = move(libcudf_datetime.extract_minute(col_view))
elif field == "second":
c_result = move(libcudf_datetime.extract_second(col_view))
elif field == "millisecond":
c_result = move(
libcudf_datetime.extract_millisecond_fraction(col_view)
)
elif field == "microsecond":
c_result = move(
libcudf_datetime.extract_microsecond_fraction(col_view)
)
elif field == "nanosecond":
c_result = move(
libcudf_datetime.extract_nanosecond_fraction(col_view)
)
elif field == "day_of_year":
c_result = move(libcudf_datetime.day_of_year(col_view))
else:
raise ValueError(f"Invalid datetime field: '{field}'")
result = Column.from_unique_ptr(move(c_result))
if field == "weekday":
# Pandas counts Monday-Sunday as 0-6
# while libcudf counts Monday-Sunday as 1-7
result = result - result.dtype.type(1)
return result
cdef libcudf_datetime.rounding_frequency _get_rounding_frequency(object freq):
cdef libcudf_datetime.rounding_frequency freq_val
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.resolution_string.html
if freq == "D":
freq_val = libcudf_datetime.rounding_frequency.DAY
elif freq == "H":
freq_val = libcudf_datetime.rounding_frequency.HOUR
elif freq in ("T", "min"):
freq_val = libcudf_datetime.rounding_frequency.MINUTE
elif freq == "S":
freq_val = libcudf_datetime.rounding_frequency.SECOND
elif freq in ("L", "ms"):
freq_val = libcudf_datetime.rounding_frequency.MILLISECOND
elif freq in ("U", "us"):
freq_val = libcudf_datetime.rounding_frequency.MICROSECOND
elif freq == "N":
freq_val = libcudf_datetime.rounding_frequency.NANOSECOND
else:
raise ValueError(f"Invalid resolution: '{freq}'")
return freq_val
@acquire_spill_lock()
def ceil_datetime(Column col, object freq):
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
cdef libcudf_datetime.rounding_frequency freq_val = \
_get_rounding_frequency(freq)
with nogil:
c_result = move(libcudf_datetime.ceil_datetimes(col_view, freq_val))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def floor_datetime(Column col, object freq):
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
cdef libcudf_datetime.rounding_frequency freq_val = \
_get_rounding_frequency(freq)
with nogil:
c_result = move(libcudf_datetime.floor_datetimes(col_view, freq_val))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def round_datetime(Column col, object freq):
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
cdef libcudf_datetime.rounding_frequency freq_val = \
_get_rounding_frequency(freq)
with nogil:
c_result = move(libcudf_datetime.round_datetimes(col_view, freq_val))
result = Column.from_unique_ptr(move(c_result))
return result
@acquire_spill_lock()
def is_leap_year(Column col):
"""Returns a boolean indicator whether the year of the date is a leap year
"""
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
with nogil:
c_result = move(libcudf_datetime.is_leap_year(col_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def date_range(DeviceScalar start, size_type n, offset):
cdef unique_ptr[column] c_result
cdef size_type months = (
offset.kwds.get("years", 0) * 12
+ offset.kwds.get("months", 0)
)
cdef const scalar* c_start = start.c_value.get()
with nogil:
c_result = move(calendrical_month_sequence(
n,
c_start[0],
months
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def extract_quarter(Column col):
"""
Returns a column which contains the corresponding quarter of the year
for every timestamp inside the input column.
"""
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
with nogil:
c_result = move(libcudf_datetime.extract_quarter(col_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def days_in_month(Column col):
"""Extracts the number of days in the month of the date
"""
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
with nogil:
c_result = move(libcudf_datetime.days_in_month(col_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def last_day_of_month(Column col):
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
with nogil:
c_result = move(libcudf_datetime.last_day_of_month(col_view))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/stream_compaction.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.stream_compaction cimport (
apply_boolean_mask as cpp_apply_boolean_mask,
distinct_count as cpp_distinct_count,
drop_nulls as cpp_drop_nulls,
duplicate_keep_option,
stable_distinct as cpp_stable_distinct,
)
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport (
nan_policy,
null_equality,
null_policy,
size_type,
)
from cudf._lib.utils cimport columns_from_unique_ptr, table_view_from_columns
@acquire_spill_lock()
def drop_nulls(list columns, how="any", keys=None, thresh=None):
"""
Drops null rows from cols depending on key columns.
Parameters
----------
columns : list of columns
how : "any" or "all". If thresh is None, drops rows of cols that have any
nulls or all nulls (respectively) in subset (default: "any")
keys : List of column indices. If set, then these columns are checked for
nulls rather than all of columns (optional)
thresh : Minimum number of non-nulls required to keep a row (optional)
Returns
-------
columns with null rows dropped
"""
cdef vector[size_type] cpp_keys = (
keys if keys is not None else range(len(columns))
)
cdef size_type c_keep_threshold = cpp_keys.size()
if thresh is not None:
c_keep_threshold = thresh
elif how == "all":
c_keep_threshold = 1
cdef unique_ptr[table] c_result
cdef table_view source_table_view = table_view_from_columns(columns)
if how not in {"any", "all"}:
raise ValueError("how must be 'any' or 'all'")
with nogil:
c_result = move(
cpp_drop_nulls(
source_table_view,
cpp_keys,
c_keep_threshold
)
)
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def apply_boolean_mask(list columns, Column boolean_mask):
"""
Drops the rows which correspond to False in boolean_mask.
Parameters
----------
columns : list of columns whose rows are dropped as per boolean_mask
boolean_mask : a boolean column of same size as source_table
Returns
-------
columns obtained from applying mask
"""
cdef unique_ptr[table] c_result
cdef table_view source_table_view = table_view_from_columns(columns)
cdef column_view boolean_mask_view = boolean_mask.view()
with nogil:
c_result = move(
cpp_apply_boolean_mask(
source_table_view,
boolean_mask_view
)
)
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def drop_duplicates(list columns,
object keys=None,
object keep='first',
bool nulls_are_equal=True):
"""
Drops rows in source_table as per duplicate rows in keys.
Parameters
----------
columns : List of columns
keys : List of column indices. If set, then these columns are checked for
duplicates rather than all of columns (optional)
keep : keep 'first' or 'last' or none of the duplicate rows
nulls_are_equal : if True, nulls are treated equal else not.
Returns
-------
columns with duplicate dropped
"""
cdef vector[size_type] cpp_keys = (
keys if keys is not None else range(len(columns))
)
cdef duplicate_keep_option cpp_keep_option
if keep == 'first':
cpp_keep_option = duplicate_keep_option.KEEP_FIRST
elif keep == 'last':
cpp_keep_option = duplicate_keep_option.KEEP_LAST
elif keep is False:
cpp_keep_option = duplicate_keep_option.KEEP_NONE
else:
raise ValueError('keep must be either "first", "last" or False')
# shifting the index number by number of index columns
cdef null_equality cpp_nulls_equal = (
null_equality.EQUAL
if nulls_are_equal
else null_equality.UNEQUAL
)
cdef table_view source_table_view = table_view_from_columns(columns)
cdef unique_ptr[table] c_result
with nogil:
c_result = move(
cpp_stable_distinct(
source_table_view,
cpp_keys,
cpp_keep_option,
cpp_nulls_equal
)
)
return columns_from_unique_ptr(move(c_result))
@acquire_spill_lock()
def distinct_count(Column source_column, ignore_nulls=True, nan_as_null=False):
"""
Finds number of unique rows in `source_column`
Parameters
----------
source_column : source table checked for unique rows
ignore_nulls : If True nulls are ignored,
else counted as one more distinct value
nan_as_null : If True, NAN is considered NULL,
else counted as one more distinct value
Returns
-------
Count of number of unique rows in `source_column`
"""
cdef null_policy cpp_null_handling = (
null_policy.EXCLUDE
if ignore_nulls
else null_policy.INCLUDE
)
cdef nan_policy cpp_nan_handling = (
nan_policy.NAN_IS_NULL
if nan_as_null
else nan_policy.NAN_IS_VALID
)
cdef column_view source_column_view = source_column.view()
with nogil:
count = cpp_distinct_count(
source_column_view,
cpp_null_handling,
cpp_nan_handling
)
return count
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/round.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.round cimport (
round as cpp_round,
rounding_method as cpp_rounding_method,
)
@acquire_spill_lock()
def round(Column input_col, int decimal_places=0, how="half_even"):
"""
Round column values to the given number of decimal places
Parameters
----------
input_col : Column whose values will be rounded
decimal_places : The number or decimal places to round to
Returns
-------
A Column with values rounded to the given number of decimal places
"""
if how not in {"half_even", "half_up"}:
raise ValueError("'how' must be either 'half_even' or 'half_up'")
cdef column_view input_col_view = input_col.view()
cdef unique_ptr[column] c_result
cdef cpp_rounding_method c_how = (
cpp_rounding_method.HALF_EVEN if how == "half_even"
else cpp_rounding_method.HALF_UP
)
with nogil:
c_result = move(
cpp_round(
input_col_view,
decimal_places,
c_how
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/utils.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf._lib.cpp.types cimport bitmask_type
cdef void * int_to_void_ptr(Py_ssize_t ptr) nogil
cdef bitmask_type * int_to_bitmask_ptr(Py_ssize_t ptr) nogil
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/types.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libc.stdint cimport int32_t
from libcpp cimport bool as cbool
from cudf._lib.cpp.types cimport data_type, type_id
cdef class DataType:
cdef data_type c_obj
cpdef type_id id(self)
cpdef int32_t scale(self)
@staticmethod
cdef DataType from_libcudf(data_type dt)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/interop.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf._lib.cpp.interop cimport column_metadata
cdef class ColumnMetadata:
def __init__(self, name):
self.name = name
self.children_meta = []
cdef column_metadata to_libcudf(self):
"""Convert to C++ column_metadata.
Since this class is mutable and cheap, it is easier to create the C++
object on the fly rather than have it directly backing the storage for
the Cython class.
"""
cdef column_metadata c_metadata
cdef ColumnMetadata child_meta
c_metadata.name = self.name.encode()
for child_meta in self.children_meta:
c_metadata.children_meta.push_back(child_meta.to_libcudf())
return c_metadata
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources column.pyx copying.pyx gpumemoryview.pyx interop.pyx scalar.pyx table.pyx
types.pyx utils.pyx
)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX pylibcudf_ ASSOCIATED_TARGETS cudf
)
find_package(Python 3.9 REQUIRED COMPONENTS Interpreter)
execute_process(
COMMAND "${Python_EXECUTABLE}" -c "import pyarrow; print(pyarrow.get_include())"
OUTPUT_VARIABLE PYARROW_INCLUDE_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${PYARROW_INCLUDE_DIR}")
endforeach()
# TODO: Clean up this include when switching to scikit-build-core. See cudf/_lib/CMakeLists.txt for
# more info
find_package(NumPy REQUIRED)
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${NumPy_INCLUDE_DIRS}")
# Switch to the line below when we switch back to FindPython.cmake in CMake 3.24.
# target_include_directories(${target} PRIVATE "${Python_NumPy_INCLUDE_DIRS}")
endforeach()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/types.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libc.stdint cimport int32_t
from cudf._lib.cpp.types cimport data_type, type_id
from cudf._lib.cpp.types import type_id as TypeId # no-cython-lint
cdef class DataType:
"""Indicator for the logical data type of an element in a column.
This is the Cython representation of libcudf's data_type.
Parameters
----------
id : TypeId
The type's identifier
scale : int
The scale associated with the data. Only used for decimal data types.
"""
def __cinit__(self, type_id id, int32_t scale=0):
self.c_obj = data_type(id, scale)
# TODO: Consider making both id and scale cached properties.
cpdef type_id id(self):
"""Get the id associated with this data type."""
return self.c_obj.id()
cpdef int32_t scale(self):
"""Get the scale associated with this data type."""
return self.c_obj.scale()
@staticmethod
cdef DataType from_libcudf(data_type dt):
"""Create a DataType from a libcudf data_type.
This method is for pylibcudf's functions to use to ingest outputs of
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
# Spoof an empty data type then swap in the real one.
cdef DataType ret = DataType.__new__(DataType, type_id.EMPTY)
ret.c_obj = dt
return ret
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/scalar.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from pyarrow cimport lib as pa
from rmm._lib.memory_resource cimport DeviceMemoryResource
from cudf._lib.cpp.scalar.scalar cimport scalar
from .interop cimport ColumnMetadata
from .types cimport DataType
cdef class Scalar:
cdef unique_ptr[scalar] c_obj
cdef DataType _data_type
# Holds a reference to the DeviceMemoryResource used for allocation.
# Ensures the MR does not get destroyed before this DeviceBuffer. `mr` is
# needed for deallocation
cdef DeviceMemoryResource mr
cdef const scalar* get(self) except *
cpdef DataType type(self)
cpdef bool is_valid(self)
@staticmethod
cdef Scalar from_libcudf(unique_ptr[scalar] libcudf_scalar, dtype=*)
cpdef pa.Scalar to_arrow(self, ColumnMetadata metadata)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/copying.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp cimport bool as cbool
from cudf._lib.cpp.copying cimport out_of_bounds_policy
from .column cimport Column
from .table cimport Table
cpdef Table gather(
Table source_table,
Column gather_map,
out_of_bounds_policy bounds_policy
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/interop.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf._lib.cpp.interop cimport column_metadata
cdef class ColumnMetadata:
cdef public object name
cdef public object children_meta
cdef column_metadata to_libcudf(self)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/utils.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libc.stdint cimport uintptr_t
from cudf._lib.cpp.types cimport bitmask_type
cdef void * int_to_void_ptr(Py_ssize_t ptr) nogil:
return <void*><uintptr_t>(ptr)
cdef bitmask_type * int_to_bitmask_ptr(Py_ssize_t ptr) nogil:
return <bitmask_type*><uintptr_t>(ptr)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/copying.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
# TODO: We want to make cpp a more full-featured package so that we can access
# directly from that. It will make namespacing much cleaner in pylibcudf. What
# we really want here would be
# cimport libcudf... libcudf.copying.algo(...)
from cudf._lib.cpp cimport copying as cpp_copying
from cudf._lib.cpp.copying cimport out_of_bounds_policy
from cudf._lib.cpp.copying import \
out_of_bounds_policy as OutOfBoundsPolicy # no-cython-lint
from cudf._lib.cpp.table.table cimport table
from .column cimport Column
from .table cimport Table
# TODO: Is it OK to reference the corresponding libcudf algorithm in the
# documentation? Otherwise there's a lot of room for duplication.
cpdef Table gather(
Table source_table,
Column gather_map,
out_of_bounds_policy bounds_policy
):
"""Select rows from source_table according to the provided gather_map.
For details on the implementation, see cudf::gather in libcudf.
Parameters
----------
source_table : Table
The table object from which to pull data.
gather_map : Column
The list of row indices to pull out of the source table.
bounds_policy : out_of_bounds_policy
Controls whether out of bounds indices are checked and nullified in the
output or if indices are assumed to be in bounds.
Returns
-------
pylibcudf.Table
The result of the gather
"""
cdef unique_ptr[table] c_result
with nogil:
c_result = move(
cpp_copying.gather(
source_table.view(),
gather_map.view(),
bounds_policy
)
)
return Table.from_libcudf(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/scalar.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cython cimport no_gc_clear
from cython.operator cimport dereference
from libcpp.memory cimport shared_ptr, unique_ptr
from libcpp.utility cimport move
from pyarrow cimport lib as pa
from rmm._lib.memory_resource cimport get_current_device_resource
from cudf._lib.cpp.interop cimport (
column_metadata,
from_arrow as cpp_from_arrow,
to_arrow as cpp_to_arrow,
)
from cudf._lib.cpp.scalar.scalar cimport fixed_point_scalar, scalar
from cudf._lib.cpp.wrappers.decimals cimport (
decimal32,
decimal64,
decimal128,
scale_type,
)
from .interop cimport ColumnMetadata
from .types cimport DataType, type_id
# The DeviceMemoryResource attribute could be released prematurely
# by the gc if the Scalar is in a reference cycle. Removing the tp_clear
# function with the no_gc_clear decoration prevents that. See
# https://github.com/rapidsai/rmm/pull/931 for details.
@no_gc_clear
cdef class Scalar:
"""A scalar value in device memory."""
# Unlike for columns, libcudf does not support scalar views. All APIs that
# accept scalar values accept references to the owning object rather than a
# special view type. As a result, pylibcudf.Scalar has a simpler structure
# than pylibcudf.Column because it can be a true wrapper around a libcudf
# column
def __cinit__(self, *args, **kwargs):
self.mr = get_current_device_resource()
def __init__(self, pa.Scalar value=None):
# TODO: This case is not something we really want to
# support, but it here for now to ease the transition of
# DeviceScalar.
if value is not None:
raise ValueError("Scalar should be constructed with a factory")
@staticmethod
def from_arrow(pa.Scalar value, DataType data_type=None):
# Allow passing a dtype, but only for the purpose of decimals for now
cdef shared_ptr[pa.CScalar] cscalar = (
pa.pyarrow_unwrap_scalar(value)
)
cdef unique_ptr[scalar] c_result
with nogil:
c_result = move(cpp_from_arrow(cscalar.get()[0]))
cdef Scalar s = Scalar.from_libcudf(move(c_result))
if s.type().id() != type_id.DECIMAL128:
if data_type is not None:
raise ValueError(
"dtype may not be passed for non-decimal types"
)
return s
if data_type is None:
raise ValueError(
"Decimal scalars must be constructed with a dtype"
)
cdef type_id tid = data_type.id()
if tid == type_id.DECIMAL32:
s.c_obj.reset(
new fixed_point_scalar[decimal32](
(<fixed_point_scalar[decimal128]*> s.c_obj.get()).value(),
scale_type(-value.type.scale),
s.c_obj.get().is_valid()
)
)
elif tid == type_id.DECIMAL64:
s.c_obj.reset(
new fixed_point_scalar[decimal64](
(<fixed_point_scalar[decimal128]*> s.c_obj.get()).value(),
scale_type(-value.type.scale),
s.c_obj.get().is_valid()
)
)
elif tid != type_id.DECIMAL128:
raise ValueError(
"Decimal scalars may only be cast to decimals"
)
return s
cpdef pa.Scalar to_arrow(self, ColumnMetadata metadata):
cdef shared_ptr[pa.CScalar] c_result
cdef column_metadata c_metadata = metadata.to_libcudf()
with nogil:
c_result = move(cpp_to_arrow(dereference(self.c_obj.get()), c_metadata))
return pa.pyarrow_wrap_scalar(c_result)
cdef const scalar* get(self) except *:
return self.c_obj.get()
cpdef DataType type(self):
"""The type of data in the column."""
return self._data_type
cpdef bool is_valid(self):
"""True if the scalar is valid, false if not"""
return self.get().is_valid()
@staticmethod
cdef Scalar from_libcudf(unique_ptr[scalar] libcudf_scalar, dtype=None):
"""Construct a Scalar object from a libcudf scalar.
This method is for pylibcudf's functions to use to ingest outputs of
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
cdef Scalar s = Scalar.__new__(Scalar)
s.c_obj.swap(libcudf_scalar)
s._data_type = DataType.from_libcudf(s.get().type())
return s
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/table.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from pyarrow cimport lib as pa
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
cdef class Table:
# List[pylibcudf.Column]
cdef list _columns
cdef table_view view(self) nogil
@staticmethod
cdef Table from_libcudf(unique_ptr[table] libcudf_tbl)
cpdef list columns(self)
cpdef pa.Table to_arrow(self, list metadata)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/__init__.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
# TODO: Verify consistent usage of relative/absolute imports in pylibcudf.
from . cimport copying, interop
from .column cimport Column
from .gpumemoryview cimport gpumemoryview
from .scalar cimport Scalar
from .table cimport Table
# TODO: cimport type_id once
# https://github.com/cython/cython/issues/5609 is resolved
from .types cimport DataType
__all__ = [
"Column",
"DataType",
"Scalar",
"Table",
"copying",
"gpumemoryview",
"interop",
]
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/table.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libcpp.memory cimport shared_ptr, unique_ptr
from libcpp.utility cimport move
from libcpp.vector cimport vector
from pyarrow cimport lib as pa
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.interop cimport (
column_metadata,
from_arrow as cpp_from_arrow,
to_arrow as cpp_to_arrow,
)
from cudf._lib.cpp.table.table cimport table
from .column cimport Column
from .interop cimport ColumnMetadata
cdef class Table:
"""A list of columns of the same size.
Parameters
----------
columns : list
The columns in this table.
"""
def __init__(self, list columns):
self._columns = columns
cdef table_view view(self) nogil:
"""Generate a libcudf table_view to pass to libcudf algorithms.
This method is for pylibcudf's functions to use to generate inputs when
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
# TODO: Make c_columns a class attribute that is updated along with
# self._columns whenever new columns are added or columns are removed.
cdef vector[column_view] c_columns
with gil:
for col in self._columns:
c_columns.push_back((<Column> col).view())
return table_view(c_columns)
@staticmethod
cdef Table from_libcudf(unique_ptr[table] libcudf_tbl):
"""Create a Table from a libcudf table.
This method is for pylibcudf's functions to use to ingest outputs of
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
cdef vector[unique_ptr[column]] c_columns = move(
dereference(libcudf_tbl).release()
)
cdef vector[unique_ptr[column]].size_type i
return Table([
Column.from_libcudf(move(c_columns[i]))
for i in range(c_columns.size())
])
cpdef list columns(self):
return self._columns
@staticmethod
def from_arrow(pa.Table pyarrow_table):
cdef shared_ptr[pa.CTable] ctable = (
pa.pyarrow_unwrap_table(pyarrow_table)
)
cdef unique_ptr[table] c_result
with nogil:
c_result = move(cpp_from_arrow(ctable.get()[0]))
return Table.from_libcudf(move(c_result))
cpdef pa.Table to_arrow(self, list metadata):
cdef shared_ptr[pa.CTable] c_result
cdef vector[column_metadata] c_metadata
cdef ColumnMetadata meta
for meta in metadata:
c_metadata.push_back(meta.to_libcudf())
with nogil:
c_result = move(cpp_to_arrow(self.view(), c_metadata))
return pa.pyarrow_wrap_table(c_result)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/__init__.py
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from . import copying, interop
from .column import Column
from .gpumemoryview import gpumemoryview
from .scalar import Scalar
from .table import Table
from .types import DataType, TypeId
__all__ = [
"Column",
"DataType",
"Scalar",
"Table",
"TypeId",
"copying",
"gpumemoryview",
"interop",
]
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/column.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.vector cimport vector
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.types cimport bitmask_type, size_type
from .gpumemoryview cimport gpumemoryview
from .types cimport DataType
cdef class Column:
# TODO: Should we document these attributes? Should we mark them readonly?
cdef:
# Core data
DataType _data_type
size_type _size
gpumemoryview _data
gpumemoryview _mask
size_type _null_count
size_type _offset
# children: List[Column]
list _children
size_type _num_children
cdef column_view view(self) nogil
@staticmethod
cdef Column from_libcudf(unique_ptr[column] libcudf_col)
cpdef DataType type(self)
cpdef Column child(self, size_type index)
cpdef size_type num_children(self)
cpdef size_type size(self)
cpdef size_type null_count(self)
cpdef size_type offset(self)
cpdef gpumemoryview data(self)
cpdef gpumemoryview null_mask(self)
cpdef list children(self)
cpdef list_view(self)
cdef class ListColumnView:
"""Accessor for methods of a Column that are specific to lists."""
cdef Column _column
cpdef child(self)
cpdef offsets(self)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/column.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from rmm._lib.device_buffer cimport DeviceBuffer
from cudf._lib.cpp.column.column cimport column, column_contents
from cudf._lib.cpp.types cimport size_type
from .gpumemoryview cimport gpumemoryview
from .types cimport DataType, type_id
from .utils cimport int_to_bitmask_ptr, int_to_void_ptr
cdef class Column:
"""A container of nullable device data as a column of elements.
This class is an implementation of [Arrow columnar data
specification](https://arrow.apache.org/docs/format/Columnar.html) for data
stored on GPUs. It relies on Python memoryview-like semantics to maintain
shared ownership of the data it is constructed with, so any input data may
also be co-owned by other data structures. The Column is designed to be
operated on using algorithms backed by libcudf.
Parameters
----------
data_type : DataType
The type of data in the column.
size : size_type
The number of rows in the column.
data : gpumemoryview
The data the column will refer to.
mask : gpumemoryview
The null mask for the column.
null_count : int
The number of null rows in the column.
offset : int
The offset into the data buffer where the column's data begins.
children : list
The children of this column if it is a compound column type.
"""
def __init__(
self, DataType data_type not None, size_type size, gpumemoryview data,
gpumemoryview mask, size_type null_count, size_type offset,
list children
):
self._data_type = data_type
self._size = size
self._data = data
self._mask = mask
self._null_count = null_count
self._offset = offset
self._children = children
self._num_children = len(children)
cdef column_view view(self) nogil:
"""Generate a libcudf column_view to pass to libcudf algorithms.
This method is for pylibcudf's functions to use to generate inputs when
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
cdef const void * data = NULL
cdef const bitmask_type * null_mask = NULL
if self._data is not None:
data = int_to_void_ptr(self._data.ptr)
if self._mask is not None:
null_mask = int_to_bitmask_ptr(self._mask.ptr)
# TODO: Check if children can ever change. If not, this could be
# computed once in the constructor and always be reused.
cdef vector[column_view] c_children
with gil:
if self._children is not None:
for child in self._children:
# Need to cast to Column here so that Cython knows that
# `view` returns a typed object, not a Python object. We
# cannot use a typed variable for `child` because cdef
# declarations cannot be inside nested blocks (`if` or
# `with` blocks) so we cannot declare it inside the `with
# gil` block, but we also cannot declare it outside the
# `with gil` block because it is erroneous to declare a
# variable of a cdef class type in a `nogil` context (which
# this whole function is).
c_children.push_back((<Column> child).view())
return column_view(
self._data_type.c_obj, self._size, data, null_mask,
self._null_count, self._offset, c_children
)
@staticmethod
cdef Column from_libcudf(unique_ptr[column] libcudf_col):
"""Create a Column from a libcudf column.
This method is for pylibcudf's functions to use to ingest outputs of
calling libcudf algorithms, and should generally not be needed by users
(even direct pylibcudf Cython users).
"""
cdef DataType dtype = DataType.from_libcudf(libcudf_col.get().type())
cdef size_type size = libcudf_col.get().size()
cdef size_type null_count = libcudf_col.get().null_count()
cdef column_contents contents = move(libcudf_col.get().release())
# Note that when converting to cudf Column objects we'll need to pull
# out the base object.
cdef gpumemoryview data = gpumemoryview(
DeviceBuffer.c_from_unique_ptr(move(contents.data))
)
cdef gpumemoryview mask = None
if null_count > 0:
mask = gpumemoryview(
DeviceBuffer.c_from_unique_ptr(move(contents.null_mask))
)
children = []
if contents.children.size() != 0:
for i in range(contents.children.size()):
children.append(
Column.from_libcudf(move(contents.children[i]))
)
return Column(
dtype,
size,
data,
mask,
null_count,
# Initial offset when capturing a C++ column is always 0.
0,
children,
)
cpdef DataType type(self):
"""The type of data in the column."""
return self._data_type
cpdef Column child(self, size_type index):
"""Get a child column of this column.
Parameters
----------
index : size_type
The index of the child column to get.
Returns
-------
Column
The child column.
"""
return self._children[index]
cpdef size_type num_children(self):
"""The number of children of this column."""
return self._num_children
cpdef list_view(self):
return ListColumnView(self)
cpdef gpumemoryview data(self):
return self._data
cpdef gpumemoryview null_mask(self):
return self._mask
cpdef size_type size(self):
return self._size
cpdef size_type offset(self):
return self._offset
cpdef size_type null_count(self):
return self._null_count
cpdef list children(self):
return self._children
cdef class ListColumnView:
"""Accessor for methods of a Column that are specific to lists."""
def __init__(self, Column col):
if col.type().id() != type_id.LIST:
raise TypeError("Column is not a list type")
self._column = col
cpdef child(self):
return self._column.child(1)
cpdef offsets(self):
return self._column.child(1)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/gpumemoryview.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
cdef class gpumemoryview:
"""Minimal representation of a memory buffer.
This class aspires to be a GPU equivalent of the [Python memoryview
type](https://docs.python.org/3/library/stdtypes.html#memoryview) for any
objects exposing a [CUDA Array
Interface](https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html).
It will be expanded to encompass more memoryview functionality over time.
"""
# TODO: dlpack support
def __init__(self, object obj):
try:
cai = obj.__cuda_array_interface__
except AttributeError:
raise ValueError(
"gpumemoryview must be constructed from an object supporting "
"the CUDA array interface"
)
self.obj = obj
# TODO: Need to respect readonly
self.ptr = cai["data"][0]
def __cuda_array_interface__(self):
return self.obj.__cuda_array_interface__
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/pylibcudf/gpumemoryview.pxd
|
# Copyright (c) 2023, NVIDIA CORPORATION.
cdef class gpumemoryview:
# TODO: Eventually probably want to make this opaque, but for now it's fine
# to treat this object as something like a POD struct
cdef readonly:
Py_ssize_t ptr
object obj
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/char_types.pyx
|
# Copyright (c) 2021-2023, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.char_types cimport (
all_characters_of_type as cpp_all_characters_of_type,
filter_characters_of_type as cpp_filter_characters_of_type,
string_character_types,
)
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def filter_alphanum(Column source_strings, object py_repl, bool keep=True):
"""
Returns a Column of strings keeping only alphanumeric character types.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_repl = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_filter_characters_of_type(
source_view,
string_character_types.ALL_TYPES if keep
else string_character_types.ALPHANUM,
scalar_repl[0],
string_character_types.ALPHANUM if keep
else string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_decimal(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only decimal characters -- those that can be used
to extract base10 numbers.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.DECIMAL,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_alnum(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only alphanumeric characters.
Equivalent to: is_alpha() or is_digit() or is_numeric() or is_decimal()
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.ALPHANUM,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_alpha(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only alphabetic characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.ALPHA,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_digit(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only decimal and digit characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.DIGIT,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_numeric(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only numeric characters. These include digit and
numeric characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.NUMERIC,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_upper(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only upper-case characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.UPPER,
string_character_types.CASE_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_lower(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain only lower-case characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.LOWER,
string_character_types.CASE_TYPES
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_space(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contains all characters which are spaces only.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_all_characters_of_type(
source_view,
string_character_types.SPACE,
string_character_types.ALL_TYPES
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/capitalize.pyx
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.capitalize cimport (
capitalize as cpp_capitalize,
is_title as cpp_is_title,
title as cpp_title,
)
@acquire_spill_lock()
def capitalize(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_capitalize(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def title(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_title(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_title(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_is_title(source_view))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/findall.pyx
|
# Copyright (c) 2019-2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libc.stdint cimport uint32_t
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.findall cimport findall as cpp_findall
from cudf._lib.cpp.strings.regex_flags cimport regex_flags
from cudf._lib.cpp.strings.regex_program cimport regex_program
@acquire_spill_lock()
def findall(Column source_strings, object pattern, uint32_t flags):
"""
Returns data with all non-overlapping matches of `pattern`
in each string of `source_strings` as a lists column.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = <regex_flags>flags
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_findall(
source_view,
dereference(c_prog)
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources
attributes.pyx
capitalize.pyx
case.pyx
char_types.pyx
combine.pyx
contains.pyx
extract.pyx
find.pyx
find_multiple.pyx
findall.pyx
json.pyx
padding.pyx
repeat.pyx
replace.pyx
replace_re.pyx
strip.pyx
substring.pyx
translate.pyx
wrap.pyx
)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX strings_ ASSOCIATED_TARGETS cudf
)
# TODO: Due to cudf's scalar.pyx needing to cimport pylibcudf's scalar.pyx (because there are parts
# of cudf Cython that need to directly access the c_obj underlying the pylibcudf Scalar) the
# requirement for arrow headers infects all of cudf. That requirement will go away once all
# scalar-related Cython code is removed from cudf.
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${NumPy_INCLUDE_DIRS}")
target_include_directories(${target} PRIVATE "${PYARROW_INCLUDE_DIR}")
endforeach()
add_subdirectory(convert)
add_subdirectory(split)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/translate.pyx
|
# Copyright (c) 2018-2023, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.pair cimport pair
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.translate cimport (
filter_characters as cpp_filter_characters,
filter_type,
translate as cpp_translate,
)
from cudf._lib.cpp.types cimport char_utf8
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def translate(Column source_strings,
object mapping_table):
"""
Translates individual characters within each string
if present in the mapping_table.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef int table_size
table_size = len(mapping_table)
cdef vector[pair[char_utf8, char_utf8]] c_mapping_table
c_mapping_table.reserve(table_size)
for key in mapping_table:
value = mapping_table[key]
if type(value) is int:
value = chr(value)
if type(value) is str:
value = int.from_bytes(value.encode(), byteorder='big')
if type(key) is int:
key = chr(key)
if type(key) is str:
key = int.from_bytes(key.encode(), byteorder='big')
c_mapping_table.push_back((key, value))
with nogil:
c_result = move(cpp_translate(source_view, c_mapping_table))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def filter_characters(Column source_strings,
object mapping_table,
bool keep,
object py_repl):
"""
Removes or keeps individual characters within each string
using the provided mapping_table.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_repl = <const string_scalar*>(
repl.get_raw_ptr()
)
cdef int table_size
table_size = len(mapping_table)
cdef vector[pair[char_utf8, char_utf8]] c_mapping_table
c_mapping_table.reserve(table_size)
for key in mapping_table:
value = mapping_table[key]
if type(value) is int:
value = chr(value)
if type(value) is str:
value = int.from_bytes(value.encode(), byteorder='big')
if type(key) is int:
key = chr(key)
if type(key) is str:
key = int.from_bytes(key.encode(), byteorder='big')
c_mapping_table.push_back((key, value))
cdef filter_type c_keep
if keep is True:
c_keep = filter_type.KEEP
else:
c_keep = filter_type.REMOVE
with nogil:
c_result = move(cpp_filter_characters(
source_view,
c_mapping_table,
c_keep,
scalar_repl[0]
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/padding.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.types cimport size_type
from enum import IntEnum
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.strings.padding cimport pad as cpp_pad, zfill as cpp_zfill
from cudf._lib.cpp.strings.side_type cimport (
side_type,
underlying_type_t_side_type,
)
class SideType(IntEnum):
LEFT = <underlying_type_t_side_type> side_type.LEFT
RIGHT = <underlying_type_t_side_type> side_type.RIGHT
BOTH = <underlying_type_t_side_type> side_type.BOTH
@acquire_spill_lock()
def pad(Column source_strings,
size_type width,
fill_char,
side=SideType.LEFT):
"""
Returns a Column by padding strings in `source_strings`
up to the given `width`. Direction of padding is to be specified by `side`.
The additional characters being filled can be changed by specifying
`fill_char`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string f_char = <string>str(fill_char).encode()
cdef side_type pad_direction = <side_type>(
<underlying_type_t_side_type> side
)
with nogil:
c_result = move(cpp_pad(
source_view,
width,
pad_direction,
f_char
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def zfill(Column source_strings,
size_type width):
"""
Returns a Column by prepending strings in `source_strings`
with '0' characters up to the given `width`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_zfill(
source_view,
width
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def center(Column source_strings,
size_type width,
fill_char):
"""
Returns a Column by filling left and right side of strings
in `source_strings` with additional character, `fill_char`
up to the given `width`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string f_char = <string>str(fill_char).encode()
with nogil:
c_result = move(cpp_pad(
source_view,
width,
side_type.BOTH,
f_char
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def ljust(Column source_strings,
size_type width,
fill_char):
"""
Returns a Column by filling right side of strings in `source_strings`
with additional character, `fill_char` up to the given `width`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string f_char = <string>str(fill_char).encode()
with nogil:
c_result = move(cpp_pad(
source_view,
width,
side_type.RIGHT,
f_char
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def rjust(Column source_strings,
size_type width,
fill_char):
"""
Returns a Column by filling left side of strings in `source_strings`
with additional character, `fill_char` up to the given `width`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string f_char = <string>str(fill_char).encode()
with nogil:
c_result = move(cpp_pad(
source_view,
width,
side_type.LEFT,
f_char
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/attributes.pyx
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.attributes cimport (
code_points as cpp_code_points,
count_bytes as cpp_count_bytes,
count_characters as cpp_count_characters,
)
@acquire_spill_lock()
def count_characters(Column source_strings):
"""
Returns an integer numeric column containing the
length of each string in characters.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_count_characters(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def count_bytes(Column source_strings):
"""
Returns an integer numeric column containing the
number of bytes of each string.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_count_bytes(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def code_points(Column source_strings):
"""
Creates a numeric column with code point values (integers)
for each character of each string.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_code_points(source_view))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/find_multiple.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.find_multiple cimport (
find_multiple as cpp_find_multiple,
)
@acquire_spill_lock()
def find_multiple(Column source_strings, Column target_strings):
"""
Returns a column with character position values where each
of the `target_strings` are found in each string of `source_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view target_view = target_strings.view()
with nogil:
c_result = move(cpp_find_multiple(
source_view,
target_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/contains.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libc.stdint cimport uint32_t
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.contains cimport (
contains_re as cpp_contains_re,
count_re as cpp_count_re,
like as cpp_like,
matches_re as cpp_matches_re,
)
from cudf._lib.cpp.strings.regex_flags cimport regex_flags
from cudf._lib.cpp.strings.regex_program cimport regex_program
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def contains_re(Column source_strings, object reg_ex, uint32_t flags):
"""
Returns a Column of boolean values with True for `source_strings`
that contain regular expression `reg_ex`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string reg_ex_string = <string>str(reg_ex).encode()
cdef regex_flags c_flags = <regex_flags>flags
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(reg_ex_string, c_flags))
c_result = move(cpp_contains_re(
source_view,
dereference(c_prog)
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def count_re(Column source_strings, object reg_ex, uint32_t flags):
"""
Returns a Column with count of occurrences of `reg_ex` in
each string of `source_strings`
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string reg_ex_string = <string>str(reg_ex).encode()
cdef regex_flags c_flags = <regex_flags>flags
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(reg_ex_string, c_flags))
c_result = move(cpp_count_re(
source_view,
dereference(c_prog)
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def match_re(Column source_strings, object reg_ex, uint32_t flags):
"""
Returns a Column with each value True if the string matches `reg_ex`
regular expression with each record of `source_strings`
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string reg_ex_string = <string>str(reg_ex).encode()
cdef regex_flags c_flags = <regex_flags>flags
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(reg_ex_string, c_flags))
c_result = move(cpp_matches_re(
source_view,
dereference(c_prog)
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def like(Column source_strings, object py_pattern, object py_escape):
"""
Returns a Column with each value True if the string matches the
`py_pattern` like expression with each record of `source_strings`
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef DeviceScalar pattern = py_pattern.device_value
cdef DeviceScalar escape = py_escape.device_value
cdef const string_scalar* scalar_ptn = <const string_scalar*>(
pattern.get_raw_ptr()
)
cdef const string_scalar* scalar_esc = <const string_scalar*>(
escape.get_raw_ptr()
)
with nogil:
c_result = move(cpp_like(
source_view,
scalar_ptn[0],
scalar_esc[0]
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/repeat.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings cimport repeat as cpp_repeat
from cudf._lib.cpp.types cimport size_type
@acquire_spill_lock()
def repeat_scalar(Column source_strings,
size_type repeats):
"""
Returns a Column after repeating
each string in `source_strings`
`repeats` number of times.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_repeat.repeat_strings(
source_view,
repeats
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def repeat_sequence(Column source_strings,
Column repeats):
"""
Returns a Column after repeating
each string in `source_strings`
`repeats` number of times.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view repeats_view = repeats.view()
with nogil:
c_result = move(cpp_repeat.repeat_strings(
source_view,
repeats_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/extract.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libc.stdint cimport uint32_t
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.extract cimport extract as cpp_extract
from cudf._lib.cpp.strings.regex_flags cimport regex_flags
from cudf._lib.cpp.strings.regex_program cimport regex_program
from cudf._lib.cpp.table.table cimport table
from cudf._lib.utils cimport data_from_unique_ptr
@acquire_spill_lock()
def extract(Column source_strings, object pattern, uint32_t flags):
"""
Returns data which contains extracted capture groups provided in
`pattern` for all `source_strings`.
The returning data contains one row for each subject string,
and one column for each group.
"""
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = <regex_flags>flags
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_extract(
source_view,
dereference(c_prog)
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/case.pyx
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.case cimport (
swapcase as cpp_swapcase,
to_lower as cpp_to_lower,
to_upper as cpp_to_upper,
)
@acquire_spill_lock()
def to_upper(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_to_upper(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def to_lower(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_to_lower(source_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def swapcase(Column source_strings):
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_swapcase(source_view))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/json.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.json cimport (
get_json_object as cpp_get_json_object,
get_json_object_options,
)
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def get_json_object(
Column col, object py_json_path, GetJsonObjectOptions options):
"""
Apply a JSONPath string to all rows in an input column
of json strings.
"""
cdef unique_ptr[column] c_result
cdef column_view col_view = col.view()
cdef DeviceScalar json_path = py_json_path.device_value
cdef const string_scalar* scalar_json_path = <const string_scalar*>(
json_path.get_raw_ptr()
)
with nogil:
c_result = move(cpp_get_json_object(
col_view,
scalar_json_path[0],
options.options,
))
return Column.from_unique_ptr(move(c_result))
cdef class GetJsonObjectOptions:
cdef get_json_object_options options
def __init__(
self,
*,
allow_single_quotes=False,
strip_quotes_from_single_strings=True,
missing_fields_as_nulls=False
):
self.options.set_allow_single_quotes(allow_single_quotes)
self.options.set_strip_quotes_from_single_strings(
strip_quotes_from_single_strings
)
self.options.set_missing_fields_as_nulls(missing_fields_as_nulls)
@property
def allow_single_quotes(self):
return self.options.get_allow_single_quotes()
@property
def strip_quotes_from_single_strings(self):
return self.options.get_strip_quotes_from_single_strings()
@property
def missing_fields_as_nulls(self):
return self.options.get_missing_fields_as_nulls()
@allow_single_quotes.setter
def allow_single_quotes(self, val):
self.options.set_allow_single_quotes(val)
@strip_quotes_from_single_strings.setter
def strip_quotes_from_single_strings(self, val):
self.options.set_strip_quotes_from_single_strings(val)
@missing_fields_as_nulls.setter
def missing_fields_as_nulls(self, val):
self.options.set_missing_fields_as_nulls(val)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/substring.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
import numpy as np
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.substring cimport slice_strings as cpp_slice_strings
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar import as_device_scalar
from cudf._lib.cpp.scalar.scalar cimport numeric_scalar
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def slice_strings(Column source_strings,
object start,
object end,
object step):
"""
Returns a Column by extracting a substring of each string
at given start and end positions. Slicing can also be
performed in steps by skipping `step` number of
characters in a string.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef DeviceScalar start_scalar = as_device_scalar(start, np.int32)
cdef DeviceScalar end_scalar = as_device_scalar(end, np.int32)
cdef DeviceScalar step_scalar = as_device_scalar(step, np.int32)
cdef numeric_scalar[size_type]* start_numeric_scalar = \
<numeric_scalar[size_type]*>(
start_scalar.get_raw_ptr())
cdef numeric_scalar[size_type]* end_numeric_scalar = \
<numeric_scalar[size_type]*>(end_scalar.get_raw_ptr())
cdef numeric_scalar[size_type]* step_numeric_scalar = \
<numeric_scalar[size_type]*>(step_scalar.get_raw_ptr())
with nogil:
c_result = move(cpp_slice_strings(
source_view,
start_numeric_scalar[0],
end_numeric_scalar[0],
step_numeric_scalar[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def slice_from(Column source_strings,
Column starts,
Column stops):
"""
Returns a Column by extracting a substring of each string
at given starts and stops positions. `starts` and `stops`
here are positions per element in the string-column.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view starts_view = starts.view()
cdef column_view stops_view = stops.view()
with nogil:
c_result = move(cpp_slice_strings(
source_view,
starts_view,
stops_view
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def get(Column source_strings,
object index):
"""
Returns a Column which contains only single
character from each input string. The index of
characters required can be controlled by passing `index`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
if index < 0:
next_index = index - 1
step = -1
else:
next_index = index + 1
step = 1
cdef DeviceScalar start_scalar = as_device_scalar(index, np.int32)
cdef DeviceScalar end_scalar = as_device_scalar(next_index, np.int32)
cdef DeviceScalar step_scalar = as_device_scalar(step, np.int32)
cdef numeric_scalar[size_type]* start_numeric_scalar = \
<numeric_scalar[size_type]*>(
start_scalar.get_raw_ptr())
cdef numeric_scalar[size_type]* end_numeric_scalar = \
<numeric_scalar[size_type]*>(end_scalar.get_raw_ptr())
cdef numeric_scalar[size_type]* step_numeric_scalar = \
<numeric_scalar[size_type]*>(step_scalar.get_raw_ptr())
with nogil:
c_result = move(cpp_slice_strings(
source_view,
start_numeric_scalar[0],
end_numeric_scalar[0],
step_numeric_scalar[0]
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/wrap.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.wrap cimport wrap as cpp_wrap
from cudf._lib.cpp.types cimport size_type
@acquire_spill_lock()
def wrap(Column source_strings,
size_type width):
"""
Returns a Column by wrapping long strings
in the Column to be formatted in paragraphs
with length less than a given `width`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_wrap(
source_view,
width
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/find.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.find cimport (
contains as cpp_contains,
ends_with as cpp_ends_with,
find as cpp_find,
rfind as cpp_rfind,
starts_with as cpp_starts_with,
)
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def contains(Column source_strings, object py_target):
"""
Returns a Column of boolean values with True for `source_strings`
that contain the pattern given in `py_target`.
"""
cdef DeviceScalar target = py_target.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
target.get_raw_ptr()
)
with nogil:
c_result = move(cpp_contains(
source_view,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def contains_multiple(Column source_strings, Column target_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain the corresponding string in `target_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view target_view = target_strings.view()
with nogil:
c_result = move(cpp_contains(
source_view,
target_view
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def endswith(Column source_strings, object py_target):
"""
Returns a Column of boolean values with True for `source_strings`
that contain strings that end with the pattern given in `py_target`.
"""
cdef DeviceScalar target = py_target.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
target.get_raw_ptr()
)
with nogil:
c_result = move(cpp_ends_with(
source_view,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def endswith_multiple(Column source_strings, Column target_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain strings that end with corresponding location
in `target_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view target_view = target_strings.view()
with nogil:
c_result = move(cpp_ends_with(
source_view,
target_view
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def startswith(Column source_strings, object py_target):
"""
Returns a Column of boolean values with True for `source_strings`
that contain strings that start with the pattern given in `py_target`.
"""
cdef DeviceScalar target = py_target.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
target.get_raw_ptr()
)
with nogil:
c_result = move(cpp_starts_with(
source_view,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def startswith_multiple(Column source_strings, Column target_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that contain strings that begin with corresponding location
in `target_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view target_view = target_strings.view()
with nogil:
c_result = move(cpp_starts_with(
source_view,
target_view
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def find(Column source_strings,
object py_target,
size_type start,
size_type end):
"""
Returns a Column containing lowest indexes in each string of
`source_strings` that fully contain `py_target` string.
Scan portion of strings in `source_strings` can be
controlled by setting `start` and `end` values.
"""
cdef DeviceScalar target = py_target.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
target.get_raw_ptr()
)
with nogil:
c_result = move(cpp_find(
source_view,
scalar_str[0],
start,
end
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def rfind(Column source_strings,
object py_target,
size_type start,
size_type end):
"""
Returns a Column containing highest indexes in each string of
`source_strings` that fully contain `py_target` string.
Scan portion of strings in `source_strings` can be
controlled by setting `start` and `end` values.
"""
cdef DeviceScalar target = py_target.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
target.get_raw_ptr()
)
with nogil:
c_result = move(cpp_rfind(
source_view,
scalar_str[0],
start,
end
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/replace.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libc.stdint cimport int32_t
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.replace cimport (
replace as cpp_replace,
replace_slice as cpp_replace_slice,
)
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def slice_replace(Column source_strings,
size_type start,
size_type stop,
object py_repl):
"""
Returns a Column by replacing specified section
of each string with `py_repl`. Positions can be
specified with `start` and `stop` params.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_replace_slice(
source_view,
scalar_str[0],
start,
stop
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def insert(Column source_strings,
size_type start,
object py_repl):
"""
Returns a Column by inserting a specified
string `py_repl` at a specific position in all strings.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_replace_slice(
source_view,
scalar_str[0],
start,
start
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace(Column source_strings,
object py_target,
object py_repl,
int32_t maxrepl):
"""
Returns a Column after replacing occurrences of
patterns `py_target` with `py_repl` in `source_strings`.
`maxrepl` indicates number of replacements to make from start.
"""
cdef DeviceScalar target = py_target.device_value
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_target = <const string_scalar*>(
target.get_raw_ptr()
)
cdef const string_scalar* scalar_repl = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_replace(
source_view,
scalar_target[0],
scalar_repl[0],
maxrepl
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_multi(Column source_strings,
Column target_strings,
Column repl_strings):
"""
Returns a Column after replacing occurrences of
patterns `target_strings` with `repl_strings` in `source_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view target_view = target_strings.view()
cdef column_view repl_view = repl_strings.view()
with nogil:
c_result = move(cpp_replace(
source_view,
target_view,
repl_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/strip.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.side_type cimport side_type
from cudf._lib.cpp.strings.strip cimport strip as cpp_strip
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def strip(Column source_strings,
object py_repl):
"""
Returns a Column by removing leading and trailing characters.
The set of characters need be stripped from left and right side
can be specified by `py_repl`.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_strip(
source_view,
side_type.BOTH,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def lstrip(Column source_strings,
object py_repl):
"""
Returns a Column by removing leading and trailing characters.
The set of characters need be stripped from left side can
be specified by `py_repl`.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_strip(
source_view,
side_type.LEFT,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def rstrip(Column source_strings,
object py_repl):
"""
Returns a Column by removing leading and trailing characters.
The set of characters need be stripped from right side can
be specified by `py_repl`.
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
repl.get_raw_ptr()
)
with nogil:
c_result = move(cpp_strip(
source_view,
side_type.RIGHT,
scalar_str[0]
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/__init__.py
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf._lib.nvtext.edit_distance import edit_distance, edit_distance_matrix
from cudf._lib.nvtext.generate_ngrams import (
generate_character_ngrams,
generate_ngrams,
hash_character_ngrams,
)
from cudf._lib.nvtext.jaccard import jaccard_index
from cudf._lib.nvtext.minhash import minhash, minhash64
from cudf._lib.nvtext.ngrams_tokenize import ngrams_tokenize
from cudf._lib.nvtext.normalize import normalize_characters, normalize_spaces
from cudf._lib.nvtext.replace import filter_tokens, replace_tokens
from cudf._lib.nvtext.stemmer import (
LetterType,
is_letter,
is_letter_multi,
porter_stemmer_measure,
)
from cudf._lib.nvtext.tokenize import (
_count_tokens_column,
_count_tokens_scalar,
_tokenize_column,
_tokenize_scalar,
character_tokenize,
detokenize,
tokenize_with_vocabulary,
)
from cudf._lib.strings.attributes import (
code_points,
count_bytes,
count_characters,
)
from cudf._lib.strings.capitalize import capitalize, is_title, title
from cudf._lib.strings.case import swapcase, to_lower, to_upper
from cudf._lib.strings.char_types import (
filter_alphanum,
is_alnum,
is_alpha,
is_decimal,
is_digit,
is_lower,
is_numeric,
is_space,
is_upper,
)
from cudf._lib.strings.combine import (
concatenate,
join,
join_lists_with_column,
join_lists_with_scalar,
)
from cudf._lib.strings.contains import contains_re, count_re, like, match_re
from cudf._lib.strings.convert.convert_fixed_point import to_decimal
from cudf._lib.strings.convert.convert_floats import is_float
from cudf._lib.strings.convert.convert_integers import is_integer
from cudf._lib.strings.convert.convert_urls import url_decode, url_encode
from cudf._lib.strings.extract import extract
from cudf._lib.strings.find import (
contains,
contains_multiple,
endswith,
endswith_multiple,
find,
rfind,
startswith,
startswith_multiple,
)
from cudf._lib.strings.find_multiple import find_multiple
from cudf._lib.strings.findall import findall
from cudf._lib.strings.json import GetJsonObjectOptions, get_json_object
from cudf._lib.strings.padding import (
SideType,
center,
ljust,
pad,
rjust,
zfill,
)
from cudf._lib.strings.repeat import repeat_scalar, repeat_sequence
from cudf._lib.strings.replace import (
insert,
replace,
replace_multi,
slice_replace,
)
from cudf._lib.strings.replace_re import (
replace_multi_re,
replace_re,
replace_with_backrefs,
)
from cudf._lib.strings.split.partition import partition, rpartition
from cudf._lib.strings.split.split import (
rsplit,
rsplit_re,
rsplit_record,
rsplit_record_re,
split,
split_re,
split_record,
split_record_re,
)
from cudf._lib.strings.strip import lstrip, rstrip, strip
from cudf._lib.strings.substring import get, slice_from, slice_strings
from cudf._lib.strings.translate import filter_characters, translate
from cudf._lib.strings.wrap import wrap
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/combine.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.combine cimport (
concatenate as cpp_concatenate,
join_list_elements as cpp_join_list_elements,
join_strings as cpp_join_strings,
output_if_empty_list,
separator_on_nulls,
)
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.utils cimport table_view_from_columns
@acquire_spill_lock()
def concatenate(list source_strings,
object sep,
object na_rep):
"""
Returns a Column by concatenating strings column-wise in `source_strings`
with the specified `sep` between each column and
`na`/`None` values are replaced by `na_rep`
"""
cdef DeviceScalar separator = sep.device_value
cdef DeviceScalar narep = na_rep.device_value
cdef unique_ptr[column] c_result
cdef table_view source_view = table_view_from_columns(source_strings)
cdef const string_scalar* scalar_separator = \
<const string_scalar*>(separator.get_raw_ptr())
cdef const string_scalar* scalar_narep = <const string_scalar*>(
narep.get_raw_ptr()
)
with nogil:
c_result = move(cpp_concatenate(
source_view,
scalar_separator[0],
scalar_narep[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def join(Column source_strings,
object sep,
object na_rep):
"""
Returns a Column by concatenating strings row-wise in `source_strings`
with the specified `sep` between each column and
`na`/`None` values are replaced by `na_rep`
"""
cdef DeviceScalar separator = sep.device_value
cdef DeviceScalar narep = na_rep.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_separator = \
<const string_scalar*>(separator.get_raw_ptr())
cdef const string_scalar* scalar_narep = <const string_scalar*>(
narep.get_raw_ptr()
)
with nogil:
c_result = move(cpp_join_strings(
source_view,
scalar_separator[0],
scalar_narep[0]
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def join_lists_with_scalar(
Column source_strings,
object py_separator,
object py_narep):
"""
Returns a Column by concatenating Lists of strings row-wise
in `source_strings` with the specified `py_separator`
between each string in lists and `<NA>`/`None` values
are replaced by `py_narep`
"""
cdef DeviceScalar separator = py_separator.device_value
cdef DeviceScalar narep = py_narep.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_separator = \
<const string_scalar*>(separator.get_raw_ptr())
cdef const string_scalar* scalar_narep = <const string_scalar*>(
narep.get_raw_ptr()
)
with nogil:
c_result = move(cpp_join_list_elements(
source_view,
scalar_separator[0],
scalar_narep[0],
separator_on_nulls.YES,
output_if_empty_list.NULL_ELEMENT
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def join_lists_with_column(
Column source_strings,
Column separator_strings,
object py_source_narep,
object py_separator_narep):
"""
Returns a Column by concatenating Lists of strings row-wise in
`source_strings` with a corresponding separator at the same
position in `separator_strings` and `<NA>`/`None` values in
`source_strings` are replaced by `py_source_narep` and
`<NA>`/`None` values in `separator_strings` are replaced
by `py_separator_narep`
"""
cdef DeviceScalar source_narep = py_source_narep.device_value
cdef DeviceScalar separator_narep = py_separator_narep.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view separator_view = separator_strings.view()
cdef const string_scalar* scalar_source_narep = \
<const string_scalar*>(source_narep.get_raw_ptr())
cdef const string_scalar* scalar_separator_narep = <const string_scalar*>(
separator_narep.get_raw_ptr()
)
with nogil:
c_result = move(cpp_join_list_elements(
source_view,
separator_view,
scalar_separator_narep[0],
scalar_source_narep[0],
separator_on_nulls.YES,
output_if_empty_list.NULL_ELEMENT
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/replace_re.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from libcpp.vector cimport vector
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.regex_flags cimport regex_flags
from cudf._lib.cpp.strings.regex_program cimport regex_program
from cudf._lib.cpp.strings.replace_re cimport (
replace_re as cpp_replace_re,
replace_with_backrefs as cpp_replace_with_backrefs,
)
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def replace_re(Column source_strings,
object pattern,
object py_repl,
size_type n):
"""
Returns a Column after replacing occurrences regular
expressions `pattern` with `py_repl` in `source_strings`.
`n` indicates the number of resplacements to be made from
start. (-1 indicates all)
"""
cdef DeviceScalar repl = py_repl.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef const string_scalar* scalar_repl = \
<const string_scalar*>(repl.get_raw_ptr())
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_replace_re(
source_view,
dereference(c_prog),
scalar_repl[0],
n
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_with_backrefs(
Column source_strings,
object pattern,
object repl):
"""
Returns a Column after using the `repl` back-ref template to create
new string with the extracted elements found using
`pattern` regular expression in `source_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef string repl_string = <string>str(repl).encode()
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_replace_with_backrefs(
source_view,
dereference(c_prog),
repl_string
))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def replace_multi_re(Column source_strings,
object patterns,
Column repl_strings):
"""
Returns a Column after replacing occurrences of multiple
regular expressions `patterns` with their corresponding
strings in `repl_strings` in `source_strings`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef column_view repl_view = repl_strings.view()
cdef int pattern_size = len(patterns)
cdef vector[string] patterns_vector
patterns_vector.reserve(pattern_size)
for pattern in patterns:
patterns_vector.push_back(str.encode(pattern))
with nogil:
c_result = move(cpp_replace_re(
source_view,
patterns_vector,
repl_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/split/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources partition.pyx split.pyx)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX strings_ ASSOCIATED_TARGETS cudf
)
# TODO: Due to cudf's scalar.pyx needing to cimport pylibcudf's scalar.pyx (because there are parts
# of cudf Cython that need to directly access the c_obj underlying the pylibcudf Scalar) the
# requirement for arrow headers infects all of cudf. That requirement will go away once all
# scalar-related Cython code is removed from cudf.
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${NumPy_INCLUDE_DIRS}")
target_include_directories(${target} PRIVATE "${PYARROW_INCLUDE_DIR}")
endforeach()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/split/split.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cython.operator cimport dereference
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.regex_flags cimport regex_flags
from cudf._lib.cpp.strings.regex_program cimport regex_program
from cudf._lib.cpp.strings.split.split cimport (
rsplit as cpp_rsplit,
rsplit_re as cpp_rsplit_re,
rsplit_record as cpp_rsplit_record,
rsplit_record_re as cpp_rsplit_record_re,
split as cpp_split,
split_re as cpp_split_re,
split_record as cpp_split_record,
split_record_re as cpp_split_record_re,
)
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.utils cimport data_from_unique_ptr
@acquire_spill_lock()
def split(Column source_strings,
object py_delimiter,
size_type maxsplit):
"""
Returns data by splitting the `source_strings`
column around the specified `py_delimiter`.
The split happens from beginning.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_split(
source_view,
scalar_str[0],
maxsplit
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
@acquire_spill_lock()
def split_record(Column source_strings,
object py_delimiter,
size_type maxsplit):
"""
Returns a Column by splitting the `source_strings`
column around the specified `py_delimiter`.
The split happens from beginning.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_split_record(
source_view,
scalar_str[0],
maxsplit
))
return Column.from_unique_ptr(
move(c_result),
)
@acquire_spill_lock()
def rsplit(Column source_strings,
object py_delimiter,
size_type maxsplit):
"""
Returns data by splitting the `source_strings`
column around the specified `py_delimiter`.
The split happens from the end.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_rsplit(
source_view,
scalar_str[0],
maxsplit
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
@acquire_spill_lock()
def rsplit_record(Column source_strings,
object py_delimiter,
size_type maxsplit):
"""
Returns a Column by splitting the `source_strings`
column around the specified `py_delimiter`.
The split happens from the end.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_rsplit_record(
source_view,
scalar_str[0],
maxsplit
))
return Column.from_unique_ptr(
move(c_result),
)
@acquire_spill_lock()
def split_re(Column source_strings,
object pattern,
size_type maxsplit):
"""
Returns data by splitting the `source_strings`
column around the delimiters identified by `pattern`.
"""
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_split_re(
source_view,
dereference(c_prog),
maxsplit
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
@acquire_spill_lock()
def rsplit_re(Column source_strings,
object pattern,
size_type maxsplit):
"""
Returns data by splitting the `source_strings`
column around the delimiters identified by `pattern`.
The delimiters are searched starting from the end of each string.
"""
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_rsplit_re(
source_view,
dereference(c_prog),
maxsplit
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
@acquire_spill_lock()
def split_record_re(Column source_strings,
object pattern,
size_type maxsplit):
"""
Returns a Column by splitting the `source_strings`
column around the delimiters identified by `pattern`.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_split_record_re(
source_view,
dereference(c_prog),
maxsplit
))
return Column.from_unique_ptr(
move(c_result),
)
@acquire_spill_lock()
def rsplit_record_re(Column source_strings,
object pattern,
size_type maxsplit):
"""
Returns a Column by splitting the `source_strings`
column around the delimiters identified by `pattern`.
The delimiters are searched starting from the end of each string.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
cdef string pattern_string = <string>str(pattern).encode()
cdef regex_flags c_flags = regex_flags.DEFAULT
cdef unique_ptr[regex_program] c_prog
with nogil:
c_prog = move(regex_program.create(pattern_string, c_flags))
c_result = move(cpp_rsplit_record_re(
source_view,
dereference(c_prog),
maxsplit
))
return Column.from_unique_ptr(
move(c_result),
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/split/partition.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.split.partition cimport (
partition as cpp_partition,
rpartition as cpp_rpartition,
)
from cudf._lib.cpp.table.table cimport table
from cudf._lib.scalar cimport DeviceScalar
from cudf._lib.utils cimport data_from_unique_ptr
@acquire_spill_lock()
def partition(Column source_strings,
object py_delimiter):
"""
Returns data by splitting the `source_strings`
column at the first occurrence of the specified `py_delimiter`.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_partition(
source_view,
scalar_str[0]
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
@acquire_spill_lock()
def rpartition(Column source_strings,
object py_delimiter):
"""
Returns a Column by splitting the `source_strings`
column at the last occurrence of the specified `py_delimiter`.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef unique_ptr[table] c_result
cdef column_view source_view = source_strings.view()
cdef const string_scalar* scalar_str = <const string_scalar*>(
delimiter.get_raw_ptr()
)
with nogil:
c_result = move(cpp_rpartition(
source_view,
scalar_str[0]
))
return data_from_unique_ptr(
move(c_result),
column_names=range(0, c_result.get()[0].num_columns())
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/convert_integers.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.convert.convert_integers cimport (
is_integer as cpp_is_integer,
)
@acquire_spill_lock()
def is_integer(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that have integers.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_is_integer(
source_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources convert_fixed_point.pyx convert_floats.pyx convert_integers.pyx
convert_lists.pyx convert_urls.pyx
)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX strings_ ASSOCIATED_TARGETS cudf
)
# TODO: Due to cudf's scalar.pyx needing to cimport pylibcudf's scalar.pyx (because there are parts
# of cudf Cython that need to directly access the c_obj underlying the pylibcudf Scalar) the
# requirement for arrow headers infects all of cudf. That requirement will go away once all
# scalar-related Cython code is removed from cudf.
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${NumPy_INCLUDE_DIRS}")
target_include_directories(${target} PRIVATE "${PYARROW_INCLUDE_DIR}")
endforeach()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/convert_floats.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.convert.convert_floats cimport (
is_float as cpp_is_float,
)
@acquire_spill_lock()
def is_float(Column source_strings):
"""
Returns a Column of boolean values with True for `source_strings`
that have floats.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_is_float(
source_view
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/convert_urls.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.convert.convert_urls cimport (
url_decode as cpp_url_decode,
url_encode as cpp_url_encode,
)
@acquire_spill_lock()
def url_decode(Column source_strings):
"""
Decode each string in column. No format checking is performed.
Parameters
----------
input_col : input column of type string
Returns
-------
URL decoded string column
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_url_decode(
source_view
))
return Column.from_unique_ptr(
move(c_result)
)
@acquire_spill_lock()
def url_encode(Column source_strings):
"""
Encode each string in column. No format checking is performed.
All characters are encoded except for ASCII letters, digits,
and these characters: '.','_','-','~'. Encoding converts to
hex using UTF-8 encoded bytes.
Parameters
----------
input_col : input column of type string
Returns
-------
URL encoded string column
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_strings.view()
with nogil:
c_result = move(cpp_url_encode(
source_view
))
return Column.from_unique_ptr(
move(c_result)
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/convert_lists.pyx
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.strings.convert.convert_lists cimport (
format_list_column as cpp_format_list_column,
)
from cudf._lib.scalar import as_device_scalar
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def format_list_column(Column source_list, Column separators):
"""
Format a list column of strings into a strings column.
Parameters
----------
input_col : input column of type list with strings child.
separators: strings used for formatting (', ', '[', ']')
Returns
-------
Formatted strings column
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = source_list.view()
cdef column_view separators_view = separators.view()
# Use 'None' as null-replacement string
cdef DeviceScalar str_na_rep = as_device_scalar("None")
cdef const string_scalar* string_scalar_na_rep = <const string_scalar*>(
str_na_rep.get_raw_ptr())
with nogil:
c_result = move(cpp_format_list_column(
source_view, string_scalar_na_rep[0], separators_view
))
return Column.from_unique_ptr(
move(c_result)
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/strings/convert/convert_fixed_point.pyx
|
# Copyright (c) 2021-2023, NVIDIA CORPORATION.
import cudf
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf.core.buffer import acquire_spill_lock
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.strings.convert.convert_fixed_point cimport (
from_fixed_point as cpp_from_fixed_point,
is_fixed_point as cpp_is_fixed_point,
to_fixed_point as cpp_to_fixed_point,
)
from cudf._lib.cpp.types cimport data_type, type_id
@acquire_spill_lock()
def from_decimal(Column input_col):
"""
Converts a `Decimal64Column` to a `StringColumn`.
Parameters
----------
input_col : input column of type decimal
Returns
-------
A column of strings representing the input decimal values.
"""
cdef column_view input_column_view = input_col.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_from_fixed_point(
input_column_view))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def to_decimal(Column input_col, object out_type):
"""
Returns a `Decimal64Column` from the provided `StringColumn`
using the scale in the `out_type`.
Parameters
----------
input_col : input column of type string
out_type : The type and scale of the decimal column expected
Returns
-------
A column of decimals parsed from the string values.
"""
cdef column_view input_column_view = input_col.view()
cdef unique_ptr[column] c_result
cdef int scale = out_type.scale
cdef data_type c_out_type
if isinstance(out_type, cudf.Decimal32Dtype):
c_out_type = data_type(type_id.DECIMAL32, -scale)
elif isinstance(out_type, cudf.Decimal64Dtype):
c_out_type = data_type(type_id.DECIMAL64, -scale)
elif isinstance(out_type, cudf.Decimal128Dtype):
c_out_type = data_type(type_id.DECIMAL128, -scale)
else:
raise TypeError("should be a decimal dtype")
with nogil:
c_result = move(
cpp_to_fixed_point(
input_column_view,
c_out_type))
result = Column.from_unique_ptr(move(c_result))
result.dtype.precision = out_type.precision
return result
@acquire_spill_lock()
def is_fixed_point(Column input_col, object dtype):
"""
Returns a Column of boolean values with True for `input_col`
that have fixed-point characters. The output row also has a
False value if the corresponding string would cause an integer
overflow. The scale of the `dtype` is used to determine overflow
in the output row.
Parameters
----------
input_col : input column of type string
dtype : The type and scale of a decimal column
Returns
-------
A Column of booleans indicating valid decimal conversion.
"""
cdef unique_ptr[column] c_result
cdef column_view source_view = input_col.view()
cdef int scale = dtype.scale
cdef data_type c_dtype = data_type(type_id.DECIMAL64, -scale)
with nogil:
c_result = move(cpp_is_fixed_point(
source_view,
c_dtype
))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/subword_tokenize.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libc.stdint cimport uint32_t
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.subword_tokenize cimport (
hashed_vocabulary as cpp_hashed_vocabulary,
load_vocabulary_file as cpp_load_vocabulary_file,
move as tr_move,
subword_tokenize as cpp_subword_tokenize,
tokenizer_result as cpp_tokenizer_result,
)
cdef class Hashed_Vocabulary:
cdef unique_ptr[cpp_hashed_vocabulary] c_obj
def __cinit__(self, hash_file):
cdef string c_hash_file = <string>str(hash_file).encode()
with nogil:
self.c_obj = move(cpp_load_vocabulary_file(c_hash_file))
@acquire_spill_lock()
def subword_tokenize_inmem_hash(
Column strings,
Hashed_Vocabulary hashed_vocabulary,
uint32_t max_sequence_length=64,
uint32_t stride=48,
bool do_lower=True,
bool do_truncate=False,
):
"""
Subword tokenizes text series by using the pre-loaded hashed vocabulary
"""
cdef column_view c_strings = strings.view()
cdef cpp_tokenizer_result c_result
with nogil:
c_result = tr_move(
cpp_subword_tokenize(
c_strings,
hashed_vocabulary.c_obj.get()[0],
max_sequence_length,
stride,
do_lower,
do_truncate,
)
)
# return the 3 tensor components
tokens = Column.from_unique_ptr(move(c_result.tensor_token_ids))
masks = Column.from_unique_ptr(move(c_result.tensor_attention_mask))
metadata = Column.from_unique_ptr(move(c_result.tensor_metadata))
return tokens, masks, metadata
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/stemmer.pyx
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from enum import IntEnum
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.stemmer cimport (
is_letter as cpp_is_letter,
letter_type,
porter_stemmer_measure as cpp_porter_stemmer_measure,
underlying_type_t_letter_type,
)
from cudf._lib.cpp.types cimport size_type
class LetterType(IntEnum):
CONSONANT = <underlying_type_t_letter_type> letter_type.CONSONANT
VOWEL = <underlying_type_t_letter_type> letter_type.VOWEL
@acquire_spill_lock()
def porter_stemmer_measure(Column strings):
cdef column_view c_strings = strings.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_porter_stemmer_measure(c_strings))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_letter(Column strings,
object ltype,
size_type index):
cdef column_view c_strings = strings.view()
cdef letter_type c_ltype = <letter_type>(
<underlying_type_t_letter_type> ltype
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_is_letter(c_strings, c_ltype, index))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def is_letter_multi(Column strings,
object ltype,
Column indices):
cdef column_view c_strings = strings.view()
cdef column_view c_indices = indices.view()
cdef letter_type c_ltype = <letter_type>(
<underlying_type_t_letter_type> ltype
)
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_is_letter(c_strings, c_ltype, c_indices))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources
byte_pair_encode.pyx edit_distance.pyx generate_ngrams.pyx jaccard.pyx minhash.pyx
ngrams_tokenize.pyx normalize.pyx replace.pyx stemmer.pyx subword_tokenize.pyx tokenize.pyx
)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" MODULE_PREFIX nvtext_ ASSOCIATED_TARGETS cudf
)
# TODO: Due to cudf's scalar.pyx needing to cimport pylibcudf's scalar.pyx (because there are parts
# of cudf Cython that need to directly access the c_obj underlying the pylibcudf Scalar) the
# requirement for arrow headers infects all of cudf. That in turn requires including numpy headers.
# These requirements will go away once all scalar-related Cython code is removed from cudf.
foreach(target IN LISTS RAPIDS_CYTHON_CREATED_TARGETS)
target_include_directories(${target} PRIVATE "${NumPy_INCLUDE_DIRS}")
target_include_directories(${target} PRIVATE "${PYARROW_INCLUDE_DIR}")
endforeach()
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/ngrams_tokenize.pyx
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.ngrams_tokenize cimport (
ngrams_tokenize as cpp_ngrams_tokenize,
)
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def ngrams_tokenize(
Column strings,
int ngrams,
object py_delimiter,
object py_separator
):
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef DeviceScalar separator = py_separator.device_value
cdef column_view c_strings = strings.view()
cdef size_type c_ngrams = ngrams
cdef const string_scalar* c_separator = <const string_scalar*>separator\
.get_raw_ptr()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_ngrams_tokenize(
c_strings,
c_ngrams,
c_delimiter[0],
c_separator[0]
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/jaccard.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.jaccard cimport jaccard_index as cpp_jaccard_index
from cudf._lib.cpp.types cimport size_type
@acquire_spill_lock()
def jaccard_index(Column input1, Column input2, int width):
cdef column_view c_input1 = input1.view()
cdef column_view c_input2 = input2.view()
cdef size_type c_width = width
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_jaccard_index(
c_input1,
c_input2,
c_width
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/edit_distance.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.edit_distance cimport (
edit_distance as cpp_edit_distance,
edit_distance_matrix as cpp_edit_distance_matrix,
)
@acquire_spill_lock()
def edit_distance(Column strings, Column targets):
cdef column_view c_strings = strings.view()
cdef column_view c_targets = targets.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_edit_distance(c_strings, c_targets))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def edit_distance_matrix(Column strings):
cdef column_view c_strings = strings.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_edit_distance_matrix(c_strings))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/generate_ngrams.pyx
|
# Copyright (c) 2018-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.generate_ngrams cimport (
generate_character_ngrams as cpp_generate_character_ngrams,
generate_ngrams as cpp_generate_ngrams,
hash_character_ngrams as cpp_hash_character_ngrams,
)
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def generate_ngrams(Column strings, int ngrams, object py_separator):
cdef DeviceScalar separator = py_separator.device_value
cdef column_view c_strings = strings.view()
cdef size_type c_ngrams = ngrams
cdef const string_scalar* c_separator = <const string_scalar*>separator\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_generate_ngrams(
c_strings,
c_ngrams,
c_separator[0]
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def generate_character_ngrams(Column strings, int ngrams):
cdef column_view c_strings = strings.view()
cdef size_type c_ngrams = ngrams
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_generate_character_ngrams(
c_strings,
c_ngrams
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def hash_character_ngrams(Column strings, int ngrams):
cdef column_view c_strings = strings.view()
cdef size_type c_ngrams = ngrams
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_hash_character_ngrams(
c_strings,
c_ngrams
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/minhash.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.minhash cimport (
minhash as cpp_minhash,
minhash64 as cpp_minhash64,
)
from cudf._lib.cpp.types cimport size_type
@acquire_spill_lock()
def minhash(Column strings, Column seeds, int width):
cdef column_view c_strings = strings.view()
cdef size_type c_width = width
cdef column_view c_seeds = seeds.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_minhash(
c_strings,
c_seeds,
c_width
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def minhash64(Column strings, Column seeds, int width):
cdef column_view c_strings = strings.view()
cdef size_type c_width = width
cdef column_view c_seeds = seeds.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_minhash64(
c_strings,
c_seeds,
c_width
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/replace.pyx
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.replace cimport (
filter_tokens as cpp_filter_tokens,
replace_tokens as cpp_replace_tokens,
)
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def replace_tokens(Column strings,
Column targets,
Column replacements,
object py_delimiter):
"""
The `targets` tokens are searched for within each `strings`
in the Column and replaced with the corresponding `replacements`
if found. Tokens are identified by the `py_delimiter` character
provided.
"""
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef column_view c_strings = strings.view()
cdef column_view c_targets = targets.view()
cdef column_view c_replacements = replacements.view()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_replace_tokens(
c_strings,
c_targets,
c_replacements,
c_delimiter[0],
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def filter_tokens(Column strings,
size_type min_token_length,
object py_replacement,
object py_delimiter):
"""
Tokens smaller than `min_token_length` are removed from `strings`
in the Column and optionally replaced with the corresponding
`py_replacement` string. Tokens are identified by the `py_delimiter`
character provided.
"""
cdef DeviceScalar replacement = py_replacement.device_value
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef column_view c_strings = strings.view()
cdef const string_scalar* c_repl = <const string_scalar*>replacement\
.get_raw_ptr()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_filter_tokens(
c_strings,
min_token_length,
c_repl[0],
c_delimiter[0],
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/normalize.pyx
|
# Copyright (c) 2018-2022, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.normalize cimport (
normalize_characters as cpp_normalize_characters,
normalize_spaces as cpp_normalize_spaces,
)
@acquire_spill_lock()
def normalize_spaces(Column strings):
cdef column_view c_strings = strings.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_normalize_spaces(c_strings))
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def normalize_characters(Column strings, bool do_lower=True):
cdef column_view c_strings = strings.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(cpp_normalize_characters(c_strings, do_lower))
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/byte_pair_encode.pyx
|
# Copyright (c) 2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.byte_pair_encode cimport (
bpe_merge_pairs as cpp_bpe_merge_pairs,
byte_pair_encoding as cpp_byte_pair_encoding,
load_merge_pairs as cpp_load_merge_pairs,
)
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.scalar cimport DeviceScalar
cdef class BPEMergePairs:
cdef unique_ptr[cpp_bpe_merge_pairs] c_obj
def __cinit__(self, Column merge_pairs):
cdef column_view c_pairs = merge_pairs.view()
with nogil:
self.c_obj = move(cpp_load_merge_pairs(c_pairs))
@acquire_spill_lock()
def byte_pair_encoding(
Column strings,
BPEMergePairs merge_pairs,
object separator
):
cdef column_view c_strings = strings.view()
cdef DeviceScalar d_separator = separator.device_value
cdef const string_scalar* c_separator = <const string_scalar*>d_separator\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_byte_pair_encoding(
c_strings,
merge_pairs.c_obj.get()[0],
c_separator[0]
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/nvtext/tokenize.pyx
|
# Copyright (c) 2018-2023, NVIDIA CORPORATION.
from cudf.core.buffer import acquire_spill_lock
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from cudf._lib.column cimport Column
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.nvtext.tokenize cimport (
character_tokenize as cpp_character_tokenize,
count_tokens as cpp_count_tokens,
detokenize as cpp_detokenize,
load_vocabulary as cpp_load_vocabulary,
tokenize as cpp_tokenize,
tokenize_vocabulary as cpp_tokenize_vocabulary,
tokenize_with_vocabulary as cpp_tokenize_with_vocabulary,
)
from cudf._lib.cpp.scalar.scalar cimport string_scalar
from cudf._lib.cpp.types cimport size_type
from cudf._lib.scalar cimport DeviceScalar
@acquire_spill_lock()
def _tokenize_scalar(Column strings, object py_delimiter):
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef column_view c_strings = strings.view()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_tokenize(
c_strings,
c_delimiter[0],
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def _tokenize_column(Column strings, Column delimiters):
cdef column_view c_strings = strings.view()
cdef column_view c_delimiters = delimiters.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_tokenize(
c_strings,
c_delimiters
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def _count_tokens_scalar(Column strings, object py_delimiter):
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef column_view c_strings = strings.view()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_count_tokens(
c_strings,
c_delimiter[0]
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def _count_tokens_column(Column strings, Column delimiters):
cdef column_view c_strings = strings.view()
cdef column_view c_delimiters = delimiters.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_count_tokens(
c_strings,
c_delimiters
)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def character_tokenize(Column strings):
cdef column_view c_strings = strings.view()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_character_tokenize(c_strings)
)
return Column.from_unique_ptr(move(c_result))
@acquire_spill_lock()
def detokenize(Column strings, Column indices, object py_separator):
cdef DeviceScalar separator = py_separator.device_value
cdef column_view c_strings = strings.view()
cdef column_view c_indices = indices.view()
cdef const string_scalar* c_separator = <const string_scalar*>separator\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_detokenize(c_strings, c_indices, c_separator[0])
)
return Column.from_unique_ptr(move(c_result))
cdef class TokenizeVocabulary:
cdef unique_ptr[cpp_tokenize_vocabulary] c_obj
def __cinit__(self, Column vocab):
cdef column_view c_vocab = vocab.view()
with nogil:
self.c_obj = move(cpp_load_vocabulary(c_vocab))
@acquire_spill_lock()
def tokenize_with_vocabulary(Column strings,
TokenizeVocabulary vocabulary,
object py_delimiter,
size_type default_id):
cdef DeviceScalar delimiter = py_delimiter.device_value
cdef column_view c_strings = strings.view()
cdef const string_scalar* c_delimiter = <const string_scalar*>delimiter\
.get_raw_ptr()
cdef unique_ptr[column] c_result
with nogil:
c_result = move(
cpp_tokenize_with_vocabulary(
c_strings,
vocabulary.c_obj.get()[0],
c_delimiter[0],
default_id
)
)
return Column.from_unique_ptr(move(c_result))
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/quantiles.pxd
|
# Copyright (c) 2020, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.vector cimport vector
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport (
interpolation,
null_order,
order,
order_info,
sorted,
)
cdef extern from "cudf/quantiles.hpp" namespace "cudf" nogil:
cdef unique_ptr[column] quantile (
column_view input,
vector[double] q,
interpolation interp,
column_view ordered_indices,
bool exact,
) except +
cdef unique_ptr[table] quantiles (
table_view source_table,
vector[double] q,
interpolation interp,
sorted is_input_sorted,
vector[order] column_order,
vector[null_order] null_precedence,
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/merge.pxd
|
# Copyright (c) 2020, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.vector cimport vector
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
cdef extern from "cudf/merge.hpp" namespace "cudf" nogil:
cdef unique_ptr[table] merge (
vector[table_view] tables_to_merge,
vector[libcudf_types.size_type] key_cols,
vector[libcudf_types.order] column_order,
vector[libcudf_types.null_order] null_precedence,
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/partitioning.pxd
|
# Copyright (c) 2020, NVIDIA CORPORATION.
from libc.stdint cimport uint32_t
from libcpp.memory cimport unique_ptr
from libcpp.pair cimport pair
from libcpp.vector cimport vector
cimport cudf._lib.cpp.types as libcudf_types
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
cdef extern from "cudf/partitioning.hpp" namespace "cudf" nogil:
cdef pair[unique_ptr[table], vector[libcudf_types.size_type]] \
hash_partition "cudf::hash_partition" (
const table_view& input,
const vector[libcudf_types.size_type]& columns_to_hash,
int num_partitions
) except +
cdef pair[unique_ptr[table], vector[libcudf_types.size_type]] \
partition "cudf::partition" (
const table_view& t,
const column_view& partition_map,
int num_partitions
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/aggregation.pxd
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libc.stdint cimport int32_t
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from libcpp.vector cimport vector
from cudf._lib.cpp.types cimport (
data_type,
interpolation,
null_order,
null_policy,
order,
size_type,
)
ctypedef int32_t underlying_type_t_correlation_type
ctypedef int32_t underlying_type_t_rank_method
cdef extern from "cudf/aggregation.hpp" namespace "cudf" nogil:
cdef cppclass aggregation:
ctypedef enum Kind:
SUM 'cudf::aggregation::SUM'
PRODUCT 'cudf::aggregation::PRODUCT'
MIN 'cudf::aggregation::MIN'
MAX 'cudf::aggregation::MAX'
COUNT_VALID 'cudf::aggregation::COUNT_VALID'
COUNT_ALL 'cudf::aggregation::COUNT_ALL'
ANY 'cudf::aggregation::ANY'
ALL 'cudf::aggregation::ALL'
SUM_OF_SQUARES 'cudf::aggregation::SUM_OF_SQUARES'
MEAN 'cudf::aggregation::MEAN'
VARIANCE 'cudf::aggregation::VARIANCE'
STD 'cudf::aggregation::STD'
MEDIAN 'cudf::aggregation::MEDIAN'
QUANTILE 'cudf::aggregation::QUANTILE'
ARGMAX 'cudf::aggregation::ARGMAX'
ARGMIN 'cudf::aggregation::ARGMIN'
NUNIQUE 'cudf::aggregation::NUNIQUE'
NTH_ELEMENT 'cudf::aggregation::NTH_ELEMENT'
RANK 'cudf::aggregation::RANK'
COLLECT 'cudf::aggregation::COLLECT_LIST'
COLLECT_SET 'cudf::aggregation::COLLECT_SET'
PTX 'cudf::aggregation::PTX'
CUDA 'cudf::aggregation::CUDA'
CORRELATION 'cudf::aggregation::CORRELATION'
COVARIANCE 'cudf::aggregation::COVARIANCE'
Kind kind
cdef cppclass rolling_aggregation:
aggregation.Kind kind
cdef cppclass groupby_aggregation:
aggregation.Kind kind
cdef cppclass groupby_scan_aggregation:
aggregation.Kind kind
cdef cppclass reduce_aggregation:
aggregation.Kind kind
cdef cppclass scan_aggregation:
aggregation.Kind kind
ctypedef enum udf_type:
CUDA 'cudf::udf_type::CUDA'
PTX 'cudf::udf_type::PTX'
ctypedef enum correlation_type:
PEARSON 'cudf::correlation_type::PEARSON'
KENDALL 'cudf::correlation_type::KENDALL'
SPEARMAN 'cudf::correlation_type::SPEARMAN'
ctypedef enum rank_method:
FIRST "cudf::rank_method::FIRST"
AVERAGE "cudf::rank_method::AVERAGE"
MIN "cudf::rank_method::MIN"
MAX "cudf::rank_method::MAX"
DENSE "cudf::rank_method::DENSE"
ctypedef enum rank_percentage:
NONE "cudf::rank_percentage::NONE"
ZERO_NORMALIZED "cudf::rank_percentage::ZERO_NORMALIZED"
ONE_NORMALIZED "cudf::rank_percentage::ONE_NORMALIZED"
cdef unique_ptr[T] make_sum_aggregation[T]() except +
cdef unique_ptr[T] make_product_aggregation[T]() except +
cdef unique_ptr[T] make_min_aggregation[T]() except +
cdef unique_ptr[T] make_max_aggregation[T]() except +
cdef unique_ptr[T] make_count_aggregation[T]() except +
cdef unique_ptr[T] make_count_aggregation[T](null_policy) except +
cdef unique_ptr[T] make_any_aggregation[T]() except +
cdef unique_ptr[T] make_all_aggregation[T]() except +
cdef unique_ptr[T] make_sum_of_squares_aggregation[T]() except +
cdef unique_ptr[T] make_mean_aggregation[T]() except +
cdef unique_ptr[T] make_variance_aggregation[T](
size_type ddof) except +
cdef unique_ptr[T] make_std_aggregation[T](size_type ddof) except +
cdef unique_ptr[T] make_median_aggregation[T]() except +
cdef unique_ptr[T] make_quantile_aggregation[T](
vector[double] q, interpolation i) except +
cdef unique_ptr[T] make_argmax_aggregation[T]() except +
cdef unique_ptr[T] make_argmin_aggregation[T]() except +
cdef unique_ptr[T] make_nunique_aggregation[T]() except +
cdef unique_ptr[T] make_nth_element_aggregation[T](
size_type n
) except +
cdef unique_ptr[T] make_nth_element_aggregation[T](
size_type n,
null_policy null_handling
) except +
cdef unique_ptr[T] make_collect_list_aggregation[T]() except +
cdef unique_ptr[T] make_collect_set_aggregation[T]() except +
cdef unique_ptr[T] make_udf_aggregation[T](
udf_type type,
string user_defined_aggregator,
data_type output_type) except +
cdef unique_ptr[T] make_correlation_aggregation[T](
correlation_type type, size_type min_periods) except +
cdef unique_ptr[T] make_covariance_aggregation[T](
size_type min_periods, size_type ddof) except +
cdef unique_ptr[T] make_rank_aggregation[T](
rank_method method,
order column_order,
null_policy null_handling,
null_order null_precedence,
rank_percentage percentage) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/rolling.pxd
|
# Copyright (c) 2020, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from cudf._lib.types import cudf_to_np_types, np_to_cudf_types
from cudf._lib.cpp.aggregation cimport rolling_aggregation
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.types cimport size_type
cdef extern from "cudf/rolling.hpp" namespace "cudf" nogil:
cdef unique_ptr[column] rolling_window(
column_view source,
column_view preceding_window,
column_view following_window,
size_type min_periods,
rolling_aggregation agg) except +
cdef unique_ptr[column] rolling_window(
column_view source,
size_type preceding_window,
size_type following_window,
size_type min_periods,
rolling_aggregation agg) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/types.pxd
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libc.stdint cimport int32_t, uint32_t
cdef extern from "cudf/types.hpp" namespace "cudf" nogil:
# The declaration below is to work around
# https://github.com/cython/cython/issues/5637
"""
#define __PYX_ENUM_CLASS_DECL enum
"""
ctypedef int32_t size_type
ctypedef uint32_t bitmask_type
ctypedef uint32_t char_utf8
ctypedef enum mask_state:
UNALLOCATED "cudf::mask_state::UNALLOCATED"
UNINITIALIZED "cudf::mask_state::UNINITIALIZED"
ALL_VALID "cudf::mask_state::ALL_VALID"
ALL_NULL "cudf::mask_state::ALL_NULL"
ctypedef enum order "cudf::order":
ASCENDING "cudf::order::ASCENDING"
DESCENDING "cudf::order::DESCENDING"
ctypedef enum null_order "cudf::null_order":
AFTER "cudf::null_order::AFTER"
BEFORE "cudf::null_order::BEFORE"
ctypedef enum sorted "cudf::sorted":
NO "cudf::sorted::NO"
YES "cudf::sorted::YES"
cdef cppclass order_info:
sorted is_sorted
order ordering
null_order null_ordering
ctypedef enum null_policy "cudf::null_policy":
EXCLUDE "cudf::null_policy::EXCLUDE"
INCLUDE "cudf::null_policy::INCLUDE"
ctypedef enum nan_policy "cudf::nan_policy":
NAN_IS_NULL "cudf::nan_policy::NAN_IS_NULL"
NAN_IS_VALID "cudf::nan_policy::NAN_IS_VALID"
ctypedef enum null_equality "cudf::null_equality":
EQUAL "cudf::null_equality::EQUAL"
UNEQUAL "cudf::null_equality::UNEQUAL"
ctypedef enum nan_equality "cudf::nan_equality":
# These names differ from the C++ names due to Cython warnings if
# "UNEQUAL" is declared by both null_equality and nan_equality.
ALL_EQUAL "cudf::nan_equality::ALL_EQUAL"
NANS_UNEQUAL "cudf::nan_equality::UNEQUAL"
cpdef enum class type_id(int32_t):
EMPTY
INT8
INT16
INT32
INT64
UINT8
UINT16
UINT32
UINT64
FLOAT32
FLOAT64
BOOL8
TIMESTAMP_DAYS
TIMESTAMP_SECONDS
TIMESTAMP_MILLISECONDS
TIMESTAMP_MICROSECONDS
TIMESTAMP_NANOSECONDS
DICTIONARY32
STRING
LIST
STRUCT
NUM_TYPE_IDS
DURATION_SECONDS
DURATION_MILLISECONDS
DURATION_MICROSECONDS
DURATION_NANOSECONDS
DECIMAL32
DECIMAL64
DECIMAL128
cdef cppclass data_type:
data_type() except +
data_type(const data_type&) except +
data_type(type_id id) except +
data_type(type_id id, int32_t scale) except +
type_id id() except +
int32_t scale() except +
cdef extern from "cudf/types.hpp" namespace "cudf" nogil:
ctypedef enum interpolation:
LINEAR "cudf::interpolation::LINEAR"
LOWER "cudf::interpolation::LOWER"
HIGHER "cudf::interpolation::HIGHER"
MIDPOINT "cudf::interpolation::MIDPOINT"
NEAREST "cudf::interpolation::NEAREST"
# A Hack to let cython compile with __int128_t symbol
# https://stackoverflow.com/a/27609033
ctypedef int int128 "__int128_t"
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/reduce.pxd
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport pair
from cudf._lib.cpp.aggregation cimport reduce_aggregation, scan_aggregation
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.types cimport data_type
cdef extern from "cudf/reduction.hpp" namespace "cudf" nogil:
cdef unique_ptr[scalar] cpp_reduce "cudf::reduce" (
column_view col,
const reduce_aggregation& agg,
data_type type
) except +
ctypedef enum scan_type:
INCLUSIVE "cudf::scan_type::INCLUSIVE",
EXCLUSIVE "cudf::scan_type::EXCLUSIVE",
cdef unique_ptr[column] cpp_scan "cudf::scan" (
column_view col,
const scan_aggregation& agg,
scan_type inclusive
) except +
cdef pair[unique_ptr[scalar],
unique_ptr[scalar]] cpp_minmax "cudf::minmax" (
column_view col
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/CMakeLists.txt
|
# =============================================================================
# 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.
# =============================================================================
set(cython_sources copying.pyx types.pyx)
set(linked_libraries cudf::cudf)
rapids_cython_create_modules(
CXX
SOURCE_FILES "${cython_sources}"
LINKED_LIBRARIES "${linked_libraries}" ASSOCIATED_TARGETS cudf MODULE_PREFIX cpp
)
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/round.pxd
|
# Copyright (c) 2021, NVIDIA CORPORATION.
from libc.stdint cimport int32_t
from libcpp.memory cimport unique_ptr
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
cdef extern from "cudf/round.hpp" namespace "cudf" nogil:
ctypedef enum rounding_method "cudf::rounding_method":
HALF_UP "cudf::rounding_method::HALF_UP"
HALF_EVEN "cudf::rounding_method::HALF_EVEN"
cdef unique_ptr[column] round (
const column_view& input,
int32_t decimal_places,
rounding_method method,
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/binaryop.pxd
|
# Copyright (c) 2020-2022, NVIDIA CORPORATION.
from libcpp.memory cimport unique_ptr
from libcpp.string cimport string
from cudf._lib.cpp.column.column cimport column
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.scalar.scalar cimport scalar
from cudf._lib.cpp.types cimport data_type
cdef extern from "cudf/binaryop.hpp" namespace "cudf" nogil:
ctypedef enum binary_operator:
ADD "cudf::binary_operator::ADD"
SUB "cudf::binary_operator::SUB"
MUL "cudf::binary_operator::MUL"
DIV "cudf::binary_operator::DIV"
TRUE_DIV "cudf::binary_operator::TRUE_DIV"
FLOOR_DIV "cudf::binary_operator::FLOOR_DIV"
MOD "cudf::binary_operator::MOD"
PYMOD "cudf::binary_operator::PYMOD"
POW "cudf::binary_operator::POW"
INT_POW "cudf::binary_operator::INT_POW"
EQUAL "cudf::binary_operator::EQUAL"
NOT_EQUAL "cudf::binary_operator::NOT_EQUAL"
LESS "cudf::binary_operator::LESS"
GREATER "cudf::binary_operator::GREATER"
LESS_EQUAL "cudf::binary_operator::LESS_EQUAL"
GREATER_EQUAL "cudf::binary_operator::GREATER_EQUAL"
NULL_EQUALS "cudf::binary_operator::NULL_EQUALS"
BITWISE_AND "cudf::binary_operator::BITWISE_AND"
BITWISE_OR "cudf::binary_operator::BITWISE_OR"
BITWISE_XOR "cudf::binary_operator::BITWISE_XOR"
LOGICAL_AND "cudf::binary_operator::LOGICAL_AND"
LOGICAL_OR "cudf::binary_operator::LOGICAL_OR"
GENERIC_BINARY "cudf::binary_operator::GENERIC_BINARY"
cdef unique_ptr[column] binary_operation (
const scalar& lhs,
const column_view& rhs,
binary_operator op,
data_type output_type
) except +
cdef unique_ptr[column] binary_operation (
const column_view& lhs,
const scalar& rhs,
binary_operator op,
data_type output_type
) except +
cdef unique_ptr[column] binary_operation (
const column_view& lhs,
const column_view& rhs,
binary_operator op,
data_type output_type
) except +
cdef unique_ptr[column] binary_operation (
const column_view& lhs,
const column_view& rhs,
const string& op,
data_type output_type
) except +
unique_ptr[column] jit_binary_operation \
"cudf::jit::binary_operation" (
const column_view& lhs,
const column_view& rhs,
binary_operator op,
data_type output_type
) except +
unique_ptr[column] jit_binary_operation \
"cudf::jit::binary_operation" (
const column_view& lhs,
const scalar& rhs,
binary_operator op,
data_type output_type
) except +
unique_ptr[column] jit_binary_operation \
"cudf::jit::binary_operation" (
const scalar& lhs,
const column_view& rhs,
binary_operator op,
data_type output_type
) except +
| 0 |
rapidsai_public_repos/cudf/python/cudf/cudf/_lib
|
rapidsai_public_repos/cudf/python/cudf/cudf/_lib/cpp/stream_compaction.pxd
|
# Copyright (c) 2020-2023, NVIDIA CORPORATION.
from libcpp cimport bool
from libcpp.memory cimport unique_ptr
from libcpp.vector cimport vector
from cudf._lib.types import cudf_to_np_types, np_to_cudf_types
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport (
nan_policy,
null_equality,
null_policy,
size_type,
)
cdef extern from "cudf/stream_compaction.hpp" namespace "cudf" \
nogil:
ctypedef enum duplicate_keep_option:
KEEP_ANY 'cudf::duplicate_keep_option::KEEP_ANY'
KEEP_FIRST 'cudf::duplicate_keep_option::KEEP_FIRST'
KEEP_LAST 'cudf::duplicate_keep_option::KEEP_LAST'
KEEP_NONE 'cudf::duplicate_keep_option::KEEP_NONE'
cdef unique_ptr[table] drop_nulls(table_view source_table,
vector[size_type] keys,
size_type keep_threshold) except +
cdef unique_ptr[table] apply_boolean_mask(
table_view source_table,
column_view boolean_mask
) except +
cdef size_type distinct_count(
column_view source_table,
null_policy null_handling,
nan_policy nan_handling) except +
cdef unique_ptr[table] stable_distinct(
table_view input,
vector[size_type] keys,
duplicate_keep_option keep,
null_equality nulls_equal,
) except +
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.