~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tsort.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 19:05:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6450.
  • Revision ID: jelmer@samba.org-20120127190543-vk350mv4a0c7aug2
Fix weave test.

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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
16
 
18
17
"""Topological sorting routines."""
19
18
 
20
 
 
21
 
from bzrlib import errors
22
 
import bzrlib.revision as _mod_revision
 
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
    )
23
27
 
24
28
 
25
29
__all__ = ["topo_sort", "TopoSorter", "merge_sort", "MergeSorter"]
30
34
 
31
35
    graph -- sequence of pairs of node->parents_list.
32
36
 
33
 
    The result is a list of node names, such that all parents come before
34
 
    their children.
 
37
    The result is a list of node names, such that all parents come before their
 
38
    children.
35
39
 
36
40
    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.
37
49
    """
38
 
    return TopoSorter(graph).sorted()
 
50
    kg = _mod_graph.KnownGraph(dict(graph))
 
51
    return kg.topo_sort()
39
52
 
40
53
 
41
54
class TopoSorter(object):
42
55
 
43
56
    def __init__(self, graph):
44
57
        """Topological sorting of a graph.
45
 
    
 
58
 
46
59
        :param graph: sequence of pairs of node_name->parent_names_list.
47
60
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
48
61
                      For this input the output from the sort or
49
62
                      iter_topo_order routines will be:
50
63
                      'A', 'B', 'C'
51
 
        
 
64
 
52
65
        node identifiers can be any hashable object, and are typically strings.
53
66
 
54
67
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
57
70
        The graph is sorted lazily: until you iterate or sort the input is
58
71
        not processed other than to create an internal representation.
59
72
 
60
 
        iteration or sorting may raise GraphCycleError if a cycle is present 
 
73
        iteration or sorting may raise GraphCycleError if a cycle is present
61
74
        in the graph.
62
75
        """
63
 
        # a dict of the graph.
 
76
        # store a dict of the graph.
64
77
        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()
79
78
 
80
79
    def sorted(self):
81
80
        """Sort the graph and return as a list.
82
 
        
 
81
 
83
82
        After calling this the sorter is empty and you must create a new one.
84
83
        """
85
84
        return list(self.iter_topo_order())
96
95
 
97
96
    def iter_topo_order(self):
98
97
        """Yield the nodes of the graph in a topological order.
99
 
        
 
98
 
100
99
        After finishing iteration the sorter is empty and you cannot continue
101
100
        iteration.
102
101
        """
103
 
        while self._graph:
 
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:
104
118
            # now pick a random node in the source graph, and transfer it to the
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
 
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
112
128
                if not parents_to_visit:
113
129
                    # append the revision to the topo sorted list
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()
 
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
117
136
                else:
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
 
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))
164
160
 
165
161
 
166
162
def merge_sort(graph, branch_tip, mainline_revisions=None, generate_revno=False):
167
163
    """Topological sort a graph which groups merges.
168
164
 
169
165
    :param graph: sequence of pairs of node->parents_list.
170
 
    :param branch_tip: the tip of the branch to graph. Revisions not 
 
166
    :param branch_tip: the tip of the branch to graph. Revisions not
171
167
                       reachable from branch_tip are not included in the
172
168
                       output.
173
169
    :param mainline_revisions: If not None this forces a mainline to be
182
178
        revision number sequences in the output. See the output description of
183
179
        the MergeSorter docstring for details.
184
180
    :result: See the MergeSorter docstring for details.
185
 
    node identifiers can be any hashable object, and are typically strings.
 
181
 
 
182
    Node identifiers can be any hashable object, and are typically strings.
186
183
    """
187
184
    return MergeSorter(graph, branch_tip, mainline_revisions,
188
185
        generate_revno).sorted()
209
206
    def __init__(self, graph, branch_tip, mainline_revisions=None,
210
207
        generate_revno=False):
211
208
        """Merge-aware topological sorting of a graph.
212
 
    
 
209
 
213
210
        :param graph: sequence of pairs of node_name->parent_names_list.
214
211
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
215
212
                      For this input the output from the sort or
216
213
                      iter_topo_order routines will be:
217
214
                      'A', 'B', 'C'
218
 
        :param branch_tip: the tip of the branch to graph. Revisions not 
 
215
        :param branch_tip: the tip of the branch to graph. Revisions not
219
216
                       reachable from branch_tip are not included in the
220
217
                       output.
221
218
        :param mainline_revisions: If not None this forces a mainline to be
233
230
        The result is a list sorted so that all parents come before
234
231
        their children. Each element of the list is a tuple containing:
235
232
        (sequence_number, node_name, merge_depth, end_of_merge)
236
 
         * sequence_number: The sequence of this row in the output. Useful for 
 
233
         * sequence_number: The sequence of this row in the output. Useful for
237
234
           GUIs.
238
235
         * node_name: The node name: opaque text to the merge routine.
239
236
         * merge_depth: How many levels of merging deep this node has been
250
247
             second commit in the trunk'.
251
248
         * end_of_merge: When True the next node is part of a different merge.
252
249
 
253
 
        
 
250
 
254
251
        node identifiers can be any hashable object, and are typically strings.
255
252
 
256
253
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
259
256
        The graph is sorted lazily: until you iterate or sort the input is
260
257
        not processed other than to create an internal representation.
261
258
 
262
 
        iteration or sorting may raise GraphCycleError if a cycle is present 
 
259
        iteration or sorting may raise GraphCycleError if a cycle is present
263
260
        in the graph.
264
261
 
265
262
        Background information on the design:
284
281
              E  1   [F]
285
282
              F 0
286
283
              C is the end of a cluster due to rule 1.
287
 
              D is not the end of a cluster from rule 1, but is from rule 2: E 
 
284
              D is not the end of a cluster from rule 1, but is from rule 2: E
288
285
                is not its left most ancestor
289
286
              E is the end of a cluster due to rule 1
290
287
              F might be but we need more data.
291
 
              
 
288
 
292
289
        we show connecting lines to a parent when:
293
290
         - The parent is the start of a merge within this cluster.
294
 
           That is, the merge was not done to the mainline before this cluster 
 
291
           That is, the merge was not done to the mainline before this cluster
295
292
           was merged to the mainline.
296
293
           This can be detected thus:
297
 
            * The parent has a higher merge depth and is the next revision in 
 
294
            * The parent has a higher merge depth and is the next revision in
298
295
              the list.
299
 
          
 
296
 
300
297
          The next revision in the list constraint is needed for this case:
301
 
          A 0   [D, B]   
302
 
          B  1  [C, F]   # we do not want to show a line to F which is depth 2 
 
298
          A 0   [D, B]
 
299
          B  1  [C, F]   # we do not want to show a line to F which is depth 2
303
300
                           but not a merge
304
 
          C  1  [H]      # note that this is a long line to show back to the 
 
301
          C  1  [H]      # note that this is a long line to show back to the
305
302
                           ancestor - see the end of merge rules.
306
303
          D 0   [G, E]
307
304
          E  1  [G, F]
342
339
        else:
343
340
            self._mainline_revisions = list(mainline_revisions)
344
341
            self._stop_revision = self._mainline_revisions[0]
345
 
        # skip the first revision, its what we reach and its parents are 
 
342
        # skip the first revision, its what we reach and its parents are
346
343
        # therefore irrelevant
347
344
        for index, revision in enumerate(self._mainline_revisions[1:]):
348
345
            # NB: index 0 means self._mainline_revisions[1]
351
348
            if parent is None:
352
349
                # end of mainline_revisions history
353
350
                continue
354
 
            if self._graph[revision][0] == parent:
 
351
            graph_parent_ids = self._graph[revision]
 
352
            if not graph_parent_ids:
 
353
                # We ran into a ghost, skip over it, this is a workaround for
 
354
                # bug #243536, the _graph has had ghosts stripped, but the
 
355
                # mainline_revisions have not
 
356
                continue
 
357
            if graph_parent_ids[0] == parent:
355
358
                continue
356
359
            # remove it from its prior spot
357
360
            self._graph[revision].remove(parent)
372
375
                            for revision in self._graph)
373
376
        # Each mainline revision counts how many child branches have spawned from it.
374
377
        self._revno_to_branch_count = {}
375
 
        
 
378
 
376
379
        # this is a stack storing the depth first search into the graph.
377
380
        self._node_name_stack = []
378
381
        # at each level of recursion we need the merge depth this node is at:
379
382
        self._node_merge_depth_stack = []
380
383
        # at each level of 'recursion' we have to check each parent. This
381
 
        # stack stores the parents we have not yet checked for the node at the 
 
384
        # stack stores the parents we have not yet checked for the node at the
382
385
        # matching depth in _node_name_stack
383
386
        self._pending_parents_stack = []
384
387
        # When we first look at a node we assign it a seqence number from its
396
399
        # D 0  [F, E]
397
400
        # E  1 [F]
398
401
        # F 0
399
 
        # the scheduling order is: F, E, D, C, B, A 
 
402
        # the scheduling order is: F, E, D, C, B, A
400
403
        # that is - 'left subtree, right subtree, node'
401
404
        # which would mean that when we schedule A we can emit the entire tree.
402
405
        self._scheduled_nodes = []
403
 
        # This records for each node when we have processed its left most 
 
406
        # This records for each node when we have processed its left most
404
407
        # unmerged subtree. After this subtree is scheduled, all other subtrees
405
408
        # have their merge depth increased by one from this nodes merge depth.
406
409
        # it contains tuples - name, merge_depth
408
411
 
409
412
        # seed the search with the tip of the branch
410
413
        if (branch_tip is not None and
411
 
            branch_tip != _mod_revision.NULL_REVISION):
 
414
            branch_tip != _mod_revision.NULL_REVISION and
 
415
            branch_tip != (_mod_revision.NULL_REVISION,)):
412
416
            parents = self._graph.pop(branch_tip)
413
417
            self._push_node(branch_tip, 0, parents)
414
418
 
415
419
    def sorted(self):
416
420
        """Sort the graph and return as a list.
417
 
        
 
421
 
418
422
        After calling this the sorter is empty and you must create a new one.
419
423
        """
420
424
        return list(self.iter_topo_order())
421
425
 
422
426
    def iter_topo_order(self):
423
427
        """Yield the nodes of the graph in a topological order.
424
 
        
 
428
 
425
429
        After finishing iteration the sorter is empty and you cannot continue
426
430
        iteration.
427
431
        """
457
461
            left_subtree_pushed_stack_append(False)
458
462
            pending_parents_stack_append(list(parents))
459
463
            # as we push it, check if it is the first child
 
464
            parent_info = None
460
465
            if parents:
461
466
                # node has parents, assign from the left most parent.
462
 
                parent_info = revnos[parents[0]]
 
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:
463
473
                first_child = parent_info[1]
464
474
                parent_info[1] = False
465
475
            else:
493
503
            pending_parents_stack_pop()
494
504
 
495
505
            parents = original_graph[node_name]
 
506
            parent_revno = None
496
507
            if parents:
497
508
                # node has parents, assign from the left most parent.
498
 
                parent_revno = revnos[parents[0]][0]
 
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:
499
515
                if not first_child:
500
516
                    # not the first child, make a new branch
501
517
                    base_revno = parent_revno[0]
510
526
                    revno = parent_revno[:-1] + (parent_revno[-1] + 1,)
511
527
            else:
512
528
                # no parents, use the root sequence
513
 
                root_count = revno_to_branch_count.get(0, 0)
 
529
                root_count = revno_to_branch_count.get(0, -1)
 
530
                root_count += 1
514
531
                if root_count:
515
532
                    revno = (0, root_count, 1)
516
533
                else:
517
534
                    revno = (1,)
518
 
                root_count += 1
519
535
                revno_to_branch_count[0] = root_count
520
536
 
521
537
            # store the revno for this node for future reference
539
555
                    if not left_subtree_pushed_stack[-1]:
540
556
                        # recurse depth first into the primary parent
541
557
                        next_node_name = pending_parents_stack[-1].pop(0)
 
558
                        is_left_subtree = True
 
559
                        left_subtree_pushed_stack[-1] = True
542
560
                    else:
543
561
                        # place any merges in right-to-left order for scheduling
544
562
                        # which gives us left-to-right order after we reverse
545
 
                        # the scheduled queue. XXX: This has the effect of 
 
563
                        # the scheduled queue. XXX: This has the effect of
546
564
                        # allocating common-new revisions to the right-most
547
 
                        # subtree rather than the left most, which will 
 
565
                        # subtree rather than the left most, which will
548
566
                        # display nicely (you get smaller trees at the top
549
567
                        # of the combined merge).
550
568
                        next_node_name = pending_parents_stack[-1].pop()
 
569
                        is_left_subtree = False
551
570
                    if next_node_name in completed_node_names:
552
571
                        # this parent was completed by a child on the
553
572
                        # call stack. skip it.
562
581
                        # current search stack (but not completed or we would
563
582
                        # have hit the continue 4 lines up.
564
583
                        # this indicates a cycle.
565
 
                        raise errors.GraphCycleError(node_name_stack)
 
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
566
589
                    next_merge_depth = 0
567
 
                    if left_subtree_pushed_stack[-1]:
 
590
                    if is_left_subtree:
568
591
                        # a new child branch from name_stack[-1]
 
592
                        next_merge_depth = 0
 
593
                    else:
569
594
                        next_merge_depth = 1
570
 
                    else:
571
 
                        next_merge_depth = 0
572
 
                        left_subtree_pushed_stack[-1] = True
573
595
                    next_merge_depth = (
574
596
                        node_merge_depth_stack[-1] + next_merge_depth)
575
597
                    push_node(
576
598
                        next_node_name,
577
599
                        next_merge_depth,
578
600
                        parents)
579
 
                    # and do not continue processing parents until this 'call' 
 
601
                    # and do not continue processing parents until this 'call'
580
602
                    # has recursed.
581
603
                    break
582
604
 
611
633
 
612
634
    def _push_node(self, node_name, merge_depth, parents):
613
635
        """Add node_name to the pending node stack.
614
 
        
 
636
 
615
637
        Names in this stack will get emitted into the output as they are popped
616
638
        off the stack.
617
639
        """
620
642
        self._left_subtree_pushed_stack.append(False)
621
643
        self._pending_parents_stack.append(list(parents))
622
644
        # as we push it, figure out if this is the first child
623
 
        parents = self._original_graph[node_name]
 
645
        parent_info = None
624
646
        if parents:
625
647
            # node has parents, assign from the left most parent.
626
 
            parent_info = self._revnos[parents[0]]
 
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:
627
654
            first_child = parent_info[1]
628
655
            parent_info[1] = False
629
656
        else:
633
660
        self._first_child_stack.append(first_child)
634
661
 
635
662
    def _pop_node(self):
636
 
        """Pop the top node off the stack 
 
663
        """Pop the top node off the stack
637
664
 
638
665
        The node is appended to the sorted output.
639
666
        """
647
674
        self._pending_parents_stack.pop()
648
675
 
649
676
        parents = self._original_graph[node_name]
 
677
        parent_revno = None
650
678
        if parents:
651
679
            # node has parents, assign from the left most parent.
652
 
            parent_revno = self._revnos[parents[0]][0]
 
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:
653
686
            if not first_child:
654
687
                # not the first child, make a new branch
655
688
                base_revno = parent_revno[0]
665
698
        else:
666
699
            # no parents, use the root sequence
667
700
            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
668
703
            if root_count:
669
704
                revno = (0, root_count, 1)
670
705
            else:
671
706
                revno = (1,)
672
 
            root_count += 1
673
707
            self._revno_to_branch_count[0] = root_count
674
708
 
675
709
        # store the revno for this node for future reference