Created
July 20, 2012 05:24
-
-
Save dangra/3148850 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example run: