/
posets.py
4755 lines (3810 loc) · 169 KB
/
posets.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
# -*- coding: utf-8 -*-
r"""
Posets
This module implements finite partially ordered sets. It defines:
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:class:`FinitePoset` | A class for finite posets
:class:`FinitePosets_n` | A class for finite posets up to isomorphism (i.e. unlabeled posets)
:meth:`Poset` | Construct a finite poset from various forms of input data.
:meth:`is_poset` | Tests whether a directed graph is acyclic and transitively reduced.
**List of Poset methods**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.antichains_iterator` | Returns an iterator over the antichains of the poset.
:meth:`~FinitePoset.antichains` | Returns the antichains of the poset.
:meth:`~FinitePoset.bottom` | Returns the bottom element of the poset, if it exists.
:meth:`~FinitePoset.cardinality` | Returns the number of elements in the poset.
:meth:`~FinitePoset.chains` | Returns all the chains of ``self``
:meth:`~FinitePoset.chain_polytope` | Returns the chain polytope of the poset.
:meth:`~FinitePoset.chain_polynomial` | Returns the chain polynomial of the poset.
:meth:`~FinitePoset.closed_interval` | Returns a list of the elements `z` such that `x \le z \le y`.
:meth:`~FinitePoset.compare_elements` | Compare `x` and `y` in the poset.
:meth:`~FinitePoset.comparability_graph` | Returns the comparability graph of the poset.
:meth:`~FinitePoset.cover_relations_iterator` | Returns an iterator for the cover relations of the poset.
:meth:`~FinitePoset.cover_relations` | Returns the list of pairs [u,v] which are cover relations
:meth:`~FinitePoset.covers` | Returns True if y covers x and False otherwise.
:meth:`~FinitePoset.coxeter_transformation` | Returns the matrix of the Auslander-Reiten translation acting on the Grothendieck group of the derived category of modules
:meth:`~FinitePoset.dual` | Returns the dual poset of the given poset.
:meth:`~FinitePoset.evacuation` | Computes evacuation on the linear extension associated to the poset ``self``.
:meth:`~FinitePoset.f_polynomial` | Returns the f-polynomial of a bounded poset.
:meth:`~FinitePoset.flag_f_polynomial` | Returns the flag f-polynomial of a bounded and ranked poset.
:meth:`~FinitePoset.flag_h_polynomial` | Returns the flag h-polynomial of a bounded and ranked poset.
:meth:`~FinitePoset.frank_network` | Returns Frank's network (a DiGraph along with a cost function on its edges) associated to ``self``.
:meth:`~FinitePoset.graphviz_string` | Returns a representation in the DOT language, ready to render in graphviz.
:meth:`~FinitePoset.greene_shape` | Computes the Greene-Kleitman partition aka Greene shape of the poset ``self``.
:meth:`~FinitePoset.h_polynomial` | Returns the h-polynomial of a bounded poset.
:meth:`~FinitePoset.has_bottom` | Returns True if the poset has a unique minimal element.
:meth:`~FinitePoset.hasse_diagram` | Returns the Hasse diagram of ``self`` as a Sage :class:`DiGraph`.
:meth:`~FinitePoset.has_isomorphic_subposet` | Return ``True`` if the poset contains a subposet isomorphic to another poset, and ``False`` otherwise.
:meth:`~FinitePoset.has_top` | Returns True if the poset contains a unique maximal element, and False otherwise.
:meth:`~FinitePoset.height` | Return the height (number of elements in the longest chain) of the poset.
:meth:`~FinitePoset.incomparability_graph` | Returns the incomparability graph of the poset.
:meth:`~FinitePoset.interval` | Returns a list of the elements `z` such that `x \le z \le y`.
:meth:`~FinitePoset.is_bounded` | Returns True if the poset contains a unique maximal element and a unique minimal element, and False otherwise.
:meth:`~FinitePoset.is_chain` | Returns True if the poset is totally ordered, and False otherwise.
:meth:`~FinitePoset.is_connected` | Return ``True`` if the poset is connected, and ``False`` otherwise.
:meth:`~FinitePoset.is_EL_labelling` | Returns whether ``f`` is an EL labelling of ``self``
:meth:`~FinitePoset.is_gequal` | Returns ``True`` if `x` is greater than or equal to `y` in the poset, and ``False`` otherwise.
:meth:`~FinitePoset.is_graded` | Returns whether this poset is graded.
:meth:`~FinitePoset.is_greater_than` | Returns ``True`` if `x` is greater than but not equal to `y` in the poset, and ``False`` otherwise.
:meth:`~FinitePoset.is_isomorphic` | Returns True if both posets are isomorphic.
:meth:`~FinitePoset.is_join_semilattice` | Returns True is the poset has a join operation, and False otherwise.
:meth:`~FinitePoset.is_lequal` | Returns ``True`` if `x` is less than or equal to `y` in the poset, and ``False`` otherwise.
:meth:`~FinitePoset.is_less_than` | Returns ``True`` if `x` is less than but not equal to `y` in the poset, and ``False`` otherwise.
:meth:`~FinitePoset.is_linear_extension` | Returns whether ``l`` is a linear extension of ``self``
:meth:`~FinitePoset.is_meet_semilattice` | Returns True if self has a meet operation, and False otherwise.
:meth:`~FinitePoset.isomorphic_subposets_iterator` | Return an iterator over the subposets isomorphic to another poset.
:meth:`~FinitePoset.isomorphic_subposets` | Return all subposets isomorphic to another poset.
:meth:`~FinitePoset.join_matrix` | Returns a matrix whose ``(i,j)`` entry is ``k``, where ``self.linear_extension()[k]`` is the join (least upper bound) of ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.
:meth:`~FinitePoset.is_incomparable_chain_free` | Returns whether the poset is `(m+n)`-free.
:meth:`~FinitePoset.is_ranked` | Returns whether this poset is ranked.
:meth:`~FinitePoset.is_slender` | Returns whether the poset ``self`` is slender or not.
:meth:`~FinitePoset.lequal_matrix` | Computes the matrix whose ``(i,j)`` entry is 1 if ``self.linear_extension()[i] < self.linear_extension()[j]`` and 0 otherwise
:meth:`~FinitePoset.level_sets` | Returns a list l such that l[i+1] is the set of minimal elements of the poset obtained by removing the elements in l[0], l[1], ..., l[i].
:meth:`~FinitePoset.linear_extension` | Returns a linear extension of this poset.
:meth:`~FinitePoset.linear_extensions` | Returns the enumerated set of all the linear extensions of this poset
:meth:`~FinitePoset.list` | List the elements of the poset. This just returns the result of :meth:`linear_extension`.
:meth:`~FinitePoset.lower_covers_iterator` | Returns an iterator for the lower covers of the element y. An lower cover of y is an element x such that y x is a cover relation.
:meth:`~FinitePoset.lower_covers` | Returns a list of lower covers of the element y. An lower cover of y is an element x such that y x is a cover relation.
:meth:`~FinitePoset.maximal_antichains` | Return all maximal antichains of the poset.
:meth:`~FinitePoset.maximal_chains` | Returns all maximal chains of this poset. Each chain is listed in increasing order.
:meth:`~FinitePoset.maximal_elements` | Returns a list of the maximal elements of the poset.
:meth:`~FinitePoset.meet_matrix` | Returns a matrix whose ``(i,j)`` entry is ``k``, where ``self.linear_extension()[k]`` is the meet (greatest lower bound) of ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.
:meth:`~FinitePoset.minimal_elements` | Returns a list of the minimal elements of the poset.
:meth:`~FinitePoset.mobius_function_matrix` | Returns a matrix whose ``(i,j)`` entry is the value of the Mobius function evaluated at ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.
:meth:`~FinitePoset.mobius_function` | Returns the value of the Mobius function of the poset on the elements x and y.
:meth:`~FinitePoset.open_interval` | Returns a list of the elements `z` such that `x < z < y`. The order is that induced by the ordering in
:meth:`~FinitePoset.order_complex` | Returns the order complex associated to this poset.
:meth:`~FinitePoset.order_filter` | Returns the order filter generated by a list of elements.
:meth:`~FinitePoset.order_ideal` | Returns the order ideal generated by a list of elements.
:meth:`~FinitePoset.order_polynomial` | Returns the order polynomial of the poset.
:meth:`~FinitePoset.order_polytope` | Returns the order polytope of the poset.
:meth:`~FinitePoset.p_partition_enumerator` | Returns a `P`-partition enumerator of the poset.
:meth:`~FinitePoset.plot` | Returns a Graphic object corresponding the Hasse diagram of the poset.
:meth:`~FinitePoset.product` | Returns the cartesian product of ``self`` and ``other``.
:meth:`~FinitePoset.promotion` | Computes the (extended) promotion on the linear extension of the poset ``self``
:meth:`~FinitePoset.random_subposet` | Return a random subposet that contains each element with probability ``p``.
:meth:`~FinitePoset.rank_function` | Returns a rank function of the poset, if it exists.
:meth:`~FinitePoset.rank` | Returns the rank of an element, or the rank of the poset if element is None.
:meth:`~FinitePoset.relabel` | Returns a copy of this poset with its elements relabelled
:meth:`~FinitePoset.relations_iterator` | Returns an iterator for all the relations of the poset.
:meth:`~FinitePoset.relations` | Returns a list of all relations of the poset.
:meth:`~FinitePoset.show` | Shows the Graphics object corresponding the Hasse diagram of the poset.
:meth:`~FinitePoset.subposet` | Returns the poset containing elements with partial order induced by that of self.
:meth:`~FinitePoset.top` | Returns the top element of the poset, if it exists.
:meth:`~FinitePoset.unwrap` | Unwraps an element of this poset
:meth:`~FinitePoset.upper_covers_iterator` | Returns an iterator for the upper covers of the element y. An upper cover of y is an element x such that y x is a cover relation.
:meth:`~FinitePoset.upper_covers` | Returns a list of upper covers of the element y. An upper cover of y is an element x such that y x is a cover relation.
:meth:`~FinitePoset.with_linear_extension` | Returns a copy of ``self`` with a different default linear extension
:meth:`~FinitePoset.zeta_polynomial` | Returns the zeta polynomial of the poset.
Classes and functions
---------------------
"""
#*****************************************************************************
# 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/
#*****************************************************************************
import copy
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.misc_c import prod
from sage.categories.category import Category
from sage.categories.sets_cat import Sets
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.categories.posets import Posets
from sage.categories.finite_posets import FinitePosets
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.parent import Parent
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring import polygen
from sage.graphs.digraph import DiGraph
from sage.graphs.digraph_generators import digraphs
from sage.combinat.posets.hasse_diagram import HasseDiagram
from sage.combinat.posets.elements import PosetElement
from sage.combinat.combinatorial_map import combinatorial_map
def Poset(data=None, element_labels=None, cover_relations=False, linear_extension=False, category = None, facade = None, key = None):
r"""
Construct a finite poset from various forms of input data.
INPUT:
- ``data`` -- different input are accepted by this constructor:
1. A two-element list or tuple `(E, R)`, where `E` is a
collection of elements of the poset and `R` is a collection
of relations `x<=y`, each represented as a two-element
lists/tuples/iterables such as [x,y]. The poset is then the
transitive closure of the provided relations. If
``cover_relations=True``, then `R` is assumed to contain
exactly the cover relations of the poset. If `E` is empty,
then `E` is taken to be the set of elements appearing in
the relations `R`.
2. A two-element list or tuple `(E, f)`, where `E` is the set
of elements of the poset and `f` is a function such that,
for any pair `x,y` of elements of `E`, `f(x,y)` returns
whether `x <= y`. If ``cover_relations=True``, then
`f(x,y)` should return whether `x` is covered by `y`.
3. A dictionary, list or tuple of upper covers: ``data[x]`` is
a list of the elements that cover the element `x` in the
poset.
.. WARNING::
If data is a list or tuple of length `2`, then it is
handled by the above case..
4. An acyclic, loop-free and multi-edge free ``DiGraph``. If
``cover_relations`` is ``True``, then the edges of the
digraph are assumed to correspond to the cover relations of
the poset. Otherwise, the cover relations are computed.
5. A previously constructed poset (the poset itself is returned).
- ``element_labels`` -- (default: None); an optional list or
dictionary of objects that label the poset elements.
- ``cover_relations`` -- a boolean (default: False); whether the
data can be assumed to describe a directed acyclic graph whose
arrows are cover relations; otherwise, the cover relations are
first computed.
- ``linear_extension`` -- a boolean (default: False); whether to
use the provided list of elements as default linear extension
for the poset; otherwise a linear extension is computed.
- ``facade`` -- a boolean or ``None`` (default); whether the
:meth:`Poset`'s elements should be wrapped to make them aware of the Poset
they belong to.
* If ``facade = True``, the :meth:`Poset`'s elements are exactly those
given as input.
* If ``facade = False``, the :meth:`Poset`'s elements will become
:class:`~sage.combinat.posets.posets.PosetElement` objects.
* If ``facade = None`` (default) the expected behaviour is the behaviour
of ``facade = True``, unless the opposite can be deduced from the
context (i.e. for instance if a :meth:`Poset` is built from another
:meth:`Poset`, itself built with ``facade = False``)
OUTPUT:
``FinitePoset`` -- an instance of the :class:`FinitePoset`` class.
If ``category`` is specified, then the poset is created in this
category instead of :class:`FinitePosets`.
.. seealso:: :class:`Posets`, :class:`~sage.categories.posets.Posets`, :class:`FinitePosets`
EXAMPLES:
1. Elements and cover relations::
sage: elms = [1,2,3,4,5,6,7]
sage: rels = [[1,2],[3,4],[4,5],[2,5]]
sage: Poset((elms, rels), cover_relations = True, facade = False)
Finite poset containing 7 elements
Elements and non-cover relations::
sage: elms = [1,2,3,4]
sage: rels = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
sage: P = Poset( [elms,rels] ,cover_relations=False); P
Finite poset containing 4 elements
sage: P.cover_relations()
[[1, 2], [2, 3], [3, 4]]
2. Elements and function: the standard permutations of [1, 2, 3, 4]
with the Bruhat order::
sage: elms = Permutations(4)
sage: fcn = lambda p,q : p.bruhat_lequal(q)
sage: Poset((elms, fcn))
Finite poset containing 24 elements
With a function that identifies the cover relations: the set
partitions of {1, 2, 3} ordered by refinement::
sage: elms = SetPartitions(3)
sage: def fcn(A, B):
... if len(A) != len(B)+1:
... return False
... for a in A:
... if not any(set(a).issubset(b) for b in B):
... return False
... return True
sage: Poset((elms, fcn), cover_relations=True)
Finite poset containing 5 elements
3. A dictionary of upper covers::
sage: Poset({'a':['b','c'], 'b':['d'], 'c':['d'], 'd':[]})
Finite poset containing 4 elements
A list of upper covers::
sage: Poset([[1,2],[4],[3],[4],[]])
Finite poset containing 5 elements
A list of upper covers and a dictionary of labels::
sage: elm_labs = {0:"a",1:"b",2:"c",3:"d",4:"e"}
sage: P = Poset([[1,2],[4],[3],[4],[]],elm_labs, facade = False)
sage: P.list()
[a, b, c, d, e]
.. warning::
The special case where the argument data is a list or tuple of
length 2 is handled by the above cases. So you cannot use this
method to input a 2-element poset.
4. An acyclic DiGraph.
::
sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})
sage: Poset(dag)
Finite poset containing 6 elements
Any directed acyclic graph without loops or multiple edges, as long
as ``cover_relations=False``::
sage: dig = DiGraph({0:[2,3], 1:[3,4,5], 2:[5], 3:[5], 4:[5]})
sage: dig.allows_multiple_edges()
False
sage: dig.allows_loops()
False
sage: dig.transitive_reduction() == dig
False
sage: Poset(dig, cover_relations=False)
Finite poset containing 6 elements
sage: Poset(dig, cover_relations=True)
Traceback (most recent call last):
...
ValueError: Hasse diagram is not transitively reduced.
.. rubric:: Default Linear extension
Every poset `P` obtained with ``Poset`` comes equipped with a
default linear extension, which is also used for enumerating
its elements. By default, this linear extension is computed,
and has no particular significance::
sage: P = Poset((divisors(12), attrcall("divides")))
sage: P.list()
[1, 2, 4, 3, 6, 12]
sage: P.linear_extension()
[1, 2, 4, 3, 6, 12]
You may enforce a specific linear extension using the
``linear_extension`` option::
sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)
sage: P.list()
[1, 2, 3, 4, 6, 12]
sage: P.linear_extension()
[1, 2, 3, 4, 6, 12]
Depending on popular request, ``Poset`` might eventually get
modified to always use the provided list of elements as
default linear extension, when it is one.
.. seealso:: :meth:`FinitePoset.linear_extensions`
.. rubric:: Facade posets
When ``facade = False``, the elements of a poset are wrapped so as to make
them aware that they belong to that poset::
sage: P = Poset(DiGraph({'d':['c','b'],'c':['a'],'b':['a']}), facade = False)
sage: d,c,b,a = list(P)
sage: a.parent() is P
True
This allows for comparing elements according to `P`::
sage: c < a
True
However, this may have surprising effects::
sage: my_elements = ['a','b','c','d']
sage: any(x in my_elements for x in P)
False
and can be anoying when one wants to manipulate the elements of
the poset::
sage: a + b
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'FinitePoset_with_category.element_class' and 'FinitePoset_with_category.element_class'
sage: a.element + b.element
'ac'
By default, facade posets are constructed instead::
sage: P = Poset(DiGraph({'d':['c','b'],'c':['a'],'b':['a']}))
In this example, the elements of the poset remain plain strings::
sage: d,c,b,a = list(P)
sage: type(a)
<type 'str'>
Of course, those strings are not aware of `P`. So to compare two
such strings, one needs to query `P`::
sage: a < b
True
sage: P.lt(a,b)
False
which models the usual mathematical notation `a <_P b`.
Most operations seem to still work, but at this point there is no
guarantee whatsoever::
sage: P.list()
['d', 'b', 'c', 'a']
sage: P.principal_order_ideal('a')
['d', 'b', 'c', 'a']
sage: P.principal_order_ideal('b')
['d', 'b']
sage: P.principal_order_ideal('d')
['d']
sage: TestSuite(P).run()
.. warning::
:class:`DiGraph` is used to construct the poset, and the
vertices of a :class:`DiGraph` are converted to plain Python
:class:`int`'s if they are :class:`Integer`'s::
sage: G = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})
sage: type(G.vertices()[0])
<type 'int'>
This is worked around by systematically converting back the
vertices of a poset to :class:`Integer`'s if they are
:class:`int`'s::
sage: P = Poset((divisors(15), attrcall("divides")), facade = False)
sage: type(P.an_element().element)
<type 'sage.rings.integer.Integer'>
sage: P = Poset((divisors(15), attrcall("divides")), facade=True)
sage: type(P.an_element())
<type 'sage.rings.integer.Integer'>
This may be abusive::
sage: P = Poset((range(5), operator.le), facade = True)
sage: P.an_element().parent()
Integer Ring
.. rubric:: Unique representation
As most parents, :class:`Poset` have unique representation (see
:class:`UniqueRepresentation`. Namely if two posets are created
from two equal data, then they are not only equal but actually
identical::
sage: data1 = [[1,2],[3],[3]]
sage: data2 = [[1,2],[3],[3]]
sage: P1 = Poset(data1)
sage: P2 = Poset(data2)
sage: P1 == P2
True
sage: P1 is P2
True
In situations where this behaviour is not desired, one can use the
``key`` option::
sage: P1 = Poset(data1, key = "foo")
sage: P2 = Poset(data2, key = "bar")
sage: P1 is P2
False
sage: P1 == P2
False
``key`` can be any hashable value and is passed down to
:class:`UniqueRepresentation`. It is otherwise ignored by the
poset constructor.
TESTS::
sage: P = Poset([[1,2],[3],[3]])
sage: type(hash(P))
<type 'int'>
Bad input::
sage: Poset([1,2,3], lambda x,y : x<y)
Traceback (most recent call last):
...
ValueError: elements_label should be a dict or a list if different from None. (Did you intend data to be equal to a pair ?)
"""
# Avoiding some errors from the user when data should be a pair
if (element_labels is not None and
not isinstance(element_labels, dict) and
not isinstance(element_labels, list)):
raise ValueError("elements_label should be a dict or a list if "+
"different from None. (Did you intend data to be "+
"equal to a pair ?)")
#Convert data to a DiGraph
elements = None
D = {}
if isinstance(data, FinitePoset):
if element_labels is None and category is None and facade is None:
return data
else:
return FinitePoset(data, data._elements, category = category, facade = facade)
elif data is None: # type 0
D = DiGraph()
elif isinstance(data, DiGraph): # type 4
D = copy.deepcopy(data)
elif isinstance(data, dict): # type 3: dictionary of upper covers
D = DiGraph(data)
elif isinstance(data,(list,tuple)): # types 1, 2, 3 (list/tuple)
if len(data) == 2: # types 1 or 2
if callable(data[1]): # type 2
elements, function = data
relations = []
for x in elements:
for y in elements:
if function(x,y) is True:
relations.append([x,y])
else: # type 1
elements, relations = data
# check that relations are relations
for r in relations:
try:
u, v = r
except ValueError:
raise TypeError("not a list of relations")
D = DiGraph()
D.add_vertices(elements)
D.add_edges(relations)
elif len(data) > 2:
# type 3, list/tuple of upper covers
D = DiGraph(dict([[Integer(i),data[i]] for i in range(len(data))]))
else:
raise ValueError("not valid poset data.")
# DEBUG: At this point D should be a DiGraph.
if not isinstance(D,DiGraph):
raise TypeError("BUG: D should be a digraph.")
# Determine cover relations, if necessary.
if cover_relations is False:
D = D.transitive_reduction()
# Check that the digraph does not contain loops, multiple edges
# and is transitively reduced.
if D.has_loops():
raise ValueError("Hasse diagram contains loops.")
elif D.has_multiple_edges():
raise ValueError("Hasse diagram contains multiple edges.")
elif cover_relations is True and not D.is_transitively_reduced():
raise ValueError("Hasse diagram is not transitively reduced.")
if linear_extension and elements is not None:
lin_ext = list(elements)
else:
# Compute a linear extension of the poset (a topological sort).
try:
lin_ext = D.topological_sort()
except Exception:
raise ValueError("Hasse diagram contains cycles.")
# Relabel using the linear_extension.
# So range(len(D)) becomes a linear extension of the poset.
rdict = dict([[lin_ext[i],i] for i in range(len(lin_ext))])
D.relabel(rdict)
# Set element labels.
if element_labels is None:
elements = lin_ext
# Work around the fact that, currently, when a DiGraph is
# created with Integer's as vertices, those vertices are
# converted to plain int's. This is a bit abusive.
elements = [ Integer(i) if isinstance(i,int) else i for i in elements ]
else:
elements = [element_labels[z] for z in lin_ext]
return FinitePoset(D,elements, category = category, facade = facade, key = key)
class FinitePoset(UniqueRepresentation, Parent):
r"""
Constructs a (finite) `n`-element poset from a set of elements and a
directed acyclic graph or poset.
INPUT:
- ``hasse_diagram`` -- an instance of this class (``FinitePoset``),
or a digraph that is transitively-reduced, acyclic, loop-free,
multiedge-free, and with vertices indexed by ``range(n)``. We also
assume that ``range(n)`` is a linear extension of the poset.
- ``elements`` - an optional list of elements, with ``element[i]``
corresponding to vertex ``i``. If ``elements`` is ``None``, then it is
set to be the vertex set of the digraph.
- ``category`` -- :class:`FinitePosets`, or a subcategory thereof.
- ``facade`` -- a boolean or ``None`` (default); whether the
:class:`~sage.combinat.posets.posets.FinitePoset`'s elements should be
wrapped to make them aware of the Poset they belong to.
* If ``facade = True``, the
:class:`~sage.combinat.posets.posets.FinitePoset`'s elements are exactly
those given as input.
* If ``facade = False``, the
:class:`~sage.combinat.posets.posets.FinitePoset`'s elements will become
:class:`~sage.combinat.posets.posets.PosetElement` objects.
* If ``facade = None`` (default) the expected behaviour is the behaviour
of ``facade = True``, unless the opposite can be deduced from the
context (i.e. for instance if a
:class:`~sage.combinat.posets.posets.FinitePoset` is built from another
:class:`~sage.combinat.posets.posets.FinitePoset`, itself built with
``facade = False``)
- ``key`` -- any hashable value (default: ``None``).
EXAMPLES::
sage: uc = [[2,3], [], [1], [1], [1], [3,4]]
sage: from sage.combinat.posets.posets import FinitePoset
sage: P = FinitePoset(DiGraph(dict([[i,uc[i]] for i in range(len(uc))])), facade = False); P
Finite poset containing 6 elements
sage: P.cover_relations()
[[0, 2], [0, 3], [2, 1], [3, 1], [4, 1], [5, 3], [5, 4]]
sage: TestSuite(P).run()
sage: P.category()
Join of Category of finite posets and Category of finite enumerated sets
sage: P.__class__
<class 'sage.combinat.posets.posets.FinitePoset_with_category'>
sage: Q = sage.combinat.posets.posets.FinitePoset(P, facade = False); Q
Finite poset containing 6 elements
sage: Q is P
True
We keep the same underlying hasse diagram, but change the elements::
sage: Q = sage.combinat.posets.posets.FinitePoset(P, elements=[1,2,3,4,5,6], facade = False); Q
Finite poset containing 6 elements
sage: Q.cover_relations()
[[1, 3], [1, 4], [3, 2], [4, 2], [5, 2], [6, 4], [6, 5]]
We test the facade argument::
sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = False)
sage: P.category()
Join of Category of finite posets and Category of finite enumerated sets
sage: parent(P[0]) is P
True
sage: Q = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = True)
sage: Q.category()
Join of Category of finite posets
and Category of finite enumerated sets
and Category of facade sets
sage: parent(Q[0]) is str
True
sage: TestSuite(Q).run(skip = ['_test_an_element']) # is_parent_of is not yet implemented
Changing a non facade poset to a facade poset::
sage: PQ = Poset(P, facade = True)
sage: PQ.category()
Join of Category of finite posets
and Category of finite enumerated sets
and Category of facade sets
sage: parent(PQ[0]) is str
True
sage: PQ is Q
True
Changing a facade poset to a non facade poset::
sage: QP = Poset(Q, facade = False)
sage: QP.category()
Join of Category of finite posets
and Category of finite enumerated sets
sage: parent(QP[0]) is QP
True
.. note::
A class that inherits from this class needs to define
``Element``. This is the class of the elements that the inheriting
class contains. For example, for this class, ``FinitePoset``,
``Element`` is ``PosetElement``. It can also define ``_dual_class`` which
is the class of dual posets of this
class. E.g. ``FiniteMeetSemilattice._dual_class`` is
``FiniteJoinSemilattice``.
TESTS:
Equality is derived from :class:`UniqueRepresentation`. We check that this
gives consistent results::
sage: P = Poset([[1,2],[3],[3]])
sage: P == P
True
sage: Q = Poset([[1,2],[],[1]])
sage: Q == P
False
sage: p1, p2 = Posets(2).list()
sage: p2 == p1, p1 != p2
(False, True)
sage: [[p1.__eq__(p2) for p1 in Posets(2)] for p2 in Posets(2)]
[[True, False], [False, True]]
sage: [[p2.__eq__(p1) for p1 in Posets(2)] for p2 in Posets(2)]
[[True, False], [False, True]]
sage: [[p2 == p1 for p1 in Posets(3)] for p2 in Posets(3)]
[[True, False, False, False, False], [False, True, False, False, False], [False, False, True, False, False], [False, False, False, True, False], [False, False, False, False, True]]
sage: [[p1.__ne__(p2) for p1 in Posets(2)] for p2 in Posets(2)]
[[False, True], [True, False]]
sage: P = Poset([[1,2,4],[3],[3]])
sage: Q = Poset([[1,2],[],[1],[4]])
sage: P != Q
True
sage: P != P
False
sage: Q != Q
False
sage: [[p1.__ne__(p2) for p1 in Posets(2)] for p2 in Posets(2)]
[[False, True], [True, False]]
"""
@staticmethod
def __classcall__(cls, hasse_diagram, elements = None, category = None, facade = None, key = None):
"""
Normalizes the arguments passed to the constructor
TESTS::
sage: P = sage.combinat.posets.posets.FinitePoset(DiGraph())
sage: type(P)
<class 'sage.combinat.posets.posets.FinitePoset_with_category'>
sage: TestSuite(P).run()
See also the extensive tests in the class documentation.
We check that :trac:`17059` is fixed::
sage: p = Poset()
sage: p is Poset(p, category=p.category())
True
"""
assert isinstance(hasse_diagram, (FinitePoset, DiGraph))
if isinstance(hasse_diagram, FinitePoset):
if elements is None:
elements = hasse_diagram._elements
if category is None:
category = hasse_diagram.category()
if facade is None:
facade = hasse_diagram in Sets().Facade()
hasse_diagram = hasse_diagram._hasse_diagram
else:
hasse_diagram = HasseDiagram(hasse_diagram, data_structure="static_sparse")
if elements is None:
elements = hasse_diagram.vertices()
if facade is None:
facade = True
elements = tuple(elements)
# Standardize the category by letting the Facade axiom be carried
# by the facade variable
if category is not None and category.is_subcategory(Sets().Facade()):
category = category._without_axiom("Facade")
category = Category.join([FinitePosets().or_subcategory(category), FiniteEnumeratedSets()])
return super(FinitePoset, cls).__classcall__(cls, hasse_diagram = hasse_diagram, elements = elements,
category = category, facade = facade, key = key)
def __init__(self, hasse_diagram, elements, category, facade, key):
"""
EXAMPLES::
sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = False)
sage: type(P)
<class 'sage.combinat.posets.posets.FinitePoset_with_category'>
The internal data structure currently consists of:
- the Hasse diagram of the poset, represented by a DiGraph
with vertices labelled 0,...,n-1 according to a linear
extension of the poset (that is if `i \mapsto j` is an edge
then `i<j`), together with some extra methods (see
:class:`sage.combinat.posets.hasse_diagram.HasseDiagram`)::
sage: P._hasse_diagram
Hasse diagram of a poset containing 4 elements
sage: P._hasse_diagram.cover_relations()
[(0, 1), (1, 2), (2, 3)]
- a tuple of the original elements, not wrapped as elements of
``self`` (but see also ``P._list``)::
sage: P._elements
('a', 'b', 'c', 'd')
``P._elements[i]`` gives the element of ``P`` corresponding
to the vertex ``i``
- a dictionary mapping back elements to vertices::
sage: P._element_to_vertex_dict
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
- and a boolean stating whether the poset is a facade poset::
sage: P._is_facade
False
This internal data structure is subject to change at any
point. Do not break encapsulation!
TESTS::
sage: TestSuite(P).run()
See also the extensive tests in the class documentation.
"""
Parent.__init__(self, category = category, facade = facade)
self._hasse_diagram = hasse_diagram
self._elements = elements
self._element_to_vertex_dict = dict( (elements[i], i) for i in range(len(elements)) )
self._is_facade = facade
@lazy_attribute
def _list(self):
"""
The list of the elements of ``self``, each wrapped to have
``self`` as parent
EXAMPLES::
sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = False)
sage: L = P._list; L
(a, b, c, d)
sage: type(L[0])
<class 'sage.combinat.posets.elements.FinitePoset_with_category.element_class'>
sage: L[0].parent() is P
True
Constructing them once for all makes future conversions
between the vertex id and the element faster. This also
ensures unique representation of the elements of this poset,
which could be used to later speed up certain operations
(equality test, ...)
"""
if self._is_facade:
return self._elements
else:
return tuple(self.element_class(self, self._elements[vertex], vertex)
for vertex in range(len(self._elements)))
# This defines the type (class) of elements of poset.
Element = PosetElement
def _element_to_vertex(self, element):
"""
Given an element of the poset (wrapped or not), returns the
corresponding vertex of the Hasse diagram.
EXAMPLES::
sage: P = Poset((divisors(15), attrcall("divides")))
sage: list(P)
[1, 3, 5, 15]
sage: x = P(5)
sage: P._element_to_vertex(x)
2
The same with a non-wrapped element of `P`::
sage: P._element_to_vertex(5)
2
TESTS::
sage: P = Poset((divisors(15), attrcall("divides")), facade = False)
Testing for wrapped elements::
sage: all(P._vertex_to_element(P._element_to_vertex(x)) is x for x in P)
True
Testing for non-wrapped elements::
sage: all(P._vertex_to_element(P._element_to_vertex(x)) is P(x) for x in divisors(15))
True
Testing for non-wrapped elements for a facade poset::
sage: P = Poset((divisors(15), attrcall("divides")), facade = True)
sage: all(P._vertex_to_element(P._element_to_vertex(x)) is x for x in P)
True
"""
if isinstance(element, self.element_class) and element.parent() is self:
return element.vertex
else:
try:
return self._element_to_vertex_dict[element]
except KeyError:
raise ValueError("element (=%s) not in poset"%element)
def _vertex_to_element(self, vertex):
"""
Return the element of ``self`` corresponding to the vertex
``vertex`` of the Hasse diagram.
It is wrapped if ``self`` is not a facade poset.
EXAMPLES::
sage: P = Poset((divisors(15), attrcall("divides")), facade = False)
sage: x = P._vertex_to_element(2)
sage: x
5
sage: x.parent() is P
True
sage: P = Poset((divisors(15), attrcall("divides")), facade = True)
sage: x = P._vertex_to_element(2)
sage: x
5
sage: x.parent() is ZZ
True
"""
return self._list[vertex]
def unwrap(self, element):
"""
Return the element ``element`` of the poset ``self`` in
unwrapped form.
INPUT:
- ``element`` -- an element of ``self``
EXAMPLES::
sage: P = Poset((divisors(15), attrcall("divides")), facade = False)
sage: x = P.an_element(); x
1
sage: x.parent()
Finite poset containing 4 elements
sage: P.unwrap(x)
1
sage: P.unwrap(x).parent()
Integer Ring
For a non facade poset, this is equivalent to using the
``.element`` attribute::
sage: P.unwrap(x) is x.element
True
For a facade poset, this does nothing::
sage: P = Poset((divisors(15), attrcall("divides")), facade=True)
sage: x = P.an_element()
sage: P.unwrap(x) is x
True
This method is useful in code where we don't know if ``P`` is
a facade poset or not.
"""
if self._is_facade:
return element
else:
return element.element
def __contains__(self, x):
r"""
Returns True if x is an element of the poset.
TESTS::
sage: from sage.combinat.posets.posets import FinitePoset
sage: P5 = FinitePoset(DiGraph({(5,):[(4,1),(3,2)], \
(4,1):[(3,1,1),(2,2,1)], \
(3,2):[(3,1,1),(2,2,1)], \
(3,1,1):[(2,1,1,1)], \
(2,2,1):[(2,1,1,1)], \
(2,1,1,1):[(1,1,1,1,1)], \
(1,1,1,1,1):[]}))
sage: x = P5.list()[3]
sage: x in P5
True
For the sake of speed, an element with the right class and
parent is assumed to be in this parent. This can possibly be
counterfeited by feeding garbage to the constructor::
sage: x = P5.element_class(P5, "a", 5)
sage: x in P5
True
"""
if isinstance(x, self.element_class):
return x.parent() is self
return x in self._element_to_vertex_dict
is_parent_of = __contains__
def _element_constructor_(self, element):
"""
Constructs an element of ``self``
EXAMPLES::