【问题标题】:Generate all paths in an efficient way using networkx in python在 python 中使用 networkx 以有效的方式生成所有路径
【发布时间】:2026-02-02 23:25:01
【问题描述】:

我正在尝试在一个相当大的网络(20,000 多个弧)中生成从每个起点到每个目的地的最多 6 个节点的所有路径。我正在使用 networkx 和 python 2.7。对于小型网络,它运行良好,但我需要为整个网络运行它。我想知道在 python 中是否有更有效的方法来做到这一点。我的代码包含一个递归函数(见下文)。我正在考虑将一些路径保留在内存中,这样我就不会为其他路径再次创建它们,但我不确定如何快速完成它。现在它甚至无法在几天内完成。 3-4 小时对我的项目来说应该没问题。

这是我创建的示例。出于说明目的,我添加了打印功能,请随意忽略它们。这里也是示例输入文件。 input

import networkx as nx
import pandas as pd
import copy
import os

class ODPath(object):    
    def __init__(self,pathID='',transittime=0,path=[],vol=0,OD='',air=False,sortstrat=[],arctransit=[]):
        self.pathID = pathID
        self.transittime = transittime
        self.path = path
        self.vol = vol
        self.OD = OD
        self.air = air
        self.sortstrat = sortstrat # a list of sort strategies
        self.arctransit = arctransit # keep the transit time of each arc as a list
    def setpath(self,newpath):
        self.path = newpath
    def setarctransitpath(self,newarctransit):
        self.arctransit = newarctransit
    def settranstime(self,newtranstime):
        self.transittime = newtranstime
    def setpathID(self,newID):
        self.pathID = newID
    def setvol(self,newvol):
        self.vol = newvol
    def setOD(self,newOD):
        self.OD = newOD
    def setAIR(self,newairTF):
        self.air = newairTF
    def setsortstrat(self,newsortstrat):
        self.sortstrat = newsortstrat

def find_allpaths(graph, start, end, pathx=ODPath(None,0,[],0,None,False)):
    path = copy.deepcopy(pathx) #to make sure the original has not been revised
    newpath = path.path +[start]    
    path.setpath(newpath)
    if len(path.path) >6:
        return []
    if start == end: 
    return [path]
    if (start) not in graph:    #check if node:start exists in the graph
        return []
    paths = []
    for node in graph[start]:   #loop over all outbound nodes of starting point  
        if node not in path.path:    #makes sure there are no cycles
            newpaths = find_allpaths(graph,node,end,path)
            for newpath in newpaths:
                if len(newpath.path) < 7: #generate only the paths that are with at most 6 hops      
                    paths.append(newpath)
    return paths
def printallpaths(path_temp):
map(printapath,path_temp)
def printapath(path):
print path.path

filename='transit_sample1.csv'
df_t= pd.read_csv(filename,delimiter=',')
df_t = df_t.reset_index()
G=nx.from_pandas_dataframe(df_t, 'node1', 'node2', ['Transit Time'],nx.DiGraph())
allpaths=find_allpaths(G,'A','S')  
printallpaths(allpaths)

非常感谢任何帮助。

【问题讨论】:

  • 如果节点ij 之间有多个路径,您想要所有路径,还是只需要最短路径? Networkx 有一个内置工具,如果您可以使用最短的,它就可以工作。

标签: python python-2.7 pandas graph networkx


【解决方案1】:

我实际上问过这个问题previously,关于优化我之前使用 networkx 编写的算法。从本质上讲,您要做的就是摆脱递归函数,转向像我一样使用记忆化的解决方案。

从这里您可以进行进一步的优化,例如使用multiple cores,或根据度等标准选择下一个要遍历的节点。

【讨论】: