-
-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathcodegen.jl
More file actions
1660 lines (1435 loc) · 54.4 KB
/
Copy pathcodegen.jl
File metadata and controls
1660 lines (1435 loc) · 54.4 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 GENERATE_X_KWARGS = """
- `expression`: `Val{true}` if this should return an `Expr` (or tuple of `Expr`s) of the
generated code. `Val{false}` otherwise.
- `wrap_gfw`: `Val{true}` if the returned functions should be wrapped in a callable
struct to make them callable using the expected syntax. The callable struct itself is
internal API. If `expression == Val{true}`, the returned expression will construct the
callable struct. If this function returns a tuple of functions/expressions, both will
be identical if `wrap_gfw == Val{true}`.
$EVAL_EXPR_MOD_KWARGS
"""
const EXPERIMENTAL_WARNING = """
!!! warn
This API is experimental and may change in a future non-breaking release.
"""
"""
$(TYPEDSIGNATURES)
Generate the RHS function for the [`equations`](@ref) of a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `implicit_dae`: Whether the generated function should be in the implicit form. Applicable
only for ODEs/DAEs or discrete systems. Instead of `f(u, p, t)` (`f(du, u, p, t)` for the
in-place form) the function is `f(du, u, p, t)` (respectively `f(resid, du, u, p, t)`).
- `override_discrete`: Whether to assume the system is discrete regardless of
`is_discrete_system(sys)`.
- `scalar`: Whether to generate a single-out-of-place function that returns a scalar for
the only equation in the system.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_rhs(
sys::System; implicit_dae = false,
scalar = false, expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, override_discrete = false,
cachesyms = nothing, compiler_options::CompilerOptions = CompilerOptions(),
kwargs...
)
dvs = unknowns(sys)
ps = parameters(sys; initial_parameters = true)
eqs = equations(sys)
obs = observed(sys)
u = dvs
p = reorder_parameters(sys, ps)
if cachesyms isa Vector{Vector{SymbolicT}}
append!(p, cachesyms)
end
t = get_iv(sys)
ddvs = nothing
extra_assignments = Assignment[]
# used for DAEProblem and ImplicitDiscreteProblem
if implicit_dae
if override_discrete || is_discrete_system(sys)
# ImplicitDiscrete case
D = Shift(t, 1)
rhss = map(eqs) do eq
# Algebraic equations get shifted forward 1, to match with differential
# equations
_iszero(eq.lhs) ? distribute_shift(D(eq.rhs)) : (eq.rhs - eq.lhs)
end
# Handle observables in algebraic equations, since they are shifted
shifted_obs = Equation[distribute_shift(D(eq)) for eq in obs]
obsidxs = observed_equations_used_by(sys, rhss; obs = shifted_obs)
ddvs = map(D, dvs)
append!(
extra_assignments,
[
Assignment(shifted_obs[i].lhs, shifted_obs[i].rhs)
for i in obsidxs
]
)
else
D = Differential(t)
ddvs = map(D, dvs)
rhss = [_iszero(eq.lhs) ? eq.rhs : eq.rhs - eq.lhs for eq in eqs]
end
else
if !override_discrete && !is_discrete_system(sys)
check_operator_variables(eqs, Differential)
check_lhs(eqs, Differential, Set(dvs))
end
rhss = [eq.rhs for eq in eqs]
end
if !isempty(assertions(sys)) && !isempty(rhss)
rhss[end] += unwrap(get_assertions_expr(sys))
end
# TODO: add an optional check on the ordering of observed equations
if scalar
rhss = only(rhss)
u = only(u)
end
args = (u, p...)
p_start = 2
if t !== nothing
args = (args..., t)
end
if implicit_dae
args = (ddvs, args...)
p_start += 1
end
u_arg = scalar ? -1 : (implicit_dae ? 2 : 1)
res = build_function_wrapper(
sys, rhss, args...; p_start, extra_assignments, u_arg,
expression = Val{true}, expression_module = eval_module, kwargs...
)
nargs = length(args) - length(p) + 1
if is_dde(sys)
p_start += 1
nargs += 1
end
return maybe_compile_function(
expression, wrap_gfw, (p_start, nargs, is_split(sys)),
res; compiler_options, eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Generate the diffusion function for the noise equations of a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_diffusion_function(
sys::System; expression = Val{true},
wrap_gfw = Val{false}, eval_expression = false,
eval_module = @__MODULE__, kwargs...
)
dvs = unknowns(sys)
ps = parameters(sys; initial_parameters = true)
eqs = get_noise_eqs(sys)
if ndims(eqs) == 2 && size(eqs, 2) == 1
# scalar noise
eqs = vec(eqs)
end
p = reorder_parameters(sys, ps)
res = build_function_wrapper(sys, eqs, dvs, p..., get_iv(sys); u_arg = 1, kwargs...)
if expression == Val{true}
return res
end
f_oop, f_iip = eval_or_rgf.(res; eval_expression, eval_module)
p_start = 2
nargs = 3
if is_dde(sys)
p_start += 1
nargs += 1
end
return maybe_compile_function(
expression, wrap_gfw, (p_start, nargs, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Calculate the gradient of the equations of `sys` with respect to the independent variable.
`simplify` is forwarded to `Symbolics.expand_derivatives`.
"""
function calculate_tgrad(sys::System; simplify = false)
check_symbolic_ad_allowed(sys)
# We need to remove explicit time dependence on the unknown because when we
# have `u(t) * t` we want to have the tgrad to be `u(t)` instead of `u'(t) *
# t + u(t)`.
rhs = [detime_dvs(eq.rhs) for eq in full_equations(sys)]
iv = get_iv(sys)
xs = unknowns(sys)
rule = Dict(map((x, xt) -> xt => x, detime_dvs.(xs), xs))
rhs = substitute.(rhs, Ref(rule))
tgrad = [expand_derivatives(Differential(iv)(r), simplify) for r in rhs]
reverse_rule = Dict(map((x, xt) -> x => xt, detime_dvs.(xs), xs))
tgrad = Num.(substitute.(tgrad, Ref(reverse_rule)))
return tgrad
end
"""
$(TYPEDSIGNATURES)
Calculate the jacobian of the equations of `sys`.
# Keyword arguments
- `simplify`, `sparse`: Forwarded to `Symbolics.jacobian`.
- `dvs`: The variables with respect to which the jacobian should be computed.
"""
function calculate_jacobian(
sys::System;
sparse = false, simplify = false, dvs = unknowns(sys)
)
check_symbolic_ad_allowed(sys)
eqs = full_equations(sys)
rhs = SymbolicT[]
sizehint!(rhs, length(eqs))
for eq in eqs
push!(rhs, eq.rhs - eq.lhs)
end
if sparse
jac = sparsejacobian(rhs, dvs; simplify)
if get_iv(sys) !== nothing
# Add nonzeros of W as non-structural zeros of the Jacobian
# (to ensure equal results for oop and iip Jacobian)
JIs, JJs, JVs = findnz(jac)
WIs, WJs, _ = findnz(W_sparsity(sys))
append!(JIs, WIs) # explicitly put all W's indices also in J,
append!(JJs, WJs) # even if it duplicates some indices
append!(JVs, zeros(eltype(JVs), length(WIs))) # add zero
jac = SparseArrays.sparse(JIs, JJs, JVs) # values at duplicate indices are summed; not overwritten
end
else
jac = jacobian(rhs, dvs; simplify)
end
return jac
end
"""
$(TYPEDSIGNATURES)
Generate the jacobian function for the equations of a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_jacobian`](@ref).
- `checkbounds`: Whether to check correctness of indices at runtime if `sparse`.
Also forwarded to `build_function_wrapper`.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_jacobian(
sys::System;
simplify = false, sparse = false, eval_expression = false,
eval_module = @__MODULE__, expression = Val{true}, wrap_gfw = Val{false},
checkbounds = false, compiler_options::CompilerOptions = CompilerOptions(), kwargs...
)
dvs = unknowns(sys)
jac = calculate_jacobian(sys; simplify, sparse, dvs)
p = reorder_parameters(sys)
t = get_iv(sys)
if t !== nothing && sparse && checkbounds
wrap_code = assert_jac_length_header(sys) # checking sparse J indices at runtime is expensive for large systems
else
wrap_code = (identity, identity)
end
args = (dvs, p...)
nargs = 2
if is_time_dependent(sys)
args = (args..., t)
nargs = 3
end
res = build_function_wrapper(
sys, jac, args...; wrap_code, u_arg = 1, expression = Val{true},
expression_module = eval_module, checkbounds, kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (2, nargs, is_split(sys)), res;
compiler_options, eval_expression, eval_module
)
end
function assert_jac_length(arr::SparseMatrixCSC, I::Vector{<:Integer}, J::Vector{<:Integer})
@assert findnz(arr)[1:2] == (I, J)
end
function assert_jac_length_header(sys)
W = W_sparsity(sys)
return identity,
function add_header(expr)
body = Let([Assignment(:_, term(assert_jac_length, expr.args[1], findnz(W)[1:2]...))], expr.body, true)
return Func(expr.args, [], body)
end
end
"""
$(TYPEDSIGNATURES)
Generate the tgrad function for the equations of a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`: Forwarded to [`calculate_tgrad`](@ref).
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_tgrad(
sys::System;
simplify = false, eval_expression = false, eval_module = @__MODULE__,
expression = Val{true}, wrap_gfw = Val{false},
compiler_options::CompilerOptions = CompilerOptions(), kwargs...
)
dvs = unknowns(sys)
ps = parameters(sys; initial_parameters = true)
tgrad = calculate_tgrad(sys, simplify = simplify)
p = reorder_parameters(sys, ps)
res = build_function_wrapper(
sys, tgrad,
dvs,
p...,
get_iv(sys);
u_arg = 1,
expression = Val{true},
expression_module = eval_module,
kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (2, 3, is_split(sys)), res;
compiler_options, eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Return an array of symbolic hessians corresponding to the equations of the system.
# Keyword Arguments
- `sparse`: Controls whether the symbolic hessians are sparse matrices
- `simplify`: Forwarded to `Symbolics.hessian`
"""
function calculate_hessian(sys::System; simplify = false, sparse = false)
rhs = [eq.rhs - eq.lhs for eq in full_equations(sys)]
dvs = unknowns(sys)
if sparse
hess = map(rhs) do expr
Symbolics.sparsehessian(expr, dvs; simplify)::AbstractSparseArray
end
else
hess = [Symbolics.hessian(expr, dvs; simplify) for expr in rhs]
end
return hess
end
"""
$(TYPEDSIGNATURES)
Return the sparsity pattern of the hessian of the equations of `sys`.
"""
function Symbolics.hessian_sparsity(sys::System)
hess = calculate_hessian(sys; sparse = true)
return similar.(hess, Float64)
end
const W_GAMMA = only(@variables ˍ₋gamma)
"""
$(TYPEDSIGNATURES)
Generate the `W = γ * M + J` function for the equations of a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_jacobian`](@ref).
- `checkbounds`: Whether to check correctness of indices at runtime if `sparse`.
Also forwarded to `build_function_wrapper`.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_W(
sys::System;
simplify = false, sparse = false, expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, checkbounds = false, kwargs...
)
dvs = unknowns(sys)
ps = parameters(sys; initial_parameters = true)
M = calculate_massmatrix(sys; simplify)
if sparse
M = SparseArrays.sparse(M)
end
J = calculate_jacobian(sys; simplify, sparse, dvs)
W = W_GAMMA * M + J
t = get_iv(sys)
if t !== nothing && sparse && checkbounds
wrap_code = assert_jac_length_header(sys)
else
wrap_code = (identity, identity)
end
p = reorder_parameters(sys, ps)
res = build_function_wrapper(
sys, W, dvs, p..., W_GAMMA, t; wrap_code,
u_arg = 1, p_end = 1 + length(p), checkbounds, kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (2, 4, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Generate the DAE jacobian `γ * J′ + J` function for the equations of a [`System`](@ref).
`J′` is the jacobian of the equations with respect to the `du` vector, and `J` is the
standard jacobian.
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_jacobian`](@ref).
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_dae_jacobian(
sys::System; simplify = false, sparse = false,
expression = Val{true}, wrap_gfw = Val{false}, eval_expression = false,
eval_module = @__MODULE__,
compiler_options::CompilerOptions = CompilerOptions(), kwargs...
)
dvs = unknowns(sys)
ps = parameters(sys; initial_parameters = true)
jac_u = calculate_jacobian(sys; simplify = simplify, sparse = sparse)
t = get_iv(sys)
derivatives = Differential(t).(unknowns(sys))
jac_du = calculate_jacobian(
sys; simplify = simplify, sparse = sparse,
dvs = derivatives
)
dvs = unknowns(sys)
jac = W_GAMMA * jac_du + jac_u
p = reorder_parameters(sys, ps)
res = build_function_wrapper(
sys, jac, derivatives, dvs, p..., W_GAMMA, t;
u_arg = 2, p_start = 3, p_end = 2 + length(p), kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (3, 5, is_split(sys)), res;
compiler_options, eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Generate the history function for a [`System`](@ref), given a symbolic representation of
the `u0` vector prior to the initial time.
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_history(
sys::System, u0; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, kwargs...
)
p = reorder_parameters(sys)
res = build_function_wrapper(
sys, u0, p..., get_iv(sys); expression = Val{true},
expression_module = eval_module, p_start = 1, p_end = length(p),
similarto = typeof(u0), wrap_delays = false, kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (1, 2, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Calculate the mass matrix of `sys`. `simplify` controls whether `Symbolics.simplify` is
applied to the symbolic mass matrix. Returns a `Diagonal` or `LinearAlgebra.I` wherever
possible.
"""
function calculate_massmatrix(sys::System; simplify = false)
eqs = [eq for eq in equations(sys)]
M = zeros(length(eqs), length(eqs))
for (i, eq) in enumerate(eqs)
if iscall(eq.lhs) && operation(eq.lhs) isa Differential
st = var_from_nested_derivative(eq.lhs)[1]
j = variable_index(sys, st)
M[i, j] = 1
else
_iszero(eq.lhs) ||
error("Only semi-explicit constant mass matrices are currently supported. Faulty equation: $eq.")
end
end
M = simplify ? Symbolics.simplify.(M) : M
if isdiag(M)
M = Diagonal(M)
end
# M should only contain concrete numbers
return M == I ? I : M
end
"""
$(TYPEDSIGNATURES)
Return a modified version of mass matrix `M` which is of a similar type to `u0`. `sparse`
controls whether the mass matrix should be a sparse matrix.
"""
function concrete_massmatrix(M; sparse = false, u0 = nothing)
return if sparse && !(u0 === nothing || M === I)
SparseArrays.sparse(M)
elseif u0 === nothing || M === I
M
elseif M isa Diagonal
Diagonal(ArrayInterface.restructure(u0, diag(M)))
else
ArrayInterface.restructure(u0 .* u0', M)
end
end
"""
$TYPEDSIGNATURES
Obtain the jacobian sparsity pattern from a torn system. Returns `nothing` by default.
"""
torn_system_jacobian_sparsity(sys::AbstractSystem) = nothing
"""
$(TYPEDSIGNATURES)
Return the sparsity pattern of the jacobian of `sys` as a matrix.
"""
function jacobian_sparsity(sys::System)
sparsity = torn_system_jacobian_sparsity(sys)
sparsity === nothing || return sparsity
return Symbolics.jacobian_sparsity(
[eq.rhs for eq in full_equations(sys)],
[dv for dv in unknowns(sys)]
)
end
"""
$(TYPEDSIGNATURES)
Return the sparsity pattern of the DAE jacobian of `sys` as a matrix.
See also: [`generate_dae_jacobian`](@ref).
"""
function jacobian_dae_sparsity(sys::System)
J1 = jacobian_sparsity(
[eq.rhs for eq in full_equations(sys)],
[dv for dv in unknowns(sys)]
)
derivatives = Differential(get_iv(sys)).(unknowns(sys))
J2 = jacobian_sparsity(
[eq.rhs for eq in full_equations(sys)],
[dv for dv in derivatives]
)
return J1 + J2
end
"""
$(TYPEDSIGNATURES)
Return the sparsity pattern of the `W` matrix of `sys`.
See also: [`generate_W`](@ref).
"""
function W_sparsity(sys::System)
jac_sparsity = jacobian_sparsity(sys)
(n, n) = size(jac_sparsity)
M = calculate_massmatrix(sys)
M_sparsity = M isa UniformScaling ? sparse(I(n)) :
SparseMatrixCSC{Bool, Int64}((!iszero).(M))
return jac_sparsity .| M_sparsity
end
"""
$(TYPEDSIGNATURES)
Return the matrix to use as the jacobian prototype given the W-sparsity matrix of the
system. This is not the same as the jacobian sparsity pattern.
# Keyword arguments
- `u0`: The `u0` vector for the problem.
- `sparse`: The prototype is `nothing` for non-sparse matrices.
"""
function calculate_W_prototype(W_sparsity; u0 = nothing, sparse = false)
sparse || return nothing
uElType = u0 === nothing ? Float64 : eltype(u0)
return similar(W_sparsity, uElType)
end
function isautonomous(sys::System)
tgrad = calculate_tgrad(sys; simplify = true)
return all(iszero, tgrad)
end
function get_bv_solution_symbol(ns)
return only(@variables BV_SOLUTION(..)[1:ns])
end
function get_constraint_unknown_subs!(subs::Dict, cons::Vector, stidxmap::Dict, iv, sol)
vs = SU.search_variables(cons)
for v in vs
iscall(v) || continue
op = operation(v)
args = arguments(v)
issym(op) && length(args) == 1 || continue
newv = op(iv)
haskey(stidxmap, newv) || continue
subs[v] = sol(args[1])[stidxmap[newv]]
end
return
end
"""
$(TYPEDSIGNATURES)
Generate the boundary condition function for a [`System`](@ref) given the state vector `u0`,
the indexes of `u0` to consider as hard constraints `u0_idxs` and the initial time `t0`.
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_boundary_conditions(
sys::System, u0, u0_idxs, t0; expression = Val{true},
wrap_gfw = Val{false}, eval_expression = false, eval_module = @__MODULE__,
kwargs...
)
iv = get_iv(sys)
sts = unknowns(sys)
ps = parameters(sys)
np = length(ps)
ns = length(sts)
stidxmap = Dict([v => i for (i, v) in enumerate(sts)])
pidxmap = Dict([v => i for (i, v) in enumerate(ps)])
# sol = get_bv_solution_symbol(ns)
cons = [con.lhs - con.rhs for con in constraints(sys)]
conssubs = Dict{SymbolicT, SymbolicT}()
get_constraint_unknown_subs!(conssubs, cons, stidxmap, iv, BVP_SOLUTION)
substituter = SU.Substituter{false}(conssubs)
cons = map(substituter, cons)
init_conds = SymbolicT[]
for i in u0_idxs
expr = BVP_SOLUTION(t0)[i] - u0[i]
push!(init_conds, expr)
end
exprs = vcat(init_conds, cons)
_p = reorder_parameters(sys, ps)
res = build_function_wrapper(
sys, exprs, _p..., iv; output_type = Array,
p_start = 1, histfn = (p, t) -> BVP_SOLUTION(t),
histfn_symbolic = BVP_SOLUTION, wrap_delays = true, kwargs...
)
return maybe_compile_function(
expression, wrap_gfw, (2, 3, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Generate the cost function for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_cost(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, kwargs...
)
obj = cost(sys)
dvs = unknowns(sys)
ps = reorder_parameters(sys)
if is_time_dependent(sys)
wrap_delays = true
p_start = 1
p_end = length(ps)
args = (ps..., get_iv(sys))
nargs = 3
else
wrap_delays = false
p_start = 2
p_end = length(ps) + 1
args = (dvs, ps...)
nargs = 2
end
u_arg = is_time_dependent(sys) ? -1 : 1
res = build_function_wrapper(
sys, obj, args...; expression = Val{true}, p_start, p_end, wrap_delays, u_arg,
histfn = (p, t) -> BVP_SOLUTION(t), histfn_symbolic = BVP_SOLUTION, kwargs...
)[1]
if expression == Val{true}
return res
end
return maybe_compile_function(
expression, wrap_gfw, (2, nargs, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Generate the cost function for a BVP [`System`](@ref). The generated function has the
signature `cost(sol, p)` where `sol` is a solution interpolation object (callable as
`sol(t)` to get state at time `t`) and `p` is the parameter object.
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_bvp_cost(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, cse = true,
checkbounds = false, kwargs...
)
obj = cost(sys)
_iszero(obj) && return nothing
iv = get_iv(sys)
sts = unknowns(sys)
ps = reorder_parameters(sys)
stidxmap = Dict([v => i for (i, v) in enumerate(sts)])
# Substitute x(t_val) -> BVP_SOLUTION(t_val)[idx] for all state evaluations
costsubs = Dict()
get_constraint_unknown_subs!(costsubs, [obj], stidxmap, iv, BVP_SOLUTION)
obj = substitute(obj, costsubs)
# Build function with signature (sol, p) where sol = BVP_SOLUTION
# The histfn mechanism replaces BVP_SOLUTION with the sol argument
res = build_function_wrapper(
sys, obj, ps...;
expression = Val{true},
p_start = 1, # sol goes before parameters
p_end = length(ps),
wrap_delays = true,
histfn = (p, t) -> BVP_SOLUTION(t),
histfn_symbolic = BVP_SOLUTION,
cse, checkbounds, kwargs...
)[1]
# (2, 2, is_split) means: 2 args out-of-place, 2 original args, split status
return maybe_compile_function(
expression, wrap_gfw, (2, 2, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Calculate the gradient of the consolidated cost of `sys` with respect to the unknowns.
`simplify` is forwarded to `Symbolics.gradient`.
"""
function calculate_cost_gradient(sys::System; simplify = false)
obj = cost(sys)
dvs = unknowns(sys)
return Symbolics.gradient(obj, dvs; simplify)
end
"""
$(TYPEDSIGNATURES)
Generate the gradient of the cost function with respect to unknowns for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`: Forwarded to [`calculate_cost_gradient`](@ref).
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_cost_gradient(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, simplify = false, kwargs...
)
obj = cost(sys)
dvs = unknowns(sys)
ps = reorder_parameters(sys)
exprs = calculate_cost_gradient(sys; simplify)
res = build_function_wrapper(sys, exprs, dvs, ps...; u_arg = 1, expression = Val{true}, kwargs...)
return maybe_compile_function(
expression, wrap_gfw, (2, 2, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Calculate the hessian of the consolidated cost of `sys` with respect to the unknowns.
`simplify` is forwarded to `Symbolics.hessian`. `sparse` controls whether a sparse
matrix is returned.
"""
function calculate_cost_hessian(sys::System; sparse = false, simplify = false)
obj = cost(sys)
dvs = unknowns(sys)
if sparse
return Symbolics.sparsehessian(obj, dvs; simplify)::AbstractSparseArray
else
return Symbolics.hessian(obj, dvs; simplify)
end
end
"""
$(TYPEDSIGNATURES)
Return the sparsity pattern for the hessian of the cost function of `sys`.
"""
function cost_hessian_sparsity(sys::System)
return similar(calculate_cost_hessian(sys; sparse = true), Float64)
end
"""
$(TYPEDSIGNATURES)
Generate the hessian of the cost function for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_cost_hessian`](@ref).
- `return_sparsity`: Whether to also return the sparsity pattern of the hessian as the
second return value.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_cost_hessian(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, simplify = false,
sparse = false, return_sparsity = false, kwargs...
)
obj = cost(sys)
dvs = unknowns(sys)
ps = reorder_parameters(sys)
sparsity = nothing
exprs = calculate_cost_hessian(sys; sparse, simplify)
if sparse
sparsity = similar(exprs, Float64)
end
res = build_function_wrapper(sys, exprs, dvs, ps...; u_arg = 1, expression = Val{true}, kwargs...)
fn = maybe_compile_function(
expression, wrap_gfw, (2, 2, is_split(sys)), res; eval_expression, eval_module
)
return return_sparsity ? (fn, sparsity) : fn
end
function canonical_constraints(sys::System)
return map(constraints(sys)) do cstr
Symbolics.canonical_form(cstr).lhs
end
end
"""
$(TYPEDSIGNATURES)
Generate the constraint function for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_cons(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, kwargs...
)
cons = canonical_constraints(sys)
dvs = unknowns(sys)
ps = reorder_parameters(sys)
res = build_function_wrapper(sys, cons, dvs, ps...; u_arg = 1, expression = Val{true}, kwargs...)
return maybe_compile_function(
expression, wrap_gfw, (2, 2, is_split(sys)), res; eval_expression, eval_module
)
end
"""
$(TYPEDSIGNATURES)
Return the jacobian of the constraints of `sys` with respect to unknowns.
# Keyword arguments
- `simplify`, `sparse`: Forwarded to `Symbolics.jacobian`.
- `return_sparsity`: Whether to also return the sparsity pattern of the jacobian.
"""
function calculate_constraint_jacobian(
sys::System; simplify = false, sparse = false,
return_sparsity = false
)
cons = canonical_constraints(sys)
dvs = unknowns(sys)
sparsity = nothing
if sparse
jac = Symbolics.sparsejacobian(cons, dvs; simplify)::AbstractSparseArray
sparsity = similar(jac, Float64)
else
jac = Symbolics.jacobian(cons, dvs; simplify)
end
return return_sparsity ? (jac, sparsity) : jac
end
"""
$(TYPEDSIGNATURES)
Generate the jacobian of the constraint function for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_constraint_jacobian`](@ref).
- `return_sparsity`: Whether to also return the sparsity pattern of the jacobian as the
second return value.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_constraint_jacobian(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, return_sparsity = false,
simplify = false, sparse = false, kwargs...
)
dvs = unknowns(sys)
ps = reorder_parameters(sys)
jac,
sparsity = calculate_constraint_jacobian(
sys; simplify, sparse, return_sparsity = true
)
res = build_function_wrapper(sys, jac, dvs, ps...; u_arg = 1, expression = Val{true}, kwargs...)
fn = maybe_compile_function(
expression, wrap_gfw, (2, 2, is_split(sys)), res; eval_expression, eval_module
)
return return_sparsity ? (fn, sparsity) : fn
end
"""
$(TYPEDSIGNATURES)
Return the hessian of the constraints of `sys` with respect to unknowns.
# Keyword arguments
- `simplify`, `sparse`: Forwarded to `Symbolics.hessian`.
- `return_sparsity`: Whether to also return the sparsity pattern of the hessian.
"""
function calculate_constraint_hessian(
sys::System; simplify = false, sparse = false, return_sparsity = false
)
cons = canonical_constraints(sys)
dvs = unknowns(sys)
sparsity = nothing
if sparse
hess = map(cons) do cstr
Symbolics.sparsehessian(cstr, dvs; simplify)::AbstractSparseArray
end
sparsity = similar.(hess, Float64)
else
hess = [Symbolics.hessian(cstr, dvs; simplify) for cstr in cons]
end
return return_sparsity ? (hess, sparsity) : hess
end
"""
$(TYPEDSIGNATURES)
Generate the hessian of the constraint function for a [`System`](@ref).
# Keyword Arguments
$GENERATE_X_KWARGS
- `simplify`, `sparse`: Forwarded to [`calculate_constraint_hessian`](@ref).
- `return_sparsity`: Whether to also return the sparsity pattern of the hessian as the
second return value.
All other keyword arguments are forwarded to [`build_function_wrapper`](@ref).
"""
function generate_constraint_hessian(
sys::System; expression = Val{true}, wrap_gfw = Val{false},
eval_expression = false, eval_module = @__MODULE__, return_sparsity = false,
simplify = false, sparse = false, kwargs...
)
dvs = unknowns(sys)