Networkx - 如何获得显示节点 ID 而不是标签的节点之间的最短路径长度

Networkx - How to get shortest path length between nodes showing node id instead of label

我是 Python 使用 NetworkX 库的新手。

假设我导入了一个 Pajek 格式的文件:

import networkx as nx
G=nx.read_pajek("pajek_network_file.net")
G=nx.Graph(G)

我的文件内容是(在Pajek中,节点被称为"Vertices"):

*Network
*Vertices 6
123 Author1
456 Author2
789 Author3
111 Author4
222 Author5
333 Author6
*Edges 
123 333
333 789
789 222
222 111
111 456

现在,我想计算我网络中节点之间的所有最短路径长度,并且我正在根据库文档使用此函数

path = nx.all_pairs_shortest_path_length(G)

Returns: lengths – 以源和目标为关键字的最短路径长度字典。

我得到的return:

print path
{u'Author4': {u'Author4': 0, u'Author5': 1, u'Author6': 3, u'Author1': 4, u'Author2': 1, u'Author3': 2}, u'Author5': {u'Author4': 1, u'Author5': 0, u'Author6': 2, u'Author1': 3, u'Author2': 2, u'Author3': 1}, u'Author6': {u'Author4': 3, u'Author5': 2, u'Author6': 0, u'Author1': 1, u'Author2': 4, u'Author3': 1}, u'Author1': {u'Author4': 4, u'Author5': 3, u'Author6': 1, u'Author1': 0, u'Author2': 5, u'Author3': 2}, u'Author2': {u'Author4': 1, u'Author5': 2, u'Author6': 4, u'Author1': 5, u'Author2': 0, u'Author3': 3}, u'Author3': {u'Author4': 2, u'Author5': 1, u'Author6': 1, u'Author1': 2, u'Author2': 3, u'Author3': 0}}

如您所见,它真的很难读,以后再用...

理想情况下,我想要的是 return 格式类似于以下内容:

source_node_id, target_node_id, path_length
123, 456, 5
123, 789, 2
123, 111, 4

简而言之,我需要仅使用(或至少包括)节点 ID 来获得 return,而不仅仅是显示节点标签。并且,要在一行中获得每对可能的对应最短路径...

这在 NetworkX 中可行吗?

函数参考:https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.shortest_paths.unweighted.all_pairs_shortest_path_length.html

这样的怎么样?

import networkx as nx                                                            
G=nx.read_pajek("pajek_network_file.net")                                        
G=nx.Graph(G)
# first get all the lengths      
path_lengths = nx.all_pairs_shortest_path_length(G)                              

# now iterate over all pairs of nodes      
for src in G.nodes():
    # look up the id as desired                           
    id_src = G.node[src].get('id')
    for dest in G.nodes():                                                       
        if src != dest: # ignore self-self paths
            id_dest =  G.node[dest].get('id')                                    
            l = path_lengths.get(src).get(dest)                                  
            print "{}, {}, {}".format(id_src, id_dest, l) 

这会产生一个输出

111, 222, 1
111, 333, 3
111, 123, 4
111, 456, 1
111, 789, 2
...

如果您需要做进一步的处理(例如排序),那么存储 l 值而不是仅仅打印它们。

(您可以使用 itertools.combinations(G.nodes(), 2) 之类的方法更清楚地遍历对,但如果您不熟悉,上面的方法会更明确一些。)

最后我只需要计算整个网络的一个子集的最短路径(我的实际网络很大,有600K节点和6M边),所以我写了一个读取源节点和目标节点的脚本来自 CSV 文件的节点对,存储到一个 numpy 数组,然后将它们作为参数传递给 nx.shortest_path_length 并对每一对进行计算,最后将结果保存到 CSV 文件。

代码在下面,我把它贴出来以防它对外面的人有用:

print "Importing libraries..."

import networkx as nx
import csv
import numpy as np

#Import network in Pajek format .net
myG=nx.read_pajek("MyNetwork_0711_onlylabel.net")

print "Finished importing Network Pajek file"

#Simplify graph into networkx format
G=nx.Graph(myG)

print "Finished converting to Networkx format"

#Network info
print "Nodes found: ",G.number_of_nodes()
print "Edges found: ",G.number_of_edges()


#Reading file and storing to array
with open('paired_nodes.csv','rb') as csvfile:
    reader = csv.reader(csvfile, delimiter = ',', quoting=csv.QUOTE_MINIMAL)#, quotechar = '"')
    data = [data for data in reader]
paired_nodes = np.asarray(data)
paired_nodes.astype(int)

print "Finished reading paired nodes file"

#Add extra column in array to store shortest path value
paired_nodes = np.append(paired_nodes,np.zeros([len(paired_nodes),1],dtype=np.int),1)

print "Just appended new column to paired nodes array"

#Get shortest path for every pair of nodes

for index in range(len(paired_nodes)):
    try:
    shortest=nx.shortest_path_length(G,paired_nodes[index,0],paired_nodes[index,1])
        #print shortest
        paired_nodes[index,2] = shortest
    except nx.NetworkXNoPath:
        #print '99999'  #Value to print when no path is found
        paired_nodes[index,2] = 99999

print "Finished calculating shortest path for paired nodes"

#Store results to csv file      
f = open('shortest_path_results.csv','w')

for item in paired_nodes:
    f.write(','.join(map(str,item)))
    f.write('\n')
f.close()

print "Done writing file with results, bye!"