-
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathutils.jl
More file actions
1714 lines (1528 loc) · 56.5 KB
/
Copy pathutils.jl
File metadata and controls
1714 lines (1528 loc) · 56.5 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
get_iv(D::Differential) = D.x
"""
$(TYPEDSIGNATURES)
Turn `x(t)` into `x`
"""
function detime_dvs(op)
return if !iscall(op)
op
elseif issym(operation(op))
SSym(nameof(operation(op)); type = Real, shape = SU.shape(op))
else
maketerm(
typeof(op), operation(op), detime_dvs.(arguments(op)),
metadata(op)
)
end
end
"""
$(TYPEDSIGNATURES)
Reverse `detime_dvs` for the given `dvs` using independent variable `iv`.
"""
function retime_dvs(op, dvs, iv)
issym(op) && return SSym(nameof(op); type = FnType{Tuple{symtype(iv)}, Real}, shape = SU.ShapeVecT())(iv)
return iscall(op) ?
maketerm(
typeof(op), operation(op), retime_dvs.(arguments(op), (dvs,), (iv,)),
metadata(op)
) :
op
end
function modified_unknowns!(munknowns, e::Equation, unknownlist = nothing)
return get_variables!(munknowns, e.lhs, unknownlist)
end
function todict(d)
eltype(d) <: Pair || throw(ArgumentError("The variable-value mapping must be a Dict."))
return d isa Dict ? d : Dict(d)
end
function _readable_code(ex)
ex isa Expr || return ex
if ex.head === :call
f, args = ex.args[1], ex.args[2:end]
if f isa Function && (nf = nameof(f); Base.isoperator(nf))
expr = Expr(:call, nf)
for a in args
push!(expr.args, _readable_code(a))
end
return expr
end
end
expr = Expr(ex.head)
for a in ex.args
push!(expr.args, _readable_code(a))
end
return expr
end
function rec_remove_macro_linenums!(expr)
if expr isa Expr
if expr.head === :macrocall
expr.args[2] = nothing
rec_remove_macro_linenums!(expr.args[3])
else
for ex in expr.args
rec_remove_macro_linenums!(ex)
end
end
end
return expr
end
function readable_code(expr)
expr = Base.remove_linenums!(_readable_code(expr))
rec_remove_macro_linenums!(expr)
return string(expr)
end
# System validation enums
"""
const CheckNone
Value that can be provided to the `check` keyword of `System` to disable checking of input.
"""
const CheckNone = 0
"""
const CheckAll
Value that can be provided to the `check` keyword of `System` to enable all input
validation.
"""
const CheckAll = 1 << 0
"""
const CheckComponents
Value that can be provided to the `check` keyword of `System` to only enable checking of
basic components of the system, such as equations, variables, etc.
"""
const CheckComponents = 1 << 1
"""
const CheckUnits
Value that can be provided to the `check` keyword of `System` to enable checking of units.
"""
const CheckUnits = 1 << 2
function check_independent_variables(ivs)
for iv in ivs
isparameter(iv) || @invokelatest warn_indepvar(iv)
end
return
end
@noinline function warn_indepvar(iv::SymbolicT)
return @warn "Independent variable $iv should be defined with @independent_variables $iv."
end
function check_parameters(ps, iv)
for p in ps
isequal(iv, p) &&
throw(ArgumentError(lazy"Independent variable $iv not allowed in parameters."))
end
return
end
function is_delay_var(iv::SymbolicT, var::SymbolicT)
return Moshi.Match.@match var begin
BSImpl.Term(; f, args) => begin
length(args) > 1 && return false
arg = args[1]
isequal(arg, iv) && return false
return symtype(arg) <: Real
end
_ => false
end
end
function check_variables(dvs, iv)
for dv in dvs
isequal(iv, dv) &&
throw(ArgumentError(lazy"Independent variable $iv not allowed in dependent variables."))
(is_delay_var(iv, dv) || SU.query(isequal(iv), dv)) ||
throw(ArgumentError(lazy"Variable $dv is not a function of independent variable $iv."))
end
return
end
function check_lhs(eq::Equation, ::Type{Differential}, dvs::Set)
v = unwrap(eq.lhs)
_iszero(v) && return
op = operation(v)
op isa Differential && isone(op.order) && only(arguments(v)) in dvs && return
error(lazy"$v is not a valid LHS. Please run mtkcompile before simulation.")
end
function check_lhs(eqs::Vector{Equation}, ::Type{Differential}, dvs::Set)
for eq in eqs
check_lhs(eq, Differential, dvs)
end
return
end
"""
collect_ivs(eqs, op = Differential)
Get all the independent variables with respect to which differentials (`op`) are taken.
"""
function collect_ivs(eqs, ::Type{op} = Differential) where {op}
vars = Set{SymbolicT}()
ivs = Set{SymbolicT}()
for eq in eqs
SU.search_variables!(vars, eq; is_atomic = OperatorIsAtomic{op}())
for v in vars
if isoperator(v, op)
collect_ivs_from_nested_operator!(ivs, v, op)
end
end
empty!(vars)
end
return ivs
end
struct IndepvarCheckPredicate
iv::SymbolicT
end
function (icp::IndepvarCheckPredicate)(ex::SymbolicT)
return Moshi.Match.@match ex begin
BSImpl.Term(; f) && if f isa Differential end => begin
f = f::Differential
isequal(f.x, icp.iv) || throw_multiple_iv(icp.iv, f.x)
return false
end
_ => false
end
end
@noinline function throw_multiple_iv(iv, newiv)
throw(ArgumentError(lazy"Differential w.r.t. variable ($newiv) other than the independent variable ($iv) are not allowed."))
end
"""
check_equations(eqs, iv)
Assert that equations are well-formed when building ODE, i.e., only containing a single independent variable.
"""
function check_equations(eqs::Vector{Equation}, iv::SymbolicT)
icp = IndepvarCheckPredicate(iv)
for eq in eqs
SU.query(icp, eq.lhs)
SU.query(icp, eq.rhs)
end
return
end
"""
$(TYPEDSIGNATURES)
Assert that the subsystems have the appropriate namespacing behavior.
"""
function check_subsystems(systems)
idxs = findall(!does_namespacing, systems)
return isempty(idxs) || throw_bad_namespacing(systems, idxs)
end
@noinline function throw_bad_namespacing(systems, idxs)
names = join(" " .* string.(nameof.(systems[idxs])), "\n")
throw(ArgumentError("All subsystems must have namespacing enabled. The following subsystems do not perform namespacing:\n$(names)"))
end
"""
Get all the independent variables with respect to which differentials are taken.
"""
function collect_ivs_from_nested_operator!(ivs, x, target_op)
if !iscall(x)
return
end
op = operation(unwrap(x))
return if op isa target_op
push!(ivs, get_iv(op))
x = if target_op <: Differential
op.x
else
error("Unknown target op type in collect_ivs $target_op. Pass Differential")
end
collect_ivs_from_nested_operator!(ivs, x, target_op)
end
end
function iv_from_nested_derivative(x, op = Differential)
return if iscall(x) &&
(operation(x) == getindex || operation(x) == real || operation(x) == imag)
iv_from_nested_derivative(arguments(x)[1], op)
elseif iscall(x)
operation(x) isa op ? iv_from_nested_derivative(arguments(x)[1], op) :
arguments(x)[1]
elseif issym(x)
x
else
nothing
end
end
"""
$TYPEDSIGNATURES
Check the validity of `bindings` given the list of parameters `ps`. This method assumes
that there are no discrete values in `ps`.
"""
function check_bindings(ps::Vector{SymbolicT}, bindings::SymmapT)
atomic_ps = AtomicArraySet()
for p in ps
push_as_atomic_array!(atomic_ps, p)
end
return check_bindings(atomic_ps, bindings)
end
function check_bindings_is_atomic(x::SymbolicT)
return SU.default_is_atomic(x) && Moshi.Match.@match x begin
BSImpl.Term(; f) && if f isa Operator end => f isa Initial
BSImpl.Term(; f) && if f === getindex end => false
_ => true
end
end
"""
$TYPEDSIGNATURES
Check if `bindings` are valid, given a list of parameters `atomic_ps`. Assumes no values in
`atomic_ps` are discretes.
"""
function check_bindings(atomic_ps::AtomicArraySet{Dict{SymbolicT, Nothing}}, bindings::SymmapT)
varsbuf = Set{SymbolicT}()
for p in atomic_ps
val = get(bindings, p, COMMON_NOTHING)
val === COMMON_NOTHING && continue
if val === COMMON_MISSING
if !is_variable_floatingpoint(p)
throw(
ArgumentError(
"""
`missing` bindings are only valid for solvable parameters! Non-floating \
point parameters cannot be solved for, and thus do not accept a binding \
of `missing`. Found invalid parameter $p of symtype $(symtype(p)).
"""
)
)
end
end
empty!(varsbuf)
SU.search_variables!(varsbuf, val; is_atomic = check_bindings_is_atomic)
setdiff!(varsbuf, atomic_ps)
filter!(x -> getmetadata(x, SymScope, LocalScope()) isa LocalScope, varsbuf)
filter!(!isinitial, varsbuf)
isempty(varsbuf) && continue
throw(
ArgumentError(
"""
Bindings for parameters can only be functions of other parameters. For parameter \
$p, encountered binding $val which contains non-parameter symbolics $varsbuf. If \
you intended $p to be a discrete variable, pass it as an unknown of the system.
"""
)
)
end
return
end
function check_no_parameter_equations_recurse(ex::SymbolicT)
return iscall(ex) && !check_bindings_is_atomic(ex)
end
"""
$TYPEDSIGNATURES
Return a 2-tuple, where the first element is a list of all parameter-only equations
in `sys`, and the second is all other equations.
"""
function find_all_parameter_equations(sys::AbstractSystem)
varsbuf = Set{SymbolicT}()
pareqs = Equation[]
allowed_vars = as_atomic_array_set(unknowns(sys))
foreach(Base.Fix1(push_as_atomic_array!, allowed_vars), observables(sys))
foreach(Base.Fix1(push_as_atomic_array!, allowed_vars), get_all_discretes_fast(sys))
rest_eqs = Equation[]
for eq in equations(sys)
empty!(varsbuf)
Symbolics.search_variables!(
varsbuf, eq; is_atomic = check_bindings_is_atomic,
recurse = check_no_parameter_equations_recurse
)
isempty(varsbuf) && (!SU.isconst(eq.lhs) || !SU.isconst(eq.rhs)) && continue
intersect!(varsbuf, allowed_vars)
push!(isempty(varsbuf) ? pareqs : rest_eqs, eq)
end
return pareqs, rest_eqs
end
"""
$(TYPEDSIGNATURES)
Validate that all equations of the system involve the unknowns/observables.
"""
function check_no_parameter_equations(sys::AbstractSystem)
if !isempty(get_systems(sys))
throw(ArgumentError("Expected flattened system"))
end
pareqs = find_all_parameter_equations(sys)[1]
return if !isempty(pareqs)
error(
"""
The equations of a system must involve the unknowns/observables. The following \
equations were found to have no unknowns/observables:
$(join(string.(pareqs), "\n"))
"""
)
end
end
"""
$TYPEDSIGNATURES
Verify that bound parameters have not been provided initial conditions. Requires the \
existence of an up-to-data `parameter_bindings_graph`.
"""
function check_no_bound_initial_conditions(sys::AbstractSystem)
bound_ps = (get_parameter_bindings_graph(sys)::ParameterBindingsGraph).bound_ps
ics = initial_conditions(sys)
bound_ics = intersect(bound_ps, keys(ics))
return isempty(bound_ics) || throw(BoundInitialConditionsError(collect(bound_ics)))
end
struct BoundInitialConditionsError <: Exception
bound_pars::Vector{SymbolicT}
end
function Base.showerror(io::IO, err::BoundInitialConditionsError)
return print(
io, """
Bound parameters cannot have initial conditions. The following bound parameters \
were found to have initial conditions:
$(join(string.(collect(err.bound_pars)), "\n"))
"""
)
end
"""
$(TYPEDSIGNATURES)
Check if the symbolic variable `v` has a default value.
"""
hasdefault(v) = hasmetadata(v, Symbolics.VariableDefaultValue)
"""
$(TYPEDSIGNATURES)
Return the default value of symbolic variable `v`.
"""
getdefault(v) = value(Symbolics.getdefaultval(v))
"""
$(TYPEDSIGNATURES)
Set the default value of symbolic variable `v` to `val`.
"""
function setdefault(v, val)
return val === nothing ? v : wrap(setdefaultval(unwrap(v), value(val)))
end
"""
$TYPEDSIGNATURES
For all variables in `vars`, obtain the value associated with metadata key `Key` (if present)
and add it to `cache`. Somewhat equivalent to [`collect_defaults!`](@ref) for arbitrary
metadata. For type-stability, the value obtained via `getmetadata` is type-asserted to the
value type of `cache`. If `cache` already contains a value for a variable, the metadata is
ignored.
"""
function collect_metadata!(::Type{Key}, cache::AtomicArrayDict{V}, vars::Vector{SymbolicT}) where {Key, V}
for var in vars
arr, _ = split_indexed_var(var)
haskey(cache, arr) && continue
value = getmetadata(arr, Key, nothing)::Union{Nothing, V}
value === nothing && continue
value = value::V
cache[arr] = value
end
return
end
"""
$TYPEDSIGNATURES
Specialized method for when `Key` refers to boolean metadata. Variables for which the value
is `true` are added to `cache`.
"""
function collect_metadata!(::Type{Key}, cache::AtomicSetT, vars::Vector{SymbolicT}) where {Key}
for var in vars
arr, _ = split_indexed_var(var)
arr in cache && continue
value = getmetadata(arr, Key, false)::Bool
value && push!(cache, arr)
end
return
end
function process_variables!(var_to_name::Dict{Symbol, SymbolicT}, initial_conditions::SymmapT, bindings::SymmapT, guesses::SymmapT, vars::Vector{SymbolicT})
collect_defaults!(initial_conditions, bindings, vars)
collect_guesses!(guesses, vars)
collect_var_to_name!(var_to_name, vars)
return nothing
end
function process_variables!(var_to_name::Dict{Symbol, SymbolicT}, initial_conditions::SymmapT, bindings::SymmapT, vars::Vector{SymbolicT})
collect_defaults!(initial_conditions, bindings, vars)
collect_var_to_name!(var_to_name, vars)
return nothing
end
function collect_defaults!(initial_conditions::SymmapT, bindings::SymmapT, v::SymbolicT)
if hasname(v) && occursin(NAMESPACE_SEPARATOR, string(getname(v)))
return
end
return Moshi.Match.@match v begin
BSImpl.Const() => return
BSImpl.Term(; f, args) && if f === getindex end => begin
collect_defaults!(initial_conditions, bindings, args[1])
end
BSImpl.Term(; f) && if f isa SymbolicT && SU.is_function_symbolic(f) end => nothing
_ => begin
def = Symbolics.getdefaultval(v, nothing)
def === nothing && return
def = BSImpl.Const{VartypeT}(def)
Moshi.Match.@match def begin
# `get!` here is just shorthand for "if the key doesn't exist, add this
# value".
BSImpl.Const() => if def === COMMON_MISSING
get!(bindings, v, def)
else
get!(initial_conditions, v, def)
end
_ => get!(bindings, v, def)
end
end
end
end
function collect_defaults!(initial_conditions::SymmapT, bindings::SymmapT, vars::Vector{SymbolicT})
for v in vars
collect_defaults!(initial_conditions, bindings, v)
end
return
end
function collect_guesses!(guesses::SymmapT, v::SymbolicT)
return Moshi.Match.@match v begin
BSImpl.Const() => return
BSImpl.Term(; f, args) && if f === getindex end => begin
collect_guesses!(guesses, args[1])
end
_ => begin
def = getguess(v)
def === nothing && return
get!(guesses, v, BSImpl.Const{VartypeT}(def))
end
end
end
function collect_guesses!(guesses::SymmapT, vars::Vector{SymbolicT})
for v in vars
collect_guesses!(guesses, v)
end
return
end
"""
$TYPEDSIGNATURES
Populate `vars` with a mapping from the name of each symbolic variable in `xs` to that variable.
"""
function collect_var_to_name!(vars::Dict{Symbol, SymbolicT}, xs::Vector{SymbolicT})
for x in xs
SU.isconst(x) && continue
x = split_indexed_var(x)[1]
hasname(x) || continue
nm = getname(x)
if !isequal(get(vars, nm, x), x)
throw(
ArgumentError(
"""
Found variables with duplicate names! $x and $(vars[nm]) have the same \
name but are not identical. This is not allowed.
"""
)
)
end
vars[nm] = x
end
return
end
"""
Throw error when difference/derivative operation occurs in the R.H.S.
"""
@noinline function throw_invalid_operator(opvar, eq, op::Type)
if op === Differential
optext = "derivative"
end
msg = "The $optext variable must be isolated to the left-hand " *
"side of the equation like `$opvar ~ ...`. You may want to use `mtkcompile` or the DAE form.\nGot $eq."
throw(InvalidSystemException(msg))
end
"""
Check if difference/derivative operation occurs in the R.H.S. of an equation
"""
function _check_operator_variables(eq, op::T, expr = eq.rhs, visited = Base.IdSet{BasicSymbolic}()) where {T}
iscall(expr) || return nothing
expr in visited && return nothing
push!(visited, expr)
if operation(expr) isa op
throw_invalid_operator(expr, eq, op)
end
return foreach(
arg -> _check_operator_variables(eq, op, arg, visited),
SymbolicUtils.arguments(expr)
)
end
"""
Check if all the LHS are unique
"""
function check_operator_variables(eqs, ::Type{op}) where {op}
ops = Set{SymbolicT}()
tmp = Set{SymbolicT}()
visited = Base.IdSet{BasicSymbolic}()
for eq in eqs
_check_operator_variables(eq, op, eq.rhs, visited)
SU.search_variables!(tmp, eq.lhs; is_atomic = OperatorIsAtomic{Differential}())
if length(tmp) == 1
x = only(tmp)
if op === Differential
is_tmp_fine = isdifferential(x)
else
is_tmp_fine = iscall(x) && !(operation(x) isa op)
end
else
nd = count(x -> iscall(x) && !(operation(x) isa op), tmp)
is_tmp_fine = iszero(nd)
end
is_tmp_fine ||
error(lazy"The LHS cannot contain nondifferentiated variables. Please run `mtkcompile` or use the DAE form.\nGot $eq")
for v in tmp
v in ops &&
error(lazy"The LHS operator must be unique. Please run `mtkcompile` or use the DAE form. $v appears in LHS more than once.")
push!(ops, v)
end
empty!(tmp)
empty!(visited)
end
return
end
isoperator(::Any, ::Type{T}) where {T} = false
isoperator(ex::Union{Num, Arr, CallAndWrap}, ::Type{op}) where {op} = isoperator(unwrap(ex), op)
function isoperator(expr::SymbolicT, ::Type{op}) where {op <: SU.Operator}
return Moshi.Match.@match expr begin
BSImpl.Term(; f) => f isa op
_ => false
end
end
isoperator(::Type{op}) where {op <: SU.Operator} = Base.Fix2(isoperator, op)
isdifferential(expr) = isoperator(expr, Differential)
isdiffeq(eq) = isdifferential(eq.lhs) || isoperator(eq.lhs, Shift)
isvariable(x::Num)::Bool = isvariable(value(x))
function isvariable(x)
x isa SymbolicT || return false
return hasmetadata(x, VariableSource) || iscall(x) && operation(x) === getindex && isvariable(arguments(x)[1])::Bool
end
function collect_operator_variables(sys::AbstractSystem, args...)
return collect_operator_variables(equations(sys), args...)
end
function collect_operator_variables(eq::Equation, args...)
return collect_operator_variables([eq], args...)
end
"""
collect_operator_variables(eqs::Vector{Equation}, ::Type{op}) where {op}
Return a `Set` containing all variables that have Operator `op` applied to them.
See also [`collect_differential_variables`](@ref).
"""
function collect_operator_variables(eqs::Vector{Equation}, ::Type{op}) where {op}
vars = Set{SymbolicT}()
diffvars = Set{SymbolicT}()
for eq in eqs
SU.search_variables!(vars, eq; is_atomic = OperatorIsAtomic{op}())
for v in vars
isoperator(v, op) || continue
push!(diffvars, arguments(v)[1])
end
empty!(vars)
end
return diffvars
end
collect_differential_variables(sys) = collect_operator_variables(sys, Differential)
"""
collect_applied_operators(x, op)
Return a `Set` with all applied operators in `x`, example:
```
@independent_variables t
@variables u(t) y(t)
D = Differential(t)
eq = D(y) ~ u
ModelingToolkitBase.collect_applied_operators(eq, Differential) == Set([D(y)])
```
The difference compared to `collect_operator_variables` is that `collect_operator_variables` returns the variable without the operator applied.
"""
function collect_applied_operators(x, ::Type{op}) where {op}
v = Set{SymbolicT}()
SU.search_variables!(v, x; is_atomic = OnlyOperatorIsAtomic{op}())
return v
end
"""
$(TYPEDSIGNATURES)
Search through equations and parameter dependencies of `sys`, where sys is at a depth of
`depth` from the root system, looking for variables scoped to the root system. Also
recursively searches through all subsystems of `sys`, increasing the depth if it is not
`-1`. A depth of `-1` indicates searching for variables with `GlobalScope`.
"""
function collect_scoped_vars!(unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, sys::AbstractSystem, iv::Union{SymbolicT, Nothing}, ::Type{op} = Differential; depth = 1) where {op}
if has_eqs(sys)
for eq in equations(sys)
eqtype_supports_collect_vars(eq) || continue
# Catalyst stores `Reaction`s in `equations(sys)`
if eq isa Equation
is_numeric_symtype(SU.symtype(eq.lhs)) || continue
end
collect_vars!(unknowns, parameters, eq, iv, op; depth)
end
end
if has_jumps(sys)
for eq in jumps(sys)
eqtype_supports_collect_vars(eq) || continue
collect_vars!(unknowns, parameters, eq, iv, op; depth)
end
end
return if has_constraints(sys)
for eq in constraints(sys)
eqtype_supports_collect_vars(eq) || continue
collect_vars!(unknowns, parameters, eq, iv, op; depth)
end
end
end
"""
$(TYPEDSIGNATURES)
Check whether the usage of operator `op` is valid in a system with independent variable
`iv`. If the system is time-independent, `iv` should be `nothing`. Throw an appropriate
error if `op` is invalid. `args` are the arguments to `op`.
# Keyword arguments
- `context`: The place where the operator occurs in the system/expression, or any other
relevant information. Useful for providing extra information in the error message.
"""
function validate_operator(op, args, iv; context = nothing)
error("`$validate_operator` is not implemented for operator `$op` in $context.")
end
function validate_operator(op::Differential, args, iv; context = nothing)
isequal(op.x, iv) || throw(OperatorIndepvarMismatchError(op, iv, context))
arg = unwrap(only(args))
return if !is_variable_floatingpoint(arg)
throw(ContinuousOperatorDiscreteArgumentError(op, arg, context))
end
end
struct ContinuousOperatorDiscreteArgumentError <: Exception
op::Any
arg::Any
context::Any
end
function Base.showerror(io::IO, err::ContinuousOperatorDiscreteArgumentError)
return print(
io, """
Operator $(err.op) expects continuous arguments, with a `symtype` such as `Number`,
`Real`, `Complex` or a subtype of `AbstractFloat`. Found $(err.arg) with a symtype of
$(symtype(err.arg))$(err.context === nothing ? "." : "in $(err.context).")
"""
)
end
struct OperatorIndepvarMismatchError <: Exception
op::Any
iv::Any
context::Any
end
function Base.showerror(io::IO, err::OperatorIndepvarMismatchError)
print(
io, """
Encountered operator `$(err.op)` which has different independent variable than the \
one used in the system `$(err.iv)`.
"""
)
return if err.context !== nothing
println(io)
print(io, "Context:\n$(err.context)")
end
end
struct OnlyOperatorIsAtomic{O} end
function (::OnlyOperatorIsAtomic{O})(ex::SymbolicT) where {O}
return Moshi.Match.@match ex begin
BSImpl.Term(; f) && if f isa O end => true
_ => false
end
end
struct OperatorIsAtomic{O} end
function (::OperatorIsAtomic{O})(ex::SymbolicT) where {O}
return SU.default_is_atomic(ex) && Moshi.Match.@match ex begin
BSImpl.Term(; f) && if f isa Operator end => f isa O
_ => true
end
end
const AnyInterval{T} = DomainSets.Interval{A, B, T} where {A, B}
"""
$(TYPEDSIGNATURES)
Search through `expr` for all symbolic variables present in it. Populate `dvs` with
unknowns and `ps` with parameters present. `iv` should be the independent variable of the
system or `nothing` for time-independent systems. Expressions where the operator `isa op`
go through `validate_operator`.
`depth` is a keyword argument which indicates how many levels down `expr` is from the root
of the system hierarchy. This is used to resolve scoping operators. The scope of a variable
can be checked using `check_scope_depth`.
This function should return `nothing`.
"""
function collect_vars!(unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, expr::SymbolicT, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator; depth = 0) where {op}
Moshi.Match.@match expr begin
BSImpl.Const() => return
BSImpl.Sym() => return collect_var!(unknowns, parameters, expr, iv; depth)
BSImpl.Term(; f) && if f isa Integral end => begin
# Handle Integral operators at expression level - discover parameters in domain bounds
# This must be done here since search_variables! returns leaf variables, not the Integral term
domain = f.domain.domain
if domain isa AnyInterval{Num}
lo, hi = unwrap.(DomainSets.endpoints(domain))
elseif domain isa AnyInterval{SymbolicT}
lo, hi = DomainSets.endpoints(domain)
elseif domain isa AnyInterval
lo = hi = COMMON_NOTHING
else
throw(
ArgumentError(
"""
ModelingToolkit does not support nonstandard intervals. Only \
`DomainSets.Interval` is supported.
"""
)
)
end
collect_vars!(unknowns, parameters, lo, iv, op; depth)
collect_vars!(unknowns, parameters, hi, iv, op; depth)
end
_ => nothing
end
vars = OrderedSet{SymbolicT}()
othervars = OrderedSet{SymbolicT}()
SU.search_variables!(vars, expr; is_atomic = OperatorIsAtomic{op}())
for var in vars
Moshi.Match.@match var begin
BSImpl.Const() => nothing
BSImpl.Term(; f, args) && if f isa op end => begin
validate_operator(f, args, iv; context = expr)
isempty(args) && continue
push!(vars, args[1])
end
BSImpl.Term(; f, args) && if iv isa SymbolicT && f isa SymbolicT && !isequal(args[1], iv) end => begin
# We know this isn't a called function symbolic, since our `is_atomic` filter
# wouldn't pick it up. Any variable then must have exactly one argument.
if length(args) > 1
throw(
ArgumentError(
"""
Time-dependent variables must have exactly one independent \
variable argument. Found $(var) with multiple arguments.
"""
)
)
end
# `EvalAt`/delayed variables
Moshi.Match.@match args[1] begin
# `y(x(t))` is a valid variable, used by ControlSystemsMTK. Needs to be
# handled separately.
BSImpl.Term(; f) && if f isa SymbolicT && !SU.is_function_symbolic(f) end => begin
collect_var!(unknowns, parameters, var, iv; depth)
collect_var!(unknowns, parameters, args[1], iv; depth)
end
_ => collect_var!(unknowns, parameters, f(iv), iv; depth)
end
# Also discover parameters used in the time argument
collect_vars!(unknowns, parameters, args[1], iv, op; depth)
end
_ => collect_var!(unknowns, parameters, var, iv; depth)
end
end
return nothing
end
function collect_vars!(unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, expr::AbstractArray, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator; depth = 0) where {op}
for var in expr
collect_vars!(unknowns, parameters, var, iv, op; depth)
end
return nothing
end
"""
$(TYPEDSIGNATURES)
Indicate whether the given equation type (Equation, Pair, etc) supports `collect_vars!`.
Can be dispatched by higher-level libraries to indicate support.
"""
eqtype_supports_collect_vars(eq) = false
eqtype_supports_collect_vars(eq::Equation) = true
eqtype_supports_collect_vars(eq::Inequality) = true
eqtype_supports_collect_vars(eq::Pair) = true
function collect_vars!(
unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, eq::Union{Equation, Inequality}, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator;
depth = 0
) where {op}
collect_vars!(unknowns, parameters, eq.lhs, iv, op; depth)
collect_vars!(unknowns, parameters, eq.rhs, iv, op; depth)
return nothing
end
function collect_vars!(
unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, ex::Union{Num, Arr, CallAndWrap}, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator; depth = 0
) where {op}
return collect_vars!(unknowns, parameters, unwrap(ex), iv, op; depth)
end
function collect_vars!(
unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, p::Pair, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator; depth = 0
) where {op}
collect_vars!(unknowns, parameters, p[1], iv, op; depth)
collect_vars!(unknowns, parameters, p[2], iv, op; depth)
return nothing
end
function collect_vars!(
unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, expr, iv::Union{SymbolicT, Nothing}, ::Type{op} = Symbolics.Operator; depth = 0
) where {op}
return nothing
end
# Break the inference cycle between the mutually recursive collectors. Julia 1.10
# can otherwise miscompile the cycle after unrelated method additions. The
# abstractly typed cell keeps downstream `collect_vars!` dispatch dynamic, while
# the explicit keyword preserves metadata recursion's depth-zero semantics.
const _COLLECT_VARS_DISPATCH = Ref{Function}(collect_vars!)
@noinline Base.@constprop :none function _call_collect_vars!(
unknowns, parameters, expr, iv
)
return _COLLECT_VARS_DISPATCH[](unknowns, parameters, expr, iv; depth = 0)
end
"""
$(TYPEDSIGNATURES)
Identify whether `var` belongs to the current system using `depth` and scoping information.
Add `var` to `unknowns` or `parameters` appropriately, and search through any expressions
in known metadata of `var` using `collect_vars!`.
"""
function collect_var!(unknowns::OrderedSet{SymbolicT}, parameters::OrderedSet{SymbolicT}, var::SymbolicT, iv::Union{SymbolicT, Nothing}; depth = 0)
isequal(var, iv) && return nothing
if Symbolics.iswrapped(var)
error(
"""
Internal Error. Please open an issue with an MWE.
Encountered a wrapped value in `collect_var!`. This function should only ever \
receive unwrapped symbolic variables. This is likely a bug in the code generating \
an expression passed to `collect_vars!` or `collect_scoped_vars!`. A common cause \
is using `substitute` with rules where the values are \
wrapped symbolic variables.
"""
)
end
arr, isarr = split_indexed_var(var)
if isarr && (
# `var` is indexed, and it is an array, so it must be a slice. Replace it with `arr`.
SU.is_array_shape(SU.shape(var)) ||
# `var` is of the form `x[i]` where `i` is also a variable/expression
any(!SU.isconst, Iterators.drop(arguments(var), 1))
)
for arg in Iterators.drop(arguments(var), 1)
_call_collect_vars!(unknowns, parameters, arg, iv)
end
var = arr
end
check_scope_depth(getmetadata(arr, SymScope, LocalScope())::AllScopes, depth) || return nothing
var = setmetadata(var, SymScope, LocalScope())
if iscalledparameter(var)
callable = getcalledparameter(var)
push!(parameters, callable)
_call_collect_vars!(unknowns, parameters, arguments(var), iv)
elseif isparameter(var) || (iscall(var) && isparameter(operation(var)))
push!(parameters, var)
else
push!(unknowns, var)
end
# Add also any parameters that appear only as defaults in the var
if hasdefault(var) && (def = getdefault(var)) !== missing
if def isa SymbolicT
_call_collect_vars!(unknowns, parameters, def, iv)
elseif def isa Num