Skip to content

Commit

Permalink
Fix topological sorting to always start with root node (#688)
Browse files Browse the repository at this point in the history
* Fix topological sorting to always start with root node

* Add test
  • Loading branch information
talmo authored Mar 25, 2022
1 parent e32e7e3 commit 19f3bfe
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
14 changes: 7 additions & 7 deletions sleap/nn/paf_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,13 +1310,13 @@ def toposort_edges(edge_types: List[EdgeType]) -> Tuple[int]:
See also: assign_connections_to_instances
"""
dg = nx.DiGraph(
[(edge_type.src_node_ind, edge_type.dst_node_ind) for edge_type in edge_types]
)
lg = nx.line_graph(dg)
sorted_dg = list(nx.topological_sort(lg))
lg = list(lg)
sorted_edge_inds = tuple([lg.index(edge) for edge in sorted_dg])
edges = [
(edge_type.src_node_ind, edge_type.dst_node_ind) for edge_type in edge_types
]
dg = nx.DiGraph(edges)
root_ind = next(nx.topological_sort(dg))
sorted_edges = nx.bfs_edges(dg, root_ind)
sorted_edge_inds = tuple([edges.index(edge) for edge in sorted_edges])
return sorted_edge_inds


Expand Down
16 changes: 16 additions & 0 deletions tests/nn/test_paf_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,22 @@ def test_toposort_edges():
sorted_edge_inds = toposort_edges(edge_types)
assert sorted_edge_inds == (12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

edge_inds = [
(1, 4),
(1, 5),
(6, 8),
(6, 7),
(6, 9),
(9, 10),
(1, 0),
(1, 3),
(1, 2),
(6, 1),
]
edge_types = [EdgeType(src_node, dst_node) for src_node, dst_node in edge_inds]
sorted_edge_inds = toposort_edges(edge_types)
assert sorted_edge_inds == (2, 3, 4, 9, 5, 0, 1, 6, 7, 8)


def test_assign_connections_to_instances():
connections = {
Expand Down

0 comments on commit 19f3bfe

Please sign in to comment.