JuMP sum variables with arbitrary set of indices


#1

Hello,

I’m trying to write a constraint with sum of variables with irregular indexes pattern.

With regular indices it works fine:

using JuMP
m = Model()
@variable(m, x[1:100, 1:100])
@constraint(m, sum(x[i, j] for i = 1:5, j = 7:13) == 87)
println(m)

resulting in following output:

 x[1,7] + x[1,8] + x[1,9] + x[1,10] + x[1,11] + x[1,12] + x[1,13] + x[2,7] + x[2,8] + x[2,9] + x[2,10] + x[2,11] + x[2,12] + x[2,13] + x[3,7] + x[3,8] + x[3,9] + x[3,10] + x[3,11] + x[3,12] + x[3,13] + x[4,7] + x[4,8] + x[4,9] + x[4,10] + x[4,11] + x[4,12] + x[4,13] + x[5,7] + x[5,8] + x[5,9] + x[5,10] + x[5,11] + x[5,12] + x[5,13] == 87

Now, I want to create constraint with more complicated pattern of indexes, lets’ say

[13,4], [22,78], [18,97], [56,32]

so that my constraint would look like this:

x[13,4] + x[22,78] + x[18,97] + x[56,32] == 87

I have an array “a” of indexes and I try to do something like this:

using JuMP
m = Model()
@variable(m, x[1:100, 1:100])
a = [[13,4], [22,78], [18,97], [56,32]]
@constraint(m, sum(x[i] for i in a) == 87)
println(m)

but it doesn’t work:

ERROR: LoadError: The operators <=, >=, and == can only be used to specify scalar constraints. If you are trying to add a vectorized constraint, use the element-wise dot comparison operators (.<=, .>=, or .==) instead

I don’t want to create vectorized constraint. I want a single scalar constraint with arbitrary variable indexes predefined in an array (or whatever else). Any suggestions please?


#2

Try @expression(m, sum(x[i,j] for (i,j) in a))


#3

That did the trick. It works even without involving @expression.

@constraint(m, sum(x[i,j] for (i,j) in a) == 87)

works as well.

Thank you for prompt and informative answer.


#4

@expression just builds a JuMP expression which can be used to define different types of constraints;

Note if the index set a contains duplicates JuMP will not “compress”, or rather compile the expression before handling them to the actual solver, which my lead to high memory use. In one of my problems I had to “compactify” the constraints manually.