Exemplo n.º 1
0
def test_integrate_predefined(method, forgiveness, banded):
    use_jac = method in requires_jac
    k = k0, k1, k2 = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    f, j = _get_f_j(k)
    kwargs = {'method': method, 'dx0': 1e-10}
    if use_jac:
        if banded:
            jac_callbacks = [bandify(j, 1, 0), None]
            kwargs['lband'] = 1
            kwargs['uband'] = 0
        else:
            jac_callbacks = [j, None]
    else:
        jac_callbacks = [None]

    for j in jac_callbacks:
        xout = np.linspace(0, 3, 31)
        atol, rtol = 1e-8, 1e-8
        # Run twice to catch possible side-effects:
        yout, nfo = integrate_predefined(f, j, y0, xout, 1e-8, 1e-8, **kwargs)
        yout, nfo = integrate_predefined(f, j, y0, xout, 1e-8, 1e-8, **kwargs)
        yref = decay_get_Cref(k, y0, xout)
        assert np.allclose(yout, yref,
                           rtol=forgiveness*rtol,
                           atol=forgiveness*atol)
        assert nfo['nfev'] > 0
        assert nfo['time_cpu'] > 1e-9
        assert nfo['time_wall'] > 1e-9
        if method in requires_jac and j is not None:
            assert nfo['njev'] > 0
Exemplo n.º 2
0
def test_rhs_unrecoverable_error():
    def f(t, y, fout):
        fout[0] = y[0]
        return -1
    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, method='adams')
    with pytest.raises(RuntimeError):
        yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
Exemplo n.º 3
0
def test_rhs_unrecoverable_error():
    def f(t, y, fout):
        fout[0] = y[0]
        return -1
    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, method='adams')
    with pytest.raises(RuntimeError):
        yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
Exemplo n.º 4
0
def integrate_ivp(u0=1.0, v0=0.0, mu=1.0, tend=10.0, dt0=1e-8, nt=0,
                  nsteps=600, t0=0.0, atol=1e-8, rtol=1e-8, plot=False,
                  savefig='None', method='bdf', dpi=100, verbose=False):
    """
    Example program integrating an IVP problem of van der Pol oscillator
    """
    f, j = get_f_and_j(mu)
    if nt > 1:
        tout = np.linspace(t0, tend, nt)
        yout, nfo = integrate_predefined(
            f, j, [u0, v0], tout, dt0, atol, rtol, nsteps=nsteps,
            check_indexing=False, method=method)
    else:
        tout, yout, nfo = integrate_adaptive(
            f, j, [u0, v0], t0, tend, dt0, atol, rtol, nsteps=nsteps,
            check_indexing=False, method=method)  # dfdt[:] also for len == 1
    if verbose:
        print(nfo)
    if plot:
        import matplotlib.pyplot as plt
        plt.plot(tout, yout[:, 1], 'g--')
        plt.plot(tout, yout[:, 0], 'k-', linewidth=2)
        if savefig == 'None':
            plt.show()
        else:
            plt.savefig(savefig, dpi=dpi)
Exemplo n.º 5
0
def test_derivative_1():
    def f(t, y, fout):
        fout[0] = y[0]
    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, nderiv=1, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
    assert yout.shape == (3, 2, 1)
    ref = np.array([
        [[exp(0)], [exp(0)]],
        [[exp(1)], [exp(1)]],
        [[exp(2)], [exp(2)]],
    ])
    assert np.allclose(yout, ref)

    with pytest.raises(RuntimeError) as excinfo:
        integrate_predefined(f, None, [1], [0, 1, 2], nsteps=7, **kwargs)
    assert 'too_much_work' in str(excinfo.value).lower()
    assert '7' in str(excinfo.value).lower()
Exemplo n.º 6
0
def test_derivative_1():
    yout, info = integrate_predefined(_f1, None, [1], [0, 1, 2], **_kwargs1)
    assert yout.shape == (3, 2, 1)
    ref = np.array([
        [[exp(0)], [exp(0)]],
        [[exp(1)], [exp(1)]],
        [[exp(2)], [exp(2)]],
    ])
    assert np.allclose(yout, ref)
Exemplo n.º 7
0
def test_derivative_1():
    def f(t, y, fout):
        fout[0] = y[0]

    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, nderiv=1, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
    assert yout.shape == (3, 2, 1)
    ref = np.array([
        [[exp(0)], [exp(0)]],
        [[exp(1)], [exp(1)]],
        [[exp(2)], [exp(2)]],
    ])
    assert np.allclose(yout, ref)

    with pytest.raises(RuntimeError) as excinfo:
        integrate_predefined(f, None, [1], [0, 1, 2], nsteps=7, **kwargs)
    assert 'too_much_work' in str(excinfo.value).lower()
    assert '7' in str(excinfo.value).lower()
Exemplo n.º 8
0
def test_rhs_recoverable_error():
    global idx
    idx = -1

    def f(t, y, fout):
        global idx
        fout[0] = y[0]
        idx = idx + 1
        return 1 if 0 < idx < 3 else 0

    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
Exemplo n.º 9
0
def test_rhs_recoverable_error():
    global idx
    idx = -2

    def f(t, y, fout):
        global idx
        fout[0] = y[0]
        idx = idx + 1
        return 1 if 0 < idx < 3 else 0

    kwargs = dict(dx0=0.0, atol=1e-8, rtol=1e-8, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2], **kwargs)
Exemplo n.º 10
0
def test_sparse_jac_predefined():
    k = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    xout = np.linspace(0, 3, 31)
    atol, rtol = 1e-8, 1e-8
    f, _, j_sparse, nnz = _get_f_j(k, with_sparse=True)
    kwargs = dict(method='bdf', linear_solver='klu', nnz=nnz)
    yout, info = integrate_predefined(f, j_sparse, y0, xout, 1.0e-8, 1.0e-8, **kwargs)
    yref = decay_get_Cref(k, y0, xout - xout[0])
    assert info['success']
    assert info['njev'] > 0
    assert np.allclose(yout, yref, rtol=10*rtol, atol=10*atol)
Exemplo n.º 11
0
def test_integrate_predefined(method, forgiveness, banded):
    use_jac = method in requires_jac
    k = k0, k1, k2 = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    f, j = _get_f_j(k)
    kwargs = {'method': method, 'dx0': 1e-10}
    if use_jac:
        if banded:
            jac_callbacks = [bandify(j, 1, 0), None]
            kwargs['lband'] = 1
            kwargs['uband'] = 0
        else:
            jac_callbacks = [j, None]
    else:
        jac_callbacks = [None]

    for j in jac_callbacks:
        xout = np.linspace(0, 3, 31)
        if config['SUNDIALS_PRECISION'] == "single":
            atol = [1e-4, 3e-5, 2e-5]
            rtol = 1e-4
        else:
            atol = [1e-8, 3e-9, 2e-9]
            rtol = 1e-8
        if method == 'bdf':
            kwargs['stab_lim_det'] = True
        # Run twice to catch possible side-effects:
        yout, nfo = integrate_predefined(f, j, y0, xout, atol, rtol, **kwargs)
        yout, nfo = integrate_predefined(f, j, y0, xout, atol, rtol, **kwargs)
        yref = decay_get_Cref(k, y0, xout)
        assert np.allclose(yout,
                           yref,
                           rtol=forgiveness * rtol,
                           atol=forgiveness * max(atol))
        assert np.allclose(nfo['atol'], atol) and np.isclose(nfo['rtol'], rtol)
        assert nfo['nfev'] > 0
        if method in requires_jac and j is not None:
            assert nfo['njev'] > 0
            if os.name == 'posix':
                assert nfo['time_jac'] >= 0
Exemplo n.º 12
0
def integrate_ivp(u0=1.0,
                  v0=0.0,
                  mu=1.0,
                  tend=10.0,
                  dt0=1e-8,
                  nt=0,
                  nsteps=600,
                  t0=0.0,
                  atol=1e-8,
                  rtol=1e-8,
                  plot=False,
                  savefig='None',
                  method='bdf',
                  dpi=100,
                  verbose=False):
    """
    Example program integrating an IVP problem of van der Pol oscillator
    """
    f, j = get_f_and_j(mu)
    if nt > 1:
        tout = np.linspace(t0, tend, nt)
        yout, nfo = integrate_predefined(f,
                                         j, [u0, v0],
                                         tout,
                                         dt0,
                                         atol,
                                         rtol,
                                         nsteps=nsteps,
                                         check_indexing=False,
                                         method=method)
    else:
        tout, yout, nfo = integrate_adaptive(
            f,
            j, [u0, v0],
            t0,
            tend,
            dt0,
            atol,
            rtol,
            nsteps=nsteps,
            check_indexing=False,
            method=method)  # dfdt[:] also for len == 1
    if verbose:
        print(nfo)
    if plot:
        import matplotlib.pyplot as plt
        plt.plot(tout, yout[:, 1], 'g--')
        plt.plot(tout, yout[:, 0], 'k-', linewidth=2)
        if savefig == 'None':
            plt.show()
        else:
            plt.savefig(savefig, dpi=dpi)
Exemplo n.º 13
0
def test_integrate_predefined(method, forgiveness, banded):
    use_jac = method in requires_jac
    k = k0, k1, k2 = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    f, j = _get_f_j(k)
    kwargs = {'method': method, 'dx0': 1e-10}
    if use_jac:
        if banded:
            jac_callbacks = [bandify(j, 1, 0), None]
            kwargs['lband'] = 1
            kwargs['uband'] = 0
        else:
            jac_callbacks = [j, None]
    else:
        jac_callbacks = [None]

    for j in jac_callbacks:
        xout = np.linspace(0, 3, 31)
        atol, rtol = 1e-8, 1e-8
        # Run twice to catch possible side-effects:
        yout, nfo = integrate_predefined(f, j, y0, xout, [1e-8, 3e-9, 2e-9],
                                         1e-8, **kwargs)
        yout, nfo = integrate_predefined(f, j, y0, xout, [1e-8, 3e-9, 2e-9],
                                         1e-8, **kwargs)
        yref = decay_get_Cref(k, y0, xout)
        assert np.allclose(yout,
                           yref,
                           rtol=forgiveness * rtol,
                           atol=forgiveness * atol)
        assert nfo['atol'] == [1e-8, 3e-9, 2e-9] and nfo['rtol'] == 1e-8
        assert nfo['nfev'] > 0
        if os.name == 'posix':
            assert nfo['time_cpu'] > 1e-9
            assert nfo['time_wall'] > 1e-9
            assert nfo['time_rhs'] > 1e-9
        if method in requires_jac and j is not None:
            assert nfo['njev'] > 0
            if os.name == 'posix':
                assert nfo['time_jac'] > 1e-9
Exemplo n.º 14
0
def test_roots_predefined_autorestart():
    def f(t, y, fout):
        fout[0] = y[0]

    def roots(t, y, out):
        out[0] = y[0] - exp(1)
    kwargs = dict(dx0=1e-12, atol=1e-12, rtol=1e-12, method='adams',
                  roots=roots, nroots=1, nsteps=3, autorestart=4)
    xout = [0, 0.5, 1.5, 2]
    yout, info = integrate_predefined(f, None, [1], xout, **kwargs)
    discrepancy = np.exp(xout) - yout.flatten()
    assert np.allclose(discrepancy, 0)
    assert len(info['root_indices']) == 1
    assert info['root_indices'][0] == 2
Exemplo n.º 15
0
def test_derivative_2():
    def f(t, y, fout):
        fout[0] = y[0]
    kwargs = dict(dx0=0.0, atol=1e-12, rtol=1e-12, nderiv=3, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2, 3, 4], **kwargs)
    assert yout.shape == (5, 4, 1)
    ref = np.array([
        [[exp(0)], [exp(0)], [0], [0]],  # higher order deriv. skipped for t0
        [[exp(1)]]*4,
        [[exp(2)]]*4,
        [[exp(3)]]*4,
        [[exp(4)]]*4,
    ])
    assert np.allclose(yout, ref)
Exemplo n.º 16
0
def test_roots_predefined():
    def f(t, y, fout):
        fout[0] = y[0]

    def roots(t, y, out):
        out[0] = y[0] - exp(1)
    kwargs = dict(dx0=1e-12, atol=1e-12, rtol=1e-12, method='adams',
                  roots=roots, nroots=1)
    xout = [0, 0.5, 1.5, 2]
    yout, info = integrate_predefined(f, None, [1], xout, **kwargs)
    discrepancy = np.exp(xout) - yout.flatten()
    assert np.allclose(discrepancy, 0)
    assert len(info['root_indices']) == 1
    assert info['root_indices'][0] == 2
Exemplo n.º 17
0
def test_derivative_2():
    def f(t, y, fout):
        fout[0] = y[0]
    kwargs = dict(dx0=0.0, atol=1e-12, rtol=1e-12, nderiv=3, method='adams')
    yout, info = integrate_predefined(f, None, [1], [0, 1, 2, 3, 4], **kwargs)
    assert yout.shape == (5, 4, 1)
    ref = np.array([
        [[exp(0)], [exp(0)], [0], [0]],  # higher order deriv. skipped for t0
        [[exp(1)]]*4,
        [[exp(2)]]*4,
        [[exp(3)]]*4,
        [[exp(4)]]*4,
    ])
    assert np.allclose(yout, ref)
Exemplo n.º 18
0
def test_predefined_ew_ele():
    k = 2.0, 3.0, 4.0
    y0 = [0.7, 0., 0.]
    atol, rtol = 1e-8, 1e-8
    kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol, method='bdf', ew_ele=True)
    f, j = _get_f_j(k)
    xout = np.logspace(-3, 1)
    yout, info = integrate_predefined(f, j, y0, xout, **kwargs)
    yref = decay_get_Cref(k, y0, xout - xout[0])
    assert np.allclose(yout, yref, rtol=10 * rtol, atol=10 * atol)
    assert yout.shape[0] == xout.size
    assert info['nfev'] > 0
    assert info['njev'] > 0
    assert info['success']
    abs_ew_ele = np.abs(np.prod(info['ew_ele'], axis=1))
    assert np.all(abs_ew_ele < 1)
Exemplo n.º 19
0
def test_predefined_roots_output():
    def f(t, y, fout):
        fout[0] = y[0]

    def roots(t, y, out):
        out[0] = y[0] - exp(1)

    kwargs = dict(dx0=1e-12, atol=1e-12, rtol=1e-12,
                  method='adams', roots=roots, nroots=1)

    yout, info = integrate_predefined(f, None, [1], [0, 2], **kwargs)
    assert len(info['root_indices']) == 1
    roots_x, roots_y = info['roots_output']
    assert roots_x.shape == (1,)
    assert roots_y.shape == (1, 1)
    assert abs(roots_x[-1] - 1) < 1e-11
    assert abs(roots_y[-1, 0] - exp(1)) < 1e-11
Exemplo n.º 20
0
def test_predefined_roots_output():
    def f(t, y, fout):
        fout[0] = y[0]

    def roots(t, y, out):
        out[0] = y[0] - exp(1)

    kwargs = dict(dx0=1e-12, atol=1e-12, rtol=1e-12,
                  method='adams', roots=roots, nroots=1)

    yout, info = integrate_predefined(f, None, [1], [0, 2], **kwargs)
    assert len(info['root_indices']) == 1
    roots_x, roots_y = info['roots_output']
    assert roots_x.shape == (1,)
    assert roots_y.shape == (1, 1)
    assert abs(roots_x[-1] - 1) < 1e-11
    assert abs(roots_y[-1, 0] - exp(1)) < 1e-11
Exemplo n.º 21
0
def test_predefined_return_on_error():
    k = 2.0, 3.0, 4.0
    y0 = [0.7, 0., 0.]
    atol, rtol = 1e-8, 1e-8
    kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol,
                  method='bdf', return_on_error=True, nsteps=7)
    f, j = _get_f_j(k)
    xout = np.logspace(-3, 1)
    yout, info = integrate_predefined(f, j, y0, xout, **kwargs)
    yref = decay_get_Cref(k, y0, xout - xout[0])
    assert np.allclose(yout[:info['nreached'], :], yref[:info['nreached'], :],
                       rtol=10*rtol,
                       atol=10*atol)
    assert 10 < info['nreached'] < 40
    assert yout.shape[0] == xout.size
    assert info['nfev'] > 0
    assert info['njev'] > 0
    assert info['success'] is False
Exemplo n.º 22
0
def test_jtimes_predefined(linear_solver, with_jac):
    g = 9.81
    y0 = [1000.0, 0.0]
    atol, rtol = 1e-8, 1e-8
    f, jac, jtimes = _gravity_f_j_jtimes(g)
    if not with_jac:
        jac = None
    kwargs = dict(atol=atol, rtol=rtol,
                  method='bdf', linear_solver=linear_solver,
                  jtimes=jtimes)
    tout = np.linspace(0, 10, 100)
    yout, info = integrate_predefined(f, jac, y0, tout, **kwargs)
    yref = gravity_analytic(g, y0, tout)
    assert np.allclose(yout, yref, rtol=10*rtol, atol=10*atol)
    assert info['success']
    assert info['njvev'] > 0
    if not with_jac:
        assert info['njev'] == 0
Exemplo n.º 23
0
def test_predefined_return_on_error():
    k = 2.0, 3.0, 4.0
    y0 = [0.7, 0., 0.]
    atol, rtol = 1e-8, 1e-8
    kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol,
                  method='bdf', return_on_error=True, nsteps=7)
    f, j = _get_f_j(k)
    xout = np.logspace(-3, 1)
    yout, info = integrate_predefined(f, j, y0, xout, **kwargs)
    yref = decay_get_Cref(k, y0, xout - xout[0])
    assert np.allclose(yout[:info['nreached'], :], yref[:info['nreached'], :],
                       rtol=10*rtol,
                       atol=10*atol)
    assert 10 < info['nreached'] < 40
    assert yout.shape[0] == xout.size
    assert info['nfev'] > 0
    assert info['njev'] > 0
    assert info['success'] is False
Exemplo n.º 24
0
def test_quads_predefined():
    k = 0.7

    def f(t, y, fout):
        fout[0] = -0.7*y[0]

    def quads(t, y, out):
        out[0] = t*y[0]
        out[1] = y[0]**2

    kwargs = dict(dx0=1e-12, atol=1e-12, rtol=1e-12, method='adams',
                  quads=quads, nquads=2)
    A, t0, duration = 42, 0, 4
    t = np.linspace(t0, duration, 37)
    yout, info = integrate_predefined(f, None, [A, 0, 0], t, **kwargs)
    assert np.allclose(yout[:, 0], 42*np.exp(-k*t))
    q0 = A/k**2 + (-A*k**2*t - A*k)*np.exp(-k*t)/k**3
    q1 = (1.0/2.0)*A**2/k - 1.0/2.0*A**2*np.exp(-2*k*t)/k
    assert np.allclose(info['quads'][:, 0], q0)
    assert np.allclose(info['quads'][:, 1], q1)
Exemplo n.º 25
0
def test_predefined_autorestart():
    k = k0, k1, k2 = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    atol, rtol = 1e-8, 1e-8
    x0, xend = 0, 3
    kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol,
                  method='BDF', nsteps=62,
                  autorestart=10)
    f, j = _get_f_j(k)
    xout = np.linspace(x0, xend)
    yout, info = integrate_predefined(f, j, y0, xout, **kwargs)
    yref = decay_get_Cref(k, y0, xout)
    assert np.allclose(yout, yref,
                       rtol=10*rtol,
                       atol=10*atol)
    assert xout[-1] > 1e-6
    assert yout.shape[0] == xout.size
    assert info['nfev'] > 0
    assert info['njev'] > 0
    assert info['success']
    assert xout[-1] == xend
Exemplo n.º 26
0
def test_predefined_autorestart():
    k = k0, k1, k2 = 2.0, 3.0, 4.0
    y0 = [0.7, 0.3, 0.5]
    atol, rtol = 1e-8, 1e-8
    x0, xend = 0, 3
    kwargs = dict(dx0=1e-10, atol=atol, rtol=rtol,
                  method='BDF', nsteps=7,
                  autorestart=10)
    f, j = _get_f_j(k)
    xout = np.linspace(x0, xend)
    yout, info = integrate_predefined(f, j, y0, xout, **kwargs)
    yref = decay_get_Cref(k, y0, xout)
    assert np.allclose(yout, yref,
                       rtol=10*rtol,
                       atol=10*atol)
    assert xout[-1] > 1e-6
    assert yout.shape[0] == xout.size
    assert info['nfev'] > 0
    assert info['njev'] > 0
    assert info['success']
    assert xout[-1] == xend
Exemplo n.º 27
0
def test_derivative_1__exception():
    with pytest.raises(RuntimeError) as excinfo:
        integrate_predefined(_f1, None, [1], [0, 1, 2], nsteps=7, **_kwargs1)
    assert 'too_much_work' in str(excinfo.value).lower()
    assert '7' in str(excinfo.value).lower()