python - pickle 不能与 PuLP 一起玩

标签 python pickle linear-programming pulp

我正在使用 Python 2.7 并使用 PuLP 库设置问题。一旦定义了变量、目标和约束,我就会挑选我的 LpProblem 对象以发送到别处的求解器。解决我的问题后,我注意到所有变量都是重复的:

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

如您所见,目标和约束都很好,但所有变量都是重复的。是什么导致了这种行为,我该如何防止这种情况发生?

最佳答案

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

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

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

关于python - pickle 不能与 PuLP 一起玩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22849208/

相关文章:

python - 通过 pickle/eval 和 zlib 进行序列化

python - python的pp模块上的PicklingError

php - 有效地保持 PHP 中的前 5 个值

python - 将数组转换为 float ,如何反转该过程?

python - 使用第二个元素从元组列表创建字典

python - 如何转储内部有 import 的函数

python - 在 OR 工具中使用 IntVar

python - 将测试分成偶数时间奴隶

python - 数组组合值

python - 整个应用程序的 Django 组权限