|
| 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