-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
poset_examples.py
1673 lines (1338 loc) · 57.8 KB
/
poset_examples.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
"""
A catalog of posets and lattices.
Some common posets can be accessed through the ``posets.<tab>`` object::
sage: posets.PentagonPoset()
Finite lattice containing 5 elements
Moreover, the set of all posets of order `n` is represented by ``Posets(n)``::
sage: Posets(5)
Posets containing 5 elements
The infinite set of all posets can be used to find minimal examples::
sage: for P in Posets():
....: if not P.is_series_parallel():
....: break
sage: P
Finite poset containing 4 elements
**Catalog of common posets:**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~Posets.AntichainPoset` | Return an antichain on `n` elements.
:meth:`~Posets.BooleanLattice` | Return the Boolean lattice on `2^n` elements.
:meth:`~Posets.ChainPoset` | Return a chain on `n` elements.
:meth:`~Posets.Crown` | Return the crown poset on `2n` elements.
:meth:`~Posets.DiamondPoset` | Return the lattice of rank two on `n` elements.
:meth:`~Posets.DivisorLattice` | Return the divisor lattice of an integer.
:meth:`~Posets.IntegerCompositions` | Return the poset of integer compositions of `n`.
:meth:`~Posets.IntegerPartitions` | Return the poset of integer partitions of ``n``.
:meth:`~Posets.IntegerPartitionsDominanceOrder` | Return the lattice of integer partitions on the integer `n` ordered by dominance.
:meth:`~Posets.NoncrossingPartitions` | Return the poset of noncrossing partitions of a finite Coxeter group ``W``.
:meth:`~Posets.PentagonPoset` | Return the Pentagon poset.
:meth:`~Posets.RandomLattice` | Return a random lattice on `n` elements.
:meth:`~Posets.RandomPoset` | Return a random poset on `n` elements.
:meth:`~Posets.RestrictedIntegerPartitions` | Return the poset of integer partitions of `n`, ordered by restricted refinement.
:meth:`~Posets.SetPartitions` | Return the poset of set partitions of the set `\{1,\dots,n\}`.
:meth:`~Posets.ShardPoset` | Return the shard intersection order.
:meth:`~Posets.SSTPoset` | Return the poset on semistandard tableaux of shape `s` and largest entry `f` that is ordered by componentwise comparison.
:meth:`~Posets.StandardExample` | Return the standard example of a poset with dimension `n`.
:meth:`~Posets.SymmetricGroupAbsoluteOrderPoset` | The poset of permutations with respect to absolute order.
:meth:`~Posets.SymmetricGroupBruhatIntervalPoset` | The poset of permutations with respect to Bruhat order.
:meth:`~Posets.SymmetricGroupBruhatOrderPoset` | The poset of permutations with respect to Bruhat order.
:meth:`~Posets.SymmetricGroupWeakOrderPoset` | The poset of permutations of `\{ 1, 2, \ldots, n \}` with respect to the weak order.
:meth:`~Posets.TamariLattice` | Return the Tamari lattice.
:meth:`~Posets.TetrahedralPoset` | Return the Tetrahedral poset with `n-1` layers based on the input colors.
:meth:`~Posets.UpDownPoset` | Return the up-down poset on `n` elements.
:meth:`~Posets.YoungDiagramPoset` | Return the poset of cells in the Young diagram of a partition.
:meth:`~Posets.YoungsLattice` | Return Young's Lattice up to rank `n`.
:meth:`~Posets.YoungsLatticePrincipalOrderIdeal` | Return the principal order ideal of the partition `lam` in Young's Lattice.
Constructions
-------------
"""
#*****************************************************************************
# Copyright (C) 2008 Peter Jipsen <jipsen@chapman.edu>,
# Franco Saliola <saliola@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
from six import add_metaclass, string_types
from sage.misc.classcall_metaclass import ClasscallMetaclass
import sage.categories.posets
from sage.combinat.permutation import Permutations, Permutation
from sage.combinat.posets.posets import Poset, FinitePoset, FinitePosets_n
from sage.combinat.posets.lattices import (LatticePoset, MeetSemilattice,
JoinSemilattice, FiniteLatticePoset)
from sage.categories.finite_posets import FinitePosets
from sage.categories.finite_lattice_posets import FiniteLatticePosets
from sage.graphs.digraph import DiGraph
from sage.rings.integer import Integer
@add_metaclass(ClasscallMetaclass)
class Posets(object):
r"""
A collection of posets and lattices.
EXAMPLES::
sage: Posets.BooleanLattice(3)
Finite lattice containing 8 elements
sage: Posets.ChainPoset(3)
Finite lattice containing 3 elements
sage: Posets.RandomPoset(17,.15)
Finite poset containing 17 elements
The category of all posets::
sage: Posets()
Category of posets
The enumerated set of all posets on `3` elements, up to an
isomorphism::
sage: Posets(3)
Posets containing 3 elements
.. SEEALSO:: :class:`~sage.categories.posets.Posets`, :class:`FinitePosets`, :func:`Poset`
TESTS::
sage: P = Posets
sage: TestSuite(P).run()
"""
@staticmethod
def __classcall__(cls, n = None):
r"""
Return either the category of all posets, or the finite
enumerated set of all finite posets on ``n`` elements up to an
isomorphism.
EXAMPLES::
sage: Posets()
Category of posets
sage: Posets(4)
Posets containing 4 elements
"""
if n is None:
return sage.categories.posets.Posets()
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
return FinitePosets_n(n)
@staticmethod
def BooleanLattice(n, facade=None):
"""
Return the Boolean lattice containing `2^n` elements.
- ``n`` (an integer) -- number of elements will be `2^n`
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: Posets.BooleanLattice(5)
Finite lattice containing 32 elements
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
if n == 0:
return LatticePoset( ([0], []) )
if n == 1:
return LatticePoset( ([0,1], [[0,1]]) )
L = [[Integer(x|(1<<y)) for y in range(n) if x&(1<<y)==0] for
x in range(2**n)]
D = DiGraph({v: L[v] for v in range(2**n)})
return FiniteLatticePoset(hasse_diagram=D,
category=FiniteLatticePosets(),
facade=facade)
@staticmethod
def ChainPoset(n, facade=None):
"""
Return a chain (a totally ordered poset) containing ``n`` elements.
- ``n`` (an integer) -- number of elements.
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: C = Posets.ChainPoset(6); C
Finite lattice containing 6 elements
sage: C.linear_extension()
[0, 1, 2, 3, 4, 5]
TESTS::
sage: for i in range(5):
....: for j in range(5):
....: if C.covers(C(i),C(j)) and j != i+1:
....: print("TEST FAILED")
Check that :trac:`8422` is solved::
sage: Posets.ChainPoset(0)
Finite lattice containing 0 elements
sage: C = Posets.ChainPoset(1); C
Finite lattice containing 1 elements
sage: C.cover_relations()
[]
sage: C = Posets.ChainPoset(2); C
Finite lattice containing 2 elements
sage: C.cover_relations()
[[0, 1]]
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
D = DiGraph([range(n), [[x,x+1] for x in range(n-1)]],
format='vertices_and_edges')
return FiniteLatticePoset(hasse_diagram=D,
category=FiniteLatticePosets(),
facade=facade)
@staticmethod
def AntichainPoset(n, facade=None):
"""
Return an antichain (a poset with no comparable elements)
containing `n` elements.
INPUT:
- ``n`` (an integer) -- number of elements
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: A = Posets.AntichainPoset(6); A
Finite poset containing 6 elements
TESTS::
sage: for i in range(5):
....: for j in range(5):
....: if A.covers(A(i),A(j)):
....: print("TEST FAILED")
TESTS:
Check that :trac:`8422` is solved::
sage: Posets.AntichainPoset(0)
Finite poset containing 0 elements
sage: C = Posets.AntichainPoset(1); C
Finite poset containing 1 elements
sage: C.cover_relations()
[]
sage: C = Posets.AntichainPoset(2); C
Finite poset containing 2 elements
sage: C.cover_relations()
[]
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
return Poset((range(n), []), facade=facade)
@staticmethod
def PentagonPoset(facade=None):
"""
Return the Pentagon poset.
INPUT:
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: P = Posets.PentagonPoset(); P
Finite lattice containing 5 elements
sage: P.cover_relations()
[[0, 1], [0, 2], [1, 4], [2, 3], [3, 4]]
TESTS:
This is smallest lattice that is not modular::
sage: P.is_modular()
False
This poset and the :meth:`DiamondPoset` are the two smallest
lattices which are not distributive::
sage: P.is_distributive()
False
sage: Posets.DiamondPoset(5).is_distributive()
False
"""
return LatticePoset([[1,2],[4],[3],[4],[]], facade=facade)
@staticmethod
def DiamondPoset(n, facade=None):
"""
Return the lattice of rank two containing ``n`` elements.
INPUT:
- ``n`` -- number of elements, an integer at least 3
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: Posets.DiamondPoset(7)
Finite lattice containing 7 elements
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n <= 2:
raise ValueError("n must be an integer at least 3")
c = [[n-1] for x in range(n)]
c[0] = [x for x in range(1,n-1)]
c[n-1] = []
D = DiGraph({v:c[v] for v in range(n)}, format='dict_of_lists')
return FiniteLatticePoset(hasse_diagram=D,
category=FiniteLatticePosets(),
facade=facade)
@staticmethod
def Crown(n, facade=None):
"""
Return the crown poset of `2n` elements.
In this poset every element `i` for `0 \leq i \leq n-1`
is covered by elements `i+n` and `i+n+1`, except that
`n-1` is covered by `n` and `n+1`.
INPUT:
- ``n`` -- number of elements, an integer at least 2
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: Posets.Crown(3)
Finite poset containing 6 elements
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 2:
raise ValueError("n must be an integer at least 2")
D = {i: [i+n, i+n+1] for i in range(n-1)}
D[n-1] = [n, n+n-1]
return FinitePoset(hasse_diagram=DiGraph(D), category=FinitePosets(),
facade=facade)
@staticmethod
def DivisorLattice(n, facade=None):
"""
Return the divisor lattice of an integer.
Elements of the lattice are divisors of `n` and `x < y` in the
lattice if `x` divides `y`.
INPUT:
- ``n`` -- an integer
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
EXAMPLES::
sage: P = Posets.DivisorLattice(12)
sage: sorted(P.cover_relations())
[[1, 2], [1, 3], [2, 4], [2, 6], [3, 6], [4, 12], [6, 12]]
sage: P = Posets.DivisorLattice(10, facade=False)
sage: P(2) < P(5)
False
TESTS::
sage: Posets.DivisorLattice(1)
Finite lattice containing 1 elements with distinguished linear extension
"""
from sage.arith.misc import divisors, is_prime
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n <= 0:
raise ValueError("n must be a positive integer")
Div_n = divisors(n)
hasse = DiGraph([Div_n, lambda a, b: b%a==0 and is_prime(b//a)])
return FiniteLatticePoset(hasse, elements=Div_n, facade=facade,
category=FiniteLatticePosets())
@staticmethod
def IntegerCompositions(n):
"""
Return the poset of integer compositions of the integer ``n``.
A composition of a positive integer `n` is a list of positive
integers that sum to `n`. The order is reverse refinement:
`[p_1,p_2,...,p_l] < [q_1,q_2,...,q_m]` if `q` consists
of an integer composition of `p_1`, followed by an integer
composition of `p_2`, and so on.
EXAMPLES::
sage: P = Posets.IntegerCompositions(7); P
Finite poset containing 64 elements
sage: len(P.cover_relations())
192
"""
from sage.combinat.composition import Compositions
C = Compositions(n)
return Poset((C, [[c,d] for c in C for d in C if d.is_finer(c)]), cover_relations=False)
@staticmethod
def IntegerPartitions(n):
"""
Return the poset of integer partitions on the integer ``n``.
A partition of a positive integer `n` is a non-increasing list
of positive integers that sum to `n`. If `p` and `q` are
integer partitions of `n`, then `p` covers `q` if and only
if `q` is obtained from `p` by joining two parts of `p`
(and sorting, if necessary).
EXAMPLES::
sage: P = Posets.IntegerPartitions(7); P
Finite poset containing 15 elements
sage: len(P.cover_relations())
28
"""
def lower_covers(partition):
r"""
Nested function for computing the lower covers
of elements in the poset of integer partitions.
"""
lc = []
for i in range(len(partition)-1):
for j in range(i+1,len(partition)):
new_partition = partition[:]
del new_partition[j]
del new_partition[i]
new_partition.append(partition[i]+partition[j])
new_partition.sort(reverse=True)
tup = tuple(new_partition)
if tup not in lc:
lc.append(tup)
return lc
from sage.combinat.partition import Partitions
H = DiGraph(dict([[tuple(p),lower_covers(p)] for p in Partitions(n)]))
return Poset(H.reverse())
@staticmethod
def RestrictedIntegerPartitions(n):
"""
Return the poset of integer partitions on the integer `n`
ordered by restricted refinement.
That is, if `p` and `q` are integer partitions of `n`, then
`p` covers `q` if and only if `q` is obtained from `p` by
joining two distinct parts of `p` (and sorting, if necessary).
EXAMPLES::
sage: P = Posets.RestrictedIntegerPartitions(7); P
Finite poset containing 15 elements
sage: len(P.cover_relations())
17
"""
def lower_covers(partition):
r"""
Nested function for computing the lower covers of elements in the
restricted poset of integer partitions.
"""
lc = []
for i in range(len(partition)-1):
for j in range(i+1,len(partition)):
if partition[i] != partition[j]:
new_partition = partition[:]
del new_partition[j]
del new_partition[i]
new_partition.append(partition[i]+partition[j])
new_partition.sort(reverse=True)
tup = tuple(new_partition)
if tup not in lc:
lc.append(tup)
return lc
from sage.combinat.partition import Partitions
H = DiGraph(dict([[tuple(p),lower_covers(p)] for p in Partitions(n)]))
return Poset(H.reverse())
@staticmethod
def IntegerPartitionsDominanceOrder(n):
r"""
Return the lattice of integer partitions on the integer `n`
ordered by dominance.
That is, if `p=(p_1,\ldots,p_i)` and `q=(q_1,\ldots,q_j)` are
integer partitions of `n`, then `p` is greater than `q` if and
only if `p_1+\cdots+p_k > q_1+\cdots+q_k` for all `k`.
INPUT:
- ``n`` -- a positive integer
EXAMPLES::
sage: P = Posets.IntegerPartitionsDominanceOrder(6); P
Finite lattice containing 11 elements
sage: P.cover_relations()
[[[1, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1]],
[[2, 1, 1, 1, 1], [2, 2, 1, 1]],
[[2, 2, 1, 1], [2, 2, 2]],
[[2, 2, 1, 1], [3, 1, 1, 1]],
[[2, 2, 2], [3, 2, 1]],
[[3, 1, 1, 1], [3, 2, 1]],
[[3, 2, 1], [3, 3]],
[[3, 2, 1], [4, 1, 1]],
[[3, 3], [4, 2]],
[[4, 1, 1], [4, 2]],
[[4, 2], [5, 1]],
[[5, 1], [6]]]
"""
from sage.rings.semirings.non_negative_integer_semiring import NN
if n not in NN:
raise ValueError('n must be an integer')
from sage.combinat.partition import Partitions, Partition
return LatticePoset((Partitions(n), Partition.dominates)).dual()
@staticmethod
def RandomPoset(n, p):
r"""
Generate a random poset on ``n`` elements according to a
probability ``p``.
INPUT:
- ``n`` - number of elements, a non-negative integer
- ``p`` - a probability, a real number between 0 and 1 (inclusive)
OUTPUT:
A poset on `n` elements. The probability `p` roughly measures
width/height of the output: `p=0` always generates an antichain,
`p=1` will return a chain. To create interesting examples,
keep the probability small, perhaps on the order of `1/n`.
EXAMPLES::
sage: set_random_seed(0) # Results are reproducible
sage: P = Posets.RandomPoset(5, 0.3)
sage: P.cover_relations()
[[5, 4], [4, 2], [1, 2]]
.. SEEALSO:: :meth:`RandomLattice`
TESTS::
sage: Posets.RandomPoset('junk', 0.5)
Traceback (most recent call last):
...
TypeError: number of elements must be an integer, not junk
sage: Posets.RandomPoset(-6, 0.5)
Traceback (most recent call last):
...
ValueError: number of elements must be non-negative, not -6
sage: Posets.RandomPoset(6, 'garbage')
Traceback (most recent call last):
...
TypeError: probability must be a real number, not garbage
sage: Posets.RandomPoset(6, -0.5)
Traceback (most recent call last):
...
ValueError: probability must be between 0 and 1, not -0.5
sage: Posets.RandomPoset(0, 0.5)
Finite poset containing 0 elements
"""
from sage.misc.prandom import random
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
try:
p = float(p)
except Exception:
raise TypeError("probability must be a real number, not {0}".format(p))
if p < 0 or p> 1:
raise ValueError("probability must be between 0 and 1, not {0}".format(p))
D = DiGraph(loops=False, multiedges=False)
D.add_vertices(range(n))
for i in range(n):
for j in range(i+1, n):
if random() < p:
D.add_edge(i, j)
D.relabel(list(Permutations(n).random_element()))
return Poset(D, cover_relations=False)
@staticmethod
def RandomLattice(n, p, properties=None):
r"""
Return a random lattice on ``n`` elements.
INPUT:
- ``n`` -- number of elements, a non-negative integer
- ``p`` -- a probability, a positive real number less than one
- ``properties`` -- a list of properties for the lattice. Currently
implemented:
* ``None``, no restrictions for lattices to create
* ``'planar'``, the lattice has an upward planar drawing
* ``'dismantlable'`` (implicated by ``'planar'``)
* ``'distributive'`` (implicated by ``'stone'``)
* ``'stone'``
OUTPUT:
A lattice on `n` elements. When ``properties`` is ``None``,
the probability `p` roughly measures number of covering
relations of the lattice. To create interesting examples, make
the probability near one, something like `0.98..0.999`.
Currently parameter ``p`` has no effect only when ``properties``
is not ``None``.
.. NOTE::
Results are reproducible in same Sage version only. Underlying
algorithm may change in future versions.
EXAMPLES::
sage: set_random_seed(0) # Results are reproducible
sage: L = Posets.RandomLattice(8, 0.995); L
Finite lattice containing 8 elements
sage: L.cover_relations()
[[7, 6], [7, 3], [7, 1], ..., [5, 4], [2, 4], [1, 4], [0, 4]]
sage: L = Posets.RandomLattice(10, 0, properties=['dismantlable'])
sage: L.is_dismantlable()
True
.. SEEALSO:: :meth:`RandomPoset`
TESTS::
sage: Posets.RandomLattice('junk', 0.5)
Traceback (most recent call last):
...
TypeError: number of elements must be an integer, not junk
sage: Posets.RandomLattice(-6, 0.5)
Traceback (most recent call last):
...
ValueError: number of elements must be non-negative, not -6
sage: Posets.RandomLattice(6, 'garbage')
Traceback (most recent call last):
...
TypeError: probability must be a real number, not garbage
sage: Posets.RandomLattice(6, -0.5)
Traceback (most recent call last):
...
ValueError: probability must be a positive real number and below 1, not -0.5
sage: Posets.RandomLattice(10, 0.5, properties=['junk'])
Traceback (most recent call last):
...
ValueError: unknown value junk for 'properties'
sage: Posets.RandomLattice(0, 0.5)
Finite lattice containing 0 elements
"""
from copy import copy
try:
n = Integer(n)
except TypeError:
raise TypeError("number of elements must be an integer, not {0}".format(n))
if n < 0:
raise ValueError("number of elements must be non-negative, not {0}".format(n))
try:
p = float(p)
except Exception:
raise TypeError("probability must be a real number, not {0}".format(p))
if p < 0 or p >= 1:
raise ValueError("probability must be a positive real number and below 1, not {0}".format(p))
if properties is None:
# Basic case, no special properties for lattice asked.
if n <= 3:
return Posets.ChainPoset(n)
covers = _random_lattice(n, p)
covers_dict = {i:covers[i] for i in range(n)}
D = DiGraph(covers_dict)
D.relabel([i-1 for i in Permutations(n).random_element()])
return LatticePoset(D, cover_relations=True)
if isinstance(properties, string_types):
properties = set([properties])
else:
properties = set(properties)
known_properties = set(['planar', 'dismantlable', 'distributive', 'stone'])
errors = properties.difference(known_properties)
if errors:
raise ValueError("unknown value %s for 'properties'" % errors.pop())
if n <= 3:
# Change this, if property='complemented' is added
return Posets.ChainPoset(n)
# Handling properties: planar => dismantlable, stone => distributive
if 'planar' in properties:
properties.discard('dismantlable')
if 'stone' in properties:
properties.discard('distributive')
# Test property combinations that are not implemented.
if 'distributive' in properties and len(properties) > 1:
raise NotImplementedError("combining 'distributive' with other properties is not implemented")
if 'stone' in properties and len(properties) > 1:
raise NotImplementedError("combining 'stone' with other properties is not implemented")
if properties == set(['planar']):
D = _random_planar_lattice(n)
D.relabel([i-1 for i in Permutations(n).random_element()])
return LatticePoset(D)
if properties == set(['dismantlable']):
D = _random_dismantlable_lattice(n)
D.relabel([i-1 for i in Permutations(n).random_element()])
return LatticePoset(D)
if properties == set(['stone']):
D = _random_stone_lattice(n)
D.relabel([i-1 for i in Permutations(n).random_element()])
return LatticePoset(D)
if properties == set(['distributive']):
tmp = Poset(_random_distributive_lattice(n)).order_ideals_lattice(as_ideals=False)
D = copy(tmp._hasse_diagram)
D.relabel([i-1 for i in Permutations(n).random_element()])
return LatticePoset(D)
raise AssertionError("Bug in RandomLattice().")
@staticmethod
def SetPartitions(n):
r"""
Return the lattice of set partitions of the set `\{1,\ldots,n\}`
ordered by refinement.
INPUT:
- ``n`` -- a positive integer
EXAMPLES::
sage: Posets.SetPartitions(4)
Finite lattice containing 15 elements
"""
from sage.rings.semirings.non_negative_integer_semiring import NN
if n not in NN:
raise ValueError('n must be an integer')
from sage.combinat.set_partition import SetPartitions
S = SetPartitions(n)
def covers(x):
for i, s in enumerate(x):
for j in range(i+1, len(x)):
L = list(x)
L[i] = s.union(x[j])
L.pop(j)
yield S(L)
return LatticePoset({x: list(covers(x)) for x in S},
cover_relations=True)
@staticmethod
def SSTPoset(s, f=None):
"""
The poset on semistandard tableaux of shape ``s`` and largest
entry ``f`` that is ordered by componentwise comparison of the
entries.
INPUT:
- ``s`` - shape of the tableaux
- ``f`` - maximum fill number. This is an optional
argument. If no maximal number is given, it will use
the number of cells in the shape.
NOTE: This is a basic implementation and most certainly
not the most efficient.
EXAMPLES::
sage: Posets.SSTPoset([2,1])
Finite poset containing 8 elements
sage: Posets.SSTPoset([2,1],4)
Finite poset containing 20 elements
sage: Posets.SSTPoset([2,1],2).cover_relations()
[[[[1, 1], [2]], [[1, 2], [2]]]]
sage: Posets.SSTPoset([3,2]).bottom() # long time (6s on sage.math, 2012)
[[1, 1, 1], [2, 2]]
sage: Posets.SSTPoset([3,2],4).maximal_elements()
[[[3, 3, 4], [4, 4]]]
"""
from sage.combinat.tableau import SemistandardTableaux
def tableaux_is_less_than(a, b):
atstring = []
btstring = []
for i in a:
atstring += i
for i in b:
btstring += i
for i in range(len(atstring)):
if atstring[i] > btstring[i]:
return False
return True
if f is None:
f=0
for i in s:
f += i
E = SemistandardTableaux(s, max_entry=f)
return Poset((E, tableaux_is_less_than))
@staticmethod
def StandardExample(n, facade=None):
r"""
Return the partially ordered set on ``2n`` elements with
dimension ``n``.
Let `P` be the poset on `\{0, 1, 2, \ldots, 2n-1\}` whose defining
relations are that `i < j` for every `0 \leq i < n \leq j < 2n`
except when `i + n = j`. The poset `P` is the so-called
*standard example* of a poset with dimension `n`.
INPUT:
- ``n`` -- an integer `\ge 2`, dimension of the constructed poset
- ``facade`` (boolean) -- whether to make the returned poset a
facade poset (see :mod:`sage.categories.facade_sets`); the
default behaviour is the same as the default behaviour of
the :func:`~sage.combinat.posets.posets.Poset` constructor
OUTPUT:
The standard example of a poset of dimension `n`.
EXAMPLES::
sage: A = Posets.StandardExample(3); A
Finite poset containing 6 elements
sage: A.dimension()
3
REFERENCES:
- [Gar2015]_
- [Ros1999]_
TESTS::
sage: A = Posets.StandardExample(10); A
Finite poset containing 20 elements
sage: len(A.cover_relations())
90
sage: P = Posets.StandardExample(5, facade=False)
sage: P(4) < P(3), P(4) > P(3)
(False, False)
"""
try:
n = Integer(n)
except TypeError:
raise TypeError("dimension must be an integer, not {0}".format(n))
if n < 2:
raise ValueError("dimension must be at least 2, not {0}".format(n))
return Poset((range(2*n), [[i, j+n] for i in range(n)
for j in range(n) if i != j]),
facade=facade)
@staticmethod
def SymmetricGroupBruhatOrderPoset(n):
"""
The poset of permutations with respect to Bruhat order.
EXAMPLES::
sage: Posets.SymmetricGroupBruhatOrderPoset(4)
Finite poset containing 24 elements
"""
if n < 10:
element_labels = {s: "".join(str(x) for x in s)
for s in Permutations(n)}
return Poset({s: s.bruhat_succ() for s in Permutations(n)},
element_labels)
@staticmethod
def SymmetricGroupBruhatIntervalPoset(start, end):
"""
The poset of permutations with respect to Bruhat order.
INPUT:
- ``start`` - list permutation
- ``end`` - list permutation (same n, of course)
.. note::
Must have ``start`` <= ``end``.
EXAMPLES:
Any interval is rank symmetric if and only if it avoids these
permutations::
sage: P1 = Posets.SymmetricGroupBruhatIntervalPoset([1,2,3,4], [3,4,1,2])
sage: P2 = Posets.SymmetricGroupBruhatIntervalPoset([1,2,3,4], [4,2,3,1])
sage: ranks1 = [P1.rank(v) for v in P1]
sage: ranks2 = [P2.rank(v) for v in P2]
sage: [ranks1.count(i) for i in uniq(ranks1)]
[1, 3, 5, 4, 1]
sage: [ranks2.count(i) for i in uniq(ranks2)]
[1, 3, 5, 6, 4, 1]
"""
start = Permutation(start)
end = Permutation(end)
if len(start) != len(end):
raise TypeError("Start (%s) and end (%s) must have same length." % (start, end))
if not start.bruhat_lequal(end):
raise TypeError("Must have start (%s) <= end (%s) in Bruhat order." % (start, end))
unseen = [start]
nodes = {}
while unseen:
perm = unseen.pop(0)
nodes[perm] = [succ_perm for succ_perm in perm.bruhat_succ()
if succ_perm.bruhat_lequal(end)]
for succ_perm in nodes[perm]:
if succ_perm not in nodes:
unseen.append(succ_perm)
return Poset(nodes)
@staticmethod
def SymmetricGroupWeakOrderPoset(n, labels="permutations", side="right"):