blob: 959cea3c6e3876ef8f192ae52a3f3b866f475db2 [file] [log] [blame]
Sapan Bhatia24836f12013-08-27 10:16:05 -04001#!/usr/bin/python
2
3import time
4import traceback
5import commands
6import threading
7import json
8
9from datetime import datetime
10from collections import defaultdict
11
Sapan Bhatia467b7ce2013-10-02 09:25:46 -040012def toposort(g, steps=None):
13 if (not steps):
14 keys = set(g.keys())
15 values = set({})
16 for v in g.values():
17 values=values | set(v)
18
19 steps=list(keys|values)
20
Sapan Bhatia24836f12013-08-27 10:16:05 -040021 reverse = {}
22
23 for k,v in g.items():
24 for rk in v:
25 try:
26 reverse[rk].append(k)
27 except:
28 reverse[rk]=k
29
30 sources = []
31 for k,v in g.items():
32 if not reverse.has_key(k):
33 sources.append(k)
34
Sapan Bhatia24836f12013-08-27 10:16:05 -040035 for k,v in reverse.iteritems():
36 if (not v):
37 sources.append(k)
38
Sapan Bhatiaa2227d12013-10-02 09:48:42 -040039 order = []
Sapan Bhatia24836f12013-08-27 10:16:05 -040040 marked = []
Sapan Bhatiaa2227d12013-10-02 09:48:42 -040041
Sapan Bhatia24836f12013-08-27 10:16:05 -040042 while sources:
Sapan Bhatia467b7ce2013-10-02 09:25:46 -040043 n = sources.pop(0)
Sapan Bhatia24836f12013-08-27 10:16:05 -040044 try:
45 for m in g[n]:
46 if m not in marked:
47 sources.append(m)
48 marked.append(m)
49 except KeyError:
50 pass
51 if (n in steps):
Sapan Bhatiaa2227d12013-10-02 09:48:42 -040052 order.append(n)
53
54 order.reverse()
Sapan Bhatia24836f12013-08-27 10:16:05 -040055
56 return order
57
Sapan Bhatia467b7ce2013-10-02 09:25:46 -040058graph_file=open('model-deps').read()
59g = json.loads(graph_file)
60print toposort(g)
61
62#print toposort({'a':'b','b':'c','c':'d','d':'c'},['d','c','b','a'])