<commit_before>﻿# Copyright 2014, 2015 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL.  If not, see <http://www.gnu.org/licenses/>.

"""CUDA implementation of n-dimensional Cartesian spaces."""

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import int, super

# External module imports
import numpy as np

# ODL imports
from odl.set.space import LinearSpace, LinearSpaceVector
from odl.space.base_ntuples import (NtuplesBase, NtuplesBaseVector,
                                    FnBase, FnBaseVector,
                                    FnWeightingBase)
from odl.util.utility import is_real_dtype, is_real_floating_dtype, dtype_repr
from odl.util.ufuncs import CudaNtuplesVectorUFuncs

try:
    import odlpp.odlpp_cuda as cuda
    CUDA_AVAILABLE = True
except ImportError:
    cuda = None
    CUDA_AVAILABLE = False

__all__ = ('CudaNtuples', 'CudaNtuplesVector',
           'CudaFn', 'CudaFnVector', 'CudaRn', 'CudaRnVector',
           'CUDA_DTYPES', 'CUDA_AVAILABLE',
           'CudaFnConstWeighting', 'CudaFnVectorWeighting',
           'cu_weighted_inner', 'cu_weighted_norm', 'cu_weighted_dist')


def _get_int_type():
    if np.dtype(np.int).itemsize == 4:
        return 'CudaVectorInt32'
    elif np.dtype(np.int).itemsize == 8:
        return 'CudaVectorInt64'
    else:
        return 'CudaVectorIntNOT_AVAILABLE'


def _add_if_exists(dtype, name):
    if hasattr(cuda, name):
        _TYPE_MAP_NPY2CUDA[np.dtype(dtype)] = getattr(cuda, name)
        CUDA_DTYPES.append(np.dtype(dtype))


# A list of all available dtypes
CUDA_DTYPES = []

# Typemap from numpy dtype to implementations
_TYPE_MAP_NPY2CUDA = {}

# Initialize the available dtypes
_add_if_exists(np.float, 'CudaVectorFloat64')
_add_if_exists(np.float32, 'CudaVectorFloat32')
_add_if_exists(np.float64, 'CudaVectorFloat64')
_add_if_exists(np.int, _get_int_type())
_add_if_exists(np.int8, 'CudaVectorInt8')
_add_if_exists(np.int16, 'CudaVectorInt16')
_add_if_exists(np.int32, 'CudaVectorInt32')
_add_if_exists(np.int64, 'CudaVectorInt64')
_add_if_exists(np.uint8, 'CudaVectorUInt8')
_add_if_exists(np.uint16, 'CudaVectorUInt16')
_add_if_exists(np.uint32, 'CudaVectorUInt32')
_add_if_exists(np.uint64, 'CudaVectorUInt64')
CUDA_DTYPES = tuple(set(CUDA_DTYPES))  # Remove duplicates


class CudaNtuples(NtuplesBase):
    """The space `NtuplesBase`, implemented in CUDA."""

    def __init__(self, size, dtype):
        """Initialize a new instance.

        Parameters
        ----------
        size : `int`
            The number entries per tuple
        dtype : `object`
            The data type for each tuple entry. Can be provided in any
            way the `numpy.dtype` function understands, most notably
            as built-in type, as one of NumPy's internal datatype
            objects or as string.

            Check ``CUDA_DTYPES`` for a list of available data types.
        """

        if dtype not in _TYPE_MAP_NPY2CUDA.keys():
            raise TypeError('data type {!r} not supported in CUDA'
                            ''.format(dtype))

        super().__init__(size, dtype)

        self._vector_impl = _TYPE_MAP_NPY2CUDA[self._dtype]

    def element(self, inp=None, data_ptr=None):
        """Create a new element.

        Parameters
        ----------
        inp : array-like or scalar, optional
            Input to initialize the new element.

            If ``inp`` is a `numpy.ndarray` of shape ``(size,)``
            and the same data type as this space, the array is wrapped,
            not copied.
            Other array-like objects are copied (with broadcasting
            if necessary).

            If a single value is given, it is copied to all entries.

            If both ``inp`` and ``data_ptr`` are `None`, an empty<commit_msg>BUG: fix bad dtype check<commit_after>﻿# Copyright 2014, 2015 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL.  If not, see <http://www.gnu.org/licenses/>.

"""CUDA implementation of n-dimensional Cartesian spaces."""

# Imports for common Python 2/3 codebase
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import int, super

# External module imports
import numpy as np

# ODL imports
from odl.set.space import LinearSpace, LinearSpaceVector
from odl.space.base_ntuples import (NtuplesBase, NtuplesBaseVector,
                                    FnBase, FnBaseVector,
                                    FnWeightingBase)
from odl.util.utility import is_real_dtype, is_real_floating_dtype, dtype_repr
from odl.util.ufuncs import CudaNtuplesVectorUFuncs

try:
    import odlpp.odlpp_cuda as cuda
    CUDA_AVAILABLE = True
except ImportError:
    cuda = None
    CUDA_AVAILABLE = False

__all__ = ('CudaNtuples', 'CudaNtuplesVector',
           'CudaFn', 'CudaFnVector', 'CudaRn', 'CudaRnVector',
           'CUDA_DTYPES', 'CUDA_AVAILABLE',
           'CudaFnConstWeighting', 'CudaFnVectorWeighting',
           'cu_weighted_inner', 'cu_weighted_norm', 'cu_weighted_dist')


def _get_int_type():
    if np.dtype(np.int).itemsize == 4:
        return 'CudaVectorInt32'
    elif np.dtype(np.int).itemsize == 8:
        return 'CudaVectorInt64'
    else:
        return 'CudaVectorIntNOT_AVAILABLE'


def _add_if_exists(dtype, name):
    if hasattr(cuda, name):
        _TYPE_MAP_NPY2CUDA[np.dtype(dtype)] = getattr(cuda, name)
        CUDA_DTYPES.append(np.dtype(dtype))


# A list of all available dtypes
CUDA_DTYPES = []

# Typemap from numpy dtype to implementations
_TYPE_MAP_NPY2CUDA = {}

# Initialize the available dtypes
_add_if_exists(np.float, 'CudaVectorFloat64')
_add_if_exists(np.float32, 'CudaVectorFloat32')
_add_if_exists(np.float64, 'CudaVectorFloat64')
_add_if_exists(np.int, _get_int_type())
_add_if_exists(np.int8, 'CudaVectorInt8')
_add_if_exists(np.int16, 'CudaVectorInt16')
_add_if_exists(np.int32, 'CudaVectorInt32')
_add_if_exists(np.int64, 'CudaVectorInt64')
_add_if_exists(np.uint8, 'CudaVectorUInt8')
_add_if_exists(np.uint16, 'CudaVectorUInt16')
_add_if_exists(np.uint32, 'CudaVectorUInt32')
_add_if_exists(np.uint64, 'CudaVectorUInt64')
CUDA_DTYPES = list(set(CUDA_DTYPES))  # Remove duplicates


class CudaNtuples(NtuplesBase):
    """The space `NtuplesBase`, implemented in CUDA."""

    def __init__(self, size, dtype):
        """Initialize a new instance.

        Parameters
        ----------
        size : `int`
            The number entries per tuple
        dtype : `object`
            The data type for each tuple entry. Can be provided in any
            way the `numpy.dtype` function understands, most notably
            as built-in type, as one of NumPy's internal datatype
            objects or as string.

            Check ``CUDA_DTYPES`` for a list of available data types.
        """

        if np.dtype(dtype) not in _TYPE_MAP_NPY2CUDA.keys():
            raise TypeError('data type {!r} not supported in CUDA'
                            ''.format(dtype))

        super().__init__(size, dtype)

        self._vector_impl = _TYPE_MAP_NPY2CUDA[self._dtype]

    def element(self, inp=None, data_ptr=None):
        """Create a new element.

        Parameters
        ----------
        inp : array-like or scalar, optional
            Input to initialize the new element.

            If ``inp`` is a `numpy.ndarray` of shape ``(size,)``
            and the same data type as this space, the array is wrapped,
            not copied.
            Other array-like objects are copied (with broadcasting
            if necessary).

            If a single value is given, it is copied to all entries.

            If both ``inp`` and ``data_ptr`` are `None`, an empty
{'fraction_non_alphanumeric': 0.09058456046407853, 'fraction_numerical': 0.013163766175814369, 'mean_word_length': 3.0861440291704647, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1037800', 'n_tokens_mistral': 2901, 'n_tokens_neox': 2792, 'n_words': 853}