コード例 #1
0
    def test_legtrim(self):
        coef = [2, -1, 1, 0]

        # Test exceptions
        assert_raises(ValueError, leg.legtrim, coef, -1)

        # Test results
        assert_equal(leg.legtrim(coef), coef[:-1])
        assert_equal(leg.legtrim(coef, 1), coef[:-3])
        assert_equal(leg.legtrim(coef, 2), [0])
コード例 #2
0
ファイル: test_ufunclike.py プロジェクト: frank1991430/test
    def test_isneginf(self):
        a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0])
        out = nx.zeros(a.shape, bool)
        tgt = nx.array([False, True, False, False, False, False])

        res = ufl.isneginf(a)
        assert_equal(res, tgt)
        res = ufl.isneginf(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
コード例 #3
0
ファイル: test_indexing.py プロジェクト: frank1991430/test
    def test_boolean_indexing_twodim(self):
        # Indexing a 2-dimensional array with
        # 2-dimensional boolean array
        a = np.array([[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]])
        b = np.array([[ True, False,  True],
                      [False,  True, False],
                      [ True, False,  True]])
        assert_equal(a[b], [1, 3, 5, 7, 9])
        assert_equal(a[b[1]], [[4, 5, 6]])
        assert_equal(a[b[0]], a[b[2]])

        # boolean assignment
        a[b] = 0
        assert_equal(a, [[0, 2, 0],
                         [4, 0, 6],
                         [0, 8, 0]])
コード例 #4
0
    def test_object_array(self):
        arr = np.array([[1.0, 2.0], [np.nan, 4.0], [np.nan, np.nan]], dtype=object)
        assert_equal(np.nanmin(arr), 1.0)
        assert_equal(np.nanmin(arr, axis=0), [1.0, 2.0])

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # assert_equal does not work on object arrays of nan
            assert_equal(list(np.nanmin(arr, axis=1)), [1.0, 4.0, np.nan])
            assert_(len(w) == 1, 'no warning raised')
            assert_(issubclass(w[0].category, RuntimeWarning))
コード例 #5
0
 def test_upgrademapper(self):
     "Tests updatemapper"
     dateparser = _bytes_to_date
     StringConverter.upgrade_mapper(dateparser, date(2000, 1, 1))
     convert = StringConverter(dateparser, date(2000, 1, 1))
     test = convert('2001-01-01')
     assert_equal(test, date(2001, 1, 1))
     test = convert('2009-01-01')
     assert_equal(test, date(2009, 1, 1))
     test = convert('')
     assert_equal(test, date(2000, 1, 1))
コード例 #6
0
def test_as_strided():
    a = np.array([None])
    a_view = as_strided(a)
    expected = np.array([None])
    assert_array_equal(a_view, np.array([None]))

    a = np.array([1, 2, 3, 4])
    a_view = as_strided(a, shape=(2, ), strides=(2 * a.itemsize, ))
    expected = np.array([1, 3])
    assert_array_equal(a_view, expected)

    a = np.array([1, 2, 3, 4])
    a_view = as_strided(a, shape=(3, 4), strides=(0, 1 * a.itemsize))
    expected = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
    assert_array_equal(a_view, expected)

    # Regression test for gh-5081
    dt = np.dtype([('num', 'i4'), ('obj', 'O')])
    a = np.empty((4, ), dtype=dt)
    a['num'] = np.arange(1, 5)
    a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
    expected_num = [[1, 2, 3, 4]] * 3
    expected_obj = [[None] * 4] * 3
    assert_equal(a_view.dtype, dt)
    assert_array_equal(expected_num, a_view['num'])
    assert_array_equal(expected_obj, a_view['obj'])

    # Make sure that void types without fields are kept unchanged
    a = np.empty((4, ), dtype='V4')
    a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
    assert_equal(a.dtype, a_view.dtype)

    # Make sure that the only type that could fail is properly handled
    dt = np.dtype({'names': [''], 'formats': ['V4']})
    a = np.empty((4, ), dtype=dt)
    a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
    assert_equal(a.dtype, a_view.dtype)

    # Custom dtypes should not be lost (gh-9161)
    r = [rational(i) for i in range(4)]
    a = np.array(r, dtype=rational)
    a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
    assert_equal(a.dtype, a_view.dtype)
    assert_array_equal([r] * 3, a_view)
コード例 #7
0
    def test_basic(self):
        assert_equal(
            eye(4),
            array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))

        assert_equal(
            eye(4, dtype='f'),
            array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],
                  'f'))

        assert_equal(eye(3) == 1, eye(3, dtype=bool))
コード例 #8
0
ファイル: test_defmatrix.py プロジェクト: frank1991430/test
 def test_fancy_indexing(self):
     a = self.a
     x = a[1, [0, 1, 0]]
     assert_(isinstance(x, matrix))
     assert_equal(x, matrix([[3, 4, 3]]))
     x = a[[1, 0]]
     assert_(isinstance(x, matrix))
     assert_equal(x, matrix([[3, 4], [1, 2]]))
     x = a[[[1], [0]], [[1, 0], [0, 1]]]
     assert_(isinstance(x, matrix))
     assert_equal(x, matrix([[4, 3], [1, 2]]))
コード例 #9
0
 def test_empty(self):
     for f, tgt_value in zip(self.nanfuncs, [0, 1]):
         mat = np.zeros((0, 3))
         tgt = tgt_value*np.ones((0, 3))
         res = f(mat, axis=0)
         assert_equal(res, tgt)
         tgt = mat
         res = f(mat, axis=1)
         assert_equal(res, tgt)
         tgt = np.zeros((0))
         res = f(mat, axis=None)
         assert_equal(res, tgt)
コード例 #10
0
 def test_empty(self):
     for f, tgt_value in zip([np.nansum, np.nanprod], [0, 1]):
         mat = np.zeros((0, 3))
         tgt = [tgt_value]*3
         res = f(mat, axis=0)
         assert_equal(res, tgt)
         tgt = []
         res = f(mat, axis=1)
         assert_equal(res, tgt)
         tgt = tgt_value
         res = f(mat, axis=None)
         assert_equal(res, tgt)
コード例 #11
0
ファイル: test_arrayprint.py プロジェクト: frank1991430/test
    def test_dtype_linewidth_wrapping(self):
        np.set_printoptions(linewidth=75)
        assert_equal(
            repr(np.arange(10, 20., dtype='f4')),
            "array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19.], dtype=float32)"
        )
        assert_equal(
            repr(np.arange(10, 23., dtype='f4')),
            textwrap.dedent("""\
            array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
                  dtype=float32)"""))

        styp = '<U4' if sys.version_info[0] >= 3 else '|S4'
        assert_equal(repr(np.ones(3, dtype=styp)),
                     "array(['1', '1', '1'], dtype='{}')".format(styp))
        assert_equal(
            repr(np.ones(12, dtype=styp)),
            textwrap.dedent("""\
            array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
                  dtype='{}')""".format(styp)))
コード例 #12
0
ファイル: test_arrayprint.py プロジェクト: frank1991430/test
    def test_object_subclass(self):
        class sub(np.ndarray):
            def __new__(cls, inp):
                obj = np.asarray(inp).view(cls)
                return obj

            def __getitem__(self, ind):
                ret = super(sub, self).__getitem__(ind)
                return sub(ret)

        # test that object + subclass is OK:
        x = sub([None, None])
        assert_equal(repr(x), 'sub([None, None], dtype=object)')
        assert_equal(str(x), '[None None]')

        x = sub([None, sub([None, None])])
        assert_equal(
            repr(x),
            'sub([None, sub([None, None], dtype=object)], dtype=object)')
        assert_equal(str(x), '[None sub([None, None], dtype=object)]')
コード例 #13
0
 def test_constant_fixed_width(self):
     "Test LineSplitter w/ fixed-width fields"
     strg = "  1  2  3  4     5   # test"
     test = LineSplitter(3)(strg)
     assert_equal(test, ['1', '2', '3', '4', '', '5', ''])
     #
     strg = "  1     3  4  5  6# test"
     test = LineSplitter(20)(strg)
     assert_equal(test, ['1     3  4  5  6'])
     #
     strg = "  1     3  4  5  6# test"
     test = LineSplitter(30)(strg)
     assert_equal(test, ['1     3  4  5  6'])
コード例 #14
0
    def test_lagval(self):
        #check empty input
        assert_equal(lag.lagval([], [1]).size, 0)

        #check normal input)
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Llist]
        for i in range(7):
            msg = "At i=%d" % i
            tgt = y[i]
            res = lag.lagval(x, [0] * i + [1])
            assert_almost_equal(res, tgt, err_msg=msg)

        #check that shape is preserved
        for i in range(3):
            dims = [2] * i
            x = np.zeros(dims)
            assert_equal(lag.lagval(x, [1]).shape, dims)
            assert_equal(lag.lagval(x, [1, 0]).shape, dims)
            assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims)
コード例 #15
0
 def test_vector(self):
     vals = (100 * arange(5)).astype('l')
     b = zeros((5, 5))
     for k in range(5):
         b[k, k] = vals[k]
     assert_equal(diag(vals), b)
     b = zeros((7, 7))
     c = b.copy()
     for k in range(5):
         b[k, k + 2] = vals[k]
         c[k + 2, k] = vals[k]
     assert_equal(diag(vals, k=2), b)
     assert_equal(diag(vals, k=-2), c)
コード例 #16
0
 def test_array_scalar(self):
     lim1 = array([-120, 100], dtype="int8")
     lim2 = array([120, -100], dtype="int8")
     lim3 = array([1200, 1000], dtype="uint16")
     t1 = linspace(lim1[0], lim1[1], 5)
     t2 = linspace(lim2[0], lim2[1], 5)
     t3 = linspace(lim3[0], lim3[1], 5)
     t4 = linspace(-120.0, 100.0, 5)
     t5 = linspace(120.0, -100.0, 5)
     t6 = linspace(1200.0, 1000.0, 5)
     assert_equal(t1, t4)
     assert_equal(t2, t5)
     assert_equal(t3, t6)
コード例 #17
0
ファイル: test_old_ma.py プロジェクト: frank1991430/test
    def test_testBasic2d(self):
        # Test of basic array creation and properties in 2 dimensions.
        for s in [(4, 3), (6, 2)]:
            (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
            x.shape = s
            y.shape = s
            xm.shape = s
            ym.shape = s
            xf.shape = s

            assert_(not isMaskedArray(x))
            assert_(isMaskedArray(xm))
            assert_equal(shape(xm), s)
            assert_equal(xm.shape, s)
            assert_equal(xm.size, reduce(lambda x, y:x * y, s))
            assert_equal(count(xm),
                             len(m1) - reduce(lambda x, y:x + y, m1))
            assert_(eq(xm, xf))
            assert_(eq(filled(xm, 1.e20), xf))
            assert_(eq(x, xm))
            self.setup()
コード例 #18
0
 def test_matrix(self, vals=None):
     if vals is None:
         vals = (100 * get_mat(5) + 1).astype('l')
     b = zeros((5, ))
     for k in range(5):
         b[k] = vals[k, k]
     assert_equal(diag(vals), b)
     b = b * 0
     for k in range(3):
         b[k] = vals[k, k + 2]
     assert_equal(diag(vals, 2), b[:3])
     for k in range(3):
         b[k] = vals[k + 2, k]
     assert_equal(diag(vals, -2), b[:3])
コード例 #19
0
    def test_other_delimiter(self):
        "Test LineSplitter on delimiter"
        strg = "1,2,3,4,,5"
        test = LineSplitter(',')(strg)
        assert_equal(test, ['1', '2', '3', '4', '', '5'])
        #
        strg = " 1,2,3,4,,5 # test"
        test = LineSplitter(',')(strg)
        assert_equal(test, ['1', '2', '3', '4', '', '5'])

        # gh-11028 bytes comment/delimiters should get encoded
        strg = b" 1,2,3,4,,5 % test"
        test = LineSplitter(delimiter=b',', comments=b'%')(strg)
        assert_equal(test, ['1', '2', '3', '4', '', '5'])
コード例 #20
0
ファイル: test_polynomial.py プロジェクト: frank1991430/test
    def test_polyval(self):
        #check empty input
        assert_equal(poly.polyval([], [1]).size, 0)

        #check normal input)
        x = np.linspace(-1, 1)
        y = [x**i for i in range(5)]
        for i in range(5):
            tgt = y[i]
            res = poly.polyval(x, [0] * i + [1])
            assert_almost_equal(res, tgt)
        tgt = x * (x**2 - 1)
        res = poly.polyval(x, [0, -1, 0, 1])
        assert_almost_equal(res, tgt)

        #check that shape is preserved
        for i in range(3):
            dims = [2] * i
            x = np.zeros(dims)
            assert_equal(poly.polyval(x, [1]).shape, dims)
            assert_equal(poly.polyval(x, [1, 0]).shape, dims)
            assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)
コード例 #21
0
ファイル: test_old_ma.py プロジェクト: frank1991430/test
 def test_testCI(self):
     # Test of conversions and indexing
     x1 = np.array([1, 2, 4, 3])
     x2 = array(x1, mask=[1, 0, 0, 0])
     x3 = array(x1, mask=[0, 1, 0, 1])
     x4 = array(x1)
     # test conversion to strings
     str(x2)  # raises?
     repr(x2)  # raises?
     assert_(eq(np.sort(x1), sort(x2, fill_value=0)))
     # tests of indexing
     assert_(type(x2[1]) is type(x1[1]))
     assert_(x1[1] == x2[1])
     assert_(x2[0] is masked)
     assert_(eq(x1[2], x2[2]))
     assert_(eq(x1[2:5], x2[2:5]))
     assert_(eq(x1[:], x2[:]))
     assert_(eq(x1[1:], x3[1:]))
     x1[2] = 9
     x2[2] = 9
     assert_(eq(x1, x2))
     x1[1:3] = 99
     x2[1:3] = 99
     assert_(eq(x1, x2))
     x2[1] = masked
     assert_(eq(x1, x2))
     x2[1:3] = masked
     assert_(eq(x1, x2))
     x2[:] = x1
     x2[1] = masked
     assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
     x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
     assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
     x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
     assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
     assert_(allequal(x4, array([1, 2, 3, 4])))
     x1 = np.arange(5) * 1.0
     x2 = masked_values(x1, 3.0)
     assert_(eq(x1, x2))
     assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
     assert_(eq(3.0, x2.fill_value))
     x1 = array([1, 'hello', 2, 3], object)
     x2 = np.array([1, 'hello', 2, 3], object)
     s1 = x1[1]
     s2 = x2[1]
     assert_equal(type(s2), str)
     assert_equal(type(s1), str)
     assert_equal(s1, s2)
     assert_(x1[1:1].shape == (0,))
コード例 #22
0
ファイル: test_arrayprint.py プロジェクト: frank1991430/test
    def test_format_function(self):
        """Test custom format function for each element in array."""
        def _format_function(x):
            if np.abs(x) < 1:
                return '.'
            elif np.abs(x) < 2:
                return 'o'
            else:
                return 'O'

        x = np.arange(3)
        if sys.version_info[0] >= 3:
            x_hex = "[0x0 0x1 0x2]"
            x_oct = "[0o0 0o1 0o2]"
        else:
            x_hex = "[0x0L 0x1L 0x2L]"
            x_oct = "[0L 01L 02L]"
        assert_(
            np.array2string(x, formatter={'all': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'int_kind': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) ==
            "[0.0000 1.0000 2.0000]")
        assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}),
                     x_hex)
        assert_equal(np.array2string(x, formatter={'int': lambda x: oct(x)}),
                     x_oct)

        x = np.arange(3.)
        assert_(
            np.array2string(x, formatter={'float_kind': lambda x: "%.2f" % x})
            == "[0.00 1.00 2.00]")
        assert_(
            np.array2string(x, formatter={'float': lambda x: "%.2f" % x}) ==
            "[0.00 1.00 2.00]")

        s = np.array(['abc', 'def'])
        assert_(
            np.array2string(s, formatter={'numpystr': lambda s: s * 2}) ==
            '[abcabc defdef]')

        # check for backcompat that using FloatFormat works and emits warning
        with assert_warns(DeprecationWarning):
            fmt = np.core.arrayprint.FloatFormat(x, 9, 'maxprec', False)
        assert_equal(np.array2string(x, formatter={'float_kind': fmt}),
                     '[0. 1. 2.]')
コード例 #23
0
 def test_del(self):
     # Make sure a view does not delete the underlying mmap
     fp_base = memmap(self.tmpfp,
                      dtype=self.dtype,
                      mode='w+',
                      shape=self.shape)
     fp_base[0] = 5
     fp_view = fp_base[0:1]
     assert_equal(fp_view[0], 5)
     del fp_view
     # Should still be able to access and assign values after
     # deleting the view
     assert_equal(fp_base[0], 5)
     fp_base[0] = 6
     assert_equal(fp_base[0], 6)
コード例 #24
0
ファイル: test_print.py プロジェクト: frank1991430/test
def check_float_type(tp):
    for x in [0, 1, -1, 1e20]:
        assert_equal(str(tp(x)),
                     str(float(x)),
                     err_msg='Failed str formatting for type %s' % tp)

    if tp(1e16).itemsize > 4:
        assert_equal(str(tp(1e16)),
                     str(float('1e16')),
                     err_msg='Failed str formatting for type %s' % tp)
    else:
        ref = '1e+16'
        assert_equal(str(tp(1e16)),
                     ref,
                     err_msg='Failed str formatting for type %s' % tp)
コード例 #25
0
ファイル: test_utils.py プロジェクト: frank1991430/test
    def test_warn(self):
        def f():
            warnings.warn("yo")
            return 3

        before_filters = sys.modules['warnings'].filters[:]
        assert_equal(assert_warns(UserWarning, f), 3)
        after_filters = sys.modules['warnings'].filters

        assert_raises(AssertionError, assert_no_warnings, f)
        assert_equal(assert_no_warnings(lambda x: x, 1), 1)

        # Check that the warnings state is unchanged
        assert_equal(before_filters, after_filters,
                     "assert_warns does not preserver warnings state")
コード例 #26
0
ファイル: test_extint128.py プロジェクト: frank1991430/test
def test_divmod_128_64():
    with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
        for a, b in it:
            if a >= 0:
                c, cr = divmod(a, b)
            else:
                c, cr = divmod(-a, b)
                c = -c
                cr = -cr

            d, dr = mt.extint_divmod_128_64(a, b)

            if c != d or d != dr or b * d + dr != a:
                assert_equal(d, c)
                assert_equal(dr, cr)
                assert_equal(b * d + dr, a)
コード例 #27
0
    def test_basic(self):
        from numpy1.random import rand

        a = rand(20, 10, 10, 1, 1)
        b = rand(20, 1, 10, 1, 20)
        c = rand(1, 1, 20, 10)
        assert_array_equal(np.squeeze(a), np.reshape(a, (20, 10, 10)))
        assert_array_equal(np.squeeze(b), np.reshape(b, (20, 10, 20)))
        assert_array_equal(np.squeeze(c), np.reshape(c, (20, 10)))

        # Squeezing to 0-dim should still give an ndarray
        a = [[[1.5]]]
        res = np.squeeze(a)
        assert_equal(res, 1.5)
        assert_equal(res.ndim, 0)
        assert_equal(type(res), np.ndarray)
コード例 #28
0
ファイル: test_regression.py プロジェクト: frank1991430/test
    def test_loadtxt_fields_subarrays(self):
        # For ticket #1936
        if sys.version_info[0] >= 3:
            from io import StringIO
        else:
            from StringIO import StringIO

        dt = [("a", 'u1', 2), ("b", 'u1', 2)]
        x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt)
        assert_equal(x, np.array([((0, 1), (2, 3))], dtype=dt))

        dt = [("a", [("a", 'u1', (1, 3)), ("b", 'u1')])]
        x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt)
        assert_equal(x, np.array([(((0, 1, 2), 3),)], dtype=dt))

        dt = [("a", 'u1', (2, 2))]
        x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt)
        assert_equal(x, np.array([(((0, 1), (2, 3)),)], dtype=dt))

        dt = [("a", 'u1', (2, 3, 2))]
        x = np.loadtxt(StringIO("0 1 2 3 4 5 6 7 8 9 10 11"), dtype=dt)
        data = [((((0, 1), (2, 3), (4, 5)), ((6, 7), (8, 9), (10, 11))),)]
        assert_equal(x, np.array(data, dtype=dt))
コード例 #29
0
ファイル: test_histograms.py プロジェクト: frank1991430/test
    def test_outliers(self):
        # Check that outliers are not tallied
        a = np.arange(10) + .5

        # Lower outliers
        h, b = histogram(a, range=[0, 9])
        assert_equal(h.sum(), 9)

        # Upper outliers
        h, b = histogram(a, range=[1, 10])
        assert_equal(h.sum(), 9)

        # Normalization
        h, b = histogram(a, range=[1, 9], density=True)
        assert_almost_equal((h * np.diff(b)).sum(), 1, decimal=15)

        # Weights
        w = np.arange(10) + .5
        h, b = histogram(a, range=[1, 9], weights=w, density=True)
        assert_equal((h * np.diff(b)).sum(), 1)

        h, b = histogram(a, bins=8, range=[1, 9], weights=w)
        assert_equal(h, w[1:-1])
コード例 #30
0
ファイル: test_financial.py プロジェクト: frank1991430/test
    def test_mirr_decimal(self):
        val = [Decimal('-4500'), Decimal('-800'), Decimal('800'), Decimal('800'),
               Decimal('600'), Decimal('600'), Decimal('800'), Decimal('800'),
               Decimal('700'), Decimal('3000')]
        assert_equal(np.mirr(val, Decimal('0.08'), Decimal('0.055')),
                     Decimal('0.066597175031553548874239618'))

        val = [Decimal('-120000'), Decimal('39000'), Decimal('30000'),
               Decimal('21000'), Decimal('37000'), Decimal('46000')]
        assert_equal(np.mirr(val, Decimal('0.10'), Decimal('0.12')), Decimal('0.126094130365905145828421880'))

        val = [Decimal('100'), Decimal('200'), Decimal('-50'),
               Decimal('300'), Decimal('-200')]
        assert_equal(np.mirr(val, Decimal('0.05'), Decimal('0.06')), Decimal('0.342823387842176663647819868'))

        val = [Decimal('39000'), Decimal('30000'), Decimal('21000'), Decimal('37000'), Decimal('46000')]
        assert_(np.isnan(np.mirr(val, Decimal('0.10'), Decimal('0.12'))))