У меня есть эта функция, чтобы найти лучший маршрут:
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)
Но результат: {1: 'A', 2: 'D', 3: 'C', 4: 'B'}
Нетрудно заметить, что A -> B -> C -> D
лучше результата. Есть ли какая-то конфигурация, которой мне не хватает? Или просто так работает ortool: он не всегда находит кратчайшее решение?
Я не эксперт по ortool, поэтому, возможно, я игнорирую некоторые вещи.
Первый ответ, который я понимаю, заключается в том, что наши инструменты не очень хорошо работают с числами с плавающей запятой, а с целыми числами они ищут лучший маршрут. Не уверен, но в данной ситуации мне это помогает.
обратный вызов транзита должен возвращать int64_t
, иначе ваши значения с плавающей запятой приведут к неопределенному поведению. (ред. В мосте SWIG между Python и C++ значения Python's floating
преобразуются в int64_t
).
ссылка:
Объявление маршрутизации RegisterTransitCallback()
:
https://github.com/google/or-tools/blob/2c333f58a37d7c75d29a58fd772c9b3f94e2ca1c/ortools/constraint_solver/routing.h#L654-L658
Типовое определение RoutingTransitCallback
:
https://github.com/google/or-tools/blob/2c333f58a37d7c75d29a58fd772c9b3f94e2ca1c/ortools/constraint_solver/routing_types.h#L49-L50
В вашем образце вы можете умножить все свое значение на 10, чтобы получить целочисленные значения, и разделить их на 10 в функции печати/отображения...
Как сейчас написано, ваш ответ неясен. Пожалуйста, отредактируйте , чтобы добавить дополнительную информацию, которая поможет другим понять, как это относится к заданному вопросу. Более подробную информацию о том, как писать хорошие ответы, вы можете найти в справочном центре.