Ejemplo n.º 1
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
Ejemplo n.º 2
0
 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"
Ejemplo n.º 3
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
Ejemplo n.º 4
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()
Ejemplo n.º 5
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)
Ejemplo n.º 6
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
Ejemplo n.º 7
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
Ejemplo n.º 8
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"]
Ejemplo n.º 9
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)
Ejemplo n.º 10
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
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
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)
Ejemplo n.º 15
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()
Ejemplo n.º 16
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
Ejemplo n.º 17
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
Ejemplo n.º 18
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)
Ejemplo n.º 19
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
Ejemplo n.º 20
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.)
Ejemplo n.º 21
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
Ejemplo n.º 22
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)
Ejemplo n.º 23
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
Ejemplo n.º 24
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)
Ejemplo n.º 25
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.º 26
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
Ejemplo n.º 27
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
Ejemplo n.º 28
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)
Ejemplo n.º 29
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
Ejemplo n.º 30
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