Skip to content

Commit 0654909

Browse files
committed
Document ImperativeEffect and the SymbolicContinousCallback changes
1 parent 54bb95a commit 0654909

File tree

2 files changed

+199
-0
lines changed

2 files changed

+199
-0
lines changed

docs/Project.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ OptimizationOptimJL = "36348300-93cb-4f02-beb5-3c3902f8871e"
1414
OrdinaryDiffEq = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed"
1515
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
1616
SciMLStructures = "53ae85a6-f571-4167-b2af-e1d143709226"
17+
Setfield = "efcf1570-3423-57d1-acb7-fd33fddbac46"
1718
StochasticDiffEq = "789caeaf-c7a9-5a7d-9973-96adeb23e2a0"
1819
SymbolicIndexingInterface = "2efcf032-c050-4f8e-a9bb-153293bab1f5"
1920
SymbolicUtils = "d1185830-fcd6-423d-90d6-eec64667417b"

docs/src/basics/Events.md

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,3 +378,201 @@ sol.ps[c] # sol[c] will error, since `c` is not a timeseries value
378378
```
379379

380380
It can be seen that the timeseries for `c` is not saved.
381+
382+
383+
## [(Experimental) Imperative affects](@id imp_affects)
384+
The `ImperativeAffect` can be used as an alternative to the aforementioned functional affect form. Note
385+
that `ImperativeAffect` is still experimental; to emphasize this, we do not export it and it should be
386+
included as `ModelingToolkit.ImperativeAffect`. It abstracts over how values are written back to the
387+
system, simplifying the definitions and (in the future) allowing assignments back to observed values
388+
by solving the nonlinear reinitialization problem afterwards.
389+
390+
We will use two examples to describe `ImperativeAffect`: a simple heater and a quadrature encoder.
391+
These examples will also demonstrate advanced usage of `ModelingToolkit.SymbolicContinousCallback`,
392+
the low-level interface that the aforementioned tuple form converts into and allows control over the
393+
exact SciMLCallbacks event that is generated for a continous event.
394+
395+
### [Heater](@id heater_events)
396+
Bang-bang control of a heater connected to a leaky plant requires hysteresis in order to prevent control oscillation.
397+
398+
```@example events
399+
@variables temp(t)
400+
params = @parameters furnace_on_threshold=0.5 furnace_off_threshold=0.7 furnace_power=1.0 leakage=0.1 furnace_on(t)::Bool=false
401+
eqs = [
402+
D(temp) ~ furnace_on * furnace_power - temp^2 * leakage
403+
]
404+
```
405+
Our plant is simple. We have a heater that's turned on and off by the clocked parameter `furnace_on`
406+
which adds `furnace_power` forcing to the system when enabled. We then leak heat porportional to `leakage`
407+
as a function of the square of the current temperature.
408+
409+
We need a controller with hysteresis to conol the plant. We wish the furnace to turn on when the temperature
410+
is below `furnace_on_threshold` and off when above `furnace_off_threshold`, while maintaining its current state
411+
in between. To do this, we create two continous callbacks:
412+
```@example events
413+
using Setfield
414+
furnace_disable = ModelingToolkit.SymbolicContinuousCallback(
415+
[temp ~ furnace_off_threshold],
416+
ModelingToolkit.ImperativeAffect(modified = (; furnace_on)) do x, o, i, c
417+
@set! x.furnace_on = false
418+
end)
419+
furnace_enable = ModelingToolkit.SymbolicContinuousCallback(
420+
[temp ~ furnace_on_threshold],
421+
ModelingToolkit.ImperativeAffect(modified = (; furnace_on)) do x, o, i, c
422+
@set! x.furnace_on = true
423+
end)
424+
```
425+
We're using the explicit form of `SymbolicContinuousCallback` here, though
426+
so far we aren't using anything that's not possible with the implicit interface.
427+
You can also write
428+
```julia
429+
[temp ~ furnace_off_threshold] => ModelingToolkit.ImperativeAffect(modified = (; furnace_on)) do x, o, i, c
430+
@set! x.furnace_on = false
431+
end
432+
```
433+
and it would work the same.
434+
435+
The `ImperativeAffect` is the larger change in this example. `ImperativeAffect` has the constructor signature
436+
```julia
437+
ImperativeAffect(f::Function; modified::NamedTuple, observed::NamedTuple, ctx)
438+
```
439+
that accepts the function to call, a named tuple of both the names of and symbolic values representing
440+
values in the system to be modified, a named tuple of the values that are merely observed (that is, used from
441+
the system but not modified), and a context that's passed to the affect function.
442+
443+
In our example, each event merely changes whether the furnace is on or off. Accordingly, we pass a `modified` tuple
444+
`(; furnace_on)` (creating a `NamedTuple` equivalent to `(furnace_on = furnace_on)`). `ImperativeAffect` will then
445+
evaluate this before calling our function to fill out all of the numerical values, then apply them back to the system
446+
once our affect function returns. Furthermore, it will check that it is possible to do this assignment.
447+
448+
The function given to `ImperativeAffect` needs to have one of four signatures, checked in this order:
449+
* `f(modified::NamedTuple, observed::NamedTuple, ctx, integrator)::NamedTuple` if the function needs the low-level integrator,
450+
* `f(modified::NamedTuple, observed::NamedTuple, ctx)::NamedTuple` if the function needs the user-defined context,
451+
* `f(modified::NamedTuple, observed::NamedTuple)::NamedTuple` if the function also reads observed values from the system,
452+
* `f(modified::NamedTuple)::NamedTuple` if the function only writes values (unknowns or parameters) to the system.
453+
The `do` block in the example implicitly constructs said function inline. For exposition, we use the full version (e.g. `x, o, i, c`) but this could be simplified to merely `x`.
454+
455+
The function `f` will be called with `observed` and `modified` `NamedTuple`s that are derived from their respective `NamedTuple` definitions.
456+
In our example, if `furnace_on` is `false`, then the value of the `x` that's passed in as `modified` will be `(furnace_on = false)`.
457+
The modified values should be passed out in the same format: to set `furnace_on` to `true` we need to return a tuple `(furnace_on = true)`.
458+
We use Setfield to do this in the example, recreating the result tuple before returning it.
459+
460+
Accordingly, we can now interpret the `ImperativeAffect` definitions to mean that when `temp = furnace_off_threshold` we
461+
will write `furnace_on = false` back to the system, and when `temp = furnace_on_threshold` we will write `furnace_on = true` back
462+
to the system.
463+
464+
```@example events
465+
@named sys = ODESystem(
466+
eqs, t, [temp], params; continuous_events = [furnace_disable, furnace_enable])
467+
ss = structural_simplify(sys)
468+
prob = ODEProblem(ss, [temp => 0.0, furnace_on => true], (0.0, 10.0))
469+
sol = solve(prob, Tsit5())
470+
plot(sol)
471+
hline!([sol.ps[furnace_off_threshold], sol.ps[furnace_on_threshold]], l = (:black, 1), primary = false)
472+
```
473+
474+
Here we see exactly the desired hysteresis. The heater starts on until the temperature hits
475+
`furnace_off_threshold`. The temperature then bleeds away until `furnace_on_threshold` at which
476+
point the furnace turns on again until `furnace_off_threshold` and so on and so forth. The controller
477+
is effectively regulating the temperature of the plant.
478+
479+
### [Quadrature Encoder](@id quadrature)
480+
For a more complex application we'll look at modeling a quadrature encoder attached to a shaft spinning at a constant speed.
481+
Traditionally, a quadrature encoder is built out of a code wheel that interrupts the sensors at constant intervals and two sensors slightly out of phase with one another.
482+
A state machine can take the pattern of pulses produced by the two sensors and determine the number of steps that the shaft has spun. The state machine takes the new value
483+
from each sensor and the old values and decodes them into the direction that the wheel has spun in this step.
484+
485+
```@example events
486+
@variables theta(t) omega(t)
487+
params = @parameters qA=0 qB=0 hA=0 hB=0 cnt::Int=0
488+
eqs = [D(theta) ~ omega
489+
omega ~ 1.0]
490+
```
491+
Our continous-time system is extremely simple. We have two states, `theta` for the angle of the shaft
492+
and `omega` for the rate at which it's spinning. We then have parameters for the state machine `qA, qB, hA, hB`
493+
and a step count `cnt`.
494+
495+
We'll then implement the decoder as a simple Julia function.
496+
```@example events
497+
function decoder(oldA, oldB, newA, newB)
498+
state = (oldA, oldB, newA, newB)
499+
if state == (0, 0, 1, 0) || state == (1, 0, 1, 1) || state == (1, 1, 0, 1) ||
500+
state == (0, 1, 0, 0)
501+
return 1
502+
elseif state == (0, 0, 0, 1) || state == (0, 1, 1, 1) || state == (1, 1, 1, 0) ||
503+
state == (1, 0, 0, 0)
504+
return -1
505+
elseif state == (0, 0, 0, 0) || state == (0, 1, 0, 1) || state == (1, 0, 1, 0) ||
506+
state == (1, 1, 1, 1)
507+
return 0
508+
else
509+
return 0 # err is interpreted as no movement
510+
end
511+
end
512+
```
513+
Based on the current and old state, this function will return 1 if the wheel spun in the positive direction,
514+
-1 if in the negative, and 0 otherwise.
515+
516+
The encoder state advances when the occlusion begins or ends. We model the
517+
code wheel as simply detecting when `cos(100*theta)` is 0; if we're at a positive
518+
edge of the 0 crossing, then we interpret that as occlusion (so the discrete `qA` goes to 1). Otherwise, if `cos` is
519+
going negative, we interpret that as lack of occlusion (so the discrete goes to 0). The decoder function is
520+
then invoked to update the count with this new information.
521+
522+
We can implement this in one of two ways: using edge sign detection or right root finding. For exposition, we
523+
will implement each sensor differently.
524+
525+
For sensor A, we're using the edge detction method. By providing a different affect to `SymbolicContinuousCallback`'s
526+
`affect_neg` argument, we can specify different behaviour for the negative crossing vs. the positive crossing of the root.
527+
In our encoder, we interpret this as occlusion or nonocclusion of the sensor, update the internal state, and tick the decoder.
528+
```@example events
529+
qAevt = ModelingToolkit.SymbolicContinuousCallback([cos(100 * theta) ~ 0],
530+
ModelingToolkit.ImperativeAffect((; qA, hA, hB, cnt), (; qB)) do x, o, i, c
531+
@set! x.hA = x.qA
532+
@set! x.hB = o.qB
533+
@set! x.qA = 1
534+
@set! x.cnt += decoder(x.hA, x.hB, x.qA, o.qB)
535+
x
536+
end,
537+
affect_neg = ModelingToolkit.ImperativeAffect(
538+
(; qA, hA, hB, cnt), (; qB)) do x, o, c, i
539+
@set! x.hA = x.qA
540+
@set! x.hB = o.qB
541+
@set! x.qA = 0
542+
@set! x.cnt += decoder(x.hA, x.hB, x.qA, o.qB)
543+
x
544+
end)
545+
```
546+
547+
The other way we can implement a sensor is by changing the root find.
548+
Normally, we use left root finding; the affect will be invoked instantaneously before
549+
the root is crossed. This makes it trickier to figure out what the new state is.
550+
Instead, we can use right root finding:
551+
552+
```@example events
553+
qBevt = ModelingToolkit.SymbolicContinuousCallback([cos(100 * theta - π / 2) ~ 0],
554+
ModelingToolkit.ImperativeAffect((; qB, hA, hB, cnt), (; qA, theta)) do x, o, i, c
555+
@set! x.hA = o.qA
556+
@set! x.hB = x.qB
557+
@set! x.qB = clamp(sign(cos(100 * o.theta - π / 2)), 0.0, 1.0)
558+
@set! x.cnt += decoder(x.hA, x.hB, o.qA, x.qB)
559+
x
560+
end; rootfind = SciMLBase.RightRootFind)
561+
```
562+
Here, sensor B is located `π / 2` behind sensor A in angular space, so we're adjusting our
563+
trigger function accordingly. We here ask for right root finding on the callback, so we know
564+
that the value of said function will have the "new" sign rather than the old one. Thus, we can
565+
determine the new state of the sensor from the sign of the indicator function evaluated at the
566+
affect activation point, with -1 mapped to 0.
567+
568+
We can now simulate the encoder.
569+
```@example events
570+
@named sys = ODESystem(
571+
eqs, t, [theta, omega], params; continuous_events = [qAevt, qBevt])
572+
ss = structural_simplify(sys)
573+
prob = ODEProblem(ss, [theta => 0.0], (0.0, pi))
574+
sol = solve(prob, Tsit5(); dtmax = 0.01)
575+
sol.ps[cnt]
576+
```
577+
`cos(100*theta)` will have 200 crossings in the half rotation we've gone through, so the encoder would notionally count 200 steps.
578+
Our encoder counts 198 steps (it loses one step to initialization and one step due to the final state falling squarely on an edge).

0 commit comments

Comments
 (0)