Google OR-Tools TSP 返回几个解决方案

2024-04-21

我最近一直致力于使用 Google 的 OR-Tools 寻找最佳路线以外的内容。我找到了一个仓库中的示例 https://github.com/google/or-tools/blob/master/examples/dotnet/csharp/tsp.cs,但这只能解决最佳路线,您知道如何为一组点生成多个解决方案吗?我目前正在使用该工具的 DotNet 版本,任何其他语言的解决方案都会有所帮助!

public class tspParams : NodeEvaluator2
{
    public static int[,] distanceMatrix =
    {
        {   0,  20,  40,   10   },
        {   20,  0,   4,   55   },
        {   40,  4,   0,   2    },
        {   10, 55,   2,   0    }
    };

    public static int tsp_size
    {
        get { return distanceMatrix.GetUpperBound(0) + 1; }
    }

    public static int num_routes
    {
        get { return 1; }
    }

    public static int depot
    {
        get { return 0; }
    }

    public override long Run(int FromNode, int ToNode)
    {
        return distanceMatrix[FromNode, ToNode];
    }
}

public class TSP
{
    public static void PrintSolution(RoutingModel routing, Assignment solution)
    {
        Console.WriteLine("Distance of the route: {0}", solution.ObjectiveValue());

        var index = routing.Start(0);

        Console.WriteLine("Route for Vehicle 0:");
        while (!routing.IsEnd(index))
        {
            Console.Write("{0} -> ", routing.IndexToNode(index));
            var previousIndex = index;
            index = solution.Value(routing.NextVar(index));
        }
        Console.WriteLine("{0}", routing.IndexToNode(index));
        //Console.WriteLine("Calculated optimal route!");
    }

    public static void Solve()
    {
        // Create Routing Model
        RoutingModel routing = new RoutingModel(
            tspParams.tsp_size, 
            tspParams.num_routes, 
            tspParams.depot);

        // Define weight of each edge
        NodeEvaluator2 distanceEvaluator = new tspParams();

        //protect callbacks from the GC
        GC.KeepAlive(distanceEvaluator);
        routing.SetArcCostEvaluatorOfAllVehicles(distanceEvaluator);

        // Setting first solution heuristic (cheapest addition).
        RoutingSearchParameters searchParameters = RoutingModel.DefaultSearchParameters();
        searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc;

        Assignment solution = routing.SolveWithParameters(searchParameters);
        PrintSolution(routing, solution);
    }
}

Use AllSolutionCollector来自底层 CP 求解器。蟒蛇代码:

    solver = routing.solver()
    collector = solver.AllSolutionCollector()

    for location_idx in range(len(data['time_windows'])):
        index = manager.NodeToIndex(location_idx)
        time_var = time_dimension.CumulVar(index)
        next_var = routing.NextVar(index)
        collector.Add(time_var)
        collector.Add(next_var)
    for v in range(data['num_vehicles']):
        index = routing.Start(v)
        time_var = time_dimension.CumulVar(index)
        next_var = routing.NextVar(index)
        collector.Add(time_var)
        collector.Add(next_var)

        index = routing.End(v)
        time_var = time_dimension.CumulVar(index)
        collector.Add(time_var)

    routing.AddSearchMonitor(collector)

    assignment = routing.SolveFromAssignmentWithParameters(initial_solution, search_parameters)
    if assignment:
        logger.info("solution count: %d", collector.SolutionCount())
        for index in range(collector.SolutionCount()):
            logger.info("solution index: %d", index)
            self.print_solution(data, manager, routing, collector.Solution(index))
        logger.info('final solution:')
        self.print_solution(data, manager, routing, assignment)
    else:
        raise OptimizationInternalException("no solution found")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google OR-Tools TSP 返回几个解决方案 的相关文章

随机推荐