Example #1
0
    def test_exceptions(self):
        # test axis must be in bounds
        for ndim in [1, 2, 3]:
            a = np.ones((1,)*ndim)
            np.concatenate((a, a), axis=0)  # OK
            assert_raises(np.AxisError, np.concatenate, (a, a), axis=ndim)
            assert_raises(np.AxisError, np.concatenate, (a, a), axis=-(ndim + 1))

        # Scalars cannot be concatenated
        assert_raises(ValueError, concatenate, (0,))
        assert_raises(ValueError, concatenate, (np.array(0),))

        # test shapes must match except for concatenation axis
        a = np.ones((1, 2, 3))
        b = np.ones((2, 2, 3))
        axis = list(range(3))
        for i in range(3):
            np.concatenate((a, b), axis=axis[0])  # OK
            assert_raises(ValueError, np.concatenate, (a, b), axis=axis[1])
            assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2])
            a = np.moveaxis(a, -1, 0)
            b = np.moveaxis(b, -1, 0)
            axis.append(axis.pop(0))

        # No arrays to concatenate raises ValueError
        assert_raises(ValueError, concatenate, ())
Example #2
0
    def test_multiple_percentiles(self):
        perc = [50, 100]
        mat = np.ones((4, 3))
        nan_mat = np.nan * mat
        # For checking consistency in higher dimensional case
        large_mat = np.ones((3, 4, 5))
        large_mat[:, 0:2:4, :] = 0
        large_mat[:, :, 3:] *= 2
        for axis in [None, 0, 1]:
            for keepdim in [False, True]:
                with suppress_warnings() as sup:
                    sup.filter(RuntimeWarning, "All-NaN slice encountered")
                    val = np.percentile(mat, perc, axis=axis, keepdims=keepdim)
                    nan_val = np.nanpercentile(nan_mat, perc, axis=axis,
                                               keepdims=keepdim)
                    assert_equal(nan_val.shape, val.shape)

                    val = np.percentile(large_mat, perc, axis=axis,
                                        keepdims=keepdim)
                    nan_val = np.nanpercentile(large_mat, perc, axis=axis,
                                               keepdims=keepdim)
                    assert_equal(nan_val, val)

        megamat = np.ones((3, 4, 5, 6))
        assert_equal(np.nanpercentile(megamat, perc, axis=(1, 2)).shape, (2, 3, 6))
Example #3
0
    def test_empty(self):
        """ Test everything is ok with empty results, even with inserted dims """
        a = np.ones((3, 4, 5))
        ai = np.ones((3, 0, 5), dtype=np.intp)

        actual = take_along_axis(a, ai, axis=1)
        assert_equal(actual.shape, ai.shape)
Example #4
0
    def test_weights(self):
        v = np.random.rand(100)
        w = np.ones(100) * 5
        a, b = histogram(v)
        na, nb = histogram(v, density=True)
        wa, wb = histogram(v, weights=w)
        nwa, nwb = histogram(v, weights=w, density=True)
        assert_array_almost_equal(a * 5, wa)
        assert_array_almost_equal(na, nwa)

        # Check weights are properly applied.
        v = np.linspace(0, 10, 10)
        w = np.concatenate((np.zeros(5), np.ones(5)))
        wa, wb = histogram(v, bins=np.arange(11), weights=w)
        assert_array_almost_equal(wa, w)

        # Check with integer weights
        wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1])
        assert_array_equal(wa, [4, 5, 0, 1])
        wa, wb = histogram([1, 2, 2, 4],
                           bins=4,
                           weights=[4, 3, 2, 1],
                           density=True)
        assert_array_almost_equal(wa, np.array([4, 5, 0, 1]) / 10. / 3. * 4)

        # Check weights with non-uniform bin widths
        a, b = histogram(np.arange(9), [0, 1, 3, 6, 10],
                         weights=[2, 1, 1, 1, 1, 1, 1, 1, 1],
                         density=True)
        assert_almost_equal(a, [.2, .1, .1, .075])
Example #5
0
 def test_polyint_type(self):
     # Ticket #944
     msg = "Wrong type, should be complex"
     x = np.ones(3, dtype=complex)
     assert_(np.polyint(x).dtype == complex, msg)
     msg = "Wrong type, should be float"
     x = np.ones(3, dtype=int)
     assert_(np.polyint(x).dtype == float, msg)
Example #6
0
    def test_prepending_ones(self):
        a = np.zeros((3, 2))

        a[...] = np.ones((1, 3, 2))
        # Fancy with subspace with and without transpose
        a[[0, 1, 2], :] = np.ones((1, 3, 2))
        a[:, [0, 1]] = np.ones((1, 3, 2))
        # Fancy without subspace (with broadcasting)
        a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2))
Example #7
0
    def test_prepend_not_one(self):
        assign = self.assign
        s_ = np.s_
        a = np.zeros(5)

        # Too large and not only ones.
        assert_raises(ValueError, assign, a, s_[...],  np.ones((2, 1)))
        assert_raises(ValueError, assign, a, s_[[1, 2, 3],], np.ones((2, 1)))
        assert_raises(ValueError, assign, a, s_[[[1], [2]],], np.ones((2,2,1)))
Example #8
0
    def test_different_ndims(self):
        a = 1.
        b = 2 * np.ones((1, 2))
        c = 3 * np.ones((1, 1, 3))

        result = np.block([a, b, c])
        expected = np.array([[[1., 2., 2., 3., 3., 3.]]])

        assert_equal(result, expected)
Example #9
0
 def test_polydiv_type(self):
     # Make polydiv work for complex types
     msg = "Wrong type, should be complex"
     x = np.ones(3, dtype=complex)
     q, r = np.polydiv(x, x)
     assert_(q.dtype == complex, msg)
     msg = "Wrong type, should be float"
     x = np.ones(3, dtype=int)
     q, r = np.polydiv(x, x)
     assert_(q.dtype == float, msg)
Example #10
0
 def test_trivial_fancy_out_of_bounds(self):
     a = np.zeros(5)
     ind = np.ones(20, dtype=np.intp)
     ind[-1] = 10
     assert_raises(IndexError, a.__getitem__, ind)
     assert_raises(IndexError, a.__setitem__, ind, 0)
     ind = np.ones(20, dtype=np.intp)
     ind[0] = 11
     assert_raises(IndexError, a.__getitem__, ind)
     assert_raises(IndexError, a.__setitem__, ind, 0)
Example #11
0
 def test_weights(self):
     v = np.random.rand(100, 2)
     hist, edges = histogramdd(v)
     n_hist, edges = histogramdd(v, density=True)
     w_hist, edges = histogramdd(v, weights=np.ones(100))
     assert_array_equal(w_hist, hist)
     w_hist, edges = histogramdd(v, weights=np.ones(100) * 2, density=True)
     assert_array_equal(w_hist, n_hist)
     w_hist, edges = histogramdd(v, weights=np.ones(100, int) * 2)
     assert_array_equal(w_hist, 2 * hist)
Example #12
0
    def test_rank3(self):
        x = np.ones(shape=(2, 2, 2))
        y = np.ones(shape=(2, 2, 2)) + 1

        self._assert_func(x, y)
        assert_raises(AssertionError, lambda: self._assert_func(y, x))

        y[0, 0, 0] = 0

        assert_raises(AssertionError, lambda: self._assert_func(x, y))
        assert_raises(AssertionError, lambda: self._assert_func(y, x))
Example #13
0
    def test_basic(self):
        d = np.ones((50, 60))
        d2 = np.ones((30, 60, 6))
        assert_(np.may_share_memory(d, d))
        assert_(np.may_share_memory(d, d[::-1]))
        assert_(np.may_share_memory(d, d[::2]))
        assert_(np.may_share_memory(d, d[1:, ::-1]))

        assert_(not np.may_share_memory(d[::-1], d2))
        assert_(not np.may_share_memory(d[::2], d2))
        assert_(not np.may_share_memory(d[1:, ::-1], d2))
        assert_(np.may_share_memory(d2[1:, ::-1], d2))
Example #14
0
def test_copyto_permut():
    # test explicit overflow case
    pad = 500
    l = [True] * pad + [True, True, True, True]
    r = np.zeros(len(l) - pad)
    d = np.ones(len(l) - pad)
    mask = np.array(l)[pad:]
    np.copyto(r, d, where=mask[::-1])

    # test all permutation of possible masks, 9 should be sufficient for
    # current 4 byte unrolled code
    power = 9
    d = np.ones(power)
    for i in range(2**power):
        r = np.zeros(power)
        l = [(i & x) != 0 for x in range(power)]
        mask = np.array(l)
        np.copyto(r, d, where=mask)
        assert_array_equal(r == 1, l)
        assert_equal(r.sum(), sum(l))

        r = np.zeros(power)
        np.copyto(r, d, where=mask[::-1])
        assert_array_equal(r == 1, l[::-1])
        assert_equal(r.sum(), sum(l))

        r = np.zeros(power)
        np.copyto(r[::2], d[::2], where=mask[::2])
        assert_array_equal(r[::2] == 1, l[::2])
        assert_equal(r[::2].sum(), sum(l[::2]))

        r = np.zeros(power)
        np.copyto(r[::2], d[::2], where=mask[::-2])
        assert_array_equal(r[::2] == 1, l[::-2])
        assert_equal(r[::2].sum(), sum(l[::-2]))

        for c in [0xFF, 0x7F, 0x02, 0x10]:
            r = np.zeros(power)
            mask = np.array(l)
            imask = np.array(l).view(np.uint8)
            imask[mask != 0] = c
            np.copyto(r, d, where=mask)
            assert_array_equal(r == 1, l)
            assert_equal(r.sum(), sum(l))

    r = np.zeros(power)
    np.copyto(r, d, where=True)
    assert_equal(r.sum(), r.size)
    r = np.ones(power)
    d = np.zeros(power)
    np.copyto(r, d, where=False)
    assert_equal(r.sum(), r.size)
Example #15
0
 def test_allnans(self):
     for f, tgt_value in zip(self.nanfuncs, [0, 1]):
         # Unlike other nan-functions, sum/prod/cumsum/cumprod don't warn on all nan input
         with assert_no_warnings():
             res = f([np.nan]*3, axis=None)
             tgt = tgt_value*np.ones((3))
             assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((3))' % (tgt_value))
             # Check scalar
             res = f(np.nan)
             tgt = tgt_value*np.ones((1))
             assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((1))' % (tgt_value))
             # Check there is no warning for not all-nan
             f([0]*3, axis=None)
Example #16
0
 def test_as_series(self):
     # check exceptions
     assert_raises(ValueError, pu.as_series, [[]])
     assert_raises(ValueError, pu.as_series, [[[1, 2]]])
     assert_raises(ValueError, pu.as_series, [[1], ['a']])
     # check common types
     types = ['i', 'd', 'O']
     for i in range(len(types)):
         for j in range(i):
             ci = np.ones(1, types[i])
             cj = np.ones(1, types[j])
             [resi, resj] = pu.as_series([ci, cj])
             assert_(resi.dtype.char == resj.dtype.char)
             assert_(resj.dtype.char == types[i])
Example #17
0
    def test_type(self):
        # Check the type of the returned histogram
        a = np.arange(10) + .5
        h, b = histogram(a)
        assert_(np.issubdtype(h.dtype, np.integer))

        h, b = histogram(a, density=True)
        assert_(np.issubdtype(h.dtype, np.floating))

        h, b = histogram(a, weights=np.ones(10, int))
        assert_(np.issubdtype(h.dtype, np.integer))

        h, b = histogram(a, weights=np.ones(10, float))
        assert_(np.issubdtype(h.dtype, np.floating))
Example #18
0
    def test_indexing_array_weird_strides(self):
        # See also gh-6221
        # the shapes used here come from the issue and create the correct
        # size for the iterator buffering size.
        x = np.ones(10)
        x2 = np.ones((10, 2))
        ind = np.arange(10)[:, None, None, None]
        ind = np.broadcast_to(ind, (10, 55, 4, 4))

        # single advanced index case
        assert_array_equal(x[ind], x[ind.copy()])
        # higher dimensional advanced index
        zind = np.zeros(4, dtype=np.intp)
        assert_array_equal(x2[ind, zind], x2[ind.copy(), zind])
Example #19
0
    def test_getitem(self):
        subscript = functools.partial(array_indexing, 0)

        # 0-d arrays don't work:
        assert_raises(IndexError, subscript, np.ones(()), 0)
        # Out of bound values:
        assert_raises(IndexError, subscript, np.ones(10), 11)
        assert_raises(IndexError, subscript, np.ones(10), -11)
        assert_raises(IndexError, subscript, np.ones((10, 10)), 11)
        assert_raises(IndexError, subscript, np.ones((10, 10)), -11)

        a = np.arange(10)
        assert_array_equal(a[4], subscript(a, 4))
        a = a.reshape(5, 2)
        assert_array_equal(a[-4], subscript(a, -4))
Example #20
0
    def test_keepdims(self):
        mat = np.eye(3)
        for axis in [None, 0, 1]:
            tgt = np.percentile(mat, 70, axis=axis, out=None,
                                overwrite_input=False)
            res = np.nanpercentile(mat, 70, axis=axis, out=None,
                                   overwrite_input=False)
            assert_(res.ndim == tgt.ndim)

        d = np.ones((3, 5, 7, 11))
        # Randomly set some elements to NaN:
        w = np.random.random((4, 200)) * np.array(d.shape)[:, None]
        w = w.astype(np.intp)
        d[tuple(w)] = np.nan
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning)
            res = np.nanpercentile(d, 90, axis=None, keepdims=True)
            assert_equal(res.shape, (1, 1, 1, 1))
            res = np.nanpercentile(d, 90, axis=(0, 1), keepdims=True)
            assert_equal(res.shape, (1, 1, 7, 11))
            res = np.nanpercentile(d, 90, axis=(0, 3), keepdims=True)
            assert_equal(res.shape, (1, 5, 7, 1))
            res = np.nanpercentile(d, 90, axis=(1,), keepdims=True)
            assert_equal(res.shape, (3, 1, 7, 11))
            res = np.nanpercentile(d, 90, axis=(0, 1, 2, 3), keepdims=True)
            assert_equal(res.shape, (1, 1, 1, 1))
            res = np.nanpercentile(d, 90, axis=(0, 1, 3), keepdims=True)
            assert_equal(res.shape, (1, 1, 7, 1))
Example #21
0
    def test_basic(self):
        A = np.arange(100).reshape(10, 10)
        mA = matrix(A)

        mB = mA.copy()
        O = np.ones((10, 10), np.float64) * 0.1
        mB = mB + O
        assert_(mB.dtype.type == np.float64)
        assert_(np.all(mA != mB))
        assert_(np.all(mB == mA + 0.1))

        mC = mA.copy()
        O = np.ones((10, 10), np.complex128)
        mC = mC * O
        assert_(mC.dtype.type == np.complex128)
        assert_(np.all(mA != mB))
Example #22
0
    def test_reverse_strides_and_subspace_bufferinit(self):
        # This tests that the strides are not reversed for simple and
        # subspace fancy indexing.
        a = np.ones(5)
        b = np.zeros(5, dtype=np.intp)[::-1]
        c = np.arange(5)[::-1]

        a[b] = c
        # If the strides are not reversed, the 0 in the arange comes last.
        assert_equal(a[0], 0)

        # This also tests that the subspace buffer is initialized:
        a = np.ones((5, 2))
        c = np.arange(10).reshape(5, 2)[::-1]
        a[b, :] = c
        assert_equal(a[0], [0, 1])
Example #23
0
 def test_result(self):
     types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
     with suppress_warnings() as sup:
         sup.filter(RuntimeWarning)
         for dt in types:
             a = np.ones((), dtype=dt)[()]
             assert_equal(operator.sub(a, a), 0)
Example #24
0
 def test_sign_spacing_structured(self):
     a = np.ones(2, dtype='<f,<f')
     assert_equal(
         repr(a),
         "array([(1., 1.), (1., 1.)], dtype=[('f0', '<f4'), ('f1', '<f4')])"
     )
     assert_equal(repr(a[0]), "(1., 1.)")
Example #25
0
    def test_object_assign(self):
        # Check that the field and object special case using copyto is active.
        # The right hand side cannot be converted to an array here.
        a = np.arange(5, dtype=object)
        b = a.copy()
        a[:3] = [1, (1,2), 3]
        b[[0, 1, 2]] = [1, (1,2), 3]
        assert_array_equal(a, b)

        # test same for subspace fancy indexing
        b = np.arange(5, dtype=object)[None, :]
        b[[0], :3] = [[1, (1,2), 3]]
        assert_array_equal(a, b[0])

        # Check that swapping of axes works.
        # There was a bug that made the later assignment throw a ValueError
        # do to an incorrectly transposed temporary right hand side (gh-5714)
        b = b.T
        b[:3, [0]] = [[1], [(1,2)], [3]]
        assert_array_equal(a, b[:, 0])

        # Another test for the memory order of the subspace
        arr = np.ones((3, 4, 5), dtype=object)
        # Equivalent slicing assignment for comparison
        cmp_arr = arr.copy()
        cmp_arr[:1, ...] = [[[1], [2], [3], [4]]]
        arr[[0], ...] = [[[1], [2], [3], [4]]]
        assert_array_equal(arr, cmp_arr)
        arr = arr.copy('F')
        arr[[0], ...] = [[[1], [2], [3], [4]]]
        assert_array_equal(arr, cmp_arr)
Example #26
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))
Example #27
0
    def test_invalid(self):
        """ Test it errors when indices has too few dimensions """
        a = np.ones((10, 10))
        ai = np.ones((10, 2), dtype=np.intp)

        # sanity check
        take_along_axis(a, ai, axis=1)

        # not enough indices
        assert_raises(ValueError, take_along_axis, a, np.array(1), axis=1)
        # bool arrays not allowed
        assert_raises(IndexError, take_along_axis, a, ai.astype(bool), axis=1)
        # float arrays not allowed
        assert_raises(IndexError, take_along_axis, a, ai.astype(float), axis=1)
        # invalid axis
        assert_raises(np.AxisError, take_along_axis, a, ai, axis=10)
Example #28
0
 def test_block_simple_row_wise(self):
     a_2d = np.ones((2, 2))
     b_2d = 2 * a_2d
     desired = np.array([[1, 1, 2, 2],
                         [1, 1, 2, 2]])
     result = block([a_2d, b_2d])
     assert_equal(desired, result)
Example #29
0
def test_packbits_very_large():
    # test some with a larger arrays gh-8637
    # code is covered earlier but larger array makes crash on bug more likely
    for s in range(950, 1050):
        for dt in '?bBhHiIlLqQ':
            x = np.ones((200, s), dtype=bool)
            np.packbits(x, axis=1)
Example #30
0
 def test_different_field_order(self):
     # gh-8940
     a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
     b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
     # this should not give a FutureWarning:
     j = join_by(['c', 'b'], a, b, jointype='inner', usemask=False)
     assert_equal(j.dtype.names, ['b', 'c', 'a1', 'a2'])