3

I am generating a network of size N with a power-law degree distribution using the so-called configuration_model algorithm. The resulting graph allows multiple edges, I have to count them but I cannot figure out how. Here is a possible solution:

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

I borrowed the sixth line of code somewhere on the internet but frankly I can't quite understand how it works. In particular I can't understand what is (graph[node][neigh]) of which it calculates the length. To me, it does not seem like a list either, but I am sure it's me not getting the idea here. Btw as a result of this code I get a very high percentage of multiple edges, more than 98% of the total number of links, and it does not seem very good to me. Is this way of calculating parallel edges correct? If so, would you explain me how it works? Do you know any other way of doing it?

1
  • What value does num have? Commented Mar 28, 2017 at 10:16

1 Answer 1

3

If you write out line 6 in for-loops instead of list expressions, you arrive at the following:

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

I am not sure what that line is counting; I am sure that it is not calculating the number of multi-edges correctly.

If you just plot the graph as an array (num = 100), you can immediately see that there are very few multi-edges:

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

enter image description here

The number of multi-edges is easily calculated with

num_multiedges = np.sum(arr>=2) / 2 # divide by two as graph is undirected 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Paul, I am still familiarizing with numpy, this is exactly what I needed! BTW I re-wrote that list comprehension like you did and I too could not figure out what it was doing, that's why I asked. The author claimed it was a multi edge counter, I wasn't sure it was either me not understanding or the code that was wrong. Again, thanks a lot.
Ahh, beaten me in couple of hours. Nice answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.