OR-Tools VRP解决方案效果不佳

如何解决OR-Tools VRP解决方案效果不佳

我正在尝试测试或使用工具来解决路由求解器以解决基本的TSP问题,但是我无法使其正常工作。在将问题发送到路由求解器之前,我已经有了一个距离矩阵和一堆贪婪的解决方案。例如,我使用底部共享的this website中的示例python代码设置了一个问题。

在示例中,我有10个城市的距离矩阵不对称。最佳贪婪解决方案(从不同城市开始的最接近解决方案)作为初始解决方案存储在data中。我有两个函数:solve_from_initial_route()solve_from_scratch(),可以在有或没有初始解决方案的信息的情况下解决同一问题,并产生相同的结果。求解器在这里表现出一些令人惊讶的行为:

  • 函数solve_from_initial_route()产生初始贪婪解决方案作为最终解决方案,并立即退出(4-5 ms),而无需尝试解决和生成运行时日志(即使启用了搜索日志记录)。
  • 函数solve_from_scratch()产生的贪婪解决方案与最终解决方案相同,并且会生成运行时日志,表明它已评估了许多选项。但是有趣的是,无论我运行求解器多长时间,解决方案始终是相同的。求解器无法以某种方式明智地执行操作,并且总是在评估较差的选择。另一方面,在不到1秒的时间内,针对相同问题运行的遗传算法所产生的解决方案要比贪婪的初始解决方案好得多!
  • 我还尝试了所有其他本地搜索选项,并且对于诸如模拟退火之类的随机算法,您可能希望在不同的时间范围内看到结果的某些变化,但这不会发生,并且解决方案始终与最初的贪婪解决方案!
  • 即使在技术上应该已经评估了所有组合,路由求解器仍会继续运行。 10个城市共有10个城市! =总共要评估3628800个序列,但是其上限要高于求解器一直运行,直到达到搜索极限而不是实际问题极限为止。

我可能没有正确设置所有选项,或者代码中缺少某些内容。在使求解器按预期工作时,我将不胜感激。

谢谢!

!pip install ortools
from __future__ import print_function
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [
        [0,227543,133934,200896,106495,163222,75896,139494,46460,102942],[135873,15673,174874,80474,197318,109993,232377,139343,46665],[229482,88692,183092,125214,214714,153718,247723,140274],[108503,174151,80542,15674,169948,82622,205007,111973,49550],[195308,94193,167348,21174,105716,169428,134221,198779,136356],[77835,203602,109992,176954,82554,15660,174340,81306,79000],[172835,119784,213500,94785,189185,21172,96019,190024,174000],[48413,232967,139358,206320,111919,168647,81321,15662,108366],[141422,153773,247490,128774,204928,101504,174329,201374],[104492,139205,45595,143494,49093,165938,78612,200997,107963,0]
    ]
    data['initial_routes'] = [
        [8,7,6,5,4,3,2,1]
    ]
    data['num_vehicles'] = 1
    data['start_idx'] = [0]
    data['end_idx'] = [9]
    return data
def print_solution(data,manager,routing,solution):
    """Prints solution on console."""
    max_route_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)
        max_route_distance = max(route_distance,max_route_distance)
    print('Maximum of the route distances: {}m'.format(max_route_distance))
def solve_from_initial_route():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),data['num_vehicles'],data['start_idx'],data['end_idx'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)


    # Create and register a transit callback.
    def distance_callback(from_index,to_index):
        """Returns the 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)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    initial_solution = routing.ReadAssignmentFromRoutes(data['initial_routes'],True)
    print('Initial solution:')
    print_solution(data,initial_solution)

    # Set default search parameters.
    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 = 2
    search_parameters.lns_time_limit.seconds = 1
    search_parameters.solution_limit = 15000
    search_parameters.log_search = True

    # Solve the problem.
    solution = routing.SolveFromAssignmentWithParameters(initial_solution,search_parameters)

    # Print solution on console.
    if solution:
        print('Solution after search:')
        print_solution(data,solution)
def solve_from_scratch():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),data['end_idx'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index,to_index):
        """Returns the 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)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Set default search parameters.
    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 = 2
    search_parameters.lns_time_limit.seconds = 1
    search_parameters.solution_limit = 150000
    search_parameters.log_search = True

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

    # Print solution on console.
    if solution:
        print('Solution after search:')
        print_solution(data,solution)
if __name__ == '__main__':
    #solve_from_initial_route()
    solve_from_scratch()

解决方法

如果我运行您的代码,它将打印

Solution after search:
Route for vehicle 0:
 0 ->  8 ->  7 ->  6 ->  5 ->  4 ->  3 ->  2 ->  1 -> 9
Distance of the route: 411223m

这是使用所有节点从0到9的最佳路径(我使用tsp_sat代码进行了检查)。而且发现时间不到1毫秒。

现在,在日志部分,

Solution #5265 (783010,objective minimum = 411223,objective maximum = 1103173,time = 1998 ms,branches = 26227,failures = 14386,depth = 33,OrOpt<3>,neighbors = 351904,filtered neighbors = 5265,accepted neighbors = 5265,memory used = 35.63 MB,limit = 99%)

GLS惩罚了成本函数,因此实际值783010不是真实距离,而是惩罚距离。

现在,solve_from_initial_route()命中了known bug

这是正确的求解代码

# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),data['num_vehicles'],data['start_idx'],data['end_idx'])

# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)


# Create and register a transit callback.
def distance_callback(from_index,to_index):
    """Returns the 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)

# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

# Set default search parameters.
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 = 1
search_parameters.lns_time_limit.seconds = 1
search_parameters.solution_limit = 15000
search_parameters.log_search = True

routing.CloseModelWithParameters(search_parameters)

initial_solution = routing.ReadAssignmentFromRoutes(data['initial_routes'],True)
print('Initial solution:')
print_solution(data,manager,routing,initial_solution)


# Solve the problem.
solution =  routing.SolveFromAssignmentWithParameters(initial_solution,search_parameters)

这将正确初始化参数,然后搜索找到最佳解决方案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-