计算图中的多个边(python)

时间:2017-03-27 22:38:37

标签: python-2.7 graph networkx

我正在使用幂律生成大小为N的网络 使用所谓的configuration_model算法进行度分布。结果图允许多个边,我必须计算它们,但我无法弄清楚如何。这是一个可能的解决方案:

import networkx as nx
import numpy as np
from networkx.utils import (powerlaw_sequence, create_degree_sequence)

deg_sequence = create_degree_sequence(num, powerlaw_sequence, exponent=2.2)
graph=nx.configuration_model(deg_sequence)

num_par = sum(len(graph[node][neigh]) for node in graph for neigh in graph.neighbors_iter(node)) // 2
print ('Graph has %d multi-links' %num_par)

self_loops=len(graph.selfloop_edges())
print ('Graph has %d self-loops' %self_loops)

edges=len(graph.edges())
print edges

我在互联网上的某个地方借了第六行代码,但坦率地说我不太明白它是如何工作的。特别是我无法理解它计算长度的是什么(graph [node] [neigh])。对我而言,它似乎也不是一个列表,但我确信这不是我的想法。 顺便说一句,作为这个代码的结果,我获得了很高的多边缘百分比,超过链接总数的98%,这对我来说似乎不太好。 这种计算平行边的方法是否正确?如果是这样,你能解释一下它是如何工作的吗?你知道其他任何做法吗?

1 个答案:

答案 0 :(得分:1)

如果在for循环而不是list表达式中写出第6行,则会得到以下结果:

num_par = 0
for node in graph:
    for neigh in graph.neighbors(node):
        num_par += len(graph[node][neigh]) / 2.

我不确定那条线在计算什么;我确信它没有正确计算多边数。

如果您只是将图形绘制为数组(num = 100),您可以立即看到几乎没有多边:

arr = nx.to_numpy_matrix(graph)
plt.imshow(arr, interpolation='nearest', cmap='gray'); plt.show()

enter image description here

使用

可以轻松计算多边数
num_multiedges = np.sum(arr>=2) / 2 # divide by two as graph is undirected