ModelingToolkit.jl icon indicating copy to clipboard operation
ModelingToolkit.jl copied to clipboard

Initial and final affect for timed periodic event in ModelingToolkit

Open jmaedler opened this issue 1 year ago • 0 comments

Question❓

Hi everyone,

I am working on an adapter for virtual commissioning using ModelingToolkit.jl. More specifically, I use discrete callbacks (timed --> periodic) to read inputs from and write output to a soft-controller. Is there a way to set the initial_affect and the final_affect arguments from DiffEqCallbacks.jl using ModelingToolkit.jl? Here is my MWE:

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

function affect!(integ, u, p, ctx)
    println("Time: $(integ.t)")    
end

@mtkmodel SimpleSystem begin
    @parameters begin
        m = 1.0
    end
    @variables begin
        y(t) = 0.0
    end
    @equations begin
        D(y) ~ m
    end
    @discrete_events begin
        1 => (affect!,[],[],[],nothing)
    end
end

@mtkbuild sys = SimpleSystem()
prob = ODEProblem(sys, Pair[], (0, 10.0))
sol = solve(prob)

If you run this code the event will not be triggered for t = 0.0 nor 10.0. If you explicitly add additional events like this:

    @discrete_events begin
        [0,10] => (affect!,[],[],[],nothing)
        1 => (affect!,[],[],[],nothing)
    end

both events will be called twise. I guess this is related to the solver starting at some $\Delta t$ in the first case (and thus overstepping 0.0) and being forced to start with 0.0 in the second case. Is there currently a way arround this behavior in ModelingToolkit.jl?

jmaedler avatar Sep 25 '24 09:09 jmaedler