Пример #1
0
    def test_dlti_instantiation(self):
        # Test that lti can be instantiated.

        dt = 0.05
        # TransferFunction
        s = dlti([1], [-1], dt=dt)
        assert_(isinstance(s, TransferFunction))
        assert_(isinstance(s, dlti))
        assert_(not isinstance(s, lti))
        assert_equal(s.dt, dt)

        # ZerosPolesGain
        s = dlti(np.array([]), np.array([-1]), 1, dt=dt)
        assert_(isinstance(s, ZerosPolesGain))
        assert_(isinstance(s, dlti))
        assert_(not isinstance(s, lti))
        assert_equal(s.dt, dt)

        # StateSpace
        s = dlti([1], [-1], 1, 3, dt=dt)
        assert_(isinstance(s, StateSpace))
        assert_(isinstance(s, dlti))
        assert_(not isinstance(s, lti))
        assert_equal(s.dt, dt)

        # Number of inputs
        assert_raises(ValueError, dlti, 1)
        assert_raises(ValueError, dlti, 1, 1, 1, 1, 1)
Пример #2
0
def test_read_write_sio():
    eg_sio1 = BytesIO()
    with make_simple(eg_sio1, 'w') as f1:
        str_val = eg_sio1.getvalue()

    eg_sio2 = BytesIO(str_val)
    with netcdf_file(eg_sio2) as f2:
        check_simple(f2)

    # Test that error is raised if attempting mmap for sio
    eg_sio3 = BytesIO(str_val)
    assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True)
    # Test 64-bit offset write / read
    eg_sio_64 = BytesIO()
    with make_simple(eg_sio_64, 'w', version=2) as f_64:
        str_val = eg_sio_64.getvalue()

    eg_sio_64 = BytesIO(str_val)
    with netcdf_file(eg_sio_64) as f_64:
        check_simple(f_64)
        assert_equal(f_64.version_byte, 2)
    # also when version 2 explicitly specified
    eg_sio_64 = BytesIO(str_val)
    with netcdf_file(eg_sio_64, version=2) as f_64:
        check_simple(f_64)
        assert_equal(f_64.version_byte, 2)
Пример #3
0
    def tst_lock_rm(self):

        # Extract tar
        tempdir = os.path.join(self.mnt_dir, 'lock_dir')
        filename = os.path.join(tempdir, 'myfile')
        os.mkdir(tempdir)
        with open(filename, 'w') as fh:
            fh.write('Hello, world')

        # copy
        try:
            s3ql.lock.main([tempdir])
        except:
            sys.excepthook(*sys.exc_info())
            pytest.fail("s3qllock raised exception")

        # Try to delete
        assert_raises(PermissionError, os.unlink, filename)

        # Try to write
        with pytest.raises(PermissionError):
            open(filename, 'w+').write('Hello')

        # delete properly
        try:
            s3ql.remove.main([tempdir])
        except:
            sys.excepthook(*sys.exc_info())
            pytest.fail("s3qlrm raised exception")

        assert 'lock_dir' not in llfuse.listdir(self.mnt_dir)
Пример #4
0
    def test_dateheader_unsupported(self):
        def read_dateheader_unsupported():
            ofile = open(test8)
            rel, attrs = read_header(ofile)
            ofile.close()

        assert_raises(ValueError, read_dateheader_unsupported)
Пример #5
0
def test_abort_co_read(conn, monkeypatch):
    # We need to delay the write to ensure that we encounter a blocking read
    path = '/foo/wurfl'
    chunks = [300, 317, 283]
    delay = 10
    while True:
        monkeypatch.setattr(MockRequestHandler, 'do_GET',
                            get_chunked_GET_handler(path, chunks, delay))
        conn.send_request('GET', path)
        resp = conn.read_response()
        assert resp.status == 200
        cofun = conn.co_read(450)
        try:
            next(cofun)
        except StopIteration:
            # Not good, need to wait longer
            pass
        else:
            break
        finally:
            conn.disconnect()

        if delay > 5000:
            pytest.fail('no blocking read even with %f sec sleep' % delay)
        delay *= 2

    assert_raises(dugong.ConnectionClosed, next, cofun)
    def test_iteration(self):
        # test that DifferentialEvolutionSolver is iterable
        # if popsize is 3 then the overall generation has size (6,)
        solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3,
                                             maxfun=12)
        x, fun = next(solver)
        assert_equal(np.size(x, 0), 2)

        # 6 nfev are required for initial calculation of energies, 6 nfev are
        # required for the evolution of the 6 population members.
        assert_equal(solver._nfev, 12)

        # the next generation should halt because it exceeds maxfun
        assert_raises(StopIteration, next, solver)

        # check a proper minimisation can be done by an iterable solver
        solver = DifferentialEvolutionSolver(rosen, self.bounds)
        x_prev, fun_prev = next(solver)
        for i, soln in enumerate(solver):
            x_current, fun_current = soln
            assert(fun_prev >= fun_current)
            x_prev, fun_prev = x_current, fun_current
            # need to have this otherwise the solver would never stop.
            if i == 50:
                break
Пример #7
0
def test_orthogonal_procrustes_shape_mismatch():
    np.random.seed(1234)
    shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
    for a, b in permutations(shapes, 2):
        A = np.random.randn(*a)
        B = np.random.randn(*b)
        assert_raises(ValueError, orthogonal_procrustes, A, B)
Пример #8
0
def test_exponential():
    for k, v in exponential_data.items():
        if v is None:
            assert_raises(ValueError, windows.exponential, *k)
        else:
            win = windows.exponential(*k)
            assert_allclose(win, v, rtol=1e-14)
Пример #9
0
def test_roots_hermite():
    rootf = sc.roots_hermite
    evalf = orth.eval_hermite
    weightf = orth.hermite(5).weight_func

    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)

    # Golub-Welsch branch
    x, w = sc.roots_hermite(5, False)
    y, v, m = sc.roots_hermite(5, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)

    muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
    assert_allclose(m, muI, rtol=muI_err)

    # Asymptotic branch (switch over at n >= 150)
    x, w = sc.roots_hermite(200, False)
    y, v, m = sc.roots_hermite(200, True)
    assert_allclose(x, y, 1e-14, 1e-14)
    assert_allclose(w, v, 1e-14, 1e-14)
    assert_allclose(sum(v), m, 1e-14, 1e-14)

    assert_raises(ValueError, sc.roots_hermite, 0)
    assert_raises(ValueError, sc.roots_hermite, 3.3)
Пример #10
0
def test_ckdtree_box_upper_bounds():
    data = np.linspace(0, 2, 10).reshape(-1, 2)
    data[:, 1] += 10
    assert_raises(ValueError, cKDTree, data, leafsize=1, boxsize=1.0)
    assert_raises(ValueError, cKDTree, data, leafsize=1, boxsize=(0.0, 2.0))
    # skip a dimension.
    cKDTree(data, leafsize=1, boxsize=(2.0, 0.0))
Пример #11
0
    def test_neldermead_initial_simplex_bad(self):
        # Check it fails with a bad simplices
        bad_simplices = []

        simplex = np.zeros((3, 2))
        simplex[...] = self.startparams[:2]
        for j in range(2):
            simplex[j+1,j] += 0.1
        bad_simplices.append(simplex)

        simplex = np.zeros((3, 3))
        bad_simplices.append(simplex)

        for simplex in bad_simplices:
            if self.use_wrapper:
                opts = {'maxiter': self.maxiter, 'disp': False,
                        'return_all': False, 'initial_simplex': simplex}
                assert_raises(ValueError,
                              optimize.minimize, self.func, self.startparams, args=(),
                              method='Nelder-mead', options=opts)
            else:
                assert_raises(ValueError, optimize.fmin, self.func, self.startparams,
                              args=(), maxiter=self.maxiter,
                              full_output=True, disp=False, retall=False,
                              initial_simplex=simplex)
Пример #12
0
def test_put_s3error_med(backend, monkeypatch):
    '''Fail as soon as data is received'''
    data = b'hello there, let us see whats going on'
    key = 'borg'

    # Monkeypatch request handler to produce 3 errors
    handler_class = mock_server.S3CRequestHandler
    def do_PUT(self, real_PUT=handler_class.do_PUT, count=[0]):
        count[0] += 1
        # Note: every time we return an error, the request will be retried
        # *twice*: once because of the error, and a second time because the
        # connection has been closed by the server.
        if count[0] > 2:
            return real_PUT(self)
        else:
            self.send_error(503, code='OperationAborted')

            # Since we don't read all the data, we have to close
            # the connection
            self.close_connection = True

    monkeypatch.setattr(handler_class, 'do_PUT', do_PUT)
    fh = backend.open_write(key)
    fh.write(data)
    assert_raises(OperationAbortedError, fh.close)

    enable_temp_fail(backend)
    fh.close()
Пример #13
0
    def test_cardinality(self):
        test_create = self.check_cardinality_create
        test_edit = self.check_cardinality_create

        for prop,             inmin, inmax, outmin, outmax in [
            (CARD.card1_in,   1,     1,     0,      999),
            (CARD.card01_in,  0,     1,     0,      999),
            (CARD.card23_in,  2,     3,     0,      999),
            (CARD.card1n_in,  1,   999,     0,      999),
            (CARD.card0_in,   0,     0,     0,      999),
            (CARD.card1_out,  0,   999,     1,        1),
            (CARD.card01_out, 0,   999,     0,        1),
            (CARD.card23_out, 0,   999,     2,        3),
            (CARD.card1n_out, 0,   999,     1,      999),
            (CARD.card0_out,  0,   999,     0,        0),
            (EXAMPLE.label,   0,     0,     0,        1),
            ]:
            for i in range(4):
                must_pass_in = (inmin <= i <= inmax)
                must_pass_out = (outmin <= i <= outmax)

                for test_proc in [self.check_cardinality_create,
                                  self.check_cardinality_create]:

                    if must_pass_in:
                        test_proc("in", prop, i)
                    else:
                        with assert_raises(InvalidDataError):
                            test_proc("in", prop, i)

                    if must_pass_out:
                        test_proc("out", prop, i)
                    else:
                        with assert_raises(InvalidDataError):
                            test_proc("out", prop, i)
Пример #14
0
def test_t_eval():
    rtol = 1e-3
    atol = 1e-6
    y0 = [1/3, 2/9]
    for t_span in ([5, 9], [5, 1]):
        t_eval = np.linspace(t_span[0], t_span[1], 10)
        res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
                        t_eval=t_eval)
        assert_equal(res.t, t_eval)
        assert_(res.t_events is None)
        assert_(res.success)
        assert_equal(res.status, 0)

        y_true = sol_rational(res.t)
        e = compute_error(res.y, y_true, rtol, atol)
        assert_(np.all(e < 5))

    t_eval = [5, 5.01, 7, 8, 8.01, 9]
    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
                    t_eval=t_eval)
    assert_equal(res.t, t_eval)
    assert_(res.t_events is None)
    assert_(res.success)
    assert_equal(res.status, 0)

    y_true = sol_rational(res.t)
    e = compute_error(res.y, y_true, rtol, atol)
    assert_(np.all(e < 5))

    t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
                    t_eval=t_eval)
    assert_equal(res.t, t_eval)
    assert_(res.t_events is None)
    assert_(res.success)
    assert_equal(res.status, 0)

    t_eval = [5.01, 7, 8, 8.01]
    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
                    t_eval=t_eval)
    assert_equal(res.t, t_eval)
    assert_(res.t_events is None)
    assert_(res.success)
    assert_equal(res.status, 0)

    y_true = sol_rational(res.t)
    e = compute_error(res.y, y_true, rtol, atol)
    assert_(np.all(e < 5))

    t_eval = [4.99, 3, 1.5, 1.1, 1.01]
    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
                    t_eval=t_eval)
    assert_equal(res.t, t_eval)
    assert_(res.t_events is None)
    assert_(res.success)
    assert_equal(res.status, 0)

    t_eval = [4, 6]
    assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
                  rtol=rtol, atol=atol, t_eval=t_eval)
Пример #15
0
    def test_random_sampling(self):
        # Simple sanity checks for sparse random sampling.
        for f in sprand, _sprandn:
            for t in [np.float32, np.float64, np.longdouble]:
                x = f(5, 10, density=0.1, dtype=t)
                assert_equal(x.dtype, t)
                assert_equal(x.shape, (5, 10))
                assert_equal(x.nonzero()[0].size, 5)

            x1 = f(5, 10, density=0.1, random_state=4321)
            assert_equal(x1.dtype, np.double)

            x2 = f(5, 10, density=0.1, random_state=np.random.RandomState(4321))

            assert_array_equal(x1.data, x2.data)
            assert_array_equal(x1.row, x2.row)
            assert_array_equal(x1.col, x2.col)

            for density in [0.0, 0.1, 0.5, 1.0]:
                x = f(5, 10, density=density)
                assert_equal(x.nnz, int(density * np.prod(x.shape)))

            for fmt in ['coo', 'csc', 'csr', 'lil']:
                x = f(5, 10, format=fmt)
                assert_equal(x.format, fmt)

            assert_raises(ValueError, lambda: f(5, 10, 1.1))
            assert_raises(ValueError, lambda: f(5, 10, -0.1))
Пример #16
0
def test_odeint_errors():
    def sys1d(x, t):
        return -100*x

    def bad1(x, t):
        return 1.0/0

    def bad2(x, t):
        return "foo"

    def bad_jac1(x, t):
        return 1.0/0

    def bad_jac2(x, t):
        return [["foo"]]

    def sys2d(x, t):
        return [-100*x[0], -0.1*x[1]]

    def sys2d_bad_jac(x, t):
        return [[1.0/0, 0], [0, -0.1]]

    assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1])
    assert_raises(ValueError, odeint, bad2, 1.0, [0, 1])

    assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1)
    assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2)

    assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1],
                  Dfun=sys2d_bad_jac)
Пример #17
0
    def test_ctypes_variants(self):
        sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double,
                                      ctypes.c_double, ctypes.c_void_p)

        sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double,
                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double),
                                      ctypes.c_void_p)

        sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double,
                                      ctypes.c_double)

        sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double,
                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double))

        sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double,
                                      ctypes.c_int, ctypes.c_double)

        all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4]
        legacy_sigs = [sin_2, sin_4]
        legacy_only_sigs = [sin_4]

        # LowLevelCallables work for new signatures
        for j, func in enumerate(all_sigs):
            callback = LowLevelCallable(func)
            if func in legacy_only_sigs:
                assert_raises(ValueError, quad, callback, 0, pi)
            else:
                assert_allclose(quad(callback, 0, pi)[0], 2.0)

        # Plain ctypes items work only for legacy signatures
        for j, func in enumerate(legacy_sigs):
            if func in legacy_sigs:
                assert_allclose(quad(func, 0, pi)[0], 2.0)
            else:
                assert_raises(ValueError, quad, func, 0, pi)
Пример #18
0
def test_upcast():
    a0 = csr_matrix([[np.pi, np.pi*1j], [3, 4]], dtype=complex)
    b0 = np.array([256+1j, 2**32], dtype=complex)

    for a_dtype in supported_dtypes:
        for b_dtype in supported_dtypes:
            msg = "(%r, %r)" % (a_dtype, b_dtype)

            if np.issubdtype(a_dtype, np.complexfloating):
                a = a0.copy().astype(a_dtype)
            else:
                a = a0.real.copy().astype(a_dtype)

            if np.issubdtype(b_dtype, np.complexfloating):
                b = b0.copy().astype(b_dtype)
            else:
                b = b0.real.copy().astype(b_dtype)

            if not (a_dtype == np.bool_ and b_dtype == np.bool_):
                c = np.zeros((2,), dtype=np.bool_)
                assert_raises(ValueError, _sparsetools.csr_matvec,
                              2, 2, a.indptr, a.indices, a.data, b, c)

            if ((np.issubdtype(a_dtype, np.complexfloating) and
                 not np.issubdtype(b_dtype, np.complexfloating)) or
                (not np.issubdtype(a_dtype, np.complexfloating) and
                 np.issubdtype(b_dtype, np.complexfloating))):
                c = np.zeros((2,), dtype=np.float64)
                assert_raises(ValueError, _sparsetools.csr_matvec,
                              2, 2, a.indptr, a.indices, a.data, b, c)

            c = np.zeros((2,), dtype=np.result_type(a_dtype, b_dtype))
            _sparsetools.csr_matvec(2, 2, a.indptr, a.indices, a.data, b, c)
            assert_allclose(c, np.dot(a.toarray(), b), err_msg=msg)
Пример #19
0
 def test_wrong_dimensions(self):
     x0 = 1.0
     assert_raises(RuntimeError, approx_derivative,
                   self.wrong_dimensions_fun, x0)
     f0 = self.wrong_dimensions_fun(np.atleast_1d(x0))
     assert_raises(ValueError, approx_derivative,
                   self.wrong_dimensions_fun, x0, f0=f0)
Пример #20
0
def test_corrupted_data():
    import zlib
    for exc, fname in [(ValueError, 'corrupted_zlib_data.mat'),
                       (zlib.error, 'corrupted_zlib_checksum.mat')]:
        with open(pjoin(test_data_path, fname), 'rb') as fp:
            rdr = MatFile5Reader(fp)
            assert_raises(exc, rdr.get_variables)
Пример #21
0
    def test_axis(self):
        n, k = 22, 3
        t = np.linspace(0, 1, n + k + 1)
        sh0 = [6, 7, 8]
        for axis in range(4):
            sh = sh0[:]
            sh.insert(axis, n)   # [22, 6, 7, 8] etc
            c = np.random.random(size=sh)
            b = BSpline(t, c, k, axis=axis)
            assert_equal(b.c.shape,
                         [sh[axis],] + sh[:axis] + sh[axis+1:])

            xp = np.random.random((3, 4, 5))
            assert_equal(b(xp).shape,
                         sh[:axis] + list(xp.shape) + sh[axis+1:])

            #0 <= axis < c.ndim
            for ax in [-1, len(sh)+1]:
                assert_raises(ValueError, BSpline, **dict(t=t, c=c, k=k, axis=ax))

            # derivative, antiderivative keeps the axis
            for b1 in [BSpline(t, c, k, axis=axis).derivative(),
                       BSpline(t, c, k, axis=axis).derivative(2),
                       BSpline(t, c, k, axis=axis).antiderivative(),
                       BSpline(t, c, k, axis=axis).antiderivative(2)]:
                assert_equal(b1.axis, b.axis)
Пример #22
0
 def test_syr2k_wrong_c(self):
     f = getattr(fblas, 'dsyr2k', None)
     if f is not None:
         assert_raises(Exception, f, **{'a': self.a,
                                        'b': self.b,
                                        'alpha': 1.,
                                        'c': np.zeros((15, 8))})
Пример #23
0
 def test_unknown_method(self):
     method = "foo"
     f0 = 10.0
     f1 = 20.0
     t1 = 1.0
     t = np.linspace(0, t1, 10)
     assert_raises(ValueError, waveforms.chirp, t, f0, t1, f1, method)
Пример #24
0
def test_tzrzf():
    """
    This test performs an RZ decomposition in which an m x n upper trapezoidal
    array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular
    and Z is unitary.
    """
    seed(1234)
    m, n = 10, 15
    for ind, dtype in enumerate(DTYPES):
        tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
                                           dtype=dtype)
        lwork = _compute_lwork(tzrzf_lw, m, n)

        if ind < 2:
            A = triu(rand(m, n).astype(dtype))
        else:
            A = triu((rand(m, n) + rand(m, n)*1j).astype(dtype))

        # assert wrong shape arg, f2py returns generic error
        assert_raises(Exception, tzrzf, A.T)
        rz, tau, info = tzrzf(A, lwork=lwork)
        # Check success
        assert_(info == 0)

        # Get Z manually for comparison
        R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype)))
        V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:]))
        Id = np.eye(n, dtype=dtype)
        ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)]
        Z = reduce(np.dot, ref)
        assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype),
                        atol=10*np.spacing(dtype(1.0).real), rtol=0.)
Пример #25
0
 def test_hyperbolic_zero_freq(self):
     # f0=0 or f1=0 must raise a ValueError.
     method = 'hyperbolic'
     t1 = 1.0
     t = np.linspace(0, t1, 5)
     assert_raises(ValueError, waveforms.chirp, t, 0, t1, 1, method)
     assert_raises(ValueError, waveforms.chirp, t, 1, t1, 0, method)
Пример #26
0
    def test_intersect(self):
        Delta = 1.0

        x = np.zeros(3)
        s = np.array([1.0, 0.0, 0.0])
        t_neg, t_pos = intersect_trust_region(x, s, Delta)
        assert_equal(t_neg, -1)
        assert_equal(t_pos, 1)

        s = np.array([-1.0, 1.0, -1.0])
        t_neg, t_pos = intersect_trust_region(x, s, Delta)
        assert_allclose(t_neg, -3**-0.5)
        assert_allclose(t_pos, 3**-0.5)

        x = np.array([0.5, -0.5, 0])
        s = np.array([0, 0, 1.0])
        t_neg, t_pos = intersect_trust_region(x, s, Delta)
        assert_allclose(t_neg, -2**-0.5)
        assert_allclose(t_pos, 2**-0.5)

        x = np.ones(3)
        assert_raises(ValueError, intersect_trust_region, x, s, Delta)

        x = np.zeros(3)
        s = np.zeros(3)
        assert_raises(ValueError, intersect_trust_region, x, s, Delta)
Пример #27
0
def test_pftrs():
    """
    Test Cholesky factorization of a positive definite Rectengular Full
    Packed (RFP) format array and solve a linear system
    """
    seed(1234)
    for ind, dtype in enumerate(DTYPES):
        n = 20
        if ind > 1:
            A = (rand(n, n) + rand(n, n)*1j).astype(dtype)
            A = A + A.conj().T + n*eye(n)
        else:
            A = (rand(n, n)).astype(dtype)
            A = A + A.T + n*eye(n)

        B = ones((n, 3), dtype=dtype)
        Bf1 = ones((n+2, 3), dtype=dtype)
        Bf2 = ones((n-2, 3), dtype=dtype)
        pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs',
                                                       'pftrf',
                                                       'trttf',
                                                       'tfttr'),
                                                      dtype=dtype)

        # Get the original array from TP
        Afp, info = trttf(A)
        A_chol_rfp, info = pftrf(n, Afp)
        # larger B arrays shouldn't segfault
        soln, info = pftrs(n, A_chol_rfp, Bf1)
        assert_(info == 0)
        assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2)
        soln, info = pftrs(n, A_chol_rfp, B)
        assert_(info == 0)
        assert_array_almost_equal(solve(A, B), soln,
                                  decimal=4 if ind % 2 == 0 else 6)
Пример #28
0
    def check(caller, func, user_data):
        caller = CALLERS[caller]
        user_data = USER_DATAS[user_data]()
        func = BAD_FUNCS[func]()

        if func is callback_python:
            func2 = lambda x: func(x, 2.0)
        else:
            func2 = LowLevelCallable(func, user_data)
            func = LowLevelCallable(func)

        # Test that basic call fails
        assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)

        # Test that passing in user_data also fails
        assert_raises(ValueError, caller, func2, 1.0)

        # Test error message
        llfunc = LowLevelCallable(func)
        try:
            caller(llfunc, 1.0)
        except ValueError as err:
            msg = str(err)
            assert_(llfunc.signature in msg, msg)
            assert_('double (double, double, int *, void *)' in msg, msg)
Пример #29
0
 def test_type_error(self):
     c = [1]
     A_eq = [[1]]
     b_eq = "hello"
     assert_raises(TypeError, linprog,
                   c, A_eq=A_eq, b_eq=b_eq,
                   method=self.method, options=self.options)
Пример #30
0
def test_read_opts():
    # tests if read is seeing option sets, at initialization and after
    # initialization
    arr = np.arange(6).reshape(1,6)
    stream = BytesIO()
    savemat(stream, {'a': arr})
    rdr = MatFile5Reader(stream)
    back_dict = rdr.get_variables()
    rarr = back_dict['a']
    assert_array_equal(rarr, arr)
    rdr = MatFile5Reader(stream, squeeze_me=True)
    assert_array_equal(rdr.get_variables()['a'], arr.reshape((6,)))
    rdr.squeeze_me = False
    assert_array_equal(rarr, arr)
    rdr = MatFile5Reader(stream, byte_order=boc.native_code)
    assert_array_equal(rdr.get_variables()['a'], arr)
    # inverted byte code leads to error on read because of swapped
    # header etc
    rdr = MatFile5Reader(stream, byte_order=boc.swapped_code)
    assert_raises(Exception, rdr.get_variables)
    rdr.byte_order = boc.native_code
    assert_array_equal(rdr.get_variables()['a'], arr)
    arr = np.array(['a string'])
    stream.truncate(0)
    stream.seek(0)
    savemat(stream, {'a': arr})
    rdr = MatFile5Reader(stream)
    assert_array_equal(rdr.get_variables()['a'], arr)
    rdr = MatFile5Reader(stream, chars_as_strings=False)
    carr = np.atleast_2d(np.array(list(arr.item()), dtype='U1'))
    assert_array_equal(rdr.get_variables()['a'], carr)
    rdr.chars_as_strings = True
    assert_array_equal(rdr.get_variables()['a'], arr)
 def test_bad_args(self):
     # even numtaps
     assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0])
     # odd bands
     assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0])
     # len(bands) != len(desired)
     assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0])
     # non-monotonic bands
     assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0])
     assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4)
     assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4)
     assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4)
     # negative desired
     assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1])
     # len(weight) != len(pairs)
     assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [1, 2])
     # negative weight
     assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [-1])
Пример #32
0
def test_identity():
    ident = interface.IdentityOperator((3, 3))
    assert_equal(ident * [1, 2, 3], [1, 2, 3])
    assert_equal(ident.dot(np.arange(9).reshape(3, 3)).ravel(), np.arange(9))

    assert_raises(ValueError, ident.matvec, [1, 2, 3, 4])
Пример #33
0
    def test_10i(self):
        # int64, float32  (should FAIL on downconvert)
        J = np.array([1, 1, 1], dtype=np.int32)
        x = np.array([1.0, 2.0, 3.0], dtype=np.longdouble)

        assert_raises(TypeError, g.test10, J, x)
Пример #34
0
    def test_10h(self):
        # int32, float16  (should FAIL on upconvert)
        J = np.array([1, 1, 1], dtype=np.int32)
        x = np.array([1.0, 2.0, 3.0], dtype=np.float16)

        assert_raises(TypeError, g.test10, J, x)
 def _test_invalid(bad_format):
     assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format))
Пример #36
0
 def test_order0_diff(self):
     assert_raises(ValueError, splder, self.spl, 4)
 def test_bad_args(self):
     # not enough taps
     assert_raises(ValueError, minimum_phase, [1.])
     assert_raises(ValueError, minimum_phase, [1., 1.])
     assert_raises(ValueError, minimum_phase, np.ones(10) * 1j)
     assert_raises(ValueError, minimum_phase, 'foo')
     assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8)
     assert_raises(ValueError, minimum_phase, np.ones(10), method='foo')
     assert_warns(RuntimeWarning, minimum_phase, np.arange(3))
def test_kaiserord():
    assert_raises(ValueError, kaiserord, 1.0, 1.0)
    numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1 / np.pi)
    assert_equal((numtaps, beta), (2, 0.0))
 def test_even_highpass_raises_value_error(self):
     """Test that attempt to create a highpass filter with an even number
     of taps raises a ValueError exception."""
     assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False)
     assert_raises(ValueError, firwin, 40, [.25, 0.5])
 def test_bad_args(self):
     assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka')
Пример #41
0
 def test_shape_argument_more(self):
     x = zeros((4, 4, 2))
     with assert_raises(ValueError,
                        match="when given, axes and shape arguments"
                        " have to be of the same length"):
         fftn(x, shape=(8, 8, 2, 1))
    def test_invalid_args(self):
        # `freq` and `gain` have different lengths.
        assert_raises(ValueError, firwin2, 50, [0, 0.5, 1], [0.0, 1.0])
        # `nfreqs` is less than `ntaps`.
        assert_raises(ValueError,
                      firwin2,
                      50, [0, 0.5, 1], [0.0, 1.0, 1.0],
                      nfreqs=33)
        # Decreasing value in `freq`
        assert_raises(ValueError, firwin2, 50, [0, 0.5, 0.4, 1.0],
                      [0, .25, .5, 1.0])
        # Value in `freq` repeated more than once.
        assert_raises(ValueError, firwin2, 50, [0, .1, .1, .1, 1.0],
                      [0.0, 0.5, 0.75, 1.0, 1.0])
        # `freq` does not start at 0.0.
        assert_raises(ValueError, firwin2, 50, [0.5, 1.0], [0.0, 1.0])

        # Type II filter, but the gain at nyquist frequency is not zero.
        assert_raises(ValueError, firwin2, 16, [0.0, 0.5, 1.0],
                      [0.0, 1.0, 1.0])

        # Type III filter, but the gains at nyquist and zero rate are not zero.
        assert_raises(ValueError,
                      firwin2,
                      17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0],
                      antisymmetric=True)
        assert_raises(ValueError,
                      firwin2,
                      17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0],
                      antisymmetric=True)
        assert_raises(ValueError,
                      firwin2,
                      17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0],
                      antisymmetric=True)

        # Type VI filter, but the gain at zero rate is not zero.
        assert_raises(ValueError,
                      firwin2,
                      16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0],
                      antisymmetric=True)
Пример #43
0
 def test_complex_input(self):
     assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
 def test_bad_cutoff(self):
     """Test that invalid cutoff argument raises ValueError."""
     # cutoff values must be greater than 0 and less than 1.
     assert_raises(ValueError, firwin, 99, -0.5)
     assert_raises(ValueError, firwin, 99, 1.5)
     # Don't allow 0 or 1 in cutoff.
     assert_raises(ValueError, firwin, 99, [0, 0.5])
     assert_raises(ValueError, firwin, 99, [0.5, 1])
     # cutoff values must be strictly increasing.
     assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2])
     assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5])
     # Must have at least one cutoff value.
     assert_raises(ValueError, firwin, 99, [])
     # 2D array not allowed.
     assert_raises(ValueError, firwin, 99, [[0.1, 0.2], [0.3, 0.4]])
     # cutoff values must be less than nyq.
     assert_raises(ValueError, firwin, 99, 50.0, nyq=40)
     assert_raises(ValueError, firwin, 99, [10, 20, 30], nyq=25)
     assert_raises(ValueError, firwin, 99, 50.0, fs=80)
     assert_raises(ValueError, firwin, 99, [10, 20, 30], fs=50)
Пример #45
0
 def test_datetime_timezone(self):
     assert_raises(ParseArffError, loadarff, test8)
Пример #46
0
 def test_invalid_sizes(self):
     assert_raises(ValueError, fft2, [[]])
     assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
Пример #47
0
def test_mat4_3d():
    # test behavior when writing 3-D arrays to matlab 4 files
    stream = BytesIO()
    arr = np.arange(24).reshape((2,3,4))
    assert_raises(ValueError, savemat, stream, {'a': arr}, True, '4')
Пример #48
0
 def test_invalid_sizes(self):
     assert_raises(ValueError, irfft, [])
     assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
Пример #49
0
def test_filenotfound():
    # Check the correct error is thrown
    assert_raises(OSError, loadmat, "NotExistentFile00.mat")
    assert_raises(OSError, loadmat, "NotExistentFile00")
Пример #50
0
    def test_dateheader_unsupported(self):
        def read_dateheader_unsupported():
            with open(test8) as ofile:
                _, _ = read_header(ofile)

        assert_raises(ValueError, read_dateheader_unsupported)
Пример #51
0
 def test_fft_n(self):
     assert_raises(ValueError, fft.fft, [1, 2, 3], 0)
Пример #52
0
def test_4_and_long_field_names_incompatible():
    # Long field names option not supported in 4
    my_struct = np.zeros((1,1),dtype=[('my_fieldname',object)])
    assert_raises(ValueError, savemat, BytesIO(),
                  {'my_struct':my_struct}, format='4', long_field_names=True)
Пример #53
0
 def test_bad_shapes(self):
     assert_raises(ValueError, companion, [[1, 1], [2, 2]])
     assert_raises(ValueError, companion, [0, 4, 5])
     assert_raises(ValueError, companion, [1])
     assert_raises(ValueError, companion, [])
Пример #54
0
def test_empty_mat_error():
    # Test we get a specific warning for an empty mat file
    sio = BytesIO()
    assert_raises(MatReadError, loadmat, sio)
Пример #55
0
    def test_incorrect_inputs(self):
        x = np.array([1, 2, 3, 4])
        y = np.array([1, 2, 3, 4])
        xc = np.array([1 + 1j, 2, 3, 4])
        xn = np.array([np.nan, 2, 3, 4])
        xo = np.array([2, 1, 3, 4])
        yn = np.array([np.nan, 2, 3, 4])
        y3 = [1, 2, 3]
        x1 = [1]
        y1 = [1]

        assert_raises(ValueError, CubicSpline, xc, y)
        assert_raises(ValueError, CubicSpline, xn, y)
        assert_raises(ValueError, CubicSpline, x, yn)
        assert_raises(ValueError, CubicSpline, xo, y)
        assert_raises(ValueError, CubicSpline, x, y3)
        assert_raises(ValueError, CubicSpline, x[:, np.newaxis], y)
        assert_raises(ValueError, CubicSpline, x1, y1)

        wrong_bc = [('periodic', 'clamped'),
                    ((2, 0), (3, 10)),
                    ((1, 0), ),
                    (0., 0.),
                    'not-a-typo']

        for bc_type in wrong_bc:
            assert_raises(ValueError, CubicSpline, x, y, 0, bc_type, True)

        # Shapes mismatch when giving arbitrary derivative values:
        Y = np.c_[y, y]
        bc1 = ('clamped', (1, 0))
        bc2 = ('clamped', (1, [0, 0, 0]))
        bc3 = ('clamped', (1, [[0, 0]]))
        assert_raises(ValueError, CubicSpline, x, Y, 0, bc1, True)
        assert_raises(ValueError, CubicSpline, x, Y, 0, bc2, True)
        assert_raises(ValueError, CubicSpline, x, Y, 0, bc3, True)

        # periodic condition, y[-1] must be equal to y[0]:
        assert_raises(ValueError, CubicSpline, x, y, 0, 'periodic', True)
Пример #56
0
 def test_bad_arg(self):
     assert_raises(ValueError, block_diag, [[[1]]])
Пример #57
0
def test_eigen_bad_kwargs():
    # Test eigen on wrong keyword argument
    A = csc_matrix(np.zeros((8, 8)))
    assert_raises(ValueError, eigs, A, which='XX')
Пример #58
0
 def test_bad_shapes(self):
     assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5])
     assert_raises(ValueError, leslie, [3, 4, 5], [[1, 1], [2, 2]])
     assert_raises(ValueError, leslie, [1, 2], [1, 2])
     assert_raises(ValueError, leslie, [1], [])
Пример #59
0
def test_eigen_bad_shapes():
    # A is not square.
    A = csc_matrix(np.zeros((2, 3)))
    assert_raises(ValueError, eigs, A)
Пример #60
0
def svd_test_input_check():
    x = np.array([[1, 2, 3], [3, 4, 3], [1, 0, 2], [0, 0, 1]], float)

    assert_raises(ValueError, svds, x, k=-1)
    assert_raises(ValueError, svds, x, k=0)
    assert_raises(ValueError, svds, x, k=10)
    assert_raises(ValueError, svds, x, k=x.shape[0])
    assert_raises(ValueError, svds, x, k=x.shape[1])
    assert_raises(ValueError, svds, x.T, k=x.shape[0])
    assert_raises(ValueError, svds, x.T, k=x.shape[1])