Or-tools не дает наилучшего результата для матрицы.Python

Программы на Python
Anonymous
Or-tools не дает наилучшего результата для матрицы.

Сообщение Anonymous »

У меня есть эта функция, чтобы найти лучший маршрут:

Код: Выделить всё

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, поэтому некоторые вещи я игнорирую.

Подробнее здесь: https://stackoverflow.com/questions/787 ... r-a-matrix

Вернуться в «Python»