DifferentialEquations.jl -- store intermediate variables?

Is there a way to store intermediate variables in ODEs using the DifferentialEquations package?

MWE:

using DifferentialEquations
#
function sys!(dx,x,p,t)
    r = 1
    u = 5*(r-x[1])
    dx[1] = 0.1*(u-x[1])
end
#
x0 = [-1.0]
tspan = (0.0,10.0)
prob = ODEProblem(sys!,x0,tspan)
sol = solve(prob)
#
plot(sol)

So… I’d like to be able to store u (and possibly also r).

  • Is this possible? (I know it is possible in ModelingToolkit by converting the DAE to an ODE; I’ll test my problem with ModelingToolkit later – it is rather big/ugly, so I’d prefer to handle it directly in DifferentialEquations first.)
  • If possible, how can I specify the variable in the plot(sol) command? (I know how to do that if only states are stored.)

Suggestions are appreciated!

It’s actually really ugly to do optimally in DifferentialEquations.jl because you don’t want to store them but instead lazily instantiate them to limit the computational cost :sweat_smile: . You can use SavingCallback or something if you want to. If you think you’re redoing computations for the save, well you’re not actually recomputing anything in most common cases because you generally don’t save at steps.

1 Like

Hm… could I store the algebraic variables in a pure integrator state, and — once solved — plot the derivative of this integral state?

Something like:

using DifferentialEquations
#
function sys!(dx,x,p,t)
    r = 1
    u = 5*(r-x[1])
    dx[1] = 0.1*(u-x[1])
    dx[2] = u
end
#
r = 1
x0 = [-1.0, 5*(r+1.0)]
tspan = (0.0,10.0)
prob = ODEProblem(sys!,x0,tspan)
sol = solve(prob)
#
plot(sol,vars=(0,1))  # gives "real" state x
plot(sol.t,Array(sol(sol.t,Val{1}))[2,:])  # gives u
  • Is there a simpler way to plot the derivative of variable 2 (u)?
  • Are there downsides to this procedure, compared to computing u in a post processing step?

If you solve it as a DAE then that derivative would be calculated