Can I use if statements in ParameterisedFunctions.jl? Is there a work around?

I am trying to check weather my Differential Equation implemented using DifferentialEquation.jl matches the results obtained in Matlab. I learnt I could do this by implementing the same differential equation using MATLABDiffEq.jl and ParameterisedFunctions.jl. My code contains several if-statements that look something like this:

function diffeq(du,u,p,t)
    if u[1]>0
        du[1]= u[1]+10
    end    
end
u0=[0.0,1.0]
tspan= (0,1)
prob= ODEProblem(diffeq,u0,tspan,p)
sol= solve(prob, MATLABDiffEq.ode15s())

However, when I debug I notice that the u0 passed does not contain number but instead it is something like this.

I believe this is due to the metaprogramming capabilities of Julia. Because of which I get a type error in the if-statement

Blockquote TypeError: non-boolean (Num) used in boolean context

How do I go about this and implement my quite complex diff equation as a parameterised function?

Duplicate with a solution posted:

Quick question on this topic @ChrisRackauckas. The posted solution above uses functionality from the IfElse.jl package, though it seems like the package itself is archived? Is IfElse going to be deprecated?

In general, if I have an ODE problem that requires if statements in each update step depending on the state of the integrator, it seems one could either (i) use the IfElse functionality as listed above, or (ii) use a DiscreteCallback . Is there any reason to use one over the other in terms of performance?

Yes, IIRC it’s Julia v1.7 that ifelse in Base Julia works just fine (the compiler was patched so that Core.ifelse is allowed to dispatch), so after that IfElse.ifelse is the same as Julia’s core ifelse. Therefore, just use Base.ifelse like you would in any other Julia code and it’ll work. IfElse.jl is just a relic of a past now.

If you have discontinuities you normally want to declare them with a callback in order to have better convergence. Technically the ODE solver is okay, because adaptivity will adjust dt around the discontinuity to be very small which will then help it hit a low amount of error, but of course that can impact performance.

1 Like