tsp问题 python_ortools tsp问题

b334ddd1e1228f4926f6f2abda140389.png

ortools是谷歌的一个开源框架,这里笔者用的是Python版本,去解决一个已知距离矩阵,求最短路径的问题。最短路径,也就是travel saleman problem,是指一个旅行商想一次走遍所有的目的地,同时花费最短的距离或时间。抽象来说既是在一个连通图上,求n个节点的最短路径。

首先贴上官方的代码,python3.6可跑通

https://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/tsp_cities.py​github.com

这个代码的一个问题是计算了回程的路径,实际上很多最短路径问题不需要计算。那么我们要知道ortools的vrp问题是通过distance_callback函数来传入距离的。因此针对返回节点 to node等于0的情况,我们可以设置距离成本为0。

def 

也就是修改回程距离为0。继续运行,结果为

Objective: 5765 miles
Route for vehicle 0:
 0 -> 7 -> 2 -> 3 -> 9 -> 10 -> 5 -> 4 -> 12 -> 11 -> 1 -> 8 -> 6 -> 0

修改print solution,把经过的站点和距离加入list中,最后return出来。

def print_tsp_solution(manager, routing, solution):
    """Prints solution on console."""
    print('Objective: {} miles'.format(solution.ObjectiveValue()))
    index = routing.Start(0)
    plan_output = 'Route for vehicle 0:n'
    route_distance = 0
    route = []
    cost = []
    while not routing.IsEnd(index):
        plan_output += ' {} ->'.format(manager.IndexToNode(index))
        route.append(manager.IndexToNode(index))
        previous_index = index
        index = solution.Value(routing.NextVar(index))
        route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)
        cost.append(routing.GetArcCostForVehicle(previous_index, index, 0))
    plan_output += ' {}n'.format(manager.IndexToNode(index))
    print(plan_output)
    plan_output += 'Route distance: {}milesn'.format(route_distance)
    # [END solution_printer]
    return route,cost

修改main函数名字(略)。

我们可以自定义一个建立距离矩阵的函数,输入是poi的经纬度列表,输出是距离矩阵。

注意这里的参数第一个元素是起点,其他元素是各个配送终点。

def 

gaode_geodistance_poi是我自己调用高德计算的骑行距离,key我已经隐藏了。需要的小伙伴自行去高德开发平台注册一个。

最后做少许修改,就可以用get_short_dist_by_pois来计算n个poi坐标的最短距离了。全部代码如下。有问题的留言我。

from 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值