I have a model with variables defined as a is below, I need to be able to access the models variables in a model agnostic way. For this I use Symbols as model[:b] will get me b for any model which has a variable b.
How can I do this when the variables are defined as a vector
model = Model()
@variable(model, 0 ≤ a[1:3] ≤ 1)
@variable(model, 0 ≤ b ≤ 1)
sa = Symbol(a)
sb = Symbol(b)
model[sb] # works
ERROR: KeyError: key Symbol("a") not found
A example of why I use symbols, maybe there’s a better way
models = [copy(model) for _ in 1:4]
[MOI.set(models[ii], MOI.Name(), "Model : $ii") for ii in 1:4]
[m[:b] for m in models] # Works
[m[sa] for m in models] # ERROR: KeyError: key Symbol("a") not found
While quite ugly, this does work. It could be made tidier by a PR to JuMP.getindex, would this be wanted in JuMP?
function get_var(m::JuMP.AbstractModel, name::Symbol)
var = JuMP.getindex(m,var_name)
The syntax model[key] is a short-cut for object_dictionary(model)[key], which has a very particular meaning. In particular, it’s not a mechanism for looking up particular variables and constraints, but also containers of variables and constraints.
We also have to think about more general uses of JuMP. For example if someone did @variable(model, x[[:a, :b]]), then they might also expect model[Symbol("x[:a]")] to work, but that gets tricky to implement.