# [ModelingToolkit.jl] varmap_to_vars function

Hello,
I have a question about the ModelingToolkit package, and in particular about @parameters value maps.

@parameters t k₁₂ k₂₁ α
p = [k₁₂ => 0.0005
k₂₁ => 0.009
α => 0.09]

I have an ODE system and I want to fit some data on it.
As a test, I tried to generate fake data with the following code (from documentation of https://docs.sciml.ai/DiffEqParamEstim/stable/) without noise.

begin
using RecursiveArrayTools # for VectorOfArray
randomized = VectorOfArray([sol(time[i]) for i in 1:length(time)])
data = convert(Array,randomized)
end

and the cost function is as follow :

cost_function = build_loss_objective(prob, Tsit5(), L2Loss(time, data[1,:]),
Optimization.AutoForwardDiff(),
maxiters=100000,verbose=false, save_idxs = [1])

Thus, normally, cost_data(p) must be equal to 0. However, cost_data doesn’t eat value maps directly and we have to convert p in an Array/Vector. We can’t just create a Vector with the values of p [0.09, 0.009, 0.0005] because the symbol ordering is not guaranteed :

The function varmap_to_vars ( Frequently Asked Questions · ModelingToolkit.jl (sciml.ai)) seems to be intended for that , but how it work is obscure. Documentation give the following example :

p = @parameters x y z
idxs = ModelingToolkit.varmap_to_vars([p[1] => 1, p[2] => 2, p[3] => 3], p)
p[idxs]

but p[idxs] is just p and not a vector …

How to correctly manage the symbol ordering when we work with value maps of ModelingToolkit ?

Thanks !

That gives you the index ordering for p[1], p[2], p[3]. So then when you index p[idxs] it’s in the order you’re expecting.

Ok thanks I understand !

But when I do optimisation :

optprob = Optimization.OptimizationProblem(cost_function, [0.02, 0.05, 0.0005], lb = [0.0, 0.0, 0.0], ub = [0.1, 0.1, 0.1])
result_bfgs = solve(optprob, BFGS())

how can I know in which order pass the initial parameters [0.02, 0.05, 0.0005] in the OptimizationProblem, and in which order they are returned by the solve function (stored in result_bfgs) ?

states(sys) would give you the ordering, and then you can use the varmap_to_vars to find the permute! indices.

1 Like