def test_dop_oscil(self): #test calling sequence. End is reached before root is found prob = SimpleOscillator() tspan = [0, prob.stop_t] solver = ode('dopri5', prob.f) soln = solver.solve(tspan, prob.y0) assert soln.flag == StatusEnumDOP.SUCCESS, "ERROR: Error occurred" assert prob.verify(prob.stop_t, soln.values.y[1]) solver = ode('dop853', prob.f) soln = solver.solve(tspan, prob.y0) assert soln.flag == StatusEnumDOP.SUCCESS, "ERROR: Error occurred" assert prob.verify(prob.stop_t, soln.values.y[1])
def test_dop_oscil(self): #test calling sequence. End is reached before root is found prob = SimpleOscillator() tspan = [0, prob.stop_t] solver = ode('dopri5', prob.f) soln = solver.solve(tspan, prob.y0) assert soln.flag==StatusEnumDOP.SUCCESS, "ERROR: Error occurred" assert prob.verify(prob.stop_t, soln.values.y[1]) solver = ode('dop853', prob.f) soln = solver.solve(tspan, prob.y0) assert soln.flag==StatusEnumDOP.SUCCESS, "ERROR: Error occurred" assert prob.verify(prob.stop_t, soln.values.y[1])
def test_cvode_tstopfn_stop(self): #test calling sequence. End is reached at a tstop global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, ontstop=ontstop_vb, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag == StatusEnum.TSTOP_RETURN, "ERROR: Error occurred" assert allclose( [soln.values.t[-1], soln.values.y[-1, 0], soln.values.y[-1, 1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol) assert len(soln.tstop.t) == 1, "ERROR: Did not find all tstop" assert len(soln.values.t) == 11, "ERROR: Did not find all output" assert allclose( [soln.tstop.t[-1], soln.tstop.y[-1, 0], soln.tstop.y[-1, 1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol)
def test_cvode_tstopfn_test(self): #test calling sequence. tstop function continues up to a time global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, ontstop=ontstop_vc, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag == StatusEnum.TSTOP_RETURN, "ERROR: Error occurred" assert allclose( [soln.values.t[-1], soln.values.y[-1, 0], soln.values.y[-1, 1]], [30.0, -1452.5024, -294.30], atol=atol, rtol=rtol) assert len(soln.tstop.t) == 3, "ERROR: Did not find all tstop" assert len(soln.values.t) == 31, "ERROR: Did not find all output" assert allclose( [soln.tstop.t[-1], soln.tstop.y[-1, 0], soln.tstop.y[-1, 1]], [30.0, -1452.5024, -294.30], atol=atol, rtol=rtol)
def solve_ode(self, time_out, solver_type='cvode', **kwargs): """ The solver types are from ::scikits.odes::, and can be found at <https://scikits-odes.readthedocs.io/en/latest/solvers.html>`_. :param time_out: The times at which the solution is evaluated :type time_out: list(float) or similar :param solver_type: must be among ['cvode','ida','dopri5','dop853'] :param kwargs: :return: """ extra_options = {'old_api': False} kwargs.update(extra_options) # Choose a solver if not hasattr(self, 'solver') \ or self._recompiled: self.solver = ode(solver_type, self.ode_fun, **kwargs) self._recompiled = False # Order the initial conditions according to variables ordered_initial_conditions = [ self.initial_conditions[variable] for variable in self.variables ] #Update fixed parameters self.ode_fun.get_params() solution = self.solver.solve(time_out, ordered_initial_conditions) return ODESolution(self, solution)
def test_cvode_rootfn_noroot(self): #test calling sequence. End is reached before root is found tspan = np.arange(0, t_end1 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=1, rootfn=root_fn, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.SUCCESS, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol)
def test_cvode_rootfn(self): #test root finding and stopping: End is reached at a root tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=1, rootfn=root_fn, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.ROOT_RETURN, "ERROR: Root not found!" assert allclose([soln.roots.t[0], soln.roots.y[0,0], soln.roots.y[0,1]], [14.206856, 10.0000, -139.3693], atol=atol, rtol=rtol)
def calc_numerical_solution(*, initial_conditions, solver_config, time, tstop): """ Run the sundials ODE solver on the set of differential equations """ # initialise the differential equation model system, internal_data = ode_system( a1=initial_conditions.ode_init_con[0], a2=initial_conditions.ode_init_con[2], a3=initial_conditions.ode_init_con[4], ρ_pressure_over_ρ_tides=initial_conditions.ρ_pressure_over_ρ_tides, ρ_real_over_ρ_pressure=initial_conditions.ρ_real_over_ρ_pressure, ) # If taylor jump is selected, then add the additional params to the ode solver to perform the action tay_args = {} # If solver_config.enable_taylor_jump: if solver_config.enable_taylor_jump: tay_args["rootfn"] = xy_close_stop_generator( solver_config.taylor_jump_threshold) tay_args["nr_rootfns"] = 1 # If time stop is selected, then set the solver to stop at this timepoint ontstop_func = ontstop_stop( ) if solver_config.enable_tstop else ontstop_cont() # Create the sundials system solver = ode("cvode", system, old_api=False, validate_flags=True, rtol=solver_config.relative_tolerance, atol=solver_config.absolute_tolerance, max_steps=solver_config.max_steps, tstop=tstop, ontstop=ontstop_func, **tay_args) # and solve it. try: soln = solver.solve(time, initial_conditions.ode_init_con) except CVODESolveFailed as e: soln = e.soln print("Solver: FAILED at time {} with conditions {}".format( soln.values.t[-1], soln.values.y[-1, :])) except CVODESolveFoundRoot as e: soln = e.soln print("Solver: FOUND ROOT at time {} with conditions {}".format( soln.values.t[-1], soln.values.y[-1, :])) except CVODESolveReachedTSTOP as e: soln = e.soln print("Solver: TIME STOP at time {}".format(soln.values.t[-1])) # except: # Bare except for problems with division by zero # raise SystemExit("Something went horribly wrong when trying to solve the ODE. Exiting") return soln, internal_data
def taylor_solution( *, angles, init_con, γ, a_0, norm_kepler_sq, taylor_stop_angle, relative_tolerance=float_type(1e-6), absolute_tolerance=float_type(1e-10), max_steps=500, η_derivs=True, store_internal=True, θ_scale=float_type(1), use_E_r=False ): """ Compute solution using taylor series """ taylor_stop_angle = rad_to_scaled(taylor_stop_angle, θ_scale) system, internal_data = ode_system( γ=γ, a_0=a_0, norm_kepler_sq=norm_kepler_sq, init_con=init_con, with_taylor=True, η_derivs=η_derivs, store_internal=store_internal, θ_scale=θ_scale, use_E_r=use_E_r, ) solver = ode( INTEGRATOR, system, linsolver=LINSOLVER, rtol=relative_tolerance, atol=absolute_tolerance, max_steps=max_steps, validate_flags=True, old_api=False, err_handler=error_handler, tstop=taylor_stop_angle, bdf_stability_detection=True, ) try: soln = solver.solve(angles, init_con) except CVODESolveFailed as e: soln = e.soln raise SolverError( "Taylor solver stopped in at {} with flag {!s}.\n{}".format( degrees(scaled_to_rad(soln.errors.t, θ_scale)), soln.flag, soln.message ) ) from e except CVODESolveReachedTSTOP as e: soln = e.soln else: raise SolverError("Taylor solver did not find taylor_stop_angle") new_angles = angles[angles > taylor_stop_angle] insert(new_angles, 0, taylor_stop_angle) return TaylorSolution( angles=scaled_to_rad(soln.values.t, θ_scale), params=soln.values.y, new_angles=new_angles, internal_data=internal_data, new_initial_conditions=soln.tstop.y[0], angle_stopped=soln.tstop.t[0], )
def test_cvode_tstopfn_notstop(self): #test calling sequence. End is reached before tstop is found global n n = 0 tspan = np.arange(0, t_end1 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1+1, ontstop=ontstop_va, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.SUCCESS, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol)
def __init__(self): """We obtain the vode solution first""" r = Iode(self.f_vode, self.jac_vode).set_integrator( 'vode', rtol=[1e-4, 1e-4, 1e-4], atol=[1e-8, 1e-14, 1e-6], method='bdf', ) r.set_initial_value([1., 0., 0.]) nr = 5 self.sol = zeros((nr, 3)) self.stop_t = [0., 0.4, 4., 40., 400.] self.sol[0] = r.y i = 1 for time in self.stop_t[1:]: r.integrate(time) self.sol[i] = r.y i += 1 #we now do the same with the sundials CVODE solution r = ode( 'cvode', self.f_cvode, jacfn=self.jac_cvode, rtol=1e-4, atol=[1e-8, 1e-14, 1e-6], lmm_type='bdf', old_api=False, ) soln = r.solve(self.stop_t, [1., 0., 0.]) self.sol2 = soln.values.y #for the solvers, only stop time, not start: self.stop_t = self.stop_t[1:] #we need to activate some extra parameters in the solver #order par is rtol,atol,lband,uband,tstop,order,nsteps, # max_step,first_step,enforce_nonnegativity,nonneg_type, # compute_initcond,constraint_init,constraint_type,algebraic_var self.ddaspk_pars = { 'rtol': [1e-4, 1e-4, 1e-4], 'atol': [1e-8, 1e-14, 1e-6], } self.ida_pars = { 'rtol': 1e-4, 'atol': [1e-8, 1e-14, 1e-6], } self.lsodi_pars = { 'rtol': [1e-4, 1e-4, 1e-4], 'atol': [1e-6, 1e-10, 1e-6], 'adda_func': self.adda }
def test_cvode_tstopfn(self): #test tstop finding and stopping: End is reached at a tstop global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.TSTOP_RETURN, "ERROR: Tstop not found!" assert allclose([soln.tstop.t[0], soln.tstop.y[0,0], soln.tstop.y[0,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol) assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol)
def test_cvode_rootfn_end(self): #test root finding with root at endtime tspan = np.arange(0, 30 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=1, rootfn=root_fn3, onroot=onroot_vc, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.ROOT_RETURN, "ERROR: Not sufficient root found" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [30.0, -1452.5024, -294.3000], atol=atol, rtol=rtol) assert len(soln.roots.t) == 3, "ERROR: Did not find all 4 roots" assert allclose([soln.roots.t[-1], soln.roots.y[-1,0], soln.roots.y[-1,1]], [30.0, -1452.5024, -294.3000], atol=atol, rtol=rtol)
def test_cvode_rootfnacc(self): #test root finding and accumilating: End is reached normally, roots stored tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=1, rootfn=root_fn, onroot=onroot_va, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.SUCCESS, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [100.0, 459.8927, -981.0000], atol=atol, rtol=rtol) assert len(soln.roots.t) == 49, "ERROR: Did not find all 49 roots" assert allclose([soln.roots.t[-1], soln.roots.y[-1,0], soln.roots.y[-1,1]], [99.447910, 10.0000, -975.5840], atol=atol, rtol=rtol)
def test_cvode_rootfn_test(self): #test root finding and accumilating: End is reached after a number of root tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=1, rootfn=root_fn, onroot=onroot_vc, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.ROOT_RETURN, "ERROR: Not sufficient root found" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [28.0, 124.4724, -274.6800], atol=atol, rtol=rtol) assert len(soln.roots.t) == 4, "ERROR: Did not find all 4 roots" assert allclose([soln.roots.t[-1], soln.roots.y[-1,0], soln.roots.y[-1,1]], [28.413692, 10.0000, -278.7383], atol=atol, rtol=rtol)
def test_cvode_rootfn_two(self): #test two root finding tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, nr_rootfns=2, rootfn=root_fn2, onroot=onroot_vc, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.ROOT_RETURN, "ERROR: Not sufficient root found" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [28.0, 106.4753, -274.6800], atol=atol, rtol=rtol) assert len(soln.roots.t) == 5, "ERROR: Did not find all 4 roots" assert allclose([soln.roots.t[-1], soln.roots.y[-1,0], soln.roots.y[-1,1]], [28.349052, 10.0000, -278.1042], atol=atol, rtol=rtol)
def test_cvode_tstopfnacc(self): #test tstop finding and accumilating: End is reached normally, tstop stored global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, ontstop=ontstop_va, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.SUCCESS, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [100.0, -8319.5023, -981.00], atol=atol, rtol=rtol) assert len(soln.tstop.t) == 9, "ERROR: Did not find all tstop" assert allclose([soln.tstop.t[-1], soln.tstop.y[-1,0], soln.tstop.y[-1,1]], [90.0, -7338.5023, -882.90], atol=atol, rtol=rtol)
def test_cvode_tstopfn_test(self): #test calling sequence. tsop function continues up to a time global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, ontstop=ontstop_vc, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.TSTOP_RETURN, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [30.0, -1452.5024, -294.30], atol=atol, rtol=rtol) assert len(soln.tstop.t) == 3, "ERROR: Did not find all tstop" assert len(soln.values.t) == 31, "ERROR: Did not find all output" assert allclose([soln.tstop.t[-1], soln.tstop.y[-1,0], soln.tstop.y[-1,1]], [30.0, -1452.5024, -294.30], atol=atol, rtol=rtol)
def __init__(self): """We obtain the vode solution first""" r = Iode(self.f_vode, self.jac_vode).set_integrator('vode', rtol=[1e-4,1e-4,1e-4], atol=[1e-8,1e-14,1e-6], method='bdf', ) r.set_initial_value([1.,0.,0.]) nr = 5 self.sol = zeros((nr, 3)) self.stop_t = [0., 0.4, 4., 40., 400.] self.sol[0] = r.y i=1 for time in self.stop_t[1:]: r.integrate(time) self.sol[i] = r.y i +=1 #we now do the same with the sundials CVODE solution r = ode('cvode', self.f_cvode, jacfn=self.jac_cvode, rtol=1e-4, atol=[1e-8,1e-14,1e-6], lmm_type='bdf', old_api=False, ) soln = r.solve(self.stop_t, [1.,0.,0.]) self.sol2 = soln.values.y #for the solvers, only stop time, not start: self.stop_t = self.stop_t[1:] #we need to activate some extra parameters in the solver #order par is rtol,atol,lband,uband,tstop,order,nsteps, # max_step,first_step,enforce_nonnegativity,nonneg_type, # compute_initcond,constraint_init,constraint_type,algebraic_var self.ddaspk_pars = {'rtol' : [1e-4,1e-4,1e-4], 'atol' : [1e-8,1e-14,1e-6], } self.ida_pars = {'rtol' : 1e-4, 'atol' : [1e-8,1e-14,1e-6], } self.lsodi_pars = {'rtol' : [1e-4,1e-4,1e-4], 'atol' : [1e-6,1e-10,1e-6], 'adda_func' : self.adda }
def test_cvode_tstopfn_stop(self): #test calling sequence. End is reached at a tstop global n n = 0 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) solver = ode('cvode', rhs_fn, tstop=T1, ontstop=ontstop_vb, old_api=False) soln = solver.solve(tspan, y0) assert soln.flag==StatusEnum.TSTOP_RETURN, "ERROR: Error occurred" assert allclose([soln.values.t[-1], soln.values.y[-1,0], soln.values.y[-1,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol) assert len(soln.tstop.t) == 1, "ERROR: Did not find all tstop" assert len(soln.values.t) == 11, "ERROR: Did not find all output" assert allclose([soln.tstop.t[-1], soln.tstop.y[-1,0], soln.tstop.y[-1,1]], [10.0, 509.4995, -98.10], atol=atol, rtol=rtol)
def test_odes(): """ Solve a test ODE and make sure the results are accurate """ sols = [] with open("input/test_odes_sols.pickle", "rb") as test_vals: real_sols = pickle.load(test_vals) t0, y0 = 1, np.array([0.5, 0.5]) # initial condition solution = ode( 'cvode', van_der_pol, old_api=False).solve( np.linspace( t0, 500, 200), y0) for sol in solution.values.y: sols.append(sol) assert np.array_equal(sols, real_sols)
def calc_numerical_solution(*, initial_conditions, solver_config, time, tstop=0): """ Run the sundials ODE solver on the set of differential equations """ # initialise the differential equation system we want to solve. This is the model we have created system_to_solve, internal_data = ode_system(store_internal_data=True) # Create the sundials system solver = ode( 'cvode', system_to_solve, old_api=False, tstop=tstop, validate_flags=True, rtol=solver_config.relative_tolerance, atol=solver_config.absolute_tolerance, max_steps=solver_config.max_steps, ) # and solve it. try: soln = solver.solve(time, initial_conditions) except CVODESolveFailed as e: soln = e.soln print("Solver: FAILED at time {} with conditions {}".format( soln.values.t[-1], soln.values.y[-1, :])) except CVODESolveFoundRoot as e: soln = e.soln print("Solver: FOUND ROOT at time {} with conditions {}".format( soln.values.t[-1], soln.values.y[-1, :])) except CVODESolveReachedTSTOP as e: soln = e.soln print("Solver: TIME STOP at time {}".format(soln.values.t[-1])) # except: # Bare except for problems with division by zero # raise SystemExit("Something went horribly wrong when trying to solve the ODE. Exiting") return soln, internal_data
def _init_reaction_diffusion_params(self, params): #Initialize variables defined below if reaction-diffusion problem #is to be solved #Cantera gas and surface phase objects within the washcoat self._gas = params.get('gas_wc', None) self._surface = params.get('surf_wc', None) if self._gas == None or self._surface == None: raise ValueError('Cantera phase objects were not provided') #Number of grid points self.ngrid = params.get('ngrid', 15) #Create non-uniform washcoat coordinates self.stch = params.get('stch', 1.0) #Mesh stretching factor w0 = 1 self.wcoord = [w0] for i in range(self.ngrid - 1): w0 *= self.stch self.wcoord.append(w0) self.wcoord = np.array(self.wcoord) - 1.0 self.wcoord = self.thickness * self.wcoord / np.max(self.wcoord) #Pre-alloc input arrays for mass fractions and coverages self.y = np.zeros((self.ngrid, self._r.ng + 1)) self.covs = np.zeros((self.ngrid, self._r.rs.ns + 1)) #Create ODE solver object to solve transient problem from scikits.odes import ode self.solver = ode('cvode', self.eval_transient, atol=1e-10, rtol=1e-05, old_api=False, max_steps=5000)
def create_ode_solver(self, **options): """ Create a `scikits.odes` ODE solver that uses CVODE Args: options (:obj:`dict`): options for the solver; see https://github.com/bmcage/odes/blob/master/scikits/odes/sundials/cvode.pyx Returns: :obj:`scikits.odes.ode`: an ODE solver instance Raises: :obj:`MultialgorithmError`: if the ODE solver cannot be created """ # use CVODE from LLNL's SUNDIALS project (https://computing.llnl.gov/projects/sundials) CVODE_SOLVER = 'cvode' solver = ode(CVODE_SOLVER, self.right_hand_side, old_api=False, **options) if not isinstance(solver, ode): # pragma: no cover raise MultialgorithmError( f"OdeSubmodel {self.id}: scikits.odes.ode() failed") return solver
# define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = -k / m * x[0] def jaceqn(t, x, jac): jac[0, 1] = 1 jac[1, 0] = -k / m # instantiate the solver from scikits.odes import ode solver = ode("cvode", rhseqn, jacfn=jaceqn) # obtain solution at a required time result = solver.solve([0.0, 1.0, 2.0], initx) print("\n t Solution Exact") print("------------------------------------") for t, u in zip(result[1], result[2]): print( "%4.2f %15.6g %15.6g" % (t, u[0], initx[0] * cos(sqrt(k / m) * t) + initx[1] * sin(sqrt(k / m) * t) / sqrt(k / m)) ) # continue the solver result = solver.solve([result[1][-1], result[1][-1] + 1], result[2][-1]) print("------------------------------------") print(" ...continuation of the solution")
def main_solution(*, heights, initial_conditions, a_0, σ_O_0, σ_P_0, σ_H_0, ρ_s, relative_tolerance=float_type(1e-6), absolute_tolerance=float_type(1e-10), max_steps=500, onroot_func=None, tstop=None, ontstop_func=None, root_func=None, root_func_args=None): """ Find solution """ extra_args = {} if root_func is not None: extra_args["rootfn"] = root_func if root_func_args is not None: extra_args["nr_rootfns"] = root_func_args else: raise SolverError("Need to specify size of root array") system = ode_system( a_0=a_0, σ_O_0=σ_O_0, σ_P_0=σ_P_0, σ_H_0=σ_H_0, ρ_s=ρ_s, ) solver = ode(INTEGRATOR, system, linsolver=LINSOLVER, rtol=relative_tolerance, atol=absolute_tolerance, max_steps=max_steps, validate_flags=True, old_api=False, err_handler=error_handler, onroot=onroot_func, tstop=tstop, ontstop=ontstop_func, bdf_stability_detection=True, **extra_args) try: soln = solver.solve(heights, initial_conditions) except CVODESolveFailed as e: soln = e.soln log.warn("Solver stopped at {} with flag {!s}.\n{}".format( soln.errors.t, soln.flag, soln.message)) if soln.flag == StatusEnum.TOO_CLOSE: raise e except CVODESolveFoundRoot as e: soln = e.soln log.notice("Found root at {}".format(soln.roots.t)) except CVODESolveReachedTSTOP as e: soln = e.soln for tstop_scaled in soln.tstop.t: log.notice("Stopped at {}".format(tstop_scaled)) return soln
#data k = 4.0 m = 1.0 #initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, tstop=1.5, old_api=False) # force new api #obtain solution at a required time soln = solver.solve([0., 1., 2.], initx) result = soln.values tstop = soln.tstop print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result.t, result.y): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) print('------------------------------------') print('Solution stopped at {0} with {1[0]:.4g}'.format(tstop.t[0], tstop.y[0])) solver.set_options(tstop=5) #continue the solver
#data k = 4.0 m = 1.0 #initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, old_api=False) # force new api #obtain solution at a required time result = solver.solve([0., 1., 2.], initx).values print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result.t, result.y): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) #continue the solver result = solver.solve([result.t[-1], result.t[-1]+1], result.y[-1]).values print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------') for t, u in zip(result.t, result.y):
def __init__(self, gas, surf, **p): #Load Cantera solution objects self.gasCT = gas self.surfCT = surf self.bulkCT = p.get('bulk', None) #If a Cantera solution object is not given if self.gasCT == None: raise ValueError('Cantera gas solution object was not provided!') else: #Get gas species index self.gas_idx = np.array([ self.surfCT.kinetics_species_index(self.gasCT.species_names[n]) for n in range(self.gasCT.n_species) ]) #Total number of species in kinetic mechanism self.n_species = self.gasCT.n_species #If a Cantera solution object is not given if self.surfCT == None: raise ValueError( 'Cantera surface solution object was not provided!') else: #Get surface species index self.surf_idx = np.array([ self.surfCT.kinetics_species_index( self.surfCT.species_names[n]) for n in range(self.surfCT.n_species) ]) #Total number of species in kinetic mechanism self.n_species += self.surfCT.n_species #If a bulk phase exists if self.bulkCT != None: #Turn bulk flag on self.flag_bulk = 1 #Get bulk species index self.bulk_idx = np.array([ self.surfCT.kinetics_species_index( self.bulkCT.species_names[n]) for n in range(self.bulkCT.n_species) ]) #Total number of species in kinetic mechanism self.n_species += self.bulkCT.n_species else: #Turn bulk flag off self.flag_bulk = 0 #Check if a coverage enthalpy depedency file was given self.cov_file = p.get('cov_file', None) if self.cov_file != None: #Set the enthanlpy-dependency flag on self.flag_enthalpy_covs = 1 #Build coverage dependency matrix self.build_cov_matrix() else: #Set the enthanlpy-dependency flag off self.flag_enthalpy_covs = 0 #Gas constant [J/kmol K] self.Rg = 8314.4621 #Reaction rate multiplier self.rm = 1.0 #Get kinetics data from Cantera solution objects self.get_kinetics_data() #Initialize auxiliary terms for net rates calculation self.init_aux_terms() #Instantiate the solver to guess the initial coverages values self.solver = ode('cvode', self.dt_coverages, atol=1e-20, rtol=1e-05, max_steps=2000, old_api=False) #Set initial thermodynamic state (300 K, 1 atm) #Gas phase self.gasCT.TP = 300.0, 101325.0 if self.flag_bulk == 1: #Bulk phase self.bulkCT.TP = 300.0, 101325.0 #Surface kinetics self.set_initial_state(300.0, 101325.0)
def robo(show_ani): # Passive Dynamic Walking for bipedal robot # % reset # parameters of leg structure paras = np.loadtxt('../data/parameters.txt', delimiter=' ') try: last = paras[-1, :] except: last = paras global c_a1, c_b1, c_a2, c_b2 q1 = last[0] q2 = last[1] q3 = last[2] c_mh = 0.5 c_mt = 0.5 c_ms = 0.05 c_a1 = last[3] c_b1 = last[4] c_a2 = last[5] c_b2 = last[6] global mh, mt, ms, a1, b1, a2, b2, lt, ls, l M = 1 # total weight L = 1 # total lenth mh = M * c_mh #mass of hip mt = M * c_mt # mass of thigh ms = M * c_ms # mass of shank a1 = L * c_a1 b1 = L * c_b1 a2 = L * c_a2 b2 = L * c_b2 lt = a2 + b2 # length of thigh ls = a1 + b1 # length of shank l = lt + ls global g, dt g = 9.8 # acceleration due to gravity, in m/s^2 dt = 0.001 # time step of simulation step_idx = 1 step_tt = 1 # how many steps going to walk step_out = 0 # show state information at every time step of the first step cycle if show_ani: step_tt = 5 step_out = 1 # show state information at every time step of the first step cycle # slop of terran global _gamma _gamma = 0.0504 global x_sf, y_sf, x_h, y_h, x_nsk, y_nsk, x_nsf, y_nsf, x_sk, y_sk global orbit_q1, orbit_q2, orbit_q3, orbit_q1d, orbit_q2d, orbit_q3d x_sf, y_sf, x_h, y_h, x_nsk, y_nsk, x_nsf, y_nsf, x_sk, y_sk = ( np.zeros(0) for _ in range(10)) orbit_q1, orbit_q2, orbit_q3, orbit_q1d, orbit_q2d, orbit_q3d = ( np.zeros(0) for _ in range(6)) tt_time_step = [] from scikits.odes import ode ini_state = [0.1877, -1.1014, -0.2884, -0.0399, -0.2884, -0.0399] pos_sf = [0, 0] # state = [q1, -1.1014, q2, -0.0399, q3, -0.0399] while True: try: solver = ode('cvode', three_linked_chain_rt, nr_rootfns=1, rootfn=root_ks, old_api=False) result = solver.solve( [0, 1], ini_state ) # detect event, generally it takes less than one second to reach knee strike t = np.arange(0.0, result.roots.t, dt) t = np.append( t, result.roots.t) # add event time stamp, right continuous tmp = integrate.odeint(three_linked_chain, ini_state, t) # integrate three chain dynamics state = np.insert(tmp[1:len(tmp) + 1], [0], ini_state, axis=0) if step_out: print('init condition: ', ini_state) print('time to knee strike: ', result.roots.t) print('three link dynamics end state: ', result.roots.y) tmp = knee_strike(state[-1]) state = np.insert(state, [len(state)], tmp, axis=0) if step_out: print('knee strike end state: ', state[-1]) solver = ode('cvode', two_linked_chain_rt, nr_rootfns=1, rootfn=root_hs, old_api=False) result = solver.solve( [0, 0.5], state[-1] ) # detect event, generally it takes less than half second to reach heel strike t = np.arange(0.0, result.roots.t, dt) t = np.append( t, result.roots.t) # add event time stamp, right continuous tmp = integrate.odeint(two_linked_chain, state[-1], t) # integrate two chain dynamics state = np.insert(tmp[1:len(tmp) + 1], [0], state, axis=0) if step_out: print('time to heel strike: ', result.roots.t) print('two link dynamics end state: ', result.roots.y) tmp = heel_strike(state[-1]) state = np.insert(state, [len(state)], tmp, axis=0) if step_out: print('heel strike end state: ', state[-1]) if step_idx == 1: time_idx = len(state) else: time_idx = len(state) + tt_time_step[-1] tt_time_step += [time_idx] if step_idx % 2 == 1: orbit_q1 = np.append(orbit_q1, state[:, 0]) orbit_q2 = np.append(orbit_q2, state[:, 2]) orbit_q3 = np.append(orbit_q3, state[:, 4]) orbit_q1d = np.append(orbit_q1d, state[:, 1]) orbit_q2d = np.append(orbit_q2d, state[:, 3]) orbit_q3d = np.append(orbit_q3d, state[:, 5]) else: orbit_q1 = np.append(orbit_q1, state[:, 2]) orbit_q2 = np.append(orbit_q2, state[:, 0]) orbit_q3 = np.append(orbit_q3, state[:, 0]) orbit_q1d = np.append(orbit_q1d, state[:, 3]) orbit_q2d = np.append(orbit_q2d, state[:, 1]) orbit_q3d = np.append(orbit_q3d, state[:, 1]) if step_idx == 1: t_start = 0 t_end = tt_time_step[-1] else: t_start = tt_time_step[-2] t_end = tt_time_step[-1] q1 = state[:, 0] q2 = state[:, 2] q3 = state[:, 4] x_sf_tmp = np.ones_like(q1) * pos_sf[0] x_sf = np.append(x_sf, x_sf_tmp) y_sf_tmp = np.ones_like(q1) * pos_sf[1] y_sf = np.append(y_sf, y_sf_tmp) x_h_tmp = x_sf_tmp - l * sin(q1) x_h = np.append(x_h, x_h_tmp) y_h_tmp = y_sf_tmp + l * cos(q1) y_h = np.append(y_h, y_h_tmp) x_nsk_tmp = x_h_tmp + lt * sin(q2) x_nsk = np.append(x_nsk, x_nsk_tmp) y_nsk_tmp = y_h_tmp - lt * cos(q2) y_nsk = np.append(y_nsk, y_nsk_tmp) x_nsf_tmp = x_nsk_tmp + ls * sin(q3) x_nsf = np.append(x_nsf, x_nsf_tmp) y_nsf_tmp = y_nsk_tmp - ls * cos(q3) y_nsf = np.append(y_nsf, y_nsf_tmp) ini_state = [ state[-1, 4], state[-1, 5], state[-1, 0], state[-1, 1], state[-1, 0], state[-1, 1] ] except: output = [[ 10000, -10000 ]] # something unexpected. set it as very unstable and slow. np.savetxt('../data/out.txt', output, delimiter=' ') if step_idx == 1: diff = [x - y for x, y in zip(ini_state, state[0]) ] # difference in starting state of two step cycle stability = np.linalg.norm(diff) v1 = [cos(_gamma), -sin(_gamma)] v2 = [x_nsf[-1], y_nsf[-1]] disp = np.dot(v1, v2) if disp < 0: speed = 1000 * disp else: speed = disp output = [[stability, speed]] np.savetxt('../data/out.txt', output, delimiter=' ') pos_sf = [x_nsf[-1], y_nsf[-1]] if step_idx == step_tt: break step_idx += 1 x_sk = x_h * (c_a1 + c_b1) + x_sf * (c_a2 + c_b2) y_sk = y_h * (c_a1 + c_b1) + y_sf * (c_a2 + c_b2) s = (c_a1 + c_b1) + (c_a2 + c_b2) x_sk /= s y_sk /= s if show_ani: show_animation()
import pkg_resources print(pkg_resources.get_distribution("scikits.odes").version) #od.test() t0, tT = 1, 500 # considered interval y0 = np.array([0.5, 0.5]) # initial condition def van_der_pol(t, y, ydot): """ we create rhs equations for the problem""" ydot[0] = y[1] ydot[1] = 1000 * (1.0 - y[0]**2) * y[1] - y[0] num = 200 t_n = np.linspace(t0, tT, num) solution = odeint(van_der_pol, t_n, y0) plt.plot(solution.values.t, solution.values.y[:, 0], label='Van der Pol oscillator') plt.show() print(solution.values.y) solution = od.ode('cvode', van_der_pol, old_api=False).solve(np.linspace(t0, 500, 200), y0) plt.plot(solution.values.t, solution.values.y[:, 0], label='Van der Pol oscillator') plt.show()
else: for (t, y, v) in zip(t_roots, y_roots[:, 0], y_roots[:, 1]): print("{:6.6f} {:15.4f} {:15.4f}".format(t, y, v)) else: print("Error: one of (t_roots, y_roots) is None while the other not.") else: print("Computation failed.") # Set tspan to end at t_end1 tspan = np.arange(0, t_end1 + 1, 1.0, np.float) # # 1. Solve the problem without onroot function i.e. compute until # the first root is found # solver = ode("cvode", rhs_fn, nr_rootfns=1, rootfn=root_fn, old_api=False) print_results(1, solver.solve(tspan, y0)) # # 2. Solve the problem with onroot function onroot_va, which resets the problem # with the current velocity when a root is found. Note that we expect no roots. # solver = ode("cvode", rhs_fn, nr_rootfns=1, rootfn=root_fn, onroot=onroot_va, old_api=False) print_results(2, solver.solve(tspan, y0), require_no_roots=True) # Set tspan to end at t_end2 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) # # 3. Solve the problem without interrupt function i.e. compute until # the first root is found #
#data k = 4.0 m = 1.0 #initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, old_api=True) #obtain solution at a required time result = solver.solve([0., 10., 20.], initx) print ('\n sundials cvode old API') print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result[1], result[2]): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) #continue the solver result = solver.solve([result[1][-1], result[1][-1]+10, result[1][-1]+110], result[2][-1]) print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------')
#initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] def rootfn(t, x, g, userdata): g[0] = 0 if abs(t - pi/2) < 1e-3 else 1 def norootfn(t, x, g, userdata): g[0] = 1 #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, rootfn=rootfn, nr_rootfns=1, old_api=False) # force new api #obtain solution at a required time soln = solver.solve([0., 1., 2.], initx) result = soln.values print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result.t, result.y): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) print('------------------------------------') print('Root found at {:.6g}'.format(soln.roots.t[0])) solver.set_options(rootfn=norootfn, nr_rootfns=1)
else: for (t, y, v) in zip(t_tstop, y_tstop[:, 0], y_tstop[:, 1]): print('{:6.1f} {:15.4f} {:15.2f}'.format(t, y, v)) else: print('Error: one of (t_tstop, y_tstop) is None while the other not.') else: print('Computation failed.') # Set tspan to end at t_end1 tspan = np.arange(0, t_end1 + 1, 1.0, np.float) # # 1. Solve the problem without ontstop function i.e. compute until # the first tstop is found # n = 0 solver = ode('cvode', rhs_fn, tstop=Y1, old_api=False) print_results(1, solver.solve(tspan, y0)) # # 2. Solve the problem with ontstop function ontstop_va, which resets the problem # with the current velocity when a root is found. Note that we expect no roots. # n = 0 solver = ode('cvode', rhs_fn, tstop=Y1, ontstop=ontstop_va, old_api=False) print_results(2, solver.solve(tspan, y0), require_no_tstop=True) # Set tspan to end at t_end2 tspan = np.arange(0, t_end2 + 1, 1.0, np.float) # # 3. Solve the problem without interrupt function i.e. compute until # the first tstop is found
def setUp(self): self.ode = ode('cvode', rhs, linsolver="spgmr", old_api=False) self.solution = self.ode.solve(xs, np.array([1]))
k = 4.0 m = 1.0 #initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = -k / m * x[0] #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, tstop=1.5, old_api=False) # force new api #obtain solution at a required time soln = solver.solve([0., 1., 2.], initx) result = soln.values tstop = soln.tstop print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result.t, result.y): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0] * cos(sqrt(k / m) * t) + initx[1] * sin(sqrt(k / m) * t) / sqrt(k / m))) print('------------------------------------') print('Solution stopped at {0} with {1[0]:.4g}'.format(tstop.t[0], tstop.y[0]))
def robo(show_ani): # Passive Dynamic Walking for bipedal robot # % reset # parameters of leg structure paras = np.loadtxt('../data/parameters.txt', delimiter=' ') try: last = paras[-1,:] except: last = paras global c_a1,c_b1,c_a2,c_b2 q1 = last[0] q2 = last[1] q3 = last[2] c_mh = 0.5 c_mt = 0.5 c_ms = 0.05 c_a1 = last[3] c_b1 = last[4] c_a2 = last[5] c_b2 = last[6] global mh,mt,ms,a1,b1,a2,b2,lt,ls,l M = 1# total weight L = 1 # total lenth mh = M * c_mh #mass of hip mt = M * c_mt # mass of thigh ms = M * c_ms # mass of shank a1 = L * c_a1 b1 = L * c_b1 a2 = L * c_a2 b2 = L * c_b2 lt = a2 + b2 # length of thigh ls = a1 + b1 # length of shank l = lt + ls global g,dt g = 9.8 # acceleration due to gravity, in m/s^2 dt = 0.001 # time step of simulation step_idx = 1 step_tt = 1 # how many steps going to walk step_out = 0 # show state information at every time step of the first step cycle if show_ani: step_tt = 5 step_out = 1 # show state information at every time step of the first step cycle # slop of terran global _gamma _gamma = 0.0504 global x_sf,y_sf,x_h,y_h,x_nsk,y_nsk,x_nsf,y_nsf,x_sk,y_sk global orbit_q1,orbit_q2,orbit_q3,orbit_q1d,orbit_q2d,orbit_q3d x_sf, y_sf, x_h, y_h, x_nsk, y_nsk, x_nsf, y_nsf, x_sk, y_sk = (np.zeros(0) for _ in range(10)) orbit_q1, orbit_q2, orbit_q3, orbit_q1d, orbit_q2d, orbit_q3d = (np.zeros(0) for _ in range(6)) tt_time_step =[] from scikits.odes import ode ini_state = [0.1877, -1.1014, -0.2884, -0.0399, -0.2884, -0.0399] pos_sf = [0,0] # state = [q1, -1.1014, q2, -0.0399, q3, -0.0399] while True: try: solver = ode('cvode', three_linked_chain_rt, nr_rootfns=1, rootfn=root_ks, old_api=False) result = solver.solve([0,1], ini_state ) # detect event, generally it takes less than one second to reach knee strike t = np.arange(0.0, result.roots.t, dt) t = np.append(t,result.roots.t) # add event time stamp, right continuous tmp = integrate.odeint(three_linked_chain, ini_state , t) # integrate three chain dynamics state = np.insert(tmp[1:len(tmp) + 1], [0], ini_state , axis=0) if step_out: print('init condition: ',ini_state ) print('time to knee strike: ', result.roots.t) print('three link dynamics end state: ',result.roots.y) tmp = knee_strike(state[-1]) state = np.insert(state, [len(state)], tmp, axis=0) if step_out: print('knee strike end state: ',state[-1]) solver = ode('cvode', two_linked_chain_rt, nr_rootfns=1, rootfn=root_hs, old_api=False) result = solver.solve([0,0.5], state[-1]) # detect event, generally it takes less than half second to reach heel strike t = np.arange(0.0, result.roots.t, dt) t = np.append(t,result.roots.t) # add event time stamp, right continuous tmp = integrate.odeint(two_linked_chain, state[-1], t) # integrate two chain dynamics state = np.insert(tmp[1:len(tmp) + 1], [0], state, axis=0) if step_out: print('time to heel strike: ', result.roots.t) print('two link dynamics end state: ', result.roots.y) tmp = heel_strike(state[-1]) state = np.insert(state, [len(state)], tmp, axis=0) if step_out: print('heel strike end state: ',state[-1]) if step_idx ==1: time_idx = len(state) else: time_idx = len(state) + tt_time_step[-1] tt_time_step += [time_idx] if step_idx%2 ==1: orbit_q1 = np.append(orbit_q1,state[:, 0]) orbit_q2 = np.append(orbit_q2,state[:, 2]) orbit_q3 = np.append(orbit_q3,state[:, 4]) orbit_q1d = np.append(orbit_q1d,state[:, 1]) orbit_q2d = np.append(orbit_q2d,state[:, 3]) orbit_q3d = np.append(orbit_q3d,state[:, 5]) else: orbit_q1 = np.append(orbit_q1,state[:, 2]) orbit_q2 = np.append(orbit_q2,state[:, 0]) orbit_q3 = np.append(orbit_q3,state[:, 0]) orbit_q1d = np.append(orbit_q1d,state[:, 3]) orbit_q2d = np.append(orbit_q2d,state[:, 1]) orbit_q3d = np.append(orbit_q3d,state[:, 1]) if step_idx==1: t_start = 0 t_end = tt_time_step[-1] else: t_start = tt_time_step[-2] t_end = tt_time_step[-1] q1 = state[:, 0] q2 = state[:, 2] q3 = state[:, 4] x_sf_tmp = np.ones_like(q1) * pos_sf[0] x_sf = np.append(x_sf,x_sf_tmp) y_sf_tmp = np.ones_like(q1) * pos_sf[1] y_sf = np.append(y_sf,y_sf_tmp) x_h_tmp = x_sf_tmp - l * sin(q1) x_h = np.append(x_h,x_h_tmp) y_h_tmp = y_sf_tmp + l * cos(q1) y_h = np.append(y_h,y_h_tmp) x_nsk_tmp = x_h_tmp + lt * sin(q2) x_nsk = np.append(x_nsk,x_nsk_tmp) y_nsk_tmp = y_h_tmp - lt * cos(q2) y_nsk = np.append(y_nsk,y_nsk_tmp) x_nsf_tmp = x_nsk_tmp + ls * sin(q3) x_nsf = np.append(x_nsf,x_nsf_tmp) y_nsf_tmp = y_nsk_tmp - ls * cos(q3) y_nsf = np.append(y_nsf,y_nsf_tmp) ini_state = [state[-1, 4],state[-1, 5],state[-1, 0],state[-1, 1],state[-1, 0],state[-1, 1]] except: output = [[10000, -10000]] # something unexpected. set it as very unstable and slow. np.savetxt('../data/out.txt', output, delimiter=' ') if step_idx == 1: diff = [x - y for x, y in zip(ini_state, state[0])] # difference in starting state of two step cycle stability = np.linalg.norm(diff) v1 = [cos(_gamma), -sin(_gamma)] v2 = [x_nsf[-1], y_nsf[-1]] disp = np.dot(v1, v2) if disp < 0: speed = 1000 * disp else: speed = disp output = [[stability, speed]] np.savetxt('../data/out.txt', output, delimiter=' ') pos_sf = [x_nsf[-1], y_nsf[-1]] if step_idx==step_tt: break step_idx += 1 x_sk = x_h * (c_a1 + c_b1) + x_sf * (c_a2 + c_b2) y_sk = y_h * (c_a1 + c_b1) + y_sf * (c_a2 + c_b2) s = (c_a1 + c_b1) + (c_a2 + c_b2) x_sk /= s y_sk /= s if show_ani: show_animation()
#define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = -k / m * x[0] def jaceqn(t, x, jac): jac[0, 1] = 1 jac[1, 0] = -k / m #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, jacfn=jaceqn) #obtain solution at a required time result = solver.solve([0., 1., 2.], initx) print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result[1], result[2]): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0] * cos(sqrt(k / m) * t) + initx[1] * sin(sqrt(k / m) * t) / sqrt(k / m))) #continue the solver result = solver.solve([result[1][-1], result[1][-1] + 1], result[2][-1]) print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------')
#initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] def jaceqn(t, x, fx, jac): jac[0,1] = 1 jac[1,0] = -k/m #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn, jacfn=jaceqn) #obtain solution at a required time result = solver.solve([0., 1., 2.], initx) print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result[1], result[2]): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) #continue the solver result = solver.solve([result[1][-1], result[1][-1]+1], result[2][-1]) print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------') for t, u in zip(result[1], result[2]):
z[1] = - gamma*k/m * r[0] + r[1] def jac_times_vecfn(v, Jv, t, y, user_data): """ Calculate Jacobian times vector product Jv = J*v""" Jv[0] = v[1] Jv[1] = -k/m * v[0] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] #instantiate the solver using a left-preconditioned BiCGStab as linear solver from scikits.odes import ode solver = ode('cvode', rhseqn, linsolver='spbcgs', precond_type='left', prec_solvefn=prec_solvefn, jac_times_vecfn=jac_times_vecfn) #obtain solution at a required time result = solver.solve([0., 1., 2.], initx) print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result[1], result[2]): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) #continue the solver result = solver.solve([result[1][-1], result[1][-1]+1], result[2][-1]) print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------') for t, u in zip(result[1], result[2]):
return Ydot # ODE parameters sigma = 10. rho = 28. beta = 8./3. # Initial conditions Y0 = [1., 1., 1.] # Instantiating the integrator solver = ode('cvode', f, rtol = 1e-6, atol = 1e-9) # Total simulation time tf = 3000. # Times at which we want the output t = np.linspace(0., tf, 100*int(tf)) # Integrating the Lorentz system results = solver.solve(t, Y0) # Writing output to a file Youtput = np.zeros( (len( results[1] ), 4) ) Youtput[:,0] = results[1] Youtput[:,1] = results[2][:,0]
def main_solution( *, angles, system_initial_conditions, ode_initial_conditions, γ, a_0, norm_kepler_sq, relative_tolerance=float_type(1e-6), absolute_tolerance=float_type(1e-10), max_steps=500, onroot_func=None, jump_before_sonic=None, tstop=None, ontstop_func=None, η_derivs=True, store_internal=True, root_func=None, root_func_args=None, θ_scale=float_type(1), use_E_r=False, v_θ_sonic_crit=None, after_sonic=None, deriv_v_θ_func=None, sonic_interp_size=None ): """ Find solution """ extra_args = {} if sonic_interp_size is not None and root_func is not None: raise SolverError("Cannot use both sonic point interp and root_func") if sonic_interp_size is not None and jump_before_sonic is not None: raise SolverError("Cannot use two sonic point methods") if sonic_interp_size is not None and not store_internal: raise SolverError("Interpolation requires internal storage") if jump_before_sonic is not None and root_func is not None: raise SolverError("Cannot use both sonic point jumper and root_func") elif jump_before_sonic is not None and onroot_func is not None: raise SolverError("Cannot use both sonic point jumper and onroot_func") elif sonic_interp_size is not None: extra_args["rootfn"] = velocity_stop_generator(1 - sonic_interp_size) extra_args["nr_rootfns"] = 1 elif jump_before_sonic is not None: extra_args["rootfn"] = velocity_stop_generator(1 - jump_before_sonic) extra_args["nr_rootfns"] = 1 elif root_func is not None: extra_args["rootfn"] = root_func if root_func_args is not None: extra_args["nr_rootfns"] = root_func_args else: raise SolverError("Need to specify size of root array") if len(angles) < 2: raise SolverError( f"Insufficient angles to solve at - angles: {angles}" ) system, internal_data = ode_system( γ=γ, a_0=a_0, norm_kepler_sq=norm_kepler_sq, init_con=system_initial_conditions, η_derivs=η_derivs, store_internal=store_internal, with_taylor=False, θ_scale=θ_scale, use_E_r=use_E_r, v_θ_sonic_crit=v_θ_sonic_crit, after_sonic=after_sonic, deriv_v_θ_func=deriv_v_θ_func, ) solver = ode( INTEGRATOR, system, linsolver=LINSOLVER, rtol=relative_tolerance, atol=absolute_tolerance, max_steps=max_steps, validate_flags=True, old_api=False, err_handler=error_handler, onroot=onroot_func, tstop=rad_to_scaled(tstop, θ_scale), ontstop=ontstop_func, bdf_stability_detection=True, **extra_args ) try: soln = solver.solve(angles, ode_initial_conditions) except CVODESolveFailed as e: soln = e.soln log.warn( "Solver stopped at {} with flag {!s}.\n{}".format( degrees(scaled_to_rad(soln.errors.t, θ_scale)), soln.flag, soln.message ) ) if soln.flag == StatusEnum.TOO_CLOSE: raise e except CVODESolveFoundRoot as e: soln = e.soln log.notice("Found root at {}".format( degrees(scaled_to_rad(soln.roots.t, θ_scale)) )) except CVODESolveReachedTSTOP as e: soln = e.soln for tstop_scaled in soln.tstop.t: log.notice("Stopped at {}".format( degrees(scaled_to_rad(tstop_scaled, θ_scale)) )) if internal_data is not None: internal_data._finalise() # pylint: disable=protected-access return soln, internal_data
#CO and H2O inlet molar fractions co_x = 0.55*(ratio/(ratio+flipratio)) h2o_x = 0.55*(flipratio/(ratio+flipratio)) '''Test PFR with simplified kinetics expression''' #Initialize simple PFR r = PFR_simple(gas = gas, surf = surf, diam = 0.01520, rate_eff = 1) #Instantiate the solver solver = ode('cvode', r.eval_reactor_wgs, atol = 1e-09, rtol = 1e-06, max_steps = 2000, old_api = False) #Inlet pressure [Pa] P_in = 1e05 #Temperature range #Trange = [T_in] Trange = list(np.linspace(273.15+300,273.15+800,100)) #Reactor axial coordinates [m] zcoord = np.linspace(0.0, 0.01, 250) #Coverage data from micro-kinetic simulation cov_data = np.array(wgs_data_incomps['covs'])
#data k = 4.0 m = 1.0 #initial data on t=0, x[0] = u, x[1] = \dot{u}, xp = \dot{x} initx = [1, 0.1] #define function for the right-hand-side equations which has specific signature def rhseqn(t, x, xdot): """ we create rhs equations for the problem""" xdot[0] = x[1] xdot[1] = - k/m * x[0] #instantiate the solver from scikits.odes import ode solver = ode('cvode', rhseqn) #obtain solution at a required time result = solver.solve([0., 1., 2.], initx) print('\n t Solution Exact') print('------------------------------------') for t, u in zip(result[1], result[2]): print('%4.2f %15.6g %15.6g' % (t, u[0], initx[0]*cos(sqrt(k/m)*t)+initx[1]*sin(sqrt(k/m)*t)/sqrt(k/m))) #continue the solver result = solver.solve([result[1][-1], result[1][-1]+1], result[2][-1]) print('------------------------------------') print(' ...continuation of the solution') print('------------------------------------') for t, u in zip(result[1], result[2]):