计算图中的多条边 (python)
Counting multiple edges in graph (python)
我正在生成一个大小为 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%,这对我来说似乎不太好。
这种计算平行边的方法是否正确?如果是这样,你能解释一下它是如何工作的吗?您知道其他方法吗?
如果您在 for 循环而不是列表表达式中写出第 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()
多边的数量很容易计算
num_multiedges = np.sum(arr>=2) / 2 # divide by two as graph is undirected
我正在生成一个大小为 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%,这对我来说似乎不太好。 这种计算平行边的方法是否正确?如果是这样,你能解释一下它是如何工作的吗?您知道其他方法吗?
如果您在 for 循环而不是列表表达式中写出第 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()
多边的数量很容易计算
num_multiedges = np.sum(arr>=2) / 2 # divide by two as graph is undirected