Implementation of custom block in Modeling Toolkit

Hello,
You’re absolutely right — yesterday I wrote the question quickly and forgot to attach the code I had tried. Luckily, after thinking about it more this morning, I found a way to implement this functionality. I’m attaching the code here in case anyone needs to implement something similar.

@mtkmodel ResponseSystemSub begin
    @parameters begin

        delay = 3.0  # Delay of system

    end

	@components begin 

		output = RealOutput()
		input = RealInput()

	end
    
    @variables begin

        timer(t) = 0.0    # Timer
        phase(t)  = 0.0 # Internal state

    end
    
    @equations begin

        # Timer increases only if phase==2
        D(timer) ~ ifelse(phase == 2,1.0,0.0)
        
        # Phase rate of change is 0, this variable will only be updated through discrete events!
        D(phase) ~ 0

        # output logic
    
	 output.u ~ ifelse(phase==0,0.0,ifelse(phase==1,1.0,2.0))

	end

	@discrete_events begin

		(input.u - 0.5 > 0) & (phase == 0) => [phase ~ 1.0, timer ~ 0.0]
		(input.u - 0.5 < 0) & (phase == 1) => [phase ~ 2.0, timer ~ 0.0]
		(timer - delay > 0) & (phase == 2) => [phase ~ 0.0, timer ~ 0.0]
		
	end

end

There are other causal implementations of this kind of system, such as the one found in IEC 61400-27, however, several auxiliary functions must be implemented. This solution works and is quite simple. If anyone finds another way to implement the same logic or finds a way to improve the model I will be glad to discuss it!

Thanks.

2 Likes