-
-
Notifications
You must be signed in to change notification settings - Fork 210
/
abstractsystem.jl
3501 lines (3101 loc) · 115 KB
/
abstractsystem.jl
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
const SYSTEM_COUNT = Threads.Atomic{UInt}(0)
get_component_type(x::AbstractSystem) = get_gui_metadata(x).type
struct GUIMetadata
type::GlobalRef
layout::Any
end
GUIMetadata(type) = GUIMetadata(type, nothing)
"""
```julia
calculate_tgrad(sys::AbstractTimeDependentSystem)
```
Calculate the time gradient of a system.
Returns a vector of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_tgrad end
"""
```julia
calculate_gradient(sys::AbstractSystem)
```
Calculate the gradient of a scalar system.
Returns a vector of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_gradient end
"""
```julia
calculate_jacobian(sys::AbstractSystem)
```
Calculate the Jacobian matrix of a system.
Returns a matrix of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_jacobian end
"""
```julia
calculate_control_jacobian(sys::AbstractSystem)
```
Calculate the Jacobian matrix of a system with respect to the system's controls.
Returns a matrix of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_control_jacobian end
"""
```julia
calculate_factorized_W(sys::AbstractSystem)
```
Calculate the factorized W-matrix of a system.
Returns a matrix of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_factorized_W end
"""
```julia
calculate_hessian(sys::AbstractSystem)
```
Calculate the hessian matrix of a scalar system.
Returns a matrix of [`Num`](@ref) instances. The result from the first
call will be cached in the system object.
"""
function calculate_hessian end
"""
```julia
generate_tgrad(sys::AbstractTimeDependentSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; kwargs...)
```
Generates a function for the time gradient of a system. Extra arguments control
the arguments to the internal [`build_function`](@ref) call.
"""
function generate_tgrad end
"""
```julia
generate_gradient(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; kwargs...)
```
Generates a function for the gradient of a system. Extra arguments control
the arguments to the internal [`build_function`](@ref) call.
"""
function generate_gradient end
"""
```julia
generate_jacobian(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; sparse = false, kwargs...)
```
Generates a function for the Jacobian matrix of a system. Extra arguments control
the arguments to the internal [`build_function`](@ref) call.
"""
function generate_jacobian end
"""
```julia
generate_factorized_W(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; sparse = false, kwargs...)
```
Generates a function for the factorized W matrix of a system. Extra arguments control
the arguments to the internal [`build_function`](@ref) call.
"""
function generate_factorized_W end
"""
```julia
generate_hessian(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; sparse = false, kwargs...)
```
Generates a function for the hessian matrix of a system. Extra arguments control
the arguments to the internal [`build_function`](@ref) call.
"""
function generate_hessian end
"""
```julia
generate_function(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys),
expression = Val{true}; kwargs...)
```
Generate a function to evaluate the system's equations.
"""
function generate_function end
"""
```julia
generate_custom_function(sys::AbstractSystem, exprs, dvs = unknowns(sys),
ps = parameters(sys); kwargs...)
```
Generate a function to evaluate `exprs`. `exprs` is a symbolic expression or
array of symbolic expression involving symbolic variables in `sys`. The symbolic variables
may be subsetted using `dvs` and `ps`. All `kwargs` are passed to the internal
[`build_function`](@ref) call. The returned function can be called as `f(u, p, t)` or
`f(du, u, p, t)` for time-dependent systems and `f(u, p)` or `f(du, u, p)` for
time-independent systems. If `split=true` (the default) was passed to [`complete`](@ref),
[`structural_simplify`](@ref) or [`@mtkbuild`](@ref), `p` is expected to be an `MTKParameters`
object.
"""
function generate_custom_function(sys::AbstractSystem, exprs, dvs = unknowns(sys),
ps = parameters(sys); wrap_code = nothing, postprocess_fbody = nothing, states = nothing,
expression = Val{true}, eval_expression = false, eval_module = @__MODULE__, kwargs...)
if !iscomplete(sys)
error("A completed system is required. Call `complete` or `structural_simplify` on the system.")
end
p = reorder_parameters(sys, unwrap.(ps))
isscalar = !(exprs isa AbstractArray)
if wrap_code === nothing
wrap_code = isscalar ? identity : (identity, identity)
end
pre, sol_states = get_substitutions_and_solved_unknowns(sys, isscalar ? [exprs] : exprs)
if postprocess_fbody === nothing
postprocess_fbody = pre
end
if states === nothing
states = sol_states
end
fnexpr = if is_time_dependent(sys)
build_function(exprs,
dvs,
p...,
get_iv(sys);
kwargs...,
postprocess_fbody,
states,
wrap_code = wrap_code .∘ wrap_mtkparameters(sys, isscalar) .∘
wrap_array_vars(sys, exprs; dvs) .∘
wrap_parameter_dependencies(sys, isscalar),
expression = Val{true}
)
else
build_function(exprs,
dvs,
p...;
kwargs...,
postprocess_fbody,
states,
wrap_code = wrap_code .∘ wrap_mtkparameters(sys, isscalar) .∘
wrap_array_vars(sys, exprs; dvs) .∘
wrap_parameter_dependencies(sys, isscalar),
expression = Val{true}
)
end
if expression == Val{true}
return fnexpr
end
if fnexpr isa Tuple
return eval_or_rgf.(fnexpr; eval_expression, eval_module)
else
return eval_or_rgf(fnexpr; eval_expression, eval_module)
end
end
function wrap_assignments(isscalar, assignments; let_block = false)
function wrapper(expr)
Func(expr.args, [], Let(assignments, expr.body, let_block))
end
if isscalar
wrapper
else
wrapper, wrapper
end
end
function wrap_parameter_dependencies(sys::AbstractSystem, isscalar)
wrap_assignments(isscalar, [eq.lhs ← eq.rhs for eq in parameter_dependencies(sys)])
end
function wrap_array_vars(
sys::AbstractSystem, exprs; dvs = unknowns(sys), ps = parameters(sys),
inputs = nothing, history = false)
isscalar = !(exprs isa AbstractArray)
array_vars = Dict{Any, AbstractArray{Int}}()
if dvs !== nothing
for (j, x) in enumerate(dvs)
if iscall(x) && operation(x) == getindex
arg = arguments(x)[1]
inds = get!(() -> Int[], array_vars, arg)
push!(inds, j)
end
end
for (k, inds) in array_vars
if inds == (inds′ = inds[1]:inds[end])
array_vars[k] = inds′
end
end
uind = 1
else
uind = 0
end
# values are (indexes, index of buffer, size of parameter)
array_parameters = Dict{Any, Tuple{AbstractArray{Int}, Int, Tuple{Vararg{Int}}}}()
# If for some reason different elements of an array parameter are in different buffers
other_array_parameters = Dict{Any, Any}()
hasinputs = inputs !== nothing
input_vars = Dict{Any, AbstractArray{Int}}()
if hasinputs
for (j, x) in enumerate(inputs)
if iscall(x) && operation(x) == getindex
arg = arguments(x)[1]
inds = get!(() -> Int[], input_vars, arg)
push!(inds, j)
end
end
for (k, inds) in input_vars
if inds == (inds′ = inds[1]:inds[end])
input_vars[k] = inds′
end
end
end
if has_index_cache(sys)
ic = get_index_cache(sys)
else
ic = nothing
end
if ps isa Tuple && eltype(ps) <: AbstractArray
ps = Iterators.flatten(ps)
end
for p in ps
p = unwrap(p)
if iscall(p) && operation(p) == getindex
p = arguments(p)[1]
end
symtype(p) <: AbstractArray && Symbolics.shape(p) != Symbolics.Unknown() || continue
scal = collect(p)
# all scalarized variables are in `ps`
any(isequal(p), ps) || all(x -> any(isequal(x), ps), scal) || continue
(haskey(array_parameters, p) || haskey(other_array_parameters, p)) && continue
idx = parameter_index(sys, p)
idx isa Int && continue
if idx isa ParameterIndex
if idx.portion != SciMLStructures.Tunable()
continue
end
array_parameters[p] = (vec(idx.idx), 1, size(idx.idx))
else
# idx === nothing
idxs = map(Base.Fix1(parameter_index, sys), scal)
if first(idxs) isa ParameterIndex
buffer_idxs = map(Base.Fix1(iterated_buffer_index, ic), idxs)
if allequal(buffer_idxs)
buffer_idx = first(buffer_idxs)
if first(idxs).portion == SciMLStructures.Tunable()
idxs = map(x -> x.idx, idxs)
else
idxs = map(x -> x.idx[end], idxs)
end
else
other_array_parameters[p] = scal
continue
end
else
buffer_idx = 1
end
sz = size(idxs)
if vec(idxs) == idxs[begin]:idxs[end]
idxs = idxs[begin]:idxs[end]
elseif vec(idxs) == idxs[begin]:-1:idxs[end]
idxs = idxs[begin]:-1:idxs[end]
end
idxs = vec(idxs)
array_parameters[p] = (idxs, buffer_idx, sz)
end
end
inputind = if history
uind + 2
else
uind + 1
end
params_offset = if history && hasinputs
uind + 2
elseif history || hasinputs
uind + 1
else
uind
end
if isscalar
function (expr)
Func(
expr.args,
[],
Let(
vcat(
[k ← :(view($(expr.args[uind].name), $v)) for (k, v) in array_vars],
[k ← :(view($(expr.args[inputind].name), $v))
for (k, v) in input_vars],
[k ← :(reshape(
view($(expr.args[params_offset + buffer_idx].name), $idxs),
$sz))
for (k, (idxs, buffer_idx, sz)) in array_parameters],
[k ← Code.MakeArray(v, symtype(k))
for (k, v) in other_array_parameters]
),
expr.body,
false
)
)
end
else
function (expr)
Func(
expr.args,
[],
Let(
vcat(
[k ← :(view($(expr.args[uind].name), $v)) for (k, v) in array_vars],
[k ← :(view($(expr.args[inputind].name), $v))
for (k, v) in input_vars],
[k ← :(reshape(
view($(expr.args[params_offset + buffer_idx].name), $idxs),
$sz))
for (k, (idxs, buffer_idx, sz)) in array_parameters],
[k ← Code.MakeArray(v, symtype(k))
for (k, v) in other_array_parameters]
),
expr.body,
false
)
)
end,
function (expr)
Func(
expr.args,
[],
Let(
vcat(
[k ← :(view($(expr.args[uind + 1].name), $v))
for (k, v) in array_vars],
[k ← :(view($(expr.args[inputind + 1].name), $v))
for (k, v) in input_vars],
[k ← :(reshape(
view($(expr.args[params_offset + buffer_idx + 1].name),
$idxs),
$sz))
for (k, (idxs, buffer_idx, sz)) in array_parameters],
[k ← Code.MakeArray(v, symtype(k))
for (k, v) in other_array_parameters]
),
expr.body,
false
)
)
end
end
end
const MTKPARAMETERS_ARG = Sym{Vector{Vector}}(:___mtkparameters___)
"""
wrap_mtkparameters(sys::AbstractSystem, isscalar::Bool, p_start = 2)
Return function(s) to be passed to the `wrap_code` keyword of `build_function` which
allow the compiled function to be called as `f(u, p, t)` where `p isa MTKParameters`
instead of `f(u, p..., t)`. `isscalar` denotes whether the function expression being
wrapped is for a scalar value. `p_start` is the index of the argument containing
the first parameter vector in the out-of-place version of the function. For example,
if a history function (DDEs) was passed before `p`, then the function before wrapping
would have the signature `f(u, h, p..., t)` and hence `p_start` would need to be `3`.
The returned function is `identity` if the system does not have an `IndexCache`.
"""
function wrap_mtkparameters(sys::AbstractSystem, isscalar::Bool, p_start = 2)
if has_index_cache(sys) && get_index_cache(sys) !== nothing
offset = Int(is_time_dependent(sys))
if isscalar
function (expr)
param_args = expr.args[p_start:(end - offset)]
param_buffer_idxs = findall(x -> x isa DestructuredArgs, param_args)
param_buffer_args = param_args[param_buffer_idxs]
destructured_mtkparams = DestructuredArgs(
[x.name for x in param_buffer_args],
MTKPARAMETERS_ARG; inds = param_buffer_idxs)
Func(
[
expr.args[begin:(p_start - 1)]...,
destructured_mtkparams,
expr.args[(end - offset + 1):end]...
],
[],
Let(param_buffer_args, expr.body, false)
)
end
else
function (expr)
param_args = expr.args[p_start:(end - offset)]
param_buffer_idxs = findall(x -> x isa DestructuredArgs, param_args)
param_buffer_args = param_args[param_buffer_idxs]
destructured_mtkparams = DestructuredArgs(
[x.name for x in param_buffer_args],
MTKPARAMETERS_ARG; inds = param_buffer_idxs)
Func(
[
expr.args[begin:(p_start - 1)]...,
destructured_mtkparams,
expr.args[(end - offset + 1):end]...
],
[],
Let(param_buffer_args, expr.body, false)
)
end,
function (expr)
param_args = expr.args[(p_start + 1):(end - offset)]
param_buffer_idxs = findall(x -> x isa DestructuredArgs, param_args)
param_buffer_args = param_args[param_buffer_idxs]
destructured_mtkparams = DestructuredArgs(
[x.name for x in param_buffer_args],
MTKPARAMETERS_ARG; inds = param_buffer_idxs)
Func(
[
expr.args[begin:p_start]...,
destructured_mtkparams,
expr.args[(end - offset + 1):end]...
],
[],
Let(param_buffer_args, expr.body, false)
)
end
end
else
identity
end
end
mutable struct Substitutions
subs::Vector{Equation}
deps::Vector{Vector{Int}}
subed_eqs::Union{Nothing, Vector{Equation}}
end
Substitutions(subs, deps) = Substitutions(subs, deps, nothing)
Base.nameof(sys::AbstractSystem) = getfield(sys, :name)
description(sys::AbstractSystem) = has_description(sys) ? get_description(sys) : ""
#Deprecated
function independent_variable(sys::AbstractSystem)
Base.depwarn(
"`independent_variable` is deprecated. Use `get_iv` or `independent_variables` instead.",
:independent_variable)
isdefined(sys, :iv) ? getfield(sys, :iv) : nothing
end
function independent_variables(sys::AbstractTimeDependentSystem)
return [getfield(sys, :iv)]
end
independent_variables(::AbstractTimeIndependentSystem) = []
function independent_variables(sys::AbstractMultivariateSystem)
return getfield(sys, :ivs)
end
"""
$(TYPEDSIGNATURES)
Get the independent variable(s) of the system `sys`.
See also [`@independent_variables`](@ref) and [`ModelingToolkit.get_iv`](@ref).
"""
function independent_variables(sys::AbstractSystem)
@warn "Please declare ($(typeof(sys))) as a subtype of `AbstractTimeDependentSystem`, `AbstractTimeIndependentSystem` or `AbstractMultivariateSystem`."
if isdefined(sys, :iv)
return [getfield(sys, :iv)]
elseif isdefined(sys, :ivs)
return getfield(sys, :ivs)
else
return []
end
end
#Treat the result as a vector of symbols always
function SymbolicIndexingInterface.is_variable(sys::AbstractSystem, sym)
sym = unwrap(sym)
if sym isa Int # [x, 1] coerces 1 to a Num
return sym in 1:length(variable_symbols(sys))
end
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return is_variable(ic, sym) ||
iscall(sym) && operation(sym) === getindex &&
is_variable(ic, first(arguments(sym)))
end
return any(isequal(sym), variable_symbols(sys)) ||
hasname(sym) && is_variable(sys, getname(sym))
end
function SymbolicIndexingInterface.is_variable(sys::AbstractSystem, sym::Symbol)
sym = unwrap(sym)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return is_variable(ic, sym)
end
return any(isequal(sym), getname.(variable_symbols(sys))) ||
count(NAMESPACE_SEPARATOR, string(sym)) == 1 &&
count(isequal(sym),
Symbol.(nameof(sys), NAMESPACE_SEPARATOR_SYMBOL, getname.(variable_symbols(sys)))) ==
1
end
function SymbolicIndexingInterface.variable_index(sys::AbstractSystem, sym)
sym = unwrap(sym)
if sym isa Int
return sym
end
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return if (idx = variable_index(ic, sym)) !== nothing
idx
elseif iscall(sym) && operation(sym) === getindex &&
(idx = variable_index(ic, first(arguments(sym)))) !== nothing
idx[arguments(sym)[(begin + 1):end]...]
else
nothing
end
end
idx = findfirst(isequal(sym), variable_symbols(sys))
if idx === nothing && hasname(sym)
idx = variable_index(sys, getname(sym))
end
return idx
end
function SymbolicIndexingInterface.variable_index(sys::AbstractSystem, sym::Symbol)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return variable_index(ic, sym)
end
idx = findfirst(isequal(sym), getname.(variable_symbols(sys)))
if idx !== nothing
return idx
elseif count(NAMESPACE_SEPARATOR, string(sym)) == 1
return findfirst(isequal(sym),
Symbol.(
nameof(sys), NAMESPACE_SEPARATOR_SYMBOL, getname.(variable_symbols(sys))))
end
return nothing
end
SymbolicIndexingInterface.variable_symbols(sys::AbstractMultivariateSystem) = sys.dvs
function SymbolicIndexingInterface.variable_symbols(sys::AbstractSystem)
return solved_unknowns(sys)
end
function SymbolicIndexingInterface.is_parameter(sys::AbstractSystem, sym)
sym = unwrap(sym)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return sym isa ParameterIndex || is_parameter(ic, sym) ||
iscall(sym) &&
operation(sym) === getindex &&
is_parameter(ic, first(arguments(sym)))
end
if unwrap(sym) isa Int
return unwrap(sym) in 1:length(parameter_symbols(sys))
end
return any(isequal(sym), parameter_symbols(sys)) ||
hasname(sym) && !(iscall(sym) && operation(sym) == getindex) &&
is_parameter(sys, getname(sym))
end
function SymbolicIndexingInterface.is_parameter(sys::AbstractSystem, sym::Symbol)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return is_parameter(ic, sym)
end
named_parameters = [getname(x)
for x in parameter_symbols(sys)
if hasname(x) && !(iscall(x) && operation(x) == getindex)]
return any(isequal(sym), named_parameters) ||
count(NAMESPACE_SEPARATOR, string(sym)) == 1 &&
count(isequal(sym),
Symbol.(nameof(sys), NAMESPACE_SEPARATOR_SYMBOL, named_parameters)) == 1
end
function SymbolicIndexingInterface.parameter_index(sys::AbstractSystem, sym)
sym = unwrap(sym)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return if sym isa ParameterIndex
sym
elseif (idx = parameter_index(ic, sym)) !== nothing
idx
elseif iscall(sym) && operation(sym) === getindex &&
(idx = parameter_index(ic, first(arguments(sym)))) !== nothing
if idx.portion isa SciMLStructures.Tunable
return ParameterIndex(
idx.portion, idx.idx[arguments(sym)[(begin + 1):end]...])
else
return ParameterIndex(
idx.portion, (idx.idx..., arguments(sym)[(begin + 1):end]...))
end
else
nothing
end
end
if sym isa Int
return sym
end
idx = findfirst(isequal(sym), parameter_symbols(sys))
if idx === nothing && hasname(sym) && !(iscall(sym) && operation(sym) == getindex)
idx = parameter_index(sys, getname(sym))
end
return idx
end
function SymbolicIndexingInterface.parameter_index(sys::AbstractSystem, sym::Symbol)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
idx = parameter_index(ic, sym)
if idx === nothing ||
idx.portion isa SciMLStructures.Discrete && idx.idx[2] == idx.idx[3] == 0
return nothing
else
return idx
end
end
pnames = [getname(x)
for x in parameter_symbols(sys)
if hasname(x) && !(iscall(x) && operation(x) == getindex)]
idx = findfirst(isequal(sym), pnames)
if idx !== nothing
return idx
elseif count(NAMESPACE_SEPARATOR, string(sym)) == 1
return findfirst(isequal(sym),
Symbol.(
nameof(sys), NAMESPACE_SEPARATOR_SYMBOL, pnames))
end
return nothing
end
function SymbolicIndexingInterface.is_timeseries_parameter(sys::AbstractSystem, sym)
is_time_dependent(sys) || return false
has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing || return false
is_timeseries_parameter(ic, sym)
end
function SymbolicIndexingInterface.timeseries_parameter_index(sys::AbstractSystem, sym)
is_time_dependent(sys) || return nothing
has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing || return nothing
timeseries_parameter_index(ic, sym)
end
function SymbolicIndexingInterface.parameter_observed(sys::AbstractSystem, sym)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
rawobs = build_explicit_observed_function(
sys, sym; param_only = true, return_inplace = true)
if rawobs isa Tuple
if is_time_dependent(sys)
obsfn = let oop = rawobs[1], iip = rawobs[2]
f1a(p, t) = oop(p, t)
f1a(out, p, t) = iip(out, p, t)
end
else
obsfn = let oop = rawobs[1], iip = rawobs[2]
f1b(p) = oop(p)
f1b(out, p) = iip(out, p)
end
end
else
obsfn = rawobs
end
else
obsfn = build_explicit_observed_function(sys, sym; param_only = true)
end
return obsfn
end
function has_observed_with_lhs(sys, sym)
has_observed(sys) || return false
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return any(isequal(sym), ic.observed_syms)
else
return any(isequal(sym), [eq.lhs for eq in observed(sys)])
end
end
function has_parameter_dependency_with_lhs(sys, sym)
has_parameter_dependencies(sys) || return false
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return any(isequal(sym), ic.dependent_pars)
else
return any(isequal(sym), [eq.lhs for eq in parameter_dependencies(sys)])
end
end
function _all_ts_idxs!(ts_idxs, ::NotSymbolic, sys, sym)
if is_variable(sys, sym) || is_independent_variable(sys, sym)
push!(ts_idxs, ContinuousTimeseries())
elseif is_timeseries_parameter(sys, sym)
push!(ts_idxs, timeseries_parameter_index(sys, sym).timeseries_idx)
end
end
# Need this to avoid ambiguity with the array case
for traitT in [
ScalarSymbolic,
ArraySymbolic
]
@eval function _all_ts_idxs!(ts_idxs, ::$traitT, sys, sym)
allsyms = vars(sym; op = Symbolics.Operator)
for s in allsyms
s = unwrap(s)
if is_variable(sys, s) || is_independent_variable(sys, s) ||
has_observed_with_lhs(sys, s)
push!(ts_idxs, ContinuousTimeseries())
elseif is_timeseries_parameter(sys, s)
push!(ts_idxs, timeseries_parameter_index(sys, s).timeseries_idx)
end
end
end
end
function _all_ts_idxs!(ts_idxs, ::ScalarSymbolic, sys, sym::Symbol)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
return _all_ts_idxs!(ts_idxs, sys, ic.symbol_to_variable[sym])
elseif is_variable(sys, sym) || is_independent_variable(sys, sym) ||
any(isequal(sym), [getname(eq.lhs) for eq in observed(sys)])
push!(ts_idxs, ContinuousTimeseries())
elseif is_timeseries_parameter(sys, sym)
push!(ts_idxs, timeseries_parameter_index(sys, s).timeseries_idx)
end
end
function _all_ts_idxs!(ts_idxs, ::NotSymbolic, sys, sym::AbstractArray)
for s in sym
_all_ts_idxs!(ts_idxs, sys, s)
end
end
_all_ts_idxs!(ts_idxs, sys, sym) = _all_ts_idxs!(ts_idxs, symbolic_type(sym), sys, sym)
function SymbolicIndexingInterface.get_all_timeseries_indexes(sys::AbstractSystem, sym)
if !is_time_dependent(sys)
return Set()
end
ts_idxs = Set()
_all_ts_idxs!(ts_idxs, sys, sym)
return ts_idxs
end
function SymbolicIndexingInterface.parameter_symbols(sys::AbstractSystem)
return parameters(sys)
end
function SymbolicIndexingInterface.is_independent_variable(sys::AbstractSystem, sym)
return any(isequal(sym), independent_variable_symbols(sys))
end
function SymbolicIndexingInterface.is_independent_variable(sys::AbstractSystem, sym::Symbol)
return any(isequal(sym), getname.(independent_variables(sys)))
end
function SymbolicIndexingInterface.independent_variable_symbols(sys::AbstractSystem)
return independent_variables(sys)
end
function SymbolicIndexingInterface.is_observed(sys::AbstractSystem, sym)
return !is_variable(sys, sym) && parameter_index(sys, sym) === nothing &&
!is_independent_variable(sys, sym) && symbolic_type(sym) != NotSymbolic()
end
function SymbolicIndexingInterface.observed(
sys::AbstractSystem, sym; eval_expression = false, eval_module = @__MODULE__)
if has_index_cache(sys) && (ic = get_index_cache(sys)) !== nothing
if sym isa Symbol
_sym = get(ic.symbol_to_variable, sym, nothing)
if _sym === nothing
throw(ArgumentError("Symbol $sym does not exist in the system"))
end
sym = _sym
elseif sym isa AbstractArray && symbolic_type(sym) isa NotSymbolic &&
any(x -> x isa Symbol, sym)
sym = map(sym) do s
if s isa Symbol
_s = get(ic.symbol_to_variable, s, nothing)
if _s === nothing
throw(ArgumentError("Symbol $s does not exist in the system"))
end
return _s
end
return unwrap(s)
end
end
end
_fn = build_explicit_observed_function(sys, sym; eval_expression, eval_module)
if is_time_dependent(sys)
return _fn
else
return let _fn = _fn
fn2(u, p) = _fn(u, p)
fn2(::Nothing, p) = _fn([], p)
fn2
end
end
end
function SymbolicIndexingInterface.default_values(sys::AbstractSystem)
return merge(
Dict(eq.lhs => eq.rhs for eq in observed(sys)),
defaults(sys)
)
end
SymbolicIndexingInterface.is_time_dependent(::AbstractTimeDependentSystem) = true
SymbolicIndexingInterface.is_time_dependent(::AbstractTimeIndependentSystem) = false
SymbolicIndexingInterface.is_markovian(sys::AbstractSystem) = !is_dde(sys)
SymbolicIndexingInterface.constant_structure(::AbstractSystem) = true
function SymbolicIndexingInterface.all_variable_symbols(sys::AbstractSystem)
syms = variable_symbols(sys)
obs = getproperty.(observed(sys), :lhs)
return isempty(obs) ? syms : vcat(syms, obs)
end
function SymbolicIndexingInterface.all_symbols(sys::AbstractSystem)
syms = all_variable_symbols(sys)
for other in (parameter_symbols(sys), independent_variable_symbols(sys))
isempty(other) || (syms = vcat(syms, other))
end
return syms
end
iscomplete(sys::AbstractSystem) = isdefined(sys, :complete) && getfield(sys, :complete)
"""
$(TYPEDSIGNATURES)
Mark a system as scheduled. It is only intended in compiler internals. A system
is scheduled after tearing based simplifications where equations are converted
into assignments.
"""
function schedule(sys::AbstractSystem)
has_schedule(sys) ? sys : (@set! sys.isscheduled = true)
end
"""
$(TYPEDSIGNATURES)
If a system is scheduled, then changing its equations, variables, and
parameters is no longer legal.
"""
function isscheduled(sys::AbstractSystem)
if has_schedule(sys)
get_schedule(sys) !== nothing
elseif has_isscheduled(sys)
get_isscheduled(sys)
else
false
end
end
"""
$(TYPEDSIGNATURES)
Mark a system as completed. A completed system is a system which is done being
defined/modified and is ready for structural analysis or other transformations.
This allows for analyses and optimizations to be performed which require knowing
the global structure of the system.
One property to note is that if a system is complete, the system will no longer
namespace its subsystems or variables, i.e. `isequal(complete(sys).v.i, v.i)`.
"""
function complete(sys::AbstractSystem; split = true, flatten = true)
if !(sys isa JumpSystem)
newunknowns = OrderedSet()
newparams = OrderedSet()
iv = has_iv(sys) ? get_iv(sys) : nothing
collect_scoped_vars!(newunknowns, newparams, sys, iv; depth = -1)
# don't update unknowns to not disturb `structural_simplify` order
# `GlobalScope`d unknowns will be picked up and added there
@set! sys.ps = unique!(vcat(get_ps(sys), collect(newparams)))
end
if flatten
eqs = equations(sys)
if eqs isa AbstractArray && eltype(eqs) <: Equation
newsys = expand_connections(sys)
else
newsys = sys
end
newsys = ModelingToolkit.flatten(newsys)
if has_parent(newsys) && get_parent(sys) === nothing
@set! newsys.parent = complete(sys; split = false, flatten = false)
end
sys = newsys
end
if split && has_index_cache(sys)
@set! sys.index_cache = IndexCache(sys)
all_ps = get_ps(sys)
if !isempty(all_ps)
# reorder parameters by portions
ps_split = reorder_parameters(sys, all_ps)
# if there are no tunables, vcat them
if isempty(get_index_cache(sys).tunable_idx)
ordered_ps = reduce(vcat, ps_split)
else
# if there are tunables, they will all be in `ps_split[1]`
# and the arrays will have been scalarized
ordered_ps = eltype(all_ps)[]
i = 1
# go through all the tunables
while i <= length(ps_split[1])
sym = ps_split[1][i]
# if the sym is not a scalarized array symbolic OR it was already scalarized,
# just push it as-is
if !iscall(sym) || operation(sym) != getindex ||
any(isequal(sym), all_ps)
push!(ordered_ps, sym)
i += 1
continue
end
# the next `length(sym)` symbols should be scalarized versions of the same
# array symbolic
if !allequal(first(arguments(x))
for x in view(ps_split[1], i:(i + length(sym) - 1)))
error("This should not be possible. Please open an issue in ModelingToolkit.jl with an MWE and stacktrace.")
end
arrsym = first(arguments(sym))
push!(ordered_ps, arrsym)
i += length(arrsym)
end
ordered_ps = vcat(
ordered_ps, reduce(vcat, ps_split[2:end]; init = eltype(ordered_ps)[]))
end
@set! sys.ps = ordered_ps
end
end
if isdefined(sys, :initializesystem) && get_initializesystem(sys) !== nothing
@set! sys.initializesystem = complete(get_initializesystem(sys); split)
end
isdefined(sys, :complete) ? (@set! sys.complete = true) : sys
end
for prop in [:eqs
:tag
:noiseeqs
:iv
:unknowns
:ps