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()
Exemplo n.º 2
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()
Exemplo n.º 3
0
def run_example(index="ind1", with_plots=True, with_test=False):
    my_pend_sys = pendulum()
    my_pend = my_pend_sys.generate_problem(index)
    my_pend.name = 'Index = {}'.format(index)
    dae_pend = IDA(my_pend) if index not in ('ovstab2',
                                             'ovstab1') else ODASSL(my_pend)
    dae_pend.atol = 1.e-6
    dae_pend.rtol = 1.e-6
    dae_pend.suppress_alg = True
    t, y, yd = dae_pend.simulate(10., 100)
    final_residual = my_pend.res(0., dae_pend.y, dae_pend.yd)

    print(my_pend.name + "  Residuals after the integration run\n")
    print(final_residual, 'Norm:  ', sl.norm(final_residual))

    if with_test:
        assert (sl.norm(final_residual) < 1.5e-1)
    if with_plots:
        dae_pend.plot(mask=[1, 1] + (len(my_pend.y0) - 2) * [0])
    return my_pend, dae_pend
Exemplo n.º 4
0
    def buildsim(self, ):
        """
        Setup the assimulo IDA simulator.
        """
        # Create an Assimulo implicit solver (IDA)
        imp_sim = IDA(self.imp_mod)  # Create a IDA solver

        # Sets the paramters
        # 1e-4 #Default 1e-6
        imp_sim.atol = self.p.RunInput['TIMESTEPPING']['SOLVER_TOL']
        # 1e-4 #Default 1e-6
        imp_sim.rtol = self.p.RunInput['TIMESTEPPING']['SOLVER_TOL']
        # Suppres the algebraic variables on the error test
        imp_sim.suppress_alg = True

        imp_sim.display_progress = False
        imp_sim.verbosity = 50
        imp_sim.report_continuously = True
        imp_sim.time_limit = 10.

        self.imp_sim = imp_sim
Exemplo n.º 5
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()
Exemplo n.º 6
0
def run_example(with_plots=True):
    r"""
    Example for demonstrating the use of a user supplied Jacobian
    
    ODE:
    
    .. math::
       
        \dot y_1-y_3 &= 0 \\
        \dot y_2-y_4 &= 0 \\
        \dot y_3+y_5 y_1 &= 0 \\
        \dot y_4+y_5 y_2+9.82&= 0 \\
        y_3^2+y_4^2-y_5(y_1^2+y_2^2)-9.82 y_2&= 0 
    
    on return:
    
       - :dfn:`imp_mod`    problem instance
    
       - :dfn:`imp_sim`    solver instance
       
    """

    #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[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,
                               name='Example using an analytic Jacobian')

    #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

    #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:
        import pylab as P
        P.plot(t, y, linestyle="dashed", marker="o")  #Plot the solution
        P.xlabel('Time')
        P.ylabel('State')
        P.title(imp_mod.name)
        P.show()

    return imp_mod, imp_sim
Exemplo n.º 7
0
def run_example(with_plots=True):
    r"""
    This is the same example from the Sundials package (cvsRoberts_FSA_dns.c)
    Its purpose is to demonstrate the use of parameters in the differential equation.

    This simple example problem for IDA, due to Robertson
    see http://www.dm.uniba.it/~testset/problems/rober.php,
    is from chemical kinetics, and consists of the system:

    .. math::

       \dot y_1 -( -p_1 y_1 + p_2 y_2 y_3)&=0 \\
       \dot y_2 -(p_1 y_1 - p_2 y_2 y_3 - p_3 y_2^2)&=0  \\
       \dot y_3 -( p_3  y_ 2^2)&=0


    on return:

       - :dfn:`imp_mod`    problem instance

       - :dfn:`imp_sim`    solver instance

    """

    def f(t, y, yd, p):
        res1 = -p[0] * y[0] + p[1] * y[1] * y[2] - yd[0]
        res2 = p[0] * y[0] - p[1] * y[1] * y[2] - p[2] * y[1] ** 2 - yd[1]
        res3 = y[0] + y[1] + y[2] - 1

        return N.array([res1, res2, res3])

    # The initial conditons
    y0 = N.array([1.0, 0.0, 0.0])  # Initial conditions for y
    yd0 = N.array([0.1, 0.0, 0.0])  # Initial conditions for dy/dt
    p0 = [0.040, 1.0e4, 3.0e7]  # Initial conditions for parameters

    # Create an Assimulo implicit problem
    imp_mod = Implicit_Problem(f, y0, yd0, p0=p0)

    # Create an Assimulo implicit solver (IDA)
    imp_sim = IDA(imp_mod)  # Create a IDA solver

    # Sets the paramters
    imp_sim.atol = N.array([1.0e-8, 1.0e-14, 1.0e-6])
    imp_sim.algvar = [1.0, 1.0, 0.0]
    imp_sim.suppress_alg = False  # Suppres the algebraic variables on the error test
    imp_sim.report_continuously = True  # Store data continuous during the simulation
    imp_sim.pbar = p0
    imp_sim.suppress_sens = False  # Dont suppress the sensitivity variables in 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(4, 400)  # Simulate 4 seconds with 400 communication points
    print(imp_sim.p_sol[0][-1], imp_sim.p_sol[1][-1], imp_sim.p_sol[0][-1])

    # Basic test
    nose.tools.assert_almost_equal(y[-1][0], 9.05518032e-01, 4)
    nose.tools.assert_almost_equal(y[-1][1], 2.24046805e-05, 4)
    nose.tools.assert_almost_equal(y[-1][2], 9.44595637e-02, 4)
    nose.tools.assert_almost_equal(imp_sim.p_sol[0][-1][0], -1.8761, 2)  # Values taken from the example in Sundials
    nose.tools.assert_almost_equal(imp_sim.p_sol[1][-1][0], 2.9614e-06, 8)
    nose.tools.assert_almost_equal(imp_sim.p_sol[2][-1][0], -4.9334e-10, 12)

    # Plot
    if with_plots:
        P.plot(t, y)
        P.title(imp_mod.name)
        P.xlabel('Time')
        P.ylabel('State')
        P.show()

    return imp_mod, imp_sim
Exemplo n.º 8
0
#plt.show()

#print z_out

#Sets the options to the problem
#imp_mod.jac = jac #Sets the jacobian
imp_mod.algvar = [1.0 for i in range(N)] + [0.0 for i in range(N+Na+Nc)] #Set the algebraic components
#imp_mod.algvar = [1.0 for i in range(N)] + [0.0 for i in range(N)] #Set the algebraic components

#Create an Assimulo implicit solver (IDA)
imp_sim = IDA(imp_mod) #Create a IDA solver

#Sets the paramters
imp_sim.atol = 1e-5 #Default 1e-6
imp_sim.rtol = 1e-5 #Default 1e-6
imp_sim.suppress_alg = True #Suppres the algebraic variables on the error test


### Simulate
imp_mod.set_j_vec( I_app )

#res_test = imp_mod.res( 0.0, y0, yd0 )
#jac_test = imp_mod.jac( 2, 0.0, y0, yd0 )

#Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
imp_sim.make_consistent('IDA_YA_YDP_INIT')
# Sim step 1
t1, y1, yd1 = imp_sim.simulate(100,100) 
#t1, y1, yd1 = imp_sim.simulate(1000,1000) 

imp_mod.set_j_vec( 0.0 )
Exemplo n.º 9
0
    def DAE_integration_assimulo(self, **kwargs):
        """
        Perform time integration for DAEs with the assimulo package
        """
        assert self.set_time_setting == 1, 'Time discretization must be specified first'
        
        if self.tclose > 0:
            close    = True
        else:
            close    = False
            
        # Control vector
        self.U = interpolate(self.boundary_cntrl_space, self.Vb).vector()[self.bndr_i_b]
        if self.discontinous_boundary_values == 1:
            self.U[self.Corner_indices] = self.U[self.Corner_indices]/2

        # Definition of the sparse solver for the DAE res function to
        # be defined next M should be invertible !! 
        my_solver = factorized(csc_matrix(self.M))
        rhs       = self.my_mult(self.J, self.my_mult(self.Q,self.A0)) + self.my_mult(self.Bext,self.U* self.boundary_cntrl_time(0.,self.tclose))
        self.AD0  = my_solver(rhs) 
        
        # Definition of the rhs function required in assimulo
        def res(t,y,yd):
            """
            Definition of the residual function required in the DAE part of assimulo
            """   
            if close:
                if t < self.tclose:
                    z = self.my_mult(self.M,yd) - self.my_mult(self.J, self.my_mult(self.Q,y)) - self.my_mult(self.Bext,self.U* self.boundary_cntrl_time(t,self.tclose))
                else:
                    z = self.my_mult(self.M,yd) - self.my_mult((self.J - self.R), self.my_mult(self.Q,y))
            else:
                z = self.my_mult(self.M,yd) - self.my_mult(self.J, self.my_mult(self.Q,y)) - self.my_mult(self.Bext,self.U* self.boundary_cntrl_time(t,self.tclose)) 
            
            return z
  

        # Definition of the jacobian function required in assimulo
        def jac(c,t,y,yd):
            """
            Definition of the Jacobian matrix required in the DAE part of assimulo
            """  
            Matrix = csr_matrix(self.my_mult(self.J,self.Q))
            
            if close and t > self.tclose:
                    Matrix = csr_matrix(self.my_mult(self.J - self.R, self.Q))
            
            return c*csr_matrix(self.M) - Matrix
        
        # Definition of the jacobian matrix vector function required in assimulo
        def jacv(t,y,yd,res,v,c):
            """
            Jacobian matrix-vector product required in the DAE part of assimulo
            """  
            w = self.my_mult(self.Q, v)
            z = self.my_mult(self.J, w)
            
            if close and t > self.tclose:
                z -= self.my_mult(self.R, w)
                
            return c*self.my_mult(self.M,v) - z
        
        print('DAE Integration using assimulo built-in functions:')

        
        model                     = Implicit_Problem(res,self.A0,self.AD0,self.tinit)
        model.jacv                = jacv
        #sim                       = Radau5DAE(model,**kwargs)
        #
        # IDA method from Assimulo
        #
        sim                       = IDA(model,**kwargs)
        sim.algvar                = [1 for i in range(self.M.shape[0])]
        sim.atol                  = 1.e-6
        sim.rtol                  = 1.e-6
        sim.report_continuously   = True
        ncp                       = self.Nt
        sim.usejac                = True
        sim.suppress_alg          = True
        sim.inith                 = self.dt
        sim.maxord                = 5
        #sim.linear_solver         = 'SPGMR'
        time_span, DAE_y, DAE_yd  = sim.simulate(self.tfinal,ncp)
        
        #print(sim.get_options())
        print(sim.print_statistics())
        
        A_dae = DAE_y.transpose()
        
        # Hamiltonian
        self.Nt    = A_dae.shape[1]
        self.tspan = np.array(time_span)
        
        Ham_dae = np.zeros(self.Nt)
        
        for k in range(self.Nt):
            #Ham_dae[k] = 1/2 * A_dae[:,k] @ self.M @ self.Q @ A_dae[:,k]
            Ham_dae[k] = 1/2 * self.my_mult(A_dae[:,k].T, \
                               self.my_mult(self.M, self.my_mult(self.Q, A_dae[:,k])))
      
        # Get q variables
        Aq_dae = A_dae[:self.Nq,:] 
        
        # Get p variables
        Ap_dae = A_dae[self.Nq:,:]

        # Get Deformation
        Rho = np.zeros(self.Np)
        for i in range(self.Np):
            Rho[i] = self.rho(self.coord_p[i])
            
        W_dae = np.zeros((self.Np,self.Nt))
        theta = .5
        for k in range(self.Nt-1):
            W_dae[:,k+1] = W_dae[:,k] + self.dt * 1/Rho[:] * ( theta * Ap_dae[:,k+1] + (1-theta) * Ap_dae[:,k] ) 

        self.Ham_dae = Ham_dae
    
        return Aq_dae, Ap_dae, Ham_dae, W_dae, np.array(time_span)    
Exemplo n.º 10
0
def run_example(with_plots=True):
    r"""
    Example for demonstrating the use of a user supplied Jacobian
    
    ODE:
    
    .. math::
       
        \dot y_1-y_3 &= 0 \\
        \dot y_2-y_4 &= 0 \\
        \dot y_3+y_5 y_1 &= 0 \\
        \dot y_4+y_5 y_2+9.82&= 0 \\
        y_3^2+y_4^2-y_5(y_1^2+y_2^2)-9.82 y_2&= 0 
    
    on return:
    
       - :dfn:`imp_mod`    problem instance
    
       - :dfn:`imp_sim`    solver instance
       
    """
    global order
    order = []

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

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

    #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,
                               name='Example for plotting used order')
    imp_mod.handle_result = handle_result

    #Sets the options to the problem
    imp_mod.algvar = [1.0, 1.0, 1.0, 1.0, 0.0]  #Set the algebraic components

    #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
    imp_sim.report_continuously = True

    #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)  #Simulate 5 seconds

    #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)
    nose.tools.assert_almost_equal(order[-1], 5, places=4)

    #Plot
    if with_plots:
        P.figure(1)
        P.plot(t, y, linestyle="dashed", marker="o")  #Plot the solution
        P.xlabel('Time')
        P.ylabel('State')
        P.title(imp_mod.name)

        P.figure(2)
        P.plot([0] + N.add.accumulate(N.diff(t)).tolist(), order)
        P.title("Used order during the integration")
        P.xlabel("Time")
        P.ylabel("Order")
        P.show()

    return imp_mod, imp_sim
Exemplo n.º 11
0
from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA
import matplotlib.pyplot as P
import numpy as N

t0 = 0.0
tfinal = 2.0
y0, yd0, switches0 = init_woodpecker()

model = Implicit_Problem(res, y0, yd0, t0, sw0=switches0)
model.state_events = state_event
model.handle_event = handle_event

sim = IDA(model)
sim.algvar = [1, 1, 1, 0, 0, 0, 0, 0]
sim.suppress_alg = True
sim.atol = [1e-5, 1e-5, 1e-5, 1e15, 1e15, 1e15, 1e15, 1e15]
t, y, yd = sim.simulate(tfinal)

#sim.print_event_data()
"""
    Plotting

    y[:,0] - plots z (height)
    y[:,1] - plots sleeve angle
    y[:,2] - plots bird angle
"""

# Plot z (height)
P.plot(t, y[:, 0])
P.title('Woodpecker')
Exemplo n.º 12
0
from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA
from Project_2 import squeezer as sq
from Project_2 import squeezer2 as sq2
import matplotlib.pyplot as plt

t0 = 0
tfinal = 0.03

# Model 1, squeezer with index 3 constraints
y0_1,yp0_1 = sq.init_squeezer()
ncp_1 = 100
model_1 = Implicit_Problem(sq.squeezer, y0_1, yp0_1, t0)
model_1.name = 'Squeezer index 3 constraints'
sim_1 = IDA(model_1)
sim_1.suppress_alg = True
sim_1.algvar = array([1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0])
sim_1.atol = ones(20,)
for i in range(size(sim_1.atol)):
    if 0 <= i <= 6:
        sim_1.atol[i] = pow(10,-6)
    else:
        sim_1.atol[i] = pow(10,5)
t, y, yd = sim_1.simulate(tfinal, ncp_1)
plt.plot(t,y[:,14:shape(y)[1]]) # Plots the Lagrange multipliers
plt.show()
plt.plot(t,(y[:,0:7]+pi)%(2*pi)-pi) # Plots the position variables i.e beta,gamma etc, modulo 2pi.
plt.show()

# Model 2, squeezer with index 2 constraints
y0_2,yp0_2 = sq2.init_squeezer()
Exemplo n.º 13
0
    def DAE_integration_assimulo_lagrangian(self, **kwargs):
        """
        Perform time integration for DAEs with the assimulo package
        Lagrangian variant
        """
        assert self.set_time_setting == 1, 'Time discretization must be specified first'
        
        if self.tclose > 0:
            close    = True
        else:
            close    = False
            
        # Control vector
        self.U = interpolate(self.boundary_cntrl_space, self.Vl).vector()[self.bndr_i_l]
        if self.discontinous_boundary_values == 1:
            self.U[self.Corner_indices] = self.U[self.Corner_indices]/2
            
        self.UU = np.zeros(self.Nb)
        for i in range(self.Nb):
            self.UU[i] = self.boundary_cntrl_space(self.coord_b[i])
        

        # Definition of the sparse solver for the DAE res function to
        # be defined next M should be invertible !! 
        #my_solver = factorized(csc_matrix(self.M))
        #rhs       = self.my_mult(self.J, self.my_mult(self.Q,self.A0)) + self.my_mult(self.Bext,self.U* self.boundary_cntrl_time(0.,self.tclose))
        #self.AD0  = my_solver(rhs) 
        
        # Definition of the rhs function required in assimulo
        def res(t,y,yd):
            """
            Definition of the residual function required in the DAE part of assimulo
            """   
            z                                    = np.zeros(self.Np+self.Nl)        
            z[0:self.Np]                         = self.my_mult(self.M_class, yd[0:self.Np])  + self.my_mult(self.D_class, y[0:self.Np]) - self.my_mult(self.C_class, y[self.Np:])
            z[self.Np:self.Np+self.Nl]           = self.my_mult(self.C_class.T, y[0:self.Np]) - self.L_class * self.boundary_cntrl_time(t,self.tclose)
            
            return z
  
        # Definition of the jacobian function required in assimulo
        def jac(c,t,y,yd):
            """
            Definition of the Jacobian matrix required in the DAE part of assimulo
            """  
            #Matrix = csr_matrix(self.my_mult(self.J,self.Q))
            
            #if close and t > self.tclose:
            #        Matrix = csr_matrix(self.my_mult(self.J - self.R, self.Q))
            
            #return c*csr_matrix(self.M) - Matrix
            
            return None
        
        # Definition of the jacobian matrix vector function required in assimulo
        def jacv(t,y,yd,res,v,c):
            """
            Jacobian matrix-vector product required in the DAE part of assimulo
            """  
            #w = self.my_mult(self.Q, v)
            #z = self.my_mult(self.J, w)
            
            #if close and t > self.tclose:
            #    z -= self.my_mult(self.R, w)
                
            #return c*self.my_mult(self.M,v) - z
            
            return None
        
        print('DAE Integration using assimulo built-in functions:')

        #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]) 
            
        # The initial conditons
        y0  =  np.concatenate(( self.Tp0, np.zeros(self.Nl) )) 
        yd0 =  np.zeros(self.Np + self.Nl)     
        
        model                     = Implicit_Problem(res,y0,yd0,self.tinit)
        #model.handle_result       = handle_result
        #model.jacv                = jacv
        #sim                       = Radau5DAE(model,**kwargs)
        #
        # IDA method from Assimulo
        #
        sim                       = IDA(model,**kwargs)
        sim.algvar                = list(np.concatenate((np.ones(self.Np), np.zeros(self.Nl) )) )
        sim.atol                  = 1.e-6
        sim.rtol                  = 1.e-6
        sim.report_continuously   = True
        ncp                       = self.Nt
        #sim.usejac                = True
        sim.suppress_alg          = True
        sim.inith                 = self.dt
        sim.maxord                = 5
        #sim.linear_solver         = 'SPGMR'
        sim.make_consistent('IDA_YA_YDP_INIT')
        
        #time_span, DAE_y, DAE_yd  = sim.simulate(self.tfinal,ncp, self.tspan)
        time_span, DAE_y, DAE_yd  = sim.simulate(self.tfinal, 0, self.tspan)
        
        #print(sim.get_options())
        print(sim.print_statistics())
        
        A_dae = DAE_y[:,0:self.Np].transpose()
                
        # Hamiltonian
        self.Nt    = A_dae.shape[1]
        self.tspan = np.array(time_span)
        
        Ham_dae = np.zeros(self.Nt)
        
        for k in range(self.Nt):
            Ham_dae[k] = 1/2 * self.my_mult(A_dae[:,k].T, \
                               self.my_mult(self.Mp_rho_Cv, A_dae[:,k]))
      
        self.Ham_dae = Ham_dae
    
        return Ham_dae, np.array(time_span)   
Exemplo n.º 14
0
def run_example():
    def residual(t,y,yd):
        return squeezer(t, y, yd)
    def residual2(t,y,yd):
        return squeezer2(t, y, yd)
    
    #The initial conditons
    t0 = 0
    y0, yd0 = init_squeezer()

    model = Implicit_Problem(residual, y0, yd0, t0)             #Create an Assimulo problem
    model2 = Implicit_Problem(residual2, y0, yd0, t0)             #Create an Assimulo problem

    sim = IDA(model) #Create the IDA solver
    sim2 = IDA(model2) #Create the IDA solver

    # index 3
    sim.algvar = 7*[True] + 7*[False] + 6*[False]
    sim.suppress_alg = True
    sim.atol = 7*[1e-6] + 7*[1e5] + 6*[1e5]

    # index 2
    sim2.algvar = 7*[True] + 7*[True] + 6*[False]
    sim2.suppress_alg = True
    sim2.atol = 7*[1e-6] + 7*[1e-6] + 6*[1e5]
        
    tfinal = 0.03        #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)
    t2,y2,yd2 = sim2.simulate(tfinal, ncp) #Use the .simulate method to simulate and provide the final time and ncp (optional)
    print("500####################")
    print("####################")
    fig, ax = P.subplots()
    P.title('IDA, difference between index 3 and index 2 formulation')
    P.xlabel('Time')
    P.ylabel('Angle')
    #P.ylabel('Step size')
    #P.axis([0, tfinal + 0.01, -0.7, 0.7])
    #P.plot(t[1:], np.diff(t))
    #P.plot(t, y[:, 0], label='beta')
    #P.plot(t, y[:, 1], label='theta')
    #P.plot(t, y[:, 2], label='gamma')
    #P.plot(t, y[:, 3], label='phi')
    #P.plot(t, y[:, 4], label='delta')
    #P.plot(t, y[:, 5], label='omega')
    #P.plot(t, y[:, 6], label='epsilon')
    P.plot(t, y[:, 0] - y2[:, 0], label='beta')
    P.plot(t, y[:, 1] - y2[:, 1], label='theta')
    P.plot(t, y[:, 2] - y2[:, 2], label='gamma')
    P.plot(t, y[:, 3] - y2[:, 3], label='phi')
    P.plot(t, y[:, 4] - y2[:, 4], label='delta')
    P.plot(t, y[:, 5] - y2[:, 5], label='omega')
    #P.plot(t, y[:, 6], label='epsilon')
    legend = ax.legend(shadow=True, loc = 'upper left')

    '''
    P.plot(t, y[:, 14])
    P.plot(t, y[:, 15])
    P.plot(t, y[:, 16])
    P.plot(t, y[:, 17])
    P.plot(t, y[:, 18])
    P.plot(t, y[:, 19])
    P.axis([0, tfinal, -100, 200])
    '''
    P.grid()
    P.show()
Exemplo n.º 15
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
Exemplo n.º 16
0
# -*- coding: utf-8 -*-
from  __future__  import division
from  scipy       import *
from  matplotlib.pyplot import *
import numpy as np

from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA
import squeezer

y0,yp0=squeezer.init_squeezer() # Initial values
t0 = 0 # Initial time

squeezemodel = Implicit_Problem(squeezer.squeezer, y0, yp0, t0)

algvar = 7*[1.]+13*[0.]
sim = IDA(squeezemodel) # Create solver instance
sim.algvar = algvar
sim.suppress_alg=True
sim.atol = 1e-7
tf = .03 # End time for simulation

t, y, yd = sim.simulate(tf)

sim.plot(mask=7*[1]+13*[0])
grid(1)
axis([0, .03, -1.5, 1.5])
xlabel('Time, t [s]')
ylabel('Angle, [rad]')
Exemplo n.º 17
0
import squeezer_ind3

y20,yp20=squeezer_ind2.init_squeezer2() # Initial values
y30,yp30=squeezer_ind3.init_squeezer3() # Initial values
t0 = 0 # Initial time

squeezemodel2 = Implicit_Problem(squeezer_ind2.squeezer2, y20, yp20, t0)
squeezemodel3 = Implicit_Problem(squeezer_ind3.squeezer3, y30, yp30, t0)

algvar = 7*[1.]+13*[0.]
solver2 = IDA(squeezemodel2)    # Create solver instance
solver3 = IDA(squeezemodel3)    # Create solver instance
solver2.algvar = algvar
solver3.algvar = algvar

solver2.suppress_alg=True
solver3.suppress_alg=True
solver2.atol = 1e-7
solver3.atol = 1e-7
solver3.maxsteps = 322

print(solver3.maxsteps)
tf = .03 # End time for simulation

t2, y2, yd2 = solver2.simulate(tf)
t3, y3, yd3 = solver3.simulate(tf)

figure(1)
plot(t2,y2[:,14:16])
title('Index 2')
figure(2)