我有一个可能发生许多事件的动态系统。我想终止一个事件上的轨迹积分,但我也想知道哪个事件被激活了。
我找到的解决方法是使用全局变量将事件索引保存在affect!
函数中。这是弹跳球示例的修改版本:
using DifferentialEquations
function f(du,u,p,t)
du[1] = u[2]
du[2] = -p
du[3] = u[4]
du[4] = 0.0
end
function condition(out,u,t,integrator) # Event when event_f(u,t) == 0
out[1] = u[1]
out[2] = (u[3] - 10.0)u[3]
end
event_idx = [0, ] # global variable
function affect!(integrator, idx)
event_idx[1] = idx
terminate!(integrator)
end
cb = VectorContinuousCallback(condition,affect!,2)
u0 = [50.0,0.0,0.0,2.0]
tspan = (0.0,15.0)
p = 9.8
prob = ODEProblem(f,u0,tspan,p)
sol = solve(prob,Tsit5(),callback=cb,dt=1e-3,adaptive=false)
println(sol.retcode)
println(event_idx) # [1]
这样做有更好的解决方案吗?