Skip to content

Instantly share code, notes, and snippets.

@rkwitt
Last active December 15, 2015 18:49
Show Gist options
  • Save rkwitt/5307166 to your computer and use it in GitHub Desktop.
Save rkwitt/5307166 to your computer and use it in GitHub Desktop.
Kitware TechTip 04-03-2013 Part 1: Graph construction from a binary adjacency matrix and a vertex label file.
"""kw-techtip-04-03-2013-p1.py
Simple example of how to construct a graph from a {0,1} adjacency matrix and a
file with vertex labels.
Usage
-----
$ python kw-techtip-04-03-2013-p1.py <AdjacencyFile> <LabelFile>
Example
-------
Adjacency file (3 vertices):
0 1 0
1 0 0
0 1 0
Corresponding label file:
2
1
2
"""
import sys
import pickle
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Load adjacency information into numpy ndarray
adj_info = np.genfromtxt(sys.argv[1], skip_header=0)
# Build graph from adjacency matrix ...
G = nx.Graph(adj_info)
# Load label information
labels = np.genfromtxt(sys.argv[2], skip_header=0)
# Set vertex labels
for idx, l in enumerate(labels):
G.node[idx]['type'] = int(l)
# Iterate through nodes and show vertex labels
for n in G.nodes():
print "Node : %d [type=%d]" % (n, int(G.node[n]['type']))
# Iterate through edges ...
for e in G.edges():
print e
# Visualize with matplotlib
plt.title("mutag_001")
nx.draw(G,node_color=range(len(G)))
plt.savefig("/tmp/mutag_001.png")
#plt.show()
pickle.dump(G,open("/tmp/graph.txt","w"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment