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
/
posets.py
8070 lines (6378 loc) · 282 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"""
Finite 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` | Return ``True`` if a directed graph is acyclic and transitively reduced.
List of Poset methods
---------------------
**Comparing, intervals and relations**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.is_less_than` | Return ``True`` if `x` is strictly less than `y` in the poset.
:meth:`~FinitePoset.is_greater_than` | Return ``True`` if `x` is strictly greater than `y` in the poset.
:meth:`~FinitePoset.is_lequal` | Return ``True`` if `x` is less than or equal to `y` in the poset.
:meth:`~FinitePoset.is_gequal` | Return ``True`` if `x` is greater than or equal to `y` in the poset.
:meth:`~FinitePoset.compare_elements` | Compare two element of the poset.
:meth:`~FinitePoset.closed_interval` | Return the list of elements in a closed interval of the poset.
:meth:`~FinitePoset.open_interval` | Return the list of elements in an open interval of the poset.
:meth:`~FinitePoset.relations` | Return the list of relations in the poset.
:meth:`~FinitePoset.relations_iterator` | Return an iterator over relations in the poset.
:meth:`~FinitePoset.order_filter` | Return the upper set generated by elements.
:meth:`~FinitePoset.order_ideal` | Return the lower set generated by elements.
**Covering**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.covers` | Return ``True`` if ``y`` covers ``x``.
:meth:`~FinitePoset.lower_covers` | Return elements covered by given element.
:meth:`~FinitePoset.upper_covers` | Return elements covering given element.
:meth:`~FinitePoset.cover_relations` | Return the list of cover relations.
:meth:`~FinitePoset.lower_covers_iterator` | Return an iterator over elements covered by given element.
:meth:`~FinitePoset.upper_covers_iterator` | Return an iterator over elements covering given element.
:meth:`~FinitePoset.cover_relations_iterator` | Return an iterator over cover relations of the poset.
**Properties of the poset**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.cardinality` | Return the number of elements in the poset.
:meth:`~FinitePoset.height` | Return the number of elements in a longest chain of the poset.
:meth:`~FinitePoset.width` | Return the number of elements in a longest antichain of the poset.
:meth:`~FinitePoset.relations_number` | Return the number of relations in the poset.
:meth:`~FinitePoset.dimension` | Return the dimension of the poset.
:meth:`~FinitePoset.jump_number` | Return the jump number of the poset.
:meth:`~FinitePoset.has_bottom` | Return ``True`` if the poset has a unique minimal element.
:meth:`~FinitePoset.has_top` | Return ``True`` if the poset has a unique maximal element.
:meth:`~FinitePoset.is_bounded` | Return ``True`` if the poset has both unique minimal and unique maximal element.
:meth:`~FinitePoset.is_chain` | Return ``True`` if the poset is totally ordered.
:meth:`~FinitePoset.is_connected` | Return ``True`` if the poset is connected.
:meth:`~FinitePoset.is_graded` | Return ``True`` if all maximal chains of the poset has same length.
:meth:`~FinitePoset.is_ranked` | Return ``True`` if the poset has a rank function.
:meth:`~FinitePoset.is_rank_symmetric` | Return ``True`` if the poset is rank symmetric.
:meth:`~FinitePoset.is_series_parallel` | Return ``True`` if the poset can be built by ordinal sums and disjoint unions.
:meth:`~FinitePoset.is_greedy` | Return ``True`` if all greedy linear extensions have equal number of jumps.
:meth:`~FinitePoset.is_jump_critical` | Return ``True`` if removal of any element reduces the jump number.
:meth:`~FinitePoset.is_eulerian` | Return ``True`` if the poset is Eulerian.
:meth:`~FinitePoset.is_incomparable_chain_free` | Return ``True`` if the poset is (m+n)-free.
:meth:`~FinitePoset.is_slender` | Return ``True`` if the poset is slender.
:meth:`~FinitePoset.is_join_semilattice` | Return ``True`` is the poset has a join operation.
:meth:`~FinitePoset.is_meet_semilattice` | Return ``True`` if the poset has a meet operation.
**Minimal and maximal elements**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.bottom` | Return the bottom element of the poset, if it exists.
:meth:`~FinitePoset.top` | Return the top element of the poset, if it exists.
:meth:`~FinitePoset.maximal_elements` | Return the list of the maximal elements of the poset.
:meth:`~FinitePoset.minimal_elements` | Return the list of the minimal elements of the poset.
**New posets from old ones**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.disjoint_union` | Return the disjoint union of the poset with other poset.
:meth:`~FinitePoset.ordinal_sum` | Return the ordinal sum of the poset with other poset.
:meth:`~FinitePoset.product` | Return the Cartesian product of the poset with other poset.
:meth:`~FinitePoset.ordinal_product` | Return the ordinal product of the poset with other poset.
:meth:`~FinitePoset.lexicographic_sum` | Return the lexicographic sum of posets.
:meth:`~FinitePoset.star_product` | Return the star product of the poset with other poset.
:meth:`~FinitePoset.with_bounds` | Return the poset with bottom and top element adjoined.
:meth:`~FinitePoset.without_bounds` | Return the poset with bottom and top element removed.
:meth:`~FinitePoset.dual` | Return the dual of the poset.
:meth:`~FinitePoset.completion_by_cuts` | Return the Dedekind-MacNeille completion of the poset.
:meth:`~FinitePoset.intervals_poset` | Return the poset of intervals of the poset.
:meth:`~FinitePoset.connected_components` | Return the connected components of the poset as subposets.
:meth:`~FinitePoset.factor` | Return the decomposition of the poset as a Cartesian product.
:meth:`~FinitePoset.ordinal_summands` | Return the ordinal summands of the poset.
:meth:`~FinitePoset.subposet` | Return the subposet containing elements with partial order induced by this poset.
:meth:`~FinitePoset.random_subposet` | Return a random subposet that contains each element with given probability.
:meth:`~FinitePoset.relabel` | Return a copy of this poset with its elements relabelled.
:meth:`~FinitePoset.canonical_label` | Return copy of the poset canonically (re)labelled to integers.
**Chains & antichains**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.is_chain_of_poset` | Return ``True`` if elements in the given list are comparable.
:meth:`~FinitePoset.is_antichain_of_poset` | Return ``True`` if elements in the given list are incomparable.
:meth:`~FinitePoset.chains` | Return the chains of the poset.
:meth:`~FinitePoset.antichains` | Return the antichains of the poset.
:meth:`~FinitePoset.maximal_chains` | Return the maximal chains of the poset.
:meth:`~FinitePoset.maximal_antichains` | Return the maximal antichains of the poset.
:meth:`~FinitePoset.antichains_iterator` | Return an iterator over the antichains of the poset.
**Drawing**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.show` | Display the Hasse diagram of the poset.
:meth:`~FinitePoset.plot` | Return a Graphic object corresponding the Hasse diagram of the poset.
:meth:`~FinitePoset.graphviz_string` | Return a representation in the DOT language, ready to render in graphviz.
**Comparing posets**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.is_isomorphic` | Return ``True`` if both posets are isomorphic.
:meth:`~FinitePoset.is_induced_subposet` | Return ``True`` if given poset is an induced subposet of this poset.
**Polynomials**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.chain_polynomial` | Return the chain polynomial of the poset.
:meth:`~FinitePoset.characteristic_polynomial` | Return the characteristic polynomial of the poset.
:meth:`~FinitePoset.f_polynomial` | Return the f-polynomial of the poset.
:meth:`~FinitePoset.flag_f_polynomial` | Return the flag f-polynomial of the poset.
:meth:`~FinitePoset.h_polynomial` | Return the h-polynomial of the poset.
:meth:`~FinitePoset.flag_h_polynomial` | Return the flag h-polynomial of the poset.
:meth:`~FinitePoset.order_polynomial` | Return the order polynomial of the poset.
:meth:`~FinitePoset.zeta_polynomial` | Return the zeta polynomial of the poset.
:meth:`~FinitePoset.kazhdan_lusztig_polynomial` | Return the Kazhdan-Lusztig polynomial of the poset.
:meth:`~FinitePoset.coxeter_polynomial` | Return the characteristic polynomial of the Coxeter transformation.
:meth:`~FinitePoset.degree_polynomial` | Return the generating polynomial of degrees of vertices in the Hasse diagram.
:meth:`~FinitePoset.p_partition_enumerator` | Return a `P`-partition enumerator of the poset.
**Polytopes**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.chain_polytope` | Return the chain polytope of the poset.
:meth:`~FinitePoset.order_polytope` | Return the order polytope of the poset.
**Graphs**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.hasse_diagram` | Return the Hasse diagram of the poset as a directed graph.
:meth:`~FinitePoset.cover_relations_graph` | Return the (undirected) graph of cover relations.
:meth:`~FinitePoset.comparability_graph` | Return the comparability graph of the poset.
:meth:`~FinitePoset.incomparability_graph` | Return the incomparability graph of the poset.
:meth:`~FinitePoset.frank_network` | Return Frank's network of the poset.
:meth:`~FinitePoset.linear_extensions_graph` | Return the linear extensions graph of the poset.
**Linear extensions**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.is_linear_extension` | Return ``True`` if the given list is a linear extension of the poset.
:meth:`~FinitePoset.linear_extension` | Return a linear extension of the poset.
:meth:`~FinitePoset.linear_extensions` | Return the enumerated set of all the linear extensions of the poset.
:meth:`~FinitePoset.promotion` | Return the (extended) promotion on the linear extension of the poset.
:meth:`~FinitePoset.evacuation` | Return evacuation on the linear extension associated to the poset.
:meth:`~FinitePoset.with_linear_extension` | Return a copy of ``self`` with a different default linear extension.
**Matrices**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
: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.moebius_function` | Return the value of Möbius function of given elements in the poset.
:meth:`~FinitePoset.moebius_function_matrix` | Return a matrix whose ``(i,j)`` entry is the value of the Möbius function evaluated at ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.
:meth:`~FinitePoset.coxeter_transformation` | Return the matrix of the Auslander-Reiten translation acting on the Grothendieck group of the derived category of modules.
:meth:`~FinitePoset.coxeter_smith_form` | Return the Smith form of the Coxeter transformation.
**Miscellanous**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~FinitePoset.sorted` | Return given list sorted by the poset.
:meth:`~FinitePoset.isomorphic_subposets` | Return all subposets isomorphic to another poset.
:meth:`~FinitePoset.isomorphic_subposets_iterator` | Return an iterator over the subposets isomorphic to another poset.
:meth:`~FinitePoset.has_isomorphic_subposet` | Return ``True`` if the poset contains a subposet isomorphic to another poset.
:meth:`~FinitePoset.list` | List the elements of the poset.
:meth:`~FinitePoset.cuts` | Return the cuts of the given poset.
:meth:`~FinitePoset.dilworth_decomposition` | Return a partition of the points into the minimal number of chains.
:meth:`~FinitePoset.greene_shape` | Computes the Greene-Kleitman partition aka Greene shape of the poset ``self``.
:meth:`~FinitePoset.incidence_algebra` | Return the incidence algebra of ``self``.
:meth:`~FinitePoset.is_EL_labelling` | Return whether ``f`` is an EL labelling of the poset.
: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.level_sets` | Return elements grouped by maximal number of cover relations from a minimal element.
:meth:`~FinitePoset.order_complex` | Return the order complex associated to this poset.
:meth:`~FinitePoset.random_order_ideal` | Return a random order ideal of ``self`` with uniform probability.
:meth:`~FinitePoset.rank` | Return the rank of an element, or the rank of the poset.
:meth:`~FinitePoset.rank_function` | Return a rank function of the poset, if it exists.
:meth:`~FinitePoset.unwrap` | Unwraps an element of this poset.
Classes and functions
---------------------
"""
#*****************************************************************************
# Copyright (C) 2008 Peter Jipsen <jipsen@chapman.edu>
# Copyright (C) 2008 Franco Saliola <saliola@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
# python3
from __future__ import division, print_function, absolute_import
from six.moves import range
from six import iteritems
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.functions.other import floor
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.rings.polynomial.polynomial_ring_constructor import PolynomialRing
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
from sage.misc.superseded import deprecated_function_alias
from sage.combinat.subset import Subsets
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
list/tuple/iterable 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 instead return whether ``x`` is covered by
``y``.
3. A dictionary of upper covers: ``data[x]`` is
a list of the elements that cover the element `x` in the poset.
4. A list or tuple of upper covers: ``data[x]`` is
a list of the elements that cover the element `x` in the poset.
If the set of elements is not a set of consecutive integers
starting from zero, then:
- every element must appear in the data, for example in its own entry.
- ``data`` must be ordered in the same way as sorted elements.
.. WARNING::
If data is a list or tuple of length `2`, then it is
handled by the case 2 above.
5. 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.
6. 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. If the data
is given as the pair ``(E, f)``, then ``E`` is taken to be the linear
extension.
- ``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
4. A list of upper covers, with range(5) as set of vertices::
sage: Poset([[1,2],[4],[3],[4],[]])
Finite poset containing 5 elements
A list of upper covers, with letters as vertices::
sage: Poset([["a","b"],["b","c"],["c"]])
Finite poset containing 3 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 case 2. So you cannot use this
method to input a 2-element poset.
5. 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 annoying when one wants to manipulate the elements of
the poset::
sage: a + b
Traceback (most recent call last):
...
TypeError: unsupported operand parent(s) for +: 'Finite poset containing 4 elements' and 'Finite poset containing 4 elements'
sage: a.element + b.element
'ab'
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)
<... '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', 'c', 'b', 'a']
sage: P.principal_order_ideal('a')
['d', 'c', 'b', '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])
<... '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)
<... 'sage.rings.integer.Integer'>
sage: P = Poset((divisors(15), attrcall("divides")), facade=True)
sage: type(P.an_element())
<... '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))
<... 'int'>
Bad input::
sage: Poset([1,2,3], lambda x,y : x<y)
Traceback (most recent call last):
...
TypeError: element_labels should be a dict or a list if different
from None. (Did you intend data to be equal to a pair ?)
Another kind of bad input, digraphs with oriented cycles::
sage: Poset(DiGraph([[1,2],[2,3],[3,4],[4,1]]))
Traceback (most recent call last):
...
ValueError: The graph is not directed acyclic
"""
# 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 TypeError("element_labels 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 and linear_extension == data._with_linear_extension:
return data
if not linear_extension:
P = FinitePoset(data, elements=None, category=category, facade=facade)
if element_labels is not None:
P = P.relabel(element_labels)
return P
else:
if element_labels is None:
return FinitePoset(data, elements=data._elements, category=category, facade=facade)
else:
return FinitePoset(data, elements=element_labels, 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, format="dict_of_lists")
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, loops=False)
elif len(data) > 2:
# type 3, list/tuple of upper covers
vertices = sorted(set(x for item in data for x in item))
if len(vertices) != len(data):
# by default, assuming vertices are the range 0..n
vertices = list(range(len(data)))
D = DiGraph({v: [u for u in cov if u != v]
for v, cov in zip(vertices, data)},
format="dict_of_lists")
else:
raise ValueError("not valid poset data")
# DEBUG: At this point D should be a DiGraph.
assert isinstance(D, DiGraph), "BUG: D should be a digraph."
# Determine cover relations, if necessary.
if cover_relations is False:
from sage.graphs.generic_graph_pyx import transitive_reduction_acyclic
D = transitive_reduction_acyclic(D)
# 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 element_labels is not None:
D = D.relabel(element_labels, inplace=False)
if linear_extension:
if element_labels is not None:
elements = element_labels
elif elements is None:
# Compute a linear extension of the poset (a topological sort).
try:
elements = D.topological_sort()
except Exception:
raise ValueError("Hasse diagram contains cycles")
else:
elements = None
return FinitePoset(D, elements=elements, category=category, facade=facade, key=key)
class FinitePoset(UniqueRepresentation, Parent):
r"""
A (finite) `n`-element poset constructed from a directed acyclic graph.
INPUT:
- ``hasse_diagram`` -- an instance of
:class:`~sage.combinat.posets.posets.FinitePoset`, or a
:class:`DiGraph` that is transitively-reduced, acyclic,
loop-free, and multiedge-free.
- ``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. Note that if this option is set,
then ``elements`` is considered as a specified linear extension of the poset
and the `linear_extension` attribute is set.
- ``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()
[[5, 4], [5, 3], [4, 1], [0, 2], [0, 3], [2, 1], [3, 1]]
sage: TestSuite(P).run()
sage: P.category()
Category of finite enumerated posets
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 with distinguished linear extension
sage: Q.cover_relations()
[[1, 2], [1, 5], [2, 6], [3, 4], [3, 5], [4, 6], [5, 6]]
We test the facade argument::
sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade=False)
sage: P.category()
Category of finite enumerated posets
sage: parent(P[0]) is P
True
sage: Q = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade=True)
sage: Q.category()
Category of facade finite enumerated posets
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()
Category of facade finite enumerated posets
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()
Category of finite enumerated posets
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]]
sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)
sage: Q = Poset(P)
sage: Q == P
False
sage: Q = Poset(P, linear_extension=True)
sage: Q == P
True
"""
# The parsing of the construction data (like a list of cover relations)
# into a :class:`DiGraph` is done in :func:`Poset`.
@staticmethod
def __classcall__(cls, hasse_diagram, elements=None, category=None, facade=None, key=None):
"""
Normalizes the arguments passed to the constructor.
INPUT:
- ``hasse_diagram`` -- a :class:`DiGraph` or a :class:`FinitePoset`
that is labeled by the elements of the poset
- ``elements`` -- (default: ``None``) the default linear extension
or ``None`` if no such default linear extension is wanted
- ``category`` -- (optional) a subcategory of :class:`FinitePosets`
- ``facade`` -- (optional) boolean if this is a facade parent or not
- ``key`` -- (optional) a key value
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 category is None:
category = hasse_diagram.category()
if facade is None:
facade = hasse_diagram in Sets().Facade()
if elements is None:
relabel = {i:x for i,x in enumerate(hasse_diagram._elements)}
else:
elements = tuple(elements)
relabel = {i:x for i,x in enumerate(elements)}
hasse_diagram = hasse_diagram._hasse_diagram.relabel(relabel, inplace=False)
hasse_diagram = hasse_diagram.copy(immutable=True)
else:
hasse_diagram = HasseDiagram(hasse_diagram, data_structure="static_sparse")
if facade is None:
facade = True
if elements is not None:
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):
r"""
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::