假设我有一个字典,其中每个元素都是由GPS坐标元组定义的四边形,并且也有一个元组,其中包含了一组旅行的原点和目的点的GPS坐标:(origin_latitude,origin_longitude),(dest_latitude,dest_longitude)),(.))。以下是两个四元数和两次旅行的示例:
dictionary={0:((0,0),(0,1),(1,1),(1,0)),1:((3,3),(3,4),(4,4),(4,3))}
trips=(((0.5,0.5),(3.5,3.5)),((-1,-1),(-2,-2)))我想将每一次旅行划分为原点四边形数、目的地四边形数和原点与目的地之间的组合号(旅行参考号).Here:
import matplotlib.path as mplPath
def is_in_zone(quadri,point):
bbPath = mplPath.Path(quadri)
return bbPath.contains_point(point)
def get_zone_nbr(dictio,trip):
start_zone=-1
end_zone=-1
trip_ref=-1
for key,coordinates in dictio.iteritems():
if is_in_zone(coordinates,trip[0]):
start_zone=key
if is_in_zone(coordinates,trip[1]):
end_zone=key
if start_zone>-1 and end_zone>-1:
trip_ref=len(dictio)*start_zone+end_zone
break
return (start_zone,end_zone,trip_ref)
if __name__=='__main__':
dictionary={0:((0,0),(0,1),(1,1),(1,0)),1:((3,3),(3,4),(4,4),(4,3))}
trips=(((0.5,0.5),(3.5,3.5)),((-1,-1),(-2,-2)))
for t in trips:
get_zone_nbr(dictionary,t)我的字典大约有30长,所以函数get_zone_nbr会很慢。我有数以百万计的旅行要处理。您看到任何优化get_zone_nbr()的明显方法了吗?或者任何能使这段代码运行得更快的东西(例如,多处理,但我不知道如何与循环一起使用它)。
发布于 2015-08-15 15:10:59
一个简单的第一个并行处理是并行地处理您的旅行。
>>> import matplotlib.path as mplPath
>>> def is_in_zone(quadri,point):
... bbPath = mplPath.Path(quadri)
... return bbPath.contains_point(point)
...
>>> def get_zone_nbr(dictio,trip):
... start_zone=-1
... end_zone=-1
... trip_ref=-1
... for key,coordinates in dictio.iteritems():
... if is_in_zone(coordinates,trip[0]):
... start_zone=key
... if is_in_zone(coordinates,trip[1]):
... end_zone=key
... if start_zone>-1 and end_zone>-1:
... trip_ref=len(dictio)*start_zone+end_zone
... break
... return (start_zone,end_zone,trip_ref)
...
>>> dictionary={0:((0,0),(0,1),(1,1),(1,0)),1:((3,3),(3,4),(4,4),(4,3))}
>>> trips=(((0.5,0.5),(3.5,3.5)),((-1,-1),(-2,-2)))
>>>
>>> from pathos.pools import ThreadPool
>>> pool = ThreadPool()
>>>
>>> results = pool.map(lambda x: get_zone_nbr(dictionary, x), trips)
>>> results
[(0, 1, 1), (-1, -1, -1)]我使用的是pathos,它是一个提供更好的序列化、灵活性和交互性的multiprocessing叉。(我也是作者。)
然后,您还可以应用相同的方法将函数get_zone_nbr中的for循环转换为映射函数调用。pathos允许您使用带有多个参数的map调用。由于您正在处理字典项,并且这些项自然是无序的,所以您可以使用“无序迭代映射”(在pathos中是uimap,但在multiprocessing中是imap_unordered)。
我还建议您对代码进行计时,以查看哪个map调用会更快。map调用有几个不同的变体,还有几个不同的并行后端。我在上面使用了一个线程池,但是进程和套接字也是并行的(对于您的情况来说,后者太慢了)。pathos为所有选择提供了统一的API,因此您只需对其进行一次编码,然后放入任何其他池/映射,直到找到适合您的情况最快的池/映射为止。
让pathos在这里:https://github.com/uqfoundation
https://stackoverflow.com/questions/32017766
复制相似问题