我有一个大型线性规划模型,我正在尝试用 PuLp 解决。到目前为止,一切都很好,除了我在尝试为我的 dict 变量中的每个“行”设置最小值和最大值时遇到了障碍。在下面的示例中,我希望每个区域的动物数量最少和最多,如图所示。
为简化起见,变量名改为“dogs”和“cats”
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))
结果如下。问题是这些变量中的每一个都应该有一个不小于 inmin_cats
和的值min_dogs
。它将价值分配给猫和狗的一个区域,而不是传播它。
('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]
如何在行级别分配最小和最大界限?