forked from SciML/ModelingToolkit.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_utils.jl
More file actions
2115 lines (1879 loc) · 70.6 KB
/
problem_utils.jl
File metadata and controls
2115 lines (1879 loc) · 70.6 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
const AnyDict = Dict{Any, Any}
"""
$(TYPEDSIGNATURES)
If called without arguments, return `Dict{Any, Any}`. Otherwise, interpret the input
as a symbolic map and turn it into a `Dict{Any, Any}`. Handles `SciMLBase.NullParameters`,
`missing` and `nothing`.
"""
anydict() = AnyDict()
anydict(::SciMLBase.NullParameters) = AnyDict()
anydict(::Nothing) = AnyDict()
anydict(::Missing) = AnyDict()
anydict(x::AnyDict) = x
anydict(x::AbstractDict) = AnyDict(x)
function anydict(x)
op = AnyDict()
for (k, v) in x
if haskey(op, k)
throw(
ArgumentError(
"""
Found duplicate entries in symbolic map. Key $k is provided multiple \
times.
"""
)
)
end
op[k] = v
end
return op
end
"""
$(TYPEDSIGNATURES)
Check if `x` is a symbolic with known size. Assumes `SymbolicUtils.shape(unwrap(x))`
is a valid operation.
"""
symbolic_has_known_size(x) = !(SU.shape(unwrap(x)) isa SU.Unknown)
"""
$(TYPEDSIGNATURES)
Check if the system is in split form (has an `IndexCache`).
"""
is_split(sys::AbstractSystem) = has_index_cache(sys) && get_index_cache(sys) !== nothing
"""
$(TYPEDSIGNATURES)
Given a variable-value mapping, add mappings for the `toterm` of each of the keys. `replace` controls whether
the old value should be removed.
"""
function add_toterms!(varmap::AbstractDict; toterm = default_toterm, replace = false)
for k in collect(keys(varmap))
ttk = toterm(unwrap(k))
haskey(varmap, ttk) && continue
varmap[ttk] = varmap[k]
!isequal(k, ttk) && replace && delete!(varmap, k)
end
return nothing
end
"""
$(TYPEDSIGNATURES)
Out-of-place version of [`add_toterms!`](@ref).
"""
function add_toterms(varmap::AbstractDict; kwargs...)
cp = copy(varmap)
add_toterms!(cp; kwargs...)
return cp
end
"""
$(TYPEDSIGNATURES)
Turn any `Symbol` keys in `varmap` to the appropriate symbolic variables in `sys`. Any
symbols that cannot be converted are ignored.
"""
function symbols_to_symbolics!(sys::AbstractSystem, varmap::AbstractDict)
return if is_split(sys)
ic = get_index_cache(sys)
for k in collect(keys(varmap))
k isa Symbol || continue
newk = get(ic.symbol_to_variable, k, nothing)
newk === nothing && continue
varmap[newk] = varmap[k]
delete!(varmap, k)
end
else
syms = all_symbols(sys)
for k in collect(keys(varmap))
k isa Symbol || continue
idx = findfirst(syms) do sym
hasname(sym) || return false
name = getname(sym)
return name == k
end
idx === nothing && continue
newk = syms[idx]
if iscall(newk) && operation(newk) === getindex
newk = arguments(newk)[1]
end
varmap[newk] = varmap[k]
delete!(varmap, k)
end
end
end
"""
$(TYPEDSIGNATURES)
Utility function to get the value `val` corresponding to key `var` in `varmap`, and
return `getindex(val, idx)` if it exists or `nothing` otherwise.
"""
function get_and_getindex(varmap, var, idx)
val = get(varmap, var, nothing)
val === nothing && return nothing
return val[idx]
end
"""
$(TYPEDSIGNATURES)
Return the list of variables in `varlist` not present in `varmap`. Uses the same criteria
for missing array variables and `toterm` forms as [`add_fallbacks!`](@ref).
"""
function missingvars(
varmap::AtomicArrayDict, varlist::Vector; toterm = default_toterm
)
missings = Set{SymbolicT}()
for var in varlist
var = unwrap(var)
get_possibly_indexed(varmap, var, COMMON_NOTHING) === COMMON_NOTHING || continue
ttsym = toterm(var)
get_possibly_indexed(varmap, ttsym, COMMON_NOTHING) === COMMON_NOTHING || continue
push!(missings, var)
end
return missings
end
"""
$(TYPEDSIGNATURES)
Attempt to interpret `vals` as a symbolic map of variables in `varlist` to values. Return
the result as a `Dict{Any, Any}`. In case `vals` is already an iterable of pairs, convert
it to a `Dict{Any, Any}` and return. If `vals` is an array (whose `eltype` is not `Pair`)
with the same length as `varlist`, assume the `i`th element of `varlist` is mapped to the
`i`th element of `vals`. Automatically `unwrap`s all keys and values in the mapping. Also
handles `SciMLBase.NullParameters` and `nothing`, both of which are interpreted as empty
maps.
"""
function to_varmap(vals, varlist::Vector)
if vals isa AbstractArray && !(eltype(vals) <: Pair) && !isempty(vals)
check_eqs_u0(varlist, varlist, vals)
vals = vec(varlist) .=> vec(vals)
end
return recursive_unwrap(anydict(vals))
end
"""
$(TYPEDSIGNATURES)
Recursively call `Symbolics.unwrap` on `x`. Useful when `x` is an array of (potentially)
symbolic values, all of which need to be unwrapped. Specializes when `x isa AbstractDict`
to unwrap keys and values, returning an `AnyDict`.
"""
function recursive_unwrap(x::AbstractArray)
return symbolic_type(x) == ArraySymbolic() ? value(x) : recursive_unwrap.(x)
end
function recursive_unwrap(x::SparseMatrixCSC)
I, J, V = findnz(x)
V = recursive_unwrap(V)
m, n = size(x)
return sparse(I, J, V, m, n)
end
recursive_unwrap(x) = value(x)
function recursive_unwrap(x::AbstractDict)
return anydict(unwrap(k) => recursive_unwrap(v) for (k, v) in x)
end
"""
$(TYPEDSIGNATURES)
Add equations `eqs` to `varmap`. Assumes each element in `eqs` maps a single symbolic
variable to an expression representing its value. In case `varmap` already contains an
entry for `eq.lhs`, insert the reverse mapping if `eq.rhs` is not a number.
"""
function add_observed_equations!(varmap::AtomicArrayDict{SymbolicT}, eqs::Vector{Equation}, bound_ps::Union{Nothing, ROSymmapT} = nothing)
for eq in eqs
if get_possibly_indexed(varmap, eq.lhs, COMMON_NOTHING) !== COMMON_NOTHING
SU.isconst(eq.rhs) && continue
get_possibly_indexed(varmap, eq.rhs, COMMON_NOTHING) !== COMMON_NOTHING && continue
bound_ps isa ROSymmapT && has_possibly_indexed_key(parent(bound_ps), eq.rhs) && continue
Moshi.Match.@match eq.rhs begin
BSImpl.Term(; f, args) && if f isa SymbolicT end => nothing
BSImpl.Sym() => nothing
_ => continue
end
write_possibly_indexed_array!(varmap, eq.rhs, eq.lhs, COMMON_NOTHING)
else
write_possibly_indexed_array!(varmap, eq.lhs, eq.rhs, COMMON_NOTHING)
end
end
return
end
"""
$(TYPEDSIGNATURES)
Add all equations in `observed(sys)` to `varmap` using [`add_observed_equations!`](@ref).
"""
function add_observed!(sys::AbstractSystem, varmap::AbstractDict)
return add_observed_equations!(varmap, observed(sys))
end
struct UnexpectedSymbolicValueInVarmap <: Exception
sym::Any
val::Any
end
function Base.showerror(io::IO, err::UnexpectedSymbolicValueInVarmap)
return println(
io,
"""
Found symbolic value $(err.val) for variable $(err.sym). You may be missing an \
initial condition or have cyclic initial conditions. If this is intended, pass \
`symbolic_u0 = true`. In case the initial conditions are not cyclic but \
require more substitutions to resolve, increase `substitution_limit`. To report \
cycles in initial conditions of unknowns/parameters, pass \
`warn_cyclic_dependency = true`. If the cycles are still not reported, you \
may need to pass a larger value for `circular_dependency_max_cycle_length` \
or `circular_dependency_max_cycles`.
"""
)
end
struct MissingGuessError <: Exception
syms::Vector{Any}
vals::Vector{Any}
end
function Base.showerror(io::IO, err::MissingGuessError)
println(
io,
"""
Cyclic guesses detected in the system. Symbolic values were found for the following \
variables/parameters in the map: \
"""
)
for (sym, val) in zip(err.syms, err.vals)
println(io, "$sym => $val")
end
return println(
io,
"""
In order to resolve this, please provide additional numeric guesses so that the \
chain can be resolved to assign numeric values to each variable. Alternatively, the \
`missing_guess_value` keyword can be used to set a fallback guess for all \
variables. The keyword must be passed an instance of the `MissingGuessValue` sum-type.
"""
)
end
const MISSING_VARIABLES_MESSAGE = """
Initial condition underdefined. Some are missing from the variable map.
Please provide a default (`u0`), initialization equation, or guess
for the following variables:
"""
struct MissingVariablesError <: Exception
vars::Any
end
function Base.showerror(io::IO, e::MissingVariablesError)
println(io, MISSING_VARIABLES_MESSAGE)
return println(io, join(e.vars, ", "))
end
"""
$TYPEDEF
A Moshi.jl enum to allow choosing what happens with missing guess values when building a
numerical problem from a `System`.
# Variants
- `MissingGuessValue.Constant(val::Number)`: Missing guesses are set to the given value
`val`.
- `MissingGuessValue.Random(rng::AbstractRNG)`: Missing guesses are set to `rand(rng)`.
- `MissingGuessValue.Error()`: Missing guess values cause an error.
"""
Moshi.Data.@data MissingGuessValue begin
Constant(Number)
Random(AbstractRNG)
Error
end
# To be overloaded downstream by MTK
default_missing_guess_value() = default_missing_guess_value(nothing)
default_missing_guess_value(_) = MissingGuessValue.Error()
"""
$(TYPEDSIGNATURES)
Return an array of values where the `i`th element corresponds to the value of `vars[i]`
in `varmap`. Will mutate `varmap` by symbolically substituting it into itself.
Keyword arguments:
- `container_type`: The type of the returned container.
- `allow_symbolic`: Whether the returned container of values can have symbolic expressions.
- `buffer_eltype`: The `eltype` of the returned container if `!allow_symbolic`. If
`Nothing`, automatically promotes the values in the container to a common `eltype`.
- `tofloat`: Whether to promote values to floating point numbers if
`buffer_eltype == Nothing`.
- `use_union`: Whether to allow using a `Union` as the `eltype` if
`buffer_eltype == Nothing`.
- `toterm`: The `toterm` function for canonicalizing keys of `varmap`. A value of `nothing`
disables this process.
- `check`: Whether to check if all of `vars` are keys of `varmap`.
- `is_initializeprob`: Whether an initialization problem is being constructed. Used for
better error messages.
- `substitution_limit`: The maximum number of times to recursively substitute `varmap` into
itself to get a numeric value for each variable in `vars`.
"""
function varmap_to_vars(
varmap::AbstractDict, vars::Vector;
tofloat = true, use_union = false, container_type = Array, buffer_eltype = Nothing,
toterm = default_toterm, check = true, allow_symbolic = false,
is_initializeprob = false, substitution_limit = 100, missing_values = MissingGuessValue.Error()
)
isempty(vars) && return nothing
if !(varmap isa SymmapT)
varmap = as_atomic_dict_with_defaults(Dict{SymbolicT, SymbolicT}(varmap), COMMON_NOTHING)
end
if toterm !== nothing
add_toterms!(varmap; toterm)
end
evaluate_varmap!(AtomicArrayDictSubstitutionWrapper(varmap), vars; limit = substitution_limit)
if check && !allow_symbolic
missing_vars = missingvars(varmap, vars; toterm)
for var in vars
var = unwrap(var)
val = get_possibly_indexed(varmap, var, COMMON_NOTHING)
SU.isconst(val) || push!(missing_vars, var)
end
Moshi.Match.@match missing_values begin
MissingGuessValue.Constant(val) => begin
cval = BSImpl.Const{VartypeT}(val)
for var in missing_vars
if Symbolics.isarraysymbolic(var)
varmap[var] = BSImpl.Const{VartypeT}(fill(val, size(var)))
else
write_possibly_indexed_array!(varmap, var, cval, COMMON_NOTHING)
end
end
end
MissingGuessValue.Random(rng) => begin
for var in missing_vars
if Symbolics.isarraysymbolic(var)
varmap[var] = rand(rng, size(var))
else
write_possibly_indexed_array!(varmap, var, Symbolics.SConst(rand(rng)), COMMON_NOTHING)
end
end
end
MissingGuessValue.Error() => begin
if !isempty(missing_vars)
if is_initializeprob
throw(MissingGuessError(collect(missing_vars), collect(missing_vars)))
else
throw(MissingVariablesError(missing_vars))
end
end
end
end
end
vals = map(vars) do x
x = unwrap(x)
v = get_possibly_indexed(varmap, x, x)
Moshi.Match.@match v begin
BSImpl.Const(; val) => return val
_ => begin
Moshi.Match.@match x begin
BSImpl.Term(; f, args) && if f isa Initial && isequal(v, args[1]) end => begin
if Symbolics.isarraysymbolic(v)
return fill(false, size(v))
else
return false
end
end
_ => return v
end
end
end
end
if !allow_symbolic
missingsyms = Any[]
missingvals = Any[]
for (sym, val) in zip(vars, vals)
val !== nothing && symbolic_type(val) == NotSymbolic() && continue
push!(missingsyms, sym)
push!(missingvals, val)
end
if !isempty(missingsyms)
is_initializeprob ? throw(MissingGuessError(missingsyms, missingvals)) :
throw(UnexpectedSymbolicValueInVarmap(missingsyms[1], missingvals[1]))
end
if buffer_eltype == Nothing
vals = promote_to_concrete(vals; tofloat, use_union)
else
vals = Vector{buffer_eltype}(vals)
end
end
if container_type <: Union{AbstractDict, Nothing, SciMLBase.NullParameters}
container_type = Array
end
if isempty(vals)
return nothing
elseif container_type <: Tuple
return (vals...,)
else
return SymbolicUtils.Code.create_array(
container_type, eltype(vals), Val{1}(),
Val(length(vals)), vals...
)
end
end
"""
$(TYPEDSIGNATURES)
Check if any of the substitution rules in `varmap` lead to cycles involving
variables in `vars`. Return a vector of vectors containing all the variables
in each cycle.
Keyword arguments:
- `max_cycle_length`: The maximum length (number of variables) of detected cycles.
- `max_cycles`: The maximum number of cycles to report.
"""
function check_substitution_cycles(
varmap::AbstractDict, vars; max_cycle_length = length(varmap), max_cycles = 10
)
# ordered set so that `vars` are the first `k` in the list
allvars = OrderedSet{Any}(vars)
union!(allvars, keys(varmap))
allvars = collect(allvars)
var_to_idx = Dict(allvars .=> eachindex(allvars))
graph = SimpleDiGraph(length(allvars))
buffer = Set()
for (k, v) in varmap
kidx = var_to_idx[k]
if symbolic_type(v) != NotSymbolic()
SU.search_variables!(buffer, v)
for var in buffer
haskey(var_to_idx, var) || continue
add_edge!(graph, kidx, var_to_idx[var])
end
elseif v isa AbstractArray
for val in v
SU.search_variables!(buffer, val)
end
for var in buffer
haskey(var_to_idx, var) || continue
add_edge!(graph, kidx, var_to_idx[var])
end
end
empty!(buffer)
end
# detect at most 100 cycles involving at most `length(varmap)` vertices
cycles = Graphs.simplecycles_limited_length(graph, max_cycle_length, max_cycles)
# only count those which contain variables in `vars`
filter!(Base.Fix1(any, <=(length(vars))), cycles)
return map(cycles) do cycle
map(Base.Fix1(getindex, allvars), cycle)
end
end
"""
$(TYPEDSIGNATURES)
Performs symbolic substitution on the values in `varmap` for the keys in `vars`, using
`varmap` itself as the set of substitution rules. If an entry in `vars` is not a key
in `varmap`, it is ignored.
"""
function evaluate_varmap!(varmap::AbstractDict{SymbolicT, SymbolicT}, vars; limit = 100)
for k in vars
arr, _ = split_indexed_var(unwrap(k))
v = get(varmap, arr, COMMON_NOTHING)
v === COMMON_NOTHING && continue
SU.isconst(v) && continue
varmap[arr] = fixpoint_sub(v, varmap; maxiters = limit, fold = Val(true))
end
return
end
"""
$(TYPEDSIGNATURES)
Remove keys in `varmap` whose values are `nothing`.
If `missing_values` is not `nothing`, it is assumed to be a collection and all removed
keys will be added to it.
"""
function filter_missing_values!(varmap::AbstractDict; missing_values = nothing)
return filter!(varmap) do kvp
if kvp[2] !== nothing
return true
end
if missing_values !== nothing
push!(missing_values, kvp[1])
end
return false
end
end
"""
$(TYPEDSIGNATURES)
For each `k => v` in `varmap` where `k` is an array (or array symbolic) add
`k[i] => v[i]` for all `i in eachindex(k)`. Return the modified `varmap`.
"""
function scalarize_varmap!(varmap::AbstractDict)
for k in collect(keys(varmap))
symbolic_type(k) == ArraySymbolic() || continue
for i in eachindex(k)
varmap[k[i]] = varmap[k][i]
end
end
return varmap
end
"""
$(TYPEDSIGNATURES)
For each array variable in `vars`, scalarize the corresponding entry in `varmap`.
If a scalarized entry already exists, it is not overridden.
"""
function scalarize_vars_in_varmap!(varmap::AbstractDict, vars)
for var in vars
symbolic_type(var) == ArraySymbolic() || continue
symbolic_has_known_size(var) || continue
haskey(varmap, var) || continue
for i in eachindex(var)
haskey(varmap, var[i]) && continue
varmap[var[i]] = varmap[var][i]
end
end
return
end
function get_temporary_value(p, floatT = Float64)
stype = symtype(unwrap(p))
return if stype == Real
zero(floatT)
elseif stype <: AbstractArray{Real}
zeros(floatT, size(p))
elseif stype <: Real
zero(stype)
elseif stype <: AbstractArray
zeros(eltype(stype), size(p))
else
error(lazy"Nonnumeric parameter $p with symtype $stype cannot be solved for during initialization")
end
end
"""
$(TYPEDEF)
A simple utility meant to be used as the `constructor` passed to `process_SciMLProblem` in
case constructing a SciMLFunction is not required. The arguments passed to it are available
in the `args` field, and the keyword arguments in the `kwargs` field.
"""
struct EmptySciMLFunction{iip, A, K} <: SciMLBase.AbstractSciMLFunction{iip}
args::A
kwargs::K
end
function EmptySciMLFunction{iip}(args...; kwargs...) where {iip}
return EmptySciMLFunction{iip, typeof(args), typeof(kwargs)}(args, kwargs)
end
"""
$TYPEDSIGNATURES
For every `Initial(x)` parameter in `sys`, add `Initial(x) => x` to `op` if it does not
already contain that key.
"""
function add_initials!(sys::AbstractSystem, op::SymmapT)
for p in get_ps(sys)
haskey(op, p) && continue
Moshi.Match.@match p begin
BSImpl.Term(; f, args) && if f isa Initial end => begin
write_possibly_indexed_array!(
op, p, if Symbolics.isarraysymbolic(p)
BSImpl.Const{VartypeT}(fill(false, size(p)))
else
COMMON_FALSE
end, COMMON_FALSE
)
end
_ => nothing
end
end
return
end
"""
$(TYPEDEF)
A callable struct used to reconstruct the `u0` and `p` of the initialization problem
with promoted types.
# Fields
$(TYPEDFIELDS)
"""
struct ReconstructInitializeprob{GP, GU}
"""
A function which when given the original problem and initialization problem, returns
the parameter object of the initialization problem with values copied from the
original.
"""
pgetter::GP
"""
Given the original problem, return the `u0` of the initialization problem.
"""
ugetter::GU
end
"""
$(TYPEDEF)
A wrapper over an observed function which allows calling it on a problem-like object.
`TD` determines whether the getter function is `(u, p, t)` (if `true`) or `(u, p)` (if
`false`).
"""
struct ObservedWrapper{TD, F}
f::F
end
ObservedWrapper{TD}(f::F) where {TD, F} = ObservedWrapper{TD, F}(f)
function (ow::ObservedWrapper{true})(prob)
return ow.f(state_values(prob), parameter_values(prob), current_time(prob))
end
function (ow::ObservedWrapper{false})(prob)
return ow.f(state_values(prob), parameter_values(prob))
end
"""
$(TYPEDSIGNATURES)
Given an index provider `indp` and a vector of symbols `syms` return a type-stable getter
function.
Note that the getter ONLY works for problem-like objects, since it generates an observed
function. It does NOT work for solutions.
"""
Base.@nospecializeinfer function concrete_getu(
indp, syms;
eval_expression, eval_module, force_time_independent = false, kwargs...
)
@nospecialize
obsfn = build_explicit_observed_function(
indp, syms; wrap_delays = false, eval_expression, eval_module,
force_time_independent, kwargs...
)
return ObservedWrapper{is_time_dependent(indp) && !force_time_independent}(obsfn)
end
"""
$(TYPEDEF)
A callable struct which applies `p_constructor` to possibly nested arrays. It also
ensures that views (including nested ones) are concretized. This is implemented manually
of using `narrow_buffer_type` to preserve type-stability.
"""
struct PConstructorApplicator{F}
p_constructor::F
end
function (pca::PConstructorApplicator)(x::AbstractArray)
return pca.p_constructor(x)
end
function (pca::PConstructorApplicator)(x::AbstractArray{Bool})
return pca.p_constructor(BitArray(x))
end
function (pca::PConstructorApplicator{typeof(identity)})(x::SubArray)
return collect(x)
end
function (pca::PConstructorApplicator{typeof(identity)})(x::SubArray{Bool})
return BitArray(x)
end
function (pca::PConstructorApplicator{typeof(identity)})(x::SubArray{<:AbstractArray})
return collect(pca.(x))
end
function (pca::PConstructorApplicator)(x::AbstractArray{<:AbstractArray})
return pca.p_constructor(pca.(x))
end
"""
$(TYPEDSIGNATURES)
Given a source system `srcsys` and destination system `dstsys`, return a function that
takes a value provider of `srcsys` and a value provider of `dstsys` and returns the
`MTKParameters` object of the latter with values from the former.
# Keyword Arguments
- `initials`: Whether to include the `Initial` parameters of `dstsys` among the values
to be transferred.
- `unwrap_initials`: Whether initials in `dstsys` corresponding to unknowns in `srcsys` are
unwrapped.
- `p_constructor`: The `p_constructor` argument to `process_SciMLProblem`.
"""
function get_mtkparameters_reconstructor(
srcsys::AbstractSystem, dstsys::AbstractSystem;
initials = false, unwrap_initials = false, p_constructor = identity,
eval_expression = false, eval_module = @__MODULE__, force_time_independent = false,
kwargs...
)
_p_constructor = p_constructor
p_constructor = PConstructorApplicator(p_constructor)
# if we call `getu` on this (and it were able to handle empty tuples) we get the
# fields of `MTKParameters` except caches.
syms = reorder_parameters(
dstsys, parameters(dstsys; initial_parameters = initials); flatten = false
)
# `dstsys` is an initialization system, do basically everything is a tunable
# and tunables are a mix of different types in `srcsys`. No initials. Constants
# are going to be constants in `srcsys`, as are `nonnumeric`.
# `syms[1]` is always the tunables because `srcsys` will have initials.
tunable_syms = syms[1]
tunable_getter = if isempty(tunable_syms)
Returns(SVector{0, Float64}())
else
p_constructor ∘ concrete_getu(
srcsys, tunable_syms; eval_expression, eval_module,
force_time_independent, kwargs...
)
end
initials_getter = if initials && !isempty(syms[2])
initsyms = Vector{Any}(syms[2])
allsyms = Set(variable_symbols(srcsys))
if unwrap_initials
for i in eachindex(initsyms)
sym = initsyms[i]
innersym = if operation(sym) === getindex
sym, idxs... = arguments(sym)
only(arguments(sym))[idxs...]
else
only(arguments(sym))
end
if innersym in allsyms
initsyms[i] = innersym
end
end
end
p_constructor ∘ concrete_getu(
srcsys, initsyms; eval_expression, eval_module,
force_time_independent, kwargs...
)
else
Returns(SVector{0, Float64}())
end
discs_getter = if isempty(syms[3])
Returns(())
else
ic = get_index_cache(dstsys)
blockarrsizes = Tuple(
map(ic.discrete_buffer_sizes) do bufsizes
p_constructor(map(x -> x.length, bufsizes))
end
)
# discretes need to be blocked arrays
# the `getu` returns a tuple of arrays corresponding to `p.discretes`
# `Base.Fix1(...)` applies `p_constructor` to each of the arrays in the tuple
# `Base.Fix2(...)` does `BlockedArray.(tuple_of_arrs, blockarrsizes)` returning a
# tuple of `BlockedArray`s
Base.Fix2(Broadcast.BroadcastFunction(BlockedArray), blockarrsizes) ∘
Base.Fix1(broadcast, p_constructor) ∘
# This `broadcast.(collect, ...)` avoids `ReshapedArray`/`SubArray`s from
# appearing in the result.
concrete_getu(
srcsys, Tuple(broadcast.(collect, syms[3]));
eval_expression, eval_module, force_time_independent, kwargs...
)
end
const_getter = if syms[4] == ()
Returns(())
else
Base.Fix1(broadcast, p_constructor) ∘ concrete_getu(
srcsys, Tuple(syms[4]);
eval_expression, eval_module, force_time_independent, kwargs...
)
end
nonnumeric_getter = if syms[5] == ()
Returns(())
else
ic = get_index_cache(dstsys)
buftypes = Tuple(
map(ic.nonnumeric_buffer_sizes) do bufsize
Vector{bufsize.type}
end
)
diffcache_params = SU.getmetadata(dstsys, DiffCacheParams, Dict{SymbolicT, Int}())::Dict{SymbolicT, Int}
diffcache_buffer_idx = 0
if !isempty(diffcache_params)
representative = first(keys(diffcache_params))
diffcache_buffer_idx, _ = ic.nonnumeric_idx[representative]
@set! buftypes[diffcache_buffer_idx] = identity
end
# nonnumerics retain the assigned buffer type without narrowing
Base.Fix1(broadcast, _p_constructor) ∘
Base.Fix1(Broadcast.BroadcastFunction(call), buftypes) ∘
concrete_getu(
srcsys, Tuple(syms[5]);
eval_expression, eval_module, force_time_independent, kwargs...
)
end
getters = (
tunable_getter, initials_getter, discs_getter, const_getter, nonnumeric_getter,
)
getter = let getters = getters, diffcache_buffer_idx = diffcache_buffer_idx
function _getter(valp, initprob)
oldcache = parameter_values(initprob).caches
tunablevals = getters[1](valp)
initialvals = getters[2](valp)
nonnumerics = getters[5](valp)
if !iszero(diffcache_buffer_idx)
@set! nonnumerics[diffcache_buffer_idx] = DiffCacheAllocatorAPIWrapper{eltype(initialvals)}.(nonnumerics[diffcache_buffer_idx])
end
return promote_with_nothing(
promote_type_with_nothing(eltype(tunablevals), initialvals),
MTKParameters(
tunablevals, initialvals, getters[3](valp),
getters[4](valp), nonnumerics, oldcache isa Tuple{} ? () :
copy.(oldcache)
)
)
end
end
return getter
end
function call(f, args...)
return f(args...)
end
"""
$(TYPEDSIGNATURES)
Construct a `ReconstructInitializeprob` which reconstructs the `u0` and `p` of `dstsys`
with values from `srcsys`.
Extra keyword arguments are forwarded to `build_function_wrapper`.
"""
function ReconstructInitializeprob(
srcsys::AbstractSystem, dstsys::AbstractSystem; u0_constructor = identity, p_constructor = identity,
eval_expression = false, eval_module = @__MODULE__, is_steadystateprob = false, kwargs...
)
@assert is_initializesystem(dstsys)
ugetter = u0_constructor ∘
concrete_getu(
srcsys, unknowns(dstsys);
eval_expression, eval_module, force_time_independent = is_steadystateprob,
iip_config = (true, false),
kwargs...
)
if is_split(dstsys)
pgetter = get_mtkparameters_reconstructor(
srcsys, dstsys; p_constructor, eval_expression, eval_module,
force_time_independent = is_steadystateprob, kwargs...
)
else
syms = parameters(dstsys)
pgetter = let inner = concrete_getu(
srcsys, syms; eval_expression, eval_module,
force_time_independent = is_steadystateprob, kwargs...
),
p_constructor = p_constructor
function _getter2(valp, initprob)
return p_constructor(inner(valp))
end
end
end
return ReconstructInitializeprob(pgetter, ugetter)
end
"""
$(TYPEDSIGNATURES)
Copy values from `srcvalp` to `dstvalp`. Returns the new `u0` and `p`.
"""
function (rip::ReconstructInitializeprob)(srcvalp, dstvalp)
# copy parameters
newp = rip.pgetter(srcvalp, dstvalp)
# no `u0`, so no type-promotion
if state_values(dstvalp) === nothing
return nothing, newp
end
# the `eltype` of the `u0` of the source
srcu0 = state_values(srcvalp)
T = srcu0 === nothing ? Union{} : eltype(srcu0)
# promote with the tunable eltype
if parameter_values(dstvalp) isa MTKParameters
if !isempty(newp.tunable)
T = promote_type(eltype(newp.tunable), T)
end
elseif !isempty(newp)
T = promote_type(eltype(newp), T)
end
u0 = rip.ugetter(srcvalp)
# and the eltype of the destination u0
if T != eltype(u0) && T != Union{} && T !== Any
u0 = T.(u0)
end
# apply the promotion to tunables portion
buf, repack, alias = SciMLStructures.canonicalize(SciMLStructures.Tunable(), newp)
if eltype(buf) != T
# only do a copy if the eltype doesn't match
newbuf = similar(buf, T)
copyto!(newbuf, buf)
newp = repack(newbuf)
end
if newp isa MTKParameters
# and initials portion
buf, repack, alias = SciMLStructures.canonicalize(SciMLStructures.Initials(), newp)
if eltype(buf) != T && !(buf isa SVector{0})
newbuf = similar(buf, T)
copyto!(newbuf, buf)
newp = repack(newbuf)
end
end
return u0, newp
end
"""
$(TYPEDSIGNATURES)
Given `sys` and its corresponding initialization system `initsys`, return the
`initializeprobpmap` function in `OverrideInitData` for the systems.
"""
function construct_initializeprobpmap(
sys::AbstractSystem, initsys::AbstractSystem; p_constructor = identity, eval_expression, eval_module,
kwargs...
)
@assert is_initializesystem(initsys)
if is_split(sys)
return let getter = get_mtkparameters_reconstructor(
initsys, sys; initials = true, unwrap_initials = true, p_constructor,
eval_expression, eval_module, kwargs...
)
function initprobpmap_split(prob, initsol)
return getter(initsol, prob)
end
end
else
return let getter = concrete_getu(
initsys, parameters(sys; initial_parameters = true);
eval_expression, eval_module, kwargs...
), p_constructor = p_constructor
function initprobpmap_nosplit(prob, initsol)
return p_constructor(getter(initsol))
end
end
end
end
function get_scimlfn(valp)
valp isa SciMLBase.AbstractSciMLFunction && return valp
if hasmethod(symbolic_container, Tuple{typeof(valp)}) &&
(sc = symbolic_container(valp)) !== valp
return get_scimlfn(sc)
end
throw(ArgumentError("SciMLFunction not found. This should never happen."))