Search code examples
juliavisualizationodeplots.jldifferentialequations.jl

Animating the solution to an ODE in Julia


I have a julia code:

using DifferentialEquations
using Plots
using ParameterizedFunctions
plotly()
lorenz = @ode_def Lorenz begin
  dx = σ*(y-x)
  dy = ρ*x-y-x*z
  dz = x*y-β*z
end σ = 10. β = 8./3. ρ => 28.
u0 = [1., 5., 10.]
tspan = (0., 2.)
prob = ODEProblem(lorenz, u0, tspan)
sol = solve(prob,save_timeseries=true)
plot(sol,vars=(:x,:y,:z))

Which results in: next plot
How can i animate this plot such that it would work either from REPL and jupyter?


Solution

  • For DifferentialEquations.jl, there is a built-in animation function which can handle this. Unfortunately, I realized that I forgot to put it in the last release. When it's released, the syntax will be (simplifying your code a little bit):

    using DifferentialEquations
    using Plots
    using ParameterizedFunctions
    pyplot()
    lorenz = @ode_def Lorenz begin
      dx = σ*(y-x)
      dy = ρ*x-y-x*z
      dz = x*y-β*z
    end σ = 10. β = 8./3. ρ => 28.
    u0 = [1., 5., 10.]
    tspan = (0., 2.)
    prob = ODEProblem(lorenz, u0, tspan)
    sol = solve(prob)
    animate(sol,vars=(:x,:y,:z),xlims=(-20,20),ylims=(-15,20),zlims=(10,40))
    

    A few things: animate can take any of the normal plot commands. However, it at each frame it plots from the beginning to the ith step, which means you may need to manually set the axis to make them not shift around. Another thing to note is that I switched backends to PyPlot. The Plotly backend cannot do animations. Maybe PlotlyJS can? The animation function is documented here.

    Using that command will be by far the easiest way, but you can do it "more manually" using the integrator interface. Essentially, you can just plot each step interval using this and get to the same place in the end. You'd have to use Plots.jl's animation interface.

    Edit: If you Pkg.update() this should now work.