Search code examples
juliajulia-jump

How to sum for all in Julia/JuMP v 1.10


I saw an outdated answer in the following thread (How to do "for all" in sum notation in Julia/JuMP) which is 3 years old unfortunately, but it's exactly what I want. However the code fails due to a number of syntax errors as the sum() function has changed these past few years.

For my code, I found that the sum() function only works for one indexing variable i, but if I include another variable j, the function stops working. I'm also using jupyter notebook if that makes any difference. Any ideas?

Using JuMP
ZS = Model(with_optimizer(Gurobi.Optimizer))

P = [[10 -20];
    [30 -40]]

@variable(ZS, x[1,1:2])
@variable(ZS, y[1:2,1])


@objective(ZS, Max, sum(x[i]*P[i,j]*y[j] for i=1:2 for j=1:2)) 


@constraint(ZS, con1, x[1] + x[2] <= 1)
@constraint(ZS, con2, y[1] + y[2] <= 1)

optimize!(ZS)

For this example of code, I received a "key not found" error


Solution

  • Change definitions of variables to be one-dimensional like this:

    @variable(ZS, x[1:2])
    @variable(ZS, y[1:2])
    

    and all should work as expected.

    Alternatively leave x and y two dimensional and redefine your objective and constraints like this:

    @objective(ZS, Max, sum(x[1,i]*P[i,j]*y[j,1] for i=1:2 for j=1:2)) 
    
    @constraint(ZS, con1, x[1,1] + x[1,2] <= 1)
    @constraint(ZS, con2, y[1,1] + y[2,1] <= 1)
    

    As a side note you can define P more simply like this:

    julia> P = [10 -20
                30 -40]
    2×2 Array{Int64,2}:
     10  -20
     30  -40