Handling Graphs with NetworkX

Python offers the library NetworkX for manipulating graphs. You can learn more here:

http://networkx.readthedocs.io/en/networkx-1.11/

http://networkx.readthedocs.io/en/networkx-1.11/tutorial/index.html

In [1]:
import networkx as nx
%matplotlib inline
In [2]:
#Creating a graph
G = nx.Graph()

#Add nodes to the graph
G.add_node(1)
G.add_nodes_from([2,3])
G.add_node('Alice')
G.add_node('Bob')
print(G.nodes())
[1, 2, 3, 'Alice', 'Bob']
In [3]:
#add edges to the graph
G.add_edge(1,2)
G.add_edges_from([(1,3),('Alice','Bob')])
e = (1,'Alice')
G.add_edge(*e)

# adding an edge with a new node will create the node Charlie in the graph
G.add_edge('Alice','Charlie')
print(G.edges())
print(G.nodes())
[(1, 2), (1, 3), (1, 'Alice'), ('Alice', 'Bob'), ('Alice', 'Charlie')]
[1, 2, 3, 'Alice', 'Bob', 'Charlie']
In [6]:
#A graph is a dictionary with nodes as the keys
#Each node is a dictionary with the neighbors as the keys, and the edge properties as values
G[1]
#G.node[1]
Out[6]:
AtlasView({2: {}, 3: {}, 'Alice': {}})
In [14]:
#Creating a graph from edges
G2 = nx.Graph()
G2.add_edges_from([(1,2),(1,3),('Alice','Bob'),(1,'Alice')])
print(G2.nodes())
print(G2.edges())
[1, 2, 3, 'Alice', 'Bob']
[(1, 2), (1, 3), (1, 'Alice'), ('Alice', 'Bob')]
In [15]:
G2.remove_edge(1,3)
G2.remove_node(3)
G2.remove_node(1)
print(G2.nodes())
print(G2.edges())
[2, 'Alice', 'Bob']
[('Alice', 'Bob')]
In [16]:
#Read a graph from a list of edges
G3 = nx.read_edgelist('graph_edges.txt')
print(G3.nodes())
print(G3.edges())
['1', '2', '3', 'Alice', 'Bob', 'Charlie']
[('1', '2'), ('1', '3'), ('1', 'Alice'), ('2', '3'), ('Alice', 'Bob'), ('Bob', 'Charlie')]

You can also assign properties and values to the nodes and edges of the graph

In [17]:
G3.node['Alice']['gender'] = 'female'
G3.node['Bob']['gender'] = 'male'
G3.node['Charlie']['gender'] = 'male'
G3.node['1']['value'] = 1
G3.node['2']['value'] = -1
G3.node['3']['value'] = 0
for n in G3.nodes():
    print(G3.node[n]) 
    
#different from G3[n]
for n in G3.nodes():
    print(G3[n])
    
G3.node['Alice']['value'] = 1
G3.node['Bob']['value'] = -1
G3.node['Charlie']['value'] = 1
for n in G3.nodes():
    print(n+ ":" + str(G3.node[n]['value']))

for n in G3.nodes():
    print(n,G3.node[n])
{'value': 1}
{'value': -1}
{'value': 0}
{'gender': 'female'}
{'gender': 'male'}
{'gender': 'male'}
{'2': {}, '3': {}, 'Alice': {}}
{'1': {}, '3': {}}
{'1': {}, '2': {}}
{'Bob': {}, '1': {}}
{'Alice': {}, 'Charlie': {}}
{'Bob': {}}
1:1
2:-1
3:0
Alice:1
Bob:-1
Charlie:1
1 {'value': 1}
2 {'value': -1}
3 {'value': 0}
Alice {'gender': 'female', 'value': 1}
Bob {'gender': 'male', 'value': -1}
Charlie {'gender': 'male', 'value': 1}
In [26]:
G3['Alice']['Bob']['label'] = 'strong'
print(G3['Bob']['Alice'])
print(G3['Alice'])
print(G3['Bob'])
{'label': 'strong'}
{'Bob': {'label': 'strong'}, '1': {}}
{'Alice': {'label': 'strong'}, 'Charlie': {}}

A special attribute of a an edge is the "weight". When adding weighted edges, you enter triples consisting of the two edge endpoints and the weight of the edge. This weight is stored in an attribute "weight" by default.

In [27]:
G4 = nx.Graph()
G4.add_weighted_edges_from([(1,2,0.5),(2,3,0.1),(3,4,0.7)])
for (a,b) in G4.edges():
    print (G4[a][b])
for (a,b,w) in G4.edges(data =True): #data=True returns weight as well
    print (str(a)+" "+ str(b) + " " + str(w['weight']))
for n in G4:
    print(G4[n])
{'weight': 0.5}
{'weight': 0.1}
{'weight': 0.7}
1 2 0.5
2 3 0.1
3 4 0.7
{2: {'weight': 0.5}}
{1: {'weight': 0.5}, 3: {'weight': 0.1}}
{2: {'weight': 0.1}, 4: {'weight': 0.7}}
{3: {'weight': 0.7}}

Directed Graphs

In [29]:
DG=nx.DiGraph()
DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75), (1,4,0.1)])
print(DG.edges())
for n in DG:
    print(DG[n])
[(1, 2), (1, 4), (3, 1)]
{2: {'weight': 0.5}, 4: {'weight': 0.1}}
{}
{1: {'weight': 0.75}}
{}

Graph Operations

Some common graph operations and algorithms are implemented in networkx library.

http://networkx.readthedocs.io/en/networkx-1.11/reference/algorithms.html

Neighbors, degrees and adjancency matrix

In [30]:
print(G.neighbors(1)) # returns the neighbors of a node
print(G.degree(1)) # returns the degree of a node
print(G4.degree(3, weight='weight'))
print(G4.degree(3))
A = nx.adjacency_matrix(G)
print(A) 
#the adjacency matrix is stored as a sparse matrix
print(type(A))
<dict_keyiterator object at 0x000002252D11E868>
3
0.7999999999999999
2
  (0, 1)	1
  (0, 2)	1
  (0, 3)	1
  (1, 0)	1
  (2, 0)	1
  (3, 0)	1
  (3, 4)	1
  (3, 5)	1
  (4, 3)	1
  (5, 3)	1
<class 'scipy.sparse.csr.csr_matrix'>

Neighbors and degrees for directed or weighted graphs

In [33]:
print(list(DG.successors(1)))
print(list(DG.neighbors(1)))
print(list(DG.predecessors(1)))
print(DG.out_degree(1,weight='weight'))
print(DG.out_degree(1))
print(DG.in_degree(1))
[2, 4]
[2, 4]
[3]
0.6
2
1

Connected components

In [76]:
G3.add_edge('1','Alice')
G3.remove_edge('1','Alice') #you can also remove_node, or a list of nodes or edges (remove_nodes_from, remove_edges_from)
G3.add_edge('Alice','Charlie')
G3.add_edge('1','4')
print(nx.number_connected_components(G3))

C = nx.connected_components(G3)
for GC in nx.connected_component_subgraphs(G3):
    print(GC.nodes())
    print(GC.edges())
    print(len(GC))
for c in C:
    print(c)
#getting the largest connected component:
Gc = max(nx.connected_component_subgraphs(G3),key=len)
print('max')
print(Gc.nodes())
#CL = nx.max_clique(G3)
2
['1', '2', '3', '4']
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3')]
4
['Alice', 'Bob', 'Charlie']
[('Alice', 'Bob'), ('Alice', 'Charlie'), ('Bob', 'Charlie')]
3
{'4', '2', '1', '3'}
{'Bob', 'Charlie', 'Alice'}
[<networkx.classes.graph.Graph object at 0x000002252EC07940>, <networkx.classes.graph.Graph object at 0x000002252EC07550>]
max
['1', '2', '3', '4']
Out[76]:
<networkx.classes.graph.Graph at 0x2252ec072e8>

Shortest paths

In [79]:
G3.add_edge('1','Alice')
sp = nx.shortest_path(G3,'3','Bob')
print(sp)
print(len(sp)-1)
print(nx.shortest_path_length(G3,'3','Bob'))

SP1 = nx.single_source_shortest_path(G3,'1')
print(SP1)
#print(nx.single_source_shortest_path_length(G3,'1'))
SP = dict(nx.all_pairs_shortest_path(G3))
#print(SP)
print(SP['1']['Bob'])
['3', '1', 'Alice', 'Bob']
3
3
{'1': ['1'], '2': ['1', '2'], '3': ['1', '3'], '4': ['1', '4'], 'Alice': ['1', 'Alice'], 'Bob': ['1', 'Alice', 'Bob'], 'Charlie': ['1', 'Alice', 'Charlie']}
['1', 'Alice', 'Bob']

Link Analysis

In [39]:
DG2 = nx.DiGraph()
DG2.add_edges_from([(1,2),(1,3),(3,2),(2,5),(4,1),(4,2),(4,3),(5,1),(5,4)])
pr = nx.pagerank(DG2)
print(pr)
[h,a] = nx.hits(DG2)
print(h)
print(a)
print(a[2])

pr = nx.pagerank(G3)
print(pr)
{1: 0.18064505060873787, 2: 0.2713164308772404, 3: 0.14665711544131715, 5: 0.26061906832422166, 4: 0.14076233474848301}
{1: 0.3028419086392418, 2: 1.3109311069706554e-15, 3: 0.1674519922094525, 5: 0.1254412274444104, 4: 0.40426487170689396}
{1: 0.23681288036482923, 2: 0.3909843234563998, 3: 0.31612245503718484, 5: 3.06089826220615e-15, 4: 0.05608034114158294}
0.3909843234563998
{'1': 0.20802924444783152, '2': 0.1459853777760842, '3': 0.1459853777760842, 'Alice': 0.20802924444783155, 'Bob': 0.1459853777760842, 'Charlie': 0.1459853777760842}

Betweeness

In [40]:
BC = nx.edge_betweenness_centrality(G3)
print(BC)
{('1', '2'): 0.26666666666666666, ('1', '3'): 0.26666666666666666, ('1', 'Alice'): 0.6, ('2', '3'): 0.06666666666666667, ('Alice', 'Bob'): 0.26666666666666666, ('Alice', 'Charlie'): 0.26666666666666666, ('Bob', 'Charlie'): 0.06666666666666667}
In [41]:
nx.draw_networkx(G3)
In [42]:
nx.draw_circular(G3)
In [60]:
nx.draw_spectral(G3)
In [44]:
nx.draw_spring(G3)
In [45]:
nx.draw_spring(DG2)

An example

In [58]:
karate=nx.read_gml("karate.gml",label='id')
nx.draw_networkx(karate)
In [59]:
pr = nx.pagerank(karate)
nx.draw_networkx(karate,node_size=[10000*v for v in pr.values()])