3

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?

Chris Rackauckas
  • 18,645
  • 3
  • 50
  • 81
93a
  • 106
  • 5

1 Answers1

5

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.

Chris Rackauckas
  • 18,645
  • 3
  • 50
  • 81
  • would you care to explain the difference (pros/cons) between ``DifferentialEquations.jl`` built-in ``animate()`` vs ``@animate`` and ``@gif``. The latter are documented reasonably well in http://docs.juliaplots.org/latest/ and http://docs.juliaplots.org/latest/animations/. The syntax is different. And would you briefly describe how to save the gif? Do you just add ``filename = "mygif.gif"`` inside the ``animate()`` function? Thanks! – PatrickT Apr 10 '21 at 06:14
  • Also, some of the urls in your answer are no longer working. – PatrickT Apr 10 '21 at 06:15
  • 1
    fixed thanks. The DiffEq one just predated some of the Plots.jl things, which may be a bit more flexible these days. – Chris Rackauckas Apr 10 '21 at 10:56