找到一组2D点之间最有效的路径(就最短距离而言)

时间:2015-09-23 20:00:29

标签: python algorithm performance euclidean-distance

我有一组存储在字典中的2D点,我需要找到最有效的路径,根据距起点(黄色圆圈)的最短距离对所有点(红色traingles)进行采样。

enter image description here

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))])

其中键是点的ID

我的策略非常简单。我使用所有可能的点序列(720点为6点)并且我从起点(黄点)开始和结束地逐点计算欧几里德距离。总距离最短的序列效率最高。

这种方法的问题是对于大量的点来说非常慢

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)

1 个答案:

答案 0 :(得分:0)

您还可以查看项目tsp-solver https://github.com/dmishin/tsp-solver