如何解决如何使路由计算与osmnx并行化?
我正在尝试并行化我的代码。
我想要做的是为每个目标计算目标与其余网络节点之间的所有最短路径。
例如,如果我有10000个节点的网络,而我有150个目标,那么我要为每个目标计算网络的10000条最短路径。
我不知道是否可以像我一样做for
循环。
import osmnx as ox
import igraph as ig
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx
import numpy as np
import matplotlib as mpl
import random as rd
import math
import ast
from IPython.display import clear_output
from copy import copy
import matplotlib.cm as cm
import matplotlib.ticker as mtick
import multiprocessing as mp
ox.config(log_console=True,use_cache=True)
cities = ox.geocode_to_gdf(['Município de Lisboa','Município de Oeiras','Município da Amadora','Município de Loures','Município de Odivelas'])
whole_polygon = cities.unary_union #unary union of both geometries
G = ox.graph_from_polygon(whole_polygon,network_type='drive',simplify=True)
G_nx = nx.relabel.convert_node_labels_to_integers(G)
def shortest_path(G,origin,target):
try:
return ox.shortest_path(G_nx,target,weight = 'length')
except:
return None
cpus = mp.cpu_count() -1
nodes = np.array(G.nodes())
n=150
dests = np.random.choice(nodes,size=n,replace=True)
list_routes=[]
for value in dests:
params = ((G,node,value) for node in nodes)
pool = mp.Pool(cpus)
sma = pool.starmap_async(shortest_path,params)
routes = sma.get()
list_routes.append(routes)
pool.close()
pool.join()
我应该得到的是list_routes
,它将包含150个列表。
我质疑我编写的代码,因为没有周期,并且只有一个目标,代码需要大约14s才能运行。但是,当我将所有内容放入周期中时,会花费很长时间,而且我不知道它是否正确。
解决方法
不要使用循环。在此OSMnx使用示例笔记本https://github.com/gboeing/osmnx-examples/blob/v0.16.0/notebooks/02-routing-speed-time.ipynb
中,有一个在路由求解中使用多处理的示例。版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。