Interface between networkx and igraph

Moses Xu picture Moses Xu · Apr 23, 2014 · Viewed 9.2k times · Source

I've been working with networkx for quite some time now and it's been serving my purposes quite well with minimal tweaks until recently when I started looking into community detection. In comparison, the igraph Python package seems to have a much wider implementations of community detection methods (even compared to networkx with Thomas Aynaud's community package added on). I'm just wondering if there's any existing, tested API that would allow easy translation of a networkx graph into the igraph structure, so I can avail myself of the power igraph provides in this area?

Your kind answers are highly appreciated.

Answer

Ulrich Stern picture Ulrich Stern · Aug 22, 2016

Here two ways to convert a NetworkX graph to an igraph:

import networkx as nx, igraph as ig

# create sample NetworkX graph
g = nx.planted_partition_graph(5, 5, 0.9, 0.1, seed=3)

# convert via edge list
g1 = ig.Graph(len(g), list(zip(*list(zip(*nx.to_edgelist(g)))[:2])))
  # nx.to_edgelist(g) returns [(0, 1, {}), (0, 2, {}), ...], which is turned
  #  into [(0, 1), (0, 2), ...] for igraph

# convert via adjacency matrix
g2 = ig.Graph.Adjacency((nx.to_numpy_matrix(g) > 0).tolist())

assert g1.get_adjacency() == g2.get_adjacency()

Using the edge list was somewhat faster for the following 2500-node graph on my machine: (Note that the code below is Python 2 only; I updated the code above to be Python 2/3 compatible.)

In [5]: g = nx.planted_partition_graph(50, 50, 0.9, 0.1, seed=3)

In [6]: %timeit ig.Graph(len(g), zip(*zip(*nx.to_edgelist(g))[:2]))
1 loops, best of 3: 264 ms per loop

In [7]: %timeit ig.Graph.Adjacency((nx.to_numpy_matrix(g) > 0).tolist())
1 loops, best of 3: 496 ms per loop

Using the edge list was also somewhat faster for g = nx.complete_graph(2500).