Esempio n. 1
0
 def test_intp(self):
     # Ticket #99
     i_width = np.int_(0).nbytes * 2 - 1
     np.intp('0x' + 'f' * i_width, 16)
     assert_raises(OverflowError, np.intp, '0x' + 'f' * (i_width + 1), 16)
     assert_raises(ValueError, np.intp, '0x1', 32)
     assert_equal(255, np.intp('0xFF', 16))
Esempio n. 2
0
    def test_array_richcompare_legacy_weirdness(self):
        # It doesn't really work to use assert_deprecated here, b/c part of
        # the point of assert_deprecated is to check that when warnings are
        # set to "error" mode then the error is propagated -- which is good!
        # But here we are testing a bunch of code that is deprecated *because*
        # it has the habit of swallowing up errors and converting them into
        # different warnings. So assert_warns will have to be sufficient.
        assert_warns(FutureWarning, lambda: np.arange(2) == "a")
        assert_warns(FutureWarning, lambda: np.arange(2) != "a")
        # No warning for scalar comparisons
        with warnings.catch_warnings():
            warnings.filterwarnings("error")
            assert_(not (np.array(0) == "a"))
            assert_(np.array(0) != "a")
            assert_(not (np.int16(0) == "a"))
            assert_(np.int16(0) != "a")

        for arg1 in [np.asarray(0), np.int16(0)]:
            struct = np.zeros(2, dtype="i4,i4")
            for arg2 in [struct, "a"]:
                for f in [operator.lt, operator.le, operator.gt, operator.ge]:
                    if sys.version_info[0] >= 3:
                        # py3
                        with warnings.catch_warnings() as l:
                            warnings.filterwarnings("always")
                            assert_raises(TypeError, f, arg1, arg2)
                            assert_(not l)
                    else:
                        # py2
                        assert_warns(DeprecationWarning, f, arg1, arg2)
Esempio n. 3
0
 def test_nan(self):
     # Test that nan is 'far' from small, tiny, inf, max and min
     for dt in [np.float32, np.float64]:
         if dt == np.float32:
             maxulp = 1e6
         else:
             maxulp = 1e12
         inf = np.array([np.inf]).astype(dt)
         nan = np.array([np.nan]).astype(dt)
         big = np.array([np.finfo(dt).max])
         tiny = np.array([np.finfo(dt).tiny])
         zero = np.array([np.PZERO]).astype(dt)
         nzero = np.array([np.NZERO]).astype(dt)
         assert_raises(
             AssertionError,
             lambda: assert_array_max_ulp(nan, inf, maxulp=maxulp))
         assert_raises(
             AssertionError,
             lambda: assert_array_max_ulp(nan, big, maxulp=maxulp))
         assert_raises(
             AssertionError,
             lambda: assert_array_max_ulp(nan, tiny, maxulp=maxulp))
         assert_raises(
             AssertionError,
             lambda: assert_array_max_ulp(nan, zero, maxulp=maxulp))
         assert_raises(
             AssertionError,
             lambda: assert_array_max_ulp(nan, nzero, maxulp=maxulp))
Esempio n. 4
0
    def test_datetime_memoryview(self):
        # gh-11656
        # Values verified with v1.13.3, shape is not () as in test_scalar_dim
        def as_dict(m):
            return dict(strides=m.strides,
                        shape=m.shape,
                        itemsize=m.itemsize,
                        ndim=m.ndim,
                        format=m.format)

        dt1 = np.datetime64('2016-01-01')
        dt2 = np.datetime64('2017-01-01')
        expected = {
            'strides': (1, ),
            'itemsize': 1,
            'ndim': 1,
            'shape': (8, ),
            'format': 'B'
        }
        v = memoryview(dt1)
        res = as_dict(v)
        assert_equal(res, expected)

        v = memoryview(dt2 - dt1)
        res = as_dict(v)
        assert_equal(res, expected)

        dt = np.dtype([('a', 'uint16'), ('b', 'M8[s]')])
        a = np.empty(1, dt)
        # Fails to create a PEP 3118 valid buffer
        assert_raises((ValueError, BufferError), memoryview, a[0])
Esempio n. 5
0
    def test_pad_too_many_axes(self):
        arr = np.arange(30).reshape(5, 6)

        # Attempt to pad using a 3D array equivalent
        bad_shape = (((3,), (4,), (5,)), ((0,), (1,), (2,)))
        assert_raises(ValueError, pad, arr, bad_shape,
                      mode='constant')
Esempio n. 6
0
 def test_extended_axis_invalid(self):
     d = np.ones((3, 5, 7, 11))
     assert_raises(np.AxisError, np.nanpercentile, d, q=5, axis=-5)
     assert_raises(np.AxisError, np.nanpercentile, d, q=5, axis=(0, -5))
     assert_raises(np.AxisError, np.nanpercentile, d, q=5, axis=4)
     assert_raises(np.AxisError, np.nanpercentile, d, q=5, axis=(0, 4))
     assert_raises(ValueError, np.nanpercentile, d, q=5, axis=(1, 1))
Esempio n. 7
0
 def test_dtype(self):
     dt = np.intc
     p = ndpointer(dtype=dt)
     assert_(p.from_param(np.array([1], dt)))
     dt = '<i4'
     p = ndpointer(dtype=dt)
     assert_(p.from_param(np.array([1], dt)))
     dt = np.dtype('>i4')
     p = ndpointer(dtype=dt)
     p.from_param(np.array([1], dt))
     assert_raises(TypeError, p.from_param,
                       np.array([1], dt.newbyteorder('swap')))
     dtnames = ['x', 'y']
     dtformats = [np.intc, np.float64]
     dtdescr = {'names': dtnames, 'formats': dtformats}
     dt = np.dtype(dtdescr)
     p = ndpointer(dtype=dt)
     assert_(p.from_param(np.zeros((10,), dt)))
     samedt = np.dtype(dtdescr)
     p = ndpointer(dtype=samedt)
     assert_(p.from_param(np.zeros((10,), dt)))
     dt2 = np.dtype(dtdescr, align=True)
     if dt.itemsize != dt2.itemsize:
         assert_raises(TypeError, p.from_param, np.zeros((10,), dt2))
     else:
         assert_(p.from_param(np.zeros((10,), dt2)))
Esempio n. 8
0
def test_iter_allocate_output_subtype():
    # Make sure that the subtype with priority wins
    # 2018-04-29: moved here from core.tests.test_nditer, given the
    # matrix specific shape test.

    # matrix vs ndarray
    a = np.matrix([[1, 2], [3, 4]])
    b = np.arange(4).reshape(2, 2).T
    i = np.nditer([a, b, None], [],
                  [['readonly'], ['readonly'], ['writeonly', 'allocate']])
    assert_(type(i.operands[2]) is np.matrix)
    assert_(type(i.operands[2]) is not np.ndarray)
    assert_equal(i.operands[2].shape, (2, 2))

    # matrix always wants things to be 2D
    b = np.arange(4).reshape(1, 2, 2)
    assert_raises(RuntimeError, np.nditer, [a, b, None], [],
                  [['readonly'], ['readonly'], ['writeonly', 'allocate']])
    # but if subtypes are disabled, the result can still work
    i = np.nditer([a, b, None], [],
                  [['readonly'], ['readonly'],
                   ['writeonly', 'allocate', 'no_subtype']])
    assert_(type(i.operands[2]) is np.ndarray)
    assert_(type(i.operands[2]) is not np.matrix)
    assert_equal(i.operands[2].shape, (1, 2, 2))
Esempio n. 9
0
    def test_opt_out(self):
        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like
Esempio n. 10
0
    def test_hermeder(self):
        # check exceptions
        assert_raises(ValueError, herme.hermeder, [0], .5)
        assert_raises(ValueError, herme.hermeder, [0], -1)

        # check that zeroth derivative does nothing
        for i in range(5):
            tgt = [0] * i + [1]
            res = herme.hermeder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # check that derivation is the inverse of integration
        for i in range(5):
            for j in range(2, 5):
                tgt = [0] * i + [1]
                res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # check derivation with scaling
        for i in range(5):
            for j in range(2, 5):
                tgt = [0] * i + [1]
                res = herme.hermeder(herme.hermeint(tgt, m=j, scl=2),
                                     m=j,
                                     scl=.5)
                assert_almost_equal(trim(res), trim(tgt))
Esempio n. 11
0
 def test_incorrect_methods(self):
     """
     Check a Value Error is thrown when an unknown string is passed in
     """
     check_list = ['mad', 'freeman', 'histograms', 'IQR']
     for estimator in check_list:
         assert_raises(ValueError, histogram, [1, 2, 3], estimator)
Esempio n. 12
0
    def test_seq_repeat(self):
        # Test that basic sequences get repeated when multiplied with
        # numpy integers. And errors are raised when multiplied with others.
        # Some of this behaviour may be controversial and could be open for
        # change.
        accepted_types = set(np.typecodes["AllInteger"])
        deprecated_types = set('?')
        forbidden_types = (set(np.typecodes["All"]) - accepted_types -
                           deprecated_types)
        forbidden_types -= set('V')  # can't default-construct void scalars

        for seq_type in (list, tuple):
            seq = seq_type([1, 2, 3])
            for numpy_type in accepted_types:
                i = np.dtype(numpy_type).type(2)
                assert_equal(seq * i, seq * int(i))
                assert_equal(i * seq, int(i) * seq)

            for numpy_type in deprecated_types:
                i = np.dtype(numpy_type).type()
                assert_equal(
                    assert_warns(DeprecationWarning, operator.mul, seq, i),
                    seq * int(i))
                assert_equal(
                    assert_warns(DeprecationWarning, operator.mul, i, seq),
                    int(i) * seq)

            for numpy_type in forbidden_types:
                i = np.dtype(numpy_type).type()
                assert_raises(TypeError, operator.mul, seq, i)
                assert_raises(TypeError, operator.mul, i, seq)
Esempio n. 13
0
 def test_inf(self):
     a = np.array([[1., 2.], [3., 4.]])
     b = a.copy()
     a[0, 0] = np.inf
     assert_raises(AssertionError, lambda: self._assert_func(a, b))
     b[0, 0] = -np.inf
     assert_raises(AssertionError, lambda: self._assert_func(a, b))
Esempio n. 14
0
 def test_basic(self):
     y = linspace(0, 10)
     assert_(len(y) == 50)
     y = linspace(2, 10, num=100)
     assert_(y[-1] == 10)
     y = linspace(2, 10, endpoint=0)
     assert_(y[-1] < 10)
     assert_raises(ValueError, linspace, 0, 10, num=-1)
Esempio n. 15
0
 def test_trimcoef(self):
     coef = [2, -1, 1, 0]
     # Test exceptions
     assert_raises(ValueError, pu.trimcoef, coef, -1)
     # Test results
     assert_equal(pu.trimcoef(coef), coef[:-1])
     assert_equal(pu.trimcoef(coef, 1), coef[:-3])
     assert_equal(pu.trimcoef(coef, 2), [0])
Esempio n. 16
0
 def test_basic(self):
     assert_raises(ValueError, fliplr, ones(4))
     a = get_mat(4)
     b = a[:, ::-1]
     assert_equal(fliplr(a), b)
     a = [[0, 1, 2], [3, 4, 5]]
     b = [[2, 1, 0], [5, 4, 3]]
     assert_equal(fliplr(a), b)
Esempio n. 17
0
 def test_int_from_infinite_longdouble___int__(self):
     x = np.longdouble(np.inf)
     assert_raises(OverflowError, x.__int__)
     with suppress_warnings() as sup:
         sup.record(np.ComplexWarning)
         x = np.clongdouble(np.inf)
         assert_raises(OverflowError, x.__int__)
         assert_equal(len(sup.log), 1)
Esempio n. 18
0
    def test_simple_arrays(self):
        x = np.array([1234.22])
        y = np.array([1234.23])

        self._assert_func(x, y, significant=5)
        self._assert_func(x, y, significant=6)
        assert_raises(AssertionError,
                      lambda: self._assert_func(x, y, significant=7))
Esempio n. 19
0
    def test_simple(self):
        x = np.array([1234.2222])
        y = np.array([1234.2223])

        self._assert_func(x, y, decimal=3)
        self._assert_func(x, y, decimal=4)
        assert_raises(AssertionError,
                      lambda: self._assert_func(x, y, decimal=5))
Esempio n. 20
0
 def test_no_postfix(self):
     assert_raises(ValueError,
                   join_by,
                   'a',
                   self.a,
                   self.b,
                   r1postfix='',
                   r2postfix='')
Esempio n. 21
0
 def test_InvalidHTTP(self):
     url = invalid_httpurl()
     assert_raises(IOError, self.ds.open, url)
     try:
         self.ds.open(url)
     except IOError as e:
         # Regression test for bug fixed in r4342.
         assert_(e.errno is None)
Esempio n. 22
0
 def test_empty(self):
     mat = np.zeros((0, 3))
     for f in self.nanfuncs:
         for axis in [0, None]:
             assert_raises(ValueError, f, mat, axis=axis)
         for axis in [1]:
             res = f(mat, axis=axis)
             assert_equal(res, np.zeros(0))
Esempio n. 23
0
    def test_basic(self):
        a = np.arange(10)

        assert_raises(IndexError, a.__getitem__, [0.5, 1.5])
        assert_raises(IndexError, a.__getitem__, (['1', '2'],))

        # The following is valid
        a.__getitem__([])
Esempio n. 24
0
    def test_non_integer_sequence_multiplication(self):
        # NumPy scalar sequence multiply should not work with non-integers
        def mult(a, b):
            return a * b

        assert_raises(TypeError, mult, [1], np.float_(3))
        # following should be OK
        mult([1], np.int_(3))
Esempio n. 25
0
def test_truncate(Poly):
    p = Poly([1, 2, 3])
    assert_raises(ValueError, p.truncate, .5)
    assert_raises(ValueError, p.truncate, 0)
    assert_equal(len(p.truncate(4)), 3)
    assert_equal(len(p.truncate(3)), 3)
    assert_equal(len(p.truncate(2)), 2)
    assert_equal(len(p.truncate(1)), 1)
Esempio n. 26
0
def test_cutdeg(Poly):
    p = Poly([1, 2, 3])
    assert_raises(ValueError, p.cutdeg, .5)
    assert_raises(ValueError, p.cutdeg, -1)
    assert_equal(len(p.cutdeg(3)), 3)
    assert_equal(len(p.cutdeg(2)), 3)
    assert_equal(len(p.cutdeg(1)), 2)
    assert_equal(len(p.cutdeg(0)), 1)
Esempio n. 27
0
def test_to_64():
    with exc_iter(INT128_VALUES) as it:
        for a, in it:
            if not (INT64_MIN <= a <= INT64_MAX):
                assert_raises(OverflowError, mt.extint_to_64, a)
            else:
                b = mt.extint_to_64(a)
                if a != b:
                    assert_equal(b, a)
Esempio n. 28
0
    def test_constant_both(self):
        # non-contiguous should raise error
        x = np.arange(6, dtype=np.float64)[::2]
        assert_raises(ValueError, self.module.foo, x)

        # check values with contiguous array
        x = np.arange(3, dtype=np.float64)
        self.module.foo(x)
        assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
Esempio n. 29
0
 def test_ndim(self):
     p = ndpointer(ndim=0)
     assert_(p.from_param(np.array(1)))
     assert_raises(TypeError, p.from_param, np.array([1]))
     p = ndpointer(ndim=1)
     assert_raises(TypeError, p.from_param, np.array(1))
     assert_(p.from_param(np.array([1])))
     p = ndpointer(ndim=2)
     assert_(p.from_param(np.array([[1]])))
Esempio n. 30
0
 def test_flags(self):
     x = np.array([[1, 2], [3, 4]], order='F')
     p = ndpointer(flags='FORTRAN')
     assert_(p.from_param(x))
     p = ndpointer(flags='CONTIGUOUS')
     assert_raises(TypeError, p.from_param, x)
     p = ndpointer(flags=x.flags.num)
     assert_(p.from_param(x))
     assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))