2

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

2 Answers2

1

Seems like you need an update of the for loop syntax and to set your solver to be non-convex.

I also recommend using anonymous labeling for vars, exp etc so that you can change them as required.

using JuMP
using Gurobi
ZS = Model(Gurobi.Optimizer)

set_optimizer_attribute(ZS, "NonConvex", 2)

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

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


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


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


optimize!(ZS)

Runtime is pretty dang long though...

Chris Swan
  • 57
  • 8
0

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
Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • Thanks for that, however now I have another error which I believe has something to do with my objective function not being implemented properly as it has 2 variables x and y. I now receive this error: Gurobi.GurobiError(10020, "Objective Q not PSD (diagonal adjustment of 7.0e+01 would be required)") – victor chin May 19 '19 at 09:53
  • The error is that your objective function is not PSD (ie. positive semi definite). Quadratic solver in Gurobi supports PSD objectives. If objective is not PSD your objective function may be non-convex in the admissible domain and thus have multiple local minima. In such a case, if you want to find a global minimum, you need to use some global optimization routine. If you need only a local minimum then you can use any general gradient optimization package. – Bogumił Kamiński May 19 '19 at 10:13