How to embed a lpSum in another lpSum

233 views
Skip to first unread message

Tao Wu

unread,
Sep 3, 2020, 4:09:05 AM9/3/20
to pulp-or-discuss
Greetings...
I need to write an objective like the following: 
sum {t in period, b in SetB} (    ParA[t, b]*VarA[t,b] / (sum{c in SetC} ParB[t, b, c])    ).

It needs to do a summation within another summation.

I have written the pulp code like the follows:
model += pulp.lpSum([  ParA[t, b]*VarA[t,b]  / (pulp.lpSum([ParB[t, b, c] for c in SetC)) for  t in period, b in SetB ] )

but it did not work.  Could anyone help me correct the code?  Appreciate your help.

Regards,

Tao

VTW

unread,
Sep 8, 2020, 2:17:49 AM9/8/20
to pulp-or-discuss
Hi!,

It would help if you had shared the error message that you get. But looking at your code, my guess is that the problem comes from dividing a pulp variable by something, which gives the following error message
TypeError: unsupported operand type(s) for /: 'LpVariable' and 'float'

I am guessing this is to prevent weird things to happen if you by accident divide by zero. The best way to solve this would probably be to do the calculations of coefficient first, and then multiply that with the pulp variable.

Example:
  • ParB is a numpy array with floats and shape (3,3)
  • ParC is a numpy array with floats and shape (3,3,5)
  • Var is a numpy array with PuLP variables and shape (3,3)
pulp.lpSum( ( ParA / ParB.sum(axis=2) ) * VarA )

PS: Note that the method .sum(axis=2) sums the third dimension of ParB, since everything is zero-indexed in Python, giving is the shape (3,3) before division. Also note that matrix division and multiplication is done element-wise unless you use specific operations for doing linear algebra operations.
Reply all
Reply to author
Forward
0 new messages