A state machine is a System whose equations are all initial_state()
and transition() statements and whose subsystems are its states: systems
of clocked discrete equations (with ShiftIndex()). initial_state(s)
names the state active at the first tick and transition(from, to, cond)
moves from state from to state to when the condition cond holds.
With immediate = TRUE the transition fires at the tick where cond
holds, before the equations of from are evaluated; otherwise it fires at
the next tick. reset = TRUE restarts the target state from the start
values of its variables. Among the transitions leaving a state the one
with the smallest priority wins.
Usage
initial_state(s)
transition(
from,
to,
cond,
immediate = TRUE,
reset = TRUE,
synchronize = FALSE,
priority = 1L
)
activeState(s)
entry(s = NULL)
ticksInState(s = NULL)
timeInState(s = NULL)Value
initial_state() and transition() return state machine
equations; the other functions return symbolic expressions.
Details
In the equations of a state, and in transition conditions,
ticksInState() is the number of ticks since the state was entered
(1 at the entry tick), timeInState() the time since then, entry() is
true at the entry tick and activeState(s) is true when state s is
active. With a state argument they refer to that state; in a transition
condition, without one, to the source state.
ModelingToolkit 11 extracts state machines and infers their clocks, but
simulating them needs an external compiler. mtkcompile() compiles each
machine of a hybrid model into a periodic callback with the semantics of
the Modelica specification (chapter 17); this is an extension of
modelcompR. Hierarchical machines and synchronize = TRUE are not
supported.
Examples
t <- t_nounits; D <- D_nounits
k <- ShiftIndex(Clock(1))
x <- GlobalScope(Variable("x", t, default = 0))
up <- System(list(k(x) ~ (k - 1)(x) + 1), t, list(x), list(), name = "up")
down <- System(list(k(x) ~ (k - 1)(x) - 1), t, list(x), list(), name = "down")
sm <- System(list(initial_state(up), transition(up, down, ticksInState() >= 3),
transition(down, up, ticksInState() >= 3)), t, systems = list(up, down), name = "sm")
z <- Variable("z", t, default = 0)
model <- System(list(D(z) ~ Hold(x)), t, systems = list(sm), name = "model")
sol <- solve(ODEProblem(mtkcompile(model), list(), c(0, 8)))
sol(seq(0.5, 7.5, by = 1), idxs = x)
#> [1] 1 2 -1 -2 1 2 -1 -2