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/api/types.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. """Define common type operations.""" from __future__ import annotations from collections import abc from functools import wraps from inspect import isclass from typing import List, Union import cupy as cp import numpy as np import pandas as pd from pandas.api import types as pd_types import cudf from cudf.core.dtypes import ( # noqa: F401 _BaseDtype, dtype, is_categorical_dtype, is_decimal32_dtype, is_decimal64_dtype, is_decimal128_dtype, is_decimal_dtype, is_interval_dtype, is_list_dtype, is_struct_dtype, ) def is_numeric_dtype(obj): """Check whether the provided array or dtype is of a numeric dtype. Parameters ---------- obj : array-like or dtype The array or dtype to check. Returns ------- bool Whether or not the array or dtype is of a numeric dtype. """ if isclass(obj): if issubclass(obj, cudf.core.dtypes.DecimalDtype): return True if issubclass(obj, _BaseDtype): return False else: if isinstance( obj, (cudf.Decimal128Dtype, cudf.Decimal64Dtype, cudf.Decimal32Dtype), ) or isinstance( getattr(obj, "dtype", None), (cudf.Decimal128Dtype, cudf.Decimal64Dtype, cudf.Decimal32Dtype), ): return True if isinstance(obj, _BaseDtype) or isinstance( getattr(obj, "dtype", None), _BaseDtype ): return False if isinstance(obj, cudf.BaseIndex): return obj._is_numeric() return pd_types.is_numeric_dtype(obj) # A version of numerical type check that does not include cudf decimals for # places where we need to distinguish fixed and floating point numbers. def _is_non_decimal_numeric_dtype(obj): if isinstance(obj, _BaseDtype) or isinstance( getattr(obj, "dtype", None), _BaseDtype ): return False try: return pd_types.is_numeric_dtype(obj) except TypeError: return False def is_integer(obj): """Return True if given object is integer. Returns ------- bool """ if isinstance(obj, cudf.Scalar): return pd.api.types.is_integer_dtype(obj.dtype) return pd.api.types.is_integer(obj) def is_string_dtype(obj): """Check whether the provided array or dtype is of the string dtype. Parameters ---------- obj : array-like or dtype The array or dtype to check. Returns ------- bool Whether or not the array or dtype is of the string dtype. """ return ( pd.api.types.is_string_dtype(obj) # Reject all cudf extension types. and not is_categorical_dtype(obj) and not is_decimal_dtype(obj) and not is_list_dtype(obj) and not is_struct_dtype(obj) and not is_interval_dtype(obj) ) def is_scalar(val): """Return True if given object is scalar. Parameters ---------- val : object Possibly scalar object. Returns ------- bool Return True if given object is scalar. """ return isinstance( val, ( cudf.Scalar, cudf._lib.scalar.DeviceScalar, cudf.core.tools.datetimes.DateOffset, ), ) or pd_types.is_scalar(val) def _is_scalar_or_zero_d_array(val): """Return True if given object is scalar or a 0d array. This is an internal function primarily used by indexing applications that need to flatten dimensions that are indexed by 0d arrays. Parameters ---------- val : object Possibly scalar object. Returns ------- bool Return True if given object is scalar. """ return ( isinstance(val, (np.ndarray, cp.ndarray)) and val.ndim == 0 ) or is_scalar(val) # TODO: We should be able to reuse the pandas function for this, need to figure # out why we can't. def is_list_like(obj): """Return `True` if the given `obj` is list-like (list, tuple, Series...). Parameters ---------- obj : object of any type which needs to be validated. Returns ------- bool Return True if given object is list-like. """ return isinstance(obj, (abc.Sequence, np.ndarray)) and not isinstance( obj, (str, bytes) ) # These methods are aliased directly into this namespace, but can be modified # later if we determine that there is a need. def _wrap_pandas_is_dtype_api(func): """Wrap a pandas dtype checking function to ignore cudf types.""" @wraps(func) def wrapped_func(obj): if ( (isclass(obj) and issubclass(obj, _BaseDtype)) or isinstance(obj, _BaseDtype) or isinstance(getattr(obj, "dtype", None), _BaseDtype) ): return False return func(obj) return wrapped_func def _union_categoricals( to_union: List[Union[cudf.Series, cudf.CategoricalIndex]], sort_categories: bool = False, ignore_order: bool = False, ): """Combine categorical data. This API is currently internal but should be exposed once full support for cudf.Categorical is ready. """ # TODO(s) in the order specified : # 1. The return type needs to be changed # to cudf.Categorical once it is implemented. # 2. Make this API public (i.e., to resemble # pd.api.types.union_categoricals) if ignore_order: raise TypeError("ignore_order is not yet implemented") result_col = cudf.core.column.CategoricalColumn._concat( [obj._column for obj in to_union] ) if sort_categories: sorted_categories = result_col.categories.sort_values(ascending=True) result_col = result_col.reorder_categories( new_categories=sorted_categories ) return cudf.Index(result_col) def is_bool_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like or dtype The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a boolean dtype. Examples -------- >>> from cudf.api.types import is_bool_dtype >>> import numpy as np >>> import cudf >>> is_bool_dtype(str) False >>> is_bool_dtype(int) False >>> is_bool_dtype(bool) True >>> is_bool_dtype(np.bool_) True >>> is_bool_dtype(np.array(['a', 'b'])) False >>> is_bool_dtype(cudf.Series([1, 2])) False >>> is_bool_dtype(np.array([True, False])) True >>> is_bool_dtype(cudf.Series([True, False], dtype='category')) True """ if isinstance(arr_or_dtype, cudf.BaseIndex): return arr_or_dtype._is_boolean() elif isinstance(arr_or_dtype, cudf.Series): if isinstance(arr_or_dtype.dtype, cudf.CategoricalDtype): return is_bool_dtype(arr_or_dtype=arr_or_dtype.dtype) else: return pd_types.is_bool_dtype(arr_or_dtype=arr_or_dtype.dtype) elif isinstance(arr_or_dtype, cudf.CategoricalDtype): return pd_types.is_bool_dtype( arr_or_dtype=arr_or_dtype.categories.dtype ) else: return pd_types.is_bool_dtype(arr_or_dtype=arr_or_dtype) def is_object_dtype(arr_or_dtype): """ Check whether an array-like or dtype is of the object dtype. Parameters ---------- arr_or_dtype : array-like or dtype The array-like or dtype to check. Returns ------- boolean Whether or not the array-like or dtype is of the object dtype. Examples -------- >>> from cudf.api.types import is_object_dtype >>> import numpy as np >>> is_object_dtype(object) True >>> is_object_dtype(int) False >>> is_object_dtype(np.array([], dtype=object)) True >>> is_object_dtype(np.array([], dtype=int)) False >>> is_object_dtype([1, 2, 3]) False """ if isinstance(arr_or_dtype, cudf.BaseIndex): return arr_or_dtype._is_object() elif isinstance(arr_or_dtype, cudf.Series): return pd_types.is_object_dtype(arr_or_dtype=arr_or_dtype.dtype) else: return pd_types.is_object_dtype(arr_or_dtype=arr_or_dtype) def is_float_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of a float dtype. Parameters ---------- arr_or_dtype : array-like or dtype The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a float dtype. Examples -------- >>> from cudf.api.types import is_float_dtype >>> import numpy as np >>> import cudf >>> is_float_dtype(str) False >>> is_float_dtype(int) False >>> is_float_dtype(float) True >>> is_float_dtype(np.array(['a', 'b'])) False >>> is_float_dtype(cudf.Series([1, 2])) False >>> is_float_dtype(cudf.Index([1, 2.])) True """ if isinstance(arr_or_dtype, cudf.BaseIndex): return arr_or_dtype._is_floating() return _wrap_pandas_is_dtype_api(pd_types.is_float_dtype)(arr_or_dtype) def is_integer_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of an integer dtype. Unlike in `is_any_int_dtype`, timedelta64 instances will return False. Parameters ---------- arr_or_dtype : array-like or dtype The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of an integer dtype and not an instance of timedelta64. Examples -------- >>> from cudf.api.types import is_integer_dtype >>> import numpy as np >>> import cudf >>> is_integer_dtype(str) False >>> is_integer_dtype(int) True >>> is_integer_dtype(float) False >>> is_integer_dtype(np.uint64) True >>> is_integer_dtype('int8') True >>> is_integer_dtype('Int8') True >>> is_integer_dtype(np.datetime64) False >>> is_integer_dtype(np.timedelta64) False >>> is_integer_dtype(np.array(['a', 'b'])) False >>> is_integer_dtype(cudf.Series([1, 2])) True >>> is_integer_dtype(np.array([], dtype=np.timedelta64)) False >>> is_integer_dtype(cudf.Index([1, 2.])) # float False """ if isinstance(arr_or_dtype, cudf.BaseIndex): return arr_or_dtype._is_integer() return _wrap_pandas_is_dtype_api(pd_types.is_integer_dtype)(arr_or_dtype) def is_any_real_numeric_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of a real number dtype. Parameters ---------- arr_or_dtype : array-like or dtype The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a real number dtype. Examples -------- >>> from cudf.api.types import is_any_real_numeric_dtype >>> import cudf >>> is_any_real_numeric_dtype(int) True >>> is_any_real_numeric_dtype(float) True >>> is_any_real_numeric_dtype(object) False >>> is_any_real_numeric_dtype(str) False >>> is_any_real_numeric_dtype(complex(1, 2)) False >>> is_any_real_numeric_dtype(bool) False >>> is_any_real_numeric_dtype(cudf.Index([1, 2, 3])) True """ return ( is_numeric_dtype(arr_or_dtype) and not is_complex_dtype(arr_or_dtype) and not is_bool_dtype(arr_or_dtype) ) def _is_pandas_nullable_extension_dtype(dtype_to_check): if isinstance( dtype_to_check, pd.api.extensions.ExtensionDtype ) and not isinstance(dtype_to_check, pd.core.dtypes.dtypes.PandasDtype): if isinstance(dtype_to_check, pd.CategoricalDtype): return _is_pandas_nullable_extension_dtype( dtype_to_check.categories.dtype ) return True return False # TODO: The below alias is removed for now since improving cudf categorical # support is ongoing and we don't want to introduce any ambiguities. The above # method _union_categoricals will take its place once exposed. # union_categoricals = pd_types.union_categoricals infer_dtype = pd_types.infer_dtype pandas_dtype = pd_types.pandas_dtype is_complex_dtype = pd_types.is_complex_dtype # TODO: Evaluate which of the datetime types need special handling for cudf. is_datetime_dtype = _wrap_pandas_is_dtype_api(pd_types.is_datetime64_dtype) is_datetime64_any_dtype = pd_types.is_datetime64_any_dtype is_datetime64_dtype = _wrap_pandas_is_dtype_api(pd_types.is_datetime64_dtype) is_datetime64_ns_dtype = _wrap_pandas_is_dtype_api( pd_types.is_datetime64_ns_dtype ) is_datetime64tz_dtype = _wrap_pandas_is_dtype_api( pd_types.is_datetime64tz_dtype ) is_extension_type = pd_types.is_extension_type is_extension_array_dtype = pd_types.is_extension_array_dtype is_int64_dtype = pd_types.is_int64_dtype is_period_dtype = pd_types.is_period_dtype is_signed_integer_dtype = pd_types.is_signed_integer_dtype is_timedelta_dtype = _wrap_pandas_is_dtype_api(pd_types.is_timedelta64_dtype) is_timedelta64_dtype = _wrap_pandas_is_dtype_api(pd_types.is_timedelta64_dtype) is_timedelta64_ns_dtype = _wrap_pandas_is_dtype_api( pd_types.is_timedelta64_ns_dtype ) is_unsigned_integer_dtype = pd_types.is_unsigned_integer_dtype is_sparse = pd_types.is_sparse # is_list_like = pd_types.is_list_like is_dict_like = pd_types.is_dict_like is_file_like = pd_types.is_file_like is_named_tuple = pd_types.is_named_tuple is_iterator = pd_types.is_iterator is_bool = pd_types.is_bool is_categorical = pd_types.is_categorical is_complex = pd_types.is_complex is_float = pd_types.is_float is_hashable = pd_types.is_hashable is_interval = pd_types.is_interval is_number = pd_types.is_number is_re = pd_types.is_re is_re_compilable = pd_types.is_re_compilable is_dtype_equal = pd_types.is_dtype_equal # Aliases of numpy dtype functionality. issubdtype = np.issubdtype
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/api/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. from cudf.api import extensions, types __all__ = ["extensions", "types"]
0
rapidsai_public_repos/cudf/python/cudf/cudf/api
rapidsai_public_repos/cudf/python/cudf/cudf/api/extensions/accessor.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import warnings from pandas.core.accessor import CachedAccessor import cudf from cudf.utils.docutils import docfmt_partial _docstring_register_accessor = """ Extends `cudf.{klass}` with custom defined accessor Parameters ---------- name : str The name to be registered in `{klass}` for the custom accessor Returns ------- decorator : callable Decorator function for accessor Notes ----- The `{klass}` object will be passed to your custom accessor upon first invocation. And will be cached for future calls. If the data passed to your accessor is of wrong datatype, you should raise an `AttributeError` in consistent with other cudf methods. Examples -------- {example} """ _dataframe_example = """ In your library code: >>> import cudf as gd >>> @gd.api.extensions.register_dataframe_accessor("point") ... class PointsAccessor: ... def __init__(self, obj): ... self._validate(obj) ... self._obj = obj ... @staticmethod ... def _validate(obj): ... cols = obj.columns ... if not all([vertex in cols for vertex in ["x", "y"]]): ... raise AttributeError("Must have vertices 'x', 'y'.") ... @property ... def bounding_box(self): ... xs, ys = self._obj["x"], self._obj["y"] ... min_x, min_y = xs.min(), ys.min() ... max_x, max_y = xs.max(), ys.max() ... return (min_x, min_y, max_x, max_y) Then in user code: >>> df = gd.DataFrame({'x': [1,2,3,4,5,6], 'y':[7,6,5,4,3,2]}) >>> df.point.bounding_box (1, 2, 6, 7) """ _index_example = """ In your library code: >>> import cudf as gd >>> @gd.api.extensions.register_index_accessor("odd") ... class OddRowAccessor: ... def __init__(self, obj): ... self._obj = obj ... def __getitem__(self, i): ... return self._obj[2 * i - 1] Then in user code: >>> gs = gd.Index(list(range(0, 50))) >>> gs.odd[1] 1 >>> gs.odd[2] 3 >>> gs.odd[3] 5 """ _series_example = """ In your library code: >>> import cudf as gd >>> @gd.api.extensions.register_series_accessor("odd") ... class OddRowAccessor: ... def __init__(self, obj): ... self._obj = obj ... def __getitem__(self, i): ... return self._obj[2 * i - 1] Then in user code: >>> gs = gd.Series(list(range(0, 50))) >>> gs.odd[1] 1 >>> gs.odd[2] 3 >>> gs.odd[3] 5 """ doc_register_dataframe_accessor = docfmt_partial( docstring=_docstring_register_accessor.format( klass="DataFrame", example=_dataframe_example ) ) doc_register_index_accessor = docfmt_partial( docstring=_docstring_register_accessor.format( klass="Index", example=_index_example ) ) doc_register_series_accessor = docfmt_partial( docstring=_docstring_register_accessor.format( klass="Series", example=_series_example ) ) def _register_accessor(name, cls): def decorator(accessor): if hasattr(cls, name): msg = f"Attribute {name} will be overridden in {cls.__name__}" warnings.warn(msg) cached_accessor = CachedAccessor(name, accessor) cls._accessors.add(name) setattr(cls, name, cached_accessor) return accessor return decorator @doc_register_dataframe_accessor() def register_dataframe_accessor(name): """{docstring}""" return _register_accessor(name, cudf.DataFrame) @doc_register_index_accessor() def register_index_accessor(name): """{docstring}""" return _register_accessor(name, cudf.BaseIndex) @doc_register_series_accessor() def register_series_accessor(name): """{docstring}""" return _register_accessor(name, cudf.Series)
0
rapidsai_public_repos/cudf/python/cudf/cudf/api
rapidsai_public_repos/cudf/python/cudf/cudf/api/extensions/__init__.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from pandas.api.extensions import no_default from cudf.api.extensions.accessor import ( register_dataframe_accessor, register_index_accessor, register_series_accessor, ) __all__ = [ "no_default", "register_dataframe_accessor", "register_index_accessor", "register_series_accessor", ]
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/orc.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import copy import io import logging import random import numpy as np import pyarrow as pa import cudf from cudf._fuzz_testing.io import IOFuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, _generate_rand_meta, pyarrow_to_pandas, ) from cudf.testing import dataset_generator as dg logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class OrcReader(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) self._df = None def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: dtypes_list = list( cudf.utils.dtypes.ALL_TYPES - {"category"} # Following dtypes are not supported by orc # https://orc.apache.org/specification/ORCv0/ - cudf.utils.dtypes.TIMEDELTA_TYPES - cudf.utils.dtypes.UNSIGNED_TYPES - {"datetime64[ns]"} ) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta seed = random.randint(0, 2**32 - 1) self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_cols"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {table.shape}") self._df = df file_obj = io.BytesIO() pa.orc.write_table(table, file_obj, stripe_size=self._rand(len(df))) file_obj.seek(0) buf = file_obj.read() self._current_buffer = copy.copy(buf) return (df, buf) def write_data(self, file_name): if self._current_buffer is not None: with open(file_name + "_crash.orc", "wb") as crash_dataset: crash_dataset.write(self._current_buffer) def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if values == ALL_POSSIBLE_VALUES: if param == "columns": col_size = self._rand(len(self._df.columns)) params_dict[param] = list( np.unique(np.random.choice(self._df.columns, col_size)) ) elif param == "stripes": f = io.BytesIO(self._current_buffer) orcFile = pa.orc.ORCFile(f) stripes = list(range(orcFile.nstripes)) params_dict[param] = np.random.choice( [ None, list( map( int, np.unique( np.random.choice( stripes, orcFile.nstripes ) ), ) ), ] ) elif param == "use_index": params_dict[param] = np.random.choice([True, False]) elif param in ("skiprows", "num_rows"): params_dict[param] = np.random.choice( [None, self._rand(len(self._df))] ) else: if not isinstance(values, list): raise TypeError("values must be of type list") params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict) class OrcWriter(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) self._df = None def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: dtypes_list = list( cudf.utils.dtypes.ALL_TYPES # TODO: Remove "bool" from below # list after following issue is fixed: # https://github.com/rapidsai/cudf/issues/6763 - {"category", "bool"} # Following dtypes are not supported by orc # https://orc.apache.org/specification/ORCv0/ - cudf.utils.dtypes.TIMEDELTA_TYPES - cudf.utils.dtypes.UNSIGNED_TYPES # TODO: Remove `DATETIME_TYPES` once # following bug is fixed: # https://github.com/rapidsai/cudf/issues/7355 - cudf.utils.dtypes.DATETIME_TYPES ) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta seed = random.randint(0, 2**32 - 1) self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_cols"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {table.shape}") self._df = df return df def write_data(self, file_name): # Due to the lack of really fast reference writer we are dumping # the dataframe to a parquet file if self._df is not None: self._df.to_parquet(file_name + "_crash.parquet")
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/avro.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import copy import io import logging import random import numpy as np import cudf from cudf._fuzz_testing.io import IOFuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, _generate_rand_meta, pandas_to_avro, pyarrow_to_pandas, ) from cudf.testing import dataset_generator as dg logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class AvroReader(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) self._df = None def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: dtypes_list = list( cudf.utils.dtypes.ALL_TYPES - {"category"} # No unsigned support in avro: # https://avro.apache.org/docs/current/spec.html - cudf.utils.dtypes.UNSIGNED_TYPES # TODO: Remove DATETIME_TYPES once # following bug is fixed: # https://github.com/rapidsai/cudf/issues/6482 - cudf.utils.dtypes.DATETIME_TYPES # TODO: Remove DURATION_TYPES once # following bug is fixed: # https://github.com/rapidsai/cudf/issues/6604 - cudf.utils.dtypes.TIMEDELTA_TYPES ) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta seed = random.randint(0, 2**32 - 1) self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_cols"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) self._df = df logging.info(f"Shape of DataFrame generated: {table.shape}") file_obj = io.BytesIO() pandas_to_avro(df, file_io_obj=file_obj) file_obj.seek(0) buf = file_obj.read() self._current_buffer = copy.copy(buf) return (df, buf) def write_data(self, file_name): if self._current_buffer is not None: with open(file_name + "_crash.avro", "wb") as crash_dataset: crash_dataset.write(self._current_buffer) def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if values == ALL_POSSIBLE_VALUES: if param == "columns": col_size = self._rand(len(self._df.columns)) params_dict[param] = list( np.unique(np.random.choice(self._df.columns, col_size)) ) elif param in ("skiprows", "num_rows"): params_dict[param] = np.random.choice( [None, self._rand(len(self._df))] ) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/csv.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import logging import random import numpy as np import cudf from cudf._fuzz_testing.io import IOFuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, _generate_rand_meta, pyarrow_to_pandas, ) from cudf.testing import dataset_generator as dg from cudf.utils.dtypes import pandas_dtypes_to_np_dtypes logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class CSVReader(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: seed = random.randint(0, 2**32 - 1) random.seed(seed) dtypes_list = list(cudf.utils.dtypes.ALL_TYPES) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_columns"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {df.shape}") self._current_buffer = df return df.to_csv() def write_data(self, file_name): if self._current_buffer is not None: self._current_buffer.to_csv(file_name + "_crash.csv") def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if values == ALL_POSSIBLE_VALUES: if param == "usecols": col_size = self._rand(len(self._df.columns)) col_val = np.random.choice( [ None, np.unique( np.random.choice(self._df.columns, col_size) ), ] ) params_dict[param] = ( col_val if col_val is None else list(col_val) ) elif param == "dtype": dtype_val = np.random.choice( [None, self._df.dtypes.to_dict()] ) if dtype_val is not None: dtype_val = { col_name: "category" if cudf.utils.dtypes.is_categorical_dtype(dtype) else pandas_dtypes_to_np_dtypes[dtype] for col_name, dtype in dtype_val.items() } params_dict[param] = dtype_val elif param == "header": header_val = np.random.choice( ["infer", np.random.randint(low=0, high=len(self._df))] ) params_dict[param] = header_val elif param == "skiprows": params_dict[param] = np.random.randint( low=0, high=len(self._df) ) elif param == "skipfooter": params_dict[param] = np.random.randint( low=0, high=len(self._df) ) elif param == "nrows": nrows_val = np.random.choice( [None, np.random.randint(low=0, high=len(self._df))] ) params_dict[param] = nrows_val else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict) class CSVWriter(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: seed = random.randint(0, 2**32 - 1) random.seed(seed) dtypes_list = list(cudf.utils.dtypes.ALL_TYPES) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_columns"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {df.shape}") self._current_buffer = df return df def write_data(self, file_name): if self._current_buffer is not None: self._current_buffer.to_csv(file_name + "_crash.csv") def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if values == ALL_POSSIBLE_VALUES: if param == "columns": col_size = self._rand(len(self._current_buffer.columns)) params_dict[param] = list( np.unique( np.random.choice( self._current_buffer.columns, col_size ) ) ) elif param == "chunksize": params_dict[param] = np.random.choice( [ None, np.random.randint( low=1, high=max(1, len(self._current_buffer)) ), ] ) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/parquet.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import logging import random import numpy as np import cudf from cudf._fuzz_testing.io import IOFuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, _generate_rand_meta, pyarrow_to_pandas, ) from cudf.testing import dataset_generator as dg logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class ParquetReader(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) self._df = None def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: dtypes_list = list( cudf.utils.dtypes.ALL_TYPES - {"category", "datetime64[ns]"} - cudf.utils.dtypes.TIMEDELTA_TYPES # TODO: Remove uint32 below after this bug is fixed # https://github.com/pandas-dev/pandas/issues/37327 - {"uint32"} | {"list", "decimal64"} ) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta seed = random.randint(0, 2**32 - 1) self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_cols"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {table.shape}") # TODO: Change this to write into # a BytesIO object once below issue is fixed # https://issues.apache.org/jira/browse/ARROW-10123 # file = io.BytesIO() df.to_parquet("temp_file") # file.seek(0) # self._current_buffer = copy.copy(file.read()) # return self._current_buffer self._df = df return "temp_file" def write_data(self, file_name): if self._current_buffer is not None: with open(file_name + "_crash.parquet", "wb") as crash_dataset: crash_dataset.write(self._current_buffer) def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if param == "columns" and values == ALL_POSSIBLE_VALUES: col_size = self._rand(len(self._df.columns)) params_dict[param] = list( np.unique(np.random.choice(self._df.columns, col_size)) ) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict) class ParquetWriter(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: seed = random.randint(0, 2**32 - 1) random.seed(seed) dtypes_list = list( cudf.utils.dtypes.ALL_TYPES - {"category", "timedelta64[ns]", "datetime64[ns]"} # TODO: Remove uint32 below after this bug is fixed # https://github.com/pandas-dev/pandas/issues/37327 - {"uint32"} | {"list", "decimal64"} ) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_columns"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {df.shape}") self._current_buffer = df return df def write_data(self, file_name): if self._current_buffer is not None: self._current_buffer.to_parquet(file_name + "_crash.parquet")
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/json.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import logging import random from collections import abc import numpy as np import cudf from cudf._fuzz_testing.io import IOFuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, _generate_rand_meta, pyarrow_to_pandas, ) from cudf.testing import dataset_generator as dg from cudf.utils.dtypes import pandas_dtypes_to_np_dtypes logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) def _get_dtype_param_value(dtype_val): if dtype_val is not None and isinstance(dtype_val, abc.Mapping): processed_dtypes = {} for col_name, dtype in dtype_val.items(): if cudf.utils.dtypes.is_categorical_dtype(dtype): processed_dtypes[col_name] = "category" else: processed_dtypes[col_name] = str( pandas_dtypes_to_np_dtypes.get(dtype, dtype) ) return processed_dtypes return dtype_val class JSONReader(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: seed = random.randint(0, 2**32 - 1) random.seed(seed) dtypes_list = list( cudf.utils.dtypes.ALL_TYPES # https://github.com/pandas-dev/pandas/issues/20599 - {"uint64"} # TODO: Remove DATETIME_TYPES after this is fixed: # https://github.com/rapidsai/cudf/issues/6586 - set(cudf.utils.dtypes.DATETIME_TYPES) ) # TODO: Uncomment following after following # issue is fixed: # https://github.com/rapidsai/cudf/issues/7086 # dtypes_list.extend(["list"]) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_columns"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) self._current_buffer = df logging.info(f"Shape of DataFrame generated: {df.shape}") return df.to_json(orient="records", lines=True) def write_data(self, file_name): if self._current_buffer is not None: self._current_buffer.to_json( file_name + "_crash_json.json", orient="records", lines=True ) def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if param == "dtype" and values == ALL_POSSIBLE_VALUES: dtype_val = np.random.choice( [True, self._current_buffer.dtypes.to_dict()] ) params_dict[param] = _get_dtype_param_value(dtype_val) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict) class JSONWriter(IOFuzz): def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, ): super().__init__( dirs=dirs, max_rows=max_rows, max_columns=max_columns, max_string_length=max_string_length, ) def generate_input(self): if self._regression: ( dtypes_meta, num_rows, num_cols, seed, ) = self.get_next_regression_params() else: seed = random.randint(0, 2**32 - 1) random.seed(seed) dtypes_list = list( cudf.utils.dtypes.ALL_TYPES # https://github.com/pandas-dev/pandas/issues/20599 - {"uint64"} # TODO: Remove DATETIME_TYPES after this is fixed: # https://github.com/rapidsai/cudf/issues/6586 - set(cudf.utils.dtypes.DATETIME_TYPES) ) # TODO: Uncomment following after following # issue is fixed: # https://github.com/rapidsai/cudf/issues/7086 # dtypes_list.extend(["list"]) dtypes_meta, num_rows, num_cols = _generate_rand_meta( self, dtypes_list ) self._current_params["dtypes_meta"] = dtypes_meta self._current_params["seed"] = seed self._current_params["num_rows"] = num_rows self._current_params["num_columns"] = num_cols logging.info( f"Generating DataFrame with rows: {num_rows} " f"and columns: {num_cols}" ) table = dg.rand_dataframe(dtypes_meta, num_rows, seed) df = pyarrow_to_pandas(table) logging.info(f"Shape of DataFrame generated: {df.shape}") self._current_buffer = df return df def write_data(self, file_name): if self._current_buffer is not None: self._current_buffer.to_json( file_name + "_crash_json.json", lines=True, orient="records" ) def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if param == "dtype" and values == ALL_POSSIBLE_VALUES: dtype_val = np.random.choice( [True, self._current_buffer.dtypes.to_dict()] ) params_dict[param] = _get_dtype_param_value(dtype_val) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/io.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import copy import json import logging import os import random import sys import numpy as np logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class IOFuzz: def __init__( self, dirs=None, max_rows=100_000, max_columns=1000, max_string_length=None, max_lists_length=None, max_lists_nesting_depth=None, max_structs_nesting_depth=None, max_struct_null_frequency=None, max_struct_types_at_each_level=None, ): dirs = [] if dirs is None else dirs self._inputs = [] self._max_rows = max_rows self._max_columns = max_columns self._max_string_length = max_string_length self._max_lists_length = max_lists_length self._max_lists_nesting_depth = max_lists_nesting_depth self._max_structs_nesting_depth = max_structs_nesting_depth self._max_struct_null_frequency = max_struct_null_frequency self._max_struct_types_at_each_level = max_struct_types_at_each_level for i, path in enumerate(dirs): if i == 0 and not os.path.exists(path): raise FileNotFoundError(f"No {path} exists") if os.path.isfile(path) and path.endswith("_crash.json"): self._load_params(path) else: for i in os.listdir(path): file_name = os.path.join(path, i) if os.path.isfile(file_name) and file_name.endswith( "_crash.json" ): self._load_params(file_name) self._regression = bool(self._inputs) self._idx = 0 self._current_params = {} self._current_buffer = None def _load_params(self, path): with open(path) as f: params = json.load(f) self._inputs.append(params) @staticmethod def _rand(n): return random.randrange(0, n + 1) def generate_input(self): raise NotImplementedError("Must be implemented by inherited class") @property def current_params(self): return self._current_params def get_next_regression_params(self): if self._idx >= len(self._inputs): logging.info( "Reached the end of all crash.json files to run..Exiting.." ) sys.exit(0) param = self._inputs[self._idx] dtypes_meta = param["dtypes_meta"] num_rows = param["num_rows"] num_cols = param["num_columns"] seed = param["seed"] random.seed(seed) self._idx += 1 self._current_params = copy.copy(param) return dtypes_meta, num_rows, num_cols, seed def set_rand_params(self, params): params_dict = { param: np.random.choice(values) for param, values in params.items() } self._current_params["test_kwargs"] = self.process_kwargs( params_dict=params_dict ) def process_kwargs(self, params_dict): return { key: bool(value) if isinstance(value, np.bool_) else str(value) if isinstance(value, np.dtype) else value for key, value in params_dict.items() }
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/fuzzer.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import datetime import json import logging import os import sys import traceback logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) class Fuzzer: def __init__( self, target, data_handler_class, dirs=None, crash_reports_dir=None, regression=False, max_rows_size=100_000, max_cols_size=1000, runs=-1, max_string_length=None, params=None, write_data_on_failure=True, max_lists_length=None, max_lists_nesting_depth=None, ): self._target = target self._dirs = [] if dirs is None else dirs self._crash_dir = crash_reports_dir self._data_handler = data_handler_class( dirs=self._dirs, max_rows=max_rows_size, max_columns=max_cols_size, max_string_length=max_string_length, max_lists_length=max_lists_length, max_lists_nesting_depth=max_lists_nesting_depth, ) self._total_executions = 0 self._regression = regression self._start_time = None self.runs = runs self.params = params self.write_data_on_failure = write_data_on_failure def log_stats(self): end_time = datetime.datetime.now() total_time_taken = end_time - self._start_time logging.info(f"Run-Time elapsed (hh:mm:ss.ms) {total_time_taken}") def write_crash(self, error): error_file_name = str(datetime.datetime.now()) if self._crash_dir: crash_path = os.path.join( self._crash_dir, error_file_name + "_crash.json", ) crash_log_path = os.path.join( self._crash_dir, error_file_name + "_crash.log", ) else: crash_path = error_file_name + "_crash.json" crash_log_path = error_file_name + "_crash.log" with open(crash_path, "w") as f: json.dump( self._data_handler.current_params, f, sort_keys=True, indent=4 ) logging.info(f"Crash params was written to {crash_path}") with open(crash_log_path, "w") as f: f.write(str(error)) logging.info(f"Crash exception was written to {crash_log_path}") if self.write_data_on_failure: self._data_handler.write_data(error_file_name) def start(self): while True: logging.info(f"Running test {self._total_executions}") file_name = self._data_handler.generate_input() try: self._start_time = datetime.datetime.now() if self.params is None: self._target(file_name) else: self._data_handler.set_rand_params(self.params) kwargs = self._data_handler._current_params["test_kwargs"] logging.info(f"Parameters passed: {str(kwargs)}") self._target(file_name, **kwargs) except KeyboardInterrupt: logging.info( f"Keyboard Interrupt encountered, stopping after " f"{self.runs} runs." ) sys.exit(0) except Exception as e: logging.exception(e) self.write_crash(traceback.format_exc()) self.log_stats() if self.runs != -1 and self._total_executions >= self.runs: logging.info(f"Completed {self.runs}, stopping now.") break self._total_executions += 1
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/main.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. from cudf._fuzz_testing import fuzzer class PythonFuzz: def __init__(self, func, params=None, data_handle=None, **kwargs): self.function = func self.data_handler_class = data_handle self.fuzz_worker = fuzzer.Fuzzer( target=self.function, data_handler_class=self.data_handler_class, dirs=kwargs.get("dir", None), crash_reports_dir=kwargs.get("crash_reports_dir", None), regression=kwargs.get("regression", False), max_rows_size=kwargs.get("max_rows_size", 100_000), max_cols_size=kwargs.get("max_cols_size", 1000), runs=kwargs.get("runs", -1), max_string_length=kwargs.get("max_string_length", None), params=params, write_data_on_failure=kwargs.get("write_data_on_failure", True), max_lists_length=kwargs.get("max_lists_length", None), max_lists_nesting_depth=kwargs.get( "max_lists_nesting_depth", None ), ) def __call__(self, *args, **kwargs): self.fuzz_worker.start() # wrap PythonFuzz to allow for deferred calling def pythonfuzz(function=None, data_handle=None, params=None, **kwargs): if function: return PythonFuzz(function, params, **kwargs) else: def wrapper(function): return PythonFuzz(function, params, data_handle, **kwargs) return wrapper if __name__ == "__main__": PythonFuzz(None)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/utils.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import random import fastavro import numpy as np import pandas as pd import pyarrow as pa import cudf from cudf.testing._utils import assert_eq from cudf.utils.dtypes import ( pandas_dtypes_to_np_dtypes, pyarrow_dtypes_to_pandas_dtypes, ) ALL_POSSIBLE_VALUES = "ALL_POSSIBLE_VALUES" _PANDAS_TO_AVRO_SCHEMA_MAP = { cudf.dtype("int8"): "int", pd.Int8Dtype(): ["int", "null"], pd.Int16Dtype(): ["int", "null"], pd.Int32Dtype(): ["int", "null"], pd.Int64Dtype(): ["long", "null"], pd.Float32Dtype(): ["float", "null"], pd.Float64Dtype(): ["double", "null"], pd.BooleanDtype(): ["boolean", "null"], pd.StringDtype(): ["string", "null"], cudf.dtype("bool_"): "boolean", cudf.dtype("int16"): "int", cudf.dtype("int32"): "int", cudf.dtype("int64"): "long", cudf.dtype("O"): "string", cudf.dtype("str"): "string", cudf.dtype("float32"): "float", cudf.dtype("float64"): "double", cudf.dtype("<M8[ns]"): {"type": "long", "logicalType": "timestamp-millis"}, cudf.dtype("<M8[ms]"): {"type": "long", "logicalType": "timestamp-millis"}, cudf.dtype("<M8[us]"): {"type": "long", "logicalType": "timestamp-micros"}, } def _generate_rand_meta(obj, dtypes_list, null_frequency_override=None): obj._current_params = {} num_rows = obj._rand(obj._max_rows) num_cols = obj._rand(obj._max_columns) dtypes_meta = [] for _ in range(num_cols): dtype = random.choice(dtypes_list) null_frequency = ( random.uniform(0, 1) if null_frequency_override is None else null_frequency_override ) # `cardinality` has to be at least 1. cardinality = max(1, obj._rand(obj._max_rows)) meta = dict() if dtype == "str": # We want to operate near the limits of string column # Hence creating a string column of size almost # equal to 2 Billion bytes(sizeof(int)) if obj._max_string_length is None: meta["max_string_length"] = random.randrange( 0, int(2000000000 / num_rows) ) else: meta["max_string_length"] = obj._max_string_length elif dtype == "list": if obj._max_lists_length is None: meta["lists_max_length"] = np.random.randint(0, 2000000000) else: meta["lists_max_length"] = obj._max_lists_length if obj._max_lists_nesting_depth is None: meta["nesting_max_depth"] = np.random.randint( 1, np.iinfo("int64").max ) else: meta["nesting_max_depth"] = obj._max_lists_nesting_depth meta["value_type"] = random.choice( list(cudf.utils.dtypes.ALL_TYPES - {"category"}) ) elif dtype == "struct": if obj._max_lists_nesting_depth is None: meta["nesting_max_depth"] = np.random.randint(2, 10) else: meta["nesting_max_depth"] = obj._max_lists_nesting_depth if obj._max_struct_null_frequency is None: meta["max_null_frequency"] = random.uniform(0, 1) else: meta["max_null_frequency"] = obj._max_struct_null_frequency if obj._max_struct_types_at_each_level is None: meta["max_types_at_each_level"] = np.random.randint( low=1, high=10 ) else: meta[ "max_types_at_each_level" ] = obj._max_struct_types_at_each_level elif dtype == "decimal64": meta["max_precision"] = cudf.Decimal64Dtype.MAX_PRECISION elif dtype == "decimal32": meta["max_precision"] = cudf.Decimal32Dtype.MAX_PRECISION meta["dtype"] = dtype meta["null_frequency"] = null_frequency meta["cardinality"] = cardinality dtypes_meta.append(meta) return dtypes_meta, num_rows, num_cols def run_test(funcs, args): if len(args) != 2: ValueError("Usage is python file_name.py function_name") function_name_to_run = args[1] try: funcs[function_name_to_run]() except KeyError: print( f"Provided function name({function_name_to_run}) does not exist." ) def pyarrow_to_pandas(table): """ Converts a pyarrow table to a pandas dataframe with Nullable dtypes. Parameters ---------- table: Pyarrow Table Pyarrow table to be converted to pandas Returns ------- DataFrame A Pandas dataframe with nullable dtypes. """ df = pd.DataFrame() for column in table.columns: if column.type in pyarrow_dtypes_to_pandas_dtypes: df[column._name] = pd.Series( column, dtype=pyarrow_dtypes_to_pandas_dtypes[column.type] ) elif isinstance(column.type, pa.StructType): df[column._name] = column.to_pandas(integer_object_nulls=True) else: df[column._name] = column.to_pandas() return df def compare_content(a, b): if a == b: return else: raise ValueError( f"Contents of two files are different:\n left: {a} \n right: {b}" ) def get_avro_dtype_info(dtype): if dtype in _PANDAS_TO_AVRO_SCHEMA_MAP: return _PANDAS_TO_AVRO_SCHEMA_MAP[dtype] else: raise TypeError( f"Unsupported dtype({dtype}) according to avro spec:" f" https://avro.apache.org/docs/current/spec.html" ) def get_avro_schema(df): fields = [ {"name": col_name, "type": get_avro_dtype_info(col_dtype)} for col_name, col_dtype in df.dtypes.items() ] schema = {"type": "record", "name": "Root", "fields": fields} return schema def convert_nulls_to_none(records, df): columns_with_nulls = {col for col in df.columns if df[col].isnull().any()} scalar_columns_convert = [ col for col in df.columns if df[col].dtype in pandas_dtypes_to_np_dtypes or pd.api.types.is_datetime64_dtype(df[col].dtype) or pd.api.types.is_timedelta64_dtype(df[col].dtype) ] for record in records: for col, value in record.items(): if col in scalar_columns_convert: if col in columns_with_nulls and value in (pd.NA, pd.NaT): record[col] = None else: if isinstance(value, str): record[col] = value elif isinstance(value, (pd.Timestamp, pd.Timedelta)): record[col] = int(value.value) else: record[col] = value.item() return records def pandas_to_avro(df, file_name=None, file_io_obj=None): schema = get_avro_schema(df) avro_schema = fastavro.parse_schema(schema) records = df.to_dict("records") records = convert_nulls_to_none(records, df) if file_name is not None: with open(file_name, "wb") as out: fastavro.writer(out, avro_schema, records) elif file_io_obj is not None: fastavro.writer(file_io_obj, avro_schema, records) def orc_to_pandas(file_name=None, file_io_obj=None, stripes=None): if file_name is not None: f = open(file_name, "rb") elif file_io_obj is not None: f = file_io_obj if stripes is None: df = pd.read_orc(f) else: orc_file = pa.orc.ORCFile(f) records = [orc_file.read_stripe(i) for i in stripes] pa_table = pa.Table.from_batches(records) df = pa_table.to_pandas() return df def compare_dataframe(left, right, nullable=True): if nullable and isinstance(left, cudf.DataFrame): left = left.to_pandas(nullable=True) if nullable and isinstance(right, cudf.DataFrame): right = right.to_pandas(nullable=True) if len(left.index) == 0 and len(right.index) == 0: check_index_type = False else: check_index_type = True return assert_eq(left, right, check_index_type=check_index_type)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/fuzz_test_csv.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import sys from io import StringIO import pandas as pd import cudf from cudf._fuzz_testing.csv import CSVReader, CSVWriter from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, compare_content, run_test, ) from cudf.testing._utils import assert_eq @pythonfuzz(data_handle=CSVReader) def csv_reader_test(csv_buffer): pdf = pd.read_csv(StringIO(csv_buffer)) gdf = cudf.read_csv(StringIO(csv_buffer)) assert_eq(gdf, pdf) @pythonfuzz(data_handle=CSVWriter) def csv_writer_test(pdf): gdf = cudf.from_pandas(pdf) pd_buffer = pdf.to_csv() gd_buffer = gdf.to_csv() compare_content(pd_buffer, gd_buffer) actual = cudf.read_csv(StringIO(gd_buffer)) expected = pd.read_csv(StringIO(pd_buffer)) assert_eq(actual, expected) @pythonfuzz( data_handle=CSVWriter, params={ "sep": list([",", "|", "\t", "\r", "~"]), "header": [True, False], "na_rep": [ "", "<NA>", "NA", "_NA_", "__", "<<<<>>>>>", "--<>--", "-+><+-", ], "columns": ALL_POSSIBLE_VALUES, "index": [True, False], "lineterminator": ["\n", "\r", "\r\n"], "chunksize": ALL_POSSIBLE_VALUES, }, ) def csv_writer_test_params( pdf, sep, header, na_rep, columns, index, lineterminator, chunksize ): gdf = cudf.from_pandas(pdf) pd_buffer = pdf.to_csv( sep=sep, header=header, na_rep=na_rep, columns=columns, index=index, lineterminator=lineterminator, chunksize=chunksize, ) gd_buffer = gdf.to_csv( sep=sep, header=header, na_rep=na_rep, columns=columns, index=index, lineterminator=lineterminator, chunksize=chunksize, ) # TODO: Uncomment once this issue is fixed # https://github.com/rapidsai/cudf/issues/6418 # compare_content(pd_buffer, gd_buffer) actual = cudf.read_csv( StringIO(gd_buffer), delimiter=sep, na_values=na_rep, lineterminator=lineterminator, ) expected = pd.read_csv( StringIO(pd_buffer), delimiter=sep, na_values=na_rep, lineterminator=lineterminator, ) if not header: # TODO: Remove renaming columns once the following bug is fixed: # https://github.com/rapidsai/cudf/issues/6418 actual.columns = expected.columns assert_eq(actual, expected) @pythonfuzz( data_handle=CSVReader, params={ "dtype": ALL_POSSIBLE_VALUES, "usecols": ALL_POSSIBLE_VALUES, "header": ALL_POSSIBLE_VALUES, "skiprows": ALL_POSSIBLE_VALUES, "skipfooter": ALL_POSSIBLE_VALUES, "nrows": ALL_POSSIBLE_VALUES, }, ) def csv_reader_test_params(csv_buffer, dtype, header, skiprows): pdf = pd.read_csv( StringIO(csv_buffer), dtype=dtype, header=header, skiprows=skiprows ) gdf = cudf.read_csv( StringIO(csv_buffer), dtype=dtype, header=header, skiprows=skiprows ) assert_eq(gdf, pdf) if __name__ == "__main__": run_test(globals(), sys.argv)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/fuzz_test_parquet.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import sys import numpy as np import pandas as pd import cudf from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.parquet import ParquetReader, ParquetWriter from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, compare_dataframe, run_test, ) @pythonfuzz(data_handle=ParquetReader) def parquet_reader_test(parquet_buffer): pdf = pd.read_parquet(parquet_buffer) gdf = cudf.read_parquet(parquet_buffer) compare_dataframe(gdf, pdf) @pythonfuzz( data_handle=ParquetReader, params={ "columns": ALL_POSSIBLE_VALUES, "use_pandas_metadata": [True, False], }, ) def parquet_reader_columns(parquet_buffer, columns, use_pandas_metadata): pdf = pd.read_parquet( parquet_buffer, columns=columns, use_pandas_metadata=use_pandas_metadata, ) gdf = cudf.read_parquet( parquet_buffer, columns=columns, use_pandas_metadata=use_pandas_metadata, ) compare_dataframe(gdf, pdf) @pythonfuzz(data_handle=ParquetWriter) def parquet_writer_test(pdf): pd_file_name = "cpu_pdf.parquet" gd_file_name = "gpu_pdf.parquet" gdf = cudf.from_pandas(pdf) pdf.to_parquet(pd_file_name) gdf.to_parquet(gd_file_name) actual = cudf.read_parquet(gd_file_name) expected = pd.read_parquet(pd_file_name) compare_dataframe(actual, expected) actual = cudf.read_parquet(pd_file_name) expected = pd.read_parquet(gd_file_name) compare_dataframe(actual, expected) @pythonfuzz( data_handle=ParquetWriter, params={ "row_group_size": np.random.random_integers(1, 10000, 100), "compression": ["snappy", None], }, ) def parquet_writer_test_rowgroup_index_compression( pdf, compression, row_group_size ): pd_file_name = "cpu_pdf.parquet" gd_file_name = "gpu_pdf.parquet" gdf = cudf.from_pandas(pdf) pdf.to_parquet( pd_file_name, compression=compression, row_group_size=row_group_size, ) gdf.to_parquet( gd_file_name, compression=compression, row_group_size=row_group_size, ) actual = cudf.read_parquet(gd_file_name) expected = pd.read_parquet(pd_file_name) compare_dataframe(actual, expected) actual = cudf.read_parquet(pd_file_name) expected = pd.read_parquet(gd_file_name) compare_dataframe(actual, expected, nullable=False) if __name__ == "__main__": run_test(globals(), sys.argv)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/fuzz_test_avro.py
# Copyright (c) 2020, NVIDIA CORPORATION. import sys import cudf from cudf._fuzz_testing.avro import AvroReader from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, compare_dataframe, run_test, ) @pythonfuzz( data_handle=AvroReader, params={ "columns": ALL_POSSIBLE_VALUES, "skiprows": ALL_POSSIBLE_VALUES, "num_rows": ALL_POSSIBLE_VALUES, }, ) def avro_reader_test(input_tuple, columns, skiprows, num_rows): pdf, parquet_buffer = input_tuple expected_pdf = pdf[skiprows:] if num_rows is not None: expected_pdf = expected_pdf.head(num_rows) if skiprows is not None or num_rows is not None: expected_pdf = expected_pdf.reset_index(drop=True) gdf = cudf.read_avro( parquet_buffer, columns=columns, skiprows=skiprows, num_rows=num_rows ) compare_dataframe(expected_pdf, gdf) if __name__ == "__main__": run_test(globals(), sys.argv)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/fuzz_test_orc.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import io import sys import cudf from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.orc import OrcReader, OrcWriter from cudf._fuzz_testing.utils import ( ALL_POSSIBLE_VALUES, compare_dataframe, orc_to_pandas, run_test, ) @pythonfuzz( data_handle=OrcReader, params={ "columns": ALL_POSSIBLE_VALUES, "skiprows": ALL_POSSIBLE_VALUES, "num_rows": ALL_POSSIBLE_VALUES, "use_index": ALL_POSSIBLE_VALUES, }, ) def orc_reader_test(input_tuple, columns, skiprows, num_rows, use_index): pdf, file_buffer = input_tuple expected_pdf = pdf.iloc[skiprows:] if num_rows is not None: expected_pdf = expected_pdf.head(num_rows) if skiprows is not None or num_rows is not None: expected_pdf.reset_index(drop=True, inplace=True) if columns is not None and len(columns) > 0: # ORC reader picks columns if only # there are any elements in `columns` expected_pdf = expected_pdf[columns] if use_index is False: expected_pdf.reset_index(drop=True, inplace=True) gdf = cudf.read_orc( io.BytesIO(file_buffer), columns=columns, skiprows=skiprows, num_rows=num_rows, use_index=use_index, ) compare_dataframe(expected_pdf, gdf) @pythonfuzz( data_handle=OrcReader, params={"columns": ALL_POSSIBLE_VALUES, "stripes": ALL_POSSIBLE_VALUES}, ) def orc_reader_stripes_test(input_tuple, columns, stripes): _, file_buffer = input_tuple expected_pdf = orc_to_pandas( file_io_obj=io.BytesIO(file_buffer), stripes=stripes ) if columns is not None and len(columns) > 0: # ORC reader picks columns if only # there are any elements in `columns` expected_pdf = expected_pdf[columns] gdf = cudf.read_orc( io.BytesIO(file_buffer), columns=columns, stripes=stripes ) compare_dataframe(expected_pdf, gdf) @pythonfuzz( data_handle=OrcWriter, params={ "compression": [None, "snappy"], "enable_statistics": ["NONE", "STRIPE", "ROWGROUP"], }, ) def orc_writer_test(pdf, compression, enable_statistics): file_to_strore = io.BytesIO() gdf = cudf.from_pandas(pdf) gdf.to_orc( file_to_strore, compression=compression, enable_statistics=enable_statistics, ) file_to_strore.seek(0) actual_df = cudf.read_orc(file_to_strore) compare_dataframe(pdf, actual_df) if __name__ == "__main__": run_test(globals(), sys.argv)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/fuzz_test_json.py
# Copyright (c) 2020, NVIDIA CORPORATION. import io import sys import pandas as pd import cudf from cudf._fuzz_testing.json import JSONReader, JSONWriter from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.utils import ALL_POSSIBLE_VALUES, run_test from cudf.testing._utils import assert_eq @pythonfuzz(data_handle=JSONReader) def json_reader_test(json_buffer): pdf = pd.read_json(io.StringIO(json_buffer), orient="records", lines=True) # Difference in behaviour with pandas # cudf reads column as strings only. pdf.columns = pdf.columns.astype("str") gdf = cudf.read_json(io.StringIO(json_buffer), engine="cudf", lines=True) assert_eq(gdf, pdf) @pythonfuzz(data_handle=JSONReader, params={"dtype": ALL_POSSIBLE_VALUES}) def json_reader_test_params(json_buffer, dtype): pdf = pd.read_json(json_buffer, dtype=dtype, orient="records", lines=True) pdf.columns = pdf.columns.astype("str") gdf = cudf.read_json(json_buffer, dtype=dtype, engine="cudf", lines=True) assert_eq(gdf, pdf) @pythonfuzz(data_handle=JSONWriter) def json_writer_test(pdf): gdf = cudf.from_pandas(pdf) pdf_buffer = pdf.to_json(lines=True, orient="records") gdf_buffer = gdf.to_json(lines=True, orient="records") # TODO: Uncomment once this is fixed: # https://github.com/rapidsai/cudf/issues/6429 # compare_content(pdf_buffer, gdf_buffer) actual = cudf.read_json( gdf_buffer, engine="cudf", lines=True, orient="records" ) expected = pd.read_json(pdf_buffer, lines=True, orient="records") expected.columns = expected.columns.astype("str") assert_eq(actual, expected) @pythonfuzz( data_handle=JSONWriter, params={ "compression": ["gzip", "bz2", "zip", "xz", None], "dtype": ALL_POSSIBLE_VALUES, }, ) def json_writer_test_params(pdf, compression, dtype): gdf = cudf.from_pandas(pdf) pdf_buffer = pdf.to_json( lines=True, orient="records", compression=compression ) gdf_buffer = gdf.to_json( lines=True, orient="records", compression=compression ) # TODO: Uncomment once this is fixed: # https://github.com/rapidsai/cudf/issues/6429 # compare_content(pdf_buffer, gdf_buffer) actual = cudf.read_json( io.StringIO(gdf_buffer), engine="cudf", lines=True, orient="records", dtype=dtype, ) expected = pd.read_json( io.StringIO(pdf_buffer), lines=True, orient="records", dtype=dtype ) # Difference in behaviour with pandas # cudf reads column as strings only. expected.columns = expected.columns.astype("str") assert_eq(actual, expected) if __name__ == "__main__": run_test(globals(), sys.argv)
0
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing
rapidsai_public_repos/cudf/python/cudf/cudf/_fuzz_testing/tests/readme.md
# Fuzz Tests This directory contains all the Fuzz tests for cudf library. ## Steps to write a fuzz test 1. Add a Data Handler class which actually generates the necessary random data according to your requirements. This class should be added in `cudf/cudf/testing/`. A sample data handler class is: `CSVWriter`: https://github.com/rapidsai/cudf/blob/branch-0.16/python/cudf/cudf/testing/csv.py 2. Data Handlers are registered by the `pythonfuzz` decorator. At runtime, the Fuzzer will continuously run registered fuzz tests. ```python from cudf.testing.csv import CSVWriter @pythonfuzz(data_handle=CSVWriter) def csv_writer_test(data_from_generate_input): ... ... ... if __name__ == "__main__": ... ... ``` ## Steps to run fuzz tests 1. To run a fuzz test, for example a test(method) is in `write_csv.py`: ```bash python write_csv.py your_function_name ``` To run a basic csv write test in `write_csv.py`: ```bash python write_csv.py csv_writer_test ``` ## Tips to run specific crash file/files Using the `pythonfuzz` decorator pass in `regression=True` with `dirs` having list of directories ```python @pythonfuzz(data_handle=CSVWriter, regression=True, dir=["/cudf/python/cudf/cudf/_fuzz_testing"]) ``` ## Tips to run for varying parameter combinations In the `pythonfuzz` decorator you can pass in the function parameters you would like to pass to the fuzz-test being written via `params` as a dictionary. The values in dictionary are sampled randomly and passed to the `your_custom_fuzz_test`. If a parameter value depends the kind of input generated by the `data_handle`(in this case `CSVReader`), then you can assign `ALL_POSSIBLE_VALUES` constant to it. This constant is used as an identifier by the `data_handle` to generate random parameter values for that specific parameter purely based on data. To perform this customization `set_rand_params` should be implemented as shown in the below example. ```python from cudf._fuzz_testing.main import pythonfuzz from cudf._fuzz_testing.utils import ALL_POSSIBLE_VALUES @pythonfuzz( data_handle=CSVWriter, params={ "columns": ALL_POSSIBLE_VALUES, "is_folder": [True, False, None], "chunksize": ALL_POSSIBLE_VALUES, }, ) def your_custom_fuzz_test(data_from_data_handle, dtype, is_folder, header): ... ... ... ``` A sample implementation of `set_rand_params` in a `data_handle` class: ``` def set_rand_params(self, params): params_dict = {} for param, values in params.items(): if values == ALL_POSSIBLE_VALUES: if param == "columns": col_size = self._rand(len(self._current_buffer.columns)) params_dict[param] = list( np.unique( np.random.choice( self._current_buffer.columns, col_size ) ) ) elif param == "chunksize": params_dict[param] = np.random.choice( [ None, np.random.randint( low=1, high=max(1, len(self._current_buffer)) ), ] ) else: params_dict[param] = np.random.choice(values) self._current_params["test_kwargs"] = self.process_kwargs(params_dict) ```
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/comm/serialize.py
# Copyright (c) 2019-2022, NVIDIA CORPORATION. import cudf # noqa: F401 from cudf.core.abc import Serializable try: from distributed.protocol import dask_deserialize, dask_serialize from distributed.protocol.cuda import cuda_deserialize, cuda_serialize from distributed.utils import log_errors @cuda_serialize.register(Serializable) def cuda_serialize_cudf_object(x): with log_errors(): return x.device_serialize() @dask_serialize.register(Serializable) def dask_serialize_cudf_object(x): with log_errors(): return x.host_serialize() @cuda_deserialize.register(Serializable) def cuda_deserialize_cudf_object(header, frames): with log_errors(): return Serializable.device_deserialize(header, frames) @dask_deserialize.register(Serializable) def dask_deserialize_cudf_object(header, frames): with log_errors(): return Serializable.host_deserialize(header, frames) except ImportError: # distributed is probably not installed on the system pass
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/dlpack.py
# Copyright (c) 2019-2022, NVIDIA CORPORATION. import cudf from cudf._lib import interop as libdlpack from cudf.core.column import ColumnBase from cudf.utils import ioutils def from_dlpack(pycapsule_obj): """Converts from a DLPack tensor to a cuDF object. DLPack is an open-source memory tensor structure: `dmlc/dlpack <https://github.com/dmlc/dlpack>`_. This function takes a PyCapsule object which contains a pointer to a DLPack tensor as input, and returns a cuDF object. This function deep copies the data in the DLPack tensor into a cuDF object. Parameters ---------- pycapsule_obj : PyCapsule Input DLPack tensor pointer which is encapsulated in a PyCapsule object. Returns ------- A cuDF DataFrame or Series depending on if the input DLPack tensor is 1D or 2D. Notes ----- cuDF from_dlpack() assumes column-major (Fortran order) input. If the input tensor is row-major, transpose it before passing it to this function. """ columns = libdlpack.from_dlpack(pycapsule_obj) column_names = range(len(columns)) if len(columns) == 1: return cudf.Series._from_columns(columns, column_names=column_names) else: return cudf.DataFrame._from_columns(columns, column_names=column_names) @ioutils.doc_to_dlpack() def to_dlpack(cudf_obj): """Converts a cuDF object to a DLPack tensor. DLPack is an open-source memory tensor structure: `dmlc/dlpack <https://github.com/dmlc/dlpack>`_. This function takes a cuDF object as input, and returns a PyCapsule object which contains a pointer to DLPack tensor. This function deep copies the data in the cuDF object into the DLPack tensor. Parameters ---------- cudf_obj : cuDF Object Input cuDF object. Returns ------- A DLPack tensor pointer which is encapsulated in a PyCapsule object. Notes ----- cuDF to_dlpack() produces column-major (Fortran order) output. If the output tensor needs to be row major, transpose the output of this function. """ if isinstance(cudf_obj, (cudf.DataFrame, cudf.Series, cudf.BaseIndex)): gdf = cudf_obj elif isinstance(cudf_obj, ColumnBase): gdf = cudf_obj.as_frame() else: raise TypeError( f"Input of type {type(cudf_obj)} cannot be converted " "to DLPack tensor" ) if any( not cudf.api.types._is_non_decimal_numeric_dtype(col.dtype) for col in gdf._data.columns ): raise TypeError("non-numeric data not yet supported") dtype = cudf.utils.dtypes.find_common_type( [col.dtype for col in gdf._data.columns] ) gdf = gdf.astype(dtype) return libdlpack.to_dlpack([*gdf._columns])
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/hdf.py
# Copyright (c) 2019, NVIDIA CORPORATION. import warnings import pandas as pd import cudf from cudf.utils import ioutils @ioutils.doc_read_hdf() def read_hdf(path_or_buf, *args, **kwargs): """{docstring}""" warnings.warn( "Using CPU via Pandas to read HDF dataset, this may " "be GPU accelerated in the future" ) pd_value = pd.read_hdf(path_or_buf, *args, **kwargs) return cudf.from_pandas(pd_value) @ioutils.doc_to_hdf() def to_hdf(path_or_buf, key, value, *args, **kwargs): """{docstring}""" warnings.warn( "Using CPU via Pandas to write HDF dataset, this may " "be GPU accelerated in the future" ) pd_value = value.to_pandas() pd.io.pytables.to_hdf(path_or_buf, key, pd_value, *args, **kwargs)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/orc.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. import datetime import warnings import pyarrow as pa from fsspec.utils import stringify_path import cudf from cudf._lib import orc as liborc from cudf.api.types import is_list_like from cudf.utils import ioutils from cudf.utils.metadata import ( # type: ignore orc_column_statistics_pb2 as cs_pb2, ) def _make_empty_df(filepath_or_buffer, columns): from pyarrow import orc orc_file = orc.ORCFile(filepath_or_buffer) schema = orc_file.schema col_names = schema.names if columns is None else columns return cudf.DataFrame._from_data( data={ col_name: cudf.core.column.column_empty( row_count=0, dtype=schema.field(col_name).type.to_pandas_dtype(), ) for col_name in col_names } ) def _parse_column_statistics(cs, column_statistics_blob): # Initialize stats to return and parse stats blob column_statistics = {} cs.ParseFromString(column_statistics_blob) # Load from parsed stats blob into stats to return if cs.HasField("numberOfValues"): column_statistics["number_of_values"] = cs.numberOfValues if cs.HasField("hasNull"): column_statistics["has_null"] = cs.hasNull if cs.HasField("intStatistics"): column_statistics["minimum"] = ( cs.intStatistics.minimum if cs.intStatistics.HasField("minimum") else None ) column_statistics["maximum"] = ( cs.intStatistics.maximum if cs.intStatistics.HasField("maximum") else None ) column_statistics["sum"] = ( cs.intStatistics.sum if cs.intStatistics.HasField("sum") else None ) elif cs.HasField("doubleStatistics"): column_statistics["minimum"] = ( cs.doubleStatistics.minimum if cs.doubleStatistics.HasField("minimum") else None ) column_statistics["maximum"] = ( cs.doubleStatistics.maximum if cs.doubleStatistics.HasField("maximum") else None ) column_statistics["sum"] = ( cs.doubleStatistics.sum if cs.doubleStatistics.HasField("sum") else None ) elif cs.HasField("stringStatistics"): column_statistics["minimum"] = ( cs.stringStatistics.minimum if cs.stringStatistics.HasField("minimum") else None ) column_statistics["maximum"] = ( cs.stringStatistics.maximum if cs.stringStatistics.HasField("maximum") else None ) column_statistics["sum"] = cs.stringStatistics.sum elif cs.HasField("bucketStatistics"): column_statistics["true_count"] = cs.bucketStatistics.count[0] column_statistics["false_count"] = ( column_statistics["number_of_values"] - column_statistics["true_count"] ) elif cs.HasField("decimalStatistics"): column_statistics["minimum"] = ( cs.decimalStatistics.minimum if cs.decimalStatistics.HasField("minimum") else None ) column_statistics["maximum"] = ( cs.decimalStatistics.maximum if cs.decimalStatistics.HasField("maximum") else None ) column_statistics["sum"] = cs.decimalStatistics.sum elif cs.HasField("dateStatistics"): column_statistics["minimum"] = ( datetime.datetime.fromtimestamp( datetime.timedelta(cs.dateStatistics.minimum).total_seconds(), datetime.timezone.utc, ) if cs.dateStatistics.HasField("minimum") else None ) column_statistics["maximum"] = ( datetime.datetime.fromtimestamp( datetime.timedelta(cs.dateStatistics.maximum).total_seconds(), datetime.timezone.utc, ) if cs.dateStatistics.HasField("maximum") else None ) elif cs.HasField("timestampStatistics"): # Before ORC-135, the local timezone offset was included and they were # stored as minimum and maximum. After ORC-135, the timestamp is # adjusted to UTC before being converted to milliseconds and stored # in minimumUtc and maximumUtc. # TODO: Support minimum and maximum by reading writer's local timezone if cs.timestampStatistics.HasField( "minimumUtc" ) and cs.timestampStatistics.HasField("maximumUtc"): column_statistics["minimum"] = datetime.datetime.fromtimestamp( cs.timestampStatistics.minimumUtc / 1000, datetime.timezone.utc ) column_statistics["maximum"] = datetime.datetime.fromtimestamp( cs.timestampStatistics.maximumUtc / 1000, datetime.timezone.utc ) elif cs.HasField("binaryStatistics"): column_statistics["sum"] = cs.binaryStatistics.sum return column_statistics @ioutils.doc_read_orc_metadata() def read_orc_metadata(path): """{docstring}""" from pyarrow import orc orc_file = orc.ORCFile(path) num_rows = orc_file.nrows num_stripes = orc_file.nstripes col_names = orc_file.schema.names return num_rows, num_stripes, col_names @ioutils.doc_read_orc_statistics() def read_orc_statistics( filepaths_or_buffers, columns=None, **kwargs, ): """{docstring}""" files_statistics = [] stripes_statistics = [] for source in filepaths_or_buffers: path_or_buf, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=source, compression=None, **kwargs ) if compression is not None: ValueError("URL content-encoding decompression is not supported") # Read in statistics and unpack ( column_names, raw_file_statistics, raw_stripes_statistics, ) = liborc.read_raw_orc_statistics(path_or_buf) # Parse column names column_names = [ column_name.decode("utf-8") for column_name in column_names ] # Parse statistics cs = cs_pb2.ColumnStatistics() file_statistics = { column_names[i]: _parse_column_statistics(cs, raw_file_stats) for i, raw_file_stats in enumerate(raw_file_statistics) if columns is None or column_names[i] in columns } if any( not parsed_statistics for parsed_statistics in file_statistics.values() ): continue else: files_statistics.append(file_statistics) for raw_stripe_statistics in raw_stripes_statistics: stripe_statistics = { column_names[i]: _parse_column_statistics(cs, raw_file_stats) for i, raw_file_stats in enumerate(raw_stripe_statistics) if columns is None or column_names[i] in columns } if any( not parsed_statistics for parsed_statistics in stripe_statistics.values() ): continue else: stripes_statistics.append(stripe_statistics) return files_statistics, stripes_statistics def _filter_stripes( filters, filepath_or_buffer, stripes=None, skip_rows=None, num_rows=None ): # Multiple sources are passed as a list. If a single source is passed, # wrap it in a list for unified processing downstream. if not is_list_like(filepath_or_buffer): filepath_or_buffer = [filepath_or_buffer] # Prepare filters filters = ioutils._prepare_filters(filters) # Get columns relevant to filtering columns_in_predicate = [ col for conjunction in filters for (col, op, val) in conjunction ] # Read and parse file-level and stripe-level statistics file_statistics, stripes_statistics = read_orc_statistics( filepath_or_buffer, columns_in_predicate ) file_stripe_map = [] for file_stat in file_statistics: # Filter using file-level statistics if not ioutils._apply_filters(filters, file_stat): continue # Filter using stripe-level statistics selected_stripes = [] num_rows_scanned = 0 for i, stripe_statistics in enumerate(stripes_statistics): num_rows_before_stripe = num_rows_scanned num_rows_scanned += next(iter(stripe_statistics.values()))[ "number_of_values" ] if stripes is not None and i not in stripes: continue if skip_rows is not None and num_rows_scanned <= skip_rows: continue else: skip_rows = 0 if ( skip_rows is not None and num_rows is not None and num_rows_before_stripe >= skip_rows + num_rows ): continue if ioutils._apply_filters(filters, stripe_statistics): selected_stripes.append(i) file_stripe_map.append(selected_stripes) return file_stripe_map @ioutils.doc_read_orc() def read_orc( filepath_or_buffer, engine="cudf", columns=None, filters=None, stripes=None, skiprows=None, num_rows=None, use_index=True, timestamp_type=None, use_python_file_object=True, storage_options=None, bytes_per_thread=None, ): """{docstring}""" from cudf import DataFrame if skiprows is not None: # Do not remove until cuIO team approves its removal. warnings.warn( "skiprows is deprecated and will be removed.", FutureWarning, ) if num_rows is not None: # Do not remove until cuIO team approves its removal. warnings.warn( "num_rows is deprecated and will be removed.", FutureWarning, ) # Multiple sources are passed as a list. If a single source is passed, # wrap it in a list for unified processing downstream. if not is_list_like(filepath_or_buffer): filepath_or_buffer = [filepath_or_buffer] # Each source must have a correlating stripe list. If a single stripe list # is provided rather than a list of list of stripes then extrapolate that # stripe list across all input sources if stripes is not None: if any(not isinstance(stripe, list) for stripe in stripes): stripes = [stripes] # Must ensure a stripe for each source is specified, unless None if not len(stripes) == len(filepath_or_buffer): raise ValueError( "A list of stripes must be provided for each input source" ) filepaths_or_buffers = [] for source in filepath_or_buffer: if ioutils.is_directory( path_or_data=source, storage_options=storage_options ): fs = ioutils._ensure_filesystem( passed_filesystem=None, path=source, storage_options=storage_options, ) source = stringify_path(source) source = fs.sep.join([source, "*.orc"]) tmp_source, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=source, compression=None, use_python_file_object=use_python_file_object, storage_options=storage_options, bytes_per_thread=bytes_per_thread, ) if compression is not None: raise ValueError( "URL content-encoding decompression is not supported" ) if isinstance(tmp_source, list): filepaths_or_buffers.extend(tmp_source) else: filepaths_or_buffers.append(tmp_source) if filters is not None: selected_stripes = _filter_stripes( filters, filepaths_or_buffers, stripes, skiprows, num_rows ) # Return empty if everything was filtered if len(selected_stripes) == 0: return _make_empty_df(filepaths_or_buffers[0], columns) else: stripes = selected_stripes if engine == "cudf": return DataFrame._from_data( *liborc.read_orc( filepaths_or_buffers, columns, stripes, skiprows, num_rows, use_index, timestamp_type, ) ) else: from pyarrow import orc def read_orc_stripe(orc_file, stripe, columns): pa_table = orc_file.read_stripe(stripe, columns) if isinstance(pa_table, pa.RecordBatch): pa_table = pa.Table.from_batches([pa_table]) return pa_table warnings.warn("Using CPU via PyArrow to read ORC dataset.") if len(filepath_or_buffer) > 1: raise NotImplementedError( "Using CPU via PyArrow only supports a single a " "single input source" ) orc_file = orc.ORCFile(filepath_or_buffer[0]) if stripes is not None and len(stripes) > 0: for stripe_source_file in stripes: pa_tables = [ read_orc_stripe(orc_file, i, columns) for i in stripe_source_file ] pa_table = pa.concat_tables(pa_tables) else: pa_table = orc_file.read(columns=columns) df = cudf.DataFrame.from_arrow(pa_table) return df @ioutils.doc_to_orc() def to_orc( df, fname, compression="snappy", statistics="ROWGROUP", stripe_size_bytes=None, stripe_size_rows=None, row_index_stride=None, cols_as_map_type=None, storage_options=None, index=None, ): """{docstring}""" for col in df._data.columns: if isinstance(col, cudf.core.column.CategoricalColumn): raise NotImplementedError( "Writing to ORC format is not yet supported with " "Categorical columns." ) if isinstance(df.index, cudf.CategoricalIndex): raise NotImplementedError( "Writing to ORC format is not yet supported with " "Categorical columns." ) if cols_as_map_type is not None and not isinstance(cols_as_map_type, list): raise TypeError("cols_as_map_type must be a list of column names.") path_or_buf = ioutils.get_writer_filepath_or_buffer( path_or_data=fname, mode="wb", storage_options=storage_options ) if ioutils.is_fsspec_open_file(path_or_buf): with path_or_buf as file_obj: file_obj = ioutils.get_IOBase_writer(file_obj) liborc.write_orc( df, file_obj, compression, statistics, stripe_size_bytes, stripe_size_rows, row_index_stride, cols_as_map_type, index, ) else: liborc.write_orc( df, path_or_buf, compression, statistics, stripe_size_bytes, stripe_size_rows, row_index_stride, cols_as_map_type, index, ) ORCWriter = liborc.ORCWriter
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/avro.py
# Copyright (c) 2019-2022, NVIDIA CORPORATION. import cudf from cudf import _lib as libcudf from cudf.utils import ioutils @ioutils.doc_read_avro() def read_avro( filepath_or_buffer, columns=None, skiprows=None, num_rows=None, storage_options=None, ): """{docstring}""" is_single_filepath_or_buffer = ioutils.ensure_single_filepath_or_buffer( path_or_data=filepath_or_buffer, storage_options=storage_options, ) if not is_single_filepath_or_buffer: raise NotImplementedError( "`read_avro` does not yet support reading multiple files" ) filepath_or_buffer, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=filepath_or_buffer, compression=None, storage_options=storage_options, ) if compression is not None: ValueError("URL content-encoding decompression is not supported") return cudf.DataFrame._from_data( *libcudf.avro.read_avro( filepath_or_buffer, columns, skiprows, num_rows ) )
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/csv.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. from collections import abc from io import BytesIO, StringIO import numpy as np from pyarrow.lib import NativeFile import cudf from cudf import _lib as libcudf from cudf.api.types import is_scalar from cudf.utils import ioutils from cudf.utils.dtypes import _maybe_convert_to_default_type from cudf.utils.nvtx_annotation import _cudf_nvtx_annotate @_cudf_nvtx_annotate @ioutils.doc_read_csv() def read_csv( filepath_or_buffer, sep=",", delimiter=None, header="infer", names=None, index_col=None, usecols=None, prefix=None, mangle_dupe_cols=True, dtype=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=0, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, skip_blank_lines=True, parse_dates=None, dayfirst=False, compression="infer", thousands=None, decimal=".", lineterminator="\n", quotechar='"', quoting=0, doublequote=True, comment=None, delim_whitespace=False, byte_range=None, use_python_file_object=True, storage_options=None, bytes_per_thread=None, ): """{docstring}""" if use_python_file_object and bytes_per_thread is not None: raise ValueError( "bytes_per_thread is only supported when " "`use_python_file_object=False`" ) if bytes_per_thread is None: bytes_per_thread = ioutils._BYTES_PER_THREAD_DEFAULT is_single_filepath_or_buffer = ioutils.ensure_single_filepath_or_buffer( path_or_data=filepath_or_buffer, storage_options=storage_options, ) if not is_single_filepath_or_buffer: raise NotImplementedError( "`read_csv` does not yet support reading multiple files" ) filepath_or_buffer, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=filepath_or_buffer, compression=compression, iotypes=(BytesIO, StringIO, NativeFile), use_python_file_object=use_python_file_object, storage_options=storage_options, bytes_per_thread=bytes_per_thread, ) if na_values is not None and is_scalar(na_values): na_values = [na_values] df = libcudf.csv.read_csv( filepath_or_buffer, lineterminator=lineterminator, quotechar=quotechar, quoting=quoting, doublequote=doublequote, header=header, mangle_dupe_cols=mangle_dupe_cols, usecols=usecols, sep=sep, delimiter=delimiter, delim_whitespace=delim_whitespace, skipinitialspace=skipinitialspace, names=names, dtype=dtype, skipfooter=skipfooter, skiprows=skiprows, dayfirst=dayfirst, compression=compression, thousands=thousands, decimal=decimal, true_values=true_values, false_values=false_values, nrows=nrows, byte_range=byte_range, skip_blank_lines=skip_blank_lines, parse_dates=parse_dates, comment=comment, na_values=na_values, keep_default_na=keep_default_na, na_filter=na_filter, prefix=prefix, index_col=index_col, ) if dtype is None or isinstance(dtype, abc.Mapping): # There exists some dtypes in the result columns that is inferred. # Find them and map them to the default dtypes. specified_dtypes = {} if dtype is None else dtype df_dtypes = df._dtypes unspecified_dtypes = { name: df_dtypes[name] for name in df._column_names if name not in specified_dtypes } default_dtypes = {} for name, dt in unspecified_dtypes.items(): if dt == np.dtype("i1"): # csv reader reads all null column as int8. # The dtype should remain int8. default_dtypes[name] = dt else: default_dtypes[name] = _maybe_convert_to_default_type(dt) df = df.astype(default_dtypes) return df @_cudf_nvtx_annotate @ioutils.doc_to_csv() def to_csv( df, path_or_buf=None, sep=",", na_rep="", columns=None, header=True, index=True, encoding=None, compression=None, lineterminator="\n", chunksize=None, storage_options=None, ): """{docstring}""" if not isinstance(sep, str): raise TypeError(f'"sep" must be string, not {type(sep).__name__}') elif len(sep) > 1: raise TypeError('"sep" must be a 1-character string') if encoding and encoding != "utf-8": error_msg = ( f"Encoding {encoding} is not supported. " + "Currently, only utf-8 encoding is supported." ) raise NotImplementedError(error_msg) if compression: error_msg = "Writing compressed csv is not currently supported in cudf" raise NotImplementedError(error_msg) return_as_string = False if path_or_buf is None: path_or_buf = StringIO() return_as_string = True path_or_buf = ioutils.get_writer_filepath_or_buffer( path_or_data=path_or_buf, mode="w", storage_options=storage_options ) if columns is not None: try: df = df[columns] except KeyError: raise NameError( "Dataframe doesn't have the labels provided in columns" ) for col in df._data.columns: if isinstance(col, cudf.core.column.ListColumn): raise NotImplementedError( "Writing to csv format is not yet supported with " "list columns." ) elif isinstance(col, cudf.core.column.StructColumn): raise NotImplementedError( "Writing to csv format is not yet supported with " "Struct columns." ) # TODO: Need to typecast categorical columns to the underlying # categories dtype to write the actual data to csv. Remove this # workaround once following issue is fixed: # https://github.com/rapidsai/cudf/issues/6661 if any( isinstance(col, cudf.core.column.CategoricalColumn) for col in df._data.columns ) or isinstance(df.index, cudf.CategoricalIndex): df = df.copy(deep=False) for col_name, col in df._data.items(): if isinstance(col, cudf.core.column.CategoricalColumn): df._data[col_name] = col.astype(col.categories.dtype) if isinstance(df.index, cudf.CategoricalIndex): df.index = df.index.astype(df.index.categories.dtype) rows_per_chunk = chunksize if chunksize else len(df) if ioutils.is_fsspec_open_file(path_or_buf): with path_or_buf as file_obj: file_obj = ioutils.get_IOBase_writer(file_obj) libcudf.csv.write_csv( df, path_or_buf=file_obj, sep=sep, na_rep=na_rep, header=header, lineterminator=lineterminator, rows_per_chunk=rows_per_chunk, index=index, ) else: libcudf.csv.write_csv( df, path_or_buf=path_or_buf, sep=sep, na_rep=na_rep, header=header, lineterminator=lineterminator, rows_per_chunk=rows_per_chunk, index=index, ) if return_as_string: path_or_buf.seek(0) return path_or_buf.read()
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/feather.py
# Copyright (c) 2019, NVIDIA CORPORATION. import warnings from pyarrow import feather from cudf.core.dataframe import DataFrame from cudf.utils import ioutils @ioutils.doc_read_feather() def read_feather(path, *args, **kwargs): """{docstring}""" warnings.warn( "Using CPU via PyArrow to read feather dataset, this may " "be GPU accelerated in the future" ) pa_table = feather.read_table(path, *args, **kwargs) return DataFrame.from_arrow(pa_table) @ioutils.doc_to_feather() def to_feather(df, path, *args, **kwargs): """{docstring}""" warnings.warn( "Using CPU via PyArrow to write Feather dataset, this may " "be GPU accelerated in the future" ) # Feather doesn't support using an index pa_table = df.to_arrow(preserve_index=False) feather.write_feather(pa_table, path, *args, **kwargs)
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/parquet.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. from __future__ import annotations import itertools import math import operator import shutil import tempfile import warnings from collections import defaultdict from contextlib import ExitStack from functools import partial, reduce from typing import Callable, Dict, List, Optional, Tuple from uuid import uuid4 import numpy as np import pandas as pd from pyarrow import dataset as ds import cudf from cudf._lib import parquet as libparquet from cudf.api.types import is_list_like from cudf.core.column import build_categorical_column, column_empty, full from cudf.utils import ioutils from cudf.utils.nvtx_annotation import _cudf_nvtx_annotate BYTE_SIZES = { "kb": 1000, "mb": 1000000, "gb": 1000000000, "tb": 1000000000000, "pb": 1000000000000000, "kib": 1024, "mib": 1048576, "gib": 1073741824, "tib": 1099511627776, "pib": 1125899906842624, "b": 1, "": 1, "k": 1000, "m": 1000000, "g": 1000000000, "t": 1000000000000, "p": 1000000000000000, "ki": 1024, "mi": 1048576, "gi": 1073741824, "ti": 1099511627776, "pi": 1125899906842624, } @_cudf_nvtx_annotate def _write_parquet( df, paths, compression="snappy", index=None, statistics="ROWGROUP", metadata_file_path=None, int96_timestamps=False, row_group_size_bytes=ioutils._ROW_GROUP_SIZE_BYTES_DEFAULT, row_group_size_rows=None, max_page_size_bytes=None, max_page_size_rows=None, partitions_info=None, storage_options=None, force_nullable_schema=False, header_version="1.0", use_dictionary=True, ): if is_list_like(paths) and len(paths) > 1: if partitions_info is None: ValueError("partition info is required for multiple paths") elif not is_list_like(partitions_info): ValueError("partition info must be list-like for multiple paths") elif not len(paths) == len(partitions_info): ValueError("partitions_info and paths must be of same size") if is_list_like(partitions_info) and len(partitions_info) > 1: if not is_list_like(paths): ValueError("paths must be list-like when partitions_info provided") paths_or_bufs = [ ioutils.get_writer_filepath_or_buffer( path_or_data=path, mode="wb", storage_options=storage_options ) for path in paths ] common_args = { "index": index, "compression": compression, "statistics": statistics, "metadata_file_path": metadata_file_path, "int96_timestamps": int96_timestamps, "row_group_size_bytes": row_group_size_bytes, "row_group_size_rows": row_group_size_rows, "max_page_size_bytes": max_page_size_bytes, "max_page_size_rows": max_page_size_rows, "partitions_info": partitions_info, "force_nullable_schema": force_nullable_schema, "header_version": header_version, "use_dictionary": use_dictionary, } if all(ioutils.is_fsspec_open_file(buf) for buf in paths_or_bufs): with ExitStack() as stack: fsspec_objs = [stack.enter_context(file) for file in paths_or_bufs] file_objs = [ ioutils.get_IOBase_writer(file_obj) for file_obj in fsspec_objs ] write_parquet_res = libparquet.write_parquet( df, filepaths_or_buffers=file_objs, **common_args ) else: write_parquet_res = libparquet.write_parquet( df, filepaths_or_buffers=paths_or_bufs, **common_args ) return write_parquet_res # Logic chosen to match: https://arrow.apache.org/ # docs/_modules/pyarrow/parquet.html#write_to_dataset @_cudf_nvtx_annotate def write_to_dataset( df, root_path, compression="snappy", filename=None, partition_cols=None, fs=None, preserve_index=False, return_metadata=False, statistics="ROWGROUP", int96_timestamps=False, row_group_size_bytes=ioutils._ROW_GROUP_SIZE_BYTES_DEFAULT, row_group_size_rows=None, max_page_size_bytes=None, max_page_size_rows=None, storage_options=None, force_nullable_schema=False, ): """Wraps `to_parquet` to write partitioned Parquet datasets. For each combination of partition group and value, subdirectories are created as follows: .. code-block:: bash root_dir/ group=value1 <filename>.parquet ... group=valueN <filename>.parquet Parameters ---------- df : cudf.DataFrame root_path : string, The root directory of the dataset compression : {'snappy', 'ZSTD', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. filename : string, default None The file name to use (within each partition directory). If None, a random uuid4 hex string will be used for each file name. partition_cols : list, Column names by which to partition the dataset. Columns are partitioned in the order they are given. fs : FileSystem, default None If nothing passed, paths assumed to be found in the local on-disk filesystem preserve_index : bool, default False Preserve index values in each parquet file. return_metadata : bool, default False Return parquet metadata for written data. Returned metadata will include the file-path metadata (relative to `root_path`). int96_timestamps : bool, default False If ``True``, write timestamps in int96 format. This will convert timestamps from timestamp[ns], timestamp[ms], timestamp[s], and timestamp[us] to the int96 format, which is the number of Julian days and the number of nanoseconds since midnight of 1970-01-01. If ``False``, timestamps will not be altered. row_group_size_bytes: integer or None, default None Maximum size of each stripe of the output. If None, 134217728 (128MB) will be used. row_group_size_rows: integer or None, default None Maximum number of rows of each stripe of the output. If None, 1000000 will be used. max_page_size_bytes: integer or None, default None Maximum uncompressed size of each page of the output. If None, 524288 (512KB) will be used. max_page_size_rows: integer or None, default None Maximum number of rows of each page of the output. If None, 20000 will be used. storage_options : dict, optional, default None Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details. force_nullable_schema : bool, default False. If True, writes all columns as `null` in schema. If False, columns are written as `null` if they contain null values, otherwise as `not null`. """ fs = ioutils._ensure_filesystem(fs, root_path, storage_options) fs.mkdirs(root_path, exist_ok=True) if partition_cols is not None and len(partition_cols) > 0: ( full_paths, metadata_file_paths, grouped_df, part_offsets, _, ) = _get_partitioned( df=df, root_path=root_path, partition_cols=partition_cols, filename=filename, fs=fs, preserve_index=preserve_index, storage_options=storage_options, ) metadata_file_path = metadata_file_paths if return_metadata else None metadata = to_parquet( df=grouped_df, path=full_paths, compression=compression, index=preserve_index, partition_offsets=part_offsets, storage_options=storage_options, metadata_file_path=metadata_file_path, statistics=statistics, int96_timestamps=int96_timestamps, row_group_size_bytes=row_group_size_bytes, row_group_size_rows=row_group_size_rows, max_page_size_bytes=max_page_size_bytes, max_page_size_rows=max_page_size_rows, force_nullable_schema=force_nullable_schema, ) else: filename = filename or _generate_filename() full_path = fs.sep.join([root_path, filename]) metadata_file_path = filename if return_metadata else None metadata = df.to_parquet( path=full_path, compression=compression, index=preserve_index, storage_options=storage_options, metadata_file_path=metadata_file_path, statistics=statistics, int96_timestamps=int96_timestamps, row_group_size_bytes=row_group_size_bytes, row_group_size_rows=row_group_size_rows, max_page_size_bytes=max_page_size_bytes, max_page_size_rows=max_page_size_rows, force_nullable_schema=force_nullable_schema, ) return metadata @ioutils.doc_read_parquet_metadata() @_cudf_nvtx_annotate def read_parquet_metadata(path): """{docstring}""" import pyarrow.parquet as pq pq_file = pq.ParquetFile(path) num_rows = pq_file.metadata.num_rows num_row_groups = pq_file.num_row_groups col_names = pq_file.schema.names return num_rows, num_row_groups, col_names @_cudf_nvtx_annotate def _process_dataset( paths, fs, filters=None, row_groups=None, categorical_partitions=True, dataset_kwargs=None, ): # Returns: # file_list - Expanded/filtered list of paths # row_groups - Filtered list of row-group selections # partition_keys - list of partition keys for each file # partition_categories - Categories for each partition # The general purpose of this function is to (1) expand # directory input into a list of paths (using the pyarrow # dataset API), (2) to apply row-group filters, and (3) # to discover directory-partitioning information # Deal with case that the user passed in a directory name file_list = paths if len(paths) == 1 and ioutils.is_directory(paths[0]): paths = ioutils.stringify_pathlike(paths[0]) # Convert filters to ds.Expression if filters is not None: from pyarrow.parquet import filters_to_expression filters = filters_to_expression(filters) # Initialize ds.FilesystemDataset # TODO: Remove the if len(paths) workaround after following bug is fixed: # https://issues.apache.org/jira/browse/ARROW-16438 dataset = ds.dataset( source=paths[0] if len(paths) == 1 else paths, filesystem=fs, **( dataset_kwargs or { "format": "parquet", "partitioning": "hive", } ), ) file_list = dataset.files if len(file_list) == 0: raise FileNotFoundError(f"{paths} could not be resolved to any files") # Deal with directory partitioning # Get all partition keys (without filters) partition_categories = defaultdict(list) file_fragment = None for file_fragment in dataset.get_fragments(): keys = ds._get_partition_keys(file_fragment.partition_expression) if not (keys or partition_categories): # Bail - This is not a directory-partitioned dataset break for k, v in keys.items(): if v not in partition_categories[k]: partition_categories[k].append(v) if not categorical_partitions: # Bail - We don't need to discover all categories. # We only need to save the partition keys from this # first `file_fragment` break if partition_categories and file_fragment is not None: # Check/correct order of `categories` using last file_frag, # because `_get_partition_keys` does NOT preserve the # partition-hierarchy order of the keys. cat_keys = [ part.split("=")[0] for part in file_fragment.path.split(fs.sep) if "=" in part ] if set(partition_categories) == set(cat_keys): partition_categories = { k: partition_categories[k] for k in cat_keys if k in partition_categories } # If we do not have partitioned data and # are not filtering, we can return here if filters is None and not partition_categories: return file_list, row_groups, [], {} # Record initial row_groups input row_groups_map = {} if row_groups is not None: # Make sure paths and row_groups map 1:1 # and save the initial mapping if len(paths) != len(file_list): raise ValueError( "Cannot specify a row_group selection for a directory path." ) row_groups_map = {path: rgs for path, rgs in zip(paths, row_groups)} # Apply filters and discover partition columns partition_keys = [] if partition_categories or filters is not None: file_list = [] if filters is not None: row_groups = [] for file_fragment in dataset.get_fragments(filter=filters): path = file_fragment.path # Extract hive-partition keys, and make sure they # are ordered the same as they are in `partition_categories` if partition_categories: raw_keys = ds._get_partition_keys( file_fragment.partition_expression ) partition_keys.append( [ (name, raw_keys[name]) for name in partition_categories.keys() ] ) # Apply row-group filtering selection = row_groups_map.get(path, None) if selection is not None or filters is not None: filtered_row_groups = [ rg_info.id for rg_fragment in file_fragment.split_by_row_group( filters, schema=dataset.schema, ) for rg_info in rg_fragment.row_groups ] file_list.append(path) if filters is not None: if selection is None: row_groups.append(filtered_row_groups) else: row_groups.append( [ rg_id for rg_id in filtered_row_groups if rg_id in selection ] ) return ( file_list, row_groups, partition_keys, partition_categories if categorical_partitions else {}, ) @ioutils.doc_read_parquet() @_cudf_nvtx_annotate def read_parquet( filepath_or_buffer, engine="cudf", columns=None, storage_options=None, filters=None, row_groups=None, use_pandas_metadata=True, use_python_file_object=True, categorical_partitions=True, open_file_options=None, bytes_per_thread=None, dataset_kwargs=None, *args, **kwargs, ): """{docstring}""" if engine not in {"cudf", "pyarrow"}: raise ValueError( f"Only supported engines are {{'cudf', 'pyarrow'}}, got {engine=}" ) # Do not allow the user to set file-opening options # when `use_python_file_object=False` is specified if use_python_file_object is False: if open_file_options: raise ValueError( "open_file_options is not currently supported when " "use_python_file_object is set to False." ) open_file_options = {} if bytes_per_thread is None: bytes_per_thread = ioutils._BYTES_PER_THREAD_DEFAULT # Multiple sources are passed as a list. If a single source is passed, # wrap it in a list for unified processing downstream. if not is_list_like(filepath_or_buffer): filepath_or_buffer = [filepath_or_buffer] # a list of row groups per source should be passed. make the list of # lists that is expected for multiple sources if row_groups is not None: if not is_list_like(row_groups): row_groups = [[row_groups]] elif not is_list_like(row_groups[0]): row_groups = [row_groups] # Check columns input if columns is not None: if not is_list_like(columns): raise ValueError("Expected list like for columns") # Start by trying construct a filesystem object, so we # can apply filters on remote file-systems fs, paths = ioutils._get_filesystem_and_paths( path_or_data=filepath_or_buffer, storage_options=storage_options ) # Normalize and validate filters filters = _normalize_filters(filters) # Use pyarrow dataset to detect/process directory-partitioned # data and apply filters. Note that we can only support partitioned # data and filtering if the input is a single directory or list of # paths. partition_keys = [] partition_categories = {} if fs and paths: ( paths, row_groups, partition_keys, partition_categories, ) = _process_dataset( paths=paths, fs=fs, filters=filters, row_groups=row_groups, categorical_partitions=categorical_partitions, dataset_kwargs=dataset_kwargs, ) filepath_or_buffer = paths if paths else filepath_or_buffer filepaths_or_buffers = [] if use_python_file_object: open_file_options = _default_open_file_options( open_file_options=open_file_options, columns=columns, row_groups=row_groups, fs=fs, ) for source in filepath_or_buffer: tmp_source, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=source, compression=None, fs=fs, use_python_file_object=use_python_file_object, open_file_options=open_file_options, storage_options=storage_options, bytes_per_thread=bytes_per_thread, ) if compression is not None: raise ValueError( "URL content-encoding decompression is not supported" ) if isinstance(tmp_source, list): filepath_or_buffer.extend(tmp_source) else: filepaths_or_buffers.append(tmp_source) # Warn user if they are not using cudf for IO # (There is a good chance this was not the intention) if engine != "cudf": warnings.warn( "Using CPU via PyArrow to read Parquet dataset. " "This option is both inefficient and unstable!" ) if filters is not None: warnings.warn( "Parquet row-group filtering is only supported with " "'engine=cudf'. Use pandas or pyarrow API directly " "for full CPU-based filtering functionality." ) # Make sure we read in the columns needed for row-wise # filtering after IO. This means that one or more columns # will be dropped almost immediately after IO. However, # we do NEED these columns for accurate filtering. projected_columns = None if columns and filters: projected_columns = columns columns = sorted( set(v[0] for v in itertools.chain.from_iterable(filters)) | set(columns) ) # Convert parquet data to a cudf.DataFrame df = _parquet_to_frame( filepaths_or_buffers, engine, *args, columns=columns, row_groups=row_groups, use_pandas_metadata=use_pandas_metadata, partition_keys=partition_keys, partition_categories=partition_categories, dataset_kwargs=dataset_kwargs, **kwargs, ) # Apply filters row-wise (if any are defined), and return df = _apply_post_filters(df, filters) if projected_columns: # Elements of `projected_columns` may now be in the index. # We must filter these names from our projection projected_columns = [ col for col in projected_columns if col in df._column_names ] return df[projected_columns] return df def _normalize_filters(filters: list | None) -> List[List[tuple]] | None: # Utility to normalize and validate the `filters` # argument to `read_parquet` if not filters: return None msg = ( f"filters must be None, or non-empty List[Tuple] " f"or List[List[Tuple]]. Got {filters}" ) if not isinstance(filters, list): raise TypeError(msg) def _validate_predicate(item): if not isinstance(item, tuple) or len(item) != 3: raise TypeError( f"Predicate must be Tuple[str, str, Any], " f"got {predicate}." ) filters = filters if isinstance(filters[0], list) else [filters] for conjunction in filters: if not conjunction or not isinstance(conjunction, list): raise TypeError(msg) for predicate in conjunction: _validate_predicate(predicate) return filters def _apply_post_filters( df: cudf.DataFrame, filters: List[List[tuple]] | None ) -> cudf.DataFrame: """Apply DNF filters to an in-memory DataFrame Disjunctive normal form (DNF) means that the inner-most tuple describes a single column predicate. These inner predicates are combined with an AND conjunction into a larger predicate. The outer-most list then combines all of the combined filters with an OR disjunction. """ if not filters: # No filters to apply return df def _handle_in(column: cudf.Series, value, *, negate) -> cudf.Series: if not isinstance(value, (list, set, tuple)): raise TypeError( "Value of 'in'/'not in' filter must be a list, set, or tuple." ) return ~column.isin(value) if negate else column.isin(value) def _handle_is(column: cudf.Series, value, *, negate) -> cudf.Series: if value not in {np.nan, None}: raise TypeError( "Value of 'is'/'is not' filter must be np.nan or None." ) return ~column.isna() if negate else column.isna() handlers: Dict[str, Callable] = { "==": operator.eq, "!=": operator.ne, "<": operator.lt, "<=": operator.le, ">": operator.gt, ">=": operator.ge, "in": partial(_handle_in, negate=False), "not in": partial(_handle_in, negate=True), "is": partial(_handle_is, negate=False), "is not": partial(_handle_is, negate=True), } # Can re-set the index before returning if we filter # out rows from a DataFrame with a default RangeIndex # (to reduce memory usage) reset_index = ( isinstance(df.index, cudf.RangeIndex) and df.index.name is None and df.index.start == 0 and df.index.step == 1 ) try: selection: cudf.Series = reduce( operator.or_, ( reduce( operator.and_, ( handlers[op](df[column], value) for (column, op, value) in expr ), ) for expr in filters ), ) if reset_index: return df[selection].reset_index(drop=True) return df[selection] except (KeyError, TypeError): warnings.warn( f"Row-wise filtering failed in read_parquet for {filters}" ) return df @_cudf_nvtx_annotate def _parquet_to_frame( paths_or_buffers, *args, row_groups=None, partition_keys=None, partition_categories=None, dataset_kwargs=None, **kwargs, ): # If this is not a partitioned read, only need # one call to `_read_parquet` if not partition_keys: return _read_parquet( paths_or_buffers, *args, row_groups=row_groups, **kwargs, ) partition_meta = None partitioning = (dataset_kwargs or {}).get("partitioning", None) if hasattr(partitioning, "schema"): partition_meta = cudf.DataFrame.from_arrow( partitioning.schema.empty_table() ) # For partitioned data, we need a distinct read for each # unique set of partition keys. Therefore, we start by # aggregating all paths with matching keys using a dict plan = {} for i, (keys, path) in enumerate(zip(partition_keys, paths_or_buffers)): rgs = row_groups[i] if row_groups else None tkeys = tuple(keys) if tkeys in plan: plan[tkeys][0].append(path) if rgs is not None: plan[tkeys][1].append(rgs) else: plan[tkeys] = ([path], None if rgs is None else [rgs]) dfs = [] for part_key, (key_paths, key_row_groups) in plan.items(): # Add new DataFrame to our list dfs.append( _read_parquet( key_paths, *args, row_groups=key_row_groups, **kwargs, ) ) # Add partition columns to the last DataFrame for name, value in part_key: _len = len(dfs[-1]) if partition_categories and name in partition_categories: # Build the categorical column from `codes` codes = full( size=_len, fill_value=partition_categories[name].index(value), ) dfs[-1][name] = build_categorical_column( categories=partition_categories[name], codes=codes, size=codes.size, offset=codes.offset, ordered=False, ) else: # Not building categorical columns, so # `value` is already what we want _dtype = ( partition_meta[name].dtype if partition_meta is not None else None ) if pd.isna(value): dfs[-1][name] = column_empty( row_count=_len, dtype=_dtype, masked=True, ) else: dfs[-1][name] = full( size=_len, fill_value=value, dtype=_dtype, ) # Concatenate dfs and return. # Assume we can ignore the index if it has no name. return ( cudf.concat(dfs, ignore_index=dfs[-1].index.name is None) if len(dfs) > 1 else dfs[0] ) @_cudf_nvtx_annotate def _read_parquet( filepaths_or_buffers, engine, columns=None, row_groups=None, use_pandas_metadata=None, *args, **kwargs, ): # Simple helper function to dispatch between # cudf and pyarrow to read parquet data if engine == "cudf": if kwargs: raise ValueError( "cudf engine doesn't support the " f"following keyword arguments: {list(kwargs.keys())}" ) if args: raise ValueError( "cudf engine doesn't support the " f"following positional arguments: {list(args)}" ) return libparquet.read_parquet( filepaths_or_buffers, columns=columns, row_groups=row_groups, use_pandas_metadata=use_pandas_metadata, ) else: if ( isinstance(filepaths_or_buffers, list) and len(filepaths_or_buffers) == 1 ): filepaths_or_buffers = filepaths_or_buffers[0] return cudf.DataFrame.from_pandas( pd.read_parquet( filepaths_or_buffers, columns=columns, engine=engine, *args, **kwargs, ) ) @ioutils.doc_to_parquet() @_cudf_nvtx_annotate def to_parquet( df, path, engine="cudf", compression="snappy", index=None, partition_cols=None, partition_file_name=None, partition_offsets=None, statistics="ROWGROUP", metadata_file_path=None, int96_timestamps=False, row_group_size_bytes=ioutils._ROW_GROUP_SIZE_BYTES_DEFAULT, row_group_size_rows=None, max_page_size_bytes=None, max_page_size_rows=None, storage_options=None, return_metadata=False, force_nullable_schema=False, header_version="1.0", use_dictionary=True, *args, **kwargs, ): """{docstring}""" if engine == "cudf": if kwargs: raise ValueError( "cudf engine doesn't support the " f"following keyword arguments: {list(kwargs.keys())}" ) if args: raise ValueError( "cudf engine doesn't support the " f"following positional arguments: {list(args)}" ) # Ensure that no columns dtype is 'category' for col in df._column_names: if partition_cols is None or col not in partition_cols: if df[col].dtype.name == "category": raise ValueError( "'category' column dtypes are currently not " + "supported by the gpu accelerated parquet writer" ) if partition_cols: if metadata_file_path is not None: warnings.warn( "metadata_file_path will be ignored/overwritten when " "partition_cols are provided. To request returning the " "metadata binary blob, pass `return_metadata=True`" ) return write_to_dataset( df, filename=partition_file_name, partition_cols=partition_cols, root_path=path, preserve_index=index, compression=compression, statistics=statistics, int96_timestamps=int96_timestamps, row_group_size_bytes=row_group_size_bytes, row_group_size_rows=row_group_size_rows, max_page_size_bytes=max_page_size_bytes, max_page_size_rows=max_page_size_rows, return_metadata=return_metadata, storage_options=storage_options, force_nullable_schema=force_nullable_schema, ) partition_info = ( [ (i, j - i) for i, j in zip(partition_offsets, partition_offsets[1:]) ] if partition_offsets is not None else None ) return _write_parquet( df, paths=path if is_list_like(path) else [path], compression=compression, index=index, statistics=statistics, metadata_file_path=metadata_file_path, int96_timestamps=int96_timestamps, row_group_size_bytes=row_group_size_bytes, row_group_size_rows=row_group_size_rows, max_page_size_bytes=max_page_size_bytes, max_page_size_rows=max_page_size_rows, partitions_info=partition_info, storage_options=storage_options, force_nullable_schema=force_nullable_schema, header_version=header_version, use_dictionary=use_dictionary, ) else: import pyarrow.parquet as pq if partition_offsets is not None: warnings.warn( "partition_offsets will be ignored when engine is not cudf" ) # If index is empty set it to the expected default value of True if index is None: index = True # Convert partition_file_name to a call back if partition_file_name: partition_file_name = lambda x: partition_file_name # noqa: E731 pa_table = df.to_arrow(preserve_index=index) return pq.write_to_dataset( pa_table, root_path=path, partition_filename_cb=partition_file_name, partition_cols=partition_cols, *args, **kwargs, ) @ioutils.doc_merge_parquet_filemetadata() def merge_parquet_filemetadata(filemetadata_list): """{docstring}""" return libparquet.merge_filemetadata(filemetadata_list) def _generate_filename(): return uuid4().hex + ".parquet" def _get_estimated_file_size(df): # NOTE: This is purely a guesstimation method # and the y = mx+c has been arrived # after extensive experimentation of parquet file size # vs dataframe sizes. df_mem_usage = df.memory_usage().sum() # Parquet file size of a dataframe with all unique values # seems to be 1/1.5 times as that of on GPU for >10000 rows # and 0.6 times else-wise. # Y(file_size) = M(0.6) * X(df_mem_usage) + C(705) file_size = int((df_mem_usage * 0.6) + 705) # 1000 Bytes accounted for row-group metadata. # A parquet file takes roughly ~810 Bytes of metadata per column. file_size = file_size + 1000 + (810 * df.shape[1]) return file_size @_cudf_nvtx_annotate def _get_partitioned( df, root_path, partition_cols, filename=None, fs=None, preserve_index=False, storage_options=None, ): fs = ioutils._ensure_filesystem( fs, root_path, storage_options=storage_options ) fs.mkdirs(root_path, exist_ok=True) part_names, grouped_df, part_offsets = _get_groups_and_offsets( df, partition_cols, preserve_index ) full_paths = [] metadata_file_paths = [] for keys in part_names.itertuples(index=False): subdir = fs.sep.join( [ _hive_dirname(name, val) for name, val in zip(partition_cols, keys) ] ) prefix = fs.sep.join([root_path, subdir]) fs.mkdirs(prefix, exist_ok=True) filename = filename or _generate_filename() full_path = fs.sep.join([prefix, filename]) full_paths.append(full_path) metadata_file_paths.append(fs.sep.join([subdir, filename])) return full_paths, metadata_file_paths, grouped_df, part_offsets, filename @_cudf_nvtx_annotate def _get_groups_and_offsets( df, partition_cols, preserve_index=False, **kwargs, ): if not (set(df._data) - set(partition_cols)): warnings.warn("No data left to save outside partition columns") _, part_offsets, part_keys, grouped_df = df.groupby( partition_cols, dropna=False, )._grouped() if not preserve_index: grouped_df.reset_index(drop=True, inplace=True) grouped_df.drop(columns=partition_cols, inplace=True) # Copy the entire keys df in one operation rather than using iloc part_names = ( part_keys.take(part_offsets[:-1]) .to_pandas(nullable=True) .to_frame(index=False) ) return part_names, grouped_df, part_offsets ParquetWriter = libparquet.ParquetWriter def _parse_bytes(s): """Parse byte string to numbers Utility function vendored from Dask. >>> _parse_bytes('100') 100 >>> _parse_bytes('100 MB') 100000000 >>> _parse_bytes('100M') 100000000 >>> _parse_bytes('5kB') 5000 >>> _parse_bytes('5.4 kB') 5400 >>> _parse_bytes('1kiB') 1024 >>> _parse_bytes('1e6') 1000000 >>> _parse_bytes('1e6 kB') 1000000000 >>> _parse_bytes('MB') 1000000 >>> _parse_bytes(123) 123 >>> _parse_bytes('5 foos') Traceback (most recent call last): ... ValueError: Could not interpret 'foos' as a byte unit """ if isinstance(s, (int, float)): return int(s) s = s.replace(" ", "") if not any(char.isdigit() for char in s): s = "1" + s for i in range(len(s) - 1, -1, -1): if not s[i].isalpha(): break index = i + 1 prefix = s[:index] suffix = s[index:] try: n = float(prefix) except ValueError as e: raise ValueError( "Could not interpret '%s' as a number" % prefix ) from e try: multiplier = BYTE_SIZES[suffix.lower()] except KeyError as e: raise ValueError( "Could not interpret '%s' as a byte unit" % suffix ) from e result = n * multiplier return int(result) class ParquetDatasetWriter: """ Write a parquet file or dataset incrementally Parameters ---------- path : str A local directory path or S3 URL. Will be used as root directory path while writing a partitioned dataset. partition_cols : list Column names by which to partition the dataset Columns are partitioned in the order they are given index : bool, default None If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, index(es) other than RangeIndex will be saved as columns. compression : {'snappy', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. statistics : {'ROWGROUP', 'PAGE', 'COLUMN', 'NONE'}, default 'ROWGROUP' Level at which column statistics should be included in file. max_file_size : int or str, default None A file size that cannot be exceeded by the writer. It is in bytes, if the input is int. Size can also be a str in form or "10 MB", "1 GB", etc. If this parameter is used, it is mandatory to pass `file_name_prefix`. file_name_prefix : str This is a prefix to file names generated only when `max_file_size` is specified. storage_options : dict, optional, default None Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details. Examples -------- Using a context >>> df1 = cudf.DataFrame({"a": [1, 1, 2, 2, 1], "b": [9, 8, 7, 6, 5]}) >>> df2 = cudf.DataFrame({"a": [1, 3, 3, 1, 3], "b": [4, 3, 2, 1, 0]}) >>> with ParquetDatasetWriter("./dataset", partition_cols=["a"]) as cw: ... cw.write_table(df1) ... cw.write_table(df2) By manually calling ``close()`` >>> cw = ParquetDatasetWriter("./dataset", partition_cols=["a"]) >>> cw.write_table(df1) >>> cw.write_table(df2) >>> cw.close() Both the methods will generate the same directory structure .. code-block:: none dataset/ a=1 <filename>.parquet a=2 <filename>.parquet a=3 <filename>.parquet """ @_cudf_nvtx_annotate def __init__( self, path, partition_cols, index=None, compression="snappy", statistics="ROWGROUP", max_file_size=None, file_name_prefix=None, storage_options=None, ) -> None: if isinstance(path, str) and path.startswith("s3://"): self.fs_meta = {"is_s3": True, "actual_path": path} self.dir_: Optional[ tempfile.TemporaryDirectory ] = tempfile.TemporaryDirectory() self.path = self.dir_.name else: self.fs_meta = {} self.dir_ = None self.path = path self.common_args = { "index": index, "compression": compression, "statistics": statistics, } self.partition_cols = partition_cols # Collection of `ParquetWriter`s, and the corresponding # partition_col values they're responsible for self._chunked_writers: List[ Tuple[libparquet.ParquetWriter, List[str], str] ] = [] # Map of partition_col values to their ParquetWriter's index # in self._chunked_writers for reverse lookup self.path_cw_map: Dict[str, int] = {} self.storage_options = storage_options self.filename = file_name_prefix self.max_file_size = max_file_size if max_file_size is not None: if file_name_prefix is None: raise ValueError( "file_name_prefix cannot be None if max_file_size is " "passed" ) self.max_file_size = _parse_bytes(max_file_size) self._file_sizes: Dict[str, int] = {} @_cudf_nvtx_annotate def write_table(self, df): """ Write a dataframe to the file/dataset """ (part_names, grouped_df, part_offsets,) = _get_groups_and_offsets( df=df, partition_cols=self.partition_cols, preserve_index=self.common_args["index"], ) fs = ioutils._ensure_filesystem(None, self.path, None) fs.mkdirs(self.path, exist_ok=True) full_paths = [] metadata_file_paths = [] full_offsets = [0] for idx, keys in enumerate(part_names.itertuples(index=False)): subdir = fs.sep.join( [ f"{name}={val}" for name, val in zip(self.partition_cols, keys) ] ) prefix = fs.sep.join([self.path, subdir]) fs.mkdirs(prefix, exist_ok=True) current_offset = (part_offsets[idx], part_offsets[idx + 1]) num_chunks = 1 parts = 1 if self.max_file_size is not None: # get the current partition start, end = current_offset sliced_df = grouped_df[start:end] current_file_size = _get_estimated_file_size(sliced_df) if current_file_size > self.max_file_size: # if the file is too large, compute metadata for # smaller chunks parts = math.ceil(current_file_size / self.max_file_size) new_offsets = list( range(start, end, int((end - start) / parts)) )[1:] new_offsets.append(end) num_chunks = len(new_offsets) parts = len(new_offsets) full_offsets.extend(new_offsets) else: full_offsets.append(end) curr_file_num = 0 num_chunks = 0 while num_chunks < parts: new_file_name = f"{self.filename}_{curr_file_num}.parquet" new_full_path = fs.sep.join([prefix, new_file_name]) # Check if the same `new_file_name` exists and # generate a `new_file_name` while new_full_path in self._file_sizes and ( self._file_sizes[new_full_path] + (current_file_size / parts) ) > (self.max_file_size): curr_file_num += 1 new_file_name = ( f"{self.filename}_{curr_file_num}.parquet" ) new_full_path = fs.sep.join([prefix, new_file_name]) self._file_sizes[new_full_path] = self._file_sizes.get( new_full_path, 0 ) + (current_file_size / parts) full_paths.append(new_full_path) metadata_file_paths.append( fs.sep.join([subdir, new_file_name]) ) num_chunks += 1 curr_file_num += 1 else: self.filename = self.filename or _generate_filename() full_path = fs.sep.join([prefix, self.filename]) full_paths.append(full_path) metadata_file_paths.append( fs.sep.join([subdir, self.filename]) ) full_offsets.append(current_offset[1]) paths, metadata_file_paths, offsets = ( full_paths, metadata_file_paths, full_offsets, ) existing_cw_batch = defaultdict(dict) new_cw_paths = [] partition_info = [(i, j - i) for i, j in zip(offsets, offsets[1:])] for path, part_info, meta_path in zip( paths, partition_info, metadata_file_paths, ): if path in self.path_cw_map: # path is a currently open file cw_idx = self.path_cw_map[path] existing_cw_batch[cw_idx][path] = part_info else: # path not currently handled by any chunked writer new_cw_paths.append((path, part_info, meta_path)) # Write out the parts of grouped_df currently handled by existing cw's for cw_idx, path_to_part_info_map in existing_cw_batch.items(): cw = self._chunked_writers[cw_idx][0] # match found paths with this cw's paths and nullify partition info # for partition_col values not in this batch this_cw_part_info = [ path_to_part_info_map.get(path, (0, 0)) for path in self._chunked_writers[cw_idx][1] ] cw.write_table(grouped_df, this_cw_part_info) if new_cw_paths: # Create new cw for unhandled paths encountered in this write_table new_paths, part_info, meta_paths = zip(*new_cw_paths) self._chunked_writers.append( ( ParquetWriter(new_paths, **self.common_args), new_paths, meta_paths, ) ) new_cw_idx = len(self._chunked_writers) - 1 self.path_cw_map.update({k: new_cw_idx for k in new_paths}) self._chunked_writers[-1][0].write_table(grouped_df, part_info) @_cudf_nvtx_annotate def close(self, return_metadata=False): """ Close all open files and optionally return footer metadata as a binary blob """ metadata = [ cw.close(metadata_file_path=meta_path if return_metadata else None) for cw, _, meta_path in self._chunked_writers ] if self.fs_meta.get("is_s3", False): local_path = self.path s3_path = self.fs_meta["actual_path"] s3_file, _ = ioutils._get_filesystem_and_paths( s3_path, storage_options=self.storage_options ) s3_file.put(local_path, s3_path, recursive=True) shutil.rmtree(self.path) if self.dir_ is not None: self.dir_.cleanup() if return_metadata: return ( merge_parquet_filemetadata(metadata) if len(metadata) > 1 else metadata[0] ) def __enter__(self): return self def __exit__(self, *args): self.close() def _default_open_file_options( open_file_options, columns, row_groups, fs=None ): """ Set default fields in open_file_options. Copies and updates `open_file_options` to include column and row-group information under the "precache_options" key. By default, we set "method" to "parquet", but precaching will be disabled if the user chooses `method=None` Parameters ---------- open_file_options : dict or None columns : list row_groups : list fs : fsspec.AbstractFileSystem, Optional """ if fs and ioutils._is_local_filesystem(fs): # Quick return for local fs return open_file_options or {} # Assume remote storage if `fs` was not specified open_file_options = (open_file_options or {}).copy() precache_options = open_file_options.pop("precache_options", {}).copy() if precache_options.get("method", "parquet") == "parquet": precache_options.update( { "method": "parquet", "engine": precache_options.get("engine", "pyarrow"), "columns": columns, "row_groups": row_groups, } ) open_file_options["precache_options"] = precache_options return open_file_options def _hive_dirname(name, val): # Simple utility to produce hive directory name if pd.isna(val): val = "__HIVE_DEFAULT_PARTITION__" return f"{name}={val}"
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/json.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. import warnings from collections import abc from io import BytesIO, StringIO import numpy as np import pandas as pd import cudf from cudf._lib import json as libjson from cudf.api.types import is_list_like from cudf.utils import ioutils from cudf.utils.dtypes import _maybe_convert_to_default_type @ioutils.doc_read_json() def read_json( path_or_buf, engine="auto", orient=None, dtype=None, lines=False, compression="infer", byte_range=None, keep_quotes=False, storage_options=None, *args, **kwargs, ): """{docstring}""" if dtype is not None and not isinstance(dtype, (abc.Mapping, bool)): raise TypeError( "'dtype' parameter only supports " "a dict of column names and types as key-value pairs, " f"or a bool, or None. Got {type(dtype)}" ) if engine == "cudf_experimental": raise ValueError( "engine='cudf_experimental' support has been removed, " "use `engine='cudf'`" ) if engine == "cudf_legacy": # TODO: Deprecated in 23.02, please # give some time until(more than couple of # releases from now) `cudf_legacy` # support can be removed completely. warnings.warn( "engine='cudf_legacy' is a deprecated engine." "This will be removed in a future release." "Please switch to using engine='cudf'.", FutureWarning, ) if engine == "cudf_legacy" and not lines: raise ValueError(f"{engine} engine only supports JSON Lines format") if engine == "auto": engine = "cudf" if lines else "pandas" if engine != "cudf" and keep_quotes: raise ValueError( "keep_quotes='True' is supported only with engine='cudf'" ) if engine == "cudf_legacy" or engine == "cudf": if dtype is None: dtype = True if kwargs: raise ValueError( "cudf engine doesn't support the " f"following keyword arguments: {list(kwargs.keys())}" ) if args: raise ValueError( "cudf engine doesn't support the " f"following positional arguments: {list(args)}" ) # Multiple sources are passed as a list. If a single source is passed, # wrap it in a list for unified processing downstream. if not is_list_like(path_or_buf): path_or_buf = [path_or_buf] filepaths_or_buffers = [] for source in path_or_buf: if ioutils.is_directory( path_or_data=source, storage_options=storage_options ): fs = ioutils._ensure_filesystem( passed_filesystem=None, path=source, storage_options=storage_options, ) source = ioutils.stringify_pathlike(source) source = fs.sep.join([source, "*.json"]) tmp_source, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=source, compression=compression, iotypes=(BytesIO, StringIO), allow_raw_text_input=True, storage_options=storage_options, ) if isinstance(tmp_source, list): filepaths_or_buffers.extend(tmp_source) else: filepaths_or_buffers.append(tmp_source) df = libjson.read_json( filepaths_or_buffers, dtype, lines, compression, byte_range, engine == "cudf_legacy", keep_quotes, ) else: warnings.warn( "Using CPU via Pandas to read JSON dataset, this may " "be GPU accelerated in the future" ) if not ioutils.ensure_single_filepath_or_buffer( path_or_data=path_or_buf, storage_options=storage_options, ): raise NotImplementedError( "`read_json` does not yet support reading " "multiple files via pandas" ) path_or_buf, compression = ioutils.get_reader_filepath_or_buffer( path_or_data=path_or_buf, compression=compression, iotypes=(BytesIO, StringIO), allow_raw_text_input=True, storage_options=storage_options, ) pd_value = pd.read_json( path_or_buf, lines=lines, dtype=dtype, compression=compression, storage_options=storage_options, orient=orient, *args, **kwargs, ) df = cudf.from_pandas(pd_value) if dtype is None: dtype = True if dtype is True or isinstance(dtype, abc.Mapping): # There exists some dtypes in the result columns that is inferred. # Find them and map them to the default dtypes. specified_dtypes = {} if dtype is True else dtype df_dtypes = df._dtypes unspecified_dtypes = { name: df_dtypes[name] for name in df._column_names if name not in specified_dtypes } default_dtypes = {} for name, dt in unspecified_dtypes.items(): if dt == np.dtype("i1"): # csv reader reads all null column as int8. # The dtype should remain int8. default_dtypes[name] = dt else: default_dtypes[name] = _maybe_convert_to_default_type(dt) df = df.astype(default_dtypes) return df @ioutils.doc_to_json() def to_json( cudf_val, path_or_buf=None, engine="auto", orient=None, storage_options=None, *args, **kwargs, ): """{docstring}""" if engine == "auto": engine = "pandas" if engine == "cudf": if orient not in {"records", None}: raise ValueError( f"Only the `orient='records'` is supported for JSON writer" f" with `engine='cudf'`, got {orient}" ) if path_or_buf is None: path_or_buf = StringIO() return_as_string = True else: path_or_buf = ioutils.get_writer_filepath_or_buffer( path_or_data=path_or_buf, mode="w", storage_options=storage_options, ) return_as_string = False if ioutils.is_fsspec_open_file(path_or_buf): with path_or_buf as file_obj: file_obj = ioutils.get_IOBase_writer(file_obj) libjson.write_json( cudf_val, path_or_buf=file_obj, *args, **kwargs ) else: libjson.write_json( cudf_val, path_or_buf=path_or_buf, *args, **kwargs ) if return_as_string: path_or_buf.seek(0) return path_or_buf.read() elif engine == "pandas": warnings.warn("Using CPU via Pandas to write JSON dataset") pd_value = cudf_val.to_pandas(nullable=True) return pd.io.json.to_json( path_or_buf, pd_value, orient=orient, storage_options=storage_options, *args, **kwargs, ) else: raise ValueError( f"`engine` only support {{'auto', 'cudf', 'pandas'}}, " f"got: {engine}" )
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/text.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. from io import BytesIO, StringIO import cudf from cudf._lib import text as libtext from cudf.utils import ioutils from cudf.utils.nvtx_annotation import _cudf_nvtx_annotate @_cudf_nvtx_annotate @ioutils.doc_read_text() def read_text( filepath_or_buffer, delimiter=None, byte_range=None, strip_delimiters=False, compression=None, compression_offsets=None, storage_options=None, ): """{docstring}""" if delimiter is None: raise ValueError("delimiter needs to be provided") filepath_or_buffer, _ = ioutils.get_reader_filepath_or_buffer( path_or_data=filepath_or_buffer, compression=None, iotypes=(BytesIO, StringIO), storage_options=storage_options, ) return cudf.Series._from_data( libtext.read_text( filepath_or_buffer, delimiter=delimiter, byte_range=byte_range, strip_delimiters=strip_delimiters, compression=compression, compression_offsets=compression_offsets, ) )
0
rapidsai_public_repos/cudf/python/cudf/cudf
rapidsai_public_repos/cudf/python/cudf/cudf/io/__init__.py
# Copyright (c) 2018-2022, NVIDIA CORPORATION. from cudf.io.avro import read_avro from cudf.io.csv import read_csv, to_csv from cudf.io.dlpack import from_dlpack from cudf.io.feather import read_feather from cudf.io.hdf import read_hdf from cudf.io.json import read_json from cudf.io.orc import read_orc, read_orc_metadata, to_orc from cudf.io.parquet import ( ParquetDatasetWriter, merge_parquet_filemetadata, read_parquet, read_parquet_metadata, write_to_dataset, ) from cudf.io.text import read_text
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_profiler.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 from cudf.pandas import LOADED, Profiler if not LOADED: raise ImportError("These tests must be run with cudf.pandas loaded") import numpy as np import pandas as pd def test_profiler(): np.random.seed(42) with Profiler() as profiler: df = pd.DataFrame( { "idx": np.random.randint(0, 10, 1000), "data": np.random.rand(1000), } ) sums = df.groupby("idx").sum() total = df.sum()["data"] assert np.isclose(total, sums.sum()["data"]) _ = pd.Timestamp(2020, 1, 1) + pd.Timedelta(1) per_function_stats = profiler.per_function_stats assert set(per_function_stats) == { "DataFrame", "DataFrame.groupby", "DataFrameGroupBy.sum", "DataFrame.sum", "Series.__getitem__", } for name, func in per_function_stats.items(): assert ( len(func["cpu"]) == 0 if "Time" not in name else len(func["gpu"]) == 0 ) per_line_stats = profiler.per_line_stats calls = [ "pd.DataFrame", "", "np.random.randint", "np.random.rand", 'df.groupby("idx").sum', 'df.sum()["data"]', "np.isclose", "pd.Timestamp", ] for line_stats, call in zip(per_line_stats, calls): # Check that the expected function calls were recorded. assert call in line_stats[1] # No CPU time assert line_stats[3] == 0 if "Time" not in call else line_stats[2] == 0 def test_profiler_hasattr_exception(): with Profiler(): df = pd.DataFrame({"data": [1, 2, 3]}) hasattr(df, "this_does_not_exist") def test_profiler_fast_slow_name_mismatch(): with Profiler(): df = pd.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}) df.iloc[0, 1] = "foo"
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_magics.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 import os import pathlib import subprocess import sys import pytest # Proxy check for whether the proxy could be referencing GPU objects without # trying to import cuDF, which could poison the global environment def _gpu_available(): try: import rmm return rmm._cuda.gpu.getDeviceCount() >= 1 except ImportError: return False LOCATION = pathlib.Path(__file__).absolute().parent @pytest.mark.skipif( not _gpu_available(), reason="Skipping test if a GPU isn't available." ) def test_magics_gpu(): sp_completed = subprocess.run( [sys.executable, LOCATION / "_magics_gpu_test.py"], capture_output=True ) assert sp_completed.stderr.decode() == "" @pytest.mark.skip( "This test was viable when cudf.pandas was separate from cudf, but now " "that it is a subpackage we always require a GPU to be present and cannot " "run this test." ) def test_magics_cpu(): env = os.environ.copy() env["CUDA_VISIBLE_DEVICES"] = "" sp_completed = subprocess.run( [sys.executable, LOCATION / "_magics_cpu_test.py"], capture_output=True, env=env, ) assert sp_completed.stderr.decode() == ""
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_cudf_pandas.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 import collections import copy import datetime import operator import pathlib import pickle import tempfile import types from io import BytesIO, StringIO import numpy as np import pyarrow as pa import pytest from numba import NumbaDeprecationWarning from cudf.pandas import LOADED, Profiler from cudf.pandas.fast_slow_proxy import _Unusable if not LOADED: raise ImportError("These tests must be run with cudf.pandas loaded") import pandas as xpd import pandas._testing as tm # Accelerated pandas has the real pandas module as an attribute pd = xpd._fsproxy_slow @pytest.fixture def dataframe(): pdf = pd.DataFrame({"a": [1, 1, 1, 2, 3], "b": [1, 2, 3, 4, 5]}) df = xpd.DataFrame(pdf) return (pdf, df) @pytest.fixture def series(dataframe): pdf, df = dataframe return (pdf["a"], df["a"]) @pytest.fixture def index(): return ( pd.Index(["a", "b", "c", "d", "e"]), xpd.Index(["a", "b", "c", "d", "e"]), ) @pytest.fixture def multiindex(dataframe): pdf, df = dataframe pmi = pd.MultiIndex.from_frame(pdf) mi = xpd.MultiIndex.from_frame(df) return (pmi, mi) @pytest.fixture def array(series): arr, xarr = series return (arr.values, xarr.values) @pytest.fixture( params=[ lambda group: group["a"].sum(), lambda group: group.sum().apply(lambda val: [val]), ] ) def groupby_udf(request): return request.param def test_assert_equal(): tm.assert_frame_equal( pd.DataFrame({"a": [1, 2, 3]}), xpd.DataFrame({"a": [1, 2, 3]}) ) with pytest.raises(AssertionError): tm.assert_frame_equal( pd.DataFrame({"a": [1, 2, 3]}), xpd.DataFrame({"a": [1, 2, 4]}) ) def test_construction(): # test that constructing a DataFrame returns an DataFrame data = {"a": [1, 2, 3], "b": ["x", "y", "z"]} pdf = pd.DataFrame(data) df = xpd.DataFrame(data) tm.assert_frame_equal(pdf, df) def test_construction_object(): # test that we can construct a Series with `object` dtype psr = pd.Series([1, "a", [1, 2, 3]]) sr = xpd.Series([1, "a", [1, 2, 3]]) tm.assert_series_equal(psr, sr) def test_construction_from_frame(dataframe): pdf, _ = dataframe df = xpd.DataFrame(pdf) tm.assert_frame_equal(pdf, df) def test_groupby(dataframe): pdf, df = dataframe expected = pdf.groupby("a", sort=True).max() gb = df.groupby("a", sort=True) got = gb.max() tm.assert_frame_equal(expected, got) def test_repr(dataframe): pdf, df = dataframe assert df.__repr__() == pdf.__repr__() def test_binops_series(series): psr, sr = series expected = psr + psr got = sr + sr tm.assert_series_equal(expected, got) def test_binops_df(dataframe): pdf, df = dataframe expected = pdf + pdf got = df + df tm.assert_frame_equal(expected, got) def test_attribute(dataframe): pdf, df = dataframe assert pdf.shape == df.shape def test_tz_localize(): psr = pd.Series(["2001-01-01", "2002-02-02"], dtype="datetime64[ms]") sr = xpd.Series(psr) tm.assert_series_equal( psr.dt.tz_localize("America/New_York"), sr.dt.tz_localize("America/New_York"), check_dtype=False, ) def test_index_tz_localize(): pti = pd.Index(pd.date_range("2020-01-01", periods=3, freq="D")) xti = xpd.Index(xpd.date_range("2020-01-01", periods=3, freq="D")) pti = pti.tz_localize("UTC") xti = xti.tz_localize("UTC") tm.assert_equal(pti, xti) def test_index_generator(): pi = pd.Index(iter(range(10))) xi = xpd.Index(iter(range(10))) tm.assert_equal(pi, xi) def test_groupby_apply_fallback(dataframe, groupby_udf): pdf, df = dataframe tm.assert_equal( pdf.groupby("a", sort=True, group_keys=True).apply(groupby_udf), df.groupby("a", sort=True, group_keys=True).apply(groupby_udf), ) def test_groupby_external_series_apply_fallback(dataframe, groupby_udf): pdf, df = dataframe tm.assert_equal( pdf.groupby( pd.Series([1, 2, 1, 2, 1]), sort=True, group_keys=True ).apply(groupby_udf), df.groupby( xpd.Series([1, 2, 1, 2, 1]), sort=True, group_keys=True ).apply(groupby_udf), ) def test_read_csv(): data = "1,2,3\n4,5,6" expected = pd.read_csv(StringIO(data)) got = xpd.read_csv(StringIO(data)) tm.assert_frame_equal(expected, got) def test_iloc(dataframe): pdf, df = dataframe tm.assert_frame_equal(pdf.iloc[:, :], df.iloc[:, :]) def test_neg(dataframe): pdf, df = dataframe tm.assert_frame_equal(-pdf, -df) def test_groupby_filter(dataframe): pdf, df = dataframe expected = pdf.groupby("a").filter(lambda df: len(df) > 2) got = df.groupby("a").filter(lambda df: len(df) > 2) tm.assert_frame_equal(expected, got) def test_groupby_rolling(dataframe): pdf, df = dataframe expected = pdf.groupby("a").rolling(2).sum() got = df.groupby("a").rolling(2).sum() tm.assert_frame_equal(expected, got) def test_groupby_rolling_window(dataframe): pdf, df = dataframe expected = pdf.groupby("a").rolling(2, win_type="triang").mean() got = df.groupby("a").rolling(2, win_type="triang").mean() tm.assert_frame_equal(expected, got) def test_ewm(): pdf = pd.DataFrame(range(5)) df = xpd.DataFrame(range(5)) result = df.ewm(0.5).mean() expected = pdf.ewm(0.5).mean() tm.assert_equal(result, expected) def test_setitem_frame(dataframe): pdf, df = dataframe pdf[pdf > 1] = -pdf df[df > 1] = -df tm.assert_frame_equal(pdf, df) def test_concat(dataframe): pdf, df = dataframe expected = pd.concat([pdf, pdf]) got = xpd.concat([df, df]) tm.assert_frame_equal(expected, got) def test_attribute_error(): df = xpd.DataFrame() with pytest.raises(AttributeError): df.blah def test_df_from_series(series): psr, sr = series tm.assert_frame_equal(pd.DataFrame(psr), xpd.DataFrame(sr)) def test_iloc_change_type(series): psr, sr = series psr.iloc[0] = "a" sr.iloc[0] = "a" tm.assert_series_equal(psr, sr) def test_rename_categories(): psr = pd.Series([1, 2, 3], dtype="category") sr = xpd.Series([1, 2, 3], dtype="category") psr = psr.cat.rename_categories({1: 5}) sr = sr.cat.rename_categories({1: 5}) tm.assert_series_equal(psr, sr) def test_rename_categories_inplace(): psr = pd.Series([1, 2, 3], dtype="category") sr = xpd.Series([1, 2, 3], dtype="category") with pytest.warns(FutureWarning): psr.cat.rename_categories({1: 5}, inplace=True) sr.cat.rename_categories({1: 5}, inplace=True) tm.assert_series_equal(psr, sr) def test_rename_categories_inplace_after_copying_parent(): s = xpd.Series([1, 2, 3], dtype="category") # cudf does not define "rename_categories", # so this copies `s` from device to host: rename_categories = s.cat.rename_categories _ = len(s) # trigger a copy of `s` from host to device: with pytest.warns(FutureWarning): rename_categories([5, 2, 3], inplace=True) assert s.cat.categories.tolist() == [5, 2, 3] def test_column_rename(dataframe): pdf, df = dataframe pdf.columns = ["x", "y"] df.columns = ["x", "y"] tm.assert_frame_equal(pdf, df) def test_shape(dataframe): pdf, df = dataframe assert pdf.shape == df.shape pdf["c"] = range(5) df["c"] = range(5) assert pdf.shape == df.shape def test_isnull(): psr = pd.Series([1, 2, 3]) sr = xpd.Series(psr) # Test that invoking `Pandas` functions works. tm.assert_series_equal(pd.isnull(psr), xpd.isnull(sr)) def test_copy_deepcopy_recursion(dataframe): # test that we don't recurse when calling the copy/deepcopy # methods, which can happen due to # https://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html import copy pdf, df = dataframe copy.copy(df) copy.deepcopy(df) @pytest.mark.parametrize("copier", [copy.copy, copy.deepcopy]) def test_copy_deepcopy(copier): s = xpd.Series([1, 2, 3]) s2 = copier(s) assert isinstance(s2, s.__class__) tm.assert_equal(s, s2) df = xpd.DataFrame({"a": [1, 2, 3]}) df2 = copier(df) assert isinstance(df2, df.__class__) tm.assert_equal(df, df2) idx = xpd.Index([1, 2, 3]) idx2 = copier(idx) assert isinstance(idx2, idx.__class__) tm.assert_equal(idx, idx2) def test_classmethod(): pdf = pd.DataFrame.from_dict({"a": [1, 2, 3]}) df = xpd.DataFrame.from_dict({"a": [1, 2, 3]}) tm.assert_frame_equal(pdf, df) def test_rolling(dataframe): pdf, df = dataframe tm.assert_frame_equal(pdf.rolling(2).agg("sum"), df.rolling(2).agg("sum")) def test_array_function_series(series): psr, sr = series np.testing.assert_allclose(np.average(psr), np.average(sr)) def test_array_function_ndarray(array): arr, xarr = array np.isclose(np.average(arr), np.average(xarr)) def test_histogram_ndarray(array): arr, xarr = array expected_hist, expected_edges = np.histogram(arr, bins="auto") got_hist, got_edges = np.histogram(xarr, bins="auto") tm.assert_almost_equal(expected_hist, got_hist) tm.assert_almost_equal(expected_edges, got_edges) def test_pickle_round_trip(dataframe): pdf, df = dataframe pickled_pdf = BytesIO() pickled_cudf_pandas = BytesIO() pdf.to_pickle(pickled_pdf) df.to_pickle(pickled_cudf_pandas) pickled_pdf.seek(0) pickled_cudf_pandas.seek(0) tm.assert_frame_equal( pd.read_pickle(pickled_pdf), xpd.read_pickle(pickled_cudf_pandas) ) def test_excel_round_trip(dataframe): pdf, df = dataframe excel_pdf = BytesIO() excel_cudf_pandas = BytesIO() pdf.to_excel(excel_pdf) df.to_excel(excel_cudf_pandas) excel_pdf.seek(0) excel_cudf_pandas.seek(0) tm.assert_frame_equal( pd.read_excel(excel_pdf), xpd.read_excel(excel_cudf_pandas) ) def test_hash_array(series): ps, xs = series expected = pd.util.hash_array(ps.values) actual = xpd.util.hash_array(xs.values) tm.assert_almost_equal(expected, actual) def test_is_sparse(): psa = pd.arrays.SparseArray([0, 0, 1, 0]) xsa = xpd.arrays.SparseArray([0, 0, 1, 0]) assert pd.api.types.is_sparse(psa) == xpd.api.types.is_sparse(xsa) def test_is_file_like(): assert pd.api.types.is_file_like("a") == xpd.api.types.is_file_like("a") assert pd.api.types.is_file_like(BytesIO()) == xpd.api.types.is_file_like( BytesIO() ) assert pd.api.types.is_file_like( StringIO("abc") ) == xpd.api.types.is_file_like(StringIO("abc")) def test_is_re_compilable(): assert pd.api.types.is_re_compilable( ".^" ) == xpd.api.types.is_re_compilable(".^") assert pd.api.types.is_re_compilable( ".*" ) == xpd.api.types.is_re_compilable(".*") def test_module_attribute_types(): assert isinstance(xpd.read_csv, types.FunctionType) assert isinstance(xpd.tseries.frequencies.Day, type) assert isinstance(xpd.api, types.ModuleType) def test_infer_freq(): expected = pd.infer_freq( pd.date_range(start="2020/12/01", end="2020/12/30", periods=30) ) got = xpd.infer_freq( xpd.date_range(start="2020/12/01", end="2020/12/30", periods=30) ) assert expected == got def test_groupby_grouper_fallback(dataframe, groupby_udf): pdf, df = dataframe tm.assert_equal( pdf.groupby(pd.Grouper("a"), sort=True, group_keys=True).apply( groupby_udf ), df.groupby(xpd.Grouper("a"), sort=True, group_keys=True).apply( groupby_udf ), ) def test_options_mode(): assert xpd.options.mode.copy_on_write == pd.options.mode.copy_on_write def test_profiler(): pytest.importorskip("cudf") # test that the profiler correctly reports # when we use the GPU v/s CPU with Profiler() as p: df = xpd.DataFrame({"a": [1, 2, 3], "b": "b"}) df.groupby("a").max() assert len(p.per_line_stats) == 2 for line_no, line, gpu_time, cpu_time in p.per_line_stats: assert gpu_time assert not cpu_time with Profiler() as p: s = xpd.Series([1, "a"]) s = s + s assert len(p.per_line_stats) == 2 for line_no, line, gpu_time, cpu_time in p.per_line_stats: assert cpu_time def test_column_access_as_attribute(): pdf = pd.DataFrame({"fast": [1, 2, 3], "slow": [2, 3, 4]}) df = xpd.DataFrame({"fast": [1, 2, 3], "slow": [2, 3, 4]}) tm.assert_series_equal(pdf.fast, df.fast) tm.assert_series_equal(pdf.slow, df.slow) def test_binop_dataframe_list(dataframe): pdf, df = dataframe expect = pdf[["a"]] == [[1, 2, 3, 4, 5]] got = df[["a"]] == [[1, 2, 3, 4, 5]] tm.assert_frame_equal(expect, got) def test_binop_array_series(series): psr, sr = series arr = psr.array expect = arr + psr got = arr + sr tm.assert_series_equal(expect, got) def test_array_ufunc_reduction(series): psr, sr = series expect = np.ufunc.reduce(np.subtract, psr) got = np.ufunc.reduce(np.subtract, sr) tm.assert_equal(expect, got) def test_array_ufunc(series): psr, sr = series expect = np.subtract(psr, psr) got = np.subtract(sr, sr) assert isinstance(got, sr.__class__) tm.assert_equal(expect, got) def test_groupby_apply_func_returns_series(dataframe): pdf, df = dataframe expect = pdf.groupby("a").apply(lambda group: pd.Series({"x": 1})) got = df.groupby("a").apply(lambda group: xpd.Series({"x": 1})) tm.assert_equal(expect, got) @pytest.mark.parametrize("data", [[1, 2, 3], ["a", None, "b"]]) def test_pyarrow_array_construction(data): cudf_pandas_series = xpd.Series(data) actual_pa_array = pa.array(cudf_pandas_series) expected_pa_array = pa.array(data) assert actual_pa_array.equals(expected_pa_array) @pytest.mark.parametrize( "op", [">", "<", "==", "<=", ">=", "+", "%", "-", "*", "/"] ) def test_cudf_pandas_eval_series(op): lhs = xpd.Series([10, 11, 12]) # noqa: F841 rhs = xpd.Series([100, 1, 12]) # noqa: F841 actual = xpd.eval(f"lhs {op} rhs") pd_lhs = pd.Series([10, 11, 12]) # noqa: F841 pd_rhs = pd.Series([100, 1, 12]) # noqa: F841 expected = pd.eval(f"pd_lhs {op} pd_rhs") tm.assert_series_equal(expected, actual) @pytest.mark.parametrize( "op", [">", "<", "==", "<=", ">=", "+", "%", "-", "*", "/"] ) def test_cudf_pandas_eval_dataframe(op): lhs = xpd.DataFrame({"a": [10, 11, 12], "b": [1, 2, 3]}) # noqa: F841 rhs = xpd.DataFrame({"a": [100, 1, 12], "b": [15, -10, 3]}) # noqa: F841 actual = xpd.eval(f"lhs {op} rhs") pd_lhs = pd.DataFrame({"a": [10, 11, 12], "b": [1, 2, 3]}) # noqa: F841 pd_rhs = pd.DataFrame({"a": [100, 1, 12], "b": [15, -10, 3]}) # noqa: F841 expected = pd.eval(f"pd_lhs {op} pd_rhs") tm.assert_frame_equal(expected, actual) @pytest.mark.parametrize( "expr", ["((a + b) * c % d) > e", "((a + b) * c % d)"] ) def test_cudf_pandas_eval_complex(expr): data = { "a": [10, 11, 12], "b": [1, 2, 3], "c": [100, 1, 12], "d": [15, -10, 3], "e": [100, 200, 300], } cudf_pandas_frame = xpd.DataFrame(data) pd_frame = pd.DataFrame(data) actual = cudf_pandas_frame.eval(expr) expected = pd_frame.eval(expr) tm.assert_series_equal(expected, actual) def test_array_function_series_fallback(series): psr, sr = series expect = np.unique(psr, return_counts=True) got = np.unique(sr, return_counts=True) tm.assert_equal(expect, got) def test_timedeltaproperties(series): psr, sr = series psr, sr = psr.astype("timedelta64[ns]"), sr.astype("timedelta64[ns]") tm.assert_equal(psr.dt.days, sr.dt.days) tm.assert_equal(psr.dt.components, sr.dt.components) tm.assert_equal(psr.dt.total_seconds(), sr.dt.total_seconds()) @pytest.mark.parametrize("scalar_type", [int, float, complex, bool]) @pytest.mark.parametrize("scalar", [1, 1.0, True, 0]) def test_coerce_zero_d_array_to_scalar(scalar_type, scalar): expected = scalar_type(pd.Series([scalar]).values[0]) got = scalar_type(xpd.Series([scalar]).values[0]) tm.assert_equal(expected, got) def test_cupy_asarray_zero_copy(): cp = pytest.importorskip("cupy") sr = xpd.Series([1, 2, 3]) cpary = cp.asarray(sr.values) assert ( sr.__cuda_array_interface__["data"][0] == cpary.__cuda_array_interface__["data"][0] ) def test_pipe(dataframe): pdf, df = dataframe def func(df, x): return df + x expect = pdf.pipe(func, 1) got = df.pipe(func, 1) tm.assert_frame_equal(expect, got) def test_pipe_tuple(dataframe): pdf, df = dataframe def func(x, df): return df + x expect = pdf.pipe((func, "df"), 1) got = df.pipe((func, "df"), 1) tm.assert_frame_equal(expect, got) def test_maintain_container_subclasses(multiindex): # pandas Frozenlist is a list subclass pmi, mi = multiindex got = mi.names.difference(["b"]) expect = pmi.names.difference(["b"]) assert got == expect assert isinstance(got, xpd.core.indexes.frozen.FrozenList) def test_rolling_win_type(): pdf = pd.DataFrame(range(5)) df = xpd.DataFrame(range(5)) result = df.rolling(2, win_type="boxcar").mean() with pytest.warns(DeprecationWarning): expected = pdf.rolling(2, win_type="boxcar").mean() tm.assert_equal(result, expected) def test_rolling_apply_numba_engine(): def weighted_mean(x): arr = np.ones((1, x.shape[1])) arr[:, :2] = (x[:, :2] * x[:, 2]).sum(axis=0) / x[:, 2].sum() return arr pdf = pd.DataFrame([[1, 2, 0.6], [2, 3, 0.4], [3, 4, 0.2], [4, 5, 0.7]]) df = xpd.DataFrame([[1, 2, 0.6], [2, 3, 0.4], [3, 4, 0.2], [4, 5, 0.7]]) with pytest.warns(NumbaDeprecationWarning): expect = pdf.rolling(2, method="table", min_periods=0).apply( weighted_mean, raw=True, engine="numba" ) got = df.rolling(2, method="table", min_periods=0).apply( weighted_mean, raw=True, engine="numba" ) tm.assert_equal(expect, got) def test_expanding(): pdf = pd.DataFrame(range(5)) df = xpd.DataFrame(range(5)) result = df.expanding().mean() expected = pdf.expanding().mean() tm.assert_equal(result, expected) def test_pipe_with_data_creating_func(): def pandas_func(df): df2 = pd.DataFrame({"b": np.arange(len(df))}) return df.join(df2) def cudf_pandas_func(df): df2 = xpd.DataFrame({"b": np.arange(len(df))}) return df.join(df2) pdf = pd.DataFrame({"a": [1, 2, 3]}) df = xpd.DataFrame({"a": [1, 2, 3]}) tm.assert_frame_equal(pdf.pipe(pandas_func), df.pipe(cudf_pandas_func)) @pytest.mark.parametrize( "data", [ '{"a": 1, "b": 2, "c": 3}', '{"a": 1, "b": 2, "c": 3}\n{"a": 4, "b": 5, "c": 6}', ], ) def test_chunked_json_reader(tmpdir, data): file_path = tmpdir / "test.json" with open(file_path, "w") as f: f.write(data) with ( pd.read_json(file_path, lines=True, chunksize=1) as pd_reader, xpd.read_json(file_path, lines=True, chunksize=1) as xpd_reader, ): for pd_chunk, xpd_chunk in zip(pd_reader, xpd_reader): tm.assert_equal(pd_chunk, xpd_chunk) with ( pd.read_json(StringIO(data), lines=True, chunksize=1) as pd_reader, xpd.read_json(StringIO(data), lines=True, chunksize=1) as xpd_reader, ): for pd_chunk, xpd_chunk in zip(pd_reader, xpd_reader): tm.assert_equal(pd_chunk, xpd_chunk) @pytest.mark.parametrize( "data", [ "1,2,3", "1,2,3\n4,5,6", ], ) def test_chunked_csv_reader(tmpdir, data): file_path = tmpdir / "test.json" with open(file_path, "w") as f: f.write(data) with ( pd.read_csv(file_path, chunksize=1) as pd_reader, xpd.read_csv(file_path, chunksize=1) as xpd_reader, ): for pd_chunk, xpd_chunk in zip(pd_reader, xpd_reader): tm.assert_equal(pd_chunk, xpd_chunk, check_index_type=False) with ( pd.read_json(StringIO(data), lines=True, chunksize=1) as pd_reader, xpd.read_json(StringIO(data), lines=True, chunksize=1) as xpd_reader, ): for pd_chunk, xpd_chunk in zip(pd_reader, xpd_reader): tm.assert_equal(pd_chunk, xpd_chunk, check_index_type=False) @pytest.mark.parametrize( "data", [(), (1,), (1, 2, 3), ("a", "b", "c"), (1, 2, "test")] ) def test_construct_from_generator(data): expect = pd.Series((x for x in data)) got = xpd.Series((x for x in data)) tm.assert_series_equal(expect, got) def test_read_csv_stringio_usecols(): data = "col1,col2,col3\na,b,1\na,b,2\nc,d,3" expect = pd.read_csv(StringIO(data), usecols=lambda x: x.upper() != "COL3") got = xpd.read_csv(StringIO(data), usecols=lambda x: x.upper() != "COL3") tm.assert_frame_equal(expect, got) def test_construct_datetime_index(): expect = pd.DatetimeIndex([10, 20, 30], dtype="datetime64[ns]") got = xpd.DatetimeIndex([10, 20, 30], dtype="datetime64[ns]") tm.assert_index_equal(expect, got) def test_construct_timedelta_index(): expect = pd.TimedeltaIndex([10, 20, 30], dtype="timedelta64[ns]") got = xpd.TimedeltaIndex([10, 20, 30], dtype="timedelta64[ns]") tm.assert_index_equal(expect, got) @pytest.mark.parametrize( "op", [ operator.eq, operator.sub, operator.lt, operator.gt, operator.le, operator.ge, ], ) def test_datetime_ops(op): pd_dt_idx1 = pd.DatetimeIndex([10, 20, 30], dtype="datetime64[ns]") cudf_pandas_dt_idx = xpd.DatetimeIndex( [10, 20, 30], dtype="datetime64[ns]" ) tm.assert_equal( op(pd_dt_idx1, pd_dt_idx1), op(cudf_pandas_dt_idx, cudf_pandas_dt_idx) ) @pytest.mark.parametrize( "op", [ operator.eq, operator.add, operator.sub, operator.lt, operator.gt, operator.le, operator.ge, ], ) def test_timedelta_ops(op): pd_td_idx1 = pd.TimedeltaIndex([10, 20, 30], dtype="timedelta64[ns]") cudf_pandas_td_idx = xpd.TimedeltaIndex( [10, 20, 30], dtype="timedelta64[ns]" ) tm.assert_equal( op(pd_td_idx1, pd_td_idx1), op(cudf_pandas_td_idx, cudf_pandas_td_idx) ) @pytest.mark.parametrize("op", [operator.add, operator.sub]) def test_datetime_timedelta_ops(op): pd_dt_idx1 = pd.DatetimeIndex([10, 20, 30], dtype="datetime64[ns]") cudf_pandas_dt_idx = xpd.DatetimeIndex( [10, 20, 30], dtype="datetime64[ns]" ) pd_td_idx1 = pd.TimedeltaIndex([10, 20, 30], dtype="timedelta64[ns]") cudf_pandas_td_idx = xpd.TimedeltaIndex( [10, 20, 30], dtype="timedelta64[ns]" ) tm.assert_equal( op(pd_dt_idx1, pd_td_idx1), op(cudf_pandas_dt_idx, cudf_pandas_td_idx) ) def test_itertuples(): df = xpd.DataFrame(range(1)) result = next(iter(df.itertuples())) tup = collections.namedtuple("Pandas", ["Index", "1"], rename=True) expected = tup(0, 0) assert result == expected assert result._fields == expected._fields def test_namedagg_namedtuple(): df = xpd.DataFrame( { "kind": ["cat", "dog", "cat", "dog"], "height": [9.1, 6.0, 9.5, 34.0], "weight": [7.9, 7.5, 9.9, 198.0], } ) result = df.groupby("kind").agg( min_height=pd.NamedAgg(column="height", aggfunc="min"), max_height=pd.NamedAgg(column="height", aggfunc="max"), average_weight=pd.NamedAgg(column="weight", aggfunc=np.mean), ) expected = xpd.DataFrame( { "min_height": [9.1, 6.0], "max_height": [9.5, 34.0], "average_weight": [8.90, 102.75], }, index=xpd.Index(["cat", "dog"], name="kind"), ) tm.assert_frame_equal(result, expected) def test_dataframe_dir(dataframe): """Test that column names are present in the dataframe dir We do not test direct dir equality because pandas does some runtime modifications of dir that we cannot replicate without forcing D2H conversions (e.g. modifying what elements are visible based on the contents of a DataFrame instance). """ _, df = dataframe assert "a" in dir(df) assert "b" in dir(df) # Only string types are added to dir df[1] = [1] * len(df) assert 1 not in dir(df) def test_array_copy(array): arr, xarr = array tm.assert_equal(copy.copy(arr), copy.copy(xarr)) def test_datetime_values_dtype_roundtrip(): s = pd.Series([1, 2, 3], dtype="datetime64[ns]") xs = xpd.Series([1, 2, 3], dtype="datetime64[ns]") expected = np.asarray(s.values) actual = np.asarray(xs.values) assert expected.dtype == actual.dtype tm.assert_equal(expected, actual) def test_resample(): ser = pd.Series( range(3), index=pd.date_range("2020-01-01", freq="D", periods=3) ) xser = xpd.Series( range(3), index=xpd.date_range("2020-01-01", freq="D", periods=3) ) expected = ser.resample("D").max() result = xser.resample("D").max() tm.assert_series_equal(result, expected) @pytest.mark.parametrize("accessor", ["str", "dt", "cat"]) def test_accessor_types(accessor): assert isinstance(getattr(xpd.Series, accessor), type) @pytest.mark.parametrize( "op", [operator.itemgetter(1), operator.methodcaller("sum")], ids=["getitem[1]", ".sum()"], ) def test_values_zero_dim_result_is_scalar(op): s = pd.Series([1, 2, 3]) x = xpd.Series([1, 2, 3]) expect = op(s.values) got = op(x.values) assert expect == got assert type(expect) is type(got) @pytest.mark.parametrize("box", ["DataFrame", "Series"]) def test_round_builtin(box): xobj = getattr(xpd, box)([1.23]) pobj = getattr(pd, box)([1.23]) result = round(xobj, 1) expected = round(pobj, 1) tm.assert_equal(result, expected) def test_hash(): xobj = xpd.Timedelta(1) pobj = pd.Timedelta(1) assert hash(xobj) == hash(pobj) def test_non_hashable_object(): with pytest.raises(TypeError): hash(pd.DataFrame(range(1))) with pytest.raises(TypeError): hash(xpd.DataFrame(range(1))) @pytest.mark.parametrize("offset", ["DateOffset", "Day", "BDay"]) def test_timestamp_offset_binop(offset): ts = xpd.Timestamp(2020, 1, 1) result = ts + getattr(xpd.offsets, offset)() expected = pd.Timestamp(2020, 1, 2) tm.assert_equal(result, expected) def test_string_dtype(): xobj = xpd.StringDtype() pobj = pd.StringDtype() tm.assert_equal(xobj, pobj) def test_string_array(): data = np.array(["1"], dtype=object) xobj = xpd.arrays.StringArray(data) pobj = pd.arrays.StringArray(data) tm.assert_extension_array_equal(xobj, pobj) def test_subclass_series(): class foo(pd.Series): def __init__(self, myinput): super().__init__(myinput) s1 = pd.Series([1, 2, 3]) s2 = foo(myinput=[1, 2, 3]) tm.assert_equal(s1, s2, check_series_type=False) @pytest.mark.parametrize( "index_type", [ xpd.RangeIndex, xpd.CategoricalIndex, xpd.DatetimeIndex, xpd.TimedeltaIndex, xpd.PeriodIndex, xpd.MultiIndex, xpd.IntervalIndex, xpd.UInt64Index, xpd.Int64Index, xpd.Float64Index, xpd.core.indexes.numeric.UInt64Index, xpd.core.indexes.numeric.Int64Index, xpd.core.indexes.numeric.Float64Index, ], ) def test_index_subclass(index_type): # test that proxy index types are derived # from Index assert issubclass(index_type, xpd.Index) assert not issubclass(xpd.Index, index_type) def test_index_internal_subclass(): # test that proxy index types that are not related by inheritance # still appear to be so if the underlying slow types are related # by inheritance: assert issubclass( xpd.Int64Index, xpd.core.indexes.numeric.NumericIndex, ) == issubclass( pd.Int64Index, pd.core.indexes.numeric.NumericIndex, ) assert isinstance( xpd.Index([1, 2, 3]), xpd.core.indexes.numeric.NumericIndex ) == isinstance(pd.Index([1, 2, 3]), pd.core.indexes.numeric.NumericIndex) def test_np_array_of_timestamps(): expected = np.array([pd.Timestamp(1)]) + pd.tseries.offsets.MonthEnd() got = np.array([xpd.Timestamp(1)]) + xpd.tseries.offsets.MonthEnd() tm.assert_equal(expected, got) @pytest.mark.parametrize( "obj", [ # Basic types xpd.Series(dtype="float64"), xpd.Series([1, 2, 3]), xpd.DataFrame(dtype="float64"), xpd.DataFrame({"a": [1, 2, 3]}), xpd.Series([1, 2, 3]), # Index (doesn't support nullary construction) xpd.Index([1, 2, 3]), xpd.Index(["a", "b", "c"]), # Complex index xpd.to_datetime( [ "1/1/2018", np.datetime64("2018-01-01"), datetime.datetime(2018, 1, 1), ] ), # Objects where the underlying store is the slow type. xpd.Series(["a", 2, 3]), xpd.Index(["a", 2, 3]), # Other types xpd.tseries.offsets.BDay(5), ], ) def test_pickle(obj): with tempfile.TemporaryFile() as f: pickle.dump(obj, f) f.seek(0) copy = pickle.load(f) tm.assert_equal(obj, copy) def test_dataframe_query(): cudf_pandas_df = xpd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]}) pd_df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]}) actual = cudf_pandas_df.query("foo > 2") expected = pd_df.query("foo > 2") tm.assert_equal(actual, expected) bizz = 2 # noqa: F841 actual = cudf_pandas_df.query("foo > @bizz") expected = pd_df.query("foo > @bizz") tm.assert_equal(actual, expected) def test_numpy_var(): np.random.seed(42) data = np.random.rand(1000) psr = pd.Series(data) sr = xpd.Series(data) tm.assert_almost_equal(np.var(psr), np.var(sr)) def test_index_new(): expected = pd.Index.__new__(pd.Index, [1, 2, 3]) got = xpd.Index.__new__(xpd.Index, [1, 2, 3]) tm.assert_equal(expected, got) expected = pd.Index.__new__(pd.Index, [1, 2, 3], dtype="int8") got = xpd.Index.__new__(xpd.Index, [1, 2, 3], dtype="int8") tm.assert_equal(expected, got) expected = pd.RangeIndex.__new__(pd.RangeIndex, 0, 10, 2) got = xpd.RangeIndex.__new__(xpd.RangeIndex, 0, 10, 2) tm.assert_equal(expected, got) @pytest.mark.xfail(not LOADED, reason="Should not fail in accelerated mode") def test_groupby_apply_callable_referencing_pandas(dataframe): pdf, df = dataframe class Callable1: def __call__(self, df): if not isinstance(df, pd.DataFrame): raise TypeError return 1 class Callable2: def __call__(self, df): if not isinstance(df, xpd.DataFrame): raise TypeError return 1 expect = pdf.groupby("a").apply(Callable1()) got = df.groupby("a").apply(Callable2()) tm.assert_equal(expect, got) def test_constructor_properties(dataframe, series, index): _, df = dataframe _, sr = series _, idx = index assert df._constructor is xpd.DataFrame assert sr._constructor is xpd.Series assert idx._constructor is xpd.Index assert sr._constructor_expanddim is xpd.DataFrame assert df._constructor_sliced is xpd.Series def test_pos(): xser = +xpd.Series([-1]) ser = +pd.Series([-1]) tm.assert_equal(xser, ser) def test_intermediates_are_proxied(): df = xpd.DataFrame({"a": [1, 2, 3]}) grouper = df.groupby("a") assert isinstance(grouper, xpd.core.groupby.generic.DataFrameGroupBy) def test_from_dataframe(): cudf = pytest.importorskip("cudf") from cudf.testing._utils import assert_eq data = {"foo": [1, 2, 3], "bar": [4, 5, 6]} cudf_pandas_df = xpd.DataFrame(data) cudf_df = cudf.DataFrame(data) # test construction of a cuDF DataFrame from an cudf_pandas DataFrame assert_eq(cudf_df, cudf.DataFrame.from_pandas(cudf_pandas_df)) assert_eq(cudf_df, cudf.from_dataframe(cudf_pandas_df)) # ideally the below would work as well, but currently segfaults # pd_df = pd.DataFrame(data) # assert_eq(pd_df, pd.api.interchange.from_dataframe(cudf_pandas_df)) def test_multiindex_values_returns_1d_tuples(): mi = xpd.MultiIndex.from_tuples([(1, 2), (3, 4)]) result = mi.values expected = np.empty(2, dtype=object) expected[...] = [(1, 2), (3, 4)] tm.assert_equal(result, expected) def test_read_sas_context(): cudf_path = pathlib.Path(__file__).parent.parent path = cudf_path / "cudf" / "tests" / "data" / "sas" / "cars.sas7bdat" with xpd.read_sas(path, format="sas7bdat", iterator=True) as reader: df = reader.read() assert isinstance(df, xpd.DataFrame) @pytest.mark.parametrize( "idx_obj", ["Float64Index", "Int64Index", "UInt64Index"] ) def test_pandas_module_getattr_objects(idx_obj): # Objects that are behind pandas.__getattr__ (version 1.5 specific) idx = getattr(xpd, idx_obj)([1, 2, 3]) assert isinstance(idx, xpd.Index) def test_concat_fast(): pytest.importorskip("cudf") assert type(xpd.concat._fsproxy_fast) is not _Unusable def test_func_namespace(): # note: this test is sensitive to Pandas' internal module layout assert xpd.concat is xpd.core.reshape.concat.concat
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_fast_slow_proxy.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 import inspect from functools import partial from io import StringIO import numpy as np import pytest from cudf.pandas.fast_slow_proxy import ( _fast_arg, _FunctionProxy, _slow_arg, _transform_arg, _Unusable, make_final_proxy_type, make_intermediate_proxy_type, ) @pytest.fixture def final_proxy(): class Fast: def __init__(self, x): self.x = x def to_slow(self): return Slow(self.x) @classmethod def from_slow(cls, slow): return cls(slow) def __eq__(self, other): return self.x == other.x def method(self): return "fast method" class Slow: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def method(self): return "slow method" Pxy = make_final_proxy_type( "Pxy", Fast, Slow, fast_to_slow=lambda fast: fast.to_slow(), slow_to_fast=lambda slow: Fast.from_slow(slow), ) return Fast(1), Slow(1), Pxy(1) @pytest.fixture def function_proxy(): def fast_func(): """ Fast doc """ return "fast func" def slow_func(): """ Slow doc """ return "slow_func" return fast_func, slow_func, _FunctionProxy(fast_func, slow_func) def test_repr_no_fast_object(): # test that __repr__ falls back to slow object # when we don't have a corresponding fast object: class Slow: def __repr__(self): return "slow object" Pxy = make_final_proxy_type( "Pxy", _Unusable, Slow, fast_to_slow=lambda fast: Slow(), slow_to_fast=lambda slow: _Unusable(), ) assert repr(Pxy()) == repr(Slow()) def test_fast_slow_arg_function_basic(): def func1(): return 1 assert _fast_arg(func1)() == _slow_arg(func1)() == 1 def func2(x, y): return x + y assert _fast_arg(func2)(1, 2) == _slow_arg(func2)(1, 2) == 3 def test_fast_slow_arg_function_closure(function_proxy, final_proxy): fast_x, slow_x, x = function_proxy fast_y, slow_y, y = final_proxy def func(): return x, y.method() assert _slow_arg(func)() == (slow_x, slow_y.method()) assert _fast_arg(func)() == (fast_x, fast_y.method()) def test_fast_slow_arg_function_global( monkeypatch, function_proxy, final_proxy ): fast_x, slow_x, x = function_proxy fast_y, slow_y, y = final_proxy # temporarily set x, y as globals monkeypatch.setitem(globals(), "__x", x) monkeypatch.setitem(globals(), "__y", y) def func(): global __x, __y return __x, __y.method() assert _slow_arg(func)() == (slow_x, slow_y.method()) assert _fast_arg(func)() == (fast_x, fast_y.method()) def test_fast_slow_arg_function_np(): # test that _fast_arg() and _slow_arg() return "externally" # defined functions like numpy functions as-is: assert _slow_arg(np.mean) is np.mean assert _slow_arg(np.unique) is np.unique assert _fast_arg(np.mean) is np.mean assert _fast_arg(np.unique) is np.unique def test_fast_slow_arg_builtins(function_proxy): # test that builtins are accessible in the result of # _fast_arg() and _slow_arg() _, _, x = function_proxy def func(): x # nonlocal x ensures _fast_arg() makes a copy return len([1]) assert _slow_arg(func)() == 1 assert _fast_arg(func)() == 1 def test_function_proxy_decorating_super_method(): # test that we can use a function proxy as a decorator to a method # that invokes super() (GH: #254) deco = _FunctionProxy(_Unusable(), lambda func: func) class Foo: @deco def method(self): super() @pytest.mark.xfail( reason="Mutually recursive functions are known to be handled incorrectly." ) def test_fast_slow_arg_recursion(final_proxy): fast_x, slow_x, x = final_proxy def foo(n): if n <= 0: return x else: return bar(n - 1) def bar(n): return foo(n - 1) assert _slow_arg(foo)(0) == slow_x assert _slow_arg(bar)(1) == slow_x assert _slow_arg(foo)(1) == slow_x assert _slow_arg(bar)(2) == slow_x assert _fast_arg(foo)(0) == fast_x assert _fast_arg(bar)(1) == fast_x assert _fast_arg(foo)(1) == fast_x assert _fast_arg(bar)(2) == fast_x def test_fallback_with_stringio(): def slow(s): return s.read() def fast(s): s.read() raise ValueError() pxy = _FunctionProxy(fast=fast, slow=slow) assert pxy(StringIO("hello")) == "hello" def test_access_class(): def func(): pass pxy = _FunctionProxy(fast=_Unusable(), slow=func) pxy.__class__ def test_class_attribute_error(final_proxy, function_proxy): _, _, x = final_proxy _, _, y = function_proxy # Test that an attribute error is raised when attempting to # access undefined class attributes: with pytest.raises(AttributeError): x.foo with pytest.raises(AttributeError): y.foo with pytest.raises(AttributeError): y.__abs__ def test_function_proxy_doc(function_proxy): _, slow, pxy = function_proxy assert pxy.__doc__ == slow.__doc__ def test_special_methods(): class Fast: def __abs__(self): pass def __gt__(self): pass class Slow: def __gt__(self): pass Pxy = make_final_proxy_type( "Pxy", Fast, Slow, fast_to_slow=lambda _: Slow(), slow_to_fast=lambda _: Fast(), ) # test that special methods defined _only_ on the # fast type are not accessible on the proxy: assert not hasattr(Pxy, "__abs__") assert not hasattr(Pxy(), "__abs__") # test that special methods defined on the # slow type are accessible on the proxy: assert hasattr(Pxy, "__gt__") assert hasattr(Pxy(), "__gt__") @pytest.fixture(scope="module") def fast_and_intermediate_with_doc(): class FastIntermediate: """The fast intermediate docstring.""" def method(self): """The fast intermediate method docstring.""" class Fast: """The fast docstring.""" @property def prop(self): """The fast property docstring.""" def method(self): """The fast method docstring.""" def intermediate(self): """The fast intermediate docstring.""" return FastIntermediate() return Fast, FastIntermediate @pytest.fixture(scope="module") def slow_and_intermediate_with_doc(): class SlowIntermediate: """The slow intermediate docstring.""" def method(self): """The slow intermediate method docstring.""" class Slow: """The slow docstring.""" @property def prop(self): """The slow property docstring.""" def method(self): """The slow method docstring.""" def intermediate(self): """The slow intermediate docstring.""" return SlowIntermediate() return Slow, SlowIntermediate def test_doc(fast_and_intermediate_with_doc, slow_and_intermediate_with_doc): Fast, FastIntermediate = fast_and_intermediate_with_doc Slow, SlowIntermediate = slow_and_intermediate_with_doc Pxy = make_final_proxy_type( "Pxy", Fast, Slow, fast_to_slow=lambda _: Slow(), slow_to_fast=lambda _: Fast(), ) IntermediatePxy = make_intermediate_proxy_type( # noqa: F841 "IntermediatePxy", FastIntermediate, SlowIntermediate, ) assert inspect.getdoc(Pxy) == inspect.getdoc(Slow) assert inspect.getdoc(Pxy()) == inspect.getdoc(Slow()) assert inspect.getdoc(Pxy.prop) == inspect.getdoc(Slow.prop) assert inspect.getdoc(Pxy().prop) == inspect.getdoc(Slow().prop) assert inspect.getdoc(Pxy.method) == inspect.getdoc(Slow.method) assert inspect.getdoc(Pxy().method) == inspect.getdoc(Slow().method) assert inspect.getdoc(Pxy().intermediate()) == inspect.getdoc( Slow().intermediate() ) assert inspect.getdoc(Pxy().intermediate().method) == inspect.getdoc( Slow().intermediate().method ) def test_dir(fast_and_intermediate_with_doc, slow_and_intermediate_with_doc): Fast, FastIntermediate = fast_and_intermediate_with_doc Slow, SlowIntermediate = slow_and_intermediate_with_doc Pxy = make_final_proxy_type( "Pxy", Fast, Slow, fast_to_slow=lambda _: Slow(), slow_to_fast=lambda _: Fast(), ) IntermediatePxy = make_intermediate_proxy_type( # noqa: F841 "IntermediatePxy", FastIntermediate, SlowIntermediate, ) assert dir(Pxy) == dir(Slow) assert dir(Pxy()) == dir(Slow()) assert dir(Pxy.prop) == dir(Slow.prop) assert dir(Pxy().prop) == dir(Slow().prop) assert dir(Pxy.method) == dir(Slow.method) assert dir(Pxy().intermediate()) == dir(Slow().intermediate()) @pytest.mark.xfail @pytest.mark.parametrize( "check", [ lambda Pxy, Slow: dir(Pxy().method) == dir(Slow().method), lambda Pxy, Slow: dir(Pxy().intermediate().method) == dir(Slow().intermediate().method), ], ) def test_dir_bound_method( fast_and_intermediate_with_doc, slow_and_intermediate_with_doc, check ): """This test will fail because dir for bound methods is currently incorrect, but we have no way to fix it without materializing the slow type, which is unnecessarily expensive.""" Fast, FastIntermediate = fast_and_intermediate_with_doc Slow, SlowIntermediate = slow_and_intermediate_with_doc Pxy = make_final_proxy_type( "Pxy", Fast, Slow, fast_to_slow=lambda _: Slow(), slow_to_fast=lambda _: Fast(), ) IntermediatePxy = make_intermediate_proxy_type( # noqa: F841 "IntermediatePxy", FastIntermediate, SlowIntermediate, ) assert check(Pxy, Slow) def test_proxy_binop(): class Foo: pass class Bar: def __add__(self, other): if isinstance(other, Foo): return "sum" return NotImplemented def __radd__(self, other): return self.__add__(other) FooProxy = make_final_proxy_type( "FooProxy", _Unusable, Foo, fast_to_slow=Foo(), slow_to_fast=_Unusable(), ) BarProxy = make_final_proxy_type( "BarProxy", _Unusable, Bar, fast_to_slow=Bar(), slow_to_fast=_Unusable(), ) assert Foo() + Bar() == "sum" assert Bar() + Foo() == "sum" assert FooProxy() + BarProxy() == "sum" assert BarProxy() + FooProxy() == "sum" assert FooProxy() + Bar() == "sum" assert Bar() + FooProxy() == "sum" assert Foo() + BarProxy() == "sum" assert BarProxy() + Foo() == "sum" def tuple_with_attrs(name, fields: list[str], extra_fields: set[str]): # Build a tuple-like class with some extra attributes and a custom # pickling scheme with __getnewargs_ex__ args = ", ".join(fields) kwargs = ", ".join(sorted(extra_fields)) code = f""" def __new__(cls, {args}, *, {kwargs}): return tuple.__new__(cls, ({args}, )) def __init__(self, {args}, *, {kwargs}): for key, val in zip({sorted(extra_fields)}, [{kwargs}]): self.__dict__[key] = val def __eq__(self, other): return ( type(other) is type(self) and tuple.__eq__(self, other) and all(getattr(self, k) == getattr(other, k) for k in self._fields) ) def __ne__(self, other): return not (self == other) def __getnewargs_ex__(self): return tuple(self), self.__dict__ """ namespace = { "__builtins__": { "AttributeError": AttributeError, "tuple": tuple, "zip": zip, "super": super, "frozenset": frozenset, "type": type, "all": all, "getattr": getattr, } } exec(code, namespace) return type( name, (tuple,), { "_fields": frozenset(extra_fields), "__eq__": namespace["__eq__"], "__getnewargs_ex__": namespace["__getnewargs_ex__"], "__init__": namespace["__init__"], "__ne__": namespace["__ne__"], "__new__": namespace["__new__"], }, ) def test_tuple_with_attrs_transform(): Bunch = tuple_with_attrs("Bunch", ["a", "b"], {"c", "d"}) Bunch2 = tuple_with_attrs("Bunch", ["a", "b"], {"c", "d"}) a = Bunch(1, 2, c=3, d=4) b = (1, 2) c = Bunch(1, 2, c=4, d=3) d = Bunch2(1, 2, c=3, d=4) assert a != c assert a != b assert b != c assert a != d transform = partial( _transform_arg, attribute_name="_fsproxy_fast", seen=set() ) aprime = transform(a) bprime = transform(b) cprime = transform(c) dprime = transform(d) assert a == aprime and a is not aprime assert b == bprime and b is not bprime assert c == cprime and c is not cprime assert d == dprime and d is not dprime
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/_magics_gpu_test.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 def ipython_magics_gpu_test(): from IPython.core.interactiveshell import InteractiveShell # Use in-memory history file to avoid file handles leaking # https://github.com/pandas-dev/pandas/pull/35711 from traitlets.config import Config # isort:skip c = Config() c.HistoryManager.hist_file = ":memory:" ip = InteractiveShell(config=c) ip.run_line_magic("load_ext", "cudf.pandas") # Directly check for private proxy attribute ip.run_cell("import pandas as pd; s = pd.Series(range(5))") result = ip.run_cell("assert hasattr(s, '_fsproxy_state')") result.raise_error() if __name__ == "__main__": ipython_magics_gpu_test()
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_array_function.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest from cudf.pandas import LOADED from cudf.pandas._wrappers.common import array_function_method if not LOADED: raise ImportError("These tests must be run with cudf.pandas loaded") import pandas._testing as tm from cudf.pandas.fast_slow_proxy import make_final_proxy_type class Slow: def __array__(self): return np.array([1, 1, 1, 2, 2, 3]) class Slow2: def __array_function__(self, func, types, args, kwargs): return "slow" class Fast: def __array_function__(self, func, types, args, kwargs): return "fast" class Fast2: def __array_function__(self, func, types, args, kwargs): return NotImplemented def test_array_function(): # test that fast dispatch to __array_function__ works Proxy = make_final_proxy_type( "Proxy", Fast, Slow2, fast_to_slow=lambda fast: Slow2(), slow_to_fast=lambda slow: Fast(), additional_attributes={"__array_function__": array_function_method}, ) tm.assert_equal(np.unique(Proxy()), "fast") def test_array_function_fallback(): # test that slow dispatch works when the fast dispatch fails Proxy = make_final_proxy_type( "Proxy", Fast2, Slow2, fast_to_slow=lambda fast: Slow2(), slow_to_fast=lambda slow: Fast2(), additional_attributes={"__array_function__": array_function_method}, ) tm.assert_equal(np.unique(Proxy()), "slow") def test_array_function_fallback_array(): # test that dispatch to slow __array__ works when # fast __array_function__ fails Proxy = make_final_proxy_type( "Proxy", Fast2, Slow, fast_to_slow=lambda fast: Slow(), slow_to_fast=lambda slow: Fast2(), additional_attributes={"__array_function__": array_function_method}, ) tm.assert_equal(np.unique(Proxy()), np.unique(np.asarray(Slow()))) def test_array_function_notimplemented(): # tests that when neither Fast nor Slow implement __array_function__, # we get a TypeError Proxy = make_final_proxy_type( "Proxy", Fast2, Fast2, fast_to_slow=lambda fast: Fast2(), slow_to_fast=lambda slow: Fast2(), additional_attributes={"__array_function__": array_function_method}, ) with pytest.raises(TypeError): np.unique(Proxy())
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/_magics_cpu_test.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 def ipython_magics_cpu_test(): import warnings from IPython.core.interactiveshell import InteractiveShell # Use in-memory history file to avoid file handles leaking # https://github.com/pandas-dev/pandas/pull/35711 from traitlets.config import Config # isort:skip warnings.filterwarnings("ignore", category=UserWarning) c = Config() c.HistoryManager.hist_file = ":memory:" ip = InteractiveShell(config=c) ip.run_line_magic("load_ext", "cudf.pandas") # confirm pandas is not aliased ip.run_cell("import pandas as pd; s = pd.Series(range(5))") result = ip.run_cell("assert not hasattr(s, '_fsproxy_state')") result.raise_error() if __name__ == "__main__": ipython_magics_cpu_test()
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/cudf_pandas_tests/test_cudf_pandas_cudf_interop.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 import cudf from cudf.pandas import LOADED if not LOADED: raise ImportError("These tests must be run with cudf.pandas loaded") import pandas as pd def test_cudf_pandas_loaded_to_cudf(): hybrid_df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) cudf_df = cudf.from_pandas(hybrid_df) pd.testing.assert_frame_equal(hybrid_df, cudf_df.to_pandas())
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/udf_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. # ============================================================================= cmake_minimum_required(VERSION 3.26.4) include(rapids-cmake) include(rapids-cpm) include(rapids-find) rapids_cpm_init() rapids_find_package( CUDAToolkit REQUIRED BUILD_EXPORT_SET udf-exports INSTALL_EXPORT_SET udf-exports ) include(${rapids-cmake-dir}/cpm/libcudacxx.cmake) rapids_cpm_libcudacxx(BUILD_EXPORT_SET udf-exports INSTALL_EXPORT_SET udf-exports) add_library(cudf_strings_udf SHARED strings/src/strings/udf/udf_apis.cu) target_include_directories( cudf_strings_udf PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/strings/include>" ) set_target_properties( cudf_strings_udf PROPERTIES BUILD_RPATH "\$ORIGIN/../" INSTALL_RPATH "\$ORIGIN/../" CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON INTERFACE_POSITION_INDEPENDENT_CODE ON ) set(UDF_CXX_FLAGS) set(UDF_CUDA_FLAGS --expt-extended-lambda --expt-relaxed-constexpr) target_compile_options( cudf_strings_udf PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${UDF_CXX_FLAGS}>" "$<$<COMPILE_LANGUAGE:CUDA>:${UDF_CUDA_FLAGS}>" ) target_link_libraries(cudf_strings_udf PUBLIC cudf::cudf) install(TARGETS cudf_strings_udf DESTINATION ./cudf/_lib/) # This function will copy the generated PTX file from its generator-specific location in the build # tree into a specified location in the build tree from which we can install it. function(copy_ptx_to_location target destination new_name) set(cmake_generated_file "${CMAKE_CURRENT_BINARY_DIR}/cmake/cp_${target}_$<LOWER_CASE:$<CONFIG>>_ptx.cmake" ) file( GENERATE OUTPUT "${cmake_generated_file}" CONTENT " set(ptx_path \"$<TARGET_OBJECTS:${target}>\") file(MAKE_DIRECTORY \"${destination}\") file(COPY_FILE \${ptx_path} \"${destination}/${new_name}\")" ) add_custom_target( ${target}_cp_ptx ALL COMMAND ${CMAKE_COMMAND} -P "${cmake_generated_file}" DEPENDS $<TARGET_OBJECTS:${target}> COMMENT "Copying PTX files to '${destination}'" ) endfunction() # Create the shim library for each architecture. set(SHIM_CUDA_FLAGS --expt-relaxed-constexpr -rdc=true) # always build a default PTX file in case RAPIDS_NO_INITIALIZE is set and the device cc can't be # safely queried through a context list(INSERT CMAKE_CUDA_ARCHITECTURES 0 "60") list(TRANSFORM CMAKE_CUDA_ARCHITECTURES REPLACE "-real" "") list(TRANSFORM CMAKE_CUDA_ARCHITECTURES REPLACE "-virtual" "") list(SORT CMAKE_CUDA_ARCHITECTURES) list(REMOVE_DUPLICATES CMAKE_CUDA_ARCHITECTURES) foreach(arch IN LISTS CMAKE_CUDA_ARCHITECTURES) set(tgt shim_${arch}) add_library(${tgt} OBJECT shim.cu) set_target_properties(${tgt} PROPERTIES CUDA_ARCHITECTURES ${arch} CUDA_PTX_COMPILATION ON) target_include_directories( ${tgt} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/strings/include>" ) target_compile_options(${tgt} PRIVATE "$<$<COMPILE_LANGUAGE:CUDA>:${SHIM_CUDA_FLAGS}>") target_link_libraries(${tgt} PUBLIC cudf::cudf) copy_ptx_to_location(${tgt} "${CMAKE_CURRENT_BINARY_DIR}/../udf" ${tgt}.ptx) install( FILES $<TARGET_OBJECTS:${tgt}> DESTINATION ./cudf/core/udf/ RENAME ${tgt}.ptx ) endforeach()
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/udf_cpp/shim.cu
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cudf/detail/utilities/device_operators.cuh> #include <cudf/strings/udf/case.cuh> #include <cudf/strings/udf/char_types.cuh> #include <cudf/strings/udf/replace.cuh> #include <cudf/strings/udf/search.cuh> #include <cudf/strings/udf/starts_with.cuh> #include <cudf/strings/udf/strip.cuh> #include <cudf/strings/udf/udf_string.cuh> #include <cuda/atomic> #include <cooperative_groups.h> #include <limits> #include <type_traits> using namespace cudf::strings::udf; extern "C" __device__ int len(int* nb_retval, void const* str) { auto sv = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = sv->length(); return 0; } extern "C" __device__ int startswith(bool* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = starts_with(*str_view, *substr_view); return 0; } extern "C" __device__ int endswith(bool* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = ends_with(*str_view, *substr_view); return 0; } extern "C" __device__ int contains(bool* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = (str_view->find(*substr_view) != cudf::string_view::npos); return 0; } extern "C" __device__ int find(int* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = str_view->find(*substr_view); return 0; } extern "C" __device__ int rfind(int* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = str_view->rfind(*substr_view); return 0; } extern "C" __device__ int eq(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view == *rhs_view); return 0; } extern "C" __device__ int ne(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view != *rhs_view); return 0; } extern "C" __device__ int ge(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view >= *rhs_view); return 0; } extern "C" __device__ int le(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view <= *rhs_view); return 0; } extern "C" __device__ int gt(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view > *rhs_view); return 0; } extern "C" __device__ int lt(bool* nb_retval, void const* str, void const* rhs) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto rhs_view = reinterpret_cast<cudf::string_view const*>(rhs); *nb_retval = (*str_view < *rhs_view); return 0; } extern "C" __device__ int pyislower(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_lower( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisupper(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_upper( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisspace(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_space( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisdecimal(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_decimal( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisnumeric(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_numeric( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisdigit(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_digit( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisalnum(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_alpha_numeric( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyisalpha(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_alpha( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pyistitle(bool* nb_retval, void const* str, std::uintptr_t chars_table) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); *nb_retval = is_title( reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(chars_table), *str_view); return 0; } extern "C" __device__ int pycount(int* nb_retval, void const* str, void const* substr) { auto str_view = reinterpret_cast<cudf::string_view const*>(str); auto substr_view = reinterpret_cast<cudf::string_view const*>(substr); *nb_retval = count(*str_view, *substr_view); return 0; } extern "C" __device__ int udf_string_from_string_view(int* nb_retbal, void const* str, void* udf_str) { auto str_view_ptr = reinterpret_cast<cudf::string_view const*>(str); auto udf_str_ptr = new (udf_str) udf_string; *udf_str_ptr = udf_string(*str_view_ptr); return 0; } extern "C" __device__ int string_view_from_udf_string(int* nb_retval, void const* udf_str, void* str) { auto udf_str_ptr = reinterpret_cast<udf_string const*>(udf_str); auto sv_ptr = new (str) cudf::string_view; *sv_ptr = cudf::string_view(*udf_str_ptr); return 0; } extern "C" __device__ int strip(int* nb_retval, void* udf_str, void* const* to_strip, void* const* strip_str) { auto to_strip_ptr = reinterpret_cast<cudf::string_view const*>(to_strip); auto strip_str_ptr = reinterpret_cast<cudf::string_view const*>(strip_str); auto udf_str_ptr = new (udf_str) udf_string; *udf_str_ptr = strip(*to_strip_ptr, *strip_str_ptr); return 0; } extern "C" __device__ int lstrip(int* nb_retval, void* udf_str, void* const* to_strip, void* const* strip_str) { auto to_strip_ptr = reinterpret_cast<cudf::string_view const*>(to_strip); auto strip_str_ptr = reinterpret_cast<cudf::string_view const*>(strip_str); auto udf_str_ptr = new (udf_str) udf_string; *udf_str_ptr = strip(*to_strip_ptr, *strip_str_ptr, cudf::strings::side_type::LEFT); return 0; } extern "C" __device__ int rstrip(int* nb_retval, void* udf_str, void* const* to_strip, void* const* strip_str) { auto to_strip_ptr = reinterpret_cast<cudf::string_view const*>(to_strip); auto strip_str_ptr = reinterpret_cast<cudf::string_view const*>(strip_str); auto udf_str_ptr = new (udf_str) udf_string; *udf_str_ptr = strip(*to_strip_ptr, *strip_str_ptr, cudf::strings::side_type::RIGHT); return 0; } extern "C" __device__ int upper(int* nb_retval, void* udf_str, void const* st, std::uintptr_t flags_table, std::uintptr_t cases_table, std::uintptr_t special_table) { auto udf_str_ptr = new (udf_str) udf_string; auto st_ptr = reinterpret_cast<cudf::string_view const*>(st); auto flags_table_ptr = reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(flags_table); auto cases_table_ptr = reinterpret_cast<cudf::strings::detail::character_cases_table_type*>(cases_table); auto special_table_ptr = reinterpret_cast<cudf::strings::detail::special_case_mapping*>(special_table); cudf::strings::udf::chars_tables tables{flags_table_ptr, cases_table_ptr, special_table_ptr}; *udf_str_ptr = to_upper(tables, *st_ptr); return 0; } extern "C" __device__ int lower(int* nb_retval, void* udf_str, void const* st, std::uintptr_t flags_table, std::uintptr_t cases_table, std::uintptr_t special_table) { auto udf_str_ptr = new (udf_str) udf_string; auto st_ptr = reinterpret_cast<cudf::string_view const*>(st); auto flags_table_ptr = reinterpret_cast<cudf::strings::detail::character_flags_table_type*>(flags_table); auto cases_table_ptr = reinterpret_cast<cudf::strings::detail::character_cases_table_type*>(cases_table); auto special_table_ptr = reinterpret_cast<cudf::strings::detail::special_case_mapping*>(special_table); cudf::strings::udf::chars_tables tables{flags_table_ptr, cases_table_ptr, special_table_ptr}; *udf_str_ptr = to_lower(tables, *st_ptr); return 0; } extern "C" __device__ int concat(int* nb_retval, void* udf_str, void* const* lhs, void* const* rhs) { auto lhs_ptr = reinterpret_cast<cudf::string_view const*>(lhs); auto rhs_ptr = reinterpret_cast<cudf::string_view const*>(rhs); auto udf_str_ptr = new (udf_str) udf_string; udf_string result; result.append(*lhs_ptr).append(*rhs_ptr); *udf_str_ptr = result; return 0; } extern "C" __device__ int replace( int* nb_retval, void* udf_str, void* const src, void* const to_replace, void* const replacement) { auto src_ptr = reinterpret_cast<cudf::string_view const*>(src); auto to_replace_ptr = reinterpret_cast<cudf::string_view const*>(to_replace); auto replacement_ptr = reinterpret_cast<cudf::string_view const*>(replacement); auto udf_str_ptr = new (udf_str) udf_string; *udf_str_ptr = replace(*src_ptr, *to_replace_ptr, *replacement_ptr); return 0; } // Groupby Shim Functions template <typename T> __device__ bool are_all_nans(cooperative_groups::thread_block const& block, T const* data, int64_t size) { // TODO: to be refactored with CG vote functions once // block size is known at build time __shared__ int64_t count; if (block.thread_rank() == 0) { count = 0; } block.sync(); for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { if (not std::isnan(data[idx])) { cuda::atomic_ref<int64_t, cuda::thread_scope_block> ref{count}; ref.fetch_add(1, cuda::std::memory_order_relaxed); break; } } block.sync(); return count == 0; } template <typename T, typename AccumT = std::conditional_t<std::is_integral_v<T>, int64_t, T>> __device__ AccumT device_sum(cooperative_groups::thread_block const& block, T const* data, int64_t size) { __shared__ AccumT block_sum; if (block.thread_rank() == 0) { block_sum = 0; } block.sync(); AccumT local_sum = 0; for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { local_sum += static_cast<AccumT>(data[idx]); } cuda::atomic_ref<AccumT, cuda::thread_scope_block> ref{block_sum}; ref.fetch_add(local_sum, cuda::std::memory_order_relaxed); block.sync(); return block_sum; } template <typename T, typename AccumT = std::conditional_t<std::is_integral_v<T>, int64_t, T>> __device__ AccumT BlockSum(T const* data, int64_t size) { auto block = cooperative_groups::this_thread_block(); if constexpr (std::is_floating_point_v<T>) { if (are_all_nans(block, data, size)) { return 0; } } auto block_sum = device_sum<T>(block, data, size); return block_sum; } template <typename T> __device__ double BlockMean(T const* data, int64_t size) { auto block = cooperative_groups::this_thread_block(); auto block_sum = device_sum<T>(block, data, size); return static_cast<double>(block_sum) / static_cast<double>(size); } template <typename T> __device__ double BlockCoVar(T const* lhs, T const* rhs, int64_t size) { auto block = cooperative_groups::this_thread_block(); __shared__ double block_covar; if (block.thread_rank() == 0) { block_covar = 0; } block.sync(); auto block_sum_lhs = device_sum<T>(block, lhs, size); auto const mu_l = static_cast<double>(block_sum_lhs) / static_cast<double>(size); auto const mu_r = [=]() { if (lhs == rhs) { // If the lhs and rhs are the same, this is calculating variance. // Thus we can assume mu_r = mu_l. return mu_l; } else { auto block_sum_rhs = device_sum<T>(block, rhs, size); return static_cast<double>(block_sum_rhs) / static_cast<double>(size); } }(); double local_covar = 0; for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { local_covar += (static_cast<double>(lhs[idx]) - mu_l) * (static_cast<double>(rhs[idx]) - mu_r); } cuda::atomic_ref<double, cuda::thread_scope_block> ref{block_covar}; ref.fetch_add(local_covar, cuda::std::memory_order_relaxed); block.sync(); if (block.thread_rank() == 0) { block_covar /= static_cast<double>(size - 1); } block.sync(); return block_covar; } template <typename T> __device__ double BlockVar(T const* data, int64_t size) { return BlockCoVar<T>(data, data, size); } template <typename T> __device__ double BlockStd(T const* data, int64_t size) { auto const var = BlockVar(data, size); return sqrt(var); } template <typename T> __device__ T BlockMax(T const* data, int64_t size) { auto block = cooperative_groups::this_thread_block(); if constexpr (std::is_floating_point_v<T>) { if (are_all_nans(block, data, size)) { return std::numeric_limits<T>::quiet_NaN(); } } auto local_max = cudf::DeviceMax::identity<T>(); __shared__ T block_max; if (block.thread_rank() == 0) { block_max = local_max; } block.sync(); for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { local_max = max(local_max, data[idx]); } cuda::atomic_ref<T, cuda::thread_scope_block> ref{block_max}; ref.fetch_max(local_max, cuda::std::memory_order_relaxed); block.sync(); return block_max; } template <typename T> __device__ T BlockMin(T const* data, int64_t size) { auto block = cooperative_groups::this_thread_block(); if constexpr (std::is_floating_point_v<T>) { if (are_all_nans(block, data, size)) { return std::numeric_limits<T>::quiet_NaN(); } } auto local_min = cudf::DeviceMin::identity<T>(); __shared__ T block_min; if (block.thread_rank() == 0) { block_min = local_min; } block.sync(); for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { local_min = min(local_min, data[idx]); } cuda::atomic_ref<T, cuda::thread_scope_block> ref{block_min}; ref.fetch_min(local_min, cuda::std::memory_order_relaxed); block.sync(); return block_min; } template <typename T> __device__ int64_t BlockIdxMax(T const* data, int64_t* index, int64_t size) { auto block = cooperative_groups::this_thread_block(); __shared__ T block_max; __shared__ int64_t block_idx_max; __shared__ bool found_max; auto local_max = cudf::DeviceMax::identity<T>(); auto local_idx_max = cudf::DeviceMin::identity<int64_t>(); if (block.thread_rank() == 0) { block_max = local_max; block_idx_max = local_idx_max; found_max = false; } block.sync(); for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { auto const current_data = data[idx]; if (current_data > local_max) { local_max = current_data; local_idx_max = index[idx]; found_max = true; } } cuda::atomic_ref<T, cuda::thread_scope_block> ref{block_max}; ref.fetch_max(local_max, cuda::std::memory_order_relaxed); block.sync(); if (found_max) { if (local_max == block_max) { cuda::atomic_ref<int64_t, cuda::thread_scope_block> ref_idx{block_idx_max}; ref_idx.fetch_min(local_idx_max, cuda::std::memory_order_relaxed); } } else { if (block.thread_rank() == 0) { block_idx_max = index[0]; } } block.sync(); return block_idx_max; } template <typename T> __device__ int64_t BlockIdxMin(T const* data, int64_t* index, int64_t size) { auto block = cooperative_groups::this_thread_block(); __shared__ T block_min; __shared__ int64_t block_idx_min; __shared__ bool found_min; auto local_min = cudf::DeviceMin::identity<T>(); auto local_idx_min = cudf::DeviceMin::identity<int64_t>(); if (block.thread_rank() == 0) { block_min = local_min; block_idx_min = local_idx_min; found_min = false; } block.sync(); for (int64_t idx = block.thread_rank(); idx < size; idx += block.size()) { auto const current_data = data[idx]; if (current_data < local_min) { local_min = current_data; local_idx_min = index[idx]; found_min = true; } } cuda::atomic_ref<T, cuda::thread_scope_block> ref{block_min}; ref.fetch_min(local_min, cuda::std::memory_order_relaxed); block.sync(); if (found_min) { if (local_min == block_min) { cuda::atomic_ref<int64_t, cuda::thread_scope_block> ref_idx{block_idx_min}; ref_idx.fetch_min(local_idx_min, cuda::std::memory_order_relaxed); } } else { if (block.thread_rank() == 0) { block_idx_min = index[0]; } } block.sync(); return block_idx_min; } template <typename T> __device__ double BlockCorr(T* const lhs_ptr, T* const rhs_ptr, int64_t size) { auto numerator = BlockCoVar(lhs_ptr, rhs_ptr, size); auto denominator = BlockStd(lhs_ptr, size) * BlockStd<T>(rhs_ptr, size); if (denominator == 0.0) { return std::numeric_limits<double>::quiet_NaN(); } else { return numerator / denominator; } } extern "C" { #define make_definition(name, cname, type, return_type) \ __device__ int name##_##cname(return_type* numba_return_value, type* const data, int64_t size) \ { \ return_type const res = name<type>(data, size); \ *numba_return_value = res; \ __syncthreads(); \ return 0; \ } make_definition(BlockSum, int32, int32_t, int64_t); make_definition(BlockSum, int64, int64_t, int64_t); make_definition(BlockSum, float32, float, float); make_definition(BlockSum, float64, double, double); make_definition(BlockMean, int32, int32_t, double); make_definition(BlockMean, int64, int64_t, double); make_definition(BlockMean, float32, float, float); make_definition(BlockMean, float64, double, double); make_definition(BlockStd, int32, int32_t, double); make_definition(BlockStd, int64, int64_t, double); make_definition(BlockStd, float32, float, float); make_definition(BlockStd, float64, double, double); make_definition(BlockVar, int64, int64_t, double); make_definition(BlockVar, int32, int32_t, double); make_definition(BlockVar, float32, float, float); make_definition(BlockVar, float64, double, double); make_definition(BlockMin, int32, int32_t, int32_t); make_definition(BlockMin, int64, int64_t, int64_t); make_definition(BlockMin, float32, float, float); make_definition(BlockMin, float64, double, double); make_definition(BlockMax, int32, int32_t, int32_t); make_definition(BlockMax, int64, int64_t, int64_t); make_definition(BlockMax, float32, float, float); make_definition(BlockMax, float64, double, double); #undef make_definition } extern "C" { #define make_definition_idx(name, cname, type) \ __device__ int name##_##cname( \ int64_t* numba_return_value, type* const data, int64_t* index, int64_t size) \ { \ auto const res = name<type>(data, index, size); \ *numba_return_value = res; \ __syncthreads(); \ return 0; \ } make_definition_idx(BlockIdxMin, int32, int32_t); make_definition_idx(BlockIdxMin, int64, int64_t); make_definition_idx(BlockIdxMin, float32, float); make_definition_idx(BlockIdxMin, float64, double); make_definition_idx(BlockIdxMax, int32, int32_t); make_definition_idx(BlockIdxMax, int64, int64_t); make_definition_idx(BlockIdxMax, float32, float); make_definition_idx(BlockIdxMax, float64, double); #undef make_definition_idx } extern "C" { #define make_definition_corr(name, cname, type) \ __device__ int name##_##cname##_##cname( \ double* numba_return_value, type* const lhs, type* const rhs, int64_t size) \ { \ double const res = name<type>(lhs, rhs, size); \ *numba_return_value = res; \ __syncthreads(); \ return 0; \ } make_definition_corr(BlockCorr, int32, int32_t); make_definition_corr(BlockCorr, int64, int64_t); #undef make_definition_corr }
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/pad.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.cuh" #include <cudf/strings/detail/pad_impl.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Pad beginning and/or end of a string with the given fill character * * The side_type::BOTH will attempt to center the text using the `fill_char`. * If `width <= d_str.length()` no change occurs and the input `d_str` is returned. * * @tparam side Specify where the padding should occur * @param d_str String to pad * @param width Minimum length in characters of the output string * @param fill_char Character used for padding */ template <side_type side = side_type::RIGHT> __device__ udf_string pad(cudf::string_view const d_str, cudf::size_type width, cudf::string_view fill_char = cudf::string_view{" ", 1}) { if (fill_char.empty()) { return udf_string{d_str}; } udf_string result; result.resize(cudf::strings::detail::compute_padded_size(d_str, width, fill_char.size_bytes())); cudf::strings::detail::pad_impl<side>(d_str, width, *fill_char.begin(), result.data()); return result; } /** * @brief Pad beginning of a string with zero '0' * * If the `width` is smaller than the length of `d_str` no change occurs. * * If `d_str` starts with a sign character ('-' or '+') then '0' padding * starts after the sign. * * @param d_str String to fill * @param width Minimum length in characters of the output string (including the sign character) */ __device__ udf_string zfill(cudf::string_view const d_str, cudf::size_type width) { udf_string result; result.resize(cudf::strings::detail::compute_padded_size(d_str, width, 1)); cudf::strings::detail::zfill_impl(d_str, width, result.data()); return result; } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/char_types.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/char_types/char_types_enum.hpp> #include <cudf/strings/detail/char_tables.hpp> #include <cudf/strings/detail/utf8.hpp> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Returns true if all characters in the string are of the type specified. * * The output will be false if the string is empty or has at least one character * not of the specified type. If all characters fit the type then true is returned. * * To ignore all but specific types, set the `verify_types` to those types * which should be checked. Otherwise, the default `ALL_TYPES` will verify all * characters match `types`. * * @code{.pseudo} * Examples: * s = ['ab', 'a b', 'a7', 'a B'] * all_characters_of_type('ab', LOWER) => true * all_characters_of_type('a b', LOWER) => false * all_characters_of_type('a7b', LOWER) => false * all_characters_of_type('aB', LOWER) => false * all_characters_of_type('ab', LOWER, LOWER|UPPER) => true * all_characters_of_type('a b', LOWER, LOWER|UPPER) => true * all_characters_of_type('a7', LOWER, LOWER|UPPER) => true * all_characters_of_type('a B', LOWER, LOWER|UPPER) => false * @endcode * * @param flags_table Table of character-type flags * @param d_str String for this operation * @param types The character types to check in the string * @param verify_types Only verify against these character types. * Default `ALL_TYPES` means return `true` * iff all characters match `types`. * @return True if all characters match the type conditions */ __device__ inline bool all_characters_of_type( cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str, string_character_types types, string_character_types verify_types = string_character_types::ALL_TYPES) { bool check = !d_str.empty(); // require at least one character size_type check_count = 0; for (auto itr = d_str.begin(); check && (itr != d_str.end()); ++itr) { auto code_point = cudf::strings::detail::utf8_to_codepoint(*itr); // lookup flags in table by code-point auto flag = code_point <= 0x00FFFF ? flags_table[code_point] : 0; if ((verify_types & flag) || // should flag be verified (flag == 0 && verify_types == ALL_TYPES)) // special edge case { check = (types & flag) > 0; ++check_count; } } return check && (check_count > 0); } /** * @brief Returns true if all characters are alphabetic only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters alphabetic */ __device__ inline bool is_alpha(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::ALPHA); } /** * @brief Returns true if all characters are alphanumeric only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are alphanumeric */ __device__ inline bool is_alpha_numeric( cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::ALPHANUM); } /** * @brief Returns true if all characters are numeric only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are numeric */ __device__ inline bool is_numeric(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::NUMERIC); } /** * @brief Returns true if all characters are digits only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are digits */ __device__ inline bool is_digit(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::DIGIT); } /** * @brief Returns true if all characters are decimal only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are decimal */ __device__ inline bool is_decimal(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::DECIMAL); } /** * @brief Returns true if all characters are spaces only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters spaces */ __device__ inline bool is_space(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type(flags_table, d_str, string_character_types::SPACE); } /** * @brief Returns true if all characters are upper case only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are upper case */ __device__ inline bool is_upper(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type( flags_table, d_str, string_character_types::UPPER, string_character_types::CASE_TYPES); } /** * @brief Returns true if all characters are lower case only * * @param flags_table Table required for checking character types * @param d_str Input string to check * @return True if characters are lower case */ __device__ inline bool is_lower(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { return all_characters_of_type( flags_table, d_str, string_character_types::LOWER, string_character_types::CASE_TYPES); } /** * @brief Returns true if string is in title case * * @param tables The char tables required for checking characters * @param d_str Input string to check * @return True if string is in title case */ __device__ inline bool is_title(cudf::strings::detail::character_flags_table_type* flags_table, string_view d_str) { auto valid = false; // requires one or more cased characters auto should_be_capitalized = true; // current character should be upper-case for (auto const chr : d_str) { auto const code_point = cudf::strings::detail::utf8_to_codepoint(chr); auto const flag = code_point <= 0x00FFFF ? flags_table[code_point] : 0; if (cudf::strings::detail::IS_UPPER_OR_LOWER(flag)) { if (should_be_capitalized == !cudf::strings::detail::IS_UPPER(flag)) return false; valid = true; } should_be_capitalized = !cudf::strings::detail::IS_UPPER_OR_LOWER(flag); } return valid; } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/udf_apis.hpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <rmm/device_buffer.hpp> #include <memory> namespace cudf { namespace strings { namespace udf { class udf_string; /** * @brief Return a cudf::string_view array for the given strings column * * No string data is copied so the input column controls the lifetime of the * underlying strings. * * New device memory is allocated and returned to hold just the string_view instances. * * @param input Strings column to convert to a string_view array. * @return Array of string_view objects in device memory */ std::unique_ptr<rmm::device_buffer> to_string_view_array(cudf::column_view const input); /** * @brief Return a STRINGS column given an array of udf_string objects * * This will make a copy of the strings in d_string in order to build * the output column. * The individual udf_strings are also cleared freeing each of their internal * device memory buffers. * * @param d_strings Pointer to device memory of udf_string objects * @param size The number of elements in the d_strings array * @return A strings column copy of the udf_string objects */ std::unique_ptr<cudf::column> column_from_udf_string_array(udf_string* d_strings, cudf::size_type size); /** * @brief Frees a vector of udf_string objects * * The individual udf_strings are cleared freeing each of their internal * device memory buffers. * * @param d_strings Pointer to device memory of udf_string objects * @param size The number of elements in the d_strings array */ void free_udf_string_array(udf_string* d_strings, cudf::size_type size); } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/udf_string.cuh
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.hpp" #include <cudf/strings/detail/utf8.hpp> #include <cudf/strings/string_view.cuh> #include <algorithm> #include <limits> #include <string> namespace cudf { namespace strings { namespace udf { namespace detail { /** * @brief Count the bytes in a null-terminated character array * * @param str Null-terminated string * @return Number of bytes in `str` up to but not including the null-terminator */ __device__ inline static cudf::size_type bytes_in_null_terminated_string(char const* str) { if (!str) return 0; cudf::size_type bytes = 0; while (*str++) ++bytes; return bytes; } } // namespace detail /** * @brief Allocate memory for strings operation * * @param bytes Number of bytes in to allocate * @return Pointer to allocated memory */ __device__ inline char* udf_string::allocate(cudf::size_type bytes) { char* data = static_cast<char*>(malloc(bytes + 1)); data[bytes] = '\0'; // add null-terminator so we can printf strings in device code return data; } /** * @brief Free memory created by allocate() * * @param data Pointer to allocated memory */ __device__ inline void udf_string::deallocate(char* data) { if (data) free(data); } /** * @brief Allocate memory for strings operation * * Reallocates memory for `m_data` with new size `bytes` * The original data in `m_data` is preserved up to `min(bytes,m_bytes)` * * @param bytes Number of bytes in to allocate * @return Pointer to allocated memory */ __device__ void udf_string::reallocate(cudf::size_type bytes) { m_capacity = bytes; auto new_data = allocate(m_capacity); memcpy(new_data, m_data, std::min(m_bytes, bytes)); deallocate(m_data); m_data = new_data; } __device__ inline udf_string::udf_string(char const* data, cudf::size_type bytes) : m_bytes(bytes), m_capacity(bytes) { m_data = allocate(m_capacity); memcpy(m_data, data, bytes); } __device__ udf_string::udf_string(cudf::size_type count, cudf::char_utf8 chr) { if (count <= 0) { return; } m_bytes = m_capacity = cudf::strings::detail::bytes_in_char_utf8(chr) * count; m_data = allocate(m_capacity); auto out_ptr = m_data; for (cudf::size_type idx = 0; idx < count; ++idx) { out_ptr += cudf::strings::detail::from_char_utf8(chr, out_ptr); } } __device__ inline udf_string::udf_string(char const* data) : udf_string(data, detail::bytes_in_null_terminated_string(data)) { } __device__ inline udf_string::udf_string(udf_string const& src) : udf_string(src.m_data, src.m_bytes) { } __device__ inline udf_string::udf_string(udf_string&& src) noexcept : m_data(src.m_data), m_bytes(src.m_bytes), m_capacity(src.m_capacity) { src.m_data = nullptr; src.m_bytes = 0; src.m_capacity = 0; } __device__ inline udf_string::udf_string(cudf::string_view str) : udf_string(str.data(), str.size_bytes()) { } __device__ inline udf_string::~udf_string() { deallocate(m_data); } __device__ inline udf_string& udf_string::operator=(udf_string const& str) { return assign(str); } __device__ inline udf_string& udf_string::operator=(udf_string&& str) noexcept { return assign(std::move(str)); } __device__ inline udf_string& udf_string::operator=(cudf::string_view str) { return assign(str); } __device__ inline udf_string& udf_string::operator=(char const* str) { return assign(str); } __device__ udf_string& udf_string::assign(udf_string&& str) noexcept { if (this == &str) { return *this; } deallocate(m_data); m_data = str.m_data; m_bytes = str.m_bytes; m_capacity = str.m_capacity; str.m_data = nullptr; str.m_bytes = 0; str.m_capacity = 0; return *this; } __device__ udf_string& udf_string::assign(cudf::string_view str) { return assign(str.data(), str.size_bytes()); } __device__ udf_string& udf_string::assign(char const* str) { return assign(str, detail::bytes_in_null_terminated_string(str)); } __device__ udf_string& udf_string::assign(char const* str, cudf::size_type bytes) { if (bytes >= m_capacity) { deallocate(m_data); m_capacity = bytes; m_data = allocate(m_capacity); } m_bytes = bytes; memcpy(m_data, str, bytes); m_data[m_bytes] = '\0'; return *this; } __device__ inline cudf::size_type udf_string::size_bytes() const noexcept { return m_bytes; } __device__ inline cudf::size_type udf_string::length() const noexcept { return cudf::strings::detail::characters_in_string(m_data, m_bytes); } __device__ constexpr cudf::size_type udf_string::max_size() const noexcept { return std::numeric_limits<cudf::size_type>::max() - 1; } __device__ inline char* udf_string::data() noexcept { return m_data; } __device__ inline char const* udf_string::data() const noexcept { return m_data; } __device__ inline bool udf_string::is_empty() const noexcept { return m_bytes == 0; } __device__ inline cudf::string_view::const_iterator udf_string::begin() const noexcept { return cudf::string_view::const_iterator(cudf::string_view(m_data, m_bytes), 0); } __device__ inline cudf::string_view::const_iterator udf_string::end() const noexcept { return cudf::string_view::const_iterator(cudf::string_view(m_data, m_bytes), length()); } __device__ inline cudf::char_utf8 udf_string::at(cudf::size_type pos) const { auto const offset = byte_offset(pos); auto chr = cudf::char_utf8{0}; if (offset < m_bytes) { cudf::strings::detail::to_char_utf8(data() + offset, chr); } return chr; } __device__ inline cudf::char_utf8 udf_string::operator[](cudf::size_type pos) const { return at(pos); } __device__ inline cudf::size_type udf_string::byte_offset(cudf::size_type pos) const { cudf::size_type offset = 0; auto start = m_data; auto end = start + m_bytes; while ((pos > 0) && (start < end)) { auto const byte = static_cast<uint8_t>(*start++); auto const char_bytes = cudf::strings::detail::bytes_in_utf8_byte(byte); if (char_bytes) { --pos; } offset += char_bytes; } return offset; } __device__ inline int udf_string::compare(cudf::string_view in) const noexcept { return compare(in.data(), in.size_bytes()); } __device__ inline int udf_string::compare(char const* data, cudf::size_type bytes) const { auto const view = static_cast<cudf::string_view>(*this); return view.compare(data, bytes); } __device__ inline bool udf_string::operator==(cudf::string_view rhs) const noexcept { return m_bytes == rhs.size_bytes() && compare(rhs) == 0; } __device__ inline bool udf_string::operator!=(cudf::string_view rhs) const noexcept { return compare(rhs) != 0; } __device__ inline bool udf_string::operator<(cudf::string_view rhs) const noexcept { return compare(rhs) < 0; } __device__ inline bool udf_string::operator>(cudf::string_view rhs) const noexcept { return compare(rhs) > 0; } __device__ inline bool udf_string::operator<=(cudf::string_view rhs) const noexcept { return compare(rhs) <= 0; } __device__ inline bool udf_string::operator>=(cudf::string_view rhs) const noexcept { return compare(rhs) >= 0; } __device__ inline void udf_string::clear() noexcept { deallocate(m_data); m_data = nullptr; m_bytes = 0; m_capacity = 0; } __device__ inline void udf_string::resize(cudf::size_type count) { if (count > max_size()) { return; } if (count > m_capacity) { reallocate(count); } // add padding if necessary (null chars) if (count > m_bytes) { memset(m_data + m_bytes, 0, count - m_bytes); } m_bytes = count; m_data[m_bytes] = '\0'; } __device__ void udf_string::reserve(cudf::size_type count) { if (count < max_size() && count > m_capacity) { reallocate(count); } } __device__ cudf::size_type udf_string::capacity() const noexcept { return m_capacity; } __device__ void udf_string::shrink_to_fit() { if (m_bytes < m_capacity) { reallocate(m_bytes); } } __device__ inline udf_string& udf_string::append(char const* str, cudf::size_type bytes) { if (bytes <= 0) { return *this; } auto const nbytes = m_bytes + bytes; if (nbytes > m_capacity) { reallocate(2 * nbytes); } memcpy(m_data + m_bytes, str, bytes); m_bytes = nbytes; m_data[m_bytes] = '\0'; return *this; } __device__ inline udf_string& udf_string::append(char const* str) { return append(str, detail::bytes_in_null_terminated_string(str)); } __device__ inline udf_string& udf_string::append(cudf::char_utf8 chr, cudf::size_type count) { auto d_str = udf_string(count, chr); return append(d_str); } __device__ inline udf_string& udf_string::append(cudf::string_view in) { return append(in.data(), in.size_bytes()); } __device__ inline udf_string& udf_string::operator+=(cudf::string_view in) { return append(in); } __device__ inline udf_string& udf_string::operator+=(cudf::char_utf8 chr) { return append(chr); } __device__ inline udf_string& udf_string::operator+=(char const* str) { return append(str); } __device__ inline udf_string& udf_string::insert(cudf::size_type pos, char const* str, cudf::size_type in_bytes) { return replace(pos, 0, str, in_bytes); } __device__ inline udf_string& udf_string::insert(cudf::size_type pos, char const* str) { return insert(pos, str, detail::bytes_in_null_terminated_string(str)); } __device__ inline udf_string& udf_string::insert(cudf::size_type pos, cudf::string_view in) { return insert(pos, in.data(), in.size_bytes()); } __device__ inline udf_string& udf_string::insert(cudf::size_type pos, cudf::size_type count, cudf::char_utf8 chr) { return replace(pos, 0, count, chr); } __device__ inline udf_string udf_string::substr(cudf::size_type pos, cudf::size_type count) const { if (pos < 0) { return udf_string{"", 0}; } auto const start_pos = byte_offset(pos); if (start_pos >= m_bytes) { return udf_string{"", 0}; } auto const end_pos = count < 0 ? m_bytes : std::min(byte_offset(pos + count), m_bytes); return udf_string{data() + start_pos, end_pos - start_pos}; } // utility for replace() __device__ void udf_string::shift_bytes(cudf::size_type start_pos, cudf::size_type end_pos, cudf::size_type nbytes) { if (nbytes < m_bytes) { // shift bytes to the left [...wxyz] -> [wxyzxyz] auto src = end_pos; auto tgt = start_pos; while (tgt < nbytes) { m_data[tgt++] = m_data[src++]; } } else if (nbytes > m_bytes) { // shift bytes to the right [abcd...] -> [abcabcd] auto src = m_bytes; auto tgt = nbytes; while (src > end_pos) { m_data[--tgt] = m_data[--src]; } } } __device__ inline udf_string& udf_string::replace(cudf::size_type pos, cudf::size_type count, char const* str, cudf::size_type in_bytes) { if (pos < 0 || in_bytes < 0) { return *this; } auto const start_pos = byte_offset(pos); if (start_pos > m_bytes) { return *this; } auto const end_pos = count < 0 ? m_bytes : std::min(byte_offset(pos + count), m_bytes); // compute new size auto const nbytes = m_bytes + in_bytes - (end_pos - start_pos); if (nbytes > m_capacity) { reallocate(2 * nbytes); } // move bytes -- make room for replacement shift_bytes(start_pos + in_bytes, end_pos, nbytes); // insert the replacement memcpy(m_data + start_pos, str, in_bytes); m_bytes = nbytes; m_data[m_bytes] = '\0'; return *this; } __device__ inline udf_string& udf_string::replace(cudf::size_type pos, cudf::size_type count, char const* str) { return replace(pos, count, str, detail::bytes_in_null_terminated_string(str)); } __device__ inline udf_string& udf_string::replace(cudf::size_type pos, cudf::size_type count, cudf::string_view in) { return replace(pos, count, in.data(), in.size_bytes()); } __device__ inline udf_string& udf_string::replace(cudf::size_type pos, cudf::size_type count, cudf::size_type chr_count, cudf::char_utf8 chr) { auto d_str = udf_string(chr_count, chr); return replace(pos, count, d_str); } __device__ udf_string& udf_string::erase(cudf::size_type pos, cudf::size_type count) { return replace(pos, count, nullptr, 0); } __device__ inline cudf::size_type udf_string::char_offset(cudf::size_type byte_pos) const { return cudf::strings::detail::characters_in_string(data(), byte_pos); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/replace.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.cuh> #include <cudf/strings/udf/udf_string.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Returns new string replacing all occurrences of target with replacement * * If target is empty then replacement is inserted between every character. * * @param source Source string to search * @param target String to match within source * @param replacement String to replace the target within the source * @return Resulting string */ __device__ inline udf_string replace(string_view source, string_view target, string_view replacement) { udf_string result; auto const tgt_length = target.length(); auto const src_length = source.length(); size_type last_position = 0; size_type position = 0; while (position != string_view::npos) { position = source.find(target, last_position); if (position != string_view::npos) { result.append(source.substr(last_position, position - last_position)); result.append(replacement); last_position = position + tgt_length; if ((tgt_length == 0) && (++last_position <= src_length)) { result.append(source.substr(position, 1)); } } } if (last_position < src_length) { result.append(source.substr(last_position, src_length - last_position)); } return result; } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/numeric.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.cuh" #include <cudf/strings/detail/convert/int_to_string.cuh> #include <cudf/strings/detail/convert/string_to_float.cuh> #include <cudf/strings/detail/convert/string_to_int.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Converts a string into an integer * * The '+' and '-' are allowed but only at the beginning of the string. * The string is expected to contain base-10 [0-9] characters only. * Any other character will end the parse. * Overflow of the int64 type is not detected. */ __device__ inline int64_t stoi(string_view const& d_str) { return cudf::strings::detail::string_to_integer(d_str); } /** * @brief Converts an integer into string * * @param value integer value to convert */ __device__ inline udf_string to_string(int64_t value) { udf_string result; if (value == 0) { result.append("0"); return result; } result.resize(cudf::strings::detail::count_digits(value)); cudf::strings::detail::integer_to_string(value, result.data()); return result; } /** * @brief Converts a string into a double * * This function supports scientific notation. * Overflow goes to inf or -inf and underflow may go to 0. */ __device__ inline double stod(string_view const& d_str) { return cudf::strings::detail::stod(d_str); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/strip.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.cuh" #include <cudf/strings/detail/strip.cuh> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Strip characters from the beginning and/or end of the given string * * The `d_to_strip` is interpreted as an array of characters to be removed. * If `d_to_strip` is an empty string, whitespace characters are stripped. * * @code{.cpp} * auto d_str = cudf::string_view{" aba ", 5}; * auto d_to_strip = cudf::string_view{}; // empty string * auto result = strip(d_str, d_to_strip); * // result is "aba" * d_to_strip = cudf::string_view{" a", 2}; // space and 'a' * result = strip(d_str, d_to_strip); * // result is "b" ('a' or ' ' removed from the ends) * @endcode * * @code{.cpp} * auto d_str = cudf::string_view{" aba ", 5}; * auto d_to_strip = cudf::string_view{}; // empty string * auto result = strip(d_str, d_to_strip, side_type::LEFT); * // result is "aba " * d_to_strip = cudf::string_view{"a ", 2}; // 'a' and space * result = strip(d_str, d_to_strip, side_type::LEFT); * // result is "ba " ('a' or ' ' removed from the beginning) * @endcode * * @code{.cpp} * auto d_str = cudf::string_view{" aba ", 5}; * auto d_to_strip = cudf::string_view{}; // empty string * auto result = strip(d_str, d_to_strip, side_type::RIGHT); * // result is " aba" * d_to_strip = cudf::string_view{" a", 2}; // space and 'a' * result = rstrip(d_str, d_to_strip, side_type::RIGHT); * // result is " ab" ('a' or ' ' removed from the end) * @endcode * * @param d_str String to strip characters from * @param d_to_strip Characters to remove * @param stype From where to strip the characters; * Default `BOTH` indicates stripping characters from the * beginning and the end of the input string `d_str` * @return New string with characters removed */ __device__ udf_string strip(cudf::string_view const d_str, cudf::string_view const d_to_strip, side_type stype = side_type::BOTH) { return udf_string{cudf::strings::detail::strip(d_str, d_to_strip, stype)}; } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/udf_string.hpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.hpp> #include <cuda_runtime.h> // This header contains all class and function declarations so that it // can be included in a .cpp file which only has declaration requirements // (i.e. sizeof, conditionally-comparable, explicit conversions, etc). // The definitions are coded in udf_string.cuh which is to be included // in .cu files that use this class in kernel calls. namespace cudf { namespace strings { namespace udf { /** * @brief Device string class for use with user-defined functions * * This class manages a device buffer of UTF-8 encoded characters * for string manipulation in a device kernel. * * Its methods and behavior are modelled after std::string but * with special consideration for UTF-8 encoded strings and for * use within a cuDF UDF. */ class udf_string { public: /** * @brief Represents unknown character position or length */ static constexpr cudf::size_type npos = static_cast<cudf::size_type>(-1); /** * @brief Cast to cudf::string_view operator */ __device__ operator cudf::string_view() const { return cudf::string_view(m_data, m_bytes); } /** * @brief Create an empty string. */ udf_string() = default; /** * @brief Create a string using existing device memory * * The given memory is copied into the instance returned. * * @param data Device pointer to UTF-8 encoded string * @param bytes Number of bytes in `data` */ __device__ udf_string(char const* data, cudf::size_type bytes); /** * @brief Create a string object from a null-terminated character array * * The given memory is copied into the instance returned. * * @param data Device pointer to UTF-8 encoded null-terminated * character array. */ __device__ udf_string(char const* data); /** * @brief Create a string object from a cudf::string_view * * The input string data is copied into the instance returned. * * @param str String to copy */ __device__ udf_string(cudf::string_view str); /** * @brief Create a string object with `count` copies of character `chr` * * @param count Number of times to copy `chr` * @param chr Character from which to create the string */ __device__ udf_string(cudf::size_type count, cudf::char_utf8 chr); /** * @brief Create a string object from another instance * * The string data is copied from the `src` into the instance returned. * * @param src String to copy */ __device__ udf_string(udf_string const& src); /** * @brief Move a string object from an rvalue reference * * The string data is moved from `src` into the instance returned. * The `src` will have no content. * * @param src String to copy */ __device__ udf_string(udf_string&& src) noexcept; __device__ ~udf_string(); __device__ udf_string& operator=(udf_string const&); __device__ udf_string& operator=(udf_string&&) noexcept; __device__ udf_string& operator=(cudf::string_view const); __device__ udf_string& operator=(char const*); /** * @brief Return the number of bytes in this string */ __device__ cudf::size_type size_bytes() const noexcept; /** * @brief Return the number of characters in this string */ __device__ cudf::size_type length() const noexcept; /** * @brief Return the maximum number of bytes a udf_string can hold */ __device__ constexpr cudf::size_type max_size() const noexcept; /** * @brief Return the internal pointer to the character array for this object */ __device__ char* data() noexcept; __device__ char const* data() const noexcept; /** * @brief Returns true if there are no characters in this string */ __device__ bool is_empty() const noexcept; /** * @brief Returns an iterator that can be used to navigate through * the UTF-8 characters in this string * * This returns a `cudf::string_view::const_iterator` which is read-only. */ __device__ cudf::string_view::const_iterator begin() const noexcept; __device__ cudf::string_view::const_iterator end() const noexcept; /** * @brief Returns the character at the specified position * * This will return 0 if `pos >= length()`. * * @param pos Index position of character to return * @return Character at position `pos` */ __device__ cudf::char_utf8 at(cudf::size_type pos) const; /** * @brief Returns the character at the specified index * * This will return 0 if `pos >= length()`. * Note this is read-only. Use replace() to modify a character. * * @param pos Index position of character to return * @return Character at position `pos` */ __device__ cudf::char_utf8 operator[](cudf::size_type pos) const; /** * @brief Return the byte offset for a given character position * * The byte offset for the character at `pos` such that * `data() + byte_offset(pos)` points to the memory location * the character at position `pos`. * * The behavior is undefined if `pos < 0 or pos >= length()` * * @param pos Index position of character to return byte offset. * @return Byte offset for character at `pos` */ __device__ cudf::size_type byte_offset(cudf::size_type pos) const; /** * @brief Comparing target string with this string * * @param str Target string to compare with this string * @return 0 If they compare equal * <0 Either the value of the first character of this string that does * not match is ordered before the corresponding character in `str`, * or all compared characters match but the `str` string is shorter. * >0 Either the value of the first character of this string that does * not match is ordered after the corresponding character in `str`, * or all compared characters match but the `str` string is longer. */ __device__ int compare(cudf::string_view str) const noexcept; /** * @brief Comparing target character array with this string * * @param str Target array of UTF-8 characters. * @param bytes Number of bytes in `str`. * @return 0 If they compare equal * <0 Either the value of the first character of this string that does * not match is ordered before the corresponding character in `str`, * or all compared characters match but `bytes < size_bytes()`. * >0 Either the value of the first character of this string that does * not match is ordered after the corresponding character in `str`, * or all compared characters match but `bytes > size_bytes()`. */ __device__ int compare(char const* str, cudf::size_type bytes) const; /** * @brief Returns true if `rhs` matches this string exactly */ __device__ bool operator==(cudf::string_view rhs) const noexcept; /** * @brief Returns true if `rhs` does not match this string */ __device__ bool operator!=(cudf::string_view rhs) const noexcept; /** * @brief Returns true if this string is ordered before `rhs` */ __device__ bool operator<(cudf::string_view rhs) const noexcept; /** * @brief Returns true if `rhs` is ordered before this string */ __device__ bool operator>(cudf::string_view rhs) const noexcept; /** * @brief Returns true if this string matches or is ordered before `rhs` */ __device__ bool operator<=(cudf::string_view rhs) const noexcept; /** * @brief Returns true if `rhs` matches or is ordered before this string */ __device__ bool operator>=(cudf::string_view rhs) const noexcept; /** * @brief Remove all bytes from this string * * All pointers, references, and iterators are invalidated. */ __device__ void clear() noexcept; /** * @brief Resizes string to contain `count` bytes * * If `count > size_bytes()` then zero-padding is added. * If `count < size_bytes()` then the string is truncated to size `count`. * * All pointers, references, and iterators may be invalidated. * * The behavior is undefined if `count > max_size()` * * @param count Size in bytes of this string. */ __device__ void resize(cudf::size_type count); /** * @brief Reserve `count` bytes in this string * * If `count > capacity()`, new memory is allocated and `capacity()` will * be greater than or equal to `count`. * There is no effect if `count <= capacity()`. * * @param count Total number of bytes to reserve for this string */ __device__ void reserve(cudf::size_type count); /** * @brief Returns the number of bytes that the string has allocated */ __device__ cudf::size_type capacity() const noexcept; /** * @brief Reduces internal allocation to just `size_bytes()` * * All pointers, references, and iterators may be invalidated. */ __device__ void shrink_to_fit(); /** * @brief Moves the contents of `str` into this string instance * * On return, the `str` will have no contents. * * @param str String to move * @return This string with new contents */ __device__ udf_string& assign(udf_string&& str) noexcept; /** * @brief Replaces the contents of this string with contents of `str` * * @param str String to copy * @return This string with new contents */ __device__ udf_string& assign(cudf::string_view str); /** * @brief Replaces the contents of this string with contents of `str` * * @param str Null-terminated UTF-8 character array * @return This string with new contents */ __device__ udf_string& assign(char const* str); /** * @brief Replaces the contents of this string with contents of `str` * * @param str UTF-8 character array * @param bytes Number of bytes to copy from `str` * @return This string with new contents */ __device__ udf_string& assign(char const* str, cudf::size_type bytes); /** * @brief Append a string to the end of this string * * @param str String to append * @return This string with the appended argument */ __device__ udf_string& operator+=(cudf::string_view str); /** * @brief Append a character to the end of this string * * @param str Character to append * @return This string with the appended argument */ __device__ udf_string& operator+=(cudf::char_utf8 chr); /** * @brief Append a null-terminated device memory character array * to the end of this string * * @param str String to append * @return This string with the appended argument */ __device__ udf_string& operator+=(char const* str); /** * @brief Append a null-terminated character array to the end of this string * * @param str String to append * @return This string with the appended argument */ __device__ udf_string& append(char const* str); /** * @brief Append a character array to the end of this string * * @param str Character array to append * @param bytes Number of bytes from `str` to append. * @return This string with the appended argument */ __device__ udf_string& append(char const* str, cudf::size_type bytes); /** * @brief Append a string to the end of this string * * @param str String to append * @return This string with the appended argument */ __device__ udf_string& append(cudf::string_view str); /** * @brief Append a character to the end of this string * a specified number of times. * * @param chr Character to append * @param count Number of times to append `chr` * @return This string with the append character(s) */ __device__ udf_string& append(cudf::char_utf8 chr, cudf::size_type count = 1); /** * @brief Insert a string into the character position specified * * There is no effect if `pos < 0 or pos > length()`. * * @param pos Character position to begin insert * @param str String to insert into this one * @return This string with the inserted argument */ __device__ udf_string& insert(cudf::size_type pos, cudf::string_view str); /** * @brief Insert a null-terminated character array into the character position specified * * There is no effect if `pos < 0 or pos > length()`. * * @param pos Character position to begin insert * @param data Null-terminated character array to insert * @return This string with the inserted argument */ __device__ udf_string& insert(cudf::size_type pos, char const* data); /** * @brief Insert a character array into the character position specified * * There is no effect if `pos < 0 or pos > length()`. * * @param pos Character position to begin insert * @param data Character array to insert * @param bytes Number of bytes from `data` to insert * @return This string with the inserted argument */ __device__ udf_string& insert(cudf::size_type pos, char const* data, cudf::size_type bytes); /** * @brief Insert a character one or more times into the character position specified * * There is no effect if `pos < 0 or pos > length()`. * * @param pos Character position to begin insert * @param count Number of times to insert `chr` * @param chr Character to insert * @return This string with the inserted argument */ __device__ udf_string& insert(cudf::size_type pos, cudf::size_type count, cudf::char_utf8 chr); /** * @brief Returns a substring of this string * * An empty string is returned if `pos < 0 or pos >= length()`. * * @param pos Character position to start the substring * @param count Number of characters for the substring; * This can be greater than the number of available characters. * Default npos returns characters in range `[pos, length())`. * @return New string with the specified characters */ __device__ udf_string substr(cudf::size_type pos, cudf::size_type count = npos) const; /** * @brief Replace a range of characters with a given string * * Replaces characters in range `[pos, pos + count]` with `str`. * There is no effect if `pos < 0 or pos > length()`. * * If `count==0` then `str` is inserted starting at `pos`. * If `count==npos` then the replacement range is `[pos,length())`. * * @param pos Position of first character to replace * @param count Number of characters to replace * @param str String to replace the given range * @return This string modified with the replacement */ __device__ udf_string& replace(cudf::size_type pos, cudf::size_type count, cudf::string_view str); /** * @brief Replace a range of characters with a null-terminated character array * * Replaces characters in range `[pos, pos + count)` with `data`. * There is no effect if `pos < 0 or pos > length()`. * * If `count==0` then `data` is inserted starting at `pos`. * If `count==npos` then the replacement range is `[pos,length())`. * * @param pos Position of first character to replace * @param count Number of characters to replace * @param data Null-terminated character array to replace the given range * @return This string modified with the replacement */ __device__ udf_string& replace(cudf::size_type pos, cudf::size_type count, char const* data); /** * @brief Replace a range of characters with a given character array * * Replaces characters in range `[pos, pos + count)` with `[data, data + bytes)`. * There is no effect if `pos < 0 or pos > length()`. * * If `count==0` then `data` is inserted starting at `pos`. * If `count==npos` then the replacement range is `[pos,length())`. * * @param pos Position of first character to replace * @param count Number of characters to replace * @param data String to replace the given range * @param bytes Number of bytes from data to use for replacement * @return This string modified with the replacement */ __device__ udf_string& replace(cudf::size_type pos, cudf::size_type count, char const* data, cudf::size_type bytes); /** * @brief Replace a range of characters with a character one or more times * * Replaces characters in range `[pos, pos + count)` with `chr` `chr_count` times. * There is no effect if `pos < 0 or pos > length()`. * * If `count==0` then `chr` is inserted starting at `pos`. * If `count==npos` then the replacement range is `[pos,length())`. * * @param pos Position of first character to replace * @param count Number of characters to replace * @param chr_count Number of times `chr` will repeated * @param chr Character to use for replacement * @return This string modified with the replacement */ __device__ udf_string& replace(cudf::size_type pos, cudf::size_type count, cudf::size_type chr_count, cudf::char_utf8 chr); /** * @brief Removes specified characters from this string * * Removes `min(count, length() - pos)` characters starting at `pos`. * There is no effect if `pos < 0 or pos >= length()`. * * @param pos Character position to begin insert * @param count Number of characters to remove starting at `pos` * @return This string with remove characters */ __device__ udf_string& erase(cudf::size_type pos, cudf::size_type count = npos); private: char* m_data{}; cudf::size_type m_bytes{}; cudf::size_type m_capacity{}; // utilities __device__ char* allocate(cudf::size_type bytes); __device__ void deallocate(char* data); __device__ void reallocate(cudf::size_type bytes); __device__ cudf::size_type char_offset(cudf::size_type byte_pos) const; __device__ void shift_bytes(cudf::size_type start_pos, cudf::size_type end_pos, cudf::size_type nbytes); }; } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/search.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Returns the number of times that the target string appears * in the source string. * * If `start <= 0` the search begins at the beginning of the `source` string. * If `end <=0` or `end` is greater the length of the `source` string, * the search stops at the end of the string. * * @param source Source string to search * @param target String to match within source * @param start First character position within source to start the search * @param end Last character position (exclusive) within source to search * @return Number of matches */ __device__ inline cudf::size_type count(string_view const source, string_view const target, cudf::size_type start = 0, cudf::size_type end = -1) { auto const tgt_length = target.length(); auto const src_length = source.length(); start = start < 0 ? 0 : start; end = (end < 0 || end > src_length) ? src_length : end; if (tgt_length == 0) { return (end - start) + 1; } cudf::size_type count = 0; cudf::size_type pos = start; while (pos != cudf::string_view::npos) { pos = source.find(target, pos, end - pos); if (pos != cudf::string_view::npos) { ++count; pos += tgt_length; } } return count; } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/case.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.cuh" #include <cudf/strings/detail/char_tables.hpp> #include <cudf/strings/detail/utf8.hpp> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Global variables for character-type flags and case conversion */ struct chars_tables { cudf::strings::detail::character_flags_table_type* flags_table; cudf::strings::detail::character_cases_table_type* cases_table; struct cudf::strings::detail::special_case_mapping* special_case_mapping_table; }; namespace detail { /** * @brief Utility for converting a single character * * There are special cases where the conversion may result in multiple characters. * * @param tables The char tables required for conversion * @param result String to append the converted character * @param code_point The code-point of the character to convert * @param flag The char-type flag of the character to convert */ __device__ inline void convert_char(chars_tables const tables, udf_string& result, uint32_t code_point, uint8_t flag) { if (!cudf::strings::detail::IS_SPECIAL(flag)) { result.append(cudf::strings::detail::codepoint_to_utf8(tables.cases_table[code_point])); return; } // handle special case auto const map = tables .special_case_mapping_table[cudf::strings::detail::get_special_case_hash_index(code_point)]; auto const output_count = cudf::strings::detail::IS_LOWER(flag) ? map.num_upper_chars : map.num_lower_chars; auto const* output_chars = cudf::strings::detail::IS_LOWER(flag) ? map.upper : map.lower; for (uint16_t idx = 0; idx < output_count; idx++) { result.append(cudf::strings::detail::codepoint_to_utf8(output_chars[idx])); } } /** * @brief Converts the given string to either upper or lower case * * @param tables The char tables required for conversion * @param d_str Input string to convert * @param case_flag Identifies upper/lower case conversion * @return New string containing the converted characters */ __device__ inline udf_string convert_case( chars_tables const tables, string_view d_str, cudf::strings::detail::character_flags_table_type case_flag) { udf_string result; for (auto const chr : d_str) { auto const code_point = cudf::strings::detail::utf8_to_codepoint(chr); auto const flag = code_point <= 0x00FFFF ? tables.flags_table[code_point] : 0; if ((flag & case_flag) || (cudf::strings::detail::IS_SPECIAL(flag) && !cudf::strings::detail::IS_UPPER_OR_LOWER(flag))) { convert_char(tables, result, code_point, flag); } else { result.append(chr); } } return result; } /** * @brief Utility for capitalize and title functions * * @tparam CapitalizeNextFn returns true if the next candidate character should be capitalized * @param tables The char tables required for conversion * @param d_str Input string to convert * @param next_fn Function for next character capitalized * @return New string containing the converted characters */ template <typename CapitalizeNextFn> __device__ inline udf_string capitalize(chars_tables const tables, string_view d_str, CapitalizeNextFn next_fn) { udf_string result; bool capitalize = true; for (auto const chr : d_str) { auto const code_point = cudf::strings::detail::utf8_to_codepoint(chr); auto const flag = code_point <= 0x00FFFF ? tables.flags_table[code_point] : 0; auto const change_case = capitalize ? cudf::strings::detail::IS_LOWER(flag) : cudf::strings::detail::IS_UPPER(flag); if (change_case) { detail::convert_char(tables, result, code_point, flag); } else { result.append(chr); } capitalize = next_fn(flag); } return result; } } // namespace detail /** * @brief Converts the given string to lower case * * @param tables The char tables required for conversion * @param d_str Input string to convert * @return New string containing the converted characters */ __device__ inline udf_string to_lower(chars_tables const tables, string_view d_str) { cudf::strings::detail::character_flags_table_type case_flag = cudf::strings::detail::IS_UPPER( cudf::strings::detail::ALL_FLAGS); // convert only upper case characters return detail::convert_case(tables, d_str, case_flag); } /** * @brief Converts the given string to upper case * * @param tables The char tables required for conversion * @param d_str Input string to convert * @return New string containing the converted characters */ __device__ inline udf_string to_upper(chars_tables const tables, string_view d_str) { cudf::strings::detail::character_flags_table_type case_flag = cudf::strings::detail::IS_LOWER( cudf::strings::detail::ALL_FLAGS); // convert only lower case characters return detail::convert_case(tables, d_str, case_flag); } /** * @brief Converts the given string to lower/upper case * * All lower case characters are converted to upper case and * all upper case characters are converted to lower case. * * @param tables The char tables required for conversion * @param d_str Input string to convert * @return New string containing the converted characters */ __device__ inline udf_string swap_case(chars_tables const tables, string_view d_str) { cudf::strings::detail::character_flags_table_type case_flag = cudf::strings::detail::IS_LOWER(cudf::strings::detail::ALL_FLAGS) | cudf::strings::detail::IS_UPPER(cudf::strings::detail::ALL_FLAGS); return detail::convert_case(tables, d_str, case_flag); } /** * @brief Capitalize the first character of the given string * * @param tables The char tables required for conversion * @param d_str Input string to convert * @return New string containing the converted characters */ __device__ inline udf_string capitalize(chars_tables const tables, string_view d_str) { auto next_fn = [](cudf::strings::detail::character_flags_table_type) -> bool { return false; }; return detail::capitalize(tables, d_str, next_fn); } /** * @brief Converts the given string to title case * * The first character after a non-character is converted to upper case. * All other characters are converted to lower case. * * @param tables The char tables required for conversion * @param d_str Input string to convert * @return New string containing the converted characters */ __device__ inline udf_string title(chars_tables const tables, string_view d_str) { auto next_fn = [](cudf::strings::detail::character_flags_table_type flag) -> bool { return !cudf::strings::detail::IS_ALPHA(flag); }; return detail::capitalize(tables, d_str, next_fn); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/split.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "udf_string.cuh" #include <cudf/strings/detail/split_utils.cuh> #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { namespace detail { /** * @brief Split string using given string * * The caller must allocate an array of cudf::string_view to be filled * in by this function. This function can be called with a `result=nullptr` * to compute the number of tokens. * * @code{.cpp} * auto d_str = cudf::string_view{"the best of times ", 19}; * auto tgt = cudf::string_view{" ", 1}; * auto token_count = split(d_str, tgt, nullptr); * auto result = new cudf::string_view[token_count]; * split(d_str, tgt, result); * // result is array like ["the", "best", "", "of", "times", ""] * @endcode * * @param d_str String to split * @param tgt String to split on * @param result Empty array to populate with output objects. * Pass `nullptr` to just get the token count. * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, cudf::string_view const tgt, cudf::string_view* result) { auto const nchars = d_str.length(); cudf::size_type count = 0; cudf::size_type last_pos = 0; while (last_pos <= nchars) { cudf::size_type const pos = d_str.find(tgt, last_pos); auto const length = (pos < 0 ? nchars : pos) - last_pos; if (result) { *result++ = d_str.substr(last_pos, length); } last_pos = pos + tgt.length(); ++count; if (pos < 0) { break; } } return count; } } // namespace detail /** * @brief Count tokens in a string without performing the split * * @code{.cpp} * auto d_str = cudf::string_view{"the best of times ", 19}; * auto tgt = cudf::string_view{" ", 1}; * auto token_count = count_tokens(d_str, tgt); * // token_count is 6 * @endcode * * @param d_str String to split * @param tgt String to split on * @return Number of tokens returned */ __device__ inline cudf::size_type count_tokens(cudf::string_view const d_str, cudf::string_view const tgt) { return detail::split(d_str, tgt, nullptr); } /** * @brief Split string using given string * * The caller must allocate an array of cudf::string_view to be filled * in by this function. * * @code{.cpp} * auto d_str = cudf::string_view{"the best of times ", 19}; * auto tgt = cudf::string_view{" ", 1}; * auto token_count = count_tokens(d_str, tgt); * auto result = new cudf::string_view[token_count]; * split(d_str, tgt, result); * // result is array like ["the", "best", "", "of", "times", ""] * @endcode * * @param d_str String to split * @param tgt String to split on * @param result Empty array to populate with output objects. * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, cudf::string_view const tgt, cudf::string_view* result) { return detail::split(d_str, tgt, result); } /** * @brief Split string using given target array * * @param d_str String to split * @param tgt Character array encoded in UTF-8 used for identifying split points * @param bytes Number of bytes to read from `tgt` * @param result Empty array to populate with output objects * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, char const* tgt, cudf::size_type bytes, cudf::string_view* result) { return detail::split(d_str, cudf::string_view{tgt, bytes}, result); } /** * @brief Split string using given target array * * @param d_str String to split * @param tgt Null-terminated character array encoded in UTF-8 used for identifying split points * @param result Empty array to populate with output objects * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, char const* tgt, cudf::string_view* result) { return split(d_str, tgt, detail::bytes_in_null_terminated_string(tgt), result); } namespace detail { /** * @brief Split string on whitespace * * The caller must allocate an array of cudf::string_view to be filled * in by this function. This function can be called with a `result=nullptr` * to compute the number of tokens. * * @code{.cpp} * auto d_str = cudf::string_view{"the best of times ", 19}; * auto token_count = split(d_str, nullptr); * auto result = new cudf::string_view[token_count]; * split(d_str, result); * // result is array like ["the", "best", "of", "times"] * @endcode * * @param d_str String to split * @param result Empty array to populate with output objects. * Pass `nullptr` to just get the token count. * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, cudf::string_view* result) { cudf::strings::detail::whitespace_string_tokenizer tokenizer{d_str}; cudf::size_type count = 0; while (tokenizer.next_token()) { auto token = tokenizer.get_token(); if (result) { *result++ = d_str.substr(token.first, token.second - token.first); } ++count; } return count; } } // namespace detail /** * @brief Count tokens in a string without performing the split on whitespace * * @code{.cpp} * auto d_str = cudf::string_view{"the best of times ", 19}; * auto token_count = count_tokens(d_str); * // token_count is 4 * @endcode * * @param d_str String to split * @return Number of tokens returned */ __device__ inline cudf::size_type count_tokens(cudf::string_view const d_str) { return detail::split(d_str, nullptr); } /** * @brief Split string on whitespace * * This will create tokens by splitting on one or more consecutive whitespace characters * found in `d_str`. * * @param d_str String to split * @param result Empty array to populate with output objects. * @return Number of tokens returned */ __device__ inline cudf::size_type split(cudf::string_view const d_str, cudf::string_view* result) { return detail::split(d_str, result); } /** * @brief Join an array of strings with a separator * * @code{.cpp} * auto separator = cudf::string_view{"::", 2}; * cudf::string_view input[] = { * cudf::string_view{"hello", 5}, * cudf::string_view{"goodbye", 7}, * cudf::string_view{"world", 5} }; * * auto result = join(separator, input, 3); * // result is "hello::goodbye::world" * @endcode * * @param separator Separator string * @param input An array of strings to join * @param count Number of elements in `input` * @return New string */ __device__ inline udf_string join(cudf::string_view const separator, cudf::string_view* input, cudf::size_type count) { udf_string result{""}; while (count-- > 0) { result += *input++; if (count > 0) { result += separator; } } return result; } /** * @brief Join an array of strings with a separator * * @param separator Null-terminated UTF-8 string * @param bytes Number of bytes to read from `separator` * @param input An array of strings to join * @param count Number of elements in `input` * @return New string */ __device__ inline udf_string join(char const* separator, cudf::size_type bytes, cudf::string_view* input, cudf::size_type count) { return join(cudf::string_view{separator, bytes}, input, count); } /** * @brief Join an array of strings with a separator * * @param separator Null-terminated UTF-8 string * @param input An array of strings to join * @param count Number of elements in `input` * @return New string */ __device__ inline udf_string join(char const* separator, cudf::string_view* input, cudf::size_type count) { return join(separator, detail::bytes_in_null_terminated_string(separator), input, count); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/include/cudf/strings/udf/starts_with.cuh
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/strings/string_view.cuh> namespace cudf { namespace strings { namespace udf { /** * @brief Returns true if the beginning of the specified string * matches the given character array. * * @param dstr String to check * @param tgt Character array encoded in UTF-8 * @param bytes Number of bytes to read from `tgt` * @return true if `tgt` matches the beginning of `dstr` */ __device__ inline bool starts_with(cudf::string_view const dstr, char const* tgt, cudf::size_type bytes) { if (bytes > dstr.size_bytes()) { return false; } auto const start_str = cudf::string_view{dstr.data(), bytes}; return start_str.compare(tgt, bytes) == 0; } /** * @brief Returns true if the beginning of the specified string * matches the given target string. * * @param dstr String to check * @param tgt String to match * @return true if `tgt` matches the beginning of `dstr` */ __device__ inline bool starts_with(cudf::string_view const dstr, cudf::string_view const& tgt) { return starts_with(dstr, tgt.data(), tgt.size_bytes()); } /** * @brief Returns true if the end of the specified string * matches the given character array. * * @param dstr String to check * @param tgt Character array encoded in UTF-8 * @param bytes Number of bytes to read from `tgt` * @return true if `tgt` matches the end of `dstr` */ __device__ inline bool ends_with(cudf::string_view const dstr, char const* tgt, cudf::size_type bytes) { if (bytes > dstr.size_bytes()) { return false; } auto const end_str = cudf::string_view{dstr.data() + dstr.size_bytes() - bytes, bytes}; return end_str.compare(tgt, bytes) == 0; } /** * @brief Returns true if the end of the specified string * matches the given target` string. * * @param dstr String to check * @param tgt String to match * @return true if `tgt` matches the end of `dstr` */ __device__ inline bool ends_with(cudf::string_view const dstr, cudf::string_view const& tgt) { return ends_with(dstr, tgt.data(), tgt.size_bytes()); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/src/strings
rapidsai_public_repos/cudf/python/cudf/udf_cpp/strings/src/strings/udf/udf_apis.cu
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cudf/strings/udf/udf_apis.hpp> #include <cudf/strings/udf/udf_string.cuh> #include <cudf/column/column_factories.hpp> #include <cudf/strings/detail/utilities.hpp> #include <cudf/strings/string_view.cuh> #include <cudf/utilities/default_stream.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/transform.h> namespace cudf { namespace strings { namespace udf { namespace detail { namespace { /** * @brief Functor wraps string_view objects around udf_string objects * * No string data is copied. */ struct udf_string_to_string_view_transform_fn { __device__ cudf::string_view operator()(cudf::strings::udf::udf_string const& dstr) { return dstr.data() == nullptr ? cudf::string_view{} : cudf::string_view{dstr.data(), dstr.size_bytes()}; } }; } // namespace /** * @copydoc to_string_view_array * * @param stream CUDA stream used for allocating/copying device memory and launching kernels */ std::unique_ptr<rmm::device_buffer> to_string_view_array(cudf::column_view const input, rmm::cuda_stream_view stream) { return std::make_unique<rmm::device_buffer>( std::move(cudf::strings::detail::create_string_vector_from_column( cudf::strings_column_view(input), stream, rmm::mr::get_current_device_resource()) .release())); } /** * @copydoc column_from_udf_string_array * * @param stream CUDA stream used for allocating/copying device memory and launching kernels */ std::unique_ptr<cudf::column> column_from_udf_string_array(udf_string* d_strings, cudf::size_type size, rmm::cuda_stream_view stream) { // create string_views of the udf_strings auto indices = rmm::device_uvector<cudf::string_view>(size, stream); thrust::transform(rmm::exec_policy(stream), d_strings, d_strings + size, indices.data(), udf_string_to_string_view_transform_fn{}); return cudf::make_strings_column(indices, cudf::string_view(nullptr, 0), stream); } /** * @copydoc free_udf_string_array * * @param stream CUDA stream used for allocating/copying device memory and launching kernels */ void free_udf_string_array(cudf::strings::udf::udf_string* d_strings, cudf::size_type size, rmm::cuda_stream_view stream) { thrust::for_each_n(rmm::exec_policy(stream), thrust::make_counting_iterator(0), size, [d_strings] __device__(auto idx) { d_strings[idx].clear(); }); } } // namespace detail // external APIs std::unique_ptr<rmm::device_buffer> to_string_view_array(cudf::column_view const input) { return detail::to_string_view_array(input, cudf::get_default_stream()); } std::unique_ptr<cudf::column> column_from_udf_string_array(udf_string* d_strings, cudf::size_type size) { return detail::column_from_udf_string_array(d_strings, size, cudf::get_default_stream()); } void free_udf_string_array(udf_string* d_strings, cudf::size_type size) { detail::free_udf_string_array(d_strings, size, cudf::get_default_stream()); } } // namespace udf } // namespace strings } // namespace cudf
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/benchmarks/conftest.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Defines pytest fixtures for all benchmarks. Most fixtures defined in this file represent one of the primary classes in the cuDF ecosystem such as DataFrame, Series, or Index. These fixtures may in turn be broken up into two categories: base fixtures and fixture unions. Each base fixture represents a specific type of object as well as certain of its properties crucial for benchmarking. Specifically, fixtures must account for the following different parameters: - Class of object (DataFrame, Series, Index) - Dtype - Nullability - Size (rows for all, rows/columns for DataFrame) One such fixture is a series of nullable integer data. Given that we generally want data across different sizes, we parametrize all fixtures across different numbers of rows rather than generating separate fixtures for each different possible number of rows. The number of columns is only relevant for DataFrame. While this core set of fixtures means that any benchmark can be run for any combination of these parameters, it also means that we would effectively have to parametrize our benchmarks with many fixtures. Not only is parametrizing tests with fixtures in this manner unsupported by pytest, it is also an inelegant solution leading to cumbersome parameter lists that must be maintained across all tests. Instead we make use of the `pytest_cases <https://smarie.github.io/python-pytest-cases/>_` pytest plugin, which supports the creation of fixture unions: fixtures that result from combining other fixtures together. The result is a set of well-defined fixtures that allow us to write benchmarks that naturally express the set of objects for which they are valid, e.g. `def bench_sort_values(frame_or_index)`. The generated fixtures are named according to the following convention: `{classname}_dtype_{dtype}[_nulls_{true|false}][_cols_{num_cols}][_rows_{num_rows}]` where classname is one of the following: index, series, dataframe, indexedframe, frame, frame_or_index. Note that in the case of indexes, to match Series/DataFrame we simply set `classname=index` and rely on the `dtype_{dtype}` component to delineate which index class is actually in use. In addition to the above fixtures, we also provide the following more specialized fixtures: - rangeindex: Since RangeIndex always holds int64 data we cannot conflate it with index_dtype_int64 (a true Int64Index), and it cannot hold nulls. As a result, it is provided as a separate fixture. """ import os import string import sys import pytest_cases # TODO: Rather than doing this path hacking (including the sessionstart and # sessionfinish hooks), we could just make the benchmarks a (sub)package to # enable relative imports. A minor change to consider when these are ported # into the main repo. sys.path.insert(0, os.path.join(os.path.dirname(__file__), "common")) from config import cudf # noqa: W0611, E402, F401 from utils import ( # noqa: E402 OrderedSet, collapse_fixtures, column_generators, make_fixture, ) # Turn off isort until we upgrade to 5.8.0 # https://github.com/pycqa/isort/issues/1594 # isort: off from config import ( # noqa: W0611, E402, F401 NUM_COLS, NUM_ROWS, collect_ignore, pytest_collection_modifyitems, pytest_sessionfinish, pytest_sessionstart, ) # isort: on @pytest_cases.fixture(params=[0, 1], ids=["AxisIndex", "AxisColumn"]) def axis(request): return request.param # First generate all the base fixtures. fixtures = OrderedSet() for dtype, column_generator in column_generators.items(): def make_dataframe(nr, nc, column_generator=column_generator): assert nc <= len( string.ascii_lowercase ), "make_dataframe only supports a maximum of 26 columns" return cudf.DataFrame( { f"{string.ascii_lowercase[i]}": column_generator(nr) for i in range(nc) } ) for nr in NUM_ROWS: # TODO: pytest_cases.fixture doesn't appear to support lambdas where # pytest does. https://github.com/smarie/python-pytest-cases/issues/278 # Once that is fixed we could use lambdas here. # TODO: pytest_cases has a bug where the first argument being a # defaulted kwarg e.g. (nr=nr, nc=nc) raises errors. # https://github.com/smarie/python-pytest-cases/issues/278 # Once that is fixed we could remove all the extraneous `request` # fixtures in these fixtures. def series_nulls_false( request, nr=nr, column_generator=column_generator ): return cudf.Series(column_generator(nr)) make_fixture( f"series_dtype_{dtype}_nulls_false_rows_{nr}", series_nulls_false, globals(), fixtures, ) def series_nulls_true( request, nr=nr, column_generator=column_generator ): s = cudf.Series(column_generator(nr)) s.iloc[::2] = None return s make_fixture( f"series_dtype_{dtype}_nulls_true_rows_{nr}", series_nulls_true, globals(), fixtures, ) # For now, not bothering to include a nullable index fixture. def index_nulls_false( request, nr=nr, column_generator=column_generator ): return cudf.Index(column_generator(nr)) make_fixture( f"index_dtype_{dtype}_nulls_false_rows_{nr}", index_nulls_false, globals(), fixtures, ) for nc in NUM_COLS: def dataframe_nulls_false( request, nr=nr, nc=nc, make_dataframe=make_dataframe ): return make_dataframe(nr, nc) make_fixture( f"dataframe_dtype_{dtype}_nulls_false_cols_{nc}_rows_{nr}", dataframe_nulls_false, globals(), fixtures, ) def dataframe_nulls_true( request, nr=nr, nc=nc, make_dataframe=make_dataframe ): df = make_dataframe(nr, nc) df.iloc[::2, :] = None return df make_fixture( f"dataframe_dtype_{dtype}_nulls_true_cols_{nc}_rows_{nr}", dataframe_nulls_true, globals(), fixtures, ) # We define some custom naming functions for use in the creation of fixture # unions to create more readable test function names that don't contain the # entire union, which quickly becomes intractably long. def unique_union_id(val): return val.alternative_name def default_union_id(val): return f"alt{val.get_alternative_idx()}" # Label the first level differently from others since there's no redundancy. idfunc = unique_union_id num_new_fixtures = len(fixtures) # Keep trying to merge existing fixtures until no new fixtures are added. while num_new_fixtures > 0: num_fixtures = len(fixtures) # Note: If we start also introducing unions across dtypes, most likely # those will take the form `*int_and_float*` or similar since we won't want # to union _all_ dtypes. In that case, the regexes will need to use # suitable lookaheads etc to avoid infinite loops here. for pat, repl in [ ("_nulls_(true|false)", ""), ("series|dataframe", "indexedframe"), ("indexedframe|index", "frame_or_index"), (r"_rows_\d+", ""), (r"_cols_\d+", ""), ]: collapse_fixtures(fixtures, pat, repl, globals(), idfunc) num_new_fixtures = len(fixtures) - num_fixtures # All subsequent levels get the same (collapsed) labels. idfunc = default_union_id for dtype, column_generator in column_generators.items(): # We have to manually add this one because we aren't including nullable # indexes but we want to be able to run some benchmarks on Series/DataFrame # that may or may not be nullable as well as Index objects. pytest_cases.fixture_union( name=f"frame_or_index_dtype_{dtype}", fixtures=( f"indexedframe_dtype_{dtype}", f"index_dtype_{dtype}_nulls_false", ), ids=["", f"index_dtype_{dtype}_nulls_false"], ) # TODO: Decide where to incorporate RangeIndex and MultiIndex fixtures. @pytest_cases.fixture(params=NUM_ROWS) def rangeindex(request): return cudf.RangeIndex(request.param)
0
rapidsai_public_repos/cudf/python/cudf
rapidsai_public_repos/cudf/python/cudf/benchmarks/pytest.ini
# Copyright (c) 2022, NVIDIA CORPORATION. [pytest] python_files = bench_*.py python_classes = Bench python_functions = bench_* markers = pandas_incompatible: mark a benchmark that cannot be run with pandas
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_indexed_frame.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of IndexedFrame methods.""" import pytest from utils import benchmark_with_object @benchmark_with_object(cls="indexedframe", dtype="int") @pytest.mark.parametrize("op", ["cumsum", "cumprod", "cummax"]) def bench_scans(benchmark, op, indexedframe): benchmark(getattr(indexedframe, op)) @benchmark_with_object(cls="indexedframe", dtype="int") @pytest.mark.parametrize("op", ["sum", "product", "mean"]) def bench_reductions(benchmark, op, indexedframe): benchmark(getattr(indexedframe, op)) @benchmark_with_object(cls="indexedframe", dtype="int") def bench_drop_duplicates(benchmark, indexedframe): benchmark(indexedframe.drop_duplicates) @benchmark_with_object(cls="indexedframe", dtype="int") def bench_rangeindex_replace(benchmark, indexedframe): # TODO: Consider adding more DataFrame-specific benchmarks for different # types of valid inputs (dicts, etc). benchmark(indexedframe.replace, 0, 2)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_dataframe_cases.py
# Copyright (c) 2022, NVIDIA CORPORATION. from utils import benchmark_with_object @benchmark_with_object(cls="dataframe", dtype="int", nulls=False) def where_case_1(dataframe): return dataframe, dataframe % 2 == 0, 0 @benchmark_with_object(cls="dataframe", dtype="int", nulls=False) def where_case_2(dataframe): cond = dataframe[dataframe.columns[0]] % 2 == 0 return dataframe, cond, 0
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_multiindex.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of MultiIndex methods.""" import numpy as np import pandas as pd import pytest from config import cudf @pytest.fixture def pidx(): num_elements = int(1e3) a = np.random.randint(0, num_elements // 10, num_elements) b = np.random.randint(0, num_elements // 10, num_elements) return pd.MultiIndex.from_arrays([a, b], names=("a", "b")) @pytest.fixture def midx(pidx): num_elements = int(1e3) a = np.random.randint(0, num_elements // 10, num_elements) b = np.random.randint(0, num_elements // 10, num_elements) df = cudf.DataFrame({"a": a, "b": b}) return cudf.MultiIndex.from_frame(df) @pytest.mark.pandas_incompatible def bench_from_pandas(benchmark, pidx): benchmark(cudf.MultiIndex.from_pandas, pidx) def bench_constructor(benchmark, midx): benchmark( cudf.MultiIndex, codes=midx.codes, levels=midx.levels, names=midx.names ) def bench_from_frame(benchmark, midx): benchmark(cudf.MultiIndex.from_frame, midx.to_frame(index=False)) def bench_copy(benchmark, midx): benchmark(midx.copy, deep=False)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_series.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of Series methods.""" import pytest from config import cudf, cupy from utils import benchmark_with_object @pytest.mark.parametrize("N", [100, 1_000_000]) def bench_construction(benchmark, N): benchmark(cudf.Series, cupy.random.rand(N)) @benchmark_with_object(cls="series", dtype="int") def bench_sort_values(benchmark, series): benchmark(series.sort_values) @benchmark_with_object(cls="series", dtype="int") @pytest.mark.parametrize("n", [10]) def bench_series_nsmallest(benchmark, series, n): benchmark(series.nsmallest, n)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_frame_or_index.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of methods that exist for both Frame and BaseIndex.""" import operator import numpy as np import pytest from utils import benchmark_with_object, make_gather_map @benchmark_with_object(cls="frame_or_index", dtype="int") @pytest.mark.parametrize("gather_how", ["sequence", "reverse", "random"]) @pytest.mark.parametrize("fraction", [0.4]) def bench_take(benchmark, gather_how, fraction, frame_or_index): nr = len(frame_or_index) gather_map = make_gather_map(nr * fraction, nr, gather_how) benchmark(frame_or_index.take, gather_map) @pytest.mark.pandas_incompatible # Series/Index work, but not DataFrame @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_argsort(benchmark, frame_or_index): benchmark(frame_or_index.argsort) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_min(benchmark, frame_or_index): benchmark(frame_or_index.min) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_where(benchmark, frame_or_index): cond = frame_or_index % 2 == 0 benchmark(frame_or_index.where, cond, 0) @benchmark_with_object(cls="frame_or_index", dtype="int", nulls=False) @pytest.mark.pandas_incompatible def bench_values_host(benchmark, frame_or_index): benchmark(lambda: frame_or_index.values_host) @benchmark_with_object(cls="frame_or_index", dtype="int", nulls=False) def bench_values(benchmark, frame_or_index): benchmark(lambda: frame_or_index.values) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_nunique(benchmark, frame_or_index): benchmark(frame_or_index.nunique) @benchmark_with_object(cls="frame_or_index", dtype="int", nulls=False) def bench_to_numpy(benchmark, frame_or_index): benchmark(frame_or_index.to_numpy) @benchmark_with_object(cls="frame_or_index", dtype="int", nulls=False) @pytest.mark.pandas_incompatible def bench_to_cupy(benchmark, frame_or_index): benchmark(frame_or_index.to_cupy) @benchmark_with_object(cls="frame_or_index", dtype="int") @pytest.mark.pandas_incompatible def bench_to_arrow(benchmark, frame_or_index): benchmark(frame_or_index.to_arrow) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_astype(benchmark, frame_or_index): benchmark(frame_or_index.astype, float) @pytest.mark.parametrize("ufunc", [np.add, np.logical_and]) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_ufunc_series_binary(benchmark, frame_or_index, ufunc): benchmark(ufunc, frame_or_index, frame_or_index) @pytest.mark.parametrize( "op", [operator.add, operator.mul, operator.eq], ) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_binops(benchmark, op, frame_or_index): benchmark(op, frame_or_index, frame_or_index) @pytest.mark.parametrize( "op", [operator.add, operator.mul, operator.eq], ) @benchmark_with_object(cls="frame_or_index", dtype="int") def bench_scalar_binops(benchmark, op, frame_or_index): benchmark(op, frame_or_index, 1)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_rangeindex.py
# Copyright (c) 2022, NVIDIA CORPORATION. import pytest @pytest.mark.pandas_incompatible def bench_values_host(benchmark, rangeindex): benchmark(lambda: rangeindex.values_host) def bench_to_numpy(benchmark, rangeindex): benchmark(rangeindex.to_numpy) @pytest.mark.pandas_incompatible def bench_to_arrow(benchmark, rangeindex): benchmark(rangeindex.to_arrow) def bench_argsort(benchmark, rangeindex): benchmark(rangeindex.argsort) def bench_nunique(benchmark, rangeindex): benchmark(rangeindex.nunique) def bench_isna(benchmark, rangeindex): benchmark(rangeindex.isna) def bench_max(benchmark, rangeindex): benchmark(rangeindex.max) def bench_min(benchmark, rangeindex): benchmark(rangeindex.min) def bench_where(benchmark, rangeindex): cond = rangeindex % 2 == 0 benchmark(rangeindex.where, cond, 0) def bench_isin(benchmark, rangeindex): values = [10, 100] benchmark(rangeindex.isin, values)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_functions_cases.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Test cases for benchmarks in bench_functions.py.""" import pytest_cases from config import NUM_ROWS, cudf, cupy @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_default_index(nr): return [ cudf.DataFrame({"a": cupy.tile([1, 2, 3], nr)}), cudf.DataFrame({"b": cupy.tile([4, 5, 7], nr)}), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_contiguous_indexes(nr): return [ cudf.DataFrame({"a": cupy.tile([1, 2, 3], nr)}), cudf.DataFrame( {"b": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_contiguous_indexes_different_cols(nr): return [ cudf.DataFrame( {"a": cupy.tile([1, 2, 3], nr), "b": cupy.tile([4, 5, 7], nr)} ), cudf.DataFrame( {"c": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_string_index(nr): return [ cudf.DataFrame( {"a": cupy.tile([1, 2, 3], nr), "b": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), cudf.DataFrame( {"c": [4, 5, 7] * nr}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_contiguous_string_index_different_col(nr): return [ cudf.DataFrame( {"a": cupy.tile([1, 2, 3], nr), "b": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), cudf.DataFrame( {"c": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3).astype("str"), ), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_complex_string_index(nr): return [ cudf.DataFrame( {"a": cupy.tile([1, 2, 3], nr), "b": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), cudf.DataFrame( {"c": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3).astype("str"), ), cudf.DataFrame( {"d": cupy.tile([1, 2, 3], nr), "e": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), cudf.DataFrame( {"f": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3).astype("str"), ), cudf.DataFrame( {"g": cupy.tile([1, 2, 3], nr), "h": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=0, stop=nr * 3).astype("str"), ), cudf.DataFrame( {"i": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3).astype("str"), ), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_unique_columns(nr): # To avoid any edge case bugs, always use at least 10 rows per DataFrame. nr_actual = max(10, nr // 20) return [ cudf.DataFrame({"a": cupy.tile([1, 2, 3], nr_actual)}), cudf.DataFrame({"b": cupy.tile([4, 5, 7], nr_actual)}), cudf.DataFrame({"c": cupy.tile([1, 2, 3], nr_actual)}), cudf.DataFrame({"d": cupy.tile([4, 5, 7], nr_actual)}), cudf.DataFrame({"e": cupy.tile([1, 2, 3], nr_actual)}), cudf.DataFrame({"f": cupy.tile([4, 5, 7], nr_actual)}), cudf.DataFrame({"g": cupy.tile([1, 2, 3], nr_actual)}), cudf.DataFrame({"h": cupy.tile([4, 5, 7], nr_actual)}), cudf.DataFrame({"i": cupy.tile([1, 2, 3], nr_actual)}), cudf.DataFrame({"j": cupy.tile([4, 5, 7], nr_actual)}), ] @pytest_cases.parametrize("nr", NUM_ROWS) def concat_case_unique_columns_with_different_range_index(nr): return [ cudf.DataFrame( {"a": cupy.tile([1, 2, 3], nr), "b": cupy.tile([4, 5, 7], nr)} ), cudf.DataFrame( {"c": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), cudf.DataFrame( {"d": cupy.tile([1, 2, 3], nr), "e": cupy.tile([4, 5, 7], nr)} ), cudf.DataFrame( {"f": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), cudf.DataFrame( {"g": cupy.tile([1, 2, 3], nr), "h": cupy.tile([4, 5, 7], nr)} ), cudf.DataFrame( {"i": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), cudf.DataFrame( {"j": cupy.tile([1, 2, 3], nr), "k": cupy.tile([4, 5, 7], nr)} ), cudf.DataFrame( {"l": cupy.tile([4, 5, 7], nr)}, index=cudf.RangeIndex(start=nr * 3, stop=nr * 2 * 3), ), ]
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_index.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of Index methods.""" import pytest from config import cudf, cupy from utils import benchmark_with_object @pytest.mark.parametrize("N", [100, 1_000_000]) def bench_construction(benchmark, N): benchmark(cudf.Index, cupy.random.rand(N)) @benchmark_with_object(cls="index", dtype="int", nulls=False) def bench_sort_values(benchmark, index): benchmark(index.sort_values)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_dataframe.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. """Benchmarks of DataFrame methods.""" import string import numpy import pytest import pytest_cases from config import cudf, cupy from utils import benchmark_with_object @pytest.mark.parametrize("N", [100, 1_000_000]) def bench_construction(benchmark, N): benchmark(cudf.DataFrame, {None: cupy.random.rand(N)}) @benchmark_with_object(cls="dataframe", dtype="float", cols=6) @pytest.mark.parametrize( "expr", ["a+b", "a+b+c+d+e", "a / (sin(a) + cos(b)) * tanh(d*e*f)"] ) def bench_eval_func(benchmark, expr, dataframe): benchmark(dataframe.eval, expr) @benchmark_with_object(cls="dataframe", dtype="int", nulls=False, cols=6) @pytest.mark.parametrize( "num_key_cols", [2, 3, 4], ) def bench_merge(benchmark, dataframe, num_key_cols): benchmark( dataframe.merge, dataframe, on=list(dataframe.columns[:num_key_cols]) ) # TODO: Some of these cases could be generalized to an IndexedFrame benchmark # instead of a DataFrame benchmark. @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize( "values", [ lambda: range(50), lambda: {f"{string.ascii_lowercase[i]}": range(50) for i in range(10)}, lambda: cudf.DataFrame( {f"{string.ascii_lowercase[i]}": range(50) for i in range(10)} ), lambda: cudf.Series(range(50)), ], ) def bench_isin(benchmark, dataframe, values): benchmark(dataframe.isin, values()) @pytest.fixture( params=[0, numpy.random.RandomState, cupy.random.RandomState], ids=["Seed", "NumpyRandomState", "CupyRandomState"], ) def random_state(request): rs = request.param return rs if isinstance(rs, int) else rs(seed=42) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize("frac", [0.5]) def bench_sample(benchmark, dataframe, axis, frac, random_state): if axis == 1 and isinstance(random_state, cupy.random.RandomState): pytest.skip("Unsupported params.") benchmark( dataframe.sample, frac=frac, axis=axis, random_state=random_state ) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize("frac", [0, 0.25, 0.5, 0.75, 1]) def bench_iloc_getitem_indices(benchmark, dataframe, frac): rs = numpy.random.RandomState(seed=42) n = int(len(dataframe) * frac) values = rs.choice(len(dataframe), size=n, replace=False) benchmark(dataframe.iloc.__getitem__, values) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize("frac", [0, 0.25, 0.5, 0.75, 1]) def bench_iloc_getitem_mask(benchmark, dataframe, frac): rs = numpy.random.RandomState(seed=42) n = int(len(dataframe) * frac) values = rs.choice(len(dataframe), size=n, replace=False) mask = numpy.zeros(len(dataframe), dtype=bool) mask[values] = True benchmark(dataframe.iloc.__getitem__, mask) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize( "slice", [slice(None), slice(0, 0, 1), slice(1, None, 10), slice(None, -1, -1)], ) def bench_iloc_getitem_slice(benchmark, dataframe, slice): benchmark(dataframe.iloc.__getitem__, slice) @benchmark_with_object(cls="dataframe", dtype="int") def bench_iloc_getitem_scalar(benchmark, dataframe): benchmark(dataframe.iloc.__getitem__, len(dataframe) // 2) @benchmark_with_object(cls="dataframe", dtype="int", nulls=False, cols=6) @pytest.mark.parametrize( "num_key_cols", [2, 3, 4], ) def bench_groupby(benchmark, dataframe, num_key_cols): benchmark(dataframe.groupby, by=list(dataframe.columns[:num_key_cols])) @benchmark_with_object(cls="dataframe", dtype="int", nulls=False, cols=6) @pytest.mark.parametrize( "agg", [ "sum", ["sum", "mean"], { f"{string.ascii_lowercase[i]}": ["sum", "mean", "count"] for i in range(6) }, ], ) @pytest.mark.parametrize( "num_key_cols", [2, 3, 4], ) @pytest.mark.parametrize("as_index", [True, False]) @pytest.mark.parametrize("sort", [True, False]) def bench_groupby_agg(benchmark, dataframe, agg, num_key_cols, as_index, sort): by = list(dataframe.columns[:num_key_cols]) benchmark(dataframe.groupby(by=by, as_index=as_index, sort=sort).agg, agg) @benchmark_with_object(cls="dataframe", dtype="int", nulls=False, cols=6) @pytest.mark.parametrize( "num_key_cols", [2, 3, 4], ) @pytest.mark.parametrize("use_frac", [True, False]) @pytest.mark.parametrize("replace", [True, False]) @pytest.mark.parametrize("target_sample_frac", [0.1, 0.5, 1]) def bench_groupby_sample( benchmark, dataframe, num_key_cols, use_frac, replace, target_sample_frac ): grouper = dataframe.groupby(by=list(dataframe.columns[:num_key_cols])) if use_frac: kwargs = {"frac": target_sample_frac, "replace": replace} else: minsize = grouper.size().min() target_size = numpy.round( target_sample_frac * minsize, decimals=0 ).astype(int) kwargs = {"n": target_size, "replace": replace} benchmark(grouper.sample, **kwargs) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize("num_cols_to_sort", [1]) def bench_sort_values(benchmark, dataframe, num_cols_to_sort): benchmark( dataframe.sort_values, list(dataframe.columns[:num_cols_to_sort]) ) @benchmark_with_object(cls="dataframe", dtype="int") @pytest.mark.parametrize("num_cols_to_sort", [1]) @pytest.mark.parametrize("n", [10]) def bench_nsmallest(benchmark, dataframe, num_cols_to_sort, n): by = list(dataframe.columns[:num_cols_to_sort]) benchmark(dataframe.nsmallest, n, by) @pytest_cases.parametrize_with_cases("dataframe, cond, other", prefix="where") def bench_where(benchmark, dataframe, cond, other): benchmark(dataframe.where, cond, other)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/API/bench_functions.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of free functions that accept cudf objects.""" import numpy as np import pytest import pytest_cases from config import NUM_ROWS, cudf, cupy from utils import benchmark_with_object @pytest_cases.parametrize_with_cases("objs", prefix="concat") @pytest.mark.parametrize( "axis", [ 1, ], ) @pytest.mark.parametrize("join", ["inner", "outer"]) @pytest.mark.parametrize("ignore_index", [True, False]) def bench_concat_axis_1(benchmark, objs, axis, join, ignore_index): benchmark( cudf.concat, objs=objs, axis=axis, join=join, ignore_index=ignore_index ) @pytest.mark.parametrize("size", [10_000, 100_000]) @pytest.mark.parametrize("cardinality", [10, 100, 1000]) @pytest.mark.parametrize("dtype", [cupy.bool_, cupy.float64]) def bench_get_dummies_high_cardinality(benchmark, size, cardinality, dtype): """Benchmark when the cardinality of column to encode is high.""" df = cudf.DataFrame( { "col": cudf.Series( cupy.random.randint(low=0, high=cardinality, size=size) ).astype("category") } ) benchmark(cudf.get_dummies, df, columns=["col"], dtype=dtype) @pytest.mark.parametrize("prefix", [None, "pre"]) def bench_get_dummies_simple(benchmark, prefix): """Benchmark with small input to test the efficiency of the API itself.""" df = cudf.DataFrame( { "col1": list(range(10)), "col2": list("abcdefghij"), "col3": cudf.Series(list(range(100, 110)), dtype="category"), } ) benchmark( cudf.get_dummies, df, columns=["col1", "col2", "col3"], prefix=prefix ) @benchmark_with_object(cls="dataframe", dtype="int", cols=6) def bench_pivot_table_simple(benchmark, dataframe): values = ["d", "e"] index = ["a", "b"] columns = ["c"] benchmark( cudf.pivot_table, data=dataframe, values=values, index=index, columns=columns, ) @pytest_cases.parametrize("nr", NUM_ROWS) def bench_crosstab_simple(benchmark, nr): series_a = np.array(["foo", "bar"] * nr) series_b = np.array(["one", "two"] * nr) series_c = np.array(["dull", "shiny"] * nr) np.random.shuffle(series_a) np.random.shuffle(series_b) np.random.shuffle(series_c) series_a = cudf.Series(series_a) series_b = cudf.Series(series_b) series_c = cudf.Series(series_c) benchmark(cudf.crosstab, index=series_a, columns=[series_b, series_c])
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/internal/bench_column.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of Column methods.""" import pytest import pytest_cases from utils import ( benchmark_with_object, make_boolean_mask_column, make_gather_map, ) @benchmark_with_object(cls="column", dtype="float") def bench_apply_boolean_mask(benchmark, column): mask = make_boolean_mask_column(column.size) benchmark(column.apply_boolean_mask, mask) @benchmark_with_object(cls="column", dtype="float") @pytest.mark.parametrize("dropnan", [True, False]) def bench_dropna(benchmark, column, dropnan): benchmark(column.dropna, drop_nan=dropnan) @benchmark_with_object(cls="column", dtype="float") def bench_unique_single_column(benchmark, column): benchmark(column.unique) @benchmark_with_object(cls="column", dtype="float") @pytest.mark.parametrize("nullify", [True, False]) @pytest.mark.parametrize("gather_how", ["sequence", "reverse", "random"]) def bench_take(benchmark, column, gather_how, nullify): gather_map = make_gather_map( column.size * 0.4, column.size, gather_how )._column benchmark(column.take, gather_map, nullify=nullify) @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_stride_1_slice_scalar(column): return column, slice(None, None, 1), 42 @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_stride_2_slice_scalar(column): return column, slice(None, None, 2), 42 @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_boolean_column_scalar(column): column = column return column, [True, False] * (len(column) // 2), 42 @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_int_column_scalar(column): column = column return column, list(range(len(column))), 42 @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_stride_1_slice_align_to_key_size( column, ): column = column key = slice(None, None, 1) start, stop, stride = key.indices(len(column)) materialized_key_size = len(column.slice(start, stop, stride)) return column, key, [42] * materialized_key_size @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_stride_2_slice_align_to_key_size( column, ): column = column key = slice(None, None, 2) start, stop, stride = key.indices(len(column)) materialized_key_size = len(column.slice(start, stop, stride)) return column, key, [42] * materialized_key_size @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_boolean_column_align_to_col_size( column, ): column = column size = len(column) return column, [True, False] * (size // 2), [42] * size @benchmark_with_object(cls="column", dtype="int", nulls=False) def setitem_case_int_column_align_to_col_size(column): column = column size = len(column) return column, list(range(size)), [42] * size # Benchmark Grid # key: slice == 1 (fill or copy_range shortcut), # slice != 1 (scatter), # column(bool) (boolean_mask_scatter), # column(int) (scatter) # value: scalar, # column (len(val) == len(key)), # column (len(val) != len(key) and len == num_true) @pytest_cases.parametrize_with_cases( "column,key,value", cases=".", prefix="setitem" ) def bench_setitem(benchmark, column, key, value): benchmark(column.__setitem__, key, value)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/internal/conftest.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Defines pytest fixtures for internal benchmarks.""" from config import NUM_ROWS, cudf from utils import ( OrderedSet, collapse_fixtures, column_generators, make_fixture, ) fixtures = OrderedSet() for dtype, column_generator in column_generators.items(): for nr in NUM_ROWS: def column_nulls_false(request, nr=nr): return cudf.core.column.as_column(column_generator(nr)) make_fixture( f"column_dtype_{dtype}_nulls_false_rows_{nr}", column_nulls_false, globals(), fixtures, ) def column_nulls_true(request, nr=nr): c = cudf.core.column.as_column(column_generator(nr)) c[::2] = None return c make_fixture( f"column_dtype_{dtype}_nulls_true_rows_{nr}", column_nulls_true, globals(), fixtures, ) num_new_fixtures = len(fixtures) # Keep trying to merge existing fixtures until no new fixtures are added. while num_new_fixtures > 0: num_fixtures = len(fixtures) # Note: If we start also introducing unions across dtypes, most likely # those will take the form `*int_and_float*` or similar since we won't want # to union _all_ dtypes. In that case, the regexes will need to use # suitable lookaheads etc to avoid infinite loops here. for pat, repl in [ ("_nulls_(true|false)", ""), (r"_rows_\d+", ""), ]: collapse_fixtures(fixtures, pat, repl, globals()) num_new_fixtures = len(fixtures) - num_fixtures
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/internal/bench_rangeindex_internal.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of internal RangeIndex methods.""" def bench_column(benchmark, rangeindex): benchmark(lambda: rangeindex._column) def bench_columns(benchmark, rangeindex): benchmark(lambda: rangeindex._columns)
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/internal/bench_dataframe_internal.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. """Benchmarks of internal DataFrame methods.""" from utils import benchmark_with_object, make_boolean_mask_column from cudf.core.copy_types import BooleanMask @benchmark_with_object(cls="dataframe", dtype="int") def bench_apply_boolean_mask(benchmark, dataframe): mask = make_boolean_mask_column(len(dataframe)) benchmark(dataframe._apply_boolean_mask, BooleanMask(mask, len(dataframe)))
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/common/config.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Module used for global configuration of benchmarks. This file contains global definitions that are important for configuring all benchmarks such as fixture sizes. In addition, this file supports the following features: - Defining the CUDF_BENCHMARKS_USE_PANDAS environment variable will change all benchmarks to run with pandas instead of cudf (and numpy instead of cupy). This feature enables easy comparisons of benchmarks between cudf and pandas. All common modules (cudf, cupy) should be imported from here by benchmark modules to allow configuration if needed. - Defining CUDF_BENCHMARKS_DEBUG_ONLY will set global configuration variables to avoid running large benchmarks, instead using minimal values to simply ensure that benchmarks are functional. This file is also where standard pytest hooks should be overridden. While these definitions typically belong in conftest.py, since any of the above environment variables could affect test collection or other properties, we must define them in this file and import them in conftest.py to ensure that they are handled appropriately. """ import os import sys # Environment variable-based configuration of benchmarking pandas or cudf. collect_ignore = [] if "CUDF_BENCHMARKS_USE_PANDAS" in os.environ: import numpy as cupy import pandas as cudf # cudf internals offer no pandas compatibility guarantees, and we also # never need to compare those benchmarks to pandas. collect_ignore.append("internal/") # Also filter out benchmarks of APIs that are not compatible with pandas. def is_pandas_compatible(item): return all(m.name != "pandas_incompatible" for m in item.own_markers) def pytest_collection_modifyitems(session, config, items): items[:] = list(filter(is_pandas_compatible, items)) else: import cupy # noqa: W0611, F401 import cudf # noqa: W0611, F401 def pytest_collection_modifyitems(session, config, items): pass def pytest_sessionstart(session): """Add the common files to the path for all tests to import.""" sys.path.insert(0, os.path.join(os.getcwd(), "common")) def pytest_sessionfinish(session, exitstatus): """Clean up sys.path after exit.""" if "common" in sys.path[0]: del sys.path[0] # Constants used to define benchmarking standards. if "CUDF_BENCHMARKS_DEBUG_ONLY" in os.environ: NUM_ROWS = [10, 20] NUM_COLS = [1, 6] else: NUM_ROWS = [100, 10_000, 1_000_000] NUM_COLS = [1, 6]
0
rapidsai_public_repos/cudf/python/cudf/benchmarks
rapidsai_public_repos/cudf/python/cudf/benchmarks/common/utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Common utilities for fixture creation and benchmarking.""" import inspect import re import textwrap from collections.abc import MutableSet from itertools import groupby from numbers import Real import pytest_cases from config import NUM_COLS, NUM_ROWS, cudf, cupy def make_gather_map(len_gather_map: Real, len_column: Real, how: str): """Create a gather map based on "how" you'd like to gather from input. - sequence: gather the first `len_gather_map` rows, the first thread collects the first element - reverse: gather the last `len_gather_map` rows, the first thread collects the last element - random: create a pseudorandom gather map `len_gather_map`, `len_column` gets rounded to integer. """ len_gather_map = round(len_gather_map) len_column = round(len_column) rstate = cupy.random.RandomState(seed=0) if how == "sequence": return cudf.Series(cupy.arange(0, len_gather_map)) elif how == "reverse": return cudf.Series( cupy.arange(len_column - 1, len_column - len_gather_map - 1, -1) ) elif how == "random": return cudf.Series(rstate.randint(0, len_column, len_gather_map)) def make_boolean_mask_column(size): rstate = cupy.random.RandomState(seed=0) return cudf.core.column.as_column(rstate.randint(0, 2, size).astype(bool)) def benchmark_with_object( cls, *, dtype="int", nulls=None, cols=None, rows=None ): """Pass "standard" cudf fixtures to functions without renaming parameters. The fixture generation logic in conftest.py provides a plethora of useful fixtures to allow developers to easily select an appropriate cross-section of the space of objects to apply a particular benchmark to. However, the usage of these fixtures is cumbersome because creating them in a principled fashion results in long names and very specific naming schemes. This decorator abstracts that naming logic away from the developer, allowing them to instead focus on defining the fixture semantically by describing its properties. Parameters ---------- cls : Union[str, Type] The class of object to test. May either be specified as the type itself, or using the name (as a string). If a string, the case is irrelevant as the string will be converted to all lowercase. dtype : Union[str, Iterable[str]], default 'int' The dtype or set of dtypes to use. nulls : Optional[bool], default None Whether to test nullable or non-nullable data. If None, both nullable and non-nullable data are included. cols : Optional[int], None The number of columns. Only valid if cls == 'dataframe'. If None, use all possible numbers of columns. Specifying multiple values is unsupported. rows : Optional[int], None The number of rows. If None, use all possible numbers of rows. Specifying multiple values is unsupported. Raises ------ AssertionError If any of the parameters do not correspond to extant fixtures. Examples -------- # Note: As an internal function, this example is not meant for doctesting. @benchmark_with_object("dataframe", dtype="int", nulls=False) def bench_columns(benchmark, df): benchmark(df.columns) """ if inspect.isclass(cls): cls = cls.__name__ cls = cls.lower() supported_classes = ( "column", "series", "index", "dataframe", "indexedframe", "frame_or_index", ) assert cls in supported_classes, ( f"cls {cls} is invalid, choose from " f"{', '.join(supported_classes)}" ) if not isinstance(dtype, list): dtype = [dtype] assert all(dt in column_generators for dt in dtype), ( f"The only supported dtypes are " f"{', '.join(column_generators)}" ) dtype_str = "_dtype_" + "_or_".join(dtype) null_str = "" if nulls is not None: null_str = f"_nulls_{nulls}".lower() col_str = "" if cols is not None: assert cols in NUM_COLS, ( f"You have requested a DataFrame with {cols} columns but fixtures " f"only exist for the values {', '.join(NUM_COLS)}" ) col_str = f"_cols_{cols}" row_str = "" if rows is not None: assert rows in NUM_ROWS, ( f"You have requested a {cls} with {rows} rows but fixtures " f"only exist for the values {', '.join(NUM_ROWS)}" ) row_str = f"_rows_{rows}" fixture_name = f"{cls}{dtype_str}{null_str}{col_str}{row_str}" def deco(bm): # pytest's test collection process relies on parsing the globals dict # to find test functions and identify their parameters for the purpose # of fixtures and parameters. Therefore, the primary purpose of this # decorator is to define a new benchmark function with a signature # identical to that of the decorated benchmark except with the user's # fixture name replaced by the true fixture name based on the arguments # to benchmark_with_object. parameters = inspect.signature(bm).parameters # Note: This logic assumes that any benchmark using this fixture has at # least two parameters since they must be using both the # pytest-benchmark `benchmark` fixture and the cudf object. params_str = ", ".join(f"{p}" for p in parameters if p != cls) arg_str = ", ".join(f"{p}={p}" for p in parameters if p != cls) if params_str: params_str += ", " if arg_str: arg_str += ", " params_str += f"{fixture_name}" arg_str += f"{cls}={fixture_name}" src = textwrap.dedent( f""" import makefun @makefun.wraps( bm, remove_args=("{cls}",), prepend_args=("{fixture_name}",) ) def wrapped_bm({params_str}): return bm({arg_str}) """ ) globals_ = {"bm": bm} exec(src, globals_) wrapped_bm = globals_["wrapped_bm"] # In case marks were applied to the original benchmark, copy them over. if marks := getattr(bm, "pytestmark", None): wrapped_bm.pytestmark = marks wrapped_bm.place_as = bm return wrapped_bm return deco class OrderedSet(MutableSet): """A minimal OrderedSet implementation built on a dict. This implementation exploits the fact that dicts are ordered as of Python 3.7. It is not intended to be performant, so only the minimal set of methods are implemented. We need this class to ensure that fixture names are constructed deterministically, otherwise pytest-xdist will complain if different threads have seemingly different tests. """ def __init__(self, args=None): args = args or [] self._data = {value: None for value in args} def __contains__(self, key): return key in self._data def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) def __repr__(self): # Helpful for debugging. data = ", ".join(str(i) for i in self._data) return f"{self.__class__.__name__}({data})" def add(self, value): self._data[value] = None def discard(self, value): self._data.pop(value, None) def make_fixture(name, func, globals_, fixtures): """Create a named fixture in `globals_` and save its name in `fixtures`. https://github.com/pytest-dev/pytest/issues/2424#issuecomment-333387206 explains why this hack is necessary. Essentially, dynamically generated fixtures must exist in globals() to be found by pytest. """ globals_[name] = pytest_cases.fixture(name=name)(func) fixtures.add(name) def collapse_fixtures(fixtures, pattern, repl, globals_, idfunc=None): """Create unions of fixtures based on specific name mappings. `fixtures` are grouped into unions according the regex replacement `re.sub(pattern, repl)` and placed into `new_fixtures`. """ def collapser(n): return re.sub(pattern, repl, n) # Note: sorted creates a new list, not a view, so it's OK to modify the # list of fixtures while iterating over the sorted result. for name, group in groupby(sorted(fixtures, key=collapser), key=collapser): group = list(group) if len(group) > 1 and name not in fixtures: pytest_cases.fixture_union(name=name, fixtures=group, ids=idfunc) # Need to assign back to the parent scope's globals. globals_[name] = globals()[name] fixtures.add(name) # A dictionary of callables that create a column of a specified length random_state = cupy.random.RandomState(42) column_generators = { "int": (lambda nr: random_state.randint(low=0, high=100, size=nr)), "float": (lambda nr: random_state.rand(nr)), }
0
rapidsai_public_repos/cudf/python/cudf/cmake
rapidsai_public_repos/cudf/python/cudf/cmake/Modules/ProtobufHelpers.cmake
# ============================================================================= # Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= include_guard(GLOBAL) # Compile protobuf files to Python. All arguments are assumed to be .proto files. function(codegen_protoc) # Allow user to provide path to protoc executable as an environment variable. if(DEFINED ENV{PROTOC}) set(protoc_COMMAND $ENV{PROTOC}) else() find_program(protoc_COMMAND protoc REQUIRED) endif() foreach(_proto_path IN LISTS ARGV) string(REPLACE "\.proto" "_pb2\.py" pb2_py_path "${_proto_path}") set(pb2_py_path "${CMAKE_CURRENT_SOURCE_DIR}/${pb2_py_path}") # Note: If we ever need to process larger numbers of protobuf files we should consider switching # to protobuf_generate_python from the FindProtobuf module. execute_process( COMMAND ${protoc_COMMAND} --python_out=. "${_proto_path}" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMAND_ERROR_IS_FATAL ANY ) # Mark entire file to skip formatting. file(READ "${pb2_py_path}" pb2_py) file( WRITE "${pb2_py_path}" [=[ # fmt: off ]=] ) file(APPEND "${pb2_py_path}" "${pb2_py}") file( APPEND "${pb2_py_path}" [=[ # fmt: on ]=] ) endforeach() endfunction()
0
rapidsai_public_repos/cudf/python/cudf/cmake
rapidsai_public_repos/cudf/python/cudf/cmake/Modules/WheelHelpers.cmake
# ============================================================================= # Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= include_guard(GLOBAL) # Making libraries available inside wheels by installing the associated targets. function(add_target_libs_to_wheel) list(APPEND CMAKE_MESSAGE_CONTEXT "add_target_libs_to_wheel") set(options "") set(one_value "LIB_DIR") set(multi_value "TARGETS") cmake_parse_arguments(_ "${options}" "${one_value}" "${multi_value}" ${ARGN}) message(VERBOSE "Installing targets '${__TARGETS}' into lib_dir '${__LIB_DIR}'") foreach(target IN LISTS __TARGETS) if(NOT TARGET ${target}) message(VERBOSE "No target named ${target}") continue() endif() get_target_property(alias_target ${target} ALIASED_TARGET) if(alias_target) set(target ${alias_target}) endif() get_target_property(is_imported ${target} IMPORTED) if(NOT is_imported) # If the target isn't imported, install it into the wheel install(TARGETS ${target} DESTINATION ${__LIB_DIR}) message(VERBOSE "install(TARGETS ${target} DESTINATION ${__LIB_DIR})") else() # If the target is imported, make sure it's global get_target_property(already_global ${target} IMPORTED_GLOBAL) if(NOT already_global) set_target_properties(${target} PROPERTIES IMPORTED_GLOBAL TRUE) endif() # Find the imported target's library so we can copy it into the wheel set(lib_loc) foreach(prop IN ITEMS IMPORTED_LOCATION IMPORTED_LOCATION_RELEASE IMPORTED_LOCATION_DEBUG) get_target_property(lib_loc ${target} ${prop}) if(lib_loc) message(VERBOSE "Found ${prop} for ${target}: ${lib_loc}") break() endif() message(VERBOSE "${target} has no value for property ${prop}") endforeach() if(NOT lib_loc) message(FATAL_ERROR "Found no libs to install for target ${target}") endif() # Copy the imported library into the wheel install(FILES ${lib_loc} DESTINATION ${__LIB_DIR}) message(VERBOSE "install(FILES ${lib_loc} DESTINATION ${__LIB_DIR})") endif() endforeach() endfunction()
0
rapidsai_public_repos/cudf/python
rapidsai_public_repos/cudf/python/custreamz/pyproject.toml
# Copyright (c) 2021-2022, NVIDIA CORPORATION. [build-system] build-backend = "setuptools.build_meta" requires = [ "setuptools", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project] name = "custreamz" dynamic = ["version"] description = "cuStreamz - GPU Accelerated Streaming" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "confluent-kafka>=1.9.0,<1.10.0a0", "cudf==24.2.*", "cudf_kafka==24.2.*", "streamz", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Topic :: Streaming", "Topic :: Scientific/Engineering", "Topic :: Apache Kafka", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ] [project.optional-dependencies] test = [ "pytest", "pytest-cov", "pytest-xdist", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cudf" [tool.setuptools] license-files = ["LICENSE"] zip-safe = false [tool.setuptools.dynamic] version = {file = "custreamz/VERSION"} [tools.setuptools.packages.find] include = [ "custreamz", "custreamz.*", ] [tool.isort] line_length = 79 multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 combine_as_imports = true order_by_type = true known_dask = [ "dask", "distributed", "dask_cuda", ] known_rapids = [ "rmm", "cudf", "dask_cudf", ] known_first_party = [ "streamz", ] default_section = "THIRDPARTY" sections = [ "FUTURE", "STDLIB", "THIRDPARTY", "DASK", "RAPIDS", "FIRSTPARTY", "LOCALFOLDER", ] skip = [ "thirdparty", ".eggs", ".git", ".hg", ".mypy_cache", ".tox", ".venv", "_build", "buck-out", "build", "dist", "__init__.py", ]
0
rapidsai_public_repos/cudf/python
rapidsai_public_repos/cudf/python/custreamz/README.md
# custreamz - GPU Accelerated Streaming Built as an extension to [python streamz](https://github.com/python-streamz/streamz), cuStreamz provides GPU accelerated abstractions for streaming data. CuStreamz can be used along side python streamz or as a standalone library for ingesting streaming data to cudf dataframes. The most common use for cuStreamz is accelerated data ingestion to a cudf dataframe. CuStreamz currently supports ingestion from Apache Kafka in the following message formats; Avro, CSV, JSON, Parquet, and ORC. For example, the following snippet consumes CSV data from a Kafka topic named `custreamz_tips` and generates a cudf dataframe. Users can visit [Apache Kafka Quickstart](https://kafka.apache.org/quickstart) to learn how to install, create `custreamz_tips` topic, and insert the [tips](https://github.com/plotly/datasets/raw/master/tips.csv) data into Kafka. ```python from custreamz import kafka # Full list of configurations can be found at: https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md kafka_configs = { "metadata.broker.list": "localhost:9092", "group.id": "custreamz-client", } # Create a reusable Kafka Consumer client; "datasource" consumer = kafka.Consumer(kafka_configs) # Read 10,000 messages from `custreamz_tips` topic in CSV format. tips_df = consumer.read_gdf(topic="custreamz_tips", partition=0, start=0, end=10000, message_format="CSV") print(tips_df.head()) tips_df['tip_percentage'] = tips_df['tip'] / tips_df['total_bill'] * 100 # display average tip by dining party size print(tips_df.groupby('size').tip_percentage.mean()) ``` A "hello world" of using cuStreamz with python streamz can be found [here](https://github.com/rapidsai-community/notebooks-contrib/blob/main/getting_started_materials/hello_worlds/hello_streamz.ipynb) A more detailed example of [parsing haproxy logs](https://github.com/rapidsai-community/notebooks-contrib/blob/branch-0.14/intermediate_notebooks/examples/custreamz/parsing_haproxy_logs.ipynb) is also available. ## Quick Start Please see the [Demo Docker Repository](https://hub.docker.com/r/rapidsai/rapidsai/), choosing a tag based on the NVIDIA CUDA version you're running. This provides a ready to run Docker container with cuStreamz already installed. ## Installation ### CUDA/GPU requirements * CUDA 11.0+ * NVIDIA driver 450.80.02+ * Pascal architecture or better (Compute Capability >=6.0) ### Conda cuStreamz is installed with conda ([miniconda](https://conda.io/miniconda.html), or the full [Anaconda distribution](https://www.anaconda.com/download)) from the `rapidsai` or `rapidsai-nightly` channel: Release: ```bash conda install -c rapidsai cudf_kafka custreamz ``` Nightly: ```bash conda install -c rapidsai-nightly cudf_kafka custreamz ``` See the [Get RAPIDS version picker](https://rapids.ai/start.html) for more OS and version info.
0
rapidsai_public_repos/cudf/python
rapidsai_public_repos/cudf/python/custreamz/setup.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from setuptools import setup setup( package_data={"custreamz": ["VERSION"]}, )
0
rapidsai_public_repos/cudf/python
rapidsai_public_repos/cudf/python/custreamz/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cudf/python
rapidsai_public_repos/cudf/python/custreamz/.coveragerc
# Configuration file for Python coverage tests [run] source = custreamz
0
rapidsai_public_repos/cudf/python/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/kafka.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import confluent_kafka as ck from cudf_kafka._lib.kafka import KafkaDatasource import cudf # Base class for anything class that needs to interact with Apache Kafka class CudfKafkaClient: def __init__(self, kafka_configs): """ Base object for any client that wants to interact with a Kafka broker. This object creates the underlying KafkaDatasource connection which is used to read data from Kafka and create cudf Dataframes. This class should not be directly instantiated. Parameters ---------- kafka_configs : dict, Dict of Key/Value pairs of librdkafka configuration values. Full list of valid configuration options can be found at https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md """ self.kafka_configs = kafka_configs self.kafka_meta_client = KafkaDatasource(kafka_configs) self.ck_consumer = ck.Consumer(kafka_configs) def list_topics(self, specific_topic=None): """ List the topics associated with the underlying Kafka Broker connection. Parameters ---------- specific_topic : str, If specified this is the only topic that metadata information will be retrieved for. Otherwise metadata for all topics in the broker will be retrieved. """ return self.kafka_meta_client.list_topics( b"" if specific_topic is None else specific_topic.encode() ) def unsubscribe(self): """ Stop all active consumption and remove consumer subscriptions to topic/partition instances """ self.kafka_meta_client.unsubscribe() def close(self, timeout=10000): """ Close the underlying socket connection to Kafka and clean up system resources """ self.kafka_meta_client.close(timeout) # Apache Kafka Consumer implementation class Consumer(CudfKafkaClient): def __init__(self, kafka_configs): """ Creates a KafkaConsumer object which allows for all valid Kafka consumer type operations such as reading messages, committing offsets, and retrieving the current consumption offsets. Parameters ---------- kafka_configs : dict, Dict of Key/Value pairs of librdkafka configuration values. Full list of valid configuration options can be found at https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md """ super().__init__(kafka_configs) def read_gdf( self, topic=None, partition=0, lines=True, start=0, end=0, batch_timeout=10000, delimiter="\n", message_format="json", ): r""" Read messages from the underlying KafkaDatasource connection and create a cudf Dataframe Parameters ---------- topic : str, Name of the Kafka topic that the messages should be read from partition : int, Partition number on the specified topic that should be read from lines : {{ True, False }}, default True, Whether messages should be treated as individual lines start : int, default 0, The beginning offset that should be used when reading a range of messages end : int, default 0, The last offset that will be read when reading a range of messages batch_timeout : int, default 10000, Amount of time to wait on the reading of the messages from Kafka in Milliseconds delimiter : str, default "\n", If lines=True this is the delimiter that will be placed between all messages that are read from Kafka message_format : {{ 'avro', 'csv', 'json', 'orc', 'parquet' }}, default 'json', Format of the messages that will be read from Kafka. This dictates which underlying cudf reader will be invoked the create the Dataframe. Returns ------- DataFrame """ if topic is None: raise ValueError( "ERROR: You must specify the topic " "that you want to consume from" ) kafka_datasource = KafkaDatasource( self.kafka_configs, topic.encode(), partition, start, end, batch_timeout, delimiter.encode(), ) cudf_readers = { "json": cudf.io.read_json, "csv": cudf.io.read_csv, "orc": cudf.io.read_orc, "avro": cudf.io.read_avro, "parquet": cudf.io.read_parquet, } result = cudf_readers[message_format]( kafka_datasource, engine="cudf", lines=True ) # Close up the cudf datasource instance # TODO: Ideally the C++ destructor should handle the # unsubscribe and closing the socket connection. kafka_datasource.unsubscribe() kafka_datasource.close(batch_timeout) if result is not None: if isinstance(result, cudf.DataFrame): return result else: return cudf.DataFrame._from_data(result) else: # empty Dataframe return cudf.DataFrame() def committed(self, partitions, timeout=10000): """ Retrieves the last successfully committed Kafka offset of the underlying KafkaDatasource connection. Parameters ---------- partitions : list, Topic/Partition instances that specify the TOPPAR instances the offsets should be retrieved for timeout : int, default 10000, Max time to wait on the response from the Kafka broker in milliseconds Returns ------- tuple Tuple of ck.TopicPartition objects """ toppars = [ ck.TopicPartition( part.topic, part.partition, self.kafka_meta_client.get_committed_offset( part.topic.encode(), part.partition ), ) for part in partitions ] return toppars def get_watermark_offsets(self, partition, timeout=10000, cached=False): """ Retrieve the low and high watermark offsets from the Kafka consumer Returns ------- Tuple with a [low, high] value Examples -------- >>> from custream import kafka >>> kafka_configs = { ... "metadata.broker.list": "localhost:9092", ... "enable.partition.eof": "true", ... "group.id": "groupid", ... "auto.offset.reset": "earliest", ... "enable.auto.commit": "false" ... } >>> consumer = kafka.KafkaHandle(kafka_configs, ... topics=["kafka-topic"], partitions=[0])) >>> low, high = consumer.get_watermark_offsets("kafka-topic", 0) """ offsets = () try: offsets = self.kafka_meta_client.get_watermark_offset( topic=partition.topic.encode(), partition=partition.partition, timeout=timeout, cached=cached, ) except RuntimeError: raise RuntimeError("Unable to connect to Kafka broker") if len(offsets) != 2: raise RuntimeError( f"Multiple watermark offsets encountered. " f"Only 2 were expected and {len(offsets)} encountered" ) if offsets[b"low"] < 0: offsets[b"low"] = 0 if offsets[b"high"] < 0: offsets[b"high"] = 0 return offsets[b"low"], offsets[b"high"] def commit(self, offsets=None, asynchronous=True): """ Takes a list of ck.TopicPartition objects and commits their offset values to the KafkaDatasource connection Parameters ---------- offsets : list, ck.TopicPartition objects containing the Topic/Partition/Offset values to be committed to the Kafka broker asynchronous : {{ True, False }}, default True, True to wait on Kafka broker response to commit request and False otherwise """ for offs in offsets: self.kafka_meta_client.commit_offset( offs.topic.encode(), offs.partition, offs.offset ) def poll(self, timeout=None): """ Consumes a single message, calls callbacks and returns events. The application must check the returned Message object's Message.error() method to distinguish between proper messages (error() returns None), or an event or error (see error().code() for specifics). Parameters ---------- timeout : float Maximum time to block waiting for message, event or callback (default: infinite (None translated into -1 in the library)). (Seconds) """ return self.ck.poll(timeout)
0
rapidsai_public_repos/cudf/python/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/_version.py
# 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. import importlib.resources __version__ = ( importlib.resources.files("custreamz") .joinpath("VERSION") .read_text() .strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cudf/python/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/__init__.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from ._version import __git_commit__, __version__ from .kafka import Consumer
0
rapidsai_public_repos/cudf/python/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/VERSION
24.02.00
0
rapidsai_public_repos/cudf/python/custreamz/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/tests/test_kafka.py
# Copyright (c) 2020, NVIDIA CORPORATION. import confluent_kafka as ck import pytest from cudf.testing._utils import assert_eq @pytest.mark.parametrize("commit_offset", [1, 45, 100, 22, 1000, 10]) @pytest.mark.parametrize("topic", ["cudf-kafka-test-topic"]) def test_kafka_offset(kafka_client, topic, commit_offset): offsets = [ck.TopicPartition(topic, 0, commit_offset)] kafka_client.commit(offsets=offsets) # Get the offsets that were just committed to Kafka retrieved_offsets = kafka_client.committed(offsets) for off in retrieved_offsets: assert_eq(off.topic, offsets[0].topic) assert_eq(off.partition, offsets[0].partition) assert_eq(off.offset, offsets[0].offset)
0
rapidsai_public_repos/cudf/python/custreamz/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/tests/test_dataframes.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. """ Tests for Streamz Dataframes (SDFs) built on top of cuDF DataFrames. *** Borrowed from streamz.dataframe.tests | License at thirdparty/LICENSE *** """ import json import operator import numpy as np import pandas as pd import pytest from dask.dataframe.utils import assert_eq from distributed import Client from streamz import Stream from streamz.dask import DaskStream from streamz.dataframe import Aggregation, DataFrame, DataFrames, Series cudf = pytest.importorskip("cudf") @pytest.fixture(scope="module") def client(): client = Client(processes=False, asynchronous=False) try: yield client finally: client.close() @pytest.fixture(params=["core", "dask"]) def stream(request, client): if request.param == "core": return Stream() else: return DaskStream() def test_identity(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) L = sdf.stream.gather().sink_to_list() sdf.emit(df) assert L[0] is df assert list(sdf.example.columns) == ["x", "y"] x = sdf.x assert isinstance(x, Series) L2 = x.stream.gather().sink_to_list() assert not L2 sdf.emit(df) assert isinstance(L2[0], cudf.Series) assert_eq(L2[0], df.x) def test_dtype(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) assert str(sdf.dtypes) == str(df.dtypes) assert sdf.x.dtype == df.x.dtype assert sdf.index.dtype == df.index.dtype def test_attributes(): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df) assert getattr(sdf, "x", -1) != -1 assert getattr(sdf, "z", -1) == -1 sdf.x with pytest.raises(AttributeError): sdf.z def test_exceptions(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) with pytest.raises(TypeError): sdf.emit(1) with pytest.raises(IndexError): sdf.emit(cudf.DataFrame()) @pytest.mark.parametrize( "func", [lambda x: x.sum(), lambda x: x.mean(), lambda x: x.count()] ) def test_reductions(stream, func): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) for example in [df, df.iloc[:0]]: sdf = DataFrame(example=example, stream=stream) df_out = func(sdf).stream.gather().sink_to_list() x = sdf.x x_out = func(x).stream.gather().sink_to_list() sdf.emit(df) sdf.emit(df) assert_eq(df_out[-1], func(cudf.concat([df, df]))) assert_eq(x_out[-1], func(cudf.concat([df, df]).x)) @pytest.mark.parametrize( "op", [ operator.add, operator.and_, operator.eq, operator.floordiv, operator.ge, operator.gt, operator.le, operator.lshift, operator.lt, operator.mod, operator.mul, operator.ne, operator.or_, operator.pow, operator.rshift, operator.sub, operator.truediv, operator.xor, ], ) @pytest.mark.parametrize("getter", [lambda df: df, lambda df: df.x]) def test_binary_operators(op, getter, stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) try: left = op(getter(df), 2) right = op(2, getter(df)) except Exception: return a = DataFrame(example=df, stream=stream) li = op(getter(a), 2).stream.gather().sink_to_list() r = op(2, getter(a)).stream.gather().sink_to_list() a.emit(df) assert_eq(li[0], left) assert_eq(r[0], right) @pytest.mark.parametrize( "op", [ operator.abs, operator.inv, operator.invert, operator.neg, lambda x: x.map(lambda x: x + 1), lambda x: x.reset_index(), lambda x: x.astype(float), ], ) @pytest.mark.parametrize("getter", [lambda df: df, lambda df: df.x]) def test_unary_operators(op, getter): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) try: expected = op(getter(df)) except Exception: return a = DataFrame(example=df) b = op(getter(a)).stream.sink_to_list() a.emit(df) assert_eq(b[0], expected) @pytest.mark.parametrize( "func", [ lambda df: df.query("x > 1 and x < 4"), pytest.param( lambda df: df.x.value_counts().nlargest(2).astype(int), marks=pytest.mark.xfail(reason="Index name lost in _getattr_"), ), ], ) def test_dataframe_simple(func): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) expected = func(df) a = DataFrame(example=df) L = func(a).stream.sink_to_list() a.emit(df) assert_eq(L[0], expected) def test_set_index(): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) a = DataFrame(example=df) b = a.set_index("x").stream.sink_to_list() a.emit(df) assert_eq(b[0], df.set_index("x")) b = a.set_index(a.y + 1).stream.sink_to_list() a.emit(df) assert_eq(b[0], df.set_index(df.y + 1)) def test_binary_stream_operators(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) expected = df.x + df.y a = DataFrame(example=df, stream=stream) b = (a.x + a.y).stream.gather().sink_to_list() a.emit(df) assert_eq(b[0], expected) def test_index(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) a = DataFrame(example=df, stream=stream) b = a.index + 5 L = b.stream.gather().sink_to_list() a.emit(df) a.emit(df) assert_eq(L[0], df.index + 5) assert_eq(L[1], df.index + 5) def test_pair_arithmetic(stream): df = cudf.DataFrame({"x": list(range(10)), "y": [1] * 10}) a = DataFrame(example=df.iloc[:0], stream=stream) L = ((a.x + a.y) * 2).stream.gather().sink_to_list() a.emit(df.iloc[:5]) a.emit(df.iloc[5:]) assert len(L) == 2 assert_eq(cudf.concat(L), (df.x + df.y) * 2) def test_getitem(stream): df = cudf.DataFrame({"x": list(range(10)), "y": [1] * 10}) a = DataFrame(example=df.iloc[:0], stream=stream) L = a[a.x > 4].stream.gather().sink_to_list() a.emit(df.iloc[:5]) a.emit(df.iloc[5:]) assert len(L) == 2 assert_eq(cudf.concat(L), df[df.x > 4]) @pytest.mark.parametrize("agg", [lambda x: x.sum(), lambda x: x.mean()]) @pytest.mark.parametrize( "grouper", [lambda a: a.x % 3, lambda a: "x", lambda a: a.index % 2, lambda a: ["x"]], ) @pytest.mark.parametrize( "indexer", [lambda g: g, lambda g: g[["y"]], lambda g: g[["x", "y"]]] ) def test_groupby_aggregate(agg, grouper, indexer, stream): df = cudf.DataFrame( {"x": (np.arange(10) // 2).astype(float), "y": [1.0, 2.0] * 5} ) a = DataFrame(example=df.iloc[:0], stream=stream) def f(x): return agg(indexer(x.groupby(grouper(x)))) L = f(a).stream.gather().sink_to_list() a.emit(df.iloc[:3]) a.emit(df.iloc[3:7]) a.emit(df.iloc[7:]) first = df.iloc[:3] g = f(first) h = f(df) assert_eq(L[0], g) assert_eq(L[-1], h) def test_repr(stream): df = cudf.DataFrame( {"x": (np.arange(10) // 2).astype(float), "y": [1.0] * 10} ) a = DataFrame(example=df, stream=stream) text = repr(a) assert type(a).__name__ in text assert "x" in text assert "y" in text text = repr(a.x) assert type(a.x).__name__ in text assert "x" in text text = repr(a.x.sum()) assert type(a.x.sum()).__name__ in text def test_repr_html(stream): df = cudf.DataFrame( {"x": (np.arange(10) // 2).astype(float), "y": [1.0] * 10} ) a = DataFrame(example=df, stream=stream) for x in [a, a.y, a.y.mean()]: html = x._repr_html_() assert type(x).__name__ in html assert "1" in html def test_setitem(stream): df = cudf.DataFrame({"x": list(range(10)), "y": [1] * 10}) sdf = DataFrame(example=df.iloc[:0], stream=stream) stream = sdf.stream sdf["z"] = sdf["x"] * 2 sdf["a"] = 10 sdf[["c", "d"]] = sdf[["x", "y"]] L = sdf.mean().stream.gather().sink_to_list() stream.emit(df.iloc[:3]) stream.emit(df.iloc[3:7]) stream.emit(df.iloc[7:]) df["z"] = df["x"] * 2 df["a"] = 10 df["c"] = df["x"] df["d"] = df["y"] assert_eq(L[-1], df.mean()) def test_setitem_overwrites(stream): df = cudf.DataFrame({"x": list(range(10))}) sdf = DataFrame(example=df.iloc[:0], stream=stream) stream = sdf.stream sdf["x"] = sdf["x"] * 2 L = sdf.stream.gather().sink_to_list() stream.emit(df.iloc[:3]) stream.emit(df.iloc[3:7]) stream.emit(df.iloc[7:]) assert_eq(L[-1], df.iloc[7:] * 2) @pytest.mark.parametrize( "kwargs,op", [ ({}, "sum"), ({}, "mean"), pytest.param({}, "min"), pytest.param( {}, "median", marks=pytest.mark.xfail(reason="Unavailable for rolling objects"), ), pytest.param({}, "max"), pytest.param( {}, "var", marks=pytest.mark.xfail(reason="Unavailable for rolling objects"), ), pytest.param({}, "count"), pytest.param( {"ddof": 0}, "std", marks=pytest.mark.xfail(reason="Unavailable for rolling objects"), ), pytest.param( {"quantile": 0.5}, "quantile", marks=pytest.mark.xfail(reason="Unavailable for rolling objects"), ), pytest.param( {"arg": {"A": "sum", "B": "min"}}, "aggregate", marks=pytest.mark.xfail(reason="Unavailable for rolling objects"), ), ], ) @pytest.mark.parametrize( "window", [pytest.param(2), 7, pytest.param("3h"), pd.Timedelta("200 minutes")], ) @pytest.mark.parametrize("m", [2, pytest.param(5)]) @pytest.mark.parametrize( "pre_get,post_get", [ (lambda df: df, lambda df: df), (lambda df: df.x, lambda x: x), (lambda df: df, lambda df: df.x), ], ) def test_rolling_count_aggregations( op, window, m, pre_get, post_get, kwargs, stream ): index = pd.DatetimeIndex( pd.date_range("2000-01-01", "2000-01-03", freq="1h") ) df = cudf.DataFrame({"x": np.arange(len(index))}, index=index) expected = getattr(post_get(pre_get(df).rolling(window)), op)(**kwargs) sdf = DataFrame(example=df, stream=stream) roll = getattr(post_get(pre_get(sdf).rolling(window)), op)(**kwargs) L = roll.stream.gather().sink_to_list() assert len(L) == 0 for i in range(0, len(df), m): sdf.emit(df.iloc[i : i + m]) assert len(L) > 1 assert_eq(cudf.concat(L), expected) def test_stream_to_dataframe(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) source = stream L = source.to_dataframe(example=df).x.sum().stream.gather().sink_to_list() source.emit(df) source.emit(df) source.emit(df) assert L == [6, 12, 18] def test_integration_from_stream(stream): source = stream sdf = ( source.partition(4) .to_batch(example=['{"x": 0, "y": 0}']) .map(json.loads) .to_dataframe() ) result = sdf.groupby(sdf.x).y.sum().mean() L = result.stream.gather().sink_to_list() for i in range(12): source.emit(json.dumps({"x": i % 3, "y": i})) assert L == [2, 28 / 3, 22.0] def test_to_frame(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) assert sdf.to_frame() is sdf a = sdf.x.to_frame() assert isinstance(a, DataFrame) assert list(a.columns) == ["x"] @pytest.mark.parametrize("op", ["cumsum", "cummax", "cumprod", "cummin"]) @pytest.mark.parametrize("getter", [lambda df: df, lambda df: df.x]) def test_cumulative_aggregations(op, getter, stream): df = cudf.DataFrame({"x": list(range(10)), "y": [1] * 10}) expected = getattr(getter(df), op)() sdf = DataFrame(example=df, stream=stream) L = getattr(getter(sdf), op)().stream.gather().sink_to_list() for i in range(0, 10, 3): sdf.emit(df.iloc[i : i + 3]) sdf.emit(df.iloc[:0]) assert len(L) > 1 assert_eq(cudf.concat(L), expected) @pytest.mark.xfail( reason="IPyWidgets 8.0 broke streamz 0.6.4. " "We should remove this xfail when this is fixed in streamz." ) def test_display(stream): pytest.importorskip("ipywidgets") pytest.importorskip("IPython") df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) s = sdf.x.sum() s._ipython_display_() def test_tail(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) L = sdf.tail(2).stream.gather().sink_to_list() sdf.emit(df) sdf.emit(df) assert_eq(L[0], df.tail(2)) assert_eq(L[1], df.tail(2)) def test_example_type_error_message(): try: DataFrame(example=[123]) except Exception as e: assert "DataFrame" in str(e) assert "[123]" in str(e) def test_dataframes(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrames(example=df, stream=stream) L = sdf.x.sum().stream.gather().sink_to_list() sdf.emit(df) sdf.emit(df) assert L == [6, 6] def test_groupby_aggregate_updating(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) assert sdf.groupby("x").y.mean()._stream_type == "updating" assert sdf.x.sum()._stream_type == "updating" assert (sdf.x.sum() + 1)._stream_type == "updating" def test_window_sum(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) L = sdf.window(n=4).x.sum().stream.gather().sink_to_list() sdf.emit(df) assert L == [6] sdf.emit(df) assert L == [6, 9] sdf.emit(df) assert L == [6, 9, 9] def test_window_sum_dataframe(stream): df = cudf.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) sdf = DataFrame(example=df, stream=stream) L = sdf.window(n=4).sum().stream.gather().sink_to_list() sdf.emit(df) assert_eq(L[0], cudf.Series([6, 15], index=["x", "y"])) sdf.emit(df) assert_eq(L[0], cudf.Series([6, 15], index=["x", "y"])) assert_eq(L[1], cudf.Series([9, 21], index=["x", "y"])) sdf.emit(df) assert_eq(L[0], cudf.Series([6, 15], index=["x", "y"])) assert_eq(L[1], cudf.Series([9, 21], index=["x", "y"])) assert_eq(L[2], cudf.Series([9, 21], index=["x", "y"])) @pytest.mark.parametrize( "func", [ lambda x: x.sum(), lambda x: x.mean(), lambda x: x.count(), lambda x: x.var(ddof=1), lambda x: x.std(ddof=1), lambda x: x.var(ddof=0), ], ) @pytest.mark.parametrize("n", [2, 4]) @pytest.mark.parametrize("getter", [lambda df: df.x]) def test_windowing_n(func, n, getter): df = cudf.DataFrame({"x": list(range(10)), "y": [1, 2] * 5}) sdf = DataFrame(example=df) L = func(getter(sdf).window(n=n)).stream.gather().sink_to_list() for i in range(0, 10, 3): sdf.emit(df.iloc[i : i + 3]) sdf.emit(df.iloc[:0]) assert len(L) == 5 assert_eq(L[0], func(getter(df).iloc[max(0, 3 - n) : 3])) assert_eq(L[-1], func(getter(df).iloc[len(df) - n :])) @pytest.mark.parametrize("func", [lambda x: x.sum(), lambda x: x.mean()]) @pytest.mark.parametrize("value", ["10h", "1d"]) @pytest.mark.parametrize("getter", [lambda df: df, lambda df: df.x]) @pytest.mark.parametrize( "grouper", [lambda a: "y", lambda a: a.index, lambda a: ["y"]] ) @pytest.mark.parametrize( "indexer", [lambda g: g, lambda g: g[["x"]], lambda g: g[["x", "y"]]] ) def test_groupby_windowing_value(func, value, getter, grouper, indexer): index = pd.DatetimeIndex( pd.date_range("2000-01-01", "2000-01-03", freq="1h") ) df = cudf.DataFrame( { "x": np.arange(len(index), dtype=float), "y": np.arange(len(index), dtype=float) % 2, }, index=index, ) value = pd.Timedelta(value) sdf = DataFrame(example=df) def f(x): return func(indexer(x.groupby(grouper(x)))) L = f(sdf.window(value)).stream.gather().sink_to_list() diff = 13 for i in range(0, len(index), diff): sdf.emit(df.iloc[i : i + diff]) assert len(L) == 4 first = df.iloc[:diff] lost = first.loc[first.index.min() + value :] first = first.iloc[len(lost) :] g = f(first) assert_eq(L[0], g) last = df.loc[index.max() - value + pd.Timedelta("1s") :] h = f(last) assert_eq(L[-1], h) @pytest.mark.parametrize("func", [lambda x: x.sum(), lambda x: x.mean()]) @pytest.mark.parametrize("n", [1, 4]) @pytest.mark.parametrize("getter", [lambda df: df, lambda df: df.x]) @pytest.mark.parametrize( "grouper", [lambda a: a.x % 3, lambda a: "y", lambda a: a.index % 2, lambda a: ["y"]], ) @pytest.mark.parametrize("indexer", [lambda g: g, lambda g: g[["x", "y"]]]) def test_groupby_windowing_n(func, n, getter, grouper, indexer): df = cudf.DataFrame({"x": np.arange(10, dtype=float), "y": [1.0, 2.0] * 5}) sdf = DataFrame(example=df) def f(x): return func(indexer(x.groupby(grouper(x)))) L = f(sdf.window(n=n)).stream.gather().sink_to_list() diff = 3 for i in range(0, 10, diff): sdf.emit(df.iloc[i : i + diff]) sdf.emit(df.iloc[:0]) assert len(L) == 5 first = df.iloc[max(0, diff - n) : diff] g = f(first) assert_eq(L[0], g) last = df.iloc[len(df) - n :] h = f(last) assert_eq(L[-1], h) def test_window_full(): df = cudf.DataFrame({"x": np.arange(10, dtype=float), "y": [1.0, 2.0] * 5}) sdf = DataFrame(example=df) L = sdf.window(n=4).apply(lambda x: x).stream.sink_to_list() sdf.emit(df.iloc[:3]) sdf.emit(df.iloc[3:8]) sdf.emit(df.iloc[8:]) assert_eq(L[0], df.iloc[:3]) assert_eq(L[1], df.iloc[4:8]) assert_eq(L[2], df.iloc[-4:]) def test_custom_aggregation(): df = cudf.DataFrame({"x": np.arange(10, dtype=float), "y": [1.0, 2.0] * 5}) class Custom(Aggregation): def initial(self, new): return 0 def on_new(self, state, new): return state + 1, state def on_old(self, state, new): return state - 100, state sdf = DataFrame(example=df) L = sdf.aggregate(Custom()).stream.sink_to_list() sdf.emit(df) sdf.emit(df) sdf.emit(df) assert L == [0, 1, 2] sdf = DataFrame(example=df) L = sdf.window(n=5).aggregate(Custom()).stream.sink_to_list() sdf.emit(df) sdf.emit(df) sdf.emit(df) assert L == [1, -198, -397] def test_groupby_aggregate_with_start_state(stream): example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example).groupby(["name"]) output0 = sdf.amount.sum(start=None).stream.gather().sink_to_list() output1 = ( sdf.amount.mean(with_state=True, start=None) .stream.gather() .sink_to_list() ) output2 = sdf.amount.count(start=None).stream.gather().sink_to_list() df = cudf.DataFrame({"name": ["Alice", "Tom"], "amount": [50, 100]}) stream.emit(df) out_df0 = cudf.DataFrame({"name": ["Alice", "Tom"], "amount": [50, 100]}) out_df1 = cudf.DataFrame( {"name": ["Alice", "Tom"], "amount": [50.0, 100.0]} ) out_df2 = cudf.DataFrame({"name": ["Alice", "Tom"], "amount": [1, 1]}) assert assert_eq(output0[0].reset_index(), out_df0) assert assert_eq(output1[0][1].reset_index(), out_df1) assert assert_eq(output2[0].reset_index(), out_df2) example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example).groupby(["name"]) output3 = sdf.amount.sum(start=output0[0]).stream.gather().sink_to_list() output4 = ( sdf.amount.mean(with_state=True, start=output1[0][0]) .stream.gather() .sink_to_list() ) output5 = sdf.amount.count(start=output2[0]).stream.gather().sink_to_list() df = cudf.DataFrame( {"name": ["Alice", "Tom", "Linda"], "amount": [50, 100, 200]} ) stream.emit(df) out_df2 = cudf.DataFrame( {"name": ["Alice", "Linda", "Tom"], "amount": [100, 200, 200]} ) out_df3 = cudf.DataFrame( {"name": ["Alice", "Linda", "Tom"], "amount": [50.0, 200.0, 100.0]} ) out_df4 = cudf.DataFrame( {"name": ["Alice", "Linda", "Tom"], "amount": [2, 1, 2]} ) assert assert_eq(output3[0].reset_index(), out_df2) assert assert_eq(output4[0][1].reset_index(), out_df3) assert assert_eq(output5[0].reset_index(), out_df4) def test_reductions_with_start_state(stream): example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output0 = sdf.amount.mean(start=(10, 2)).stream.gather().sink_to_list() output1 = sdf.amount.count(start=3).stream.gather().sink_to_list() output2 = sdf.amount.sum(start=10).stream.gather().sink_to_list() df = cudf.DataFrame( {"name": ["Alice", "Tom", "Linda"], "amount": [50, 100, 200]} ) stream.emit(df) assert output0[0] == 72.0 assert output1[0] == 6 assert output2[0] == 360 def test_rolling_aggs_with_start_state(stream): example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output0 = ( sdf.rolling(2, with_state=True, start=()) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame( {"name": ["Alice", "Tom", "Linda"], "amount": [50, 100, 200]} ) stream.emit(df) df = cudf.DataFrame({"name": ["Bob"], "amount": [250]}) stream.emit(df) assert assert_eq( output0[-1][0].reset_index(drop=True), cudf.Series([200, 250], name="amount"), ) assert assert_eq( output0[-1][1].reset_index(drop=True), cudf.Series([450], name="amount"), ) stream = Stream() example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output1 = ( sdf.rolling(2, with_state=True, start=output0[-1][0]) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame({"name": ["Alice"], "amount": [50]}) stream.emit(df) assert assert_eq( output1[-1][0].reset_index(drop=True), cudf.Series([250, 50], name="amount"), ) assert assert_eq( output1[-1][1].reset_index(drop=True), cudf.Series([300], name="amount"), ) def test_window_aggs_with_start_state(stream): example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output0 = ( sdf.window(2, with_state=True, start=None) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame( {"name": ["Alice", "Tom", "Linda"], "amount": [50, 100, 200]} ) stream.emit(df) df = cudf.DataFrame({"name": ["Bob"], "amount": [250]}) stream.emit(df) assert output0[-1][1] == 450 stream = Stream() example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output1 = ( sdf.window(2, with_state=True, start=output0[-1][0]) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame({"name": ["Alice"], "amount": [50]}) stream.emit(df) assert output1[-1][1] == 300 def test_windowed_groupby_aggs_with_start_state(stream): example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output0 = ( sdf.window(5, with_state=True, start=None) .groupby(["name"]) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame( {"name": ["Alice", "Tom", "Linda"], "amount": [50, 100, 200]} ) stream.emit(df) df = cudf.DataFrame( {"name": ["Alice", "Linda", "Bob"], "amount": [250, 300, 350]} ) stream.emit(df) stream = Stream() example = cudf.DataFrame({"name": [], "amount": []}) sdf = DataFrame(stream, example=example) output1 = ( sdf.window(5, with_state=True, start=output0[-1][0]) .groupby(["name"]) .amount.sum() .stream.gather() .sink_to_list() ) df = cudf.DataFrame( { "name": ["Alice", "Linda", "Tom", "Bob"], "amount": [50, 100, 150, 200], } ) stream.emit(df) out_df1 = cudf.DataFrame( { "name": ["Alice", "Bob", "Linda", "Tom"], "amount": [50, 550, 100, 150], } ) assert_eq(output1[-1][1].reset_index(), out_df1)
0
rapidsai_public_repos/cudf/python/custreamz/custreamz
rapidsai_public_repos/cudf/python/custreamz/custreamz/tests/conftest.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import socket import pytest from custreamz import kafka @pytest.fixture(scope="session") def kafka_client(): # Check for the existence of a kafka broker s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect_ex(("localhost", 9092)) s.shutdown(2) s.close() except Exception: pytest.skip( "A running Kafka instance must be available to run these tests" ) kafka_configs = { "metadata.broker.list": "localhost:9092", "enable.partition.eof": "true", "group.id": "groupid", "auto.offset.reset": "earliest", "enable.auto.commit": "false", } return kafka.Consumer(kafka_configs)
0
rapidsai_public_repos/cudf
rapidsai_public_repos/cudf/java/README.md
# Java API for cudf This project provides java bindings for cudf, to be able to process large amounts of data on a GPU. This is still a work in progress so some APIs may change until the 1.0 release. ## Behavior on Systems with Multiple GPUs The cudf project currently works with a single GPU per process. The CUDA runtime assigns the default GPU to all new operating system threads when they start to interact with CUDA. This means that if you use a multi-threaded environment, like Java processes tend to be, and try to use a non-default GPU for cudf you can run into hard to debug issues including resource leaks, invalid states, application crashes, and poor performance. To prevent this the Java cudf API will remember the device used to initialize the Rapids Memory Manager (RMM), and automatically set the thread's active device to it, if needed. It will not set the device back when the cudf call completes. This is different from most CUDA libraries and can result in unexpected behavior if you try to mix these libraries using the same thread. ## Dependency This is a fat jar with the binary dependencies packaged in the jar. This means the jar will only run on platforms the jar was compiled for. When this is in an official Maven repository we will list the platforms that it is compiled and tested for. In the mean time you will need to build it yourself. In official releases there should be no classifier on the jar and it should run against most modern cuda drivers. ```xml <dependency> <groupId>ai.rapids</groupId> <artifactId>cudf</artifactId> <version>${cudf.version}</version> </dependency> ``` In some cases there may be a classifier to indicate the version of cuda required. See the [Build From Source](#build-from-source) section below for more information about when this can happen. No official release of the jar will have a classifier on it. CUDA 11.0: ```xml <dependency> <groupId>ai.rapids</groupId> <artifactId>cudf</artifactId> <classifier>cuda11</classifier> <version>${cudf.version}</version> </dependency> ``` ## Build From Source Build [libcudf](../cpp) first, and make sure the JDK is installed and available. Specify the cmake option `-DCUDF_USE_ARROW_STATIC=ON -DCUDF_ENABLE_ARROW_S3=OFF` when building so that Apache Arrow is linked statically to libcudf, as this will help create a jar that does not require Arrow and its dependencies to be available in the runtime environment. After building libcudf, the Java bindings can be built via Maven, e.g.: ``` mvn clean install ``` If you have a compatible GPU on your build system the tests will use it. If not you will see a lot of skipped tests. ### Using the Java CI Docker Image If you are interested in building a Java cudf jar that is similar to the official releases that can run on all modern Linux systems, see the [Java CI README](ci/README.md) for instructions on how to build within a Docker environment using devtoolset. Note that building the jar without the Docker setup and script will likely produce a jar that can only run in environments similar to that of the build machine. If you decide to build without Docker and the build script, examining the cmake and Maven settings in the [Java CI build script](ci/build-in-docker.sh) can be helpful if you are encountering difficulties during the build. ## Statically Linking the CUDA Runtime If you use the default cmake options libcudart will be dynamically linked to libcudf and libcudfjni. To build with a static CUDA runtime, build libcudf with the `-DCUDA_STATIC_RUNTIME=ON` as a cmake parameter, and similarly build with `-DCUDA_STATIC_RUNTIME=ON` when building the Java bindings with Maven. ### Building with a libcudf Archive When statically linking the CUDA runtime, it is recommended to build cuDF as an archive rather than a shared library, as this allows the Java bindings to only have a single shared library that uses the CUDA runtime. To build libcudf as an archive, specify `-DBUILD_SHARED_LIBS=OFF` as a cmake parameter when building libcudf, then specify `-DCUDF_JNI_LIBCUDF_STATIC=ON` when building the Java bindings with Maven. ## Per-thread Default Stream The JNI code can be built with *per-thread default stream* (PTDS), which gives each host thread its own default CUDA stream, and can potentially increase the overlap of data copying and compute between different threads (see [blog post](https://devblogs.nvidia.com/gpu-pro-tip-cuda-7-streams-simplify-concurrency/)). Since the PTDS option is for each compilation unit, it should be done at the same time across the whole codebase. To enable PTDS, first build cuDF: ```shell script cd src/cudf/cpp/build cmake .. -DCMAKE_INSTALL_PREFIX=$CONDA_PREFIX -DCUDF_USE_PER_THREAD_DEFAULT_STREAM=ON make -j`nproc` make install ``` then build the jar: ```shell script cd src/cudf/java mvn clean install -DCUDF_USE_PER_THREAD_DEFAULT_STREAM=ON ``` ## GPUDirect Storage (GDS) The JNI code can be built with *GPUDirect Storage* (GDS) support, which enables direct copying between GPU device buffers and supported filesystems (see https://docs.nvidia.com/gpudirect-storage/). To enable GDS support, first make sure GDS is installed (see https://docs.nvidia.com/gpudirect-storage/troubleshooting-guide/index.html), then run: ```shell script cd src/cudf/java mvn clean install -DUSE_GDS=ON ```
0
rapidsai_public_repos/cudf
rapidsai_public_repos/cudf/java/pom.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 2019-2023, NVIDIA CORPORATION. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ai.rapids</groupId> <artifactId>cudf</artifactId> <version>24.02.0-SNAPSHOT</version> <name>cudfjni</name> <description> This project provides java bindings for cudf, to be able to process large amounts of data on a GPU. This is still a work in progress so some APIs may change until the 1.0 release. </description> <url>http://ai.rapids</url> <licenses> <license> <name>Apache License, Version 2.0</name> <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> <comments>A business-friendly OSS license</comments> </license> </licenses> <scm> <connection>scm:git:https://github.com/rapidsai/cudf.git</connection> <developerConnection>scm:git:[email protected]:rapidsai/cudf.git</developerConnection> <tag>HEAD</tag> <url>https://github.com/rapidsai/cudf</url> </scm> <developers> <developer> <id>revans2</id> <name>Robert Evans</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-6</timezone> </developer> <developer> <id>jlowe</id> <name>Jason Lowe</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-6</timezone> </developer> <developer> <id>abellina</id> <name>Alessandro Bellina</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-6</timezone> </developer> <developer> <id>tgraves</id> <name>Thomas Graves</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-6</timezone> </developer> <developer> <id>rjafri</id> <name>Raza Jafri</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-8</timezone> </developer> <developer> <id>nartal</id> <name>Niranjan Artal</name> <email>[email protected]</email> <roles> <role>Committer</role> </roles> <timezone>-8</timezone> </developer> </developers> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>${slf4j.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.25.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.arrow</groupId> <artifactId>arrow-vector</artifactId> <version>${arrow.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-avro</artifactId> <version>1.10.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>3.2.4</version> <scope>test</scope> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>5.4.2</junit.version> <ai.rapids.refcount.debug>false</ai.rapids.refcount.debug> <ai.rapids.cudf.nvtx.enabled>false</ai.rapids.cudf.nvtx.enabled> <native.build.path>${basedir}/target/cmake-build</native.build.path> <skipNativeCopy>false</skipNativeCopy> <cxx.flags/> <CMAKE_EXPORT_COMPILE_COMMANDS>OFF</CMAKE_EXPORT_COMPILE_COMMANDS> <CUDA_STATIC_RUNTIME>OFF</CUDA_STATIC_RUNTIME> <CUDF_USE_PER_THREAD_DEFAULT_STREAM>OFF</CUDF_USE_PER_THREAD_DEFAULT_STREAM> <USE_GDS>OFF</USE_GDS> <GPU_ARCHS>RAPIDS</GPU_ARCHS> <CUDF_JNI_LIBCUDF_STATIC>OFF</CUDF_JNI_LIBCUDF_STATIC> <native.build.path>${project.build.directory}/cmake-build</native.build.path> <slf4j.version>1.7.30</slf4j.version> <arrow.version>0.15.1</arrow.version> <parallel.level>4</parallel.level> <CUDF_CPP_BUILD_DIR/> <cmake.ccache.opts/> </properties> <profiles> <profile> <id>no-cxx-deprecation-warnings</id> <properties> <cxx.flags>-Wno-deprecated-declarations</cxx.flags> </properties> </profile> <profile> <id>default-tests</id> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <excludes> <exclude>**/CudaFatalTest.java</exclude> <exclude>**/ColumnViewNonEmptyNullsTest.java</exclude> </excludes> </configuration> <executions> <execution> <id>main-tests</id> <goals> <goal>test</goal> </goals> </execution> <execution> <id>non-empty-null-test</id> <goals> <goal>test</goal> </goals> <configuration> <argLine>-da:ai.rapids.cudf.AssertEmptyNulls</argLine> <test>*/ColumnViewNonEmptyNullsTest.java</test> </configuration> </execution> <execution> <id>fatal-cuda-test</id> <goals> <goal>test</goal> </goals> <configuration> <reuseForks>false</reuseForks> <test>*/CudaFatalTest.java</test> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>no-cufile-tests</id> <activation> <property> <name>USE_GDS</name> <value>!ON</value> </property> </activation> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <excludes> <exclude>**/ColumnViewNonEmptyNullsTest.java</exclude> <exclude>**/CuFileTest.java</exclude> <exclude>**/CudaFatalTest.java</exclude> </excludes> </configuration> <executions> <execution> <id>main-tests</id> <goals> <goal>test</goal> </goals> </execution> <execution> <id>fatal-cuda-test</id> <goals> <goal>test</goal> </goals> <configuration> <reuseForks>false</reuseForks> <test>*/CudaFatalTest.java</test> </configuration> </execution> <execution> <id>non-empty-null-test</id> <goals> <goal>test</goal> </goals> <configuration> <argLine>-da:ai.rapids.cudf.AssertEmptyNulls</argLine> <test>*/ColumnViewNonEmptyNullsTest.java</test> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>release</id> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement> <properties> <gpg.passphrase>${GPG_PASSPHRASE}</gpg.passphrase> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> <execution> <id>test-jars</id> <goals> <goal>test-jar</goal> </goals> </execution> </executions> <configuration> <excludeResources>true</excludeResources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9.1</version> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> <configuration> <additionalparam>-Xdoclint:none</additionalparam> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.7</version> <extensions>true</extensions> <configuration> <serverId>ossrh</serverId> <nexusUrl>https://oss.sonatype.org/</nexusUrl> <autoReleaseAfterClose>false</autoReleaseAfterClose> </configuration> </plugin> </plugins> </build> </profile> </profiles> <build> <resources> <resource> <!-- Include the properties file to provide the build information. --> <directory>${project.build.directory}/extra-resources</directory> <filtering>true</filtering> </resource> <resource> <directory>${basedir}/..</directory> <targetPath>META-INF</targetPath> <includes> <include>LICENSE</include> </includes> </resource> </resources> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>gmaven-plugin</artifactId> <version>1.5</version> </plugin> <plugin> <artifactId>maven-exec-plugin</artifactId> <version>1.6.0</version> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <!-- downgrade version so symlinks are followed --> <version>2.6</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.4.2</version> </dependency> <dependency> <!-- to get around bug https://github.com/junit-team/junit5/issues/1367 --> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-logger-api</artifactId> <version>2.21.0</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.22.0</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>cmake</id> <phase>validate</phase> <configuration> <tasks> <mkdir dir="${native.build.path}"/> <exec dir="${native.build.path}" failonerror="true" executable="cmake"> <arg value="${basedir}/src/main/native"/> <arg line="${cmake.ccache.opts}"/> <arg value="-DCUDA_STATIC_RUNTIME=${CUDA_STATIC_RUNTIME}" /> <arg value="-DCUDF_USE_PER_THREAD_DEFAULT_STREAM=${CUDF_USE_PER_THREAD_DEFAULT_STREAM}" /> <arg value="-DUSE_GDS=${USE_GDS}" /> <arg value="-DCMAKE_CXX_FLAGS=${cxx.flags}"/> <arg value="-DCMAKE_EXPORT_COMPILE_COMMANDS=${CMAKE_EXPORT_COMPILE_COMMANDS}"/> <arg value="-DCUDF_CPP_BUILD_DIR=${CUDF_CPP_BUILD_DIR}"/> <arg value="-DGPU_ARCHS=${GPU_ARCHS}"/> <arg value="-DCUDF_JNI_LIBCUDF_STATIC=${CUDF_JNI_LIBCUDF_STATIC}"/> <arg value="-DCUDF_JNI_ENABLE_PROFILING=${CUDF_JNI_ENABLE_PROFILING}"/> <arg value="-DBUILD_SHARED_LIBS=ON"/> </exec> <exec dir="${native.build.path}" failonerror="true" executable="cmake"> <arg value="--build"/> <arg value="."/> <arg value="--parallel"/> <arg value="${parallel.level}"/> </exec> <mkdir dir="${project.build.directory}/extra-resources"/> <exec executable="bash" output="${project.build.directory}/extra-resources/cudf-java-version-info.properties"> <arg value="${project.basedir}/buildscripts/build-info"/> <arg value="${project.version}"/> </exec> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>gmaven-plugin</artifactId> <executions> <execution> <id>setproperty</id> <phase>validate</phase> <goals> <goal>execute</goal> </goals> <configuration> <source> def sout = new StringBuffer(), serr = new StringBuffer() //This only works on linux def proc = 'ldd ${native.build.path}/libcudfjni.so'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(10000) def libcudf = ~/libcudf.*\\.so\\s+=>\\s+(.*)libcudf.*\\.so\\s+.*/ def cudfm = libcudf.matcher(sout) if (cudfm.find()) { pom.properties['native.cudf.path'] = cudfm.group(1) } else { fail("Could not find cudf as a dependency of libcudfjni out> $sout err> $serr") } def nvccout = new StringBuffer(), nvccerr = new StringBuffer() def nvccproc = 'nvcc --version'.execute() nvccproc.consumeProcessOutput(nvccout, nvccerr) nvccproc.waitForOrKill(10000) def cudaPattern = ~/Cuda compilation tools, release ([0-9]+)/ def cm = cudaPattern.matcher(nvccout) if (cm.find()) { def classifier = 'cuda' + cm.group(1) pom.properties['cuda.classifier'] = classifier } else { fail('could not find CUDA version') } </source> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <!--Set by groovy script--> <classifier>${cuda.classifier}</classifier> </configuration> <executions> <execution> <goals> <goal>test-jar</goal> </goals> <configuration> <classifier>tests</classifier> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- you can turn this off, by passing -DtrimStackTrace=true when running tests --> <trimStackTrace>false</trimStackTrace> <redirectTestOutputToFile>true</redirectTestOutputToFile> <systemPropertyVariables> <ai.rapids.refcount.debug>${ai.rapids.refcount.debug}</ai.rapids.refcount.debug> <ai.rapids.cudf.nvtx.enabled>${ai.rapids.cudf.nvtx.enabled}</ai.rapids.cudf.nvtx.enabled> </systemPropertyVariables> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-native-libs</id> <phase>generate-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <overwrite>true</overwrite> <skip>${skipNativeCopy}</skip> <outputDirectory>${project.build.outputDirectory}/${os.arch}/${os.name}</outputDirectory> <resources> <resource> <directory>${native.build.path}</directory> <includes> <include>libcudfjni.so</include> <include>libcufilejni.so</include> <include>libnvcomp.so</include> <include>libnvcomp_gdeflate.so</include> <include>libnvcomp_bitcomp.so</include> </includes> </resource> <resource> <!--Set by groovy script--> <directory>${native.cudf.path}</directory> <includes> <include>libcudf.so</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
0
rapidsai_public_repos/cudf/java
rapidsai_public_repos/cudf/java/dev/cudf_java_styles.xml
<code_scheme name="cudf_java" version="173"> <JavaCodeStyleSettings> <option name="JD_ADD_BLANK_AFTER_DESCRIPTION" value="false" /> </JavaCodeStyleSettings> <codeStyleSettings language="JAVA"> <option name="RIGHT_MARGIN" value="100" /> <option name="KEEP_SIMPLE_BLOCKS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" /> <option name="KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE" value="true" /> <option name="WRAP_LONG_LINES" value="true" /> <indentOptions> <option name="INDENT_SIZE" value="2" /> <option name="CONTINUATION_INDENT_SIZE" value="4" /> <option name="TAB_SIZE" value="2" /> </indentOptions> <arrangement> <groups /> </arrangement> </codeStyleSettings> </code_scheme>
0
rapidsai_public_repos/cudf/java
rapidsai_public_repos/cudf/java/ci/README.md
# Build Jar artifact of cuDF ## Build the docker image ### Prerequisite 1. Docker should be installed. 2. [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) should be installed. ### Build the docker image In the root path of cuDF repo, run below command to build the docker image. ```bash docker build -f java/ci/Dockerfile.centos7 --build-arg CUDA_VERSION=11.8.0 -t cudf-build:11.8.0-devel-centos7 . ``` The following CUDA versions are supported w/ CUDA Enhanced Compatibility: * CUDA 11.0+ Change the --build-arg CUDA_VERSION to what you need. You can replace the tag "cudf-build:11.8.0-devel-centos7" with another name you like. ## Start the docker then build ### Start the docker Run below command to start a docker container with GPU. ```bash nvidia-docker run -it cudf-build:11.8.0-devel-centos7 bash ``` ### Download the cuDF source code You can download the cuDF repo in the docker container or you can mount it into the container. Here I choose to download again in the container. ```bash git clone --recursive https://github.com/rapidsai/cudf.git -b branch-24.02 ``` ### Build cuDF jar with devtoolset ```bash cd cudf export WORKSPACE=`pwd` scl enable devtoolset-11 "java/ci/build-in-docker.sh" ``` ### The output You can find the cuDF jar in java/target/ like cudf-24.02.0-SNAPSHOT-cuda11.jar.
0
rapidsai_public_repos/cudf/java
rapidsai_public_repos/cudf/java/ci/build-in-docker.sh
#!/bin/bash # # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 -ex gcc --version SKIP_JAVA_TESTS=${SKIP_JAVA_TESTS:-true} BUILD_CPP_TESTS=${BUILD_CPP_TESTS:-OFF} ENABLE_CUDA_STATIC_RUNTIME=${ENABLE_CUDA_STATIC_RUNTIME:-ON} ENABLE_PTDS=${ENABLE_PTDS:-ON} RMM_LOGGING_LEVEL=${RMM_LOGGING_LEVEL:-OFF} ENABLE_NVTX=${ENABLE_NVTX:-ON} ENABLE_GDS=${ENABLE_GDS:-OFF} OUT=${OUT:-out} CMAKE_GENERATOR=${CMAKE_GENERATOR:-Ninja} SIGN_FILE=$1 #Set absolute path for OUT_PATH OUT_PATH="$WORKSPACE/$OUT" # set on Jenkins parameter echo "SIGN_FILE: $SIGN_FILE,\ SKIP_JAVA_TESTS: $SKIP_JAVA_TESTS,\ BUILD_CPP_TESTS: $BUILD_CPP_TESTS,\ ENABLE_CUDA_STATIC_RUNTIME: $ENABLE_CUDA_STATIC_RUNTIME,\ ENABLED_PTDS: $ENABLE_PTDS,\ ENABLE_NVTX: $ENABLE_NVTX,\ ENABLE_GDS: $ENABLE_GDS,\ RMM_LOGGING_LEVEL: $RMM_LOGGING_LEVEL,\ OUT_PATH: $OUT_PATH" INSTALL_PREFIX=/usr/local/rapids export GIT_COMMITTER_NAME="ci" export GIT_COMMITTER_EMAIL="[email protected]" export CUDACXX=/usr/local/cuda/bin/nvcc export LIBCUDF_KERNEL_CACHE_PATH=/rapids ###### Build libcudf ###### rm -rf "$WORKSPACE/cpp/build" mkdir -p "$WORKSPACE/cpp/build" cd "$WORKSPACE/cpp/build" cmake .. -G"${CMAKE_GENERATOR}" \ -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX \ -DCUDA_STATIC_RUNTIME=$ENABLE_CUDA_STATIC_RUNTIME \ -DUSE_NVTX=$ENABLE_NVTX \ -DCUDF_USE_ARROW_STATIC=ON \ -DCUDF_ENABLE_ARROW_S3=OFF \ -DBUILD_TESTS=$BUILD_CPP_TESTS \ -DCUDF_USE_PER_THREAD_DEFAULT_STREAM=$ENABLE_PTDS \ -DRMM_LOGGING_LEVEL=$RMM_LOGGING_LEVEL \ -DBUILD_SHARED_LIBS=OFF if [[ -z "${PARALLEL_LEVEL}" ]]; then cmake --build . else cmake --build . --parallel $PARALLEL_LEVEL fi cmake --install . ###### Build cudf jar ###### BUILD_ARG="-Dmaven.repo.local=\"$WORKSPACE/.m2\"\ -DskipTests=$SKIP_JAVA_TESTS\ -DCUDF_USE_PER_THREAD_DEFAULT_STREAM=$ENABLE_PTDS\ -DCUDA_STATIC_RUNTIME=$ENABLE_CUDA_STATIC_RUNTIME\ -DCUDF_JNI_LIBCUDF_STATIC=ON\ -DUSE_GDS=$ENABLE_GDS -Dtest=*,!CuFileTest,!CudaFatalTest,!ColumnViewNonEmptyNullsTest" if [ "$SIGN_FILE" == true ]; then # Build javadoc and sources only when SIGN_FILE is true BUILD_ARG="$BUILD_ARG -Prelease" fi if [ -f "$WORKSPACE/java/ci/settings.xml" ]; then # Build with an internal settings.xml BUILD_ARG="$BUILD_ARG -s \"$WORKSPACE/java/ci/settings.xml\"" fi cd "$WORKSPACE/java" mvn -B clean package $BUILD_ARG ###### Stash Jar files ###### rm -rf $OUT_PATH mkdir -p $OUT_PATH cp -f target/*.jar $OUT_PATH
0
rapidsai_public_repos/cudf/java
rapidsai_public_repos/cudf/java/ci/Dockerfile.centos7
# # Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ### # Build the image for cudf development environment. # # Arguments: CUDA_VERSION=11.X.Y # ### ARG CUDA_VERSION=11.8.0 FROM nvidia/cuda:$CUDA_VERSION-devel-centos7 ### Install basic requirements ARG DEVTOOLSET_VERSION=11 RUN yum install -y centos-release-scl RUN yum install -y devtoolset-${DEVTOOLSET_VERSION} epel-release RUN yum install -y git zlib-devel maven tar wget patch ninja-build ## pre-create the CMAKE_INSTALL_PREFIX folder, set writable by any user for Jenkins RUN mkdir /usr/local/rapids && mkdir /rapids && chmod 777 /usr/local/rapids && chmod 777 /rapids ARG CMAKE_VERSION=3.26.4 RUN cd /usr/local/ && wget --quiet https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz && \ tar zxf cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz && \ rm cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz ENV PATH /usr/local/cmake-${CMAKE_VERSION}-linux-x86_64/bin:$PATH ARG CCACHE_VERSION=4.6 RUN cd /tmp && wget --quiet https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz && \ tar zxf ccache-${CCACHE_VERSION}.tar.gz && \ rm ccache-${CCACHE_VERSION}.tar.gz && \ cd ccache-${CCACHE_VERSION} && \ mkdir build && \ cd build && \ scl enable devtoolset-${DEVTOOLSET_VERSION} \ "cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DZSTD_FROM_INTERNET=ON \ -DREDIS_STORAGE_BACKEND=OFF && \ cmake --build . --parallel ${PARALLEL_LEVEL} --target install" && \ cd ../.. && \ rm -rf ccache-${CCACHE_VERSION}
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/JCudfSerialization.java
/* * * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ai.rapids.cudf; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * Serialize and deserialize CUDF tables and columns using a custom format. The goal of this is * to provide a way to efficiently serialize and deserialize cudf data for distributed * processing within a single application. Typically after a partition like operation has happened. * It is not intended for inter-application communication or for long term storage of data, there * are much better standards based formats for all of that. * <p> * The goal is to transfer data from a local GPU to a remote GPU as quickly and efficiently as * possible using build in java communication channels. There is no guarantee of compatibility * between different releases of CUDF. This is to allow us to adapt if internal memory layouts * and formats change. * <p> * This version optimizes for reduced memory transfers, and as such will try to do the fewest number * of transfers possible when putting the data back onto the GPU. This means that it will slice * a single large memory buffer into smaller buffers used by the resulting ColumnVectors. The * downside of this is that generally none of the memory can be released until all of the * ColumnVectors are closed. It is assumed that this will not be a problem because for processing * efficiency after the data is transferred it will likely be combined with other similar batches * from other processes into a single larger buffer. */ public class JCudfSerialization { /** * Magic number "CUDF" in ASCII, which is 1178883395 if read in LE from big endian, which is * too large for any reasonable metadata for arrow, so we should probably be okay detecting * this, and switching back/forth at a later time. */ private static final int SER_FORMAT_MAGIC_NUMBER = 0x43554446; private static final short VERSION_NUMBER = 0x0000; private static final class ColumnOffsets { private final long validity; private final long offsets; private final long data; private final long dataLen; public ColumnOffsets(long validity, long offsets, long data, long dataLen) { this.validity = validity; this.offsets = offsets; this.data = data; this.dataLen = dataLen; } } /** * Holds the metadata about a serialized table. If this is being read from a stream * isInitialized will return true if the metadata was read correctly from the stream. * It will return false if an EOF was encountered at the beginning indicating that * there was no data to be read. */ public static final class SerializedTableHeader { private SerializedColumnHeader[] columns; private int numRows; private long dataLen; private boolean initialized = false; private boolean dataRead = false; public SerializedTableHeader(DataInputStream din) throws IOException { readFrom(din); } SerializedTableHeader(SerializedColumnHeader[] columns, int numRows, long dataLen) { this.columns = columns; this.numRows = numRows; this.dataLen = dataLen; initialized = true; dataRead = true; } /** Constructor for a row-count only table (no columns) */ public SerializedTableHeader(int numRows) { this(new SerializedColumnHeader[0], numRows, 0); } /** Get the column header for the corresponding column index */ public SerializedColumnHeader getColumnHeader(int columnIndex) { return columns[columnIndex]; } /** * Set to true once data is successfully read from a stream by readTableIntoBuffer. * @return true if data was read, else false. */ public boolean wasDataRead() { return dataRead; } /** * Returns the size of a buffer needed to read data into the stream. */ public long getDataLen() { return dataLen; } /** * Returns the number of rows stored in this table. */ public int getNumRows() { return numRows; } /** * Returns the number of columns stored in this table */ public int getNumColumns() { return columns != null ? columns.length : 0; } /** * Returns true if the metadata for this table was read, else false indicating an EOF was * encountered. */ public boolean wasInitialized() { return initialized; } /** * Returns the number of bytes needed to serialize this table header. * Note that this is only the metadata for the table (i.e.: column types, row counts, etc.) * and does not include the bytes needed to serialize the table data. */ public long getSerializedHeaderSizeInBytes() { // table header always has: // - 4-byte magic number // - 2-byte version number // - 4-byte column count // - 4-byte row count // - 8-byte data buffer length long total = 4 + 2 + 4 + 4 + 8; for (SerializedColumnHeader column : columns) { total += column.getSerializedHeaderSizeInBytes(); } return total; } /** Returns the number of bytes needed to serialize this table header and the table data. */ public long getTotalSerializedSizeInBytes() { return getSerializedHeaderSizeInBytes() + dataLen; } private void readFrom(DataInputStream din) throws IOException { try { int num = din.readInt(); if (num != SER_FORMAT_MAGIC_NUMBER) { throw new IllegalStateException("THIS DOES NOT LOOK LIKE CUDF SERIALIZED DATA. " + "Expected magic number " + SER_FORMAT_MAGIC_NUMBER + " Found " + num); } } catch (EOFException e) { // If we get an EOF at the very beginning don't treat it as an error because we may // have finished reading everything... return; } short version = din.readShort(); if (version != VERSION_NUMBER) { throw new IllegalStateException("READING THE WRONG SERIALIZATION FORMAT VERSION FOUND " + version + " EXPECTED " + VERSION_NUMBER); } int numColumns = din.readInt(); numRows = din.readInt(); columns = new SerializedColumnHeader[numColumns]; for (int i = 0; i < numColumns; i++) { columns[i] = SerializedColumnHeader.readFrom(din, numRows); } dataLen = din.readLong(); initialized = true; } public void writeTo(DataWriter dout) throws IOException { // Now write out the data dout.writeInt(SER_FORMAT_MAGIC_NUMBER); dout.writeShort(VERSION_NUMBER); dout.writeInt(columns.length); dout.writeInt(numRows); // Header for each column... for (SerializedColumnHeader column : columns) { column.writeTo(dout); } dout.writeLong(dataLen); } } /** Holds the metadata about a serialized column. */ public static final class SerializedColumnHeader { public final DType dtype; public final long nullCount; public final long rowCount; public final SerializedColumnHeader[] children; SerializedColumnHeader(DType dtype, long rowCount, long nullCount, SerializedColumnHeader[] children) { this.dtype = dtype; this.rowCount = rowCount; this.nullCount = nullCount; this.children = children; } SerializedColumnHeader(ColumnBufferProvider column, long rowOffset, long numRows) { this.dtype = column.getType(); this.rowCount = numRows; long columnNullCount = column.getNullCount(); // For a subset of the original column we do not know the null count unless // the original column is either all nulls or no nulls. if (column.getRowCount() == numRows || columnNullCount == 0 || columnNullCount == column.getRowCount()) { this.nullCount = Math.min(columnNullCount, numRows); } else { this.nullCount = ColumnView.UNKNOWN_NULL_COUNT; } ColumnBufferProvider[] childProviders = column.getChildProviders(); if (childProviders != null) { children = new SerializedColumnHeader[childProviders.length]; long childRowOffset = rowOffset; long childNumRows = numRows; if (dtype.equals(DType.LIST)) { if (numRows > 0) { childRowOffset = column.getOffset(rowOffset); childNumRows = column.getOffset(rowOffset + numRows) - childRowOffset; } } for (int i = 0; i < children.length; i++) { children[i] = new SerializedColumnHeader(childProviders[i], childRowOffset, childNumRows); } } else { children = null; } } /** Get the data type of the column */ public DType getType() { return dtype; } /** Get the row count of the column */ public long getRowCount() { return rowCount; } /** Get the null count of the column */ public long getNullCount() { return nullCount; } /** Get the metadata for any child columns or null if there are no children */ public SerializedColumnHeader[] getChildren() { return children; } /** Get the number of child columns */ public int getNumChildren() { return children != null ? children.length : 0; } /** Return the number of bytes needed to store this column header in serialized form. */ public long getSerializedHeaderSizeInBytes() { // column header always has: // - 4-byte type ID // - 4-byte type scale // - 4-byte null count long total = 4 + 4 + 4; if (dtype.isNestedType()) { assert children != null; if (dtype.equals(DType.LIST)) { total += 4; // 4-byte child row count } else if (dtype.equals(DType.STRUCT)) { total += 4; // 4-byte child count } else { throw new IllegalStateException("Unexpected nested type: " + dtype); } for (SerializedColumnHeader child : children) { total += child.getSerializedHeaderSizeInBytes(); } } return total; } /** Write this column header to the specified writer */ public void writeTo(DataWriter dout) throws IOException { dout.writeInt(dtype.typeId.getNativeId()); dout.writeInt(dtype.getScale()); dout.writeInt((int) nullCount); if (dtype.isNestedType()) { assert children != null; if (dtype.equals(DType.LIST)) { dout.writeInt((int) children[0].getRowCount()); } else if (dtype.equals(DType.STRUCT)) { dout.writeInt(getNumChildren()); } else { throw new IllegalStateException("Unexpected nested type: " + dtype); } for (SerializedColumnHeader child : children) { child.writeTo(dout); } } } static SerializedColumnHeader readFrom(DataInputStream din, long rowCount) throws IOException { DType dtype = DType.fromNative(din.readInt(), din.readInt()); long nullCount = din.readInt(); SerializedColumnHeader[] children = null; if (dtype.isNestedType()) { int numChildren; long childRowCount; if (dtype.equals(DType.LIST)) { numChildren = 1; childRowCount = din.readInt(); } else if (dtype.equals(DType.STRUCT)) { numChildren = din.readInt(); childRowCount = rowCount; } else { throw new IllegalStateException("Unexpected nested type: " + dtype); } children = new SerializedColumnHeader[numChildren]; for (int i = 0; i < numChildren; i++) { children[i] = readFrom(din, childRowCount); } } return new SerializedColumnHeader(dtype, rowCount, nullCount, children); } } /** Class to hold the header and buffer pair result from host-side concatenation */ public static final class HostConcatResult implements AutoCloseable { private final SerializedTableHeader tableHeader; private final HostMemoryBuffer hostBuffer; public HostConcatResult(SerializedTableHeader tableHeader, HostMemoryBuffer tableBuffer) { this.tableHeader = tableHeader; this.hostBuffer = tableBuffer; } public SerializedTableHeader getTableHeader() { return tableHeader; } public HostMemoryBuffer getHostBuffer() { return hostBuffer; } /** Build a contiguous table in device memory from this host-concatenated result */ public ContiguousTable toContiguousTable() { DeviceMemoryBuffer devBuffer = DeviceMemoryBuffer.allocate(hostBuffer.length); try { if (hostBuffer.length > 0) { devBuffer.copyFromHostBuffer(hostBuffer); } Table table = sliceUpColumnVectors(tableHeader, devBuffer, hostBuffer); try { return new ContiguousTable(table, devBuffer); } catch (Exception e) { table.close(); throw e; } } catch (Exception e) { devBuffer.close(); throw e; } } @Override public void close() { hostBuffer.close(); } } /** * Visible for testing */ static abstract class ColumnBufferProvider implements AutoCloseable { public abstract DType getType(); public abstract long getNullCount(); public abstract long getOffset(long index); public abstract long getRowCount(); public abstract HostMemoryBuffer getHostBufferFor(BufferType buffType); public abstract long getBufferStartOffset(BufferType buffType); public abstract ColumnBufferProvider[] getChildProviders(); @Override public abstract void close(); } /** * Visible for testing */ static class ColumnProvider extends ColumnBufferProvider { private final HostColumnVectorCore column; private final boolean closeAtEnd; private final ColumnBufferProvider[] childProviders; ColumnProvider(HostColumnVectorCore column, boolean closeAtEnd) { this.column = column; this.closeAtEnd = closeAtEnd; if (getType().isNestedType()) { int numChildren = column.getNumChildren(); childProviders = new ColumnBufferProvider[numChildren]; for (int i = 0; i < numChildren; i++) { childProviders[i] = new ColumnProvider(column.getChildColumnView(i), false); } } else { childProviders = null; } } @Override public DType getType() { return column.getType(); } @Override public long getNullCount() { return column.getNullCount(); } @Override public long getOffset(long index) { return column.getOffsets().getInt(index * Integer.BYTES); } @Override public long getRowCount() { return column.getRowCount(); } @Override public HostMemoryBuffer getHostBufferFor(BufferType buffType) { switch (buffType) { case VALIDITY: return column.getValidity(); case OFFSET: return column.getOffsets(); case DATA: return column.getData(); default: throw new IllegalStateException("Unexpected buffer type: " + buffType); } } @Override public long getBufferStartOffset(BufferType buffType) { // All of the buffers start at 0 for this. return 0; } @Override public ColumnBufferProvider[] getChildProviders() { return childProviders; } @Override public void close() { if (closeAtEnd) { column.close(); } } } private static class BufferOffsetProvider extends ColumnBufferProvider { private final SerializedColumnHeader header; private final ColumnOffsets offsets; private final HostMemoryBuffer buffer; private final ColumnBufferProvider[] childProviders; private BufferOffsetProvider(SerializedColumnHeader header, ColumnOffsets offsets, HostMemoryBuffer buffer, ColumnBufferProvider[] childProviders) { this.header = header; this.offsets = offsets; this.buffer = buffer; this.childProviders = childProviders; } @Override public DType getType() { return header.getType(); } @Override public long getNullCount() { return header.getNullCount(); } @Override public long getRowCount() { return header.getRowCount(); } @Override public HostMemoryBuffer getHostBufferFor(BufferType buffType) { return buffer; } @Override public long getBufferStartOffset(BufferType buffType) { switch (buffType) { case DATA: return offsets.data; case OFFSET: return offsets.offsets; case VALIDITY: return offsets.validity; default: throw new IllegalArgumentException("Buffer type " + buffType + " is not supported"); } } @Override public long getOffset(long index) { assert getType().hasOffsets(); assert (index >= 0 && index <= getRowCount()) : "index is out of range 0 <= " + index + " <= " + getRowCount(); return buffer.getInt(offsets.offsets + (index * Integer.BYTES)); } @Override public ColumnBufferProvider[] getChildProviders() { return childProviders; } @Override public void close() { // NOOP } } /** * Visible for testing */ static abstract class DataWriter { public abstract void writeByte(byte b) throws IOException; public abstract void writeShort(short s) throws IOException; public abstract void writeInt(int i) throws IOException; public abstract void writeIntNativeOrder(int i) throws IOException; public abstract void writeLong(long val) throws IOException; /** * Copy data from src starting at srcOffset and going for len bytes. * @param src where to copy from. * @param srcOffset offset to start at. * @param len amount to copy. */ public abstract void copyDataFrom(HostMemoryBuffer src, long srcOffset, long len) throws IOException; public void copyDataFrom(ColumnBufferProvider column, BufferType buffType, long offset, long length) throws IOException { HostMemoryBuffer buff = column.getHostBufferFor(buffType); long startOffset = column.getBufferStartOffset(buffType); copyDataFrom(buff, startOffset + offset, length); } public void flush() throws IOException { // NOOP by default } public abstract void write(byte[] arr, int offset, int length) throws IOException; } /** * Visible for testing */ static final class DataOutputStreamWriter extends DataWriter { private final byte[] arrayBuffer = new byte[1024 * 128]; private final DataOutputStream dout; public DataOutputStreamWriter(DataOutputStream dout) { this.dout = dout; } @Override public void writeByte(byte b) throws IOException { dout.writeByte(b); } @Override public void writeShort(short s) throws IOException { dout.writeShort(s); } @Override public void writeInt(int i) throws IOException { dout.writeInt(i); } @Override public void writeIntNativeOrder(int i) throws IOException { // TODO this only works on Little Endian Architectures, x86. If we need // to support others we need to detect the endianness and switch on the right implementation. writeInt(Integer.reverseBytes(i)); } @Override public void writeLong(long val) throws IOException { dout.writeLong(val); } @Override public void copyDataFrom(HostMemoryBuffer src, long srcOffset, long len) throws IOException { long dataLeft = len; while (dataLeft > 0) { int amountToCopy = (int)Math.min(arrayBuffer.length, dataLeft); src.getBytes(arrayBuffer, 0, srcOffset, amountToCopy); dout.write(arrayBuffer, 0, amountToCopy); srcOffset += amountToCopy; dataLeft -= amountToCopy; } } @Override public void flush() throws IOException { dout.flush(); } @Override public void write(byte[] arr, int offset, int length) throws IOException { dout.write(arr, offset, length); } } private static final class HostDataWriter extends DataWriter { private final HostMemoryBuffer buffer; private long offset = 0; public HostDataWriter(HostMemoryBuffer buffer) { this.buffer = buffer; } @Override public void writeByte(byte b) { buffer.setByte(offset, b); offset += 1; } @Override public void writeShort(short s) { buffer.setShort(offset, s); offset += 2; } @Override public void writeInt(int i) { buffer.setInt(offset, i); offset += 4; } @Override public void writeIntNativeOrder(int i) { // This is already in the native order... writeInt(i); } @Override public void writeLong(long val) { buffer.setLong(offset, val); offset += 8; } @Override public void copyDataFrom(HostMemoryBuffer src, long srcOffset, long len) { buffer.copyFromHostBuffer(offset, src, srcOffset, len); offset += len; } @Override public void write(byte[] arr, int srcOffset, int length) { buffer.setBytes(offset, arr, srcOffset, length); offset += length; } } ///////////////////////////////////////////// // METHODS ///////////////////////////////////////////// ///////////////////////////////////////////// // PADDING FOR ALIGNMENT ///////////////////////////////////////////// private static long padFor64byteAlignment(long orig) { return ((orig + 63) / 64) * 64; } private static long padFor64byteAlignment(DataWriter out, long bytes) throws IOException { final long paddedBytes = padFor64byteAlignment(bytes); while (paddedBytes > bytes) { out.writeByte((byte)0); bytes++; } return paddedBytes; } ///////////////////////////////////////////// // SERIALIZED SIZE ///////////////////////////////////////////// private static long getRawStringDataLength(ColumnBufferProvider column, long rowOffset, long numRows) { if (numRows <= 0) { return 0; } long start = column.getOffset(rowOffset); long end = column.getOffset(rowOffset + numRows); return end - start; } private static long getSlicedSerializedDataSizeInBytes(ColumnBufferProvider[] columns, long rowOffset, long numRows) { long totalDataSize = 0; for (ColumnBufferProvider column: columns) { totalDataSize += getSlicedSerializedDataSizeInBytes(column, rowOffset, numRows); } return totalDataSize; } private static long getSlicedSerializedDataSizeInBytes(ColumnBufferProvider column, long rowOffset, long numRows) { long totalDataSize = 0; DType type = column.getType(); if (needsValidityBuffer(column.getNullCount())) { totalDataSize += padFor64byteAlignment(BitVectorHelper.getValidityLengthInBytes(numRows)); } if (type.hasOffsets()) { if (numRows > 0) { // Add in size of offsets vector totalDataSize += padFor64byteAlignment((numRows + 1) * Integer.BYTES); if (type.equals(DType.STRING)) { totalDataSize += padFor64byteAlignment(getRawStringDataLength(column, rowOffset, numRows)); } } } else if (type.getSizeInBytes() > 0) { totalDataSize += padFor64byteAlignment(column.getType().getSizeInBytes() * numRows); } if (numRows > 0 && type.isNestedType()) { if (type.equals(DType.LIST)) { ColumnBufferProvider child = column.getChildProviders()[0]; long childStartRow = column.getOffset(rowOffset); long childNumRows = column.getOffset(rowOffset + numRows) - childStartRow; totalDataSize += getSlicedSerializedDataSizeInBytes(child, childStartRow, childNumRows); } else if (type.equals(DType.STRUCT)) { for (ColumnBufferProvider childProvider : column.getChildProviders()) { totalDataSize += getSlicedSerializedDataSizeInBytes(childProvider, rowOffset, numRows); } } else { throw new IllegalStateException("Unexpected nested type: " + type); } } return totalDataSize; } /** * Get the size in bytes needed to serialize the given data. The columns should be in host memory * before calling this. * @param columns columns to be serialized. * @param rowOffset the first row to serialize. * @param numRows the number of rows to serialize. * @return the size in bytes needed to serialize the data including the header. */ public static long getSerializedSizeInBytes(HostColumnVector[] columns, long rowOffset, long numRows) { ColumnBufferProvider[] providers = providersFrom(columns, false); try { SerializedColumnHeader[] columnHeaders = new SerializedColumnHeader[providers.length]; for (int i = 0; i < columnHeaders.length; i++) { columnHeaders[i] = new SerializedColumnHeader(providers[i], rowOffset, numRows); } long dataLen = getSlicedSerializedDataSizeInBytes(providers, rowOffset, numRows); SerializedTableHeader tableHeader = new SerializedTableHeader(columnHeaders, (int) numRows, dataLen); return tableHeader.getTotalSerializedSizeInBytes(); } finally { closeAll(providers); } } ///////////////////////////////////////////// // HELPER METHODS buildIndex ///////////////////////////////////////////// /** Build a list of column offset descriptors using a pre-order traversal of the columns */ static ArrayDeque<ColumnOffsets> buildIndex(SerializedTableHeader header, HostMemoryBuffer buffer) { int numTopColumns = header.getNumColumns(); ArrayDeque<ColumnOffsets> offsetsList = new ArrayDeque<>(); long bufferOffset = 0; for (int i = 0; i < numTopColumns; i++) { SerializedColumnHeader column = header.getColumnHeader(i); bufferOffset = buildIndex(column, buffer, offsetsList, bufferOffset); } return offsetsList; } /** * Append a list of column offset descriptors using a pre-order traversal of the column * @param column column offset descriptors will be built for this column and its child columns * @param buffer host buffer backing the column data * @param offsetsList list where column offset descriptors will be appended during traversal * @param bufferOffset offset in the host buffer where the column data begins * @return buffer offset at the end of this column's data including all child columns */ private static long buildIndex(SerializedColumnHeader column, HostMemoryBuffer buffer, ArrayDeque<ColumnOffsets> offsetsList, long bufferOffset) { long validity = 0; long offsets = 0; long data = 0; long dataLen = 0; long rowCount = column.getRowCount(); if (needsValidityBuffer(column.getNullCount())) { long validityLen = padFor64byteAlignment(BitVectorHelper.getValidityLengthInBytes(rowCount)); validity = bufferOffset; bufferOffset += validityLen; } DType dtype = column.getType(); if (dtype.hasOffsets()) { if (rowCount > 0) { long offsetsLen = (rowCount + 1) * Integer.BYTES; offsets = bufferOffset; int startOffset = buffer.getInt(bufferOffset); int endOffset = buffer.getInt(bufferOffset + (rowCount * Integer.BYTES)); bufferOffset += padFor64byteAlignment(offsetsLen); if (dtype.equals(DType.STRING)) { dataLen = endOffset - startOffset; data = bufferOffset; bufferOffset += padFor64byteAlignment(dataLen); } } } else if (dtype.getSizeInBytes() > 0) { dataLen = dtype.getSizeInBytes() * rowCount; data = bufferOffset; bufferOffset += padFor64byteAlignment(dataLen); } offsetsList.add(new ColumnOffsets(validity, offsets, data, dataLen)); SerializedColumnHeader[] children = column.getChildren(); if (children != null) { for (SerializedColumnHeader child : children) { bufferOffset = buildIndex(child, buffer, offsetsList, bufferOffset); } } return bufferOffset; } ///////////////////////////////////////////// // HELPER METHODS FOR PROVIDERS ///////////////////////////////////////////// private static void closeAll(ColumnBufferProvider[] providers) { for (int i = 0; i < providers.length; i++) { providers[i].close(); } } private static void closeAll(ColumnBufferProvider[][] providers) { for (int i = 0; i < providers.length; i++) { if (providers[i] != null) { closeAll(providers[i]); } } } private static ColumnBufferProvider[] providersFrom(ColumnVector[] columns) { HostColumnVector[] onHost = new HostColumnVector[columns.length]; boolean success = false; try { for (int i = 0; i < columns.length; i++) { onHost[i] = columns[i].copyToHost(); } ColumnBufferProvider[] ret = providersFrom(onHost, true); success = true; return ret; } finally { if (!success) { for (int i = 0; i < onHost.length; i++) { if (onHost[i] != null) { onHost[i].close(); onHost[i] = null; } } } } } private static ColumnBufferProvider[] providersFrom(HostColumnVector[] columns, boolean closeAtEnd) { ColumnBufferProvider[] providers = new ColumnBufferProvider[columns.length]; for (int i = 0; i < columns.length; i++) { providers[i] = new ColumnProvider(columns[i], closeAtEnd); } return providers; } /** * For a batch of tables described by a header and corresponding buffer, return a mapping of * top column index to the corresponding column providers for that column across all tables. */ private static ColumnBufferProvider[][] providersFrom(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers) { int numColumns = 0; int numTables = headers.length; int numNonEmptyTables = 0; ArrayList<ArrayList<ColumnBufferProvider>> providersPerColumn = null; for (int tableIdx = 0; tableIdx < numTables; tableIdx++) { SerializedTableHeader header = headers[tableIdx]; if (tableIdx == 0) { numColumns = header.getNumColumns(); providersPerColumn = new ArrayList<>(numColumns); for (int i = 0; i < numColumns; i++) { providersPerColumn.add(new ArrayList<>(numTables)); } } else { checkCompatibleTypes(headers[0], header, tableIdx); } // filter out empty tables but keep at least one if all were empty if (headers[tableIdx].getNumRows() > 0 || (numNonEmptyTables == 0 && tableIdx == numTables - 1)) { numNonEmptyTables++; HostMemoryBuffer dataBuffer = dataBuffers[tableIdx]; ArrayDeque<ColumnOffsets> offsets = buildIndex(header, dataBuffer); for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) { ColumnBufferProvider provider = buildBufferOffsetProvider( header.getColumnHeader(columnIdx), offsets, dataBuffer); providersPerColumn.get(columnIdx).add(provider); } assert offsets.isEmpty(); } else { assert headers[tableIdx].dataLen == 0; } } ColumnBufferProvider[][] result = new ColumnBufferProvider[numColumns][]; for (int i = 0; i < numColumns; i++) { result[i] = providersPerColumn.get(i).toArray(new ColumnBufferProvider[0]); } return result; } private static void checkCompatibleTypes(SerializedTableHeader expected, SerializedTableHeader other, int tableIdx) { int numColumns = expected.getNumColumns(); if (other.getNumColumns() != numColumns) { throw new IllegalArgumentException("The number of columns did not match " + tableIdx + " " + other.getNumColumns() + " != " + numColumns); } for (int i = 0; i < numColumns; i++) { checkCompatibleTypes(expected.getColumnHeader(i), other.getColumnHeader(i), tableIdx, i); } } private static void checkCompatibleTypes(SerializedColumnHeader expected, SerializedColumnHeader other, int tableIdx, int columnIdx) { DType dtype = expected.getType(); if (!dtype.equals(other.getType())) { throw new IllegalArgumentException("Type mismatch at table " + tableIdx + "column " + columnIdx + " expected " + dtype + " but found " + other.getType()); } if (dtype.isNestedType()) { SerializedColumnHeader[] expectedChildren = expected.getChildren(); SerializedColumnHeader[] otherChildren = other.getChildren(); if (expectedChildren.length != otherChildren.length) { throw new IllegalArgumentException("Child count mismatch at table " + tableIdx + "column " + columnIdx + " expected " + expectedChildren.length + " but found " + otherChildren.length); } for (int i = 0; i < expectedChildren.length; i++) { checkCompatibleTypes(expectedChildren[i], otherChildren[i], tableIdx, columnIdx); } } } private static BufferOffsetProvider buildBufferOffsetProvider(SerializedColumnHeader header, ArrayDeque<ColumnOffsets> offsets, HostMemoryBuffer dataBuffer) { ColumnOffsets columnOffsets = offsets.remove(); ColumnBufferProvider[] childProviders = null; SerializedColumnHeader[] children = header.getChildren(); if (children != null) { childProviders = new ColumnBufferProvider[children.length]; for (int i = 0; i < children.length; i++) { childProviders[i] = buildBufferOffsetProvider(children[i], offsets, dataBuffer); } } return new BufferOffsetProvider(header, columnOffsets, dataBuffer, childProviders); } ///////////////////////////////////////////// // HELPER METHODS FOR SerializedTableHeader ///////////////////////////////////////////// private static SerializedTableHeader calcHeader(ColumnBufferProvider[] columns, long rowOffset, int numRows) { SerializedColumnHeader[] headers = new SerializedColumnHeader[columns.length]; for (int i = 0; i < headers.length; i++) { headers[i] = new SerializedColumnHeader(columns[i], rowOffset, numRows); } long dataLength = getSlicedSerializedDataSizeInBytes(columns, rowOffset, numRows); return new SerializedTableHeader(headers, numRows, dataLength); } /** * Calculate the new header for a concatenated set of columns. * @param providersPerColumn first index is the column, second index is the table. * @return the new header. */ private static SerializedTableHeader calcConcatHeader(ColumnBufferProvider[][] providersPerColumn) { int numColumns = providersPerColumn.length; long rowCount = 0; long totalDataSize = 0; ArrayList<SerializedColumnHeader> headers = new ArrayList<>(numColumns); for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) { totalDataSize += calcConcatColumnHeaderAndSize(headers, providersPerColumn[columnIdx]); if (columnIdx == 0) { rowCount = headers.get(0).getRowCount(); } else { assert rowCount == headers.get(columnIdx).getRowCount(); } } SerializedColumnHeader[] columnHeaders = headers.toArray(new SerializedColumnHeader[0]); return new SerializedTableHeader(columnHeaders, (int)rowCount, totalDataSize); } /** * Calculate a column header describing all of the columns concatenated together * @param outHeaders list that will be appended with the new column header * @param providers columns to be concatenated * @return total bytes needed to store the data for the result column and its children */ private static long calcConcatColumnHeaderAndSize(ArrayList<SerializedColumnHeader> outHeaders, ColumnBufferProvider[] providers) { long totalSize = 0; int numTables = providers.length; long rowCount = 0; long nullCount = 0; for (ColumnBufferProvider provider : providers) { rowCount += provider.getRowCount(); if (nullCount != ColumnView.UNKNOWN_NULL_COUNT) { long providerNullCount = provider.getNullCount(); if (providerNullCount == ColumnView.UNKNOWN_NULL_COUNT) { nullCount = ColumnView.UNKNOWN_NULL_COUNT; } else { nullCount += providerNullCount; } } } if (rowCount > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot build a batch larger than " + Integer.MAX_VALUE + " rows"); } if (needsValidityBuffer(nullCount)) { totalSize += padFor64byteAlignment(BitVectorHelper.getValidityLengthInBytes(rowCount)); } ColumnBufferProvider firstProvider = providers[0]; DType dtype = firstProvider.getType(); if (dtype.hasOffsets()) { if (rowCount > 0) { totalSize += padFor64byteAlignment((rowCount + 1) * Integer.BYTES); if (dtype.equals(DType.STRING)) { long stringDataLen = 0; for (ColumnBufferProvider provider : providers) { stringDataLen += getRawStringDataLength(provider, 0, provider.getRowCount()); } totalSize += padFor64byteAlignment(stringDataLen); } } } else if (dtype.getSizeInBytes() > 0) { totalSize += padFor64byteAlignment(dtype.getSizeInBytes() * rowCount); } SerializedColumnHeader[] children = null; if (dtype.isNestedType()) { int numChildren = firstProvider.getChildProviders().length; ArrayList<SerializedColumnHeader> childHeaders = new ArrayList<>(numChildren); ColumnBufferProvider[] childColumnProviders = new ColumnBufferProvider[numTables]; for (int childIdx = 0; childIdx < numChildren; childIdx++) { // collect all the providers for the current child and build the child's header for (int tableIdx = 0; tableIdx < numTables; tableIdx++) { childColumnProviders[tableIdx] = providers[tableIdx].getChildProviders()[childIdx]; } totalSize += calcConcatColumnHeaderAndSize(childHeaders, childColumnProviders); } children = childHeaders.toArray(new SerializedColumnHeader[0]); } outHeaders.add(new SerializedColumnHeader(dtype, rowCount, nullCount, children)); return totalSize; } ///////////////////////////////////////////// // HELPER METHODS FOR DataWriters ///////////////////////////////////////////// private static DataWriter writerFrom(OutputStream out) { if (!(out instanceof DataOutputStream)) { out = new DataOutputStream(new BufferedOutputStream(out)); } return new DataOutputStreamWriter((DataOutputStream) out); } private static DataWriter writerFrom(HostMemoryBuffer buffer) { return new HostDataWriter(buffer); } ///////////////////////////////////////////// // Serialize Data Methods ///////////////////////////////////////////// private static long copySlicedAndPad(DataWriter out, ColumnBufferProvider column, BufferType buffer, long offset, long length) throws IOException { out.copyDataFrom(column, buffer, offset, length); return padFor64byteAlignment(out, length); } ///////////////////////////////////////////// // VALIDITY ///////////////////////////////////////////// private static boolean needsValidityBuffer(long nullCount) { return nullCount > 0 || nullCount == ColumnView.UNKNOWN_NULL_COUNT; } private static int copyPartialValidity(byte[] dest, int destBitOffset, ColumnBufferProvider provider, int srcBitOffset, int lengthBits) { HostMemoryBuffer src = provider.getHostBufferFor(BufferType.VALIDITY); long baseSrcByteOffset = provider.getBufferStartOffset(BufferType.VALIDITY); int destStartBytes = destBitOffset / 8; int destStartBitOffset = destBitOffset % 8; long srcStartBytes = baseSrcByteOffset + (srcBitOffset / 8); int srcStartBitOffset = srcBitOffset % 8; int availableDestBits = (dest.length * 8) - destBitOffset; int bitsToCopy = Math.min(lengthBits, availableDestBits); int lastIndex = (bitsToCopy + destStartBitOffset + 7) / 8; byte allBitsSet = ~0; byte firstSrcMask = (byte)(allBitsSet << destStartBitOffset); int srcShift = destStartBitOffset - srcStartBitOffset; if (srcShift > 0) { // Shift left. If we are going to shift this is the path typically taken. byte current = src.getByte(srcStartBytes); byte result = (byte)(current << srcShift); // The first time we need to include any data already in dest. result |= dest[destStartBytes] & ~firstSrcMask; dest[destStartBytes] = result; // Keep the previous bytes around so we don't have to keep reading from src, which is not free byte previous = current; for (int index = 1; index < lastIndex; index++) { current = src.getByte(index + srcStartBytes); result = (byte)(current << srcShift); result |= (previous & 0xFF) >>> (8 - srcShift); dest[index + destStartBytes] = result; previous = current; } return bitsToCopy; } else if (srcShift < 0) { srcShift = -srcShift; // shifting right only happens when the buffer runs out of space. byte result = src.getByte(srcStartBytes); result = (byte)((result & 0xFF) >>> srcShift); byte next = 0; if (srcStartBytes + 1 < src.length) { next = src.getByte(srcStartBytes + 1); } result |= (byte)(next << 8 - srcShift); result &= firstSrcMask; // The first time through we need to include the data already in dest. result |= dest[destStartBytes] & ~firstSrcMask; dest[destStartBytes] = result; for (int index = 1; index < lastIndex - 1; index++) { result = next; result = (byte)((result & 0xFF) >>> srcShift); next = src.getByte(srcStartBytes + index + 1); result |= (byte)(next << 8 - srcShift); dest[index + destStartBytes] = result; } int idx = lastIndex - 1; if (idx > 0) { result = next; result = (byte) ((result & 0xFF) >>> srcShift); next = 0; if (srcStartBytes + idx + 1 < src.length) { next = src.getByte(srcStartBytes + idx + 1); } result |= (byte) (next << 8 - srcShift); dest[idx + destStartBytes] = result; } return bitsToCopy; } else { src.getBytes(dest, destStartBytes, srcStartBytes, (bitsToCopy + 7) / 8); return bitsToCopy; } } // package-private for testing static long copySlicedValidity(DataWriter out, ColumnBufferProvider column, long rowOffset, long numRows) throws IOException { long validityLen = BitVectorHelper.getValidityLengthInBytes(numRows); long byteOffset = (rowOffset / 8); long bytesLeft = validityLen; int lshift = (int) rowOffset % 8; if (lshift == 0) { out.copyDataFrom(column, BufferType.VALIDITY, byteOffset, bytesLeft); } else { byte[] arrayBuffer = new byte[128 * 1024]; int rowsStoredInArray = 0; int rowsLeftInBatch = (int) numRows; int validityBitOffset = (int) rowOffset; while(rowsLeftInBatch > 0) { int rowsStoredJustNow = copyPartialValidity(arrayBuffer, rowsStoredInArray, column, validityBitOffset, rowsLeftInBatch); assert rowsStoredJustNow > 0; rowsLeftInBatch -= rowsStoredJustNow; rowsStoredInArray += rowsStoredJustNow; validityBitOffset += rowsStoredJustNow; if (rowsStoredInArray == arrayBuffer.length * 8) { out.write(arrayBuffer, 0, arrayBuffer.length); rowsStoredInArray = 0; } } if (rowsStoredInArray > 0) { out.write(arrayBuffer, 0, (rowsStoredInArray + 7) / 8); } } return padFor64byteAlignment(out, validityLen); } // Package private for testing static int fillValidity(byte[] dest, int destBitOffset, int lengthBits) { int destStartBytes = destBitOffset / 8; int destStartBits = destBitOffset % 8; long lengthBytes = BitVectorHelper.getValidityLengthInBytes(lengthBits); int rshift = destStartBits; int totalCopied = 0; if (rshift != 0) { // Fill in what we need to make it copyable dest[destStartBytes] |= (0xFF << destStartBits); destStartBytes += 1; totalCopied = (8 - destStartBits); // Not used again, but just to be safe destStartBits = 0; } int amountToCopyBytes = (int) Math.min(lengthBytes, dest.length - destStartBytes); for (int i = 0; i < amountToCopyBytes; i++) { dest[i + destStartBytes] = (byte) 0xFF; } totalCopied += amountToCopyBytes * 8; return Math.min(totalCopied, lengthBits); } private static long concatValidity(DataWriter out, long numRows, ColumnBufferProvider[] providers) throws IOException { long validityLen = BitVectorHelper.getValidityLengthInBytes(numRows); byte[] arrayBuffer = new byte[128 * 1024]; int rowsStoredInArray = 0; for (ColumnBufferProvider provider : providers) { int rowsLeftInBatch = (int) provider.getRowCount(); int validityBitOffset = 0; while(rowsLeftInBatch > 0) { int rowsStoredJustNow; if (needsValidityBuffer(provider.getNullCount())) { rowsStoredJustNow = copyPartialValidity(arrayBuffer, rowsStoredInArray, provider, validityBitOffset, rowsLeftInBatch); } else { rowsStoredJustNow = fillValidity(arrayBuffer, rowsStoredInArray, rowsLeftInBatch); } assert rowsStoredJustNow > 0; assert rowsStoredJustNow <= rowsLeftInBatch; rowsLeftInBatch -= rowsStoredJustNow; rowsStoredInArray += rowsStoredJustNow; validityBitOffset += rowsStoredJustNow; if (rowsStoredInArray == arrayBuffer.length * 8) { out.write(arrayBuffer, 0, arrayBuffer.length); rowsStoredInArray = 0; } } } if (rowsStoredInArray > 0) { int len = (rowsStoredInArray + 7) / 8; out.write(arrayBuffer, 0, len); } return padFor64byteAlignment(out, validityLen); } ///////////////////////////////////////////// // STRING ///////////////////////////////////////////// private static long copySlicedStringData(DataWriter out, ColumnBufferProvider column, long rowOffset, long numRows) throws IOException { if (numRows > 0) { long startByteOffset = column.getOffset(rowOffset); long endByteOffset = column.getOffset(rowOffset + numRows); long bytesToCopy = endByteOffset - startByteOffset; long srcOffset = startByteOffset; return copySlicedAndPad(out, column, BufferType.DATA, srcOffset, bytesToCopy); } return 0; } private static void copyConcatStringData(DataWriter out, ColumnBufferProvider[] providers) throws IOException { long totalCopied = 0; for (ColumnBufferProvider provider : providers) { long rowCount = provider.getRowCount(); if (rowCount > 0) { HostMemoryBuffer dataBuffer = provider.getHostBufferFor(BufferType.DATA); long currentOffset = provider.getBufferStartOffset(BufferType.DATA); long dataLeft = provider.getOffset(rowCount); out.copyDataFrom(dataBuffer, currentOffset, dataLeft); totalCopied += dataLeft; } } padFor64byteAlignment(out, totalCopied); } private static long copySlicedOffsets(DataWriter out, ColumnBufferProvider column, long rowOffset, long numRows) throws IOException { if (numRows <= 0) { // Don't copy anything, there are no rows return 0; } long bytesToCopy = (numRows + 1) * Integer.BYTES; long srcOffset = rowOffset * Integer.BYTES; if (rowOffset == 0) { return copySlicedAndPad(out, column, BufferType.OFFSET, srcOffset, bytesToCopy); } HostMemoryBuffer buff = column.getHostBufferFor(BufferType.OFFSET); long startOffset = column.getBufferStartOffset(BufferType.OFFSET) + srcOffset; if (bytesToCopy >= Integer.MAX_VALUE) { throw new IllegalStateException("Copy is too large, need to do chunked copy"); } ByteBuffer bb = buff.asByteBuffer(startOffset, (int)bytesToCopy); int start = bb.getInt(); out.writeIntNativeOrder(0); long total = Integer.BYTES; for (int i = 1; i < (numRows + 1); i++) { int offset = bb.getInt(); out.writeIntNativeOrder(offset - start); total += Integer.BYTES; } assert total == bytesToCopy; long ret = padFor64byteAlignment(out, total); return ret; } private static void copyConcatOffsets(DataWriter out, ColumnBufferProvider[] providers) throws IOException { long totalCopied = 0; int offsetToAdd = 0; for (ColumnBufferProvider provider : providers) { long rowCount = provider.getRowCount(); if (rowCount > 0) { HostMemoryBuffer offsetsBuffer = provider.getHostBufferFor(BufferType.OFFSET); long currentOffset = provider.getBufferStartOffset(BufferType.OFFSET); if (totalCopied == 0) { // first chunk of offsets can be copied verbatim totalCopied = (rowCount + 1) * Integer.BYTES; out.copyDataFrom(offsetsBuffer, currentOffset, totalCopied); offsetToAdd = offsetsBuffer.getInt(currentOffset + (rowCount * Integer.BYTES)); } else { int localOffset = 0; // first row's offset has already been written when processing the previous table for (int row = 1; row < rowCount + 1; row++) { localOffset = offsetsBuffer.getInt(currentOffset + (row * Integer.BYTES)); out.writeIntNativeOrder(localOffset + offsetToAdd); } // last local offset of this chunk is the length of data referenced by offsets offsetToAdd += localOffset; totalCopied += rowCount * Integer.BYTES; } } } padFor64byteAlignment(out, totalCopied); } ///////////////////////////////////////////// // BASIC DATA ///////////////////////////////////////////// private static long sliceBasicData(DataWriter out, ColumnBufferProvider column, long rowOffset, long numRows) throws IOException { DType type = column.getType(); long bytesToCopy = numRows * type.getSizeInBytes(); long srcOffset = rowOffset * type.getSizeInBytes(); return copySlicedAndPad(out, column, BufferType.DATA, srcOffset, bytesToCopy); } private static void concatBasicData(DataWriter out, DType type, ColumnBufferProvider[] providers) throws IOException { long totalCopied = 0; for (ColumnBufferProvider provider : providers) { long rowCount = provider.getRowCount(); if (rowCount > 0) { HostMemoryBuffer dataBuffer = provider.getHostBufferFor(BufferType.DATA); long currentOffset = provider.getBufferStartOffset(BufferType.DATA); long dataLeft = rowCount * type.getSizeInBytes(); out.copyDataFrom(dataBuffer, currentOffset, dataLeft); totalCopied += dataLeft; } } padFor64byteAlignment(out, totalCopied); } ///////////////////////////////////////////// // COLUMN AND TABLE WRITE ///////////////////////////////////////////// private static void writeConcat(DataWriter out, SerializedColumnHeader header, ColumnBufferProvider[] providers) throws IOException { if (needsValidityBuffer(header.getNullCount())) { concatValidity(out, header.getRowCount(), providers); } DType dtype = header.getType(); if (dtype.hasOffsets()) { if (header.getRowCount() > 0) { copyConcatOffsets(out, providers); if (dtype.equals(DType.STRING)) { copyConcatStringData(out, providers); } } } else if (dtype.getSizeInBytes() > 0) { concatBasicData(out, dtype, providers); } if (dtype.isNestedType()) { int numTables = providers.length; SerializedColumnHeader[] childHeaders = header.getChildren(); ColumnBufferProvider[] childColumnProviders = new ColumnBufferProvider[numTables]; for (int childIdx = 0; childIdx < childHeaders.length; childIdx++) { // collect all the providers for the current child column for (int tableIdx = 0; tableIdx < numTables; tableIdx++) { childColumnProviders[tableIdx] = providers[tableIdx].getChildProviders()[childIdx]; } writeConcat(out, childHeaders[childIdx], childColumnProviders); } } } private static void writeSliced(DataWriter out, ColumnBufferProvider column, long rowOffset, long numRows) throws IOException { if (needsValidityBuffer(column.getNullCount())) { try (NvtxRange range = new NvtxRange("Write Validity", NvtxColor.DARK_GREEN)) { copySlicedValidity(out, column, rowOffset, numRows); } } DType type = column.getType(); if (type.hasOffsets()) { if (numRows > 0) { try (NvtxRange offsetRange = new NvtxRange("Write Offset Data", NvtxColor.ORANGE)) { copySlicedOffsets(out, column, rowOffset, numRows); if (type.equals(DType.STRING)) { try (NvtxRange dataRange = new NvtxRange("Write String Data", NvtxColor.RED)) { copySlicedStringData(out, column, rowOffset, numRows); } } } } } else if (type.getSizeInBytes() > 0){ try (NvtxRange range = new NvtxRange("Write Data", NvtxColor.BLUE)) { sliceBasicData(out, column, rowOffset, numRows); } } if (numRows > 0 && type.isNestedType()) { if (type.equals(DType.LIST)) { try (NvtxRange range = new NvtxRange("Write List Child", NvtxColor.PURPLE)) { ColumnBufferProvider child = column.getChildProviders()[0]; long childStartRow = column.getOffset(rowOffset); long childNumRows = column.getOffset(rowOffset + numRows) - childStartRow; writeSliced(out, child, childStartRow, childNumRows); } } else if (type.equals(DType.STRUCT)) { try (NvtxRange range = new NvtxRange("Write Struct Children", NvtxColor.PURPLE)) { for (ColumnBufferProvider child : column.getChildProviders()) { writeSliced(out, child, rowOffset, numRows); } } } else { throw new IllegalStateException("Unexpected nested type: " + type); } } } private static void writeSliced(ColumnBufferProvider[] columns, DataWriter out, long rowOffset, long numRows) throws IOException { assert rowOffset >= 0; assert numRows >= 0; for (int i = 0; i < columns.length; i++) { long rows = columns[i].getRowCount(); assert rowOffset + numRows <= rows; assert rows == (int) rows : "can only support an int for indexes"; } SerializedTableHeader header = calcHeader(columns, rowOffset, (int) numRows); header.writeTo(out); try (NvtxRange range = new NvtxRange("Write Sliced", NvtxColor.GREEN)) { for (int i = 0; i < columns.length; i++) { writeSliced(out, columns[i], rowOffset, numRows); } } out.flush(); } /** * Write all or part of a table out in an internal format. * @param t the table to be written. * @param out the stream to write the serialized table out to. * @param rowOffset the first row to write out. * @param numRows the number of rows to write out. */ public static void writeToStream(Table t, OutputStream out, long rowOffset, long numRows) throws IOException { writeToStream(t.getColumns(), out, rowOffset, numRows); } /** * Write all or part of a set of columns out in an internal format. * @param columns the columns to be written. * @param out the stream to write the serialized table out to. * @param rowOffset the first row to write out. * @param numRows the number of rows to write out. */ public static void writeToStream(ColumnVector[] columns, OutputStream out, long rowOffset, long numRows) throws IOException { ColumnBufferProvider[] providers = providersFrom(columns); try { DataWriter writer = writerFrom(out); writeSliced(providers, writer, rowOffset, numRows); } finally { closeAll(providers); } } /** * Write all or part of a set of columns out in an internal format. * @param columns the columns to be written. * @param out the stream to write the serialized table out to. * @param rowOffset the first row to write out. * @param numRows the number of rows to write out. */ public static void writeToStream(HostColumnVector[] columns, OutputStream out, long rowOffset, long numRows) throws IOException { ColumnBufferProvider[] providers = providersFrom(columns, false); try { DataWriter writer = writerFrom(out); writeSliced(providers, writer, rowOffset, numRows); } finally { closeAll(providers); } } /** * Write a rowcount only header to the output stream in a case * where a columnar batch with no columns but a non zero row count is received * @param out the stream to write the serialized table out to. * @param numRows the number of rows to write out. */ public static void writeRowsToStream(OutputStream out, long numRows) throws IOException { DataWriter writer = writerFrom(out); SerializedTableHeader header = new SerializedTableHeader((int) numRows); header.writeTo(writer); writer.flush(); } /** * Take the data from multiple batches stored in the parsed headers and the dataBuffer and write * it out to out as if it were a single buffer. * @param headers the headers parsed from multiple streams. * @param dataBuffers an array of buffers that hold the data, one per header. * @param out what to write the data out to. * @throws IOException on any error. */ public static void writeConcatedStream(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers, OutputStream out) throws IOException { ColumnBufferProvider[][] providersPerColumn = providersFrom(headers, dataBuffers); try { SerializedTableHeader combined = calcConcatHeader(providersPerColumn); DataWriter writer = writerFrom(out); combined.writeTo(writer); try (NvtxRange range = new NvtxRange("Concat Host Side", NvtxColor.GREEN)) { int numColumns = combined.getNumColumns(); for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) { ColumnBufferProvider[] providers = providersPerColumn[columnIdx]; writeConcat(writer, combined.getColumnHeader(columnIdx), providersPerColumn[columnIdx]); } } writer.flush(); } finally { closeAll(providersPerColumn); } } ///////////////////////////////////////////// // COLUMN AND TABLE READ ///////////////////////////////////////////// private static HostColumnVectorCore buildHostColumn(SerializedColumnHeader column, ArrayDeque<ColumnOffsets> columnOffsets, HostMemoryBuffer buffer, boolean isRootColumn) { ColumnOffsets offsetsInfo = columnOffsets.remove(); SerializedColumnHeader[] children = column.getChildren(); int numChildren = children != null ? children.length : 0; List<HostColumnVectorCore> childColumns = new ArrayList<>(numChildren); try { if (children != null) { for (SerializedColumnHeader child : children) { childColumns.add(buildHostColumn(child, columnOffsets, buffer, false)); } } DType dtype = column.getType(); long rowCount = column.getRowCount(); long nullCount = column.getNullCount(); HostMemoryBuffer dataBuffer = null; HostMemoryBuffer validityBuffer = null; HostMemoryBuffer offsetsBuffer = null; if (!dtype.isNestedType()) { dataBuffer = buffer.slice(offsetsInfo.data, offsetsInfo.dataLen); } if (needsValidityBuffer(nullCount)) { long validitySize = BitVectorHelper.getValidityLengthInBytes(rowCount); validityBuffer = buffer.slice(offsetsInfo.validity, validitySize); } if (dtype.hasOffsets()) { // one 32-bit integer offset per row plus one additional offset at the end long offsetsSize = rowCount > 0 ? (rowCount + 1) * Integer.BYTES : 0; offsetsBuffer = buffer.slice(offsetsInfo.offsets, offsetsSize); } HostColumnVectorCore result; // Only creates HostColumnVector for root columns, since child columns are managed by their parents. if (isRootColumn) { result = new HostColumnVector(dtype, rowCount, Optional.of(nullCount), dataBuffer, validityBuffer, offsetsBuffer, childColumns); } else { result = new HostColumnVectorCore(dtype, rowCount, Optional.of(nullCount), dataBuffer, validityBuffer, offsetsBuffer, childColumns); } childColumns = null; return result; } finally { if (childColumns != null) { for (HostColumnVectorCore c : childColumns) { c.close(); } } } } private static long buildColumnView(SerializedColumnHeader column, ArrayDeque<ColumnOffsets> columnOffsets, DeviceMemoryBuffer combinedBuffer) { ColumnOffsets offsetsInfo = columnOffsets.remove(); long[] childViews = null; try { SerializedColumnHeader[] children = column.getChildren(); if (children != null) { childViews = new long[children.length]; for (int i = 0; i < childViews.length; i++) { childViews[i] = buildColumnView(children[i], columnOffsets, combinedBuffer); } } DType dtype = column.getType(); long bufferAddress = combinedBuffer.getAddress(); long dataAddress = dtype.isNestedType() ? 0 : bufferAddress + offsetsInfo.data; long validityAddress = needsValidityBuffer(column.getNullCount()) ? bufferAddress + offsetsInfo.validity : 0; long offsetsAddress = dtype.hasOffsets() ? bufferAddress + offsetsInfo.offsets : 0; return ColumnView.makeCudfColumnView( dtype.typeId.getNativeId(), dtype.getScale(), dataAddress, offsetsInfo.dataLen, offsetsAddress, validityAddress, (int) column.getNullCount(), (int) column.getRowCount(), childViews); } finally { if (childViews != null) { for (long childView : childViews) { ColumnView.deleteColumnView(childView); } } } } private static Table sliceUpColumnVectors(SerializedTableHeader header, DeviceMemoryBuffer combinedBuffer, HostMemoryBuffer combinedBufferOnHost) { try (NvtxRange range = new NvtxRange("bufferToTable", NvtxColor.PURPLE)) { ArrayDeque<ColumnOffsets> columnOffsets = buildIndex(header, combinedBufferOnHost); int numColumns = header.getNumColumns(); ColumnVector[] vectors = new ColumnVector[numColumns]; try { for (int i = 0; i < numColumns; i++) { SerializedColumnHeader column = header.getColumnHeader(i); long columnView = buildColumnView(column, columnOffsets, combinedBuffer); vectors[i] = ColumnVector.fromViewWithContiguousAllocation(columnView, combinedBuffer); } assert columnOffsets.isEmpty(); return new Table(vectors); } finally { for (ColumnVector cv: vectors) { if (cv != null) { cv.close(); } } } } } public static Table readAndConcat(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers) throws IOException { ContiguousTable ct = concatToContiguousTable(headers, dataBuffers); ct.getBuffer().close(); return ct.getTable(); } /** * Concatenate multiple tables in host memory into a contiguous table in device memory. * @param headers table headers corresponding to the host table buffers * @param dataBuffers host table buffer for each input table to be concatenated * @return contiguous table in device memory */ public static ContiguousTable concatToContiguousTable(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers) throws IOException { try (HostConcatResult concatResult = concatToHostBuffer(headers, dataBuffers)) { return concatResult.toContiguousTable(); } } /** * Concatenate multiple tables in host memory into a single host table buffer. * @param headers table headers corresponding to the host table buffers * @param dataBuffers host table buffer for each input table to be concatenated * @param hostMemoryAllocator allocator for host memory buffers * @return host table header and buffer */ public static HostConcatResult concatToHostBuffer(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers, HostMemoryAllocator hostMemoryAllocator ) throws IOException { ColumnBufferProvider[][] providersPerColumn = providersFrom(headers, dataBuffers); try { SerializedTableHeader combined = calcConcatHeader(providersPerColumn); HostMemoryBuffer hostBuffer = hostMemoryAllocator.allocate(combined.dataLen); try { try (NvtxRange range = new NvtxRange("Concat Host Side", NvtxColor.GREEN)) { DataWriter writer = writerFrom(hostBuffer); int numColumns = combined.getNumColumns(); for (int columnIdx = 0; columnIdx < numColumns; columnIdx++) { writeConcat(writer, combined.getColumnHeader(columnIdx), providersPerColumn[columnIdx]); } } } catch (Exception e) { hostBuffer.close(); throw e; } return new HostConcatResult(combined, hostBuffer); } finally { closeAll(providersPerColumn); } } public static HostConcatResult concatToHostBuffer(SerializedTableHeader[] headers, HostMemoryBuffer[] dataBuffers ) throws IOException { return concatToHostBuffer(headers, dataBuffers, DefaultHostMemoryAllocator.get()); } /** * Deserialize a serialized contiguous table into an array of host columns. * * @param header serialized table header * @param hostBuffer buffer containing the data for all columns in the serialized table * @return array of host columns representing the data from the serialized table */ public static HostColumnVector[] unpackHostColumnVectors(SerializedTableHeader header, HostMemoryBuffer hostBuffer) { ArrayDeque<ColumnOffsets> columnOffsets = buildIndex(header, hostBuffer); int numColumns = header.getNumColumns(); HostColumnVector[] columns = new HostColumnVector[numColumns]; boolean succeeded = false; try { for (int i = 0; i < numColumns; i++) { SerializedColumnHeader column = header.getColumnHeader(i); columns[i] = (HostColumnVector) buildHostColumn(column, columnOffsets, hostBuffer, true); } assert columnOffsets.isEmpty(); succeeded = true; } finally { if (!succeeded) { for (HostColumnVector c : columns) { if (c != null) { c.close(); } } } } return columns; } /** * After reading a header for a table read the data portion into a host side buffer. * @param in the stream to read the data from. * @param header the header that finished just moments ago. * @param buffer the buffer to write the data into. If there is not enough room to store * the data in buffer it will not be read and header will still have dataRead * set to false. * @throws IOException */ public static void readTableIntoBuffer(InputStream in, SerializedTableHeader header, HostMemoryBuffer buffer) throws IOException { if (header.initialized && (buffer.length >= header.dataLen)) { try (NvtxRange range = new NvtxRange("Read Data", NvtxColor.RED)) { buffer.copyFromStream(0, in, header.dataLen); } header.dataRead = true; } } public static TableAndRowCountPair readTableFrom(SerializedTableHeader header, HostMemoryBuffer hostBuffer) { ContiguousTable contigTable = null; DeviceMemoryBuffer devBuffer = DeviceMemoryBuffer.allocate(hostBuffer.length); try { if (hostBuffer.length > 0) { try (NvtxRange range = new NvtxRange("Copy Data To Device", NvtxColor.WHITE)) { devBuffer.copyFromHostBuffer(hostBuffer); } } if (header.getNumColumns() > 0) { Table table = sliceUpColumnVectors(header, devBuffer, hostBuffer); contigTable = new ContiguousTable(table, devBuffer); } } finally { if (contigTable == null) { devBuffer.close(); } } return new TableAndRowCountPair(header.numRows, contigTable); } /** * Read a serialize table from the given InputStream. * @param in the stream to read the table data from. * @param hostMemoryAllocator a host memory allocator for an intermediate host memory buffer * @return the deserialized table in device memory, or null if the stream has no table to read * from, an end of the stream at the very beginning. * @throws IOException on any error. * @throws EOFException if the data stream ended unexpectedly in the middle of processing. */ public static TableAndRowCountPair readTableFrom(InputStream in, HostMemoryAllocator hostMemoryAllocator) throws IOException { DataInputStream din; if (in instanceof DataInputStream) { din = (DataInputStream) in; } else { din = new DataInputStream(in); } SerializedTableHeader header = new SerializedTableHeader(din); if (!header.initialized) { return new TableAndRowCountPair(0, null); } try (HostMemoryBuffer hostBuffer = hostMemoryAllocator.allocate(header.dataLen)) { if (header.dataLen > 0) { readTableIntoBuffer(din, header, hostBuffer); } return readTableFrom(header, hostBuffer); } } public static TableAndRowCountPair readTableFrom(InputStream in) throws IOException { return readTableFrom(in, DefaultHostMemoryAllocator.get()); } /** Holds the result of deserializing a table. */ public static final class TableAndRowCountPair implements Closeable { private final int numRows; private final ContiguousTable contigTable; public TableAndRowCountPair(int numRows, ContiguousTable table) { this.numRows = numRows; this.contigTable = table; } @Override public void close() { if (contigTable != null) { contigTable.close(); } } /** Get the number of rows that were deserialized. */ public int getNumRows() { return numRows; } /** * Get the Table that was deserialized or null if there was no data * (e.g.: rows without columns). * <p>NOTE: Ownership of the table is not transferred by this method. * The table is still owned by this instance and will be closed when this * instance is closed. */ public Table getTable() { if (contigTable != null) { return contigTable.getTable(); } return null; } /** * Get the ContiguousTable that was deserialized or null if there was no * data (e.g.: rows without columns). * <p>NOTE: Ownership of the contiguous table is not transferred by this * method. The contiguous table is still owned by this instance and will * be closed when this instance is closed. */ public ContiguousTable getContiguousTable() { return contigTable; } } }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/CuFileBuffer.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.rapids.cudf; /** * Represents a cuFile buffer. */ public final class CuFileBuffer extends BaseDeviceMemoryBuffer { private static final int ALIGNMENT = 4096; private final DeviceMemoryBuffer deviceMemoryBuffer; private final CuFileResourceCleaner cleaner; static { CuFile.initialize(); } /** * Construct a new cuFile buffer. * * @param buffer The device memory buffer used for the cuFile buffer. This buffer is owned * by the cuFile buffer, and will be closed when the cuFile buffer is closed. * @param registerBuffer If true, register the cuFile buffer. */ private CuFileBuffer(DeviceMemoryBuffer buffer, boolean registerBuffer) { super(buffer.address, buffer.length, (MemoryBufferCleaner) null); if (registerBuffer && !isAligned(buffer)) { buffer.close(); throw new IllegalArgumentException( "To register a cuFile buffer, its length must be a multiple of " + ALIGNMENT); } deviceMemoryBuffer = buffer; cleaner = new CuFileResourceCleaner(create(buffer.address, buffer.length, registerBuffer), CuFileBuffer::destroy); MemoryCleaner.register(this, cleaner); } /** * Allocate memory for use with cuFile on the GPU. You must close it when done. * * @param bytes size in bytes to allocate * @param registerBuffer If true, register the cuFile buffer. * @return the buffer */ public static CuFileBuffer allocate(long bytes, boolean registerBuffer) { DeviceMemoryBuffer buffer = DeviceMemoryBuffer.allocate(bytes); return new CuFileBuffer(buffer, registerBuffer); } @Override public MemoryBuffer slice(long offset, long len) { throw new UnsupportedOperationException("Slice on cuFile buffer is not supported"); } @Override public void close() { cleaner.close(this); deviceMemoryBuffer.close(); } long getPointer() { return cleaner.getPointer(); } private boolean isAligned(BaseDeviceMemoryBuffer buffer) { return buffer.length % ALIGNMENT == 0; } private static native long create(long address, long length, boolean registerBuffer); private static native void destroy(long pointer); }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/RmmCudaAsyncMemoryResource.java
/* * 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. */ package ai.rapids.cudf; /** * A device memory resource that uses `cudaMallocAsync` and `cudaFreeAsync` for allocation and * deallocation. */ public class RmmCudaAsyncMemoryResource implements RmmDeviceMemoryResource { private final long releaseThreshold; private final long size; private long handle = 0; /** * Create a new async memory resource * @param size the initial size of the pool * @param releaseThreshold size in bytes for when memory is released back to cuda */ public RmmCudaAsyncMemoryResource(long size, long releaseThreshold) { this.size = size; this.releaseThreshold = releaseThreshold; handle = Rmm.newCudaAsyncMemoryResource(size, releaseThreshold); } @Override public long getHandle() { return handle; } public long getSize() { return size; } @Override public void close() { if (handle != 0) { Rmm.releaseCudaAsyncMemoryResource(handle); handle = 0; } } @Override public String toString() { return Long.toHexString(getHandle()) + "/ASYNC(" + size + ", " + releaseThreshold + ")"; } }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/MixedJoinSize.java
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.rapids.cudf; /** This class tracks size information associated with a mixed table join. */ public final class MixedJoinSize implements AutoCloseable { private final long outputRowCount; // This is in flux, avoid exposing publicly until the dust settles. private ColumnVector matches; MixedJoinSize(long outputRowCount, ColumnVector matches) { this.outputRowCount = outputRowCount; this.matches = matches; } /** Return the number of output rows that would be generated from the mixed join */ public long getOutputRowCount() { return outputRowCount; } ColumnVector getMatches() { return matches; } @Override public synchronized void close() { matches.close(); } }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/NullEquality.java
/* * * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ai.rapids.cudf; /** * How should nulls be compared in an operation. */ public enum NullEquality { UNEQUAL(false), EQUAL(true); NullEquality(boolean nullsEqual) { this.nullsEqual = nullsEqual; } final boolean nullsEqual; }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/HashType.java
/* * * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ai.rapids.cudf; /** * Hash algorithm identifiers, mirroring native enum cudf::hash_id */ public enum HashType { IDENTITY(0), MURMUR3(1), HASH_SPARK_MURMUR3(2), HASH_MD5(3); private static final HashType[] HASH_TYPES = HashType.values(); final int nativeId; HashType(int nativeId) { this.nativeId = nativeId; } public int getNativeId() { return nativeId; } public static HashType fromNative(int nativeId) { for (HashType type : HASH_TYPES) { if (type.nativeId == nativeId) { return type; } } throw new IllegalArgumentException("Could not translate " + nativeId + " into a HashType"); } }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/CloseableArray.java
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.rapids.cudf; /** Utility class that wraps an array of closeable instances and can be closed */ public class CloseableArray<T extends AutoCloseable> implements AutoCloseable { private T[] array; public static <T extends AutoCloseable> CloseableArray<T> wrap(T[] array) { return new CloseableArray<T>(array); } CloseableArray(T[] array) { this.array = array; } public int size() { return array.length; } public T get(int i) { return array[i]; } public T set(int i, T obj) { array[i] = obj; return obj; } public T[] getArray() { return array; } public T[] release() { T[] result = array; array = null; return result; } public void closeAt(int i) { try { T toClose = array[i]; array[i] = null; toClose.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } @Override public void close() { close(null); } public void close(Exception pendingError) { if (array == null) { return; } T[] toClose = array; array = null; RuntimeException error = null; if (pendingError instanceof RuntimeException) { error = (RuntimeException) pendingError; } else if (pendingError != null) { error = new RuntimeException(pendingError); } for (T obj: toClose) { if (obj != null) { try { obj.close(); } catch (RuntimeException e) { if (error != null) { error.addSuppressed(e); } else { error = e; } } catch (Exception e) { if (error != null) { error.addSuppressed(e); } else { error = new RuntimeException(e); } } } } if (error != null) { throw error; } } }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/CudfException.java
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.rapids.cudf; /** * Exception thrown by cudf itself. */ public class CudfException extends RuntimeException { CudfException(String message) { this(message, "No native stacktrace is available."); } CudfException(String message, String nativeStacktrace) { super(message); this.nativeStacktrace = nativeStacktrace; } CudfException(String message, String nativeStacktrace, Throwable cause) { super(message, cause); this.nativeStacktrace = nativeStacktrace; } public final String getNativeStacktrace() { return nativeStacktrace; } private final String nativeStacktrace; }
0
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids
rapidsai_public_repos/cudf/java/src/main/java/ai/rapids/cudf/RegexProgram.java
/* * * 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. * */ package ai.rapids.cudf; import java.util.EnumSet; /** * Regex program class, closely following cudf::strings::regex_program. */ public class RegexProgram { private String pattern; // regex pattern // regex flags for interpreting special characters in the pattern private EnumSet<RegexFlag> flags; // controls how capture groups in the pattern are used // default is to extract a capture group private CaptureGroups capture; /** * Constructor for RegexProgram * * @param pattern Regex pattern */ public RegexProgram(String pattern) { this(pattern, EnumSet.of(RegexFlag.DEFAULT), CaptureGroups.EXTRACT); } /** * Constructor for RegexProgram * * @param pattern Regex pattern * @param flags Regex flags setting */ public RegexProgram(String pattern, EnumSet<RegexFlag> flags) { this(pattern, flags, CaptureGroups.EXTRACT); } /** * Constructor for RegexProgram * * @param pattern Regex pattern setting * @param capture Capture groups setting */ public RegexProgram(String pattern, CaptureGroups capture) { this(pattern, EnumSet.of(RegexFlag.DEFAULT), capture); } /** * Constructor for RegexProgram * * @param pattern Regex pattern * @param flags Regex flags setting * @param capture Capture groups setting */ public RegexProgram(String pattern, EnumSet<RegexFlag> flags, CaptureGroups capture) { assert pattern != null : "pattern may not be null"; this.pattern = pattern; this.flags = flags; this.capture = capture; } /** * Get the pattern used to create this instance * * @param return A regex pattern as a string */ public String pattern() { return pattern; } /** * Get the regex flags setting used to create this instance * * @param return Regex flags setting */ public EnumSet<RegexFlag> flags() { return flags; } /** * Reset the regex flags setting for this instance * * @param flags Regex flags setting */ public void setFlags(EnumSet<RegexFlag> flags) { this.flags = flags; } /** * Get the capture groups setting used to create this instance * * @param return Capture groups setting */ public CaptureGroups capture() { return capture; } /** * Reset the capture groups setting for this instance * * @param capture Capture groups setting */ public void setCapture(CaptureGroups capture) { this.capture = capture; } /** * Combine the regex flags using 'or' * * @param return An integer representing the value of combined (or'ed) flags */ public int combinedFlags() { int allFlags = 0; for (RegexFlag flag : flags) { allFlags |= flag.nativeId; } return allFlags; } }
0