summing over multiple indices

1,465 views
Skip to first unread message

eric

unread,
Nov 15, 2009, 8:20:39 AM11/15/09
to pulp-or-discuss
Hi, sorry for the simple question, but I'm new to pulp and not that
good at python yet. (I'll be happy to rtfm if someone tells me where
to look.)

I have a 3 dimensional variable:

self.x = LpVariable.dicts("x",(docs, days, shifts),
0,1,LpInteger)

and related costs (using a numpy array)

self.xc = zeros((ndocs,ndays,nshifts))

and I want to add the objective function where I multiply each x by
it's corresponding c.
How do I do that?

More generally, how do I use lpsum over multiple indices?

thanks,
Eric

Stuart Mitchell

unread,
Nov 15, 2009, 4:17:19 PM11/15/09
to pulp-or...@googlegroups.com
ok there is a little thing to remember that pulp.LpVariable.dicts
generates dictionaries of dictionaries so the following is possible

>>> import pulp
>>> docs = ['a','b','c']
>>> days = ['mon','tue', 'wed']
>>> shifts = [0,1,2,3]
>>> x = pulp.LpVariable.dicts('x',(docs,days,shifts),0,1,pulp.LpInteger)
>>> x['a']['mon'][3]
x_a_mon_3

but the numpy array can only index by integers so the following is required.

>>> import pulp
>>> docs = [0,1,2]
>>> days = [0,1,2,3,4]
>>> shifts = [0,1,2,3]
>>> x = pulp.LpVariable.matrix('x',(docs,days,shifts),0,1,pulp.LpInteger)
>>> x[1][1][2]
x_1_1_2
>>> c = numpy.zeros((len(docs),len(days),len(shifts)))
>>> c[1][1][2]
0.0
>>> c[(1,1,2)]
0.0
>>> pulp.lpSum([c[doc][day][shift] * x[doc][day][shift]
... for doc in docs
... for day in days
... for shift in shifts])
0

Note the solution expression is zero as the c matrix is all zero

Stu
--
___________________________________
Dr Stuart Mitchell
Research Fellow
Light Metals Research Centre (LMRC)
University of Auckland
Private Bag 92019
Auckland
New Zealand

Ph (wk) +64 9 3737599 ext 84867
(ddi) +64 9 9234867
(fax) +64 9 3737925
(mb) +64 21 441331
___________________________________

eric

unread,
Nov 15, 2009, 5:40:57 PM11/15/09
to pulp-or-discuss
Thanks! That works great.

Eric
Reply all
Reply to author
Forward
0 new messages