Search code examples
pythonpython-3.xlinear-programminggurobi

How to define multiple indices for Gurobi with Python API where indices are of different data types and depend on each other?


I'm quite new to Gurobi and Python and I came across a following problem. Given are sets:

import pandas as pd

I = pd.DataFrame(index = ['i0', 'i1', 'i2', 'i3', 'i4'])

L = [('k0', 'j2'), ('k0', 'j3'), ('k0', 'j4'), ('k1', 'j3'), ('k2', 'j1'), ('k2', 'j2'), ('k2', 'j4')]

N_i = {'i0': [('k0', 'j4')],'i1': [('k0', 'j3'), ('k1', 'j3')],
 'i2': [],'i3': [('k0', 'j2'), ('k0', 'j3'), ('k0', 'j4'), ('k2', 'j2'), ('k2', 'j4')],
 'i4': [('k0', 'j4')]}

theta = {'i0': 27, 'i1': 36, 'i2': 31, 'i3': 14, 'i4': 41}

I have to define the following objective function and constraint:

enter image description here

I tried to do something like this in different variations, but it didn't work.

import gurobipy as gp
from gurobipy import GRB
import itertools

model1 = gp.Model('Location-allocation problem 1')
x_ikj = model1.addVars(list(itertools.product(I.index, L)), vtype = GRB.INTEGER, name = 'x_ikj')
model1.addConstrs(gp.quicksum(x_ikj[i, k, j]
            for (k, j) in N_i[i]) >= theta[i] for i in I.index)

Do you have any ideas how can I formulate such a problem?


Solution

  • First, you defined the index tuple of x_ikj as (i, (k, j)) rather than (i, k, j). In fact, itertools.product is unnecessary since gurobipy.Model.addVars() does the cross-product for you. So the simple fix is to write:

    x_ikj = model1.addVars(I.index, L, vtype = GRB.INTEGER, name = 'x_ikj')
    

    Additionally, it looks like you're mixing a Pandas DataFrame (for I) with Python built-in data types for L. This is not common; people typically pick one data type or the other.