def simulate(self, Tend, nIntervals, gridWidth): problem = Explicit_Problem(self.rhs, self.y0) problem.name = 'CVode' # solver.rhs = self.right_hand_side problem.handle_result = self.handle_result problem.state_events = self.state_events problem.handle_event = self.handle_event problem.time_events = self.time_events problem.finalize = self.finalize simulation = CVode(problem) # Change multistep method: 'adams' or 'VDF' if self.discr == 'Adams': simulation.discr = 'Adams' simulation.maxord = 12 else: simulation.discr = 'BDF' simulation.maxord = 5 # Change iteration algorithm: functional(FixedPoint) or newton if self.iter == 'FixedPoint': simulation.iter = 'FixedPoint' else: simulation.iter = 'Newton' # Sets additional parameters simulation.atol = self.atol simulation.rtol = self.rtol simulation.verbosity = self.verbosity if hasattr(simulation, 'continuous_output'): simulation.continuous_output = False # default 0, if one step approach should be used elif hasattr(simulation, 'report_continuously'): simulation.report_continuously = False # default 0, if one step approach should be used # '''Initialize problem ''' # self.t_cur = self.t0 # self.y_cur = self.y0 # Calculate nOutputIntervals: if gridWidth <> None: nOutputIntervals = int((Tend - self.t0) / gridWidth) else: nOutputIntervals = nIntervals # Check for feasible input parameters if nOutputIntervals == 0: print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1' nOutputIntervals = 1 # Perform simulation simulation.simulate( Tend, nOutputIntervals ) # to get the values: t_new, y_new = simulation.simulate
def simulate(self, Tend, nIntervals, gridWidth): problem = Explicit_Problem(self.rhs, self.y0) problem.name = 'CVode' # solver.rhs = self.right_hand_side problem.handle_result = self.handle_result problem.state_events = self.state_events problem.handle_event = self.handle_event problem.time_events = self.time_events problem.finalize = self.finalize simulation = CVode(problem) # Change multistep method: 'adams' or 'VDF' if self.discr == 'Adams': simulation.discr = 'Adams' simulation.maxord = 12 else: simulation.discr = 'BDF' simulation.maxord = 5 # Change iteration algorithm: functional(FixedPoint) or newton if self.iter == 'FixedPoint': simulation.iter = 'FixedPoint' else: simulation.iter = 'Newton' # Sets additional parameters simulation.atol = self.atol simulation.rtol = self.rtol simulation.verbosity = self.verbosity if hasattr(simulation, 'continuous_output'): simulation.continuous_output = False # default 0, if one step approach should be used elif hasattr(simulation, 'report_continuously'): simulation.report_continuously = False # default 0, if one step approach should be used # '''Initialize problem ''' # self.t_cur = self.t0 # self.y_cur = self.y0 # Calculate nOutputIntervals: if gridWidth <> None: nOutputIntervals = int((Tend - self.t0) / gridWidth) else: nOutputIntervals = nIntervals # Check for feasible input parameters if nOutputIntervals == 0: print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1' nOutputIntervals = 1 # Perform simulation simulation.simulate(Tend, nOutputIntervals) # to get the values: t_new, y_new = simulation.simulate
import matplotlib.pyplot as plt def rhs(t,y): k = 1000 L = k*(math.sqrt(y[0]**2+y[1]**2)-1)/math.sqrt(y[0]**2+y[1]**2) result = numpy.array([y[2],y[3],-y[0]*L,-y[1]*L-1]) return result t0 = 0 y0 = numpy.array([0.8,-0.8,0,0]) model = Explicit_Problem(rhs,y0,t0) model.name = 'task1' sim = CVode(model) sim.atol=numpy.array([1,1,1,1])*1e-5 sim.rtol=1e-6 sim.maxord=3 #sim.discr='BDF' #sim.iter='Newton' tfinal = 70 (t,y) = sim.simulate(tfinal) #sim.plot() plt.plot(y[:,0],y[:,1]) plt.axis('equal') plt.show()
def simulate(self, Tend, nIntervals, gridWidth): # define assimulo problem:(has to be done here because of the starting value in Explicit_Problem solver = Explicit_Problem(self.rhs, self.y0) ''' *******DELETE LATER ''''''''' # problem.handle_event = handle_event # problem.state_events = state_events # problem.init_mode = init_mode solver.handle_result = self.handle_result solver.name = 'Simple Explicit Example' simulation = CVode(solver) # Create a RungeKutta34 solver # simulation.inith = 0.1 #Sets the initial step, default = 0.01 # Change multistep method: 'adams' or 'VDF' if self.discr == 'Adams': simulation.discr = 'Adams' simulation.maxord = 12 else: simulation.discr = 'BDF' simulation.maxord = 5 # Change iteration algorithm: functional(FixedPoint) or newton if self.iter == 'FixedPoint': simulation.iter = 'FixedPoint' else: simulation.iter = 'Newton' # Sets additional parameters simulation.atol = self.atol simulation.rtol = self.rtol simulation.verbosity = 0 if hasattr(simulation, 'continuous_output'): simulation.continuous_output = False # default 0, if one step approach should be used elif hasattr(simulation, 'report_continuously'): simulation.report_continuously = False # default 0, if one step approach should be used # Create Solver and set settings # noRootFunctions = np.size(self.state_events(self.t0, np.array(self.y0))) # solver = sundials.CVodeSolver(RHS = self.f, ROOT = self.rootf, SW = [False]*noRootFunctions, # abstol = self.atol, reltol = self.rtol) # solver.settings.JAC = None #Add user-dependent jacobian here '''Initialize problem ''' # solver.init(self.t0, self.y0) self.handle_result(self.t0, self.y0) nextTimeEvent = self.time_events(self.t0, self.y0) self.t_cur = self.t0 self.y_cur = self.y0 state_event = False # # if gridWidth <> None: nOutputIntervals = int((Tend - self.t0) / gridWidth) else: nOutputIntervals = nIntervals # Define step length depending on if gridWidth or nIntervals has been chosen if nOutputIntervals > 0: # Last point on grid (does not have to be Tend:) if(gridWidth <> None): dOutput = gridWidth else: dOutput = (Tend - self.t0) / nIntervals else: dOutput = Tend outputStepCounter = long(1) nextOutputPoint = min(self.t0 + dOutput, Tend) while self.t_cur < Tend: # Time-Event detection and step time adjustment if nextTimeEvent is None or nextOutputPoint < nextTimeEvent: time_event = False self.t_cur = nextOutputPoint else: time_event = True self.t_cur = nextTimeEvent try: # #Integrator step # self.y_cur = solver.step(self.t_cur) # self.y_cur = np.array(self.y_cur) # state_event = False # Simulate # take a step to next output point: t_new, y_new = simulation.simulate(self.t_cur) # 5, 10) #5, 10 self.t_cur self.t_cur 2. argument nsteps Simulate 5 seconds # t_new, y_new are both vectors of the time and states at t_cur and all intermediate # points before it! So take last values: self.t_cur = t_new[-1] self.y_cur = y_new[-1] state_event = False except: import sys print "Unexpected error:", sys.exc_info()[0] # except CVodeRootException, info: # self.t_cur = info.t # self.y_cur = info.y # self.y_cur = np.array(self.y_cur) # time_event = False # state_event = True # # # Depending on events have been detected do different tasks if time_event or state_event: event_info = [state_event, time_event] if not self.handle_event(self, event_info): break solver.init(self.t_cur, self.y_cur) nextTimeEvent = self.time_events(self.t_cur, self.y_cur) # If no timeEvent happens: if nextTimeEvent <= self.t_cur: nextTimeEvent = None if self.t_cur == nextOutputPoint: # Write output if not happened before: if not time_event and not state_event: self.handle_result(nextOutputPoint, self.y_cur) outputStepCounter += 1 nextOutputPoint = min(self.t0 + outputStepCounter * dOutput, Tend) self.finalize()
def run_example(with_plots=True): """ Simulations for the Gyro (Heavy Top) example in Celledoni/Safstrom: Journal of Physics A, Vol 39, 5463-5478, 2006 on return: - :dfn:`exp_mod` problem instance - :dfn:`exp_sim` solver instance """ def curl(v): return array([[0, v[2], -v[1]], [-v[2], 0, v[0]], [v[1], -v[0], 0]]) #Defines the rhs def f(t, u): """ Simulations for the Gyro (Heavy Top) example in Celledoni/Safstrom: Journal of Physics A, Vol 39, 5463-5478, 2006 """ I1 = 1000. I2 = 5000. I3 = 6000. u0 = [0, 0, 1.] pi = u[0:3] Q = (u[3:12]).reshape((3, 3)) Qu0 = dot(Q, u0) f = array([Qu0[1], -Qu0[0], 0.]) f = 0 omega = array([pi[0] / I1, pi[1] / I2, pi[2] / I3]) pid = dot(curl(omega), pi) + f Qd = dot(curl(omega), Q) return hstack([pid, Qd.reshape((9, ))]) def energi(state): energi = [] for st in state: Q = (st[3:12]).reshape((3, 3)) pi = st[0:3] u0 = [0, 0, 1.] Qu0 = dot(Q, u0) V = Qu0[2] # potential energy T = 0.5 * (pi[0]**2 / 1000. + pi[1]**2 / 5000. + pi[2]**2 / 6000.) energi.append([T]) return energi #Initial conditions y0 = hstack([[1000. * 10, 5000. * 10, 6000 * 10], eye(3).reshape((9, ))]) #Create an Assimulo explicit problem exp_mod = Explicit_Problem(f, y0, name="Gyroscope Example") #Create an Assimulo explicit solver (CVode) exp_sim = CVode(exp_mod) #Sets the parameters exp_sim.discr = 'BDF' exp_sim.iter = 'Newton' exp_sim.maxord = 2 #Sets the maxorder exp_sim.atol = 1.e-10 exp_sim.rtol = 1.e-10 #Simulate t, y = exp_sim.simulate(0.1) #Plot if with_plots: import pylab as P P.plot(t, y / 10000.) P.xlabel('Time') P.ylabel('States, scaled by $10^4$') P.title(exp_mod.name) P.show() #Basic tests nose.tools.assert_almost_equal(y[-1][0], 692.800241862) nose.tools.assert_almost_equal(y[-1][8], 7.08468221e-1) return exp_mod, exp_sim
#Create Assimulo problem model mod_pen = Explicit_Problem(rhs, y0, t0) mod_pen.name = 'Elastic Pendulum with CVode' """ Run simulation """ #Create solver object sim_pen = CVode(mod_pen) #Simulation parameters #atol = 1.e-6*ones(shape(y0)) atol = rtol * N.array([1, 1, 1, 1]) #default 1e-06 sim_pen.atol = atol sim_pen.rtol = rtol sim_pen.maxh = hmax sim_pen.maxord = maxord sim_pen.inith = h0 #Simulate t, y = sim_pen.simulate(tf) """ Plot results """ #Plot #P.plot(t,y) #P.legend(['$x$','$y$','$\dot{x}$','$\dot{y}$']) #P.title('Elastic pendulum with k = ' + str(k) + ', stretch = ' + str(stretch)) #P.xlabel('time') #P.ylabel('state') #show() P.plot(y[:, 0], y[:, 1])
# Define the rhs def rhs(t, y): k = 10 A = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [-L(y, k), 0, 0, 0], [0, -L(y, k), 0, 0]]) b = np.array([0, 0, 0, -1]) yd = np.dot(A, y) + b return yd def L(y, k): norm = ln.norm(y[0:2]) return k * (norm - 1) / norm pend_mod = Explicit_Problem(rhs, y0 = np.array([1.0, 1.0, 1.0, 1.0])) pend_mod.name = 'Nonlinear Pendulum' # Define an explicit solver exp_sim = BDF_3(pend_mod) # Create a BDF solver t, y = exp_sim.simulate(4) exp_sim.plot() mpl.show() toltmp=0.1 cvod= CVode(pend_mod) cvod.atol=toltmp cvod.rtol=toltmp cvod.maxord=19 cvod.simulate(5) cvod.plot()