/
hasse_diagram.py
3666 lines (2982 loc) · 130 KB
/
hasse_diagram.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"""
Hasse diagrams of posets
{INDEX_OF_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.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import annotations
from collections import deque
from sage.arith.misc import binomial
from sage.combinat.posets.hasse_cython import IncreasingChains
from sage.graphs.digraph import DiGraph
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.misc.lazy_import import lazy_import
from sage.misc.rest_index_of_methods import gen_rest_table_index
from sage.rings.integer_ring import ZZ
lazy_import('sage.combinat.posets.hasse_cython_flint',
['moebius_matrix_fast', 'coxeter_matrix_fast'])
lazy_import('sage.matrix.constructor', 'matrix')
lazy_import('sage.rings.finite_rings.finite_field_constructor', 'GF')
class LatticeError(ValueError):
"""
Helper exception class to forward elements without meet or
join to upper level, so that the user will see "No meet for
a and b" instead of "No meet for 1 and 2".
"""
def __init__(self, fail, x, y) -> None:
"""
Initialize the exception.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import LatticeError
sage: error = LatticeError('join', 3, 8)
sage: error.x
3
"""
ValueError.__init__(self, None)
self.fail = fail
self.x = x
self.y = y
def __str__(self) -> str:
"""
Return string representation of the exception.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import LatticeError
sage: error = LatticeError('meet', 15, 18)
sage: error.__str__()
'no meet for 15 and 18'
"""
return f"no {self.fail} for {self.x} and {self.y}"
class HasseDiagram(DiGraph):
"""
The Hasse diagram of a poset. This is just a transitively-reduced,
directed, acyclic graph without loops or multiple edges.
.. note::
We assume that ``range(n)`` is a linear extension of the poset.
That is, ``range(n)`` is the vertex set and a topological sort of
the digraph.
This should not be called directly, use Poset instead; all type
checking happens there.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]}); H
Hasse diagram of a poset containing 4 elements
sage: TestSuite(H).run()
"""
def _repr_(self):
r"""
TESTS::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})
sage: H._repr_()
'Hasse diagram of a poset containing 4 elements'
"""
return "Hasse diagram of a poset containing %s elements" % self.order()
def linear_extension(self):
r"""
Return a linear extension
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})
sage: H.linear_extension()
[0, 1, 2, 3]
"""
# Recall: we assume range(n) is a linear extension.
return list(range(len(self)))
def linear_extensions(self):
r"""
Return an iterator over all linear extensions.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})
sage: list(H.linear_extensions()) # optional - sage.modules
[[0, 1, 2, 3], [0, 2, 1, 3]]
"""
from sage.combinat.posets.linear_extension_iterator import linear_extension_iterator
return linear_extension_iterator(self)
def greedy_linear_extensions_iterator(self):
r"""
Return an iterator over greedy linear extensions of the Hasse diagram.
A linear extension `[e_1, e_2, \ldots, e_n]` is *greedy* if for
every `i` either `e_{i+1}` covers `e_i` or all upper covers
of `e_i` have at least one lower cover that is not in
`[e_1, e_2, \ldots, e_i]`.
Informally said a linear extension is greedy if it "always
goes up when possible" and so has no unnecessary jumps.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: N5 = HasseDiagram({0: [1, 2], 2: [3], 1: [4], 3: [4]})
sage: for l in N5.greedy_linear_extensions_iterator():
....: print(l)
[0, 1, 2, 3, 4]
[0, 2, 3, 1, 4]
TESTS::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: list(HasseDiagram({}).greedy_linear_extensions_iterator())
[[]]
sage: H = HasseDiagram({0: []})
sage: list(H.greedy_linear_extensions_iterator())
[[0]]
"""
N = self.order()
def greedy_rec(H, linext):
if len(linext) == N:
yield linext
S = []
if linext:
S = [x for x in H.neighbor_out_iterator(linext[-1])
if all(low in linext for low in H.neighbor_in_iterator(x))]
if not S:
S_ = set(self).difference(set(linext))
S = [x for x in S_
if not any(low in S_
for low in self.neighbor_in_iterator(x))]
for e in S:
yield from greedy_rec(H, linext + [e])
return greedy_rec(self, [])
def supergreedy_linear_extensions_iterator(self):
r"""
Return an iterator over supergreedy linear extensions of the Hasse diagram.
A linear extension `[e_1, e_2, \ldots, e_n]` is *supergreedy* if,
for every `i` and `j` where `i > j`, `e_i` covers `e_j` if for
every `i > k > j` at least one lower cover of `e_k` is not in
`[e_1, e_2, \ldots, e_k]`.
Informally said a linear extension is supergreedy if it "always
goes as high possible, and withdraw so less as possible".
These are also called depth-first linear extensions.
EXAMPLES:
We show the difference between "only greedy" and supergreedy
extensions::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0: [1, 2], 2: [3, 4]})
sage: G_ext = list(H.greedy_linear_extensions_iterator())
sage: SG_ext = list(H.supergreedy_linear_extensions_iterator())
sage: [0, 2, 3, 1, 4] in G_ext
True
sage: [0, 2, 3, 1, 4] in SG_ext
False
sage: len(SG_ext)
4
TESTS::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: list(HasseDiagram({}).supergreedy_linear_extensions_iterator())
[[]]
sage: list(HasseDiagram({0: [], 1: []}).supergreedy_linear_extensions_iterator())
[[0, 1], [1, 0]]
"""
N = self.order()
def supergreedy_rec(H, linext):
k = len(linext)
if k == N:
yield linext
else:
S = []
while not S:
if not k: # Start from new minimal element
S = [x for x in self.sources() if x not in linext]
else:
S = [x for x in self.neighbor_out_iterator(linext[k - 1])
if x not in linext and
all(low in linext
for low in self.neighbor_in_iterator(x))]
k -= 1
for e in S:
yield from supergreedy_rec(H, linext + [e])
return supergreedy_rec(self, [])
def is_linear_extension(self, lin_ext=None) -> bool:
r"""
Test if an ordering is a linear extension.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})
sage: H.is_linear_extension(list(range(4)))
True
sage: H.is_linear_extension([3,2,1,0])
False
"""
if lin_ext is None or lin_ext == list(range(len(self))):
return all(x < y for x, y in self.cover_relations_iterator())
else:
return all(lin_ext.index(x) < lin_ext.index(y)
for x, y in self.cover_relations_iterator())
def cover_relations_iterator(self):
r"""
Iterate over cover relations.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})
sage: list(H.cover_relations_iterator())
[(0, 2), (0, 3), (1, 3), (1, 4), (2, 5), (3, 5), (4, 5)]
"""
yield from self.edge_iterator(labels=False)
def cover_relations(self):
r"""
Return the list of cover relations.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})
sage: H.cover_relations()
[(0, 2), (0, 3), (1, 3), (1, 4), (2, 5), (3, 5), (4, 5)]
"""
return list(self.cover_relations_iterator())
def is_lequal(self, i, j) -> bool:
"""
Return ``True`` if i is less than or equal to j in the poset, and
``False`` otherwise.
.. note::
If the :meth:`lequal_matrix` has been computed, then this method is
redefined to use the cached data (see :meth:`_alternate_is_lequal`).
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
sage: x,y,z = 0, 1, 4
sage: H.is_lequal(x,y)
False
sage: H.is_lequal(y,x)
False
sage: H.is_lequal(x,z)
True
sage: H.is_lequal(y,z)
True
sage: H.is_lequal(z,z)
True
"""
return i == j or (i < j and j in self.breadth_first_search(i))
def is_less_than(self, x, y) -> bool:
r"""
Return ``True`` if ``x`` is less than but not equal to ``y`` in the
poset, and ``False`` otherwise.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
sage: x,y,z = 0, 1, 4
sage: H.is_less_than(x,y)
False
sage: H.is_less_than(y,x)
False
sage: H.is_less_than(x,z)
True
sage: H.is_less_than(y,z)
True
sage: H.is_less_than(z,z)
False
"""
if x == y:
return False
return self.is_lequal(x, y)
def is_gequal(self, x, y) -> bool:
r"""
Return ``True`` if ``x`` is greater than or equal to ``y``, and
``False`` otherwise.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: Q = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
sage: x,y,z = 0,1,4
sage: Q.is_gequal(x,y)
False
sage: Q.is_gequal(y,x)
False
sage: Q.is_gequal(x,z)
False
sage: Q.is_gequal(z,x)
True
sage: Q.is_gequal(z,y)
True
sage: Q.is_gequal(z,z)
True
"""
return self.is_lequal(y, x)
def is_greater_than(self, x, y) -> bool:
"""
Return ``True`` if ``x`` is greater than but not equal to
``y``, and ``False`` otherwise.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: Q = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})
sage: x,y,z = 0,1,4
sage: Q.is_greater_than(x,y)
False
sage: Q.is_greater_than(y,x)
False
sage: Q.is_greater_than(x,z)
False
sage: Q.is_greater_than(z,x)
True
sage: Q.is_greater_than(z,y)
True
sage: Q.is_greater_than(z,z)
False
"""
return self.is_less_than(y, x)
def minimal_elements(self):
"""
Return a list of the minimal elements of the poset.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})
sage: P(0) in P.minimal_elements()
True
sage: P(1) in P.minimal_elements()
True
sage: P(2) in P.minimal_elements()
True
"""
return self.sources()
def maximal_elements(self):
"""
Return a list of the maximal elements of the poset.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})
sage: P.maximal_elements()
[4]
"""
return self.sinks()
@cached_method
def bottom(self):
"""
Return the bottom element of the poset, if it exists.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})
sage: P.bottom() is None
True
sage: Q = Poset({0:[1],1:[]})
sage: Q.bottom()
0
"""
min_elms = self.minimal_elements()
if len(min_elms) == 1:
return min_elms[0]
return None
def has_bottom(self) -> bool:
"""
Return ``True`` if the poset has a unique minimal element.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})
sage: P.has_bottom()
False
sage: Q = Poset({0:[1],1:[]})
sage: Q.has_bottom()
True
"""
return self.bottom() is not None
def top(self):
"""
Return the top element of the poset, if it exists.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})
sage: P.top() is None
True
sage: Q = Poset({0:[1],1:[]})
sage: Q.top()
1
"""
max_elms = self.maximal_elements()
if len(max_elms) == 1:
return max_elms[0]
return None
def has_top(self) -> bool:
"""
Return ``True`` if the poset contains a unique maximal element, and
``False`` otherwise.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})
sage: P.has_top()
False
sage: Q = Poset({0:[1],1:[]})
sage: Q.has_top()
True
"""
return self.top() is not None
def is_bounded(self) -> bool:
"""
Return ``True`` if the poset contains a unique maximal element and a
unique minimal element, and ``False`` otherwise.
EXAMPLES::
sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})
sage: P.is_bounded()
False
sage: Q = Poset({0:[1],1:[]})
sage: Q.is_bounded()
True
"""
return self.has_top() and self.has_bottom()
def is_chain(self) -> bool:
"""
Return ``True`` if the poset is totally ordered, and ``False`` otherwise.
EXAMPLES::
sage: L = Poset({0:[1],1:[2],2:[3],3:[4]})
sage: L.is_chain()
True
sage: V = Poset({0:[1,2]})
sage: V.is_chain()
False
TESTS:
Check :issue:`15330`::
sage: p = Poset(DiGraph({0:[1],2:[1]}))
sage: p.is_chain()
False
"""
if self.cardinality() == 0:
return True
return (self.num_edges() + 1 == self.num_verts() and # tree
all(d <= 1 for d in self.out_degree()) and
all(d <= 1 for d in self.in_degree()))
def is_antichain_of_poset(self, elms) -> bool:
"""
Return ``True`` if ``elms`` is an antichain of the Hasse
diagram and ``False`` otherwise.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})
sage: H.is_antichain_of_poset([1, 2, 3])
True
sage: H.is_antichain_of_poset([0, 2, 3])
False
"""
from itertools import combinations
elms_sorted = sorted(set(elms))
return not any(self.is_lequal(a, b) for a, b in
combinations(elms_sorted, 2))
def dual(self):
"""
Return a poset that is dual to the given poset.
This means that it has the same elements but opposite order.
The elements are renumbered to ensure that ``range(n)``
is a linear extension.
EXAMPLES::
sage: P = posets.IntegerPartitions(4) # optional - sage.combinat
sage: H = P._hasse_diagram; H # optional - sage.combinat
Hasse diagram of a poset containing 5 elements
sage: H.dual() # optional - sage.combinat
Hasse diagram of a poset containing 5 elements
TESTS::
sage: H = posets.IntegerPartitions(4)._hasse_diagram # optional - sage.combinat
sage: H.is_isomorphic( H.dual().dual() ) # optional - sage.combinat
True
sage: H.is_isomorphic( H.dual() ) # optional - sage.combinat
False
"""
H = self.reverse(immutable=False)
H.relabel(perm=list(range(H.num_verts() - 1, -1, -1)), inplace=True)
return HasseDiagram(H)
def _precompute_intervals(self):
"""
Precompute all intervals of the poset.
This will significantly speed up computing congruences. On the
other hand, it will cost much more memory. Currently this is
a hidden feature. See the example below for how to use it.
EXAMPLES::
sage: B4 = posets.BooleanLattice(4)
sage: B4.is_isoform() # Slow # optional - sage.combinat
True
sage: B4._hasse_diagram._precompute_intervals()
sage: B4 = posets.BooleanLattice(4)
sage: B4.is_isoform() # Faster now # optional - sage.combinat
True
"""
n = self.order()
v_up = (frozenset(self.depth_first_search(v)) for v in range(n))
v_down = [frozenset(self.depth_first_search(v, neighbors=self.neighbor_in_iterator))
for v in range(n)]
self._intervals = [[sorted(up.intersection(down)) for down in v_down]
for up in v_up]
def interval(self, x, y):
r"""
Return a list of the elements `z` of ``self`` such that
`x \leq z \leq y`.
The order is that induced by the ordering in ``self.linear_extension``.
INPUT:
- ``x`` -- any element of the poset
- ``y`` -- any element of the poset
.. NOTE::
The method :meth:`_precompute_intervals()` creates a cache
which is used if available, making the function very fast.
.. SEEALSO:: :meth:`interval_iterator`
EXAMPLES::
sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]
sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram(dag)
sage: I = set([2,5,6,4,7])
sage: I == set(H.interval(2,7))
True
"""
try:
# when the intervals have been precomputed
return self._intervals[x][y]
except AttributeError:
return list(self.interval_iterator(x, y))
def interval_iterator(self, x, y):
r"""
Return an iterator of the elements `z` of ``self`` such that
`x \leq z \leq y`.
INPUT:
- ``x`` -- any element of the poset
- ``y`` -- any element of the poset
.. SEEALSO:: :meth:`interval`
.. NOTE::
This becomes much faster when first calling :meth:`_leq_storage`,
which precomputes the principal upper ideals.
EXAMPLES::
sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]
sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram(dag)
sage: I = set([2,5,6,4,7])
sage: I == set(H.interval_iterator(2,7))
True
"""
for z in range(x, y + 1):
if self.is_lequal(x, z) and self.is_lequal(z, y):
yield z
closed_interval = interval
def open_interval(self, x, y):
"""
Return a list of the elements `z` of ``self`` such that `x < z < y`.
The order is that induced by the ordering in ``self.linear_extension``.
EXAMPLES::
sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]
sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram(dag)
sage: set([5,6,4]) == set(H.open_interval(2,7))
True
sage: H.open_interval(7,2)
[]
"""
ci = self.interval(x, y)
if not ci:
return []
else:
return ci[1:-1]
def rank_function(self):
r"""
Return the (normalized) rank function of the poset,
if it exists.
A *rank function* of a poset `P` is a function `r`
that maps elements of `P` to integers and satisfies:
`r(x) = r(y) + 1` if `x` covers `y`. The function `r`
is normalized such that its minimum value on every
connected component of the Hasse diagram of `P` is
`0`. This determines the function `r` uniquely (when
it exists).
OUTPUT:
- a lambda function, if the poset admits a rank function
- ``None``, if the poset does not admit a rank function
EXAMPLES::
sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])
sage: P.rank_function() is not None
True
sage: P = Poset(([1,2,3,4],[[1,4],[2,3],[3,4]]), facade = True)
sage: P.rank_function() is not None
True
sage: P = Poset(([1,2,3,4,5],[[1,2],[2,3],[3,4],[1,5],[5,4]]), facade = True)
sage: P.rank_function() is not None
False
sage: P = Poset(([1,2,3,4,5,6,7,8],[[1,4],[2,3],[3,4],[5,7],[6,7]]), facade = True)
sage: f = P.rank_function(); f is not None
True
sage: f(5)
0
sage: f(2)
0
TESTS::
sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])
sage: r = P.rank_function()
sage: for u,v in P.cover_relations_iterator():
....: if r(v) != r(u) + 1:
....: print("Bug in rank_function!")
::
sage: Q = Poset([[1,2],[4],[3],[4],[]])
sage: Q.rank_function() is None
True
test for issue :issue:`14006`::
sage: H = Poset()._hasse_diagram
sage: s = dumps(H)
sage: f = H.rank_function()
sage: s = dumps(H)
"""
if self._rank is None:
return None
# the rank function is just the getitem of the list
return self._rank.__getitem__
@lazy_attribute
def _rank(self):
r"""
Build the rank function of the poset, if it exists, i.e.
an array ``d`` where ``d[object] = self.rank_function()(object)``
A *rank function* of a poset `P` is a function `r`
that maps elements of `P` to integers and satisfies:
`r(x) = r(y) + 1` if `x` covers `y`. The function `r`
is normalized such that its minimum value on every
connected component of the Hasse diagram of `P` is
`0`. This determines the function `r` uniquely (when
it exists).
EXAMPLES::
sage: H = Poset()._hasse_diagram
sage: H._rank
[]
sage: H = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])._hasse_diagram
sage: H._rank
[0, 1, 1, 2, 2, 1, 2, 3]
sage: H = Poset(([1,2,3,4,5],[[1,2],[2,3],[3,4],[1,5],[5,4]]))._hasse_diagram
sage: H._rank is None
True
"""
# rank[i] is the rank of point i. It is equal to None until the rank of
# i is computed
rank = [None] * self.order()
not_found = set(self.vertex_iterator())
while not_found:
y = not_found.pop()
rank[y] = 0 # We set some vertex to have rank 0
component = {y}
queue = {y}
while queue:
# look at the neighbors of y and set the ranks;
# then look at the neighbors of the neighbors ...
y = queue.pop()
for x in self.neighbor_out_iterator(y):
if rank[x] is None:
rank[x] = rank[y] + 1
queue.add(x)
component.add(x)
for x in self.neighbor_in_iterator(y):
if rank[x] is None:
rank[x] = rank[y] - 1
queue.add(x)
component.add(x)
elif rank[x] != rank[y] - 1:
return None
# Normalize the ranks of vertices in the connected component
# so that smallest is 0:
m = min(rank[j] for j in component)
for j in component:
rank[j] -= m
not_found.difference_update(component)
# now, all ranks are set.
return rank
def rank(self, element=None):
r"""
Return the rank of ``element``, or the rank of the poset if
``element`` is ``None``. (The rank of a poset is the length of
the longest chain of elements of the poset.)
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})
sage: H.rank(5)
2
sage: H.rank()
3
sage: Q = HasseDiagram({0:[1,2],1:[3],2:[],3:[]})
sage: Q.rank()
2
sage: Q.rank(1)
1
"""
if element is None:
return len(self.level_sets()) - 1
else:
return self.rank_function()(element)
def is_ranked(self) -> bool:
r"""
Return ``True`` if the poset is ranked, and ``False`` otherwise.
A poset is *ranked* if it admits a rank function. For more information
about the rank function, see :meth:`~rank_function`
and :meth:`~is_graded`.
EXAMPLES::
sage: P = Poset([[1],[2],[3],[4],[]])
sage: P.is_ranked()
True
sage: Q = Poset([[1,5],[2,6],[3],[4],[],[6,3],[4]])
sage: Q.is_ranked()
False
"""
return bool(self.rank_function())
def covers(self, x, y):
"""
Return ``True`` if y covers x and ``False`` otherwise.
EXAMPLES::
sage: Q = Poset([[1,5],[2,6],[3],[4],[],[6,3],[4]])
sage: Q.covers(Q(1),Q(6))
True
sage: Q.covers(Q(1),Q(4))
False
"""
return self.has_edge(x, y)
def upper_covers_iterator(self, element):
r"""
Return the list of elements that cover ``element``.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})
sage: list(H.upper_covers_iterator(0))
[1, 2, 3]
sage: list(H.upper_covers_iterator(7))
[]
"""
yield from self.neighbor_out_iterator(element)
def lower_covers_iterator(self, element):
r"""
Return the list of elements that are covered by ``element``.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})
sage: list(H.lower_covers_iterator(0))
[]
sage: list(H.lower_covers_iterator(4))
[1, 2]
"""
yield from self.neighbor_in_iterator(element)
def cardinality(self):
r"""
Return the number of elements in the poset.
EXAMPLES::
sage: Poset([[1,2,3],[4],[4],[4],[]]).cardinality()
5
TESTS:
For a time, this function was named ``size()``, which
would override the same-named method of the underlying
digraph. :issue:`8735` renamed this method to ``cardinality()``
with a deprecation warning. :issue:`11214` removed the warning
since code for graphs was raising the warning inadvertently.
This tests that ``size()`` for a Hasse diagram returns the
number of edges in the digraph. ::
sage: L = posets.BooleanLattice(5)
sage: H = L.hasse_diagram()
sage: H.size()
80
sage: H.size() == H.num_edges()
True
"""
return self.order()
def moebius_function(self, i, j): # dumb algorithm
r"""
Return the value of the Möbius function of the poset
on the elements ``i`` and ``j``.
EXAMPLES::
sage: P = Poset([[1,2,3],[4],[4],[4],[]])
sage: H = P._hasse_diagram
sage: H.moebius_function(0,4)
2
sage: for u,v in P.cover_relations_iterator():
....: if P.moebius_function(u,v) != -1:
....: print("Bug in moebius_function!")
"""
try:
return self._moebius_function_values[(i, j)]
except AttributeError:
self._moebius_function_values = {}
return self.moebius_function(i, j)
except KeyError:
if i == j:
self._moebius_function_values[(i, j)] = 1
elif i > j:
self._moebius_function_values[(i, j)] = 0
else:
ci = self.interval(i, j)
if not ci:
self._moebius_function_values[(i, j)] = 0
else:
self._moebius_function_values[(i, j)] = -sum(self.moebius_function(i, k) for k in ci[:-1])
return self._moebius_function_values[(i, j)]
def bottom_moebius_function(self, j):
r"""
Return the value of the Möbius function of the poset
on the elements ``zero`` and ``j``, where ``zero`` is
``self.bottom()``, the unique minimal element of the poset.
EXAMPLES::
sage: P = Poset({0: [1,2]})
sage: hasse = P._hasse_diagram
sage: hasse.bottom_moebius_function(1)
-1
sage: hasse.bottom_moebius_function(2)
-1
sage: P = Poset({0: [1,3], 1:[2], 2:[4], 3:[4]})
sage: hasse = P._hasse_diagram
sage: for i in range(5):
....: print(hasse.bottom_moebius_function(i))
1
-1
0
-1
1
TESTS::
sage: P = Poset({0:[2], 1:[2]})
sage: hasse = P._hasse_diagram
sage: hasse.bottom_moebius_function(1)
Traceback (most recent call last):