pulpython中LP的约束公式化

2024-10-01 09:38:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个LP问题,我试图用Python-3中的PuLP来解决它。我能想到的一个选择是显式地编写所有变量,但我想避免它。有没有一种方法可以在这个问题中使用列表/字典?(我确实提到了使用dicts的https://pythonhosted.org/PuLP/CaseStudies/a_sudoku_problem.html,但不太了解整个解决方案)

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

LP问题:The objective function image

(这里,cost{i,j}是所有(i,j)配对的已知成本。在

受制于:

The constraint equations image

我将非常感谢任何帮助,因为我是优化和python/pull的初学者。在


Tags: 方法httpsorg列表字典html解决方案pulp
1条回答
网友
1楼 · 发布于 2024-10-01 09:38:10

“list/dicts”是一种在域(索引变量)上定义变量的方法。 LpVariable.dicts()indexs参数定义所提供集的域笛卡尔积。另见纸浆的文档-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]))

相关问题 更多 >