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

How to plot intermediate solutions of or-tools with plotly

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

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

这是来自 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()

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