-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgraph_parse.py
executable file
·44 lines (38 loc) · 1.34 KB
/
graph_parse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python
import random, sys
from collections import defaultdict as ddict
import graph_gen, visualize
def parse(text):
nodes = set()
edge_counts = ddict(int) # key: (src,dst), val: count
for line in text.split('\n'):
if line.strip() == '':
continue
ballot = [part.split('=') for part in line.split('>')]
for i, group1 in enumerate(ballot):
for group2 in ballot[i+1:]:
for A in group1:
nodes.add(A)
for B in group2:
edge_counts[(A,B)] += 1 # A beats B in this ballot
nodes = list(nodes)
edges = []
for i,A in enumerate(nodes):
for B in nodes:
margin = edge_counts[(A,B)] - edge_counts[(B,A)]
if margin > 0:
edges.append({graph_gen.SOURCE: A, graph_gen.TARGET: B, 'label': str(margin)})
elif margin < 0:
edges.append({graph_gen.SOURCE: B, graph_gen.TARGET: A, 'label': str(-margin)})
return {'nodes': nodes, 'edges': edges}
def main():
if len(sys.argv) != 3:
print 'Usage: graph_parse.py <path> <out-dir>'
return
path,outdir = sys.argv[1:]
with open(path) as f:
text = f.read()
graph = parse(text)
visualize.generate_alchemy_graph(graph, outdir)
if __name__ == '__main__':
main()