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

PuLp: min and max thresholds for lpSum constraints

我有一个大型线性规划模型,我正尝试使用 PuLp 求解。到目前为止,一切都很顺利,除了我在尝试为我的 dict 变量中的每个 "row" 设置最小值和最大值时遇到了障碍。在下面的示例中,我希望每个区域的动物数量最少和最多。

为简化起见,变量名称已更改为 "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))

结果如下。问题是这些变量中的每一个都应该有一个不小于 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]

如何在行级别分配最小和最大界限?

您目前在 dogs/cats 的总和上加上了 minimum/maximum。 请尝试以下操作:

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 中建模 :)