PuLp:lpSum约束的最小和最大阈值

时间:2015-10-07 19:44:17

标签: python-2.7 linear-programming pulp coin-or-cbc

我有一个大型线性编程模型,我试图用PuLp解决。到目前为止,一切都很顺利,除了我试图在我的dict变量中为每个“行”设置最小值和最大值时遇到障碍。在下面的例子中,我希望每个区域有最小和最大数量的动物。

为简化,变量名称更改为“狗”和“猫”

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))

结果如下。问题是每个变量的值应不低于min_catsmin_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]

如何在行级别指定最小和最大边界?

1 个答案:

答案 0 :(得分:2)

您目前正在对您的狗/猫的总和进行最小/最大值。 请尝试以下方法:

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] 

PuLP的好运建模:)