OR-Tools VRP解决方案效果不佳

时间:2020-08-20 16:07:01

标签: optimization traveling-salesman or-tools

我正在尝试测试或使用工具来解决路由求解器以解决基本的TSP问题,但是我无法使其正常工作。在将问题发送到路由求解器之前,我已经有了一个距离矩阵和一堆贪婪的解决方案。例如,我使用底部共享的this website中的示例python代码设置了一个问题。

在示例中,我有10个城市的距离矩阵不对称。最佳贪婪解决方案(从不同城市开始的最接近解决方案)作为初始解决方案存储在data中。我有两个函数:solve_from_initial_route()solve_from_scratch(),可以在有或没有初始解决方案的信息的情况下解决同一问题,并产生相同的结果。求解器在这里表现出一些令人惊讶的行为:

  • 函数solve_from_initial_route()产生初始贪婪解决方案作为最终解决方案,并立即退出(4-5 ms),而无需尝试解决和生成运行时日志(即使启用了搜索日志记录)。
  • 函数solve_from_scratch()产生的贪婪解决方案与最终解决方案相同,并且会生成运行时日志,表明它已评估了许多选项。但是有趣的是,无论我运行求解器多长时间,解决方案始终是相同的。求解器无法以某种方式明智地执行操作,并且总是在评估较差的选择。另一方面,在不到1秒的时间内,针对相同问题运行的遗传算法所产生的解决方案要比贪婪的初始解决方案好得多!
  • 我还尝试了所有其他本地搜索选项,并且对于诸如模拟退火之类的随机算法,您可能希望在不同的时间范围内看到结果的某些变化,但这不会发生,并且解决方案始终与最初的贪婪解决方案!
  • 即使在技术上应该已经评估了所有组合,路由求解器仍会继续运行。 10个城市共有10个城市! =总共要评估3628800个序列,但是其上限要高于求解器一直运行,直到达到搜索极限而不是实际问题极限为止。

我可能没有正确设置所有选项,或者代码中缺少某些内容。在使求解器按预期工作时,我将不胜感激。

谢谢!

!pip install ortools
from __future__ import print_function
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [
        [0, 227543, 133934, 200896, 106495, 163222, 75896, 139494, 46460, 102942],
        [135873, 0, 15673, 174874, 80474, 197318, 109993, 232377, 139343, 46665],
        [229482, 15673, 0, 88692, 183092, 125214, 214714, 153718, 247723, 140274],
        [108503, 174151, 80542, 0, 15674, 169948, 82622, 205007, 111973, 49550],
        [195308, 94193, 167348, 21174, 0, 105716, 169428, 134221, 198779, 136356],
        [77835, 203602, 109992, 176954, 82554, 0, 15660, 174340, 81306, 79000],
        [172835, 119784, 213500, 94785, 189185, 21172, 0, 96019, 190024, 174000],
        [48413, 232967, 139358, 206320, 111919, 168647, 81321, 0, 15662, 108366],
        [141422, 153773, 247490, 128774, 204928, 101504, 174329, 15662, 0, 201374],
        [104492, 139205, 45595, 143494, 49093, 165938, 78612, 200997, 107963, 0]
    ]
    data['initial_routes'] = [
        [8, 7, 6, 5, 4, 3, 2, 1]
    ]
    data['num_vehicles'] = 1
    data['start_idx'] = [0]
    data['end_idx'] = [9]
    return data
def print_solution(data, manager, routing, solution):
    """Prints solution on console."""
    max_route_distance = 0
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        route_distance = 0
        while not routing.IsEnd(index):
            plan_output += ' {} -> '.format(manager.IndexToNode(index))
            previous_index = index
            index = solution.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(
                previous_index, index, vehicle_id)
        plan_output += '{}\n'.format(manager.IndexToNode(index))
        plan_output += 'Distance of the route: {}m\n'.format(route_distance)
        print(plan_output)
        max_route_distance = max(route_distance, max_route_distance)
    print('Maximum of the route distances: {}m'.format(max_route_distance))
def solve_from_initial_route():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['start_idx'],
                                           data['end_idx'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)


    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['distance_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    initial_solution = routing.ReadAssignmentFromRoutes(data['initial_routes'],True)
    print('Initial solution:')
    print_solution(data, manager, routing, initial_solution)

    # Set default search parameters.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 2
    search_parameters.lns_time_limit.seconds = 1
    search_parameters.solution_limit = 15000
    search_parameters.log_search = True

    # Solve the problem.
    solution = routing.SolveFromAssignmentWithParameters(initial_solution, search_parameters)

    # Print solution on console.
    if solution:
        print('Solution after search:')
        print_solution(data, manager, routing, solution)
def solve_from_scratch():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['start_idx'],
                                           data['end_idx'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['distance_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Set default search parameters.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 2
    search_parameters.lns_time_limit.seconds = 1
    search_parameters.solution_limit = 150000
    search_parameters.log_search = True

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print('Solution after search:')
        print_solution(data, manager, routing, solution)
if __name__ == '__main__':
    #solve_from_initial_route()
    solve_from_scratch()

1 个答案:

答案 0 :(得分:1)

如果我运行您的代码,它将打印

Solution after search:
Route for vehicle 0:
 0 ->  8 ->  7 ->  6 ->  5 ->  4 ->  3 ->  2 ->  1 -> 9
Distance of the route: 411223m

这是使用所有节点从0到9的最佳路径(我使用tsp_sat代码进行了检查)。而且发现时间不到1毫秒。

现在,在日志部分,

Solution #5265 (783010, objective minimum = 411223, objective maximum = 1103173, time = 1998 ms, branches = 26227, failures = 14386, depth = 33, OrOpt<3>, neighbors = 351904, filtered neighbors = 5265, accepted neighbors = 5265, memory used = 35.63 MB, limit = 99%)

GLS惩罚了成本函数,因此实际值783010不是真实距离,而是惩罚距离。

现在,solve_from_initial_route()命中了known bug

这是正确的求解代码

# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                       data['num_vehicles'], 
                                       data['start_idx'],
                                       data['end_idx'])

# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)


# Create and register a transit callback.
def distance_callback(from_index, to_index):
    """Returns the distance between the two nodes."""
    # Convert from routing variable Index to distance matrix NodeIndex.
    from_node = manager.IndexToNode(from_index)
    to_node = manager.IndexToNode(to_index)
    return data['distance_matrix'][from_node][to_node]

transit_callback_index = routing.RegisterTransitCallback(distance_callback)

# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

# Set default search parameters.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
search_parameters.time_limit.seconds = 1
search_parameters.lns_time_limit.seconds = 1
search_parameters.solution_limit = 15000
search_parameters.log_search = True

routing.CloseModelWithParameters(search_parameters)

initial_solution = routing.ReadAssignmentFromRoutes(data['initial_routes'],
                                                    True)
print('Initial solution:')
print_solution(data, manager, routing, initial_solution)


# Solve the problem.
solution =  routing.SolveFromAssignmentWithParameters(initial_solution, search_parameters)

这将正确初始化参数,然后搜索找到最佳解决方案。