在python中使用networkx高效地生成所有路径

2024-04-26 03:11:59 发布

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

我试图在一个相当大的网络(20000+弧)中生成从每个原点到每个目的地最多6个节点的所有路径。我使用的是networkx和python2.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)

我真的很感激你的帮助。在


Tags: pathinimportselfifdefairstart
1条回答
网友
1楼 · 发布于 2024-04-26 03:11:59

我实际上问了这个问题previously关于优化我以前用networkx编写的一个算法。基本上,你要做的是从递归函数中脱离出来,而转向像我一样使用记忆的解决方案。在

从这里可以进一步优化,比如使用multiple cores,或者根据度等条件选择要遍历的下一个节点。在

相关问题 更多 >