Google OR-Tools设置SAVINGS初始策略时无结果返回求助
解决Google OR-Tools中SAVINGS策略无结果返回的问题
以下是几个排查和解决的方向:
- 检查OR-Tools版本:Clarke-Wright节约算法对应的
SAVINGS策略是在OR-Tools v9.0及之后版本才加入的,如果你的版本低于这个,这个枚举值其实是无效的,程序会静默失败。可以通过print(ortools.__version__)查看版本,及时升级到最新稳定版。 - 修正参数设置的语法:你的代码里给枚举值加了多余的括号,虽然Python语法不会报错,但可能导致参数传递异常,改成:
search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.SAVINGS - 开启错误日志与状态检查:默认情况下OR-Tools不会打印详细错误,你可以添加日志配置,同时检查求解状态:
状态码比如from ortools.routing import routing_log_pb2 # 添加日志配置 search_parameters.log_search = True search_parameters.logging_options = routing_log_pb2.LoggingOptions() search_parameters.logging_options.log_to_stdout = True # 求解后检查状态 solution = routing.SolveWithParameters(search_parameters) print(f"求解状态: {routing.status()}")ROUTING_NOT_SOLVED会告诉你问题所在,比如约束冲突、策略不支持等。 - 确认问题配置的合理性:
- 如果你的CVRP问题只有1个客户节点,SAVINGS算法没有可合并的路径,可能不会生成有效输出;
- 检查车辆容量、节点需求的设置是否合理,比如有没有需求超过车辆容量的情况,这种会直接导致无解。
- 验证求解结果的输出逻辑:确保你保留了官方示例中遍历结果、打印路径的代码,比如:
如果没有这段逻辑,就算求解成功你也看不到结果。if solution: print(f"总行驶距离: {solution.ObjectiveValue()} 单位") # 遍历车辆打印路径 for vehicle_id in range(manager.GetNumberOfVehicles()): index = routing.Start(vehicle_id) plan_output = f"车辆 {vehicle_id} 的路径:\n" route_distance = 0 while not routing.IsEnd(index): plan_output += f" {manager.IndexToNode(index)} ->" previous_index = index index = solution.Value(routing.NextVar(index)) route_distance += routing.GetArcCostForVehicle(previous_index, index, vehicle_id) plan_output += f" {manager.IndexToNode(index)}\n" plan_output += f"路径总距离: {route_distance} 单位\n" print(plan_output) else: print("未找到可行解")
内容的提问来源于stack exchange,提问作者Cakra1337
相关产品推荐
相关产品推荐

