Example #1
0
def run_example():

    def residual(t,y,yd):

        res_0 = yd[0]-y[2]
        res_1 = yd[1]-y[3]
        res_2 = yd[2]+y[4]*y[0]
        res_3 = yd[3]+y[4]*y[1]+9.82
        res_4 = y[2]**2+y[3]**2-y[4]*(y[0]**2+y[1]**2)-y[1]*9.82

        return np.array([res_0,res_1,res_2,res_3,res_4])
    
    #The initial conditons
    t0  = 0.0 #Initial time
    y0  = [1.0, 0.0, 0.0, 0.0, 0.0] #Initial conditions
    yd0 = [0.0, 0.0, 0.0, -9.82, 0.0] #Initial conditions
    print (residual(t0,y0,yd0))

    model = Implicit_Problem(residual, y0, yd0, t0)             #Create an Assimulo problem
    model.name = 'Pendulum'        #Specifies the name of problem (optional)

    sim = IDA(model) #Create the IDA solver
        
    tfinal = 10.0        #Specify the final time
    ncp = 500            #Number of communcation points (number of return points)

    t,y,yd = sim.simulate(tfinal, ncp) #Use the .simulate method to simulate and provide the final time and ncp (optional)
    
    sim.plot()
Example #2
0
    def test_time_event(self):
        f = lambda t, y, yd: y - yd
        global tnext
        global nevent
        tnext = 0.0
        nevent = 0

        def time_events(t, y, yd, 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 = Implicit_Problem(f, 0.0, 0.0)
        exp_mod.time_events = time_events
        exp_mod.handle_event = handle_event

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

        assert nevent == 5
Example #3
0
    def test_usejac(self):
        """
        This tests the functionality of the property usejac.
        """
        f = lambda t, x, xd: N.array([xd[0] - x[1], xd[1] - 9.82]
                                     )  #Defines the rhs
        jac = lambda c, t, x, xd: N.array([[c, -1.], [0., c]]
                                          )  #Defines the jacobian

        imp_mod = Implicit_Problem(f, [1.0, 0.0], [0., -9.82])
        imp_mod.jac = jac

        imp_sim = IDA(imp_mod)

        imp_sim.simulate(3, 100)

        assert imp_sim.statistics["nfevalsLS"] == 0
        nose.tools.assert_almost_equal(imp_sim.y_sol[-1][0], 45.1900000, 4)

        imp_sim.reset()
        imp_sim.usejac = False
        imp_sim.simulate(3., 100)

        nose.tools.assert_almost_equal(imp_sim.y_sol[-1][0], 45.1900000, 4)
        assert imp_sim.statistics["nfevalsLS"] > 0
Example #4
0
 def setUp(self):
     """
     This sets up the test case.
     """
     #Define the residual
     def f(t,y,yd):
         eps = 1.e-6
         my = 1./eps
         yd_0 = y[1]
         yd_1 = my*((1.-y[0]**2)*y[1]-y[0])
         
         res_0 = yd[0]-yd_0
         res_1 = yd[1]-yd_1
         
         return N.array([res_0,res_1])
     
     y0 = [2.0,-0.6] #Initial conditions
     yd0 = [-.6,-200000.]
     
     #Define an Assimulo problem
     self.mod = Implicit_Problem(f,y0,yd0)
     self.mod_t0 = Implicit_Problem(f,y0,yd0,1.0)
         
     #Define an explicit solver
     self.sim = _Radau5DAE(self.mod) #Create a Radau5 solve
     self.sim_t0 = _Radau5DAE(self.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
 def test_problem_name_attribute(self):
     res = lambda t,y,yd: y
     
     prob = Implicit_Problem(res, 0.0, 0.0)
     assert prob.name == "---"
     prob = Implicit_Problem(res, 0.0, 0.0, name="Test")
     assert prob.name == "Test"
Example #6
0
    def test_completed_step(self):
        """
        This tests the functionality of the method completed_step.
        """
        global nsteps
        nsteps = 0

        def f(t, y, yd):
            res_1 = y[0] + y[1] + 1.0
            res_2 = y[1]
            return N.array([res_1, res_2])

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

        y0 = [-1.0, 0.0]
        yd0 = [1.0, 0.0]

        mod = Implicit_Problem(f, y0, yd0)
        mod.step_events = completed_step

        sim = IDA(mod)

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

        sim = IDA(mod)
        nsteps = 0
        sim.simulate(2.)
        assert len(sim.t_sol) == sim.statistics["nsteps"] + 1
        assert nsteps == sim.statistics["nsteps"]
Example #7
0
 def test_completed_step(self):
     """
     This tests the functionality of the method completed_step.
     """
     global nsteps
     nsteps = 0
     def f(t,y,yd):
         res_1 = y[0] + y[1]+1.0
         res_2 = y[1]
         return N.array([res_1, res_2])
     def completed_step(solver):
         global nsteps
         nsteps += 1
     
     y0 = [-1.0, 0.0]
     yd0 = [1.0 , 0.0]    
     
     mod = Implicit_Problem(f, y0, yd0)
     mod.step_events = completed_step
     
     sim = IDA(mod)
     
     sim.simulate(2., 100)
     assert len(sim.t_sol) == 101
     assert nsteps == sim.statistics["nsteps"]
     
     sim = IDA(mod)
     nsteps = 0
     sim.simulate(2.)
     assert len(sim.t_sol) == sim.statistics["nsteps"] + 1
     assert nsteps == sim.statistics["nsteps"]
Example #8
0
 def test_time_event(self):
     f = lambda t,y,yd: y-yd
     global tnext
     global nevent
     tnext = 0.0
     nevent = 0
     def time_events(t,y,yd,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 = Implicit_Problem(f,0.0,0.0)
     exp_mod.time_events = time_events
     exp_mod.handle_event = handle_event
     
     #CVode
     exp_sim = IDA(exp_mod)
     exp_sim(5.,100)
     
     assert nevent == 5
Example #9
0
 def solve(self):
     # Setup IDA
     assert self._initial_time is not None
     problem = Implicit_Problem(self._residual_vector_eval,
                                self.solution.vector(),
                                self.solution_dot.vector(),
                                self._initial_time)
     problem.jac = self._jacobian_matrix_eval
     problem.handle_result = self._monitor
     # Define an Assimulo IDA solver
     solver = IDA(problem)
     # Setup options
     assert self._time_step_size is not None
     solver.inith = self._time_step_size
     if self._absolute_tolerance is not None:
         solver.atol = self._absolute_tolerance
     if self._max_time_steps is not None:
         solver.maxsteps = self._max_time_steps
     if self._relative_tolerance is not None:
         solver.rtol = self._relative_tolerance
     if self._report:
         solver.verbosity = 10
         solver.display_progress = True
         solver.report_continuously = True
     else:
         solver.display_progress = False
         solver.verbosity = 50
     # Assert consistency of final time and time step size
     assert self._final_time is not None
     final_time_consistency = (
         self._final_time - self._initial_time) / self._time_step_size
     assert isclose(
         round(final_time_consistency), final_time_consistency
     ), ("Final time should be occuring after an integer number of time steps"
         )
     # Prepare monitor computation if not provided by parameters
     if self._monitor_initial_time is None:
         self._monitor_initial_time = self._initial_time
     assert isclose(
         round(self._monitor_initial_time / self._time_step_size),
         self._monitor_initial_time / self._time_step_size
     ), ("Monitor initial time should be a multiple of the time step size"
         )
     if self._monitor_time_step_size is None:
         self._monitor_time_step_size = self._time_step_size
     assert isclose(
         round(self._monitor_time_step_size / self._time_step_size),
         self._monitor_time_step_size / self._time_step_size
     ), ("Monitor time step size should be a multiple of the time step size"
         )
     monitor_t = arange(
         self._monitor_initial_time,
         self._final_time + self._monitor_time_step_size / 2.,
         self._monitor_time_step_size)
     # Solve
     solver.simulate(self._final_time, ncp_list=monitor_t)
def run_example():

	#initial values
	t0 = 0
	y0 = np.array([0., -0.10344, -0.65, 0., 0. , 0., -0.628993, 0.047088]) #|phi_s| <= 0.1034 rad, |phi_b| <= 0.12 rad
	yd0 = np.array([0., 0., 0., 0., 0., 0., 0., 0.])
	sw = [False, True, False]
	
	#problem
	model = Implicit_Problem(pecker, y0, yd0, t0, sw0=sw)
	model.state_events = state_events #from woodpecker.py
	model.handle_event = handle_event #from woodpecker.py
	model.name = 'Woodpeckermodel'
	sim = IDA(model) #create IDA solver
	tfinal = 2.0 #final time
	ncp = 500 #number control points	
	sim.suppress_alg = True
	sim.rtol=1.e-6
	sim.atol[6:8] = 1e6
	sim.algvar[6:8] = 0
	t, y, yd = sim.simulate(tfinal, ncp) #simulate
	
	#plot
	fig, ax = P.subplots()
	ax.plot(t, y[:, 0], label='z')
	legend = ax.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(1)
	fig2, ax2 = P.subplots()
	ax2.plot(t, y[:, 1], label='phi_s')
	ax2.plot(t, y[:, 2], label='phi_b')
	legend = ax2.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(2)
	fig3, ax3 = P.subplots()
	ax3.plot(t, y[:, 4], label='phi_sp')
	ax3.plot(t, y[:, 5], label='phi_bp')
	legend = ax3.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(3)
	fig4, ax4 = P.subplots()
	ax4.plot(t, y[:, 6], label='lambda_1')
	ax4.plot(t, y[:, 7], label='lambda_2')
	legend = ax4.legend(loc='upper right', shadow=True)
	P.grid()
	
	#event data
	sim.print_event_data()
	
	#show plots
	P.show()
	print("...")
	P.show()
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Implicit_Problem(self.rhs, self.y0, self.yd0)
        problem.name = 'IDA'
        # 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
        # Create IDA object and set additional parameters
        simulation = IDA(problem)
        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.tout1 = self.tout1
        simulation.lsoff = self.lsoff

        # 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,  yd_new = simulation.simulate
Example #12
0
    def initialize_ode_solver(self, y_0, yd_0, t_0):
        model = Implicit_Problem(self.residual, y_0, yd_0, t_0)
        model.handle_result = self.handle_result
        solver = IDA(model)
        solver.rtol = self.solver_rtol
        solver.atol = self.solver_atol  # * np.array([100, 10, 1e-4, 1e-4])
        solver.inith = 0.1  # self.wind.R_g / const.C
        solver.maxh = self.dt * self.wind.R_g / const.C
        solver.report_continuously = True
        solver.display_progress = False
        solver.verbosity = 50  # 50 = quiet
        solver.num_threads = 3

        # solver.display_progress = True
        return solver
Example #13
0
 def test_elapsed_step_time(self):
     res = lambda t,y,yd: y
     
     prob = Implicit_Problem(res, 0.0, 0.0)
     solv = Implicit_ODE(prob)
     
     assert solv.get_elapsed_step_time() == -1.0
Example #14
0
    def setUp(self):
        """
        This sets up the test case.
        """
        class Prob_IDA(Implicit_Problem):
            def __init__(self):
                pass
            res = lambda self,t,y,yd,sw: N.array([y[0]-1.0])
            state_events = lambda self,t,y,yd,sw: N.array([t-1.0, t])
            y0 = [1.0]
            yd0 = [1.0]
            sw0 = [False, True]
            
        res = Prob_IDA()
        
        class Prob_CVode(Explicit_Problem):
            def __init__(self):
                pass
            rhs = lambda self,t,y,sw: N.array([1.0])
            state_events = lambda self,t,y,sw: N.array([t-1.0, t])
            y0 = [1.0]
            sw0 = [False, True]

        f = Prob_CVode()
        
        self.simulators = [IDA(res), CVode(f)]
        
        
        f = lambda t,y,yd,p: N.array([0.0])
        y0 = [1.0]
        yd0 = [1.0]
        p0 = [1.0]
        
        mod = Implicit_Problem(f, y0,yd0,p0=p0)
        self.sim = IDA(mod)
Example #15
0
    def test_initstep(self):
        """
        This tests the funtionality of the property initstep.
        """
        def f(t, y, yd):
            res_0 = yd[0] - y[1]
            res_1 = yd[1] + 9.82 - 0.01 * y[1]**2
            return N.array([res_0, res_1])

        mod = Implicit_Problem(f, y0=[5.0, 0.0], yd0=[0.0, 9.82])

        sim = IDA(mod)
        sim.simulate(2.0)

        nose.tools.assert_almost_equal(sim.y_sol[-1][0],
                                       -13.4746473811,
                                       places=7)

        sim.reset()
        sim.inith = 1e-10
        sim.simulate(2.0)

        nose.tools.assert_almost_equal(sim.y_sol[-1][0],
                                       -13.4746596311,
                                       places=7)
Example #16
0
    def test_handle_result(self):
        """
        This function tests the handle result.
        """
        f = lambda t,x,xd: x**0.25-xd
        def handle_result(solver, t ,y, yd):
            assert solver.t == t
        
        prob = Implicit_Problem(f, [1.0],[1.0])
        prob.handle_result = handle_result
        
        sim = IDA(prob)

        sim.report_continuously = True
        
        sim.simulate(10.)
Example #17
0
    def test_handle_result(self):
        """
        This function tests the handle result.
        """
        f = lambda t,x,xd: x**0.25-xd
        def handle_result(solver, t ,y, yd):
            assert solver.t == t
        
        prob = Implicit_Problem(f, [1.0],[1.0])
        prob.handle_result = handle_result
        
        sim = IDA(prob)

        sim.continuous_output = True
        
        sim.simulate(10.)
Example #18
0
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Implicit_Problem(self.rhs, self.y0, self.yd0)
        problem.name = 'IDA'
        # 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
        # Create IDA object and set additional parameters
        simulation = IDA(problem)
        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.tout1 = self.tout1
        simulation.lsoff = self.lsoff

        # 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,  yd_new = simulation.simulate
Example #19
0
 def test_implicit_problem(self):
     f = lambda t,y,yd: yd + 1
     y0 = [1.0, 1.0, 1.0]
     yd0 = [-1.0, -1.0, -1.0]
     
     self.problem = Implicit_Problem(f,y0, yd0)
     self.simulator = ODASSL(self.problem)
     
     self.simulator.simulate(1)
Example #20
0
    def test_switches(self):
        """
        This tests that the switches are actually turned when override.
        """
        res = lambda t,x,xd,sw: N.array([1.0 - xd])
        state_events = lambda t,x,xd,sw: N.array([x[0]-1.])
        def handle_event(solver, event_info):
            solver.sw = [False] #Override the switches to point to another instance
        
        mod = Implicit_Problem(res,[0.0], [1.0])
        mod.sw0 = [True]

        mod.state_events = state_events
        mod.handle_event = handle_event
        
        sim = Radau5DAE(mod)
        assert sim.sw[0] == True
        sim.simulate(3)
        assert sim.sw[0] == False
Example #21
0
    def setUp(self):
        """
        This function sets up the test case.
        """
        f = lambda t, y, yd: y
        y0 = [1.0]
        yd0 = [1.0]

        self.problem = Implicit_Problem(f, y0, yd0)
        self.simulator = IDA(self.problem)
Example #22
0
 def test_switches(self):
     """
     This tests that the switches are actually turned when override.
     """
     f = lambda t,x,xd,sw: N.array([xd[0]- 1.0])
     state_events = lambda t,x,xd,sw: N.array([x[0]-1.])
     def handle_event(solver, event_info):
         solver.sw = [False] #Override the switches to point to another instance
     
     mod = Implicit_Problem(f, [0.0],[1.0])
     mod.f = f
     mod.sw0 = [True]
     mod.state_events = state_events
     mod.handle_event = handle_event
     
     sim = IDA(mod)
     assert sim.sw[0] == True
     sim.simulate(3)
     assert sim.sw[0] == False
Example #23
0
    def test_time_limit(self):
        f = lambda t, y, yd: yd - y

        exp_mod = Implicit_Problem(f, 1.0, 1.0)
        exp_sim = IDA(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)
Example #24
0
    def test_time_event(self):
        """
        This tests the functionality of the time event function.
        """
        f = lambda t,x,xd,sw: xd-x
        
        def time_events(t, y, yd, sw):
            if sw[0]:
                return 1.0
            if sw[1]:
                return 3.0
            return None
        
        def handle_event(solver, event_info):
            
            if event_info[1]:
                solver.y  = N.array([1.0])
                solver.yd = N.array([1.0])
                
                if not solver.sw[0]:
                    solver.sw[1] = False
                
                if solver.sw[0]:
                    solver.sw[0] = False
        
        mod = Implicit_Problem(f,[1.0],[1.0])
        mod.time_events = time_events
        mod.handle_event = handle_event
        mod.switches0 = [True, True]
        
        sim = IDA(mod)
        
        sim.simulate(5.0)

        nose.tools.assert_almost_equal(sim.y_sol[38], 1.0000000, 5)
        nose.tools.assert_almost_equal(sim.y_sol[87], 1.0000000, 5)
        
        sim = IDA(mod, [1.0],[1.0])
        sim.simulate(2.0)
        
        nose.tools.assert_almost_equal(sim.t_sol[-1], 2.0000000, 5)
Example #25
0
    def test_time_event(self):
        """
        This tests the functionality of the time event function.
        """
        f = lambda t, x, xd, sw: xd - x

        def time_events(t, y, yd, sw):
            if sw[0]:
                return 1.0
            if sw[1]:
                return 3.0
            return None

        def handle_event(solver, event_info):

            if event_info[1]:
                solver.y = N.array([1.0])
                solver.yd = N.array([1.0])

                if not solver.sw[0]:
                    solver.sw[1] = False

                if solver.sw[0]:
                    solver.sw[0] = False

        mod = Implicit_Problem(f, [1.0], [1.0])
        mod.time_events = time_events
        mod.handle_event = handle_event
        mod.switches0 = [True, True]

        sim = IDA(mod)

        sim.simulate(5.0)

        nose.tools.assert_almost_equal(sim.y_sol[38], 1.0000000, 5)
        nose.tools.assert_almost_equal(sim.y_sol[87], 1.0000000, 5)

        sim = IDA(mod, [1.0], [1.0])
        sim.simulate(2.0)

        nose.tools.assert_almost_equal(sim.t_sol[-1], 2.0000000, 5)
Example #26
0
def run_example(with_plots=True):
    
    #Define the residual
    def f(t,y,yd):
        eps = 1.e-6
        my = 1./eps
        yd_0 = y[1]
        yd_1 = my*((1.-y[0]**2)*y[1]-y[0])
        
        res_0 = yd[0]-yd_0
        res_1 = yd[1]-yd_1
        
        return N.array([res_0,res_1])
    
    y0 = [2.0,-0.6] #Initial conditions
    yd0 = [-.6,-200000.]
    
    #Define an Assimulo problem
    imp_mod = Implicit_Problem(f,y0,yd0)
    imp_mod.name = 'Van der Pol (implicit)'
    
    #Define an explicit solver
    imp_sim = Radau5DAE(imp_mod) #Create a Radau5 solver
    
    #Sets the parameters
    imp_sim.atol = 1e-4 #Default 1e-6
    imp_sim.rtol = 1e-4 #Default 1e-6
    imp_sim.inith = 1.e-4 #Initial step-size

    #Simulate
    t, y, yd = imp_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
Example #27
0
def run_example(with_plots=True):

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

        res_0 = yd[0] - yd_0
        res_1 = yd[1] - yd_1

        return N.array([res_0, res_1])

    y0 = [2.0, -0.6]  #Initial conditions
    yd0 = [-.6, -200000.]

    #Define an Assimulo problem
    imp_mod = Implicit_Problem(f, y0, yd0)
    imp_mod.name = 'Van der Pol (implicit)'

    #Define an explicit solver
    imp_sim = Radau5DAE(imp_mod)  #Create a Radau5 solver

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

    #Simulate
    t, y, yd = imp_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
Example #28
0
def main():
    y0 = [1.0, 0.0, 0.0, 0.0, 5]
    yd0 = [0.0, 0.0, 0.0, -9.82, 0.0]
    # tout = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0]
    tout = np.linspace(0.0, 10.0, 500)

    implicit_model = Implicit_Problem(res, y0, yd0, name="Example problem")
    # implicit_model.jac = jac
    implicit_model.algvar = [1.0, 1.0, 1.0, 1.0, 0.0]

    implicit_solver = IDA(implicit_model)
    implicit_solver.atol = 1E-6
    implicit_solver.rtol = 1E-6
    implicit_solver.suppress_alg = True
    implicit_solver.make_consistent("IDA_YA_YDP_INIT")
    t, y, yd = implicit_solver.simulate(10.0, ncp=500)

    plt.plot(t, y, linestyle="dashed", marker="o")
    plt.xlabel("Time")
    plt.ylabel("State")
    plt.title(implicit_model.name)
    plt.show()
Example #29
0
 def solve_squeezer(self):
     model = Implicit_Problem(self.squeezer_func, self.y, self.yp, self.t)
     sim = IDA(model)
     tfinal = 10.0
     ncp = 1000
     sim.atol = 1.0e-6
     sim.suppress_alg = True
     for i in range(sim.algvar.size):
         if i > 14:
             sim.algvar[i] = 0
     print(sim.algvar)
     t, y, yd = sim.simulate(tfinal, ncp)
     sim.plot()
Example #30
0
    def test_clear_event_log(self):
        """
        This tests the functionality of the time event function.
        """
        f = lambda t, x, xd, sw: xd - x

        def time_events(t, y, yd, sw):
            if sw[0]:
                return 1.0
            if sw[1]:
                return 3.0
            return None

        def handle_event(solver, event_info):

            if event_info[1]:
                solver.y = N.array([1.0])
                solver.yd = N.array([1.0])

                if not solver.sw[0]:
                    solver.sw[1] = False

                if solver.sw[0]:
                    solver.sw[0] = False

        mod = Implicit_Problem(f, [1.0], [1.0], sw0=[True, True])
        mod.time_events = time_events
        mod.handle_event = handle_event

        sim = IDA(mod)
        sim.verbosity = 10
        assert len(sim.event_data) == 0
        sim.simulate(5.0)
        assert len(sim.event_data) > 0

        sim.reset()
        assert len(sim.event_data) == 0
        sim.simulate(5.0)
        assert len(sim.event_data) > 0
Example #31
0
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, yd):
        res = yd[0] + y[0] * param
        return N.array([res])

    param = 2

    # Define an Assimulo problem
    imp_mod = Implicit_Problem(
        f,
        t0=5,
        y0=0.02695,
        yd0=-0.02695,
        name='IDA Example: $\dot y + y = 0$ (reverse time)')

    # Define an explicit solver
    imp_sim = IDA(imp_mod)  # Create a IDA solver

    # Sets the parameters
    imp_sim.atol = [1e-8]  # Default 1e-6
    imp_sim.rtol = 1e-8  # Default 1e-6
    imp_sim.backward = True

    # Simulate
    t, y, yd = imp_sim.simulate(0)  # Simulate 5 seconds (t0=5 -> tf=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.xlabel('Time')
        P.ylabel('State')
        P.title(imp_mod.name)
        P.show()

    return imp_mod, imp_sim
Example #32
0
    def test_usejac(self):
        """
        This tests the functionality of the property usejac.
        """
        f = lambda t,x,xd: N.array([xd[0]-x[1], xd[1]-9.82])       #Defines the rhs
        jac = lambda c,t,x,xd: N.array([[c,-1.],[0.,c]]) #Defines the jacobian

        imp_mod = Implicit_Problem(f,[1.0,0.0],[0.,-9.82])
        imp_mod.jac = jac
        
        imp_sim = IDA(imp_mod)
        
        imp_sim.simulate(3,100)

        assert imp_sim.statistics["nfevalsLS"] == 0
        nose.tools.assert_almost_equal(imp_sim.y_sol[-1][0], 45.1900000, 4)
        
        imp_sim.reset()
        imp_sim.usejac=False
        imp_sim.simulate(3.,100)

        nose.tools.assert_almost_equal(imp_sim.y_sol[-1][0], 45.1900000, 4)
        assert imp_sim.statistics["nfevalsLS"] > 0
Example #33
0
    def test_interpolate(self):
        """
        This tests the functionality of the method interpolate.
        """
        f = lambda t, y, yd: y**0.25 - yd

        prob = Implicit_Problem(f, [1.0], [1.0])

        sim = IDA(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)
Example #34
0
 def test_re_init(self):
     
     res = lambda t,y,yd: y
     
     prob = Implicit_Problem(res, 0.0, 0.0)
     solv = Implicit_ODE(prob)
     
     assert solv.t == 0.0
     assert solv.y[0] == 0.0
     assert solv.yd[0] == 0.0
     
     solv.re_init(1.0, 2.0, 3.0)
     
     assert solv.t == 1.0
     assert solv.y[0] == 2.0
     assert solv.yd[0] == 3.0
Example #35
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)
Example #36
0
    def test_make_consistency(self):
        """
        This tests the functionality of the method make_consistency.
        """
        def f(t, y, yd):
            res_1 = y[0] + y[1] + 1.0
            res_2 = y[1]
            return N.array([res_1, res_2])

        y0 = [2.0, 2.0]
        yd0 = [1.0, 0.0]

        my_Prob = Implicit_Problem(f, y0, yd0)

        simulator = IDA(my_Prob)

        [flag, y, yd] = simulator.make_consistent('IDA_Y_INIT')

        nose.tools.assert_almost_equal(y[1], 0.00000)
        nose.tools.assert_almost_equal(y[0], -1.0000)
        nose.tools.assert_almost_equal(yd[0], 1.0000)
        nose.tools.assert_almost_equal(yd[1], 0.0000)
Example #37
0
       + ct.omega ** 2 / ct.vA(x,ct.z) ** 2 * u_perp

    res = np.zeros(6 * ct.nz)
    res[0:ct.nz] = np.real(dux + 1j * ct.omega * b_par + nabla_perp_u_perp)
    res[ct.nz:2 * ct.nz] = np.imag(dux + 1j * ct.omega * b_par +
                                   nabla_perp_u_perp)
    res[2 * ct.nz:3 * ct.nz] = np.real(db_par + 1j / ct.omega * L_ux)
    res[3 * ct.nz:4 * ct.nz] = np.imag(db_par + 1j / ct.omega * L_ux)
    res[4 * ct.nz:5 * ct.nz] = np.real(L_u_perp -
                                       1j * ct.omega * nabla_perp_b_par)
    res[5 * ct.nz:] = np.imag(L_u_perp - 1j * ct.omega * nabla_perp_b_par)

    return res


model = Implicit_Problem(residual, ct.U_x_min, ct.dU_x_min, ct.x_min)
model.name = 'Resonant abosprotion'

sim = IDA(model)

x, U, dU = sim.simulate(ct.x_max, ct.nx)

# sim.plot()

# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.plot(ct.z, ct.dU_perp_x_min[0:ct.nz])
# ax.plot(ct.z, np.real(ct.du_perp_ana(ct.x_min,ct.z)))

# fig = plt.figure()
# ax = fig.add_subplot(111)
Example #38
0
        solver.sw[2] = not solver.sw[2]
        solver.sw[3] = not solver.sw[3]
        
    # State IV => State III
    if solver.sw[3]:
        solver.sw[3] = not solver.sw[3]
        solver.sw[2] = not solver.sw[2]          
        
        
        
        
y0,yp0 = init_woodpecker()
t0 = 0.0
sw0 = np.array([1,0,0,0])

model = Implicit_Problem(woodpecker,y0,yp0,t0,sw0)

model.state_events = state_events
model.handle_event = handle_event

solver = IDA(model)
solver.simulate(3)





        

        
	
Example #39
0
def run_example(with_plots=True):
    
    #Defines the residual
    def f(t,y,yd):
        
        res_0 = yd[0]-y[2]
        res_1 = yd[1]-y[3]
        res_2 = yd[2]+y[4]*y[0]
        res_3 = yd[3]+y[4]*y[1]+9.82
        #res_4 = y[0]**2+y[1]**2-1
        res_4 = y[2]**2+y[3]**2-y[4]*(y[0]**2+y[1]**2)-y[1]*9.82

        return N.array([res_0,res_1,res_2,res_3,res_4])
    
    #Defines the jacobian
    def jac(c,t,y,yd):
        jacobian = N.zeros([len(y),len(y)])
        
        #Derivative
        jacobian[0,0] = 1*c
        jacobian[1,1] = 1*c
        jacobian[2,2] = 1*c
        jacobian[3,3] = 1*c
        
        #Differentiated
        jacobian[0,2] = -1
        jacobian[1,3] = -1
        jacobian[2,0] = y[4]
        jacobian[3,1] = y[4]
        jacobian[4,0] = y[0]*2*y[4]*-1
        jacobian[4,1] = y[1]*2*y[4]*-1-9.82
        jacobian[4,2] = y[2]*2
        jacobian[4,3] = y[3]*2
        
        #Algebraic
        jacobian[2,4] = y[0]
        jacobian[3,4] = y[1]
        jacobian[4,4] = -(y[0]**2+y[1]**2)
        
        return jacobian
        
    #The initial conditons
    y0 = [1.0,0.0,0.0,0.0,5] #Initial conditions
    yd0 = [0.0,0.0,0.0,-9.82,0.0] #Initial conditions
    
    #Create an Assimulo implicit problem
    imp_mod = Implicit_Problem(f,y0,yd0)
    
    #Sets the options to the problem
    imp_mod.jac = jac #Sets the jacobian
    imp_mod.algvar = [1.0,1.0,1.0,1.0,0.0] #Set the algebraic components
    imp_mod.name = 'Test Jacobian'
    
    #Create an Assimulo implicit solver (IDA)
    imp_sim = IDA(imp_mod) #Create a IDA solver
    
    #Sets the paramters
    imp_sim.atol = 1e-6 #Default 1e-6
    imp_sim.rtol = 1e-6 #Default 1e-6
    imp_sim.suppress_alg = True #Suppres the algebraic variables on the error test
    
    #Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
    imp_sim.make_consistent('IDA_YA_YDP_INIT')
    
    #Simulate
    t, y, yd = imp_sim.simulate(5,1000) #Simulate 5 seconds with 1000 communication points
    
    #Basic tests
    nose.tools.assert_almost_equal(y[-1][0],0.9401995, places=4)
    nose.tools.assert_almost_equal(y[-1][1],-0.34095124, places=4)
    nose.tools.assert_almost_equal(yd[-1][0], -0.88198927, places=4)
    nose.tools.assert_almost_equal(yd[-1][1], -2.43227069, places=4)
    
    #Plot
    if with_plots:
        P.plot(t,y)
        P.show()
Example #40
0
t0 = 0.0


posIndex = list(range(0,7))
velocityIndex = list(range(7,14))
lambdaIndex = list(range(14,20))

algvar = numpy.ones(numpy.size(y0))

indexNumber = 1 
#1 - expl runge - index1 solution
#2 - index2
#3 - index3

if indexNumber == 3:
    problem = Implicit_Problem(squeezer3, y0, yd0, t0)
    algvar[lambdaIndex] = 0
    algvar[velocityIndex] = 0
    sim = IDA(problem)
    sim.atol = numpy.ones(numpy.size(y0))*1e-7
    sim.atol[lambdaIndex] = 1e-1
    sim.atol[velocityIndex] = 1e-5
elif indexNumber == 2:
    problem = Implicit_Problem(squeezer2, y0, yd0, t0)
    algvar[lambdaIndex] = 0
    algvar[velocityIndex] = 1
    sim = IDA(problem)
    sim.atol = numpy.ones(numpy.size(y0))*1e-7
    sim.atol[lambdaIndex] = 1e-5
    sim.atol[velocityIndex] = 1e-5
elif indexNumber == 1:
Example #41
0
    print('-1 ger inte true')
          
t0 = 0;
startsw = [1,0,0,0]
y0 = numpy.array([0.5, 0,0, -0, 0, 0.5,-1e-4,0])
yd0 =  numpy.array([-0, 0, 0.5,-g, 1e-12, 0, 0, 0])

w0 = -0.91
y0 = numpy.array([0.5, 0,0, -0, w0, w0,-1e-4,0])
yd0 =  numpy.array([-0, w0, w0,-g, 1e-12, 0, 0, 0])

#y0 = numpy.array([4.83617428e-01, -3.00000000e-02, -2.16050178e-01, 1.67315232e-16, -5.39725367e-14, -1.31300925e+01, -7.20313572e-02, -6.20545138e-02])
#yd0 = numpy.array([1.55140566e-17, -5.00453439e-15, -1.31302838e+01, 6.62087352e-13, -2.13577297e-10, 2.21484026e+02, -4.67637454e+00, -2.89824658e+00])
#startsw = [0,1, 0, 0]

problem = Implicit_Problem(res, y0, yd0, t0, sw0=startsw)

problem.state_events = state_events
problem.handle_event = handle_event
problem.name = 'Woodpecker'

phipIndex = [4, 5]
lambdaIndex = [6, 7]
sim = IDA(problem)
sim.rtol = 1e-6

sim.atol[phipIndex] = 1e8
sim.algvar[phipIndex] = 1
sim.atol[lambdaIndex] = 1e8
sim.algvar[lambdaIndex] = 1 
def run_example(with_plots=True):
    """
    This example show how to use Assimulo and IDA for simulating sensitivities
    for initial conditions.::
    
        0 = dy1/dt - -(k01+k21+k31)*y1 - k12*y2 - k13*y3 - b1
        0 = dy2/dt - k21*y1 + (k02+k12)*y2
        0 = 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, yd,p):
        y1,y2,y3 = y
        yd1,yd2,yd3 = yd
        k01 = 0.0211
        k02 = 0.0162
        k21 = 0.0111
        k12 = 0.0124
        k31 = 0.0039
        k13 = 0.000035
        b1 = 49.3
        
        res_0 = -yd1 -(k01+k21+k31)*y1+k12*y2+k13*y3+b1
        res_1 = -yd2 + k21*y1-(k02+k12)*y2
        res_2 = -yd3 + k31*y1-k13*y3
        
        return N.array([res_0,res_1,res_2])
    
    #The initial conditions
    y0 = [0.0,0.0,0.0]          #Initial conditions for y
    yd0 = [49.3,0.,0.]
    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 implicit problem
    imp_mod = Implicit_Problem(f,y0,yd0,p0=p0)
    
    #Sets the options to the problem
    imp_mod.yS0=yS0

    #Create an Assimulo explicit solver (IDA)
    imp_sim = IDA(imp_mod)
    
    #Sets the paramters
    imp_sim.rtol = 1e-7
    imp_sim.atol = 1e-6
    imp_sim.pbar = [1,1,1] #pbar is used to estimate the tolerances for the parameters
    imp_sim.continuous_output = True #Need to be able to store the result using the interpolate methods
    imp_sim.sensmethod = 'SIMULTANEOUS' #Defines the sensitvity method used
    imp_sim.suppress_sens = False            #Dont suppress the sensitivity variables in the error test.

    #Simulate
    t, y, yd = imp_sim.simulate(400) #Simulate 400 seconds
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0], 1577.6552477,3)
    nose.tools.assert_almost_equal(y[-1][1], 611.9574565, 3)
    nose.tools.assert_almost_equal(y[-1][2], 2215.88563217, 3)
    nose.tools.assert_almost_equal(imp_sim.p_sol[0][1][0], 1.0)
    
    #Plot
    if with_plots:
        P.figure(1)
        P.subplot(221)
        P.plot(t, N.array(imp_sim.p_sol[0])[:,0],
               t, N.array(imp_sim.p_sol[0])[:,1],
               t, N.array(imp_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(imp_sim.p_sol[1])[:,0],
               t, N.array(imp_sim.p_sol[1])[:,1],
               t, N.array(imp_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(imp_sim.p_sol[2])[:,0],
               t, N.array(imp_sim.p_sol[2])[:,1],
               t, N.array(imp_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()
Example #43
0
def simulate(model, init_cond, start_time=0., final_time=1., input=(lambda t: []), ncp=500, blt=True,
             causalization_options=sp.CausalizationOptions(), expand_to_sx=True, suppress_alg=False,
             tol=1e-8, solver="IDA"):
    """
    Simulate model from CasADi Interface using CasADi.

    init_cond is a dictionary containing initial conditions for all variables.
    """
    if blt:
        t_0 = timing.time()
        blt_model = sp.BLTModel(model, causalization_options)
        blt_time = timing.time() - t_0
        print("BLT analysis time: %.3f s" % blt_time)
        blt_model._model = model
        model = blt_model
    
    if causalization_options['closed_form']:
        solved_vars = model._solved_vars
        solved_expr = model._solved_expr
        #~ for (var, expr) in itertools.izip(solved_vars, solved_expr):
            #~ print('%s := %s' % (var.getName(), expr))
        return model
        dh() # This is not a debug statement!

    # Extract model variables
    model_states = [var for var in model.getVariables(model.DIFFERENTIATED) if not var.isAlias()]
    model_derivatives = [var for var in model.getVariables(model.DERIVATIVE) if not var.isAlias()]
    model_algs = [var for var in model.getVariables(model.REAL_ALGEBRAIC) if not var.isAlias()]
    model_inputs = [var for var in model.getVariables(model.REAL_INPUT) if not var.isAlias()]
    states = [var.getVar() for var in model_states]
    derivatives = [var.getMyDerivativeVariable().getVar() for var in model_states]
    algebraics = [var.getVar() for var in model_algs]
    inputs = [var.getVar() for var in model_inputs]
    n_x = len(states)
    n_y = len(states) + len(algebraics)
    n_w = len(algebraics)
    n_u = len(inputs)

    # Create vectorized model variables
    t = model.getTimeVariable()
    y = MX.sym("y", n_y)
    yd = MX.sym("yd", n_y)
    u = MX.sym("u", n_u)

    # Extract the residuals and substitute the (x,z) variables for the old variables
    scalar_vars = states + algebraics + derivatives + inputs
    vector_vars = [y[k] for k in range(n_y)] + [yd[k] for k in range(n_x)] + [u[k] for k in range(n_u)]
    [dae] = substitute([model.getDaeResidual()], scalar_vars, vector_vars)

    # Fix parameters
    if not blt:
        # Sort parameters
        par_kinds = [model.BOOLEAN_CONSTANT,
                     model.BOOLEAN_PARAMETER_DEPENDENT,
                     model.BOOLEAN_PARAMETER_INDEPENDENT,
                     model.INTEGER_CONSTANT,
                     model.INTEGER_PARAMETER_DEPENDENT,
                     model.INTEGER_PARAMETER_INDEPENDENT,
                     model.REAL_CONSTANT,
                     model.REAL_PARAMETER_INDEPENDENT,
                     model.REAL_PARAMETER_DEPENDENT]
        pars = reduce(list.__add__, [list(model.getVariables(par_kind)) for
                                     par_kind in par_kinds])

        # Get parameter values
        model.calculateValuesForDependentParameters()
        par_vars = [par.getVar() for par in pars]
        par_vals = [model.get_attr(par, "_value") for par in pars]

        # Eliminate parameters
        [dae] = casadi.substitute([dae], par_vars, par_vals)

    # Extract initial conditions
    y0 = [init_cond[var.getName()] for var in model_states] + [init_cond[var.getName()] for var in model_algs]
    yd0 = [init_cond[var.getName()] for var in model_derivatives] + n_w * [0.]

    # Create residual CasADi functions
    dae_res = MXFunction([t, y, yd, u], [dae])
    dae_res.setOption("name", "complete_dae_residual")
    dae_res.init()

    ###################
    #~ import matplotlib.pyplot as plt
    #~ h = MX.sym("h")
    #~ iter_matrix_expr = dae_res.jac(2)/h + dae_res.jac(1)
    #~ iter_matrix = MXFunction([t, y, yd, u, h], [iter_matrix_expr])
    #~ iter_matrix.init()
    #~ n = 100;
    #~ hs = np.logspace(-8, 1, n);
    #~ conds = [np.linalg.cond(iter_matrix.call([0, y0, yd0, input(0), hval])[0].toArray()) for hval in hs]
    #~ plt.close(1)
    #~ plt.figure(1)
    #~ plt.loglog(hs, conds, 'b-')
    #~ #plt.gca().invert_xaxis()
    #~ plt.grid('on')

    #~ didx = range(4, 12) + range(30, 33)
    #~ aidx = [i for i in range(33) if i not in didx]
    #~ didx = range(10)
    #~ aidx = []
    #~ F = MXFunction([t, y, yd, u], [dae[didx]])
    #~ F.init()
    #~ G = MXFunction([t, y, yd, u], [dae[aidx]])
    #~ G.init()
    #~ dFddx = F.jac(2)[:, :n_x]
    #~ dFdx = F.jac(1)[:, :n_x]
    #~ dFdy = F.jac(1)[:, n_x:]
    #~ dGdx = G.jac(1)[:, :n_x]
    #~ dGdy = G.jac(1)[:, n_x:]
    #~ E_matrix = MXFunction([t, y, yd, u, h], [dFddx])
    #~ E_matrix.init()
    #~ E_cond = np.linalg.cond(E_matrix.call([0, y0, yd0, input(0), hval])[0].toArray())
    #~ iter_matrix_expr = vertcat([horzcat([dFddx + h*dFdx, h*dFdy]), horzcat([dGdx, dGdy])])
    #~ iter_matrix = MXFunction([t, y, yd, u, h], [iter_matrix_expr])
    #~ iter_matrix.init()
    #~ n = 100
    #~ hs = np.logspace(-8, 1, n)
    #~ conds = [np.linalg.cond(iter_matrix.call([0, y0, yd0, input(0), hval])[0].toArray()) for hval in hs]
    #~ plt.loglog(hs, conds, 'b--')
    #~ plt.gca().invert_xaxis()
    #~ plt.grid('on')
    #~ plt.xlabel('$h$')
    #~ plt.ylabel('$\kappa$')
    
    #~ plt.show()
    #~ dh()
    ###################

    # Expand to SX
    if expand_to_sx:
        dae_res = SXFunction(dae_res)
        dae_res.init()

    # Create DAE residual Assimulo function
    def dae_residual(t, y, yd):
        dae_res.setInput(t, 0)
        dae_res.setInput(y, 1)
        dae_res.setInput(yd, 2)
        dae_res.setInput(input(t), 3)
        dae_res.evaluate()
        return dae_res.getOutput(0).toArray().reshape(-1)

    # Set up simulator
    problem = Implicit_Problem(dae_residual, y0, yd0, start_time)
    if solver == "IDA":
        simulator = IDA(problem)
    elif solver == "Radau5DAE":
        simulator = Radau5DAE(problem)
    else:
        raise ValueError("Unknown solver %s" % solver)
    simulator.rtol = tol
    simulator.atol = 1e-4 * np.array([model.get_attr(var, "nominal") for var in model_states + model_algs])
    #~ simulator.atol = tol * np.ones([n_y, 1])
    simulator.report_continuously = True

    # Log method order
    if solver == "IDA":
        global order
        order = []
        def handle_result(solver, t, y, yd):
            global order
            order.append(solver.get_last_order())
            solver.t_sol.extend([t])
            solver.y_sol.extend([y])
            solver.yd_sol.extend([yd])
        problem.handle_result = handle_result

    # Suppress algebraic variables
    if suppress_alg:
        if isinstance(suppress_alg, bool):
            simulator.algvar = n_x * [True] + (n_y - n_x) * [False]
        else:
            simulator.algvar = n_x * [True] + suppress_alg
        simulator.suppress_alg = True

    # Simulate
    t_0 = timing.time()
    (t, y, yd) = simulator.simulate(final_time, ncp)
    simul_time = timing.time() - t_0
    stats = {'time': simul_time, 'steps': simulator.statistics['nsteps']}
    if solver == "IDA":
        stats['order'] = order

    # Generate result for time and inputs
    class SimulationResult(dict):
        pass
    res = SimulationResult()
    res.stats = stats
    res['time'] = t
    if u.numel() > 0:
        input_names = [var.getName() for var in model_inputs]
        for name in input_names:
            res[name] = []
        for time in t:
            input_val = input(time)
            for (name, val) in itertools.izip(input_names, input_val):
                res[name].append(val)

    # Create results for everything else
    if blt:
        # Iteration variables
        i = 0
        for var in model_states:
            res[var.getName()] = y[:, i]
            res[var.getMyDerivativeVariable().getName()] = yd[:, i]
            i += 1
        for var in model_algs:
            res[var.getName()] = y[:, i]
            i += 1

        # Create function for computing solved algebraics
        for (_, sol_alg) in model._explicit_solved_algebraics:
            res[sol_alg.name] = []
        alg_sol_f = casadi.MXFunction(model._known_vars + model._explicit_unsolved_vars, model._solved_expr)
        alg_sol_f.init()
        if expand_to_sx:
            alg_sol_f = casadi.SXFunction(alg_sol_f)
            alg_sol_f.init()

        # Compute solved algebraics
        for k in xrange(len(t)):
            for (i, var) in enumerate(model._known_vars + model._explicit_unsolved_vars):
                alg_sol_f.setInput(res[var.getName()][k], i)
            alg_sol_f.evaluate()
            for (j, sol_alg) in model._explicit_solved_algebraics:
                res[sol_alg.name].append(alg_sol_f.getOutput(j).toScalar())
    else:
        res_vars = model_states + model_algs
        for (i, var) in enumerate(res_vars):
            res[var.getName()] = y[:, i]
            der_var = var.getMyDerivativeVariable()
            if der_var is not None:
                res[der_var.getName()] = yd[:, i]

    # Add results for all alias variables (only treat time-continuous variables) and convert to array
    if blt:
        res_model = model._model
    else:
        res_model = model
    for var in res_model.getAllVariables():
        if var.getVariability() == var.CONTINUOUS:
            res[var.getName()] = np.array(res[var.getModelVariable().getName()])
    res["time"] = np.array(res["time"])
    res._blt_model = blt_model
    return res
			print("II to I")
		
	elif state_info[3] != 0:
		if solver.sw[2] == 1 and yp[2] > 0:
			yp[2] = -yp[2]
			print("DING")
	solver.yd = yp
	solver.y = y	
 
t0 = 0
tfinal = 1
ncp = 500
y0 = [0., -0.10344, -0.65, 0. ,0. , 0., -0.6911, -0.14161]
yp0 = [0., 0., 0., 0., 0., 1.40059e2, 0., 0.]
switches0 = [False, True, False]
mod = Implicit_Problem(woodpeckertoy, y0, yp0, t0, sw0 = switches0)
mod.state_events = state_events
mod.handle_event = handle_event

sim = IDA(mod)
sim.suppress_alg = True
sim.rtol=1.e-6
sim.atol[3:8] = 1e6
sim.algvar[3:8] = 0.
t, y, yp = sim.simulate(tfinal, ncp)

P.plot(t,y[:,0:3])
P.legend(["z","phiS", "phiB", "z vel", "phiS vel", "phiB vel"])
P.ylabel('y')
P.xlabel('x')
fontlabel_size = 20
Example #45
0
def dae_solver(residual,
               y0,
               yd0,
               t0,
               p0=None,
               jac=None,
               name='DAE',
               solver='IDA',
               algvar=None,
               atol=1e-6,
               backward=False,
               display_progress=True,
               pbar=None,
               report_continuously=False,
               rtol=1e-6,
               sensmethod='STAGGERED',
               suppress_alg=False,
               suppress_sens=False,
               usejac=False,
               usesens=False,
               verbosity=30,
               tfinal=10.,
               ncp=500):
    '''
    DAE solver.

    Parameters
    ----------
    residual: function
        Implicit DAE model.
    y0: List[float]
        Initial model state.
    yd0: List[float]
        Initial model state derivatives.
    t0: float
        Initial simulation time.
    p0: List[float]
        Parameters for which sensitivites are to be calculated.
    jac: function
        Model jacobian.
    name: string
        Model name.
    solver: string
        DAE solver.
    algvar: List[bool]
        A list for defining which variables are differential and which are algebraic.
        The value True(1.0) indicates a differential variable and the value False(0.0) indicates an algebraic variable.
    atol: float
        Absolute tolerance.
    backward: bool
        Specifies if the simulation is done in reverse time.
    display_progress: bool
        Actives output during the integration in terms of that the current integration is periodically printed to the stdout.
        Report_continuously needs to be activated.
    pbar: List[float]
        An array of positive floats equal to the number of parameters. Default absolute values of the parameters.
        Specifies the order of magnitude for the parameters. Useful if IDAS is to estimate tolerances for the sensitivity solution vectors.
    report_continuously: bool
        Specifies if the solver should report the solution continuously after steps.
    rtol: float
        Relative tolerance.
    sensmethod: string
        Specifies the sensitivity solution method.
        Can be either ‘SIMULTANEOUS’ or ‘STAGGERED’. Default is 'STAGGERED'.
    suppress_alg: bool
        Indicates that the error-tests are suppressed on algebraic variables.
    suppress_sens: bool
        Indicates that the error-tests are suppressed on the sensitivity variables.
    usejac: bool
        Sets the option to use the user defined jacobian.
    usesens: bool
        Aactivates or deactivates the sensitivity calculations.
    verbosity: int
        Determines the level of the output.
        QUIET = 50 WHISPER = 40 NORMAL = 30 LOUD = 20 SCREAM = 10
    tfinal: float
        Simulation final time.
    ncp: int
        Number of communication points (number of return points).

    Returns
    -------
    sol: solution [time, model states], List[float]
    '''
    if usesens is True:  # parameter sensitivity
        model = Implicit_Problem(residual, y0, yd0, t0, p0=p0)
    else:
        model = Implicit_Problem(residual, y0, yd0, t0)

    model.name = name

    if usejac is True:  # jacobian
        model.jac = jac

    if algvar is not None:  # differential or algebraic variables
        model.algvar = algvar

    if solver == 'IDA':  # solver
        from assimulo.solvers import IDA
        sim = IDA(model)

    sim.atol = atol
    sim.rtol = rtol
    sim.backward = backward  # backward in time
    sim.report_continuously = report_continuously
    sim.display_progress = display_progress
    sim.suppress_alg = suppress_alg
    sim.verbosity = verbosity

    if usesens is True:  # sensitivity
        sim.sensmethod = sensmethod
        sim.pbar = np.abs(p0)
        sim.suppress_sens = suppress_sens

    # Simulation
    # t, y, yd = sim.simulate(tfinal, ncp=(ncp - 1))
    ncp_list = np.linspace(t0, tfinal, num=ncp, endpoint=True)
    t, y, yd = sim.simulate(tfinal, ncp=0, ncp_list=ncp_list)

    # Plot
    # sim.plot()

    # plt.figure()
    # plt.subplot(221)
    # plt.plot(t, y[:, 0], 'b.-')
    # plt.legend([r'$\lambda$'])
    # plt.subplot(222)
    # plt.plot(t, y[:, 1], 'r.-')
    # plt.legend([r'$\dot{\lambda}$'])
    # plt.subplot(223)
    # plt.plot(t, y[:, 2], 'k.-')
    # plt.legend([r'$\eta$'])
    # plt.subplot(224)
    # plt.plot(t, y[:, 3], 'm.-')
    # plt.legend([r'$\dot{\eta}$'])

    # plt.figure()
    # plt.subplot(221)
    # plt.plot(t, yd[:, 0], 'b.-')
    # plt.legend([r'$\dot{\lambda}$'])
    # plt.subplot(222)
    # plt.plot(t, yd[:, 1], 'r.-')
    # plt.legend([r'$\ddot{\lambda}$'])
    # plt.subplot(223)
    # plt.plot(t, yd[:, 2], 'k.-')
    # plt.legend([r'$\dot{\eta}$'])
    # plt.subplot(224)
    # plt.plot(t, yd[:, 3], 'm.-')
    # plt.legend([r'$\ddot{\eta}$'])

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(y[:, 0], y[:, 1])
    # plt.xlabel(r'$\lambda$')
    # plt.ylabel(r'$\dot{\lambda}$')
    # plt.subplot(122)
    # plt.plot(y[:, 2], y[:, 3])
    # plt.xlabel(r'$\eta$')
    # plt.ylabel(r'$\dot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(yd[:, 0], yd[:, 1])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\ddot{\lambda}$')
    # plt.subplot(122)
    # plt.plot(yd[:, 2], yd[:, 3])
    # plt.xlabel(r'$\dot{\eta}$')
    # plt.ylabel(r'$\ddot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(y[:, 0], y[:, 2])
    # plt.xlabel(r'$\lambda$')
    # plt.ylabel(r'$\eta$')
    # plt.subplot(122)
    # plt.plot(y[:, 1], y[:, 3])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\dot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(yd[:, 0], yd[:, 2])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\dot{\eta}$')
    # plt.subplot(122)
    # plt.plot(yd[:, 1], yd[:, 3])
    # plt.xlabel(r'$\ddot{\lambda}$')
    # plt.ylabel(r'$\ddot{\eta}$')

    # plt.show()

    sol = [t, y, yd]
    return sol
Example #46
0
import numpay as np
import pylab as P
from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA

y0 = np.array([0 0 0 0 0 0 0])
yp0 = np.array([0 0 0 0 0 0 0])
t0 = 0.0



model = Implicit_Problem(squeezer, y0, yp0, t0)
model.name = 'Squeezer'

solver = IDA(model)


Example #47
0
def run_example(with_plots=True):
    """
    This example show how to use Assimulo and IDA for simulating sensitivities
    for initial conditions.::
    
        0 = dy1/dt - -(k01+k21+k31)*y1 - k12*y2 - k13*y3 - b1
        0 = dy2/dt - k21*y1 + (k02+k12)*y2
        0 = 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
    
    on return:
    
       - :dfn:`imp_mod`    problem instance
    
       - :dfn:`imp_sim`    solver instance
    
    """
    def f(t, y, yd, p):
        y1, y2, y3 = y
        yd1, yd2, yd3 = yd
        k01 = 0.0211
        k02 = 0.0162
        k21 = 0.0111
        k12 = 0.0124
        k31 = 0.0039
        k13 = 0.000035
        b1 = 49.3

        res_0 = -yd1 - (k01 + k21 + k31) * y1 + k12 * y2 + k13 * y3 + b1
        res_1 = -yd2 + k21 * y1 - (k02 + k12) * y2
        res_2 = -yd3 + k31 * y1 - k13 * y3

        return N.array([res_0, res_1, res_2])

    #The initial conditions
    y0 = [0.0, 0.0, 0.0]  #Initial conditions for y
    yd0 = [49.3, 0., 0.]
    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 implicit problem
    imp_mod = Implicit_Problem(f,
                               y0,
                               yd0,
                               p0=p0,
                               name='Example: Computing Sensitivities')

    #Sets the options to the problem
    imp_mod.yS0 = yS0

    #Create an Assimulo explicit solver (IDA)
    imp_sim = IDA(imp_mod)

    #Sets the paramters
    imp_sim.rtol = 1e-7
    imp_sim.atol = 1e-6
    imp_sim.pbar = [
        1, 1, 1
    ]  #pbar is used to estimate the tolerances for the parameters
    imp_sim.report_continuously = True  #Need to be able to store the result using the interpolate methods
    imp_sim.sensmethod = 'SIMULTANEOUS'  #Defines the sensitvity method used
    imp_sim.suppress_sens = False  #Dont suppress the sensitivity variables in the error test.

    #Simulate
    t, y, yd = imp_sim.simulate(400)  #Simulate 400 seconds

    #Basic test
    nose.tools.assert_almost_equal(y[-1][0], 1577.6552477, 3)
    nose.tools.assert_almost_equal(y[-1][1], 611.9574565, 3)
    nose.tools.assert_almost_equal(y[-1][2], 2215.88563217, 3)
    nose.tools.assert_almost_equal(imp_sim.p_sol[0][1][0], 1.0)

    #Plot
    if with_plots:
        P.figure(1)
        P.subplot(221)
        P.plot(t,
               N.array(imp_sim.p_sol[0])[:, 0], t,
               N.array(imp_sim.p_sol[0])[:, 1], t,
               N.array(imp_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(imp_sim.p_sol[1])[:, 0], t,
               N.array(imp_sim.p_sol[1])[:, 1], t,
               N.array(imp_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(imp_sim.p_sol[2])[:, 0], t,
               N.array(imp_sim.p_sol[2])[:, 1], t,
               N.array(imp_sim.p_sol[2])[:, 2])
        P.title("Parameter p3")
        P.legend(("p3/dy1", "p3/dy2", "p3/dy3"))
        P.subplot(224)
        P.title('ODE Solution')
        P.plot(t, y)
        P.suptitle(imp_mod.name)
        P.show()

        return imp_mod, imp_sim
Example #48
0
def run_example(with_plots=True):
    r"""
    An example for IDA with scaled preconditioned GMRES method
    as a special linear solver.
    Note, how the operation Jacobian times vector is provided.
    
    ODE:
    
    .. math::
       
       \dot y_1 - y_2 &= 0\\
       \dot y_2 -9.82 &= 0
       
    
    on return:
    
       - :dfn:`imp_mod`    problem instance
    
       - :dfn:`imp_sim`    solver instance
       
    """

    #Defines the residual
    def res(t, y, yd):
        res_0 = yd[0] - y[1]
        res_1 = yd[1] + 9.82

        return N.array([res_0, res_1])

    #Defines the Jacobian*vector product
    def jacv(t, y, yd, res, v, c):
        jy = N.array([[0, -1.], [0, 0]])
        jyd = N.array([[1, 0.], [0, 1]])
        j = jy + c * jyd
        return N.dot(j, v)

    #Initial conditions
    y0 = [1.0, 0.0]
    yd0 = [0.0, -9.82]

    #Defines an Assimulo implicit problem
    imp_mod = Implicit_Problem(
        res, y0, yd0, name='Example using the Jacobian Vector product')

    imp_mod.jacv = jacv  #Sets the jacobian

    imp_sim = IDA(imp_mod)  #Create an IDA solver instance

    #Set the parameters
    imp_sim.atol = 1e-5  #Default 1e-6
    imp_sim.rtol = 1e-5  #Default 1e-6
    imp_sim.linear_solver = 'SPGMR'  #Change linear solver
    #imp_sim.options["usejac"] = False

    #Simulate
    t, y, yd = imp_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.xlabel('Time')
        P.ylabel('State')
        P.title(imp_mod.name)
        P.show()
    return imp_mod, imp_sim