def run_example(with_plots=True): global exp_mod, exp_sim #Define the rhs def f(t,y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, y0=4) exp_mod.name = 'Simple CVode Example' #Define an explicit solver exp_sim = CVode(exp_mod) #Create a CVode solver #Sets the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = [1e-4] #Default 1e-6 exp_sim.rtol = 1e-4 #Default 1e-6 #Simulate t1, y1 = exp_sim.simulate(5,100) #Simulate 5 seconds t2, y2 = exp_sim.simulate(7) #Simulate 2 seconds more #Basic test nose.tools.assert_almost_equal(y2[-1], 0.00347746, 5)
def run_example(with_plots=True): global exp_mod, exp_sim #Define the rhs def f(t, y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, y0=4) exp_mod.name = 'Simple CVode Example' #Define an explicit solver exp_sim = CVode(exp_mod) #Create a CVode solver #Sets the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = [1e-4] #Default 1e-6 exp_sim.rtol = 1e-4 #Default 1e-6 #Simulate t1, y1 = exp_sim.simulate(5, 100) #Simulate 5 seconds t2, y2 = exp_sim.simulate(7) #Simulate 2 seconds more #Basic test nose.tools.assert_almost_equal(y2[-1], 0.00347746, 5)
def simulate(self, Tend, nIntervals, gridWidth): problem = Explicit_Problem(self.rhs, self.y0) problem.name = 'RK34' problem.handle_result = self.handle_result problem.handle_event = self.handle_event problem.time_events = self.time_events problem.finalize = self.finalize if hasattr(self, 'state_events'): print 'Warning: state_event function in RK34 is not supported and will be ignored!' simulation = RungeKutta34(problem) # 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 simulation.inith = self.inith # 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 run_example(with_plots=True): r""" Example for the use of the implicit Euler method to solve Van der Pol's equation .. math:: \dot y_1 &= y_2 \\ \dot y_2 &= \mu ((1.-y_1^2) y_2-y_1) with :math:`\mu= 10^6`. on return: - :dfn:`exp_mod` problem instance - :dfn:`exp_sim` solver instance """ #Define the rhs def f(t, y): eps = 1.e-6 my = 1. / eps yd_0 = y[1] yd_1 = my * ((1. - y[0]**2) * y[1] - y[0]) return N.array([yd_0, yd_1]) y0 = [2.0, -0.6] #Initial conditions #Define an Assimulo problem exp_mod = Explicit_Problem(f, y0) exp_mod.name = 'Van der Pol (explicit)' #Define an explicit solver exp_sim = Radau5ODE(exp_mod) #Create a Radau5 solver #Sets the parameters exp_sim.atol = 1e-4 #Default 1e-6 exp_sim.rtol = 1e-4 #Default 1e-6 exp_sim.inith = 1.e-4 #Initial step-size #Simulate t, y = exp_sim.simulate(2.) #Simulate 2 seconds #Plot if with_plots: import pylab as P P.plot(t, y[:, 0]) #, marker='o') P.xlabel('Time') P.ylabel('State') P.title(exp_mod.name) P.show() #Basic test x1 = y[:, 0] assert N.abs(x1[-1] - 1.706168035) < 1e-3 #For test purpose return exp_mod, exp_sim
def run_example(with_plots=True): #Defines the rhs def f(t, y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, 4.0) exp_mod.name = 'Simple Explicit Example' #Explicit Euler exp_sim = ExplicitEuler(exp_mod) #Create a explicit Euler solver exp_sim.options["continuous_output"] = True #Simulate t1, y1 = exp_sim.simulate(3) #Simulate 3 seconds t2, y2 = exp_sim.simulate(5, 100) #Simulate 2 second more #Basic test nose.tools.assert_almost_equal(y2[-1], 0.02628193) #Plot if with_plots: P.plot(t1, y1, color="b") P.plot(t2, y2, color="b") P.show()
def run_example(with_plots=True): #Defines the rhs def f(t,y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, 4.0) exp_mod.name = 'Simple Explicit Example' #Explicit Euler exp_sim = ExplicitEuler(exp_mod) #Create a explicit Euler solver exp_sim.options["continuous_output"] = True #Simulate t1, y1 = exp_sim.simulate(3) #Simulate 3 seconds t2, y2 = exp_sim.simulate(5,100) #Simulate 2 second more #Basic test nose.tools.assert_almost_equal(y2[-1], 0.02628193) #Plot if with_plots: P.plot(t1, y1, color="b") P.plot(t2, y2, color="b") P.show()
def ode_sim(t_final): y0 = get_initial() # initial conditions from Parameter.py t0 = 0.0 param = new_param() ecoli_ode = lambda t, x: rhs(t, x, param) model = Explicit_Problem(ecoli_ode, y0, t0) # Create an Assimulo problem model.name = 'E Coli ODE' sim = CVode(model) # Create the solver CVode sim.rtol = 1e-8 sim.atol = 1e-8 # pdb.set_trace() t, y = sim.simulate(t_final) # Use the .simulate method to simulate and provide the final time # Plot met_labels = ["ACCOA", "ACEx", "ACO", "ACP", "ADP", "AKG", "AMP", "ASP", "ATP", "BPG", "CAMP", "CIT", "COA", "CYS", "DAP", "E4P", "ei", "eiia", "eiiaP", "eiicb", "eiicbP", "eiP", "F6P", "FDP", "FUM", "G6P", "GAP", "GL6P", "GLCx", "GLX", "HCO3", "hpr", "hprP", "icd", "icdP", "ICIT", "KDPG", "MAL", "MG", "MN", "NAD", "NADH", "NADP", "NADPH", "OAA", "P", "PEP", "PGA2", "PGA3", "PGN", "PYR", "PYRx", "Q", "QH2", "R5P", "RU5P", "S7P", "SUC", "SUCCOA", "SUCx", "tal", "talC3", "tkt", "tktC2", "X5P", "Px", "Pp", "GLCp", "ACEp", "ACE", "Hc", "Hp", "FAD", "FADH2", "O2", "FEED"] for i in y: if i.any() < 0: print i plt.plot([t, t], [y[:, i] for i in [4, 9]], label=["ADP", "ATP"]) plt.title('Metabolite Concentrations Over Time') plt.xlabel('Time') plt.ylabel('Concentration') plt.legend() plt.savefig('concentration.png') return model, sim
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
def run_example(with_plots=True): #Defines the rhs def f(t, y): yd_0 = y[1] yd_1 = -9.82 return N.array([yd_0, yd_1]) #Defines the jacobian*vector product def jacv(t, y, fy, v): j = N.array([[0, 1.], [0, 0]]) return N.dot(j, v) y0 = [1.0, 0.0] #Initial conditions #Defines an Assimulo explicit problem exp_mod = Explicit_Problem(f, y0) exp_mod.jacv = jacv #Sets the jacobian exp_mod.name = 'Example using the Jacobian Vector product' exp_sim = CVode(exp_mod) #Create a CVode solver #Set the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = 1e-5 #Default 1e-6 exp_sim.rtol = 1e-5 #Default 1e-6 exp_sim.linear_solver = 'SPGMR' #Change linear solver #exp_sim.options["usejac"] = False #Simulate t, y = exp_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.show()
def run_example(with_plots=True): global t, y #Defines the rhs def f(t, y): yd_0 = y[1] yd_1 = -9.82 #print y, yd_0, yd_1 return N.array([yd_0, yd_1]) #Defines the jacobian def jac(t, y): j = N.array([[0, 1.], [0, 0]]) return j #Defines an Assimulo explicit problem y0 = [1.0, 0.0] #Initial conditions exp_mod = Explicit_Problem(f, y0) exp_mod.jac = jac #Sets the jacobian exp_mod.name = 'Example using Jacobian' exp_sim = CVode(exp_mod) #Create a CVode solver #Set the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = 1e-5 #Default 1e-6 exp_sim.rtol = 1e-5 #Default 1e-6 #Simulate t, y = exp_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, linestyle="dashed", marker="o") #Plot the solution P.show()
def run_example(with_plots=True): #Defines the rhs def f(t,y): yd_0 = y[1] yd_1 = -9.82 return N.array([yd_0,yd_1]) #Defines the jacobian*vector product def jacv(t,y,fy,v): j = N.array([[0,1.],[0,0]]) return N.dot(j,v) y0 = [1.0,0.0] #Initial conditions #Defines an Assimulo explicit problem exp_mod = Explicit_Problem(f,y0) exp_mod.jacv = jacv #Sets the jacobian exp_mod.name = 'Example using the Jacobian Vector product' exp_sim = CVode(exp_mod) #Create a CVode solver #Set the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = 1e-5 #Default 1e-6 exp_sim.rtol = 1e-5 #Default 1e-6 exp_sim.linear_solver = 'SPGMR' #Change linear solver #exp_sim.options["usejac"] = False #Simulate t, y = exp_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.show()
def run_example(with_plots=True): global t,y #Defines the rhs def f(t,y): yd_0 = y[1] yd_1 = -9.82 #print y, yd_0, yd_1 return N.array([yd_0,yd_1]) #Defines the jacobian def jac(t,y): j = N.array([[0,1.],[0,0]]) return j #Defines an Assimulo explicit problem y0 = [1.0,0.0] #Initial conditions exp_mod = Explicit_Problem(f,y0) exp_mod.jac = jac #Sets the jacobian exp_mod.name = 'Example using Jacobian' exp_sim = CVode(exp_mod) #Create a CVode solver #Set the parameters exp_sim.iter = 'Newton' #Default 'FixedPoint' exp_sim.discr = 'BDF' #Default 'Adams' exp_sim.atol = 1e-5 #Default 1e-6 exp_sim.rtol = 1e-5 #Default 1e-6 #Simulate t, y = exp_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,linestyle="dashed",marker="o") #Plot the solution P.show()
def run_example(with_plots=True): #Defines the rhs def f(t, y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, 4.0) exp_mod.name = 'Simple Explicit Example' exp_sim = RungeKutta4(exp_mod) #Create a RungeKutta4 solver #Simulate t, y = exp_sim.simulate(5, 100) #Simulate 5 seconds #Basic test nose.tools.assert_almost_equal(y[-1], 0.02695179) #Plot if with_plots: P.plot(t, y) P.show()
def run_example(with_plots=True): #Defines the rhs def f(t,y): ydot = -y[0] return N.array([ydot]) #Define an Assimulo problem exp_mod = Explicit_Problem(f, 4.0) exp_mod.name = 'Simple Explicit Example' exp_sim = RungeKutta4(exp_mod) #Create a RungeKutta4 solver #Simulate t, y = exp_sim.simulate(5, 100) #Simulate 5 seconds #Basic test nose.tools.assert_almost_equal(y[-1],0.02695179) #Plot if with_plots: P.plot(t,y) P.show()
def run_example(): def rhs(t,y): A =N.array([[0,1],[-2,-1]]) yd=N.dot(A,y) return yd y0=N.array([1.0,1.0]) t0=0.0 model = Explicit_Problem(rhs,y0,t0) #Create an Assimulo problem model.name = 'Linear Test ODE' sim = CVode(model) #Create the solver CVode tfinal = 10.0 #Specify the final time t,y = sim.simulate(tfinal) #Use the .simulate method to simulate and provide the final time #Plot P.plot(t,y) P.show()
def run_example(with_plots=True): #Define the rhs def f(t,y): eps = 1.e-6 my = 1./eps yd_0 = y[1] yd_1 = my*((1.-y[0]**2)*y[1]-y[0]) return N.array([yd_0,yd_1]) y0 = [2.0,-0.6] #Initial conditions #Define an Assimulo problem exp_mod = Explicit_Problem(f,y0) exp_mod.name = 'Van der Pol (explicit)' #Define an explicit solver exp_sim = Radau5ODE(exp_mod) #Create a Radau5 solver #Sets the parameters exp_sim.atol = 1e-4 #Default 1e-6 exp_sim.rtol = 1e-4 #Default 1e-6 exp_sim.inith = 1.e-4 #Initial step-size #Simulate t, y = exp_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
solver.y[1] = -0.9*solver.y[1] #Change the velocity and lose energy solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [N.pi/2.0, 0.0] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Pendulum with events' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance #Simulation ncp = 200 #Number of communication points tfinal = 10.0 #Final time
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()
#Define rhs def rhs(t, y): lamb = lambda y1, y2: k * (N.sqrt(y1**2 + y2**2) - 1) / N.sqrt(y1**2 + y2** 2) ydot = N.zeros(y.shape) ydot[0] = y[2] ydot[1] = y[3] ydot[2] = -y[0] * lamb(y[0], y[1]) ydot[3] = -y[1] * lamb(y[0], y[1]) - 1 return ydot #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
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ #X = X.copy() g = 9.81 x = X[0] vx = X[2] vy = X[3] return np.array([vx, vy, -(np.pi**2) * x, -g, 1.0]) def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ x = X[0] y = X[1] return [x - y] #return np.array([x - y]) def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[ 0] #We are only interested in state events info if state_info[ 0] != 0: #Check if the first event function have been triggered if solver.sw[0]: #If the switch is True the pendulum bounces X = solver.y X[1] = X[0] + 1e-3 X[3] = 0.9 * (X[2] - X[3]) #solver.sw[0] = not solver.sw[0] #Change event function #Initial values phi = 1.0241592 Y0 = -13.0666666 A = 2.0003417 w = np.pi y0 = [ A * np.sin(phi), 1 + A * np.sin(phi), A * w * np.cos(phi), Y0 - A * w * np.cos(phi) - 1, 0 ] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball on Sonusoidal Platform' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) sim.options['verbosity'] = 40 #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance return sim
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ X = X.copy() X[0] = X[1] X[1] = -1 + 0.04 * (X[1]**2) * np.sin(X[1]) X[2] = 1 return X def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ return [X[0] - np.sin(X[2])] def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[0] #We are only interested in state events info if state_info[0] != 0: #Check if the first event function have been triggered if solver.sw[0]: #If the switch is True the pendulum bounces X = solver.y if X[1] - np.cos(X[2]) < 0: X[1] = -0.9*X[1] + 1.9*np.cos(X[2]) #solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [0, 0, 0] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball on Sonusoidal Platform' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) #sim.options['verbosity'] = 20 #LOUD sim.options['verbosity'] = 40 #WHISPER #sim.options['minh'] = 1e-4 #sim.options['rtol'] = 1e-3 #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance return sim
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ #X = X.copy() g = 9.81 x = X[0] vx = X[2] vy = X[3] return np.array([vx, vy, -(np.pi**2)*x, -g, 1.0]) def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ x = X[0] y = X[1] return [x - y] #return np.array([x - y]) def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[0] #We are only interested in state events info if state_info[0] != 0: #Check if the first event function have been triggered if solver.sw[0]: #If the switch is True the pendulum bounces X = solver.y X[1] = X[0] + 1e-3 X[3] = 0.9*(X[2] - X[3]) #solver.sw[0] = not solver.sw[0] #Change event function #Initial values phi = 1.0241592; Y0 = -13.0666666; A = 2.0003417; w = np.pi y0 = [A*np.sin(phi), 1+A*np.sin(phi), A*w*np.cos(phi), Y0 - A*w*np.cos(phi)-1, 0] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball on Sonusoidal Platform' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) sim.options['verbosity'] = 40 #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance return sim
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ g = 1 Y = X.copy() Y[0] = X[2] #x_dot Y[1] = X[3] #y_dot Y[2] = 0 #vx_dot Y[3] = -g #vy_dot return Y def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ return [X[1]] # y == 0 def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[0] #We are only interested in state events info if state_info[0] != 0: #Check if the first event function have been triggered if solver.sw[0]: X = solver.y if X[3] < 0: # if the ball is falling (vy < 0) # bounce! X[1] = 1e-5 X[3] = -0.75*X[3] #solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [0., 0., 0., 0.] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball in X-Y' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) #sim = RungeKutta34(mod) #sim.options['verbosity'] = 20 #LOUD sim.verbosity = 40 #WHISPER #sim.display_progress = True #sim.options['minh'] = 1e-4 #sim.options['rtol'] = 1e-3 # #Specifies options # sim.discr = 'Adams' #Sets the discretization method # sim.iter = 'FixedPoint' #Sets the iteration method # sim.rtol = 1.e-8 #Sets the relative tolerance # sim.atol = 1.e-6 #Sets the absolute tolerance return sim
def run_example(): def pendulum(t,y,sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ l=1.0 g=9.81 yd_0 = y[1] yd_1 = -g/l*N.sin(y[0]) return N.array([yd_0, yd_1]) def state_events(t,y,sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ if sw[0]: e_0 = y[0]+N.pi/4. else: e_0 = y[0] return N.array([e_0]) def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[0] #We are only interested in state events info if state_info[0] != 0: #Check if the first event function have been triggered if solver.sw[0]: #If the switch is True the pendulum bounces solver.y[1] = -0.9*solver.y[1] #Change the velocity and lose energy solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [N.pi/2.0, 0.0] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Pendulum with events' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance #Simulation ncp = 200 #Number of communication points tfinal = 10.0 #Final time t,y = sim.simulate(tfinal, ncp) #Simulate #Print event information sim.print_event_data() #Plot P.plot(t,y) P.show()
yd = np.dot(A, y) + b return yd #def rhs(t,y): # A =np.array([[0, 1],[-2, -1]]) # yd=np.dot(A, y) # # return yd def L(y, k): norm = ln.norm(y[0:2]) return k * (norm - 1) / norm y0 = np.array([1.0, 1.0, 1.0, 1.0]) t0 = 0.0 model = Explicit_Problem(rhs, y0, t0) # Create an Assimulo problem model.name = 'Linear Test ODE' # Specifies the name of problem sim = CVode(model) tfinal = 100.0 #Specify the final time t, y = sim.simulate( tfinal) #Use the .simulate method to simulate and provide the final time sim.plot()
import numpy import math from assimulo.problem import Explicit_Problem from assimulo.solvers import CVode 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()
def create_model(): def nav(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ A, b = get_dyn(sw2mode(sw)) return np.dot(A, X) + b def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ #TODO: is this the best way? mode = sw2mode(sw) g = get_guard_vals(X, mode) G = [g[0], g[1], g[2], g[3]] # y == 0 if debug: print(mode) print('G =', G) return G def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[ 0] #We are only interested in state events info if debug: print('############### EVENT DETECTED') g = state_info if g[0] <= 0 or g[1] <= 0 or g[2] <= 0 or g[3] <= 0: mode = sw2mode(solver.sw) mode_ = new_mode(g, mode) if debug: print('############### new_mode =', mode_) solver.sw = mode2sw(mode_) #Initial values y0 = [0., 0., 0., 0.] #Initial states t0 = 5.0 #Initial time switches0 = [False] * NUM_MODES #Initial switches # Without the below statemment, it hits an error switches0[79] = True #Create an Assimulo Problem mod = Explicit_Problem(nav, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'nav30' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) #sim = RungeKutta34(mod) #sim.options['verbosity'] = 20 #LOUD #sim.options['verbosity'] = 40 #WHISPER sim.verbosity = 40 #WHISPER #sim.display_progress = True #sim.options['minh'] = 1e-4 #sim.options['rtol'] = 1e-3 # #Specifies options # sim.discr = 'Adams' #Sets the discretization method # sim.iter = 'FixedPoint' #Sets the iteration method # sim.rtol = 1.e-8 #Sets the relative tolerance # sim.atol = 1.e-6 #Sets the absolute tolerance return sim
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ g = 1 Y = X.copy() Y[0] = X[2] #x_dot Y[1] = X[3] #y_dot Y[2] = 0 #vx_dot Y[3] = -g #vy_dot return Y def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ return [X[1]] # y == 0 def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[ 0] #We are only interested in state events info if state_info[ 0] != 0: #Check if the first event function have been triggered if solver.sw[0]: X = solver.y if X[3] < 0: # if the ball is falling (vy < 0) # bounce! #X[1] = 1e-5 # used with CVode X[1] = 1e-3 # gives better results with Dopri X[3] = -0.75 * X[3] #solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [0., 0., 0., 0.] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball in X-Y' #Sets the name of the problem #Create an Assimulo solver (CVode) # leaks memory!! #sim = CVode(mod) # hands and possibly leaks memory #sim = LSODAR(mod) #sim = RungeKutta34(mod) sim = Dopri5(mod) #sim.options['verbosity'] = 20 #LOUD sim.verbosity = 40 #WHISPER #sim.display_progress = False #sim.options['minh'] = 1e-4 #sim.options['rtol'] = 1e-3 # What is time_limit? sim.time_limit = 1 # #Specifies options # sim.discr = 'Adams' #Sets the discretization method # sim.iter = 'FixedPoint' #Sets the iteration method # sim.rtol = 1.e-8 #Sets the relative tolerance # sim.atol = 1.e-6 #Sets the absolute tolerance return sim
import numpy as N import pylab as P from assimulo.problem import Explicit_Problem #Imports the problem formulation from Assimulo from assimulo.solvers.sundials import CVode #Imports the solver CVode from Assimulo def rhs(t,y): A =N.array([[0,1],[-2,-1]]) yd=N.dot(A,y) return yd y0=N.array([1.0,1.0]) t0=0.0 model = Explicit_Problem(rhs, y0, t0) #Create an Assimulo problem model.name = 'Linear Test ODE' #Specifies the name of problem (optional) sim = CVode(model) tfinal = 10.0 #Specify the final time t, y = sim.simulate(tfinal) #Use the .simulate method to simulate and provide the final time #Plots the result P.plot(t,y) P.show()
def create_model(): def pendulum(t, X, sw): """ The ODE to be simulated. The parameter sw should be fixed during the simulation and only be changed during the event handling. """ X = X.copy() X[0] = X[1] X[1] = -1 + 0.04 * (X[1]**2) * np.sin(X[1]) X[2] = 1 return X def state_events(t, X, sw): """ This is our function that keep track of our events, when the sign of any of the events has changed, we have an event. """ return [X[0] - np.sin(X[2])] def handle_event(solver, event_info): """ Event handling. This functions is called when Assimulo finds an event as specified by the event functions. """ state_info = event_info[ 0] #We are only interested in state events info if state_info[ 0] != 0: #Check if the first event function have been triggered if solver.sw[0]: #If the switch is True the pendulum bounces X = solver.y if X[1] - np.cos(X[2]) < 0: X[1] = -0.9 * X[1] + 1.9 * np.cos(X[2]) #solver.sw[0] = not solver.sw[0] #Change event function #Initial values y0 = [0, 0, 0] #Initial states t0 = 0.0 #Initial time switches0 = [True] #Initial switches #Create an Assimulo Problem mod = Explicit_Problem(pendulum, y0, t0, sw0=switches0) mod.state_events = state_events #Sets the state events to the problem mod.handle_event = handle_event #Sets the event handling to the problem mod.name = 'Bouncing Ball on Sonusoidal Platform' #Sets the name of the problem #Create an Assimulo solver (CVode) sim = CVode(mod) #sim = LSODAR(mod) #sim.options['verbosity'] = 20 #LOUD sim.options['verbosity'] = 40 #WHISPER #sim.options['minh'] = 1e-4 #sim.options['rtol'] = 1e-3 #Specifies options sim.discr = 'Adams' #Sets the discretization method sim.iter = 'FixedPoint' #Sets the iteration method sim.rtol = 1.e-8 #Sets the relative tolerance sim.atol = 1.e-6 #Sets the absolute tolerance return sim