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
/
tableau.py
6608 lines (5407 loc) · 216 KB
/
tableau.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"""
Tableaux
AUTHORS:
- Mike Hansen (2007): initial version
- Jason Bandlow (2011): updated to use Parent/Element model, and many
minor fixes
- Andrew Mathas (2012-13): completed the transition to the parent/element model
begun by Jason Bandlow
- Travis Scrimshaw (11-22-2012): Added tuple options, changed ``*katabolism*``
to ``*catabolism*``. Cleaned up documentation.
This file consists of the following major classes:
Element classes:
* :class:`Tableau`
* :class:`SemistandardTableau`
* :class:`StandardTableau`
Factory classes:
* :class:`Tableaux`
* :class:`SemistandardTableaux`
* :class:`StandardTableaux`
Parent classes:
* :class:`Tableaux_all`
* :class:`Tableaux_size`
* :class:`SemistandardTableaux_all` (facade class)
* :class:`SemistandardTableaux_size`
* :class:`SemistandardTableaux_size_inf`
* :class:`SemistandardTableaux_size_weight`
* :class:`SemistandardTableaux_shape`
* :class:`SemistandardTableaux_shape_inf`
* :class:`SemistandardTableaux_shape_weight`
* :class:`StandardTableaux_all` (facade class)
* :class:`StandardTableaux_size`
* :class:`StandardTableaux_shape`
For display options, see :meth:`Tableaux.global_options`.
.. TODO:
- Move methods that only apply to semistandard tableaux from tableau to
semistandard tableau
- Copy/move functionality to skew tableaux
- Add a class for tableaux of a given shape (eg Tableaux_shape)
"""
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
# 2011 Jason Bandlow <jbandlow@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 sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets
from sage.sets.family import Family
from sage.sets.non_negative_integers import NonNegativeIntegers
from sage.structure.global_options import GlobalOptions
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.list_clone import ClonableList
from sage.structure.parent import Parent
from sage.misc.classcall_metaclass import ClasscallMetaclass
from sage.rings.infinity import PlusInfinity
from sage.rings.arith import factorial
from sage.rings.integer import Integer
from sage.combinat.composition import Composition, Compositions
from integer_vector import IntegerVectors
import sage.libs.symmetrica.all as symmetrica
import sage.misc.prandom as random
import permutation
import itertools
from sage.groups.perm_gps.permgroup import PermutationGroup
from sage.misc.all import uniq, prod
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.categories.sets_cat import Sets
from sage.combinat.combinatorial_map import combinatorial_map
TableauOptions=GlobalOptions(name='tableaux',
doc=r"""
Sets the global options for elements of the tableau, skew_tableau,
and tableau tuple classes. The defaults are for tableau to be
displayed as a list, latexed as a Young diagram using the English
convention.
""",
end_doc=r"""
.. NOTE::
Changing the ``convention`` for tableaux also changes the
``convention`` for partitions.
If no parameters are set, then the function returns a copy of the
options dictionary.
EXAMPLES::
sage: T = Tableau([[1,2,3],[4,5]])
sage: T
[[1, 2, 3], [4, 5]]
sage: Tableaux.global_options(display="array")
sage: T
1 2 3
4 5
sage: Tableaux.global_options(convention="french")
sage: T
4 5
1 2 3
Changing the ``convention`` for tableaux also changes the ``convention``
for partitions and vice versa::
sage: P = Partition([3,3,1])
sage: print P.ferrers_diagram()
*
***
***
sage: Partitions.global_options(convention="english")
sage: print P.ferrers_diagram()
***
***
*
sage: T
1 2 3
4 5
The ASCII art can also be changed::
sage: t = Tableau([[1,2,3],[4,5]])
sage: ascii_art(t)
1 2 3
4 5
sage: Tableaux.global_options(ascii_art="table")
sage: ascii_art(t)
+---+---+
| 4 | 5 |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
sage: Tableaux.global_options(ascii_art="compact")
sage: ascii_art(t)
|4|5|
|1|2|3|
sage: Tableaux.global_options.reset()
""",
display=dict(default="list",
description='Controls the way in which tableaux are printed',
values=dict(list='print tableaux as lists',
diagram='display as Young diagram (similar to :meth:`~sage.combinat.tableau.Tableau.pp()`',
compact='minimal length string representation'),
alias=dict(array="diagram", ferrers_diagram="diagram", young_diagram="diagram"),
case_sensitive=False),
ascii_art=dict(default="repr",
description='Controls the ascii art output for tableaux',
values=dict(repr='display using the diagram string representation',
table='display as a table',
compact='minimal length ascii art'),
case_sensitive=False),
latex=dict(default="diagram",
description='Controls the way in which tableaux are latexed',
values=dict(list='as a list', diagram='as a Young diagram'),
alias=dict(array="diagram", ferrers_diagram="diagram", young_diagram="diagram"),
case_sensitive=False),
convention=dict(default="English",
description='Sets the convention used for displaying tableaux and partitions',
values=dict(English='use the English convention',French='use the French convention'),
case_sensitive=False),
notation = dict(alt_name="convention")
)
class Tableau(ClonableList):
"""
A class to model a tableau.
INPUT:
- ``t`` -- a Tableau, a list of iterables, or an empty list
OUTPUT:
- A Tableau object constructed from ``t``.
A tableau is abstractly a mapping from the cells in a partition to
arbitrary objects (called entries). It is often represented as a
finite list of nonempty lists (or generally an iterable of
iterables) of weakly decreasing lengths. This list,
in particular, can be empty, representing the empty tableau.
Note that Sage uses the English convention for partitions and
tableaux; the longer rows are displayed on top.
EXAMPLES::
sage: t = Tableau([[1,2,3],[4,5]]); t
[[1, 2, 3], [4, 5]]
sage: t.shape()
[3, 2]
sage: t.pp() # pretty print
1 2 3
4 5
sage: t.is_standard()
True
sage: Tableau([['a','c','b'],[[],(2,1)]])
[['a', 'c', 'b'], [[], (2, 1)]]
sage: Tableau([]) # The empty tableau
[]
When using code that will generate a lot of tableaux, it is slightly more
efficient to construct a Tableau from the appropriate Parent object::
sage: T = Tableaux()
sage: T([[1, 2, 3], [4, 5]])
[[1, 2, 3], [4, 5]]
.. SEEALSO:
- :class:`Tableaux`
- :class:`SemistandardTableaux`
- :class:`SemistandardTableau`
- :class:`StandardTableaux`
- :class:`StandardTableau`
TESTS::
sage: Tableau([[1],[2,3]])
Traceback (most recent call last):
...
ValueError: A tableau must be a list of iterables of weakly decreasing length.
sage: Tableau([1,2,3])
Traceback (most recent call last):
...
ValueError: A tableau must be a list of iterables.
"""
__metaclass__ = ClasscallMetaclass
@staticmethod
def __classcall_private__(cls, t):
r"""
This ensures that a tableau is only ever constructed as an
``element_class`` call of an appropriate parent.
TESTS::
sage: t = Tableau([[1,1],[1]])
sage: TestSuite(t).run()
sage: t.parent()
Tableaux
sage: t.category()
Category of elements of Tableaux
sage: type(t)
<class 'sage.combinat.tableau.Tableaux_all_with_category.element_class'>
"""
if isinstance(t, cls):
return t
# We must verify ``t`` is a list of iterables, and also
# normalize it to be a list of tuples.
try:
t = map(tuple, t)
except TypeError:
raise ValueError("A tableau must be a list of iterables.")
return Tableaux_all().element_class(Tableaux_all(), t)
def __init__(self, parent, t):
r"""
Initialize a tableau.
TESTS::
sage: t = Tableaux()([[1,1],[1]])
sage: s = Tableaux(3)([[1,1],[1]])
sage: s==t
True
sage: t.parent()
Tableaux
sage: s.parent()
Tableaux of size 3
sage: r = Tableaux()(s); r.parent()
Tableaux
sage: s is t # identical tableaux are distinct objects
False
A tableau is shallowly immutable. See :trac:`15862`. The entries
themselves may be mutable objects, though in that case the
resulting Tableau should be unhashable.
sage: T = Tableau([[1,2],[2]])
sage: t0 = T[0]
sage: t0[1] = 3
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
sage: T[0][1] = 5
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
"""
if isinstance(t, Tableau):
# Since we are (supposed to be) immutable, we can share the underlying data
ClonableList.__init__(self, parent, t)
return
# Normalize t to be a list of tuples.
t = map(tuple, t)
ClonableList.__init__(self, parent, t)
# This dispatches the input verification to the :meth:`check`
# method.
def __eq__(self, other):
r"""
Check whether ``self`` is equal to ``other``.
.. TODO::
This overwrites the equality check of
:class:`~sage.structure.list_clone.ClonableList`
in order to circumvent the coercion framework.
Eventually this should be solved more elegantly,
for example along the lines of what was done for
`k`-tableaux.
For now, two elements are equal if their underlying
defining lists compare equal.
INPUT:
``other`` -- the element that ``self`` is compared to
OUTPUT:
A Boolean.
TESTS::
sage: t = Tableau([[1,2]])
sage: t == 0
False
sage: t == Tableaux(2)([[1,2]])
True
"""
if isinstance(other, Tableau):
return list(self) == list(other)
else:
return list(self) == other
def __ne__(self, other):
r"""
Check whether ``self`` is unequal to ``other``.
See the documentation of :meth:`__eq__`.
INPUT:
``other`` -- the element that ``self`` is compared to
OUTPUT:
A Boolean.
TESTS::
sage: t = Tableau([[2,3],[1]])
sage: t != []
True
"""
if isinstance(other, Tableau):
return list(self) != list(other)
else:
return list(self) != other
def check(self):
r"""
Check that ``self`` is a valid straight-shape tableau.
EXAMPLES::
sage: t = Tableau([[1,1],[2]])
sage: t.check()
sage: t = Tableau([[None, None, 1], [2, 4], [3, 4, 5]])
Traceback (most recent call last):
...
ValueError: A tableau must be a list of iterables of weakly decreasing length.
"""
# Check that it has partition shape. That's all we require from a
# general tableau.
lens = map(len, self)
for (a, b) in itertools.izip(lens, lens[1:]):
if a < b:
raise ValueError("A tableau must be a list of iterables of weakly decreasing length.")
if lens and lens[-1] == 0:
raise ValueError("A tableau must not have empty rows.")
def _repr_(self):
"""
Return a string representation of ``self``.
EXAMPLES::
sage: t = Tableau([[1,2,3],[4,5]])
sage: Tableaux.global_options(display="list")
sage: t
[[1, 2, 3], [4, 5]]
sage: Tableaux.global_options(display="array")
sage: t
1 2 3
4 5
sage: Tableaux.global_options(display="compact"); t
1,2,3/4,5
sage: Tableaux.global_options.reset()
"""
return self.parent().global_options.dispatch(self,'_repr_','display')
def _repr_list(self):
"""
Return a string representation of ``self`` as a list.
EXAMPLES::
sage: T = Tableau([[1,2,3],[4,5]])
sage: T._repr_list()
'[[1, 2, 3], [4, 5]]'
"""
return repr(map(list, self))
# See #18024. CombinatorialObject provided __str__, though ClonableList
# doesn't. Emulate the old functionality. Possibly remove when
# CombinatorialObject is removed.
__str__ = _repr_list
def _repr_diagram(self):
"""
Return a string representation of ``self`` as an array.
EXAMPLES::
sage: t = Tableau([[1,2,3],[4,5]])
sage: print t._repr_diagram()
1 2 3
4 5
sage: Tableaux.global_options(convention="french")
sage: print t._repr_diagram()
4 5
1 2 3
sage: Tableaux.global_options.reset()
"""
if self.parent().global_options('convention') == "English":
return '\n'.join(["".join(map(lambda x: "%3s"%str(x) , row)) for row in self])
else:
return '\n'.join(["".join(map(lambda x: "%3s"%str(x) , row)) for row in reversed(self)])
def _repr_compact(self):
"""
Return a compact string representation of ``self``.
EXAMPLES::
sage: Tableau([[1,2,3],[4,5]])._repr_compact()
'1,2,3/4,5'
sage: Tableau([])._repr_compact()
'-'
"""
if not self:
return '-'
return '/'.join(','.join('%s'%r for r in row) for row in self)
def _ascii_art_(self):
"""
TESTS::
sage: ascii_art(list(StandardTableaux(3)))
[ 1 ]
[ 1 3 1 2 2 ]
[ 1 2 3, 2 , 3 , 3 ]
sage: Tableaux.global_options(ascii_art="compact")
sage: ascii_art(list(StandardTableaux(3)))
[ |1| ]
[ |1|3| |1|2| |2| ]
[ |1|2|3|, |2| , |3| , |3| ]
sage: Tableaux.global_options(convention="french", ascii_art="table")
sage: ascii_art(list(StandardTableaux(3)))
[ +---+ ]
[ | 3 | ]
[ +---+ +---+ +---+ ]
[ | 2 | | 3 | | 2 | ]
[ +---+---+---+ +---+---+ +---+---+ +---+ ]
[ | 1 | 2 | 3 | | 1 | 3 | | 1 | 2 | | 1 | ]
[ +---+---+---+, +---+---+, +---+---+, +---+ ]
sage: Tableaux.global_options(ascii_art="repr")
sage: ascii_art(list(StandardTableaux(3)))
[ 3 ]
[ 2 3 2 ]
[ 1 2 3, 1 3, 1 2, 1 ]
sage: Tableaux.global_options.reset()
"""
ascii = self.parent().global_options.dispatch(self,'_ascii_art_','ascii_art')
from sage.misc.ascii_art import AsciiArt
return AsciiArt(ascii.splitlines())
def _unicode_art_(self):
r"""
TESTS::
sage: unicode_art(Tableau([[1,2,3],[4],[5]]))
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┴───┘
│ 4 │
├───┤
│ 5 │
└───┘
sage: unicode_art(Tableau([]))
┌┐
└┘
"""
from sage.typeset.unicode_art import UnicodeArt
return UnicodeArt(self._ascii_art_table(unicode=True).splitlines())
_ascii_art_repr = _repr_diagram
def _ascii_art_table(self, unicode=False):
"""
TESTS:
We check that :trac:`16487` is fixed::
sage: t = Tableau([[1,2,3],[4,5]])
sage: print t._ascii_art_table()
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 |
+---+---+
sage: Tableaux.global_options(convention="french")
sage: print t._ascii_art_table()
+---+---+
| 4 | 5 |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
sage: t = Tableau([]); print t._ascii_art_table()
++
++
sage: Tableaux.global_options.reset()
sage: t = Tableau([[1,2,3,10,15],[12,15,17]])
sage: print t._ascii_art_table()
+----+----+----+----+----+
| 1 | 2 | 3 | 10 | 15 |
+----+----+----+----+----+
| 12 | 15 | 17 |
+----+----+----+
sage: t = Tableau([[1,2,15,7],[12,5,6],[8,10],[9]])
sage: Tableaux.global_options(ascii_art='table')
sage: ascii_art(t)
+----+----+----+---+
| 1 | 2 | 15 | 7 |
+----+----+----+---+
| 12 | 5 | 6 |
+----+----+----+
| 8 | 10 |
+----+----+
| 9 |
+----+
sage: Tableaux.global_options(convention='french')
sage: ascii_art(t)
+----+
| 9 |
+----+----+
| 8 | 10 |
+----+----+----+
| 12 | 5 | 6 |
+----+----+----+---+
| 1 | 2 | 15 | 7 |
+----+----+----+---+
sage: Tableaux.global_options.reset()
Unicode version::
sage: t = Tableau([[1,2,15,7],[12,5],[8,10],[9]])
sage: print t._ascii_art_table(unicode=True)
┌────┬────┬────┬───┐
│ 1 │ 2 │ 15 │ 7 │
├────┼────┼────┴───┘
│ 12 │ 5 │
├────┼────┤
│ 8 │ 10 │
├────┼────┘
│ 9 │
└────┘
sage: Tableaux().global_options(convention='french')
sage: t = Tableau([[1,2,15,7],[12,5],[8,10],[9]])
sage: print t._ascii_art_table(unicode=True)
┌────┐
│ 9 │
├────┼────┐
│ 8 │ 10 │
├────┼────┤
│ 12 │ 5 │
├────┼────┼────┬───┐
│ 1 │ 2 │ 15 │ 7 │
└────┴────┴────┴───┘
sage: Tableaux.global_options.reset()
"""
if unicode:
import unicodedata
v = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL')
h = unicodedata.lookup('BOX DRAWINGS LIGHT HORIZONTAL')
dl = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND LEFT')
dr = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND RIGHT')
ul = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND LEFT')
ur = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND RIGHT')
vr = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND RIGHT')
vl = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND LEFT')
uh = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND HORIZONTAL')
dh = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND HORIZONTAL')
vh = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL')
else:
v = '|'
h = '-'
dl = dr = ul = ur = vr = vl = uh = dh = vh = '+'
if len(self) == 0:
return dr + dl + '\n' + ur + ul
# Get the widths of the columns
str_tab = map(lambda row: map(str, row), self)
col_widths = [1]*len(str_tab[0])
for row in str_tab:
for i,e in enumerate(row):
col_widths[i] = max(col_widths[i], len(e))
matr = [] # just the list of lines
l1 = ""
l1 += dr + h*(2+col_widths[0])
for w in col_widths[1:]:
l1 += dh + h + h + h*w
matr.append(l1 + dl)
for nrow,row in enumerate(str_tab):
l1 = ""; l2 = ""
n = len(str_tab[nrow+1]) if nrow+1 < len(str_tab) else 0
for i,(e,w) in enumerate(zip(row,col_widths)):
if i == 0:
if n:
l1 += vr + h*(2+w)
else:
l1 += ur + h*(2+w)
elif i <= n:
l1 += vh + h*(2+w)
else:
l1 += uh + h*(2+w)
if unicode:
l2 += u"{} {:^{width}} ".format(v, e, width=w)
else:
l2 += "{} {:^{width}} ".format(v, e, width=w)
if i+1 <= n:
l1 += vl
else:
l1 += ul
l2 += v
matr.append(l2)
matr.append(l1)
if self.parent().global_options('convention') == "English":
return "\n".join(matr)
else:
output = "\n".join(reversed(matr))
if unicode:
tr = {
ord(dl): ul, ord(dr): ur,
ord(ul): dl, ord(ur): dr,
ord(dh): uh, ord(uh): dh}
return output.translate(tr)
else:
return output
def _ascii_art_compact(self):
"""
TESTS:
We check that :trac:`16487` is fixed::
sage: t = Tableau([[1,2,3],[4,5]])
sage: print t._ascii_art_compact()
|1|2|3|
|4|5|
sage: Tableaux.global_options(convention="french")
sage: print t._ascii_art_compact()
|4|5|
|1|2|3|
sage: Tableaux.global_options.reset()
sage: t = Tableau([[1,2,3,10,15],[12,15,17]])
sage: print t._ascii_art_compact()
|1 |2 |3 |10|15|
|12|15|17|
"""
if len(self) == 0:
return "."
if self.parent().global_options('convention') == "English":
T = self
else:
T = reversed(self)
# Get the widths of the columns
str_tab = map(lambda row: map(str, row), T)
col_widths = [1]*len(self[0])
for row in str_tab:
for i,e in enumerate(row):
col_widths[i] = max(col_widths[i], len(e))
return "\n".join("|"
+ "|".join("{:^{width}}".format(e,width=col_widths[i]) for i,e in enumerate(row))
+ "|" for row in str_tab)
def _latex_(self):
r"""
Return a LaTeX version of ``self``.
EXAMPLES::
sage: t = Tableau([[1,1,2],[2,3],[3]])
sage: latex(t) # indirect doctest
{\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}}
\raisebox{-.6ex}{$\begin{array}[b]{*{3}c}\cline{1-3}
\lr{1}&\lr{1}&\lr{2}\\\cline{1-3}
\lr{2}&\lr{3}\\\cline{1-2}
\lr{3}\\\cline{1-1}
\end{array}$}
}
sage: Tableaux.global_options(convention="french")
sage: latex(t) # indirect doctest
{\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}}
\raisebox{-.6ex}{$\begin{array}[t]{*{3}c}\cline{1-1}
\lr{3}\\\cline{1-2}
\lr{2}&\lr{3}\\\cline{1-3}
\lr{1}&\lr{1}&\lr{2}\\\cline{1-3}
\end{array}$}
}
sage: Tableaux.global_options.reset()
"""
return self.parent().global_options.dispatch(self,'_latex_', 'latex')
_latex_list=_repr_list
def _latex_diagram(self):
r"""
Return a LaTeX representation of ``self`` as a Young diagram.
EXAMPLES::
sage: t = Tableau([[1,1,2],[2,3],[3]])
sage: print t._latex_diagram()
{\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}}
\raisebox{-.6ex}{$\begin{array}[b]{*{3}c}\cline{1-3}
\lr{1}&\lr{1}&\lr{2}\\\cline{1-3}
\lr{2}&\lr{3}\\\cline{1-2}
\lr{3}\\\cline{1-1}
\end{array}$}
}
"""
if len(self) == 0:
return "{\\emptyset}"
from output import tex_from_array
return tex_from_array(self)
def __div__(self, t):
"""
Return the skew tableau ``self``/``t``, where ``t`` is a partition
contained in the shape of ``self``.
EXAMPLES::
sage: t = Tableau([[1,2,3],[3,4],[5]])
sage: t/[1,1]
[[None, 2, 3], [None, 4], [5]]
sage: t/[3,1]
[[None, None, None], [None, 4], [5]]
sage: t/[2,1,1,1]
Traceback (most recent call last):
...
ValueError: the shape of the tableau must contain the partition
"""
from sage.combinat.partition import Partition
#if t is a list, convert to to a partition first
if isinstance(t, list):
t = Partition(t)
#Check to make sure that tableau shape contains t
if not self.shape().contains(t):
raise ValueError("the shape of the tableau must contain the partition")
st = [list(row) for row in self] # create deep copy of t
for i, t_i in enumerate(t):
st_i = st[i]
for j in range(t_i):
st_i[j] = None
from sage.combinat.skew_tableau import SkewTableau
return SkewTableau(st)
def __call__(self, *cell):
r"""
INPUT:
- ``cell`` -- a pair of integers, tuple, or list specifying a cell in
the tableau
OUTPUT:
- The value in the corresponding cell.
EXAMPLES::
sage: t = Tableau([[1,2,3],[4,5]])
sage: t(1,0)
4
sage: t((1,0))
4
sage: t(3,3)
Traceback (most recent call last):
...
IndexError: The cell (3,3) is not contained in [[1, 2, 3], [4, 5]]
"""
try:
i,j = cell
except ValueError:
i,j = cell[0]
try:
return self[i][j]
except IndexError:
raise IndexError("The cell (%d,%d) is not contained in %s"%(i,j,repr(self)))
def level(self):
"""
Returns the level of ``self``, which is always 1.
This function exists mainly for compatibility with :class:`TableauTuple`.
EXAMPLE::
sage: Tableau([[1,2,3],[4,5]]).level()
1
"""
return 1
def components(self):
"""
This function returns a list containing itself. It exists mainly for
compatibility with :class:`TableauTuple` as it allows constructions like the
example below.
EXAMPLES::
sage: t = Tableau([[1,2,3],[4,5]]);
sage: for s in t.components(): print s.to_list()
[[1, 2, 3], [4, 5]]
"""
return [self]
@combinatorial_map(name='shape')
def shape(self):
r"""
Return the shape of a tableau ``self``.
EXAMPLES::
sage: Tableau([[1,2,3],[4,5],[6]]).shape()
[3, 2, 1]
"""
from sage.combinat.partition import Partition
return Partition([len(row) for row in self])
def size(self):
"""
Return the size of the shape of the tableau ``self``.
EXAMPLES::
sage: Tableau([[1, 4, 6], [2, 5], [3]]).size()
6
sage: Tableau([[1, 3], [2, 4]]).size()
4
"""
return sum([len(row) for row in self])
def corners(self):
"""
Return the corners of the tableau ``self``.
EXAMPLES::
sage: Tableau([[1, 4, 6], [2, 5], [3]]).corners()
[(0, 2), (1, 1), (2, 0)]
sage: Tableau([[1, 3], [2, 4]]).corners()
[(1, 1)]
"""
return self.shape().corners()
@combinatorial_map(order=2,name='conjugate')
def conjugate(self):
"""
Return the conjugate of ``self``.
EXAMPLES::
sage: Tableau([[1,2],[3,4]]).conjugate()
[[1, 3], [2, 4]]
sage: c = StandardTableau([[1,2],[3,4]]).conjugate()
sage: c.parent()
Standard tableaux
"""
conj_shape = self.shape().conjugate()
conj = [[None]*row_length for row_length in conj_shape]
for i in range(len(conj)):
for j in range(len(conj[i])):
conj[i][j] = self[j][i]
if isinstance(self, StandardTableau):
return StandardTableau(conj)
return Tableau(conj)
def pp(self):
"""
Returns a pretty print string of the tableau.
EXAMPLES::
sage: T = Tableau([[1,2,3],[3,4],[5]])
sage: T.pp()
1 2 3
3 4
5
sage: Tableaux.global_options(convention="french")
sage: T.pp()
5
3 4
1 2 3
sage: Tableaux.global_options.reset()
"""
print self._repr_diagram()
def to_word_by_row(self):
"""
Return the word obtained from a row reading of the tableau ``self``
(starting with the lowermost row, reading every row from left
to right).
EXAMPLES::
sage: Tableau([[1,2],[3,4]]).to_word_by_row()
word: 3412
sage: Tableau([[1, 4, 6], [2, 5], [3]]).to_word_by_row()
word: 325146
"""
from sage.combinat.words.word import Word
w = []
for row in reversed(self):
w += row
return Word(w)
def to_word_by_column(self):
"""
Return the word obtained from a column reading of the tableau ``self``
(starting with the leftmost column, reading every column from bottom
to top).
EXAMPLES::
sage: Tableau([[1,2],[3,4]]).to_word_by_column()