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
# -*- 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]')
from handle_event_woodpecker import handle_event 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])
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)
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() ncp_2 = 100
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)
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()
# Check Jacobian g = jac(0.1, t, y, yp) isNotValid = isnan(g).any() if isNotValid == True: raise ValueError('Please check initial conditions. Jacobian has NaN.\n') # Create an Assimulo implicit problem imp_mod = Implicit_Problem(res, y, yp) imp_mod.jac = jac # Sets the jacobian # Sets the options to the problem # Create an Assimulo implicit solver (IDA) imp_sim = IDA(imp_mod) # Create a IDA solver imp_sim.algvar = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0] imp_sim.suppress_alg = True # Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT' imp_sim.make_consistent('IDA_YA_YDP_INIT') # Simulate 4*pi seconds with 1000 communication points endtime = eval(params['endtime']) N = params['timepoints'] t_sol, y_sol, yd_sol = imp_sim.simulate(endtime, N) t = array(t_sol) # Save results outputfile = params['Output'] # Output file name data = {
from assimulo.problem import Implicit_Problem from assimulo.solvers import IDA import squeezer_ind2 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)