Terminate simulation on event using ModelingToolkit

Hi all,

First of all, thank you all for your immense efforts on Julia and ModelingToolkit. I’ve been using it for over 2 years and I keep being impressed with the power and capabilities.

I’m trying to terminate an MTK simulation using an event description.

I have a minimal example below:

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D

function affect!(mod,obs,ctx,int)
    ModelingToolkit.terminate!(int)
end

function FOL(;name)
    @parameters begin
        τ = 3.0 # parameters
    end
    @variables begin
        x(t) = 0.0 # dependent variables
    end
    eq=[
        D(x) ~ (1 - x) / τ
    ]

    events = [x ~ 0.6]=>(affect!,(;))

    return System(eq, t; name=name, continuous_events=events)
end

using OrdinaryDiffEq
@mtkbuild fol = FOL()
prob = ODEProblem(fol, [], (0.0, 10.0))
sol = solve(prob)

using Plots
plot(sol)

I get the following error. The full description did not fit, so I just pasted the summary.

MethodError: no method matching _generated_writeback(::OrdinaryDiffEqCore.ODEIntegrator{}, ::@NamedTuple{}, ::Vector{Float64})

Closest candidates are:
  _generated_writeback(::Any, ::NamedTuple{NS1}, !Matched::NamedTuple{NS2}) where {NS1, NS2}
   @ ModelingToolkit ~/.julia/packages/ModelingToolkit/80wTI/src/systems/imperative_affect.jl:148

I am running Julia v1.10.10 and MTK v10.26.0.

The problem is very trivial so I am surely missing something obvious…

Kind regards,

Koen Linders

Open an issue. I’m surprised that didn’t just work but we haven’t tested using terminations yet.

Thank you for the response Chris! I’ll make an issue :+1:

Actually it was a small easy bug

Just for good bookkeeping: The issue was solved by @cryptic.ax on Github.

The solution is returning an empty NamedTuple like so

function affect!(mod,obs,ctx,int)
    ModelingToolkit.terminate!(int)

    return (;)
end

Thank you all for your help