# ODE 方程组问题

## 介绍

\begin{align} \frac{dx}{dt} &= \alpha x - \beta xy \\ \frac{dy}{dt} &= \delta xy - \gamma y \end{align}

• du 代表左边的微分 \frac{dx}{dt}\frac{dy}{dt}
• u 代表 变量的组合， xy
• p 代表常数项

$$f(du, u, p, t) = \begin{cases} du[1] = p[1] u[1] - p[2] u[1] u[2] \\ du[2] = p[4] u[1] u[2] - p[3] u[2] \end{cases}$$

## 描述问题

function lotka_volterra(du, u, p, t)
x, y = u
alpha, beta, gamma, delta = p
du[1] = alpha * x - beta * x * y
du[2] = delta * x * y - gamma * y
end


• x 是猎物的数量，比如狒狒
• y 是猎手的数量，比如猎豹
• \frac{dx}{dt}\frac{dy}{dt} 代表两个数量的瞬时增长率
• t 表示时间
• \alpha \beta, \gamma, \delta 描述两个物种相互作用的正实参数

• x_begin 初始的狒狒数量为 10
• y_begin 初始的猎豹数量为 10
• u_begin 为 [xbegin, ybegin]
• \alpha 为 0.4
• \beta 为 0.4
• \gamma 为 0.4
• \delta 为 0.1
• tspan 为 (0, 100)
• p 为 [\alpha, \beta, \gamma, \delta]

prob = ODEProblem(lotka_volterra, u_begin, tspan, p)


## 解决问题

sol = solve(prob)


plot(sol,
legend = (0.78, 0.09),
linewidth = 2,
title = "Lotka-Volterra Equations",
xaxis = "Time in Years",
yaxis = "Population",
labels = ["Baboons" "Cheetahs"],
formatter = :plain,
widen = true,
xlims = (0.0, 100.0),
ylims = (0.0, 30.0))


# ODE 方程组 洛仑兹方程组

## 描述问题

\begin{align} \frac{dx}{dt} &= \sigma(y - x) \\ \frac{dy}{dt} &= x(\rho - z) - y \\ \frac{dz}{dt} &= xy - \beta z \end{align}

• x_begin 为 0
• y_begin 为 1
• z_begin 为 0
• u_begin 为 [xbegin, ybegin, zbegin]
• \sigma 为 10.0
• \rho 为 28.0
• \beta 为 8/3
• p 常数项 [\sigma, \rho, \beta]
• tspan 时间间隔为 (0.0, 100.0)

function lorenz(du, u, p, t)
x, y, z = u
sigma, rho, beta = p
du[1] = sigma * (y - x)
du[2] = x * (rho - z) - y
du[3] = x * y - beta * z
end


prob = ODEProblem(lorenz, u_begin, tspan, p)


## 解决问题

sol = solve(prob, reltol = 1e-8, abstol = 1e-8)


u = view(sol.u, 1:length(sol.t))
sol_u_matrix = reduce(hcat, u)'
x = sol_u_matrix[:, 1]
y = sol_u_matrix[:, 2]
z = sol_u_matrix[:, 3]


plot(x, y, z,
legend = false,
title = "Lorenz Attractor (phase space x y z)",
xaxis = "convection (x)",
yaxis = "horizontal (y)",
zaxis = "vertical (z)",
formatter = :plain,
widen = true,
xlims = (-30.0, 30.0),
ylims = (-30.0, 30.0),
zlims = (0.0, 50.0))