Python numpy.can_cast() Examples

The following are 30 code examples for showing how to use numpy.can_cast(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: astropy-healpix   Author: astropy   File: test_core.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_lonlat_to_healpix_shape():
    healpix_index = lonlat_to_healpix(2 * u.deg, 3 * u.deg, 8)
    assert np.can_cast(healpix_index, np.int64)

    lon, lat = np.ones((2, 4)) * u.deg, np.zeros((2, 4)) * u.deg
    healpix_index = lonlat_to_healpix(lon, lat, 8)
    assert healpix_index.shape == (2, 4)

    healpix_index, dx, dy = lonlat_to_healpix(2 * u.deg, 3 * u.deg, 8, return_offsets=True)
    assert np.can_cast(healpix_index, np.int64)
    assert isinstance(dx, float)
    assert isinstance(dy, float)

    lon, lat = np.ones((2, 4)) * u.deg, np.zeros((2, 4)) * u.deg
    healpix_index, dx, dy = lonlat_to_healpix(lon, lat, 8, return_offsets=True)
    assert healpix_index.shape == (2, 4)
    assert dx.shape == (2, 4)
    assert dy.shape == (2, 4) 
Example 2
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 6 votes vote down vote up
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))


# Custom exception class to test exception propagation in fromiter 
Example 3
Project: mars   Author: mars-project   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def check_out_param(out, t, casting):
    from .base import broadcast_to

    if not hasattr(out, 'shape'):
        raise TypeError('return arrays must be a tensor')

    try:
        broadcast_to(t, out.shape)
    except ValueError:
        raise ValueError("operands could not be broadcast together "
                         "with shapes ({0}) ({1})".format(','.join(str(s) for s in t.shape),
                                                          ','.join(str(s) for s in out.shape)))

    if not np.can_cast(t.dtype, out.dtype, casting):
        raise TypeError("output (typecode '{0}') could not be coerced "
                        "to provided output paramter (typecode '{1}') "
                        "according to the casting rule ''{2}''".format(t.dtype.char, out.dtype.char, casting)) 
Example 4
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 6 votes vote down vote up
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))
            

# Custom exception class to test exception propagation in fromiter 
Example 5
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 6 votes vote down vote up
def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8 and
            not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
            (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None 
Example 6
Project: Computable   Author: ktraunmueller   File: test_base.py    License: MIT License 6 votes vote down vote up
def _can_cast_samekind(dtype1, dtype2):
    """Compatibility function for numpy 1.5.1; `casting` kw is numpy >=1.6.x

    default for casting kw is 'safe', which gives the same result as in 1.5.x
    and a strict subset of 'same_kind'.  So for 1.5.x we just skip the cases
    where 'safe' is False and 'same_kind' True.
    """
    if np.__version__[:3] == '1.5':
        return np.can_cast(dtype1, dtype2)
    else:
        return np.can_cast(dtype1, dtype2, casting='same_kind')


#------------------------------------------------------------------------------
# Generic tests
#------------------------------------------------------------------------------

# TODO check that spmatrix( ... , copy=X ) is respected
# TODO test prune
# TODO test has_sorted_indices 
Example 7
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_numeric.py    License: MIT License 6 votes vote down vote up
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))


# Custom exception class to test exception propagation in fromiter 
Example 8
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: image.py    License: MIT License 6 votes vote down vote up
def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8 and
            not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
            (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None 
Example 9
Project: neural-network-animation   Author: miloharper   File: image.py    License: MIT License 6 votes vote down vote up
def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8 and
            not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
            (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None 
Example 10
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_numeric.py    License: MIT License 6 votes vote down vote up
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))


# Custom exception class to test exception propagation in fromiter 
Example 11
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_base.py    License: MIT License 6 votes vote down vote up
def test_imul_scalar(self):
        def check(dtype):
            dat = self.dat_dtypes[dtype]
            datsp = self.datsp_dtypes[dtype]

            # Avoid implicit casting.
            if np.can_cast(type(2), dtype, casting='same_kind'):
                a = datsp.copy()
                a *= 2
                b = dat.copy()
                b *= 2
                assert_array_equal(b, a.todense())

            if np.can_cast(type(17.3), dtype, casting='same_kind'):
                a = datsp.copy()
                a *= 17.3
                b = dat.copy()
                b *= 17.3
                assert_array_equal(b, a.todense())

        for dtype in self.math_dtypes:
            check(dtype) 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_base.py    License: MIT License 6 votes vote down vote up
def test_idiv_scalar(self):
        def check(dtype):
            dat = self.dat_dtypes[dtype]
            datsp = self.datsp_dtypes[dtype]

            if np.can_cast(type(2), dtype, casting='same_kind'):
                a = datsp.copy()
                a /= 2
                b = dat.copy()
                b /= 2
                assert_array_equal(b, a.todense())

            if np.can_cast(type(17.3), dtype, casting='same_kind'):
                a = datsp.copy()
                a /= 17.3
                b = dat.copy()
                b /= 17.3
                assert_array_equal(b, a.todense())

        for dtype in self.math_dtypes:
            # /= should only be used with float dtypes to avoid implicit
            # casting.
            if not np.can_cast(dtype, np.int_):
                check(dtype) 
Example 13
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))


# Custom exception class to test exception propagation in fromiter 
Example 14
Project: nelpy   Author: nelpy   File: utils.py    License: MIT License 6 votes vote down vote up
def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """

        self._full_res = A
        self._A = A

        if (self._A.dtype != np.uint8 and
                not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
                (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None
        self._sx, self._sy = None, None 
Example 15
Project: pySINDy   Author: luckystarufo   File: test_numeric.py    License: MIT License 6 votes vote down vote up
def test_can_cast_values(self):
        # gh-5917
        for dt in np.sctypes['int'] + np.sctypes['uint']:
            ii = np.iinfo(dt)
            assert_(np.can_cast(ii.min, dt))
            assert_(np.can_cast(ii.max, dt))
            assert_(not np.can_cast(ii.min - 1, dt))
            assert_(not np.can_cast(ii.max + 1, dt))

        for dt in np.sctypes['float']:
            fi = np.finfo(dt)
            assert_(np.can_cast(fi.min, dt))
            assert_(np.can_cast(fi.max, dt))


# Custom exception class to test exception propagation in fromiter 
Example 16
Project: ImageFusion   Author: pfchai   File: image.py    License: MIT License 6 votes vote down vote up
def set_data(self, A):
        """
        Set the image array

        ACCEPTS: numpy/PIL Image A
        """
        # check if data is PIL Image without importing Image
        if hasattr(A, 'getpixel'):
            self._A = pil_to_array(A)
        else:
            self._A = cbook.safe_masked_invalid(A)

        if (self._A.dtype != np.uint8 and
            not np.can_cast(self._A.dtype, np.float)):
            raise TypeError("Image data can not convert to float")

        if (self._A.ndim not in (2, 3) or
            (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))):
            raise TypeError("Invalid dimensions for image data")

        self._imcache = None
        self._rgbacache = None
        self._oldxslice = None
        self._oldyslice = None 
Example 17
Project: arctic   Author: man-group   File: tickstore.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _pad_and_fix_dtypes(self, cols, column_dtypes):
        # Pad out Nones with empty arrays of appropriate dtypes
        rtn = {}
        index = cols[INDEX]
        full_length = len(index)
        for k, v in iteritems(cols):
            if k != INDEX and k != 'SYMBOL':
                col_len = len(v)
                if col_len < full_length:
                    v = ([None, ] * (full_length - col_len)) + v
                    assert len(v) == full_length
                for i, arr in enumerate(v):
                    if arr is None:
                        #  Replace Nones with appropriate-length empty arrays
                        v[i] = self._empty(len(index[i]), column_dtypes.get(k))
                    else:
                        # Promote to appropriate dtype only if we can safely cast all the values
                        # This avoids the case with strings where None is cast as 'None'.
                        # Casting the object to a string is not worthwhile anyway as Pandas changes the
                        # dtype back to objectS
                        if (i == 0 or v[i].dtype != v[i - 1].dtype) and np.can_cast(v[i].dtype, column_dtypes[k],
                                                                                    casting='safe'):
                            v[i] = v[i].astype(column_dtypes[k], casting='safe')

            rtn[k] = v
        return rtn 
Example 18
Project: astropy-healpix   Author: astropy   File: test_core.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nested_ring_shape(function):
    index = function(1, 8)
    assert np.can_cast(index, np.int64)

    index = function([[1, 2, 3], [2, 3, 4]], 8)
    assert index.shape == (2, 3) 
Example 19
Project: astropy-healpix   Author: astropy   File: test_healpy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ang2pix_shape():
    ipix = hp_compat.ang2pix(8, 1., 2.)
    assert np.can_cast(ipix, np.int64)

    ipix = hp_compat.ang2pix(8, [[1., 2.], [3., 4.]], [[1., 2.], [3., 4.]])
    assert ipix.shape == (2, 2) 
Example 20
Project: astropy-healpix   Author: astropy   File: test_healpy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_vec2pix_shape():
    ipix = hp_compat.vec2pix(8, 1., 2., 3.)
    assert np.can_cast(ipix, np.int64)

    ipix = hp_compat.vec2pix(8, [[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]])
    assert ipix.shape == (2, 2) 
Example 21
Project: recruit   Author: Frank-qlu   File: print_coercion_tables.py    License: Apache License 2.0 5 votes vote down vote up
def print_cancast_table(ntypes):
    print('X', end=' ')
    for char in ntypes:
        print(char, end=' ')
    print()
    for row in ntypes:
        print(row, end=' ')
        for col in ntypes:
            print(int(np.can_cast(row, col)), end=' ')
        print() 
Example 22
Project: recruit   Author: Frank-qlu   File: blocks.py    License: Apache License 2.0 5 votes vote down vote up
def replace(self, to_replace, value, inplace=False, filter=None,
                regex=False, convert=True):
        inplace = validate_bool_kwarg(inplace, 'inplace')
        to_replace_values = np.atleast_1d(to_replace)
        if not np.can_cast(to_replace_values, bool):
            return self
        return super(BoolBlock, self).replace(to_replace, value,
                                              inplace=inplace, filter=filter,
                                              regex=regex, convert=convert) 
Example 23
Project: mars   Author: mars-project   File: copyto.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, *inputs):
        from ..core import Tensor

        src, dst, where = self._extract_inputs(inputs)

        if not isinstance(dst, Tensor):
            raise TypeError('dst has to be a Tensor')

        self._dtype = dst.dtype
        self._gpu = dst.op.gpu
        self._sparse = dst.issparse()

        if not np.can_cast(src.dtype, dst.dtype, casting=self.casting):
            raise TypeError('Cannot cast array from {0!r} to {1!r} '
                            'according to the rule {2!s}'.format(
                                src.dtype, dst.dtype, self.casting))

        try:
            broadcast_to(src, dst.shape)
        except ValueError:
            raise ValueError('could not broadcast input array '
                             'from shape {0!r} into shape {1!r}'.format(src.shape, dst.shape))
        if where:
            try:
                broadcast_to(where, dst.shape)
            except ValueError:
                raise ValueError('could not broadcast where mask '
                                 'from shape {0!r} into shape {1!r}'.format(src.shape, dst.shape))

        inps = [src, dst]
        if where is not None:
            inps.append(where)
        ret = self.new_tensor(inps, dst.shape, order=dst.order)
        dst.data = ret.data 
Example 24
Project: mars   Author: mars-project   File: core.py    License: Apache License 2.0 5 votes vote down vote up
def assert_dtype_consistent(expected_dtype, real_dtype):
        if isinstance(real_dtype, pd.DatetimeTZDtype):
            real_dtype = real_dtype.base
        if expected_dtype != real_dtype:
            if expected_dtype == np.dtype('O') and real_dtype.type is np.str_:
                # real dtype is string, this matches expectation
                return
            if expected_dtype is None:
                raise AssertionError('Expected dtype cannot be None')
            if not np.can_cast(real_dtype, expected_dtype) and not np.can_cast(expected_dtype, real_dtype):
                raise AssertionError('cannot cast between dtype of real dtype %r and dtype %r defined in metadata'
                                     % (real_dtype, expected_dtype)) 
Example 25
Project: lambda-packs   Author: ryfeus   File: print_coercion_tables.py    License: MIT License 5 votes vote down vote up
def print_cancast_table(ntypes):
    print('X', end=' ')
    for char in ntypes:
        print(char, end=' ')
    print()
    for row in ntypes:
        print(row, end=' ')
        for col in ntypes:
            print(int(np.can_cast(row, col)), end=' ')
        print() 
Example 26
Project: lambda-packs   Author: ryfeus   File: sputils.py    License: MIT License 5 votes vote down vote up
def upcast(*args):
    """Returns the nearest supported sparse dtype for the
    combination of one or more types.

    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype

    Examples
    --------

    >>> upcast('int32')
    <type 'numpy.int32'>
    >>> upcast('bool')
    <type 'numpy.bool_'>
    >>> upcast('int32','float32')
    <type 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <type 'numpy.complex128'>

    """

    t = _upcast_memo.get(hash(args))
    if t is not None:
        return t

    upcast = np.find_common_type(args, [])

    for t in supported_dtypes:
        if np.can_cast(upcast, t):
            _upcast_memo[hash(args)] = t
            return t

    raise TypeError('no supported conversion for types: %r' % (args,)) 
Example 27
Project: lambda-packs   Author: ryfeus   File: sputils.py    License: MIT License 5 votes vote down vote up
def get_sum_dtype(dtype):
    """Mimic numpy's casting for np.sum"""
    if np.issubdtype(dtype, np.float_):
        return np.float_
    if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
        return np.uint
    if np.can_cast(dtype, np.int_):
        return np.int_
    return dtype 
Example 28
Project: lambda-packs   Author: ryfeus   File: interpolate.py    License: MIT License 5 votes vote down vote up
def __init__(self, points, values, method="linear", bounds_error=True,
                 fill_value=np.nan):
        if method not in ["linear", "nearest"]:
            raise ValueError("Method '%s' is not defined" % method)
        self.method = method
        self.bounds_error = bounds_error

        if not hasattr(values, 'ndim'):
            # allow reasonable duck-typed values
            values = np.asarray(values)

        if len(points) > values.ndim:
            raise ValueError("There are %d point arrays, but values has %d "
                             "dimensions" % (len(points), values.ndim))

        if hasattr(values, 'dtype') and hasattr(values, 'astype'):
            if not np.issubdtype(values.dtype, np.inexact):
                values = values.astype(float)

        self.fill_value = fill_value
        if fill_value is not None:
            fill_value_dtype = np.asarray(fill_value).dtype
            if (hasattr(values, 'dtype') and not
                    np.can_cast(fill_value_dtype, values.dtype,
                                casting='same_kind')):
                raise ValueError("fill_value must be either 'None' or "
                                 "of a type compatible with values")

        for i, p in enumerate(points):
            if not np.all(np.diff(p) > 0.):
                raise ValueError("The points in dimension %d must be strictly "
                                 "ascending" % i)
            if not np.asarray(p).ndim == 1:
                raise ValueError("The points in dimension %d must be "
                                 "1-dimensional" % i)
            if not values.shape[i] == len(p):
                raise ValueError("There are %d points and %d values in "
                                 "dimension %d" % (len(p), values.shape[i], i))
        self.grid = tuple([np.asarray(p) for p in points])
        self.values = values 
Example 29
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: print_coercion_tables.py    License: MIT License 5 votes vote down vote up
def print_cancast_table(ntypes):
    print('X', end=' ')
    for char in ntypes:
        print(char, end=' ')
    print()
    for row in ntypes:
        print(row, end=' ')
        for col in ntypes:
            print(int(np.can_cast(row, col)), end=' ')
        print() 
Example 30
Project: D-VAE   Author: muhanzhang   File: subtensor.py    License: MIT License 5 votes vote down vote up
def perform(self, node, inp, out_):
        x, i = inp
        out, = out_
        # Copy always implied by numpy advanced indexing semantic.
        if out[0] is not None and out[0].shape == (len(i),) + x.shape[1:]:
            o = out[0]
        else:
            o = None

        # If i.dtype is more precise than numpy.intp (int32 on 32-bit machines,
        # int64 on 64-bit machines), numpy may raise the following error:
        # TypeError: array cannot be safely cast to required type.
        # We need to check if values in i can fit in numpy.intp, because
        # if they don't, that should be an error (no array can have that
        # many elements on a 32-bit arch).
        if i.dtype != numpy.intp:
            i_ = theano._asarray(i, dtype=numpy.intp)
            if not numpy.can_cast(i.dtype, numpy.intp):
                # Check if there was actually an incorrect conversion
                if numpy.any(i != i_):
                    raise IndexError(
                        'index contains values that are bigger '
                        'than the maximum array size on this system.', i)
            i = i_

        out[0] = x.take(i, axis=0, out=o)