How to avoid global variables in JuMP

I am reading the performance tips of JuMP. It says “The most important rule is to avoid global variables”, but I am not sure what it means in the JuMP context and how to implement it.

In the example below, the value of X, Z, K, L are known and defined before JuMP. They are needed to calculate the objective function of the optimization problem. How should I avoid having them as global variables?

using JuMP, Ipopt

m = Model(Ipopt.Optimizer)

@variable(m, θ[1:4])
@variable(m, δ[1:H])

# X, Z, K, L are known data
mu = @expression(m, X * reshape(θ, (K, L)) * Z')
v = @expression(m, δ .+ mu)
# more arguments..
1 Like

You can define them as const, but you can also “embed” your model in a function where you pass the parameters (data) of your model as argument of the function and you return the values of the endogenous variables of your model (or whatever of your interest, most likely including the status of the optimisation).
Something like:

function find_optimal(H, X, Z, K, L; solver = Ipopt.Optimizer)
   m = Model(solver)
   @variable(m, θ[1:4])
   @variable(m, δ[1:H])
    ...
   optimize!(m)
   return ( θ = value.(θ), δ = value.(δ), status=status(m)
end
2 Likes