create table edges ( fromnode int, tonode int, distance numeric );
insert into edges(fromnode, tonode, distance) values (1, 2, 1306), (1, 5, 2161), (1, 6, 2661), (2, 3, 919), (2, 4, 629), (3, 4, 435), (3, 5, 1225), (3, 7, 1983), (5, 6, 1483), (5, 7, 1258);
In [3]:
import psycopg2
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
conn = psycopg2.connect(database="postgres", user="postgres", password="***", host="127.0.0.1", port="5432")
In [5]:
query = """SELECT fromnode, tonode, distance from edges"""
df = pd.read_sql_query(query, conn)
df.shape
Out[5]:
In [11]:
# from dataframe to graph
# import as undirected graph
g=nx.from_pandas_dataframe(df, 'fromnode', 'tonode', 'distance')
In [12]:
# from graph to dataframe as a matrix
nx.to_pandas_dataframe(g, weight='distance')
Out[12]:
In [13]:
# print nodes and edges
print 'list nodes: ', g.nodes(), '\n'
print 'no. nodes:', len(g) #no. nodes
print 'no. edges:', g.number_of_edges(), '\n'
print 'list edges: ', g.edges(), '\n'
print 'list all edge attributes: ', dict(((a,b,),c['distance']) for a,b,c in g.edges(data=True))
In [14]:
# choose layoutl pos=position for nodes
pos = nx.fruchterman_reingold_layout(g)
# draw network
nx.draw(g, pos, with_labels = True, node_size=800, node_color='pink', edge_color='grey')
# label edges
edge_labels = dict([((u,v,),d['distance']) for u,v,d in g.edges(data=True)])
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
Out[14]:
In [37]:
s=2
t=7
print nx.shortest_path(g, source=s,target=t, weight='distance')
plt.figure(figsize=(5, 5))
# choose layout
pos = nx.fruchterman_reingold_layout(g)
# draw network
nx.draw(g, pos, with_labels = True, node_size=800, node_color='pink', edge_color='grey')
# nx.draw_networkx_edges(g, pos, edge_color='grey',width=0.1, alpha=0.5)
# label edges
edge_labels = dict([((u,v,),d['distance']) for u,v,d in g.edges(data=True)])
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
# plot shortest path
path = nx.shortest_path(g, source=s,target=t, weight='distance')
path_edges = zip(path,path[1:])
# nx.draw_networkx_nodes(g,pos,nodelist=path,node_color='black', node_size=1000)
nx.draw_networkx_edges(g,pos,edgelist=path_edges,edge_color='r',width=15)
Out[37]:
In [31]:
# shortest path
nx.shortest_path(graph, source=1, target=3, weight='distance')
Out[31]:
In [32]:
# shortest path
paths = nx.all_shortest_paths(graph, source=1, target=7, weight='distance')
for path in paths:
print path
In [33]:
# all simple paths without weight
path = nx.all_simple_paths(graph, source=1, target=7)
for i in path:
print i