ODE中与时间有关的事件

时间:2018-09-13 10:19:58

标签: julia ode

我最近从朱莉娅开始,想解决我常见的问题之一-实施与时间有关的事件。

现在我有:

# Packages
using Plots
using DifferentialEquations

# Parameters
k21 = 0.14*24
k12 = 0.06*24
ke = 1.14*24
α = 0.5
β = 0.05
η = 0.477
μ = 0.218
k1 = 0.5
V1 = 6

# Time
maxtime = 10
tspan = (0.0, maxtime)

# Dose
stim = 100

# Initial conditions
x0 = [0 0 2e11 8e11]

# Model equations
function system(dy, y, p, t)
  dy[1] = k21*y[2] - (k12 + ke)*y[1]
  dy[2] = k12*y[1] - k21*y[2]
  dy[3] = (α - μ - η)*y[3] + β*y[4] - k1/V1*y[1]*y[3]
  dy[4] = μ*y[3] - β*y[4]
end

# Events
eventtimes = [2, 5]
function condition(y, t, integrator)
    t - eventtimes
end
function affect!(integrator)
    x0[1] = stim
end
cb = ContinuousCallback(condition, affect!)

# Solve
prob = ODEProblem(system, x0, tspan)
sol = solve(prob, Rodas4(), callback = cb)

# Plotting
plot(sol, layout = (2, 2))

但是给出的输出不正确。更具体地说,没有考虑事件,并且0的初始条件似乎不是y1,而是stim

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

t - eventtimes不起作用,因为一个是标量,另一个是矢量。但是对于这种情况,仅使用DiscreteCallback会容易得多。当您将其设置为DiscreteCallback时,应预先设置停止时间,以使其达到25的回调。这是一个示例:

# Packages
using Plots
using DifferentialEquations

# Parameters
k21 = 0.14*24
k12 = 0.06*24
ke = 1.14*24
α = 0.5
β = 0.05
η = 0.477
μ = 0.218
k1 = 0.5
V1 = 6

# Time
maxtime = 10
tspan = (0.0, maxtime)

# Dose
stim = 100

# Initial conditions
x0 = [0 0 2e11 8e11]

# Model equations
function system(dy, y, p, t)
  dy[1] = k21*y[2] - (k12 + ke)*y[1]
  dy[2] = k12*y[1] - k21*y[2]
  dy[3] = (α - μ - η)*y[3] + β*y[4] - k1/V1*y[1]*y[3]
  dy[4] = μ*y[3] - β*y[4]
end

# Events
eventtimes = [2.0, 5.0]
function condition(y, t, integrator)
    t ∈ eventtimes
end
function affect!(integrator)
    integrator.u[1] = stim
end
cb = DiscreteCallback(condition, affect!)

# Solve
prob = ODEProblem(system, x0, tspan)
sol = solve(prob, Rodas4(), callback = cb, tstops = eventtimes)

# Plotting
plot(sol, layout = (2, 2))

enter image description here

这完全避免了寻根,因此将时间选择窃取到寻根系统中应该是一个更好的解决方案。

无论哪种方式,请注意将affect更改为

function affect!(integrator)
    integrator.u[1] = stim
end

它需要修改当前的u值,否则将无济于事。