Ticket #14498: trac_14498-tree-imps-dg-rebased.patch

File trac_14498-tree-imps-dg-rebased.patch, 60.5 KB (added by chapoton, 6 years ago)
  • sage/combinat/abstract_tree.py

    # HG changeset patch
    # User Frederic Chapoton <chapoton at math.univ-lyon1.fr>
    # Date 1382123112 -7200
    # Node ID b3162778b44eb8e6f0c04ed70e5b87ae4b009895
    # Parent  20a34cc5729a9c90846e984ff1fd9b0dfe42d374
    trac #14498: some improvements on trees
    
    diff --git a/sage/combinat/abstract_tree.py b/sage/combinat/abstract_tree.py
    a b incoherent with the data structure. 
    6666from sage.structure.list_clone import ClonableArray
    6767from sage.rings.integer import Integer
    6868from sage.misc.misc_c import prod
    69 from sage.misc import lazy_attribute
    7069###############################################################################
    7170# # use to load tikz in the preamble (one for *view* and one for *notebook*)
    7271from sage.misc.latex import latex
    class AbstractTree(object): 
    365364            |  / /        |
    366365            | 4 5         |
    367366
    368         The algorithm explorer this tree in the following order:
     367        The algorithm explores this tree in the following order:
    369368        `4,5,3,2,7,6,9,10,8,1`.
    370369
    371370        TESTS::
    class AbstractTree(object): 
    860859
    861860    def tree_factorial(self):
    862861        """
    863         Returns the tree-factorial of ``self``
     862        Return the tree-factorial of ``self``
    864863
    865864        Definition:
    866865
  • sage/combinat/binary_tree.py

    diff --git a/sage/combinat/binary_tree.py b/sage/combinat/binary_tree.py
    a b  
    22"""
    33Binary Trees
    44
    5 This module deals with binary trees as mathematical (in particular immmutable)
     5This module deals with binary trees as mathematical (in particular immutable)
    66objects.
    77
    88.. NOTE::
    AUTHORS: 
    1414
    1515- Florent Hivert (2010-2011): initial implementation.
    1616
    17 References
    18 ----------
     17REFERENCES:
    1918
    2019.. [LodayRonco] Jean-Louis Loday and María O. Ronco.
    21    *Hopf algebra of the planar binary trees*.
    22    
     20   *Hopf algebra of the planar binary trees*,
     21   Advances in Mathematics, volume 139, issue 2,
     22   10 November 1998, pp. 293-309.
     23   http://www.sciencedirect.com/science/article/pii/S0001870898917595
     24
    2325.. [HNT05] Florent Hivert, Jean-Christophe Novelli, and Jean-Yves Thibon.
    24    *The algebra of binary search trees*.
     26   *The algebra of binary search trees*,
     27   :arxiv:`math/0401089v2`.
     28
     29.. [CP12] Gregory Chatel, Vivane Pons.
     30   *Counting smaller trees in the Tamari order*,
     31   :arxiv:`1212.0751v1`.
    2532"""
    2633#*****************************************************************************
    2734#       Copyright (C) 2010 Florent Hivert <Florent.Hivert@univ-rouen.fr>,
    class BinaryTree(AbstractClonableTree, C 
    4451    """
    4552    Binary trees.
    4653
    47     Binary trees here mean ordered (a.k.a. plane) binary trees,
    48     meaning that the children of each node are ordered.
     54    Binary trees here mean ordered (a.k.a. plane) finite binary
     55    trees, where "ordered" means that the children of each node are
     56    ordered.
     57
     58    Binary trees contain nodes and leaves, where each node has two
     59    children while each leaf has no children. The number of leaves
     60    always equals the number of nodes plus `1`.
    4961
    5062    INPUT:
    5163
    5264    - ``children`` -- ``None`` (default) or a list, tuple or iterable of
    53       length 2 of binary trees or convertible objects. This corresponds to
    54       the standard recursive definition of a binary tree as either a leaf
    55       or a pair of binary trees. Syntactic sugar allows leaving out all
    56       but the outermost calls of the ``BinaryTree()`` constructor, so that,
    57       e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can be
    58       simplified to ``BinaryTree([None,None])``. It is also allowed to
     65      length `2` of binary trees or convertible objects. This corresponds
     66      to the standard recursive definition of a binary tree as either a
     67      leaf or a pair of binary trees. Syntactic sugar allows leaving out
     68      all but the outermost calls of the ``BinaryTree()`` constructor, so
     69      that, e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can
     70      be simplified to ``BinaryTree([None,None])``. It is also allowed to
    5971      abbreviate ``[None, None]`` by ``[]``.
    6072
    6173    - ``check`` -- (default to ``True``) whether check for binary should be
    class BinaryTree(AbstractClonableTree, C 
    98110    def __classcall_private__(cls, *args, **opts):
    99111        """
    100112        Ensure that binary trees created by the enumerated sets and directly
    101         are the same and that they are instances of :class:`BinaryTree`
     113        are the same and that they are instances of :class:`BinaryTree`.
    102114
    103115        TESTS::
    104116
    class BinaryTree(AbstractClonableTree, C 
    128140    @lazy_class_attribute
    129141    def _auto_parent(cls):
    130142        """
    131         The automatic parent of the element of this class
     143        The automatic parent of the elements of this class.
    132144
    133145        When calling the constructor of an element of this class, one needs a
    134146        parent. This class attribute specifies which parent is used.
    class BinaryTree(AbstractClonableTree, C 
    139151            Binary trees
    140152            sage: BinaryTree([None, None]).parent()
    141153            Binary trees
    142          """
     154        """
    143155        return BinaryTrees_all()
    144156
    145157    def __init__(self, parent, children = None, check = True):
    class BinaryTree(AbstractClonableTree, C 
    175187
    176188    def check(self):
    177189        """
    178         Checks that ``self`` is a binary tree
     190        Check that ``self`` is a binary tree.
    179191
    180192        EXAMPLES::
    181193
    class BinaryTree(AbstractClonableTree, C 
    411423
    412424    def is_empty(self):
    413425        """
    414         Return whether ``self`` is  empty.
     426        Return whether ``self`` is empty.
     427
     428        The notion of emptiness employed here is the one which defines
     429        a binary tree to be empty if its root is a leaf. There is
     430        precisely one empty binary tree.
    415431
    416432        EXAMPLES::
    417433
    class BinaryTree(AbstractClonableTree, C 
    424440        """
    425441        return not self
    426442
    427     def graph(self):
     443    def graph(self, with_leaves=True):
    428444        """
    429         Convert ``self`` to a digraph
    430 
    431         EXAMPLE::
     445        Convert ``self`` to a digraph. By default, this graph contains
     446        both nodes and leaves, hence is never empty. To obtain a graph
     447        which contains only the nodes, the ``with_leaves`` optional
     448        keyword variable has to be set to ``False``.
     449
     450        INPUT:
     451
     452        - ``with_leaves`` -- (default: ``True``) a Boolean, determining
     453          whether the resulting graph will be formed from the leaves
     454          and the nodes of ``self`` (if ``True``), or only from the
     455          nodes of ``self`` (if ``False``)
     456
     457        EXAMPLES::
    432458
    433459            sage: t1 = BinaryTree([[], None])
    434460            sage: t1.graph()
    435461            Digraph on 5 vertices
     462            sage: t1.graph(with_leaves=False)
     463            Digraph on 2 vertices
    436464
    437465            sage: t1 = BinaryTree([[], [[], None]])
    438466            sage: t1.graph()
    439467            Digraph on 9 vertices
    440468            sage: t1.graph().edges()
    441469            [(0, 1, None), (0, 4, None), (1, 2, None), (1, 3, None), (4, 5, None), (4, 8, None), (5, 6, None), (5, 7, None)]
     470            sage: t1.graph(with_leaves=False)
     471            Digraph on 4 vertices
     472            sage: t1.graph(with_leaves=False).edges()
     473            [(0, 1, None), (0, 2, None), (2, 3, None)]
     474
     475            sage: t1 = BinaryTree()
     476            sage: t1.graph()
     477            Digraph on 1 vertex
     478            sage: t1.graph(with_leaves=False)
     479            Digraph on 0 vertices
     480
     481            sage: BinaryTree([]).graph()
     482            Digraph on 3 vertices
     483            sage: BinaryTree([]).graph(with_leaves=False)
     484            Digraph on 1 vertex
     485
     486            sage: t1 = BinaryTree([[], [[], []]])
     487            sage: t1.graph(with_leaves=False)
     488            Digraph on 5 vertices
     489            sage: t1.graph(with_leaves=False).edges()
     490            [(0, 1, None), (0, 2, None), (2, 3, None), (2, 4, None)]
    442491        """
    443492        from sage.graphs.graph import DiGraph
    444         res = DiGraph()
    445         def rec(tr, idx):
    446             if not tr:
    447                 return
    448             else:
    449                 nbl = 2*tr[0].node_number() + 1
    450                 res.add_edges([[idx,idx+1], [idx,idx+1+nbl]])
    451                 rec(tr[0], idx + 1)
    452                 rec(tr[1], idx + nbl + 1)
    453         rec(self, 0)
    454         return res
     493
     494        if with_leaves:   # We want leaves and nodes.
     495
     496            # Special treatment for the case when self has only 1 vertex.
     497            # In this case, rec(self, 0) would give a false result.
     498            if not self:
     499                return DiGraph([[0], lambda i,j: False])
     500   
     501            res = DiGraph()
     502            # The edge set of res will be built up step by step using the
     503            # following function:
     504            def rec(tr, idx):
     505                if not tr:  # tr is a leaf.
     506                    return
     507                else:  # tr is a node.
     508                    nbl = 2*tr[0].node_number() + 1
     509                    res.add_edges([[idx,idx+1], [idx,idx+1+nbl]])
     510                    rec(tr[0], idx + 1)
     511                    rec(tr[1], idx + nbl + 1)
     512            rec(self, 0)
     513            return res
     514
     515        else:   # We want only the nodes.
     516
     517            # Special treatment for the case when self has only 1 node.
     518            # In this case, the general DiGraph construction would
     519            # falsely yield an empty graph (since it adds nodes only
     520            # implicitly by adding edges).
     521            if self.node_number() == 1:
     522                return DiGraph([[0], lambda i,j: False])
     523
     524            res = DiGraph()
     525            # The edge set of res will be built up step by step using the
     526            # following function:
     527            def rec(tr, idx):
     528                if not tr:  # tr is a leaf.
     529                    return
     530                else:  # tr is a node.
     531                    nbl = tr[0].node_number()
     532                    if nbl > 0:
     533                        res.add_edge([idx, idx + 1])
     534                        rec(tr[0], idx + 1)
     535                    if tr[1].node_number() > 0:
     536                        res.add_edge([idx, idx + nbl + 1])
     537                        rec(tr[1], idx + nbl + 1)
     538            rec(self, 0)
     539            return res
    455540
    456541    def canonical_labelling(self,shift=1):
    457542        """
    458543        Return a labelled version of ``self``.
    459544
     545        The canonical labelling of a binary tree is a certain labelling of the
     546        nodes (not the leaves) of the tree.
    460547        The actual canonical labelling is currently unspecified. However, it
    461548        is guaranteed to have labels in `1...n` where `n` is the number of
    462549        nodes of the tree. Moreover, two (unlabelled) trees compare as equal if
    class BinaryTree(AbstractClonableTree, C 
    480567        else:
    481568            return LTR(None)
    482569
    483     def show(self):
     570    def show(self, with_leaves=False):
    484571        """
     572        Show the binary tree ``show``, with or without leaves depending
     573        on the Boolean keyword variable ``with_leaves``.
     574
     575        .. WARNING::
     576
     577            Left and right children might get interchanged in
     578            the actual picture.
     579
    485580        TESTS::
    486581
    487582            sage: t1 = BinaryTree([[], [[], None]])
    488583            sage: t1.show()
    489584        """
    490         self.graph().show(layout='tree', tree_root=0, tree_orientation="down")
     585        try:
     586            self.graph(with_leaves=with_leaves).show(layout='tree', tree_root=0, tree_orientation="down")
     587        except RuntimeError:
     588            # This is for the border case BinaryTree().show().
     589            self.graph(with_leaves=with_leaves).show()
    491590
    492591    def make_node(self, child_list = [None, None]):
    493592        """
    494         Modify ``self`` so that it becomes a node with children ``childlist``
     593        Modify ``self`` so that it becomes a node with children ``child_list``.
    495594
    496595        INPUT:
    497596
    class BinaryTree(AbstractClonableTree, C 
    510609            ...
    511610            ValueError: object is immutable; please change a copy instead.
    512611            sage: with t.clone() as t1:
    513             ...    t1.make_node([None, None])
     612            ....:     t1.make_node([None, None])
    514613            sage: t, t1
    515614            (., [., .])
    516615            sage: with t.clone() as t:
    517             ...    t.make_node([BinaryTree(), BinaryTree(), BinaryTree([])])
     616            ....:     t.make_node([BinaryTree(), BinaryTree(), BinaryTree([])])
    518617            Traceback (most recent call last):
    519618            ...
    520619            ValueError: the list must have length 2
    521620            sage: with t1.clone() as t2:
    522             ...    t2.make_node([t1, t1])
     621            ....:     t2.make_node([t1, t1])
    523622            sage: with t2.clone() as t3:
    524             ...    t3.make_node([t1, t2])
     623            ....:     t3.make_node([t1, t2])
    525624            sage: t1, t2, t3
    526625            ([., .], [[., .], [., .]], [[., .], [[., .], [., .]]])
    527626        """
    class BinaryTree(AbstractClonableTree, C 
    533632
    534633    def make_leaf(self):
    535634        """
    536         Modify ``self`` so that it became a leaf
     635        Modify ``self`` so that it becomes a leaf (i. e., an empty tree).
    537636
    538637        .. NOTE:: ``self`` must be in a mutable state.
    539638
    class BinaryTree(AbstractClonableTree, C 
    548647            ...
    549648            ValueError: object is immutable; please change a copy instead.
    550649            sage: with t.clone() as t1:
    551             ...    t1.make_leaf()
     650            ....:     t1.make_leaf()
    552651            sage: t, t1
    553652            ([., .], .)
    554653        """
    class BinaryTree(AbstractClonableTree, C 
    585684    def to_dyck_word_tamari(self):
    586685        r"""
    587686        Return the Dyck word associated with ``self`` in consistency with
    588         the Tamari order on dyck words and binary trees.
     687        the Tamari order on Dyck words and binary trees.
    589688
    590689        The bijection is defined recursively as follows:
    591690
    class BinaryTree(AbstractClonableTree, C 
    605704            sage: BinaryTree([[[], [[], None]], [[], []]]).to_dyck_word_tamari()
    606705            [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]
    607706        """
    608         from sage.combinat.dyck_word import DyckWord
    609707        return self.to_dyck_word("L1R0")
    610708
    611709    @combinatorial_map(name="to Dyck paths: up step, left tree, down step, right tree")
    612710    def to_dyck_word(self, usemap="1L0R"):
    613711        r"""
     712        Return the Dyck word associated with ``self`` using the given map.
     713
    614714        INPUT:
    615715
    616716        - ``usemap`` -- a string, either ``1L0R``, ``1R0L``, ``L1R0``, ``R1L0``
    617717
    618         Return the Dyck word associated with ``self`` using the given map.
    619 
    620718        The bijection is defined recursively as follows:
    621719
    622720        - a leaf is associated to the empty Dyck Word
    623721
    624722        - a tree with children `l,r` is associated with the Dyck word
    625723          described by ``usemap`` where `L` and `R` are respectively the
    626           Dyck words associated with the `l` and `r`.
     724          Dyck words associated with the trees `l` and `r`.
    627725
    628726        EXAMPLES::
    629727
    class BinaryTree(AbstractClonableTree, C 
    728826    @combinatorial_map(name="To ordered tree, right child = right brother")
    729827    def to_ordered_tree_right_branch(self):
    730828        r"""
    731         Return an ordered tree of size n+1 by the following recursive rule:
     829        Return an ordered tree of size `n+1` by the following recursive rule:
    732830
    733831        - if `x` is the right child of `y`, `x` becomes the right brother
    734832          of `y`
    class BinaryTree(AbstractClonableTree, C 
    784882        Return a 312-avoiding permutation corresponding to the binary tree.
    785883
    786884        The linear extensions of a binary tree form an interval of the weak
    787         order called the sylester class of the tree. This permutation is
     885        order called the sylvester class of the tree. This permutation is
    788886        the minimal element of this sylvester class.
    789887
    790888        EXAMPLES::
    class BinaryTree(AbstractClonableTree, C 
    809907        return Permutation(self._postfix_word())
    810908
    811909    @combinatorial_map(name="To complete tree")
    812     def as_ordered_tree(self,with_leaves=True):
     910    def as_ordered_tree(self, with_leaves=True):
    813911        r"""
    814912        Return the same tree seen as an ordered tree. By default, leaves
    815         are transformed into actual nodes.
     913        are transformed into actual nodes, but this can be avoided by
     914        setting the optional variable ``with_leaves`` to ``False``.
    816915
    817916        EXAMPLES::
    818917
    class BinaryTree(AbstractClonableTree, C 
    832931        if with_leaves:
    833932            children = [child.as_ordered_tree(with_leaves) for child in self]
    834933        else:
     934            if not self:
     935                raise ValueError("The empty binary tree cannot be made into an ordered tree with with_leaves = False")
    835936            children = [child.as_ordered_tree(with_leaves) for child in self if not child.is_empty()]
    836937        if self in LabelledBinaryTrees():
    837938            from sage.combinat.ordered_tree import LabelledOrderedTree
    class BinaryTree(AbstractClonableTree, C 
    841942            return OrderedTree(children)
    842943
    843944    @combinatorial_map(name="To graph")
    844     def to_undirected_graph(self, with_leaves = False):
     945    def to_undirected_graph(self, with_leaves=False):
    845946        r"""
    846947        Return the undirected graph obtained from the tree nodes and edges.
    847         Leafs are ignored by default but can set ``with_leaves`` to ``True``
    848         to obtain the graph of the complete tree.
     948        Leaves are ignored by default, but one can set ``with_leaves`` to
     949        ``True`` to obtain the graph of the complete tree.
     950
     951        INPUT:
     952
     953        - ``with_leaves`` -- (default: ``False``) a Boolean, determining
     954          whether the resulting graph will be formed from the leaves
     955          and the nodes of ``self`` (if ``True``), or only from the
     956          nodes of ``self`` (if ``False``)
    849957
    850958        EXAMPLES::
    851959
    class BinaryTree(AbstractClonableTree, C 
    855963            sage: bt.to_undirected_graph(with_leaves=True)
    856964            Graph on 3 vertices
    857965
     966            sage: bt = BinaryTree()
     967            sage: bt.to_undirected_graph()
     968            Graph on 0 vertices
     969            sage: bt.to_undirected_graph(with_leaves=True)
     970            Graph on 1 vertex
     971
    858972        If the tree is labelled, we use its labelling to label the graph.
    859973        Otherwise, we use the graph canonical labelling which means that
    860974        two different trees can have the same graph.
    class BinaryTree(AbstractClonableTree, C 
    873987            sage: BinaryTree([[],[]]).to_undirected_graph() == BinaryTree([[[],None],None]).to_undirected_graph()
    874988            True
    875989        """
     990        if (not with_leaves) and (not self):
     991            # this case needs extra care :(
     992            from sage.graphs.graph import Graph
     993            return Graph([])
    876994        return self.as_ordered_tree(with_leaves).to_undirected_graph()
    877995
    878996    @combinatorial_map(name="To poset")
    879     def to_poset(self, with_leaves = False, root_to_leaf=False):
     997    def to_poset(self, with_leaves=False, root_to_leaf=False):
    880998        r"""
    881         Return the poset obtained by interpreting the tree as a hasse
     999        Return the poset obtained by interpreting the tree as a Hasse
    8821000        diagram.
    8831001
    8841002        The default orientation is from leaves to root but you can
    8851003        pass ``root_to_leaf=True`` to obtain the inverse orientation.
    8861004
    887         Leafs are ignored by default but can set ``with_leaves`` to ``True``
    888         to obtain the poset of the complete tree.
     1005        Leaves are ignored by default, but one can set ``with_leaves`` to
     1006        ``True`` to obtain the poset of the complete tree.
    8891007
    8901008        INPUT:
    8911009
    892         - ``with_leaves`` -- boolean, true if leaves should be added to the poset
    893         - ``root_to_leaf`` -- boolean, true if the poset orientation should
    894           be from root to leaves. It is false by default.
     1010        - ``with_leaves`` -- (default: ``False``) a Boolean, determining
     1011          whether the resulting poset will be formed from the leaves
     1012          and the nodes of ``self`` (if ``True``), or only from the
     1013          nodes of ``self`` (if ``False``)
     1014        - ``root_to_leaf`` -- (default: ``False``) a Boolean,
     1015          determining whether the poset orientation should be from root
     1016          to leaves (if ``True``) or from leaves to root (if ``False``).
    8951017
    8961018        EXAMPLES::
    8971019
    class BinaryTree(AbstractClonableTree, C 
    9141036            2[1[., .], 3[., 4[., .]]]
    9151037            sage: bt.to_poset().cover_relations()
    9161038            [[4, 3], [3, 2], [1, 2]]
     1039
     1040        Let us check that the empty binary tree is correctly handled::
     1041
     1042            sage: bt = BinaryTree()
     1043            sage: bt.to_poset()
     1044            Finite poset containing 0 elements
     1045            sage: bt.to_poset(with_leaves=True)
     1046            Finite poset containing 1 elements
    9171047        """
     1048        if (not with_leaves) and (not self):
     1049            # this case needs extra care :(
     1050            from sage.combinat.posets.posets import Poset
     1051            return Poset({})
    9181052        return self.as_ordered_tree(with_leaves).to_poset(root_to_leaf)
    9191053
    9201054    @combinatorial_map(name="To 132 avoiding permutation")
    class BinaryTree(AbstractClonableTree, C 
    9231057        Return a 132-avoiding permutation corresponding to the binary tree.
    9241058
    9251059        The linear extensions of a binary tree form an interval of the weak
    926         order called the sylester class of the tree. This permutation is
     1060        order called the sylvester class of the tree. This permutation is
    9271061        the maximal element of this sylvester class.
    9281062
    9291063        EXAMPLES::
    class BinaryTree(AbstractClonableTree, C 
    10141148
    10151149    def canopee(self):
    10161150        """
    1017         Return the canopee of ``self``
    1018 
    1019         The *canopee* of a non empty binary tree `T` with `n` internal nodes is
     1151        Return the canopee of ``self``.
     1152
     1153        The *canopee* of a non-empty binary tree `T` with `n` internal nodes is
    10201154        the list `l` of `0` and `1` of length `n-1` obtained by going along the
    10211155        leaves of `T` from left to right except the two extremal ones, writing
    10221156        `0` if the leaf is a right leaf and `1` if the leaf is a left leaf.
    class BinaryTree(AbstractClonableTree, C 
    10361170
    10371171        The number of pairs `(t_1, t_2)` of binary trees of size `n` such that
    10381172        the canopee of `t_1` is the complementary of the canopee of `t_2` is
    1039         also the number of Baxter permutations (see [DG]_, see
     1173        also the number of Baxter permutations (see [DG94]_, see
    10401174        also :oeis:`A001181`). We check this in small cases::
    10411175
    10421176            sage: [len([(u,v) for u in BinaryTrees(n) for v in BinaryTrees(n)
    1043             ...       if map(lambda x:1-x, u.canopee()) == v.canopee()])
    1044             ...    for n in range(1, 5)]
     1177            ....:       if map(lambda x:1-x, u.canopee()) == v.canopee()])
     1178            ....:    for n in range(1, 5)]
    10451179            [1, 2, 6, 22]
    10461180
    10471181        Here is a less trivial implementation of this::
    class BinaryTree(AbstractClonableTree, C 
    10491183            sage: from sage.sets.finite_set_map_cy import fibers
    10501184            sage: from sage.misc.all import attrcall
    10511185            sage: def baxter(n):
    1052             ...      f = fibers(lambda t: tuple(t.canopee()),
    1053             ...                   BinaryTrees(n))
    1054             ...      return sum(len(f[i])*len(f[tuple(1-x for x in i)])
    1055             ...                 for i in f)
     1186            ....:     f = fibers(lambda t: tuple(t.canopee()),
     1187            ....:                   BinaryTrees(n))
     1188            ....:     return sum(len(f[i])*len(f[tuple(1-x for x in i)])
     1189            ....:                for i in f)
    10561190            sage: [baxter(n) for n in range(1, 7)]
    10571191            [1, 2, 6, 22, 92, 422]
    10581192
    class BinaryTree(AbstractClonableTree, C 
    10651199
    10661200        REFERENCES:
    10671201
    1068             .. [DG] S. Dulucq and O, Guibert. Mots de piles, tableaux
    1069                standards et permutations de Baxter, proceedings of
    1070                Formal Power Series and Algebraic Combinatorics, 1994.
     1202        .. [DG94] S. Dulucq and O. Guibert. Mots de piles, tableaux
     1203           standards et permutations de Baxter, proceedings of
     1204           Formal Power Series and Algebraic Combinatorics, 1994.
    10711205        """
    10721206        if not self:
    10731207            raise ValueError("canopee is only defined for non empty binary trees")
    class BinaryTree(AbstractClonableTree, C 
    10831217
    10841218    def in_order_traversal_iter(self):
    10851219        """
    1086         The depth-first infix-order traversal iterator.
    1087 
    1088         This method iters each node following the infix order traversal
    1089         algorithm.
    1090 
    1091         For example on the following binary tree `T` where we denote leaves by
    1092         `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
     1220        The depth-first infix-order traversal iterator for the binary
     1221        tree ``self``.
     1222
     1223        This method iters each vertex (node and leaf alike) following the
     1224        depth-first infix order traversal algorithm.
     1225
     1226        The *depth-first infix order traversal algorithm* iterates
     1227        through a binary tree as follows::
     1228
     1229            iterate through the left subtree (by the depth-first infix
     1230                order traversal algorithm);
     1231            yield the root;
     1232            iterate through the right subtree (by the depth-first infix
     1233                order traversal algorithm).
     1234
     1235        For example on the following binary tree `T`, where we denote
     1236        leaves by `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
    10931237
    10941238            |     ____3____          |
    10951239            |    /         \         |
    class BinaryTree(AbstractClonableTree, C 
    11011245            |         / \   / \      |
    11021246            |        d   e f   g     |
    11031247
    1104         the *depth-first infixe-order traversal algorithm* explores `T` in
    1105         the following order of nodes `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
    1106 
    1107         ALGORITHM::
    1108 
    1109             explore the left subtree
    1110             manipulate the root with function `node_action` if the root is
    1111                 a node and with function `leaf_action` if it is a leaf
    1112             explore the right subtree
     1248        the depth-first infix-order traversal algorithm iterates through
     1249        the vertices of `T` in the following order:
     1250        `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
     1251
     1252        See :meth:`in_order_traversal` for a version of this algorithm
     1253        which not only iterates through, but actually does something at
     1254        the vertices of tree.
    11131255
    11141256        TESTS::
    11151257
    class BinaryTree(AbstractClonableTree, C 
    11501292
    11511293    def in_order_traversal(self, node_action=None, leaf_action=None):
    11521294        r"""
    1153         The depth-first infix-order traversal algorithm.
    1154 
    1155         .. SEEALSO::
    1156 
    1157             :meth:`~sage.combinat.binary_tree.BinaryTree.in_order_traversal_iter()`
     1295        Explore the binary tree ``self`` using the depth-first infix-order
     1296        traversal algorithm, executing the ``node_action`` function
     1297        whenever traversing a node and executing the ``leaf_action``
     1298        function whenever traversing a leaf.
     1299
     1300        In more detail, what this method does to a tree `T` is the
     1301        following::
     1302
     1303            if the root of `T` is a node:
     1304                apply in_order_traversal to the left subtree of `T`
     1305                    (with the same node_action and leaf_action);
     1306                apply node_action to the root of `T`;
     1307                apply in_order_traversal to the right subtree of `T`
     1308                    (with the same node_action and leaf_action);
     1309            else:
     1310                apply leaf_action to the root of `T`.
     1311
     1312        For example on the following binary tree `T`, where we denote
     1313        leaves by `a, b, c, \ldots` and nodes by `1, 2, 3, \ldots`::
     1314
     1315            |     ____3____          |
     1316            |    /         \         |
     1317            |   1          __7__     |
     1318            |  / \        /     \    |
     1319            | a   2      _5_     8   |
     1320            |    / \    /   \   / \  |
     1321            |   b   c  4     6 h   i |
     1322            |         / \   / \      |
     1323            |        d   e f   g     |
     1324
     1325        this method first applies ``leaf_action`` to `a`, then applies
     1326        ``node_action`` to `1`, then ``leaf_action`` to `b`, then
     1327        ``node_action`` to `2`, etc., with the vertices being traversed
     1328        in the order `a,1,b,2,c,3,d,4,e,5,f,6,g,7,h,8,i`.
     1329
     1330        See :meth:`in_order_traversal_iter` for a version of this
     1331        algorithm which only iterates through the vertices rather than
     1332        applying any function to them.
    11581333
    11591334        INPUT:
    11601335
    class BinaryTree(AbstractClonableTree, C 
    12181393
    12191394    def tamari_greater(self):
    12201395        r"""
    1221         The list of all trees greater than ``self``.
     1396        The list of all trees greater or equal to ``self`` in the Tamari
     1397        order.
    12221398        This is the transitive ideal of its successors.
    12231399
    1224         The tree::
     1400        The Tamari order on binary trees of size `n` is the partial order
     1401        on the set of all binary trees of size `n` generated by the
     1402        following requirement:  If a binary tree `T'` is obtained by
     1403        right rotation (see :meth:`right_rotate`) from a binary tree `T`,
     1404        then `T < T'`.
     1405        This not only is a well-defined partial order, but actually is
     1406        a lattice structure on the set of binary trees of size `n`, and
     1407        is a quotient of the weak order on the `n`-th symmetric group.
     1408        See [CP12]_.
     1409
     1410        For example, the tree::
    12251411
    12261412            |     __o__   |
    12271413            |    /     \  |
    class BinaryTree(AbstractClonableTree, C 
    12291415            |  / \     /  |
    12301416            | o   o   o   |
    12311417
    1232         has these trees greater than it::
     1418        has these trees greater or equal to it::
    12331419
    12341420            |o          , o        , o        , o        ,  o       ,   o      ,|
    12351421            | \            \          \          \           \           \      |
    class BinaryTree(AbstractClonableTree, C 
    12761462
    12771463    def tamari_pred(self):
    12781464        r"""
    1279         Compute the list of predecessor of ``self`` in the tamari poset.
     1465        Compute the list of predecessors of ``self`` in the Tamari poset.
    12801466        This list is computed by all left rotate possible on
    12811467        its nodes.
    12821468
    class BinaryTree(AbstractClonableTree, C 
    13221508
    13231509    def tamari_smaller(self):
    13241510        r"""
    1325         The list of all trees smaller than ``self``.
     1511        The list of all trees smaller or equal to ``self`` in the Tamari
     1512        order.
    13261513        This is the transitive ideal of its predecessors.
    13271514
    13281515        The tree::
    class BinaryTree(AbstractClonableTree, C 
    13331520            |  / \     /  |
    13341521            | o   o   o   |
    13351522
    1336         has these trees smaller than it::
     1523        has these trees smaller or equal to it::
    13371524
    13381525            |    __o__  ,       _o_  ,        o ,         o,         o,           o |
    13391526            |   /     \        /   \         /           /          /            /  |
    class BinaryTree(AbstractClonableTree, C 
    13641551
    13651552    def tamari_succ(self):
    13661553        r"""
    1367         Compute the list of successors of ``self`` in the tamari poset.
    1368         There is the list of all trees obtains by a right rotate of
     1554        Compute the list of successors of ``self`` in the Tamari poset.
     1555        There is the list of all trees obtained by a right rotate of
    13691556        one of its nodes.
    13701557
    1371         The list of successor of::
     1558        The list of successors of::
    13721559
    13731560            |     __o__   |
    13741561            |    /     \  |
    class BinaryTree(AbstractClonableTree, C 
    13931580            [[[[., .], .], .], .]
    13941581            sage: b.tamari_succ()
    13951582            [[[[., .], .], [., .]], [[[., .], [., .]], .], [[[., [., .]], .], .]]
     1583
     1584            sage: b = B([])
     1585            sage: b.tamari_succ()
     1586            []
     1587
     1588            sage: b = B([[],[]])
     1589            sage: b.tamari_succ()
     1590            [[., [., [., .]]]]
    13961591        """
    13971592        res = []
    13981593        if self.is_empty():
    class BinaryTree(AbstractClonableTree, C 
    14041599             [B([g, self[1]]) for g in self[0].tamari_succ()] +
    14051600             [B([self[0], d]) for d in self[1].tamari_succ()])
    14061601
    1407     def q_hook_length_formula(self):
     1602    def q_hook_length_fraction(self, q=None, q_factor=False):
    14081603        r"""
    1409         Compute the ``q-hook length formula`` of a binary tree.
    1410 
    1411         If `q=1` then ``q-hook length formula`` computes the number of
    1412         permutations such that the shape of binary search tree associated is
    1413         *self*.
     1604        Compute the ``q``-hook length fraction of the binary tree ``self``,
     1605        with an additional "q-factor" if desired.
     1606
     1607        If `T` is a (plane) binary tree and `q` is a polynomial
     1608        indeterminate over some ring, then the `q`-hook length fraction
     1609        `h_{q} (T)` of `T` is defined by
    14141610
    14151611        .. MATH::
    14161612
    1417             f_{q} (T) = \frac{[\lvert T \rvert]_q!}{\prod_{t \in T}
    1418             q^{right(t)} \lvert t \rvert]_q}
    1419 
    1420         where `\lvert T \rvert` is the node number of `T`, `t \in T` the set
    1421         of all subtrees of `T`, and `right(t)` the number of nodes of the
    1422         right subtree of `t`.
    1423 
    1424         There are `20` permutations which give a binary tree of the
     1613            h_{q} (T)
     1614            = \frac{[\lvert T \rvert]_q!}{\prod_{t \in T}
     1615            [\lvert T_t \rvert]_q},
     1616
     1617        where the product ranges over all nodes `t` of `T`, where `T_t`
     1618        denotes the subtree of `T` consisting of `t` and its all
     1619        descendants, and where for every tree `S`, we denote by
     1620        `\lvert S \rvert` the number of nodes of `S`. While this
     1621        definition only shows that `h_{q} (T)` is a rational function
     1622        in `T`, it is in fact easy to show that `h_{q} (T)` is
     1623        actually a polynomial in `T`, and thus makes sense when any
     1624        element of a commutative ring is substituted for `q`.
     1625        This can also be explicitly seen from the following recursive
     1626        formula for `h_{q} (T)`:
     1627
     1628        .. MATH::
     1629
     1630            h_{q} (T)
     1631            = \binom{ \lvert T \rvert - 1 }{ \lvert T_1 \rvert }_q
     1632            h_{q} (T_1) h_{q} (T_2),
     1633
     1634        where `T` is any nonempty binary tree, and `T_1` and `T_2` are
     1635        the two children trees of the root of `T`, and where
     1636        `\binom{a}{b}_q` denotes a `q`-binomial coefficient.
     1637
     1638        A variation of the `q`-hook length fraction is the following
     1639        "`q`-hook length fraction with `q`-factor":
     1640
     1641        .. MATH::
     1642
     1643            f_{q} (T)
     1644            = h_{q} (T) \cdot
     1645            \prod_{t \in T} q^{\lvert T_{\mathrm{right}(t)} \rvert},
     1646
     1647        where for every node `t`, we denote by `\mathrm{right}(t)` the
     1648        right child of `t`.
     1649        This `f_{q} (T)` differs from `h_{q} (T)` only in a
     1650        multiplicative factor, which is a power of `q`.
     1651
     1652        When `q = 1`, both `f_{q} (T)` and `h_{q} (T)` equal the number
     1653        of permutations whose binary search tree (see [HNT05]_ for the
     1654        definition) is `T` (after dropping the labels). For example,
     1655        there are `20` permutations which give a binary tree of the
    14251656        following shape::
    14261657
    14271658            |     __o__   |
    class BinaryTree(AbstractClonableTree, C 
    14301661            |  / \     /  |
    14311662            | o   o   o   |
    14321663
    1433         by the binary search insertion algorithm.
    1434 
    1435         TESTS::
     1664        by the binary search insertion algorithm, in accordance with
     1665        the fact that this tree satisfies `f_{1} (T) = 20`.
     1666
     1667        When `q` is considered as a polynomial indeterminate,
     1668        `f_{q} (T)` is the generating function for all permutations
     1669        whose binary search tree is `T` (after dropping the labels)
     1670        with respect to the number of inversions (i. e., the Coxeter
     1671        length) of the permutations.
     1672
     1673        Objects similar to `h_{q} (T)` also make sense for general
     1674        ordered forests (rather than just binary trees), see e. g.
     1675        [BW88]_, Theorem 9.1.
     1676
     1677        INPUT:
     1678
     1679        - ``q`` -- a ring element which is to be substituted as `q`
     1680          into the `q`-hook length fraction (by default, this is
     1681          set to be the indeterminate `q` in the polynomial ring
     1682          `\ZZ[q]`)
     1683
     1684        - ``q_factor`` -- a Boolean (default: ``False``) which
     1685          determines whether to compute `h_{q} (T)` or to
     1686          compute `f_{q} (T)` (namely, `h_{q} (T)` is obtained when
     1687          ``q_factor == False``, and `f_{q} (T)` is obtained when
     1688          ``q_factor == True``)
     1689
     1690        REFERENCES:
     1691
     1692        .. [BW88] Anders Bjoerner, Michelle L. Wachs,
     1693           *Generalized quotients in Coxeter groups*.
     1694           Transactions of the American Mathematical Society,
     1695           vol. 308, no. 1, July 1988.
     1696           http://www.ams.org/journals/tran/1988-308-01/S0002-9947-1988-0946427-X/S0002-9947-1988-0946427-X.pdf
     1697       
     1698        EXAMPLES:
     1699
     1700        Let us start with a simple example. Actually, let us start
     1701        with the easiest possible example -- the binary tree with
     1702        only one vertex (which is a leaf)::
     1703
     1704            sage: b = BinaryTree()
     1705            sage: b.q_hook_length_fraction()
     1706            1
     1707            sage: b.q_hook_length_fraction(q_factor=True)
     1708            1
     1709
     1710        Nothing different for a tree with one node and two leaves::
     1711
     1712            sage: b = BinaryTree([]); b
     1713            [., .]
     1714            sage: b.q_hook_length_fraction()
     1715            1
     1716            sage: b.q_hook_length_fraction(q_factor=True)
     1717            1
     1718
     1719        Let us get to a more interesting tree::
    14361720
    14371721            sage: b = BinaryTree([[[],[]],[[],None]]); b
    14381722            [[[., .], [., .]], [[., .], .]]
    1439             sage: b.q_hook_length_formula()(q=1)
     1723            sage: b.q_hook_length_fraction()(q=1)
    14401724            20
    1441             sage: BinaryTree([[],[]]).q_hook_length_formula()
    1442             (((q + 2)*q + 2)*q + 1)*q/((q + 1)*q + 1)
     1725            sage: b.q_hook_length_fraction()
     1726            q^7 + 2*q^6 + 3*q^5 + 4*q^4 + 4*q^3 + 3*q^2 + 2*q + 1
     1727            sage: b.q_hook_length_fraction(q_factor=True)
     1728            q^10 + 2*q^9 + 3*q^8 + 4*q^7 + 4*q^6 + 3*q^5 + 2*q^4 + q^3
     1729            sage: b.q_hook_length_fraction(q=2)
     1730            465
     1731            sage: b.q_hook_length_fraction(q=2, q_factor=True)
     1732            3720
     1733            sage: q = PolynomialRing(ZZ, 'q').gen()
     1734            sage: b.q_hook_length_fraction(q=q**2)
     1735            q^14 + 2*q^12 + 3*q^10 + 4*q^8 + 4*q^6 + 3*q^4 + 2*q^2 + 1
     1736
     1737        Let us check the fact that `f_{q} (T)` is the generating function
     1738        for all permutations whose binary search tree is `T` (after
     1739        dropping the labels) with respect to the number of inversions of
     1740        the permutations::
     1741
     1742            sage: def q_hook_length_fraction_2(T):
     1743            ....:     P = PolynomialRing(ZZ, 'q')
     1744            ....:     q = P.gen()
     1745            ....:     res = P.zero()
     1746            ....:     for w in T.sylvester_class():
     1747            ....:         res += q ** Permutation(w).length()
     1748            ....:     return res
     1749            sage: def test_genfun(i):
     1750            ....:     return all( q_hook_length_fraction_2(T)
     1751            ....:                 == T.q_hook_length_fraction(q_factor=True)
     1752            ....:                 for T in BinaryTrees(i) )
     1753            sage: test_genfun(4)
     1754            True
     1755            sage: test_genfun(7)  # long time
     1756            True
    14431757        """
    1444         from sage.combinat.q_analogues import q_factorial, q_int
    1445         from sage.symbolic.ring import SymbolicRing
    1446 
    1447         q = SymbolicRing().var('q')
    1448 
    1449         def product_of_subtrees(b):
    1450             if b.is_empty():
    1451                 return q ** 0
    1452             return (q ** (-b[0].node_number()) * q_int(b.node_number())) * \
    1453                 product_of_subtrees(b[0]) * product_of_subtrees(b[1])
    1454 
    1455         return q_factorial(self.node_number()) / product_of_subtrees(self)
     1758        from sage.combinat.q_analogues import q_binomial
     1759
     1760        if q is None:
     1761            from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
     1762            from sage.rings.integer_ring import ZZ
     1763            basering = PolynomialRing(ZZ, 'q')
     1764            q = basering.gen()
     1765        else:
     1766            basering = q.base_ring()
     1767
     1768        if q_factor:
     1769            def product_of_subtrees(b):
     1770                if b.is_empty():
     1771                    return basering.one()
     1772                b0 = b[0]
     1773                b1 = b[1]
     1774                return q_binomial(b.node_number() - 1, b0.node_number(), q=q) * \
     1775                    product_of_subtrees(b0) * product_of_subtrees(b1) * \
     1776                    q ** (b1.node_number())
     1777        else:
     1778            def product_of_subtrees(b):
     1779                if b.is_empty():
     1780                    return basering.one()
     1781                b0 = b[0]
     1782                b1 = b[1]
     1783                return q_binomial(b.node_number() - 1, b0.node_number(), q=q) * \
     1784                    product_of_subtrees(b0) * product_of_subtrees(b1)
     1785
     1786        return product_of_subtrees(self)
    14561787
    14571788    @combinatorial_map(name="Right rotate")
    14581789    def right_rotate(self):
    14591790        r"""
    1460         Right rotation operation of tree.
    1461 
    1462         The right rotation is defined by;:
     1791        Return the result of right rotation applied to the binary
     1792        tree ``self``.
     1793
     1794        Right rotation on binary trees is defined as follows:
     1795        Let `T` be a nonempty binary tree such that the left
     1796        child of the root of `T` is a node. Let `C` be the right
     1797        child of the root of `T`, and let `A` and `B` be the
     1798        left and right children of the left child of the root
     1799        of `T`. (Keep in mind that nodes of trees are identified
     1800        with the subtrees consisting of their descendants.)
     1801        Then, the right rotation of `T` is the nonempty binary
     1802        tree in which the left child of the root is `A`, whereas
     1803        the right child of the root is a node whose left and right
     1804        children are `B` and `C`. In pictures::
     1805
     1806            |     *                      *     |
     1807            |    / \                    / \    |
     1808            |   *   C -right-rotate->  A   *   |
     1809            |  / \                        / \  |
     1810            | A   B                      B   C |
     1811
     1812        where asterisks signify a single node each (but `A`, `B`
     1813        and `C` might be empty).
     1814
     1815        For example, ::
    14631816
    14641817            |     o                     _o_   |
    14651818            |    /                     /   \  |
    class BinaryTree(AbstractClonableTree, C 
    14751828            |  /     \                               \      |
    14761829            | o       o                               o     |
    14771830
     1831        Right rotation is the inverse operation to left rotation
     1832        (:meth:`left_rotate`).
     1833
     1834        The right rotation operation introduced here is the one defined
     1835        in Definition 2.1 of [CP12]_.
     1836
     1837        .. SEEALSO::
     1838
     1839            :meth:`left_rotate`
     1840
    14781841        EXAMPLES::
    14791842
    14801843            sage: b = BinaryTree([[[],[]], None]); ascii_art([b])
    class BinaryTree(AbstractClonableTree, C 
    14891852            [ o     o ]
    14901853            [      /  ]
    14911854            [     o   ]
    1492             sage: b = BinaryTree([[[[],None],[None,[]]], []]);ascii_art([b])
     1855            sage: b = BinaryTree([[[[],None],[None,[]]], []]); ascii_art([b])
    14931856            [       __o__   ]
    14941857            [      /     \  ]
    14951858            [     o       o ]
    class BinaryTree(AbstractClonableTree, C 
    15121875    @combinatorial_map(name="Left rotate")
    15131876    def left_rotate(self):
    15141877        r"""
    1515         Left rotation operation of tree.
    1516 
    1517         The left rotation is defined by;:
     1878        Return the result of left rotation applied to the binary
     1879        tree ``self``.
     1880
     1881        Left rotation on binary trees is defined as follows:
     1882        Let `T` be a nonempty binary tree such that the right
     1883        child of the root of `T` is a node. Let `A` be the left
     1884        child of the root of `T`, and let `B` and `C` be the
     1885        left and right children of the right child of the root
     1886        of `T`. (Keep in mind that nodes of trees are identified
     1887        with the subtrees consisting of their descendants.)
     1888        Then, the left rotation of `T` is the nonempty binary
     1889        tree in which the right child of the root is `C`, whereas
     1890        the left child of the root is a node whose left and right
     1891        children are `A` and `B`. In pictures::
     1892
     1893            |   *                        *   |
     1894            |  / \                      / \  |
     1895            | A   *  -left-rotate->    *   C |
     1896            |    / \                  / \    |
     1897            |   B   C                A   B   |
     1898
     1899        where asterisks signify a single node each (but `A`, `B`
     1900        and `C` might be empty).
     1901
     1902        For example, ::
    15181903
    15191904            |   _o_                        o |
    15201905            |  /   \                      /  |
    class BinaryTree(AbstractClonableTree, C 
    15321917            |                                 /     \  |
    15331918            |                                o       o |
    15341919
     1920        Left rotation is the inverse operation to right rotation
     1921        (:meth:`right_rotate`).
     1922
     1923        .. SEEALSO::
     1924
     1925            :meth:`right_rotate`
     1926
    15351927        EXAMPLES::
    15361928
    15371929            sage: b = BinaryTree([[],[[],None]]); ascii_art([b])
    class BinaryTree(AbstractClonableTree, C 
    15551947    @combinatorial_map(name="Over operation on Binary Trees")
    15561948    def over(self, bt):
    15571949        r"""
    1558         The ``over`` (`/`) operation defined by Loday-Ronco [LodayRonco]_.
     1950        Return ``self`` over ``bt``, where "over" is the ``over`` (`/`)
     1951        operation defined by Loday-Ronco [LodayRonco]_.
     1952
     1953        If `T` and `T'` are two binary trees, then `T` over `T'`
     1954        (written `T / T'`) is defined as the tree obtained by grafting
     1955        `T'` on the rightmost node of `T`. See section 4.5 of [HNT05]_.
     1956
     1957        .. TODO::
     1958
     1959            Fix this doc and figure out which of the different
     1960            (inconsistent?) notations to follow. I don't see the
     1961            "over" operation defined in [LodayRonco]_, although
     1962            [HNT05]_ pretends that it is defined there. In
     1963            [HNT05]_ the definition is somewhat vague about the
     1964            order of the operads. Loday and Ronco seem to define
     1965            "over" on page 2 of "Order structure on the algebra
     1966            of permutations and of planar binary trees", but
     1967            with a different choice of left/right.
    15591968
    15601969        This is defined by::
    15611970
    class BinaryTree(AbstractClonableTree, C 
    16792088
    16802089    def sylvester_class(self, left_to_right=False):
    16812090        r"""
    1682         Iterate the sylvester class corresponding to the binary tree.
    1683        
    1684         The sylvester class is the set of permutations corresponding to the
    1685         canonical binary search tree with same shape of ``self``.
    1686         See [HNT05]_ for more.
    1687        
    1688         For example the following has the permutations `(1,3,2)` and `(3,1,2)`
    1689         associated::
     2091        Iterate over the sylvester class corresponding to the binary tree
     2092        ``self``.
     2093
     2094        The sylvester class of a tree `T` is the set of permutations
     2095        `\sigma` whose binary search tree (a notion defined in [HNT05]_,
     2096        Definition 7) is `T` after forgetting the labels. This is an
     2097        equivalence class of the sylvester congruence (the congruence on
     2098        words which sets two words `uacvbw` and `ucavbw` congruent
     2099        whenever `a`, `b`, `c` are letters satisfying `a \leq b < c`, and
     2100        extends by transitivity) on the symmetric group.
     2101
     2102        For example the following tree's sylvester class consists of the
     2103        permutations `(1,3,2)` and `(3,1,2)`::
    16902104
    16912105            [   o   ]
    16922106            [  / \  ]
    16932107            [ o   o ]
    1694        
     2108
     2109        (only the nodes are drawn here).
     2110
     2111        The binary search tree of a word is constructed by an RSK-like
     2112        algorithm, in which the word is read from right to left. If a
     2113        left-to-right reading is to be employed instead, the
     2114        ``left_to_right`` optional keyword variable should be set to
     2115        ``True``.
     2116
    16952117        TESTS::
    1696        
     2118
    16972119            sage: list(BinaryTree([[],[]]).sylvester_class())
    16982120            [[1, 3, 2], [3, 1, 2]]
    16992121            sage: bt = BinaryTree([[[],None],[[],[]]])
    class BinaryTree(AbstractClonableTree, C 
    17182140             [6, 4, 1, 2, 5, 3],
    17192141             [6, 4, 1, 5, 2, 3],
    17202142             [6, 4, 5, 1, 2, 3]]
    1721             sage: len(l) == Integer(bt.q_hook_length_formula()(q=1))
     2143            sage: len(l) == Integer(bt.q_hook_length_fraction()(q=1))
    17222144            True
     2145
     2146        Border cases::
     2147
     2148            sage: list(BinaryTree().sylvester_class())
     2149            [[]]
     2150            sage: list(BinaryTree([]).sylvester_class())
     2151            [[1]]
    17232152        """
    17242153        if self.is_empty():
    17252154            yield []
    class BinaryTree(AbstractClonableTree, C 
    17432172
    17442173    def is_full(self):
    17452174        r"""
    1746         A full binary tree is a tree in which every node other than the leaves
    1747         has two children.
     2175        Return ``True`` if ``self`` is full, else return ``False``.
     2176
     2177        A full binary tree is a tree in which every node either has two
     2178        child nodes or has two child leaves.
    17482179
    17492180        This is also known as *proper binary tree* or *2-tree* or *strictly
    17502181        binary tree*.
    class BinaryTree(AbstractClonableTree, C 
    17902221
    17912222    def is_perfect(self):
    17922223        r"""
     2224        Return ``True`` if ``self`` is perfect, else return ``False``.
     2225
    17932226        A perfect binary tree is a full tree in which all leaves are at the
    17942227        same depth.
    17952228
    class BinaryTree(AbstractClonableTree, C 
    18362269
    18372270    def is_complete(self):
    18382271        r"""
     2272        Return ``True`` if ``self`` is complete, else return ``False``.
     2273
    18392274        A complete binary tree is a perfect binary tree except possibly in the
    18402275        last level.
    18412276
    class BinaryTree(AbstractClonableTree, C 
    18542289            |  / \     / \      |
    18552290            | o   o   o   o     |
    18562291
    1857         is not complet but the following ones are::
     2292        is not complete but the following ones are::
    18582293
    18592294            |     __o__          _o_            ___o___     |
    18602295            |    /     \        /   \          /       \    |
    class BinaryTree(AbstractClonableTree, C 
    18662301
    18672302        EXAMPLES::
    18682303
    1869 
    18702304            sage: lst = lambda i: filter(lambda bt: bt.is_complete(), BinaryTrees(i))
    18712305            sage: for i in range(9): ascii_art(lst(i)) # long time
    18722306            [  ]
    class BinaryTrees(UniqueRepresentation,  
    19822416            return BinaryTrees_all()
    19832417        else:
    19842418            if not (isinstance(n, (Integer, int)) and n >= 0):
    1985                 raise ValueError("n must be a non negative integer")
     2419                raise ValueError("n must be a nonnegative integer")
    19862420            return BinaryTrees_size(Integer(n))
    19872421
    19882422    @cached_method
    class BinaryTrees_size(BinaryTrees): 
    22512685
    22522686class LabelledBinaryTree(AbstractLabelledClonableTree, BinaryTree):
    22532687    """
    2254     The class of labelled binary tree
     2688    Labelled binary trees.
     2689
     2690    A labelled binary tree is a binary tree (see :class:`BinaryTree` for
     2691    the meaning of this) with a label assigned to each node. (The labels
     2692    need not be integers, nor are they required to be distinct. ``None``
     2693    can be used as a label.)
     2694
     2695    .. TODO::
     2696
     2697        Explain how to init these.
     2698
     2699        Maybe allow ``LabelledBinaryTree()`` syntax for
     2700        ``LabelledBinaryTree(None)`` (in analogy to ``BinaryTree``
     2701        class).
    22552702
    22562703    EXAMPLE::
    22572704
    class LabelledBinaryTree(AbstractLabelle 
    22822729    @lazy_class_attribute
    22832730    def _auto_parent(cls):
    22842731        """
    2285         The automatic parent of the element of this class
     2732        The automatic parent of the elements of this class.
    22862733
    22872734        When calling the constructor of an element of this class, one needs a
    22882735        parent. This class attribute specifies which parent is used.
    class LabelledBinaryTree(AbstractLabelle 
    23162763
    23172764    def binary_search_insert(self, letter):
    23182765        """
    2319         Insert a letter in a binary search tree
     2766        Return the result of inserting a letter ``letter`` into the
     2767        right strict binary search tree ``self``.
    23202768
    23212769        INPUT:
    23222770
    23232771        - ``letter`` -- any object comparable with the label of ``self``
    23242772
     2773        OUTPUT:
     2774
     2775        The right strict binary search tree ``self`` with ``letter``
     2776        inserted into it according to the binary search insertion
     2777        algorithm.
     2778
    23252779        .. NOTE:: ``self`` is supposed to be a binary search tree. No check is
    23262780                  performed.
    23272781
     2782        A right strict binary search tree is defined to be a labelled
     2783        binary tree such that for each node `n` with label `x`,
     2784        every descendant of the left child of `n` has a label `\leq x`,
     2785        and every descendant of the right child of `n` has a label
     2786        `> x`. (Here, only nodes count as descendants, and every node
     2787        counts as its own descendant too.)
     2788
     2789        .. TODO::
     2790
     2791            Explain the algorithm.
     2792
    23282793        EXAMPLES::
    23292794
    23302795            sage: LBT = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    23362801            3[1[., .], .]
    23372802            sage: res = LBT(None)
    23382803            sage: for i in [3,1,5,2,4,6]:
    2339             ...       res = res.binary_search_insert(i)
     2804            ....:     res = res.binary_search_insert(i)
    23402805            sage: res
    23412806            3[1[., 2[., .]], 5[4[., .], 6[., .]]]
    23422807        """
    class LabelledBinaryTree(AbstractLabelle 
    23532818
    23542819    def right_rotate(self):
    23552820        r"""
    2356         Right rotation operation of a tree.
    2357 
    2358         The right rotation of a tree is defined by::
     2821        Return the result of right rotation applied to the labelled
     2822        binary tree ``self``.
     2823
     2824        Right rotation on labelled binary trees is defined as
     2825        follows: Let `T` be a nonempty labelled binary tree such
     2826        that the left child of the root of `T` is a node. Let
     2827        `C` be the right child of the root of `T`, and let `A`
     2828        and `B` be the left and right children of the left child
     2829        of the root of `T`. (Keep in mind that nodes of trees are
     2830        identified with the subtrees consisting of their
     2831        descendants.) Furthermore, let `y` be the label at the
     2832        root of `T`, and `x` be the label at the left child of the
     2833        root of `T`.
     2834        Then, the right rotation of `T` is the nonempty labelled
     2835        binary tree in which the root is labelled `x`, the left
     2836        child of the root is `A`, whereas the right child of the
     2837        root is a node labelled `y` whose left and right children
     2838        are `B` and `C`. In pictures::
    23592839
    23602840            |     y                      x     |
    23612841            |    / \                    / \    |
    class LabelledBinaryTree(AbstractLabelle 
    23632843            |  / \                        / \  |
    23642844            | A   B                      B   C |
    23652845
     2846        Right rotation is the inverse operation to left rotation
     2847        (:meth:`left_rotate`).
     2848
    23662849        TESTS::
    23672850
    23682851            sage: LB = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    23792862
    23802863    def left_rotate(self):
    23812864        r"""
    2382         Left rotation operation of a tree.
    2383 
    2384         The left rotation of a tree is defined by::
     2865        Return the result of left rotation applied to the labelled
     2866        binary tree ``self``.
     2867
     2868        Left rotation on labelled binary trees is defined as
     2869        follows: Let `T` be a nonempty labelled binary tree such
     2870        that the right child of the root of `T` is a node. Let
     2871        `A` be the left child of the root of `T`, and let `B`
     2872        and `C` be the left and right children of the right child
     2873        of the root of `T`. (Keep in mind that nodes of trees are
     2874        identified with the subtrees consisting of their
     2875        descendants.) Furthermore, let `x` be the label at the
     2876        root of `T`, and `y` be the label at the right child of the
     2877        root of `T`.
     2878        Then, the left rotation of `T` is the nonempty labelled
     2879        binary tree in which the root is labelled `y`, the right
     2880        child of the root is `C`, whereas the left child of the
     2881        root is a node labelled `x` whose left and right children
     2882        are `A` and `B`. In pictures::
    23852883
    23862884           |     y                    x     |
    23872885           |    / \                  / \    |
    class LabelledBinaryTree(AbstractLabelle 
    23892887           |  / \                      / \  |
    23902888           | A   B                    B   C |
    23912889
     2890        Left rotation is the inverse operation to right rotation
     2891        (:meth:`right_rotate`).
     2892
    23922893        TESTS::
    23932894
    23942895            sage: LB = LabelledBinaryTree
    class LabelledBinaryTree(AbstractLabelle 
    24052906
    24062907    def heap_insert(self, l):
    24072908        r"""
    2408         Insert a letter in a binary heap (tree).
    2409 
    2410         Roughly, a binary heap will be a complete binary tree such that for
    2411         each nodes the label is greater or equals to the label of its children.
     2909        Return the result of inserting a letter ``l`` into the binary
     2910        heap (tree) ``self``.
     2911
     2912        Roughly, a binary heap will be a labelled complete binary tree
     2913        such that for each node the label is greater or equal to the
     2914        label of each of its children.
    24122915
    24132916        For example::
    24142917
    class LabelledBinaryTree(AbstractLabelle 
    24182921            |  / \      |
    24192922            | 3   4     |
    24202923
     2924        is a binary heap.
     2925
    24212926        INPUT:
    24222927
    24232928        - ``letter`` -- any object comparable with the label of ``self``
  • sage/combinat/ordered_tree.py

    diff --git a/sage/combinat/ordered_tree.py b/sage/combinat/ordered_tree.py
    a b from sage.combinat.combinatorial_map imp 
    2626
    2727class OrderedTree(AbstractClonableTree, ClonableList):
    2828    """
    29     The class for (ordered rooted) Trees
     29    The class of (ordered rooted) trees.
    3030
    31     An ordered tree is constructed from a node called the root on which one
     31    An ordered tree is constructed from a node, called the root, on which one
    3232    has grafted a possibly empty list of trees. There is a total order on the
    3333    children of a node which is given by the order of the elements in the
    34     list. Note that there is no empty ordered tree.
     34    list. Note that there is no empty ordered tree (so the smallest ordered
     35    tree consists of just one node).
    3536
    3637    INPUT:
    3738
    class OrderedTree(AbstractClonableTree,  
    6263        sage: tt1.__hash__() == tt2.__hash__()
    6364        True
    6465
    65     Trees are usually immutable. However they inherits from
    66     :class:`sage.structure.list_clone.ClonableList`. So that they can be
    67     modified using the clone protocol:
     66    Trees are usually immutable. However they inherit from
     67    :class:`sage.structure.list_clone.ClonableList`, so that they can be
     68    modified using the clone protocol. Let us now see what this means.
    6869
    69     Trying to modify a non mutable tree raises an error::
     70    Trying to modify a non-mutable tree raises an error::
    7071
    7172        sage: tt1[1] = tt2
    7273        Traceback (most recent call last):
    class OrderedTree(AbstractClonableTree,  
    7677    Here is the correct way to do it::
    7778
    7879        sage: with tt2.clone() as tt2:
    79         ...    tt2[1] = tt1
     80        ....:     tt2[1] = tt1
    8081        sage: tt2
    8182        [[], [[], [[], []], [[], []]], [[], []]]
    8283
    8384    It is also possible to append a child to a tree::
    8485
    8586        sage: with tt2.clone() as tt3:
    86         ...    tt3.append(OrderedTree([]))
     87        ....:     tt3.append(OrderedTree([]))
    8788        sage: tt3
    8889        [[], [[], [[], []], [[], []]], [[], []], []]
    8990
    9091    Or to insert a child in a tree::
    9192
    9293        sage: with tt2.clone() as tt3:
    93         ...    tt3.insert(2, OrderedTree([]))
     94        ....:     tt3.insert(2, OrderedTree([]))
    9495        sage: tt3
    9596        [[], [[], [[], []], [[], []]], [], [[], []]]
    9697
    class OrderedTree(AbstractClonableTree,  
    108109
    109110        sage: tt1bis = OrderedTree(tt1)
    110111        sage: with tt1.clone() as tt1:
    111         ...    tt1[1] = tt1bis
     112        ....:     tt1[1] = tt1bis
    112113        sage: tt1
    113114        [[], [[], [[], []], [[], []]], [[], []]]
    114115        sage: tt1 == tt2
    class OrderedTree(AbstractClonableTree,  
    159160    Check that the hash value is correctly updated after modification::
    160161
    161162        sage: with tt2.clone() as tt2:
    162         ...    tt2[1,1] = tt1
     163        ....:     tt2[1,1] = tt1
    163164        sage: tt1.__hash__() == tt2.__hash__()
    164165        False
    165166    """
    class OrderedTree(AbstractClonableTree,  
    246247
    247248    def is_empty(self):
    248249        """
    249         Return if ``self`` is the empty tree
     250        Return if ``self`` is the empty tree.
    250251
    251         For ordered trees, returns always ``False``
     252        For ordered trees, returns always ``False``.
    252253
    253254        .. NOTE:: this is different from ``bool(t)`` which returns whether
    254255                  ``t`` has some child or not.
  • sage/misc/latex.py

    diff --git a/sage/misc/latex.py b/sage/misc/latex.py
    a b def latex_extra_preamble(): 
    605605        sage: from sage.misc.latex import latex_extra_preamble
    606606        sage: print latex_extra_preamble()
    607607        ...
     608        \usepackage{tikz}
     609        <BLANKLINE>
    608610        \newcommand{\ZZ}{\Bold{Z}}
    609611        \newcommand{\NN}{\Bold{N}}
    610612        \newcommand{\RR}{\Bold{R}}