ahajib
ahajib

Reputation: 13500

Convert python-igraph graph to networkx

Recently I've been working with python-igraph package and all my code is based on graphs I create using igraph. Right now, I need to calculate some measures for my graph which apparently are implemented in networkx and not in igraph such as (katz_centrality_numpy, edge_betweenness_centrality, ...). I am wondering if there is a way to convert one graph to another between these two packages and to avoid reading from files again since my files are huge and have to repeat the same process alot.

By the way, when I pass the igraph graph to a networkx function I receive the following error:

TypeError: 'Graph' object is not iterable

Thanks :)

Upvotes: 7

Views: 7529

Answers (5)

user2383054
user2383054

Reputation: 365

Now you can directly translate from igraph to networkx using:

G = graph.to_networkx()

where "graph" is an igraph graph, for the sake of redundancy.

https://igraph.org/python/doc/api/igraph.Graph.html#to_networkx

Upvotes: 1

LHeng
LHeng

Reputation: 601

The top answer works nicely, but just in case one needs to preserve the order of the nodes (so that mNgraph.nodes is sorted), and one's igraph.Graph has no node names, consider using something like

mNgraph = networkx.Graph()
mNgraph.add_nodes_from(range(mIgraph.vcount()))
mNgraph.add_edges_from(mIgraph.get_edgelist())

Upvotes: 0

Ebrahim Byagowi
Ebrahim Byagowi

Reputation: 11218

As I try to store names of nodes/edges on both igraph or nx, this is my one-liner version which also transfers nodes names while transferring from igraph object, g, to nx, G, the result:

G = nx.from_edgelist([(names[x[0]], names[x[1]])
                      for names in [g.vs['name']] # simply a let
                      for x in g.get_edgelist()], nx.DiGraph())

Also if you need the reverse way, have a look at this answer.

Upvotes: 3

Ella Sharakanski
Ella Sharakanski

Reputation: 2773

You can initiate a networkx graph with edges:

Graph([(1,2), (3,4)])

See the documentation.

EDIT:

This is how to use it (Thank you nimafl for the code):

graph is the igraph graph and we create G which is a networkx graph.

import networkx
A = graph.get_edgelist()
G = networkx.DiGraph(A) # In case your graph is directed
G = networkx.Graph(A) # In case you graph is undirected

Upvotes: 6

ahajib
ahajib

Reputation: 13500

Ok so I figured it out myself. Here is what you should do. Assuming that your python.igraph object is called graph we create a networkx graph called G as following:

import networkx as netx

A = [edge.tuple for edge in graph.es]
# In case your graph is directed
G = netx.DiGraph(A)
# In case you graph is undirected
G = netx.Graph(A)

graph.es returns the graph edge list and then add all of them to A and using matrix A we create a graph in networkx.

Good luck with your codes :)

Upvotes: 1

Related Questions