Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions refcycle/i_directed_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,46 @@ def ancestors(self, start, generations=None):
)
return self.full_subgraph(visited)

def shortest_path(self, start, end):
"""
Find a shortest path from start to end.

Returns the subgraph consisting of the vertices in that path
and the edges between them.

Raises ValueError if no path from start to end exists.
"""
# Vertices whose children are yet to be explored.
to_visit = deque([start])

# Mapping from each child to the parent that it was first found via.
# We map the start vertex to a dummy object.
dummy = object()
explored = self.vertex_dict()
explored[start] = dummy

# Breadth-first search, rooted at ``start``.
while to_visit:
if end in explored:
break

parent = to_visit.popleft()
for child in self.children(parent):
if child not in explored:
explored[child] = parent
to_visit.append(child)
else:
raise ValueError("No path found.")

# Backtrack to construct vertices of path.
vertex = end
path = []
while vertex is not dummy:
path.append(vertex)
vertex = explored[vertex]

return self.full_subgraph(path)

def _component_graph(self):
"""
Compute the graph of strongly connected components.
Expand Down
46 changes: 46 additions & 0 deletions refcycle/test/test_object_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,52 @@ def test_ancestors(self):
self.assertCountEqual(graph.ancestors(c), [c, a])
self.assertCountEqual(graph.ancestors(d), [d, b, c, a])

def test_shortest_path(self):
# Looking for paths from a to f, we have:
# a -> b -> e -> f
# a -> c -> f (shortest)
a = []
b = []
c = []
d = []
e = []
f = []
a.append(b)
a.append(c)
a.append(d)
b.append(e)
e.append(f)
c.append(f)
graph = ObjectGraph([a, b, c, d, e, f])
path = graph.shortest_path(a, f)
self.assertIsInstance(path, IDirectedGraph)
self.assertEqual(len(path.vertices), 3)

self.assertIn(a, path.vertices)
self.assertIn(c, path.vertices)
self.assertIn(f, path.vertices)

def test_shortest_path_no_path(self):
a = []
b = []
c = []
a.append(b)
c.append(b)
graph = ObjectGraph([a, b, c])
with self.assertRaises(ValueError):
graph.shortest_path(a, c)

def test_shortest_path_start_equals_end(self):
a = []
b = []
a.append(b)
b.append(a)
a.append(a)
graph = ObjectGraph([a])
path = graph.shortest_path(a, a)
self.assertIsInstance(path, IDirectedGraph)
self.assertEqual(len(path.vertices), 1)

def test_to_dot(self):
a = []
b = []
Expand Down