~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tsort.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
16
17
 
17
18
"""Topological sorting routines."""
18
19
 
19
 
from __future__ import absolute_import
20
 
 
21
 
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    graph as _mod_graph,
25
 
    revision as _mod_revision,
26
 
    )
 
20
 
 
21
from bzrlib import errors
 
22
import bzrlib.revision as _mod_revision
27
23
 
28
24
 
29
25
__all__ = ["topo_sort", "TopoSorter", "merge_sort", "MergeSorter"]
34
30
 
35
31
    graph -- sequence of pairs of node->parents_list.
36
32
 
37
 
    The result is a list of node names, such that all parents come before their
38
 
    children.
 
33
    The result is a list of node names, such that all parents come before
 
34
    their children.
39
35
 
40
36
    node identifiers can be any hashable object, and are typically strings.
41
 
 
42
 
    This function has the same purpose as the TopoSorter class, but uses a
43
 
    different algorithm to sort the graph. That means that while both return a
44
 
    list with parents before their child nodes, the exact ordering can be
45
 
    different.
46
 
 
47
 
    topo_sort is faster when the whole list is needed, while when iterating
48
 
    over a part of the list, TopoSorter.iter_topo_order should be used.
49
37
    """
50
 
    kg = _mod_graph.KnownGraph(dict(graph))
51
 
    return kg.topo_sort()
 
38
    return TopoSorter(graph).sorted()
52
39
 
53
40
 
54
41
class TopoSorter(object):
55
42
 
56
43
    def __init__(self, graph):
57
44
        """Topological sorting of a graph.
58
 
 
 
45
    
59
46
        :param graph: sequence of pairs of node_name->parent_names_list.
60
47
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
61
48
                      For this input the output from the sort or
62
49
                      iter_topo_order routines will be:
63
50
                      'A', 'B', 'C'
64
 
 
 
51
        
65
52
        node identifiers can be any hashable object, and are typically strings.
66
53
 
67
54
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
70
57
        The graph is sorted lazily: until you iterate or sort the input is
71
58
        not processed other than to create an internal representation.
72
59
 
73
 
        iteration or sorting may raise GraphCycleError if a cycle is present
 
60
        iteration or sorting may raise GraphCycleError if a cycle is present 
74
61
        in the graph.
75
62
        """
76
 
        # store a dict of the graph.
 
63
        # a dict of the graph.
77
64
        self._graph = dict(graph)
 
65
        self._visitable = set(self._graph)
 
66
        ### if debugging:
 
67
        # self._original_graph = dict(graph)
 
68
        
 
69
        # this is a stack storing the depth first search into the graph.
 
70
        self._node_name_stack = []
 
71
        # at each level of 'recursion' we have to check each parent. This
 
72
        # stack stores the parents we have not yet checked for the node at the 
 
73
        # matching depth in _node_name_stack
 
74
        self._pending_parents_stack = []
 
75
        # this is a set of the completed nodes for fast checking whether a
 
76
        # parent in a node we are processing on the stack has already been
 
77
        # emitted and thus can be skipped.
 
78
        self._completed_node_names = set()
78
79
 
79
80
    def sorted(self):
80
81
        """Sort the graph and return as a list.
81
 
 
 
82
        
82
83
        After calling this the sorter is empty and you must create a new one.
83
84
        """
84
85
        return list(self.iter_topo_order())
95
96
 
96
97
    def iter_topo_order(self):
97
98
        """Yield the nodes of the graph in a topological order.
98
 
 
 
99
        
99
100
        After finishing iteration the sorter is empty and you cannot continue
100
101
        iteration.
101
102
        """
102
 
        graph = self._graph
103
 
        visitable = set(graph)
104
 
 
105
 
        # this is a stack storing the depth first search into the graph.
106
 
        pending_node_stack = []
107
 
        # at each level of 'recursion' we have to check each parent. This
108
 
        # stack stores the parents we have not yet checked for the node at the
109
 
        # matching depth in pending_node_stack
110
 
        pending_parents_stack = []
111
 
 
112
 
        # this is a set of the completed nodes for fast checking whether a
113
 
        # parent in a node we are processing on the stack has already been
114
 
        # emitted and thus can be skipped.
115
 
        completed_node_names = set()
116
 
 
117
 
        while graph:
 
103
        while self._graph:
118
104
            # now pick a random node in the source graph, and transfer it to the
119
 
            # top of the depth first search stack of pending nodes.
120
 
            node_name, parents = graph.popitem()
121
 
            pending_node_stack.append(node_name)
122
 
            pending_parents_stack.append(list(parents))
123
 
 
124
 
            # loop until pending_node_stack is empty
125
 
            while pending_node_stack:
126
 
                parents_to_visit = pending_parents_stack[-1]
127
 
                # if there are no parents left, the revision is done
 
105
            # top of the depth first search stack.
 
106
            node_name, parents = self._graph.popitem()
 
107
            self._push_node(node_name, parents)
 
108
            while self._node_name_stack:
 
109
                # loop until this call completes.
 
110
                parents_to_visit = self._pending_parents_stack[-1]
 
111
                # if all parents are done, the revision is done
128
112
                if not parents_to_visit:
129
113
                    # append the revision to the topo sorted list
130
 
                    # all the nodes parents have been added to the output,
131
 
                    # now we can add it to the output.
132
 
                    popped_node = pending_node_stack.pop()
133
 
                    pending_parents_stack.pop()
134
 
                    completed_node_names.add(popped_node)
135
 
                    yield popped_node
 
114
                    # all the nodes parents have been added to the output, now
 
115
                    # we can add it to the output.
 
116
                    yield self._pop_node()
136
117
                else:
137
 
                    # recurse depth first into a single parent
138
 
                    next_node_name = parents_to_visit.pop()
139
 
 
140
 
                    if next_node_name in completed_node_names:
141
 
                        # parent was already completed by a child, skip it.
142
 
                        continue
143
 
                    if next_node_name not in visitable:
144
 
                        # parent is not a node in the original graph, skip it.
145
 
                        continue
146
 
 
147
 
                    # transfer it along with its parents from the source graph
148
 
                    # into the top of the current depth first search stack.
149
 
                    try:
150
 
                        parents = graph.pop(next_node_name)
151
 
                    except KeyError:
152
 
                        # if the next node is not in the source graph it has
153
 
                        # already been popped from it and placed into the
154
 
                        # current search stack (but not completed or we would
155
 
                        # have hit the continue 6 lines up).  this indicates a
156
 
                        # cycle.
157
 
                        raise errors.GraphCycleError(pending_node_stack)
158
 
                    pending_node_stack.append(next_node_name)
159
 
                    pending_parents_stack.append(list(parents))
 
118
                    while self._pending_parents_stack[-1]:
 
119
                        # recurse depth first into a single parent 
 
120
                        next_node_name = self._pending_parents_stack[-1].pop()
 
121
                        if next_node_name in self._completed_node_names:
 
122
                            # this parent was completed by a child on the
 
123
                            # call stack. skip it.
 
124
                            continue
 
125
                        if next_node_name not in self._visitable:
 
126
                            continue
 
127
                        # otherwise transfer it from the source graph into the
 
128
                        # top of the current depth first search stack.
 
129
                        try:
 
130
                            parents = self._graph.pop(next_node_name)
 
131
                        except KeyError:
 
132
                            # if the next node is not in the source graph it has
 
133
                            # already been popped from it and placed into the
 
134
                            # current search stack (but not completed or we would
 
135
                            # have hit the continue 4 lines up.
 
136
                            # this indicates a cycle.
 
137
                            raise errors.GraphCycleError(self._node_name_stack)
 
138
                        self._push_node(next_node_name, parents)
 
139
                        # and do not continue processing parents until this 'call' 
 
140
                        # has recursed.
 
141
                        break
 
142
 
 
143
    def _push_node(self, node_name, parents):
 
144
        """Add node_name to the pending node stack.
 
145
        
 
146
        Names in this stack will get emitted into the output as they are popped
 
147
        off the stack.
 
148
        """
 
149
        self._node_name_stack.append(node_name)
 
150
        self._pending_parents_stack.append(list(parents))
 
151
 
 
152
    def _pop_node(self):
 
153
        """Pop the top node off the stack 
 
154
 
 
155
        The node is appended to the sorted output.
 
156
        """
 
157
        # we are returning from the flattened call frame:
 
158
        # pop off the local variables
 
159
        node_name = self._node_name_stack.pop()
 
160
        self._pending_parents_stack.pop()
 
161
 
 
162
        self._completed_node_names.add(node_name)
 
163
        return node_name
160
164
 
161
165
 
162
166
def merge_sort(graph, branch_tip, mainline_revisions=None, generate_revno=False):
163
167
    """Topological sort a graph which groups merges.
164
168
 
165
169
    :param graph: sequence of pairs of node->parents_list.
166
 
    :param branch_tip: the tip of the branch to graph. Revisions not
 
170
    :param branch_tip: the tip of the branch to graph. Revisions not 
167
171
                       reachable from branch_tip are not included in the
168
172
                       output.
169
173
    :param mainline_revisions: If not None this forces a mainline to be
178
182
        revision number sequences in the output. See the output description of
179
183
        the MergeSorter docstring for details.
180
184
    :result: See the MergeSorter docstring for details.
181
 
 
182
 
    Node identifiers can be any hashable object, and are typically strings.
 
185
    node identifiers can be any hashable object, and are typically strings.
183
186
    """
184
187
    return MergeSorter(graph, branch_tip, mainline_revisions,
185
188
        generate_revno).sorted()
206
209
    def __init__(self, graph, branch_tip, mainline_revisions=None,
207
210
        generate_revno=False):
208
211
        """Merge-aware topological sorting of a graph.
209
 
 
 
212
    
210
213
        :param graph: sequence of pairs of node_name->parent_names_list.
211
214
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
212
215
                      For this input the output from the sort or
213
216
                      iter_topo_order routines will be:
214
217
                      'A', 'B', 'C'
215
 
        :param branch_tip: the tip of the branch to graph. Revisions not
 
218
        :param branch_tip: the tip of the branch to graph. Revisions not 
216
219
                       reachable from branch_tip are not included in the
217
220
                       output.
218
221
        :param mainline_revisions: If not None this forces a mainline to be
230
233
        The result is a list sorted so that all parents come before
231
234
        their children. Each element of the list is a tuple containing:
232
235
        (sequence_number, node_name, merge_depth, end_of_merge)
233
 
         * sequence_number: The sequence of this row in the output. Useful for
 
236
         * sequence_number: The sequence of this row in the output. Useful for 
234
237
           GUIs.
235
238
         * node_name: The node name: opaque text to the merge routine.
236
239
         * merge_depth: How many levels of merging deep this node has been
247
250
             second commit in the trunk'.
248
251
         * end_of_merge: When True the next node is part of a different merge.
249
252
 
250
 
 
 
253
        
251
254
        node identifiers can be any hashable object, and are typically strings.
252
255
 
253
256
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
256
259
        The graph is sorted lazily: until you iterate or sort the input is
257
260
        not processed other than to create an internal representation.
258
261
 
259
 
        iteration or sorting may raise GraphCycleError if a cycle is present
 
262
        iteration or sorting may raise GraphCycleError if a cycle is present 
260
263
        in the graph.
261
264
 
262
265
        Background information on the design:
281
284
              E  1   [F]
282
285
              F 0
283
286
              C is the end of a cluster due to rule 1.
284
 
              D is not the end of a cluster from rule 1, but is from rule 2: E
 
287
              D is not the end of a cluster from rule 1, but is from rule 2: E 
285
288
                is not its left most ancestor
286
289
              E is the end of a cluster due to rule 1
287
290
              F might be but we need more data.
288
 
 
 
291
              
289
292
        we show connecting lines to a parent when:
290
293
         - The parent is the start of a merge within this cluster.
291
 
           That is, the merge was not done to the mainline before this cluster
 
294
           That is, the merge was not done to the mainline before this cluster 
292
295
           was merged to the mainline.
293
296
           This can be detected thus:
294
 
            * The parent has a higher merge depth and is the next revision in
 
297
            * The parent has a higher merge depth and is the next revision in 
295
298
              the list.
296
 
 
 
299
          
297
300
          The next revision in the list constraint is needed for this case:
298
 
          A 0   [D, B]
299
 
          B  1  [C, F]   # we do not want to show a line to F which is depth 2
 
301
          A 0   [D, B]   
 
302
          B  1  [C, F]   # we do not want to show a line to F which is depth 2 
300
303
                           but not a merge
301
 
          C  1  [H]      # note that this is a long line to show back to the
 
304
          C  1  [H]      # note that this is a long line to show back to the 
302
305
                           ancestor - see the end of merge rules.
303
306
          D 0   [G, E]
304
307
          E  1  [G, F]
339
342
        else:
340
343
            self._mainline_revisions = list(mainline_revisions)
341
344
            self._stop_revision = self._mainline_revisions[0]
342
 
        # skip the first revision, its what we reach and its parents are
 
345
        # skip the first revision, its what we reach and its parents are 
343
346
        # therefore irrelevant
344
347
        for index, revision in enumerate(self._mainline_revisions[1:]):
345
348
            # NB: index 0 means self._mainline_revisions[1]
375
378
                            for revision in self._graph)
376
379
        # Each mainline revision counts how many child branches have spawned from it.
377
380
        self._revno_to_branch_count = {}
378
 
 
 
381
        
379
382
        # this is a stack storing the depth first search into the graph.
380
383
        self._node_name_stack = []
381
384
        # at each level of recursion we need the merge depth this node is at:
382
385
        self._node_merge_depth_stack = []
383
386
        # at each level of 'recursion' we have to check each parent. This
384
 
        # stack stores the parents we have not yet checked for the node at the
 
387
        # stack stores the parents we have not yet checked for the node at the 
385
388
        # matching depth in _node_name_stack
386
389
        self._pending_parents_stack = []
387
390
        # When we first look at a node we assign it a seqence number from its
399
402
        # D 0  [F, E]
400
403
        # E  1 [F]
401
404
        # F 0
402
 
        # the scheduling order is: F, E, D, C, B, A
 
405
        # the scheduling order is: F, E, D, C, B, A 
403
406
        # that is - 'left subtree, right subtree, node'
404
407
        # which would mean that when we schedule A we can emit the entire tree.
405
408
        self._scheduled_nodes = []
406
 
        # This records for each node when we have processed its left most
 
409
        # This records for each node when we have processed its left most 
407
410
        # unmerged subtree. After this subtree is scheduled, all other subtrees
408
411
        # have their merge depth increased by one from this nodes merge depth.
409
412
        # it contains tuples - name, merge_depth
411
414
 
412
415
        # seed the search with the tip of the branch
413
416
        if (branch_tip is not None and
414
 
            branch_tip != _mod_revision.NULL_REVISION and
415
 
            branch_tip != (_mod_revision.NULL_REVISION,)):
 
417
            branch_tip != _mod_revision.NULL_REVISION):
416
418
            parents = self._graph.pop(branch_tip)
417
419
            self._push_node(branch_tip, 0, parents)
418
420
 
419
421
    def sorted(self):
420
422
        """Sort the graph and return as a list.
421
 
 
 
423
        
422
424
        After calling this the sorter is empty and you must create a new one.
423
425
        """
424
426
        return list(self.iter_topo_order())
425
427
 
426
428
    def iter_topo_order(self):
427
429
        """Yield the nodes of the graph in a topological order.
428
 
 
 
430
        
429
431
        After finishing iteration the sorter is empty and you cannot continue
430
432
        iteration.
431
433
        """
461
463
            left_subtree_pushed_stack_append(False)
462
464
            pending_parents_stack_append(list(parents))
463
465
            # as we push it, check if it is the first child
464
 
            parent_info = None
465
466
            if parents:
466
467
                # node has parents, assign from the left most parent.
467
 
                try:
468
 
                    parent_info = revnos[parents[0]]
469
 
                except KeyError:
470
 
                    # Left-hand parent is a ghost, consider it not to exist
471
 
                    pass
472
 
            if parent_info is not None:
 
468
                parent_info = revnos[parents[0]]
473
469
                first_child = parent_info[1]
474
470
                parent_info[1] = False
475
471
            else:
503
499
            pending_parents_stack_pop()
504
500
 
505
501
            parents = original_graph[node_name]
506
 
            parent_revno = None
507
502
            if parents:
508
503
                # node has parents, assign from the left most parent.
509
 
                try:
510
 
                    parent_revno = revnos[parents[0]][0]
511
 
                except KeyError:
512
 
                    # left-hand parent is a ghost, treat it as not existing
513
 
                    pass
514
 
            if parent_revno is not None:
 
504
                parent_revno = revnos[parents[0]][0]
515
505
                if not first_child:
516
506
                    # not the first child, make a new branch
517
507
                    base_revno = parent_revno[0]
555
545
                    if not left_subtree_pushed_stack[-1]:
556
546
                        # recurse depth first into the primary parent
557
547
                        next_node_name = pending_parents_stack[-1].pop(0)
558
 
                        is_left_subtree = True
559
 
                        left_subtree_pushed_stack[-1] = True
560
548
                    else:
561
549
                        # place any merges in right-to-left order for scheduling
562
550
                        # which gives us left-to-right order after we reverse
563
 
                        # the scheduled queue. XXX: This has the effect of
 
551
                        # the scheduled queue. XXX: This has the effect of 
564
552
                        # allocating common-new revisions to the right-most
565
 
                        # subtree rather than the left most, which will
 
553
                        # subtree rather than the left most, which will 
566
554
                        # display nicely (you get smaller trees at the top
567
555
                        # of the combined merge).
568
556
                        next_node_name = pending_parents_stack[-1].pop()
569
 
                        is_left_subtree = False
570
557
                    if next_node_name in completed_node_names:
571
558
                        # this parent was completed by a child on the
572
559
                        # call stack. skip it.
581
568
                        # current search stack (but not completed or we would
582
569
                        # have hit the continue 4 lines up.
583
570
                        # this indicates a cycle.
584
 
                        if next_node_name in self._original_graph:
585
 
                            raise errors.GraphCycleError(node_name_stack)
586
 
                        else:
587
 
                            # This is just a ghost parent, ignore it
588
 
                            continue
 
571
                        raise errors.GraphCycleError(node_name_stack)
589
572
                    next_merge_depth = 0
590
 
                    if is_left_subtree:
 
573
                    if left_subtree_pushed_stack[-1]:
591
574
                        # a new child branch from name_stack[-1]
 
575
                        next_merge_depth = 1
 
576
                    else:
592
577
                        next_merge_depth = 0
593
 
                    else:
594
 
                        next_merge_depth = 1
 
578
                        left_subtree_pushed_stack[-1] = True
595
579
                    next_merge_depth = (
596
580
                        node_merge_depth_stack[-1] + next_merge_depth)
597
581
                    push_node(
598
582
                        next_node_name,
599
583
                        next_merge_depth,
600
584
                        parents)
601
 
                    # and do not continue processing parents until this 'call'
 
585
                    # and do not continue processing parents until this 'call' 
602
586
                    # has recursed.
603
587
                    break
604
588
 
633
617
 
634
618
    def _push_node(self, node_name, merge_depth, parents):
635
619
        """Add node_name to the pending node stack.
636
 
 
 
620
        
637
621
        Names in this stack will get emitted into the output as they are popped
638
622
        off the stack.
639
623
        """
642
626
        self._left_subtree_pushed_stack.append(False)
643
627
        self._pending_parents_stack.append(list(parents))
644
628
        # as we push it, figure out if this is the first child
645
 
        parent_info = None
 
629
        parents = self._original_graph[node_name]
646
630
        if parents:
647
631
            # node has parents, assign from the left most parent.
648
 
            try:
649
 
                parent_info = self._revnos[parents[0]]
650
 
            except KeyError:
651
 
                # Left-hand parent is a ghost, consider it not to exist
652
 
                pass
653
 
        if parent_info is not None:
 
632
            parent_info = self._revnos[parents[0]]
654
633
            first_child = parent_info[1]
655
634
            parent_info[1] = False
656
635
        else:
660
639
        self._first_child_stack.append(first_child)
661
640
 
662
641
    def _pop_node(self):
663
 
        """Pop the top node off the stack
 
642
        """Pop the top node off the stack 
664
643
 
665
644
        The node is appended to the sorted output.
666
645
        """
674
653
        self._pending_parents_stack.pop()
675
654
 
676
655
        parents = self._original_graph[node_name]
677
 
        parent_revno = None
678
656
        if parents:
679
657
            # node has parents, assign from the left most parent.
680
 
            try:
681
 
                parent_revno = self._revnos[parents[0]][0]
682
 
            except KeyError:
683
 
                # left-hand parent is a ghost, treat it as not existing
684
 
                pass
685
 
        if parent_revno is not None:
 
658
            parent_revno = self._revnos[parents[0]][0]
686
659
            if not first_child:
687
660
                # not the first child, make a new branch
688
661
                base_revno = parent_revno[0]
698
671
        else:
699
672
            # no parents, use the root sequence
700
673
            root_count = self._revno_to_branch_count.get(0, 0)
701
 
            root_count = self._revno_to_branch_count.get(0, -1)
702
 
            root_count += 1
703
674
            if root_count:
704
675
                revno = (0, root_count, 1)
705
676
            else:
706
677
                revno = (1,)
 
678
            root_count += 1
707
679
            self._revno_to_branch_count[0] = root_count
708
680
 
709
681
        # store the revno for this node for future reference