Python numpy.sctypes() Examples

The following are 30 code examples for showing how to use numpy.sctypes(). 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: me-ica   Author: ME-ICA   File: test_casting.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_able_casting():
    # Check the able_int_type function guesses numpy out type
    types = np.sctypes['int'] + np.sctypes['uint']
    for in_type in types:
        in_info = np.iinfo(in_type)
        in_mn, in_mx = in_info.min, in_info.max
        A = np.zeros((1,), dtype=in_type)
        for out_type in types:
            out_info = np.iinfo(out_type)
            out_mn, out_mx = out_info.min, out_info.max
            B = np.zeros((1,), dtype=out_type)
            ApBt = (A + B).dtype.type
            able_type = able_int_type([in_mn, in_mx, out_mn, out_mx])
            if able_type is None:
                assert_equal(ApBt, np.float64)
                continue
            # Use str for comparison to avoid int32/64 vs intp comparison
            # failures
            assert_equal(np.dtype(ApBt).str, np.dtype(able_type).str) 
Example 2
Project: me-ica   Author: ME-ICA   File: test_scaling.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_scaling_in_abstract():
    # Confirm that, for all ints and uints as input, and all possible outputs,
    # for any simple way of doing the calculation, the result is near enough
    for category0, category1 in (('int', 'int'),
                                 ('uint', 'int'),
                                ):
        for in_type in np.sctypes[category0]:
            for out_type in np.sctypes[category1]:
                check_int_a2f(in_type, out_type)
    # Converting floats to integer
    for category0, category1 in (('float', 'int'),
                                 ('float', 'uint'),
                                 ('complex', 'int'),
                                 ('complex', 'uint'),
                                ):
        for in_type in np.sctypes[category0]:
            for out_type in np.sctypes[category1]:
                check_int_a2f(in_type, out_type) 
Example 3
Project: me-ica   Author: ME-ICA   File: test_utils.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_better_float():
    # Better float function
    def check_against(f1, f2):
        return f1 if FLOAT_TYPES.index(f1) >= FLOAT_TYPES.index(f2) else f2
    for first in FLOAT_TYPES:
        for other in IUINT_TYPES + np.sctypes['complex']:
            assert_equal(better_float_of(first, other), first)
            assert_equal(better_float_of(other, first), first)
            for other2 in IUINT_TYPES + np.sctypes['complex']:
                assert_equal(better_float_of(other, other2), np.float32)
                assert_equal(better_float_of(other, other2, np.float64),
                             np.float64)
        for second in FLOAT_TYPES:
            assert_equal(better_float_of(first, second),
                         check_against(first, second))
    # Check codes and dtypes work
    assert_equal(better_float_of('f4', 'f8', 'f4'), np.float64)
    assert_equal(better_float_of('i4', 'i8', 'f8'), np.float64) 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
Project: coffeegrindsize   Author: jgagneastro   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: me-ica   Author: ME-ICA   File: casting.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def ok_floats():
    """ Return floating point types sorted by precision

    Remove longdouble if it has no higher precision than float64
    """
    floats = sorted(np.sctypes['float'], key=lambda f : type_info(f)['nmant'])
    if best_float() != np.longdouble and np.longdouble in floats:
        floats.remove(np.longdouble)
    return floats 
Example 12
Project: me-ica   Author: ME-ICA   File: casting.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def able_int_type(values):
    """ Find the smallest integer numpy type to contain sequence `values`

    Prefers uint to int if minimum is >= 0

    Parameters
    ----------
    values : sequence
        sequence of integer values

    Returns
    -------
    itype : None or numpy type
        numpy integer type or None if no integer type holds all `values`

    Examples
    --------
    >>> able_int_type([0, 1]) == np.uint8
    True
    >>> able_int_type([-1, 1]) == np.int8
    True
    """
    if any([v % 1 for v in values]):
        return None
    mn = min(values)
    mx = max(values)
    if mn >= 0:
        for ityp in np.sctypes['uint']:
            if mx <= np.iinfo(ityp).max:
                return ityp
    for ityp in np.sctypes['int']:
        info = np.iinfo(ityp)
        if mn >= info.min and mx <= info.max:
            return ityp
    return None 
Example 13
Project: me-ica   Author: ME-ICA   File: test_round_trip.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_round_trip():
    scaling_type = np.float32
    rng = np.random.RandomState(20111121)
    N = 10000
    sd_10s = range(-20, 51, 5)
    iuint_types = np.sctypes['int'] + np.sctypes['uint']
    # Remove intp types, which cannot be set into nifti header datatype
    iuint_types.remove(np.intp)
    iuint_types.remove(np.uintp)
    f_types = [np.float32, np.float64]
    # Expanding standard deviations
    for i, sd_10 in enumerate(sd_10s):
        sd = 10.0**sd_10
        V_in = rng.normal(0, sd, size=(N,1))
        for j, in_type in enumerate(f_types):
            for k, out_type in enumerate(iuint_types):
                check_arr(sd_10, V_in, in_type, out_type, scaling_type)
    # Spread integers across range
    for i, sd in enumerate(np.linspace(0.05, 0.5, 5)):
        for j, in_type in enumerate(iuint_types):
            info = np.iinfo(in_type)
            mn, mx = info.min, info.max
            type_range = mx - mn
            center = type_range / 2.0 + mn
            # float(sd) because type_range can be type 'long'
            width = type_range * float(sd)
            V_in = rng.normal(center, width, size=(N,1))
            for k, out_type in enumerate(iuint_types):
                check_arr(sd, V_in, in_type, out_type, scaling_type) 
Example 14
Project: me-ica   Author: ME-ICA   File: test_scaling.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def check_int_a2f(in_type, out_type):
    # Check that array to / from file returns roughly the same as input
    big_floater = np.maximum_sctype(np.float)
    info = type_info(in_type)
    this_min, this_max = info['min'], info['max']
    if not in_type in np.sctypes['complex']:
        data = np.array([this_min, this_max], in_type)
        # Bug in numpy 1.6.2 on PPC leading to infs - abort
        if not np.all(np.isfinite(data)):
            if DEBUG:
                print 'Hit PPC max -> inf bug; skip in_type %s' % in_type
            return
    else: # Funny behavior with complex256
        data = np.zeros((2,), in_type)
        data[0] = this_min + 0j
        data[1] = this_max + 0j
    str_io = BytesIO()
    try:
        scale, inter, mn, mx = calculate_scale(data, out_type, True)
    except ValueError:
        if DEBUG:
            print in_type, out_type, sys.exc_info()[1]
        return
    array_to_file(data, str_io, out_type, 0, inter, scale, mn, mx)
    data_back = array_from_file(data.shape, out_type, str_io)
    data_back = apply_read_scaling(data_back, scale, inter)
    assert_true(np.allclose(big_floater(data), big_floater(data_back)))
    # Try with analyze-size scale and inter
    scale32 = np.float32(scale)
    inter32 = np.float32(inter)
    if scale32 == np.inf or inter32 == np.inf:
        return
    data_back = array_from_file(data.shape, out_type, str_io)
    data_back = apply_read_scaling(data_back, scale32, inter32)
    # Clip at extremes to remove inf
    info = type_info(in_type)
    out_min, out_max = info['min'], info['max']
    assert_true(np.allclose(big_floater(data),
                            big_floater(np.clip(data_back, out_min, out_max)))) 
Example 15
Project: me-ica   Author: ME-ICA   File: test_floating.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_as_int_np_fix():
    # Test as_int works for integers.  We need as_int for integers because of a
    # numpy 1.4.1 bug such that int(np.uint32(2**32-1) == -1
    for t in np.sctypes['int'] + np.sctypes['uint']:
        info = np.iinfo(t)
        mn, mx = np.array([info.min, info.max], dtype=t)
        assert_equal((mn, mx), (as_int(mn), as_int(mx))) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}
        # void, bytes, str
        variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}
        self.dtypes = sorted(dtypes - variable_sized |
                             {np.dtype(tp.str.replace("0", str(i)))
                              for tp in variable_sized for i in range(1, 10)},
                             key=lambda dtype: dtype.str)
        self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}
        self.ndims = 10 
Example 17
Project: recruit   Author: Frank-qlu   File: test_getlimits.py    License: Apache License 2.0 5 votes vote down vote up
def test_unsigned_max(self):
        types = np.sctypes['uint']
        for T in types:
            assert_equal(iinfo(T).max, T(-1)) 
Example 18
Project: recruit   Author: Frank-qlu   File: test_getlimits.py    License: Apache License 2.0 5 votes vote down vote up
def test_plausible_finfo():
    # Assert that finfo returns reasonable results for all types
    for ftype in np.sctypes['float'] + np.sctypes['complex']:
        info = np.finfo(ftype)
        assert_(info.nmant > 1)
        assert_(info.minexp < -1)
        assert_(info.maxexp > 1) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_nextafter_0():
    for t, direction in itertools.product(np.sctypes['float'], (1, -1)):
        tiny = np.finfo(t).tiny
        assert_(0. < direction * np.nextafter(t(0), t(direction)) < tiny)
        assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0) 
Example 20
Project: recruit   Author: Frank-qlu   File: test_numerictypes.py    License: Apache License 2.0 5 votes vote down vote up
def test_uint(self, t):
        assert_equal(np.maximum_sctype(t), np.sctypes['uint'][-1]) 
Example 21
Project: recruit   Author: Frank-qlu   File: test_numerictypes.py    License: Apache License 2.0 5 votes vote down vote up
def test_float(self, t):
        assert_equal(np.maximum_sctype(t), np.sctypes['float'][-1]) 
Example 22
Project: recruit   Author: Frank-qlu   File: test_numerictypes.py    License: Apache License 2.0 5 votes vote down vote up
def test_complex(self, t):
        assert_equal(np.maximum_sctype(t), np.sctypes['complex'][-1]) 
Example 23
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_getlimits.py    License: MIT License 5 votes vote down vote up
def test_unsigned_max(self):
        types = np.sctypes['uint']
        for T in types:
            assert_equal(iinfo(T).max, T(-1)) 
Example 24
Project: vnpy_crypto   Author: birforce   File: test_numeric.py    License: MIT License 5 votes vote down vote up
def setup(self):
        dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}
        # void, bytes, str
        variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}
        self.dtypes = sorted(dtypes - variable_sized |
                             {np.dtype(tp.str.replace("0", str(i)))
                              for tp in variable_sized for i in range(1, 10)},
                             key=lambda dtype: dtype.str)
        self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}
        self.ndims = 10 
Example 25
Project: vnpy_crypto   Author: birforce   File: test_getlimits.py    License: MIT License 5 votes vote down vote up
def test_unsigned_max(self):
        types = np.sctypes['uint']
        for T in types:
            assert_equal(iinfo(T).max, T(-1)) 
Example 26
Project: vnpy_crypto   Author: birforce   File: test_getlimits.py    License: MIT License 5 votes vote down vote up
def test_plausible_finfo():
    # Assert that finfo returns reasonable results for all types
    for ftype in np.sctypes['float'] + np.sctypes['complex']:
        info = np.finfo(ftype)
        assert_(info.nmant > 1)
        assert_(info.minexp < -1)
        assert_(info.maxexp > 1) 
Example 27
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_nextafter_0():
    for t, direction in itertools.product(np.sctypes['float'], (1, -1)):
        tiny = np.finfo(t).tiny
        assert_(0. < direction * np.nextafter(t(0), t(direction)) < tiny)
        assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0) 
Example 28
Project: Computable   Author: ktraunmueller   File: test_multiarray.py    License: MIT License 5 votes vote down vote up
def _clip_type(self,type_group,array_max,
                   clip_min,clip_max,inplace=False,
                   expected_min=None,expected_max=None):
        if expected_min is None:
            expected_min = clip_min
        if expected_max is None:
            expected_max = clip_max

        for T in np.sctypes[type_group]:
            if sys.byteorder == 'little':
                byte_orders = ['=', '>']
            else:
                byte_orders = ['<', '=']

            for byteorder in byte_orders:
                dtype = np.dtype(T).newbyteorder(byteorder)

                x = (np.random.random(1000) * array_max).astype(dtype)
                if inplace:
                    x.clip(clip_min, clip_max, x)
                else:
                    x = x.clip(clip_min, clip_max)
                    byteorder = '='

                if x.dtype.byteorder == '|': byteorder = '|'
                assert_equal(x.dtype.byteorder, byteorder)
                self._check_range(x, expected_min, expected_max)
        return x 
Example 29
Project: Computable   Author: ktraunmueller   File: test_multiarray.py    License: MIT License 5 votes vote down vote up
def test_ip_types(self):
        unchecked_types = [str, unicode, np.void, object]

        x = np.random.random(1000)*100
        mask = x < 40

        for val in [-100, 0, 15]:
            for types in np.sctypes.values():
                for T in types:
                    if T not in unchecked_types:
                        yield self.tst_basic, x.copy().astype(T), T, mask, val 
Example 30
Project: Computable   Author: ktraunmueller   File: test_multiarray.py    License: MIT License 5 votes vote down vote up
def test_ip_types(self):
        unchecked_types = [str, unicode, np.void, object]

        x = np.random.random(24)*100
        x.shape = 2, 3, 4
        for types in np.sctypes.values():
            for T in types:
                if T not in unchecked_types:
                    yield self.tst_basic, x.copy().astype(T)