gpt4 book ai didi

python - 如何用plotly绘制or-tools的中间解

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:12 24 4
gpt4 key购买 nike

最近,我在 plotly 上遇到了很多困难,似乎我驯服了它来满足我的需求,直到这个问题出现。我正在使用 or-tools 求解器解决作业车间问题,并使用plotly 创建交互式甘特图。一切都很顺利,但还有一件事让它变得完美。我不想简单地绘制这个数学问题的最终结果,还想绘制中间步骤,这意味着求解器在找到最佳解决方案之前找到的所有解决方案。 Or-Tools 在其网站上提供了解决方案打印机的代码,这满足了我的要求:它打印找到的中间解决方案。我面临的唯一问题是:我无法用plotly 绘制中间解决方案。

下面你可以看到Or-Tools提供的代码,我针对我的问题修改了它,它工作得很好。它打印中间解决方案。一旦求解器找到最佳解决方案,它就会继续执行我的绘图函数并绘制甘特图。我尝试将绘图函数放在 VarArraySolutionPrinter 类的 on_soltuion_callback 函数中。发生了什么,它绘制找到的第一个解决方案并停止代码的执行。有没有一种方法可以绘制我的求解器在实现最优的过程中找到的所有解决方案?

这是来自 or-tools 的代码:来源:https://developers.google.com/optimization/cp/cp_solver

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ortools.sat.python import cp_model


class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
"""Print intermediate solutions."""

def __init__(self, variables):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__variables = variables
self.__solution_count = 0

def on_solution_callback(self):
self.__solution_count += 1
for v in self.__variables:
print('%s=%i' % (v, self.Value(v)), end=' ')
print()

def solution_count(self):
return self.__solution_count


def SearchForAllSolutionsSampleSat():
"""Showcases calling the solver to search for all solutions."""
# Creates the model.
model = cp_model.CpModel()

# Creates the variables.
num_vals = 3
x = model.NewIntVar(0, num_vals - 1, 'x')
y = model.NewIntVar(0, num_vals - 1, 'y')
z = model.NewIntVar(0, num_vals - 1, 'z')

# Create the constraints.
model.Add(x != y)

# Create a solver and solve.
solver = cp_model.CpSolver()
solution_printer = VarArraySolutionPrinter([x, y, z])
status = solver.SearchForAllSolutions(model, solution_printer)

print('Status = %s' % solver.StatusName(status))
print('Number of solutions found: %i' %solution_printer.solution_count())


SearchForAllSolutionsSampleSat()

最佳答案

我终于明白了。我只是深度复制了我的对象并绘制了对象的深度复制版本。

关于python - 如何用plotly绘制or-tools的中间解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429875/

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