4

Im trying to set up a linear programming problem that involves 3 plants and 4 distribution centers. The goal is to minimize the cost but each plant distribution center combo has a different cost associated.

Is there a better way to create variables either with pulp or another library so I don't have to write so many. Currently mine look like this.

from pulp import *  
#define the problem   
prob=LpProblem('transportation', LpMinimize)  
#create Variables  
plant1_center1 = LpVariable('plant1_center1', lowBound=0, cat='Integer')       
plant1_center2 = LpVariable('plant1_center2', lowBound=0, cat='Integer')  
plant1_center3 = LpVariable('plant1_center3', lowBound=0, cat='Integer')  
plant1_center4 = LpVariable('plant1_center4', lowBound=0, cat='Integer')  
plant2_center1 = LpVariable('plant2_center1', lowBound=0, cat='Integer')  
plant2_center2 = LpVariable('plant2_center2', lowBound=0, cat='Integer')   
plant2_center3 = LpVariable('plant2_center3', lowBound=0, cat='Integer')   
plant2_center4 = LpVariable('plant2_center4', lowBound=0, cat='Integer')   
plant3_center1 = LpVariable('plant3_center1', lowBound=0, cat='Integer')   
plant3_center2 = LpVariable('plant3_center2', lowBound=0, cat='Integer')   
plant3_center3 = LpVariable('plant3_center3', lowBound=0, cat='Integer')   
plant3_center4 = LpVariable('plant3_center4', lowBound=0, cat='Integer')  

It works but I hate having to create a variable like this every time.

Mikey
  • 47
  • 6
  • you can add all variables in a dictionary `{'plant{}_center_{}'.format(p,c):LpVariable('plant3_center4', lowBound=0, cat='Integer') for p in range(1,5) for c in range(1,5)}` – Naga kiran Aug 19 '21 at 03:44
  • 1
    @Nagakiran Good suggestion, I think that'd be `{f'plant{p}_center_{c}': LpVariable(f'plant{p}_center{c}', lowBound=0, cat='Integer') for p in range(1,4) for c in range(1,5)}` though – ggorlen Aug 19 '21 at 14:15

1 Answers1

1

How about using string interpolation and a couple of loops for rows (plants) and columns (distribution centers):

from pulp import *

def make_var(i, j):
    return LpVariable(f"plant{i}_center{j}", lowBound=0, cat="Integer")

n_plants = 3
n_dist_centers = 4
prob = LpProblem("transportation", LpMinimize)
plants = [
    [make_var(i, j) for j in range(n_dist_centers)] 
    for i in range(n_plants)
]

for row in plants:
    print(row)

I've zero-indexed it so you can access a particular plant using plants[plant_number][dist_center_number], but you should be able to 1-index it easily if you need to using range(1, n_plants + 1).

See A Transportation Problem which offers similar patterns you could try.

ggorlen
  • 44,755
  • 7
  • 76
  • 106