Esempio n. 1
0
    def test_problem_name_attribute(self):
        rhs = lambda t, y: y

        prob = Explicit_Problem(rhs, 0.0)
        assert prob.name == "---"
        prob = Explicit_Problem(rhs, 0.0, name="Test")
        assert prob.name == "Test"
Esempio n. 2
0
 def setUp(self):
     """
     This sets up the test case.
     """
     def f(t,y):
         eps = 1.e-6
         my = 1./eps
         yd_0 = y[1]
         yd_1 = my*((1.-y[0]**2)*y[1]-y[0])
         
         return N.array([yd_0,yd_1])
     
     def jac(t,y):
         eps = 1.e-6
         my = 1./eps
         J = N.zeros([2,2])
         
         J[0,0]=0.
         J[0,1]=1.
         J[1,0]=my*(-2.*y[0]*y[1]-1.)
         J[1,1]=my*(1.-y[0]**2)
         
         return J
     
     def jac_sparse(t,y):
         eps = 1.e-6
         my = 1./eps
         J = N.zeros([2,2])
         
         J[0,0]=0.
         J[0,1]=1.
         J[1,0]=my*(-2.*y[0]*y[1]-1.)
         J[1,1]=my*(1.-y[0]**2)
         
         return sp.csc_matrix(J)
     
     #Define an Assimulo problem
     y0 = [2.0,-0.6] #Initial conditions
     
     exp_mod = Explicit_Problem(f,y0)
     exp_mod_t0 = Explicit_Problem(f,y0,1.0)
     exp_mod_sp = Explicit_Problem(f,y0)
     
     exp_mod.jac = jac
     exp_mod_sp.jac = jac_sparse
     self.mod = exp_mod
         
     #Define an explicit solver
     self.sim = Radau5ODE(exp_mod) #Create a Radau5 solve
     self.sim_t0 = Radau5ODE(exp_mod_t0)
     self.sim_sp = Radau5ODE(exp_mod_sp)
     
     #Sets the parameters
     self.sim.atol = 1e-4 #Default 1e-6
     self.sim.rtol = 1e-4 #Default 1e-6
     self.sim.inith = 1.e-4 #Initial step-size
     self.sim.usejac = False
Esempio n. 3
0
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Explicit_Problem(self.rhs, self.y0)
        problem.name = 'RK34'
        problem.handle_result = self.handle_result
        problem.handle_event = self.handle_event
        problem.time_events = self.time_events
        problem.finalize = self.finalize

        if hasattr(self, 'state_events'):
            print 'Warning: state_event function in RK34 is not supported and will be ignored!'

        simulation = RungeKutta34(problem)

        # Sets additional parameters
        simulation.atol = self.atol
        simulation.rtol = self.rtol
        simulation.verbosity = self.verbosity
        if hasattr(simulation, 'continuous_output'):
            simulation.continuous_output = False  # default 0, if one step approach should be used
        elif hasattr(simulation, 'report_continuously'):
            simulation.report_continuously = False  # default 0, if one step approach should be used
        simulation.inith = self.inith

        # Calculate nOutputIntervals:
        if gridWidth <> None:
            nOutputIntervals = int((Tend - self.t0) / gridWidth)
        else:
            nOutputIntervals = nIntervals
        # Check for feasible input parameters
        if nOutputIntervals == 0:
            print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1'
            nOutputIntervals = 1
        # Perform simulation
        simulation.simulate(Tend, nOutputIntervals)  # to get the values: t_new, y_new = simulation.simulate
def ode_sim(t_final):
    y0 = get_initial()  # initial conditions from Parameter.py
    t0 = 0.0
    param = new_param()

    ecoli_ode = lambda t, x: rhs(t, x, param)
    model = Explicit_Problem(ecoli_ode, y0, t0)  # Create an Assimulo problem
    model.name = 'E Coli ODE'
    sim = CVode(model)  # Create the solver CVode

    sim.rtol = 1e-8
    sim.atol = 1e-8
#    pdb.set_trace()
    t, y = sim.simulate(t_final)  # Use the .simulate method to simulate and provide the final time

    # Plot
    met_labels = ["ACCOA", "ACEx", "ACO", "ACP", "ADP", "AKG", "AMP", "ASP", "ATP", "BPG", "CAMP", "CIT", "COA", "CYS",
                  "DAP", "E4P", "ei", "eiia", "eiiaP", "eiicb", "eiicbP", "eiP", "F6P", "FDP", "FUM", "G6P", "GAP",
                  "GL6P", "GLCx", "GLX", "HCO3", "hpr", "hprP", "icd", "icdP", "ICIT", "KDPG", "MAL", "MG", "MN", "NAD",
                  "NADH", "NADP", "NADPH", "OAA", "P", "PEP", "PGA2", "PGA3", "PGN", "PYR", "PYRx", "Q", "QH2", "R5P",
                  "RU5P", "S7P", "SUC", "SUCCOA", "SUCx", "tal", "talC3", "tkt", "tktC2", "X5P", "Px", "Pp", "GLCp",
                  "ACEp", "ACE", "Hc", "Hp", "FAD", "FADH2", "O2", "FEED"]

    for i in y:
        if i.any() < 0:
            print i

    plt.plot([t, t], [y[:, i] for i in [4, 9]], label=["ADP", "ATP"])
    plt.title('Metabolite Concentrations Over Time')
    plt.xlabel('Time')
    plt.ylabel('Concentration')
    plt.legend()
    plt.savefig('concentration.png')

    return model, sim
Esempio n. 5
0
    def test_elapsed_step_time(self):
        rhs = lambda t, y: y

        prob = Explicit_Problem(rhs, 0.0)
        solv = Explicit_ODE(prob)

        assert solv.get_elapsed_step_time() == -1.0
Esempio n. 6
0
def run_example(with_plots=True):

    #Defines the rhs
    def f(t, y):
        ydot = -y[0]
        return N.array([ydot])

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f, 4.0)
    exp_mod.name = 'Simple Explicit Example'

    #Explicit Euler
    exp_sim = ExplicitEuler(exp_mod)  #Create a explicit Euler solver
    exp_sim.options["continuous_output"] = True

    #Simulate
    t1, y1 = exp_sim.simulate(3)  #Simulate 3 seconds
    t2, y2 = exp_sim.simulate(5, 100)  #Simulate 2 second more

    #Basic test
    nose.tools.assert_almost_equal(y2[-1], 0.02628193)

    #Plot
    if with_plots:
        P.plot(t1, y1, color="b")
        P.plot(t2, y2, color="b")
        P.show()
Esempio n. 7
0
    def __init__(self,
                 rhs,
                 output_dt,
                 solver_dt,
                 y0,
                 args,
                 t0=0.,
                 console=False,
                 terminate=False,
                 terminate_depth=100.,
                 **kwargs):
        self.terminate = terminate
        super(CVODEIntegrator, self).__init__(rhs, output_dt, solver_dt, y0,
                                              args, t0, console)

        # Setup solver
        if terminate:
            self.prob = ExtendedProblem(self.rhs,
                                        self.args,
                                        terminate_depth,
                                        y0=self.y0)
        else:
            self.prob = Explicit_Problem(self.rhs, self.y0)

        self.sim = self._setup_sim(**kwargs)

        self.kwargs = kwargs
Esempio n. 8
0
def run_example(with_plots=True):
    global exp_mod, exp_sim

    #Define the rhs
    def f(t, y):
        ydot = -y[0]
        return N.array([ydot])

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f, y0=4)
    exp_mod.name = 'Simple CVode Example'

    #Define an explicit solver
    exp_sim = CVode(exp_mod)  #Create a CVode solver

    #Sets the parameters
    exp_sim.iter = 'Newton'  #Default 'FixedPoint'
    exp_sim.discr = 'BDF'  #Default 'Adams'
    exp_sim.atol = [1e-4]  #Default 1e-6
    exp_sim.rtol = 1e-4  #Default 1e-6

    #Simulate
    t1, y1 = exp_sim.simulate(5, 100)  #Simulate 5 seconds
    t2, y2 = exp_sim.simulate(7)  #Simulate 2 seconds more

    #Basic test
    nose.tools.assert_almost_equal(y2[-1], 0.00347746, 5)
Esempio n. 9
0
def simulate_ode(fun, y_initial, tf, opts):
    "function to run CVode solver on given problem"
    # get options
    ode_opts, ode_system_options = opts
    # iter, discretization_method, atol, rtol, time_points = ode_opts
    iter = ode_opts["iter"]
    discretization_method = ode_opts["discr"]
    atol = ode_opts["atol"]
    rtol = ode_opts["rtol"]
    time_points = ode_opts["time_points"]
    try:
        display_progress = ode_opts["display_progress"]
    except KeyError:
        display_progress = True
    try:
        verbosity = ode_opts["verbosity"]
    except KeyError:
        verbosity = 10

    # define explicit assimulo problem
    prob = Explicit_Problem(lambda t, x: fun(t, x, ode_system_options),
                            y0=y_initial)

    # create solver instance
    solver = CVode(prob)

    # set solver options
    solver.iter, solver.discr, solver.atol, solver.rtol, solver.display_progress, solver.verbosity = \
        iter, discretization_method, atol, rtol, display_progress, verbosity

    # simulate system
    time_course, y_result = solver.simulate(tf, time_points)

    return time_course, y_result, prob, solver
Esempio n. 10
0
    def test_usejac_csc_matrix(self):
        """
        This tests the functionality of the property usejac.
        """
        f = lambda t, x: N.array([x[1], -9.82])  #Defines the rhs
        jac = lambda t, x: sp.csc_matrix(N.array([[0., 1.], [0., 0.]])
                                         )  #Defines the jacobian

        exp_mod = Explicit_Problem(f, [1.0, 0.0])
        exp_mod.jac = jac

        exp_sim = CVode(exp_mod)
        exp_sim.discr = 'BDF'
        exp_sim.iter = 'Newton'
        exp_sim.simulate(5., 100)

        assert exp_sim.statistics["nfcnjacs"] == 0
        nose.tools.assert_almost_equal(exp_sim.y_sol[-1][0], -121.75000143, 4)

        exp_sim.reset()
        exp_sim.usejac = False
        exp_sim.simulate(5., 100)

        nose.tools.assert_almost_equal(exp_sim.y_sol[-1][0], -121.75000143, 4)
        assert exp_sim.statistics["nfcnjacs"] > 0
Esempio n. 11
0
    def test_completed_step(self):
        """
        This tests the functionality of the method completed_step.
        """
        global nsteps
        nsteps = 0
        f = lambda t, x: x**0.25

        def completed_step(solver):
            global nsteps
            nsteps += 1

        mod = Explicit_Problem(f, 1.0)
        mod.step_events = completed_step

        sim = CVode(mod)

        sim.simulate(2., 100)
        assert len(sim.t_sol) == 101
        assert nsteps == sim.statistics["nsteps"]

        sim = CVode(mod)
        nsteps = 0
        sim.simulate(2.)
        assert len(sim.t_sol) == sim.statistics["nsteps"] + 1
        assert nsteps == sim.statistics["nsteps"]
def run_example(with_plots=True):
    r"""
    Example for the use of the implicit Euler method to solve
    Van der Pol's equation
    
    .. math::
       
        \dot y_1 &= y_2 \\
        \dot y_2 &= \mu ((1.-y_1^2) y_2-y_1)

    with :math:`\mu= 10^6`.

    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance

    """

    #Define the rhs
    def f(t, y):
        eps = 1.e-6
        my = 1. / eps
        yd_0 = y[1]
        yd_1 = my * ((1. - y[0]**2) * y[1] - y[0])

        return N.array([yd_0, yd_1])

    y0 = [2.0, -0.6]  #Initial conditions

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f, y0)
    exp_mod.name = 'Van der Pol (explicit)'

    #Define an explicit solver
    exp_sim = Radau5ODE(exp_mod)  #Create a Radau5 solver

    #Sets the parameters
    exp_sim.atol = 1e-4  #Default 1e-6
    exp_sim.rtol = 1e-4  #Default 1e-6
    exp_sim.inith = 1.e-4  #Initial step-size

    #Simulate
    t, y = exp_sim.simulate(2.)  #Simulate 2 seconds

    #Plot
    if with_plots:
        import pylab as P
        P.plot(t, y[:, 0])  #, marker='o')
        P.xlabel('Time')
        P.ylabel('State')
        P.title(exp_mod.name)
        P.show()

    #Basic test
    x1 = y[:, 0]
    assert N.abs(x1[-1] - 1.706168035) < 1e-3  #For test purpose

    return exp_mod, exp_sim
Esempio n. 13
0
    def test_time_event(self):
        f = lambda t, y: [1.0]
        global tnext
        global nevent
        tnext = 0.0
        nevent = 0

        def time_events(t, y, sw):
            global tnext, nevent
            events = [1.0, 2.0, 2.5, 3.0]
            for ev in events:
                if t < ev:
                    tnext = ev
                    break
                else:
                    tnext = None
            nevent += 1
            return tnext

        def handle_event(solver, event_info):
            solver.y += 1.0
            global tnext
            nose.tools.assert_almost_equal(solver.t, tnext)
            assert event_info[0] == []
            assert event_info[1] == True

        exp_mod = Explicit_Problem(f, 0.0)
        exp_mod.time_events = time_events
        exp_mod.handle_event = handle_event

        #CVode
        exp_sim = CVode(exp_mod)
        exp_sim(5., 100)

        assert nevent == 5
Esempio n. 14
0
def run_example(with_plots=True):
    r"""
    Example for the use of LSODAR method to solve
    Van der Pol's equation
    
    .. math::
       
        \dot y_1 &= y_2 \\
        \dot y_2 &= \mu ((1.-y_1^2) y_2-y_1)

    with :math:`\mu=\frac{1}{5} 10^3`.

    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance

    """

    #Define the rhs
    def f(t, y):
        eps = 1.e-6
        my = 1. / eps
        yd_0 = y[1]
        yd_1 = my * ((1. - y[0]**2) * y[1] - y[0])

        return N.array([yd_0, yd_1])

    y0 = [2.0, -0.6]  #Initial conditions

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f, y0, name="LSODAR: Van der Pol's equation")

    #Define an explicit solver
    exp_sim = LSODAR(exp_mod)  #Create a Radau5 solver

    #Sets the parameters
    exp_sim.atol = 1e-4  #Default 1e-6
    exp_sim.rtol = 1e-4  #Default 1e-6

    #Simulate
    t, y = exp_sim.simulate(2.)  #Simulate 2 seconds

    #Plot
    if with_plots:
        P.plot(t, y[:, 0], marker='o')
        P.title(exp_mod.name)
        P.ylabel("State: $y_1$")
        P.xlabel("Time")
        P.show()

    #Basic test
    x1 = y[:, 0]
    assert N.abs(x1[-1] - 1.706168035) < 1e-3  #For test purpose

    return exp_mod, exp_sim
Esempio n. 15
0
    def setUp(self):
        """
        This function sets up the test case.
        """
        f = lambda t, y: N.array(y)
        y0 = [1.0]

        self.problem = Explicit_Problem(f, y0)
        self.simulator = CVode(self.problem)
Esempio n. 16
0
    def setUp(self):
        """
        This function sets up the test case.
        """
        f = lambda t, y: 1.0
        y0 = 1

        self.problem = Explicit_Problem(f, y0)
        self.simulator = Dopri5(self.problem)
Esempio n. 17
0
    def test_backward_integration(self):
        def f(t, y):
            x, v = y
            return [x, -x - 0.1 * v]

        mod = Explicit_Problem(f, y0=[1, 0], t0=10)
        sim = CVode(mod)
        sim.backward = True
        t, y = sim.simulate(0, ncp_list=np.arange(1, 10))

        assert np.all(t == np.arange(0, 11)[::-1])

        mod = Explicit_Problem(f, y0=[1, 0], t0=10)
        sim = CVode(mod)
        sim.backward = True
        t, y = sim.simulate(0, ncp_list=np.arange(1, 10)[::-1])

        assert np.all(t == np.arange(0, 11)[::-1])
Esempio n. 18
0
 def test_ncp_list(self):
     f = lambda t,y:N.array(-y)
     y0 = [4.0]
     
     prob = Explicit_Problem(f,y0)
     sim = CVode(prob)
     
     t, y = sim.simulate(7, ncp_list=N.arange(0, 7, 0.1)) #Simulate 5 seconds
     
     nose.tools.assert_almost_equal(float(y[-1]), 0.00364832, 4)
Esempio n. 19
0
    def _assimulo_problem(self):
        rhs = self._problem.right_hand_side_as_function
        parameters = self._parameters
        initial_conditions = self._initial_conditions
        initial_timepoint = self._starting_time

        model = Explicit_Problem(lambda t, x: rhs(x, parameters),
                                 initial_conditions, initial_timepoint)

        return model
Esempio n. 20
0
    def test_time_limit(self):
        f = lambda t, y: -y

        exp_mod = Explicit_Problem(f, 1.0)
        exp_sim = CVode(exp_mod)

        exp_sim.maxh = 1e-8
        exp_sim.time_limit = 1  #One second
        exp_sim.report_continuously = True

        nose.tools.assert_raises(TimeLimitExceeded, exp_sim.simulate, 1)
Esempio n. 21
0
    def setUp(self):
        """
        This sets up the test case.
        """

        f = lambda t,y:[1.0,2.0]

        #Define an Assimulo problem
        y0 = [2.0,-0.6] #Initial conditions
        exp_mod = Explicit_Problem(f,y0)
        self.sim = Radau5ODE(exp_mod)
Esempio n. 22
0
    def test_exception(self):
        """
        This tests that exceptions are no caught when evaluating the RHS in ExpEuler.
        """
        def f(t, y):
            raise NotImplementedError

        prob = Explicit_Problem(f, 0.0)
        sim = ExplicitEuler(prob)

        nose.tools.assert_raises(NotImplementedError, sim.simulate, 1.0)
Esempio n. 23
0
    def setUp(self):
        #Define the rhs
        def f(t, y):
            eps = 1.e-6
            my = 1. / eps
            yd_0 = y[1]
            yd_1 = my * ((1. - y[0]**2) * y[1] - y[0])

            return N.array([yd_0, yd_1])

        #Define the jacobian
        def jac(t, y):
            eps = 1.e-6
            my = 1. / eps
            j = N.array(
                [[0.0, 1.0],
                 [my * ((-2.0 * y[0]) * y[1] - 1.0), my * (1.0 - y[0]**2)]])
            return j

        def jac_sparse(t, y):
            eps = 1.e-6
            my = 1. / eps
            J = N.zeros([2, 2])

            J[0, 0] = 0.
            J[0, 1] = 1.
            J[1, 0] = my * (-2. * y[0] * y[1] - 1.)
            J[1, 1] = my * (1. - y[0]**2)

            return sp.csc_matrix(J)

        y0 = [2.0, -0.6]  #Initial conditions

        #Define an Assimulo problem
        exp_mod = Explicit_Problem(f, y0, name='Van der Pol (explicit)')
        exp_mod_sp = Explicit_Problem(f, y0, name='Van der Pol (explicit)')
        exp_mod.jac = jac
        exp_mod_sp.jac = jac_sparse
        self.mod = exp_mod
        self.mod_sp = exp_mod_sp
Esempio n. 24
0
    def test_spgmr(self):
        f = lambda t, y: N.array([y[1], -9.82])
        fsw = lambda t, y, sw: N.array([y[1], -9.82])
        fp = lambda t, y, p: N.array([y[1], -9.82])
        fswp = lambda t, y, sw, p: N.array([y[1], -9.82])
        jacv = lambda t, y, fy, v: N.dot(N.array([[0, 1.], [0, 0]]), v)
        jacvsw = lambda t, y, fy, v, sw: N.dot(N.array([[0, 1.], [0, 0]]), v)
        jacvp = lambda t, y, fy, v, p: N.dot(N.array([[0, 1.], [0, 0]]), v)
        jacvswp = lambda t, y, fy, v, sw, p: N.dot(N.array([[0, 1.], [0, 0]]),
                                                   v)
        y0 = [1.0, 0.0]  #Initial conditions

        def run_sim(exp_mod):
            exp_sim = CVode(exp_mod)  #Create a CVode solver
            exp_sim.linear_solver = 'SPGMR'  #Change linear solver

            #Simulate
            t, y = exp_sim.simulate(
                5, 1000)  #Simulate 5 seconds with 1000 communication points

            #Basic tests
            nose.tools.assert_almost_equal(y[-1][0], -121.75000000, 4)
            nose.tools.assert_almost_equal(y[-1][1], -49.100000000)

        exp_mod = Explicit_Problem(f, y0)
        exp_mod.jacv = jacv  #Sets the jacobian
        run_sim(exp_mod)

        #Need someway of suppressing error messages from deep down in the Cython wrapper
        #See http://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer
        try:
            from cStringIO import StringIO
        except ImportError:
            from io import StringIO
        import sys
        stderr = sys.stderr
        sys.stderr = StringIO()

        exp_mod = Explicit_Problem(f, y0)
        exp_mod.jacv = jacvsw  #Sets the jacobian
        nose.tools.assert_raises(CVodeError, run_sim, exp_mod)

        exp_mod = Explicit_Problem(fswp, y0, sw0=[True], p0=1.0)
        exp_mod.jacv = jacvsw  #Sets the jacobian
        nose.tools.assert_raises(CVodeError, run_sim, exp_mod)

        #Restore standard error
        sys.stderr = stderr

        exp_mod = Explicit_Problem(fp, y0, p0=1.0)
        exp_mod.jacv = jacvp  #Sets the jacobian
        run_sim(exp_mod)

        exp_mod = Explicit_Problem(fsw, y0, sw0=[True])
        exp_mod.jacv = jacvsw  #Sets the jacobian
        run_sim(exp_mod)

        exp_mod = Explicit_Problem(fswp, y0, sw0=[True], p0=1.0)
        exp_mod.jacv = jacvswp  #Sets the jacobian
        run_sim(exp_mod)
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Explicit_Problem(self.rhs, self.y0)
        problem.name = 'CVode'
        # solver.rhs = self.right_hand_side
        problem.handle_result = self.handle_result
        problem.state_events = self.state_events
        problem.handle_event = self.handle_event
        problem.time_events = self.time_events
        problem.finalize = self.finalize

        simulation = CVode(problem)

        # Change multistep method: 'adams' or 'VDF'
        if self.discr == 'Adams':
            simulation.discr = 'Adams'
            simulation.maxord = 12
        else:
            simulation.discr = 'BDF'
            simulation.maxord = 5
        # Change iteration algorithm: functional(FixedPoint) or newton
        if self.iter == 'FixedPoint':
            simulation.iter = 'FixedPoint'
        else:
            simulation.iter = 'Newton'

        # Sets additional parameters
        simulation.atol = self.atol
        simulation.rtol = self.rtol
        simulation.verbosity = self.verbosity
        if hasattr(simulation, 'continuous_output'):
            simulation.continuous_output = False  # default 0, if one step approach should be used
        elif hasattr(simulation, 'report_continuously'):
            simulation.report_continuously = False  # default 0, if one step approach should be used

        # '''Initialize problem '''
        # self.t_cur = self.t0
        # self.y_cur = self.y0

        # Calculate nOutputIntervals:
        if gridWidth <> None:
            nOutputIntervals = int((Tend - self.t0) / gridWidth)
        else:
            nOutputIntervals = nIntervals
        # Check for feasible input parameters
        if nOutputIntervals == 0:
            print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1'
            nOutputIntervals = 1
        # Perform simulation
        simulation.simulate(
            Tend, nOutputIntervals
        )  # to get the values: t_new, y_new = simulation.simulate
Esempio n. 26
0
    def _assimulo_problem(self):
        rhs = self._problem.right_hand_side_as_function
        parameters = self._parameters
        initial_conditions = self._initial_conditions
        initial_timepoint = self._starting_time

        # Solvers with sensitivity support should be able to accept parameters
        # into rhs function directly
        model = Explicit_Problem(lambda t, x, p: rhs(x, p), initial_conditions,
                                 initial_timepoint)

        model.p0 = np.array(parameters)
        return model
Esempio n. 27
0
    def test_stiff_problem(self):
        f = lambda t, y: -15.0 * y
        y0 = 1.0

        problem = Explicit_Problem(f, y0)
        simulator = ImplicitEuler(problem)

        t, y = simulator.simulate(1)

        y_correct = lambda t: N.exp(-15 * t)

        abs_err = N.abs(y[:, 0] - y_correct(N.array(t)))
        assert N.max(abs_err) < 0.1
Esempio n. 28
0
def simulate_prob(t_start, t_stop, x0, p, ncp, with_plots=False):
    """Simulates the problem using Assimulo.

    Args:
        t_start (double): Simulation start time.
        t_stop (double): Simulation stop time.
        x0 (list): Initial value.
        p (list): Problem specific parameters.
        ncp (int): Number of communication points.
        with_plots (bool): Plots the solution.

    Returns:
        tuple: (t,y). Time vector and solution at each time.

    """

    # Assimulo
    # Define the right-hand side
    def f(t, y):
        xd_1 = p[0] * y[0]
        xd_2 = p[1] * (y[1] - y[0]**2)
        return np.array([xd_1, xd_2])

    # Define an Assimulo problem
    exp_mod = Explicit_Problem(f, y0=x0, name='Planar ODE')

    # Define an explicit solver
    exp_sim = CVode(exp_mod)

    # Sets the solver parameters
    exp_sim.atol = 1e-12
    exp_sim.rtol = 1e-11

    # Simulate
    t, y = exp_sim.simulate(tfinal=t_stop, ncp=ncp)

    # Plot
    if with_plots:
        x1 = y[:, 0]
        x2 = y[:, 1]
        plt.figure()
        plt.title('Planar ODE')
        plt.plot(t, x1, 'b')
        plt.plot(t, x2, 'k')
        plt.legend(['x1', 'x2'])
        plt.xlim(t_start, t_stop)
        plt.xlabel('Time (s)')
        plt.ylabel('x')
        plt.grid(True)

    return t, y.T
def run_example(with_plots=True):
    """
    The same as example :doc:`EXAMPLE_cvode_basic`  but now integrated backwards in time.
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
       
    """

    #Define the rhs
    def f(t, y):
        ydot = -y[0]
        return N.array([ydot])

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(
        f,
        t0=5,
        y0=0.02695,
        name=r'CVode Test Example (reverse time): $\dot y = - y$ ')

    #Define an explicit solver
    exp_sim = CVode(exp_mod)  #Create a CVode solver

    #Sets the parameters
    exp_sim.iter = 'Newton'  #Default 'FixedPoint'
    exp_sim.discr = 'BDF'  #Default 'Adams'
    exp_sim.atol = [1e-8]  #Default 1e-6
    exp_sim.rtol = 1e-8  #Default 1e-6
    exp_sim.backward = True

    #Simulate
    t, y = exp_sim.simulate(0)  #Simulate 5 seconds (t0=5 -> tf=0)

    #print 'y(5) = {}, y(0) ={}'.format(y[0][0],y[-1][0])

    #Basic test
    nose.tools.assert_almost_equal(float(y[-1]), 4.00000000, 3)

    #Plot
    if with_plots:
        P.plot(t, y, color="b")
        P.title(exp_mod.name)
        P.ylabel('y')
        P.xlabel('Time')
        P.show()

    return exp_mod, exp_sim
Esempio n. 30
0
def run_example(with_plots=True):
    r"""
    Demonstration of the use of CVode by solving the
    linear test equation :math:`\dot y = - y`
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
       
    """

    #Define the rhs
    def f(t, y):
        ydot = -y[0]
        return N.array([ydot])

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f,
                               y0=4,
                               name=r'CVode Test Example: $\dot y = - y$')

    #Define an explicit solver
    exp_sim = CVode(exp_mod)  #Create a CVode solver

    #Sets the parameters
    exp_sim.iter = 'Newton'  #Default 'FixedPoint'
    exp_sim.discr = 'BDF'  #Default 'Adams'
    exp_sim.atol = [1e-4]  #Default 1e-6
    exp_sim.rtol = 1e-4  #Default 1e-6

    #Simulate
    t1, y1 = exp_sim.simulate(5, 100)  #Simulate 5 seconds
    t2, y2 = exp_sim.simulate(7)  #Simulate 2 seconds more

    #Plot
    if with_plots:
        import pylab as P
        P.plot(t1, y1, color="b")
        P.plot(t2, y2, color="r")
        P.title(exp_mod.name)
        P.ylabel('y')
        P.xlabel('Time')
        P.show()

    #Basic test
    nose.tools.assert_almost_equal(float(y2[-1]), 0.00347746, 5)
    nose.tools.assert_almost_equal(exp_sim.get_last_step(), 0.0222169642893, 3)

    return exp_mod, exp_sim