I’m not sure how scoping is handled when constructing and subsequently simulating a ModelingToolkit model. Would the following code be “bad practice” since the default references a globally scoped variable? Or is only the value bound to the default value in the ModelingToolkit model, in which case the global variable is only referenced at the time of instantiation?
using ModelingToolkit
# Global variables used to compute system parameters
ρ = 2.25e-8 # Resistivity of copper
L = 1
A = 0.001
R = ρ*L/A
@mtkmodel Resistor begin
@parameters begin
R = R
end
#... more code
end
If the above is “bad” practice, what would be a better way of doing this?
It’s not bad practice. That would just make those values hardcoded, so they cannot be estimated or changed in the future. But maybe that’s what you want? There’s a use case for it.
1 Like
Thanks! My use case was for a quick and dirty simulation that I don’t plan to necessarily extend/re-use. I see how I don’t gain much, however, when I could just define all of my input parameters as an array of pairs from the outset and pass them in at the time of problem construction. I was just curious if there was any performance implications by using a global variable in this context since I know doing something like the following would be bad:
my_global_var = 10
function add_to(x)
return x + my_global_var
end
I think the macros are what’s making it difficult for me to wrap my head around what’s happening here. Does modeling toolkit reference the global variable at run time? Or does it bind the value to the symbolic parameters at the point of instantiation such that it doesn’t have to reference global variables?
Since the code that is generated will trace through the function, the MTK generated ODE will be type-stable and fast with the global variable’s value directly placed in the generated equation, and updating the global will not update the value in the equation.