|
| 1 | +# # Implicit time-integration |
| 2 | + |
| 3 | +# ## Necessary packages |
| 4 | +using NewtonKrylov |
| 5 | +using CairoMakie |
| 6 | + |
| 7 | +# ## Implicit schemes |
| 8 | + |
| 9 | +# ### Implicit Euler |
| 10 | + |
| 11 | +function G_Euler!(res, f, y, yₙ, t, Δt) |
| 12 | + return res .= yₙ .+ Δt .* f(y, t) .- y |
| 13 | +end |
| 14 | + |
| 15 | +# ### Implicit Midpoint |
| 16 | + |
| 17 | +function G_Midpoint!(res, f, y, yₙ, t, Δt) |
| 18 | + return res .= yₙ .+ Δt .* f((yₙ .+ y) ./ 2, t + Δt / 2) .- y |
| 19 | +end |
| 20 | + |
| 21 | +# ### Implicit Trapezoid |
| 22 | + |
| 23 | +function G_Trapezoid!(res, f, y, yₙ, t, Δt) |
| 24 | + return res .= yₙ .+ (Δt / 2) .* (f(yₙ, t) .+ f(y, t + Δt)) .- y |
| 25 | +end |
| 26 | + |
| 27 | +# ## Spring equations |
| 28 | + |
| 29 | +function f(x, t, γ) |
| 30 | + return [ |
| 31 | + x[2], # dx/dt = v |
| 32 | + -γ^2 * x[1], |
| 33 | + ] # dv/dt = -γ^2 * x |
| 34 | +end |
| 35 | + |
| 36 | +# ## Non-adaptive time stepping |
| 37 | + |
| 38 | +function implicit_spring(G! = G_Euler!) |
| 39 | + k = 2.0 # spring constant |
| 40 | + m = 1.0 # object's mass |
| 41 | + x0 = 0.1 # initial position |
| 42 | + v0 = 0.0 # initial velocity |
| 43 | + |
| 44 | + t₀ = 0.0 |
| 45 | + tₛ = 40.0 |
| 46 | + Δt = 0.01 |
| 47 | + |
| 48 | + ts = t₀:Δt:tₛ |
| 49 | + |
| 50 | + yₙ = [x0, v0] |
| 51 | + |
| 52 | + γ = sqrt(k / m) |
| 53 | + |
| 54 | + hist = [copy(yₙ)] |
| 55 | + for t in ts |
| 56 | + if t == t₀ |
| 57 | + continue |
| 58 | + end |
| 59 | + F!(res, y) = G!(res, (y, t) -> f(y, t, γ), y, yₙ, t, Δt) |
| 60 | + y, _ = newton_krylov!(F!, copy(yₙ)) |
| 61 | + push!(hist, y) |
| 62 | + yₙ .= y |
| 63 | + end |
| 64 | + return hist, ts |
| 65 | +end |
| 66 | + |
| 67 | +# ## Plots |
| 68 | + |
| 69 | +hist_euler, ts_euler = implicit_spring(G_Euler!) |
| 70 | +v_euler = map(y -> y[1], hist_euler) |
| 71 | +x_euler = map(y -> y[2], hist_euler) |
| 72 | + |
| 73 | +hist_midpoint, ts_midpoint = implicit_spring(G_Midpoint!) |
| 74 | +v_midpoint = map(y -> y[1], hist_midpoint) |
| 75 | +x_midpoint = map(y -> y[2], hist_midpoint) |
| 76 | + |
| 77 | + |
| 78 | +hist_trapezoid, ts_trapezoid = implicit_spring(G_Trapezoid!) |
| 79 | +v_trapezoid = map(y -> y[1], hist_trapezoid) |
| 80 | +x_trapezoid = map(y -> y[2], hist_trapezoid) |
| 81 | + |
| 82 | + |
| 83 | +fig = Figure() |
| 84 | +ax = fig[1, 1] |
| 85 | + |
| 86 | +lines(fig[1, 1], ts_euler, v_euler, label = "Euler") |
| 87 | +lines(fig[1, 2], ts_euler, x_euler, label = "Euler") |
| 88 | + |
| 89 | +lines(fig[2, 1], ts_midpoint, v_midpoint, label = "Midpoint") |
| 90 | +lines(fig[2, 2], ts_midpoint, x_midpoint, label = "Midpoint") |
| 91 | + |
| 92 | +lines(fig[3, 1], ts_trapezoid, v_trapezoid, label = "Midpoint") |
| 93 | +lines(fig[3, 2], ts_trapezoid, x_trapezoid, label = "Midpoint") |
| 94 | + |
| 95 | +fig |
0 commit comments