pythonor-toolsvehicle-routing

Or-tools is not giving the best route for a matrix with floating point distances


I have this function to find the best route:

from ortools.constraint_solver import pywrapcp, routing_enums_pb2
import numpy as np

def sin_restriccion(matriz_input, indices_input):
    # Convertir el DataFrame a una matriz de distancias
    distance_matrix = matriz_input
    locations = indices_input

    # Crear el modelo de datos
    def create_data_model():
        data = {}
        data['distance_matrix'] = distance_matrix
        data['num_vehicles'] = 1
        data['depot'] = 0  # Puedes ajustar el depot según sea necesario
        return data

    # Crear el modelo de datos
    data = create_data_model()

    # Crear el gestor de rutas
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Crear el modelo de rutas
    routing = pywrapcp.RoutingModel(manager)

    # Crear la función de distancia
    def distance_callback(from_index, to_index):
        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)

    # Definir el costo de la distancia
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Eliminar la restricción de retorno al depot
    routing.SetFixedCostOfAllVehicles(0)
    end_index = manager.NodeToIndex(data['depot'])
    routing.AddDisjunction([end_index], 1000000)  # Penalización alta para no regresar al depot

    # Definir parámetros de búsqueda
    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 = 10  # Ajustar el límite de tiempo según sea necesario

    # Resolver el problema
    solution = routing.SolveWithParameters(search_parameters)

    # Preparar el resultado como un diccionario
    if solution:
        index = routing.Start(0)
        route_dict = {}
        step = 1
        total_distance = 0
        while not routing.IsEnd(index):
            node_index = manager.IndexToNode(index)
            route_dict[step] = locations[node_index]
            next_index = solution.Value(routing.NextVar(index))
            total_distance += distance_callback(index, next_index)
            index = next_index
            step += 1
        # Imprimir distancia total recorrida
        print(f'Distancia total recorrida: {total_distance}')
        return route_dict
    else:
        print('No hay solución')
        return 'No hay solución'

# Ejemplo de uso con la matriz proporcionada
matriz = np.array([
    [0.0, 22.3, 1965.4, 2108.5],
    [500.0, 0.0, 1611.7, 2130.8],  # B a A es 500 en lugar de 22.3
    [2033.1, 2080.6, 0.0, 2267.8],
    [2037.2, 2084.7, 2189.1, 0.0]
])

indices = ['A', 'B', 'C', 'D']

# Llamada a la función
ruta_optima = sin_restriccion(matriz, indices)
print(ruta_optima)

But the result is: {1: 'A', 2: 'D', 3: 'C', 4: 'B'}

It is not too hard to see that A -> B -> C -> D is better that the result. Is there any configuration I am missing? Or its just how ortool works, not always finding the shortest solution?

I am not an expert with ortool so there may be some things I am ignoring.


Solution

  • the transit callback must return an int64_t, otherwise your floating point values will result to an undefind behaviour. (ed In the SWIG bridge between Python and C++, Python's floating values are converted to int64_t).

    ref:
    The routing RegisterTransitCallback() declaration:
    https://github.com/google/or-tools/blob/2c333f58a37d7c75d29a58fd772c9b3f94e2ca1c/ortools/constraint_solver/routing.h#L654-L658
    Typedef of RoutingTransitCallback:
    https://github.com/google/or-tools/blob/2c333f58a37d7c75d29a58fd772c9b3f94e2ca1c/ortools/constraint_solver/routing_types.h#L49-L50

    In your sample you could multiply all your value per 10 to have integer values, and divide them by 10 in your print/display function...