This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
set_partition.py
2338 lines (1901 loc) · 75.4 KB
/
set_partition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Set Partitions
AUTHORS:
- Mike Hansen
- MuPAD-Combinat developers (for algorithms and design inspiration).
- Travis Scrimshaw (2013-02-28): Removed ``CombinatorialClass`` and added
entry point through :class:`SetPartition`.
- Martin Rubey (2017-10-10): Cleanup, add crossings and nestings, add
random generation.
This module defines a class for immutable partitioning of a set. For
mutable version see :func:`DisjointSet`.
"""
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function, absolute_import, division
from six.moves import range
from six import add_metaclass
from sage.sets.set import Set, Set_generic
import itertools
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.list_clone import ClonableArray
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.misc.inherit_comparison import InheritComparisonClasscallMetaclass
from sage.rings.infinity import infinity
from sage.rings.integer import Integer
from sage.combinat.misc import IterableFunctionCall
from sage.combinat.combinatorial_map import combinatorial_map
import sage.combinat.subset as subset
from sage.combinat.partition import Partition, Partitions
from sage.combinat.set_partition_ordered import OrderedSetPartitions
from sage.combinat.combinat import bell_number, stirling_number2
from sage.combinat.permutation import Permutation
from sage.functions.other import factorial
from sage.misc.prandom import random, randint
from sage.probability.probability_distribution import GeneralDiscreteDistribution
@add_metaclass(InheritComparisonClasscallMetaclass)
class AbstractSetPartition(ClonableArray):
r"""
Methods of set partitions which are independent of the base set
"""
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: S = SetPartitions(4)
sage: S([[1,3],[2,4]])
{{1, 3}, {2, 4}}
"""
return '{' + ', '.join(('{' + repr(sorted(x))[1:-1] + '}' for x in self)) + '}'
def __hash__(self):
"""
Return the hash of ``self``.
The parent is not included as part of the hash.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = SetPartition([[1], [2,3], [4]])
sage: B = P([[1], [2,3], [4]])
sage: hash(A) == hash(B)
True
"""
return sum(hash(x) for x in self)
def __eq__(self, y):
"""
Check equality of ``self`` and ``y``.
The parent is not included as part of the equality check.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = SetPartition([[1], [2,3], [4]])
sage: B = P([[1], [2,3], [4]])
sage: A == B
True
sage: C = P([[2, 3], [1], [4]])
sage: A == C
True
sage: D = P([[1], [2, 4], [3]])
sage: A == D
False
"""
if not isinstance(y, AbstractSetPartition):
return False
return list(self) == list(y)
def __ne__(self, y):
"""
Check lack of equality of ``self`` and ``y``.
The parent is not included as part of the equality check.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = SetPartition([[1], [2,3], [4]])
sage: B = P([[1], [2,3], [4]])
sage: A != B
False
sage: C = P([[2, 3], [1], [4]])
sage: A != C
False
sage: D = P([[1], [2, 4], [3]])
sage: A != D
True
"""
return not (self == y)
def __lt__(self, y):
"""
Check that ``self`` is less than ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: A < B
True
sage: C = P([[1,2,4], [3]])
sage: B < C
True
sage: B < B
False
sage: D = P([[1,4], [2], [3]])
sage: E = P([[1,4], [2,3]])
sage: D < E
True
sage: F = P([[1,2,4], [3]])
sage: E < C
False
sage: A < E
True
sage: A < C
True
"""
if not isinstance(y, AbstractSetPartition):
return False
return [sorted(_) for _ in self] < [sorted(_) for _ in y]
def __gt__(self, y):
"""
Check that ``self`` is greater than ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: B > A
True
sage: A > B
False
"""
if not isinstance(y, AbstractSetPartition):
return False
return [sorted(_) for _ in self] > [sorted(_) for _ in y]
def __le__(self, y):
"""
Check that ``self`` is less than or equals ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: A <= B
True
sage: A <= A
True
"""
return self == y or self < y
def __ge__(self, y):
"""
Check that ``self`` is greater than or equals ``y``.
The ordering used is lexicographic, where:
- a set partition is considered as the list of its parts
sorted by increasing smallest element;
- each part is regarded as a list of its elements, sorted
in increasing order;
- the parts themselves are compared lexicographically.
EXAMPLES::
sage: P = SetPartitions(4)
sage: A = P([[1], [2,3], [4]])
sage: B = SetPartition([[1,2,3], [4]])
sage: B >= A
True
sage: B >= B
True
"""
return self == y or self > y
def __mul__(self, other):
r"""
The product of the set partitions ``self`` and ``other``.
The product of two set partitions `B` and `C` is defined as the
set partition whose parts are the nonempty intersections between
each part of `B` and each part of `C`. This product is also
the infimum of `B` and `C` in the classical set partition
lattice (that is, the coarsest set partition which is finer than
each of `B` and `C`). Consequently, ``inf`` acts as an alias for
this method.
.. SEEALSO::
:meth:`sup`
EXAMPLES::
sage: x = SetPartition([ [1,2], [3,5,4] ])
sage: y = SetPartition(( (3,1,2), (5,4) ))
sage: x * y
{{1, 2}, {3}, {4, 5}}
sage: S = SetPartitions(4)
sage: sp1 = S([[2,3,4], [1]])
sage: sp2 = S([[1,3], [2,4]])
sage: s = S([[2,4], [3], [1]])
sage: sp1.inf(sp2) == s
True
TESTS:
Here is a different implementation of the ``__mul__`` method
(one that was formerly used for the ``inf`` method, before it
was realized that the methods do the same thing)::
sage: def mul2(s, t):
....: temp = [ss.intersection(ts) for ss in s for ts in t]
....: temp = filter(lambda x: x != Set([]), temp)
....: return s.__class__(s.parent(), temp)
Let us check that this gives the same as ``__mul__`` on set
partitions of `\{1, 2, 3, 4\}`::
sage: all( all( mul2(s, t) == s * t for s in SetPartitions(4) )
....: for t in SetPartitions(4) )
True
"""
new_composition = []
for B in self:
for C in other:
BintC = B.intersection(C)
if BintC:
new_composition.append(BintC)
return SetPartition(new_composition)
inf = __mul__
def sup(self, t):
"""
Return the supremum of ``self`` and ``t`` in the classical set
partition lattice.
The supremum of two set partitions `B` and `C` is obtained as the
transitive closure of the relation which relates `i` to `j` if
and only if `i` and `j` are in the same part in at least
one of the set partitions `B` and `C`.
.. SEEALSO::
:meth:`__mul__`
EXAMPLES::
sage: S = SetPartitions(4)
sage: sp1 = S([[2,3,4], [1]])
sage: sp2 = S([[1,3], [2,4]])
sage: s = S([[1,2,3,4]])
sage: sp1.sup(sp2) == s
True
"""
res = Set(list(self))
for p in t:
inters = Set([x for x in list(res) if x.intersection(p) != Set([])])
res = res.difference(inters).union(_set_union(inters))
return self.parent()(res)
def standard_form(self):
r"""
Return ``self`` as a list of lists.
When the ground set is totally ordered, the elements of each
block are listed in increasing order.
This is not related to standard set partitions (which simply
means set partitions of `[n] = \{ 1, 2, \ldots , n \}` for some
integer `n`) or standardization (:meth:`standardization`).
EXAMPLES::
sage: [x.standard_form() for x in SetPartitions(4, [2,2])]
[[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
TESTS::
sage: SetPartition([(1, 9, 8), (2, 3, 4, 5, 6, 7)]).standard_form()
[[1, 8, 9], [2, 3, 4, 5, 6, 7]]
"""
return [sorted(_) for _ in self]
def base_set(self):
"""
Return the base set of ``self``, which is the union of all parts
of ``self``.
EXAMPLES::
sage: SetPartition([[1], [2,3], [4]]).base_set()
{1, 2, 3, 4}
sage: SetPartition([[1,2,3,4]]).base_set()
{1, 2, 3, 4}
sage: SetPartition([]).base_set()
{}
"""
return Set([e for p in self for e in p])
def base_set_cardinality(self):
"""
Return the cardinality of the base set of ``self``, which is the sum
of the sizes of the parts of ``self``.
This is also known as the *size* (sometimes the *weight*) of
a set partition.
EXAMPLES::
sage: SetPartition([[1], [2,3], [4]]).base_set_cardinality()
4
sage: SetPartition([[1,2,3,4]]).base_set_cardinality()
4
"""
return sum(len(x) for x in self)
def coarsenings(self):
"""
Return a list of coarsenings of ``self``.
.. SEEALSO::
:meth:`refinements`
EXAMPLES::
sage: SetPartition([[1,3],[2,4]]).coarsenings()
[{{1, 2, 3, 4}}, {{1, 3}, {2, 4}}]
sage: SetPartition([[1],[2,4],[3]]).coarsenings()
[{{1, 2, 3, 4}},
{{1}, {2, 3, 4}},
{{1, 3}, {2, 4}},
{{1, 2, 4}, {3}},
{{1}, {2, 4}, {3}}]
sage: SetPartition([]).coarsenings()
[{}]
"""
SP = SetPartitions(len(self))
def union(s):
# Return the partition obtained by combining, for every
# part of s, those parts of self which are indexed by
# the elements of this part of s into a single part.
ret = []
for part in s:
cur = Set([])
for i in part:
cur = cur.union(self[i-1]) # -1 for indexing
ret.append(cur)
return ret
return [self.parent()(union(s)) for s in SP]
def max_block_size(self):
r"""
The maximum block size of the diagram.
EXAMPLES::
sage: from sage.combinat.diagram_algebras import PartitionDiagram, PartitionDiagrams
sage: pd = PartitionDiagram([[1,-3,-5],[2,4],[3,-1,-2],[5],[-4]])
sage: pd.max_block_size()
3
sage: [d.max_block_size() for d in PartitionDiagrams(2)]
[4, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
sage: [sp.max_block_size() for sp in SetPartitions(3)]
[3, 2, 2, 2, 1]
"""
return max(len(block) for block in self)
@add_metaclass(InheritComparisonClasscallMetaclass)
class SetPartition(AbstractSetPartition):
"""
A partition of a set.
A set partition `p` of a set `S` is a partition of `S` into subsets
called parts and represented as a set of sets. By extension, a set
partition of a nonnegative integer `n` is the set partition of the
integers from 1 to `n`. The number of set partitions of `n` is called
the `n`-th Bell number.
There is a natural integer partition associated with a set partition,
namely the nonincreasing sequence of sizes of all its parts.
There is a classical lattice associated with all set partitions of
`n`. The infimum of two set partitions is the set partition obtained
by intersecting all the parts of both set partitions. The supremum
is obtained by transitive closure of the relation `i` related to `j`
if and only if they are in the same part in at least one of the set
partitions.
We will use terminology from partitions, in particular the *length* of
a set partition `A = \{A_1, \ldots, A_k\}` is the number of parts of `A`
and is denoted by `|A| := k`. The *size* of `A` is the cardinality of `S`.
We will also sometimes use the notation `[n] := \{1, 2, \ldots, n\}`.
EXAMPLES:
There are 5 set partitions of the set `\{1,2,3\}`::
sage: SetPartitions(3).cardinality()
5
Here is the list of them::
sage: SetPartitions(3).list()
[{{1, 2, 3}},
{{1}, {2, 3}},
{{1, 3}, {2}},
{{1, 2}, {3}},
{{1}, {2}, {3}}]
There are 6 set partitions of `\{1,2,3,4\}` whose underlying partition is
`[2, 1, 1]`::
sage: SetPartitions(4, [2,1,1]).list()
[{{1}, {2}, {3, 4}},
{{1}, {2, 4}, {3}},
{{1}, {2, 3}, {4}},
{{1, 4}, {2}, {3}},
{{1, 3}, {2}, {4}},
{{1, 2}, {3}, {4}}]
Since :trac:`14140`, we can create a set partition directly by
:class:`SetPartition`, which creates the base set by taking the
union of the parts passed in::
sage: s = SetPartition([[1,3],[2,4]]); s
{{1, 3}, {2, 4}}
sage: s.parent()
Set partitions
"""
@staticmethod
def __classcall_private__(cls, parts, check=True):
"""
Create a set partition from ``parts`` with the appropriate parent.
EXAMPLES::
sage: s = SetPartition([[1,3],[2,4]]); s
{{1, 3}, {2, 4}}
sage: s.parent()
Set partitions
"""
P = SetPartitions()
return P.element_class(P, parts, check=check)
def __init__(self, parent, s, check=True):
"""
Initialize ``self``.
EXAMPLES::
sage: S = SetPartitions(4)
sage: s = S([[1,3],[2,4]])
sage: TestSuite(s).run()
sage: SetPartition([])
{}
"""
self._latex_options = {}
ClonableArray.__init__(self, parent, sorted(map(Set, s), key=min), check=check)
def check(self):
"""
Check that we are a valid set partition.
EXAMPLES::
sage: S = SetPartitions(4)
sage: s = S([[1, 3], [2, 4]])
sage: s.check()
TESTS::
sage: s = S([[1, 2, 3]], check=False)
sage: s.check()
Traceback (most recent call last):
...
ValueError: {{1, 2, 3}} is not an element of Set partitions of {1, 2, 3, 4}
sage: s = S([1, 2, 3])
Traceback (most recent call last):
...
TypeError: Element has no defined underlying set
"""
if self not in self.parent():
raise ValueError("%s is not an element of %s"%(self, self.parent()))
def set_latex_options(self, **kwargs):
r"""
Set the latex options for use in the ``_latex_`` function
- ``tikz_scale`` -- (default: 1) scale for use with tikz package
- ``plot`` -- (default: ``None``) ``None`` returns the set notation,
``linear`` returns a linear plot, ``cyclic`` returns a cyclic
plot
- ``color`` -- (default: ``'black'``) the arc colors
- ``fill`` -- (default: ``False``) if ``True`` then fills ``color``,
else you can pass in a color to alter the fill color -
*only works with cyclic plot*
- ``show_labels`` -- (default: ``True``) if ``True`` shows labels -
*only works with plots*
- ``radius`` -- (default: ``"1cm"``) radius of circle for cyclic
plot - *only works with cyclic plot*
- ``angle`` -- (default: 0) angle for linear plot
EXAMPLES::
sage: SP = SetPartition([[1,6], [3,5,4]])
sage: SP.set_latex_options(tikz_scale=2,plot='linear',fill=True,color='blue',angle=45)
sage: SP.set_latex_options(plot='cyclic')
sage: SP.latex_options()
{'angle': 45,
'color': 'blue',
'fill': True,
'plot': 'cyclic',
'radius': '1cm',
'show_labels': True,
'tikz_scale': 2}
"""
valid_args = ['tikz_scale', 'plot', 'color', 'fill', 'show_labels',
'radius', 'angle']
for key in kwargs:
if key not in valid_args:
raise ValueError("unknown keyword argument: %s"%key)
if key == 'plot':
if not (kwargs['plot'] == 'cyclic'
or kwargs['plot'] == 'linear'
or kwargs['plot'] is None):
raise ValueError("plot must be None, 'cyclic', or 'linear'")
for opt in kwargs:
self._latex_options[opt] = kwargs[opt]
def latex_options(self):
r"""
Return the latex options for use in the ``_latex_`` function as a
dictionary. The default values are set using the global options.
Options can be found in :meth:`set_latex_options`
EXAMPLES::
sage: SP = SetPartition([[1,6], [3,5,4]]); SP.latex_options()
{'angle': 0,
'color': 'black',
'fill': False,
'plot': None,
'radius': '1cm',
'show_labels': True,
'tikz_scale': 1}
"""
opts = self._latex_options.copy()
if "tikz_scale" not in opts:
opts["tikz_scale"] = 1
if "plot" not in opts:
opts["plot"] = None
if "color" not in opts:
opts['color'] = 'black'
if "fill" not in opts:
opts["fill"] = False
if "show_labels" not in opts:
opts['show_labels'] = True
if "radius" not in opts:
opts['radius'] = "1cm"
if "angle" not in opts:
opts['angle'] = 0
return opts
def _latex_(self):
r"""
Return a `\LaTeX` string representation of ``self``.
EXAMPLES::
sage: x = SetPartition([[1,2], [3,5,4]])
sage: latex(x)
\{\{1, 2\}, \{3, 4, 5\}\}
sage: x.set_latex_options(plot='linear', angle=25, color='red')
sage: latex(x)
\begin{tikzpicture}[scale=1]
\node[below=.05cm] at (0,0) {$1$};
\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (0) at (0,0) {};
\node[below=.05cm] at (1,0) {$2$};
\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (1) at (1,0) {};
\node[below=.05cm] at (2,0) {$3$};
\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (2) at (2,0) {};
\node[below=.05cm] at (3,0) {$4$};
\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (3) at (3,0) {};
\node[below=.05cm] at (4,0) {$5$};
\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (4) at (4,0) {};
\draw[color=red] (1) to [out=115,in=65] (0);
\draw[color=red] (3) to [out=115,in=65] (2);
\draw[color=red] (4) to [out=115,in=65] (3);
\end{tikzpicture}
sage: p = SetPartition([['a','c'],['b',1],[20]])
sage: p.set_latex_options(plot='cyclic', color='blue', fill=True, tikz_scale=2)
sage: latex(p)
\begin{tikzpicture}[scale=2]
\draw (0,0) circle [radius=1cm];
\node[label=90:1] (0) at (90:1cm) {};
\node[label=18:20] (1) at (18:1cm) {};
\node[label=-54:a] (2) at (-54:1cm) {};
\node[label=-126:b] (3) at (-126:1cm) {};
\node[label=-198:c] (4) at (-198:1cm) {};
\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] (2.center) -- (4.center) -- cycle;
\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] (0.center) -- (3.center) -- cycle;
\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] (1.center) -- cycle;
\fill[color=black] (0) circle (1.5pt);
\fill[color=black] (1) circle (1.5pt);
\fill[color=black] (2) circle (1.5pt);
\fill[color=black] (3) circle (1.5pt);
\fill[color=black] (4) circle (1.5pt);
\end{tikzpicture}
"""
latex_options = self.latex_options()
if latex_options["plot"] is None:
return repr(self).replace("{",r"\{").replace("}",r"\}")
from sage.misc.latex import latex
latex.add_package_to_preamble_if_available("tikz")
res = "\\begin{{tikzpicture}}[scale={}]\n".format(latex_options['tikz_scale'])
cardinality = self.base_set_cardinality()
from sage.rings.integer_ring import ZZ
if all(x in ZZ for x in self.base_set()):
sort_key = ZZ
else:
sort_key = str
base_set = sorted(self.base_set(), key=sort_key)
color = latex_options['color']
# If we want cyclic plots
if latex_options['plot'] == 'cyclic':
degrees = 360 // cardinality
radius = latex_options['radius']
res += "\\draw (0,0) circle [radius={}];\n".format(radius)
# Add nodes
for k,i in enumerate(base_set):
location = (cardinality - k) * degrees - 270
if latex_options['show_labels']:
res += "\\node[label={}:{}]".format(location, i)
else:
res += "\\node"
res += " ({}) at ({}:{}) {{}};\n".format(k, location, radius)
# Setup partitions
for partition in sorted(self, key=str):
res += "\\draw[-,thick,color="+color
if latex_options['fill'] is not False:
if isinstance(latex_options['fill'], str):
res += ",fill=" + latex_options['fill']
else:
res += ",fill={},fill opacity=0.1".format(color)
res += "] "
res += " -- ".join("({}.center)".format(base_set.index(j))
for j in sorted(partition, key=sort_key))
res += " -- cycle;\n"
# Draw the circles on top
for k in range(len(base_set)):
res += "\\fill[color=black] ({}) circle (1.5pt);\n".format(k)
# If we want line plots
elif latex_options['plot'] == 'linear':
angle = latex_options['angle']
# setup line
for k,i in enumerate(base_set):
if latex_options['show_labels']:
res += "\\node[below=.05cm] at ({},0) {{${}$}};\n".format(k, i)
res += "\\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] "
res += "({k}) at ({k},0) {{}};\n".format(k=k)
# setup arcs
for partition in sorted(self, key=str):
p = sorted(partition, key=sort_key)
if len(p) <= 1:
continue
for k in range(1, len(p)):
res += "\\draw[color={}] ({})".format(color, base_set.index(p[k]))
res += " to [out={},in={}] ".format(90+angle, 90-angle)
res += "({});\n".format(base_set.index(p[k-1]))
else:
raise ValueError("plot must be None, 'cyclic', or 'linear'")
res += "\\end{tikzpicture}"
return res
cardinality = ClonableArray.__len__
size = AbstractSetPartition.base_set_cardinality
def pipe(self, other):
r"""
Return the pipe of the set partitions ``self`` and ``other``.
The pipe of two set partitions is defined as follows:
For any integer `k` and any subset `I` of `\ZZ`, let `I + k`
denote the subset of `\ZZ` obtained by adding `k` to every
element of `k`.
If `B` and `C` are set partitions of `[n]` and `[m]`,
respectively, then the pipe of `B` and `C` is defined as the
set partition
.. MATH::
\{ B_1, B_2, \ldots, B_b,
C_1 + n, C_2 + n, \ldots, C_c + n \}
of `[n+m]`, where `B = \{ B_1, B_2, \ldots, B_b \}` and
`C = \{ C_1, C_2, \ldots, C_c \}`. This pipe is denoted by
`B | C`.
EXAMPLES::
sage: SetPartition([[1,3],[2,4]]).pipe(SetPartition([[1,3],[2]]))
{{1, 3}, {2, 4}, {5, 7}, {6}}
sage: SetPartition([]).pipe(SetPartition([[1,2],[3,5],[4]]))
{{1, 2}, {3, 5}, {4}}
sage: SetPartition([[1,2],[3,5],[4]]).pipe(SetPartition([]))
{{1, 2}, {3, 5}, {4}}
sage: SetPartition([[1,2],[3]]).pipe(SetPartition([[1]]))
{{1, 2}, {3}, {4}}
"""
# Note: GIGO if self and other are not standard.
parts = list(self)
n = self.base_set_cardinality()
for newpart in other:
raised_newpart = Set([i + n for i in newpart])
parts.append(raised_newpart)
return SetPartition(parts)
@combinatorial_map(name='shape')
def shape(self):
r"""
Return the integer partition whose parts are the sizes of the sets
in ``self``.
EXAMPLES::
sage: S = SetPartitions(5)
sage: x = S([[1,2], [3,5,4]])
sage: x.shape()
[3, 2]
sage: y = S([[2], [3,1], [5,4]])
sage: y.shape()
[2, 2, 1]
"""
return Partition(sorted(map(len, self), reverse=True))
# we define aliases for shape()
shape_partition = shape
to_partition = shape
@combinatorial_map(name='to permutation')
def to_permutation(self):
r"""
Convert a set partition of `\{1,...,n\}` to a permutation by considering
the blocks of the partition as cycles.
The cycles are such that the number of excedences is maximised, that is,
each cycle is of the form `(a_1,a_2, ...,a_k)` with `a_1<a_2<...<a_k`.
EXAMPLES::
sage: s = SetPartition([[1,3],[2,4]])
sage: s.to_permutation()
[3, 4, 1, 2]
"""
return Permutation(tuple( map(tuple, self.standard_form()) ))
def apply_permutation(self, p):
r"""
Apply ``p`` to the underlying set of ``self``.
INPUT:
- ``p`` -- a permutation
EXAMPLES::
sage: x = SetPartition([[1,2], [3,5,4]])
sage: p = Permutation([2,1,4,5,3])
sage: x.apply_permutation(p)
{{1, 2}, {3, 4, 5}}
sage: q = Permutation([3,2,1,5,4])
sage: x.apply_permutation(q)
{{1, 4, 5}, {2, 3}}
sage: m = PerfectMatching([(1,4),(2,6),(3,5)])
sage: m.apply_permutation(Permutation([4,1,5,6,3,2]))
[(1, 2), (3, 5), (4, 6)]
"""
return self.__class__(self.parent(), [Set(map(p, B)) for B in self])
def crossings_iterator(self):
r"""
Return the crossing arcs of a set partition on a totally ordered set.
OUTPUT:
We place the elements of the ground set in order on a
line and draw the set partition by linking consecutive
elements of each block in the upper half-plane. This
function returns an iterator over the pairs of crossing
lines (as a line correspond to a pair, the iterator
produces pairs of pairs).
EXAMPLES::
sage: p = SetPartition([[1,4],[2,5,7],[3,6]])
sage: next(p.crossings_iterator())
((1, 4), (2, 5))
TESTS::
sage: p = SetPartition([]); p.crossings()
[]
"""
# each arc is sorted, but the set of arcs might not be
arcs = sorted(self.arcs(), key=min)
while arcs:
i1,j1 = arcs.pop(0)
for i2,j2 in arcs:
# we know that i1 < i2 and i1 < j1 and i2 < j2
if i2 < j1 < j2:
yield ((i1,j1), (i2,j2))
def crossings(self):
r"""
Return the crossing arcs of a set partition on a totally ordered set.
OUTPUT:
We place the elements of the ground set in order on a
line and draw the set partition by linking consecutive
elements of each block in the upper half-plane. This
function returns a list of the pairs of crossing lines
(as a line correspond to a pair, it returns a list of
pairs of pairs).
EXAMPLES::
sage: p = SetPartition([[1,4],[2,5,7],[3,6]])
sage: p.crossings()
[((1, 4), (2, 5)), ((1, 4), (3, 6)), ((2, 5), (3, 6)), ((3, 6), (5, 7))]
TESTS::
sage: p = SetPartition([]); p.crossings()
[]
"""
return list(self.crossings_iterator())
def number_of_crossings(self):
r"""
Return the number of crossings.
OUTPUT:
We place the elements of the ground set in order on a
line and draw the set partition by linking consecutive
elements of each block in the upper half-plane. This
function returns the number the pairs of crossing lines.
EXAMPLES::
sage: p = SetPartition([[1,4],[2,5,7],[3,6]])
sage: p.number_of_crossings()
4
sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
[(1, 3), (2, 8), (4, 7), (5, 6)]
sage: n.number_of_crossings()
1
"""
return Integer( len(list(self.crossings_iterator())) )
def is_noncrossing(self):
r"""
Check if ``self`` is noncrossing.
OUTPUT:
We place the elements of the ground set in order on a
line and draw the set partition by linking consecutive
elements of each block in the upper half-plane. This
function returns ``True`` if the picture obtained this
way has no crossings.
EXAMPLES::
sage: p = SetPartition([[1,4],[2,5,7],[3,6]])
sage: p.is_noncrossing()
False
sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
[(1, 3), (2, 8), (4, 7), (5, 6)]
sage: n.is_noncrossing()