Ejemplo n.º 1
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
Ejemplo n.º 2
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)
Ejemplo n.º 3
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()
Ejemplo n.º 4
0
def run_example(with_plots=True):
    """
    This is the same example from the Sundials package (cvsRoberts_FSA_dns.c)

    This simple example problem for CVode, due to Robertson, 
    is from chemical kinetics, and consists of the following three 
    equations::
    
       dy1/dt = -p1*y1 + p2*y2*y3
       dy2/dt = p1*y1 - p2*y2*y3 - p3*y2**2
       dy3/dt = p3*(y2)^2
    
    """
    
    def f(t, y, p):
        
        yd_0 = -p[0]*y[0]+p[1]*y[1]*y[2]
        yd_1 = p[0]*y[0]-p[1]*y[1]*y[2]-p[2]*y[1]**2
        yd_2 = p[2]*y[1]**2
        
        return N.array([yd_0,yd_1,yd_2])
    
    #The initial conditions
    y0 = [1.0,0.0,0.0]          #Initial conditions for y
    
    #Create an Assimulo explicit problem
    exp_mod = Explicit_Problem(f,y0)
    
    #Sets the options to the problem
    exp_mod.p0 = [0.040, 1.0e4, 3.0e7]  #Initial conditions for parameters
    exp_mod.pbar = [0.040, 1.0e4, 3.0e7]

    #Create an Assimulo explicit solver (CVode)
    exp_sim = CVode(exp_mod)
    
    #Sets the paramters
    exp_sim.iter = 'Newton'
    exp_sim.discr = 'BDF'
    exp_sim.rtol = 1.e-4
    exp_sim.atol = N.array([1.0e-8, 1.0e-14, 1.0e-6])
    exp_sim.sensmethod = 'SIMULTANEOUS' #Defines the sensitvity method used
    exp_sim.suppress_sens = False       #Dont suppress the sensitivity variables in the error test.
    exp_sim.continuous_output = True

    #Simulate
    t, y = exp_sim.simulate(4,400) #Simulate 4 seconds with 400 communication points
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0], 9.05518032e-01, 4)
    nose.tools.assert_almost_equal(y[-1][1], 2.24046805e-05, 4)
    nose.tools.assert_almost_equal(y[-1][2], 9.44595637e-02, 4)
    nose.tools.assert_almost_equal(exp_sim.p_sol[0][-1][0], -1.8761, 2) #Values taken from the example in Sundials
    nose.tools.assert_almost_equal(exp_sim.p_sol[1][-1][0], 2.9614e-06, 8)
    nose.tools.assert_almost_equal(exp_sim.p_sol[2][-1][0], -4.9334e-10, 12)
    
    #Plot
    if with_plots:
        P.plot(t, y)
        P.show()  
Ejemplo n.º 5
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
Ejemplo n.º 6
0
 def test_handle_result(self):
     """
     This function tests the handle result.
     """
     f = lambda t,x: x**0.25
     def handle_result(solver,t,y):
         assert solver.t == t
     
     prob = Explicit_Problem(f, [1.0])
     prob.handle_result = handle_result
     
     sim = CVode(prob)
     sim.continuous_output = True
     sim.simulate(10.)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
def run_example(with_plots=True):
    
    #Defines the rhs
    def f(t,y):
        yd_0 = y[1]
        yd_1 = -9.82

        return N.array([yd_0,yd_1])
    
    #Defines the jacobian*vector product
    def jacv(t,y,fy,v):
        j = N.array([[0,1.],[0,0]])
        return N.dot(j,v)
    
    y0 = [1.0,0.0] #Initial conditions
    
    #Defines an Assimulo explicit problem
    exp_mod = Explicit_Problem(f,y0)
    
    exp_mod.jacv = jacv #Sets the jacobian
    exp_mod.name = 'Example using the Jacobian Vector product'
    
    exp_sim = CVode(exp_mod) #Create a CVode solver
    
    #Set the parameters
    exp_sim.iter = 'Newton' #Default 'FixedPoint'
    exp_sim.discr = 'BDF' #Default 'Adams'
    exp_sim.atol = 1e-5 #Default 1e-6
    exp_sim.rtol = 1e-5 #Default 1e-6
    exp_sim.linear_solver = 'SPGMR' #Change linear solver
    #exp_sim.options["usejac"] = False
    
    #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)
    
    #Plot
    if with_plots:
        P.plot(t,y)
        P.show()
Ejemplo n.º 9
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)
     self.simulator.verbosity = 0
Ejemplo n.º 10
0
def run_example(with_plots=True):
    global t,y
    
    #Defines the rhs
    def f(t,y):
        yd_0 = y[1]
        yd_1 = -9.82
        #print y, yd_0, yd_1
        return N.array([yd_0,yd_1])
    
    #Defines the jacobian
    def jac(t,y):
        j = N.array([[0,1.],[0,0]])
        return j
    
    #Defines an Assimulo explicit problem
    y0 = [1.0,0.0] #Initial conditions

    exp_mod = Explicit_Problem(f,y0)
    
    exp_mod.jac = jac #Sets the jacobian
    exp_mod.name = 'Example using Jacobian'

    
    exp_sim = CVode(exp_mod) #Create a CVode solver
    
    #Set the parameters
    exp_sim.iter = 'Newton' #Default 'FixedPoint'
    exp_sim.discr = 'BDF' #Default 'Adams'
    exp_sim.atol = 1e-5 #Default 1e-6
    exp_sim.rtol = 1e-5 #Default 1e-6
    
    #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)
        
    #Plot
    if with_plots:
        P.plot(t,y,linestyle="dashed",marker="o") #Plot the solution
        P.show()
Ejemplo n.º 11
0
    def test_switches(self):
        """
        This tests that the switches are actually turned when override.
        """
        f = lambda t,x,sw: N.array([1.0])
        state_events = lambda t,x,sw: N.array([x[0]-1.])
        def handle_event(solver, event_info):
            solver.sw = [False] #Override the switches to point to another instance
        
        mod = Explicit_Problem(f,[0.0])
        mod.sw0 = [True]

        mod.state_events = state_events
        mod.handle_event = handle_event
        
        sim = CVode(mod)
        assert sim.sw[0] == True
        sim.simulate(3)
        assert sim.sw[0] == False
Ejemplo n.º 12
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
Ejemplo n.º 13
0
def run_example(with_plots=True):
    global t, y

    #Defines the rhs
    def f(t, y):
        yd_0 = y[1]
        yd_1 = -9.82
        #print y, yd_0, yd_1
        return N.array([yd_0, yd_1])

    #Defines the jacobian
    def jac(t, y):
        j = N.array([[0, 1.], [0, 0]])
        return j

    #Defines an Assimulo explicit problem
    y0 = [1.0, 0.0]  #Initial conditions

    exp_mod = Explicit_Problem(f, y0)

    exp_mod.jac = jac  #Sets the jacobian
    exp_mod.name = 'Example using Jacobian'

    exp_sim = CVode(exp_mod)  #Create a CVode solver

    #Set the parameters
    exp_sim.iter = 'Newton'  #Default 'FixedPoint'
    exp_sim.discr = 'BDF'  #Default 'Adams'
    exp_sim.atol = 1e-5  #Default 1e-6
    exp_sim.rtol = 1e-5  #Default 1e-6

    #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)

    #Plot
    if with_plots:
        P.plot(t, y, linestyle="dashed", marker="o")  #Plot the solution
        P.show()
Ejemplo n.º 14
0
    def test_switches(self):
        """
        This tests that the switches are actually turned when override.
        """
        f = lambda t,x,sw: N.array([1.0])
        state_events = lambda t,x,sw: N.array([x[0]-1.])
        def handle_event(solver, event_info):
            solver.sw = [False] #Override the switches to point to another instance
        
        mod = Explicit_Problem(f,[0.0])
        mod.sw0 = [True]

        mod.state_events = state_events
        mod.handle_event = handle_event
        
        sim = Radau5ODE(mod)
        assert sim.sw[0] == True
        sim.simulate(3)
        assert sim.sw[0] == False
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
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
     
     #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.jac = jac
     self.mod = exp_mod
         
     #Define an explicit solver
     self.sim = _Radau5ODE(exp_mod) #Create a Radau5 solve
     self.sim_t0 = _Radau5ODE(exp_mod_t0)
     
     #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
Ejemplo n.º 17
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
     
     #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.jac = jac
     self.mod = exp_mod
         
     #Define an explicit solver
     self.sim = Radau5ODE(exp_mod) #Create a Radau5 solve
     self.sim_t0 = Radau5ODE(exp_mod_t0)
     
     #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
Ejemplo n.º 18
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)
Ejemplo n.º 19
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)
Ejemplo n.º 20
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)
Ejemplo n.º 21
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 = LSODAR(exp_mod)  #Create a LSODAR solve
        self.sim_sp = LSODAR(exp_mod_sp)

        #Sets the parameters
        self.sim.atol = 1e-6  #Default 1e-6
        self.sim.rtol = 1e-6  #Default 1e-6
        self.sim.usejac = False
Ejemplo n.º 22
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
Ejemplo n.º 23
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
Ejemplo n.º 24
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
Ejemplo n.º 25
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
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
Ejemplo n.º 27
0
    def test_change_norm(self):

        assert self.simulator.options["norm"] == "WRMS"
        self.simulator.norm = 'WRMS'
        assert self.simulator.norm == 'WRMS'
        self.simulator.norm = 'EUCLIDEAN'
        assert self.simulator.options["norm"] == "EUCLIDEAN"
        assert self.simulator.norm == 'EUCLIDEAN'

        f = lambda t, y: N.array([1.0])
        y0 = 4.0  #Initial conditions

        exp_mod = Explicit_Problem(f, y0)
        exp_sim = CVode(exp_mod)  #Create a CVode solver

        exp_sim.norm = "WRMS"
        exp_sim.simulate(1)

        exp_mod = Explicit_Problem(f, y0)
        exp_sim = CVode(exp_mod)  #Create a CVode solver

        exp_sim.norm = "EUCLIDEAN"
        exp_sim.simulate(1)
Ejemplo n.º 28
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 = ImplicitEuler(exp_mod)
        exp_sim.simulate(5., 100)

        assert exp_sim.statistics["nfcnjacs"] == 0
        nose.tools.assert_almost_equal(exp_sim.y_sol[-1][0], -121.995500, 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.995500, 4)
        assert exp_sim.statistics["nfcnjacs"] > 0
Ejemplo n.º 29
0
    def test_re_init(self):

        rhs = lambda t, y: y

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

        assert solv.t == 0.0
        assert solv.y[0] == 0.0

        solv.re_init(1.0, 2.0)

        assert solv.t == 1.0
        assert solv.y[0] == 2.0
Ejemplo n.º 30
0
def run_example():

    def rhs(t,y):
        A =N.array([[0,1],[-2,-1]])
        yd=N.dot(A,y)
        
        return yd
        
    y0=N.array([1.0,1.0])
    t0=0.0
        
    model = Explicit_Problem(rhs,y0,t0) #Create an Assimulo problem
    model.name = 'Linear Test ODE'

    sim = CVode(model) #Create the solver CVode

    tfinal = 10.0 #Specify the final time
        
    t,y = sim.simulate(tfinal) #Use the .simulate method to simulate and provide the final time
        
    #Plot
    P.plot(t,y)
    P.show()
Ejemplo n.º 31
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'
    
    exp_sim = RungeKutta4(exp_mod) #Create a RungeKutta4 solver
    
    #Simulate
    t, y = exp_sim.simulate(5, 100) #Simulate 5 seconds
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1],0.02695179)
    
    #Plot
    if with_plots:
        P.plot(t,y)
        P.show()
Ejemplo n.º 32
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'

    exp_sim = RungeKutta4(exp_mod)  #Create a RungeKutta4 solver

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

    #Basic test
    nose.tools.assert_almost_equal(y[-1], 0.02695179)

    #Plot
    if with_plots:
        P.plot(t, y)
        P.show()
Ejemplo n.º 33
0
    def test_simulate_explicit(self):
        """
        Test a simulation of an explicit problem using IDA.
        """
        f = lambda t, y: N.array(-y)
        y0 = [1.0]

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

        assert simulator.yd0[0] == -simulator.y0[0]

        t, y = simulator.simulate(1.0)

        nose.tools.assert_almost_equal(float(y[-1]), float(N.exp(-1.0)), 4)
Ejemplo n.º 34
0
    def test_usejac(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: 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["nfevalsLS"] == 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["nfevalsLS"] > 0
Ejemplo n.º 35
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"]
Ejemplo n.º 36
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"]
Ejemplo n.º 37
0
    def test_interpolate(self):
        """
        This tests the functionality of the method interpolate.
        """
        f = lambda t, x: N.array(x**0.25)

        prob = Explicit_Problem(f, [1.0])

        sim = CVode(prob)
        sim.simulate(10., 100)
        y100 = sim.y_sol
        t100 = sim.t_sol
        sim.reset()
        sim.simulate(10.)
        nose.tools.assert_almost_equal(y100[-2], sim.interpolate(9.9, 0), 5)
Ejemplo n.º 38
0
def run_example(with_plots=True):
    
    #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:
        P.plot(t,y[:,0], marker='o')
        P.show()
    
    #Basic test
    x1 = y[:,0]
    assert N.abs(x1[-1]-1.706168035) < 1e-3 #For test purpose
Ejemplo n.º 39
0
    def test_usejac(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: 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["nfevalsLS"] == 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["nfevalsLS"] > 0
Ejemplo n.º 40
0
    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
Ejemplo n.º 41
0
    def test_change_discr(self):
        """
        This tests that the change from Functional to Newton works
        """
        f = lambda t, y: N.array([1.0])
        y0 = 4.0  #Initial conditions

        exp_mod = Explicit_Problem(f, y0)
        exp_sim = CVode(exp_mod)  #Create a CVode solver

        exp_sim.iter = "FixedPoint"
        exp_sim.simulate(1)
        assert exp_sim.statistics["njevals"] == 0
        exp_sim.iter = "Newton"
        exp_sim.simulate(2)
        assert exp_sim.statistics["njevals"] > 0
Ejemplo n.º 42
0
def doSimulate():

    theta0 = 1.0  # radianer, startvinkel från lodrätt

    tfinal = 3

    title = 'k = {0}, stretch = {1}, {2}'.format(k, stretch, solver)

    r0 = 1.0 + stretch
    x0 = r0 * np.sin(theta0)
    y0 = -r0 * np.cos(theta0)
    t0 = 0.0

    y_init = np.array([x0, y0, 0, 0])

    ElasticSpring = Explicit_Problem(rhs, y_init, t0)
    if solver.lower() == "cvode":
        sim = CVode(ElasticSpring)
    elif solver.lower() == "bdf_2":
        sim = BDF_2(ElasticSpring)
    elif solver.lower() == "ee":
        sim = EE(ElasticSpring)
    else:
        sim == None
        raise ValueError('Expected "CVode", "EE" or "BDF_2"')
    sim.report_continuously = False

    npoints = 100 * tfinal

    #t,y = sim.simulate(tfinal,npoints)
    try:
        #for i in [1]:
        t, y = sim.simulate(tfinal)
        xpos, ypos = y[:, 0], y[:, 1]
        #plt.plot(t,y[:,0:2])
        plt.plot(xpos, ypos)
        plt.plot(xpos[0], ypos[0], 'or')
        plt.xlabel('y_1')
        plt.ylabel('y_2')
        plt.title(title)
        plt.axis('equal')
        plt.show()
    except Explicit_ODE_Exception as e:
        print(e.message)
        print("for the case {0}.".format(title))
Ejemplo n.º 43
0
def run_example(with_plots=True):
    r"""
    Demonstration of the use of the use of the explicit euler method by solving the
    linear test equation :math:`\dot y = - y`
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
       
    """

    #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,
                               name='ExplicitEuler Example: $\dot y = - y$')

    #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

    #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.02628193)

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

    #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, name='RK34 Example: $\dot y = - y$')

    exp_sim = RungeKutta34(exp_mod)  #Create a RungeKutta34 solver
    exp_sim.inith = 0.1  #Sets the initial step, default = 0.01

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

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

    #Plot
    if with_plots:
        import pylab as P
        P.plot(t, y)
        P.title(exp_mod.name)
        P.ylabel('y')
        P.xlabel('Time')
        P.show()

    return exp_mod, exp_sim
Ejemplo n.º 45
0
    def test_pbar(self):
        """
        Tests the property of pbar.
        """
        f = lambda t, y, p: N.array([0.0] * len(y))
        y0 = [1.0] * 2
        p0 = [1000.0, -100.0]
        exp_mod = Explicit_Problem(f, y0, p0=p0)

        exp_sim = CVode(exp_mod)

        nose.tools.assert_almost_equal(exp_sim.pbar[0], 1000.00000, 4)
        nose.tools.assert_almost_equal(exp_sim.pbar[1], 100.000000, 4)

        f = lambda t, y, yd, p: N.array([0.0] * len(y))
        yd0 = [0.0] * 2
        imp_mod = Implicit_Problem(f, y0, yd0, p0=p0)

        imp_sim = IDA(imp_mod)

        nose.tools.assert_almost_equal(imp_sim.pbar[0], 1000.00000, 4)
        nose.tools.assert_almost_equal(imp_sim.pbar[1], 100.000000, 4)
Ejemplo n.º 46
0
def create_model():
    def pendulum(t, X, sw):
        """
        The ODE to be simulated. The parameter sw should be fixed during
        the simulation and only be changed during the event handling.
        """

        X = X.copy()
        X[0] = X[1]
        X[1] = -1 + 0.04 * (X[1]**2) * np.sin(X[1])
        X[2] = 1

        return X

    def state_events(t, X, sw):
        """
        This is our function that keep track of our events, when the sign
        of any of the events has changed, we have an event.
        """
        return [X[0] - np.sin(X[2])]

    def handle_event(solver, event_info):
        """
        Event handling. This functions is called when Assimulo finds an event as
        specified by the event functions.
        """
        state_info = event_info[0] #We are only interested in state events info

        if state_info[0] != 0: #Check if the first event function have been triggered

            if solver.sw[0]: #If the switch is True the pendulum bounces
                X = solver.y
                if X[1] - np.cos(X[2]) < 0:
                    X[1] = -0.9*X[1] + 1.9*np.cos(X[2])

            #solver.sw[0] = not solver.sw[0] #Change event function

    #Initial values
    y0 = [0, 0, 0] #Initial states
    t0 = 0.0             #Initial time
    switches0 = [True]   #Initial switches

    #Create an Assimulo Problem
    mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0)

    mod.state_events = state_events #Sets the state events to the problem
    mod.handle_event = handle_event #Sets the event handling to the problem
    mod.name = 'Bouncing Ball on Sonusoidal Platform'   #Sets the name of the problem

    #Create an Assimulo solver (CVode)
    sim = CVode(mod)
    #sim = LSODAR(mod)
    #sim.options['verbosity'] = 20 #LOUD
    sim.options['verbosity'] = 40 #WHISPER
    #sim.options['minh'] = 1e-4
    #sim.options['rtol'] = 1e-3

    #Specifies options
    sim.discr = 'Adams'     #Sets the discretization method
    sim.iter = 'FixedPoint' #Sets the iteration method
    sim.rtol = 1.e-8        #Sets the relative tolerance
    sim.atol = 1.e-6        #Sets the absolute tolerance

    return sim
Ejemplo n.º 47
0
def create_model():
    def pendulum(t, X, sw):
        """
        The ODE to be simulated. The parameter sw should be fixed during
        the simulation and only be changed during the event handling.
        """
        g = 1

        Y = X.copy()
        Y[0] = X[2]     #x_dot
        Y[1] = X[3]     #y_dot
        Y[2] = 0        #vx_dot
        Y[3] = -g       #vy_dot
        return Y

    def state_events(t, X, sw):
        """
        This is our function that keep track of our events, when the sign
        of any of the events has changed, we have an event.
        """
        return [X[1]] # y == 0

    def handle_event(solver, event_info):
        """
        Event handling. This functions is called when Assimulo finds an event as
        specified by the event functions.
        """
        state_info = event_info[0] #We are only interested in state events info

        if state_info[0] != 0: #Check if the first event function have been triggered
            if solver.sw[0]:
                X = solver.y
                if X[3] < 0: # if the ball is falling (vy < 0)
                    # bounce!
                    X[1] = 1e-5
                    X[3] = -0.75*X[3]

            #solver.sw[0] = not solver.sw[0] #Change event function

    #Initial values
    y0 = [0., 0., 0., 0.] #Initial states
    t0 = 0.0             #Initial time
    switches0 = [True]   #Initial switches

    #Create an Assimulo Problem
    mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0)

    mod.state_events = state_events #Sets the state events to the problem
    mod.handle_event = handle_event #Sets the event handling to the problem
    mod.name = 'Bouncing Ball in X-Y'   #Sets the name of the problem

    #Create an Assimulo solver (CVode)
    sim = CVode(mod)
    #sim = LSODAR(mod)
    #sim = RungeKutta34(mod)
    #sim.options['verbosity'] = 20 #LOUD
    sim.verbosity = 40 #WHISPER
    #sim.display_progress = True
    #sim.options['minh'] = 1e-4
    #sim.options['rtol'] = 1e-3

#     #Specifies options
#     sim.discr = 'Adams'     #Sets the discretization method
#     sim.iter = 'FixedPoint' #Sets the iteration method
#     sim.rtol = 1.e-8        #Sets the relative tolerance
#     sim.atol = 1.e-6        #Sets the absolute tolerance

    return sim
Ejemplo n.º 48
0
def create_model():
    def pendulum(t, X, sw):
        """
        The ODE to be simulated. The parameter sw should be fixed during
        the simulation and only be changed during the event handling.
        """

        #X = X.copy()
        g = 9.81
        x = X[0]
        vx = X[2]
        vy = X[3]

        return np.array([vx, vy, -(np.pi**2)*x, -g, 1.0])

    def state_events(t, X, sw):
        """
        This is our function that keep track of our events, when the sign
        of any of the events has changed, we have an event.
        """
        x = X[0]
        y = X[1]

        return [x - y]
        #return np.array([x - y])

    def handle_event(solver, event_info):
        """
        Event handling. This functions is called when Assimulo finds an event as
        specified by the event functions.
        """
        state_info = event_info[0] #We are only interested in state events info

        if state_info[0] != 0: #Check if the first event function have been triggered

            if solver.sw[0]: #If the switch is True the pendulum bounces
                X = solver.y
                X[1] = X[0] + 1e-3
                X[3] = 0.9*(X[2] - X[3])

            #solver.sw[0] = not solver.sw[0] #Change event function

    #Initial values
    phi = 1.0241592; Y0 = -13.0666666; A = 2.0003417; w = np.pi
    y0 = [A*np.sin(phi), 1+A*np.sin(phi), A*w*np.cos(phi), Y0 - A*w*np.cos(phi)-1, 0] #Initial states
    t0 = 0.0             #Initial time
    switches0 = [True]   #Initial switches

    #Create an Assimulo Problem
    mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0)

    mod.state_events = state_events #Sets the state events to the problem
    mod.handle_event = handle_event #Sets the event handling to the problem
    mod.name = 'Bouncing Ball on Sonusoidal Platform'   #Sets the name of the problem

    #Create an Assimulo solver (CVode)
    sim = CVode(mod)
    #sim = LSODAR(mod)
    sim.options['verbosity'] = 40

    #Specifies options
    sim.discr = 'Adams'     #Sets the discretization method
    sim.iter = 'FixedPoint' #Sets the iteration method
    sim.rtol = 1.e-8        #Sets the relative tolerance
    sim.atol = 1.e-6        #Sets the absolute tolerance

    return sim
Ejemplo n.º 49
0
    if state_info[0] != 0: #Check if the first event function has been triggered

        if solver.sw[0]: #If the switch is True the pendulum bounces
            solver.y[1] = -0.9*solver.y[1] #Change the velocity and lose energy

        solver.sw[0] = not solver.sw[0] #Change event function
        
        
#Initial values
y0 = [N.pi/2.0, 0.0] #Initial states
t0 = 0.0             #Initial time
switches0 = [True]   #Initial switches

#Create an Assimulo Problem
mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0)

mod.state_events = state_events #Sets the state events to the problem
mod.handle_event = handle_event #Sets the event handling to the problem
mod.name = 'Pendulum with events'   #Sets the name of the problem


#Create an Assimulo solver (CVode)
sim = CVode(mod)

#Specifies options
sim.discr = 'Adams'     #Sets the discretization method
sim.iter = 'FixedPoint' #Sets the iteration method
sim.rtol = 1.e-8        #Sets the relative tolerance
sim.atol = 1.e-6        #Sets the absolute tolerance
Ejemplo n.º 50
0
 def handle_result(self, solver, t, y):
     if t < self.t_cutoff:
         Explicit_Problem.handle_result(self, solver, t, y)
Ejemplo n.º 51
0
import numpy
import math
from assimulo.problem import Explicit_Problem
from assimulo.solvers import CVode
import matplotlib.pyplot as plt

def rhs(t,y):
    k = 1000 
    L = k*(math.sqrt(y[0]**2+y[1]**2)-1)/math.sqrt(y[0]**2+y[1]**2)
    result = numpy.array([y[2],y[3],-y[0]*L,-y[1]*L-1])
    return result
t0 = 0
y0 = numpy.array([0.8,-0.8,0,0])

model = Explicit_Problem(rhs,y0,t0)
model.name = 'task1'

sim = CVode(model)
sim.atol=numpy.array([1,1,1,1])*1e-5
sim.rtol=1e-6
sim.maxord=3
#sim.discr='BDF'
#sim.iter='Newton'


tfinal = 70

(t,y) = sim.simulate(tfinal)

#sim.plot()
def run_example(with_plots=True):
    """
    This example show how to use Assimulo and CVode for simulating sensitivities
    for initial conditions.::
    
        dy1/dt = -(k01+k21+k31)*y1 + k12*y2 + k13*y3 + b1
        dy2/dt = k21*y1 - (k02+k12)*y2
        dy3/dt = k31*y1 - k13*y3
     
        y1(0) = p1, y2(0) = p2, y3(0) = p3
        p1=p2=p3 = 0 
    
    See http://sundials.2283335.n4.nabble.com/Forward-sensitivities-for-initial-conditions-td3239724.html
    """
    def f(t, y, p):
        y1,y2,y3 = y
        k01 = 0.0211
        k02 = 0.0162
        k21 = 0.0111
        k12 = 0.0124
        k31 = 0.0039
        k13 = 0.000035
        b1 = 49.3
        
        yd_0 = -(k01+k21+k31)*y1+k12*y2+k13*y3+b1
        yd_1 = k21*y1-(k02+k12)*y2
        yd_2 = k31*y1-k13*y3
        
        return N.array([yd_0,yd_1,yd_2])
    
    #The initial conditions
    y0 = [0.0,0.0,0.0]          #Initial conditions for y
    p0 = [0.0, 0.0, 0.0]  #Initial conditions for parameters
    yS0 = N.array([[1,0,0],[0,1,0],[0,0,1.]])
    
    #Create an Assimulo explicit problem
    exp_mod = Explicit_Problem(f, y0, p0=p0)
    
    #Sets the options to the problem
    exp_mod.yS0 = yS0
    
    #Create an Assimulo explicit solver (CVode)
    exp_sim = CVode(exp_mod)
    
    #Sets the paramters
    exp_sim.iter = 'Newton'
    exp_sim.discr = 'BDF'
    exp_sim.rtol = 1e-7
    exp_sim.atol = 1e-6
    exp_sim.pbar = [1,1,1] #pbar is used to estimate the tolerances for the parameters
    exp_sim.continuous_output = True #Need to be able to store the result using the interpolate methods
    exp_sim.sensmethod = 'SIMULTANEOUS' #Defines the sensitvity method used
    exp_sim.suppress_sens = False            #Dont suppress the sensitivity variables in the error test.
    
    #Simulate
    t, y = exp_sim.simulate(400) #Simulate 400 seconds
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0], 1577.6552477, 5)
    nose.tools.assert_almost_equal(y[-1][1], 611.9574565, 5)
    nose.tools.assert_almost_equal(y[-1][2], 2215.88563217, 5)
    nose.tools.assert_almost_equal(exp_sim.p_sol[0][1][0], 1.0)

    #Plot
    if with_plots:
        P.figure(1)
        P.subplot(221)
        P.plot(t, N.array(exp_sim.p_sol[0])[:,0],
               t, N.array(exp_sim.p_sol[0])[:,1],
               t, N.array(exp_sim.p_sol[0])[:,2])
        P.title("Parameter p1")
        P.legend(("p1/dy1","p1/dy2","p1/dy3"))
        P.subplot(222)
        P.plot(t, N.array(exp_sim.p_sol[1])[:,0],
               t, N.array(exp_sim.p_sol[1])[:,1],
               t, N.array(exp_sim.p_sol[1])[:,2])
        P.title("Parameter p2")
        P.legend(("p2/dy1","p2/dy2","p2/dy3"))
        P.subplot(223)
        P.plot(t, N.array(exp_sim.p_sol[2])[:,0],
               t, N.array(exp_sim.p_sol[2])[:,1],
               t, N.array(exp_sim.p_sol[2])[:,2])
        P.title("Parameter p3")
        P.legend(("p3/dy1","p3/dy2","p3/dy3"))
        P.subplot(224)
        P.plot(t, y)
        P.show()
Ejemplo n.º 53
0
    def simulate(self, Tend, nIntervals, gridWidth):

        # define assimulo problem:(has to be done here because of the starting value in Explicit_Problem
        solver = Explicit_Problem(self.rhs, self.y0)
        ''' *******DELETE LATER '''''''''
#        problem.handle_event = handle_event
#        problem.state_events = state_events
#        problem.init_mode = init_mode

        solver.handle_result = self.handle_result


        solver.name = 'Simple Explicit Example'
        simulation = CVode(solver)  # Create a RungeKutta34 solver
        # simulation.inith = 0.1 #Sets the initial step, default = 0.01

        # 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 = 0
        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

        # Create Solver and set settings
#        noRootFunctions = np.size(self.state_events(self.t0, np.array(self.y0)))

#        solver = sundials.CVodeSolver(RHS = self.f, ROOT = self.rootf, SW = [False]*noRootFunctions,
#                       abstol = self.atol, reltol = self.rtol)
        # solver.settings.JAC = None   #Add user-dependent jacobian here

        '''Initialize problem '''
#        solver.init(self.t0, self.y0)
        self.handle_result(self.t0, self.y0)
        nextTimeEvent = self.time_events(self.t0, self.y0)
        self.t_cur = self.t0
        self.y_cur = self.y0
        state_event = False
#
#
        if gridWidth <> None:
            nOutputIntervals = int((Tend - self.t0) / gridWidth)
        else:
            nOutputIntervals = nIntervals
        # Define step length depending on if gridWidth or nIntervals has been chosen
        if nOutputIntervals > 0:
            # Last point on grid (does not have to be Tend:)
            if(gridWidth <> None):
                dOutput = gridWidth
            else:
                dOutput = (Tend - self.t0) / nIntervals
        else:
            dOutput = Tend

        outputStepCounter = long(1)
        nextOutputPoint = min(self.t0 + dOutput, Tend)

        while self.t_cur < Tend:

            # Time-Event detection and step time adjustment
            if nextTimeEvent is None or nextOutputPoint < nextTimeEvent:
                time_event = False
                self.t_cur = nextOutputPoint
            else:
                time_event = True
                self.t_cur = nextTimeEvent



            try:
#                #Integrator step
#                self.y_cur = solver.step(self.t_cur)
#                self.y_cur = np.array(self.y_cur)
#                state_event = False
                # Simulate




                # take a step to next output point:
                t_new, y_new = simulation.simulate(self.t_cur)  # 5, 10) #5, 10  self.t_cur self.t_cur  2. argument nsteps Simulate 5 seconds
                # t_new, y_new are both vectors of the time and states at t_cur and all intermediate
                # points before it! So take last values:
                self.t_cur = t_new[-1]
                self.y_cur = y_new[-1]
                state_event = False

            except:
                import sys
                print "Unexpected error:", sys.exc_info()[0]
#            except CVodeRootException, info:
#                self.t_cur = info.t
#                self.y_cur = info.y
#                self.y_cur = np.array(self.y_cur)
#                time_event = False
#                state_event = True
#
#
            # Depending on events have been detected do different tasks
            if time_event or state_event:
                event_info = [state_event, time_event]
                if not self.handle_event(self, event_info):
                    break
                solver.init(self.t_cur, self.y_cur)

                nextTimeEvent = self.time_events(self.t_cur, self.y_cur)
                # If no timeEvent happens:
                if nextTimeEvent <= self.t_cur:
                    nextTimeEvent = None

            if self.t_cur == nextOutputPoint:
                # Write output if not happened before:
                if not time_event and not state_event:
                    self.handle_result(nextOutputPoint, self.y_cur)
                outputStepCounter += 1
                nextOutputPoint = min(self.t0 + outputStepCounter * dOutput, Tend)

        self.finalize()
Ejemplo n.º 54
0
        return np.array([y1,y2,y3,y4])
    return f
    
    
    
    
#pend_mod=Explicit_Problem(f, y0=np.array([1, 1, 0, 0] ))
#pend_mod.problem_name='Nonlinear Pendulum'

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

#t, y = exp_sim.simulate(1)

rhs = getRHS(100)
pend_mod=Explicit_Problem(rhs, y0=np.array([2, 2, 0, 0]))
pend_mod.problem_name='Nonlinear Pendulum'

#Define an explicit solver
solver = CVode(pend_mod)

time = 10
t1,y1 = solver(time)

P.plot(y1[:,0],y1[:,1])
P.grid()
P.show()
P.title('CVode for k = 1, time = 30s')
P.xlabel('X-pos')
P.ylabel('Y-pos')
Ejemplo n.º 55
0
import numpy as N
import pylab as P
from assimulo.problem import Explicit_Problem  #Imports the problem formulation from Assimulo
from assimulo.solvers.sundials import CVode #Imports the solver CVode from Assimulo

def rhs(t,y):
    A =N.array([[0,1],[-2,-1]])
    yd=N.dot(A,y)

    return yd

y0=N.array([1.0,1.0])
t0=0.0

model = Explicit_Problem(rhs, y0, t0) #Create an Assimulo problem
model.name = 'Linear Test ODE'        #Specifies the name of problem (optional)

sim = CVode(model)

tfinal = 10.0        #Specify the final time

t, y = sim.simulate(tfinal) #Use the .simulate method to simulate and provide the final time

#Plots the result
P.plot(t,y)
P.show()
Ejemplo n.º 56
0
 def __init__(self, new_rhs, y0, rhs_jac=None):
     Explicit_Problem.__init__(self, y0=y0)
     self.rhs = new_rhs
     self.rhs_jac = rhs_jac