inducer / pytools

http://pypi.python.org/pypi/pytools
Other
68 stars 25 forks source link

[Feature-request] Topological sort with keying function that exposes internal state #143

Open kaushikcfd opened 2 years ago

kaushikcfd commented 2 years ago

Consider the DAG below:

from pytools.graph import compute_topological_order

dag = {"A": {"C"},
       "B": {"E"},
       "C": {"D"},
       "D": set(),
       "E": set(),
       }

colors = {"A": "red",
          "B": "red",
          "C": "blue",
          "D": "red",
          "E": "blue"
          }

sorted_nodes = compute_topological_order(dag, key=lambda x: x)
print(sorted_nodes)                            # ['A', 'B', 'C', 'D', 'E']
print([colors[node] for node in sorted_nodes]) # ['red', 'red', 'blue', 'red', 'blue']

My application needs a valid topological sort that minimizes the jumps from 'red'<->'blue' nodes in the final schedule. And so for this problem, the topological sort order I'm after would be ['A', 'B', 'C', 'E', 'D']. I don't think that's possible with the current interface of compute_topological_order.

inducer commented 2 years ago

Is some greedy thing enough, or do you need an actual minimum?

kaushikcfd commented 2 years ago

A greedy thing seems enough.