Ошибка времени выполнения: сбой вызова SWIG std :: function в лазурных блоках данных - PullRequest
0 голосов
/ 05 июля 2019

При использовании решателя маршрутизации Google or-tools выдается ошибка во время выполнения. В сегменте кода не было никаких изменений до и после получения этой ошибки. Раньше это работало. Но недавно, после изменения соединения с БД, я получаю эту ошибку. (Хотя я сомневаюсь, как модификация соединения дБ может повлиять на решатель маршрутизации)

Я использую записную книжку 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 =' Маршрут для транспортного средства {}: \ 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.

Пожалуйста, помогите.

1 Ответ

0 голосов
/ 11 июля 2019

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))
...