如何使用osmnx并行路由计算?

2024-06-29 00:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试并行化我的代码

我想要它做的是为每个目标计算目标和其余网络节点之间的所有最短路径

例如,如果我有一个由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, origin, 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个列表

我质疑我写的代码,因为如果没有循环,并且只有一个目标,代码运行大约需要14秒。但是当我把所有的东西都放在循环中时,它需要很长时间,我不知道它是否正确


Tags: import网络true目标formatplotlibasde