Callbacks within CallbackSet interfering with each other

Hi there,

I’m trying to use callbacks to create pulses to two identical systems ran through the same set of differential equations. It seems like putting the two Callbacks together results in the Callbacks somehow interfering with each other. I am not sure why… Maybe I am doing something wrong without realizing it…

Here is a (somewhat) minimal working example:

Essentially, every time that the function sin(u[1]/2) hits 0, a pulse of a magnitude of 1 is created in u[2]. Similarly, every time that the function sin(u[3]/2) hits 0, a pulse of a magnitude of 1 is created in u[4]. I’m plotting the cosines of u[1] and u[3] to illustrate the timing of pulses.

using Plots, DifferentialEquations

# System of differential equations
function f(du, u, p, t)
    du[1] = 2*π*sqrt(u[2]) 
    du[2] = -u[2]
    du[3] = 2*π*sqrt(u[4]) 
    du[4] = -u[4]
end

# Parameters
p = []

# Initial Conditions
u0 = [0.00, 1.5, 0.0, 1.5]

# Callback 1
condition1(u,t,integrator) = sin(u[1]/2)
affect1!(integrator) = integrator.u[2] += 1
cb1 = ContinuousCallback(condition1, affect1!, save_positions=(false,false))

# Callback 2
condition2(u,t,integrator) = sin(u[3]/2)
affect2!(integrator) = integrator.u[4] += 1
cb2 = ContinuousCallback(condition2, affect2!, save_positions=(false,false))

# All Callbacks together
cbs = CallbackSet(cb1, cb2)

# Define problem
prob = ODEProblem(f, u0, (0, 20), p, callback = cbs)

# Solve problem
sol = solve(prob, saveat = 0.01)
tr = cat(sol.u..., dims = 2)

# Plotting
plot()
plot!(sol.t, cos.(tr[1, :]))
plot!(sol.t, (tr[2, :]))
plot!(sol.t, cos.(tr[3, :]))
plot!(sol.t, (tr[4, :]))

When running this, the solution kind of blows up and the two pairs of solutions that should be identical to each other start differing.

Something peculiar is that, when changing the initial conditions to u0 = [0.001, 1.5, 0.0, 1.5], for instance, the weird behavior stops.

Furthermore, when running u[1]-u[2] separately from u[3]-u[4] (using two different systems altogether) this behavior stops. I’m thinking to there is a weird interaction in the CallbackSet function… but I’m not too sure why and how to fix it.

Thanks!

Can you open an issue?

Sounds good! Just did