泡菜不适合PuLP

时间:2014-04-03 21:18:01

标签: python pickle linear-programming pulp

我正在使用Python 2.7并使用PuLP库来设置问题。一旦定义了变量,目标和约束,我就会挑选我的LpProblem对象以发送给其他地方的Solver。在解决我的问题时,我注意到所有变量都是重复的:

import pulp
import pickle

prob = pulp.LpProblem('test problem', pulp.LpMaximize)
x = pulp.LpVariable('x', 0, 10)
y = pulp.LpVariable('y', 3, 6)
prob += x + y
prob += x <= 5

print prob
print pickle.loads(pickle.dumps(prob))

第一个print语句输出:

>>> print prob
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5

VARIABLES
x <= 10 Continuous
3 <= y <= 6 Continuous

而第二次打印:

>>> print pickle.loads(pickle.dumps(prob))
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5

VARIABLES
x <= 10 Continuous
x <= 10 Continuous
3 <= y <= 6 Continuous
3 <= y <= 6 Continuous

正如您所看到的,目标和约束都很好,但所有变量都是重复的。导致此行为的原因是什么,以及如何防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

所以我还没弄清楚为什么会发生这种情况,但对于陷入同样情况的人,我确实有办法解决这个问题:

def UnpicklePulpProblem(pickled_problem):
    wrong_result = pickle.loads(pickled_problem)
    result = pulp.LpProblem(wrong_result.name, wrong_result.sense)
    result += wrong_result.objective
    for i in wrong_result.constraints: result += wrong_result.constraints[i], i
    return result

以这种方式添加目标和约束可确保变量仅在问题中定义一次,因为您基本上是从头开始重建问题。