python车辆路径优化_车辆路径问题中距离维的设置
我正在尝试解决一个有5个司机送货的车辆路线问题。我用haversine和lat long来计算距离矩阵。我是新的或工具,所以遵循vrp的例子。在
问题是,对于5个驱动程序,只为2个驱动程序生成路由,并且这些路径非常长。我想生成多条较短的路线,这样所有的驱动程序都被利用了。请检查我是否设置了错误的约束。在
有人能解释一下,如何在谷歌或工具中设置“距离”维度和设置全局泛成本系数。这是代码和输出。在from __future__ import print_function
import pandas as pd
import numpy as np
import googlemaps
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
gmaps = googlemaps.Client(key='API Key')
def calculate_geocodes():
df = pd.read_csv("banglore_zone.csv")
df['lat'] = pd.Series(np.repeat(0, df.size), dtype=float)
df['long'] = pd.Series(np.repeat(0, df.size), dtype=float)
result = np.zeros([df.size, 2])
for index, row in df.iterrows():
# print(row['Address'])
geocode_result = gmaps.geocode(row['Address'])[0]
lat = (geocode_result['geometry']['location']['lat'])
lng = (geocode_result['geometry']['location']['lng'])
result[index] = lat, lng
df.lat[index] = lat
df.long[index] = lng
print("First step", df)
coords = df.as_matrix(columns=['lat', 'long'])
return coords, df
def calculate_distance_matrix(coordinates, gmaps):
distance_matrix = np.zeros(
(np.size(coordinates, 0), np.size(coordinates, 0))) # create an empty matrix for distance between all locations
for index in range(0, np.size(coordinates, 0)):
src = coordinates[index]
for ind in range(0, np.size(coordinates, 0)):
dst = coordinates[ind]
distance_matrix[index, ind] = distance(src[0], src[1], dst[0], dst[1])
return distance_matrix
def distance(lat1, long1, lat2, long2):
# Note: The formula used in this function is not exact, as it assumes
# the Earth is a perfect sphere.
# Mean radius of Earth in miles
radius_earth = 3959
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi / 180.0
phi1 = lat1 * degrees_to_radians
phi2 = lat2 * degrees_to_radians
lambda1 = long1 * degrees_to_radians
lambda2 = long2 * degrees_to_radians
dphi = phi2 - phi1
dlambda = lambda2 - lambda1
a = haversine(dphi) + math.cos(phi1) * math.cos(phi2) * haversine(dlambda)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius_earth * c
return d
def haversine(angle):
h = math.sin(angle / 2) ** 2
return h
def create_data_model(distance_matrix, number_of_vehicles, depot):
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = distance_matrix
print(distance_matrix)
data['num_vehicles'] = number_of_vehicles
data['depot'] = depot
return data
def print_solution(data, manager, routing, solution, address_dataframe):
"""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(address_dataframe.iloc[manager.IndexToNode(index), 0])
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 main():
coordinates, address_dataframe = calculate_geocodes()
distance_matrix = calculate_distance_matrix(coordinates, gmaps)
data = create_data_model(distance_matrix, 5, 0)
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(
len(data['distance_matrix']), data['num_vehicles'], data['depot'])
# 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)
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
80, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.local_search_metaheuristic = (
routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
search_parameters.time_limit.seconds = 120
search_parameters.log_search = False
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if solution:
print_solution(data, manager, routing, solution, address_dataframe)
if __name__ == '__main__':
main()
距离矩阵和输出是-
^{pr2}$
python车辆路径优化_车辆路径问题中距离维的设置相关推荐
- python多目标优化_多目标优化算法(四)NSGA3(NSGAIII)论文复现以及matlab和python的代码...
前言:最近太忙,这个系列已经很久没有更新了,本次就更新一个Deb大神的NSGA2的"升级版"算法NSGA3.因为multi-objective optimization已经被做烂了 ...
- 知乎 运动规划和路径规划_运动路径–过去,现在和未来
知乎 运动规划和路径规划 Making animations that "feel right" can be tricky. 制作"感觉不错"的动画可能很棘手 ...
- 什么叫python代码的优化_优化Python代码
如果你的问题是关于优化python代码(我认为应该是这样),那么你可以做各种各样的intesting的事情,但是首先: 你可能不应该痴迷于优化python代码!如果您正在使用最快的算法来解决问题,并且 ...
- python 字节码 优化_字节码优化
Python是一种动态语言.这意味着您在编写代码方面有很大的自由度.由于python公开了大量的自省(顺便说一句,这非常有用),许多优化根本无法执行.例如,在第一个示例中,python无法知道调用它时 ...
- python 链表操作 优化_链表的内存优化
我最近制作了一个脚本来生成随机迷宫,它使用一个自定义的迷宫类,由几个迷宫节点构建而成.每个节点如下所示:class mazeNode: def __init__(self, pos, conn = N ...
- python多目标优化_多目标优化---帕累托(Pareto)
多目标优化-帕累托(Pareto) 1 多目标优化简介: 在现实生活中有很多的问题都是由互相冲突和影响的多个目标组成,这些目标不可能同时达到最优的状态,我们通常会尽量让这些目标在一定的区域内达到最佳的 ...
- 【路径规划】基于蚁群算法的多配送中心车辆路径优化方法matlab代码
1模型介绍 一种基于蚁群算法的多配送中心车辆路径优化方法,首先,针对多配送中心车辆路径优化问题,对各个客户点设计了以最近配送中心为启发式信息的惩罚函数;其次,将具有上述启发式信息的罚函数加入到各配送点 ...
- vrp车辆路径问题 php,车辆路径问题(VRP)
[绘芯滑轨屏推荐]车辆路径问题(VRP)一般定义为:对一系列装货点和卸货点,组织适当的行车线路,使车辆有序地通过它们,在满足一定的约束条件(如货物需求量.发送量.交发货时间.车辆容量限制.行驶里程限制 ...
- python画车辆轨迹图_如何利用 Python 绘制酷炫的 车辆轨迹 — 速度时空图?三维数据用二维图像呈现...
说明:本文系交通攻城狮原创文章,如需转载请私信联系,侵权必究. 2020,第 30 期,编程笔记 建议直接阅读精编版:如何利用 Python 绘制酷炫的 车辆轨迹 - 速度时空图?三维数据用二维图像呈 ...
最新文章
- 如何在OS X中打印到PDF文件
- GAN人脸修复--Generative Face Completion
- 微服务之数据同步Porter
- 双边滤波(bilateral filter)彩色图 matlab实现代码
- Codeforces 55D Beautiful Number (数位统计)
- 收藏 | 一文看完吴恩达最新演讲精髓,人工智能部署的三大挑战及解决方案
- tomcat7.0.55配置单向和双向HTTPS连接
- Oracle 10.2.0.4 升级到 10.2.0.5
- heidisql连接远程数据库_远程连接数据库异常问题
- 海康Ehome协议java开发
- 各移动云测试平台对比
- 12306的(再次破解)从查票到购票
- Android-Task execution finished ‘signingReport‘
- 【图文】实操重置密码
- UVa1395(最小值最小生成树+并查集)
- 计算机科学与技术考研双非,985弱势“好考”专业与双非王牌专业大汇总!考研报考必备!...
- 码农的2019又开始了,抓不住重点的我很悲催
- 在echarts中使用百度地图,卫星地图
- 奢华运动服饰品牌博格纳中国首家精品店北京开业;乐高集团品牌零售业务在华发展跃上新台阶 | 知消...
- 防止微机室教师机对学生机的控制