You are on page 1of 3

Tutorial Python+NetworkX

Python
To use Python interactively use the IPython shell. The file in Portable Python is ipython-portable.exe.
To print out variables, one can use the print command or simply type the var:
In [1]: a = 10
In [2]: print a
10
In [3]: a
Out[3]: 10
In [4]:

NetworkX
This section explains how to use the NetworkX library to create and manipulate networks.
The documentation for the netio.py and sndlibio.py are in the comments inside the files. To use
these libraries, put them in the same folder where data files are and change ipython to that folder with the
cd command.

Creating graphs
To import the NetworkX library, use the command:
from networkx import *
Then, to create a network, do:
G = Graph()
then, to add edges, do:
G.add_edge(1,2) # add edge
G.add_edge(1,2,peso=10) # add edge with weight
To create a network based on a SNDlib file, put the sndlibio.py file in the same folder and do an
import. It may be necessary to change to the correct folder first:
cd <folder>
ex:
cd /Project/graph/
then, import SNDlib:
import sndlibio

and load the network from the SNDlib file. Example for germany50.txt:
H = Graph()
sndlibio.readSNDlib(H,'germany50.txt')
To create a network based on a file with a list of edges in the following format:
node1
node1 node2
node1 node2 weight

# for single node


# for edge
# for weighted edge

put the netio.py file in the same folder and do an import (it may be necessary to change to the correct
folder first), import netio.py and use readSimpleNet() function:
import netio
I = Graph()
netio.readSimpleNet(I,'sample_network.txt')

Graph analysis
To check all properties of a specific node:
H.node['Berlin']
and for a specific property:
H.node['Berlin']['latitude']
To check all properties of a specific edge:
H['Berlin']['Magdeburg']
and for a specific property:
H['Berlin']['Magdeburg']['demand']
To calculate the shortest path of all nodes in the network, do:
shortest_path(G)
To calculate the shortest path from a specific node:
shortest_path(G,1)
shortest_path(H,'Berlin',weight='demand')
To calculate the shortest path from a specific node to another:
shortest_path(G,1,2)
shortest_path(H,'Berlin','Kassel',weight='demand')
For centrality calculation, use the following:

degree_centrality(G)
degree_centrality(H)
closeness_centrality(G)
closeness_centrality(H,distance='demand')
betweenness_centrality(G)
betweenness_centrality(H,weight='demand')

You might also like