# Using callback functions via CallbackSet

Hi everyone,

I’m trying to add two DiscreteCallbacks to my integrator using CallbackSet. Each of them seem to work when the other one is not present, but the first one does not work when the second one is present. This is my code:

using DifferentialEquations
using DelimitedFiles

function Helmholtz(du,u,p,t)
d=0.1;
α=6.0;
β=1.0;

du[1] = u[2]
du[2] = -d *u[2]-α* u[1]+β*u[1].^2
end

function σ_Helmholtz(du,u,p,t)
du[1] = 0.5
du[2] = 0.5
end

mat_res=

for n=1:5
u0 = [5.0,0.0]
tspan=(0.0,300.0)
t_int=0.0:0.01:300.0;
#We build the problem:
prob_sde_Helmholtz = SDEProblem(Helmholtz,σ_Helmholtz,u0,tspan)

#TO STOP THE SIMULATION WHEN THE SOLUTION GOES BEYOND 100
condition(u,t,integrator) = u[1]>100 #if x hits 100
affect!(integrator) = terminate!(integrator) #the computation stops
cb1 = DiscreteCallback(condition,affect!, save_positions=(true,true))

# RESETTING TO A GIVEN POSITION
t_reset = [20.0 40.0 60.0];
condition(u,t,integrator) = t ∈ t_reset && (u[1] < 6.0)
affect!(integrator) = integrator.u[1] =5.0
cb2 = DiscreteCallback(condition,affect!,save_positions=(true,true))

a=CallbackSet(cb1,cb2);

sol = solve(prob_sde_Helmholtz, SRIW1(),callback=a,tstops=t_reset, reltol=1e-3,abstol=1e-6, maxiters=1e10)

sol_int = sol(t_int);
sol_iter=[sol_int[1,:] sol_int[2,:]];

push!(mat_res,sol_iter’)

@show n

end

mat_res=hcat(mat_res’…)

Any idea on how to fix it?

1 Like

You used the same function, so you redefined the function. Just use two different function names.

1 Like