MTK programmatic populating initial guess values

Hi all, this should be really easy but I can’t quite figure it out.
When you create an MTK system, and want to solve it as a NonlinearProblem, ODEProblem, or whatever, you often need provide an initial guess or initial conditions.

Not a MWE here, just some generic whiteboard code

sys = mtkcompile(_sys)
guess = [ pump.port_b.m_dot => -100.0, pipe.port_a.p => 10.0, some_valve.port_a.m_dot => 1.0]
# and so on with more guess values

prob = NonlinearProblem(sys, guess)
sol = solve(prob)

what I’d like to do is be able to iterate in a loop building the guess vector from strings, as I know what is in the system. Something like this:

for i in N_valves
push!(guesses, Pair(Symbol("valve_$i.port_a.m_dot"), 33)) 
push!(guesses, Pair(Symbol("valve_$i.port_a.p"), 42)) 
# exact guess values don't matter here
end

However, the type of the guess array is

typeof(guesses)
Vector{Pair{Num, Float64}}

The type of the guess pair vectors doesn’t say anything about a Symbol, and the above for loop doesn’t work. Num is supposed to be an abstract type, although displaying the guess vector shows the names and guess value

julia> guesses
3-element Vector{Pair{Num, Float64}}:
   pump₊port_b₊m_dot(t) => -100.0
   pipe₊port_a₊p(t) => 10.0
 some_valve₊port_a₊m_dot(t) => 1.0

So that is puzzling.

@Oscar_Smith @cryptic.ax may have comments here.

See MTK string parsing. The docs are broken, but it should point you to the right functions

what I’d like to do is be able to iterate in a loop building the guess vector from strings, as I know what is in the system.

We allow specifying guesses as a vector of pairs, but it’s actually a Dict. I’d recommend doing

guess = Dict{Symbolics.SymbolicT, Symbolics.SymbolicT}()
for i in N_valves
  var = getproperty(sys, Symbol(:valve_, i)).port_a.m_dot
  guess[var] = 33
end

The same pattern applies for initial conditions. If you need more flexibility in getting the name, var = ModelingToolkit.parse_variable(sys, "valve_$i.port_a.m_dot") should work.

The type of the guess pair vectors doesn’t say anything about a Symbol

Symbolic variables are not Symbols.

Num is supposed to be an abstract type

Num is a concrete type.

When using getproperty to access variables from systems, you will get one of a couple different types depending on the variable that was accessed (whether it’s a scalar or array, etc.). Num is one of those types. All these types are very thin wrappers over Symbolics.SymbolicT, and automatically convert to it. Thus the above approach is likely the best way to do this.

Thank you for the solution, this works. Thank you all for replying! And yes I was confusing “Number” and “Num”.