【发布时间】:2019-07-29 15:21:41
【问题描述】:
我之前在 igraph 中使用了函数distance(),它计算两个节点或两个节点向量之间的距离。现在我正在使用NetworkX 2.2 在python 中编写代码,并且我还试图找到两个节点列表之间的距离(不是两个节点)。
似乎在 NetworkX 中没有功能可以做到这一点。事实上,我使用了shortest_path_length(),但它没有用。我在这里做的是:1.逐条读取图形,2.然后为每条边选择第一个顶点v1和第二个顶点v2,3.找到连接到第一个顶点的邻居并找到连接的邻居到第二个顶点,4.最后计算v1的邻居和v2的邻居之间的距离。
最后我想得到,对于每条边,一个向量包含顶点 v1 和 v2 的邻居之间的距离。我在 R 中的代码
library(igraph)
graph<-matrix(c(4,3,4,1,4,2,3,2,3,1),ncol=2,byrow=TRUE)
g<-graph.data.frame(d = graph, directed = FALSE)
v1<-c()
v2<-c()
n1<-list()
n2<-list()
distance<-list()
distance.bt.neighbors<-list()
for(edge in 1:length(E(g))){
v1[edge]<-ends(graph = g, es = edge)[1]
v2[edge]<-ends(graph = g, es = edge)[2]
n1<-neighbors(g,v1[edge],mode=c("all"))
n2<-neighbors(g,v2[edge],mode=c("all"))
distance[[edge]]<-distances(g, v = n1, to = n2, mode = c("all"))
distance.bt.neighbors[[edge]]<-c(distance[[edge]])
}
distance.bt.neighbors
[[1]]
[1] 1 1 1 1 0 2 1 2 0
[[2]]
[1] 1 1 1 0 1 1
[[3]]
[1] 1 1 1 0 1 1
[[4]]
[1] 0 1 1 1 1 1
[[5]]
[1] 0 1 1 1 1 1
为了在python中做到这一点,我写了这段代码
import os
import igraph
import numpy as np
import networkx as nx
os.chdir('Desktop')
graph = nx.read_edgelist("attempt") # the file attempt contains the same data as in the R code.
neighbor1 = []
neighbor2 = []
distance = []
for edge in list(graph.edges):
neighbor1.append(list(graph.neighbors(edge[0])))
neighbor2.append(list(graph.neighbors(edge[1])))
distance.append(nx.shortest_path_length(graph, source=neighbor1, target= neighbor2))
但我收到此错误,指出邻居未定义为顶点,因为它们不是单个值的列表
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/home/abdelrahman/anaconda/lib/python3.7/site-packages/networkx/algorithms/shortest_paths/generic.py", line 312, in shortest_path_length
p = nx.bidirectional_shortest_path(G, source, target)
File "/home/abdelrahman/anaconda/lib/python3.7/site-packages/networkx/algorithms/shortest_paths/unweighted.py", line 223, in bidirectional_shortest_path
raise nx.NodeNotFound(msg.format(source, target))
networkx.exception.NodeNotFound: Either source [['3', '4']] or target [['1', '2']] is not in G
在 python 中是否有可能获得一个顶点列表之间的距离列表,而不是像我在 R 中所做的那样的单个值?有没有这样的功能,如果没有,是否可以修改当前的功能?
注意:我没有使用 igraph-python 来获取所需的列表,原因有两个:根据我的搜索,在 igraph 中没有这样的功能,以及避免丢失 tryinh 时产生的顶点名称的问题获取顶点的邻居。
【问题讨论】: