Skip to content

Instantly share code, notes, and snippets.

@dangra
Created July 20, 2012 05:24
Show Gist options
  • Save dangra/3148850 to your computer and use it in GitHub Desktop.
Save dangra/3148850 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# GistID: 3148850
import json
import fileinput
from igraph import Graph
from itertools import permutations
from optparse import OptionParser
from ndd.graphs import PGraph, partition_graph
def _partition(n, edges, weights):
edgemap = dict(zip(edges, weights))
pg = PGraph()
pg.nodes = range(n)
pg.edges = [(b1, b2, w) for (b1, b2), w in edgemap.iteritems()]
partitions = partition_graph(pg)
pedges = set(e for p in partitions for e in permutations(p, 2) if e in set(edges))
pig = Graph(n)
pig.add_edges(edges)
pig.es['weight'] = weights
pig.es['color'] = ['black' if e in pedges else 'white' for e in edges]
return pig
def readjlist(fo):
row = (json.loads(line) for line in fo)
for _, nodes, scorededges in row:
nodemap = dict((n, x) for x, n in enumerate(nodes))
edges = []
weights = []
for n1, n2, score in scorededges:
edges.append((nodemap[n1], nodemap[n2]))
weights.append(score)
cid = min(nodes)
n = len(nodes)
ig = Graph(n)
ig.add_edges(edges)
ig.es['weight'] = weights
ig.es['label'] = ['%s-%s' % tuple(e) for e in edges]
# partitioned graph
pig = _partition(n, edges, weights)
yield cid, ig, pig
def main():
op = OptionParser()
op.add_option('--layout', default='lgl')
opts, args = op.parse_args()
fo = fileinput.input(args)
for cid, ig, pig in readjlist(fo):
print '\n#### Cluster'
print ig.summary()
print '\n#### Partitioned'
print pig.summary()
ig.save(cid + '.svg', layout=opts.layout, format='svg',
width=800, height=600, font_size=7)
pig.save(cid + '-parted.svg', layout=opts.layout, format='svg',
width=800, height=600, font_size=7)
if __name__ == '__main__':
main()
@dangra
Copy link
Author

dangra commented Jul 20, 2012

example run:

$ head -n1 pcsample.jl |python clusterplot.py 

#### Cluster
10 nodes, 17 edges, undirected

Number of components: 1
Diameter: 4
Density: 0.3778
Average path length: 2.0889

#### Partitioned
10 nodes, 12 edges, undirected

Number of components: 3
Diameter: 1
Density: 0.2667
Average path length: 1.0000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment