Skip to content

Commit 120acfa

Browse files
Add a tutorial for second-order ODEs and energy preservation (#131)
* Add a tutorial for second-order ODEs and energy preservation * Apply JuliaFormatter.jl
1 parent 6f4ce9c commit 120acfa

File tree

5 files changed

+168
-4
lines changed

5 files changed

+168
-4
lines changed

docs/Project.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@ DifferentialEquations = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
44
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
55
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
66
ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78"
7+
OrdinaryDiffEq = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed"
78
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
89
ProbNumDiffEq = "bf3e78b0-7d74-48a5-b855-9609533b56a5"

docs/make.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ makedocs(
99
"Home" => "index.md",
1010
"Tutorials" => [
1111
"Introduction to ODE Filters" => "getting_started.md"
12+
"Second Order ODEs and Energy Preservation" => "dynamical_odes.md"
1213
"Differential Algebraic Equations" => "dae.md"
1314
],
1415
"Solvers and Options" => "solvers.md",

docs/src/dynamical_odes.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# Second Order ODEs and Energy Preservation
2+
In this tutorial we consider an _energy-preserving_, physical dynamical system, given by a _second-order_ ODE.
3+
4+
5+
#### TL;DR:
6+
1. To _efficiently_ solve second-order ODEs, just define the problem as a `SecondOrderODEProblem`.
7+
2. To preserve constant quantities, use the `ManifoldUpdate` callback; same syntax as
8+
[DiffEqCallback.jl's `ManifoldProjection`](https://diffeq.sciml.ai/stable/features/callback_library/#Manifold-Conservation-and-Projection).
9+
10+
11+
## Simulating the Hénon-Heiles system
12+
The Hénon-Heiles model describes the motion of a star around a galactic center, restricted to a plane.
13+
It is given by a second-order ODE
14+
```math
15+
\begin{aligned}
16+
\ddot{x} &= - x - 2 x y \\
17+
\ddot{y} &= y^2 - y - x^2.
18+
\end{aligned}
19+
```
20+
Our goal is to numerically simulate this system on a time span
21+
``t \in [0, T]``, starting with initial values
22+
``x(0)=0``, ``y(0) = 0.1``, ``\dot{x}(0) = 0.5``, ``\dot{y}(0) = 0``.
23+
24+
25+
### Transforming the problem into a first-order ODE
26+
A very common approach is to first transform the problem into a first-order ODE by introducing a new variable
27+
```math
28+
u = [dx,dy,x,y],
29+
```
30+
to obtain
31+
```math
32+
\begin{aligned}
33+
\dot{u}_1(t) &= - u_3 - 2 u_3 u_4 \\
34+
\dot{u}_2(t) &= u_4^2 - u_4 - u_4^2 \\
35+
\dot{u}_3(t) &= u_1 \\
36+
\dot{u}_4(t) &= u_2.
37+
\end{aligned}
38+
```
39+
40+
This first-order ODE can then be solved using any conventional ODE solver - including our `EK1`:
41+
42+
```@example 2
43+
using ProbNumDiffEq, Plots
44+
45+
function Hénon_Heiles(du,u,p,t)
46+
du[1] = -u[3] - 2*u[3]*u[4]
47+
du[2] = u[4]^2 - u[4] -u[3]^2
48+
du[3] = u[1]
49+
du[4] = u[2]
50+
end
51+
u0, du0 = [0.0, 0.1], [0.5, 0.0]
52+
tspan = (0.0, 100.0)
53+
prob = ODEProblem(Hénon_Heiles, [du0; u0], tspan)
54+
sol = solve(prob, EK1());
55+
plot(sol, vars=(3,4)) # where `vars=(3,4)` is used to plot x agains y
56+
```
57+
58+
### Solving the second-order ODE directly
59+
Instead of first transforming the problem, we can also solve it directly as a second-order ODE, by defining it as a `SecondOrderODEProblem`.
60+
61+
!!! note
62+
The `SecondOrderODEProblem` type is not defined in ProbNumDiffEq.jl but is provided by SciMLBase.jl.
63+
For more information, check out the DifferentialEquations.jl documentation on [Dynamical, Hamiltonian and 2nd Order ODE Problems](https://diffeq.sciml.ai/stable/types/dynamical_types/).
64+
65+
```@example 2
66+
function Hénon_Heiles2(ddu,du,u,p,t)
67+
ddu[1] = -u[1] - 2*u[1]*u[2]
68+
ddu[2] = u[2]^2 - u[2] -u[1]^2
69+
end
70+
prob2 = SecondOrderODEProblem(Hénon_Heiles2, du0, u0, tspan)
71+
sol2 = solve(prob2, EK1());
72+
plot(sol2, vars=(3,4))
73+
```
74+
75+
### Benchmark: Solving second order ODEs is _faster_
76+
Solving second-order ODEs is not just a matter of convenience - in fact, SciMLBase's `SecondOrderODEProblem` is neatly designed in such a way that all the classic solvers from OrdinaryDiffEq.jl can handle it by solving the corresponding first-order ODE.
77+
But, transforming the ODE to first order increases the dimensionality of the problem, and comes therefore at increased computational cost; this also motivates [classic specialized solvers for second-order ODEs](https://diffeq.sciml.ai/stable/solvers/dynamical_solve/).
78+
79+
The probablistic numerical solvers from ProbNumDiffEq.jl have the same internal state representation for first and second order ODEs; all that changes is the _measurement model_ [1].
80+
As a result, we can use the `EK1` both for first and second order ODEs, but it automatically specializes on the latter to provide a __2x performance boost__:
81+
```
82+
julia> @btime solve(prob, EK1(order=3), adaptive=false, dt=1e-2);
83+
766.312 ms (400362 allocations: 173.38 MiB)
84+
85+
julia> @btime solve(prob2, EK1(order=4), adaptive=false, dt=1e-2);
86+
388.301 ms (510676 allocations: 102.78 MiB)
87+
```
88+
89+
90+
## Energy preservation
91+
In addition to the ODE given above, we know that the solution of the Hénon-Heiles model has to _preserve energy_ over time.
92+
The total energy can be expressed as the sum of the potential and kinetic energies, given by
93+
```math
94+
\begin{aligned}
95+
\operatorname{PotentialEnergy}(x,y) &= \frac{1}{2} \left( x^2 + y^2 + 2 x^2 y - \frac{2y^3}{3} \right), \\
96+
\operatorname{KineticEnergy}(\dot{x}, \dot{y}) &= \frac{1}{2} \left( \dot{x}^2 + \dot{y}^2 \right).
97+
\end{aligned}
98+
```
99+
100+
In code:
101+
```@example 2
102+
PotentialEnergy(x,y) = 1//2 * (x^2 + y^2 + 2x^2*y - 2//3 * y^3)
103+
KineticEnergy(dx,dy) = 1//2 * (dx^2 + dy^2)
104+
E(dx,dy,x,y) = PotentialEnergy(x,y) + KineticEnergy(dx,dy)
105+
E(u) = E(u...); # convenient shorthand
106+
```
107+
108+
So, let's have a look at how the total energy changes over time when we numerically simulate the Hénon-Heiles model over a long period of time:
109+
Standard solve
110+
```@example 2
111+
longprob = remake(prob2, tspan=(0.0, 1e3))
112+
longsol = solve(longprob, EK1(smooth=false), dense=false)
113+
plot(longsol.t, E.(longsol.u))
114+
```
115+
It visibly loses energy over time, from an initial 0.12967 to a final 0.12899.
116+
Let's fix this to get a physically more meaningful solution.
117+
118+
### Energy preservation with the `ManifoldUpdate` callback
119+
In the language of ODE filters, preserving energy over time amounts to just another measurement model [1].
120+
The most convenient way of updating on this additional zero measurement with ProbNumDiffEq.jl is with the `ManifoldUpdate` callback.
121+
122+
!!! note
123+
The `ManifoldUpdate` callback can be thought of a probabilistic counterpart to the [`ManifoldProjection`](https://diffeq.sciml.ai/stable/features/callback_library/#Manifold-Conservation-and-Projection) callback provided by DiffEqCallbacks.jl.
124+
125+
To do so, first define a (vector-valued) residual function, here chosen to be the difference between the current energy and the initial energy, and build a `ManifoldUpdate` callback
126+
```@example 2
127+
residual(u) = [E(u) - E(du0..., u0...)]
128+
cb = ManifoldUpdate(residual)
129+
```
130+
131+
Then, solve the ODE with this callback
132+
```@example 2
133+
longsol_preserving = solve(longprob, EK1(smooth=false), dense=false, callback=cb)
134+
plot(longsol.t, E.(longsol.u))
135+
plot!(longsol_preserving.t, E.(longsol_preserving.u))
136+
```
137+
138+
Voilà! With the `ManifoldUpdate` callback we could preserve the energy over time and obtain a more truthful probabilistic numerical long-term simulation of the Hénon-Heiles model.
139+
140+
141+
#### References
142+
[1] N. Bosch, F. Tronarp, P. Hennig: **Pick-and-Mix Information Operators for Probabilistic ODE Solvers** (2022)

docs/src/getting_started.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ In this tutorial, we consider a
1111
described by an ODE of the form
1212
```math
1313
\begin{aligned}
14-
\dot{y}_1(t) &= c (y_1 - \frac{y_1^3}{3} + y_2) \\
15-
\dot{y}_2(t) &= -\frac{1}{c} (y_1 - a - b y_2)
14+
\dot{y}_1 &= c (y_1 - \frac{y_1^3}{3} + y_2) \\
15+
\dot{y}_2 &= -\frac{1}{c} (y_1 - a - b y_2)
1616
\end{aligned}
1717
```
1818
on a time span ``t \in [0, T]``, with initial value ``y(0) = y_0``.

src/callbacks.jl

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,28 @@ function manifoldupdate(x, f; maxiters=100, ϵ₁=1e-25, ϵ₂=1e-15)
2424
return Gaussian(m_i_new, C_i_new)
2525
end
2626

27-
function ManifoldUpdate(residualf, args...; maxiters=100, ϵ₁=1e-25, ϵ₂=1e-15, kwargs...)
27+
"""
28+
ManifoldUpdate(residual::Function)
29+
30+
Update the state to satisfy a zero residual function via iterated extended Kalman filtering.
31+
32+
`ManifoldUpdate` returns a `SciMLBase.DiscreteCallback`, which, at each solver step,
33+
performs an iterated extended Kalman filter update to keep the residual measurement to be
34+
zero. Additional arguments and keyword arguments for the `DiscreteCallback` can be passed.
35+
36+
# Additional keyword arguments
37+
- `maxiters::Int`: Maximum number of IEKF iterations.
38+
Setting this to 1 results in a single standard EKF update.
39+
"""
40+
function ManifoldUpdate(
41+
residual::Function,
42+
args...;
43+
maxiters=100,
44+
ϵ₁=1e-25,
45+
ϵ₂=1e-15,
46+
kwargs...,
47+
)
2848
condition(u, t, integ) = true
29-
affect!(integ) = manifoldupdate!(integ, residualf; maxiters=maxiters, ϵ₁=ϵ₁, ϵ₂=ϵ₂)
49+
affect!(integ) = manifoldupdate!(integ, residual; maxiters=maxiters, ϵ₁=ϵ₁, ϵ₂=ϵ₂)
3050
return DiscreteCallback(condition, affect!, args...; kwargs...)
3151
end

0 commit comments

Comments
 (0)