diff --git a/docs/src/basics/Events.md b/docs/src/basics/Events.md index 33ce84d31e..9b6da30114 100644 --- a/docs/src/basics/Events.md +++ b/docs/src/basics/Events.md @@ -336,3 +336,45 @@ one must still use a vector ```julia discrete_events = [[2.0] => [v ~ -v]] ``` + +## Saving discrete values + +Time-dependent parameters which are updated in callbacks are termed as discrete variables. +ModelingToolkit enables automatically saving the timeseries of these discrete variables, +and indexing the solution object to obtain the saved timeseries. Consider the following +example: + +```@example events +@variables x(t) +@parameters c(t) + +@mtkbuild sys = ODESystem( + D(x) ~ c * cos(x), t, [x], [c]; discrete_events = [[t ~ 1.0] => [c ~ c + 1]]) + +prob = ODEProblem(sys, [x => 0.0], (0.0, 2pi), [c => 1.0]) +sol = solve(prob, Tsit5()) +sol[c] +``` + +The solution object can also be interpolated with the discrete variables + +```@example events +sol([1.0, 2.0], idxs = [c, c * cos(x)]) +``` + +Note that only time-dependent parameters will be saved. If we repeat the above example with +this change: + +```@example events +@variables x(t) +@parameters c + +@mtkbuild sys = ODESystem( + D(x) ~ c * cos(x), t, [x], [c]; discrete_events = [[t ~ 1.0] => [c ~ c + 1]]) + +prob = ODEProblem(sys, [x => 0.0], (0.0, 2pi), [c => 1.0]) +sol = solve(prob, Tsit5()) +sol[c] +``` + +It can be seen that the timeseries for `c` is not saved.