How to retrieve the time of events in a modeling toolkit solution?

I have a MTK system with a @continuous_events block. Is there a way to retrieve when these events are triggered somewhere in the solution ? I could not find anything about this in Event Handling and Callback Functions · ModelingToolkit.jl.

It’s not necessarily saved unless you add that to the affect!

Ok, but where should it be specified ? For instance on the bouncing ball example from the documentation

@variables x(t)=1 v(t)=0

root_eqs = [x ~ 0]  # the event happens at the ground x(t) = 0
affect = [v ~ -Pre(v)] # the effect is that the velocity changes sign

@mtkcompile ball = System(
    [D(x) ~ v
     D(v) ~ -9.8], t; continuous_events = root_eqs => affect) # equation => affect

tspan = (0.0, 5.0)
prob = ODEProblem(ball, Pair[], tspan)
sol = solve(prob, Tsit5())
@assert 0 <= minimum(sol[x]) <= 1e-10 # the ball never went through the floor but got very close
plot(sol)

Do you mean some option should be added to [v~ -Pre(v), <some saving option ?>] ?
Or do you mean that an additional discrete parameter should be added to the system to store the time of these events, or something else ?

If you use a FunctionalAffect then you can just push!(times,t)

So far, I have detected these events by finding double occurrences of a time step in sol.t which seems to work fine, but it is quite fragile I believe. Also it does not allow to keep track of which event or system in a complex model triggered the event.

As there is apparently no built-in way to store these events, do you think this could be done at the subsystem level so that it could be indexed in the solution later on ? That could at least allow to sort the events location per system, and even per event if one discrete is defined per event, as presented in Event Handling and Callback Functions · ModelingToolkit.jl

We can add it in the future.

1 Like

You could also add a variable, set its derivative to zero in the equations and updating it to the current time in the callbacks.