在Pulp Python中制定LP的约束

时间:2015-05-20 04:43:00

标签: python mathematical-optimization pulp

我有这个LP问题,我试图在Python-3中使用PuLP来解决它。我能想到的一个选择是明确地写出所有变量,但我想避免它。有没有办法在这个问题上使用list / dicts? (我的确提到了使用dicts的https://pythonhosted.org/PuLP/CaseStudies/a_sudoku_problem.html,但并不完全理解整个解决方案)

假设 wt {i,j,type} 表示 person [i] person [j] 之间的交易商品数量

LP问题: The objective function image

(此处, cost {i,j} 是所有(i,j)对的已知配对成本。

受制于:

The constraint equations image

我会非常感激任何帮助,因为我是优化和蟒蛇/纸浆的初学者。

1 个答案:

答案 0 :(得分:4)

' list / dicts'是一种在域上定义变量的方法(索引变量)。 indexs LpVariable.dicts()参数定义了所提供集合的域 - 笛卡尔积。另见PuLP文档 - LpVariable

下面的代码示例不包含您的所有约束,但我相信您可以轻松填写​​剩余的约束。约束1(const1const2)通过wt变量的下限和上限来处理。

from pulp import LpProblem, LpVariable, LpMaximize, LpInteger, lpSum, value

prob = LpProblem("problem", LpMaximize)

# define 'index sets'
I = range(10) # [0, 1, ..., 9]
J = range(10)
T = range(3)

# define parameter cost[i,j]
cost = {}
for i in I:
    for j in J:
        cost[i,j] = i + j # whatever

# define wt[i,j,t]
const1 = 0 # lower bound for w[i,j,t]
const2 = 100 # upper bound for w[i,j,t]
wt = LpVariable.dicts(name="wt", indexs=(I, J, T), lowBound=const1, upBound=const2, cat=LpInteger)

# define assign[i,j]
assign = LpVariable.dicts(name="assign", indexs=(I, J))

# contraint 
for i in I:
    for j in J:
        prob += assign[i][j] == lpSum(wt[i][j][t] for t in T), ""

# objective
prob += lpSum(cost[i,j] * assign[i][j] for i in I for j in J)

prob.solve()

for i in I:
    for j in J:
        for t in T:
            print "wt(%s, %s, %s) = %s" % (i, j, t, value(wt[i][j][t]))

for i in I:
    for j in J:
        print "assign(%s, %s) = %s" % (i, j, value(assign[i][j]))