newbie problem with creating constraints using Python

1,066 views
Skip to first unread message

Betty Love

unread,
Oct 3, 2013, 10:06:17 PM10/3/13
to gur...@googlegroups.com
I'm having trouble adding a set of constraints.  I'm getting a "IndexError: list index out of range" error on the last piece of code below.

Any suggestions would be appreciated.
 

lines = range(3)

products = range(3)

workers = range(20)


cost_per_worker = [700,1000,1500] # on production lines 1,2,3

products_per_worker = [[50,90,120],[75,110,130],[90,125,150]] # product i/line j

demand = [600,800,1000] #for products 1,2,3


# Production line setup costs

setup = [2000,3000,4000]


m = Model('Rader 3.3')


# Variables


# y[i] = 1 if line i is used; 0 otherwise

y = {}

for line in lines:

    y[line] = m.addVar(obj=setup[line],vtype=GRB.BINARY,name='y%s' % (line))

 

# w[i,j,k] = 1 if worker i produces product j on line k

w={}

for i in workers:

    for j in products:

        for k in lines:

            w[i,j,k] = m.addVar(obj=cost_per_worker[k],vtype=GRB.BINARY,name='w%d%d%d' % (i,j,k))


m.update()


#Meet demand for product j

for j in products:

    m.addConstr(quicksum(products_per_worker[j,k]*quicksum(w[i,j,k] for i in workers)

          for k in lines) >= demand[j], 'demand_%d' % (j))


Jakob Sch.

unread,
Oct 4, 2013, 3:20:14 AM10/4/13
to gur...@googlegroups.com
Hi Betty,

an IndexError is usually a sign that you tried to access an index in a list or dictionary, that is not there... I modified your code so that, at least on my computer with gurobi 5.6, it works without errors... Change the last lines to
for j in products:
    m.addConstr(quicksum([products_per_worker[j][k] * quicksum([w[(i, j, k)] for i in workers]) for k
        in lines]) >= demand[j], 'demand_%d' % (j))

I noted that you are mixing some things up in your code. You should pay attention to the difference of lists and dictionaries... A good starting point for some basic python is http://www.greenteapress.com/thinkpython/ or http://www.diveintopython.net/. You could also have a look at the documentary from python itself: http://docs.python.org/2/tutorial/datastructures.html

Hope that helps...
Best regards,
Jakob

Betty Love

unread,
Oct 4, 2013, 10:19:16 AM10/4/13
to gur...@googlegroups.com
Figured it out!  

products_per_worker[j,k]

should have been

products_per_worker[j][k]

Betty Love

unread,
Oct 4, 2013, 11:33:01 AM10/4/13
to gur...@googlegroups.com
Thanks, Jakob.  I did figure out my error in accessing the list products_per_worker  as well as making the argument to quicksum a list.  I've been working off the netflow.py example which uses the tuplelist() object and have had trouble wrapping my brain around that.  Now it's getting clearer!  Thank you again!
Reply all
Reply to author
Forward
0 new messages