Skip to content

Commit 07a2f00

Browse files
feat: add modelingtoolkitize(::NonlinearProblem)
1 parent a8eff55 commit 07a2f00

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/ModelingToolkit.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ include("modelingtoolkitize/common.jl")
182182
include("modelingtoolkitize/odeproblem.jl")
183183
include("modelingtoolkitize/sdeproblem.jl")
184184
include("modelingtoolkitize/optimizationproblem.jl")
185+
include("modelingtoolkitize/nonlinearproblem.jl")
185186

186187
include("systems/nonlinear/homotopy_continuation.jl")
187188
include("systems/nonlinear/initializesystem.jl")
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
$(TYPEDSIGNATURES)
3+
4+
Convert a `NonlinearProblem` or `NonlinearLeastSquaresProblem` to a
5+
`ModelingToolkit.System`.
6+
7+
# Keyword arguments
8+
9+
- `u_names`: An array of names of the same size as `prob.u0` to use as the names of the
10+
unknowns of the system. The names should be given as `Symbol`s.
11+
- `p_names`: A collection of names to use for parameters of the system. The collection
12+
should have keys corresponding to indexes of `prob.p`. For example, if `prob.p` is an
13+
associative container like `NamedTuple`, then `p_names` should map keys of `prob.p` to
14+
the name that the corresponding parameter should have in the returned system. The names
15+
should be given as `Symbol`s.
16+
17+
All other keyword arguments are forwarded to the created `System`.
18+
"""
19+
function modelingtoolkitize(
20+
prob::Union{NonlinearProblem, NonlinearLeastSquaresProblem};
21+
u_names = nothing, p_names = nothing, kwargs...)
22+
p = prob.p
23+
has_p = !(p isa Union{DiffEqBase.NullParameters, Nothing})
24+
25+
vars = construct_vars(prob, nothing, u_names)
26+
params = construct_params(prob, nothing, p_names)
27+
28+
rhs = trace_rhs(prob, vars, params, nothing)
29+
eqs = vcat([0 ~ rhs[i] for i in eachindex(prob.u0)]...)
30+
31+
sts = vec(collect(vars))
32+
33+
# turn `params` into a list of symbolic variables as opposed to
34+
# a parameter object containing symbolic variables.
35+
_params = params
36+
params = vec(collect(values(params)))
37+
38+
defaults = defaults_from_u0_p(prob, vars, _params, params)
39+
# In case initials crept in, specifically from when we constructed parameters
40+
# using prob.f.sys
41+
filter!(x -> !iscall(x) || !(operation(x) isa Initial), params)
42+
filter!(x -> !iscall(x[1]) || !(operation(x[1]) isa Initial), defaults)
43+
44+
return System(eqs, sts, params;
45+
defaults,
46+
name = gensym(:MTKizedNonlin),
47+
kwargs...)
48+
end

0 commit comments

Comments
 (0)