code stringlengths 17 6.64M |
|---|
def from_rank(n, rank):
'\n Return the permutation of the set `\\{1,...,n\\}` with lexicographic\n rank ``rank``. This is the permutation whose Lehmer code is the\n factoradic representation of ``rank``. In particular, the\n permutation with rank `0` is the identity permutation.\n\n The permutation is computed without iterating through all of the\n permutations with lower rank. This makes it efficient for large\n permutations.\n\n .. NOTE::\n\n The variable ``rank`` is not checked for being in the interval\n from `0` to `n! - 1`. When outside this interval, it acts as\n its residue modulo `n!`.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: Permutation([3, 6, 5, 4, 2, 1]).rank()\n 359\n sage: [permutation.from_rank(3, i) for i in range(6)]\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n sage: Permutations(6)[10]\n [1, 2, 4, 6, 3, 5]\n sage: permutation.from_rank(6,10)\n [1, 2, 4, 6, 3, 5]\n '
factoradic = ([None] * n)
for j in range(1, (n + 1)):
factoradic[(n - j)] = Integer((rank % j))
rank = (int(rank) // j)
return from_lehmer_code(factoradic, Permutations(n))
|
def from_inversion_vector(iv, parent=None):
'\n Return the permutation corresponding to inversion vector ``iv``.\n\n See `~sage.combinat.permutation.Permutation.to_inversion_vector`\n for a definition of the inversion vector of a permutation.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.from_inversion_vector([3,1,0,0,0])\n [3, 2, 4, 1, 5]\n sage: permutation.from_inversion_vector([2,3,6,4,0,2,2,1,0])\n [5, 9, 1, 8, 2, 6, 4, 7, 3]\n sage: permutation.from_inversion_vector([0])\n [1]\n sage: permutation.from_inversion_vector([])\n []\n '
p = iv[:]
open_spots = list(range(len(iv)))
for (i, ivi) in enumerate(iv):
p[open_spots.pop(ivi)] = (i + 1)
if (parent is None):
parent = Permutations()
return parent(p)
|
def from_cycles(n, cycles, parent=None):
'\n Return the permutation in the `n`-th symmetric group whose decomposition\n into disjoint cycles is ``cycles``.\n\n This function checks that its input is correct (i.e. that the cycles are\n disjoint and their elements integers among `1...n`). It raises an exception\n otherwise.\n\n .. WARNING::\n\n It assumes that the elements are of ``int`` type.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.from_cycles(4, [[1,2]])\n [2, 1, 3, 4]\n sage: permutation.from_cycles(4, [[1,2,4]])\n [2, 4, 3, 1]\n sage: permutation.from_cycles(10, [[3,1],[4,5],[6,8,9]])\n [3, 2, 1, 5, 4, 8, 7, 9, 6, 10]\n sage: permutation.from_cycles(10, ((2, 5), (6, 1, 3)))\n [3, 5, 6, 4, 2, 1, 7, 8, 9, 10]\n sage: permutation.from_cycles(4, [])\n [1, 2, 3, 4]\n sage: permutation.from_cycles(4, [[]])\n [1, 2, 3, 4]\n sage: permutation.from_cycles(0, [])\n []\n\n Bad input (see :trac:`13742`)::\n\n sage: Permutation("(-12,2)(3,4)")\n Traceback (most recent call last):\n ...\n ValueError: all elements should be strictly positive integers, but I found -12\n sage: Permutation("(1,2)(2,4)")\n Traceback (most recent call last):\n ...\n ValueError: the element 2 appears more than once in the input\n sage: permutation.from_cycles(4, [[1,18]])\n Traceback (most recent call last):\n ...\n ValueError: you claimed that this is a permutation on 1...4, but it contains 18\n\n TESTS:\n\n Verify that :trac:`34662` has been fixed::\n\n sage: permutation.from_cycles(6, (c for c in [[1,2,3], [4,5,6]]))\n [2, 3, 1, 5, 6, 4]\n '
if (parent is None):
parent = Permutations(n)
p = (n * [None])
for cycle in cycles:
cycle_length = len(cycle)
for i in range(cycle_length):
k = ZZ(cycle[i])
pk = ZZ(cycle[((i + 1) % cycle_length)])
if ((k < 1) or (pk < 1)):
raise ValueError(f'all elements should be strictly positive integers, but I found {min(k, pk)}')
if ((k > n) or (pk > n)):
raise ValueError(f'you claimed that this is a permutation on 1...{n}, but it contains {max(k, pk)}')
if (p[(k - 1)] is not None):
raise ValueError(f'the element {k} appears more than once in the input')
p[(k - 1)] = pk
for i in range(n):
if (p[i] is None):
p[i] = ZZ((i + 1))
return parent(p, check=False)
|
def from_lehmer_code(lehmer, parent=None):
'\n Return the permutation with Lehmer code ``lehmer``.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: lc = Permutation([2,1,5,4,3]).to_lehmer_code(); lc\n [1, 0, 2, 1, 0]\n sage: permutation.from_lehmer_code(lc)\n [2, 1, 5, 4, 3]\n '
p = []
open_spots = list(range(1, (len(lehmer) + 1)))
for ivi in lehmer:
p.append(open_spots.pop(ivi))
if (parent is None):
parent = Permutations()
return parent(p)
|
def from_lehmer_cocode(lehmer, parent=Permutations()):
'\n Return the permutation with Lehmer cocode ``lehmer``.\n\n The Lehmer cocode of a permutation `p` is defined as the\n list `(c_1, c_2, \\ldots, c_n)`, where `c_i` is the number\n of `j < i` such that `p(j) > p(i)`.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: lcc = Permutation([2,1,5,4,3]).to_lehmer_cocode(); lcc\n [0, 1, 0, 1, 2]\n sage: permutation.from_lehmer_cocode(lcc)\n [2, 1, 5, 4, 3]\n '
p = []
ell = len(lehmer)
i = (ell - 1)
open_spots = list(range(1, (ell + 1)))
for ivi in reversed(lehmer):
p.append(open_spots.pop((i - ivi)))
i -= 1
p.reverse()
return parent(p)
|
def from_reduced_word(rw, parent=None):
'\n Return the permutation corresponding to the reduced word ``rw``.\n\n See\n :meth:`~sage.combinat.permutation.Permutation.reduced_words` for\n a definition of reduced words and the convention on the order of\n multiplication used.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.from_reduced_word([3,2,3,1,2,3,1])\n [3, 4, 2, 1]\n sage: permutation.from_reduced_word([])\n []\n '
if (parent is None):
parent = Permutations()
if (not rw):
return parent([])
p = [(i + 1) for i in range((max(rw) + 1))]
for i in rw:
(p[(i - 1)], p[i]) = (p[i], p[(i - 1)])
return parent(p)
|
def bistochastic_as_sum_of_permutations(M, check=True):
'\n Return the positive sum of permutations corresponding to\n the bistochastic matrix ``M``.\n\n A stochastic matrix is a matrix with nonnegative real entries such that the\n sum of the elements of any row is equal to `1`. A bistochastic matrix is a\n stochastic matrix whose transpose matrix is also stochastic ( there are\n conditions both on the rows and on the columns ).\n\n According to the Birkhoff-von Neumann Theorem, any bistochastic matrix\n can be written as a convex combination of permutation matrices, which also\n means that the polytope of bistochastic matrices is integer.\n\n As a non-bistochastic matrix can obviously not be written as a convex\n combination of permutations, this theorem is an equivalence.\n\n This function, given a bistochastic matrix, returns the corresponding\n decomposition.\n\n INPUT:\n\n - ``M`` -- A bistochastic matrix\n\n - ``check`` (boolean) -- set to ``True`` (default) to check\n that the matrix is indeed bistochastic\n\n OUTPUT:\n\n - An element of ``CombinatorialFreeModule``, which is a free `F`-module\n ( where `F` is the ground ring of the given matrix ) whose basis is\n indexed by the permutations.\n\n .. NOTE::\n\n - In this function, we just assume 1 to be any constant : for us a\n matrix `M` is bistochastic if there exists `c>0` such that `M/c`\n is bistochastic.\n\n - You can obtain a sequence of pairs ``(permutation,coeff)``, where\n ``permutation`` is a Sage ``Permutation`` instance, and ``coeff``\n its corresponding coefficient from the result of this function\n by applying the ``list`` function.\n\n - If you are interested in the matrix corresponding to a ``Permutation``\n you will be glad to learn about the ``Permutation.to_matrix()`` method.\n\n - The base ring of the matrix can be anything that can be coerced to ``RR``.\n\n .. SEEALSO::\n\n - :meth:`~sage.matrix.matrix2.as_sum_of_permutations`\n to use this method through the ``Matrix`` class.\n\n EXAMPLES:\n\n We create a bistochastic matrix from a convex sum of permutations, then\n try to deduce the decomposition from the matrix::\n\n sage: from sage.combinat.permutation import bistochastic_as_sum_of_permutations\n\n sage: # needs networkx sage.graphs sage.modules\n sage: L = []\n sage: L.append((9,Permutation([4, 1, 3, 5, 2])))\n sage: L.append((6,Permutation([5, 3, 4, 1, 2])))\n sage: L.append((3,Permutation([3, 1, 4, 2, 5])))\n sage: L.append((2,Permutation([1, 4, 2, 3, 5])))\n sage: M = sum([c * p.to_matrix() for (c,p) in L])\n sage: decomp = bistochastic_as_sum_of_permutations(M)\n sage: print(decomp)\n 2*B[[1, 4, 2, 3, 5]] + 3*B[[3, 1, 4, 2, 5]]\n + 9*B[[4, 1, 3, 5, 2]] + 6*B[[5, 3, 4, 1, 2]]\n\n An exception is raised when the matrix is not positive and bistochastic::\n\n sage: # needs sage.modules\n sage: M = Matrix([[2,3],[2,2]])\n sage: decomp = bistochastic_as_sum_of_permutations(M)\n Traceback (most recent call last):\n ...\n ValueError: The matrix is not bistochastic\n sage: bistochastic_as_sum_of_permutations(Matrix(GF(7), 2, [2,1,1,2]))\n Traceback (most recent call last):\n ...\n ValueError: The base ring of the matrix must have a coercion map to RR\n sage: bistochastic_as_sum_of_permutations(Matrix(ZZ, 2, [2,-1,-1,2]))\n Traceback (most recent call last):\n ...\n ValueError: The matrix should have nonnegative entries\n '
n = M.nrows()
if (n != M.ncols()):
raise ValueError('The matrix is expected to be square')
if (not all(((x >= 0) for x in M.list()))):
raise ValueError('The matrix should have nonnegative entries')
if (check and (not M.is_bistochastic(normalized=False))):
raise ValueError('The matrix is not bistochastic')
from sage.rings.real_mpfr import RR
if (not RR.has_coerce_map_from(M.base_ring())):
raise ValueError('The base ring of the matrix must have a coercion map to RR')
from sage.graphs.bipartite_graph import BipartiteGraph
from sage.combinat.free_module import CombinatorialFreeModule
CFM = CombinatorialFreeModule(M.base_ring(), Permutations(n))
value = 0
G = BipartiteGraph(M, weighted=True)
P = Permutations()
while (G.size() > 0):
matching = G.matching(use_edge_labels=True)
matching = [(min(u, v), max(u, v), w) for (u, v, w) in matching]
minimum = min([x[2] for x in matching])
for (u, v, l) in matching:
if (minimum == l):
G.delete_edge((u, v, l))
else:
G.set_edge_label(u, v, (l - minimum))
matching.sort(key=(lambda x: x[0]))
value += (minimum * CFM(P([((x[1] - n) + 1) for x in matching])))
return value
|
def bounded_affine_permutation(A):
'\n Return the bounded affine permutation of a matrix.\n\n The *bounded affine permutation* of a matrix `A` with entries in `R`\n is a partial permutation of length `n`, where `n` is the number of\n columns of `A`. The entry in position `i` is the smallest value `j`\n such that column `i` is in the span of columns `i+1, \\ldots, j`,\n over `R`, where column indices are taken modulo `n`.\n If column `i` is the zero vector, then the permutation has a\n fixed point at `i`.\n\n INPUT:\n\n - ``A`` -- matrix with entries in a ring `R`\n\n EXAMPLES::\n\n sage: from sage.combinat.permutation import bounded_affine_permutation\n sage: A = Matrix(ZZ, [[1,0,0,0], [0,1,0,0]]) # needs sage.modules\n sage: bounded_affine_permutation(A) # needs sage.libs.flint sage.modules\n [5, 6, 3, 4]\n\n sage: A = Matrix(ZZ, [[0,1,0,1,0], [0,0,1,1,0]]) # needs sage.modules\n sage: bounded_affine_permutation(A) # needs sage.libs.flint sage.modules\n [1, 4, 7, 8, 5]\n\n REFERENCES:\n\n - [KLS2013]_\n '
n = A.ncols()
R = A.base_ring()
from sage.modules.free_module import FreeModule
from sage.modules.free_module import span
z = FreeModule(R, A.nrows()).zero()
v = A.columns()
perm = []
for j in range(n):
if (not v[j]):
perm.append((j + 1))
continue
V = span([z], R)
for i in range((j + 1), ((j + n) + 1)):
index = (i % n)
V = (V + span([v[index]], R))
if (not V.dimension()):
continue
if (v[j] in V):
perm.append((i + 1))
break
S = Permutations((2 * n), n)
return S(perm)
|
class StandardPermutations_descents(StandardPermutations_n_abstract):
'\n Permutations of `\\{1, \\ldots, n\\}` with a fixed set of descents.\n '
@staticmethod
def __classcall_private__(cls, d, n):
'\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: P1 = Permutations(descents=([1,0,4,8],12))\n sage: P2 = Permutations(descents=((0,1,4,8),12))\n sage: P1 is P2\n True\n '
return super().__classcall__(cls, tuple(sorted(d)), n)
def __init__(self, d, n):
'\n The class of all permutations of `\\{1, 2, ..., n\\}`\n with set of descent positions `d` (where the descent positions\n are being counted from `0`, so that `i` lies in this set if\n and only if the permutation takes a larger value at `i + 1` than\n at `i + 2`).\n\n TESTS::\n\n sage: P = Permutations(descents=([1,0,2], 5))\n sage: TestSuite(P).run() # needs sage.graphs sage.modules\n '
StandardPermutations_n_abstract.__init__(self, n)
self._d = d
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(descents=([1,0,4,8],12))\n Standard permutations of 12 with descents [0, 1, 4, 8]\n '
return ('Standard permutations of %s with descents %s' % (self.n, list(self._d)))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n ALGORITHM:\n\n The algorithm described in [Vie1979]_ is implemented naively.\n\n EXAMPLES::\n\n sage: P = Permutations(descents=([1,0,2], 5))\n sage: P.cardinality()\n 4\n\n TESTS::\n\n sage: Permutations(descents=([], 1)).cardinality()\n 1\n\n sage: Permutations(descents=([1,4], 6)).cardinality()\n 40\n\n sage: def P(D, n):\n ....: return Permutations(descents=(D, n + 1))\n sage: all(P(D, n).cardinality() == len(P(D, n).list()) # needs sage.graphs sage.modules\n ....: for n in range(5) for D in subsets(range(n)))\n True\n\n sage: n = 20\n sage: D = [6, 8, 10, 11, 12, 13, 14, 15, 17, 19]\n sage: P(D, n).cardinality()\n 125291047596\n\n '
def m(l):
s = 0
partial_sums = [0]
for i in l:
s += i
partial_sums.append(s)
return partial_sums
def d(l):
return m(reversed(l))[::(- 1)]
one = ZZ.one()
if (not self._d):
return one
l_ops = ([1] * (self.n - 1))
for i in self._d:
l_ops[i] = 0
l = [one]
for op in reversed(l_ops):
if op:
l = m(l)
else:
l = d(l)
return sum(l)
def first(self):
'\n Return the first permutation with descents `d`.\n\n EXAMPLES::\n\n sage: Permutations(descents=([1,0,4,8],12)).first()\n [3, 2, 1, 4, 6, 5, 7, 8, 10, 9, 11, 12]\n '
return descents_composition_first(Composition(descents=(self._d, self.n)))
def last(self):
'\n Return the last permutation with descents `d`.\n\n EXAMPLES::\n\n sage: Permutations(descents=([1,0,4,8],12)).last()\n [12, 11, 8, 9, 10, 4, 5, 6, 7, 1, 2, 3]\n '
return descents_composition_last(Composition(descents=(self._d, self.n)))
def __iter__(self):
'\n Iterate over all the permutations that have the descents `d`.\n\n EXAMPLES::\n\n sage: Permutations(descents=([2,0],5)).list() # needs sage.graphs sage.modules\n [[5, 2, 4, 1, 3],\n [5, 3, 4, 1, 2],\n [4, 3, 5, 1, 2],\n [4, 2, 5, 1, 3],\n [3, 2, 5, 1, 4],\n [2, 1, 5, 3, 4],\n [3, 1, 5, 2, 4],\n [4, 1, 5, 2, 3],\n [5, 1, 4, 2, 3],\n [5, 1, 3, 2, 4],\n [4, 1, 3, 2, 5],\n [3, 1, 4, 2, 5],\n [2, 1, 4, 3, 5],\n [3, 2, 4, 1, 5],\n [4, 2, 3, 1, 5],\n [5, 2, 3, 1, 4]]\n '
return iter(descents_composition_list(Composition(descents=(self._d, self.n))))
|
def descents_composition_list(dc):
'\n Return a list of all the permutations that have the descent\n composition ``dc``.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.descents_composition_list([1,2,2]) # needs sage.graphs sage.modules\n [[5, 2, 4, 1, 3],\n [5, 3, 4, 1, 2],\n [4, 3, 5, 1, 2],\n [4, 2, 5, 1, 3],\n [3, 2, 5, 1, 4],\n [2, 1, 5, 3, 4],\n [3, 1, 5, 2, 4],\n [4, 1, 5, 2, 3],\n [5, 1, 4, 2, 3],\n [5, 1, 3, 2, 4],\n [4, 1, 3, 2, 5],\n [3, 1, 4, 2, 5],\n [2, 1, 4, 3, 5],\n [3, 2, 4, 1, 5],\n [4, 2, 3, 1, 5],\n [5, 2, 3, 1, 4]]\n '
return [p.inverse() for p in StandardPermutations_recoils(dc)]
|
def descents_composition_first(dc):
'\n Compute the smallest element of a descent class having a descent\n composition ``dc``.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.descents_composition_first([1,1,3,4,3])\n [3, 2, 1, 4, 6, 5, 7, 8, 10, 9, 11, 12]\n '
if (not isinstance(dc, Composition)):
try:
dc = Composition(dc)
except TypeError:
raise TypeError('The argument must be of type Composition')
cpl = [x for x in reversed(dc.conjugate())]
res = []
s = 0
for cpli in cpl:
s += cpli
res += [(s - j) for j in range(cpli)]
return Permutations()(res)
|
def descents_composition_last(dc):
'\n Return the largest element of a descent class having a descent\n composition ``dc``.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.descents_composition_last([1,1,3,4,3])\n [12, 11, 8, 9, 10, 4, 5, 6, 7, 1, 2, 3]\n '
if (not isinstance(dc, Composition)):
try:
dc = Composition(dc)
except TypeError:
raise TypeError('The argument must be of type Composition')
s = 0
res = []
for i in reversed(range(len(dc))):
res = ([j for j in range((s + 1), ((s + dc[i]) + 1))] + res)
s += dc[i]
return Permutations()(res)
|
class StandardPermutations_recoilsfiner(Permutations):
@staticmethod
def __classcall_private__(cls, recoils):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(recoils_finer=[2,2])\n sage: S2 = Permutations(recoils_finer=(2,2))\n sage: S1 is S2\n True\n '
return super().__classcall__(cls, Composition(recoils))
def __init__(self, recoils):
'\n TESTS::\n\n sage: P = Permutations(recoils_finer=[2,2])\n sage: TestSuite(P).run() # needs sage.graphs\n '
Permutations.__init__(self, category=FiniteEnumeratedSets())
self.recoils = recoils
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(recoils_finer=[2,2])\n Standard permutations whose recoils composition is finer than [2, 2]\n '
return ('Standard permutations whose recoils composition is finer than %s' % self.recoils)
def __iter__(self):
'\n Iterate over of all of the permutations whose recoils composition\n is finer than ``self.recoils``.\n\n EXAMPLES::\n\n sage: Permutations(recoils_finer=[2,2]).list() # needs sage.graphs sage.modules\n [[3, 1, 4, 2],\n [3, 4, 1, 2],\n [1, 3, 4, 2],\n [1, 3, 2, 4],\n [1, 2, 3, 4],\n [3, 1, 2, 4]]\n '
recoils = self.recoils
dag = DiGraph()
for i in range(1, (sum(recoils) + 1)):
dag.add_vertex(i)
pos = 1
for part in recoils:
for i in range((part - 1)):
dag.add_edge(pos, (pos + 1))
pos += 1
pos += 1
for le in dag.topological_sort_generator():
(yield self.element_class(self, le, check=False))
|
class StandardPermutations_recoilsfatter(Permutations):
@staticmethod
def __classcall_private__(cls, recoils):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(recoils_fatter=[2,2])\n sage: S2 = Permutations(recoils_fatter=(2,2))\n sage: S1 is S2\n True\n '
return super().__classcall__(cls, Composition(recoils))
def __init__(self, recoils):
'\n TESTS::\n\n sage: P = Permutations(recoils_fatter=[2,2])\n sage: TestSuite(P).run() # needs sage.graphs\n '
Permutations.__init__(self, category=FiniteEnumeratedSets())
self.recoils = recoils
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(recoils_fatter=[2,2])\n Standard permutations whose recoils composition is fatter than [2, 2]\n '
return ('Standard permutations whose recoils composition is fatter than %s' % self.recoils)
def __iter__(self):
'\n Iterate over of all of the permutations whose recoils composition\n is fatter than ``self.recoils``.\n\n EXAMPLES::\n\n sage: Permutations(recoils_fatter=[2,2]).list() # needs sage.graphs sage.modules\n [[4, 3, 2, 1],\n [3, 2, 1, 4],\n [3, 2, 4, 1],\n [3, 4, 2, 1],\n [3, 4, 1, 2],\n [3, 1, 4, 2],\n [1, 3, 4, 2],\n [1, 3, 2, 4],\n [3, 1, 2, 4],\n [1, 4, 3, 2],\n [4, 1, 3, 2],\n [4, 3, 1, 2]]\n '
recoils = self.recoils
dag = DiGraph()
for i in range(1, (sum(recoils) + 1)):
dag.add_vertex(i)
pos = 0
for i in range((len(recoils) - 1)):
pos += recoils[i]
dag.add_edge((pos + 1), pos)
for le in dag.topological_sort_generator():
(yield self.element_class(self, le, check=False))
|
class StandardPermutations_recoils(Permutations):
'\n Permutations of `\\{1, \\ldots, n\\}` with a fixed recoils composition.\n '
@staticmethod
def __classcall_private__(cls, recoils):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(recoils=[2,2])\n sage: S2 = Permutations(recoils=(2,2))\n sage: S1 is S2\n True\n '
return super().__classcall__(cls, Composition(recoils))
def __init__(self, recoils):
'\n TESTS::\n\n sage: P = Permutations(recoils=[2,2])\n sage: TestSuite(P).run() # needs sage.graphs\n '
Permutations.__init__(self, category=FiniteEnumeratedSets())
self.recoils = recoils
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(recoils=[2,2])\n Standard permutations whose recoils composition is [2, 2]\n '
return ('Standard permutations whose recoils composition is %s' % self.recoils)
def __iter__(self):
'\n Iterate over of all of the permutations whose recoils composition\n is equal to ``self.recoils``.\n\n EXAMPLES::\n\n sage: Permutations(recoils=[2,2]).list() # needs sage.graphs sage.modules\n [[3, 1, 4, 2], [3, 4, 1, 2], [1, 3, 4, 2], [1, 3, 2, 4], [3, 1, 2, 4]]\n '
recoils = self.recoils
dag = DiGraph()
for i in range(1, (sum(recoils) + 1)):
dag.add_vertex(i)
pos = 1
for part in recoils:
for i in range((part - 1)):
dag.add_edge(pos, (pos + 1))
pos += 1
pos += 1
pos = 0
for i in range((len(recoils) - 1)):
pos += recoils[i]
dag.add_edge((pos + 1), pos)
for le in dag.topological_sort_generator():
(yield self.element_class(self, le, check=False))
|
def from_major_code(mc, final_descent=False):
'\n Return the permutation with major code ``mc``.\n\n The major code of a permutation is defined in\n :meth:`~sage.combinat.permutation.Permutation.to_major_code`.\n\n .. WARNING::\n\n This function creates illegal permutations (i.e. ``Permutation([9])``,\n and this is dangerous as the :meth:`Permutation` class is only designed\n to handle permutations on `1...n`. This will have to be changed when Sage\n permutations will be able to handle anything, but right now this should\n be fixed. Be careful with the results.\n\n .. WARNING::\n\n If ``mc`` is not a major index of a permutation, then the return\n value of this method can be anything. Garbage in, garbage out!\n\n REFERENCES:\n\n - Skandera, M. *An Eulerian Partner for Inversions*. Sem.\n Lothar. Combin. 46 (2001) B46d.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.from_major_code([5, 0, 1, 0, 1, 2, 0, 1, 0])\n [9, 3, 5, 7, 2, 1, 4, 6, 8]\n sage: permutation.from_major_code([8, 3, 3, 1, 4, 0, 1, 0, 0])\n [2, 8, 4, 3, 6, 7, 9, 5, 1]\n sage: Permutation([2,1,6,4,7,3,5]).to_major_code()\n [3, 2, 0, 2, 2, 0, 0]\n sage: permutation.from_major_code([3, 2, 0, 2, 2, 0, 0])\n [2, 1, 6, 4, 7, 3, 5]\n\n TESTS::\n\n sage: permutation.from_major_code([])\n []\n\n sage: all( permutation.from_major_code(p.to_major_code()) == p\n ....: for p in Permutations(5) )\n True\n '
if (not mc):
w = []
else:
w = [len(mc)]
for i in reversed(range(1, len(mc))):
d = Permutation(w, check=False).descents(final_descent=final_descent)
d.reverse()
a = [x for x in range(1, (len(w) + 1)) if (x not in d)]
d.append(0)
l = mc[(i - 1)]
indices = (d + a)
w.insert(indices[l], i)
return Permutation(w, check=False)
|
class StandardPermutations_bruhat_smaller(Permutations):
'\n Permutations of `\\{1, \\ldots, n\\}` that are less than or equal to a\n permutation `p` in the Bruhat order.\n '
@staticmethod
def __classcall_private__(cls, p):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(bruhat_smaller=[2,3,1])\n sage: S2 = Permutations(bruhat_smaller=(1,2,3))\n sage: S1 is S2\n True\n '
return super().__classcall__(cls, Permutation(p))
def __init__(self, p):
'\n TESTS::\n\n sage: P = Permutations(bruhat_smaller=[3,2,1])\n sage: TestSuite(P).run()\n '
Permutations.__init__(self, category=FiniteEnumeratedSets())
self.p = p
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(bruhat_smaller=[3,2,1])\n Standard permutations that are less than or equal to [3, 2, 1] in the Bruhat order\n '
return ('Standard permutations that are less than or equal to %s in the Bruhat order' % self.p)
def __iter__(self):
'\n Iterate through a list of permutations smaller than or equal to ``p``\n in the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutations(bruhat_smaller=[4,1,2,3]).list()\n [[1, 2, 3, 4],\n [1, 2, 4, 3],\n [1, 3, 2, 4],\n [1, 4, 2, 3],\n [2, 1, 3, 4],\n [2, 1, 4, 3],\n [3, 1, 2, 4],\n [4, 1, 2, 3]]\n '
return iter(transitive_ideal((lambda x: x.bruhat_pred()), self.p))
|
class StandardPermutations_bruhat_greater(Permutations):
'\n Permutations of `\\{1, \\ldots, n\\}` that are greater than or equal to a\n permutation `p` in the Bruhat order.\n '
@staticmethod
def __classcall_private__(cls, p):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(bruhat_greater=[2,3,1])\n sage: S2 = Permutations(bruhat_greater=(1,2,3))\n sage: S1 is S2\n True\n '
return super().__classcall__(cls, Permutation(p))
def __init__(self, p):
'\n TESTS::\n\n sage: P = Permutations(bruhat_greater=[3,2,1])\n sage: TestSuite(P).run()\n '
Permutations.__init__(self, category=FiniteEnumeratedSets())
self.p = p
def _repr_(self):
'\n TESTS::\n\n sage: Permutations(bruhat_greater=[3,2,1])\n Standard permutations that are greater than or equal to [3, 2, 1] in the Bruhat order\n '
return ('Standard permutations that are greater than or equal to %s in the Bruhat order' % self.p)
def __iter__(self):
'\n Iterate through a list of permutations greater than or equal to ``p``\n in the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutations(bruhat_greater=[4,1,2,3]).list()\n [[4, 1, 2, 3],\n [4, 1, 3, 2],\n [4, 2, 1, 3],\n [4, 2, 3, 1],\n [4, 3, 1, 2],\n [4, 3, 2, 1]]\n '
return iter(transitive_ideal((lambda x: x.bruhat_succ()), self.p))
|
def bruhat_lequal(p1, p2):
'\n Return ``True`` if ``p1`` is less than ``p2`` in the Bruhat order.\n\n Algorithm from mupad-combinat.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.bruhat_lequal([2,4,3,1],[3,4,2,1])\n True\n '
n1 = len(p1)
if (n1 == 0):
return True
if ((p1[0] > p2[0]) or (p1[(n1 - 1)] < p2[(n1 - 1)])):
return False
for i in range(n1):
c = 0
for j in range(n1):
if (p2[j] > (i + 1)):
c += 1
if (p1[j] > (i + 1)):
c -= 1
if (c < 0):
return False
return True
|
def permutohedron_lequal(p1, p2, side='right'):
"\n Return ``True`` if ``p1`` is less than or equal to ``p2`` in the\n permutohedron order.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side='left'``, then they will be done in the\n left permutohedron.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: permutation.permutohedron_lequal(Permutation([3,2,1,4]),Permutation([4,2,1,3]))\n False\n sage: permutation.permutohedron_lequal(Permutation([3,2,1,4]),Permutation([4,2,1,3]), side='left')\n True\n "
l1 = p1.number_of_inversions()
l2 = p2.number_of_inversions()
if (l1 > l2):
return False
if (side == 'right'):
prod = p1._left_to_right_multiply_on_right(p2.inverse())
else:
prod = p1._left_to_right_multiply_on_left(p2.inverse())
return (prod.number_of_inversions() == (l2 - l1))
|
def to_standard(p, key=None):
'\n Return a standard permutation corresponding to the iterable ``p``.\n\n INPUT:\n\n - ``p`` -- an iterable\n - ``key`` -- (optional) a comparison key for the element\n ``x`` of ``p``\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: import sage.combinat.permutation as permutation\n sage: permutation.to_standard([4,2,7])\n [2, 1, 3]\n sage: permutation.to_standard([1,2,3])\n [1, 2, 3]\n sage: permutation.to_standard([])\n []\n sage: permutation.to_standard([1,2,3], key=lambda x: -x)\n [3, 2, 1]\n sage: permutation.to_standard([5,8,2,5], key=lambda x: -x)\n [2, 1, 4, 3]\n\n TESTS:\n\n Does not mutate the list::\n\n sage: a = [1,2,4]\n sage: permutation.to_standard(a) # needs sage.combinat\n [1, 2, 3]\n sage: a\n [1, 2, 4]\n\n We check against the naive method::\n\n sage: def std(p):\n ....: s = [0]*len(p)\n ....: c = p[:]\n ....: biggest = max(p) + 1\n ....: i = 1\n ....: for _ in range(len(c)):\n ....: smallest = min(c)\n ....: smallest_index = c.index(smallest)\n ....: s[smallest_index] = i\n ....: i += 1\n ....: c[smallest_index] = biggest\n ....: return Permutations()(s)\n sage: p = list(Words(100, 1000).random_element()) # needs sage.combinat\n sage: std(p) == permutation.to_standard(p) # needs sage.combinat\n True\n '
ev_dict = evaluation_dict(p)
ordered_alphabet = sorted(ev_dict, key=key)
offset = 0
for k in ordered_alphabet:
temp = ev_dict[k]
ev_dict[k] = offset
offset += temp
result = []
for l in p:
ev_dict[l] += 1
result.append(ev_dict[l])
return Permutations(len(result))(result)
|
class CyclicPermutations(Permutations_mset):
'\n Return the class of all cyclic permutations of ``mset`` in cycle notation.\n These are the same as necklaces.\n\n INPUT:\n\n - ``mset`` -- A multiset\n\n EXAMPLES::\n\n sage: CyclicPermutations(range(4)).list() # needs sage.combinat\n [[0, 1, 2, 3],\n [0, 1, 3, 2],\n [0, 2, 1, 3],\n [0, 2, 3, 1],\n [0, 3, 1, 2],\n [0, 3, 2, 1]]\n sage: CyclicPermutations([1,1,1]).list() # needs sage.combinat\n [[1, 1, 1]]\n '
@staticmethod
def __classcall_private__(cls, mset):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: CP1 = CyclicPermutations([1,1,1])\n sage: CP2 = CyclicPermutations((1,1,1))\n sage: CP1 is CP2\n True\n\n sage: CP = CyclicPermutations([1,2,3,3])\n sage: CP\n Cyclic permutations of [1, 2, 3, 3]\n sage: TestSuite(CP).run() # not tested -- broken\n '
return super().__classcall__(cls, tuple(mset))
def _repr_(self):
'\n TESTS::\n\n sage: CyclicPermutations(range(4))\n Cyclic permutations of [0, 1, 2, 3]\n '
return ('Cyclic permutations of %s' % list(self.mset))
def __iter__(self, distinct=False):
'\n EXAMPLES::\n\n sage: CyclicPermutations(range(4)).list() # indirect doctest # needs sage.combinat\n [[0, 1, 2, 3],\n [0, 1, 3, 2],\n [0, 2, 1, 3],\n [0, 2, 3, 1],\n [0, 3, 1, 2],\n [0, 3, 2, 1]]\n sage: CyclicPermutations([1,1,1]).list() # needs sage.combinat\n [[1, 1, 1]]\n sage: CyclicPermutations([1,1,1]).list(distinct=True) # needs sage.combinat\n [[1, 1, 1], [1, 1, 1]]\n '
if distinct:
content = ([1] * len(self.mset))
else:
content = ([0] * len(self.mset))
index_list = map(self.mset.index, self.mset)
for i in index_list:
content[i] += 1
from .necklace import Necklaces
for necklace in Necklaces(content):
(yield [self.mset[(x - 1)] for x in necklace])
iterator = __iter__
def list(self, distinct=False):
'\n EXAMPLES::\n\n sage: CyclicPermutations(range(4)).list() # needs sage.combinat\n [[0, 1, 2, 3],\n [0, 1, 3, 2],\n [0, 2, 1, 3],\n [0, 2, 3, 1],\n [0, 3, 1, 2],\n [0, 3, 2, 1]]\n '
return list(self.__iter__(distinct=distinct))
|
class CyclicPermutationsOfPartition(Permutations):
'\n Combinations of cyclic permutations of each cell of a given partition.\n\n This is the same as a Cartesian product of necklaces.\n\n EXAMPLES::\n\n sage: CyclicPermutationsOfPartition([[1,2,3,4],[5,6,7]]).list() # needs sage.combinat\n [[[1, 2, 3, 4], [5, 6, 7]],\n [[1, 2, 4, 3], [5, 6, 7]],\n [[1, 3, 2, 4], [5, 6, 7]],\n [[1, 3, 4, 2], [5, 6, 7]],\n [[1, 4, 2, 3], [5, 6, 7]],\n [[1, 4, 3, 2], [5, 6, 7]],\n [[1, 2, 3, 4], [5, 7, 6]],\n [[1, 2, 4, 3], [5, 7, 6]],\n [[1, 3, 2, 4], [5, 7, 6]],\n [[1, 3, 4, 2], [5, 7, 6]],\n [[1, 4, 2, 3], [5, 7, 6]],\n [[1, 4, 3, 2], [5, 7, 6]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3,4],[4,4,4]]).list() # needs sage.combinat\n [[[1, 2, 3, 4], [4, 4, 4]],\n [[1, 2, 4, 3], [4, 4, 4]],\n [[1, 3, 2, 4], [4, 4, 4]],\n [[1, 3, 4, 2], [4, 4, 4]],\n [[1, 4, 2, 3], [4, 4, 4]],\n [[1, 4, 3, 2], [4, 4, 4]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list() # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]], [[1, 3, 2], [4, 4, 4]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list(distinct=True) # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]],\n [[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]]]\n '
@staticmethod
def __classcall_private__(cls, partition):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: CP1 = CyclicPermutationsOfPartition([[1,2,3],[4,4,4]])\n sage: CP2 = CyclicPermutationsOfPartition([[1,2,3],[4,4,4]])\n sage: CP1 is CP2\n True\n '
partition = tuple(map(tuple, partition))
return super().__classcall__(cls, partition)
def __init__(self, partition):
'\n TESTS::\n\n sage: CP = CyclicPermutationsOfPartition([[1,2,3,4],[5,6,7]])\n sage: CP\n Cyclic permutations of partition [[1, 2, 3, 4], [5, 6, 7]]\n sage: TestSuite(CP).run() # needs sage.combinat\n '
self.partition = partition
Permutations.__init__(self, category=FiniteEnumeratedSets())
class Element(ClonableArray):
'\n A cyclic permutation of a partition.\n '
def check(self):
'\n Check that ``self`` is a valid element.\n\n EXAMPLES::\n\n sage: CP = CyclicPermutationsOfPartition([[1,2,3,4],[5,6,7]])\n sage: elt = CP[0] # needs sage.combinat\n sage: elt.check() # needs sage.combinat\n '
if ([sorted(_) for _ in self] != [sorted(_) for _ in self.parent().partition]):
raise ValueError(('Invalid cyclic permutation of the partition' % self.parent().partition))
def _repr_(self):
'\n TESTS::\n\n sage: CyclicPermutationsOfPartition([[1,2,3,4],[5,6,7]])\n Cyclic permutations of partition [[1, 2, 3, 4], [5, 6, 7]]\n '
return 'Cyclic permutations of partition {}'.format([list(_) for _ in self.partition])
def __iter__(self, distinct=False):
'\n AUTHORS:\n\n - Robert Miller\n\n EXAMPLES::\n\n sage: CyclicPermutationsOfPartition([[1,2,3,4], # indirect doctest # needs sage.combinat\n ....: [5,6,7]]).list()\n [[[1, 2, 3, 4], [5, 6, 7]],\n [[1, 2, 4, 3], [5, 6, 7]],\n [[1, 3, 2, 4], [5, 6, 7]],\n [[1, 3, 4, 2], [5, 6, 7]],\n [[1, 4, 2, 3], [5, 6, 7]],\n [[1, 4, 3, 2], [5, 6, 7]],\n [[1, 2, 3, 4], [5, 7, 6]],\n [[1, 2, 4, 3], [5, 7, 6]],\n [[1, 3, 2, 4], [5, 7, 6]],\n [[1, 3, 4, 2], [5, 7, 6]],\n [[1, 4, 2, 3], [5, 7, 6]],\n [[1, 4, 3, 2], [5, 7, 6]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3,4],[4,4,4]]).list() # needs sage.combinat\n [[[1, 2, 3, 4], [4, 4, 4]],\n [[1, 2, 4, 3], [4, 4, 4]],\n [[1, 3, 2, 4], [4, 4, 4]],\n [[1, 3, 4, 2], [4, 4, 4]],\n [[1, 4, 2, 3], [4, 4, 4]],\n [[1, 4, 3, 2], [4, 4, 4]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list() # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]], [[1, 3, 2], [4, 4, 4]]]\n\n ::\n\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list(distinct=True) # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]],\n [[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]]]\n '
if (len(self.partition) == 1):
for i in CyclicPermutations(self.partition[0]).iterator(distinct=distinct):
(yield self.element_class(self, [i], check=False))
else:
for right in CyclicPermutationsOfPartition(self.partition[1:]).iterator(distinct=distinct):
for perm in CyclicPermutations(self.partition[0]).iterator(distinct=distinct):
(yield self.element_class(self, ([perm] + list(right)), check=False))
iterator = __iter__
def list(self, distinct=False):
'\n EXAMPLES::\n\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list() # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]], [[1, 3, 2], [4, 4, 4]]]\n sage: CyclicPermutationsOfPartition([[1,2,3],[4,4,4]]).list(distinct=True) # needs sage.combinat\n [[[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]],\n [[1, 2, 3], [4, 4, 4]],\n [[1, 3, 2], [4, 4, 4]]]\n '
return list(self.iterator(distinct=distinct))
|
class StandardPermutations_all_avoiding(StandardPermutations_all):
'\n All standard permutations avoiding a set of patterns.\n '
@staticmethod
def __classcall_private__(cls, a):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: P1 = Permutations(avoiding=([2,1,3],[1,2,3]))\n sage: P2 = Permutations(avoiding=[[2,1,3],[1,2,3]])\n sage: P1 is P2\n True\n '
a = tuple(map(Permutation, a))
return super().__classcall__(cls, a)
def __init__(self, a):
'\n TESTS::\n\n sage: P = Permutations(avoiding=[[2,1,3],[1,2,3]])\n sage: TestSuite(P).run(max_runs=25) # needs sage.combinat\n '
Permutations.__init__(self, category=InfiniteEnumeratedSets())
self._a = a
def patterns(self):
'\n Return the patterns avoided by this class of permutations.\n\n EXAMPLES::\n\n sage: P = Permutations(avoiding=[[2,1,3],[1,2,3]])\n sage: P.patterns()\n ([2, 1, 3], [1, 2, 3])\n '
return self._a
def _repr_(self):
'\n EXAMPLES::\n\n sage: Permutations(avoiding=[[2,1,3],[1,2,3]])\n Standard permutations avoiding [[2, 1, 3], [1, 2, 3]]\n '
return f'Standard permutations avoiding {list(self._a)}'
def __contains__(self, x):
'\n TESTS::\n\n sage: [1,3,2] in Permutations(avoiding=[1,3,2]) # needs sage.combinat\n False\n sage: [1,3,2] in Permutations(avoiding=[[1,3,2]]) # needs sage.combinat\n False\n sage: [2,1,3] in Permutations(avoiding=[[1,3,2],[1,2,3]]) # needs sage.combinat\n True\n sage: [2,1,3] in Permutations(avoiding=[])\n True\n '
if (not super().__contains__(x)):
return False
x = Permutations()(x)
return all((x.avoids(p) for p in self._a))
def __iter__(self):
'\n Iterate over ``self``.\n\n TESTS::\n\n sage: it = iter(Permutations(avoiding=[[2,1,3],[1,2,3]]))\n sage: [next(it) for i in range(10)] # needs sage.combinat\n [[],\n [1],\n [1, 2],\n [2, 1],\n [1, 3, 2],\n [2, 3, 1],\n [3, 1, 2],\n [3, 2, 1],\n [1, 4, 3, 2],\n [2, 4, 3, 1]]\n '
n = 0
while True:
for x in itertools.permutations(range(1, (n + 1))):
x = self.element_class(self, x, check=False)
if all((x.avoids(p) for p in self._a)):
(yield x)
n += 1
|
class StandardPermutations_avoiding_generic(StandardPermutations_n_abstract):
'\n Generic class for subset of permutations avoiding a set of patterns.\n '
@staticmethod
def __classcall_private__(cls, n, a):
'\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: P1 = Permutations(3, avoiding=([2,1,3],[1,2,3]))\n sage: P2 = Permutations(3, avoiding=[[2,1,3],[1,2,3]])\n sage: P1 is P2\n True\n '
a = tuple(map(Permutation, a))
return super().__classcall__(cls, n, a)
def __init__(self, n, a):
"\n EXAMPLES::\n\n sage: P = Permutations(3, avoiding=[[2,1,3],[1,2,3]])\n sage: TestSuite(P).run() # needs sage.combinat\n sage: type(P)\n <class 'sage.combinat.permutation.StandardPermutations_avoiding_generic_with_category'>\n "
StandardPermutations_n_abstract.__init__(self, n)
self._a = a
@property
def a(self):
'\n ``self.a`` is deprecated; use :meth:`patterns` instead.\n\n TESTS::\n\n sage: P = Permutations(3, avoiding=[[2,1,3],[1,2,3]])\n sage: P.a\n doctest:...: DeprecationWarning: The attribute a for the list of patterns to avoid is deprecated, use the method patterns instead.\n See https://github.com/sagemath/sage/issues/26810 for details.\n ([2, 1, 3], [1, 2, 3])\n '
from sage.misc.superseded import deprecation
deprecation(26810, 'The attribute a for the list of patterns to avoid is deprecated, use the method patterns instead.')
return self.patterns()
def patterns(self):
'\n Return the patterns avoided by this class of permutations.\n\n EXAMPLES::\n\n sage: P = Permutations(3, avoiding=[[2,1,3],[1,2,3]])\n sage: P.patterns()\n ([2, 1, 3], [1, 2, 3])\n '
return self._a
def __contains__(self, x):
'\n TESTS::\n\n sage: [1,3,2] in Permutations(3, avoiding=[1,3,2]) # needs sage.combinat\n False\n sage: [1,3,2] in Permutations(3, avoiding=[[1,3,2]]) # needs sage.combinat\n False\n sage: [2,1,3] in Permutations(3, avoiding=[[1,3,2],[1,2,3]]) # needs sage.combinat\n True\n sage: [2,1,3] in Permutations(3, avoiding=[])\n True\n '
if (not super().__contains__(x)):
return False
x = Permutations()(x)
return all((x.avoids(p) for p in self._a))
def _repr_(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[[2, 1, 3],[1,2,3]])\n Standard permutations of 3 avoiding [[2, 1, 3], [1, 2, 3]]\n '
return ('Standard permutations of %s avoiding %s' % (self.n, list(self._a)))
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[[2, 1, 3],[1,2,3]]).list() # needs sage.combinat\n [[1, 3, 2], [3, 1, 2], [2, 3, 1], [3, 2, 1]]\n sage: Permutations(0, avoiding=[[2, 1, 3],[1,2,3]]).list()\n [[]]\n '
if (self.n > 0):
return iter(PatternAvoider(self, self._a))
return iter([self.element_class(self, [], check=False)])
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: P = Permutations(3, avoiding=[[2, 1, 3],[1,2,3]])\n sage: P.cardinality() # needs sage.combinat\n 4\n '
one = ZZ.one()
return sum((one for p in self))
|
class StandardPermutations_avoiding_12(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[1, 2])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([1, 2]),))
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[1,2]).list()\n [[3, 2, 1]]\n '
(yield self.element_class(self, range(self.n, 0, (- 1)), check=False))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: P = Permutations(3, avoiding=[1, 2])\n sage: P.cardinality()\n 1\n '
return ZZ.one()
|
class StandardPermutations_avoiding_21(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[2, 1])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([2, 1]),))
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[2,1]).list()\n [[1, 2, 3]]\n '
(yield self.element_class(self, range(1, (self.n + 1)), check=False))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: P = Permutations(3, avoiding=[2, 1])\n sage: P.cardinality()\n 1\n '
return ZZ.one()
|
class StandardPermutations_avoiding_132(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[1, 3, 2])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([1, 3, 2]),))
def cardinality(self):
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[1, 3, 2]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[1, 3, 2]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[1,3,2]).list() # indirect doctest\n [[1, 2, 3], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n sage: Permutations(4, avoiding=[1,3,2]).list()\n [[4, 1, 2, 3],\n [4, 2, 1, 3],\n [4, 2, 3, 1],\n [4, 3, 1, 2],\n [4, 3, 2, 1],\n [3, 4, 1, 2],\n [3, 4, 2, 1],\n [2, 3, 4, 1],\n [3, 2, 4, 1],\n [1, 2, 3, 4],\n [2, 1, 3, 4],\n [2, 3, 1, 4],\n [3, 1, 2, 4],\n [3, 2, 1, 4]]\n '
if (self.n == 0):
return
elif (self.n < 3):
for p in itertools.permutations(range(1, (self.n + 1))):
(yield self.element_class(self, p, check=False))
return
elif (self.n == 3):
for p in itertools.permutations(range(1, (self.n + 1))):
if (p != (1, 3, 2)):
(yield self.element_class(self, p, check=False))
return
for right in StandardPermutations_avoiding_132((self.n - 1)):
(yield self.element_class(self, ([self.n] + list(right)), check=False))
for i in range(1, (self.n - 1)):
for left in StandardPermutations_avoiding_132(i):
for right in StandardPermutations_avoiding_132(((self.n - i) - 1)):
(yield self.element_class(self, (([(x + ((self.n - i) - 1)) for x in left] + [self.n]) + list(right)), check=False))
for left in StandardPermutations_avoiding_132((self.n - 1)):
(yield self.element_class(self, (list(left) + [self.n]), check=False))
|
class StandardPermutations_avoiding_123(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[2, 1, 3])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([1, 2, 3]),))
def cardinality(self) -> Integer:
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[1, 2, 3]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[1, 2, 3]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[1, 2, 3]).list() # indirect doctest\n [[1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n sage: Permutations(2, avoiding=[1, 2, 3]).list()\n [[1, 2], [2, 1]]\n sage: Permutations(3, avoiding=[1, 2, 3]).list()\n [[1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n '
if (self.n == 0):
return
elif (self.n < 3):
for p in itertools.permutations(range(1, (self.n + 1))):
(yield self.element_class(self, p, check=False))
return
elif (self.n == 3):
for p in itertools.permutations(range(1, (self.n + 1))):
if (p != (1, 2, 3)):
(yield self.element_class(self, p, check=False))
return
for p in StandardPermutations_avoiding_132(self.n):
m = (self.n + 1)
minima_pos = []
minima = []
for i in range(self.n):
if (p[i] < m):
minima_pos.append(i)
minima.append(p[i])
m = p[i]
new_p = []
non_minima = [x for x in range(self.n, 0, (- 1)) if (x not in minima)]
a = 0
b = 0
for i in range(self.n):
if (i in minima_pos):
new_p.append(minima[a])
a += 1
else:
new_p.append(non_minima[b])
b += 1
(yield self.element_class(self, new_p, check=False))
|
class StandardPermutations_avoiding_321(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[3, 2, 1])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([3, 2, 1]),))
def cardinality(self):
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[3, 2, 1]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[3, 2, 1]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[3, 2, 1]).list() # indirect doctest\n [[2, 3, 1], [3, 1, 2], [1, 3, 2], [2, 1, 3], [1, 2, 3]]\n '
for p in StandardPermutations_avoiding_123(self.n):
(yield self.element_class(self, p.reverse(), check=False))
|
class StandardPermutations_avoiding_231(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[2, 3, 1])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([2, 3, 1]),))
def cardinality(self):
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[2, 3, 1]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[2, 3, 1]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[2, 3, 1]).list()\n [[3, 2, 1], [3, 1, 2], [1, 3, 2], [2, 1, 3], [1, 2, 3]]\n '
for p in StandardPermutations_avoiding_132(self.n):
(yield self.element_class(self, p.reverse(), check=False))
|
class StandardPermutations_avoiding_312(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[3, 1, 2])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([3, 1, 2]),))
def cardinality(self):
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[3, 1, 2]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[3, 1, 2]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[3, 1, 2]).list()\n [[3, 2, 1], [2, 3, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3]]\n '
for p in StandardPermutations_avoiding_132(self.n):
(yield self.element_class(self, p.complement(), check=False))
|
class StandardPermutations_avoiding_213(StandardPermutations_avoiding_generic):
def __init__(self, n):
'\n TESTS::\n\n sage: P = Permutations(3, avoiding=[2, 1, 3])\n sage: TestSuite(P).run() # needs sage.combinat\n '
super().__init__(n, (Permutations()([2, 1, 3]),))
def cardinality(self):
'\n EXAMPLES::\n\n sage: Permutations(5, avoiding=[2, 1, 3]).cardinality()\n 42\n sage: len( Permutations(5, avoiding=[2, 1, 3]).list() )\n 42\n '
return catalan_number(self.n)
def __iter__(self):
'\n EXAMPLES::\n\n sage: Permutations(3, avoiding=[2, 1, 3]).list()\n [[1, 2, 3], [1, 3, 2], [3, 1, 2], [2, 3, 1], [3, 2, 1]]\n '
for p in StandardPermutations_avoiding_132(self.n):
(yield p.complement().reverse())
|
class PatternAvoider(GenericBacktracker):
def __init__(self, parent, patterns):
'\n EXAMPLES::\n\n sage: from sage.combinat.permutation import PatternAvoider\n sage: P = Permutations(4)\n sage: p = PatternAvoider(P, [[1,2,3]])\n sage: loads(dumps(p))\n <sage.combinat.permutation.PatternAvoider object at 0x...>\n '
GenericBacktracker.__init__(self, [], 1)
self._patterns = patterns
self._parent = parent
def _rec(self, obj, state):
'\n EXAMPLES::\n\n sage: from sage.combinat.permutation import PatternAvoider\n sage: P = Permutations(4)\n sage: p = PatternAvoider(P, [[1,2]])\n sage: list(p._rec([1], 2)) # needs sage.combinat\n [([2, 1], 3, False)]\n '
i = state
if (state != self._parent.n):
new_state = (state + 1)
yld = False
else:
new_state = None
yld = True
for pos in reversed(range((len(obj) + 1))):
new_obj = self._parent.element_class(self._parent, ((obj[:pos] + [i]) + obj[pos:]), check=False)
if all(((not new_obj.has_pattern(p)) for p in self._patterns)):
(yield (new_obj, new_state, yld))
|
class PermutationsNK(Permutations_setk):
'\n This exists solely for unpickling ``PermutationsNK`` objects created\n with Sage <= 6.3.\n '
def __setstate__(self, state):
'\n For unpickling old ``PermutationsNK`` objects.\n\n EXAMPLES::\n\n sage: loads(b"x\\x9cM\\x90\\xcdN\\xc30\\x10\\x84\\xd5B\\x0bM\\x81\\xf2\\xd3\\x1ex"\n ....: b"\\x03\\xb8\\xe4\\x80x\\x8bJ\\x16B\\xf2y\\xb5qV\\xa9\\x95\\xd8\\xce"\n ....: b"\\xda[$\\x0eHp\\xe0\\xc0[\\xe3\\xb4j\\xe1bi\\xfd\\xcd\\x8cg\\xfd96"\n ....: b"\\t\\x1b*Mp\\x95\\xf5(eO\\xd1m\\x05\\xc5\\x06\\x0f\\xbe-^\\xfe\\xc6"\n ....: b"\\xa4\\xd6\\x05\\x8f\\x1e\\xbfx\\xfc\\xc1\'\\x0f\\xba\\x00r\\x15\\xd5"\n ....: b"\\xb5\\xf5\\r\\x9f*\\xbd\\x04\\x13\\xfc\\x1bE\\x01G\\xb2\\t5xt\\xc4"\n ....: b"\\x13\\xa5\\xa7`j\\x14\\xe4\\xa9\\xd230(\\xd4\\x84\\xf8\\xceg\\x03"\n ....: b"\\x18$\\x89\\xcf\\x95\\x1e\\x83\\xe7\\xd9\\xbeH\\xccy\\xa9\\xb4>\\xeb"\n ....: b"(\\x16\\x0e[\\x82\\xc3\\xc0\\x85\\x1e=\\x7f\\xbf\\xf2\\\\\\xcf\\xa1!O"\n ....: b"\\x11%\\xc4\\xc4\\x17\\x83\\xbf\\xe5\\xcbM\\xc6O\\x19_\\xe9\\tT\\x98"\n ....: b"\\x88\\x17J/\\xa0\\xb7\\xa6\\xed\\x08r\\xb3\\x94w\\xe0\\xeb\\xf5(W"\n ....: b"\\xa5\\x8e\\x1cy\\x19*\'\\x89[\\x93s\\xf8F\\xe9U~\\xca\\x8a\\xc5\\xee"\n ....: b"\\xb8Kg\\x93\\xf0\\xad\\xd2\\xf7G\\xcb\\xa0\\x80\\x1eS\\xcaG\\xcc\\x17"\n ....: b"|\\xf7\\x93\\x03\\x0f>4\\xbb\\x8f\\xdb\\xd9\\x96\\xea\\x1f0\\x81\\xa2"\n ....: b"\\xa1=X\\xa9mU\\xfe\\x02=\\xaa\\x87\\x14")\n Permutations of the set [0, 1, 2, 3] of length 2\n '
self.__class__ = Permutations_setk
self.__init__(tuple(range(state['_n'])), state['_k'])
|
@richcmp_method
class PlanePartition(ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
'\n A plane partition.\n\n A *plane partition* is a stack of cubes in the positive orthant.\n\n INPUT:\n\n - ``PP`` -- a list of lists which represents a tableau\n - ``box_size`` -- (optional) a list ``[A, B, C]`` of 3 positive integers,\n where ``A``, ``B``, ``C`` are the lengths of the box in the `x`-axis,\n `y`-axis, `z`-axis, respectively; if this is not given, it is\n determined by the smallest box bounding ``PP``\n\n OUTPUT:\n\n The plane partition whose tableau representation is ``PP``.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP\n Plane partition [[4, 3, 3, 1], [2, 1, 1], [1, 1]]\n\n TESTS::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: TestSuite(PP).run()\n sage: hash(PP) # random\n '
@staticmethod
def __classcall_private__(cls, PP, box_size=None):
"\n Construct a plane partition with the appropriate parent.\n\n EXAMPLES::\n\n sage: p = PlanePartition([[2,1],[1]])\n sage: TestSuite(p).run()\n\n sage: p.parent()\n Plane partitions\n sage: p.category()\n Category of elements of Plane partitions\n sage: type(p)\n <class 'sage.combinat.plane_partition.PlanePartitions_all_with_category.element_class'>\n "
if (isinstance(PP, PlanePartition) and (box_size is None)):
return PP
pp = PlanePartitions(box_size=box_size)
return pp.element_class(pp, PP)
def __init__(self, parent, pp, check=True):
'\n Initialize a plane partition.\n\n TESTS::\n\n sage: a = PlanePartitions()([[2,1],[1]])\n sage: b = PlanePartitions([2,2,2])([[2,1],[1]])\n sage: c = PlanePartitions(4)([[2,1],[1]])\n sage: a == b\n True\n sage: a is b\n False\n sage: a == c\n True\n sage: a is c\n False\n '
if isinstance(pp, PlanePartition):
ClonableArray.__init__(self, parent, pp, check=False)
else:
pp = [list(row) for row in pp]
if pp:
for i in reversed(range(len(pp))):
while (pp[i] and (not pp[i][(- 1)])):
del pp[i][(- 1)]
if (not pp[i]):
pp.pop(i)
pp = [tuple(row) for row in pp]
ClonableArray.__init__(self, parent, pp, check=check)
if (self.parent()._box is None):
if pp:
self._max_x = len(pp)
self._max_y = len(pp[0])
self._max_z = pp[0][0]
else:
self._max_x = 0
self._max_y = 0
self._max_z = 0
else:
(self._max_x, self._max_y, self._max_z) = self.parent()._box
def __richcmp__(self, other, op):
'\n Compare ``self`` to ``other``.\n\n .. TODO::\n\n This overwrites the comparison check of\n :class:`~sage.structure.list_clone.ClonableArray`\n in order to circumvent the coercion framework.\n Eventually this should be solved more elegantly,\n for example along the lines of what was done for\n `k`-tableaux.\n\n For now, this compares two elements by their underlying\n defining lists.\n\n INPUT:\n\n - ``other`` -- the element that ``self`` is compared to\n\n OUTPUT:\n\n A boolean.\n\n TESTS::\n\n sage: t = PlanePartition([[2,1],[1]])\n sage: t == 0\n False\n sage: t == PlanePartitions(4)([[2,1],[1]])\n True\n\n sage: s = PlanePartition([[3,1],[1]])\n sage: s != []\n True\n\n sage: t < s\n True\n sage: s < t\n False\n sage: s > t\n True\n '
if isinstance(other, PlanePartition):
return self._richcmp_(other, op)
return richcmp(list(self), other, op)
def check(self):
'\n Check to see that ``self`` is a valid plane partition.\n\n EXAMPLES::\n\n sage: a = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: a.check()\n sage: b = PlanePartition([[1,2],[1]])\n Traceback (most recent call last):\n ...\n ValueError: not weakly decreasing along rows\n sage: c = PlanePartition([[1,1],[2]])\n Traceback (most recent call last):\n ...\n ValueError: not weakly decreasing along columns\n sage: d = PlanePartition([[2,-1],[-2]])\n Traceback (most recent call last):\n ...\n ValueError: entries not all nonnegative\n sage: e = PlanePartition([[3/2,1],[.5]])\n Traceback (most recent call last):\n ...\n ValueError: entries not all integers\n\n '
if (not all(((a in ZZ) for b in self for a in b))):
raise ValueError('entries not all integers')
for row in self:
if (not all(((c >= 0) for c in row))):
raise ValueError('entries not all nonnegative')
if (not all(((row[i] >= row[(i + 1)]) for i in range((len(row) - 1))))):
raise ValueError('not weakly decreasing along rows')
for (row, next) in zip(self, self[1:]):
if (not all(((row[c] >= next[c]) for c in range(len(next))))):
raise ValueError('not weakly decreasing along columns')
def _repr_(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n Plane partition [[4, 3, 3, 1], [2, 1, 1], [1, 1]]\n '
return 'Plane partition {}'.format([list(row) for row in self])
def to_tableau(self) -> Tableau:
'\n Return the tableau class of ``self``.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.to_tableau()\n [[4, 3, 3, 1], [2, 1, 1], [1, 1]]\n '
return Tableau(self)
def z_tableau(self, tableau=True) -> Tableau:
'\n Return the projection of ``self`` in the `z` direction.\n\n If ``tableau`` is set to ``False``, then only the list of lists\n consisting of the projection of boxes size onto the `xy`-plane\n is returned instead of a :class:`Tableau` object. This output will\n not have empty trailing rows or trailing zeros removed.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.z_tableau()\n [[4, 3, 3, 1], [2, 1, 1, 0], [1, 1, 0, 0]]\n '
Z = [[0 for i in range(self._max_y)] for j in range(self._max_x)]
for C in self.cells():
Z[C[0]][C[1]] += 1
if tableau:
return Tableau(Z)
return Z
def y_tableau(self, tableau=True) -> Tableau:
'\n Return the projection of ``self`` in the `y` direction.\n\n If ``tableau`` is set to ``False``, then only the list of lists\n consisting of the projection of boxes size onto the `xz`-plane\n is returned instead of a :class:`Tableau` object. This output will\n not have empty trailing rows or trailing zeros removed.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.y_tableau()\n [[4, 3, 2], [3, 1, 0], [3, 0, 0], [1, 0, 0]]\n '
Y = [[0 for i in range(self._max_x)] for j in range(self._max_z)]
for C in self.cells():
Y[C[2]][C[0]] += 1
if tableau:
return Tableau(Y)
return Y
def x_tableau(self, tableau=True) -> Tableau:
'\n Return the projection of ``self`` in the `x` direction.\n\n If ``tableau`` is set to ``False``, then only the list of lists\n consisting of the projection of boxes size onto the `yz`-plane\n is returned instead of a :class:`Tableau` object. This output will\n not have empty trailing rows or trailing zeros removed.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.x_tableau()\n [[3, 2, 1, 1], [3, 1, 1, 0], [2, 1, 1, 0], [1, 0, 0, 0]]\n '
X = [[0 for i in range(self._max_z)] for j in range(self._max_y)]
for C in self.cells():
X[C[1]][C[2]] += 1
if tableau:
return Tableau(X)
return X
def cells(self) -> list[list[int]]:
'\n Return the list of cells inside ``self``.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[3,1],[2]])\n sage: PP.cells()\n [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [1, 0, 0], [1, 0, 1]]\n '
L = []
for r in range(len(self)):
for c in range(len(self[r])):
for h in range(self[r][c]):
L.append([r, c, h])
return L
def number_of_boxes(self) -> Integer:
'\n Return the number of boxes in the plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[3,1],[2]])\n sage: PP.number_of_boxes()\n 6\n '
return sum((sum(row) for row in self))
def _repr_diagram(self, show_box=False, use_unicode=False) -> str:
'\n Return a string of the 3D diagram of ``self``.\n\n INPUT:\n\n - ``show_box`` -- boolean (default: ``False``); if ``True``,\n also shows the visible tiles on the `xy`-, `yz`-, `zx`-planes\n - ``use_unicode`` -- boolean (default: ``False``); use unicode\n\n OUTPUT:\n\n A string of the 3D diagram of the plane partition.\n\n EXAMPLES::\n\n sage: print(PlanePartition([[4,3,3,1],[2,1,1],[1,1]])._repr_diagram())\n __\n /\\_\\\n __/\\/_/\n __/\\_\\/\\_\\\n /\\_\\/_/\\/\\_\\\n \\/\\_\\_\\/\\/_/\n \\/_/\\_\\/_/\n \\/_/\\_\\\n \\/_/\n sage: print(PlanePartition([[4,3,3,1],[2,1,1],[1,1]])._repr_diagram(True))\n ______\n /_/_/\\_\\\n /_/_/\\/_/\\\n /_/\\_\\/\\_\\/\\\n /\\_\\/_/\\/\\_\\/\\\n \\/\\_\\_\\/\\/_/\\/\n \\/_/\\_\\/_/\\/\n \\_\\/_/\\_\\/\n \\_\\_\\/_/\n '
x = self._max_x
y = self._max_y
z = self._max_z
drawing = [[' ' for i in range((((2 * x) + y) + z))] for j in range(((y + z) + 1))]
hori = ('_' if use_unicode else '_')
down = ('╲' if use_unicode else '\\')
up = ('╱' if use_unicode else '/')
def superpose(l, c, letter):
exist = drawing[l][c]
if ((exist == ' ') or (exist == '_')):
drawing[l][c] = letter
def add_topside(i, j, k):
X = ((z + j) - k)
Y = ((((2 * x) - (2 * i)) + j) + k)
superpose(X, (Y - 2), hori)
superpose(X, (Y - 1), hori)
superpose((X + 1), (Y - 2), down)
superpose((X + 1), (Y - 1), hori)
superpose((X + 1), Y, down)
def add_rightside(i, j, k):
X = ((z + j) - k)
Y = ((((2 * x) - (2 * i)) + j) + k)
superpose((X - 1), (Y - 1), hori)
superpose((X - 1), Y, hori)
superpose(X, (Y - 2), up)
superpose(X, (Y - 1), hori)
superpose(X, Y, up)
def add_leftside(i, j, k):
X = ((z + j) - k)
Y = ((((2 * x) - (2 * i)) + j) + k)
superpose(X, Y, up)
superpose(X, (Y + 1), down)
superpose((X + 1), (Y + 1), up)
superpose((X + 1), Y, down)
tab = self.z_tableau()
for r in range(len(tab)):
for c in range(len(tab[r])):
if ((tab[r][c] > 0) or show_box):
add_topside(r, c, tab[r][c])
tab = self.y_tableau()
for r in range(len(tab)):
for c in range(len(tab[r])):
if ((self.y_tableau()[r][c] > 0) or show_box):
add_rightside(c, tab[r][c], r)
tab = self.x_tableau()
for r in range(len(tab)):
for c in range(len(tab[r])):
if ((self.x_tableau()[r][c] > 0) or show_box):
add_leftside(tab[r][c], r, c)
check = (not show_box)
while check:
if (drawing and all(((char == ' ') for char in drawing[(- 1)]))):
drawing.pop()
else:
check = False
if (not drawing):
return ('∅' if use_unicode else '')
if use_unicode:
return '\n'.join((''.join(row) for row in drawing))
return '\n'.join((''.join(row) for row in drawing))
def _ascii_art_(self):
'\n Return an ascii art representation of ``self``.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: ascii_art(PP)\n __\n /\\_\\\n __/\\/_/\n __/\\_\\/\\_\\\n /\\_\\/_/\\/\\_\\\n \\/\\_\\_\\/\\/_/\n \\/_/\\_\\/_/\n \\/_/\\_\\\n \\/_/\n '
from sage.typeset.ascii_art import AsciiArt
return AsciiArt(self._repr_diagram().splitlines(), baseline=0)
def _unicode_art_(self):
'\n Return a unicode representation of ``self``.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: unicode_art(PP)\n __\n ╱╲_╲\n __╱╲╱_╱\n __╱╲_╲╱╲_╲\n ╱╲_╲╱_╱╲╱╲_╲\n ╲╱╲_╲_╲╱╲╱_╱\n ╲╱_╱╲_╲╱_╱\n ╲╱_╱╲_╲\n ╲╱_╱\n '
from sage.typeset.unicode_art import UnicodeArt
return UnicodeArt(self._repr_diagram(use_unicode=True).splitlines(), baseline=0)
def pp(self, show_box=False):
'\n Return a pretty print of the plane partition.\n\n INPUT:\n\n - ``show_box`` -- boolean (default: ``False``); if ``True``,\n also shows the visible tiles on the `xy`-, `yz`-, `zx`-planes\n\n OUTPUT:\n\n A pretty print of the plane partition.\n\n EXAMPLES::\n\n sage: PlanePartition([[4,3,3,1],[2,1,1],[1,1]]).pp()\n __\n /\\_\\\n __/\\/_/\n __/\\_\\/\\_\\\n /\\_\\/_/\\/\\_\\\n \\/\\_\\_\\/\\/_/\n \\/_/\\_\\/_/\n \\/_/\\_\\\n \\/_/\n sage: PlanePartition([[4,3,3,1],[2,1,1],[1,1]]).pp(True)\n ______\n /_/_/\\_\\\n /_/_/\\/_/\\\n /_/\\_\\/\\_\\/\\\n /\\_\\/_/\\/\\_\\/\\\n \\/\\_\\_\\/\\/_/\\/\n \\/_/\\_\\/_/\\/\n \\_\\/_/\\_\\/\n \\_\\_\\/_/\n '
print(self._repr_diagram(show_box))
def _repr_svg_(self) -> str:
"\n Return the svg picture of a plane partition.\n\n This can be displayed by Jupyter.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[2, 1, 1], [1, 1]])\n sage: PP._repr_svg_() # needs sage.modules\n '<?xml...</g></svg>'\n "
colors = ['snow', 'tomato', 'steelblue']
resu = '<?xml version="1.0" standalone="no"?>'
resu += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
resu += '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
resu += '<svg xmlns="http://www.w3.org/2000/svg" '
resu += 'xmlns:xlink="http://www.w3.org/1999/xlink" width="300" viewBox='
resu1 = '<defs><polygon points="0, 0 -0.866, 0.5 0, 1 0.866, 0.5" '
resu1 += f'id="cz" style="fill:{colors[0]}"/>'
resu1 += '<polygon points="0, 0 0.866, 0.5 0.866, -0.5 0, -1" '
resu1 += f'id="cx" style="fill:{colors[1]}"/>'
resu1 += '<polygon points="0, 0 0, -1 -0.866, -0.5 -0.866, 0.5" '
resu1 += f'id="cy" style="fill:{colors[2]}"/></defs>'
resu1 += '<g style="stroke-width:0.01;stroke-linejoin:bevel; '
resu1 += 'stroke-linecap:butt; stroke:black; fill:red">'
vx = (- vector([0.866, (- 0.5)]))
vy = (- vector([(- 0.866), (- 0.5)]))
vz = (- vector([0, 1]))
(Nx, Ny, Nz) = self.bounding_box()
resu += ('"%.3f %.3f %.3f %.3f ">' % (((- 0.866) * Nx), (- Nz), ((0.866 * Nx) + (0.866 * Ny)), (Nz + (0.5 * (Nx + Ny)))))
resu += resu1
mat = self.z_tableau()
for i in range(Nx):
for j in range(Ny):
if mat[i][j]:
v = (((i * vx) + (j * vy)) + (mat[i][j] * vz))
resu += ('<use transform="translate(%.3f, %.3f)' % (v[0], v[1]))
resu += '" xlink:href="#cz" />'
mat = self.y_tableau()
for j in range(Nz):
for k in range(Nx):
if mat[j][k]:
v = (((j * vz) + (k * vx)) + (mat[j][k] * vy))
resu += ('<use transform="translate(%.3f, %.3f)' % (v[0], v[1]))
resu += '" xlink:href="#cy" />'
mat = self.x_tableau()
for k in range(Ny):
for i in range(Nz):
if mat[k][i]:
v = (((k * vy) + (i * vz)) + (mat[k][i] * vx))
resu += ('<use transform="translate(%.3f, %.3f)' % (v[0], v[1]))
resu += '" xlink:href="#cx" />'
return (resu + '</g></svg>')
def _latex_(self, show_box=False, colors=['white', 'lightgray', 'darkgray']) -> str:
'\n Return latex code for ``self``, which uses TikZ package to draw\n the plane partition.\n\n INPUT:\n\n - ``show_box`` -- boolean (default: ``False``); if ``True``,\n also shows the visible tiles on the `xy`-, `yz`-, `zx`-planes\n - ``colors`` -- (default: ``["white", "lightgray", "darkgray"]``)\n list ``[A, B, C]`` of 3 strings representing colors\n\n OUTPUT:\n\n Latex code for drawing the plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[1]])\n sage: latex(PP) # needs sage.graphs\n \\begin{tikzpicture}\n \\draw[fill=white,shift={(210:0)},shift={(-30:0)},shift={(90:1)}]\n (0,0)--(-30:1)--(0,-1)--(210:1)--(0,0);\n \\draw[fill=darkgray,shift={(210:0)},shift={(-30:1)},shift={(90:0)}]\n (0,0)--(210:1)--(150:1)--(0,1)--(0,0);\n \\draw[fill=lightgray,shift={(210:1)},shift={(-30:0)},shift={(90:0)}]\n (0,0)--(0,1)--(30:1)--(-30:1)--(0,0);\n \\end{tikzpicture}\n '
from sage.graphs.graph_latex import setup_latex_preamble
setup_latex_preamble()
ret = '\\begin{tikzpicture}\n'
def add_topside(i, j, k):
return '\\draw[fill={},shift={{(210:{})}},shift={{(-30:{})}},shift={{(90:{})}}]\n(0,0)--(-30:1)--(0,-1)--(210:1)--(0,0);\n'.format(colors[0], i, j, k)
def add_leftside(j, k, i):
return '\\draw[fill={},shift={{(210:{})}},shift={{(-30:{})}},shift={{(90:{})}}]\n(0,0)--(0,1)--(30:1)--(-30:1)--(0,0);\n'.format(colors[1], i, j, k)
def add_rightside(k, i, j):
return '\\draw[fill={},shift={{(210:{})}},shift={{(-30:{})}},shift={{(90:{})}}]\n(0,0)--(210:1)--(150:1)--(0,1)--(0,0);\n'.format(colors[2], i, j, k)
funcs = [add_topside, add_rightside, add_leftside]
tableaux = [self.z_tableau(), self.y_tableau(), self.x_tableau()]
for i in range(3):
f = funcs[i]
tab = tableaux[i]
for r in range(len(tab)):
for c in range(len(tab[r])):
if ((tab[r][c] > 0) or show_box):
ret += f(r, c, tab[r][c])
return (ret + '\\end{tikzpicture}')
def plot(self, show_box=False, colors=None):
'\n Return a plot of ``self``.\n\n INPUT:\n\n - ``show_box`` -- boolean (default: ``False``); if ``True``,\n also shows the visible tiles on the `xy`-, `yz`-, `zx`-planes\n - ``colors`` -- (default: ``["white", "lightgray", "darkgray"]``)\n list ``[A, B, C]`` of 3 strings representing colors\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.plot() # needs sage.plot\n Graphics object consisting of 27 graphics primitives\n '
from sage.functions.trig import cos, sin
from sage.plot.polygon import polygon
from sage.symbolic.constants import pi
from sage.plot.plot import plot
if (colors is None):
colors = ['white', 'lightgray', 'darkgray']
Uside = [[0, 0], [cos(((- pi) / 6)), sin(((- pi) / 6))], [0, (- 1)], [cos(((7 * pi) / 6)), sin(((7 * pi) / 6))]]
Lside = [[0, 0], [cos(((- pi) / 6)), sin(((- pi) / 6))], [cos((pi / 6)), sin((pi / 6))], [0, 1]]
Rside = [[0, 0], [0, 1], [cos(((5 * pi) / 6)), sin(((5 * pi) / 6))], [cos(((7 * pi) / 6)), sin(((7 * pi) / 6))]]
Xdir = [cos(((7 * pi) / 6)), sin(((7 * pi) / 6))]
Ydir = [cos(((- pi) / 6)), sin(((- pi) / 6))]
Zdir = [0, 1]
def move(side, i, j, k):
return [[(((P[0] + (i * Xdir[0])) + (j * Ydir[0])) + (k * Zdir[0])), (((P[1] + (i * Xdir[1])) + (j * Ydir[1])) + (k * Zdir[1]))] for P in side]
def add_topside(i, j, k):
return polygon(move(Uside, i, j, k), edgecolor='black', color=colors[0])
def add_leftside(i, j, k):
return polygon(move(Lside, i, j, k), edgecolor='black', color=colors[1])
def add_rightside(i, j, k):
return polygon(move(Rside, i, j, k), edgecolor='black', color=colors[2])
TP = plot([])
for r in range(len(self.z_tableau())):
for c in range(len(self.z_tableau()[r])):
if ((self.z_tableau()[r][c] > 0) or show_box):
TP += add_topside(r, c, self.z_tableau()[r][c])
for r in range(len(self.y_tableau())):
for c in range(len(self.y_tableau()[r])):
if ((self.y_tableau()[r][c] > 0) or show_box):
TP += add_rightside(c, self.y_tableau()[r][c], r)
for r in range(len(self.x_tableau())):
for c in range(len(self.x_tableau()[r])):
if ((self.x_tableau()[r][c] > 0) or show_box):
TP += add_leftside(self.x_tableau()[r][c], r, c)
TP.axes(show=False)
return TP
def contains(self, PP) -> bool:
'\n Return ``True`` if ``PP`` is a plane partition that fits\n inside ``self``.\n\n Specifically, ``self`` contains ``PP`` if, for all `i`, `j`,\n the height of ``PP`` at `ij` is less than or equal to the\n height of ``self`` at `ij`.\n\n EXAMPLES::\n\n sage: P1 = PlanePartition([[5,4,3], [3,2,2], [1]])\n sage: P2 = PlanePartition([[3,2], [1,1], [0,0], [0,0]])\n sage: P3 = PlanePartition([[5,5,5], [2,1,0]])\n sage: P1.contains(P2)\n True\n sage: P2.contains(P1)\n False\n sage: P1.contains(P3)\n False\n sage: P3.contains(P2)\n True\n '
if (not isinstance(PP, PlanePartition)):
PP = PlanePartition(PP)
if (len(self) < len(PP)):
return False
for (rowself, rowPP) in zip(self, PP):
if (len(rowself) < len(rowPP)):
return False
if any(((valself < valPP) for (valself, valPP) in zip(rowself, rowPP))):
return False
return True
def plot3d(self, colors=None):
'\n Return a 3D-plot of ``self``.\n\n INPUT:\n\n - ``colors`` -- (default: ``["white", "lightgray", "darkgray"]``)\n list ``[A, B, C]`` of 3 strings representing colors\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.plot3d() # needs sage.plot\n Graphics3d Object\n '
if (colors is None):
colors = ['white', 'lightgray', 'darkgray']
from sage.plot.plot3d.platonic import cube
return sum((cube(c, color=colors, frame_thickness=2, frame_color='black', frame=False) for c in self.cells()))
def complement(self, tableau_only=False) -> PP:
'\n Return the complement of ``self``.\n\n If the parent of ``self`` consists only of partitions inside a given\n box, then the complement is taken in this box. Otherwise, the\n complement is taken in the smallest box containing the plane partition.\n The empty plane partition with no box specified is its own complement.\n\n If ``tableau_only`` is set to ``True``, then only the tableau\n consisting of the projection of boxes size onto the `xy`-plane\n is returned instead of a :class:`PlanePartition`. This output will\n not have empty trailing rows or trailing zeros removed.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.complement()\n Plane partition [[4, 4, 3, 3], [4, 3, 3, 2], [3, 1, 1]]\n sage: PP.complement(True)\n [[4, 4, 3, 3], [4, 3, 3, 2], [3, 1, 1, 0]]\n '
A = self._max_x
B = self._max_y
C = self._max_z
T = [[C for i in range(B)] for j in range(A)]
z_tab = self.z_tableau()
for r in range(A):
for c in range(B):
T[((A - 1) - r)][((B - 1) - c)] = (C - z_tab[r][c])
if tableau_only:
return T
P = self.parent()
if (not P._box):
pp = PlanePartitions()
return pp.element_class(pp, T)
return P.element_class(P, T, check=False)
def transpose(self, tableau_only=False) -> PP:
'\n Return the transpose of ``self``.\n\n If ``tableau_only`` is set to ``True``, then only the tableau\n consisting of the projection of boxes size onto the `xy`-plane\n is returned instead of a :class:`PlanePartition`. This will\n not necessarily have trailing rows or trailing zeros removed.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.transpose()\n Plane partition [[4, 2, 1], [3, 1, 1], [3, 1], [1]]\n sage: PP.transpose(True)\n [[4, 2, 1], [3, 1, 1], [3, 1, 0], [1, 0, 0]]\n\n sage: PPP = PlanePartitions([1, 2, 3])\n sage: PP = PPP([[1, 1]])\n sage: PT = PP.transpose(); PT\n Plane partition [[1], [1]]\n sage: PT.parent()\n Plane partitions inside a 2 x 1 x 3 box\n '
T = [[0 for i in range(self._max_x)] for j in range(self._max_y)]
z_tab = self.z_tableau()
for r in range(len(z_tab)):
for c in range(len(z_tab[r])):
T[c][r] = z_tab[r][c]
P = self.parent()
if tableau_only:
return T
elif ((P._box is None) or (P._box[0] == P._box[1])):
return P.element_class(P, T, check=False)
new_box = (P._box[1], P._box[0], P._box[2])
newP = PlanePartitions(new_box, symmetry=P._symmetry)
return newP.element_class(newP, T)
def is_SPP(self) -> bool:
'\n Return whether ``self`` is a symmetric plane partition.\n\n A plane partition is symmetric if the corresponding tableau is\n symmetric about the diagonal.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_SPP()\n False\n sage: PP = PlanePartition([[3,3,2],[3,3,2],[2,2,2]])\n sage: PP.is_SPP()\n True\n sage: PP = PlanePartition([[3,2,1],[2,0,0]])\n sage: PP.is_SPP()\n False\n sage: PP = PlanePartition([[3,2,0],[2,0,0]])\n sage: PP.is_SPP()\n True\n sage: PP = PlanePartition([[3,2],[2,0],[1,0]])\n sage: PP.is_SPP()\n False\n sage: PP = PlanePartition([[3,2],[2,0],[0,0]])\n sage: PP.is_SPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_SPP()\n True\n '
if (not self):
return True
Z = self.z_tableau()
c1 = len(Z)
c2 = len(Z[0])
size = max(c1, c2)
T = [[0 for i in range(size)] for j in range(size)]
for i in range(c1):
for j in range(c2):
T[i][j] = Z[i][j]
return all(((T[r][c] == T[c][r]) for r in range(size) for c in range(r, size)))
def is_CSPP(self) -> bool:
'\n Return whether ``self`` is a cyclically symmetric plane partition.\n\n A plane partition is cyclically symmetric if its `x`, `y`, and `z`\n tableaux are all equal.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_CSPP()\n False\n sage: PP = PlanePartition([[3,2,2],[3,1,0],[1,1,0]])\n sage: PP.is_CSPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_CSPP()\n True\n '
if (self.z_tableau() == self.y_tableau()):
return True
return False
def is_TSPP(self) -> bool:
'\n Return whether ``self`` is a totally symmetric plane partition.\n\n A plane partition is totally symmetric if it is both symmetric and\n cyclically symmetric.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_TSPP()\n False\n sage: PP = PlanePartition([[3,3,3],[3,3,2],[3,2,1]])\n sage: PP.is_TSPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_TSPP()\n True\n '
return (self.is_CSPP() and self.is_SPP())
def is_SCPP(self) -> bool:
'\n Return whether ``self`` is a self-complementary plane partition.\n\n Note that the complement of a plane partition (and thus the property of\n being self-complementary) is dependent on the choice of a box that it is\n contained in. If no parent/bounding box is specified, the box is taken\n to be the smallest box that contains the plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_SCPP()\n False\n sage: PP = PlanePartition([[4,4,4,4],[4,4,2,0],[4,2,0,0],[0,0,0,0]])\n sage: PP.is_SCPP()\n False\n sage: PP = PlanePartitions([4,4,4])([[4,4,4,4],[4,4,2,0],[4,2,0,0],[0,0,0,0]])\n sage: PP.is_SCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_SCPP()\n True\n '
return (self.z_tableau(tableau=False) == self.complement(tableau_only=True))
def is_TCPP(self) -> bool:
'\n Return whether ``self`` is a transpose-complementary plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_TCPP()\n False\n sage: PP = PlanePartition([[4,4,3,2],[4,4,2,1],[4,2,0,0],[2,0,0,0]])\n sage: PP.is_TCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_TCPP()\n True\n '
return (self.transpose(True) == self.complement(True))
def is_SSCPP(self) -> bool:
'\n Return whether ``self`` is a symmetric, self-complementary\n plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_SSCPP()\n False\n sage: PP = PlanePartition([[4,3,3,2],[3,2,2,1],[3,2,2,1],[2,1,1,0]])\n sage: PP.is_SSCPP()\n True\n sage: PP = PlanePartition([[2,1],[1,0]])\n sage: PP.is_SSCPP()\n True\n sage: PP = PlanePartition([[4,3,2],[3,2,1],[2,1,0]])\n sage: PP.is_SSCPP()\n True\n sage: PP = PlanePartition([[4,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,0]])\n sage: PP.is_SSCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_SSCPP()\n True\n '
return (self.is_SPP() and self.is_SCPP())
def is_CSTCPP(self) -> bool:
'\n Return whether ``self`` is a cyclically symmetric and\n transpose-complementary plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_CSTCPP()\n False\n sage: PP = PlanePartition([[4,4,3,2],[4,3,2,1],[3,2,1,0],[2,1,0,0]])\n sage: PP.is_CSTCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_CSTCPP()\n True\n '
return (self.is_CSPP() and self.is_TCPP())
def is_CSSCPP(self) -> bool:
'\n Return whether ``self`` is a cyclically symmetric and\n self-complementary plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_CSSCPP()\n False\n sage: PP = PlanePartition([[4,4,4,1],[3,3,2,1],[3,2,1,1],[3,0,0,0]])\n sage: PP.is_CSSCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_CSSCPP()\n True\n '
return (self.is_CSPP() and self.is_SCPP())
def is_TSSCPP(self) -> bool:
'\n Return whether ``self`` is a totally symmetric self-complementary\n plane partition.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])\n sage: PP.is_TSSCPP()\n False\n sage: PP = PlanePartition([[4,4,3,2],[4,3,2,1],[3,2,1,0],[2,1,0,0]])\n sage: PP.is_TSSCPP()\n True\n\n TESTS::\n\n sage: PlanePartition([]).is_TSSCPP()\n True\n '
return (self.is_TSPP() and self.is_SCPP())
def to_order_ideal(self):
'\n Return the order ideal corresponding to ``self``.\n\n .. TODO::\n\n As many families of symmetric plane partitions are in bijection\n with order ideals in an associated poset, this function could\n feasibly have options to send symmetric plane partitions\n to the associated order ideal in that poset, instead.\n\n EXAMPLES::\n\n sage: PlanePartition([[3,2,1],[2,2],[2]]).to_order_ideal() # needs sage.graphs sage.modules\n [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 2, 0),\n (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (2, 0, 0), (2, 0, 1)]\n sage: PlanePartition([[2,1],[1],[1]]).to_order_ideal() # needs sage.graphs sage.modules\n [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (2, 0, 0)]\n '
from sage.combinat.posets.poset_examples import posets
(a, b, c) = (self._max_x, self._max_y, self._max_z)
Q = posets.ProductOfChains([a, b, c])
count = 0
generate = []
for (i, row) in enumerate(self):
for (j, val) in enumerate(row):
if (val > 0):
generate.append((i, j, (val - 1)))
count += 1
oi = Q.order_ideal(generate)
return oi
def maximal_boxes(self) -> list:
'\n Return the coordinates of the maximal boxes of ``self``.\n\n The maximal boxes of a plane partitions are the boxes that can be\n removed from a plane partition and still yield a valid plane partition.\n\n EXAMPLES::\n\n sage: sorted(PlanePartition([[3,2,1],[2,2],[2]]).maximal_boxes())\n [[0, 0, 2], [0, 2, 0], [1, 1, 1], [2, 0, 1]]\n sage: sorted(PlanePartition([[2,1],[1],[1]]).maximal_boxes())\n [[0, 0, 1], [0, 1, 0], [2, 0, 0]]\n '
generate = []
for (i, row) in enumerate(self):
for (j, entry) in enumerate(row):
if (((i == (len(self) - 1)) or ((len(self[(i + 1)]) - 1) < j) or (self[(i + 1)][j] < entry)) and ((j == (len(row) - 1)) or (row[(j + 1)] < entry))):
generate.append([i, j, (entry - 1)])
return generate
def cyclically_rotate(self, preserve_parent=False) -> PP:
'\n Return the cyclic rotation of ``self``.\n\n By default, if the parent of ``self`` consists of plane\n partitions inside an `a \\times b \\times c` box, the result\n will have a parent consisting of partitions inside\n a `c \\times a \\times b` box, unless the optional parameter\n ``preserve_parent`` is set to ``True``. Enabling this setting\n may give an element that is **not** an element of its parent.\n\n EXAMPLES::\n\n sage: PlanePartition([[3,2,1],[2,2],[2]]).cyclically_rotate()\n Plane partition [[3, 3, 1], [2, 2], [1]]\n sage: PP = PlanePartition([[4,1],[1],[1]])\n sage: PP.cyclically_rotate()\n Plane partition [[3, 1, 1, 1], [1]]\n sage: PP == PP.cyclically_rotate().cyclically_rotate().cyclically_rotate()\n True\n\n sage: # needs sage.graphs sage.modules\n sage: PP = PlanePartitions([4,3,2]).random_element()\n sage: PP.cyclically_rotate().parent()\n Plane partitions inside a 2 x 4 x 3 box\n sage: PP = PlanePartitions([3,4,2])([[2,2,2,2],[2,2,2,2],[2,2,2,2]])\n sage: PP_rotated = PP.cyclically_rotate(preserve_parent=True)\n sage: PP_rotated in PP_rotated.parent()\n False\n '
b = self._max_y
c = self._max_z
new_antichain = []
for elem in self.maximal_boxes():
new = (elem[1], elem[2], elem[0])
new_antichain.append(new)
pp_matrix = [([0] * c) for i in range(b)]
for box in new_antichain:
y = box[0]
z = box[1]
x = box[2]
pp_matrix[y][z] = (x + 1)
if new_antichain:
for i in range(b):
i = (b - (i + 1))
for j in range(c):
j = (c - (j + 1))
if (pp_matrix[i][j] == 0):
iValue = 0
jValue = 0
if (i < (b - 1)):
iValue = pp_matrix[(i + 1)][j]
if (j < (c - 1)):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
P = self.parent()
if ((P._box is None) or preserve_parent or (P._box[0] == P._box[1] == P._box[2])):
return P.element_class(P, pp_matrix, check=preserve_parent)
new_box = (P._box[2], P._box[0], P._box[1])
newP = PlanePartitions(new_box, symmetry=P._symmetry)
return newP.element_class(newP, pp_matrix)
def bounding_box(self):
'\n Return the smallest box `(a, b, c)` that ``self`` is contained in.\n\n EXAMPLES::\n\n sage: PP = PlanePartition([[5,2,1,1], [2,2], [2]])\n sage: PP.bounding_box()\n (3, 4, 5)\n '
if (not self):
return (0, 0, 0)
return (len(self), len(self[0]), self[0][0])
|
class PlanePartitions(UniqueRepresentation, Parent):
"\n Plane partitions.\n\n ``PlanePartitions()`` returns the class of all plane partitions.\n\n ``PlanePartitions(n)`` return the class of all plane partitions with\n precisely `n` boxes.\n\n ``PlanePartitions([a, b, c])`` returns the class of plane partitions\n that fit inside an `a \\times b \\times c` box.\n\n ``PlanePartitions([a, b, c])`` has the optional keyword ``symmetry``, which\n restricts the plane partitions inside a box of the specified size satisfying\n certain symmetry conditions.\n\n - ``symmetry='SPP'`` gives the class of symmetric plane partitions. which\n is all plane partitions fixed under reflection across the diagonal.\n Requires that `a = b`.\n\n - ``symmetry='CSPP'`` gives the class of cyclic plane partitions, which\n is all plane partitions fixed under cyclic rotation of coordinates.\n Requires that `a = b = c`.\n\n - ``symmetry='TSPP'`` gives the class of totally symmetric plane partitions,\n which is all plane partitions fixed under any interchanging of coordinates.\n Requires that `a = b = c`.\n\n - ``symmetry='SCPP'`` gives the class of self-complementary plane partitions.\n which is all plane partitions that are equal to their own complement\n in the specified box. Requires at least one of `a,b,c` be even.\n\n - ``symmetry='TCPP'`` gives the class of transpose complement plane\n partitions, which is all plane partitions whose complement in the box\n of the specified size is equal to their transpose. Requires `a = b` and\n at least one of `a, b, c` be even.\n\n - ``symmetry='SSCPP'`` gives the class of symmetric self-complementary\n plane partitions, which is all plane partitions that are both\n symmetric and self-complementary. Requires `a = b` and at least one of\n `a, b, c` be even.\n\n - ``symmetry='CSTCPP'`` gives the class of cyclically symmetric transpose\n complement plane partitions, which is all plane partitions that are\n both symmetric and equal to the transpose of their complement. Requires\n `a = b = c`.\n\n - ``symmetry='CSSCPP'`` gives the class of cyclically symmetric\n self-complementary plane partitions, which is all plane partitions that\n are both cyclically symmetric and self-complementary. Requires `a = b = c`\n and all `a, b, c` be even.\n\n - ``symmetry='TSSCPP'`` gives the class of totally symmetric\n self-complementary plane partitions, which is all plane partitions that\n are totally symmetric and also self-complementary. Requires `a = b = c`\n and all `a, b, c` be even.\n\n EXAMPLES:\n\n If no arguments are passed, then the class of all plane partitions\n is returned::\n\n sage: PlanePartitions()\n Plane partitions\n sage: [[2,1],[1]] in PlanePartitions()\n True\n\n If an integer `n` is passed, then the class of plane partitions of `n`\n is returned::\n\n sage: PlanePartitions(3)\n Plane partitions of size 3\n sage: PlanePartitions(3).list()\n [Plane partition [[3]],\n Plane partition [[2, 1]],\n Plane partition [[1, 1, 1]],\n Plane partition [[2], [1]],\n Plane partition [[1, 1], [1]],\n Plane partition [[1], [1], [1]]]\n\n If a three-element tuple or list `[a,b,c]` is passed, then the class of all\n plane partitions that fit inside and `a \\times b \\times c` box is returned::\n\n sage: PlanePartitions([2,2,2])\n Plane partitions inside a 2 x 2 x 2 box\n sage: [[2,1],[1]] in PlanePartitions([2,2,2])\n True\n\n If an additional keyword ``symmetry`` is pass along with a three-element\n tuple or list `[a, b,c ]`, then the class of all plane partitions that fit\n inside an `a \\times b \\times c` box with the specified symmetry is returned::\n\n sage: PlanePartitions([2,2,2], symmetry='CSPP')\n Cyclically symmetric plane partitions inside a 2 x 2 x 2 box\n sage: [[2,1],[1]] in PlanePartitions([2,2,2], symmetry='CSPP')\n True\n\n .. SEEALSO::\n\n - :class:`PlanePartition`\n - :class:`PlanePartitions_all`\n - :class:`PlanePartitions_n`\n - :class:`PlanePartitions_box`\n - :class:`PlanePartitions_SPP`\n - :class:`PlanePartitions_CSPP`\n - :class:`PlanePartitions_TSPP`\n - :class:`PlanePartitions_SCPP`\n - :class:`PlanePartitions_TCPP`\n - :class:`PlanePartitions_SSCPP`\n - :class:`PlanePartitions_CSTCPP`\n - :class:`PlanePartitions_CSSCPP`\n - :class:`PlanePartitions_TSSCPP`\n "
@staticmethod
def __classcall_private__(cls, *args, **kwds):
"\n Return the appropriate parent based on arguments.\n\n See the documentation for :class:`PlanePartitions` for more information.\n\n TESTS::\n\n sage: PlanePartitions()\n Plane partitions\n sage: PlanePartitions([3,3,3])\n Plane partitions inside a 3 x 3 x 3 box\n sage: PlanePartitions(3)\n Plane partitions of size 3\n sage: PlanePartitions([4,4,4], symmetry='TSSCPP')\n Totally symmetric self-complementary plane partitions inside a 4 x 4 x 4 box\n sage: PlanePartitions(4, symmetry='TSSCPP')\n Traceback (most recent call last):\n ...\n ValueError: the number of boxes may only be specified if no symmetry is required\n "
symmetry = kwds.get('symmetry', None)
box_size = kwds.get('box_size', None)
if ((not args) and (symmetry is None) and (box_size is None)):
return PlanePartitions_all()
if (args and (box_size is None)):
if isinstance(args[0], (int, Integer)):
if (symmetry is None):
return PlanePartitions_n(args[0])
else:
raise ValueError('the number of boxes may only be specified if no symmetry is required')
box_size = args[0]
box_size = tuple(box_size)
if (symmetry is None):
return PlanePartitions_box(box_size)
elif (symmetry == 'SPP'):
return PlanePartitions_SPP(box_size)
elif (symmetry == 'CSPP'):
return PlanePartitions_CSPP(box_size)
elif (symmetry == 'TSPP'):
return PlanePartitions_TSPP(box_size)
elif (symmetry == 'SCPP'):
return PlanePartitions_SCPP(box_size)
elif (symmetry == 'TCPP'):
return PlanePartitions_TCPP(box_size)
elif (symmetry == 'SSCPP'):
return PlanePartitions_SSCPP(box_size)
elif (symmetry == 'CSTCPP'):
return PlanePartitions_CSTCPP(box_size)
elif (symmetry == 'CSSCPP'):
return PlanePartitions_CSSCPP(box_size)
elif (symmetry == 'TSSCPP'):
return PlanePartitions_TSSCPP(box_size)
raise ValueError('invalid symmetry class option')
def __init__(self, box_size=None, symmetry=None, category=None):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions(box_size=[2,2,1])\n sage: TestSuite(PP).run() # needs sage.modules\n '
if ((box_size is not None) and (len(box_size) != 3)):
raise ValueError('invalid box size')
self._box = box_size
self._symmetry = symmetry
Parent.__init__(self, category=category)
Element = PlanePartition
def __contains__(self, pp):
'\n Check to see that ``pp`` is a valid plane partition.\n\n EXAMPLES::\n\n sage: [[3,2,1],[2,1]] in PlanePartitions()\n True\n sage: [[3,2,1],[1,2]] in PlanePartitions()\n False\n sage: [[3,2,1],[3,3]] in PlanePartitions()\n False\n '
if isinstance(pp, PlanePartition):
return True
if isinstance(pp, (list, tuple)):
if (not pp):
return True
if (not all(((a in ZZ) for b in pp for a in b))):
return False
for row in pp:
if (not all(((c >= 0) for c in row))):
return False
if (not all(((row[i] >= row[(i + 1)]) for i in range((len(row) - 1))))):
return False
for (row, nxt) in zip(pp, pp[1:]):
if (not all(((row[c] >= nxt[c]) for c in range(len(nxt))))):
return False
return True
return False
def box(self) -> tuple:
'\n Return the size of the box of the plane partition of ``self``\n is contained in.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,3,5])\n sage: P.box()\n (4, 3, 5)\n\n sage: PP = PlanePartitions()\n sage: PP.box() is None\n True\n '
return self._box
def symmetry(self) -> str:
"\n Return the symmetry class of ``self``.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: PP.symmetry()\n 'SPP'\n sage: PP = PlanePartitions()\n sage: PP.symmetry() is None\n True\n "
return self._symmetry
|
class PlanePartitions_all(PlanePartitions, DisjointUnionEnumeratedSets):
'\n All plane partitions.\n '
def __init__(self):
'\n Initializes the class of all plane partitions.\n\n .. WARNING::\n\n Input is not checked; please use :class:`PlanePartitions` to\n ensure the options are properly parsed.\n\n TESTS::\n\n sage: from sage.combinat.plane_partition import PlanePartitions_all\n sage: P = PlanePartitions_all()\n sage: TestSuite(P).run()\n '
self._box = None
self._symmetry = None
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), PlanePartitions_n), facade=True, keepkey=False)
def _repr_(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PlanePartitions()\n Plane partitions\n '
return 'Plane partitions'
def an_element(self):
'\n Return a particular element of the class.\n\n TESTS::\n\n sage: P = PlanePartitions()\n sage: P.an_element()\n Plane partition [[2, 1], [1]]\n '
return self.element_class(self, [[2, 1], [1]])
|
class PlanePartitions_box(PlanePartitions):
'\n All plane partitions that fit inside a box of a specified size.\n\n By convention, a plane partition in an `a \\times b \\times c` box\n will have at most `a` rows, of lengths at most `b`, with entries\n at most `c`.\n '
def __init__(self, box_size):
'\n Initializes the class of plane partitions that fit in a box of a\n specified size.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([4,3,2])\n sage: TestSuite(PP).run() # long time # needs sage.modules\n '
super().__init__(box_size, category=FiniteEnumeratedSets())
def _repr_(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PlanePartitions([4,3,2])\n Plane partitions inside a 4 x 3 x 2 box\n '
return 'Plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __contains__(self, x):
'\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions([2,2,2])\n True\n sage: [[3,1],[1]] in PlanePartitions([2,2,2])\n False\n sage: [[2,1],[1],[1]] in PlanePartitions([2,2,2])\n False\n sage: [[2,1,1],[1]] in PlanePartitions([2,2,2])\n False\n '
if (len(x) == 0):
return True
return (PlanePartitions.__contains__(self, x) and (len(x) <= self._box[0]) and (len(x[0]) <= self._box[1]) and (x[0][0] <= self._box[2]))
def to_poset(self):
'\n Return the product of three chains poset, whose order ideals are\n naturally in bijection with plane partitions inside a box.\n\n EXAMPLES::\n\n sage: PlanePartitions([2,2,2]).to_poset() # needs sage.graphs sage.modules\n Finite lattice containing 8 elements\n '
a = self._box[0]
b = self._box[1]
c = self._box[2]
from sage.combinat.posets.poset_examples import posets
return posets.ProductOfChains([a, b, c])
def from_order_ideal(self, I) -> PP:
'\n Return the plane partition corresponding to an order ideal in the\n poset given in :meth:`to_poset`.\n\n EXAMPLES::\n\n sage: I = [(1, 0, 0), (1, 0, 1), (1, 1, 0), (0, 1, 0),\n ....: (0, 0, 0), (0, 0, 1), (0, 1, 1)]\n sage: PlanePartitions([2,2,2]).from_order_ideal(I) # needs sage.graphs sage.modules\n Plane partition [[2, 2], [2, 1]]\n '
return self.from_antichain(self.to_poset().order_ideal_generators(I))
def from_antichain(self, A) -> PP:
'\n Return the plane partition corresponding to an antichain in the poset\n given in :meth:`to_poset`.\n\n EXAMPLES::\n\n sage: A = [(1,0,1), (0,1,1), (1,1,0)]\n sage: PlanePartitions([2,2,2]).from_antichain(A)\n Plane partition [[2, 2], [2, 1]]\n '
a = self._box[0]
b = self._box[1]
pp_matrix = [([0] * b) for i in range(a)]
for ac in A:
x = ac[0]
y = ac[1]
z = ac[2]
pp_matrix[x][y] = (z + 1)
if A:
for i in range(a):
i = (a - (i + 1))
for j in range(b):
j = (b - (j + 1))
if (pp_matrix[i][j] == 0):
iValue = 0
jValue = 0
if (i < (a - 1)):
iValue = pp_matrix[(i + 1)][j]
if (j < (b - 1)):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
return self.element_class(self, pp_matrix)
def __iter__(self) -> Iterator:
'\n Iterate over all partitions that fit inside a box.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([1,2,1])) # needs sage.modules\n [Plane partition [], Plane partition [[1]], Plane partition [[1, 1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality()\n ....: for b in cartesian_product([range(4)]*3)\n ....: if (PP := PlanePartitions(b)))\n True\n '
A = self._box[0]
B = self._box[1]
C = self._box[2]
if (not A):
(yield self.element_class(self, [], check=False))
return
from sage.combinat.tableau import SemistandardTableaux as SST
for T in SST([B for i in range(A)], max_entry=(C + A)):
PP = [[0 for _ in range(B)] for _ in range(A)]
for r in range(A):
for c in range(B):
PP[((A - 1) - r)][((B - 1) - c)] = ((T[r][c] - r) - 1)
(yield self.element_class(self, PP, check=False))
def cardinality(self) -> Integer:
'\n Return the cardinality of ``self``.\n\n The number of plane partitions inside an `a \\times b \\times c`\n box is equal to\n\n .. MATH::\n\n \\prod_{i=1}^{a} \\prod_{j=1}^{b} \\prod_{k=1}^{c}\n \\frac{i+j+k-1}{i+j+k-2}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,3,5])\n sage: P.cardinality()\n 116424\n '
A = self._box[0]
B = self._box[1]
C = self._box[2]
return Integer((prod(((((i + j) + k) - 1) for i in range(1, (A + 1)) for j in range(1, (B + 1)) for k in range(1, (C + 1)))) // prod(((((i + j) + k) - 2) for i in range(1, (A + 1)) for j in range(1, (B + 1)) for k in range(1, (C + 1))))))
def random_element(self) -> PP:
'\n Return a uniformly random plane partition inside a box.\n\n ALGORITHM:\n\n This uses the\n :meth:`~sage.combinat.posets.posets.FinitePoset.random_order_ideal`\n method and the natural bijection with plane partitions.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,3,5])\n sage: P.random_element() # random # needs sage.graphs sage.modules\n Plane partition [[4, 3, 3], [4], [2]]\n '
Z = self.from_order_ideal(self.to_poset().random_order_ideal())
return self.element_class(self, Z, check=False)
|
class PlanePartitions_n(PlanePartitions):
'\n Plane partitions with a fixed number of boxes.\n '
def __init__(self, n):
"\n Initializes the class of plane partitions with ``n`` boxes.\n\n .. WARNING::\n\n Input is not checked; please use :class:`PlanePartitions` to\n ensure the options are properly parsed.\n\n TESTS::\n\n sage: PP = PlanePartitions(4)\n sage: type(PP)\n <class 'sage.combinat.plane_partition.PlanePartitions_n_with_category'>\n sage: TestSuite(PP).run()\n "
super().__init__(category=FiniteEnumeratedSets())
self._n = n
def _repr_(self) -> str:
'\n TESTS::\n\n sage: PlanePartitions(3)\n Plane partitions of size 3\n '
return 'Plane partitions of size {}'.format(self._n)
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions(4)\n True\n sage: [[2,1],[1]] in PlanePartitions(3)\n False\n '
return (PlanePartitions.__contains__(self, x) and (PlanePartition(x).number_of_boxes() == self._n))
def __iter__(self) -> Iterator:
'\n Iterate over all plane partitions of a fixed size.\n\n EXAMPLES::\n\n sage: list(PlanePartitions(2))\n [Plane partition [[2]], Plane partition [[1, 1]], Plane partition [[1], [1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality() for n in range(9) if (PP := PlanePartitions(n)))\n True\n '
from sage.combinat.partition import Partitions
def P_in_shape_iter(n, la):
if ((n < 0) or (sum(la) < n)):
return
if (n == 0):
(yield [])
return
if (len(la) == 1):
if (la[0] >= n):
(yield [n])
return
if (sum(la) == n):
(yield la)
return
for mu_0 in range(min(n, la[0]), 0, (- 1)):
new_la = [min(mu_0, la[i]) for i in range(1, len(la))]
for mu in P_in_shape_iter((n - mu_0), new_la):
(yield ([mu_0] + mu))
def PP_first_row_iter(n, la):
m = (n - sum(la))
if (m < 0):
return
if (m == 0):
(yield [la])
return
for k in range(m, 0, (- 1)):
for mu in P_in_shape_iter(k, la):
for PP in PP_first_row_iter(m, mu):
(yield ([la] + PP))
n = self._n
if (not n):
(yield PlanePartition([]))
return
for m in range(n, 0, (- 1)):
for la in Partitions(m):
for a in PP_first_row_iter(n, la):
(yield self.element_class(self, a, check=False))
def cardinality(self) -> Integer:
'\n Return the number of plane partitions with ``n`` boxes.\n\n Calculated using the recurrence relation\n\n .. MATH::\n\n PL(n) = \\sum_{k=1}^n PL(n-k) \\sigma_2(k),\n\n where `\\sigma_k(n)` is the sum of the `k`-th powers of\n divisors of `n`.\n\n EXAMPLES::\n\n sage: P = PlanePartitions(17)\n sage: P.cardinality()\n 18334\n\n '
PPn = [1]
for i in range(1, (1 + self._n)):
nextPPn = (sum(((PPn[(i - k)] * Sigma()(k, 2)) for k in range(1, (i + 1)))) / i)
PPn.append(nextPPn)
return Integer(PPn[(- 1)])
|
class PlanePartitions_SPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n symmetric.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: TestSuite(PP).run() # needs sage.graphs sage.modules\n sage: PlanePartitions([4,3,2], symmetry='SPP')\n Traceback (most recent call last):\n ...\n ValueError: x and y dimensions (4 and 3) must be equal\n "
if (box_size[0] != box_size[1]):
raise ValueError('x and y dimensions ({} and {}) must be equal'.format(box_size[0], box_size[1]))
super().__init__(box_size, 'SPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([3,3,2], symmetry='SPP')\n Symmetric plane partitions inside a 3 x 3 x 2 box\n "
return 'Symmetric plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __contains__(self, x) -> bool:
"\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions([2,2,2], symmetry='SPP')\n True\n sage: [[2,1],[1]] in PlanePartitions([1,1,1], symmetry='SPP')\n False\n sage: [[2,1],[2]] in PlanePartitions([2,2,2], symmetry='SPP')\n False\n "
P = PlanePartition(x)
max = (P._max_x, P._max_y, P._max_z)
return (PlanePartitions.__contains__(self, x) and P.is_SPP() and all(((a <= b) for (a, b) in zip(max, self._box))))
def to_poset(self):
"\n Return a poset whose order ideals are in bijection with\n symmetric plane partitions.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: PP.to_poset() # needs sage.graphs\n Finite poset containing 12 elements\n sage: PP.to_poset().order_ideals_lattice().cardinality() == PP.cardinality() # needs sage.graphs sage.modules sage.rings.finite_rings\n True\n "
a = self._box[0]
c = self._box[2]
def comp(x, y):
return all(((a <= b) for (a, b) in zip(x, y)))
pl = [(x, y, z) for x in range(a) for y in range((x + 1)) for z in range(c)]
from sage.combinat.posets.posets import Poset
return Poset((pl, comp))
def from_order_ideal(self, I) -> PP:
"\n Return the symmetric plane partition corresponding to an order ideal\n in the poset given in :meth:`to_poset()`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: I = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (2, 0, 0)]\n sage: PP.from_order_ideal(I) # needs sage.graphs\n Plane partition [[1, 1, 1], [1, 1], [1]]\n "
return self.from_antichain(self.to_poset().order_ideal_generators(I))
def from_antichain(self, A) -> PP:
"\n Return the symmetric plane partition corresponding to an antichain\n in the poset given in :meth:`to_poset()`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: A = [(2, 2, 0), (1, 0, 1), (1, 1, 0)]\n sage: PP.from_antichain(A)\n Plane partition [[2, 2, 1], [2, 1, 1], [1, 1, 1]]\n "
a = self._box[0]
b = self._box[1]
pp_matrix = [([0] * b) for i in range(a)]
for ac in A:
x = ac[0]
y = ac[1]
z = ac[2]
pp_matrix[x][y] = (z + 1)
if A:
for i in range(a):
i = (a - (i + 1))
for j in range(b):
j = (b - (j + 1))
if ((pp_matrix[i][j] == 0) and (i >= j)):
iValue = 0
jValue = 0
if (i < (a - 1)):
iValue = pp_matrix[(i + 1)][j]
if (j < (b - 1)):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
elif (j > i):
pp_matrix[i][j] = pp_matrix[j][i]
return self.element_class(self, pp_matrix)
def __iter__(self) -> Iterator:
"\n Iterate over all symmetric plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([2,2,1], symmetry='SPP')) # needs sage.graphs sage.modules sage.rings.finite_rings\n [Plane partition [],\n Plane partition [[1, 1], [1, 1]],\n Plane partition [[1, 1], [1]],\n Plane partition [[1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality()\n ....: for a, b in cartesian_product([range(4)]*2)\n ....: if (PP := PlanePartitions([a, a, b], symmetry='SPP')))\n True\n "
for acl in self.to_poset().antichains_iterator():
(yield self.from_antichain(acl))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of symmetric plane partitions inside an `a \\times a \\times b`\n box is equal to\n\n .. MATH::\n\n \\left(\\prod_{i=1}^{a} \\frac{2i + b - 1}{2i - 1}\\right)\n \\left(\\prod_{1 \\leq i < j \\leq a} \\frac{i+j+b-1}{i+j-1}\\right).\n\n EXAMPLES::\n\n sage: P = PlanePartitions([3,3,2], symmetry='SPP')\n sage: P.cardinality()\n 35\n "
a = self._box[0]
c = self._box[2]
left_prod_num = prod(((((2 * i) + c) - 1) for i in range(1, (a + 1))))
left_prod_den = prod((((2 * i) - 1) for i in range(1, (a + 1))))
right_prod_num = prod(((((i + j) + c) - 1) for j in range(1, (a + 1)) for i in range(1, j)))
right_prod_den = prod((((i + j) - 1) for j in range(1, (a + 1)) for i in range(1, j)))
return Integer((((left_prod_num * right_prod_num) // left_prod_den) // right_prod_den))
def random_element(self) -> PP:
"\n Return a uniformly random element of ``self``.\n\n ALGORITHM:\n\n This uses the\n :meth:`~sage.combinat.posets.posets.FinitePoset.random_order_ideal`\n method and the natural bijection between symmetric plane partitions\n and order ideals in an associated poset.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='SPP')\n sage: PP.random_element() # random # needs sage.graphs\n Plane partition [[2, 2, 2], [2, 2], [2]]\n "
Z = self.from_order_ideal(self.to_poset().random_order_ideal())
return self.element_class(self, Z, check=False)
|
class PlanePartitions_CSPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n cyclically symmetric.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='CSPP')\n sage: TestSuite(PP).run() # needs sage.graphs sage.modules sage.rings.finite_rings\n sage: PlanePartitions([4,3,2], symmetry='CSPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (4,3,2) must all be equal\n "
if ((box_size[0] != box_size[1]) or (box_size[1] != box_size[2])):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be equal'.format(*box_size))
super().__init__(box_size, 'CSPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([3,3,3], symmetry='CSPP')\n Cyclically symmetric plane partitions inside a 3 x 3 x 3 box\n "
return 'Cyclically symmetric plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __contains__(self, x) -> bool:
"\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions([2,2,2], symmetry='CSPP')\n True\n sage: [[2,1],[1]] in PlanePartitions([1,1,1], symmetry='CSPP')\n False\n sage: [[2,1],[2]] in PlanePartitions([2,2,2], symmetry='CSPP')\n False\n "
P = PlanePartition(x)
max = (P._max_x, P._max_y, P._max_z)
return (PlanePartitions.__contains__(self, x) and P.is_CSPP() and all(((a <= b) for (a, b) in zip(max, self._box))))
def to_poset(self):
"\n Return a partially ordered set whose order ideals are in bijection with\n cyclically symmetric plane partitions.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='CSPP')\n sage: PP.to_poset() # needs sage.graphs\n Finite poset containing 11 elements\n sage: PP.to_poset().order_ideals_lattice().cardinality() == PP.cardinality() # needs sage.graphs\n True\n "
a = self._box[0]
b = self._box[1]
c = self._box[2]
def comp(x, y):
return all(((a <= b) for (a, b) in zip(x, y)))
def comp2(x, y):
return (comp(x, y) or comp(x, (y[2], y[0], y[1])) or comp(x, (y[1], y[2], y[0])))
pl = [(x, y, z) for x in range(a) for y in range(b) for z in range(x, c) if ((y <= z) and ((x != z) or (y == x)))]
from sage.combinat.posets.posets import Poset
return Poset((pl, comp2))
def from_antichain(self, acl) -> PP:
"\n Return the cyclically symmetric plane partition corresponding to an\n antichain in the poset given in :meth:`to_poset()`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='CSPP')\n sage: A = [(0, 2, 2), (1, 1, 1)]\n sage: PP.from_antichain(A)\n Plane partition [[3, 3, 3], [3, 2, 1], [3, 1, 1]]\n "
b = self._box[1]
c = self._box[2]
pp_matrix = [([0] * c) for i in range(b)]
for ac in acl:
x = ac[0]
y = ac[1]
z = ac[2]
pp_matrix[y][z] = (x + 1)
pp_matrix[z][x] = (y + 1)
pp_matrix[x][y] = (z + 1)
if (acl != []):
for i in range(b):
i = (b - (i + 1))
for j in range(c):
j = (c - (j + 1))
if (pp_matrix[i][j] == 0):
iValue = 0
jValue = 0
if (i < (b - 1)):
iValue = pp_matrix[(i + 1)][j]
if (j < (c - 1)):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
return self.element_class(self, pp_matrix)
def from_order_ideal(self, I) -> PP:
"\n Return the cylically symmetric plane partition corresponding\n to an order ideal in the poset given in :meth:`to_poset`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='CSPP')\n sage: I = [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1), (0, 1, 2),\n ....: (1, 0, 2), (0, 2, 2), (1, 1, 1), (1, 1, 2), (1, 2, 2)]\n sage: PP.from_order_ideal(I) # needs sage.graphs\n Plane partition [[3, 3, 3], [3, 3, 3], [3, 3, 2]]\n "
return self.from_antichain(self.to_poset().order_ideal_generators(I))
def random_element(self) -> PP:
"\n Return a uniformly random element of ``self``.\n\n ALGORITHM:\n\n This uses the\n :meth:`~sage.combinat.posets.posets.FinitePoset.random_order_ideal`\n method and the natural bijection between cyclically symmetric plane\n partitions and order ideals in an associated poset.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='CSPP')\n sage: PP.random_element() # random # needs sage.graphs\n Plane partition [[3, 2, 2], [3, 1], [1, 1]]\n "
Z = self.from_order_ideal(self.to_poset().random_order_ideal())
return self.element_class(self, Z, check=False)
def __iter__(self) -> Iterator:
"\n Iterate over all cyclically symmetric plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([2,2,2], symmetry='CSPP')) # needs sage.graphs sage.modules\n [Plane partition [],\n Plane partition [[2, 2], [2, 2]],\n Plane partition [[2, 2], [2, 1]],\n Plane partition [[2, 1], [1]],\n Plane partition [[1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality() for n in range(5) if (PP := PlanePartitions([n]*3, symmetry='CSPP')))\n True\n "
for acl in self.to_poset().antichains_iterator():
(yield self.from_antichain(acl))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of cyclically symmetric plane partitions inside an\n `a \\times a \\times a` box is equal to\n\n .. MATH::\n\n \\left(\\prod_{i=1}^{a} \\frac{3i - 1}{3i - 2}\\right)\n \\left(\\prod_{1 \\leq i < j \\leq a} \\frac{i+j+a-1}{2i+j-1}\\right).\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,4,4], symmetry='CSPP')\n sage: P.cardinality()\n 132\n "
a = self._box[0]
num = (prod((((3 * i) - 1) for i in range(1, (a + 1)))) * prod(((((i + j) + a) - 1) for j in range(1, (a + 1)) for i in range(1, (j + 1)))))
den = (prod((((3 * i) - 2) for i in range(1, (a + 1)))) * prod(((((2 * i) + j) - 1) for j in range(1, (a + 1)) for i in range(1, (j + 1)))))
return Integer((num // den))
|
class PlanePartitions_TSPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n totally symmetric.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='TSPP')\n sage: TestSuite(PP).run() # needs sage.graphs sage.modules\n sage: PlanePartitions([4,3,2], symmetry='TSPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (4,3,2) must all be equal\n "
if ((box_size[0] != box_size[1]) or (box_size[1] != box_size[2])):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be equal'.format(box_size[0], box_size[1], box_size[2]))
super().__init__(box_size, 'TSPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([3,3,3], symmetry='TSPP')\n Totally symmetric plane partitions inside a 3 x 3 x 3 box\n "
return 'Totally symmetric plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __contains__(self, x) -> bool:
"\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions([2,2,2], symmetry='TSPP')\n True\n sage: [[2,1],[1]] in PlanePartitions([1,1,1], symmetry='TSPP')\n False\n sage: [[2,1],[2]] in PlanePartitions([2,2,2], symmetry='TSPP')\n False\n "
P = PlanePartition(x)
maxval = (P._max_x, P._max_y, P._max_z)
return (PlanePartitions.__contains__(self, x) and P.is_TSPP() and all(((a <= b) for (a, b) in zip(maxval, self._box))))
def to_poset(self):
"\n Return a poset whose order ideals are in bijection with totally\n symmetric plane partitions.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='TSPP')\n sage: PP.to_poset() # needs sage.graphs\n Finite poset containing 10 elements\n sage: (PP.to_poset().order_ideals_lattice().cardinality() # needs sage.graphs sage.modules sage.rings.finite_rings\n ....: == PP.cardinality())\n True\n "
a = self._box[0]
b = self._box[1]
c = self._box[2]
def comp(x, y):
return all(((a <= b) for (a, b) in zip(x, y)))
pl = [(x, y, z) for x in range(a) for y in range(x, b) for z in range(y, c)]
from sage.combinat.posets.posets import Poset
return Poset((pl, comp))
def from_antichain(self, acl) -> PP:
"\n Return the totally symmetric plane partition corresponding to an\n antichain in the poset given in :meth:`to_poset()`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='TSPP')\n sage: A = [(0, 0, 2), (0, 1, 1)]\n sage: PP.from_antichain(A)\n Plane partition [[3, 2, 1], [2, 1], [1]]\n "
b = self._box[1]
c = self._box[2]
pp_matrix = [([0] * c) for i in range(b)]
for ac in acl:
x = ac[0]
y = ac[1]
z = ac[2]
pp_matrix[y][z] = (x + 1)
pp_matrix[z][x] = (y + 1)
pp_matrix[x][y] = (z + 1)
pp_matrix[z][y] = (x + 1)
pp_matrix[x][z] = (y + 1)
pp_matrix[y][x] = (z + 1)
if (acl != []):
for i in range(b):
i = (b - (i + 1))
for j in range(c):
j = (c - (j + 1))
if (pp_matrix[i][j] == 0):
iValue = 0
jValue = 0
if (i < (b - 1)):
iValue = pp_matrix[(i + 1)][j]
if (j < (c - 1)):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
return self.element_class(self, pp_matrix)
def from_order_ideal(self, I) -> PP:
"\n Return the totally symmetric plane partition corresponding\n to an order ideal in the poset given in :meth:`to_poset`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([3,3,3], symmetry='TSPP')\n sage: I = [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1)]\n sage: PP.from_order_ideal(I) # needs sage.graphs\n Plane partition [[3, 2, 1], [2, 1], [1]]\n "
return self.from_antichain(self.to_poset().order_ideal_generators(I))
def __iter__(self) -> Iterator:
"\n An iterator for totally symmetric plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([2,2,2], symmetry='TSPP')) # needs sage.graphs sage.modules\n [Plane partition [],\n Plane partition [[2, 2], [2, 2]],\n Plane partition [[2, 2], [2, 1]],\n Plane partition [[2, 1], [1]],\n Plane partition [[1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality() for n in range(5) if (PP := PlanePartitions([n]*3, symmetry='TSPP')))\n True\n "
for acl in self.to_poset().antichains_iterator():
(yield self.from_antichain(acl))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of totally symmetric plane partitions inside an\n `a \\times a \\times a` box is equal to\n\n .. MATH::\n\n \\prod_{1 \\leq i \\leq j \\leq a} \\frac{i+j+a-1}{i+2j-2}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,4,4], symmetry='TSPP')\n sage: P.cardinality()\n 66\n "
a = self._box[0]
num = prod(((((i + j) + a) - 1) for j in range(1, (a + 1)) for i in range(1, (j + 1))))
den = prod((((i + (2 * j)) - 2) for j in range(1, (a + 1)) for i in range(1, (j + 1))))
return Integer((num // den))
|
class PlanePartitions_SCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n self-complementary.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([4,3,2], symmetry='SCPP')\n sage: TestSuite(PP).run()\n sage: PlanePartitions([5,3,1], symmetry='SCPP')\n Traceback (most recent call last):\n ...\n ValueError: dimensions (5,3,1) cannot all be odd\n "
if (((box_size[0] % 2) == 1) and ((box_size[1] % 2) == 1) and ((box_size[2] % 2) == 1)):
raise ValueError('dimensions ({},{},{}) cannot all be odd'.format(*box_size))
super().__init__(box_size, 'SCPP', category=FiniteEnumeratedSets())
def __contains__(self, x) -> bool:
"\n TESTS::\n\n sage: [[2,1],[1]] in PlanePartitions([2,2,2], symmetry='SCPP')\n True\n sage: [[2,1],[1]] in PlanePartitions([3,2,2], symmetry='SCPP')\n False\n sage: [[2,1],[1]] in PlanePartitions([2,1,1], symmetry='SCPP')\n False\n sage: [[2,1],[2]] in PlanePartitions([2,2,2], symmetry='SCPP')\n False\n "
return ((x in PlanePartitions(self._box)) and PlanePartitions(self._box)(x).is_SCPP())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([4,3,2], symmetry='SCPP')\n Self-complementary plane partitions inside a 4 x 3 x 2 box\n "
return 'Self-complementary plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __iter__(self) -> Iterator:
"\n An iterator for self-complementary plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([3,2,2], symmetry='SCPP'))\n [Plane partition [[1, 1], [1, 1], [1, 1]],\n Plane partition [[2, 1], [1, 1], [1]],\n Plane partition [[2, 2], [1, 1]],\n Plane partition [[2], [2], [2]],\n Plane partition [[2, 1], [2], [1]],\n Plane partition [[2, 2], [2]]]\n\n TESTS::\n\n sage: PP = PlanePartitions([3,4,5], symmetry='SCPP')\n sage: len(set(PP)) == PP.cardinality()\n True\n\n sage: all(len(set(PP)) == PP.cardinality()\n ....: for b in cartesian_product([range(4)]*3)\n ....: if is_even(prod(b)) and (PP := PlanePartitions(b, symmetry='SCPP')))\n True\n "
b = self._box[0]
a = self._box[1]
c = self._box[2]
def Partitions_inside_lambda(la):
'\n Iterate over all partitions contained in la with the same number\n of parts including 0s.\n '
from sage.combinat.partition import Partitions
for k in range(sum(la), (- 1), (- 1)):
for mu in Partitions(k, outer=la):
(yield (mu + ([0] * (len(la) - len(mu)))))
def Partitions_inside_lambda_with_smallest_at_least_k(la, k):
'\n Iterate over all partitions contained in la with the smallest\n entry at least k.\n '
for mu in Partitions_inside_lambda([(val - k) for val in la]):
(yield [(mu[i] + k) for i in range(len(la))])
def possible_middle_row_for_b_odd(a, c):
'\n Iterate over all possible middle row for SCPP inside box(a,b,c)\n when b is odd.\n '
if (((a * c) % 2) == 1):
(yield)
return
for mu in Partitions_inside_lambda([(c // 2) for i in range((a // 2))]):
nu = [(c - mu[((len(mu) - 1) - i)]) for i in range(len(mu))]
if (not (a % 2)):
la = (nu + mu)
else:
la = ((nu + [(c // 2)]) + mu)
(yield la)
def possible_middle_row_for_b_even(a, c):
'\n Iterate over all possible middle ((b/2)+1)st row for SCPP inside\n box(a,b,c) when b is even.\n '
for mu in Partitions_inside_lambda([(c // 2) for i in range(((a + 1) // 2))]):
if (not mu):
(yield [])
continue
nu = [(c - mu[((len(mu) - 1) - i)]) for i in range((a // 2))]
for tau in Partitions_inside_lambda_with_smallest_at_least_k(nu, mu[0]):
la = (tau + mu)
(yield la)
def PPs_with_first_row_la_and_with_k_rows(la, k):
'Iterate over PPs with first row la and with k rows in total.'
if (k == 0):
(yield [])
return
if (k == 1):
(yield [la])
return
for mu in Partitions_inside_lambda(la):
for PP in PPs_with_first_row_la_and_with_k_rows(mu, (k - 1)):
(yield ([la] + PP))
def complement(PP, c):
'Return the complement of PP with respect to height c'
b = len(PP)
if (not b):
return []
a = len(PP[0])
return [[(c - PP[((b - 1) - i)][((a - 1) - j)]) for j in range(a)] for i in range(b)]
if ((b % 2) == 1):
for la in possible_middle_row_for_b_odd(a, c):
for PP in PPs_with_first_row_la_and_with_k_rows(la, ((b + 1) // 2)):
PP_below = PP[1:]
PP_above = complement(PP_below, c)
(yield self.element_class(self, ((PP_above + [la]) + PP_below)))
else:
for la in possible_middle_row_for_b_even(a, c):
for PP in PPs_with_first_row_la_and_with_k_rows(la, (b // 2)):
PP_below = PP
PP_above = complement(PP_below, c)
(yield self.element_class(self, (PP_above + PP_below)))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of self complementary plane partitions inside a\n `2a \\times 2b \\times 2c` box is equal to\n\n .. MATH::\n\n \\left(\\prod_{i=1}^{r}\\prod_{j=1}^{b}\n \\frac{i + j + c - 1}{i + j - 1}\\right)^2.\n\n The number of self complementary plane partitions inside an\n `(2a+1) \\times 2b \\times 2c` box is equal to\n\n .. MATH::\n\n \\left(\\prod_{i=1}^{a} \\prod_{j=1}^{b} \\frac{i+j+c-1}{i+j-1} \\right)\n \\left(\\prod_{i=1}^{a+1} \\prod_{j=1}^{b} \\frac{i+j+c-1}{i+j-1} \\right).\n\n The number of self complementary plane partitions inside an\n `(2a+1) \\times (2b+1) \\times 2c` box is equal to\n\n .. MATH::\n\n \\left(\\prod_{i=1}^{a+1} \\prod_{j=1}^{b} \\frac{i+j+c-1}{i+j-1} \\right)\n \\left(\\prod_{i=1}^{a} \\prod_{j=1}^{b+1} \\frac{i+j+c-1}{i+j-1} \\right).\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,4,4], symmetry='SCPP')\n sage: P.cardinality()\n 400\n\n sage: P = PlanePartitions([5,4,4], symmetry='SCPP')\n sage: P.cardinality()\n 1000\n sage: P = PlanePartitions([4,5,4], symmetry='SCPP')\n sage: P.cardinality()\n 1000\n sage: P = PlanePartitions([4,4,5], symmetry='SCPP')\n sage: P.cardinality()\n 1000\n\n sage: P = PlanePartitions([5,5,4], symmetry='SCPP')\n sage: P.cardinality()\n 2500\n sage: P = PlanePartitions([5,4,5], symmetry='SCPP')\n sage: P.cardinality()\n 2500\n sage: P = PlanePartitions([4,5,5], symmetry='SCPP')\n sage: P.cardinality()\n 2500\n "
r = self._box[0]
s = self._box[1]
t = self._box[2]
if ((r % 2) == 0):
R = (r // 2)
if ((s % 2) == 0):
S = (s // 2)
if ((t % 2) == 0):
T = (t // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 1))))))
else:
T = ((t - 1) // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 2))))))
else:
S = ((s - 1) // 2)
if ((t % 2) == 0):
T = (t // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 2)) for k in range(1, (T + 1))))))
else:
T = ((t - 1) // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 2)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 2))))))
R = ((r - 1) // 2)
if ((s % 2) == 0):
S = (s // 2)
if ((t % 2) == 0):
T = (t // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 2)) for j in range(1, (S + 1)) for k in range(1, (T + 1))))))
else:
T = ((t - 1) // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 2)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 1)) for k in range(1, (T + 2))))))
S = ((s - 1) // 2)
if ((t % 2) == 0):
T = (t // 2)
return Integer((prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 2)) for j in range(1, (S + 1)) for k in range(1, (T + 1)))) * prod(((Integer((((i + j) + k) - 1)) / Integer((((i + j) + k) - 2))) for i in range(1, (R + 1)) for j in range(1, (S + 2)) for k in range(1, (T + 1))))))
return Integer(0)
|
class PlanePartitions_TCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n transpose-complement.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([3,3,2], symmetry='TCPP')\n sage: TestSuite(PP).run() # needs sage.graphs sage.modules\n\n sage: PlanePartitions([3,3,3], symmetry='TCPP')\n Traceback (most recent call last):\n ...\n ValueError: z dimension (3) must be even\n\n sage: PlanePartitions([4,3,2], symmetry='TCPP')\n Traceback (most recent call last):\n ...\n ValueError: x and y dimensions (4 and 3) must be equal\n "
if ((box_size[2] % 2) == 1):
raise ValueError('z dimension ({}) must be even'.format(box_size[2]))
if (box_size[0] != box_size[1]):
raise ValueError('x and y dimensions ({} and {}) must be equal'.format(box_size[0], box_size[1]))
super().__init__(box_size, 'TCPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([3,3,2], symmetry='TCPP')\n Transpose complement plane partitions inside a 3 x 3 x 2 box\n "
return 'Transpose complement plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __iter__(self) -> Iterator:
"\n Iterate over all transpose complement plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([3,3,2], symmetry='TCPP')) # needs sage.modules\n [Plane partition [[2, 2, 1], [2, 1], [1]],\n Plane partition [[2, 1, 1], [2, 1, 1], [1]],\n Plane partition [[2, 2, 1], [1, 1], [1, 1]],\n Plane partition [[2, 1, 1], [1, 1, 1], [1, 1]],\n Plane partition [[1, 1, 1], [1, 1, 1], [1, 1, 1]]]\n "
for p in PlanePartitions(self._box):
if p.is_TCPP():
(yield self.element_class(self, p))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of transpose complement plane partitions inside an\n `a \\times a \\times 2b` box is equal to\n\n .. MATH::\n\n \\binom{b+1-1}{a-1} \\prod_{1\\leq i,j \\leq a-2}\n \\frac{i + j + 2b - 1}{i + j - 1}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([3,3,2], symmetry='TCPP')\n sage: P.cardinality()\n 5\n "
a = self._box[0]
c = self._box[2]
return Integer(((binomial((((c // 2) + a) - 1), (a - 1)) * prod(((((c + i) + j) + 1) for j in range(1, (a - 1)) for i in range(1, (1 + j))))) // prod((((i + j) + 1) for j in range(1, (a - 1)) for i in range(1, (1 + j))))))
|
class PlanePartitions_SSCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n symmetric self-complementary.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([2, 2, 4], symmetry='SSCPP')\n sage: TestSuite(PP).run() # needs sage.modules\n\n sage: PP = PlanePartitions([4, 4, 2], symmetry='SSCPP')\n sage: TestSuite(PP).run() # long time # needs sage.modules\n\n sage: PlanePartitions([4, 2, 2], symmetry='SSCPP')\n Traceback (most recent call last):\n ...\n ValueError: x and y dimensions (4 and 2) must be equal\n\n sage: PlanePartitions([4, 4, 3], symmetry='SSCPP')\n Traceback (most recent call last):\n ...\n ValueError: z dimension (3) must be even\n "
if (box_size[0] != box_size[1]):
raise ValueError('x and y dimensions ({} and {}) must be equal'.format(box_size[0], box_size[1]))
if ((box_size[2] % 2) == 1):
raise ValueError('z dimension ({}) must be even'.format(box_size[2]))
super().__init__(box_size, 'SSCPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([4, 4, 2], symmetry='SSCPP')\n Symmetric self-complementary plane partitions inside a 4 x 4 x 2 box\n "
return 'Symmetric self-complementary plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __iter__(self) -> Iterator:
"\n Iterate over all symmetric self-complementary plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([4,4,2], symmetry='SSCPP')) # needs sage.modules\n [Plane partition [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],\n Plane partition [[2, 2, 2, 1], [2, 1, 1], [2, 1, 1], [1]],\n Plane partition [[2, 2, 1, 1], [2, 2, 1, 1], [1, 1], [1, 1]],\n Plane partition [[2, 2, 2, 1], [2, 2, 1], [2, 1], [1]],\n Plane partition [[2, 2, 1, 1], [2, 1, 1, 1], [1, 1, 1], [1, 1]],\n Plane partition [[2, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality()\n ....: for a, b in cartesian_product([range(5), range(0, 5, 2)])\n ....: if (PP := PlanePartitions([a, a, b], symmetry='SSCPP')))\n True\n "
for p in PlanePartitions(self._box, symmetry='SPP'):
if p.is_SSCPP():
(yield self.element_class(self, p))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of symmetric self-complementary plane partitions inside a\n `2a \\times 2a \\times 2b` box is equal to\n\n .. MATH::\n\n \\prod_{i=1}^a \\prod_{j=1}^a \\frac{i + j + b - 1}{i + j - 1}.\n\n The number of symmetric self-complementary plane partitions inside a\n `(2a+1) \\times (2a+1) \\times 2b` box is equal to\n\n .. MATH::\n\n \\prod_{i=1}^a \\prod_{j=1}^{a+1} \\frac{i + j + b - 1}{i + j - 1}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([4,4,2], symmetry='SSCPP')\n sage: P.cardinality()\n 6\n sage: Q = PlanePartitions([3,3,2], symmetry='SSCPP')\n sage: Q.cardinality()\n 3\n "
a = self._box[0]
c = self._box[2]
num = prod(((((i + j) + k) - 1) for i in range(1, (1 + (a // 2))) for j in range(1, (1 + ((a + 1) // 2))) for k in range(1, (1 + (c // 2)))))
den = prod(((((i + j) + k) - 2) for i in range(1, (1 + (a // 2))) for j in range(1, (1 + ((a + 1) // 2))) for k in range(1, (1 + (c // 2)))))
return Integer((num // den))
|
class PlanePartitions_CSTCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n cyclically symmetric and transpose-complement.\n '
def __init__(self, box_size):
"\n TESTS::\n\n sage: PP = PlanePartitions([2,2,2], symmetry='CSTCPP')\n sage: TestSuite(PP).run() # needs sage.modules\n\n sage: PlanePartitions([4,3,2], symmetry='CSTCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (4,3,2) must all be equal\n\n sage: PlanePartitions([3,3,3], symmetry='CSTCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (3,3,3) must all be even\n "
if ((box_size[0] != box_size[1]) or (box_size[1] != box_size[2])):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be equal'.format(*box_size))
if ((box_size[0] % 2) == 1):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be even'.format(*box_size))
super().__init__(box_size, 'CSTPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([4,4,4], symmetry='CSTCPP')\n Cyclically symmetric transpose complement plane partitions inside a 4 x 4 x 4 box\n "
return 'Cyclically symmetric transpose complement plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __iter__(self) -> Iterator:
"\n Iterate over all cyclically symmetry transpose complement plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([2,2,2], symmetry='CSTCPP')) # needs sage.modules\n [Plane partition [[2, 1], [1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality()\n ....: for n in range(0, 5, 2)\n ....: if (PP := PlanePartitions([n]*3, symmetry='CSTCPP')))\n True\n "
for p in PlanePartitions(self._box, symmetry='TSPP'):
if p.is_CSTCPP():
(yield self.element_class(self, p))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of cyclically symmetric transpose complement plane partitions\n inside a `2a \\times 2a \\times 2a` box is equal to\n\n .. MATH::\n\n \\prod_{i=0}^{a-1} \\frac{(3i+1)(6i)!(2i)!}{(4i+1)!(4i)!}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([6,6,6], symmetry='CSTCPP')\n sage: P.cardinality()\n 11\n "
a = (self._box[0] // 2)
num = prod((((((3 * i) + 1) * factorial((6 * i))) * factorial((2 * i))) for i in range(a)))
den = prod(((factorial(((4 * i) + 1)) * factorial((4 * i))) for i in range(a)))
return Integer((num // den))
|
class PlanePartitions_CSSCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n cyclically symmetric self-complementary.\n '
def __init__(self, box_size):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: PP = PlanePartitions([2,2,2], symmetry='CSSCPP')\n sage: TestSuite(PP).run() # needs sage.modules\n sage: PlanePartitions([4,3,2], symmetry='CSSCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (4,3,2) must all be equal\n sage: PlanePartitions([3,3,3], symmetry='CSSCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (3,3,3) must all be even\n "
if ((box_size[0] != box_size[1]) or (box_size[1] != box_size[2])):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be equal'.format(*box_size))
if ((box_size[0] % 2) == 1):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be even'.format(*box_size))
super().__init__(box_size, 'CSSCPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([4,4,4], symmetry='CSSCPP')\n Cyclically symmetric self-complementary plane partitions inside a 4 x 4 x 4 box\n "
return 'Cyclically symmetric self-complementary plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def __iter__(self) -> Iterator:
"\n Iterate over all cyclically symmetric self-complementary plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([2,2,2], symmetry='CSSCPP')) # needs sage.modules\n [Plane partition [[2, 1], [1]]]\n "
for p in PlanePartitions(self._box, symmetry='CSPP'):
if p.is_CSSCPP():
(yield self.element_class(self, p))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of cyclically symmetric self-complementary plane partitions\n inside a `2a \\times 2a \\times 2a` box is equal to\n\n .. MATH::\n\n \\left( \\prod_{i=0}^{a-1} \\frac{(3i+1)!}{(a+i)!} \\right)^2.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([6,6,6], symmetry='CSSCPP')\n sage: P.cardinality()\n 49\n "
a = (self._box[0] // 2)
num = prod(((factorial(((3 * i) + 1)) ** 2) for i in range(a)))
den = prod(((factorial((a + i)) ** 2) for i in range(a)))
return Integer((num // den))
|
class PlanePartitions_TSSCPP(PlanePartitions):
'\n Plane partitions that fit inside a box of a specified size that are\n totally symmetric self-complementary.\n '
def __init__(self, box_size):
"\n TESTS::\n\n sage: PP = PlanePartitions([4,4,4], symmetry='TSSCPP')\n sage: TestSuite(PP).run() # needs sage.modules\n sage: PlanePartitions([4,3,2], symmetry='TSSCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (4,3,2) must all be equal\n sage: PlanePartitions([3,3,3], symmetry='TSSCPP')\n Traceback (most recent call last):\n ...\n ValueError: x, y, and z dimensions (3,3,3) must all be even\n "
if ((box_size[0] != box_size[1]) or (box_size[1] != box_size[2])):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be equal'.format(*box_size))
if ((box_size[0] % 2) == 1):
raise ValueError('x, y, and z dimensions ({},{},{}) must all be even'.format(*box_size))
super().__init__(box_size, 'TSSCPP', category=FiniteEnumeratedSets())
def _repr_(self) -> str:
"\n EXAMPLES::\n\n sage: PlanePartitions([4,4,4], symmetry='TSSCPP')\n Totally symmetric self-complementary plane partitions inside a 4 x 4 x 4 box\n "
return 'Totally symmetric self-complementary plane partitions inside a {} x {} x {} box'.format(self._box[0], self._box[1], self._box[2])
def to_poset(self):
"\n Return a poset whose order ideals are in bijection with\n totally symmetric self-complementary plane partitions.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([6,6,6], symmetry='TSSCPP')\n sage: PP.to_poset() # needs sage.graphs sage.modules\n Finite poset containing 4 elements\n sage: PP.to_poset().order_ideals_lattice().cardinality() == PP.cardinality() # needs sage.graphs sage.modules\n True\n "
from sage.combinat.posets.posets import Poset
a = self._box[0]
b = self._box[1]
c = self._box[2]
if ((a != b) or (b != c) or (a != c)):
return Poset()
def comp(x, y):
return all(((xx <= yy) for (xx, yy) in zip(x, y)))
A = (a // 2)
pl = [(x, y, z) for x in range((A - 1)) for y in range(x, (A - 1)) for z in range((A - 1)) if (z <= ((A - 2) - y))]
return Poset((pl, comp))
def from_antichain(self, acl) -> PP:
"\n Return the totally symmetric self-complementary plane partition\n corresponding to an antichain in the poset given in :meth:`to_poset()`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([6,6,6], symmetry='TSSCPP')\n sage: A = [(0, 0, 1), (1, 1, 0)]\n sage: PP.from_antichain(A)\n Plane partition [[6, 6, 6, 5, 5, 3], [6, 5, 5, 4, 3, 1], [6, 5, 4, 3, 2, 1], [5, 4, 3, 2, 1], [5, 3, 2, 1, 1], [3, 1, 1]]\n "
a = self._box[0]
b = self._box[1]
c = self._box[2]
n = a
N = (n // 2)
pp_matrix = [([0] * c) for i in range(b)]
width = (N - 1)
height = (N - 1)
for i in range(width):
for j in range(i, height):
for ac in acl:
if ((ac[0] == i) and (ac[1] == j)):
zVal = ac[2]
matrixVal = pp_matrix[(j + N)][(i + N)]
if ((zVal + 1) > matrixVal):
pp_matrix[(j + N)][(i + N)] = (zVal + 1)
for i in range(width):
i = (width - (i + 1))
i = (i + N)
for j in range(height):
j = (height - (j + 1))
j = (j + N)
if (pp_matrix[i][j] == 0):
if (i >= j):
iValue = 0
jValue = 0
if (i < n):
iValue = pp_matrix[(i + 1)][j]
if (j < n):
jValue = pp_matrix[i][(j + 1)]
pp_matrix[i][j] = max(iValue, jValue)
for i in range(width):
i += N
for j in range(height):
j += N
if (i >= j):
pp_matrix[j][i] = pp_matrix[i][j]
for i in range(N):
for j in range(N):
pp_matrix[i][j] = (n - pp_matrix[(n - (i + 1))][(n - (j + 1))])
for i in range(N):
for j in range(N):
x = i
y = j
if (pp_matrix[x][(y + N)] == 0):
pp_matrix[x][(y + N)] = N
if (pp_matrix[(x + N)][y] == 0):
pp_matrix[(x + N)][y] = N
for i in range(N):
for j in range(N):
x = (i + N)
y = (j + N)
if (pp_matrix[x][y] > 0):
z = pp_matrix[x][y]
for cVal in range(z):
pp_matrix[x][(0 + cVal)] += 1
pp_matrix[(n - (1 + cVal))][(N - (j + 1))] -= 1
for i in range(N):
for j in range(N):
pp_matrix[j][(i + N)] = pp_matrix[(i + N)][j]
return self.element_class(self, pp_matrix)
def from_order_ideal(self, I) -> PP:
"\n Return the totally symmetric self-complementary plane partition\n corresponding to an order ideal in the poset given in :meth:`to_poset`.\n\n EXAMPLES::\n\n sage: PP = PlanePartitions([6,6,6], symmetry='TSSCPP') # needs sage.graphs\n sage: I = [(0, 0, 0), (0, 1, 0), (1, 1, 0)]\n sage: PP.from_order_ideal(I) # needs sage.graphs\n Plane partition [[6, 6, 6, 5, 5, 3], [6, 5, 5, 3, 3, 1], [6, 5, 5, 3, 3, 1],\n [5, 3, 3, 1, 1], [5, 3, 3, 1, 1], [3, 1, 1]]\n "
return self.from_antichain(self.to_poset().order_ideal_generators(I))
def __iter__(self) -> Iterator:
"\n Iterate over all totally symmetric self-complementary plane partitions.\n\n EXAMPLES::\n\n sage: list(PlanePartitions([4,4,4], symmetry='TSSCPP')) # needs sage.graphs sage.modules\n [Plane partition [[4, 4, 2, 2], [4, 4, 2, 2], [2, 2], [2, 2]],\n Plane partition [[4, 4, 3, 2], [4, 3, 2, 1], [3, 2, 1], [2, 1]]]\n\n TESTS::\n\n sage: all(len(set(PP)) == PP.cardinality() for n in range(0,11,2) if (PP := PlanePartitions([n]*3, symmetry='TSSCPP')))\n True\n "
for acl in self.to_poset().antichains_iterator():
(yield self.from_antichain(acl))
def cardinality(self) -> Integer:
"\n Return the cardinality of ``self``.\n\n The number of totally symmetric self-complementary plane partitions\n inside a `2a \\times 2a \\times 2a` box is equal to\n\n .. MATH::\n\n \\prod_{i=0}^{a-1} \\frac{(3i+1)!}{(a+i)!}.\n\n EXAMPLES::\n\n sage: P = PlanePartitions([6,6,6], symmetry='TSSCPP')\n sage: P.cardinality()\n 7\n "
a = (self._box[0] // 2)
num = prod((factorial(((3 * i) + 1)) for i in range(a)))
den = prod((factorial((a + i)) for i in range(a)))
return Integer((num // den))
|
class CartesianProductPoset(CartesianProduct):
"\n A class implementing Cartesian products of posets (and elements\n thereof). Compared to :class:`CartesianProduct` you are able to\n specify an order for comparison of the elements.\n\n INPUT:\n\n - ``sets`` -- a tuple of parents.\n\n - ``category`` -- a subcategory of\n ``Sets().CartesianProducts() & Posets()``.\n\n - ``order`` -- a string or function specifying an order less or equal.\n It can be one of the following:\n\n - ``'native'`` -- elements are ordered by their native ordering,\n i.e., the order the wrapped elements (tuples) provide.\n\n - ``'lex'`` -- elements are ordered lexicographically.\n\n - ``'product'`` -- an element is less or equal to another\n element, if less or equal is true for all its components\n (Cartesian projections).\n\n - A function which performs the comparison `\\leq`. It takes two\n input arguments and outputs a boolean.\n\n Other keyword arguments (``kwargs``) are passed to the constructor\n of :class:`CartesianProduct`.\n\n EXAMPLES::\n\n sage: P = Poset((srange(3), lambda left, right: left <= right))\n sage: Cl = cartesian_product((P, P), order='lex')\n sage: Cl((1, 1)) <= Cl((2, 0))\n True\n sage: Cp = cartesian_product((P, P), order='product')\n sage: Cp((1, 1)) <= Cp((2, 0))\n False\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: Cs = cartesian_product((P, P), order=le_sum)\n sage: Cs((1, 1)) <= Cs((2, 0))\n True\n\n TESTS::\n\n sage: Cl.category()\n Join of Category of finite posets and\n Category of Cartesian products of finite enumerated sets\n sage: TestSuite(Cl).run(skip=['_test_construction'])\n sage: Cp.category()\n Join of Category of finite posets and\n Category of Cartesian products of finite enumerated sets\n sage: TestSuite(Cp).run(skip=['_test_construction'])\n\n .. SEEALSO::\n\n :class:`CartesianProduct`\n "
def __init__(self, sets, category, order=None, **kwargs):
"\n See :class:`CartesianProductPoset` for details.\n\n TESTS::\n\n sage: P = Poset((srange(3), lambda left, right: left <= right))\n sage: C = cartesian_product((P, P), order='notexisting')\n Traceback (most recent call last):\n ...\n ValueError: no order 'notexisting' known\n sage: C = cartesian_product((P, P), category=(Groups(),))\n sage: C.category()\n Join of Category of groups and Category of posets\n "
if (order is None):
self._le_ = self.le_product
elif isinstance(order, str):
try:
self._le_ = getattr(self, ('le_' + order))
except AttributeError:
raise ValueError(("no order '%s' known" % (order,)))
else:
self._le_ = order
from sage.categories.category import Category
from sage.categories.posets import Posets
if (not isinstance(category, tuple)):
category = (category,)
category = Category.join((category + (Posets(),)))
super().__init__(sets, category, **kwargs)
def le(self, left, right):
'\n Test whether ``left`` is less than or equal to ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method uses the order defined on creation of this\n Cartesian product. See :class:`CartesianProductPoset`.\n\n EXAMPLES::\n\n sage: P = posets.ChainPoset(10)\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((P, P), order=le_sum)\n sage: C.le(C((1, 6)), C((6, 1)))\n True\n sage: C.le(C((6, 1)), C((1, 6)))\n False\n sage: C.le(C((1, 6)), C((6, 6)))\n True\n sage: C.le(C((6, 6)), C((1, 6)))\n False\n '
return self._le_(left, right)
def le_lex(self, left, right):
"\n Test whether ``left`` is lexicographically smaller or equal\n to ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n EXAMPLES::\n\n sage: P = Poset((srange(2), lambda left, right: left <= right))\n sage: Q = cartesian_product((P, P), order='lex')\n sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))]\n sage: for a in T:\n ....: for b in T:\n ....: assert Q.le(a, b) == (a <= b)\n ....: print('%s <= %s = %s' % (a, b, a <= b))\n (0, 0) <= (0, 0) = True\n (0, 0) <= (1, 1) = True\n (0, 0) <= (0, 1) = True\n (0, 0) <= (1, 0) = True\n (1, 1) <= (0, 0) = False\n (1, 1) <= (1, 1) = True\n (1, 1) <= (0, 1) = False\n (1, 1) <= (1, 0) = False\n (0, 1) <= (0, 0) = False\n (0, 1) <= (1, 1) = True\n (0, 1) <= (0, 1) = True\n (0, 1) <= (1, 0) = True\n (1, 0) <= (0, 0) = False\n (1, 0) <= (1, 1) = True\n (1, 0) <= (0, 1) = False\n (1, 0) <= (1, 0) = True\n\n TESTS:\n\n Check that :trac:`19999` is resolved::\n\n sage: P = Poset((srange(2), lambda left, right: left <= right))\n sage: Q = cartesian_product((P, P), order='product')\n sage: R = cartesian_product((Q, P), order='lex')\n sage: R(((1, 0), 0)) <= R(((0, 1), 0))\n False\n sage: R(((0, 1), 0)) <= R(((1, 0), 0))\n False\n "
for (l, r, S) in zip(left.value, right.value, self.cartesian_factors()):
if (l == r):
continue
if S.le(l, r):
return True
if S.le(r, l):
return False
return False
return True
def le_product(self, left, right):
"\n Test whether ``left`` is component-wise smaller or equal\n to ``right``.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n The comparison is ``True`` if the result of the\n comparison in each component is ``True``.\n\n EXAMPLES::\n\n sage: P = Poset((srange(2), lambda left, right: left <= right))\n sage: Q = cartesian_product((P, P), order='product')\n sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))]\n sage: for a in T:\n ....: for b in T:\n ....: assert Q.le(a, b) == (a <= b)\n ....: print('%s <= %s = %s' % (a, b, a <= b))\n (0, 0) <= (0, 0) = True\n (0, 0) <= (1, 1) = True\n (0, 0) <= (0, 1) = True\n (0, 0) <= (1, 0) = True\n (1, 1) <= (0, 0) = False\n (1, 1) <= (1, 1) = True\n (1, 1) <= (0, 1) = False\n (1, 1) <= (1, 0) = False\n (0, 1) <= (0, 0) = False\n (0, 1) <= (1, 1) = True\n (0, 1) <= (0, 1) = True\n (0, 1) <= (1, 0) = False\n (1, 0) <= (0, 0) = False\n (1, 0) <= (1, 1) = True\n (1, 0) <= (0, 1) = False\n (1, 0) <= (1, 0) = True\n "
return all((S.le(l, r) for (l, r, S) in zip(left.value, right.value, self.cartesian_factors())))
def le_native(self, left, right):
"\n Test whether ``left`` is smaller or equal to ``right`` in the order\n provided by the elements themselves.\n\n INPUT:\n\n - ``left`` -- an element.\n\n - ``right`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n EXAMPLES::\n\n sage: P = Poset((srange(2), lambda left, right: left <= right))\n sage: Q = cartesian_product((P, P), order='native')\n sage: T = [Q((0, 0)), Q((1, 1)), Q((0, 1)), Q((1, 0))]\n sage: for a in T:\n ....: for b in T:\n ....: assert Q.le(a, b) == (a <= b)\n ....: print('%s <= %s = %s' % (a, b, a <= b))\n (0, 0) <= (0, 0) = True\n (0, 0) <= (1, 1) = True\n (0, 0) <= (0, 1) = True\n (0, 0) <= (1, 0) = True\n (1, 1) <= (0, 0) = False\n (1, 1) <= (1, 1) = True\n (1, 1) <= (0, 1) = False\n (1, 1) <= (1, 0) = False\n (0, 1) <= (0, 0) = False\n (0, 1) <= (1, 1) = True\n (0, 1) <= (0, 1) = True\n (0, 1) <= (1, 0) = True\n (1, 0) <= (0, 0) = False\n (1, 0) <= (1, 1) = True\n (1, 0) <= (0, 1) = False\n (1, 0) <= (1, 0) = True\n "
return (left.value <= right.value)
class Element(CartesianProduct.Element):
def _le_(self, other):
'\n Return if this element is less or equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method calls :meth:`CartesianProductPoset.le`. Override\n it in inherited class to change this.\n\n It can be assumed that this element and ``other`` have\n the same parent.\n\n TESTS::\n\n sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset\n sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((QQ, QQ), order=le_sum)\n sage: C((1/3, 2)) <= C((2, 1/3)) # indirect doctest\n True\n sage: C((1/3, 2)) <= C((2, 2)) # indirect doctest\n True\n '
return self.parent().le(self, other)
def __le__(self, other):
'\n Return if this element is less than or equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method uses the coercion framework to find a\n suitable common parent.\n\n This method can be deleted once :trac:`10130` is fixed and\n provides these methods automatically.\n\n TESTS::\n\n sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset\n sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((QQ, QQ), order=le_sum)\n sage: C((1/3, 2)) <= C((2, 1/3))\n True\n sage: C((1/3, 2)) <= C((2, 2))\n True\n\n The following example tests that the coercion gets involved in\n comparisons; it can be simplified once :trac:`18182` is merged.\n ::\n\n sage: class MyCP(CartesianProductPoset):\n ....: def _coerce_map_from_(self, S):\n ....: if isinstance(S, self.__class__):\n ....: S_factors = S.cartesian_factors()\n ....: R_factors = self.cartesian_factors()\n ....: if len(S_factors) == len(R_factors):\n ....: if all(r.has_coerce_map_from(s)\n ....: for r,s in zip(R_factors, S_factors)):\n ....: return True\n sage: QQ.CartesianProduct = MyCP\n sage: A = cartesian_product((QQ, ZZ), order=le_sum)\n sage: B = cartesian_product((QQ, QQ), order=le_sum)\n sage: A((1/2, 4)) <= B((1/2, 5))\n True\n '
from sage.structure.element import have_same_parent
if have_same_parent(self, other):
return self._le_(other)
from sage.structure.element import get_coercion_model
import operator
try:
return get_coercion_model().bin_op(self, other, operator.le)
except TypeError:
return False
def __ge__(self, other):
'\n Return if this element is greater than or equal to ``other``.\n\n INPUT:\n\n - ``other`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method uses the coercion framework to find a\n suitable common parent.\n\n This method can be deleted once :trac:`10130` is fixed and\n provides these methods automatically.\n\n TESTS::\n\n sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset\n sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((QQ, QQ), order=le_sum)\n sage: C((1/3, 2)) >= C((2, 1/3))\n False\n sage: C((1/3, 2)) >= C((2, 2))\n False\n '
return (other <= self)
def __lt__(self, other):
'\n Return if this element is less than ``other``.\n\n INPUT:\n\n - ``other`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method uses the coercion framework to find a\n suitable common parent.\n\n This method can be deleted once :trac:`10130` is fixed and\n provides these methods automatically.\n\n TESTS::\n\n sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset\n sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((QQ, QQ), order=le_sum)\n sage: C((1/3, 2)) < C((2, 1/3))\n True\n sage: C((1/3, 2)) < C((2, 2))\n True\n '
return ((not (self == other)) and (self <= other))
def __gt__(self, other):
'\n Return if this element is greater than ``other``.\n\n INPUT:\n\n - ``other`` -- an element.\n\n OUTPUT:\n\n A boolean.\n\n .. NOTE::\n\n This method uses the coercion framework to find a\n suitable common parent.\n\n This method can be deleted once :trac:`10130` is fixed and\n provides these methods automatically.\n\n TESTS::\n\n sage: from sage.combinat.posets.cartesian_product import CartesianProductPoset\n sage: QQ.CartesianProduct = CartesianProductPoset # needed until #19269 is fixed\n sage: def le_sum(left, right):\n ....: return (sum(left) < sum(right) or\n ....: sum(left) == sum(right) and left[0] <= right[0])\n sage: C = cartesian_product((QQ, QQ), order=le_sum)\n sage: C((1/3, 2)) > C((2, 1/3))\n False\n sage: C((1/3, 2)) > C((2, 2))\n False\n '
return ((not (self == other)) and (other <= self))
|
class DCompletePoset(FiniteJoinSemilattice):
'\n A d-complete poset.\n\n D-complete posets are a class of posets introduced by Proctor\n in [Proc1999]_. It includes common families such as shapes, shifted\n shapes, and rooted forests. Proctor showed in [PDynk1999]_ that\n d-complete posets have decompositions in *irreducible* posets,\n and showed in [Proc2014]_ that d-complete posets admit a hook-length\n formula (see :wikipedia:`Hook_length_formula`). A complete proof of\n the hook-length formula can be found in [KY2019]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: P = Posets.DoubleTailedDiamond(2)\n sage: TestSuite(P).run()\n '
_lin_ext_type = LinearExtensionsOfPosetWithHooks
_desc = 'Finite d-complete poset'
@lazy_attribute
def _hooks(self):
'\n The hook lengths of the elements of the d-complete poset.\n\n See [KY2019]_ for the definition of hook lengths for d-complete posets.\n\n TESTS::\n\n sage: from sage.combinat.posets.d_complete import DCompletePoset\n sage: P = DCompletePoset(DiGraph({0: [1, 2], 1: [3], 2: [3], 3: []}))\n sage: P._hooks\n {0: 1, 1: 2, 2: 2, 3: 3}\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: P = DCompletePoset(Posets.YoungDiagramPoset(Partition([3,2,1]))._hasse_diagram.reverse()) # optional - sage.combinat\n sage: P._hooks # optional - sage.combinat\n {0: 5, 1: 3, 2: 1, 3: 3, 4: 1, 5: 1}\n '
hooks = {}
min_diamond = {}
max_diamond = {}
H = self._hasse_diagram
(diamonds, _) = H.diamonds()
diamond_index = {}
for (index, d) in enumerate(diamonds):
min_diamond[d[3]] = d[0]
max_diamond[d[0]] = d[3]
diamond_index[d[3]] = index
min_elmt = d[0]
max_elmt = d[3]
while True:
potential_min = H.neighbors_in(min_elmt)
potential_max = H.neighbors_out(max_elmt)
found_diamond = False
for mx in potential_max:
if (H.in_degree(mx) != 1):
continue
for mn in potential_min:
if (len(H.all_paths(mn, mx)) == 2):
min_elmt = mn
max_elmt = mx
min_diamond[mx] = mn
max_diamond[mn] = mx
diamond_index[mx] = index
found_diamond = True
break
if found_diamond:
break
if (not found_diamond):
break
queue = deque(H.sources())
enqueued = set()
while queue:
elmt = queue.popleft()
if (elmt not in diamond_index):
hooks[elmt] = H.order_ideal_cardinality([elmt])
else:
diamond = diamonds[diamond_index[elmt]]
side1 = diamond[1]
side2 = diamond[2]
hooks[elmt] = ((hooks[side1] + hooks[side2]) - hooks[min_diamond[elmt]])
enqueued.add(elmt)
for c in H.neighbors_out(elmt):
if (c not in enqueued):
queue.append(c)
enqueued.add(c)
poset_hooks = {self._vertex_to_element(key): ZZ(value) for (key, value) in hooks.items()}
return poset_hooks
def get_hook(self, elmt):
'\n Return the hook length of the element ``elmt``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.d_complete import DCompletePoset\n sage: P = DCompletePoset(DiGraph({0: [1], 1: [2]}))\n sage: P.get_hook(1)\n 2\n '
return self._hooks[elmt]
def get_hooks(self):
'\n Return all the hook lengths as a dictionary.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.d_complete import DCompletePoset\n sage: P = DCompletePoset(DiGraph({0: [1, 2], 1: [3], 2: [3], 3: []}))\n sage: P.get_hooks()\n {0: 1, 1: 2, 2: 2, 3: 3}\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: YDP321 = Posets.YoungDiagramPoset(Partition([3,2,1])) # optional - sage.combinat\n sage: P = DCompletePoset(YDP321._hasse_diagram.reverse()) # optional - sage.combinat\n sage: P.get_hooks() # optional - sage.combinat\n {0: 5, 1: 3, 2: 1, 3: 3, 4: 1, 5: 1}\n '
return dict(self._hooks)
def hook_product(self):
'\n Return the hook product for the poset.\n\n TESTS::\n\n sage: from sage.combinat.posets.d_complete import DCompletePoset\n sage: P = DCompletePoset(DiGraph({0: [1, 2], 1: [3], 2: [3], 3: []}))\n sage: P.hook_product()\n 12\n sage: P = DCompletePoset(posets.YoungDiagramPoset(Partition([3,2,1]), # optional - sage.combinat\n ....: dual=True))\n sage: P.hook_product() # optional - sage.combinat\n 45\n '
if (not self._hasse_diagram):
return ZZ.one()
return ZZ(prod(self._hooks.values()))
|
class PosetElement(Element):
def __init__(self, poset, element, vertex):
'\n Establish the parent-child relationship between ``poset``\n and ``element``, where ``element`` is associated to the\n vertex ``vertex`` of the Hasse diagram of the poset.\n\n INPUT:\n\n - ``poset`` -- a poset object\n\n - ``element`` -- any object\n\n - ``vertex`` -- a vertex of the Hasse diagram of the poset\n\n TESTS::\n\n sage: from sage.combinat.posets.elements import PosetElement\n sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n sage: e = P(0)\n sage: e.parent() is P\n True\n sage: TestSuite(e).run()\n '
Element.__init__(self, poset)
if isinstance(element, self.parent().element_class):
self.element = element.element
else:
self.element = element
self.vertex = vertex
def __hash__(self):
'\n TESTS::\n\n sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n sage: e = P(0)\n sage: hash(e)\n 0\n '
return hash(self.element)
def _repr_(self):
"\n TESTS::\n\n sage: Poset([[1,2],[4],[3],[4],[]], facade = False)(0)._repr_()\n '0'\n "
return ('%s' % str(self.element))
def _latex_(self):
"\n Return the latex code of the poset element.\n\n EXAMPLES::\n\n sage: m = matrix(2, [1,2,3,4])\n sage: m.set_immutable()\n sage: P = Poset(([m],[]), facade=False)\n sage: [e] = P\n sage: type(e)\n <class 'sage.combinat.posets.posets.FinitePoset_with_category.element_class'>\n sage: latex(e) #indirect doctest\n \\left(\\begin{array}{rr}\n 1 & 2 \\\\\n 3 & 4\n \\end{array}\\right)\n "
from sage.misc.latex import latex
return latex(self.element)
def __eq__(self, other):
'\n TESTS::\n\n sage: P = Poset([["a","b"],["d"],["c"],["d"],[]], facade = False)\n sage: Q = Poset([["a","b"],["d"],["c"],[],[]], facade = False)\n sage: P(0).__eq__(P(4))\n False\n sage: from sage.combinat.posets.elements import PosetElement\n sage: PosetElement(P,0,"c") == PosetElement(P,0,"c")\n True\n sage: PosetElement(P,0,"c") == PosetElement(Q,0,"c")\n False\n sage: PosetElement(P,0,"b") == PosetElement(P,0,"c")\n False\n\n .. warning:: as an optimization, this only compares the parent\n and vertex, using the invariant that, in a proper poset\n element, ``self.element == other.element`` if and only\n ``self.vertex == other.vertex``::\n\n sage: PosetElement(P,1,"c") == PosetElement(P,0,"c")\n True\n\n Test that :trac:`12351` is fixed::\n\n sage: P(0) == int(0)\n False\n '
return (have_same_parent(self, other) and (self.vertex == other.vertex))
def __ne__(self, other):
'\n TESTS::\n\n sage: P = Poset([[1,2],[4],[3],[4],[]])\n sage: P = Poset([["a","b"],["d"],["c"],["d"],[]])\n sage: P(0).__ne__(P(4))\n True\n sage: from sage.combinat.posets.elements import PosetElement\n sage: PosetElement(P,0,"c") != PosetElement(P,0,"c")\n False\n sage: PosetElement(P,0,"b") != PosetElement(P,0,"c")\n True\n\n For this one, see comment in :meth:`__eq__`::\n\n sage: PosetElement(P,1,"c") != PosetElement(P,0,"c")\n False\n '
return (not (self == other))
def _cmp(self, other):
'\n TESTS::\n\n sage: P = Poset([[1,2],[4],[3],[4],[]], facade = False)\n sage: P(0)._cmp(P(4))\n -1\n sage: P(4)._cmp(P(0))\n 1\n sage: P(0)._cmp(P(0))\n 0\n sage: P(1)._cmp(P(2))\n\n '
return self.parent().compare_elements(self, other)
def __lt__(self, other):
'\n TESTS\n\n ::\n\n sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: P = Poset(dag, facade = False)\n sage: P(0) < P(1)\n False\n sage: P(4) < P(1)\n False\n sage: P(0) < P(0)\n False\n '
return ((self._cmp(other) == (- 1)) or False)
def __le__(self, other):
'\n TESTS\n\n ::\n\n sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: P = Poset(dag, facade = False)\n sage: P(1) <= P(0)\n False\n sage: P(0) <= P(1)\n False\n sage: P(0) <= P(3)\n True\n sage: P(0) <= P(0)\n True\n '
return ((self == other) or (self._cmp(other) == (- 1)) or False)
def __gt__(self, other):
'\n TESTS\n\n ::\n\n sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: P = Poset(dag)\n sage: P(0).__gt__(P(5))\n False\n sage: P(5).__gt__(P(0))\n True\n sage: P(0).__gt__(P(0))\n False\n '
return ((self._cmp(other) == 1) or False)
def __ge__(self, other):
'\n TESTS\n\n ::\n\n sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: P = Poset(dag)\n sage: P(0).__ge__(P(5))\n False\n sage: P(5).__ge__(P(0))\n True\n sage: P(0).__ge__(P(0))\n True\n '
return ((self == other) or (self._cmp(other) == 1) or False)
|
class MeetSemilatticeElement(PosetElement):
def __mul__(self, other):
'\n Return the meet of ``self`` and ``other`` in the lattice.\n\n EXAMPLES::\n\n sage: D = posets.DiamondPoset(5, facade=False)\n sage: D(1) * D(2)\n 0\n sage: D(1) * D(1)\n 1\n sage: D(1) * D(0)\n 0\n sage: D(1) * D(4)\n 1\n '
return self.parent().meet(self, other)
|
class JoinSemilatticeElement(PosetElement):
def __add__(self, other):
'\n Return the join of ``self`` and ``other`` in the lattice.\n\n EXAMPLES::\n\n sage: D = posets.DiamondPoset(5,facade=False)\n sage: D(1) + D(2)\n 4\n sage: D(1) + D(1)\n 1\n sage: D(1) + D(4)\n 4\n sage: D(1) + D(0)\n 1\n '
return self.parent().join(self, other)
|
class LatticePosetElement(MeetSemilatticeElement, JoinSemilatticeElement):
pass
|
class ForestPoset(FinitePoset):
'\n A forest poset is a poset where the underlying Hasse diagram and is\n directed acyclic graph.\n '
_lin_ext_type = LinearExtensionsOfForest
_desc = 'Finite forest poset'
|
class LatticeError(ValueError):
'\n Helper exception class to forward elements without meet or\n join to upper level, so that the user will see "No meet for\n a and b" instead of "No meet for 1 and 2".\n '
def __init__(self, fail, x, y):
"\n Initialize the exception.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import LatticeError\n sage: error = LatticeError('join', 3, 8)\n sage: error.x\n 3\n "
ValueError.__init__(self, None)
self.fail = fail
self.x = x
self.y = y
def __str__(self):
"\n Return string representation of the exception.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import LatticeError\n sage: error = LatticeError('meet', 15, 18)\n sage: error.__str__()\n 'no meet for 15 and 18'\n "
return 'no {} for {} and {}'.format(self.fail, self.x, self.y)
|
class HasseDiagram(DiGraph):
'\n The Hasse diagram of a poset. This is just a transitively-reduced,\n directed, acyclic graph without loops or multiple edges.\n\n .. note::\n\n We assume that ``range(n)`` is a linear extension of the poset.\n That is, ``range(n)`` is the vertex set and a topological sort of\n the digraph.\n\n This should not be called directly, use Poset instead; all type\n checking happens there.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]}); H\n Hasse diagram of a poset containing 4 elements\n sage: TestSuite(H).run()\n '
def _repr_(self):
"\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})\n sage: H._repr_()\n 'Hasse diagram of a poset containing 4 elements'\n "
return ('Hasse diagram of a poset containing %s elements' % self.order())
def linear_extension(self):
'\n Return a linear extension\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})\n sage: H.linear_extension()\n [0, 1, 2, 3]\n '
return list(range(len(self)))
def linear_extensions(self):
'\n Return an iterator over all linear extensions.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})\n sage: list(H.linear_extensions()) # optional - sage.modules\n [[0, 1, 2, 3], [0, 2, 1, 3]]\n '
from sage.combinat.posets.linear_extension_iterator import linear_extension_iterator
return linear_extension_iterator(self)
def greedy_linear_extensions_iterator(self):
'\n Return an iterator over greedy linear extensions of the Hasse diagram.\n\n A linear extension `[e_1, e_2, \\ldots, e_n]` is *greedy* if for\n every `i` either `e_{i+1}` covers `e_i` or all upper covers\n of `e_i` have at least one lower cover that is not in\n `[e_1, e_2, \\ldots, e_i]`.\n\n Informally said a linear extension is greedy if it "always\n goes up when possible" and so has no unnecessary jumps.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: N5 = HasseDiagram({0: [1, 2], 2: [3], 1: [4], 3: [4]})\n sage: for l in N5.greedy_linear_extensions_iterator():\n ....: print(l)\n [0, 1, 2, 3, 4]\n [0, 2, 3, 1, 4]\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: list(HasseDiagram({}).greedy_linear_extensions_iterator())\n [[]]\n sage: H = HasseDiagram({0: []})\n sage: list(H.greedy_linear_extensions_iterator())\n [[0]]\n '
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):
'\n Return an iterator over supergreedy linear extensions of the Hasse diagram.\n\n A linear extension `[e_1, e_2, \\ldots, e_n]` is *supergreedy* if,\n for every `i` and `j` where `i > j`, `e_i` covers `e_j` if for\n every `i > k > j` at least one lower cover of `e_k` is not in\n `[e_1, e_2, \\ldots, e_k]`.\n\n Informally said a linear extension is supergreedy if it "always\n goes as high possible, and withdraw so less as possible".\n These are also called depth-first linear extensions.\n\n EXAMPLES:\n\n We show the difference between "only greedy" and supergreedy\n extensions::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 2: [3, 4]})\n sage: G_ext = list(H.greedy_linear_extensions_iterator())\n sage: SG_ext = list(H.supergreedy_linear_extensions_iterator())\n sage: [0, 2, 3, 1, 4] in G_ext\n True\n sage: [0, 2, 3, 1, 4] in SG_ext\n False\n\n sage: len(SG_ext)\n 4\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: list(HasseDiagram({}).supergreedy_linear_extensions_iterator())\n [[]]\n sage: list(HasseDiagram({0: [], 1: []}).supergreedy_linear_extensions_iterator())\n [[0, 1], [1, 0]]\n '
N = self.order()
def supergreedy_rec(H, linext):
k = len(linext)
if (k == N):
(yield linext)
else:
S = []
while (not S):
if (not k):
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:
'\n Test if an ordering is a linear extension.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})\n sage: H.is_linear_extension(list(range(4)))\n True\n sage: H.is_linear_extension([3,2,1,0])\n False\n '
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):
'\n Iterate over cover relations.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: list(H.cover_relations_iterator())\n [(0, 2), (0, 3), (1, 3), (1, 4), (2, 5), (3, 5), (4, 5)]\n '
(yield from self.edge_iterator(labels=False))
def cover_relations(self):
'\n Return the list of cover relations.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: H.cover_relations()\n [(0, 2), (0, 3), (1, 3), (1, 4), (2, 5), (3, 5), (4, 5)]\n '
return list(self.cover_relations_iterator())
def is_lequal(self, i, j) -> bool:
'\n Return ``True`` if i is less than or equal to j in the poset, and\n ``False`` otherwise.\n\n .. note::\n\n If the :meth:`lequal_matrix` has been computed, then this method is\n redefined to use the cached data (see :meth:`_alternate_is_lequal`).\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: x,y,z = 0, 1, 4\n sage: H.is_lequal(x,y)\n False\n sage: H.is_lequal(y,x)\n False\n sage: H.is_lequal(x,z)\n True\n sage: H.is_lequal(y,z)\n True\n sage: H.is_lequal(z,z)\n True\n '
return ((i == j) or ((i < j) and (j in self.breadth_first_search(i))))
def is_less_than(self, x, y) -> bool:
'\n Return ``True`` if ``x`` is less than but not equal to ``y`` in the\n poset, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: x,y,z = 0, 1, 4\n sage: H.is_less_than(x,y)\n False\n sage: H.is_less_than(y,x)\n False\n sage: H.is_less_than(x,z)\n True\n sage: H.is_less_than(y,z)\n True\n sage: H.is_less_than(z,z)\n False\n '
if (x == y):
return False
return self.is_lequal(x, y)
def is_gequal(self, x, y) -> bool:
'\n Return ``True`` if ``x`` is greater than or equal to ``y``, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: Q = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: x,y,z = 0,1,4\n sage: Q.is_gequal(x,y)\n False\n sage: Q.is_gequal(y,x)\n False\n sage: Q.is_gequal(x,z)\n False\n sage: Q.is_gequal(z,x)\n True\n sage: Q.is_gequal(z,y)\n True\n sage: Q.is_gequal(z,z)\n True\n '
return self.is_lequal(y, x)
def is_greater_than(self, x, y) -> bool:
'\n Return ``True`` if ``x`` is greater than but not equal to\n ``y``, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: Q = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: x,y,z = 0,1,4\n sage: Q.is_greater_than(x,y)\n False\n sage: Q.is_greater_than(y,x)\n False\n sage: Q.is_greater_than(x,z)\n False\n sage: Q.is_greater_than(z,x)\n True\n sage: Q.is_greater_than(z,y)\n True\n sage: Q.is_greater_than(z,z)\n False\n '
return self.is_less_than(y, x)
def minimal_elements(self):
'\n Return a list of the minimal elements of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P(0) in P.minimal_elements()\n True\n sage: P(1) in P.minimal_elements()\n True\n sage: P(2) in P.minimal_elements()\n True\n '
return self.sources()
def maximal_elements(self):
'\n Return a list of the maximal elements of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P.maximal_elements()\n [4]\n '
return self.sinks()
@cached_method
def bottom(self):
'\n Return the bottom element of the poset, if it exists.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P.bottom() is None\n True\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.bottom()\n 0\n '
min_elms = self.minimal_elements()
if (len(min_elms) == 1):
return min_elms[0]
return None
def has_bottom(self) -> bool:
'\n Return ``True`` if the poset has a unique minimal element.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P.has_bottom()\n False\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.has_bottom()\n True\n '
return (self.bottom() is not None)
def top(self):
'\n Return the top element of the poset, if it exists.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})\n sage: P.top() is None\n True\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.top()\n 1\n '
max_elms = self.maximal_elements()
if (len(max_elms) == 1):
return max_elms[0]
return None
def has_top(self) -> bool:
'\n Return ``True`` if the poset contains a unique maximal element, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})\n sage: P.has_top()\n False\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.has_top()\n True\n '
return (self.top() is not None)
def is_bounded(self) -> bool:
'\n Return ``True`` if the poset contains a unique maximal element and a\n unique minimal element, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})\n sage: P.is_bounded()\n False\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.is_bounded()\n True\n '
return (self.has_top() and self.has_bottom())
def is_chain(self) -> bool:
'\n Return ``True`` if the poset is totally ordered, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: L = Poset({0:[1],1:[2],2:[3],3:[4]})\n sage: L.is_chain()\n True\n sage: V = Poset({0:[1,2]})\n sage: V.is_chain()\n False\n\n TESTS:\n\n Check :trac:`15330`::\n\n sage: p = Poset(DiGraph({0:[1],2:[1]}))\n sage: p.is_chain()\n False\n '
if (self.cardinality() == 0):
return True
return (((self.num_edges() + 1) == self.num_verts()) and 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:
'\n Return ``True`` if ``elms`` is an antichain of the Hasse\n diagram and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})\n sage: H.is_antichain_of_poset([1, 2, 3])\n True\n sage: H.is_antichain_of_poset([0, 2, 3])\n False\n '
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):
'\n Return a poset that is dual to the given poset.\n\n This means that it has the same elements but opposite order.\n The elements are renumbered to ensure that ``range(n)``\n is a linear extension.\n\n EXAMPLES::\n\n sage: P = posets.IntegerPartitions(4) # optional - sage.combinat\n sage: H = P._hasse_diagram; H # optional - sage.combinat\n Hasse diagram of a poset containing 5 elements\n sage: H.dual() # optional - sage.combinat\n Hasse diagram of a poset containing 5 elements\n\n TESTS::\n\n sage: H = posets.IntegerPartitions(4)._hasse_diagram # optional - sage.combinat\n sage: H.is_isomorphic( H.dual().dual() ) # optional - sage.combinat\n True\n sage: H.is_isomorphic( H.dual() ) # optional - sage.combinat\n False\n '
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):
'\n Precompute all intervals of the poset.\n\n This will significantly speed up computing congruences. On the\n other hand, it will cost much more memory. Currently this is\n a hidden feature. See the example below for how to use it.\n\n EXAMPLES::\n\n sage: B4 = posets.BooleanLattice(4)\n sage: B4.is_isoform() # Slow # optional - sage.combinat\n True\n sage: B4._hasse_diagram._precompute_intervals()\n sage: B4 = posets.BooleanLattice(4)\n sage: B4.is_isoform() # Faster now # optional - sage.combinat\n True\n '
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):
'\n Return a list of the elements `z` of ``self`` such that\n `x \\leq z \\leq y`.\n\n The order is that induced by the ordering in ``self.linear_extension``.\n\n INPUT:\n\n - ``x`` -- any element of the poset\n\n - ``y`` -- any element of the poset\n\n .. NOTE::\n\n The method :meth:`_precompute_intervals()` creates a cache\n which is used if available, making the function very fast.\n\n .. SEEALSO:: :meth:`interval_iterator`\n\n EXAMPLES::\n\n sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]\n sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram(dag)\n sage: I = set([2,5,6,4,7])\n sage: I == set(H.interval(2,7))\n True\n '
try:
return self._intervals[x][y]
except AttributeError:
return list(self.interval_iterator(x, y))
def interval_iterator(self, x, y):
'\n Return an iterator of the elements `z` of ``self`` such that\n `x \\leq z \\leq y`.\n\n INPUT:\n\n - ``x`` -- any element of the poset\n\n - ``y`` -- any element of the poset\n\n .. SEEALSO:: :meth:`interval`\n\n .. NOTE::\n\n This becomes much faster when first calling :meth:`_leq_storage`,\n which precomputes the principal upper ideals.\n\n EXAMPLES::\n\n sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]\n sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram(dag)\n sage: I = set([2,5,6,4,7])\n sage: I == set(H.interval_iterator(2,7))\n True\n '
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):
'\n Return a list of the elements `z` of ``self`` such that `x < z < y`.\n\n The order is that induced by the ordering in ``self.linear_extension``.\n\n EXAMPLES::\n\n sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]\n sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram(dag)\n sage: set([5,6,4]) == set(H.open_interval(2,7))\n True\n sage: H.open_interval(7,2)\n []\n '
ci = self.interval(x, y)
if (not ci):
return []
else:
return ci[1:(- 1)]
def rank_function(self):
'\n Return the (normalized) rank function of the poset,\n if it exists.\n\n A *rank function* of a poset `P` is a function `r`\n that maps elements of `P` to integers and satisfies:\n `r(x) = r(y) + 1` if `x` covers `y`. The function `r`\n is normalized such that its minimum value on every\n connected component of the Hasse diagram of `P` is\n `0`. This determines the function `r` uniquely (when\n it exists).\n\n OUTPUT:\n\n - a lambda function, if the poset admits a rank function\n - ``None``, if the poset does not admit a rank function\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: P.rank_function() is not None\n True\n sage: P = Poset(([1,2,3,4],[[1,4],[2,3],[3,4]]), facade = True)\n sage: P.rank_function() is not None\n True\n sage: P = Poset(([1,2,3,4,5],[[1,2],[2,3],[3,4],[1,5],[5,4]]), facade = True)\n sage: P.rank_function() is not None\n False\n sage: P = Poset(([1,2,3,4,5,6,7,8],[[1,4],[2,3],[3,4],[5,7],[6,7]]), facade = True)\n sage: f = P.rank_function(); f is not None\n True\n sage: f(5)\n 0\n sage: f(2)\n 0\n\n TESTS::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: r = P.rank_function()\n sage: for u,v in P.cover_relations_iterator():\n ....: if r(v) != r(u) + 1:\n ....: print("Bug in rank_function!")\n\n ::\n\n sage: Q = Poset([[1,2],[4],[3],[4],[]])\n sage: Q.rank_function() is None\n True\n\n test for issue :trac:`14006`::\n\n sage: H = Poset()._hasse_diagram\n sage: s = dumps(H)\n sage: f = H.rank_function()\n sage: s = dumps(H)\n '
if (self._rank is None):
return None
return self._rank.__getitem__
@lazy_attribute
def _rank(self):
'\n Build the rank function of the poset, if it exists, i.e.\n an array ``d`` where ``d[object] = self.rank_function()(object)``\n\n A *rank function* of a poset `P` is a function `r`\n that maps elements of `P` to integers and satisfies:\n `r(x) = r(y) + 1` if `x` covers `y`. The function `r`\n is normalized such that its minimum value on every\n connected component of the Hasse diagram of `P` is\n `0`. This determines the function `r` uniquely (when\n it exists).\n\n EXAMPLES::\n\n sage: H = Poset()._hasse_diagram\n sage: H._rank\n []\n sage: H = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])._hasse_diagram\n sage: H._rank\n [0, 1, 1, 2, 2, 1, 2, 3]\n sage: H = Poset(([1,2,3,4,5],[[1,2],[2,3],[3,4],[1,5],[5,4]]))._hasse_diagram\n sage: H._rank is None\n True\n '
rank = ([None] * self.order())
not_found = set(self.vertex_iterator())
while not_found:
y = not_found.pop()
rank[y] = 0
component = set([y])
queue = set([y])
while queue:
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
m = min((rank[j] for j in component))
for j in component:
rank[j] -= m
not_found.difference_update(component)
return rank
def rank(self, element=None):
'\n Return the rank of ``element``, or the rank of the poset if\n ``element`` is ``None``. (The rank of a poset is the length of\n the longest chain of elements of the poset.)\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.rank(5)\n 2\n sage: H.rank()\n 3\n sage: Q = HasseDiagram({0:[1,2],1:[3],2:[],3:[]})\n sage: Q.rank()\n 2\n sage: Q.rank(1)\n 1\n '
if (element is None):
return (len(self.level_sets()) - 1)
else:
return self.rank_function()(element)
def is_ranked(self) -> bool:
'\n Return ``True`` if the poset is ranked, and ``False`` otherwise.\n\n A poset is *ranked* if it admits a rank function. For more information\n about the rank function, see :meth:`~rank_function`\n and :meth:`~is_graded`.\n\n EXAMPLES::\n\n sage: P = Poset([[1],[2],[3],[4],[]])\n sage: P.is_ranked()\n True\n sage: Q = Poset([[1,5],[2,6],[3],[4],[],[6,3],[4]])\n sage: Q.is_ranked()\n False\n '
return bool(self.rank_function())
def covers(self, x, y):
'\n Return ``True`` if y covers x and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: Q = Poset([[1,5],[2,6],[3],[4],[],[6,3],[4]])\n sage: Q.covers(Q(1),Q(6))\n True\n sage: Q.covers(Q(1),Q(4))\n False\n '
return self.has_edge(x, y)
def upper_covers_iterator(self, element):
'\n Return the list of elements that cover ``element``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: list(H.upper_covers_iterator(0))\n [1, 2, 3]\n sage: list(H.upper_covers_iterator(7))\n []\n '
(yield from self.neighbor_out_iterator(element))
def lower_covers_iterator(self, element):
'\n Return the list of elements that are covered by ``element``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: list(H.lower_covers_iterator(0))\n []\n sage: list(H.lower_covers_iterator(4))\n [1, 2]\n '
(yield from self.neighbor_in_iterator(element))
def cardinality(self):
'\n Return the number of elements in the poset.\n\n EXAMPLES::\n\n sage: Poset([[1,2,3],[4],[4],[4],[]]).cardinality()\n 5\n\n TESTS:\n\n For a time, this function was named ``size()``, which\n would override the same-named method of the underlying\n digraph. :trac:`8735` renamed this method to ``cardinality()``\n with a deprecation warning. :trac:`11214` removed the warning\n since code for graphs was raising the warning inadvertently.\n This tests that ``size()`` for a Hasse diagram returns the\n number of edges in the digraph. ::\n\n sage: L = posets.BooleanLattice(5)\n sage: H = L.hasse_diagram()\n sage: H.size()\n 80\n sage: H.size() == H.num_edges()\n True\n '
return self.order()
def moebius_function(self, i, j):
'\n Return the value of the Möbius function of the poset\n on the elements ``i`` and ``j``.\n\n EXAMPLES::\n\n sage: P = Poset([[1,2,3],[4],[4],[4],[]])\n sage: H = P._hasse_diagram\n sage: H.moebius_function(0,4)\n 2\n sage: for u,v in P.cover_relations_iterator():\n ....: if P.moebius_function(u,v) != -1:\n ....: print("Bug in moebius_function!")\n '
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):
'\n Return the value of the Möbius function of the poset\n on the elements ``zero`` and ``j``, where ``zero`` is\n ``self.bottom()``, the unique minimal element of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1,2]})\n sage: hasse = P._hasse_diagram\n sage: hasse.bottom_moebius_function(1)\n -1\n sage: hasse.bottom_moebius_function(2)\n -1\n sage: P = Poset({0: [1,3], 1:[2], 2:[4], 3:[4]})\n sage: hasse = P._hasse_diagram\n sage: for i in range(5):\n ....: print(hasse.bottom_moebius_function(i))\n 1\n -1\n 0\n -1\n 1\n\n TESTS::\n\n sage: P = Poset({0:[2], 1:[2]})\n sage: hasse = P._hasse_diagram\n sage: hasse.bottom_moebius_function(1)\n Traceback (most recent call last):\n ...\n ValueError: the poset does not have a bottom element\n '
zero = self.bottom()
if (zero is None):
raise ValueError('the poset does not have a bottom element')
try:
return self._moebius_function_values[(zero, j)]
except AttributeError:
self._moebius_function_values = {}
return self.bottom_moebius_function(j)
except KeyError:
if (zero == j):
self._moebius_function_values[(zero, j)] = 1
else:
ci = self._backend.depth_first_search(j, reverse=True)
next(ci)
self._moebius_function_values[(zero, j)] = (- sum((self.bottom_moebius_function(k) for k in ci)))
return self._moebius_function_values[(zero, j)]
def moebius_function_matrix(self, algorithm='cython'):
"\n Return the matrix of the Möbius function of this poset.\n\n This returns the matrix over `\\ZZ` whose ``(x, y)`` entry\n is the value of the Möbius function of ``self`` evaluated on\n ``x`` and ``y``, and redefines :meth:`moebius_function` to use it.\n\n INPUT:\n\n - ``algorithm`` -- optional, ``'recursive'``, ``'matrix'``\n or ``'cython'`` (default)\n\n This uses either the recursive formula, a generic matrix inversion\n or a specific matrix inversion coded in Cython.\n\n OUTPUT:\n\n a dense matrix for the algorithm ``cython``, a sparse matrix otherwise\n\n .. NOTE::\n\n The result is cached in :meth:`_moebius_function_matrix`.\n\n .. SEEALSO:: :meth:`lequal_matrix`, :meth:`coxeter_transformation`\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.moebius_function_matrix() # optional - sage.libs.flint sage.modules\n [ 1 -1 -1 -1 1 0 1 0]\n [ 0 1 0 0 -1 0 0 0]\n [ 0 0 1 0 -1 -1 -1 2]\n [ 0 0 0 1 0 0 -1 0]\n [ 0 0 0 0 1 0 0 -1]\n [ 0 0 0 0 0 1 0 -1]\n [ 0 0 0 0 0 0 1 -1]\n [ 0 0 0 0 0 0 0 1]\n\n TESTS::\n\n sage: # needs sage.modules sage.libs.flint\n sage: H.moebius_function_matrix().is_immutable()\n True\n sage: hasattr(H,'_moebius_function_matrix')\n True\n sage: H.moebius_function == H._moebius_function_from_matrix\n True\n sage: H = posets.TamariLattice(3)._hasse_diagram\n sage: M = H.moebius_function_matrix('matrix'); M\n [ 1 -1 -1 0 1]\n [ 0 1 0 0 -1]\n [ 0 0 1 -1 0]\n [ 0 0 0 1 -1]\n [ 0 0 0 0 1]\n sage: _ = H.__dict__.pop('_moebius_function_matrix')\n sage: H.moebius_function_matrix('cython') == M\n True\n sage: _ = H.__dict__.pop('_moebius_function_matrix')\n sage: H.moebius_function_matrix('recursive') == M\n True\n sage: _ = H.__dict__.pop('_moebius_function_matrix')\n sage: H.moebius_function_matrix('banana')\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm\n "
if (not hasattr(self, '_moebius_function_matrix')):
if (algorithm == 'recursive'):
n = self.cardinality()
gt = self._leq_storage
greater_than = [sorted(gt[i]) for i in range(n)]
m = {}
for i in range((n - 1), (- 1), (- 1)):
m[(i, i)] = ZZ.one()
available = []
for k in greater_than[i]:
if (k != i):
available.append(k)
m[(i, k)] = (- ZZ.sum((m[(j, k)] for j in available if (k in greater_than[j]))))
M = matrix(ZZ, n, n, m, sparse=True)
elif (algorithm == 'matrix'):
M = self.lequal_matrix().inverse_of_unit()
elif (algorithm == 'cython'):
M = moebius_matrix_fast(self._leq_storage)
else:
raise ValueError('unknown algorithm')
self._moebius_function_matrix = M
self._moebius_function_matrix.set_immutable()
self.moebius_function = self._moebius_function_from_matrix
return self._moebius_function_matrix
def _moebius_function_from_matrix(self, i, j):
'\n Return the value of the Möbius function of the poset\n on the elements ``i`` and ``j``.\n\n EXAMPLES::\n\n sage: P = Poset([[1,2,3],[4],[4],[4],[]])\n sage: H = P._hasse_diagram\n sage: H.moebius_function(0,4) # indirect doctest\n 2\n sage: for u,v in P.cover_relations_iterator():\n ....: if P.moebius_function(u,v) != -1:\n ....: print("Bug in moebius_function!")\n\n This uses ``self._moebius_function_matrix``, as computed by\n :meth:`moebius_function_matrix`.\n '
return self._moebius_function_matrix[(i, j)]
@cached_method
def coxeter_transformation(self, algorithm='cython'):
'\n Return the matrix of the Auslander-Reiten translation acting on\n the Grothendieck group of the derived category of modules on the\n poset, in the basis of simple modules.\n\n INPUT:\n\n - ``algorithm`` -- optional, ``\'cython\'`` (default) or ``\'matrix\'``\n\n This uses either a specific matrix code in Cython, or generic matrices.\n\n .. SEEALSO:: :meth:`lequal_matrix`, :meth:`moebius_function_matrix`\n\n EXAMPLES::\n\n sage: # needs sage.libs.flint sage.modules\n sage: P = posets.PentagonPoset()._hasse_diagram\n sage: M = P.coxeter_transformation(); M\n [ 0 0 0 0 -1]\n [ 0 0 0 1 -1]\n [ 0 1 0 0 -1]\n [-1 1 1 0 -1]\n [-1 1 0 1 -1]\n sage: P.__dict__[\'coxeter_transformation\'].clear_cache()\n sage: P.coxeter_transformation(algorithm="matrix") == M\n True\n\n TESTS::\n\n sage: # needs sage.libs.flint sage.modules\n sage: P = posets.PentagonPoset()._hasse_diagram\n sage: M = P.coxeter_transformation()\n sage: M**8 == 1\n True\n sage: P.__dict__[\'coxeter_transformation\'].clear_cache()\n sage: P.coxeter_transformation(algorithm="banana")\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm\n '
if (algorithm == 'matrix'):
return ((- self.lequal_matrix()) * self.moebius_function_matrix().transpose())
elif (algorithm == 'cython'):
return coxeter_matrix_fast(self._leq_storage)
else:
raise ValueError('unknown algorithm')
def order_filter(self, elements):
'\n Return the order filter generated by a list of elements.\n\n `I` is an order filter if, for any `x` in `I` and `y` such that\n `y \\ge x`, then `y` is in `I`.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.order_filter([3,8])\n [3, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n '
return sorted(self.depth_first_search(elements))
def principal_order_filter(self, i):
'\n Return the order filter generated by ``i``.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.principal_order_filter(2)\n [2, 3, 6, 7, 10, 11, 14, 15]\n '
return self.order_filter([i])
def order_ideal(self, elements):
'\n Return the order ideal generated by a list of elements.\n\n `I` is an order ideal if, for any `x` in `I` and `y` such that\n `y \\le x`, then `y` is in `I`.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.order_ideal([7,10])\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]\n '
return sorted(self.depth_first_search(elements, neighbors=self.neighbor_in_iterator))
def order_ideal_cardinality(self, elements):
'\n Return the cardinality of the order ideal generated by ``elements``.\n\n `I` is an order ideal if, for any `x` in `I` and `y` such that\n `y \\le x`, then `y` is in `I`.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.order_ideal_cardinality([7,10])\n 10\n '
seen = set()
q = deque(elements)
size = 0
while q:
v = q.popleft()
if (v in seen):
continue
size += 1
seen.add(v)
q.extend(self.neighbor_in_iterator(v))
return ZZ(size)
def principal_order_ideal(self, i):
'\n Return the order ideal generated by `i`.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.principal_order_ideal(6)\n [0, 2, 4, 6]\n '
return self.order_ideal([i])
@lazy_attribute
def _leq_storage(self):
'\n Store the comparison relation as a list of Python sets.\n\n The `i`-th item in the list is the set of elements greater than `i`.\n\n EXAMPLES::\n\n sage: H = posets.DiamondPoset(7)._hasse_diagram\n sage: H._leq_storage\n [{0, 1, 2, 3, 4, 5, 6}, {1, 6}, {2, 6}, {3, 6}, {4, 6}, {5, 6}, {6}]\n '
n = self.order()
greater_than = [set([i]) for i in range(n)]
for i in range((n - 1), (- 1), (- 1)):
gt = greater_than[i]
for j in self.neighbor_out_iterator(i):
gt = gt.union(greater_than[j])
greater_than[i] = gt
self.is_lequal = self._alternate_is_lequal
return greater_than
@lazy_attribute
def _leq_matrix_boolean(self):
'\n Compute a boolean matrix whose ``(i,j)`` entry is 1 if ``i``\n is less than ``j`` in the poset, and 0 otherwise; and\n redefines ``__lt__`` to use this matrix.\n\n .. SEEALSO:: :meth:`_leq_matrix`\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: H = P._hasse_diagram\n sage: M = H._leq_matrix_boolean; M # optional - sage.modules sage.rings.finite_rings\n [1 1 1 1 1 1 1 1]\n [0 1 0 1 0 0 0 1]\n [0 0 1 1 1 0 1 1]\n [0 0 0 1 0 0 0 1]\n [0 0 0 0 1 0 0 1]\n [0 0 0 0 0 1 1 1]\n [0 0 0 0 0 0 1 1]\n [0 0 0 0 0 0 0 1]\n sage: M.base_ring() # optional - sage.modules sage.rings.finite_rings\n Finite Field of size 2\n '
n = self.order()
R = GF(2)
one = R.one()
greater_than = self._leq_storage
D = {(i, j): one for i in range(n) for j in greater_than[i]}
M = matrix(R, n, n, D, sparse=True)
M.set_immutable()
return M
@lazy_attribute
def _leq_matrix(self):
'\n Compute an integer matrix whose ``(i,j)`` entry is 1 if ``i``\n is less than ``j`` in the poset, and 0 otherwise.\n\n .. SEEALSO:: :meth:`_leq_matrix_boolean`\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: H = P._hasse_diagram\n sage: M = H._leq_matrix; M # optional - sage.modules\n [1 1 1 1 1 1 1 1]\n [0 1 0 1 0 0 0 1]\n [0 0 1 1 1 0 1 1]\n [0 0 0 1 0 0 0 1]\n [0 0 0 0 1 0 0 1]\n [0 0 0 0 0 1 1 1]\n [0 0 0 0 0 0 1 1]\n [0 0 0 0 0 0 0 1]\n sage: M.base_ring() # optional - sage.modules\n Integer Ring\n '
n = self.order()
greater_than = self._leq_storage
D = {(i, j): 1 for i in range(n) for j in greater_than[i]}
return matrix(ZZ, n, n, D, sparse=True, immutable=True)
def lequal_matrix(self, boolean=False):
'\n Return a matrix whose ``(i,j)`` entry is 1 if ``i`` is less\n than ``j`` in the poset, and 0 otherwise; and redefines\n ``__lt__`` to use the boolean version of this matrix.\n\n INPUT:\n\n - ``boolean`` -- optional flag (default ``False``) telling whether to\n return a matrix with coefficients in `\\GF(2)` or in `\\ZZ`\n\n .. SEEALSO::\n\n :meth:`moebius_function_matrix`, :meth:`coxeter_transformation`\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: H = P._hasse_diagram\n sage: M = H.lequal_matrix(); M # optional - sage.modules\n [1 1 1 1 1 1 1 1]\n [0 1 0 1 0 0 0 1]\n [0 0 1 1 1 0 1 1]\n [0 0 0 1 0 0 0 1]\n [0 0 0 0 1 0 0 1]\n [0 0 0 0 0 1 1 1]\n [0 0 0 0 0 0 1 1]\n [0 0 0 0 0 0 0 1]\n sage: M.base_ring() # optional - sage.modules\n Integer Ring\n\n sage: P = posets.DiamondPoset(6)\n sage: H = P._hasse_diagram\n sage: M = H.lequal_matrix(boolean=True) # optional - sage.modules sage.rings.finite_rings\n sage: M.base_ring() # optional - sage.modules sage.rings.finite_rings\n Finite Field of size 2\n\n TESTS::\n\n sage: H.lequal_matrix().is_immutable() # optional - sage.modules\n True\n '
if boolean:
return self._leq_matrix_boolean
else:
return self._leq_matrix
def _alternate_is_lequal(self, i, j):
'\n Return ``True`` if ``i`` is less than or equal to ``j`` in\n ``self``, and ``False`` otherwise.\n\n .. NOTE::\n\n If the :meth:`lequal_matrix` has been computed, then\n :meth:`is_lequal` is redefined to use the cached data.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: H.lequal_matrix() # optional - sage.modules\n [1 0 1 1 1]\n [0 1 1 1 1]\n [0 0 1 1 1]\n [0 0 0 1 1]\n [0 0 0 0 1]\n sage: x,y,z = 0, 1, 4\n sage: H._alternate_is_lequal(x,y)\n False\n sage: H._alternate_is_lequal(y,x)\n False\n sage: H._alternate_is_lequal(x,z)\n True\n sage: H._alternate_is_lequal(y,z)\n True\n sage: H._alternate_is_lequal(z,z)\n True\n '
return (j in self._leq_storage[i])
def prime_elements(self):
'\n Return the join-prime and meet-prime elements of the bounded poset.\n\n An element `x` of a poset `P` is join-prime if the subposet\n induced by `\\{y \\in P \\mid y \\not\\ge x\\}` has a top element.\n Meet-prime is defined dually.\n\n .. NOTE::\n\n The poset is expected to be bounded, and this is *not* checked.\n\n OUTPUT:\n\n A pair `(j, m)` where `j` is a list of join-prime elements\n and `m` is a list of meet-prime elements.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [4], 3: [4]})\n sage: H.prime_elements()\n ([1, 2], [2, 3])\n '
n = self.order()
join_primes = []
meet_primes = []
def add_elements(e):
upset = frozenset(self.depth_first_search(e))
meet_prime = None
for u in upset:
for m in self.neighbor_in_iterator(u):
if ((m not in upset) and all(((u_ in upset) for u_ in self.neighbor_out_iterator(m)))):
if (meet_prime is not None):
return
meet_prime = m
join_primes.append(e)
meet_primes.append(meet_prime)
for e in range(n):
if (self.in_degree(e) == 1):
add_elements(e)
return (join_primes, meet_primes)
@lazy_attribute
def _meet(self):
'\n Return the matrix of meets of ``self``.\n\n The ``(x,y)``-entry of this matrix is the meet of ``x`` and\n ``y`` in ``self`` if the meet exists; and `-1` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H._meet # optional - sage.modules\n [0 0 0 0 0 0 0 0]\n [0 1 0 0 1 0 0 1]\n [0 0 2 0 2 2 2 2]\n [0 0 0 3 0 0 3 3]\n [0 1 2 0 4 2 2 4]\n [0 0 2 0 2 5 2 5]\n [0 0 2 3 2 2 6 6]\n [0 1 2 3 4 5 6 7]\n\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H._meet # optional - sage.modules\n [ 0 -1 0 0]\n [-1 1 1 1]\n [ 0 1 2 -1]\n [ 0 1 -1 3]\n\n sage: H = HasseDiagram({0:[1,2],1:[3,4],2:[3,4]})\n sage: H._meet # optional - sage.modules\n [ 0 0 0 0 0]\n [ 0 1 0 1 1]\n [ 0 0 2 2 2]\n [ 0 1 2 3 -1]\n [ 0 1 2 -1 4]\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: L = LatticePoset({0:[1,2,3],1:[4],2:[4],3:[4]}) # optional - sage.modules\n sage: P = L.dual() # optional - sage.modules\n sage: P.meet(2,3) # optional - sage.modules\n 4\n '
self._meet_semilattice_failure = ()
n = self.cardinality()
if (n == 0):
return matrix(0)
meet = [[(- 1) for x in range(n)] for x in range(n)]
lc = [self.neighbors_in(x) for x in range(n)]
for x in range(n):
meet[x][x] = x
for y in range(x):
T = [meet[y][z] for z in lc[x] if (meet[y][z] != (- 1))]
if (not T):
q = (- 1)
else:
q = max(T)
for z in T:
if (meet[z][q] != z):
q = (- 1)
break
meet[x][y] = q
meet[y][x] = q
if (q == (- 1)):
self._meet_semilattice_failure += ((x, y),)
return matrix(ZZ, meet)
def meet_matrix(self):
'\n Return the matrix of meets of ``self``, when ``self`` is a\n meet-semilattice; raise an error otherwise.\n\n The ``(x,y)``-entry of this matrix is the meet of ``x`` and\n ``y`` in ``self``.\n\n This algorithm is modelled after the algorithm of Freese-Jezek-Nation\n (p217). It can also be found on page 140 of [Gec81]_.\n\n .. NOTE::\n\n If ``self`` is a meet-semilattice, then the return of this method\n is the same as :meth:`_meet`. Once the matrix has been computed,\n it is stored in :meth:`_meet`. Delete this attribute if you want to\n recompute the matrix.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.meet_matrix() # optional - sage.modules\n [0 0 0 0 0 0 0 0]\n [0 1 0 0 1 0 0 1]\n [0 0 2 0 2 2 2 2]\n [0 0 0 3 0 0 3 3]\n [0 1 2 0 4 2 2 4]\n [0 0 2 0 2 5 2 5]\n [0 0 2 3 2 2 6 6]\n [0 1 2 3 4 5 6 7]\n\n REFERENCE:\n\n .. [Gec81] Fundamentals of Computation Theory\n Gecseg, F.\n Proceedings of the 1981 International Fct-Conference\n Szeged, Hungaria, August 24-28, vol 117\n Springer-Verlag, 1981\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H.meet_matrix()\n Traceback (most recent call last):\n ...\n ValueError: not a meet-semilattice: no bottom element\n\n sage: H = HasseDiagram({0:[1,2],1:[3,4],2:[3,4]})\n sage: H.meet_matrix() # optional - sage.modules\n Traceback (most recent call last):\n ...\n LatticeError: no meet for ...\n '
n = self.cardinality()
if ((n != 0) and (not self.has_bottom())):
raise ValueError('not a meet-semilattice: no bottom element')
mt = self._meet
if self._meet_semilattice_failure:
(x, y) = self._meet_semilattice_failure[0]
raise LatticeError('meet', x, y)
return mt
def is_meet_semilattice(self) -> bool:
'\n Return ``True`` if ``self`` has a meet operation, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.is_meet_semilattice() # optional - sage.modules\n True\n\n sage: H = HasseDiagram({0:[1,2],1:[3],2:[3],3:[]})\n sage: H.is_meet_semilattice() # optional - sage.modules\n True\n\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H.is_meet_semilattice() # optional - sage.modules\n False\n\n sage: H = HasseDiagram({0:[1,2],1:[3,4],2:[3,4]})\n sage: H.is_meet_semilattice() # optional - sage.modules\n False\n '
try:
self.meet_matrix()
except ValueError:
return False
else:
return True
@lazy_attribute
def _join(self):
'\n Computes a matrix whose ``(x,y)``-entry is the join of ``x``\n and ``y`` in ``self`` if the join exists; and `-1` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H._join # optional - sage.modules\n [0 1 2 3 4 5 6 7]\n [1 1 4 7 4 7 7 7]\n [2 4 2 6 4 5 6 7]\n [3 7 6 3 7 7 6 7]\n [4 4 4 7 4 7 7 7]\n [5 7 5 7 7 5 7 7]\n [6 7 6 6 7 7 6 7]\n [7 7 7 7 7 7 7 7]\n\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H._join # optional - sage.modules\n [ 0 -1 2 3]\n [-1 1 2 3]\n [ 2 2 2 -1]\n [ 3 3 -1 3]\n\n sage: H = HasseDiagram({0:[2,3],1:[2,3],2:[4],3:[4]})\n sage: H._join # optional - sage.modules\n [ 0 -1 2 3 4]\n [-1 1 2 3 4]\n [ 2 2 2 4 4]\n [ 3 3 4 3 4]\n [ 4 4 4 4 4]\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: L = LatticePoset({0:[1,2,3],1:[4],2:[4],3:[4]}) # optional - sage.modules\n sage: P = L.dual() # optional - sage.modules\n sage: P.join(2,3) # optional - sage.modules\n 0\n '
self._join_semilattice_failure = ()
n = self.cardinality()
if (n == 0):
return matrix(0)
join = [[(- 1) for x in range(n)] for x in range(n)]
uc = [self.neighbors_out(x) for x in range(n)]
for x in range((n - 1), (- 1), (- 1)):
join[x][x] = x
for y in range((n - 1), x, (- 1)):
T = [join[y][z] for z in uc[x] if (join[y][z] != (- 1))]
if (not T):
q = (- 1)
else:
q = min(T)
for z in T:
if (join[z][q] != z):
q = (- 1)
break
join[x][y] = q
join[y][x] = q
if (q == (- 1)):
self._join_semilattice_failure += ((x, y),)
return matrix(ZZ, join)
def join_matrix(self):
'\n Return the matrix of joins of ``self``, when ``self`` is a\n join-semilattice; raise an error otherwise.\n\n The ``(x,y)``-entry of this matrix is the join of ``x`` and\n ``y`` in ``self``.\n\n This algorithm is modelled after the algorithm of Freese-Jezek-Nation\n (p217). It can also be found on page 140 of [Gec81]_.\n\n .. NOTE::\n\n If ``self`` is a join-semilattice, then the return of this method\n is the same as :meth:`_join`. Once the matrix has been computed,\n it is stored in :meth:`_join`. Delete this attribute if you want\n to recompute the matrix.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.join_matrix() # optional - sage.modules\n [0 1 2 3 4 5 6 7]\n [1 1 4 7 4 7 7 7]\n [2 4 2 6 4 5 6 7]\n [3 7 6 3 7 7 6 7]\n [4 4 4 7 4 7 7 7]\n [5 7 5 7 7 5 7 7]\n [6 7 6 6 7 7 6 7]\n [7 7 7 7 7 7 7 7]\n\n TESTS::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H.join_matrix()\n Traceback (most recent call last):\n ...\n ValueError: not a join-semilattice: no top element\n\n sage: H = HasseDiagram({0:[2,3],1:[2,3],2:[4],3:[4]})\n sage: H.join_matrix() # optional - sage.modules\n Traceback (most recent call last):\n ...\n LatticeError: no join for ...\n '
n = self.cardinality()
if ((n != 0) and (not self.has_top())):
raise ValueError('not a join-semilattice: no top element')
jn = self._join
if self._join_semilattice_failure:
(x, y) = self._join_semilattice_failure[0]
raise LatticeError('join', x, y)
return jn
def is_join_semilattice(self) -> bool:
'\n Return ``True`` if ``self`` has a join operation, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})\n sage: H.is_join_semilattice() # optional - sage.modules\n True\n sage: H = HasseDiagram({0:[2,3],1:[2,3]})\n sage: H.is_join_semilattice() # optional - sage.modules\n False\n sage: H = HasseDiagram({0:[2,3],1:[2,3],2:[4],3:[4]})\n sage: H.is_join_semilattice() # optional - sage.modules\n False\n '
try:
self.join_matrix()
except ValueError:
return False
else:
return True
def find_nonsemidistributive_elements(self, meet_or_join):
"\n Check if the lattice is semidistributive or not.\n\n INPUT:\n\n - ``meet_or_join`` -- string ``'meet'`` or ``'join'``\n to decide if to check for join-semidistributivity or\n meet-semidistributivity\n\n OUTPUT:\n\n - ``None`` if the lattice is semidistributive OR\n - tuple ``(u, e, x, y)`` such that\n `u = e \\vee x = e \\vee y` but `u \\neq e \\vee (x \\wedge y)`\n if ``meet_or_join=='join'`` and\n `u = e \\wedge x = e \\wedge y` but `u \\neq e \\wedge (x \\vee y)`\n if ``meet_or_join=='meet'``\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1, 2], 1:[3, 4], 2:[4, 5], 3:[6],\n ....: 4:[6], 5:[6]})\n sage: H.find_nonsemidistributive_elements('join') is None # optional - sage.modules\n False\n sage: H.find_nonsemidistributive_elements('meet') is None # optional - sage.modules\n True\n "
if (meet_or_join == 'join'):
M1 = self.join_matrix()
M2 = self.meet_matrix()
elif (meet_or_join == 'meet'):
M1 = self.meet_matrix()
M2 = self.join_matrix()
else:
raise ValueError("meet_or_join must be 'join' or 'meet'")
n = self.order()
for e in range(n):
for x in range(n):
u = M1[(e, x)]
for y in range(x):
if (u == M1[(e, y)]):
if (u != M1[(e, M2[(x, y)])]):
return (u, e, x, y)
return None
def vertical_decomposition(self, return_list=False):
'\n Return vertical decomposition of the lattice.\n\n This is the backend function for vertical decomposition\n functions of lattices.\n\n The property of being vertically decomposable is defined for lattices.\n This is *not* checked, and the function works with any bounded poset.\n\n INPUT:\n\n - ``return_list``, a boolean. If ``False`` (the default), return\n an element that is not the top neither the bottom element of the\n lattice, but is comparable to all elements of the lattice, if\n the lattice is vertically decomposable and ``None`` otherwise.\n If ``True``, return list of decomposition elements.\n\n EXAMPLES::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram\n sage: H.vertical_decomposition() is None\n True\n sage: P = Poset( ([1,2,3,6,12,18,36], attrcall("divides")) )\n sage: P._hasse_diagram.vertical_decomposition()\n 3\n sage: P._hasse_diagram.vertical_decomposition(return_list=True)\n [3]\n '
n = self.cardinality()
if (n < 3):
if return_list:
return []
else:
return None
result = []
m = 0
for i in range((n - 1)):
for j in self.outgoing_edge_iterator(i):
m = max(m, j[1])
if (m == (i + 1)):
if (not return_list):
if (m < (n - 1)):
return m
else:
return None
result.append(m)
result.pop()
return result
def is_complemented(self) -> (int | None):
'\n Return an element of the lattice that has no complement.\n\n If the lattice is complemented, return ``None``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n\n sage: H = HasseDiagram({0:[1, 2], 1:[3], 2:[3], 3:[4]})\n sage: H.is_complemented() # optional - sage.modules\n 1\n\n sage: H = HasseDiagram({0:[1, 2, 3], 1:[4], 2:[4], 3:[4]})\n sage: H.is_complemented() is None # optional - sage.modules\n True\n '
mt = self.meet_matrix()
jn = self.join_matrix()
top = (self.cardinality() - 1)
has_complement = ([False] * top)
for i in range(1, top):
if has_complement[i]:
continue
for j in range(top, 0, (- 1)):
if ((jn[(i, j)] == top) and (mt[(i, j)] == 0)):
has_complement[j] = True
break
else:
return i
return None
def pseudocomplement(self, element):
'\n Return the pseudocomplement of ``element``, if it exists.\n\n The pseudocomplement is the greatest element whose\n meet with given element is the bottom element. It may\n not exist, and then the function returns ``None``.\n\n INPUT:\n\n - ``element`` -- an element of the lattice.\n\n OUTPUT:\n\n An element of the Hasse diagram, i.e. an integer, or\n ``None`` if the pseudocomplement does not exist.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [4], 3: [4]})\n sage: H.pseudocomplement(2) # optional - sage.modules\n 3\n\n sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})\n sage: H.pseudocomplement(2) is None # optional - sage.modules\n True\n '
e = (self.order() - 1)
mt = self.meet_matrix()
while (mt[(e, element)] != 0):
e -= 1
e1 = e
while (e1 > 0):
if ((mt[(e1, element)] == 0) and (not self.is_lequal(e1, e))):
return None
e1 -= 1
return e
def orthocomplementations_iterator(self):
'\n Return an iterator over orthocomplementations of the lattice.\n\n OUTPUT:\n\n An iterator that gives plain list of integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2], 1:[3,4], 3:[5], 4:[5], 2:[6,7],\n ....: 6:[8], 7:[8], 5:[9], 8:[9]})\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n [[9, 8, 5, 6, 7, 2, 3, 4, 1, 0], [9, 8, 5, 7, 6, 2, 4, 3, 1, 0]]\n\n ALGORITHM:\n\n As ``DiamondPoset(2*n+2)`` has `(2n)!/(n!2^n)` different\n orthocomplementations, the complexity of listing all of\n them is necessarily `O(n!)`.\n\n An orthocomplemented lattice is self-dual, so that for example\n orthocomplement of an atom is a coatom. This function\n basically just computes list of possible orthocomplementations\n for every element (i.e. they must be complements and "duals"),\n and then tries to fit them all.\n\n TESTS:\n\n Special and corner cases::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram() # Empty\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n [[]]\n sage: H = HasseDiagram({0:[]}) # One element\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n [[0]]\n sage: H = HasseDiagram({0:[1]}) # Two elements\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n [[1, 0]]\n\n Trivial cases: odd number of elements, not self-dual, not complemented::\n\n sage: H = posets.DiamondPoset(5)._hasse_diagram\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n sage: H = posets.ChainPoset(4)._hasse_diagram\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n sage: H = HasseDiagram( ([[0, 1], [0, 2], [0, 3], [1, 4], [1, 8], [4, 6], [4, 7], [6, 9], [7, 9], [2, 5], [3, 5], [5, 8], [8, 9]]) )\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n sage: H = HasseDiagram({0:[1, 2, 3], 1: [4], 2:[4], 3: [5], 4:[5]})\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n\n Complemented, self-dual and even number of elements, but\n not orthocomplemented::\n\n sage: H = HasseDiagram( ([[0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [0, 6], [3, 7], [5, 7], [6, 7]]) )\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n\n Unique orthocomplementations; second is not uniquely complemented,\n but has only one orthocomplementation::\n\n sage: H = posets.BooleanLattice(4)._hasse_diagram # Uniquely complemented\n sage: len(list(H.orthocomplementations_iterator())) # optional - sage.groups\n 1\n sage: H = HasseDiagram({0:[1, 2], 1:[3], 2:[4], 3:[5], 4:[5]})\n sage: len([_ for _ in H.orthocomplementations_iterator()]) # optional - sage.groups\n 1\n\n "Lengthening diamond" must keep the number of orthocomplementations::\n\n sage: H = HasseDiagram( ([[0, 1], [0, 2], [0, 3], [0, 4], [1, 5], [2, 5], [3, 5], [4, 5]]) )\n sage: n = len([_ for _ in H.orthocomplementations_iterator()]); n # optional - sage.groups\n 3\n sage: H = HasseDiagram(\'M]??O?@??C??OA???OA??@?A??C?A??O??\')\n sage: len([_ for _ in H.orthocomplementations_iterator()]) == n # optional - sage.groups\n True\n\n This lattice has an unique "possible orthocomplement" for every\n element, but they can not be fit together; orthocomplement pairs\n would be 0-11, 1-7, 2-4, 3-10, 5-9 and 6-8, and then orthocomplements\n for chain 0-1-6-11 would be 11-7-8-0, which is not a chain::\n\n sage: H = HasseDiagram(\'KTGG_?AAC?O?o?@?@?E?@?@??\')\n sage: list(H.orthocomplementations_iterator()) # optional - sage.groups\n []\n '
n = self.order()
if (n == 0):
(yield [])
return
if (n == 1):
(yield [0])
return
if (n % 2):
return
dual_isomorphism = self.is_isomorphic(self.reverse(), certificate=True)[1]
if (dual_isomorphism is None):
return
orbits = self.automorphism_group(return_group=False, orbits=True)
orbit_number = ([None] * n)
for (ind, orbit) in enumerate(orbits):
for e in orbit:
orbit_number[e] = ind
comps = ([None] * n)
mt = self.meet_matrix()
jn = self.join_matrix()
for e in range(n):
comps[e] = [x for x in range(n) if ((mt[(e, x)] == 0) and (jn[(e, x)] == (n - 1)) and (x in orbits[orbit_number[dual_isomorphism[e]]]))]
def recursive_fit(orthocomplements, unbinded):
if (not unbinded):
(yield orthocomplements)
else:
next_to_fit = unbinded[0]
possible_values = [x for x in comps[next_to_fit] if (x not in orthocomplements)]
for x in self.lower_covers_iterator(next_to_fit):
if (orthocomplements[x] is not None):
possible_values = [y for y in possible_values if self.has_edge(y, orthocomplements[x])]
for x in self.upper_covers_iterator(next_to_fit):
if (orthocomplements[x] is not None):
possible_values = [y for y in possible_values if self.has_edge(orthocomplements[x], y)]
for e in possible_values:
new_binded = orthocomplements[:]
new_binded[next_to_fit] = e
new_binded[e] = next_to_fit
new_unbinded = unbinded[1:]
new_unbinded.remove(e)
(yield from recursive_fit(new_binded, new_unbinded))
start = ([None] * n)
for e in range(n):
if (not comps[e]):
return
if (len(comps[e]) == 1):
e_ = comps[e][0]
for lc in self.lower_covers_iterator(e):
if (start[lc] is not None):
if (not self.has_edge(e_, start[lc])):
return
if (start[e_] is None):
start[e] = e_
start[e_] = e
start_unbinded = [e for e in range(n) if (start[e] is None)]
(yield from recursive_fit(start, start_unbinded))
def find_nonsemimodular_pair(self, upper):
'\n Return pair of elements showing the lattice is not modular.\n\n INPUT:\n\n - ``upper``, a Boolean -- if ``True``, test whether the lattice is\n upper semimodular; otherwise test whether the lattice is\n lower semimodular.\n\n OUTPUT:\n\n ``None``, if the lattice is semimodular. Pair `(a, b)` violating\n semimodularity otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1, 2], 1:[3, 4], 2:[4, 5], 3:[6], 4:[6], 5:[6]})\n sage: H.find_nonsemimodular_pair(upper=True) is None\n True\n sage: H.find_nonsemimodular_pair(upper=False)\n (5, 3)\n\n sage: H_ = HasseDiagram(H.reverse().relabel(lambda x: 6-x, inplace=False))\n sage: H_.find_nonsemimodular_pair(upper=True)\n (3, 1)\n sage: H_.find_nonsemimodular_pair(upper=False) is None\n True\n '
if upper:
neighbors = self.neighbors_out
else:
neighbors = self.neighbors_in
n = self.order()
for e in range(n):
covers = neighbors(e)
covers_len = len(covers)
if (covers_len < 2):
continue
for a_i in range(covers_len):
a = covers[a_i]
covers_a = neighbors(a)
for b_i in range(a_i):
b = covers[b_i]
if (not any(((j in covers_a) for j in neighbors(b)))):
return (a, b)
return None
def antichains_iterator(self):
'\n Return an iterator over the antichains of the poset.\n\n .. note::\n\n The algorithm is based on Freese-Jezek-Nation p. 226.\n It does a depth first search through the set of all\n antichains organized in a prefix tree.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: H.antichains_iterator()\n <generator object ...antichains_iterator at ...>\n sage: list(H.antichains_iterator())\n [[], [4], [3], [2], [1], [1, 3], [1, 2], [0]]\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0:[1,2],1:[4],2:[3],3:[4]})\n sage: list(H.antichains_iterator())\n [[], [4], [3], [2], [1], [1, 3], [1, 2], [0]]\n sage: H = HasseDiagram({0:[],1:[],2:[]})\n sage: list(H.antichains_iterator())\n [[], [2], [1], [1, 2], [0], [0, 2], [0, 1], [0, 1, 2]]\n sage: H = HasseDiagram({0:[1],1:[2],2:[3],3:[4]})\n sage: list(H.antichains_iterator())\n [[], [4], [3], [2], [1], [0]]\n\n TESTS::\n\n sage: H = Poset()._hasse_diagram\n sage: list(H.antichains_iterator()) # optional - sage.modules\n [[]]\n '
antichains_queues = [([], list(range((self.cardinality() - 1), (- 1), (- 1))))]
leq = self.lequal_matrix()
while antichains_queues:
(antichain, queue) = antichains_queues.pop()
(yield antichain)
while queue:
x = queue.pop()
new_antichain = (antichain + [x])
new_queue = [t for t in queue if (not (leq[(t, x)] or leq[(x, t)]))]
antichains_queues.append((new_antichain, new_queue))
def are_incomparable(self, i, j):
'\n Return whether ``i`` and ``j`` are incomparable in the poset\n\n INPUT:\n\n - ``i``, ``j`` -- vertices of this Hasse diagram\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: H.are_incomparable(1,2)\n True\n sage: V = H.vertices(sort=True)\n sage: [ (i,j) for i in V for j in V if H.are_incomparable(i,j)]\n [(1, 2), (1, 3), (2, 1), (3, 1)]\n '
if (i == j):
return False
if (i > j):
(i, j) = (j, i)
mat = self._leq_matrix_boolean
return (not mat[(i, j)])
def are_comparable(self, i, j):
'\n Return whether ``i`` and ``j`` are comparable in the poset\n\n INPUT:\n\n - ``i``, ``j`` -- vertices of this Hasse diagram\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: H.are_comparable(1,2)\n False\n sage: V = H.vertices(sort=True)\n sage: [ (i,j) for i in V for j in V if H.are_comparable(i,j)]\n [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 4),\n (2, 0), (2, 2), (2, 3), (2, 4), (3, 0), (3, 2), (3, 3), (3, 4),\n (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]\n '
if (i == j):
return True
if (i > j):
(i, j) = (j, i)
mat = self._leq_matrix_boolean
return bool(mat[(i, j)])
def antichains(self, element_class=list):
'\n Return all antichains of ``self``, organized as a prefix tree\n\n INPUT:\n\n - ``element_class`` -- (default:list) an iterable type\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: A = H.antichains()\n sage: list(A)\n [[], [0], [1], [1, 2], [1, 3], [2], [3], [4]]\n sage: A.cardinality()\n 8\n sage: [1,3] in A\n True\n sage: [1,4] in A\n False\n\n TESTS::\n\n sage: # needs sage.modules\n sage: TestSuite(A).run()\n sage: A = Poset()._hasse_diagram.antichains()\n sage: list(A)\n [[]]\n sage: TestSuite(A).run()\n '
from sage.combinat.subsets_pairwise import PairwiseCompatibleSubsets
return PairwiseCompatibleSubsets(self.vertices(sort=True), self.are_incomparable, element_class=element_class)
def chains(self, element_class=list, exclude=None, conversion=None):
'\n Return all chains of ``self``, organized as a prefix tree.\n\n INPUT:\n\n - ``element_class`` -- (optional, default: ``list``) an iterable type\n\n - ``exclude`` -- elements of the poset to be excluded\n (optional, default: ``None``)\n\n - ``conversion`` -- (optional, default: ``None``) used to pass\n the list of elements of the poset in their fixed order\n\n OUTPUT:\n\n The enumerated set (with a forest structure given by prefix\n ordering) consisting of all chains of ``self``, each of\n which is given as an ``element_class``.\n\n If ``conversion`` is given, then the chains are converted\n to chain of elements of this list.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: A = H.chains()\n sage: list(A)\n [[], [0], [0, 1], [0, 1, 4], [0, 2], [0, 2, 3], [0, 2, 3, 4], [0, 2, 4],\n [0, 3], [0, 3, 4], [0, 4], [1], [1, 4], [2], [2, 3], [2, 3, 4], [2, 4],\n [3], [3, 4], [4]]\n sage: A.cardinality()\n 20\n sage: [1,3] in A\n False\n sage: [1,4] in A\n True\n\n One can exclude some vertices::\n\n sage: # needs sage.modules\n sage: list(H.chains(exclude=[4, 3]))\n [[], [0], [0, 1], [0, 2], [1], [2]]\n\n The ``element_class`` keyword determines how the chains are\n being returned::\n\n sage: P = Poset({1: [2, 3], 2: [4]})\n sage: list(P._hasse_diagram.chains(element_class=tuple))\n [(), (0,), (0, 1), (0, 1, 2), (0, 2), (0, 3), (1,), (1, 2), (2,), (3,)]\n sage: list(P._hasse_diagram.chains())\n [[], [0], [0, 1], [0, 1, 2], [0, 2], [0, 3], [1], [1, 2], [2], [3]]\n\n (Note that taking the Hasse diagram has renamed the vertices.) ::\n\n sage: list(P._hasse_diagram.chains(element_class=tuple, exclude=[0]))\n [(), (1,), (1, 2), (2,), (3,)]\n\n .. SEEALSO:: :meth:`antichains`\n '
return IncreasingChains(self._leq_storage, element_class, exclude, conversion)
def is_linear_interval(self, t_min, t_max) -> bool:
'\n Return whether the interval ``[t_min, t_max]`` is linear.\n\n This means that this interval is a total order.\n\n EXAMPLES::\n sage: # needs sage.modules\n sage: P = posets.PentagonPoset()\n sage: H = P._hasse_diagram\n sage: H.is_linear_interval(0, 4)\n False\n sage: H.is_linear_interval(0, 3)\n True\n sage: H.is_linear_interval(1, 3)\n False\n sage: H.is_linear_interval(1, 1)\n True\n\n TESTS::\n\n sage: P = posets.TamariLattice(3)\n sage: H = P._hasse_diagram\n sage: D = H._leq_storage\n sage: a, b = H.bottom(), H.top()\n sage: H.is_linear_interval(a, b)\n False\n sage: H.is_linear_interval(a, a)\n True\n '
if ('_leq_storage' in self.__dict__):
if (not self.is_lequal(t_min, t_max)):
return False
t = t_max
while (t != t_min):
found = False
for u in self.neighbor_in_iterator(t):
if self.is_lequal(t_min, u):
if (not found):
found = True
t = u
else:
return False
return True
it = self.all_paths_iterator([t_min], [t_max], simple=True, trivial=True)
try:
next(it)
except StopIteration:
return False
try:
next(it)
except StopIteration:
return True
return False
def diamonds(self):
'\n Return the list of diamonds of ``self``.\n\n A diamond is the following subgraph of the Hasse diagram::\n\n z\n / \\\n x y\n \\ /\n w\n\n Thus each edge represents a cover relation in the Hasse diagram.\n We represent his as the tuple `(w, x, y, z)`.\n\n OUTPUT:\n\n A tuple with\n\n - a list of all diamonds in the Hasse Diagram,\n - a boolean checking that every `w,x,y` that form a ``V``, there is a\n unique element `z`, which completes the diamond.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: H.diamonds()\n ([(0, 1, 2, 3)], True)\n\n sage: P = posets.YoungDiagramPoset(Partition([3, 2, 2])) # optional - sage.combinat\n sage: H = P._hasse_diagram # optional - sage.combinat\n sage: H.diamonds() # optional - sage.combinat\n ([(0, 1, 3, 4), (3, 4, 5, 6)], False)\n '
diamonds = []
all_diamonds_completed = True
for w in self.vertices(sort=True):
covers = self.neighbors_out(w)
for (i, x) in enumerate(covers):
for y in covers[(i + 1):]:
zs = self.common_upper_covers([x, y])
if (len(zs) != 1):
all_diamonds_completed = False
for z in zs:
diamonds.append((w, x, y, z))
return (diamonds, all_diamonds_completed)
def common_upper_covers(self, vertices):
'\n Return the list of all common upper covers of ``vertices``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: H.common_upper_covers([1, 2])\n [3]\n\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: H = Posets.YoungDiagramPoset(Partition([3, 2, 2]))._hasse_diagram # optional - sage.combinat\n sage: H.common_upper_covers([4, 5]) # optional - sage.combinat\n [6]\n '
covers = set(self.neighbor_out_iterator(vertices.pop()))
for v in vertices:
covers = covers.intersection(self.neighbor_out_iterator(v))
return list(covers)
def common_lower_covers(self, vertices):
'\n Return the list of all common lower covers of ``vertices``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: H.common_lower_covers([1, 2])\n [0]\n\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: H = Posets.YoungDiagramPoset(Partition([3, 2, 2]))._hasse_diagram # optional - sage.combinat\n sage: H.common_lower_covers([4, 5]) # optional - sage.combinat\n [3]\n '
covers = set(self.neighbor_in_iterator(vertices.pop()))
for v in vertices:
covers = covers.intersection(self.neighbor_in_iterator(v))
return list(covers)
def _trivial_nonregular_congruence(self):
'\n Return a pair of elements giving "trivial" non-regular congruence.\n\n This returns a pair `a, b` such that `b` covers only `a` and\n `a` is covered by only `b`, and either `a` has one lower cover\n or `b` has one upper cover. If no such pair exists, return\n ``None``.\n\n This pair gives a trivial non-regular congruence.\n\n The Hasse diagram is expected to be bounded.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [4], 2: [3], 3: [4]})\n sage: H._trivial_nonregular_congruence()\n (2, 3)\n\n TESTS::\n\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [3]})\n sage: H._trivial_nonregular_congruence() is None\n True\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [3], 3: [4]})\n sage: H._trivial_nonregular_congruence()\n (3, 4)\n sage: H = HasseDiagram({0: [1], 1: [2, 3], 2: [4], 3: [4]})\n sage: H._trivial_nonregular_congruence()\n (0, 1)\n sage: H = HasseDiagram({0: [1]})\n sage: H._trivial_nonregular_congruence() is None\n True\n '
n = self.order()
if (n == 2):
return None
if (self.out_degree(0) == 1):
return (0, 1)
if (self.in_degree((n - 1)) == 1):
return ((n - 2), (n - 1))
for v in range(1, (n - 1)):
if ((self.in_degree(v) == 1) and (self.out_degree(v) == 1)):
v_ = next(self.neighbor_out_iterator(v))
if ((self.in_degree(v_) == 1) and (self.out_degree(v_) == 1)):
return (v, v_)
return None
def sublattices_iterator(self, elms, min_e):
'\n Return an iterator over sublattices of the Hasse diagram.\n\n INPUT:\n\n - ``elms`` -- elements already in sublattice; use set() at start\n - ``min_e`` -- smallest new element to add for new sublattices\n\n OUTPUT:\n\n List of sublattices as sets of integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1:[3], 2:[3]})\n sage: it = H.sublattices_iterator(set(), 0); it\n <generator object ...sublattices_iterator at ...>\n sage: next(it) # optional - sage.modules\n set()\n sage: next(it) # optional - sage.modules\n {0}\n '
(yield elms)
mt = self.meet_matrix()
jn = self.join_matrix()
for e in range(min_e, self.cardinality()):
if (e in elms):
continue
current_set = set(elms)
gens = set([e])
while gens:
g = gens.pop()
if ((g < e) and (g not in elms)):
break
if (g in current_set):
continue
for x in current_set:
gens.add(mt[(x, g)])
gens.add(jn[(x, g)])
current_set.add(g)
else:
(yield from self.sublattices_iterator(current_set, (e + 1)))
def maximal_sublattices(self):
'\n Return maximal sublattices of the lattice.\n\n EXAMPLES::\n\n sage: L = posets.PentagonPoset() # optional - sage.modules\n sage: ms = L._hasse_diagram.maximal_sublattices() # optional - sage.modules\n sage: sorted(ms, key=sorted) # optional - sage.modules\n [{0, 1, 2, 4}, {0, 1, 3, 4}, {0, 2, 3, 4}]\n '
jn = self.join_matrix()
mt = self.meet_matrix()
def sublattice(elms, e):
'\n Helper function to get sublattice generated by list\n of elements.\n '
gens_remaining = set([e])
current_set = set(elms)
while gens_remaining:
g = gens_remaining.pop()
if (g in current_set):
continue
for x in current_set:
gens_remaining.add(jn[(x, g)])
gens_remaining.add(mt[(x, g)])
current_set.add(g)
return current_set
N = self.cardinality()
elms = [0]
sublats = [set([0])]
result = []
skip = (- 1)
while True:
found_element_to_append = False
e = elms[(- 1)]
while (e != skip):
e += 1
if (e == N):
maybe_found = sublats[(- 1)]
if (not any((maybe_found.issubset(x) for x in result))):
result.append(sublats[(- 1)])
break
if (e in sublats[(- 1)]):
continue
sl = sublattice(sublats[(- 1)], e)
if (len(sl) < N):
new_elms = sl.difference(sublats[(- 1)])
if (not any(((x < e) for x in new_elms))):
found_element_to_append = True
break
if found_element_to_append:
elms.append(e)
sublats.append(sl)
continue
e = elms.pop()
sublats.pop()
last_element_increment = True
while True:
e += 1
if (e == N):
last_element_increment = False
break
if (e in sublats[(- 1)]):
continue
sl = sublattice(sublats[(- 1)], e)
if (len(sl) == N):
continue
new_elms = sl.difference(set(sublats[(- 1)]))
if any(((x < e) for x in new_elms)):
continue
elms.append(e)
sublats.append(sl)
break
if (not last_element_increment):
skip = elms[(- 1)]
if (skip == 0):
break
if (self.out_degree(0) == 1):
result.append(set(range(1, N)))
return result
def frattini_sublattice(self):
'\n Return the list of elements of the Frattini sublattice of the lattice.\n\n EXAMPLES::\n\n sage: H = posets.PentagonPoset()._hasse_diagram # optional - sage.modules\n sage: H.frattini_sublattice() # optional - sage.modules\n [0, 4]\n '
n = self.cardinality()
if ((n == 0) or (n == 2)):
return []
if (n == 1):
return [0]
max_sublats = self.maximal_sublattices()
return [e for e in range(self.cardinality()) if all(((e in ms) for ms in max_sublats))]
def kappa_dual(self, a):
'\n Return the minimum element smaller than the element covering\n ``a`` but not smaller than ``a``.\n\n Define `\\kappa^*(a)` as the minimum element of\n `(\\downarrow a_*) \\setminus (\\downarrow a)`, where `a_*` is the element\n covering `a`. It is always a join-irreducible element, if it exists.\n\n .. NOTE::\n\n Element ``a`` is expected to be meet-irreducible, and\n this is *not* checked.\n\n INPUT:\n\n - ``a`` -- a join-irreducible element of the lattice\n\n OUTPUT:\n\n The element `\\kappa^*(a)` or ``None`` if there\n is not a unique smallest element with given constraints.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [3, 4], 2: [4, 5], 3: [6], 4: [6], 5: [6]})\n sage: H.kappa_dual(3)\n 2\n sage: H.kappa_dual(4) is None\n True\n\n TESTS::\n\n sage: H = HasseDiagram({0: [1]})\n sage: H.kappa_dual(0)\n 1\n '
uc = next(self.neighbor_out_iterator(a))
if (self.in_degree(uc) == 1):
return uc
lt_a = set(self.depth_first_search(a, neighbors=self.neighbor_in_iterator))
tmp = set(self.depth_first_search(uc, neighbors=(lambda v: [v_ for v_ in self.neighbor_in_iterator(v) if (v_ not in lt_a)])))
result = None
for e in tmp:
if all(((x not in tmp) for x in self.neighbor_in_iterator(e))):
if result:
return None
result = e
return result
def skeleton(self):
'\n Return the skeleton of the lattice.\n\n The lattice is expected to be pseudocomplemented and non-empty.\n\n The skeleton of the lattice is the subposet induced by\n those elements that are the pseudocomplement to at least one\n element.\n\n OUTPUT:\n\n List of elements such that the subposet induced by them is\n the skeleton of the lattice.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [3, 4], 2: [4],\n ....: 3: [5], 4: [5]})\n sage: H.skeleton() # optional - sage.modules\n [5, 2, 0, 3]\n '
p_atoms = []
for atom in self.neighbor_out_iterator(0):
p_atom = self.pseudocomplement(atom)
if (p_atom is None):
raise ValueError('lattice is not pseudocomplemented')
p_atoms.append(p_atom)
n = len(p_atoms)
mt = self.meet_matrix()
pos = ([0] * n)
meets = ([(self.order() - 1)] * n)
result = [(self.order() - 1)]
i = 0
while (i >= 0):
new_meet = mt[(meets[(i - 1)], p_atoms[pos[i]])]
result.append(new_meet)
if (pos[i] == (n - 1)):
i -= 1
pos[i] += 1
else:
meets[i] = new_meet
pos[(i + 1)] = (pos[i] + 1)
i += 1
return result
def is_convex_subset(self, S) -> bool:
'\n Return ``True`` if `S` is a convex subset of the poset,\n and ``False`` otherwise.\n\n A subset `S` is *convex* in the poset if `b \\in S` whenever\n `a, c \\in S` and `a \\le b \\le c`.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: B3 = HasseDiagram({0: [1, 2, 4], 1: [3, 5], 2: [3, 6],\n ....: 3: [7], 4: [5, 6], 5: [7], 6: [7]})\n sage: B3.is_convex_subset([1, 3, 5, 4]) # Also connected\n True\n sage: B3.is_convex_subset([1, 3, 4]) # Not connected\n True\n\n sage: B3.is_convex_subset([0, 1, 2, 3, 6]) # No, 0 < 4 < 6\n False\n sage: B3.is_convex_subset([0, 1, 2, 7]) # No, 1 < 3 < 7.\n False\n\n TESTS::\n\n sage: B3.is_convex_subset([])\n True\n sage: B3.is_convex_subset([6])\n True\n '
if (not S):
return True
s_max = max(S)
ok = set()
for a in S:
for b in self.neighbor_out_iterator(a):
if ((b >= s_max) or (b in S)):
continue
def neighbors(v_):
return [v for v in self.neighbor_out_iterator(v_) if ((v <= s_max) and (v not in ok))]
for c in self.depth_first_search(b, neighbors=neighbors):
if (c in S):
return False
ok.add(c)
return True
def neutral_elements(self):
"\n Return the list of neutral elements of the lattice.\n\n An element `a` in a lattice is neutral if the sublattice\n generated by `a`, `x` and `y` is distributive for every\n `x`, `y` in the lattice.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [4], 2: [3], 3: [4, 5],\n ....: 4: [6], 5: [6]})\n sage: sorted(H.neutral_elements()) # optional - sage.modules\n [0, 4, 6]\n\n ALGORITHM:\n\n Basically we just check the distributivity against all element\n pairs `x, y` to see if element `a` is neutral or not.\n\n If we found that `a, x, y` is not a distributive triple, we add\n all three to list of non-neutral elements. If we found `a` to\n be neutral, we add it to list of neutral elements. When testing\n we skip already found neutral elements, as they can't be our `x`\n or `y`.\n\n We skip `a, x, y` as trivial if it is a chain. We do that by\n letting `x` to be a non-comparable to `a`; `y` can be any element.\n\n We first try to found `x` and `y` from elements not yet tested,\n so that we could get three birds with one stone.\n\n And last, the top and bottom elements are always neutral and\n need not be tested.\n "
n = self.order()
if (n < 5):
return set(range(n))
todo = set(range(1, (n - 1)))
neutrals = set([0, (n - 1)])
notneutrals = set()
all_elements = set(range(n))
mt = self.meet_matrix()
jn = self.join_matrix()
def is_neutral(a):
noncomp = all_elements.difference(self.depth_first_search(a))
noncomp.difference_update(self.depth_first_search(a, neighbors=self.neighbor_in_iterator))
for x in noncomp.intersection(todo):
meet_ax = mt[(a, x)]
join_ax = jn[(a, x)]
for y in todo:
if (mt[(mt[(join_ax, jn[(a, y)])], jn[(x, y)])] != jn[(jn[(meet_ax, mt[(a, y)])], mt[(x, y)])]):
notneutrals.add(x)
notneutrals.add(y)
return False
for y in notneutrals:
if (mt[(mt[(join_ax, jn[(a, y)])], jn[(x, y)])] != jn[(jn[(meet_ax, mt[(a, y)])], mt[(x, y)])]):
notneutrals.add(x)
return False
for x in noncomp.difference(todo):
meet_ax = mt[(a, x)]
join_ax = jn[(a, x)]
for y in todo:
if (mt[(mt[(join_ax, jn[(a, y)])], jn[(x, y)])] != jn[(jn[(meet_ax, mt[(a, y)])], mt[(x, y)])]):
notneutrals.add(y)
return False
for y in notneutrals:
if (mt[(mt[(join_ax, jn[(a, y)])], jn[(x, y)])] != jn[(jn[(meet_ax, mt[(a, y)])], mt[(x, y)])]):
return False
return True
while todo:
e = todo.pop()
if is_neutral(e):
neutrals.add(e)
else:
notneutrals.add(e)
return neutrals
def kappa(self, a):
'\n Return the maximum element greater than the element covered\n by ``a`` but not greater than ``a``.\n\n Define `\\kappa(a)` as the maximum element of\n `(\\uparrow a_*) \\setminus (\\uparrow a)`, where `a_*` is the element\n covered by `a`. It is always a meet-irreducible element, if it exists.\n\n .. NOTE::\n\n Element ``a`` is expected to be join-irreducible, and\n this is *not* checked.\n\n INPUT:\n\n - ``a`` -- a join-irreducible element of the lattice\n\n OUTPUT:\n\n The element `\\kappa(a)` or ``None`` if there\n is not a unique greatest element with given constraints.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4, 5], 3: [5], 4: [6], 5: [6]})\n sage: H.kappa(1)\n 5\n sage: H.kappa(2) is None\n True\n\n TESTS::\n\n sage: H = HasseDiagram({0: [1]})\n sage: H.kappa(1)\n 0\n '
lc = next(self.neighbor_in_iterator(a))
if (self.out_degree(lc) == 1):
return lc
gt_a = set(self.depth_first_search(a))
tmp = set(self.depth_first_search(lc, neighbors=(lambda v: [v_ for v_ in self.neighbor_out_iterator(v) if (v_ not in gt_a)])))
result = None
for e in tmp:
if all(((x not in tmp) for x in self.neighbor_out_iterator(e))):
if result:
return None
result = e
return result
def atoms_of_congruence_lattice(self):
'\n Return atoms of the congruence lattice.\n\n In other words, return "minimal non-trivial" congruences:\n A congruence is minimal if the only finer (as a partition\n of set of elements) congruence is the trivial congruence\n where every block contains only one element.\n\n .. SEEALSO:: :meth:`congruence`\n\n OUTPUT:\n\n List of congruences, every congruence as\n :class:`sage.combinat.set_partition.SetPartition`\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: N5 = HasseDiagram({0: [1, 2], 1: [4], 2: [3], 3:[4]})\n sage: N5.atoms_of_congruence_lattice() # optional - sage.combinat\n [{{0}, {1}, {2, 3}, {4}}]\n sage: Hex = HasseDiagram({0: [1, 2], 1: [3], 2: [4], 3: [5], 4: [5]})\n sage: Hex.atoms_of_congruence_lattice() # optional - sage.combinat\n [{{0}, {1}, {2, 4}, {3}, {5}}, {{0}, {1, 3}, {2}, {4}, {5}}]\n\n ALGORITHM:\n\n Every atom is a join-irreducible. Every join-irreducible of\n `\\mathrm{Con}(L)` is a principal congruence generated by a\n meet-irreducible element and the only element covering it (and also\n by a join-irreducible element and the only element covered by it).\n Hence we check those principal congruences to find the minimal ones.\n '
from sage.combinat.set_partition import SetPartitions
join_irreducibles = [v for v in self if (self.in_degree(v) == 1)]
meet_irreducibles = [v for v in self if (self.out_degree(v) == 1)]
if (len(join_irreducibles) < len(meet_irreducibles)):
irr = [(v, next(self.neighbor_in_iterator(v))) for v in join_irreducibles]
else:
irr = [(next(self.neighbor_out_iterator(v)), v) for v in meet_irreducibles]
S = SetPartitions(range(self.order()))
min_congruences = []
already_tried = []
while irr:
next_pair = irr.pop()
cong = self.congruence([next_pair], stop_pairs=already_tried)
already_tried.append(next_pair)
if (cong is not None):
cong = S(cong)
min_congruences = [c for c in min_congruences if ((c != cong) and (not S.is_less_than(cong, c)))]
if (not any((S.is_less_than(c, cong) for c in min_congruences))):
min_congruences.append(cong)
return min_congruences
def congruence(self, parts, start=None, stop_pairs=[]):
'\n Return the congruence ``start`` "extended" by ``parts``.\n\n ``start`` is assumed to be a valid congruence of the lattice,\n and this is *not* checked.\n\n INPUT:\n\n - ``parts`` -- a list of lists; congruences to add\n - ``start`` -- a disjoint set; already computed congruence (or ``None``)\n - ``stop_pairs`` -- a list of pairs; list of pairs for stopping computation\n\n OUTPUT:\n\n ``None``, if the congruence generated by ``start`` and ``parts``\n together contains a block that has elements `a, b` so that ``(a, b)``\n is in the list ``stop_pairs``. Otherwise the least congruence that\n contains a block whose subset is `p` for every `p` in ``parts`` or\n ``start``, given as :class:`sage.sets.disjoint_set.DisjointSet_class`.\n\n ALGORITHM:\n\n Use the quadrilateral argument from page 120 of [Dav1997]_.\n\n Basically we take one block from todo-list, search quadrilateral\n blocks up and down against the block, and then complete them to\n closed intervals and add to todo-list.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [4], 3: [4]})\n sage: cong = H.congruence([[0, 1]]); cong # optional - sage.modules\n {{0, 1, 3}, {2, 4}}\n sage: H.congruence([[0, 2]], start=cong) # optional - sage.modules\n {{0, 1, 2, 3, 4}}\n\n sage: H.congruence([[0, 1]], stop_pairs=[(1, 3)]) is None # optional - sage.modules\n True\n\n TESTS::\n\n sage: H = HasseDiagram(\'HT@O?GO?OE?G@??\')\n sage: H.congruence([[0, 1]]).number_of_subsets() # optional - sage.modules\n 1\n sage: H = HasseDiagram(\'HW_oC?@@O@?O@??\')\n sage: H.congruence([[0, 1]]).number_of_subsets() # optional - sage.modules\n 1\n\n Check :trac:`21861`::\n\n sage: H = HasseDiagram({0: [1, 2], 1: [3], 2: [4], 3: [4]})\n sage: tmp = H.congruence([[1, 3]]) # optional - sage.modules\n sage: tmp.number_of_subsets() # optional - sage.modules\n 4\n sage: H.congruence([[0, 1]], start=tmp).number_of_subsets() # optional - sage.modules\n 2\n sage: tmp.number_of_subsets() # optional - sage.modules\n 4\n '
from sage.sets.disjoint_set import DisjointSet
from copy import copy
n = self.order()
mt = self.meet_matrix()
jn = self.join_matrix()
def fill_to_interval(S):
'\n Return the smallest interval containing elements in the set S.\n '
m = (n - 1)
for e in S:
m = mt[(m, e)]
j = 0
for e in S:
j = jn[(j, e)]
return self.interval(m, j)
cong = (copy(start) if start else DisjointSet(n))
t = (- 1)
while (t != cong.number_of_subsets()):
for part in parts:
if part:
c = part[0]
for e in fill_to_interval(part):
cong.union(e, c)
t = cong.number_of_subsets()
for c in list(cong):
r = c[0]
for v in fill_to_interval(c):
cong.union(r, v)
todo = set((cong.find(e) for part in parts for e in part))
while todo:
for (a, b) in stop_pairs:
if (cong.find(a) == cong.find(b)):
return None
block = sorted(cong.root_to_elements_dict()[cong.find(todo.pop())])
b = block[(- 1)]
for a in block:
for c in self.neighbor_out_iterator(a):
if (c not in block):
d = jn[(c, b)]
if (cong.find(d) != cong.find(c)):
break
else:
continue
break
else:
a = block[0]
for b in reversed(block):
for d in self.neighbor_in_iterator(b):
if (d not in block):
c = mt[(d, a)]
if (cong.find(c) != cong.find(d)):
break
else:
continue
break
else:
continue
todo.add(a)
todo.add(c)
while (c is not None):
newblock = cong.find(c)
for i in self.interval(c, d):
cong.union(newblock, i)
C = cong.root_to_elements_dict()[cong.find(newblock)]
mins = [i for i in C if all(((i_ not in C) for i_ in self.neighbor_in_iterator(i)))]
maxs = [i for i in C if all(((i_ not in C) for i_ in self.neighbor_out_iterator(i)))]
c = None
if ((len(mins) > 1) or (len(maxs) > 1)):
c = (n - 1)
for m in mins:
c = mt[(c, m)]
d = 0
for m in maxs:
d = jn[(d, m)]
todo = set((cong.find(x) for x in todo))
return cong
def find_nontrivial_congruence(self):
'\n Return a pair that generates non-trivial congruence or\n ``None`` if there is not any.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [5], 2: [3, 4], 3: [5], 4: [5]})\n sage: H.find_nontrivial_congruence() # optional - sage.modules\n {{0, 1}, {2, 3, 4, 5}}\n\n sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})\n sage: H.find_nontrivial_congruence() is None # optional - sage.modules\n True\n\n ALGORITHM:\n\n See https://www.math.hawaii.edu/~ralph/Preprints/conlat.pdf:\n\n If `\\Theta` is a join irreducible element of a `\\mathrm{Con}(L)`,\n then there is at least one join-irreducible `j` and one\n meet-irreducible `m` such that `\\Theta` is both the principal\n congruence generated by `(j^*, j)`, where `j^*` is the unique\n lower cover of `j`, and the principal congruence generated by\n `(m, m^*)`, where `m^*` is the unique upper cover of `m`.\n\n So, we only check join irreducibles or meet irreducibles,\n whichever is a smaller set. To optimize more we stop computation\n whenever it finds a pair that we know to generate one-element\n congruence.\n '
join_irreducibles = [v for v in self if (self.in_degree(v) == 1)]
meet_irreducibles = [v for v in self if (self.out_degree(v) == 1)]
if (len(join_irreducibles) < len(meet_irreducibles)):
irr = [(v, next(self.neighbor_in_iterator(v))) for v in join_irreducibles]
else:
irr = [(next(self.neighbor_out_iterator(v)), v) for v in meet_irreducibles]
irr.sort(key=(lambda x: (x[0] - x[1])))
tried = []
for pair in irr:
cong = self.congruence([pair], stop_pairs=tried)
if ((cong is not None) and (cong.number_of_subsets() > 1)):
return cong
tried.append(pair)
return None
def principal_congruences_poset(self):
'\n Return the poset of join-irreducibles of the congruence lattice.\n\n OUTPUT:\n\n A pair `(P, D)` where `P` is a poset and `D` is a dictionary.\n\n Elements of `P` are pairs `(x, y)` such that `x` is an element\n of the lattice and `y` is an element covering it. In the poset\n `(a, b)` is less than `(c, d)` iff the principal congruence\n generated by `(a, b)` is refinement of the principal congruence\n generated by `(c, d)`.\n\n `D` is a dictionary from pairs `(x, y)` to the congruence\n (given as DisjointSet) generated by the pair.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: N5 = HasseDiagram({0: [1, 2], 1: [4], 2: [3], 3: [4]})\n sage: P, D = N5.principal_congruences_poset() # optional - sage.combinat\n sage: P # optional - sage.combinat\n Finite poset containing 3 elements\n sage: P.bottom() # optional - sage.combinat\n (2, 3)\n sage: D[(2, 3)] # optional - sage.combinat\n {{0}, {1}, {2, 3}, {4}}\n '
from sage.combinat.set_partition import SetPartition, SetPartitions
from sage.combinat.posets.posets import Poset
n = self.order()
if (self.in_degree_sequence().count(1) > self.out_degree_sequence().count(1)):
irr = [(e, next(self.neighbor_out_iterator(e))) for e in range(n) if (self.out_degree(e) == 1)]
else:
irr = [(next(self.neighbor_in_iterator(e)), e) for e in range(n) if (self.in_degree(e) == 1)]
D = {}
P = {}
uniq_congs = set()
for ab in irr:
cong = self.congruence([ab])
cong_ = SetPartition(cong)
if (cong_ not in uniq_congs):
uniq_congs.add(cong_)
D[ab] = cong
P[ab] = cong_
T = SetPartitions(n)
P = DiGraph([D, (lambda a, b: T.is_less_than(P[a], P[b]))])
return (Poset(P), D)
def congruences_iterator(self):
"\n Return an iterator over all congruences of the lattice.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram('GY@OQ?OW@?O?')\n sage: it = H.congruences_iterator(); it\n <generator object ...>\n sage: sorted([cong.number_of_subsets() for cong in it]) # optional - sage.combinat\n [1, 2, 2, 2, 4, 4, 4, 8]\n "
from sage.sets.disjoint_set import DisjointSet
(P, congs) = self.principal_congruences_poset()
for a in P.antichains_iterator():
achain = tuple(a)
n = len(achain)
if (n == 0):
(yield DisjointSet(self.order()))
if (n == 1):
congs[achain] = congs[a[0]]
(yield congs[achain[0]])
if (n > 1):
c = congs[achain[:(- 1)]]
c = self.congruence([achain[(- 1)]], start=c)
(yield c)
congs[achain] = c
def is_congruence_normal(self) -> bool:
"\n Return ``True`` if the lattice can be constructed from the one-element\n lattice with Day doubling constructions of convex subsets.\n\n Subsets to double does not need to be lower nor upper pseudo-intervals.\n On the other hand they must be convex, i.e. doubling a non-convex but\n municipal subset will give a lattice that returns ``False`` from\n this function.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram('IX?Q@?AG?OG?W?O@??')\n sage: H.is_congruence_normal() # optional - sage.combinat\n True\n\n The 5-element diamond is the smallest non-example::\n\n sage: H = HasseDiagram({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})\n sage: H.is_congruence_normal() # optional - sage.combinat\n False\n\n This is done by doubling a non-convex subset::\n\n sage: H = HasseDiagram('OQC?a?@CO?G_C@?GA?O??_??@?BO?A_?G??C??_?@???')\n sage: H.is_congruence_normal() # optional - sage.combinat\n False\n\n TESTS::\n\n sage: HasseDiagram().is_congruence_normal() # optional - sage.combinat\n True\n sage: HasseDiagram({0: []}).is_congruence_normal() # optional - sage.combinat\n True\n\n ALGORITHM:\n\n See http://www.math.hawaii.edu/~jb/inflation.pdf\n "
from sage.combinat.set_partition import SetPartition
n = self.order()
congs_ji: dict[(SetPartition, list)] = {}
for ji in range(n):
if (self.in_degree(ji) == 1):
cong = SetPartition(self.congruence([[ji, next(self.neighbor_in_iterator(ji))]]))
if (cong not in congs_ji):
congs_ji[cong] = []
congs_ji[cong].append(ji)
for mi in range(n):
if (self.out_degree(mi) == 1):
cong = SetPartition(self.congruence([[mi, next(self.neighbor_out_iterator(mi))]]))
if any((self.is_lequal(ji, mi) for ji in congs_ji[cong])):
return False
return True
@staticmethod
def _glue_spectra(a_spec, b_spec, orientation):
'\n Return the `a`-spectrum of a poset by merging ``a_spec`` and ``b_spec``.\n\n ``a_spec`` and ``b_spec`` are the `a`-spectrum and `b`-spectrum of two different\n posets (see :meth:`atkinson` for the definition of `a`-spectrum).\n\n The orientation determines whether `a < b` or `b < a` in the combined poset.\n\n This is a helper method for :meth:`atkinson`.\n\n INPUT:\n\n - ``a_spec`` -- list; the `a`-spectrum of a poset `P`\n\n - ``b_spec`` -- list; the `b`-spectrum of a poset `Q`\n\n - ``orientation`` -- boolean; ``True`` if `a < b`, ``False`` otherwise\n\n OUTPUT:\n\n The `a`-spectrum (or `b`-spectrum, depending on orientation),\n returned as a list, of the poset which is a disjoint union\n of `P` and `Q`, together with the additional\n covering relation `a < b`.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: Pdata = [0, 1, 2, 0]\n sage: Qdata = [1, 1, 0]\n sage: HasseDiagram._glue_spectra(Pdata, Qdata, True)\n [0, 20, 28, 18, 0, 0, 0]\n\n sage: Pdata = [0, 0, 2]\n sage: Qdata = [0, 1]\n sage: HasseDiagram._glue_spectra(Pdata, Qdata, False)\n [0, 0, 0, 0, 8]\n '
new_a_spec = []
if (not orientation):
(a_spec, b_spec) = (b_spec, a_spec)
p = len(a_spec)
q = len(b_spec)
for r in range(1, ((p + q) + 1)):
new_a_spec.append(0)
for i in range(max(1, (r - q)), (min(p, r) + 1)):
k_val = (binomial((r - 1), (i - 1)) * binomial(((p + q) - r), (p - i)))
if orientation:
inner_sum = sum((b_spec[(j - 1)] for j in range(((r - i) + 1), (len(b_spec) + 1))))
else:
inner_sum = sum((b_spec[(j - 1)] for j in range(1, ((r - i) + 1))))
new_a_spec[(- 1)] = (new_a_spec[(- 1)] + ((a_spec[(i - 1)] * k_val) * inner_sum))
return new_a_spec
def _split(self, a, b):
'\n Return the two connected components obtained by deleting the covering\n relation `a < b` from a Hasse diagram that is a tree.\n\n This is a helper method for :meth:`FinitePoset.atkinson`.\n\n INPUT:\n\n - ``a`` -- an element of the poset\n - ``b`` -- an element of the poset which covers ``a``\n\n OUTPUT:\n\n A list containing two posets which are the connected components\n of this poset after deleting the covering relation `a < b`.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1, 2], 1: [], 2: []})\n sage: H._split(0, 1)\n [Hasse diagram of a poset containing 2 elements, Hasse diagram of a poset containing 1 elements]\n\n sage: H = HasseDiagram({0: [1], 1: [2], 2: [3], 3: [4], 4: []})\n sage: H._split(1, 2)\n [Hasse diagram of a poset containing 2 elements, Hasse diagram of a poset containing 3 elements]\n\n TESTS::\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [1,2,3], 1: [4, 5], 2: [4, 6], 3: [5, 6], 4: [7], 5: [7], 6: [7], 7: []})\n sage: H._split(0, 1)\n Traceback (most recent call last):\n ...\n ValueError: wrong number of connected components after the covering relation is deleted\n\n sage: H = HasseDiagram({0: [1], 1: [], 2: []})\n sage: H._split(0, 1)\n Traceback (most recent call last):\n ...\n ValueError: wrong number of connected components after the covering relation is deleted\n '
split_hasse = self.copy(self)
split_hasse.delete_edge(a, b)
components = split_hasse.connected_components_subgraphs()
if (not (len(components) == 2)):
raise ValueError('wrong number of connected components after the covering relation is deleted')
(c1, c2) = components
if (a in c2):
(c1, c2) = (c2, c1)
return [c1, c2]
def _spectrum_of_tree(self, a):
'\n Return the `a`-spectrum of a poset whose underlying graph is a tree.\n\n This is a helper method for :meth:`FinitePoset.atkinson`.\n\n INPUT:\n\n - ``a`` -- an element of the poset\n\n OUTPUT:\n\n The `a`-spectrum of this poset, returned as a list.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.hasse_diagram import HasseDiagram\n sage: H = HasseDiagram({0: [2], 1: [2], 2: [3, 4], 3: [], 4: []})\n sage: H._spectrum_of_tree(0)\n [2, 2, 0, 0, 0]\n\n sage: H = HasseDiagram({0: [2], 1: [2], 2: [3, 4], 3: [], 4: []})\n sage: H._spectrum_of_tree(2)\n [0, 0, 4, 0, 0]\n\n sage: H = HasseDiagram({0: [2], 1: [2], 2: [3, 4], 3: [], 4: []})\n sage: H._spectrum_of_tree(3)\n [0, 0, 0, 2, 2]\n '
upper_covers = self.neighbors_out(a)
lower_covers = self.neighbors_in(a)
if ((not upper_covers) and (not lower_covers)):
return [1]
if upper_covers:
b = upper_covers[0]
orientation = True
else:
(a, b) = (lower_covers[0], a)
orientation = False
(P, Q) = self._split(a, b)
a_spec = P._spectrum_of_tree(a)
b_spec = Q._spectrum_of_tree(b)
return HasseDiagram._glue_spectra(a_spec, b_spec, orientation)
|
class IncidenceAlgebra(CombinatorialFreeModule):
'\n The incidence algebra of a poset.\n\n Let `P` be a poset and `R` be a commutative unital associative ring.\n The *incidence algebra* `I_P` is the algebra of functions\n `\\alpha \\colon P \\times P \\to R` such that `\\alpha(x, y) = 0`\n if `x \\not\\leq y` where multiplication is given by convolution:\n\n .. MATH::\n\n (\\alpha \\ast \\beta)(x, y) = \\sum_{x \\leq k \\leq y}\n \\alpha(x, k) \\beta(k, y).\n\n This has a natural basis given by indicator functions for the\n interval `[a, b]`, i.e. `X_{a,b}(x,y) = \\delta_{ax} \\delta_{by}`.\n The incidence algebra is a unital algebra with the identity given\n by the Kronecker delta `\\delta(x, y) = \\delta_{xy}`. The Möbius\n function of `P` is another element of `I_p` whose inverse is the\n `\\zeta` function of the poset (so `\\zeta(x, y) = 1` for\n every interval `[x, y]`).\n\n .. TODO::\n\n Implement the incidence coalgebra.\n\n REFERENCES:\n\n - :wikipedia:`Incidence_algebra`\n '
def __init__(self, R, P, prefix='I'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: P = posets.BooleanLattice(3)\n sage: I = P.incidence_algebra(QQ)\n sage: TestSuite(I).run() # long time\n '
cat = Algebras(R).WithBasis()
if (P in FiniteEnumeratedSets()):
cat = cat.FiniteDimensional()
self._poset = P
CombinatorialFreeModule.__init__(self, R, map(tuple, P.relations()), prefix=prefix, category=cat)
def _repr_term(self, A):
"\n Return a string representation of the term labeled by ``A``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I._repr_term((4, 12))\n 'I[4, 12]'\n "
return (self.prefix() + str(list(A)))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.incidence_algebra(QQ)\n Incidence algebra of Finite lattice containing 16 elements\n over Rational Field\n '
return f'Incidence algebra of {self._poset} over {self.base_ring()}'
def _coerce_map_from_(self, R):
'\n Return the coerce map from ``R`` into ``self`` if it exists\n or ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: R = I.reduced_subalgebra()\n sage: I.has_coerce_map_from(R)\n True\n sage: I.has_coerce_map_from(QQ)\n True\n sage: Pp = posets.BooleanLattice(3)\n sage: Rp = Pp.incidence_algebra(QQ).reduced_subalgebra()\n sage: I.has_coerce_map_from(Rp)\n False\n '
if (isinstance(R, ReducedIncidenceAlgebra) and (R._ambient is self)):
return copy(R.lift)
return super()._coerce_map_from_(R)
def reduced_subalgebra(self, prefix='R'):
'\n Return the reduced incidence subalgebra.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I.reduced_subalgebra()\n Reduced incidence algebra of Finite lattice containing 16 elements\n over Rational Field\n '
return ReducedIncidenceAlgebra(self, prefix)
def poset(self):
'\n Return the defining poset of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I.poset()\n Finite lattice containing 16 elements\n sage: I.poset() == P\n True\n '
return self._poset
def some_elements(self):
'\n Return a list of elements of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(1)\n sage: I = P.incidence_algebra(QQ)\n sage: Ielts = I.some_elements(); Ielts # random\n [2*I[0, 0] + 2*I[0, 1] + 3*I[1, 1],\n I[0, 0] - I[0, 1] + I[1, 1],\n I[0, 0] + I[0, 1] + I[1, 1]]\n sage: [a in I for a in Ielts]\n [True, True, True]\n '
return [self.an_element(), self.moebius(), self.zeta()]
def product_on_basis(self, A, B):
'\n Return the product of basis elements indexed by ``A`` and ``B``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I.product_on_basis((1, 3), (3, 11))\n I[1, 11]\n sage: I.product_on_basis((1, 3), (2, 2))\n 0\n '
if (A[1] == B[0]):
return self.monomial((A[0], B[1]))
return self.zero()
@cached_method
def one(self):
'\n Return the element `1` in ``self`` (which is the Kronecker\n delta `\\delta(x, y)`).\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I.one()\n I[0, 0] + I[1, 1] + I[2, 2] + I[3, 3] + I[4, 4] + I[5, 5]\n + I[6, 6] + I[7, 7] + I[8, 8] + I[9, 9] + I[10, 10]\n + I[11, 11] + I[12, 12] + I[13, 13] + I[14, 14] + I[15, 15]\n '
return self.sum_of_monomials(((x, x) for x in self._poset))
delta = one
@cached_method
def zeta(self):
'\n Return the `\\zeta` function in ``self``.\n\n The `\\zeta` function on a poset `P` is given by\n\n .. MATH::\n\n \\zeta(x, y) = \\begin{cases}\n 1 & x \\leq y, \\\\\n 0 & x \\not\\leq y.\n \\end{cases}\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I.zeta() * I.moebius() == I.one()\n True\n '
return self.sum(self.basis())
@cached_method
def moebius(self):
'\n Return the Möbius function of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: I = P.incidence_algebra(QQ)\n sage: I.moebius()\n I[0, 0] - I[0, 1] - I[0, 2] + I[0, 3] + I[1, 1]\n - I[1, 3] + I[2, 2] - I[2, 3] + I[3, 3]\n '
mu = self._poset.moebius_function
R = self.base_ring()
return self.sum_of_terms(((A, R(mu(*A))) for A in self.basis().keys()))
def __getitem__(self, A):
'\n Return the basis element indexed by ``A``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I[2, 6]\n I[2, 6]\n sage: I[(2, 6)]\n I[2, 6]\n sage: I[[2, 6]]\n I[2, 6]\n sage: I[2]\n I[2, 2]\n\n sage: I[2, 5]\n Traceback (most recent call last):\n ...\n ValueError: not an interval\n\n sage: I[-1]\n Traceback (most recent call last):\n ...\n ValueError: not an element of the poset\n '
if (not isinstance(A, (list, tuple))):
if (A not in self._poset.list()):
raise ValueError('not an element of the poset')
A = (A, A)
else:
A = tuple(A)
if ((len(A) != 2) or (A not in self.basis().keys())):
raise ValueError('not an interval')
return self.monomial(A)
@lazy_attribute
def _linear_extension(self):
'\n Return a fixed linear extension of the defining poset of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: I._linear_extension\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)\n '
return tuple(self._poset.linear_extension())
class Element(CombinatorialFreeModule.Element):
'\n An element of an incidence algebra.\n '
def __call__(self, x, y):
'\n Return ``self(x, y)``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: mu = I.moebius()\n sage: mu(0, 12)\n 1\n sage: mu(0, 7)\n -1\n sage: mu(15, 0)\n 0\n '
P = self.parent()._poset
x = P(x)
y = P(y)
return self[(x, y)]
@cached_method
def to_matrix(self):
'\n Return ``self`` as a matrix.\n\n We define a matrix `M_{xy} = \\alpha(x, y)` for some element\n `\\alpha \\in I_P` in the incidence algebra `I_P` and we order\n the elements `x,y \\in P` by some linear extension of `P`. This\n defines an algebra (iso)morphism; in particular, multiplication\n in the incidence algebra goes to matrix multiplication.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: I = P.incidence_algebra(QQ)\n sage: I.moebius().to_matrix()\n [ 1 -1 -1 1]\n [ 0 1 0 -1]\n [ 0 0 1 -1]\n [ 0 0 0 1]\n sage: I.zeta().to_matrix()\n [1 1 1 1]\n [0 1 0 1]\n [0 0 1 1]\n [0 0 0 1]\n\n TESTS:\n\n We check that this is an algebra (iso)morphism::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: mu = I.moebius()\n sage: (mu*mu).to_matrix() == mu.to_matrix() * mu.to_matrix()\n True\n '
P = self.parent()
MS = MatrixSpace(P.base_ring(), P._poset.cardinality(), sparse=True)
L = P._linear_extension
M = copy(MS.zero())
for (i, c) in self:
M[(L.index(i[0]), L.index(i[1]))] = c
M.set_immutable()
return M
def is_unit(self):
'\n Return if ``self`` is a unit.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: I = P.incidence_algebra(QQ)\n sage: mu = I.moebius()\n sage: mu.is_unit()\n True\n sage: zeta = I.zeta()\n sage: zeta.is_unit()\n True\n sage: x = mu - I.zeta() + I[2,2]\n sage: x.is_unit()\n False\n sage: y = I.moebius() + I.zeta()\n sage: y.is_unit()\n True\n\n This depends on the base ring::\n\n sage: I = P.incidence_algebra(ZZ)\n sage: y = I.moebius() + I.zeta()\n sage: y.is_unit()\n False\n '
return all((self[(x, x)].is_unit() for x in self.parent()._poset))
def __invert__(self):
'\n Return the inverse of ``self`` if it exists.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: I = P.incidence_algebra(QQ)\n sage: mu = I.moebius()\n sage: ~mu\n I[0, 0] + I[0, 1] + I[0, 2] + I[0, 3] + I[1, 1]\n + I[1, 3] + I[2, 2] + I[2, 3] + I[3, 3]\n sage: x = mu - I.zeta() + I[2,2]\n sage: ~x\n Traceback (most recent call last):\n ...\n ValueError: element is not invertible\n\n TESTS::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: mu = I.moebius()\n sage: ~mu == I.zeta()\n True\n sage: ~I.one() == I.one()\n True\n '
M = self.to_matrix()
if (not M.is_invertible()):
raise ValueError('element is not invertible')
inv = (~ M)
L = self.parent()._linear_extension
return self.parent().sum_of_terms((((L[i], L[j]), inv[(i, j)]) for (i, j) in inv.nonzero_positions(copy=False)))
|
class ReducedIncidenceAlgebra(CombinatorialFreeModule):
"\n The reduced incidence algebra of a poset.\n\n The reduced incidence algebra `R_P` is a subalgebra of the\n incidence algebra `I_P` where `\\alpha(x, y) = \\alpha(x', y')` when\n `[x, y]` is isomorphic to `[x', y']` as posets. Thus the delta, Möbius,\n and zeta functions are all elements of `R_P`.\n "
def __init__(self, I, prefix='R'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: P = posets.BooleanLattice(3)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: TestSuite(R).run() # long time\n '
self._ambient = I
EC = {}
P = self._ambient._poset
if (not P.is_finite()):
raise NotImplementedError('only implemented for finite posets')
for i in self._ambient.basis().keys():
S = P.subposet(P.interval(*i))
added = False
for k in EC:
if S._hasse_diagram.is_isomorphic(k._hasse_diagram):
EC[k].append(i)
added = True
break
if (not added):
EC[S] = [i]
self._equiv_classes = map(sorted, EC.values())
self._equiv_classes = {cls[0]: cls for cls in self._equiv_classes}
cat = Algebras(I.base_ring()).FiniteDimensional().WithBasis()
CombinatorialFreeModule.__init__(self, I.base_ring(), sorted(self._equiv_classes.keys()), prefix=prefix, category=cat)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.incidence_algebra(QQ).reduced_subalgebra()\n Reduced incidence algebra of Finite lattice containing 16 elements\n over Rational Field\n '
msg = 'Reduced incidence algebra of {} over {}'
return msg.format(self._ambient._poset, self.base_ring())
def poset(self):
'\n Return the defining poset of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.poset()\n Finite lattice containing 16 elements\n sage: R.poset() == P\n True\n '
return self._ambient._poset
def some_elements(self):
'\n Return a list of elements of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.some_elements()\n [2*R[(0, 0)] + 2*R[(0, 1)] + 3*R[(0, 3)],\n R[(0, 0)] - R[(0, 1)] + R[(0, 3)] - R[(0, 7)] + R[(0, 15)],\n R[(0, 0)] + R[(0, 1)] + R[(0, 3)] + R[(0, 7)] + R[(0, 15)]]\n '
return [self.an_element(), self.moebius(), self.zeta()]
@cached_method
def one_basis(self):
'\n Return the index of the element `1` in ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.one_basis()\n (0, 0)\n '
for A in self.basis().keys():
if (A[0] == A[1]):
return A
def delta(self):
'\n Return the Kronecker delta function in ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.delta()\n R[(0, 0)]\n '
return self.one()
@cached_method
def zeta(self):
'\n Return the `\\zeta` function in ``self``.\n\n The `\\zeta` function on a poset `P` is given by\n\n .. MATH::\n\n \\zeta(x, y) = \\begin{cases}\n 1 & x \\leq y, \\\\\n 0 & x \\not\\leq y.\n \\end{cases}\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.zeta()\n R[(0, 0)] + R[(0, 1)] + R[(0, 3)] + R[(0, 7)] + R[(0, 15)]\n '
return self.sum(self.basis())
@cached_method
def moebius(self):
'\n Return the Möbius function of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.moebius()\n R[(0, 0)] - R[(0, 1)] + R[(0, 3)] - R[(0, 7)] + R[(0, 15)]\n '
mu = self._ambient._poset.moebius_function
R = self.base_ring()
return self.sum_of_terms(((A, R(mu(*A))) for A in self.basis().keys()))
@cached_method
def _lift_basis(self, x):
'\n Lift the basis element indexed by ``x`` to the ambient incidence\n algebra of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R._lift_basis((0, 7))\n I[0, 7] + I[0, 11] + I[0, 13] + I[0, 14] + I[1, 15]\n + I[2, 15] + I[4, 15] + I[8, 15]\n '
return self._ambient.sum_of_monomials(self._equiv_classes[x])
@lazy_attribute
def lift(self):
'\n Return the lift morphism from ``self`` to the ambient space.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R.lift\n Generic morphism:\n From: Reduced incidence algebra of Finite lattice containing 4 elements over Rational Field\n To: Incidence algebra of Finite lattice containing 4 elements over Rational Field\n sage: R.an_element() - R.one()\n R[(0, 0)] + 2*R[(0, 1)] + 3*R[(0, 3)]\n sage: R.lift(R.an_element() - R.one())\n I[0, 0] + 2*I[0, 1] + 2*I[0, 2] + 3*I[0, 3] + I[1, 1]\n + 2*I[1, 3] + I[2, 2] + 2*I[2, 3] + I[3, 3]\n '
return self.module_morphism(self._lift_basis, codomain=self._ambient)
def __getitem__(self, A):
'\n Return the basis element indexed by ``A``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: R[0, 0]\n R[(0, 0)]\n sage: R[0, 1]\n R[(0, 1)]\n sage: R[0, 15]\n R[(0, 15)]\n sage: R[0]\n R[(0, 0)]\n\n This works for any representative of the equivalence class::\n\n sage: R[3, 3]\n R[(0, 0)]\n sage: R[3, 11]\n R[(0, 1)]\n\n TESTS:\n\n sage: R[2, 5]\n Traceback (most recent call last):\n ...\n ValueError: not an interval\n\n sage: R[-1]\n Traceback (most recent call last):\n ...\n ValueError: not an element of the poset\n '
if (not isinstance(A, (list, tuple))):
if (A not in self._ambient._poset.list()):
raise ValueError('not an element of the poset')
return self.one()
else:
A = tuple(A)
if (len(A) != 2):
raise ValueError('not an interval')
for k in self._equiv_classes:
if (A in self._equiv_classes[k]):
return self.monomial(k)
raise ValueError('not an interval')
def _retract(self, x):
'\n Return the retract of ``x`` from the incidence algebra to ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: I = P.incidence_algebra(QQ)\n sage: R = I.reduced_subalgebra()\n sage: all(R._retract(R.lift(x)) == x for x in R.basis())\n True\n sage: R._retract(I.zeta()) == R.zeta()\n True\n sage: R._retract(I.delta()) == R.delta()\n True\n sage: R._retract(I.moebius()) == R.moebius()\n True\n '
return self.sum_of_terms(((k, x[k]) for k in self.basis().keys()))
class Element(CombinatorialFreeModule.Element):
'\n An element of a reduced incidence algebra.\n '
def __call__(self, x, y):
'\n Return ``self(x, y)``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: x = R.an_element()\n sage: x(0, 7)\n 0\n sage: x(7, 15)\n 2\n sage: x(4, 15)\n 0\n '
return self.parent().lift(self)(x, y)
def _mul_(self, other):
'\n Return the product of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: x = R.an_element()\n sage: x * R.zeta()\n 2*R[(0, 0)] + 4*R[(0, 1)] + 9*R[(0, 3)] + 17*R[(0, 7)] + 28*R[(0, 15)]\n sage: x * R.moebius()\n 2*R[(0, 0)] + R[(0, 3)] - 5*R[(0, 7)] + 12*R[(0, 15)]\n sage: x * R.moebius() * R.zeta() == x\n True\n '
P = self.parent()
return P._retract((P.lift(self) * P.lift(other)))
@cached_method
def to_matrix(self):
'\n Return ``self`` as a matrix.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: mu = R.moebius()\n sage: mu.to_matrix()\n [ 1 -1 -1 1]\n [ 0 1 0 -1]\n [ 0 0 1 -1]\n [ 0 0 0 1]\n '
return self.parent().lift(self).to_matrix()
def is_unit(self):
'\n Return if ``self`` is a unit.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: x = R.an_element()\n sage: x.is_unit()\n True\n '
return self[self.parent().one_basis()].is_unit()
def __invert__(self):
'\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: R = P.incidence_algebra(QQ).reduced_subalgebra()\n sage: x = R.an_element()\n sage: ~x\n 1/2*R[(0, 0)] - 1/2*R[(0, 1)] + 1/4*R[(0, 3)]\n + 3/2*R[(0, 7)] - 33/4*R[(0, 15)]\n '
P = self.parent()
return P._retract((~ P.lift(self)))
def lift(self):
'\n Return the lift of ``self`` to the ambient space.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(2)\n sage: I = P.incidence_algebra(QQ)\n sage: R = I.reduced_subalgebra()\n sage: x = R.an_element(); x\n 2*R[(0, 0)] + 2*R[(0, 1)] + 3*R[(0, 3)]\n sage: x.lift()\n 2*I[0, 0] + 2*I[0, 1] + 2*I[0, 2] + 3*I[0, 3] + 2*I[1, 1]\n + 2*I[1, 3] + 2*I[2, 2] + 2*I[2, 3] + 2*I[3, 3]\n '
return self.parent().lift(self)
|
def MeetSemilattice(data=None, *args, **options):
"\n Construct a meet semi-lattice from various forms of input data.\n\n INPUT:\n\n - ``data``, ``*args``, ``**options`` -- data and options that will\n be passed down to :func:`Poset` to construct a poset that is\n also a meet semilattice.\n\n .. SEEALSO:: :func:`Poset`, :func:`JoinSemilattice`, :func:`LatticePoset`\n\n EXAMPLES:\n\n Using data that defines a poset::\n\n sage: MeetSemilattice([[1,2],[3],[3]])\n Finite meet-semilattice containing 3 elements\n\n sage: MeetSemilattice([[1,2],[3],[3]], cover_relations = True)\n Finite meet-semilattice containing 3 elements\n\n Using a previously constructed poset::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: L = MeetSemilattice(P); L\n Finite meet-semilattice containing 3 elements\n sage: type(L)\n <class 'sage.combinat.posets.lattices.FiniteMeetSemilattice_with_category'>\n\n If the data is not a lattice, then an error is raised::\n\n sage: MeetSemilattice({'a': ['b', 'c'], 'b': ['d', 'e'],\n ....: 'c': ['d', 'e'], 'd': ['f'], 'e': ['f']})\n Traceback (most recent call last):\n ...\n LatticeError: no meet for e and d\n "
if (isinstance(data, FiniteMeetSemilattice) and (not args) and (not options)):
return data
if ('check' in options):
check = options.pop('check')
else:
check = True
P = Poset(data, *args, **options)
if check:
try:
P._hasse_diagram.meet_matrix()
except LatticeError as error:
error.x = P._vertex_to_element(error.x)
error.y = P._vertex_to_element(error.y)
raise
return FiniteMeetSemilattice(P)
|
class FiniteMeetSemilattice(FinitePoset):
'\n .. note::\n We assume that the argument passed to MeetSemilattice is the poset\n of a meet-semilattice (i.e. a poset with greatest lower bound for\n each pair of elements).\n\n TESTS::\n\n sage: M = MeetSemilattice([[1,2],[3],[3]])\n sage: TestSuite(M).run()\n\n ::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: M = MeetSemilattice(P)\n sage: TestSuite(M).run()\n '
Element = MeetSemilatticeElement
_desc = 'Finite meet-semilattice'
def meet_matrix(self):
'\n Return a matrix whose ``(i,j)`` entry is ``k``, where\n ``self.linear_extension()[k]`` is the meet (greatest lower bound) of\n ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.\n\n EXAMPLES::\n\n sage: P = LatticePoset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]], facade = False)\n sage: M = P.meet_matrix(); M\n [0 0 0 0 0 0 0 0]\n [0 1 0 1 0 0 0 1]\n [0 0 2 2 2 0 2 2]\n [0 1 2 3 2 0 2 3]\n [0 0 2 2 4 0 2 4]\n [0 0 0 0 0 5 5 5]\n [0 0 2 2 2 5 6 6]\n [0 1 2 3 4 5 6 7]\n sage: M[P(4).vertex,P(3).vertex] == P(0).vertex\n True\n sage: M[P(5).vertex,P(2).vertex] == P(2).vertex\n True\n sage: M[P(5).vertex,P(2).vertex] == P(5).vertex\n False\n '
return self._hasse_diagram.meet_matrix()
def meet(self, x, y=None):
'\n Return the meet of given elements in the lattice.\n\n INPUT:\n\n - ``x, y`` -- two elements of the (semi)lattice OR\n - ``x`` -- a list or tuple of elements\n\n EXAMPLES::\n\n sage: D = posets.DiamondPoset(5)\n sage: D.meet(1, 2)\n 0\n sage: D.meet(1, 1)\n 1\n sage: D.meet(1, 0)\n 0\n sage: D.meet(1, 4)\n 1\n\n Using list of elements as an argument. Meet of empty list is\n the bottom element::\n\n sage: B4=posets.BooleanLattice(4)\n sage: B4.meet([3,5,6])\n 0\n sage: B4.meet([])\n 15\n\n For non-facade lattices operator ``*`` works for meet::\n\n sage: L = posets.PentagonPoset(facade=False)\n sage: L(1)*L(2)\n 0\n\n .. SEEALSO::\n\n - Dual function: :meth:`~sage.combinat.posets.lattices.FiniteJoinSemilattice.join`\n '
mt = self._hasse_diagram.meet_matrix()
if (y is not None):
(i, j) = map(self._element_to_vertex, (x, y))
return self._vertex_to_element(mt[(i, j)])
m = (self.cardinality() - 1)
for i in (self._element_to_vertex(_) for _ in x):
m = mt[(i, m)]
return self._vertex_to_element(m)
def atoms(self):
'\n Return the list atoms of this (semi)lattice.\n\n An *atom* of a lattice is an element covering the bottom element.\n\n EXAMPLES::\n\n sage: L = posets.DivisorLattice(60)\n sage: sorted(L.atoms())\n [2, 3, 5]\n\n .. SEEALSO::\n\n - Dual function: :meth:`~FiniteJoinSemilattice.coatoms`\n\n TESTS::\n\n sage: LatticePoset().atoms()\n []\n sage: LatticePoset({0: []}).atoms()\n []\n '
if (self.cardinality() == 0):
return []
return self.upper_covers(self.bottom())
def submeetsemilattice(self, elms):
'\n Return the smallest meet-subsemilattice containing elements on the given list.\n\n INPUT:\n\n - ``elms`` -- a list of elements of the lattice.\n\n EXAMPLES::\n\n sage: L = posets.DivisorLattice(1000)\n sage: L_ = L.submeetsemilattice([200, 250, 125]); L_\n Finite meet-semilattice containing 5 elements\n sage: L_.list()\n [25, 50, 200, 125, 250]\n\n .. SEEALSO::\n\n - Dual function: :meth:`subjoinsemilattice`\n\n TESTS::\n\n sage: L.submeetsemilattice([])\n Finite meet-semilattice containing 0 elements\n '
gens_remaining = set(elms)
current_set = set()
while gens_remaining:
g = gens_remaining.pop()
if (g in current_set):
continue
for x in current_set:
gens_remaining.add(self.meet(x, g))
current_set.add(g)
return MeetSemilattice(self.subposet(current_set))
def subjoinsemilattice(self, elms):
'\n Return the smallest join-subsemilattice containing elements on the given list.\n\n INPUT:\n\n - ``elms`` -- a list of elements of the lattice.\n\n EXAMPLES::\n\n sage: L = posets.DivisorLattice(1000)\n sage: L_ = L.subjoinsemilattice([2, 25, 125]); L_\n Finite join-semilattice containing 5 elements\n sage: sorted(L_.list())\n [2, 25, 50, 125, 250]\n\n .. SEEALSO::\n\n - Dual function: :meth:`submeetsemilattice`\n\n TESTS::\n\n sage: L.subjoinsemilattice([])\n Finite join-semilattice containing 0 elements\n '
gens_remaining = set(elms)
current_set = set()
while gens_remaining:
g = gens_remaining.pop()
if (g in current_set):
continue
for x in current_set:
gens_remaining.add(self.join(x, g))
current_set.add(g)
return JoinSemilattice(self.subposet(current_set))
def pseudocomplement(self, element):
"\n Return the pseudocomplement of ``element``, if it exists.\n\n The (meet-)pseudocomplement is the greatest element whose\n meet with given element is the bottom element. I.e.\n in a meet-semilattice with bottom element `\\hat{0}`\n the pseudocomplement of an element `e` is the element\n `e^\\star` such that `e \\wedge e^\\star = \\hat{0}` and\n `e' \\le e^\\star` if `e \\wedge e' = \\hat{0}`.\n\n See :wikipedia:`Pseudocomplement`.\n\n INPUT:\n\n - ``element`` -- an element of the lattice.\n\n OUTPUT:\n\n An element of the lattice or ``None`` if the pseudocomplement does\n not exist.\n\n EXAMPLES:\n\n The pseudocomplement's pseudocomplement is not always the original\n element::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [6]})\n sage: L.pseudocomplement(2)\n 5\n sage: L.pseudocomplement(5)\n 4\n\n An element can have complements but no pseudocomplement, or vice\n versa::\n\n sage: L = LatticePoset({0: [1, 2], 1: [3, 4, 5], 2: [5], 3: [6],\n ....: 4: [6], 5: [6]})\n sage: L.complements(1), L.pseudocomplement(1)\n ([], 2)\n sage: L.complements(2), L.pseudocomplement(2)\n ([3, 4], None)\n\n .. SEEALSO:: :meth:`~sage.combinat.posets.lattices.FiniteLatticePoset.is_pseudocomplemented`\n\n TESTS::\n\n sage: L = LatticePoset({'a': []})\n sage: L.pseudocomplement('a')\n 'a'\n sage: L = LatticePoset({'a': ['b'], 'b': ['c']})\n sage: [L.pseudocomplement(e) for e in ['a', 'b', 'c']]\n ['c', 'a', 'a']\n "
v = self._element_to_vertex(element)
e = self._hasse_diagram.pseudocomplement(v)
if (e is None):
return None
return self._vertex_to_element(e)
|
def JoinSemilattice(data=None, *args, **options):
"\n Construct a join semi-lattice from various forms of input data.\n\n INPUT:\n\n - ``data``, ``*args``, ``**options`` -- data and options that will\n be passed down to :func:`Poset` to construct a poset that is\n also a join semilattice\n\n .. SEEALSO:: :func:`Poset`, :func:`MeetSemilattice`, :func:`LatticePoset`\n\n EXAMPLES:\n\n Using data that defines a poset::\n\n sage: JoinSemilattice([[1,2],[3],[3]])\n Finite join-semilattice containing 3 elements\n\n sage: JoinSemilattice([[1,2],[3],[3]], cover_relations = True)\n Finite join-semilattice containing 3 elements\n\n Using a previously constructed poset::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: J = JoinSemilattice(P); J\n Finite join-semilattice containing 3 elements\n sage: type(J)\n <class 'sage.combinat.posets.lattices.FiniteJoinSemilattice_with_category'>\n\n If the data is not a lattice, then an error is raised::\n\n sage: JoinSemilattice({'a': ['b', 'c'], 'b': ['d', 'e'],\n ....: 'c': ['d', 'e'], 'd': ['f'], 'e': ['f']})\n Traceback (most recent call last):\n ...\n LatticeError: no join for b and c\n "
if (isinstance(data, FiniteJoinSemilattice) and (not args) and (not options)):
return data
if ('check' in options):
check = options.pop('check')
else:
check = True
P = Poset(data, *args, **options)
if check:
try:
P._hasse_diagram.join_matrix()
except LatticeError as error:
error.x = P._vertex_to_element(error.x)
error.y = P._vertex_to_element(error.y)
raise
return FiniteJoinSemilattice(P)
|
class FiniteJoinSemilattice(FinitePoset):
'\n We assume that the argument passed to FiniteJoinSemilattice is the\n poset of a join-semilattice (i.e. a poset with least upper bound\n for each pair of elements).\n\n TESTS::\n\n sage: J = JoinSemilattice([[1,2],[3],[3]])\n sage: TestSuite(J).run()\n\n ::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: J = JoinSemilattice(P)\n sage: TestSuite(J).run()\n\n '
Element = JoinSemilatticeElement
_desc = 'Finite join-semilattice'
def join_matrix(self):
'\n Return a matrix whose ``(i,j)`` entry is ``k``, where\n ``self.linear_extension()[k]`` is the join (least upper bound) of\n ``self.linear_extension()[i]`` and ``self.linear_extension()[j]``.\n\n EXAMPLES::\n\n sage: P = LatticePoset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]], facade = False)\n sage: J = P.join_matrix(); J\n [0 1 2 3 4 5 6 7]\n [1 1 3 3 7 7 7 7]\n [2 3 2 3 4 6 6 7]\n [3 3 3 3 7 7 7 7]\n [4 7 4 7 4 7 7 7]\n [5 7 6 7 7 5 6 7]\n [6 7 6 7 7 6 6 7]\n [7 7 7 7 7 7 7 7]\n sage: J[P(4).vertex,P(3).vertex] == P(7).vertex\n True\n sage: J[P(5).vertex,P(2).vertex] == P(5).vertex\n True\n sage: J[P(5).vertex,P(2).vertex] == P(2).vertex\n False\n '
return self._hasse_diagram.join_matrix()
def join(self, x, y=None):
'\n Return the join of given elements in the lattice.\n\n INPUT:\n\n - ``x, y`` -- two elements of the (semi)lattice OR\n - ``x`` -- a list or tuple of elements\n\n EXAMPLES::\n\n sage: D = posets.DiamondPoset(5)\n sage: D.join(1, 2)\n 4\n sage: D.join(1, 1)\n 1\n sage: D.join(1, 4)\n 4\n sage: D.join(1, 0)\n 1\n\n Using list of elements as an argument. Join of empty list is\n the bottom element::\n\n sage: B4=posets.BooleanLattice(4)\n sage: B4.join([2,4,8])\n 14\n sage: B4.join([])\n 0\n\n For non-facade lattices operator ``+`` works for join::\n\n sage: L = posets.PentagonPoset(facade=False)\n sage: L(1)+L(2)\n 4\n\n .. SEEALSO::\n\n - Dual function: :meth:`~sage.combinat.posets.lattices.FiniteMeetSemilattice.meet`\n '
jn = self._hasse_diagram.join_matrix()
if (y is not None):
(i, j) = map(self._element_to_vertex, (x, y))
return self._vertex_to_element(jn[(i, j)])
j = 0
for i in (self._element_to_vertex(_) for _ in x):
j = jn[(i, j)]
return self._vertex_to_element(j)
def coatoms(self):
'\n Return the list of co-atoms of this (semi)lattice.\n\n A *co-atom* of a lattice is an element covered by the top element.\n\n EXAMPLES::\n\n sage: L = posets.DivisorLattice(60)\n sage: sorted(L.coatoms())\n [12, 20, 30]\n\n .. SEEALSO::\n\n - Dual function: :meth:`~FiniteMeetSemilattice.atoms`\n\n TESTS::\n\n sage: LatticePoset().coatoms()\n []\n sage: LatticePoset({0: []}).coatoms()\n []\n '
if (self.cardinality() == 0):
return []
return self.lower_covers(self.top())
|
def LatticePoset(data=None, *args, **options):
"\n Construct a lattice from various forms of input data.\n\n INPUT:\n\n - ``data``, ``*args``, ``**options`` -- data and options that will\n be passed down to :func:`Poset` to construct a poset that is\n also a lattice.\n\n OUTPUT:\n\n An instance of :class:`FiniteLatticePoset`.\n\n .. SEEALSO::\n\n :class:`Posets`, :class:`FiniteLatticePosets`,\n :func:`JoinSemiLattice`, :func:`MeetSemiLattice`\n\n EXAMPLES:\n\n Using data that defines a poset::\n\n sage: LatticePoset([[1,2],[3],[3]])\n Finite lattice containing 3 elements\n\n sage: LatticePoset([[1,2],[3],[3]], cover_relations = True)\n Finite lattice containing 3 elements\n\n Using a previously constructed poset::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: L = LatticePoset(P); L\n Finite lattice containing 3 elements\n sage: type(L)\n <class 'sage.combinat.posets.lattices.FiniteLatticePoset_with_category'>\n\n If the data is not a lattice, then an error is raised::\n\n sage: elms = [1,2,3,4,5,6,7]\n sage: rels = [[1,2],[3,4],[4,5],[2,5]]\n sage: LatticePoset((elms, rels))\n Traceback (most recent call last):\n ...\n ValueError: not a meet-semilattice: no bottom element\n\n Creating a facade lattice::\n\n sage: L = LatticePoset([[1,2],[3],[3]], facade = True)\n sage: L.category()\n Category of facade finite enumerated lattice posets\n sage: parent(L[0])\n Integer Ring\n sage: TestSuite(L).run(skip = ['_test_an_element']) # is_parent_of is not yet implemented\n "
if (isinstance(data, FiniteLatticePoset) and (not args) and (not options)):
return data
if ('check' in options):
check = options.pop('check')
else:
check = True
P = Poset(data, *args, **options)
if (P.cardinality() != 0):
if (not P.has_bottom()):
raise ValueError('not a meet-semilattice: no bottom element')
if check:
try:
P._hasse_diagram.join_matrix()
except LatticeError as error:
error.x = P._vertex_to_element(error.x)
error.y = P._vertex_to_element(error.y)
raise
return FiniteLatticePoset(P, category=FiniteLatticePosets(), facade=P._is_facade)
|
class FiniteLatticePoset(FiniteMeetSemilattice, FiniteJoinSemilattice):
'\n We assume that the argument passed to FiniteLatticePoset is the\n poset of a lattice (i.e. a poset with greatest lower bound and\n least upper bound for each pair of elements).\n\n TESTS::\n\n sage: L = LatticePoset([[1,2],[3],[3]])\n sage: TestSuite(L).run()\n\n ::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: L = LatticePoset(P)\n sage: TestSuite(L).run()\n\n '
Element = LatticePosetElement
def _repr_(self):
"\n TESTS::\n\n sage: L = LatticePoset([[1,2],[3],[3]])\n sage: L._repr_()\n 'Finite lattice containing 3 elements'\n\n ::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: L = LatticePoset(P)\n sage: L._repr_()\n 'Finite lattice containing 3 elements'\n "
s = ('Finite lattice containing %s elements' % self._hasse_diagram.order())
if self._with_linear_extension:
s += ' with distinguished linear extension'
return s
def double_irreducibles(self):
'\n Return the list of double irreducible elements of this lattice.\n\n A *double irreducible* element of a lattice is an element\n covering and covered by exactly one element. In other words\n it is neither a meet nor a join of any elements.\n\n EXAMPLES::\n\n sage: L = posets.DivisorLattice(12)\n sage: sorted(L.double_irreducibles())\n [3, 4]\n\n sage: L = posets.BooleanLattice(3)\n sage: L.double_irreducibles()\n []\n\n .. SEEALSO::\n\n :meth:`~sage.categories.finite_lattice_posets.FiniteLatticePosets.ParentMethods.meet_irreducibles`,\n :meth:`~sage.categories.finite_lattice_posets.FiniteLatticePosets.ParentMethods.join_irreducibles`\n\n TESTS::\n\n sage: LatticePoset().double_irreducibles()\n []\n sage: posets.ChainPoset(2).double_irreducibles()\n []\n '
H = self._hasse_diagram
return [self._vertex_to_element(e) for e in H if ((H.in_degree(e) == 1) and (H.out_degree(e) == 1))]
def join_primes(self):
'\n Return the join-prime elements of the lattice.\n\n An element `x` of a lattice `L` is *join-prime* if `x \\le a \\vee b`\n implies `x \\le a` or `x \\le b` for every `a, b \\in L`.\n\n These are also called *coprime* in some books. Every join-prime\n is join-irreducible; converse holds if and only if the lattice\n is distributive.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [5],\n ....: 4: [6], 5: [7], 6: [7]})\n sage: L.join_primes()\n [3, 4]\n\n sage: D12 = posets.DivisorLattice(12) # Distributive lattice\n sage: D12.join_irreducibles() == D12.join_primes()\n True\n\n .. SEEALSO::\n\n - Dual function: :meth:`meet_primes`\n - Other: :meth:`~sage.categories.finite_lattice_posets.FiniteLatticePosets.ParentMethods.join_irreducibles`\n\n TESTS::\n\n sage: LatticePoset().join_primes()\n []\n sage: posets.DiamondPoset(5).join_primes()\n []\n '
return [self._vertex_to_element(v) for v in self._hasse_diagram.prime_elements()[0]]
def meet_primes(self):
'\n Return the meet-prime elements of the lattice.\n\n An element `x` of a lattice `L` is *meet-prime* if `x \\ge a \\wedge b`\n implies `x \\ge a` or `x \\ge b` for every `a, b \\in L`.\n\n These are also called just *prime* in some books. Every meet-prime\n is meet-irreducible; converse holds if and only if the lattice\n is distributive.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [5],\n ....: 4: [6], 5: [7], 6: [7]})\n sage: L.meet_primes()\n [6, 5]\n\n sage: D12 = posets.DivisorLattice(12)\n sage: sorted(D12.meet_primes())\n [3, 4, 6]\n\n .. SEEALSO::\n\n - Dual function: :meth:`join_primes`\n - Other: :meth:`~sage.categories.finite_lattice_posets.FiniteLatticePosets.ParentMethods.meet_irreducibles`\n\n TESTS::\n\n sage: LatticePoset().meet_primes()\n []\n sage: posets.DiamondPoset(5).meet_primes()\n []\n '
return [self._vertex_to_element(v) for v in self._hasse_diagram.prime_elements()[1]]
def neutral_elements(self):
"\n Return the list of neutral elements of the lattice.\n\n An element `e` of the lattice `L` is *neutral* if the sublattice\n generated by `e`, `x` and `y` is distributive for all `x, y \\in L`.\n It can also be characterized as an element of intersection of\n maximal distributive sublattices.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3], 2: [6], 3: [4, 5, 6], 4: [8],\n ....: 5: [7], 6: [7], 7: [8, 9], 8: [10], 9: [10]})\n sage: L.neutral_elements()\n [1, 3, 8, 10]\n\n TESTS::\n\n sage: all(posets.ChainPoset(i).neutral_elements() == list(range(i))\n ....: for i in range(4))\n True\n\n sage: posets.BooleanLattice(3).neutral_elements()\n [0, 1, 2, 3, 4, 5, 6, 7]\n\n sage: L = LatticePoset(DiGraph('QQG?LA??__?OG@C??p???O??A?E??@??@g??Q??S??@??E??@??@???'))\n sage: L.neutral_elements()\n [0, 1, 4, 5, 15, 17]\n "
t = sorted(self._hasse_diagram.neutral_elements())
return [self._vertex_to_element(v) for v in t]
def is_join_distributive(self, certificate=False):
"\n Return ``True`` if the lattice is join-distributive and ``False``\n otherwise.\n\n A lattice is *join-distributive* if every interval from an element\n to the join of the element's upper covers is a distributive lattice.\n Actually this distributive sublattice is then a Boolean lattice.\n\n They are also called as *Dilworth's lattices* and *upper locally\n distributive lattices*. They can be characterized in many other\n ways, see [Dil1940]_.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where `e` is an element such that the interval\n from `e` to the meet of upper covers of `e` is not distributive.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [5, 7],\n ....: 4: [6, 7], 5: [8, 9], 6: [9], 7: [9, 10],\n ....: 8: [11], 9: [11], 10: [11]})\n sage: L.is_join_distributive()\n True\n\n sage: L = LatticePoset({1: [2], 2: [3, 4], 3: [5], 4: [6],\n ....: 5: [7], 6: [7]})\n sage: L.is_join_distributive()\n False\n sage: L.is_join_distributive(certificate=True)\n (False, 2)\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_meet_distributive`\n - Weaker properties: :meth:`is_meet_semidistributive`,\n :meth:`is_upper_semimodular`\n - Stronger properties: :meth:`is_distributive`\n\n TESTS::\n\n sage: E = LatticePoset()\n sage: E.is_join_distributive()\n True\n sage: E.is_join_distributive(certificate=True)\n (True, None)\n\n sage: L = LatticePoset({1: []})\n sage: L.is_join_distributive()\n True\n sage: L.is_join_distributive(certificate=True)\n (True, None)\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3: [5, 6],\n ....: 4: [6], 5: [7], 6:[7]})\n sage: L.is_join_distributive()\n False\n sage: L.is_join_distributive(certificate=True)\n (False, 1)\n\n sage: L = LatticePoset({1: [2], 2: [3, 4, 5], 3: [6], 4: [6], 5: [6]})\n sage: L.is_join_distributive(certificate=True)\n (False, 2)\n "
if ((self.is_ranked() and (len(self.meet_irreducibles()) == self.rank())) or (self.cardinality() == 0)):
return ((True, None) if certificate else True)
if (not certificate):
return False
result = self.is_upper_semimodular(certificate=True)
if (not result[0]):
return (False, self.meet(result[1]))
from sage.graphs.digraph import DiGraph
M3 = DiGraph({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})
diamond = next(self._hasse_diagram.subgraph_search_iterator(M3, return_graphs=False))
return (False, self[diamond[0]])
def is_meet_distributive(self, certificate=False):
"\n Return ``True`` if the lattice is meet-distributive and ``False``\n otherwise.\n\n A lattice is *meet-distributive* if every interval to an element\n from the meet of the element's lower covers is a distributive lattice.\n Actually this distributive sublattice is then a Boolean lattice.\n\n They are also called as *lower locally distributive lattices*.\n They can be characterized in many other ways, see [Dil1940]_.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where `e` is an element such that the interval\n to `e` from the meet of lower covers of `e` is not distributive.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3: [5, 6, 7],\n ....: 4: [7], 5: [9, 8], 6: [10, 8], 7:\n ....: [9, 10], 8: [11], 9: [11], 10: [11]})\n sage: L.is_meet_distributive()\n True\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [5], 4: [6],\n ....: 5: [6], 6: [7]})\n sage: L.is_meet_distributive()\n False\n sage: L.is_meet_distributive(certificate=True)\n (False, 6)\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_join_distributive`\n - Weaker properties: :meth:`is_join_semidistributive`,\n :meth:`is_lower_semimodular`\n - Stronger properties: :meth:`is_distributive`\n\n TESTS::\n\n sage: E = LatticePoset()\n sage: E.is_meet_distributive()\n True\n sage: E.is_meet_distributive(certificate=True)\n (True, None)\n\n sage: L = LatticePoset({1: []})\n sage: L.is_meet_distributive()\n True\n sage: L.is_meet_distributive(certificate=True)\n (True, None)\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [5, 6], 4: [7],\n ....: 5: [7], 6: [7]})\n sage: L.is_meet_distributive()\n False\n sage: L.is_meet_distributive(certificate=True)\n (False, 7)\n\n sage: L = LatticePoset({1: [2], 2: [3, 4, 5], 3: [6], 4: [6], 5: [6]})\n sage: L.is_meet_distributive(certificate=True)\n (False, 6)\n "
if ((self.is_ranked() and (len(self.join_irreducibles()) == self.rank())) or (self.cardinality() == 0)):
return ((True, None) if certificate else True)
if (not certificate):
return False
result = self.is_lower_semimodular(certificate=True)
if (not result[0]):
return (False, self.join(result[1]))
from sage.graphs.digraph import DiGraph
M3 = DiGraph({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})
diamond = next(self._hasse_diagram.subgraph_search_iterator(M3, return_graphs=False))
return (False, self[diamond[4]])
def is_stone(self, certificate=False):
"\n Return ``True`` if the lattice is a Stone lattice, and ``False``\n otherwise.\n\n The lattice is expected to be distributive (and hence\n pseudocomplemented).\n\n A pseudocomplemented lattice is a Stone lattice if\n\n .. MATH::\n\n e^* \\vee e^{**} = \\top\n\n for every element `e` of the lattice, where `^*` is the\n pseudocomplement and `\\top` is the top element of the lattice.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)`` such that `e^* \\vee e^{**} \\neq \\top`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES:\n\n Divisor lattices are canonical example::\n\n sage: D72 = posets.DivisorLattice(72)\n sage: D72.is_stone()\n True\n\n A non-example::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [4], 4: [5]})\n sage: L.is_stone()\n False\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_distributive`\n\n TESTS::\n\n sage: LatticePoset().is_stone() # Empty lattice\n True\n\n sage: L = LatticePoset(DiGraph('GW?_W@?W@?O?'))\n sage: L.is_stone() # Pass the fast check, but not a Stone lattice\n False\n "
if (not self.is_distributive()):
raise ValueError('the lattice is not distributive')
from sage.arith.misc import factor
ok = ((True, None) if certificate else True)
if (self.cardinality() < 5):
return ok
atoms_n = self._hasse_diagram.out_degree(0)
if (atoms_n == 1):
return ok
if (not certificate):
if (sum([x[1] for x in factor(self.cardinality())]) < atoms_n):
return False
if (self._hasse_diagram.in_degree((self.cardinality() - 1)) < atoms_n):
return False
one = self.top()
tested = set()
for e in self:
e_ = self.pseudocomplement(e)
if (e_ not in tested):
if (self.join(e_, self.pseudocomplement(e_)) != one):
if certificate:
return (False, e)
return False
tested.add(e_)
return ok
def is_distributive(self, certificate=False):
'\n Return ``True`` if the lattice is distributive, and ``False``\n otherwise.\n\n A lattice `(L, \\vee, \\wedge)` is distributive if meet\n distributes over join: `x \\wedge (y \\vee z) = (x \\wedge y)\n \\vee (x \\wedge z)` for every `x,y,z \\in L` just like `x \\cdot\n (y+z)=x \\cdot y + x \\cdot z` in normal arithmetic. For duality\n in lattices it follows that then also join distributes over\n meet.\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (x, y, z))``, where `x`, `y` and `z` are elements\n of the lattice such that\n `x \\wedge (y \\vee z) \\neq (x \\wedge y) \\vee (x \\wedge z)`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [4], 4: [5]})\n sage: L.is_distributive()\n True\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3: [6], 4: [6], 5: [6]})\n sage: L.is_distributive()\n False\n sage: L.is_distributive(certificate=True)\n (False, (5, 3, 2))\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_modular`,\n :meth:`is_semidistributive`, :meth:`is_join_distributive`,\n :meth:`is_meet_distributive`, :meth:`is_subdirectly_reducible`,\n :meth:`is_trim`,\n :meth:`is_constructible_by_doublings` (by interval doubling),\n :meth:`is_extremal`\n\n - Stronger properties: :meth:`is_stone`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_distributive() for i in range(3)]\n [True, True, True]\n '
from sage.graphs.digraph import DiGraph
ok = ((True, None) if certificate else True)
if (self.cardinality() == 0):
return ok
if (self.is_graded() and (self.rank() == len(self.join_irreducibles()) == len(self.meet_irreducibles()))):
return ok
if (not certificate):
return False
(result, cert) = self.is_modular(certificate=True)
if (not result):
return (False, (cert[2], cert[1], cert[0]))
M3 = DiGraph({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})
diamond = next(self._hasse_diagram.subgraph_search_iterator(M3, return_graphs=False))
return (False, (self._vertex_to_element(diamond[1]), self._vertex_to_element(diamond[2]), self._vertex_to_element(diamond[3])))
def is_semidistributive(self):
'\n Return ``True`` if the lattice is both join- and meet-semidistributive,\n and ``False`` otherwise.\n\n EXAMPLES:\n\n Tamari lattices are typical examples of semidistributive but not\n distributive (and hence not modular) lattices::\n\n sage: T4 = posets.TamariLattice(4)\n sage: T4.is_semidistributive(), T4.is_distributive()\n (True, False)\n\n Smallest non-selfdual example::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [5], 4: [6], 5: [7], 6: [7]})\n sage: L.is_semidistributive()\n True\n\n The diamond is not semidistributive::\n\n sage: L = posets.DiamondPoset(5)\n sage: L.is_semidistributive()\n False\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_join_semidistributive`,\n :meth:`is_meet_semidistributive`\n - Stronger properties: :meth:`is_distributive`\n\n TESTS::\n\n sage: LatticePoset().is_semidistributive()\n True\n sage: LatticePoset({1: []}).is_semidistributive()\n True\n '
H = self._hasse_diagram
return ((H.in_degree_sequence().count(1) == H.out_degree_sequence().count(1)) and self.is_meet_semidistributive())
def is_meet_semidistributive(self, certificate=False):
"\n Return ``True`` if the lattice is meet-semidistributive, and ``False``\n otherwise.\n\n A lattice is meet-semidistributive if for all elements\n `e, x, y` in the lattice we have\n\n .. MATH::\n\n e \\wedge x = e \\wedge y \\implies\n e \\wedge x = e \\wedge (x \\vee y)\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (e, x, y))`` such that `e \\wedge x = e \\wedge y`\n but `e \\wedge x \\neq e \\wedge (x \\vee y)`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1:[2, 3, 4], 2:[4, 5], 3:[5, 6],\n ....: 4:[7], 5:[7], 6:[7]})\n sage: L.is_meet_semidistributive()\n True\n sage: L_ = L.dual()\n sage: L_.is_meet_semidistributive()\n False\n sage: L_.is_meet_semidistributive(certificate=True)\n (False, (5, 4, 6))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_join_semidistributive`\n - Weaker properties: :meth:`is_pseudocomplemented`,\n :meth:`is_interval_dismantlable`\n - Stronger properties: :meth:`is_semidistributive`,\n :meth:`is_join_distributive`,\n :meth:`is_constructible_by_doublings` (by upper pseudo-intervals)\n\n TESTS::\n\n sage: LatticePoset().is_meet_semidistributive()\n True\n\n Smallest lattice that fails the quick check::\n\n sage: L = LatticePoset(DiGraph('IY_T@A?CC_@?W?O@??'))\n sage: L.is_meet_semidistributive()\n False\n\n Confirm that :trac:`21340` is fixed::\n\n sage: posets.BooleanLattice(4).is_meet_semidistributive()\n True\n "
n = self.cardinality()
if (n == 0):
if certificate:
return (True, None)
return True
H = self._hasse_diagram
if ((not certificate) and ((H.size() * 2) > (n * _log_2(n)))):
return False
for v in H:
if ((H.in_degree(v) == 1) and (H.kappa(v) is None)):
if (not certificate):
return False
v_ = next(H.neighbor_in_iterator(v))
t1 = set(H.depth_first_search(v_))
t2 = set(H.depth_first_search(v))
tmp = sorted(t1.difference(t2), reverse=True)
x = tmp[0]
for y in tmp:
if H.are_incomparable(x, y):
return (False, (self._vertex_to_element(v), self._vertex_to_element(x), self._vertex_to_element(y)))
if certificate:
return (True, None)
return True
def is_join_semidistributive(self, certificate=False):
"\n Return ``True`` if the lattice is join-semidistributive, and ``False``\n otherwise.\n\n A lattice is join-semidistributive if for all elements `e, x, y` in\n the lattice we have\n\n .. MATH::\n\n e \\vee x = e \\vee y \\implies\n e \\vee x = e \\vee (x \\wedge y)\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (e, x, y))`` such that `e \\vee x = e \\vee y`\n but `e \\vee x \\neq e \\vee (x \\wedge y)`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: T4 = posets.TamariLattice(4)\n sage: T4.is_join_semidistributive()\n True\n sage: L = LatticePoset({1:[2, 3], 2:[4, 5], 3:[5, 6],\n ....: 4:[7], 5:[7], 6:[7]})\n sage: L.is_join_semidistributive()\n False\n sage: L.is_join_semidistributive(certificate=True)\n (False, (5, 4, 6))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_meet_semidistributive`\n - Weaker properties: :meth:`is_join_pseudocomplemented`,\n :meth:`is_interval_dismantlable`\n - Stronger properties: :meth:`is_semidistributive`,\n :meth:`is_meet_distributive`,\n :meth:`is_constructible_by_doublings` (by lower pseudo-intervals)\n\n TESTS::\n\n sage: LatticePoset().is_join_semidistributive()\n True\n\n Smallest lattice that fails the quick check::\n\n sage: L = LatticePoset(DiGraph('IY_T@A?CC_@?W?O@??'))\n sage: L.is_join_semidistributive()\n False\n\n Confirm that :trac:`21340` is fixed::\n\n sage: posets.BooleanLattice(3).is_join_semidistributive()\n True\n "
n = self.cardinality()
if (n == 0):
if certificate:
return (True, None)
return True
H = self._hasse_diagram
if ((not certificate) and ((H.size() * 2) > (n * _log_2(n)))):
return False
for v in H:
if ((H.out_degree(v) == 1) and (H.kappa_dual(v) is None)):
if (not certificate):
return False
v_ = next(H.neighbor_out_iterator(v))
it = H.neighbor_in_iterator
t1 = set(H.depth_first_search(v_, neighbors=it))
t2 = set(H.depth_first_search(v, neighbors=it))
tmp = sorted(t1.difference(t2))
x = tmp[0]
for y in tmp:
if H.are_incomparable(x, y):
return (False, (self._vertex_to_element(v), self._vertex_to_element(x), self._vertex_to_element(y)))
if certificate:
return (True, None)
return True
return all(((H.kappa_dual(v) is not None) for v in H if (H.out_degree(v) == 1)))
def is_extremal(self):
'\n Return ``True`` if the lattice is extremal, and ``False``\n otherwise.\n\n A lattice is *extremal* if the number of join-irreducibles is equal\n to the number of meet-irreducibles and to the number of\n cover relations in the longest chains.\n\n EXAMPLES::\n\n sage: posets.PentagonPoset().is_extremal()\n True\n\n sage: P = LatticePoset(posets.SymmetricGroupWeakOrderPoset(3))\n sage: P.is_extremal()\n False\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_distributive`, :meth:`is_trim`\n\n REFERENCES:\n\n - [Mark1992]_\n '
ji = len(self.join_irreducibles())
mi = len(self.meet_irreducibles())
return (ji == mi == (self.height() - 1))
def is_trim(self, certificate=False):
'\n Return whether a lattice is trim.\n\n A lattice is trim if it is extremal and left modular.\n\n This notion is defined in [Thom2006]_.\n\n INPUT:\n\n - certificate -- boolean (default ``False``) whether to return\n instead a maximum chain of left modular elements\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.is_trim()\n True\n\n sage: Q = LatticePoset(posets.SymmetricGroupWeakOrderPoset(3))\n sage: Q.is_trim()\n False\n\n TESTS::\n\n sage: LatticePoset({1:[]}).is_trim(True)\n (True, [1])\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_extremal`\n - Stronger properties: :meth:`is_distributive`\n\n REFERENCES:\n\n .. [Thom2006] Hugh Thomas, *An analogue of distributivity for\n ungraded lattices*. Order 23 (2006), no. 2-3, 249-269.\n '
ji = len(self.join_irreducibles())
mi = len(self.meet_irreducibles())
(h, chain) = self.height(certificate=True)
if (not (ji == mi == (h - 1))):
return ((False, None) if certificate else False)
if all((self.is_left_modular_element(e) for e in chain)):
return ((True, chain) if certificate else True)
else:
return ((False, None) if certificate else False)
def is_complemented(self, certificate=False):
'\n Return ``True`` if the lattice is complemented, and\n ``False`` otherwise.\n\n A lattice is complemented if every element has at least one\n complement.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where ``e`` is an element without a complement.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0: [1, 2, 3], 1: [4], 2: [4], 3: [4]})\n sage: L.is_complemented()\n True\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [5], 4: [6],\n ....: 5: [7], 6: [7]})\n sage: L.is_complemented()\n False\n sage: L.is_complemented(certificate=True)\n (False, 2)\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_sectionally_complemented`,\n :meth:`is_cosectionally_complemented`,\n :meth:`is_orthocomplemented`\n - Other: :meth:`complements`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_complemented() for i in range(5)]\n [True, True, True, False, False]\n '
e = self._hasse_diagram.is_complemented()
if (not certificate):
return (e is None)
if (e is None):
return (True, None)
return (False, self._vertex_to_element(e))
def is_cosectionally_complemented(self, certificate=False):
"\n Return ``True`` if the lattice is cosectionally complemented, and\n ``False`` otherwise.\n\n A lattice is *cosectionally complemented* if all intervals to\n the top element interpreted as sublattices are complemented\n lattices.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate if the lattice is not cosectionally complemented.\n\n OUTPUT:\n\n - If ``certificate=False`` return ``True`` or ``False``.\n If ``certificate=True`` return either ``(True, None)``\n or ``(False, (b, e))``, where `b` is an element so that in the\n sublattice from `b` to the top element has no complement\n for element `e`.\n\n EXAMPLES:\n\n The smallest sectionally but not cosectionally complemented lattice::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3: [5], 4: [6], 5: [6]})\n sage: L.is_sectionally_complemented(), L.is_cosectionally_complemented()\n (True, False)\n\n A sectionally and cosectionally but not relatively complemented\n lattice::\n\n sage: L = LatticePoset(DiGraph('MYi@O?P??D?OG?@?O_?C?Q??O?W?@??O??'))\n sage: L.is_sectionally_complemented() and L.is_cosectionally_complemented()\n True\n sage: L.is_relatively_complemented()\n False\n\n Getting a certificate::\n\n sage: L = LatticePoset(DiGraph('HW?@D?Q?GE?G@??'))\n sage: L.is_cosectionally_complemented(certificate=True)\n (False, (2, 7))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_sectionally_complemented`\n - Weaker properties: :meth:`is_complemented`, :meth:`is_coatomic`,\n :meth:`is_regular`\n - Stronger properties: :meth:`is_relatively_complemented`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_cosectionally_complemented() for i in range(5)]\n [True, True, True, False, False]\n "
if ((not certificate) and (not self.is_coatomic())):
return False
H = self._hasse_diagram
jn = H.join_matrix()
n = H.order()
for e in range((n - 2), (- 1), (- 1)):
t = 0
for uc in H.neighbor_out_iterator(e):
t = jn[(t, uc)]
if (t == (n - 1)):
break
else:
if certificate:
return (False, (self[e], self[t]))
return False
return ((True, None) if certificate else True)
def is_relatively_complemented(self, certificate=False):
"\n Return ``True`` if the lattice is relatively complemented, and\n ``False`` otherwise.\n\n A lattice is relatively complemented if every interval of it\n is a complemented lattice.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate if the lattice is not relatively complemented.\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b, c))``, where `b` is the only element that\n covers `a` and is covered by `c`. If ``certificate=False``\n return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4, 8], 2: [5, 6], 3: [5, 7],\n ....: 4: [6, 7], 5: [9], 6: [9], 7: [9], 8: [9]})\n sage: L.is_relatively_complemented()\n True\n\n sage: L = posets.PentagonPoset()\n sage: L.is_relatively_complemented()\n False\n\n Relatively complemented lattice must be both atomic and coatomic.\n Implication to other direction does not hold::\n\n sage: L = LatticePoset({0: [1, 2, 3, 4, 5], 1: [6, 7], 2: [6, 8],\n ....: 3: [7, 8, 9], 4: [9, 11], 5: [9, 10],\n ....: 6: [10, 11], 7: [12], 8: [12], 9: [12],\n ....: 10: [12], 11: [12]})\n sage: L.is_atomic() and L.is_coatomic()\n True\n sage: L.is_relatively_complemented()\n False\n\n We can also get a non-complemented 3-element interval::\n\n sage: L.is_relatively_complemented(certificate=True)\n (False, (1, 6, 11))\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_sectionally_complemented`,\n :meth:`is_cosectionally_complemented`, :meth:`is_isoform`\n - Stronger properties: :meth:`is_geometric`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_relatively_complemented() for\n ....: i in range(5)]\n [True, True, True, False, False]\n\n Usually a lattice that is not relatively complemented contains elements\n `l`, `m`, and `u` such that `r(l) + 1 = r(m) = r(u) - 1`, where `r` is\n the rank function and `m` is the only element in the interval `[l, u]`.\n We construct an example where this does not hold::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B5 = posets.BooleanLattice(5)\n sage: B3 = B3.subposet([e for e in B3 if e not in [0, 7]])\n sage: B5 = B5.subposet([e for e in B5 if e not in [0, 31]])\n sage: B3 = B3.hasse_diagram()\n sage: B5 = B5.relabel(lambda x: x+10).hasse_diagram()\n sage: G = B3.union(B5)\n sage: G.add_edge(B3.sources()[0], B5.neighbors_in(B5.sinks()[0])[0])\n sage: L = LatticePoset(Poset(G).with_bounds())\n sage: L.is_relatively_complemented()\n False\n\n Confirm that :trac:`22292` is fixed::\n\n sage: L = LatticePoset(DiGraph('IYOS`G?CE?@?C?_@??'))\n sage: L.is_relatively_complemented(certificate=True)\n (False, (7, 8, 9))\n "
from sage.misc.flatten import flatten
from collections import Counter
H = self._hasse_diagram
n = H.order()
if (n < 3):
return ((True, None) if certificate else True)
if (not certificate):
if (H.out_degree(0) != H.in_degree().count(1)):
return False
if (H.in_degree((n - 1)) != H.out_degree().count(1)):
return False
for e1 in range((n - 1)):
C = Counter(flatten([H.neighbors_out(e2) for e2 in H.neighbor_out_iterator(e1)]))
for (e3, c) in C.items():
if ((c == 1) and (len(H.closed_interval(e1, e3)) == 3)):
if (not certificate):
return False
for e2 in H.neighbor_in_iterator(e3):
if (e2 in H.neighbor_out_iterator(e1)):
break
return (False, (self._vertex_to_element(e1), self._vertex_to_element(e2), self._vertex_to_element(e3)))
return ((True, None) if certificate else True)
def is_sectionally_complemented(self, certificate=False):
"\n Return ``True`` if the lattice is sectionally complemented, and\n ``False`` otherwise.\n\n A lattice is sectionally complemented if all intervals from\n the bottom element interpreted as sublattices are complemented\n lattices.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate if the lattice is not sectionally complemented.\n\n OUTPUT:\n\n - If ``certificate=False`` return ``True`` or ``False``.\n If ``certificate=True`` return either ``(True, None)``\n or ``(False, (t, e))``, where `t` is an element so that in the\n sublattice from the bottom element to `t` has no complement\n for element `e`.\n\n EXAMPLES:\n\n Smallest examples of a complemented but not sectionally complemented\n lattice and a sectionally complemented but not relatively complemented\n lattice::\n\n sage: L = posets.PentagonPoset()\n sage: L.is_complemented()\n True\n sage: L.is_sectionally_complemented()\n False\n\n sage: L = LatticePoset({0: [1, 2, 3], 1: [4], 2: [4], 3: [5], 4: [5]})\n sage: L.is_sectionally_complemented()\n True\n sage: L.is_relatively_complemented()\n False\n\n Getting a certificate::\n\n sage: L = LatticePoset(DiGraph('HYOgC?C@?C?G@??'))\n sage: L.is_sectionally_complemented(certificate=True)\n (False, (6, 1))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_cosectionally_complemented`\n - Weaker properties: :meth:`is_complemented`, :meth:`is_atomic`,\n :meth:`is_regular`\n - Stronger properties: :meth:`is_relatively_complemented`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_sectionally_complemented() for i in range(5)]\n [True, True, True, False, False]\n "
if ((not certificate) and (not self.is_atomic())):
return False
H = self._hasse_diagram
mt = H.meet_matrix()
n = (H.order() - 1)
for e in range(2, (n + 1)):
t = n
for lc in H.neighbor_in_iterator(e):
t = mt[(t, lc)]
if (t == 0):
break
else:
if certificate:
return (False, (self[e], self[t]))
return False
return ((True, None) if certificate else True)
def breadth(self, certificate=False):
'\n Return the breadth of the lattice.\n\n The breadth of a lattice is the largest integer `n` such that\n any join of elements `x_1, x_2, \\ldots, x_{n+1}` is join of a\n proper subset of `x_i`.\n\n This can be also characterized by subposets: a lattice\n of breadth at least `n` contains a subposet isomorphic to the\n Boolean lattice of `2^n` elements.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return the pair `(b, a)` where `b` is\n the breadth and `a` is an antichain such that the join of `a`\n differs from the join of any proper subset of `a`.\n If ``certificate=False`` return just the breadth.\n\n EXAMPLES::\n\n sage: D10 = posets.DiamondPoset(10)\n sage: D10.breadth()\n 2\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3.breadth()\n 3\n sage: B3.breadth(certificate=True)\n (3, [1, 2, 4])\n\n ALGORITHM:\n\n For a lattice to have breadth at least `n`, it must have an\n `n`-element antichain `A` with join `j`. Element `j` must\n cover at least `n` elements. There must also be `n-2` levels\n of elements between `A` and `j`. So we start by searching\n elements that could be our `j` and then just check possible\n antichains `A`.\n\n .. NOTE::\n\n Prior to version 8.1 this function returned just an\n antichain with ``certificate=True``.\n\n TESTS::\n\n sage: posets.ChainPoset(0).breadth()\n 0\n sage: posets.ChainPoset(1).breadth()\n 1\n '
from sage.combinat.subsets_pairwise import PairwiseCompatibleSubsets
n = self.cardinality()
if (n == 0):
return ((0, []) if certificate else 0)
if self.is_chain():
return ((1, [self.bottom()]) if certificate else 1)
H = self._hasse_diagram
jn = H.join_matrix()
def join(L):
j = 0
for i in L:
j = jn[(i, j)]
return j
indegs = [H.in_degree(i) for i in range(n)]
max_breadth = max(indegs)
for B in range(max_breadth, 1, (- 1)):
for j in H:
if (indegs[j] < B):
continue
too_close = set(H.breadth_first_search(j, neighbors=H.neighbor_in_iterator, distance=(B - 2)))
elems = [e for e in H.order_ideal([j]) if (e not in too_close)]
achains = PairwiseCompatibleSubsets(elems, H.are_incomparable)
achains_n = achains.elements_of_depth_iterator(B)
for A in achains_n:
if (join(A) == j):
if all(((join((A[:i] + A[(i + 1):])) != j) for i in range(B))):
if certificate:
return (B, [self._vertex_to_element(e) for e in A])
else:
return B
assert False, 'BUG: breadth() in lattices.py have an error.'
def complements(self, element=None):
"\n Return the list of complements of an element in the lattice,\n or the dictionary of complements for all elements.\n\n Elements `x` and `y` are complements if their meet and join\n are respectively the bottom and the top element of the lattice.\n\n INPUT:\n\n - ``element`` -- an element of the lattice whose complement is\n returned. If ``None`` (default) then dictionary of\n complements for all elements having at least one\n complement is returned.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0:['a','b','c'],'a':[1],'b':[1],'c':[1]})\n sage: C = L.complements()\n\n Let us check that 'a' and 'b' are complements of each other::\n\n sage: 'a' in C['b']\n True\n sage: 'b' in C['a']\n True\n\n Full list of complements::\n\n sage: L.complements() # random order\n {0: [1], 1: [0], 'a': ['b', 'c'], 'b': ['c', 'a'], 'c': ['b', 'a']}\n\n sage: L = LatticePoset({0:[1,2],1:[3],2:[3],3:[4]})\n sage: L.complements() # random order\n {0: [4], 4: [0]}\n sage: L.complements(1)\n []\n\n .. SEEALSO:: :meth:`is_complemented`\n\n TESTS::\n\n sage: L = LatticePoset({0:['a','b','c'], 'a':[1], 'b':[1], 'c':[1]})\n sage: for v,v_complements in L.complements().items():\n ....: for v_c in v_complements:\n ....: assert L.meet(v,v_c) == L.bottom()\n ....: assert L.join(v,v_c) == L.top()\n\n sage: posets.ChainPoset(0).complements()\n {}\n sage: posets.ChainPoset(1).complements()\n {0: [0]}\n sage: posets.ChainPoset(2).complements()\n {0: [1], 1: [0]}\n "
if (element is None):
n = self.cardinality()
if (n == 1):
return {self[0]: [self[0]]}
jn = self.join_matrix()
mt = self.meet_matrix()
zero = 0
one = (n - 1)
c = [[] for _ in repeat(None, n)]
for x in range(n):
for y in range(x, n):
if ((jn[x][y] == one) and (mt[x][y] == zero)):
c[x].append(y)
c[y].append(x)
comps = {}
for i in range(n):
if c[i]:
comps[self._vertex_to_element(i)] = [self._vertex_to_element(x) for x in c[i]]
return comps
if (element not in self):
raise ValueError(('element (=%s) not in poset' % element))
return [x for x in self if ((self.meet(x, element) == self.bottom()) and (self.join(x, element) == self.top()))]
def is_pseudocomplemented(self, certificate=False):
'\n Return ``True`` if the lattice is pseudocomplemented, and ``False``\n otherwise.\n\n A lattice is (meet-)pseudocomplemented if every element `e` has a\n pseudocomplement `e^\\star`, i.e. the greatest element such that\n the meet of `e` and `e^\\star` is the bottom element.\n\n See :wikipedia:`Pseudocomplement`.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where ``e`` is an element without a\n pseudocomplement. If ``certificate=False`` return ``True``\n or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 5], 2: [3, 6], 3: [4], 4: [7],\n ....: 5: [6], 6: [7]})\n sage: L.is_pseudocomplemented()\n True\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5, 6], 3: [6], 4: [7],\n ....: 5: [7], 6: [7]})\n sage: L.is_pseudocomplemented()\n False\n sage: L.is_pseudocomplemented(certificate=True)\n (False, 3)\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_join_pseudocomplemented`\n - Stronger properties: :meth:`is_meet_semidistributive`\n - Other: :meth:`~sage.combinat.posets.lattices.FiniteMeetSemilattice.pseudocomplement()`.\n\n ALGORITHM:\n\n According to [Cha92]_ a lattice is pseudocomplemented if and\n only if every atom has a pseudocomplement. So we only check those.\n\n TESTS::\n\n sage: LatticePoset({}).is_pseudocomplemented()\n True\n '
H = self._hasse_diagram
if (H.order() == 0):
if certificate:
return (True, None)
return True
for e in H.neighbor_out_iterator(0):
if (H.kappa(e) is None):
if certificate:
return (False, self._vertex_to_element(e))
return False
if certificate:
return (True, None)
return True
def is_join_pseudocomplemented(self, certificate=False):
"\n Return ``True`` if the lattice is join-pseudocomplemented, and\n ``False`` otherwise.\n\n A lattice is join-pseudocomplemented if every element `e` has a\n join-pseudocomplement `e'`, i.e. the least element such that\n the join of `e` and `e'` is the top element.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where ``e`` is an element without a\n join-pseudocomplement. If ``certificate=False`` return ``True``\n or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 5], 2: [3, 6], 3: [4], 4: [7],\n ....: 5: [6], 6: [7]})\n sage: L.is_join_pseudocomplemented()\n True\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5, 6], 3: [6], 4: [7],\n ....: 5: [7], 6: [7]})\n sage: L.is_join_pseudocomplemented()\n False\n sage: L.is_join_pseudocomplemented(certificate=True)\n (False, 4)\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_pseudocomplemented`\n - Stronger properties: :meth:`is_join_semidistributive`\n\n TESTS::\n\n sage: LatticePoset({}).is_pseudocomplemented()\n True\n "
H = self._hasse_diagram
if (H.order() == 0):
if certificate:
return (True, None)
return True
for e in H.neighbor_in_iterator((H.order() - 1)):
if (H.kappa_dual(e) is None):
if certificate:
return (False, self._vertex_to_element(e))
return False
if certificate:
return (True, None)
return True
def skeleton(self):
'\n Return the skeleton of the lattice.\n\n The lattice is expected to be pseudocomplemented.\n\n The *skeleton* of a pseudocomplemented lattice `L`, where `^*` is\n the pseudocomplementation operation, is the subposet induced by\n `\\{e^* \\mid e \\in L\\}`. Actually this poset is a Boolean lattice.\n\n EXAMPLES::\n\n sage: D12 = posets.DivisorLattice(12)\n sage: S = D12.skeleton(); S\n Finite lattice containing 4 elements\n sage: S.cover_relations()\n [[1, 3], [1, 4], [3, 12], [4, 12]]\n\n sage: T4 = posets.TamariLattice(4)\n sage: T4.skeleton().is_isomorphic(posets.BooleanLattice(3))\n True\n\n .. SEEALSO:: :meth:`sage.combinat.posets.lattices.FiniteMeetSemilattice.pseudocomplement`.\n\n TESTS::\n\n sage: posets.ChainPoset(0).skeleton()\n Finite lattice containing 0 elements\n sage: posets.ChainPoset(1).skeleton()\n Finite lattice containing 1 elements\n sage: posets.ChainPoset(2).skeleton()\n Finite lattice containing 2 elements\n sage: posets.ChainPoset(3).skeleton()\n Finite lattice containing 2 elements\n\n sage: L = posets.BooleanLattice(3)\n sage: L == L.skeleton()\n True\n\n sage: posets.DiamondPoset(5).skeleton()\n Traceback (most recent call last):\n ...\n ValueError: lattice is not pseudocomplemented\n '
if (self.cardinality() < 3):
return self
elms = [self._vertex_to_element(v) for v in self._hasse_diagram.skeleton()]
return LatticePoset(self.subposet(elms))
def is_orthocomplemented(self, unique=False):
'\n Return ``True`` if the lattice admits an orthocomplementation, and\n ``False`` otherwise.\n\n An orthocomplementation of a lattice is a function defined for\n every element `e` and marked as `e^{\\bot}` such that\n 1) they are complements, i.e. `e \\vee e^{\\bot}` is the top element\n and `e \\wedge e^{\\bot}` is the bottom element, 2) it is involution,\n i.e. `{(e^{\\bot})}^{\\bot} = e`, and 3) it is order-reversing, i.e.\n if `a < b` then `b^{\\bot} < a^{\\bot}`.\n\n INPUT:\n\n - ``unique``, a Boolean -- If ``True``, return ``True`` only\n if the lattice has exactly one orthocomplementation. If\n ``False`` (the default), return ``True`` when the lattice\n has at least one orthocomplementation.\n\n EXAMPLES::\n\n sage: D5 = posets.DiamondPoset(5)\n sage: D5.is_orthocomplemented()\n False\n\n sage: D6 = posets.DiamondPoset(6)\n sage: D6.is_orthocomplemented() # needs sage.groups\n True\n sage: D6.is_orthocomplemented(unique=True) # needs sage.groups\n False\n\n sage: hexagon = LatticePoset({0: [1, 2], 1: [3], 2: [4], 3:[5], 4: [5]})\n sage: hexagon.is_orthocomplemented(unique=True) # needs sage.groups\n True\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_complemented`,\n :meth:`~sage.categories.finite_posets.FinitePosets.ParentMethods.is_self_dual`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_orthocomplemented() for i in range(4)]\n [True, True, True, False]\n '
it = self._hasse_diagram.orthocomplementations_iterator()
try:
next(it)
if (not unique):
return True
except StopIteration:
return False
try:
next(it)
return False
except StopIteration:
return True
raise AssertionError('bug in is_orthocomplemented()')
def is_atomic(self, certificate=False):
'\n Return ``True`` if the lattice is atomic, and ``False`` otherwise.\n\n A lattice is atomic if every element can be written as a join of atoms.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where `e` is a join-irreducible element\n that is not an atom. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3:[5], 4:[6], 5:[6]})\n sage: L.is_atomic()\n True\n\n sage: L = LatticePoset({0: [1, 2], 1: [3], 2: [3], 3:[4]})\n sage: L.is_atomic()\n False\n sage: L.is_atomic(certificate=True)\n (False, 4)\n\n TESTS::\n\n sage: LatticePoset({}).is_atomic()\n True\n\n .. NOTE::\n\n See [EnumComb1]_, Section 3.3 for a discussion of atomic lattices.\n\n .. SEEALSO::\n\n - Dual property: :meth:`~FiniteLatticePoset.is_coatomic`\n - Stronger properties: :meth:`is_sectionally_complemented`\n - Mutually exclusive properties: :meth:`is_vertically_decomposable`\n '
if (not certificate):
return ((self.cardinality() == 0) or (self._hasse_diagram.out_degree(0) == self._hasse_diagram.in_degree().count(1)))
if (self.cardinality() < 3):
return (True, None)
H = self._hasse_diagram
atoms = set(H.neighbor_out_iterator(0))
for v in H:
if ((H.in_degree(v) == 1) and (v not in atoms)):
return (False, self._vertex_to_element(v))
return (True, None)
def is_coatomic(self, certificate=False):
'\n Return ``True`` if the lattice is coatomic, and ``False`` otherwise.\n\n A lattice is coatomic if every element can be written as a meet\n of coatoms; i.e. if the dual of the lattice is atomic.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)``, where `e` is a meet-irreducible element\n that is not a coatom. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(3)\n sage: L.is_coatomic()\n True\n\n sage: L = LatticePoset({1: [2], 2: [3, 4], 3: [5], 4:[5]})\n sage: L.is_coatomic()\n False\n sage: L.is_coatomic(certificate=True)\n (False, 1)\n\n TESTS::\n\n sage: LatticePoset({}).is_coatomic()\n True\n\n .. SEEALSO::\n\n - Dual property: :meth:`~FiniteLatticePoset.is_atomic`\n - Stronger properties: :meth:`is_cosectionally_complemented`\n - Mutually exclusive properties: :meth:`is_vertically_decomposable`\n '
n = self.cardinality()
if (not certificate):
if (n == 0):
return True
return (self._hasse_diagram.in_degree((n - 1)) == self._hasse_diagram.out_degree().count(1))
if (self.cardinality() < 3):
return (True, None)
H = self._hasse_diagram
coatoms = set(H.neighbor_in_iterator((n - 1)))
for v in H:
if ((H.out_degree(v) == 1) and (v not in coatoms)):
return (False, self._vertex_to_element(v))
return (True, None)
def is_geometric(self):
"\n Return ``True`` if the lattice is geometric, and ``False`` otherwise.\n\n A lattice is geometric if it is both atomic and upper semimodular.\n\n EXAMPLES:\n\n Canonical example is the lattice of partitions of finite set\n ordered by refinement::\n\n sage: L = posets.SetPartitions(4) # needs sage.combinat\n sage: L.is_geometric() # needs sage.combinat\n True\n\n Smallest example of geometric lattice that is not modular::\n\n sage: L = LatticePoset(DiGraph('K]?@g@S?q?M?@?@?@?@?@?@??'))\n sage: L.is_geometric()\n True\n sage: L.is_modular()\n False\n\n Two non-examples::\n\n sage: L = LatticePoset({1:[2, 3, 4], 2:[5, 6], 3:[5], 4:[6], 5:[7], 6:[7]})\n sage: L.is_geometric() # Graded, but not upper semimodular\n False\n sage: L = posets.ChainPoset(3)\n sage: L.is_geometric() # Modular, but not atomic\n False\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_upper_semimodular`, :meth:`is_relatively_complemented`\n\n TESTS::\n\n sage: LatticePoset({}).is_geometric()\n True\n sage: LatticePoset({1:[]}).is_geometric()\n True\n "
return (self.is_atomic() and self.is_upper_semimodular())
def is_planar(self):
'\n Return ``True`` if the lattice is *upward* planar, and ``False``\n otherwise.\n\n A lattice is upward planar if its Hasse diagram has a planar drawing in\n the `\\mathbb{R}^2` plane, in such a way that `x` is strictly below `y`\n (on the vertical axis) whenever `x<y` in the lattice.\n\n Note that the scientific literature on posets often omits "upward" and\n shortens it to "planar lattice" (e.g. [GW2014]_), which can cause\n confusion with the notion of graph planarity in graph theory.\n\n .. NOTE::\n\n Not all lattices which are planar -- in the sense of graph planarity\n -- admit such a planar drawing (see example below).\n\n ALGORITHM:\n\n Using the result from [Platt1976]_, this method returns its result by\n testing that the Hasse diagram of the lattice is planar (in the sense of\n graph theory) when an edge is added between the top and bottom elements.\n\n EXAMPLES:\n\n The Boolean lattice of `2^3` elements is not upward planar, even if\n its covering relations graph is planar::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3.is_planar()\n False\n sage: G = B3.cover_relations_graph()\n sage: G.is_planar()\n True\n\n Ordinal product of planar lattices is obviously planar. Same does\n not apply to Cartesian products::\n\n sage: P = posets.PentagonPoset()\n sage: Pc = P.product(P)\n sage: Po = P.ordinal_product(P)\n sage: Pc.is_planar()\n False\n sage: Po.is_planar()\n True\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_dismantlable`\n\n TESTS::\n\n sage: posets.ChainPoset(0).is_planar()\n True\n sage: posets.ChainPoset(1).is_planar()\n True\n '
if (self.cardinality() < 8):
return True
g = self._hasse_diagram.copy(immutable=False)
g.add_edge(0, (self.cardinality() - 1))
return g.is_planar()
def is_modular(self, L=None, certificate=False):
'\n Return ``True`` if the lattice is modular and ``False`` otherwise.\n\n An element `b` of a lattice is *modular* if\n\n .. MATH::\n\n x \\vee (a \\wedge b) = (x \\vee a) \\wedge b\n\n for every element `x \\leq b` and `a`. A lattice is modular if every\n element is modular. There are other equivalent definitions, see\n :wikipedia:`Modular_lattice`.\n\n With the parameter ``L`` this can be used to check that\n some subset of elements are all modular.\n\n INPUT:\n\n - ``L`` -- (default: ``None``) a list of elements to check being\n modular, if ``L`` is ``None``, then this checks the entire lattice\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (x, a, b))``, where `a`, `b` and `x` are elements\n of the lattice such that `x < b` but\n `x \\vee (a \\wedge b) \\neq (x \\vee a) \\wedge b`. If also\n `L` is given then `b` in the certificate will be an element\n of `L`. If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = posets.DiamondPoset(5)\n sage: L.is_modular()\n True\n\n sage: L = posets.PentagonPoset()\n sage: L.is_modular()\n False\n\n sage: L = LatticePoset({1:[2,3],2:[4,5],3:[5,6],4:[7],5:[7],6:[7]})\n sage: L.is_modular(certificate=True)\n (False, (2, 6, 4))\n sage: [L.is_modular([x]) for x in L]\n [True, True, False, True, True, False, True]\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_upper_semimodular`,\n :meth:`is_lower_semimodular`, :meth:`is_supersolvable`\n - Stronger properties: :meth:`is_distributive`\n - Other: :meth:`is_modular_element`\n\n TESTS::\n\n sage: all(posets.ChainPoset(i).is_modular() for i in range(4))\n True\n\n sage: L = LatticePoset({1:[2,3],2:[4,5],3:[5,6],4:[7],5:[7],6:[7]})\n sage: L.is_modular(L=[1, 4, 2], certificate=True)\n (False, (2, 6, 4))\n sage: L.is_modular(L=[1, 6, 2], certificate=True)\n (False, (3, 4, 6))\n '
if ((not certificate) and (L is None)):
return (self.is_upper_semimodular() and self.is_lower_semimodular())
if (certificate and (L is None)):
tmp = self.is_lower_semimodular(certificate=True)
if (not tmp[0]):
(a, b) = tmp[1]
t = self.meet(a, b)
for x in self.upper_covers(t):
if self.is_less_than(x, b):
return (False, (x, a, b))
if self.is_less_than(x, a):
return (False, (x, b, a))
tmp = self.is_upper_semimodular(certificate=True)
if (not tmp[0]):
(x, a) = tmp[1]
t = self.join(x, a)
for b in self.lower_covers(t):
if self.is_greater_than(b, x):
return (False, (x, a, b))
if self.is_greater_than(b, a):
return (False, (a, x, b))
return (True, None)
for b in L:
for x in self.principal_lower_set(b):
for a in self:
if (self.join(x, self.meet(a, b)) != self.meet(self.join(x, a), b)):
if certificate:
return (False, (x, a, b))
return False
if certificate:
return (True, None)
return True
def is_modular_element(self, x):
'\n Return ``True`` if ``x`` is a modular element and ``False`` otherwise.\n\n INPUT:\n\n - ``x`` -- an element of the lattice\n\n An element `x` in a lattice `L` is *modular* if `x \\leq b` implies\n\n .. MATH::\n\n x \\vee (a \\wedge b) = (x \\vee a) \\wedge b\n\n for every `a, b \\in L`.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1:[2,3],2:[4,5],3:[5,6],4:[7],5:[7],6:[7]})\n sage: L.is_modular()\n False\n sage: [L.is_modular_element(x) for x in L]\n [True, True, False, True, True, False, True]\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_left_modular_element`\n - Other: :meth:`is_modular` to check modularity for the full\n lattice or some set of elements\n '
return self.is_modular([x])
def is_left_modular_element(self, x):
'\n Return ``True`` if ``x`` is a left modular element\n and ``False`` otherwise.\n\n INPUT:\n\n - ``x`` -- an element of the lattice\n\n An element `x` in a lattice `L` is *left modular* if\n\n .. MATH::\n\n (y \\vee x) \\wedge z = y \\vee (x \\wedge z)\n\n for every `y \\leq z \\in L`.\n\n It is enough to check this condition on all cover relations `y < z`.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: [i for i in P if P.is_left_modular_element(i)]\n [0, 2, 3, 4]\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_modular_element`\n '
return all(((self.meet(self.join(y, x), z) == self.join(y, self.meet(x, z))) for (y, z) in self.cover_relations_iterator()))
def is_upper_semimodular(self, certificate=False):
'\n Return ``True`` if the lattice is upper semimodular and\n ``False`` otherwise.\n\n A lattice is upper semimodular if any pair of elements with\n a common lower cover have also a common upper cover.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate if the lattice is not upper semimodular.\n\n OUTPUT:\n\n - If ``certificate=False`` return ``True`` or ``False``.\n If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b))``, where `a` and `b` covers their meet but\n are not covered by their join.\n\n See :wikipedia:`Semimodular_lattice`\n\n EXAMPLES::\n\n sage: L = posets.DiamondPoset(5)\n sage: L.is_upper_semimodular()\n True\n\n sage: L = posets.PentagonPoset()\n sage: L.is_upper_semimodular()\n False\n\n sage: L = LatticePoset(posets.IntegerPartitions(4)) # needs sage.combinat\n sage: L.is_upper_semimodular() # needs sage.combinat\n True\n\n sage: L = LatticePoset({1:[2, 3, 4], 2: [5], 3:[5, 6], 4:[6], 5:[7], 6:[7]})\n sage: L.is_upper_semimodular(certificate=True)\n (False, (4, 2))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_lower_semimodular`\n - Weaker properties: :meth:`~sage.combinat.posets.posets.FinitePoset.is_graded`\n - Stronger properties: :meth:`is_modular`,\n :meth:`is_join_distributive`, :meth:`is_geometric`\n\n TESTS::\n\n sage: all(posets.ChainPoset(i).is_upper_semimodular() for i in range(5))\n True\n '
nonmodular = self._hasse_diagram.find_nonsemimodular_pair(upper=True)
if (nonmodular is None):
return ((True, None) if certificate else True)
if certificate:
return (False, (self._vertex_to_element(nonmodular[0]), self._vertex_to_element(nonmodular[1])))
return False
def is_lower_semimodular(self, certificate=False):
"\n Return ``True`` if the lattice is lower semimodular and\n ``False`` otherwise.\n\n A lattice is lower semimodular if any pair of elements with\n a common upper cover have also a common lower cover.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate if the lattice is not lower semimodular.\n\n OUTPUT:\n\n - If ``certificate=False`` return ``True`` or ``False``.\n If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b))``, where `a` and `b` are covered by their\n join but do no cover their meet.\n\n See :wikipedia:`Semimodular_lattice`\n\n EXAMPLES::\n\n sage: L = posets.DiamondPoset(5)\n sage: L.is_lower_semimodular()\n True\n\n sage: L = posets.PentagonPoset()\n sage: L.is_lower_semimodular()\n False\n\n sage: L = posets.ChainPoset(6)\n sage: L.is_lower_semimodular()\n True\n\n sage: L = LatticePoset(DiGraph('IS?`?AAOE_@?C?_@??'))\n sage: L.is_lower_semimodular(certificate=True)\n (False, (4, 2))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_upper_semimodular`\n - Weaker properties: :meth:`~sage.combinat.posets.posets.FinitePoset.is_graded`\n - Stronger properties: :meth:`is_modular`,\n :meth:`is_meet_distributive`\n "
nonmodular = self._hasse_diagram.find_nonsemimodular_pair(upper=False)
if (nonmodular is None):
return ((True, None) if certificate else True)
if certificate:
return (False, (self._vertex_to_element(nonmodular[0]), self._vertex_to_element(nonmodular[1])))
return False
def is_supersolvable(self, certificate=False):
'\n Return ``True`` if the lattice is supersolvable, and\n ``False`` otherwise.\n\n A lattice `L` is *supersolvable* if there exists a maximal chain `C`\n such that every `x \\in C` is a modular element in `L`. Equivalent\n definition is that the sublattice generated by `C` and any other chain\n is distributive.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(False, None)`` or\n ``(True, C)``, where ``C`` is a maximal chain of modular elements.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = posets.DiamondPoset(5)\n sage: L.is_supersolvable()\n True\n\n sage: L = posets.PentagonPoset()\n sage: L.is_supersolvable()\n False\n\n sage: L = LatticePoset({1:[2,3],2:[4,5],3:[5,6],4:[7],5:[7],6:[7]})\n sage: L.is_supersolvable()\n True\n sage: L.is_supersolvable(certificate=True)\n (True, [1, 2, 5, 7])\n sage: L.is_modular()\n False\n\n sage: L = LatticePoset({0: [1, 2, 3, 4], 1: [5, 6, 7],\n ....: 2: [5, 8, 9], 3: [6, 8, 10], 4: [7, 9, 10],\n ....: 5: [11], 6: [11], 7: [11], 8: [11],\n ....: 9: [11], 10: [11]})\n sage: L.is_supersolvable()\n False\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`~sage.combinat.posets.posets.FinitePoset.is_graded`\n - Stronger properties: :meth:`is_modular`\n\n TESTS::\n\n sage: LatticePoset().is_supersolvable()\n True\n '
from sage.misc.cachefunc import cached_function
not_ok = ((False, None) if certificate else False)
if (not self.is_ranked()):
return not_ok
if (self.cardinality() == 0):
if certificate:
return (True, [])
return True
H = self._hasse_diagram
mt = H.meet_matrix()
jn = H.join_matrix()
height = self.height()
n = H.order()
cur = H.maximal_elements()[0]
cert = [cur]
next_ = [H.neighbor_in_iterator(cur)]
@cached_function
def is_modular_elt(a):
return all((((H._rank[a] + H._rank[b]) == (H._rank[mt[(a, b)]] + H._rank[jn[(a, b)]])) for b in range(n)))
if (not is_modular_elt(cur)):
return not_ok
while (len(next_) < height):
try:
cur = next(next_[(- 1)])
except StopIteration:
next_.pop()
cert.pop()
if (not next_):
return not_ok
continue
if is_modular_elt(cur):
next_.append(H.neighbor_in_iterator(cur))
cert.append(cur)
if certificate:
return (True, [self._vertex_to_element(e) for e in reversed(cert)])
return True
def vertical_composition(self, other, labels='pairs'):
'\n Return the vertical composition of the lattice with ``other``.\n\n Let `L` and `K` be lattices and `b_K` the bottom element\n of `K`. The vertical composition of `L` and `K` is the ordinal\n sum of `L` and `K \\setminus \\{b_K\\}`. Informally said this is\n lattices "glued" together with a common element.\n\n Mathematically, it is only defined when `L` and `K` have no\n common element; here we force that by giving them different\n names in the resulting poset.\n\n INPUT:\n\n - ``other`` -- a lattice\n\n - ``labels`` -- a string (default ``\'pairs\'``); can be one of\n the following:\n\n * ``\'pairs\'`` - each element ``v`` in this poset will be\n named ``(0, v)`` and each element ``u`` in ``other`` will\n be named ``(1, u)`` in the result\n * ``\'integers\'`` - the elements of the result will be\n relabeled with consecutive integers\n\n EXAMPLES::\n\n sage: L = LatticePoset({\'a\': [\'b\', \'c\'], \'b\': [\'d\'], \'c\': [\'d\']})\n sage: K = LatticePoset({\'e\': [\'f\', \'g\'], \'f\': [\'h\'], \'g\': [\'h\']})\n sage: M = L.vertical_composition(K)\n sage: M.list()\n [(0, \'a\'), (0, \'b\'), (0, \'c\'), (0, \'d\'), (1, \'f\'), (1, \'g\'), (1, \'h\')]\n sage: M.upper_covers((0, \'d\'))\n [(1, \'f\'), (1, \'g\')]\n\n sage: C2 = posets.ChainPoset(2)\n sage: M3 = posets.DiamondPoset(5)\n sage: L = C2.vertical_composition(M3, labels=\'integers\')\n sage: L.cover_relations()\n [[0, 1], [1, 2], [1, 3], [1, 4], [2, 5], [3, 5], [4, 5]]\n\n .. SEEALSO::\n\n :meth:`vertical_decomposition`,\n :meth:`sage.combinat.posets.posets.FinitePoset.ordinal_sum`\n\n TESTS::\n\n sage: C0 = LatticePoset()\n sage: C1 = LatticePoset({\'a\': []})\n sage: C2 = LatticePoset({\'b\': [\'c\']})\n sage: C2.vertical_composition(C2)\n Finite lattice containing 3 elements\n sage: C0.vertical_composition(C0)\n Finite lattice containing 0 elements\n sage: C0.vertical_composition(C1).list()\n [(1, \'a\')]\n sage: C1.vertical_composition(C0).list()\n [(0, \'a\')]\n sage: C1.vertical_composition(C1).list()\n [(0, \'a\')]\n sage: C1.vertical_composition(C2).list()\n [(0, \'a\'), (1, \'c\')]\n sage: C2.vertical_composition(C1).list()\n [(0, \'b\'), (0, \'c\')]\n '
from copy import copy
if (labels not in ['integers', 'pairs']):
raise ValueError("labels must be either 'pairs' or 'integers'")
if (not isinstance(self, FiniteLatticePoset)):
raise ValueError('the input is not a finite lattice')
if (self._is_facade != other._is_facade):
raise ValueError('mixing facade and non-facade lattices is not defined')
if (labels == 'integers'):
g_self = copy(self._hasse_diagram)
g_other = other._hasse_diagram.copy(immutable=False)
n = max(g_self.order(), 1)
g_other.relabel((lambda v: ((v + n) - 1)))
g_result = g_self.union(g_other)
return FiniteLatticePoset(g_result, elements=range(g_result.order()), facade=self._is_facade, category=FiniteLatticePosets())
if (self.cardinality() == 0):
return other.relabel((lambda e: (1, e)))
S = other.subposet([e for e in other if (e != other.bottom())])
return LatticePoset(self.ordinal_sum(S), facade=self._is_facade)
def vertical_decomposition(self, elements_only=False):
'\n Return sublattices from the vertical decomposition of the lattice.\n\n Let `d_1, \\ldots, d_n` be elements (excluding the top and bottom\n elements) comparable to every element of the lattice. Let `b`\n be the bottom element and `t` be the top element. This function\n returns either a list `d_1, \\ldots, d_n`, or the list of\n intervals `[b, d_1], [d_1, d_2], \\ldots, [d_{n-1}, d_n], [d_n,\n t]` as lattices.\n\n Informally said, this returns the lattice split into parts at\n every single-element "cutting point".\n\n INPUT:\n\n - ``elements_only`` - if ``True``, return the list of decomposing\n elements as defined above; if ``False`` (the default),\n return the list of sublattices so that the lattice is a\n vertical composition of them.\n\n EXAMPLES:\n\n Number 6 is divided by 1, 2, and 3, and it divides 12, 18 and 36::\n\n sage: L = LatticePoset( ([1, 2, 3, 6, 12, 18, 36],\n ....: attrcall("divides")) )\n sage: parts = L.vertical_decomposition()\n sage: [lat.list() for lat in parts]\n [[1, 2, 3, 6], [6, 12, 18, 36]]\n sage: L.vertical_decomposition(elements_only=True)\n [6]\n\n .. SEEALSO::\n\n :meth:`vertical_composition`,\n :meth:`is_vertically_decomposable`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).vertical_decomposition(elements_only=True)\n ....: for i in range(5)]\n [[], [], [], [1], [1, 2]]\n '
if (self.cardinality() <= 2):
if (not elements_only):
return [self]
else:
return []
if elements_only:
return [self[e] for e in self._hasse_diagram.vertical_decomposition(return_list=True)]
elms = (([0] + self._hasse_diagram.vertical_decomposition(return_list=True)) + [(self.cardinality() - 1)])
n = len(elms)
result = []
for i in range((n - 1)):
result.append(LatticePoset(self.subposet([self[e] for e in range(elms[i], (elms[(i + 1)] + 1))])))
return result
def is_vertically_decomposable(self, certificate=False):
'\n Return ``True`` if the lattice is vertically decomposable, and\n ``False`` otherwise.\n\n A lattice is vertically decomposable if it has an element that\n is comparable to all elements and is neither the bottom nor\n the top element.\n\n Informally said, a lattice is vertically decomposable if it\n can be seen as two lattices "glued" by unifying the top\n element of first lattice to the bottom element of second one.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(False, None)`` or\n ``(True, e)``, where `e` is an element that is comparable to all\n other elements and is neither the bottom nor the top element.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: posets.TamariLattice(4).is_vertically_decomposable()\n False\n sage: L = LatticePoset( ([1, 2, 3, 6, 12, 18, 36],\n ....: attrcall("divides")) )\n sage: L.is_vertically_decomposable()\n True\n sage: L.is_vertically_decomposable(certificate=True)\n (True, 6)\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_subdirectly_reducible`\n - Mutually exclusive properties: :meth:`is_atomic`, :meth:`is_coatomic`,\n :meth:`is_regular`\n - Other: :meth:`vertical_decomposition`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_vertically_decomposable() for i in\n ....: range(5)]\n [False, False, False, True, True]\n '
e = self._hasse_diagram.vertical_decomposition()
if (e is None):
if certificate:
return (False, None)
return False
if certificate:
return (True, self._vertex_to_element(e))
return True
def sublattice(self, elms):
'\n Return the smallest sublattice containing elements on the given list.\n\n INPUT:\n\n - ``elms`` -- a list of elements of the lattice.\n\n EXAMPLES::\n\n sage: L = LatticePoset(([], [[1,2],[1,17],[1,8],[2,3],[2,22],[2,5],[2,7],[17,22],[17,13],[8,7],[8,13],[3,16],[3,9],[22,16],[22,18],[22,10],[5,18],[5,14],[7,9],[7,14],[7,10],[13,10],[16,6],[16,19],[9,19],[18,6],[18,33],[14,33],[10,19],[10,33],[6,4],[19,4],[33,4]]))\n sage: L.sublattice([14, 13, 22]).list()\n [1, 2, 8, 7, 14, 17, 13, 22, 10, 33]\n\n sage: L = posets.BooleanLattice(3)\n sage: L.sublattice([3,5,6,7])\n Finite lattice containing 8 elements\n '
gens_remaining = set(elms)
current_set = set()
while gens_remaining:
g = gens_remaining.pop()
if (g in current_set):
continue
for x in current_set:
gens_remaining.add(self.join(x, g))
gens_remaining.add(self.meet(x, g))
current_set.add(g)
return LatticePoset(self.subposet(current_set))
def is_sublattice(self, other):
"\n Return ``True`` if the lattice is a sublattice of ``other``,\n and ``False`` otherwise.\n\n Lattice `K` is a sublattice of `L` if `K` is an (induced) subposet\n of `L` and closed under meet and join of `L`.\n\n .. NOTE::\n\n This method does not check whether the lattice is a\n *isomorphic* (i.e., up to relabeling) sublattice of ``other``,\n but only if ``other`` directly contains the lattice as an\n sublattice.\n\n EXAMPLES:\n\n A pentagon sublattice in a non-modular lattice::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [5, 6], 4: [7], 5: [7], 6: [7]})\n sage: N5 = LatticePoset({1: [2, 6], 2: [4], 4: [7], 6: [7]})\n sage: N5.is_sublattice(L)\n True\n\n This pentagon is a subposet but not closed under join, hence not a sublattice::\n\n sage: N5_ = LatticePoset({1: [2, 3], 2: [4], 3: [7], 4: [7]})\n sage: N5_.is_induced_subposet(L)\n True\n sage: N5_.is_sublattice(L)\n False\n\n .. SEEALSO::\n\n :meth:`isomorphic_sublattices_iterator`\n\n TESTS::\n\n sage: E = LatticePoset({})\n sage: P = posets.PentagonPoset()\n sage: E.is_sublattice(P)\n True\n\n sage: P1 = LatticePoset({'a':['b']})\n sage: P2 = P1.dual()\n sage: P1.is_sublattice(P2)\n False\n\n sage: P = MeetSemilattice({0: [1]})\n sage: E.is_sublattice(P)\n True\n sage: P = JoinSemilattice({0: [1]})\n sage: E.is_sublattice(P)\n True\n sage: P = Poset({0: [1]})\n sage: E.is_sublattice(P)\n True\n "
try:
o_meet = other.meet
o_join = other.join
except AttributeError:
raise TypeError('other is not a lattice')
if (not self.is_induced_subposet(other)):
return False
n = self.cardinality()
for i in range(n):
for j in range(i):
if ((o_meet(self[i], self[j]) not in self) or (o_join(self[i], self[j]) not in self)):
return False
return True
def sublattices(self):
'\n Return all sublattices of the lattice.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2:[5], 3:[5, 6], 4:[6],\n ....: 5:[7], 6:[7]})\n sage: sublats = L.sublattices(); len(sublats)\n 54\n sage: sublats[3]\n Finite lattice containing 4 elements\n sage: sublats[3].list()\n [1, 2, 3, 5]\n\n TESTS:\n\n A subposet that is a lattice but not a sublattice::\n\n sage: L = LatticePoset({1: [2, 3], 2:[4], 3:[4], 4:[5]})\n sage: sl = L.sublattices()\n sage: LatticePoset({1: [2, 3], 2:[5], 3:[5]}) in sl\n False\n\n `n`-element chain has `2^n` sublattices (also tests empty lattice)::\n\n sage: [len(posets.ChainPoset(n).sublattices()) for n in range(4)]\n [1, 2, 4, 8]\n '
return [LatticePoset(self.subposet(map(self._vertex_to_element, elms))) for elms in self._hasse_diagram.sublattices_iterator(set(), 0)]
def sublattices_lattice(self, labels='lattice'):
"\n Return the lattice of sublattices.\n\n Every element of the returned lattice is a sublattice and\n they are ordered by containment; that is, atoms are one-element\n lattices, coatoms are maximal sublattices of the original\n lattice and so on.\n\n INPUT:\n\n - ``labels`` -- string; can be one of the following:\n\n * ``'lattice'`` (default) elements of the lattice will be\n lattices that correspond to sublattices of the original lattice\n\n * ``'tuple'`` - elements are tuples of elements of the sublattices\n of the original lattice\n\n * ``'integer'`` - elements are plain integers\n\n EXAMPLES::\n\n sage: D4 = posets.DiamondPoset(4)\n sage: sll = D4.sublattices_lattice(labels='tuple')\n sage: sll.coatoms() # = maximal sublattices of the original lattice\n [(0, 1, 3), (0, 2, 3)]\n\n sage: L = posets.DivisorLattice(12)\n sage: sll = L.sublattices_lattice()\n sage: L.is_dismantlable() == (len(sll.atoms()) == sll.rank())\n True\n\n TESTS::\n\n sage: E = posets.ChainPoset(0)\n sage: E.sublattices_lattice()\n Finite lattice containing 1 elements\n\n sage: C3 = posets.ChainPoset(3)\n sage: sll = C3.sublattices_lattice(labels='integer')\n sage: sll.is_isomorphic(posets.BooleanLattice(3))\n True\n "
if (labels not in ['lattice', 'tuple', 'integer']):
raise ValueError("labels must be one of 'lattice', 'tuple' or 'integer'")
sublats = [frozenset(x) for x in self._hasse_diagram.sublattices_iterator(set(), 0)]
L = LatticePoset([sublats, (lambda a, b: ((a != b) and a.issubset(b)))])
if (labels == 'integer'):
return L.canonical_label()
L = L.relabel((lambda x: tuple((self._vertex_to_element(y) for y in x))))
if (labels == 'lattice'):
return L.relabel(self.sublattice)
return L
def isomorphic_sublattices_iterator(self, other):
'\n Return an iterator over the sublattices of the lattice isomorphic to ``other``.\n\n INPUT:\n\n - other -- a finite lattice\n\n EXAMPLES:\n\n A non-modular lattice contains a pentagon sublattice::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [5, 6], 4: [7], 5: [7], 6: [7]})\n sage: L.is_modular()\n False\n sage: N5 = posets.PentagonPoset()\n sage: N5_in_L = next(L.isomorphic_sublattices_iterator(N5)); N5_in_L\n Finite lattice containing 5 elements\n sage: N5_in_L.list()\n [1, 3, 6, 4, 7]\n\n A divisor lattice is modular, hence does not contain the\n pentagon as sublattice, even if it has the pentagon\n subposet::\n\n sage: D12 = posets.DivisorLattice(12)\n sage: D12.has_isomorphic_subposet(N5)\n True\n sage: list(D12.isomorphic_sublattices_iterator(N5))\n []\n\n .. SEEALSO::\n\n :meth:`sage.combinat.posets.posets.FinitePoset.isomorphic_subposets_iterator`\n\n .. WARNING::\n\n This function will return same sublattice as many times as\n there are automorphism on it. This is due to\n :meth:`~sage.graphs.generic_graph.GenericGraph.subgraph_search_iterator`\n returning labelled subgraphs.\n\n TESTS::\n\n sage: E = LatticePoset()\n sage: P = LatticePoset({1: []})\n sage: list(N5.isomorphic_sublattices_iterator(E))\n [Finite lattice containing 0 elements]\n sage: len(list(N5.isomorphic_sublattices_iterator(P)))\n 5\n '
from itertools import combinations
if (not isinstance(other, FiniteLatticePoset)):
raise TypeError('the input is not a finite lattice')
H = self._hasse_diagram
mt = H.meet_matrix()
jn = H.join_matrix()
self_closure = H.transitive_closure()
other_closure = other._hasse_diagram.transitive_closure()
for g in self_closure.subgraph_search_iterator(other_closure, induced=True, return_graphs=False):
if all((((mt[(a, b)] in g) and (jn[(a, b)] in g)) for (a, b) in combinations(g, 2))):
(yield self.sublattice([self._vertex_to_element(v) for v in g]))
def maximal_sublattices(self):
'\n Return maximal (proper) sublattices of the lattice.\n\n EXAMPLES::\n\n sage: L = LatticePoset(( [], [[1,2],[1,17],[1,8],[2,3],[2,22],\n ....: [2,5],[2,7],[17,22],[17,13],[8,7],\n ....: [8,13],[3,16],[3,9],[22,16],[22,18],\n ....: [22,10],[5,18],[5,14],[7,9],[7,14],\n ....: [7,10],[13,10],[16,6],[16,19],[9,19],\n ....: [18,6],[18,33],[14,33],[10,19],\n ....: [10,33],[6,4],[19,4],[33,4]] ))\n sage: maxs = L.maximal_sublattices()\n sage: len(maxs)\n 7\n sage: sorted(maxs[0].list())\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 16, 18, 19, 22, 33]\n '
n = self.cardinality()
if (n < 2):
return []
if (n == 2):
return [self.sublattice([self.bottom()]), self.sublattice([self.top()])]
return [self.sublattice([self[x] for x in d]) for d in self._hasse_diagram.maximal_sublattices()]
def frattini_sublattice(self):
'\n Return the Frattini sublattice of the lattice.\n\n The Frattini sublattice `\\Phi(L)` is the intersection of all\n proper maximal sublattices of `L`. It is also the set of\n "non-generators" - if the sublattice generated by set `S` of\n elements is whole lattice, then also `S \\setminus \\Phi(L)`\n generates whole lattice.\n\n EXAMPLES::\n\n sage: L = LatticePoset(( [], [[1,2],[1,17],[1,8],[2,3],[2,22],\n ....: [2,5],[2,7],[17,22],[17,13],[8,7],\n ....: [8,13],[3,16],[3,9],[22,16],[22,18],\n ....: [22,10],[5,18],[5,14],[7,9],[7,14],\n ....: [7,10],[13,10],[16,6],[16,19],[9,19],\n ....: [18,6],[18,33],[14,33],[10,19],\n ....: [10,33],[6,4],[19,4],[33,4]] ))\n sage: sorted(L.frattini_sublattice().list())\n [1, 2, 4, 10, 19, 22, 33]\n '
return LatticePoset(self.subposet([self[x] for x in self._hasse_diagram.frattini_sublattice()]))
def moebius_algebra(self, R):
'\n Return the Möbius algebra of ``self`` over ``R``.\n\n OUTPUT:\n\n An instance of :class:`sage.combinat.posets.moebius_algebra.MoebiusAlgebra`.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: L.moebius_algebra(QQ)\n Moebius algebra of Finite lattice containing 16 elements over Rational Field\n '
from sage.combinat.posets.moebius_algebra import MoebiusAlgebra
return MoebiusAlgebra(R, self)
def quantum_moebius_algebra(self, q=None):
'\n Return the quantum Möbius algebra of ``self`` with parameter ``q``.\n\n INPUT:\n\n - ``q`` -- (optional) the deformation parameter `q`\n\n OUTPUT:\n\n An instance of :class:`sage.combinat.posets.moebius_algebra.QuantumMoebiusAlgebra`.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: L.quantum_moebius_algebra()\n Quantum Moebius algebra of Finite lattice containing 16 elements\n with q=q over Univariate Laurent Polynomial Ring in q over Integer Ring\n '
from sage.combinat.posets.moebius_algebra import QuantumMoebiusAlgebra
return QuantumMoebiusAlgebra(self, q)
def day_doubling(self, S):
"\n Return the lattice with Alan Day's doubling construction of subset `S`.\n\n The subset `S` is assumed to be convex (i.e. if\n `a, c \\in S` and `a < b < c` in the lattice, then `b \\in S`)\n and connected (i.e. if `a, b \\in S` then there is a chain\n `a=e_1, e_2, \\ldots, e_n=b` such that `e_i` either covers or\n is covered by `e_{i+1}`).\n\n .. image:: ../../../media/day-doubling.png\n\n Alan Day's doubling construction is a specific extension of\n the lattice. Here we formulate it in a format more suitable\n for computation.\n\n Let `L` be a lattice and `S` a convex subset of it. The resulting\n lattice `L[S]` has elements `(e, 0)` for each `e \\in L` and\n `(e, 1)` for each `e \\in S`. If `x \\le y` in `L`, then in the\n new lattice we have\n\n * `(x, 0), (x, 1) \\le (y, 0), (y, 1)`\n * `(x, 0) \\le (x, 1)`\n\n INPUT:\n\n - ``S`` -- a subset of the lattice\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: ['a', 'b', 2], 'a': ['c'], 'b': ['c', 'd'],\n ....: 2: [3], 'c': [4], 'd': [4], 3: [4]})\n sage: L2 = L.day_doubling(['a', 'b', 'c', 'd']); L2\n Finite lattice containing 12 elements\n sage: set(L2.upper_covers((1, 0))) == set([(2, 0), ('a', 0), ('b', 0)])\n True\n sage: set(L2.upper_covers(('b', 0))) == set([('d', 0), ('b', 1), ('c', 0)])\n True\n\n .. SEEALSO::\n\n :meth:`is_constructible_by_doublings`\n\n TESTS::\n\n sage: L2._hasse_diagram.is_isomorphic(DiGraph('KSCH??_BO?g?_?@?G?@?A?@??'))\n True\n\n sage: L = LatticePoset({'a': ['b']})\n sage: set(L.day_doubling([]).list()) == set([('a', 0), ('b', 0)])\n True\n sage: set(L.day_doubling(['a', 'b']).list()) == set([('a', 0), ('a', 1), ('b', 0), ('b', 1)])\n True\n "
S = sorted(set(S))
S_ = [self._element_to_vertex(e) for e in S]
if (not self._hasse_diagram.is_convex_subset(S_)):
raise ValueError('subset S is not convex')
if (not self._hasse_diagram.subgraph(S_).is_connected()):
raise ValueError('subset S is not connected')
g = self.hasse_diagram()
g.relabel((lambda e: (e, 0)))
for e in S:
g.add_edge((e, 0), (e, 1))
for e_up in self.upper_covers(e):
if (e_up in S):
g.add_edge((e, 1), (e_up, 1))
else:
g.delete_edge((e, 0), (e_up, 0))
g.add_edge((e, 1), (e_up, 0))
return LatticePoset(g)
def adjunct(self, other, a, b):
"\n Return the adjunct of the lattice by ``other`` on the pair `(a, b)`.\n\n It is assumed that `a < b` but `b` does not cover `a`.\n\n The adjunct of a lattice `K` to `L` with respect to pair\n `(a, b)` of `L` is defined such that `x < y` if\n\n - `x, y \\in K` and `x < y` in `K`,\n - `x, y \\in L` and `x < y` in `L`,\n - `x \\in L`, `y \\in K` and `x \\le a` in `L`, or\n - `x \\in K`, `y \\in L` and `b \\le y` in `L`.\n\n Informally this can be seen as attaching the lattice `K` to `L`\n as a new block between `a` and `b`. Dismantlable lattices are exactly\n those that can be created from chains with this function.\n\n Mathematically, it is only defined when `L` and `K` have no\n common element; here we force that by giving them different\n names in the resulting lattice.\n\n EXAMPLES::\n\n sage: Pnum = posets.PentagonPoset()\n sage: Palp = Pnum.relabel(lambda x: chr(ord('a')+x))\n sage: PP = Pnum.adjunct(Palp, 0, 3)\n sage: PP.atoms()\n [(0, 1), (0, 2), (1, 'a')]\n sage: PP.coatoms()\n [(0, 3), (0, 1)]\n\n TESTS::\n\n sage: P = posets.PentagonPoset()\n sage: E = LatticePoset()\n sage: PE = P.adjunct(E, 0, 3); PE.is_isomorphic(P)\n True\n sage: PE.bottom()\n (0, 0)\n sage: C4 = posets.ChainPoset(4)\n sage: C1 = posets.ChainPoset(1)\n sage: C4.adjunct(C1, 0, 3).is_isomorphic(P)\n True\n "
if (not isinstance(other, FiniteLatticePoset)):
raise ValueError('other is not a finite lattice')
if (not self.is_greater_than(b, a)):
raise ValueError(('element %s is not greater than %s in the lattice' % (b, a)))
if self.covers(a, b):
raise ValueError(('element %s covers element %s in the lattice' % (b, a)))
if (other.cardinality() == 0):
return self.relabel((lambda e: (0, e)))
g_self = self.hasse_diagram()
g_other = other.hasse_diagram()
g = g_self.disjoint_union(g_other, labels='pairs')
g.add_edge((0, a), (1, other.bottom()))
g.add_edge((1, other.top()), (0, b))
return LatticePoset(g)
def center(self):
'\n Return the center of the lattice.\n\n An element of a lattice is *central* if it is neutral and has a\n complement. The subposet induced by central elements is a *center* of\n the lattice. Actually it is a Boolean lattice.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [6, 7], 3: [8, 9, 7],\n ....: 4: [5, 6], 5: [8, 10], 6: [10], 7: [13, 11],\n ....: 8: [13, 12], 9: [11, 12], 10: [13],\n ....: 11: [14], 12: [14], 13: [14]})\n sage: C = L.center(); C\n Finite lattice containing 4 elements\n sage: C.cover_relations()\n [[1, 2], [1, 12], [2, 14], [12, 14]]\n\n sage: L = posets.DivisorLattice(60)\n sage: sorted(L.center().list())\n [1, 3, 4, 5, 12, 15, 20, 60]\n\n .. SEEALSO::\n\n :meth:`neutral_elements`, :meth:`complements`\n\n TESTS::\n\n sage: LatticePoset().center()\n Finite lattice containing 0 elements\n\n sage: posets.ChainPoset(1).center()\n Finite lattice containing 1 elements\n\n sage: L = posets.BooleanLattice(3)\n sage: L.center() == L\n True\n '
neutrals = self.neutral_elements()
comps = self.complements()
return self.sublattice([e for e in neutrals if (e in comps)])
def is_dismantlable(self, certificate=False):
'\n Return ``True`` if the lattice is dismantlable, and ``False``\n otherwise.\n\n An `n`-element lattice `L_n` is dismantlable if there is a sublattice\n chain `L_{n-1} \\supset L_{n-2}, \\supset \\cdots, \\supset L_0` so that\n every `L_i` is a sublattice of `L_{i+1}` with one element less, and\n `L_0` is the empty lattice. In other words, a dismantlable lattice\n can be reduced to empty lattice removing doubly irreducible\n element one by one.\n\n INPUT:\n\n - ``certificate`` (boolean) -- Whether to return a certificate.\n\n * If ``certificate = False`` (default), returns ``True`` or\n ``False`` accordingly.\n\n * If ``certificate = True``, returns:\n\n * ``(True, elms)`` when the lattice is dismantlable, where\n ``elms`` is elements listed in a possible removing order.\n\n * ``(False, crown)`` when the lattice is not dismantlable,\n where ``crown`` is a subposet of `2k` elements\n `a_1, \\ldots, a_k, b_1, \\ldots, b_k` with covering\n relations `a_i \\lessdot b_i` and `a_i \\lessdot b_{i+1}`\n for `i \\in [1, \\ldots, k-1]`, and `a_k \\lessdot b_1`.\n\n EXAMPLES::\n\n sage: DL12 = LatticePoset((divisors(12), attrcall("divides")))\n sage: DL12.is_dismantlable()\n True\n sage: DL12.is_dismantlable(certificate=True)\n (True, [4, 2, 1, 3, 6, 12])\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3.is_dismantlable()\n False\n sage: B3.is_dismantlable(certificate=True)\n (False, Finite poset containing 6 elements)\n\n Every planar lattice is dismantlable. Converse is not true::\n\n sage: L = LatticePoset( ([], [[0, 1], [0, 2], [0, 3], [0, 4],\n ....: [1, 7], [2, 6], [3, 5], [4, 5],\n ....: [4, 6], [4, 7], [5, 8], [6, 8],\n ....: [7, 8]]) )\n sage: L.is_dismantlable()\n True\n sage: L.is_planar()\n False\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_planar`\n - Weaker properties: :meth:`is_sublattice_dismantlable`\n\n TESTS::\n\n sage: posets.ChainPoset(0).is_dismantlable()\n True\n sage: posets.ChainPoset(1).is_dismantlable()\n True\n\n sage: L = LatticePoset(DiGraph(\'L@_?W?E?@CCO?A?@??_?O?Jw????C?\'))\n sage: L.is_dismantlable()\n False\n sage: c = L.is_dismantlable(certificate=True)[1]\n sage: (3 in c, 12 in c, 9 in c)\n (True, False, True)\n '
from sage.graphs.digraph import DiGraph
from copy import copy
H = copy(self._hasse_diagram)
cert = []
limit = (0 if certificate else 7)
while (H.order() > limit):
for e in H:
i = H.in_degree(e)
o = H.out_degree(e)
if ((i < 2) and (o < 2)):
if certificate:
cert.append(e)
if ((i == 1) and (o == 1)):
lower = next(H.neighbor_in_iterator(e))
upper = next(H.neighbor_out_iterator(e))
H.delete_vertex(e)
if (upper not in H.depth_first_search(lower)):
H.add_edge(lower, upper)
else:
H.delete_vertex(e)
break
else:
if (not certificate):
return False
k = 3
while True:
crown = DiGraph({i: [(k + i), (k + ((i + 1) % k))] for i in range(k)})
sg = H.transitive_closure().subgraph_search(crown, True)
if sg:
elms = [self[e] for e in sg]
return (False, self.subposet(elms))
k += 1
if (not certificate):
return True
return (True, [self[e] for e in cert])
def is_interval_dismantlable(self, certificate=False):
'\n Return ``True`` if the lattice is interval dismantlable, and\n ``False`` otherwise.\n\n An interval dismantling is a subdivision of a lattice to a principal\n upper set and a principal lower set. A lattice is *interval\n dismantlable* if it can be decomposed into 1-element lattices by\n consecutive interval distmantlings.\n\n A lattice is *minimally interval non-dismantlable* if it is not\n interval dismantlable, but all of its sublattices are interval\n dismantlable.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - if ``certificate=False``, return only ``True`` or ``False``\n - if ``certificate=True``, return either\n\n * ``(True, list)`` where ``list`` is a nested list showing the\n decomposition; for example ``list[1][0]`` is a lower part of\n upper part of the lattice when decomposed twice.\n * ``(False, M)`` where `M` is a minimally interval non-dismantlable\n sublattice of the lattice.\n\n EXAMPLES::\n\n sage: L1 = LatticePoset({1: [2, 3], 3: [4, 5], 2: [6], 4: [6], 5: [6]})\n sage: L1.is_interval_dismantlable()\n True\n\n sage: L2 = LatticePoset({1: [2, 3, 4, 5], 2: [6], 3: [6], 4: [6],\n ....: 5: [6, 7], 6: [8], 7: [9, 10], 8:[10], 9:[10]})\n sage: L2.is_interval_dismantlable()\n False\n\n To get certificates::\n\n sage: L1.is_interval_dismantlable(certificate=True)\n (True, [[[1], [2]], [[[3], [5]], [[4], [6]]]])\n sage: L2.is_interval_dismantlable(certificate=True)\n (False, Finite lattice containing 5 elements)\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_join_semidistributive`,\n :meth:`is_meet_semidistributive`\n - Weaker properties: :meth:`is_sublattice_dismantlable`\n\n TESTS::\n\n sage: LatticePoset().is_interval_dismantlable()\n True\n sage: LatticePoset().is_interval_dismantlable(certificate=True)\n (True, [])\n '
def minimal_non_int_dismant(L):
'\n Return a minimally interval non-dismantlable sublattice.\n\n Assumes that L is interval non-dismantlable.\n '
while True:
H = L._hasse_diagram
for sl in H.sublattices_iterator(set(), 0):
if ((len(sl) < 5) or (len(sl) == H.order())):
continue
L_ = L.sublattice([L._vertex_to_element(v) for v in sl])
if (not L_.is_interval_dismantlable()):
L = L_
break
else:
return L
def recursive_is_interval_dismantlable(self):
if (self.cardinality() == 1):
return (True, [self[0]])
mp = self.meet_primes()
if (not mp):
return (False, self)
e = mp[0]
e_lower = self.principal_lower_set(e)
L_down = LatticePoset(self.subposet(e_lower))
result_down = recursive_is_interval_dismantlable(L_down)
if (not result_down[0]):
return result_down
L_up = LatticePoset(self.subposet([x for x in self if (x not in e_lower)]))
result_up = recursive_is_interval_dismantlable(L_up)
if (not result_up[0]):
return result_up
return (True, [result_down[1], result_up[1]])
if (self.cardinality() == 0):
return ((True, []) if certificate else True)
result = recursive_is_interval_dismantlable(self)
if result[0]:
return (result if certificate else True)
return ((False, minimal_non_int_dismant(self)) if certificate else False)
def is_sublattice_dismantlable(self):
'\n Return ``True`` if the lattice is sublattice dismantlable, and\n ``False`` otherwise.\n\n A sublattice dismantling is a subdivision of a lattice into two\n non-empty sublattices. A lattice is *sublattice dismantlable*\n if it can be decomposed into 1-element lattices by consecutive\n sublattice dismantlings.\n\n EXAMPLES:\n\n The smallest non-example is this (and the dual)::\n\n sage: P = Poset({1: [11, 12, 13], 2: [11, 14, 15],\n ....: 3: [12, 14, 16], 4: [13, 15, 16]})\n sage: L = LatticePoset(P.with_bounds())\n sage: L.is_sublattice_dismantlable()\n False\n\n Here we adjoin a (double-irreducible-)dismantlable lattice\n as a part to an interval-dismantlable lattice::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: N5 = posets.PentagonPoset()\n sage: L = B3.adjunct(N5, 1, 7)\n sage: L.is_dismantlable(), L.is_interval_dismantlable()\n (False, False)\n sage: L.is_sublattice_dismantlable()\n True\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_dismantlable`, :meth:`is_interval_dismantlable`\n\n TESTS::\n\n sage: LatticePoset().is_sublattice_dismantlable()\n True\n\n .. TODO::\n\n Add a certificate-option.\n '
from sage.combinat.subset import Subsets
if (self.cardinality() <= 11):
return True
for low in self:
if (len(self.lower_covers(low)) <= 1):
for up in self.principal_upper_set(low):
if (len(self.upper_covers(up)) <= 1):
if ((low == self.bottom()) and (up == self.top())):
continue
S1 = self.interval(low, up)
S2 = [e for e in self if (e not in S1)]
if all((((self.meet(a, b) in S2) and (self.join(a, b) in S2)) for (a, b) in Subsets(S2, 2))):
sub1 = self.sublattice(S1)
sub2 = self.sublattice(S2)
return (sub1.is_sublattice_dismantlable() and sub2.is_sublattice_dismantlable())
return False
def is_subdirectly_reducible(self, certificate=False):
'\n Return ``True`` if the lattice is subdirectly reducible.\n\n A lattice `M` is a *subdirect product* of `K` and `L` if it\n is a sublattice of `K \\times L`. Lattice `M` is *subdirectly\n reducible* if there exists such lattices `K` and `L` so that\n `M` is not a sublattice of either.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - if ``certificate=False``, return only ``True`` or ``False``\n - if ``certificate=True``, return either\n\n * ``(True, (K, L))`` such that the lattice is isomorphic to\n a sublattice of `K \\times L`.\n * ``(False, (a, b))``, where `a` and `b` are elements that are\n in the same congruence class for every nontrivial congruence\n of the lattice. Special case: If the lattice has zero or one element,\n return ``(False, None)``.\n\n EXAMPLES::\n\n sage: N5 = posets.PentagonPoset()\n sage: N5.is_subdirectly_reducible() # needs sage.combinat\n False\n\n sage: hex = LatticePoset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [6]})\n sage: hex.is_subdirectly_reducible() # needs sage.combinat\n True\n\n sage: hex.is_subdirectly_reducible(certificate=True) # needs sage.combinat\n (True,\n (Finite lattice containing 5 elements, Finite lattice containing 5 elements))\n\n sage: N5.is_subdirectly_reducible(certificate=True) # needs sage.combinat\n (False, (2, 3))\n sage: res, cert = hex.is_subdirectly_reducible(certificate=True) # needs sage.combinat\n sage: cert[0].is_isomorphic(N5) # needs sage.combinat\n True\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_distributive`,\n :meth:`is_vertically_decomposable`\n - Other: :meth:`subdirect_decomposition`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_subdirectly_reducible() for i in range(5)] # needs sage.combinat\n [False, False, False, True, True]\n '
H = self._hasse_diagram
A = H.atoms_of_congruence_lattice()
if (not certificate):
return (len(A) > 1)
if (self.cardinality() < 2):
return (False, None)
if (len(A) == 1):
for a in A[0]:
if (len(a) > 1):
(x, y) = (min(a), max(a))
return (False, (self._vertex_to_element(x), self._vertex_to_element(y)))
H_closure = H.transitive_closure()
a0 = [min(v) for v in A[0]]
a1 = [min(v) for v in A[1]]
K0 = LatticePoset(H_closure.subgraph(a0).transitive_reduction())
K1 = LatticePoset(H_closure.subgraph(a1).transitive_reduction())
return (True, (K0, K1))
def canonical_meetands(self, e):
"\n Return the canonical meetands of `e`.\n\n The canonical meetands of an element `e` in the lattice `L` is the\n subset `S \\subseteq L` such that 1) the meet of `S` is `e`, and\n 2) if the meet of some other subset `S'` of is also `e`, then for\n every element `s \\in S` there is an element `s' \\in S'` such that\n `s \\ge s'`.\n\n Informally said this is the set of greatest possible elements\n with given meet. It exists for every element if and only if\n the lattice is meet-semidistributive. Canonical meetands are\n always meet-irreducibles.\n\n INPUT:\n\n - ``e`` -- an element of the lattice\n\n OUTPUT:\n\n - canonical meetands as a list, if it exists; if not, ``None``\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [5, 6], 4: [6],\n ....: 5: [7], 6: [7]})\n sage: L.canonical_meetands(1)\n [5, 4]\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [6], 4: [6],\n ....: 5: [6]})\n sage: L.canonical_meetands(1) is None\n True\n\n .. SEEALSO::\n\n :meth:`canonical_joinands`\n\n TESTS::\n\n LatticePoset({1: []}).canonical_meetands(1)\n [1]\n "
H = self._hasse_diagram
e = self._element_to_vertex(e)
meetands = []
for a in H.neighbor_out_iterator(e):
above_a = set(H.depth_first_search(a))
def go_up(v):
return [v_ for v_ in H.neighbor_out_iterator(v) if (v_ not in above_a)]
result = None
for v in H.depth_first_search(e, neighbors=go_up):
if ((H.out_degree(v) == 1) and (next(H.neighbor_out_iterator(v)) in above_a)):
if (result is not None):
return None
result = v
meetands.append(result)
return [self._vertex_to_element(v) for v in meetands]
def canonical_joinands(self, e):
"\n Return the canonical joinands of `e`.\n\n The canonical joinands of an element `e` in the lattice `L` is the\n subset `S \\subseteq L` such that 1) the join of `S` is `e`, and\n 2) if the join of some other subset `S'` of is also `e`, then for\n every element `s \\in S` there is an element `s' \\in S'` such that\n `s \\le s'`.\n\n Informally said this is the set of lowest possible elements\n with given join. It exists for every element if and only if\n the lattice is join-semidistributive. Canonical joinands are\n always join-irreducibles.\n\n INPUT:\n\n - ``e`` -- an element of the lattice\n\n OUTPUT:\n\n - canonical joinands as a list, if it exists; if not, ``None``\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [5], 4: [6],\n ....: 5: [7], 6: [7]})\n sage: L.canonical_joinands(7)\n [3, 4]\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [6], 4: [6],\n ....: 5: [6]})\n sage: L.canonical_joinands(6) is None\n True\n\n .. SEEALSO::\n\n :meth:`canonical_meetands`\n\n TESTS::\n\n LatticePoset({1: []}).canonical_joinands(1)\n [1]\n "
H = self._hasse_diagram
e = self._element_to_vertex(e)
joinands = []
for a in H.neighbor_in_iterator(e):
below_a = set(H.depth_first_search(a, neighbors=H.neighbor_in_iterator))
def go_down(v):
return [v_ for v_ in H.neighbor_in_iterator(v) if (v_ not in below_a)]
result = None
for v in H.depth_first_search(e, neighbors=go_down):
if ((H.in_degree(v) == 1) and (next(H.neighbor_in_iterator(v)) in below_a)):
if (result is not None):
return None
result = v
joinands.append(result)
return [self._vertex_to_element(v) for v in joinands]
def is_constructible_by_doublings(self, type) -> bool:
"\n Return ``True`` if the lattice is constructible by doublings, and\n ``False`` otherwise.\n\n We call a lattice doubling constructible if it can be constructed\n from the one element lattice by a sequence of Alan Day's doubling\n constructions.\n\n Lattices constructible by interval doubling are also called\n *bounded*. Lattices constructible by lower and upper pseudo-interval\n are called *lower bounded* and *upper bounded*. Lattices\n constructible by any convex set doubling are called *congruence\n normal*.\n\n INPUT:\n\n - ``type`` -- a string; can be one of the following:\n\n * ``'interval'`` - allow only doublings of an interval\n * ``'lower'`` - allow doublings of lower pseudo-interval; that is, a\n subset of the lattice with a unique minimal element\n * ``'upper'`` - allow doublings of upper pseudo-interval; that is, a\n subset of the lattice with a unique maximal element\n * ``'convex'`` - allow doubling of any convex set\n * ``'any'`` - allow doubling of any set\n\n EXAMPLES:\n\n The pentagon can be constructed by doubling intervals; the 5-element\n diamond can not be constructed by any doublings::\n\n sage: posets.PentagonPoset().is_constructible_by_doublings('interval')\n True\n\n sage: posets.DiamondPoset(5).is_constructible_by_doublings('any') # needs sage.combinat\n False\n\n After doubling both upper and lower pseudo-interval a lattice is\n constructible by convex subset doubling::\n\n sage: L = posets.BooleanLattice(2)\n sage: L = L.day_doubling([0, 1, 2]) # A lower pseudo-interval\n sage: L.is_constructible_by_doublings('interval')\n False\n sage: L.is_constructible_by_doublings('lower')\n True\n sage: L = L.day_doubling([(3,0), (1,1), (2,1)]) # An upper pseudo-interval\n sage: L.is_constructible_by_doublings('upper')\n False\n sage: L.is_constructible_by_doublings('convex') # needs sage.combinat\n True\n\n An example of a lattice that can be constructed by doublings\n of a non-convex subsets::\n\n sage: L = LatticePoset(DiGraph('OQC?a?@CO?G_C@?GA?O??_??@?BO?A_?G??C??_?@???'))\n sage: L.is_constructible_by_doublings('convex')\n False\n sage: L.is_constructible_by_doublings('any')\n True\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_distributive` (doubling by interval),\n :meth:`is_join_semidistributive` (doubling by lower pseudo-intervals),\n :meth:`is_meet_semidistributive` (doubling by upper pseudo-intervals)\n - Mutually exclusive properties: :meth:`is_simple` (doubling by any set)\n - Other: :meth:`day_doubling`\n\n TESTS::\n\n sage: LatticePoset().is_constructible_by_doublings('interval')\n True\n\n The congruence lattice of this lattice has maximal chains satisfying the needed\n property, but also maximal chains not satisfying that; this shows that the code\n can't be optimized to test just some maximal chain::\n\n sage: L = LatticePoset(DiGraph('QSO?I?_?_GBG??_??a???@?K??A??B???C??s??G??I??@??A??@???'))\n sage: L.is_constructible_by_doublings('convex')\n False\n sage: L.is_constructible_by_doublings('any')\n True\n\n ALGORITHM:\n\n According to [HOLM2016]_ a lattice `L` is lower bounded if and only if\n `|\\mathrm{Ji}(L)| = |\\mathrm{Ji}(\\mathrm{Con}\\ L)|`, and so dually\n `|\\mathrm{Mi}(L)| = |\\mathrm{Mi}(\\mathrm{Con}\\ L)|` in upper bounded\n lattices. The same reference gives a test for being constructible by\n convex or by any subset.\n "
if (type not in ['interval', 'lower', 'upper', 'convex', 'any']):
raise ValueError("type must be one of 'interval', 'lower', 'upper', 'convex' or 'any'")
if (self.cardinality() < 5):
return True
if ((type == 'interval') and (len(self.join_irreducibles()) != len(self.meet_irreducibles()))):
return False
if ((type == 'upper') or (type == 'interval')):
H = self._hasse_diagram
found = set()
for v in H:
if (H.out_degree(v) == 1):
S = frozenset(map(frozenset, H.congruence([[v, next(H.neighbor_out_iterator(v))]])))
if (S in found):
return False
found.add(S)
return True
if (type == 'lower'):
H = self._hasse_diagram
found = set()
for v in H:
if (H.in_degree(v) == 1):
S = frozenset(map(frozenset, H.congruence([[v, next(H.neighbor_in_iterator(v))]])))
if (S in found):
return False
found.add(S)
return True
if (type == 'convex'):
return self._hasse_diagram.is_congruence_normal()
def splitting_depth_2(a, b):
'\n Return ``True`` if every block of `b` is made from\n combining at most two blocks of `a`.\n '
return all(((len([x for x in a if x.issubset(y)]) <= 2) for y in b))
conL = self.congruences_lattice()
todo = [conL[0]]
reachable = []
while todo:
e = todo.pop()
for e_up in conL.upper_covers(e):
if ((e_up not in reachable) and splitting_depth_2(e, e_up)):
if (len(e_up) == 1):
return True
reachable.append(e_up)
todo.append(e_up)
return False
def is_isoform(self, certificate=False):
'\n Return ``True`` if the lattice is isoform and ``False`` otherwise.\n\n A congruence is *isoform* (or *isotype*) if all blocks are isomorphic\n sublattices. A lattice is isoform if it has only isoform\n congruences.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate if the lattice is not isoform\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, C)``, where `C` is a non-isoform congruence as a\n :class:`sage.combinat.set_partition.SetPartition`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [6, 7],\n ....: 4: [7], 5: [8], 6: [8], 7: [8]})\n sage: L.is_isoform() # needs sage.combinat\n True\n\n Every isoform lattice is (trivially) uniform, but the converse is\n not true::\n\n sage: L = LatticePoset({1: [2, 3, 6], 2: [4, 5], 3: [5], 4: [9, 8],\n ....: 5: [7, 8], 6: [9], 7: [10], 8: [10], 9: [10]})\n sage: L.is_isoform(), L.is_uniform() # needs sage.combinat\n (False, True)\n\n sage: L.is_isoform(certificate=True) # needs sage.combinat\n (False, {{1, 2, 4, 6, 9}, {3, 5, 7, 8, 10}})\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_uniform`\n - Stronger properties: :meth:`is_simple`,\n :meth:`is_relatively_complemented`\n - Other: :meth:`congruence`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_isoform() for i in range(5)]\n [True, True, True, False, False]\n\n sage: posets.DiamondPoset(5).is_isoform() # Simple, so trivially isoform # needs sage.combinat\n True\n '
ok = ((True, None) if certificate else True)
H = self._hasse_diagram
if (H.order() == 0):
return ok
for c in H.congruences_iterator():
cong = list(c)
if (len(cong) in [1, H.order()]):
continue
if (not certificate):
if any(((len(x) != len(cong[0])) for x in cong)):
return False
d = H.subgraph(cong[0])
for part in cong:
if (not H.subgraph(part).is_isomorphic(d)):
if certificate:
from sage.combinat.set_partition import SetPartition
return (False, SetPartition([[self._vertex_to_element(v) for v in p] for p in cong]))
return False
return ok
def is_uniform(self, certificate=False):
'\n Return ``True`` if the lattice is uniform and ``False`` otherwise.\n\n A congruence is *uniform* if all blocks have equal number\n of elements. A lattice is uniform if it has only uniform\n congruences.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate if the lattice is not uniform\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, C)``, where `C` is a non-uniform congruence as a\n :class:`sage.combinat.set_partition.SetPartition`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [6, 7], 3: [5], 4: [5],\n ....: 5: [9, 8], 6: [9], 7: [10], 8: [10], 9: [10]})\n sage: L.is_uniform() # needs sage.combinat\n True\n\n Every uniform lattice is regular, but the converse is not true::\n\n sage: N6 = LatticePoset({1: [2, 3, 5], 2: [4], 3: [4], 5: [6], 4: [6]})\n sage: N6.is_uniform(), N6.is_regular()\n (False, True)\n\n sage: N6.is_uniform(certificate=True) # needs sage.combinat\n (False, {{1, 2, 3, 4}, {5, 6}})\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_regular`\n - Stronger properties: :meth:`is_isoform`\n - Other: :meth:`congruence`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_uniform() for i in range(5)]\n [True, True, True, False, False]\n\n sage: posets.DiamondPoset(5).is_uniform() # Simple, so trivially uniform # needs sage.combinat\n True\n '
ok = ((True, None) if certificate else True)
H = self._hasse_diagram
if (H.order() < 3):
return ok
x = H._trivial_nonregular_congruence()
if (x is not None):
if certificate:
return (False, self.congruence([[self._vertex_to_element(x[0]), self._vertex_to_element(x[1])]]))
return False
x = self.is_vertically_decomposable(certificate=True)
if x[0]:
if certificate:
return (False, self.congruence([self.vertical_decomposition()[0]]))
return False
for c in H.congruences_iterator():
cong = list(c)
n = len(cong[0])
for part in cong:
if (len(part) != n):
if certificate:
from sage.combinat.set_partition import SetPartition
return (False, SetPartition([[self._vertex_to_element(v) for v in p] for p in c]))
return False
return ok
def is_regular(self, certificate=False):
'\n Return ``True`` if the lattice is regular and ``False`` otherwise.\n\n A congruence of a lattice is *regular* if it is generated\n by any of its parts. A lattice is regular if it has only\n regular congruences.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate if the lattice is not regular\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (C, p))``, where `C` is a non-regular congruence as a\n :class:`sage.combinat.set_partition.SetPartition` and `p` is a\n congruence class of `C` such that the congruence generated by `p`\n is not `C`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [8, 7], 4: [6, 7],\n ....: 5: [8], 6: [9], 7: [9], 8: [9]})\n sage: L.is_regular() # needs sage.combinat\n True\n\n sage: N5 = posets.PentagonPoset()\n sage: N5.is_regular() # needs sage.combinat\n False\n sage: N5.is_regular(certificate=True) # needs sage.combinat\n (False, ({{0}, {1}, {2, 3}, {4}}, [0]))\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`is_uniform`,\n :meth:`is_sectionally_complemented`,\n :meth:`is_cosectionally_complemented`\n - Mutually exclusive properties: :meth:`is_vertically_decomposable`\n - Other: :meth:`congruence`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_regular() for i in range(5)] # needs sage.combinat\n [True, True, True, False, False]\n '
ok = ((True, None) if certificate else True)
H = self._hasse_diagram
if (H.order() < 3):
return ok
for cong in H.congruences_iterator():
x = iter(cong.root_to_elements_dict().values())
ell = len(next(x))
if all(((len(p) == ell) for p in x)):
continue
for part in cong:
if (H.congruence([part]) != cong):
if certificate:
from sage.combinat.set_partition import SetPartition
return (False, (SetPartition([[self._vertex_to_element(v) for v in p] for p in cong]), [self._vertex_to_element(v) for v in part]))
return False
return ok
def is_simple(self, certificate=False):
'\n Return ``True`` if the lattice is simple and ``False`` otherwise.\n\n A lattice is *simple* if it has no nontrivial congruences; in\n other words, for every two distinct elements `a` and `b` the\n principal congruence generated by `(a, b)` has only one\n component, i.e. the whole lattice.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate if the lattice is not simple\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, c)``, where `c` is a nontrivial congruence as a\n :class:`sage.combinat.set_partition.SetPartition`.\n If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: posets.DiamondPoset(5).is_simple() # Smallest nontrivial example\n True\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [6], 4: [6], 5: [6]})\n sage: L.is_simple()\n False\n sage: L.is_simple(certificate=True)\n (False, {{1, 3}, {2, 4, 5, 6}})\n\n Two more examples. First is a non-simple lattice without any\n 2-element congruences::\n\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5], 3: [5], 4: [6, 7],\n ....: 5: [8], 6: [8], 7: [8]})\n sage: L.is_simple() # needs sage.combinat\n False\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [8],\n ....: 5: [8], 6: [8], 7: [8]})\n sage: L.is_simple() # needs sage.combinat\n True\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`is_isoform`\n - Mutually exclusive properties: :meth:`is_constructible_by_doublings`\n (by any set)\n - Other: :meth:`congruence`\n\n TESTS::\n\n sage: [posets.ChainPoset(i).is_simple() for i in range(5)]\n [True, True, True, False, False]\n '
from sage.combinat.set_partition import SetPartition
cong = self._hasse_diagram.find_nontrivial_congruence()
if (cong is None):
return ((True, None) if certificate else True)
if (not certificate):
return False
return (False, SetPartition([[self._vertex_to_element(v) for v in s] for s in cong]))
def subdirect_decomposition(self):
'\n Return the subdirect decomposition of the lattice.\n\n The subdirect decomposition of a lattice `L` is the list\n of smaller lattices `L_1, \\ldots, L_n` such that `L` is\n a sublattice of `L_1 \\times \\ldots \\times L_n`, none\n of `L_i` can be decomposed further and `L` is not a sublattice\n of any `L_i`. (Except when the list has only one element, i.e.\n when the lattice is subdirectly irreducible.)\n\n EXAMPLES::\n\n sage: posets.ChainPoset(3).subdirect_decomposition() # needs sage.combinat\n [Finite lattice containing 2 elements, Finite lattice containing 2 elements]\n\n sage: # needs sage.combinat\n sage: L = LatticePoset({1: [2, 4], 2: [3], 3: [6, 7], 4: [5, 7],\n ....: 5: [9, 8], 6: [9], 7: [9], 8: [10], 9: [10]})\n sage: Ldecomp = L.subdirect_decomposition()\n sage: [fac.cardinality() for fac in Ldecomp]\n [2, 5, 7]\n sage: Ldecomp[1].is_isomorphic(posets.PentagonPoset())\n True\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: posets.ChainPoset(0).subdirect_decomposition()\n [Finite lattice containing 0 elements]\n sage: posets.ChainPoset(1).subdirect_decomposition()\n [Finite lattice containing 1 elements]\n sage: posets.ChainPoset(2).subdirect_decomposition()\n [Finite lattice containing 2 elements]\n\n The pentagon is subdirectly irreducible, i.e. the decomposition\n has only one element::\n\n sage: N5 = posets.PentagonPoset()\n sage: N5.subdirect_decomposition() # needs sage.combinat\n [Finite lattice containing 5 elements]\n '
H = self._hasse_diagram
(cong_ji, congs) = H.principal_congruences_poset()
if ((self.cardinality() <= 2) or cong_ji.has_bottom()):
return [self.relabel(self._element_to_vertex_dict)]
L_ = cong_ji.order_ideals_lattice()
c = L_.canonical_meetands(L_.bottom())
L = L_.subposet(L_.order_ideal(c))
C = {}
for e in L:
low = L.lower_covers(e)
if (len(low) == 1):
C[e] = congs[max(e, key=cong_ji._element_to_vertex)]
elif low:
low_0 = min(low, key=(lambda x: C[x].number_of_subsets()))
for new_pair in e:
if (new_pair not in low_0):
break
C[e] = self._hasse_diagram.congruence([new_pair], start=C[low_0])
decomposing_congruences = [C[m] for m in L.maximal_elements()]
decomposing_congruences.sort(key=(lambda x: x.number_of_subsets()))
result = []
for congruence in decomposing_congruences:
part_bottoms = [min(part) for part in congruence]
F = H.transitive_closure().subgraph(part_bottoms)
result.append(LatticePoset(F))
return result
def congruence(self, S):
'\n Return the congruence generated by set of sets `S`.\n\n A congruence of a lattice is an equivalence relation `\\cong` that is\n compatible with meet and join; i.e. if `a_1 \\cong a_2` and\n `b_1 \\cong b_2`, then `(a_1 \\\\vee b_1) \\cong (a_2 \\\\vee b_2)` and\n `(a_1 \\wedge b_1) \\cong (a_2 \\wedge b_2)`.\n\n By the congruence generated by set of sets `\\{S_1, \\ldots, S_n\\}` we\n mean the least congruence `\\cong` such that for every `x, y \\in S_i`\n for some `i` we have `x \\cong y`.\n\n INPUT:\n\n - ``S`` -- a list of lists; list of element blocks that the congruence\n will contain\n\n OUTPUT:\n\n Congruence of the lattice as a\n :class:`sage.combinat.set_partition.SetPartition`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: L = posets.DivisorLattice(12)\n sage: cong = L.congruence([[1, 3]])\n sage: sorted(sorted(c) for c in cong)\n [[1, 3], [2, 6], [4, 12]]\n sage: L.congruence([[1, 2], [6, 12]])\n {{1, 2, 4}, {3, 6, 12}}\n\n sage: L = LatticePoset({1: [2, 3], 2: [4], 3: [4], 4: [5]})\n sage: L.congruence([[1, 2]]) # needs sage.combinat\n {{1, 2}, {3, 4}, {5}}\n\n sage: L = LatticePoset({1: [2, 3], 2: [4, 5, 6], 4: [5], 5: [7, 8],\n ....: 6: [8], 3: [9], 7: [10], 8: [10], 9:[10]})\n sage: cong = L.congruence([[1, 2]]) # needs sage.combinat\n sage: cong[0] # needs sage.combinat\n frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})\n\n .. SEEALSO:: :meth:`quotient`\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: P = posets.PentagonPoset()\n sage: P.congruence([])\n {{0}, {1}, {2}, {3}, {4}}\n sage: P.congruence([[2]])\n {{0}, {1}, {2}, {3}, {4}}\n sage: P.congruence([[2, 2]])\n {{0}, {1}, {2}, {3}, {4}}\n sage: P.congruence([[0, 4]])\n {{0, 1, 2, 3, 4}}\n sage: LatticePoset().congruence([])\n {}\n\n "Double zigzag" to ensure that up-down propagation\n works::\n\n sage: L = LatticePoset(DiGraph(\'P^??@_?@??B_?@??B??@_?@??B_?@??B??@??A??C??G??O???\'))\n sage: sorted(sorted(p) for p in L.congruence([[1,6]])) # needs sage.combinat\n [[0], [1, 6], [2], [3, 8], [4], [5, 10], [7, 12], [9, 14], [11], [13], [15], [16]]\n\n Simple lattice, i.e. a lattice without any nontrivial congruence::\n\n sage: L = LatticePoset(DiGraph(\'GPb_@?OC@?O?\'))\n sage: L.congruence([[1,2]]) # needs sage.combinat\n {{0, 1, 2, 3, 4, 5, 6, 7}}\n '
from sage.combinat.set_partition import SetPartition
S = [[self._element_to_vertex(e) for e in s] for s in S]
cong = self._hasse_diagram.congruence(S)
return SetPartition([[self._vertex_to_element(v) for v in s] for s in cong])
def quotient(self, congruence, labels='tuple'):
"\n Return the quotient lattice by ``congruence``.\n\n Let `L` be a lattice and `\\Theta` be a congruence of `L` with\n congruence classes `\\Theta_1, \\Theta_2, \\ldots`. The quotient\n lattice `L/\\Theta` is the lattice with elements\n `\\{\\Theta_1, \\Theta_2, \\ldots\\}` and meet and join given by the\n original lattice. Explicitly, if `e_1 \\in \\Theta_1` and\n `e_2 \\in \\Theta_2`, such that `e_1 \\vee e_2 \\in \\Theta_3` then\n `\\Theta_1 \\vee \\Theta_2 = \\Theta_3` in `L/\\Theta` and similarly\n for meets.\n\n INPUT:\n\n - ``congruence`` -- list of lists; a congruence\n\n - ``labels`` -- string; the elements of the resulting\n lattice and can be one of the following:\n\n * ``'tuple'`` - elements are tuples of elements of the original\n lattice\n * ``'lattice'`` - elements are sublattices of the original lattice\n * ``'integer'`` - elements are labeled by integers\n\n .. WARNING::\n\n ``congruence`` is expected to be a valid congruence of the\n lattice. This is *not* checked.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: L = posets.PentagonPoset()\n sage: c = L.congruence([[0, 1]])\n sage: I = L.quotient(c); I\n Finite lattice containing 2 elements\n sage: I.top()\n (2, 3, 4)\n sage: I = L.quotient(c, labels='lattice')\n sage: I.top()\n Finite lattice containing 3 elements\n\n sage: # needs sage.combinat\n sage: B3 = posets.BooleanLattice(3)\n sage: c = B3.congruence([[0,1]])\n sage: B2 = B3.quotient(c, labels='integer')\n sage: B2.is_isomorphic(posets.BooleanLattice(2))\n True\n\n .. SEEALSO:: :meth:`congruence`\n\n TESTS::\n\n sage: E = LatticePoset()\n sage: E.quotient([])\n Finite lattice containing 0 elements\n\n sage: L = posets.PentagonPoset()\n sage: L.quotient(L.congruence([[1]])).is_isomorphic(L) # needs sage.combinat\n True\n "
if (labels not in ['lattice', 'tuple', 'integer']):
raise ValueError("labels must be one of 'lattice', 'tuple' or 'integer'")
parts_H = [sorted([self._element_to_vertex(e) for e in part]) for part in congruence]
minimal_vertices = [part[0] for part in parts_H]
H = self._hasse_diagram.transitive_closure().subgraph(minimal_vertices).transitive_reduction()
if (labels == 'integer'):
H.relabel(list(range(len(minimal_vertices))))
return LatticePoset(H)
part_dict = {m[0]: [self._vertex_to_element(x) for x in m] for m in parts_H}
if (labels == 'tuple'):
H.relabel((lambda m: tuple(part_dict[m])))
return LatticePoset(H)
H.relabel((lambda m: self.sublattice(part_dict[m])))
return LatticePoset(H)
def congruences_lattice(self, labels='congruence'):
"\n Return the lattice of congruences.\n\n A congruence of a lattice is a partition of elements to classes\n compatible with both meet- and join-operation; see :meth:`congruence`.\n Elements of the *congruence lattice* are congruences ordered by\n refinement; i.e. if every class of a congruence `\\Theta` is\n contained in some class of `\\Phi`, then `\\Theta \\le \\Phi`\n in the congruence lattice.\n\n INPUT:\n\n - ``labels`` -- a string; the type of elements in the resulting lattice\n\n OUTPUT:\n\n A distributive lattice.\n\n - If ``labels='congruence'``, then elements of the\n result will be congruences given as\n :class:`sage.combinat.set_partition.SetPartition`.\n - If ``labels='integers'``, result is a lattice on\n integers isomorphic to the congruence lattice.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: N5 = posets.PentagonPoset()\n sage: CL = N5.congruences_lattice(); CL\n Finite lattice containing 5 elements\n sage: CL.atoms()\n [{{0}, {1}, {2, 3}, {4}}]\n sage: CL.coatoms()\n [{{0, 1}, {2, 3, 4}}, {{0, 2, 3}, {1, 4}}]\n\n sage: C4 = posets.ChainPoset(4)\n sage: CL = C4.congruences_lattice(labels='integer') # needs sage.combinat\n sage: CL.is_isomorphic(posets.BooleanLattice(3)) # needs sage.combinat\n True\n\n TESTS::\n\n sage: # needs sage.combinat\n sage: posets.ChainPoset(0).congruences_lattice()\n Finite lattice containing 1 elements\n sage: posets.ChainPoset(1).congruences_lattice()\n Finite lattice containing 1 elements\n sage: posets.ChainPoset(2).congruences_lattice()\n Finite lattice containing 2 elements\n sage: posets.ChainPoset(3).congruences_lattice()\n Finite lattice containing 4 elements\n "
from sage.sets.set import Set
from sage.sets.disjoint_set import DisjointSet
from sage.combinat.set_partition import SetPartition
if (labels not in ['integer', 'congruence']):
raise ValueError("'labels' must be 'integer' or 'congruence'")
(cong_ji, congs) = self._hasse_diagram.principal_congruences_poset()
if (labels == 'integer'):
tmp = Poset(cong_ji).order_ideals_lattice(as_ideals=False)
return tmp.relabel(tmp._element_to_vertex_dict)
L = cong_ji.order_ideals_lattice()
C = {}
C[Set()] = DisjointSet(self.cardinality())
for e in L:
low = L.lower_covers(e)
if (len(low) == 1):
C[e] = congs[max(e, key=cong_ji._element_to_vertex)]
if (len(low) > 1):
low_0 = min(low, key=(lambda x: C[x].number_of_subsets()))
for new_pair in e:
if (new_pair not in low_0):
break
C[e] = self._hasse_diagram.congruence([new_pair], start=C[low_0])
return L.relabel((lambda e: SetPartition([[self._vertex_to_element(v) for v in p] for p in C[e]])))
def feichtner_yuzvinsky_ring(self, G, use_defining=False, base_ring=None):
"\n Return the Feichtner-Yuzvinsky ring of ``self`` and ``G``.\n\n Let `R` be a commutative ring, `L` a lattice, and `G \\subseteq L`.\n The *Feichtner-Yuzvinsky ring* is the quotient of the polynomial\n ring `R[h_g \\mid g \\in G]` by the ideal generated by\n\n - `h_a` for every atom `a \\in L \\cap G` and\n - for every antichain `A` of the subposet `G` such that\n `g := \\bigvee A \\in G` (with the join taken in `L`)\n\n .. MATH::\n\n \\prod_{a \\in A} (h_g - h_a).\n\n This was originally described for `G` such that `(L, G)` is a built\n lattice in the sense of [FY2004]_ (which has a geometric motivation),\n but this has been extended to `G` being an arbitrary subset.\n\n This is not the original definition, which uses the nested subsets\n of `G` (see [FY2004]_ for the definition). However, the original\n construction, which we call the *defining* presentation and use the\n variables `\\{x_g \\mid g \\in G\\}`, can be recovered by setting\n `h_g = \\sum_{g' \\geq g} x_{g'}` (where `g' \\in G`).\n\n INPUT:\n\n - ``G`` -- a subset of elements of ``self``\n - ``use_defining`` -- (default: ``False``) whether or not to use\n the defining presentation in `x_g`\n - ``base_ring`` -- (default: `\\QQ`) the base ring\n\n The order on the variables is equal to the ordering of the\n elements in ``G``.\n\n EXAMPLES::\n\n sage: B2 = posets.BooleanLattice(2)\n sage: FY = B2.feichtner_yuzvinsky_ring(B2[1:])\n sage: FY\n Quotient of Multivariate Polynomial Ring in h0, h1, h2 over Rational Field\n by the ideal (h0, h1, h0*h1 - h0*h2 - h1*h2 + h2^2)\n\n sage: FY = B2.feichtner_yuzvinsky_ring(B2[1:], use_defining=True)\n sage: FY\n Quotient of Multivariate Polynomial Ring in x0, x1, x2 over Rational Field\n by the ideal (x0 + x2, x1 + x2, x0*x1)\n\n We reproduce the example from Section 5 of [Coron2023]_::\n\n sage: # needs sage.geometry.polyhedron\n sage: H.<a,b,c,d> = HyperplaneArrangements(QQ)\n sage: Arr = H(a-b, b-c, c-d, d-a)\n sage: P = LatticePoset(Arr.intersection_poset())\n sage: FY = P.feichtner_yuzvinsky_ring([P.top(),5,1,2,3,4])\n sage: FY.defining_ideal().groebner_basis() # needs sage.libs.singular\n [h0^2 - h0*h1, h1^2, h2, h3, h4, h5]\n\n TESTS::\n\n sage: B2 = posets.BooleanLattice(2)\n sage: B2.feichtner_yuzvinsky_ring([1,2,1])\n Traceback (most recent call last):\n ...\n ValueError: the input set G must not contain duplicates\n "
if (base_ring is None):
from sage.rings.rational_field import QQ
base_ring = QQ
G = tuple(G)
Gmap = {g: i for (i, g) in enumerate(G)}
if (len(G) != len(Gmap)):
raise ValueError('the input set G must not contain duplicates')
GP = self.subposet(G)
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
if use_defining:
R = PolynomialRing(base_ring, 'x', len(G))
gens = R.gens()
gens = [R.sum((gens[Gmap[gp]] for gp in GP.order_filter([g]))) for g in G]
else:
R = PolynomialRing(base_ring, 'h', len(G))
gens = R.gens()
I = []
atoms = set(self.atoms())
for (i, g) in enumerate(G):
if (g in atoms):
I.append(gens[i])
for A in GP.antichains_iterator():
if (len(A) <= 1):
continue
gp = A[0]
for y in A[1:]:
gp = self.join(gp, y)
if (gp not in Gmap):
continue
i = Gmap[gp]
I.append(R.prod(((gens[i] - gens[Gmap[a]]) for a in A)))
return R.quotient(I)
|
def _log_2(n):
'\n Return the 2-based logarithm of `n` rounded up.\n\n `n` is assumed to be a positive integer.\n\n EXAMPLES::\n\n sage: sage.combinat.posets.lattices._log_2(10)\n 4\n\n TESTS::\n\n sage: sage.combinat.posets.lattices._log_2(15)\n 4\n sage: sage.combinat.posets.lattices._log_2(16)\n 4\n sage: sage.combinat.posets.lattices._log_2(17)\n 5\n '
bits = (- 1)
i = n
while i:
i = (i >> 1)
bits += 1
if ((1 << bits) == n):
return bits
return (bits + 1)
|
class LinearExtensionOfPoset(ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
'\n A linear extension of a finite poset `P` of size `n` is a total\n ordering `\\pi := \\pi_0 \\pi_1 \\ldots \\pi_{n-1}` of its elements\n such that `i<j` whenever `\\pi_i < \\pi_j` in the poset `P`.\n\n When the elements of `P` are indexed by `\\{1,2,\\ldots,n\\}`, `\\pi`\n denotes a permutation of the elements of `P` in one-line notation.\n\n INPUT:\n\n - ``linear_extension`` -- a list of the elements of `P`\n - ``poset`` -- the underlying poset `P`\n\n .. SEEALSO:: :class:`~sage.combinat.posets.posets.Poset`, :class:`LinearExtensionsOfPoset`\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]), linear_extension=True, facade=False)\n sage: p = P.linear_extension([1,4,2,3]); p\n [1, 4, 2, 3]\n sage: p.parent()\n The set of all linear extensions of Finite poset containing 4 elements with distinguished linear extension\n sage: p[0], p[1], p[2], p[3]\n (1, 4, 2, 3)\n\n Following Schützenberger and later Haiman and\n Malvenuto-Reutenauer, Stanley [Stan2009]_ defined a promotion\n and evacuation operator on any finite poset `P` using operators\n `\\tau_i` on the linear extensions of `P`::\n\n sage: p.promotion()\n [1, 2, 3, 4]\n sage: Q = p.promotion().to_poset()\n sage: Q.cover_relations()\n [[1, 3], [1, 4], [2, 3]]\n sage: Q == P\n True\n\n sage: p.promotion(3)\n [1, 4, 2, 3]\n sage: Q = p.promotion(3).to_poset()\n sage: Q == P\n False\n sage: Q.cover_relations()\n [[1, 2], [1, 4], [3, 4]]\n '
@staticmethod
def __classcall_private__(cls, linear_extension, poset):
"\n Implements the shortcut ``LinearExtensionOfPoset(linear_extension, poset)`` to ``LinearExtensionsOfPoset(poset)(linear_extension)``\n\n INPUT:\n\n - ``linear_extension`` -- a list of elements of ``poset``\n - ``poset`` -- a finite poset\n\n .. TODO:: check whether this method is still useful\n\n TESTS::\n\n sage: from sage.combinat.posets.linear_extensions import LinearExtensionOfPoset\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]))\n sage: p = LinearExtensionOfPoset([1,4,2,3], P)\n sage: p.parent()\n The set of all linear extensions of Finite poset containing 4 elements\n sage: type(p)\n <class 'sage.combinat.posets.linear_extensions.LinearExtensionsOfPoset_with_category.element_class'>\n sage: p.poset()\n Finite poset containing 4 elements\n sage: TestSuite(p).run()\n\n TESTS::\n\n sage: LinearExtensionOfPoset([4,3,2,1], P)\n Traceback (most recent call last):\n ...\n ValueError: [4, 3, 2, 1] is not a linear extension of Finite poset containing 4 elements\n\n sage: p is LinearExtensionOfPoset(p, P)\n True\n "
if isinstance(linear_extension, cls):
return linear_extension
return LinearExtensionsOfPoset(poset)(linear_extension)
def check(self):
'\n Checks whether ``self`` is indeed a linear extension of the underlying poset.\n\n TESTS::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]))\n sage: P.linear_extension([1,4,2,3])\n [1, 4, 2, 3]\n sage: P.linear_extension([4,3,2,1])\n Traceback (most recent call last):\n ...\n ValueError: [4, 3, 2, 1] is not a linear extension of Finite poset containing 4 elements\n '
P = self.parent().poset()
if (not P.is_linear_extension(self)):
raise ValueError(('%s is not a linear extension of %s' % (self, P)))
def poset(self):
'\n Return the underlying original poset.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,2],[2,3],[1,4]]))\n sage: p = P.linear_extension([1,2,4,3])\n sage: p.poset()\n Finite poset containing 4 elements\n '
return self.parent().poset()
def _latex_(self):
"\n Return the latex string for ``self``.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]))\n sage: p = P.linear_extension([1,2,3,4])\n sage: p._latex_()\n '\\\\mathtt{(1, 2, 3, 4)}'\n "
return (('\\mathtt{' + str(tuple(self))) + '}')
def to_poset(self):
'\n Return the poset associated to the linear extension ``self``.\n\n This method returns the poset obtained from the original poset\n `P` by relabelling the `i`-th element of ``self`` to the\n `i`-th element of the original poset, while keeping the linear\n extension of the original poset.\n\n For a poset with default linear extension `1,\\dots,n`,\n ``self`` can be interpreted as a permutation, and the\n relabelling is done according to the inverse of this\n permutation.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,2],[1,3],[3,4]]), linear_extension=True, facade=False)\n sage: p = P.linear_extension([1,3,4,2])\n sage: Q = p.to_poset(); Q\n Finite poset containing 4 elements with distinguished linear extension\n sage: P == Q\n False\n\n The default linear extension remains the same::\n\n sage: list(P)\n [1, 2, 3, 4]\n sage: list(Q)\n [1, 2, 3, 4]\n\n But the relabelling can be seen on cover relations::\n\n sage: P.cover_relations()\n [[1, 2], [1, 3], [3, 4]]\n sage: Q.cover_relations()\n [[1, 2], [1, 4], [2, 3]]\n\n sage: p = P.linear_extension([1,2,3,4])\n sage: Q = p.to_poset()\n sage: P == Q\n True\n '
P = self.parent().poset()
old = [P.unwrap(x) for x in self]
new = [P.unwrap(x) for x in P]
relabelling = dict(zip(old, new))
return P.relabel(relabelling).with_linear_extension(new)
def is_greedy(self):
'\n Return ``True`` if the linear extension is greedy.\n\n A linear extension `[e_1, e_2, \\ldots, e_n]` is *greedy* if for\n every `i` either `e_{i+1}` covers `e_i` or all upper covers\n of `e_i` have at least one lower cover that is not in\n `[e_1, e_2, \\ldots, e_i]`.\n\n Informally said a linear extension is greedy if it "always\n goes up when possible" and so has no unnecessary jumps.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset() # optional - sage.modules\n sage: for l in P.linear_extensions(): # optional - sage.modules\n ....: if not l.is_greedy():\n ....: print(l)\n [0, 2, 1, 3, 4]\n\n TESTS::\n\n sage: E = Poset()\n sage: E.linear_extensions()[0].is_greedy()\n True\n '
P = self.poset()
for i in range((len(self) - 1)):
if (not P.covers(self[i], self[(i + 1)])):
for u in P.upper_covers(self[i]):
if all(((l in self[:(i + 1)]) for l in P.lower_covers(u))):
return False
return True
def is_supergreedy(self):
'\n Return ``True`` if the linear extension is supergreedy.\n\n A linear extension of a poset `P` with elements `\\{x_1,x_2,...,x_t\\}`\n is *super greedy*, if it can be obtained using the following\n algorithm: choose `x_1` to be a minimal element of `P`;\n suppose `X = \\{x_1,...,x_i\\}` have been chosen; let `M` be\n the set of minimal elements of `P\\setminus X`. If there is an element\n of `M` which covers an element `x_j` in `X`, then let `x_{i+1}`\n be one of these such that `j` is maximal; otherwise, choose `x_{i+1}`\n to be any element of `M`.\n\n Informally, a linear extension is supergreedy if it "always\n goes up and receedes the least"; in other words, supergreedy\n linear extensions are depth-first linear extensions.\n For more details see [KTZ1987]_.\n\n EXAMPLES::\n\n sage: X = [0,1,2,3,4,5,6]\n sage: Y = [[0,5],[1,4],[1,5],[3,6],[4,3],[5,6],[6,2]]\n sage: P = Poset((X,Y), cover_relations=True, facade=False)\n sage: for l in P.linear_extensions(): # optional - sage.modules sage.rings.finite_rings\n ....: if l.is_supergreedy():\n ....: print(l)\n [1, 4, 3, 0, 5, 6, 2]\n [0, 1, 4, 3, 5, 6, 2]\n [0, 1, 5, 4, 3, 6, 2]\n\n sage: Q = posets.PentagonPoset() # optional - sage.modules\n sage: for l in Q.linear_extensions(): # optional - sage.modules sage.rings.finite_rings\n ....: if not l.is_supergreedy():\n ....: print(l)\n [0, 2, 1, 3, 4]\n\n TESTS::\n\n sage: T = Poset()\n sage: T.linear_extensions()[0].is_supergreedy()\n True\n '
H = self.poset().hasse_diagram()
L = sources = H.sources()
linext = []
for e in self:
if (e not in L):
return False
linext.append(e)
for y in reversed(linext):
L = [x for x in H.neighbor_out_iterator(y) if ((x not in linext) and all(((low in linext) for low in H.neighbor_in_iterator(x))))]
if L:
break
else:
L = sources = [x for x in sources if (x not in linext)]
return True
def tau(self, i):
'\n Return the operator `\\tau_i` on linear extensions ``self`` of a poset.\n\n INPUT:\n\n - `i` -- an integer between `1` and `n-1`, where `n` is the cardinality of the poset.\n\n The operator `\\tau_i` on a linear extension `\\pi` of a poset\n `P` interchanges positions `i` and `i+1` if the result is\n again a linear extension of `P`, and otherwise acts\n trivially. For more details, see [Stan2009]_.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]), linear_extension=True)\n sage: L = P.linear_extensions()\n sage: l = L.an_element(); l\n [1, 2, 3, 4]\n sage: l.tau(1)\n [2, 1, 3, 4]\n sage: for p in L: # optional - sage.modules sage.rings.finite_rings\n ....: for i in range(1,4):\n ....: print("{} {} {}".format(i, p, p.tau(i)))\n 1 [1, 2, 3, 4] [2, 1, 3, 4]\n 2 [1, 2, 3, 4] [1, 2, 3, 4]\n 3 [1, 2, 3, 4] [1, 2, 4, 3]\n 1 [2, 1, 3, 4] [1, 2, 3, 4]\n 2 [2, 1, 3, 4] [2, 1, 3, 4]\n 3 [2, 1, 3, 4] [2, 1, 4, 3]\n 1 [2, 1, 4, 3] [1, 2, 4, 3]\n 2 [2, 1, 4, 3] [2, 1, 4, 3]\n 3 [2, 1, 4, 3] [2, 1, 3, 4]\n 1 [1, 4, 2, 3] [1, 4, 2, 3]\n 2 [1, 4, 2, 3] [1, 2, 4, 3]\n 3 [1, 4, 2, 3] [1, 4, 2, 3]\n 1 [1, 2, 4, 3] [2, 1, 4, 3]\n 2 [1, 2, 4, 3] [1, 4, 2, 3]\n 3 [1, 2, 4, 3] [1, 2, 3, 4]\n\n TESTS::\n\n sage: type(l.tau(1))\n <class \'sage.combinat.posets.linear_extensions.LinearExtensionsOfPoset_with_category.element_class\'>\n sage: l.tau(2) == l\n True\n '
P = self.poset()
a = self[(i - 1)]
b = self[i]
if (P.lt(a, b) or P.lt(b, a)):
return self
with self.clone() as q:
q[(i - 1)] = b
q[i] = a
return q
def promotion(self, i=1):
'\n Compute the (generalized) promotion on the linear extension of a poset.\n\n INPUT:\n\n - ``i`` -- (default: `1`) an integer between `1` and `n-1`,\n where `n` is the cardinality of the poset\n\n The `i`-th generalized promotion operator `\\partial_i` on a linear\n extension `\\pi` is defined as `\\pi \\tau_i \\tau_{i+1} \\cdots \\tau_{n-1}`,\n where `n` is the size of the linear extension (or size of the\n underlying poset).\n\n For more details see [Stan2009]_.\n\n .. SEEALSO:: :meth:`tau`, :meth:`evacuation`\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4,5,6,7], [[1,2],[1,4],[2,3],[2,5],[3,6],[4,7],[5,6]]))\n sage: p = P.linear_extension([1,2,3,4,5,6,7])\n sage: q = p.promotion(4); q\n [1, 2, 3, 5, 6, 4, 7]\n sage: p.to_poset() == q.to_poset()\n False\n sage: p.to_poset().is_isomorphic(q.to_poset())\n True\n '
for j in range(i, len(self)):
self = self.tau(j)
return self
def evacuation(self):
'\n Compute evacuation on the linear extension of a poset.\n\n Evacuation on a linear extension `\\pi` of length `n` is defined as\n `\\pi (\\tau_1 \\cdots \\tau_{n-1}) (\\tau_1 \\cdots \\tau_{n-2}) \\cdots (\\tau_1)`.\n For more details see [Stan2009]_.\n\n .. SEEALSO:: :meth:`tau`, :meth:`promotion`\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4,5,6,7], [[1,2],[1,4],[2,3],[2,5],[3,6],[4,7],[5,6]]))\n sage: p = P.linear_extension([1,2,3,4,5,6,7])\n sage: p.evacuation()\n [1, 4, 2, 3, 7, 5, 6]\n sage: p.evacuation().evacuation() == p\n True\n '
for i in reversed(range(1, (len(self) + 1))):
for j in range(1, i):
self = self.tau(j)
return self
def jump_count(self):
'\n Return the number of jumps in the linear extension.\n\n A *jump* in a linear extension `[e_1, e_2, \\ldots, e_n]`\n is a pair `(e_i, e_{i+1})` such that `e_{i+1}` does not\n cover `e_i`.\n\n .. SEEALSO::\n\n - :meth:`sage.combinat.posets.posets.FinitePoset.jump_number()`\n\n EXAMPLES::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: l1 = B3.linear_extension((0, 1, 2, 3, 4, 5, 6, 7))\n sage: l1.jump_count()\n 3\n sage: l2 = B3.linear_extension((0, 1, 2, 4, 3, 5, 6, 7))\n sage: l2.jump_count()\n 5\n\n TESTS::\n\n sage: E = Poset()\n sage: E.linear_extensions()[0].jump_count()\n 0\n sage: C4 = posets.ChainPoset(4)\n sage: C4.linear_extensions()[0].jump_count()\n 0\n sage: A4 = posets.AntichainPoset(4)\n sage: A4.linear_extensions()[0].jump_count()\n 3\n '
P = self.poset()
n = 0
for i in range((len(self) - 1)):
if (not P.covers(self[i], self[(i + 1)])):
n += 1
return n
|
class LinearExtensionsOfPoset(UniqueRepresentation, Parent):
'\n The set of all linear extensions of a finite poset\n\n INPUT:\n\n - ``poset`` -- a poset `P` of size `n`\n - ``facade`` -- a boolean (default: ``False``)\n\n .. SEEALSO::\n\n - :meth:`sage.combinat.posets.posets.FinitePoset.linear_extensions`\n\n EXAMPLES::\n\n sage: elms = [1,2,3,4]\n sage: rels = [[1,3],[1,4],[2,3]]\n sage: P = Poset((elms, rels), linear_extension=True)\n sage: L = P.linear_extensions(); L\n The set of all linear extensions of Finite poset containing 4 elements with distinguished linear extension\n sage: L.cardinality()\n 5\n sage: L.list() # optional - sage.modules sage.rings.finite_rings\n [[1, 2, 3, 4], [2, 1, 3, 4], [2, 1, 4, 3], [1, 4, 2, 3], [1, 2, 4, 3]]\n sage: L.an_element()\n [1, 2, 3, 4]\n sage: L.poset()\n Finite poset containing 4 elements with distinguished linear extension\n '
@staticmethod
def __classcall_private__(cls, poset, facade=False):
"\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: from sage.combinat.posets.linear_extensions import LinearExtensionsOfPoset\n sage: P = Poset(([1,2],[[1,2]]))\n sage: L = LinearExtensionsOfPoset(P)\n sage: type(L)\n <class 'sage.combinat.posets.linear_extensions.LinearExtensionsOfPoset_with_category'>\n sage: L is LinearExtensionsOfPoset(P,facade=False)\n True\n "
return super().__classcall__(cls, poset, facade=facade)
def __init__(self, poset, facade):
'\n TESTS::\n\n sage: from sage.combinat.posets.linear_extensions import LinearExtensionsOfPoset\n sage: P = Poset(([1,2,3],[[1,2],[1,3]]))\n sage: L = P.linear_extensions()\n sage: L is LinearExtensionsOfPoset(P)\n True\n sage: L._poset is P\n True\n sage: TestSuite(L).run()\n\n sage: P = Poset((divisors(15), attrcall("divides")))\n sage: L = P.linear_extensions()\n sage: TestSuite(L).run()\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade=True)\n sage: L = P.linear_extensions()\n sage: TestSuite(L).run()\n\n sage: L = P.linear_extensions(facade = True)\n sage: TestSuite(L).run(skip="_test_an_element")\n '
self._poset = poset
self._is_facade = facade
if facade:
facade = (list,)
Parent.__init__(self, category=FiniteEnumeratedSets(), facade=facade)
def _repr_(self):
'\n TESTS::\n\n sage: P = Poset(([1,2,3],[[1,2],[1,3]]))\n sage: P.linear_extensions()\n The set of all linear extensions of Finite poset containing 3 elements\n '
return ('The set of all linear extensions of %s' % self._poset)
def poset(self):
'\n Return the underlying original poset.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,2],[2,3],[1,4]]))\n sage: L = P.linear_extensions()\n sage: L.poset()\n Finite poset containing 4 elements\n '
return self._poset
def cardinality(self):
'\n Return the number of linear extensions.\n\n EXAMPLES::\n\n sage: N = Poset({0: [2, 3], 1: [3]})\n sage: N.linear_extensions().cardinality()\n 5\n\n TESTS::\n\n sage: Poset().linear_extensions().cardinality()\n 1\n sage: posets.ChainPoset(1).linear_extensions().cardinality()\n 1\n sage: posets.BooleanLattice(4).linear_extensions().cardinality()\n 1680384\n '
from sage.rings.integer import Integer
n = len(self._poset)
if (not n):
return Integer(1)
up = self._poset._hasse_diagram.to_dictionary()
for i in range(n):
up[((n - 1) - i)] = sorted(set((up[((n - 1) - i)] + [item for x in up[((n - 1) - i)] for item in up[x]])))
Jup = {1: []}
loc = ([1] * n)
m = 1
for x in range(n):
K = [[loc[x]]]
j = 0
while K[j]:
K.append([b for a in K[j] for b in Jup[a]])
j += 1
K = sorted(set((item for sublist in K for item in sublist)))
for j in range(len(K)):
i = ((m + j) + 1)
Jup[i] = [((m + K.index(a)) + 1) for a in Jup[K[j]]]
Jup[K[j]] = (Jup[K[j]] + [i])
for y in up[x]:
loc[y] = ((K.index(loc[y]) + m) + 1)
m += len(K)
Jup[m] = Integer(1)
while (m > 1):
m -= 1
ct = Integer(0)
for j in Jup[m]:
ct += Jup[j]
Jup[m] = ct
return ct
def __iter__(self):
'\n Iterates through the linear extensions of the underlying poset.\n\n EXAMPLES::\n\n sage: elms = [1,2,3,4]\n sage: rels = [[1,3],[1,4],[2,3]]\n sage: P = Poset((elms, rels), linear_extension=True)\n sage: L = P.linear_extensions()\n sage: list(L) # optional - sage.modules sage.rings.finite_rings\n [[1, 2, 3, 4], [2, 1, 3, 4], [2, 1, 4, 3], [1, 4, 2, 3], [1, 2, 4, 3]]\n '
from sage.combinat.posets.linear_extension_iterator import linear_extension_iterator
vertex_to_element = self._poset._vertex_to_element
for lin_ext in linear_extension_iterator(self._poset._hasse_diagram):
(yield self._element_constructor_([vertex_to_element(_) for _ in lin_ext]))
def __contains__(self, obj):
'\n Membership testing\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True, linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: L = P.linear_extensions()\n sage: L([1, 2, 4, 3, 6, 12]) in L\n True\n sage: [1, 2, 4, 3, 6, 12] in L\n False\n\n sage: L = P.linear_extensions(facade=True)\n sage: [1, 2, 4, 3, 6, 12] in L\n True\n sage: [1, 3, 2, 6, 4, 12] in L\n True\n sage: [1, 3, 6, 2, 4, 12] in L\n False\n\n sage: [p for p in Permutations(list(P)) if list(p) in L]\n [[1, 2, 3, 4, 6, 12], [1, 2, 3, 6, 4, 12], [1, 2, 4, 3, 6, 12], [1, 3, 2, 4, 6, 12], [1, 3, 2, 6, 4, 12]]\n\n '
if (not self._is_facade):
return super().__contains__(obj)
return (isinstance(obj, (list, tuple)) and self.poset().is_linear_extension(obj))
def markov_chain_digraph(self, action='promotion', labeling='identity'):
"\n Return the digraph of the action of generalized promotion or tau on ``self``\n\n INPUT:\n\n - ``action`` -- 'promotion' or 'tau' (default: 'promotion')\n - ``labeling`` -- 'identity' or 'source' (default: 'identity')\n\n .. TODO::\n\n - generalize this feature by accepting a family of operators as input\n - move up in some appropriate category\n\n This method creates a graph with vertices being the linear extensions of a given finite\n poset and an edge from `\\pi` to `\\pi'` if `\\pi' = \\pi \\partial_i` where `\\partial_i` is\n the promotion operator (see :meth:`promotion`) if ``action`` is set to ``promotion``\n and `\\tau_i` (see :meth:`tau`) if ``action`` is set to ``tau``. The label of the edge\n is `i` (resp. `\\pi_i`) if ``labeling`` is set to ``identity`` (resp. ``source``).\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]), linear_extension = True)\n sage: L = P.linear_extensions()\n sage: G = L.markov_chain_digraph(); G\n Looped multi-digraph on 5 vertices\n sage: G.vertices(sort=True, key=repr)\n [[1, 2, 3, 4], [1, 2, 4, 3], [1, 4, 2, 3], [2, 1, 3, 4], [2, 1, 4, 3]]\n sage: G.edges(sort=True, key=repr)\n [([1, 2, 3, 4], [1, 2, 3, 4], 4), ([1, 2, 3, 4], [1, 2, 4, 3], 2), ([1, 2, 3, 4], [1, 2, 4, 3], 3),\n ([1, 2, 3, 4], [2, 1, 4, 3], 1), ([1, 2, 4, 3], [1, 2, 3, 4], 3), ([1, 2, 4, 3], [1, 2, 4, 3], 4),\n ([1, 2, 4, 3], [1, 4, 2, 3], 2), ([1, 2, 4, 3], [2, 1, 3, 4], 1), ([1, 4, 2, 3], [1, 2, 3, 4], 1),\n ([1, 4, 2, 3], [1, 2, 3, 4], 2), ([1, 4, 2, 3], [1, 4, 2, 3], 3), ([1, 4, 2, 3], [1, 4, 2, 3], 4),\n ([2, 1, 3, 4], [1, 2, 4, 3], 1), ([2, 1, 3, 4], [2, 1, 3, 4], 4), ([2, 1, 3, 4], [2, 1, 4, 3], 2),\n ([2, 1, 3, 4], [2, 1, 4, 3], 3), ([2, 1, 4, 3], [1, 4, 2, 3], 1), ([2, 1, 4, 3], [2, 1, 3, 4], 2),\n ([2, 1, 4, 3], [2, 1, 3, 4], 3), ([2, 1, 4, 3], [2, 1, 4, 3], 4)]\n\n sage: G = L.markov_chain_digraph(labeling = 'source')\n sage: G.vertices(sort=True, key=repr)\n [[1, 2, 3, 4], [1, 2, 4, 3], [1, 4, 2, 3], [2, 1, 3, 4], [2, 1, 4, 3]]\n sage: G.edges(sort=True, key=repr)\n [([1, 2, 3, 4], [1, 2, 3, 4], 4), ([1, 2, 3, 4], [1, 2, 4, 3], 2), ([1, 2, 3, 4], [1, 2, 4, 3], 3),\n ([1, 2, 3, 4], [2, 1, 4, 3], 1), ([1, 2, 4, 3], [1, 2, 3, 4], 4), ([1, 2, 4, 3], [1, 2, 4, 3], 3),\n ([1, 2, 4, 3], [1, 4, 2, 3], 2), ([1, 2, 4, 3], [2, 1, 3, 4], 1), ([1, 4, 2, 3], [1, 2, 3, 4], 1),\n ([1, 4, 2, 3], [1, 2, 3, 4], 4), ([1, 4, 2, 3], [1, 4, 2, 3], 2), ([1, 4, 2, 3], [1, 4, 2, 3], 3),\n ([2, 1, 3, 4], [1, 2, 4, 3], 2), ([2, 1, 3, 4], [2, 1, 3, 4], 4), ([2, 1, 3, 4], [2, 1, 4, 3], 1),\n ([2, 1, 3, 4], [2, 1, 4, 3], 3), ([2, 1, 4, 3], [1, 4, 2, 3], 2), ([2, 1, 4, 3], [2, 1, 3, 4], 1),\n ([2, 1, 4, 3], [2, 1, 3, 4], 4), ([2, 1, 4, 3], [2, 1, 4, 3], 3)]\n\n The edges of the graph are by default colored using blue for\n edge 1, red for edge 2, green for edge 3, and yellow for edge 4::\n\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n Alternatively, one may get the graph of the action of the ``tau`` operator::\n\n sage: G = L.markov_chain_digraph(action='tau'); G\n Looped multi-digraph on 5 vertices\n sage: G.vertices(sort=True, key=repr)\n [[1, 2, 3, 4], [1, 2, 4, 3], [1, 4, 2, 3], [2, 1, 3, 4], [2, 1, 4, 3]]\n sage: G.edges(sort=True, key=repr)\n [([1, 2, 3, 4], [1, 2, 3, 4], 2), ([1, 2, 3, 4], [1, 2, 4, 3], 3), ([1, 2, 3, 4], [2, 1, 3, 4], 1),\n ([1, 2, 4, 3], [1, 2, 3, 4], 3), ([1, 2, 4, 3], [1, 4, 2, 3], 2), ([1, 2, 4, 3], [2, 1, 4, 3], 1),\n ([1, 4, 2, 3], [1, 2, 4, 3], 2), ([1, 4, 2, 3], [1, 4, 2, 3], 1), ([1, 4, 2, 3], [1, 4, 2, 3], 3),\n ([2, 1, 3, 4], [1, 2, 3, 4], 1), ([2, 1, 3, 4], [2, 1, 3, 4], 2), ([2, 1, 3, 4], [2, 1, 4, 3], 3),\n ([2, 1, 4, 3], [1, 2, 4, 3], 1), ([2, 1, 4, 3], [2, 1, 3, 4], 3), ([2, 1, 4, 3], [2, 1, 4, 3], 2)]\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n\n .. SEEALSO:: :meth:`markov_chain_transition_matrix`, :meth:`promotion`, :meth:`tau`\n\n TESTS::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]), linear_extension = True, facade = True)\n sage: L = P.linear_extensions()\n sage: G = L.markov_chain_digraph(labeling = 'source'); G\n Looped multi-digraph on 5 vertices\n "
L = sorted(self)
d = {x: {y: [] for y in L} for x in L}
if (action == 'promotion'):
R = list(range(self.poset().cardinality()))
else:
R = list(range((self.poset().cardinality() - 1)))
if (labeling == 'source'):
for x in L:
for i in R:
child = getattr(x, action)((i + 1))
d[x][child] += [self.poset().unwrap(x[i])]
else:
for x in L:
for i in R:
child = getattr(x, action)((i + 1))
d[x][child] += [(i + 1)]
G = DiGraph(d, format='dict_of_dicts')
if have_dot2tex():
G.set_latex_options(format='dot2tex', edge_labels=True, color_by_label={1: 'blue', 2: 'red', 3: 'green', 4: 'yellow'})
return G
def markov_chain_transition_matrix(self, action='promotion', labeling='identity'):
"\n Return the transition matrix of the Markov chain for the action of generalized promotion or tau on ``self``\n\n INPUT:\n\n - ``action`` -- 'promotion' or 'tau' (default: 'promotion')\n - ``labeling`` -- 'identity' or 'source' (default: 'identity')\n\n This method yields the transition matrix of the Markov chain defined by the action of the generalized\n promotion operator `\\partial_i` (resp. `\\tau_i`) on the set of linear extensions of a finite poset.\n Here the transition from the linear extension `\\pi` to `\\pi'`, where `\\pi' = \\pi \\partial_i`\n (resp. `\\pi'= \\pi \\tau_i`) is counted with weight `x_i` (resp. `x_{\\pi_i}` if ``labeling`` is set to ``source``).\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4], [[1,3],[1,4],[2,3]]), linear_extension = True)\n sage: L = P.linear_extensions()\n sage: L.markov_chain_transition_matrix() # optional - sage.modules\n [-x0 - x1 - x2 x2 x0 + x1 0 0]\n [ x1 + x2 -x0 - x1 - x2 0 x0 0]\n [ 0 x1 -x0 - x1 0 x0]\n [ 0 x0 0 -x0 - x1 - x2 x1 + x2]\n [ x0 0 0 x1 + x2 -x0 - x1 - x2]\n\n sage: L.markov_chain_transition_matrix(labeling='source') # optional - sage.modules\n [-x0 - x1 - x2 x3 x0 + x3 0 0]\n [ x1 + x2 -x0 - x1 - x3 0 x1 0]\n [ 0 x1 -x0 - x3 0 x1]\n [ 0 x0 0 -x0 - x1 - x2 x0 + x3]\n [ x0 0 0 x0 + x2 -x0 - x1 - x3]\n\n sage: L.markov_chain_transition_matrix(action='tau') # optional - sage.modules\n [ -x0 - x2 x2 0 x0 0]\n [ x2 -x0 - x1 - x2 x1 0 x0]\n [ 0 x1 -x1 0 0]\n [ x0 0 0 -x0 - x2 x2]\n [ 0 x0 0 x2 -x0 - x2]\n\n sage: L.markov_chain_transition_matrix(action='tau', labeling='source') # optional - sage.modules\n [ -x0 - x2 x3 0 x1 0]\n [ x2 -x0 - x1 - x3 x3 0 x1]\n [ 0 x1 -x3 0 0]\n [ x0 0 0 -x1 - x2 x3]\n [ 0 x0 0 x2 -x1 - x3]\n\n .. SEEALSO:: :meth:`markov_chain_digraph`, :meth:`promotion`, :meth:`tau`\n\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.matrix.constructor import matrix
L = sorted(self.list())
n = self.poset().cardinality()
R = PolynomialRing(QQ, 'x', n)
x = [R.gen(i) for i in range(n)]
l = self.cardinality()
M = {(i, j): 0 for i in range(l) for j in range(l)}
if (labeling == 'source'):
for i in range(l):
perm = [self.poset().unwrap(k) for k in L[i]]
for j in range((n - 1)):
p = getattr(L[i], action)((j + 1))
M[(L.index(p), i)] += x[(perm[j] - 1)]
else:
for i in range(l):
for j in range((n - 1)):
p = getattr(L[i], action)((j + 1))
M[(L.index(p), i)] += x[j]
for i in range(l):
M[(i, i)] += (- sum((M[(j, i)] for j in range(l))))
return matrix(l, l, (lambda x, y: M[(x, y)]))
def _element_constructor_(self, lst, check=True):
'\n Constructor for elements of this class.\n\n TESTS::\n\n sage: P = Poset(([1,2,3,4], [[1,2],[1,4],[2,3]]))\n sage: L = P.linear_extensions()\n sage: x = L._element_constructor_([1,2,4,3]); x\n [1, 2, 4, 3]\n sage: x.parent() is L\n True\n\n sage: L._element_constructor_([4,3,2,1])\n Traceback (most recent call last):\n ...\n ValueError: [4, 3, 2, 1] is not a linear extension of Finite poset containing 4 elements\n sage: L._element_constructor_([4,3,2,1],check=False)\n [4, 3, 2, 1]\n '
if isinstance(lst, LinearExtensionOfPoset):
lst = list(lst)
if (not isinstance(lst, (list, tuple))):
raise TypeError('input should be a list or tuple')
lst = [self._poset(_) for _ in lst]
if self._is_facade:
return lst
else:
return self.element_class(self, lst, check)
Element = LinearExtensionOfPoset
|
class LinearExtensionsOfPosetWithHooks(LinearExtensionsOfPoset):
'\n Linear extensions such that the poset has well-defined\n hook lengths (i.e., d-complete).\n '
def cardinality(self):
'\n Count the number of linear extensions using a hook-length formula.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: P = Posets.YoungDiagramPoset(Partition([3,2]), dual=True) # optional - sage.combinat\n sage: P.linear_extensions().cardinality() # optional - sage.combinat sage.modules\n 5\n '
num_elmts = self._poset.cardinality()
if (num_elmts == 0):
return 1
hook_product = self._poset.hook_product()
return (factorial(num_elmts) // hook_product)
|
class LinearExtensionsOfForest(LinearExtensionsOfPoset):
'\n Linear extensions such that the poset is a forest.\n '
def cardinality(self):
"\n Use Atkinson's algorithm to compute the number of linear extensions.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.forest import ForestPoset\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: P = Poset({0: [2], 1: [2], 2: [3, 4], 3: [], 4: []})\n sage: P.linear_extensions().cardinality() # optional - sage.modules\n 4\n\n sage: Q = Poset({0: [1], 1: [2, 3], 2: [], 3: [], 4: [5, 6], 5: [], 6: []})\n sage: Q.linear_extensions().cardinality() # optional - sage.modules\n 140\n "
return sum(self.atkinson(self._elements[0]))
|
class LinearExtensionsOfMobile(LinearExtensionsOfPoset):
'\n Linear extensions for a mobile poset.\n '
def cardinality(self):
'\n Return the number of linear extensions by using the determinant\n formula for counting linear extensions of mobiles.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.mobile import MobilePoset\n sage: M = MobilePoset(DiGraph([[0,1,2,3,4,5,6,7,8], [(1,0),(3,0),(2,1),(2,3),(4,\n ....: 3), (5,4),(5,6),(7,4),(7,8)]]))\n sage: M.linear_extensions().cardinality() # optional - sage.modules\n 1098\n\n sage: M1 = posets.RibbonPoset(6, [1,3])\n sage: M1.linear_extensions().cardinality() # optional - sage.modules\n 61\n\n sage: P = posets.MobilePoset(posets.RibbonPoset(7, [1,3]), # optional - sage.combinat\n ....: {1: [posets.YoungDiagramPoset([3, 2], dual=True)],\n ....: 3: [posets.DoubleTailedDiamond(6)]},\n ....: anchor=(4, 2, posets.ChainPoset(6)))\n sage: P.linear_extensions().cardinality() # optional - sage.combinat sage.modules\n 361628701868606400\n '
import sage.combinat.posets.d_complete as dc
if self._poset._anchor:
anchor_index = self._poset._ribbon.index(self._poset._anchor[0])
else:
anchor_index = len(self._poset._ribbon)
folds_up = []
folds_down = []
for (ind, r) in enumerate(self._poset._ribbon[:(- 1)]):
if ((ind < anchor_index) and self._poset.is_greater_than(r, self._poset._ribbon[(ind + 1)])):
folds_up.append((self._poset._ribbon[(ind + 1)], r))
elif ((ind >= anchor_index) and self._poset.is_less_than(r, self._poset._ribbon[(ind + 1)])):
folds_down.append((r, self._poset._ribbon[(ind + 1)]))
if ((not folds_up) and (not folds_down)):
return dc.DCompletePoset(self._poset).linear_extensions().cardinality()
cr = self._poset.cover_relations()
foldless_cr = [tuple(c) for c in cr if ((tuple(c) not in folds_up) and (tuple(c) not in folds_down))]
elmts = list(self._poset._elements)
poset_components = DiGraph([elmts, foldless_cr])
ordered_poset_components = [poset_components.connected_component_containing_vertex(f[1], sort=False) for f in folds_up]
ordered_poset_components.extend((poset_components.connected_component_containing_vertex(f[0], sort=False) for f in folds_down))
ordered_poset_components.append(poset_components.connected_component_containing_vertex((folds_down[(- 1)][1] if folds_down else folds_up[(- 1)][0]), sort=False))
folds = folds_up
folds.extend(folds_down)
mat = []
for i in range((len(folds) + 1)):
mat_poset = dc.DCompletePoset(self._poset.subposet(ordered_poset_components[i]))
row = (([0] * ((i - 1) if ((i - 1) > 0) else 0)) + ([1] * (1 if (i >= 1) else 0)))
row.append((1 / mat_poset.hook_product()))
for (j, f) in enumerate(folds[i:]):
next_poset = self._poset.subposet(ordered_poset_components[((j + i) + 1)])
mat_poset = dc.DCompletePoset(next_poset.slant_sum(mat_poset, f[0], f[1]))
row.append((1 / mat_poset.hook_product()))
mat.append(row)
return (matrix(QQ, mat).determinant() * factorial(self._poset.cardinality()))
|
class MobilePoset(FinitePoset):
"\n A mobile poset.\n\n Mobile posets are an extension of d-complete posets which permit a determinant\n formula for counting linear extensions. They are formed by having a ribbon\n poset with d-complete posets 'hanging' below it and at most one\n d-complete poset above it, known as the anchor. See [GGMM2020]_\n for the definition.\n\n EXAMPLES::\n\n sage: P = posets.MobilePoset(posets.RibbonPoset(7, [1,3]), # optional - sage.combinat\n ....: {1: [posets.YoungDiagramPoset([3, 2], dual=True)],\n ....: 3: [posets.DoubleTailedDiamond(6)]},\n ....: anchor=(4, 2, posets.ChainPoset(6)))\n sage: len(P._ribbon) # optional - sage.combinat\n 8\n sage: P._anchor # optional - sage.combinat\n (4, 5)\n\n This example is Example 5.9 in [GGMM2020]_::\n\n sage: P1 = posets.MobilePoset(posets.RibbonPoset(8, [2,3,4]),\n ....: {4: [posets.ChainPoset(1)]},\n ....: anchor=(3, 0, posets.ChainPoset(1)))\n sage: sorted([P1._element_to_vertex(i) for i in P1._ribbon])\n [0, 1, 2, 6, 7, 9]\n sage: P1._anchor\n (3, 2)\n\n sage: P2 = posets.MobilePoset(posets.RibbonPoset(15, [1,3,5,7,9,11,13]),\n ....: {}, anchor=(8, 0, posets.ChainPoset(1)))\n sage: sorted(P2._ribbon)\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n sage: P2._anchor\n (8, (8, 0))\n sage: P2.linear_extensions().cardinality() # optional - sage.modules\n 21399440939\n\n sage: EP = posets.MobilePoset(posets.ChainPoset(0), {})\n Traceback (most recent call last):\n ...\n ValueError: the empty poset is not a mobile poset\n "
_lin_ext_type = LinearExtensionsOfMobile
_desc = 'Finite mobile poset'
def __init__(self, hasse_diagram, elements, category, facade, key, ribbon=None, check=True):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = posets.MobilePoset(posets.RibbonPoset(15, [1,3,5,7,9,11,13]),\n ....: {}, anchor=(8, 0, posets.ChainPoset(1)))\n sage: TestSuite(P).run()\n '
FinitePoset.__init__(self, hasse_diagram=hasse_diagram, elements=elements, category=category, facade=facade, key=key)
if (not self._hasse_diagram):
raise ValueError('the empty poset is not a mobile poset')
if ribbon:
if (check and (not self._is_valid_ribbon(ribbon))):
raise ValueError('invalid ribbon')
self._ribbon = ribbon
def _is_valid_ribbon(self, ribbon):
'\n Return ``True`` if a ribbon has at most one anchor, no vertex has two\n or more anchors, and every hanging poset is d-complete.\n\n INPUT:\n\n - ``ribbon`` -- a list of elements that form a ribbon in your poset\n\n TESTS::\n\n sage: P = posets.RibbonPoset(5, [2])\n sage: P._is_valid_ribbon([0,1,2,3,4])\n True\n sage: P._is_valid_ribbon([2])\n False\n sage: P._is_valid_ribbon([2,3,4])\n True\n sage: P._is_valid_ribbon([2,3])\n True\n '
ribbon = [self._element_to_vertex(x) for x in ribbon]
G = self._hasse_diagram
G_un = G.to_undirected().copy(immutable=False)
R = G.subgraph(ribbon)
num_anchors = 0
for r in ribbon:
anchor_neighbors = set(G.neighbor_out_iterator(r)).difference(set(R.neighbor_out_iterator(r)))
if (len(anchor_neighbors) == 1):
num_anchors += 1
elif (len(anchor_neighbors) > 1):
return False
for lc in G.neighbor_in_iterator(r):
if (lc in ribbon):
continue
G_un.delete_edge(lc, r)
P = Poset(G.subgraph(G_un.connected_component_containing_vertex(lc, sort=False)))
if ((P.top() != lc) or (not P.is_d_complete())):
return False
G_un.add_edge(lc, r)
return True
@lazy_attribute
def _anchor(self):
'\n The anchor of the mobile poset.\n\n TESTS::\n\n sage: from sage.combinat.posets.mobile import MobilePoset\n sage: M = MobilePoset(DiGraph([[0,1,2,3,4,5,6,7,8],\n ....: [(1,0),(3,0),(2,1),(2,3),(4,3), (5,4),(5,6),(7,4),(7,8)]]))\n sage: M._anchor\n (4, 3)\n '
ribbon = [self._element_to_vertex(x) for x in self._ribbon]
H = self._hasse_diagram
R = H.subgraph(ribbon)
anchor = None
for r in ribbon:
anchor_neighbors = set(H.neighbor_out_iterator(r)).difference(set(R.neighbor_out_iterator(r)))
if (len(anchor_neighbors) == 1):
anchor = (r, anchor_neighbors.pop())
break
return ((self._vertex_to_element(anchor[0]), self._vertex_to_element(anchor[1])) if (anchor is not None) else None)
@lazy_attribute
def _ribbon(self):
'\n The ribbon of the mobile poset.\n\n TESTS::\n\n sage: from sage.combinat.posets.mobile import MobilePoset\n sage: M = MobilePoset(DiGraph([[0,1,2,3,4,5,6,7,8],\n ....: [(1,0),(3,0),(2,1),(2,3),(4,3), (5,4),(5,6),(7,4),(7,8)]]))\n sage: sorted(M._ribbon)\n [4, 5, 6, 7, 8]\n sage: M._is_valid_ribbon(M._ribbon)\n True\n sage: M2 = MobilePoset(Poset([[0,1,2,3,4,5,6,7,8],\n ....: [(1,0),(3,0),(2,1),(2,3),(4,3),(5,4),(7,4),(7,8)]]))\n sage: sorted(M2._ribbon)\n [4, 7, 8]\n sage: M2._is_valid_ribbon(M2._ribbon)\n True\n '
H = self._hasse_diagram
H_un = H.to_undirected()
max_elmts = H.sinks()
ribbon = []
if (len(max_elmts) == 1):
return [self._vertex_to_element(max_elmts[0])]
start = max_elmts[0]
zigzag_elmts = set()
for m in max_elmts[1:]:
sp = H_un.shortest_path(start, m)
zigzag_elmts.update(sp)
max_elmt_graph = H.subgraph(zigzag_elmts)
G = max_elmt_graph.to_undirected()
if G.is_path():
ends = max_elmt_graph.vertices(sort=True, degree=1)
ribbon = G.shortest_path(ends[0], ends[1])
for (end_count, end) in enumerate(ends):
if (not (H_un.is_cut_vertex(end) or (H_un.degree(end) == 1))):
traverse_ribbon = (ribbon if (end_count == 0) else ribbon[::(- 1)])
for (ind, p) in enumerate(traverse_ribbon):
if H_un.is_cut_edge(p, traverse_ribbon[(ind + 1)]):
return [self._vertex_to_element(r) for r in G.shortest_path(ends[((end_count + 1) % 2)], traverse_ribbon[(ind + 1)])]
return [self._vertex_to_element(r) for r in ribbon]
ends = max_elmt_graph.vertices(sort=True, degree=1)
deg3 = max_elmt_graph.vertices(sort=True, degree=3)[0]
anchoredEnd = None
for end in ends:
if (not (H_un.is_cut_vertex(end) or (H_un.degree(end) == 1))):
anchoredEnd = end
break
if (anchoredEnd is not None):
ends.remove(anchoredEnd)
return [self._vertex_to_element(r) for r in G.shortest_path(ends[0], ends[1])]
possible_anchors = ends[:]
for end in ends:
path = G.shortest_path(end, deg3)
if (sum((bool((z in max_elmts)) for z in path)) != 1):
possible_anchors.remove(end)
for p in possible_anchors:
path = G.shortest_path(p, deg3)
if max_elmt_graph.has_edge(path[(- 2)], path[(- 1)]):
possible_anchors.remove(p)
anchoredEnd = possible_anchors[0]
ends.remove(anchoredEnd)
return [self._vertex_to_element(r) for r in G.shortest_path(ends[0], ends[1])]
def ribbon(self):
'\n Return the ribbon of the mobile poset.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.mobile import MobilePoset\n sage: M3 = MobilePoset(Posets.RibbonPoset(5, [1,2]))\n sage: sorted(M3.ribbon())\n [1, 2, 3, 4]\n '
return self._ribbon
def anchor(self):
'\n Return the anchor of the mobile poset.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.mobile import MobilePoset\n sage: M2 = MobilePoset(Poset([[0,1,2,3,4,5,6,7,8],\n ....: [(1,0),(3,0),(2,1),(2,3),(4,3),(5,4),(7,4),(7,8)]]))\n sage: M2.anchor()\n (4, 3)\n sage: M3 = MobilePoset(Posets.RibbonPoset(5, [1,2]))\n sage: M3.anchor() is None\n True\n '
return self._anchor
|
class BasisAbstract(CombinatorialFreeModule, BindableClass):
'\n Abstract base class for a basis.\n '
def __getitem__(self, x):
'\n Return the basis element indexed by ``x``.\n\n INPUT:\n\n - ``x`` -- an element of the lattice\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: E = L.moebius_algebra(QQ).E()\n sage: E[5]\n E[5]\n sage: C = L.quantum_moebius_algebra().C()\n sage: C[5]\n C[5]\n '
L = self.realization_of()._lattice
return self.monomial(L(x))
|
class MoebiusAlgebra(Parent, UniqueRepresentation):
'\n The Möbius algebra of a lattice.\n\n Let `L` be a lattice. The *Möbius algebra* `M_L` was originally\n constructed by Solomon [Solomon67]_ and has a natural basis\n `\\{ E_x \\mid x \\in L \\}` with multiplication given by\n `E_x \\cdot E_y = E_{x \\vee y}`. Moreover this has a basis given by\n orthogonal idempotents `\\{ I_x \\mid x \\in L \\}` (so\n `I_x I_y = \\delta_{xy} I_x` where `\\delta` is the Kronecker delta)\n related to the natural basis by\n\n .. MATH::\n\n I_x = \\sum_{x \\leq y} \\mu_L(x, y) E_y,\n\n where `\\mu_L` is the Möbius function of `L`.\n\n .. NOTE::\n\n We use the join `\\vee` for our multiplication, whereas [Greene73]_\n and [Etienne98]_ define the Möbius algebra using the meet `\\wedge`.\n This is done for compatibility with :class:`QuantumMoebiusAlgebra`.\n\n REFERENCES:\n\n .. [Solomon67] Louis Solomon.\n *The Burnside Algebra of a Finite Group*.\n Journal of Combinatorial Theory, **2**, 1967.\n :doi:`10.1016/S0021-9800(67)80064-4`.\n\n .. [Greene73] Curtis Greene.\n *On the Möbius algebra of a partially ordered set*.\n Advances in Mathematics, **10**, 1973.\n :doi:`10.1016/0001-8708(73)90106-0`.\n\n .. [Etienne98] Gwihen Etienne.\n *On the Möbius algebra of geometric lattices*.\n European Journal of Combinatorics, **19**, 1998.\n :doi:`10.1006/eujc.1998.0227`.\n '
def __init__(self, R, L):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(3)\n sage: M = L.moebius_algebra(QQ)\n sage: TestSuite(M).run()\n '
cat = Algebras(R).Commutative().WithBasis()
if (L in FiniteEnumeratedSets()):
cat = cat.FiniteDimensional()
self._lattice = L
self._category = cat
Parent.__init__(self, base=R, category=self._category.WithRealizations())
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: L.moebius_algebra(QQ)\n Moebius algebra of Finite lattice containing 16 elements over Rational Field\n '
return 'Moebius algebra of {} over {}'.format(self._lattice, self.base_ring())
def a_realization(self):
'\n Return a particular realization of ``self`` (the `B`-basis).\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.moebius_algebra(QQ)\n sage: M.a_realization()\n Moebius algebra of Finite lattice containing 16 elements\n over Rational Field in the natural basis\n '
return self.E()
def lattice(self):
'\n Return the defining lattice of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.moebius_algebra(QQ)\n sage: M.lattice()\n Finite lattice containing 16 elements\n sage: M.lattice() == L\n True\n '
return self._lattice
class E(BasisAbstract):
'\n The natural basis of a Möbius algebra.\n\n Let `E_x` and `E_y` be basis elements of `M_L` for some lattice `L`.\n Multiplication is given by `E_x E_y = E_{x \\vee y}`.\n '
def __init__(self, M, prefix='E'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.moebius_algebra(QQ)\n sage: TestSuite(M.E()).run()\n '
self._basis_name = 'natural'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
@cached_method
def _to_idempotent_basis(self, x):
'\n Convert the element indexed by ``x`` to the idempotent basis.\n\n EXAMPLES::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: E = M.E()\n sage: all(E(E._to_idempotent_basis(x)) == E.monomial(x)\n ....: for x in E.basis().keys())\n True\n '
M = self.realization_of()
I = M.idempotent()
return I.sum_of_monomials(M._lattice.order_filter([x]))
def product_on_basis(self, x, y):
'\n Return the product of basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: E = L.moebius_algebra(QQ).E()\n sage: E.product_on_basis(5, 14)\n E[15]\n sage: E.product_on_basis(2, 8)\n E[10]\n\n TESTS::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: E = M.E()\n sage: I = M.I()\n sage: all(I(x)*I(y) == I(x*y) for x in E.basis() for y in E.basis())\n True\n '
return self.monomial(self.realization_of()._lattice.join(x, y))
@cached_method
def one(self):
'\n Return the element ``1`` of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: E = L.moebius_algebra(QQ).E()\n sage: E.one()\n E[0]\n '
elts = self.realization_of()._lattice.minimal_elements()
return self.sum_of_monomials(elts)
natural = E
class I(BasisAbstract):
'\n The (orthogonal) idempotent basis of a Möbius algebra.\n\n Let `I_x` and `I_y` be basis elements of `M_L` for some lattice `L`.\n Multiplication is given by `I_x I_y = \\delta_{xy} I_x` where\n `\\delta_{xy}` is the Kronecker delta.\n '
def __init__(self, M, prefix='I'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.moebius_algebra(QQ)\n sage: TestSuite(M.I()).run()\n\n Check that the transition maps can be pickled::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.moebius_algebra(QQ)\n sage: E = M.E()\n sage: I = M.I()\n sage: phi = E.coerce_map_from(I)\n sage: loads(dumps(phi))\n Generic morphism:\n ...\n '
self._basis_name = 'idempotent'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
E = M.E()
self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice._element_to_vertex).register_as_coercion()
E.module_morphism(E._to_idempotent_basis, codomain=self, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice._element_to_vertex).register_as_coercion()
@cached_method
def _to_natural_basis(self, x):
'\n Convert the element indexed by ``x`` to the natural basis.\n\n EXAMPLES::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: I = M.I()\n sage: all(I(I._to_natural_basis(x)) == I.monomial(x)\n ....: for x in I.basis().keys())\n True\n '
M = self.realization_of()
N = M.natural()
moebius = M._lattice.moebius_function
return N.sum_of_terms(((y, moebius(x, y)) for y in M._lattice.order_filter([x])))
def product_on_basis(self, x, y):
'\n Return the product of basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: I = L.moebius_algebra(QQ).I()\n sage: I.product_on_basis(5, 14)\n 0\n sage: I.product_on_basis(2, 2)\n I[2]\n\n TESTS::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: E = M.E()\n sage: I = M.I()\n sage: all(E(x)*E(y) == E(x*y) for x in I.basis() for y in I.basis())\n True\n '
if (x == y):
return self.monomial(x)
return self.zero()
@cached_method
def one(self):
'\n Return the element ``1`` of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: I = L.moebius_algebra(QQ).I()\n sage: I.one()\n I[0] + I[1] + I[2] + I[3] + I[4] + I[5] + I[6] + I[7] + I[8]\n + I[9] + I[10] + I[11] + I[12] + I[13] + I[14] + I[15]\n '
return self.sum_of_monomials(self.realization_of()._lattice)
def __getitem__(self, x):
'\n Return the basis element indexed by ``x``.\n\n INPUT:\n\n - ``x`` -- an element of the lattice\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: I = L.moebius_algebra(QQ).I()\n sage: I[5]\n I[5]\n '
L = self.realization_of()._lattice
return self.monomial(L(x))
idempotent = I
|
class QuantumMoebiusAlgebra(Parent, UniqueRepresentation):
'\n The quantum Möbius algebra of a lattice.\n\n Let `L` be a lattice, and we define the *quantum Möbius algebra* `M_L(q)`\n as the algebra with basis `\\{ E_x \\mid x \\in L \\}` with\n multiplication given by\n\n .. MATH::\n\n E_x E_y = \\sum_{z \\geq a \\geq x \\vee y} \\mu_L(a, z)\n q^{\\operatorname{crk} a} E_z,\n\n where `\\mu_L` is the Möbius function of `L` and `\\operatorname{crk}`\n is the corank function (i.e., `\\operatorname{crk} a =\n \\operatorname{rank} L - \\operatorname{rank}` a). At `q = 1`, this\n reduces to the multiplication formula originally given by Solomon.\n '
def __init__(self, L, q=None):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.quantum_moebius_algebra()\n sage: TestSuite(M).run() # long time\n\n sage: from sage.combinat.posets.moebius_algebra import QuantumMoebiusAlgebra\n sage: L = posets.Crown(2)\n sage: QuantumMoebiusAlgebra(L)\n Traceback (most recent call last):\n ...\n ValueError: L must be a lattice\n '
if (not L.is_lattice()):
raise ValueError('L must be a lattice')
if (q is None):
q = LaurentPolynomialRing(ZZ, 'q').gen()
self._q = q
R = q.parent()
cat = Algebras(R).WithBasis()
if (L in FiniteEnumeratedSets()):
cat = cat.Commutative().FiniteDimensional()
self._lattice = L
self._category = cat
Parent.__init__(self, base=R, category=self._category.WithRealizations())
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: L.quantum_moebius_algebra()\n Quantum Moebius algebra of Finite lattice containing 16 elements\n with q=q over Univariate Laurent Polynomial Ring in q over Integer Ring\n '
txt = 'Quantum Moebius algebra of {} with q={} over {}'
return txt.format(self._lattice, self._q, self.base_ring())
def a_realization(self):
'\n Return a particular realization of ``self`` (the `B`-basis).\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.quantum_moebius_algebra()\n sage: M.a_realization()\n Quantum Moebius algebra of Finite lattice containing 16 elements\n with q=q over Univariate Laurent Polynomial Ring in q\n over Integer Ring in the natural basis\n '
return self.E()
def lattice(self):
'\n Return the defining lattice of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.quantum_moebius_algebra()\n sage: M.lattice()\n Finite lattice containing 16 elements\n sage: M.lattice() == L\n True\n '
return self._lattice
class E(BasisAbstract):
'\n The natural basis of a quantum Möbius algebra.\n\n Let `E_x` and `E_y` be basis elements of `M_L` for some lattice `L`.\n Multiplication is given by\n\n .. MATH::\n\n E_x E_y = \\sum_{z \\geq a \\geq x \\vee y} \\mu_L(a, z)\n q^{\\operatorname{crk} a} E_z,\n\n where `\\mu_L` is the Möbius function of `L` and `\\operatorname{crk}`\n is the corank function (i.e., `\\operatorname{crk} a =\n \\operatorname{rank} L - \\operatorname{rank}` a).\n '
def __init__(self, M, prefix='E'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(4)\n sage: M = L.quantum_moebius_algebra()\n sage: TestSuite(M.E()).run() # long time\n '
self._basis_name = 'natural'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
def product_on_basis(self, x, y):
'\n Return the product of basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: E = L.quantum_moebius_algebra().E()\n sage: E.product_on_basis(5, 14)\n E[15]\n sage: E.product_on_basis(2, 8)\n q^2*E[10] + (q-q^2)*E[11] + (q-q^2)*E[14] + (1-2*q+q^2)*E[15]\n '
L = self.realization_of()._lattice
q = self.realization_of()._q
moebius = L.moebius_function
rank = L.rank_function()
R = L.rank()
j = L.join(x, y)
return self.sum_of_terms(((z, (moebius(a, z) * (q ** (R - rank(a))))) for z in L.order_filter([j]) for a in L.closed_interval(j, z)))
@cached_method
def one(self):
'\n Return the element ``1`` of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: E = L.quantum_moebius_algebra().E()\n sage: all(E.one() * b == b for b in E.basis())\n True\n '
L = self.realization_of()._lattice
q = self.realization_of()._q
moebius = L.moebius_function
rank = L.rank_function()
R = L.rank()
return self.sum_of_terms(((x, (moebius(y, x) * (q ** (rank(y) - R)))) for x in L for y in L.order_ideal([x])))
natural = E
class C(BasisAbstract):
'\n The characteristic basis of a quantum Möbius algebra.\n\n The characteristic basis `\\{ C_x \\mid x \\in L \\}` of `M_L`\n for some lattice `L` is defined by\n\n .. MATH::\n\n C_x = \\sum_{a \\geq x} P(F^x; q) E_a,\n\n where `F^x = \\{ y \\in L \\mid y \\geq x \\}` is the principal order\n filter of `x` and `P(F^x; q)` is the characteristic polynomial\n of the (sub)poset `F^x`.\n '
def __init__(self, M, prefix='C'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(3)\n sage: M = L.quantum_moebius_algebra()\n sage: TestSuite(M.C()).run() # long time\n '
self._basis_name = 'characteristic'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
E = M.E()
phi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice._element_to_vertex)
phi.register_as_coercion()
(~ phi).register_as_coercion()
@cached_method
def _to_natural_basis(self, x):
'\n Convert the element indexed by ``x`` to the natural basis.\n\n EXAMPLES::\n\n sage: M = posets.BooleanLattice(4).quantum_moebius_algebra()\n sage: C = M.C()\n sage: all(C(C._to_natural_basis(x)) == C.monomial(x)\n ....: for x in C.basis().keys())\n True\n '
M = self.realization_of()
N = M.natural()
q = M._q
L = M._lattice
def poly(x, y):
return L.subposet(L.closed_interval(x, y)).characteristic_polynomial()
return N.sum_of_terms(((y, poly(x, y)(q=q)) for y in L.order_filter([x])))
characteristic_basis = C
class KL(BasisAbstract):
'\n The Kazhdan-Lusztig basis of a quantum Möbius algebra.\n\n The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L`\n for some lattice `L` is defined by\n\n .. MATH::\n\n B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a,\n\n where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`,\n following the definition given in [EPW14]_.\n\n EXAMPLES:\n\n We construct some examples of Proposition 4.5 of [EPW14]_::\n\n sage: M = posets.BooleanLattice(4).quantum_moebius_algebra()\n sage: KL = M.KL()\n sage: KL[4] * KL[5]\n (q^2+q^3)*KL[5] + (q+2*q^2+q^3)*KL[7] + (q+2*q^2+q^3)*KL[13]\n + (1+3*q+3*q^2+q^3)*KL[15]\n sage: KL[4] * KL[15]\n (1+3*q+3*q^2+q^3)*KL[15]\n sage: KL[4] * KL[10]\n (q+3*q^2+3*q^3+q^4)*KL[14] + (1+4*q+6*q^2+4*q^3+q^4)*KL[15]\n '
def __init__(self, M, prefix='KL'):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: L = posets.BooleanLattice(3)\n sage: M = L.quantum_moebius_algebra()\n sage: TestSuite(M.KL()).run() # long time\n '
self._basis_name = 'Kazhdan-Lusztig'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
E = M.E()
phi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice._element_to_vertex)
phi.register_as_coercion()
(~ phi).register_as_coercion()
@cached_method
def _to_natural_basis(self, x):
'\n Convert the element indexed by ``x`` to the natural basis.\n\n EXAMPLES::\n\n sage: M = posets.BooleanLattice(4).quantum_moebius_algebra()\n sage: KL = M.KL()\n sage: all(KL(KL._to_natural_basis(x)) == KL.monomial(x) # long time\n ....: for x in KL.basis().keys())\n True\n '
M = self.realization_of()
L = M._lattice
E = M.E()
q = M._q
rank = L.rank_function()
return E.sum_of_terms(((y, ((q ** (rank(y) - rank(x))) * L.kazhdan_lusztig_polynomial(x, y)(q=(q ** (- 2))))) for y in L.order_filter([x])))
kazhdan_lusztig = KL
|
class MoebiusAlgebraBases(Category_realization_of_parent):
'\n The category of bases of a Möbius algebra.\n\n INPUT:\n\n - ``base`` -- a Möbius algebra\n\n TESTS::\n\n sage: from sage.combinat.posets.moebius_algebra import MoebiusAlgebraBases\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: bases = MoebiusAlgebraBases(M)\n sage: M.E() in bases\n True\n '
def _repr_(self):
'\n Return the representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.moebius_algebra import MoebiusAlgebraBases\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: MoebiusAlgebraBases(M)\n Category of bases of Moebius algebra of Finite lattice\n containing 16 elements over Rational Field\n '
return 'Category of bases of {}'.format(self.base())
def super_categories(self):
'\n The super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.moebius_algebra import MoebiusAlgebraBases\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: bases = MoebiusAlgebraBases(M)\n sage: bases.super_categories()\n [Category of finite dimensional commutative algebras with basis over Rational Field,\n Category of realizations of Moebius algebra of Finite lattice\n containing 16 elements over Rational Field]\n '
return [self.base()._category, Realizations(self.base())]
class ParentMethods():
def _repr_(self):
'\n Text representation of this basis of a Möbius algebra.\n\n EXAMPLES::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ)\n sage: M.E()\n Moebius algebra of Finite lattice containing 16 elements\n over Rational Field in the natural basis\n sage: M.I()\n Moebius algebra of Finite lattice containing 16 elements\n over Rational Field in the idempotent basis\n '
return '{} in the {} basis'.format(self.realization_of(), self._basis_name)
def product_on_basis(self, x, y):
'\n Return the product of basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: C = L.quantum_moebius_algebra().C()\n sage: C.product_on_basis(5, 14)\n q^3*C[15]\n sage: C.product_on_basis(2, 8)\n q^4*C[10]\n '
R = self.realization_of().a_realization()
return self((R(self.monomial(x)) * R(self.monomial(y))))
@cached_method
def one(self):
'\n Return the element ``1`` of ``self``.\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(4)\n sage: C = L.quantum_moebius_algebra().C()\n sage: all(C.one() * b == b for b in C.basis())\n True\n '
R = self.realization_of().a_realization()
return self(R.one())
class ElementMethods():
pass
|
def check_int(n, minimum=0):
"\n Check that ``n`` is an integer at least equal to ``minimum``.\n\n This is a boilerplate function ensuring input safety.\n\n INPUT:\n\n - ``n`` -- anything\n\n - ``minimum`` -- an optional integer (default: 0)\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.poset_examples import check_int\n sage: check_int(6, 3)\n 6\n sage: check_int(6)\n 6\n\n sage: check_int(-1)\n Traceback (most recent call last):\n ...\n ValueError: number of elements must be a non-negative integer, not -1\n\n sage: check_int(1, 3)\n Traceback (most recent call last):\n ...\n ValueError: number of elements must be an integer at least 3, not 1\n\n sage: check_int('junk')\n Traceback (most recent call last):\n ...\n ValueError: number of elements must be a non-negative integer, not junk\n "
if (minimum == 0):
msg = 'a non-negative integer'
else:
msg = f'an integer at least {minimum}'
if ((n not in NonNegativeIntegers()) or (n < minimum)):
raise ValueError((('number of elements must be ' + msg) + f', not {n}'))
return Integer(n)
|
class Posets(metaclass=ClasscallMetaclass):
'\n A collection of posets and lattices.\n\n EXAMPLES::\n\n sage: posets.BooleanLattice(3)\n Finite lattice containing 8 elements\n sage: posets.ChainPoset(3)\n Finite lattice containing 3 elements\n sage: posets.RandomPoset(17,.15)\n Finite poset containing 17 elements\n\n The category of all posets::\n\n sage: Posets()\n Category of posets\n\n The enumerated set of all posets on `3` elements, up to an\n isomorphism::\n\n sage: Posets(3)\n Posets containing 3 elements\n\n .. SEEALSO:: :class:`~sage.categories.posets.Posets`, :class:`FinitePosets`, :func:`Poset`\n\n TESTS::\n\n sage: P = Posets\n sage: TestSuite(P).run()\n '
@staticmethod
def __classcall__(cls, n=None):
'\n Return either the category of all posets, or the finite\n enumerated set of all finite posets on ``n`` elements up to an\n isomorphism.\n\n EXAMPLES::\n\n sage: Posets()\n Category of posets\n sage: Posets(4)\n Posets containing 4 elements\n '
if (n is None):
return sage.categories.posets.Posets()
n = check_int(n)
return FinitePosets_n(n)
@staticmethod
def BooleanLattice(n, facade=None, use_subsets=False):
'\n Return the Boolean lattice containing `2^n` elements.\n\n - ``n`` -- integer; number of elements will be `2^n`\n - ``facade`` -- boolean; whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n - ``use_subsets`` -- boolean (default: ``False``); if ``True``,\n then label the elements by subsets of `\\{1, 2, \\ldots, n\\}`;\n otherwise label the elements by `0, 1, 2, \\ldots, 2^n-1`\n\n EXAMPLES::\n\n sage: posets.BooleanLattice(5)\n Finite lattice containing 32 elements\n\n sage: sorted(posets.BooleanLattice(2))\n [0, 1, 2, 3]\n sage: sorted(posets.BooleanLattice(2, use_subsets=True), key=list)\n [{}, {1}, {1, 2}, {2}]\n\n TESTS:\n\n Check isomorphism::\n\n sage: B5 = posets.BooleanLattice(5)\n sage: B5S = posets.BooleanLattice(5, use_subsets=True)\n sage: B5.is_isomorphic(B5S)\n True\n\n Check the corner cases::\n\n sage: list(posets.BooleanLattice(0, use_subsets=True))\n [{}]\n sage: list(posets.BooleanLattice(1, use_subsets=True))\n [{}, {1}]\n '
n = check_int(n)
if (n == 0):
if use_subsets:
from sage.sets.set import Set
return LatticePoset(([Set()], []), facade=facade)
return LatticePoset(([0], []), facade=facade)
if (n == 1):
if use_subsets:
from sage.sets.set import Set
V = [Set(), Set([1])]
return LatticePoset((V, [V]), facade=facade)
return LatticePoset(([0, 1], [[0, 1]]), facade=facade)
if use_subsets:
from sage.sets.set import Set
cur_level = [frozenset(range(1, (n + 1)))]
D = DiGraph()
D.add_vertex(Set(cur_level[0]))
while cur_level:
next_level = set()
for X in cur_level:
for i in X:
Y = X.difference([i])
D.add_edge(Set(Y), Set(X))
next_level.add(Y)
cur_level = next_level
return FiniteLatticePoset(D, category=FiniteLatticePosets(), facade=facade)
D = DiGraph({v: [Integer((v | (1 << y))) for y in range(n) if ((v & (1 << y)) == 0)] for v in range((2 ** n))})
return FiniteLatticePoset(hasse_diagram=D, category=FiniteLatticePosets(), facade=facade)
@staticmethod
def ChainPoset(n, facade=None):
'\n Return a chain (a totally ordered poset) containing ``n`` elements.\n\n - ``n`` (an integer) -- number of elements.\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: C = posets.ChainPoset(6); C\n Finite lattice containing 6 elements\n sage: C.linear_extension()\n [0, 1, 2, 3, 4, 5]\n\n TESTS::\n\n sage: for i in range(5):\n ....: for j in range(5):\n ....: if C.covers(C(i),C(j)) and j != i+1:\n ....: print("TEST FAILED")\n\n Check that :trac:`8422` is solved::\n\n sage: posets.ChainPoset(0)\n Finite lattice containing 0 elements\n sage: C = posets.ChainPoset(1); C\n Finite lattice containing 1 elements\n sage: C.cover_relations()\n []\n sage: C = posets.ChainPoset(2); C\n Finite lattice containing 2 elements\n sage: C.cover_relations()\n [[0, 1]]\n '
n = check_int(n)
D = DiGraph([range(n), [[x, (x + 1)] for x in range((n - 1))]], format='vertices_and_edges')
return FiniteLatticePoset(hasse_diagram=D, category=FiniteLatticePosets(), facade=facade)
@staticmethod
def AntichainPoset(n, facade=None):
'\n Return an antichain (a poset with no comparable elements)\n containing `n` elements.\n\n INPUT:\n\n - ``n`` (an integer) -- number of elements\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: A = posets.AntichainPoset(6); A\n Finite poset containing 6 elements\n\n TESTS::\n\n sage: for i in range(5):\n ....: for j in range(5):\n ....: if A.covers(A(i),A(j)):\n ....: print("TEST FAILED")\n\n TESTS:\n\n Check that :trac:`8422` is solved::\n\n sage: posets.AntichainPoset(0)\n Finite poset containing 0 elements\n sage: C = posets.AntichainPoset(1); C\n Finite poset containing 1 elements\n sage: C.cover_relations()\n []\n sage: C = posets.AntichainPoset(2); C\n Finite poset containing 2 elements\n sage: C.cover_relations()\n []\n '
n = check_int(n)
return Poset((range(n), []), facade=facade)
@staticmethod
def PentagonPoset(facade=None):
'\n Return the Pentagon poset.\n\n INPUT:\n\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset(); P\n Finite lattice containing 5 elements\n sage: P.cover_relations()\n [[0, 1], [0, 2], [1, 4], [2, 3], [3, 4]]\n\n TESTS:\n\n This is smallest lattice that is not modular::\n\n sage: P.is_modular()\n False\n\n This poset and the :meth:`DiamondPoset` are the two smallest\n lattices which are not distributive::\n\n sage: P.is_distributive()\n False\n sage: posets.DiamondPoset(5).is_distributive()\n False\n '
return LatticePoset([[1, 2], [4], [3], [4], []], facade=facade)
@staticmethod
def DiamondPoset(n, facade=None):
'\n Return the lattice of rank two containing ``n`` elements.\n\n INPUT:\n\n - ``n`` -- number of elements, an integer at least 3\n\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: posets.DiamondPoset(7)\n Finite lattice containing 7 elements\n '
n = check_int(n, 3)
c = [[(n - 1)] for x in range(n)]
c[0] = [x for x in range(1, (n - 1))]
c[(n - 1)] = []
D = DiGraph({v: c[v] for v in range(n)}, format='dict_of_lists')
return FiniteLatticePoset(hasse_diagram=D, category=FiniteLatticePosets(), facade=facade)
@staticmethod
def Crown(n, facade=None):
'\n Return the crown poset of `2n` elements.\n\n In this poset every element `i` for `0 \\leq i \\leq n-1`\n is covered by elements `i+n` and `i+n+1`, except that\n `n-1` is covered by `n` and `n+1`.\n\n INPUT:\n\n - ``n`` -- number of elements, an integer at least 2\n\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: posets.Crown(3)\n Finite poset containing 6 elements\n '
n = check_int(n, 2)
D = {i: [(i + n), ((i + n) + 1)] for i in range((n - 1))}
D[(n - 1)] = [n, ((n + n) - 1)]
return FinitePoset(hasse_diagram=DiGraph(D), category=FinitePosets(), facade=facade)
@staticmethod
def DivisorLattice(n, facade=None):
'\n Return the divisor lattice of an integer.\n\n Elements of the lattice are divisors of `n` and `x < y` in the\n lattice if `x` divides `y`.\n\n INPUT:\n\n - ``n`` -- an integer\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: P = posets.DivisorLattice(12)\n sage: sorted(P.cover_relations())\n [[1, 2], [1, 3], [2, 4], [2, 6], [3, 6], [4, 12], [6, 12]]\n\n sage: P = posets.DivisorLattice(10, facade=False)\n sage: P(2) < P(5)\n False\n\n TESTS::\n\n sage: posets.DivisorLattice(1)\n Finite lattice containing 1 elements with distinguished linear extension\n '
from sage.arith.misc import divisors, is_prime
n = check_int(n, 1)
Div_n = divisors(n)
hasse = DiGraph([Div_n, (lambda a, b: (((b % a) == 0) and is_prime((b // a))))])
return FiniteLatticePoset(hasse, elements=Div_n, facade=facade, category=FiniteLatticePosets())
@staticmethod
def IntegerCompositions(n):
'\n Return the poset of integer compositions of the integer ``n``.\n\n A composition of a positive integer `n` is a list of positive\n integers that sum to `n`. The order is reverse refinement:\n `[p_1,p_2,...,p_l] < [q_1,q_2,...,q_m]` if `q` consists\n of an integer composition of `p_1`, followed by an integer\n composition of `p_2`, and so on.\n\n EXAMPLES::\n\n sage: P = posets.IntegerCompositions(7); P\n Finite poset containing 64 elements\n sage: len(P.cover_relations())\n 192\n '
from sage.combinat.composition import Compositions
C = Compositions(n)
return Poset((C, [[c, d] for c in C for d in C if d.is_finer(c)]), cover_relations=False)
@staticmethod
def IntegerPartitions(n):
'\n Return the poset of integer partitions on the integer ``n``.\n\n A partition of a positive integer `n` is a non-increasing list\n of positive integers that sum to `n`. If `p` and `q` are\n integer partitions of `n`, then `p` covers `q` if and only\n if `q` is obtained from `p` by joining two parts of `p`\n (and sorting, if necessary).\n\n EXAMPLES::\n\n sage: P = posets.IntegerPartitions(7); P\n Finite poset containing 15 elements\n sage: len(P.cover_relations())\n 28\n '
def lower_covers(partition):
'\n Nested function for computing the lower covers\n of elements in the poset of integer partitions.\n '
lc = []
for i in range((len(partition) - 1)):
for j in range((i + 1), len(partition)):
new_partition = partition[:]
del new_partition[j]
del new_partition[i]
new_partition.append((partition[i] + partition[j]))
new_partition.sort(reverse=True)
tup = tuple(new_partition)
if (tup not in lc):
lc.append(tup)
return lc
from sage.combinat.partition import Partitions
H = DiGraph(dict([[tuple(p), lower_covers(p)] for p in Partitions(n)]))
return Poset(H.reverse())
@staticmethod
def RestrictedIntegerPartitions(n):
'\n Return the poset of integer partitions on the integer `n`\n ordered by restricted refinement.\n\n That is, if `p` and `q` are integer partitions of `n`, then\n `p` covers `q` if and only if `q` is obtained from `p` by\n joining two distinct parts of `p` (and sorting, if necessary).\n\n EXAMPLES::\n\n sage: P = posets.RestrictedIntegerPartitions(7); P\n Finite poset containing 15 elements\n sage: len(P.cover_relations())\n 17\n\n '
def lower_covers(partition):
'\n Nested function for computing the lower covers of elements in the\n restricted poset of integer partitions.\n '
lc = []
for i in range((len(partition) - 1)):
for j in range((i + 1), len(partition)):
if (partition[i] != partition[j]):
new_partition = partition[:]
del new_partition[j]
del new_partition[i]
new_partition.append((partition[i] + partition[j]))
new_partition.sort(reverse=True)
tup = tuple(new_partition)
if (tup not in lc):
lc.append(tup)
return lc
from sage.combinat.partition import Partitions
H = DiGraph(dict([[tuple(p), lower_covers(p)] for p in Partitions(n)]))
return Poset(H.reverse())
@staticmethod
def IntegerPartitionsDominanceOrder(n):
'\n Return the lattice of integer partitions on the integer `n`\n ordered by dominance.\n\n That is, if `p=(p_1,\\ldots,p_i)` and `q=(q_1,\\ldots,q_j)` are\n integer partitions of `n`, then `p` is greater than `q` if and\n only if `p_1+\\cdots+p_k > q_1+\\cdots+q_k` for all `k`.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: P = posets.IntegerPartitionsDominanceOrder(6); P\n Finite lattice containing 11 elements\n sage: P.cover_relations()\n [[[1, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1]],\n [[2, 1, 1, 1, 1], [2, 2, 1, 1]],\n [[2, 2, 1, 1], [2, 2, 2]],\n [[2, 2, 1, 1], [3, 1, 1, 1]],\n [[2, 2, 2], [3, 2, 1]],\n [[3, 1, 1, 1], [3, 2, 1]],\n [[3, 2, 1], [3, 3]],\n [[3, 2, 1], [4, 1, 1]],\n [[3, 3], [4, 2]],\n [[4, 1, 1], [4, 2]],\n [[4, 2], [5, 1]],\n [[5, 1], [6]]]\n '
n = check_int(n)
from sage.combinat.partition import Partitions, Partition
return LatticePoset((Partitions(n), Partition.dominates)).dual()
@staticmethod
def PowerPoset(n):
'\n Return the power poset on `n` element posets.\n\n Elements of the power poset are all posets on\n the set `\\{0, 1, \\ldots, n-1\\}` ordered by extension.\n That is, the antichain of `n` elements is the bottom and\n `P_a \\le P_b` in the power poset if `P_b` is an extension\n of `P_a`.\n\n These were studied in [Bru1994]_.\n\n EXAMPLES::\n\n sage: P3 = posets.PowerPoset(3); P3\n Finite meet-semilattice containing 19 elements\n sage: all(P.is_chain() for P in P3.maximal_elements())\n True\n\n TESTS::\n\n sage: P0 = posets.PowerPoset(0); P0\n Finite meet-semilattice containing 1 elements\n sage: P0[0]\n Finite poset containing 0 elements\n sage: P1 = posets.PowerPoset(1); P1\n Finite meet-semilattice containing 1 elements\n sage: P1[0]\n Finite poset containing 1 elements\n sage: P1[0][0]\n 0\n '
n = check_int(n)
all_pos_n = set()
Pn = list(Posets(n))
for P in Pn:
for r in Permutations(P):
all_pos_n.add(P.relabel(list(r)))
return MeetSemilattice((all_pos_n, (lambda A, B: all((B.is_lequal(x, y) for (x, y) in A.cover_relations_iterator())))))
@staticmethod
def ProductOfChains(chain_lengths, facade=None):
'\n Return a product of chains.\n\n - ``chain_lengths`` -- A list of nonnegative integers; number of\n elements in each chain.\n\n - ``facade`` -- boolean; whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n EXAMPLES::\n\n sage: P = posets.ProductOfChains([2, 2]); P\n Finite lattice containing 4 elements\n sage: P.linear_extension()\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: P.upper_covers((0,0))\n [(0, 1), (1, 0)]\n sage: P.lower_covers((1,1))\n [(0, 1), (1, 0)]\n\n TESTS::\n\n sage: P = posets.ProductOfChains([]); P\n Finite lattice containing 0 elements\n sage: P = posets.ProductOfChains([3, 0, 1]); P\n Finite lattice containing 0 elements\n sage: P = posets.ProductOfChains([1,1,1,1]); P\n Finite lattice containing 1 elements\n '
try:
l = [Integer(x) for x in chain_lengths]
except TypeError:
raise TypeError('parameter chain_lengths must be a list of integers, not {0}'.format(chain_lengths))
if any(((x < 0) for x in l)):
raise TypeError('parameter chain_lengths must be a list of nonnegative integers, not {0}'.format(l))
if (not chain_lengths):
return LatticePoset(facade=facade)
from sage.categories.cartesian_product import cartesian_product
elements = cartesian_product([range(i) for i in l])
def compare(a, b):
return all(((x <= y) for (x, y) in zip(a, b)))
return LatticePoset([elements, compare], facade=facade)
@staticmethod
def RandomPoset(n, p):
"\n Generate a random poset on ``n`` elements according to a\n probability ``p``.\n\n INPUT:\n\n - ``n`` - number of elements, a non-negative integer\n\n - ``p`` - a probability, a real number between 0 and 1 (inclusive)\n\n OUTPUT:\n\n A poset on `n` elements. The probability `p` roughly measures\n width/height of the output: `p=0` always generates an antichain,\n `p=1` will return a chain. To create interesting examples,\n keep the probability small, perhaps on the order of `1/n`.\n\n EXAMPLES::\n\n sage: set_random_seed(0) # Results are reproducible\n sage: P = posets.RandomPoset(5, 0.3)\n sage: P.cover_relations()\n [[5, 4], [4, 2], [1, 2]]\n\n .. SEEALSO:: :meth:`RandomLattice`\n\n TESTS::\n\n sage: posets.RandomPoset(6, 'garbage')\n Traceback (most recent call last):\n ...\n TypeError: probability must be a real number, not garbage\n\n sage: posets.RandomPoset(6, -0.5)\n Traceback (most recent call last):\n ...\n ValueError: probability must be between 0 and 1, not -0.5\n\n sage: posets.RandomPoset(0, 0.5)\n Finite poset containing 0 elements\n "
from sage.misc.prandom import random
n = check_int(n)
try:
p = float(p)
except (TypeError, ValueError):
raise TypeError('probability must be a real number, not {0}'.format(p))
if ((p < 0) or (p > 1)):
raise ValueError('probability must be between 0 and 1, not {0}'.format(p))
D = DiGraph(loops=False, multiedges=False)
D.add_vertices(range(n))
for i in range(n):
for j in range((i + 1), n):
if (random() < p):
D.add_edge(i, j)
D.relabel(list(Permutations(n).random_element()))
return Poset(D, cover_relations=False)
@staticmethod
def RandomLattice(n, p, properties=None):
"\n Return a random lattice on ``n`` elements.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n\n - ``p`` -- a probability, a positive real number less than one\n\n - ``properties`` -- a list of properties for the lattice. Currently\n implemented:\n\n * ``None``, no restrictions for lattices to create\n * ``'planar'``, the lattice has an upward planar drawing\n * ``'dismantlable'`` (implicated by ``'planar'``)\n * ``'distributive'`` (implicated by ``'stone'``)\n * ``'stone'``\n\n OUTPUT:\n\n A lattice on `n` elements. When ``properties`` is ``None``,\n the probability `p` roughly measures number of covering\n relations of the lattice. To create interesting examples, make\n the probability a little below one, for example `0.9`.\n\n Currently parameter ``p`` has no effect only when ``properties``\n is not ``None``.\n\n .. NOTE::\n\n Results are reproducible in same Sage version only. Underlying\n algorithm may change in future versions.\n\n EXAMPLES::\n\n sage: set_random_seed(0) # Results are reproducible\n sage: L = posets.RandomLattice(8, 0.995); L\n Finite lattice containing 8 elements\n sage: L.cover_relations()\n [[7, 6], [7, 3], [7, 1], ..., [5, 4], [2, 4], [1, 4], [0, 4]]\n sage: L = posets.RandomLattice(10, 0, properties=['dismantlable'])\n sage: L.is_dismantlable()\n True\n\n .. SEEALSO:: :meth:`RandomPoset`\n\n TESTS::\n\n sage: posets.RandomLattice(6, 'garbage')\n Traceback (most recent call last):\n ...\n TypeError: probability must be a real number, not garbage\n\n sage: posets.RandomLattice(6, -0.5)\n Traceback (most recent call last):\n ...\n ValueError: probability must be a positive real number and below 1, not -0.5\n\n sage: posets.RandomLattice(10, 0.5, properties=['junk'])\n Traceback (most recent call last):\n ...\n ValueError: unknown value junk for 'properties'\n\n sage: posets.RandomLattice(0, 0.5)\n Finite lattice containing 0 elements\n "
from copy import copy
n = check_int(n)
try:
p = float(p)
except Exception:
raise TypeError('probability must be a real number, not {0}'.format(p))
if ((p < 0) or (p >= 1)):
raise ValueError('probability must be a positive real number and below 1, not {0}'.format(p))
if (properties is None):
if (n <= 3):
return posets.ChainPoset(n)
covers = _random_lattice(n, p)
covers_dict = {i: covers[i] for i in range(n)}
D = DiGraph(covers_dict)
D.relabel([(i - 1) for i in Permutations(n).random_element()])
return LatticePoset(D, cover_relations=True)
if isinstance(properties, str):
properties = set([properties])
else:
properties = set(properties)
known_properties = set(['planar', 'dismantlable', 'distributive', 'stone'])
errors = properties.difference(known_properties)
if errors:
raise ValueError(("unknown value %s for 'properties'" % errors.pop()))
if (n <= 3):
return posets.ChainPoset(n)
if ('planar' in properties):
properties.discard('dismantlable')
if ('stone' in properties):
properties.discard('distributive')
if (('distributive' in properties) and (len(properties) > 1)):
raise NotImplementedError("combining 'distributive' with other properties is not implemented")
if (('stone' in properties) and (len(properties) > 1)):
raise NotImplementedError("combining 'stone' with other properties is not implemented")
if (properties == set(['planar'])):
D = _random_planar_lattice(n)
D.relabel([(i - 1) for i in Permutations(n).random_element()])
return LatticePoset(D)
if (properties == set(['dismantlable'])):
D = _random_dismantlable_lattice(n)
D.relabel([(i - 1) for i in Permutations(n).random_element()])
return LatticePoset(D)
if (properties == set(['stone'])):
D = _random_stone_lattice(n)
D.relabel([(i - 1) for i in Permutations(n).random_element()])
return LatticePoset(D)
if (properties == set(['distributive'])):
tmp = Poset(_random_distributive_lattice(n)).order_ideals_lattice(as_ideals=False)
D = copy(tmp._hasse_diagram)
D.relabel([(i - 1) for i in Permutations(n).random_element()])
return LatticePoset(D)
raise AssertionError('bug in RandomLattice()')
@staticmethod
def SetPartitions(n):
'\n Return the lattice of set partitions of the set `\\{1,\\ldots,n\\}`\n ordered by refinement.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: posets.SetPartitions(4)\n Finite lattice containing 15 elements\n '
from sage.combinat.set_partition import SetPartitions
n = check_int(n)
S = SetPartitions(n)
def covers(x):
for (i, s) in enumerate(x):
for j in range((i + 1), len(x)):
L = list(x)
L[i] = s.union(x[j])
L.pop(j)
(yield S(L))
return LatticePoset({x: list(covers(x)) for x in S}, cover_relations=True)
@staticmethod
def SSTPoset(s, f=None):
'\n The lattice poset on semistandard tableaux of shape ``s`` and largest\n entry ``f`` that is ordered by componentwise comparison of the\n entries.\n\n INPUT:\n\n - ``s`` - shape of the tableaux\n\n - ``f`` - maximum fill number. This is an optional\n argument. If no maximal number is given, it will use\n the number of cells in the shape.\n\n .. NOTE::\n\n This is a basic implementation and most certainly\n not the most efficient.\n\n EXAMPLES::\n\n sage: posets.SSTPoset([2,1])\n Finite lattice containing 8 elements\n\n sage: posets.SSTPoset([2,1],4)\n Finite lattice containing 20 elements\n\n sage: posets.SSTPoset([2,1],2).cover_relations()\n [[[[1, 1], [2]], [[1, 2], [2]]]]\n\n sage: posets.SSTPoset([3,2]).bottom() # long time (6s on sage.math, 2012)\n [[1, 1, 1], [2, 2]]\n\n sage: posets.SSTPoset([3,2],4).maximal_elements()\n [[[3, 3, 4], [4, 4]]]\n '
from sage.combinat.tableau import SemistandardTableaux
def tableaux_is_less_than(a, b):
return all(((ix <= iy) for (x, y) in zip(a, b) for (ix, iy) in zip(x, y)))
if (f is None):
f = sum(s)
E = SemistandardTableaux(s, max_entry=f)
return LatticePoset((E, tableaux_is_less_than))
@staticmethod
def StandardExample(n, facade=None):
'\n Return the partially ordered set on ``2n`` elements with\n dimension ``n``.\n\n Let `P` be the poset on `\\{0, 1, 2, \\ldots, 2n-1\\}` whose defining\n relations are that `i < j` for every `0 \\leq i < n \\leq j < 2n`\n except when `i + n = j`. The poset `P` is the so-called\n *standard example* of a poset with dimension `n`.\n\n INPUT:\n\n - ``n`` -- an integer `\\ge 2`, dimension of the constructed poset\n - ``facade`` (boolean) -- whether to make the returned poset a\n facade poset (see :mod:`sage.categories.facade_sets`); the\n default behaviour is the same as the default behaviour of\n the :func:`~sage.combinat.posets.posets.Poset` constructor\n\n OUTPUT:\n\n The standard example of a poset of dimension `n`.\n\n EXAMPLES::\n\n sage: A = posets.StandardExample(3); A\n Finite poset containing 6 elements\n sage: A.dimension()\n 3\n\n REFERENCES:\n\n - [Gar2015]_\n - [Ros1999]_\n\n TESTS::\n\n sage: A = posets.StandardExample(10); A\n Finite poset containing 20 elements\n sage: len(A.cover_relations())\n 90\n\n sage: P = posets.StandardExample(5, facade=False)\n sage: P(4) < P(3), P(4) > P(3)\n (False, False)\n '
n = check_int(n, 2)
return Poset((range((2 * n)), [[i, (j + n)] for i in range(n) for j in range(n) if (i != j)]), facade=facade)
@staticmethod
def SymmetricGroupBruhatOrderPoset(n):
'\n The poset of permutations with respect to Bruhat order.\n\n EXAMPLES::\n\n sage: posets.SymmetricGroupBruhatOrderPoset(4)\n Finite poset containing 24 elements\n '
if (n < 10):
element_labels = {s: ''.join((str(x) for x in s)) for s in Permutations(n)}
return Poset({s: s.bruhat_succ() for s in Permutations(n)}, element_labels)
@staticmethod
def SymmetricGroupBruhatIntervalPoset(start, end):
'\n The poset of permutations with respect to Bruhat order.\n\n INPUT:\n\n - ``start`` - list permutation\n\n - ``end`` - list permutation (same n, of course)\n\n .. note::\n\n Must have ``start`` <= ``end``.\n\n EXAMPLES:\n\n Any interval is rank symmetric if and only if it avoids these\n permutations::\n\n sage: P1 = posets.SymmetricGroupBruhatIntervalPoset([1,2,3,4], [3,4,1,2])\n sage: P2 = posets.SymmetricGroupBruhatIntervalPoset([1,2,3,4], [4,2,3,1])\n sage: ranks1 = [P1.rank(v) for v in P1]\n sage: ranks2 = [P2.rank(v) for v in P2]\n sage: [ranks1.count(i) for i in sorted(set(ranks1))]\n [1, 3, 5, 4, 1]\n sage: [ranks2.count(i) for i in sorted(set(ranks2))]\n [1, 3, 5, 6, 4, 1]\n '
start = Permutation(start)
end = Permutation(end)
if (len(start) != len(end)):
raise TypeError(('start (%s) and end (%s) must have same length' % (start, end)))
if (not start.bruhat_lequal(end)):
raise TypeError(('must have start (%s) <= end (%s) in Bruhat order' % (start, end)))
unseen = [start]
nodes = {}
while unseen:
perm = unseen.pop(0)
nodes[perm] = [succ_perm for succ_perm in perm.bruhat_succ() if succ_perm.bruhat_lequal(end)]
for succ_perm in nodes[perm]:
if (succ_perm not in nodes):
unseen.append(succ_perm)
return Poset(nodes)
@staticmethod
def SymmetricGroupWeakOrderPoset(n, labels='permutations', side='right'):
'\n The poset of permutations of `\\{ 1, 2, \\ldots, n \\}` with respect\n to the weak order (also known as the permutohedron order, cf.\n :meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal`).\n\n The optional variable ``labels`` (default: ``"permutations"``)\n determines the labelling of the elements if `n < 10`. The optional\n variable ``side`` (default: ``"right"``) determines whether the\n right or the left permutohedron order is to be used.\n\n EXAMPLES::\n\n sage: posets.SymmetricGroupWeakOrderPoset(4)\n Finite poset containing 24 elements\n '
if ((n < 10) and (labels == 'permutations')):
element_labels = dict([[s, ''.join(map(str, s))] for s in Permutations(n)])
if ((n < 10) and (labels == 'reduced_words')):
element_labels = dict([[s, ''.join(map(str, s.reduced_word_lexmin()))] for s in Permutations(n)])
if (side == 'left'):
def weak_covers(s):
'\n Nested function for computing the covers of elements in the\n poset of left weak order for the symmetric group.\n '
return [v for v in s.bruhat_succ() if ((s.length() + s.inverse().right_action_product(v).length()) == v.length())]
else:
def weak_covers(s):
'\n Nested function for computing the covers of elements in the\n poset of right weak order for the symmetric group.\n '
return [v for v in s.bruhat_succ() if ((s.length() + s.inverse().left_action_product(v).length()) == v.length())]
return Poset(dict([[s, weak_covers(s)] for s in Permutations(n)]), element_labels)
@staticmethod
def TetrahedralPoset(n, *colors, **labels):
"\n Return the tetrahedral poset based on the input colors.\n\n This method will return the tetrahedral poset with n-1 layers and\n covering relations based on the input colors of 'green', 'red',\n 'orange', 'silver', 'yellow' and 'blue' as defined in [Striker2011]_.\n For particular color choices, the order ideals of the resulting\n tetrahedral poset will be isomorphic to known combinatorial objects.\n\n For example, for the colors 'blue', 'yellow', 'orange', and 'green',\n the order ideals will be in bijection with alternating sign matrices.\n For the colors 'yellow', 'orange', and 'green', the order ideals will\n be in bijection with semistandard Young tableaux of staircase shape.\n For the colors 'red', 'orange', 'green', and optionally 'yellow', the\n order ideals will be in bijection with totally symmetric\n self-complementary plane partitions in a `2n \\times 2n \\times 2n` box.\n\n INPUT:\n\n - ``n`` - Defines the number (n-1) of layers in the poset.\n\n - ``colors`` - The colors that define the covering relations of the\n poset. Colors used are 'green', 'red', 'yellow', 'orange', 'silver',\n and 'blue'.\n\n - ``labels`` - Keyword variable used to determine whether the poset\n is labeled with integers or tuples. To label with integers, the\n method should be called with ``labels='integers'``. Otherwise, the\n labeling will default to tuples.\n\n EXAMPLES::\n\n sage: posets.TetrahedralPoset(4,'green','red','yellow','silver','blue','orange')\n Finite poset containing 10 elements\n\n sage: posets.TetrahedralPoset(4,'green','red','yellow','silver','blue','orange', labels='integers')\n Finite poset containing 10 elements\n\n sage: A = AlternatingSignMatrices(3)\n sage: p = A.lattice()\n sage: ji = p.join_irreducibles_poset()\n sage: tet = posets.TetrahedralPoset(3, 'green','yellow','blue','orange')\n sage: ji.is_isomorphic(tet)\n True\n\n TESTS::\n\n sage: posets.TetrahedralPoset(4,'scarlet')\n Traceback (most recent call last):\n ...\n ValueError: color input must be among: 'green', 'red', 'yellow',\n 'orange', 'silver', and 'blue'\n "
n = check_int(n, 2)
n = (n - 1)
for c in colors:
if (c not in ('green', 'red', 'yellow', 'orange', 'silver', 'blue')):
raise ValueError("color input must be among: 'green', 'red', 'yellow', 'orange', 'silver', and 'blue'")
elem = [(i, j, k) for i in range(n) for j in range((n - i)) for k in range(((n - i) - j))]
rels = []
elem_labels = {}
if ('labels' in labels):
if (labels['labels'] == 'integers'):
labelcount = 0
for (i, j, k) in elem:
elem_labels[(i, j, k)] = labelcount
labelcount += 1
for c in colors:
for (i, j, k) in elem:
if (((i + j) + k) < (n - 1)):
if (c == 'green'):
rels.append([(i, j, k), ((i + 1), j, k)])
if (c == 'red'):
rels.append([(i, j, k), (i, j, (k + 1))])
if (c == 'yellow'):
rels.append([(i, j, k), (i, (j + 1), k)])
if ((j < (n - 1)) and (k > 0)):
if (c == 'orange'):
rels.append([(i, j, k), (i, (j + 1), (k - 1))])
if ((i < (n - 1)) and (j > 0)):
if (c == 'silver'):
rels.append([(i, j, k), ((i + 1), (j - 1), k)])
if ((i < (n - 1)) and (k > 0)):
if (c == 'blue'):
rels.append([(i, j, k), ((i + 1), j, (k - 1))])
return Poset([elem, rels], elem_labels)
import sage.combinat.shard_order
ShardPoset = staticmethod(sage.combinat.shard_order.shard_poset)
import sage.combinat.tamari_lattices
TamariLattice = staticmethod(sage.combinat.tamari_lattices.TamariLattice)
DexterSemilattice = staticmethod(sage.combinat.tamari_lattices.DexterSemilattice)
@staticmethod
def CoxeterGroupAbsoluteOrderPoset(W, use_reduced_words=True):
"\n Return the poset of elements of a Coxeter group with respect\n to absolute order.\n\n INPUT:\n\n - ``W`` -- a Coxeter group\n - ``use_reduced_words`` -- boolean (default: ``True``); if\n ``True``, then the elements are labeled by their lexicographically\n minimal reduced word\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['B', 3]) # needs sage.groups\n sage: posets.CoxeterGroupAbsoluteOrderPoset(W) # needs sage.groups\n Finite poset containing 48 elements\n\n sage: W = WeylGroup(['B', 2], prefix='s') # needs sage.groups\n sage: posets.CoxeterGroupAbsoluteOrderPoset(W, False) # needs sage.groups\n Finite poset containing 8 elements\n "
if use_reduced_words:
element_labels = {s: tuple(s.reduced_word()) for s in W}
return Poset({s: s.absolute_covers() for s in W}, element_labels)
return Poset({s: s.absolute_covers() for s in W})
@staticmethod
def NoncrossingPartitions(W):
"\n Return the lattice of noncrossing partitions.\n\n INPUT:\n\n - ``W`` -- a finite Coxeter group or a Weyl group\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A', 3]) # needs sage.groups\n sage: posets.NoncrossingPartitions(W) # needs sage.groups\n Finite lattice containing 14 elements\n\n sage: W = WeylGroup(['B', 2], prefix='s') # needs sage.groups\n sage: posets.NoncrossingPartitions(W) # needs sage.groups\n Finite lattice containing 6 elements\n "
return W.noncrossing_partition_lattice()
@staticmethod
def SymmetricGroupAbsoluteOrderPoset(n, labels='permutations'):
'\n Return the poset of permutations with respect to absolute order.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n - ``label`` -- (default: ``\'permutations\'``) a label for the elements\n of the poset returned by the function; the options are\n\n * ``\'permutations\'`` - labels the elements are given by their\n one-line notation\n * ``\'reduced_words\'`` - labels the elements by the\n lexicographically minimal reduced word\n * ``\'cycles\'`` - labels the elements by their expression\n as a product of cycles\n\n EXAMPLES::\n\n sage: posets.SymmetricGroupAbsoluteOrderPoset(4) # needs sage.groups\n Finite poset containing 24 elements\n sage: posets.SymmetricGroupAbsoluteOrderPoset(3, labels="cycles") # needs sage.groups\n Finite poset containing 6 elements\n sage: posets.SymmetricGroupAbsoluteOrderPoset(3, labels="reduced_words") # needs sage.groups\n Finite poset containing 6 elements\n '
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
W = SymmetricGroup(n)
if (labels == 'permutations'):
element_labels = {s: s.tuple() for s in W}
if (labels == 'reduced_words'):
element_labels = {s: tuple(s.reduced_word()) for s in W}
if (labels == 'cycles'):
element_labels = {s: ''.join((x for x in s.cycle_string() if (x != ','))) for s in W}
return Poset({s: s.absolute_covers() for s in W}, element_labels)
@staticmethod
def UpDownPoset(n, m=1):
'\n Return the up-down poset on `n` elements where every `(m+1)`\n step is down and the rest are up.\n\n The case where `m=1` is sometimes referred to as the zig-zag poset\n or the fence.\n\n INPUT:\n\n - ``n`` - nonnegative integer, number of elements in the poset\n - ``m`` - nonnegative integer (default 1), how frequently down\n steps occur\n\n OUTPUT:\n\n The partially ordered set on `\\{ 0, 1, \\ldots, n-1 \\}`\n where `i` covers `i+1` if `m` divides `i+1`, and `i+1` covers `i`\n otherwise.\n\n EXAMPLES::\n\n sage: P = posets.UpDownPoset(7, 2); P\n Finite poset containing 7 elements\n sage: sorted(P.cover_relations())\n [[0, 1], [1, 2], [3, 2], [3, 4], [4, 5], [6, 5]]\n\n Fibonacci numbers as the number of antichains of a poset::\n\n sage: [len(posets.UpDownPoset(n).antichains().list()) for n in range(6)]\n [1, 2, 3, 5, 8, 13]\n\n TESTS::\n\n sage: P = posets.UpDownPoset(0); P\n Finite poset containing 0 elements\n '
n = check_int(n)
try:
m = Integer(m)
except TypeError:
raise TypeError('parameter m must be an integer, not {0}'.format(m))
if (m < 1):
raise ValueError('parameter m must be positive, not {0}'.format(m))
covers = [([i, (i + 1)] if ((i + 1) % (m + 1)) else [(i + 1), i]) for i in range((n - 1))]
return Poset((range(n), covers), cover_relations=True)
@staticmethod
def YoungDiagramPoset(lam, dual=False):
'\n Return the poset of cells in the Young diagram of a partition.\n\n INPUT:\n\n - ``lam`` -- a partition\n - ``dual`` -- (default: ``False``) determines the orientation\n of the poset; if ``True``, then it is a join semilattice,\n otherwise it is a meet semilattice\n\n EXAMPLES::\n\n sage: P = posets.YoungDiagramPoset(Partition([2, 2])); P\n Finite meet-semilattice containing 4 elements\n\n sage: sorted(P.cover_relations())\n [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]\n\n sage: posets.YoungDiagramPoset([3, 2], dual=True)\n Finite join-semilattice containing 5 elements\n '
from sage.combinat.partition import Partition
lam = Partition(lam)
if dual:
def cell_geq(a, b):
'\n Nested function that returns `True` if the cell `a` is\n to the right or below\n the cell `b` in the (English) Young diagram.\n '
return (((a[0] == (b[0] + 1)) and (a[1] == b[1])) or ((a[1] == (b[1] + 1)) and (a[0] == b[0])))
return JoinSemilattice((lam.cells(), cell_geq), cover_relations=True)
else:
def cell_leq(a, b):
'\n Nested function that returns `True` if the cell `a` is\n to the left or above\n the cell `b` in the (English) Young diagram.\n '
return (((a[0] == (b[0] - 1)) and (a[1] == b[1])) or ((a[1] == (b[1] - 1)) and (a[0] == b[0])))
return MeetSemilattice((lam.cells(), cell_leq), cover_relations=True)
@staticmethod
def YoungsLattice(n):
"\n Return Young's Lattice up to rank `n`.\n\n In other words, the poset of partitions\n of size less than or equal to `n` ordered by inclusion.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: P = posets.YoungsLattice(3); P\n Finite meet-semilattice containing 7 elements\n sage: P.cover_relations()\n [[[], [1]],\n [[1], [1, 1]],\n [[1], [2]],\n [[1, 1], [1, 1, 1]],\n [[1, 1], [2, 1]],\n [[2], [2, 1]],\n [[2], [3]]]\n "
from sage.combinat.partition import Partitions, Partition
from sage.misc.flatten import flatten
partitions = flatten([list(Partitions(i)) for i in range((n + 1))])
return JoinSemilattice((partitions, Partition.contains)).dual()
@staticmethod
def YoungsLatticePrincipalOrderIdeal(lam):
"\n Return the principal order ideal of the\n partition `lam` in Young's Lattice.\n\n INPUT:\n\n - ``lam`` -- a partition\n\n EXAMPLES::\n\n sage: P = posets.YoungsLatticePrincipalOrderIdeal(Partition([2,2]))\n sage: P\n Finite lattice containing 6 elements\n sage: P.cover_relations()\n [[[], [1]],\n [[1], [1, 1]],\n [[1], [2]],\n [[1, 1], [2, 1]],\n [[2], [2, 1]],\n [[2, 1], [2, 2]]]\n "
ideal = {}
level = [lam]
while level:
new_level = set()
for mu in level:
down = mu.down_list()
ideal[mu] = down
new_level.update(down)
level = new_level
H = DiGraph(ideal)
return LatticePoset(H.reverse())
@staticmethod
def YoungFibonacci(n):
"\n Return the Young-Fibonacci lattice up to rank `n`.\n\n Elements of the (infinite) lattice are words with letters '1'\n and '2'. The covers of a word are the words with another '1'\n added somewhere not after the first occurrence of an existing\n '1' and, additionally, the words where the first '1' is replaced by a\n '2'. The lattice is truncated to have rank `n`.\n\n See :wikipedia:`Young-Fibonacci lattice`.\n\n EXAMPLES::\n\n sage: Y5 = posets.YoungFibonacci(5); Y5\n Finite meet-semilattice containing 20 elements\n sage: sorted(Y5.upper_covers(Word('211')))\n [word: 1211, word: 2111, word: 221]\n\n TESTS::\n\n sage: posets.YoungFibonacci(0)\n Finite meet-semilattice containing 1 elements\n sage: posets.YoungFibonacci(1)\n Finite meet-semilattice containing 2 elements\n "
from sage.combinat.posets.lattices import FiniteMeetSemilattice
from sage.categories.finite_posets import FinitePosets
from sage.combinat.words.word import Word
n = check_int(n)
if (n == 0):
return MeetSemilattice({'': []})
covers = []
current_level = ['']
for i in range(1, (n + 1)):
new_level = set()
for low in current_level:
ind = low.find('1')
if (ind != (- 1)):
up = ((low[:ind] + '2') + low[(ind + 1):])
new_level.add(up)
covers.append((low, up))
else:
ind = len(low)
for j in range((ind + 1)):
up = ((('2' * j) + '1') + low[j:len(low)])
new_level.add(up)
covers.append((low, up))
current_level = new_level
D = DiGraph([[], covers], format='vertices_and_edges')
D.relabel(Word, inplace=True)
return FiniteMeetSemilattice(hasse_diagram=D, category=FinitePosets())
@staticmethod
def DoubleTailedDiamond(n):
'\n Return a double-tailed diamond of `2n + 2` elements.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: P = posets.DoubleTailedDiamond(2); P\n Finite d-complete poset containing 6 elements\n sage: P.cover_relations()\n [[1, 2], [2, 3], [2, 4], [3, 5], [4, 5], [5, 6]]\n '
n = check_int(n, 1)
edges = [(i, (i + 1)) for i in range(1, n)]
edges.extend([(n, (n + 1)), (n, (n + 2)), ((n + 1), (n + 3)), ((n + 2), (n + 3))])
edges.extend([(i, (i + 1)) for i in range((n + 3), ((2 * n) + 2))])
p = DiGraph([list(range(1, ((2 * n) + 3))), edges])
return DCompletePoset(p)
@staticmethod
def PermutationPattern(n):
'\n Return the poset of permutations under pattern containment\n up to rank ``n``.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n A permutation `u = u_1 \\cdots u_n` contains the pattern\n `v = v_1 \\cdots v_m` if there is a (not necessarily consecutive)\n subsequence of `u` of length `m` whose entries have the same\n relative order as `v`.\n\n See :wikipedia:`Permutation_pattern`.\n\n EXAMPLES::\n\n sage: P4 = posets.PermutationPattern(4); P4\n Finite poset containing 33 elements\n sage: sorted(P4.lower_covers(Permutation([2,4,1,3])))\n [[1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2]]\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.permutation.Permutation.has_pattern`\n\n TESTS::\n\n sage: posets.PermutationPattern(1)\n Finite poset containing 1 elements\n sage: posets.PermutationPattern(2)\n Finite poset containing 3 elements\n '
n = check_int(n, 1)
elem = []
for i in range(1, (n + 1)):
elem += Permutations(i)
return Poset((elem, (lambda a, b: b.has_pattern(a))))
@staticmethod
def PermutationPatternInterval(bottom, top):
'\n Return the poset consisting of an interval in the poset of permutations\n under pattern containment between ``bottom`` and ``top``.\n\n INPUT:\n\n - ``bottom``, ``top`` -- permutations where ``top`` contains\n ``bottom`` as a pattern\n\n A permutation `u = u_1 \\cdots u_n` contains the pattern\n `v = v_1 \\cdots v_m` if there is a (not necessarily consecutive)\n subsequence of `u` of length `m` whose entries have the same\n relative order as `v`.\n\n See :wikipedia:`Permutation_pattern`.\n\n EXAMPLES::\n\n sage: t = Permutation([2,3,1])\n sage: b = Permutation([4,6,2,3,5,1])\n sage: R = posets.PermutationPatternInterval(t, b); R\n Finite poset containing 14 elements\n sage: R.moebius_function(R.bottom(),R.top())\n -4\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.permutation.Permutation.has_pattern`,\n :meth:`PermutationPattern`\n\n TESTS::\n\n sage: p = Permutation([1])\n sage: posets.PermutationPatternInterval(p, p)\n Finite poset containing 1 elements\n '
P = Permutations()
top = P(top)
bottom = P(bottom)
if (not top.has_pattern(bottom)):
raise ValueError("{} doesn't contain {} as a pattern".format(top, bottom))
elem = [[top]]
level = 0
rel = []
while ((len(top) - len(bottom)) >= (level + 1)):
elem.append([])
for upper in elem[level]:
upper_perm = P(upper)
for i in range((len(top) - level)):
lower = list(upper)
j = lower.pop(i)
for k in range(((len(top) - level) - 1)):
if (lower[k] > j):
lower[k] = (lower[k] - 1)
lower_perm = P(lower)
if lower_perm.has_pattern(bottom):
rel += [[lower_perm, upper_perm]]
if (lower not in elem[(level + 1)]):
elem[(level + 1)].append(lower_perm)
level += 1
elem = [item for sublist in elem for item in sublist]
return Poset((elem, rel))
@staticmethod
def PermutationPatternOccurrenceInterval(bottom, top, pos):
'\n Return the poset consisting of an interval in the poset of\n permutations under pattern containment between ``bottom`` and\n ``top``, where a specified instance of ``bottom`` in ``top``\n must be maintained.\n\n INPUT:\n\n - ``bottom``, ``top`` -- permutations where ``top`` contains\n ``bottom`` as a pattern\n - ``pos`` -- a list of indices indicating a distinguished copy of\n ``bottom`` inside ``top`` (indexed starting at 0)\n\n For further information (and picture illustrating included example),\n see [ST2010]_ .\n\n See :wikipedia:`Permutation_pattern`.\n\n EXAMPLES::\n\n sage: t = Permutation([3,2,1])\n sage: b = Permutation([6,3,4,5,2,1])\n sage: A = posets.PermutationPatternOccurrenceInterval(t, b, (0,2,4)); A\n Finite poset containing 8 elements\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.permutation.Permutation.has_pattern`,\n :meth:`PermutationPattern`, :meth:`PermutationPatternInterval`\n '
P = Permutations()
top = P(top)
bottom = P(bottom)
if (not (to_standard([top[z] for z in pos]) == list(bottom))):
raise ValueError("cannot find 'bottom' in 'top' given by 'pos'")
elem = [[(top, pos)]]
level = 0
rel = []
while ((len(top) - len(bottom)) >= (level + 1)):
elem.append([])
for upper in elem[level]:
for i in range((len(top) - level)):
if (i in upper[1]):
continue
lower_perm = list(upper[0])
j = lower_perm.pop(i)
for e in range(((len(top) - level) - 1)):
if (lower_perm[e] > j):
lower_perm[e] = (lower_perm[e] - 1)
lower_pos = list(upper[1])
for f in range(len(upper[1])):
if (upper[1][f] > i):
lower_pos[f] = (upper[1][f] - 1)
rel += [[(P(lower_perm), tuple(lower_pos)), (P(upper[0]), upper[1])]]
if ((P(lower_perm), tuple(lower_pos)) not in elem[(level + 1)]):
elem[(level + 1)].append((P(lower_perm), tuple(lower_pos)))
level += 1
elem = [item for sublist in elem for item in sublist]
return Poset([elem, rel])
@staticmethod
def RibbonPoset(n, descents):
'\n Return a ribbon poset on ``n`` vertices with descents at ``descents``.\n\n INPUT:\n\n - ``n`` -- the number of vertices\n - ``descents`` -- an iterable; the indices on the ribbon where `y > x`\n\n EXAMPLES::\n\n sage: R = Posets.RibbonPoset(5, [1,2])\n sage: sorted(R.cover_relations())\n [[0, 1], [2, 1], [3, 2], [3, 4]]\n '
n = check_int(n)
return Mobile(DiGraph([list(range(n)), [(((i + 1), i) if (i in descents) else (i, (i + 1))) for i in range((n - 1))]]))
@staticmethod
def MobilePoset(ribbon, hangers, anchor=None):
'\n Return a mobile poset with the ribbon ``ribbon`` and\n with hanging d-complete posets specified in ``hangers``\n and a d-complete poset attached above, specified in ``anchor``.\n\n INPUT:\n\n - ``ribbon`` -- a finite poset that is a ribbon\n - ``hangers`` -- a dictionary mapping an element on the ribbon\n to a list of d-complete posets that it covers\n - ``anchor`` -- (optional) a ``tuple`` (``ribbon_elmt``,\n ``anchor_elmt``, ``anchor_poset``), where ``anchor_elmt`` covers\n ``ribbon_elmt``, and ``anchor_elmt`` is an acyclic element of\n ``anchor_poset``\n\n EXAMPLES::\n\n sage: R = Posets.RibbonPoset(5, [1,2])\n sage: H = Poset([[5, 6, 7], [(5, 6), (6,7)]])\n sage: M = Posets.MobilePoset(R, {3: [H]})\n sage: len(M.cover_relations())\n 7\n\n sage: P = posets.MobilePoset(posets.RibbonPoset(7, [1,3]),\n ....: {1: [posets.YoungDiagramPoset([3, 2], dual=True)],\n ....: 3: [posets.DoubleTailedDiamond(6)]},\n ....: anchor=(4, 2, posets.ChainPoset(6)))\n sage: len(P.cover_relations())\n 33\n '
elements = []
cover_relations = []
cover_relations.extend(ribbon.cover_relations())
elements.extend(ribbon._elements)
if anchor:
for cr in anchor[2].cover_relations():
cover_relations.append(((anchor[0], cr[0]), (anchor[0], cr[1])))
cover_relations.append((anchor[0], (anchor[0], anchor[1])))
for elmt in anchor[2]._elements:
elements.append((anchor[0], elmt))
for (r, hangs) in hangers.items():
for (i, h) in enumerate(hangs):
for v in h._elements:
elements.append((r, i, v))
for cr in h.cover_relations():
cover_relations.append(((r, i, cr[0]), (r, i, cr[1])))
cover_relations.append(((r, i, h.top()), r))
return Mobile(DiGraph([elements, cover_relations]))
|
def _random_lattice(n, p):
'\n Return a random lattice.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n - ``p`` -- a number at least zero and less than one; higher number\n means more covering relations\n\n OUTPUT:\n\n A list of lists. Interpreted as a list of lower covers\n for a poset, it is a lattice with ``0..n-1`` as a linear\n extension.\n\n EXAMPLES::\n\n sage: set_random_seed(42) # Results are reproducible\n sage: sage.combinat.posets.poset_examples._random_lattice(7, 0.4)\n [[], [0], [0], [1, 2], [1], [0], [3, 4, 5]]\n\n ALGORITHM::\n\n We add elements one by one. We check that adding a maximal\n element `e` to a meet-semilattice `L` with maximal elements\n `M` will create a semilattice by checking that there is a\n meet for `e, m` for all `m \\in M`. We do that by keeping\n track of meet matrix and list of maximal elements.\n '
from sage.functions.other import floor
from sage.misc.functional import sqrt
from sage.misc.prandom import random
n = (n - 1)
meets = [([None] * n) for _ in range(n)]
meets[0][0] = 0
maxs = set([0])
lc_all = [[]]
for i in range(1, n):
while True:
lc_list = [((i - 1) - floor((i * sqrt(random()))))]
while ((random() < p) and (0 not in lc_list)):
new = ((i - 1) - floor((i * sqrt(random()))))
if any(((meets[new][lc] in [new, lc]) for lc in lc_list)):
continue
lc_list.append(new)
if all((any((all(((meets[m][meets[a][a1]] == meets[m][a1]) for a1 in lc_list if (a1 != a))) for a in lc_list)) for m in maxs)):
break
maxs.difference_update(lc_list)
meets[i][i] = i
for lc in lc_list:
meets[i][lc] = meets[lc][i] = lc
for e in range(i):
meets[i][e] = meets[e][i] = max((meets[e][lc] for lc in lc_list))
maxs.add(i)
lc_all.append(lc_list)
lc_all.append(list(maxs))
return lc_all
|
def _random_dismantlable_lattice(n):
'\n Return a random dismantlable lattice on `n` elements.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n\n OUTPUT:\n\n A digraph that can be interpreted as the Hasse diagram of a random\n dismantlable lattice. It has `0` as the bottom element and `n-1` as\n the top element, but otherwise `0, \\ldots, n-1` *is not* usually a\n linear extension of the lattice.\n\n EXAMPLES::\n\n sage: set_random_seed(78) # Results are reproducible\n sage: D = sage.combinat.posets.poset_examples._random_dismantlable_lattice(10); D\n Digraph on 10 vertices\n sage: D.neighbors_in(8)\n [0]\n\n ALGORITHM::\n\n We add elements one by one by "de-dismantling", i.e. select\n a random pair of comparable elements and add a new element\n between them.\n '
from sage.misc.prandom import randint
D = DiGraph({0: [(n - 1)]})
for i in range(1, (n - 1)):
a = randint(0, (i // 2))
b_ = list(D.depth_first_search(a))
b = b_[randint(1, (len(b_) - 1))]
D.add_vertex(i)
D.add_edge(a, i)
D.add_edge(i, b)
D.delete_edge(a, b)
return D
|
def _random_planar_lattice(n):
'\n Return a random planar lattice on `n` elements.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n\n OUTPUT:\n\n A random planar lattice. It has `0` as the bottom\n element and `n-1` as the top element, but otherwise\n `0, \\ldots, n-1` *is not* usually a linear extension of\n the lattice.\n\n EXAMPLES::\n\n sage: set_random_seed(78) # Results are reproducible\n sage: D = sage.combinat.posets.poset_examples._random_planar_lattice(10); D\n Digraph on 10 vertices\n sage: D.neighbors_in(8)\n [1]\n\n ALGORITHM::\n\n Every planar lattice is dismantlable.\n\n We add elements one by one like when generating\n dismantlable lattices, and after every addition\n check that we still have a planar lattice.\n '
from sage.misc.prandom import randint
G = DiGraph({0: [(n - 1)]})
while (G.order() < n):
i = (G.order() - 1)
a = randint(0, (i // 2))
b_ = list(G.depth_first_search(a))
b = b_[randint(1, (len(b_) - 1))]
G1 = G.copy()
G.add_vertex(i)
G.add_edge(a, i)
G.add_edge(i, b)
G.delete_edge(a, b)
G2 = G.copy()
G2.add_edge((n - 1), 0)
if (not G2.is_planar()):
G = G1.copy()
return G
|
def _random_distributive_lattice(n):
"\n Return a random poset that has `n` antichains.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n\n OUTPUT:\n\n A random poset (as DiGraph) that has `n` antichains; i.e. a poset\n that's order ideals lattice has `n` elements.\n\n EXAMPLES::\n\n sage: g = sage.combinat.posets.poset_examples._random_distributive_lattice(10)\n sage: Poset(g).order_ideals_lattice(as_ideals=False).cardinality()\n 10\n\n ALGORITHM:\n\n Add elements until there are at least `n` antichains.\n Remove elements until there are at most `n` antichains.\n Repeat.\n "
from sage.combinat.posets.hasse_diagram import HasseDiagram
from copy import copy
from sage.combinat.subset import Subsets
from sage.graphs.digraph_generators import digraphs
if (n < 4):
return digraphs.Path((n - 1))
H = HasseDiagram({0: []})
while (sum((1 for _ in H.antichains_iterator())) < n):
D = copy(H)
newcover = Subsets(H).random_element()
new_element = H.order()
D.add_vertex(new_element)
for e in newcover:
D.add_edge(e, new_element)
D = D.transitive_reduction()
H = HasseDiagram(D)
while (sum((1 for _ in H.antichains_iterator())) > n):
D = copy(H)
to_delete = H.random_vertex()
for a in D.neighbors_in(to_delete):
for b in D.neighbors_out(to_delete):
D.add_edge(a, b)
D.delete_vertex(to_delete)
D.relabel({z: (z - 1) for z in range((to_delete + 1), (D.order() + 1))})
H = HasseDiagram(D)
return D
|
def _random_stone_lattice(n):
'\n Return a random Stone lattice on `n` elements.\n\n INPUT:\n\n - ``n`` -- number of elements, a non-negative integer\n\n OUTPUT:\n\n A random lattice (as a digraph) of `n` elements.\n\n EXAMPLES::\n\n sage: g = sage.combinat.posets.poset_examples._random_stone_lattice(10)\n sage: LatticePoset(g).is_stone()\n True\n\n ALGORITHM:\n\n Randomly split `n` to some factors. For every factor `p` generate\n a random distributive lattice on `p-1` elements and add a new bottom\n element to it. Compute the cartesian product of those lattices.\n '
from sage.arith.misc import factor
from sage.combinat.partition import Partitions
from sage.misc.misc_c import prod
from copy import copy
factors = sum([([f[0]] * f[1]) for f in factor(n)], [])
sage.misc.prandom.shuffle(factors)
part_lengths = list(Partitions(len(factors)).random_element())
parts = []
while part_lengths:
x = part_lengths.pop()
parts.append(prod(factors[:x]))
factors = factors[x:]
result = DiGraph(1)
for p in parts:
g = _random_distributive_lattice((p - 1))
g = copy(Poset(g).order_ideals_lattice(as_ideals=False)._hasse_diagram)
g.add_edge((- 1), 0)
result = result.cartesian_product(g)
result.relabel()
return result
|
def Poset(data=None, element_labels=None, cover_relations=False, linear_extension=False, category=None, facade=None, key=None):
'\n Construct a finite poset from various forms of input data.\n\n INPUT:\n\n - ``data`` -- different input are accepted by this constructor:\n\n 1. A two-element list or tuple ``(E, R)``, where ``E`` is a\n collection of elements of the poset and ``R`` is a collection\n of relations ``x <= y``, each represented as a two-element\n list/tuple/iterable such as ``[x, y]``. The poset is then\n the transitive closure of the provided relations. If\n ``cover_relations=True``, then ``R`` is assumed to contain\n exactly the cover relations of the poset. If ``E`` is empty,\n then ``E`` is taken to be the set of elements appearing in\n the relations ``R``.\n\n 2. A two-element list or tuple ``(E, f)``, where ``E`` is the set\n of elements of the poset and ``f`` is a function such that,\n for any pair ``x, y`` of elements of ``E``, ``f(x, y)``\n returns whether ``x <= y``. If ``cover_relations=True``, then\n ``f(x, y)`` should instead return whether ``x`` is covered by\n ``y``.\n\n 3. A dictionary of upper covers: ``data[x]`` is\n a list of the elements that cover the element `x` in the poset.\n\n 4. A list or tuple of upper covers: ``data[x]`` is\n a list of the elements that cover the element `x` in the poset.\n\n If the set of elements is not a set of consecutive integers\n starting from zero, then:\n\n - every element must appear in the data, for example in its own entry.\n - ``data`` must be ordered in the same way as sorted elements.\n\n .. WARNING::\n\n If data is a list or tuple of length `2`, then it is\n handled by the case 2 above.\n\n 5. An acyclic, loop-free and multi-edge free ``DiGraph``. If\n ``cover_relations`` is ``True``, then the edges of the\n digraph are assumed to correspond to the cover relations of\n the poset. Otherwise, the cover relations are computed.\n\n 6. A previously constructed poset (the poset itself is returned).\n\n - ``element_labels`` -- (default: ``None``); an optional list or\n dictionary of objects that label the poset elements.\n\n - ``cover_relations`` -- a boolean (default: ``False``); whether the\n data can be assumed to describe a directed acyclic graph whose\n arrows are cover relations; otherwise, the cover relations are\n first computed.\n\n - ``linear_extension`` -- a boolean (default: ``False``); whether to\n use the provided list of elements as default linear extension\n for the poset; otherwise a linear extension is computed. If the data\n is given as the pair ``(E, f)``, then ``E`` is taken to be the linear\n extension.\n\n - ``facade`` -- a boolean or ``None`` (default); whether the\n :meth:`Poset`\'s elements should be wrapped to make them aware of the\n Poset they belong to.\n\n * If ``facade = True``, the :meth:`Poset`\'s elements are exactly those\n given as input.\n\n * If ``facade = False``, the :meth:`Poset`\'s elements will become\n :class:`~sage.combinat.posets.posets.PosetElement` objects.\n\n * If ``facade = None`` (default) the expected behaviour is the behaviour\n of ``facade = True``, unless the opposite can be deduced from the\n context (i.e. for instance if a :meth:`Poset` is built from another\n :meth:`Poset`, itself built with ``facade = False``)\n\n OUTPUT:\n\n ``FinitePoset`` -- an instance of the :class:`FinitePoset` class.\n\n If ``category`` is specified, then the poset is created in this\n category instead of :class:`FinitePosets`.\n\n .. SEEALSO::\n\n :class:`Posets`, :class:`~sage.categories.posets.Posets`,\n :class:`FinitePosets`\n\n EXAMPLES:\n\n 1. Elements and cover relations::\n\n sage: elms = [1,2,3,4,5,6,7]\n sage: rels = [[1,2],[3,4],[4,5],[2,5]]\n sage: Poset((elms, rels), cover_relations = True, facade = False)\n Finite poset containing 7 elements\n\n Elements and non-cover relations::\n\n sage: elms = [1,2,3,4]\n sage: rels = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n sage: P = Poset( [elms,rels] ,cover_relations=False); P\n Finite poset containing 4 elements\n sage: P.cover_relations()\n [[1, 2], [2, 3], [3, 4]]\n\n 2. Elements and function: the standard permutations of [1, 2, 3, 4]\n with the Bruhat order::\n\n sage: elms = Permutations(4)\n sage: fcn = lambda p,q : p.bruhat_lequal(q)\n sage: Poset((elms, fcn))\n Finite poset containing 24 elements\n\n With a function that identifies the cover relations: the set\n partitions of `\\{1, 2, 3\\}` ordered by refinement::\n\n sage: # needs sage.combinat\n sage: elms = SetPartitions(3)\n sage: def fcn(A, B):\n ....: if len(A) != len(B)+1:\n ....: return False\n ....: for a in A:\n ....: if not any(set(a).issubset(b) for b in B):\n ....: return False\n ....: return True\n sage: Poset((elms, fcn), cover_relations=True)\n Finite poset containing 5 elements\n\n 3. A dictionary of upper covers::\n\n sage: Poset({\'a\':[\'b\',\'c\'], \'b\':[\'d\'], \'c\':[\'d\'], \'d\':[]})\n Finite poset containing 4 elements\n\n 4. A list of upper covers, with range(5) as set of vertices::\n\n sage: Poset([[1,2],[4],[3],[4],[]])\n Finite poset containing 5 elements\n\n A list of upper covers, with letters as vertices::\n\n sage: Poset([["a","b"],["b","c"],["c"]])\n Finite poset containing 3 elements\n\n A list of upper covers and a dictionary of labels::\n\n sage: elm_labs = {0:"a",1:"b",2:"c",3:"d",4:"e"}\n sage: P = Poset([[1,2],[4],[3],[4],[]], elm_labs, facade=False)\n sage: P.list()\n [a, b, c, d, e]\n\n .. WARNING::\n\n The special case where the argument data is a list or tuple of\n length 2 is handled by the case 2. So you cannot use this\n method to input a 2-element poset.\n\n 5. An acyclic DiGraph.\n\n ::\n\n sage: dag = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: Poset(dag)\n Finite poset containing 6 elements\n\n Any directed acyclic graph without loops or multiple edges, as long\n as ``cover_relations=False``::\n\n sage: dig = DiGraph({0:[2,3], 1:[3,4,5], 2:[5], 3:[5], 4:[5]})\n sage: dig.allows_multiple_edges()\n False\n sage: dig.allows_loops()\n False\n sage: dig.transitive_reduction() == dig\n False\n sage: Poset(dig, cover_relations=False)\n Finite poset containing 6 elements\n sage: Poset(dig, cover_relations=True)\n Traceback (most recent call last):\n ...\n ValueError: Hasse diagram is not transitively reduced\n\n .. rubric:: Default Linear extension\n\n Every poset `P` obtained with ``Poset`` comes equipped with a\n default linear extension, which is also used for enumerating\n its elements. By default, this linear extension is computed,\n and has no particular significance::\n\n sage: P = Poset((divisors(12), attrcall("divides")))\n sage: P.list()\n [1, 2, 4, 3, 6, 12]\n sage: P.linear_extension()\n [1, 2, 4, 3, 6, 12]\n\n You may enforce a specific linear extension using the\n ``linear_extension`` option::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: P.linear_extension()\n [1, 2, 3, 4, 6, 12]\n\n Depending on popular request, ``Poset`` might eventually get\n modified to always use the provided list of elements as\n default linear extension, when it is one.\n\n .. SEEALSO:: :meth:`FinitePoset.linear_extensions`\n\n .. rubric:: Facade posets\n\n When ``facade = False``, the elements of a poset are wrapped so as to make\n them aware that they belong to that poset::\n\n sage: P = Poset(DiGraph({\'d\':[\'c\',\'b\'],\'c\':[\'a\'],\'b\':[\'a\']}), facade = False)\n sage: d,c,b,a = list(P)\n sage: a.parent() is P\n True\n\n This allows for comparing elements according to `P`::\n\n sage: c < a\n True\n\n However, this may have surprising effects::\n\n sage: my_elements = [\'a\',\'b\',\'c\',\'d\']\n sage: any(x in my_elements for x in P)\n False\n\n and can be annoying when one wants to manipulate the elements of\n the poset::\n\n sage: a + b\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand parent(s) for +: \'Finite poset containing 4 elements\' and \'Finite poset containing 4 elements\'\n sage: a.element + b.element\n \'ab\'\n\n By default, facade posets are constructed instead::\n\n sage: P = Poset(DiGraph({\'d\':[\'c\',\'b\'],\'c\':[\'a\'],\'b\':[\'a\']}))\n\n In this example, the elements of the poset remain plain strings::\n\n sage: d,c,b,a = list(P)\n sage: type(a)\n <class \'str\'>\n\n Of course, those strings are not aware of `P`. So to compare two\n such strings, one needs to query `P`::\n\n sage: a < b\n True\n sage: P.lt(a,b)\n False\n\n which models the usual mathematical notation `a <_P b`.\n\n Most operations seem to still work, but at this point there is no\n guarantee whatsoever::\n\n sage: P.list()\n [\'d\', \'c\', \'b\', \'a\']\n sage: P.principal_order_ideal(\'a\')\n [\'d\', \'c\', \'b\', \'a\']\n sage: P.principal_order_ideal(\'b\')\n [\'d\', \'b\']\n sage: P.principal_order_ideal(\'d\')\n [\'d\']\n sage: TestSuite(P).run()\n\n .. WARNING::\n\n :class:`DiGraph` is used to construct the poset, and the\n vertices of a :class:`DiGraph` are converted to plain Python\n :class:`int`\'s if they are :class:`Integer`\'s::\n\n sage: G = DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]})\n sage: type(G.vertices(sort=True)[0])\n <class \'int\'>\n\n This is worked around by systematically converting back the\n vertices of a poset to :class:`Integer`\'s if they are\n :class:`int`\'s::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = False)\n sage: type(P.an_element().element)\n <class \'sage.rings.integer.Integer\'>\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade=True)\n sage: type(P.an_element())\n <class \'sage.rings.integer.Integer\'>\n\n This may be abusive::\n\n sage: P = Poset((range(5), operator.le), facade = True)\n sage: P.an_element().parent()\n Integer Ring\n\n .. rubric:: Unique representation\n\n As most parents, :class:`Poset` have unique representation (see\n :class:`UniqueRepresentation`). Namely if two posets are created\n from two equal data, then they are not only equal but actually\n identical::\n\n sage: data1 = [[1,2],[3],[3]]\n sage: data2 = [[1,2],[3],[3]]\n sage: P1 = Poset(data1)\n sage: P2 = Poset(data2)\n sage: P1 == P2\n True\n sage: P1 is P2\n True\n\n In situations where this behaviour is not desired, one can use the\n ``key`` option::\n\n sage: P1 = Poset(data1, key = "foo")\n sage: P2 = Poset(data2, key = "bar")\n sage: P1 is P2\n False\n sage: P1 == P2\n False\n\n ``key`` can be any hashable value and is passed down to\n :class:`UniqueRepresentation`. It is otherwise ignored by the\n poset constructor.\n\n TESTS::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: type(hash(P))\n <class \'int\'>\n\n Bad input::\n\n sage: Poset([1,2,3], lambda x,y : x<y)\n Traceback (most recent call last):\n ...\n TypeError: element_labels should be a dict or a list if different\n from None. (Did you intend data to be equal to a pair ?)\n\n Another kind of bad input, digraphs with oriented cycles::\n\n sage: Poset(DiGraph([[1,2],[2,3],[3,4],[4,1]]))\n Traceback (most recent call last):\n ...\n ValueError: The graph is not directed acyclic\n\n Some more bad input, an element list with duplicates while\n ``linear_extension=True``::\n\n sage: Poset(( [1,2,3,3], [[1,2]]), linear_extension=True)\n Traceback (most recent call last):\n ...\n ValueError: the provided list of elements is not a linear extension\n for the poset as it contains duplicate elements\n '
if (not ((element_labels is None) or isinstance(element_labels, (dict, 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 ?)')
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
elif (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)
elements = None
D = {}
if (data is None):
D = DiGraph()
elif isinstance(data, DiGraph):
D = data.copy(immutable=True)
elif isinstance(data, dict):
D = DiGraph(data, format='dict_of_lists')
elif isinstance(data, (list, tuple)):
if (len(data) == 2):
if callable(data[1]):
(elements, function) = data
relations = [[x, y] for x in elements for y in elements if function(x, y)]
else:
(elements, relations) = data
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):
vertices = sorted(set((x for item in data for x in item)))
if (len(vertices) != len(data)):
vertices = 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')
assert isinstance(D, DiGraph), 'BUG: D should be a digraph.'
if (not cover_relations):
from sage.graphs.generic_graph_pyx import transitive_reduction_acyclic
D = transitive_reduction_acyclic(D)
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 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):
try:
elements = D.topological_sort()
except TypeError:
raise ValueError('Hasse diagram contains cycles')
elif (len(elements) != len(set(elements))):
raise ValueError('the provided list of elements is not a linear extension for the poset as it contains duplicate elements')
else:
elements = None
return FinitePoset(D, elements=elements, category=category, facade=facade, key=key)
|
class FinitePoset(UniqueRepresentation, Parent):
'\n A (finite) `n`-element poset constructed from a directed acyclic graph.\n\n INPUT:\n\n - ``hasse_diagram`` -- an instance of\n :class:`~sage.combinat.posets.posets.FinitePoset`, or a\n :class:`DiGraph` that is transitively-reduced, acyclic,\n loop-free, and multiedge-free.\n\n - ``elements`` -- an optional list of elements, with ``element[i]``\n corresponding to vertex ``i``. If ``elements`` is ``None``, then it is\n set to be the vertex set of the digraph. Note that if this option is set,\n then ``elements`` is considered as a specified linear extension of the poset\n and the `linear_extension` attribute is set.\n\n - ``category`` -- :class:`FinitePosets`, or a subcategory thereof.\n\n - ``facade`` -- a boolean or ``None`` (default); whether the\n :class:`~sage.combinat.posets.posets.FinitePoset`\'s elements should be\n wrapped to make them aware of the Poset they belong to.\n\n * If ``facade = True``, the\n :class:`~sage.combinat.posets.posets.FinitePoset`\'s elements are exactly\n those given as input.\n\n * If ``facade = False``, the\n :class:`~sage.combinat.posets.posets.FinitePoset`\'s elements will become\n :class:`~sage.combinat.posets.posets.PosetElement` objects.\n\n * If ``facade = None`` (default) the expected behaviour is the behaviour\n of ``facade = True``, unless the opposite can be deduced from the\n context (i.e. for instance if a\n :class:`~sage.combinat.posets.posets.FinitePoset` is built from another\n :class:`~sage.combinat.posets.posets.FinitePoset`, itself built with\n ``facade = False``)\n\n - ``key`` -- any hashable value (default: ``None``).\n\n EXAMPLES::\n\n sage: uc = [[2,3], [], [1], [1], [1], [3,4]]\n sage: from sage.combinat.posets.posets import FinitePoset\n sage: P = FinitePoset(DiGraph(dict([[i,uc[i]] for i in range(len(uc))])), facade=False); P\n Finite poset containing 6 elements\n sage: P.cover_relations()\n [[5, 4], [5, 3], [4, 1], [0, 2], [0, 3], [2, 1], [3, 1]]\n sage: TestSuite(P).run()\n sage: P.category()\n Category of finite enumerated posets\n sage: P.__class__\n <class \'sage.combinat.posets.posets.FinitePoset_with_category\'>\n\n sage: Q = sage.combinat.posets.posets.FinitePoset(P, facade = False); Q\n Finite poset containing 6 elements\n\n sage: Q is P\n True\n\n We keep the same underlying Hasse diagram, but change the elements::\n\n sage: Q = sage.combinat.posets.posets.FinitePoset(P, elements=[1,2,3,4,5,6], facade=False); Q\n Finite poset containing 6 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 5], [2, 6], [3, 4], [3, 5], [4, 6], [5, 6]]\n\n We test the facade argument::\n\n sage: P = Poset(DiGraph({\'a\':[\'b\'],\'b\':[\'c\'],\'c\':[\'d\']}), facade=False)\n sage: P.category()\n Category of finite enumerated posets\n sage: parent(P[0]) is P\n True\n\n sage: Q = Poset(DiGraph({\'a\':[\'b\'],\'b\':[\'c\'],\'c\':[\'d\']}), facade=True)\n sage: Q.category()\n Category of facade finite enumerated posets\n sage: parent(Q[0]) is str\n True\n sage: TestSuite(Q).run(skip = [\'_test_an_element\']) # is_parent_of is not yet implemented\n\n Changing a non facade poset to a facade poset::\n\n sage: PQ = Poset(P, facade=True)\n sage: PQ.category()\n Category of facade finite enumerated posets\n sage: parent(PQ[0]) is str\n True\n sage: PQ is Q\n True\n\n Changing a facade poset to a non facade poset::\n\n sage: QP = Poset(Q, facade = False)\n sage: QP.category()\n Category of finite enumerated posets\n sage: parent(QP[0]) is QP\n True\n\n Conversion to some other software is possible::\n\n sage: P = posets.TamariLattice(3)\n sage: libgap(P) # optional - gap_package_qpa\n <A poset on 5 points>\n\n sage: P = Poset({1:[2],2:[]})\n sage: macaulay2(\'needsPackage "Posets"\') # optional - macaulay2\n Posets\n sage: macaulay2(P) # optional - macaulay2\n Relation Matrix: | 1 1 |\n | 0 1 |\n\n .. NOTE::\n\n A class that inherits from this class needs to define\n ``Element``. This is the class of the elements that the inheriting\n class contains. For example, for this class, ``FinitePoset``,\n ``Element`` is ``PosetElement``. It can also define ``_dual_class`` which\n is the class of dual posets of this\n class. E.g. ``FiniteMeetSemilattice._dual_class`` is\n ``FiniteJoinSemilattice``.\n\n TESTS:\n\n Equality is derived from :class:`UniqueRepresentation`. We check that this\n gives consistent results::\n\n sage: P = Poset([[1,2],[3],[3]])\n sage: P == P\n True\n sage: Q = Poset([[1,2],[],[1]])\n sage: Q == P\n False\n sage: p1, p2 = Posets(2).list()\n sage: p2 == p1, p1 != p2\n (False, True)\n sage: [[p1.__eq__(p2) for p1 in Posets(2)] for p2 in Posets(2)]\n [[True, False], [False, True]]\n sage: [[p2.__eq__(p1) for p1 in Posets(2)] for p2 in Posets(2)]\n [[True, False], [False, True]]\n sage: [[p2 == p1 for p1 in Posets(3)] for p2 in Posets(3)]\n [[True, False, False, False, False],\n [False, True, False, False, False],\n [False, False, True, False, False],\n [False, False, False, True, False],\n [False, False, False, False, True]]\n\n sage: [[p1.__ne__(p2) for p1 in Posets(2)] for p2 in Posets(2)]\n [[False, True], [True, False]]\n sage: P = Poset([[1,2,4],[3],[3]])\n sage: Q = Poset([[1,2],[],[1],[4]])\n sage: P != Q\n True\n sage: P != P\n False\n sage: Q != Q\n False\n sage: [[p1.__ne__(p2) for p1 in Posets(2)] for p2 in Posets(2)]\n [[False, True], [True, False]]\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: Q = Poset(P)\n sage: Q == P\n False\n sage: Q = Poset(P, linear_extension=True)\n sage: Q == P\n True\n '
_lin_ext_type = LinearExtensionsOfPoset
_desc = 'Finite poset'
@staticmethod
def __classcall__(cls, hasse_diagram, elements=None, category=None, facade=None, key=None):
"\n Normalizes the arguments passed to the constructor.\n\n INPUT:\n\n - ``hasse_diagram`` -- a :class:`DiGraph` or a :class:`FinitePoset`\n that is labeled by the elements of the poset\n - ``elements`` -- (default: ``None``) the default linear extension\n or ``None`` if no such default linear extension is wanted\n - ``category`` -- (optional) a subcategory of :class:`FinitePosets`\n - ``facade`` -- (optional) boolean if this is a facade parent or not\n - ``key`` -- (optional) a key value\n\n TESTS::\n\n sage: P = sage.combinat.posets.posets.FinitePoset(DiGraph())\n sage: type(P)\n <class 'sage.combinat.posets.posets.FinitePoset_with_category'>\n sage: TestSuite(P).run()\n\n See also the extensive tests in the class documentation.\n\n We check that :trac:`17059` is fixed::\n\n sage: p = Poset()\n sage: p is Poset(p, category=p.category())\n True\n "
assert isinstance(hasse_diagram, (FinitePoset, DiGraph))
if isinstance(hasse_diagram, FinitePoset):
poset = hasse_diagram
if (category is None):
category = poset.category()
if (facade is None):
facade = (poset in Sets().Facade())
if (elements is None):
relabel = {i: x for (i, x) in enumerate(poset._elements)}
else:
elements = tuple(elements)
relabel = {i: x for (i, x) in enumerate(elements)}
hasse_diagram = poset._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)
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().__classcall__(cls, hasse_diagram=hasse_diagram, elements=elements, category=category, facade=facade, key=key)
def __init__(self, hasse_diagram, elements, category, facade, key):
"\n EXAMPLES::\n\n sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = False)\n sage: type(P)\n <class 'sage.combinat.posets.posets.FinitePoset_with_category'>\n\n The internal data structure currently consists of:\n\n - the Hasse diagram of the poset, represented by a DiGraph\n with vertices labelled 0,...,n-1 according to a linear\n extension of the poset (that is if `i \\mapsto j` is an edge\n then `i<j`), together with some extra methods (see\n :class:`sage.combinat.posets.hasse_diagram.HasseDiagram`)::\n\n sage: P._hasse_diagram\n Hasse diagram of a poset containing 4 elements\n sage: P._hasse_diagram.cover_relations()\n [(0, 1), (1, 2), (2, 3)]\n\n - a tuple of the original elements, not wrapped as elements of\n ``self`` (but see also ``P._list``)::\n\n sage: P._elements\n ('a', 'b', 'c', 'd')\n\n ``P._elements[i]`` gives the element of ``P`` corresponding\n to the vertex ``i``\n\n - a dictionary mapping back elements to vertices::\n\n sage: P._element_to_vertex_dict\n {'a': 0, 'b': 1, 'c': 2, 'd': 3}\n\n - and a boolean stating whether the poset is a facade poset::\n\n sage: P._is_facade\n False\n\n This internal data structure is subject to change at any\n point. Do not break encapsulation!\n\n TESTS::\n\n sage: TestSuite(P).run()\n\n See also the extensive tests in the class documentation.\n "
Parent.__init__(self, category=category, facade=facade)
if (elements is None):
self._with_linear_extension = False
try:
elements = tuple(hasse_diagram.topological_sort())
except TypeError:
raise ValueError('Hasse diagram contains cycles')
else:
self._with_linear_extension = True
self._elements = tuple(((Integer(i) if isinstance(i, int) else i) for i in elements))
rdict = {self._elements[i]: i for i in range(len(self._elements))}
self._hasse_diagram = HasseDiagram(hasse_diagram.relabel(rdict, inplace=False), data_structure='static_sparse')
self._element_to_vertex_dict = {self._elements[i]: i for i in range(len(self._elements))}
self._is_facade = facade
@lazy_attribute
def _list(self):
"\n The list of the elements of ``self``, each wrapped to have\n ``self`` as parent\n\n EXAMPLES::\n\n sage: P = Poset(DiGraph({'a':['b'],'b':['c'],'c':['d']}), facade = False)\n sage: L = P._list; L\n (a, b, c, d)\n sage: type(L[0])\n <class 'sage.combinat.posets.posets.FinitePoset_with_category.element_class'>\n sage: L[0].parent() is P\n True\n\n Constructing them once for all makes future conversions\n between the vertex id and the element faster. This also\n ensures unique representation of the elements of this poset,\n which could be used to later speed up certain operations\n (equality test, ...)\n "
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))))
Element = PosetElement
def _element_to_vertex(self, element):
'\n Given an element of the poset (wrapped or not), returns the\n corresponding vertex of the Hasse diagram.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(15), attrcall("divides")))\n sage: list(P)\n [1, 3, 5, 15]\n sage: x = P(5)\n sage: P._element_to_vertex(x)\n 2\n\n The same with a non-wrapped element of `P`::\n\n sage: P._element_to_vertex(5)\n 2\n\n TESTS::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = False)\n\n Testing for wrapped elements::\n\n sage: all(P._vertex_to_element(P._element_to_vertex(x)) is x for x in P)\n True\n\n Testing for non-wrapped elements::\n\n sage: all(P._vertex_to_element(P._element_to_vertex(x)) is P(x) for x in divisors(15))\n True\n\n Testing for non-wrapped elements for a facade poset::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = True)\n sage: all(P._vertex_to_element(P._element_to_vertex(x)) is x for x in P)\n True\n '
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):
'\n Return the element of ``self`` corresponding to the vertex\n ``vertex`` of the Hasse diagram.\n\n It is wrapped if ``self`` is not a facade poset.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = False)\n sage: x = P._vertex_to_element(2)\n sage: x\n 5\n sage: x.parent() is P\n True\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = True)\n sage: x = P._vertex_to_element(2)\n sage: x\n 5\n sage: x.parent() is ZZ\n True\n '
return self._list[vertex]
def unwrap(self, element):
'\n Return the element ``element`` of the poset ``self`` in\n unwrapped form.\n\n INPUT:\n\n - ``element`` -- an element of ``self``\n\n EXAMPLES::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = False)\n sage: x = P.an_element(); x\n 1\n sage: x.parent()\n Finite poset containing 4 elements\n sage: P.unwrap(x)\n 1\n sage: P.unwrap(x).parent()\n Integer Ring\n\n For a non facade poset, this is equivalent to using the\n ``.element`` attribute::\n\n sage: P.unwrap(x) is x.element\n True\n\n For a facade poset, this does nothing::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade=True)\n sage: x = P.an_element()\n sage: P.unwrap(x) is x\n True\n\n This method is useful in code where we do not know if ``P`` is\n a facade poset or not.\n '
if self._is_facade:
return element
else:
return element.element
def __contains__(self, x):
'\n Return ``True`` if ``x`` is an element of the poset.\n\n TESTS::\n\n sage: from sage.combinat.posets.posets import FinitePoset\n sage: P5 = FinitePoset(DiGraph({(5,):[(4,1),(3,2)],\n ....: (4,1):[(3,1,1),(2,2,1)],\n ....: (3,2):[(3,1,1),(2,2,1)],\n ....: (3,1,1):[(2,1,1,1)],\n ....: (2,2,1):[(2,1,1,1)],\n ....: (2,1,1,1):[(1,1,1,1,1)],\n ....: (1,1,1,1,1):[]}))\n sage: x = P5.list()[3]\n sage: x in P5\n True\n\n For the sake of speed, an element with the right class and\n parent is assumed to be in this parent. This can possibly be\n counterfeited by feeding garbage to the constructor::\n\n sage: x = P5.element_class(P5, "a", 5)\n sage: x in P5\n True\n '
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):
'\n Constructs an element of ``self``\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.posets import FinitePoset\n sage: P = FinitePoset(DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]}), facade = False)\n sage: P(5)\n 5\n sage: Q = FinitePoset(DiGraph({5:[2,3], 1:[3,4], 2:[0], 3:[0], 4:[0]}), facade = False)\n sage: Q(5)\n 5\n\n Accessing the ``i``-th element of ``self`` as ``P[i]``::\n\n sage: P = FinitePoset(DiGraph({\'a\':[\'b\',\'c\'], \'b\':[\'d\'], \'c\':[\'d\'], \'d\':[]}), facade = False)\n sage: P(\'a\') == P[0]\n True\n sage: P(\'d\') == P[-1]\n True\n\n TESTS::\n\n sage: P = Poset(DiGraph({0:[2,3], 1:[3,4], 2:[5], 3:[5], 4:[5]}), facade = False)\n sage: all(P(x) is x for x in P)\n True\n sage: P = Poset((divisors(15), attrcall("divides")), facade = True)\n sage: all(P(x) is x for x in P)\n True\n '
try:
return self._list[self._element_to_vertex_dict[element]]
except KeyError:
raise ValueError(('%s is not an element of this poset' % type(element)))
def __call__(self, element):
"\n Creates elements of this poset\n\n This overrides the generic call method for all parents\n :meth:`Parent.__call__`, as a work around to allow for facade\n posets over plain Python objects (e.g. Python's\n int's). Indeed, the default __call__ method expects the result\n of :meth:`_element_constructor_` to be a Sage element (see\n :meth:`sage.structure.coerce_maps.DefaultConvertMap_unique._call_`)::\n\n sage: P = Poset(DiGraph({'d':['c','b'],'c':['a'],'b':['a']}),\n ....: facade = True)\n sage: P('a') # indirect doctest\n 'a'\n sage: TestSuite(P).run()\n sage: P = Poset(((False, True), operator.eq), facade = True)\n sage: P(True)\n 1\n "
if (self._is_facade and (element in self._element_to_vertex_dict)):
return element
return super().__call__(element)
def hasse_diagram(self):
'\n Return the Hasse diagram of the poset as a Sage :class:`DiGraph`.\n\n The Hasse diagram is a directed graph where vertices are the\n elements of the poset and there is an edge from `u` to `v`\n whenever `v` covers `u` in the poset.\n\n If ``dot2tex`` is installed, then this sets the Hasse diagram\'s latex\n options to use the ``dot2tex`` formatting.\n\n EXAMPLES::\n\n sage: P = posets.DivisorLattice(12)\n sage: H = P.hasse_diagram(); H\n Digraph on 6 vertices\n sage: P.cover_relations()\n [[1, 2], [1, 3], [2, 4], [2, 6], [3, 6], [4, 12], [6, 12]]\n sage: H.edges(sort=True, labels=False)\n [(1, 2), (1, 3), (2, 4), (2, 6), (3, 6), (4, 12), (6, 12)]\n\n TESTS::\n\n sage: Poset().hasse_diagram()\n Digraph on 0 vertices\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade=True)\n sage: H = P.hasse_diagram()\n sage: H.vertices(sort=True)\n [1, 3, 5, 15]\n sage: H.edges(sort=True)\n [(1, 3, None), (1, 5, None), (3, 15, None), (5, 15, None)]\n sage: H.set_latex_options(format="dot2tex")\n sage: view(H) # optional - dot2tex, not tested (opens external window)\n '
G = DiGraph(self._hasse_diagram).relabel(self._list, inplace=False)
from sage.graphs.dot2tex_utils import have_dot2tex
if have_dot2tex():
G.set_latex_options(format='dot2tex', prog='dot', rankdir='up')
return G
def _latex_(self):
'\n Return a latex method for the poset.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2], [[1,2]]), cover_relations = True)\n sage: print(P._latex_()) # optional - dot2tex graphviz\n \\begin{tikzpicture}[>=latex,line join=bevel,]\n %%\n \\node (node_...) at (...bp,...bp) [draw,draw=none] {$...$};\n \\node (node_...) at (...bp,...bp) [draw,draw=none] {$...$};\n \\draw [black,->] (node_...) ..controls (...bp,...bp) and (...bp,...bp) .. (node_...);\n %\n \\end{tikzpicture}\n '
return self.hasse_diagram()._latex_()
def _repr_(self):
"\n Return a string representation of the poset.\n\n TESTS::\n\n sage: partitions_of_five = {(5,):[(4,1),(3,2)],\n ....: (4,1):[(3,1,1),(2,2,1)],\n ....: (3,2):[(3,1,1),(2,2,1)],\n ....: (3,1,1):[(2,1,1,1)],\n ....: (2,2,1):[(2,1,1,1)],\n ....: (2,1,1,1):[(1,1,1,1,1)],\n ....: (1,1,1,1,1):[]}\n sage: P5 = Poset(partitions_of_five)\n sage: P5._repr_()\n 'Finite poset containing 7 elements'\n\n sage: M = MeetSemilattice([[1,2],[3],[3]])\n sage: M._repr_()\n 'Finite meet-semilattice containing 3 elements'\n "
s = f'{self._desc} containing {self._hasse_diagram.order()} elements'
if self._with_linear_extension:
s += ' with distinguished linear extension'
return s
def _rich_repr_(self, display_manager, **kwds):
"\n Rich Output Magic Method\n\n See :mod:`sage.repl.rich_output` for details.\n\n EXAMPLES::\n\n sage: from sage.repl.rich_output import get_display_manager\n sage: dm = get_display_manager()\n sage: Poset()._rich_repr_(dm, edge_labels=True)\n OutputPlainText container\n\n The ``supplemental_plot`` preference lets us control whether\n this object is shown as text or picture+text::\n\n sage: dm.preferences.supplemental_plot\n 'never'\n sage: del dm.preferences.supplemental_plot\n sage: posets.ChainPoset(20)\n Finite lattice containing 20 elements (use the .plot() method to plot)\n sage: dm.preferences.supplemental_plot = 'never'\n "
prefs = display_manager.preferences
is_small = (0 < self.cardinality() < 20)
can_plot = (prefs.supplemental_plot != 'never')
plot_graph = (can_plot and ((prefs.supplemental_plot == 'always') or is_small))
if plot_graph:
plot_kwds = dict(kwds)
plot_kwds.setdefault('title', repr(self))
output = self.plot(**plot_kwds)._rich_repr_(display_manager)
if (output is not None):
return output
if can_plot:
text = f'{repr(self)} (use the .plot() method to plot)'
else:
text = repr(self)
tp = display_manager.types
if ((prefs.text == 'latex') and (tp.OutputLatex in display_manager.supported_output())):
return tp.OutputLatex(f' ext{{{text}}}')
return tp.OutputPlainText(text)
def __iter__(self):
'\n Iterates through the elements of a linear extension of the poset.\n\n EXAMPLES::\n\n sage: D = Poset({ 0:[1,2], 1:[3], 2:[3,4] })\n sage: sorted(D.__iter__())\n [0, 1, 2, 3, 4]\n '
return iter(self._list)
def sorted(self, l, allow_incomparable=True, remove_duplicates=False):
'\n Return the list `l` sorted by the poset.\n\n INPUT:\n\n - ``l`` -- a list of elements of the poset\n - ``allow_incomparable`` -- a Boolean. If ``True`` (the default),\n return incomparable elements in some order; if ``False``, raise\n an error if ``l`` is not a chain of the poset.\n - ``remove_duplicates`` - a Boolean. If ``True``, remove duplicates\n from the output list.\n\n EXAMPLES::\n\n sage: P = posets.DivisorLattice(36)\n sage: P.sorted([1, 4, 1, 6, 2, 12]) # Random order for 4 and 6\n [1, 1, 2, 4, 6, 12]\n sage: P.sorted([1, 4, 1, 6, 2, 12], remove_duplicates=True)\n [1, 2, 4, 6, 12]\n sage: P.sorted([1, 4, 1, 6, 2, 12], allow_incomparable=False)\n Traceback (most recent call last):\n ...\n ValueError: the list contains incomparable elements\n\n sage: P = Poset({7:[1, 5], 1:[2, 6], 5:[3], 6:[3, 4]})\n sage: P.sorted([4, 1, 4, 5, 7]) # Random order for 1 and 5\n [7, 1, 5, 4, 4]\n sage: P.sorted([1, 4, 4, 7], remove_duplicates=True)\n [7, 1, 4]\n sage: P.sorted([4, 1, 4, 5, 7], allow_incomparable=False)\n Traceback (most recent call last):\n ...\n ValueError: the list contains incomparable elements\n\n TESTS::\n\n sage: P = posets.PentagonPoset()\n sage: P.sorted([], allow_incomparable=True, remove_duplicates=True)\n []\n sage: P.sorted([], allow_incomparable=False, remove_duplicates=True)\n []\n sage: P.sorted([], allow_incomparable=True, remove_duplicates=False)\n []\n sage: P.sorted([], allow_incomparable=False, remove_duplicates=False)\n []\n '
v = [self._element_to_vertex(x) for x in l]
if remove_duplicates:
v = set(v)
o = sorted(v)
if (not allow_incomparable):
H = self._hasse_diagram
if (not all((H.is_lequal(a, b) for (a, b) in zip(o, o[1:])))):
raise ValueError('the list contains incomparable elements')
return [self._vertex_to_element(x) for x in o]
def linear_extension(self, linear_extension=None, check=True):
'\n Return a linear extension of this poset.\n\n A linear extension of a finite poset `P` of size `n` is a total\n ordering `\\pi := \\pi_0 \\pi_1 \\ldots \\pi_{n-1}` of its elements\n such that `i<j` whenever `\\pi_i < \\pi_j` in the poset `P`.\n\n INPUT:\n\n - ``linear_extension`` -- (default: ``None``) a list of the\n elements of ``self``\n - ``check`` -- a boolean (default: ``True``);\n whether to check that ``linear_extension`` is indeed a\n linear extension of ``self``.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade=True)\n\n Without optional argument, the default linear extension of the\n poset is returned, as a plain list::\n\n sage: P.linear_extension()\n [1, 3, 5, 15]\n\n Otherwise, a full-featured linear extension is constructed\n as an element of ``P.linear_extensions()``::\n\n sage: l = P.linear_extension([1,5,3,15]); l\n [1, 5, 3, 15]\n sage: type(l)\n <class \'sage.combinat.posets.linear_extensions.LinearExtensionsOfPoset_with_category.element_class\'>\n sage: l.parent()\n The set of all linear extensions of Finite poset containing 4 elements\n\n By default, the linear extension is checked for correctness::\n\n sage: l = P.linear_extension([1,3,15,5])\n Traceback (most recent call last):\n ...\n ValueError: [1, 3, 15, 5] is not a linear extension of Finite poset containing 4 elements\n\n This can be disabled (at your own risks!) with::\n\n sage: P.linear_extension([1,3,15,5], check=False)\n [1, 3, 15, 5]\n\n .. SEEALSO:: :meth:`is_linear_extension`, :meth:`linear_extensions`\n\n .. TODO::\n\n - Is it acceptable to have those two features for a single method?\n\n - In particular, we miss a short idiom to get the default\n linear extension\n '
L = self.linear_extensions()
if (linear_extension is not None):
return L(linear_extension, check=check)
return L(self._list, check=check)
@cached_method
def linear_extensions(self, facade=False):
'\n Return the enumerated set of all the linear extensions of this poset.\n\n INPUT:\n\n - ``facade`` -- a boolean (default: ``False``);\n whether to return the linear extensions as plain lists\n\n .. warning::\n\n The ``facade`` option is not yet fully functional::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: L = P.linear_extensions(facade=True); L\n The set of all linear extensions of Finite poset containing 6 elements with distinguished linear extension\n sage: L([1, 2, 3, 4, 6, 12])\n Traceback (most recent call last):\n ...\n TypeError: Cannot convert list to sage.structure.element.Element\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: L = P.linear_extensions(); L\n The set of all linear extensions of Finite poset containing 6 elements with distinguished linear extension\n sage: l = L.an_element(); l\n [1, 2, 3, 4, 6, 12]\n sage: L.cardinality()\n 5\n sage: L.list()\n [[1, 2, 3, 4, 6, 12],\n [1, 2, 4, 3, 6, 12],\n [1, 3, 2, 4, 6, 12],\n [1, 3, 2, 6, 4, 12],\n [1, 2, 3, 6, 4, 12]]\n\n Each element is aware that it is a linear extension of `P`::\n\n sage: type(l.parent())\n <class \'sage.combinat.posets.linear_extensions.LinearExtensionsOfPoset_with_category\'>\n\n With ``facade=True``, the elements of ``L`` are plain lists instead::\n\n sage: L = P.linear_extensions(facade=True)\n sage: l = L.an_element()\n sage: type(l)\n <class \'list\'>\n\n .. WARNING::\n\n In Sage <= 4.8, this function used to return a plain list\n of lists. To recover the previous functionality, please use::\n\n sage: L = list(P.linear_extensions(facade=True)); L\n [[1, 2, 3, 4, 6, 12],\n [1, 2, 4, 3, 6, 12],\n [1, 3, 2, 4, 6, 12],\n [1, 3, 2, 6, 4, 12],\n [1, 2, 3, 6, 4, 12]]\n sage: type(L[0])\n <class \'list\'>\n\n .. SEEALSO:: :meth:`linear_extension`, :meth:`is_linear_extension`\n\n TESTS::\n\n sage: D = Poset({ 0:[1,2], 1:[3], 2:[3,4] })\n sage: list(D.linear_extensions())\n [[0, 1, 2, 3, 4], [0, 2, 1, 3, 4], [0, 2, 1, 4, 3], [0, 2, 4, 1, 3], [0, 1, 2, 4, 3]]\n '
return self._lin_ext_type(self, facade=facade)
def spectrum(self, a):
'\n Return the `a`-spectrum of this poset.\n\n The `a`-spectrum in a poset `P` is the list of integers whose\n `i`-th position contains the number of linear extensions of `P`\n that have `a` in the `i`-th location.\n\n INPUT:\n\n - ``a`` -- an element of this poset\n\n OUTPUT:\n\n The `a`-spectrum of this poset, returned as a list.\n\n EXAMPLES::\n\n sage: P = posets.ChainPoset(5)\n sage: P.spectrum(2)\n [0, 0, 1, 0, 0]\n\n sage: P = posets.BooleanLattice(3)\n sage: P.spectrum(5)\n [0, 0, 0, 4, 12, 16, 16, 0]\n\n sage: P = posets.YoungDiagramPoset(Partition([3,2,1])) # needs sage.combinat\n sage: P.spectrum((0,1)) # needs sage.combinat\n [0, 8, 6, 2, 0, 0]\n\n sage: P = posets.AntichainPoset(4)\n sage: P.spectrum(3)\n [6, 6, 6, 6]\n\n TESTS::\n\n sage: P = posets.ChainPoset(5)\n sage: P.spectrum(6)\n Traceback (most recent call last):\n ...\n ValueError: input element is not in poset\n '
if (a not in self):
raise ValueError('input element is not in poset')
a_spec = ([0] * len(self))
for L in self.linear_extensions():
idx = L.index(a)
a_spec[idx] += 1
return a_spec
def atkinson(self, a):
'\n Return the `a`-spectrum of a poset whose Hasse diagram is\n cycle-free as an undirected graph.\n\n Given an element `a` in a poset `P`, the `a`-spectrum is the list of\n integers whose `i`-th term contains the number of linear extensions of\n `P` with element `a` located in the i-th position.\n\n INPUT:\n\n - ``self`` -- a poset whose Hasse diagram is a forest\n\n - ``a`` -- an element of the poset\n\n OUTPUT:\n\n The `a`-spectrum of this poset, returned as a list.\n\n EXAMPLES::\n\n sage: P = Poset({0: [2], 1: [2], 2: [3, 4], 3: [], 4: []})\n sage: P.atkinson(0)\n [2, 2, 0, 0, 0]\n\n sage: P = Poset({0: [1], 1: [2, 3], 2: [], 3: [], 4: [5, 6], 5: [], 6: []})\n sage: P.atkinson(5)\n [0, 10, 18, 24, 28, 30, 30]\n\n sage: P = posets.AntichainPoset(10)\n sage: P.atkinson(0)\n [362880, 362880, 362880, 362880, 362880, 362880, 362880, 362880, 362880, 362880]\n\n TESTS::\n\n sage: P = posets.ChainPoset(5)\n sage: P.atkinson(6)\n Traceback (most recent call last):\n ...\n ValueError: input element is not in poset\n\n sage: P = posets.BooleanLattice(2)\n sage: P.atkinson(1)\n Traceback (most recent call last):\n ...\n ValueError: this poset is not a forest\n\n .. NOTE::\n\n This function is the implementation of the algorithm from [At1990]_.\n '
if (a not in self):
raise ValueError('input element is not in poset')
if (not self._hasse_diagram.to_undirected().is_forest()):
raise ValueError('this poset is not a forest')
n = self.cardinality()
components = self.connected_components()
remainder_poset = Poset()
for X in components:
if (a in X):
main = X
else:
remainder_poset = remainder_poset.disjoint_union(X)
hasse_a = main._element_to_vertex(a)
a_spec = main._hasse_diagram._spectrum_of_tree(hasse_a)
if (not remainder_poset.cardinality()):
return a_spec
b = remainder_poset.an_element()
b_spec = remainder_poset.atkinson(b)
n_lin_exts = sum(b_spec)
new_a_spec = []
k = main.cardinality()
for r in range(1, (n + 1)):
new_a_spec.append(0)
for i in range(max(1, ((r - n) + k)), (min(r, k) + 1)):
k_val = (binomial((r - 1), (i - 1)) * binomial((n - r), (k - i)))
new_a_spec[(- 1)] += ((k_val * a_spec[(i - 1)]) * n_lin_exts)
return new_a_spec
def is_linear_extension(self, l) -> bool:
'\n Return whether ``l`` is a linear extension of ``self``.\n\n INPUT:\n\n - ``l`` -- a list (or iterable) containing all of the elements of ``self`` exactly once\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True, linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: P.is_linear_extension([1, 2, 4, 3, 6, 12])\n True\n sage: P.is_linear_extension([1, 2, 4, 6, 3, 12])\n False\n\n sage: [p for p in Permutations(list(P)) if P.is_linear_extension(p)]\n [[1, 2, 3, 4, 6, 12],\n [1, 2, 3, 6, 4, 12],\n [1, 2, 4, 3, 6, 12],\n [1, 3, 2, 4, 6, 12],\n [1, 3, 2, 6, 4, 12]]\n sage: list(P.linear_extensions())\n [[1, 2, 3, 4, 6, 12],\n [1, 2, 4, 3, 6, 12],\n [1, 3, 2, 4, 6, 12],\n [1, 3, 2, 6, 4, 12],\n [1, 2, 3, 6, 4, 12]]\n\n .. NOTE::\n\n This is used and systematically tested in\n :class:`~sage.combinat.posets.linear_extensions.LinearExtensionsOfPosets`\n\n .. SEEALSO:: :meth:`linear_extension`, :meth:`linear_extensions`\n\n TESTS:\n\n Check that :trac:`15313` is fixed::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True, linear_extension=True)\n sage: P.is_linear_extension([1,2,4,3,6,12,1337])\n False\n sage: P.is_linear_extension([1,2,4,3,6,666,12,1337])\n False\n sage: P = Poset(DiGraph(5))\n sage: P.is_linear_extension([\'David\', \'McNeil\', \'La\', \'Lamentable\', \'Aventure\', \'de\', \'Simon\', \'Wiesenthal\'])\n False\n '
index = {x: i for (i, x) in enumerate(l)}
return ((len(l) == self.cardinality()) and all(((x in index) for x in self)) and all(((index[i] < index[j]) for (i, j) in self.cover_relations())))
def list(self):
"\n List the elements of the poset. This just returns the result\n of :meth:`linear_extension`.\n\n EXAMPLES::\n\n sage: D = Poset({ 0:[1,2], 1:[3], 2:[3,4] }, facade = False)\n sage: D.list()\n [0, 1, 2, 3, 4]\n sage: type(D.list()[0])\n <class 'sage.combinat.posets.posets.FinitePoset_with_category.element_class'>\n "
return list(self._list)
def plot(self, label_elements=True, element_labels=None, layout='acyclic', cover_labels=None, **kwds):
'\n Return a Graphic object for the Hasse diagram of the poset.\n\n If the poset is ranked, the plot uses the rank function for\n the heights of the elements.\n\n INPUT:\n\n - Options to change element look:\n\n * ``element_colors`` - a dictionary where keys are colors and values\n are lists of elements\n * ``element_color`` - a color for elements not set in\n ``element_colors``\n * ``element_shape`` - the shape of elements, like ``\'s\'`` for\n square; see https://matplotlib.org/api/markers_api.html for the list\n * ``element_size`` (default: 200) - the size of elements\n * ``label_elements`` (default: ``True``) - whether to display\n element labels\n * ``element_labels`` (default: ``None``) - a dictionary where keys\n are elements and values are labels to show\n\n - Options to change cover relation look:\n\n * ``cover_colors`` - a dictionary where keys are colors and values\n are lists of cover relations given as pairs of elements\n * ``cover_color`` - a color for elements not set in\n ``cover_colors``\n * ``cover_style`` - style for cover relations: ``\'solid\'``,\n ``\'dashed\'``, ``\'dotted\'`` or ``\'dashdot\'``\n * ``cover_labels`` - a dictionary, list or function representing\n labels of the covers of the poset. When set to ``None`` (default)\n no label is displayed on the edges of the Hasse Diagram.\n * ``cover_labels_background`` - a background color for cover\n relations. The default is "white". To achieve a transparent\n background use "transparent".\n\n - Options to change overall look:\n\n * ``figsize`` (default: 8) - size of the whole plot\n * ``title`` - a title for the plot\n * ``fontsize`` - fontsize for the title\n * ``border`` (default: ``False``) - whether to draw a border over the\n plot\n\n .. NOTE::\n\n All options of :meth:`GenericGraph.plot\n <sage.graphs.generic_graph.GenericGraph.plot>` are also available\n through this function.\n\n EXAMPLES:\n\n This function can be used without any parameters::\n\n sage: # needs sage.plot\n sage: D12 = posets.DivisorLattice(12)\n sage: D12.plot()\n Graphics object consisting of 14 graphics primitives\n\n Just the abstract form of the poset; examples of relabeling::\n\n sage: # needs sage.plot\n sage: D12.plot(label_elements=False)\n Graphics object consisting of 8 graphics primitives\n sage: d = {1: 0, 2: \'a\', 3: \'b\', 4: \'c\', 6: \'d\', 12: 1}\n sage: D12.plot(element_labels=d)\n Graphics object consisting of 14 graphics primitives\n sage: d = {i: str(factor(i)) for i in D12}\n sage: D12.plot(element_labels=d)\n Graphics object consisting of 14 graphics primitives\n\n Some settings for coverings::\n\n sage: # needs sage.plot\n sage: d = {(a, b): b/a for a, b in D12.cover_relations()}\n sage: D12.plot(cover_labels=d, cover_color=\'gray\', cover_style=\'dotted\')\n Graphics object consisting of 21 graphics primitives\n\n To emphasize some elements and show some options::\n\n sage: # needs sage.plot\n sage: L = LatticePoset({0: [1, 2, 3, 4], 1: [12], 2: [6, 7],\n ....: 3: [5, 9], 4: [5, 6, 10, 11], 5: [13],\n ....: 6: [12], 7: [12, 8, 9], 8: [13], 9: [13],\n ....: 10: [12], 11: [12], 12: [13]})\n sage: F = L.frattini_sublattice()\n sage: F_internal = [c for c in F.cover_relations()\n ....: if c in L.cover_relations()]\n sage: L.plot(figsize=12, border=True, element_shape=\'s\',\n ....: element_size=400, element_color=\'white\',\n ....: element_colors={\'blue\': F, \'green\': L.double_irreducibles()},\n ....: cover_color=\'lightgray\', cover_colors={\'black\': F_internal},\n ....: title=\'The Frattini\\nsublattice in blue\', fontsize=10)\n Graphics object consisting of 39 graphics primitives\n\n TESTS:\n\n We check that ``label_elements`` and ``element_labels`` are honored::\n\n sage: # needs sage.plot\n sage: def get_plot_labels(P):\n ....: return sorted(t.string for t in P\n ....: if isinstance(t, sage.plot.text.Text))\n sage: P1 = Poset({ 0:[1,2], 1:[3], 2:[3,4] })\n sage: P2 = Poset({ 0:[1,2], 1:[3], 2:[3,4] }, facade=True)\n sage: get_plot_labels(P1.plot(label_elements=False))\n []\n sage: get_plot_labels(P1.plot(label_elements=True))\n [\'0\', \'1\', \'2\', \'3\', \'4\']\n sage: element_labels = {0:\'a\', 1:\'b\', 2:\'c\', 3:\'d\', 4:\'e\'}\n sage: get_plot_labels(P1.plot(element_labels=element_labels))\n [\'a\', \'b\', \'c\', \'d\', \'e\']\n sage: get_plot_labels(P2.plot(element_labels=element_labels))\n [\'a\', \'b\', \'c\', \'d\', \'e\']\n\n The following checks that :trac:`18936` has been fixed and labels still work::\n\n sage: # needs sage.plot\n sage: P = Poset({0: [1,2], 1:[3]})\n sage: heights = {1 : [0], 2 : [1], 3 : [2,3]}\n sage: P.plot(heights=heights)\n Graphics object consisting of 8 graphics primitives\n sage: elem_labels = {0 : \'a\', 1 : \'b\', 2 : \'c\', 3 : \'d\'}\n sage: P.plot(element_labels=elem_labels, heights=heights)\n Graphics object consisting of 8 graphics primitives\n\n The following checks that equal labels are allowed (:trac:`15206`)::\n\n sage: # needs sage.plot\n sage: P = Poset({1: [2,3]})\n sage: labs = {i: P.rank(i) for i in range(1, 4)}; labs\n {1: 0, 2: 1, 3: 1}\n sage: P.plot(element_labels=labs)\n Graphics object consisting of 6 graphics primitives\n\n The following checks that non-hashable labels are allowed (:trac:`15206`)::\n\n sage: # needs sage.plot\n sage: P = Poset({1: [2,3]})\n sage: labs = {1: [2, 3], 2: [], 3: []}; labs\n {1: [2, 3], 2: [], 3: []}\n sage: P.plot(element_labels=labs)\n Graphics object consisting of 6 graphics primitives\n\n Plot of the empty poset::\n\n sage: # needs sage.plot\n sage: P = Poset({})\n sage: P.plot()\n Graphics object consisting of 0 graphics primitives\n '
graph = self.hasse_diagram()
rename = {'element_color': 'vertex_color', 'element_colors': 'vertex_colors', 'element_size': 'vertex_size', 'element_shape': 'vertex_shape', 'cover_color': 'edge_color', 'cover_labels_background': 'edge_labels_background', 'cover_colors': 'edge_colors', 'cover_style': 'edge_style', 'border': 'graph_border'}
for param in rename:
tmp = kwds.pop(param, None)
if (tmp is not None):
kwds[rename[param]] = tmp
heights = kwds.pop('heights', None)
if (heights is None):
rank_function = self.rank_function()
if rank_function:
heights = defaultdict(list)
for i in self:
heights[rank_function(i)].append(i)
if (label_elements and (element_labels is not None)):
from sage.misc.element_with_label import ElementWithLabel
relabeling = {self(element): ElementWithLabel(self(element), label) for (element, label) in element_labels.items()}
graph = graph.relabel(relabeling, inplace=False)
if (heights is not None):
for key in heights:
heights[key] = [relabeling[i] for i in heights[key]]
if (cover_labels is not None):
if callable(cover_labels):
for (v, w) in graph.edges(sort=False, labels=False):
graph.set_edge_label(v, w, cover_labels(v, w))
elif isinstance(cover_labels, dict):
for (v, w) in cover_labels:
graph.set_edge_label(self(v), self(w), cover_labels[(v, w)])
else:
for (v, w, l) in cover_labels:
graph.set_edge_label(self(v), self(w), l)
cover_labels = True
else:
cover_labels = False
return graph.plot(vertex_labels=label_elements, edge_labels=cover_labels, layout=layout, heights=heights, **kwds)
def show(self, label_elements=True, element_labels=None, cover_labels=None, **kwds):
"\n Displays the Hasse diagram of the poset.\n\n INPUT:\n\n - ``label_elements`` (default: ``True``) - whether to display\n element labels\n\n - ``element_labels`` (default: ``None``) - a dictionary of\n element labels\n\n - ``cover_labels`` - a dictionary, list or function representing labels\n of the covers of ``self``. When set to ``None`` (default) no label is\n displayed on the edges of the Hasse Diagram.\n\n .. NOTE::\n\n This method also accepts:\n\n - All options of :meth:`GenericGraph.plot\n <sage.graphs.generic_graph.GenericGraph.plot>`\n\n - All options of :meth:`Graphics.show\n <sage.plot.graphics.Graphics.show>`\n\n EXAMPLES::\n\n sage: # needs sage.plot\n sage: D = Poset({ 0:[1,2], 1:[3], 2:[3,4] })\n sage: D.plot(label_elements=False)\n Graphics object consisting of 6 graphics primitives\n sage: D.show()\n sage: elm_labs = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'}\n sage: D.show(element_labels=elm_labs)\n\n One more example with cover labels::\n\n sage: # needs sage.plot\n sage: P = posets.PentagonPoset()\n sage: P.show(cover_labels=lambda a, b: a - b)\n "
from sage.graphs.graph_plot import graphplot_options
plot_kwds = {k: kwds.pop(k) for k in graphplot_options if (k in kwds)}
self.plot(label_elements=label_elements, element_labels=element_labels, cover_labels=cover_labels, **plot_kwds).show(**kwds)
def level_sets(self):
'\n Return elements grouped by maximal number of cover relations\n from a minimal element.\n\n This returns a list of lists ``l`` such that ``l[i]`` is the\n set of minimal elements of the poset obtained by removing the\n elements in ``l[0], l[1], ..., l[i-1]``. (In particular,\n ``l[0]`` is the set of minimal elements of ``self``.)\n\n Every level is an antichain of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[1,2],1:[3],2:[3],3:[]})\n sage: P.level_sets()\n [[0], [1, 2], [3]]\n\n sage: Q = Poset({0:[1,2], 1:[3], 2:[4], 3:[4]})\n sage: Q.level_sets()\n [[0], [1, 2], [3], [4]]\n\n .. SEEALSO::\n\n :meth:`dilworth_decomposition` to return elements grouped\n to chains.\n '
return [[self._vertex_to_element(_) for _ in level] for level in self._hasse_diagram.level_sets()]
def cover_relations(self):
'\n Return the list of pairs ``[x, y]`` of elements of the poset such\n that ``y`` covers ``x``.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.cover_relations()\n [[1, 2], [0, 2], [2, 3], [3, 4]]\n '
return [c for c in self.cover_relations_iterator()]
@combinatorial_map(name='cover_relations_graph')
def cover_relations_graph(self):
'\n Return the (undirected) graph of cover relations.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1, 2], 1: [3], 2: [3]})\n sage: G = P.cover_relations_graph(); G\n Graph on 4 vertices\n sage: G.has_edge(3, 1), G.has_edge(3, 0)\n (True, False)\n\n .. SEEALSO::\n\n :meth:`hasse_diagram`\n\n TESTS::\n\n sage: Poset().cover_relations_graph()\n Graph on 0 vertices\n\n Check that it is hashable and coincides with the Hasse diagram as a\n graph::\n\n sage: P = Poset({0: [1, 2], 1: [3], 2: [3]})\n sage: G = P.cover_relations_graph()\n sage: hash(G) == hash(G)\n True\n sage: G == Graph(P.hasse_diagram())\n True\n '
from sage.graphs.graph import Graph
return Graph(self.hasse_diagram(), immutable=True)
def cover_relations_iterator(self):
"\n Return an iterator over the cover relations of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: type(P.cover_relations_iterator())\n <class 'generator'>\n sage: [z for z in P.cover_relations_iterator()]\n [[1, 2], [0, 2], [2, 3], [3, 4]]\n "
for (u, v) in self._hasse_diagram.edge_iterator(labels=False):
(yield [self._vertex_to_element(w) for w in (u, v)])
def relations(self):
'\n Return the list of all relations of the poset.\n\n A relation is a pair of elements `x` and `y` such that `x \\leq y`\n in the poset.\n\n The number of relations is the dimension of the incidence\n algebra.\n\n OUTPUT:\n\n A list of pairs (each pair is a list), where the first element\n of the pair is less than or equal to the second element.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.relations()\n [[1, 1], [1, 2], [1, 3], [1, 4], [0, 0], [0, 2], [0, 3],\n [0, 4], [2, 2], [2, 3], [2, 4], [3, 3], [3, 4], [4, 4]]\n\n .. SEEALSO::\n\n :meth:`relations_number`, :meth:`relations_iterator`\n\n TESTS::\n\n sage: P = Poset() # Test empty poset\n sage: P.relations()\n []\n\n AUTHOR:\n\n - Rob Beezer (2011-05-04)\n '
return list(self.relations_iterator())
def diamonds(self):
'\n Return the list of diamonds of ``self``.\n\n A diamond is the following subgraph of the Hasse diagram::\n\n z\n / \\\n x y\n \\ /\n w\n\n Thus each edge represents a cover relation in the Hasse diagram.\n We represent this as the tuple `(w, x, y, z)`.\n\n OUTPUT:\n\n A tuple with\n\n - a list of all diamonds in the Hasse Diagram,\n - a boolean checking that every `w,x,y` that form a ``V``, there is a\n unique element `z`, which completes the diamond.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: P.diamonds()\n ([(0, 1, 2, 3)], True)\n\n sage: P = posets.YoungDiagramPoset(Partition([3, 2, 2])) # needs sage.combinat\n sage: P.diamonds() # needs sage.combinat\n ([((0, 0), (0, 1), (1, 0), (1, 1)), ((1, 0), (1, 1), (2, 0), (2, 1))], False)\n '
(diamonds, all_diamonds_completed) = self._hasse_diagram.diamonds()
return ([tuple(map(self._vertex_to_element, d)) for d in diamonds], all_diamonds_completed)
def common_upper_covers(self, elmts):
'\n Return all of the common upper covers of the elements ``elmts``.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: P.common_upper_covers([1, 2])\n [3]\n '
vertices = list(map(self._element_to_vertex, elmts))
return list(map(self._vertex_to_element, self._hasse_diagram.common_upper_covers(vertices)))
def common_lower_covers(self, elmts):
'\n Return all of the common lower covers of the elements ``elmts``.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1,2], 1: [3], 2: [3], 3: []})\n sage: P.common_lower_covers([1, 2])\n [0]\n '
vertices = list(map(self._element_to_vertex, elmts))
return list(map(self._vertex_to_element, self._hasse_diagram.common_lower_covers(vertices)))
def meet(self, x, y):
"\n Return the meet of two elements ``x, y`` in the poset if the meet\n exists; and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: D = Poset({1:[2,3], 2:[4], 3:[4]})\n sage: D.meet(2, 3)\n 1\n sage: P = Poset({'a':['b', 'c'], 'b':['e', 'f'], 'c':['f', 'g'],\n ....: 'd':['f', 'g']})\n sage: P.meet('a', 'b')\n 'a'\n sage: P.meet('e', 'a')\n 'a'\n sage: P.meet('c', 'b')\n 'a'\n sage: P.meet('e', 'f')\n 'b'\n sage: P.meet('e', 'g')\n 'a'\n sage: P.meet('c', 'd') is None\n True\n sage: P.meet('g', 'f') is None\n True\n "
(i, j) = map(self._element_to_vertex, (x, y))
mt = self._hasse_diagram._meet
if (mt[(i, j)] == (- 1)):
return None
else:
return self._vertex_to_element(mt[(i, j)])
def join(self, x, y):
"\n Return the join of two elements ``x, y`` in the poset if the join\n exists; and ``None`` otherwise.\n\n EXAMPLES::\n\n sage: D = Poset({1:[2,3], 2:[4], 3:[4]})\n sage: D.join(2, 3)\n 4\n sage: P = Poset({'e':['b'], 'f':['b', 'c', 'd'], 'g':['c', 'd'],\n ....: 'b':['a'], 'c':['a']})\n sage: P.join('a', 'b')\n 'a'\n sage: P.join('e', 'a')\n 'a'\n sage: P.join('c', 'b')\n 'a'\n sage: P.join('e', 'f')\n 'b'\n sage: P.join('e', 'g')\n 'a'\n sage: P.join('c', 'd') is None\n True\n sage: P.join('g', 'f') is None\n True\n "
(i, j) = map(self._element_to_vertex, (x, y))
jn = self._hasse_diagram._join
if (jn[(i, j)] == (- 1)):
return None
else:
return self._vertex_to_element(jn[(i, j)])
def is_d_complete(self) -> bool:
'\n Return ``True`` if a poset is d-complete and ``False`` otherwise.\n\n .. SEEALSO::\n\n - :mod:`~sage.combinat.posets.d_complete`\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.posets import FinitePoset\n sage: A = Poset({0: [1,2]})\n sage: A.is_d_complete()\n False\n\n sage: from sage.combinat.posets.poset_examples import Posets\n sage: B = Posets.DoubleTailedDiamond(3)\n sage: B.is_d_complete()\n True\n\n sage: C = Poset({0: [2], 1: [2], 2: [3, 4], 3: [5], 4: [5], 5: [6]})\n sage: C.is_d_complete()\n False\n\n sage: D = Poset({0: [1, 2], 1: [4], 2: [4], 3: [4]})\n sage: D.is_d_complete()\n False\n\n sage: P = Posets.YoungDiagramPoset(Partition([3, 2, 2]), dual=True) # needs sage.combinat\n sage: P.is_d_complete() # needs sage.combinat\n True\n '
min_diamond = {}
max_diamond = {}
H = self._hasse_diagram
(diamonds, all_diamonds_completed) = H.diamonds()
if (not all_diamonds_completed):
return False
diamond_index = {}
for (index, d) in enumerate(diamonds):
min_diamond[d[3]] = d[0]
max_diamond[d[0]] = d[3]
diamond_index[d[3]] = index
min_elmt = d[0]
max_elmt = d[3]
if (H.in_degree(max_elmt) != 2):
return False
while True:
potential_min = H.neighbors_in(min_elmt)
potential_max = H.neighbors_out(max_elmt)
max_dk_minus = max_elmt
found_diamond = False
for mn in potential_min:
if (len(H.all_paths(mn, max_dk_minus)) > 2):
continue
for mx in potential_max:
if (len(H.all_paths(mn, mx)) == 2):
if (H.in_degree(mx) != 1):
return False
if ((mx in min_diamond) or (mn in max_diamond)):
return False
min_elmt = mn
max_elmt = mx
min_diamond[mx] = mn
max_diamond[mn] = mx
diamond_index[mx] = index
found_diamond = True
if (not found_diamond):
break
return True
def slant_sum(self, p, element, p_element):
'\n Return the slant sum poset of posets ``self`` and ``p`` by\n connecting them with a cover relation ``(p_element, element)``.\n\n .. NOTE::\n\n The element names of ``self`` and ``p`` must be distinct.\n\n INPUT:\n\n - ``p`` -- the poset used for the slant sum\n - ``element`` -- the element of ``self`` that is the top of\n the new cover relation\n - ``p_element`` -- the element of ``p`` that is the bottom of\n the new cover relation\n\n EXAMPLES::\n\n sage: R = posets.RibbonPoset(5, [1,2])\n sage: H = Poset([[5, 6, 7], [(5, 6), (6,7)]])\n sage: SS = R.slant_sum(H, 3, 7)\n sage: all(cr in SS.cover_relations() for cr in R.cover_relations())\n True\n sage: all(cr in SS.cover_relations() for cr in H.cover_relations())\n True\n sage: SS.covers(7, 3)\n True\n '
elements = (p._elements + self._elements)
cover_relations = (p.cover_relations() + self.cover_relations())
cover_relations.append((p_element, element))
return Poset([elements, cover_relations])
def intervals_poset(self):
'\n Return the natural partial order on the set of intervals of the poset.\n\n OUTPUT:\n\n a finite poset\n\n The poset of intervals of a poset `P` has the set of intervals `[x,y]`\n in `P` as elements, endowed with the order relation defined by\n `[x_1,y_1] \\leq [x_2,y_2]` if and only if `x_1 \\leq x_2` and\n `y_1 \\leq y_2`.\n\n This is also called `P` to the power *2*, meaning\n the poset of poset-morphisms from the 2-chain to `P`.\n\n If `P` is a lattice, the result is also a lattice.\n\n EXAMPLES::\n\n sage: P = Poset({0:[1]})\n sage: P.intervals_poset()\n Finite poset containing 3 elements\n\n sage: P = posets.PentagonPoset()\n sage: P.intervals_poset()\n Finite lattice containing 13 elements\n\n TESTS::\n\n sage: P = Poset({})\n sage: P.intervals_poset()\n Finite poset containing 0 elements\n\n sage: P = Poset({0:[]})\n sage: P.intervals_poset()\n Finite poset containing 1 elements\n\n sage: P = Poset({0:[], 1:[]})\n sage: P.intervals_poset().is_isomorphic(P)\n True\n '
from sage.combinat.posets.lattices import LatticePoset, FiniteLatticePoset
if isinstance(self, FiniteLatticePoset):
constructor = LatticePoset
else:
constructor = Poset
ints = [tuple(u) for u in self.relations()]
covers = []
for (a, b) in ints:
covers.extend([[(a, b), (a, bb)] for bb in self.upper_covers(b)])
if (a != b):
covers.extend([[(a, b), (aa, b)] for aa in self.upper_covers(a) if self.le(aa, b)])
dg = DiGraph([ints, covers], format='vertices_and_edges')
return constructor(dg, cover_relations=True)
def relations_iterator(self, strict=False):
"\n Return an iterator for all the relations of the poset.\n\n A relation is a pair of elements `x` and `y` such that `x \\leq y`\n in the poset.\n\n INPUT:\n\n - ``strict`` -- a boolean (default ``False``) if ``True``, returns\n an iterator over relations `x < y`, excluding all\n relations `x \\leq x`.\n\n OUTPUT:\n\n A generator that produces pairs (each pair is a list), where the\n first element of the pair is less than or equal to the second element.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: it = P.relations_iterator()\n sage: type(it)\n <class 'generator'>\n sage: next(it), next(it)\n ([1, 1], [1, 2])\n\n sage: P = posets.PentagonPoset()\n sage: list(P.relations_iterator(strict=True))\n [[0, 1], [0, 2], [0, 4], [0, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n\n .. SEEALSO::\n\n :meth:`relations_number`, :meth:`relations`.\n\n AUTHOR:\n\n - Rob Beezer (2011-05-04)\n "
elements = self._elements
hd = self._hasse_diagram
if strict:
for i in hd:
for j in hd.breadth_first_search(i):
if (i != j):
(yield [elements[i], elements[j]])
else:
for i in hd:
for j in hd.breadth_first_search(i):
(yield [elements[i], elements[j]])
def relations_number(self):
'\n Return the number of relations in the poset.\n\n A relation is a pair of elements `x` and `y` such that `x\\leq y`\n in the poset.\n\n Relations are also often called intervals. The number of\n intervals is the dimension of the incidence algebra.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.relations_number()\n 13\n\n sage: posets.TamariLattice(4).relations_number()\n 68\n\n .. SEEALSO::\n\n :meth:`relations_iterator`, :meth:`relations`\n\n TESTS::\n\n sage: Poset().relations_number()\n 0\n '
return sum((1 for _ in self.relations_iterator()))
intervals_number = relations_number
def linear_intervals_count(self) -> list[int]:
'\n Return the enumeration of linear intervals w.r.t. their cardinality.\n\n An interval is linear if it is a total order.\n\n OUTPUT: list of integers\n\n .. SEEALSO:: :meth:`is_linear_interval`\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.linear_intervals_count()\n [5, 5, 2]\n sage: P = posets.TamariLattice(4)\n sage: P.linear_intervals_count()\n [14, 21, 12, 2]\n\n TESTS::\n\n sage: P = Poset()\n sage: P.linear_intervals_count()\n []\n '
if (not self.cardinality()):
return []
H = self._hasse_diagram
stock = [(x, x, x) for x in H]
poly = [len(stock)]
exposant = 0
while True:
exposant += 1
next_stock = []
short_stock = [(ch[0], ch[2]) for ch in stock]
for (xmin, cov_xmin, xmax) in stock:
for y in H.neighbor_out_iterator(xmax):
if (exposant == 1):
next_stock.append((xmin, y, y))
elif ((cov_xmin, y) in short_stock):
if H.is_linear_interval(xmin, y):
next_stock.append((xmin, cov_xmin, y))
if next_stock:
poly.append(len(next_stock))
stock = next_stock
else:
break
return poly
def is_linear_interval(self, x, y) -> bool:
'\n Return whether the interval ``[x, y]`` is linear.\n\n This means that this interval is a total order.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.is_linear_interval(0, 4)\n False\n sage: P.is_linear_interval(0, 3)\n True\n sage: P.is_linear_interval(1, 3)\n False\n '
a = self._element_to_vertex(x)
b = self._element_to_vertex(y)
return self._hasse_diagram.is_linear_interval(a, b)
def is_incomparable_chain_free(self, m, n=None) -> bool:
"\n Return ``True`` if the poset is `(m+n)`-free, and ``False`` otherwise.\n\n A poset is `(m+n)`-free if there is no incomparable chains of\n lengths `m` and `n`. Three cases have special name\n (see [EnumComb1]_, exercise 3.15):\n\n - ''interval order'' is `(2+2)`-free\n - ''semiorder'' (or ''unit interval order'') is `(1+3)`-free and\n `(2+2)`-free\n - ''weak order'' is `(1+2)`-free.\n\n INPUT:\n\n - ``m``, ``n`` - positive integers\n\n It is also possible to give a list of integer pairs as argument.\n See below for an example.\n\n EXAMPLES::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3.is_incomparable_chain_free(1, 3)\n True\n sage: B3.is_incomparable_chain_free(2, 2)\n False\n\n sage: IP6 = posets.IntegerPartitions(6) # needs sage.combinat\n sage: IP6.is_incomparable_chain_free(1, 3) # needs sage.combinat\n False\n sage: IP6.is_incomparable_chain_free(2, 2) # needs sage.combinat\n True\n\n A list of pairs as an argument::\n\n sage: B3.is_incomparable_chain_free([[1, 3], [2, 2]])\n False\n\n We show how to get an incomparable chain pair::\n\n sage: P = posets.PentagonPoset()\n sage: chains_1_2 = Poset({0:[], 1:[2]})\n sage: incomps = P.isomorphic_subposets(chains_1_2)[0]\n sage: sorted(incomps.list()), incomps.cover_relations()\n ([1, 2, 3], [[2, 3]])\n\n TESTS::\n\n sage: Poset().is_incomparable_chain_free(1,1) # Test empty poset\n True\n\n sage: [len([p for p in Posets(n) # long time\n ....: if p.is_incomparable_chain_free(((3, 1), (2, 2)))])\n ....: for n in range(6)]\n [1, 1, 2, 5, 14, 42]\n\n sage: Q = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: Q.is_incomparable_chain_free(2, 20/10)\n True\n sage: Q.is_incomparable_chain_free(2, 1.5)\n Traceback (most recent call last):\n ...\n TypeError: 2 and 1.5... must be integers\n sage: Q.is_incomparable_chain_free(2, -1)\n Traceback (most recent call last):\n ...\n ValueError: 2 and -1 must be positive integers\n sage: P = Poset(((0, 1, 2, 3, 4), ((0, 1), (1, 2), (0, 3), (4, 2))))\n sage: P.is_incomparable_chain_free((3, 1))\n Traceback (most recent call last):\n ...\n TypeError: (3, 1) is not a tuple of tuples\n sage: P.is_incomparable_chain_free([3, 1], [2, 2])\n Traceback (most recent call last):\n ...\n TypeError: [3, 1] and [2, 2] must be integers\n sage: P.is_incomparable_chain_free([[3, 1], [2, 2]])\n True\n sage: P.is_incomparable_chain_free(([3, 1], [2, 2]))\n True\n sage: P.is_incomparable_chain_free([3, 1], 2)\n Traceback (most recent call last):\n ...\n TypeError: [3, 1] and 2 must be integers\n sage: P.is_incomparable_chain_free(([3, 1], [2, 2, 2]))\n Traceback (most recent call last):\n ...\n ValueError: '([3, 1], [2, 2, 2])' is not a tuple of length-2 tuples\n\n AUTHOR:\n\n - Eric Rowland (2013-05-28)\n "
if (n is None):
try:
chain_pairs = [tuple(chain_pair) for chain_pair in m]
except TypeError:
raise TypeError(('%s is not a tuple of tuples' % str(tuple(m))))
if (not all(((len(chain_pair) == 2) for chain_pair in chain_pairs))):
raise ValueError(('%r is not a tuple of length-2 tuples' % str(tuple(m))))
chain_pairs = sorted(chain_pairs, key=min)
else:
chain_pairs = [(m, n)]
if chain_pairs:
closure = self._hasse_diagram.transitive_closure()
for (m, n) in chain_pairs:
try:
(m, n) = (Integer(m), Integer(n))
except TypeError:
raise TypeError(f'{m} and {n} must be integers')
if ((m < 1) or (n < 1)):
raise ValueError(f'{m} and {n} must be positive integers')
twochains = (digraphs.TransitiveTournament(m) + digraphs.TransitiveTournament(n))
if (closure.subgraph_search(twochains, induced=True) is not None):
return False
return True
def is_lequal(self, x, y) -> bool:
'\n Return ``True`` if `x` is less than or equal to `y` in the poset, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.is_lequal(2, 4)\n True\n sage: P.is_lequal(2, 2)\n True\n sage: P.is_lequal(0, 1)\n False\n sage: P.is_lequal(3, 2)\n False\n\n .. SEEALSO:: :meth:`is_less_than`, :meth:`is_gequal`.\n '
i = self._element_to_vertex(x)
j = self._element_to_vertex(y)
return self._hasse_diagram.is_lequal(i, j)
le = is_lequal
def is_less_than(self, x, y) -> bool:
'\n Return ``True`` if `x` is less than but not equal to `y` in the poset,\n and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.is_less_than(1, 3)\n True\n sage: P.is_less_than(0, 1)\n False\n sage: P.is_less_than(2, 2)\n False\n\n For non-facade posets also ``<`` works::\n\n sage: P = Poset({3: [1, 2]}, facade=False)\n sage: P(1) < P(2)\n False\n\n .. SEEALSO:: :meth:`is_lequal`, :meth:`is_greater_than`.\n '
i = self._element_to_vertex(x)
j = self._element_to_vertex(y)
return self._hasse_diagram.is_less_than(i, j)
lt = is_less_than
def is_gequal(self, x, y) -> bool:
'\n Return ``True`` if `x` is greater than or equal to `y` in the poset,\n and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.is_gequal(3, 1)\n True\n sage: P.is_gequal(2, 2)\n True\n sage: P.is_gequal(0, 1)\n False\n\n .. SEEALSO:: :meth:`is_greater_than`, :meth:`is_lequal`.\n '
i = self._element_to_vertex(x)
j = self._element_to_vertex(y)
return self._hasse_diagram.is_lequal(j, i)
ge = is_gequal
def is_greater_than(self, x, y) -> bool:
'\n Return ``True`` if `x` is greater than but not equal to `y` in the\n poset, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[4], 4:[]})\n sage: P.is_greater_than(3, 1)\n True\n sage: P.is_greater_than(1, 2)\n False\n sage: P.is_greater_than(3, 3)\n False\n sage: P.is_greater_than(0, 1)\n False\n\n For non-facade posets also ``>`` works::\n\n sage: P = Poset({3: [1, 2]}, facade=False)\n sage: P(2) > P(3)\n True\n\n .. SEEALSO:: :meth:`is_gequal`, :meth:`is_less_than`.\n '
i = self._element_to_vertex(x)
j = self._element_to_vertex(y)
return self._hasse_diagram.is_less_than(j, i)
gt = is_greater_than
def compare_elements(self, x, y):
'\n Compare `x` and `y` in the poset.\n\n - If `x < y`, return ``-1``.\n - If `x = y`, return ``0``.\n - If `x > y`, return ``1``.\n - If `x` and `y` are not comparable, return ``None``.\n\n EXAMPLES::\n\n sage: P = Poset([[1, 2], [4], [3], [4], []])\n sage: P.compare_elements(0, 0)\n 0\n sage: P.compare_elements(0, 4)\n -1\n sage: P.compare_elements(4, 0)\n 1\n sage: P.compare_elements(1, 2) is None\n True\n '
(i, j) = map(self._element_to_vertex, (x, y))
if (i == j):
return 0
elif self._hasse_diagram.is_less_than(i, j):
return (- 1)
elif self._hasse_diagram.is_less_than(j, i):
return 1
else:
return None
def minimal_elements(self):
'\n Return the list of the minimal elements of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P(0) in P.minimal_elements()\n True\n sage: P(1) in P.minimal_elements()\n True\n sage: P(2) in P.minimal_elements()\n True\n\n .. SEEALSO:: :meth:`maximal_elements`.\n '
return [self._vertex_to_element(_) for _ in self._hasse_diagram.minimal_elements()]
def maximal_elements(self):
'\n Return the list of the maximal elements of the poset.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P.maximal_elements()\n [4]\n\n .. SEEALSO:: :meth:`minimal_elements`.\n '
return [self._vertex_to_element(_) for _ in self._hasse_diagram.maximal_elements()]
def bottom(self):
'\n Return the unique minimal element of the poset, if it exists.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4],4:[]})\n sage: P.bottom() is None\n True\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.bottom()\n 0\n\n .. SEEALSO:: :meth:`has_bottom`, :meth:`top`\n '
hasse_bot = self._hasse_diagram.bottom()
if (hasse_bot is None):
return None
else:
return self._vertex_to_element(hasse_bot)
def has_bottom(self):
'\n Return ``True`` if the poset has a unique minimal element, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3], 1:[3], 2:[3], 3:[4], 4:[]})\n sage: P.has_bottom()\n False\n sage: Q = Poset({0:[1], 1:[]})\n sage: Q.has_bottom()\n True\n\n .. SEEALSO::\n\n - Dual Property: :meth:`has_top`\n - Stronger properties: :meth:`is_bounded`\n - Other: :meth:`bottom`\n\n TESTS::\n\n sage: Poset().has_top() # Test empty poset\n False\n '
return self._hasse_diagram.has_bottom()
def top(self):
'\n Return the unique maximal element of the poset, if it exists.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3],1:[3],2:[3],3:[4,5],4:[],5:[]})\n sage: P.top() is None\n True\n sage: Q = Poset({0:[1],1:[]})\n sage: Q.top()\n 1\n\n .. SEEALSO:: :meth:`has_top`, :meth:`bottom`\n\n TESTS::\n\n sage: R = Poset([[0],[]])\n sage: R.list()\n [0]\n sage: R.top() #Issue #10776\n 0\n '
hasse_top = self._hasse_diagram.top()
if (hasse_top is None):
return None
else:
return self._vertex_to_element(hasse_top)
def has_top(self):
'\n Return ``True`` if the poset has a unique maximal element, and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3], 1:[3], 2:[3], 3:[4, 5], 4:[], 5:[]})\n sage: P.has_top()\n False\n sage: Q = Poset({0:[3], 1:[3], 2:[3], 3:[4], 4:[]})\n sage: Q.has_top()\n True\n\n .. SEEALSO::\n\n - Dual Property: :meth:`has_bottom`\n - Stronger properties: :meth:`is_bounded`\n - Other: :meth:`top`\n\n TESTS::\n\n sage: Poset().has_top() # Test empty poset\n False\n '
return self._hasse_diagram.has_top()
def height(self, certificate=False):
'\n Return the height (number of elements in a longest chain) of the poset.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return ``(h, c)``, where ``h`` is the\n height and ``c`` is a chain of maximum cardinality.\n If ``certificate=False`` return only the height.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1], 2: [3, 4], 4: [5, 6]})\n sage: P.height()\n 3\n sage: posets.PentagonPoset().height(certificate=True)\n (4, [0, 2, 3, 4])\n\n TESTS::\n\n sage: Poset().height()\n 0\n '
if (not certificate):
return (self.rank() + 1)
levels = self.level_sets()
height = len(levels)
if (height == 0):
return (0, [])
n = (height - 2)
previous = levels[(- 1)][0]
max_chain = [previous]
while (n >= 0):
for i in levels[n]:
if self.covers(i, previous):
break
max_chain.append(i)
previous = i
n -= 1
max_chain.reverse()
return (height, max_chain)
def has_isomorphic_subposet(self, other):
'\n Return ``True`` if the poset contains a subposet isomorphic to\n ``other``.\n\n By subposet we mean that there exist a set ``X`` of elements such\n that ``self.subposet(X)`` is isomorphic to ``other``.\n\n INPUT:\n\n - ``other`` -- a finite poset\n\n EXAMPLES::\n\n sage: D = Poset({1:[2,3], 2:[4], 3:[4]})\n sage: T = Poset({1:[2,3], 2:[4,5], 3:[6,7]})\n sage: N5 = posets.PentagonPoset()\n\n sage: N5.has_isomorphic_subposet(T)\n False\n sage: N5.has_isomorphic_subposet(D)\n True\n\n sage: len([P for P in Posets(5) if P.has_isomorphic_subposet(D)])\n 11\n\n '
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
if (self._hasse_diagram.transitive_closure().subgraph_search(other._hasse_diagram.transitive_closure(), induced=True) is None):
return False
return True
def is_bounded(self) -> bool:
'\n Return ``True`` if the poset is bounded, and ``False`` otherwise.\n\n A poset is bounded if it contains both a unique maximal element\n and a unique minimal element.\n\n EXAMPLES::\n\n sage: P = Poset({0:[3], 1:[3], 2:[3], 3:[4, 5], 4:[], 5:[]})\n sage: P.is_bounded()\n False\n sage: Q = posets.DiamondPoset(5)\n sage: Q.is_bounded()\n True\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`has_bottom`, :meth:`has_top`\n - Other: :meth:`with_bounds`, :meth:`without_bounds`\n\n TESTS::\n\n sage: Poset().is_bounded() # Test empty poset\n False\n sage: Poset({1:[]}).is_bounded() # Here top == bottom\n True\n sage: ( len([P for P in Posets(5) if P.is_bounded()]) ==\n ....: Posets(3).cardinality() )\n True\n '
return self._hasse_diagram.is_bounded()
def is_chain(self) -> bool:
'\n Return ``True`` if the poset is totally ordered ("chain"), and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: I = Poset({0:[1], 1:[2], 2:[3], 3:[4]})\n sage: I.is_chain()\n True\n\n sage: II = Poset({0:[1], 2:[3]})\n sage: II.is_chain()\n False\n\n sage: V = Poset({0:[1, 2]})\n sage: V.is_chain()\n False\n\n TESTS::\n\n sage: [len([P for P in Posets(n) if P.is_chain()]) for n in range(5)]\n [1, 1, 1, 1, 1]\n '
return self._hasse_diagram.is_chain()
def is_chain_of_poset(self, elms, ordered=False) -> bool:
'\n Return ``True`` if ``elms`` is a chain of the poset,\n and ``False`` otherwise.\n\n Set of elements are a *chain* of a poset if they are comparable\n to each other.\n\n INPUT:\n\n - ``elms`` -- a list or other iterable containing some elements\n of the poset\n\n - ``ordered`` -- a Boolean. If ``True``, then return ``True``\n only if elements in ``elms`` are strictly increasing in the\n poset; this makes no sense if ``elms`` is a set. If ``False``\n (the default), then elements can be repeated and be in any\n order.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")))\n sage: sorted(P.list())\n [1, 2, 3, 4, 6, 12]\n sage: P.is_chain_of_poset([12, 3])\n True\n sage: P.is_chain_of_poset({3, 4, 12})\n False\n sage: P.is_chain_of_poset([12, 3], ordered=True)\n False\n sage: P.is_chain_of_poset((1, 1, 3))\n True\n sage: P.is_chain_of_poset((1, 1, 3), ordered=True)\n False\n sage: P.is_chain_of_poset((1, 3), ordered=True)\n True\n\n TESTS::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.is_chain_of_poset([])\n True\n sage: P.is_chain_of_poset((1,3,7,15,14))\n False\n sage: P.is_chain_of_poset({10})\n True\n sage: P.is_chain_of_poset([32])\n Traceback (most recent call last):\n ...\n ValueError: element (=32) not in poset\n '
if ordered:
sorted_o = elms
return all((self.lt(a, b) for (a, b) in zip(sorted_o, sorted_o[1:])))
else:
sorted_o = sorted(elms, key=self._element_to_vertex)
return all((self.le(a, b) for (a, b) in zip(sorted_o, sorted_o[1:])))
def is_antichain_of_poset(self, elms):
"\n Return ``True`` if ``elms`` is an antichain of the poset\n and ``False`` otherwise.\n\n Set of elements are an *antichain* of a poset if they are\n pairwise incomparable.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(5)\n sage: P.is_antichain_of_poset([3, 5, 7])\n False\n sage: P.is_antichain_of_poset([3, 5, 14])\n True\n\n TESTS::\n\n sage: P = posets.PentagonPoset()\n sage: P.is_antichain_of_poset([])\n True\n sage: P.is_antichain_of_poset([0])\n True\n sage: P.is_antichain_of_poset([1, 2, 1])\n True\n\n Check :trac:`19078`::\n\n sage: P.is_antichain_of_poset([0, 1, 'junk'])\n Traceback (most recent call last):\n ...\n ValueError: element (=junk) not in poset\n "
elms_H = [self._element_to_vertex(e) for e in elms]
return self._hasse_diagram.is_antichain_of_poset(elms_H)
def is_connected(self) -> bool:
'\n Return ``True`` if the poset is connected, and ``False`` otherwise.\n\n A poset is connected if its Hasse diagram is connected.\n\n If a poset is not connected, then it can be divided to parts\n `S_1` and `S_2` so that every element of `S_1` is incomparable to\n every element of `S_2`.\n\n EXAMPLES::\n\n sage: P = Poset({1:[2, 3], 3:[4, 5]})\n sage: P.is_connected()\n True\n\n sage: P = Poset({1:[2, 3], 3:[4, 5], 6:[7, 8]})\n sage: P.is_connected()\n False\n\n .. SEEALSO:: :meth:`connected_components`\n\n TESTS::\n\n sage: Poset().is_connected() # Test empty poset\n True\n '
return self._hasse_diagram.is_connected()
def is_series_parallel(self) -> bool:
'\n Return ``True`` if the poset is series-parallel, and ``False``\n otherwise.\n\n A poset is *series-parallel* if it can be built up from one-element\n posets using the operations of disjoint union and ordinal\n sum. This is also called *N-free* property: every poset that is not\n series-parallel contains a subposet isomorphic to the 4-element\n N-shaped poset where `a > c, d` and `b > d`.\n\n .. NOTE::\n\n Some papers use the term N-free for posets having no\n N-shaped poset as a *cover-preserving subposet*. This definition\n is not used here.\n\n See :wikipedia:`Series-parallel partial order`.\n\n EXAMPLES::\n\n sage: VA = Poset({1: [2, 3], 4: [5], 6: [5]})\n sage: VA.is_series_parallel()\n True\n sage: big_N = Poset({1: [2, 4], 2: [3], 4:[7], 5:[6], 6:[7]})\n sage: big_N.is_series_parallel()\n False\n\n TESTS::\n\n sage: Poset().is_series_parallel()\n True\n '
if (self.cardinality() < 4):
return True
if (not self.is_connected()):
return all((part.is_series_parallel() for part in self.connected_components()))
parts = self.ordinal_summands()
if (len(parts) == 1):
return False
return all((part.is_series_parallel() for part in parts))
def is_EL_labelling(self, f, return_raising_chains=False):
'\n Return ``True`` if ``f`` is an EL labelling of ``self``.\n\n A labelling `f` of the edges of the Hasse diagram of a poset\n is called an EL labelling (edge lexicographic labelling) if\n for any two elements `u` and `v` with `u \\leq v`,\n\n - there is a unique `f`-raising chain from `u` to `v` in\n the Hasse diagram, and this chain is lexicographically\n first among all chains from `u` to `v`.\n\n For more details, see [Bj1980]_.\n\n INPUT:\n\n - ``f`` -- a function taking two elements ``a`` and ``b`` in\n ``self`` such that ``b`` covers ``a`` and returning elements\n in a totally ordered set.\n\n - ``return_raising_chains`` (optional; default:``False``) if\n ``True``, returns the set of all raising chains in ``self``,\n if possible.\n\n EXAMPLES:\n\n Let us consider a Boolean poset::\n\n sage: P = Poset([[(0,0),(0,1),(1,0),(1,1)],[[(0,0),(0,1)],[(0,0),(1,0)],[(0,1),(1,1)],[(1,0),(1,1)]]],facade=True)\n sage: label = lambda a,b: min( i for i in [0,1] if a[i] != b[i] )\n sage: P.is_EL_labelling(label)\n True\n sage: P.is_EL_labelling(label,return_raising_chains=True)\n {((0, 0), (0, 1)): [1],\n ((0, 0), (1, 0)): [0],\n ((0, 0), (1, 1)): [0, 1],\n ((0, 1), (1, 1)): [0],\n ((1, 0), (1, 1)): [1]}\n '
label_dict = {(a, b): f(a, b) for (a, b) in self.cover_relations_iterator()}
if return_raising_chains:
raising_chains = {}
for (a, b) in self.relations_iterator(strict=True):
P = self.subposet(self.interval(a, b))
max_chains = sorted([[label_dict[(chain[i], chain[(i + 1)])] for i in range((len(chain) - 1))] for chain in P.maximal_chains_iterator()])
if ((max_chains[0] != sorted(max_chains[0])) or any(((max_chains[i] == sorted(max_chains[i])) for i in range(1, len(max_chains))))):
return False
elif return_raising_chains:
raising_chains[(a, b)] = max_chains[0]
if return_raising_chains:
return raising_chains
else:
return True
def dimension(self, certificate=False, *, solver=None, integrality_tolerance=0.001):
'\n Return the dimension of the Poset.\n\n The (Dushnik-Miller) dimension of a poset is the minimal\n number of total orders so that the poset is their\n "intersection". More precisely, the dimension of a poset\n defined on a set `X` of points is the smallest integer `n`\n such that there exist linear extensions `P_1,...,P_n` of `P`\n satisfying:\n\n .. MATH::\n\n u\\leq_P v\\ \\text{if and only if }\\ \\forall i, u\\leq_{P_i} v\n\n For more information, see the :wikipedia:`Order_dimension`.\n\n INPUT:\n\n - ``certificate`` (boolean; default:``False``) -- whether to return an\n integer (the dimension) or a certificate, i.e. a smallest set of\n linear extensions.\n\n - ``solver`` -- (default: ``None``) Specify a Mixed Integer Linear Programming\n (MILP) solver to be used. If set to ``None``, the default one is used. For\n more information on MILP solvers and which default solver is used, see\n the method\n :meth:`solve <sage.numerical.mip.MixedIntegerLinearProgram.solve>`\n of the class\n :class:`MixedIntegerLinearProgram <sage.numerical.mip.MixedIntegerLinearProgram>`.\n\n - ``integrality_tolerance`` -- parameter for use with MILP solvers over an\n inexact base ring; see :meth:`MixedIntegerLinearProgram.get_values`.\n\n .. NOTE::\n\n The speed of this function greatly improves when more efficient\n MILP solvers (e.g. Gurobi, CPLEX) are installed. See\n :class:`MixedIntegerLinearProgram` for more information.\n\n .. NOTE::\n\n Prior to version 8.3 this returned only realizer with\n ``certificate=True``. Now it returns a pair having a realizer as\n the second element. See :trac:`25588` for details.\n\n ALGORITHM:\n\n As explained [FT00]_, the dimension of a poset is equal to the (weak)\n chromatic number of a hypergraph. More precisely:\n\n Let `inc(P)` be the set of (ordered) pairs of incomparable elements\n of `P`, i.e. all `uv` and `vu` such that `u\\not \\leq_P v` and `v\\not\n \\leq_P u`. Any linear extension of `P` is a total order on `X` that\n can be seen as the union of relations from `P` along with some\n relations from `inc(P)`. Thus, the dimension of `P` is the smallest\n number of linear extensions of `P` which *cover* all points of\n `inc(P)`.\n\n Consequently, `dim(P)` is equal to the chromatic number of the\n hypergraph `\\mathcal H_{inc}`, where `\\mathcal H_{inc}` is the\n hypergraph defined on `inc(P)` whose sets are all `S\\subseteq\n inc(P)` such that `P\\cup S` is not acyclic.\n\n We solve this problem through a :mod:`Mixed Integer Linear Program\n <sage.numerical.mip>`.\n\n The problem is known to be NP-complete.\n\n EXAMPLES:\n\n We create a poset, compute a set of linear extensions and check\n that we get back the poset from them::\n\n sage: P = Poset([[1,4], [3], [4,5,3], [6], [], [6], []])\n sage: P.dimension()\n 3\n sage: dim, L = P.dimension(certificate=True)\n sage: L # random -- architecture-dependent\n [[0, 2, 4, 5, 1, 3, 6], [2, 5, 0, 1, 3, 4, 6], [0, 1, 2, 3, 5, 6, 4]]\n sage: Poset( (L[0], lambda x, y: all(l.index(x) < l.index(y) for l in L)) ) == P\n True\n\n According to Schnyder\'s theorem, the incidence poset (of\n height 2) of a graph has dimension `\\leq 3` if and only if\n the graph is planar::\n\n sage: G = graphs.CompleteGraph(4)\n sage: P = Poset(DiGraph({(u,v):[u,v] for u,v,_ in G.edges(sort=True)}))\n sage: P.dimension()\n 3\n\n sage: G = graphs.CompleteBipartiteGraph(3,3)\n sage: P = Poset(DiGraph({(u,v):[u,v] for u,v,_ in G.edges(sort=True)}))\n sage: P.dimension() # not tested - around 4s with CPLEX\n 4\n\n TESTS:\n\n Empty Poset::\n\n sage: Poset().dimension()\n 0\n sage: Poset().dimension(certificate=True)\n (0, [])\n\n Chain and certificate, :trac:`26861`::\n\n sage: Poset({\'a\': [\'b\']}).dimension(certificate=True)[1]\n [[\'a\', \'b\']]\n '
if (self.cardinality() == 0):
return ((0, []) if certificate else 0)
if self.is_chain():
return ((1, [self.list()]) if certificate else 1)
k = 2
if (not certificate):
from sage.graphs.comparability import greedy_is_comparability as is_comparability
if is_comparability(self._hasse_diagram.transitive_closure().to_undirected().complement()):
return 2
k = 3
max_value = max((self.cardinality() // 2), self.width())
from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException
P = Poset(self._hasse_diagram)
hasse_diagram = P.hasse_diagram()
inc_graph = P.incomparability_graph()
inc_P = inc_graph.edges(sort=False, labels=False)
cycles = [[(u, v), (v, u)] for (u, v) in inc_P]
def init_LP(k, cycles, inc_P):
"\n Initialize a LP object with k colors and the constraints from 'cycles'\n\n sage: init_LP(1,2,3) # not tested\n "
p = MixedIntegerLinearProgram(constraint_generation=True, solver=solver)
b = p.new_variable(binary=True)
for (u, v) in inc_P:
p.add_constraint((p.sum((b[((u, v), i)] for i in range(k))) == 1))
p.add_constraint((p.sum((b[((v, u), i)] for i in range(k))) == 1))
for cycle in cycles:
for i in range(k):
p.add_constraint((p.sum((b[(point, i)] for point in cycle)) <= (len(cycle) - 1)))
return (p, b)
(p, b) = init_LP(k, cycles, inc_P)
while True:
if ((not certificate) and (k == max_value)):
return k
try:
p.solve()
except MIPSolverException:
k += 1
(p, b) = init_LP(k, cycles, inc_P)
continue
linear_extensions = [hasse_diagram.copy() for i in range(k)]
for (((u, v), i), x) in p.get_values(b, convert=bool, tolerance=integrality_tolerance).items():
if x:
linear_extensions[i].add_edge(u, v)
okay = True
for g in linear_extensions:
(is_acyclic, cycle) = g.is_directed_acyclic(certificate=True)
if (not is_acyclic):
okay = False
cycle = [(cycle[(i - 1)], cycle[i]) for i in range(len(cycle))]
cycle = [(u, v) for (u, v) in cycle if ((not P.lt(u, v)) and (not P.lt(v, u)))]
cycles.append(cycle)
for i in range(k):
p.add_constraint((p.sum((b[(point, i)] for point in cycle)) <= (len(cycle) - 1)))
if okay:
break
linear_extensions = [g.topological_sort() for g in linear_extensions]
if certificate:
return (k, [[self._list[i] for i in l] for l in linear_extensions])
return k
def magnitude(self) -> Integer:
'\n Return the magnitude of ``self``.\n\n The magnitude is an integer defined as the sum of all Möbius\n numbers, and can be seen as some kind of Euler characteristic of\n the poset. It is additive under disjoint union and multiplicative\n under Cartesian product.\n\n REFERENCES:\n\n - [Lein2008] Tom Leinster, *The Euler Characteristic of a Category*,\n Documenta Mathematica, Vol. 13 (2008), 21-49\n https://www.math.uni-bielefeld.de/documenta/vol-13/02.html\n\n - https://golem.ph.utexas.edu/category/2011/06/the_magnitude_of_an_enriched_c.html\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.libs.flint\n sage: P = posets.PentagonPoset()\n sage: P.magnitude()\n 1\n\n sage: W = SymmetricGroup(4)\n sage: P = W.noncrossing_partition_lattice().without_bounds()\n sage: P.magnitude()\n -4\n\n sage: P = posets.TamariLattice(4).without_bounds()\n sage: P.magnitude()\n 0\n\n .. SEEALSO:: :meth:`order_complex`\n\n TESTS::\n\n sage: # needs sage.groups sage.libs.flint\n sage: P1 = posets.RandomPoset(20, 0.05)\n sage: P2 = posets.RandomPoset(20, 0.05)\n sage: m1 = P1.magnitude()\n sage: m2 = P2.magnitude()\n sage: U = P1.disjoint_union(P2)\n sage: P = P1.product(P2)\n sage: U.magnitude() == m1 + m2\n True\n sage: P.magnitude() == m1*m2\n True\n\n sage: Poset({}).magnitude() # needs sage.libs.flint\n 0\n sage: Poset({1: []}).magnitude() # needs sage.libs.flint\n 1\n '
H = self._hasse_diagram
return sum(H.moebius_function_matrix().list())
def jump_number(self, certificate=False):
'\n Return the jump number of the poset.\n\n A *jump* in a linear extension `[e_1, \\ldots, e_n]` of a poset `P`\n is a pair `(e_i, e_{i+1})` so that `e_{i+1}` does not cover `e_i`\n in `P`. The jump number of a poset is the minimal number of jumps\n in linear extensions of a poset.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) Whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return a pair `(n, l)` where\n `n` is the jump number and `l` is a linear extension\n with `n` jumps. If ``certificate=False`` return only\n the jump number.\n\n EXAMPLES::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3.jump_number()\n 3\n\n sage: N = Poset({1: [3, 4], 2: [3]})\n sage: N.jump_number(certificate=True)\n (1, [1, 4, 2, 3])\n\n ALGORITHM:\n\n It is known that every poset has a greedy linear extension --\n an extension `[e_1, e_2, \\ldots, e_n]` where every `e_{i+1}` is\n an upper cover of `e_i` if that is possible -- with the smallest\n possible number of jumps; see [Sys1987]_.\n\n Hence it suffices to test only those. We do that by backtracking.\n\n The problem is proven to be NP-complete.\n\n .. SEEALSO:: :meth:`is_jump_critical`\n\n TESTS::\n\n sage: E = Poset()\n sage: E.jump_number(certificate=True)\n (0, [])\n\n sage: C4 = posets.ChainPoset(4)\n sage: A4 = posets.AntichainPoset(4)\n sage: C4.jump_number()\n 0\n sage: A4.jump_number()\n 3\n '
N = self.cardinality()
if (N == 0):
return ((0, []) if certificate else 0)
self_as_set = set(self)
nonlocals = [N, []]
def greedy_rec(self, linext, jumpcount):
'\n Recursively extend beginning of a linear extension by one element,\n unless we see that an extension with smaller jump number already\n has been found.\n '
if (len(linext) == N):
nonlocals[0] = jumpcount
nonlocals[1] = linext[:]
return
S = []
if linext:
S = [x for x in self.upper_covers(linext[(- 1)]) if all(((low in linext) for low in self.lower_covers(x)))]
if (not S):
if (jumpcount >= (nonlocals[0] - 1)):
return
jumpcount += 1
S_ = self_as_set.difference(set(linext))
S = [x for x in S_ if (not any(((low in S_) for low in self.lower_covers(x))))]
for e in S:
greedy_rec(self, (linext + [e]), jumpcount)
greedy_rec(self, [], (- 1))
if certificate:
return (nonlocals[0], nonlocals[1])
return nonlocals[0]
def is_jump_critical(self, certificate=False):
'\n Return ``True`` if the poset is jump-critical, and ``False`` otherwise.\n\n A poset `P` is *jump-critical* if every proper subposet has smaller\n jump number.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, e)`` so that removing element `e` from the poset does not\n decrease the jump number. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: P = Poset({1: [3, 6], 2: [3, 4, 5], 4: [6, 7], 5: [7]})\n sage: P.is_jump_critical()\n True\n\n sage: P = posets.PentagonPoset()\n sage: P.is_jump_critical()\n False\n sage: P.is_jump_critical(certificate=True)\n (False, 3)\n\n .. SEEALSO:: :meth:`jump_number`\n\n TESTS::\n\n sage: Poset().is_jump_critical()\n True\n sage: Poset().is_jump_critical(certificate=True)\n (True, None)\n '
for e in self:
up = self.upper_covers(e)
if (len(up) == 1):
if (len(self.upper_covers(up[0])) == 1):
if certificate:
return (False, up[0])
return False
jumps = self.jump_number()
for e in self:
P = self.subposet([x for x in self if (x != e)])
if (P.jump_number() == jumps):
return ((False, e) if certificate else False)
return ((True, None) if certificate else True)
def rank_function(self):
'\n Return the (normalized) rank function of the poset,\n if it exists.\n\n A *rank function* of a poset `P` is a function `r`\n that maps elements of `P` to integers and satisfies:\n `r(x) = r(y) + 1` if `x` covers `y`. The function `r`\n is normalized such that its minimum value on every\n connected component of the Hasse diagram of `P` is\n `0`. This determines the function `r` uniquely (when\n it exists).\n\n OUTPUT:\n\n - a lambda function, if the poset admits a rank function\n - ``None``, if the poset does not admit a rank function\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3,4],[[1,4],[2,3],[3,4]]), facade=True)\n sage: P.rank_function() is not None\n True\n sage: P = Poset(([1,2,3,4,5],[[1,2],[2,3],[3,4],[1,5],[5,4]]), facade=True)\n sage: P.rank_function() is not None\n False\n sage: P = Poset(([1,2,3,4,5,6,7,8],[[1,4],[2,3],[3,4],[5,7],[6,7]]), facade=True)\n sage: f = P.rank_function(); f is not None\n True\n sage: f(5)\n 0\n sage: f(2)\n 0\n\n TESTS::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: r = P.rank_function()\n sage: for u,v in P.cover_relations_iterator():\n ....: if r(v) != r(u) + 1:\n ....: print("Bug in rank_function!")\n\n ::\n\n sage: Q = Poset([[1,2],[4],[3],[4],[]])\n sage: Q.rank_function() is None\n True\n '
hasse_rf = self._hasse_diagram.rank_function()
if (hasse_rf is None):
return None
else:
return (lambda z: hasse_rf(self._element_to_vertex(z)))
def rank(self, element=None):
"\n Return the rank of an element ``element`` in the poset ``self``,\n or the rank of the poset if ``element`` is ``None``.\n\n (The rank of a poset is the length of the longest chain of\n elements of the poset. This is sometimes called the length of a poset.)\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]], facade = False)\n sage: P.rank(5)\n 2\n sage: P.rank()\n 3\n sage: Q = Poset([[1,2],[3],[],[]])\n\n sage: P = posets.SymmetricGroupBruhatOrderPoset(4)\n sage: [(v,P.rank(v)) for v in P]\n [('1234', 0),\n ('1243', 1),\n ...\n ('4312', 5),\n ('4321', 6)]\n "
if (element is None):
return (len(self.level_sets()) - 1)
elif self.is_ranked():
return self.rank_function()(element)
else:
raise ValueError('the poset is not ranked')
def is_ranked(self) -> bool:
'\n Return ``True`` if the poset is ranked, and ``False`` otherwise.\n\n A poset is ranked if there is a function `r` from poset elements\n to integers so that `r(x)=r(y)+1` when `x` covers `y`.\n\n Informally said a ranked poset can be "levelized": every element is\n on a "level", and every cover relation goes only one level up.\n\n EXAMPLES::\n\n sage: P = Poset( ([1, 2, 3, 4], [[1, 2], [2, 4], [3, 4]] ))\n sage: P.is_ranked()\n True\n\n sage: P = Poset([[1, 5], [2, 6], [3], [4],[], [6, 3], [4]])\n sage: P.is_ranked()\n False\n\n .. SEEALSO:: :meth:`rank_function`, :meth:`rank`, :meth:`is_graded`\n\n TESTS::\n\n sage: Poset().is_ranked() # Test empty poset\n True\n '
return bool(self.rank_function())
def is_graded(self) -> bool:
"\n Return ``True`` if the poset is graded, and ``False`` otherwise.\n\n A poset is graded if all its maximal chains have the same length.\n\n There are various competing definitions for graded\n posets (see :wikipedia:`Graded_poset`). This definition is from\n section 3.1 of Richard Stanley's *Enumerative Combinatorics,\n Vol. 1* [EnumComb1]_. Some sources call these posets *tiered*.\n\n Every graded poset is ranked. The converse is true\n for bounded posets, including lattices.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset() # Not even ranked\n sage: P.is_graded()\n False\n\n sage: P = Poset({1:[2, 3], 3:[4]}) # Ranked, but not graded\n sage: P.is_graded()\n False\n\n sage: P = Poset({1:[3, 4], 2:[3, 4], 5:[6]})\n sage: P.is_graded()\n True\n\n sage: P = Poset([[1], [2], [], [4], []])\n sage: P.is_graded()\n False\n\n .. SEEALSO:: :meth:`is_ranked`, :meth:`level_sets`\n\n TESTS::\n\n sage: Poset().is_graded() # Test empty poset\n True\n "
if (len(self) <= 2):
return True
hasse = self._hasse_diagram
rf = hasse.rank_function()
if (rf is None):
return False
if (not all(((rf(i) == 0) for i in hasse.minimal_elements()))):
return False
maxes = hasse.maximal_elements()
rank = rf(maxes[0])
return all(((rf(i) == rank) for i in maxes))
def covers(self, x, y):
'\n Return ``True`` if ``y`` covers ``x`` and ``False`` otherwise.\n\n Element `y` covers `x` if `x < y` and there is no `z` such that\n `x < z < y`.\n\n EXAMPLES::\n\n sage: P = Poset([[1,5], [2,6], [3], [4], [], [6,3], [4]])\n sage: P.covers(1, 6)\n True\n sage: P.covers(1, 4)\n False\n sage: P.covers(1, 5)\n False\n '
return self._hasse_diagram.has_edge(*[self._element_to_vertex(w) for w in (x, y)])
def upper_covers_iterator(self, x):
"\n Return an iterator over the upper covers of the element ``x``.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[]})\n sage: type(P.upper_covers_iterator(0))\n <class 'generator'>\n "
for e in self._hasse_diagram.neighbor_out_iterator(self._element_to_vertex(x)):
(yield self._vertex_to_element(e))
def upper_covers(self, x):
'\n Return the list of upper covers of the element ``x``.\n\n An upper cover of `x` is an element `y` such that `x < y` and\n there is no element `z` so that `x < z < y`.\n\n EXAMPLES::\n\n sage: P = Poset([[1,5], [2,6], [3], [4], [], [6,3], [4]])\n sage: P.upper_covers(1)\n [2, 6]\n\n .. SEEALSO:: :meth:`lower_covers`\n '
return [e for e in self.upper_covers_iterator(x)]
def lower_covers_iterator(self, x):
"\n Return an iterator over the lower covers of the element ``x``.\n\n EXAMPLES::\n\n sage: P = Poset({0:[2], 1:[2], 2:[3], 3:[]})\n sage: l0 = P.lower_covers_iterator(3)\n sage: type(l0)\n <class 'generator'>\n sage: next(l0)\n 2\n "
for e in self._hasse_diagram.neighbor_in_iterator(self._element_to_vertex(x)):
(yield self._vertex_to_element(e))
def lower_covers(self, x):
'\n Return the list of lower covers of the element ``x``.\n\n A lower cover of `x` is an element `y` such that `y < x` and\n there is no element `z` so that `y < z < x`.\n\n EXAMPLES::\n\n sage: P = Poset([[1,5], [2,6], [3], [4], [], [6,3], [4]])\n sage: P.lower_covers(3)\n [2, 5]\n sage: P.lower_covers(0)\n []\n\n .. SEEALSO:: :meth:`upper_covers`\n '
return [e for e in self.lower_covers_iterator(x)]
def cardinality(self):
'\n Return the number of elements in the poset.\n\n EXAMPLES::\n\n sage: Poset([[1,2,3],[4],[4],[4],[]]).cardinality()\n 5\n\n .. SEEALSO::\n\n :meth:`degree_polynomial` for a more refined invariant\n '
return Integer(self._hasse_diagram.order())
def moebius_function(self, x, y):
'\n Return the value of the Möbius function of the poset on the\n elements x and y.\n\n EXAMPLES::\n\n sage: P = Poset([[1,2,3],[4],[4],[4],[]])\n sage: P.moebius_function(P(0),P(4))\n 2\n sage: sum(P.moebius_function(P(0),v) for v in P)\n 0\n sage: sum(abs(P.moebius_function(P(0),v))\n ....: for v in P)\n 6\n sage: for u,v in P.cover_relations_iterator():\n ....: if P.moebius_function(u,v) != -1:\n ....: print("Bug in moebius_function!")\n\n ::\n\n sage: Q = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]])\n sage: Q.moebius_function(Q(0),Q(7))\n 0\n sage: Q.moebius_function(Q(0),Q(5))\n 0\n sage: Q.moebius_function(Q(2),Q(7))\n 2\n sage: Q.moebius_function(Q(3),Q(3))\n 1\n sage: sum([Q.moebius_function(Q(0),v) for v in Q])\n 0\n '
(i, j) = map(self._element_to_vertex, (x, y))
return self._hasse_diagram.moebius_function(i, j)
def moebius_function_matrix(self, ring=ZZ, sparse=False):
'\n Return a matrix whose ``(i,j)`` entry is the value of the Möbius\n function evaluated at ``self.linear_extension()[i]`` and\n ``self.linear_extension()[j]``.\n\n INPUT:\n\n - ``ring`` -- the ring of coefficients (default: ``ZZ``)\n - ``sparse`` -- whether the returned matrix is sparse or not\n (default: ``True``)\n\n EXAMPLES::\n\n sage: P = Poset([[4,2,3],[],[1],[1],[1]])\n sage: x,y = (P.linear_extension()[0],P.linear_extension()[1])\n sage: P.moebius_function(x,y)\n -1\n sage: M = P.moebius_function_matrix(); M # needs sage.libs.flint\n [ 1 -1 -1 -1 2]\n [ 0 1 0 0 -1]\n [ 0 0 1 0 -1]\n [ 0 0 0 1 -1]\n [ 0 0 0 0 1]\n sage: M[0,4] # needs sage.libs.flint\n 2\n sage: M[0,1] # needs sage.libs.flint\n -1\n\n We now demonstrate the usage of the optional parameters::\n\n sage: P.moebius_function_matrix(ring=QQ, sparse=False).parent() # needs sage.libs.flint\n Full MatrixSpace of 5 by 5 dense matrices over Rational Field\n '
M = self._hasse_diagram.moebius_function_matrix()
if (ring is not ZZ):
M = M.change_ring(ring)
if (not sparse):
M = M.dense_matrix()
return M
def lequal_matrix(self, ring=ZZ, sparse=False):
'\n Compute the matrix whose ``(i,j)`` entry is 1 if\n ``self.linear_extension()[i] < self.linear_extension()[j]`` and 0\n otherwise.\n\n INPUT:\n\n - ``ring`` -- the ring of coefficients (default: ``ZZ``)\n - ``sparse`` -- whether the returned matrix is sparse or not\n (default: ``True``)\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]], facade=False)\n sage: LEQM = P.lequal_matrix(); LEQM\n [1 1 1 1 1 1 1 1]\n [0 1 0 1 0 0 0 1]\n [0 0 1 1 1 0 1 1]\n [0 0 0 1 0 0 0 1]\n [0 0 0 0 1 0 0 1]\n [0 0 0 0 0 1 1 1]\n [0 0 0 0 0 0 1 1]\n [0 0 0 0 0 0 0 1]\n sage: LEQM[1,3]\n 1\n sage: P.linear_extension()[1] < P.linear_extension()[3]\n True\n sage: LEQM[2,5]\n 0\n sage: P.linear_extension()[2] < P.linear_extension()[5]\n False\n\n We now demonstrate the usage of the optional parameters::\n\n sage: P.lequal_matrix(ring=QQ, sparse=False).parent() # needs sage.libs.flint\n Full MatrixSpace of 8 by 8 dense matrices over Rational Field\n '
M = self._hasse_diagram.lequal_matrix(boolean=False)
if (ring is not ZZ):
M = M.change_ring(ring)
if (not sparse):
M = M.dense_matrix()
return M
def coxeter_transformation(self):
'\n Return the Coxeter transformation of the poset.\n\n OUTPUT:\n\n a square matrix with integer coefficients\n\n The output is the matrix of the Auslander-Reiten translation\n acting on the Grothendieck group of the derived category of\n modules on the poset, in the basis of simple\n modules. This matrix is usually called the Coxeter\n transformation.\n\n EXAMPLES::\n\n sage: posets.PentagonPoset().coxeter_transformation() # needs sage.libs.flint\n [ 0 0 0 0 -1]\n [ 0 0 0 1 -1]\n [ 0 1 0 0 -1]\n [-1 1 1 0 -1]\n [-1 1 0 1 -1]\n\n .. SEEALSO::\n\n :meth:`coxeter_polynomial`, :meth:`coxeter_smith_form`\n\n TESTS::\n\n sage: M = posets.PentagonPoset().coxeter_transformation() # needs sage.libs.flint\n sage: M ** 8 == 1 # needs sage.libs.flint\n True\n '
return self._hasse_diagram.coxeter_transformation()
def coxeter_polynomial(self):
'\n Return the Coxeter polynomial of the poset.\n\n OUTPUT:\n\n a polynomial in one variable\n\n The output is the characteristic polynomial of the Coxeter\n transformation. This polynomial only depends on the derived\n category of modules on the poset.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.coxeter_polynomial() # needs sage.libs.flint\n x^5 + x^4 + x + 1\n\n sage: p = posets.SymmetricGroupWeakOrderPoset(3) # needs sage.groups\n sage: p.coxeter_polynomial() # needs sage.groups sage.libs.flint\n x^6 + x^5 - x^3 + x + 1\n\n .. SEEALSO::\n\n :meth:`coxeter_transformation`, :meth:`coxeter_smith_form`\n '
return self._hasse_diagram.coxeter_transformation().charpoly()
def coxeter_smith_form(self, algorithm='singular'):
"\n Return the Smith normal form of `x` minus the Coxeter transformation\n matrix.\n\n INPUT:\n\n - ``algorithm`` -- optional (default ``'singular'``), possible\n values are ``'singular'``, ``'sage'``, ``'gap'``,\n ``'pari'``, ``'maple'``, ``'magma'``, ``'fricas'``\n\n Beware that speed depends very much on the choice of\n algorithm. Sage is rather slow, Singular is faster and Pari is\n fast at least for small sizes.\n\n OUTPUT:\n\n - list of polynomials in one variable, each one dividing the next one\n\n The output list is a refinement of the characteristic polynomial of\n the Coxeter transformation, which is its product. This list\n of polynomials only depends on the derived category of modules\n on the poset.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.coxeter_smith_form() # needs sage.libs.singular\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n\n sage: P = posets.DiamondPoset(7)\n sage: prod(P.coxeter_smith_form()) == P.coxeter_polynomial() # needs sage.libs.singular\n True\n\n TESTS::\n\n sage: P = posets.PentagonPoset()\n sage: P.coxeter_smith_form(algorithm='sage') # needs sage.libs.flint\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n sage: P.coxeter_smith_form(algorithm='gap') # needs sage.libs.gap\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n sage: P.coxeter_smith_form(algorithm='pari') # needs sage.libs.pari\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n sage: P.coxeter_smith_form(algorithm='fricas') # optional - fricas\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n sage: P.coxeter_smith_form(algorithm='maple') # optional - maple\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n sage: P.coxeter_smith_form(algorithm='magma') # optional - magma\n [1, 1, 1, 1, x^5 + x^4 + x + 1]\n\n .. SEEALSO::\n\n :meth:`coxeter_transformation`, :meth:`coxeter_matrix`\n "
c0 = self.coxeter_transformation()
x = polygen(QQ, 'x')
if (algorithm == 'singular'):
from sage.interfaces.singular import singular
singular.LIB('jacobson.lib')
sing_m = singular((x - c0))
L = sing_m.smith().sage().diagonal()
return sorted([(u / u.lc()) for u in L], key=(lambda p: p.degree()))
if (algorithm == 'sage'):
return (x - c0).smith_form(transformation=False).diagonal()
if (algorithm == 'magma'):
from sage.interfaces.magma import magma
elem = magma('ElementaryDivisors')
return elem.evaluate((x - c0)).sage()
if (algorithm == 'gap'):
from sage.libs.gap.libgap import libgap
gap_m = libgap((x - c0))
elem = gap_m.ElementaryDivisorsMat()
return elem.sage()
if (algorithm == 'pari'):
from sage.libs.pari import pari
pari_m = pari((x - c0))
elem = pari_m.matsnf(2)
A = x.parent()
return sorted((A(f) for f in elem), key=(lambda p: p.degree()))
if (algorithm == 'maple'):
from sage.interfaces.maple import maple
maple_m = maple((x - c0))
maple.load('MatrixPolynomialAlgebra')
maple.load('ArrayTools')
elem = maple.SmithForm(maple_m).Diagonal()
A = x.parent()
return [A(f.sage()) for f in elem]
if (algorithm == 'fricas'):
from sage.interfaces.fricas import fricas
fm = fricas((x - c0))
return list(fricas((fm.name() + '::Matrix(UP(x, FRAC INT))')).smith().diagonal().sage())
def is_meet_semilattice(self, certificate=False):
'\n Return ``True`` if the poset has a meet operation, and\n ``False`` otherwise.\n\n A meet is the greatest lower bound for given elements, if it exists.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b))`` where elements `a` and `b` have no\n greatest lower bound. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: P = Poset({1:[2, 3, 4], 2:[5, 6], 3:[6], 4:[6, 7]})\n sage: P.is_meet_semilattice()\n True\n\n sage: Q = P.dual()\n sage: Q.is_meet_semilattice()\n False\n\n sage: V = posets.IntegerPartitions(5) # needs sage.combinat\n sage: V.is_meet_semilattice(certificate=True) # needs sage.combinat\n (False, ((2, 2, 1), (3, 1, 1)))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_join_semilattice`\n - Stronger properties: :meth:`~sage.categories.finite_posets.FinitePosets.ParentMethods.is_lattice`\n\n TESTS::\n\n sage: Poset().is_meet_semilattice() # Test empty lattice\n True\n sage: len([P for P in Posets(4) if P.is_meet_semilattice()])\n 5\n\n sage: P = Poset({1: [2], 3: []})\n sage: P.is_meet_semilattice(certificate=True)\n (False, (3, 1))\n '
from sage.combinat.posets.hasse_diagram import LatticeError
try:
self._hasse_diagram.meet_matrix()
except LatticeError as error:
if (not certificate):
return False
x = self._vertex_to_element(error.x)
y = self._vertex_to_element(error.y)
return (False, (x, y))
except ValueError as error:
if (error.args[0] != 'not a meet-semilattice: no bottom element'):
raise
if (not certificate):
return False
i = 1
while (self._hasse_diagram.in_degree(i) > 0):
i += 1
x = self._vertex_to_element(0)
y = self._vertex_to_element(i)
return (False, (x, y))
if certificate:
return (True, None)
return True
def is_join_semilattice(self, certificate=False):
'\n Return ``True`` if the poset has a join operation, and ``False``\n otherwise.\n\n A join is the least upper bound for given elements, if it exists.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b))`` where elements `a` and `b` have no\n least upper bound. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: P = Poset([[1,3,2], [4], [4,5,6], [6], [7], [7], [7], []])\n sage: P.is_join_semilattice()\n True\n\n sage: P = Poset({1:[3, 4], 2:[3, 4], 3:[5], 4:[5]})\n sage: P.is_join_semilattice()\n False\n sage: P.is_join_semilattice(certificate=True)\n (False, (2, 1))\n\n .. SEEALSO::\n\n - Dual property: :meth:`is_meet_semilattice`\n - Stronger properties: :meth:`~sage.categories.finite_posets.FinitePosets.ParentMethods.is_lattice`\n\n TESTS::\n\n sage: Poset().is_join_semilattice() # Test empty lattice\n True\n sage: len([P for P in Posets(4) if P.is_join_semilattice()])\n 5\n\n sage: X = Poset({1: [3], 2: [3], 3: [4, 5]})\n sage: X.is_join_semilattice(certificate=True)\n (False, (5, 4))\n '
from sage.combinat.posets.hasse_diagram import LatticeError
try:
self._hasse_diagram.join_matrix()
except LatticeError as error:
if (not certificate):
return False
x = self._vertex_to_element(error.x)
y = self._vertex_to_element(error.y)
return (False, (x, y))
except ValueError as error:
if (error.args[0] != 'not a join-semilattice: no top element'):
raise
if (not certificate):
return False
n = (self.cardinality() - 1)
i = (n - 1)
while (self._hasse_diagram.out_degree(i) > 0):
i -= 1
x = self._vertex_to_element(n)
y = self._vertex_to_element(i)
return (False, (x, y))
if certificate:
return (True, None)
return True
def is_isomorphic(self, other, **kwds):
'\n Return ``True`` if both posets are isomorphic.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2,3],[[1,3],[2,3]]))\n sage: Q = Poset(([4,5,6],[[4,6],[5,6]]))\n sage: P.is_isomorphic(Q)\n True\n\n TESTS:\n\n Since :trac:`25576`, one can ask for the isomorphism::\n\n sage: P.is_isomorphic(Q, certificate=True)\n (True, {1: 4, 2: 5, 3: 6})\n '
if hasattr(other, 'hasse_diagram'):
return self.hasse_diagram().is_isomorphic(other.hasse_diagram(), **kwds)
else:
raise TypeError("'other' is not a finite poset")
def isomorphic_subposets_iterator(self, other):
'\n Return an iterator over the subposets of ``self`` isomorphic to\n ``other``.\n\n By subposet we mean ``self.subposet(X)`` which is isomorphic\n to ``other`` and where ``X`` is a subset of elements of\n ``self``.\n\n INPUT:\n\n - ``other`` -- a finite poset\n\n EXAMPLES::\n\n sage: D = Poset({1:[2,3], 2:[4], 3:[4]})\n sage: N5 = posets.PentagonPoset()\n sage: for P in N5.isomorphic_subposets_iterator(D):\n ....: print(P.cover_relations())\n [[0, 1], [0, 2], [1, 4], [2, 4]]\n [[0, 1], [0, 3], [1, 4], [3, 4]]\n [[0, 1], [0, 2], [1, 4], [2, 4]]\n [[0, 1], [0, 3], [1, 4], [3, 4]]\n\n .. WARNING::\n\n This function will return same subposet as many times as\n there are automorphism on it. This is due to\n :meth:`~sage.graphs.generic_graph.GenericGraph.subgraph_search_iterator`\n returning labelled subgraphs. On the other hand, this\n function does not eat memory like\n :meth:`isomorphic_subposets` does.\n\n .. SEEALSO::\n\n :meth:`sage.combinat.posets.lattices.FiniteLatticePoset.isomorphic_sublattices_iterator`.\n '
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
return (self.subposet([self._list[i] for i in x]) for x in self._hasse_diagram.transitive_closure().subgraph_search_iterator(other.hasse_diagram().transitive_closure(), induced=True, return_graphs=False))
def isomorphic_subposets(self, other):
"\n Return a list of subposets of ``self`` isomorphic to ``other``.\n\n By subposet we mean ``self.subposet(X)`` which is isomorphic to\n ``other`` and where ``X`` is a subset of elements of ``self``.\n\n INPUT:\n\n - ``other`` -- a finite poset\n\n EXAMPLES::\n\n sage: C2 = Poset({0:[1]})\n sage: C3 = Poset({'a':['b'], 'b':['c']})\n sage: L = sorted(x.cover_relations() for x in C3.isomorphic_subposets(C2))\n sage: for x in L: print(x)\n [['a', 'b']]\n [['a', 'c']]\n [['b', 'c']]\n\n sage: D = Poset({1:[2,3], 2:[4], 3:[4]})\n sage: N5 = posets.PentagonPoset()\n sage: len(N5.isomorphic_subposets(D))\n 2\n\n .. NOTE::\n\n If this function takes too much time, try using\n :meth:`isomorphic_subposets_iterator`.\n "
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
L = self._hasse_diagram.transitive_closure().subgraph_search_iterator(other._hasse_diagram.transitive_closure(), induced=True, return_graphs=False)
return [self.subposet([self._list[i] for i in x]) for x in sorted(set((frozenset(y) for y in L)))]
def antichains(self, element_constructor=type([])):
'\n Return the antichains of the poset.\n\n An *antichain* of a poset is a set of elements of the\n poset that are pairwise incomparable.\n\n INPUT:\n\n - ``element_constructor`` -- a function taking an iterable as\n argument (default: ``list``)\n\n OUTPUT:\n\n The enumerated set (of type\n :class:`~sage.combinat.subsets_pairwise.PairwiseCompatibleSubsets`)\n of all antichains of the poset, each of which is given as an\n ``element_constructor.``\n\n EXAMPLES::\n\n sage: A = posets.PentagonPoset().antichains(); A\n Set of antichains of Finite lattice containing 5 elements\n sage: list(A)\n [[], [0], [1], [1, 2], [1, 3], [2], [3], [4]]\n sage: A.cardinality()\n 8\n sage: A[3]\n [1, 2]\n\n To get the antichains as, say, sets, one may use the\n ``element_constructor`` option::\n\n sage: list(posets.ChainPoset(3).antichains(element_constructor=set))\n [set(), {0}, {1}, {2}]\n\n To get the antichains of a given size one can currently use::\n\n sage: list(A.elements_of_depth_iterator(2))\n [[1, 2], [1, 3]]\n\n Eventually the following syntax will be accepted::\n\n sage: A.subset(size = 2) # todo: not implemented\n\n .. NOTE::\n\n Internally, this uses\n :class:`sage.combinat.subsets_pairwise.PairwiseCompatibleSubsets`\n and :class:`RecursivelyEnumeratedSet_forest`. At this point, iterating\n through this set is about twice slower than using\n :meth:`antichains_iterator` (tested on\n ``posets.AntichainPoset(15)``). The algorithm is the same\n (depth first search through the tree), but\n :meth:`antichains_iterator` manually inlines things which\n apparently avoids some infrastructure overhead.\n\n On the other hand, this returns a full featured enumerated\n set, with containment testing, etc.\n\n .. SEEALSO:: :meth:`maximal_antichains`, :meth:`chains`\n '
vertex_to_element = self._vertex_to_element
def f(antichain):
return element_constructor((vertex_to_element(x) for x in antichain))
result = self._hasse_diagram.antichains(element_class=f)
result.rename(('Set of antichains of %s' % self))
return result
def antichains_iterator(self):
'\n Return an iterator over the antichains of the poset.\n\n EXAMPLES::\n\n sage: it = posets.PentagonPoset().antichains_iterator(); it\n <generator object ...antichains_iterator at ...>\n sage: next(it), next(it)\n ([], [4])\n\n .. SEEALSO:: :meth:`antichains`\n '
vertex_to_element = self._vertex_to_element
for antichain in self._hasse_diagram.antichains_iterator():
(yield [vertex_to_element(_) for _ in antichain])
def width(self, certificate=False):
'\n Return the width of the poset (the size of its longest antichain).\n\n It is computed through a matching in a bipartite graph; see\n :wikipedia:`Dilworth%27s_theorem` for more information. The width is\n also called Dilworth number.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return ``(w, a)``, where `w` is the\n width of a poset and `a` is an antichain of maximum cardinality.\n If ``certificate=False`` return only width of the poset.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.width()\n 6\n\n sage: w, max_achain = P.width(certificate=True)\n sage: sorted(max_achain)\n [3, 5, 6, 9, 10, 12]\n\n TESTS::\n\n sage: Poset().width()\n 0\n sage: Poset().width(certificate=True)\n (0, [])\n '
if certificate:
max_achain = self.incomparability_graph().clique_maximum()
return (len(max_achain), max_achain)
from sage.graphs.graph import Graph
n = self.cardinality()
g = Graph()
for (v, u) in self._hasse_diagram.transitive_closure().edge_iterator(labels=False):
g.add_edge((u + n), v)
return (n - len(g.matching()))
def dilworth_decomposition(self):
"\n Return a partition of the points into the minimal number of chains.\n\n According to Dilworth's theorem, the points of a poset can be\n partitioned into `\\alpha` chains, where `\\alpha` is the cardinality of\n its largest antichain. This method returns such a partition.\n\n See :wikipedia:`Dilworth%27s_theorem`.\n\n ALGORITHM:\n\n We build a bipartite graph in which a vertex `v` of the poset is\n represented by two vertices `v^-,v^+`. For any two `u,v` such that\n `u<v` in the poset we add an edge `v^+u^-`.\n\n A matching in this graph is equivalent to a partition of the poset\n into chains: indeed, a chain `v_1...v_k` gives rise to the matching\n `v_1^+v_2^-,v_2^+v_3^-,...`, and from a matching one can build the\n union of chains.\n\n According to Dilworth's theorem, the number of chains is equal to\n `\\alpha` (the posets' width).\n\n EXAMPLES::\n\n sage: p = posets.BooleanLattice(4)\n sage: p.width()\n 6\n sage: p.dilworth_decomposition() # random\n [[7, 6, 4], [11, 3], [12, 8, 0], [13, 9, 1], [14, 10, 2], [15, 5]]\n\n\n .. SEEALSO::\n\n :meth:`level_sets` to return elements grouped to antichains.\n\n TESTS::\n\n sage: p = posets.IntegerCompositions(5)\n sage: d = p.dilworth_decomposition()\n sage: for chain in d:\n ....: for i in range(len(chain)-1):\n ....: assert p.is_greater_than(chain[i],chain[i+1])\n sage: set(p) == set().union(*d)\n True\n "
from sage.graphs.graph import Graph
n = self.cardinality()
g = Graph()
for (v, u) in self._hasse_diagram.transitive_closure().edge_iterator(labels=False):
g.add_edge((u + n), v)
matching = {}
for (u, v, _) in g.matching():
matching[u] = v
matching[v] = u
chains = []
for v in range(n):
if (v in matching):
continue
chain = []
while True:
chain.append(self._list[v])
v = matching.get((v + n), None)
if (v is None):
break
chains.append(chain)
return chains
def chains(self, element_constructor=type([]), exclude=None):
'\n Return the chains of the poset.\n\n A *chain* of a poset is an increasing sequence of\n distinct elements of the poset.\n\n INPUT:\n\n - ``element_constructor`` -- a function taking an iterable as\n argument (optional, default: ``list``)\n\n - ``exclude`` -- elements of the poset to be excluded\n (optional, default: ``None``)\n\n OUTPUT:\n\n The enumerated set (of type\n :class:`~sage.combinat.subsets_pairwise.PairwiseCompatibleSubsets`)\n of all chains of the poset, each of which is given as an\n ``element_constructor``.\n\n EXAMPLES::\n\n sage: C = posets.PentagonPoset().chains(); C\n Set of chains of Finite lattice containing 5 elements\n sage: list(C)\n [[], [0], [0, 1], [0, 1, 4], [0, 2], [0, 2, 3], [0, 2, 3, 4], [0, 2, 4],\n [0, 3], [0, 3, 4], [0, 4], [1], [1, 4], [2], [2, 3], [2, 3, 4], [2, 4],\n [3], [3, 4], [4]]\n\n Exclusion of elements, tuple (instead of list) as constructor::\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [4, 5]})\n sage: list(P.chains(element_constructor=tuple, exclude=[3]))\n [(), (1,), (1, 2), (1, 2, 4), (1, 4), (1, 5), (2,), (2, 4), (4,), (5,)]\n\n To get the chains of a given size one can currently use::\n\n sage: list(C.elements_of_depth_iterator(2))\n [[0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [2, 3], [2, 4], [3, 4]]\n\n Eventually the following syntax will be accepted::\n\n sage: C.subset(size = 2) # not implemented\n\n .. SEEALSO:: :meth:`maximal_chains`, :meth:`antichains`\n '
if (exclude is not None):
exclude = [self._element_to_vertex(x) for x in exclude]
result = self._hasse_diagram.chains(element_class=element_constructor, exclude=exclude, conversion=self._elements)
result.rename(('Set of chains of %s' % self))
return result
def connected_components(self):
'\n Return the connected components of the poset as subposets.\n\n EXAMPLES::\n\n sage: P = Poset({1: [2, 3], 3: [4, 5], 6: [7, 8]})\n sage: parts = sorted(P.connected_components(), key=len); parts\n [Finite poset containing 3 elements,\n Finite poset containing 5 elements]\n sage: parts[0].cover_relations()\n [[6, 7], [6, 8]]\n\n .. SEEALSO:: :meth:`disjoint_union`, :meth:`is_connected`\n\n TESTS::\n\n sage: Poset().connected_components() # Test empty poset\n []\n\n sage: P = Poset({1: [2, 3], 3: [4, 5]})\n sage: CC = P.connected_components()\n sage: CC[0] is P\n True\n\n sage: P = Poset({1: [2, 3], 3: [4, 5], 6: [7, 8]}, facade=False)\n sage: V = sorted(P.connected_components(), key=len)[0]\n sage: V(7) < V(8) # Facade argument should be inherited\n False\n '
comps = self._hasse_diagram.connected_components_subgraphs()
if (len(comps) == 1):
return [self]
result = []
if self._is_facade:
for part in comps:
G = part.relabel(self._vertex_to_element, inplace=False)
result.append(Poset(G, cover_relations=True, facade=True))
else:
for part in comps:
G = part.relabel((lambda v: self._vertex_to_element(v).element), inplace=False)
result.append(Poset(G, cover_relations=True, facade=False))
return result
def ordinal_summands(self):
"\n Return the ordinal summands of the poset as subposets.\n\n The ordinal summands of a poset `P` is the longest list of\n non-empty subposets `P_1, \\ldots, P_n` whose ordinal sum is `P`. This\n decomposition is unique.\n\n EXAMPLES::\n\n sage: P = Poset({'a': ['c', 'd'], 'b': ['d'], 'c': ['x', 'y'],\n ....: 'd': ['x', 'y']})\n sage: parts = P.ordinal_summands(); parts\n [Finite poset containing 4 elements, Finite poset containing 2 elements]\n sage: sorted(parts[0])\n ['a', 'b', 'c', 'd']\n sage: Q = parts[0].ordinal_sum(parts[1])\n sage: Q.is_isomorphic(P)\n True\n\n .. SEEALSO::\n\n :meth:`ordinal_sum`\n\n ALGORITHM:\n\n Suppose that a poset `P` is the ordinal sum of posets `L` and `U`. Then\n `P` contains maximal antichains `l` and `u` such that every element of\n `u` covers every element of `l`; they correspond to maximal elements of\n `L` and minimal elements of `U`.\n\n We consider a linear extension `x_1,\\ldots,x_n` of the poset's\n elements.\n\n We keep track of the maximal elements of subposet induced by elements\n `0,\\ldots,x_i` and minimal elements of subposet induced by elements\n `x_{i+1},\\ldots,x_n`, incrementing `i` one by one. We then check if\n `l` and `u` fit the previous description.\n\n TESTS::\n\n sage: Poset().ordinal_summands()\n [Finite poset containing 0 elements]\n sage: Poset({1: []}).ordinal_summands()\n [Finite poset containing 1 elements]\n "
n = self.cardinality()
if (n <= 0):
return [self]
H = self._hasse_diagram
cut_points = [(- 1)]
in_degrees = H.in_degree()
lower = set()
upper = set(H.sources())
for e in range(n):
lower.add(e)
lower.difference_update(H.neighbors_in(e))
upper.discard(e)
up_covers = H.neighbors_out(e)
for uc in up_covers:
in_degrees[uc] -= 1
if (in_degrees[uc] == 0):
upper.add(uc)
if ((e + 1) in up_covers):
uc_len = len(upper)
for l in lower:
if (H.out_degree(l) != uc_len):
break
else:
for l in lower:
if (set(H.neighbors_out(l)) != upper):
break
else:
cut_points.append(e)
cut_points.append((n - 1))
parts = []
for (i, j) in zip(cut_points, cut_points[1:]):
G = self._hasse_diagram.subgraph(range((i + 1), (j + 1)))
parts.append(Poset(G.relabel(self._vertex_to_element, inplace=False)))
return parts
def product(self, other):
"\n Return the Cartesian product of the poset with ``other``.\n\n The Cartesian (or 'direct') product of `P` and\n `Q` is defined by `(p, q) \\le (p', q')` iff `p \\le p'`\n in `P` and `q \\le q'` in `Q`.\n\n Product of (semi)lattices are returned as a (semi)lattice.\n\n EXAMPLES::\n\n sage: P = posets.ChainPoset(3)\n sage: Q = posets.ChainPoset(4)\n sage: PQ = P.product(Q) ; PQ\n Finite lattice containing 12 elements\n sage: len(PQ.cover_relations())\n 17\n sage: Q.product(P).is_isomorphic(PQ)\n True\n\n sage: P = posets.BooleanLattice(2)\n sage: Q = P.product(P)\n sage: Q.is_isomorphic(posets.BooleanLattice(4))\n True\n\n One can also simply use `*`::\n\n sage: P = posets.ChainPoset(2)\n sage: Q = posets.ChainPoset(3)\n sage: P*Q\n Finite lattice containing 6 elements\n\n .. SEEALSO::\n\n :class:`~sage.combinat.posets.cartesian_product.CartesianProductPoset`, :meth:`factor`\n\n TESTS::\n\n sage: Poset({0: [1]}).product(Poset()) # Product with empty poset\n Finite poset containing 0 elements\n sage: Poset().product(Poset()) # Product of two empty poset\n Finite poset containing 0 elements\n\n We check that :trac:`19113` is fixed::\n\n sage: L = LatticePoset({1: []})\n sage: type(L) == type(L.product(L))\n True\n "
from sage.combinat.posets.lattices import LatticePoset, JoinSemilattice, MeetSemilattice, FiniteLatticePoset, FiniteMeetSemilattice, FiniteJoinSemilattice
if (isinstance(self, FiniteLatticePoset) and isinstance(other, FiniteLatticePoset)):
constructor = LatticePoset
elif (isinstance(self, FiniteMeetSemilattice) and isinstance(other, FiniteMeetSemilattice)):
constructor = MeetSemilattice
elif (isinstance(self, FiniteJoinSemilattice) and isinstance(other, FiniteJoinSemilattice)):
constructor = JoinSemilattice
else:
constructor = Poset
return constructor(self.hasse_diagram().cartesian_product(other.hasse_diagram()))
_mul_ = product
def rees_product(self, other):
"\n Return the Rees product of ``self`` and ``other``.\n\n This is only defined if both posets are graded.\n\n The underlying set is the set of pairs `(p,q)` in the Cartesian\n product such that `\\operatorname{rk}(p) \\geq \\operatorname{rk}(q)`.\n\n This operation was defined by Björner and Welker in [BjWe2005]_.\n Other references are [MBRe2011]_ and [LSW2012]_.\n\n EXAMPLES::\n\n sage: B3 = posets.BooleanLattice(3)\n sage: B3t = B3.subposet(list(range(1,8)))\n sage: C3 = posets.ChainPoset(3)\n sage: D = B3t.rees_product(C3); D\n Finite poset containing 12 elements\n sage: sorted(D.minimal_elements())\n [(1, 0), (2, 0), (4, 0)]\n sage: sorted(D.maximal_elements())\n [(7, 0), (7, 1), (7, 2)]\n sage: D.with_bounds().moebius_function('bottom','top')\n 2\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`ordinal_product`, :meth:`star_product`\n\n TESTS::\n\n sage: T = posets.TamariLattice(3)\n sage: T.rees_product(T)\n Traceback (most recent call last):\n ...\n TypeError: the Rees product is defined only for graded posets\n "
if (not (self.is_graded() and other.is_graded())):
raise TypeError('the Rees product is defined only for graded posets')
rk0 = self.rank_function()
rk1 = other.rank_function()
rees_set = [(p, q) for p in self for q in other if (rk0(p) >= rk1(q))]
def covers(pq, ppqq):
(p, q) = pq
(pp, qq) = ppqq
return (self.covers(p, pp) and ((q == qq) or other.covers(q, qq)))
return Poset((rees_set, covers), cover_relations=True)
def factor(self):
'\n Factor the poset as a Cartesian product of smaller posets.\n\n This only works for connected posets for the moment.\n\n The decomposition of a connected poset as a Cartesian product\n of posets (prime in the sense that they cannot be written as\n Cartesian products) is unique up to reordering and\n isomorphism.\n\n OUTPUT:\n\n a list of posets\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: Q = P*P\n sage: Q.factor()\n [Finite poset containing 5 elements,\n Finite poset containing 5 elements]\n\n sage: P1 = posets.ChainPoset(3)\n sage: P2 = posets.ChainPoset(7)\n sage: P1.factor()\n [Finite lattice containing 3 elements]\n sage: (P1 * P2).factor()\n [Finite poset containing 7 elements,\n Finite poset containing 3 elements]\n\n sage: P = posets.TamariLattice(4)\n sage: (P*P).factor()\n [Finite poset containing 14 elements,\n Finite poset containing 14 elements]\n\n .. SEEALSO:: :meth:`product`\n\n TESTS::\n\n sage: P = posets.AntichainPoset(4)\n sage: P.factor()\n Traceback (most recent call last):\n ...\n NotImplementedError: the poset is not connected\n\n sage: P = posets.Crown(2)\n sage: P.factor()\n [Finite poset containing 4 elements]\n\n sage: Poset().factor()\n [Finite poset containing 0 elements]\n\n sage: factor(posets.BooleanLattice(2))\n [Finite poset containing 2 elements,\n Finite poset containing 2 elements]\n\n REFERENCES:\n\n .. [Feig1986] Joan Feigenbaum, *Directed Cartesian-Product Graphs\n have Unique Factorizations that can be computed in Polynomial Time*,\n Discrete Applied Mathematics 15 (1986) 105-110\n :doi:`10.1016/0166-218X(86)90023-5`\n '
from sage.graphs.graph import Graph
from sage.misc.flatten import flatten
dg = self._hasse_diagram
if (not dg.is_connected()):
raise NotImplementedError('the poset is not connected')
if ZZ(dg.num_verts()).is_prime():
return [self]
G = dg.to_undirected()
(is_product, dic) = G.is_cartesian_product(relabeling=True)
if (not is_product):
return [self]
dic = {key: tuple(flatten(dic[key])) for key in dic}
prod_dg = dg.relabel(dic, inplace=False)
v0 = next(iter(dic.values()))
n = len(v0)
factors_range = list(range(n))
fusion = Graph(n)
def edge_color(va, vb):
for i in range(n):
if (va[i] != vb[i]):
return i
for (i0, i1) in Subsets(factors_range, 2):
for x in prod_dg:
neigh0 = [y for y in prod_dg.neighbor_iterator(x) if (edge_color(x, y) == i0)]
neigh1 = [z for z in prod_dg.neighbor_iterator(x) if (edge_color(x, z) == i1)]
for (x0, x1) in product(neigh0, neigh1):
x2 = list(x0)
x2[i1] = x1[i1]
x2 = tuple(x2)
A0 = prod_dg.has_edge(x, x0)
B0 = prod_dg.has_edge(x1, x2)
if (A0 != B0):
fusion.add_edge([i0, i1])
break
A1 = prod_dg.has_edge(x, x1)
B1 = prod_dg.has_edge(x0, x2)
if (A1 != B1):
fusion.add_edge([i0, i1])
break
fusion = fusion.transitive_closure()
resu = []
for s in fusion.connected_components(sort=False):
subg = [x for x in prod_dg if all(((x[i] == v0[i]) for i in factors_range if (i not in s)))]
resu.append(Poset(prod_dg.subgraph(subg)))
return resu
def disjoint_union(self, other, labels='pairs'):
"\n Return a poset isomorphic to disjoint union (also called direct\n sum) of the poset with ``other``.\n\n The disjoint union of `P` and `Q` is a poset that contains\n every element and relation from both `P` and `Q`, and where\n every element of `P` is incomparable to every element of `Q`.\n\n Mathematically, it is only defined when `P` and `Q` have no\n common element; here we force that by giving them different\n names in the resulting poset.\n\n INPUT:\n\n - ``other``, a poset.\n\n - ``labels`` - (defaults to 'pairs') If set to 'pairs', each\n element ``v`` in this poset will be named ``(0,v)`` and each\n element ``u`` in ``other`` will be named ``(1,u)`` in the\n result. If set to 'integers', the elements of the result\n will be relabeled with consecutive integers.\n\n EXAMPLES::\n\n sage: P1 = Poset({'a': 'b'})\n sage: P2 = Poset({'c': 'd'})\n sage: P = P1.disjoint_union(P2); P\n Finite poset containing 4 elements\n sage: sorted(P.cover_relations())\n [[(0, 'a'), (0, 'b')], [(1, 'c'), (1, 'd')]]\n sage: P = P1.disjoint_union(P2, labels='integers')\n sage: P.cover_relations()\n [[2, 3], [0, 1]]\n\n sage: N5 = posets.PentagonPoset(); N5\n Finite lattice containing 5 elements\n sage: N5.disjoint_union(N5) # Union of lattices is not a lattice\n Finite poset containing 10 elements\n\n We show how to get literally direct sum with elements untouched::\n\n sage: P = P1.disjoint_union(P2).relabel(lambda x: x[1])\n sage: sorted(P.cover_relations())\n [['a', 'b'], ['c', 'd']]\n\n .. SEEALSO:: :meth:`connected_components`\n\n TESTS::\n\n sage: N5 = posets.PentagonPoset()\n sage: P0 = Poset()\n sage: N5.disjoint_union(P0).is_isomorphic(N5)\n True\n sage: P0.disjoint_union(P0)\n Finite poset containing 0 elements\n\n sage: A3 = posets.AntichainPoset(3)\n sage: A4 = posets.AntichainPoset(4)\n sage: A7 = posets.AntichainPoset(7)\n sage: A3.disjoint_union(A4).is_isomorphic(A7)\n True\n "
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
return Poset(self.hasse_diagram().disjoint_union(other.hasse_diagram(), labels=labels))
def ordinal_product(self, other, labels='pairs'):
"\n Return the ordinal product of ``self`` and ``other``.\n\n The ordinal product of two posets `P` and `Q` is a partial\n order on the Cartesian product of the underlying sets of `P`\n and `Q`, defined as follows (see [EnumComb1]_, p. 284).\n\n In the ordinal product, `(p,q) \\leq (p',q')` if either `p \\leq\n p'` or `p = p'` and `q \\leq q'`.\n\n This construction is not symmetric in `P` and `Q`. Informally\n said we put a copy of `Q` in place of every element of `P`.\n\n INPUT:\n\n - ``other`` -- a poset\n\n - ``labels`` -- either ``'integers'`` or ``'pairs'`` (default); how\n the resulting poset will be labeled\n\n EXAMPLES::\n\n sage: P1 = Poset((['a', 'b'], [['a', 'b']]))\n sage: P2 = Poset((['c', 'd'], [['c', 'd']]))\n sage: P = P1.ordinal_product(P2); P\n Finite poset containing 4 elements\n sage: sorted(P.cover_relations())\n [[('a', 'c'), ('a', 'd')], [('a', 'd'), ('b', 'c')],\n [('b', 'c'), ('b', 'd')]]\n\n .. SEEALSO::\n\n :meth:`product`, :meth:`ordinal_sum`\n\n TESTS::\n\n sage: P1.ordinal_product(24)\n Traceback (most recent call last):\n ...\n TypeError: 'other' is not a finite poset\n sage: P1.ordinal_product(P2, labels='camembert')\n Traceback (most recent call last):\n ...\n ValueError: labels must be either 'pairs' or 'integers'\n\n sage: N5 = posets.PentagonPoset()\n sage: P0 = Poset()\n sage: N5.ordinal_product(P0) == P0\n True\n sage: P0.ordinal_product(N5) == P0\n True\n sage: P0.ordinal_product(P0) == P0\n True\n\n sage: A3 = posets.AntichainPoset(3)\n sage: A4 = posets.AntichainPoset(4)\n sage: A12 = posets.AntichainPoset(12)\n sage: A3.ordinal_product(A4).is_isomorphic(A12)\n True\n\n sage: C3 = posets.ChainPoset(3)\n sage: C4 = posets.ChainPoset(4)\n sage: C12 = posets.ChainPoset(12)\n sage: C3.ordinal_product(C4).is_isomorphic(C12)\n True\n "
from sage.combinat.posets.lattices import LatticePoset, FiniteLatticePoset
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
othermax = other.maximal_elements()
othermin = other.minimal_elements()
dg = DiGraph()
dg.add_vertices([(s, t) for s in self for t in other])
dg.add_edges([((s, t), (s2, t2)) for (s, s2) in self.cover_relations_iterator() for t in othermax for t2 in othermin])
dg.add_edges([((s, t), (s, t2)) for s in self for (t, t2) in other.cover_relations_iterator()])
if (labels == 'integers'):
dg.relabel()
elif (labels != 'pairs'):
raise ValueError("labels must be either 'pairs' or 'integers'")
if (isinstance(self, FiniteLatticePoset) and isinstance(other, FiniteLatticePoset)):
return LatticePoset(dg)
return Poset(dg)
def ordinal_sum(self, other, labels='pairs'):
"\n Return a poset or (semi)lattice isomorphic to ordinal sum of the\n poset with ``other``.\n\n The ordinal sum of `P` and `Q` is a poset that contains every\n element and relation from both `P` and `Q`, and where every\n element of `P` is smaller than any element of `Q`.\n\n Mathematically, it is only defined when `P` and `Q` have no\n common element; here we force that by giving them different\n names in the resulting poset.\n\n The ordinal sum on lattices is a lattice; resp. for meet- and\n join-semilattices.\n\n INPUT:\n\n - ``other``, a poset.\n\n - ``labels`` - (defaults to 'pairs') If set to 'pairs', each\n element ``v`` in this poset will be named ``(0,v)`` and each\n element ``u`` in ``other`` will be named ``(1,u)`` in the\n result. If set to 'integers', the elements of the result\n will be relabeled with consecutive integers.\n\n EXAMPLES::\n\n sage: P1 = Poset( ([1, 2, 3, 4], [[1, 2], [1, 3], [1, 4]]) )\n sage: P2 = Poset( ([1, 2, 3,], [[2,1], [3,1]]) )\n sage: P3 = P1.ordinal_sum(P2); P3\n Finite poset containing 7 elements\n sage: len(P1.maximal_elements())*len(P2.minimal_elements())\n 6\n sage: len(P1.cover_relations()+P2.cover_relations())\n 5\n sage: len(P3.cover_relations()) # Every element of P2 is greater than elements of P1.\n 11\n sage: P3.list() # random\n [(0, 1), (0, 2), (0, 4), (0, 3), (1, 2), (1, 3), (1, 1)]\n sage: P4 = P1.ordinal_sum(P2, labels='integers')\n sage: P4.list() # random\n [0, 1, 2, 3, 5, 6, 4]\n\n Return type depends on input types::\n\n sage: P = Poset({1:[2]}); P\n Finite poset containing 2 elements\n sage: JL = JoinSemilattice({1:[2]}); JL\n Finite join-semilattice containing 2 elements\n sage: L = LatticePoset({1:[2]}); L\n Finite lattice containing 2 elements\n sage: P.ordinal_sum(L)\n Finite poset containing 4 elements\n sage: L.ordinal_sum(JL)\n Finite join-semilattice containing 4 elements\n sage: L.ordinal_sum(L)\n Finite lattice containing 4 elements\n\n .. SEEALSO::\n\n :meth:`ordinal_summands`, :meth:`disjoint_union`,\n :meth:`sage.combinat.posets.lattices.FiniteLatticePoset.vertical_composition`\n\n TESTS::\n\n sage: N5 = posets.PentagonPoset()\n sage: P0 = LatticePoset({})\n sage: N5.ordinal_sum(P0).is_isomorphic(N5)\n True\n sage: P0.ordinal_sum(P0)\n Finite lattice containing 0 elements\n "
from sage.combinat.posets.lattices import LatticePoset, JoinSemilattice, MeetSemilattice, FiniteLatticePoset, FiniteMeetSemilattice, FiniteJoinSemilattice
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
G = self.hasse_diagram().disjoint_union(other.hasse_diagram())
selfmax = self.maximal_elements()
othermin = other.minimal_elements()
for u in selfmax:
for v in othermin:
G.add_edge((0, u), (1, v))
if (labels == 'integers'):
G.relabel()
elif (labels != 'pairs'):
raise ValueError("labels must be either 'pairs' or 'integers'")
if (isinstance(self, FiniteLatticePoset) and isinstance(other, FiniteLatticePoset)):
return LatticePoset(G)
if (isinstance(self, FiniteMeetSemilattice) and isinstance(other, FiniteMeetSemilattice)):
return MeetSemilattice(G)
if (isinstance(self, FiniteJoinSemilattice) and isinstance(other, FiniteJoinSemilattice)):
return JoinSemilattice(G)
return Poset(G)
def star_product(self, other, labels='pairs'):
"\n Return a poset isomorphic to the star product of the\n poset with ``other``.\n\n Both this poset and ``other`` are expected to be bounded\n and have at least two elements.\n\n Let `P` be a poset with top element `\\top_P` and `Q` be a poset\n with bottom element `\\bot_Q`. The star product of\n `P` and `Q` is the ordinal sum of `P \\setminus \\top_P` and\n `Q \\setminus \\bot_Q`.\n\n Mathematically, it is only defined when `P` and `Q` have no\n common elements; here we force that by giving them different\n names in the resulting poset.\n\n INPUT:\n\n - ``other`` -- a poset.\n\n - ``labels`` -- (defaults to 'pairs') If set to 'pairs', each\n element ``v`` in this poset will be named ``(0, v)`` and each\n element ``u`` in ``other`` will be named ``(1, u)`` in the\n result. If set to 'integers', the elements of the result\n will be relabeled with consecutive integers.\n\n EXAMPLES:\n\n This is mostly used to combine two Eulerian posets to third one,\n and makes sense for graded posets only::\n\n sage: B2 = posets.BooleanLattice(2)\n sage: B3 = posets.BooleanLattice(3)\n sage: P = B2.star_product(B3); P\n Finite poset containing 10 elements\n sage: P.is_eulerian() # needs sage.libs.flint\n True\n\n We can get elements as pairs or as integers::\n\n sage: ABC = Poset({'a': ['b'], 'b': ['c']})\n sage: XYZ = Poset({'x': ['y'], 'y': ['z']})\n sage: ABC.star_product(XYZ).list()\n [(0, 'a'), (0, 'b'), (1, 'y'), (1, 'z')]\n sage: sorted(ABC.star_product(XYZ, labels='integers'))\n [0, 1, 2, 3]\n\n TESTS::\n\n sage: C0 = Poset()\n sage: C1 = Poset({0: []})\n sage: C2 = Poset({0: [1]})\n sage: C2.star_product(42)\n Traceback (most recent call last):\n ...\n TypeError: 'other' is not a finite poset\n sage: C2.star_product(C0)\n Traceback (most recent call last):\n ...\n ValueError: 'other' is not bounded\n sage: C0.star_product(C2)\n Traceback (most recent call last):\n ...\n ValueError: the poset is not bounded\n sage: C2.star_product(C1)\n Traceback (most recent call last):\n ...\n ValueError: 'other' has less than two elements\n sage: C1.star_product(C2)\n Traceback (most recent call last):\n ...\n ValueError: the poset has less than two elements\n "
if (not hasattr(other, 'hasse_diagram')):
raise TypeError("'other' is not a finite poset")
if (not self.is_bounded()):
raise ValueError('the poset is not bounded')
if (not other.is_bounded()):
raise ValueError("'other' is not bounded")
if (self.cardinality() < 2):
raise ValueError('the poset has less than two elements')
if (other.cardinality() < 2):
raise ValueError("'other' has less than two elements")
if (labels not in ['pairs', 'integers']):
raise ValueError("labels must be either 'pairs' or 'integers'")
G = self.hasse_diagram().disjoint_union(other.hasse_diagram())
selfmax = self.lower_covers(self.top())
othermin = other.upper_covers(other.bottom())
G.delete_vertex((0, self.top()))
G.delete_vertex((1, other.bottom()))
for u in selfmax:
for v in othermin:
G.add_edge((0, u), (1, v))
if (labels == 'integers'):
G.relabel()
return Poset(G)
def lexicographic_sum(self, P):
'\n Return the lexicographic sum using this poset as index.\n\n In the lexicographic sum of posets `P_t` by index poset `T`\n we have `x \\le y` if either `x \\le y` in `P_t`\n for some `t \\in T`, or `x \\in P_i`, `y \\in P_j` and\n `i \\le j` in `T`.\n\n Informally said we substitute every element of `T` by corresponding\n poset `P_t`.\n\n Mathematically, it is only defined when all `P_t` have no\n common element; here we force that by giving them different\n names in the resulting poset.\n\n :meth:`disjoint_union` and :meth:`ordinal_sum` are special cases\n of lexicographic sum where the index poset is an (anti)chain.\n :meth:`ordinal_product` is a special case where every `P_t` is same\n poset.\n\n INPUT:\n\n - ``P`` -- dictionary whose keys are elements of this poset, values are posets\n\n EXAMPLES::\n\n sage: N = Poset({1: [3, 4], 2: [4]})\n sage: P = {1: posets.PentagonPoset(), 2: N,\n ....: 3: posets.ChainPoset(3), 4: posets.AntichainPoset(4)}\n sage: NP = N.lexicographic_sum(P); NP\n Finite poset containing 16 elements\n sage: sorted(NP.minimal_elements())\n [(1, 0), (2, 1), (2, 2)]\n\n TESTS::\n\n sage: from collections import defaultdict\n sage: P = defaultdict(lambda: Poset({3: [4]}))\n sage: P[1] = Poset({5: [6]})\n sage: T = Poset({1: [2]})\n sage: T.lexicographic_sum(P)\n Finite poset containing 4 elements\n\n sage: P[1] = Poset()\n sage: T.lexicographic_sum(P)\n Traceback (most recent call last):\n ...\n ValueError: lexicographic sum of the empty poset is not defined\n\n sage: P = {1: T, 2: T, 3: T}\n sage: T.lexicographic_sum(P)\n Traceback (most recent call last):\n ...\n ValueError: keys of dict P does not match to elements of the poset\n sage: P = {1: T}\n sage: T.lexicographic_sum(P)\n Traceback (most recent call last):\n ...\n ValueError: keys of dict P does not match to elements of the poset\n\n sage: P = {1: Poset({1: []}, facade=True), 2: Poset({1: []}, facade=False)}\n sage: T.lexicographic_sum(P)\n Traceback (most recent call last):\n ...\n TypeError: mixing facade and non-facade posets is not defined\n\n sage: T = Poset({42: []}, facade=False)\n sage: P = {T[0]: Poset({57: []}, facade=False)}\n sage: T.lexicographic_sum(P)._is_facade\n False\n sage: T = Poset({42: []}, facade=True)\n sage: P = {T[0]: Poset({57: []}, facade=True)}\n sage: T.lexicographic_sum(P)._is_facade\n True\n '
if (isinstance(P, dict) and (not isinstance(P, defaultdict))):
if (set(P) != set(self)):
raise ValueError('keys of dict P does not match to elements of the poset')
d = DiGraph()
for t in self:
if (P[t]._is_facade != self._is_facade):
raise TypeError('mixing facade and non-facade posets is not defined')
if (P[t].cardinality() == 0):
raise ValueError('lexicographic sum of the empty poset is not defined')
part = P[t].hasse_diagram()
part.relabel((lambda x: (t, x)), inplace=True)
d = d.union(part)
for (a, b) in self.cover_relations_iterator():
for l in P[a].maximal_elements():
for u in P[b].minimal_elements():
d.add_edge((a, l), (b, u))
return Poset(d, facade=self._is_facade)
def dual(self):
'\n Return the dual poset of the given poset.\n\n In the dual of a poset `P` we have `x \\le y` iff `y \\le x` in `P`.\n\n EXAMPLES::\n\n sage: P = Poset({1: [2, 3], 3: [4]})\n sage: P.cover_relations()\n [[1, 2], [1, 3], [3, 4]]\n sage: Q = P.dual()\n sage: Q.cover_relations()\n [[4, 3], [3, 1], [2, 1]]\n\n Dual of a lattice is a lattice; dual of a meet-semilattice is\n join-semilattice and vice versa. Also the dual of a (non-)facade poset\n is again (non-)facade::\n\n sage: V = MeetSemilattice({1: [2, 3]}, facade=False)\n sage: A = V.dual(); A\n Finite join-semilattice containing 3 elements\n sage: A(2) < A(1)\n True\n\n .. SEEALSO:: :meth:`~sage.categories.finite_posets.FinitePosets.ParentMethods.is_self_dual`\n\n TESTS::\n\n sage: Poset().dual() == Poset() # Test the empty poset\n True\n '
if self._with_linear_extension:
elements = reversed(self._elements)
else:
elements = None
H = self._hasse_diagram.relabel({i: x for (i, x) in enumerate(self._elements)}, inplace=False)
return self._dual_class(H.reverse(), elements=elements, category=self.category(), facade=self._is_facade)
def with_bounds(self, labels=('bottom', 'top')):
"\n Return the poset with bottom and top elements adjoined.\n\n This function adds top and bottom elements to the poset.\n It will always add elements, it does not check if the poset\n already has a bottom or a top element.\n\n For lattices and semilattices this function returns a lattice.\n\n INPUT:\n\n - ``labels`` -- A pair of elements to use as a bottom and top\n element of the poset. Default is strings ``'bottom'`` and\n ``'top'``. Either of them can be ``None``, and then a new\n bottom or top element will not be added.\n\n EXAMPLES::\n\n sage: V = Poset({0: [1, 2]})\n sage: trafficsign = V.with_bounds(); trafficsign\n Finite poset containing 5 elements\n sage: trafficsign.list()\n ['bottom', 0, 1, 2, 'top']\n sage: trafficsign = V.with_bounds(labels=(-1, -2))\n sage: trafficsign.cover_relations()\n [[-1, 0], [0, 1], [0, 2], [1, -2], [2, -2]]\n\n sage: Y = V.with_bounds(labels=(-1, None))\n sage: Y.cover_relations()\n [[-1, 0], [0, 1], [0, 2]]\n\n sage: P = posets.PentagonPoset() # A lattice\n sage: P.with_bounds()\n Finite lattice containing 7 elements\n\n sage: P = posets.PentagonPoset(facade=False)\n sage: P.with_bounds()\n Finite lattice containing 7 elements\n\n .. SEEALSO::\n\n :meth:`without_bounds` for the reverse operation\n\n TESTS::\n\n sage: P = Poset().with_bounds()\n sage: P.cover_relations()\n [['bottom', 'top']]\n\n sage: L = LatticePoset({}).with_bounds(); L\n Finite lattice containing 2 elements\n sage: L.meet_irreducibles() # Issue 21543\n ['bottom']\n\n sage: Poset().with_bounds((None, 1))\n Finite poset containing 1 elements\n sage: LatticePoset().with_bounds((None, 1))\n Finite lattice containing 1 elements\n sage: MeetSemilattice().with_bounds((None, 1))\n Finite lattice containing 1 elements\n sage: JoinSemilattice().with_bounds((None, 1))\n Finite join-semilattice containing 1 elements\n sage: Poset().with_bounds((1, None))\n Finite poset containing 1 elements\n sage: LatticePoset().with_bounds((1, None))\n Finite lattice containing 1 elements\n sage: MeetSemilattice().with_bounds((1, None))\n Finite meet-semilattice containing 1 elements\n sage: JoinSemilattice().with_bounds((1, None))\n Finite lattice containing 1 elements\n\n sage: P = Poset({0: []})\n sage: L = LatticePoset({0: []})\n sage: ML = MeetSemilattice({0: []})\n sage: JL = JoinSemilattice({0: []})\n sage: P.with_bounds((None, None))\n Finite poset containing 1 elements\n sage: L.with_bounds((None, None))\n Finite lattice containing 1 elements\n sage: ML.with_bounds((None, None))\n Finite meet-semilattice containing 1 elements\n sage: JL.with_bounds((None, None))\n Finite join-semilattice containing 1 elements\n sage: P.with_bounds((1, None))\n Finite poset containing 2 elements\n sage: L.with_bounds((1, None))\n Finite lattice containing 2 elements\n sage: ML.with_bounds((1, None))\n Finite meet-semilattice containing 2 elements\n sage: JL.with_bounds((1, None))\n Finite lattice containing 2 elements\n sage: P.with_bounds((None, 1))\n Finite poset containing 2 elements\n sage: L.with_bounds((None, 1))\n Finite lattice containing 2 elements\n sage: ML.with_bounds((None, 1))\n Finite lattice containing 2 elements\n sage: JL.with_bounds((None, 1))\n Finite join-semilattice containing 2 elements\n\n sage: posets.PentagonPoset().with_bounds(labels=(4, 5))\n Traceback (most recent call last):\n ...\n ValueError: the poset already has element 4\n "
if (len(labels) != 2):
raise TypeError('labels must be a pair')
(new_min, new_max) = labels
if (new_min in self):
raise ValueError(('the poset already has element %s' % new_min))
if (new_max in self):
raise ValueError(('the poset already has element %s' % new_max))
from sage.combinat.posets.lattices import LatticePoset, JoinSemilattice, MeetSemilattice, FiniteLatticePoset, FiniteMeetSemilattice, FiniteJoinSemilattice
if (isinstance(self, FiniteLatticePoset) or (isinstance(self, FiniteMeetSemilattice) and (new_max is not None)) or (isinstance(self, FiniteJoinSemilattice) and (new_min is not None))):
constructor = LatticePoset
elif isinstance(self, FiniteMeetSemilattice):
constructor = MeetSemilattice
elif isinstance(self, FiniteJoinSemilattice):
constructor = JoinSemilattice
else:
constructor = Poset
if (self.cardinality() == 0):
if ((new_min is None) and (new_max is None)):
return constructor(facade=self._is_facade)
if (new_min is None):
return constructor({new_min: []}, facade=self._is_facade)
if (new_max is None):
return constructor({new_max: []}, facade=self._is_facade)
return constructor({new_min: [new_max]}, facade=self._is_facade)
if self._is_facade:
D = self.hasse_diagram()
else:
D = Poset(self, facade=True).hasse_diagram()
if (new_min is not None):
D.add_edges([(new_min, e) for e in D.sources()])
if (new_max is not None):
D.add_edges([(e, new_max) for e in D.sinks()])
return constructor(D, facade=self._is_facade)
def without_bounds(self):
'\n Return the poset without its top and bottom elements.\n\n This is useful as an input for the method :meth:`order_complex`.\n\n If there is either no top or no bottom element, this\n raises a :class:`TypeError`.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: Q = P.without_bounds(); Q\n Finite poset containing 3 elements\n sage: Q.cover_relations()\n [[2, 3]]\n\n sage: P = posets.DiamondPoset(5)\n sage: Q = P.without_bounds(); Q\n Finite poset containing 3 elements\n sage: Q.cover_relations()\n []\n\n .. SEEALSO::\n\n :meth:`with_bounds` for the reverse operation\n\n TESTS::\n\n sage: P = Poset({1:[2],3:[2,4]})\n sage: P.without_bounds()\n Traceback (most recent call last):\n ...\n TypeError: the poset is missing either top or bottom\n\n sage: P = Poset({1:[]})\n sage: P.without_bounds()\n Finite poset containing 0 elements\n\n sage: P = Poset({})\n sage: P.without_bounds()\n Traceback (most recent call last):\n ...\n TypeError: the poset is missing either top or bottom\n '
if self.is_bounded():
g = copy(self._hasse_diagram)
g.delete_vertices([0, (g.order() - 1)])
g.relabel(self._vertex_to_element)
return Poset(g, facade=self._is_facade)
raise TypeError('the poset is missing either top or bottom')
def relabel(self, relabeling=None):
'\n Return a copy of this poset with its elements relabeled.\n\n INPUT:\n\n - ``relabeling`` -- a function, dictionary, list or tuple\n\n The given function or dictionary must map each (non-wrapped)\n element of ``self`` to some distinct object. The given list or tuple\n must be made of distinct objects.\n\n When the input is a list or a tuple, the relabeling uses\n the total ordering of the elements of the poset given by\n ``list(self)``.\n\n If no relabeling is given, the poset is relabeled by integers\n from `0` to `n-1` according to one of its linear extensions. This means\n that `i<j` as integers whenever `i<j` in the relabeled poset.\n\n EXAMPLES:\n\n Relabeling using a function::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: P.cover_relations()\n [[1, 2], [1, 3], [2, 4], [2, 6], [3, 6], [4, 12], [6, 12]]\n sage: Q = P.relabel(lambda x: x+1)\n sage: Q.list()\n [2, 3, 4, 5, 7, 13]\n sage: Q.cover_relations()\n [[2, 3], [2, 4], [3, 5], [3, 7], [4, 7], [5, 13], [7, 13]]\n\n Relabeling using a dictionary::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True, facade=False)\n sage: relabeling = {c.element:i for (i,c) in enumerate(P)}\n sage: relabeling\n {1: 0, 2: 1, 3: 2, 4: 3, 6: 4, 12: 5}\n sage: Q = P.relabel(relabeling)\n sage: Q.list()\n [0, 1, 2, 3, 4, 5]\n sage: Q.cover_relations()\n [[0, 1], [0, 2], [1, 3], [1, 4], [2, 4], [3, 5], [4, 5]]\n\n Mind the ``c.element``; this is because the relabeling is\n applied to the elements of the poset without the wrapping.\n Thanks to this convention, the same relabeling function can\n be used both for facade or non facade posets.\n\n Relabeling using a list::\n\n sage: P = posets.PentagonPoset()\n sage: list(P)\n [0, 1, 2, 3, 4]\n sage: P.cover_relations()\n [[0, 1], [0, 2], [1, 4], [2, 3], [3, 4]]\n sage: Q = P.relabel(list(\'abcde\'))\n sage: Q.cover_relations()\n [[\'a\', \'b\'], [\'a\', \'c\'], [\'b\', \'e\'], [\'c\', \'d\'], [\'d\', \'e\']]\n\n Default behaviour is increasing relabeling::\n\n sage: a2 = posets.ChainPoset(2)\n sage: P = a2 * a2\n sage: Q = P.relabel()\n sage: Q.cover_relations()\n [[0, 1], [0, 2], [1, 3], [2, 3]]\n\n Relabeling a (semi)lattice gives a (semi)lattice::\n\n sage: P = JoinSemilattice({0: [1]})\n sage: P.relabel(lambda n: n+1)\n Finite join-semilattice containing 2 elements\n\n .. NOTE::\n\n As can be seen in the above examples, the default linear\n extension of ``Q`` is that of ``P`` after relabeling. In\n particular, ``P`` and ``Q`` share the same internal Hasse\n diagram.\n\n TESTS:\n\n Test non-facade poset::\n\n sage: P = Poset({3: [2]}, facade=False)\n sage: Q = P.relabel(lambda x: chr(ord(\'a\')+x))\n sage: Q(\'c\') < Q(\'d\')\n False\n\n The following checks that :trac:`14019` has been fixed::\n\n sage: d = DiGraph({2:[1],3:[1]})\n sage: p1 = Poset(d)\n sage: p2 = p1.relabel({1:1,2:3,3:2})\n sage: p1.hasse_diagram() == p2.hasse_diagram()\n True\n sage: p1 == p2\n True\n\n sage: d = DiGraph({2:[1],3:[1]})\n sage: p1 = Poset(d)\n sage: p2 = p1.relabel({1:2,2:3,3:1})\n sage: p3 = p2.relabel({2:1,1:2,3:3})\n sage: p1.hasse_diagram() == p3.hasse_diagram()\n True\n sage: p1 == p3\n True\n '
from sage.combinat.posets.lattices import FiniteLatticePoset, FiniteMeetSemilattice, FiniteJoinSemilattice
if isinstance(self, FiniteLatticePoset):
constructor = FiniteLatticePoset
elif isinstance(self, FiniteMeetSemilattice):
constructor = FiniteMeetSemilattice
elif isinstance(self, FiniteJoinSemilattice):
constructor = FiniteJoinSemilattice
else:
constructor = FinitePoset
if (relabeling is None):
return constructor(self._hasse_diagram, category=self.category(), facade=self._is_facade)
if isinstance(relabeling, (list, tuple)):
relabeling = {i: relabeling[i] for i in range(len(self._elements))}
else:
if isinstance(relabeling, dict):
relabeling = relabeling.__getitem__
relabeling = {i: relabeling(x) for (i, x) in enumerate(self._elements)}
if (not self._with_linear_extension):
elements = None
else:
elements = tuple((relabeling[self._element_to_vertex(x)] for x in self._elements))
return constructor(self._hasse_diagram.relabel(relabeling, inplace=False), elements=elements, category=self.category(), facade=self._is_facade)
def canonical_label(self, algorithm=None):
'\n Return the unique poset on the labels `\\{0, \\ldots, n-1\\}` (where `n`\n is the number of elements in the poset) that is isomorphic to this\n poset and invariant in the isomorphism class.\n\n INPUT:\n\n - ``algorithm`` -- string (optional); a parameter forwarded\n to underlying graph function to select the algorithm to use\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: P.list()\n [1, 2, 3, 4, 6, 12]\n sage: Q = P.canonical_label()\n sage: sorted(Q.list())\n [0, 1, 2, 3, 4, 5]\n sage: Q.is_isomorphic(P)\n True\n\n Canonical labeling of (semi)lattice returns (semi)lattice::\n\n sage: D = DiGraph({\'a\':[\'b\',\'c\']})\n sage: P = Poset(D)\n sage: ML = MeetSemilattice(D)\n sage: P.canonical_label()\n Finite poset containing 3 elements\n sage: ML.canonical_label()\n Finite meet-semilattice containing 3 elements\n\n .. SEEALSO::\n\n - Canonical labeling of directed graphs:\n :meth:`~sage.graphs.generic_graph.GenericGraph.canonical_label()`\n\n TESTS::\n\n sage: P = Poset(digraphs.Path(10), linear_extension=True)\n sage: Q = P.canonical_label()\n sage: Q.linear_extension() # random\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: Q.cover_relations() # random\n [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]\n sage: P = Poset(digraphs.Path(10))\n sage: Q = P.canonical_label()\n sage: Q.linear_extension() # random\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sage: Q.is_isomorphic(P)\n True\n\n sage: Poset().canonical_label() # Test the empty poset\n Finite poset containing 0 elements\n\n sage: D2 = posets.DiamondPoset(4).canonical_label(algorithm=\'bliss\') # optional - bliss\n sage: B2 = posets.BooleanLattice(2).canonical_label(algorithm=\'bliss\') # optional - bliss\n sage: D2 == B2 # optional - bliss\n True\n '
canonical_label = self._hasse_diagram.canonical_label(certificate=True, algorithm=algorithm)[1]
canonical_label = {self._elements[v]: i for (v, i) in canonical_label.items()}
return self.relabel(canonical_label)
def with_linear_extension(self, linear_extension):
'\n Return a copy of ``self`` with a different default linear extension.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), linear_extension=True)\n sage: P.cover_relations()\n [[1, 2], [1, 3], [2, 4], [2, 6], [3, 6], [4, 12], [6, 12]]\n sage: list(P)\n [1, 2, 3, 4, 6, 12]\n sage: Q = P.with_linear_extension([1,3,2,6,4,12])\n sage: list(Q)\n [1, 3, 2, 6, 4, 12]\n sage: Q.cover_relations()\n [[1, 3], [1, 2], [3, 6], [2, 6], [2, 4], [6, 12], [4, 12]]\n\n TESTS:\n\n We check that we can pass in a list of elements of ``P`` instead::\n\n sage: Q = P.with_linear_extension([P(_) for _ in [1,3,2,6,4,12]])\n sage: list(Q)\n [1, 3, 2, 6, 4, 12]\n sage: Q.cover_relations()\n [[1, 3], [1, 2], [3, 6], [2, 6], [2, 4], [6, 12], [4, 12]]\n\n We check that this works for facade posets too::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True)\n sage: Q = P.with_linear_extension([1,3,2,6,4,12]); Q\n Finite poset containing 6 elements with distinguished linear extension\n sage: list(Q)\n [1, 3, 2, 6, 4, 12]\n sage: Q.cover_relations()\n [[1, 3], [1, 2], [3, 6], [2, 6], [2, 4], [6, 12], [4, 12]]\n sage: sorted(Q.cover_relations()) == sorted(P.cover_relations())\n True\n\n (Semi)lattice remains (semi)lattice with new linear extension::\n\n sage: L = LatticePoset(P)\n sage: Q = L.with_linear_extension([1,3,2,6,4,12]); Q\n Finite lattice containing 6 elements with distinguished linear extension\n\n .. NOTE::\n\n With the current implementation, this requires relabeling\n the internal :class:`DiGraph` which is `O(n+m)`, where `n`\n is the number of elements and `m` the number of cover relations.\n '
new_vertices = [self._element_to_vertex(element) for element in linear_extension]
vertex_relabeling = dict(zip(new_vertices, linear_extension))
constructor = self.__class__.__base__
return constructor(self._hasse_diagram.relabel(vertex_relabeling, inplace=False), elements=linear_extension, category=self.category(), facade=self._is_facade)
def graphviz_string(self, graph_string='graph', edge_string='--'):
'\n Return a representation in the DOT language, ready to render in\n graphviz.\n\n See http://www.graphviz.org/doc/info/lang.html for more information\n about graphviz.\n\n EXAMPLES::\n\n sage: P = Poset({\'a\':[\'b\'],\'b\':[\'d\'],\'c\':[\'d\'],\'d\':[\'f\'],\'e\':[\'f\'],\'f\':[]})\n sage: print(P.graphviz_string())\n graph {\n "f";"d";"b";"a";"c";"e";\n "f"--"e";"d"--"c";"b"--"a";"d"--"b";"f"--"d";\n }\n '
s = ('%s {\n' % graph_string)
for v in reversed(self.list()):
s += ('"%s";' % v)
s += '\n'
for (u, v) in self.cover_relations_iterator():
s += f'"{v}"{edge_string}"{u}";'
s += '\n}'
return s
def subposet(self, elements):
'\n Return the poset containing given elements with partial order\n induced by this poset.\n\n EXAMPLES::\n\n sage: P = Poset({\'a\': [\'c\', \'d\'], \'b\': [\'d\',\'e\'], \'c\': [\'f\'],\n ....: \'d\': [\'f\'], \'e\': [\'f\']})\n sage: Q = P.subposet([\'a\', \'b\', \'f\']); Q\n Finite poset containing 3 elements\n sage: Q.cover_relations()\n [[\'b\', \'f\'], [\'a\', \'f\']]\n\n A subposet of a non-facade poset is again a non-facade poset::\n\n sage: P = posets.PentagonPoset(facade=False)\n sage: Q = P.subposet([0, 1, 2, 4])\n sage: Q(1) < Q(2)\n False\n\n TESTS::\n\n sage: P = Poset({\'a\': [\'b\'], \'b\': [\'c\']})\n sage: P.subposet((\'a\', \'b\', \'c\'))\n Finite poset containing 3 elements\n sage: P.subposet([])\n Finite poset containing 0 elements\n sage: P.subposet(["a","b","x"])\n Traceback (most recent call last):\n ...\n ValueError: element (=x) not in poset\n sage: P.subposet(3)\n Traceback (most recent call last):\n ...\n TypeError: \'sage.rings.integer.Integer\' object is not iterable\n '
H = self._hasse_diagram
elms = sorted(set((self._element_to_vertex(e) for e in elements)))
if (not elms):
return Poset()
relations = []
lt = [set() for _ in range((elms[(- 1)] + 1))]
for i in range(elms[0], (elms[(- 1)] + 1)):
for low in H.neighbor_in_iterator(i):
lt[i].update(lt[low])
if (i in elms):
relations += [(x, i) for x in lt[i]]
lt[i] = set([i])
g = DiGraph([elms, relations], format='vertices_and_edges')
if self._is_facade:
g.relabel(self._vertex_to_element, inplace=True)
else:
g.relabel((lambda v: self._vertex_to_element(v).element), inplace=True)
return Poset(g, cover_relations=False, facade=self._is_facade)
def random_subposet(self, p):
'\n Return a random subposet that contains each element with\n probability ``p``.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(3)\n sage: set_random_seed(0) # Results are reproducible\n sage: Q = P.random_subposet(0.5)\n sage: Q.cover_relations()\n [[0, 2], [0, 5], [2, 3], [3, 7], [5, 7]]\n\n TESTS::\n\n sage: P = posets.IntegerPartitions(4) # needs sage.combinat\n sage: P.random_subposet(1) == P # needs sage.combinat\n True\n '
from sage.misc.randstate import current_randstate
random = current_randstate().python_random().random
elements = []
p = float(p)
if ((p < 0) or (p > 1)):
raise ValueError('probability p must be in [0..1]')
for v in self:
if (random() <= p):
elements.append(v)
return self.subposet(elements)
def random_order_ideal(self, direction='down'):
"\n Return a random order ideal with uniform probability.\n\n INPUT:\n\n - ``direction`` -- ``'up'``, ``'down'`` or ``'antichain'``\n (default: ``'down'``)\n\n OUTPUT:\n\n A randomly selected order ideal (or order filter if\n ``direction='up'``, or antichain if ``direction='antichain'``)\n where all order ideals have equal probability of occurring.\n\n ALGORITHM:\n\n Uses the coupling from the past algorithm described in [Propp1997]_.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(3)\n sage: P.random_order_ideal() # random\n [0, 1, 2, 3, 4, 5, 6]\n sage: P.random_order_ideal(direction='up') # random\n [6, 7]\n sage: P.random_order_ideal(direction='antichain') # random\n [1, 2]\n\n sage: P = posets.TamariLattice(5)\n sage: a = P.random_order_ideal('antichain')\n sage: P.is_antichain_of_poset(a)\n True\n sage: a = P.random_order_ideal('up')\n sage: P.is_order_filter(a)\n True\n sage: a = P.random_order_ideal('down')\n sage: P.is_order_ideal(a)\n True\n "
from sage.misc.randstate import current_randstate
from sage.misc.randstate import seed
from sage.misc.randstate import random
hd = self._hasse_diagram
n = len(hd)
lower_covers = [list(hd.lower_covers_iterator(i)) for i in range(n)]
upper_covers = [list(hd.upper_covers_iterator(i)) for i in range(n)]
count = n
seedlist = [(current_randstate().long_seed(), count)]
while True:
state = ([2] * n)
for (currseed, count) in seedlist:
with seed(currseed):
for _ in range(count):
for element in range(n):
if ((random() % 2) == 1):
s = [state[i] for i in lower_covers[element]]
if (1 not in s):
if (2 not in s):
state[element] = 0
elif (state[element] == 1):
state[element] = 2
else:
s = [state[i] for i in upper_covers[element]]
if (0 not in s):
if (2 not in s):
state[element] = 1
elif (state[element] == 0):
state[element] = 2
if all(((x != 2) for x in state)):
break
count = (seedlist[0][1] * 2)
seedlist.insert(0, (current_randstate().long_seed(), count))
if (direction == 'up'):
return [self._vertex_to_element(i) for (i, x) in enumerate(state) if (x == 1)]
if (direction == 'antichain'):
return [self._vertex_to_element(i) for (i, x) in enumerate(state) if ((x == 0) and all(((state[j] == 1) for j in hd.upper_covers_iterator(i))))]
if (direction != 'down'):
raise ValueError("direction must be 'up', 'down' or 'antichain'")
return [self._vertex_to_element(i) for (i, x) in enumerate(state) if (x == 0)]
def random_maximal_chain(self):
'\n Return a random maximal chain of the poset.\n\n The distribution is not uniform.\n\n EXAMPLES::\n\n sage: set_random_seed(0) # results are reproduceable\n sage: P = posets.BooleanLattice(4)\n sage: P.random_maximal_chain()\n [0, 2, 10, 11, 15]\n\n TESTS::\n\n sage: Poset().random_maximal_chain()\n []\n sage: Poset({42: []}).random_maximal_chain()\n [42]\n '
from sage.misc.prandom import randint
if (self.cardinality() == 0):
return []
mins = self.minimal_elements()
new = mins[randint(0, (len(mins) - 1))]
result = [new]
nexts = self.upper_covers(new)
while nexts:
new = nexts[randint(0, (len(nexts) - 1))]
result.append(new)
nexts = self.upper_covers(new)
return result
def random_maximal_antichain(self):
'\n Return a random maximal antichain of the poset.\n\n The distribution is not uniform.\n\n EXAMPLES::\n\n sage: set_random_seed(0) # results are reproduceable\n sage: P = posets.BooleanLattice(4)\n sage: P.random_maximal_antichain()\n [1, 8, 2, 4]\n\n TESTS::\n\n sage: Poset().random_maximal_antichain()\n []\n sage: Poset({42: []}).random_maximal_antichain()\n [42]\n '
H = self.hasse_diagram()
result = []
while H.order():
new = H.random_vertex()
result.append(new)
down = list(H.depth_first_search(new, neighbors=H.neighbor_in_iterator))
up = list(H.depth_first_search(new))
H.delete_vertices((down + up))
return result
def random_linear_extension(self):
'\n Return a random linear extension of the poset.\n\n The distribution is not uniform.\n\n EXAMPLES::\n\n sage: set_random_seed(0) # results are reproduceable\n sage: P = posets.BooleanLattice(4)\n sage: P.random_linear_extension()\n [0, 2, 8, 1, 9, 4, 5, 10, 6, 12, 14, 13, 3, 7, 11, 15]\n\n TESTS::\n\n sage: Poset().random_linear_extension()\n []\n sage: Poset({42: []}).random_linear_extension()\n [42]\n '
from sage.misc.prandom import randint
H = self._hasse_diagram
result = []
indegs = list(H.in_degree_iterator())
mins = H.sources()
for _ in range(H.order()):
new_index = randint(0, (len(mins) - 1))
new = mins[new_index]
result.append(new)
mins = (mins[:new_index] + mins[(new_index + 1):])
for u in H.neighbor_out_iterator(new):
indegs[u] -= 1
if (indegs[u] == 0):
mins.append(u)
return [self._vertex_to_element(v) for v in result]
def order_filter(self, elements):
'\n Return the order filter generated by the elements of an\n iterable ``elements``.\n\n `I` is an order filter if, for any `x` in `I` and `y` such that\n `y \\ge x`, then `y` is in `I`. This is also called upper set or\n upset.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(1000), attrcall("divides")))\n sage: P.order_filter([20, 25])\n [20, 40, 25, 50, 100, 200, 125, 250, 500, 1000]\n\n .. SEEALSO::\n\n :meth:`order_ideal`, :meth:`~sage.categories.posets.Posets.ParentMethods.principal_order_filter`.\n\n TESTS::\n\n sage: P = Poset() # Test empty poset\n sage: P.order_filter([])\n []\n sage: C = posets.ChainPoset(5)\n sage: C.order_filter([])\n []\n '
vertices = sorted(map(self._element_to_vertex, elements))
of = self._hasse_diagram.order_filter(vertices)
return [self._vertex_to_element(_) for _ in of]
def order_ideal(self, elements):
'\n Return the order ideal generated by the elements of an\n iterable ``elements``.\n\n `I` is an order ideal if, for any `x` in `I` and `y` such that\n `y \\le x`, then `y` is in `I`. This is also called lower set or\n downset.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(1000), attrcall("divides")))\n sage: P.order_ideal([20, 25])\n [1, 2, 4, 5, 10, 20, 25]\n\n .. SEEALSO::\n\n :meth:`order_filter`, :meth:`~sage.categories.posets.Posets.ParentMethods.principal_order_ideal`.\n\n TESTS::\n\n sage: P = Poset() # Test empty poset\n sage: P.order_ideal([])\n []\n sage: C = posets.ChainPoset(5)\n sage: C.order_ideal([])\n []\n '
vertices = [self._element_to_vertex(_) for _ in elements]
oi = self._hasse_diagram.order_ideal(vertices)
return [self._vertex_to_element(_) for _ in oi]
def order_ideal_cardinality(self, elements):
'\n Return the cardinality of the order ideal generated by ``elements``.\n\n The elements `I` is an order ideal if, for any `x \\in I` and `y`\n such that `y \\le x`, then `y \\in I`.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.order_ideal_cardinality([7,10])\n 10\n '
vertices = [self._element_to_vertex(elmt) for elmt in elements]
return self._hasse_diagram.order_ideal_cardinality(vertices)
def order_ideal_plot(self, elements):
'\n Return a plot of the order ideal generated by the elements of an\n iterable ``elements``.\n\n `I` is an order ideal if, for any `x` in `I` and `y` such that\n `y \\le x`, then `y` is in `I`. This is also called lower set or\n downset.\n\n EXAMPLES::\n\n sage: # needs sage.plot\n sage: P = Poset((divisors(1000), attrcall("divides")))\n sage: P.order_ideal_plot([20, 25])\n Graphics object consisting of 41 graphics primitives\n\n TESTS::\n\n sage: # needs sage.plot\n sage: P = Poset() # Test empty poset\n sage: P.order_ideal_plot([])\n Graphics object consisting of 0 graphics primitives\n sage: C = posets.ChainPoset(5)\n sage: C.order_ideal_plot([])\n Graphics object consisting of 10 graphics primitives\n '
order_ideal = self.order_ideal(elements)
order_filer = self.order_filter(self.order_ideal_complement_generators(order_ideal))
order_ideal_color_dictionary = {}
order_ideal_color_dictionary['green'] = order_ideal
order_ideal_color_dictionary['red'] = order_filer
return self.plot(element_colors=order_ideal_color_dictionary)
def interval(self, x, y):
'\n Return a list of the elements `z` such that `x \\le z \\le y`.\n\n INPUT:\n\n - ``x`` -- any element of the poset\n\n - ``y`` -- any element of the poset\n\n EXAMPLES::\n\n sage: uc = [[1,3,2],[4],[4,5,6],[6],[7],[7],[7],[]]\n sage: dag = DiGraph(dict(zip(range(len(uc)),uc)))\n sage: P = Poset(dag)\n sage: I = set(map(P,[2,5,6,4,7]))\n sage: I == set(P.interval(2,7))\n True\n\n ::\n\n sage: dg = DiGraph({"a":["b","c"], "b":["d"], "c":["d"]})\n sage: P = Poset(dg, facade = False)\n sage: P.interval("a","d")\n [a, b, c, d]\n '
return [self._vertex_to_element(w) for w in self._hasse_diagram.interval(self._element_to_vertex(x), self._element_to_vertex(y))]
def closed_interval(self, x, y):
'\n Return the list of elements `z` such that `x \\le z \\le y` in the poset.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(1000), attrcall("divides")))\n sage: P.closed_interval(2, 100)\n [2, 4, 10, 20, 50, 100]\n\n .. SEEALSO::\n\n :meth:`open_interval`\n\n TESTS::\n\n sage: C = posets.ChainPoset(10)\n sage: C.closed_interval(3, 3)\n [3]\n sage: C.closed_interval(8, 5)\n []\n sage: A = posets.AntichainPoset(10)\n sage: A.closed_interval(3, 7)\n []\n '
return [self._vertex_to_element(_) for _ in self._hasse_diagram.interval(self._element_to_vertex(x), self._element_to_vertex(y))]
def open_interval(self, x, y):
'\n Return the list of elements `z` such that `x < z < y` in the poset.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(1000), attrcall("divides")))\n sage: P.open_interval(2, 100)\n [4, 10, 20, 50]\n\n .. SEEALSO::\n\n :meth:`closed_interval`\n\n TESTS::\n\n sage: C = posets.ChainPoset(10)\n sage: C.open_interval(3, 3)\n []\n sage: C.open_interval(3, 4)\n []\n sage: C.open_interval(7, 3)\n []\n sage: A = posets.AntichainPoset(10)\n sage: A.open_interval(3, 7)\n []\n '
return [self._vertex_to_element(_) for _ in self._hasse_diagram.open_interval(self._element_to_vertex(x), self._element_to_vertex(y))]
def comparability_graph(self):
'\n Return the comparability graph of the poset.\n\n The comparability graph is an undirected graph where vertices\n are the elements of the poset and there is an edge between two\n vertices if they are comparable in the poset.\n\n See :wikipedia:`Comparability_graph`\n\n EXAMPLES::\n\n sage: Y = Poset({1: [2], 2: [3, 4]})\n sage: g = Y.comparability_graph(); g\n Comparability graph on 4 vertices\n sage: Y.compare_elements(1, 3) is not None\n True\n sage: g.has_edge(1, 3)\n True\n\n .. SEEALSO:: :meth:`incomparability_graph`, :mod:`sage.graphs.comparability`\n\n TESTS::\n\n sage: Poset().comparability_graph()\n Comparability graph on 0 vertices\n\n sage: C4 = posets.ChainPoset(4)\n sage: C4.comparability_graph().is_isomorphic(graphs.CompleteGraph(4))\n True\n\n sage: A4 = posets.AntichainPoset(4)\n sage: A4.comparability_graph().is_isomorphic(Graph(4))\n True\n '
G = self.hasse_diagram().transitive_closure().to_undirected()
G.rename(('Comparability graph on %s vertices' % self.cardinality()))
return G
def incomparability_graph(self):
'\n Return the incomparability graph of the poset.\n\n This is the complement of the comparability graph, i.e. an\n undirected graph where vertices are the elements of the poset\n and there is an edge between vertices if they are not\n comparable in the poset.\n\n EXAMPLES::\n\n sage: Y = Poset({1: [2], 2: [3, 4]})\n sage: g = Y.incomparability_graph(); g\n Incomparability graph on 4 vertices\n sage: Y.compare_elements(1, 3) is not None\n True\n sage: g.has_edge(1, 3)\n False\n\n .. SEEALSO:: :meth:`comparability_graph`\n\n TESTS::\n\n sage: Poset().incomparability_graph()\n Incomparability graph on 0 vertices\n\n sage: C4 = posets.ChainPoset(4)\n sage: C4.incomparability_graph().is_isomorphic(Graph(4))\n True\n\n sage: A4 = posets.AntichainPoset(4)\n sage: A4.incomparability_graph().is_isomorphic(graphs.CompleteGraph(4))\n True\n '
G = self.comparability_graph().complement()
G.rename(('Incomparability graph on %s vertices' % self.cardinality()))
return G
def linear_extensions_graph(self):
'\n Return the linear extensions graph of the poset.\n\n Vertices of the graph are linear extensions of the poset.\n Two vertices are connected by an edge if the linear extensions\n differ by only one adjacent transposition.\n\n EXAMPLES::\n\n sage: N = Poset({1: [3, 4], 2: [4]})\n sage: G = N.linear_extensions_graph(); G\n Graph on 5 vertices\n sage: G.neighbors(N.linear_extension([1,2,3,4]))\n [[2, 1, 3, 4], [1, 3, 2, 4], [1, 2, 4, 3]]\n\n sage: chevron = Poset({1: [2, 6], 2: [3], 4: [3, 5], 6: [5]})\n sage: G = chevron.linear_extensions_graph(); G\n Graph on 22 vertices\n sage: G.size()\n 36\n\n TESTS::\n\n sage: Poset().linear_extensions_graph()\n Graph on 1 vertex\n\n sage: A4 = posets.AntichainPoset(4)\n sage: G = A4.linear_extensions_graph()\n sage: G.is_regular()\n True\n '
from sage.graphs.graph import Graph
L = list(self.linear_extensions())
G = Graph()
G.add_vertices(L)
for i in range(len(L)):
for j in range(i):
tmp = [(x != y) for (x, y) in zip(L[i], L[j])]
if ((tmp.count(True) == 2) and tmp[(tmp.index(True) + 1)]):
G.add_edge(L[i], L[j])
return G
def maximal_antichains(self):
"\n Return the maximal antichains of the poset.\n\n An antichain `a` of poset `P` is *maximal* if there is\n no element `e \\in P \\setminus a` such that `a \\cup \\{e\\}`\n is an antichain.\n\n EXAMPLES::\n\n sage: P = Poset({'a':['b', 'c'], 'b':['d','e']})\n sage: [sorted(anti) for anti in P.maximal_antichains()]\n [['a'], ['b', 'c'], ['c', 'd', 'e']]\n\n sage: posets.PentagonPoset().maximal_antichains()\n [[0], [1, 2], [1, 3], [4]]\n\n .. SEEALSO:: :meth:`antichains`, :meth:`maximal_chains`\n "
return self.incomparability_graph().cliques_maximal()
def maximal_chains(self, partial=None):
'\n Return all maximal chains of this poset.\n\n Each chain is listed in increasing order.\n\n INPUT:\n\n - ``partial`` -- list (optional); if given, the list\n ``partial`` is assumed to be the start of a maximal chain,\n and the function will find all maximal chains starting with\n the elements in ``partial``\n\n This is used in constructing the order complex for the poset.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(3)\n sage: P.maximal_chains()\n [[0, 1, 3, 7], [0, 1, 5, 7], [0, 2, 3, 7], [0, 2, 6, 7], [0, 4, 5, 7], [0, 4, 6, 7]]\n sage: P.maximal_chains(partial=[0,2])\n [[0, 2, 3, 7], [0, 2, 6, 7]]\n sage: Q = posets.ChainPoset(6)\n sage: Q.maximal_chains()\n [[0, 1, 2, 3, 4, 5]]\n\n .. SEEALSO:: :meth:`maximal_antichains`, :meth:`chains`\n '
return list(self.maximal_chains_iterator(partial=partial))
def maximal_chains_iterator(self, partial=None):
'\n Return an iterator over maximal chains.\n\n Each chain is listed in increasing order.\n\n INPUT:\n\n - ``partial`` -- list (optional); if given, the list\n ``partial`` is assumed to be the start of a maximal chain,\n and the function will yield all maximal chains starting with\n the elements in ``partial``\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(3)\n sage: it = P.maximal_chains_iterator()\n sage: next(it)\n [0, 1, 3, 7]\n\n TESTS::\n\n sage: P = posets.BooleanLattice(3)\n sage: it = P.maximal_chains_iterator([0, 4])\n sage: next(it)\n [0, 4, 5, 7]\n\n .. SEEALSO::\n\n :meth:`antichains_iterator`\n '
if (not partial):
start = self.minimal_elements()
partial = []
else:
start = self.upper_covers(partial[(- 1)])
if (not start):
(yield partial)
elif (len(start) == 1):
(yield from self.maximal_chains_iterator(partial=(partial + start)))
else:
parts = ((partial + [x]) for x in start)
for new in parts:
(yield from self.maximal_chains_iterator(partial=new))
def maximal_chain_length(self):
'\n Return the maximum length of a maximal chain in the poset.\n\n The length here is the number of vertices.\n\n EXAMPLES::\n\n sage: P = posets.TamariLattice(5)\n sage: P.maximal_chain_length()\n 11\n\n TESTS::\n\n sage: Poset().maximal_chain_length()\n 0\n\n .. SEEALSO:: :meth:`maximal_chains`, :meth:`maximal_chains_iterator`\n '
if (not self.cardinality()):
return 0
store = {}
for x in self:
below = self.lower_covers(x)
if (not below):
store[x] = 1
else:
store[x] = (1 + max((store[y] for y in below)))
return max(store.values())
def order_complex(self, on_ints=False):
'\n Return the order complex associated to this poset.\n\n The order complex is the simplicial complex with vertices equal\n to the elements of the poset, and faces given by the chains.\n\n INPUT:\n\n - ``on_ints`` -- a boolean (default: ``False``)\n\n OUTPUT:\n\n an order complex of type :class:`SimplicialComplex`\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(3)\n sage: S = P.order_complex(); S\n Simplicial complex with vertex set (0, 1, 2, 3, 4, 5, 6, 7) and 6 facets\n sage: S.f_vector()\n [1, 8, 19, 18, 6]\n sage: S.homology() # S is contractible\n {0: 0, 1: 0, 2: 0, 3: 0}\n sage: Q = P.subposet([1,2,3,4,5,6])\n sage: Q.order_complex().homology() # a circle\n {0: 0, 1: Z}\n\n sage: P = Poset((divisors(15), attrcall("divides")), facade = True)\n sage: P.order_complex()\n Simplicial complex with vertex set (1, 3, 5, 15) and facets {(1, 3, 15), (1, 5, 15)}\n\n If ``on_ints``, then the elements of the poset are labelled\n `0,1,\\dots` in the chain complex::\n\n sage: P.order_complex(on_ints=True)\n Simplicial complex with vertex set (0, 1, 2, 3) and facets {(0, 1, 3), (0, 2, 3)}\n '
from sage.topology.simplicial_complex import SimplicialComplex
L = self.list()
if on_ints:
iso = dict([(L[i], i) for i in range(len(L))])
facets = []
for f in self.maximal_chains_iterator():
if on_ints:
facets.append([iso[a] for a in f])
elif self._is_facade:
facets.append([a for a in f])
else:
facets.append([a.element for a in f])
return SimplicialComplex(facets, maximality_check=False)
def order_polytope(self):
'\n Return the order polytope of the poset ``self``.\n\n The order polytope of a finite poset `P` is defined as the subset\n of `\\RR^P` consisting of all maps `x : P \\to \\RR` satisfying\n\n .. MATH::\n\n 0 \\leq x(p) \\leq 1 \\mbox{ for all } p \\in P,\n\n and\n\n .. MATH::\n\n x(p) \\leq x(q) \\mbox{ for all } p, q \\in P\n \\mbox{ satisfying } p < q.\n\n This polytope was defined and studied in [St1986]_.\n\n EXAMPLES::\n\n sage: P = posets.AntichainPoset(3)\n sage: Q = P.order_polytope(); Q # needs sage.geometry.polyhedron\n A 3-dimensional polyhedron in ZZ^3 defined as the convex hull of 8 vertices\n sage: P = posets.PentagonPoset()\n sage: Q = P.order_polytope(); Q # needs sage.geometry.polyhedron\n A 5-dimensional polyhedron in ZZ^5 defined as the convex hull of 8 vertices\n\n sage: P = Poset([[1,2,3],[[1,2],[1,3]]])\n sage: Q = P.order_polytope() # needs sage.geometry.polyhedron\n sage: Q.contains((1,0,0)) # needs sage.geometry.polyhedron\n False\n sage: Q.contains((0,1,1)) # needs sage.geometry.polyhedron\n True\n '
from sage.geometry.polyhedron.constructor import Polyhedron
ineqs = [([0] + [(ZZ((j == v)) - ZZ((j == u))) for j in self]) for (u, v) in self.hasse_diagram().edges(sort=False, labels=False)]
for i in self.maximal_elements():
ineqs += [([1] + [(- ZZ((j == i))) for j in self])]
for i in self.minimal_elements():
ineqs += [([0] + [ZZ((j == i)) for j in self])]
return Polyhedron(ieqs=ineqs, base_ring=ZZ)
def chain_polytope(self):
'\n Return the chain polytope of the poset ``self``.\n\n The chain polytope of a finite poset `P` is defined as the subset\n of `\\RR^P` consisting of all maps `x : P \\to \\RR` satisfying\n\n .. MATH::\n\n x(p) \\geq 0 \\mbox{ for all } p \\in P,\n\n and\n\n .. MATH::\n\n x(p_1) + x(p_2) + \\ldots + x(p_k) \\leq 1\n \\mbox{ for all chains } p_1 < p_2 < \\ldots < p_k\n \\mbox{ in } P.\n\n This polytope was defined and studied in [St1986]_.\n\n EXAMPLES::\n\n sage: P = posets.AntichainPoset(3)\n sage: Q = P.chain_polytope();Q # needs sage.geometry.polyhedron\n A 3-dimensional polyhedron in ZZ^3 defined as the convex hull of 8 vertices\n sage: P = posets.PentagonPoset()\n sage: Q = P.chain_polytope();Q # needs sage.geometry.polyhedron\n A 5-dimensional polyhedron in ZZ^5 defined as the convex hull of 8 vertices\n '
from sage.geometry.polyhedron.constructor import Polyhedron
ineqs = [([1] + [(- ZZ((j in chain))) for j in self]) for chain in self.maximal_chains_iterator()]
for i in self:
ineqs += [([0] + [ZZ((j == i)) for j in self])]
return Polyhedron(ieqs=ineqs, base_ring=ZZ)
def zeta_polynomial(self):
'\n Return the zeta polynomial of the poset.\n\n The zeta polynomial of a poset is the unique polynomial `Z(q)`\n such that for every integer `m > 1`, `Z(m)` is the number of\n weakly increasing sequences `x_1 \\leq x_2 \\leq \\dots \\leq x_{m-1}`\n of elements of the poset.\n\n The polynomial `Z(q)` is integral-valued, but generally does not\n have integer coefficients. It can be computed as\n\n .. MATH::\n\n Z(q) = \\sum_{k \\geq 1} \\dbinom{q-2}{k-1} c_k,\n\n where `c_k` is the number of all chains of length `k` in the\n poset.\n\n For more information, see section 3.12 of [EnumComb1]_.\n\n In particular, `Z(2)` is the number of vertices and `Z(3)` is\n the number of intervals.\n\n EXAMPLES::\n\n sage: posets.ChainPoset(2).zeta_polynomial()\n q\n sage: posets.ChainPoset(3).zeta_polynomial()\n 1/2*q^2 + 1/2*q\n\n sage: P = posets.PentagonPoset()\n sage: P.zeta_polynomial()\n 1/6*q^3 + q^2 - 1/6*q\n\n sage: P = posets.DiamondPoset(5)\n sage: P.zeta_polynomial()\n 3/2*q^2 - 1/2*q\n\n TESTS:\n\n Checking the simplest cases::\n\n sage: Poset({}).zeta_polynomial()\n 0\n sage: Poset({1: []}).zeta_polynomial()\n 1\n sage: Poset({1: [], 2: []}).zeta_polynomial()\n 2\n sage: parent(_)\n Univariate Polynomial Ring in q over Rational Field\n '
R = PolynomialRing(QQ, 'q')
q = R.gen()
g = self.chain_polynomial()
n = g.degree()
f = R(g[max(n, 1)])
while (n > 1):
f = ((q - n) * f)
n -= 1
f = (g[n] + (f / n))
return f
def M_triangle(self):
'\n Return the M-triangle of the poset.\n\n The poset is expected to be graded.\n\n OUTPUT:\n\n an :class:`~sage.combinat.triangles_FHM.M_triangle`\n\n The M-triangle is the generating polynomial of the Möbius numbers\n\n .. MATH::\n\n M(x, y)=\\sum_{a \\leq b} \\mu(a,b) x^{|a|}y^{|b|} .\n\n EXAMPLES::\n\n sage: P = posets.DiamondPoset(5)\n sage: P.M_triangle() # needs sage.combinat\n M: x^2*y^2 - 3*x*y^2 + 3*x*y + 2*y^2 - 3*y + 1\n\n TESTS::\n\n sage: P = posets.PentagonPoset()\n sage: P.M_triangle() # needs sage.combinat\n Traceback (most recent call last):\n ...\n ValueError: the poset is not graded\n '
from sage.combinat.triangles_FHM import M_triangle
hasse = self._hasse_diagram
rk = hasse.rank_function()
if (rk is None):
raise ValueError('the poset is not graded')
ring = PolynomialRing(ZZ, 'x,y')
p = ring.sum(((hasse.moebius_function(a, b) * ring.monomial(rk(a), rk(b))) for a in hasse for b in hasse.principal_order_filter(a)))
return M_triangle(p)
def f_polynomial(self):
'\n Return the `f`-polynomial of the poset.\n\n The poset is expected to be bounded.\n\n This is the `f`-polynomial of the order complex of the poset\n minus its bounds.\n\n The coefficient of `q^i` is the number of chains of\n `i+1` elements containing both bounds of the poset.\n\n .. note::\n\n This is slightly different from the ``fPolynomial``\n method in Macaulay2.\n\n EXAMPLES::\n\n sage: P = posets.DiamondPoset(5)\n sage: P.f_polynomial()\n 3*q^2 + q\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [7], 6: [7]})\n sage: P.f_polynomial()\n q^4 + 4*q^3 + 5*q^2 + q\n\n .. SEEALSO::\n\n :meth:`is_bounded`, :meth:`h_polynomial`, :meth:`order_complex`,\n :meth:`sage.topology.cell_complex.GenericCellComplex.f_vector`\n\n TESTS::\n\n sage: P = Poset({2: []})\n sage: P.f_polynomial()\n 1\n\n sage: P = Poset({2:[1,3]})\n sage: P.f_polynomial()\n Traceback (most recent call last):\n ...\n ValueError: the poset is not bounded\n '
q = polygen(ZZ, 'q')
hasse = self._hasse_diagram
if (len(hasse) == 1):
return q.parent().one()
maxi = hasse.top()
mini = hasse.bottom()
if ((mini is None) or (maxi is None)):
raise ValueError('the poset is not bounded')
hasse_size = hasse.cardinality()
chain_polys = ([0] * hasse_size)
for i in range(1, (hasse_size - 1)):
chain_polys[i] = (q + sum(((q * chain_polys[j]) for j in hasse.principal_order_ideal(i) if j)))
return (q + (q * sum(chain_polys)))
def h_polynomial(self):
'\n Return the `h`-polynomial of a bounded poset ``self``.\n\n This is the `h`-polynomial of the order complex of the poset\n minus its bounds.\n\n This is related to the `f`-polynomial by a simple change\n of variables:\n\n .. MATH::\n\n h(q) = (1-q)^{\\deg f} f \\left( \\frac{q}{1-q} \\right),\n\n where `f` and `h` denote the `f`-polynomial and the\n `h`-polynomial, respectively.\n\n See :wikipedia:`h-vector`.\n\n .. WARNING::\n\n This is slightly different from the ``hPolynomial``\n method in Macaulay2.\n\n EXAMPLES::\n\n sage: P = posets.AntichainPoset(3).order_ideals_lattice()\n sage: P.h_polynomial()\n q^3 + 4*q^2 + q\n sage: P = posets.DiamondPoset(5)\n sage: P.h_polynomial()\n 2*q^2 + q\n sage: P = Poset({1: []})\n sage: P.h_polynomial()\n 1\n\n .. SEEALSO::\n\n :meth:`is_bounded`, :meth:`f_polynomial`, :meth:`order_complex`,\n :meth:`sage.topology.simplicial_complex.SimplicialComplex.h_vector`\n '
q = polygen(ZZ, 'q')
ring = q.parent()
hasse = self._hasse_diagram
if (len(hasse) == 1):
return q.parent().one()
maxi = hasse.top()
mini = hasse.bottom()
if ((mini is None) or (maxi is None)):
raise ValueError('the poset is not bounded')
f = ring.sum((ring.monomial(len(ch)) for ch in hasse.chains(exclude=[mini, maxi])))
d = f.degree()
f = ((((1 - q) ** d) * q) * f(q=(q / (1 - q))))
return ring(f)
def flag_f_polynomial(self):
"\n Return the flag `f`-polynomial of the poset.\n\n The poset is expected to be bounded and ranked.\n\n This is the sum, over all chains containing both bounds,\n of a monomial encoding the ranks of the elements of the chain.\n\n More precisely, if `P` is a bounded ranked poset, then the\n flag `f`-polynomial of `P` is defined as the polynomial\n\n .. MATH::\n\n \\sum_{\\substack{p_0 < p_1 < \\ldots < p_k, \\\\\n p_0 = \\min P, \\ p_k = \\max P}}\n x_{\\rho(p_1)} x_{\\rho(p_2)} \\cdots x_{\\rho(p_k)}\n \\in \\ZZ[x_1, x_2, \\cdots, x_n],\n\n where `\\min P` and `\\max P` are (respectively) the minimum and\n the maximum of `P`, where `\\rho` is the rank function of `P`\n (normalized to satisfy `\\rho(\\min P) = 0`), and where\n `n` is the rank of `\\max P`. (Note that the indeterminate\n `x_0` does not actually appear in the polynomial.)\n\n For technical reasons, the polynomial is returned in the\n slightly larger ring `\\ZZ[x_0, x_1, x_2, \\cdots, x_{n+1}]` by\n this method.\n\n See :wikipedia:`h-vector`.\n\n EXAMPLES::\n\n sage: P = posets.DiamondPoset(5)\n sage: P.flag_f_polynomial()\n 3*x1*x2 + x2\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [6]})\n sage: fl = P.flag_f_polynomial(); fl\n 2*x1*x2*x3 + 2*x1*x3 + 2*x2*x3 + x3\n sage: q = polygen(ZZ,'q')\n sage: fl(q,q,q,q) == P.f_polynomial()\n True\n\n sage: P = Poset({1: [2, 3, 4], 2: [5], 3: [5], 4: [5], 5: [6]})\n sage: P.flag_f_polynomial()\n 3*x1*x2*x3 + 3*x1*x3 + x2*x3 + x3\n\n .. SEEALSO:: :meth:`is_bounded`, :meth:`flag_h_polynomial`\n\n TESTS::\n\n sage: P = Poset({2: [3]})\n sage: P.flag_f_polynomial()\n x1\n\n sage: P = Poset({2: []})\n sage: P.flag_f_polynomial()\n 1\n "
hasse = self._hasse_diagram
maxi = hasse.top()
mini = hasse.bottom()
if ((mini is None) or (maxi is None)):
raise ValueError('the poset is not bounded')
rk = hasse.rank_function()
if (rk is None):
raise ValueError('the poset is not ranked')
n = rk(maxi)
if (n == 0):
return PolynomialRing(ZZ, 'x', 1).one()
anneau = PolynomialRing(ZZ, 'x', (n + 1))
x = anneau.gens()
return (x[n] * sum((prod((x[rk(i)] for i in ch)) for ch in hasse.chains(exclude=[mini, maxi]))))
def flag_h_polynomial(self):
"\n Return the flag `h`-polynomial of the poset.\n\n The poset is expected to be bounded and ranked.\n\n If `P` is a bounded ranked poset whose maximal element has\n rank `n` (where the minimal element is set to have rank `0`),\n then the flag `h`-polynomial of `P` is defined as the\n polynomial\n\n .. MATH::\n\n \\prod_{k=1}^n (1-x_k) \\cdot f \\left(\\frac{x_1}{1-x_1},\n \\frac{x_2}{1-x_2}, \\cdots, \\frac{x_n}{1-x_n}\\right)\n \\in \\ZZ[x_1, x_2, \\cdots, x_n],\n\n where `f` is the flag `f`-polynomial of `P` (see\n :meth:`flag_f_polynomial`).\n\n For technical reasons, the polynomial is returned in the\n slightly larger ring `\\QQ[x_0, x_1, x_2, \\cdots, x_{n+1}]` by\n this method.\n\n See :wikipedia:`h-vector`.\n\n EXAMPLES::\n\n sage: P = posets.DiamondPoset(5)\n sage: P.flag_h_polynomial()\n 2*x1*x2 + x2\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [6]})\n sage: fl = P.flag_h_polynomial(); fl\n -x1*x2*x3 + x1*x3 + x2*x3 + x3\n sage: q = polygen(ZZ,'q')\n sage: fl(q,q,q,q) == P.h_polynomial()\n True\n\n sage: P = Poset({1: [2, 3, 4], 2: [5], 3: [5], 4: [5], 5: [6]})\n sage: P.flag_h_polynomial()\n 2*x1*x3 + x3\n\n sage: P = posets.ChainPoset(4)\n sage: P.flag_h_polynomial()\n x3\n\n .. SEEALSO:: :meth:`is_bounded`, :meth:`flag_f_polynomial`\n\n TESTS::\n\n sage: P = Poset({2: [3]})\n sage: P.flag_h_polynomial()\n x1\n\n sage: P = Poset({2: []})\n sage: P.flag_h_polynomial()\n 1\n "
hasse = self._hasse_diagram
maxi = hasse.top()
mini = hasse.bottom()
if ((mini is None) or (maxi is None)):
raise ValueError('the poset is not bounded')
rk = hasse.rank_function()
if (rk is None):
raise ValueError('the poset is not ranked')
n = rk(maxi)
if (n == 0):
return PolynomialRing(QQ, 'x', 1).one()
anneau = PolynomialRing(QQ, 'x', (n + 1))
x = anneau.gens()
return ((prod(((1 - x[k]) for k in range(1, n))) * x[n]) * sum((prod(((x[rk(i)] / (1 - x[rk(i)])) for i in ch)) for ch in hasse.chains(exclude=[mini, maxi]))))
def characteristic_polynomial(self):
'\n Return the characteristic polynomial of the poset.\n\n The poset is expected to be graded and have a bottom\n element.\n\n If `P` is a graded poset with rank `n` and a unique minimal\n element `\\hat{0}`, then the characteristic polynomial of\n `P` is defined to be\n\n .. MATH::\n\n \\sum_{x \\in P} \\mu(\\hat{0}, x) q^{n-\\rho(x)} \\in \\ZZ[q],\n\n where `\\rho` is the rank function, and `\\mu` is the Möbius\n function of `P`.\n\n See section 3.10 of [EnumComb1]_.\n\n EXAMPLES::\n\n sage: P = posets.DiamondPoset(5)\n sage: P.characteristic_polynomial()\n q^2 - 3*q + 2\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [5], 4: [6], 5: [6], 6: [7]})\n sage: P.characteristic_polynomial()\n q^4 - 2*q^3 + q\n\n TESTS::\n\n sage: P = Poset({1: []})\n sage: P.characteristic_polynomial()\n 1\n '
H = self._hasse_diagram
rk = H.rank_function()
if (not self.is_graded()):
raise ValueError('the poset is not graded')
if (not self.has_bottom()):
raise ValueError('the poset does not have a bottom element')
n = rk(H.maximal_elements()[0])
ring = PolynomialRing(ZZ, 'q')
return ring.sum(((H.bottom_moebius_function(x) * ring.monomial((n - rk(x)))) for x in H))
def chain_polynomial(self):
'\n Return the chain polynomial of the poset.\n\n The coefficient of `q^k` is the number of chains of `k`\n elements in the poset. List of coefficients of this polynomial\n is also called a *f-vector* of the poset.\n\n .. note::\n\n This is not what has been called the chain polynomial\n in [St1986]_. The latter is identical with the order\n polynomial in SageMath (:meth:`order_polynomial`).\n\n .. SEEALSO:: :meth:`f_polynomial`, :meth:`order_polynomial`\n\n EXAMPLES::\n\n sage: P = posets.ChainPoset(3)\n sage: t = P.chain_polynomial(); t\n q^3 + 3*q^2 + 3*q + 1\n sage: t(1) == len(list(P.chains()))\n True\n\n sage: P = posets.BooleanLattice(3)\n sage: P.chain_polynomial()\n 6*q^4 + 18*q^3 + 19*q^2 + 8*q + 1\n\n sage: P = posets.AntichainPoset(5)\n sage: P.chain_polynomial()\n 5*q + 1\n\n TESTS::\n\n sage: P = Poset()\n sage: P.chain_polynomial()\n 1\n sage: parent(P.chain_polynomial())\n Univariate Polynomial Ring in q over Integer Ring\n\n sage: R = Poset({1: []})\n sage: R.chain_polynomial()\n q + 1\n '
hasse = self._hasse_diagram
q = polygen(ZZ, 'q')
one = q.parent().one()
hasse_size = hasse.cardinality()
chain_polys = ([0] * hasse_size)
for i in range(hasse_size):
chain_polys[i] = (q + sum(((q * chain_polys[j]) for j in hasse.principal_order_ideal(i))))
return (one + sum(chain_polys))
def order_polynomial(self):
'\n Return the order polynomial of the poset.\n\n The order polynomial `\\Omega_P(q)` of a poset `P` is defined\n as the unique polynomial `S` such that for each integer\n `m \\geq 1`, `S(m)` is the number of order-preserving maps\n from `P` to `\\{1,\\ldots,m\\}`.\n\n See sections 3.12 and 3.15 of [EnumComb1]_, and also\n [St1986]_.\n\n EXAMPLES::\n\n sage: P = posets.AntichainPoset(3)\n sage: P.order_polynomial()\n q^3\n\n sage: P = posets.ChainPoset(3)\n sage: f = P.order_polynomial(); f\n 1/6*q^3 + 1/2*q^2 + 1/3*q\n sage: [f(i) for i in range(4)]\n [0, 1, 4, 10]\n\n .. SEEALSO:: :meth:`order_polytope`\n '
return self.order_ideals_lattice(as_ideals=False).zeta_polynomial()
def degree_polynomial(self):
'\n Return the generating polynomial of degrees of vertices in ``self``.\n\n This is the sum\n\n .. MATH::\n\n \\sum_{v \\in P} x^{\\operatorname{in}(v)} y^{\\operatorname{out}(v)},\n\n where ``in(v)`` and ``out(v)`` are the number of incoming and\n outgoing edges at vertex `v` in the Hasse diagram of `P`.\n\n Because this polynomial is multiplicative for Cartesian\n product of posets, it is useful to help see if the poset can\n be isomorphic to a Cartesian product.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.degree_polynomial()\n x^2 + 3*x*y + y^2\n\n sage: P = posets.BooleanLattice(4)\n sage: P.degree_polynomial().factor()\n (x + y)^4\n\n .. SEEALSO::\n\n :meth:`cardinality` for the value at `(x, y) = (1, 1)`\n '
return self._hasse_diagram.degree_polynomial()
def promotion(self, i=1):
'\n Compute the (extended) promotion on the linear extension\n of the poset ``self``.\n\n INPUT:\n\n - ``i`` -- an integer between `1` and `n` (default: `1`)\n\n OUTPUT:\n\n - an isomorphic poset, with the same default linear extension\n\n The extended promotion is defined on a poset ``self`` of size\n `n` by applying the promotion operator `\\tau_i \\tau_{i+1}\n \\cdots \\tau_{n-1}` to the default linear extension `\\pi` of ``self``\n (see :meth:`~sage.combinat.posets.linear_extensions.LinearExtensionOfPoset.promotion`),\n and relabeling ``self`` accordingly. For more details see [Stan2009]_.\n\n When the elements of the poset ``self`` are labelled by\n `\\{1,2,\\ldots,n\\}`, the linear extension is the identity, and\n `i=1`, the above algorithm corresponds to the promotion\n operator on posets defined by Schützenberger as\n follows. Remove `1` from ``self`` and replace it by the\n minimum `j` of all labels covering `1` in the poset. Then,\n remove `j` and replace it by the minimum of all labels\n covering `j`, and so on. This process ends when a label is a\n local maximum. Place the label `n+1` at this vertex. Finally,\n decrease all labels by `1`.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2], [[1,2]]), linear_extension=True, facade=False)\n sage: P.promotion()\n Finite poset containing 2 elements with distinguished linear extension\n sage: P == P.promotion()\n True\n\n sage: P = Poset(([1,2,3,4,5,6,7], [[1,2],[1,4],[2,3],[2,5],[3,6],[4,7],[5,6]]))\n sage: P.list()\n [1, 2, 3, 5, 6, 4, 7]\n sage: Q = P.promotion(4); Q\n Finite poset containing 7 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 6], [2, 3], [2, 5], [3, 7], [5, 7], [6, 4]]\n\n Note that if one wants to obtain the promotion defined by\n Schützenberger\'s algorithm directly on the poset, one needs\n to make sure the linear extension is the identity::\n\n sage: P = P.with_linear_extension([1,2,3,4,5,6,7])\n sage: P.list()\n [1, 2, 3, 4, 5, 6, 7]\n sage: Q = P.promotion(4); Q\n Finite poset containing 7 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 6], [2, 3], [2, 4], [3, 5], [4, 5], [6, 7]]\n sage: Q = P.promotion()\n sage: Q.cover_relations()\n [[1, 2], [1, 3], [2, 4], [2, 5], [3, 6], [4, 7], [5, 7]]\n\n Here is an example for a poset not labelled by `\\{1, 2, \\ldots, n\\}`::\n\n sage: P = Poset((divisors(30), attrcall("divides")), linear_extension=True)\n sage: P.list()\n [1, 2, 3, 5, 6, 10, 15, 30]\n sage: P.cover_relations()\n [[1, 2], [1, 3], [1, 5], [2, 6], [2, 10], [3, 6], [3, 15],\n [5, 10], [5, 15], [6, 30], [10, 30], [15, 30]]\n sage: Q = P.promotion(4); Q\n Finite poset containing 8 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 3], [1, 6], [2, 5], [2, 15], [3, 5], [3, 10],\n [5, 30], [6, 10], [6, 15], [10, 30], [15, 30]]\n\n .. SEEALSO::\n\n - :meth:`linear_extension`\n - :meth:`with_linear_extension` and the ``linear_extension`` option of :func:`Poset`\n - :meth:`~sage.combinat.posets.linear_extensions.LinearExtensionOfPoset.promotion`\n - :meth:`evacuation`\n\n AUTHOR:\n\n - Anne Schilling (2012-02-18)\n '
return self.linear_extension().promotion(i).to_poset()
def evacuation(self):
'\n Compute evacuation on the linear extension associated\n to the poset ``self``.\n\n OUTPUT:\n\n - an isomorphic poset, with the same default linear extension\n\n Evacuation is defined on a poset ``self`` of size `n` by\n applying the evacuation operator\n `(\\tau_1 \\cdots \\tau_{n-1}) (\\tau_1 \\cdots \\tau_{n-2}) \\cdots (\\tau_1)`,\n to the default linear extension `\\pi` of ``self``\n (see :meth:`~sage.combinat.posets.linear_extensions.LinearExtensionOfPoset.evacuation`),\n and relabeling ``self`` accordingly. For more details see [Stan2009]_.\n\n EXAMPLES::\n\n sage: P = Poset(([1,2], [[1,2]]), linear_extension=True, facade=False)\n sage: P.evacuation()\n Finite poset containing 2 elements with distinguished linear extension\n sage: P.evacuation() == P\n True\n\n sage: P = Poset(([1,2,3,4,5,6,7], [[1,2],[1,4],[2,3],[2,5],[3,6],[4,7],[5,6]]), linear_extension=True, facade=False)\n sage: P.list()\n [1, 2, 3, 4, 5, 6, 7]\n sage: Q = P.evacuation(); Q\n Finite poset containing 7 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 3], [2, 5], [3, 4], [3, 6], [4, 7], [6, 7]]\n\n Note that the results depend on the linear extension associated\n to the poset::\n\n sage: P = Poset(([1,2,3,4,5,6,7], [[1,2],[1,4],[2,3],[2,5],[3,6],[4,7],[5,6]]))\n sage: P.list()\n [1, 2, 3, 5, 6, 4, 7]\n sage: Q = P.evacuation(); Q\n Finite poset containing 7 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 2], [1, 5], [2, 3], [5, 6], [5, 4], [6, 7], [4, 7]]\n\n Here is an example of a poset where the elements are not labelled\n by `\\{1,2,\\ldots,n\\}`::\n\n sage: P = Poset((divisors(15), attrcall("divides")), linear_extension = True)\n sage: P.list()\n [1, 3, 5, 15]\n sage: Q = P.evacuation(); Q\n Finite poset containing 4 elements with distinguished linear extension\n sage: Q.cover_relations()\n [[1, 3], [1, 5], [3, 15], [5, 15]]\n\n .. SEEALSO::\n\n - :meth:`linear_extension`\n - :meth:`with_linear_extension` and the ``linear_extension`` option of :func:`Poset`\n - :meth:`~sage.combinat.posets.linear_extensions.LinearExtensionOfPoset.evacuation`\n - :meth:`promotion`\n\n AUTHOR:\n\n - Anne Schilling (2012-02-18)\n '
return self.linear_extension().evacuation().to_poset()
def is_rank_symmetric(self) -> bool:
'\n Return ``True`` if the poset is rank symmetric, and ``False``\n otherwise.\n\n The poset is expected to be graded and connected.\n\n A poset of rank `h` (maximal chains have `h+1` elements) is rank\n symmetric if the number of elements are equal in ranks `i` and\n `h-i` for every `i` in `0, 1, \\ldots, h`.\n\n EXAMPLES::\n\n sage: P = Poset({1:[3, 4, 5], 2:[3, 4, 5], 3:[6], 4:[7], 5:[7]})\n sage: P.is_rank_symmetric()\n True\n sage: P = Poset({1:[2], 2:[3, 4], 3:[5], 4:[5]})\n sage: P.is_rank_symmetric()\n False\n\n TESTS::\n\n sage: Poset().is_rank_symmetric() # Test empty poset\n True\n '
if (not self.is_connected()):
raise ValueError('the poset is not connected')
if (not self.is_graded()):
raise ValueError('the poset is not graded')
levels = self._hasse_diagram.level_sets()
h = len(levels)
for i in range((h // 2)):
if (len(levels[i]) != len(levels[((h - 1) - i)])):
return False
return True
def is_slender(self, certificate=False):
'\n Return ``True`` if the poset is slender, and ``False`` otherwise.\n\n A finite graded poset is *slender* if every rank 2\n interval contains three or four elements, as defined in\n [Stan2009]_. (This notion of "slender" is unrelated to\n the eponymous notion defined by Graetzer and Kelly in\n "The Free `\\mathfrak{m}`-Lattice on the Poset `H`",\n Order 1 (1984), 47--65.)\n\n This function *does not* check if the poset is graded or not.\n Instead it just returns ``True`` if the poset does not contain\n 5 distinct elements `x`, `y`, `a`, `b` and `c` such that\n `x \\lessdot a,b,c \\lessdot y` where `\\lessdot` is the covering\n relation.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (a, b))`` so that the interval `[a, b]` has at\n least five elements. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: P = Poset(([1, 2, 3, 4], [[1, 2], [1, 3], [2, 4], [3, 4]]))\n sage: P.is_slender()\n True\n sage: P = Poset(([1,2,3,4,5],[[1,2],[1,3],[1,4],[2,5],[3,5],[4,5]]))\n sage: P.is_slender()\n False\n\n sage: # needs sage.groups\n sage: W = WeylGroup([\'A\', 2])\n sage: G = W.bruhat_poset()\n sage: G.is_slender()\n True\n sage: W = WeylGroup([\'A\', 3])\n sage: G = W.bruhat_poset()\n sage: G.is_slender()\n True\n\n sage: P = posets.IntegerPartitions(6) # needs sage.combinat\n sage: P.is_slender(certificate=True) # needs sage.combinat\n (False, ((6,), (3, 2, 1)))\n\n TESTS::\n\n sage: Poset().is_slender() # Test empty poset\n True\n\n Correct certificate (:trac:`22373`)::\n\n sage: P = Poset({0:[1,2,3],1:[4],2:[4],3:[4,5]})\n sage: P.is_slender(True)\n (False, (0, 4))\n '
for x in self:
d = {}
for y in self.upper_covers(x):
for c in self.upper_covers(y):
d[c] = (d.get(c, 0) + 1)
for (c, y) in d.items():
if (y >= 3):
if certificate:
return (False, (x, c))
return False
if certificate:
return (True, None)
return True
def is_sperner(self):
'\n Return ``True`` if the poset is Sperner, and ``False`` otherwise.\n\n The poset is expected to be ranked.\n\n A poset is Sperner, if no antichain is larger than the largest\n rank level (one of the sets of elements of the same rank) in\n the poset.\n\n See :wikipedia:`Sperner_property_of_a_partially_ordered_set`\n\n .. SEEALSO:: :meth:`width`, :meth:`dilworth_decomposition`\n\n EXAMPLES::\n\n sage: posets.SetPartitions(3).is_sperner() # needs sage.combinat\n True\n\n sage: P = Poset({0:[3,4,5],1:[5],2:[5]})\n sage: P.is_sperner()\n False\n\n TESTS::\n\n sage: posets.PentagonPoset().is_sperner()\n Traceback (most recent call last):\n ...\n ValueError: the poset is not ranked\n\n sage: P = Poset()\n sage: P.is_sperner()\n True\n '
if (not self.is_ranked()):
raise ValueError('the poset is not ranked')
if (not self.cardinality()):
return True
W = self.width()
N = max((len(level) for level in self._hasse_diagram.level_sets()))
return (W <= N)
def is_eulerian(self, k=None, certificate=False):
"\n Return ``True`` if the poset is Eulerian, and ``False`` otherwise.\n\n The poset is expected to be graded and bounded.\n\n A poset is Eulerian if every non-trivial interval has the same\n number of elements of even rank as of odd rank. A poset is\n `k`-eulerian if every non-trivial interval up to rank `k`\n is Eulerian.\n\n See :wikipedia:`Eulerian_poset`.\n\n INPUT:\n\n - ``k``, an integer -- only check if the poset is `k`-eulerian.\n If ``None`` (the default), check if the poset is Eulerian.\n - ``certificate``, a Boolean -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``True, None`` or\n ``False, (a, b)``, where the interval ``(a, b)`` is not\n Eulerian. If ``certificate=False`` return ``True`` or ``False``.\n\n EXAMPLES::\n\n sage: P = Poset({0: [1, 2, 3], 1: [4, 5], 2: [4, 6], 3: [5, 6],\n ....: 4: [7, 8], 5: [7, 8], 6: [7, 8], 7: [9], 8: [9]})\n sage: P.is_eulerian() # needs sage.libs.flint\n True\n sage: P = Poset({0: [1, 2, 3], 1: [4, 5, 6], 2: [4, 6], 3: [5,6],\n ....: 4: [7], 5:[7], 6:[7]})\n sage: P.is_eulerian() # needs sage.libs.flint\n False\n\n Canonical examples of Eulerian posets are the face lattices of\n convex polytopes::\n\n sage: P = polytopes.cube().face_lattice() # needs sage.geometry.polyhedron\n sage: P.is_eulerian() # needs sage.geometry.polyhedron sage.libs.flint\n True\n\n A poset that is 3- but not 4-eulerian::\n\n sage: P = Poset(DiGraph('MWW@_?W?@_?W??@??O@_?W?@_?W?@??O??')); P\n Finite poset containing 14 elements\n sage: P.is_eulerian(k=3) # needs sage.libs.flint\n True\n sage: P.is_eulerian(k=4) # needs sage.libs.flint\n False\n\n Getting an interval that is not Eulerian::\n\n sage: P = posets.DivisorLattice(12)\n sage: P.is_eulerian(certificate=True) # needs sage.libs.flint\n (False, (1, 4))\n\n TESTS::\n\n sage: Poset().is_eulerian()\n Traceback (most recent call last):\n ...\n ValueError: the poset is not bounded\n\n sage: Poset({1: []}).is_eulerian()\n True\n\n sage: posets.PentagonPoset().is_eulerian()\n Traceback (most recent call last):\n ...\n ValueError: the poset is not graded\n\n sage: posets.BooleanLattice(3).is_eulerian(k=123, certificate=True) # needs sage.libs.flint\n (True, None)\n "
if (k is not None):
try:
k = Integer(k)
except TypeError:
raise TypeError(f"parameter 'k' must be an integer, not {k}")
if (k <= 0):
raise ValueError(f"parameter 'k' must be positive, not {k}")
if (not self.is_bounded()):
raise ValueError('the poset is not bounded')
if (not self.is_ranked()):
raise ValueError('the poset is not graded')
n = self.cardinality()
if (n == 1):
return True
if ((k is None) and (not certificate) and ((n % 2) == 1)):
return False
H = self._hasse_diagram
M = H.moebius_function_matrix()
levels = H.level_sets()
height = len(levels)
if ((k is None) or (k > height)):
k = height
for rank_diff in range(2, (k + 1), 2):
for level in range((height - rank_diff)):
for i in levels[level]:
for j in levels[(level + rank_diff)]:
if (H.is_lequal(i, j) and (M[(i, j)] != 1)):
if certificate:
return (False, (self._vertex_to_element(i), self._vertex_to_element(j)))
return False
return ((True, None) if certificate else True)
def is_greedy(self, certificate=False):
'\n Return ``True`` if the poset is greedy, and ``False`` otherwise.\n\n A poset is *greedy* if every greedy linear extension\n has the same number of jumps.\n\n INPUT:\n\n - ``certificate`` -- (default: ``False``) whether to return\n a certificate\n\n OUTPUT:\n\n - If ``certificate=True`` return either ``(True, None)`` or\n ``(False, (A, B))`` where `A` and `B` are greedy linear extension\n so that `B` has more jumps. If ``certificate=False`` return\n ``True`` or ``False``.\n\n EXAMPLES:\n\n This is not a self-dual property::\n\n sage: W = Poset({1: [3, 4], 2: [4, 5]})\n sage: M = W.dual()\n sage: W.is_greedy()\n True\n sage: M.is_greedy()\n False\n\n Getting a certificate::\n\n sage: N = Poset({1: [3], 2: [3, 4]})\n sage: N.is_greedy(certificate=True)\n (False, ([1, 2, 4, 3], [2, 4, 1, 3]))\n\n TESTS::\n\n sage: Poset().is_greedy()\n True\n sage: posets.AntichainPoset(3).is_greedy()\n True\n sage: posets.ChainPoset(3).is_greedy()\n True\n '
H = self._hasse_diagram
N1 = (H.order() - 1)
it = H.greedy_linear_extensions_iterator()
A = next(it)
A_jumps = sum((1 for i in range(N1) if H.has_edge(A[i], A[(i + 1)])))
for B in it:
B_jumps = sum((1 for i in range(N1) if H.has_edge(B[i], B[(i + 1)])))
if (A_jumps != B_jumps):
if certificate:
if (A_jumps > B_jumps):
(A, B) = (B, A)
return (False, (self.linear_extension([self[v] for v in A]), self.linear_extension([self[v] for v in B])))
return False
return ((True, None) if certificate else True)
def frank_network(self):
"\n Return Frank's network of the poset.\n\n This is defined in Section 8 of [BF1999]_.\n\n OUTPUT:\n\n A pair `(G, e)`, where `G` is Frank's network of `P` encoded as a\n :class:`DiGraph`, and `e` is the cost function on its edges encoded\n as a dictionary (indexed by these edges, which in turn are encoded\n as tuples of 2 vertices).\n\n .. NOTE::\n\n Frank's network of `P` is a certain directed graph with `2|P| + 2`\n vertices, defined in Section 8 of [BF1999]_. Its set of vertices\n consists of two vertices `(0, p)` and `(1, p)` for each element\n `p` of `P`, as well as two vertices `(-1, 0)` and `(2, 0)`.\n (These notations are not the ones used in [BF1999]_; see the table\n below for their relation.) The edges are:\n\n - for each `p` in `P`, an edge from `(-1, 0)` to `(0, p)`;\n\n - for each `p` in `P`, an edge from `(1, p)` to `(2, 0)`;\n\n - for each `p` and `q` in `P` such that `p \\geq q`, an edge from\n `(0, p)` to `(1, q)`.\n\n We make this digraph into a network in the sense of flow theory as\n follows: The vertex `(-1, 0)` is considered as the source of this\n network, and the vertex `(2, 0)` as the sink. The cost function is\n defined to be `1` on the edge from `(0, p)` to `(1, p)` for each\n `p \\in P`, and to be `0` on every other edge. The capacity is `1`\n on each edge. Here is how to translate this notations into that\n used in [BF1999]_::\n\n our notations [BF1999]\n (-1, 0) s\n (0, p) x_p\n (1, p) y_p\n (2, 0) t\n a[e] a(e)\n\n EXAMPLES::\n\n sage: ps = [[16,12,14,-13],[[12,14],[14,-13],[12,16],[16,-13]]]\n sage: G, e = Poset(ps).frank_network()\n sage: G.edges(sort=True)\n [((-1, 0), (0, -13), None), ((-1, 0), (0, 12), None), ((-1, 0), (0, 14), None), ((-1, 0), (0, 16), None), ((0, -13), (1, -13), None), ((0, -13), (1, 12), None), ((0, -13), (1, 14), None), ((0, -13), (1, 16), None), ((0, 12), (1, 12), None), ((0, 14), (1, 12), None), ((0, 14), (1, 14), None), ((0, 16), (1, 12), None), ((0, 16), (1, 16), None), ((1, -13), (2, 0), None), ((1, 12), (2, 0), None), ((1, 14), (2, 0), None), ((1, 16), (2, 0), None)]\n sage: e\n {((-1, 0), (0, -13)): 0,\n ((-1, 0), (0, 12)): 0,\n ((-1, 0), (0, 14)): 0,\n ((-1, 0), (0, 16)): 0,\n ((0, -13), (1, -13)): 1,\n ((0, -13), (1, 12)): 0,\n ((0, -13), (1, 14)): 0,\n ((0, -13), (1, 16)): 0,\n ((0, 12), (1, 12)): 1,\n ((0, 14), (1, 12)): 0,\n ((0, 14), (1, 14)): 1,\n ((0, 16), (1, 12)): 0,\n ((0, 16), (1, 16)): 1,\n ((1, -13), (2, 0)): 0,\n ((1, 12), (2, 0)): 0,\n ((1, 14), (2, 0)): 0,\n ((1, 16), (2, 0)): 0}\n sage: qs = [[1,2,3,4,5,6,7,8,9],[[1,3],[3,4],[5,7],[1,9],[2,3]]]\n sage: Poset(qs).frank_network()\n (Digraph on 20 vertices,\n {((-1, 0), (0, 1)): 0,\n ((-1, 0), (0, 2)): 0,\n ((-1, 0), (0, 3)): 0,\n ((-1, 0), (0, 4)): 0,\n ((-1, 0), (0, 5)): 0,\n ((-1, 0), (0, 6)): 0,\n ((-1, 0), (0, 7)): 0,\n ((-1, 0), (0, 8)): 0,\n ((-1, 0), (0, 9)): 0,\n ((0, 1), (1, 1)): 1,\n ((0, 2), (1, 2)): 1,\n ((0, 3), (1, 1)): 0,\n ((0, 3), (1, 2)): 0,\n ((0, 3), (1, 3)): 1,\n ((0, 4), (1, 1)): 0,\n ((0, 4), (1, 2)): 0,\n ((0, 4), (1, 3)): 0,\n ((0, 4), (1, 4)): 1,\n ((0, 5), (1, 5)): 1,\n ((0, 6), (1, 6)): 1,\n ((0, 7), (1, 5)): 0,\n ((0, 7), (1, 7)): 1,\n ((0, 8), (1, 8)): 1,\n ((0, 9), (1, 1)): 0,\n ((0, 9), (1, 9)): 1,\n ((1, 1), (2, 0)): 0,\n ((1, 2), (2, 0)): 0,\n ((1, 3), (2, 0)): 0,\n ((1, 4), (2, 0)): 0,\n ((1, 5), (2, 0)): 0,\n ((1, 6), (2, 0)): 0,\n ((1, 7), (2, 0)): 0,\n ((1, 8), (2, 0)): 0,\n ((1, 9), (2, 0)): 0})\n\n AUTHOR:\n\n - Darij Grinberg (2013-05-09)\n "
P0 = [(0, i) for i in self]
pdict = {((- 1), 0): P0, (2, 0): []}
for i in self:
pdict[(0, i)] = [(1, j) for j in self if self.ge(i, j)]
pdict[(1, i)] = [(2, 0)]
G = DiGraph(pdict, format='dict_of_lists')
a = {e: 0 for e in G.edge_iterator(labels=False)}
for i in self:
a[((0, i), (1, i))] = 1
return (G, a)
@combinatorial_map(name='Greene-Kleitman partition')
def greene_shape(self):
'\n Return the Greene-Kleitman partition of ``self``.\n\n The Greene-Kleitman partition of a finite poset `P` is the partition\n `(c_1 - c_0, c_2 - c_1, c_3 - c_2, \\ldots)`, where `c_k` is the\n maximum cardinality of a union of `k` chains of `P`. Equivalently,\n this is the conjugate of the partition `(a_1 - a_0, a_2 - a_1, a_3 -\n a_2, \\ldots)`, where `a_k` is the maximum cardinality of a union of\n `k` antichains of `P`.\n\n See many sources, e. g., [BF1999]_, for proofs of this equivalence.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: P = Poset([[3,2,1], [[3,1],[2,1]]])\n sage: P.greene_shape()\n [2, 1]\n sage: P = Poset([[1,2,3,4], [[1,4],[2,4],[4,3]]])\n sage: P.greene_shape()\n [3, 1]\n sage: P = Poset([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],\n ....: [[1,4],[2,4],[4,3]]])\n sage: P.greene_shape()\n [3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n sage: P = Poset([[],[]])\n sage: P.greene_shape()\n []\n\n AUTHOR:\n\n - Darij Grinberg (2013-05-09)\n '
from sage.combinat.partition import Partition
(G, a) = self.frank_network()
n = len(self)
chron = _ford_fulkerson_chronicle(G, ((- 1), 0), (2, 0), a)
size = 0
ps = []
part = 0
(pold, vold) = (0, 0)
while (size != n):
(p, v) = next(chron)
if (v > vold):
size += p
if (part > 0):
ps.append(part)
elif (p > pold):
part += 1
(pold, vold) = (p, v)
ps.reverse()
return Partition(ps)
def p_partition_enumerator(self, tup, R, weights=None, check=False):
'\n Return a `P`-partition enumerator of ``self``.\n\n Given a total order `\\prec` on the elements of a finite poset `P`\n (the order of `P` and the total order `\\prec` can be unrelated; in\n particular, the latter does not have to extend the former), a\n `P`-partition enumerator is the quasisymmetric function\n `\\sum_f \\prod_{p \\in P} x_{f(p)}`, where the first sum is taken over\n all `P`-partitions `f`.\n\n A `P`-partition is a function `f : P \\to \\{1,2,3,...\\}` satisfying\n the following properties for any two elements `i` and `j` of `P`\n satisfying `i <_P j`:\n\n - if `i \\prec j` then `f(i) \\leq f(j)`,\n\n - if `j \\prec i` then `f(i) < f(j)`.\n\n The optional argument ``weights`` allows constructing a\n generalized ("weighted") version of the `P`-partition enumerator.\n Namely, ``weights`` should be a dictionary whose keys are the\n elements of ``P``.\n Then, the generalized `P`-partition enumerator corresponding to\n weights ``weights`` is `\\sum_f \\prod_{p \\in P} x_{f(p)}^{w(p)}`,\n where the sum is again over all `P`-partitions `f`. Here,\n `w(p)` is ``weights[p]``. The classical `P`-partition enumerator\n is the particular case obtained when all `p` satisfy `w(p) = 1`.\n\n In the language of [Grinb2016a]_, the generalized `P`-partition\n enumerator is the quasisymmetric function\n `\\Gamma\\left(\\mathbf{E}, w\\right)`, where `\\mathbf{E}` is the\n special double poset `(P, <_P, \\prec)`, and where\n `w` is the dictionary ``weights`` (regarded as a function from\n `P` to the positive integers).\n\n INPUT:\n\n - ``tup`` -- the tuple containing all elements of `P` (each of\n them exactly once), in the order dictated by the total order\n `\\prec`\n\n - ``R`` -- a commutative ring\n\n - ``weights`` -- (optional) a dictionary of positive integers,\n indexed by elements of `P`; any missing item will be understood\n as `1`\n\n OUTPUT:\n\n The `P`-partition enumerator of ``self`` according to ``tup`` in the\n algebra `QSym` of quasisymmetric functions over the base ring `R`.\n\n EXAMPLES::\n\n sage: P = Poset([[1,2,3,4],[[1,4],[2,4],[4,3]]])\n sage: FP = P.p_partition_enumerator((3,1,2,4), QQ, check=True); FP # needs sage.combinat\n 2*M[1, 1, 1, 1] + 2*M[1, 2, 1] + M[2, 1, 1] + M[3, 1]\n\n sage: expansion = FP.expand(5) # needs sage.combinat\n sage: xs = expansion.parent().gens() # needs sage.combinat\n sage: expansion == sum(xs[a]*xs[b]*xs[c]*xs[d] # needs sage.combinat\n ....: for a in range(5) for b in range(5)\n ....: for c in range(5) for d in range(5)\n ....: if a <= b and c <= b and b < d)\n True\n\n sage: P = Poset([[],[]])\n sage: FP = P.p_partition_enumerator((), QQ, check=True); FP # needs sage.combinat\n M[]\n\n With the ``weights`` parameter::\n\n sage: P = Poset([[1,2,3,4],[[1,4],[2,4],[4,3]]])\n sage: FP = P.p_partition_enumerator((3,1,2,4), QQ, # needs sage.combinat\n ....: weights={1: 1, 2: 2, 3: 1, 4: 1}, check=True); FP\n M[1, 2, 1, 1] + M[1, 3, 1] + M[2, 1, 1, 1] + M[2, 2, 1] + M[3, 1, 1] + M[4, 1]\n sage: FP = P.p_partition_enumerator((3,1,2,4), QQ, # needs sage.combinat\n ....: weights={2: 2}, check=True); FP\n M[1, 2, 1, 1] + M[1, 3, 1] + M[2, 1, 1, 1] + M[2, 2, 1] + M[3, 1, 1] + M[4, 1]\n\n sage: P = Poset([[\'a\',\'b\',\'c\'], [[\'a\',\'b\'], [\'a\',\'c\']]])\n sage: FP = P.p_partition_enumerator((\'b\',\'c\',\'a\'), QQ, # needs sage.combinat\n ....: weights={\'a\': 3, \'b\': 5, \'c\': 7}, check=True); FP\n M[3, 5, 7] + M[3, 7, 5] + M[3, 12]\n\n sage: P = Poset([[\'a\',\'b\',\'c\'], [[\'a\',\'c\'], [\'b\',\'c\']]])\n sage: FP = P.p_partition_enumerator((\'b\',\'c\',\'a\'), QQ, # needs sage.combinat\n ....: weights={\'a\': 3, \'b\': 5, \'c\': 7}, check=True); FP\n M[3, 5, 7] + M[3, 12] + M[5, 3, 7] + M[8, 7]\n sage: FP = P.p_partition_enumerator((\'a\',\'b\',\'c\'), QQ, # needs sage.combinat\n ....: weights={\'a\': 3, \'b\': 5, \'c\': 7}, check=True); FP\n M[3, 5, 7] + M[3, 12] + M[5, 3, 7] + M[5, 10] + M[8, 7] + M[15]\n '
if check:
if (sorted(self.list()) != sorted(tup)):
raise ValueError('the elements of tup are not those of P')
from sage.combinat.composition import Composition
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
QR = QuasiSymmetricFunctions(R)
n = len(tup)
res = QR.zero()
tupdict = dict(zip(tup, range(n)))
if (weights is None):
F = QR.Fundamental()
for lin in self.linear_extensions(facade=True):
descents = [(i + 1) for i in range((n - 1)) if (tupdict[lin[i]] > tupdict[lin[(i + 1)]])]
res += F(Composition(from_subset=(descents, n)))
return res
for lin in self.linear_extensions(facade=True):
M = QR.Monomial()
lin_weights = Composition([weights.get(lin[i], 1) for i in range(n)])
descents = [(i + 1) for i in range((n - 1)) if (tupdict[lin[i]] > tupdict[lin[(i + 1)]])]
d_c = Composition(from_subset=(descents, n))
for comp in d_c.finer():
res += M[lin_weights.fatten(comp)]
return res
def cuts(self):
'\n Return the list of cuts of the poset ``self``.\n\n A cut is a subset `A` of ``self`` such that the set of lower\n bounds of the set of upper bounds of `A` is exactly `A`.\n\n The cuts are computed here using the maximal independent sets in the\n auxiliary graph defined as `P \\times [0,1]` with an edge\n from `(x, 0)` to `(y, 1)` if\n and only if `x \\not\\geq_P y`. See the end of section 4 in [JRJ94]_.\n\n EXAMPLES::\n\n sage: P = posets.AntichainPoset(3)\n sage: Pc = P.cuts()\n sage: Pc # random\n [frozenset({0}),\n frozenset(),\n frozenset({0, 1, 2}),\n frozenset({2}),\n frozenset({1})]\n sage: sorted(list(c) for c in Pc)\n [[], [0], [0, 1, 2], [1], [2]]\n\n .. SEEALSO::\n\n :meth:`completion_by_cuts`\n '
from sage.graphs.graph import Graph
from sage.graphs.independent_sets import IndependentSets
auxg = Graph({(u, 0): [(v, 1) for v in self if (not self.ge(u, v))] for u in self}, format='dict_of_lists')
auxg.add_vertices([(v, 1) for v in self])
return [frozenset([xa for (xa, xb) in c if (xb == 0)]) for c in IndependentSets(auxg, maximal=True)]
def completion_by_cuts(self):
'\n Return the completion by cuts of ``self``.\n\n This is the smallest lattice containing the poset. This is also\n called the Dedekind-MacNeille completion.\n\n See the :wikipedia:`Dedekind-MacNeille completion`.\n\n OUTPUT:\n\n - a finite lattice\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.completion_by_cuts().is_isomorphic(P)\n True\n\n sage: Y = Poset({1: [2], 2: [3, 4]})\n sage: trafficsign = LatticePoset({1: [2], 2: [3, 4], 3: [5], 4: [5]})\n sage: L = Y.completion_by_cuts()\n sage: L.is_isomorphic(trafficsign)\n True\n\n sage: P = posets.SymmetricGroupBruhatOrderPoset(3)\n sage: Q = P.completion_by_cuts(); Q\n Finite lattice containing 7 elements\n\n .. SEEALSO::\n\n :meth:`cuts`,\n :meth:`~sage.categories.finite_lattice_posets.FiniteLatticePosets.ParentMethods.irreducibles_poset`\n\n TESTS::\n\n sage: Poset().completion_by_cuts()\n Finite lattice containing 0 elements\n '
from sage.combinat.posets.lattices import LatticePoset
if (self.cardinality() == 0):
return LatticePoset({})
return LatticePoset((self.cuts(), (lambda a, b: a.issuperset(b))))
def incidence_algebra(self, R, prefix='I'):
'\n Return the incidence algebra of ``self`` over ``R``.\n\n OUTPUT:\n\n An instance of :class:`sage.combinat.posets.incidence_algebras.IncidenceAlgebra`.\n\n EXAMPLES::\n\n sage: P = posets.BooleanLattice(4)\n sage: P.incidence_algebra(QQ)\n Incidence algebra of Finite lattice containing 16 elements\n over Rational Field\n '
from sage.combinat.posets.incidence_algebras import IncidenceAlgebra
return IncidenceAlgebra(R, self, prefix)
@cached_method(key=(lambda self, x, y, l: (x, y)))
def _kl_poly(self, x=None, y=None, canonical_labels=None):
"\n Cached Kazhdan-Lusztig polynomial of ``self`` for generic `q`.\n\n EXAMPLES::\n\n sage: L = posets.SymmetricGroupWeakOrderPoset(4)\n sage: L._kl_poly()\n 1\n sage: x = '2314'\n sage: y = '3421'\n sage: L._kl_poly(x, y)\n -q + 1\n\n .. SEEALSO::\n\n :meth:`kazhdan_lusztig_polynomial`\n\n AUTHORS:\n\n - Travis Scrimshaw (27-12-2014)\n "
R = PolynomialRing(ZZ, 'q')
q = R.gen(0)
if (self.cardinality() == 0):
return q.parent().zero()
if (not self.rank()):
return q.parent().one()
if (canonical_labels is None):
canonical_labels = ((x is None) and (y is None))
if ((x is not None) or (y is not None)):
if (x == y):
return q.parent().one()
if (x is None):
x = self.minimal_elements()[0]
if (y is None):
y = self.maximal_elements()[0]
if (not self.le(x, y)):
return q.parent().zero()
P = self.subposet(self.interval(x, y))
return P.kazhdan_lusztig_polynomial(q=q, canonical_labels=canonical_labels)
min_elt = self.minimal_elements()[0]
if canonical_labels:
def sublat(P):
return self.subposet(P).canonical_label()
else:
def sublat(P):
return self.subposet(P)
poly = (- sum(((sublat(self.order_ideal([x])).characteristic_polynomial() * sublat(self.order_filter([x])).kazhdan_lusztig_polynomial()) for x in self if (x != min_elt))))
tr = ((self.rank() // 2) + 1)
ret = poly.truncate(tr)
return ret(q=q)
def kazhdan_lusztig_polynomial(self, x=None, y=None, q=None, canonical_labels=None):
"\n Return the Kazhdan-Lusztig polynomial `P_{x,y}(q)` of the poset.\n\n The poset is expected to be ranked.\n\n We follow the definition given in [EPW14]_. Let `G` denote a\n graded poset with unique minimal and maximal elements and `\\chi_G`\n denote the characteristic polynomial of `G`. Let `I_x` and `F^x`\n denote the principal order ideal and filter of `x` respectively.\n Define the *Kazhdan-Lusztig polynomial* of `G` as the unique\n polynomial `P_G(q)` satisfying the following:\n\n 1. If `\\operatorname{rank} G = 0`, then `P_G(q) = 1`.\n 2. If `\\operatorname{rank} G > 0`, then `\\deg P_G(q) <\n \\frac{1}{2} \\operatorname{rank} G`.\n 3. We have\n\n .. MATH::\n\n q^{\\operatorname{rank} G} P_G(q^{-1})\n = \\sum_{x \\in G} \\chi_{I_x}(q) P_{F^x}(q).\n\n We then extend this to `P_{x,y}(q)` by considering the subposet\n corresponding to the (closed) interval `[x, y]`. We also\n define `P_{\\emptyset}(q) = 0` (so if `x \\not\\leq y`,\n then `P_{x,y}(q) = 0`).\n\n INPUT:\n\n - ``q`` -- (default: `q \\in \\ZZ[q]`) the indeterminate `q`\n - ``x`` -- (default: the minimal element) the element `x`\n - ``y`` -- (default: the maximal element) the element `y`\n - ``canonical_labels`` -- (optional) for subposets, use the\n canonical labeling (this can limit recursive calls for posets\n with large amounts of symmetry, but producing the labeling\n takes time); if not specified, this is ``True`` if ``x``\n and ``y`` are both not specified and ``False`` otherwise\n\n EXAMPLES::\n\n sage: L = posets.BooleanLattice(3)\n sage: L.kazhdan_lusztig_polynomial()\n 1\n\n ::\n\n sage: L = posets.SymmetricGroupWeakOrderPoset(4)\n sage: L.kazhdan_lusztig_polynomial()\n 1\n sage: x = '2314'\n sage: y = '3421'\n sage: L.kazhdan_lusztig_polynomial(x, y)\n -q + 1\n sage: L.kazhdan_lusztig_polynomial(x, y, var('t')) # needs sage.symbolic\n -t + 1\n\n AUTHORS:\n\n - Travis Scrimshaw (27-12-2014)\n "
if (not self.is_ranked()):
raise ValueError('the poset is not ranked')
if (q is None):
q = PolynomialRing(ZZ, 'q').gen(0)
poly = self._kl_poly(x, y, canonical_labels)
return poly(q=q)
def is_induced_subposet(self, other):
'\n Return ``True`` if the poset is an induced subposet of ``other``, and\n ``False`` otherwise.\n\n A poset `P` is an induced subposet of `Q` if every element\n of `P` is an element of `Q`, and `x \\le_P y` iff `x \\le_Q y`.\n Note that "induced" here has somewhat different meaning compared\n to that of graphs.\n\n INPUT:\n\n - ``other``, a poset.\n\n .. NOTE::\n\n This method does not check whether the poset is a\n *isomorphic* (i.e., up to relabeling) subposet of ``other``,\n but only if ``other`` directly contains the poset as an\n induced subposet. For isomorphic subposets see\n :meth:`has_isomorphic_subposet`.\n\n EXAMPLES::\n\n sage: P = Poset({1:[2, 3]})\n sage: Q = Poset({1:[2, 4], 2:[3]})\n sage: P.is_induced_subposet(Q)\n False\n sage: R = Poset({0:[1], 1:[3, 4], 3:[5], 4:[2]})\n sage: P.is_induced_subposet(R)\n True\n\n TESTS::\n\n sage: P = Poset({2:[1]})\n sage: Poset().is_induced_subposet(P)\n True\n sage: Poset().is_induced_subposet(Poset())\n True\n sage: P.is_induced_subposet(Poset())\n False\n\n Bad input::\n\n sage: Poset().is_induced_subposet(\'junk\')\n Traceback (most recent call last):\n ...\n AttributeError: \'str\' object has no attribute \'subposet\'...\n '
if ((not self._is_facade) or (isinstance(other, FinitePoset) and (not other._is_facade))):
raise TypeError('the function is not defined on non-facade posets')
return (set(self).issubset(set(other)) and (other.subposet(self).hasse_diagram() == self.hasse_diagram()))
def _libgap_(self):
'\n Conversion to gap.\n\n This uses the QPA package (https://folk.ntnu.no/oyvinso/QPA/).\n\n EXAMPLES::\n\n sage: P = posets.TamariLattice(3)\n sage: libgap(P) # optional - gap_package_qpa\n <A poset on 5 points>\n sage: A = libgap(GF(2)).PosetAlgebra(P); A # optional - gap_package_qpa\n <GF(2)[<quiver with 5 vertices and 5 arrows>]/<two-sided ideal in <GF(2)[<quiver with 5 vertices and 5 arrows>]>, (1 generator)>>\n sage: A.Dimension() # optional - gap_package_qpa\n 13\n '
from sage.libs.gap.libgap import libgap
libgap.LoadPackage('QPA')
L = list(self)
g = libgap.Poset(L, [self.principal_order_filter(x) for x in L])
return g
def _macaulay2_init_(self, macaulay2=None):
'\n Conversion to Macaulay2.\n\n This uses the ``Posets`` package.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P._macaulay2_init_()\n \'needsPackage "Posets";poset({0,1,2,3,4},{{0,1},{0,2},{1,4},{2,3},{3,4}})\'\n\n sage: P = Poset({1:[2],2:[]})\n sage: macaulay2(\'needsPackage "Posets"\') # optional - macaulay2\n Posets\n sage: macaulay2(P) # optional - macaulay2\n Relation Matrix: | 1 1 |\n | 0 1 |\n '
H = self._hasse_diagram
txt = 'needsPackage "Posets";'
txt += ('poset({%s},{' % ','.join((str(x) for x in H)))
txt += ','.join((f'{{{str(x)},{str(y)}}}' for (x, y) in H.cover_relations_iterator()))
return (txt + '})')
|
class FinitePosets_n(UniqueRepresentation, Parent):
'\n The finite enumerated set of all posets on `n` elements, up to an isomorphism.\n\n EXAMPLES::\n\n sage: P = Posets(3)\n sage: P.cardinality()\n 5\n sage: for p in P: print(p.cover_relations())\n []\n [[1, 2]]\n [[0, 1], [0, 2]]\n [[0, 1], [1, 2]]\n [[1, 2], [0, 2]]\n '
def __init__(self, n):
"\n EXAMPLES::\n\n sage: P = Posets(3); P\n Posets containing 3 elements\n sage: P.category()\n Category of finite enumerated sets\n sage: P.__class__\n <class 'sage.combinat.posets.posets.FinitePosets_n_with_category'>\n sage: TestSuite(P).run()\n "
Parent.__init__(self, category=FiniteEnumeratedSets())
self._n = n
def _repr_(self):
"\n EXAMPLES::\n\n sage: P = Posets(3)\n sage: P._repr_()\n 'Posets containing 3 elements'\n "
return ('Posets containing %s elements' % self._n)
def __contains__(self, P):
'\n EXAMPLES::\n\n sage: posets.PentagonPoset() in Posets(5)\n True\n sage: posets.PentagonPoset() in Posets(3)\n False\n sage: 1 in Posets(3)\n False\n '
return ((P in FinitePosets()) and (P.cardinality() == self._n))
def __iter__(self):
'\n Return an iterator of representatives of the isomorphism classes\n of finite posets of a given size.\n\n .. NOTE::\n\n This uses the DiGraph iterator as a backend to construct\n transitively-reduced, acyclic digraphs.\n\n EXAMPLES::\n\n sage: P = Posets(2)\n sage: list(P)\n [Finite poset containing 2 elements, Finite poset containing 2 elements]\n '
from sage.graphs.digraph_generators import DiGraphGenerators
for dig in DiGraphGenerators()(self._n, is_poset):
label_dict = dict(zip(dig.topological_sort(), range(dig.order())))
(yield FinitePoset(dig.relabel(label_dict, inplace=False)))
def cardinality(self, from_iterator=False):
'\n Return the cardinality of this object.\n\n .. note::\n\n By default, this returns pre-computed values obtained from\n the On-Line Encyclopedia of Integer Sequences (:oeis:`A000112`).\n To override this, pass the argument ``from_iterator=True``.\n\n EXAMPLES::\n\n sage: P = Posets(3)\n sage: P.cardinality()\n 5\n sage: P.cardinality(from_iterator=True)\n 5\n '
known_values = [1, 1, 2, 5, 16, 63, 318, 2045, 16999, 183231, 2567284, 46749427, 1104891746, 33823827452, 1338193159771, 68275077901156, 4483130665195087]
if ((not from_iterator) and (self._n < len(known_values))):
return Integer(known_values[self._n])
return super().cardinality()
|
def is_poset(dig):
'\n Return ``True`` if a directed graph is acyclic and transitively\n reduced, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.posets import is_poset\n sage: dig = DiGraph({0:[2, 3], 1:[3, 4, 5], 2:[5], 3:[5], 4:[5]})\n sage: is_poset(dig)\n False\n sage: is_poset(dig.transitive_reduction())\n True\n '
return (dig.is_directed_acyclic() and dig.is_transitively_reduced())
|
def _ford_fulkerson_chronicle(G, s, t, a):
"\n Iterate through the Ford-Fulkerson algorithm for an acyclic directed\n graph with all edge capacities equal to `1`. This is an auxiliary algorithm\n for use by the :meth:`FinitePoset.greene_shape` method of finite posets,\n and is lacking some of the functionality that a general Ford-Fulkerson\n algorithm implementation should have.\n\n INPUT:\n\n - ``G`` -- an acyclic directed graph\n\n - ``s`` -- a vertex of `G` as the source\n\n - ``t`` -- a vertex of `G` as the sink\n\n - ``a`` -- a cost function (on the set of edges of ``G``) encoded as\n a dictionary. The keys of this dictionary are encoded as pairs\n of vertices.\n\n OUTPUT:\n\n An iterator which iterates through the values `(p, v)` during the\n application of the Ford-Fulkerson algorithm applied to the graph\n `G` with source `s`, sink `t`, cost function `a` and capacity `1`\n on each edge. Here, `p` denotes the value of the potential, and `v`\n denotes the value of the flow at every moment during the execution\n of the algorithm. The algorithm starts at `(p, v) = (0, 0)`.\n Every time ``next()`` is called, the iterator performs one step of\n the algorithm (incrementing either `p` or `v`) and yields the\n resulting pair `(p, v)`. Note that `(0, 0)` is never yielded.\n The iterator goes on for eternity, since the stopping condition\n is not implemented. This is OK for use in the ``greene_partition``\n function, since that one knows when to stop.\n\n The notation used here is that of Section 7 of [BF1999]_.\n\n .. WARNING::\n\n This method is tailor-made for its use in the\n :meth:`FinitePoset.greene_shape()` method of a finite poset. It is not\n very useful in general. First of all, as said above, the iterator\n does not know when to halt. Second, `G` needs to be acyclic for it\n to correctly work. This must be amended if this method is ever to be\n used outside the Greene-Kleitman partition construction. For the\n Greene-Kleitman partition, this is a non-issue since Frank's network\n is always acyclic.\n\n EXAMPLES::\n\n sage: from sage.combinat.posets.posets import _ford_fulkerson_chronicle\n sage: G = DiGraph({1: [3,6,7], 2: [4], 3: [7], 4: [], 6: [7,8], 7: [9], 8: [9,12], 9: [], 10: [], 12: []})\n sage: s = 1\n sage: t = 9\n sage: (1, 6, None) in G.edges(sort=False)\n True\n sage: (1, 6) in G.edges(sort=False)\n False\n sage: a = {(1, 6): 4, (2, 4): 0, (1, 3): 4, (1, 7): 1, (3, 7): 6, (7, 9): 1, (6, 7): 3, (6, 8): 1, (8, 9): 0, (8, 12): 2}\n sage: ffc = _ford_fulkerson_chronicle(G, s, t, a)\n sage: next(ffc)\n (1, 0)\n sage: next(ffc)\n (2, 0)\n sage: next(ffc)\n (2, 1)\n sage: next(ffc)\n (3, 1)\n sage: next(ffc)\n (4, 1)\n sage: next(ffc)\n (5, 1)\n sage: next(ffc)\n (5, 2)\n sage: next(ffc)\n (6, 2)\n sage: next(ffc)\n (7, 2)\n sage: next(ffc)\n (8, 2)\n sage: next(ffc)\n (9, 2)\n sage: next(ffc)\n (10, 2)\n sage: next(ffc)\n (11, 2)\n "
pi = {v: 0 for v in G}
p = 0
f = {edge: 0 for edge in G.edge_iterator(labels=False)}
val = 0
capacity = {edge: 1 for edge in G.edge_iterator(labels=False)}
while True:
Gprime = DiGraph()
Gprime.add_vertices(G)
for (u, v) in G.edge_iterator(labels=False):
if ((pi[v] - pi[u]) == a[(u, v)]):
if (f[(u, v)] < capacity[(u, v)]):
Gprime.add_edge(u, v)
elif (f[(u, v)] > 0):
Gprime.add_edge(v, u)
X = set(Gprime.depth_first_search(s))
if (t in X):
shortest_path = Gprime.shortest_path(s, t, by_weight=False)
shortest_path_in_edges = zip(shortest_path[:(- 1)], shortest_path[1:])
for (u, v) in shortest_path_in_edges:
if (v in G.neighbor_out_iterator(u)):
f[(u, v)] += 1
else:
f[(v, u)] -= 1
val += 1
else:
for v in G:
if (v not in X):
pi[v] += 1
p += 1
(yield (p, val))
|
def q_int(n, q=None):
"\n Return the `q`-analogue of the integer `n`.\n\n The `q`-analogue of the integer `n` is given by\n\n .. MATH::\n\n [n]_q = \\begin{cases}\n 1 + q + \\cdots + q^{n-1}, & \\text{if } n \\geq 0, \\\\\n -q^{-n} [-n]_q, & \\text{if } n \\leq 0.\n \\end{cases}\n\n Consequently, if `q = 1` then `[n]_1 = n` and if `q \\neq 1` then\n `[n]_q = (q^n-1)/(q-1)`.\n\n If the argument `q` is not specified then it defaults to the generator `q`\n of the univariate polynomial ring over the integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_int\n sage: q_int(3)\n q^2 + q + 1\n sage: q_int(-3)\n (-q^2 - q - 1)/q^3\n sage: p = ZZ['p'].0\n sage: q_int(3,p)\n p^2 + p + 1\n sage: q_int(3/2)\n Traceback (most recent call last):\n ...\n ValueError: 3/2 must be an integer\n\n TESTS:\n\n We check that :trac:`15805` is fixed::\n\n sage: q_int(0).parent()\n Univariate Polynomial Ring in q over Integer Ring\n\n We check that :trac:`25715` is fixed::\n\n sage: q_int(0, 3r)\n 0\n "
if (n not in ZZ):
raise ValueError(f'{n} must be an integer')
if (q is None):
q = ZZ['q'].gen()
if (n == 0):
return parent(q)(0)
if (n > 0):
return sum(((q ** i) for i in range(n)))
return ((- (q ** n)) * sum(((q ** i) for i in range((- n)))))
|
def q_factorial(n, q=None):
"\n Return the `q`-analogue of the factorial `n!`.\n\n This is the product\n\n .. MATH::\n\n [1]_q [2]_q \\cdots [n]_q\n = 1 \\cdot (1+q) \\cdot (1+q+q^2) \\cdots (1+q+q^2+\\cdots+q^{n-1}) .\n\n If `q` is unspecified, then this function defaults to\n using the generator `q` for a univariate polynomial\n ring over the integers.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_factorial\n sage: q_factorial(3)\n q^3 + 2*q^2 + 2*q + 1\n sage: p = ZZ['p'].0\n sage: q_factorial(3, p)\n p^3 + 2*p^2 + 2*p + 1\n\n The `q`-analogue of `n!` is only defined for `n` a non-negative\n integer (:trac:`11411`)::\n\n sage: q_factorial(-2)\n Traceback (most recent call last):\n ...\n ValueError: argument (-2) must be a nonnegative integer\n\n TESTS::\n\n sage: q_factorial(0).parent()\n Univariate Polynomial Ring in q over Integer Ring\n "
if (n in ZZ):
if (n == 0):
return q_int(1, q)
elif (n >= 1):
return prod((q_int(i, q) for i in range(1, (n + 1))))
raise ValueError(('argument (%s) must be a nonnegative integer' % n))
|
def q_binomial(n, k, q=None, algorithm='auto'):
'\n Return the `q`-binomial coefficient.\n\n This is also known as the Gaussian binomial coefficient, and is defined by\n\n .. MATH::\n\n \\binom{n}{k}_q = \\frac{(1-q^n)(1-q^{n-1}) \\cdots (1-q^{n-k+1})}\n {(1-q)(1-q^2)\\cdots (1-q^k)}.\n\n See :wikipedia:`Gaussian_binomial_coefficient`.\n\n If `q` is unspecified, then the variable is the generator `q` for\n a univariate polynomial ring over the integers.\n\n INPUT:\n\n - ``n, k`` -- the values `n` and `k` defined above\n\n - ``q`` -- (default: ``None``) the variable `q`; if ``None``, then use a\n default variable in `\\ZZ[q]`\n\n - ``algorithm`` -- (default: ``\'auto\'``) the algorithm to use and can be\n one of the following:\n\n - ``\'auto\'`` -- automatically choose the algorithm; see the algorithm\n section below\n - ``\'naive\'`` -- use the naive algorithm\n - ``\'cyclotomic\'`` -- use cyclotomic algorithm\n\n ALGORITHM:\n\n The naive algorithm uses the product formula. The cyclotomic\n algorithm uses a product of cyclotomic polynomials\n (cf. [CH2006]_).\n\n When the algorithm is set to ``\'auto\'``, we choose according to\n the following rules:\n\n - If ``q`` is a polynomial:\n\n When ``n`` is small or ``k`` is small with respect to ``n``, one\n uses the naive algorithm. When both ``n`` and ``k`` are big, one\n uses the cyclotomic algorithm.\n\n - If ``q`` is in the symbolic ring (or a symbolic subring), one uses\n the cyclotomic algorithm.\n\n - Otherwise one uses the naive algorithm, unless ``q`` is a root of\n unity, then one uses the cyclotomic algorithm.\n\n EXAMPLES:\n\n By default, the variable is the generator of `\\ZZ[q]`::\n\n sage: from sage.combinat.q_analogues import q_binomial\n sage: g = q_binomial(5,1) ; g\n q^4 + q^3 + q^2 + q + 1\n sage: g.parent()\n Univariate Polynomial Ring in q over Integer Ring\n\n The `q`-binomial coefficient vanishes unless `0 \\leq k \\leq n`::\n\n sage: q_binomial(4,5)\n 0\n sage: q_binomial(5,-1)\n 0\n\n Other variables can be used, given as third parameter::\n\n sage: p = ZZ[\'p\'].gen()\n sage: q_binomial(4,2,p)\n p^4 + p^3 + 2*p^2 + p + 1\n\n The third parameter can also be arbitrary values::\n\n sage: q_binomial(5,1,2) == g.subs(q=2)\n True\n sage: q_binomial(5,1,1)\n 5\n sage: q_binomial(4,2,-1)\n 2\n sage: q_binomial(4,2,3.14)\n 152.030056160000\n sage: R = GF((5, 2), \'t\')\n sage: t = R.gen(0)\n sage: q_binomial(6, 3, t)\n 2*t + 3\n\n We can also do this for more complicated objects such as matrices or\n symmetric functions::\n\n sage: q_binomial(4,2,matrix([[2,1],[-1,3]]))\n [ -6 84]\n [-84 78]\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.schur()\n sage: q_binomial(4,1, s[2]+s[1])\n s[] + s[1] + s[1, 1] + s[1, 1, 1] + 2*s[2] + 4*s[2, 1] + 3*s[2, 1, 1]\n + 4*s[2, 2] + 3*s[2, 2, 1] + s[2, 2, 2] + 3*s[3] + 7*s[3, 1] + 3*s[3, 1, 1]\n + 6*s[3, 2] + 2*s[3, 2, 1] + s[3, 3] + 4*s[4] + 6*s[4, 1] + s[4, 1, 1]\n + 3*s[4, 2] + 3*s[5] + 2*s[5, 1] + s[6]\n\n TESTS:\n\n One checks that the first two arguments are integers::\n\n sage: q_binomial(1/2,1)\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n\n One checks that `n` is nonnegative::\n\n sage: q_binomial(-4,1)\n Traceback (most recent call last):\n ...\n ValueError: n must be nonnegative\n\n This also works for variables in the symbolic ring::\n\n sage: z = var(\'z\') # needs sage.symbolic\n sage: factor(q_binomial(4, 2, z)) # needs sage.symbolic\n (z^2 + z + 1)*(z^2 + 1)\n\n This also works for complex roots of unity::\n\n sage: q_binomial(10, 4, QQbar(I)) # needs sage.rings.number_field\n 2\n\n Note that the symbolic computation works (see :trac:`14982`)::\n\n sage: q_binomial(10, 4, I) # needs sage.rings.number_field\n 2\n\n Check that the algorithm does not matter::\n\n sage: q_binomial(6, 3, algorithm=\'naive\') == q_binomial(6, 3, algorithm=\'cyclotomic\')\n True\n\n One more test::\n\n sage: q_binomial(4, 2, Zmod(6)(2), algorithm=\'naive\')\n 5\n\n Check that it works with Python integers::\n\n sage: r = q_binomial(3r, 2r, 1r); r\n 3\n sage: type(r)\n <class \'int\'>\n\n Check that arbitrary polynomials work::\n\n sage: R.<x> = ZZ[]\n sage: q_binomial(2, 1, x^2 - 1, algorithm="naive")\n x^2\n sage: q_binomial(2, 1, x^2 - 1, algorithm="cyclotomic")\n x^2\n\n Check that the parent is always the parent of ``q``::\n\n sage: R.<q> = CyclotomicField(3)\n sage: for algo in ["naive", "cyclotomic"]:\n ....: for n in range(4):\n ....: for k in range(4):\n ....: a = q_binomial(n, k, q, algorithm=algo)\n ....: assert a.parent() is R\n\n ::\n\n sage: q_binomial(2, 1, x^2 - 1, algorithm="quantum")\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm \'quantum\'\n\n REFERENCES:\n\n .. [CH2006] William Y.C. Chen and Qing-Hu Hou, *Factors of the Gaussian\n coefficients*, Discrete Mathematics 306 (2006), 1446-1449.\n :doi:`10.1016/j.disc.2006.03.031`\n\n AUTHORS:\n\n - Frédéric Chapoton, David Joyner and William Stein\n '
n = ZZ(n)
k = ZZ(k)
if (n < 0):
raise ValueError('n must be nonnegative')
k = min((n - k), k)
if (q is None):
from sage.rings.polynomial.polynomial_ring import polygen
q = polygen(ZZ, name='q')
is_polynomial = True
else:
from sage.rings.polynomial.polynomial_element import Polynomial
is_polynomial = isinstance(q, Polynomial)
R = parent(q)
zero = R(0)
one = R(1)
if (k <= 0):
return (one if (k == 0) else zero)
if (algorithm == 'auto'):
if ((n <= 70) or (k <= (n // 4))):
algorithm = 'naive'
elif is_polynomial:
algorithm = 'cyclotomic'
else:
import sage.rings.abc
if isinstance(R, sage.rings.abc.SymbolicRing):
algorithm = 'cyclotomic'
else:
algorithm = 'naive'
while (algorithm == 'naive'):
denom = prod(((one - (q ** i)) for i in range(1, (k + 1))))
if (not denom):
algorithm = 'cyclotomic'
break
else:
num = prod(((one - (q ** i)) for i in range(((n - k) + 1), (n + 1))))
try:
try:
return (num // denom)
except TypeError:
return (num / denom)
except (TypeError, ZeroDivisionError):
return q_binomial(n, k)(q)
if (algorithm == 'cyclotomic'):
from sage.rings.polynomial.cyclotomic import cyclotomic_value
return prod((cyclotomic_value(d, q) for d in range(2, (n + 1)) if ((n // d) != ((k // d) + ((n - k) // d)))))
else:
raise ValueError('unknown algorithm {!r}'.format(algorithm))
|
def gaussian_binomial(n, k, q=None, algorithm='auto'):
'\n This is an alias of :func:`q_binomial`.\n\n See :func:`q_binomial` for the full documentation.\n\n EXAMPLES::\n\n sage: gaussian_binomial(4,2)\n q^4 + q^3 + 2*q^2 + q + 1\n '
return q_binomial(n, k, q, algorithm)
|
def q_multinomial(seq, q=None, binomial_algorithm='auto'):
"\n Return the `q`-multinomial coefficient.\n\n This is also known as the Gaussian multinomial coefficient, and is\n defined by\n\n .. MATH::\n\n \\binom{n}{k_1, k_2, \\ldots, k_m}_q = \\frac{[n]_q!}\n {[k_1]_q! [k_2]_q! \\cdots [k_m]_q!}\n\n where `n = k_1 + k_2 + \\cdots + k_m`.\n\n If `q` is unspecified, then the variable is the generator `q` for\n a univariate polynomial ring over the integers.\n\n INPUT:\n\n - ``seq`` -- an iterable of the values `k_1` to `k_m` defined above\n\n - ``q`` -- (default: ``None``) the variable `q`; if ``None``, then use a\n default variable in `\\ZZ[q]`\n\n - ``binomial_algorithm`` -- (default: ``'auto'``) the algorithm to use\n in :meth:`~sage.combinat.q_analogues.q_binomial`; see possible values\n there\n\n ALGORITHM:\n\n We use the equivalent formula\n\n .. MATH::\n\n \\binom{k_1 + \\cdots + k_m}{k_1, \\ldots, k_m}_q\n = \\prod_{i=1}^m \\binom{\\sum_{j=1}^i k_j}{k_i}_q.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_multinomial\n sage: q_multinomial([1,2,1])\n q^5 + 2*q^4 + 3*q^3 + 3*q^2 + 2*q + 1\n sage: q_multinomial([1,2,1], q=1) == multinomial([1,2,1])\n True\n sage: q_multinomial((3,2)) == q_binomial(5,3)\n True\n sage: q_multinomial([])\n 1\n "
binomials = []
partial_sum = 0
for elem in seq:
partial_sum += elem
binomials.append(q_binomial(partial_sum, elem, q=q, algorithm=binomial_algorithm))
return prod(binomials)
|
def q_catalan_number(n, q=None, m=1):
"\n Return the `q`-Catalan number of index `n`.\n\n INPUT:\n\n - ``q`` -- optional variable\n\n - ``m`` -- (optional integer) to get instead the ``m``-Fuss-Catalan numbers\n\n If `q` is unspecified, then it defaults to using the generator `q` for\n a univariate polynomial ring over the integers.\n\n There are several `q`-Catalan numbers. This procedure\n returns the one which can be written using the `q`-binomial coefficients.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_catalan_number\n sage: q_catalan_number(4)\n q^12 + q^10 + q^9 + 2*q^8 + q^7 + 2*q^6 + q^5 + 2*q^4 + q^3 + q^2 + 1\n\n sage: p = ZZ['p'].0\n sage: q_catalan_number(4, p)\n p^12 + p^10 + p^9 + 2*p^8 + p^7 + 2*p^6 + p^5 + 2*p^4 + p^3 + p^2 + 1\n\n sage: q_catalan_number(3, m=2)\n q^12 + q^10 + q^9 + q^8 + q^7 + 2*q^6 + q^5 + q^4 + q^3 + q^2 + 1\n\n TESTS:\n\n The `q`-Catalan number of index `n` is only defined for `n` a\n nonnegative integer (:trac:`11411`)::\n\n sage: q_catalan_number(-2)\n Traceback (most recent call last):\n ...\n ValueError: argument (-2) must be a nonnegative integer\n\n sage: q_catalan_number(3).parent()\n Univariate Polynomial Ring in q over Integer Ring\n sage: q_catalan_number(0).parent()\n Univariate Polynomial Ring in q over Integer Ring\n "
if (n in ZZ):
if (n in {0, 1}):
return q_int(1, q)
if (n >= 2):
return (prod((q_int(j, q) for j in range(((m * n) + 2), (((m + 1) * n) + 1)))) // prod((q_int(j, q) for j in range(2, (n + 1)))))
raise ValueError(f'argument ({n}) must be a nonnegative integer')
|
def qt_catalan_number(n):
'\n Return the `q,t`-Catalan number of index `n`.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import qt_catalan_number\n sage: qt_catalan_number(1)\n 1\n sage: qt_catalan_number(2)\n q + t\n sage: qt_catalan_number(3)\n q^3 + q^2*t + q*t^2 + t^3 + q*t\n sage: qt_catalan_number(4)\n q^6 + q^5*t + q^4*t^2 + q^3*t^3 + q^2*t^4 + q*t^5 + t^6 + q^4*t + q^3*t^2 + q^2*t^3 + q*t^4 + q^3*t + q^2*t^2 + q*t^3\n\n The `q,t`-Catalan number of index `n` is only defined for `n` a\n nonnegative integer (:trac:`11411`)::\n\n sage: qt_catalan_number(-2)\n Traceback (most recent call last):\n ...\n ValueError: argument (-2) must be a nonnegative integer\n '
if ((n in ZZ) and (n >= 0)):
ZZqt = ZZ[('q', 't')]
d = {}
for dw in DyckWords(n):
tup = (dw.area(), dw.bounce())
d[tup] = (d.get(tup, 0) + 1)
return ZZqt(d)
else:
raise ValueError(('argument (%s) must be a nonnegative integer' % n))
|
def q_pochhammer(n, a, q=None):
"\n Return the `q`-Pochhammer `(a; q)_n`.\n\n The `q`-Pochhammer symbol is defined by\n\n .. MATH::\n\n (a; q)_n = \\prod_{k=0}^{n-1} (1 - aq^k)\n\n with `(a; q)_0 = 1` for all `a, q` and `n \\in \\NN`.\n By using the identity\n\n .. MATH::\n\n (a; q)_n = \\frac{(a; q)_{\\infty}}{(aq^n; q)_{\\infty}},\n\n we can extend the definition to `n < 0` by\n\n .. MATH::\n\n (a; q)_n = \\frac{1}{(aq^n; q)_{-n}}\n = \\prod_{k=1}^{-n} \\frac{1}{1 - a/q^k}.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_pochhammer\n sage: q_pochhammer(3, 1/7)\n 6/343*q^3 - 6/49*q^2 - 6/49*q + 6/7\n sage: q_pochhammer(3, 3)\n -18*q^3 + 6*q^2 + 6*q - 2\n sage: q_pochhammer(3, 1)\n 0\n\n sage: R.<q> = ZZ[]\n sage: q_pochhammer(4, q)\n q^10 - q^9 - q^8 + 2*q^5 - q^2 - q + 1\n sage: q_pochhammer(4, q^2)\n q^14 - q^12 - q^11 - q^10 + q^8 + 2*q^7 + q^6 - q^4 - q^3 - q^2 + 1\n sage: q_pochhammer(-3, q)\n 1/(-q^9 + q^7 + q^6 + q^5 - q^4 - q^3 - q^2 + 1)\n\n TESTS::\n\n sage: q_pochhammer(0, 2)\n 1\n sage: q_pochhammer(0, 1)\n 1\n sage: q_pochhammer(0, var('a')) # needs sage.symbolic\n 1\n\n We check that :trac:`25715` is fixed::\n\n sage: q_pochhammer(0, 3r)\n 1\n\n REFERENCES:\n\n - :wikipedia:`Q-Pochhammer_symbol`\n "
if (q is None):
q = ZZ['q'].gen()
if (n not in ZZ):
raise ValueError('{} must be an integer'.format(n))
R = parent(q)
one = R(1)
if (n < 0):
return R.prod(((one / (one - (a / (q ** (- k))))) for k in range(1, ((- n) + 1))))
return R.prod(((one - (a * (q ** k))) for k in range(n)))
|
@cached_function(key=(lambda t, q: (_Partitions(t), q)))
def q_jordan(t, q=None):
'\n Return the `q`-Jordan number of `t`.\n\n If `q` is the power of a prime number, the output is the number of\n complete flags in `\\GF{q}^N` (where `N` is the size of `t`) stable\n under a linear nilpotent endomorphism `f_t` whose Jordan type is\n given by `t`, i.e. such that for all `i`:\n\n .. MATH::\n\n \\dim (\\ker f_t^i) = t[0] + \\cdots + t[i-1]\n\n If `q` is unspecified, then it defaults to using the generator `q` for\n a univariate polynomial ring over the integers.\n\n The result is cached.\n\n INPUT:\n\n - ``t`` -- an integer partition, or an argument accepted by\n :class:`Partition`\n\n - ``q`` -- (default: ``None``) the variable `q`; if ``None``, then use a\n default variable in `\\ZZ[q]`\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_jordan\n sage: [q_jordan(mu, 2) for mu in Partitions(5)]\n [9765, 1029, 213, 93, 29, 9, 1]\n sage: [q_jordan(mu, 2) for mu in Partitions(6)]\n [615195, 40635, 5643, 2331, 1491, 515, 147, 87, 47, 11, 1]\n sage: q_jordan([3,2,1])\n 16*q^4 + 24*q^3 + 14*q^2 + 5*q + 1\n sage: q_jordan([2,1], x) # needs sage.symbolic\n 2*x + 1\n\n If the partition is trivial (i.e. has only one part), we get\n the `q`-factorial (in this case, the nilpotent endomorphism is\n necessarily `0`)::\n\n sage: from sage.combinat.q_analogues import q_factorial\n sage: q_jordan([5]) == q_factorial(5)\n True\n sage: q_jordan([11], 5) == q_factorial(11, 5)\n True\n\n TESTS::\n\n sage: all(multinomial(mu.conjugate()) == q_jordan(mu, 1) for mu in Partitions(6))\n True\n\n AUTHOR:\n\n - Xavier Caruso (2012-06-29)\n '
if (q is None):
q = ZZ['q'].gen()
if all(((part == 0) for part in t)):
return parent(q)(1)
tj = 0
res = parent(q)(0)
for i in range((len(t) - 1), (- 1), (- 1)):
ti = t[i]
if (ti > tj):
tp = list(t)
tp[i] -= 1
res += ((q_jordan(tp, q) * (q ** tj)) * q_int((ti - tj), q))
tj = ti
return res
|
def q_subgroups_of_abelian_group(la, mu, q=None, algorithm='birkhoff'):
"\n Return the `q`-number of subgroups of type ``mu`` in a finite abelian\n group of type ``la``.\n\n INPUT:\n\n - ``la`` -- type of the ambient group as a :class:`Partition`\n - ``mu`` -- type of the subgroup as a :class:`Partition`\n - ``q`` -- (default: ``None``) an indeterminate or a prime number; if\n ``None``, this defaults to `q \\in \\ZZ[q]`\n - ``algorithm`` -- (default: ``'birkhoff'``) the algorithm to use can be\n one of the following:\n\n - ``'birkhoff`` -- use the Birkhoff formula from [Bu87]_\n - ``'delsarte'`` -- use the formula from [Delsarte48]_\n\n OUTPUT:\n\n The number of subgroups of type ``mu`` in a group of type ``la`` as a\n polynomial in ``q``.\n\n ALGORITHM:\n\n Let `q` be a prime number and `\\lambda = (\\lambda_1, \\ldots, \\lambda_l)`\n be a partition. A finite abelian `q`-group is of type `\\lambda` if it\n is isomorphic to\n\n .. MATH::\n\n \\ZZ / q^{\\lambda_1} \\ZZ \\times \\cdots \\times \\ZZ / q^{\\lambda_l} \\ZZ.\n\n The formula from [Bu87]_ works as follows:\n Let `\\lambda` and `\\mu` be partitions. Let `\\lambda^{\\prime}` and\n `\\mu^{\\prime}` denote the conjugate partitions to `\\lambda` and `\\mu`,\n respectively. The number of subgroups of type `\\mu` in a group of type\n `\\lambda` is given by\n\n .. MATH::\n\n \\prod_{i=1}^{\\mu_1} q^{\\mu^{\\prime}_{i+1}\n (\\lambda^{\\prime}_i - \\mu^{\\prime}_i)}\n \\binom{\\lambda^{\\prime}_i - \\mu^{\\prime}_{i+1}}\n {\\mu^{\\prime}_i - \\mu^{\\prime}_{i+1}}_q\n\n The formula from [Delsarte48]_ works as follows:\n Let `\\lambda` and `\\mu` be partitions. Let `(s_1, s_2, \\ldots, s_l)`\n and `(r_1, r_2, \\ldots, r_k)` denote the parts of the partitions\n conjugate to `\\lambda` and `\\mu` respectively. Let\n\n\n .. MATH::\n\n \\mathfrak{F}(\\xi_1, \\ldots, \\xi_k) = \\xi_1^{r_2} \\xi_2^{r_3} \\cdots\n \\xi_{k-1}^{r_k} \\prod_{i_1=r_2}^{r_1-1} (\\xi_1-q^{i_1})\n \\prod_{i_2=r_3}^{r_2-1} (\\xi_2-q^{i_2}) \\cdots\n \\prod_{i_k=0}^{r_k-1} (\\xi_k-q^{-i_k}).\n\n Then the number of subgroups of type `\\mu` in a group of type `\\lambda`\n is given by\n\n .. MATH::\n\n \\frac{\\mathfrak{F}(q^{s_1}, q^{s_2}, \\ldots, q^{s_k})}{\\mathfrak{F}\n (q^{r_1}, q^{r_2}, \\ldots, q^{r_k})}.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_subgroups_of_abelian_group\n sage: q_subgroups_of_abelian_group([1,1], [1])\n q + 1\n sage: q_subgroups_of_abelian_group([3,3,2,1], [2,1])\n q^6 + 2*q^5 + 3*q^4 + 2*q^3 + q^2\n sage: R.<t> = QQ[]\n sage: q_subgroups_of_abelian_group([5,3,1], [3,1], t)\n t^4 + 2*t^3 + t^2\n sage: q_subgroups_of_abelian_group([5,3,1], [3,1], 3)\n 144\n sage: q_subgroups_of_abelian_group([1,1,1], [1]) == q_subgroups_of_abelian_group([1,1,1], [1,1])\n True\n sage: q_subgroups_of_abelian_group([5], [3])\n 1\n sage: q_subgroups_of_abelian_group([1], [2])\n 0\n sage: q_subgroups_of_abelian_group([2], [1,1])\n 0\n\n TESTS:\n\n Check the same examples with ``algorithm='delsarte'``::\n\n sage: q_subgroups_of_abelian_group([1,1], [1], algorithm='delsarte')\n q + 1\n sage: q_subgroups_of_abelian_group([3,3,2,1], [2,1], algorithm='delsarte')\n q^6 + 2*q^5 + 3*q^4 + 2*q^3 + q^2\n sage: q_subgroups_of_abelian_group([5,3,1], [3,1], t, algorithm='delsarte')\n t^4 + 2*t^3 + t^2\n sage: q_subgroups_of_abelian_group([5,3,1], [3,1], 3, algorithm='delsarte')\n 144\n sage: q_subgroups_of_abelian_group([1,1,1], [1], algorithm='delsarte') == q_subgroups_of_abelian_group([1,1,1], [1,1])\n True\n sage: q_subgroups_of_abelian_group([5], [3], algorithm='delsarte')\n 1\n sage: q_subgroups_of_abelian_group([1], [2], algorithm='delsarte')\n 0\n sage: q_subgroups_of_abelian_group([2], [1,1], algorithm='delsarte')\n 0\n\n Check that :trac:`25715` is fixed::\n\n sage: parent(q_subgroups_of_abelian_group([2], [1], algorithm='delsarte'))\n Univariate Polynomial Ring in q over Integer Ring\n sage: q_subgroups_of_abelian_group([7,7,1], [])\n 1\n sage: q_subgroups_of_abelian_group([7,7,1], [0,0])\n 1\n\n REFERENCES:\n\n .. [Bu87] Butler, Lynne M. *A unimodality result in the enumeration\n of subgroups of a finite abelian group.* Proceedings of the American\n Mathematical Society 101, no. 4 (1987): 771-775.\n :doi:`10.1090/S0002-9939-1987-0911049-8`\n\n .. [Delsarte48] \\S. Delsarte, *Fonctions de Möbius Sur Les Groupes Abéliens\n Finis*, Annals of Mathematics, second series, Vol. 45, No. 3, (Jul 1948),\n pp. 600-609. http://www.jstor.org/stable/1969047\n\n AUTHORS:\n\n - Amritanshu Prasad (2013-06-07): Implemented the Delsarte algorithm\n - Tomer Bauer (2013, 2018): Implemented the Birkhoff algorithm and refactoring\n "
if (q is None):
q = ZZ['q'].gen()
la_c = _Partitions(la).conjugate()
mu_c = _Partitions(mu).conjugate()
k = mu_c.length()
if (not mu_c):
return parent(q)(1)
if (not la_c.contains(mu_c)):
return parent(q)(0)
if (algorithm == 'delsarte'):
def F(args):
prd = (lambda j: prod(((args[j] - (q ** i)) for i in range(mu_c[(j + 1)], mu_c[j]))))
F1 = prod((((args[i] ** mu_c[(i + 1)]) * prd(i)) for i in range((k - 1))))
return (F1 * prod(((args[(k - 1)] - (q ** i)) for i in range(mu_c[(k - 1)]))))
return (F([(q ** ss) for ss in la_c[:k]]) // F([(q ** rr) for rr in mu_c]))
if (algorithm == 'birkhoff'):
fac1 = (q ** sum(((mu_c[(i + 1)] * (la_c[i] - mu_c[i])) for i in range((k - 1)))))
fac2 = prod((q_binomial((la_c[i] - mu_c[(i + 1)]), (mu_c[i] - mu_c[(i + 1)]), q=q) for i in range((k - 1))))
fac3 = q_binomial(la_c[(k - 1)], mu_c[(k - 1)], q=q)
return prod([fac1, fac2, fac3])
raise ValueError('invalid algorithm choice')
|
@cached_function
def q_stirling_number1(n, k, q=None):
"\n Return the (unsigned) `q`-Stirling number of the first kind.\n\n This is a `q`-analogue of :func:`sage.combinat.combinat.stirling_number1` .\n\n INPUT:\n\n - ``n``, ``k`` -- integers with ``1 <= k <= n``\n\n - ``q`` -- optional variable (default `q`)\n\n OUTPUT: a polynomial in the variable `q`\n\n These polynomials satisfy the recurrence\n\n .. MATH::\n\n s_{n,k} = s_{n-1,k-1} + [n-1]_q s_{n-1, k}.\n\n EXAMPLES::\n\n sage: from sage.combinat.q_analogues import q_stirling_number1\n sage: q_stirling_number1(4,2)\n q^3 + 3*q^2 + 4*q + 3\n\n sage: all(stirling_number1(6,k) == q_stirling_number1(6,k)(1) # needs sage.libs.gap\n ....: for k in range(1,6))\n True\n\n sage: x = polygen(QQ['q'],'x')\n sage: S = sum(q_stirling_number1(5,k)*x**k for k in range(1, 6))\n sage: factor(S) # needs sage.libs.singular\n x * (x + 1) * (x + q + 1) * (x + q^2 + q + 1) * (x + q^3 + q^2 + q + 1)\n\n TESTS::\n\n sage: q_stirling_number1(-1,2)\n Traceback (most recent call last):\n ...\n ValueError: q-Stirling numbers are not defined for n < 0\n\n We check that :trac:`25715` is fixed::\n\n sage: q_stirling_number1(2,1,1r)\n 1\n\n REFERENCES:\n\n - [Ca1948]_\n\n - [Ca1954]_\n "
if (q is None):
q = ZZ['q'].gen()
if (n < 0):
raise ValueError('q-Stirling numbers are not defined for n < 0')
if (n == 0 == k):
return parent(q)(1)
if ((k > n) or (k < 1)):
return parent(q)(0)
return (q_stirling_number1((n - 1), (k - 1), q=q) + (q_int((n - 1), q=q) * q_stirling_number1((n - 1), k, q=q)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.