Ticket #14063: trac_14063-remove_cc_compositions-ts.patch

File trac_14063-remove_cc_compositions-ts.patch, 55.3 KB (added by tscrim, 7 years ago)

Fixed docstrings

  • sage/combinat/composition.py

    # HG changeset patch
    # User Travis Scrimshaw <tscrim@ucdavis.edu>
    # Date 1361280404 28800
    # Node ID a963fa24217ffd1f11ce84a68f8fd33ba72792fc
    # Parent b9dca1a217f9a12d1a87974164725bf158937c1f
    Trac #14063 - Removed CombinatorialClass from Compositions.
    
    diff --git a/sage/combinat/composition.py b/sage/combinat/composition.py
    a b  
    1 """
     1r"""
    22Integer compositions
    33
    44A composition `c` of a nonnegative integer `n` is a list of positive integers
    AUTHORS: 
    1919
    2020- Mike Hansen, Nicolas M. Thiery
    2121- MuPAD-Combinat developers (algorithms and design inspiration)
     22- Travis Scrimshaw (2013-02-03): Removed ``CombinatorialClass``
    2223"""
    2324#*****************************************************************************
    2425#       Copyright (C) 2007 Mike Hansen       <mhansen@gmail.com>
    AUTHORS: 
    2930#*****************************************************************************
    3031
    3132from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
     33from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
     34from sage.structure.unique_representation import UniqueRepresentation
    3235from sage.structure.parent import Parent
     36from sage.structure.element import Element
     37from sage.misc.classcall_metaclass import ClasscallMetaclass
    3338from sage.misc.superseded import deprecated_function_alias
     39from sage.rings.all import ZZ
    3440import sage.combinat.skew_partition
    35 from combinat import CombinatorialClass, CombinatorialObject, InfiniteAbstractCombinatorialClass
     41from combinat import CombinatorialObject
    3642from cartesian_product import CartesianProduct
    3743from integer_list import IntegerListsLex
    3844import __builtin__
    3945from sage.rings.integer import Integer
    4046
    41 def Composition(co=None, descents=None, code=None, from_subset=None):
    42     """
     47class Composition(CombinatorialObject, Element):
     48    r"""
    4349    Integer compositions
    4450
    4551    A composition of a nonnegative integer `n` is a list
    46     `(i_1,\dots,i_k)` of positive integers with total sum `n`.
     52    `(i_1, \ldots, i_k)` of positive integers with total sum `n`.
    4753
    4854    EXAMPLES:
    4955
    def Composition(co=None, descents=None,  
    5864        [2, 3, 4]
    5965
    6066    You can also create a composition from its code. The *code* of
    61     a composition `[i_1, i_2, \dots, i_k]` of `n` is a list of length `n`
     67    a composition `(i_1, i_2, \ldots, i_k)` of `n` is a list of length `n`
    6268    that consists of a `1` followed by `i_1-1` zeros, then a `1` followed
    6369    by `i_2-1` zeros, and so on.
    6470
    def Composition(co=None, descents=None,  
    7480        [3, 1, 2, 3, 5]
    7581
    7682    You can also create the composition of `n` corresponding to a subset of
    77     `\{1, 2, \dots, n-1\}` under the bijection that maps the composition
    78     `[i_1, i_2, \dots, i_k]` of `n` to the subset
    79     `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \dots, i_1 + \cdots + i_{k-1}\}`
     83    `\{1, 2, \ldots, n-1\}` under the bijection that maps the composition
     84    `(i_1, i_2, \ldots, i_k)` of `n` to the subset
     85    `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \ldots, i_1 + \cdots + i_{k-1}\}`
    8086    (see :meth:`to_subset`)::
    8187
    8288        sage: Composition(from_subset=({1, 2, 4}, 5))
    def Composition(co=None, descents=None,  
    8490        sage: Composition([1, 1, 2, 1]).to_subset()
    8591        {1, 2, 4}
    8692
    87     The following notation equivalently specifies the composition from the set
    88     `\{i_1 - 1, i_1 + i_2 - 1, i_1 + i_2 + i_3 - 1, \dots, i_1 + \cdots
     93    The following notation equivalently specifies the composition from the
     94    set `\{i_1 - 1, i_1 + i_2 - 1, i_1 + i_2 + i_3 - 1, \dots, i_1 + \cdots
    8995    + i_{k-1} - 1, n-1\}` or `\{i_1 - 1, i_1 + i_2 - 1, i_1 + i_2 + i_3
    9096    - 1, \dots, i_1 + \cdots + i_{k-1} - 1\}` and `n`. This provides
    9197    compatibility with Python's `0`-indexing.
    def Composition(co=None, descents=None,  
    100106        [1, 1, 2, 1]
    101107        sage: Composition(descents=({0,1,3},5))
    102108        [1, 1, 2, 1]
     109    """
     110    __metaclass__ = ClasscallMetaclass
    103111
    104     """
    105     if descents is not None:
    106         if isinstance(descents, tuple):
    107             return from_descents(descents[0], nps=descents[1])
    108         else:
    109             return from_descents(descents)
    110     elif code is not None:
    111         return from_code(code)
    112     elif from_subset is not None:
    113         return composition_from_subset(*from_subset)
    114     elif isinstance(co, Composition_class):
    115         return co
    116     else:
    117         co = list(co)
    118         assert(co in Compositions())
    119         #raise ValueError, "invalid composition"
    120         return Composition_class(co)
    121 
    122 class Composition_class(CombinatorialObject):
    123     __doc__ = Composition.__doc__
    124 
    125     def parent(self):
     112    @staticmethod
     113    def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=None):
    126114        """
    127         Returns the combinatorial class of compositions.
     115        This constructs a list from optional arguments and delegates the
     116        construction of a :class:`Composition` to the ``element_class()`` call
     117        of the appropriate parent.
    128118
    129119        EXAMPLES::
    130120
    131             sage: Composition([3,2,1]).parent()
    132             Compositions of non-negative integers
     121            sage: Composition([3,2,1])
     122            [3, 2, 1]
     123            sage: Composition(from_subset=({1, 2, 4}, 5))
     124            [1, 1, 2, 1]
     125            sage: Composition(descents=[1,0,4,8,11])
     126            [1, 1, 3, 4, 3]
     127            sage: Composition([4,1,2,3,5]).to_code()
     128            [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
     129            sage: Composition(code=_)
     130            [4, 1, 2, 3, 5]
    133131        """
    134         return Compositions()
     132        if descents is not None:
     133            if isinstance(descents, tuple):
     134                return Compositions().from_descents(descents[0], nps=descents[1])
     135            else:
     136                return Compositions().from_descents(descents)
     137        elif code is not None:
     138            return Compositions().from_code(code)
     139        elif from_subset is not None:
     140            return Compositions().from_subset(*from_subset)
     141        elif isinstance(co, Composition):
     142            return co
     143        else:
     144            return Compositions()(list(co))
     145
     146    def __init__(self, parent, lst):
     147        """
     148        Initialize ``self``.
     149
     150        EXAMPLES::
     151
     152            sage: C = Composition([3,1,2])
     153            sage: TestSuite(C).run()
     154        """
     155        CombinatorialObject.__init__(self, lst)
     156        Element.__init__(self, parent)
     157
     158    def __setstate__(self, state):
     159        r"""
     160        In order to maintain backwards compatibility and be able to unpickle a
     161        old pickle from ``Partition_class`` we have to override the default
     162        ``__setstate__``.
     163
     164        EXAMPLES::
     165
     166            sage: loads("x\x9ck`J.NLO\xd5K\xce\xcfM\xca\xccK,\x011\n\xf2\x8b3K2\xf3\xf3\xb8\x9c\x11\xec\xf8\xe4\x9c\xc4\xe2b\xaeBF\xcd\xc6B\xa6\xdaBf\x8dP\xd6\xf8\x8c\xc4\xe2\x8cB\x16? +'\xb3\xb8\xa4\x905\xb6\x90M\x03bZQf^z\xb1^f^Ijzj\x11Wnbvj<\x8cS\xc8\x1e\xcah\xd8\x1aT\xc8\x91\x01d\x18\x01\x19\x9c\x19P\x11\xae\xd4\xd2$=\x00eW0g")
     167            [1, 2, 1]
     168            sage: loads(dumps( Composition([1,2,1]) ))  # indirect doctest
     169            [1, 2, 1]
     170        """
     171        if isinstance(state, dict):   # for old pickles from Composition_class
     172            self._set_parent(Compositions())
     173            self.__dict__ = state
     174        else:
     175            self._set_parent(state[0])
     176            self.__dict__ = state[1]
    135177
    136178    def conjugate(self):
    137179        r"""
    class Composition_class(CombinatorialObj 
    155197            cocjg += [i+1 for _ in range(0, (coofcp[n-i-1]-coofcp[n-i-2]))]
    156198        cocjg += [n for j in range(coofcp[0])]
    157199
    158         return Composition([cocjg[0]] + [cocjg[i]-cocjg[i-1]+1 for i in range(1,len(cocjg)) ])
     200        return self.parent()([cocjg[0]] + [cocjg[i]-cocjg[i-1]+1 for i in range(1,len(cocjg))])
    159201
    160202    def reversed(self):
    161203        """
    162         Returns the reverse of the composition.
     204        Return the reverse composition of ``self``.
    163205
    164206        EXAMPLES::
    165207
    166208            sage: Composition([1, 1, 3, 1, 2, 1, 3]).reversed()
    167209            [3, 1, 2, 1, 3, 1, 1]
    168210        """
    169         return Composition(reversed(self))
    170 
     211        return self.parent()(reversed(self))
    171212
    172213    def complement(self):
    173214        """
    174         Returns the complement of the composition co. The complement is the
    175         reverse of co's conjugate composition.
     215        Return the complement composition of ``self``. The complement is the
     216        reverse of the conjugate composition of ``self``.
    176217
    177218        EXAMPLES::
    178219
    class Composition_class(CombinatorialObj 
    183224        """
    184225        return self.conjugate().reversed()
    185226
    186 
    187227    def __add__(self, other):
    188228        """
    189         Returns the concatenation of two compositions.
     229        Return the concatenation of two compositions.
    190230
    191231        EXAMPLES::
    192232
    class Composition_class(CombinatorialObj 
    202242
    203243    def size(self):
    204244        """
    205         Returns the size of the composition, that is the sum of its parts.
     245        Return the size of ``self``, that is the sum of its parts.
    206246
    207247        EXAMPLES::
    208248
    class Composition_class(CombinatorialObj 
    214254    @staticmethod
    215255    def sum(compositions):
    216256        """
    217         Returns the concatenation of the given compositions.
     257        Return the concatenation of the given compositions.
    218258
    219259        INPUT:
    220260
    class Composition_class(CombinatorialObj 
    222262
    223263        EXAMPLES::
    224264
    225             sage: sage.combinat.composition.Composition_class.sum([Composition([1, 1, 3]), Composition([4, 1, 2]), Composition([3,1])])
     265            sage: Composition.sum([Composition([1, 1, 3]), Composition([4, 1, 2]), Composition([3,1])])
    226266            [1, 1, 3, 4, 1, 2, 3, 1]
    227267
    228268        Any iterable can be provided as input::
    229269
    230             sage: sage.combinat.composition.Composition_class.sum([Composition([i,i]) for i in [4,1,3]])
     270            sage: Composition.sum([Composition([i,i]) for i in [4,1,3]])
    231271            [4, 4, 1, 1, 3, 3]
    232272
    233273        Empty inputs are handled gracefully::
    234274
    235             sage: sage.combinat.composition.Composition_class.sum([]) == Composition([])
     275            sage: Composition.sum([]) == Composition([])
    236276            True
    237277        """
    238278        return sum(compositions, Composition([]))
    239279
    240280    def finer(self):
    241281        """
    242         Returns the set of compositions which are finer than self.
     282        Return the set of compositions which are finer than ``self``.
    243283
    244284        EXAMPLES::
    245285
    class Composition_class(CombinatorialObj 
    249289            sage: list(C)
    250290            [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 1, 1], [1, 2, 2], [2, 1, 1, 1], [2, 1, 2], [3, 1, 1], [3, 2]]
    251291        """
    252         return CartesianProduct(*[Compositions(i) for i in self]).map(Composition_class.sum)
     292        return CartesianProduct(*[Compositions(i) for i in self]).map(Composition.sum)
    253293
    254294    def is_finer(self, co2):
    255295        """
    256         Returns True if the composition self is finer than the composition
    257         co2; otherwise, it returns False.
     296        Return ``True`` if the composition ``self`` is finer than the
     297        composition ``co2``; otherwise, it returns ``False``.
    258298
    259299        EXAMPLES::
    260300
    class Composition_class(CombinatorialObj 
    269309        """
    270310        co1 = self
    271311        if sum(co1) != sum(co2):
    272             #Error: compositions are not of the same size
    273             raise ValueError, "compositions self (= %s) and co2 (= %s) must be of the same size"%(self, co2)
    274 
     312            raise ValueError("compositions self (= %s) and co2 (= %s) must be of the same size"%(self, co2))
    275313
    276314        sum1 = 0
    277315        sum2 = 0
    class Composition_class(CombinatorialObj 
    287325        return True
    288326
    289327    def fatten(self, grouping):
    290         """
    291         Returns the composition fatter than self, obtained by grouping
     328        r"""
     329        Return the composition fatter than ``self``, obtained by grouping
    292330        together consecutive parts according to grouping.
    293331
    294332        INPUT:
    295333
    296         - ``grouping`` -- a composition whose sum is the length of self
     334        - ``grouping`` -- a composition whose sum is the length of ``self``
    297335
    298336        EXAMPLES:
    299337
    class Composition_class(CombinatorialObj 
    301339
    302340            sage: c = Composition([4,5,2,7,1])
    303341
    304         With `grouping = (1,\dots,1)`, `c` is left unchanged::
     342        With ``grouping`` equal to `(1, \ldots, 1)`, `c` is left unchanged::
    305343
    306344            sage: c.fatten(Composition([1,1,1,1,1]))
    307345            [4, 5, 2, 7, 1]
    308346
    309         With `grouping = (5)`, this yields the coarser composition above `c`::
     347        With ``grouping`` equal to `(\ell)` where `\ell` is the length of
     348        ``self``, this yields the coarser composition above `c`::
    310349
    311350            sage: c.fatten(Composition([5]))
    312351            [19]
    class Composition_class(CombinatorialObj 
    331370        for i in range(len(grouping)):
    332371            result[i] = sum(self[j:j+grouping[i]])
    333372            j += grouping[i]
    334         return Composition_class(result)
     373        return Composition(result)
    335374
    336375    def fatter(self):
    337376        """
    338         Returns the set of compositions which are fatter than self.
     377        Return the set of compositions which are fatter than ``self``.
    339378
    340         Complexity for generation: `O(size(c))` memory, `O(size(result))` time
     379        Complexity for generation: `O(|c|)` memory, `O(|r|)` time where `|c|`
     380        is the size of ``self`` and `r` is the result.
    341381
    342382        EXAMPLES::
    343383
    class Composition_class(CombinatorialObj 
    360400
    361401    def refinement_splitting(self, J):
    362402        r"""
    363         Returns the refinement splitting of ``I=self`` according to ``J``.
     403        Return the refinement splitting of ``self`` according to ``J``.
    364404
    365405        INPUT:
    366406
    367         - `J:=(J_1,\dots,J_m)` -- a composition such that `I` is finer than `J`
     407        - ``J`` -- A composition such that ``I`` is finer than ``J``
    368408
    369409        OUTPUT:
    370410
    class Composition_class(CombinatorialObj 
    372412          obtained by splitting `I`, such that
    373413          `|I^{(p)}| = J_p` for all `p = 1, \ldots, m`.
    374414
    375         .. SEEALSO:: :meth:`refinement_splitting_lengths`
     415        .. SEEALSO::
     416
     417            :meth:`refinement_splitting_lengths`
    376418
    377419        EXAMPLES::
    378420
    class Composition_class(CombinatorialObj 
    392434        I = self
    393435        if sum(I) != sum(J):
    394436            #Error: compositions are not of the same size
    395             raise ValueError, "compositions self (= %s) and J (= %s) must be of the same size"%(I, J)
     437            raise ValueError("compositions self (= %s) and J (= %s) must be of the same size"%(I, J))
    396438        sum1 = 0
    397439        sum2 = 0
    398440        i1 = -1
    class Composition_class(CombinatorialObj 
    405447                new_comp.append(I[i1])
    406448                sum1 += new_comp[-1]
    407449            if sum1 > sum2:
    408                 raise ValueError, \
    409                     "composition J (= %s) does not refine self (= %s)"%(I, J)
     450                raise ValueError("composition J (= %s) does not refine self (= %s)"%(I, J))
    410451            decomp.append(Composition(new_comp))
    411452        return decomp
    412453
    413454    def refinement_splitting_lengths(self, J):
    414455        """
    415         Returns the lengths of the compositions in the refinement splitting of ``I=self`` according to ``J``.
     456        Return the lengths of the compositions in the refinement splitting of
     457        ``I=self`` according to ``J``.
    416458
    417         .. SEEALSO:: :meth:`refinement_splitting` for the definition of refinement splitting
     459        .. SEEALSO::
     460
     461            :meth:`refinement_splitting` for the definition of refinement splitting
    418462
    419463        EXAMPLES::
    420464
    class Composition_class(CombinatorialObj 
    437481
    438482    def major_index(self):
    439483        """
    440         Returns the major index of the composition co. The major index is
     484        Return the major index of ``self``. The major index is
    441485        defined as the sum of the descents.
    442486
    443487        EXAMPLES::
    class Composition_class(CombinatorialObj 
    452496        else:
    453497            return sum([(lv-(i+1))*co[i] for i in range(lv)])
    454498
    455 
    456499    def to_code(self):
    457500        """
    458         Returns the code of the composition self. The code of a composition
    459         is a list of length self.size() of 1s and 0s such that there is a 1
     501        Return the code of the composition ``self``. The code of a composition
     502        is a list of length ``self.size()`` of 1s and 0s such that there is a 1
    460503        wherever a new part starts.
    461504
    462505        EXAMPLES::
    class Composition_class(CombinatorialObj 
    464507            sage: Composition([4,1,2,3,5]).to_code()
    465508            [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
    466509        """
    467 
    468510        if self == []:
    469511            return [0]
    470512
    class Composition_class(CombinatorialObj 
    479521        The partial sums of the sequence defined by the entries of the
    480522        composition.
    481523
    482         If `I = [i_1, \dots, i_m]` is a composition, then the partial sums of
     524        If `I = (i_1, \ldots, i_m)` is a composition, then the partial sums of
    483525        the entries of the composition are
    484         `[i_1, i_1 + i_2, \dots, i_1 + i_2 + \cdots + i_{m}]`.
     526        `[i_1, i_1 + i_2, \ldots, i_1 + i_2 + \cdots + i_{m}]`.
    485527
    486528        INPUT:
    487529
    488530        - ``final`` -- (default: ``True``) whether or not to include the final
    489531          partial sum, which is always the size of the composition.
    490532
    491         .. SEEALSO:: :meth:`to_subset`
     533        .. SEEALSO::
     534
     535            :meth:`to_subset`
    492536
    493537        EXAMPLES::
    494538
    495539            sage: Composition([1,1,3,1,2,1,3]).partial_sums()
    496540            [1, 2, 5, 6, 8, 9, 12]
    497541
    498         With ``final=False``, the last partial sum is not included::
     542        With ``final = False``, the last partial sum is not included::
    499543
    500544            sage: Composition([1,1,3,1,2,1,3]).partial_sums(final=False)
    501545            [1, 2, 5, 6, 8, 9]
    class Composition_class(CombinatorialObj 
    513557    def to_subset(self, final=False):
    514558        r"""
    515559        The subset corresponding to ``self`` under the bijection (see below)
    516         between compositions of `n` and subsets of `\{1, 2, \dots, n-1\}`.
     560        between compositions of `n` and subsets of `\{1, 2, \ldots, n-1\}`.
    517561
    518         The bijection maps a composition `[i_1, \dots, i_k]` of `n` to
    519         `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \dots, i_1 + \cdots + i_{k-1}\}`.
     562        The bijection maps a composition `(i_1, \ldots, i_k)` of `n` to
     563        `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \ldots, i_1 + \cdots + i_{k-1}\}`.
    520564
    521565        INPUT:
    522566
    523567        - ``final`` -- (default: ``False``) whether or not to include the final
    524568          partial sum, which is always the size of the composition.
    525569
    526         .. SEEALSO:: :meth:`partial_sums`
     570        .. SEEALSO::
     571
     572            :meth:`partial_sums`
    527573
    528574        EXAMPLES::
    529575
    class Composition_class(CombinatorialObj 
    566612        through the original implementation was broken (it gave the wrong
    567613        answer). The same information can be found in :meth:`partial_sums`.
    568614
    569         .. SEEALSO:: :meth:`partial_sums`
     615        .. SEEALSO::
     616
     617            :meth:`partial_sums`
    570618
    571619        INPUT:
    572620
    573         - ``self`` -- a composition
    574         - ``final_descent`` -- (Default: False) a boolean integer
     621        - ``final_descent`` -- (Default: ``False``) a boolean integer
    575622
    576623        OUTPUT:
    577624
    578625        - Returns the list of partial sums of ``self`` with each part
    579626          subtracted by `1`. This includes the sum of all entries when
    580           ``final_descent`` is true.
     627          ``final_descent`` is ``True``.
    581628
    582629        EXAMPLES::
    583630
    class Composition_class(CombinatorialObj 
    591638
    592639    def peaks(self):
    593640        """
    594         Returns a list of the peaks of the composition self. The
     641        Return a list of the peaks of the composition ``self``. The
    595642        peaks of a composition are the descents which do not
    596643        immediately follow another descent.
    597644
    class Composition_class(CombinatorialObj 
    621668
    622669    def to_skew_partition(self, overlap=1):
    623670        """
    624         Returns the skew partition obtained from the composition co. The
     671        Return the skew partition obtained from ``self``. The
    625672        parameter overlap indicates the number of cells that are covered by
    626673        cells of the previous line.
    627674
    class Composition_class(CombinatorialObj 
    655702        r"""
    656703        The (overlapping) shuffles of ``self`` and ``other``.
    657704
    658         Suppose `I = [i_1, \dots, i_k]` and `J = [j_1, \dots, j_l]` are two
     705        Suppose `I = (i_1, \ldots, i_k)` and `J = (j_1, \ldots, j_l)` are two
    659706        compositions. A *shuffle* of `I` and `J` is a composition of length
    660707        `k + l` that contains both `I` and `J` as subsequences.
    661708
    class Composition_class(CombinatorialObj 
    669716        INPUT:
    670717
    671718        -  ``other`` -- composition
     719
    672720        -  ``overlap`` -- boolean (default: ``False``); if ``True``, the
    673721           overlapping shuffle product is returned.
    674722
    675723        OUTPUT:
    676724
    677         - enumerated set (allowing for mutliplicities)
     725        An enumerated set (allowing for mutliplicities)
    678726
    679727        EXAMPLES:
    680728
    class Composition_class(CombinatorialObj 
    724772
    725773##############################################################
    726774
    727 
    728 def Compositions(n=None, **kwargs):
     775class Compositions(Parent, UniqueRepresentation):
    729776    r"""
    730     Sets of integer Compositions.
     777    Set of integer compositions.
    731778
    732779    A composition `c` of a nonnegative integer `n` is a list of
    733780    positive integers with total sum `n`.
    734781
    735     See also: ``Composition``, ``Partitions``, ``IntegerVectors``
     782    .. SEEALSO::
     783
     784        - :class:`Composition`
     785        - :class:`Partitions`
     786        - :class:`IntegerVectors`
    736787
    737788    EXAMPLES:
    738789
    def Compositions(n=None, **kwargs): 
    743794
    744795    Here is the list of them::
    745796
    746         sage: list(Compositions(4))
     797        sage: Compositions(4).list()
    747798        [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]
    748799
    749800    You can use the ``.first()`` method to get the 'first' composition of
    def Compositions(n=None, **kwargs): 
    758809        sage: Compositions(4).next([1,1,2])
    759810        [1, 2, 1]
    760811
    761 
    762 
    763812    If `n` is not specified, this returns the combinatorial class of
    764813    all (non-negative) integer compositions::
    765814
    def Compositions(n=None, **kwargs): 
    772821        sage: [-2,3,1] in Compositions()
    773822        False
    774823
    775     If n is specified, it returns the class of compositions of n::
     824    If `n` is specified, it returns the class of compositions of `n`::
    776825
    777826        sage: Compositions(3)
    778827        Compositions of 3
    def Compositions(n=None, **kwargs): 
    803852
    804853    Note that the given constraints should be compatible::
    805854
    806         sage: [4,2] in Compositions(6, inner=[2,2], min_part=3) #
     855        sage: [4,2] in Compositions(6, inner=[2,2], min_part=3)
    807856        True
    808857
    809     The options length, min_length, and max_length can be used to set
    810     length constraints on the compositions. For example, the
     858    The options ``length``, ``min_length``, and ``max_length`` can be used
     859    to set length constraints on the compositions. For example, the
    811860    compositions of 4 of length equal to, at least, and at most 2 are
    812861    given by::
    813862
    def Compositions(n=None, **kwargs): 
    818867        sage: Compositions(4, max_length=2).list()
    819868        [[4], [3, 1], [2, 2], [1, 3]]
    820869
    821     Setting both min_length and max_length to the same value is
    822     equivalent to setting length to this value::
     870    Setting both ``min_length`` and ``max_length`` to the same value is
     871    equivalent to setting ``length`` to this value::
    823872
    824873        sage: Compositions(4, min_length=2, max_length=2).list()
    825874        [[3, 1], [2, 2], [1, 3]]
    826875
    827     The options inner and outer can be used to set part-by-part
     876    The options ``inner`` and ``outer`` can be used to set part-by-part
    828877    containment constraints. The list of compositions of 4 bounded
    829     above by [3,1,2] is given by::
     878    above by ``[3,1,2]`` is given by::
    830879
    831880        sage: list(Compositions(4, outer=[3,1,2]))
    832881        [[3, 1], [2, 1, 1], [1, 1, 2]]
    833882
    834     Outer sets max_length to the length of its argument. Moreover, the
    835     parts of outer may be infinite to clear the constraint on specific
     883    ``outer`` sets ``max_length`` to the length of its argument. Moreover, the
     884    parts of ``outer`` may be infinite to clear the constraint on specific
    836885    parts. This is the list of compositions of 4 of length at most 3
    837886    such that the first and third parts are at most 1::
    838887
    839         sage: list(Compositions(4, outer=[1,oo,1]))
     888        sage: Compositions(4, outer=[1,oo,1]).list()
    840889        [[1, 3], [1, 2, 1]]
    841890
    842     This is the list of compositions of 4 bounded below by [1,1,1]::
     891    This is the list of compositions of 4 bounded below by ``[1,1,1]``::
    843892
    844         sage: list(Compositions(4, inner=[1,1,1]))
     893        sage: Compositions(4, inner=[1,1,1]).list()
    845894        [[2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]
    846895
    847     The options min_slope and max_slope can be used to set constraints
    848     on the slope, that is the difference `p[i+1]-p[i]` of two
     896    The options ``min_slope`` and ``max_slope`` can be used to set constraints
     897    on the slope, that is the difference ``p[i+1]-p[i]`` of two
    849898    consecutive parts. The following is the list of weakly increasing
    850899    compositions of 4::
    851900
    def Compositions(n=None, **kwargs): 
    881930    results. It is up to the user to ensure that the inner and outer
    882931    compositions themselves satisfy the parts and slope constraints.
    883932
    884     Note that if you specify min_part=0, then the objects produced may
     933    Note that if you specify ``min_part=0``, then the objects produced may
    885934    have parts equal to zero. This violates the internal assumptions
    886     that the Composition class makes. Use at your own risk, or
     935    that the composition class makes. Use at your own risk, or
    887936    preferably consider using ``IntegerVectors`` instead::
    888937
    889         sage: list(Compositions(2, length=3, min_part=0))
     938        sage: Compositions(2, length=3, min_part=0).list()
    890939        doctest:... RuntimeWarning: Currently, setting min_part=0 produces Composition objects which violate internal assumptions.  Calling methods on these objects may produce errors or WRONG results!
    891940        [[2, 0, 0], [1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1], [0, 0, 2]]
    892941
    def Compositions(n=None, **kwargs): 
    894943        [[2, 0, 0], [1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1], [0, 0, 2]]
    895944
    896945    The generation algorithm is constant amortized time, and handled
    897     by the generic tool ``IntegerListsLex``.
     946    by the generic tool :class:`IntegerListsLex`.
    898947
    899948    TESTS::
    900949
    def Compositions(n=None, **kwargs): 
    905954        sage: Compositions(6, min_part=2, length=3)
    906955        Compositions of the integer 6 satisfying constraints length=3, min_part=2
    907956
    908 
    909957        sage: [2, 1] in Compositions(3, length=2)
    910958        True
    911959        sage: [2,1,2] in Compositions(5, min_part=1)
    def Compositions(n=None, **kwargs): 
    9551003        sage: Compositions(5, max_slope=1, min_slope=-2, min_length=2, max_length=4, outer=[2,5,2]).list()
    9561004        [[2, 3], [2, 2, 1], [2, 1, 2], [1, 2, 2]]
    9571005    """
    958     if n is None:
    959         assert(len(kwargs) == 0)
    960         return Compositions_all()
    961     else:
    962         if len(kwargs) == 0:
    963             if isinstance(n, (int,Integer)):
    964                 return Compositions_n(n)
     1006    @staticmethod
     1007    def __classcall_private__(self, n=None, **kwargs):
     1008        """
     1009        Return the correct parent based upon the input.
     1010
     1011        EXAMPLES::
     1012
     1013            sage: C = Compositions(3)
     1014            sage: C2 = Compositions(int(3))
     1015            sage: C is C2
     1016            True
     1017        """
     1018        if n is None:
     1019            if len(kwargs) != 0:
     1020                raise ValueError("Incorrect number of arguments")
     1021            return Compositions_all()
     1022        else:
     1023            if len(kwargs) == 0:
     1024                if isinstance(n, (int,Integer)):
     1025                    return Compositions_n(n)
     1026                else:
     1027                    raise ValueError("n must be an integer")
    9651028            else:
    966                 raise ValueError, "n must be an integer"
     1029                # FIXME: should inherit from IntegerListLex, and implement repr, or _name as a lazy attribute
     1030                kwargs['name'] = "Compositions of the integer %s satisfying constraints %s"%(n, ", ".join( ["%s=%s"%(key, kwargs[key]) for key in sorted(kwargs.keys())] ))
     1031                kwargs['element_constructor'] = Composition
     1032                if 'min_part' not in kwargs:
     1033                    kwargs['min_part'] = 1
     1034                elif kwargs['min_part'] == 0:
     1035                    from warnings import warn
     1036                    warn("Currently, setting min_part=0 produces Composition objects which violate internal assumptions.  Calling methods on these objects may produce errors or WRONG results!", RuntimeWarning)
     1037
     1038                if 'outer' in kwargs:
     1039                    kwargs['ceiling'] = list(kwargs['outer'])
     1040                    if 'max_length' in kwargs:
     1041                        kwargs['max_length'] = min(len(kwargs['outer']), kwargs['max_length'])
     1042                    else:
     1043                        kwargs['max_length'] = len(kwargs['outer'])
     1044                    del kwargs['outer']
     1045
     1046                if 'inner' in kwargs:
     1047                    inner = list(kwargs['inner'])
     1048                    kwargs['floor'] = inner
     1049                    del kwargs['inner']
     1050                    # Should this be handled by integer lists lex?
     1051                    if 'min_length' in kwargs:
     1052                        kwargs['min_length'] = max(len(inner), kwargs['min_length'])
     1053                    else:
     1054                        kwargs['min_length'] = len(inner)
     1055                return IntegerListsLex(n, **kwargs)
     1056
     1057    def __init__(self, is_infinite=False):
     1058        """
     1059        Initialize ``self``.
     1060
     1061        EXAMPLES::
     1062
     1063            sage: C = Compositions()
     1064            sage: TestSuite(C).run()
     1065        """
     1066        if is_infinite:
     1067            Parent.__init__(self, category=InfiniteEnumeratedSets())
    9671068        else:
    968             # FIXME: should inherit from IntegerListLex, and implement repr, or _name as a lazy attribute
    969             kwargs['name'] = "Compositions of the integer %s satisfying constraints %s"%(n, ", ".join( ["%s=%s"%(key, kwargs[key]) for key in sorted(kwargs.keys())] ))
    970             kwargs['element_constructor'] = Composition_class
    971             if 'min_part' not in kwargs:
    972                 kwargs['min_part'] = 1
    973             elif kwargs['min_part'] == 0:
    974                 from warnings import warn
    975                 warn("Currently, setting min_part=0 produces Composition objects which violate internal assumptions.  Calling methods on these objects may produce errors or WRONG results!", RuntimeWarning)
     1069            Parent.__init__(self, category=FiniteEnumeratedSets())
    9761070
    977             if 'outer' in kwargs:
    978                 kwargs['ceiling'] = list(kwargs['outer'])
    979                 if 'max_length' in kwargs:
    980                     kwargs['max_length'] = min( len(kwargs['outer']), kwargs['max_length'])
    981                 else:
    982                     kwargs['max_length'] = len(kwargs['outer'])
    983                 del kwargs['outer']
     1071    Element = Composition
    9841072
    985             if 'inner' in kwargs:
    986                 inner = list(kwargs['inner'])
    987                 kwargs['floor'] = inner
    988                 del kwargs['inner']
    989                 # Should this be handled by integer lists lex?
    990                 if 'min_length' in kwargs:
    991                     kwargs['min_length'] = max( len(inner), kwargs['min_length'])
    992                 else:
    993                     kwargs['min_length'] = len(inner)
    994             return IntegerListsLex(n, **kwargs)
     1073    def _element_constructor_(self, lst):
     1074        """
     1075        Construct an element with ``self`` as parent.
     1076       
     1077        EXAMPLES::
    9951078
     1079            sage: P = Compositions()
     1080            sage: P([3,3,1]) # indirect doctest
     1081            [3, 3, 1]
     1082        """
     1083        if isinstance(lst, Composition):
     1084            lst = list(lst)
     1085        elt = self.element_class(self, lst)
     1086        if elt not in self:
     1087            raise ValueError("%s not in %s"%(elt, self))
     1088        return elt
     1089
     1090    def __contains__(self, x):
     1091        """
     1092        TESTS::
     1093
     1094            sage: [2,1,3] in Compositions()
     1095            True
     1096            sage: [] in Compositions()
     1097            True
     1098            sage: [-2,-1] in Compositions()
     1099            False
     1100            sage: [0,0] in Compositions()
     1101            True
     1102        """
     1103        if isinstance(x, Composition):
     1104            return True
     1105        elif isinstance(x, __builtin__.list):
     1106            for i in range(len(x)):
     1107                if (not isinstance(x[i], (int, Integer))) and x[i] not in ZZ:
     1108                    return False
     1109                if x[i] < 0:
     1110                    return False
     1111            return True
     1112        else:
     1113            return False
     1114
     1115    def from_descents(self, descents, nps=None):
     1116        """
     1117        Returns a composition from the list of descents.
     1118
     1119        INPUT:
     1120
     1121        - ``descents`` -- an iterable
     1122
     1123        - ``nps`` -- (default: ``None``) an integer or ``None``; if ``None``, then
     1124          ``nps`` is taken to be `1` plus the maximum element of ``descents``.
     1125
     1126        EXAMPLES::
     1127
     1128            sage: [x-1 for x in Composition([1, 1, 3, 4, 3]).to_subset()]
     1129            [0, 1, 4, 8]
     1130            sage: Compositions().from_descents([1,0,4,8],12)
     1131            [1, 1, 3, 4, 3]
     1132            sage: Compositions().from_descents([1,0,4,8,11])
     1133            [1, 1, 3, 4, 3]
     1134        """
     1135        d = [x+1 for x in sorted(descents)]
     1136        if nps is None:
     1137            nps = d.pop()
     1138        return self.from_subset(d, nps)
     1139
     1140    def from_subset(self, S, n):
     1141        r"""
     1142        The composition of `n` corresponding to the subset ``S`` of
     1143        `\{1, 2, \ldots, n-1\}` under the bijection that maps the composition
     1144        `(i_1, i_2, \ldots, i_k)` of `n` to the subset
     1145        `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \ldots, i_1 + \cdots + i_{k-1}\}`
     1146        (see :meth:`Composition.to_subset`).
     1147
     1148        INPUT:
     1149
     1150        - ``S`` -- an iterable, a subset of `n-1`
     1151
     1152        - ``n`` -- an integer
     1153
     1154        EXAMPLES::
     1155
     1156            sage: Compositions().from_subset([2,1,5,9], 12)
     1157            [1, 1, 3, 4, 3]
     1158            sage: Compositions().from_subset({2,1,5,9}, 12)
     1159            [1, 1, 3, 4, 3]
     1160
     1161        TESTS::
     1162
     1163            sage: Compositions().from_subset([2,1,5,9],9)
     1164            Traceback (most recent call last):
     1165            ...
     1166            ValueError: S (=[1, 2, 5, 9]) is not a subset of {1, ..., 8}
     1167        """
     1168        d = sorted(S)
     1169
     1170        if d == []:
     1171            if n == 0:
     1172                return self.element_class(self, [])
     1173            else:
     1174                return self.element_class(self, [n])
     1175
     1176        if n <= max(d):
     1177            raise ValueError, "S (=%s) is not a subset of {1, ..., %s}" % (d,n-1)
     1178        elif n > max(d):
     1179            d.append(n)
     1180
     1181        co = [d[0]]
     1182        for i in range(len(d)-1):
     1183            co += [ d[i+1]-d[i] ]
     1184
     1185        return self.element_class(self, co)
     1186
     1187    def from_code(self, code):
     1188        """
     1189        Return the composition from its code. The code of a composition is a
     1190        list of length ``self.size()`` of 1s and 0s such that there is a 1
     1191        wherever a new part starts.
     1192
     1193        EXAMPLES::
     1194
     1195            sage: Composition([4,1,2,3,5]).to_code()
     1196            [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
     1197            sage: Compositions().from_code(_)
     1198            [4, 1, 2, 3, 5]
     1199            sage: Composition([3,1,2,3,5]).to_code()
     1200            [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
     1201            sage: Compositions().from_code(_)
     1202            [3, 1, 2, 3, 5]
     1203        """
     1204        if code == [0]:
     1205            return []
     1206
     1207        L = filter(lambda x: code[x]==1, range(len(code))) #the positions of the letter 1
     1208        return self.element_class(self, [L[i]-L[i-1] for i in range(1, len(L))] + [len(code)-L[-1]])
    9961209
    9971210# Allows to unpickle old constrained Compositions_constraints objects.
    9981211class Compositions_constraints(IntegerListsLex):
    class Compositions_constraints(IntegerLi 
    10121225        """
    10131226        n = data['n']
    10141227        self.__class__ = IntegerListsLex
    1015         constraints = {
    1016                        'min_part' : 1,
    1017                        'element_constructor' : Composition_class}
     1228        constraints = {'min_part' : 1,
     1229                       'element_constructor' : Composition}
    10181230        constraints.update(data['constraints'])
    10191231        self.__init__(n, **constraints)
    10201232
    1021 class Compositions_all(InfiniteAbstractCombinatorialClass):
     1233class Compositions_all(Compositions):
     1234    """
     1235    Class of all compositions.
     1236    """
    10221237    def __init__(self):
    10231238        """
     1239        Initialize ``self``.
     1240
    10241241        TESTS::
    10251242
    10261243            sage: C = Compositions()
    10271244            sage: TestSuite(C).run()
     1245        """
     1246        Compositions.__init__(self, True)
    10281247
     1248    def _repr_(self):
    10291249        """
    1030         Parent.__init__(self, category = InfiniteEnumeratedSets())
     1250        Return a string representation of ``self``.
    10311251
    1032     def __repr__(self):
    1033         """
    10341252        TESTS::
    10351253
    10361254            sage: repr(Compositions())
    class Compositions_all(InfiniteAbstractC 
    10381256        """
    10391257        return "Compositions of non-negative integers"
    10401258
    1041     Element = Composition_class
    1042 
    10431259    def subset(self, size=None):
    10441260        """
    1045         Returns the set of compositions of the given size.
     1261        Return the set of compositions of the given size.
    10461262
    10471263        EXAMPLES::
    10481264
    class Compositions_all(InfiniteAbstractC 
    10561272            return self
    10571273        return Compositions(size)
    10581274
    1059     def __contains__(self, x):
     1275    def __iter__(self):
    10601276        """
    1061         TESTS::
    1062 
    1063             sage: [2,1,3] in Compositions()
    1064             True
    1065             sage: [] in Compositions()
    1066             True
    1067             sage: [-2,-1] in Compositions()
    1068             False
    1069             sage: [0,0] in Compositions()
    1070             True
    1071         """
    1072         if isinstance(x, Composition_class):
    1073             return True
    1074         elif isinstance(x, __builtin__.list):
    1075             for i in range(len(x)):
    1076                 if not isinstance(x[i], (int, Integer)):
    1077                     return False
    1078                 if x[i] < 0:
    1079                     return False
    1080             return True
    1081         else:
    1082             return False
    1083 
    1084     def _infinite_cclass_slice(self, n):
    1085         """
    1086         Needed by InfiniteAbstractCombinatorialClass to build __iter__.
     1277        Iterate over all compositions.
    10871278
    10881279        TESTS::
    10891280
    1090             sage: Compositions()._infinite_cclass_slice(4) == Compositions(4)
    1091             True
    1092             sage: it = iter(Compositions())    # indirect doctest
     1281            sage: C = Compositions()
     1282            sage: it = C.__iter__()
    10931283            sage: [it.next() for i in range(10)]
    10941284            [[], [1], [1, 1], [2], [1, 1, 1], [1, 2], [2, 1], [3], [1, 1, 1, 1], [1, 1, 2]]
    10951285        """
    1096         return Compositions_n(n)
     1286        n = 0
     1287        while True:
     1288            for c in Compositions(n):
     1289                yield self.element_class(self, list(c))
     1290            n += 1
    10971291
     1292class Compositions_n(Compositions):
     1293    """
     1294    Class of compositions of a fixed `n`.
     1295    """
     1296    @staticmethod
     1297    def __classcall_private__(cls, n):
     1298        """
     1299        Standardize input to ensure a unique representation.
    10981300
    1099 class Compositions_n(CombinatorialClass):
     1301        EXAMPLES::
     1302
     1303            sage: C = Compositions(5)
     1304            sage: C2 = Compositions(int(5))
     1305            sage: C3 = Compositions(ZZ(5))
     1306            sage: C is C2
     1307            True
     1308            sage: C is C3
     1309            True
     1310        """
     1311        return super(Compositions_n, cls).__classcall__(cls, Integer(n))
     1312
    11001313    def __init__(self, n):
    11011314        """
    11021315        TESTS::
    class Compositions_n(CombinatorialClass) 
    11041317            sage: C = Compositions(3)
    11051318            sage: C == loads(dumps(C))
    11061319            True
     1320            sage: TestSuite(C).run()
    11071321        """
    11081322        self.n = n
     1323        Compositions.__init__(self, False)
    11091324
    1110     def __repr__(self):
     1325    def _repr_(self):
    11111326        """
     1327        Return a string representation of ``self``.
     1328
    11121329        TESTS::
    11131330
    11141331            sage: repr(Compositions(3))
    class Compositions_n(CombinatorialClass) 
    11331350
    11341351    def cardinality(self):
    11351352        """
     1353        Return the number of compositions of `n`.
     1354
    11361355        TESTS::
    11371356
    11381357            sage: Compositions(3).cardinality()
    class Compositions_n(CombinatorialClass) 
    11471366        else:
    11481367            return 0
    11491368
    1150     def list(self):
     1369    def __iter__(self):
    11511370        """
     1371        Iterate over the compositions of `n`.
     1372
    11521373        TESTS::
    11531374
    11541375            sage: Compositions(4).list()
    class Compositions_n(CombinatorialClass) 
    11571378            [[]]
    11581379        """
    11591380        if self.n == 0:
    1160             return [Composition_class([])]
     1381            yield self.element_class(self, [])
     1382            return
    11611383
    1162         result = []
    11631384        for i in range(1,self.n+1):
    1164             result += map(lambda x: [i]+x[:], Compositions_n(self.n-i).list())
    1165 
    1166         return [Composition_class(r) for r in result]
    1167 
    1168 
    1169 
    1170 
    1171 # Those belong to the Composition class
     1385            for c in Compositions_n(self.n-i):
     1386                yield self.element_class(self, [i]+list(c))
    11721387
    11731388def from_descents(descents, nps=None):
    1174     """
    1175     Returns a composition from the list of descents.
    1176 
    1177     INPUT:
    1178 
    1179     - ``descents`` -- an iterable
    1180     - ``nps`` -- (default: ``None``) an integer or ``None``; if ``None``, then
    1181       ``nps`` is taken to be `1` plus the maximum element of ``descents``.
     1389    r"""
     1390    This has been deprecated in :trac:`14063`. Use
     1391    :meth:`Compositions.from_descents()` instead.
    11821392
    11831393    EXAMPLES::
    11841394
    11851395        sage: [x-1 for x in Composition([1, 1, 3, 4, 3]).to_subset()]
    11861396        [0, 1, 4, 8]
    11871397        sage: sage.combinat.composition.from_descents([1,0,4,8],12)
    1188         [1, 1, 3, 4, 3]
    1189         sage: sage.combinat.composition.from_descents([1,0,4,8,11])
     1398        doctest:1: DeprecationWarning: from_descents is deprecated. Use Compositions().from_descents instead.
     1399        See http://trac.sagemath.org/14063 for details.
    11901400        [1, 1, 3, 4, 3]
    11911401    """
    1192     d = [x+1 for x in sorted(descents)]
    1193     if nps is None:
    1194         nps = d.pop()
    1195     return composition_from_subset(d, nps)
     1402    from sage.misc.superseded import deprecation
     1403    deprecation(14063, 'from_descents is deprecated. Use Compositions().from_descents instead.')
     1404    return Compositions().from_descents(descents, nps)
    11961405
    11971406def composition_from_subset(S, n):
    1198     """
    1199     The composition of `n` corresponding to the subset ``S`` of
    1200     `\{1, 2, \dots, n-1\}` under the bijection that maps the composition
    1201     `[i_1, i_2, \dots, i_k]` of `n` to the subset
    1202     `\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \dots, i_1 + \cdots + i_{k-1}\}`
    1203     (see :meth:`to_subset`).
    1204 
    1205     INPUT:
    1206 
    1207     - ``S`` -- an iterable, a subset of `n-1`
    1208     - ``n`` -- an integer
     1407    r"""
     1408    This has been deprecated in :trac:`14063`. Use
     1409    :meth:`Compositions.from_subset()` instead.
    12091410
    12101411    EXAMPLES::
    12111412
    12121413        sage: from sage.combinat.composition import composition_from_subset
    12131414        sage: composition_from_subset([2,1,5,9], 12)
     1415        doctest:1: DeprecationWarning: composition_from_subset is deprecated. Use Compositions().from_subset instead.
     1416        See http://trac.sagemath.org/14063 for details.
    12141417        [1, 1, 3, 4, 3]
    1215         sage: composition_from_subset({2,1,5,9}, 12)
    1216         [1, 1, 3, 4, 3]
    1217 
    1218     TESTS::
    1219 
    1220         sage: from sage.combinat.composition import composition_from_subset
    1221         sage: composition_from_subset([2,1,5,9],9)
    1222         Traceback (most recent call last):
    1223         ...
    1224         ValueError: S (=[1, 2, 5, 9]) is not a subset of {1, ..., 8}
    12251418    """
    1226     d = sorted(S)
    1227 
    1228     if d == []:
    1229         if n == 0:
    1230             return Composition([])
    1231         else:
    1232             return Composition([n])
    1233 
    1234     if n <= max(d):
    1235         raise ValueError, "S (=%s) is not a subset of {1, ..., %s}" % (d,n-1)
    1236     elif n > max(d):
    1237         d.append(n)
    1238 
    1239     co = [d[0]]
    1240     for i in range(len(d)-1):
    1241         co += [ d[i+1]-d[i] ]
    1242 
    1243     return Composition(co)
     1419    from sage.misc.superseded import deprecation
     1420    deprecation(14063, 'composition_from_subset is deprecated. Use Compositions().from_subset instead.')
     1421    return Compositions().from_subset(S, n)
    12441422
    12451423def from_code(code):
    1246     """
    1247     Return the composition from its code. The code of a composition is a
    1248     list of length self.size() of 1s and 0s such that there is a 1
    1249     wherever a new part starts.
     1424    r"""
     1425    This has been deprecated in :trac:`14063`. Use
     1426    :meth:`Compositions.from_code()` instead.
    12501427
    12511428    EXAMPLES::
    12521429
    def from_code(code): 
    12541431        sage: Composition([4,1,2,3,5]).to_code()
    12551432        [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
    12561433        sage: composition.from_code(_)
     1434        doctest:1: DeprecationWarning: from_code is deprecated. Use Compositions().from_code instead.
     1435        See http://trac.sagemath.org/14063 for details.
    12571436        [4, 1, 2, 3, 5]
    1258         sage: Composition([3,1,2,3,5]).to_code()
    1259         [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
    1260         sage: composition.from_code(_)
    1261         [3, 1, 2, 3, 5]
    12621437    """
    1263     if code == [0]:
    1264         return []
     1438    from sage.misc.superseded import deprecation
     1439    deprecation(14063, 'from_code is deprecated. Use Compositions().from_code instead.')
     1440    return Compositions().from_code(code)
    12651441
    1266     L = filter(lambda x: code[x]==1, range(len(code))) #the positions of the letter 1
    1267     return Composition([L[i]-L[i-1] for i in range(1, len(L))] + [len(code)-L[-1]])
     1442from sage.structure.sage_object import register_unpickle_override
     1443register_unpickle_override('sage.combinat.composition', 'Composition_class', Composition)
    12681444
  • sage/combinat/composition_signed.py

    diff --git a/sage/combinat/composition_signed.py b/sage/combinat/composition_signed.py
    a b Signed Compositions 
    1616#                  http://www.gnu.org/licenses/
    1717#*****************************************************************************
    1818
    19 from combinat import CombinatorialClass
    20 import composition
     19from composition import Compositions_n, Composition
    2120import cartesian_product
    2221from sage.rings.all import binomial, Integer
    2322import __builtin__
    2423
    25 def SignedCompositions(n):
     24class SignedCompositions(Compositions_n):
    2625    """
    27     Returns the combinatorial class of signed compositions of n.
    28    
     26    The class of signed compositions of `n`.
     27
    2928    EXAMPLES::
    30    
     29
    3130        sage: SC3 = SignedCompositions(3); SC3
    3231        Signed compositions of 3
    3332        sage: SC3.cardinality()
    def SignedCompositions(n): 
    5958         [-2, -1],
    6059         [3],
    6160         [-3]]
     61
     62    TESTS::
     63
     64        sage: SC = SignedCompositions(3)
     65        sage: TestSuite(SC).run()
    6266    """
    63     return SignedCompositions_n(n)
    64 
    65 class SignedCompositions_n(CombinatorialClass):
    66     def __init__(self, n):
    67         """
    68         TESTS::
    69        
    70             sage: SC3 = SignedCompositions(3)
    71             sage: SC3 == loads(dumps(SC3))
    72             True
    73         """
    74         self.n = n
    75 
    7667    def __repr__(self):
    7768        """
    7869        TESTS::
    79        
    80             sage: repr(SignedCompositions(3))
    81             'Signed compositions of 3'
     70
     71            sage: SignedCompositions(3)
     72            Signed compositions of 3
    8273        """
    8374        return "Signed compositions of %s"%self.n
    8475
    8576    def __contains__(self, x):
    8677        """
    8778        TESTS::
    88        
     79
    8980            sage: [] in SignedCompositions(0)
    9081            True
    9182            sage: [0] in SignedCompositions(0)
    class SignedCompositions_n(Combinatorial 
    9586            sage: [-2, 1, -3] in SignedCompositions(6)
    9687            True
    9788        """
    98         if x == []:
    99             return True
    100        
    10189        if isinstance(x, __builtin__.list):
    10290            for i in range(len(x)):
    103                 if not isinstance(x[i], (int, Integer)):
     91                if (not isinstance(x[i], (int, Integer))) and x[i] not in ZZ:
    10492                    return False
    10593                if x[i] == 0:
    10694                    return False
    107                 return True
    108         else:
     95        elif not isinstance(x, Composition):
    10996            return False
    110 
    11197        return sum([abs(i) for i in x]) == self.n
    11298       
    11399    def cardinality(self):
    114         """
     100        r"""
     101        Return the number of elements in ``self``.
     102
     103        The number of signed compositions of `n` is equal to
     104
     105        .. MATH::
     106
     107            \sum_{i=1}^{n+1} \binom{n-1}{i-1} 2^i
     108
    115109        TESTS::
    116        
     110
    117111            sage: SC4 = SignedCompositions(4)
    118112            sage: SC4.cardinality() == len(SC4.list())
    119113            True
    120114            sage: SignedCompositions(3).cardinality()
    121115            18
    122116        """
    123         return sum([ binomial(self.n-1, i-1)*2**(i) for i in range(1, self.n+1)])
     117        return sum([binomial(self.n-1, i-1)*2**(i) for i in range(1, self.n+1)])
    124118
    125119    def __iter__(self):
    126120        """
    127121        TESTS::
    128        
     122
    129123            sage: SignedCompositions(0).list()   #indirect doctest
    130124            [[]]
    131125            sage: SignedCompositions(1).list()   #indirect doctest
    class SignedCompositions_n(Combinatorial 
    133127            sage: SignedCompositions(2).list()   #indirect doctest
    134128            [[1, 1], [1, -1], [-1, 1], [-1, -1], [2], [-2]]
    135129        """
    136         for comp in composition.Compositions(self.n):
     130        for comp in Compositions_n.__iter__(self):
    137131            l = len(comp)
    138132            a = [[1,-1] for i in range(l)]
    139133            for sign in cartesian_product.CartesianProduct(*a):
    140134                yield [ sign[i]*comp[i] for i in range(l)]
    141135
     136from sage.structure.sage_object import register_unpickle_override
     137register_unpickle_override('sage.combinat.composition_signed', 'SignedCompositions_n', SignedCompositions)
     138
  • sage/combinat/ncsf_qsym/generic_basis_code.py

    diff --git a/sage/combinat/ncsf_qsym/generic_basis_code.py b/sage/combinat/ncsf_qsym/generic_basis_code.py
    a b AUTHORS: 
    2929from sage.misc.cachefunc import cached_method
    3030from sage.categories.realizations import Category_realization_of_parent
    3131from sage.categories.modules_with_basis import ModulesWithBasis, ModuleMorphismByLinearity
    32 from sage.combinat.composition import Composition, Composition_class
     32from sage.combinat.composition import Composition
    3333from sage.combinat.partition import Partition
    3434from sage.combinat.permutation import Permutations
    3535from sage.rings.integer import Integer
    class BasesOfQSymOrNCSF(Category_realiza 
    110110                This could possibly be shared with Sym, FQSym, and
    111111                other algebras with bases indexed by list-like objects
    112112            """
    113             if isinstance(c, Composition_class):
     113            if isinstance(c, Composition):
    114114                assert len(rest) == 0
    115115            else:
    116116                if len(rest) > 0 or isinstance(c, (int, Integer)):
  • sage/combinat/ncsf_qsym/qsym.py

    diff --git a/sage/combinat/ncsf_qsym/qsym.py b/sage/combinat/ncsf_qsym/qsym.py
    a b class QuasiSymmetricFunctions(UniqueRepr 
    12111211            M = self.realization_of().Monomial()
    12121212            if J == []:
    12131213                return M([])
    1214             return M.sum_of_terms((I, number_of_fCT( I, J) ) for I in Compositions(J.size()))
     1214            C = Compositions()
     1215            C_size = Compositions(J.size())
     1216            return M.sum_of_terms((C(I), number_of_fCT(C(I), J)) for I in C_size)
    12151217
    12161218        @cached_method
    12171219        def _matrix_monomial_to_dual_immaculate(self, n):
    class QuasiSymmetricFunctions(UniqueRepr 
    12381240            I = N.I()
    12391241            S = N.S()
    12401242            mat = []
     1243            C = Compositions()
    12411244            for alp in Compositions(n):
    12421245                row = []
    1243                 expansion = S(I(alp))
     1246                expansion = S(I(C(alp)))
    12441247                for bet in Compositions(n):
    1245                     row.append(expansion.coefficient(Composition(bet)))
     1248                    row.append(expansion.coefficient(C(bet)))
    12461249                mat.append(row)
    12471250            return mat
    12481251
    class QuasiSymmetricFunctions(UniqueRepr 
    12691272                -dI[1, 1, 1, 1, 1, 1] + dI[1, 1, 1, 1, 2] + dI[1, 1, 1, 3] - dI[1, 1, 4] - dI[1, 2, 1, 1, 1] + dI[1, 2, 3] + dI[2, 1, 1, 1, 1] - dI[2, 1, 1, 2] + dI[2, 2, 1, 1] - dI[2, 2, 2] - dI[3, 1, 1, 1] + dI[3, 1, 2]
    12701273            """
    12711274            n = J.size()
    1272             C= Compositions(n)
     1275            C = Compositions()
     1276            C_n = Compositions(n)
    12731277            mat = self._matrix_monomial_to_dual_immaculate(n)
    1274             column = C.list().index(J)
    1275             return self.sum_of_terms( (I, mat[C.list().index(I)][column])
    1276                                             for I in Compositions(n))
     1278            column = C_n.list().index(J)
     1279            return self.sum_of_terms( (C(I), mat[C_n.list().index(I)][column])
     1280                                            for I in C_n)
    12771281
    12781282    dI = dualImmaculate
  • sage/combinat/necklace.py

    diff --git a/sage/combinat/necklace.py b/sage/combinat/necklace.py
    a b The algorithm used in this file comes fr 
    2121#
    2222#                  http://www.gnu.org/licenses/
    2323#*****************************************************************************
    24 from sage.combinat.composition import Composition, Composition_class
     24from sage.combinat.composition import Composition
    2525from combinat import CombinatorialClass
    2626from sage.rings.arith import euler_phi,factorial, divisors, gcd
    2727from sage.rings.integer import Integer
    class Necklaces_evaluation(Combinatorial 
    5656            sage: N == loads(dumps(N))
    5757            True
    5858        """
    59         if isinstance(e, Composition_class):
     59        if isinstance(e, Composition):
    6060            self.e = e
    6161        else:
    6262            self.e = Composition(e)
  • sage/combinat/permutation.py

    diff --git a/sage/combinat/permutation.py b/sage/combinat/permutation.py
    a b from sage.rings.all import ZZ, Integer,  
    201201from sage.matrix.all import matrix
    202202from sage.combinat.tools import transitive_ideal
    203203import sage.combinat.subword as subword
    204 from sage.combinat.composition import Composition, Composition_class
     204from sage.combinat.composition import Composition, Composition
    205205import tableau
    206206import sage.combinat.partition
    207207from permutation_nk import PermutationsNK
    def descents_composition_first(dc): 
    42594259        [3, 2, 1, 4, 6, 5, 7, 8, 10, 9, 11, 12]
    42604260    """
    42614261
    4262     if not isinstance(dc, Composition_class):
     4262    if not isinstance(dc, Composition):
    42634263        try:
    42644264            dc = Composition(dc)
    42654265        except TypeError:
    def descents_composition_last(dc): 
    42854285        sage: permutation.descents_composition_last([1,1,3,4,3])
    42864286        [12, 11, 8, 9, 10, 4, 5, 6, 7, 1, 2, 3]
    42874287    """
    4288     if not isinstance(dc, Composition_class):
     4288    if not isinstance(dc, Composition):
    42894289        try:
    42904290            dc = Composition(dc)
    42914291        except TypeError:
  • sage/sets/disjoint_union_enumerated_sets.py

    diff --git a/sage/sets/disjoint_union_enumerated_sets.py b/sage/sets/disjoint_union_enumerated_sets.py
    a b class DisjointUnionEnumeratedSets(Unique 
    296296            sage: U4 = DisjointUnionEnumeratedSets(
    297297            ...            Family(NonNegativeIntegers(), Compositions))
    298298            sage: U4._is_a(Composition([3,2,1,1]))
    299             doctest:...: UserWarning: Disjoint union of Lazy family (Compositions(i))_{i in Non negative integers} is an infinite union
     299            doctest:...: UserWarning: Disjoint union of Lazy family (<class 'sage.combinat.composition.Compositions'>(i))_{i in Non negative integers} is an infinite union
    300300            The default implementation of __contains__ can loop forever. Please overload it.
    301301            True
    302302        """