Is there a faster way to define variables using pulp for linear programming?

Viewed 117

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.

1 Answers

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.

Related