[英]find the most efficient path (in term of shortest distance) between a set of 2D points
I have a set of 2D points stored in a dictionary and i need to find the most efficient path to sampling all points (red traingles) in term of the shortest distance from a start-end point (yellow circle). 我在字典中存储了一组2D点,我需要找到最有效的路径来采样所有点(红色梯级),即距起点(黄圈)的最短距离。
dict_points = OrderedDict([(0, (0.5129102892466411, 1.2791525891782567)), (1, (1.8571436538551014, 1.3979619805011203)), (2, (2.796472292985357, 1.3021773853592946)), (3, (2.2054745567697513, 0.5231652951626251)), (4, (1.1209493135130593, 0.8220950186969501)), (5, (0.16416153316980153, 0.7241249969879273))]) dict_points = OrderedDict([[0,(0.5129102892466411,1.2791525891782567)),(1,(1.8571436538551014,1.3979619805011203)),(2,(2.796472292985357,1.3021773853592946)),(3,(2.2054745567697513,0.5231652951626251493)),(4,( ,0.8220950186969501)),(5,(0.16416153316980153,0.7241249969879273))])
where the key is the ID of the point 关键是点的ID
My strategy is very simple. 我的策略很简单。 I use all points sequence possible (720 for 6 points) and i compute the euclidean distance point-by-point starting and ending from the start-end point (yellow point). 我使用所有可能的点序列(6个点为720),并从起点到终点(黄点)逐点计算欧几里得距离。 The sequence with the shortest total distance is the most efficient. 总距离最短的序列最有效。
The problem of this approach is that get very slow for a large number of points 这种方法的问题是,对于很多点来说,它变得非常慢
import math
import itertools
base = (2.596, 2.196)
def segments(poly):
"""A sequence of (x,y) numeric coordinates pairs """
return zip(poly, poly[1:] + [poly[0]])
def best_path(dict_points, base=None):
sequence_min_distance = None
l = dict_points.keys()
gen = itertools.permutations(l)
min_dist = float('+inf')
for index, i in enumerate(gen):
seq = gen.next()
seq_list = [dict_points[s] for s in seq]
if base:
seq_list.insert(0, base)
points_paired = segments(seq_list)
tot_dist = 0
for points in points_paired:
dist = math.hypot(points[1][0] - points[0][0], points[1][1] - points[0][1])
tot_dist += dist
if tot_dist <= min_dist:
sequence_min_distance = seq
min_dist = min(min_dist, tot_dist)
return sequence_min_distance
best_seq = best_path(dict_points)
(5, 4, 3, 2, 1, 0)
您还可以查看项目tsp-solver
https://github.com/dmishin/tsp-solver
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.