I've got a problem where WhenEvent
successfully detects an event, but then performs only some of the actions.
In this minimal example, x[t]
can not exceed 1
(driven by If
). If x[t]
equals 1
in the time window from 0.1
to 0.9
, it should be reduced to 0.2
, toggle a DiscreteVariable, and print the time.
sol = NDSolve[{x'[t] == If[x[t] < 1, 4 x[t], 0],
WhenEvent[0.1 < t < 0.9 && x[t] >= 1,
{Print[t], x[t] -> 0.2, dv[t] -> 1 - dv[t]}],
x[0] == 0.9, dv[0] == 0}, {x, dv}, {t, 0, 1},
DiscreteVariables -> {dv}][[1]];
(* 0.1 *)
(* 0.502359 *)
The two printed times show that the WhenEvent
was correctly triggered twice -- once when the time window opens at t == 0.1
and another time later. But plotting x[t]
shows that it was not correctly reduced to 0.2
at the second event at t = 0.502359
.
Plot[Evaluate[x[t] /. sol], {t, 0, 1}]
However the DiscreteVariable
dv[t]
was successfully toggled twice:
Plot[Evaluate[dv[t] /. sol], {t, 0, 1}]
This seems to be an unfortunate interaction with the If
statement, because changing x'[t] == 4 x[t]
causes it to work fine.
Bug or just my improper use of WhenEvent
? Any ideas for a workaround?