Skip to content

Commit

Permalink
Detecting loops in Sankeys (#271)
Browse files Browse the repository at this point in the history
* Detecting loops in Sankeys

* Fixing the algo
  • Loading branch information
mistercrunch committed Apr 9, 2016
1 parent a3dcb0f commit 866e00d
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion caravel/viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,32 @@ def query_obj(self):
def get_data(self):
df = self.get_df()
df.columns = ['source', 'target', 'value']
return df.to_dict(orient='records')
recs = df.to_dict(orient='records')

hierarchy = defaultdict(set)
for row in recs:
hierarchy[row['source']].add(row['target'])

def find_cycle(g):
"""Whether there's a cycle in a directed graph"""
path = set()
def visit(vertex):
path.add(vertex)
for neighbour in g.get(vertex, ()):
if neighbour in path or visit(neighbour):
return (vertex, neighbour)
path.remove(vertex)
for v in g:
cycle = visit(v)
if cycle:
return cycle

cycle = find_cycle(hierarchy)
if cycle:
raise Exception(
"There's a loop in your Sankey, please provide a tree. "
"Here's a faulty link: {}".format(cycle))
return recs


class DirectedForceViz(BaseViz):
Expand Down

0 comments on commit 866e00d

Please sign in to comment.