Shew
Shew

Reputation: 1596

Gurobi constraints and objective function

I am very new to Gurobi. I am trying to solve the following ILP

minimize \sum_i c_i y_i + \sum_i \sum_j D_{ij} x_{ij}

Here D is stored as a 2D numpy array. My constraints are as follows

x_{ij} <= y_i y_i + \sum_j x_{ij} = 1

Here's the image of the algebra :

enter image description here

My code so far is as follows,

from gurobipy import *

def gurobi(D,c):
    n = D.shape[0]
    m = Model()
    X = m.addVars(n,n,vtype=GRB.BINARY)
    y = m.addVars(n,vtype=GRB.BINARY)   

    m.update()

    for j in range(D.shape[0]):
        for i in range(D.shape[0]):
            m.addConstr(X[i,j] <= y[i])

I am not sure about, how to implement the second constraint and specify the objective function, as objective terms includes a numpy array. Any help ?

Upvotes: 1

Views: 892

Answers (2)

Martin Bagaram
Martin Bagaram

Reputation: 51

This is a very simple case. You can write the first constraint this way. It is a good habit to name your constraints.

m.addConstrs((x[i,j] <= y[j] for i in range(D.shape[0]) for j in range(D.shape[0])), name='something')

If you want to add the second constraint, you can write it like this

m.addConstrs((y[i] + x.sum(i, '*') <= 1 for i in range(n)), name='something')

you could write the second equations ass well using quicksum as suggested by digEmAll. The advantage of using quicksum is that you can add if condition so that you don't um over all values of j. Here is how you could do it

m.addConstrs((y[i] + quicksum(x[i, j] for j in range(n)) <= 1 for i in range(n)), name='something')

if you only needed some values of j to sum over then you could:

m.addConstrs((y[i] + quicksum(x[i, j] for j in range(n) if j condition)  <= 1 for i in range(n)), name='something')

I hope this helps

Upvotes: 1

digEmAll
digEmAll

Reputation: 57220

Unfortunately I don't have GUROBI because it's really expensive...

but, according to this tutorial the second constraint should be implemented like this :

for i in range(n):
    m.addConstr(y[i] + quicksum(X[i,j] for j in range(n), i) == 1)

while the objective function can be defined as :

m.setObjective(quicksum(c[i]*y[i] for i in range(n)) + quicksum(quicksum(D[i,j] * x[i,j]) for i in range(n) for j in range(n)), GRB.MINIMIZE)

N.B: I'm assuming D is a matrix n x n

Upvotes: 1

Related Questions