Skip to content

Commit 3dbd747

Browse files
committed
test compute_topological_order_with_dynamic_key
1 parent a4284cf commit 3dbd747

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

test/test_pytools.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,50 @@ class Eq3(Tag):
703703
assert hash(eq1) != hash(eq3)
704704

705705

706+
def test_compute_topological_order_with_dynamic_key():
707+
from pytools.graph import compute_topological_order_with_dynamic_key
708+
709+
dag = {"A": {"C"},
710+
"B": {"E"},
711+
"C": {"D"},
712+
"D": set(),
713+
"E": set(),
714+
}
715+
716+
colors = {"A": "red",
717+
"B": "red",
718+
"C": "blue",
719+
"D": "red",
720+
"E": "blue"}
721+
722+
# {{{ set a dynamic key to greedily schedule continuous chunks of blue/red nodes
723+
724+
def trigger_key_update(state):
725+
if len(state.scheduled_nodes) == 1:
726+
# initially we preferred blue.
727+
return colors[state.scheduled_nodes[0]] == "red"
728+
else:
729+
return (colors[state.scheduled_nodes[-1]]
730+
!= colors[state.scheduled_nodes[-2]])
731+
732+
def get_key(state):
733+
if len(state.scheduled_nodes) == 0:
734+
# initial state => prefer blue.
735+
return lambda x: (colors[x] != "blue",
736+
x)
737+
else:
738+
return lambda x: (colors[x] != colors[state.scheduled_nodes[-1]],
739+
x)
740+
741+
# }}}
742+
743+
sorted_nodes = compute_topological_order_with_dynamic_key(
744+
dag,
745+
trigger_key_update, get_key)
746+
747+
assert sorted_nodes == ["A", "B", "C", "E", "D"]
748+
749+
706750
if __name__ == "__main__":
707751
if len(sys.argv) > 1:
708752
exec(sys.argv[1])

0 commit comments

Comments
 (0)