0

在使用 google or-tools 的路由求解器时,会抛出运行时错误。在收到此错误之前和之后,代码段中没有进行任何更改。以前,它正在工作。但是最近在进行数据库连接修改后,我收到了这个错误。(虽然,我怀疑 dB 连接修改会如何影响路由求解器)

我正在使用 Azure Databricks 笔记本。由于我是运筹学的新手,因此我将https://developers.google.com/optimization/routing/pickup_delivery#complete_programs页面中给出的示例作为参考。

这是具有拣货和交付问题的车辆路线。

from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = dist
    data['pickups_deliveries'] = nodes_pickup_delivery
    data['num_vehicles'] = 2
    data['depot'] = 0
    return data

solution_list = []
def print_solution(data, manager, routing, assignment):
    """Prints assignment on console."""
    total_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
        i = []
        while not routing.IsEnd(index):
            i.append(manager.IndexToNode(index))
            plan_output += ' {} -> '.format(str(cityList[manager.IndexToNode(index)]))
            previous_index = index
            index = assignment.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(previous_index, index, vehicle_id)
        solution_list.append(i)
        plan_output += '{}\n'.format(str(cityList[manager.IndexToNode(index)]))
        plan_output += 'Distance of the route: {} miles\n'.format(route_distance)
        #print(plan_output)
        total_distance += route_distance 
    #print('Total Distance of all routes: {} miles'.format(total_distance))

def main():
    """Entry point of the program."""
    # Instantiate the data problem.
    data = create_data_model()

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

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

    # Define cost of each arc.
    def distance_callback(from_index, to_index):
        """Returns the manhattan 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)
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        40,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Define Transportation Requests.
    for request in data['pickups_deliveries']:
        pickup_index = manager.NodeToIndex(request[0])
        delivery_index = manager.NodeToIndex(request[1])
        routing.AddPickupAndDelivery(pickup_index, delivery_index)
        routing.solver().Add(routing.VehicleVar(pickup_index) == routing.VehicleVar(delivery_index))
        routing.solver().Add(distance_dimension.CumulVar(pickup_index) <= distance_dimension.CumulVar(delivery_index))

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    #search_parameters.time_limit.seconds = 90
    search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PARALLEL_CHEAPEST_INSERTION)

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

    # Print solution on console.
    if assignment:
        print_solution(data, manager, routing, assignment)


if __name__ == '__main__':
    main()

我得到的错误指向以下代码段:'plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)' 抛出的错误是:

RuntimeError: SWIG std::function invocation failed.

RuntimeErrorTraceback (most recent call last)
<command-2714173895177597> in <module>()
     89 
     90 if __name__ == '__main__':
---> 91     main()

<command-2714173895177597> in main()
     85     # Print solution on console.
     86     if assignment:
---> 87         print_solution(data, manager, routing, assignment)
     88 
     89 

<command-2714173895177597> in print_solution(data, manager, routing, assignment)
     18     for vehicle_id in range(data['num_vehicles']):
     19         index = routing.Start(vehicle_id)
---> 20         plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
     21         route_distance = 0
     22         i = []

RuntimeError: SWIG std::function invocation failed.

请帮忙。

4

1 回答 1

-1

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = dist
    data['pickups_deliveries'] = nodes_pickup_delivery
    data['num_vehicles'] = 2
    data['depot'] = 0 #Dummy location
    return data

solution_list = []
def print_solution(data, manager, routing, assignment):
    """Prints assignment on console."""
    total_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
        i = []
        while not routing.IsEnd(index):
            i.append(manager.IndexToNode(index))
            plan_output += ' {} -> '.format(manager.IndexToNode(index))
            previous_index = index
            index = assignment.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(previous_index, index, vehicle_id)  
        solution_list.append(i)
        plan_output += '{}({})\n'.format(str(cityList[manager.IndexToNode(index)]))
        plan_output += 'Distance of the route: {} miles\n'.format(route_distance)
        print(plan_output)
        total_distance += route_distance
    print('Total Distance of all routes: {} miles'.format(total_distance))

于 2019-07-11T07:46:20.083 回答