Diffeq trigger callback from inside f

I am looking to improve the performance of my ODE. Since the expensive operation g(u,p) (which involves inverting matrices) has to be done anyway to calculate du/dt, I’d like not to have to reevaluate it at every step for the callback condition too. Is there a clean way of triggering the callback from f? Maybe by storing additional values?

function f(du,u,p,t)
    x = g(u,p)
    du = h(u,x,p)
end

function condition(u,t,integrator)
   x = g(u,p)
   somecheck(x)
end
affect!(integrator) = ...
cb = Callback(condition, affect!)

u0 = ...
prob = ODEProblem(f, u0, cb, tspan, pars)
solve(prob)

Modify a parameter and check in the callback if that parameter is true?

1 Like

Yup that’s probably a good approach. Thanks!