Ticket #14140: trac_14140-remove_cc_set_partitions-ts.patch

File trac_14140-remove_cc_set_partitions-ts.patch, 78.9 KB (added by tscrim, 8 years ago)
  • doc/en/thematic_tutorials/sandpile.rst

    # HG changeset patch
    # User Travis Scrimshaw <tscrim@ucdavis.edu>
    # Date 1362156973 28800
    # Node ID ce4a5741afce9d91c884ec7dac052899b4f3f4b7
    # Parent e0ae5c206ebce43de27f0c37b5376752061df89b
    #14140: Refactor set_partition* to remove CombinatorialClass.
    
    diff --git a/doc/en/thematic_tutorials/sandpile.rst b/doc/en/thematic_tutorials/sandpile.rst
    a b Other 
    40234023        sage: S = Sandpile(graphs.CycleGraph(4), 0)
    40244024        sage: P = [admissible_partitions(S, i) for i in [2,3,4]]
    40254025        sage: P
    4026         [[{{1, 2, 3}, {0}},
     4026        [[{{0}, {1, 2, 3}},
    40274027          {{0, 2, 3}, {1}},
    4028           {{2}, {0, 1, 3}},
     4028          {{0, 1, 3}, {2}},
    40294029          {{0, 1, 2}, {3}},
    4030           {{2, 3}, {0, 1}},
    4031           {{1, 2}, {0, 3}}],
    4032          [{{2, 3}, {0}, {1}},
    4033           {{1, 2}, {3}, {0}},
    4034           {{2}, {0, 3}, {1}},
    4035           {{2}, {3}, {0, 1}}],
    4036          [{{2}, {3}, {0}, {1}}]]
     4030          {{0, 1}, {2, 3}},
     4031          {{0, 3}, {1, 2}}],
     4032         [{{0}, {1}, {2, 3}},
     4033          {{0}, {1, 2}, {3}},
     4034          {{0, 3}, {1}, {2}},
     4035          {{0, 1}, {2}, {3}}],
     4036         [{{0}, {1}, {2}, {3}}]]
    40374037        sage: for p in P: # long time
    40384038        ...    sum([partition_sandpile(S, i).betti(verbose=false)[-1] for i in p]) # long time
    40394039        6
  • sage/combinat/all.py

    diff --git a/sage/combinat/all.py b/sage/combinat/all.py
    a b from non_decreasing_parking_function imp 
    8585from combination import Combinations
    8686from cartesian_product import CartesianProduct
    8787
    88 from set_partition import SetPartitions
    89 from set_partition_ordered import OrderedSetPartitions
     88from set_partition import SetPartition, SetPartitions
     89from set_partition_ordered import OrderedSetPartition, OrderedSetPartitions
    9090from subset import Subsets
    9191#from subsets_pairwise import PairwiseCompatibleSubsets
    9292from necklace import Necklaces
  • sage/combinat/partition.py

    diff --git a/sage/combinat/partition.py b/sage/combinat/partition.py
    a b def partitions_set(S,k=None, use_file=Tr 
    59325932        sage: partitions_set(S,2)
    59335933        doctest:1: DeprecationWarning: partitions_set is deprecated. Use SetPartitions instead.
    59345934        See http://trac.sagemath.org/13072 for details.
    5935         Set partitions of [1, 2, 3, 4] with 2 parts
     5935        Set partitions of {1, 2, 3, 4} with 2 parts
    59365936    """
    59375937    from sage.misc.superseded import deprecation
    59385938    deprecation(13072,'partitions_set is deprecated. Use SetPartitions instead.')
  • sage/combinat/partition_algebra.py

    diff --git a/sage/combinat/partition_algebra.py b/sage/combinat/partition_algebra.py
    a b Partition/Diagram Algebras 
    1818
    1919from combinat import CombinatorialClass, catalan_number
    2020from combinatorial_algebra import CombinatorialAlgebra, CombinatorialAlgebraElement
    21 import set_partition
    22 from sage.sets.set import Set
     21from sage.combinat.set_partition import SetPartition, SetPartitions, SetPartitions_set
     22from sage.sets.set import Set, is_Set
    2323from sage.graphs.graph import Graph
    2424from sage.rings.arith import factorial, binomial
    2525from permutation import Permutations
    def create_set_partition_function(letter 
    4444        if k - math.floor(k) == 0.5:
    4545            return globals()['SetPartitions' + letter + 'khalf_k'](floor(k))
    4646
    47     raise ValueError, "k must be an integer or an integer + 1/2"
     47    raise ValueError("k must be an integer or an integer + 1/2")
    4848
     49class SetPartitionsXkElement(SetPartition):
     50    """
     51    An element for the classes of ``SetPartitionXk`` where ``X`` is some
     52    letter.
     53    """
     54    def check(self):
     55        """
     56        Check to make sure this is a set partition.
     57
     58        EXAMLPLES::
     59
     60            sage: A2p5 = SetPartitionsAk(2.5)
     61            sage: A2p5.first() # random
     62            {{1, 2, 3, -1, -3, -2}}
     63        """
     64        #Check to make sure each element of x is a set
     65        u = Set([])
     66        for s in self:
     67            assert isinstance(s, (set, frozenset)) or is_Set(s)
    4968
    5069#####
    5170#A_k#
    SetPartitionsAk.__doc__ = ( 
    81100        {{-1}, {-2}, {2}, {3, -3}, {1}}
    82101        sage: A2p5.random_element() #random
    83102        {{-1}, {-2}, {3, -3}, {1, 2}}
    84 
    85103    """)
    86104
    87 class SetPartitionsAk_k(set_partition.SetPartitions_set):
     105class SetPartitionsAk_k(SetPartitions_set):
    88106    def __init__(self, k):
    89107        """
    90108        TESTS::
    class SetPartitionsAk_k(set_partition.Se 
    95113            True
    96114        """
    97115        self.k = k
    98         set_partition.SetPartitions_set.__init__(self, Set(range(1,k+1) + map(lambda x: -1*x,range(1,k+1))))
     116        SetPartitions_set.__init__(self, frozenset(range(1,k+1) + map(lambda x: -1*x,range(1,k+1))))
    99117
    100     def __repr__(self):
     118    Element = SetPartitionsXkElement
     119
     120    def _repr_(self):
    101121        """
    102122        TESTS::
    103123       
    104             sage: repr(SetPartitionsAk(3))
    105             'Set partitions of {1, ..., 3, -1, ..., -3}'
     124            sage: SetPartitionsAk(3)
     125            Set partitions of {1, ..., 3, -1, ..., -3}
    106126        """
    107127        return "Set partitions of {1, ..., %s, -1, ..., -%s}"%(self.k, self.k)
    108128
    109 class SetPartitionsAkhalf_k(CombinatorialClass):
     129class SetPartitionsAkhalf_k(SetPartitions_set):
    110130    def __init__(self, k):
    111131        """
    112132        TESTS::
    class SetPartitionsAkhalf_k(Combinatoria 
    117137            True
    118138        """
    119139        self.k = k
    120         self._set = range(1,k+2) + map(lambda x: -1*x, range(1,k+1))
     140        SetPartitions_set.__init__( self, frozenset(range(1,k+2) + map(lambda x: -1*x, range(1,k+1))) )
    121141
    122     def __repr__(self):
     142    Element = SetPartitionsXkElement
     143
     144    def _repr_(self):
    123145        """
    124146        TESTS::
    125147       
    126             sage: repr(SetPartitionsAk(2.5))
    127             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block'
     148            sage: SetPartitionsAk(2.5)
     149            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block
    128150        """
    129151        s = self.k+1
    130152        return "Set partitions of {1, ..., %s, -1, ..., -%s} with %s and -%s in the same block"%(s,s,s,s)
    class SetPartitionsAkhalf_k(Combinatoria 
    151173
    152174        return True
    153175
    154     def cardinality(self):
    155         """
    156         TESTS::
    157        
    158             sage: SetPartitionsAk(1.5).cardinality()
    159             5
    160             sage: SetPartitionsAk(2.5).cardinality()
    161             52
    162             sage: SetPartitionsAk(3.5).cardinality()
    163             877
    164         """
    165         return set_partition.SetPartitions_set(self._set).cardinality()
    166 
    167176    def __iter__(self):
    168177        """
    169178        TESTS::
    class SetPartitionsAkhalf_k(Combinatoria 
    183192            True
    184193        """
    185194        kp = Set([-self.k-1])
    186         for sp in set_partition.SetPartitions_set(self._set):
     195        for sp in SetPartitions_set.__iter__(self):
    187196            res = []
    188197            for part in sp:
    189198                if self.k+1 in part:
    190199                    res.append( part + kp )
    191200                else:
    192201                    res.append(part)
    193             yield Set(res)
     202            yield self.element_class(self, res)
    194203
    195204#####
    196205#S_k#
    SetPartitionsSk.__doc__ = ( 
    243252        {{1, -3}, {2, -2}, {4, -4}, {3, -1}}
    244253    """)
    245254class SetPartitionsSk_k(SetPartitionsAk_k):
    246     def __repr__(self):
     255    def _repr_(self):
    247256        """
    248257        TESTS::
    249258       
    250             sage: repr(SetPartitionsSk(3))
    251             'Set partitions of {1, ..., 3, -1, ..., -3} with propagating number 3'
     259            sage: SetPartitionsSk(3)
     260            Set partitions of {1, ..., 3, -1, ..., -3} with propagating number 3
    252261        """
    253         return SetPartitionsAk_k.__repr__(self) + " with propagating number %s"%self.k
     262        return SetPartitionsAk_k._repr_(self) + " with propagating number %s"%self.k
    254263
    255264    def __contains__(self, x):
    256265        """
    class SetPartitionsSk_k(SetPartitionsAk_ 
    310319            res = []
    311320            for i in range(self.k):
    312321                res.append( Set([ i+1, -p[i] ]) )
    313             yield Set(res)
     322            yield self.element_class(self, res)
    314323
    315324class SetPartitionsSkhalf_k(SetPartitionsAkhalf_k):
    316325    def __contains__(self, x):
    class SetPartitionsSkhalf_k(SetPartition 
    332341            return False
    333342        return True
    334343
    335     def __repr__(self):
     344    def _repr_(self):
    336345        """
    337346        TESTS::
    338347       
    339             sage: repr(SetPartitionsSk(2.5))
    340             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number 3'
     348            sage: SetPartitionsSk(2.5)
     349            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number 3
    341350        """
    342351        s = self.k+1
    343         return SetPartitionsAkhalf_k.__repr__(self) + " and propagating number %s"%s
     352        return SetPartitionsAkhalf_k._repr_(self) + " and propagating number %s"%s
    344353
    345354    def cardinality(self):
    346355        """
    class SetPartitionsSkhalf_k(SetPartition 
    380389                res.append( Set([ i+1, -p[i] ]) )
    381390
    382391            res.append(Set([self.k+1, -self.k - 1]))
    383             yield Set(res)
     392            yield self.element_class(self, res)
    384393
    385394#####
    386395#I_k#
    SetPartitionsIk.__doc__ = ( 
    421430
    422431    """)
    423432class SetPartitionsIk_k(SetPartitionsAk_k):
    424     def __repr__(self):
     433    def _repr_(self):
    425434        """
    426435        TESTS::
    427436       
    428             sage: repr(SetPartitionsIk(3))
    429             'Set partitions of {1, ..., 3, -1, ..., -3} with propagating number < 3'
     437            sage: SetPartitionsIk(3)
     438            Set partitions of {1, ..., 3, -1, ..., -3} with propagating number < 3
    430439        """
    431         return SetPartitionsAk_k.__repr__(self) + " with propagating number < %s"%self.k
     440        return SetPartitionsAk_k._repr_(self) + " with propagating number < %s"%self.k
    432441
    433442    def __contains__(self, x):
    434443        """
    class SetPartitionsIkhalf_k(SetPartition 
    501510            return False
    502511        return True
    503512
    504     def __repr__(self):
     513    def _repr_(self):
    505514        """
    506515        TESTS::
    507516       
    508             sage: repr(SetPartitionsIk(2.5))
    509             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number < 3'
     517            sage: SetPartitionsIk(2.5)
     518            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number < 3
    510519        """
    511         return SetPartitionsAkhalf_k.__repr__(self) + " and propagating number < %s"%(self.k+1)
     520        return SetPartitionsAkhalf_k._repr_(self) + " and propagating number < %s"%(self.k+1)
    512521
    513522    def cardinality(self):
    514523        """
    SetPartitionsBk.__doc__ = ( 
    576585    """)
    577586
    578587class SetPartitionsBk_k(SetPartitionsAk_k):
    579     def __repr__(self):
     588    def _repr_(self):
    580589        """
    581590        TESTS::
    582591       
    583             sage: repr(SetPartitionsBk(2.5))
    584             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2'
     592            sage: SetPartitionsBk(2.5)
     593            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2
    585594        """
    586         return SetPartitionsAk_k.__repr__(self) + " with block size 2"
     595        return SetPartitionsAk_k._repr_(self) + " with block size 2"
    587596
    588597    def __contains__(self, x):
    589598        """
    class SetPartitionsBk_k(SetPartitionsAk_ 
    665674            sage: all( [ bk.cardinality() == len(bk.list()) for bk in bks] )
    666675            True
    667676        """
    668         for sp in set_partition.SetPartitions(self.set, [2]*(len(self.set)/2)):
    669             yield sp
     677        for sp in SetPartitions(self._set, [2]*(len(self._set)/2)):
     678            yield self.element_class(self, sp)
    670679
    671680class SetPartitionsBkhalf_k(SetPartitionsAkhalf_k):
    672     def __repr__(self):
     681    def _repr_(self):
    673682        """
    674683        TESTS::
    675684       
    676             sage: repr(SetPartitionsBk(2.5))
    677             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2'
     685            sage: SetPartitionsBk(2.5)
     686            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2
    678687        """
    679         return SetPartitionsAkhalf_k.__repr__(self) + " and with block size 2"
     688        return SetPartitionsAkhalf_k._repr_(self) + " and with block size 2"
    680689
    681690   
    682691    def __contains__(self, x):
    class SetPartitionsBkhalf_k(SetPartition 
    737746             {{1, 2}, {-3, -1}, {4, -4}, {3, -2}}]
    738747        """
    739748        set = range(1,self.k+1) + map(lambda x: -1*x, range(1,self.k+1))
    740         for sp in set_partition.SetPartitions(set, [2]*(len(set)/2) ):
    741             yield sp + Set([Set([self.k+1, -self.k -1])])
     749        for sp in SetPartitions(set, [2]*(len(set)/2) ):
     750            yield self.element_class(self, Set(list(sp)) + Set([Set([self.k+1, -self.k -1])]))
    742751
    743752#####
    744753#P_k#
    SetPartitionsPk.__doc__ = ( 
    777786
    778787    """)
    779788class SetPartitionsPk_k(SetPartitionsAk_k):
    780     def __repr__(self):
     789    def _repr_(self):
    781790        """
    782791        TESTS::
    783792       
    784             sage: repr(SetPartitionsPk(3))
    785             'Set partitions of {1, ..., 3, -1, ..., -3} that are planar'
     793            sage: SetPartitionsPk(3)
     794            Set partitions of {1, ..., 3, -1, ..., -3} that are planar
    786795        """
    787         return SetPartitionsAk_k.__repr__(self) + " that are planar"
     796        return SetPartitionsAk_k._repr_(self) + " that are planar"
    788797
    789798    def __contains__(self, x):
    790799        """
    class SetPartitionsPk_k(SetPartitionsAk_ 
    842851        """
    843852        for sp in SetPartitionsAk_k.__iter__(self):
    844853            if is_planar(sp):
    845                 yield sp
     854                yield self.element_class(self, sp)
    846855
    847856class SetPartitionsPkhalf_k(SetPartitionsAkhalf_k):
    848857    def __contains__(self, x):
    class SetPartitionsPkhalf_k(SetPartition 
    865874       
    866875        return True
    867876
    868     def __repr__(self):
     877    def _repr_(self):
    869878        """
    870879        TESTS::
    871880       
    872881            sage: repr( SetPartitionsPk(2.5) )
    873882            'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and that are planar'
    874883        """
    875         return SetPartitionsAkhalf_k.__repr__(self) + " and that are planar"
     884        return SetPartitionsAkhalf_k._repr_(self) + " and that are planar"
    876885
    877886    def cardinality(self):
    878887        """
    class SetPartitionsPkhalf_k(SetPartition 
    898907        """
    899908        for sp in SetPartitionsAkhalf_k.__iter__(self):
    900909            if is_planar(sp):
    901                 yield sp
     910                yield self.element_class(self, sp)
    902911
    903912
    904913#####
    SetPartitionsTk.__doc__ = ( 
    936945
    937946    """)
    938947class SetPartitionsTk_k(SetPartitionsBk_k):
    939     def __repr__(self):
     948    def _repr_(self):
    940949        """
    941950        TESTS::
    942951       
    943             sage: repr(SetPartitionsTk(3))
    944             'Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 and that are planar'
     952            sage: SetPartitionsTk(3)
     953            Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 and that are planar
    945954        """
    946         return SetPartitionsBk_k.__repr__(self) + " and that are planar"
     955        return SetPartitionsBk_k._repr_(self) + " and that are planar"
    947956
    948957    def __contains__(self, x):
    949958        """
    class SetPartitionsTk_k(SetPartitionsBk_ 
    9941003        """
    9951004        for sp in SetPartitionsBk_k.__iter__(self):
    9961005            if is_planar(sp):
    997                 yield sp
     1006                yield self.element_class(self, sp)
    9981007
    9991008class SetPartitionsTkhalf_k(SetPartitionsBkhalf_k):
    10001009    def __contains__(self, x):
    class SetPartitionsTkhalf_k(SetPartition 
    10171026       
    10181027        return True
    10191028
    1020     def __repr__(self):
     1029    def _repr_(self):
    10211030        """
    10221031        TESTS::
    10231032       
    1024             sage: repr(SetPartitionsTk(2.5))
    1025             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 and that are planar'
     1033            sage: SetPartitionsTk(2.5)
     1034            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 and that are planar
    10261035        """
    1027         return SetPartitionsBkhalf_k.__repr__(self) + " and that are planar"
     1036        return SetPartitionsBkhalf_k._repr_(self) + " and that are planar"
    10281037
    10291038    def cardinality(self):
    10301039        """
    class SetPartitionsTkhalf_k(SetPartition 
    10521061        """
    10531062        for sp in SetPartitionsBkhalf_k.__iter__(self):
    10541063            if is_planar(sp):
    1055                 yield sp
     1064                yield self.element_class(self, sp)
    10561065
    10571066
    10581067
    class SetPartitionsRk_k(SetPartitionsAk_ 
    10731082        self.k = k
    10741083        SetPartitionsAk_k.__init__(self, k)
    10751084
    1076     def __repr__(self):
     1085    def _repr_(self):
    10771086        """
    10781087        TESTS::
    10791088       
    1080             sage: repr(SetPartitionsRk(3))
    1081             'Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block'
     1089            sage: SetPartitionsRk(3)
     1090            Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block
    10821091        """
    1083         return SetPartitionsAk_k.__repr__(self) + " with at most 1 positive and negative entry in each block"
     1092        return SetPartitionsAk_k._repr_(self) + " with at most 1 positive and negative entry in each block"
    10841093
    10851094    def __contains__(self, x):
    10861095        """
    class SetPartitionsRk_k(SetPartitionsAk_ 
    11411150        positives = Set(range(1, self.k+1))
    11421151        negatives = Set( [ -i for i in positives ] )
    11431152
    1144         yield to_set_partition([],self.k)
     1153        yield self.element_class(self, to_set_partition([],self.k))
    11451154        for n in range(1,self.k+1):
    11461155            for top in Subsets(positives, n):
    11471156                t = list(top)
    class SetPartitionsRk_k(SetPartitionsAk_ 
    11491158                    b = list(bottom)
    11501159                    for permutation in Permutations(n):
    11511160                        l = [ [t[i], b[ permutation[i] - 1 ] ] for i in range(n) ]
    1152                         yield to_set_partition(l, k=self.k)
     1161                        yield self.element_class(self, to_set_partition(l, k=self.k))
    11531162
    11541163class SetPartitionsRkhalf_k(SetPartitionsAkhalf_k):
    11551164    def __contains__(self, x):
    class SetPartitionsRkhalf_k(SetPartition 
    11861195       
    11871196        return True
    11881197
    1189     def __repr__(self):
     1198    def _repr_(self):
    11901199        """
    11911200        TESTS::
    11921201       
    1193             sage: repr(SetPartitionsRk(2.5))
    1194             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block'
     1202            sage: SetPartitionsRk(2.5)
     1203            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block
    11951204        """
    1196         return SetPartitionsAkhalf_k.__repr__(self) + " and with at most 1 positive and negative entry in each block"
     1205        return SetPartitionsAkhalf_k._repr_(self) + " and with at most 1 positive and negative entry in each block"
    11971206
    11981207    def cardinality(self):
    11991208        """
    class SetPartitionsRkhalf_k(SetPartition 
    12131222        TESTS::
    12141223       
    12151224            sage: R2p5 = SetPartitionsRk(2.5)
    1216             sage: list(R2p5) #random due to sets
     1225            sage: L = list(R2p5); L #random due to sets
    12171226            [{{-2}, {-1}, {3, -3}, {2}, {1}},
    12181227             {{-2}, {3, -3}, {2}, {1, -1}},
    12191228             {{-1}, {3, -3}, {2}, {1, -2}},
    class SetPartitionsRkhalf_k(SetPartition 
    12211230             {{-1}, {2, -2}, {3, -3}, {1}},
    12221231             {{2, -2}, {3, -3}, {1, -1}},
    12231232             {{2, -1}, {3, -3}, {1, -2}}]
    1224             sage: len(_)
     1233            sage: len(L)
    12251234            7
    12261235        """
    12271236        positives = Set(range(1, self.k+1))
    12281237        negatives = Set( [ -i for i in positives ] )
    12291238       
    1230         yield to_set_partition([[self.k+1, -self.k-1]], self.k+1)
     1239        yield self.element_class(self, to_set_partition([[self.k+1, -self.k-1]], self.k+1))
    12311240        for n in range(1,self.k+1):
    12321241            for top in Subsets(positives, n):
    12331242                t = list(top)
    class SetPartitionsRkhalf_k(SetPartition 
    12351244                    b = list(bottom)
    12361245                    for permutation in Permutations(n):
    12371246                        l = [ [t[i], b[ permutation[i] - 1 ] ] for i in range(n) ] + [ [self.k+1, -self.k-1] ]
    1238                         yield to_set_partition(l, k=self.k+1)
     1247                        yield self.element_class(self, to_set_partition(l, k=self.k+1))
    12391248
    12401249
    12411250SetPartitionsPRk = functools.partial(create_set_partition_function,"PR")
    class SetPartitionsPRk_k(SetPartitionsRk 
    12551264        self.k = k
    12561265        SetPartitionsRk_k.__init__(self, k)
    12571266
    1258     def __repr__(self):
     1267    def _repr_(self):
    12591268        """
    12601269        TESTS::
    12611270       
    1262             sage: repr(SetPartitionsPRk(3))
    1263             'Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block and that are planar'
     1271            sage: SetPartitionsPRk(3)
     1272            Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block and that are planar
    12641273        """
    1265         return SetPartitionsRk_k.__repr__(self) + " and that are planar"
     1274        return SetPartitionsRk_k._repr_(self) + " and that are planar"
    12661275
    12671276    def __contains__(self, x):
    12681277        """
    class SetPartitionsPRk_k(SetPartitionsRk 
    13111320        positives = Set(range(1, self.k+1))
    13121321        negatives = Set( [ -i for i in positives ] )
    13131322
    1314         yield to_set_partition([], self.k)
     1323        yield self.element_class(self, to_set_partition([], self.k))
    13151324        for n in range(1,self.k+1):
    13161325            for top in Subsets(positives, n):
    13171326                t = list(top)
    class SetPartitionsPRk_k(SetPartitionsRk 
    13201329                    b = list(bottom)
    13211330                    b.sort(reverse=True)
    13221331                    l = [ [t[i], b[ i ] ] for i in range(n) ]
    1323                     yield to_set_partition(l, k=self.k)
     1332                    yield self.element_class(self, to_set_partition(l, k=self.k))
    13241333
    13251334class SetPartitionsPRkhalf_k(SetPartitionsRkhalf_k):
    13261335    def __contains__(self, x):
    class SetPartitionsPRkhalf_k(SetPartitio 
    13441353       
    13451354        return True
    13461355
    1347     def __repr__(self):
     1356    def _repr_(self):
    13481357        """
    13491358        TESTS::
    13501359       
    1351             sage: repr(SetPartitionsPRk(2.5))
    1352             'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block and that are planar'
     1360            sage: SetPartitionsPRk(2.5)
     1361            Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block and that are planar
    13531362        """
    1354         return SetPartitionsRkhalf_k.__repr__(self) + " and that are planar"
     1363        return SetPartitionsRkhalf_k._repr_(self) + " and that are planar"
    13551364
    13561365    def cardinality(self):
    13571366        """
    class SetPartitionsPRkhalf_k(SetPartitio 
    13701379        """
    13711380        TESTS::
    13721381       
    1373             sage: list(SetPartitionsPRk(2.5))
    1374             [{{-2}, {-1}, {3, -3}, {2}, {1}},
    1375              {{-2}, {3, -3}, {2}, {1, -1}},
    1376              {{-1}, {3, -3}, {2}, {1, -2}},
    1377              {{-2}, {2, -1}, {3, -3}, {1}},
    1378              {{-1}, {2, -2}, {3, -3}, {1}},
    1379              {{2, -2}, {3, -3}, {1, -1}}]
    1380             sage: len(_)
     1382            sage: L = list(SetPartitionsPRk(2.5)); L
     1383            [{{3, -3}, {-2}, {-1}, {1}, {2}},
     1384             {{3, -3}, {-2}, {1, -1}, {2}},
     1385             {{3, -3}, {1, -2}, {-1}, {2}},
     1386             {{3, -3}, {-2}, {2, -1}, {1}},
     1387             {{3, -3}, {2, -2}, {-1}, {1}},
     1388             {{3, -3}, {2, -2}, {1, -1}}]
     1389            sage: len(L)
    13811390            6
    13821391        """
    13831392        positives = Set(range(1, self.k+1))
    13841393        negatives = Set( [ -i for i in positives ] )
    13851394       
    1386         yield to_set_partition([[self.k+1, -self.k-1]],k=self.k+1)
     1395        yield self.element_class(self, to_set_partition([[self.k+1, -self.k-1]],k=self.k+1))
    13871396        for n in range(1,self.k+1):
    13881397            for top in Subsets(positives, n):
    13891398                t = list(top)
    class SetPartitionsPRkhalf_k(SetPartitio 
    13921401                    b = list(bottom)
    13931402                    b.sort(reverse=True)
    13941403                    l = [ [t[i], b[ i ] ] for i in range(n) ] + [ [self.k+1, -self.k-1] ]
    1395                     yield to_set_partition(l, k=self.k+1)
     1404                    yield self.element_class(self, to_set_partition(l, k=self.k+1))
    13961405
    13971406#########################################################
    13981407#Algebras
    def set_partition_composition(sp1, sp2): 
    18351844
    18361845
    18371846    return ( Set(res), total_removed )
     1847
  • sage/combinat/set_partition.py

    diff --git a/sage/combinat/set_partition.py b/sage/combinat/set_partition.py
    a b  
    11r"""
    22Set Partitions
    33
    4 A set partition s of a set set is a partition of set, into subsets
    5 called parts and represented as a set of sets. By extension, a set
    6 partition of a nonnegative integer n is the set partition of the
    7 integers from 1 to n. The number of set partitions of n is called
    8 the n-th Bell number.
    9 
    10 There is a natural integer partition associated with a set
    11 partition, that is the non-decreasing sequence of sizes of all its
    12 parts.
    13 
    14 There is a classical lattice associated with all set partitions of
    15 n. The infimum of two set partitions is the set partition obtained
    16 by intersecting all the parts of both set partitions. The supremum
    17 is obtained by transitive closure of the relation i related to j
    18 iff they are in the same part in at least one of the set
    19 partitions.
    20 
    21 EXAMPLES: There are 5 set partitions of the set 1,2,3.
    22 
    23 ::
    24 
    25     sage: SetPartitions(3).cardinality()
    26     5
    27 
    28 Here is the list of them
    29 
    30 ::
    31 
    32     sage: SetPartitions(3).list() #random due to the sets
    33     [{{1, 2, 3}}, {{2, 3}, {1}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{2}, {3}, {1}}]
    34 
    35 There are 6 set partitions of 1,2,3,4 whose underlying partition is
    36 [2, 1, 1]::
    37 
    38     sage: SetPartitions(4, [2,1,1]).list() #random due to the sets
    39     [{{3, 4}, {2}, {1}},
    40      {{2, 4}, {3}, {1}},
    41      {{4}, {2, 3}, {1}},
    42      {{1, 4}, {2}, {3}},
    43      {{1, 3}, {4}, {2}},
    44      {{1, 2}, {4}, {3}}]
    45 
    464AUTHORS:
    475
    486- Mike Hansen
    497
    508- MuPAD-Combinat developers (for algorithms and design inspiration).
     9
     10- Travis Scrimshaw (2013-02-28): Removed ``CombinatorialClass`` and added
     11  entry point through :class:`SetPartition`.
    5112"""
    5213#*****************************************************************************
    5314#       Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
    AUTHORS: 
    6526#*****************************************************************************
    6627
    6728from sage.sets.set import Set, is_Set, Set_object_enumerated
    68 import sage.combinat.partition as partition
    69 import sage.rings.integer
    70 import __builtin__
     29
    7130import itertools
    72 from cartesian_product import CartesianProduct
     31import copy
     32
     33from sage.structure.parent import Parent
     34from sage.structure.unique_representation import UniqueRepresentation
     35from sage.structure.list_clone import ClonableArray
     36from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
     37from sage.misc.classcall_metaclass import ClasscallMetaclass
     38from sage.rings.infinity import infinity
     39from sage.rings.integer import Integer
     40
     41from sage.combinat.cartesian_product import CartesianProduct
     42from sage.combinat.misc import IterableFunctionCall
     43from sage.combinat.combinatorial_map import combinatorial_map
    7344import sage.combinat.subset as subset
    74 import sage.combinat.set_partition_ordered as set_partition_ordered
    75 import copy
    76 from combinat import CombinatorialClass, bell_number, stirling_number2
    77 from misc import IterableFunctionCall
     45from sage.combinat.partition import Partition, Partitions
     46from sage.combinat.set_partition_ordered import OrderedSetPartitions
     47from sage.combinat.combinat import bell_number, stirling_number2
     48from sage.combinat.permutation import Permutation
    7849
     50class SetPartition(ClonableArray):
     51    """
     52    A partition of a set.
    7953
    80 def SetPartitions(s, part=None):
     54    A set partition `p` of a set `S` is a partition of `S` into subsets
     55    called parts and represented as a set of sets. By extension, a set
     56    partition of a nonnegative integer `n` is the set partition of the
     57    integers from 1 to `n`. The number of set partitions of `n` is called
     58    the `n`-th Bell number.
     59
     60    There is a natural integer partition associated with a set partition,
     61    that is the non-decreasing sequence of sizes of all its parts.
     62
     63    There is a classical lattice associated with all set partitions of
     64    `n`. The infimum of two set partitions is the set partition obtained
     65    by intersecting all the parts of both set partitions. The supremum
     66    is obtained by transitive closure of the relation `i` related to `j`
     67    if and only if they are in the same part in at least one of the set
     68    partitions.
     69
     70    EXAMPLES: There are 5 set partitions of the set `\{1,2,3\}`.
     71
     72    ::
     73
     74        sage: SetPartitions(3).cardinality()
     75        5
     76
     77    Here is the list of them
     78
     79    ::
     80
     81        sage: SetPartitions(3).list()
     82        [{{1, 2, 3}},
     83         {{1}, {2, 3}},
     84         {{1, 3}, {2}},
     85         {{1, 2}, {3}},
     86         {{1}, {2}, {3}}]
     87
     88    There are 6 set partitions of `\{1,2,3,4\}` whose underlying partition is
     89    `[2, 1, 1]`::
     90
     91        sage: SetPartitions(4, [2,1,1]).list()
     92        [{{1}, {2}, {3, 4}},
     93         {{1}, {2, 4}, {3}},
     94         {{1}, {2, 3}, {4}},
     95         {{1, 4}, {2}, {3}},
     96         {{1, 3}, {2}, {4}},
     97         {{1, 2}, {3}, {4}}]
     98
     99    Since :trac:`14140`, we can create a set partition directly by
     100    :class:`SetPartition` which creates the parent object by taking the
     101    union of the partitions passed in. However it is recommended and
     102    (marginally) faster to create the parent first and then create the set
     103    partition from that. ::
     104
     105        sage: s = SetPartition([[1,3],[2,4]]); s
     106        {{1, 3}, {2, 4}}
     107        sage: s.parent()
     108        Set partitions of {1, 2, 3, 4}
    81109    """
     110    __metaclass__ = ClasscallMetaclass
     111
     112    @staticmethod
     113    def __classcall_private__(cls, parts):
     114        """
     115        Create a set partition from ``parts`` with the appropriate parent.
     116
     117        EXAMPLES::
     118
     119            sage: s = SetPartition([[1,3],[2,4]]); s
     120            {{1, 3}, {2, 4}}
     121            sage: s.parent()
     122            Set partitions of {1, 2, 3, 4}
     123        """
     124        P = SetPartitions( _union(Set(map(Set, parts))) )
     125        return P.element_class(P, parts)
     126
     127    def __init__(self, parent, s):
     128        """
     129        Initialize ``self``.
     130
     131        EXAMPLES::
     132
     133            sage: S = SetPartitions(4)
     134            sage: s = S([[1,3],[2,4]])
     135            sage: TestSuite(s).run()
     136            sage: SetPartition([])
     137            {}
     138        """
     139        ClonableArray.__init__(self, parent, sorted(map(Set, s), key=min))
     140
     141    def check(self):
     142        """
     143        Check that we are a valid ordered set partition.
     144
     145        EXAMPLES::
     146
     147            sage: OS = OrderedSetPartitions(4)
     148            sage: s = OS([[1, 3], [2, 4]])
     149            sage: s.check()
     150        """
     151        assert self in self.parent()
     152
     153    def __mul__(self, other):
     154        r"""
     155        The product of two set partitions (resp. compositions) is defined
     156        as the intersection (resp. ordered) of sets appearing in the
     157        partitions (resp. compositions).
     158
     159        EXAMPLES::
     160
     161            sage: x = SetPartition([ [1,2], [3,5,4] ])
     162            sage: y = SetPartition(( (3,1,2), (5,4) ))
     163            sage: x * y
     164            {{1, 2}, {3}, {4, 5}}
     165        """
     166        new_composition = []
     167        for B in self:
     168           for C in other:
     169                BintC = B.intersection(C)
     170                if BintC:
     171                    new_composition.append(BintC)
     172        return self.__class__(self.parent(), new_composition)
     173
     174    def _repr_(self):
     175        """
     176        Return string representation of ``self``.
     177
     178        EXAMPLES::
     179
     180            sage: S = SetPartitions(4)
     181            sage: S([[1,3],[2,4]])
     182            {{1, 3}, {2, 4}}
     183        """
     184        return '{' + repr(list(self))[1:-1] + '}'
     185
     186    def _latex_(self):
     187        r"""
     188        Return a `\LaTeX` string representation.
     189
     190        EXAMPLES::
     191
     192            sage: x = SetPartition([[1,2], [3,5,4]])
     193            sage: latex(x)
     194            \{\{1, 2\}, \{3, 4, 5\}\}
     195        """
     196        return repr(self).replace("{",r"\{").replace("}",r"\}")
     197
     198    cardinality = ClonableArray.__len__
     199
     200    def inf(self, t):
     201        """
     202        Return the infimum of ``self`` and ``t`` in the classical set partition
     203        lattice.
     204
     205        The infimum of two set partitions is the set partition obtained
     206        by intersecting all the parts of both set partitions.
     207
     208        EXAMPLES::
     209
     210            sage: S = SetPartitions(4)
     211            sage: sp1 = S([[2,3,4], [1]])
     212            sage: sp2 = S([[1,3], [2,4]])
     213            sage: s = S([[2,4], [3], [1]])
     214            sage: sp1.inf(sp2) == s
     215            True
     216        """
     217        temp = [ss.intersection(ts) for ss in self for ts in t]
     218        temp = filter(lambda x: x != Set([]), temp)
     219        return self.__class__(self.parent(), temp)
     220
     221    def sup(self,t):
     222        """
     223        Return the supremum of ``self`` and ``t`` in the classical set
     224        partition lattice.
     225
     226        The supremum is obtained by transitive closure of the relation `i`
     227        related to `j` if and only if they are in the same part in at least
     228        one of the set partitions.
     229       
     230        EXAMPLES::
     231
     232            sage: S = SetPartitions(4)
     233            sage: sp1 = S([[2,3,4], [1]])
     234            sage: sp2 = S([[1,3], [2,4]])
     235            sage: s = S([[1,2,3,4]])
     236            sage: sp1.sup(sp2) == s
     237            True
     238        """
     239        res = Set(list(self))
     240        for p in t:
     241            inters = Set(filter(lambda x: x.intersection(p) != Set([]), list(res)))
     242            res = res.difference(inters).union(_set_union(inters))
     243        return self.__class__(self.parent(), res)
     244
     245    @combinatorial_map(name='shape')
     246    def shape(self):
     247        r"""
     248        Return the integer partition whose parts are the sizes of the sets
     249        in ``self``.
     250
     251        EXAMPLES::
     252
     253            sage: S = SetPartitions(5)
     254            sage: x = S([[1,2], [3,5,4]])
     255            sage: x.shape()
     256            [3, 2]
     257            sage: y = S([[2], [3,1], [5,4]])
     258            sage: y.shape()
     259            [2, 2, 1]
     260        """
     261        from sage.combinat.partition import Partition
     262        return Partition(sorted(map(len, self), reverse=True))
     263
     264    # we define aliases for shape()
     265    shape_partition = shape
     266    to_partition = shape
     267
     268    @combinatorial_map(name='to permutation')
     269    def to_permutation(self):
     270        """
     271        Convert ``self`` to a permutation by considering the partitions as
     272        cycles.
     273
     274        EXAMPLES::
     275
     276            sage: s = SetPartition([[1,3],[2,4]])
     277            sage: s.to_permutation()
     278            [3, 4, 1, 2]
     279        """
     280        return Permutation(tuple( map(tuple, self.standard_form()) ))
     281
     282    def standard_form(self):
     283        """
     284        Return ``self`` as a list of lists.
     285       
     286        EXAMPLES::
     287       
     288            sage: [x.standard_form() for x in SetPartitions(4, [2,2])]
     289            [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
     290        """
     291        return list(map(list, self))
     292
     293    def apply_permutation(self, p):
     294        r"""
     295        Apply ``p`` to the underlying set of ``self``.
     296
     297        INPUT:
     298
     299        - ``p`` -- A permutation
     300
     301        EXAMPLES::
     302
     303            sage: x = SetPartition([[1,2], [3,5,4]])
     304            sage: p = Permutation([2,1,4,5,3])
     305            sage: x.apply_permutation(p)
     306            {{1, 2}, {3, 4, 5}}
     307            sage: q = Permutation([3,2,1,5,4])
     308            sage: x.apply_permutation(q)
     309            {{1, 4, 5}, {2, 3}}
     310        """
     311        return self.__class__(self.parent(), [Set(map(p, B)) for B in self])
     312
     313    def is_noncrossing(self):
     314        r"""
     315        Check if ``self`` is non crossing.
     316
     317        EXAMPLES::
     318
     319            sage: x = SetPartition([[1,2],[3,4]])
     320            sage: x.is_noncrossing()
     321            True
     322            sage: x = SetPartition([[1,3],[2,4]])
     323            sage: x.is_noncrossing()
     324            False
     325
     326        AUTHOR: Florent Hivert
     327        """
     328        l = list(self)
     329        mins = map(min, l)
     330        maxs = map(max, l)
     331
     332        for i in range(1, len(l)):
     333            for j in range(i):
     334                poss = [mins[i], maxs[i], mins[j], maxs[j]]
     335                possort = sorted(poss)
     336                cont = [possort.index(mins[i]), possort.index(maxs[i])]
     337                if cont == [0,2] or cont == [1,3]:
     338                    return False
     339                if (cont == [0,3] and
     340                    any(mins[j] < x < maxs[j] for x in l[i])):
     341                    return False
     342                if (cont == [1,2] and
     343                    any(mins[i] < x < maxs[i] for x in l[j])):
     344                    return False
     345        return True
     346
     347class SetPartitions(Parent, UniqueRepresentation):
     348    r"""
    82349    An unordered partition of a set `S` is a set of pairwise
    83350    disjoint nonempty subsets with union `S` and is represented
    84351    by a sorted list of such subsets.
    85352   
    86     SetPartitions(s) returns the class of all set partitions of the set
    87     s, which can be a set or a string; if a string, each character is
     353    ``SetPartitions(s)`` returns the class of all set partitions of the set
     354    ``s``, which can be a set or a string; if a string, each character is
    88355    considered an element.
    89356   
    90     SetPartitions(n), where n is an integer, returns the class of all
    91     set partitions of the set [1, 2,..., n].
     357    ``SetPartitions(n)``, where n is an integer, returns the class of all
     358    set partitions of the set `\{1, 2, \ldots, n\}`.
    92359   
    93     You may specify a second argument k. If k is an integer,
    94     SetPartitions returns the class of set partitions into k parts; if
    95     it is an integer partition, SetPartitions returns the class of set
    96     partitions whose block sizes correspond to that integer partition.
     360    You may specify a second argument `k`. If `k` is an integer,
     361    :class:`SetPartitions` returns the class of set partitions into `k` parts;
     362    if it is an integer partition, :class:`SetPartitions` returns the class of
     363    set partitions whose block sizes correspond to that integer partition.
    97364   
    98365    The Bell number `B_n`, named in honor of Eric Temple Bell,
    99     is the number of different partitions of a set with n elements.
     366    is the number of different partitions of a set with `n` elements.
    100367   
    101368    EXAMPLES::
    102369   
    103370        sage: S = [1,2,3,4]
    104371        sage: SetPartitions(S,2)
    105         Set partitions of [1, 2, 3, 4] with 2 parts
     372        Set partitions of {1, 2, 3, 4} with 2 parts
    106373        sage: SetPartitions([1,2,3,4], [3,1]).list()
    107         [{{2, 3, 4}, {1}}, {{1, 3, 4}, {2}}, {{3}, {1, 2, 4}}, {{4}, {1, 2, 3}}]
     374        [{{1}, {2, 3, 4}}, {{1, 3, 4}, {2}}, {{1, 2, 4}, {3}}, {{1, 2, 3}, {4}}]
    108375        sage: SetPartitions(7, [3,3,1]).cardinality()
    109376        70
    110    
    111     In strings, repeated letters are considered distinct::
    112    
    113         sage: SetPartitions('aabcd').cardinality()
    114         52
     377
     378    In strings, repeated letters are not considered distinct as of
     379    :trac:`14140`::
     380
    115381        sage: SetPartitions('abcde').cardinality()
    116382        52
    117    
     383        sage: SetPartitions('aabcd').cardinality()
     384        15
     385
    118386    REFERENCES:
    119387
    120     - http://en.wikipedia.org/wiki/Partition_of_a_set
     388    - :wikipedia:`Partition_of_a_set`
    121389    """
    122     if isinstance(s, (int, sage.rings.integer.Integer)):
    123         set = range(1, s+1)
    124     elif isinstance(s, str):
    125         set = [x for x in s]
    126     else:
    127         set = s
    128    
    129     if part is not None:
    130         if isinstance(part, (int, sage.rings.integer.Integer)):
    131             if len(set) < part:
    132                 raise ValueError, "part must be <= len(set)"
    133             else:
    134                 return SetPartitions_setn(set,part)
    135         else:
    136             if part not in partition.Partitions(len(set)):
    137                 raise ValueError, "part must be a partition of %s"%len(set)
    138             else:
    139                 return SetPartitions_setparts(set, [partition.Partition(part)])
    140     else:
    141         return SetPartitions_set(set)
     390    @staticmethod
     391    def __classcall_private__(cls, s, part=None):
     392        """
     393        Normalize input to ensure a unique representation.
    142394
     395        EXAMPLES::
    143396
    144 
    145 class SetPartitions_setparts(CombinatorialClass):
    146     Element = Set_object_enumerated
    147     def __init__(self, set, parts):
    148         """
    149         TESTS::
    150        
    151             sage: S = SetPartitions(4, [2,2])
    152             sage: S == loads(dumps(S))
     397            sage: S = SetPartitions(4)
     398            sage: T = SetPartitions([1,2,3,4])
     399            sage: S is T
    153400            True
    154401        """
    155         self.set = set
    156         self.parts = parts
     402        if isinstance(s, (int, Integer)):
     403            s = frozenset(range(1, s+1))
     404        else:
     405            try:
     406                if s.cardinality() == infinity:
     407                    raise ValueError("The set must be finite")
     408            except AttributeError:
     409                pass
     410            s = frozenset(s)
     411       
     412        if part is not None:
     413            if isinstance(part, (int, Integer)):
     414                if len(s) < part:
     415                    raise ValueError("part must be <= len(set)")
     416                else:
     417                    return SetPartitions_setn(s, part)
     418            else:
     419                if part not in Partitions(len(s)):
     420                    raise ValueError("part must be a partition of %s"%len(s))
     421                else:
     422                    return SetPartitions_setparts(s, Partition(part))
     423        else:
     424            return SetPartitions_set(s)
    157425
    158     def __repr__(self):
     426    def __init__(self, s):
    159427        """
    160         TESTS::
    161        
    162             sage: repr(SetPartitions(4, [2,2]))
    163             'Set partitions of [1, 2, 3, 4] with sizes in [[2, 2]]'
     428        Initialize ``self``.
     429
     430        EXAMPLES::
     431
     432            sage: S = SetPartitions(3)
     433            sage: TestSuite(S).run()
     434            sage: SetPartitions(0).list()
     435            [{}]
     436            sage: SetPartitions([]).list()
     437            [{}]
    164438        """
    165         return "Set partitions of %s with sizes in %s"%(self.set, self.parts)
     439        self._set = s
     440        Parent.__init__(self, category=FiniteEnumeratedSets())
    166441
    167442    def __contains__(self, x):
    168443        """
    class SetPartitions_setparts(Combinatori 
    172447            sage: all([sp in S for sp in S])
    173448            True
    174449        """
    175         #x must be a set
    176         if not is_Set(x):
     450        #x must be a set, if it's not, make it into one
     451        if not (isinstance(x, (SetPartition, set, frozenset)) or is_Set(x)):
    177452            return False
    178453
    179454        #Make sure that the number of elements match up
    180         if sum(map(len, x)) != len(self.set):
     455        if sum(map(len, x)) != len(self._set):
    181456            return False
    182457
    183         #Check to make sure each element of x
    184         #is a set
     458        #Check to make sure each element of x is a set
    185459        u = Set([])
    186460        for s in x:
    187             if not is_Set(s):
     461            if not (isinstance(s, (set, frozenset)) or is_Set(s)):
    188462                return False
    189             u = u.union(s)
     463            u = u.union(Set(s))
    190464
    191465        #Make sure that the union of all the
    192466        #sets is the original set
    193         if u != Set(self.set):
     467        if u != Set(self._set):
    194468            return False
    195469
    196470        return True
    197471
    198     def cardinality(self):
     472    def _element_constructor_(self, s):
    199473        """
    200         Returns the number of set partitions of set. This number is given
    201         by the n-th Bell number where n is the number of elements in the
    202         set.
    203        
    204         If a partition or partition length is specified, then count will
    205         generate all of the set partitions.
    206        
     474        Construct an element of ``self`` from ``s``.
     475
     476        INPUT:
     477
     478        - ``s`` -- A set of sets
     479
    207480        EXAMPLES::
    208        
    209             sage: SetPartitions([1,2,3,4]).cardinality()
    210             15
    211             sage: SetPartitions(3).cardinality()
    212             5
    213             sage: SetPartitions(3,2).cardinality()
    214             3
    215             sage: SetPartitions([]).cardinality()
    216             1
     481
     482            sage: S = SetPartitions(4)
     483            sage: S([[1,3],[2,4]])
     484            {{1, 3}, {2, 4}}
     485            sage: S = SetPartitions([])
     486            sage: S([])
     487            {}
    217488        """
    218         return len(self.list())
     489        if isinstance(s, SetPartition):
     490            if s.parent() == self:
     491                return s
     492            raise ValueError("Cannot convert %s into an element of %s"%(s, self))
     493        return self.element_class(self, s)
    219494
     495    Element = SetPartition
    220496
    221497    def _iterator_part(self, part):
    222498        """
    223         Returns an iterator for the set partitions with block sizes
     499        Return an iterator for the set partitions with block sizes
    224500        corresponding to the partition part.
    225501       
    226502        INPUT:
    227        
    228        
    229         -  ``part`` - a Partition object
    230        
    231        
     503
     504        -  ``part`` -- a :class:`Partition` object
     505
    232506        EXAMPLES::
    233507       
    234508            sage: S = SetPartitions(3)
    class SetPartitions_setparts(Combinatori 
    239513            sage: len(list(S._iterator_part(Partition([2,1])))) == S21.cardinality()
    240514            True
    241515        """
    242         set = self.set
    243 
    244516        nonzero = []
    245517        expo = [0]+part.to_exp()
    246518
    class SetPartitions_setparts(Combinatori 
    250522
    251523        taillesblocs = map(lambda x: (x[0])*(x[1]), nonzero)
    252524
    253         blocs = set_partition_ordered.OrderedSetPartitions(copy.copy(set), taillesblocs).list()
     525        blocs = OrderedSetPartitions(self._set, taillesblocs)
    254526
    255527        for b in blocs:
    256             lb = [ IterableFunctionCall(_listbloc, nonzero[i][0], nonzero[i][1], b[i]) for i in range(len(nonzero)) ]
     528            lb = [IterableFunctionCall(_listbloc, nonzero[i][0], nonzero[i][1], b[i]) for i in range(len(nonzero))]
    257529            for x in itertools.imap(lambda x: _union(x), CartesianProduct( *lb )):
    258530                yield x
    259531
     532    def is_less_than(self, s, t):
     533        """
     534        Check if `s < t` in the ordering on set partitions.
    260535
    261    
     536        EXAMPLES::
     537
     538            sage: S = SetPartitions(4)
     539            sage: s = S([[1,3],[2,4]])
     540            sage: t = S([[1],[2],[3],[4]])
     541            sage: S.is_less_than(t, s)
     542            True
     543        """
     544        if s.parent()._set != t.parent()._set:
     545            raise ValueError("cannot compare partitions of different sets")
     546
     547        if s == t:
     548            return False
     549
     550        for p in s:
     551            f = lambda z: z.intersection(p) != Set([])
     552            if len(filter(f, list(t)) ) != 1:
     553                return False
     554        return True
     555
     556    lt = is_less_than
     557
     558class SetPartitions_setparts(SetPartitions):
     559    r"""
     560    Class of all set partitions with fixed partition sizes corresponding to
     561    and integer partition `\lambda`.
     562    """
     563    @staticmethod
     564    def __classcall_private__(cls, s, parts):
     565        """
     566        Normalize input to ensure a unique representation.
     567
     568        EXAMPLES::
     569
     570            sage: S = SetPartitions(4, [2,2])
     571            sage: T = SetPartitions([1,2,3,4], Partition([2,2]))
     572            sage: S is T
     573            True
     574        """
     575        if isinstance(s, (int, Integer)):
     576            s = xrange(1, s+1)
     577        return super(SetPartitions_setparts, cls).__classcall__(cls, frozenset(s), Partition(parts))
     578
     579    def __init__(self, s, parts):
     580        """
     581        TESTS::
     582       
     583            sage: S = SetPartitions(4, [2,2])
     584            sage: S == loads(dumps(S))
     585            True
     586        """
     587        SetPartitions.__init__(self, s)
     588        self.parts = parts
     589
     590    def _repr_(self):
     591        """
     592        TESTS::
     593       
     594            sage: SetPartitions(4, [2,2])
     595            Set partitions of {1, 2, 3, 4} with sizes in [2, 2]
     596        """
     597        return "Set partitions of %s with sizes in %s"%(Set(self._set), self.parts)
     598
     599    def cardinality(self):
     600        """
     601        Return the cardinality of ``self``.
     602
     603        EXAMPLES::
     604
     605            sage: SetPartitions(3, [2,1]).cardinality()
     606            3
     607        """
     608        return len(self.list())
     609
    262610    def __iter__(self):
    263611        """
    264612        An iterator for all the set partitions of the set.
    265        
     613
    266614        EXAMPLES::
    267        
    268             sage: SetPartitions(3).list()
    269             [{{1, 2, 3}}, {{2, 3}, {1}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{2}, {3}, {1}}]
     615
     616            sage: SetPartitions(3, [2,1]).list()
     617            [{{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}]
    270618        """
    271         for p in self.parts:
    272             for sp in self._iterator_part(p):
    273                 yield sp
     619        for sp in self._iterator_part(self.parts):
     620            yield self.element_class(self, sp)
    274621
     622class SetPartitions_setn(SetPartitions):
     623    @staticmethod
     624    def __classcall_private__(cls, s, n):
     625        """
     626        Normalize ``s`` to ensure a unique representation.
    275627
    276 class SetPartitions_setn(SetPartitions_setparts):
    277     def __init__(self, set, n):
     628        EXAMPLES::
     629
     630            sage: S1 = SetPartitions(set([2,1,4]), 2)
     631            sage: S2 = SetPartitions([4,1,2], 2)
     632            sage: S3 = SetPartitions((1,2,4), 2)
     633            sage: S1 is S2, S1 is S3
     634            (True, True)
     635        """
     636        return super(SetPartitions_setn, cls).__classcall__(cls, frozenset(s), n)
     637
     638    def __init__(self, s, n):
     639        """
     640        TESTS::
     641
     642            sage: S = SetPartitions(5, 3)
     643            sage: TestSuite(S).run()
     644        """
     645        self.n = n
     646        SetPartitions.__init__(self, s)
     647
     648    def _repr_(self):
    278649        """
    279650        TESTS::
    280651       
    281             sage: S = SetPartitions(5, 3)
    282             sage: S == loads(dumps(S)) # Not tested: todo - IntegerListsLex needs to pickle properly
    283             True
     652            sage: SetPartitions(5, 3)
     653            Set partitions of {1, 2, 3, 4, 5} with 3 parts
    284654        """
    285         self.n = n
    286         SetPartitions_setparts.__init__(self, set, partition.Partitions(len(set), length=n).list())
    287 
    288     def __repr__(self):
    289         """
    290         TESTS::
    291        
    292             sage: repr(SetPartitions(5, 3))
    293             'Set partitions of [1, 2, 3, 4, 5] with 3 parts'
    294         """
    295         return "Set partitions of %s with %s parts"%(self.set,self.n)
     655        return "Set partitions of %s with %s parts"%(Set(self._set), self.n)
    296656
    297657    def cardinality(self):
    298658        """
    299659        The Stirling number of the second kind is the number of partitions
    300         of a set of size n into k blocks.
     660        of a set of size `n` into `k` blocks.
    301661       
    302662        EXAMPLES::
    303663       
    class SetPartitions_setn(SetPartitions_s 
    306666            sage: stirling_number2(5,3)
    307667            25
    308668        """
    309         return stirling_number2(len(self.set), self.n)
    310    
    311 class SetPartitions_set(SetPartitions_setparts):
    312     def __init__(self, set):
     669        return stirling_number2(len(self._set), self.n)
     670
     671    def __iter__(self):
     672        """
     673        Iterate over ``self``.
     674
     675        EXAMPLES::
     676
     677            sage: SetPartitions(3).list()
     678            [{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}]
     679        """
     680        for p in Partitions(len(self._set), length=self.n):
     681            for sp in self._iterator_part(p):
     682                yield self.element_class(self, sp)
     683
     684class SetPartitions_set(SetPartitions):
     685    """
     686    Set partitions of a fixed set `S`.
     687    """
     688    @staticmethod
     689    def __classcall_private__(cls, s):
     690        """
     691        Normalize ``s`` to ensure a unique representation.
     692
     693        EXAMPLES::
     694
     695            sage: S1 = SetPartitions(set([2,1,4]))
     696            sage: S2 = SetPartitions([4,1,2])
     697            sage: S3 = SetPartitions((1,2,4))
     698            sage: S1 is S2, S1 is S3
     699            (True, True)
     700        """
     701        return super(SetPartitions_set, cls).__classcall__(cls, frozenset(s))
     702
     703    def _repr_(self):
    313704        """
    314705        TESTS::
    315706       
    316             sage: S = SetPartitions([1,2,3])
    317             sage: S == loads(dumps(S))
    318             True
     707            sage: SetPartitions([1,2,3])
     708            Set partitions of {1, 2, 3}
    319709        """
    320         SetPartitions_setparts.__init__(self, set, partition.Partitions(len(set)))
    321 
    322     def __repr__(self):
    323         """
    324         TESTS::
    325        
    326             sage: repr( SetPartitions([1,2,3]) )
    327             'Set partitions of [1, 2, 3]'
    328         """
    329         return "Set partitions of %s"%(self.set)
     710        return "Set partitions of %s"%(Set(self._set))
    330711
    331712    def cardinality(self):
    332713        """
     714        Return the number of set partitions of the set `S`.
     715
     716        The cardinality is given by the `n`-th Bell number where `n` is the
     717        number of elements in the set `S`.
     718
    333719        EXAMPLES::
    334        
    335             sage: SetPartitions(4).cardinality()
     720
     721            sage: SetPartitions([1,2,3,4]).cardinality()
    336722            15
    337             sage: bell_number(4)
    338             15
     723            sage: SetPartitions(3).cardinality()
     724            5
     725            sage: SetPartitions(3,2).cardinality()
     726            3
     727            sage: SetPartitions([]).cardinality()
     728            1
    339729        """
    340         return bell_number(len(self.set))
     730        return bell_number(len(self._set))
    341731
     732    def __iter__(self):
     733        """
     734        Iterate over ``self``.
    342735
     736        EXAMPLES::
     737
     738            sage: SetPartitions(3).list()
     739            [{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}}, {{1}, {2}, {3}}]
     740        """
     741        for p in Partitions(len(self._set)):
     742            for sp in self._iterator_part(p):
     743                yield self.element_class(self, sp)
    343744
    344745def _listbloc(n, nbrepets, listint=None):
    345     """
    346     listbloc decomposes a set of n\*nbrepets integers (the list
    347     listint) in nbrepets parts.
     746    r"""
     747    Decompose a set of `n \times n` ``brepets`` integers (the list
     748    ``listint``) in ``nbrepets`` parts.
    348749   
    349750    It is used in the algorithm to generate all set partitions.
    350    
    351     Not to be called by the user.
     751
     752    .. WARNING::
     753
     754        Internal function that is not to be called by the user.
    352755   
    353756    EXAMPLES::
    354757   
    def _listbloc(n, nbrepets, listint=None) 
    358761        sage: list(sage.combinat.set_partition._listbloc(2,2,[1,2,3,4])) == l
    359762        True
    360763    """
    361     if isinstance(listint, (int, sage.rings.integer.Integer)) or listint is None:
     764    if isinstance(listint, (int, Integer)) or listint is None:
    362765        listint = Set(range(1,n+1))
    363766
    364 
    365767    if nbrepets == 1:
    366768        yield Set([listint])
    367769        return
    368770   
    369     l = __builtin__.list(listint)
     771    l = list(listint)
    370772    l.sort()
    371773    smallest = Set(l[:1])
    372774    new_listint = Set(l[1:])
    def _listbloc(n, nbrepets, listint=None) 
    377779        for z in _listbloc(n, nbrepets-1, new_listint-ssens):
    378780            yield f(z,ssens)
    379781
    380 
    381 
    382782def _union(s):
    383783    """
    384784    TESTS::
    def _set_union(s): 
    407807
    408808def inf(s,t):
    409809    """
    410     Returns the infimum of the two set partitions s and t.
     810    Deprecated in :trac:`14140`. Use :meth:`SetPartition.inf()` instead.
    411811   
    412812    EXAMPLES::
    413813   
    def inf(s,t): 
    415815        sage: sp2 = Set([Set([1,3]), Set([2,4])])
    416816        sage: s = Set([ Set([2,4]), Set([3]), Set([1])]) #{{2, 4}, {3}, {1}}
    417817        sage: sage.combinat.set_partition.inf(sp1, sp2) == s
     818        doctest:1: DeprecationWarning: inf(s, t) is deprecated. Use s.inf(t) instead.
     819        See http://trac.sagemath.org/14140 for details.
    418820        True
    419821    """
     822    from sage.misc.superseded import deprecation
     823    deprecation(14140, 'inf(s, t) is deprecated. Use s.inf(t) instead.')
    420824    temp = [ss.intersection(ts) for ss in s for ts in t]
    421825    temp = filter(lambda x: x != Set([]), temp)
    422826    return Set(temp)
    423827
    424828def sup(s,t):
    425829    """
    426     Returns the supremum of the two set partitions s and t.
     830    Deprecated in :trac:`14140`. Use :meth:`SetPartition.sup()` instead.
    427831   
    428832    EXAMPLES::
    429833   
    def sup(s,t): 
    431835        sage: sp2 = Set([Set([1,3]), Set([2,4])])
    432836        sage: s = Set([ Set([1,2,3,4]) ])
    433837        sage: sage.combinat.set_partition.sup(sp1, sp2) == s
     838        doctest:1: DeprecationWarning: sup(s, t) is deprecated. Use s.sup(t) instead.
     839        See http://trac.sagemath.org/14140 for details.
    434840        True
    435841    """
     842    from sage.misc.superseded import deprecation
     843    deprecation(14140, 'sup(s, t) is deprecated. Use s.sup(t) instead.')
    436844    res = s
    437845    for p in t:
    438         inters = Set(filter(lambda x: x.intersection(p) != Set([]), __builtin__.list(res)))
     846        inters = Set(filter(lambda x: x.intersection(p) != Set([]), list(res)))
    439847        res = res.difference(inters).union(_set_union(inters))
    440 
    441848    return res
    442 
    443849   
    444850def standard_form(sp):
    445851    """
    446     Returns the set partition as a list of lists.
     852    Deprecated in :trac:`14140`. Use :meth:`SetPartition.standard_form()`
     853    instead.
    447854   
    448855    EXAMPLES::
    449856   
    450857        sage: map(sage.combinat.set_partition.standard_form, SetPartitions(4, [2,2]))
    451         [[[3, 4], [1, 2]], [[2, 4], [1, 3]], [[2, 3], [1, 4]]]
     858        doctest:1: DeprecationWarning: standard_form(sp) is deprecated. Use sp.standard_form() instead.
     859        See http://trac.sagemath.org/14140 for details.
     860        [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
    452861    """
    453 
    454     return [__builtin__.list(x) for x in sp]
    455 
     862    from sage.misc.superseded import deprecation
     863    deprecation(14140, 'standard_form(sp) is deprecated. Use sp.standard_form() instead.')
     864    return [list(x) for x in sp]
    456865
    457866def less(s, t):
    458867    """
    459     Returns True if s < t otherwise it returns False.
     868    Deprecated in :trac:`14140`. Use :meth:`SetPartitions.is_less_than()`
     869    instead.
    460870   
    461871    EXAMPLES::
    462872   
    463873        sage: z = SetPartitions(3).list()
    464874        sage: sage.combinat.set_partition.less(z[0], z[1])
    465         False
    466         sage: sage.combinat.set_partition.less(z[4], z[1])
    467         True
    468         sage: sage.combinat.set_partition.less(z[4], z[0])
    469         True
    470         sage: sage.combinat.set_partition.less(z[3], z[0])
    471         True
    472         sage: sage.combinat.set_partition.less(z[2], z[0])
    473         True
    474         sage: sage.combinat.set_partition.less(z[1], z[0])
    475         True
    476         sage: sage.combinat.set_partition.less(z[0], z[0])
     875        doctest:1: DeprecationWarning: less(s, t) is deprecated. Use SetPartitions.is_less_tan(s, t) instead.
     876        See http://trac.sagemath.org/14140 for details.
    477877        False
    478878    """
    479 
     879    from sage.misc.superseded import deprecation
     880    deprecation(14140, 'less(s, t) is deprecated. Use SetPartitions.is_less_tan(s, t) instead.')
    480881    if _union(s) != _union(t):
    481         raise ValueError, "cannot compare partitions of different sets"
    482 
     882        raise ValueError("cannot compare partitions of different sets")
    483883    if s == t:
    484884        return False
    485 
    486885    for p in s:
    487886        f = lambda z: z.intersection(p) != Set([])
    488         if len(filter(f, __builtin__.list(t)) ) != 1:
     887        if len(filter(f, list(t)) ) != 1:
    489888            return False
    490 
    491889    return True
    492890
    493 
    494891def cyclic_permutations_of_set_partition(set_part):
    495892    """
    496893    Returns all combinations of cyclic permutations of each cell of the
  • sage/combinat/set_partition_ordered.py

    diff --git a/sage/combinat/set_partition_ordered.py b/sage/combinat/set_partition_ordered.py
    a b  
    11r"""
    22Ordered Set Partitions
    33
    4 An ordered set partition p of a set s is a partition of s, into
    5 subsets called parts and represented as a list of sets. By
    6 extension, an ordered set partition of a nonnegative integer n is
    7 the set partition of the integers from 1 to n. The number of
    8 ordered set partitions of n is called the n-th ordered Bell
    9 number.
    10 
    11 There is a natural integer composition associated with an ordered
    12 set partition, that is the sequence of sizes of all its parts in
    13 order.
    14 
    15 EXAMPLES: There are 13 ordered set partitions of {1,2,3}.
    16 
    17 ::
    18 
    19     sage: OrderedSetPartitions(3).cardinality()
    20     13
    21 
    22 Here is the list of them::
    23 
    24     sage: OrderedSetPartitions(3).list() #random due to the sets
    25     [[{1}, {2}, {3}],
    26      [{1}, {3}, {2}],
    27      [{2}, {1}, {3}],
    28      [{3}, {1}, {2}],
    29      [{2}, {3}, {1}],
    30      [{3}, {2}, {1}],
    31      [{1}, {2, 3}],
    32      [{2}, {1, 3}],
    33      [{3}, {1, 2}],
    34      [{1, 2}, {3}],
    35      [{1, 3}, {2}],
    36      [{2, 3}, {1}],
    37      [{1, 2, 3}]]
    38 
    39 There are 12 ordered set partitions of {1,2,3,4} whose underlying
    40 composition is [1,2,1].
    41 
    42 ::
    43 
    44     sage: OrderedSetPartitions(4,[1,2,1]).list() #random due to the sets
    45     [[{1}, {2, 3}, {4}],
    46      [{1}, {2, 4}, {3}],
    47      [{1}, {3, 4}, {2}],
    48      [{2}, {1, 3}, {4}],
    49      [{2}, {1, 4}, {3}],
    50      [{3}, {1, 2}, {4}],
    51      [{4}, {1, 2}, {3}],
    52      [{3}, {1, 4}, {2}],
    53      [{4}, {1, 3}, {2}],
    54      [{2}, {3, 4}, {1}],
    55      [{3}, {2, 4}, {1}],
    56      [{4}, {2, 3}, {1}]]
    57 
    584AUTHORS:
    595
    606- Mike Hansen
    617
    628- MuPAD-Combinat developers (for algorithms and design inspiration)
     9
     10- Travis Scrimshaw (2013-02-28): Removed ``CombinatorialClass`` and added
     11  entry point through :class:`OrderedSetPartition`.
    6312"""
    6413#*****************************************************************************
    6514#       Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
    AUTHORS: 
    7726#*****************************************************************************
    7827
    7928from sage.rings.arith import factorial
    80 import sage.combinat.composition as composition
     29import sage.rings.integer
     30from sage.sets.set import Set, is_Set
     31from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
     32from sage.misc.classcall_metaclass import ClasscallMetaclass
     33from sage.misc.misc import prod
     34from sage.structure.parent import Parent
     35from sage.structure.unique_representation import UniqueRepresentation
     36from sage.structure.list_clone import ClonableArray
     37from sage.combinat.combinatorial_map import combinatorial_map
     38from sage.combinat.combinat import stirling_number2
     39from sage.combinat.composition import Composition, Compositions
    8140from sage.combinat.words.word import Word
    8241import sage.combinat.permutation as permutation
    83 import sage.rings.integer
    84 from sage.combinat.combinat import stirling_number2
    85 from sage.sets.set import Set, is_Set
    86 from combinat import CombinatorialClass
    87 from sage.misc.misc import prod
    8842
     43class OrderedSetPartition(ClonableArray):
     44    """
     45    An ordered partition of a set.
    8946
    90 def OrderedSetPartitions(s, c=None):
     47    An ordered set partition `p` of a set `s` is a partition of `s` into
     48    subsets called parts and represented as a list of sets. By
     49    extension, an ordered set partition of a nonnegative integer `n` is
     50    the set partition of the integers from 1 to `n`. The number of
     51    ordered set partitions of `n` is called the `n`-th ordered Bell
     52    number.
     53
     54    There is a natural integer composition associated with an ordered
     55    set partition, that is the sequence of sizes of all its parts in
     56    order.
     57
     58    EXAMPLES:
     59
     60    There are 13 ordered set partitions of `\{1,2,3\}`::
     61
     62        sage: OrderedSetPartitions(3).cardinality()
     63        13
     64
     65    Here is the list of them::
     66
     67        sage: OrderedSetPartitions(3).list()
     68        [[{1}, {2}, {3}],
     69         [{1}, {3}, {2}],
     70         [{2}, {1}, {3}],
     71         [{3}, {1}, {2}],
     72         [{2}, {3}, {1}],
     73         [{3}, {2}, {1}],
     74         [{1}, {2, 3}],
     75         [{2}, {1, 3}],
     76         [{3}, {1, 2}],
     77         [{1, 2}, {3}],
     78         [{1, 3}, {2}],
     79         [{2, 3}, {1}],
     80         [{1, 2, 3}]]
     81
     82    There are 12 ordered set partitions of `\{1,2,3,4\}` whose underlying
     83    composition is `[1,2,1]`::
     84
     85        sage: OrderedSetPartitions(4,[1,2,1]).list()
     86        [[{1}, {2, 3}, {4}],
     87         [{1}, {2, 4}, {3}],
     88         [{1}, {3, 4}, {2}],
     89         [{2}, {1, 3}, {4}],
     90         [{2}, {1, 4}, {3}],
     91         [{3}, {1, 2}, {4}],
     92         [{4}, {1, 2}, {3}],
     93         [{3}, {1, 4}, {2}],
     94         [{4}, {1, 3}, {2}],
     95         [{2}, {3, 4}, {1}],
     96         [{3}, {2, 4}, {1}],
     97         [{4}, {2, 3}, {1}]]
     98
     99    Since :trac:`14140`, we can create an ordered set partition directly by
     100    :class:`OrderedSetPartition` which creates the parent object by taking the
     101    union of the partitions passed in. However it is recommended and
     102    (marginally) faster to create the parent first and then create the ordered
     103    set partition from that. ::
     104
     105        sage: s = OrderedSetPartition([[1,3],[2,4]]); s
     106        [{1, 3}, {2, 4}]
     107        sage: s.parent()
     108        Ordered set partitions of {1, 2, 3, 4}
    91109    """
    92     Returns the combinatorial class of ordered set partitions of s.
     110    __metaclass__ = ClasscallMetaclass
     111
     112    @staticmethod
     113    def __classcall_private__(cls, parts):
     114        """
     115        Create a set partition from ``parts`` with the appropriate parent.
     116
     117        EXAMPLES::
     118
     119            sage: s = OrderedSetPartition([[1,3],[2,4]]); s
     120            [{1, 3}, {2, 4}]
     121            sage: s.parent()
     122            Ordered set partitions of {1, 2, 3, 4}
     123            sage: t = OrderedSetPartition([[2,4],[1,3]]); t
     124            [{2, 4}, {1, 3}]
     125            sage: s != t
     126            True
     127        """
     128        P = OrderedSetPartitions( reduce(lambda x,y: x.union(y), map(Set, parts)) )
     129        return P.element_class(P, parts)
     130
     131    def __init__(self, parent, s):
     132        """
     133        Initialize ``self``.
     134
     135        EXAMPLES::
     136
     137            sage: OS = OrderedSetPartitions(4)
     138            sage: s = OS([[1, 3], [2, 4]])
     139            sage: TestSuite(s).run()
     140        """
     141        ClonableArray.__init__(self, parent, map(Set, s))
     142
     143    def check(self):
     144        """
     145        Check that we are a valid ordered set partition.
     146
     147        EXAMPLES::
     148
     149            sage: OS = OrderedSetPartitions(4)
     150            sage: s = OS([[1, 3], [2, 4]])
     151            sage: s.check()
     152        """
     153        assert self in self.parent()
     154
     155    @combinatorial_map(name='to composition')
     156    def to_composition(self):
     157        r"""
     158        Return the integer composition whose parts are the sizes of the sets
     159        in ``self``.
     160
     161        EXAMPLES::
     162
     163            sage: S = OrderedSetPartitions(5)
     164            sage: x = S([[3,5,4], [1, 2]])
     165            sage: x.to_composition()
     166            [3, 2]
     167            sage: y = S([[3,1], [2], [5,4]])
     168            sage: y.to_composition()
     169            [2, 1, 2]
     170        """
     171        return Composition(map(len, self))
     172
     173class OrderedSetPartitions(Parent, UniqueRepresentation):
     174    """
     175    Return the combinatorial class of ordered set partitions of ``s``.
    93176   
    94177    EXAMPLES::
    95178   
    def OrderedSetPartitions(s, c=None): 
    125208    ::
    126209   
    127210        sage: OS = OrderedSetPartitions("cat"); OS
    128         Ordered set partitions of ['c', 'a', 't']
     211        Ordered set partitions of {'a', 'c', 't'}
    129212        sage: OS.list()
    130213        [[{'a'}, {'c'}, {'t'}],
    131214         [{'a'}, {'t'}, {'c'}],
    def OrderedSetPartitions(s, c=None): 
    141224         [{'c', 't'}, {'a'}],
    142225         [{'a', 'c', 't'}]]
    143226    """
    144     if isinstance(s, (int, sage.rings.integer.Integer)):
    145         if s < 0:
    146             raise ValueError, "s must be non-negative"
    147         set = Set(range(1, s+1))
    148     elif isinstance(s, str):
    149         set = [x for x in s]
    150     else:
    151         set = Set(s)
    152        
    153     if c is None:
    154         return OrderedSetPartitions_s(set)
    155     else:
     227    @staticmethod
     228    def __classcall_private__(cls, s, c=None):
     229        """
     230        Choose the correct parent based upon input.
     231
     232        EXAMPLES::
     233
     234            sage: OrderedSetPartitions(4)
     235            Ordered set partitions of {1, 2, 3, 4}
     236            sage: OrderedSetPartitions(4, [1, 2, 1])
     237            Ordered set partitions of {1, 2, 3, 4} into parts of size [1, 2, 1]
     238        """
     239        if isinstance(s, (int, sage.rings.integer.Integer)):
     240            if s < 0:
     241                raise ValueError("s must be non-negative")
     242            s = frozenset(range(1, s+1))
     243        else:
     244            s = frozenset(s)
     245           
     246        if c is None:
     247            return OrderedSetPartitions_s(s)
     248
    156249        if isinstance(c, (int, sage.rings.integer.Integer)):
    157             return OrderedSetPartitions_sn(set, c)
    158         elif c not in composition.Compositions(len(set)):
    159             raise ValueError, "c must be a composition of %s"%len(set)
    160         else:
    161             return OrderedSetPartitions_scomp(set,c)
    162        
     250            return OrderedSetPartitions_sn(s, c)
     251        if c not in Compositions(len(s)):
     252            raise ValueError("c must be a composition of %s"%len(s))
     253        return OrderedSetPartitions_scomp(s, Composition(c))
    163254
    164 class OrderedSetPartitions_s(CombinatorialClass):
    165255    def __init__(self, s):
    166256        """
    167         TESTS::
    168        
    169             sage: OS = OrderedSetPartitions([1,2,3,4])
    170             sage: OS == loads(dumps(OS))
    171             True
     257        Initialize ``self``.
     258
     259        EXAMPLES::
     260
     261            sage: OS = OrderedSetPartitions(4)
     262            sage: TestSuite(OS).run()
    172263        """
    173         self.s = s
     264        self._set = s
     265        Parent.__init__(self, category=FiniteEnumeratedSets())
    174266
    175     def __repr__(self):
     267    def _element_constructor_(self, s):
    176268        """
    177         TESTS::
    178        
    179             sage: repr(OrderedSetPartitions([1,2,3,4]))
    180             'Ordered set partitions of {1, 2, 3, 4}'
     269        Construct an element of ``self`` from ``s``.
     270
     271        EXAMPLES::
     272
     273            sage: OS = OrderedSetPartitions(4)
     274            sage: OS([[1,3],[2,4]])
     275            [{1, 3}, {2, 4}]
    181276        """
    182         return "Ordered set partitions of %s"%self.s
     277        if isinstance(s, OrderedSetPartition):
     278            if s.parent() == self:
     279                return s
     280            raise ValueError("Cannot convert %s into an element of %s"%(s, self))
     281        return self.element_class(self, list(s))
     282
     283    Element = OrderedSetPartition
    183284
    184285    def __contains__(self, x):
    185286        """
    class OrderedSetPartitions_s(Combinatori 
    190291            True
    191292        """
    192293        #x must be a list
    193         if not isinstance(x, list):
     294        if not isinstance(x, (OrderedSetPartition, list, tuple)):
    194295            return False
    195296
    196297        #The total number of elements in the list
    197         #should be the same as the number is self.s
    198         if sum(map(len, x)) != len(self.s):
     298        #should be the same as the number is self._set
     299        if sum(map(len, x)) != len(self._set):
    199300            return False
    200301
    201302        #Check to make sure each element of the list
    202303        #is a set
    203304        u = Set([])
    204305        for s in x:
    205             if not is_Set(s):
     306            if not isinstance(s, (set, frozenset)) and not is_Set(s):
    206307                return False
    207308            u = u.union(s)
    208309
    209310        #Make sure that the union of all the
    210311        #sets is the original set
    211         if u != Set(self.s):
     312        if u != Set(self._set):
    212313            return False
    213314
    214315        return True
    215316
     317class OrderedSetPartitions_s(OrderedSetPartitions):
     318    """
     319    Class of ordered partitions of a set `S`.
     320    """
     321    def _repr_(self):
     322        """
     323        TESTS::
     324       
     325            sage: OrderedSetPartitions([1,2,3,4])
     326            Ordered set partitions of {1, 2, 3, 4}
     327        """
     328        return "Ordered set partitions of %s"%Set(self._set)
     329
    216330    def cardinality(self):
    217331        """
    218332        EXAMPLES::
    class OrderedSetPartitions_s(Combinatori 
    232346            sage: OrderedSetPartitions(5).cardinality()
    233347            541
    234348        """
    235         set = self.s
    236         return sum([factorial(k)*stirling_number2(len(set),k) for k in range(len(set)+1)])
    237 
    238 
     349        return sum([factorial(k)*stirling_number2(len(self._set),k) for k in range(len(self._set)+1)])
    239350
    240351    def __iter__(self):
    241352        """
    class OrderedSetPartitions_s(Combinatori 
    256367             [{2, 3}, {1}],
    257368             [{1, 2, 3}]]
    258369        """
    259         for x in composition.Compositions(len(self.s)):
    260             for z in OrderedSetPartitions(self.s,x):
    261                 yield z
     370        for x in Compositions(len(self._set)):
     371            for z in OrderedSetPartitions(self._set, x):
     372                yield self.element_class(self, z)
    262373
    263 
    264 class OrderedSetPartitions_sn(CombinatorialClass):
     374class OrderedSetPartitions_sn(OrderedSetPartitions):
    265375    def __init__(self, s, n):
    266376        """
    267377        TESTS::
    class OrderedSetPartitions_sn(Combinator 
    270380            sage: OS == loads(dumps(OS))
    271381            True
    272382        """
    273         self.s = s
     383        OrderedSetPartitions.__init__(self, s)
    274384        self.n = n
    275385
    276386    def __contains__(self, x):
    class OrderedSetPartitions_sn(Combinator 
    285395            sage: len(filter(lambda x: x in OS, OrderedSetPartitions([1,2,3,4])))
    286396            14
    287397        """
    288         return x in OrderedSetPartitions_s(self.s) and len(x) == self.n
     398        return OrderedSetPartitions.__contains__(self, x) and len(x) == self.n
    289399
    290400    def __repr__(self):
    291401        """
    292402        TESTS::
    293403       
    294             sage: repr(OrderedSetPartitions([1,2,3,4], 2))
    295             'Ordered set partitions of {1, 2, 3, 4} into 2 parts'
     404            sage: OrderedSetPartitions([1,2,3,4], 2)
     405            Ordered set partitions of {1, 2, 3, 4} into 2 parts
    296406        """
    297         return "Ordered set partitions of %s into %s parts"%(self.s,self.n)
     407        return "Ordered set partitions of %s into %s parts"%(Set(self._set),self.n)
    298408
    299409    def cardinality(self):
    300410        """
     411        Return the cardinality of ``self``.
     412
     413        The number of ordered partitions of a set of length `k` into `n` parts
     414        is equal to `n! S(n,k)` where `S(n,k)` denotes the Stirling number
     415        of the second kind.
     416
    301417        EXAMPLES::
    302418       
    303419            sage: OrderedSetPartitions(4,2).cardinality()
    class OrderedSetPartitions_sn(Combinator 
    305421            sage: OrderedSetPartitions(4,1).cardinality()
    306422            1
    307423        """
    308         set = self.s
    309         n   = self.n
    310         return factorial(n)*stirling_number2(len(set),n)
     424        return factorial(self.n)*stirling_number2(len(self._set), self.n)
    311425
    312426    def __iter__(self):
    313427        """
    class OrderedSetPartitions_sn(Combinator 
    329443             [{3}, {1, 2, 4}],
    330444             [{4}, {1, 2, 3}]]
    331445        """
    332         for x in composition.Compositions(len(self.s),length=self.n):
    333             for z in OrderedSetPartitions_scomp(self.s,x):
    334                 yield z
     446        for x in Compositions(len(self._set),length=self.n):
     447            for z in OrderedSetPartitions_scomp(self._set,x):
     448                yield self.element_class(self, z)
    335449
    336 class OrderedSetPartitions_scomp(CombinatorialClass):
     450class OrderedSetPartitions_scomp(OrderedSetPartitions):
    337451    def __init__(self, s, comp):
    338452        """
    339453        TESTS::
    class OrderedSetPartitions_scomp(Combina 
    342456            sage: OS == loads(dumps(OS))
    343457            True
    344458        """
    345         self.s = s
    346         self.c = composition.Composition(comp)
     459        OrderedSetPartitions.__init__(self, s)
     460        self.c = Composition(comp)
    347461
    348462    def __repr__(self):
    349463        """
    350464        TESTS::
    351465       
    352             sage: repr(OrderedSetPartitions([1,2,3,4], [2,1,1]))
    353             'Ordered set partitions of {1, 2, 3, 4} into parts of size [2, 1, 1]'
     466            sage: OrderedSetPartitions([1,2,3,4], [2,1,1])
     467            Ordered set partitions of {1, 2, 3, 4} into parts of size [2, 1, 1]
    354468        """
    355         return "Ordered set partitions of %s into parts of size %s"%(self.s,self.c)
     469        return "Ordered set partitions of %s into parts of size %s"%(Set(self._set), self.c)
    356470
    357471    def __contains__(self, x):
    358472        """
    class OrderedSetPartitions_scomp(Combina 
    366480            sage: len(filter(lambda x: x in OS, OrderedSetPartitions([1,2,3,4])))
    367481            12
    368482        """
    369         return x in OrderedSetPartitions_s(self.s) and map(len, x) == self.c
     483        return OrderedSetPartitions.__contains__(self, x) and map(len, x) == self.c
    370484   
    371485    def cardinality(self):
    372         """
     486        r"""
     487        Return the cardinality of ``self``.
     488
     489        The number of ordered set partitions of a set of length `k` with
     490        composition shape `\mu` is equal to
     491
     492        .. MATH::
     493
     494            \frac{k!}{\prod_{\mu_i \neq 0} \mu_i!}.
     495
    373496        EXAMPLES::
    374497       
    375498            sage: OrderedSetPartitions(5,[2,3]).cardinality()
    class OrderedSetPartitions_scomp(Combina 
    383506            sage: OrderedSetPartitions(5, [2,0,3]).cardinality()
    384507            10
    385508        """
    386         return factorial(len(self.s))/prod([factorial(i) for i in self.c])
     509        return factorial(len(self._set))/prod([factorial(i) for i in self.c])
    387510   
    388511    def __iter__(self):
    389512        """
    class OrderedSetPartitions_scomp(Combina 
    404527             [{3, 4}, {2}, {1}]]
    405528        """
    406529        comp = self.c
    407         lset = [x for x in self.s]
     530        lset = [x for x in self._set]
    408531        l = len(self.c)
    409532        dcomp = [-1] + comp.descents(final_descent=True)
    410533
    class OrderedSetPartitions_scomp(Combina 
    414537
    415538        for x in permutation.Permutations(p):
    416539            res = permutation.Permutation_class(range(1,len(lset))) * Word(x).standard_permutation().inverse()
    417             res =[lset[x-1] for x in res]
    418             yield [ Set( res[dcomp[i]+1:dcomp[i+1]+1] ) for i in range(l)]
    419            
     540            res = [lset[x-1] for x in res]
     541            yield self.element_class( self, [ Set( res[dcomp[i]+1:dcomp[i+1]+1] ) for i in range(l)] )
    420542
    421 
    422 
  • sage/combinat/tutorial.py

    diff --git a/sage/combinat/tutorial.py b/sage/combinat/tutorial.py
    a b Set partitions:: 
    848848
    849849    sage: C = SetPartitions([1,2,3])
    850850    sage: C
    851     Set partitions of [1, 2, 3]
     851    Set partitions of {1, 2, 3}
    852852    sage: C.cardinality()
    853853    5
    854854    sage: C.list()
    855     [{{1, 2, 3}}, {{2, 3}, {1}}, {{1, 3}, {2}}, {{1, 2}, {3}},
    856      {{2}, {3}, {1}}]
     855    [{{1, 2, 3}}, {{1}, {2, 3}}, {{1, 3}, {2}}, {{1, 2}, {3}},
     856     {{1}, {2}, {3}}]
    857857
    858858Partial orders on a set of `8` elements, up to isomorphism::
    859859
  • sage/misc/sageinspect.py

    diff --git a/sage/misc/sageinspect.py b/sage/misc/sageinspect.py
    a b def sage_getsourcelines(obj, is_binary=F 
    16981698        sage: sage_getsourcelines(obj)
    16991699        (['def create_set_partition_function(letter, k):\n',
    17001700        ...
    1701         '    raise ValueError, "k must be an integer or an integer + 1/2"\n'], 31)
     1701        '    raise ValueError("k must be an integer or an integer + 1/2")\n'], 31)
    17021702
    17031703    Here are some cases that were covered in :trac`11298`;
    17041704    note that line numbers may easily change, and therefore we do
  • sage/sandpiles/sandpile.py

    diff --git a/sage/sandpiles/sandpile.py b/sage/sandpiles/sandpile.py
    a b def admissible_partitions(S, k): 
    51485148
    51495149        sage: S = Sandpile(graphs.CycleGraph(4), 0)
    51505150        sage: P = [admissible_partitions(S, i) for i in [2,3,4]]
    5151         sage: P 
    5152         [[{{1, 2, 3}, {0}},
     5151        sage: P
     5152        [[{{0}, {1, 2, 3}},
    51535153          {{0, 2, 3}, {1}},
    5154           {{2}, {0, 1, 3}},
     5154          {{0, 1, 3}, {2}},
    51555155          {{0, 1, 2}, {3}},
    5156           {{2, 3}, {0, 1}},
    5157           {{1, 2}, {0, 3}}],
    5158          [{{2, 3}, {0}, {1}},
    5159           {{1, 2}, {3}, {0}},
    5160           {{2}, {0, 3}, {1}},
    5161           {{2}, {3}, {0, 1}}],
    5162          [{{2}, {3}, {0}, {1}}]]
     5156          {{0, 1}, {2, 3}},
     5157          {{0, 3}, {1, 2}}],
     5158         [{{0}, {1}, {2, 3}},
     5159          {{0}, {1, 2}, {3}},
     5160          {{0, 3}, {1}, {2}},
     5161          {{0, 1}, {2}, {3}}],
     5162         [{{0}, {1}, {2}, {3}}]]
    51635163        sage: for p in P:
    51645164        ...    sum([partition_sandpile(S, i).betti(verbose=False)[-1] for i in p])
    51655165        6