I have a large linear programming model that I'm trying to solve with PuLp. So far everything is going great except I hit a snag when trying to setup minimums and maximums for each "row" in my dict variable. In the example below, I'd like to have a minimum and maximum amount of animals per area as indicated.
The variable names were changed to "dogs" and "cats" for simplification
import pulp as lp
prob = lp.LpProblem("test problem", lp.LpMaximize)
# in reality I have 20,000 areas
areas = [1, 2, 3]
costs = {1: 300,
2: 310,
3: 283}
dogs = {1: 150,
2: 300,
3: 400}
# Max cats per area
cats = {1: 400,
2: 140,
3: 0}
# minimum dogs per area
min_dogs = {1: 50,
2: 5,
3: 80}
# min cats per area
min_cats = {1: 5,
2: 24,
3: 0}
prob = lp.LpProblem("Example for SO", lp.LpMinimize)
# Setup variables
dog_vars = lp.LpVariable.dicts('dogs', dogs, 0)
cat_vars = lp.LpVariable.dicts('cats', cats, 0)
# Objective:
prob += lp.lpSum([costs[i] * (dog_vars[i] + cat_vars[i]) for i in areas])
# Constraints
prob += lp.lpSum([costs[i] * (dog_vars[i] + cat_vars[i]) for i in areas]) <= 50000
# Constraints not working:
prob += lp.lpSum([dog_vars[i] - min_dogs[i] for i in dogs]) >= 0
prob += lp.lpSum([cat_vars[i] - min_cats[i] for i in cats]) >= 0
prob.solve()
print("Status:", lp.LpStatus[prob.status])
for v in prob.variables():
print(v.name, "=", v.varValue)
print("Total # of km to be done", lp.value(prob.objective))
The results are the following. The issue is there should be a value for each of these variables no less than in min_cats
and min_dogs
. It assigned the value to one area for cats and dogs instead of spreading it.
('Status:', 'Optimal')
('cats_1', '=', 0.0)
('cats_2', '=', 0.0)
('cats_3', '=', 29.0)
('dogs_1', '=', 0.0)
('dogs_2', '=', 0.0)
('dogs_3', '=', 135.0)
('Total # of km to be done', 46412.0)
[Finished in 0.7s]
How can I assign my minimum and maximum bounds at the row level?
You are currently putting a minimum/maximum on the sum of your dogs/cats. Try the following:
for i in areas:
prob += dog_vars[i] >= min_dogs[i]
prob += dog_vars[i] <= max_dogs[i]
prob += cat_vars[i] >= min_cats[i]
prob += cat_vars[i] <= max_cats[i]
Good luck modelling in PuLP :)