ИЛИ Проблема с доставкой самовывоза инструмента не работает с импортом матрицы расстояний из базы данных - PullRequest
0 голосов
/ 18 июня 2020

Я использую Google OR Tools для решения проблемы с маршрутизацией транспортных средств с перехватом и доставкой. Я импортирую матрицу расстояний из базы данных psql и убедился, что это целочисленный список. Даже тогда я получаю следующую ошибку:

ПРЕДУПРЕЖДЕНИЕ: запись журнала перед InitGoogleLogging () записывается в STDERR F0618 10: 57: 31.900391 Маршрутизация 8448. cc: 1554] Проверка не удалась: доставка <размер (34359738369 vs. 13) <strong>* Проверить трассировку стека сбоев: * Прервано (дамп ядра)

Кто-нибудь может мне помочь с этим?

Это самовывоз доставка мой код (без требований) для справки-

 """Simple Pickup Delivery Problem (PDP)."""
#from __future__ import print_function
import import_data_pd as idp
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

dat = idp.var()
dd=[]

for i in range(10):
    row=[]
    for j in range(10):
        print("dat i j={}".format(dat[i][j]))
        row.append(dat[i][j])
    dd.append(row)
print(type(dd[0][1]))

print("dd={}".format(dd))
# prind output of dd is [[0, 0, 13, 2147, 39, 84666, 84666, 20, 21, 1987], [12, 0, 12, 2160, 39, 84666, 84666, 33, 33, 1999], [42, 29, 0, 2176, 68, 84695, 84695, 49, 49, 2015], [45, 46, 58, 0, 6, 84712, 84712, 66, 67, 2032], [39, 39, 52, 2186, 0, 84705, 84705, 59, 60, 2026], [73, 74, 86, 2221, 34, 0, 0, 94, 94, 2060], [73, 74, 86, 2221, 34, 0, 0, 94, 94, 2060], [34, 22, 33, 2126, 61, 84687, 84687, 0, 0, 1966], [33, 21, 32, 2167, 60, 84686, 84686, 40, 0, 2007], [75, 63, 74, 160, 102, 84728, 84728, 82, 41, 0]]

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = dd
    data['pickups_deliveries'] = [[1, 6], [2, 10], [4, 3], [5, 9], [7, 8], [15, 11], [13, 12], [16, 14]]
    data['num_vehicles'] = 4
    data['depot'] = 0
    return data


def print_solution(data, manager, routing, solution):
    """Prints solution 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
        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)
        total_distance += route_distance
    print('Total Distance of all routes: {}m'.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
        3000,  # 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.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PARALLEL_CHEAPEST_INSERTION)

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

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


if __name__ == '__main__':
    main()

1 Ответ

2 голосов
/ 18 июня 2020

Проблема в том, что ваша матрица расстояний равна 9x9, а некоторые из ваших пар pdp - [15, 11], [13, 12] и [16, 14].

Кроме того, у вас есть расстояния в 80k, а максимальная емкость вашего измерения составляет 3k. Значит, проблема невозможна.

...