MTK & efficient formulation

I have a file with a number of models (ModelingToolkit-MTK, functions, etc.) where, say, temperature, is a parameter. I want to explore what happens for different parameter values (e.g., temperature). To make sure that I use the same temperature everywhere, I want to define the value in one location so that I change it once and know it is consistent throughout the code.

I’m curious about the efficiency of different ways of doing this. As an example, consider a linear ODE where I use time constant as parameter (instead of temperature).

# Global setting of parameter
_τ = 1
# Model
# Independent variable
@variables t
# Differentiation operator 
Dt = Differential(t)
# Parameters
@parameters τ = _τ
# Dependent variable
@variables x(t)=1
# Equation & model
eqs = [Dt(x) ~ -x/τ + sin(t) ]
@named model = ODESystem(eqs)
# Time span & numeric model & solution
prob = ODEProblem(model,[],tspan)
sol = solve(prob)

OK – if I re-run the entire code above every time I change the parameter (), things work.

  • I assume that the parameters macro makes sure that there is no type problem, i.e., that the value of the global variable is assigned to the local variable τ in the function that eventually is produced. I.e., so that the local variable τ does not depend on a global variable. (??)

An alternative way to do it would be:

# Parameters
@parameters τ = 1
# Dependent variable
_τ = 2
prob = ODEProblem(model,[],tspan, [τ=>_τ])

OK – I think this should work, too.

  • This alternative formulation is probably more efficient in that I only have to run the code generating the prob every time I change τ, i.e., I don’t re-create the symbolic model, variables, etc. every time (?)
  • Are there other advantageous to this alternative way?

Finally, I could do a remake, I guess:

_τ = 2
prob1 = remake(prob, p=Dict([τ=>_τ]))

which probably saves some more time.


  • Which of the above methods is the recommended method?

remake is the recommended method.

The other thing you can do is prob[τ] = _τ

1 Like