-
-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathcallbacks.jl
More file actions
1660 lines (1456 loc) · 64.9 KB
/
callbacks.jl
File metadata and controls
1660 lines (1456 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
abstract type AbstractCallback end
function has_functional_affect(cb)
return affects(cb) isa ImperativeAffect
end
struct SymbolicAffect
affect::Vector{Equation}
discrete_parameters::Vector{SymbolicT}
end
@noinline function depwarn_alg_eqs()
return Base.depwarn(
"""
The `alg_eqs` keyword for callback affects is deprecated. The equations can \
simply be passed as equations of the affect.
""",
:callback_alg_eqs
)
end
function SymbolicAffect(
affect::Vector{Equation}; alg_eqs = Equation[],
discrete_parameters = SymbolicT[], kwargs...
)
if !isempty(alg_eqs)
depwarn_alg_eqs()
append!(affect, alg_eqs)
end
if symbolic_type(discrete_parameters) !== NotSymbolic()
discrete_parameters = SymbolicT[unwrap(discrete_parameters)]
elseif !(discrete_parameters isa Vector{SymbolicT})
_discs = SymbolicT[]
for p in discrete_parameters
push!(_discs, unwrap(p))
end
discrete_parameters = _discs
end
return SymbolicAffect(affect, discrete_parameters)
end
function SymbolicAffect(affect::SymbolicAffect; kwargs...)
return SymbolicAffect(
affect.affect; discrete_parameters = affect.discrete_parameters, kwargs...
)
end
SymbolicAffect(affect; kwargs...) = make_affect(affect; kwargs...)
"""
AssignmentAffect(assignments)
A special shorthand affect usable in symbolic callbacks. `assignments` is an array of
`Pair`s, where the LHS of each pair is the variable/discrete to assign and the RHS is
the value to assign it. The RHS is evaluated using the values of variables and parameters
before the callback. In other words, it is evaluated as if the entire expression is enclosed
in [`Pre`](@ref). In addition, if the LHS is created using `@discretes` it will automatically
be added to the list of `discrete_parameters` typically provided when manually creating
events.
"""
function AssignmentAffect(affect::AbstractArray{T}) where {T <: Pair}
discrete_parameters = SymbolicT[]
new_affect = Equation[]
for (lhs, rhs) in affect
lhs = unwrap(lhs)::SymbolicT
rhs = unwrap(rhs)
push!(new_affect, lhs ~ Pre(rhs))
if first(getmetadata(lhs, Symbolics.VariableSource)::NTuple{2, Symbol}) == :discretes
push!(discrete_parameters, lhs)
end
end
return SymbolicAffect(new_affect; discrete_parameters)
end
function SymbolicAffect(affect::Vector; discrete_parameters = SymbolicT[], kwargs...)
assigns = Pair{SymbolicT, SymbolicT}[]
eqs = Equation[]
for aff in affect
if aff isa Equation
push!(eqs, aff)
elseif aff isa Pair
push!(assigns, aff)
else
throw(
ArgumentError(
lazy"""
Unrecognized affect format $aff. Affects must be equations or `Pair`s.
"""
)
)
end
end
aff1 = SymbolicAffect(eqs; discrete_parameters, kwargs...)
aff2 = AssignmentAffect(assigns; kwargs...)
return SymbolicAffect([aff1.affect; aff2.affect], [aff1.discrete_parameters; aff2.discrete_parameters])
end
function (s::SymbolicUtils.Substituter)(aff::SymbolicAffect)
return SymbolicAffect(s(aff.affect), s(aff.discrete_parameters))
end
discretes(affect::SymbolicAffect) = affect.discrete_parameters
struct AffectSystem
"""The internal implicit discrete system whose equations are solved to obtain values after the affect."""
system::AbstractSystem
"""Unknowns of the parent ODESystem whose values are modified or accessed by the affect."""
unknowns::Vector{SymbolicT}
"""Parameters of the parent ODESystem whose values are accessed by the affect."""
parameters::Vector{SymbolicT}
"""Parameters of the parent ODESystem whose values are modified by the affect."""
discretes::Vector{SymbolicT}
end
function (s::SymbolicUtils.Substituter)(aff::AffectSystem)
sys = aff.system
@set! sys.eqs = s(get_eqs(sys))
@set! sys.parameter_dependencies = (get_parameter_dependencies(sys))
@set! sys.defaults = Dict([k => s(v) for (k, v) in defaults(sys)])
@set! sys.guesses = Dict([k => s(v) for (k, v) in guesses(sys)])
@set! sys.unknowns = s(get_unknowns(sys))
@set! sys.ps = s(get_ps(sys))
return AffectSystem(sys, s(aff.unknowns), s(aff.parameters), s(aff.discretes))
end
function AffectSystem(spec::SymbolicAffect; iv = nothing, alg_eqs = Equation[], kwargs...)
affect = spec.affect
if !isempty(alg_eqs)
depwarn_alg_eqs()
affect = [affect; alg_eqs]
end
return AffectSystem(affect; iv, discrete_parameters = spec.discrete_parameters, kwargs...)
end
function AffectSystem(
affect::Vector{Equation}; discrete_parameters = SymbolicT[],
iv = nothing, extra_eqs = Equation[], kwargs...
)
isempty(affect) && return nothing
if isnothing(iv)
iv = t_nounits
@warn "No independent variable specified. Defaulting to t_nounits."
end
affect = [affect; extra_eqs]
discrete_parameters = SymbolicAffect(affect; discrete_parameters).discrete_parameters
for p in discrete_parameters
SU.query(isequal(unwrap(iv)), unwrap(p)) ||
error("Non-time dependent parameter $p passed in as a discrete. Must be declared as @parameters $p(t).")
end
dvs = OrderedSet{SymbolicT}()
params = OrderedSet{SymbolicT}()
_varsbuf = Set{SymbolicT}()
for eq in affect
collect_vars!(dvs, params, eq, iv, Pre)
empty!(_varsbuf)
SU.search_variables!(_varsbuf, eq; is_atomic = OperatorIsAtomic{Pre}())
filter!(x -> iscall(x) && operation(x) === Pre(), _varsbuf)
union!(params, _varsbuf)
diffvs = collect_applied_operators(eq, Differential)
union!(dvs, diffvs)
end
pre_params = filter(haspre, params)
sys_params = SymbolicT[]
disc_ps_set = Set{SymbolicT}(discrete_parameters)
disc_ps_set = gather_array_params(disc_ps_set)
discrete_parameters = collect(disc_ps_set)
for p in params
p in disc_ps_set && continue
p in pre_params && continue
push!(sys_params, p)
end
discretes = discrete_parameters
dvs = collect(dvs)
_dvs = map(default_toterm, dvs)
subs = Dict{SymbolicT, SymbolicT}(zip(dvs, _dvs))
affect = substitute(affect, subs)
ps = collect(gather_array_params(union(pre_params, sys_params)))
@named affectsys = System(
affect, iv, collect(union(_dvs, discretes)),
ps; is_discrete = true
)
# This `@invokelatest` should not be necessary, but it works around the inference bug
# in https://github.com/JuliaLang/julia/issues/59943. Remove it at your own risk, the
# bug took weeks to reduce to an MWE.
affectsys = (@invokelatest mtkcompile(affectsys; fully_determined = nothing))::System
# get accessed parameters p from Pre(p) in the callback parameters
accessed_params = Vector{SymbolicT}(filter(isparameter, map(unPre, collect(pre_params))))
union!(accessed_params, sys_params)
# add scalarized unknowns to the map.
_obs = observed(unhack_system(affectsys))
_dvs = vcat(unknowns(affectsys), map(eq -> eq.lhs, _obs))
_dvs = __safe_scalarize_vars(_dvs)
_discs = __safe_scalarize_vars(discretes)
setdiff!(_dvs, _discs)
return AffectSystem(affectsys, _dvs, accessed_params, discrete_parameters)
end
function __safe_scalarize_vars(vars::Vector{SymbolicT})
_vars = SymbolicT[]
for v in vars
sh = SU.shape(v)::SU.ShapeVecT
if isempty(sh)
push!(_vars, v)
continue
end
for i in SU.stable_eachindex(v)
push!(_vars, v[i])
end
end
return _vars
end
safe_vec(@nospecialize(x)) = x isa SymbolicT ? [x] : vec(x::Array{SymbolicT})
system(a::AffectSystem) = a.system::System
discretes(a::AffectSystem) = a.discretes
unknowns(a::AffectSystem) = a.unknowns
parameters(a::AffectSystem) = a.parameters
all_equations(a::AffectSystem) = vcat(equations(system(a)), observed(system(a)))
function Base.show(iio::IO, aff::AffectSystem)
println(iio, "Affect system defined by equations:")
eqs = all_equations(aff)
return show(iio, eqs)
end
function Base.:(==)(a1::AffectSystem, a2::AffectSystem)
return isequal(system(a1), system(a2)) &&
isequal(discretes(a1), discretes(a2)) &&
isequal(unknowns(a1), unknowns(a2)) &&
isequal(parameters(a1), parameters(a2))
end
function Base.hash(a::AffectSystem, s::UInt)
s = hash(system(a), s)
s = hash(unknowns(a), s)
s = hash(parameters(a), s)
return hash(discretes(a), s)
end
function SU.search_variables!(vars, aff::AffectSystem; kwargs...)
SU.search_variables!(vars, unknowns(aff); kwargs...)
SU.search_variables!(vars, parameters(aff); kwargs...)
return SU.search_variables!(vars, discretes(aff); kwargs...)
end
"""
Pre(x)
The `Pre` operator. Used by the callback system to indicate the value of a parameter or variable
before the callback is triggered.
"""
struct Pre <: Symbolics.Operator end
Pre(x) = Pre()(x)
SymbolicUtils.promote_symtype(::Type{Pre}, T) = T
SymbolicUtils.isbinop(::Pre) = false
Base.nameof(::Pre) = :Pre
Base.show(io::IO, x::Pre) = print(io, "Pre")
unPre(x::Num) = unPre(unwrap(x))
unPre(x::Symbolics.Arr) = unPre(unwrap(x))
unPre(x::SymbolicT) = (iscall(x) && operation(x) isa Pre) ? only(arguments(x)) : x
distribute_shift_into_operator(::Pre) = false
(p::Pre)(x::Num) = Num(p(unwrap(x)))
(p::Pre)(x::Symbolics.Arr{T, N}) where {T, N} = Symbolics.Arr{T, N}(p(unwrap(x)))
(p::Pre)(x::Symbolics.SymStruct{T}) where {T} = Symbolics.SymStruct{T}(p(unwrap(x)))
(p::Pre)(x::Symbolics.CallAndWrap{T}) where {T} = Symbolics.CallAndWrap{T}(p(unwrap(x)))
function (p::Pre)(x::SymbolicT)
iscall(x) || return x
return Moshi.Match.@match x begin
BSImpl.Term(; f) && if f isa Pre end => return x
BSImpl.Term(; f) && if f isa Differential end => begin
return p(default_toterm(x))
end
BSImpl.Term(; f, args, type, shape) && if f === getindex end => begin
arrpre = p(args[1])
Moshi.Match.@match arrpre begin
BSImpl.Term(; f = f2) && if f2 isa Pre end => begin
newargs = SArgsT((x,))
return toparam(BSImpl.Term{VartypeT}(p, newargs; type, shape))
end
_ => begin
newargs = copy(parent(args))
newargs[1] = arrpre
return toparam(BSImpl.Term{VartypeT}(f, newargs; type, shape))
end
end
end
BSImpl.Term(; f, type, shape) && if f isa SymbolicT && !SU.is_function_symbolic(f) end => begin
return toparam(BSImpl.Term{VartypeT}(p, SArgsT((x,)); type, shape))
end
_ => begin
op = operation(x)
args = map(p, arguments(x))
return toparam(maketerm(SymbolicT, op, args, nothing; type = symtype(x)))
end
end
end
(::Pre)(x) = x
haspre(eq::Equation) = haspre(eq.lhs) || haspre(eq.rhs)
haspre(O) = recursive_hasoperator(Pre, O)
function validate_operator(op::Pre, args, iv; context = nothing)
end
###############################
###### Continuous events ######
###############################
const Affect = Union{AffectSystem, ImperativeAffect}
"""
SymbolicContinuousCallback(eqs::Vector{Equation}, affect = nothing, iv = nothing;
affect_neg = affect, initialize = nothing, finalize = nothing,
rootfind = SciMLBase.LeftRootFind, initialize_save_discretes = true)
A [`ContinuousCallback`](@ref SciMLBase.ContinuousCallback) specified symbolically. Takes a vector of equations `eq`
as well as the positive-edge `affect` and negative-edge `affect_neg` that apply when *any* of `eq` are satisfied.
By default `affect_neg = affect`; to only get rising edges specify `affect_neg = nothing`.
Assume without loss of generality that the equation is of the form `c(u,p,t) ~ 0`; we denote the integrator state as `i.u`.
For compactness, we define `prev_sign = sign(c(u[t-1], p[t-1], t-1))` and `cur_sign = sign(c(u[t], p[t], t))`.
A condition edge will be detected and the callback will be invoked iff `prev_sign * cur_sign <= 0`.
The positive edge `affect` will be triggered iff an edge is detected and if `prev_sign < 0`; similarly, `affect_neg` will be
triggered iff an edge is detected and `prev_sign > 0`.
Inter-sample condition activation is not guaranteed; for example if we use the dirac delta function as `c` to insert a
sharp discontinuity between integrator steps (which in this example would not normally be identified by adaptivity) then the condition is not
guaranteed to be triggered.
Once detected the integrator will "wind back" through a root-finding process to identify the point when the condition became active; the method used
is specified by `rootfind` from [`SciMLBase.RootfindOpt`](@ref). If we denote the time when the condition becomes active as `tc`,
the value in the integrator after windback will be:
* `u[tc-epsilon], p[tc-epsilon], tc` if `LeftRootFind` is used,
* `u[tc+epsilon], p[tc+epsilon], tc` if `RightRootFind` is used,
* or `u[t], p[t], t` if `NoRootFind` is used.
For example, if we want to detect when an unknown variable `x` satisfies `x > 0` using the condition `x ~ 0` on a positive edge (that is, `D(x) > 0`),
then left root finding will get us `x=-epsilon`, right root finding `x=epsilon` and no root finding will produce whatever the next step of the integrator was after
it passed through 0.
Multiple callbacks in the same system with different `rootfind` operations will be grouped
by their `rootfind` value into separate VectorContinuousCallbacks in the enumeration order of `SciMLBase.RootfindOpt`. This may cause some callbacks to not fire if several become
active at the same instant. See the `SciMLBase` documentation for more information on the semantic rules.
Affects (i.e. `affect` and `affect_neg`) can be specified as either:
* A list of equations that should be applied when the callback is triggered (e.g. `x ~ 3, y ~ 7`) which must be of the form `unknown ~ observed value` where each `unknown` appears only once. Equations will be applied in the order that they appear in the vector; parameters and state updates will become immediately visible to following equations. Instead of
equations, elements can also be `Pair`s. These are parsed according to the [`AssignmentAffect`](@ref) semantics
and combined with the remaining `Equation`s.
* An [`AssignmentAffect`](@ref).
* A tuple `(f!, unknowns, read_parameters, modified_parameters, ctx)`, where:
+ `f!` is a function with signature `(integ, u, p, ctx)` that is called with the integrator, a state *index* vector `u` derived from `unknowns`, a parameter *index* vector `p` derived from `read_parameters`, and the `ctx` that was given at construction time. Note that `ctx` is aliased between instances.
+ `unknowns` is a vector of symbolic unknown variables and optionally their aliases (e.g. if the model was defined with `@variables x(t)` then a valid value for `unknowns` would be `[x]`). A variable can be aliased with a pair `x => :y`. The indices of these `unknowns` will be passed to `f!` in `u` in a named tuple; in the earlier example, if we pass `[x]` as `unknowns` then `f!` can access `x` as `integ.u[u.x]`. If no alias is specified the name of the index will be the symbol version of the variable name.
+ `read_parameters` is a vector of the parameters that are *used* by `f!`. Their indices are passed to `f` in `p` similarly to the indices of `unknowns` passed in `u`.
+ `modified_parameters` is a vector of the parameters that are *modified* by `f!`. Note that a parameter will not appear in `p` if it only appears in `modified_parameters`; it must appear in both `parameters` and `modified_parameters` if it is used in the affect definition.
+ `ctx` is a user-defined context object passed to `f!` when invoked. This value is aliased for each problem.
* A [`ImperativeAffect`](@ref); refer to its documentation for details.
`reinitializealg` is used to set how the system will be reinitialized after the callback.
- Symbolic affects have reinitialization built in. In this case the algorithm will default to SciMLBase.NoInit(), and should **not** be provided.
- Functional and imperative affects will default to SciMLBase.CheckInit(), which will error if the system is not properly reinitialized after the callback. If your system is a DAE, pass in an algorithm like SciMLBase.BrownBasicFullInit() to properly re-initialize.
`initialize_save_discretes` is a flag indicating whether the discrete variables modified by this
callback should be saved at the start of the integration (when the `initialize` runs).
Initial and final affects can also be specified identically to positive and negative edge affects. Initialization affects
will run as soon as the solver starts, while finalization affects will be executed after termination.
"""
struct SymbolicContinuousCallback <: AbstractCallback
conditions::Vector{Equation}
affect::Union{Affect, SymbolicAffect, Nothing}
affect_neg::Union{Affect, SymbolicAffect, Nothing}
initialize::Union{Affect, SymbolicAffect, Nothing}
finalize::Union{Affect, SymbolicAffect, Nothing}
rootfind::Union{Nothing, SciMLBase.RootfindOpt}
reinitializealg::SciMLBase.DAEInitializationAlgorithm
zero_crossing_id::Symbol
initialize_save_discretes::Bool
end
function SymbolicContinuousCallback(
conditions::Union{Equation, Vector{Equation}},
affect = nothing;
affect_neg = affect,
initialize = nothing,
finalize = nothing,
rootfind = SciMLBase.LeftRootFind,
reinitializealg = nothing,
zero_crossing_id = gensym(),
initialize_save_discretes = true,
kwargs...
)
conditions = (conditions isa AbstractVector) ? conditions : [conditions]
if isnothing(reinitializealg)
if any(
a -> a isa ImperativeAffect,
[affect, affect_neg, initialize, finalize]
)
reinitializealg = SciMLBase.CheckInit()
else
reinitializealg = SciMLBase.NoInit()
end
end
return SymbolicContinuousCallback(
conditions, SymbolicAffect(affect; kwargs...),
SymbolicAffect(affect_neg; kwargs...),
SymbolicAffect(initialize; kwargs...), SymbolicAffect(
finalize; kwargs...
),
rootfind, reinitializealg, zero_crossing_id, initialize_save_discretes
)
end # Default affect to nothing
function SymbolicContinuousCallback(p::Pair, args...; kwargs...)
return SymbolicContinuousCallback(p[1], p[2], args...; kwargs...)
end
SymbolicContinuousCallback(cb::SymbolicContinuousCallback, args...; kwargs...) = cb
SymbolicContinuousCallback(cb::Nothing; kwargs...) = nothing
SymbolicContinuousCallback(cb::Nothing, args...; kwargs...) = nothing
function SymbolicContinuousCallback(cb::Tuple, args...; kwargs...)
return if length(cb) == 2
SymbolicContinuousCallback(cb[1]; kwargs..., cb[2]...)
else
error("Malformed tuple specifying callback. Should be a condition => affect pair, followed by a vector of kwargs.")
end
end
function complete(cb::SymbolicContinuousCallback; kwargs...)
return SymbolicContinuousCallback(
cb.conditions, make_affect(cb.affect; kwargs...),
make_affect(cb.affect_neg; kwargs...), make_affect(cb.initialize; kwargs...),
make_affect(cb.finalize; kwargs...), cb.rootfind, cb.reinitializealg,
cb.zero_crossing_id, cb.initialize_save_discretes
)
end
make_affect(affect::SymbolicAffect; kwargs...) = AffectSystem(affect; kwargs...)
make_affect(affect::Nothing; kwargs...) = nothing
make_affect(affect::Tuple; kwargs...) = ImperativeAffect(affect...)
make_affect(affect::NamedTuple; kwargs...) = ImperativeAffect(; affect...)
make_affect(affect::Affect; kwargs...) = affect
make_affect(affect::Vector{Equation}; kwargs...) = AffectSystem(affect; kwargs...)
function make_affect(affect; kwargs...)
error("Malformed affect $(affect). This should be a vector of equations or a tuple specifying a functional affect.")
end
function Base.show(io::IO, cb::AbstractCallback)
indent = get(io, :indent, 0)
iio = IOContext(io, :indent => indent + 1)
is_discrete(cb) ? print(io, "SymbolicDiscreteCallback(") :
print(io, "SymbolicContinuousCallback(")
print(iio, "Conditions:")
show(iio, equations(cb))
print(iio, "; ")
if affects(cb) != nothing
print(iio, "Affect:")
show(iio, affects(cb))
print(iio, ", ")
end
if !is_discrete(cb) && affect_negs(cb) != nothing
print(iio, "Negative-edge affect:")
show(iio, affect_negs(cb))
print(iio, ", ")
end
if initialize_affects(cb) != nothing
print(iio, "Initialization affect:")
show(iio, initialize_affects(cb))
print(iio, ", ")
end
if finalize_affects(cb) != nothing
print(iio, "Finalization affect:")
show(iio, finalize_affects(cb))
end
return print(iio, ")")
end
function Base.show(io::IO, mime::MIME"text/plain", cb::AbstractCallback)
indent = get(io, :indent, 0)
iio = IOContext(io, :indent => indent + 1)
is_discrete(cb) ? println(io, "SymbolicDiscreteCallback:") :
println(io, "SymbolicContinuousCallback:")
println(iio, "Conditions:")
show(iio, mime, equations(cb))
print(iio, "\n")
if affects(cb) != nothing
println(iio, "Affect:")
show(iio, mime, affects(cb))
print(iio, "\n")
end
if !is_discrete(cb) && affect_negs(cb) != nothing
print(iio, "Negative-edge affect:\n")
show(iio, mime, affect_negs(cb))
print(iio, "\n")
end
if initialize_affects(cb) != nothing
println(iio, "Initialization affect:")
show(iio, mime, initialize_affects(cb))
print(iio, "\n")
end
return if finalize_affects(cb) != nothing
println(iio, "Finalization affect:")
show(iio, mime, finalize_affects(cb))
print(iio, "\n")
end
end
function SU.search_variables!(vars, cb::AbstractCallback; kwargs...)
if symbolic_type(conditions(cb)) isa NotSymbolic
SU.search_variables!(vars, conditions(cb); kwargs...)
end
affs = affects(cb)
affs === nothing || SU.search_variables!(vars, affs; kwargs...)
affs = initialize_affects(cb)
affs === nothing || SU.search_variables!(vars, affs; kwargs...)
affs = finalize_affects(cb)
affs === nothing || SU.search_variables!(vars, affs; kwargs...)
return is_discrete(cb) || SU.search_variables!(vars, affect_negs(cb); kwargs...)
end
################################
######## Discrete events #######
################################
"""
SymbolicDiscreteCallback(conditions::Vector{Equation}, affect = nothing, iv = nothing;
initialize = nothing, finalize = nothing)
A callback that triggers at the first timestep that the conditions are satisfied.
The condition can be one of:
- Δt::Real - periodic events with period Δt
- ts::Vector{Real} - events trigger at these preset times given by `ts`
- eqs::Vector{SymbolicT} - events trigger when the condition evaluates to true
- A `SciMLBase.Clock(dt; phase)` - events trigger with period `dt` and phase `phase`.
Note that this form will ignore the `initialize_save_discretes` keyword argument in the
interest of correctness. The callback will trigger and save at `tspan[1]` if the clock
would tick at `tspan[1]`.
Arguments:
- iv: The independent variable of the system. This must be specified if the independent variable appears in one of the equations explicitly, as in x ~ t + 1.
"""
struct SymbolicDiscreteCallback <: AbstractCallback
conditions::Union{Number, Vector{<:Number}, SymbolicT, SciMLBase.TimeDomain}
affect::Union{Affect, SymbolicAffect, Nothing}
initialize::Union{Affect, SymbolicAffect, Nothing}
finalize::Union{Affect, SymbolicAffect, Nothing}
reinitializealg::SciMLBase.DAEInitializationAlgorithm
initialize_save_discretes::Bool
end
function SymbolicDiscreteCallback(
condition::Union{SymbolicT, Number, Vector{<:Number}, SciMLBase.TimeDomain},
affect = nothing; initialize = nothing, finalize = nothing,
reinitializealg = nothing, initialize_save_discretes = true, kwargs...
)
# Manual error check (to prevent events like `[X < 5.0] => [X ~ Pre(X) + 10.0]` from being created).
(condition isa Vector) && (eltype(condition) <: Num) &&
error("Vectors of symbolic conditions are not allowed for `SymbolicDiscreteCallback`.")
if condition isa SciMLBase.TimeDomain
if !SciMLBase.isclock(condition)
throw(
ArgumentError("Clock given to `SymbolicDiscreteCallback` must be a `SciMLBase.Clock`.")
)
end
c = condition
else
@assert !(condition isa SymbolicT && symtype(condition) != Bool)
c = is_timed_condition(condition) ? condition : value(scalarize(condition))
c = is_timed_condition(condition) ? condition : value(scalarize(condition))
end
if isnothing(reinitializealg)
if any(
a -> a isa ImperativeAffect,
[affect, initialize, finalize]
)
reinitializealg = SciMLBase.CheckInit()
else
reinitializealg = SciMLBase.NoInit()
end
end
return SymbolicDiscreteCallback(
c, SymbolicAffect(affect; kwargs...),
SymbolicAffect(initialize; kwargs...),
SymbolicAffect(finalize; kwargs...), reinitializealg,
initialize_save_discretes
)
end # Default affect to nothing
function SymbolicDiscreteCallback(p::Pair, args...; kwargs...)
return SymbolicDiscreteCallback(p[1], p[2], args...; kwargs...)
end
SymbolicDiscreteCallback(cb::SymbolicDiscreteCallback, args...; kwargs...) = cb
SymbolicDiscreteCallback(cb::Nothing, args...; kwargs...) = nothing
function SymbolicDiscreteCallback(cb::Tuple, args...; kwargs...)
return if length(cb) == 2
SymbolicDiscreteCallback(cb[1]; cb[2]...)
else
error("Malformed tuple specifying callback. Should be a condition => affect pair, followed by a vector of kwargs.")
end
end
function complete(cb::SymbolicDiscreteCallback; kwargs...)
return SymbolicDiscreteCallback(
cb.conditions, make_affect(cb.affect; kwargs...),
make_affect(cb.initialize; kwargs...),
make_affect(cb.finalize; kwargs...), cb.reinitializealg,
cb.initialize_save_discretes
)
end
function is_timed_condition(condition::T) where {T}
return if T === Num
false
elseif T <: Real
true
elseif T <: AbstractVector
eltype(condition) <: Real
elseif T <: SciMLBase.TimeDomain
true
else
false
end
end
to_cb_vector(cbs::Vector{<:AbstractCallback}; kwargs...) = cbs
to_cb_vector(cbs::Union{Nothing, Vector{Nothing}}; kwargs...) = AbstractCallback[]
to_cb_vector(cb::AbstractCallback; kwargs...) = [cb]
function to_cb_vector(cbs; CB_TYPE = SymbolicContinuousCallback, kwargs...)
return if cbs isa Pair
[CB_TYPE(cbs; kwargs...)]
else
cbs_filtered = filter!(c -> !isnothing(c), [CB_TYPE(cb; kwargs...) for cb in cbs])
Vector{CB_TYPE}(cbs_filtered)
end
end
############################################
########## Namespacing Utilities ###########
############################################
function namespace_affects(affect::AffectSystem, s)
affsys = system(affect)
old_ts = get_tearing_state(affsys)
# if we just `renamespace` the system, it updates the name. However, this doesn't
# namespace the returned values from `equations(affsys)`, etc. which we need. So we
# need to manually namespace everything. This is done by renaming the system to the
# namespace, putting it as a subsystem of an empty system called `affectsys`, and then
# flatten the system. The resultant system has everything namespaced, and is still
# called `affectsys` for further namespacing
affsys = rename(affsys, nameof(s))
affsys = toggle_namespacing(affsys, true)
affsys = System(
Equation[], get_iv(affsys)::SymbolicT, SymbolicT[], SymbolicT[];
systems = System[affsys], name = :affectsys
)
affsys = complete(affsys)
@set! affsys.tearing_state = old_ts
return AffectSystem(
affsys,
renamespace.((s,), unknowns(affect)),
renamespace.((s,), parameters(affect)),
renamespace.((s,), discretes(affect))
)
end
function namespace_affects(affect::SymbolicAffect, s)
return SymbolicAffect(
namespace_equation.(affect.affect, (s,)),
renamespace.((s,), affect.discrete_parameters)
)
end
namespace_affects(af::Nothing, s) = nothing
function namespace_callback(cb::SymbolicContinuousCallback, s)::SymbolicContinuousCallback
return SymbolicContinuousCallback(
namespace_equation.(equations(cb), (s,)),
namespace_affects(affects(cb), s),
affect_neg = namespace_affects(affect_negs(cb), s),
initialize = namespace_affects(initialize_affects(cb), s),
finalize = namespace_affects(finalize_affects(cb), s),
rootfind = cb.rootfind, reinitializealg = cb.reinitializealg,
zero_crossing_id = cb.zero_crossing_id
)
end
function namespace_conditions(condition, s)
return is_timed_condition(condition) ? condition : namespace_expr(condition, s)
end
function namespace_callback(cb::SymbolicDiscreteCallback, s)::SymbolicDiscreteCallback
return SymbolicDiscreteCallback(
namespace_conditions(conditions(cb), s),
namespace_affects(affects(cb), s),
initialize = namespace_affects(initialize_affects(cb), s),
finalize = namespace_affects(finalize_affects(cb), s), reinitializealg = cb.reinitializealg
)
end
function Base.hash(cb::AbstractCallback, s::UInt)
s = conditions(cb) isa AbstractVector ? foldr(hash, conditions(cb), init = s) :
hash(conditions(cb), s)
s = hash(affects(cb), s)
!is_discrete(cb) && (s = hash(affect_negs(cb), s))
s = hash(initialize_affects(cb), s)
s = hash(finalize_affects(cb), s)
!is_discrete(cb) && (s = hash(cb.rootfind, s))
hash(cb.reinitializealg, s)
!is_discrete(cb) && (s = hash(cb.zero_crossing_id, s))
return s
end
###########################
######### Helpers #########
###########################
conditions(cb::AbstractCallback) = cb.conditions
function conditions(cbs::Vector{<:AbstractCallback})
return reduce(vcat, conditions(cb) for cb in cbs; init = [])
end
function conditions(cbs::Vector{SymbolicContinuousCallback})
return mapreduce(conditions, vcat, cbs; init = Equation[])
end
equations(cb::AbstractCallback) = conditions(cb)
equations(cb::Vector{<:AbstractCallback}) = conditions(cb)
affects(cb::AbstractCallback) = cb.affect
function affects(cbs::Vector{<:AbstractCallback})
return reduce(vcat, affects(cb) for cb in cbs; init = [])
end
affect_negs(cb::SymbolicContinuousCallback) = cb.affect_neg
function affect_negs(cbs::Vector{SymbolicContinuousCallback})
return reduce(vcat, affect_negs(cb) for cb in cbs; init = [])
end
initialize_affects(cb::AbstractCallback) = cb.initialize
function initialize_affects(cbs::Vector{<:AbstractCallback})
return reduce(initialize_affects, vcat, cbs; init = [])
end
finalize_affects(cb::AbstractCallback) = cb.finalize
function finalize_affects(cbs::Vector{<:AbstractCallback})
return reduce(finalize_affects, vcat, cbs; init = [])
end
function Base.:(==)(e1::AbstractCallback, e2::AbstractCallback)
is_discrete(e1) === is_discrete(e2) || return false
isequal(e1.conditions, e2.conditions) && isequal(e1.affect, e2.affect) || return false
isequal(e1.initialize, e2.initialize) || return false
isequal(e1.finalize, e2.finalize) || return false
isequal(e1.reinitializealg, e2.reinitializealg) || return false
if !is_discrete(e1)
isequal(e1.affect_neg, e2.affect_neg) || return false
isequal(e1.rootfind, e2.rootfind) || return false
isequal(e1.zero_crossing_id, e2.zero_crossing_id) || return false
end
return true
end
Base.isempty(cb::AbstractCallback) = isempty(cb.conditions)
####################################
####### Compilation functions ######
####################################
struct CompiledCondition{IsDiscrete, F}
f::F
end
function CompiledCondition{ID}(f::F) where {ID, F}
return CompiledCondition{ID, F}(f)
end
function (cc::CompiledCondition)(out, u, t, integ)
return cc.f(out, u, parameter_values(integ), t)
end
function (cc::CompiledCondition{false})(u, t, integ)
return if DiffEqBase.isinplace(SciMLBase.get_sol(integ).prob)
tmp, = DiffEqBase.get_tmp_cache(integ)
cc.f(tmp, u, parameter_values(integ), t)
tmp[1]
else
cc.f(u, parameter_values(integ), t)
end
end
function (cc::CompiledCondition{true})(u, t, integ)
return cc.f(u, parameter_values(integ), t)
end
####################################
#### Callable structs for affects ##
####################################
"""
ExplicitAffect{DVS, PS, UF, PF}
Callable struct representing a compiled explicit affect (one with no algebraic equations).
Invokes `u_up!` to update state variables and `p_up!` to update discrete parameters, then
optionally resets aggregated jumps. Created by [`compile_explicit_affect`](@ref).
# Fields
- `dvs_to_update`: symbolic unknowns modified by this affect (emptiness is checked at call time)
- `ps_to_update`: symbolic discrete parameters modified by this affect
- `reset_jumps`: if `true`, call `reset_aggregated_jumps!` after the update
- `u_up!`: compiled in-place function that writes updated state into the integrator
- `p_up!`: compiled in-place function that writes updated parameters into the integrator
"""
struct ExplicitAffect{DVS, PS, UF, PF}
dvs_to_update::DVS
ps_to_update::PS
reset_jumps::Bool
u_up!::UF
p_up!::PF
end
function (ea::ExplicitAffect)(integ)
isempty(ea.dvs_to_update) || ea.u_up!(integ)
isempty(ea.ps_to_update) || ea.p_up!(integ)
return ea.reset_jumps && reset_aggregated_jumps!(integ)
end
"""
ImplicitAffect{DVS, PS, AFFSYS, AFF, UG, AG, AUS, APS, US, PST, UGT, PG, PROB}
Callable struct representing a compiled implicit affect (one whose equations require solving
an `ImplicitDiscreteProblem` at each callback invocation). Created by
[`compile_implicit_affect`](@ref).
The `affprob` field is a plain (non-`Ref`) immutable field of type `PROB`. The in-place
setter functions `affu_setter!` and `affp_setter!` mutate the problem's internal mutable
arrays directly; `remake` is then called to produce a transient local copy with the current
`tspan` for the `init` call, without writing back to the struct.
# Fields
- `dvs_to_update`: unknowns of the parent system written back after solving
- `ps_to_update`: discrete parameters of the parent system written back after solving
- `affsys`: the compiled affect `System` (an `ImplicitDiscreteSystem`)
- `aff`: the `AffectSystem` descriptor (used for error reporting)
- `reset_jumps`: if `true`, call `reset_aggregated_jumps!` after the update
- `affu_getter`: reads current parent-system unknowns into the affect problem's `u0`
- `affp_getter`: reads current parent-system parameters into the affect problem's `p`
- `affu_setter!`: sets the affect problem's unknowns in-place
- `affp_setter!`: sets the affect problem's parameters in-place
- `u_setter!`: writes solved unknowns back into the parent integrator
- `p_setter!`: writes solved parameters back into the parent integrator
- `u_getter`: reads solved unknowns from the affect solution
- `p_getter`: reads solved parameters from the affect solution
- `affprob`: the pre-built `ImplicitDiscreteProblem` (mutated in-place each call)
"""
struct ImplicitAffect{DVS, PS, AFFSYS, AFF, UG, AG, AUS, APS, US, PST, UGT, PG, PROB}
dvs_to_update::DVS
ps_to_update::PS
affsys::AFFSYS
aff::AFF
reset_jumps::Bool
affu_getter::UG
affp_getter::AG
affu_setter!::AUS
affp_setter!::APS
u_setter!::US
p_setter!::PST
u_getter::UGT
p_getter::PG
affprob::PROB
end
function (ia::ImplicitAffect)(integ)
ia.affu_setter!(ia.affprob, ia.affu_getter(integ))
ia.affp_setter!(ia.affprob, ia.affp_getter(integ))
# remake only updates tspan; result is a transient local, not stored back to struct
affprob = remake(ia.affprob, tspan = (integ.t, integ.t))
affsol = init(affprob, IDSolve())
(check_error(affsol) === ReturnCode.InitialFailure) &&
throw(UnsolvableCallbackError(all_equations(ia.aff)))
ia.u_setter!(integ, ia.u_getter(affsol))
ia.p_setter!(integ, ia.p_getter(affsol))
return ia.reset_jumps && reset_aggregated_jumps!(integ)
end
"""
VectorAffect{E2A, AFFS}
Callable struct for the positive-edge arm of a `VectorContinuousCallback`. Routes an
integrator call to the appropriate per-equation affect based on the equation index `idx`.
Created inside [`generate_callback`](@ref) for vectors of `SymbolicContinuousCallback`s.
# Fields
- `eq2affect`: maps condition equation index → affect index
- `affects`: vector of compiled affect callables, one per callback in the group
"""
struct VectorAffect{E2A, AFFS}
eq2affect::E2A
affects::AFFS
end
(va::VectorAffect)(integ, idx) = va.affects[va.eq2affect[idx]](integ)
"""
VectorAffectNeg{E2A, AFFS}
Callable struct for the negative-edge arm of a `VectorContinuousCallback`. Like
[`VectorAffect`](@ref) but skips `nothing` entries (callbacks with no negative-edge affect).
# Fields
- `eq2affect`: maps condition equation index → affect index
- `affect_negs`: vector of compiled negative-edge affect callables (entries may be `nothing`)
"""
struct VectorAffectNeg{E2A, AFFS}
eq2affect::E2A
affect_negs::AFFS
end
function (va::VectorAffectNeg)(integ, idx)
f = va.affect_negs[va.eq2affect[idx]]
f === nothing && return
return f(integ)
end
"""
VectorOptionalAffect{FUNS}
Callable struct for the `initialize` or `finalize` slot of a `VectorContinuousCallback`.
Iterates over a heterogeneous vector of optional compiled affect callables, skipping
`nothing` entries. The four-argument signature `(cb, u, t, integ)` matches the SciMLBase
initialize/finalize protocol. Created by [`wrap_vector_optional_affect`](@ref).
# Fields
- `funs`: vector of compiled affect callables or `nothing`, one per callback in the group
"""
struct VectorOptionalAffect{FUNS}
funs::FUNS
end
function (voa::VectorOptionalAffect)(cb, u, t, integ)
for func in voa.funs
func === nothing || func(integ)
end
return
end
"""
InitFinalizeWrapper{F}
Callable struct that adapts a compiled single-integrator affect `f(integrator)` to the
four-argument `(cb, u, t, integrator)` protocol expected by SciMLBase's `initialize` and
`finalize` callback fields. Used in [`generate_callback`](@ref) for single callbacks whose
`initialize` or `finalize` field is non-`nothing`.
# Fields
- `f`: the inner compiled affect callable with signature `f(integrator)`
"""
struct InitFinalizeWrapper{F}
f::F
end
(ifw::InitFinalizeWrapper)(c, u, t, integ) = ifw.f(integ)
"""
compile_condition(cb::AbstractCallback, sys, dvs, ps; expression, kwargs...)
Returns a function `condition(u,t,integrator)`, condition(out,u,t,integrator)` returning the `condition(cb)`.
"""
Base.@nospecializeinfer function compile_condition(
@nospecialize(cbs::Union{AbstractCallback, Vector{<:AbstractCallback}}),
sys, @nospecialize(dvs), @nospecialize(ps);
eval_expression = false, eval_module = @__MODULE__, kwargs...
)
u = map(value, dvs)
p = map.(value, reorder_parameters(sys, ps))
t = get_iv(sys)
condit = conditions(cbs)
if !is_discrete(cbs)
condit = reduce(vcat, flatten_equations(Vector{Equation}(condit)))
condit = condit isa AbstractVector ? [c.lhs - c.rhs for c in condit] :
[condit.lhs - condit.rhs]
end
fs = build_function_wrapper(
sys, condit, u, p..., t; kwargs..., cse = false
)
fs = GeneratedFunctionWrapper{(2, 3, is_split(sys))}(
Val{false}, fs...; eval_expression, eval_module
)
return CompiledCondition{is_discrete(cbs)}(fs)
end
is_discrete(cb::AbstractCallback) = cb isa SymbolicDiscreteCallback
is_discrete(cb::Vector{<:AbstractCallback}) = eltype(cb) isa SymbolicDiscreteCallback
"""
generate_continuous_callbacks(sys, dvs, ps; kwargs...)