How to use @expression macro with non-numeric indexes


I am building an optimization model where I would like to use JuMP expressions to smoothly add elements of constraints across different parts of the model. However, the sets I am working with and over which I am initializing my variables are not numeric but often lists of strings. In this case, @expresssion macro returns DenseAxisArray instead of Matrix{AffExpr}, which I cannot easily manipulate, add together and use functions such as [add_to_expression!]

Here is a simple example:

using JuMP
model = Model()
I = [1, 2, 3] #first set
J = ["A", "B", "C"] #second set

@variable(model, x[i in I, j in J] >= 0)
@expression(model, expr[i in I, j in J], x) #produces the DenseAxisArray

Is there any other way to do it?

It’s actually still stored as a Matrix under the hood, see

You can access the matrix using or
Alternatively, you can use

@variable(model, x[i in eachindex(I), j in eachindex(J)] >= 0)

so that JuMP just uses a Matrix but then you cannot index it with the elements of I and J but with their indices instead.

Hi @asuski, welcome to the forum :smile:

Can you share a larger example of what you are trying to do? In most cases, you should be able to write similar code depending on whether the data structure is a matrix or dense axis array.

See Containers · JuMP, which explains the various operations you can do with a dense axis array.