获取并计算节点邻居Python

时间:2014-07-17 15:30:35

标签: python graph matplotlib nodes networkx

我正在尝试读取具有节点对和权重的文件。我发现每一对的邻居都是个体并且两者都合计。稍后找到每个节点具有的邻居的比率。我很难找到节点。

infile.txt

0_node1 0_node2 0w
1_node1 1_node2 1w
2_node1 2_node2 2w
3_node1 3_node2 3w
4_node1 4_node2 4w

代码:

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
G = nx.read_edgelist('infile.txt', data=[("weight", float)])

def get_triangle(G):
  for n1 in G.nodes:
    neighbors1 = set(G[n1])
    for n2 in filter(lambda x: x>n1, nodes):
      neighbors2 = set(G[n2])
      common = neighbors1 & neighbors2
      for n3 in filter(lambda x: x>n2, common):
         print n1
         print n2
         print n3

我确实检查了程序中的缩进似乎没有问题。我没有得到邻居名单。

1 个答案:

答案 0 :(得分:0)

如果您要对值进行任何操作,我建议产生一个3节点元组。

我必须更改数据,以便导入工作(我删除了w),并且支持在networkx中查找三角形节点,这有助于限制我们每次迭代的对象数量。

infile.txt

0_node1 0_node2 0
1_node1 1_node2 1
2_node1 2_node2 2
3_node1 3_node2 3
4_node1 4_node2 4
0_node1 1_node2 5
0_node2 1_node2 6
0_node2 1_node1 7

enter image description here

代码:

import networkx as nx
import itertools as it

def get_triangles(G):

    def found_rotation(x):
        for rotation in it.permutations(x):
            if rotation in triangles_duplicates:
                return 1
                return 0

    triangles = []
    triangles_duplicates=[]
    triangle_nodes = dict((x,nx.triangles(G,x))  for x in G.nodes() if nx.triangles(G,x) > 0)

    for vertex1  in triangle_nodes:
        vertex1_neighbors_that_are_triangles = set(G.neighbors(vertex1)).intersection( \
                                                                                       set(triangle_nodes) )
        for vertex2 in vertex1_neighbors_that_are_triangles:
            if triangle_nodes[vertex2] > 0:
                vertex2_neighbors_that_are_triangles_and_not_vertex1 = \
                                                                       set(G.neighbors(vertex2)).intersection(\
                                                                                                              G.neighbors(vertex1))-{vertex1}-{vertex2}
                for vertex3 in vertex2_neighbors_that_are_triangles_and_not_vertex1:
                    if triangle_nodes[vertex3]>0:
                        for z in G.neighbors(vertex3):
                            if (vertex1 == z) and  not found_rotation((vertex1,vertex2,vertex3)):
                                triangle_nodes[vertex1] -=1
                                triangle_nodes[vertex2] -=1
                                triangle_nodes[vertex3] -=1
                                triangles.append((vertex1,vertex2,vertex3))
                                triangles_duplicates.append((vertex1,vertex2,vertex3))
    return triangles

if __name__ == "__main__":
    #G = nx.karate_club_graph()
    G = nx.read_edgelist('this.txt', data=[("weight",int)])

对于这样的数据,答案是2个三角形 (或者你可以用karate_club_graph切换它并得到45)

如果你对此有所帮助,我有兴趣看到改进。