gpt4 book ai didi

python - Or-Tools CP-SAT 求解器导出/导入 : how to access vars after loading a model?

转载 作者:行者123 更新时间:2023-12-04 08:27:16 25 4
gpt4 key购买 nike

使用 OR-Tools CP-CAT 求解器的 Python 接口(interface) (reference) ,我希望能够保存 cp_model,稍后或从不同的进程加载它,并继续与之交互。
我能够将模型序列化为 Protubuf,然后加载并解决它:

from google.protobuf import text_format
from ortools.sat.python import cp_model

def create_model():
model = cp_model.CpModel()
a = model.NewIntVar(0, 10, "var_a")
b = model.NewIntVar(0, 10, "var_b")

model.Maximize(a + b)
return model

def clone_model(model):
new_model = cp_model.CpModel()
text_format.Parse(str(model), new_model.Proto())

return new_model

def solve_model(model):
solver = cp_model.CpSolver()
status = solver.Solve(new_model)

print(solver.StatusName(status))
print(solver.ObjectiveValue())

# Works fine
model = create_model()
new_model = clone_model(model)
solve_model(new_model)
(source)
但是,我想在加载模型后继续与模型交互。例如,我希望能够执行以下操作:
model = create_model()
new_model = clone_model(model)

c = new_model.NewIntVar(0, 5, "var_c")
new_model.Add(a < c)
问题是最后一行不起作用,因为 a没有定义;而且我找不到任何方法来访问现有模型的变量。
我正在寻找类似的东西: a = new_model.getExistingVariable("var_a")这将允许我在加载模型后继续与模型中预先存在的变量进行交互。

最佳答案

根据@Stradivari 的评论,一种似乎有效的方法是简单地 pickle模型及其变量。
例如:

from ortools.sat.python import cp_model
import pickle

class ClonableModel:
def __init__(self):
self.model = cp_model.CpModel()
self.vars = {}

def create_model(self):
self.vars['a'] = self.model.NewIntVar(0, 10, "var_a")
self.vars['b'] = self.model.NewIntVar(0, 10, "var_b")

self.model.Maximize(self.vars['a'] + self.vars['b'])

# Also possible to serialize via a file / over network
def clone(self):
return pickle.loads(pickle.dumps(self))

def solve(self):
solver = cp_model.CpSolver()
status = solver.Solve(self.model)

return '%s: %i' % (solver.StatusName(status), solver.ObjectiveValue())
现在,以下工作按预期工作:
model = ClonableModel()
model.create_model()

new_model = model.clone()
new_model.model.NewIntVar(0,5,"c")
new_model.model.Add(new_model.vars['a'] < c)

print('Original model: %s' % model.solve())
print('Cloned model: %s' % new_model.solve())

# Original model: OPTIMAL: 20
# Cloned model: OPTIMAL: 14

关于python - Or-Tools CP-SAT 求解器导出/导入 : how to access vars after loading a model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65199401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com