code stringlengths 17 6.64M |
|---|
def _break_at_descents(alpha, weak=True):
'\n Return the deconcatenation of the composition ``alpha`` at its\n set of descents.\n\n OUTPUT:\n\n A list `[a_1, \\ldots, a_r]` of nonempty lists whose concatenation\n is ``list(alpha)`` with the property that ``alpha[i] >= alpha[i+1]``\n if and only if positions `i` and `i+1` correspond to different\n lists. (Specifically, ``alpha[i]`` is the last letter of some\n `a_j` and ``alpha[i+1]`` is the first letter of `a_{j+1}`.)\n\n If the optional argument ``weak`` is ``False``, then only make\n breaks when ``alpha[i] > alpha[i+1]``.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _break_at_descents\n sage: _break_at_descents([1, 2, 3, 2, 2, 1, 4, 3])\n [[1, 2, 3], [2], [2], [1, 4], [3]]\n sage: _break_at_descents([1, 2, 3, 2, 2, 1, 4, 3], weak=False)\n [[1, 2, 3], [2, 2], [1, 4], [3]]\n sage: _break_at_descents([])\n []\n '
if (not alpha):
return []
Blocks = []
block = [alpha[0]]
for i in range(1, len(alpha)):
if ((alpha[(i - 1)] > alpha[i]) or ((alpha[(i - 1)] == alpha[i]) and weak)):
Blocks.append(block)
block = [alpha[i]]
else:
block.append(alpha[i])
if block:
Blocks.append(block)
return Blocks
|
def _refine_block(S, strong=False):
'\n Return the list of all possible refinements of a set `S`.\n\n A refinement of `S` is a tuple of nonempty subsets whose union is `S`.\n\n If optional argument ``strong`` is set to ``True``, then only those\n refinements that are deconcatenations of the list ``sorted(S)`` are returned.\n\n (The subsets involved are stored as ``frozenset`` objects.)\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _refine_block\n sage: _refine_block([1, 2], strong=True)\n [(frozenset({1}), frozenset({2})), (frozenset({1, 2}),)]\n\n sage: [tuple(Set(x) for x in tupl) for tupl in _refine_block([1, 2, 3], strong=True)]\n [({1}, {2}, {3}), ({1}, {2, 3}), ({1, 2}, {3}), ({1, 2, 3},)]\n sage: [tuple(Set(x) for x in tupl) for tupl in _refine_block([1, 2, 3])]\n [({3}, {2}, {1}), ({2}, {3}, {1}), ({3}, {1}, {2}),\n ({3}, {1, 2}), ({2}, {1}, {3}), ({2}, {1, 3}),\n ({2, 3}, {1}), ({1}, {3}, {2}), ({1}, {2}, {3}),\n ({1}, {2, 3}), ({1, 3}, {2}), ({1, 2}, {3}),\n ({1, 2, 3},)]\n\n TESTS::\n\n sage: len(_refine_block([1, 2, 3, 4])) == 1 + binomial(4,1)*2 + binomial(4,2) + binomial(4,2)*factorial(3) + factorial(4)\n True\n sage: len(_refine_block([1, 2, 3, 4], strong=True)) == 2**3\n True\n sage: _refine_block([])\n Traceback (most recent call last):\n ...\n ValueError: S (=[]) must be nonempty\n '
if (not S):
raise ValueError(('S (=%s) must be nonempty' % S))
if all(((s in ZZ) for s in S)):
X = sorted(S)
else:
X = sorted(S, key=str)
n = len(X)
out = []
if (not strong):
WordSet = IntegerListsLex(min_part=0, max_part=(n - 1), length=n)
else:
WordSet = IntegerListsLex(min_part=0, max_part=(n - 1), length=n, min_slope=0)
for w in WordSet:
if _is_initial_segment(sorted(set(w))):
a = [frozenset() for _ in range((max(w) + 1))]
for pos in range(n):
a[w[pos]] = a[w[pos]].union({X[pos]})
out.append(tuple(a))
return out
|
def _is_initial_segment(lst):
'\n Return True if ``lst`` is an interval in `\\ZZ` of the form `[0, 1, \\ldots, n]`.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _is_initial_segment\n sage: _is_initial_segment([1, 2, 3])\n False\n sage: _is_initial_segment([0, 1, 2, 3])\n True\n sage: _is_initial_segment([0])\n True\n '
return (list(range((max(lst) + 1))) == lst)
|
def _split_block(S, k=2):
'\n Return the list of all possible splittings of a set `S` into `k` parts.\n\n A splitting of `S` is a tuple of (possibly empty) subsets whose union is `S`.\n\n (The subsets involved are stored as ``frozenset`` objects.)\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _split_block\n sage: S = [1, 2, 3]\n sage: _split_block(S, 1)\n [(frozenset({1, 2, 3}),)]\n\n sage: [tuple(Set(x) for x in tupl) for tupl in _split_block(S, 2)]\n [({}, {1, 2, 3}), ({3}, {1, 2}), ({2}, {1, 3}), ({2, 3}, {1}),\n ({1}, {2, 3}), ({1, 3}, {2}), ({1, 2}, {3}), ({1, 2, 3}, {})]\n sage: [tuple(Set(x) for x in tupl) for tupl in _split_block({2, 4}, 3)]\n [({}, {}, {2, 4}), ({}, {4}, {2}), ({4}, {}, {2}),\n ({}, {2}, {4}), ({}, {2, 4}, {}), ({4}, {2}, {}),\n ({2}, {}, {4}), ({2}, {4}, {}), ({2, 4}, {}, {})]\n '
if all(((s in ZZ) for s in S)):
X = sorted(S)
else:
X = sorted(S, key=str)
n = len(X)
out = []
for w in IntegerListsLex(min_part=0, max_part=(k - 1), length=n):
a = [frozenset() for _ in range(k)]
for pos in range(n):
a[w[pos]] = a[w[pos]].union({X[pos]})
out.append(tuple(a))
return out
|
def _to_minimaj_blocks(T):
'\n Return a tuple of tuples, representing an ordered multiset partition into sets\n in the minimaj ordering on blocks\n\n INPUT:\n\n - ``T`` -- a sequence of row words corresponding to (skew-)tableaux.\n\n OUTPUT:\n\n The minimaj bijection `\\phi^{-1}` of [BCHOPSY2017]_ applied to ``T``.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _to_minimaj_blocks\n sage: co = OrderedMultisetPartitionsIntoSets(14).an_element(); co\n [{2,3}, {2,3}, {4}]\n sage: co.to_tableaux_words()\n [[3, 2], [], [3, 2, 4]]\n sage: _to_minimaj_blocks(co.to_tableaux_words()) == co.minimaj_blocks()\n True\n '
mu = [(i,) for i in T[(- 1)]]
breaks = (([0] + _descents(T[(- 1)])) + [(len(mu) - 1)])
T = [T[i][::(- 1)] for i in range((len(T) - 1))][::(- 1)]
for f in range((len(breaks) - 1)):
for j in range(breaks[f], (breaks[(f + 1)] + 1)):
mu[j] += tuple((i for i in T[f] if (((mu[j][0] < i) or (j == breaks[f])) and ((j == breaks[(f + 1)]) or (i <= mu[(j + 1)][0])))))
return tuple(mu)
|
class MinimajCrystal(UniqueRepresentation, Parent):
'\n Crystal of ordered multiset partitions into sets with `ell` letters from\n alphabet `\\{1, 2, \\ldots, n\\}` divided into `k` blocks.\n\n Elements are represented in the minimaj ordering of blocks as in\n Benkart et al. [BCHOPSY2017]_.\n\n .. NOTE::\n\n Elements are not stored internally as ordered multiset partitions\n into sets, but as certain (pairs of) words stemming from the minimaj\n bijection `\\phi` of [BCHOPSY2017]_. See\n :class:`sage.combinat.multiset_partition_into_sets_ordered.MinimajCrystal.Element`\n for further details.\n\n AUTHORS:\n\n - Anne Schilling (2018): initial draft\n - Aaron Lauve (2018): changed to use ``Letters`` crystal for elements\n\n EXAMPLES::\n\n sage: list(crystals.Minimaj(2,3,2)) # needs sage.modules\n [((2, 1), (1,)), ((2,), (1, 2)), ((1,), (1, 2)), ((1, 2), (2,))]\n\n sage: b = crystals.Minimaj(3, 5, 2).an_element(); b # needs sage.modules\n ((2, 3, 1), (1, 2))\n sage: b.f(2) # needs sage.modules\n ((2, 3, 1), (1, 3))\n sage: b.e(2) # needs sage.modules\n '
def __init__(self, n, ell, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: B = crystals.Minimaj(2,3,2)\n sage: TestSuite(B).run()\n sage: B = crystals.Minimaj(3, 5, 2)\n sage: TestSuite(B).run()\n sage: list(crystals.Minimaj(2,6,3))\n [((1, 2), (2, 1), (1, 2))]\n sage: list(crystals.Minimaj(2,5,2)) # blocks too fat for alphabet\n []\n sage: list(crystals.Minimaj(4,2,3)) # more blocks than letters\n Traceback (most recent call last):\n ...\n ValueError: n (=4), ell (=2), and k (=3) must all be positive integers\n '
Parent.__init__(self, category=ClassicalCrystals())
self.n = n
self.ell = ell
self.k = k
if (not all([(n in ZZ), (ell in ZZ), (k in ZZ)])):
raise TypeError(('n (=%s), ell (=%s), and k (=%s) must all be positive integers' % (n, ell, k)))
if (not all([(n > 0), (ell >= k), (k > 0)])):
raise ValueError(('n (=%s), ell (=%s), and k (=%s) must all be positive integers' % (n, ell, k)))
self._cartan_type = CartanType(['A', (n - 1)])
B = Letters(['A', (n - 1)])
T = tensor(([B] * ell))
self._BT = (B, T)
self._OMPs = OrderedMultisetPartitionsIntoSets(n, ell, length=k)
self.module_generators = []
for co in self._OMPs:
t = co.to_tableaux_words()
word = T(*[B(a) for a in _concatenate(t)])
blocks = [len(h) for h in t]
breaks = tuple(([0] + running_total(blocks)))
mu = self.element_class(self, (word, breaks))
self.module_generators.append(mu)
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Minimaj(3,4,2); B # needs sage.modules\n Minimaj Crystal of type A_2 of words of length 4 into 2 blocks\n '
return ('Minimaj Crystal of type A_%s of words of length %s into %s blocks' % ((self.n - 1), self.ell, self.k))
def _an_element_(self):
'\n Return a typical element of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: B = crystals.Minimaj(4,5,3)\n sage: B.an_element()\n ((2, 3, 1), (1,), (1,))\n sage: B = crystals.Minimaj(2,2,1)\n sage: B.an_element()\n ((1, 2),)\n sage: B = crystals.Minimaj(1,2,1)\n sage: B.an_element()\n Traceback (most recent call last):\n ...\n EmptySetError\n '
t = self._OMPs.an_element().to_tableaux_words()
breaks = tuple(([0] + running_total([len(h) for h in t])))
(B, T) = self._BT
return self.element_class(self, (T(*[B(a) for a in _concatenate(t)]), breaks))
def _element_constructor_(self, x):
'\n Build an element of Minimaj from an ordered multiset partition into sets.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: B1 = crystals.Minimaj(4,5,3); b = B1.an_element(); b\n ((2, 3, 1), (1,), (1,))\n sage: B1._element_constructor_(list(b))\n ((2, 3, 1), (1,), (1,))\n sage: B1._element_constructor_([[1,2,3], [2], [2]])\n ((3, 1, 2), (2,), (2,))\n sage: B2 = crystals.Minimaj(5,5,3)\n sage: B2._element_constructor_(b)\n ((2, 3, 1), (1,), (1,))\n '
x = list(x)
if (x in self):
t = self._OMPs(x).to_tableaux_words()
breaks = tuple(([0] + running_total([len(h) for h in t])))
(B, T) = self._BT
return self.element_class(self, (T(*[B(a) for a in _concatenate(t)]), breaks))
else:
raise ValueError(('cannot convert %s into an element of %s' % (x, self)))
def __contains__(self, x):
'\n Return ``True`` if ``x`` is an element of ``self`` or an ordered\n multiset partition into sets.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: B1 = crystals.Minimaj(2,5,3); b1 = B1.an_element(); b1\n ((1, 2), (2, 1), (1,))\n sage: B2 = crystals.Minimaj(5,5,3); b2 = B2.an_element(); b2\n ((2, 3, 1), (1,), (1,))\n sage: b2a = B2(((1,2), (1,), (1,2))); b2a\n ((2, 1), (1,), (1, 2))\n sage: b1 in B2\n True\n sage: b2 in B1\n False\n sage: b2a in B1\n True\n '
if isinstance(x, MinimajCrystal.Element):
if (x.parent() == self):
return True
else:
return (list(x) in self._OMPs)
else:
return (x in self._OMPs)
def from_tableau(self, t):
'\n Return the bijection `\\phi^{-1}` of [BCHOPSY2017]_ applied to ``t``.\n\n INPUT:\n\n - ``t`` -- a sequence of column tableaux and a ribbon tableau\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: B = crystals.Minimaj(3,6,3)\n sage: b = B.an_element(); b\n ((3, 1, 2), (2, 1), (1,))\n sage: t = b.to_tableaux_words(); t\n [[1], [2, 1], [], [3, 2, 1]]\n sage: B.from_tableau(t)\n ((3, 1, 2), (2, 1), (1,))\n sage: B.from_tableau(t) == b\n True\n\n TESTS::\n\n sage: # needs sage.modules\n sage: B = crystals.Minimaj(3,6,3)\n sage: all(mu == B.from_tableau(mu.to_tableaux_words()) for mu in B)\n True\n sage: t = B.an_element().to_tableaux_words()\n sage: B1 = crystals.Minimaj(3,6,2)\n sage: B1.from_tableau(t)\n Traceback (most recent call last):\n ...\n ValueError: ((3, 1, 2), (2, 1), (1,)) is not an element of\n Minimaj Crystal of type A_2 of words of length 6 into 2 blocks\n '
mu = _to_minimaj_blocks(t)
if (mu in self):
return self(mu)
else:
raise ValueError(('%s is not an element of %s' % (mu, self)))
def val(self, q='q'):
'\n Return the `Val` polynomial corresponding to ``self``.\n\n EXAMPLES:\n\n Verifying Example 4.5 from [BCHOPSY2017]_::\n\n sage: B = crystals.Minimaj(3, 4, 2) # for `Val_{4,1}^{(3)}` # needs sage.modules\n sage: B.val() # needs sage.modules\n (q^2+q+1)*s[2, 1, 1] + q*s[2, 2]\n '
H = [self._OMPs(list(b)) for b in self.highest_weight_vectors()]
Sym = SymmetricFunctions(ZZ[q])
q = Sym.base_ring().gens()[0]
s = Sym.schur()
return sum((((q ** t.minimaj()) * s[sorted(t.weight().values(), reverse=True)]) for t in H), Sym.zero())
class Element(ElementWrapper):
'\n An element of a Minimaj crystal.\n\n .. NOTE::\n\n Minimaj elements `b` are stored internally as pairs\n ``(w, breaks)``, where:\n\n - ``w`` is a word of length ``self.parent().ell`` over the\n letters `1` up to ``self.parent().n``;\n - ``breaks`` is a list of de-concatenation points to turn ``w``\n into a list of row words of (skew-)tableaux that represent\n `b` under the minimaj bijection `\\phi` of [BCHOPSY2017]_.\n\n The pair ``(w, breaks)`` may be recovered via ``b.value``.\n '
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: crystals.Minimaj(4,5,3).an_element() # needs sage.modules\n ((2, 3, 1), (1,), (1,))\n '
return repr(self._minimaj_blocks_from_word_pair())
def __iter__(self):
'\n Iterate over ``self._minimaj_blocks_from_word_pair()``.\n\n EXAMPLES::\n\n sage: b = crystals.Minimaj(4,5,3).an_element(); b # needs sage.modules\n ((2, 3, 1), (1,), (1,))\n sage: b.value # needs sage.modules\n ([1, 3, 2, 1, 1], (0, 1, 2, 5))\n sage: list(b) # needs sage.modules\n [(2, 3, 1), (1,), (1,)]\n '
return self._minimaj_blocks_from_word_pair().__iter__()
def _latex_(self):
'\n Return the latex representation of ``self``.\n\n EXAMPLES::\n\n sage: b = crystals.Minimaj(4,5,3).an_element(); b # needs sage.modules\n ((2, 3, 1), (1,), (1,))\n sage: latex(b) # needs sage.modules\n \\left(\\left(2, 3, 1\\right), \\left(1\\right), \\left(1\\right)\\right)\n '
return latex(self._minimaj_blocks_from_word_pair())
def _minimaj_blocks_from_word_pair(self):
'\n Return the tuple of tuples (in the minimaj ordering on blocks of\n ordered multiset partitions into sets) corresponding to ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Minimaj(4,5,3) # needs sage.modules\n sage: b = B.an_element(); b.value # needs sage.modules\n ([1, 3, 2, 1, 1], (0, 1, 2, 5))\n sage: b._minimaj_blocks_from_word_pair() # needs sage.modules\n ((2, 3, 1), (1,), (1,))\n '
return _to_minimaj_blocks(self.to_tableaux_words())
def to_tableaux_words(self):
'\n Return the image of the ordered multiset partition into sets ``self``\n under the minimaj bijection `\\phi` of [BCHOPSY2017]_.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: B = crystals.Minimaj(4,5,3)\n sage: b = B.an_element(); b\n ((2, 3, 1), (1,), (1,))\n sage: b.to_tableaux_words()\n [[1], [3], [2, 1, 1]]\n sage: b = B([[1,3,4], [3], [3]]); b\n ((4, 1, 3), (3,), (3,))\n sage: b.to_tableaux_words()\n [[3, 1], [], [4, 3, 3]]\n '
(w, breaks) = self.value
return [[ZZ(w[a].value) for a in range(breaks[j], breaks[(j + 1)])] for j in range((len(breaks) - 1))]
def e(self, i):
'\n Return `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Minimaj(4,3,2) # needs sage.modules\n sage: b = B([[2,3], [3]]); b # needs sage.modules\n ((2, 3), (3,))\n sage: [b.e(i) for i in range(1,4)] # needs sage.modules\n [((1, 3), (3,)), ((2,), (2, 3)), None]\n '
P = self.parent()
(w, breaks) = self.value
if (w.e(i) is None):
return None
w = w.e(i)
return P.element_class(P, (w, breaks))
def f(self, i):
'\n Return `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Minimaj(4,3,2) # needs sage.modules\n sage: b = B([[2,3], [3]]); b # needs sage.modules\n ((2, 3), (3,))\n sage: [b.f(i) for i in range(1,4)] # needs sage.modules\n [None, None, ((2, 3), (4,))]\n '
P = self.parent()
(w, breaks) = self.value
if (w.f(i) is None):
return None
w = w.f(i)
return P.element_class(P, (w, breaks))
|
def coeff_pi(J, I):
'\n Returns the coefficient `\\pi_{J,I}` as defined in [NCSF]_.\n\n INPUT:\n\n - ``J`` -- a composition\n - ``I`` -- a composition refining ``J``\n\n OUTPUT:\n\n - integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_pi\n sage: coeff_pi(Composition([1,1,1]), Composition([2,1]))\n 2\n sage: coeff_pi(Composition([2,1]), Composition([3]))\n 6\n '
return prod((prod(K.partial_sums()) for K in J.refinement_splitting(I)))
|
def coeff_lp(J, I):
'\n Returns the coefficient `lp_{J,I}` as defined in [NCSF]_.\n\n INPUT:\n\n - ``J`` -- a composition\n - ``I`` -- a composition refining ``J``\n\n OUTPUT:\n\n - integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_lp\n sage: coeff_lp(Composition([1,1,1]), Composition([2,1]))\n 1\n sage: coeff_lp(Composition([2,1]), Composition([3]))\n 1\n '
return prod((K[(- 1)] for K in J.refinement_splitting(I)))
|
def coeff_ell(J, I):
'\n Returns the coefficient `\\ell_{J,I}` as defined in [NCSF]_.\n\n INPUT:\n\n - ``J`` -- a composition\n - ``I`` -- a composition refining ``J``\n\n OUTPUT:\n\n - integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_ell\n sage: coeff_ell(Composition([1,1,1]), Composition([2,1]))\n 2\n sage: coeff_ell(Composition([2,1]), Composition([3]))\n 2\n '
return prod([len(elt) for elt in J.refinement_splitting(I)])
|
def coeff_sp(J, I):
'\n Returns the coefficient `sp_{J,I}` as defined in [NCSF]_.\n\n INPUT:\n\n - ``J`` -- a composition\n - ``I`` -- a composition refining ``J``\n\n OUTPUT:\n\n - integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_sp\n sage: coeff_sp(Composition([1,1,1]), Composition([2,1]))\n 2\n sage: coeff_sp(Composition([2,1]), Composition([3]))\n 4\n '
return prod(((factorial(len(K)) * prod(K)) for K in J.refinement_splitting(I)))
|
def coeff_dab(I, J):
'\n Return the number of standard composition tableaux of shape `I` with\n descent composition `J`.\n\n INPUT:\n\n - ``I, J`` -- compositions\n\n OUTPUT:\n\n - An integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import coeff_dab\n sage: coeff_dab(Composition([2,1]),Composition([2,1]))\n 1\n sage: coeff_dab(Composition([1,1,2]),Composition([1,2,1]))\n 0\n '
d = 0
for T in CompositionTableaux(I):
if (T.is_standard() and (T.descent_composition() == J)):
d += 1
return d
|
def compositions_order(n):
'\n Return the compositions of `n` ordered as defined in [QSCHUR]_.\n\n Let `S(\\gamma)` return the composition `\\gamma` after sorting. For\n compositions `\\alpha` and `\\beta`, we order `\\alpha \\rhd \\beta` if\n\n 1) `S(\\alpha) > S(\\beta)` lexicographically, or\n 2) `S(\\alpha) = S(\\beta)` and `\\alpha > \\beta` lexicographically.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - A list of the compositions of ``n`` sorted into decreasing order\n by `\\rhd`\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import compositions_order\n sage: compositions_order(3)\n [[3], [2, 1], [1, 2], [1, 1, 1]]\n sage: compositions_order(4)\n [[4], [3, 1], [1, 3], [2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n '
def _keyfunction(I):
return (sorted(I, reverse=True), list(I))
return sorted(Compositions(n), key=_keyfunction, reverse=True)
|
def m_to_s_stat(R, I, K):
"\n Return the coefficient of the complete non-commutative symmetric\n function `S^K` in the expansion of the monomial non-commutative\n symmetric function `M^I` with respect to the complete basis\n over the ring `R`. This is the coefficient in formula (36) of\n Tevlin's paper [Tev2007]_.\n\n INPUT:\n\n - ``R`` -- A ring, supposed to be a `\\QQ`-algebra\n - ``I``, ``K`` -- compositions\n\n OUTPUT:\n\n - The coefficient of `S^K` in the expansion of `M^I` in the\n complete basis of the non-commutative symmetric functions\n over ``R``.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import m_to_s_stat\n sage: m_to_s_stat(QQ, Composition([2,1]), Composition([1,1,1]))\n -1\n sage: m_to_s_stat(QQ, Composition([3]), Composition([1,2]))\n -2\n sage: m_to_s_stat(QQ, Composition([2,1,2]), Composition([2,1,2]))\n 8/3\n "
stat = 0
for J in Compositions(I.size()):
if (I.is_finer(J) and K.is_finer(J)):
pvec = ([0] + Composition(I).refinement_splitting_lengths(J).partial_sums())
pp = prod((R((len(I) - pvec[i])) for i in range((len(pvec) - 1))))
stat += R(((((- 1) ** (len(I) - len(K))) / pp) * coeff_lp(K, J)))
return stat
|
@cached_function
def number_of_fCT(content_comp, shape_comp):
'\n Return the number of Immaculate tableaux of shape\n ``shape_comp`` and content ``content_comp``.\n\n See [BBSSZ2012]_, Definition 3.9, for the notion of an\n immaculate tableau.\n\n INPUT:\n\n - ``content_comp``, ``shape_comp`` -- compositions\n\n OUTPUT:\n\n - An integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import number_of_fCT\n sage: number_of_fCT(Composition([3,1]), Composition([1,3]))\n 0\n sage: number_of_fCT(Composition([1,2,1]), Composition([1,3]))\n 1\n sage: number_of_fCT(Composition([1,1,3,1]), Composition([2,1,3]))\n 2\n '
if (content_comp.to_partition().length() == 1):
if (shape_comp.to_partition().length() == 1):
return 1
else:
return 0
C = Compositions((content_comp.size() - content_comp[(- 1)]), outer=list(shape_comp))
s = 0
for x in C:
if (len(x) >= (len(shape_comp) - 1)):
s += number_of_fCT(Composition(content_comp[:(- 1)]), x)
return s
|
@cached_function
def number_of_SSRCT(content_comp, shape_comp):
'\n The number of semi-standard reverse composition tableaux.\n\n The dual quasisymmetric-Schur functions satisfy a left Pieri rule\n where `S_n dQS_\\gamma` is a sum over dual quasisymmetric-Schur\n functions indexed by compositions which contain the composition\n `\\gamma`. The definition of an SSRCT comes from this rule. The\n number of SSRCT of content `\\beta` and shape `\\alpha` is equal to\n the number of SSRCT of content `(\\beta_2, \\ldots, \\beta_\\ell)`\n and shape `\\gamma` where `dQS_\\alpha` appears in the expansion of\n `S_{\\beta_1} dQS_\\gamma`.\n\n In sage the recording tableau for these objects are called\n :class:`~sage.combinat.composition_tableau.CompositionTableaux`.\n\n INPUT:\n\n - ``content_comp``, ``shape_comp`` -- compositions\n\n OUTPUT:\n\n - An integer\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.combinatorics import number_of_SSRCT\n sage: number_of_SSRCT(Composition([3,1]), Composition([1,3]))\n 0\n sage: number_of_SSRCT(Composition([1,2,1]), Composition([1,3]))\n 1\n sage: number_of_SSRCT(Composition([1,1,2,2]), Composition([3,3]))\n 2\n sage: all(CompositionTableaux(be).cardinality()\n ....: == sum(number_of_SSRCT(al,be)*binomial(4,len(al))\n ....: for al in Compositions(4))\n ....: for be in Compositions(4))\n True\n '
if (len(content_comp) == 1):
if (len(shape_comp) == 1):
return ZZ.one()
else:
return ZZ.zero()
s = ZZ.zero()
cond = (lambda al, be: all((((al[j] <= be_val) and (not any((((al[i] <= k) and (k <= be[i])) for k in range(al[j], be_val) for i in range(j))))) for (j, be_val) in enumerate(be))))
C = Compositions((content_comp.size() - content_comp[0]), inner=([1] * len(shape_comp)), outer=list(shape_comp))
for x in C:
if cond(x, shape_comp):
s += number_of_SSRCT(Composition(content_comp[1:]), x)
if (shape_comp[0] <= content_comp[0]):
C = Compositions((content_comp.size() - content_comp[0]), inner=[min(val, (shape_comp[0] + 1)) for val in shape_comp[1:]], outer=shape_comp[1:])
Comps = Compositions()
for x in C:
if cond(([shape_comp[0]] + list(x)), shape_comp):
s += number_of_SSRCT(Comps(content_comp[1:]), x)
return s
|
class BasesOfQSymOrNCSF(Category_realization_of_parent):
def _repr_object_names(self):
"\n Return the name of the objects of this category.\n\n TESTS::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import BasesOfQSymOrNCSF\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: C = BasesOfQSymOrNCSF(QSym)\n sage: C._repr_object_names()\n 'bases of Non-Commutative Symmetric Functions or Quasisymmetric functions over the Rational Field'\n sage: C\n Category of bases of Non-Commutative Symmetric Functions or Quasisymmetric functions over the Rational Field\n\n "
return ('bases of Non-Commutative Symmetric Functions or Quasisymmetric functions over the %s' % self.base().base_ring())
def super_categories(self):
'\n TESTS::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import BasesOfQSymOrNCSF\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: BasesOfQSymOrNCSF(QSym).super_categories()\n [Category of realizations of Quasisymmetric functions over the Rational Field,\n Category of graded Hopf algebras with basis over Rational Field,\n Join of Category of realizations of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of graded coalgebras over Rational Field]\n '
R = self.base().base_ring()
from sage.categories.graded_hopf_algebras_with_basis import GradedHopfAlgebrasWithBasis
from sage.categories.graded_hopf_algebras import GradedHopfAlgebras
return [self.base().Realizations(), GradedHopfAlgebrasWithBasis(R), GradedHopfAlgebras(R).Realizations()]
class ParentMethods():
def _repr_(self):
"\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: S._repr_()\n 'Non-Commutative Symmetric Functions over the Rational Field in the Complete basis'\n sage: F = QuasiSymmetricFunctions(ZZ).Fundamental()\n sage: F._repr_()\n 'Quasisymmetric functions over the Integer Ring in the Fundamental basis'\n "
return ('%s in the %s basis' % (self.realization_of(), self._realization_name()))
def __getitem__(self, c, *rest):
"\n This method implements the abuses of notations::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi[2,1]\n Psi[2, 1]\n sage: Psi[[2,1]]\n Psi[2, 1]\n sage: Psi[Composition([2,1])]\n Psi[2, 1]\n\n .. TODO::\n\n This should call ``super.monomial`` if the input can't\n be made into a composition so as not to interfere with\n the standard notation ``Psi['x,y,z']``.\n\n This could possibly be shared with Sym, FQSym, and\n other algebras with bases indexed by list-like objects\n "
if isinstance(c, Composition):
assert (len(rest) == 0)
elif ((len(rest) > 0) or isinstance(c, (int, Integer))):
c = self._indices(([c] + list(rest)))
else:
c = self._indices(list(c))
return self.monomial(c)
@cached_method
def one_basis(self):
"\n Return the empty composition.\n\n OUTPUT:\n\n - The empty composition.\n\n EXAMPLES::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).L()\n sage: parent(L)\n <class 'sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Elementary_with_category'>\n sage: parent(L).one_basis()\n []\n "
return Compositions()([])
def sum_of_finer_compositions(self, composition):
'\n Return the sum of all finer compositions.\n\n INPUT:\n\n - ``composition`` -- a composition\n\n OUTPUT:\n\n - The sum of all basis ``self`` elements which are indexed by\n compositions finer than ``composition``.\n\n EXAMPLES::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).L()\n sage: L.sum_of_finer_compositions(Composition([2,1]))\n L[1, 1, 1] + L[2, 1]\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: R.sum_of_finer_compositions(Composition([1,3]))\n R[1, 1, 1, 1] + R[1, 1, 2] + R[1, 2, 1] + R[1, 3]\n '
return self.sum_of_monomials((compo for compo in composition.finer()))
def sum_of_fatter_compositions(self, composition):
'\n Return the sum of all fatter compositions.\n\n INPUT:\n\n - ``composition`` -- a composition\n\n OUTPUT:\n\n - the sum of all basis elements which are indexed by\n compositions fatter (coarser?) than ``composition``.\n\n EXAMPLES::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).L()\n sage: L.sum_of_fatter_compositions(Composition([2,1]))\n L[2, 1] + L[3]\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: R.sum_of_fatter_compositions(Composition([1,3]))\n R[1, 3] + R[4]\n '
return self.sum_of_monomials((compo for compo in composition.fatter()))
def alternating_sum_of_compositions(self, n):
'\n Alternating sum over compositions of ``n``.\n\n Note that this differs from the method\n :meth:`alternating_sum_of_finer_compositions` because the\n coefficient of the composition `1^n` is positive. This\n method is used in the expansion of the elementary generators\n into the complete generators and vice versa.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - The expansion of the complete generator indexed by ``n``\n into the elementary basis.\n\n EXAMPLES::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).L()\n sage: L.alternating_sum_of_compositions(0)\n L[]\n sage: L.alternating_sum_of_compositions(1)\n L[1]\n sage: L.alternating_sum_of_compositions(2)\n L[1, 1] - L[2]\n sage: L.alternating_sum_of_compositions(3)\n L[1, 1, 1] - L[1, 2] - L[2, 1] + L[3]\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.alternating_sum_of_compositions(3)\n S[1, 1, 1] - S[1, 2] - S[2, 1] + S[3]\n '
ring = self.base_ring()
return (((- ring.one()) ** n) * self.sum_of_terms(((compo, ring(((- 1) ** len(compo)))) for compo in Compositions(n))))
def alternating_sum_of_finer_compositions(self, composition, conjugate=False):
'\n Return the alternating sum of finer compositions in a basis of the\n non-commutative symmetric functions.\n\n INPUT:\n\n - ``composition`` -- a composition\n - ``conjugate`` -- (default: ``False``) a boolean\n\n OUTPUT:\n\n - The alternating sum of the compositions finer than ``composition``,\n in the basis ``self``. The alternation is upon the length of the\n compositions, and is normalized so that ``composition`` has\n coefficient `1`. If the variable ``conjugate`` is set to ``True``,\n then the conjugate of ``composition`` is used instead of\n ``composition``.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: elementary = NCSF.elementary()\n sage: elementary.alternating_sum_of_finer_compositions(Composition([2,2,1]))\n L[1, 1, 1, 1, 1] - L[1, 1, 2, 1] - L[2, 1, 1, 1] + L[2, 2, 1]\n sage: elementary.alternating_sum_of_finer_compositions(Composition([1,2]))\n -L[1, 1, 1] + L[1, 2]\n\n TESTS::\n\n sage: complete = NonCommutativeSymmetricFunctions(ZZ).complete()\n sage: I = Composition([2])\n sage: x = complete.alternating_sum_of_finer_compositions(I)\n sage: [c.parent() for c in x.coefficients()]\n [Integer Ring, Integer Ring]\n '
if conjugate:
composition = composition.conjugate()
l = len(composition)
ring = self.base_ring()
return self.sum_of_terms(((compo, ring(((- 1) ** (len(compo) - l)))) for compo in composition.finer()))
def alternating_sum_of_fatter_compositions(self, composition):
'\n Return the alternating sum of fatter compositions in a basis of the\n non-commutative symmetric functions.\n\n INPUT:\n\n - ``composition`` -- a composition\n\n OUTPUT:\n\n - The alternating sum of the compositions fatter than ``composition``,\n in the basis ``self``. The alternation is upon the length of the\n compositions, and is normalized so that ``composition`` has\n coefficient `1`.\n\n EXAMPLES::\n\n sage: NCSF=NonCommutativeSymmetricFunctions(QQ)\n sage: elementary = NCSF.elementary()\n sage: elementary.alternating_sum_of_fatter_compositions(Composition([2,2,1]))\n L[2, 2, 1] - L[2, 3] - L[4, 1] + L[5]\n sage: elementary.alternating_sum_of_fatter_compositions(Composition([1,2]))\n L[1, 2] - L[3]\n\n TESTS::\n\n sage: complete = NonCommutativeSymmetricFunctions(ZZ).complete()\n sage: I = Composition([1,1])\n sage: x = complete.alternating_sum_of_fatter_compositions(I)\n sage: [c.parent() for c in x.coefficients()]\n [Integer Ring, Integer Ring]\n '
l = len(composition)
ring = self.base_ring()
return self.sum_of_terms(((compo, ring(((- 1) ** (len(compo) - l)))) for compo in composition.fatter()))
def sum_of_partition_rearrangements(self, par):
'\n Return the sum of all basis elements indexed by compositions which can be\n sorted to obtain a given partition.\n\n INPUT:\n\n - ``par`` -- a partition\n\n OUTPUT:\n\n - The sum of all ``self`` basis elements indexed by compositions\n which are permutations of ``par`` (without multiplicity).\n\n EXAMPLES::\n\n sage: NCSF=NonCommutativeSymmetricFunctions(QQ)\n sage: elementary = NCSF.elementary()\n sage: elementary.sum_of_partition_rearrangements(Partition([2,2,1]))\n L[1, 2, 2] + L[2, 1, 2] + L[2, 2, 1]\n sage: elementary.sum_of_partition_rearrangements(Partition([3,2,1]))\n L[1, 2, 3] + L[1, 3, 2] + L[2, 1, 3] + L[2, 3, 1] + L[3, 1, 2] + L[3, 2, 1]\n sage: elementary.sum_of_partition_rearrangements(Partition([]))\n L[]\n '
return self.sum_of_monomials((self._indices(comp) for comp in Permutations(par)))
def _comp_to_par(self, comp):
'\n Return the partition if the composition is actually a partition. Otherwise\n returns nothing.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - ``comp`` as a partition, if it is sorted; otherwise returns\n ``None`` (nothing).\n\n EXAMPLES::\n\n sage: NCSF=NonCommutativeSymmetricFunctions(QQ)\n sage: L = NCSF.elementary()\n sage: L._comp_to_par(Composition([1,1,3,1,2]))\n sage: L.sum_of_partition_rearrangements(Composition([]))\n L[]\n sage: L._comp_to_par(Composition([3,2,1,1]))\n [3, 2, 1, 1]\n '
try:
return Partition(comp)
except ValueError:
return None
def degree_on_basis(self, I):
'\n Return the degree of the basis element indexed by `I`.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The degree of the non-commutative symmetric function basis\n element of ``self`` indexed by ``I``. By definition, this is\n the size of the composition ``I``.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: R.degree_on_basis(Composition([2,3]))\n 5\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: M.degree_on_basis(Composition([3,2]))\n 5\n sage: M.degree_on_basis(Composition([]))\n 0\n '
return I.size()
def skew(self, x, y, side='left'):
"\n Return a function ``x`` in ``self`` skewed by a function\n ``y`` in the Hopf dual of ``self``.\n\n INPUT:\n\n - ``x`` -- a non-commutative or quasi-symmetric function; it is\n an element of ``self``\n - ``y`` -- a quasi-symmetric or non-commutative symmetric\n function; it is an element of the dual algebra of ``self``\n - ``side`` -- (default: ``'left'``)\n either ``'left'`` or ``'right'``\n\n OUTPUT:\n\n - The result of skewing the element ``x`` by the Hopf algebra\n element ``y`` (either from the left or from the right, as\n determined by ``side``), written in the basis ``self``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: S.skew(S[2,2,2], F[1,1])\n S[1, 1, 2] + S[1, 2, 1] + S[2, 1, 1]\n sage: S.skew(S[2,2,2], F[2])\n S[1, 1, 2] + S[1, 2, 1] + S[2, 1, 1] + 3*S[2, 2]\n\n ::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: R.skew(R[2,2,2], F[1,1])\n R[1, 1, 2] + R[1, 2, 1] + R[1, 3] + R[2, 1, 1] + 2*R[2, 2] + R[3, 1] + R[4]\n sage: R.skew(R[2,2,2], F[2])\n R[1, 1, 2] + R[1, 2, 1] + R[1, 3] + R[2, 1, 1] + 3*R[2, 2] + R[3, 1] + R[4]\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M.skew(M[3,2], S[2])\n 0\n sage: M.skew(M[3,2], S[2], side='right')\n M[3]\n sage: M.skew(M[3,2], S[3])\n M[2]\n sage: M.skew(M[3,2], S[3], side='right')\n 0\n\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: R.skew([2,1], [1])\n Traceback (most recent call last):\n ...\n AssertionError: x must be an element of Non-Commutative Symmetric Functions over the Rational Field\n sage: R([2,1]).skew_by([1])\n Traceback (most recent call last):\n ...\n AssertionError: y must be an element of Quasisymmetric functions over the Rational Field\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F([2,1]).skew_by([1])\n Traceback (most recent call last):\n ...\n AssertionError: y must be an element of Non-Commutative Symmetric Functions over the Rational Field\n "
alg = self.realization_of()
assert (x in alg), ('x must be an element of %s' % alg)
assert (y in alg.dual()), ('y must be an element of %s' % alg.dual())
if hasattr(self, 'dual'):
x = self(x)
y = self.dual()(y)
v = (1 if (side == 'left') else 0)
return self.sum((((coeff * y[IJ[(1 - v)]]) * self[IJ[v]]) for (IJ, coeff) in x.coproduct() if (IJ[(1 - v)] in y.support())))
else:
return self._skew_by_coercion(x, y, side=side)
def _skew_by_coercion(self, x, y, side='left'):
"\n Return a function ``x`` in ``self`` skewed by a function\n ``y`` in the Hopf dual of ``self`` using coercion.\n\n INPUT:\n\n - ``x`` -- a non-commutative or quasi-symmetric function; it is\n an element of ``self``\n - ``y`` -- a quasi-symmetric or non-commutative symmetric\n function; it is an element of the dual algebra of ``self``\n - ``side`` -- (default: ``'left'``)\n either ``'left'`` or ``'right'``\n\n OUTPUT:\n\n - The result of skewing the element ``x`` by the Hopf algebra\n element ``y`` (either from the left or from the right, as\n determined by ``side``), written in the basis ``self``.\n This uses coercion to a concrete realization (either the\n complete basis of non-commutative symmetric functions or\n the monomial basis of the quasi-symmetric functions).\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M._skew_by_coercion(M[1,2,1,3], R[1])\n M[2, 1, 3]\n sage: M._skew_by_coercion(M[1,2,1,3], R[1],side='right')\n 0\n "
a_realization = self.realization_of().a_realization()
return self(a_realization.skew(a_realization(x), y, side=side))
def duality_pairing(self, x, y):
'\n The duality pairing between elements of `NSym` and elements\n of `QSym`.\n\n This is a default implementation that uses\n ``self.realizations_of().a_realization()`` and its dual basis.\n\n INPUT:\n\n - ``x`` -- an element of ``self``\n - ``y`` -- an element in the dual basis of ``self``\n\n OUTPUT:\n\n - The result of pairing the function ``x`` from ``self`` with the function\n ``y`` from the dual basis of ``self``\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).Ribbon()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: R.duality_pairing(R[1,1,2], F[1,1,2])\n 1\n sage: R.duality_pairing(R[1,2,1], F[1,1,2])\n 0\n sage: F.duality_pairing(F[1,2,1], R[1,1,2])\n 0\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).Complete()\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: S.duality_pairing(S[1,1,2], M[1,1,2])\n 1\n sage: S.duality_pairing(S[1,2,1], M[1,1,2])\n 0\n sage: M.duality_pairing(M[1,1,2], S[1,1,2])\n 1\n sage: M.duality_pairing(M[1,2,1], S[1,1,2])\n 0\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).Complete()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: S.duality_pairing(S[1,2], F[1,1,1])\n 0\n sage: S.duality_pairing(S[1,1,1,1], F[4])\n 1\n\n TESTS:\n\n The result has the right parent even if the sum is empty::\n\n sage: x = S.duality_pairing(S.zero(), F.zero()); x\n 0\n sage: parent(x)\n Rational Field\n '
if hasattr(self, 'dual'):
x = self(x)
y = self.dual()(y)
return self.base_ring().sum(((coeff * y[I]) for (I, coeff) in x))
else:
return self.duality_pairing_by_coercion(x, y)
def duality_pairing_by_coercion(self, x, y):
'\n The duality pairing between elements of NSym and elements of QSym.\n\n This is a default implementation that uses\n ``self.realizations_of().a_realization()`` and its dual basis.\n\n INPUT:\n\n - ``x`` -- an element of ``self``\n - ``y`` -- an element in the dual basis of ``self``\n\n OUTPUT:\n\n - The result of pairing the function ``x`` from ``self`` with\n the function ``y`` from the dual basis of ``self``\n\n EXAMPLES::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).Elementary()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: L.duality_pairing_by_coercion(L[1,2], F[1,2])\n 0\n sage: F.duality_pairing_by_coercion(F[1,2], L[1,2])\n 0\n sage: L.duality_pairing_by_coercion(L[1,1,1], F[1,2])\n 1\n sage: F.duality_pairing_by_coercion(F[1,2], L[1,1,1])\n 1\n\n TESTS:\n\n The result has the right parent even if the sum is empty::\n\n sage: x = F.duality_pairing_by_coercion(F.zero(), L.zero()); x\n 0\n sage: parent(x)\n Rational Field\n '
a_realization = self.realization_of().a_realization()
x = a_realization(x)
y = a_realization.dual()(y)
return self.base_ring().sum(((coeff * y[I]) for (I, coeff) in x))
def duality_pairing_matrix(self, basis, degree):
'\n The matrix of scalar products between elements of NSym and\n elements of QSym.\n\n INPUT:\n\n - ``basis`` -- A basis of the dual Hopf algebra\n - ``degree`` -- a non-negative integer\n\n OUTPUT:\n\n - The matrix of scalar products between the basis ``self``\n and the basis ``basis`` in the dual Hopf algebra in\n degree ``degree``.\n\n EXAMPLES:\n\n The ribbon basis of NCSF is dual to the fundamental basis of\n QSym::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: R.duality_pairing_matrix(F, 3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n sage: F.duality_pairing_matrix(R, 3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n\n The complete basis of NCSF is dual to the monomial basis of\n QSym::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: S.duality_pairing_matrix(M, 3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n sage: M.duality_pairing_matrix(S, 3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n\n The matrix between the ribbon basis of NCSF and the monomial\n basis of QSym::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: R.duality_pairing_matrix(M, 3)\n [ 1 -1 -1 1]\n [ 0 1 0 -1]\n [ 0 0 1 -1]\n [ 0 0 0 1]\n sage: M.duality_pairing_matrix(R, 3)\n [ 1 0 0 0]\n [-1 1 0 0]\n [-1 0 1 0]\n [ 1 -1 -1 1]\n\n The matrix between the complete basis of NCSF and the\n fundamental basis of QSym::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: S.duality_pairing_matrix(F, 3)\n [1 1 1 1]\n [0 1 0 1]\n [0 0 1 1]\n [0 0 0 1]\n\n A base case test::\n\n sage: R.duality_pairing_matrix(M,0)\n [1]\n '
from sage.matrix.constructor import matrix
from sage.combinat.composition import Compositions
return matrix(self.base_ring(), [[self.duality_pairing(self[I], basis[J]) for J in Compositions(degree)] for I in Compositions(degree)])
def counit_on_basis(self, I):
'\n The counit is defined by sending all elements of positive degree to zero.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.counit_on_basis([1,3])\n 0\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M.counit_on_basis([1,3])\n 0\n\n TESTS::\n\n sage: S.counit_on_basis([])\n 1\n sage: S.counit_on_basis(Composition([]))\n 1\n sage: M.counit_on_basis([])\n 1\n sage: M.counit_on_basis(Composition([]))\n 1\n '
if I:
return self.base_ring().zero()
else:
return self.base_ring().one()
def degree_negation(self, element):
'\n Return the image of ``element`` under the degree negation\n automorphism of ``self``.\n\n The degree negation is the automorphism which scales every\n homogeneous element of degree `k` by `(-1)^k` (for all `k`).\n\n INPUT:\n\n - ``element`` -- element of ``self``\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: f = 2*S[2,1] + 4*S[1,1] - 5*S[1,2] - 3*S[[]]\n sage: S.degree_negation(f)\n -3*S[] + 4*S[1, 1] + 5*S[1, 2] - 2*S[2, 1]\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: dI = QSym.dualImmaculate()\n sage: f = -3*dI[2,1] + 4*dI[2] + 2*dI[1]\n sage: dI.degree_negation(f)\n -2*dI[1] + 4*dI[2] + 3*dI[2, 1]\n\n TESTS:\n\n Using :meth:`degree_negation` on an element of a different\n basis works correctly::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: Phi = NSym.Phi()\n sage: S.degree_negation(Phi[2])\n -S[1, 1] + 2*S[2]\n sage: S.degree_negation(Phi[3])\n -S[1, 1, 1] + 3/2*S[1, 2] + 3/2*S[2, 1] - 3*S[3]\n sage: Phi.degree_negation(S[3])\n -1/6*Phi[1, 1, 1] - 1/4*Phi[1, 2] - 1/4*Phi[2, 1] - 1/3*Phi[3]\n\n The zero element behaves well::\n\n sage: a = Phi.degree_negation(S.zero()); a\n 0\n sage: parent(a)\n Non-Commutative Symmetric Functions over the Rational Field in the Phi basis\n\n .. TODO::\n\n Generalize this to all graded vector spaces?\n '
return self.sum_of_terms([(lam, (((- 1) ** (sum(lam) % 2)) * a)) for (lam, a) in self(element)], distinct=True)
class ElementMethods():
def degree_negation(self):
'\n Return the image of ``self`` under the degree negation\n automorphism of the parent of ``self``.\n\n The degree negation is the automorphism which scales every\n homogeneous element of degree `k` by `(-1)^k` (for all `k`).\n\n Calling ``degree_negation(self)`` is equivalent to calling\n ``self.parent().degree_negation(self)``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: f = 2*S[2,1] + 4*S[1,1] - 5*S[1,2] - 3*S[[]]\n sage: f.degree_negation()\n -3*S[] + 4*S[1, 1] + 5*S[1, 2] - 2*S[2, 1]\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: dI = QSym.dualImmaculate()\n sage: f = -3*dI[2,1] + 4*dI[2] + 2*dI[1]\n sage: f.degree_negation()\n -2*dI[1] + 4*dI[2] + 3*dI[2, 1]\n\n TESTS:\n\n The zero element behaves well::\n\n sage: a = S.zero().degree_negation(); a\n 0\n sage: parent(a)\n Non-Commutative Symmetric Functions over the Integer Ring in the Complete basis\n\n .. TODO::\n\n Generalize this to all graded vector spaces?\n '
return self.parent().sum_of_terms([(lam, (((- 1) ** (sum(lam) % 2)) * a)) for (lam, a) in self], distinct=True)
def duality_pairing(self, y):
'\n The duality pairing between elements of `NSym` and elements\n of `QSym`.\n\n The complete basis is dual to the monomial basis with respect\n to this pairing.\n\n INPUT:\n\n - ``y`` -- an element of the dual Hopf algebra of ``self``\n\n OUTPUT:\n\n - The result of pairing ``self`` with ``y``.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).Ribbon()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: R[1,1,2].duality_pairing(F[1,1,2])\n 1\n sage: R[1,2,1].duality_pairing(F[1,1,2])\n 0\n\n ::\n\n sage: L = NonCommutativeSymmetricFunctions(QQ).Elementary()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: L[1,2].duality_pairing(F[1,2])\n 0\n sage: L[1,1,1].duality_pairing(F[1,2])\n 1\n\n '
return self.parent().duality_pairing(self, y)
def skew_by(self, y, side='left'):
"\n The operation which is dual to multiplication by ``y``, where ``y``\n is an element of the dual space of ``self``.\n\n This is calculated through the coproduct of ``self`` and the\n expansion of ``y`` in the dual basis.\n\n INPUT:\n\n - ``y`` -- an element of the dual Hopf algebra of ``self``\n - ``side`` -- (Default='left') Either 'left' or 'right'\n\n OUTPUT:\n\n - The result of skewing ``self`` by ``y``, on the side ``side``\n\n EXAMPLES:\n\n Skewing an element of NCSF by an element of QSym::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: R([2,2,2]).skew_by(F[1,1])\n R[1, 1, 2] + R[1, 2, 1] + R[1, 3] + R[2, 1, 1] + 2*R[2, 2] + R[3, 1] + R[4]\n sage: R([2,2,2]).skew_by(F[2])\n R[1, 1, 2] + R[1, 2, 1] + R[1, 3] + R[2, 1, 1] + 3*R[2, 2] + R[3, 1] + R[4]\n\n Skewing an element of QSym by an element of NCSF::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F[3,2].skew_by(R[1,1])\n 0\n sage: F[3,2].skew_by(R[1,1], side='right')\n 0\n sage: F[3,2].skew_by(S[1,1,1], side='right')\n F[2]\n sage: F[3,2].skew_by(S[1,2], side='right')\n F[2]\n sage: F[3,2].skew_by(S[2,1], side='right')\n 0\n sage: F[3,2].skew_by(S[1,1,1])\n F[2]\n sage: F[3,2].skew_by(S[1,1])\n F[1, 2]\n sage: F[3,2].skew_by(S[1])\n F[2, 2]\n\n ::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M[3,2].skew_by(S[2])\n 0\n sage: M[3,2].skew_by(S[2], side='right')\n M[3]\n sage: M[3,2].skew_by(S[3])\n M[2]\n sage: M[3,2].skew_by(S[3], side='right')\n 0\n "
return self.parent().skew(self, y, side=side)
def degree(self):
'\n The maximum of the degrees of the homogeneous summands.\n\n .. SEEALSO:: :meth:`~sage.categories.graded_algebras_with_basis.GradedAlgebrasWithBasis.ElementMethods.homogeneous_degree`\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: (x, y) = (S[2], S[3])\n sage: x.degree()\n 2\n sage: (x^3 + 4*y^2).degree()\n 6\n sage: ((1 + x)^3).degree()\n 6\n\n ::\n\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: (x, y) = (F[2], F[3])\n sage: x.degree()\n 2\n sage: (x^3 + 4*y^2).degree()\n 6\n sage: ((1 + x)^3).degree()\n 6\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.zero().degree()\n Traceback (most recent call last):\n ...\n ValueError: the zero element does not have a well-defined degree\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F.zero().degree()\n Traceback (most recent call last):\n ...\n ValueError: the zero element does not have a well-defined degree\n '
return self.maximal_degree()
|
class AlgebraMorphism(ModuleMorphismByLinearity):
'\n A class for algebra morphism defined on a free algebra from the image of the generators\n '
def __init__(self, domain, on_generators, position=0, codomain=None, category=None, anti=False):
"\n Given a map on the multiplicative basis of a free algebra, this method\n returns the algebra morphism that is the linear extension of its image\n on generators.\n\n INPUT:\n\n - ``domain`` -- an algebra with a multiplicative basis\n - ``on_generators`` -- a function defined on the index set of the generators\n - ``codomain`` -- the codomain\n - ``position`` -- integer; default is 0\n - ``category`` -- a category; defaults to None\n - ``anti`` -- a boolean; defaults to False\n\n OUTPUT:\n\n - module morphism\n\n EXAMPLES:\n\n We construct explicitly an algebra morphism::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import AlgebraMorphism\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = NCSF.Psi()\n sage: f = AlgebraMorphism(Psi, attrcall('conjugate'), codomain=Psi)\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n\n Usually, however, one constructs algebra morphisms\n using the ``algebra_morphism`` method for an algebra::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = NCSF.Psi()\n sage: def double(i) : return Psi[i,i]\n sage: f = Psi.algebra_morphism(double, codomain = Psi)\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] + 3*Psi[1, 1, 3, 3, 2, 2] + Psi[2, 2, 4, 4]\n sage: f.category()\n Category of endsets of unital magmas and right modules over Rational Field and left modules over Rational Field\n\n When extra properties about the morphism are known, one\n can specify the category of which it is a morphism::\n\n sage: def negate(i): return -Psi[i]\n sage: f = Psi.algebra_morphism(negate, codomain = Psi, category = GradedHopfAlgebrasWithBasis(QQ))\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] - 3*Psi[1, 3, 2] + Psi[2, 4]\n sage: f.category()\n Category of endsets of Hopf algebras over Rational Field and graded modules over Rational Field\n\n If ``anti`` is true, this returns an anti-algebra morphism::\n\n sage: f = Psi.algebra_morphism(double, codomain = Psi, anti=True)\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] + 3*Psi[2, 2, 3, 3, 1, 1] + Psi[4, 4, 2, 2]\n sage: f.category()\n Category of endsets of modules with basis over Rational Field\n\n TESTS::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n sage: f = Psi.algebra_morphism(Phi.antipode_on_generators, codomain=Phi)\n sage: f(Psi[1, 2, 2, 1])\n Phi[1, 2, 2, 1]\n sage: f(Psi[3, 1, 2])\n -Phi[3, 1, 2]\n sage: f.__class__\n <class 'sage.combinat.ncsf_qsym.generic_basis_code.AlgebraMorphism_with_category'>\n sage: TestSuite(f).run(skip=['_test_nonzero_equal'])\n "
assert (position == 0)
assert (codomain is not None)
if (category is None):
if anti:
category = ModulesWithBasis(domain.base_ring())
else:
category = AlgebrasWithBasis(domain.base_ring())
self._anti = anti
self._on_generators = on_generators
ModuleMorphismByLinearity.__init__(self, domain=domain, codomain=codomain, position=position, category=category)
def __eq__(self, other):
'\n Check equality.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n sage: f = Psi.algebra_morphism(Phi.antipode_on_generators, codomain=Phi)\n sage: g = Psi.algebra_morphism(Phi.antipode_on_generators, codomain=Phi)\n sage: f == g\n True\n sage: f is g\n False\n '
return ((self.__class__ is other.__class__) and (self.parent() == other.parent()) and (self._zero == other._zero) and (self._on_generators == other._on_generators) and (self._position == other._position) and (self._is_module_with_basis_over_same_base_ring == other._is_module_with_basis_over_same_base_ring))
def __ne__(self, other):
'\n Check equality.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n sage: f = Psi.algebra_morphism(Phi.antipode_on_generators, codomain=Phi)\n sage: g = Psi.algebra_morphism(Phi.antipode_on_generators, codomain=Phi)\n sage: f != g\n False\n sage: h = Phi.algebra_morphism(Psi.antipode_on_generators, codomain=Psi)\n sage: f != h\n True\n '
return (not (self == other))
def _on_basis(self, c):
'\n Computes the image of this morphism on the basis element indexed by\n ``c``.\n\n INPUT:\n\n - ``c`` -- an iterable that spits out generators\n\n OUTPUT:\n\n - element of the codomain\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import AlgebraMorphism\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = NCSF.Psi()\n sage: Phi = NCSF.Phi()\n sage: f = AlgebraMorphism(Psi, lambda i : Phi[i,i], codomain=Phi)\n sage: f._on_basis([ 3, 2 ])\n Phi[3, 3, 2, 2]\n\n '
if self._anti:
c = reversed(c)
return self.codomain().prod((self._on_generators(i) for i in c))
|
class GradedModulesWithInternalProduct(Category_over_base_ring):
'\n Constructs the class of modules with internal product. This is used to give an internal\n product structure to the non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import GradedModulesWithInternalProduct\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: R in GradedModulesWithInternalProduct(QQ)\n True\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.combinat.ncsf_qsym.generic_basis_code import GradedModulesWithInternalProduct\n sage: GradedModulesWithInternalProduct(ZZ).super_categories()\n [Category of graded modules over Integer Ring]\n '
from sage.categories.graded_modules import GradedModules
R = self.base_ring()
return [GradedModules(R)]
class ParentMethods():
@abstract_method(optional=True)
def internal_product_on_basis(self, I, J):
'\n The internal product of the two basis elements indexed by ``I`` and\n ``J`` (optional)\n\n INPUT:\n\n - ``I``, ``J`` -- compositions indexing two elements of the basis of self\n\n Returns the internal product of the corresponding basis elements.\n If this method is implemented, the internal product is defined from\n it by linearity.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S.internal_product_on_basis([2,2], [1,2,1])\n 2*S[1, 1, 1, 1] + S[1, 1, 2] + S[2, 1, 1]\n sage: S.internal_product_on_basis([2,2], [2,1])\n 0\n '
@lazy_attribute
def internal_product(self):
'\n The bilinear product inherited from the isomorphism with\n the descent algebra.\n\n This is constructed by extending the method\n :meth:`internal_product_on_basis` bilinearly, if available,\n or using the method\n :meth:`~GradedModulesWithInternalProduct.Realizations.ParentMethods.internal_product_by_coercion`.\n\n OUTPUT:\n\n - The internal product map of the algebra the non-commutative\n symmetric functions.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S.internal_product\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n sage: S.internal_product(S[2,2], S[1,2,1])\n 2*S[1, 1, 1, 1] + S[1, 1, 2] + S[2, 1, 1]\n sage: S.internal_product(S[2,2], S[1,2])\n 0\n\n ::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: R.internal_product\n <bound method ....internal_product_by_coercion ...>\n sage: R.internal_product_by_coercion(R[1, 1], R[1,1])\n R[2]\n sage: R.internal_product(R[2,2], R[1,2])\n 0\n\n '
if (self.internal_product_on_basis is not NotImplemented):
return self.module_morphism(self.module_morphism(self.internal_product_on_basis, position=0, codomain=self), position=1)
else:
return self.internal_product_by_coercion
itensor = internal_product
kronecker_product = internal_product
class ElementMethods():
def internal_product(self, other):
'\n Return the internal product of two non-commutative\n symmetric functions.\n\n The internal product on the algebra of non-commutative symmetric\n functions is adjoint to the internal coproduct on the algebra of\n quasisymmetric functions with respect to the duality pairing\n between these two algebras. This means, explicitly, that any\n two non-commutative symmetric functions `f` and `g` and any\n quasi-symmetric function `h` satisfy\n\n .. MATH::\n\n \\langle f * g, h \\rangle\n = \\sum_i \\left\\langle f, h^{\\prime}_i \\right\\rangle\n \\left\\langle g, h^{\\prime\\prime}_i \\right\\rangle,\n\n where we write `\\Delta^{\\times}(h)` as `\\sum_i h^{\\prime}_i\n \\otimes h^{\\prime\\prime}_i`. Here, `f * g` denotes the internal\n product of the non-commutative symmetric functions `f` and `g`.\n\n If `f` and `g` are two homogeneous elements of `NSym` having\n distinct degrees, then the internal product `f * g` is zero.\n\n Explicit formulas can be given for internal products of\n elements of the complete and the Psi bases. First, the formula\n for the Complete basis ([NCSF1]_ Proposition 5.1): If `I` and\n `J` are two compositions of lengths `p` and `q`, respectively,\n then the corresponding Complete homogeneous non-commutative\n symmetric functions `S^I` and `S^J` have internal product\n\n .. MATH::\n\n S^I * S^J = \\sum S^{\\operatorname*{comp}M},\n\n where the sum ranges over all `p \\times q`-matrices\n `M \\in \\NN^{p \\times q}` (with nonnegative integers as\n entries) whose row sum vector is `I` (that is, the sum of the\n entries of the `r`-th row is the `r`-th part of `I` for all\n `r`) and whose column sum vector is `J` (that is, the sum of\n all entries of the `s`-th row is the `s`-th part of `J` for\n all `s`). Here, for any `M \\in \\NN^{p \\times q}`, we denote\n by `\\operatorname*{comp}M` the composition obtained by\n reading the entries of the matrix `M` in the usual order\n (row by row, proceeding left to right in each row,\n traversing the rows from top to bottom).\n\n The formula on the Psi basis ([NCSF2]_ Lemma 3.10) is more\n complicated. Let `I` and `J` be two compositions of lengths\n `p` and `q`, respectively, having the same size `|I| = |J|`.\n We denote by `\\Psi^K` the element of the Psi basis\n corresponding to any composition `K`.\n\n - If `p > q`, then `\\Psi^I * \\Psi^J` is plainly `0`.\n\n - Assume that `p = q`. Let `\\widetilde{\\delta}_{I, J}` denote\n the integer `1` if the compositions `I` and `J` are\n permutations of each other, and the integer `0` otherwise.\n For every positive integer `i`, let `m_i` denote the number\n of parts of `I` equal to `i`. Then, `\\Psi^I * \\Psi^J` equals\n `\\widetilde{\\delta}_{I, J} \\prod_{i>0} i^{m_i} m_i! \\Psi^I`.\n\n - Now assume that `p < q`. Write the composition `I` as\n `I = (i_1, i_2, \\ldots, i_p)`. For every nonempty\n composition `K = (k_1, k_2, \\ldots, k_s)`, denote by\n `\\Gamma_K` the non-commutative symmetric function\n `k_1 [\\ldots [[\\Psi_{k_1}, \\Psi_{k_2}], \\Psi_{k_3}],\n \\ldots \\Psi_{k_s}]`. For any subset `A` of\n `\\{ 1, 2, \\ldots, q \\}`, let `J_A` be the composition\n obtained from `J` by removing the `r`-th parts for all\n `r \\notin A` (while keeping the `r`-th parts for all\n `r \\in A` in order). Then, `\\Psi^I * \\Psi^J` equals the\n sum of `\\Gamma_{J_{K_1}} \\Gamma_{J_{K_2}} \\cdots\n \\Gamma_{J_{K_p}}` over all ordered set partitions\n `(K_1, K_2, \\ldots, K_p)` of `\\{ 1, 2, \\ldots, q \\}`\n into `p` parts such that each `1 \\leq k \\leq p` satisfies\n `\\left\\lvert J_{K_k} \\right\\rvert = i_k`.\n (See\n :meth:`~sage.combinat.set_partition_ordered.OrderedSetPartition`\n for the meaning of "ordered set partition".)\n\n Aliases for :meth:`internal_product()` are :meth:`itensor()` and\n :meth:`kronecker_product()`.\n\n INPUT:\n\n - ``other`` -- another non-commutative symmetric function\n\n OUTPUT:\n\n - The result of taking the internal product of ``self`` with\n ``other``.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: x = S.an_element(); x\n 2*S[] + 2*S[1] + 3*S[1, 1]\n sage: x.internal_product(S[2])\n 3*S[1, 1]\n sage: x.internal_product(S[1])\n 2*S[1]\n sage: S[1,2].internal_product(S[1,2])\n S[1, 1, 1] + S[1, 2]\n\n Let us check the duality between the inner product and the inner\n coproduct in degree `4`::\n\n sage: M = QuasiSymmetricFunctions(FiniteField(29)).M()\n sage: S = NonCommutativeSymmetricFunctions(FiniteField(29)).S()\n sage: def tensor_incopr(f, g, h): # computes \\sum_i \\left< f, h\'_i \\right> \\left< g, h\'\'_i \\right>\n ....: result = h.base_ring().zero()\n ....: h_parent = h.parent()\n ....: for partition_pair, coeff in h.internal_coproduct().monomial_coefficients().items():\n ....: result += coeff * f.duality_pairing(h_parent[partition_pair[0]]) * g.duality_pairing(h_parent[partition_pair[1]])\n ....: return result\n sage: def testall(n):\n ....: return all( all( all( tensor_incopr(S[u], S[v], M[w]) == (S[u].itensor(S[v])).duality_pairing(M[w])\n ....: for w in Compositions(n) )\n ....: for v in Compositions(n) )\n ....: for u in Compositions(n) )\n sage: testall(2)\n True\n sage: testall(3) # long time\n True\n sage: testall(4) # not tested, too long\n True\n\n The internal product on the algebra of non-commutative symmetric\n functions commutes with the canonical commutative projection on\n the symmetric functions::\n\n sage: S = NonCommutativeSymmetricFunctions(ZZ).S()\n sage: e = SymmetricFunctions(ZZ).e()\n sage: def int_pr_of_S_in_e(I, J):\n ....: return (S[I].internal_product(S[J])).to_symmetric_function()\n sage: all( all( int_pr_of_S_in_e(I, J)\n ....: == S[I].to_symmetric_function().internal_product(S[J].to_symmetric_function())\n ....: for I in Compositions(3) )\n ....: for J in Compositions(3) )\n True\n '
return self.parent().internal_product(self, other)
itensor = internal_product
kronecker_product = internal_product
class Realizations(RealizationsCategory):
class ParentMethods():
def internal_product_by_coercion(self, left, right):
'\n Internal product of ``left`` and ``right``.\n\n This is a default implementation that computes\n the internal product in the realization specified\n by ``self.realization_of().a_realization()``.\n\n INPUT:\n\n - ``left`` -- an element of the non-commutative symmetric functions\n - ``right`` -- an element of the non-commutative symmetric functions\n\n OUTPUT:\n\n - The internal product of ``left`` and ``right``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.internal_product_by_coercion(S[2,1], S[3])\n S[2, 1]\n sage: S.internal_product_by_coercion(S[2,1], S[4])\n 0\n '
R = self.realization_of().a_realization()
return self(R.internal_product(R(left), R(right)))
|
class NonCommutativeSymmetricFunctions(UniqueRepresentation, Parent):
'\n The abstract algebra of non-commutative symmetric functions.\n\n We construct the abstract algebra of non-commutative symmetric\n functions over the rational numbers::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: NCSF\n Non-Commutative Symmetric Functions over the Rational Field\n sage: S = NCSF.complete()\n sage: R = NCSF.ribbon()\n sage: S[2,1]*R[1,2]\n S[2, 1, 1, 2] - S[2, 1, 3]\n\n NCSF is the unique free (non-commutative!) graded connected algebra with\n one generator in each degree::\n\n sage: NCSF.category()\n Join of Category of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of monoids with realizations\n and Category of graded coalgebras over Rational Field\n and Category of coalgebras over Rational Field with realizations\n and Category of cocommutative coalgebras over Rational Field\n\n sage: [S[i].degree() for i in range(10)]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n We use the Sage standard renaming idiom to get shorter outputs::\n\n sage: NCSF.rename("NCSF")\n sage: NCSF\n NCSF\n\n NCSF has many representations as a concrete algebra. Each of them\n has a distinguished basis, and its elements are expanded in this\n basis. Here is the `\\Psi`\n (:class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Psi`)\n representation::\n\n sage: Psi = NCSF.Psi()\n sage: Psi\n NCSF in the Psi basis\n\n Elements of ``Psi`` are linear combinations of basis elements indexed\n by compositions::\n\n sage: Psi.an_element()\n 2*Psi[] + 2*Psi[1] + 3*Psi[1, 1]\n\n The basis itself is accessible through::\n\n sage: Psi.basis()\n Lazy family (Term map from Compositions of non-negative integers...\n sage: Psi.basis().keys()\n Compositions of non-negative integers\n\n To construct an element one can therefore do::\n\n sage: Psi.basis()[Composition([2,1,3])]\n Psi[2, 1, 3]\n\n As this is rather cumbersome, the following abuses of notation are\n allowed::\n\n sage: Psi[Composition([2, 1, 3])]\n Psi[2, 1, 3]\n sage: Psi[[2, 1, 3]]\n Psi[2, 1, 3]\n sage: Psi[2, 1, 3]\n Psi[2, 1, 3]\n\n or even::\n\n sage: Psi[(i for i in [2, 1, 3])]\n Psi[2, 1, 3]\n\n Unfortunately, due to a limitation in Python syntax, one cannot use::\n\n sage: Psi[] # not implemented\n\n Instead, you can use::\n\n sage: Psi[[]]\n Psi[]\n\n Now, we can construct linear combinations of basis elements::\n\n sage: Psi[2,1,3] + 2 * (Psi[4] + Psi[2,1])\n 2*Psi[2, 1] + Psi[2, 1, 3] + 2*Psi[4]\n\n .. rubric:: Algebra structure\n\n To start with, ``Psi`` is a graded algebra, the grading being induced by\n the size of compositions. The one is the basis element indexed by the empty\n composition::\n\n sage: Psi.one()\n Psi[]\n sage: S.one()\n S[]\n sage: R.one()\n R[]\n\n As we have seen above, the ``Psi`` basis is multiplicative; that is\n multiplication is induced by linearity from the concatenation of\n compositions::\n\n sage: Psi[1,3] * Psi[2,1]\n Psi[1, 3, 2, 1]\n sage: (Psi.one() + 2 * Psi[1,3]) * Psi[2, 4]\n 2*Psi[1, 3, 2, 4] + Psi[2, 4]\n\n .. rubric:: Hopf algebra structure\n\n ``Psi`` is further endowed with a coalgebra structure. The coproduct\n is an algebra morphism, and therefore determined by its values on\n the generators; those are primitive::\n\n sage: Psi[1].coproduct()\n Psi[] # Psi[1] + Psi[1] # Psi[]\n sage: Psi[2].coproduct()\n Psi[] # Psi[2] + Psi[2] # Psi[]\n\n The coproduct, being cocommutative on the generators, is\n cocommutative everywhere::\n\n sage: Psi[1,2].coproduct()\n Psi[] # Psi[1, 2] + Psi[1] # Psi[2] + Psi[1, 2] # Psi[] + Psi[2] # Psi[1]\n\n The algebra and coalgebra structures on ``Psi`` combine to form a\n bialgebra structure, which cooperates with the grading to form a\n connected graded bialgebra. Thus, as any connected graded bialgebra,\n ``Psi`` is a Hopf algebra. Over ``QQ`` (or any other `\\QQ`-algebra),\n this Hopf algebra ``Psi`` is isomorphic to the tensor algebra of\n its space of primitive elements.\n\n The antipode is an anti-algebra morphism; in the ``Psi`` basis, it\n sends the generators to their opposites and changes their sign if\n they are of odd degree::\n\n sage: Psi[3].antipode()\n -Psi[3]\n sage: Psi[1,3,2].antipode()\n -Psi[2, 3, 1]\n sage: Psi[1,3,2].coproduct().apply_multilinear_morphism(lambda be,ga: Psi(be)*Psi(ga).antipode())\n 0\n\n The counit is defined by sending all elements of positive degree to\n zero::\n\n sage: S[3].degree(), S[3,1,2].degree(), S.one().degree()\n (3, 6, 0)\n sage: S[3].counit()\n 0\n sage: S[3,1,2].counit()\n 0\n sage: S.one().counit()\n 1\n sage: (S[3] - 2*S[3,1,2] + 7).counit()\n 7\n sage: (R[3] - 2*R[3,1,2] + 7).counit()\n 7\n\n It is possible to change the prefix used to display the basis\n elements using the method\n :meth:`~sage.structure.indexed_generators.IndexedGenerators.print_options`.\n Say that for instance one wanted to display the\n :class:`~NonCommutativeSymmetricFunctions.Complete` basis as having\n a prefix ``H`` instead of the default ``S``::\n\n sage: H = NCSF.complete()\n sage: H.an_element()\n 2*S[] + 2*S[1] + 3*S[1, 1]\n sage: H.print_options(prefix=\'H\')\n sage: H.an_element()\n 2*H[] + 2*H[1] + 3*H[1, 1]\n sage: H.print_options(prefix=\'S\') #restore to \'S\'\n\n .. rubric:: Concrete representations\n\n NCSF admits the concrete realizations defined in [NCSF1]_::\n\n sage: Phi = NCSF.Phi()\n sage: Psi = NCSF.Psi()\n sage: ribbon = NCSF.ribbon()\n sage: complete = NCSF.complete()\n sage: elementary = NCSF.elementary()\n\n To change from one basis to another, one simply does::\n\n sage: Phi(Psi[1])\n Phi[1]\n sage: Phi(Psi[3])\n -1/4*Phi[1, 2] + 1/4*Phi[2, 1] + Phi[3]\n\n In general, one can mix up different bases in computations::\n\n sage: Phi[1] * Psi[1]\n Phi[1, 1]\n\n Some of the changes of basis are easy to guess::\n\n sage: ribbon(complete[1,3,2])\n R[1, 3, 2] + R[1, 5] + R[4, 2] + R[6]\n\n This is the sum of all fatter compositions. Using the usual\n Möbius function for the boolean lattice, the inverse change of\n basis is given by the alternating sum of all fatter compositions::\n\n sage: complete(ribbon[1,3,2])\n S[1, 3, 2] - S[1, 5] - S[4, 2] + S[6]\n\n The analogue of the elementary basis is the sum over\n all finer compositions than the \'complement\' of the composition\n in the ribbon basis::\n\n sage: Composition([1,3,2]).complement()\n [2, 1, 2, 1]\n sage: ribbon(elementary([1,3,2]))\n R[1, 1, 1, 1, 1, 1] + R[1, 1, 1, 2, 1] + R[2, 1, 1, 1, 1] + R[2, 1, 2, 1]\n\n By Möbius inversion on the composition poset, the ribbon\n basis element corresponding to a composition `I` is then the\n alternating sum over all compositions fatter than the\n complement composition of `I` in the elementary basis::\n\n sage: elementary(ribbon[2,1,2,1])\n L[1, 3, 2] - L[1, 5] - L[4, 2] + L[6]\n\n The `\\Phi`\n (:class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Phi`)\n and `\\Psi` bases are computed by changing to and from the\n :class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Complete`\n basis. The expansion of `\\Psi` basis is given in Proposition 4.5\n of [NCSF1]_ by the formulae\n\n .. MATH::\n\n S^I = \\sum_{J \\geq I} \\frac{1}{\\pi_u(J,I)} \\Psi^J\n\n and\n\n .. MATH::\n\n \\Psi^I = \\sum_{J \\geq I} (-1)^{\\ell(J)-\\ell(I)} lp(J,I) S^J\n\n where the coefficients `\\pi_u(J,I)` and `lp(J,I)` are coefficients in the\n methods :meth:`~sage.combinat.ncsf_qsym.combinatorics.coeff_pi` and\n :meth:`~sage.combinat.ncsf_qsym.combinatorics.coeff_lp` respectively. For\n example::\n\n sage: Psi(complete[3])\n 1/6*Psi[1, 1, 1] + 1/3*Psi[1, 2] + 1/6*Psi[2, 1] + 1/3*Psi[3]\n sage: complete(Psi[3])\n S[1, 1, 1] - 2*S[1, 2] - S[2, 1] + 3*S[3]\n\n The\n :class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Phi`\n basis is another analogue of the power sum basis from the algebra of\n symmetric functions and the expansion in the Complete basis is given in\n Proposition 4.9 of [NCSF1]_ by the formulae\n\n .. MATH::\n\n S^I = \\sum_{J \\geq I} \\frac{1}{sp(J,I)} \\Phi^J\n\n and\n\n .. MATH::\n\n \\Phi^I = \\sum_{J \\geq I} (-1)^{\\ell(J)-\\ell(I)}\n \\frac{\\prod_i I_i}{\\ell(J,I)} S^J\n\n where the coefficients `sp(J,I)` and `\\ell(J,I)` are coefficients in the\n methods :meth:`~sage.combinat.ncsf_qsym.combinatorics.coeff_sp` and\n :meth:`~sage.combinat.ncsf_qsym.combinatorics.coeff_ell` respectively.\n For example::\n\n sage: Phi(complete[3])\n 1/6*Phi[1, 1, 1] + 1/4*Phi[1, 2] + 1/4*Phi[2, 1] + 1/3*Phi[3]\n sage: complete(Phi[3])\n S[1, 1, 1] - 3/2*S[1, 2] - 3/2*S[2, 1] + 3*S[3]\n\n Here is how to fetch the conversion morphisms::\n\n sage: f = complete.coerce_map_from(elementary); f\n Generic morphism:\n From: NCSF in the Elementary basis\n To: NCSF in the Complete basis\n sage: g = elementary.coerce_map_from(complete); g\n Generic morphism:\n From: NCSF in the Complete basis\n To: NCSF in the Elementary basis\n sage: f.category()\n Category of homsets of unital magmas and right modules over Rational Field and\n left modules over Rational Field\n sage: f(elementary[1,2,2])\n S[1, 1, 1, 1, 1] - S[1, 1, 1, 2] - S[1, 2, 1, 1] + S[1, 2, 2]\n sage: g(complete[1,2,2])\n L[1, 1, 1, 1, 1] - L[1, 1, 1, 2] - L[1, 2, 1, 1] + L[1, 2, 2]\n sage: h = f*g; h\n Composite map:\n From: NCSF in the Complete basis\n To: NCSF in the Complete basis\n Defn: Generic morphism:\n From: NCSF in the Complete basis\n To: NCSF in the Elementary basis\n then\n Generic morphism:\n From: NCSF in the Elementary basis\n To: NCSF in the Complete basis\n sage: h(complete[1,3,2])\n S[1, 3, 2]\n\n .. rubric:: Additional concrete representations\n\n NCSF has some additional bases which appear in the literature::\n\n sage: Monomial = NCSF.Monomial()\n sage: Immaculate = NCSF.Immaculate()\n sage: dualQuasisymmetric_Schur = NCSF.dualQuasisymmetric_Schur()\n\n The :class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Monomial`\n basis was introduced in [Tev2007]_ and the\n :class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Immaculate`\n basis was introduced in [BBSSZ2012]_. The\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Quasisymmetric_Schur`\n were defined in [QSCHUR]_ and the dual basis is implemented here as\n :class:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.dualQuasisymmetric_Schur`.\n Refer to the documentation for the use and definition of these bases.\n\n .. TODO::\n\n - implement fundamental, forgotten, and simple (coming\n from the simple modules of HS_n) bases.\n\n We revert back to the original name from our custom short name NCSF::\n\n sage: NCSF\n NCSF\n sage: NCSF.rename()\n sage: NCSF\n Non-Commutative Symmetric Functions over the Rational Field\n\n TESTS::\n\n sage: TestSuite(Phi).run()\n sage: TestSuite(Psi).run()\n sage: TestSuite(complete).run()\n\n '
def __init__(self, R):
'\n TESTS::\n\n sage: NCSF1 = NonCommutativeSymmetricFunctions(FiniteField(23))\n sage: NCSF2 = NonCommutativeSymmetricFunctions(Integers(23))\n sage: TestSuite(NonCommutativeSymmetricFunctions(QQ)).run()\n '
assert ((R in Fields()) or (R in Rings()))
self._base = R
cat = GradedHopfAlgebras(R).WithRealizations().Cocommutative()
Parent.__init__(self, category=cat)
Psi = self.Psi()
Phi = self.Phi()
complete = self.complete()
elementary = self.elementary()
ribbon = self.ribbon()
complete.module_morphism(ribbon.sum_of_fatter_compositions, codomain=ribbon).register_as_coercion()
ribbon.module_morphism(complete.alternating_sum_of_fatter_compositions, codomain=complete).register_as_coercion()
complete.algebra_morphism(elementary.alternating_sum_of_compositions, codomain=elementary).register_as_coercion()
elementary.algebra_morphism(complete.alternating_sum_of_compositions, codomain=complete).register_as_coercion()
complete.algebra_morphism(Psi._from_complete_on_generators, codomain=Psi).register_as_coercion()
Psi.algebra_morphism(Psi._to_complete_on_generators, codomain=complete).register_as_coercion()
complete.algebra_morphism(Phi._from_complete_on_generators, codomain=Phi).register_as_coercion()
Phi.algebra_morphism(Phi._to_complete_on_generators, codomain=complete).register_as_coercion()
def _repr_(self):
"\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(ZZ)\n sage: N._repr_()\n 'Non-Commutative Symmetric Functions over the Integer Ring'\n "
return ('Non-Commutative Symmetric Functions over the %s' % self.base_ring())
def a_realization(self):
'\n Gives a realization of the algebra of non-commutative symmetric functions. This\n particular realization is the complete basis of non-commutative symmetric functions.\n\n OUTPUT:\n\n - The realization of the non-commutative symmetric functions in the\n complete basis.\n\n EXAMPLES::\n\n sage: NonCommutativeSymmetricFunctions(ZZ).a_realization()\n Non-Commutative Symmetric Functions over the Integer Ring in the Complete basis\n '
return self.complete()
_shorthands = tuple(['S', 'R', 'L', 'Phi', 'Psi', 'nM', 'I', 'dQS', 'dYQS', 'ZL', 'ZR'])
def dual(self):
'\n Return the dual to the non-commutative symmetric functions.\n\n OUTPUT:\n\n - The dual of the non-commutative symmetric functions over a ring. This\n is the algebra of quasi-symmetric functions over the ring.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: NCSF.dual()\n Quasisymmetric functions over the Rational Field\n '
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
return QuasiSymmetricFunctions(self.base_ring())
class Bases(Category_realization_of_parent):
'\n Category of bases of non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.Bases()\n Category of bases of Non-Commutative Symmetric Functions over the Rational Field\n sage: R = N.Ribbon()\n sage: R in N.Bases()\n True\n '
def super_categories(self):
'\n Return the super categories of the category of bases of the\n non-commutative symmetric functions.\n\n OUTPUT:\n\n - list\n\n TESTS::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.Bases().super_categories()\n [Category of bases of Non-Commutative Symmetric Functions or Quasisymmetric functions over the Rational Field,\n Category of realizations of graded modules with internal product over Rational Field]\n\n '
R = self.base().base_ring()
from .generic_basis_code import GradedModulesWithInternalProduct
return [BasesOfQSymOrNCSF(self.base()), GradedModulesWithInternalProduct(R).Realizations()]
class ParentMethods():
def to_symmetric_function_on_basis(self, I):
'\n The image of the basis element indexed by ``I`` under the map\n to the symmetric functions.\n\n This default implementation does a change of basis and\n computes the image in the complete basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The image of the non-commutative basis element of\n ``self`` indexed by the composition ``I`` under the map from\n non-commutative symmetric functions to the symmetric\n functions. This will be a symmetric function.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: I = N.Immaculate()\n sage: I.to_symmetric_function(I[1,3])\n -h[2, 2] + h[3, 1]\n sage: I.to_symmetric_function(I[1,2])\n 0\n sage: Phi = N.Phi()\n sage: Phi.to_symmetric_function_on_basis([3,1,2])==Phi.to_symmetric_function(Phi[3,1,2])\n True\n sage: Phi.to_symmetric_function_on_basis([])\n h[]\n '
S = self.realization_of().complete()
return S.to_symmetric_function(S(self[I]))
@lazy_attribute
def to_symmetric_function(self):
'\n Morphism to the algebra of symmetric functions.\n\n This is constructed by extending the computation on the basis\n or by coercion to the complete basis.\n\n OUTPUT:\n\n - The module morphism from the basis ``self`` to the symmetric\n functions which corresponds to taking a commutative image.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: x = R.an_element(); x\n 2*R[] + 2*R[1] + 3*R[1, 1]\n sage: R.to_symmetric_function(x)\n 2*s[] + 2*s[1] + 3*s[1, 1]\n sage: nM = N.Monomial()\n sage: nM.to_symmetric_function(nM[3,1])\n h[1, 1, 1, 1] - 7/2*h[2, 1, 1] + h[2, 2] + 7/2*h[3, 1] - 2*h[4]\n '
on_basis = self.to_symmetric_function_on_basis
codom = on_basis([]).parent()
return self.module_morphism(on_basis, codomain=codom)
def immaculate_function(self, xs):
'\n Return the immaculate function corresponding to the\n integer vector ``xs``, written in the basis ``self``.\n\n If `\\alpha` is any integer vector -- i.e., an element of\n `\\ZZ^m` for some `m \\in \\NN` --, the *immaculate function\n corresponding to* `\\alpha` is a non-commutative symmetric\n function denoted by `\\mathfrak{S}_{\\alpha}`. One way to\n define this function is by setting\n\n .. MATH::\n\n \\mathfrak{S}_{\\alpha}\n = \\sum_{\\sigma \\in S_m} (-1)^{\\sigma}\n S_{\\alpha_1 + \\sigma(1) - 1}\n S_{\\alpha_2 + \\sigma(2) - 2}\n \\cdots\n S_{\\alpha_m + \\sigma(m) - m},\n\n where `\\alpha` is written in the form\n `(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)`, and where `S`\n stands for the complete basis\n (:class:`~NonCommutativeSymmetricFunctions.Complete`).\n\n The immaculate function `\\mathfrak{S}_{\\alpha}` first\n appeared in [BBSSZ2012]_ (where it was defined\n differently, but the definition we gave above appeared as\n Theorem 3.27).\n\n The immaculate functions `\\mathfrak{S}_{\\alpha}` for\n `\\alpha` running over all compositions (i.e., finite\n sequences of positive integers) form a basis of `NCSF`.\n This is the *immaculate basis*\n (:class:`~NonCommutativeSymmetricFunctions.Immaculate`).\n\n INPUT:\n\n - ``xs`` -- list (or tuple or any iterable -- possibly a\n composition) of integers\n\n OUTPUT:\n\n The immaculate function `\\mathfrak{S}_{xs}`\n written in the basis ``self``.\n\n EXAMPLES:\n\n Let us first check that, for ``xs`` a composition, we get\n the same as the result of\n ``self.realization_of().I()[xs]``::\n\n sage: def test_comp(xs):\n ....: NSym = NonCommutativeSymmetricFunctions(QQ)\n ....: I = NSym.I()\n ....: return I[xs] == I.immaculate_function(xs)\n sage: def test_allcomp(n):\n ....: return all( test_comp(c) for c in Compositions(n) )\n sage: test_allcomp(1)\n True\n sage: test_allcomp(2)\n True\n sage: test_allcomp(3)\n True\n\n Now some examples of non-composition immaculate\n functions::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: I = NSym.I()\n sage: I.immaculate_function([0, 1])\n 0\n sage: I.immaculate_function([0, 2])\n -I[1, 1]\n sage: I.immaculate_function([-1, 1])\n -I[]\n sage: I.immaculate_function([2, -1])\n 0\n sage: I.immaculate_function([2, 0])\n I[2]\n sage: I.immaculate_function([2, 0, 1])\n 0\n sage: I.immaculate_function([1, 0, 2])\n -I[1, 1, 1]\n sage: I.immaculate_function([2, 0, 2])\n -I[2, 1, 1]\n sage: I.immaculate_function([0, 2, 0, 2])\n I[1, 1, 1, 1] + I[1, 2, 1]\n sage: I.immaculate_function([2, 0, 2, 0, 2])\n I[2, 1, 1, 1, 1] + I[2, 1, 2, 1]\n\n TESTS:\n\n Basis-independence::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: L = NSym.L()\n sage: S = NSym.S()\n sage: L(S.immaculate_function([0, 2, 0, 2])) == L.immaculate_function([0, 2, 0, 2])\n True\n '
S = self.realization_of().S()
res = S.zero()
m = len(xs)
ys = [((xs_i - i) - 1) for (i, xs_i) in enumerate(xs)]
for s in Permutations(m):
psco = [(ys[i] + s_i) for (i, s_i) in enumerate(s)]
if (not all(((j >= 0) for j in psco))):
continue
psco2 = [j for j in psco if (j != 0)]
pr = (s.sign() * S[psco2])
res += pr
return self(res)
class ElementMethods():
def verschiebung(self, n):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined\n to be the map from the `\\mathbf{k}`-algebra of noncommutative\n symmetric functions to itself that sends the complete function\n `S^I` indexed by a composition `I = (i_1, i_2, \\ldots , i_k)`\n to `S^{(i_1/n, i_2/n, \\ldots , i_k/n)}` if all of the numbers\n `i_1, i_2, \\ldots, i_k` are divisible by `n`, and to `0`\n otherwise. This operator `\\mathbf{V}_n` is a Hopf algebra\n endomorphism. For every positive integer `r` with `n \\mid r`,\n it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = S_{r/n},\n \\quad \\mathbf{V}_n(\\Lambda_r) = (-1)^{r - r/n} \\Lambda_{r/n},\n \\quad \\mathbf{V}_n(\\Psi_r) = n \\Psi_{r/n},\n \\quad \\mathbf{V}_n(\\Phi_r) = n \\Phi_{r/n}\n\n (where `S_r` denotes the `r`-th complete non-commutative\n symmetric function, `\\Lambda_r` denotes the `r`-th elementary\n non-commutative symmetric function, `\\Psi_r` denotes the `r`-th\n power-sum non-commutative symmetric function of the first kind,\n and `\\Phi_r` denotes the `r`-th power-sum non-commutative\n symmetric function of the second kind). For every positive\n integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = \\mathbf{V}_n(\\Lambda_r)\n = \\mathbf{V}_n(\\Psi_r) = \\mathbf{V}_n(\\Phi_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism.\n\n It is a lift of the `n`-th Verschiebung operator on the ring\n of symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung`)\n to the ring of noncommutative symmetric functions.\n\n The action of the `n`-th Verschiebung operator can also be\n described on the ribbon Schur functions. Namely, every\n composition `I` of size `n \\ell` satisfies\n\n .. MATH::\n\n \\mathbf{V}_n ( R_I )\n = (-1)^{\\ell(I) - \\ell(J)} \\cdot R_{J / n},\n\n where `J` denotes the meet of the compositions `I` and\n `(\\underbrace{n, n, \\ldots, n}_{|I|/n \\mbox{ times}})`,\n where `\\ell(I)` is the length of `I`, and\n where `J / n` denotes the composition obtained by dividing\n every entry of `J` by `n`.\n For a composition `I` of size not divisible by `n`, we have\n `\\mathbf{V}_n( R_I ) = 0`.\n\n .. SEEALSO::\n\n :meth:`frobenius method of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius>`,\n :meth:`verschiebung method of Sym\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of noncommutative symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: S[3,2].verschiebung(2)\n 0\n sage: S[6,4].verschiebung(2)\n S[3, 2]\n sage: (S[9,1] - S[8,2] + 2*S[6,4] - 3*S[3] + 4*S[[]]).verschiebung(2)\n 4*S[] + 2*S[3, 2] - S[4, 1]\n sage: (S[3,3] - 2*S[2]).verschiebung(3)\n S[1, 1]\n sage: S([4,2]).verschiebung(1)\n S[4, 2]\n sage: R = NSym.R()\n sage: R([4,2]).verschiebung(2)\n R[2, 1]\n\n Being Hopf algebra endomorphisms, the Verschiebung operators\n commute with the antipode::\n\n sage: all( R(I).verschiebung(2).antipode()\n ....: == R(I).antipode().verschiebung(2)\n ....: for I in Compositions(4) )\n True\n\n They lift the Verschiebung operators of the ring of symmetric\n functions::\n\n sage: all( S(I).verschiebung(2).to_symmetric_function()\n ....: == S(I).to_symmetric_function().verschiebung(2)\n ....: for I in Compositions(4) )\n True\n\n The Frobenius operators on `QSym` are adjoint to the\n Verschiebung operators on `NSym` with respect to the duality\n pairing::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: M = QSym.M()\n sage: all( all( M(I).frobenius(3).duality_pairing(S(J))\n ....: == M(I).duality_pairing(S(J).verschiebung(3))\n ....: for I in Compositions(2) )\n ....: for J in Compositions(3) )\n True\n '
parent = self.parent()
S = parent.realization_of().S()
C = parent._indices
dct = {C([(i // n) for i in I]): coeff for (I, coeff) in S(self) if all((((i % n) == 0) for i in I))}
return parent(S._from_dict(dct))
def bernstein_creation_operator(self, n):
'\n Return the image of ``self`` under the `n`-th Bernstein\n creation operator.\n\n Let `n` be an integer. The `n`-th Bernstein creation\n operator `\\mathbb{B}_n` is defined as the endomorphism of\n the space `NSym` of noncommutative symmetric functions\n which sends every `f` to\n\n .. MATH::\n\n \\sum_{i \\geq 0} (-1)^i H_{n+i} F_{1^i}^\\perp,\n\n where usual notations are in place (the letter `H` stands\n for the complete basis of `NSym`, the letter `F` stands\n for the fundamental basis of the algebra `QSym` of\n quasisymmetric functions, and `F_{1^i}^\\perp` means\n skewing (:meth:`~sage.combinat.ncsf_qsym.generic_basis_code.BasesOfQSymOrNCSF.ElementMethods.skew_by`)\n by `F_{1^i}`). Notice that `F_{1^i}` is nothing other than the\n elementary symmetric function `e_i`.\n\n This has been introduced in [BBSSZ2012]_, section 3.1, in\n analogy to the Bernstein creation operators on the\n symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.bernstein_creation_operator`),\n and studied further in [BBSSZ2012]_, mainly in the context\n of immaculate functions\n (:class:`~NonCommutativeSymmetricFunctions.Immaculate`).\n In fact, if `(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)` is\n an `m`-tuple of integers, then\n\n .. MATH::\n\n \\mathbb{B}_n I_{(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)}\n = I_{(n, \\alpha_1, \\alpha_2, \\ldots, \\alpha_m)},\n\n where `I_{(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)}` is the\n immaculate function associated to the `m`-tuple\n `(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)` (see\n :meth:`~NonCommutativeSymmetricFunctions.Bases.ParentMethods.immaculate_function`).\n\n EXAMPLES:\n\n We get the immaculate functions by repeated application of\n Bernstein creation operators::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: I = NSym.I()\n sage: S = NSym.S()\n sage: def immaculate_by_bernstein(xs):\n ....: # immaculate function corresponding to integer\n ....: # tuple ``xs``, computed by iterated application\n ....: # of Bernstein creation operators.\n ....: res = S.one()\n ....: for i in reversed(xs):\n ....: res = res.bernstein_creation_operator(i)\n ....: return res\n sage: import itertools\n sage: all( immaculate_by_bernstein(p) == I.immaculate_function(p)\n ....: for p in itertools.product(range(-1, 3), repeat=3))\n True\n\n Some examples::\n\n sage: S[3,2].bernstein_creation_operator(-2)\n S[2, 1]\n sage: S[3,2].bernstein_creation_operator(-1)\n S[1, 2, 1] - S[2, 2] - S[3, 1]\n sage: S[3,2].bernstein_creation_operator(0)\n -S[1, 2, 2] - S[1, 3, 1] + S[2, 2, 1] + S[3, 2]\n sage: S[3,2].bernstein_creation_operator(1)\n S[1, 3, 2] - S[2, 2, 2] - S[2, 3, 1] + S[3, 2, 1]\n sage: S[3,2].bernstein_creation_operator(2)\n S[2, 3, 2] - S[3, 2, 2] - S[3, 3, 1] + S[4, 2, 1]\n '
parent = self.parent()
res = parent.zero()
if (not self):
return res
max_degree = max((sum(m) for (m, c) in self))
NSym = parent.realization_of()
S = NSym.S()
F = NSym.dual().F()
for i in range((max_degree + 1)):
if ((n + i) > 0):
res += ((((- 1) ** i) * S[(n + i)]) * self.skew_by(F[([1] * i)]))
elif ((n + i) == 0):
res += (((- 1) ** i) * self.skew_by(F[([1] * i)]))
return res
def star_involution(self):
"\n Return the image of the noncommutative symmetric function\n ``self`` under the star involution.\n\n The star involution is defined as the algebra antihomomorphism\n `NCSF \\to NCSF` which, for every positive integer `n`, sends\n the `n`-th complete non-commutative symmetric function `S_n` to\n `S_n`. Denoting by `f^{\\ast}` the image of an element\n `f \\in NCSF` under this star involution, it can be shown that\n every composition `I` satisfies\n\n .. MATH::\n\n (S^I)^{\\ast} = S^{I^r}, \\quad\n (\\Lambda^I)^{\\ast} = \\Lambda^{I^r}, \\quad\n R_I^{\\ast} = R_{I^r}, \\quad\n (\\Phi^I)^{\\ast} = \\Phi^{I^r},\n\n where `I^r` denotes the reversed composition of `I`, and\n standard notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `R` for the ribbon basis, and `\\Phi` for that of the power-sums\n of the second kind). The star involution is an involution and a\n coalgebra automorphism of `NCSF`. It is an automorphism of the\n graded vector space `NCSF`. Under the canonical isomorphism\n between the `n`-th graded component of `NCSF` and the descent\n algebra of the symmetric group `S_n` (see\n :meth:`to_descent_algebra`), the star involution (restricted to\n the `n`-th graded component) corresponds to the automorphism\n of the descent algebra given by\n `x \\mapsto \\omega_n x \\omega_n`, where `\\omega_n` is the\n permutation `(n, n-1, \\ldots, 1) \\in S_n` (written here in\n one-line notation). If `\\pi` denotes the projection from `NCSF`\n to the ring of symmetric functions\n (:meth:`to_symmetric_function`), then `\\pi(f^{\\ast}) = \\pi(f)`\n for every `f \\in NCSF`.\n\n The star involution on `NCSF` is adjoint to the star involution\n on `QSym` by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n See [NCSF2]_, section 2.3 for the properties of this map.\n\n .. SEEALSO::\n\n :meth:`star involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: S[3,2].star_involution()\n S[2, 3]\n sage: S[6,3].star_involution()\n S[3, 6]\n sage: (S[9,1] - S[8,2] + 2*S[6,4] - 3*S[3] + 4*S[[]]).star_involution()\n 4*S[] + S[1, 9] - S[2, 8] - 3*S[3] + 2*S[4, 6]\n sage: (S[3,3] - 2*S[2]).star_involution()\n -2*S[2] + S[3, 3]\n sage: S([4,2]).star_involution()\n S[2, 4]\n sage: R = NSym.R()\n sage: R([4,2]).star_involution()\n R[2, 4]\n sage: R.zero().star_involution()\n 0\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NSym.Phi()\n sage: Phi([2,1]).star_involution()\n Phi[1, 2]\n\n The Psi basis doesn't behave as nicely::\n\n sage: Psi = NSym.Psi()\n sage: Psi([2,1]).star_involution()\n Psi[1, 2]\n sage: Psi([3,1]).star_involution()\n 1/2*Psi[1, 1, 2] - 1/2*Psi[1, 2, 1] + Psi[1, 3]\n\n The star involution commutes with the antipode::\n\n sage: all( R(I).star_involution().antipode()\n ....: == R(I).antipode().star_involution()\n ....: for I in Compositions(4) )\n True\n\n Checking the relation with the descent algebra described\n above::\n\n sage: def descent_test(n):\n ....: DA = DescentAlgebra(QQ, n)\n ....: NSym = NonCommutativeSymmetricFunctions(QQ)\n ....: S = NSym.S()\n ....: DAD = DA.D()\n ....: w_n = DAD(set(range(1, n)))\n ....: for I in Compositions(n):\n ....: if not (S[I].star_involution()\n ....: == w_n * S[I].to_descent_algebra(n) * w_n):\n ....: return False\n ....: return True\n sage: all( descent_test(i) for i in range(4) )\n True\n sage: all( descent_test(i) for i in range(6) ) # long time\n True\n\n Testing the `\\pi(f^{\\ast}) = \\pi(f)` relation noticed above::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NSym.R()\n sage: all( R(I).star_involution().to_symmetric_function()\n ....: == R(I).to_symmetric_function()\n ....: for I in Compositions(4) )\n True\n\n The star involution on `QSym` is adjoint to the star involution\n on `NSym` with respect to the duality pairing::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: all( all( M(I).star_involution().duality_pairing(S(J))\n ....: == M(I).duality_pairing(S(J).star_involution())\n ....: for I in Compositions(2) )\n ....: for J in Compositions(3) )\n True\n "
parent = self.parent()
S = parent.realization_of().S()
dct = {I.reversed(): coeff for (I, coeff) in S(self)}
return parent(S._from_dict(dct))
def omega_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the omega involution.\n\n The omega involution is defined as the algebra antihomomorphism\n `NCSF \\to NCSF` which, for every positive integer `n`, sends\n the `n`-th complete non-commutative symmetric function `S_n` to\n the `n`-th elementary non-commutative symmetric function\n `\\Lambda_n`. This omega involution is denoted by `\\omega`. It\n can be shown that every composition `I` satisfies\n\n .. MATH::\n\n \\omega(S^I) = \\Lambda^{I^r}, \\quad\n \\omega(\\Lambda^I) = S^{I^r}, \\quad\n \\omega(R_I) = R_{I^t}, \\quad\n \\omega(\\Phi^I) = (-1)^{|I|-\\ell(I)} \\Phi^{I^r},\n \\omega(\\Psi^I) = (-1)^{|I|-\\ell(I)} \\Psi^{I^r},\n\n where `I^r` denotes the reversed composition of `I`, and\n `I^t` denotes the conjugate composition of `I`, and `\\ell(I)`\n denotes the length of the\n composition `I`, and standard notations for classical bases\n of `NCSF` are being used (`S` for the complete basis,\n `\\Lambda` for the elementary basis, `R` for the ribbon\n basis, `\\Phi` for that of the power-sums of the second\n kind, and `\\Psi` for that of the power-sums of the first\n kind). More generally, if `f` is a homogeneous element of\n `NCSF` of degree `n`, then\n\n .. MATH::\n\n \\omega(f) = (-1)^n S(f),\n\n where `S` denotes the antipode of `NCSF`.\n\n The omega involution `\\omega` is an involution and a\n coalgebra automorphism of `NCSF`. It is an automorphism of the\n graded vector space `NCSF`. If `\\pi` denotes the projection\n from `NCSF` to the ring of symmetric functions\n (:meth:`to_symmetric_function`), then\n `\\pi(\\omega(f)) = \\omega(\\pi(f))` for every `f \\in NCSF`,\n where the `\\omega` on the right hand side denotes the omega\n automorphism of `Sym`.\n\n The omega involution on `NCSF` is adjoint to the omega\n involution on `QSym` by the standard adjunction between `NCSF`\n and `QSym`.\n\n The omega involution has been denoted by `\\omega` in [LMvW13]_,\n section 3.6.\n See [NCSF1]_, section 3.1 for the properties of this map.\n\n .. SEEALSO::\n\n :meth:`omega involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.omega_involution>`,\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: L(S[3,2].omega_involution())\n L[2, 3]\n sage: L(S[6,3].omega_involution())\n L[3, 6]\n sage: L(S[1,3].omega_involution())\n L[3, 1]\n sage: L((S[9,1] - S[8,2] + 2*S[6,4] - 3*S[3] + 4*S[[]]).omega_involution()) # long time\n 4*L[] + L[1, 9] - L[2, 8] - 3*L[3] + 2*L[4, 6]\n sage: L((S[3,3] - 2*S[2]).omega_involution())\n -2*L[2] + L[3, 3]\n sage: L(S([4,2]).omega_involution())\n L[2, 4]\n sage: R = NSym.R()\n sage: R([4,2]).omega_involution()\n R[1, 2, 1, 1, 1]\n sage: R.zero().omega_involution()\n 0\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NSym.Phi()\n sage: Phi([2,1]).omega_involution()\n -Phi[1, 2]\n sage: Psi = NSym.Psi()\n sage: Psi([2,1]).omega_involution()\n -Psi[1, 2]\n sage: Psi([3,1]).omega_involution()\n Psi[1, 3]\n\n Testing the `\\pi(\\omega(f)) = \\omega(\\pi(f))` relation noticed\n above::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NSym.R()\n sage: all( R(I).omega_involution().to_symmetric_function()\n ....: == R(I).to_symmetric_function().omega_involution()\n ....: for I in Compositions(4) )\n True\n\n The omega involution on `QSym` is adjoint to the omega\n involution on `NSym` with respect to the duality pairing::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: all( all( M(I).omega_involution().duality_pairing(S(J))\n ....: == M(I).duality_pairing(S(J).omega_involution())\n ....: for I in Compositions(2) )\n ....: for J in Compositions(3) )\n True\n '
return self.antipode().degree_negation()
def psi_involution(self):
"\n Return the image of the noncommutative symmetric function\n ``self`` under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `NCSF \\to NCSF` which, for every composition `I`, sends the\n complete noncommutative symmetric function `S^I` to the\n elementary noncommutative symmetric function `\\Lambda^I`.\n It can be shown that every composition `I` satisfies\n\n .. MATH::\n\n \\psi(R_I) = R_{I^c}, \\quad \\psi(S^I) = \\Lambda^I, \\quad\n \\psi(\\Lambda^I) = S^I, \\quad\n \\psi(\\Phi^I) = (-1)^{|I| - \\ell(I)} \\Phi^I\n\n where `I^c` denotes the complement of the composition `I`, and\n `\\ell(I)` denotes the length of `I`, and where standard\n notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `\\Phi` for the basis of the power sums of the second kind,\n and `R` for the ribbon basis). The map `\\psi` is an involution\n and a graded Hopf algebra automorphism of `NCSF`. If `\\pi`\n denotes the projection from `NCSF` to the ring of symmetric\n functions (:meth:`to_symmetric_function`), then\n `\\pi(\\psi(f)) = \\omega(\\pi(f))` for every `f \\in NCSF`, where\n the `\\omega` on the right hand side denotes the omega\n automorphism of `Sym`.\n\n The involution `\\psi` of `NCSF` is adjoint to the involution\n `\\psi` of `QSym` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: R = NSym.R()\n sage: R[3,2].psi_involution()\n R[1, 1, 2, 1]\n sage: R[6,3].psi_involution()\n R[1, 1, 1, 1, 1, 2, 1, 1]\n sage: (R[9,1] - R[8,2] + 2*R[2,4] - 3*R[3] + 4*R[[]]).psi_involution()\n 4*R[] - 3*R[1, 1, 1] + R[1, 1, 1, 1, 1, 1, 1, 1, 2] - R[1, 1, 1, 1, 1, 1, 1, 2, 1] + 2*R[1, 2, 1, 1, 1]\n sage: (R[3,3] - 2*R[2]).psi_involution()\n -2*R[1, 1] + R[1, 1, 2, 1, 1]\n sage: R([2,1,1]).psi_involution()\n R[1, 3]\n sage: S = NSym.S()\n sage: S([2,1]).psi_involution()\n S[1, 1, 1] - S[2, 1]\n sage: S.zero().psi_involution()\n 0\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NSym.Phi()\n sage: Phi([2,1]).psi_involution()\n -Phi[2, 1]\n sage: Phi([3,1]).psi_involution()\n Phi[3, 1]\n\n The Psi basis doesn't behave as nicely::\n\n sage: Psi = NSym.Psi()\n sage: Psi([2,1]).psi_involution()\n -Psi[2, 1]\n sage: Psi([3,1]).psi_involution()\n 1/2*Psi[1, 2, 1] - 1/2*Psi[2, 1, 1] + Psi[3, 1]\n\n The involution `\\psi` commutes with the antipode::\n\n sage: all( R(I).psi_involution().antipode()\n ....: == R(I).antipode().psi_involution()\n ....: for I in Compositions(4) )\n True\n\n Testing the `\\pi(\\psi(f)) = \\omega(\\pi(f))` relation noticed\n above::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NSym.R()\n sage: all( R(I).psi_involution().to_symmetric_function()\n ....: == R(I).to_symmetric_function().omega()\n ....: for I in Compositions(4) )\n True\n\n The involution `\\psi` of `QSym` is adjoint to the involution\n `\\psi` of `NSym` with respect to the duality pairing::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: all( all( M(I).psi_involution().duality_pairing(S(J))\n ....: == M(I).duality_pairing(S(J).psi_involution())\n ....: for I in Compositions(2) )\n ....: for J in Compositions(3) )\n True\n "
parent = self.parent()
R = parent.realization_of().R()
dct = {I.complement(): coeff for (I, coeff) in R(self)}
return parent(R._from_dict(dct))
def left_padded_kronecker_product(self, x):
'\n Return the left-padded Kronecker product of ``self`` and\n ``x`` in the basis of ``self``.\n\n The left-padded Kronecker product is a bilinear map\n mapping two non-commutative symmetric functions to\n another, not necessarily preserving degree.\n It can be defined as follows: Let `*` denote the internal\n product (:meth:`~sage.combinat.ncsf_qsym.generic_basis_code.GradedModulesWithInternalProduct.ElementMethods.internal_product`)\n on the space of non-commutative symmetric functions. For any\n composition `I`, let `S^I` denote the complete homogeneous\n symmetric function indexed by `I`. For any compositions\n `\\alpha`, `\\beta`, `\\gamma`, let\n `g^{\\gamma}_{\\alpha, \\beta}` denote the coefficient of\n `S^{\\gamma}` in the internal product\n `S^{\\alpha} * S^{\\beta}`.\n For every composition `I = (i_1, i_2, \\ldots, i_k)`\n and every integer `n > \\left\\lvert I \\right\\rvert`, define the\n *`n`-completion of `I`* to be the composition\n `(n - \\left\\lvert I \\right\\rvert, i_1, i_2, \\ldots, i_k)`;\n this `n`-completion is denoted by `I[n]`.\n Then, for any compositions `\\alpha` and `\\beta` and every\n integer `n > \\left\\lvert \\alpha \\right\\rvert\n + \\left\\lvert\\beta\\right\\rvert`, we can write the\n internal product `S^{\\alpha[n]} * S^{\\beta[n]}` in the form\n\n .. MATH::\n\n S^{\\alpha[n]} * S^{\\beta[n]} =\n \\sum_{\\gamma} g^{\\gamma[n]}_{\\alpha[n], \\beta[n]}\n S^{\\gamma[n]}\n\n with `\\gamma` ranging over all compositions. The\n coefficients `g^{\\gamma[n]}_{\\alpha[n], \\beta[n]}`\n are independent on `n`. These coefficients\n `g^{\\gamma[n]}_{\\alpha[n], \\beta[n]}` are denoted by\n `\\widetilde{g}^{\\gamma}_{\\alpha, \\beta}`, and the\n non-commutative symmetric function\n\n .. MATH::\n\n \\sum_{\\gamma} \\widetilde{g}^{\\gamma}_{\\alpha, \\beta}\n S^{\\gamma}\n\n is said to be the *left-padded Kronecker product* of\n `S^{\\alpha}` and `S^{\\beta}`. By bilinearity, this\n extends to a definition of a left-padded Kronecker product\n of any two non-commutative symmetric functions.\n\n The left-padded Kronecker product on the non-commutative\n symmetric functions lifts the left-padded Kronecker\n product on the symmetric functions. More precisely: Let\n `\\pi` denote the canonical projection\n (:meth:`to_symmetric_function`) from the non-commutative\n symmetric functions to the symmetric functions. Then, any\n two non-commutative symmetric functions `f` and `g`\n satisfy\n\n .. MATH::\n\n \\pi(f \\overline{*} g) = \\pi(f) \\overline{*} \\pi(g),\n\n where the `\\overline{*}` on the left-hand side denotes the\n left-padded Kronecker product on the non-commutative\n symmetric functions, and the `\\overline{*}` on the\n right-hand side denotes the left-padded Kronecker product\n on the symmetric functions.\n\n INPUT:\n\n - ``x`` -- element of the ring of non-commutative\n symmetric functions over the same base ring as ``self``\n\n OUTPUT:\n\n - the left-padded Kronecker product of ``self`` with ``x``\n (an element of the ring of non-commutative symmetric\n functions in the same basis as ``self``)\n\n AUTHORS:\n\n - Darij Grinberg (15 Mar 2014)\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: S[2,1].left_padded_kronecker_product(S[3])\n S[1, 1, 1, 1] + S[1, 2, 1] + S[2, 1] + S[2, 1, 1, 1] + S[2, 2, 1] + S[3, 2, 1]\n sage: S[2,1].left_padded_kronecker_product(S[1])\n S[1, 1, 1] + S[1, 2, 1] + S[2, 1]\n sage: S[1].left_padded_kronecker_product(S[2,1])\n S[1, 1, 1] + S[2, 1] + S[2, 1, 1]\n sage: S[1,1].left_padded_kronecker_product(S[2])\n S[1, 1] + 2*S[1, 1, 1] + S[2, 1, 1]\n sage: S[1].left_padded_kronecker_product(S[1,2,1])\n S[1, 1, 1, 1] + S[1, 2, 1] + S[1, 2, 1, 1] + S[2, 1, 1]\n sage: S[2].left_padded_kronecker_product(S[3])\n S[1, 2] + S[2, 1, 1] + S[3, 2]\n\n Taking the left-padded Kronecker product with\n `1 = S^{\\empty}` is the identity map on the ring of\n non-commutative symmetric functions::\n\n sage: all( S[Composition([])].left_padded_kronecker_product(S[lam])\n ....: == S[lam].left_padded_kronecker_product(S[Composition([])])\n ....: == S[lam] for i in range(4)\n ....: for lam in Compositions(i) )\n True\n\n Here is a rule for the left-padded Kronecker product of\n `S_1` (this is the same as `S^{(1)}`) with any complete\n homogeneous function: Let `I` be a composition.\n Then, the left-padded Kronecker product of `S_1` and\n `S^I` is `\\sum_K a_K S^K`, where the sum runs\n over all compositions `K`, and the coefficient `a_K` is\n defined as the number of ways to obtain `K` from `I` by\n one of the following two operations:\n\n - Insert a `1` at the end of `I`.\n - Subtract `1` from one of the entries of `I` (and remove\n the entry if it thus becomes `0`), and insert a `1` at\n the end of `I`.\n\n We check this for compositions of size `\\leq 4`::\n\n sage: def mults1(I):\n ....: # Left left-padded Kronecker multiplication by S[1].\n ....: res = S[I[:] + [1]]\n ....: for k in range(len(I)):\n ....: I2 = I[:]\n ....: if I2[k] == 1:\n ....: I2 = I2[:k] + I2[k+1:]\n ....: else:\n ....: I2[k] -= 1\n ....: res += S[I2 + [1]]\n ....: return res\n sage: all( mults1(I) == S[1].left_padded_kronecker_product(S[I])\n ....: for i in range(5) for I in Compositions(i) )\n True\n\n A similar rule can be made for the left-padded Kronecker\n product of any complete homogeneous function with `S_1`:\n Let `I` be a composition. Then, the left-padded Kronecker\n product of `S^I` and `S_1` is `\\sum_K b_K S^K`, where the\n sum runs over all compositions `K`, and the coefficient\n `b_K` is defined as the number of ways to obtain `K` from\n `I` by one of the following two operations:\n\n - Insert a `1` at the front of `I`.\n - Subtract `1` from one of the entries of `I` (and remove\n the entry if it thus becomes `0`), and insert a `1`\n right after this entry.\n\n We check this for compositions of size `\\leq 4`::\n\n sage: def mults2(I):\n ....: # Left left-padded Kronecker multiplication by S[1].\n ....: res = S[[1] + I[:]]\n ....: for k in range(len(I)):\n ....: I2 = I[:]\n ....: i2k = I2[k]\n ....: if i2k != 1:\n ....: I2 = I2[:k] + [i2k-1, 1] + I2[k+1:]\n ....: res += S[I2]\n ....: return res\n sage: all( mults2(I) == S[I].left_padded_kronecker_product(S[1])\n ....: for i in range(5) for I in Compositions(i) )\n True\n\n Checking the\n `\\pi(f \\overline{*} g) = \\pi(f) \\overline{*} \\pi(g)`\n equality::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: R = NSym.R()\n sage: def testpi(n):\n ....: for I in Compositions(n):\n ....: for J in Compositions(n):\n ....: a = R[I].to_symmetric_function()\n ....: b = R[J].to_symmetric_function()\n ....: x = a.left_padded_kronecker_product(b)\n ....: y = R[I].left_padded_kronecker_product(R[J])\n ....: y = y.to_symmetric_function()\n ....: if x != y:\n ....: return False\n ....: return True\n sage: testpi(3)\n True\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: (2*S([])).left_padded_kronecker_product(3*S([]))\n 6*S[]\n\n Different bases and base rings::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: L(S[2].left_padded_kronecker_product(L[2]))\n L[1, 1, 1] + L[2] + L[2, 1, 1] - L[2, 2]\n sage: S(L[2].left_padded_kronecker_product(S[1,1]))\n S[1, 1] + 2*S[1, 1, 1] + S[1, 1, 1, 1] - S[1, 1, 2]\n\n sage: NSym = NonCommutativeSymmetricFunctions(CyclotomicField(12))\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: v = L[2].left_padded_kronecker_product(L[2]); v\n L[1, 1] + L[1, 1, 1] + (-1)*L[2] + L[2, 2]\n sage: parent(v)\n Non-Commutative Symmetric Functions over the Cyclotomic Field of order 12 and degree 4 in the Elementary basis\n\n sage: NSym = NonCommutativeSymmetricFunctions(Zmod(14))\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: v = L[2].left_padded_kronecker_product(L[2]); v\n L[1, 1] + L[1, 1, 1] + 13*L[2] + L[2, 2]\n sage: parent(v)\n Non-Commutative Symmetric Functions over the Ring of integers modulo 14 in the Elementary basis\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: R = NSym.R()\n sage: v = R[1].left_padded_kronecker_product(R[1]); parent(v)\n Non-Commutative Symmetric Functions over the Integer Ring in the Ribbon basis\n '
_Compositions = Compositions()
parent = self.parent()
comp_parent = parent.realization_of().S()
comp_self = comp_parent(self)
comp_x = comp_parent(x)
result = comp_parent.zero()
for (lam, a) in comp_self:
lam_list = lam._list
if (not lam._list):
result += (a * comp_x)
continue
sum_lam = sum(lam_list)
for (mu, b) in comp_x:
mu_list = mu._list
if (not mu_list):
result += ((a * b) * comp_parent(lam))
continue
sum_mu = sum(mu_list)
stab = ((1 + sum_lam) + sum_mu)
S_lam_stabilized = comp_parent(_Compositions(([(stab - sum_lam)] + lam_list)))
S_mu_stabilized = comp_parent(_Compositions(([(stab - sum_mu)] + mu_list)))
lam_star_mu = S_lam_stabilized.internal_product(S_mu_stabilized)
for (nu, c) in lam_star_mu:
nu_unstabilized = _Compositions(nu[1:])
result += (((a * b) * c) * comp_parent(nu_unstabilized))
return parent(result)
def to_descent_algebra(self, n=None):
'\n Return the image of the ``n``-th degree homogeneous component\n of ``self`` in the descent algebra of `S_n` over the same\n base ring as ``self``.\n\n This is based upon the canonical isomorphism from the\n `n`-th degree homogeneous component of the algebra of\n noncommutative symmetric functions to the descent algebra\n of `S_n`. This isomorphism maps the inner product of\n noncommutative symmetric functions either to the product\n in the descent algebra of `S_n` or to its opposite\n (depending on how the latter is defined).\n\n If ``n`` is not specified, it will be taken to be the highest\n homogeneous component of ``self``.\n\n OUTPUT:\n\n - The image of the ``n``-th homogeneous component of ``self``\n under the isomorphism into the descent algebra of `S_n`\n over the same base ring as ``self``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(ZZ).S()\n sage: S[2,1].to_descent_algebra(3)\n B[2, 1]\n sage: (S[1,2,1] - 3 * S[1,1,2]).to_descent_algebra(4)\n -3*B[1, 1, 2] + B[1, 2, 1]\n sage: S[2,1].to_descent_algebra(2)\n 0\n sage: S[2,1].to_descent_algebra()\n B[2, 1]\n sage: S.zero().to_descent_algebra().parent()\n Descent algebra of 0 over Integer Ring in the subset basis\n sage: (S[1,2,1] - 3 * S[1,1,2]).to_descent_algebra(1)\n 0\n '
if (n is None):
if self.is_zero():
n = 0
else:
n = self.degree()
from sage.combinat.descent_algebra import DescentAlgebra
S = NonCommutativeSymmetricFunctions(self.base_ring()).S()
S_expansion = S(self)
B = DescentAlgebra(self.base_ring(), n).B()
return B.sum(((coeff * B[I]) for (I, coeff) in S_expansion if (sum(I) == n)))
def to_symmetric_group_algebra(self):
'\n Return the image of a non-commutative symmetric function into the\n symmetric group algebra where the ribbon basis element indexed by a\n composition is associated with the sum of all permutations which have\n descent set equal to said composition. In compliance with the anti-\n isomorphism between the descent algebra and the non-commutative\n symmetric functions, we index descent positions by the reversed composition.\n\n OUTPUT:\n\n - The image of ``self`` under the embedding of the `n`-th\n degree homogeneous component of the non-commutative\n symmetric functions in the symmetric group algebra of\n `S_n`. This can behave unexpectedly when ``self`` is\n not homogeneous.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: R[2,1].to_symmetric_group_algebra()\n [1, 3, 2] + [2, 3, 1]\n sage: R([]).to_symmetric_group_algebra()\n []\n\n TESTS:\n\n Sending a noncommutative symmetric function to the symmetric\n group algebra directly has the same result as going through\n the descent algebra::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: SGA4 = SymmetricGroupAlgebra(QQ, 4)\n sage: D4 = DescentAlgebra(QQ, 4).D()\n sage: all( S[C].to_symmetric_group_algebra()\n ....: == SGA4(D4(S[C].to_descent_algebra(4)))\n ....: for C in Compositions(4) )\n True\n '
S = NonCommutativeSymmetricFunctions(self.base_ring()).S()
S_expansion = S(self)
return sum(((S_expansion.coefficient(I) * S._to_symmetric_group_algebra_on_basis(I)) for I in S_expansion.support()))
def to_symmetric_function(self):
'\n Return the commutative image of a non-commutative symmetric function.\n\n OUTPUT:\n\n - The commutative image of ``self``. This will be a symmetric function.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: x = R.an_element(); x\n 2*R[] + 2*R[1] + 3*R[1, 1]\n sage: x.to_symmetric_function()\n 2*s[] + 2*s[1] + 3*s[1, 1]\n sage: y = N.Phi()[1,3]\n sage: y.to_symmetric_function()\n h[1, 1, 1, 1] - 3*h[2, 1, 1] + 3*h[3, 1]\n '
return self.parent().to_symmetric_function(self)
chi = to_symmetric_function
def to_ncsym(self):
'\n Return the image of ``self`` under the injective\n algebra homomorphism `\\kappa : NSym \\to NCSym`\n that fixes the symmetric functions.\n\n As usual, `NCSym` denotes the ring of symmetric\n functions in non-commuting variables.\n Let `S_n` denote a generator of the complete basis.\n The algebra homomorphism `\\kappa : NSym \\to NCSym`\n is defined by\n\n .. MATH::\n\n S_n \\mapsto \\sum_{A \\vdash [n]}\n \\frac{\\lambda(A)! \\lambda(A)^!}{n!} \\mathbf{m}_A .\n\n It has the property that the canonical maps\n `\\chi : NCSym \\to Sym` and `\\rho : NSym \\to Sym`\n satisfy `\\chi \\circ \\kappa = \\rho`.\n\n .. NOTE::\n\n A remark in [BRRZ08]_ makes it clear that the embedding\n of `NSym` into `NCSym` that preserves the projection into\n the symmetric functions is not unique. While this seems\n to be a natural embedding, any free set of algebraic\n generators of `NSym` can be sent to a set of free elements\n in `NCSym` to form another embedding.\n\n .. SEEALSO::\n\n :class:`NonCommutativeSymmetricFunctions` for a definition\n of `NCSym`.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S[2].to_ncsym()\n 1/2*m{{1}, {2}} + m{{1, 2}}\n sage: S[1,2,1].to_ncsym()\n 1/2*m{{1}, {2}, {3}, {4}} + 1/2*m{{1}, {2}, {3, 4}} + m{{1}, {2, 3}, {4}}\n + m{{1}, {2, 3, 4}} + 1/2*m{{1}, {2, 4}, {3}} + 1/2*m{{1, 2}, {3}, {4}}\n + 1/2*m{{1, 2}, {3, 4}} + m{{1, 2, 3}, {4}} + m{{1, 2, 3, 4}}\n + 1/2*m{{1, 2, 4}, {3}} + 1/2*m{{1, 3}, {2}, {4}} + 1/2*m{{1, 3}, {2, 4}}\n + 1/2*m{{1, 3, 4}, {2}} + 1/2*m{{1, 4}, {2}, {3}} + m{{1, 4}, {2, 3}}\n sage: S[1,2].to_ncsym()\n 1/2*m{{1}, {2}, {3}} + m{{1}, {2, 3}} + 1/2*m{{1, 2}, {3}}\n + m{{1, 2, 3}} + 1/2*m{{1, 3}, {2}}\n sage: S[[]].to_ncsym()\n m{}\n\n sage: R = N.ribbon()\n sage: x = R.an_element(); x\n 2*R[] + 2*R[1] + 3*R[1, 1]\n sage: x.to_ncsym()\n 2*m{} + 2*m{{1}} + 3/2*m{{1}, {2}}\n sage: R[2,1].to_ncsym()\n 1/3*m{{1}, {2}, {3}} + 1/6*m{{1}, {2, 3}}\n + 2/3*m{{1, 2}, {3}} + 1/6*m{{1, 3}, {2}}\n\n sage: Phi = N.Phi()\n sage: Phi[1,2].to_ncsym()\n m{{1}, {2, 3}} + m{{1, 2, 3}}\n sage: Phi[1,3].to_ncsym()\n -1/4*m{{1}, {2}, {3, 4}} - 1/4*m{{1}, {2, 3}, {4}} + m{{1}, {2, 3, 4}}\n + 1/2*m{{1}, {2, 4}, {3}} - 1/4*m{{1, 2}, {3, 4}} - 1/4*m{{1, 2, 3}, {4}}\n + m{{1, 2, 3, 4}} + 1/2*m{{1, 2, 4}, {3}} + 1/2*m{{1, 3}, {2, 4}}\n - 1/4*m{{1, 3, 4}, {2}} - 1/4*m{{1, 4}, {2, 3}}\n\n TESTS:\n\n Check that `\\chi \\circ \\kappa = \\rho`::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: mon = SymmetricFunctions(QQ).monomial()\n sage: all(S[c].to_ncsym().to_symmetric_function()\n ....: == S[c].to_symmetric_function()\n ....: for i in range(5) for c in Compositions(i))\n True\n\n We also check that the `NCSym` monomials agree on the homogeneous\n and complete basis::\n\n sage: h = SymmetricFunctions(QQ).h()\n sage: all(m.from_symmetric_function(h[i])\n ....: == S[i].to_ncsym() for i in range(6))\n True\n '
from sage.combinat.ncsym.ncsym import SymmetricFunctionsNonCommutingVariables
from sage.combinat.set_partition import SetPartitions
P = self.parent()
S = P.realization_of().complete()
R = P.base_ring()
m = SymmetricFunctionsNonCommutingVariables(R).m()
SP = SetPartitions()
def on_basis(I):
if (not I._list):
return m.one()
def c_num(A):
return R(prod((factorial(i) for i in A.shape())))
return prod((m.sum_of_terms([(SP(A), R((c_num(A) / factorial(n)))) for A in SetPartitions(n)], distinct=True) for n in I))
return m.linear_combination(((on_basis(I), coeff) for (I, coeff) in S(self)))
def to_fqsym(self):
'\n Return the image of the non-commutative symmetric\n function ``self`` under the morphism\n `\\iota : NSym \\to FQSym`.\n\n This morphism is the injective algebra homomorphism\n `NSym \\to FQSym` that sends each Complete generator\n `S_n` to `F_{[1, 2, \\ldots, n]}`. It is the inclusion\n map, if we regard both `NSym` and `FQSym` as rings of\n noncommutative power series.\n\n .. SEEALSO::\n\n :class:`FreeQuasisymmetricFunctions` for a definition\n of `FQSym`.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: x = 2*R[[]] + 2*R[1] + 3*R[2]\n sage: x.to_fqsym()\n 2*F[] + 2*F[1] + 3*F[1, 2]\n sage: R[2,1].to_fqsym()\n F[1, 3, 2] + F[3, 1, 2]\n sage: x = R.an_element(); x\n 2*R[] + 2*R[1] + 3*R[1, 1]\n sage: x.to_fqsym()\n 2*F[] + 2*F[1] + 3*F[2, 1]\n\n sage: y = N.Phi()[1,2]\n sage: y.to_fqsym()\n F[1, 2, 3] - F[1, 3, 2] + F[2, 1, 3] + F[2, 3, 1]\n - F[3, 1, 2] - F[3, 2, 1]\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S[2].to_fqsym()\n F[1, 2]\n sage: S[1,2].to_fqsym()\n F[1, 2, 3] + F[2, 1, 3] + F[2, 3, 1]\n sage: S[2,1].to_fqsym()\n F[1, 2, 3] + F[1, 3, 2] + F[3, 1, 2]\n sage: S[1,2,1].to_fqsym()\n F[1, 2, 3, 4] + F[1, 2, 4, 3] + F[1, 4, 2, 3]\n + F[2, 1, 3, 4] + F[2, 1, 4, 3] + F[2, 3, 1, 4]\n + F[2, 3, 4, 1] + F[2, 4, 1, 3] + F[2, 4, 3, 1]\n + F[4, 1, 2, 3] + F[4, 2, 1, 3] + F[4, 2, 3, 1]\n '
from sage.combinat.fqsym import FreeQuasisymmetricFunctions
P = self.parent()
S = P.realization_of().complete()
F = FreeQuasisymmetricFunctions(P.base_ring()).F()
def on_basis(I):
return F.prod((F[Permutations(i)(range(1, (i + 1)))] for i in I))
return F.linear_combination(((on_basis(I), coeff) for (I, coeff) in S(self)))
def to_fsym(self):
'\n Return the image of ``self`` under the natural map to\n `FSym`.\n\n There is an injective Hopf algebra morphism from `NSym` to\n `FSym` (see\n :class:`~sage.combinat.chas.fsym.FreeSymmetricFunctions`),\n which maps the ribbon `R_\\alpha` indexed by a composition\n `\\alpha` to the sum of all tableaux whose descent\n composition is `\\alpha`.\n If we regard `NSym` as a Hopf subalgebra of `FQSym` via\n the morphism `\\iota : NSym \\to FQSym` (implemented as\n :meth:`to_fqsym`), then this injective morphism is just\n the inclusion map.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: x = 2*R[[]] + 2*R[1] + 3*R[2]\n sage: x.to_fsym()\n 2*G[] + 2*G[1] + 3*G[12]\n sage: R[2,1].to_fsym()\n G[12|3]\n sage: R[1,2].to_fsym()\n G[13|2]\n sage: R[2,1,2].to_fsym()\n G[12|35|4] + G[125|3|4]\n sage: x = R.an_element(); x\n 2*R[] + 2*R[1] + 3*R[1, 1]\n sage: x.to_fsym()\n 2*G[] + 2*G[1] + 3*G[1|2]\n\n sage: y = N.Phi()[1,2]\n sage: y.to_fsym()\n -G[1|2|3] - G[12|3] + G[123] + G[13|2]\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S[2].to_fsym()\n G[12]\n sage: S[2,1].to_fsym()\n G[12|3] + G[123]\n '
from sage.combinat.chas.fsym import FreeSymmetricFunctions
G = FreeSymmetricFunctions(self.base_ring()).G()
return G(self)
def expand(self, n, alphabet='x'):
'\n Expand the noncommutative symmetric function into an\n element of a free algebra in ``n`` indeterminates of\n an alphabet, which by default is ``\'x\'``.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer; the number of variables\n in the expansion\n - ``alphabet`` -- (default: ``\'x\'``); the alphabet in\n which ``self`` is to be expanded\n\n OUTPUT:\n\n - An expansion of ``self`` into the ``n`` variables\n specified by ``alphabet``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: S[3].expand(3)\n x0^3 + x0^2*x1 + x0^2*x2 + x0*x1^2 + x0*x1*x2\n + x0*x2^2 + x1^3 + x1^2*x2 + x1*x2^2 + x2^3\n sage: L = NSym.L()\n sage: L[3].expand(3)\n x2*x1*x0\n sage: L[2].expand(3)\n x1*x0 + x2*x0 + x2*x1\n sage: L[3].expand(4)\n x2*x1*x0 + x3*x1*x0 + x3*x2*x0 + x3*x2*x1\n sage: Psi = NSym.Psi()\n sage: Psi[2, 1].expand(3)\n x0^3 + x0^2*x1 + x0^2*x2 + x0*x1*x0 + x0*x1^2 + x0*x1*x2\n + x0*x2*x0 + x0*x2*x1 + x0*x2^2 - x1*x0^2 - x1*x0*x1\n - x1*x0*x2 + x1^2*x0 + x1^3 + x1^2*x2 + x1*x2*x0\n + x1*x2*x1 + x1*x2^2 - x2*x0^2 - x2*x0*x1 - x2*x0*x2\n - x2*x1*x0 - x2*x1^2 - x2*x1*x2 + x2^2*x0 + x2^2*x1 + x2^3\n\n One can use a different set of variables by adding an optional\n argument ``alphabet=...``::\n\n sage: L[3].expand(4, alphabet="y")\n y2*y1*y0 + y3*y1*y0 + y3*y2*y0 + y3*y2*y1\n\n TESTS::\n\n sage: (3*S([])).expand(2)\n 3\n sage: L[4,2].expand(0)\n 0\n sage: S([]).expand(0)\n 1\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: S[3].expand(3)\n x0^3 + x0^2*x1 + x0^2*x2 + x0*x1^2 + x0*x1*x2\n + x0*x2^2 + x1^3 + x1^2*x2 + x1*x2^2 + x2^3\n\n .. TODO::\n\n So far this is only implemented on the elementary\n basis, and everything else goes through coercion.\n Maybe it is worth shortcutting some of the other\n bases?\n '
NSym = self.parent().realization_of()
L = NSym.L()
from sage.algebras.free_algebra import FreeAlgebra
P = FreeAlgebra(NSym.base_ring(), n, alphabet)
x = P.gens()
def image_of_L_k(k, i):
if (k == 0):
return P.one()
if (k > i):
return P.zero()
return ((x[(i - 1)] * image_of_L_k((k - 1), (i - 1))) + image_of_L_k(k, (i - 1)))
def on_basis(comp):
return P.prod((image_of_L_k(k, n) for k in comp))
return L._apply_module_morphism(L(self), on_basis, codomain=P)
class MultiplicativeBases(Category_realization_of_parent):
'\n Category of multiplicative bases of non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBases()\n Category of multiplicative bases of Non-Commutative Symmetric Functions over the Rational Field\n\n The complete basis is a multiplicative basis, but the ribbon basis is not::\n\n sage: N.Complete() in N.MultiplicativeBases()\n True\n sage: N.Ribbon() in N.MultiplicativeBases()\n False\n '
def super_categories(self):
'\n Return the super categories of the category of multiplicative\n bases of the non-commutative symmetric functions.\n\n OUTPUT:\n\n - list\n\n TESTS::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBases().super_categories()\n [Category of bases of Non-Commutative Symmetric Functions over the Rational Field]\n\n '
return [self.base().Bases()]
class ParentMethods():
@cached_method
def algebra_generators(self):
'\n Return the algebra generators of a given multiplicative basis of\n non-commutative symmetric functions.\n\n OUTPUT:\n\n - The family of generators of the multiplicative basis ``self``.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: f = Psi.algebra_generators()\n sage: f\n Lazy family (<lambda>(i))_{i in Positive integers}\n sage: f[1], f[2], f[3]\n (Psi[1], Psi[2], Psi[3])\n '
from sage.sets.family import Family
from sage.sets.positive_integers import PositiveIntegers
return Family(PositiveIntegers(), (lambda i: self.monomial(self._indices([i]))))
def product_on_basis(self, composition1, composition2):
'\n Return the product of two basis elements from the multiplicative basis.\n Multiplication is just concatenation on compositions.\n\n INPUT:\n\n - ``composition1``, ``composition2`` -- integer compositions\n\n OUTPUT:\n\n - The product of the two non-commutative symmetric functions\n indexed by ``composition1`` and ``composition2`` in the\n multiplicative basis ``self``. This will be again\n a non-commutative symmetric function.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi[3,1,2] * Psi[4,2] == Psi[3,1,2,4,2]\n True\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.product_on_basis(Composition([2,1]), Composition([1,2]))\n S[2, 1, 1, 2]\n '
return self.monomial((composition1 + composition2))
def algebra_morphism(self, on_generators, **keywords):
'\n Given a map defined on the generators of the multiplicative\n basis ``self``, return the algebra morphism that extends\n this map to the whole algebra of non-commutative symmetric\n functions.\n\n INPUT:\n\n - ``on_generators`` -- a function defined on the index set of\n the generators (that is, on the positive integers)\n - ``anti`` -- a boolean; defaults to ``False``\n - ``category`` -- a category; defaults to ``None``\n\n OUTPUT:\n\n - The algebra morphism of ``self`` which is defined by\n ``on_generators`` in the basis ``self``. When ``anti``\n is set to ``True``, an algebra anti-morphism is\n computed instead of an algebra morphism.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = NCSF.Psi()\n sage: double = lambda i: Psi[i,i]\n sage: f = Psi.algebra_morphism(double, codomain = Psi)\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] + 3*Psi[1, 1, 3, 3, 2, 2] + Psi[2, 2, 4, 4]\n sage: f.category()\n Category of endsets of unital magmas and right modules over Rational Field and left modules over Rational Field\n\n When extra properties about the morphism are known, one\n can specify the category of which it is a morphism::\n\n sage: negate = lambda i: -Psi[i]\n sage: f = Psi.algebra_morphism(negate, codomain = Psi, category = GradedHopfAlgebrasWithBasis(QQ))\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] - 3*Psi[1, 3, 2] + Psi[2, 4]\n sage: f.category()\n Category of endsets of Hopf algebras over Rational Field and graded modules over Rational Field\n\n If ``anti`` is true, this returns an anti-algebra morphism::\n\n sage: f = Psi.algebra_morphism(double, codomain = Psi, anti=True)\n sage: f\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )\n 2*Psi[] + 3*Psi[2, 2, 3, 3, 1, 1] + Psi[4, 4, 2, 2]\n sage: f.category()\n Category of endsets of modules with basis over Rational Field\n '
from sage.combinat.ncsf_qsym.generic_basis_code import AlgebraMorphism
return AlgebraMorphism(self, on_generators, **keywords)
def to_symmetric_function_on_generators(self, i):
'\n Morphism of the generators to symmetric functions.\n\n This is constructed by coercion to the complete basis\n and applying the morphism.\n\n OUTPUT:\n\n - The module morphism from the basis ``self`` to the symmetric\n functions which corresponds to taking a commutative image.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = N.Phi()\n sage: Phi.to_symmetric_function_on_generators(3)\n h[1, 1, 1] - 3*h[2, 1] + 3*h[3]\n sage: Phi.to_symmetric_function_on_generators(0)\n h[]\n sage: Psi = N.Psi()\n sage: Psi.to_symmetric_function_on_generators(3)\n h[1, 1, 1] - 3*h[2, 1] + 3*h[3]\n sage: L = N.elementary()\n sage: L.to_symmetric_function_on_generators(3)\n h[1, 1, 1] - 2*h[2, 1] + h[3]\n '
S = self.realization_of().a_realization()
if (not i):
return S.to_symmetric_function_on_basis([])
return S.to_symmetric_function(S(self([i])))
@lazy_attribute
def to_symmetric_function(self):
'\n Morphism to the algebra of symmetric functions.\n\n This is constructed by extending the algebra morphism\n by the image of the generators.\n\n OUTPUT:\n\n - The module morphism from the basis ``self`` to the symmetric\n functions which corresponds to taking a commutative image.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S.to_symmetric_function(S[1,3])\n h[3, 1]\n sage: Phi = N.Phi()\n sage: Phi.to_symmetric_function(Phi[1,3])\n h[1, 1, 1, 1] - 3*h[2, 1, 1] + 3*h[3, 1]\n sage: Psi = N.Psi()\n sage: Psi.to_symmetric_function(Psi[1,3])\n h[1, 1, 1, 1] - 3*h[2, 1, 1] + 3*h[3, 1]\n '
codom = self.to_symmetric_function_on_generators(1).parent()
return self.algebra_morphism(self.to_symmetric_function_on_generators, codomain=codom)
@lazy_attribute
def antipode(self):
'\n Return the antipode morphism on the basis ``self``.\n\n The antipode of `NSym` is closely related to the omega\n involution; see\n :meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.omega_involution`\n for the latter.\n\n OUTPUT:\n\n - The antipode module map from non-commutative symmetric\n functions on basis ``self``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.antipode\n Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n '
if hasattr(self, 'antipode_on_generators'):
return self.algebra_morphism(self.antipode_on_generators, codomain=self, anti=True)
else:
return NotImplemented
@lazy_attribute
def coproduct(self):
'\n Return the coproduct morphism in the basis ``self``.\n\n OUTPUT:\n\n - The coproduct module map from non-commutative symmetric\n functions on basis ``self``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.coproduct\n Generic morphism:\n From: Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n To: Non-Commutative Symmetric Functions over the Rational Field in the Complete basis # Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n '
from sage.categories.tensor import tensor
if hasattr(self, 'coproduct_on_generators'):
return self.algebra_morphism(self.coproduct_on_generators, codomain=tensor([self, self]))
else:
return NotImplemented
class MultiplicativeBasesOnGroupLikeElements(Category_realization_of_parent):
'\n Category of multiplicative bases on grouplike elements of\n non-commutative symmetric functions.\n\n Here, a "multiplicative basis on grouplike elements" means\n a multiplicative basis whose generators `(f_1, f_2, f_3, \\ldots )`\n satisfy\n\n .. MATH::\n\n \\Delta(f_i) = \\sum_{j=0}^{i} f_j \\otimes f_{i-j}\n\n with `f_0 = 1`. (In other words, the generators are to form a\n divided power sequence in the sense of a coalgebra.) This\n does not mean that the generators are grouplike, but means that\n the element `1 + f_1 + f_2 + f_3 + \\cdots` in the completion of\n the ring of non-commutative symmetric functions with respect\n to the grading is grouplike.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBasesOnGroupLikeElements()\n Category of multiplicative bases on group like elements of Non-Commutative Symmetric Functions over the Rational Field\n\n The complete basis is a multiplicative basis, but the ribbon basis is not::\n\n sage: N.Complete() in N.MultiplicativeBasesOnGroupLikeElements()\n True\n sage: N.Ribbon() in N.MultiplicativeBasesOnGroupLikeElements()\n False\n '
def super_categories(self):
'\n Return the super categories of the category of multiplicative\n bases of group-like elements of the non-commutative symmetric\n functions.\n\n OUTPUT:\n\n - list\n\n TESTS::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBasesOnGroupLikeElements().super_categories()\n [Category of multiplicative bases of Non-Commutative Symmetric Functions over the Rational Field]\n '
return [self.base().MultiplicativeBases()]
class ParentMethods():
def antipode_on_basis(self, composition):
'\n Return the application of the antipode to a basis element.\n\n INPUT:\n\n - ``composition`` -- a composition\n\n OUTPUT:\n\n - The image of the basis element indexed by ``composition``\n under the antipode map.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: S.antipode_on_basis(Composition([2,1]))\n -S[1, 1, 1] + S[1, 2]\n sage: S[1].antipode() # indirect doctest\n -S[1]\n sage: S[2].antipode() # indirect doctest\n S[1, 1] - S[2]\n sage: S[3].antipode() # indirect doctest\n -S[1, 1, 1] + S[1, 2] + S[2, 1] - S[3]\n sage: S[2,3].coproduct().apply_multilinear_morphism(lambda be,ga: S(be)*S(ga).antipode())\n 0\n sage: S[2,3].coproduct().apply_multilinear_morphism(lambda be,ga: S(be).antipode()*S(ga))\n 0\n '
return (((- 1) ** len(composition)) * self.alternating_sum_of_finer_compositions(composition.reversed()))
def coproduct_on_generators(self, i):
'\n Return the image of the `i^{th}` generator of the algebra under\n the coproduct.\n\n INPUT:\n\n - ``i`` -- a positive integer\n\n OUTPUT:\n\n - The result of applying the coproduct to the `i^{th}`\n generator of ``self``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: S.coproduct_on_generators(3)\n S[] # S[3] + S[1] # S[2] + S[2] # S[1] + S[3] # S[]\n\n TESTS::\n\n sage: S.coproduct_on_generators(0)\n Traceback (most recent call last):\n ...\n ValueError: Not a positive integer: 0\n '
if (i < 1):
raise ValueError('Not a positive integer: {}'.format(i))
def C(i):
return (self._indices([i]) if i else self._indices([]))
T = self.tensor_square()
return T.sum_of_monomials(((C(j), C((i - j))) for j in range((i + 1))))
class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent):
'\n Category of multiplicative bases of the non-commutative symmetric\n functions whose generators are primitive elements.\n\n An element `x` of a bialgebra is *primitive* if\n `\\Delta(x) = x \\otimes 1 + 1 \\otimes x`, where\n `\\Delta` is the coproduct of the bialgebra.\n\n Given a multiplicative basis and knowing the coproducts and antipodes\n of its generators, one can compute the coproduct and the antipode of\n any element, since they are respectively algebra morphisms and\n anti-morphisms. See :meth:`~ParentMethods.antipode_on_generators` and\n :meth:`~ParentMethods.coproduct_on_generators`.\n\n .. TODO:: this could be generalized to any free algebra.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBasesOnPrimitiveElements()\n Category of multiplicative bases on primitive elements of Non-Commutative Symmetric Functions over the Rational Field\n\n The Phi and Psi bases are multiplicative bases whose generators\n are primitive elements, but the complete and ribbon bases are not::\n\n sage: N.Phi() in N.MultiplicativeBasesOnPrimitiveElements()\n True\n sage: N.Psi() in N.MultiplicativeBasesOnPrimitiveElements()\n True\n sage: N.Complete() in N.MultiplicativeBasesOnPrimitiveElements()\n False\n sage: N.Ribbon() in N.MultiplicativeBasesOnPrimitiveElements()\n False\n '
def super_categories(self):
'\n Return the super categories of the category of multiplicative\n bases of primitive elements of the non-commutative symmetric\n functions.\n\n OUTPUT:\n\n - list\n\n TESTS::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: N.MultiplicativeBasesOnPrimitiveElements().super_categories()\n [Category of multiplicative bases of Non-Commutative Symmetric Functions over the Rational Field]\n '
return [self.base().MultiplicativeBases()]
class ParentMethods():
def antipode_on_generators(self, i):
'\n Return the image of a generator of a primitive basis of\n the non-commutative symmetric functions under the antipode\n map.\n\n INPUT:\n\n - ``i`` -- a positive integer\n\n OUTPUT:\n\n - The image of the `i`-th generator of the multiplicative\n basis ``self`` under the antipode of the algebra of\n non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: Psi=NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi.antipode_on_generators(2)\n -Psi[2]\n\n TESTS::\n\n sage: Psi.antipode_on_generators(0)\n Traceback (most recent call last):\n ...\n ValueError: Not a positive integer: 0\n '
if (i < 1):
raise ValueError('Not a positive integer: {}'.format(i))
return (- self.algebra_generators()[i])
def coproduct_on_generators(self, i):
'\n Return the image of the `i^{th}` generator of the\n multiplicative basis ``self`` under the coproduct.\n\n INPUT:\n\n - ``i`` -- a positive integer\n\n OUTPUT:\n\n - The result of applying the coproduct to the\n `i^{th}` generator of ``self``.\n\n EXAMPLES::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi.coproduct_on_generators(3)\n Psi[] # Psi[3] + Psi[3] # Psi[]\n\n TESTS::\n\n sage: Psi.coproduct_on_generators(0)\n Traceback (most recent call last):\n ...\n ValueError: Not a positive integer: 0\n '
if (i < 1):
raise ValueError('Not a positive integer: {}'.format(i))
x = self.algebra_generators()[i]
from sage.categories.tensor import tensor
return (tensor([self.one(), x]) + tensor([x, self.one()]))
class Ribbon(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n Ribbon basis.\n\n The Ribbon basis is defined in Definition 3.12 of [NCSF1]_, where\n it is denoted by `(R_I)_I`. It is connected to the complete\n basis of the ring of non-commutative symmetric functions by the\n following relation: For every composition `I`, we have\n\n .. MATH::\n\n R_I = \\sum_J (-1)^{\\ell(I) - \\ell(J)} S^J,\n\n where the sum is over all compositions `J` which are coarser than\n `I` and `\\ell(I)` denotes the length of `I`. (See the proof of\n Proposition 4.13 in [NCSF1]_.)\n\n The elements of the Ribbon basis are commonly referred to as the\n ribbon Schur functions.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: R = NCSF.Ribbon(); R\n Non-Commutative Symmetric Functions over the Rational Field in the Ribbon basis\n sage: R.an_element()\n 2*R[] + 2*R[1] + 3*R[1, 1]\n\n The following are aliases for this basis::\n\n sage: NCSF.ribbon()\n Non-Commutative Symmetric Functions over the Rational Field in the Ribbon basis\n sage: NCSF.R()\n Non-Commutative Symmetric Functions over the Rational Field in the Ribbon basis\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(ZZ).ribbon(); R\n Non-Commutative Symmetric Functions over the Integer Ring in the Ribbon basis\n sage: TestSuite(R).run()\n\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: R.one().coproduct()\n R[] # R[]\n sage: R.one().antipode()\n R[]\n\n We include some sanity tests to verify that conversions between the\n ribbon basis and other bases work the way they should::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: all(S(R(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(R(S(R[comp])) == R[comp] for comp in Compositions(5))\n True\n\n ::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: L = NonCommutativeSymmetricFunctions(QQ).elementary()\n sage: all(L(R(L[comp])) == L[comp] for comp in Compositions(5))\n True\n sage: all(R(L(R[comp])) == R[comp] for comp in Compositions(5))\n True\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='R', bracket=False, category=NCSF.Bases())
def dual(self):
'\n Return the dual basis to the ribbon basis of the non-commutative symmetric\n functions. This is the Fundamental basis of the quasi-symmetric functions.\n\n OUTPUT:\n\n - The fundamental basis of the quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: R.dual()\n Quasisymmetric functions over the Rational Field in the Fundamental basis\n '
return self.realization_of().dual().Fundamental()
def product_on_basis(self, I, J):
'\n Return the product of two ribbon basis elements of the non-commutative\n symmetric functions.\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The product of the ribbon functions indexed by ``I`` and ``J``.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: R[1,2,1] * R[3,1]\n R[1, 2, 1, 3, 1] + R[1, 2, 4, 1]\n sage: ( R[1,2] + R[3] ) * ( R[3,1] + R[1,2,1] )\n R[1, 2, 1, 2, 1] + R[1, 2, 3, 1] + R[1, 3, 2, 1] + R[1, 5, 1] + R[3, 1, 2, 1] + R[3, 3, 1] + R[4, 2, 1] + R[6, 1]\n\n TESTS::\n\n sage: R[[]] * R[3,1]\n R[3, 1]\n sage: R[1,2,1] * R[[]]\n R[1, 2, 1]\n sage: R.product_on_basis(Composition([2,1]), Composition([1]))\n R[2, 1, 1] + R[2, 2]\n '
if (not I._list):
return self.monomial(J)
elif (not J._list):
return self.monomial(I)
else:
return (self.monomial(self._indices((I[:] + J[:]))) + self.monomial(self._indices(((I[:(- 1)] + [(I[(- 1)] + J[0])]) + J[1:]))))
def antipode_on_basis(self, composition):
'\n Return the application of the antipode to a basis element\n of the ribbon basis ``self``.\n\n INPUT:\n\n - ``composition`` -- a composition\n\n OUTPUT:\n\n - The image of the basis element indexed by ``composition``\n under the antipode map.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon()\n sage: R.antipode_on_basis(Composition([2,1]))\n -R[2, 1]\n sage: R[3,1].antipode() # indirect doctest\n R[2, 1, 1]\n sage: R[[]].antipode() # indirect doctest\n R[]\n\n We check that the implementation of the antipode at hand does\n not contradict the generic one::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: all( S(R[I].antipode()) == S(R[I]).antipode()\n ....: for I in Compositions(4) )\n True\n '
if ((composition.size() % 2) == 0):
return self[composition.conjugate()]
else:
return (- self[composition.conjugate()])
def to_symmetric_function_on_basis(self, I):
'\n Return the commutative image of a ribbon basis element of the\n non-commutative symmetric functions.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The commutative image of the ribbon basis element indexed by\n ``I``. This will be expressed as a symmetric function in the\n Schur basis.\n\n EXAMPLES::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).R()\n sage: R.to_symmetric_function_on_basis(Composition([3,1,1]))\n s[3, 1, 1]\n sage: R.to_symmetric_function_on_basis(Composition([4,2,1]))\n s[4, 2, 1] + s[5, 1, 1] + s[5, 2]\n sage: R.to_symmetric_function_on_basis(Composition([]))\n s[]\n '
s = SymmetricFunctions(self.base_ring()).schur()
if (not I):
return s([])
return s(I.to_skew_partition())
class Element(CombinatorialFreeModule.Element):
def verschiebung(self, n):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined\n to be the map from the `\\mathbf{k}`-algebra of noncommutative\n symmetric functions to itself that sends the complete function\n `S^I` indexed by a composition `I = (i_1, i_2, \\ldots , i_k)`\n to `S^{(i_1/n, i_2/n, \\ldots , i_k/n)}` if all of the numbers\n `i_1, i_2, \\ldots, i_k` are divisible by `n`, and to `0`\n otherwise. This operator `\\mathbf{V}_n` is a Hopf algebra\n endomorphism. For every positive integer `r` with `n \\mid r`,\n it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = S_{r/n},\n \\quad \\mathbf{V}_n(\\Lambda_r) = (-1)^{r - r/n} \\Lambda_{r/n},\n \\quad \\mathbf{V}_n(\\Psi_r) = n \\Psi_{r/n},\n \\quad \\mathbf{V}_n(\\Phi_r) = n \\Phi_{r/n}\n\n (where `S_r` denotes the `r`-th complete non-commutative\n symmetric function, `\\Lambda_r` denotes the `r`-th elementary\n non-commutative symmetric function, `\\Psi_r` denotes the `r`-th\n power-sum non-commutative symmetric function of the first kind,\n and `\\Phi_r` denotes the `r`-th power-sum non-commutative\n symmetric function of the second kind). For every positive\n integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = \\mathbf{V}_n(\\Lambda_r)\n = \\mathbf{V}_n(\\Psi_r) = \\mathbf{V}_n(\\Phi_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism.\n\n It is a lift of the `n`-th Verschiebung operator on the ring\n of symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung`)\n to the ring of noncommutative symmetric functions.\n\n The action of the `n`-th Verschiebung operator can also be\n described on the ribbon Schur functions. Namely, every\n composition `I` of size `n \\ell` satisfies\n\n .. MATH::\n\n \\mathbf{V}_n ( R_I )\n = (-1)^{\\ell(I) - \\ell(J)} \\cdot R_{J / n},\n\n where `J` denotes the meet of the compositions `I` and\n `(\\underbrace{n, n, \\ldots, n}_{|I|/n \\mbox{ times}})`,\n where `\\ell(I)` is the length of `I`, and\n where `J / n` denotes the composition obtained by\n dividing every entry of `J` by `n`.\n For a composition `I` of size not divisible by `n`, we\n have `\\mathbf{V}_n ( R_I ) = 0`.\n\n .. SEEALSO::\n\n :meth:`verschiebung method of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.verschiebung>`,\n :meth:`frobenius method of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius>`,\n :meth:`verschiebung method of Sym\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of noncommutative symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: R = NSym.R()\n sage: R([4,2]).verschiebung(2)\n R[2, 1]\n sage: R([2,1]).verschiebung(3)\n -R[1]\n sage: R([3]).verschiebung(2)\n 0\n sage: R([]).verschiebung(2)\n R[]\n sage: R([5, 1]).verschiebung(3)\n -R[2]\n sage: R([5, 1]).verschiebung(6)\n -R[1]\n sage: R([5, 1]).verschiebung(2)\n -R[3]\n sage: R([1, 2, 3, 1]).verschiebung(7)\n -R[1]\n sage: R([1, 2, 3, 1]).verschiebung(5)\n 0\n sage: (R[1] - R[2] + 2*R[3]).verschiebung(1)\n R[1] - R[2] + 2*R[3]\n\n TESTS:\n\n The current implementation on the ribbon basis gives the\n same results as the default implementation::\n\n sage: S = NSym.S()\n sage: def test_ribbon(N, n):\n ....: for I in Compositions(N):\n ....: if S(R[I].verschiebung(n)) != S(R[I]).verschiebung(n):\n ....: return False\n ....: return True\n sage: test_ribbon(4, 2)\n True\n sage: test_ribbon(6, 2)\n True\n sage: test_ribbon(6, 3)\n True\n sage: test_ribbon(8, 4) # long time\n True\n '
parent = self.parent()
C = parent._indices
def ribbon_mapper(I, coeff):
M = sum(I)
m = (M // n)
J = I.meet(([n] * m))
Jn = C([(j // n) for j in J])
if ((len(I) - len(J)) % 2):
return (Jn, (- coeff))
else:
return (Jn, coeff)
return parent.sum_of_terms([ribbon_mapper(I, coeff) for (I, coeff) in self if ((sum(I) % n) == 0)])
def star_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the star involution.\n\n The star involution is defined as the algebra antihomomorphism\n `NCSF \\to NCSF` which, for every positive integer `n`, sends\n the `n`-th complete non-commutative symmetric function `S_n` to\n `S_n`. Denoting by `f^{\\ast}` the image of an element\n `f \\in NCSF` under this star involution, it can be shown that\n every composition `I` satisfies\n\n .. MATH::\n\n (S^I)^{\\ast} = S^{I^r}, \\quad\n (\\Lambda^I)^{\\ast} = \\Lambda^{I^r}, \\quad\n R_I^{\\ast} = R_{I^r}, \\quad\n (\\Phi^I)^{\\ast} = \\Phi^{I^r},\n\n where `I^r` denotes the reversed composition of `I`, and\n standard notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `R` for the ribbon basis, and `\\Phi` for that of the power-sums\n of the second kind). The star involution is an involution and a\n coalgebra automorphism of `NCSF`. It is an automorphism of the\n graded vector space `NCSF`. Under the canonical isomorphism\n between the `n`-th graded component of `NCSF` and the descent\n algebra of the symmetric group `S_n` (see\n :meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_descent_algebra`),\n the star involution (restricted to\n the `n`-th graded component) corresponds to the automorphism\n of the descent algebra given by\n `x \\mapsto \\omega_n x \\omega_n`, where `\\omega_n` is the\n permutation `(n, n-1, \\ldots, 1) \\in S_n` (written here in\n one-line notation). If `\\pi` denotes the projection from `NCSF`\n to the ring of symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(f^{\\ast}) = \\pi(f)` for every `f \\in NCSF`.\n\n The star involution on `NCSF` is adjoint to the star involution\n on `QSym` by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n See [NCSF2]_, section 2.3 for the properties of this map.\n\n .. SEEALSO::\n\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`star involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: R = NSym.R()\n sage: R[3,1,4,2].star_involution()\n R[2, 4, 1, 3]\n sage: R[4,1,2].star_involution()\n R[2, 1, 4]\n sage: (R[1] - R[2] + 2*R[5,4] - 3*R[3] + 4*R[[]]).star_involution()\n 4*R[] + R[1] - R[2] - 3*R[3] + 2*R[4, 5]\n sage: (R[3,3] - 21*R[1]).star_involution()\n -21*R[1] + R[3, 3]\n sage: R([14,1]).star_involution()\n R[1, 14]\n\n The implementation at hand is tailored to the ribbon basis.\n It is equivalent to the generic implementation via the\n complete basis::\n\n sage: S = NSym.S()\n sage: all( S(R[I].star_involution()) == S(R[I]).star_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
dct = {I.reversed(): coeff for (I, coeff) in self}
return parent._from_dict(dct)
R = ribbon = Ribbon
class Complete(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n Complete basis.\n\n The Complete basis is defined in Definition 3.4 of [NCSF1]_, where\n it is denoted by `(S^I)_I`. It is a multiplicative basis, and is\n connected to the elementary generators `\\Lambda_i` of the ring of\n non-commutative symmetric functions by the following relation:\n Define a non-commutative symmetric function `S_n` for every\n nonnegative integer `n` by the power series identity\n\n .. MATH::\n\n \\sum_{k \\geq 0} t^k S_k\n = \\left( \\sum_{k \\geq 0} (-t)^k \\Lambda_k \\right)^{-1},\n\n with `\\Lambda_0` denoting `1`. For every composition\n `(i_1, i_2, \\ldots, i_k)`, we have\n `S^{(i_1, i_2, \\ldots, i_k)} = S_{i_1} S_{i_2} \\cdots S_{i_k}`.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NCSF.Complete(); S\n Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n sage: S.an_element()\n 2*S[] + 2*S[1] + 3*S[1, 1]\n\n The following are aliases for this basis::\n\n sage: NCSF.complete()\n Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n sage: NCSF.S()\n Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: TestSuite(S).run()\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='S', bracket=False, category=NCSF.MultiplicativeBasesOnGroupLikeElements())
def dual(self):
'\n Return the dual basis to the complete basis of non-commutative symmetric\n functions. This is the Monomial basis of quasi-symmetric functions.\n\n OUTPUT:\n\n - The Monomial basis of quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S.dual()\n Quasisymmetric functions over the Rational Field in the Monomial basis\n '
return self.realization_of().dual().Monomial()
def internal_product_on_basis(self, I, J):
'\n The internal product of two non-commutative symmetric\n complete functions.\n\n See :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.GradedModulesWithInternalProduct.ElementMethods.internal_product`\n for a thorough documentation of this operation.\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The internal product of the complete non-commutative symmetric\n function basis elements indexed by ``I`` and ``J``, expressed in\n the complete basis.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S.internal_product_on_basis([2,2],[1,2,1])\n 2*S[1, 1, 1, 1] + S[1, 1, 2] + S[2, 1, 1]\n sage: S.internal_product_on_basis([2,2],[1,2])\n 0\n '
from sage.combinat.integer_matrices import IntegerMatrices
IM = IntegerMatrices(I, J)
return self.sum_of_monomials((IM.to_composition(m) for m in IM))
def to_symmetric_function_on_basis(self, I):
'\n The commutative image of a complete element\n\n The commutative image of a basis element is obtained by sorting\n the indexing composition of the basis element and the output\n is in the complete basis of the symmetric functions.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The commutative image of the complete basis element\n indexed by ``I``. The result is the complete symmetric function\n indexed by the partition obtained by sorting ``I``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: S.to_symmetric_function_on_basis([2,1,3])\n h[3, 2, 1]\n sage: S.to_symmetric_function_on_basis([])\n h[]\n '
h = SymmetricFunctions(self.base_ring()).complete()
return h[Partition(sorted(I, reverse=True))]
@lazy_attribute
def to_symmetric_function(self):
'\n Morphism to the algebra of symmetric functions.\n\n This is constructed by extending the computation on the\n complete basis.\n\n OUTPUT:\n\n - The module morphism from the basis ``self`` to the symmetric\n functions which corresponds to taking a commutative image.\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: S = N.complete()\n sage: S.to_symmetric_function(S[3,1,2])\n h[3, 2, 1]\n sage: S.to_symmetric_function(S[[]])\n h[]\n '
on_basis = self.to_symmetric_function_on_basis
codom = SymmetricFunctions(self.base_ring()).complete()
return self.module_morphism(on_basis, codomain=codom)
def _to_symmetric_group_algebra_on_basis(self, I):
'\n Return the image of the complete non-commutative symmetric function indexed\n by the composition ``I`` in the symmetric group algebra under the canonical\n embedding of the degree-`|I|` homogeneous non-commutative symmetric\n functions into the `|I|`-th symmetric group algebra.\n\n This embedding sends the complete basis element indexed by the composition\n ``I`` to the sum of all permutations whose descent composition is fatter\n than ``I`` (that is, all permutations whose right descent set is contained\n in the subset corresponding to ``I``).\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The sum of all permutations of `\\{ 1, 2, \\ldots, |I| \\}` with right\n descent set contained in ``I``.\n\n EXAMPLES::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: S._to_symmetric_group_algebra_on_basis(Composition([1,2]))\n [1, 2, 3] + [2, 1, 3] + [3, 1, 2]\n sage: S._to_symmetric_group_algebra_on_basis(Composition([]))\n []\n sage: S._to_symmetric_group_algebra_on_basis(Composition([1]))\n [1]\n '
n = sum(I)
from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra
from sage.sets.set import Set
if (n == 0):
return SymmetricGroupAlgebra(self.base_ring(), n).one()
sga = SymmetricGroupAlgebra(self.base_ring(), n)
J = [(j - 1) for j in I.to_subset()]
return sga.sum_of_monomials((p for K in Set(J).subsets() for p in Permutations(descents=(K, n))))
class Element(CombinatorialFreeModule.Element):
'\n An element in the Complete basis.\n '
def psi_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `NCSF \\to NCSF` which, for every composition `I`, sends the\n complete noncommutative symmetric function `S^I` to the\n elementary noncommutative symmetric function `\\Lambda^I`.\n It can be shown that every composition `I` satisfies\n\n .. MATH::\n\n \\psi(R_I) = R_{I^c}, \\quad \\psi(S^I) = \\Lambda^I, \\quad\n \\psi(\\Lambda^I) = S^I, \\quad\n \\psi(\\Phi^I) = (-1)^{|I| - \\ell(I)} \\Phi^I\n\n where `I^c` denotes the complement of the composition `I`, and\n `\\ell(I)` denotes the length of `I`, and where standard\n notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary\n basis, `\\Phi` for the basis of the power sums of the second\n kind, and `R` for the ribbon basis). The map `\\psi` is an\n involution and a graded Hopf algebra automorphism of `NCSF`.\n If `\\pi` denotes the projection from `NCSF` to the ring of\n symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(\\psi(f)) = \\omega(\\pi(f))` for every `f \\in NCSF`, where\n the `\\omega` on the right hand side denotes the omega\n automorphism of `Sym`.\n\n The involution `\\psi` of `NCSF` is adjoint to the involution\n `\\psi` of `QSym` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`psi involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: S[3,1].psi_involution()\n S[1, 1, 1, 1] - S[1, 2, 1] - S[2, 1, 1] + S[3, 1]\n sage: L(S[3,1].psi_involution())\n L[3, 1]\n sage: S[[]].psi_involution()\n S[]\n sage: S[1,1].psi_involution()\n S[1, 1]\n sage: (S[2,1] - 2*S[2]).psi_involution()\n -2*S[1, 1] + S[1, 1, 1] + 2*S[2] - S[2, 1]\n\n The implementation at hand is tailored to the complete basis.\n It is equivalent to the generic implementation via the\n ribbon basis::\n\n sage: R = NSym.R()\n sage: all( R(S[I].psi_involution()) == R(S[I]).psi_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
return parent.sum((((((- 1) ** (I.size() - len(I))) * coeff) * parent.alternating_sum_of_finer_compositions(I)) for (I, coeff) in self._monomial_coefficients.items()))
S = complete = Complete
class Elementary(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n Elementary basis.\n\n The Elementary basis is defined in Definition 3.4 of [NCSF1]_,\n where it is denoted by `(\\Lambda^I)_I`. It is a multiplicative\n basis, and is obtained from the elementary generators\n `\\Lambda_i` of the ring of non-commutative symmetric functions\n through the formula\n `\\Lambda^{(i_1, i_2, \\ldots, i_k)}\n = \\Lambda_{i_1} \\Lambda_{i_2} \\cdots \\Lambda_{i_k}`\n for every composition `(i_1, i_2, \\ldots, i_k)`.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: L = NCSF.Elementary(); L\n Non-Commutative Symmetric Functions over the Rational Field in the Elementary basis\n sage: L.an_element()\n 2*L[] + 2*L[1] + 3*L[1, 1]\n\n The following are aliases for this basis::\n\n sage: NCSF.elementary()\n Non-Commutative Symmetric Functions over the Rational Field in the Elementary basis\n sage: NCSF.L()\n Non-Commutative Symmetric Functions over the Rational Field in the Elementary basis\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: NonCommutativeSymmetricFunctions(ZZ).elementary()\n Non-Commutative Symmetric Functions over the Integer Ring in the Elementary basis\n\n TESTS::\n\n sage: L = NonCommutativeSymmetricFunctions(ZZ).elementary()\n sage: TestSuite(L).run()\n\n We include a sanity test to verify the conversion between the\n elementary and complete basis works the way it should::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: L = NonCommutativeSymmetricFunctions(QQ).elementary()\n sage: L(S[3])\n L[1, 1, 1] - L[1, 2] - L[2, 1] + L[3]\n sage: L(S[2,1])\n L[1, 1, 1] - L[2, 1]\n sage: L(S[1,2])\n L[1, 1, 1] - L[1, 2]\n sage: L(S[1,1,1])\n L[1, 1, 1]\n sage: S(L[3])\n S[1, 1, 1] - S[1, 2] - S[2, 1] + S[3]\n sage: S(L[2,1])\n S[1, 1, 1] - S[2, 1]\n sage: S(L[1,2])\n S[1, 1, 1] - S[1, 2]\n sage: S(L[1,1,1])\n S[1, 1, 1]\n sage: all(S(L(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(L(S(L[comp])) == L[comp] for comp in Compositions(5))\n True\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='L', bracket=False, category=NCSF.MultiplicativeBasesOnGroupLikeElements())
class Element(CombinatorialFreeModule.Element):
def verschiebung(self, n):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined\n to be the map from the `\\mathbf{k}`-algebra of noncommutative\n symmetric functions to itself that sends the complete function\n `S^I` indexed by a composition `I = (i_1, i_2, \\ldots , i_k)`\n to `S^{(i_1/n, i_2/n, \\ldots , i_k/n)}` if all of the numbers\n `i_1, i_2, \\ldots, i_k` are divisible by `n`, and to `0`\n otherwise. This operator `\\mathbf{V}_n` is a Hopf algebra\n endomorphism. For every positive integer `r` with `n \\mid r`,\n it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = S_{r/n},\n \\quad \\mathbf{V}_n(\\Lambda_r) = (-1)^{r - r/n} \\Lambda_{r/n},\n \\quad \\mathbf{V}_n(\\Psi_r) = n \\Psi_{r/n},\n \\quad \\mathbf{V}_n(\\Phi_r) = n \\Phi_{r/n}\n\n (where `S_r` denotes the `r`-th complete non-commutative\n symmetric function, `\\Lambda_r` denotes the `r`-th elementary\n non-commutative symmetric function, `\\Psi_r` denotes the `r`-th\n power-sum non-commutative symmetric function of the first kind,\n and `\\Phi_r` denotes the `r`-th power-sum non-commutative\n symmetric function of the second kind). For every positive\n integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = \\mathbf{V}_n(\\Lambda_r)\n = \\mathbf{V}_n(\\Psi_r) = \\mathbf{V}_n(\\Phi_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism.\n\n It is a lift of the `n`-th Verschiebung operator on the ring\n of symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung`)\n to the ring of noncommutative symmetric functions.\n\n The action of the `n`-th Verschiebung operator can also be\n described on the ribbon Schur functions. Namely, every\n composition `I` of size `n \\ell` satisfies\n\n .. MATH::\n\n \\mathbf{V}_n ( R_I )\n = (-1)^{\\ell(I) - \\ell(J)} \\cdot R_{J / n},\n\n where `J` denotes the meet of the compositions `I` and\n `(\\underbrace{n, n, \\ldots, n}_{|I|/n \\mbox{ times}})`,\n where `\\ell(I)` is the length of `I`, and\n where `J / n` denotes the composition obtained by\n dividing every entry of `J` by `n`.\n For a composition `I` of size not divisible by `n`, we\n have `\\mathbf{V}_n ( R_I ) = 0`.\n\n .. SEEALSO::\n\n :meth:`verschiebung method of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.verschiebung>`,\n :meth:`frobenius method of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius>`,\n :meth:`verschiebung method of Sym\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of noncommutative symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: L = NSym.L()\n sage: L([4,2]).verschiebung(2)\n -L[2, 1]\n sage: L([2,4]).verschiebung(2)\n -L[1, 2]\n sage: L([6]).verschiebung(2)\n -L[3]\n sage: L([2,1]).verschiebung(3)\n 0\n sage: L([3]).verschiebung(2)\n 0\n sage: L([]).verschiebung(2)\n L[]\n sage: L([5, 1]).verschiebung(3)\n 0\n sage: L([5, 1]).verschiebung(6)\n 0\n sage: L([5, 1]).verschiebung(2)\n 0\n sage: L([1, 2, 3, 1]).verschiebung(7)\n 0\n sage: L([7]).verschiebung(7)\n L[1]\n sage: L([1, 2, 3, 1]).verschiebung(5)\n 0\n sage: (L[1] - L[2] + 2*L[3]).verschiebung(1)\n L[1] - L[2] + 2*L[3]\n\n TESTS:\n\n The current implementation on the Elementary basis gives\n the same results as the default implementation::\n\n sage: S = NSym.S()\n sage: def test_L(N, n):\n ....: for I in Compositions(N):\n ....: if S(L[I].verschiebung(n)) != S(L[I]).verschiebung(n):\n ....: return False\n ....: return True\n sage: test_L(4, 2)\n True\n sage: test_L(6, 2)\n True\n sage: test_L(6, 3)\n True\n sage: test_L(8, 4) # long time\n True\n '
parent = self.parent()
C = parent._indices
return parent.sum_of_terms([(C([(i // n) for i in I]), (coeff * ((- 1) ** ((sum(I) * (n - 1)) // n)))) for (I, coeff) in self if all((((i % n) == 0) for i in I))], distinct=True)
def star_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the star involution.\n\n The star involution is defined as the algebra antihomomorphism\n `NCSF \\to NCSF` which, for every positive integer `n`, sends\n the `n`-th complete non-commutative symmetric function `S_n` to\n `S_n`. Denoting by `f^{\\ast}` the image of an element\n `f \\in NCSF` under this star involution, it can be shown that\n every composition `I` satisfies\n\n .. MATH::\n\n (S^I)^{\\ast} = S^{I^r}, \\quad\n (\\Lambda^I)^{\\ast} = \\Lambda^{I^r}, \\quad\n R_I^{\\ast} = R_{I^r}, \\quad\n (\\Phi^I)^{\\ast} = \\Phi^{I^r},\n\n where `I^r` denotes the reversed composition of `I`, and\n standard notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `R` for the ribbon basis, and `\\Phi` for that of the power-sums\n of the second kind). The star involution is an involution and a\n coalgebra automorphism of `NCSF`. It is an automorphism of the\n graded vector space `NCSF`. Under the canonical isomorphism\n between the `n`-th graded component of `NCSF` and the descent\n algebra of the symmetric group `S_n` (see\n :meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_descent_algebra`),\n the star involution (restricted to\n the `n`-th graded component) corresponds to the automorphism\n of the descent algebra given by\n `x \\mapsto \\omega_n x \\omega_n`, where `\\omega_n` is the\n permutation `(n, n-1, \\ldots, 1) \\in S_n` (written here in\n one-line notation). If `\\pi` denotes the projection from `NCSF`\n to the ring of symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(f^{\\ast}) = \\pi(f)` for every `f \\in NCSF`.\n\n The star involution on `NCSF` is adjoint to the star involution\n on `QSym` by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n See [NCSF2]_, section 2.3 for the properties of this map.\n\n .. SEEALSO::\n\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: L = NSym.L()\n sage: L[3,3,2,3].star_involution()\n L[3, 2, 3, 3]\n sage: L[6,3,3].star_involution()\n L[3, 3, 6]\n sage: (L[1,9,1] - L[8,2] + 2*L[6,4] - 3*L[3] + 4*L[[]]).star_involution()\n 4*L[] + L[1, 9, 1] - L[2, 8] - 3*L[3] + 2*L[4, 6]\n sage: (L[3,3] - 2*L[2]).star_involution()\n -2*L[2] + L[3, 3]\n sage: L([4,1]).star_involution()\n L[1, 4]\n\n The implementation at hand is tailored to the elementary basis.\n It is equivalent to the generic implementation via the\n complete basis::\n\n sage: S = NSym.S()\n sage: all( S(L[I].star_involution()) == S(L[I]).star_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
dct = {I.reversed(): coeff for (I, coeff) in self}
return parent._from_dict(dct)
def psi_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `NCSF \\to NCSF` which, for every composition `I`, sends the\n complete noncommutative symmetric function `S^I` to the\n elementary noncommutative symmetric function `\\Lambda^I`.\n It can be shown that every composition `I` satisfies\n\n .. MATH::\n\n \\psi(R_I) = R_{I^c}, \\quad \\psi(S^I) = \\Lambda^I, \\quad\n \\psi(\\Lambda^I) = S^I, \\quad\n \\psi(\\Phi^I) = (-1)^{|I| - \\ell(I)} \\Phi^I\n\n where `I^c` denotes the complement of the composition `I`, and\n `\\ell(I)` denotes the length of `I`, and where standard\n notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `\\Phi` for the basis of the power sums of the second kind,\n and `R` for the ribbon basis). The map `\\psi` is an involution\n and a graded Hopf algebra automorphism of `NCSF`. If `\\pi`\n denotes the projection from `NCSF` to the ring of symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(\\psi(f)) = \\omega(\\pi(f))` for every `f \\in NCSF`, where\n the `\\omega` on the right hand side denotes the omega\n automorphism of `Sym`.\n\n The involution `\\psi` of `NCSF` is adjoint to the involution\n `\\psi` of `QSym` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`psi involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: L = NSym.L()\n sage: L[3,1].psi_involution()\n L[1, 1, 1, 1] - L[1, 2, 1] - L[2, 1, 1] + L[3, 1]\n sage: S(L[3,1].psi_involution())\n S[3, 1]\n sage: L[[]].psi_involution()\n L[]\n sage: L[1,1].psi_involution()\n L[1, 1]\n sage: (L[2,1] - 2*L[2]).psi_involution()\n -2*L[1, 1] + L[1, 1, 1] + 2*L[2] - L[2, 1]\n\n The implementation at hand is tailored to the elementary basis.\n It is equivalent to the generic implementation via the\n ribbon basis::\n\n sage: R = NSym.R()\n sage: all( R(L[I].psi_involution()) == R(L[I]).psi_involution()\n ....: for I in Compositions(3) )\n True\n sage: all( R(L[I].psi_involution()) == R(L[I]).psi_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
return parent.sum((((((- 1) ** (I.size() - len(I))) * coeff) * parent.alternating_sum_of_finer_compositions(I)) for (I, coeff) in self._monomial_coefficients.items()))
L = elementary = Elementary
class Psi(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n Psi basis.\n\n The Psi basis is defined in Definition 3.4 of [NCSF1]_, where\n it is denoted by `(\\Psi^I)_I`. It is a multiplicative basis, and\n is connected to the elementary generators `\\Lambda_i` of the ring\n of non-commutative symmetric functions by the following relation:\n Define a non-commutative symmetric function `\\Psi_n` for every\n positive integer `n` by the power series identity\n\n .. MATH::\n\n \\frac{d}{dt} \\sigma(t)\n = \\sigma(t) \\cdot \\left( \\sum_{k \\geq 1} t^{k-1} \\Psi_k \\right),\n\n where\n\n .. MATH::\n\n \\sigma(t) = \\left( \\sum_{k \\geq 0} (-t)^k \\Lambda_k \\right)^{-1}\n\n and where `\\Lambda_0` denotes `1`. For every composition\n `(i_1, i_2, \\ldots, i_k)`, we have\n `\\Psi^{(i_1, i_2, \\ldots, i_k)}\n = \\Psi_{i_1} \\Psi_{i_2} \\cdots \\Psi_{i_k}`.\n\n The `\\Psi`-basis is a basis only when the base ring is a\n `\\QQ`-algebra (although the `\\Psi^I` can be defined over any base\n ring). The elements of the `\\Psi`-basis are known as the\n "power-sum non-commutative symmetric functions of the first kind".\n The generators `\\Psi_n` correspond to the Dynkin\n (quasi-)idempotents in the descent algebras of the symmetric\n groups (see [NCSF1]_, 5.2 for details).\n\n Another (equivalent) definition of `\\Psi_n` is\n\n .. MATH::\n\n \\Psi_n = \\sum_{i=0}^{n-1} (-1)^i R_{1^i, n-i},\n\n where `R` denotes the ribbon basis of `NCSF`, and where `1^i`\n stands for `i` repetitions of the integer `1`.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = NCSF.Psi(); Psi\n Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: Psi.an_element()\n 2*Psi[] + 2*Psi[1] + 3*Psi[1, 1]\n\n Checking the equivalent definition of `\\Psi_n`::\n\n sage: def test_psi(n):\n ....: NCSF = NonCommutativeSymmetricFunctions(ZZ)\n ....: R = NCSF.R()\n ....: Psi = NCSF.Psi()\n ....: a = R.sum([(-1) ** i * R[[1]*i + [n-i]]\n ....: for i in range(n)])\n ....: return a == R(Psi[n])\n sage: test_psi(2)\n True\n sage: test_psi(3)\n True\n sage: test_psi(4)\n True\n '
def __init__(self, NCSF):
'\n TESTS:\n\n We include a sanity test to verify the conversion to\n and from the complete basis works the way it should::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi(); Psi\n Non-Commutative Symmetric Functions over the Rational Field in the Psi basis\n sage: all(S(Psi(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(Psi(S(Psi[comp])) == Psi[comp] for comp in Compositions(5))\n True\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='Psi', bracket=False, category=NCSF.MultiplicativeBasesOnPrimitiveElements())
def _from_complete_on_generators(self, n):
'\n Expand a complete generator of non-commutative symmetric\n functions in the Psi basis.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - The expansion of the complete generator indexed by ``n`` into the\n Psi basis.\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi._from_complete_on_generators(1)\n Psi[1]\n sage: Psi._from_complete_on_generators(2)\n 1/2*Psi[1, 1] + 1/2*Psi[2]\n sage: Psi._from_complete_on_generators(3)\n 1/6*Psi[1, 1, 1] + 1/3*Psi[1, 2] + 1/6*Psi[2, 1] + 1/3*Psi[3]\n '
one = self.base_ring().one()
I = self._indices([n])
return self.sum_of_terms(((J, (one / coeff_pi(J, I))) for J in Compositions(n)), distinct=True)
def _to_complete_on_generators(self, n):
'\n Expand a `\\Psi` basis element of non-commutative symmetric\n functions in the complete basis.\n\n This formula is given in Proposition 4.5 of [NCSF1]_ which states\n\n .. MATH::\n\n \\Psi_n = \\sum_{J \\models n} (-1)^{\\ell(J)-1} lp(J,I) S^J.\n\n The coefficient `lp(J,I)` is given in the function\n :meth:`sage.combinat.ncsf_qsym.combinatorics.coeff_lp`.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - The expansion of the `\\Psi` function indexed by ``n`` in the\n complete basis.\n\n TESTS::\n\n sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n sage: Psi._to_complete_on_generators(1)\n S[1]\n sage: Psi._to_complete_on_generators(2)\n -S[1, 1] + 2*S[2]\n sage: Psi._to_complete_on_generators(3)\n S[1, 1, 1] - 2*S[1, 2] - S[2, 1] + 3*S[3]\n '
minus_one = (- self.base_ring().one())
complete = self.realization_of().complete()
return complete.sum_of_terms(((J, ((minus_one ** (len(J) + 1)) * coeff_lp(J, [n]))) for J in Compositions(n)), distinct=True)
def internal_product_on_basis_by_bracketing(self, I, J):
'\n The internal product of two elements of the Psi basis.\n\n See :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.GradedModulesWithInternalProduct.ElementMethods.internal_product`\n for a thorough documentation of this operation.\n\n This is an implementation using [NCSF2]_ Lemma 3.10.\n It is fast when the length of `I` is small, but can get\n very slow otherwise. Therefore it is not being used by\n default for internally multiplying Psi functions.\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The internal product of the elements of the Psi basis of\n `NSym` indexed by ``I`` and ``J``, expressed in the Psi\n basis.\n\n AUTHORS:\n\n - Travis Scrimshaw, 29 Mar 2014\n\n EXAMPLES::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: Psi = N.Psi()\n sage: Psi.internal_product_on_basis_by_bracketing([2,2],[1,2,1])\n 0\n sage: Psi.internal_product_on_basis_by_bracketing([1,2,1],[2,1,1])\n 4*Psi[1, 2, 1]\n sage: Psi.internal_product_on_basis_by_bracketing([2,1,1],[1,2,1])\n 4*Psi[2, 1, 1]\n sage: Psi.internal_product_on_basis_by_bracketing([1,2,1], [1,1,1,1])\n 0\n sage: Psi.internal_product_on_basis_by_bracketing([3,1], [1,2,1])\n -Psi[1, 2, 1] + Psi[2, 1, 1]\n sage: Psi.internal_product_on_basis_by_bracketing([1,2,1], [3,1])\n 0\n sage: Psi.internal_product_on_basis_by_bracketing([2,2],[1,2])\n 0\n sage: Psi.internal_product_on_basis_by_bracketing([4], [1,2,1])\n -Psi[1, 1, 2] + 2*Psi[1, 2, 1] - Psi[2, 1, 1]\n\n TESTS:\n\n The internal product computed by this method is identical with\n the one obtained by coercion to the complete basis::\n\n sage: S = N.S()\n sage: def psi_int_test(n):\n ....: for I in Compositions(n):\n ....: for J in Compositions(n):\n ....: a = S(Psi.internal_product_on_basis_by_bracketing(I, J))\n ....: b = S(Psi[I]).internal_product(S(Psi[J]))\n ....: if a != b:\n ....: return False\n ....: return True\n sage: all( psi_int_test(i) for i in range(4) )\n True\n sage: psi_int_test(4) # long time\n True\n '
if (sum(I) != sum(J)):
return self.zero()
p = len(I)
q = len(J)
if (p > q):
return self.zero()
if (p == q):
Is = sorted(I, reverse=True)
Js = sorted(J, reverse=True)
if (Is != Js):
return 0
return (Partition(Is).centralizer_size() * self[I])
def Gamma(K):
'\n Compute `\\Gamma_K` for a nonempty composition `K` (which\n can be encoded as a list). See the doc of\n :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.GradedModulesWithInternalProduct.ElementMethods.internal_product`\n for a definition of this.\n '
k1 = K[0]
res = (k1 * self[k1])
for k in K[1:]:
Psik = self[k]
res = ((res * Psik) - (Psik * res))
return res
if (p == 1):
return Gamma(J)
K = [[(- 1)]]
cur_sum = 0
base = set(range(q))
result = self.zero()
while True:
if ((len(K) > p) or (not base)):
base.union(K.pop()[:(- 1)])
part = K[(- 1)]
base.add(part[(- 1)])
else:
part = K[(- 1)]
Ik = I[(len(K) - 1)]
cur_sum = sum((J[j] for j in part[:(- 1)]))
while (cur_sum != Ik):
part[(- 1)] += 1
if (part[(- 1)] >= q):
part.pop()
if (not part):
break
base.add(part[(- 1)])
cur_sum -= J[part[(- 1)]]
elif ((part[(- 1)] in base) and ((cur_sum + J[part[(- 1)]]) <= Ik)):
cur_sum += J[part[(- 1)]]
base.remove(part[(- 1)])
if (cur_sum < Ik):
part.append(part[(- 1)])
if (not part):
K.pop()
if (not K):
break
base.add(K[(- 1)][(- 1)])
continue
if ((not base) and (len(K) == p)):
result += self.prod((Gamma(tuple((J[j] for j in S))) for S in K))
base.add(part[(- 1)])
else:
K.append([(- 1)])
return result
class Element(CombinatorialFreeModule.Element):
def verschiebung(self, n):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined\n to be the map from the `\\mathbf{k}`-algebra of noncommutative\n symmetric functions to itself that sends the complete function\n `S^I` indexed by a composition `I = (i_1, i_2, \\ldots , i_k)`\n to `S^{(i_1/n, i_2/n, \\ldots , i_k/n)}` if all of the numbers\n `i_1, i_2, \\ldots, i_k` are divisible by `n`, and to `0`\n otherwise. This operator `\\mathbf{V}_n` is a Hopf algebra\n endomorphism. For every positive integer `r` with `n \\mid r`,\n it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = S_{r/n},\n \\quad \\mathbf{V}_n(\\Lambda_r) = (-1)^{r - r/n} \\Lambda_{r/n},\n \\quad \\mathbf{V}_n(\\Psi_r) = n \\Psi_{r/n},\n \\quad \\mathbf{V}_n(\\Phi_r) = n \\Phi_{r/n}\n\n (where `S_r` denotes the `r`-th complete non-commutative\n symmetric function, `\\Lambda_r` denotes the `r`-th elementary\n non-commutative symmetric function, `\\Psi_r` denotes the `r`-th\n power-sum non-commutative symmetric function of the first kind,\n and `\\Phi_r` denotes the `r`-th power-sum non-commutative\n symmetric function of the second kind). For every positive\n integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = \\mathbf{V}_n(\\Lambda_r)\n = \\mathbf{V}_n(\\Psi_r) = \\mathbf{V}_n(\\Phi_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism.\n\n It is a lift of the `n`-th Verschiebung operator on the ring\n of symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung`)\n to the ring of noncommutative symmetric functions.\n\n The action of the `n`-th Verschiebung operator can also be\n described on the ribbon Schur functions. Namely, every\n composition `I` of size `n \\ell` satisfies\n\n .. MATH::\n\n \\mathbf{V}_n ( R_I )\n = (-1)^{\\ell(I) - \\ell(J)} \\cdot R_{J / n},\n\n where `J` denotes the meet of the compositions `I` and\n `(\\underbrace{n, n, \\ldots, n}_{|I|/n \\mbox{ times}})`,\n where `\\ell(I)` is the length of `I`, and\n where `J / n` denotes the composition obtained by\n dividing every entry of `J` by `n`.\n For a composition `I` of size not divisible by `n`, we\n have `\\mathbf{V}_n ( R_I ) = 0`.\n\n .. SEEALSO::\n\n :meth:`verschiebung method of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.verschiebung>`,\n :meth:`frobenius method of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius>`,\n :meth:`verschiebung method of Sym\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of noncommutative symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: Psi = NSym.Psi()\n sage: Psi([4,2]).verschiebung(2)\n 4*Psi[2, 1]\n sage: Psi([2,4]).verschiebung(2)\n 4*Psi[1, 2]\n sage: Psi([6]).verschiebung(2)\n 2*Psi[3]\n sage: Psi([2,1]).verschiebung(3)\n 0\n sage: Psi([3]).verschiebung(2)\n 0\n sage: Psi([]).verschiebung(2)\n Psi[]\n sage: Psi([5, 1]).verschiebung(3)\n 0\n sage: Psi([5, 1]).verschiebung(6)\n 0\n sage: Psi([5, 1]).verschiebung(2)\n 0\n sage: Psi([1, 2, 3, 1]).verschiebung(7)\n 0\n sage: Psi([7]).verschiebung(7)\n 7*Psi[1]\n sage: Psi([1, 2, 3, 1]).verschiebung(5)\n 0\n sage: (Psi[1] - Psi[2] + 2*Psi[3]).verschiebung(1)\n Psi[1] - Psi[2] + 2*Psi[3]\n\n TESTS:\n\n The current implementation on the Psi basis gives the\n same results as the default implementation::\n\n sage: S = NSym.S()\n sage: def test_psi(N, n):\n ....: for I in Compositions(N):\n ....: if S(Psi[I].verschiebung(n)) != S(Psi[I]).verschiebung(n):\n ....: return False\n ....: return True\n sage: test_psi(4, 2)\n True\n sage: test_psi(6, 2)\n True\n sage: test_psi(6, 3)\n True\n sage: test_psi(8, 4) # long time\n True\n '
parent = self.parent()
C = parent._indices
return parent.sum_of_terms([(C([(i // n) for i in I]), (coeff * (n ** len(I)))) for (I, coeff) in self if all((((i % n) == 0) for i in I))], distinct=True)
class Phi(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n Phi basis.\n\n The Phi basis is defined in Definition 3.4 of [NCSF1]_, where\n it is denoted by `(\\Phi^I)_I`. It is a multiplicative basis, and\n is connected to the elementary generators `\\Lambda_i` of the ring\n of non-commutative symmetric functions by the following relation:\n Define a non-commutative symmetric function `\\Phi_n` for every\n positive integer `n` by the power series identity\n\n .. MATH::\n\n \\sum_{k\\geq 1} t^k \\frac{1}{k} \\Phi_k\n = -\\log \\left( \\sum_{k \\geq 0} (-t)^k \\Lambda_k \\right),\n\n with `\\Lambda_0` denoting `1`. For every composition\n `(i_1, i_2, \\ldots, i_k)`, we have\n `\\Phi^{(i_1, i_2, \\ldots, i_k)}\n = \\Phi_{i_1} \\Phi_{i_2} \\cdots \\Phi_{i_k}`.\n\n The `\\Phi`-basis is well-defined only when the base ring is a\n `\\QQ`-algebra. The elements of the `\\Phi`-basis are known as the\n "power-sum non-commutative symmetric functions of the second\n kind".\n\n The generators `\\Phi_n` are related to the (first) Eulerian\n idempotents in the descent algebras of the symmetric groups (see\n [NCSF1]_, 5.4 for details).\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NCSF.Phi(); Phi\n Non-Commutative Symmetric Functions over the Rational Field in the Phi basis\n sage: Phi.an_element()\n 2*Phi[] + 2*Phi[1] + 3*Phi[1, 1]\n '
def __init__(self, NCSF):
'\n TESTS:\n\n We include a sanity test to verify the conversion to\n and from the complete basis works the way it should::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi(); Phi\n Non-Commutative Symmetric Functions over the Rational Field in the Phi basis\n sage: all(S(Phi(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(Phi(S(Phi[comp])) == Phi[comp] for comp in Compositions(5))\n True\n\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='Phi', bracket=False, category=NCSF.MultiplicativeBasesOnPrimitiveElements())
def _from_complete_on_generators(self, n):
'\n Expand a complete basis element of non-commutative symmetric\n functions in the `\\Phi` basis.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - The expansion of the complete function indexed by ``n`` in the\n `\\Phi` basis.\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n sage: Phi._from_complete_on_generators(1)\n Phi[1]\n sage: Phi._from_complete_on_generators(2)\n 1/2*Phi[1, 1] + 1/2*Phi[2]\n sage: Phi._from_complete_on_generators(3)\n 1/6*Phi[1, 1, 1] + 1/4*Phi[1, 2] + 1/4*Phi[2, 1] + 1/3*Phi[3]\n '
one = self.base_ring().one()
return self.sum_of_terms(((J, (one / coeff_sp(J, [n]))) for J in Compositions(n)), distinct=True)
def _to_complete_on_generators(self, n):
'\n Expand a `\\Phi` basis element of non-commutative symmetric\n functions in the complete basis.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n - The expansion of the `\\Phi` function indexed by ``n`` in the\n complete basis.\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n sage: Phi._to_complete_on_generators(1)\n S[1]\n sage: Phi._to_complete_on_generators(2)\n -S[1, 1] + 2*S[2]\n sage: Phi._to_complete_on_generators(3)\n S[1, 1, 1] - 3/2*S[1, 2] - 3/2*S[2, 1] + 3*S[3]\n '
minus_one = (- self.base_ring().one())
complete = self.realization_of().complete()
return complete.sum_of_terms(((J, (((minus_one ** (len(J) + 1)) * n) / coeff_ell(J, [n]))) for J in Compositions(n)), distinct=True)
class Element(CombinatorialFreeModule.Element):
def verschiebung(self, n):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined\n to be the map from the `\\mathbf{k}`-algebra of noncommutative\n symmetric functions to itself that sends the complete function\n `S^I` indexed by a composition `I = (i_1, i_2, \\ldots , i_k)`\n to `S^{(i_1/n, i_2/n, \\ldots , i_k/n)}` if all of the numbers\n `i_1, i_2, \\ldots, i_k` are divisible by `n`, and to `0`\n otherwise. This operator `\\mathbf{V}_n` is a Hopf algebra\n endomorphism. For every positive integer `r` with `n \\mid r`,\n it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = S_{r/n},\n \\quad \\mathbf{V}_n(\\Lambda_r) = (-1)^{r - r/n} \\Lambda_{r/n},\n \\quad \\mathbf{V}_n(\\Psi_r) = n \\Psi_{r/n},\n \\quad \\mathbf{V}_n(\\Phi_r) = n \\Phi_{r/n}\n\n (where `S_r` denotes the `r`-th complete non-commutative\n symmetric function, `\\Lambda_r` denotes the `r`-th elementary\n non-commutative symmetric function, `\\Psi_r` denotes the `r`-th\n power-sum non-commutative symmetric function of the first kind,\n and `\\Phi_r` denotes the `r`-th power-sum non-commutative\n symmetric function of the second kind). For every positive\n integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(S_r) = \\mathbf{V}_n(\\Lambda_r)\n = \\mathbf{V}_n(\\Psi_r) = \\mathbf{V}_n(\\Phi_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism.\n\n It is a lift of the `n`-th Verschiebung operator on the ring\n of symmetric functions\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung`)\n to the ring of noncommutative symmetric functions.\n\n The action of the `n`-th Verschiebung operator can also be\n described on the ribbon Schur functions. Namely, every\n composition `I` of size `n \\ell` satisfies\n\n .. MATH::\n\n \\mathbf{V}_n ( R_I )\n = (-1)^{\\ell(I) - \\ell(J)} \\cdot R_{J / n},\n\n where `J` denotes the meet of the compositions `I` and\n `(\\underbrace{n, n, \\ldots, n}_{|I|/n \\mbox{ times}})`,\n where `\\ell(I)` is the length of `I`, and\n where `J / n` denotes the composition obtained by\n dividing every entry of `J` by `n`.\n For a composition `I` of size not divisible by `n`, we\n have `\\mathbf{V}_n ( R_I ) = 0`.\n\n .. SEEALSO::\n\n :meth:`verschiebung method of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.verschiebung>`,\n :meth:`frobenius method of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius>`,\n :meth:`verschiebung method of Sym\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.verschiebung>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of noncommutative symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(ZZ)\n sage: Phi = NSym.Phi()\n sage: Phi([4,2]).verschiebung(2)\n 4*Phi[2, 1]\n sage: Phi([2,4]).verschiebung(2)\n 4*Phi[1, 2]\n sage: Phi([6]).verschiebung(2)\n 2*Phi[3]\n sage: Phi([2,1]).verschiebung(3)\n 0\n sage: Phi([3]).verschiebung(2)\n 0\n sage: Phi([]).verschiebung(2)\n Phi[]\n sage: Phi([5, 1]).verschiebung(3)\n 0\n sage: Phi([5, 1]).verschiebung(6)\n 0\n sage: Phi([5, 1]).verschiebung(2)\n 0\n sage: Phi([1, 2, 3, 1]).verschiebung(7)\n 0\n sage: Phi([7]).verschiebung(7)\n 7*Phi[1]\n sage: Phi([1, 2, 3, 1]).verschiebung(5)\n 0\n sage: (Phi[1] - Phi[2] + 2*Phi[3]).verschiebung(1)\n Phi[1] - Phi[2] + 2*Phi[3]\n\n TESTS:\n\n The current implementation on the Phi basis gives the\n same results as the default implementation::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NSym.S()\n sage: Phi = NSym.Phi()\n sage: def test_phi(N, n):\n ....: for I in Compositions(N):\n ....: if S(Phi[I].verschiebung(n)) != S(Phi[I]).verschiebung(n):\n ....: return False\n ....: return True\n sage: test_phi(4, 2)\n True\n sage: test_phi(6, 2)\n True\n sage: test_phi(6, 3)\n True\n sage: test_phi(8, 4) # long time\n True\n '
parent = self.parent()
C = parent._indices
return parent.sum_of_terms([(C([(i // n) for i in I]), (coeff * (n ** len(I)))) for (I, coeff) in self if all((((i % n) == 0) for i in I))], distinct=True)
def star_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the star involution.\n\n The star involution is defined as the algebra antihomomorphism\n `NCSF \\to NCSF` which, for every positive integer `n`, sends\n the `n`-th complete non-commutative symmetric function `S_n` to\n `S_n`. Denoting by `f^{\\ast}` the image of an element\n `f \\in NCSF` under this star involution, it can be shown that\n every composition `I` satisfies\n\n .. MATH::\n\n (S^I)^{\\ast} = S^{I^r}, \\quad\n (\\Lambda^I)^{\\ast} = \\Lambda^{I^r}, \\quad\n R_I^{\\ast} = R_{I^r}, \\quad\n (\\Phi^I)^{\\ast} = \\Phi^{I^r},\n\n where `I^r` denotes the reversed composition of `I`, and\n standard notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `R` for the ribbon basis, and `\\Phi` for that of the power-sums\n of the second kind). The star involution is an involution and a\n coalgebra automorphism of `NCSF`. It is an automorphism of the\n graded vector space `NCSF`. Under the canonical isomorphism\n between the `n`-th graded component of `NCSF` and the descent\n algebra of the symmetric group `S_n` (see\n :meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_descent_algebra`),\n the star involution (restricted to\n the `n`-th graded component) corresponds to the automorphism\n of the descent algebra given by\n `x \\mapsto \\omega_n x \\omega_n`, where `\\omega_n` is the\n permutation `(n, n-1, \\ldots, 1) \\in S_n` (written here in\n one-line notation). If `\\pi` denotes the projection from `NCSF`\n to the ring of symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(f^{\\ast}) = \\pi(f)` for every `f \\in NCSF`.\n\n The star involution on `NCSF` is adjoint to the star involution\n on `QSym` by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n See [NCSF2]_, section 2.3 for the properties of this map.\n\n .. SEEALSO::\n\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NSym.Phi()\n sage: Phi[3,1,1,4].star_involution()\n Phi[4, 1, 1, 3]\n sage: Phi[4,2,1].star_involution()\n Phi[1, 2, 4]\n sage: (Phi[1,4] - Phi[2,3] + 2*Phi[5,4] - 3*Phi[3] + 4*Phi[[]]).star_involution()\n 4*Phi[] - 3*Phi[3] - Phi[3, 2] + Phi[4, 1] + 2*Phi[4, 5]\n sage: (Phi[3,3] + 3*Phi[1]).star_involution()\n 3*Phi[1] + Phi[3, 3]\n sage: Phi([2,1]).star_involution()\n Phi[1, 2]\n\n The implementation at hand is tailored to the Phi basis.\n It is equivalent to the generic implementation via the\n complete basis::\n\n sage: S = NSym.S()\n sage: all( S(Phi[I].star_involution()) == S(Phi[I]).star_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
dct = {I.reversed(): coeff for (I, coeff) in self}
return parent._from_dict(dct)
def psi_involution(self):
'\n Return the image of the noncommutative symmetric function\n ``self`` under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `NCSF \\to NCSF` which, for every composition `I`, sends the\n complete noncommutative symmetric function `S^I` to the\n elementary noncommutative symmetric function `\\Lambda^I`.\n It can be shown that every composition `I` satisfies\n\n .. MATH::\n\n \\psi(R_I) = R_{I^c}, \\quad \\psi(S^I) = \\Lambda^I, \\quad\n \\psi(\\Lambda^I) = S^I, \\quad\n \\psi(\\Phi^I) = (-1)^{|I| - \\ell(I)} \\Phi^I\n\n where `I^c` denotes the complement of the composition `I`, and\n `\\ell(I)` denotes the length of `I`, and where standard\n notations for classical bases of `NCSF` are being used\n (`S` for the complete basis, `\\Lambda` for the elementary basis,\n `\\Phi` for the basis of the power sums of the second kind,\n and `R` for the ribbon basis). The map `\\psi` is an involution\n and a graded Hopf algebra automorphism of `NCSF`. If `\\pi`\n denotes the projection from `NCSF` to the ring of symmetric functions\n (:meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`),\n then `\\pi(\\psi(f)) = \\omega(\\pi(f))` for every `f \\in NCSF`, where\n the `\\omega` on the right hand side denotes the omega\n automorphism of `Sym`.\n\n The involution `\\psi` of `NCSF` is adjoint to the involution\n `\\psi` of `QSym` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`psi involution of QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution of NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: Phi = NSym.Phi()\n sage: Phi[3,2].psi_involution()\n -Phi[3, 2]\n sage: Phi[2,2].psi_involution()\n Phi[2, 2]\n sage: Phi[[]].psi_involution()\n Phi[]\n sage: (Phi[2,1] - 2*Phi[2]).psi_involution()\n 2*Phi[2] - Phi[2, 1]\n sage: Phi(0).psi_involution()\n 0\n\n The implementation at hand is tailored to the Phi basis.\n It is equivalent to the generic implementation via the\n ribbon basis::\n\n sage: R = NSym.R()\n sage: all( R(Phi[I].psi_involution()) == R(Phi[I]).psi_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
dct = {I: (((- 1) ** (I.size() - len(I))) * coeff) for (I, coeff) in self}
return parent._from_dict(dct)
class Monomial(CombinatorialFreeModule, BindableClass):
"\n The monomial basis defined in Tevlin's paper [Tev2007]_.\n\n The monomial basis is well-defined only when the base ring is a\n `\\QQ`-algebra. It is the basis denoted by `(M^I)_I` in [Tev2007]_.\n\n TESTS::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: nM = NCSF.monomial(); nM\n Non-Commutative Symmetric Functions over the Rational Field in the Monomial basis\n sage: nM([1,1])*nM([2])\n 3*nM[1, 1, 2] + nM[1, 3] + nM[2, 2]\n sage: R = NCSF.ribbon()\n sage: nM(R[1,3,1])\n 11*nM[1, 1, 1, 1, 1] + 8*nM[1, 1, 2, 1] + 8*nM[1, 2, 1, 1] + 5*nM[1, 3, 1] + 8*nM[2, 1, 1, 1] + 5*nM[2, 2, 1] + 5*nM[3, 1, 1] + 2*nM[4, 1]\n "
def __init__(self, NCSF):
'\n TESTS:\n\n We include a sanity test to verify the conversion to\n and from the complete basis works the way it should::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: nM = NonCommutativeSymmetricFunctions(QQ).Monomial(); nM\n Non-Commutative Symmetric Functions over the Rational Field in the Monomial basis\n sage: all(S(nM(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(nM(S(nM[comp])) == nM[comp] for comp in Compositions(5))\n True\n\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='nM', bracket=False, category=NCSF.Bases())
category = self.category()
NCSF = NonCommutativeSymmetricFunctions(self.base_ring())
S = NCSF.complete()
Psi = NCSF.Psi()
to_S = self.module_morphism(on_basis=self._to_complete_on_basis, codomain=S, category=category)
to_S.register_as_coercion()
from_psi = Psi.module_morphism(on_basis=self._from_psi_on_basis, codomain=self, category=category)
from_psi.register_as_coercion()
def _to_complete_on_basis(self, I):
'\n Expand a Monomial basis element of non-commutative symmetric functions\n in the complete basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The expansion of the Monomial function indexed by ``I`` in\n the complete basis.\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: nM = NonCommutativeSymmetricFunctions(QQ).nM()\n sage: nM._to_complete_on_basis(Composition([1,1,1]))\n S[1, 1, 1] - S[1, 2] - S[2, 1] + S[3]\n sage: nM._to_complete_on_basis(Composition([1,2]))\n -S[1, 1, 1] + 2*S[1, 2] + 1/2*S[2, 1] - 3/2*S[3]\n sage: nM._to_complete_on_basis(Composition([2,1]))\n -S[1, 1, 1] + S[1, 2] + 3/2*S[2, 1] - 3/2*S[3]\n sage: nM._to_complete_on_basis(Composition([3]))\n S[1, 1, 1] - 2*S[1, 2] - S[2, 1] + 3*S[3]\n '
S = NonCommutativeSymmetricFunctions(self.base_ring()).S()
return S.sum_of_terms(((K, m_to_s_stat(self.base_ring(), I, K)) for K in Compositions(sum(I))), distinct=True)
def _from_psi_on_basis(self, I):
'\n Expand a Psi basis element of non-commutative symmetric functions\n in the Monomial basis.\n\n INPUT:\n\n - ``self`` - the Monomial basis of non-commutative symmetric functions\n - ``I`` - a composition\n\n OUTPUT:\n\n - The expansion of the Psi function indexed by ``I`` into the Monomial\n basis.\n\n TESTS::\n\n sage: nM=NonCommutativeSymmetricFunctions(QQ).nM()\n sage: nM._from_psi_on_basis(Composition([3]))\n nM[3]\n sage: nM._from_psi_on_basis(Composition([1,2]))\n 2*nM[1, 2] + nM[3]\n sage: nM._from_psi_on_basis(Composition([2,1]))\n 2*nM[2, 1] + nM[3]\n sage: nM._from_psi_on_basis(Composition([1,1,1]))\n 6*nM[1, 1, 1] + 2*nM[1, 2] + 4*nM[2, 1] + nM[3]\n '
M = NonCommutativeSymmetricFunctions(self.base_ring()).nM()
sum_of_elements = M.zero()
for J in Compositions(I.size()):
if I.is_finer(J):
len_of_J = len(J)
p = ([0] + self._indices(I).refinement_splitting_lengths(J).partial_sums())
sum_of_elements += (prod((((len_of_J - k) ** (p[(k + 1)] - p[k])) for k in range(len_of_J))) * M(J))
return sum_of_elements
nM = monomial = Monomial
class Immaculate(CombinatorialFreeModule, BindableClass):
"\n The immaculate basis of the non-commutative symmetric\n functions.\n\n The immaculate basis first appears in Berg, Bergeron,\n Saliola, Serrano and Zabrocki's [BBSSZ2012]_. It can be\n described as the family `(\\mathfrak{S}_{\\alpha})`, where\n `\\alpha` runs over all compositions, and\n `\\mathfrak{S}_{\\alpha}` denotes the immaculate function\n corresponding to `\\alpha` (see\n :meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ParentMethods.immaculate_function`).\n\n If `\\alpha` is a composition `(\\alpha_1, \\alpha_2, \\ldots,\n \\alpha_m)`, then\n\n .. MATH::\n\n \\mathfrak{S}_{\\alpha}\n = \\sum_{\\sigma \\in S_m} (-1)^{\\sigma}\n S_{\\alpha_1 + \\sigma(1) - 1} S_{\\alpha_2 + \\sigma(2) - 2}\n \\cdots S_{\\alpha_m + \\sigma(m) - m}.\n\n .. WARNING::\n\n This *basis* contains only the immaculate functions\n indexed by compositions (i.e., finite sequences of\n positive integers). To obtain the remaining immaculate\n functions (sensu lato), use the\n :meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ParentMethods.immaculate_function`\n method. Calling the immaculate *basis* with a list\n which is not a composition will currently return\n garbage!\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: I = NCSF.I()\n sage: I([1,3,2])*I([1])\n I[1, 3, 2, 1] + I[1, 3, 3] + I[1, 4, 2] + I[2, 3, 2]\n sage: I([1])*I([1,3,2])\n I[1, 1, 3, 2] - I[2, 2, 1, 2] - I[2, 2, 2, 1] - I[2, 2, 3] - I[3, 2, 2]\n sage: I([1,3])*I([1,1])\n I[1, 3, 1, 1] + I[1, 4, 1] + I[2, 3, 1] + I[2, 4]\n sage: I([3,1])*I([2,1])\n I[3, 1, 2, 1] + I[3, 2, 1, 1] + I[3, 2, 2] + I[3, 3, 1] + I[4, 1, 1, 1] + I[4, 1, 2] + 2*I[4, 2, 1] + I[4, 3] + I[5, 1, 1] + I[5, 2]\n sage: R = NCSF.ribbon()\n sage: I(R[1,3,1])\n I[1, 3, 1] + I[2, 2, 1] + I[2, 3] + I[3, 1, 1] + I[3, 2]\n sage: R(I(R([2,1,3])))\n R[2, 1, 3]\n "
def __init__(self, NCSF):
'\n TESTS:\n\n We include a sanity test to verify the conversion to\n and from the complete basis works the way it should::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).complete()\n sage: I = NonCommutativeSymmetricFunctions(QQ).Immaculate(); I\n Non-Commutative Symmetric Functions over the Rational Field in the Immaculate basis\n sage: all(S(I(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(I(S(I[comp])) == I[comp] for comp in Compositions(5))\n True\n\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='I', bracket=False, category=NCSF.Bases())
category = self.category()
S = self.realization_of().complete()
to_S = self.module_morphism(on_basis=self._to_complete_on_basis, codomain=S, category=category)
to_S.register_as_coercion()
from_S = S.module_morphism(on_basis=self._from_complete_on_basis, codomain=self, category=category)
from_S.register_as_coercion()
def _realization_name(self):
"\n TESTS::\n\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: I = N.I()\n sage: I._realization_name()\n 'Immaculate'\n "
return 'Immaculate'
def _H(self, alpha):
'\n Return the complete basis element indexed by a list ``alpha`` if\n the list happens to be a composition (possibly with `0`s\n interspersed). Otherwise, return `0`.\n\n INPUT:\n\n - ``alpha`` -- a list\n\n OUTPUT:\n\n - the complete basis element indexed by ``alpha`` (with any\n zeroes removed) if all entries of ``alpha`` are nonnegative;\n otherwise, `0`\n\n EXAMPLES::\n\n sage: I = NonCommutativeSymmetricFunctions(QQ).I()\n sage: I._H([2,0,1])\n S[2, 1]\n sage: I._H([2,0,1,-1])\n 0\n sage: I._H([1,0,2])\n S[1, 2]\n '
S = NonCommutativeSymmetricFunctions(self.base_ring()).complete()
if any(((d < 0) for d in alpha)):
return S.zero()
return S([d for d in alpha if (d > 0)])
@cached_method
def _to_complete_on_basis(self, alpha):
'\n Return the expansion of an Immaculate basis element in the\n complete basis.\n\n INPUT:\n\n - ``alpha`` -- a composition\n\n OUTPUT:\n\n - The expansion in the complete basis of the basis element\n of the Immaculate basis ``self`` indexed by the\n composition ``alpha``.\n\n EXAMPLES::\n\n sage: I = NonCommutativeSymmetricFunctions(QQ).I()\n sage: I._to_complete_on_basis(Composition([]))\n S[]\n sage: I._to_complete_on_basis(Composition([2,1,3]))\n S[2, 1, 3] - S[2, 2, 2] + S[3, 2, 1] - S[3, 3] - S[4, 1, 1] + S[4, 2]\n '
alpha_list = alpha._list
if (not alpha_list):
return self._H([])
if (alpha_list == [1]):
return self._H([1])
la = len(alpha_list)
S = NonCommutativeSymmetricFunctions(self.base_ring()).complete()
return S.sum(((sigma.signature() * self._H([((alpha_list[i] + sigma[i]) - (i + 1)) for i in range(la)])) for sigma in Permutations(la)))
@cached_method
def _from_complete_on_basis(self, comp_content):
'\n Return the expansion of a complete basis element in the\n Immaculate basis.\n\n INPUT:\n\n - ``comp_content`` -- a composition\n\n OUTPUT:\n\n - The expansion in the Immaculate basis of the basis element\n of the complete basis indexed by the composition\n ``comp_content``.\n\n EXAMPLES::\n\n sage: I = NonCommutativeSymmetricFunctions(QQ).I()\n sage: I._from_complete_on_basis(Composition([]))\n I[]\n sage: I._from_complete_on_basis(Composition([2,1,3]))\n I[2, 1, 3] + I[2, 2, 2] + I[2, 3, 1] + I[2, 4] + I[3, 1, 2] + I[3, 2, 1] + 2*I[3, 3] + I[4, 1, 1] + 2*I[4, 2] + 2*I[5, 1] + I[6]\n '
I = NonCommutativeSymmetricFunctions(self.base_ring()).I()
if (not comp_content._list):
return I([])
return I.sum_of_terms(((comp_shape, number_of_fCT(comp_content, comp_shape)) for comp_shape in Compositions(sum(comp_content))), distinct=True)
def dual(self):
'\n Return the dual basis to the Immaculate basis of NCSF.\n\n The basis returned is the dualImmaculate basis of QSym.\n\n OUTPUT:\n\n - The dualImmaculate basis of the quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: I = NonCommutativeSymmetricFunctions(QQ).Immaculate()\n sage: I.dual()\n Quasisymmetric functions over the Rational Field in the dualImmaculate\n basis\n '
return self.realization_of().dual().dualImmaculate()
class Element(CombinatorialFreeModule.Element):
'\n An element in the Immaculate basis.\n '
def bernstein_creation_operator(self, n):
'\n Return the image of ``self`` under the `n`-th Bernstein\n creation operator.\n\n Let `n` be an integer. The `n`-th Bernstein creation\n operator `\\mathbb{B}_n` is defined as the endomorphism of\n the space `NSym` of noncommutative symmetric functions\n given by\n\n .. MATH::\n\n \\mathbb{B}_n I_{(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)}\n = I_{(n, \\alpha_1, \\alpha_2, \\ldots, \\alpha_m)},\n\n where `I_{(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m)}` is the\n immaculate function associated to the `m`-tuple\n `(\\alpha_1, \\alpha_2, \\ldots, \\alpha_m) \\in \\ZZ^m`.\n\n This has been introduced in [BBSSZ2012]_, section 3.1, in\n analogy to the Bernstein creation operators on the\n symmetric functions.\n\n For more information on the `n`-th Bernstein creation\n operator, see\n :meth:`~NonCommutativeSymmetricFunctions.Bases.ElementMethods.bernstein_creation_operator`.\n\n EXAMPLES::\n\n sage: NSym = NonCommutativeSymmetricFunctions(QQ)\n sage: I = NSym.I()\n sage: b = I[1,3,2,1]\n sage: b.bernstein_creation_operator(3)\n I[3, 1, 3, 2, 1]\n sage: b.bernstein_creation_operator(5)\n I[5, 1, 3, 2, 1]\n sage: elt = b + 3*I[4,1,2]\n sage: elt.bernstein_creation_operator(1)\n I[1, 1, 3, 2, 1] + 3*I[1, 4, 1, 2]\n\n We check that this agrees with the definition on the\n Complete basis::\n\n sage: S = NSym.S()\n sage: S(elt).bernstein_creation_operator(1) == S(elt.bernstein_creation_operator(1))\n True\n\n Check on non-positive values of `n`::\n\n sage: I[2,2,2].bernstein_creation_operator(-1)\n I[1, 1, 1, 2] + I[1, 1, 2, 1] + I[1, 2, 1, 1] - I[1, 2, 2]\n sage: I[2,3,2].bernstein_creation_operator(0)\n -I[1, 1, 3, 2] - I[1, 2, 2, 2] - I[1, 2, 3, 1] + I[2, 3, 2]\n '
if (n <= 0):
return super(NonCommutativeSymmetricFunctions.Immaculate.Element, self).bernstein_creation_operator(n)
C = Compositions()
P = self.parent()
return P.sum_of_terms(((C(([n] + list(m))), c) for (m, c) in self))
I = Immaculate
class dualQuasisymmetric_Schur(CombinatorialFreeModule, BindableClass):
'\n The basis of NCSF dual to the Quasisymmetric-Schur basis of QSym.\n\n The\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Quasisymmetric_Schur`\n functions are defined in [QSCHUR]_ (see also\n Definition 5.1.1 of [LMvW13]_). The dual basis in the algebra\n of non-commutative symmetric functions is defined by the following\n formula:\n\n .. MATH::\n\n R_\\alpha = \\sum_{T} dQS_{shape(T)},\n\n where the sum is over all standard composition tableaux with\n descent composition equal to `\\alpha`.\n The\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Quasisymmetric_Schur`\n basis `QS_\\alpha` has the property that\n\n .. MATH::\n\n s_\\lambda = \\sum_{sort(\\alpha) = \\lambda} QS_\\alpha.\n\n As a consequence the commutative image of a dual\n Quasisymmetric-Schur element in the algebra of symmetric functions\n (the map defined in the method\n :meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.to_symmetric_function`)\n is equal to the Schur function indexed by the decreasing sort of the\n indexing composition.\n\n .. SEEALSO::\n\n :class:`~sage.combinat.composition_tableau.CompositionTableaux`,\n :class:`~sage.combinat.composition_tableau.CompositionTableau`.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dQS = NCSF.dQS()\n sage: dQS([1,3,2])*dQS([1])\n dQS[1, 2, 4] + dQS[1, 3, 2, 1] + dQS[1, 3, 3] + dQS[3, 2, 2]\n sage: dQS([1])*dQS([1,3,2])\n dQS[1, 1, 3, 2] + dQS[1, 3, 3] + dQS[1, 4, 2] + dQS[2, 3, 2]\n sage: dQS([1,3])*dQS([1,1])\n dQS[1, 3, 1, 1] + dQS[1, 4, 1] + dQS[3, 2, 1] + dQS[4, 2]\n sage: dQS([3,1])*dQS([2,1])\n dQS[1, 1, 4, 1] + dQS[1, 4, 2] + dQS[1, 5, 1] + dQS[2, 4, 1] + dQS[3, 1,\n 2, 1] + dQS[3, 2, 2] + dQS[3, 3, 1] + dQS[4, 3] + dQS[5, 2]\n sage: dQS([1,1]).coproduct()\n dQS[] # dQS[1, 1] + dQS[1] # dQS[1] + dQS[1, 1] # dQS[]\n sage: dQS([3,3]).coproduct().monomial_coefficients()[(Composition([1,2]),Composition([1,2]))]\n -1\n sage: S = NCSF.complete()\n sage: dQS(S[1,3,1])\n dQS[1, 3, 1] + dQS[1, 4] + dQS[3, 2] + dQS[4, 1] + dQS[5]\n sage: S(dQS[1,3,1])\n S[1, 3, 1] - S[3, 2] - S[4, 1] + S[5]\n sage: s = SymmetricFunctions(QQ).s()\n sage: s(S(dQS([2,1,3])).to_symmetric_function())\n s[3, 2, 1]\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NCSF.complete()\n sage: dQS = NCSF.dualQuasisymmetric_Schur()\n sage: dQS(S(dQS.an_element())) == dQS.an_element()\n True\n sage: S(dQS(S.an_element())) == S.an_element()\n True\n sage: TestSuite(dQS).run() # long time\n '
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='dQS', bracket=False, category=NCSF.Bases())
category = self.category()
self._S = self.realization_of().complete()
to_S = self.module_morphism(on_basis=self._to_complete_on_basis, codomain=self._S, category=category)
to_S.register_as_coercion()
from_S = self._S.module_morphism(on_basis=self._from_complete_on_basis, codomain=self, category=category)
from_S.register_as_coercion()
def _realization_name(self):
"\n TESTS::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dQS = NCSF.dQS()\n sage: dQS._realization_name()\n 'dual Quasisymmetric-Schur'\n "
return 'dual Quasisymmetric-Schur'
@cached_method
def _to_complete_transition_matrix(self, n):
'\n A matrix representing the transition coefficients to\n the complete basis along with the ordering.\n\n INPUT:\n\n - ``n`` -- an integer\n\n OUTPUT:\n\n - a pair of a square matrix and the ordered list of compositions\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dQS = NCSF.dQS()\n sage: dQS._to_complete_transition_matrix(4)[0]\n [ 1 0 0 0 0 0 0 0]\n [-1 1 0 0 0 0 0 0]\n [-1 0 1 0 0 0 0 0]\n [ 0 0 -1 1 0 0 0 0]\n [ 1 -1 0 -1 1 0 0 0]\n [ 1 -1 0 -1 0 1 0 0]\n [ 1 0 -1 -1 0 0 1 0]\n [-1 1 1 1 -1 -1 -1 1]\n '
if (n == 0):
return (matrix([[]]), [])
CO = compositions_order(n)
from sage.rings.integer_ring import ZZ
MS = MatrixSpace(ZZ, len(CO))
return (MS([[number_of_SSRCT(al, be) for be in CO] for al in CO]).inverse(), CO)
@cached_method
def _to_complete_on_basis(self, comp):
'\n The expansion of the dual Quasisymmetric-Schur basis element\n indexed by ``comp`` in the complete basis.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the complete basis\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dQS = NCSF.dQS()\n sage: dQS._to_complete_on_basis(Composition([1,3,1]))\n S[1, 3, 1] - S[3, 2] - S[4, 1] + S[5]\n '
if (not comp._list):
return self.one()
(T, comps) = self._to_complete_transition_matrix(comp.size())
i = comps.index(comp)
return self._S._from_dict({c: T[(i, j)] for (j, c) in enumerate(comps) if (T[(i, j)] != 0)}, remove_zeros=False)
@cached_method
def _from_complete_on_basis(self, comp_content):
'\n Return the expansion of a complete basis element in the\n dual Quasisymmetric-Schur basis.\n\n INPUT:\n\n - ``comp_content`` -- a composition\n\n OUTPUT:\n\n - the expansion in the dual Quasisymmetric-Schur basis of\n the basis element of the complete basis indexed by the\n composition ``comp_content``\n\n EXAMPLES::\n\n sage: dQS=NonCommutativeSymmetricFunctions(QQ).dQS()\n sage: dQS._from_complete_on_basis(Composition([]))\n dQS[]\n sage: dQS._from_complete_on_basis(Composition([2,1,1]))\n dQS[1, 3] + dQS[2, 1, 1] + dQS[2, 2] + dQS[3, 1] + dQS[4]\n '
if (not comp_content._list):
return self([])
return self.sum_of_terms(((comp_shape, number_of_SSRCT(comp_content, comp_shape)) for comp_shape in Compositions(sum(comp_content))), distinct=True)
def dual(self):
'\n The dual basis to the dual Quasisymmetric-Schur basis of NCSF.\n\n The basis returned is the\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Quasisymmetric_Schur`\n basis of QSym.\n\n OUTPUT:\n\n - the Quasisymmetric-Schur basis of the quasi-symmetric functions\n\n EXAMPLES::\n\n sage: dQS=NonCommutativeSymmetricFunctions(QQ).dualQuasisymmetric_Schur()\n sage: dQS.dual()\n Quasisymmetric functions over the Rational Field in the Quasisymmetric\n Schur basis\n sage: dQS.duality_pairing_matrix(dQS.dual(),3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n '
return self.realization_of().dual().Quasisymmetric_Schur()
def to_symmetric_function_on_basis(self, I):
'\n The commutative image of a dual quasi-symmetric Schur element\n\n The commutative image of a basis element is obtained by sorting\n the indexing composition of the basis element.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The commutative image of the dual quasi-Schur basis element\n indexed by ``I``. The result is the Schur symmetric function\n indexed by the partition obtained by sorting ``I``.\n\n EXAMPLES::\n\n sage: dQS=NonCommutativeSymmetricFunctions(QQ).dQS()\n sage: dQS.to_symmetric_function_on_basis([2,1,3])\n s[3, 2, 1]\n sage: dQS.to_symmetric_function_on_basis([])\n s[]\n '
s = SymmetricFunctions(self.base_ring()).s()
return s[Partition(sorted(I, reverse=True))]
dQS = dualQuasisymmetric_Schur
class dualYoungQuasisymmetric_Schur(CombinatorialFreeModule, BindableClass):
'\n The basis of NCSF dual to the Young Quasisymmetric-Schur basis of QSym.\n\n The\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.YoungQuasisymmetric_Schur`\n functions are given in Definition 5.2.1 of [LMvW13]_. The dual basis\n in the algebra of non-commutative symmetric functions are related by\n an involution reversing the indexing composition of the complete\n expansion of a quasi-Schur basis element. This basis has many of the\n same properties as the Quasisymmetric Schur basis and is related to\n that basis by an algebraic transformation.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dYQS = NCSF.dYQS()\n sage: dYQS([1,3,2])*dYQS([1])\n dYQS[1, 3, 2, 1] + dYQS[1, 3, 3] + dYQS[1, 4, 2] + dYQS[2, 3, 2]\n sage: dYQS([1])*dYQS([1,3,2])\n dYQS[1, 1, 3, 2] + dYQS[2, 3, 2] + dYQS[3, 3, 1] + dYQS[4, 1, 2]\n sage: dYQS([1,3])*dYQS([1,1])\n dYQS[1, 3, 1, 1] + dYQS[1, 4, 1] + dYQS[2, 3, 1] + dYQS[2, 4]\n sage: dYQS([3,1])*dYQS([2,1])\n dYQS[3, 1, 2, 1] + dYQS[3, 2, 2] + dYQS[3, 3, 1] + dYQS[4, 1, 1, 1]\n + dYQS[4, 1, 2] + dYQS[4, 2, 1] + dYQS[4, 3] + dYQS[5, 1, 1]\n + dYQS[5, 2]\n sage: dYQS([1,1]).coproduct()\n dYQS[] # dYQS[1, 1] + dYQS[1] # dYQS[1] + dYQS[1, 1] # dYQS[]\n sage: dYQS([3,3]).coproduct().monomial_coefficients()[(Composition([1,2]),Composition([2,1]))]\n 1\n sage: S = NCSF.complete()\n sage: dYQS(S[1,3,1])\n dYQS[1, 3, 1] + dYQS[1, 4] + dYQS[2, 3] + dYQS[4, 1] + dYQS[5]\n sage: S(dYQS[1,3,1])\n S[1, 3, 1] - S[1, 4] - S[2, 3] + S[5]\n sage: s = SymmetricFunctions(QQ).s()\n sage: s(S(dYQS([2,1,3])).to_symmetric_function())\n s[3, 2, 1]\n '
def __init__(self, NCSF):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NCSF.complete()\n sage: dYQS = NCSF.dualYoungQuasisymmetric_Schur()\n sage: dYQS(S(dYQS.an_element())) == dYQS.an_element()\n True\n sage: S(dYQS(S.an_element())) == S.an_element()\n True\n sage: TestSuite(dYQS).run() # long time\n '
category = NCSF.Bases()
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='dYQS', bracket=False, category=category)
self._S = NCSF.complete()
self._dQS = NCSF.dualQuasisymmetric_Schur()
self.module_morphism(on_basis=self._to_complete_on_basis, codomain=self._S, category=category).register_as_coercion()
self._S.module_morphism(on_basis=self._from_complete_on_basis, codomain=self, category=category).register_as_coercion()
def _realization_name(self):
"\n TESTS::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dYQS = NCSF.dYQS()\n sage: dYQS._realization_name()\n 'dual Young Quasisymmetric-Schur'\n "
return 'dual Young Quasisymmetric-Schur'
def _to_complete_on_basis(self, comp):
'\n The expansion of the dual Quasisymmetric-Schur basis element\n indexed by ``comp`` in the complete basis.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the complete basis\n\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: dYQS = NCSF.dYQS()\n sage: dYQS._to_complete_on_basis(Composition([1,3,1]))\n S[1, 3, 1] - S[1, 4] - S[2, 3] + S[5]\n '
elt = self._dQS._to_complete_on_basis(comp.reversed())
return self._S._from_dict({al.reversed(): c for (al, c) in elt}, coerce=False, remove_zeros=False)
def _from_complete_on_basis(self, comp):
'\n Return the expansion of a complete basis element in the\n dual Young Quasisymmetric-Schur basis.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - the expansion in the dual Young Quasisymmetric-Schur basis of\n the basis element in the complete basis indexed by the\n composition ``comp``\n\n EXAMPLES::\n\n sage: dYQS=NonCommutativeSymmetricFunctions(QQ).dYQS()\n sage: dYQS._from_complete_on_basis(Composition([]))\n dYQS[]\n sage: dYQS._from_complete_on_basis(Composition([2,1,1]))\n dYQS[2, 1, 1] + dYQS[2, 2] + 2*dYQS[3, 1] + dYQS[4]\n '
elt = self._dQS._from_complete_on_basis(comp.reversed())
return self._from_dict({al.reversed(): c for (al, c) in elt}, coerce=False, remove_zeros=False)
def dual(self):
'\n The dual basis to the dual Quasisymmetric-Schur basis of NCSF.\n\n The basis returned is the\n :class:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Quasisymmetric_Schur`\n basis of QSym.\n\n OUTPUT:\n\n - the Young Quasisymmetric-Schur basis of quasi-symmetric functions\n\n EXAMPLES::\n\n sage: dYQS=NonCommutativeSymmetricFunctions(QQ).dualYoungQuasisymmetric_Schur()\n sage: dYQS.dual()\n Quasisymmetric functions over the Rational Field in the Young\n Quasisymmetric Schur basis\n sage: dYQS.duality_pairing_matrix(dYQS.dual(),3)\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n '
return self.realization_of().dual().Young_Quasisymmetric_Schur()
def to_symmetric_function_on_basis(self, I):
'\n The commutative image of a dual Young quasi-symmetric\n Schur element.\n\n The commutative image of a basis element is obtained by sorting\n the indexing composition of the basis element.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - The commutative image of the dual Young quasi-Schur basis element\n indexed by ``I``. The result is the Schur symmetric function\n indexed by the partition obtained by sorting ``I``.\n\n EXAMPLES::\n\n sage: dYQS=NonCommutativeSymmetricFunctions(QQ).dYQS()\n sage: dYQS.to_symmetric_function_on_basis([2,1,3])\n s[3, 2, 1]\n sage: dYQS.to_symmetric_function_on_basis([])\n s[]\n '
s = SymmetricFunctions(self.base_ring()).s()
return s[Partition(sorted(I, reverse=True))]
dYQS = dualYoungQuasisymmetric_Schur
class Zassenhaus_left(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in the\n left Zassenhaus basis.\n\n This basis is the left-version of the basis defined in Section 2.5.1\n of [HLNT09]_.\n It is multiplicative, with `Z_n` defined as the element of `NCSF_n`\n satisfying the equation\n\n .. MATH::\n\n \\sigma_1 = \\cdots exp(Z_n) \\cdots exp(Z_2) exp(Z_1),\n\n where\n\n .. MATH::\n\n \\sigma_1 = \\sum_{n \\geq 0} S_n .\n\n It can be recursively computed by the formula\n\n .. MATH::\n\n S_n = \\sum_{\\lambda \\vdash n}\n \\frac{1}{m_1(\\lambda)! m_2(\\lambda)! m_3(\\lambda)! \\cdots}\n Z_{\\lambda_1} Z_{\\lambda_2} Z_{\\lambda_3} \\cdots\n\n for all `n \\geq 0`.\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: ZL = NCSF.Zassenhaus_left(); ZL\n Non-Commutative Symmetric Functions over the Rational Field\n in the Zassenhaus_left basis\n sage: TestSuite(ZL).run()\n\n TESTS:\n\n Test coproduct and antipode on the multiplicative identity::\n\n sage: ZL.one()\n ZL[]\n sage: ZL.one().coproduct()\n ZL[] # ZL[]\n sage: ZL.one().antipode()\n ZL[]\n\n We include some sanity tests to verify that conversions between\n this basis and other bases work the way they should::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: ZL = NCSF.ZL()\n sage: R = NCSF.ribbon()\n sage: S = NCSF.complete()\n sage: ZL(S[3])\n 1/6*ZL[1, 1, 1] + ZL[2, 1] + ZL[3]\n sage: all(S(ZL(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(ZL(S(ZL[comp])) == ZL[comp] for comp in Compositions(5))\n True\n sage: all(R(ZL(R[comp])) == R[comp] for comp in Compositions(5))\n True\n sage: all(ZL(R(ZL[comp])) == ZL[comp] for comp in Compositions(5))\n True\n '
cat = NCSF.MultiplicativeBasesOnPrimitiveElements()
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='ZL', bracket=False, category=cat)
S = self.realization_of().S()
to_complete = self.algebra_morphism(self._to_complete_on_generator, codomain=S)
to_complete.register_as_coercion()
from_complete = S.module_morphism(on_basis=self._from_complete_on_basis, codomain=self)
from_complete.register_as_coercion()
def _to_complete_on_generator(self, n):
'\n Expand a (left) Zassenhaus generator of non-commutative symmetric\n functions in the complete basis.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The expansion of the (left) Zassenhaus generator indexed by ``n``\n into the complete basis.\n\n TESTS::\n\n sage: ZL = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_left()\n sage: ZL._to_complete_on_generator(1)\n S[1]\n sage: ZL._to_complete_on_generator(2)\n -1/2*S[1, 1] + S[2]\n '
S = self.realization_of().S()
if (n <= 1):
return S[n]
from sage.combinat.partitions import ZS1_iterator
from sage.rings.integer_ring import ZZ
it = ZS1_iterator(n)
next(it)
res = S[n]
for p in it:
d = {}
for part in p:
d[part] = (d.get(part, 0) + 1)
coeff = ZZ(prod((factorial(d[l]) for l in d)))
res = (res - (prod((self._to_complete_on_generator(i) for i in p)) / coeff))
return res
@cached_method
def _complete_to_zassenhaus_transition_matrix_inverse(self, n):
'\n The change of basis matrix from the S basis to the ZL basis.\n\n EXAMPLES::\n\n sage: ZL = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_left()\n sage: ZL._complete_to_zassenhaus_transition_matrix_inverse(3)\n [ 1 0 0 0]\n [1/2 1 0 0]\n [1/2 0 1 0]\n [1/6 0 1 1]\n '
from sage.matrix.constructor import matrix
S = self.realization_of().S()
m = []
for I in Compositions(n):
x = S(self.basis()[I])
m.append([x.coefficient(J) for J in Compositions(n)])
M = matrix(m).inverse()
M.set_immutable()
return M
def _from_complete_on_basis(self, I):
'\n Convert the Complete basis element indexed by ``I`` to ``self``.\n\n EXAMPLES::\n\n sage: ZL = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_left()\n sage: ZL._from_complete_on_basis(Composition([1,3,2]))\n 1/12*ZL[1, 1, 1, 1, 1, 1] + 1/6*ZL[1, 1, 1, 1, 2]\n + 1/2*ZL[1, 2, 1, 1, 1] + ZL[1, 2, 1, 2]\n + 1/2*ZL[1, 3, 1, 1] + ZL[1, 3, 2]\n '
n = I.size()
m = self._complete_to_zassenhaus_transition_matrix_inverse(n)
C = Compositions(n)
coeffs = m[C.rank(I)]
return self._from_dict({J: coeffs[i] for (i, J) in enumerate(C)})
ZL = Zassenhaus_left
class Zassenhaus_right(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of non-commutative symmetric functions in\n the right Zassenhaus basis.\n\n This basis is defined in Section 2.5.1 of [HLNT09]_.\n It is multiplicative, with `Z_n` defined as the element of `NCSF_n`\n satisfying the equation\n\n .. MATH::\n\n \\sigma_1 = exp(Z_1) exp(Z_2) exp(Z_3) \\cdots exp(Z_n) \\cdots\n\n where\n\n .. MATH::\n\n \\sigma_1 = \\sum_{n \\geq 0} S_n .\n\n It can be recursively computed by the formula\n\n .. MATH::\n\n S_n = \\sum_{\\lambda \\vdash n}\n \\frac{1}{m_1(\\lambda)! m_2(\\lambda)! m_3(\\lambda)! \\cdots}\n \\cdots Z_{\\lambda_3} Z_{\\lambda_2} Z_{\\lambda_1}\n\n for all `n \\geq 0`.\n\n Note that there is a variant (called the "noncommutative\n power sum symmetric functions of the third kind")\n in Definition 5.26 of [NCSF2]_ that satisfies:\n\n .. MATH::\n\n \\sigma_1 = exp(Z_1) exp(Z_2/2) exp(Z_3/3) \\cdots exp(Z_n/n) \\cdots.\n '
def __init__(self, NCSF):
'\n EXAMPLES::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: ZR = NCSF.Zassenhaus_right(); ZR\n Non-Commutative Symmetric Functions over the Rational Field\n in the Zassenhaus_right basis\n sage: TestSuite(ZR).run()\n\n TESTS:\n\n Test coproduct and antipode on the multiplicative identity::\n\n sage: ZR = NCSF.ZR()\n sage: ZR.one()\n ZR[]\n sage: ZR.one().coproduct()\n ZR[] # ZR[]\n sage: ZR.one().antipode()\n ZR[]\n\n We include some sanity tests to verify that conversions between\n this basis and other bases work the way they should::\n\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: ZR = NCSF.Zassenhaus_right()\n sage: R = NCSF.ribbon()\n sage: S = NCSF.complete()\n sage: ZR(S[3])\n 1/6*ZR[1, 1, 1] + ZR[1, 2] + ZR[3]\n sage: all(S(ZR(S[comp])) == S[comp] for comp in Compositions(5))\n True\n sage: all(ZR(S(ZR[comp])) == ZR[comp] for comp in Compositions(5))\n True\n sage: all(R(ZR(R[comp])) == R[comp] for comp in Compositions(5))\n True\n sage: all(ZR(R(ZR[comp])) == ZR[comp] for comp in Compositions(5))\n True\n '
cat = NCSF.MultiplicativeBasesOnPrimitiveElements()
CombinatorialFreeModule.__init__(self, NCSF.base_ring(), Compositions(), prefix='ZR', bracket=False, category=cat)
S = self.realization_of().S()
to_complete = self.algebra_morphism(self._to_complete_on_generator, codomain=S)
to_complete.register_as_coercion()
from_complete = S.module_morphism(on_basis=self._from_complete_on_basis, codomain=self)
from_complete.register_as_coercion()
def _to_complete_on_generator(self, n):
'\n Expand a (right) Zassenhaus generator of non-commutative symmetric\n functions in the complete basis.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The expansion of the (right) Zassenhaus generator indexed by ``n``\n into the complete basis.\n\n TESTS::\n\n sage: ZR = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_right()\n sage: ZR._to_complete_on_generator(1)\n S[1]\n sage: ZR._to_complete_on_generator(2)\n -1/2*S[1, 1] + S[2]\n '
S = self.realization_of().S()
if (n <= 1):
return S[n]
from sage.combinat.partitions import ZS1_iterator
from sage.rings.integer_ring import ZZ
it = ZS1_iterator(n)
next(it)
res = S[n]
for p in it:
d = {}
for part in p:
d[part] = (d.get(part, 0) + 1)
coeff = ZZ(prod((factorial(d[e]) for e in d)))
res = (res - (prod((self._to_complete_on_generator(i) for i in reversed(p))) / coeff))
return res
@cached_method
def _complete_to_zassenhaus_transition_matrix_inverse(self, n):
'\n The change of basis matrix from the S basis to the ZR basis.\n\n EXAMPLES::\n\n sage: ZR = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_right()\n sage: ZR._complete_to_zassenhaus_transition_matrix_inverse(3)\n [ 1 0 0 0]\n [1/2 1 0 0]\n [1/2 0 1 0]\n [1/6 1 0 1]\n '
from sage.matrix.constructor import matrix
S = self.realization_of().S()
m = []
for I in Compositions(n):
x = S(self.basis()[I])
m.append([x.coefficient(J) for J in Compositions(n)])
M = matrix(m).inverse()
M.set_immutable()
return M
def _from_complete_on_basis(self, I):
'\n Convert the Complete basis element indexed by ``I`` to ``self``.\n\n EXAMPLES::\n\n sage: ZR = NonCommutativeSymmetricFunctions(QQ).Zassenhaus_right()\n sage: ZR._from_complete_on_basis(Composition([1,3,2]))\n 1/12*ZR[1, 1, 1, 1, 1, 1] + 1/6*ZR[1, 1, 1, 1, 2]\n + 1/2*ZR[1, 1, 2, 1, 1] + ZR[1, 1, 2, 2]\n + 1/2*ZR[1, 3, 1, 1] + ZR[1, 3, 2]\n '
n = I.size()
m = self._complete_to_zassenhaus_transition_matrix_inverse(n)
C = Compositions(n)
coeffs = m[C.rank(I)]
return self._from_dict({J: coeffs[i] for (i, J) in enumerate(C)})
ZR = Zassenhaus_right
|
class QuasiSymmetricFunctions(UniqueRepresentation, Parent):
'\n .. rubric:: The Hopf algebra of quasisymmetric functions.\n\n Let `R` be a commutative ring with unity.\n The `R`-algebra of quasi-symmetric functions may be realized as an\n `R`-subalgebra of the ring of power series in countably many\n variables `R[[x_1, x_2, x_3, \\ldots]]`. It consists of those\n formal power series `p` which are degree-bounded (i. e., the degrees\n of all monomials occurring with nonzero coefficient in `p` are bounded\n from above, although the bound can depend on `p`) and satisfy the\n following condition: For every tuple `(a_1, a_2, \\ldots, a_m)` of\n positive integers, the coefficient of the monomial\n `x_{i_1}^{a_1} x_{i_2}^{a_2} \\cdots x_{i_m}^{a_m}` in `p` is the same\n for all strictly increasing sequences `(i_1 < i_2 < \\cdots < i_m)` of\n positive integers. (In other words, the coefficient of a monomial in `p`\n depends only on the sequence of nonzero exponents in the monomial. If\n "sequence" were to be replaced by "multiset" here, we would obtain\n the definition of a symmetric function.)\n\n The `R`-algebra of quasi-symmetric functions is commonly called\n `\\mathrm{QSym}_R` or occasionally just `\\mathrm{QSym}` (when\n `R` is clear from the context or `\\ZZ` or `\\QQ`). It is graded by\n the total degree of the power series. Its homogeneous elements of degree\n `k` form a free `R`-submodule of rank equal to the number of\n compositions of `k` (that is, `2^{k-1}` if `k \\geq 1`, else `1`).\n\n The two classical bases of `\\mathrm{QSym}`, the monomial basis\n `(M_I)_I` and the fundamental basis `(F_I)_I`, are indexed by\n compositions `I = (I_1, I_2, \\cdots, I_\\ell )` and defined by the\n formulas:\n\n .. MATH::\n\n M_I = \\sum_{1 \\leq i_1 < i_2 < \\cdots < i_\\ell} x_{i_1}^{I_1}\n x_{i_2}^{I_2} \\cdots x_{i_\\ell}^{I_\\ell}\n\n and\n\n .. MATH::\n\n F_I = \\sum_{(j_1, j_2, \\ldots, j_n)} x_{j_1} x_{j_2} \\cdots\n x_{j_n}\n\n where in the second equation the sum runs over all weakly increasing\n `n`-tuples `(j_1, j_2, \\ldots, j_n)` of positive integers\n (where `n` is the size of `I`) which increase strictly from `j_r`\n to `j_{r+1}` if `r` is a descent of the composition `I`.\n\n These bases are related by the formula\n\n `F_I = \\sum_{J \\leq I} M_J`\n\n where the inequality `J \\leq I` indicates that `J` is finer than `I`.\n\n The `R`-algebra of quasi-symmetric functions is a Hopf algebra,\n with the coproduct satisfying\n\n .. MATH::\n\n \\Delta M_I = \\sum_{k=0}^{\\ell} M_{(I_1, I_2, \\cdots, I_k)} \\otimes\n M_{(I_{k+1}, I_{k+2}, \\cdots , I_{\\ell})}\n\n for every composition `I = (I_1, I_2, \\cdots , I_\\ell )`.\n\n It is possible to define an `R`-algebra of quasi-symmetric\n functions in a finite number of variables as well (but it is not\n a bialgebra). These quasi-symmetric functions are actual polynomials\n then, not just power series.\n\n Chapter 5 of [GriRei18]_ and Section 11 of [HazWitt1]_ are devoted\n to quasi-symmetric functions, as are Malvenuto\'s thesis [Mal1993]_\n and part of Chapter 7 of [Sta-EC2]_.\n\n .. rubric:: The implementation of the quasi-symmetric function Hopf algebra\n\n We realize the `R`-algebra of quasi-symmetric functions in Sage as\n a graded Hopf algebra with basis elements indexed by compositions::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QSym.category()\n Join of Category of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of commutative algebras over Rational Field\n and Category of monoids with realizations\n and Category of graded coalgebras over Rational Field\n and Category of coalgebras over Rational Field with realizations\n\n The most standard two bases for this `R`-algebra are the monomial and\n fundamental bases, and are accessible by the ``M()`` and ``F()`` methods::\n\n sage: M = QSym.M()\n sage: F = QSym.F()\n sage: M(F[2,1,2])\n M[1, 1, 1, 1, 1] + M[1, 1, 1, 2] + M[2, 1, 1, 1] + M[2, 1, 2]\n sage: F(M[2,1,2])\n F[1, 1, 1, 1, 1] - F[1, 1, 1, 2] - F[2, 1, 1, 1] + F[2, 1, 2]\n\n The product on this space is commutative and is inherited from the product\n on the realization within the ring of power series::\n\n sage: M[3]*M[1,1] == M[1,1]*M[3]\n True\n sage: M[3]*M[1,1]\n M[1, 1, 3] + M[1, 3, 1] + M[1, 4] + M[3, 1, 1] + M[4, 1]\n sage: F[3]*F[1,1]\n F[1, 1, 3] + F[1, 2, 2] + F[1, 3, 1] + F[1, 4] + F[2, 1, 2]\n + F[2, 2, 1] + F[2, 3] + F[3, 1, 1] + F[3, 2] + F[4, 1]\n sage: M[3]*F[2]\n M[1, 1, 3] + M[1, 3, 1] + M[1, 4] + M[2, 3] + M[3, 1, 1] + M[3, 2]\n + M[4, 1] + M[5]\n sage: F[2]*M[3]\n F[1, 1, 1, 2] - F[1, 2, 2] + F[2, 1, 1, 1] - F[2, 1, 2] - F[2, 2, 1]\n + F[5]\n\n There is a coproduct on `\\mathrm{QSym}` as well, which in the Monomial\n basis acts by cutting the composition into a left half and a right\n half. The coproduct is not co-commutative::\n\n sage: M[1,3,1].coproduct()\n M[] # M[1, 3, 1] + M[1] # M[3, 1] + M[1, 3] # M[1] + M[1, 3, 1] # M[]\n sage: F[1,3,1].coproduct()\n F[] # F[1, 3, 1] + F[1] # F[3, 1] + F[1, 1] # F[2, 1]\n + F[1, 2] # F[1, 1] + F[1, 3] # F[1] + F[1, 3, 1] # F[]\n\n .. rubric:: The duality pairing with non-commutative symmetric functions\n\n These two operations endow the quasi-symmetric functions\n `\\mathrm{QSym}` with the structure of a Hopf algebra. It is the graded\n dual Hopf algebra of the non-commutative symmetric functions `NCSF`.\n Under this duality, the Monomial basis of `\\mathrm{QSym}` is dual to\n the Complete basis of `NCSF`, and the Fundamental basis of\n `\\mathrm{QSym}` is dual to the Ribbon basis of `NCSF` (see [MR]_).\n\n ::\n\n sage: S = M.dual(); S\n Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n sage: M[1,3,1].duality_pairing( S[1,3,1] )\n 1\n sage: M.duality_pairing_matrix( S, degree=4 )\n [1 0 0 0 0 0 0 0]\n [0 1 0 0 0 0 0 0]\n [0 0 1 0 0 0 0 0]\n [0 0 0 1 0 0 0 0]\n [0 0 0 0 1 0 0 0]\n [0 0 0 0 0 1 0 0]\n [0 0 0 0 0 0 1 0]\n [0 0 0 0 0 0 0 1]\n sage: F.duality_pairing_matrix( S, degree=4 )\n [1 0 0 0 0 0 0 0]\n [1 1 0 0 0 0 0 0]\n [1 0 1 0 0 0 0 0]\n [1 1 1 1 0 0 0 0]\n [1 0 0 0 1 0 0 0]\n [1 1 0 0 1 1 0 0]\n [1 0 1 0 1 0 1 0]\n [1 1 1 1 1 1 1 1]\n sage: NCSF = M.realization_of().dual()\n sage: R = NCSF.Ribbon()\n sage: F.duality_pairing_matrix( R, degree=4 )\n [1 0 0 0 0 0 0 0]\n [0 1 0 0 0 0 0 0]\n [0 0 1 0 0 0 0 0]\n [0 0 0 1 0 0 0 0]\n [0 0 0 0 1 0 0 0]\n [0 0 0 0 0 1 0 0]\n [0 0 0 0 0 0 1 0]\n [0 0 0 0 0 0 0 1]\n sage: M.duality_pairing_matrix( R, degree=4 )\n [ 1 0 0 0 0 0 0 0]\n [-1 1 0 0 0 0 0 0]\n [-1 0 1 0 0 0 0 0]\n [ 1 -1 -1 1 0 0 0 0]\n [-1 0 0 0 1 0 0 0]\n [ 1 -1 0 0 -1 1 0 0]\n [ 1 0 -1 0 -1 0 1 0]\n [-1 1 1 -1 1 -1 -1 1]\n\n Let `H` and `G` be elements of `\\mathrm{QSym}`, and `h` an element of\n `NCSF`. Then, if we represent the duality pairing with the\n mathematical notation `[ \\cdot, \\cdot ]`,\n\n `[H G, h] = [H \\otimes G, \\Delta(h)]~.`\n\n For example, the coefficient of ``M[2,1,4,1]`` in ``M[1,3]*M[2,1,1]`` may be\n computed with the duality pairing::\n\n sage: I, J = Composition([1,3]), Composition([2,1,1])\n sage: (M[I]*M[J]).duality_pairing(S[2,1,4,1])\n 1\n\n And the coefficient of ``S[1,3] # S[2,1,1]`` in ``S[2,1,4,1].coproduct()`` is\n equal to this result::\n\n sage: S[2,1,4,1].coproduct()\n S[] # S[2, 1, 4, 1] + ... + S[1, 3] # S[2, 1, 1] + ... + S[4, 1] # S[2, 1]\n\n The duality pairing on the tensor space is another way of getting this\n coefficient, but currently the method ``duality_pairing`` is not defined on\n the tensor squared space. However, we can extend this functionality by\n applying a linear morphism to the terms in the coproduct, as follows::\n\n sage: X = S[2,1,4,1].coproduct()\n sage: def linear_morphism(x, y):\n ....: return x.duality_pairing(M[1,3]) * y.duality_pairing(M[2,1,1])\n sage: X.apply_multilinear_morphism(linear_morphism, codomain=ZZ)\n 1\n\n Similarly, if `H` is an element of `\\mathrm{QSym}` and `g` and `h` are\n elements of `NCSF`, then\n\n .. MATH::\n\n [ H, g h ] = [ \\Delta(H), g \\otimes h ].\n\n For example, the coefficient of ``R[2,3,1]`` in ``R[2,1]*R[2,1]`` is\n computed with the duality pairing by the following command::\n\n sage: (R[2,1]*R[2,1]).duality_pairing(F[2,3,1])\n 1\n sage: R[2,1]*R[2,1]\n R[2, 1, 2, 1] + R[2, 3, 1]\n\n This coefficient should then be equal to the coefficient of\n ``F[2,1] # F[2,1]`` in ``F[2,3,1].coproduct()``::\n\n sage: F[2,3,1].coproduct()\n F[] # F[2, 3, 1] + ... + F[2, 1] # F[2, 1] + ... + F[2, 3, 1] # F[]\n\n This can also be computed by the duality pairing on the tensor space,\n as above::\n\n sage: X = F[2,3,1].coproduct()\n sage: def linear_morphism(x, y):\n ....: return x.duality_pairing(R[2,1]) * y.duality_pairing(R[2,1])\n sage: X.apply_multilinear_morphism(linear_morphism, codomain=ZZ)\n 1\n\n .. rubric:: The operation dual to multiplication by a non-commutative symmetric function\n\n Let `g \\in NCSF` and consider the linear endomorphism of `NCSF` defined by\n left (respectively, right) multiplication by `g`. Since there is a duality\n between `\\mathrm{QSym}` and `NCSF`, this linear transformation induces an\n operator `g^{\\perp}` on `\\mathrm{QSym}` satisfying\n\n .. MATH::\n\n [ g^{\\perp}(H), h ] = [ H, gh ].\n\n for any non-commutative symmetric function `h`.\n\n This is implemented by the method\n :meth:`~sage.combinat.ncsf_qsym.generic_basis_code.BasesOfQSymOrNCSF.ElementMethods.skew_by`.\n Explicitly, if ``H`` is a quasi-symmetric function and ``g``\n a non-commutative symmetric function, then ``H.skew_by(g)`` and\n ``H.skew_by(g, side=\'right\')`` are expressions that satisfy,\n for any non-commutative symmetric function ``h``, the following\n equalities::\n\n H.skew_by(g).duality_pairing(h) == H.duality_pairing(g*h)\n H.skew_by(g, side=\'right\').duality_pairing(h) == H.duality_pairing(h*g)\n\n For example, ``M[J].skew_by(S[I])`` is `0` unless the composition ``J``\n begins with ``I`` and ``M(J).skew_by(S(I), side=\'right\')`` is `0` unless\n the composition ``J`` ends with ``I``. For example::\n\n sage: M[3,2,2].skew_by(S[3])\n M[2, 2]\n sage: M[3,2,2].skew_by(S[2])\n 0\n sage: M[3,2,2].coproduct().apply_multilinear_morphism( lambda x,y: x.duality_pairing(S[3])*y )\n M[2, 2]\n sage: M[3,2,2].skew_by(S[3], side=\'right\')\n 0\n sage: M[3,2,2].skew_by(S[2], side=\'right\')\n M[3, 2]\n\n .. rubric:: The counit\n\n The counit is defined by sending all elements of positive degree to zero::\n\n sage: M[3].degree(), M[3,1,2].degree(), M.one().degree()\n (3, 6, 0)\n sage: M[3].counit()\n 0\n sage: M[3,1,2].counit()\n 0\n sage: M.one().counit()\n 1\n sage: (M[3] - 2*M[3,1,2] + 7).counit()\n 7\n sage: (F[3] - 2*F[3,1,2] + 7).counit()\n 7\n\n .. rubric:: The antipode\n\n The antipode sends the Fundamental basis element indexed by the\n composition `I` to `(-1)^{|I|}` times the Fundamental\n basis element indexed by the conjugate composition to `I`\n (where `|I|` stands for the size of `I`, that is, the sum of all\n entries of `I`).\n ::\n\n sage: F[3,2,2].antipode()\n -F[1, 2, 2, 1, 1]\n sage: Composition([3,2,2]).conjugate()\n [1, 2, 2, 1, 1]\n\n The antipodes of the Monomial quasisymmetric functions can also be\n computed easily: Every composition `I` satisfies\n\n .. MATH::\n\n \\omega(M_I) = (-1)^{\\ell(I)} \\sum M_J,\n\n where the sum ranges over all compositions `J` of `|I|`\n which are coarser than the reversed composition `I^r` of\n `I`. Here, `\\ell(I)` denotes the length of the composition `I`\n (that is, the number of its parts). ::\n\n sage: M[3,2,1].antipode()\n -M[1, 2, 3] - M[1, 5] - M[3, 3] - M[6]\n sage: M[3,2,2].antipode()\n -M[2, 2, 3] - M[2, 5] - M[4, 3] - M[7]\n\n We demonstrate here the defining relation of the antipode::\n\n sage: X = F[3,2,2].coproduct()\n sage: X.apply_multilinear_morphism(lambda x,y: x*y.antipode())\n 0\n sage: X.apply_multilinear_morphism(lambda x,y: x.antipode()*y)\n 0\n\n .. rubric:: The relation with symmetric functions\n\n The quasi-symmetric functions are a ring which contain the\n symmetric functions as a subring. The Monomial quasi-symmetric\n functions are related to the monomial symmetric functions by\n\n .. MATH::\n\n m_\\lambda = \\sum_{\\operatorname{sort}(I) = \\lambda} M_I\n\n (where `\\operatorname{sort}(I)` denotes the result of sorting\n the entries of `I` in decreasing order).\n\n There are methods to test if an expression in the quasi-symmetric\n functions is a symmetric function and, if it is, send it to an\n expression in the symmetric functions::\n\n sage: f = M[1,1,2] + M[1,2,1]\n sage: f.is_symmetric()\n False\n sage: g = M[3,1] + M[1,3]\n sage: g.is_symmetric()\n True\n sage: g.to_symmetric_function()\n m[3, 1]\n\n The expansion of the Schur function in terms of the Fundamental quasi-symmetric\n functions is due to [Ges]_. There is one term in the expansion for each standard\n tableau of shape equal to the partition indexing the Schur function.\n ::\n\n sage: f = F[3,2] + F[2,2,1] + F[2,3] + F[1,3,1] + F[1,2,2]\n sage: f.is_symmetric()\n True\n sage: f.to_symmetric_function()\n 5*m[1, 1, 1, 1, 1] + 3*m[2, 1, 1, 1] + 2*m[2, 2, 1] + m[3, 1, 1] + m[3, 2]\n sage: s = SymmetricFunctions(QQ).s()\n sage: s(f.to_symmetric_function())\n s[3, 2]\n\n It is also possible to convert a symmetric function to a\n quasi-symmetric function::\n\n sage: m = SymmetricFunctions(QQ).m()\n sage: M( m[3,1,1] )\n M[1, 1, 3] + M[1, 3, 1] + M[3, 1, 1]\n sage: F( s[2,2,1] )\n F[1, 1, 2, 1] + F[1, 2, 1, 1] + F[1, 2, 2] + F[2, 1, 2] + F[2, 2, 1]\n\n It is possible to experiment with the quasi-symmetric function expansion of other\n bases, but it is important that the base ring be the same for both algebras.\n ::\n\n sage: R = QQ[\'t\']\n sage: Qp = SymmetricFunctions(R).hall_littlewood().Qp()\n sage: QSymt = QuasiSymmetricFunctions(R)\n sage: Ft = QSymt.F()\n sage: Ft( Qp[2,2] )\n F[1, 2, 1] + t*F[1, 3] + (t+1)*F[2, 2] + t*F[3, 1] + t^2*F[4]\n\n ::\n\n sage: K = QQ[\'q\',\'t\'].fraction_field()\n sage: Ht = SymmetricFunctions(K).macdonald().Ht()\n sage: Fqt = QuasiSymmetricFunctions(Ht.base_ring()).F()\n sage: Fqt(Ht[2,1])\n q*t*F[1, 1, 1] + (q+t)*F[1, 2] + (q+t)*F[2, 1] + F[3]\n\n The following will raise an error because the base ring of ``F`` is not\n equal to the base ring of ``Ht``::\n\n sage: F(Ht[2,1])\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= McdHt[2, 1]) an element of self (=Quasisymmetric functions over the Rational Field in the Fundamental basis)\n\n .. rubric:: The map to the ring of polynomials\n\n The quasi-symmetric functions can be seen as an inverse limit\n of a subring of a polynomial ring as the number of variables\n increases. Indeed, there exists a projection from the\n quasi-symmetric functions onto the polynomial ring\n `R[x_1, x_2, \\ldots, x_n]`. This projection is defined by\n sending the variables `x_{n+1}, x_{n+2}, \\cdots` to `0`, while\n the remaining `n` variables remain fixed. Note that this\n projection sends `M_I` to `0` if the length of the composition\n `I` is higher than `n`. ::\n\n sage: M[1,3,1].expand(4)\n x0*x1^3*x2 + x0*x1^3*x3 + x0*x2^3*x3 + x1*x2^3*x3\n sage: F[1,3,1].expand(4)\n x0*x1^3*x2 + x0*x1^3*x3 + x0*x1^2*x2*x3 + x0*x1*x2^2*x3 + x0*x2^3*x3 + x1*x2^3*x3\n sage: M[1,3,1].expand(2)\n 0\n\n TESTS::\n\n sage: QSym = QuasiSymmetricFunctions(QQ); QSym\n Quasisymmetric functions over the Rational Field\n sage: QSym.base_ring()\n Rational Field\n sage: algebras.QSym(QQ) is QSym\n True\n '
def __init__(self, R):
'\n The Hopf algebra of quasi-symmetric functions.\n See ``QuasiSymmetricFunctions`` for full documentation.\n\n EXAMPLES::\n\n sage: QuasiSymmetricFunctions(QQ)\n Quasisymmetric functions over the Rational Field\n sage: QSym1 = QuasiSymmetricFunctions(FiniteField(23))\n sage: QSym2 = QuasiSymmetricFunctions(Integers(23))\n sage: TestSuite(QuasiSymmetricFunctions(QQ)).run()\n '
assert ((R in Fields()) or (R in Rings()))
self._base = R
category = GradedHopfAlgebras(R).Commutative()
self._category = category
Parent.__init__(self, category=category.WithRealizations())
Monomial = self.Monomial()
Fundamental = self.Fundamental()
dualImmaculate = self.dualImmaculate()
QS = self.Quasisymmetric_Schur()
Fundamental.module_morphism(Monomial.sum_of_finer_compositions, codomain=Monomial, category=category).register_as_coercion()
Monomial.module_morphism(Fundamental.alternating_sum_of_finer_compositions, codomain=Fundamental, category=category).register_as_coercion()
dualImmaculate.module_morphism(dualImmaculate._to_Monomial_on_basis, codomain=Monomial, category=category).register_as_coercion()
Monomial.module_morphism(dualImmaculate._from_Monomial_on_basis, codomain=dualImmaculate, category=category).register_as_coercion()
QS.module_morphism(QS._to_monomial_on_basis, codomain=Monomial, category=category).register_as_coercion()
Monomial.module_morphism(QS._from_monomial_on_basis, codomain=QS, category=category).register_as_coercion()
Sym = SymmetricFunctions(self.base_ring())
Sym_m_to_M = Sym.m().module_morphism(Monomial.sum_of_partition_rearrangements, triangular='upper', inverse_on_support=Monomial._comp_to_par, codomain=Monomial, category=category)
Sym_m_to_M.register_as_coercion()
self.to_symmetric_function = Sym_m_to_M.section()
Sym_s_to_F = Sym.s().module_morphism(Fundamental._from_schur_on_basis, unitriangular='upper', codomain=Fundamental, category=category)
Sym_s_to_F.register_as_coercion()
def _repr_(self):
"\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: M._repr_()\n 'Quasisymmetric functions over the Integer Ring in the Monomial basis'\n "
return ('Quasisymmetric functions over the %s' % self.base_ring())
def a_realization(self):
'\n Return the realization of the Monomial basis of the ring of quasi-symmetric functions.\n\n OUTPUT:\n\n - The Monomial basis of quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: QuasiSymmetricFunctions(QQ).a_realization()\n Quasisymmetric functions over the Rational Field in the Monomial basis\n '
return self.Monomial()
_shorthands = tuple(['M', 'F', 'E', 'dI', 'QS', 'YQS', 'phi', 'psi'])
def dual(self):
'\n Return the dual Hopf algebra of the quasi-symmetric functions, which is the\n non-commutative symmetric functions.\n\n OUTPUT:\n\n - The non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QSym.dual()\n Non-Commutative Symmetric Functions over the Rational Field\n '
return NonCommutativeSymmetricFunctions(self.base_ring())
def from_polynomial(self, f, check=True):
"\n Return the quasi-symmetric function in the Monomial basis\n corresponding to the quasi-symmetric polynomial ``f``.\n\n INPUT:\n\n - ``f`` -- a polynomial in finitely many variables over the same base\n ring as ``self``. It is assumed that this polynomial is\n quasi-symmetric.\n - ``check`` -- boolean (default: ``True``), checks whether the\n polynomial is indeed quasi-symmetric.\n\n OUTPUT:\n\n - quasi-symmetric function in the Monomial basis\n\n EXAMPLES::\n\n sage: P = PolynomialRing(QQ, 'x', 3)\n sage: x = P.gens()\n sage: f = x[0] + x[1] + x[2]\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QSym.from_polynomial(f)\n M[1]\n\n Beware of setting ``check=False``::\n\n sage: f = x[0] + 2*x[1] + x[2]\n sage: QSym.from_polynomial(f, check=True)\n Traceback (most recent call last):\n ...\n ValueError: x0 + 2*x1 + x2 is not a quasi-symmetric polynomial\n sage: QSym.from_polynomial(f, check=False)\n M[1]\n\n To expand the quasi-symmetric function in a basis other than the\n Monomial basis, the following shorthands are provided::\n\n sage: M = QSym.Monomial()\n sage: f = x[0]**2+x[1]**2+x[2]**2\n sage: g = M.from_polynomial(f); g\n M[2]\n sage: F = QSym.Fundamental()\n sage: F(g)\n -F[1, 1] + F[2]\n sage: F.from_polynomial(f)\n -F[1, 1] + F[2]\n "
assert (self.base_ring() == f.base_ring())
exponent_coefficient = f.dict()
z = {}
for (e, c) in exponent_coefficient.items():
I = Compositions()([ei for ei in e if ei])
if (I not in z):
z[I] = c
out = self.Monomial()._from_dict(z)
if (check and (out.expand(f.parent().ngens(), f.parent().variable_names()) != f)):
raise ValueError(('%s is not a quasi-symmetric polynomial' % f))
return out
class Bases(Category_realization_of_parent):
'\n Category of bases of quasi-symmetric functions.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QSym.Bases()\n Category of bases of Quasisymmetric functions over the Rational Field\n '
def super_categories(self):
'\n Return the super categories of bases of the Quasi-symmetric functions.\n\n OUTPUT:\n\n - a list of categories\n\n TESTS::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QSym.Bases().super_categories()\n [Category of commutative bases of Non-Commutative Symmetric Functions or Quasisymmetric functions over the Rational Field]\n '
return [BasesOfQSymOrNCSF(self.base()).Commutative()]
class ParentMethods():
'\n Methods common to all bases of ``QuasiSymmetricFunctions``.\n '
def from_polynomial(self, f, check=True):
"\n The quasi-symmetric function expanded in this basis\n corresponding to the quasi-symmetric polynomial ``f``.\n\n This is a default implementation that computes\n the expansion in the Monomial basis and converts\n to this basis.\n\n INPUT:\n\n - ``f`` -- a polynomial in finitely many variables over the same base\n ring as ``self``. It is assumed that this polynomial is\n quasi-symmetric.\n - ``check`` -- boolean (default: ``True``), checks whether the\n polynomial is indeed quasi-symmetric.\n\n OUTPUT:\n\n - quasi-symmetric function\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: P = PolynomialRing(QQ, 'x', 3)\n sage: x = P.gens()\n sage: f = x[0] + x[1] + x[2]\n sage: M.from_polynomial(f)\n M[1]\n sage: F.from_polynomial(f)\n F[1]\n sage: f = x[0]**2+x[1]**2+x[2]**2\n sage: M.from_polynomial(f)\n M[2]\n sage: F.from_polynomial(f)\n -F[1, 1] + F[2]\n\n If the polynomial is not quasi-symmetric, an error\n is raised::\n\n sage: f = x[0]^2+x[1]\n sage: M.from_polynomial(f)\n Traceback (most recent call last):\n ...\n ValueError: x0^2 + x1 is not a quasi-symmetric polynomial\n sage: F.from_polynomial(f)\n Traceback (most recent call last):\n ...\n ValueError: x0^2 + x1 is not a quasi-symmetric polynomial\n\n TESTS:\n\n We convert some quasi-symmetric functions to quasi-symmetric\n polynomials and back::\n\n sage: f = (M[1,2] + M[1,1]).expand(3); f\n x0*x1^2 + x0*x2^2 + x1*x2^2 + x0*x1 + x0*x2 + x1*x2\n sage: M.from_polynomial(f)\n M[1, 1] + M[1, 2]\n sage: f = (2*M[2,1]+M[1,1]+3*M[3]).expand(3)\n sage: M.from_polynomial(f)\n M[1, 1] + 2*M[2, 1] + 3*M[3]\n sage: f = (F[1,2] + F[1,1]).expand(3); f\n x0*x1^2 + x0*x1*x2 + x0*x2^2 + x1*x2^2 + x0*x1 + x0*x2 + x1*x2\n sage: F.from_polynomial(f)\n F[1, 1] + F[1, 2]\n sage: f = (2*F[2,1]+F[1,1]+3*F[3]).expand(3)\n sage: F.from_polynomial(f)\n F[1, 1] + 2*F[2, 1] + 3*F[3]\n "
g = self.realization_of().from_polynomial(f, check=check)
return self(g)
def Eulerian(self, n, j, k=None):
'\n Return the Eulerian (quasi)symmetric function `Q_{n,j}` in\n terms of ``self``.\n\n INPUT:\n\n - ``n`` -- the value `n` or a partition\n - ``j`` -- the number of excedances\n - ``k`` -- (optional) if specified, determines the number of\n fixed points of the permutation\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: M.Eulerian(3, 1)\n 4*M[1, 1, 1] + 3*M[1, 2] + 3*M[2, 1] + 2*M[3]\n sage: M.Eulerian(4, 1, 2)\n 6*M[1, 1, 1, 1] + 4*M[1, 1, 2] + 4*M[1, 2, 1]\n + 2*M[1, 3] + 4*M[2, 1, 1] + 3*M[2, 2] + 2*M[3, 1] + M[4]\n sage: QS = QSym.QS()\n sage: QS.Eulerian(4, 2)\n 2*QS[1, 3] + QS[2, 2] + 2*QS[3, 1] + 3*QS[4]\n sage: QS.Eulerian([2, 2, 1], 2)\n QS[1, 2, 2] + QS[1, 4] + QS[2, 1, 2] + QS[2, 2, 1]\n + QS[2, 3] + QS[3, 2] + QS[4, 1] + QS[5]\n sage: dI = QSym.dI()\n sage: dI.Eulerian(5, 2)\n -dI[1, 3, 1] - 5*dI[1, 4] + dI[2, 2, 1] + dI[3, 1, 1]\n + 5*dI[3, 2] + 6*dI[4, 1] + 6*dI[5]\n '
F = self.realization_of().F()
if (n in _Partitions):
n = _Partitions(n)
return self(F.Eulerian(n, j, k))
class ElementMethods():
'\n Methods common to all elements of ``QuasiSymmetricFunctions``.\n '
def internal_coproduct(self):
'\n Return the inner coproduct of ``self`` in the basis of ``self``.\n\n The inner coproduct (also known as the Kronecker coproduct,\n or as the second comultiplication on the `R`-algebra of\n quasi-symmetric functions) is an `R`-algebra homomorphism\n `\\Delta^{\\times}` from the `R`-algebra of quasi-symmetric\n functions to the tensor square (over `R`) of quasi-symmetric\n functions. It can be defined in the following two ways:\n\n #. If `I` is a composition, then a `(0, I)`-matrix will mean a\n matrix whose entries are nonnegative integers such that no\n row and no column of this matrix is zero, and such that if\n all the non-zero entries of the matrix are read (row by row,\n starting at the topmost row, reading every row from left to\n right), then the reading word obtained is `I`. If `A` is\n a `(0, I)`-matrix, then `\\mathrm{row}(A)` will denote the\n vector of row sums of `A` (regarded as a composition), and\n `\\mathrm{column}(A)` will denote the vector of column sums\n of `A` (regarded as a composition).\n\n For every composition `I`, the internal coproduct\n `\\Delta^{\\times}(M_I)` of the `I`-th monomial quasisymmetric\n function `M_I` is the sum\n\n .. MATH::\n\n \\sum_{A \\hbox{ is a } (0, I) \\text{-matrix}}\n M_{\\mathrm{row}(A)} \\otimes M_{\\mathrm{column}(A)}.\n\n See Section 11.39 of [HazWitt1]_.\n\n #. For every permutation `w`, let `C(w)` denote the descent\n composition of `w`. Then, for any composition `I` of size\n `n`, the internal coproduct `\\Delta^{\\times}(F_I)` of the\n `I`-th fundamental quasisymmetric function `F_I` is the sum\n\n .. MATH::\n\n \\sum_{\\substack{\\sigma \\in S_n,\\\\ \\tau \\in S_n,\\\\\n \\tau \\sigma = \\pi}} F_{C(\\sigma)} \\otimes F_{C(\\tau)},\n\n where `\\pi` is any permutation in `S_n` having descent\n composition `I` and where permutations act from the left and\n multiply accordingly, so `\\tau \\sigma` means first applying\n `\\sigma` and then `\\tau`. See Theorem 4.23 in [Mal1993]_,\n but beware of the notations which are apparently different\n from those in [HazWitt1]_.\n\n The restriction of the internal coproduct to the\n `R`-algebra of symmetric functions is the well-known\n internal coproduct on the symmetric functions.\n\n The method :meth:`kronecker_coproduct` is a synonym of this one.\n\n EXAMPLES:\n\n Let us compute the internal coproduct of `M_{21}` (which is\n short for `M_{[2, 1]}`). The `(0, [2,1])`-matrices are\n\n .. MATH::\n\n \\begin{bmatrix} 2 & 1 \\end{bmatrix},\n \\begin{bmatrix} 2 \\\\ 1 \\end{bmatrix},\n \\begin{bmatrix} 2 & 0 \\\\ 0 & 1 \\end{bmatrix}, \\hbox{ and }\n \\begin{bmatrix} 0 & 2 \\\\ 1 & 0 \\end{bmatrix}\n\n so\n\n .. MATH::\n\n \\Delta^\\times(M_{21}) = M_{3} \\otimes M_{21} +\n M_{21} \\otimes M_3 + M_{21} \\otimes M_{21} +\n M_{21} \\otimes M_{12}.\n\n This is confirmed by the following Sage computation\n (incidentally demonstrating the non-cocommutativity of\n the internal coproduct)::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: a = M([2,1])\n sage: a.internal_coproduct()\n M[2, 1] # M[1, 2] + M[2, 1] # M[2, 1] + M[2, 1] # M[3] + M[3] # M[2, 1]\n\n Further examples::\n\n sage: all( M([i]).internal_coproduct() == tensor([M([i]), M([i])])\n ....: for i in range(1, 4) )\n True\n\n sage: M([1, 2]).internal_coproduct()\n M[1, 2] # M[1, 2] + M[1, 2] # M[2, 1] + M[1, 2] # M[3] + M[3] # M[1, 2]\n\n The definition of `\\Delta^{\\times}(M_I)` in terms of\n `(0, I)`-matrices is not suitable for computation in\n cases where the length of `I` is large, but we can use\n it as a doctest. Here is a naive implementation::\n\n sage: def naive_internal_coproduct_on_M(I):\n ....: # INPUT: composition I\n ....: # (not quasi-symmetric function)\n ....: # OUTPUT: interior coproduct of M_I\n ....: M = QuasiSymmetricFunctions(ZZ).M()\n ....: M2 = M.tensor(M)\n ....: res = M2.zero()\n ....: l = len(I)\n ....: n = I.size()\n ....: for S in Subsets(range(l**2), l):\n ....: M_list = sorted(S)\n ....: row_M = [sum([I[M_list.index(l * i + j)]\n ....: for j in range(l) if\n ....: l * i + j in S])\n ....: for i in range(l)]\n ....: col_M = [sum([I[M_list.index(l * i + j)]\n ....: for i in range(l) if\n ....: l * i + j in S])\n ....: for j in range(l)]\n ....: if 0 in row_M:\n ....: first_zero = row_M.index(0)\n ....: row_M = row_M[:first_zero]\n ....: if sum(row_M) != n:\n ....: continue\n ....: if 0 in col_M:\n ....: first_zero = col_M.index(0)\n ....: col_M = col_M[:first_zero]\n ....: if sum(col_M) != n:\n ....: continue\n ....: res += tensor([M(Compositions(n)(row_M)),\n ....: M(Compositions(n)(col_M))])\n ....: return res\n sage: all( naive_internal_coproduct_on_M(I)\n ....: == M(I).internal_coproduct()\n ....: for I in Compositions(3) )\n True\n\n TESTS:\n\n Border cases::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: F = QuasiSymmetricFunctions(ZZ).F()\n sage: M([]).internal_coproduct()\n M[] # M[]\n sage: F([]).internal_coproduct()\n F[] # F[]\n\n The implementations on the ``F`` and ``M`` bases agree\n with each other::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: F = QuasiSymmetricFunctions(ZZ).F()\n sage: def int_copr_on_F_via_M(I):\n ....: result = tensor([F.zero(), F.zero()])\n ....: w = M(F(I)).internal_coproduct()\n ....: for lam, a in w:\n ....: (U, V) = lam\n ....: result += a * tensor([F(M(U)), F(M(V))])\n ....: return result\n sage: all( int_copr_on_F_via_M(I) == F(I).internal_coproduct()\n ....: for I in Compositions(3) )\n True\n sage: all( int_copr_on_F_via_M(I) == F(I).internal_coproduct()\n ....: for I in Compositions(4) )\n True\n\n Restricting to the subring of symmetric functions gives the\n standard internal coproduct on the latter::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: e = SymmetricFunctions(ZZ).e()\n sage: def int_copr_of_e_in_M(mu):\n ....: result = tensor([M.zero(), M.zero()])\n ....: w = e(mu).internal_coproduct()\n ....: for lam, a in w:\n ....: (nu, kappa) = lam\n ....: result += a * tensor([M(e(nu)), M(e(kappa))])\n ....: return result\n sage: all( int_copr_of_e_in_M(mu) == M(e(mu)).internal_coproduct()\n ....: for mu in Partitions(3) )\n True\n sage: all( int_copr_of_e_in_M(mu) == M(e(mu)).internal_coproduct()\n ....: for mu in Partitions(4) )\n True\n\n .. TODO::\n\n Implement this directly on the monomial basis maybe?\n The `(0, I)`-matrices are a pain to generate from their\n definition, but maybe there is a good algorithm.\n If so, the above "further examples" should be moved\n to the M-method.\n '
parent = self.parent()
F = parent.realization_of().F()
from sage.categories.tensor import tensor
result = tensor([parent.zero(), parent.zero()])
for (lam, a) in F(self).internal_coproduct():
(I, J) = lam
result += (a * tensor([parent(F(I)), parent(F(J))]))
return result
kronecker_coproduct = internal_coproduct
def frobenius(self, n):
'\n Return the image of the quasi-symmetric function ``self``\n under the `n`-th Frobenius operator.\n\n The `n`-th Frobenius operator `\\mathbf{f}_n` is defined to be\n the map from the `R`-algebra of quasi-symmetric functions\n to itself that sends every symmetric function\n `P(x_1, x_2, x_3, \\ldots)` to\n `P(x_1^n, x_2^n, x_3^n, \\ldots)`. This operator `\\mathbf{f}_n`\n is a Hopf algebra endomorphism, and satisfies\n\n .. MATH::\n\n f_n M_{(i_1, i_2, i_3, \\ldots)} =\n M_{(ni_1, ni_2, ni_3, \\ldots)}\n\n for every composition `(i_1, i_2, i_3, \\ldots)`\n (where `M` means the monomial basis).\n\n The `n`-th Frobenius operator is also called the `n`-th\n Frobenius endomorphism. It is not related to the Frobenius map\n which connects the ring of symmetric functions with the\n representation theory of the symmetric group.\n\n The `n`-th Frobenius operator is also the `n`-th Adams operator\n of the `\\Lambda`-ring of quasi-symmetric functions over the\n integers.\n\n The restriction of the `n`-th Frobenius operator to the\n subring formed by all symmetric functions is, not\n unexpectedly, the `n`-th Frobenius operator of the ring of\n symmetric functions.\n\n .. SEEALSO::\n\n :meth:`Symmetric functions plethysm\n <sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.plethysm>`\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Frobenius operator (on the\n ring of quasi-symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: M = QSym.M()\n sage: F = QSym.F()\n sage: M[3,2].frobenius(2)\n M[6, 4]\n sage: (M[2,1] - 2*M[3]).frobenius(4)\n M[8, 4] - 2*M[12]\n sage: M([]).frobenius(3)\n M[]\n sage: F[1,1].frobenius(2)\n F[1, 1, 1, 1] - F[1, 1, 2] - F[2, 1, 1] + F[2, 2]\n\n The Frobenius endomorphisms are multiplicative::\n\n sage: all( all( M(I).frobenius(3) * M(J).frobenius(3)\n ....: == (M(I) * M(J)).frobenius(3)\n ....: for I in Compositions(3) )\n ....: for J in Compositions(2) )\n True\n\n Being Hopf algebra endomorphisms, the Frobenius operators\n commute with the antipode::\n\n sage: all( M(I).frobenius(4).antipode()\n ....: == M(I).antipode().frobenius(4)\n ....: for I in Compositions(3) )\n True\n\n The restriction of the Frobenius operators to the subring\n of symmetric functions are the Frobenius operators of\n the latter::\n\n sage: e = SymmetricFunctions(ZZ).e()\n sage: all( M(e(lam)).frobenius(3)\n ....: == M(e(lam).frobenius(3))\n ....: for lam in Partitions(3) )\n True\n '
parent = self.parent()
M = parent.realization_of().M()
C = parent._indices
dct = {C([(n * i) for i in I]): coeff for (I, coeff) in M(self)}
result_in_M_basis = M._from_dict(dct)
return parent(result_in_M_basis)
def star_involution(self):
'\n Return the image of the quasisymmetric function ``self`` under\n the star involution.\n\n The star involution is defined as the linear map\n `QSym \\to QSym` which, for every composition `I`, sends the\n monomial quasisymmetric function `M_I` to `M_{I^r}`. Here, if\n `I` is a composition, we denote by `I^r` the reversed\n composition of `I`. Denoting by `f^{\\ast}` the image of an\n element `f \\in QSym` under the star involution, it can be shown\n that every composition `I` satisfies\n\n .. MATH::\n\n (M_I)^{\\ast} = M_{I^r}, \\quad (F_I)^{\\ast} = F_{I^r},\n\n where `F_I` denotes the fundamental quasisymmetric function\n corresponding to the composition `I`. The star involution is an\n involution, an algebra automorphism and a coalgebra\n anti-automorphism of `QSym`. It also is an automorphism of the\n graded vector space `QSym`, and is the identity on the subspace\n `Sym` of `QSym`. It is adjoint to the star involution on `NCSF`\n by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`star involution on NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: M = QSym.M()\n sage: M[3,2].star_involution()\n M[2, 3]\n sage: M[6,3].star_involution()\n M[3, 6]\n sage: (M[9,1] - M[6,2] + 2*M[6,4] - 3*M[3] + 4*M[[]]).star_involution()\n 4*M[] + M[1, 9] - M[2, 6] - 3*M[3] + 2*M[4, 6]\n sage: (M[3,3] - 2*M[2]).star_involution()\n -2*M[2] + M[3, 3]\n sage: M([4,2]).star_involution()\n M[2, 4]\n sage: dI = QSym.dI()\n sage: dI([1,2]).star_involution()\n -dI[1, 2] + dI[2, 1]\n sage: dI.zero().star_involution()\n 0\n\n The star involution commutes with the antipode::\n\n sage: all( M(I).star_involution().antipode()\n ....: == M(I).antipode().star_involution()\n ....: for I in Compositions(4) )\n True\n\n The star involution is the identity on `Sym`::\n\n sage: Sym = SymmetricFunctions(ZZ)\n sage: e = Sym.e()\n sage: all( M(e(lam)).star_involution() == M(e(lam))\n ....: for lam in Partitions(4) )\n True\n '
parent = self.parent()
M = parent.realization_of().M()
dct = {I.reversed(): coeff for (I, coeff) in M(self)}
return parent(M._from_dict(dct))
def omega_involution(self):
'\n Return the image of the quasisymmetric function\n ``self`` under the omega involution.\n\n The omega involution is defined as the linear map\n `QSym \\to QSym` which, for every composition `I`, sends\n the fundamental quasisymmetric function `F_I` to\n `F_{I^t}`, where `I^t` denotes the conjugate\n (:meth:`~sage.combinat.composition.Composition.conjugate`)\n of the composition `I`. This map is commonly denoted by\n `\\omega`. It is an algebra homomorphism and a coalgebra\n antihomomorphism; it also is an involution and an\n automorphism of the graded vector space `QSym`. Also,\n every composition `I` satisfies\n\n .. MATH::\n\n \\omega(M_I) = (-1)^{|I|-\\ell(I)} \\sum M_J,\n\n where the sum ranges over all compositions `J` of `|I|`\n which are coarser than the reversed composition `I^r` of\n `I`. Here, `\\ell(I)` denotes the length of the composition\n `I` (that is, the number of parts of `I`).\n\n If `f` is a homogeneous element of `NCSF` of degree `n`,\n then\n\n .. MATH::\n\n \\omega(f) = (-1)^n S(f),\n\n where `S` denotes the antipode of `QSym`.\n\n The restriction of `\\omega` to the ring of symmetric\n functions (which is a subring of `QSym`) is precisely the\n omega involution\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.omega`)\n of said ring.\n\n The omega involution on `QSym` is adjoint to the omega\n involution on `NCSF` by the standard adjunction between `NCSF`\n and `QSym`.\n\n The omega involution has been denoted by `\\omega` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`omega involution on NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.omega_involution>`,\n :meth:`psi involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: F = QSym.F()\n sage: F[3,2].omega_involution()\n F[1, 2, 1, 1]\n sage: F[6,3].omega_involution()\n F[1, 1, 2, 1, 1, 1, 1, 1]\n sage: (F[9,1] - F[8,2] + 2*F[2,4] - 3*F[3] + 4*F[[]]).omega_involution()\n 4*F[] - 3*F[1, 1, 1] + 2*F[1, 1, 1, 2, 1] - F[1, 2, 1, 1, 1, 1, 1, 1, 1] + F[2, 1, 1, 1, 1, 1, 1, 1, 1]\n sage: (F[3,3] - 2*F[2]).omega_involution()\n -2*F[1, 1] + F[1, 1, 2, 1, 1]\n sage: F([2,1,1]).omega_involution()\n F[3, 1]\n sage: M = QSym.M()\n sage: M([2,1]).omega_involution()\n -M[1, 2] - M[3]\n sage: M.zero().omega_involution()\n 0\n\n Testing the fact that the restriction of `\\omega` to `Sym`\n is the omega automorphism of `Sym`::\n\n sage: Sym = SymmetricFunctions(ZZ)\n sage: e = Sym.e()\n sage: all( F(e[lam]).omega_involution() == F(e[lam].omega())\n ....: for lam in Partitions(4) )\n True\n '
return self.antipode().degree_negation()
def psi_involution(self):
'\n Return the image of the quasisymmetric function ``self``\n under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `QSym \\to QSym` which, for every composition `I`, sends the\n fundamental quasisymmetric function `F_I` to `F_{I^c}`, where\n `I^c` denotes the complement of the composition `I`.\n The map `\\psi` is an involution and a graded Hopf algebra\n automorphism of `QSym`. Its restriction to the ring of\n symmetric functions coincides with the omega automorphism of\n the latter ring.\n\n The involution `\\psi` of `QSym` is adjoint to the involution\n `\\psi` of `NCSF` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution on NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: F = QSym.F()\n sage: F[3,2].psi_involution()\n F[1, 1, 2, 1]\n sage: F[6,3].psi_involution()\n F[1, 1, 1, 1, 1, 2, 1, 1]\n sage: (F[9,1] - F[8,2] + 2*F[2,4] - 3*F[3] + 4*F[[]]).psi_involution()\n 4*F[] - 3*F[1, 1, 1] + F[1, 1, 1, 1, 1, 1, 1, 1, 2] - F[1, 1, 1, 1, 1, 1, 1, 2, 1] + 2*F[1, 2, 1, 1, 1]\n sage: (F[3,3] - 2*F[2]).psi_involution()\n -2*F[1, 1] + F[1, 1, 2, 1, 1]\n sage: F([2,1,1]).psi_involution()\n F[1, 3]\n sage: M = QSym.M()\n sage: M([2,1]).psi_involution()\n -M[2, 1] - M[3]\n sage: M.zero().psi_involution()\n 0\n\n The involution `\\psi` commutes with the antipode::\n\n sage: all( F(I).psi_involution().antipode()\n ....: == F(I).antipode().psi_involution()\n ....: for I in Compositions(4) )\n True\n\n Testing the fact that the restriction of `\\psi` to `Sym`\n is the omega automorphism of `Sym`::\n\n sage: Sym = SymmetricFunctions(ZZ)\n sage: e = Sym.e()\n sage: all( F(e[lam]).psi_involution() == F(e[lam].omega())\n ....: for lam in Partitions(4) )\n True\n '
parent = self.parent()
F = parent.realization_of().F()
dct = {I.complement(): coeff for (I, coeff) in F(self)}
return parent(F._from_dict(dct))
def dendriform_less(self, other):
'\n Return the result of applying the dendriform smaller\n operation to the two quasi-symmetric functions ``self``\n and ``other``.\n\n The dendriform smaller operation is a binary operation,\n denoted by `\\prec` and written infix, on the ring of\n quasi-symmetric functions. It can be defined as a\n restriction of a binary operation (denoted by `\\prec`\n and written infix as well) on the ring of formal power\n series `R[[x_1, x_2, x_3, \\ldots]]`, which is defined\n as follows: If `m` and `n` are two monomials in\n `x_1, x_2, x_3, \\ldots`, then we let `m \\prec n` be\n the product `mn` if the smallest positive integer `i`\n for which `x_i` occurs in `m` is smaller than the\n smallest positive integer `j` for which `x_j` occurs\n in `n` (this is understood to be false when `m = 1`,\n and true when `m \\neq 1` and `n = 1`), and we let\n `m \\prec n` be `0` otherwise. Having thus defined\n `\\prec` on monomials, we extend `\\prec` to a binary\n operation on `R[[x_1, x_2, x_3, \\ldots]]` by requiring\n it to be continuous (in both inputs) and `R`-bilinear.\n It is easily seen that `QSym \\prec QSym \\subseteq\n QSym`, so that `\\prec` restricts to a binary operation\n on `QSym`.\n\n .. SEEALSO::\n\n :meth:`dendriform_leq`\n\n INPUT:\n\n - ``other`` -- a quasi-symmetric function over the\n same base ring as ``self``\n\n OUTPUT:\n\n The quasi-symmetric function ``self`` `\\prec`\n ``other``, written in the basis of ``self``.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: M[2, 1].dendriform_less(M[1, 2])\n 2*M[2, 1, 1, 2] + M[2, 1, 2, 1] + M[2, 1, 3] + M[2, 2, 2]\n sage: F = QSym.F()\n sage: F[2, 1].dendriform_less(F[1, 2])\n F[1, 1, 2, 1, 1] + F[1, 1, 2, 2] + F[1, 1, 3, 1]\n + F[1, 2, 1, 2] + F[1, 2, 2, 1] + F[1, 2, 3]\n + F[2, 1, 1, 2] + F[2, 1, 2, 1] + F[2, 1, 3] + F[2, 2, 2]\n\n The operation `\\prec` can be used to recursively\n construct the dual immaculate basis: For every positive\n integer `m` and every composition `I`, the dual\n immaculate function `\\operatorname{dI}_{[m, I]}` of the\n composition `[m, I]` (this composition is `I` with `m`\n prepended to it) is `F_{[m]} \\prec \\operatorname{dI}_I`. ::\n\n sage: dI = QSym.dI()\n sage: dI(F[2]).dendriform_less(dI[1, 2])\n dI[2, 1, 2]\n\n We check with the identity element::\n\n sage: M.one().dendriform_less(M[1,2])\n 0\n sage: M[1,2].dendriform_less(M.one())\n M[1, 2]\n\n The operation `\\prec` is not symmetric, nor if\n `a \\prec b \\neq 0`, then `b \\prec a = 0` (as it would be\n for a single monomial)::\n\n sage: M[1,2,1].dendriform_less(M[1,2])\n M[1, 1, 2, 1, 2] + 2*M[1, 1, 2, 2, 1] + M[1, 1, 2, 3]\n + M[1, 1, 4, 1] + 2*M[1, 2, 1, 1, 2] + M[1, 2, 1, 2, 1]\n + M[1, 2, 1, 3] + M[1, 2, 2, 2] + M[1, 3, 1, 2]\n + M[1, 3, 2, 1] + M[1, 3, 3]\n sage: M[1,2].dendriform_less(M[1,2,1])\n M[1, 1, 2, 1, 2] + 2*M[1, 1, 2, 2, 1] + M[1, 1, 2, 3]\n + M[1, 1, 4, 1] + M[1, 2, 1, 2, 1] + M[1, 3, 2, 1]\n '
P = self.parent()
M = P.realization_of().M()
a = M(self)
b = M(other)
res = M.zero()
for (I, I_coeff) in a:
if (not I):
continue
i_head = I[0]
I_tail = Composition(I[1:])
for (J, J_coeff) in b:
shufpro = I_tail.shuffle_product(J, overlap=True)
res += (J_coeff * M.sum_of_monomials((Composition(([i_head] + list(K))) for K in shufpro)))
return P(res)
def dendriform_leq(self, other):
'\n Return the result of applying the dendriform\n smaller-or-equal operation to the two quasi-symmetric\n functions ``self`` and ``other``.\n\n The dendriform smaller-or-equal operation is a binary\n operation, denoted by `\\preceq` and written infix, on\n the ring of quasi-symmetric functions. It can be\n defined as a restriction of a binary operation\n (denoted by `\\preceq` and written infix as well) on\n the ring of formal power series\n `R[[x_1, x_2, x_3, \\ldots]]`, which is defined as\n follows: If `m` and `n` are two monomials in\n `x_1, x_2, x_3, \\ldots`, then we let `m \\preceq n` be\n the product `mn` if the smallest positive integer `i`\n for which `x_i` occurs in `m` is smaller or equal to\n the smallest positive integer `j` for which `x_j`\n occurs in `n` (this is understood to be false when\n `m = 1` and `n \\neq 1`, and true when `n = 1`), and we\n let `m \\preceq n` be `0` otherwise. Having thus\n defined `\\preceq` on monomials, we extend `\\preceq` to\n a binary operation on `R[[x_1, x_2, x_3, \\ldots]]` by\n requiring it to be continuous (in both inputs) and\n `R`-bilinear. It is easily seen that\n `QSym \\preceq QSym \\subseteq QSym`, so that `\\preceq`\n restricts to a binary operation on `QSym`.\n\n This operation `\\preceq` is related to the dendriform\n smaller relation `\\prec` (:meth:`dendriform_less`).\n Namely, if we define a binary operation `\\succ` on\n `QSym` by `a \\succ b = b \\prec a`, then\n `(QSym, \\preceq, \\succ)` is a dendriform `R`-algebra.\n Thus, any `a, b \\in QSym` satisfy\n `a \\preceq b = ab - b \\prec a`.\n\n .. SEEALSO::\n\n :meth:`dendriform_less`\n\n INPUT:\n\n - ``other`` -- a quasi-symmetric function over the\n same base ring as ``self``\n\n OUTPUT:\n\n The quasi-symmetric function ``self`` `\\preceq`\n ``other``, written in the basis of ``self``.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: M[2, 1].dendriform_leq(M[1, 2])\n 2*M[2, 1, 1, 2] + M[2, 1, 2, 1] + M[2, 1, 3] + M[2, 2, 2]\n + M[3, 1, 2] + M[3, 2, 1] + M[3, 3]\n sage: F = QSym.F()\n sage: F[2, 1].dendriform_leq(F[1, 2])\n F[2, 1, 1, 2] + F[2, 1, 2, 1] + F[2, 1, 3] + F[2, 2, 1, 1]\n + 2*F[2, 2, 2] + F[2, 3, 1] + F[3, 1, 2] + F[3, 2, 1] + F[3, 3]\n '
P = self.parent()
return ((self * P(other)) - P(other.dendriform_less(self)))
def expand(self, n, alphabet='x'):
"\n Expand the quasi-symmetric function into ``n`` variables in\n an alphabet, which by default is ``'x'``.\n\n INPUT:\n\n - ``n`` -- A nonnegative integer; the number of variables\n in the expansion\n - ``alphabet`` -- (default: ``'x'``); the alphabet in\n which ``self`` is to be expanded\n\n OUTPUT:\n\n - An expansion of ``self`` into the ``n`` variables specified\n by ``alphabet``.\n\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: F[3].expand(3)\n x0^3 + x0^2*x1 + x0*x1^2 + x1^3 + x0^2*x2 + x0*x1*x2 + x1^2*x2 + x0*x2^2 + x1*x2^2 + x2^3\n sage: F[2,1].expand(3)\n x0^2*x1 + x0^2*x2 + x0*x1*x2 + x1^2*x2\n\n One can use a different set of variable by adding an optional\n argument ``alphabet=...`` ::\n\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: F[3].expand(2,alphabet='y')\n y0^3 + y0^2*y1 + y0*y1^2 + y1^3\n\n TESTS::\n\n sage: (3*F([])).expand(2)\n 3\n sage: F[4,2].expand(0)\n 0\n sage: F([]).expand(0)\n 1\n "
M = self.parent().realization_of().Monomial()
return M(self).expand(n, alphabet)
def is_symmetric(self):
'\n Return ``True`` if ``self`` is an element of the symmetric\n functions.\n\n This is being tested by looking at the expansion in\n the Monomial basis and checking if the coefficients are\n the same if the indexing compositions are permutations\n of each other.\n\n OUTPUT:\n\n - ``True`` if ``self`` is symmetric.\n ``False`` if ``self`` is not symmetric.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: F = QSym.Fundamental()\n sage: (F[3,2] + F[2,3]).is_symmetric()\n False\n sage: (F[1, 1, 1, 2] + F[1, 1, 3] + F[1, 3, 1] + F[2, 1, 1, 1] + F[3, 1, 1]).is_symmetric()\n True\n sage: F([]).is_symmetric()\n True\n '
M = self.parent().realization_of().Monomial()
return M(self).is_symmetric()
def to_symmetric_function(self):
'\n Convert a quasi-symmetric function to a symmetric function.\n\n OUTPUT:\n\n - If ``self`` is a symmetric function, then return the expansion\n in the monomial basis. Otherwise raise an error.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: F = QSym.Fundamental()\n sage: (F[3,2] + F[2,3]).to_symmetric_function()\n Traceback (most recent call last):\n ...\n ValueError: F[2, 3] + F[3, 2] is not a symmetric function\n sage: m = SymmetricFunctions(QQ).m()\n sage: s = SymmetricFunctions(QQ).s()\n sage: F(s[3,1,1]).to_symmetric_function()\n 6*m[1, 1, 1, 1, 1] + 3*m[2, 1, 1, 1] + m[2, 2, 1] + m[3, 1, 1]\n sage: m(s[3,1,1])\n 6*m[1, 1, 1, 1, 1] + 3*m[2, 1, 1, 1] + m[2, 2, 1] + m[3, 1, 1]\n '
if self.is_symmetric():
M = self.parent().realization_of().Monomial()
return M(self).to_symmetric_function()
else:
raise ValueError(('%s is not a symmetric function' % self))
class Monomial(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric function in the Monomial basis.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.M()\n sage: F = QSym.F()\n sage: M(F[2,2])\n M[1, 1, 1, 1] + M[1, 1, 2] + M[2, 1, 1] + M[2, 2]\n sage: m = SymmetricFunctions(QQ).m()\n sage: M(m[3,1,1])\n M[1, 1, 3] + M[1, 3, 1] + M[3, 1, 1]\n sage: (1+M[1])^3\n M[] + 3*M[1] + 6*M[1, 1] + 6*M[1, 1, 1] + 3*M[1, 2] + 3*M[2] + 3*M[2, 1] + M[3]\n sage: M[1,2,1].coproduct()\n M[] # M[1, 2, 1] + M[1] # M[2, 1] + M[1, 2] # M[1] + M[1, 2, 1] # M[]\n\n The following is an alias for this basis::\n\n sage: QSym.Monomial()\n Quasisymmetric functions over the Rational Field in the Monomial basis\n\n TESTS::\n\n sage: M(F([]))\n M[]\n sage: M(F(0))\n 0\n sage: M(m([]))\n M[]\n '
def __init__(self, QSym):
'\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial(); M\n Quasisymmetric functions over the Rational Field in the Monomial basis\n sage: TestSuite(M).run()\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='M', bracket=False, category=QSym.Bases())
def dual(self):
'\n Return the dual basis to the Monomial basis. This is the complete basis of the\n non-commutative symmetric functions.\n\n OUTPUT:\n\n - The complete basis of the non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M.dual()\n Non-Commutative Symmetric Functions over the Rational Field in the Complete basis\n '
return self.realization_of().dual().Complete()
def product_on_basis(self, I, J):
'\n The product on Monomial basis elements.\n\n The product of the basis elements indexed by two compositions\n `I` and `J` is the sum of the basis elements indexed by\n compositions in the stuffle product (also called the\n overlapping shuffle product) of `I` and `J`.\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The product of the Monomial quasi-symmetric functions indexed by ``I`` and\n ``J``, expressed in the Monomial basis.\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: c1 = Composition([2])\n sage: c2 = Composition([1,3])\n sage: M.product_on_basis(c1, c2)\n M[1, 2, 3] + M[1, 3, 2] + M[1, 5] + M[2, 1, 3] + M[3, 3]\n sage: M.product_on_basis(c1, Composition([]))\n M[2]\n '
return self.sum_of_monomials(I.shuffle_product(J, overlap=True))
def antipode_on_basis(self, compo):
'\n Return the result of the antipode applied to a quasi-symmetric Monomial basis\n element.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The result of the antipode applied to the composition ``compo``, expressed\n in the Monomial basis.\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: M.antipode_on_basis(Composition([2,1]))\n M[1, 2] + M[3]\n sage: M.antipode_on_basis(Composition([]))\n M[]\n '
return (((- 1) ** len(compo)) * self.sum_of_fatter_compositions(compo.reversed()))
def coproduct_on_basis(self, compo):
'\n Return the coproduct of a Monomial basis element.\n\n Combinatorial rule: deconcatenation.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The coproduct applied to the Monomial quasi-symmetric function indexed by\n ``compo``, expressed in the Monomial basis.\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: M[4,2,3].coproduct()\n M[] # M[4, 2, 3] + M[4] # M[2, 3] + M[4, 2] # M[3] + M[4, 2, 3] # M[]\n sage: M.coproduct_on_basis(Composition([]))\n M[] # M[]\n '
return self.tensor_square().sum_of_monomials(((self._indices(compo[:i]), self._indices(compo[i:])) for i in range((len(compo) + 1))))
def lambda_of_monomial(self, I, n):
'\n Return the image of the monomial quasi-symmetric function\n `M_I` under the lambda-map `\\lambda^n`, expanded in the\n monomial basis.\n\n The ring of quasi-symmetric functions over the integers,\n `\\mathrm{QSym}_{\\ZZ}` (and more generally, the ring of\n quasi-symmetric functions over any binomial ring) becomes\n a `\\lambda`-ring (with the `\\lambda`-structure inherited\n from the ring of formal power series, so that\n `\\lambda^i(x_j)` is `x_j` if `i = 1` and `0` if `i > 1`).\n\n The Adams operations of this `\\lambda`-ring are the\n Frobenius endomorphisms `\\mathbf{f}_n` (see\n :meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.frobenius`\n for their definition). Using these endomorphisms, the\n `\\lambda`-operations can be explicitly computed via the formula\n\n .. MATH::\n\n \\exp \\left(- \\sum_{n=1}^{\\infty}\n \\frac{1}{n} \\mathbf{f}_n(x) t^n \\right)\n = \\sum_{j=0}^{\\infty} (-1)^j \\lambda^j(x) t^j\n\n in the ring of formal power series in a variable `t` over\n the ring of quasi-symmetric functions. In particular,\n every composition `I = (I_1, I_2, \\cdots, I_\\ell )` satisfies\n\n .. MATH::\n\n \\exp \\left(- \\sum_{n=1}^{\\infty}\n \\frac{1}{n} M_{(nI_1, nI_2, \\cdots, nI_\\ell )} t^n \\right)\n = \\sum_{j=0}^{\\infty} (-1)^j \\lambda^j(M_I) t^j\n\n (corrected version of Remark 2.4 in [Haz2004]_).\n\n The quasi-symmetric functions `\\lambda^i(M_I)` with `n`\n ranging over the positive integers and `I` ranging over\n the reduced Lyndon compositions (i. e., compositions\n which are Lyndon words and have the gcd of their entries\n equal to `1`) form a set of free polynomial generators\n for `\\mathrm{QSym}`. See [GriRei18]_, Chapter 6, for\n the proof, and [Haz2004]_ for a major part of it.\n\n INPUT:\n\n - ``I`` -- composition\n - ``n`` -- nonnegative integer\n\n OUTPUT:\n\n The quasi-symmetric function `\\lambda^n(M_I)`, expanded in\n the monomial basis over the ground ring of ``self``.\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(CyclotomicField()).Monomial()\n sage: M.lambda_of_monomial([1, 2], 2)\n 2*M[1, 1, 2, 2] + M[1, 1, 4] + M[1, 2, 1, 2] + M[1, 3, 2] + M[2, 2, 2]\n sage: M.lambda_of_monomial([1, 1], 2)\n 3*M[1, 1, 1, 1] + M[1, 1, 2] + M[1, 2, 1] + M[2, 1, 1]\n sage: M = QuasiSymmetricFunctions(Integers(19)).Monomial()\n sage: M.lambda_of_monomial([1, 2], 3)\n 6*M[1, 1, 1, 2, 2, 2] + 3*M[1, 1, 1, 2, 4] + 3*M[1, 1, 1, 4, 2]\n + M[1, 1, 1, 6] + 4*M[1, 1, 2, 1, 2, 2] + 2*M[1, 1, 2, 1, 4]\n + 2*M[1, 1, 2, 2, 1, 2] + 2*M[1, 1, 2, 3, 2] + 4*M[1, 1, 3, 2, 2]\n + 2*M[1, 1, 3, 4] + M[1, 1, 4, 1, 2] + M[1, 1, 5, 2]\n + 2*M[1, 2, 1, 1, 2, 2] + M[1, 2, 1, 1, 4] + M[1, 2, 1, 2, 1, 2]\n + M[1, 2, 1, 3, 2] + 4*M[1, 2, 2, 2, 2] + M[1, 2, 2, 4] + M[1, 2, 4, 2]\n + 2*M[1, 3, 1, 2, 2] + M[1, 3, 1, 4] + M[1, 3, 2, 1, 2] + M[1, 3, 3, 2]\n + M[1, 4, 2, 2] + 3*M[2, 1, 2, 2, 2] + M[2, 1, 2, 4] + M[2, 1, 4, 2]\n + 2*M[2, 2, 1, 2, 2] + M[2, 2, 1, 4] + M[2, 2, 2, 1, 2] + M[2, 2, 3, 2]\n + 2*M[2, 3, 2, 2] + M[2, 3, 4] + M[3, 2, 2, 2]\n\n The map `\\lambda^0` sends everything to `1`::\n\n sage: M = QuasiSymmetricFunctions(ZZ).Monomial()\n sage: all( M.lambda_of_monomial(I, 0) == M.one()\n ....: for I in Compositions(3) )\n True\n\n The map `\\lambda^1` is the identity map::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: all( M.lambda_of_monomial(I, 1) == M(I)\n ....: for I in Compositions(3) )\n True\n sage: M = QuasiSymmetricFunctions(Integers(5)).Monomial()\n sage: all( M.lambda_of_monomial(I, 1) == M(I)\n ....: for I in Compositions(3) )\n True\n sage: M = QuasiSymmetricFunctions(ZZ).Monomial()\n sage: all( M.lambda_of_monomial(I, 1) == M(I)\n ....: for I in Compositions(3) )\n True\n '
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
QQM = QuasiSymmetricFunctions(QQ).M()
QQ_result = QQM.zero()
for lam in Partitions(n):
coeff = (QQ(((- 1) ** len(lam))) / lam.centralizer_size())
QQ_result += (coeff * QQM.prod([QQM(self._indices([(k * i) for i in I])) for k in lam]))
QQ_result *= ((- 1) ** n)
result = self.sum_of_terms([(J, ZZ(coeff)) for (J, coeff) in QQ_result], distinct=True)
return result
class Element(CombinatorialFreeModule.Element):
'\n Element methods of the ``Monomial`` basis of ``QuasiSymmetricFunctions``.\n '
def psi_involution(self):
'\n Return the image of the quasisymmetric function ``self``\n under the involution `\\psi`.\n\n The involution `\\psi` is defined as the linear map\n `QSym \\to QSym` which, for every composition `I`, sends the\n fundamental quasisymmetric function `F_I` to `F_{I^c}`, where\n `I^c` denotes the complement of the composition `I`.\n The map `\\psi` is an involution and a graded Hopf algebra\n automorphism of `QSym`. Its restriction to the ring of\n symmetric functions coincides with the omega automorphism of\n the latter ring.\n\n The involution `\\psi` of `QSym` is adjoint to the involution\n `\\psi` of `NCSF` by the standard adjunction between `NCSF` and\n `QSym`.\n\n The involution `\\psi` has been denoted by `\\psi` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`psi involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`psi involution on NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.psi_involution>`,\n :meth:`star involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: M = QSym.M()\n sage: M[3,2].psi_involution()\n -M[3, 2] - M[5]\n sage: M[3,1].psi_involution()\n M[3, 1] + M[4]\n sage: M[3,1,1].psi_involution()\n M[3, 1, 1] + M[3, 2] + M[4, 1] + M[5]\n sage: M[1,1,1].psi_involution()\n M[1, 1, 1] + M[1, 2] + M[2, 1] + M[3]\n sage: M[[]].psi_involution()\n M[]\n sage: M(0).psi_involution()\n 0\n sage: (2*M[[]] - M[3,1] + 4*M[2]).psi_involution()\n 2*M[] - 4*M[2] - M[3, 1] - M[4]\n\n This particular implementation is tailored to the monomial\n basis. It is semantically equivalent to the generic\n implementation it overshadows::\n\n sage: F = QSym.F()\n sage: all( F(M[I].psi_involution()) == F(M[I]).psi_involution()\n ....: for I in Compositions(3) )\n True\n\n sage: F = QSym.F()\n sage: all( F(M[I].psi_involution()) == F(M[I]).psi_involution()\n ....: for I in Compositions(4) )\n True\n '
parent = self.parent()
return parent.sum((((((- 1) ** (I.size() - len(I))) * coeff) * parent.sum_of_fatter_compositions(I)) for (I, coeff) in self._monomial_coefficients.items()))
def expand(self, n, alphabet='x'):
"\n Expand the quasi-symmetric function written in the monomial basis in\n `n` variables.\n\n INPUT:\n\n - ``n`` -- an integer\n - ``alphabet`` -- (default: ``'x'``) a string\n\n OUTPUT:\n\n - The quasi-symmetric function ``self`` expressed in the ``n`` variables\n described by ``alphabet``.\n\n .. TODO:: accept an *alphabet* as input\n\n EXAMPLES::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: M[4,2].expand(3)\n x0^4*x1^2 + x0^4*x2^2 + x1^4*x2^2\n\n One can use a different set of variables by using the\n optional argument ``alphabet``::\n\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: M[2,1,1].expand(4,alphabet='y')\n y0^2*y1*y2 + y0^2*y1*y3 + y0^2*y2*y3 + y1^2*y2*y3\n\n TESTS::\n\n sage: (3*M([])).expand(2)\n 3\n sage: M[4,2].expand(0)\n 0\n sage: M([]).expand(0)\n 1\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
M = self.parent()
P = PolynomialRing(M.base_ring(), n, alphabet)
x = P.gens()
def on_basis(comp, i):
if (not comp):
return P.one()
elif (len(comp) > i):
return P.zero()
else:
return (((x[(i - 1)] ** comp[(- 1)]) * on_basis(comp[:(- 1)], (i - 1))) + on_basis(comp, (i - 1)))
return M._apply_module_morphism(self, (lambda comp: on_basis(comp, n)), codomain=P)
def is_symmetric(self):
'\n Determine if a quasi-symmetric function, written in the Monomial basis,\n is symmetric.\n\n This is being tested by looking at the expansion in the Monomial\n basis and checking if the coefficients are the same if the indexing\n compositions are permutations of each other.\n\n OUTPUT:\n\n - ``True`` if ``self`` is an element of the symmetric\n functions and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.Monomial()\n sage: (M[3,2] + M[2,3] + M[4,1]).is_symmetric()\n False\n sage: (M[3,2] + M[2,3]).is_symmetric()\n True\n sage: (M[1,2,1] + M[1,1,2]).is_symmetric()\n False\n sage: (M[1,2,1] + M[1,1,2] + M[2,1,1]).is_symmetric()\n True\n '
from sage.combinat.permutation import Permutations_mset
d = {}
for (I, coeff) in self:
partition = I.to_partition()
if (partition not in d):
d[partition] = [coeff, 1]
elif (d[partition][0] != coeff):
return False
else:
d[partition][1] += 1
return all(((d[partition][1] == Permutations_mset(partition).cardinality()) for partition in d))
def to_symmetric_function(self):
'\n Take a quasi-symmetric function, expressed in the monomial basis, and\n return its symmetric realization, when possible, expressed in the\n monomial basis of symmetric functions.\n\n OUTPUT:\n\n - If ``self`` is a symmetric function, then the expansion\n in the monomial basis of the symmetric functions is returned.\n Otherwise an error is raised.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: M = QSym.Monomial()\n sage: (M[3,2] + M[2,3] + M[4,1]).to_symmetric_function()\n Traceback (most recent call last):\n ...\n ValueError: M[2, 3] + M[3, 2] + M[4, 1] is not a symmetric function\n sage: (M[3,2] + M[2,3] + 2*M[4,1] + 2*M[1,4]).to_symmetric_function()\n m[3, 2] + 2*m[4, 1]\n sage: m = SymmetricFunctions(QQ).m()\n sage: M(m[3,1,1]).to_symmetric_function()\n m[3, 1, 1]\n sage: (M(m[2,1])*M(m[2,1])).to_symmetric_function()-m[2,1]*m[2,1]\n 0\n\n TESTS::\n\n sage: (M(0)).to_symmetric_function()\n 0\n sage: (M([])).to_symmetric_function()\n m[]\n sage: (2*M([])).to_symmetric_function()\n 2*m[]\n\n We check that the result is indexed by partitions::\n\n sage: M([]).to_symmetric_function().leading_support().parent()\n Partitions\n '
m = SymmetricFunctions(self.parent().base_ring()).monomial()
if self.is_symmetric():
return m._from_dict({_Partitions(list(I)): coeff for (I, coeff) in self if (list(I) in _Partitions)}, remove_zeros=False)
else:
raise ValueError(('%s is not a symmetric function' % self))
M = Monomial
class Fundamental(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric functions in the Fundamental basis.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: F = QSym.F()\n sage: M = QSym.M()\n sage: F(M[2,2])\n F[1, 1, 1, 1] - F[1, 1, 2] - F[2, 1, 1] + F[2, 2]\n sage: s = SymmetricFunctions(QQ).s()\n sage: F(s[3,2])\n F[1, 2, 2] + F[1, 3, 1] + F[2, 2, 1] + F[2, 3] + F[3, 2]\n sage: (1+F[1])^3\n F[] + 3*F[1] + 3*F[1, 1] + F[1, 1, 1] + 2*F[1, 2] + 3*F[2] + 2*F[2, 1] + F[3]\n sage: F[1,2,1].coproduct()\n F[] # F[1, 2, 1] + F[1] # F[2, 1] + F[1, 1] # F[1, 1] + F[1, 2] # F[1] + F[1, 2, 1] # F[]\n\n The following is an alias for this basis::\n\n sage: QSym.Fundamental()\n Quasisymmetric functions over the Rational Field in the Fundamental basis\n\n TESTS::\n\n sage: F(M([]))\n F[]\n sage: F(M(0))\n 0\n sage: F(s([]))\n F[]\n sage: F(s(0))\n 0\n '
def __init__(self, QSym):
'\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental(); F\n Quasisymmetric functions over the Rational Field in the Fundamental basis\n sage: TestSuite(F).run()\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='F', bracket=False, category=QSym.Bases())
def _from_schur_on_basis(self, la):
'\n Maps the Schur symmetric function indexed by ``la`` to the\n Fundamental basis.\n\n EXAMPLES::\n\n sage: s = SymmetricFunctions(QQ).schur()\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: F(s[2,2]-s[3,1]) # indirect doctest\n F[1, 2, 1] - F[1, 3] - F[3, 1]\n\n sage: F._from_schur_on_basis(Partition([]))\n F[]\n\n sage: F._from_schur_on_basis(Partition([2,2,2]))\n F[1, 1, 2, 1, 1] + F[1, 2, 1, 2] + F[1, 2, 2, 1] + F[2, 1, 2, 1] + F[2, 2, 2]\n '
C = self._indices
res = 0
n = la.size()
for T in StandardTableaux(la):
des = T.standard_descents()
comp = C.from_descents([(d - 1) for d in des], n)
res += self.monomial(comp)
return res
def dual(self):
'\n Return the dual basis to the Fundamental basis. This is the ribbon\n basis of the non-commutative symmetric functions.\n\n OUTPUT:\n\n - The ribbon basis of the non-commutative symmetric functions.\n\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F.dual()\n Non-Commutative Symmetric Functions over the Rational Field in the Ribbon basis\n '
return self.realization_of().dual().Ribbon()
def antipode_on_basis(self, compo):
'\n Return the antipode to a Fundamental quasi-symmetric basis element.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The result of the antipode applied to the quasi-symmetric\n Fundamental basis element indexed by ``compo``.\n\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F.antipode_on_basis(Composition([2,1]))\n -F[2, 1]\n '
return (((- 1) ** compo.size()) * self.monomial(compo.conjugate()))
def coproduct_on_basis(self, compo):
'\n Return the coproduct to a Fundamental quasi-symmetric basis element.\n\n Combinatorial rule: quasi-deconcatenation.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The application of the coproduct to the Fundamental quasi-symmetric\n function indexed by the composition ``compo``.\n\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).Fundamental()\n sage: F[4].coproduct()\n F[] # F[4] + F[1] # F[3] + F[2] # F[2] + F[3] # F[1] + F[4] # F[]\n sage: F[2,1,3].coproduct()\n F[] # F[2, 1, 3] + F[1] # F[1, 1, 3] + F[2] # F[1, 3] + F[2, 1] # F[3] + F[2, 1, 1] # F[2] + F[2, 1, 2] # F[1] + F[2, 1, 3] # F[]\n\n TESTS::\n\n sage: F.coproduct_on_basis(Composition([2,1,3]))\n F[] # F[2, 1, 3] + F[1] # F[1, 1, 3] + F[2] # F[1, 3] + F[2, 1] # F[3] + F[2, 1, 1] # F[2] + F[2, 1, 2] # F[1] + F[2, 1, 3] # F[]\n sage: F.one().coproduct() # generic for graded / graded connected\n F[] # F[]\n '
T = self.tensor_square()
C = Composition
return (T.sum_of_monomials(((C(compo[:i]), C(compo[i:])) for i in range((len(compo) + 1)))) + T.sum_of_monomials(((C((compo[:i] + [j])), C(([(compo[i] - j)] + compo[(i + 1):]))) for i in range(len(compo)) for j in range(1, compo[i]))))
@cached_method
def Eulerian(self, n, j, k=None):
'\n Return the Eulerian (quasi)symmetric function `Q_{n,j}` (with\n `n` either an integer or a partition) defined in [SW2010]_ in\n terms of the fundamental quasisymmetric functions.\n Or, if the optional argument ``k`` is specified, return the\n function `Q_{n,j,k}` defined ibidem.\n\n If `n` and `j` are nonnegative integers, then the Eulerian\n quasisymmetric function `Q_{n,j}` is defined as\n\n .. MATH::\n\n Q_{n,j} := \\sum_{\\sigma} F_{\\mathrm{Dex}(\\sigma)},\n\n where we sum over all permutations `\\sigma \\in S_n` such that\n the number of excedances of `\\sigma` is `j`, and where\n `\\mathrm{Dex}(\\sigma)` is a composition of `n` defined as follows:\n Let `S` be the set of all `i \\in \\{ 1, 2, \\ldots, n-1 \\}` such\n that either `\\sigma_i > \\sigma_{i+1} > i+1` or\n `i \\geq \\sigma_i > \\sigma_{i+1}` or\n `\\sigma_{i+1} > i + 1 > \\sigma_i`. Then,\n `\\mathrm{Dex}(\\sigma)` is set to be the composition of `n` whose\n descent set is `S`.\n\n Here, an excedance of a permutation `\\sigma \\in S_n` means an\n element `i \\in \\{ 1, 2, \\ldots, n-1 \\}` satisfying `\\sigma_i > i`.\n\n Similarly we can define a quasisymmetric function `Q_{\\lambda, j}`\n for every partition `\\lambda` and every nonnegative integer `j`.\n This differs from `Q_{n,j}` only in that the sum is restricted to\n all permutations `\\sigma \\in S_n` whose cycle type is `\\lambda`\n (where `n = |\\lambda|`, and where we still require the number of\n excedances to be `j`). The method at hand allows computing these\n functions by passing `\\lambda` as the ``n`` parameter.\n\n Analogously we can define a quasisymmetric function `Q_{n,j,k}` for\n any nonnegative integers `n`, `j` and `k` by restricting the sum to\n all permutations `\\sigma \\in S_n` that have exactly `k` fixed\n points (and `j` excedances). This can be obtained by specifying the\n optional ``k`` argument in this method.\n\n All three versions of Eulerian quasisymmetric functions\n (`Q_{n,j}`, `Q_{\\lambda,j}` and `Q_{n,j,k}`) are actually\n symmetric functions. See\n :meth:`~sage.combinat.sf.SymmetricFunctionsBases.ParentMethods.Eulerian`.\n\n INPUT:\n\n - ``n`` -- the nonnegative integer `n` or a partition\n - ``j`` -- the number of excedances\n - ``k`` -- (optional) if specified, determines the number of fixed\n points of the permutations which are being summed over\n\n EXAMPLES::\n\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F.Eulerian(3, 1)\n F[1, 2] + F[2, 1] + 2*F[3]\n sage: F.Eulerian(4, 2)\n F[1, 2, 1] + 2*F[1, 3] + 3*F[2, 2] + 2*F[3, 1] + 3*F[4]\n sage: F.Eulerian(5, 2)\n F[1, 1, 2, 1] + F[1, 1, 3] + F[1, 2, 1, 1] + 7*F[1, 2, 2] + 6*F[1, 3, 1] + 6*F[1, 4] + 2*F[2, 1, 2] + 7*F[2, 2, 1] + 11*F[2, 3] + F[3, 1, 1] + 11*F[3, 2] + 6*F[4, 1] + 6*F[5]\n sage: F.Eulerian(4, 0)\n F[4]\n sage: F.Eulerian(4, 3)\n F[4]\n sage: F.Eulerian(4, 1, 2)\n F[1, 2, 1] + F[1, 3] + 2*F[2, 2] + F[3, 1] + F[4]\n sage: F.Eulerian(Partition([2, 2, 1]), 2)\n F[1, 1, 2, 1] + F[1, 2, 1, 1] + 2*F[1, 2, 2] + F[1, 3, 1]\n + F[1, 4] + F[2, 1, 2] + 2*F[2, 2, 1] + 2*F[2, 3]\n + 2*F[3, 2] + F[4, 1] + F[5]\n sage: F.Eulerian(0, 0)\n F[]\n sage: F.Eulerian(0, 1)\n 0\n sage: F.Eulerian(1, 0)\n F[1]\n sage: F.Eulerian(1, 1)\n 0\n\n TESTS::\n\n sage: F = QuasiSymmetricFunctions(QQ).F()\n sage: F.Eulerian(Partition([3, 1]), 1, 1)\n Traceback (most recent call last):\n ...\n ValueError: invalid input, k cannot be specified\n '
from sage.combinat.partition import _Partitions
if (n in _Partitions):
if (k is not None):
raise ValueError('invalid input, k cannot be specified')
la = _Partitions(n)
n = sum(la)
else:
la = None
if (n == 0):
if ((k is not None) and (k != 0)):
return self.zero()
if (j != 0):
return self.zero()
return self.one()
monomials = []
for p in Permutations(n):
dex = []
exc = 0
for i in range((n - 1)):
if (p[i] > (i + 1)):
exc += 1
if (((p[i] > p[(i + 1)]) or ((p[i] <= (i + 1)) and (p[(i + 1)] > (i + 2)))) and (not ((p[i] > (i + 1)) and (p[(i + 1)] <= (i + 2))))):
dex.append(i)
if (exc != j):
continue
if ((k is not None) and (p.number_of_fixed_points() != k)):
continue
if ((la is not None) and (p.cycle_type() != la)):
continue
d = (([(- 1)] + dex) + [(n - 1)])
monomials.append(Compositions()([(d[(i + 1)] - d[i]) for i in range((len(d) - 1))]))
return self.sum_of_monomials(monomials)
class Element(CombinatorialFreeModule.Element):
def internal_coproduct(self):
'\n Return the inner coproduct of ``self`` in the Fundamental basis.\n\n The inner coproduct (also known as the Kronecker coproduct,\n or as the second comultiplication on the `R`-algebra of\n quasi-symmetric functions) is an `R`-algebra homomorphism\n `\\Delta^{\\times}` from the `R`-algebra of quasi-symmetric\n functions to the tensor square (over `R`) of quasi-symmetric\n functions. It can be defined in the following two ways:\n\n #. If `I` is a composition, then a `(0, I)`-matrix will mean a\n matrix whose entries are nonnegative integers such that no\n row and no column of this matrix is zero, and such that if\n all the non-zero entries of the matrix are read (row by row,\n starting at the topmost row, reading every row from left to\n right), then the reading word obtained is `I`. If `A` is\n a `(0, I)`-matrix, then `\\mathrm{row}(A)` will denote the\n vector of row sums of `A` (regarded as a composition), and\n `\\mathrm{column}(A)` will denote the vector of column sums\n of `A` (regarded as a composition).\n\n For every composition `I`, the internal coproduct\n `\\Delta^{\\times}(M_I)` of the `I`-th monomial quasisymmetric\n function `M_I` is the sum\n\n .. MATH::\n\n \\sum_{A \\hbox{ is a } (0, I) \\text{-matrix}}\n M_{\\mathrm{row}(A)} \\otimes M_{\\mathrm{column}(A)}.\n\n See Section 11.39 of [HazWitt1]_.\n\n #. For every permutation `w`, let `C(w)` denote the descent\n composition of `w`. Then, for any composition `I` of size\n `n`, the internal coproduct `\\Delta^{\\times}(F_I)` of the\n `I`-th fundamental quasisymmetric function `F_I` is the sum\n\n .. MATH::\n\n \\sum_{\\substack{\\sigma \\in S_n,\\\\ \\tau \\in S_n,\\\\\n \\tau \\sigma = \\pi}} F_{C(\\sigma)} \\otimes F_{C(\\tau)},\n\n where `\\pi` is any permutation in `S_n` having descent\n composition `I` and where permutations act from the left and\n multiply accordingly, so `\\tau \\sigma` means first applying\n `\\sigma` and then `\\tau`. See Theorem 4.23 in [Mal1993]_,\n but beware of the notations which are apparently different\n from those in [HazWitt1]_.\n\n The restriction of the internal coproduct to the\n `R`-algebra of symmetric functions is the well-known\n internal coproduct on the symmetric functions.\n\n The method :meth:`kronecker_coproduct` is a synonym of this one.\n\n EXAMPLES:\n\n Let us compute the internal coproduct of `M_{21}` (which is\n short for `M_{[2, 1]}`). The `(0, [2,1])`-matrices are\n\n .. MATH::\n\n \\begin{bmatrix}2& 1\\end{bmatrix},\n \\begin{bmatrix}2\\\\1\\end{bmatrix},\n \\begin{bmatrix}2& 0\\\\0& 1\\end{bmatrix}, \\hbox{ and }\n \\begin{bmatrix}0&2\\\\1&0\\end{bmatrix}\n\n so\n\n .. MATH::\n\n \\Delta^\\times(M_{21}) = M_{3} \\otimes M_{21} +\n M_{21} \\otimes M_3 + M_{21} \\otimes M_{21} +\n M_{21} \\otimes M_{12}.\n\n This is confirmed by the following Sage computation (incidentally\n demonstrating the non-cocommutativity of the internal\n coproduct)::\n\n sage: M = QuasiSymmetricFunctions(ZZ).M()\n sage: a = M([2,1])\n sage: a.internal_coproduct()\n M[2, 1] # M[1, 2] + M[2, 1] # M[2, 1] + M[2, 1] # M[3] + M[3] # M[2, 1]\n\n Some examples on the Fundamental basis::\n\n sage: F = QuasiSymmetricFunctions(ZZ).F()\n sage: F([1,1]).internal_coproduct()\n F[1, 1] # F[2] + F[2] # F[1, 1]\n sage: F([2]).internal_coproduct()\n F[1, 1] # F[1, 1] + F[2] # F[2]\n sage: F([3]).internal_coproduct()\n F[1, 1, 1] # F[1, 1, 1] + F[1, 2] # F[1, 2] + F[1, 2] # F[2, 1]\n + F[2, 1] # F[1, 2] + F[2, 1] # F[2, 1] + F[3] # F[3]\n sage: F([1,2]).internal_coproduct()\n F[1, 1, 1] # F[1, 2] + F[1, 2] # F[2, 1] + F[1, 2] # F[3]\n + F[2, 1] # F[1, 1, 1] + F[2, 1] # F[2, 1] + F[3] # F[1, 2]\n '
F = self.parent()
F2 = F.tensor(F)
result = F2.zero()
from sage.categories.tensor import tensor
from sage.combinat.permutation import Permutation
for (I, a) in self:
from sage.combinat.permutation import descents_composition_last
pi = descents_composition_last(I)
n = I.size()
for sigma in Permutations(n):
sigma_inverse = sigma.inverse()
tau = Permutation([pi(i) for i in sigma_inverse])
result += (a * tensor([F(sigma.descents_composition()), F(tau.descents_composition())]))
return result
kronecker_coproduct = internal_coproduct
def star_involution(self):
'\n Return the image of the quasisymmetric function ``self`` under\n the star involution.\n\n The star involution is defined as the linear map\n `QSym \\to QSym` which, for every composition `I`, sends the\n monomial quasisymmetric function `M_I` to `M_{I^r}`. Here, if\n `I` is a composition, we denote by `I^r` the reversed\n composition of `I`. Denoting by `f^{\\ast}` the image of an\n element `f \\in QSym` under the star involution, it can be shown\n that every composition `I` satisfies\n\n .. MATH::\n\n (M_I)^{\\ast} = M_{I^r}, \\quad (F_I)^{\\ast} = F_{I^r},\n\n where `F_I` denotes the fundamental quasisymmetric function\n corresponding to the composition `I`. The star involution is an\n involution, an algebra automorphism and a coalgebra\n anti-automorphism of `QSym`. It also is an automorphism of the\n graded vector space `QSym`, and is the identity on the subspace\n `Sym` of `QSym`. It is adjoint to the star involution on `NCSF`\n by the standard adjunction between `NCSF` and `QSym`.\n\n The star involution has been denoted by `\\rho` in [LMvW13]_,\n section 3.6.\n\n .. SEEALSO::\n\n :meth:`star involution on QSym\n <sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Bases.ElementMethods.star_involution>`,\n :meth:`star involution on NCSF\n <sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.star_involution>`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: F = QSym.F()\n sage: F[3,1].star_involution()\n F[1, 3]\n sage: F[5,3].star_involution()\n F[3, 5]\n sage: (F[9,1] - F[6,2] + 2*F[6,4] - 3*F[3] + 4*F[[]]).star_involution()\n 4*F[] + F[1, 9] - F[2, 6] - 3*F[3] + 2*F[4, 6]\n sage: (F[3,3] - 2*F[2]).star_involution()\n -2*F[2] + F[3, 3]\n sage: F([4,2]).star_involution()\n F[2, 4]\n sage: dI = QSym.dI()\n sage: dI([1,2]).star_involution()\n -dI[1, 2] + dI[2, 1]\n sage: dI.zero().star_involution()\n 0\n '
parent = self.parent()
dct = {I.reversed(): coeff for (I, coeff) in self}
return parent._from_dict(dct)
F = Fundamental
class Essential(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric functions in the Essential basis.\n\n The Essential quasi-symmetric functions are defined by\n\n .. MATH::\n\n E_I = \\sum_{J \\geq I} M_J = \\sum_{i_1 \\leq \\cdots \\leq i_k}\n x_{i_1}^{I_1} \\cdots x_{i_k}^{I_k},\n\n where `I = (I_1, \\ldots, I_k)`.\n\n .. NOTE::\n\n Our convention of `\\leq` and `\\geq` of compositions is\n opposite that of [Hoff2015]_.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: E = QSym.E()\n sage: M = QSym.M()\n sage: E(M[2,2])\n E[2, 2] - E[4]\n sage: s = SymmetricFunctions(QQ).s()\n sage: E(s[3,2])\n 5*E[1, 1, 1, 1, 1] - 2*E[1, 1, 1, 2] - 2*E[1, 1, 2, 1]\n - 2*E[1, 2, 1, 1] + E[1, 2, 2] - 2*E[2, 1, 1, 1]\n + E[2, 1, 2] + E[2, 2, 1]\n sage: (1 + E[1])^3\n E[] + 3*E[1] + 6*E[1, 1] + 6*E[1, 1, 1] - 3*E[1, 2]\n - 3*E[2] - 3*E[2, 1] + E[3]\n sage: E[1,2,1].coproduct()\n E[] # E[1, 2, 1] + E[1] # E[2, 1] + E[1, 2] # E[1] + E[1, 2, 1] # E[]\n\n The following is an alias for this basis::\n\n sage: QSym.Essential()\n Quasisymmetric functions over the Rational Field in the Essential basis\n\n TESTS::\n\n sage: E(M([]))\n E[]\n sage: E(M(0))\n 0\n sage: E(s([]))\n E[]\n sage: E(s(0))\n 0\n '
def __init__(self, QSym):
'\n EXAMPLES::\n\n sage: E = QuasiSymmetricFunctions(QQ).Essential()\n sage: TestSuite(E).run()\n\n TESTS::\n\n sage: E = QuasiSymmetricFunctions(QQ).E()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all(E(M(E[c])) == E[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n sage: all(M(E(M[c])) == M[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='E', bracket=False, category=QSym.Bases())
M = QSym.M()
category = self.realization_of()._category
M.module_morphism(self.alternating_sum_of_fatter_compositions, codomain=self, category=category).register_as_coercion()
self.module_morphism(M.sum_of_fatter_compositions, codomain=M, category=category).register_as_coercion()
def antipode_on_basis(self, compo):
'\n Return the result of the antipode applied to a quasi-symmetric\n Essential basis element.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The result of the antipode applied to the composition ``compo``,\n expressed in the Essential basis.\n\n EXAMPLES::\n\n sage: E = QuasiSymmetricFunctions(QQ).E()\n sage: E.antipode_on_basis(Composition([2,1]))\n E[1, 2] - E[3]\n sage: E.antipode_on_basis(Composition([]))\n E[]\n\n TESTS::\n\n sage: E = QuasiSymmetricFunctions(QQ).E()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all(E(M(E[c]).antipode()) == E[c].antipode()\n ....: for n in range(5) for c in Compositions(n))\n True\n\n sage: all((-1)**len(I) * E[I] == M[I].star_involution().antipode()\n ....: for k in [3,4] for I in Compositions(k))\n True\n '
return (((- 1) ** len(compo)) * self.alternating_sum_of_fatter_compositions(compo.reversed()))
def coproduct_on_basis(self, compo):
'\n Return the coproduct of a Essential basis element.\n\n Combinatorial rule: deconcatenation.\n\n INPUT:\n\n - ``compo`` -- composition\n\n OUTPUT:\n\n - The coproduct applied to the Essential quasi-symmetric function\n indexed by ``compo``, expressed in the Essential basis.\n\n EXAMPLES::\n\n sage: E = QuasiSymmetricFunctions(QQ).Essential()\n sage: E[4,2,3].coproduct()\n E[] # E[4, 2, 3] + E[4] # E[2, 3] + E[4, 2] # E[3] + E[4, 2, 3] # E[]\n sage: E.coproduct_on_basis(Composition([]))\n E[] # E[]\n '
return self.tensor_square().sum_of_monomials(((self._indices(compo[:i]), self._indices(compo[i:])) for i in range((len(compo) + 1))))
def product_on_basis(self, I, J):
'\n The product on Essential basis elements.\n\n The product of the basis elements indexed by two compositions\n `I` and `J` is the sum of the basis elements indexed by\n compositions `K` in the stuffle product (also called the\n overlapping shuffle product) of `I` and `J` with a\n coefficient of `(-1)^{\\ell(I) + \\ell(J) - \\ell(K)}`,\n where `\\ell(C)` is the length of the composition `C`.\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The product of the Essential quasi-symmetric functions indexed\n by ``I`` and ``J``, expressed in the Essential basis.\n\n EXAMPLES::\n\n sage: E = QuasiSymmetricFunctions(QQ).E()\n sage: c1 = Composition([2])\n sage: c2 = Composition([1,3])\n sage: E.product_on_basis(c1, c2)\n E[1, 2, 3] + E[1, 3, 2] - E[1, 5] + E[2, 1, 3] - E[3, 3]\n sage: E.product_on_basis(c1, Composition([]))\n E[2]\n sage: E.product_on_basis(c1, Composition([3]))\n E[2, 3] + E[3, 2] - E[5]\n\n TESTS::\n\n sage: E = QuasiSymmetricFunctions(QQ).E()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all(E(M(E[cp])*M(E[c])) == E[cp]*E[c] # long time\n ....: for c in Compositions(3) for cp in Compositions(5))\n True\n '
n = (len(I) + len(J))
return self.sum_of_terms(((K, ((- 1) ** (n - len(K)))) for K in I.shuffle_product(J, overlap=True)))
E = Essential
class Quasisymmetric_Schur(CombinatorialFreeModule, BindableClass):
"\n The Hopf algebra of quasi-symmetric function in the Quasisymmetric\n Schur basis.\n\n The basis of Quasisymmetric Schur functions is defined in [QSCHUR]_\n and in Definition 5.1.1 of [LMvW13]_.\n Don't mistake them for the completely unrelated quasi-Schur\n functions of [NCSF1]_!\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QS = QSym.QS()\n sage: F = QSym.F()\n sage: M = QSym.M()\n sage: F(QS[1,2])\n F[1, 2]\n sage: M(QS[1,2])\n M[1, 1, 1] + M[1, 2]\n sage: s = SymmetricFunctions(QQ).s()\n sage: QS(s[2,1,1])\n QS[1, 1, 2] + QS[1, 2, 1] + QS[2, 1, 1]\n "
def __init__(self, QSym):
'\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: F = QSym.Fundamental()\n sage: QS = QSym.Quasisymmetric_Schur()\n sage: QS(F(QS.an_element())) == QS.an_element()\n True\n sage: F(QS(F.an_element())) == F.an_element()\n True\n sage: M = QSym.Monomial()\n sage: QS(M(QS.an_element())) == QS.an_element()\n True\n sage: M(QS(M.an_element())) == M.an_element()\n True\n sage: TestSuite(QS).run() # long time\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='QS', bracket=False, category=QSym.Bases())
def _realization_name(self):
"\n Return a nicer name for ``self`` than what is inherited\n from :mod:`sage.categories.sets_cat`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QS = QSym.QS()\n sage: QS._realization_name()\n 'Quasisymmetric Schur'\n "
return 'Quasisymmetric Schur'
@cached_method
def _from_monomial_transition_matrix(self, n):
'\n A matrix representing the transition coefficients to\n the complete basis and the ordering of compositions.\n\n INPUT:\n\n - ``n`` -- an integer\n\n OUTPUT:\n\n - a pair of a square matrix and the ordered list of compositions\n\n EXAMPLES::\n\n sage: QS = QuasiSymmetricFunctions(QQ).QS()\n sage: QS._from_monomial_transition_matrix(4)[0]\n [ 1 -1 -1 0 1 1 1 -1]\n [ 0 1 0 0 -1 -1 0 1]\n [ 0 0 1 -1 0 0 -1 1]\n [ 0 0 0 1 -1 -1 -1 1]\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 '
if (n == 0):
return (matrix([[]]), [])
CO = compositions_order(n)
from sage.rings.integer_ring import ZZ
MS = MatrixSpace(ZZ, len(CO))
M = MS([[number_of_SSRCT(al, be) for al in CO] for be in CO])
return (M.inverse_of_unit(), CO)
@cached_method
def _from_monomial_on_basis(self, comp):
'\n Maps the Monomial quasi-symmetric function indexed by\n ``comp`` to the Quasisymmetric Schur basis.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Quasisymmetric Schur basis\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QS = QSym.QS()\n sage: M = QSym.M()\n sage: QS._from_monomial_on_basis(Composition([1,3,1]))\n QS[1, 1, 1, 1, 1] - QS[1, 1, 2, 1] + QS[1, 3, 1] - QS[2, 2, 1]\n sage: QS._from_monomial_on_basis(Composition([2]))\n -QS[1, 1] + QS[2]\n '
comp = Composition(comp)
if (not comp._list):
return self.one()
(T, comps) = self._from_monomial_transition_matrix(comp.size())
i = comps.index(comp)
return self._from_dict({c: T[(i, j)] for (j, c) in enumerate(comps) if (T[(i, j)] != 0)}, remove_zeros=False)
@cached_method
def _to_monomial_on_basis(self, comp_shape):
'\n Expand the quasi-symmetric Schur function in the Monomial basis.\n\n The expansion of the quasi-symmetric Schur function indexed\n by ``comp_shape`` has coefficients which are given by the method\n :meth:`~sage.combinat.ncsf_qsym.combinatorics.number_of_SSRCT`.\n\n INPUT:\n\n - ``comp_shape`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Monomial basis\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QS = QSym.QS()\n sage: QS._to_monomial_on_basis(Composition([1,3,1]))\n 2*M[1, 1, 1, 1, 1] + 2*M[1, 1, 2, 1] + M[1, 2, 1, 1] + M[1, 3, 1] + M[2, 1, 1, 1] + M[2, 2, 1]\n '
M = self.realization_of().Monomial()
if (not comp_shape):
return M([])
return M.sum_of_terms(((comp_content, number_of_SSRCT(comp_content, comp_shape)) for comp_content in Compositions(sum(comp_shape))), distinct=True)
def dual(self):
'\n The dual basis to the Quasisymmetric Schur basis.\n\n The dual basis to the Quasisymmetric Schur basis is\n implemented as dual.\n\n OUTPUT:\n\n - the dual Quasisymmetric Schur basis of the\n non-commutative symmetric functions\n\n EXAMPLES::\n\n sage: QS = QuasiSymmetricFunctions(QQ).Quasisymmetric_Schur()\n sage: QS.dual()\n Non-Commutative Symmetric Functions over the Rational Field\n in the dual Quasisymmetric-Schur basis\n '
return self.realization_of().dual().dualQuasisymmetric_Schur()
QS = Quasisymmetric_Schur
class Young_Quasisymmetric_Schur(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric functions in the Young\n Quasisymmetric Schur basis.\n\n The basis of Young Quasisymmetric Schur functions is from\n Definition 5.2.1 of [LMvW13]_.\n\n This basis is related to the Quasisymmetric Schur basis ``QS`` by\n ``QS(alpha.reversed()) == YQS(alpha).star_involution()`` .\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: YQS = QSym.YQS()\n sage: F = QSym.F()\n sage: QS = QSym.QS()\n sage: F(YQS[1,2])\n F[1, 2]\n sage: all(QS(al.reversed())==YQS(al).star_involution() for al in Compositions(5))\n True\n sage: s = SymmetricFunctions(QQ).s()\n sage: YQS(s[2,1,1])\n YQS[1, 1, 2] + YQS[1, 2, 1] + YQS[2, 1, 1]\n '
def __init__(self, QSym):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: F = QSym.Fundamental()\n sage: YQS = QSym.Young_Quasisymmetric_Schur()\n sage: YQS(F(YQS.an_element())) == YQS.an_element()\n True\n sage: F(YQS(F.an_element())) == F.an_element()\n True\n sage: M = QSym.Monomial()\n sage: YQS(M(YQS.an_element())) == YQS.an_element()\n True\n sage: M(YQS(M.an_element())) == M.an_element()\n True\n sage: TestSuite(YQS).run() # long time\n '
self._QS = QSym.QS()
self._M = QSym.M()
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='YQS', bracket=False, category=QSym.Bases())
self.module_morphism(self._to_monomial_on_basis, codomain=self._M, category=QSym.Bases()).register_as_coercion()
self._M.module_morphism(self._from_monomial_on_basis, codomain=self, category=QSym.Bases()).register_as_coercion()
def _realization_name(self):
"\n Return a nicer name for ``self`` than what is inherited\n from :mod:`sage.categories.sets_cat`.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: QS = QSym.QS()\n sage: QS._realization_name()\n 'Quasisymmetric Schur'\n "
return 'Young Quasisymmetric Schur'
@cached_method
def _to_monomial_on_basis(self, comp):
'\n Expand the Young quasi-symmetric Schur function in the\n Monomial basis.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Monomial basis\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: YQS = QSym.QS()\n sage: YQS._to_monomial_on_basis(Composition([2]))\n M[1, 1] + M[2]\n sage: YQS._to_monomial_on_basis(Composition([1,3,1]))\n 2*M[1, 1, 1, 1, 1] + 2*M[1, 1, 2, 1] + M[1, 2, 1, 1] + M[1, 3, 1] + M[2, 1, 1, 1] + M[2, 2, 1]\n '
return self._M(self._QS.monomial(comp.reversed())).star_involution()
@cached_method
def _from_monomial_on_basis(self, comp):
'\n The expansion of the quasi-symmetric Schur function indexed\n by ``comp_shape`` has coefficients which are given by the method\n :meth:`~sage.combinat.ncsf_qsym.combinatorics.number_of_SSRCT`.\n\n INPUT:\n\n - ``comp`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Young Quasisymmetric Schur basis\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: YQS = QSym.YQS()\n sage: YQS._from_monomial_on_basis(Composition([2]))\n -YQS[1, 1] + YQS[2]\n sage: YQS._from_monomial_on_basis(Composition([1,3,1]))\n YQS[1, 1, 1, 1, 1] - YQS[1, 2, 1, 1] - YQS[1, 2, 2] + YQS[1, 3, 1]\n '
elt = self._QS(self._M.monomial(comp.reversed()))
return self._from_dict({al.reversed(): c for (al, c) in elt}, coerce=False, remove_zeros=False)
YQS = Young_Quasisymmetric_Schur
class dualImmaculate(CombinatorialFreeModule, BindableClass):
def __init__(self, QSym):
'\n The dual immaculate basis of the quasi-symmetric functions.\n\n This basis first appears in [BBSSZ2012]_.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: dI = QSym.dI()\n sage: dI([1,3,2])*dI([1]) # long time (6s on sage.math, 2013)\n dI[1, 1, 3, 2] + dI[2, 3, 2]\n sage: dI([1,3])*dI([1,1])\n dI[1, 1, 1, 3] + dI[1, 1, 4] + dI[1, 2, 3] - dI[1, 3, 2] - dI[1, 4, 1] - dI[1, 5] + dI[2, 3, 1] + dI[2, 4]\n sage: dI([3,1])*dI([2,1]) # long time (7s on sage.math, 2013)\n dI[1, 1, 5] - dI[1, 4, 1, 1] - dI[1, 4, 2] - 2*dI[1, 5, 1] - dI[1, 6] - dI[2, 4, 1] - dI[2, 5] - dI[3, 1, 3] + dI[3, 2, 1, 1] + dI[3, 2, 2] + dI[3, 3, 1] + dI[4, 1, 1, 1] + 2*dI[4, 2, 1] + dI[4, 3] + dI[5, 1, 1] + dI[5, 2]\n sage: F = QSym.F()\n sage: dI(F[1,3,1])\n -dI[1, 1, 1, 2] + dI[1, 1, 2, 1] - dI[1, 2, 2] + dI[1, 3, 1]\n sage: F(dI(F([2,1,3])))\n F[2, 1, 3]\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='dI', bracket=False, category=QSym.Bases())
def _to_Monomial_on_basis(self, J):
'\n Expand the dual immaculate function labelled by a composition\n ``J`` in the quasi-symmetric monomial basis.\n\n INPUT:\n\n - ``J`` -- a composition\n\n OUTPUT:\n\n - A quasi-symmetric function in the monomial basis.\n\n EXAMPLES::\n\n sage: dI = QuasiSymmetricFunctions(QQ).dI()\n sage: dI._to_Monomial_on_basis(Composition([1,3]))\n M[1, 1, 1, 1] + M[1, 1, 2] + M[1, 2, 1] + M[1, 3]\n sage: dI._to_Monomial_on_basis(Composition([]))\n M[]\n sage: dI._to_Monomial_on_basis(Composition([2,1,2]))\n 4*M[1, 1, 1, 1, 1] + 3*M[1, 1, 1, 2] + 2*M[1, 1, 2, 1] + M[1, 1, 3] + M[1, 2, 1, 1] + M[1, 2, 2] + M[2, 1, 1, 1] + M[2, 1, 2]\n '
M = self.realization_of().Monomial()
if (not J._list):
return M([])
C = Compositions()
C_size = Compositions(J.size())
return M.sum_of_terms(((C(I), number_of_fCT(C(I), J)) for I in C_size), distinct=True)
@cached_method
def _matrix_monomial_to_dual_immaculate(self, n):
'\n This function caches the change of basis matrix from the\n quasisymmetric monomial basis to the dual immaculate basis.\n\n INPUT:\n\n - ``J`` -- a composition\n\n OUTPUT:\n\n - A list. Each entry in the list is a row in the\n change-of-basis matrix.\n\n EXAMPLES::\n\n sage: dI = QuasiSymmetricFunctions(QQ).dI()\n sage: dI._matrix_monomial_to_dual_immaculate(3)\n [[1, -1, -1, 1], [0, 1, -1, 0], [0, 0, 1, -1], [0, 0, 0, 1]]\n sage: dI._matrix_monomial_to_dual_immaculate(0)\n [[1]]\n '
N = NonCommutativeSymmetricFunctions(self.base_ring())
I = N.I()
S = N.S()
mat = []
C = Compositions()
C_n = Compositions(n)
for alp in C_n:
row = []
expansion = S(I(C(alp)))
for bet in C_n:
row.append(expansion.coefficient(C(bet)))
mat.append(row)
return mat
def _from_Monomial_on_basis(self, J):
'\n Expand the monomial quasi-symmetric function labelled by the\n composition ``J`` in the dual immaculate basis.\n\n INPUT:\n\n - ``J`` -- a composition\n\n OUTPUT:\n\n - A quasi-symmetric function in the dual immaculate basis.\n\n EXAMPLES::\n\n sage: dI = QuasiSymmetricFunctions(QQ).dI()\n sage: dI._from_Monomial_on_basis(Composition([]))\n dI[]\n sage: dI._from_Monomial_on_basis(Composition([2,1]))\n -dI[1, 1, 1] - dI[1, 2] + dI[2, 1]\n sage: dI._from_Monomial_on_basis(Composition([3,1,2]))\n -dI[1, 1, 1, 1, 1, 1] + dI[1, 1, 1, 1, 2] + dI[1, 1, 1, 3] - dI[1, 1, 4] - dI[1, 2, 1, 1, 1] + dI[1, 2, 3] + dI[2, 1, 1, 1, 1] - dI[2, 1, 1, 2] + dI[2, 2, 1, 1] - dI[2, 2, 2] - dI[3, 1, 1, 1] + dI[3, 1, 2]\n '
n = J.size()
C = Compositions()
C_n = Compositions(n)
mat = self._matrix_monomial_to_dual_immaculate(n)
column = C_n.list().index(J)
return self.sum_of_terms(((C(I), mat[C_n.list().index(I)][column]) for I in C_n), distinct=True)
dI = dualImmaculate
class HazewinkelLambda(CombinatorialFreeModule, BindableClass):
'\n The Hazewinkel lambda basis of the quasi-symmetric functions.\n\n This basis goes back to [Haz2004]_, albeit it is indexed in a\n different way here. It is a multiplicative basis in a weak\n sense of this word (the product of any two basis elements is a\n basis element, but of course not the one obtained by\n concatenating the indexing compositions).\n\n In [Haz2004]_, Hazewinkel showed that the `\\mathbf{k}`-algebra\n `\\mathrm{QSym}` is a polynomial algebra. (The proof is correct\n but rests upon an unproven claim that the lexicographically\n largest term of the `n`-th shuffle power of a Lyndon word is\n the `n`-fold concatenation of this Lyndon word with\n itself, occurring `n!` times in that shuffle power. But this\n can be deduced from Section 2 of [Rad1979]_. See also\n Chapter 6 of [GriRei18]_, specifically Theorem 6.5.13, for a\n complete proof.) More precisely, he showed that\n `\\mathrm{QSym}` is generated, as a free commutative\n `\\mathbf{k}`-algebra, by the elements `\\lambda^n(M_I)`, where\n `n` ranges over the positive integers, and `I` ranges over\n all compositions which are Lyndon words and whose entries\n have gcd `1`. Here, `\\lambda^n` denotes the `n`-th lambda\n operation as explained in\n :meth:`~sage.combinat.ncsf_qsym.qsym.QuasiSymmetricFunctions.Monomial.lambda_of_monomial`.\n\n Thus, products of these generators form a `\\mathbf{k}`-module\n basis of `\\mathrm{QSym}`. We index this basis by compositions\n here. More precisely, we define the Hazewinkel lambda basis\n `(\\mathrm{HWL}_I)_I` (with `I` ranging over all compositions)\n as follows:\n\n Let `I` be a composition. Let `I = I_1 I_2 \\ldots I_k` be the\n Chen-Fox-Lyndon factorization of `I` (see\n :meth:`~sage.combinat.words.finite_word.FiniteWord_class.lyndon_factorization`).\n For every `j \\in \\{1, 2, \\ldots , k\\}`, let `g_j` be the\n gcd of the entries of the Lyndon word `I_j`, and let `J_j` be\n the result of dividing the entries of `I_j` by this gcd. Then,\n `\\mathrm{HWL}_I` is defined to be\n `\\prod_{j=1}^{k} \\lambda^{g_j} (M_{J_j})`.\n\n .. TODO::\n\n The conversion from the M basis to the HWL basis is\n currently implemented in the naive way (inverting the\n base-change matrix in the other direction). This matrix\n is not triangular (not even after any permutations of\n the bases), and there could very well be a faster method\n (the one given by Hazewinkel?).\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ)\n sage: HWL = QSym.HazewinkelLambda()\n sage: M = QSym.M()\n sage: M(HWL([2]))\n M[1, 1]\n sage: M(HWL([1,1]))\n 2*M[1, 1] + M[2]\n sage: M(HWL([1,2]))\n M[1, 2]\n sage: M(HWL([2,1]))\n 3*M[1, 1, 1] + M[1, 2] + M[2, 1]\n sage: M(HWL(Composition([])))\n M[]\n sage: HWL(M([1,1]))\n HWL[2]\n sage: HWL(M(Composition([2])))\n HWL[1, 1] - 2*HWL[2]\n sage: HWL(M([1]))\n HWL[1]\n\n TESTS:\n\n Transforming from the M-basis into the HWL-basis and back\n returns us to where we started::\n\n sage: all( M(HWL(M[I])) == M[I] for I in Compositions(3) )\n True\n sage: all( HWL(M(HWL[I])) == HWL[I] for I in Compositions(4) )\n True\n\n Checking the HWL basis elements corresponding to Lyndon\n words::\n\n sage: all( M(HWL[Composition(I)])\n ....: == M.lambda_of_monomial([i // gcd(I) for i in I], gcd(I))\n ....: for I in LyndonWords(e=3, k=2) )\n True\n '
def __init__(self, QSym):
'\n TESTS::\n\n sage: HWL = QuasiSymmetricFunctions(QQ).HazewinkelLambda()\n sage: TestSuite(HWL).run()\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='HWL', bracket=False, category=QSym.Bases())
def __init_extra__(self):
'\n Set up caches for the transition maps to and from the monomial\n basis, and register them as coercions.\n\n TESTS::\n\n sage: HWL = QuasiSymmetricFunctions(QQ).HazewinkelLambda()\n sage: M = QuasiSymmetricFunctions(QQ).Monomial()\n sage: M2HWL = HWL.coerce_map_from(M); M2HWL\n Generic morphism:\n From: Quasisymmetric functions over the Rational Field in the Monomial basis\n To: Quasisymmetric functions over the Rational Field in the HazewinkelLambda basis\n sage: HWL2M = M.coerce_map_from(HWL); HWL2M\n Generic morphism:\n From: Quasisymmetric functions over the Rational Field in the HazewinkelLambda basis\n To: Quasisymmetric functions over the Rational Field in the Monomial basis\n sage: HWL2M(HWL[2])\n M[1, 1]\n sage: M2HWL(M[2])\n HWL[1, 1] - 2*HWL[2]\n '
M = self.realization_of().M()
category = self.realization_of()._category
M.module_morphism(self._from_Monomial_on_basis, codomain=self, category=category).register_as_coercion()
self.module_morphism(self._to_Monomial_on_basis, codomain=M, category=category).register_as_coercion()
self._M_to_self_cache = {}
self._M_from_self_cache = {}
self._M_transition_matrices = {}
self._M_inverse_transition_matrices = {}
def _precompute_cache(self, n, to_self_cache, from_self_cache, transition_matrices, inverse_transition_matrices, from_self_gen_function):
'\n Compute the transition matrices between ``self`` and the\n monomial basis in the homogeneous components of degree `n`.\n The results are not returned, but rather stored in the caches.\n\n This assumes that the transition matrices in all degrees smaller\n than `n` have already been computed and cached!\n\n INPUT:\n\n - ``n`` -- nonnegative integer\n - ``to_self_cache`` -- a cache which stores the coordinates of\n the elements of the monomial basis with respect to the\n basis ``self``\n - ``from_self_cache`` -- a cache which stores the coordinates\n of the elements of ``self`` with respect to the monomial\n basis\n - ``transition_matrices`` -- a cache for transition matrices\n which contain the coordinates of the elements of the monomial\n basis with respect to ``self``\n - ``inverse_transition_matrices`` -- a cache for transition\n matrices which contain the coordinates of the elements of\n ``self`` with respect to the monomial basis\n - ``from_self_gen_function`` -- a function which takes a\n Lyndon word `I` and returns the Hazewinkel Lambda basis\n element indexed by `I` expanded with respect to the\n monomial basis (as an element of the monomial basis, not as\n a dictionary)\n\n EXAMPLES:\n\n The examples below demonstrate how the caches are built\n step by step using the ``_precompute_cache`` method. In order\n not to influence the outcome of other doctests, we make sure\n not to use the caches internally used by this class, but\n rather to create new caches. This allows us to compute the\n transition matrices for a slight variation of the Hazewinkel\n Lambda basis, namely the basis whose `I`-th element is given\n by the simple formula `\\prod_{j=1}^{k} M_{I_j}` instead of\n `\\prod_{j=1}^{k} \\lambda^{g_j} (M_{J_j})`. We will see that\n this is only a `\\QQ`-basis rather than a `\\ZZ`-basis (a\n reason why the Ditters conjecture took so long to prove)::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: HWL = QSym.HazewinkelLambda()\n sage: M = QSym.M()\n sage: toy_to_self_cache = {}\n sage: toy_from_self_cache = {}\n sage: toy_transition_matrices = {}\n sage: toy_inverse_transition_matrices = {}\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(toy_to_self_cache)\n []\n sage: def toy_gen_function(I):\n ....: return M[I]\n sage: HWL._precompute_cache(0, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)])]\n sage: HWL._precompute_cache(1, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)])]\n sage: HWL._precompute_cache(2, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([1, 1], 1/2), ([2], -1/2)]), ([2], [([2], 1)])]\n sage: toy_transition_matrices[2]\n [ 1/2 -1/2]\n [ 0 1]\n sage: toy_inverse_transition_matrices[2]\n [2 1]\n [0 1]\n sage: sorted(toy_transition_matrices)\n [0, 1, 2]\n\n As we see from the fractions in the transition matrices, this\n is only a basis over `\\QQ`, not over `\\ZZ`.\n\n Let us try another variation on the definition of the basis:\n `\\prod_{j=1}^{k} \\lambda^{g_j} (M_{J_j})` will now be replaced\n by `\\prod_{j=1}^{k} M_{J_j^{g_j}}`, where `J_g` means the\n `g`-fold concatenation of the composition `J` with itself::\n\n sage: toy_to_self_cache = {}\n sage: toy_from_self_cache = {}\n sage: toy_transition_matrices = {}\n sage: toy_inverse_transition_matrices = {}\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(toy_to_self_cache)\n []\n sage: def toy_gen_function(I):\n ....: xs = [i // gcd(I) for i in I] * gcd(I)\n ....: return M[xs]\n sage: HWL._precompute_cache(0, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)])]\n sage: HWL._precompute_cache(1, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)])]\n sage: HWL._precompute_cache(2, toy_to_self_cache,\n ....: toy_from_self_cache,\n ....: toy_transition_matrices,\n ....: toy_inverse_transition_matrices,\n ....: toy_gen_function)\n sage: l(toy_to_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([2], 1)]), ([2], [([1, 1], 1), ([2], -2)])]\n\n This appears to form another `\\ZZ`-basis of\n `\\mathrm{QSym}`, but the appearance is deceiving: it\n fails to span the degree-`9` part of `\\mathrm{QSym}`.\n (The corresponding computation is not tested as it takes\n a few minutes.) We have not checked if it spans\n `\\mathrm{QSym}` over `\\QQ`.\n '
base_ring = self.base_ring()
zero = base_ring.zero()
if (n == 0):
part = self._indices([])
one = base_ring.one()
to_self_cache[part] = {part: one}
from_self_cache[part] = {part: one}
transition_matrices[n] = matrix(base_ring, [[one]])
inverse_transition_matrices[n] = matrix(base_ring, [[one]])
return
compositions_n = Compositions(n).list()
len_compositions_n = (2 ** (n - 1))
M = self.realization_of().M()
transition_matrix_n = matrix(base_ring, len_compositions_n, len_compositions_n)
i = 0
for I in compositions_n:
M_coeffs = {}
self_I_in_M_basis = M.prod([from_self_gen_function(self._indices(list(J))) for J in Word(I).lyndon_factorization()])
j = 0
for J in compositions_n:
if (J in self_I_in_M_basis._monomial_coefficients):
sp = self_I_in_M_basis._monomial_coefficients[J]
M_coeffs[J] = sp
transition_matrix_n[(i, j)] = sp
j += 1
from_self_cache[I] = M_coeffs
i += 1
inverse_transition_matrices[n] = transition_matrix_n
inverse_transition = (~ transition_matrix_n).change_ring(base_ring)
for i in range(len_compositions_n):
self_coeffs = {}
for j in range(len_compositions_n):
if (inverse_transition[(i, j)] != zero):
self_coeffs[compositions_n[j]] = inverse_transition[(i, j)]
to_self_cache[compositions_n[i]] = self_coeffs
transition_matrices[n] = inverse_transition
def _precompute_M(self, n):
"\n Compute the transition matrices between ``self`` and the\n monomial basis in the homogeneous components of degree `n`\n (and in those of smaller degree, if not already computed).\n The result is not returned, but rather stored in the cache.\n\n INPUT:\n\n - ``n`` -- nonnegative integer\n\n EXAMPLES:\n\n The examples below demonstrate how the caches of ``self`` are\n built step by step using the ``_precompute_M`` method. This\n demonstration relies on an untouched Hazewinkel Lambda basis\n (because any computations might have filled the cache already).\n We obtain such a basis by choosing a ground ring unlikely to\n appear elsewhere::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ['hell', 'yeah'])\n sage: HWL = QSym.HazewinkelLambda()\n sage: M = QSym.M()\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(HWL._M_to_self_cache)\n []\n sage: HWL._precompute_M(0)\n sage: l(HWL._M_to_self_cache)\n [([], [([], 1)])]\n sage: HWL._precompute_M(1)\n sage: l(HWL._M_to_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)])]\n sage: HWL._precompute_M(2)\n sage: l(HWL._M_to_self_cache)\n [([], [([], 1)]),\n ([1], [([1], 1)]),\n ([1, 1], [([2], 1)]),\n ([2], [([1, 1], 1), ([2], -2)])]\n sage: HWL._M_transition_matrices[2]\n [ 0 1]\n [ 1 -2]\n sage: HWL._M_inverse_transition_matrices[2]\n [2 1]\n [1 0]\n sage: sorted(HWL._M_transition_matrices)\n [0, 1, 2]\n\n We did not have to call ``HWL._precompute_M(0)``,\n ``HWL._precompute_M(1)`` and ``HWL._precompute_M(2)``\n in this order; it would be enough to just call\n ``HWL._precompute_M(2)``::\n\n sage: QSym = QuasiSymmetricFunctions(ZZ['lol', 'wut'])\n sage: HWL = QSym.HazewinkelLambda()\n sage: M = QSym.M()\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(HWL._M_to_self_cache)\n []\n sage: HWL._precompute_M(2)\n sage: l(HWL._M_to_self_cache)\n [([], [([], 1)]),\n ([1], [([1], 1)]),\n ([1, 1], [([2], 1)]),\n ([2], [([1, 1], 1), ([2], -2)])]\n sage: HWL._precompute_M(1)\n sage: l(HWL._M_to_self_cache)\n [([], [([], 1)]),\n ([1], [([1], 1)]),\n ([1, 1], [([2], 1)]),\n ([2], [([1, 1], 1), ([2], -2)])]\n "
l = len(self._M_transition_matrices)
M = self.realization_of().M()
if (l <= n):
from sage.misc.cachefunc import cached_function
from sage.arith.misc import gcd
@cached_function
def monolambda(I):
g = gcd(I)
I_reduced = [(i // g) for i in I]
return M.lambda_of_monomial(I_reduced, g)
for i in range(l, (n + 1)):
self._precompute_cache(i, self._M_to_self_cache, self._M_from_self_cache, self._M_transition_matrices, self._M_inverse_transition_matrices, monolambda)
def _to_Monomial_on_basis(self, J):
'\n Expand the Hazewinkel Lambda basis element labelled by a\n composition ``J`` in the quasi-symmetric Monomial basis.\n\n INPUT:\n\n - ``J`` -- a composition\n\n OUTPUT:\n\n - A quasi-symmetric function in the Monomial basis.\n\n EXAMPLES::\n\n sage: HWL = QuasiSymmetricFunctions(QQ).HazewinkelLambda()\n sage: J = Composition([1, 2, 1])\n sage: HWL._to_Monomial_on_basis(J)\n 2*M[1, 1, 2] + M[1, 2, 1] + M[1, 3] + M[2, 2]\n '
n = sum(J)
self._precompute_M(n)
return self.realization_of().M()._from_dict(self._M_from_self_cache[J])
def _from_Monomial_on_basis(self, J):
'\n Expand the Monomial quasi-symmetric function labelled by the\n composition ``J`` in the Hazewinkel Lambda basis.\n\n INPUT:\n\n - ``J`` -- a composition\n\n OUTPUT:\n\n - A quasi-symmetric function in the Hazewinkel lambda basis.\n\n EXAMPLES::\n\n sage: HWL = QuasiSymmetricFunctions(QQ).HazewinkelLambda()\n sage: J = Composition([1, 2, 1])\n sage: HWL._from_Monomial_on_basis(J)\n -2*HWL[1, 1, 2] + HWL[1, 2, 1] - HWL[1, 3] - HWL[2, 2] + 2*HWL[3, 1] - 2*HWL[4]\n '
n = sum(J)
self._precompute_M(n)
return self._from_dict(self._M_to_self_cache[J])
def product_on_basis(self, I, J):
'\n The product on Hazewinkel Lambda basis elements.\n\n The product of the basis elements indexed by two compositions\n `I` and `J` is the basis element obtained by concatenating the\n Lyndon factorizations of the words `I` and `J`, then reordering\n the Lyndon factors in nonincreasing order, and finally\n concatenating them in this order (giving a new composition).\n\n INPUT:\n\n - ``I``, ``J`` -- compositions\n\n OUTPUT:\n\n - The product of the Hazewinkel Lambda quasi-symmetric\n functions indexed by ``I`` and ``J``, expressed in the\n Hazewinkel Lambda basis.\n\n EXAMPLES::\n\n sage: HWL = QuasiSymmetricFunctions(QQ).HazewinkelLambda()\n sage: c1 = Composition([1, 2, 1])\n sage: c2 = Composition([2, 1, 3, 2])\n sage: HWL.product_on_basis(c1, c2)\n HWL[2, 1, 3, 2, 1, 2, 1]\n sage: HWL.product_on_basis(c1, Composition([]))\n HWL[1, 2, 1]\n sage: HWL.product_on_basis(Composition([]), Composition([]))\n HWL[]\n\n TESTS::\n\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all( all( M(HWL[I] * HWL[J]) == M(HWL[I]) * M(HWL[J]) # long time\n ....: for I in Compositions(3) )\n ....: for J in Compositions(3) )\n True\n '
from sage.misc.flatten import flatten
I_factors = [list(i) for i in Word(I).lyndon_factorization()]
J_factors = [list(j) for j in Word(J).lyndon_factorization()]
new_factors = sorted((I_factors + J_factors), reverse=True)
return self.monomial(self._indices(flatten(new_factors)))
class psi(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric functions in the `\\psi` basis.\n\n The `\\psi` basis is defined as a rescaled Hopf dual of the `\\Psi`\n basis of the non-commutative symmetric functions (see Section 3.1\n of [BDHMN2017]_), where the pairing is\n\n .. MATH::\n\n (\\psi_I, \\Psi_J) = z_I \\delta_{I,J},\n\n where `z_I = 1^{m_1} m_1! 2^{m_2} m_2! \\cdots` with `m_i` being the\n multiplicity of `i` in the composition `I`. Therefore, we call these\n the *quasi-symmetric power sums of the first kind*.\n\n Using the duality, we can directly define the `\\psi` basis by\n\n .. MATH::\n\n \\psi_I = \\sum_{J \\succ I} z_I / \\pi_{I,J} M_J,\n\n where `\\pi_{I,J}` is as defined in [NCSF]_.\n\n The `\\psi`-basis is well-defined only when the base ring is a\n `\\QQ`-algebra.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: psi = QSym.psi(); psi\n Quasisymmetric functions over the Rational Field in the psi basis\n sage: psi.an_element()\n 2*psi[] + 2*psi[1] + 3*psi[1, 1]\n sage: p = SymmetricFunctions(QQ).p()\n sage: psi(p[2,2,1])\n psi[1, 2, 2] + psi[2, 1, 2] + psi[2, 2, 1]\n sage: all(sum(psi(list(al)) for al in Permutations(la))==psi(p(la)) for la in Partitions(6))\n True\n sage: p = SymmetricFunctions(QQ).p()\n sage: psi(p[3,2,2])\n psi[2, 2, 3] + psi[2, 3, 2] + psi[3, 2, 2]\n\n Checking the equivalent definition of `\\psi_n`::\n\n sage: def test_psi(n):\n ....: psi = QuasiSymmetricFunctions(QQ).psi()\n ....: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()\n ....: M = matrix([[psi[I].duality_pairing(Psi[J])\n ....: for I in Compositions(n)]\n ....: for J in Compositions(n)])\n ....: def z(J): return J.to_partition().centralizer_size()\n ....: return M == matrix.diagonal([z(I) for I in Compositions(n)])\n sage: all(test_psi(k) for k in range(1,5))\n True\n '
def __init__(self, QSym):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: psi = QuasiSymmetricFunctions(QQ).psi()\n sage: TestSuite(psi).run()\n\n TESTS::\n\n sage: psi = QuasiSymmetricFunctions(QQ).psi()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all(psi(M(psi[c])) == psi[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n sage: all(M(psi(M[c])) == M[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='psi', bracket=False, category=QSym.Bases())
category = self.realization_of()._category
Monomial = self.realization_of().Monomial()
self.module_morphism(self._to_Monomial_on_basis, codomain=Monomial, category=category).register_as_coercion()
Monomial.module_morphism(self._from_Monomial_on_basis, codomain=self, category=category).register_as_coercion()
def _from_Monomial_on_basis(self, I):
'\n Expand a Monomial basis element indexed by ``I`` in the\n `\\psi` basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the `\\psi` basis\n\n TESTS::\n\n sage: psi = QuasiSymmetricFunctions(QQ).psi()\n sage: I = Composition([2, 3, 2])\n sage: psi._from_Monomial_on_basis(I)\n 1/2*psi[2, 3, 2] - 2/5*psi[2, 5] - 3/5*psi[5, 2] + 2/7*psi[7]\n '
R = self.base_ring()
minus_one = (- R.one())
def z(J):
return R(J.to_partition().centralizer_size())
return self._from_dict({J: (((minus_one ** (len(I) - len(J))) / z(J)) * coeff_lp(I, J)) for J in I.fatter()})
def _to_Monomial_on_basis(self, I):
'\n Expand a `\\psi` basis element indexed by ``I`` in the\n Monomial basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Monomial basis\n\n TESTS::\n\n sage: psi = QuasiSymmetricFunctions(QQ).psi()\n sage: I = Composition([2, 3, 2])\n sage: psi._to_Monomial_on_basis(I)\n 2*M[2, 3, 2] + 4/5*M[2, 5] + 6/5*M[5, 2] + 12/35*M[7]\n '
R = self.base_ring()
z = R(I.to_partition().centralizer_size())
Monomial = self.realization_of().Monomial()
return Monomial._from_dict({J: (z / coeff_pi(I, J)) for J in I.fatter()})
class phi(CombinatorialFreeModule, BindableClass):
'\n The Hopf algebra of quasi-symmetric functions in the `\\phi` basis.\n\n The `\\phi` basis is defined as a rescaled Hopf dual of the `\\Phi`\n basis of the non-commutative symmetric functions (see Section 3.1\n of [BDHMN2017]_), where the pairing is\n\n .. MATH::\n\n (\\phi_I, \\Phi_J) = z_I \\delta_{I,J},\n\n where `z_I = 1^{m_1} m_1! 2^{m_2} m_2! \\cdots` with `m_i` being the\n multiplicity of `i` in the composition `I`. Therefore, we call these\n the *quasi-symmetric power sums of the second kind*.\n\n Using the duality, we can directly define the `\\phi` basis by\n\n .. MATH::\n\n \\phi_I = \\sum_{J \\succ I} z_I / sp_{I,J} M_J,\n\n where `sp_{I,J}` is as defined in [NCSF]_.\n\n The `\\phi`-basis is well-defined only when the base ring is a\n `\\QQ`-algebra.\n\n EXAMPLES::\n\n sage: QSym = QuasiSymmetricFunctions(QQ)\n sage: phi = QSym.phi(); phi\n Quasisymmetric functions over the Rational Field in the phi basis\n sage: phi.an_element()\n 2*phi[] + 2*phi[1] + 3*phi[1, 1]\n sage: p = SymmetricFunctions(QQ).p()\n sage: phi(p[2,2,1])\n phi[1, 2, 2] + phi[2, 1, 2] + phi[2, 2, 1]\n sage: all(sum(phi(list(al)) for al in Permutations(la))==phi(p(la)) for la in Partitions(6))\n True\n sage: p = SymmetricFunctions(QQ).p()\n sage: phi(p[3,2,2])\n phi[2, 2, 3] + phi[2, 3, 2] + phi[3, 2, 2]\n\n Checking the equivalent definition of `\\phi_n`::\n\n sage: def test_phi(n):\n ....: phi = QuasiSymmetricFunctions(QQ).phi()\n ....: Phi = NonCommutativeSymmetricFunctions(QQ).Phi()\n ....: M = matrix([[phi[I].duality_pairing(Phi[J])\n ....: for I in Compositions(n)]\n ....: for J in Compositions(n)])\n ....: def z(J): return J.to_partition().centralizer_size()\n ....: return M == matrix.diagonal([z(I) for I in Compositions(n)])\n sage: all(test_phi(k) for k in range(1,5))\n True\n '
def __init__(self, QSym):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: phi = QuasiSymmetricFunctions(QQ).phi()\n sage: TestSuite(phi).run()\n\n TESTS::\n\n sage: phi = QuasiSymmetricFunctions(QQ).phi()\n sage: M = QuasiSymmetricFunctions(QQ).M()\n sage: all(phi(M(phi[c])) == phi[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n sage: all(M(phi(M[c])) == M[c] for n in range(5)\n ....: for c in Compositions(n))\n True\n '
CombinatorialFreeModule.__init__(self, QSym.base_ring(), Compositions(), prefix='phi', bracket=False, category=QSym.Bases())
category = self.realization_of()._category
Monomial = self.realization_of().Monomial()
self.module_morphism(self._to_Monomial_on_basis, codomain=Monomial, category=category).register_as_coercion()
Monomial.module_morphism(self._from_Monomial_on_basis, codomain=self, category=category).register_as_coercion()
def _from_Monomial_on_basis(self, I):
'\n Expand a Monomial basis element indexed by ``I`` in the\n `\\phi` basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the `\\psi` basis\n\n TESTS::\n\n sage: phi = QuasiSymmetricFunctions(QQ).phi()\n sage: I = Composition([3, 2, 2])\n sage: phi._from_Monomial_on_basis(I)\n 1/2*phi[3, 2, 2] - 1/2*phi[3, 4] - 1/2*phi[5, 2] + 1/3*phi[7]\n '
R = self.base_ring()
minus_one = (- R.one())
def z(J):
return R(J.to_partition().centralizer_size())
return self._from_dict({J: (((minus_one ** (len(I) - len(J))) * R.prod(J)) / (coeff_ell(I, J) * z(J))) for J in I.fatter()})
def _to_Monomial_on_basis(self, I):
'\n Expand a `\\phi` basis element indexed by ``I`` in the\n Monomial basis.\n\n INPUT:\n\n - ``I`` -- a composition\n\n OUTPUT:\n\n - a quasi-symmetric function in the Monomial basis\n\n TESTS::\n\n sage: phi = QuasiSymmetricFunctions(QQ).phi()\n sage: I = Composition([3, 2, 2])\n sage: phi._to_Monomial_on_basis(I)\n 2*M[3, 2, 2] + M[3, 4] + M[5, 2] + 1/3*M[7]\n '
R = self.base_ring()
z = R(I.to_partition().centralizer_size())
Monomial = self.realization_of().Monomial()
return Monomial._from_dict({J: (z / coeff_sp(I, J)) for J in I.fatter()})
|
class NCSymBasis_abstract(CombinatorialFreeModule, BindableClass):
'\n Abstract base class for a basis of `NCSym` or its dual.\n '
def _element_constructor_(self, x):
'\n Construct an element of ``self``.\n\n INPUT:\n\n - ``x`` -- a set partition or list of lists of integers\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m([[1,3],[2]])\n m{{1, 3}, {2}}\n sage: m(SetPartition([[1,3],[2]]))\n m{{1, 3}, {2}}\n '
if isinstance(x, (list, tuple)):
x = SetPartition(x)
return super()._element_constructor_(x)
|
class NCSymOrNCSymDualBases(Category_realization_of_parent):
'\n Base category for the category of bases of symmetric functions\n in non-commuting variables or its Hopf dual for the common code.\n '
def super_categories(self):
'\n Return the super categories of bases of (the Hopf dual of) the\n symmetric functions in non-commuting variables.\n\n OUTPUT:\n\n - a list of categories\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymOrNCSymDualBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymOrNCSymDualBases(NCSym).super_categories()\n [Category of realizations of Symmetric functions in\n non-commuting variables over the Rational Field,\n Category of graded Hopf algebras with basis over Rational Field,\n Join of Category of realizations of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of graded coalgebras over Rational Field]\n '
R = self.base().base_ring()
from sage.categories.graded_hopf_algebras_with_basis import GradedHopfAlgebrasWithBasis
return [self.base().Realizations(), GradedHopfAlgebrasWithBasis(R), GradedHopfAlgebras(R).Realizations()]
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymOrNCSymDualBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymOrNCSymDualBases(NCSym)\n Category of bases of NCSym or NCSym^* over the Rational Field\n '
return 'Category of bases of NCSym or NCSym^* over the {}'.format(self.base().base_ring())
class ParentMethods():
def _repr_(self):
"\n TESTS::\n\n sage: SymmetricFunctionsNonCommutingVariables(QQ).m()\n Symmetric functions in non-commuting variables over the Rational Field in the monomial basis\n sage: SymmetricFunctionsNonCommutingVariables(QQ).m().dual_basis()\n Dual symmetric functions in non-commuting variables over the Rational Field in the w basis\n sage: SymmetricFunctionsNonCommutingVariables(QQ).chi()\n Symmetric functions in non-commuting variables over the Rational Field in the\n supercharacter basis with parameter q=2\n sage: SymmetricFunctionsNonCommutingVariables(QQ['q'].fraction_field()).rho('q')\n Symmetric functions in non-commuting variables over the Fraction Field\n of Univariate Polynomial Ring in q over Rational Field in the\n deformed_coarse_powersum basis with parameter q\n "
str = '{} in the {} basis'.format(self.realization_of(), self._realization_name())
if hasattr(self, '_q'):
str += ' with parameter q'
if (repr(self._q) != 'q'):
str += ('=' + repr(self._q))
return str
def __getitem__(self, i):
'\n Return the basis element indexed by ``i``.\n\n INPUT:\n\n - ``i`` -- a set partition or a list of list of integers\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w[[1], [2,3]]\n w{{1}, {2, 3}}\n sage: w[{1}, (2,3)]\n w{{1}, {2, 3}}\n sage: w[[]]\n w{}\n '
if isinstance(i, SetPartition):
return self.monomial(i)
if (i == []):
return self.one()
if (not isinstance(i, tuple)):
i = (i,)
return self.monomial(SetPartition(i))
@cached_method
def one_basis(self):
'\n Return the index of the basis element containing `1`.\n\n OUTPUT:\n\n - The empty set partition\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m.one_basis()\n {}\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.one_basis()\n {}\n '
return SetPartition([])
def counit_on_basis(self, A):
'\n The counit is defined by sending all elements of positive degree\n to zero.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - either the ``0`` or the ``1`` of the base ring of ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m.counit_on_basis(SetPartition([[1,3], [2]]))\n 0\n sage: m.counit_on_basis(SetPartition([]))\n 1\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.counit_on_basis(SetPartition([[1,3], [2]]))\n 0\n sage: w.counit_on_basis(SetPartition([]))\n 1\n '
if (len(A) != 0):
return self.base_ring().zero()
return self.base_ring().one()
def duality_pairing(self, x, y):
'\n Compute the pairing between an element of ``self`` and an element\n of the dual.\n\n Carry out this computation by converting ``x`` to the `\\mathbf{m}`\n basis and ``y`` to the `\\mathbf{w}` basis.\n\n INPUT:\n\n - ``x`` -- an element of symmetric functions in non-commuting\n variables\n - ``y`` -- an element of the dual of symmetric functions in\n non-commuting variables\n\n OUTPUT:\n\n - an element of the base ring of ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: w = NCSym.m().dual_basis()\n sage: matrix([[h(A).duality_pairing(w(B)) for A in SetPartitions(3)] for B in SetPartitions(3)])\n [6 2 2 2 1]\n [2 2 1 1 1]\n [2 1 2 1 1]\n [2 1 1 2 1]\n [1 1 1 1 1]\n sage: (h[[1,2],[3]] + 3*h[[1,3],[2]]).duality_pairing(2*w[[1,3],[2]] + w[[1,2,3]] + 2*w[[1,2],[3]])\n 32\n '
m = self.realization_of().m()
x = m(x)
y = m.dual_basis()(y)
return sum(((coeff * y[I]) for (I, coeff) in x))
def duality_pairing_matrix(self, basis, degree):
'\n The matrix of scalar products between elements of `NCSym` and\n elements of `NCSym^*`.\n\n INPUT:\n\n - ``basis`` -- a basis of the dual Hopf algebra\n - ``degree`` -- a non-negative integer\n\n OUTPUT:\n\n - the matrix of scalar products between the basis ``self`` and the\n basis ``basis`` in the dual Hopf algebra of degree ``degree``\n\n EXAMPLES:\n\n The matrix between the `\\mathbf{m}` basis and the\n `\\mathbf{w}` basis::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: w = NCSym.dual().w()\n sage: m.duality_pairing_matrix(w, 3)\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n\n Similarly for some of the other basis of `NCSym` and the `\\mathbf{w}`\n basis::\n\n sage: e = NCSym.e()\n sage: e.duality_pairing_matrix(w, 3)\n [0 0 0 0 1]\n [0 0 1 1 1]\n [0 1 0 1 1]\n [0 1 1 0 1]\n [1 1 1 1 1]\n sage: p = NCSym.p()\n sage: p.duality_pairing_matrix(w, 3)\n [1 0 0 0 0]\n [1 1 0 0 0]\n [1 0 1 0 0]\n [1 0 0 1 0]\n [1 1 1 1 1]\n sage: cp = NCSym.cp()\n sage: cp.duality_pairing_matrix(w, 3)\n [1 0 0 0 0]\n [1 1 0 0 0]\n [0 0 1 0 0]\n [1 0 0 1 0]\n [1 1 1 1 1]\n sage: x = NCSym.x()\n sage: w.duality_pairing_matrix(x, 3)\n [ 0 0 0 0 1]\n [ 1 0 -1 -1 1]\n [ 1 -1 0 -1 1]\n [ 1 -1 -1 0 1]\n [ 2 -1 -1 -1 1]\n\n A base case test::\n\n sage: m.duality_pairing_matrix(w, 0)\n [1]\n '
from sage.matrix.constructor import matrix
return matrix(self.base_ring(), [[self.duality_pairing(self[I], basis[J]) for J in SetPartitions(degree)] for I in SetPartitions(degree)])
class ElementMethods():
def duality_pairing(self, other):
'\n Compute the pairing between ``self`` and an element ``other`` of the dual.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: w = m.dual_basis()\n sage: elt = m[[1,3],[2]] - 3*m[[1,2],[3]]\n sage: elt.duality_pairing(w[[1,3],[2]])\n 1\n sage: elt.duality_pairing(w[[1,2],[3]])\n -3\n sage: elt.duality_pairing(w[[1,2]])\n 0\n sage: e = NCSym.e()\n sage: w[[1,3],[2]].duality_pairing(e[[1,3],[2]])\n 0\n '
return self.parent().duality_pairing(self, other)
|
class NCSymBases(Category_realization_of_parent):
'\n Category of bases of symmetric functions in non-commuting variables.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsym.bases import NCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymBases(NCSym)\n Category of bases of symmetric functions in non-commuting variables over the Rational Field\n '
def super_categories(self):
'\n Return the super categories of bases of the Hopf dual of the\n symmetric functions in non-commuting variables.\n\n OUTPUT:\n\n - a list of categories\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymBases(NCSym).super_categories()\n [Category of bases of NCSym or NCSym^* over the Rational Field]\n '
return [NCSymOrNCSymDualBases(self.base())]
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymBases(NCSym)\n Category of bases of symmetric functions in non-commuting variables over the Rational Field\n '
return 'Category of bases of symmetric functions in non-commuting variables over the {}'.format(self.base().base_ring())
class ParentMethods():
def from_symmetric_function(self, f):
'\n Return the image of the symmetric function ``f`` in ``self``.\n\n This is performed by converting to the monomial basis and\n extending the method :meth:`sum_of_partitions` linearly. This is a\n linear map from the symmetric functions to the symmetric functions\n in non-commuting variables that does not preserve the product or\n coproduct structure of the Hopf algebra.\n\n .. SEEALSO:: :meth:`to_symmetric_function`\n\n INPUT:\n\n - ``f`` -- a symmetric function\n\n OUTPUT:\n\n - an element of ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: Sym = SymmetricFunctions(QQ)\n sage: e = NCSym.e()\n sage: elem = Sym.e()\n sage: elt = e.from_symmetric_function(elem[2,1,1]); elt\n 1/12*e{{1}, {2}, {3, 4}} + 1/12*e{{1}, {2, 3}, {4}} + 1/12*e{{1}, {2, 4}, {3}}\n + 1/12*e{{1, 2}, {3}, {4}} + 1/12*e{{1, 3}, {2}, {4}} + 1/12*e{{1, 4}, {2}, {3}}\n sage: elem(elt.to_symmetric_function())\n e[2, 1, 1]\n sage: e.from_symmetric_function(elem[4])\n 1/24*e{{1, 2, 3, 4}}\n sage: p = NCSym.p()\n sage: pow = Sym.p()\n sage: elt = p.from_symmetric_function(pow[2,1,1]); elt\n 1/6*p{{1}, {2}, {3, 4}} + 1/6*p{{1}, {2, 3}, {4}} + 1/6*p{{1}, {2, 4}, {3}}\n + 1/6*p{{1, 2}, {3}, {4}} + 1/6*p{{1, 3}, {2}, {4}} + 1/6*p{{1, 4}, {2}, {3}}\n sage: pow(elt.to_symmetric_function())\n p[2, 1, 1]\n sage: p.from_symmetric_function(pow[4])\n p{{1, 2, 3, 4}}\n sage: h = NCSym.h()\n sage: comp = Sym.complete()\n sage: elt = h.from_symmetric_function(comp[2,1,1]); elt\n 1/12*h{{1}, {2}, {3, 4}} + 1/12*h{{1}, {2, 3}, {4}} + 1/12*h{{1}, {2, 4}, {3}}\n + 1/12*h{{1, 2}, {3}, {4}} + 1/12*h{{1, 3}, {2}, {4}} + 1/12*h{{1, 4}, {2}, {3}}\n sage: comp(elt.to_symmetric_function())\n h[2, 1, 1]\n sage: h.from_symmetric_function(comp[4])\n 1/24*h{{1, 2, 3, 4}}\n '
m = self.realization_of().m()
return self(m.from_symmetric_function(f))
def primitive(self, A, i=1):
'\n Return the primitive associated to ``A`` in ``self``.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.ncsym.ncsym.SymmetricFunctionsNonCommutingVariables.powersum.primitive`\n\n INPUT:\n\n - ``A`` -- a set partition\n - ``i`` -- a positive integer\n\n OUTPUT:\n\n - an element of ``self``\n\n EXAMPLES::\n\n sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e()\n sage: elt = e.primitive(SetPartition([[1,3],[2]])); elt\n e{{1, 2}, {3}} - e{{1, 3}, {2}}\n sage: elt.coproduct()\n e{} # e{{1, 2}, {3}} - e{} # e{{1, 3}, {2}} + e{{1, 2}, {3}} # e{} - e{{1, 3}, {2}} # e{}\n '
p = self.realization_of().p()
return self(p.primitive(A, i))
@abstract_method(optional=True)
def internal_coproduct_on_basis(self, i):
'\n The internal coproduct of the algebra on the basis (optional).\n\n INPUT:\n\n - ``i`` -- the indices of an element of the basis of ``self``\n\n OUTPUT:\n\n - an element of the tensor squared of ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m.internal_coproduct_on_basis(SetPartition([[1,2]]))\n m{{1, 2}} # m{{1, 2}}\n '
@lazy_attribute
def internal_coproduct(self):
'\n Compute the internal coproduct of ``self``.\n\n If :meth:`internal_coproduct_on_basis()` is available, construct\n the internal coproduct morphism from ``self`` to ``self``\n `\\otimes` ``self`` by extending it by linearity. Otherwise, this uses\n :meth:`internal_coproduct_by_coercion()`, if available.\n\n OUTPUT:\n\n - an element of the tensor squared of ``self``\n\n EXAMPLES::\n\n sage: cp = SymmetricFunctionsNonCommutingVariables(QQ).cp()\n sage: cp.internal_coproduct(cp[[1,3],[2]] - 2*cp[[1]])\n -2*cp{{1}} # cp{{1}} + cp{{1, 2, 3}} # cp{{1, 3}, {2}} + cp{{1, 3}, {2}} # cp{{1, 2, 3}}\n + cp{{1, 3}, {2}} # cp{{1, 3}, {2}}\n '
if (self.internal_coproduct_on_basis is not NotImplemented):
return Hom(self, tensor([self, self]), ModulesWithBasis(self.base_ring()))(on_basis=self.internal_coproduct_on_basis)
elif hasattr(self, 'internal_coproduct_by_coercion'):
return self.internal_coproduct_by_coercion
def internal_coproduct_by_coercion(self, x):
'\n Return the internal coproduct by coercing the element to the powersum basis.\n\n INPUT:\n\n - ``x`` -- an element of ``self``\n\n OUTPUT:\n\n - an element of the tensor squared of ``self``\n\n EXAMPLES::\n\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: h[[1,3],[2]].internal_coproduct() # indirect doctest\n 2*h{{1}, {2}, {3}} # h{{1}, {2}, {3}} - h{{1}, {2}, {3}} # h{{1, 3}, {2}}\n - h{{1, 3}, {2}} # h{{1}, {2}, {3}} + h{{1, 3}, {2}} # h{{1, 3}, {2}}\n '
R = self.realization_of().a_realization()
return self.tensor_square().sum(((coeff * tensor([self(R[A]), self(R[B])])) for ((A, B), coeff) in R(x).internal_coproduct()))
class ElementMethods():
def expand(self, n, alphabet='x'):
"\n Expand the symmetric function into ``n`` non-commuting\n variables in an alphabet, which by default is ``'x'``.\n\n This computation is completed by coercing the element ``self``\n into the monomial basis and computing the expansion in\n the ``alphabet`` there.\n\n INPUT:\n\n - ``n`` -- the number of variables in the expansion\n - ``alphabet`` -- (default: ``'x'``) the alphabet in which\n ``self`` is to be expanded\n\n OUTPUT:\n\n - an expansion of ``self`` into the ``n`` non-commuting\n variables specified by ``alphabet``\n\n EXAMPLES::\n\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: h[[1,3],[2]].expand(3)\n 2*x0^3 + x0^2*x1 + x0^2*x2 + 2*x0*x1*x0 + x0*x1^2 + x0*x1*x2 + 2*x0*x2*x0\n + x0*x2*x1 + x0*x2^2 + x1*x0^2 + 2*x1*x0*x1 + x1*x0*x2 + x1^2*x0 + 2*x1^3\n + x1^2*x2 + x1*x2*x0 + 2*x1*x2*x1 + x1*x2^2 + x2*x0^2 + x2*x0*x1 + 2*x2*x0*x2\n + x2*x1*x0 + x2*x1^2 + 2*x2*x1*x2 + x2^2*x0 + x2^2*x1 + 2*x2^3\n sage: x = SymmetricFunctionsNonCommutingVariables(QQ).x()\n sage: x[[1,3],[2]].expand(3)\n -x0^2*x1 - x0^2*x2 - x0*x1^2 - x0*x1*x2 - x0*x2*x1 - x0*x2^2 - x1*x0^2\n - x1*x0*x2 - x1^2*x0 - x1^2*x2 - x1*x2*x0 - x1*x2^2 - x2*x0^2 - x2*x0*x1\n - x2*x1*x0 - x2*x1^2 - x2^2*x0 - x2^2*x1\n "
m = self.parent().realization_of().monomial()
return m(self).expand(n, alphabet)
def to_symmetric_function(self):
'\n Compute the projection of an element of symmetric function in\n non-commuting variables to the symmetric functions.\n\n The projection of a monomial symmetric function in non-commuting\n variables indexed by the set partition ``A`` is defined as\n\n .. MATH::\n\n \\mathbf{m}_A \\mapsto m_{\\lambda(A)} \\prod_i n_i(\\lambda(A))!\n\n where `\\lambda(A)` is the partition associated with `A` by\n taking the sizes of the parts and `n_i(\\mu)` is the\n multiplicity of `i` in `\\mu`. For other bases this map is extended\n linearly.\n\n OUTPUT:\n\n - an element of the symmetric functions in the monomial basis\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: h = NCSym.h()\n sage: p = NCSym.p()\n sage: cp = NCSym.cp()\n sage: x = NCSym.x()\n sage: cp[[1,3],[2]].to_symmetric_function()\n m[2, 1]\n sage: x[[1,3],[2]].to_symmetric_function()\n -6*m[1, 1, 1] - 2*m[2, 1]\n sage: e[[1,3],[2]].to_symmetric_function()\n 2*e[2, 1]\n sage: h[[1,3],[2]].to_symmetric_function()\n 2*h[2, 1]\n sage: p[[1,3],[2]].to_symmetric_function()\n p[2, 1]\n '
m = self.parent().realization_of().monomial()
return m(self).to_symmetric_function()
def to_wqsym(self):
'\n Return the image of ``self`` under the canonical\n inclusion map `NCSym \\to WQSym`.\n\n The canonical inclusion map `NCSym \\to WQSym` is\n an injective homomorphism of algebras. It sends a\n basis element `\\mathbf{m}_A` of `NCSym` to the sum of\n basis elements `\\mathbf{M}_P` of `WQSym`, where `P`\n ranges over all ordered set partitions that become\n `A` when the ordering is forgotten.\n This map is denoted by `\\theta` in [BZ05]_ (17).\n\n .. SEEALSO::\n\n :class:`WordQuasiSymmetricFunctions` for a\n definition of `WQSym`.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: h = NCSym.h()\n sage: p = NCSym.p()\n sage: cp = NCSym.cp()\n sage: x = NCSym.x()\n sage: m = NCSym.m()\n sage: m[[1,3],[2]].to_wqsym()\n M[{1, 3}, {2}] + M[{2}, {1, 3}]\n sage: x[[1,3],[2]].to_wqsym()\n -M[{1}, {2}, {3}] - M[{1}, {2, 3}] - M[{1}, {3}, {2}]\n - M[{1, 2}, {3}] - M[{2}, {1}, {3}] - M[{2}, {3}, {1}]\n - M[{2, 3}, {1}] - M[{3}, {1}, {2}] - M[{3}, {1, 2}]\n - M[{3}, {2}, {1}]\n sage: (4*p[[1,3],[2]]-p[[1]]).to_wqsym()\n -M[{1}] + 4*M[{1, 2, 3}] + 4*M[{1, 3}, {2}] + 4*M[{2}, {1, 3}]\n '
parent = self.parent()
NCSym = parent.realization_of()
R = parent.base_ring()
m = NCSym.monomial()
from sage.combinat.chas.wqsym import WordQuasiSymmetricFunctions
M = WordQuasiSymmetricFunctions(R).M()
from itertools import permutations
OSP = M.basis().keys()
def to_wqsym_on_m_basis(A):
l = len(A)
return M.sum_of_terms(((OSP([A[ui] for ui in u]), 1) for u in permutations(range(l))), distinct=True)
return M.linear_combination(((to_wqsym_on_m_basis(A), coeff) for (A, coeff) in m(self)))
def internal_coproduct(self):
'\n Return the internal coproduct of ``self``.\n\n The internal coproduct is defined on the power sum basis as\n\n .. MATH::\n\n \\mathbf{p}_A \\mapsto \\mathbf{p}_A \\otimes \\mathbf{p}_A\n\n and the map is extended linearly.\n\n OUTPUT:\n\n - an element of the tensor square of the basis of ``self``\n\n EXAMPLES::\n\n sage: x = SymmetricFunctionsNonCommutingVariables(QQ).x()\n sage: x[[1,3],[2]].internal_coproduct()\n x{{1}, {2}, {3}} # x{{1, 3}, {2}} + x{{1, 3}, {2}} # x{{1}, {2}, {3}}\n + x{{1, 3}, {2}} # x{{1, 3}, {2}}\n '
return self.parent().internal_coproduct(self)
def omega(self):
'\n Return the involution `\\omega` applied to ``self``.\n\n The involution `\\omega` is defined by\n\n .. MATH::\n\n \\mathbf{e}_A \\mapsto \\mathbf{h}_A\n\n and the result is extended linearly.\n\n OUTPUT:\n\n - an element in the same basis as ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: m[[1,3],[2]].omega()\n -2*m{{1, 2, 3}} - m{{1, 3}, {2}}\n sage: p = NCSym.p()\n sage: p[[1,3],[2]].omega()\n -p{{1, 3}, {2}}\n sage: cp = NCSym.cp()\n sage: cp[[1,3],[2]].omega()\n -2*cp{{1, 2, 3}} - cp{{1, 3}, {2}}\n sage: x = NCSym.x()\n sage: x[[1,3],[2]].omega()\n -2*x{{1}, {2}, {3}} - x{{1, 3}, {2}}\n '
P = self.parent()
e = P.realization_of().e()
h = P.realization_of().h()
return P(h.sum_of_terms(e(self)))
|
class MultiplicativeNCSymBases(Category_realization_of_parent):
'\n Category of multiplicative bases of symmetric functions in non-commuting variables.\n\n A multiplicative basis is one for which `\\mathbf{b}_A \\mathbf{b}_B = \\mathbf{b}_{A|B}`\n where `A|B` is the :meth:`~sage.combinat.set_partition.SetPartition.pipe` operation\n on set partitions.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsym.bases import MultiplicativeNCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: MultiplicativeNCSymBases(NCSym)\n Category of multiplicative bases of symmetric functions in non-commuting variables over the Rational Field\n '
def super_categories(self):
'\n Return the super categories of bases of the Hopf dual of the\n symmetric functions in non-commuting variables.\n\n OUTPUT:\n\n - a list of categories\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import MultiplicativeNCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: MultiplicativeNCSymBases(NCSym).super_categories()\n [Category of bases of symmetric functions in non-commuting variables over the Rational Field]\n '
return [NCSymBases(self.base())]
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import MultiplicativeNCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: MultiplicativeNCSymBases(NCSym)\n Category of multiplicative bases of symmetric functions in non-commuting variables over the Rational Field\n '
return 'Category of multiplicative bases of symmetric functions in non-commuting variables over the {}'.format(self.base().base_ring())
class ParentMethods():
def product_on_basis(self, A, B):
'\n The product on basis elements.\n\n The product on a multiplicative basis is given by\n `\\mathbf{b}_A \\cdot \\mathbf{b}_B = \\mathbf{b}_{A | B}`.\n\n The bases `\\{ \\mathbf{e}, \\mathbf{h}, \\mathbf{x}, \\mathbf{cp}, \\mathbf{p},\n \\mathbf{chi}, \\mathbf{rho} \\}` are all multiplicative.\n\n INPUT:\n\n - ``A``, ``B`` -- set partitions\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e()\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: x = SymmetricFunctionsNonCommutingVariables(QQ).x()\n sage: cp = SymmetricFunctionsNonCommutingVariables(QQ).cp()\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).p()\n sage: chi = SymmetricFunctionsNonCommutingVariables(QQ).chi()\n sage: rho = SymmetricFunctionsNonCommutingVariables(QQ).rho()\n sage: A = SetPartition([[1], [2, 3]])\n sage: B = SetPartition([[1], [3], [2,4]])\n sage: e.product_on_basis(A, B)\n e{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: h.product_on_basis(A, B)\n h{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: x.product_on_basis(A, B)\n x{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: cp.product_on_basis(A, B)\n cp{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: p.product_on_basis(A, B)\n p{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: chi.product_on_basis(A, B)\n chi{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: rho.product_on_basis(A, B)\n rho{{1}, {2, 3}, {4}, {5, 7}, {6}}\n sage: e.product_on_basis(A,B)==e(h(e(A))*h(e(B)))\n True\n sage: h.product_on_basis(A,B)==h(x(h(A))*x(h(B)))\n True\n sage: x.product_on_basis(A,B)==x(h(x(A))*h(x(B)))\n True\n sage: cp.product_on_basis(A,B)==cp(p(cp(A))*p(cp(B)))\n True\n sage: p.product_on_basis(A,B)==p(e(p(A))*e(p(B)))\n True\n '
return self.monomial(A.pipe(B))
class ElementMethods():
pass
|
class NCSymDualBases(Category_realization_of_parent):
'\n Category of bases of dual symmetric functions in non-commuting variables.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsym.bases import NCSymDualBases\n sage: DNCSym = SymmetricFunctionsNonCommutingVariables(QQ).dual()\n sage: NCSymDualBases(DNCSym)\n Category of bases of dual symmetric functions in non-commuting variables over the Rational Field\n '
def super_categories(self):
'\n Return the super categories of bases of the Hopf dual of the\n symmetric functions in non-commuting variables.\n\n OUTPUT:\n\n - a list of categories\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymBases\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: NCSymBases(NCSym).super_categories()\n [Category of bases of NCSym or NCSym^* over the Rational Field]\n '
return [NCSymOrNCSymDualBases(self.base())]
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: from sage.combinat.ncsym.bases import NCSymDualBases\n sage: DNCSym = SymmetricFunctionsNonCommutingVariables(QQ).dual()\n sage: NCSymDualBases(DNCSym)\n Category of bases of dual symmetric functions in non-commuting variables over the Rational Field\n '
return 'Category of bases of dual symmetric functions in non-commuting variables over the {}'.format(self.base().base_ring())
|
class SymmetricFunctionsNonCommutingVariablesDual(UniqueRepresentation, Parent):
'\n The Hopf dual to the symmetric functions in non-commuting variables.\n\n See Section 2.3 of [BZ05]_ for a study.\n '
def __init__(self, R):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: NCSymD1 = SymmetricFunctionsNonCommutingVariablesDual(FiniteField(23))\n sage: NCSymD2 = SymmetricFunctionsNonCommutingVariablesDual(Integers(23))\n sage: TestSuite(SymmetricFunctionsNonCommutingVariables(QQ).dual()).run()\n '
assert ((R in Fields()) or (R in Rings()))
self._base = R
category = GradedHopfAlgebras(R).Commutative()
Parent.__init__(self, category=category.WithRealizations())
w = self.w()
Sym = SymmetricFunctions(self.base_ring())
Sym_h_to_w = Sym.h().module_morphism(w.sum_of_partitions, triangular='lower', inverse_on_support=w._set_par_to_par, codomain=w, category=category)
Sym_h_to_w.register_as_coercion()
self.to_symmetric_function = Sym_h_to_w.section()
def _repr_(self):
'\n EXAMPLES::\n\n sage: SymmetricFunctionsNonCommutingVariables(ZZ).dual()\n Dual symmetric functions in non-commuting variables over the Integer Ring\n '
return ('Dual symmetric functions in non-commuting variables over the %s' % self.base_ring())
def a_realization(self):
'\n Return the realization of the `\\mathbf{w}` basis of ``self``.\n\n EXAMPLES::\n\n sage: SymmetricFunctionsNonCommutingVariables(QQ).dual().a_realization()\n Dual symmetric functions in non-commuting variables over the Rational Field in the w basis\n '
return self.w()
_shorthands = tuple(['w'])
def dual(self):
'\n Return the dual Hopf algebra of the dual symmetric functions in\n non-commuting variables.\n\n EXAMPLES::\n\n sage: NCSymD = SymmetricFunctionsNonCommutingVariables(QQ).dual()\n sage: NCSymD.dual()\n Symmetric functions in non-commuting variables over the Rational Field\n '
from sage.combinat.ncsym.ncsym import SymmetricFunctionsNonCommutingVariables
return SymmetricFunctionsNonCommutingVariables(self.base_ring())
class w(NCSymBasis_abstract):
'\n The dual Hopf algebra of symmetric functions in non-commuting variables\n in the `\\mathbf{w}` basis.\n\n EXAMPLES::\n\n sage: NCSymD = SymmetricFunctionsNonCommutingVariables(QQ).dual()\n sage: w = NCSymD.w()\n\n We have the embedding `\\chi^*` of `Sym` into `NCSym^*` available as\n a coercion::\n\n sage: h = SymmetricFunctions(QQ).h()\n sage: w(h[2,1])\n w{{1}, {2, 3}} + w{{1, 2}, {3}} + w{{1, 3}, {2}}\n\n Similarly we can pull back when we are in the image of `\\chi^*`::\n\n sage: elt = 3*(w[[1],[2,3]] + w[[1,2],[3]] + w[[1,3],[2]])\n sage: h(elt)\n 3*h[2, 1]\n '
def __init__(self, NCSymD):
'\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: TestSuite(w).run()\n '
def key_func_set_part(A):
return sorted(map(sorted, A))
R = NCSymD.base_ring()
category = GradedHopfAlgebras(R).Commutative()
category &= NCSymDualBases(NCSymD)
CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='w', bracket=False, sorting_key=key_func_set_part, category=category)
@lazy_attribute
def to_symmetric_function(self):
'\n The preimage of `\\chi^*` in the `\\mathbf{w}` basis.\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.to_symmetric_function\n Generic morphism:\n From: Dual symmetric functions in non-commuting variables over the Rational Field in the w basis\n To: Symmetric Functions over Rational Field in the homogeneous basis\n '
return self.realization_of().to_symmetric_function
def dual_basis(self):
'\n Return the dual basis to the `\\mathbf{w}` basis.\n\n The dual basis to the `\\mathbf{w}` basis is the monomial basis\n of the symmetric functions in non-commuting variables.\n\n OUTPUT:\n\n - the monomial basis of the symmetric functions in non-commuting variables\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.dual_basis()\n Symmetric functions in non-commuting variables over the Rational Field in the monomial basis\n '
return self.realization_of().dual().m()
def product_on_basis(self, A, B):
'\n The product on `\\mathbf{w}` basis elements.\n\n The product on the `\\mathbf{w}` is the dual to the coproduct on the\n `\\mathbf{m}` basis. On the basis `\\mathbf{w}` it is defined as\n\n .. MATH::\n\n \\mathbf{w}_A \\mathbf{w}_B = \\sum_{S \\subseteq [n]}\n \\mathbf{w}_{A\\uparrow_S \\cup B\\uparrow_{S^c}}\n\n where the sum is over all possible subsets `S` of `[n]` such that\n `|S| = |A|` with a term indexed the union of `A \\uparrow_S` and\n `B \\uparrow_{S^c}`. The notation `A \\uparrow_S` represents the\n unique set partition of the set `S` such that the standardization\n is `A`. This product is commutative.\n\n INPUT:\n\n - ``A``, ``B`` -- set partitions\n\n OUTPUT:\n\n - an element of the `\\mathbf{w}` basis\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: A = SetPartition([[1], [2,3]])\n sage: B = SetPartition([[1, 2, 3]])\n sage: w.product_on_basis(A, B)\n w{{1}, {2, 3}, {4, 5, 6}} + w{{1}, {2, 3, 4}, {5, 6}}\n + w{{1}, {2, 3, 5}, {4, 6}} + w{{1}, {2, 3, 6}, {4, 5}}\n + w{{1}, {2, 4}, {3, 5, 6}} + w{{1}, {2, 4, 5}, {3, 6}}\n + w{{1}, {2, 4, 6}, {3, 5}} + w{{1}, {2, 5}, {3, 4, 6}}\n + w{{1}, {2, 5, 6}, {3, 4}} + w{{1}, {2, 6}, {3, 4, 5}}\n + w{{1, 2, 3}, {4}, {5, 6}} + w{{1, 2, 4}, {3}, {5, 6}}\n + w{{1, 2, 5}, {3}, {4, 6}} + w{{1, 2, 6}, {3}, {4, 5}}\n + w{{1, 3, 4}, {2}, {5, 6}} + w{{1, 3, 5}, {2}, {4, 6}}\n + w{{1, 3, 6}, {2}, {4, 5}} + w{{1, 4, 5}, {2}, {3, 6}}\n + w{{1, 4, 6}, {2}, {3, 5}} + w{{1, 5, 6}, {2}, {3, 4}}\n sage: B = SetPartition([[1], [2]])\n sage: w.product_on_basis(A, B)\n 3*w{{1}, {2}, {3}, {4, 5}} + 2*w{{1}, {2}, {3, 4}, {5}}\n + 2*w{{1}, {2}, {3, 5}, {4}} + w{{1}, {2, 3}, {4}, {5}}\n + w{{1}, {2, 4}, {3}, {5}} + w{{1}, {2, 5}, {3}, {4}}\n sage: w.product_on_basis(A, SetPartition([]))\n w{{1}, {2, 3}}\n '
if (len(A) == 0):
return self.monomial(B)
if (len(B) == 0):
return self.monomial(A)
P = SetPartitions()
n = A.size()
k = B.size()
def unions(s):
a = sorted(s)
b = sorted(Set(range(1, ((n + k) + 1))).difference(s))
ret = [[a[(i - 1)] for i in sorted(part)] for part in A]
ret += [[b[(i - 1)] for i in sorted(part)] for part in B]
return P(ret)
return self.sum_of_terms([(unions(s), 1) for s in Subsets((n + k), n)])
def coproduct_on_basis(self, A):
'\n Return the coproduct of a `\\mathbf{w}` basis element.\n\n The coproduct on the basis element `\\mathbf{w}_A` is the sum over\n tensor product terms `\\mathbf{w}_B \\otimes \\mathbf{w}_C` where\n `B` is the restriction of `A` to `\\{1,2,\\ldots,k\\}` and `C` is\n the restriction of `A` to `\\{k+1, k+2, \\ldots, n\\}`.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - The coproduct applied to the `\\mathbf{w}` dual symmetric function\n in non-commuting variables indexed by ``A`` expressed in the\n `\\mathbf{w}` basis.\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w[[1], [2,3]].coproduct()\n w{} # w{{1}, {2, 3}} + w{{1}} # w{{1, 2}}\n + w{{1}, {2}} # w{{1}} + w{{1}, {2, 3}} # w{}\n sage: w.coproduct_on_basis(SetPartition([]))\n w{} # w{}\n '
n = A.size()
return self.tensor_square().sum_of_terms([((A.restriction(range(1, (i + 1))).standardization(), A.restriction(range((i + 1), (n + 1))).standardization()), 1) for i in range((n + 1))], distinct=True)
def antipode_on_basis(self, A):
'\n Return the antipode applied to the basis element indexed by ``A``.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.antipode_on_basis(SetPartition([[1],[2,3]]))\n -3*w{{1}, {2}, {3}} + w{{1, 2}, {3}} + w{{1, 3}, {2}}\n sage: F = w[[1,3],[5],[2,4]].coproduct()\n sage: F.apply_multilinear_morphism(lambda x,y: x.antipode()*y)\n 0\n '
if (A.size() == 0):
return self.one()
if (A.size() == 1):
return (- self(A))
cpr = self.coproduct_on_basis(A)
return (- sum((((c * self.monomial(B1)) * self.antipode_on_basis(B2)) for ((B1, B2), c) in cpr if (B2 != A))))
def duality_pairing(self, x, y):
'\n Compute the pairing between an element of ``self`` and an\n element of the dual.\n\n INPUT:\n\n - ``x`` -- an element of the dual of symmetric functions in\n non-commuting variables\n - ``y`` -- an element of the symmetric functions in non-commuting\n variables\n\n OUTPUT:\n\n - an element of the base ring of ``self``\n\n EXAMPLES::\n\n sage: DNCSym = SymmetricFunctionsNonCommutingVariablesDual(QQ)\n sage: w = DNCSym.w()\n sage: m = w.dual_basis()\n sage: matrix([[w(A).duality_pairing(m(B)) for A in SetPartitions(3)] for B in SetPartitions(3)])\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n sage: (w[[1,2],[3]] + 3*w[[1,3],[2]]).duality_pairing(2*m[[1,3],[2]] + m[[1,2,3]] + 2*m[[1,2],[3]])\n 8\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: matrix([[w(A).duality_pairing(h(B)) for A in SetPartitions(3)] for B in SetPartitions(3)])\n [6 2 2 2 1]\n [2 2 1 1 1]\n [2 1 2 1 1]\n [2 1 1 2 1]\n [1 1 1 1 1]\n sage: (2*w[[1,3],[2]] + w[[1,2,3]] + 2*w[[1,2],[3]]).duality_pairing(h[[1,2],[3]] + 3*h[[1,3],[2]])\n 32\n '
x = self(x)
y = self.dual_basis()(y)
return sum(((coeff * y[I]) for (I, coeff) in x))
def sum_of_partitions(self, la):
'\n Return the sum over all sets partitions whose shape is ``la``,\n scaled by `\\prod_i m_i!` where `m_i` is the multiplicity\n of `i` in ``la``.\n\n INPUT:\n\n - ``la`` -- an integer partition\n\n OUTPUT:\n\n - an element of ``self``\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w.sum_of_partitions([2,1,1])\n 2*w{{1}, {2}, {3, 4}} + 2*w{{1}, {2, 3}, {4}} + 2*w{{1}, {2, 4}, {3}}\n + 2*w{{1, 2}, {3}, {4}} + 2*w{{1, 3}, {2}, {4}} + 2*w{{1, 4}, {2}, {3}}\n '
la = Partition(la)
c = prod([factorial(i) for i in la.to_exp()])
P = SetPartitions()
return self.sum_of_terms([(P(m), c) for m in SetPartitions(sum(la), la)], distinct=True)
def _set_par_to_par(self, A):
'\n Return the shape of ``A`` if ``A`` is the canonical standard\n set partition `A_1 | A_2 | \\cdots | A_k` where `|` is the pipe\n operation (see\n :meth:`~sage.combinat.set_partition.SetPartition.pipe()` )\n and `A_i = [\\lambda_i]` where `\\lambda_1 \\leq \\lambda_2 \\leq\n \\cdots \\leq \\lambda_k`. Otherwise, return ``None``.\n\n This is the trailing term of `h_{\\lambda}` mapped by `\\chi` to\n the `\\mathbf{w}` basis and is used by the coercion framework to\n construct the preimage `\\chi^{-1}`.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w._set_par_to_par(SetPartition([[1], [2], [3,4,5]]))\n [3, 1, 1]\n sage: w._set_par_to_par(SetPartition([[1,2,3],[4],[5]]))\n sage: w._set_par_to_par(SetPartition([[1],[2,3,4],[5]]))\n sage: w._set_par_to_par(SetPartition([[1],[2,3,5],[4]]))\n\n TESTS:\n\n This is used in the coercion between `\\mathbf{w}` and the\n homogeneous symmetric functions. ::\n\n sage: w = SymmetricFunctionsNonCommutingVariablesDual(QQ).w()\n sage: h = SymmetricFunctions(QQ).h()\n sage: h(w[[1,3],[2]])\n Traceback (most recent call last):\n ...\n ValueError: w{{1, 3}, {2}} is not in the image\n sage: h(w(h[2,1])) == w(h[2,1]).to_symmetric_function()\n True\n '
cur = 1
prev_len = 0
for p in A:
if ((prev_len > len(p)) or (list(p) != list(range(cur, (cur + len(p)))))):
return None
prev_len = len(p)
cur += len(p)
return A.shape()
class Element(CombinatorialFreeModule.Element):
'\n An element in the `\\mathbf{w}` basis.\n '
def expand(self, n, letter='x'):
"\n Expand ``self`` written in the `\\mathbf{w}` basis in `n^2`\n commuting variables which satisfy the relation\n `x_{ij} x_{ik} = 0` for all `i`, `j`, and `k`.\n\n The expansion of an element of the `\\mathbf{w}` basis is\n given by equations (26) and (55) in [HNT06]_.\n\n INPUT:\n\n - ``n`` -- an integer\n - ``letter`` -- (default: ``'x'``) a string\n\n OUTPUT:\n\n - The symmetric function of ``self`` expressed in the ``n*n``\n non-commuting variables described by ``letter``.\n\n REFERENCES:\n\n .. [HNT06] \\F. Hivert, J.-C. Novelli, J.-Y. Thibon.\n *Commutative combinatorial Hopf algebras*. (2006).\n :arxiv:`0605262v1`.\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w[[1,3],[2]].expand(4)\n x02*x11*x20 + x03*x11*x30 + x03*x22*x30 + x13*x22*x31\n\n One can use a different set of variable by using the\n optional argument ``letter``::\n\n sage: w[[1,3],[2]].expand(3, letter='y')\n y02*y11*y20\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.combinat.permutation import Permutations
m = self.parent()
names = ['{}{}{}'.format(letter, i, j) for i in range(n) for j in range(n)]
R = PolynomialRing(m.base_ring(), (n * n), names)
x = [[R.gens()[((i * n) + j)] for j in range(n)] for i in range(n)]
I = R.ideal([(x[i][j] * x[i][k]) for j in range(n) for k in range(n) for i in range(n)])
Q = R.quotient(I, names)
x = [[Q.gens()[((i * n) + j)] for j in range(n)] for i in range(n)]
P = SetPartitions()
def on_basis(A):
k = A.size()
ret = R.zero()
if (n < k):
return ret
for p in Permutations(k):
if (P(p.to_cycles()) == A):
ret += R.sum((prod((x[I[i]][I[(p[i] - 1)]] for i in range(k))) for I in Subsets(range(n), k)))
return ret
return m._apply_module_morphism(self, on_basis, codomain=R)
def is_symmetric(self):
'\n Determine if a `NCSym^*` function, expressed in the\n `\\mathbf{w}` basis, is symmetric.\n\n A function `f` in the `\\mathbf{w}` basis is a symmetric\n function if it is in the image of `\\chi^*`. That is to say we\n have\n\n .. MATH::\n\n f = \\sum_{\\lambda} c_{\\lambda} \\prod_i m_i(\\lambda)!\n \\sum_{\\lambda(A) = \\lambda} \\mathbf{w}_A\n\n where the second sum is over all set partitions `A` whose\n shape `\\lambda(A)` is equal to `\\lambda` and `m_i(\\mu)` is\n the multiplicity of `i` in the partition `\\mu`.\n\n OUTPUT:\n\n - ``True`` if `\\lambda(A)=\\lambda(B)` implies the coefficients of\n `\\mathbf{w}_A` and `\\mathbf{w}_B` are equal, ``False`` otherwise\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: elt = w.sum_of_partitions([2,1,1])\n sage: elt.is_symmetric()\n True\n sage: elt -= 3*w.sum_of_partitions([1,1])\n sage: elt.is_symmetric()\n True\n sage: w = SymmetricFunctionsNonCommutingVariables(ZZ).dual().w()\n sage: elt = w.sum_of_partitions([2,1,1]) / 2\n sage: elt.is_symmetric()\n False\n sage: elt = w[[1,3],[2]]\n sage: elt.is_symmetric()\n False\n sage: elt = w[[1],[2,3]] + w[[1,2],[3]] + 2*w[[1,3],[2]]\n sage: elt.is_symmetric()\n False\n '
d = {}
R = self.base_ring()
for (A, coeff) in self:
la = A.shape()
exp = prod([factorial(i) for i in la.to_exp()])
if (la not in d):
if ((coeff / exp) not in R):
return False
d[la] = [coeff, 1]
else:
if (d[la][0] != coeff):
return False
d[la][1] += 1
return all(((d[la][1] == SetPartitions(la.size(), la).cardinality()) for la in d))
def to_symmetric_function(self):
'\n Take a function in the `\\mathbf{w}` basis, and return its\n symmetric realization, when possible, expressed in the\n homogeneous basis of symmetric functions.\n\n OUTPUT:\n\n - If ``self`` is a symmetric function, then the expansion\n in the homogeneous basis of the symmetric functions is returned.\n Otherwise an error is raised.\n\n EXAMPLES::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: elt = w[[1],[2,3]] + w[[1,2],[3]] + w[[1,3],[2]]\n sage: elt.to_symmetric_function()\n h[2, 1]\n sage: elt = w.sum_of_partitions([2,1,1]) / 2\n sage: elt.to_symmetric_function()\n 1/2*h[2, 1, 1]\n\n TESTS::\n\n sage: w = SymmetricFunctionsNonCommutingVariables(QQ).dual().w()\n sage: w(0).to_symmetric_function()\n 0\n sage: w([]).to_symmetric_function()\n h[]\n sage: (2*w([])).to_symmetric_function()\n 2*h[]\n '
if (not self.is_symmetric()):
raise ValueError('not a symmetric function')
h = SymmetricFunctions(self.parent().base_ring()).homogeneous()
d = {A.shape(): c for (A, c) in self}
return h.sum_of_terms([(AA, (cc / prod([factorial(i) for i in AA.to_exp()]))) for (AA, cc) in d.items()], distinct=True)
|
def matchings(A, B):
'\n Iterate through all matchings of the sets `A` and `B`.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsym.ncsym import matchings\n sage: list(matchings([1, 2, 3], [-1, -2]))\n [[[1], [2], [3], [-1], [-2]],\n [[1], [2], [3, -1], [-2]],\n [[1], [2], [3, -2], [-1]],\n [[1], [2, -1], [3], [-2]],\n [[1], [2, -1], [3, -2]],\n [[1], [2, -2], [3], [-1]],\n [[1], [2, -2], [3, -1]],\n [[1, -1], [2], [3], [-2]],\n [[1, -1], [2], [3, -2]],\n [[1, -1], [2, -2], [3]],\n [[1, -2], [2], [3], [-1]],\n [[1, -2], [2], [3, -1]],\n [[1, -2], [2, -1], [3]]]\n '
lst_A = list(A)
lst_B = list(B)
if (not lst_A):
if (not lst_B):
(yield [])
else:
(yield [[b] for b in lst_B])
return
if (not lst_B):
(yield [[a] for a in lst_A])
return
rem_A = lst_A[:]
a = rem_A.pop(0)
for m in matchings(rem_A, lst_B):
(yield ([[a]] + m))
for i in range(len(lst_B)):
rem_B = lst_B[:]
b = rem_B.pop(i)
for m in matchings(rem_A, rem_B):
(yield ([[a, b]] + m))
|
def nesting(la, nu):
'\n Return the nesting number of ``la`` inside of ``nu``.\n\n If we consider a set partition `A` as a set of arcs `i - j` where `i`\n and `j` are in the same part of `A`. Define\n\n .. MATH::\n\n \\operatorname{nst}_{\\lambda}^{\\nu} = \\#\\{ i < j < k < l \\mid\n i - l \\in \\nu, j - k \\in \\lambda \\},\n\n and this corresponds to the number of arcs of `\\lambda` strictly\n contained inside of `\\nu`.\n\n EXAMPLES::\n\n sage: from sage.combinat.ncsym.ncsym import nesting\n sage: nu = SetPartition([[1,4], [2], [3]])\n sage: mu = SetPartition([[1,4], [2,3]])\n sage: nesting(set(mu).difference(nu), nu)\n 1\n\n ::\n\n sage: lst = list(SetPartitions(4))\n sage: d = {}\n sage: for i, nu in enumerate(lst):\n ....: for mu in nu.coarsenings():\n ....: if set(nu.arcs()).issubset(mu.arcs()):\n ....: d[i, lst.index(mu)] = nesting(set(mu).difference(nu), nu)\n sage: matrix(d)\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 1 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n '
arcs = []
for p in nu:
p = sorted(p)
arcs += [(p[i], p[(i + 1)]) for i in range((len(p) - 1))]
nst = 0
for p in la:
p = sorted(p)
for i in range((len(p) - 1)):
for a in arcs:
if (a[0] >= p[i]):
break
if (p[(i + 1)] < a[1]):
nst += 1
return nst
|
class SymmetricFunctionsNonCommutingVariables(UniqueRepresentation, Parent):
"\n Symmetric functions in non-commutative variables.\n\n The ring of symmetric functions in non-commutative variables,\n which is not to be confused with the :class:`non-commutative symmetric\n functions<NonCommutativeSymmetricFunctions>`, is the ring of all\n bounded-degree noncommutative power series in countably many\n indeterminates (i.e., elements in\n `R \\langle \\langle x_1, x_2, x_3, \\ldots \\rangle \\rangle` of bounded\n degree) which are invariant with respect to the action of the\n symmetric group `S_{\\infty}` on the indices of the indeterminates.\n It can be regarded as a direct limit over all `n \\to \\infty` of rings\n of `S_n`-invariant polynomials in `n` non-commuting variables\n (that is, `S_n`-invariant elements of `R\\langle x_1, x_2, \\ldots, x_n \\rangle`).\n\n This ring is implemented as a Hopf algebra whose basis elements are\n indexed by set partitions.\n\n Let `A = \\{A_1, A_2, \\ldots, A_r\\}` be a set partition of the integers\n `[k] := \\{ 1, 2, \\ldots, k \\}`. This partition `A` determines an\n equivalence relation `\\sim_A` on `[k]`, which has `c \\sim_A d` if and\n only if `c` and `d` are in the same part `A_j` of `A`.\n The monomial basis element `\\mathbf{m}_A` indexed by `A` is the sum of\n monomials `x_{i_1} x_{i_2} \\cdots x_{i_k}` such that `i_c = i_d` if\n and only if `c \\sim_A d`.\n\n The `k`-th graded component of the ring of symmetric functions in\n non-commutative variables has its dimension equal to the number of\n set partitions of `[k]`. (If we work, instead, with finitely many --\n say, `n` -- variables, then its dimension is equal to the number of\n set partitions of `[k]` where the number of parts is at most `n`.)\n\n .. NOTE::\n\n All set partitions are considered standard (i.e., set partitions\n of `[n]` for some `n`) unless otherwise stated.\n\n REFERENCES:\n\n .. [BZ05] \\N. Bergeron, M. Zabrocki. *The Hopf algebra of symmetric\n functions and quasisymmetric functions in non-commutative variables\n are free and cofree*. (2005). :arxiv:`math/0509265v3`.\n\n .. [BHRZ06] \\N. Bergeron, C. Hohlweg, M. Rosas, M. Zabrocki.\n *Grothendieck bialgebras, partition lattices, and symmetric\n functions in noncommutative variables*. Electronic Journal of\n Combinatorics. **13** (2006).\n\n .. [RS06] \\M. Rosas, B. Sagan. *Symmetric functions in noncommuting\n variables*. Trans. Amer. Math. Soc. **358** (2006). no. 1, 215-232.\n :arxiv:`math/0208168`.\n\n .. [BRRZ08] \\N. Bergeron, C. Reutenauer, M. Rosas, M. Zabrocki.\n *Invariants and coinvariants of the symmetric group in noncommuting\n variables*. Canad. J. Math. **60** (2008). 266-296.\n :arxiv:`math/0502082`\n\n .. [BT13] \\N. Bergeron, N. Thiem. *A supercharacter table decomposition\n via power-sum symmetric functions*. Int. J. Algebra Comput. **23**,\n 763 (2013). :doi:`10.1142/S0218196713400171`. :arxiv:`1112.4901`.\n\n EXAMPLES:\n\n We begin by first creating the ring of `NCSym` and the bases that are\n analogues of the usual symmetric functions::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: e = NCSym.e()\n sage: h = NCSym.h()\n sage: p = NCSym.p()\n sage: m\n Symmetric functions in non-commuting variables over the Rational Field in the monomial basis\n\n The basis is indexed by set partitions, so we create a few elements and\n convert them between these bases::\n\n sage: elt = m(SetPartition([[1,3],[2]])) - 2*m(SetPartition([[1],[2]])); elt\n -2*m{{1}, {2}} + m{{1, 3}, {2}}\n sage: e(elt)\n 1/2*e{{1}, {2, 3}} - 2*e{{1, 2}} + 1/2*e{{1, 2}, {3}} - 1/2*e{{1, 2, 3}} - 1/2*e{{1, 3}, {2}}\n sage: h(elt)\n -4*h{{1}, {2}} - 2*h{{1}, {2}, {3}} + 1/2*h{{1}, {2, 3}} + 2*h{{1, 2}}\n + 1/2*h{{1, 2}, {3}} - 1/2*h{{1, 2, 3}} + 3/2*h{{1, 3}, {2}}\n sage: p(elt)\n -2*p{{1}, {2}} + 2*p{{1, 2}} - p{{1, 2, 3}} + p{{1, 3}, {2}}\n sage: m(p(elt))\n -2*m{{1}, {2}} + m{{1, 3}, {2}}\n\n sage: elt = p(SetPartition([[1,3],[2]])) - 4*p(SetPartition([[1],[2]])) + 2; elt\n 2*p{} - 4*p{{1}, {2}} + p{{1, 3}, {2}}\n sage: e(elt)\n 2*e{} - 4*e{{1}, {2}} + e{{1}, {2}, {3}} - e{{1, 3}, {2}}\n sage: m(elt)\n 2*m{} - 4*m{{1}, {2}} - 4*m{{1, 2}} + m{{1, 2, 3}} + m{{1, 3}, {2}}\n sage: h(elt)\n 2*h{} - 4*h{{1}, {2}} - h{{1}, {2}, {3}} + h{{1, 3}, {2}}\n sage: p(m(elt))\n 2*p{} - 4*p{{1}, {2}} + p{{1, 3}, {2}}\n\n There is also a shorthand for creating elements. We note that we must use\n ``p[[]]`` to create the empty set partition due to python's syntax. ::\n\n sage: eltm = m[[1,3],[2]] - 3*m[[1],[2]]; eltm\n -3*m{{1}, {2}} + m{{1, 3}, {2}}\n sage: elte = e[[1,3],[2]]; elte\n e{{1, 3}, {2}}\n sage: elth = h[[1,3],[2,4]]; elth\n h{{1, 3}, {2, 4}}\n sage: eltp = p[[1,3],[2,4]] + 2*p[[1]] - 4*p[[]]; eltp\n -4*p{} + 2*p{{1}} + p{{1, 3}, {2, 4}}\n\n There is also a natural projection to the usual symmetric functions by\n letting the variables commute. This projection map preserves the product\n and coproduct structure. We check that Theorem 2.1 of [RS06]_ holds::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: Sm = Sym.m()\n sage: Se = Sym.e()\n sage: Sh = Sym.h()\n sage: Sp = Sym.p()\n sage: eltm.to_symmetric_function()\n -6*m[1, 1] + m[2, 1]\n sage: Sm(p(eltm).to_symmetric_function())\n -6*m[1, 1] + m[2, 1]\n sage: elte.to_symmetric_function()\n 2*e[2, 1]\n sage: Se(h(elte).to_symmetric_function())\n 2*e[2, 1]\n sage: elth.to_symmetric_function()\n 4*h[2, 2]\n sage: Sh(m(elth).to_symmetric_function())\n 4*h[2, 2]\n sage: eltp.to_symmetric_function()\n -4*p[] + 2*p[1] + p[2, 2]\n sage: Sp(e(eltp).to_symmetric_function())\n -4*p[] + 2*p[1] + p[2, 2]\n "
def __init__(self, R):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: NCSym1 = SymmetricFunctionsNonCommutingVariables(FiniteField(23))\n sage: NCSym2 = SymmetricFunctionsNonCommutingVariables(Integers(23))\n sage: TestSuite(SymmetricFunctionsNonCommutingVariables(QQ)).run()\n '
assert ((R in Fields()) or (R in Rings()))
self._base = R
category = GradedHopfAlgebras(R).Cocommutative()
Parent.__init__(self, category=category.WithRealizations())
def _repr_(self):
'\n EXAMPLES::\n\n sage: SymmetricFunctionsNonCommutingVariables(ZZ)\n Symmetric functions in non-commuting variables over the Integer Ring\n '
return ('Symmetric functions in non-commuting variables over the %s' % self.base_ring())
def a_realization(self):
'\n Return the realization of the powersum basis of ``self``.\n\n OUTPUT:\n\n - The powersum basis of symmetric functions in non-commuting variables.\n\n EXAMPLES::\n\n sage: SymmetricFunctionsNonCommutingVariables(QQ).a_realization()\n Symmetric functions in non-commuting variables over the Rational Field in the powersum basis\n '
return self.powersum()
_shorthands = tuple(['chi', 'cp', 'm', 'e', 'h', 'p', 'rho', 'x'])
def dual(self):
'\n Return the dual Hopf algebra of the symmetric functions in\n non-commuting variables.\n\n EXAMPLES::\n\n sage: SymmetricFunctionsNonCommutingVariables(QQ).dual()\n Dual symmetric functions in non-commuting variables over the Rational Field\n '
from sage.combinat.ncsym.dual import SymmetricFunctionsNonCommutingVariablesDual
return SymmetricFunctionsNonCommutingVariablesDual(self.base_ring())
class monomial(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the monomial basis.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: m[[1,3],[2]]*m[[1,2]]\n m{{1, 3}, {2}, {4, 5}} + m{{1, 3}, {2, 4, 5}} + m{{1, 3, 4, 5}, {2}}\n sage: m[[1,3],[2]].coproduct()\n m{} # m{{1, 3}, {2}} + m{{1}} # m{{1, 2}} + m{{1, 2}} # m{{1}} + m{{1,\n 3}, {2}} # m{}\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.m()).run()\n '
R = NCSym.base_ring()
category = GradedHopfAlgebras(R).Cocommutative()
category &= NCSymBases(NCSym)
CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='m', bracket=False, category=category)
@cached_method
def _m_to_p_on_basis(self, A):
'\n Return `\\mathbf{m}_A` in terms of the powersum basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the powersum basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: all(m(m._m_to_p_on_basis(A)) == m[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
def lt(s, t):
if (s == t):
return False
for p in s:
if (len([z for z in t if z.intersection(p)]) != 1):
return False
return True
p = self.realization_of().p()
P = Poset((A.coarsenings(), lt))
R = self.base_ring()
return p._from_dict({B: R(P.moebius_function(A, B)) for B in P})
@cached_method
def _m_to_cp_on_basis(self, A):
'\n Return `\\mathbf{m}_A` in terms of the `\\mathbf{cp}` basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{cp}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: all(m(m._m_to_cp_on_basis(A)) == m[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
cp = self.realization_of().cp()
arcs = set(A.arcs())
R = self.base_ring()
return cp._from_dict({B: R(((- 1) ** len(set(B.arcs()).difference(A.arcs())))) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False)
def from_symmetric_function(self, f):
'\n Return the image of the symmetric function ``f`` in ``self``.\n\n This is performed by converting to the monomial basis and\n extending the method :meth:`sum_of_partitions` linearly. This is a\n linear map from the symmetric functions to the symmetric functions\n in non-commuting variables that does not preserve the product or\n coproduct structure of the Hopf algebra.\n\n .. SEEALSO:: :meth:`~Element.to_symmetric_function`\n\n INPUT:\n\n - ``f`` -- an element of the symmetric functions\n\n OUTPUT:\n\n - An element of the `\\mathbf{m}` basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: mon = SymmetricFunctions(QQ).m()\n sage: elt = m.from_symmetric_function(mon[2,1,1]); elt\n 1/12*m{{1}, {2}, {3, 4}} + 1/12*m{{1}, {2, 3}, {4}} + 1/12*m{{1}, {2, 4}, {3}}\n + 1/12*m{{1, 2}, {3}, {4}} + 1/12*m{{1, 3}, {2}, {4}} + 1/12*m{{1, 4}, {2}, {3}}\n sage: elt.to_symmetric_function()\n m[2, 1, 1]\n sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e()\n sage: elm = SymmetricFunctions(QQ).e()\n sage: e(m.from_symmetric_function(elm[4]))\n 1/24*e{{1, 2, 3, 4}}\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: hom = SymmetricFunctions(QQ).h()\n sage: h(m.from_symmetric_function(hom[4]))\n 1/24*h{{1, 2, 3, 4}}\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).p()\n sage: pow = SymmetricFunctions(QQ).p()\n sage: p(m.from_symmetric_function(pow[4]))\n p{{1, 2, 3, 4}}\n sage: p(m.from_symmetric_function(pow[2,1]))\n 1/3*p{{1}, {2, 3}} + 1/3*p{{1, 2}, {3}} + 1/3*p{{1, 3}, {2}}\n sage: p([[1,2]])*p([[1]])\n p{{1, 2}, {3}}\n\n Check that `\\chi \\circ \\widetilde{\\chi}` is the identity on `Sym`::\n\n sage: all(m.from_symmetric_function(pow(la)).to_symmetric_function() == pow(la)\n ....: for la in Partitions(4))\n True\n '
m = SymmetricFunctions(self.base_ring()).m()
return self.sum([(c * self.sum_of_partitions(i)) for (i, c) in m(f)])
def dual_basis(self):
'\n Return the dual basis to the monomial basis.\n\n OUTPUT:\n\n - the `\\mathbf{w}` basis of the dual Hopf algebra\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m.dual_basis()\n Dual symmetric functions in non-commuting variables over the Rational Field in the w basis\n '
return self.realization_of().dual().w()
def duality_pairing(self, x, y):
'\n Compute the pairing between an element of ``self`` and an element\n of the dual.\n\n INPUT:\n\n - ``x`` -- an element of symmetric functions in non-commuting\n variables\n - ``y`` -- an element of the dual of symmetric functions in\n non-commuting variables\n\n OUTPUT:\n\n - an element of the base ring of ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: m = NCSym.m()\n sage: w = m.dual_basis()\n sage: matrix([[m(A).duality_pairing(w(B)) for A in SetPartitions(3)] for B in SetPartitions(3)])\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n sage: (m[[1,2],[3]] + 3*m[[1,3],[2]]).duality_pairing(2*w[[1,3],[2]] + w[[1,2,3]] + 2*w[[1,2],[3]])\n 8\n '
x = self(x)
y = self.dual_basis()(y)
return sum(((coeff * y[I]) for (I, coeff) in x))
def product_on_basis(self, A, B):
'\n The product on monomial basis elements.\n\n The product of the basis elements indexed by two set partitions `A`\n and `B` is the sum of the basis elements indexed by set partitions\n `C` such that `C \\wedge ([n] | [k]) = A | B` where `n = |A|`\n and `k = |B|`. Here `A \\wedge B` is the infimum of `A` and `B`\n and `A | B` is the\n :meth:`SetPartition.pipe` operation.\n Equivalently we can describe all `C` as matchings between the\n parts of `A` and `B` where if `a \\in A` is matched\n with `b \\in B`, we take `a \\cup b` instead of `a` and `b` in `C`.\n\n INPUT:\n\n - ``A``, ``B`` -- set partitions\n\n OUTPUT:\n\n - an element of the `\\mathbf{m}` basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: A = SetPartition([[1], [2,3]])\n sage: B = SetPartition([[1], [3], [2,4]])\n sage: m.product_on_basis(A, B)\n m{{1}, {2, 3}, {4}, {5, 7}, {6}} + m{{1}, {2, 3, 4}, {5, 7}, {6}}\n + m{{1}, {2, 3, 5, 7}, {4}, {6}} + m{{1}, {2, 3, 6}, {4}, {5, 7}}\n + m{{1, 4}, {2, 3}, {5, 7}, {6}} + m{{1, 4}, {2, 3, 5, 7}, {6}}\n + m{{1, 4}, {2, 3, 6}, {5, 7}} + m{{1, 5, 7}, {2, 3}, {4}, {6}}\n + m{{1, 5, 7}, {2, 3, 4}, {6}} + m{{1, 5, 7}, {2, 3, 6}, {4}}\n + m{{1, 6}, {2, 3}, {4}, {5, 7}} + m{{1, 6}, {2, 3, 4}, {5, 7}}\n + m{{1, 6}, {2, 3, 5, 7}, {4}}\n sage: B = SetPartition([[1], [2]])\n sage: m.product_on_basis(A, B)\n m{{1}, {2, 3}, {4}, {5}} + m{{1}, {2, 3, 4}, {5}}\n + m{{1}, {2, 3, 5}, {4}} + m{{1, 4}, {2, 3}, {5}} + m{{1, 4}, {2, 3, 5}}\n + m{{1, 5}, {2, 3}, {4}} + m{{1, 5}, {2, 3, 4}}\n sage: m.product_on_basis(A, SetPartition([]))\n m{{1}, {2, 3}}\n\n TESTS:\n\n We check that we get all of the correct set partitions::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: A = SetPartition([[1], [2,3]])\n sage: B = SetPartition([[1], [2]])\n sage: S = SetPartition([[1,2,3], [4,5]])\n sage: AB = SetPartition([[1], [2,3], [4], [5]])\n sage: L = sorted(filter(lambda x: S.inf(x) == AB, SetPartitions(5)), key=str)\n sage: list(map(list, L)) == list(map(list, sorted(m.product_on_basis(A, B).support(), key=str)))\n True\n '
if (not A):
return self.monomial(B)
if (not B):
return self.monomial(A)
P = SetPartitions()
n = A.size()
B = [Set([(y + n) for y in b]) for b in B]
unions = (lambda m: [reduce((lambda a, b: a.union(b)), x) for x in m])
one = self.base_ring().one()
return self._from_dict({P(unions(m)): one for m in matchings(A, B)}, remove_zeros=False)
def coproduct_on_basis(self, A):
'\n Return the coproduct of a monomial basis element.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - The coproduct applied to the monomial symmetric function in\n non-commuting variables indexed by ``A`` expressed in the\n monomial basis.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: m[[1, 3], [2]].coproduct()\n m{} # m{{1, 3}, {2}} + m{{1}} # m{{1, 2}} + m{{1, 2}} # m{{1}} + m{{1, 3}, {2}} # m{}\n sage: m.coproduct_on_basis(SetPartition([]))\n m{} # m{}\n sage: m.coproduct_on_basis(SetPartition([[1,2,3]]))\n m{} # m{{1, 2, 3}} + m{{1, 2, 3}} # m{}\n sage: m[[1,5],[2,4],[3,7],[6]].coproduct()\n m{} # m{{1, 5}, {2, 4}, {3, 7}, {6}} + m{{1}} # m{{1, 5}, {2, 4}, {3, 6}}\n + 2*m{{1, 2}} # m{{1, 3}, {2, 5}, {4}} + m{{1, 2}} # m{{1, 4}, {2, 3}, {5}}\n + 2*m{{1, 2}, {3}} # m{{1, 3}, {2, 4}} + m{{1, 3}, {2}} # m{{1, 4}, {2, 3}}\n + 2*m{{1, 3}, {2, 4}} # m{{1, 2}, {3}} + 2*m{{1, 3}, {2, 5}, {4}} # m{{1, 2}}\n + m{{1, 4}, {2, 3}} # m{{1, 3}, {2}} + m{{1, 4}, {2, 3}, {5}} # m{{1, 2}}\n + m{{1, 5}, {2, 4}, {3, 6}} # m{{1}} + m{{1, 5}, {2, 4}, {3, 7}, {6}} # m{}\n '
P = SetPartitions()
if (not A):
return self.tensor_square().monomial((P([]), P([])))
if (len(A) == 1):
return self.tensor_square().sum_of_monomials([(P([]), A), (A, P([]))])
ell_set = list(range(1, (len(A) + 1)))
L = ([[[], ell_set]] + list(SetPartitions(ell_set, 2)))
def to_basis(S):
if (not S):
return P([])
sub_parts = [list(A[(i - 1)]) for i in S]
mins = [min(p) for p in sub_parts]
over_max = (max([max(p) for p in sub_parts]) + 1)
ret = [[] for _ in repeat(None, len(S))]
cur = 1
while (min(mins) != over_max):
m = min(mins)
i = mins.index(m)
ret[i].append(cur)
cur += 1
sub_parts[i].pop(sub_parts[i].index(m))
if sub_parts[i]:
mins[i] = min(sub_parts[i])
else:
mins[i] = over_max
return P(ret)
L1 = [(to_basis(S), to_basis(C)) for (S, C) in L]
L2 = [(M, N) for (N, M) in L1]
return self.tensor_square().sum_of_monomials((L1 + L2))
def internal_coproduct_on_basis(self, A):
'\n Return the internal coproduct of a monomial basis element.\n\n The internal coproduct is defined by\n\n .. MATH::\n\n \\Delta^{\\odot}(\\mathbf{m}_A) = \\sum_{B \\wedge C = A}\n \\mathbf{m}_B \\otimes \\mathbf{m}_C\n\n where we sum over all pairs of set partitions `B` and `C`\n whose infimum is `A`.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the tensor square of the `\\mathbf{m}` basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: m.internal_coproduct_on_basis(SetPartition([[1,3],[2]]))\n m{{1, 2, 3}} # m{{1, 3}, {2}} + m{{1, 3}, {2}} # m{{1, 2, 3}} + m{{1, 3}, {2}} # m{{1, 3}, {2}}\n '
P = SetPartitions()
SP = SetPartitions(A.size())
ret = [[A, A]]
for (i, B) in enumerate(SP):
for C in SP[(i + 1):]:
if (B.inf(C) == A):
B_std = P(list(B.standardization()))
C_std = P(list(C.standardization()))
ret.append([B_std, C_std])
ret.append([C_std, B_std])
return self.tensor_square().sum_of_monomials(((B, C) for (B, C) in ret))
def sum_of_partitions(self, la):
'\n Return the sum over all set partitions whose shape is ``la``\n with a fixed coefficient `C` defined below.\n\n Fix a partition `\\lambda`, we define\n `\\lambda! := \\prod_i \\lambda_i!` and `\\lambda^! := \\prod_i m_i!`.\n Recall that `|\\lambda| = \\sum_i \\lambda_i` and `m_i` is the\n number of parts of length `i` of `\\lambda`. Thus we defined the\n coefficient as\n\n .. MATH::\n\n C := \\frac{\\lambda! \\lambda^!}{|\\lambda|!}.\n\n Hence we can define a lift `\\widetilde{\\chi}` from `Sym`\n to `NCSym` by\n\n .. MATH::\n\n m_{\\lambda} \\mapsto C \\sum_A \\mathbf{m}_A\n\n where the sum is over all set partitions whose shape\n is `\\lambda`.\n\n INPUT:\n\n - ``la`` -- an integer partition\n\n OUTPUT:\n\n - an element of the `\\mathbf{m}` basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: m.sum_of_partitions(Partition([2,1,1]))\n 1/12*m{{1}, {2}, {3, 4}} + 1/12*m{{1}, {2, 3}, {4}} + 1/12*m{{1}, {2, 4}, {3}}\n + 1/12*m{{1, 2}, {3}, {4}} + 1/12*m{{1, 3}, {2}, {4}} + 1/12*m{{1, 4}, {2}, {3}}\n\n TESTS:\n\n Check that `\\chi \\circ \\widetilde{\\chi}` is the identity on `Sym`::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).m()\n sage: mon = SymmetricFunctions(QQ).monomial()\n sage: all(m.from_symmetric_function(mon[la]).to_symmetric_function() == mon[la]\n ....: for i in range(6) for la in Partitions(i))\n True\n '
from sage.combinat.partition import Partition
la = Partition(la)
R = self.base_ring()
P = SetPartitions()
c = R((prod((factorial(i) for i in la)) / ZZ(factorial(la.size()))))
return self._from_dict({P(m): c for m in SetPartitions(sum(la), la)}, remove_zeros=False)
class Element(CombinatorialFreeModule.Element):
'\n An element in the monomial basis of `NCSym`.\n '
def expand(self, n, alphabet='x'):
"\n Expand ``self`` written in the monomial basis in `n`\n non-commuting variables.\n\n INPUT:\n\n - ``n`` -- an integer\n - ``alphabet`` -- (default: ``'x'``) a string\n\n OUTPUT:\n\n - The symmetric function of ``self`` expressed in the ``n``\n non-commuting variables described by ``alphabet``.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: m[[1,3],[2]].expand(4)\n x0*x1*x0 + x0*x2*x0 + x0*x3*x0 + x1*x0*x1 + x1*x2*x1 + x1*x3*x1\n + x2*x0*x2 + x2*x1*x2 + x2*x3*x2 + x3*x0*x3 + x3*x1*x3 + x3*x2*x3\n\n One can use a different set of variables by using the\n optional argument ``alphabet``::\n\n sage: m[[1],[2,3]].expand(3,alphabet='y')\n y0*y1^2 + y0*y2^2 + y1*y0^2 + y1*y2^2 + y2*y0^2 + y2*y1^2\n "
from sage.algebras.free_algebra import FreeAlgebra
from sage.combinat.permutation import Permutations
m = self.parent()
F = FreeAlgebra(m.base_ring(), n, alphabet)
x = F.gens()
def on_basis(A):
basic_term = ([0] * A.size())
for (index, part) in enumerate(A):
for i in part:
basic_term[(i - 1)] = index
return sum((prod((x[(p[i] - 1)] for i in basic_term)) for p in Permutations(n, len(A))))
return m._apply_module_morphism(self, on_basis, codomain=F)
def to_symmetric_function(self):
'\n The projection of ``self`` to the symmetric functions.\n\n Take a symmetric function in non-commuting variables\n expressed in the `\\mathbf{m}` basis, and return the projection of\n expressed in the monomial basis of symmetric functions.\n\n The map `\\chi \\colon NCSym \\to Sym` is defined by\n\n .. MATH::\n\n \\mathbf{m}_A \\mapsto\n m_{\\lambda(A)} \\prod_i n_i(\\lambda(A))!\n\n where `\\lambda(A)` is the partition associated with `A` by\n taking the sizes of the parts and `n_i(\\mu)` is the\n multiplicity of `i` in `\\mu`.\n\n OUTPUT:\n\n - an element of the symmetric functions in the monomial basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctionsNonCommutingVariables(QQ).monomial()\n sage: m[[1,3],[2]].to_symmetric_function()\n m[2, 1]\n sage: m[[1],[3],[2]].to_symmetric_function()\n 6*m[1, 1, 1]\n '
m = SymmetricFunctions(self.parent().base_ring()).monomial()
c = (lambda la: prod((factorial(i) for i in la.to_exp())))
return m.sum_of_terms(((i.shape(), (coeff * c(i.shape()))) for (i, coeff) in self))
m = monomial
class elementary(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the elementary basis.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.e()).run()\n '
CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='e', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._e_to_m_on_basis, codomain=m).register_as_coercion()
p = NCSym.p()
self.module_morphism(self._e_to_p_on_basis, codomain=p, triangular='upper').register_as_coercion()
p.module_morphism(p._p_to_e_on_basis, codomain=self, triangular='upper').register_as_coercion()
h = NCSym.h()
self.module_morphism(self._e_to_h_on_basis, codomain=h, triangular='upper').register_as_coercion()
h.module_morphism(h._h_to_e_on_basis, codomain=self, triangular='upper').register_as_coercion()
@cached_method
def _e_to_m_on_basis(self, A):
'\n Return `\\mathbf{e}_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: all(e(e._e_to_m_on_basis(A)) == e[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
m = self.realization_of().m()
n = A.size()
P = SetPartitions(n)
min_elt = P([[i] for i in range(1, (n + 1))])
one = self.base_ring().one()
return m._from_dict({B: one for B in P if (A.inf(B) == min_elt)}, remove_zeros=False)
@cached_method
def _e_to_h_on_basis(self, A):
'\n Return `\\mathbf{e}_A` in terms of the homogeneous basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{h}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: all(e(e._e_to_h_on_basis(A)) == e[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
h = self.realization_of().h()
sign = (lambda B: ((- 1) ** (B.size() - len(B))))
coeff = (lambda B: (sign(B) * prod((factorial(sum((1 for part in B if part.issubset(big)))) for big in A))))
R = self.base_ring()
return h._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False)
@cached_method
def _e_to_p_on_basis(self, A):
'\n Return `\\mathbf{e}_A` in terms of the powersum basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{p}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: all(e(e._e_to_p_on_basis(A)) == e[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
p = self.realization_of().p()
coeff = (lambda B: prod([(((- 1) ** (i - 1)) * factorial((i - 1))) for i in B.shape()]))
R = self.base_ring()
return p._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False)
class Element(CombinatorialFreeModule.Element):
'\n An element in the elementary basis of `NCSym`.\n '
def omega(self):
'\n Return the involution `\\omega` applied to ``self``.\n\n The involution `\\omega` on `NCSym` is defined by\n `\\omega(\\mathbf{e}_A) = \\mathbf{h}_A`.\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: e = NCSym.e()\n sage: h = NCSym.h()\n sage: elt = e[[1,3],[2]].omega(); elt\n 2*e{{1}, {2}, {3}} - e{{1, 3}, {2}}\n sage: elt.omega()\n e{{1, 3}, {2}}\n sage: h(elt)\n h{{1, 3}, {2}}\n '
P = self.parent()
h = P.realization_of().h()
return P(h.sum_of_terms(self))
def to_symmetric_function(self):
'\n The projection of ``self`` to the symmetric functions.\n\n Take a symmetric function in non-commuting variables\n expressed in the `\\mathbf{e}` basis, and return the projection of\n expressed in the elementary basis of symmetric functions.\n\n The map `\\chi \\colon NCSym \\to Sym` is given by\n\n .. MATH::\n\n \\mathbf{e}_A \\mapsto\n e_{\\lambda(A)} \\prod_i \\lambda(A)_i!\n\n where `\\lambda(A)` is the partition associated with `A` by\n taking the sizes of the parts.\n\n OUTPUT:\n\n - An element of the symmetric functions in the elementary basis\n\n EXAMPLES::\n\n sage: e = SymmetricFunctionsNonCommutingVariables(QQ).e()\n sage: e[[1,3],[2]].to_symmetric_function()\n 2*e[2, 1]\n sage: e[[1],[3],[2]].to_symmetric_function()\n e[1, 1, 1]\n '
e = SymmetricFunctions(self.parent().base_ring()).e()
c = (lambda la: prod((factorial(i) for i in la)))
return e.sum_of_terms(((i.shape(), (coeff * c(i.shape()))) for (i, coeff) in self))
e = elementary
class homogeneous(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the homogeneous basis.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: h[[1,3],[2,4]]*h[[1,2,3]]\n h{{1, 3}, {2, 4}, {5, 6, 7}}\n sage: h[[1,2]].coproduct()\n h{} # h{{1, 2}} + 2*h{{1}} # h{{1}} + h{{1, 2}} # h{}\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.h()).run()\n '
CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='h', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._h_to_m_on_basis, codomain=m).register_as_coercion()
p = NCSym.p()
self.module_morphism(self._h_to_p_on_basis, codomain=p).register_as_coercion()
p.module_morphism(p._p_to_h_on_basis, codomain=self).register_as_coercion()
@cached_method
def _h_to_m_on_basis(self, A):
'\n Return `\\mathbf{h}_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: all(h(h._h_to_m_on_basis(A)) == h[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
P = SetPartitions()
m = self.realization_of().m()
coeff = (lambda B: prod((factorial(i) for i in B.shape())))
R = self.base_ring()
return m._from_dict({P(B): R(coeff(A.inf(B))) for B in SetPartitions(A.size())}, remove_zeros=False)
@cached_method
def _h_to_e_on_basis(self, A):
'\n Return `\\mathbf{h}_A` in terms of the elementary basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{e}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: all(h(h._h_to_e_on_basis(A)) == h[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
e = self.realization_of().e()
sign = (lambda B: ((- 1) ** (B.size() - len(B))))
coeff = (lambda B: (sign(B) * prod((factorial(sum((1 for part in B if part.issubset(big)))) for big in A))))
R = self.base_ring()
return e._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False)
@cached_method
def _h_to_p_on_basis(self, A):
'\n Return `\\mathbf{h}_A` in terms of the powersum basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{p}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: all(h(h._h_to_p_on_basis(A)) == h[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
p = self.realization_of().p()
coeff = (lambda B: abs(prod([(((- 1) ** (i - 1)) * factorial((i - 1))) for i in B.shape()])))
R = self.base_ring()
return p._from_dict({B: R(coeff(B)) for B in A.refinements()}, remove_zeros=False)
class Element(CombinatorialFreeModule.Element):
'\n An element in the homogeneous basis of `NCSym`.\n '
def omega(self):
'\n Return the involution `\\omega` applied to ``self``.\n\n The involution `\\omega` on `NCSym` is defined by\n `\\omega(\\mathbf{h}_A) = \\mathbf{e}_A`.\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: h = NCSym.h()\n sage: e = NCSym.e()\n sage: elt = h[[1,3],[2]].omega(); elt\n 2*h{{1}, {2}, {3}} - h{{1, 3}, {2}}\n sage: elt.omega()\n h{{1, 3}, {2}}\n sage: e(elt)\n e{{1, 3}, {2}}\n '
P = self.parent()
e = self.parent().realization_of().e()
return P(e.sum_of_terms(self))
def to_symmetric_function(self):
'\n The projection of ``self`` to the symmetric functions.\n\n Take a symmetric function in non-commuting variables\n expressed in the `\\mathbf{h}` basis, and return the projection of\n expressed in the complete basis of symmetric functions.\n\n The map `\\chi \\colon NCSym \\to Sym` is given by\n\n .. MATH::\n\n \\mathbf{h}_A \\mapsto\n h_{\\lambda(A)} \\prod_i \\lambda(A)_i!\n\n where `\\lambda(A)` is the partition associated with `A` by\n taking the sizes of the parts.\n\n OUTPUT:\n\n - An element of the symmetric functions in the complete basis\n\n EXAMPLES::\n\n sage: h = SymmetricFunctionsNonCommutingVariables(QQ).h()\n sage: h[[1,3],[2]].to_symmetric_function()\n 2*h[2, 1]\n sage: h[[1],[3],[2]].to_symmetric_function()\n h[1, 1, 1]\n '
h = SymmetricFunctions(self.parent().base_ring()).h()
c = (lambda la: prod((factorial(i) for i in la)))
return h.sum_of_terms(((i.shape(), (coeff * c(i.shape()))) for (i, coeff) in self))
h = homogeneous
class powersum(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the powersum basis.\n\n The powersum basis is given by\n\n .. MATH::\n\n \\mathbf{p}_A = \\sum_{A \\leq B} \\mathbf{m}_B,\n\n where we sum over all coarsenings of the set partition `A`. If we\n allow our variables to commute, then `\\mathbf{p}_A` goes to the\n usual powersum symmetric function `p_{\\lambda}` whose (integer)\n partition `\\lambda` is the shape of `A`.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: p = NCSym.p()\n\n sage: x = p.an_element()**2; x\n 4*p{} + 8*p{{1}} + 4*p{{1}, {2}} + 6*p{{1}, {2, 3}}\n + 12*p{{1, 2}} + 6*p{{1, 2}, {3}} + 9*p{{1, 2}, {3, 4}}\n sage: x.to_symmetric_function()\n 4*p[] + 8*p[1] + 4*p[1, 1] + 12*p[2] + 12*p[2, 1] + 9*p[2, 2]\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.p()).run()\n '
CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='p', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._p_to_m_on_basis, codomain=m, unitriangular='lower').register_as_coercion()
m.module_morphism(m._m_to_p_on_basis, codomain=self, unitriangular='lower').register_as_coercion()
x = NCSym.x()
self.module_morphism(self._p_to_x_on_basis, codomain=x, unitriangular='upper').register_as_coercion()
x.module_morphism(x._x_to_p_on_basis, codomain=self, unitriangular='upper').register_as_coercion()
@cached_method
def _p_to_m_on_basis(self, A):
'\n Return `\\mathbf{p}_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: p = NCSym.p()\n sage: all(p(p._p_to_m_on_basis(A)) == p[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
m = self.realization_of().m()
one = self.base_ring().one()
return m._from_dict({B: one for B in A.coarsenings()}, remove_zeros=False)
@cached_method
def _p_to_e_on_basis(self, A):
'\n Return `\\mathbf{p}_A` in terms of the elementary basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{e}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: p = NCSym.p()\n sage: all(p(p._p_to_e_on_basis(A)) == p[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
e = self.realization_of().e()
P_refine = Poset((A.refinements(), A.parent().lt))
c = prod(((((- 1) ** (i - 1)) * factorial((i - 1))) for i in A.shape()))
R = self.base_ring()
return e._from_dict({B: R((P_refine.moebius_function(B, A) / ZZ(c))) for B in P_refine}, remove_zeros=False)
@cached_method
def _p_to_h_on_basis(self, A):
'\n Return `\\mathbf{p}_A` in terms of the homogeneous basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{h}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: p = NCSym.p()\n sage: all(p(p._p_to_h_on_basis(A)) == p[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
h = self.realization_of().h()
P_refine = Poset((A.refinements(), A.parent().lt))
c = abs(prod(((((- 1) ** (i - 1)) * factorial((i - 1))) for i in A.shape())))
R = self.base_ring()
return h._from_dict({B: R((P_refine.moebius_function(B, A) / ZZ(c))) for B in P_refine}, remove_zeros=False)
@cached_method
def _p_to_x_on_basis(self, A):
'\n Return `\\mathbf{p}_A` in terms of the `\\mathbf{x}` basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - An element of the `\\mathbf{x}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: p = NCSym.p()\n sage: all(p(p._p_to_x_on_basis(A)) == p[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
x = self.realization_of().x()
one = self.base_ring().one()
return x._from_dict({B: one for B in A.refinements()}, remove_zeros=False)
def coproduct_on_basis(self, A):
'\n Return the coproduct of a monomial basis element.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - The coproduct applied to the monomial symmetric function in\n non-commuting variables indexed by ``A`` expressed in the\n monomial basis.\n\n EXAMPLES::\n\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum()\n sage: p[[1, 3], [2]].coproduct()\n p{} # p{{1, 3}, {2}} + p{{1}} # p{{1, 2}} + p{{1, 2}} # p{{1}} + p{{1, 3}, {2}} # p{}\n sage: p.coproduct_on_basis(SetPartition([[1]]))\n p{} # p{{1}} + p{{1}} # p{}\n sage: p.coproduct_on_basis(SetPartition([]))\n p{} # p{}\n '
P = SetPartitions()
if (not A):
return self.tensor_square().monomial((P([]), P([])))
if (len(A) == 1):
return self.tensor_square().sum_of_monomials([(P([]), A), (A, P([]))])
ell_set = list(range(1, (len(A) + 1)))
L = ([[[], ell_set]] + list(SetPartitions(ell_set, 2)))
def to_basis(S):
if (not S):
return P([])
sub_parts = [list(A[(i - 1)]) for i in S]
mins = [min(p) for p in sub_parts]
over_max = (max([max(p) for p in sub_parts]) + 1)
ret = [[] for _ in repeat(None, len(S))]
cur = 1
while (min(mins) != over_max):
m = min(mins)
i = mins.index(m)
ret[i].append(cur)
cur += 1
sub_parts[i].pop(sub_parts[i].index(m))
if sub_parts[i]:
mins[i] = min(sub_parts[i])
else:
mins[i] = over_max
return P(ret)
L1 = [(to_basis(S), to_basis(C)) for (S, C) in L]
L2 = [(M, N) for (N, M) in L1]
return self.tensor_square().sum_of_monomials((L1 + L2))
def internal_coproduct_on_basis(self, A):
'\n Return the internal coproduct of a powersum basis element.\n\n The internal coproduct is defined by\n\n .. MATH::\n\n \\Delta^{\\odot}(\\mathbf{p}_A) = \\mathbf{p}_A \\otimes\n \\mathbf{p}_A\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the tensor square of ``self``\n\n EXAMPLES::\n\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum()\n sage: p.internal_coproduct_on_basis(SetPartition([[1,3],[2]]))\n p{{1, 3}, {2}} # p{{1, 3}, {2}}\n '
return self.tensor_square().monomial((A, A))
def antipode_on_basis(self, A):
'\n Return the result of the antipode applied to a powersum basis element.\n\n Let `A` be a set partition. The antipode given in [LM2011]_ is\n\n .. MATH::\n\n S(\\mathbf{p}_A) = \\sum_{\\gamma} (-1)^{\\ell(\\gamma)}\n \\mathbf{p}_{\\gamma[A]}\n\n where we sum over all ordered set partitions (i.e. set\n compositions) of `[\\ell(A)]` and\n\n .. MATH::\n\n \\gamma[A] = A_{\\gamma_1}^{\\downarrow} | \\cdots |\n A_{\\gamma_{\\ell(A)}}^{\\downarrow}\n\n is the action of `\\gamma` on `A` defined in\n :meth:`SetPartition.ordered_set_partition_action()`.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum()\n sage: p.antipode_on_basis(SetPartition([[1], [2,3]]))\n p{{1, 2}, {3}}\n sage: p.antipode_on_basis(SetPartition([]))\n p{}\n sage: F = p[[1,3],[5],[2,4]].coproduct()\n sage: F.apply_multilinear_morphism(lambda x,y: x.antipode()*y)\n 0\n '
P = SetPartitions()
def action(gamma):
cur = 1
ret = []
for S in gamma:
sub_parts = [list(A[(i - 1)]) for i in S]
mins = [min(p) for p in sub_parts]
over_max = (max([max(p) for p in sub_parts]) + 1)
temp = [[] for _ in repeat(None, len(S))]
while (min(mins) != over_max):
m = min(mins)
i = mins.index(m)
temp[i].append(cur)
cur += 1
sub_parts[i].pop(sub_parts[i].index(m))
if sub_parts[i]:
mins[i] = min(sub_parts[i])
else:
mins[i] = over_max
ret += temp
return P(ret)
return self.sum_of_terms(((A.ordered_set_partition_action(gamma), ((- 1) ** len(gamma))) for gamma in OrderedSetPartitions(len(A))))
def primitive(self, A, i=1):
'\n Return the primitive associated to ``A`` in ``self``.\n\n Fix some `i \\in S`. Let `A` be an atomic set partition of `S`,\n then the primitive `p(A)` given in [LM2011]_ is\n\n .. MATH::\n\n p(A) = \\sum_{\\gamma} (-1)^{\\ell(\\gamma)-1}\n \\mathbf{p}_{\\gamma[A]}\n\n where we sum over all ordered set partitions of `[\\ell(A)]` such\n that `i \\in \\gamma_1` and `\\gamma[A]` is the action of `\\gamma`\n on `A` defined in\n :meth:`SetPartition.ordered_set_partition_action()`.\n If `A` is not atomic, then `p(A) = 0`.\n\n .. SEEALSO:: :meth:`SetPartition.is_atomic`\n\n INPUT:\n\n - ``A`` -- a set partition\n - ``i`` -- (default: 1) index in the base set for ``A`` specifying\n which set of primitives this belongs to\n\n OUTPUT:\n\n - an element in the basis ``self``\n\n EXAMPLES::\n\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).powersum()\n sage: elt = p.primitive(SetPartition([[1,3], [2]])); elt\n -p{{1, 2}, {3}} + p{{1, 3}, {2}}\n sage: elt.coproduct()\n -p{} # p{{1, 2}, {3}} + p{} # p{{1, 3}, {2}} - p{{1, 2}, {3}} # p{} + p{{1, 3}, {2}} # p{}\n sage: p.primitive(SetPartition([[1], [2,3]]))\n 0\n sage: p.primitive(SetPartition([]))\n p{}\n '
if (not A):
return self.one()
A = SetPartitions()(A)
if (not A.is_atomic()):
return self.zero()
return self.sum_of_terms(((A.ordered_set_partition_action(gamma), ((- 1) ** (len(gamma) - 1))) for gamma in OrderedSetPartitions(len(A)) if (i in gamma[0])))
class Element(CombinatorialFreeModule.Element):
'\n An element in the powersum basis of `NCSym`.\n '
def to_symmetric_function(self):
'\n The projection of ``self`` to the symmetric functions.\n\n Take a symmetric function in non-commuting variables\n expressed in the `\\mathbf{p}` basis, and return the projection of\n expressed in the powersum basis of symmetric functions.\n\n The map `\\chi \\colon NCSym \\to Sym` is given by\n\n .. MATH::\n\n \\mathbf{p}_A \\mapsto p_{\\lambda(A)}\n\n where `\\lambda(A)` is the partition associated with `A` by\n taking the sizes of the parts.\n\n OUTPUT:\n\n - an element of symmetric functions in the power sum basis\n\n EXAMPLES::\n\n sage: p = SymmetricFunctionsNonCommutingVariables(QQ).p()\n sage: p[[1,3],[2]].to_symmetric_function()\n p[2, 1]\n sage: p[[1],[3],[2]].to_symmetric_function()\n p[1, 1, 1]\n '
p = SymmetricFunctions(self.parent().base_ring()).p()
return p.sum_of_terms(((i.shape(), coeff) for (i, coeff) in self))
p = powersum
class coarse_powersum(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the `\\mathbf{cp}` basis.\n\n This basis was defined in [BZ05]_ as\n\n .. MATH::\n\n \\mathbf{cp}_A = \\sum_{A \\leq_* B} \\mathbf{m}_B,\n\n where we sum over all strict coarsenings of the set partition `A`.\n An alternative description of this basis was given in [BT13]_ as\n\n .. MATH::\n\n \\mathbf{cp}_A = \\sum_{A \\subseteq B} \\mathbf{m}_B,\n\n where we sum over all set partitions whose arcs are a subset of\n the arcs of the set partition `A`.\n\n .. NOTE::\n\n In [BZ05]_, this basis was denoted by `\\mathbf{q}`. In [BT13]_,\n this basis was called the powersum basis and denoted by `p`.\n However it is a coarser basis than the usual powersum basis in\n the sense that it does not yield the usual powersum basis\n of the symmetric function under the natural map of letting\n the variables commute.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: cp = NCSym.cp()\n sage: cp[[1,3],[2,4]]*cp[[1,2,3]]\n cp{{1, 3}, {2, 4}, {5, 6, 7}}\n sage: cp[[1,2],[3]].internal_coproduct()\n cp{{1, 2}, {3}} # cp{{1, 2}, {3}}\n sage: ps = SymmetricFunctions(NCSym.base_ring()).p()\n sage: ps(cp[[1,3],[2]].to_symmetric_function())\n p[2, 1] - p[3]\n sage: ps(cp[[1,2],[3]].to_symmetric_function())\n p[2, 1]\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.cp()).run()\n '
CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='cp', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._cp_to_m_on_basis, codomain=m, unitriangular='lower').register_as_coercion()
m.module_morphism(m._m_to_cp_on_basis, codomain=self, unitriangular='lower').register_as_coercion()
@cached_method
def _cp_to_m_on_basis(self, A):
'\n Return `\\mathbf{cp}_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: cp = NCSym.cp()\n sage: all(cp(cp._cp_to_m_on_basis(A)) == cp[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
m = self.realization_of().m()
one = self.base_ring().one()
return m._from_dict({B: one for B in A.strict_coarsenings()}, remove_zeros=False)
cp = coarse_powersum
class x_basis(NCSymBasis_abstract):
'\n The Hopf algebra of symmetric functions in non-commuting variables\n in the `\\mathbf{x}` basis.\n\n This basis is defined in [BHRZ06]_ by the formula:\n\n .. MATH::\n\n \\mathbf{x}_A = \\sum_{B \\leq A} \\mu(B, A) \\mathbf{p}_B\n\n and has the following properties:\n\n .. MATH::\n\n \\mathbf{x}_A \\mathbf{x}_B = \\mathbf{x}_{A|B}, \\quad \\quad\n \\Delta^{\\odot}(\\mathbf{x}_C) = \\sum_{A \\vee B = C} \\mathbf{x}_A\n \\otimes \\mathbf{x}_B.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: x = NCSym.x()\n sage: x[[1,3],[2,4]]*x[[1,2,3]]\n x{{1, 3}, {2, 4}, {5, 6, 7}}\n sage: x[[1,2],[3]].internal_coproduct()\n x{{1}, {2}, {3}} # x{{1, 2}, {3}} + x{{1, 2}, {3}} # x{{1}, {2}, {3}} +\n x{{1, 2}, {3}} # x{{1, 2}, {3}}\n '
def __init__(self, NCSym):
'\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: TestSuite(NCSym.x()).run()\n '
CombinatorialFreeModule.__init__(self, NCSym.base_ring(), SetPartitions(), prefix='x', bracket=False, category=MultiplicativeNCSymBases(NCSym))
@cached_method
def _x_to_p_on_basis(self, A):
'\n Return `\\mathbf{x}_A` in terms of the powersum basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\mathbf{p}` basis\n\n TESTS::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: x = NCSym.x()\n sage: all(x(x._x_to_p_on_basis(A)) == x[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n '
def lt(s, t):
if (s == t):
return False
for p in s:
if (len([z for z in t if z.intersection(p)]) != 1):
return False
return True
p = self.realization_of().p()
P_refine = Poset((A.refinements(), lt))
R = self.base_ring()
return p._from_dict({B: R(P_refine.moebius_function(B, A)) for B in P_refine})
x = x_basis
class deformed_coarse_powersum(NCSymBasis_abstract):
"\n The Hopf algebra of symmetric functions in non-commuting variables\n in the `\\rho` basis.\n\n This basis was defined in [BT13]_ as a `q`-deformation of the\n `\\mathbf{cp}` basis:\n\n .. MATH::\n\n \\rho_A = \\sum_{A \\subseteq B}\n \\frac{1}{q^{\\operatorname{nst}_{B-A}^A}} \\mathbf{m}_B,\n\n where we sum over all set partitions whose arcs are a subset of\n the arcs of the set partition `A`.\n\n INPUT:\n\n - ``q`` -- (default: ``2``) the parameter `q`\n\n EXAMPLES::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: rho = NCSym.rho(q)\n\n We construct Example 3.1 in [BT13]_::\n\n sage: rnode = lambda A: sorted([a[1] for a in A.arcs()], reverse=True)\n sage: dimv = lambda A: sorted([a[1]-a[0] for a in A.arcs()], reverse=True)\n sage: lst = list(SetPartitions(4))\n sage: S = sorted(lst, key=lambda A: (dimv(A), rnode(A)))\n sage: m = NCSym.m()\n sage: matrix([[m(rho[A])[B] for B in S] for A in S])\n [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]\n [ 0 1 0 0 1 1 0 1 0 0 1 0 0 0 0]\n [ 0 0 1 0 1 0 1 1 0 0 0 0 0 0 1]\n [ 0 0 0 1 0 1 1 1 0 0 0 1 0 0 0]\n [ 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0]\n [ 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1/q]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n "
def __init__(self, NCSym, q=2):
"\n EXAMPLES::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: TestSuite(NCSym.rho(q)).run()\n "
R = NCSym.base_ring()
self._q = R(q)
CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='rho', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._rho_to_m_on_basis, codomain=m).register_as_coercion()
m.module_morphism(self._m_to_rho_on_basis, codomain=self).register_as_coercion()
def q(self):
"\n Return the deformation parameter `q` of ``self``.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: rho = NCSym.rho(5)\n sage: rho.q()\n 5\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: rho = NCSym.rho(q)\n sage: rho.q() == q\n True\n "
return self._q
@cached_method
def _rho_to_m_on_basis(self, A):
"\n Return `\\rho_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: rho = NCSym.rho(q)\n sage: all(rho(rho._rho_to_m_on_basis(A)) == rho[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n "
m = self.realization_of().m()
arcs = set(A.arcs())
return m._from_dict({B: (self._q ** (- nesting(set(B).difference(A), A))) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False)
@cached_method
def _m_to_rho_on_basis(self, A):
"\n Return `\\mathbf{m}_A` in terms of the `\\rho` basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\rho` basis\n\n TESTS::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: rho = NCSym.rho(q)\n sage: m = NCSym.m()\n sage: all(m(rho._m_to_rho_on_basis(A)) == m[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n "
coeff = (lambda A, B: (((- 1) ** len(set(B.arcs()).difference(A.arcs()))) / (self._q ** nesting(set(B).difference(A), B))))
arcs = set(A.arcs())
return self._from_dict({B: coeff(A, B) for B in A.coarsenings() if arcs.issubset(B.arcs())}, remove_zeros=False)
rho = deformed_coarse_powersum
class supercharacter(NCSymBasis_abstract):
"\n The Hopf algebra of symmetric functions in non-commuting variables\n in the supercharacter `\\chi` basis.\n\n This basis was defined in [BT13]_ as a `q`-deformation of the\n supercharacter basis.\n\n .. MATH::\n\n \\chi_A = \\sum_B \\chi_A(B) \\mathbf{m}_B,\n\n where we sum over all set partitions `A` and `\\chi_A(B)` is the\n evaluation of the supercharacter `\\chi_A` on the superclass `\\mu_B`.\n\n .. NOTE::\n\n The supercharacters considered in [BT13]_ are coarser than\n those considered by Aguiar et. al.\n\n INPUT:\n\n - ``q`` -- (default: ``2``) the parameter `q`\n\n EXAMPLES::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: chi = NCSym.chi(q)\n sage: chi[[1,3],[2]]*chi[[1,2]]\n chi{{1, 3}, {2}, {4, 5}}\n sage: chi[[1,3],[2]].coproduct()\n chi{} # chi{{1, 3}, {2}} + (2*q-2)*chi{{1}} # chi{{1}, {2}} +\n (3*q-2)*chi{{1}} # chi{{1, 2}} + (2*q-2)*chi{{1}, {2}} # chi{{1}} +\n (3*q-2)*chi{{1, 2}} # chi{{1}} + chi{{1, 3}, {2}} # chi{}\n sage: chi2 = NCSym.chi()\n sage: chi(chi2[[1,2],[3]])\n ((-q+2)/q)*chi{{1}, {2}, {3}} + 2/q*chi{{1, 2}, {3}}\n sage: chi2\n Symmetric functions in non-commuting variables over the Fraction Field\n of Univariate Polynomial Ring in q over Rational Field in the\n supercharacter basis with parameter q=2\n "
def __init__(self, NCSym, q=2):
"\n EXAMPLES::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: TestSuite(NCSym.chi(q)).run()\n "
R = NCSym.base_ring()
self._q = R(q)
CombinatorialFreeModule.__init__(self, R, SetPartitions(), prefix='chi', bracket=False, category=MultiplicativeNCSymBases(NCSym))
m = NCSym.m()
self.module_morphism(self._chi_to_m_on_basis, codomain=m).register_as_coercion()
m.module_morphism(self._m_to_chi_on_basis, codomain=self).register_as_coercion()
def q(self):
"\n Return the deformation parameter `q` of ``self``.\n\n EXAMPLES::\n\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(QQ)\n sage: chi = NCSym.chi(5)\n sage: chi.q()\n 5\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: chi = NCSym.chi(q)\n sage: chi.q() == q\n True\n "
return self._q
@cached_method
def _chi_to_m_on_basis(self, A):
"\n Return `\\chi_A` in terms of the monomial basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\mathbf{m}` basis\n\n TESTS::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: chi = NCSym.chi(q)\n sage: all(chi(chi._chi_to_m_on_basis(A)) == chi[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n "
m = self.realization_of().m()
q = self._q
arcs = set(A.arcs())
ret = {}
for B in SetPartitions(A.size()):
Barcs = B.arcs()
if any(((((a[0] == b[0]) and (b[1] < a[1])) or ((b[0] > a[0]) and (a[1] == b[1]))) for a in arcs for b in Barcs)):
continue
ret[B] = (((((- 1) ** len(arcs.intersection(Barcs))) * ((q - 1) ** (len(arcs) - len(arcs.intersection(Barcs))))) * (q ** (sum(((a[1] - a[0]) for a in arcs)) - len(arcs)))) / (q ** nesting(B, A)))
return m._from_dict(ret, remove_zeros=False)
@cached_method
def _graded_inverse_matrix(self, n):
"\n Return the inverse of the transition matrix of the ``n``-th\n graded part from the `\\chi` basis to the monomial basis.\n\n EXAMPLES::\n\n sage: R = QQ['q'].fraction_field(); q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: chi = NCSym.chi(q); m = NCSym.m()\n sage: lst = list(SetPartitions(2))\n sage: m = matrix([[m(chi[A])[B] for A in lst] for B in lst]); m\n [ -1 1]\n [q - 1 1]\n sage: chi._graded_inverse_matrix(2)\n [ -1/q 1/q]\n [(q - 1)/q 1/q]\n sage: chi._graded_inverse_matrix(2) * m\n [1 0]\n [0 1]\n "
lst = SetPartitions(n)
MS = MatrixSpace(self.base_ring(), lst.cardinality())
m = self.realization_of().m()
m = MS([[m(self[A])[B] for A in lst] for B in lst])
return (~ m)
@cached_method
def _m_to_chi_on_basis(self, A):
"\n Return `\\mathbf{m}_A` in terms of the `\\chi` basis.\n\n INPUT:\n\n - ``A`` -- a set partition\n\n OUTPUT:\n\n - an element of the `\\chi` basis\n\n TESTS::\n\n sage: R = QQ['q'].fraction_field()\n sage: q = R.gen()\n sage: NCSym = SymmetricFunctionsNonCommutingVariables(R)\n sage: chi = NCSym.chi(q)\n sage: m = NCSym.m()\n sage: all(m(chi._m_to_chi_on_basis(A)) == m[A] for i in range(5)\n ....: for A in SetPartitions(i))\n True\n "
n = A.size()
lst = list(SetPartitions(n))
m = self._graded_inverse_matrix(n)
i = lst.index(A)
return self._from_dict({B: m[(j, i)] for (j, B) in enumerate(lst)})
chi = supercharacter
|
def Necklaces(content):
'\n Return the set of necklaces with evaluation ``content``.\n\n A necklace is a list of integers that such that the list is\n the smallest lexicographic representative of all the cyclic shifts\n of the list.\n\n .. SEEALSO::\n\n :class:`LyndonWords`\n\n INPUT:\n\n - ``content`` -- a list or tuple of non-negative integers\n\n EXAMPLES::\n\n sage: Necklaces([2,1,1])\n Necklaces with evaluation [2, 1, 1]\n sage: Necklaces([2,1,1]).cardinality()\n 3\n sage: Necklaces([2,1,1]).first()\n [1, 1, 2, 3]\n sage: Necklaces([2,1,1]).last()\n [1, 2, 1, 3]\n sage: Necklaces([2,1,1]).list()\n [[1, 1, 2, 3], [1, 1, 3, 2], [1, 2, 1, 3]]\n sage: Necklaces([0,2,1,1]).list()\n [[2, 2, 3, 4], [2, 2, 4, 3], [2, 3, 2, 4]]\n sage: Necklaces([2,0,1,1]).list()\n [[1, 1, 3, 4], [1, 1, 4, 3], [1, 3, 1, 4]]\n '
return Necklaces_evaluation(content)
|
class Necklaces_evaluation(UniqueRepresentation, Parent):
'\n Necklaces with a fixed evaluation (content).\n\n INPUT:\n\n - ``content`` -- a list or tuple of non-negative integers\n '
@staticmethod
def __classcall_private__(cls, content):
'\n Return the correct parent object, with standardized parameters.\n\n EXAMPLES::\n\n sage: Necklaces([2,1,1]) is Necklaces(Composition([2,1,1]))\n True\n '
if (not isinstance(content, Composition)):
content = Composition(content)
return super().__classcall__(cls, content)
def __init__(self, content):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: N = Necklaces([2,2,2])\n sage: N == loads(dumps(N))\n True\n sage: T = Necklaces([2,1])\n sage: TestSuite(T).run()\n '
self._content = content
Parent.__init__(self, category=FiniteEnumeratedSets())
def content(self):
'\n Return the content (or evaluation) of the necklaces.\n\n EXAMPLES::\n\n sage: N = Necklaces([2,2,2])\n sage: N.content()\n [2, 2, 2]\n '
return self._content
def __repr__(self) -> str:
"\n TESTS::\n\n sage: repr(Necklaces([2,1,1]))\n 'Necklaces with evaluation [2, 1, 1]'\n "
return ('Necklaces with evaluation %s' % self._content)
def __contains__(self, x) -> bool:
'\n Return ``True`` if ``x`` is the smallest word of all its cyclic shifts\n and the content vector of ``x`` is equal to ``content``.\n\n INPUT:\n\n - ``x`` -- a list of integers\n\n EXAMPLES::\n\n sage: [2,1,2,1] in Necklaces([2,2])\n False\n sage: [1,2,1,2] in Necklaces([2,2])\n True\n sage: [1,1,2,2] in Necklaces([2,2])\n True\n sage: [1,2,2,2] in Necklaces([2,2])\n False\n sage: all(n in Necklaces([2,1,3,1]) for n in Necklaces([2,1,3,1]))\n True\n sage: all(n in Necklaces([0,1,2,3]) for n in Necklaces([0,1,2,3]))\n True\n '
xl = list(x)
e = ([0] * len(self._content))
if (len(xl) != sum(self._content)):
return False
for i in xl:
if (not isinstance(i, (int, Integer))):
return False
if (i <= 0):
return False
if (i > len(self._content)):
return False
e[(i - 1)] += 1
if (e != self._content):
return False
cyclic_shift = xl[:]
for i in range((len(xl) - 1)):
cyclic_shift = (cyclic_shift[1:] + cyclic_shift[:1])
if (cyclic_shift < xl):
return False
return True
def cardinality(self) -> Integer:
'\n Return the number of integer necklaces with the evaluation ``content``.\n\n The formula for the number of necklaces of content `\\alpha`\n a composition of `n` is:\n\n .. MATH::\n\n \\sum_{d|gcd(\\alpha)} \\phi(d)\n \\binom{n/d}{\\alpha_1/d, \\ldots, \\alpha_\\ell/d},\n\n where `\\phi(d)` is the Euler `\\phi` function.\n\n EXAMPLES::\n\n sage: Necklaces([]).cardinality()\n 0\n sage: Necklaces([2,2]).cardinality()\n 2\n sage: Necklaces([2,3,2]).cardinality()\n 30\n sage: Necklaces([0,3,2]).cardinality()\n 2\n\n Check to make sure that the count matches up with the number of\n necklace words generated.\n\n ::\n\n sage: comps = [[],[2,2],[3,2,7],[4,2],[0,4,2],[2,0,4]]+Compositions(4).list()\n sage: ns = [Necklaces(comp) for comp in comps]\n sage: all(n.cardinality() == len(n.list()) for n in ns) # needs sage.libs.pari\n True\n '
evaluation = self._content
le = list(evaluation)
if (not le):
return ZZ.zero()
n = sum(le)
return (ZZ.sum((((euler_phi(j) * factorial((n // j))) // prod((factorial((ni // j)) for ni in evaluation))) for j in divisors(gcd(le)))) // n)
def __iter__(self):
'\n An iterator for the integer necklaces with evaluation ``content``.\n\n EXAMPLES::\n\n sage: Necklaces([]).list() #indirect test\n []\n sage: Necklaces([1]).list() #indirect test\n [[1]]\n sage: Necklaces([2]).list() #indirect test\n [[1, 1]]\n sage: Necklaces([3]).list() #indirect test\n [[1, 1, 1]]\n sage: Necklaces([3,3]).list() #indirect test\n [[1, 1, 1, 2, 2, 2],\n [1, 1, 2, 1, 2, 2],\n [1, 1, 2, 2, 1, 2],\n [1, 2, 1, 2, 1, 2]]\n sage: Necklaces([2,1,3]).list() #indirect test\n [[1, 1, 2, 3, 3, 3],\n [1, 1, 3, 2, 3, 3],\n [1, 1, 3, 3, 2, 3],\n [1, 1, 3, 3, 3, 2],\n [1, 2, 1, 3, 3, 3],\n [1, 2, 3, 1, 3, 3],\n [1, 2, 3, 3, 1, 3],\n [1, 3, 1, 3, 2, 3],\n [1, 3, 1, 3, 3, 2],\n [1, 3, 2, 1, 3, 3]]\n '
if (not self._content):
return
k = 0
while (not self._content[k]):
k += 1
for z in _sfc(self._content[k:]):
(yield [((x + 1) + k) for x in z])
|
def _ffc(content, equality=False):
'\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _ffc\n sage: list(_ffc([3,3])) #necklaces\n [[0, 1, 0, 1, 0, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 0, 1, 1, 1]]\n sage: list(_ffc([3,3], equality=True)) #Lyndon words\n [[0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 1, 1]]\n '
e = list(content)
a = ([(len(e) - 1)] * sum(e))
r = ([0] * sum(e))
a[0] = 0
e[0] -= 1
k = len(e)
rng_k = list(range(k))
rng_k.reverse()
dll = DoublyLinkedList(rng_k)
if (not e[0]):
dll.hide(0)
(yield from _fast_fixed_content(a, e, 2, 1, k, r, 2, dll, equality=equality))
|
def _fast_fixed_content(a, content, t, p, k, r, s, dll, equality=False):
'\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _fast_fixed_content\n sage: from sage.combinat.misc import DoublyLinkedList\n sage: e = [3,3]\n sage: a = [len(e)-1]*sum(e)\n sage: r = [0]*sum(e)\n sage: a[0] = 0\n sage: e[0] -= 1\n sage: k = len(e)\n sage: dll = DoublyLinkedList(list(reversed(range(k))))\n sage: if e[0] == 0: dll.hide(0)\n sage: list(_fast_fixed_content(a,e,2,1,k,r,2,dll))\n [[0, 1, 0, 1, 0, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 0, 1, 1, 1]]\n sage: list(_fast_fixed_content(a,e,2,1,k,r,2,dll,True))\n [[0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 1, 1]]\n '
n = len(a)
if (content[(k - 1)] == ((n - t) + 1)):
if (content[(k - 1)] == r[((t - p) - 1)]):
if equality:
if (n == p):
(yield a)
elif (not (n % p)):
(yield a)
elif (content[(k - 1)] > r[((t - p) - 1)]):
(yield a)
elif (content[0] != ((n - t) + 1)):
j = dll.head()
sp = s
while ((j != 'end') and (j >= a[((t - p) - 1)])):
r[(s - 1)] = (t - s)
a[(t - 1)] = j
content[j] -= 1
if (not content[j]):
dll.hide(j)
if (j != (k - 1)):
sp = (t + 1)
if (j == a[((t - p) - 1)]):
(yield from _fast_fixed_content(a[:], content, (t + 1), p, k, r, sp, dll, equality=equality))
else:
(yield from _fast_fixed_content(a[:], content, (t + 1), t, k, r, sp, dll, equality=equality))
if (not content[j]):
dll.unhide(j)
content[j] += 1
j = dll.next(j)
a[(t - 1)] = (k - 1)
return
|
def _lfc(content, equality=False):
'\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _lfc\n sage: list(_lfc([3,3])) #necklaces\n [[0, 1, 0, 1, 0, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 0, 1, 1, 1]]\n sage: list(_lfc([3,3], equality=True)) #Lyndon words\n [[0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 1, 1]]\n '
content = list(content)
a = ([0] * sum(content))
content[0] -= 1
k = len(content)
rng_k = list(range(k))
rng_k.reverse()
dll = DoublyLinkedList(rng_k)
if (not content[0]):
dll.hide(0)
(yield from _list_fixed_content(a, content, 2, 1, k, dll, equality=equality))
|
def _list_fixed_content(a, content, t, p, k, dll, equality=False):
'\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _list_fixed_content\n sage: from sage.combinat.misc import DoublyLinkedList\n sage: e = [3,3]\n sage: a = [0]*sum(e)\n sage: e[0] -= 1\n sage: k = len(e)\n sage: dll = DoublyLinkedList(list(reversed(range(k))))\n sage: if e[0] == 0: dll.hide(0)\n sage: list(_list_fixed_content(a,e,2,1,k,dll))\n [[0, 1, 0, 1, 0, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 0, 1, 1, 1]]\n sage: list(_list_fixed_content(a,e,2,1,k,dll,True))\n [[0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 0, 0, 1, 1, 1]]\n '
n = len(a)
if (t > n):
if equality:
if (n == p):
(yield a)
elif (not (n % p)):
(yield a)
else:
j = dll.head()
while ((j != 'end') and (j >= a[((t - p) - 1)])):
a[(t - 1)] = j
content[j] -= 1
if (not content[j]):
dll.hide(j)
if (j == a[((t - p) - 1)]):
(yield from _list_fixed_content(a[:], content[:], (t + 1), p, k, dll, equality=equality))
else:
(yield from _list_fixed_content(a[:], content[:], (t + 1), t, k, dll, equality=equality))
if (not content[j]):
dll.unhide(j)
content[j] += 1
j = dll.next(j)
|
def _sfc(content, equality=False):
"\n This wrapper function calls :meth:`sage.combinat.necklace._simple_fixed_content`.\n If ``equality`` is ``True`` the function returns Lyndon words with content\n vector equal to ``content``, otherwise it returns necklaces.\n\n INPUT:\n\n - ``content`` -- a list of non-negative integers with no leading 0s\n - ``equality`` -- boolean (optional, default: ``True``)\n\n .. WARNING::\n\n You will get incorrect results if there are leading 0's in ``content``.\n See :trac:`12997` and :trac:`17436`.\n\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _sfc\n sage: list(_sfc([3,3])) #necklaces\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 1, 0, 1, 0, 1]]\n sage: list(_sfc([3,3], equality=True)) #Lyndon words\n [[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1]]\n "
content = list(content)
a = ([0] * sum(content))
content[0] -= 1
k = len(content)
return _simple_fixed_content(a, content, 2, 1, k, equality=equality)
|
def _simple_fixed_content(a, content, t, p, k, equality=False):
'\n EXAMPLES::\n\n sage: from sage.combinat.necklace import _simple_fixed_content\n sage: content = [3,3]\n sage: a = [0]*sum(content)\n sage: content[0] -= 1\n sage: k = len(content); k\n 2\n sage: list(_simple_fixed_content(a, content, 2, 1, k))\n [[0, 0, 0, 1, 1, 1],\n [0, 0, 1, 0, 1, 1],\n [0, 0, 1, 1, 0, 1],\n [0, 1, 0, 1, 0, 1]]\n sage: list(_simple_fixed_content(a, content, 2, 1, k, True))\n [[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1]]\n '
n = len(a)
if (t > n):
if equality:
if (n == p):
(yield a)
elif (not (n % p)):
(yield a)
else:
r = list(range(a[((t - p) - 1)], k))
for j in r:
if (content[j] > 0):
a[(t - 1)] = j
content[j] -= 1
if (j == a[((t - p) - 1)]):
(yield from _simple_fixed_content(a[:], content, (t + 1), p, k, equality=equality))
else:
(yield from _simple_fixed_content(a[:], content, (t + 1), t, k, equality=equality))
content[j] += 1
|
def _lyn(w):
'\n Return the length of the longest prefix of ``w`` that is a Lyndon word.\n\n EXAMPLES::\n\n sage: import sage.combinat.necklace as necklace\n sage: necklace._lyn([0,1,1,0,0,1,2])\n 3\n sage: necklace._lyn([0,0,0,1])\n 4\n sage: necklace._lyn([2,1,0,0,2,2,1])\n 1\n '
p = 1
k = (max(w) + 1)
for i in range(1, len(w)):
b = w[i]
a = w[:i]
if ((b < a[(i - p)]) or (b > (k - 1))):
return p
elif (b == a[(i - p)]):
pass
else:
p = (i + 1)
return p
|
def NonDecreasingParkingFunctions(n=None):
'\n Return the set of Non-Decreasing Parking Functions.\n\n A *non-decreasing parking function* of size `n` is a non-decreasing\n function `f` from `\\{1,\\dots,n\\}` to itself such that for all `i`,\n one has `f(i) \\leq i`.\n\n EXAMPLES:\n\n Here are all the-non decreasing parking functions of size 5::\n\n sage: NonDecreasingParkingFunctions(3).list()\n [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3]]\n\n If no size is specified, then NonDecreasingParkingFunctions\n returns the set of all non-decreasing parking functions.\n\n ::\n\n sage: PF = NonDecreasingParkingFunctions(); PF\n Non-decreasing parking functions\n sage: [] in PF\n True\n sage: [1] in PF\n True\n sage: [2] in PF\n False\n sage: [1,1,3] in PF\n True\n sage: [1,1,4] in PF\n False\n\n If the size `n` is specified, then NonDecreasingParkingFunctions returns\n the set of all non-decreasing parking functions of size `n`.\n\n ::\n\n sage: PF = NonDecreasingParkingFunctions(0)\n sage: PF.list()\n [[]]\n sage: PF = NonDecreasingParkingFunctions(1)\n sage: PF.list()\n [[1]]\n sage: PF = NonDecreasingParkingFunctions(3)\n sage: PF.list()\n [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3]]\n\n sage: PF3 = NonDecreasingParkingFunctions(3); PF3\n Non-decreasing parking functions of size 3\n sage: [] in PF3\n False\n sage: [1] in PF3\n False\n sage: [1,1,3] in PF3\n True\n sage: [1,1,4] in PF3\n False\n\n TESTS::\n\n sage: PF = NonDecreasingParkingFunctions(5)\n sage: len(PF.list()) == PF.cardinality()\n True\n sage: NonDecreasingParkingFunctions("foo")\n Traceback (most recent call last):\n ...\n TypeError: unable to convert \'foo\' to an integer\n '
if (n is None):
return NonDecreasingParkingFunctions_all()
else:
return NonDecreasingParkingFunctions_n(n)
|
def is_a(x, n=None) -> bool:
'\n Check whether a list is a non-decreasing parking function.\n\n If a size `n` is specified, checks if a list is a non-decreasing\n parking function of size `n`.\n\n TESTS::\n\n sage: from sage.combinat.non_decreasing_parking_function import is_a\n sage: is_a([1,1,2])\n True\n sage: is_a([1,1,4])\n False\n sage: is_a([1,1,3], 3)\n True\n '
if (not isinstance(x, (list, tuple))):
return False
prev = 1
for (i, elt) in enumerate(x):
if ((prev > elt) or (elt > (i + 1))):
return False
prev = elt
return ((n is None) or (n == len(x)))
|
class NonDecreasingParkingFunction(Element):
'\n A *non decreasing parking function* of size `n` is a non-decreasing\n function `f` from `\\{1,\\dots,n\\}` to itself such that for all `i`,\n one has `f(i) \\leq i`.\n\n EXAMPLES::\n\n sage: NonDecreasingParkingFunction([])\n []\n sage: NonDecreasingParkingFunction([1])\n [1]\n sage: NonDecreasingParkingFunction([2])\n Traceback (most recent call last):\n ...\n ValueError: [2] is not a non-decreasing parking function\n sage: NonDecreasingParkingFunction([1,2])\n [1, 2]\n sage: NonDecreasingParkingFunction([1,1,2])\n [1, 1, 2]\n sage: NonDecreasingParkingFunction([1,1,4])\n Traceback (most recent call last):\n ...\n ValueError: [1, 1, 4] is not a non-decreasing parking function\n '
def __init__(self, lst):
'\n TESTS::\n\n sage: NonDecreasingParkingFunction([1, 1, 2, 2, 5, 6])\n [1, 1, 2, 2, 5, 6]\n '
if (not is_a(lst)):
raise ValueError(('%s is not a non-decreasing parking function' % lst))
parent = NonDecreasingParkingFunctions_n(len(lst))
Element.__init__(self, parent)
self._list = lst
def __getitem__(self, n):
'\n Return the `n^{th}` item in the underlying list.\n\n .. note::\n\n Note that this is different than the image of ``n`` under\n function. It is "off by one".\n\n EXAMPLES::\n\n sage: p = NonDecreasingParkingFunction([1, 1, 2, 2, 5, 6])\n sage: p[0]\n 1\n sage: p[2]\n 2\n '
return self._list[n]
def __call__(self, n):
'\n Return the image of ``n`` under the parking function.\n\n EXAMPLES::\n\n sage: p = NonDecreasingParkingFunction([1, 1, 2, 2, 5, 6])\n sage: p(3)\n 2\n sage: p(6)\n 6\n '
return self._list[(n - 1)]
def _mul_(self, lp) -> NonDecreasingParkingFunction:
'\n The composition of non-decreasing parking functions.\n\n EXAMPLES::\n\n sage: p = NonDecreasingParkingFunction([1,1,3])\n sage: q = NonDecreasingParkingFunction([1,2,2])\n sage: p * q\n [1, 1, 1]\n sage: q * p\n [1, 1, 2]\n '
lp = lp._list
sp = self._list
lp = (lp[:] + [(i + 1) for i in range(len(lp), len(lp))])
sp = (sp[:] + [(i + 1) for i in range(len(sp), len(lp))])
return NonDecreasingParkingFunction([sp[(i - 1)] for i in lp])
def to_dyck_word(self):
'\n Implement the bijection to :class:`Dyck\n words<sage.combinat.dyck_word.DyckWords>`, which is defined as follows.\n Take a non decreasing parking function, say [1,1,2,4,5,5], and draw\n its graph::\n\n ___\n | . 5\n _| . 5\n ___| . . 4\n _| . . . . 2\n | . . . . . 1\n | . . . . . 1\n\n The corresponding Dyck word [1,1,0,1,0,0,1,0,1,1,0,0] is then read off\n from the sequence of horizontal and vertical steps. The converse\n bijection is :meth:`.from_dyck_word`.\n\n EXAMPLES::\n\n sage: NonDecreasingParkingFunction([1,1,2,4,5,5]).to_dyck_word()\n [1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0]\n sage: NonDecreasingParkingFunction([]).to_dyck_word()\n []\n sage: NonDecreasingParkingFunction([1,1,1]).to_dyck_word()\n [1, 1, 1, 0, 0, 0]\n sage: NonDecreasingParkingFunction([1,2,3]).to_dyck_word()\n [1, 0, 1, 0, 1, 0]\n sage: NonDecreasingParkingFunction([1,1,3,3,4,6,6]).to_dyck_word()\n [1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0]\n\n TESTS::\n\n sage: ndpf = NonDecreasingParkingFunctions(5)\n sage: list(ndpf) == [pf.to_dyck_word().to_non_decreasing_parking_function() for pf in ndpf]\n True\n '
from sage.combinat.dyck_word import CompleteDyckWords_all
return CompleteDyckWords_all().from_non_decreasing_parking_function(self)
def __len__(self) -> int:
'\n Return the length of ``self``.\n\n EXAMPLES::\n\n sage: ndpf = NonDecreasingParkingFunctions(5)\n sage: len(ndpf.random_element())\n 5\n '
return len(self._list)
grade = __len__
def _repr_(self) -> str:
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: NonDecreasingParkingFunction([1,1,1])\n [1, 1, 1]\n '
return str(self._list)
def _richcmp_(self, other, op) -> bool:
'\n Compare ``self`` with ``other``.\n\n EXAMPLES::\n\n sage: a = NonDecreasingParkingFunction([1,1,1])\n sage: b = NonDecreasingParkingFunction([1,1,2])\n sage: a == b, a < b, b <= a\n (False, True, False)\n '
return richcmp(self._list, other._list, op)
def __hash__(self) -> int:
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: a = NonDecreasingParkingFunction([1,1,1])\n sage: b = NonDecreasingParkingFunction([1,1,2])\n sage: hash(a) == hash(b)\n False\n '
return hash(tuple(self._list))
@classmethod
def from_dyck_word(cls, dw) -> NonDecreasingParkingFunction:
'\n Bijection from :class:`Dyck\n words<sage.combinat.dyck_word.DyckWords>`. It is the inverse of the\n bijection :meth:`.to_dyck_word`. You can find there the mathematical\n definition.\n\n EXAMPLES::\n\n sage: NonDecreasingParkingFunction.from_dyck_word([])\n []\n sage: NonDecreasingParkingFunction.from_dyck_word([1,0])\n [1]\n sage: NonDecreasingParkingFunction.from_dyck_word([1,1,0,0])\n [1, 1]\n sage: NonDecreasingParkingFunction.from_dyck_word([1,0,1,0])\n [1, 2]\n sage: NonDecreasingParkingFunction.from_dyck_word([1,0,1,1,0,1,0,0,1,0])\n [1, 2, 2, 3, 5]\n\n TESTS::\n\n sage: ndpf = NonDecreasingParkingFunctions(5)\n sage: list(ndpf) == [NonDecreasingParkingFunction.from_dyck_word(pf.to_dyck_word()) for pf in ndpf]\n True\n '
res = []
val = 1
for i in dw:
if (i == 0):
val += 1
else:
res.append(val)
return cls(res)
|
class NonDecreasingParkingFunctions_all(UniqueRepresentation, Parent):
def __init__(self):
'\n TESTS::\n\n sage: PF = NonDecreasingParkingFunctions()\n sage: PF == loads(dumps(PF))\n True\n '
cat = (InfiniteEnumeratedSets() & SetsWithGrading())
Parent.__init__(self, category=cat)
def __repr__(self) -> str:
"\n TESTS::\n\n sage: repr(NonDecreasingParkingFunctions())\n 'Non-decreasing parking functions'\n "
return 'Non-decreasing parking functions'
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: [] in NonDecreasingParkingFunctions()\n True\n sage: [1] in NonDecreasingParkingFunctions()\n True\n sage: [2] in NonDecreasingParkingFunctions()\n False\n sage: [1,1,3] in NonDecreasingParkingFunctions()\n True\n sage: [1,1,4] in NonDecreasingParkingFunctions()\n False\n '
if isinstance(x, NonDecreasingParkingFunction):
return True
return is_a(x)
def __iter__(self):
'\n An iterator\n\n TESTS::\n\n sage: it = iter(NonDecreasingParkingFunctions()) # indirect doctest\n sage: [next(it) for i in range(8)]\n [[], [1], [1, 1], [1, 2], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2]]\n '
for n in NN:
(yield from NonDecreasingParkingFunctions_n(n))
def graded_component(self, n):
'\n Return the graded component.\n\n EXAMPLES::\n\n sage: P = NonDecreasingParkingFunctions()\n sage: P.graded_component(4) == NonDecreasingParkingFunctions(4)\n True\n '
return NonDecreasingParkingFunctions_n(n)
|
class NonDecreasingParkingFunctions_n(UniqueRepresentation, Parent):
'\n The combinatorial class of non-decreasing parking functions of\n size `n`.\n\n A *non-decreasing parking function* of size `n` is a non-decreasing\n function `f` from `\\{1,\\dots,n\\}` to itself such that for all `i`,\n one has `f(i) \\leq i`.\n\n The number of non-decreasing parking functions of size `n` is the\n `n`-th Catalan number.\n\n EXAMPLES::\n\n sage: PF = NonDecreasingParkingFunctions(3)\n sage: PF.list()\n [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3]]\n sage: PF = NonDecreasingParkingFunctions(4)\n sage: PF.list()\n [[1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 1, 3], [1, 1, 1, 4], [1, 1, 2, 2], [1, 1, 2, 3], [1, 1, 2, 4], [1, 1, 3, 3], [1, 1, 3, 4], [1, 2, 2, 2], [1, 2, 2, 3], [1, 2, 2, 4], [1, 2, 3, 3], [1, 2, 3, 4]]\n sage: [ NonDecreasingParkingFunctions(i).cardinality() for i in range(10)]\n [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]\n\n .. warning::\n\n The precise order in which the parking function are generated or\n listed is not fixed, and may change in the future.\n\n AUTHORS:\n\n - Florent Hivert\n '
def __init__(self, n):
"\n TESTS::\n\n sage: PF = NonDecreasingParkingFunctions(3)\n sage: PF == loads(dumps(PF))\n True\n sage: TestSuite(PF).run(skip='_test_elements')\n "
n = Integer(n)
if (n < 0):
raise ValueError(('%s is not a non-negative integer' % n))
self.n = n
Parent.__init__(self, category=Monoids().Enumerated().Finite())
def __repr__(self) -> str:
"\n TESTS::\n\n sage: repr(NonDecreasingParkingFunctions(3))\n 'Non-decreasing parking functions of size 3'\n "
return ('Non-decreasing parking functions of size %s' % self.n)
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: PF3 = NonDecreasingParkingFunctions(3); PF3\n Non-decreasing parking functions of size 3\n sage: [] in PF3\n False\n sage: [1] in PF3\n False\n sage: [1,1,3] in PF3\n True\n sage: [1,1,1] in PF3\n True\n sage: [1,1,4] in PF3\n False\n sage: all(p in PF3 for p in PF3)\n True\n '
if isinstance(x, NonDecreasingParkingFunction):
return True
return is_a(x, self.n)
def cardinality(self) -> Integer:
'\n Return the number of non-decreasing parking functions of size\n `n`.\n\n This number is the `n`-th :func:`Catalan\n number<sage.combinat.combinat.catalan_number>`.\n\n EXAMPLES::\n\n sage: PF = NonDecreasingParkingFunctions(0)\n sage: PF.cardinality()\n 1\n sage: PF = NonDecreasingParkingFunctions(1)\n sage: PF.cardinality()\n 1\n sage: PF = NonDecreasingParkingFunctions(3)\n sage: PF.cardinality()\n 5\n sage: PF = NonDecreasingParkingFunctions(5)\n sage: PF.cardinality()\n 42\n '
return catalan_number(self.n)
def random_element(self) -> NonDecreasingParkingFunction:
'\n Return a random parking function of the given size.\n\n EXAMPLES::\n\n sage: ndpf = NonDecreasingParkingFunctions(5)\n sage: x = ndpf.random_element(); x # random\n [1, 2, 2, 4, 5]\n sage: x in ndpf\n True\n '
from sage.combinat.dyck_word import DyckWords
n = self.n
dw = DyckWords(n).random_element()
return NonDecreasingParkingFunction.from_dyck_word(dw)
def one(self) -> NonDecreasingParkingFunction:
'\n Return the unit of this monoid.\n\n This is the non-decreasing parking function [1, 2, ..., n].\n\n EXAMPLES::\n\n sage: ndpf = NonDecreasingParkingFunctions(5)\n sage: x = ndpf.random_element(); x # random\n sage: e = ndpf.one()\n sage: x == e*x == x*e\n True\n '
return NonDecreasingParkingFunction(list(range(1, (self.n + 1))))
def __iter__(self):
'\n Return an iterator for non-decreasing parking functions of size `n`.\n\n .. warning::\n\n The precise order in which the parking function are\n generated is not fixed, and may change in the future.\n\n EXAMPLES::\n\n sage: PF = NonDecreasingParkingFunctions(0)\n sage: [e for e in PF] # indirect doctest\n [[]]\n sage: PF = NonDecreasingParkingFunctions(1)\n sage: [e for e in PF] # indirect doctest\n [[1]]\n sage: PF = NonDecreasingParkingFunctions(3)\n sage: [e for e in PF] # indirect doctest\n [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 2, 3]]\n sage: PF = NonDecreasingParkingFunctions(4)\n sage: [e for e in PF] # indirect doctest\n [[1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 1, 3], [1, 1, 1, 4], [1, 1, 2, 2], [1, 1, 2, 3], [1, 1, 2, 4], [1, 1, 3, 3], [1, 1, 3, 4], [1, 2, 2, 2], [1, 2, 2, 3], [1, 2, 2, 4], [1, 2, 3, 3], [1, 2, 3, 4]]\n\n TESTS::\n\n sage: PF = NonDecreasingParkingFunctions(5)\n sage: [e for e in PF] == PF.list()\n True\n sage: PF = NonDecreasingParkingFunctions(6)\n sage: [e for e in PF] == PF.list()\n True\n\n Complexity: constant amortized time.\n '
def iterator_rec(n):
'\n TESTS::\n\n sage: PF = NonDecreasingParkingFunctions(2)\n sage: [e for e in PF] # indirect doctest\n [[1, 1], [1, 2]]\n '
if (n == 0):
(yield [])
return
if (n == 1):
(yield [1])
return
for res1 in iterator_rec((n - 1)):
for i in range(res1[(- 1)], (n + 1)):
res = copy(res1)
res.append(i)
(yield res)
return
for res in iterator_rec(self.n):
(yield NonDecreasingParkingFunction(res))
return
Element = NonDecreasingParkingFunction
|
def update_ndw_symbols(os, cs):
"\n A way to alter the open and close symbols from sage.\n\n INPUT:\n\n - ``os`` -- the open symbol\n - ``cs`` -- the close symbol\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_dyck_word import update_ndw_symbols\n sage: update_ndw_symbols(0,1)\n sage: dw = NuDyckWord('0101001','0110010'); dw\n [0, 1, 0, 1, 0, 0, 1]\n\n sage: dw = NuDyckWord('1010110','1001101'); dw\n Traceback (most recent call last):\n ...\n ValueError: invalid nu-Dyck word\n sage: update_ndw_symbols(1,0)\n "
global ndw_open_symbol
global ndw_close_symbol
ndw_open_symbol = os
ndw_close_symbol = cs
|
def replace_dyck_char(x):
"\n A map sending an opening character (``'1'``, ``'N'``, and ``'('``) to\n ``ndw_open_symbol``, a closing character (``'0'``, ``'E'``, and ``')'``) to\n ``ndw_close_symbol``, and raising an error on any input other than one of\n the opening or closing characters.\n\n This is the inverse map of :func:`replace_dyck_symbol`.\n\n INPUT:\n\n - ``x`` -- str - A ``'1'``, ``'0'``, ``'N'``, ``'E'``, ``'('`` or ``')'``\n\n OUTPUT:\n\n - If ``x`` is an opening character, replace ``x`` with the\n constant ``ndw_open_symbol``.\n\n - If ``x`` is a closing character, replace ``x`` with the\n constant ``ndw_close_symbol``.\n\n - Raise a :class:`ValueError` if ``x`` is neither an opening nor a\n closing character.\n\n .. SEEALSO:: :func:`replace_dyck_symbol`\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_dyck_word import replace_dyck_char\n sage: replace_dyck_char('(')\n 1\n sage: replace_dyck_char(')')\n 0\n sage: replace_dyck_char(1)\n Traceback (most recent call last):\n ...\n ValueError\n "
if ((x == '(') or (x == 'N') or (x == str(ndw_open_symbol))):
return ndw_open_symbol
if ((x == ')') or (x == 'E') or (x == str(ndw_close_symbol))):
return ndw_close_symbol
raise ValueError
|
def replace_dyck_symbol(x, open_char='N', close_char='E') -> str:
"\n A map sending ``ndw_open_symbol`` to ``open_char`` and ``ndw_close_symbol``\n to ``close_char``, and raising an error on any input other than\n ``ndw_open_symbol`` and ``ndw_close_symbol``. The values of the constants\n ``ndw_open_symbol`` and ``ndw_close_symbol`` are subject to change.\n\n This is the inverse map of :func:`replace_dyck_char`.\n\n INPUT:\n\n - ``x`` -- either ``ndw_open_symbol`` or ``ndw_close_symbol``.\n\n - ``open_char`` -- str (optional) default ``'N'``\n\n - ``close_char`` -- str (optional) default ``'E'``\n\n OUTPUT:\n\n - If ``x`` is ``ndw_open_symbol``, replace ``x`` with ``open_char``.\n\n - If ``x`` is ``ndw_close_symbol``, replace ``x`` with ``close_char``.\n\n - If ``x`` is neither ``ndw_open_symbol`` nor ``ndw_close_symbol``, a\n :class:`ValueError` is raised.\n\n .. SEEALSO:: :func:`replace_dyck_char`\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_dyck_word import replace_dyck_symbol\n sage: replace_dyck_symbol(1)\n 'N'\n sage: replace_dyck_symbol(0)\n 'E'\n sage: replace_dyck_symbol(3)\n Traceback (most recent call last):\n ...\n ValueError\n "
if (x == ndw_open_symbol):
return open_char
if (x == ndw_close_symbol):
return close_char
raise ValueError
|
class NuDyckWord(CombinatorialElement):
"\n A `\\nu`-Dyck word.\n\n Given a lattice path `\\nu` in the `\\ZZ^2` grid starting at the origin\n `(0,0)` consisting of North `N = (0,1)` and East `E = (1,0)` steps, a\n `\\nu`-Dyck path is a lattice path in the `\\ZZ^2` grid starting at the\n origin `(0,0)` and ending at the same coordinate as `\\nu` such that it is\n weakly above `\\nu`. A `\\nu`-Dyck word is the representation of a\n `\\nu`-Dyck path where a North step is represented by a 1 and an East step\n is represented by a 0.\n\n INPUT:\n\n - k1 -- A path for the `\\nu`-Dyck word\n\n - k2 -- A path for `\\nu`\n\n EXAMPLES::\n\n sage: dw = NuDyckWord([1,0,1,0],[1,0,0,1]); dw\n [1, 0, 1, 0]\n sage: print(dw)\n NENE\n sage: dw.height()\n 2\n\n sage: dw = NuDyckWord('1010',[1,0,0,1]); dw\n [1, 0, 1, 0]\n\n sage: dw = NuDyckWord('NENE',[1,0,0,1]); dw\n [1, 0, 1, 0]\n\n sage: NuDyckWord([1,0,1,0],[1,0,0,1]).pretty_print()\n __\n _|x\n | . .\n\n sage: from sage.combinat.nu_dyck_word import update_ndw_symbols\n sage: update_ndw_symbols(0,1)\n sage: dw = NuDyckWord('0101001','0110010'); dw\n [0, 1, 0, 1, 0, 0, 1]\n sage: dw.pp()\n __\n |x\n _| .\n _|x .\n | . . .\n sage: update_ndw_symbols(1,0)\n "
@staticmethod
def __classcall_private__(cls, dw=None, nu=None, **kwargs):
"\n Return an element with the appropriate parent.\n\n EXAMPLES::\n\n sage: NuDyckWord('110100','101010')\n [1, 1, 0, 1, 0, 0]\n sage: NuDyckWord('010','010')\n [0, 1, 0]\n "
if (dw is None):
from sage.combinat.dyck_word import DyckWord
return DyckWord(dw, kwargs)
if isinstance(dw, NuDyckWord):
return dw
if (nu is None):
raise ValueError('nu required')
dw = to_word_path(dw)
nu = to_word_path(nu)
if path_weakly_above_other(dw, nu):
return NuDyckWords(nu)(dw)
raise ValueError('invalid nu-Dyck word')
def __init__(self, parent, dw, latex_options=None):
"\n Initialize a nu-Dyck word.\n\n EXAMPLES::\n\n sage: NuDyckWord('010', '010')\n [0, 1, 0]\n sage: NuDyckWord('110100','101010')\n [1, 1, 0, 1, 0, 0]\n "
Element.__init__(self, parent)
self._path = to_word_path(dw)
self._list = list(self._path)
if (parent is None):
raise ValueError('need parent object')
self._nu = parent._nu
if (latex_options is None):
latex_options = {}
self._latex_options = dict(latex_options)
def __eq__(self, other):
"\n Return if two paths are equal.\n\n EXAMPLES::\n\n sage: u = NuDyckWord('010','010')\n sage: w = NuDyckWord('110100','101010')\n sage: w == w\n True\n sage: u == w\n False\n sage: u == 4\n False\n "
if (not isinstance(other, NuDyckWord)):
return False
return ((self._path == other._path) and (self._nu == other._nu))
def __neq__(self, other):
"\n Return if two paths are not equal.\n\n EXAMPLES::\n\n sage: u = NuDyckWord('010','010')\n sage: w = NuDyckWord('110100','101010')\n sage: w != w\n False\n sage: u != w\n True\n sage: u != 4\n True\n "
return (not self.__eq__(other))
def __le__(self, other):
"\n Return if one path is included in another.\n\n EXAMPLES::\n\n sage: ND1 = NuDyckWord('101', '011')\n sage: ND2 = NuDyckWord('110', '011')\n sage: ND3 = NuDyckWord('011', '011')\n sage: ND1 <= ND1\n True\n sage: ND1 <= ND2\n True\n sage: ND2 <= ND1\n False\n sage: ND3 <= ND2\n True\n sage: ND3 <= ND1\n True\n\n "
if (self._nu == other._nu):
return path_weakly_above_other(other._path, self._path)
return False
def __lt__(self, other):
"\n Return if one path is strictly included in another\n\n EXAMPLES::\n\n sage: ND1 = NuDyckWord('101', '011')\n sage: ND2 = NuDyckWord('110', '011')\n sage: ND3 = NuDyckWord('011', '011')\n sage: ND1 < ND1\n False\n sage: ND1 < ND2\n True\n sage: ND2 < ND1\n False\n sage: ND3 < ND2\n True\n sage: ND3 < ND1\n True\n "
return (self.__le__(other) and (not self.__eq__(other)))
def __ge__(self, other):
"\n Return if one path is included in another\n\n EXAMPLES::\n\n sage: ND1 = NuDyckWord('101', '011')\n sage: ND2 = NuDyckWord('110', '011')\n sage: ND3 = NuDyckWord('011', '011')\n sage: ND1 >= ND1\n True\n sage: ND1 >= ND2\n False\n sage: ND2 >= ND1\n True\n sage: ND1 >= ND3\n True\n sage: ND2 >= ND3\n True\n "
if (self._nu == other._nu):
return path_weakly_above_other(self._path, other._path)
return False
def __gt__(self, other):
"\n Return if one path is strictly included in another\n\n EXAMPLES::\n\n sage: ND1 = NuDyckWord('101', '011')\n sage: ND2 = NuDyckWord('110', '011')\n sage: ND3 = NuDyckWord('011', '011')\n sage: ND1 > ND1\n False\n sage: ND1 > ND2\n False\n sage: ND2 > ND1\n True\n sage: ND1 > ND3\n True\n sage: ND2 > ND3\n True\n "
return (self.__ge__(other) and (not self.__eq__(other)))
def _cache_key(self) -> tuple:
"\n Return a cache key for ``self``.\n\n EXAMPLES::\n\n sage: u = NuDyckWord('010','010')\n sage: u._cache_key()\n (0, 1, 0, 0, 1, 0)\n "
return (tuple(self._path) + tuple(self._nu))
def __hash__(self) -> int:
"\n Return a hash for ``self``.\n\n EXAMPLES::\n\n sage: u = NuDyckWord('010','010')\n sage: hash(u) # random\n -4577085166836515071\n "
return hash(''.join((str(i) for i in self._list)))
def set_latex_options(self, D):
'\n Set the latex options for use in the ``_latex_`` function.\n\n The default values are set in the ``__init__`` function.\n\n - ``color`` -- (default: black) the line color.\n\n - ``line width`` -- (default: `2 \\times` ``tikz_scale``) value\n representing the line width.\n\n - ``nu_options`` -- (default: ``\'rounded corners=1, color=red, line\n width=1\'``) str to indicate what the tikz options should be for path\n of `\\nu`.\n\n - ``points_color`` -- (default: ``\'black\'``) str to indicate color\n points should be drawn with.\n\n - ``show_grid`` -- (default: ``True``) boolean value to indicate if\n grid should be shown.\n\n - ``show_nu`` -- (default: ``True``) boolean value to indicate if `\\nu`\n should be shown.\n\n - ``show_points`` -- (default: ``False``) boolean value to indicate\n if points should be shown on path.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package.\n\n INPUT:\n\n - ``D`` -- a dictionary with a list of latex parameters to change\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord(\'010\',\'010\')\n sage: NDW.set_latex_options({"tikz_scale":2})\n sage: NDW.set_latex_options({"color":"blue", "show_points":True})\n\n .. TODO::\n\n This should probably be merged into NuDyckWord.options.\n '
for opt in D:
self._latex_options[opt] = D[opt]
def latex_options(self) -> dict:
"\n Return the latex options for use in the ``_latex_`` function as a\n dictionary.\n\n The default values are set using the options.\n\n - ``color`` -- (default: black) the line color.\n\n - ``line width`` -- (default: 2*``tikz_scale``) value representing the\n line width.\n\n - ``nu_options`` -- (default: ``'rounded corners=1, color=red, line\n width=1'``) str to indicate what the tikz options should be for path\n of `\\nu`.\n\n - ``points_color`` -- (default: ``'black'``) str to indicate color\n points should be drawn with.\n\n - ``show_grid`` -- (default: ``True``) boolean value to indicate if\n grid should be shown.\n\n - ``show_nu`` -- (default: ``True``) boolean value to indicate if `\\nu`\n should be shown.\n\n - ``show_points`` -- (default: ``False``) boolean value to indicate\n if points should be shown on path.\n\n - ``tikz_scale`` -- (default: 1) scale for use with the tikz package.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('010','010')\n sage: NDW.latex_options()\n {'color': black,\n 'line width': 2,\n 'nu_options': rounded corners=1, color=red, line width=1,\n 'points_color': black,\n 'show_grid': True,\n 'show_nu': True,\n 'show_points': False,\n 'tikz_scale': 1}\n\n .. TODO::\n\n This should probably be merged into NuDyckWord.options.\n "
d = self._latex_options.copy()
opts = self.parent().options
if ('tikz_scale' not in d):
d['tikz_scale'] = opts.latex_tikz_scale
if ('line width' not in d):
d['line width'] = (opts.latex_line_width_scalar * d['tikz_scale'])
if ('color' not in d):
d['color'] = opts.latex_color
if ('show_points' not in d):
d['show_points'] = opts.latex_show_points
if ('points_color' not in d):
d['points_color'] = opts.latex_points_color
if ('show_grid' not in d):
d['show_grid'] = opts.latex_show_grid
if ('show_nu' not in d):
d['show_nu'] = opts.latex_show_nu
if ('nu_options' not in d):
d['nu_options'] = opts.latex_nu_options
return d
def _repr_(self) -> str:
'\n Return a string representation of ``self`` depending on\n :meth:`NuDyckWords.options`.\n\n TESTS::\n\n sage: NuDyckWord(\'01010\',\'00011\')\n [0, 1, 0, 1, 0]\n sage: NuDyckWord(\'10010\',\'00011\')\n [1, 0, 0, 1, 0]\n sage: NuDyckWords.options.display="lattice"\n sage: NuDyckWord(\'10010\',\'00011\')\n __\n ___|x\n |x x x\n\n sage: NuDyckWords.options._reset()\n '
return self.parent().options._dispatch(self, '_repr_', 'display')
def _repr_list(self) -> str:
"\n Return a string representation of ``self`` as a list.\n\n TESTS::\n\n sage: NuDyckWord([1,1,0],[1,0,1]) # indirect doctest\n [1, 1, 0]\n sage: NuDyckWord('NNEE','NENE')\n [1, 1, 0, 0]\n "
return str(list(self._path))
def _repr_lattice(self, style=None, labelling=None):
"\n See :meth:`pretty_print()`.\n\n TESTS::\n\n sage: n = NuDyckWord('00011001000100','00011001000100')\n sage: print(n._repr_lattice(style='N-E', labelling=[1,2,3,4]))\n ____\n _____| . . 4\n ___| . . . . . 3\n | . . . . . . . 2\n ______| . . . . . . . 1\n\n\n sage: print(NuDyckWord('100101','010011')._repr_lattice())\n _|\n ___|x\n |x . .\n\n sage: print(NuDyckWord('110010','001011')._repr_lattice())\n __\n ___|x\n |x x x\n |x x .\n "
if (style is None):
style = self.parent().options.diagram_style
if (style == 'grid'):
style = 'N-E'
if (style == 'N-E'):
path_length = self._path.length()
height = self._path.height()
width = self._path.width()
if (path_length == 0):
return '.\n'
if (labelling is None):
labels = ([' '] * height)
else:
if (len(labelling) != height):
raise ValueError(f'the given labelling has the wrong length: {height} needed')
labels = [str(label) for label in labelling]
max_length = max((len(label) for label in labels))
labels = [lbl.rjust((max_length + 1)) for lbl in labels]
rev_path = list(self._path.reversal())
rev_nu_path = list(self._nu.reversal())
ts = ''
cur_pos = rev_path.index(ndw_open_symbol)
cur_nu_pos = rev_nu_path.index(ndw_open_symbol)
if (cur_pos > 0):
ts += (' ' * (width - cur_pos))
ts += (' _' + ('__' * (cur_pos - 1)))
ts += '_\n'
for i in range((height - 1)):
old_pos = cur_pos
old_nu_pos = cur_nu_pos
cur_pos = rev_path.index(ndw_open_symbol, (cur_pos + 1))
cur_nu_pos = rev_nu_path.index(ndw_open_symbol, (cur_nu_pos + 1))
ts += (' ' * (((width - cur_pos) + i) + 1))
if (cur_pos != (old_pos + 1)):
ts += (' _' + ('__' * ((cur_pos - old_pos) - 2)))
ts += '|'
if (old_pos >= 0):
ts += ('x ' * (old_pos - old_nu_pos))
ts += (' .' * (old_nu_pos - i))
ts += labels[((height - i) - 1)]
ts += '\n'
ts += ('__' * ((path_length - cur_pos) - 1))
ts += '|'
ts += ('x ' * (cur_pos - cur_nu_pos))
ts += (' .' * ((cur_nu_pos - i) - 1))
ts += labels[0]
ts += '\n'
return ts
raise ValueError(f'the given style (={style}) is not valid')
def _ascii_art_(self):
"\n Return an ASCII art representation of ``self``.\n\n TESTS::\n\n sage: ascii_art(NuDyckWord('00011001000100','00011001000100'))\n ____\n _____| . .\n ___| . . . . .\n | . . . . . . .\n ______| . . . . . . .\n\n "
from sage.typeset.ascii_art import AsciiArt
rep = self.parent().options.ascii_art
if (rep == 'pretty_output'):
ret = self._repr_lattice()
return AsciiArt(ret.splitlines(), baseline=0)
def __str__(self) -> str:
"\n Return a string consisting of N and E steps corresponding to\n the `\\nu`-Dyck word.\n\n EXAMPLES::\n\n sage: str(NuDyckWord('100101','010011'))\n 'NEENEN'\n sage: str(NuDyckWord('101010','100110'))\n 'NENENE'\n "
return ''.join((replace_dyck_symbol(let) for let in self._path))
def pretty_print(self, style=None, labelling=None):
'\n Display a NuDyckWord as a lattice path in the `\\ZZ^2` grid.\n\n If the ``style`` is "N-E", then a cell below the diagonal is\n indicated by a period, whereas a cell below the path but above\n the diagonal is indicated by an x. If a list of labels is\n included, they are displayed along the vertical edges of the\n Dyck path.\n\n INPUT:\n\n - ``style`` -- (default: ``None``) can either be:\n\n - ``None`` to use the option default\n - "N-E" to show ``self`` as a path of north and east steps, or\n\n - ``labelling`` -- (if style is "N-E") a list of labels assigned to\n the up steps in ``self``.\n\n - ``underpath`` -- (if style is "N-E", default: ``True``) If ``True``,\n an ``x`` to show the boxes between `\\nu` and the `\\nu`-Dyck Path.\n\n EXAMPLES::\n\n sage: for ND in NuDyckWords(\'101010\'): ND.pretty_print()\n __\n _| .\n _| . .\n | . . .\n __\n ___| .\n |x . .\n | . . .\n ____\n |x .\n _| . .\n | . . .\n ____\n _|x .\n |x . .\n | . . .\n ______\n |x x .\n |x . .\n | . . .\n\n ::\n\n sage: nu = [1,0,1,0,1,0,1,0,1,0,1,0]\n sage: ND = NuDyckWord([1,1,1,0,1,0,0,1,1,0,0,0],nu)\n sage: ND.pretty_print()\n ______\n |x x .\n ___|x . .\n _|x x . . .\n |x x . . . .\n |x . . . . .\n | . . . . . .\n\n ::\n\n sage: NuDyckWord([1,1,0,0,1,0],[1,0,1,0,1,0]).pretty_print(\n ....: labelling=[1,3,2])\n __\n ___| . 2\n |x . . 3\n | . . . 1\n\n ::\n\n sage: NuDyckWord(\'1101110011010010001101111000110000\',\n ....: \'1010101010101010101010101010101010\').pretty_print(\n ....: labelling=list(range(1,18)))\n ________\n |x x x . 17\n _____|x x . . 16\n |x x x x . . . 15\n |x x x . . . . 14\n |x x . . . . . 13\n _|x . . . . . . 12\n |x . . . . . . . 11\n _____| . . . . . . . . 10\n ___|x x . . . . . . . . . 9\n _|x x x . . . . . . . . . . 8\n |x x x . . . . . . . . . . . 7\n ___|x x . . . . . . . . . . . . 6\n |x x x . . . . . . . . . . . . . 5\n |x x . . . . . . . . . . . . . . 4\n _|x . . . . . . . . . . . . . . . 3\n |x . . . . . . . . . . . . . . . . 2\n | . . . . . . . . . . . . . . . . . 1\n\n\n ::\n\n sage: NuDyckWord().pretty_print()\n .\n '
print(self._repr_lattice(style, labelling))
pp = pretty_print
def _latex_(self):
'\n A latex representation of ``self`` using the tikzpicture package.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord(\'010\',\'010\')\n sage: NDW.set_latex_options({"show_points":True})\n sage: latex(NDW)\n \\vcenter{\\hbox{$\\begin{tikzpicture}[scale=1]\n \\draw[dotted] (0, 0) grid (2, 1);\n \\draw[line width=2,color=black,fill=black](0, 0) circle (0.21);\n \\draw[line width=2,color=black,fill=black](1, 0) circle (0.21);\n \\draw[line width=2,color=black,fill=black](1, 1) circle (0.21);\n \\draw[line width=2,color=black,fill=black](2, 1) circle (0.21);\n \\draw[rounded corners=1, color=red, line width=1] (0, 0) -- (1, 0) -- (1, 1) -- (2, 1);\n \\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (1, 0) -- (1, 1) -- (2, 1);\n \\end{tikzpicture}$}}\n sage: NuDyckWord(\'01\',\'01\')._latex_()\n \'\\\\vcenter{\\\\hbox{$\\\\begin{tikzpicture}[scale=1]\\n \\\\draw[dotted] (0, 0) grid (1, 1);\\n \\\\draw[rounded corners=1, color=red, line width=1] (0, 0) -- (1, 0) -- (1, 1);\\n \\\\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (1, 0) -- (1, 1);\\n\\\\end{tikzpicture}$}}\'\n sage: NuDyckWord(\'101100\',\'101010\')._latex_()\n \'\\\\vcenter{\\\\hbox{$\\\\begin{tikzpicture}[scale=1]\\n \\\\draw[dotted] (0, 0) grid (3, 3);\\n \\\\draw[rounded corners=1, color=red, line width=1] (0, 0) -- (0, 1) -- (1, 1) -- (1, 2) -- (2, 2) -- (2, 3) -- (3, 3);\\n \\\\draw[rounded corners=1, color=black, line width=2] (0, 0) -- (0, 1) -- (1, 1) -- (1, 2) -- (1, 3) -- (2, 3) -- (3, 3);\\n\\\\end{tikzpicture}$}}\'\n '
latex.add_package_to_preamble_if_available('tikz')
latex_options = self.latex_options()
res = '\\vcenter{\\hbox{$\\begin{tikzpicture}'
res += (('[scale=' + str(latex_options['tikz_scale'])) + ']')
res += '\n'
if latex_options['show_grid']:
grid = [((0, 0), (self.width(), self.height()))]
for (v1, v2) in grid:
res += (' \\draw[dotted] %s grid %s;' % (str(v1), str(v2)))
res += '\n'
if latex_options['show_points']:
pt_color = latex_options['points_color']
radius = (0.15 + (0.03 * latex_options['line width']))
for v in self.points():
res += ' \\draw[line width=2,'
res += ('color=%s,fill=%s]' % (pt_color, pt_color))
res += ('%s circle (%s);' % (str(v), str(radius)))
res += '\n'
if latex_options['show_nu']:
res += (' \\draw[%s]' % str(latex_options['nu_options']))
for (k, p) in enumerate(self._nu.points()):
if (k == 0):
res += (' %s' % str(p))
else:
res += (' -- %s' % str(p))
res += ';\n'
res += (' \\draw[rounded corners=1, color=%s, line width=%s]' % (latex_options['color'], str(latex_options['line width'])))
for (k, p) in enumerate(self._path.points()):
if (k == 0):
res += (' %s' % str(p))
else:
res += (' -- %s' % str(p))
res += ';\n'
res += '\\end{tikzpicture}$}}'
return res
def plot(self, **kwds):
"\n Plot a `\\nu`-Dyck word as a continuous path.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('010','010')\n sage: NDW.plot() # needs sage.plot\n Graphics object consisting of 1 graphics primitive\n "
from sage.plot.plot import list_plot
return list_plot(list(self.points()), plotjoined=True, **kwds)
def path(self):
"\n Return the underlying path object.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('10011001000','00100101001')\n sage: NDW.path()\n Path: 10011001000\n "
return self._path
def height(self):
"\n Return the height of ``self``.\n\n The height is the number of ``north`` steps.\n\n EXAMPLES::\n\n sage: NuDyckWord('1101110011010010001101111000110000',\n ....: '1010101010101010101010101010101010').height()\n 17\n "
return self._path.height()
def width(self):
"\n Return the width of ``self``.\n\n The width is the number of ``east`` steps.\n\n EXAMPLES::\n\n sage: NuDyckWord('110111001101001000110111100011000',\n ....: '101010101010101010101010101010101').width()\n 16\n "
return self._path.width()
def length(self):
"\n Return the length of ``self``.\n\n The length is the total number of steps.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('10011001000','00100101001')\n sage: NDW.length()\n 11\n "
return self._path.length()
def points(self):
"\n Return an iterator for the points on the `\\nu`-Dyck path.\n\n EXAMPLES::\n\n sage: list(NuDyckWord('110111001101001000110111100011000',\n ....: '101010101010101010101010101010101')._path.points())\n [(0, 0),\n (0, 1),\n (0, 2),\n (1, 2),\n (1, 3),\n (1, 4),\n (1, 5),\n (2, 5),\n (3, 5),\n (3, 6),\n (3, 7),\n (4, 7),\n (4, 8),\n (5, 8),\n (6, 8),\n (6, 9),\n (7, 9),\n (8, 9),\n (9, 9),\n (9, 10),\n (9, 11),\n (10, 11),\n (10, 12),\n (10, 13),\n (10, 14),\n (10, 15),\n (11, 15),\n (12, 15),\n (13, 15),\n (13, 16),\n (13, 17),\n (14, 17),\n (15, 17),\n (16, 17)]\n "
return self._path.points()
def heights(self):
"\n Return the heights of each point on ``self``.\n\n We view the Dyck word as a Dyck path from `(0,0)` to\n `(x,y)` in the first quadrant by letting ``1``'s represent\n steps in the direction `(0,1)` and ``0``'s represent steps in\n the direction `(1,0)`.\n\n The heights is the sequence of the `y`-coordinates of all\n `x+y` lattice points along the path.\n\n EXAMPLES::\n\n sage: NuDyckWord('010','010').heights()\n [0, 0, 1, 1]\n sage: NuDyckWord('110100','101010').heights()\n [0, 1, 2, 2, 3, 3, 3]\n "
return self._path.height_vector()
def widths(self):
"\n Return the widths of each point on ``self``.\n\n We view the Dyck word as a Dyck path from `(0,0)` to\n `(x,y)` in the first quadrant by letting ``1``'s represent\n steps in the direction `(0,1)` and ``0``'s represent steps in\n the direction `(1,0)`.\n\n The widths is the sequence of the `x`-coordinates of all\n `x+y` lattice points along the path.\n\n EXAMPLES::\n\n sage: NuDyckWord('010','010').widths()\n [0, 1, 1, 2]\n sage: NuDyckWord('110100','101010').widths()\n [0, 0, 0, 1, 1, 2, 3]\n "
return self._path.width_vector()
def horizontal_distance(self):
"\n Return a list of how far each point is from `\\nu`.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('10010100','00000111')\n sage: NDW.horizontal_distance()\n [5, 5, 4, 3, 3, 2, 2, 1, 0]\n sage: NDW = NuDyckWord('10010100','00001011')\n sage: NDW.horizontal_distance()\n [4, 5, 4, 3, 3, 2, 2, 1, 0]\n sage: NDW = NuDyckWord('10011001000','00100101001')\n sage: NDW.horizontal_distance()\n [2, 4, 3, 2, 3, 5, 4, 3, 3, 2, 1, 0]\n "
nu_points = list(self._nu.points())
nu_easts = [max((i for (i, j) in nu_points if (j == k))) for k in range((self._nu.height() + 1))]
points = list(self._path.points())
return [(nu_easts[j] - i) for (i, j) in points]
def can_mutate(self, i) -> (bool | int):
"\n Return True/False based off if mutable at height `i`.\n\n Can only mutate if an east step is followed by a north step at height\n `i`.\n\n OUTPUT:\n\n Whether we can mutate at height of `i`.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('10010100','00000111')\n sage: NDW.can_mutate(1)\n False\n sage: NDW.can_mutate(3)\n 5\n\n TESTS::\n\n sage: NDW = NuDyckWord('10010100','00000111')\n sage: NDW.can_mutate(33)\n Traceback (most recent call last):\n ...\n ValueError: cannot mutate above or below path\n "
if ((i > self.height()) or (i <= 0)):
raise ValueError('cannot mutate above or below path')
level = 0
ndw = self._list
for (j, k) in enumerate(ndw):
if (k == ndw_open_symbol):
level += 1
if (level == i):
break
if ((j > 0) and (ndw[(j - 1)] == ndw_close_symbol)):
return j
return False
def mutate(self, i) -> (None | NuDyckWord):
"\n Return a new `\\nu`-Dyck Word if possible.\n\n If at height `i` we have an east step E meeting a north step N then we\n calculate all horizontal distances from this point until we find\n the first point that has the same horizontal distance to `\\nu`. We let\n\n - d is everything up until EN (not including EN)\n\n - f be everything between N and the point with the same horizontal\n distance (including N)\n\n - g is everything after f\n\n .. SEEALSO:: :meth:`can_mutate`\n\n EXAMPLES::\n\n sage: NDW = NuDyckWord('10010100','00000111')\n sage: NDW.mutate(1)\n sage: NDW.mutate(3)\n [1, 0, 0, 1, 1, 0, 0, 0]\n "
mutation_index = self.can_mutate(i)
if (not mutation_index):
return None
horiz = self.horizontal_distance()
horiz_num = horiz[mutation_index]
other_index = len(horiz)
for i in range((mutation_index + 1), len(horiz)):
if (horiz[i] == horiz_num):
other_index = i
break
ndw = self._list
d = ndw[0:(mutation_index - 1)]
e = ndw[mutation_index:other_index]
f = ndw[other_index:]
return NuDyckWord((((d + e) + [ndw_close_symbol]) + f), self._nu)
|
class NuDyckWords(Parent):
"\n `\\nu`-Dyck words.\n\n Given a lattice path `\\nu` in the `\\ZZ^2` grid starting at the origin\n `(0,0)` consisting of North `N = (0,1)` and East `E = (1,0)` steps, a\n `\\nu`-Dyck path is a lattice path in the`\\ZZ^2` grid starting at the\n origin `(0,0)` and ending at the same coordinate as `\\nu` such that it is\n weakly above `\\nu`. A `\\nu`-Dyck word is the representation of a\n `\\nu`-Dyck path where a North step is represented by a 1 and an East step\n is represented by a 0.\n\n INPUT:\n\n - ``nu`` -- the base lattice path.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWords('1010'); NDW\n [1, 0, 1, 0] Dyck words\n sage: [1,0,1,0] in NDW\n True\n sage: [1,1,0,0] in NDW\n True\n sage: [1,0,0,1] in NDW\n False\n sage: [0,1,0,1] in NDW\n False\n sage: NDW.cardinality()\n 2\n "
Element = NuDyckWord
def __init__(self, nu=()):
'\n Intialize ``self``.\n\n EXAMPLES::\n\n sage: TestSuite(NuDyckWords(nu=[1,0,1])).run()\n '
Parent.__init__(self, category=FiniteEnumeratedSets())
self._nu = to_word_path(nu)
if (self._nu is None):
raise ValueError('invalid nu supplied')
class options(GlobalOptions):
"\n Set and display the options for `\\nu`-Dyck words. If no parameters\n are set, then the function returns a copy of the options dictionary.\n\n The ``options`` to `\\nu`-Dyck words can be accessed as the method\n :meth:`NuDyckWords.options` of :class:`NuDyckWords` and\n related parent classes.\n\n @OPTIONS\n\n EXAMPLES::\n\n sage: ND = NuDyckWords('101')\n sage: ND\n [1, 0, 1] Dyck words\n sage: ND.options\n Current options for NuDyckWords\n - ascii_art: pretty_output\n - diagram_style: grid\n - display: list\n - latex_color: black\n - latex_line_width_scalar: 2\n - latex_nu_options: rounded corners=1, color=red, line width=1\n - latex_points_color: black\n - latex_show_grid: True\n - latex_show_nu: True\n - latex_show_points: False\n - latex_tikz_scale: 1\n "
NAME = 'NuDyckWords'
module = 'sage.combinat.nu_dyck_path'
display = dict(default='list', description='Specifies how nu Dyck words should be printed', values=dict(list='displayed as a list', lattice='displayed on the lattice defined by ``diagram_style``'), case_sensitive=False)
ascii_art = dict(default='pretty_output', description='Specifies how the ascii art of nu Dyck words should be printed', values=dict(pretty_output='Using pretty printing'), alias=dict(pretty_print='pretty_output'), case_sensitive=False)
diagram_style = dict(default='grid', values=dict(grid='printing as paths on a grid using N and E steps'), alias={'N-E': 'grid'}, case_sensitive=False)
latex_tikz_scale = dict(default=1, description='The default value for the tikz scale when latexed', checker=(lambda x: True))
latex_line_width_scalar = dict(default=2, description='The default value for the line width as a multiple of the tikz scale when latexed', checker=(lambda x: True))
latex_color = dict(default='black', description='The default value for the color when latexed', checker=(lambda x: isinstance(x, str)))
latex_show_points = dict(default=False, description='The default value for showing points', checker=(lambda x: isinstance(x, bool)))
latex_points_color = dict(default='black', description='The default value for path color.', checker=(lambda x: isinstance(x, str)))
latex_show_grid = dict(default=True, description='The default value for showing grid', checker=(lambda x: isinstance(x, bool)))
latex_show_nu = dict(default=True, description='The default value for showing nu', checker=(lambda x: isinstance(x, bool)))
latex_nu_options = dict(default='rounded corners=1, color=red, line width=1', description='The default value for options for nu path', checker=(lambda x: isinstance(x, str)))
def _element_constructor_(self, word):
"\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWords('101')\n sage: elt = NDW('110'); elt\n [1, 1, 0]\n sage: elt.parent() is NDW\n True\n "
if (isinstance(word, NuDyckWord) and (word.parent() is self)):
return word
return self.element_class(self, to_word_path(word))
def __contains__(self, x) -> bool:
'\n Check for containment.\n\n TESTS::\n\n sage: NDW = NuDyckWords([1,0,1,1])\n sage: [1,1,0,1] in NDW\n True\n sage: [1,0,1,1] in NDW\n True\n sage: [0] in NDW\n False\n sage: [1, 0] in NDW\n False\n '
return path_weakly_above_other(to_word_path(x), self._nu)
def __eq__(self, other):
'\n Return equality.\n\n TESTS::\n\n sage: A = NuDyckWords([1,0,1,1])\n sage: B = NuDyckWords([1,0,1,1])\n sage: C = NuDyckWords([1,0,1,1,1])\n sage: A == B\n True\n sage: A == C\n False\n '
if (not isinstance(other, NuDyckWords)):
return False
return (self._nu == other._nu)
def __neq__(self, other):
'\n Return inequality.\n\n TESTS::\n\n sage: A = NuDyckWords([1,0,1,1])\n sage: B = NuDyckWords([1,0,1,1])\n sage: C = NuDyckWords([1,0,1,1,1])\n sage: A != B\n False\n sage: A != C\n True\n '
return (not self.__eq__(other))
def _repr_(self) -> str:
'\n TESTS::\n\n sage: NuDyckWords([1,0,1,1])\n [1, 0, 1, 1] Dyck words\n '
return f'{list(self._nu)} Dyck words'
def _cache_key(self) -> str:
"\n Return a cache key\n\n TESTS::\n\n sage: NuDyckWords([1,0,1,1])._cache_key()\n '1011'\n "
return str(self._nu)
def _an_element_(self):
"\n Return an element.\n\n TESTS::\n\n sage: NuDyckWords('101').an_element()\n [1, 0, 1]\n "
return self.element_class(self, self._nu)
def __iter__(self, N=[], D=[], i=None, X=None):
"\n Iterate over ``self``.\n\n The iterator interchanges a 0,1 pair whenever the 0 comes before a 1\n\n EXAMPLES::\n\n sage: it = NuDyckWords('101010').__iter__()\n sage: [i for i in it]\n [[1, 0, 1, 0, 1, 0],\n [1, 1, 0, 0, 1, 0],\n [1, 0, 1, 1, 0, 0],\n [1, 1, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0]]\n "
def transpose_close_open(N):
for (k, v) in enumerate(N._list):
if ((k > 0) and (v == ndw_open_symbol)):
w = N._list[(k - 1)]
if (w == ndw_close_symbol):
new = ((N._list[:(k - 1)] + [v, w]) + N._list[(k + 1):])
(yield self.element_class(self, new))
RES = RecursivelyEnumeratedSet([self.element_class(self, self._nu)], transpose_close_open)
return RES.breadth_first_search_iterator()
def cardinality(self):
"\n Return the number of `\\nu`-Dyck words.\n\n EXAMPLES::\n\n sage: NDW = NuDyckWords('101010'); NDW.cardinality()\n 5\n sage: NDW = NuDyckWords('1010010'); NDW.cardinality()\n 7\n sage: NDW = NuDyckWords('100100100'); NDW.cardinality()\n 12\n "
return Integer(len([1 for _ in self.__iter__()]))
|
def to_word_path(word):
"\n Convert input into a word path over an appropriate alphabet.\n\n Helper function.\n\n INPUT:\n\n - ``word`` -- word to convert to wordpath\n\n OUTPUT:\n\n - A ``FiniteWordPath_north_east`` object.\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_dyck_word import to_word_path\n sage: wp = to_word_path('NEENENEN'); wp\n Path: 10010101\n sage: from sage.combinat.words.paths import FiniteWordPath_north_east\n sage: isinstance(wp,FiniteWordPath_north_east)\n True\n sage: to_word_path('1001')\n Path: 1001\n sage: to_word_path([0,1,0,0,1,0])\n Path: 010010\n "
if isinstance(word, FiniteWordPath_north_east):
return word
if isinstance(word, NuDyckWord):
return word.path()
if isinstance(word, str):
word = map(replace_dyck_char, word)
P = WordPaths_north_east([ndw_open_symbol, ndw_close_symbol])
return P(word)
|
def path_weakly_above_other(path, other) -> bool:
"\n Test if ``path`` is weakly above ``other``.\n\n A path `P` is wealy above another path `Q` if `P` and `Q` are the same\n length and if any prefix of length `n` of `Q` contains more North steps\n than the prefix of length `n` of `P`.\n\n INPUT:\n\n - ``path`` -- The path to verify is weakly above the other path.\n\n - ``other`` -- The other path to verify is weakly below the path.\n\n OUTPUT:\n\n bool\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_dyck_word import path_weakly_above_other\n sage: path_weakly_above_other('1001','0110')\n False\n sage: path_weakly_above_other('1001','0101')\n True\n sage: path_weakly_above_other('1111','0101')\n False\n sage: path_weakly_above_other('111100','0101')\n False\n "
path = to_word_path(path)
other = to_word_path(other)
if ((path.length() != other.length()) or (path.height() != other.height())):
return False
p_height = path.height_vector()
o_height = other.height_vector()
return all(((p_h >= o_h) for (p_h, o_h) in zip(p_height, o_height)))
|
def NuTamariLattice(nu):
'\n Return the `\\nu`-Tamari lattice.\n\n INPUT:\n\n - `\\nu` -- a list of 0s and 1s or a string of 0s and 1s.\n\n OUTPUT:\n\n a finite lattice\n\n The elements of the lattice are\n :func:`\\nu-Dyck paths<sage.combinat.nu_dyck_word.NuDyckWord>` weakly above\n `\\nu`.\n\n The usual :wikipedia:`Tamari lattice<Tamari_lattice>` is the special case\n where `\\nu = (NE)^h` where `h` is the height.\n\n Other special cases give the `m`-Tamari lattices studied in [BMFPR]_.\n\n EXAMPLES::\n\n sage: from sage.combinat.nu_tamari_lattice import NuTamariLattice\n sage: NuTamariLattice([1,0,1,0,0,1,0])\n Finite lattice containing 7 elements\n sage: NuTamariLattice([1,0,1,0,1,0])\n Finite lattice containing 5 elements\n sage: NuTamariLattice([1,0,1,0,1,0,1,0])\n Finite lattice containing 14 elements\n sage: NuTamariLattice([1,0,1,0,1,0,0,0,1])\n Finite lattice containing 24 elements\n '
NDW = NuDyckWords(nu)
covers = []
elements = []
height = NDW[0].height()
for ndw in NDW:
elements.append(ndw)
for i in range(1, (height + 1)):
new_ndw = ndw.mutate(i)
if (new_ndw is not None):
covers.append([ndw, new_ndw])
return LatticePoset([elements, covers])
|
class OrderedTree(AbstractClonableTree, ClonableList, metaclass=InheritComparisonClasscallMetaclass):
'\n The class of (ordered rooted) trees.\n\n An ordered tree is constructed from a node, called the root, on which one\n has grafted a possibly empty list of trees. There is a total order on the\n children of a node which is given by the order of the elements in the\n list. Note that there is no empty ordered tree (so the smallest ordered\n tree consists of just one node).\n\n INPUT:\n\n One can create a tree from any list (or more generally iterable) of trees\n or objects convertible to a tree. Alternatively a string is also\n accepted. The syntax is the same as for printing: children are grouped by\n square brackets.\n\n EXAMPLES::\n\n sage: x = OrderedTree([])\n sage: x1 = OrderedTree([x,x])\n sage: x2 = OrderedTree([[],[]])\n sage: x1 == x2\n True\n sage: tt1 = OrderedTree([x,x1,x2])\n sage: tt2 = OrderedTree([[], [[], []], x2])\n sage: tt1 == tt2\n True\n\n sage: OrderedTree([]) == OrderedTree()\n True\n\n TESTS::\n\n sage: x1.__hash__() == x2.__hash__()\n True\n sage: tt1.__hash__() == tt2.__hash__()\n True\n\n Trees are usually immutable. However they inherit from\n :class:`sage.structure.list_clone.ClonableList`, so that they can be\n modified using the clone protocol. Let us now see what this means.\n\n Trying to modify a non-mutable tree raises an error::\n\n sage: tt1[1] = tt2\n Traceback (most recent call last):\n ...\n ValueError: object is immutable; please change a copy instead.\n\n Here is the correct way to do it::\n\n sage: with tt2.clone() as tt2:\n ....: tt2[1] = tt1\n sage: tt2\n [[], [[], [[], []], [[], []]], [[], []]]\n\n It is also possible to append a child to a tree::\n\n sage: with tt2.clone() as tt3:\n ....: tt3.append(OrderedTree([]))\n sage: tt3\n [[], [[], [[], []], [[], []]], [[], []], []]\n\n Or to insert a child in a tree::\n\n sage: with tt2.clone() as tt3:\n ....: tt3.insert(2, OrderedTree([]))\n sage: tt3\n [[], [[], [[], []], [[], []]], [], [[], []]]\n\n We check that ``tt1`` is not modified and that everything is correct with\n respect to equality::\n\n sage: tt1\n [[], [[], []], [[], []]]\n sage: tt1 == tt2\n False\n sage: tt1.__hash__() == tt2.__hash__()\n False\n\n TESTS::\n\n sage: tt1bis = OrderedTree(tt1)\n sage: with tt1.clone() as tt1:\n ....: tt1[1] = tt1bis\n sage: tt1\n [[], [[], [[], []], [[], []]], [[], []]]\n sage: tt1 == tt2\n True\n sage: tt1.__hash__() == tt2.__hash__()\n True\n sage: len(tt1)\n 3\n sage: tt1[2]\n [[], []]\n sage: tt1[3]\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n sage: tt1[1:2]\n [[[], [[], []], [[], []]]]\n\n Various tests involving construction, equality and hashing::\n\n sage: OrderedTree() == OrderedTree()\n True\n sage: t1 = OrderedTree([[],[[]]])\n sage: t2 = OrderedTree([[],[[]]])\n sage: t1 == t2\n True\n sage: t2 = OrderedTree(t1)\n sage: t1 == t2\n True\n sage: t1 = OrderedTree([[],[[]]])\n sage: t2 = OrderedTree([[[]],[]])\n sage: t1 == t2\n False\n\n sage: t1 = OrderedTree([[],[[]]])\n sage: t2 = OrderedTree([[],[[]]])\n sage: t1.__hash__() == t2.__hash__()\n True\n sage: t2 = OrderedTree([[[]],[]])\n sage: t1.__hash__() == t2.__hash__()\n False\n sage: OrderedTree().__hash__() == OrderedTree([]).__hash__()\n True\n sage: tt1 = OrderedTree([t1,t2,t1])\n sage: tt2 = OrderedTree([t1, [[[]],[]], t1])\n sage: tt1.__hash__() == tt2.__hash__()\n True\n\n Check that the hash value is correctly updated after modification::\n\n sage: with tt2.clone() as tt2:\n ....: tt2[1,1] = tt1\n sage: tt1.__hash__() == tt2.__hash__()\n False\n '
@staticmethod
def __classcall_private__(cls, *args, **opts):
"\n Ensure that trees created by the enumerated sets and directly\n are the same and that they are instances of :class:`OrderedTree`\n\n TESTS::\n\n sage: issubclass(OrderedTrees().element_class, OrderedTree)\n True\n sage: t0 = OrderedTree([[],[[], []]])\n sage: t0.parent()\n Ordered trees\n sage: type(t0)\n <class 'sage.combinat.ordered_tree.OrderedTrees_all_with_category.element_class'>\n\n sage: t1 = OrderedTrees()([[],[[], []]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n\n sage: t1 = OrderedTrees(4)([[],[[]]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n "
return cls._auto_parent.element_class(cls._auto_parent, *args, **opts)
@lazy_class_attribute
def _auto_parent(cls):
'\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: OrderedTree([[],[[]]])._auto_parent\n Ordered trees\n sage: OrderedTree([[],[[]]]).parent()\n Ordered trees\n\n .. NOTE::\n\n It is possible to bypass the automatic parent mechanism using::\n\n sage: t1 = OrderedTree.__new__(OrderedTree, Parent(), [])\n sage: t1.__init__(Parent(), [])\n sage: t1\n []\n sage: t1.parent()\n <sage.structure.parent.Parent object at ...>\n '
return OrderedTrees_all()
def __init__(self, parent=None, children=None, check=True):
'\n TESTS::\n\n sage: t1 = OrderedTrees(4)([[],[[]]])\n sage: TestSuite(t1).run()\n sage: OrderedTrees()("[]") # indirect doctest\n []\n sage: all(OrderedTree(repr(tr)) == tr for i in range(6) for tr in OrderedTrees(i))\n True\n '
if (children is None):
children = []
if isinstance(children, str):
children = eval(children)
if ((children.__class__ is self.__class__) and (children.parent() == parent)):
children = list(children)
else:
children = [self.__class__(parent, x) for x in children]
ClonableArray.__init__(self, parent, children, check=check)
def is_empty(self):
'\n Return if ``self`` is the empty tree.\n\n For ordered trees, this always returns ``False``.\n\n .. NOTE:: this is different from ``bool(t)`` which returns whether\n ``t`` has some child or not.\n\n EXAMPLES::\n\n sage: t = OrderedTrees(4)([[],[[]]])\n sage: t.is_empty()\n False\n sage: bool(t)\n True\n '
return False
def _to_binary_tree_rec(self, bijection='left'):
'\n Internal recursive method to obtain a binary tree from an ordered\n tree.\n\n See :meth:`to_binary_tree_left_branch` and\n :meth:`to_binary_tree_right_branch` for what it does.\n\n EXAMPLES::\n\n sage: T = OrderedTree([[],[]])\n sage: T._to_binary_tree_rec()\n [[., .], .]\n sage: T._to_binary_tree_rec(bijection="right")\n [., [., .]]\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T._to_binary_tree_rec()\n [[[., .], [[., .], .]], [[., .], [., .]]]\n sage: T._to_binary_tree_rec(bijection="right")\n [., [[., [., .]], [[., [[., .], .]], .]]]\n '
from sage.combinat.binary_tree import BinaryTree
root = BinaryTree()
if (bijection == 'left'):
for child in self:
root = BinaryTree([root, child._to_binary_tree_rec(bijection)])
elif (bijection == 'right'):
children = list(self)
children.reverse()
for child in children:
root = BinaryTree([child._to_binary_tree_rec(bijection), root])
else:
raise ValueError('the bijection argument should be either left or right')
return root
@combinatorial_map(name='To binary tree, left brother = left child')
def to_binary_tree_left_branch(self):
'\n Return a binary tree of size `n-1` (where `n` is the size of `t`,\n and where `t` is ``self``) obtained from `t` by the following\n recursive rule:\n\n - if `x` is the left brother of `y` in `t`, then `x` becomes the\n left child of `y`;\n - if `x` is the last child of `y` in `t`, then `x` becomes the\n right child of `y`,\n\n and removing the root of `t`.\n\n EXAMPLES::\n\n sage: T = OrderedTree([[],[]])\n sage: T.to_binary_tree_left_branch()\n [[., .], .]\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T.to_binary_tree_left_branch()\n [[[., .], [[., .], .]], [[., .], [., .]]]\n\n TESTS::\n\n sage: T = OrderedTree([[],[]])\n sage: T == T.to_binary_tree_left_branch().to_ordered_tree_left_branch()\n True\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T == T.to_binary_tree_left_branch().to_ordered_tree_left_branch()\n True\n '
return self._to_binary_tree_rec()
@combinatorial_map(name='To parallelogram polyomino')
def to_parallelogram_polyomino(self, bijection=None):
"\n Return a polyomino parallelogram.\n\n INPUT:\n\n - ``bijection`` -- (default: ``'Boussicault-Socci'``) is the name of the\n bijection to use. Possible values are ``'Boussicault-Socci'``,\n ``'via dyck and Delest-Viennot'``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: T = OrderedTree([[[], [[], [[]]]], [], [[[],[]]], [], []])\n sage: T.to_parallelogram_polyomino(bijection='Boussicault-Socci')\n [[0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1],\n [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0]]\n sage: T = OrderedTree( [] )\n sage: T.to_parallelogram_polyomino()\n [[1], [1]]\n sage: T = OrderedTree( [[]] )\n sage: T.to_parallelogram_polyomino()\n [[0, 1], [1, 0]]\n sage: T = OrderedTree( [[],[]] )\n sage: T.to_parallelogram_polyomino()\n [[0, 1, 1], [1, 1, 0]]\n sage: T = OrderedTree( [[[]]] )\n sage: T.to_parallelogram_polyomino()\n [[0, 0, 1], [1, 0, 0]]\n "
if ((bijection is None) or (bijection == 'Boussicault-Socci')):
return self._to_parallelogram_polyomino_Boussicault_Socci()
if (bijection == 'via dyck and Delest-Viennot'):
raise NotImplementedError
raise ValueError('unknown bijection')
def _to_parallelogram_polyomino_Boussicault_Socci(self):
'\n Return the polyomino parallelogram using the Boussicault-Socci\n bijection.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: T = OrderedTree(\n ....: [[[], [[], [[]]]], [], [[[],[]]], [], []]\n ....: )\n sage: T._to_parallelogram_polyomino_Boussicault_Socci()\n [[0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0]]\n sage: T = OrderedTree( [] )\n sage: T._to_parallelogram_polyomino_Boussicault_Socci()\n [[1], [1]]\n sage: T = OrderedTree( [[]] )\n sage: T._to_parallelogram_polyomino_Boussicault_Socci()\n [[0, 1], [1, 0]]\n sage: T = OrderedTree( [[],[]] )\n sage: T._to_parallelogram_polyomino_Boussicault_Socci()\n [[0, 1, 1], [1, 1, 0]]\n sage: T = OrderedTree( [[[]]] )\n sage: T._to_parallelogram_polyomino_Boussicault_Socci()\n [[0, 0, 1], [1, 0, 0]]\n '
from sage.combinat.parallelogram_polyomino import ParallelogramPolyomino
if (self.node_number() == 1):
return ParallelogramPolyomino([[1], [1]])
upper_nodes = []
lower_nodes = []
w_coordinate = {}
w_coordinate[()] = 0
h_coordinate = {}
cpt = 0
for h in range(0, self.depth(), 2):
for node in self.paths_at_depth(h):
h_coordinate[node] = cpt
lower_nodes.append(node)
cpt += 1
cpt = 0
for h in range(1, self.depth(), 2):
for node in self.paths_at_depth(h):
w_coordinate[node] = cpt
upper_nodes.append(node)
cpt += 1
def W(path):
if (path in w_coordinate):
return w_coordinate[path]
else:
return w_coordinate[path[:(- 1)]]
def H(path):
if (path in h_coordinate):
return h_coordinate[path]
else:
return h_coordinate[path[:(- 1)]]
lower_path = []
for i in range(1, len(lower_nodes)):
lower_path.append(0)
lower_path += ([1] * (W(lower_nodes[i]) - W(lower_nodes[(i - 1)])))
lower_path.append(0)
lower_path += ([1] * (self.node_number() - len(lower_path)))
upper_path = []
for i in range(1, len(upper_nodes)):
upper_path.append(1)
upper_path += ([0] * (H(upper_nodes[i]) - H(upper_nodes[(i - 1)])))
upper_path.append(1)
upper_path += ([0] * (self.node_number() - len(upper_path)))
return ParallelogramPolyomino([lower_path, upper_path])
@combinatorial_map(name='To binary tree, right brother = right child')
def to_binary_tree_right_branch(self):
'\n Return a binary tree of size `n-1` (where `n` is the size of `t`,\n and where `t` is ``self``) obtained from `t` by the following\n recursive rule:\n\n - if `x` is the right brother of `y` in `t`, then`x` becomes the\n right child of `y`;\n - if `x` is the first child of `y` in `t`, then `x` becomes the\n left child of `y`,\n\n and removing the root of `t`.\n\n EXAMPLES::\n\n sage: T = OrderedTree([[],[]])\n sage: T.to_binary_tree_right_branch()\n [., [., .]]\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T.to_binary_tree_right_branch()\n [., [[., [., .]], [[., [[., .], .]], .]]]\n\n TESTS::\n\n sage: T = OrderedTree([[],[]])\n sage: T == T.to_binary_tree_right_branch().to_ordered_tree_right_branch()\n True\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T == T.to_binary_tree_right_branch().to_ordered_tree_right_branch()\n True\n '
return self._to_binary_tree_rec(bijection='right')
@combinatorial_map(name='To Dyck path')
def to_dyck_word(self):
'\n Return the Dyck path corresponding to ``self`` where the maximal\n height of the Dyck path is the depth of ``self`` .\n\n EXAMPLES::\n\n sage: T = OrderedTree([[],[]])\n sage: T.to_dyck_word() # needs sage.combinat\n [1, 0, 1, 0]\n sage: T = OrderedTree([[],[[]]])\n sage: T.to_dyck_word() # needs sage.combinat\n [1, 0, 1, 1, 0, 0]\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T.to_dyck_word() # needs sage.combinat\n [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]\n '
word = []
for child in self:
word.append(1)
word.extend(child.to_dyck_word())
word.append(0)
from sage.combinat.dyck_word import DyckWord
return DyckWord(word)
@combinatorial_map(name='To graph')
def to_undirected_graph(self):
'\n Return the undirected graph obtained from the tree nodes and edges.\n\n The graph is endowed with an embedding, so that it will be displayed\n correctly.\n\n EXAMPLES::\n\n sage: t = OrderedTree([])\n sage: t.to_undirected_graph()\n Graph on 1 vertex\n sage: t = OrderedTree([[[]],[],[]])\n sage: t.to_undirected_graph()\n Graph on 5 vertices\n\n If the tree is labelled, we use its labelling to label the graph. This\n will fail if the labels are not all distinct.\n Otherwise, we use the graph canonical labelling which means that\n two different trees can have the same graph.\n\n EXAMPLES::\n\n sage: t = OrderedTree([[[]],[],[]])\n sage: t.canonical_labelling().to_undirected_graph()\n Graph on 5 vertices\n\n TESTS::\n\n sage: t.canonical_labelling().to_undirected_graph() == t.to_undirected_graph()\n False\n sage: OrderedTree([[],[]]).to_undirected_graph() == OrderedTree([[[]]]).to_undirected_graph()\n True\n sage: OrderedTree([[],[],[]]).to_undirected_graph() == OrderedTree([[[[]]]]).to_undirected_graph()\n False\n '
from sage.graphs.graph import Graph
g = Graph()
if (self in LabelledOrderedTrees()):
relabel = False
else:
self = self.canonical_labelling()
relabel = True
roots = [self]
g.add_vertex(name=self.label())
emb = {self.label(): []}
while roots:
node = roots.pop()
children = reversed([child.label() for child in node])
emb[node.label()].extend(children)
for child in node:
g.add_vertex(name=child.label())
emb[child.label()] = [node.label()]
g.add_edge(child.label(), node.label())
roots.append(child)
g.set_embedding(emb)
if relabel:
g = g.canonical_label()
return g
@combinatorial_map(name='To poset')
def to_poset(self, root_to_leaf=False):
'\n Return the poset obtained by interpreting the tree as a Hasse\n diagram. The default orientation is from leaves to root but you can\n pass ``root_to_leaf=True`` to obtain the inverse orientation.\n\n INPUT:\n\n - ``root_to_leaf`` -- boolean, true if the poset orientation should\n be from root to leaves. It is false by default.\n\n EXAMPLES::\n\n sage: t = OrderedTree([])\n sage: t.to_poset()\n Finite poset containing 1 elements\n sage: p = OrderedTree([[[]],[],[]]).to_poset()\n sage: p.height(), p.width() # needs networkx\n (3, 3)\n\n If the tree is labelled, we use its labelling to label the poset.\n Otherwise, we use the poset canonical labelling::\n\n sage: t = OrderedTree([[[]],[],[]]).canonical_labelling().to_poset()\n sage: t.height(), t.width() # needs networkx\n (3, 3)\n '
if (self in LabelledOrderedTrees()):
relabel = False
else:
self = self.canonical_labelling()
relabel = True
relations = []
elements = [self.label()]
roots = [self]
while roots:
node = roots.pop()
for child in node:
elements.append(child.label())
relations.append(((node.label(), child.label()) if root_to_leaf else (child.label(), node.label())))
roots.append(child)
from sage.combinat.posets.posets import Poset
p = Poset([elements, relations])
if relabel:
p = p.canonical_label()
return p
@combinatorial_map(order=2, name='Left-right symmetry')
def left_right_symmetry(self):
'\n Return the symmetric tree of ``self``.\n\n The symmetric tree `s(T)` of an ordered tree `T` is\n defined as follows:\n If `T` is an ordered tree with children `C_1, C_2, \\ldots, C_k`\n (listed from left to right), then the symmetric tree `s(T)` of\n `T` is the ordered tree with children\n `s(C_k), s(C_{k-1}), \\ldots, s(C_1)` (from left to right).\n\n EXAMPLES::\n\n sage: T = OrderedTree([[],[[]]])\n sage: T.left_right_symmetry()\n [[[]], []]\n sage: T = OrderedTree([[], [[], []], [[], [[]]]])\n sage: T.left_right_symmetry()\n [[[[]], []], [[], []], []]\n '
children = [c.left_right_symmetry() for c in self]
children.reverse()
return OrderedTree(children)
def plot(self):
'\n Plot the tree ``self``.\n\n .. WARNING::\n\n For a labelled tree, this will fail unless all labels are\n distinct. For unlabelled trees, some arbitrary labels are chosen.\n Use :meth:`_latex_`, ``view``,\n :meth:`_ascii_art_` or ``pretty_print`` for more\n faithful representations of the data of the tree.\n\n EXAMPLES::\n\n sage: p = OrderedTree([[[]],[],[]])\n sage: ascii_art(p)\n _o__\n / / /\n o o o\n |\n o\n sage: p.plot() # needs sage.plot\n Graphics object consisting of 10 graphics primitives\n\n .. PLOT::\n\n P = OrderedTree([[[]],[],[]]).plot()\n sphinx_plot(P)\n\n Now a labelled example::\n\n sage: g = OrderedTree([[],[[]],[]]).canonical_labelling()\n sage: ascii_art(g)\n _1__\n / / /\n 2 3 5\n |\n 4\n sage: g.plot() # needs sage.plot\n Graphics object consisting of 10 graphics primitives\n\n .. PLOT::\n\n P = OrderedTree([[],[[]],[]]).canonical_labelling().plot()\n sphinx_plot(P)\n '
try:
root = self.label()
g = self.to_undirected_graph()
except AttributeError:
root = 1
g = self.canonical_labelling().to_undirected_graph()
return g.plot(layout='tree', tree_root=root, tree_orientation='down')
def sort_key(self):
'\n Return a tuple of nonnegative integers encoding the ordered\n tree ``self``.\n\n The first entry of the tuple is the number of children of the\n root. Then the rest of the tuple is the concatenation of the\n tuples associated to these children (we view the children of\n a tree as trees themselves) from left to right.\n\n This tuple characterizes the tree uniquely, and can be used to\n sort the ordered trees.\n\n .. NOTE::\n\n By default, this method does not encode any extra\n structure that ``self`` might have -- e.g., if you were\n to define a class ``EdgeColoredOrderedTree`` which\n implements edge-colored trees and which inherits from\n :class:`OrderedTree`, then the :meth:`sort_key` method\n it would inherit would forget about the colors of the\n edges (and thus would not characterize edge-colored\n trees uniquely). If you want to preserve extra data,\n you need to override this method or use a new method.\n For instance, on the :class:`LabelledOrderedTree`\n subclass, this method is overridden by a slightly\n different method, which encodes not only the numbers\n of children of the nodes of ``self``, but also their\n labels.\n Be careful with using overridden methods, however:\n If you have (say) a class ``BalancedTree`` which\n inherits from :class:`OrderedTree` and which encodes\n balanced trees, and if you have another class\n ``BalancedLabelledOrderedTree`` which inherits both\n from ``BalancedOrderedTree`` and from\n :class:`LabelledOrderedTree`, then (depending on the MRO)\n the default :meth:`sort_key` method on\n ``BalancedLabelledOrderedTree`` (unless manually\n overridden) will be taken either from ``BalancedTree``\n or from :class:`LabelledOrderedTree`, and in the former\n case will ignore the labelling!\n\n EXAMPLES::\n\n sage: RT = OrderedTree\n sage: RT([[],[[]]]).sort_key()\n (2, 0, 1, 0)\n sage: RT([[[]],[]]).sort_key()\n (2, 1, 0, 0)\n '
l = len(self)
if (l == 0):
return (0,)
resu = ([l] + [u for t in self for u in t.sort_key()])
return tuple(resu)
@cached_method
def normalize(self, inplace=False):
'\n Return the normalized tree of ``self``.\n\n INPUT:\n\n - ``inplace`` -- boolean, (default ``False``) if ``True``,\n then ``self`` is modified and nothing returned. Otherwise\n the normalized tree is returned.\n\n The normalization of an ordered tree `t` is an ordered tree `s`\n which has the property that `t` and `s` are isomorphic as\n *unordered* rooted trees, and that if two ordered trees `t` and\n `t\'` are isomorphic as *unordered* rooted trees, then the\n normalizations of `t` and `t\'` are identical. In other words,\n normalization is a map from the set of ordered trees to itself\n which picks a representative from every equivalence class with\n respect to the relation of "being isomorphic as unordered\n trees", and maps every ordered tree to the representative\n chosen from its class.\n\n This map proceeds recursively by first normalizing every\n subtree, and then sorting the subtrees according to the value\n of the :meth:`sort_key` method.\n\n Consider the quotient map `\\pi` that sends a planar rooted tree to\n the associated unordered rooted tree. Normalization is the\n composite `s \\circ \\pi`, where `s` is a section of `\\pi`.\n\n EXAMPLES::\n\n sage: OT = OrderedTree\n sage: ta = OT([[],[[]]])\n sage: tb = OT([[[]],[]])\n sage: ta.normalize() == tb.normalize()\n True\n sage: ta == tb\n False\n\n An example with inplace normalization::\n\n sage: OT = OrderedTree\n sage: ta = OT([[],[[]]])\n sage: tb = OT([[[]],[]])\n sage: ta.normalize(inplace=True); ta\n [[], [[]]]\n sage: tb.normalize(inplace=True); tb\n [[], [[]]]\n '
if (not inplace):
with self.clone() as res:
resl = res._get_list()
for i in range(len(resl)):
resl[i] = resl[i].normalize()
resl.sort(key=(lambda t: t.sort_key()))
return res
else:
resl = self._get_list()
for i in range(len(resl)):
resl[i] = resl[i].normalize()
resl.sort(key=(lambda t: t.sort_key()))
|
class OrderedTrees(UniqueRepresentation, Parent):
'\n Factory for ordered trees\n\n INPUT:\n\n - ``size`` -- (optional) an integer\n\n OUTPUT:\n\n - the set of all ordered trees (of the given ``size`` if specified)\n\n EXAMPLES::\n\n sage: OrderedTrees()\n Ordered trees\n\n sage: OrderedTrees(2)\n Ordered trees of size 2\n\n .. NOTE:: this is a factory class whose constructor returns instances of\n subclasses.\n\n .. NOTE:: the fact that OrderedTrees is a class instead of a simple callable\n is an implementation detail. It could be changed in the future\n and one should not rely on it.\n '
@staticmethod
def __classcall_private__(cls, n=None):
'\n TESTS::\n\n sage: from sage.combinat.ordered_tree import OrderedTrees_all, OrderedTrees_size\n sage: isinstance(OrderedTrees(2), OrderedTrees)\n True\n sage: isinstance(OrderedTrees(), OrderedTrees)\n True\n sage: OrderedTrees(2) is OrderedTrees_size(2)\n True\n sage: OrderedTrees(5).cardinality()\n 14\n sage: OrderedTrees() is OrderedTrees_all()\n True\n '
if (n is None):
return OrderedTrees_all()
else:
if (not (isinstance(n, (Integer, int)) and (n >= 0))):
raise ValueError('n must be a non negative integer')
return OrderedTrees_size(Integer(n))
@cached_method
def leaf(self):
'\n Return a leaf tree with ``self`` as parent\n\n EXAMPLES::\n\n sage: OrderedTrees().leaf()\n []\n\n TESTS::\n\n sage: (OrderedTrees().leaf() is\n ....: sage.combinat.ordered_tree.OrderedTrees_all().leaf())\n True\n '
return self([])
|
class OrderedTrees_all(DisjointUnionEnumeratedSets, OrderedTrees):
'\n The set of all ordered trees.\n\n EXAMPLES::\n\n sage: OT = OrderedTrees(); OT\n Ordered trees\n sage: OT.cardinality()\n +Infinity\n '
def __init__(self):
'\n TESTS::\n\n sage: from sage.combinat.ordered_tree import OrderedTrees_all\n sage: B = OrderedTrees_all()\n sage: B.cardinality()\n +Infinity\n\n sage: it = iter(B)\n sage: (next(it), next(it), next(it), next(it), next(it))\n ([], [[]], [[], []], [[[]]], [[], [], []])\n sage: next(it).parent()\n Ordered trees\n sage: B([])\n []\n\n sage: B is OrderedTrees_all()\n True\n sage: TestSuite(B).run() # long time\n '
DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), OrderedTrees_size), facade=True, keepkey=False)
def _repr_(self):
'\n TESTS::\n\n sage: OrderedTrees() # indirect doctest\n Ordered trees\n '
return 'Ordered trees'
def __contains__(self, x):
'\n TESTS::\n\n sage: T = OrderedTrees()\n sage: 1 in T\n False\n sage: T([]) in T\n True\n '
return isinstance(x, self.element_class)
def unlabelled_trees(self):
'\n Return the set of unlabelled trees associated to ``self``\n\n EXAMPLES::\n\n sage: OrderedTrees().unlabelled_trees()\n Ordered trees\n '
return self
def labelled_trees(self):
'\n Return the set of labelled trees associated to ``self``\n\n EXAMPLES::\n\n sage: OrderedTrees().labelled_trees()\n Labelled ordered trees\n '
return LabelledOrderedTrees()
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: T = OrderedTrees()\n sage: T([]) # indirect doctest\n []\n '
return self.element_class(self, *args, **keywords)
Element = OrderedTree
|
class OrderedTrees_size(OrderedTrees):
'\n The enumerated sets of binary trees of a given size\n\n EXAMPLES::\n\n sage: S = OrderedTrees(3); S\n Ordered trees of size 3\n sage: S.cardinality()\n 2\n sage: S.list()\n [[[], []], [[[]]]]\n '
def __init__(self, size):
'\n TESTS::\n\n sage: from sage.combinat.ordered_tree import OrderedTrees_size\n sage: TestSuite(OrderedTrees_size(0)).run()\n sage: for i in range(6): TestSuite(OrderedTrees_size(i)).run()\n '
super().__init__(category=FiniteEnumeratedSets())
self._size = size
def _repr_(self):
'\n TESTS::\n\n sage: OrderedTrees(3) # indirect doctest\n Ordered trees of size 3\n '
return 'Ordered trees of size {}'.format(self._size)
def __contains__(self, x):
'\n TESTS::\n\n sage: T = OrderedTrees(3)\n sage: 1 in T\n False\n sage: T([[],[]]) in T\n True\n '
return (isinstance(x, self.element_class) and (x.node_number() == self._size))
def _an_element_(self):
'\n TESTS::\n\n sage: OrderedTrees(3).an_element() # indirect doctest\n [[], []]\n '
if (self._size == 0):
raise EmptySetError
return self.first()
def cardinality(self):
'\n The cardinality of ``self``\n\n This is a Catalan number.\n\n TESTS::\n\n sage: OrderedTrees(0).cardinality()\n 0\n sage: OrderedTrees(1).cardinality()\n 1\n sage: OrderedTrees(6).cardinality()\n 42\n '
if (self._size == 0):
return Integer(0)
else:
from .combinat import catalan_number
return catalan_number((self._size - 1))
def random_element(self):
'\n Return a random ``OrderedTree`` with uniform probability.\n\n This method generates a random ``DyckWord`` and then uses a\n bijection between Dyck words and ordered trees.\n\n EXAMPLES::\n\n sage: OrderedTrees(5).random_element() # random # needs sage.combinat\n [[[], []], []]\n sage: OrderedTrees(0).random_element()\n Traceback (most recent call last):\n ...\n EmptySetError: there are no ordered trees of size 0\n sage: OrderedTrees(1).random_element() # needs sage.combinat\n []\n\n TESTS::\n\n sage: all(OrderedTrees(10).random_element() in OrderedTrees(10) # needs sage.combinat\n ....: for i in range(20))\n True\n '
if (self._size == 0):
raise EmptySetError('there are no ordered trees of size 0')
return CompleteDyckWords_size((self._size - 1)).random_element().to_ordered_tree()
def __iter__(self):
'\n A basic generator\n\n .. TODO:: could be optimized.\n\n TESTS::\n\n sage: OrderedTrees(0).list()\n []\n sage: OrderedTrees(1).list()\n [[]]\n sage: OrderedTrees(2).list()\n [[[]]]\n sage: OrderedTrees(3).list()\n [[[], []], [[[]]]]\n sage: OrderedTrees(4).list()\n [[[], [], []], [[], [[]]], [[[]], []], [[[], []]], [[[[]]]]]\n '
if (self._size == 0):
return
for c in Compositions((self._size - 1)):
for lst in itertools.product(*[self.__class__(i) for i in c]):
(yield self._element_constructor_(lst))
@lazy_attribute
def _parent_for(self):
'\n Return the parent of the element generated by ``self``\n\n TESTS::\n\n sage: OrderedTrees(3)._parent_for\n Ordered trees\n '
return OrderedTrees_all()
@lazy_attribute
def element_class(self):
'\n The class of the element of ``self``\n\n EXAMPLES::\n\n sage: from sage.combinat.ordered_tree import OrderedTrees_size, OrderedTrees_all\n sage: S = OrderedTrees_size(3)\n sage: S.element_class is OrderedTrees().element_class\n True\n sage: S.first().__class__ == OrderedTrees_all().first().__class__\n True\n '
return self._parent_for.element_class
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: S = OrderedTrees(0)\n sage: S([]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: wrong number of nodes\n\n sage: S = OrderedTrees(1) # indirect doctest\n sage: S([])\n []\n '
res = self.element_class(self._parent_for, *args, **keywords)
if (res.node_number() != self._size):
raise ValueError('wrong number of nodes')
return res
|
class LabelledOrderedTree(AbstractLabelledClonableTree, OrderedTree):
'\n Labelled ordered trees.\n\n A labelled ordered tree is an ordered tree with a label attached at each\n node.\n\n INPUT:\n\n - ``children`` -- a list or tuple or more generally any iterable\n of trees or object convertible to trees\n - ``label`` -- any Sage object (default: ``None``)\n\n EXAMPLES::\n\n sage: x = LabelledOrderedTree([], label = 3); x\n 3[]\n sage: LabelledOrderedTree([x, x, x], label = 2)\n 2[3[], 3[], 3[]]\n sage: LabelledOrderedTree((x, x, x), label = 2)\n 2[3[], 3[], 3[]]\n sage: LabelledOrderedTree([[],[[], []]], label = 3)\n 3[None[], None[None[], None[]]]\n '
@staticmethod
def __classcall_private__(cls, *args, **opts):
"\n Ensure that trees created by the sets and directly are the same and\n that they are instances of :class:`LabelledOrderedTree`\n\n TESTS::\n\n sage: issubclass(LabelledOrderedTrees().element_class, LabelledOrderedTree)\n True\n sage: t0 = LabelledOrderedTree([[],[[], []]], label = 3)\n sage: t0.parent()\n Labelled ordered trees\n sage: type(t0)\n <class 'sage.combinat.ordered_tree.LabelledOrderedTrees_with_category.element_class'>\n "
return cls._auto_parent.element_class(cls._auto_parent, *args, **opts)
@lazy_class_attribute
def _auto_parent(cls):
'\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: LabelledOrderedTree._auto_parent\n Labelled ordered trees\n sage: LabelledOrderedTree([], label = 3).parent()\n Labelled ordered trees\n '
return LabelledOrderedTrees()
_UnLabelled = OrderedTree
__hash__ = ClonableArray.__hash__
@combinatorial_map(order=2, name='Left-right symmetry')
def left_right_symmetry(self):
'\n Return the symmetric tree of ``self``.\n\n The symmetric tree `s(T)` of a labelled ordered tree `T` is\n defined as follows:\n If `T` is a labelled ordered tree with children\n `C_1, C_2, \\ldots, C_k` (listed from left to right), then the\n symmetric tree `s(T)` of `T` is a labelled ordered tree with\n children `s(C_k), s(C_{k-1}), \\ldots, s(C_1)` (from left to\n right), and with the same root label as `T`.\n\n .. NOTE::\n\n If you have a subclass of :meth:`LabelledOrderedTree`\n which also inherits from another subclass of\n :meth:`OrderedTree` which does not come with a labelling,\n then (depending on the method resolution order) it might\n happen that this method gets overridden by an\n implementation from that other subclass, and thus forgets\n about the labels. In this case you need to manually\n override this method on your subclass.\n\n EXAMPLES::\n\n sage: L2 = LabelledOrderedTree([], label=2)\n sage: L3 = LabelledOrderedTree([], label=3)\n sage: T23 = LabelledOrderedTree([L2, L3], label=4)\n sage: T23.left_right_symmetry()\n 4[3[], 2[]]\n sage: T223 = LabelledOrderedTree([L2, T23], label=17)\n sage: T223.left_right_symmetry()\n 17[4[3[], 2[]], 2[]]\n sage: T223.left_right_symmetry().left_right_symmetry() == T223\n True\n '
children = [c.left_right_symmetry() for c in self]
children.reverse()
return LabelledOrderedTree(children, label=self.label())
def sort_key(self):
'\n Return a tuple of nonnegative integers encoding the labelled\n tree ``self``.\n\n The first entry of the tuple is a pair consisting of the\n number of children of the root and the label of the root. Then\n the rest of the tuple is the concatenation of the tuples\n associated to these children (we view the children of\n a tree as trees themselves) from left to right.\n\n This tuple characterizes the labelled tree uniquely, and can\n be used to sort the labelled ordered trees provided that the\n labels belong to a type which is totally ordered.\n\n .. WARNING::\n\n This method overrides :meth:`OrderedTree.sort_key`\n and returns a result different from what the latter\n would return, as it wants to encode the whole labelled\n tree including its labelling rather than just the\n unlabelled tree. Therefore, be careful with using this\n method on subclasses of :class:`LabelledOrderedTree`;\n under some circumstances they could inherit it from\n another superclass instead of from :class:`OrderedTree`,\n which would cause the method to forget the labelling.\n See the docstring of :meth:`OrderedTree.sort_key`.\n\n EXAMPLES::\n\n sage: L2 = LabelledOrderedTree([], label=2)\n sage: L3 = LabelledOrderedTree([], label=3)\n sage: T23 = LabelledOrderedTree([L2, L3], label=4)\n sage: T23.sort_key()\n ((2, 4), (0, 2), (0, 3))\n sage: T32 = LabelledOrderedTree([L3, L2], label=5)\n sage: T32.sort_key()\n ((2, 5), (0, 3), (0, 2))\n sage: T23322 = LabelledOrderedTree([T23, T32, L2], label=14)\n sage: T23322.sort_key()\n ((3, 14), (2, 4), (0, 2), (0, 3), (2, 5), (0, 3), (0, 2), (0, 2))\n '
l = len(self)
if (l == 0):
return ((0, self.label()),)
resu = ([(l, self.label())] + [u for t in self for u in t.sort_key()])
return tuple(resu)
|
class LabelledOrderedTrees(UniqueRepresentation, Parent):
'\n This is a parent stub to serve as a factory class for trees with various\n label constraints.\n\n EXAMPLES::\n\n sage: LOT = LabelledOrderedTrees(); LOT\n Labelled ordered trees\n sage: x = LOT([], label = 3); x\n 3[]\n sage: x.parent() is LOT\n True\n sage: y = LOT([x, x, x], label = 2); y\n 2[3[], 3[], 3[]]\n sage: y.parent() is LOT\n True\n '
def __init__(self, category=None):
'\n TESTS::\n\n sage: TestSuite(LabelledOrderedTrees()).run()\n '
if (category is None):
category = Sets()
Parent.__init__(self, category=category)
def _repr_(self):
'\n TESTS::\n\n sage: LabelledOrderedTrees() # indirect doctest\n Labelled ordered trees\n '
return 'Labelled ordered trees'
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: LabelledOrderedTrees().cardinality()\n +Infinity\n '
return Infinity
def _an_element_(self):
'\n Return a labelled ordered tree.\n\n EXAMPLES::\n\n sage: LabelledOrderedTrees().an_element() # indirect doctest\n toto[3[], 42[3[], 3[]], 5[None[]]]\n '
LT = self._element_constructor_
t = LT([], label=3)
t1 = LT([t, t], label=42)
t2 = LT([[]], label=5)
return LT([t, t1, t2], label='toto')
def _element_constructor_(self, *args, **keywords):
'\n EXAMPLES::\n\n sage: T = LabelledOrderedTrees()\n sage: T([], label=2) # indirect doctest\n 2[]\n '
return self.element_class(self, *args, **keywords)
def unlabelled_trees(self):
'\n Return the set of unlabelled trees associated to ``self``.\n\n This is the set of ordered trees, since ``self`` is the set of\n labelled ordered trees.\n\n EXAMPLES::\n\n sage: LabelledOrderedTrees().unlabelled_trees()\n Ordered trees\n '
return OrderedTrees_all()
def labelled_trees(self):
'\n Return the set of labelled trees associated to ``self``.\n\n This is precisely ``self``, because ``self`` already is the set\n of labelled ordered trees.\n\n EXAMPLES::\n\n sage: LabelledOrderedTrees().labelled_trees()\n Labelled ordered trees\n sage: LOT = LabelledOrderedTrees()\n sage: x = LOT([], label = 3)\n sage: y = LOT([x, x, x], label = 2)\n sage: y.canonical_labelling()\n 1[2[], 3[], 4[]]\n '
return self
Element = LabelledOrderedTree
|
def tex_from_array(array, with_lines=True):
'\n Return a latex string for a two dimensional array of partition, composition or skew composition shape\n\n INPUT:\n\n - ``array`` -- a list of list\n - ``with_lines`` -- a boolean (default: ``True``)\n Whether to draw a line to separate the entries in the array.\n\n Empty rows are allowed; however, such rows should be given as\n ``[None]`` rather than ``[]``.\n\n The array is drawn using either the English or French convention\n following :meth:`Tableaux.options`.\n\n .. SEEALSO:: :meth:`tex_from_array_tuple`\n\n EXAMPLES::\n\n sage: from sage.combinat.output import tex_from_array\n sage: print(tex_from_array([[1,2,3],[4,5]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\cline{1-3}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-3}\n \\lr{4}&\\lr{5}\\\\\\cline{1-2}\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\lr{4}&\\lr{5}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\cline{1-3}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-4}\n \\lr{4}&\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{1-4}\n \\lr{8}\\\\\\cline{1-1}\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\lr{4}&\\lr{5}&\\lr{6}&\\lr{7}\\\\\n \\lr{8}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\cline{3-3}\n &&\\lr{3}\\\\\\cline{2-4}\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{1-4}\n \\lr{8}\\\\\\cline{1-1}\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\cline{3-3}\n &&\\lr{3}\\\\\\cline{2-4}\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{2-4}\n &\\lr{8}\\\\\\cline{2-2}\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\\\\n &&\\lr{3}\\\\\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\n \\lr{8}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\\\\n &&\\lr{3}\\\\\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\n &\\lr{8}\\\\\n \\end{array}$}\n }\n sage: Tableaux.options.convention="french"\n sage: print(tex_from_array([[1,2,3],[4,5]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\cline{1-2}\n \\lr{4}&\\lr{5}\\\\\\cline{1-3}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-3}\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{4}&\\lr{5}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\cline{1-1}\n \\lr{8}\\\\\\cline{1-4}\n \\lr{4}&\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{1-4}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-3}\n \\end{array}$}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\\\\n \\lr{8}\\\\\n \\lr{4}&\\lr{5}&\\lr{6}&\\lr{7}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\cline{1-1}\n \\lr{8}\\\\\\cline{1-4}\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{2-4}\n &&\\lr{3}\\\\\\cline{3-3}\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\cline{2-2}\n &\\lr{8}\\\\\\cline{2-4}\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\\cline{2-4}\n &&\\lr{3}\\\\\\cline{3-3}\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\\\\n \\lr{8}\\\\\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\n &&\\lr{3}\\\\\n \\end{array}$}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\\\\n &\\lr{8}\\\\\n &\\lr{5}&\\lr{6}&\\lr{7}\\\\\n &&\\lr{3}\\\\\n \\end{array}$}\n }\n sage: Tableaux.options.convention="russian"\n sage: print(tex_from_array([[1,2,3],[4,5]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\cline{1-2}\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}\\\\\\cline{1-3}\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\\cline{1-3}\n \\end{array}$}}\n }\n sage: print(tex_from_array([[1,2,3],[4,5]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}\\\\\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\n \\end{array}$}}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\cline{1-1}\n \\lr{\\rotatebox{-45}{8}}\\\\\\cline{1-4}\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\\cline{1-4}\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\\cline{1-3}\n \\end{array}$}}\n }\n sage: print(tex_from_array([[1,2,3],[4,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\\\\n \\lr{\\rotatebox{-45}{8}}\\\\\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\n \\end{array}$}}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\cline{1-1}\n \\lr{\\rotatebox{-45}{8}}\\\\\\cline{1-4}\n &\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\\cline{2-4}\n &&\\lr{\\rotatebox{-45}{3}}\\\\\\cline{3-3}\n \\end{array}$}}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\cline{2-2}\n &\\lr{\\rotatebox{-45}{8}}\\\\\\cline{2-4}\n &\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\\cline{2-4}\n &&\\lr{\\rotatebox{-45}{3}}\\\\\\cline{3-3}\n \\end{array}$}}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\\\\n \\lr{\\rotatebox{-45}{8}}\\\\\n &\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\n &&\\lr{\\rotatebox{-45}{3}}\\\\\n \\end{array}$}}\n }\n sage: print(tex_from_array([[None,None,3],[None,5,6,7],[None,8]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{4}c}\\\\\n &\\lr{\\rotatebox{-45}{8}}\\\\\n &\\lr{\\rotatebox{-45}{5}}&\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\n &&\\lr{\\rotatebox{-45}{3}}\\\\\n \\end{array}$}}\n }\n\n sage: Tableaux.options._reset()\n '
lr = lr_macro.substitute(bar=('|' if with_lines else ''))
if (Tableaux.options.convention == 'English'):
return ('{%s\n%s\n}' % (lr, tex_from_skew_array(array, with_lines)))
else:
return ('{%s\n%s\n}' % (lr, tex_from_skew_array(array[::(- 1)], with_lines, align='t')))
|
def tex_from_array_tuple(a_tuple, with_lines=True):
'\n Return a latex string for a tuple of two dimensional array of partition,\n composition or skew composition shape.\n\n INPUT:\n\n - ``a_tuple`` -- a tuple of lists of lists\n - ``with_lines`` -- a boolean (default: ``True``)\n Whether to draw lines to separate the entries in the components of ``a_tuple``.\n\n .. SEEALSO:: :meth:`tex_from_array` for the description of each array\n\n EXAMPLES::\n\n sage: from sage.combinat.output import tex_from_array_tuple\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\cline{1-3}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-3}\n \\lr{4}&\\lr{5}\\\\\\cline{1-2}\n \\end{array}$},\\emptyset,\\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\cline{2-3}\n &\\lr{6}&\\lr{7}\\\\\\cline{2-3}\n &\\lr{8}\\\\\\cline{1-2}\n \\lr{9}\\\\\\cline{1-1}\n \\end{array}$}\n }\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\lr{4}&\\lr{5}\\\\\n \\end{array}$},\\emptyset,\\raisebox{-.6ex}{$\\begin{array}[b]{*{3}c}\\\\\n &\\lr{6}&\\lr{7}\\\\\n &\\lr{8}\\\\\n \\lr{9}\\\\\n \\end{array}$}\n }\n sage: Tableaux.options.convention="french"\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\cline{1-2}\n \\lr{4}&\\lr{5}\\\\\\cline{1-3}\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\\cline{1-3}\n \\end{array}$},\\emptyset,\\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\cline{1-1}\n \\lr{9}\\\\\\cline{1-2}\n &\\lr{8}\\\\\\cline{2-3}\n &\\lr{6}&\\lr{7}\\\\\\cline{2-3}\n \\end{array}$}\n }\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{4}&\\lr{5}\\\\\n \\lr{1}&\\lr{2}&\\lr{3}\\\\\n \\end{array}$},\\emptyset,\\raisebox{-.6ex}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{9}\\\\\n &\\lr{8}\\\\\n &\\lr{6}&\\lr{7}\\\\\n \\end{array}$}\n }\n sage: Tableaux.options.convention="russian"\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]]))\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\cline{1-2}\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}\\\\\\cline{1-3}\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\\cline{1-3}\n \\end{array}$}},\\emptyset,\\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\cline{1-1}\n \\lr{\\rotatebox{-45}{9}}\\\\\\cline{1-2}\n &\\lr{\\rotatebox{-45}{8}}\\\\\\cline{2-3}\n &\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\\cline{2-3}\n \\end{array}$}}\n }\n sage: print(tex_from_array_tuple([[[1,2,3],[4,5]],[],[[None,6,7],[None,8],[9]]], with_lines=False))\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{\\rotatebox{-45}{4}}&\\lr{\\rotatebox{-45}{5}}\\\\\n \\lr{\\rotatebox{-45}{1}}&\\lr{\\rotatebox{-45}{2}}&\\lr{\\rotatebox{-45}{3}}\\\\\n \\end{array}$}},\\emptyset,\\raisebox{-.6ex}{\\rotatebox{45}{$\\begin{array}[t]{*{3}c}\\\\\n \\lr{\\rotatebox{-45}{9}}\\\\\n &\\lr{\\rotatebox{-45}{8}}\\\\\n &\\lr{\\rotatebox{-45}{6}}&\\lr{\\rotatebox{-45}{7}}\\\\\n \\end{array}$}}\n }\n\n sage: Tableaux.options._reset()\n '
lr = lr_macro.substitute(bar=('|' if with_lines else ''))
if (Tableaux.options.convention == 'English'):
return ('{%s\n%s\n}' % (lr, ','.join((('\\emptyset' if (comp == []) else tex_from_skew_array(comp, with_lines)) for comp in a_tuple))))
else:
return ('{%s\n%s\n}' % (lr, ','.join((('\\emptyset' if (comp == []) else tex_from_skew_array(comp[::(- 1)], with_lines, align='t')) for comp in a_tuple))))
|
def tex_from_skew_array(array, with_lines=False, align='b'):
'\n This function creates latex code for a "skew composition" ``array``.\n That is, for a two dimensional array in which each row can begin with\n an arbitrary number ``None``\'s and the remaining entries could, in\n principle, be anything but probably should be strings or integers of similar\n width. A row consisting completely of ``None``\'s is allowed.\n\n INPUT:\n\n - ``array`` -- The array\n\n - ``with_lines`` -- (Default: ``False``) If ``True`` lines are drawn, if\n ``False`` they are not\n\n - ``align`` -- (Default: ``\'b\'``) Determines the alignment on the latex\n array environments\n\n EXAMPLES::\n\n sage: array=[[None, 2,3,4],[None,None],[5,6,7,8]]\n sage: print(sage.combinat.output.tex_from_skew_array(array))\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\\\\n &\\lr{2}&\\lr{3}&\\lr{4}\\\\\n &\\\\\n \\lr{5}&\\lr{6}&\\lr{7}&\\lr{8}\\\\\n \\end{array}$}\n\n TESTS::\n\n sage: sage.combinat.output.tex_from_skew_array([(1,2,3), (2,3,4)])\n \'\\\\raisebox{-.6ex}{$\\\\begin{array}[b]{*{3}c}\\\\\\\\\\n\\\\lr{1}&\\\\lr{2}&\\\\lr{3}\\\\\\\\\\n\\\\lr{2}&\\\\lr{3}&\\\\lr{4}\\\\\\\\\\n\\\\end{array}$}\'\n sage: sage.combinat.output.tex_from_skew_array([((1,2,),)])\n \'\\\\raisebox{-.6ex}{$\\\\begin{array}[b]{*{1}c}\\\\\\\\\\n\\\\lr{(1, 2)}\\\\\\\\\\n\\\\end{array}$}\'\n '
if with_lines:
nones = [(1 if (None not in row) else ((1 + len(row)) - row[::(- 1)].index(None))) for row in array]
def end_line(r):
if (r == 0):
return ('\\cline{%s-%s}' % (nones[0], len(array[0])))
elif (r == len(array)):
start = nones[(r - 1)]
finish = len(array[(r - 1)])
else:
start = min(nones[r], nones[(r - 1)])
finish = max(len(array[r]), len(array[(r - 1)]))
return ('\\\\' if (start > finish) else ('\\\\\\cline{%s-%s}' % (start, finish)))
else:
end_line = (lambda r: '\\\\')
raisebox_start = '\\raisebox{-.6ex}{'
raisebox_end = '}'
lr_start = '\\lr{'
lr_end = '}'
if (Tableaux.options.convention == 'Russian'):
raisebox_start += '\\rotatebox{45}{'
raisebox_end += '}'
lr_start += '\\rotatebox{-45}{'
lr_end += '}'
tex = ('%s$\\begin{array}[%s]{*{%s}c}' % (raisebox_start, align, max(map(len, array))))
tex += (end_line(0) + '\n')
for r in range(len(array)):
tex += '&'.join((('' if (c is None) else ('%s%s%s' % (lr_start, c, lr_end))) for c in array[r]))
tex += (end_line((r + 1)) + '\n')
return ((tex + '\\end{array}$') + raisebox_end)
|
def ascii_art_table(data, use_unicode=False, convention='English'):
'\n Return an ascii art table of ``data``.\n\n EXAMPLES::\n\n sage: from sage.combinat.output import ascii_art_table\n\n sage: data = [[None, None, 1], [2, 2], [3,4,5], [None, None, 10], [], [6]]\n sage: print(ascii_art_table(data))\n +----+\n | 1 |\n +---+---+----+\n | 2 | 2 |\n +---+---+----+\n | 3 | 4 | 5 |\n +---+---+----+\n | 10 |\n +----+\n <BLANKLINE>\n +---+\n | 6 |\n +---+\n sage: print(ascii_art_table(data, use_unicode=True))\n ┌────┐\n │ 1 │\n ┌───┬───┼────┘\n │ 2 │ 2 │\n ├───┼───┼────┐\n │ 3 │ 4 │ 5 │\n └───┴───┼────┤\n │ 10 │\n └────┘\n <BLANKLINE>\n ┌───┐\n │ 6 │\n └───┘\n\n sage: data = [[1, None, 2], [None, 2]]\n sage: print(ascii_art_table(data))\n +---+ +---+\n | 1 | | 2 |\n +---+---+---+\n | 2 |\n +---+\n sage: print(ascii_art_table(data, use_unicode=True))\n ┌───┐ ┌───┐\n │ 1 │ │ 2 │\n └───┼───┼───┘\n │ 2 │\n └───┘\n '
if (convention == 'Russian'):
return ascii_art_table_russian(data, use_unicode)
if use_unicode:
import unicodedata
v = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL')
h = unicodedata.lookup('BOX DRAWINGS LIGHT HORIZONTAL')
dl = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND LEFT')
dr = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND RIGHT')
ul = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND LEFT')
ur = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND RIGHT')
vr = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND RIGHT')
vl = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND LEFT')
uh = unicodedata.lookup('BOX DRAWINGS LIGHT UP AND HORIZONTAL')
dh = unicodedata.lookup('BOX DRAWINGS LIGHT DOWN AND HORIZONTAL')
vh = unicodedata.lookup('BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL')
from sage.typeset.unicode_art import unicode_art as art
else:
v = '|'
h = '-'
dl = dr = ul = ur = vr = vl = uh = dh = vh = '+'
from sage.typeset.ascii_art import ascii_art as art
if (not data):
return ''
ncols = max((len(row) for row in data))
str_tab = ([([None] * ncols)] + [([(art(val) if (val is not None) else None) for val in row] + ([None] * (ncols - len(row)))) for row in data])
str_tab.append(([None] * ncols))
col_widths = ([1] * len(str_tab[0]))
if use_unicode:
def get_len(e):
if (e is None):
return 0
return (len(e) - list(str(e)).count('̄'))
else:
def get_len(e):
if (e is None):
return 0
return len(e)
for row in str_tab:
for (i, e) in enumerate(row):
col_widths[i] = max(col_widths[i], get_len(e))
matr = []
for (nrow, row) in enumerate(str_tab):
if (nrow == 0):
continue
l1 = ''
l2 = ''
for (i, (e, w)) in enumerate(zip(row, col_widths)):
prev_row = str_tab[(nrow - 1)]
if (i == 0):
if (e is None):
if (prev_row[i] is None):
l1 += (' ' * (3 + w))
else:
l1 += (ur + (h * (2 + w)))
l2 += (' ' * (3 + w))
else:
if (prev_row[i] is None):
l1 += (dr + (h * (2 + w)))
else:
l1 += (vr + (h * (2 + w)))
l2 += '{} {:^{width}} '.format(v, e, width=w)
elif (e is None):
if (row[(i - 1)] is None):
if (prev_row[(i - 1)] is None):
if (prev_row[i] is None):
l1 += (' ' * (3 + w))
else:
l1 += (ur + (h * (2 + w)))
elif (prev_row[i] is None):
l1 += (ul + (' ' * (2 + w)))
else:
l1 += (uh + (h * (2 + w)))
l2 += (' ' * (3 + w))
else:
if (prev_row[(i - 1)] is None):
if (prev_row[i] is None):
l1 += (dl + (' ' * (2 + w)))
else:
l1 += (vh + (h * (2 + w)))
elif (prev_row[i] is None):
l1 += (vl + (' ' * (2 + w)))
else:
l1 += (vh + (h * (2 + w)))
l2 += (v + (' ' * (2 + w)))
else:
if (row[(i - 1)] is None):
if (prev_row[(i - 1)] is None):
if (prev_row[i] is None):
l1 += (dr + (h * (2 + w)))
else:
l1 += (vr + (h * (2 + w)))
else:
l1 += (vh + (h * (2 + w)))
elif ((prev_row[(i - 1)] is None) and (prev_row[i] is None)):
l1 += (dh + (h * (2 + w)))
else:
l1 += (vh + (h * (2 + w)))
l2 += '{} {:^{width}} '.format(v, e, width=w)
if (row[(- 1)] is None):
if (prev_row[(- 1)] is None):
l1 += ' '
else:
l1 += ul
l2 += ' '
else:
if (prev_row[(- 1)] is None):
l1 += dl
else:
l1 += vl
l2 += v
matr.append(l1)
matr.append(l2)
matr.pop()
if (convention == 'English'):
return '\n'.join(matr)
else:
output = '\n'.join(reversed(matr))
if use_unicode:
tr = {ord(dl): ul, ord(dr): ur, ord(ul): dl, ord(ur): dr, ord(dh): uh, ord(uh): dh}
return output.translate(tr)
else:
return output
|
def ascii_art_table_russian(data, use_unicode=False, compact=False):
'\n Return an ascii art table of ``data`` for the russian convention.\n\n EXAMPLES::\n\n sage: from sage.combinat.output import ascii_art_table_russian\n sage: data = [[None, None, 1], [2, 2], [3,4,5], [None, None, 10], [], [6]]\n sage: print(ascii_art_table_russian(data))\n / \\ / \\\n / \\ / \\\n \\ 6 / \\ 10 \\\n \\ / \\ / \\\n \\ / \\ / \\\n X 5 /\n / \\ /\n / \\ /\n / 4 X\n / \\ / \\ / \\\n / \\ / \\ / \\\n \\ 3 X 2 X 1 /\n \\ / \\ / \\ /\n \\ / \\ / \\ /\n \\ 2 /\n \\ /\n \\ /\n sage: print(ascii_art_table_russian(data, use_unicode=True))\n ╱ ╲ ╱ ╲\n ╱ ╲ ╱ ╲\n ╲ 6 ╱ ╲ 10 ╲\n ╲ ╱ ╲ ╱ ╲\n ╲ ╱ ╲ ╱ ╲\n ╳ 5 ╱\n ╱ ╲ ╱\n ╱ ╲ ╱\n ╱ 4 ╳\n ╱ ╲ ╱ ╲ ╱ ╲\n ╱ ╲ ╱ ╲ ╱ ╲\n ╲ 3 ╳ 2 ╳ 1 ╱\n ╲ ╱ ╲ ╱ ╲ ╱\n ╲ ╱ ╲ ╱ ╲ ╱\n ╲ 2 ╱\n ╲ ╱\n ╲ ╱\n sage: data = [[1, None, 2], [None, 2]]\n sage: print(ascii_art_table_russian(data))\n / \\ / \\\n \\ 2 X 2 /\n \\ / \\ /\n X\n / \\\n \\ 1 /\n \\ /\n sage: print(ascii_art_table_russian(data, use_unicode=True))\n ╱ ╲ ╱ ╲\n ╲ 2 ╳ 2 ╱\n ╲ ╱ ╲ ╱\n ╳\n ╱ ╲\n ╲ 1 ╱\n ╲ ╱\n '
if use_unicode:
import unicodedata
urdl = unicodedata.lookup('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')
uldr = unicodedata.lookup('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')
x = unicodedata.lookup('BOX DRAWINGS LIGHT DIAGONAL CROSS')
else:
urdl = '/'
uldr = '\\'
x = 'X'
if (not data):
return ''
if use_unicode:
def get_len(e):
if (e is None):
return 0
return (len(e) - list(str(e)).count('̄'))
else:
def get_len(e):
if (e is None):
return 0
return len(e)
str_tab = [[(str(val) if (val is not None) else None) for val in row] for row in data]
max_str = max([max(([1] + [get_len(e) for e in row])) for row in str_tab])
max_str = ((max_str + 1) - (max_str % 2))
if compact:
diag_length = max_str
else:
diag_length = (max_str + 2)
row_height = int(((diag_length + 1) // 2))
max_height = max(((a + len(val)) for (a, val) in enumerate(str_tab)))
str_list = []
for k in range(max_height, (- 1), (- 1)):
for i in range(row_height):
if ((k == max_height) and (i == 0)):
continue
st = (' ' * ((max_height - k) * row_height))
for j in range((k + 1)):
N_box = box_exists(str_tab, ((k - j) + 1), j)
S_box = box_exists(str_tab, (k - j), (j - 1))
SE_box = box_exists(str_tab, ((k - j) - 1), j)
E_box = box_exists(str_tab, (k - j), j)
W_box = box_exists(str_tab, ((k - j) + 1), (j - 1))
if (i == 0):
if ((N_box and S_box) or (W_box and E_box)):
st += x
elif ((E_box and S_box) or (W_box and N_box)):
st += urdl
elif ((E_box and N_box) or (W_box and S_box)):
st += uldr
elif E_box:
st += uldr
elif W_box:
st += urdl
else:
st += ' '
if E_box:
st_num = str_tab[(k - j)][j]
ln_left = int(((len(st_num) - (len(st_num) % 2)) / 2))
st += st_num.rjust((((row_height - 1) - ln_left) + len(st_num)), ' ').ljust(diag_length, ' ')
else:
st += (' ' * diag_length)
if ((j == k) and E_box):
st += urdl
else:
lstr = ' '
rstr = ' '
if (E_box or S_box):
lstr = uldr
if (E_box or SE_box):
rstr = urdl
st += (' ' * i)
st += lstr
st += (' ' * ((2 * (row_height - i)) - 1))
st += rstr
st += (' ' * (i - 1))
str_list.append(st)
import re
mm = (min((len(re.search('^ +', l)[0]) for l in str_list)) - 1)
str_list = [l[mm:].rstrip() for l in str_list]
while (str_list[(- 1)] == ''):
str_list.pop()
return '\n'.join(str_list)
|
def box_exists(tab, i, j):
"\n Return ``True`` if ``tab[i][j]`` exists and is not ``None``; in particular this\n allows for `tab[i][j]` to be ``''`` or ``0``.\n\n INPUT:\n\n - ``tab`` -- a list of lists\n - ``i`` -- first coordinate\n - ``j`` -- second coordinate\n\n TESTS::\n\n sage: from sage.combinat.output import box_exists\n sage: tab = [[1,None,'', 0],[None]]\n sage: box_exists(tab, 0, 0)\n True\n sage: box_exists(tab, 0, 1)\n False\n sage: box_exists(tab, 0, 2)\n True\n sage: box_exists(tab, 0, 3)\n True\n sage: box_exists(tab, 0, 4)\n False\n sage: box_exists(tab, 1, 0)\n False\n sage: box_exists(tab, 1, 1)\n False\n sage: box_exists(tab, 0, -1)\n False\n "
if ((j < 0) or (i < 0)):
return False
return ((len(tab) > i) and (len(tab[i]) > j) and (tab[i][j] is not None))
|
class LocalOptions():
'\n This class allow to add local options to an object.\n LocalOptions is like a dictionary, it has keys and values that represent\n options and the values associated to the option. This is useful to\n decorate an object with some optional informations.\n\n :class:`LocalOptions` should be used as follow.\n\n INPUT:\n\n - ``name`` -- The name of the LocalOptions\n\n - ``<options>=dict(...)`` -- dictionary specifying an option\n\n The options are specified by keyword arguments with their values\n being a dictionary which describes the option. The\n allowed/expected keys in the dictionary are:\n\n - ``checker`` -- a function for checking whether a particular value for\n the option is valid\n - ``default`` -- the default value of the option\n - ``values`` -- a dictionary of the legal values for this option (this\n automatically defines the corresponding ``checker``); this dictionary\n gives the possible options, as keys, together with a brief description\n of them\n\n ::\n\n sage: from sage.combinat.parallelogram_polyomino import LocalOptions\n sage: o = LocalOptions(\n ....: \'Name Example\',\n ....: delim=dict(\n ....: default=\'b\',\n ....: values={\'b\':\'the option b\', \'p\':\'the option p\'}\n ....: )\n ....: )\n sage: class Ex:\n ....: options=o\n ....: def _repr_b(self): return "b"\n ....: def _repr_p(self): return "p"\n ....: def __repr__(self): return self.options._dispatch(\n ....: self, \'_repr_\',\'delim\'\n ....: )\n sage: e = Ex(); e\n b\n sage: e.options(delim=\'p\'); e\n p\n\n This class is temporary, in the future, this class should be integrated in\n sage.structure.global_options.py. We should split global_option in two\n classes LocalOptions and GlobalOptions.\n '
def __init__(self, name='', **options):
'\n Construct a new LocalOptions.\n\n INPUT:\n\n - ``name`` -- The name of the LocalOptions\n\n - ``<options>=dict(...)`` -- dictionary specifying an option\n\n The options are specified by keyword arguments with their values\n being a dictionary which describes the option. The\n allowed/expected keys in the dictionary are:\n\n - ``checker`` -- a function for checking whether a particular value for\n the option is valid\n - ``default`` -- the default value of the option\n - ``values`` -- a dictionary of the legal values for this option (this\n automatically defines the corresponding ``checker``); this dictionary\n gives the possible options, as keys, together with a brief\n description of them.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n '
self._name = name
self._available_options = options
self._options = {}
for key in self._available_options:
self._options[key] = self._available_options[key]['default']
def __repr__(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n sage: o\n Current options for Name Example\n - display: \'list\'\n - tikz_options: \'toto\'\n '
options = list(self._options)
if (options == []):
return 'Current options for {}'.format(self._name)
options.sort()
width = (1 + max((len(key) for key in options)))
txt = '\n'.join((' - {:{}} {}'.format((key + ':'), width, pprint.pformat(self[key])) for key in options))
return 'Current options for {}\n{}'.format(self._name, txt)
def __setitem__(self, key, value):
'\n The ``__setitem__`` method is used to change the current values of the\n options. It also checks that the supplied options are valid and changes\n any alias to its generic value.\n\n INPUT:\n\n - ``key`` -- An option.\n\n - ``value`` -- The value.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: ),\n ....: size=dict(\n ....: default=1,\n ....: checker=lambda x : x in NN\n ....: )\n ....: )\n sage: o("display")\n \'list\'\n sage: o["display"]="diagram"\n sage: o("display")\n \'diagram\'\n sage: o["display"]="?"\n Current value : diagram\n {\'default\': \'list\', \'values\':\n {\'diagram\': \'diagram representation\',\n \'list\': \'list representation\'}}\n sage: o("size")\n 1\n sage: o["size"]=3\n sage: o("size")\n 3\n sage: o["size"]=-6\n\n '
assert (key in self._available_options)
if (value == '?'):
res = ('Current value : ' + str(self._options[key]))
option_key = self._available_options[key]
if ('values' in option_key):
res += ('\n' + pprint.pformat(self._available_options[key]))
print(res)
else:
available_options = self._available_options
if ('values' in available_options):
assert (value in self._available_options[key]['values'])
if ('checker' in available_options):
assert available_options['checker'](value)
self._options[key] = value
def __call__(self, *get_values, **options):
'\n Get or set value of the option ``option``.\n\n INPUT:\n\n - ``get_values`` -- The options to be printed.\n\n - ``<options>=dict(...)`` -- dictionary specifying an option see\n :class:`LocalOptions` for more details.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n sage: o("display")\n \'list\'\n sage: o(display="diagram")\n sage: o("display")\n \'diagram\'\n sage: o(display="?")\n Current value : diagram\n {\'default\': \'list\', \'values\':\n {\'diagram\': \'diagram representation\',\n \'list\': \'list representation\'}}\n\n '
for key in options:
value = options[key]
self.__setitem__(key, value)
for key in get_values:
return self.__getitem__(key)
def __getitem__(self, key):
'\n Return the current value of the option ``key``.\n\n INPUT:\n\n - ``key`` -- An option.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n sage: o["display"]\n \'list\'\n '
return self._options[key]
def __iter__(self):
'\n A generator for the options in ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n sage: all(key in [\'tikz_options\',\'display\'] for key in o)\n True\n '
return self._available_options.__iter__()
def keys(self) -> list[str]:
'\n Return the list of the options in ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: LocalOptions\n ....: )\n sage: o = LocalOptions(\n ....: "Name Example",\n ....: tikz_options=dict(\n ....: default="toto",\n ....: values=dict(\n ....: toto="name",\n ....: x="3"\n ....: )\n ....: ),\n ....: display=dict(\n ....: default="list",\n ....: values=dict(\n ....: list="list representation",\n ....: diagram="diagram representation"\n ....: )\n ....: )\n ....: )\n sage: keys=o.keys()\n sage: keys.sort()\n sage: keys\n [\'display\', \'tikz_options\']\n '
return list(self)
def _dispatch(self, obj, dispatch_to, option, *get_values, **set_values):
'\n The *dispatchable* options are options which dispatch related methods\n of the corresponding class. The format for specifying a dispatchable\n option is to include ``dispatch_to = <option name>`` in the\n specifications for the options and then to add the options to the\n class.\n\n The ``_dispatch`` method will then call the method named\n ``<option name> + \'_\' + <current value of option>`` of ``obj``\n with arguments ``*get_values, **set_values``.\n\n Note that the argument ``self`` is necessary here because the\n dispatcher is a method of the options class and not of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import LocalOptions\n sage: delim = {\'default\': \'b\',\n ....: \'values\': {\'b\': \'option b\', \'p\': \'option p\'}}\n sage: o = LocalOptions(\'Name example\', delim=delim)\n sage: class Ex:\n ....: options=o\n ....: def _repr_b(self): return "b"\n ....: def _repr_p(self): return "p"\n ....: def __repr__(self): return self.options._dispatch(\n ....: self, \'_repr_\',\'delim\')\n sage: e = Ex(); e\n b\n sage: e.options(delim=\'p\'); e\n p\n '
assert (option in self._available_options)
if (dispatch_to[(- 1)] == '_'):
dispatch_to = dispatch_to[:(- 1)]
f = getattr(obj, ((dispatch_to + '_') + str(self._options[option])))
return f(*get_values, **set_values)
|
class _drawing_tool():
"\n Technical class to produce TIKZ drawing.\n\n This class contains some 2D geometric tools to produce some TIKZ\n drawings.\n\n With that classes you can use options to set up drawing informations.\n Then the class will produce a drawing by using those informations.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, default_tikz_options,\n ....: ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_line([1, 1], [-1, -1])\n '\\n \\\\draw[color=black, line width=1] (1.000000, 1.000000) --\n (-1.000000, -1.000000);'\n\n sage: fct = lambda vec: [2*vec[0], vec[1]]\n sage: dt = _drawing_tool(opt, fct)\n sage: dt.draw_line([1, 1], [-1, -1])\n '\\n \\\\draw[color=black, line width=1] (2.000000, 1.000000) --\n (-2.000000, -1.000000);'\n\n sage: import copy\n sage: opt = copy.deepcopy(opt)\n sage: opt['mirror'] = [0,1]\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_line([1, 1], [-1, -1])\n '\\n \\\\draw[color=black, line width=1] (-1.000000, 1.000000) --\n (1.000000, -1.000000);'\n\n "
def __init__(self, options, XY=(lambda v: v)):
"\n Construct a drawing tools to produce some TIKZ drawing.\n\n INPUT:\n\n - ``options`` -- drawing options\n\n - ``XY`` -- A user function to convert vector in other vector.\n (default : identity function)\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, default_tikz_options,\n ....: ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_line([1, 1], [-1, -1])\n '\\n \\\\draw[color=black, line width=1] (1.000000, 1.000000) --\n (-1.000000, -1.000000);'\n "
self._XY = (lambda v: XY([float(v[0]), float(v[1])]))
self._translation = options['translation']
self._mirror = options['mirror']
self._rotation = options['rotation']
self._color_line = options['color_line']
self._line_size = options['line_size']
self._point_size = options['point_size']
self._color_point = options['color_point']
def XY(self, v):
"\n This function give the image of v by some transformation given by the\n drawing option of ``_drawing_tool``.\n\n The transformation is the composition of rotation, mirror, translation\n and XY user function.\n\n First we apply XY function, then the translation, then the mirror and\n finally the rotation.\n\n INPUT:\n\n - ``v`` -- The vector to transform.\n\n OUTPUT:\n\n A list of 2 floats encoding a vector.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.XY([1, 1])\n [1.0, 1.0]\n\n sage: fct = lambda vec: [2*vec[0], vec[1]]\n sage: dt = _drawing_tool(opt, fct)\n sage: dt.XY([1, 1])\n [2.0, 1.0]\n\n sage: import copy\n sage: opt = copy.deepcopy(opt)\n sage: opt['mirror'] = [0, 1]\n sage: dt = _drawing_tool(opt)\n sage: dt.XY([1, 1])\n [-1.0, 1.0]\n "
def translate(pos, v):
'\n Translate a position with a vector.\n\n INPUT:\n\n - ``pos`` -- The position to translate.\n\n - ``v`` -- The translation vector.\n\n OUTPUT:\n\n The translated position.\n '
return [(pos[0] + v[0]), (pos[1] + v[1])]
def rotate(pos, angle):
'\n Rotate by `angle` a position around the origin.\n\n INPUT:\n\n - ``pos`` -- The position to rotate.\n\n - ``angle`` -- The angle of rotation.\n\n OUTPUT:\n\n The rotated position.\n '
[x, y] = pos
return [((x * cos(angle)) - (y * sin(angle))), ((x * sin(angle)) + (y * cos(angle)))]
def mirror(pos, axe):
'\n Return the mirror of a position according to a given axe.\n\n INPUT:\n\n - ``pos`` -- The position to mirror.\n\n - ``axe`` -- The axe vector.\n\n OUTPUT:\n\n The mirrored position.\n '
if (axe is None):
return pos
if (not isinstance(axe, (list, tuple))):
raise ValueError(('mirror option should be None or a list of two real' + ' encoding a 2D vector.'))
n = float(sqrt(((axe[0] ** 2) + (axe[1] ** 2))))
axe[0] = float((axe[0] / n))
axe[1] = float((axe[1] / n))
sp = ((pos[0] * axe[0]) + (pos[1] * axe[1]))
sn = (((- pos[0]) * axe[1]) + (pos[1] * axe[0]))
return [((sp * axe[0]) + (sn * axe[1])), ((sp * axe[1]) - (sn * axe[0]))]
return rotate(mirror(translate(self._XY(v), self._translation), self._mirror), self._rotation)
def draw_line(self, v1, v2, color=None, size=None):
"\n Return the TIKZ code for a line.\n\n INPUT:\n\n - ``v1`` -- point, The first point of the line.\n\n - ``v2`` -- point, The second point of the line.\n\n - ``color`` -- string (default:``None``), The color of the line.\n If set to ``None``, the color is chosen according the\n drawing option given by ``_drawing_tool``.\n\n - ``size`` -- integer (default:``None``), The size of the line.\n If set to ``None``, the size is chosen according the\n drawing option given by ``_drawing_tool``.\n\n OUTPUT:\n\n The code of a line in TIKZ.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_line([1, 1], [-1, -1])\n '\\n \\\\draw[color=black, line width=1] (1.000000, 1.000000) --\n (-1.000000, -1.000000);'\n "
if (color is None):
color = self._color_line
if (size is None):
size = self._line_size
[x1, y1] = self.XY(v1)
[x2, y2] = self.XY(v2)
return ('\n \\draw[color=%s, line width=%s] (%f, %f) -- (%f, %f);' % (color, size, float(x1), float(y1), float(x2), float(y2)))
def draw_polyline(self, list_of_vertices, color=None, size=None):
"\n Return the TIKZ code for a polyline.\n\n INPUT:\n\n - ``list_of_vertices`` -- A list of points\n\n - ``color`` -- string (default:``None``), The color of the line.\n If set to ``None``, the color is chosen according the\n drawing option given by ``_drawing_tool``.\n\n - ``size`` -- integer (default:``None``), The size of the line.\n If set to ``None``, the size is chosen according the\n drawing option given by ``_drawing_tool``.\n\n OUTPUT:\n\n The code of a polyline in TIKZ.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_polyline([[1, 1], [-1, -1], [0,0]])\n '\\n \\\\draw[color=black, line width=1] (1.000000, 1.000000) --\n (-1.000000, -1.000000);\\n \\\\draw[color=black, line width=1]\n (-1.000000, -1.000000) -- (0.000000, 0.000000);'\n "
res = ''
for i in range((len(list_of_vertices) - 1)):
res += self.draw_line(list_of_vertices[i], list_of_vertices[(i + 1)], color, size)
return res
def draw_point(self, p1, color=None, size=None):
"\n Return the TIKZ code for a point.\n\n\n INPUT:\n\n - ``p1`` -- A point\n\n - ``color`` -- string (default:``None``), The color of the line.\n If set to ``None``, the color is chosen according the\n drawing option given by ``_drawing_tool``.\n\n - ``size`` -- integer (default:``None``), The size of the line.\n If set to ``None``, the size is chosen according the\n drawing option given by ``_drawing_tool``.\n\n OUTPUT:\n\n The code of a point in TIKZ.\n\n EXAMPLES::\n\n sage: from sage.combinat.parallelogram_polyomino import (\n ....: _drawing_tool, ParallelogramPolyominoesOptions\n ....: )\n sage: opt = ParallelogramPolyominoesOptions['tikz_options']\n sage: dt = _drawing_tool(opt)\n sage: dt.draw_point([1, 1])\n '\\n \\\\filldraw[color=black] (1.000000, 1.000000) circle (3.5pt);'\n "
if (color is None):
color = self._color_point
if (size is None):
size = self._point_size
[x1, y1] = self.XY(p1)
return ('\n \\filldraw[color=%s] (%f, %f) circle (%spt);' % (color, float(x1), float(y1), size))
|
class ParallelogramPolyomino(ClonableList, metaclass=InheritComparisonClasscallMetaclass):
'\n Parallelogram Polyominoes.\n\n A parallelogram polyomino is a finite connected union of cells\n whose boundary can be decomposed in two paths, the upper and the lower\n paths, which are comprised of north and east unit steps and meet only at\n their starting and final points.\n\n Parallelogram Polyominoes can be defined with those two paths.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp\n [[0, 1], [1, 0]]\n '
@staticmethod
def __classcall_private__(cls, *args, **opts):
'\n Ensure that parallelogram polyominoes created by the enumerated sets\n are instances of :class:`ParallelogramPolyomino` and have the same\n parent.\n\n TESTS::\n\n sage: issubclass(\n ....: ParallelogramPolyominoes().element_class,\n ....: ParallelogramPolyomino\n ....: )\n True\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.parent()\n Parallelogram polyominoes\n sage: str(type(pp)) == (\n ....: "<class \'sage.combinat.parallelogram_polyomino" +\n ....: ".ParallelogramPolyominoes_all_with_category" +\n ....: ".element_class\'>"\n ....: )\n True\n\n sage: pp1 = ParallelogramPolyominoes()([[0, 1], [1, 0]])\n sage: pp1.parent() is pp.parent()\n True\n sage: type(pp1) is type(pp)\n True\n\n sage: pp1 = ParallelogramPolyominoes(2)([[0, 1], [1, 0]])\n sage: pp1.parent() is pp.parent()\n True\n sage: type(pp1) is type(pp)\n True\n '
return cls._auto_parent._element_constructor_(*args, **opts)
@lazy_class_attribute
def _auto_parent(cls):
'\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino._auto_parent\n Parallelogram polyominoes\n sage: ParallelogramPolyominoes()([[0, 1], [1, 0]]).parent()\n Parallelogram polyominoes\n '
return ParallelogramPolyominoes()
def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(ParallelogramPolyomino([[0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]]))\n ***\n ****\n ***\n ***\n **\n *\n sage: ascii_art(ParallelogramPolyomino([[0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]]))\n **\n ***\n ***\n ***\n **\n **\n '
from sage.typeset.ascii_art import AsciiArt
data = zip(self.lower_widths(), self.upper_widths())
txt = []
for (x, y) in data:
txt += [((' ' * x) + ('*' * (y - x)))]
return AsciiArt(txt)
def _unicode_art_(self):
'\n TESTS::\n\n sage: unicode_art(ParallelogramPolyomino([[0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]]))\n ┌┬┬┐\n ├┼┼┼┐\n └┼┼┼┤\n └┼┼┼┐\n └┼┼┤\n └┼┤\n └┘\n sage: unicode_art(ParallelogramPolyomino([[0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]]))\n ┌┬┐\n ├┼┼┐\n ├┼┼┤\n ├┼┼┤\n └┴┼┼┐\n └┼┼┐\n └┴┘\n '
from sage.typeset.unicode_art import UnicodeArt
data = list(zip(self.lower_widths(), self.upper_widths()))
txt = [(('┌' + ('┬' * (data[0][1] - 1))) + '┐')]
for i in range(1, len(data)):
(x1, y1) = data[(i - 1)]
(x2, y2) = data[i]
line = [(' ' * x1)]
if (x1 == x2):
line += ['├']
else:
line += [(('└' + ('┴' * ((x2 - x1) - 1))) + '┼')]
line += [('┼' * ((y1 - x2) - 1))]
if (y1 == y2):
line += ['┤']
else:
line += [(('┼' + ('┬' * ((y2 - y1) - 1))) + '┐')]
txt += [''.join(line)]
txt += [((((' ' * data[(- 1)][0]) + '└') + ('┴' * ((data[(- 1)][1] - data[(- 1)][0]) - 1))) + '┘')]
return UnicodeArt(txt, baseline=0)
def check(self):
'\n This method raises an error if the internal data of the class does not\n represent a parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp = ParallelogramPolyomino([[1], [1]])\n\n sage: pp = ParallelogramPolyomino( # indirect doctest\n ....: [[1, 0], [0, 1]]\n ....: )\n Traceback (most recent call last):\n ...\n ValueError: the lower and upper paths are crossing\n\n sage: pp = ParallelogramPolyomino([[1], [0, 1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the lower and upper paths have different sizes (2 != 1)\n\n sage: pp = ParallelogramPolyomino([[1], [0]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the two paths have distinct ends\n\n sage: pp = ParallelogramPolyomino([[0], [1]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the two paths have distinct ends\n\n sage: pp = ParallelogramPolyomino([[0], [0]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the lower or the upper path can...t be equal to [0]\n\n sage: pp = ParallelogramPolyomino([[], [0]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the lower or the upper path can...t be equal to []\n\n sage: pp = ParallelogramPolyomino([[0], []]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the lower or the upper path can...t be equal to []\n\n sage: pp = ParallelogramPolyomino([[], []]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: the lower or the upper path can...t be equal to []\n '
lower_path = self.lower_path()
upper_path = self.upper_path()
if ((lower_path == [0]) and (upper_path == [0])):
raise ValueError("the lower or the upper path can't be equal to [0]")
if ((lower_path == []) or (upper_path == [])):
raise ValueError("the lower or the upper path can't be equal to []")
if (len(upper_path) != len(lower_path)):
raise ValueError(('the lower and upper paths have different sizes (%s != %s)' % (len(upper_path), len(lower_path))))
p_up = [0, 0]
p_down = [0, 0]
for i in range((len(upper_path) - 1)):
p_up[(1 - upper_path[i])] += 1
p_down[(1 - lower_path[i])] += 1
if ((p_up[0] <= p_down[0]) or (p_down[1] <= p_up[1])):
raise ValueError('the lower and upper paths are crossing')
p_up[(1 - upper_path[(- 1)])] += 1
p_down[(1 - lower_path[(- 1)])] += 1
if ((p_up[0] != p_down[0]) or (p_up[1] != p_down[1])):
raise ValueError('the two paths have distinct ends')
def __hash__(self):
'\n Return the hash code of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: hash(pp) == hash((\n ....: (0, 0, 0, 1, 0, 1, 0, 1, 1), (1, 0, 1, 1, 0, 0, 1, 0, 0)\n ....: ))\n True\n\n sage: PPS = ParallelogramPolyominoes(8)\n sage: D = { PPS[0]: True, PPS[1]: True }\n sage: D[PPS[0]] = False\n sage: import pprint\n sage: pp = pprint.PrettyPrinter()\n sage: pp.pprint(D)\n {[[0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0]]: False,\n [[0, 0, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0]]: True}\n '
return hash(tuple(map(tuple, list(self))))
def __copy__(self):
'\n Copy a parallelogram Polyomino\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp1 = copy(pp)\n sage: pp1 is pp\n False\n sage: pp1 == pp\n True\n sage: pp1\n [[0, 0, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 1, 0, 0, 1, 0, 0]]\n '
return ParallelogramPolyomino([self.lower_path(), self.upper_path()])
def __init__(self, parent, value, check=True):
'\n Construct a parallelogram polyomino.\n\n The input is a pair of lower path and upper path.\n\n The lower and upper paths of the empty parallelogram polyomino are\n [1] and [1].\n\n EXAMPLES::\n\n sage: lower_path = [0, 0, 1, 0, 1, 1]\n sage: upper_path = [1, 1, 0, 1, 0, 0]\n sage: pp = ParallelogramPolyomino([lower_path, upper_path])\n sage: pp\n [[0, 0, 1, 0, 1, 1], [1, 1, 0, 1, 0, 0]]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp\n [[0, 1], [1, 0]]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp\n [[1], [1]]\n '
ClonableList.__init__(self, parent, value)
if check:
if (not isinstance(value, (list, tuple))):
raise ValueError(('value %s must be a list or a tuple' % value))
self.check()
self._options = None
def reflect(self) -> ParallelogramPolyomino:
'\n Return the parallelogram polyomino obtained by switching rows and\n columns.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,0,0,0,1,1,0,1,0,1], [1,0,1,0,0,1,1,0,0,0]])\n sage: pp.heights(), pp.upper_heights()\n ([4, 3, 2, 3], [0, 1, 3, 3])\n sage: pp = pp.reflect()\n sage: pp.widths(), pp.lower_widths()\n ([4, 3, 2, 3], [0, 1, 3, 3])\n\n sage: pp = ParallelogramPolyomino([[0,0,0,1,1], [1,0,0,1,0]])\n sage: ascii_art(pp)\n *\n *\n **\n sage: ascii_art(pp.reflect())\n ***\n *\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.reflect()\n [[1], [1]]\n '
if (self.size() == 1):
return self
(a, b) = self
return ParallelogramPolyomino([[(1 - v) for v in b], [(1 - v) for v in a]])
def rotate(self) -> ParallelogramPolyomino:
'\n Return the parallelogram polyomino obtained by rotation of 180 degrees.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,0,0,1,1], [1,0,0,1,0]])\n sage: ascii_art(pp)\n *\n *\n **\n sage: ascii_art(pp.rotate())\n **\n *\n *\n '
(a, b) = self
return ParallelogramPolyomino([b[::(- 1)], a[::(- 1)]])
def _to_dyck_delest_viennot(self):
'\n Convert to a Dyck word using the Delest-Viennot bijection.\n\n This bijection is described on page 179 and page 180 Figure 6\n in the article [DeVi1984]_, where it is called the classical\n bijection `\\gamma`.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0]])\n sage: pp._to_dyck_delest_viennot()\n [1, 1, 0, 1, 1, 0, 1, 0, 0, 0]\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp._to_dyck_delest_viennot()\n []\n\n '
from sage.combinat.dyck_word import DyckWord
dyck = []
dick_size = (self.size() - 1)
if (not dick_size):
return DyckWord([])
upper_path = self.upper_path()
lower_path = self.lower_path()
dyck.append((1 - lower_path[0]))
for i in range(1, dick_size):
dyck.append(upper_path[i])
dyck.append((1 - lower_path[i]))
dyck.append(upper_path[dick_size])
return DyckWord(dyck)
def _to_dyck_delest_viennot_peaks_valleys(self):
'\n Convert to a Dyck word using the Delest-Viennot bijection `\\beta`.\n\n This bijection is described on page 182 and Figure 8 in the\n article [DeVi1984]_. It returns the unique Dyck path whose\n peak heights are the column heights and whose valley heights\n are the overlaps between adjacent columns.\n\n EXAMPLES:\n\n This is the example in Figure 8 of [DeVi1984]_::\n\n sage: pp = ParallelogramPolyomino([[0,0,0,0,1,1,0,1,0,1], [1,0,1,0,0,1,1,0,0,0]])\n sage: pp._to_dyck_delest_viennot_peaks_valleys()\n [1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp._to_dyck_delest_viennot_peaks_valleys()\n []\n '
from sage.combinat.dyck_word import DyckWord
a = self.heights()
u = self.upper_heights()
b = (([0] + [(((a[i] - u[(i + 1)]) + u[i]) - 1) for i in range((len(a) - 1))]) + [0])
dyck = []
for i in range(len(a)):
dyck.extend(([1] * (a[i] - b[i])))
dyck.extend(([0] * (a[i] - b[(i + 1)])))
return DyckWord(dyck)
@combinatorial_map(name='To Dyck word')
def to_dyck_word(self, bijection=None):
"\n Convert to a Dyck word.\n\n INPUT:\n\n - ``bijection`` -- string or ``None`` (default:``None``) The name of\n the bijection. If it is set to ``None`` then the ``'Delest-Viennot'``\n bijection is used.\n Expected values are ``None``, ``'Delest-Viennot'``, or ``'Delest-Viennot-beta'``.\n\n OUTPUT:\n\n a Dyck word\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0]])\n sage: pp.to_dyck_word()\n [1, 1, 0, 1, 1, 0, 1, 0, 0, 0]\n sage: pp.to_dyck_word(bijection='Delest-Viennot')\n [1, 1, 0, 1, 1, 0, 1, 0, 0, 0]\n\n sage: pp.to_dyck_word(bijection='Delest-Viennot-beta')\n [1, 0, 1, 1, 1, 0, 1, 0, 0, 0]\n "
if ((bijection is None) or (bijection == 'Delest-Viennot')):
return self._to_dyck_delest_viennot()
if (bijection == 'Delest-Viennot-beta'):
return self._to_dyck_delest_viennot_peaks_valleys()
raise ValueError('the given bijection is not valid')
@staticmethod
def _from_dyck_word_delest_viennot(dyck):
'\n Convert a Dyck word to a parallelogram polyomino using the Delest\n Viennot bijection.\n\n This bijection is described on page 179 and page 180 Figure 6 in\n the article [DeVi1984]_, where it is called the classical\n bijection `\\gamma`.\n\n INPUT:\n\n - ``dyck`` -- a Dyck word\n\n OUTPUT:\n\n A parallelogram polyomino.\n\n EXAMPLES::\n\n sage: dyck = DyckWord([1, 1, 0, 1, 1, 0, 1, 0, 0, 0])\n sage: ParallelogramPolyomino._from_dyck_word_delest_viennot(dyck)\n [[0, 1, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0]]\n\n TESTS::\n\n sage: gamma = ParallelogramPolyomino._to_dyck_delest_viennot\n sage: gamma_inv = ParallelogramPolyomino._from_dyck_word_delest_viennot\n sage: all(all(D == gamma(gamma_inv(D)) for D in DyckWords(n)) for n in range(7))\n True\n '
l = (([1] + list(dyck)) + [0])
word_up = []
word_down = []
for i in range(0, len(l), 2):
word_up.append(l[i])
word_down.append((1 - l[(i + 1)]))
return ParallelogramPolyomino([word_down, word_up])
@staticmethod
def _from_dyck_word_delest_viennot_peaks_valleys(dyck):
'\n Convert a Dyck word to a parallelogram polyomino using the Delest\n Viennot bijection `\\beta`.\n\n This bijection is described on page 182 and Figure 8 in\n the article [DeVi1984]_.\n\n INPUT:\n\n - ``dyck`` -- a Dyck word\n\n OUTPUT:\n\n A parallelogram polyomino.\n\n EXAMPLES::\n\n sage: dyck = DyckWord([1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0])\n sage: ParallelogramPolyomino._from_dyck_word_delest_viennot_peaks_valleys(dyck)\n [[0, 0, 0, 0, 1, 1, 0, 1, 0, 1], [1, 0, 1, 0, 0, 1, 1, 0, 0, 0]]\n\n sage: dyck = DyckWord([1,1,0,1,1,1,1,1,0,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0])\n sage: ParallelogramPolyomino._from_dyck_word_delest_viennot_peaks_valleys(dyck)\n [[0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0]]\n\n TESTS::\n\n sage: beta = ParallelogramPolyomino._to_dyck_delest_viennot_peaks_valleys\n sage: beta_inv = ParallelogramPolyomino._from_dyck_word_delest_viennot_peaks_valleys\n sage: all(all(D == beta(beta_inv(D)) for D in DyckWords(n)) for n in range(7))\n True\n '
if (not dyck):
return ParallelogramPolyomino([[1], [1]])
a = []
b = [0]
h = 0
for i in range((len(dyck) - 1)):
if (dyck[i] == 1):
h += 1
if (dyck[(i + 1)] == 0):
a.append(h)
else:
if (dyck[(i + 1)] == 1):
b.append(h)
h -= 1
b.append(0)
word_down = []
word_up = []
for i in range(len(a)):
word_down.extend((([0] * (a[i] - b[i])) + [1]))
word_up.extend(([1] + ([0] * (a[i] - b[(i + 1)]))))
return ParallelogramPolyomino([word_down, word_up])
@staticmethod
def from_dyck_word(dyck, bijection=None):
"\n Convert a Dyck word to parallelogram polyomino.\n\n INPUT:\n\n - ``dyck`` -- a Dyck word\n\n - ``bijection`` -- string or ``None`` (default:``None``) the bijection\n to use. See :meth:`to_dyck_word` for more details.\n\n OUTPUT:\n\n A parallelogram polyomino.\n\n EXAMPLES::\n\n sage: dyck = DyckWord([1, 1, 0, 1, 1, 0, 1, 0, 0, 0])\n sage: ParallelogramPolyomino.from_dyck_word(dyck)\n [[0, 1, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0]]\n sage: ParallelogramPolyomino.from_dyck_word(dyck, bijection='Delest-Viennot')\n [[0, 1, 0, 0, 1, 1], [1, 1, 1, 0, 0, 0]]\n sage: ParallelogramPolyomino.from_dyck_word(dyck, bijection='Delest-Viennot-beta')\n [[0, 0, 1, 0, 1, 1], [1, 1, 1, 0, 0, 0]]\n "
if ((bijection is None) or (bijection == 'Delest-Viennot')):
return ParallelogramPolyomino._from_dyck_word_delest_viennot(dyck)
if (bijection == 'Delest-Viennot-beta'):
return ParallelogramPolyomino._from_dyck_word_delest_viennot_peaks_valleys(dyck)
raise ValueError('the given bijection is not valid')
def _to_binary_tree_Aval_Boussicault(self, position=None):
'\n Convert to a binary tree using the Aval-Boussicault algorithm.\n\n You can use the parameter ``position`` to use the bijection on\n a new parallelogram polyomino (PP). This PP is obtained by cutting the\n PP in such a way the cell at position ``position`` becomes the\n top-left most corner of the PP.\n\n Reference: [ABBS2013]_\n\n INPUT:\n\n - ``position`` -- the cell position. This is a recursive parameter.\n It should not be used directly.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp._to_binary_tree_Aval_Boussicault()\n [[., [[., .], [[., [., .]], .]]], [[., .], .]]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp._to_binary_tree_Aval_Boussicault()\n [., .]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp._to_binary_tree_Aval_Boussicault()\n .\n '
from sage.combinat.binary_tree import BinaryTree
if (position is None):
position = [0, 0]
if (self.size() == 1):
return BinaryTree()
result = [BinaryTree(), BinaryTree()]
right_son = list(position)
left_son = list(position)
w = (right_son[1] + 1)
h = (left_son[0] + 1)
while (w < self.width()):
if (self[right_son[0]][w] == 1):
if (self[(right_son[0] - 1)][w] == 0):
right_son[1] = w
result[1] = self._to_binary_tree_Aval_Boussicault(right_son)
break
w += 1
while (h < self.height()):
if (self[h][left_son[1]] == 1):
if (self[h][(left_son[1] - 1)] == 0):
left_son[0] = h
result[0] = self._to_binary_tree_Aval_Boussicault(left_son)
break
h += 1
return BinaryTree(result)
@combinatorial_map(name='To binary tree')
def to_binary_tree(self, bijection=None):
"\n Convert to a binary tree.\n\n INPUT:\n\n - ``bijection`` -- string or ``None`` (default:``None``) The name of\n bijection to use for the conversion. The possible values are ``None``\n or ``'Aval-Boussicault'``. The ``None`` value is equivalent to\n ``'Aval-Boussicault'``.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp.to_binary_tree()\n [[., [[., .], [[., [., .]], .]]], [[., .], .]]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.to_binary_tree()\n [., .]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.to_binary_tree()\n .\n "
if ((bijection is None) or (bijection == 'Aval-Boussicault')):
return self._to_binary_tree_Aval_Boussicault([0, 0])
def _to_ordered_tree_via_dyck(self):
'\n Convert the parallelogram polyominoe (PP) by using first the\n Delest-Viennot bijection between PP and Dyck paths, and then\n by using the classical bijection between Dyck paths and\n ordered trees.\n\n This last bijection is described in [DerZak1980]_ (see page 12 and\n Figure 3.1 of page 13).\n\n See :meth:`_to_dyck_delest_viennot` for the exact references.\n See also :meth:`to_ordered_tree()`.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp._to_ordered_tree_via_dyck()\n [[]]\n\n sage: pp = ParallelogramPolyomino([[0, 1, 1], [1, 1, 0]])\n sage: pp._to_ordered_tree_via_dyck()\n [[[]]]\n\n sage: pp = ParallelogramPolyomino([[0, 0, 1], [1, 0, 0]])\n sage: pp._to_ordered_tree_via_dyck()\n [[], []]\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp._to_ordered_tree_via_dyck()\n [[[[]], [[[]], []]], [[]]]\n '
return self._to_dyck_delest_viennot().to_ordered_tree()
def _to_ordered_tree_Bou_Socci(self):
"\n Return the ordered tree using the Boussicault-Socci bijection.\n\n This bijection is described in the article [BRS2015]_.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp._to_ordered_tree_Bou_Socci()\n [[[[[]], [[[]]]]], [[]]]\n sage: pp.to_ordered_tree(bijection='Boussicault-Socci')\n [[[[[]], [[[]]]]], [[]]]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp._to_ordered_tree_Bou_Socci()\n [[]]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp._to_ordered_tree_Bou_Socci()\n []\n "
from sage.combinat.ordered_tree import OrderedTree
from sage.combinat.binary_tree import BinaryTree
def make_tree(b_tree, d):
'\n This is a technical function that converts binary tree to ordered\n tree with the following construction.\n\n Add a virtual root v such that the root become:\n\n - the left son of v if ``d`` is equal to 0;\n\n - the right son of v if ``d`` is equal to 1;\n\n Then now the vertices of the ordered tree are the vertices of\n the binary tree and the virtual root.\n\n The edges are defined as follow:\n\n - if v1 is a left (resp. right) son of v2 and v2 is a right\n (resp. left) son of v3, then, in the ordered tree, v2 is the\n father of v1;\n - if v1 is a left (resp. right) son of v2 and v2 is a left (resp.\n right) son of v3, then, in the ordered tree, v2 and v3 are\n brother and v2 are on the left of v3.\n\n For example, if d is equal to 1\n\n ::\n\n 1\n / \\\n 2 3\n /\n 7\n / \\\n 8 4\n \\\n 5\n \\\n 6\n\n becomes\n\n ::\n\n _____v_____\n | |\n ___1___ ____ 3\n | | |\n 2 ___7__ 8\n | | |\n 4 5 6\n\n and if d = 0, it becomes\n\n ::\n\n _________v________\n | | | |\n 1 2 ____7___ 8\n | | | |\n 3 4 5 6\n\n INPUT:\n\n - ``b_tree`` -- a binary tree\n\n - ``d`` -- 0 or 1\n\n OUTPUT:\n\n An ordered tree.\n '
if (b_tree == BinaryTree()):
return OrderedTree([])
res = []
res.append(make_tree(b_tree[(1 - d)], (1 - d)))
res += make_tree(b_tree[d], d)
return OrderedTree(res)
return make_tree(self.to_binary_tree(bijection='Aval-Boussicault'), 1)
@combinatorial_map(name='To ordered tree')
def to_ordered_tree(self, bijection=None):
"\n Return an ordered tree from the parallelogram polyomino.\n\n Different bijections can be specified.\n\n The bijection 'via dyck and Delest-Viennot' is the composition of\n :meth:`_to_dyck_delest_viennot` and the classical bijection between\n dyck paths and ordered trees.\n\n The bijection between Dyck Word and ordered trees is described\n in [DerZak1980]_ (See page 12 and 13 and Figure 3.1).\n\n The bijection 'Boussicault-Socci' is described in [BRS2015]_.\n\n INPUT:\n\n - ``bijection`` -- string or ``None`` (default:``None``) The name of\n bijection to use for the conversion. The possible value are ``None``,\n ``'Boussicault-Socci'`` or ``'via dyck and Delest-Viennot'``.\n The ``None`` value is equivalent to the ``'Boussicault-Socci'``\n value.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp.to_ordered_tree()\n [[[[[]], [[[]]]]], [[]]]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.to_ordered_tree()\n [[]]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.to_ordered_tree()\n []\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 1, 0, 1, 1, 0, 0, 0, 1, 0]\n ....: ]\n ....: )\n sage: pp.to_ordered_tree('via dyck and Delest-Viennot')\n [[[[]], [[[]], []]], [[]]]\n "
if ((bijection is None) or (bijection == 'Boussicault-Socci')):
return self._to_ordered_tree_Bou_Socci()
if (bijection == 'via dyck and Delest-Viennot'):
return self._to_ordered_tree_via_dyck()
def get_options(self):
"\n Return all the options of the object.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.get_options()\n Current options for ParallelogramPolyominoes_size\n - display: 'list'\n - drawing_components: {'bounce_0': False,\n 'bounce_1': False,\n 'bounce_values': False,\n 'diagram': True,\n 'tree': False}\n - latex: 'drawing'\n - tikz_options: {'color_bounce_0': 'red',\n 'color_bounce_1': 'blue',\n 'color_line': 'black',\n 'color_point': 'black',\n 'line_size': 1,\n 'mirror': None,\n 'point_size': 3.5,\n 'rotation': 0,\n 'scale': 1,\n 'translation': [0, 0]}\n "
if (self._options is None):
return self.parent().get_options()
return self._options
def set_options(self, *get_value, **set_value):
"\n Set new options to the object.\n See :class:`LocalOptions` for more info.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: pp\n [[0, 0, 0, 0, 1, 0, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 0]]\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: view(PP) # not tested\n sage: pp.set_options(\n ....: drawing_components=dict(\n ....: diagram = True,\n ....: bounce_0 = True,\n ....: bounce_1 = True,\n ....: )\n ....: )\n sage: view(PP) # not tested\n "
if (self._options is None):
self._options = deepcopy(self.get_options())
self._options(*get_value, **set_value)
def upper_path(self) -> list:
'\n Get the upper path of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: lower_path = [0, 0, 1, 0, 1, 1]\n sage: upper_path = [1, 1, 0, 1, 0, 0]\n sage: pp = ParallelogramPolyomino([lower_path, upper_path])\n sage: pp.upper_path()\n [1, 1, 0, 1, 0, 0]\n '
return list(ClonableList.__getitem__(self, 1))
def lower_path(self) -> list:
'\n Get the lower path of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: lower_path = [0, 0, 1, 0, 1, 1]\n sage: upper_path = [1, 1, 0, 1, 0, 0]\n sage: pp = ParallelogramPolyomino([lower_path, upper_path])\n sage: pp.lower_path()\n [0, 0, 1, 0, 1, 1]\n '
return list(ClonableList.__getitem__(self, 0))
@staticmethod
def _prefix_lengths(word, up):
'\n Convert a word to a list of lengths using the following algorithm:\n\n 1) convert each 1-``up`` letter of the word by the number of ``up``\n located on the left in the word;\n 2) remove all the ``up`` letters and return the resulting list of\n integers.\n\n INPUT:\n\n - ``word`` -- a word of 0 and 1.\n\n - ``up`` -- 0 or 1 (a letter of the word)\n\n OUTPUT:\n\n A list of integers\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino._prefix_lengths([], 1)\n []\n sage: ParallelogramPolyomino._prefix_lengths([], 0)\n []\n sage: ParallelogramPolyomino._prefix_lengths([1,1,0,1,0,0,1], 1)\n [2, 3, 3]\n sage: ParallelogramPolyomino._prefix_lengths([1,1,0,1,0,0,1], 0)\n [0, 0, 1, 3]\n '
res = []
h = 0
for e in word:
if (e == up):
h += 1
else:
res.append(h)
return res
def upper_heights(self):
"\n Return the list of heights associated to each vertical step of the\n parallelogram polyomino's upper path.\n\n OUTPUT:\n\n A list of integers.\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino([[0, 1], [1, 0]]).upper_heights()\n [0]\n sage: ParallelogramPolyomino(\n ....: [[0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 1, 0]]\n ....: ).upper_heights()\n [0, 1, 1, 2, 2]\n "
return ParallelogramPolyomino._prefix_lengths(self.upper_path(), 0)
def lower_heights(self):
"\n Return the list of heights associated to each vertical step of the\n parallelogram polyomino's lower path.\n\n OUTPUT:\n\n A list of integers.\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino([[0, 1], [1, 0]]).lower_heights()\n [1]\n sage: ParallelogramPolyomino(\n ....: [[0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 1, 0]]\n ....: ).lower_heights()\n [2, 2, 3, 3, 3]\n "
return ParallelogramPolyomino._prefix_lengths(self.lower_path(), 0)
def upper_widths(self):
"\n Return the list of widths associated to each horizontal step of the\n parallelogram polyomino's upper path.\n\n OUTPUT:\n\n A list of integers.\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino([[0, 1], [1, 0]]).upper_widths()\n [1]\n sage: ParallelogramPolyomino(\n ....: [[0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 1, 0]]\n ....: ).upper_widths()\n [1, 3, 5]\n "
return ParallelogramPolyomino._prefix_lengths(self.upper_path(), 1)
def lower_widths(self):
"\n Return the list of widths associated to each horizontal step of the\n parallelogram polyomino's lower path.\n\n OUTPUT:\n\n A list of integers.\n\n EXAMPLES::\n\n sage: ParallelogramPolyomino([[0, 1], [1, 0]]).lower_widths()\n [0]\n sage: ParallelogramPolyomino(\n ....: [[0, 0, 1, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 1, 0]]\n ....: ).lower_widths()\n [0, 0, 2]\n "
return ParallelogramPolyomino._prefix_lengths(self.lower_path(), 1)
def widths(self) -> list:
'\n Return a list of the widths of the parallelogram polyomino.\n\n Namely, the parallelogram polyomino is split row by row and the\n method returns the list containing the sizes of the rows.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.widths()\n [1, 3, 3, 3, 2]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.widths()\n [1]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.widths()\n []\n '
widths = []
uw = self.upper_widths()
lw = self.lower_widths()
for i in range(len(lw)):
widths.append((uw[i] - lw[i]))
return widths
def degree_convexity(self) -> int:
'\n Return the degree convexity of a parallelogram polyomino.\n\n A convex polyomino is said to be k-convex if every pair of its cells\n can be connected by a monotone path (path with south and east steps)\n with at most k changes of direction.\n The degree of convexity of a convex polyomino P is the smallest integer\n k such that P is k-convex.\n\n If the parallelogram polyomino is empty, the function return -1.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.degree_convexity()\n 3\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.degree_convexity()\n 0\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.degree_convexity()\n -1\n '
l0 = len(self.bounce_path(direction=0))
l1 = len(self.bounce_path(direction=1))
return (min(l0, l1) - 1)
def is_flat(self) -> bool:
'\n Return whether the two bounce paths join together in the rightmost cell\n of the bottom row of P.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.is_flat()\n False\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.is_flat()\n True\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.is_flat()\n True\n '
l0 = len(self.bounce_path(direction=0))
l1 = len(self.bounce_path(direction=1))
return (l0 == l1)
def is_k_directed(self, k) -> bool:
'\n Return whether the Polyomino Parallelogram is k-directed.\n\n A convex polyomino is said to be k-convex if every pair of its cells\n can be connected by a monotone path (path with south and east steps)\n with at most k changes of direction.\n\n The degree of convexity of a convex polyomino P is the smallest integer\n k such that P is k-convex.\n\n INPUT:\n\n - ``k`` -- A non negative integer.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.is_k_directed(3)\n True\n sage: pp.is_k_directed(4)\n True\n sage: pp.is_k_directed(5)\n True\n sage: pp.is_k_directed(0)\n False\n sage: pp.is_k_directed(1)\n False\n sage: pp.is_k_directed(2)\n False\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.is_k_directed(0)\n True\n sage: pp.is_k_directed(1)\n True\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.is_k_directed(0)\n True\n sage: pp.is_k_directed(1)\n True\n '
return (self.degree_convexity() <= k)
def heights(self) -> list:
'\n Return a list of heights of the parallelogram polyomino.\n\n Namely, the parallelogram polyomino is split column by column and\n the method returns the list containing the sizes of the columns.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 1, 0, 1, 0, 1, 1],\n ....: [1, 0, 1, 1, 0, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.heights()\n [3, 3, 4, 2]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.heights()\n [1]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.heights()\n [0]\n '
uh = self.upper_heights()
lh = self.lower_heights()
return [(a - b) for (a, b) in zip(lh, uh)]
def width(self):
'\n Return the width of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 1, 0, 0, 1, 1, 0, 1, 1, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 1, 0]\n ....: ]\n ....: )\n sage: pp.width()\n 6\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.width()\n 1\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.width()\n 1\n '
if (self.size() == 1):
return 1
return self.upper_widths()[(- 1)]
def height(self):
'\n Return the height of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 1, 0, 0, 1, 1, 0, 1, 1, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 1, 0]\n ....: ]\n ....: )\n sage: pp.height()\n 4\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.height()\n 1\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.height()\n 0\n '
if (self.size() == 1):
return 0
return self.lower_heights()[(- 1)]
def cell_is_inside(self, w, h):
'\n Determine whether the cell at a given position\n is inside the parallelogram polyomino.\n\n INPUT:\n\n - ``w`` -- The x coordinate of the box position.\n\n - ``h`` -- The y coordinate of the box position.\n\n OUTPUT:\n\n Return 0 if there is no cell at the given position,\n return 1 if there is a cell.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 1, 0, 0, 1, 1, 0, 1, 1, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 1, 0]\n ....: ]\n ....: )\n sage: pp.cell_is_inside(0, 0)\n 1\n sage: pp.cell_is_inside(1, 0)\n 1\n sage: pp.cell_is_inside(0, 1)\n 0\n sage: pp.cell_is_inside(3, 0)\n 0\n sage: pp.cell_is_inside(pp.width()-1,pp.height()-1)\n 1\n sage: pp.cell_is_inside(pp.width(),pp.height()-1)\n 0\n sage: pp.cell_is_inside(pp.width()-1,pp.height())\n 0\n '
lower_widths = self.lower_widths()
widths = self.widths()
if ((h >= len(widths)) or (h < 0)):
return 0
if ((lower_widths[h] <= w) and (w < (lower_widths[h] + widths[h]))):
return 1
return 0
@cached_method
def get_array(self):
'\n Return an array of 0s and 1s such that the 1s represent the boxes of\n the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.get_array()\n [[1]]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.get_array()\n []\n '
width = self.width()
height = self.height()
return [[self.cell_is_inside(w, h) for w in range(width)] for h in range(height)]
class _polyomino_row():
'\n This is an internal class representing a single row of\n a parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: row = ParallelogramPolyomino._polyomino_row(pp, 4)\n sage: row\n [0, 1, 1]\n '
def __init__(self, polyomino, row):
'\n The constructor of the class\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: row = ParallelogramPolyomino._polyomino_row(pp, 4)\n '
self.polyomino = polyomino
self.row = row
def __getitem__(self, column):
'\n Return 0 or 1 if the is a cell inside the specific column inside the\n row.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n\n sage: row = ParallelogramPolyomino._polyomino_row(pp, 4)\n sage: [row[-1], row[0], row[1], row[2], row[3]]\n [0, 0, 1, 1, 0]\n '
if (self.is_inside() and (0 <= column) and (column < self.polyomino.width())):
return self.polyomino.get_array()[self.row][column]
return 0
def is_inside(self) -> bool:
'\n Return ``True`` if the row is inside the parallelogram polyomino,\n return ``False`` otherwise.\n\n EXAMPLES::\n\n sage: PP = ParallelogramPolyomino\n sage: pp = PP(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n\n sage: [\n ....: PP._polyomino_row(pp, i).is_inside()\n ....: for i in [-1,0,3,5,6]\n ....: ]\n [False, True, True, True, False]\n '
return ((0 <= self.row) and (self.row < self.polyomino.height()))
def is_outside(self) -> bool:
'\n Return ``True`` if the row is outside the parallelogram polyomino,\n return ``False`` otherwise.\n\n EXAMPLES::\n\n sage: PP = ParallelogramPolyomino\n sage: pp = PP(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n\n sage: [\n ....: PP._polyomino_row(pp, i).is_outside()\n ....: for i in [-1,0,3,5,6]\n ....: ]\n [True, False, False, False, True]\n '
return (not self.is_inside())
def __repr__(self) -> str:
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PP = ParallelogramPolyomino\n sage: pp = PP(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: pp[-1]\n The (outside) row -1 of the parallelogram\n sage: pp[0]\n [1, 0, 0]\n sage: pp[5]\n [0, 0, 1]\n sage: pp[6]\n The (outside) row 6 of the parallelogram\n '
if self.is_outside():
return ('The (outside) row %s of the parallelogram' % self.row)
else:
return str(self.polyomino.get_array()[self.row])
def __getitem__(self, row):
'\n Return the row of the parallelogram polyomino.\n\n The index of the row can be out of range of the height of\n the parallelogram polyomino.\n In that case, the row returned is outside the parallelogram\n polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: pp[0].is_inside()\n True\n sage: pp[3].is_outside()\n True\n sage: pp[-1].is_outside()\n True\n sage: pp[0][0]\n 1\n sage: pp[[0, 1]]\n 1\n sage: pp[2][0]\n 0\n sage: pp[-1][0]\n 0\n sage: pp[[4, 4]]\n 0\n '
if isinstance(row, list):
return self._polyomino_row(self, row[0])[row[1]]
return self._polyomino_row(self, row)
def bounce_path(self, direction=1):
"\n Return the bounce path of the parallelogram polyomino.\n\n The bounce path is a path with two steps (1, 0) and (0, 1).\n\n If 'direction' is 1 (resp. 0), the bounce path is the path\n starting at position (h=1, w=0) (resp. (h=0, w=1)) with\n initial direction, the vector (0, 1) (resp. (1, 0)), and turning\n each time the path crosses the perimeter of the parallelogram\n polyomino.\n\n The path is coded by a list of integers. Each integer represents\n the size of the path between two turnings.\n\n You can visualize the two bounce paths by using the following\n commands.\n\n INPUT:\n\n - ``direction`` -- the initial direction of the bounce path (see above\n for the definition).\n\n EXAMPLES::\n\n sage: PP = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: PP.bounce_path(direction=1)\n [2, 2, 1]\n sage: PP.bounce_path(direction=0)\n [2, 1, 1, 1]\n\n sage: PP = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 1, 1, 0, 0, 1, 1],\n ....: [1, 1, 1, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: PP.bounce_path(direction=1)\n [3, 1, 2, 2]\n sage: PP.bounce_path(direction=0)\n [2, 4, 2]\n\n sage: PP = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: PP.set_options(\n ....: drawing_components=dict(\n ....: diagram = True\n ....: , bounce_0 = True\n ....: , bounce_1 = True\n ....: )\n ....: )\n sage: view(PP) # not tested\n\n sage: PP = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: PP.bounce_path(direction=1)\n [1]\n sage: PP.bounce_path(direction=0)\n [1]\n\n sage: PP = ParallelogramPolyomino([[1], [1]])\n sage: PP.bounce_path(direction=1)\n []\n sage: PP.bounce_path(direction=0)\n []\n\n TESTS::\n\n sage: PP = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: PP.bounce_path(direction=1)\n [2, 2, 1]\n sage: PP.bounce_path(direction=0)\n [2, 1, 1, 1]\n "
result = []
pos = [0, 0]
pos[direction] -= 1
old = list(pos)
ne = list(pos)
ne[direction] += 1
while (self[ne] == 1):
pos[direction] += 1
while (self[pos] == 1):
pos[direction] += 1
pos[direction] -= 1
result.append((pos[direction] - old[direction]))
direction = (1 - direction)
(old[0], old[1]) = pos
(ne[0], ne[1]) = pos
ne[direction] += 1
return result
def bounce(self, direction=1):
'\n Return the bounce of the parallelogram polyomino.\n\n Let ``p`` be the bounce path of the parallelogram\n polyomino (:meth:`bounce_path`). The bounce is defined by:\n\n ``sum([(1+ floor(i/2))*p[i] for i in range(len(p))])``\n\n INPUT:\n\n - ``direction`` -- the initial direction of the bounce path\n (see :meth:`bounce_path` for the definition).\n\n EXAMPLES::\n\n sage: PP = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: PP.bounce(direction=1)\n 6\n sage: PP.bounce(direction=0)\n 7\n\n sage: PP = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 1, 1, 0, 0, 1, 1],\n ....: [1, 1, 1, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: PP.bounce(direction=1)\n 12\n sage: PP.bounce(direction=0)\n 10\n\n sage: PP = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: PP.bounce(direction=1)\n 1\n sage: PP.bounce(direction=0)\n 1\n\n sage: PP = ParallelogramPolyomino([[1], [1]])\n sage: PP.bounce(direction=1)\n 0\n sage: PP.bounce(direction=0)\n 0\n '
return sum((((1 + (i // 2)) * pi) for (i, pi) in enumerate(self.bounce_path(direction))))
def area(self):
'\n Return the area of the parallelogram polyomino. The area of a\n parallelogram polyomino is the number of cells of the parallelogram\n polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1],\n ....: [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0]\n ....: ]\n ....: )\n sage: pp.area()\n 13\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.area()\n 1\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.area()\n 0\n '
return sum(self.heights())
def _repr_(self) -> str:
"\n Return a string representation of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: pp # indirect doctest\n [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n sage: pp.set_options(display='drawing')\n sage: pp # indirect doctest\n [1 1 0]\n [1 1 0]\n [0 1 1]\n "
return self.get_options()._dispatch(self, '_repr_', 'display')
def _repr_list(self) -> str:
"\n Return a string representation with list style.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: pp._repr_() == pp._repr_list()\n True\n sage: pp._repr_list()\n '[[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]'\n "
return ClonableList._repr_(self)
def _repr_drawing(self) -> str:
"\n Return a string representing a drawing of the parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 0]]\n ....: )\n sage: pp._repr_() == pp._repr_drawing()\n False\n sage: pp._repr_drawing()\n '[1 1 0]\\n[1 1 0]\\n[0 1 1]'\n "
return str(matrix(self.get_array()))
def get_tikz_options(self):
"\n Return all the tikz options permitting to draw the parallelogram\n polyomino.\n\n See :class:`LocalOption` to have more informations about the\n modification of those options.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.get_tikz_options()\n {'color_bounce_0': 'red',\n 'color_bounce_1': 'blue',\n 'color_line': 'black',\n 'color_point': 'black',\n 'line_size': 1,\n 'mirror': None,\n 'point_size': 3.5,\n 'rotation': 0,\n 'scale': 1,\n 'translation': [0, 0]}\n "
return self.get_options()['tikz_options']
def _to_tikz_diagram(self):
'\n Return the tikz code of the diagram representing ``self``.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_diagram()\n True\n sage: print(pp.to_tikz())\n <BLANKLINE>\n \\draw[color=black, line width=1] (0.000000, 5.000000) --\n (0.000000, 3.000000);\n \\draw[color=black, line width=1] (3.000000, 4.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 5.000000) --\n (1.000000, 5.000000);\n \\draw[color=black, line width=1] (1.000000, 0.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (1.000000, 5.000000) --\n (1.000000, 0.000000);\n \\draw[color=black, line width=1] (2.000000, 4.000000) --\n (2.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (3.000000, 4.000000);\n \\draw[color=black, line width=1] (0.000000, 3.000000) --\n (3.000000, 3.000000);\n \\draw[color=black, line width=1] (1.000000, 2.000000) --\n (3.000000, 2.000000);\n \\draw[color=black, line width=1] (1.000000, 1.000000) --\n (3.000000, 1.000000);\n\n '
tikz_options = self.get_tikz_options()
grid_width = (self.width() + 1)
grid_height = (self.height() + 1)
drawing_tool = _drawing_tool(tikz_options, XY=(lambda v: [v[0], ((grid_height - 1) - v[1])]))
res = ''
if (self.size() == 1):
res += drawing_tool.draw_line([0, 0], [1, 0])
return res
res += drawing_tool.draw_line([0, 0], [0, self.lower_heights()[0]])
res += drawing_tool.draw_line([(grid_width - 1), self.upper_heights()[(grid_width - 2)]], [(grid_width - 1), self.lower_heights()[(grid_width - 2)]])
res += drawing_tool.draw_line([0, 0], [self.upper_widths()[0], 0])
res += drawing_tool.draw_line([self.lower_widths()[(grid_height - 2)], (grid_height - 1)], [self.upper_widths()[(grid_height - 2)], (grid_height - 1)])
for w in range(1, (grid_width - 1)):
h1 = self.upper_heights()[(w - 1)]
h2 = self.lower_heights()[w]
res += drawing_tool.draw_line([w, h1], [w, h2])
for h in range(1, (grid_height - 1)):
w1 = self.lower_widths()[(h - 1)]
w2 = self.upper_widths()[h]
res += drawing_tool.draw_line([w1, h], [w2, h])
return res
def _to_tikz_bounce(self, directions=None):
'\n Return the tikz code to display one or both bounces of ``self``.\n\n See :meth:`ParallelogramPolyomino.bounce_path` for more information\n about the bounce.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 0, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1, 0, 0]]\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_bounce()\n False\n sage: pp.set_options(drawing_components=dict(\n ....: diagram=False, bounce_0=True)\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_bounce([0])\n True\n sage: pp.set_options(\n ....: drawing_components=dict(diagram=False, bounce_1=True)\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_bounce([1])\n True\n sage: pp.set_options(\n ....: drawing_components=dict(\n ....: diagram=False, bounce_0= True, bounce_1=True\n ....: )\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_bounce([0,1])\n True\n sage: pp.to_tikz() == pp._to_tikz_bounce()\n True\n sage: pp.set_options(\n ....: drawing_components=dict(diagram=True, bounce_0=True)\n ....: )\n sage: print(pp.to_tikz()) # indirect doctest\n <BLANKLINE>\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (0.000000, 1.000000);\n \\draw[color=black, line width=1] (4.000000, 2.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (1.000000, 4.000000);\n \\draw[color=black, line width=1] (2.000000, 0.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (1.000000, 4.000000) --\n (1.000000, 1.000000);\n \\draw[color=black, line width=1] (2.000000, 3.000000) --\n (2.000000, 0.000000);\n \\draw[color=black, line width=1] (3.000000, 3.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 3.000000) --\n (3.000000, 3.000000);\n \\draw[color=black, line width=1] (0.000000, 2.000000) --\n (4.000000, 2.000000);\n \\draw[color=black, line width=1] (0.000000, 1.000000) --\n (4.000000, 1.000000);\n \\draw[color=red, line width=2] (1.000000, 4.000000) --\n (1.000000, 1.000000);\n \\draw[color=red, line width=2] (1.000000, 1.000000) --\n (4.000000, 1.000000);\n \\draw[color=red, line width=2] (4.000000, 1.000000) --\n (4.000000, 0.000000);\n '
if (directions is None):
directions = [0, 1]
res = ''
tikz_options = self.get_tikz_options()
grid_height = (self.height() + 1)
drawing_tool = _drawing_tool(tikz_options, XY=(lambda v: [v[0], ((grid_height - 1) - v[1])]))
def draw_bounce(direction, color):
'\n Return the TIKZ code of the bounce path of ``self``.\n\n See :meth:`ParallelogramPolyomino.bounce_path` for more information\n about the bounce.\n '
if (len(self.bounce_path(direction)) > len(self.bounce_path((1 - direction)))):
increase_size_line = 1
else:
increase_size_line = 0
res = ''
bp = self.bounce_path(direction)
pos = [0, 0]
pos[(1 - direction)] += 1
old = list(pos)
for e in bp:
pos[direction] += e
res += drawing_tool.draw_line([old[1], old[0]], [pos[1], pos[0]], color=color, size=((2 * tikz_options['line_size']) + increase_size_line))
(old[0], old[1]) = pos
direction = (1 - direction)
return res
if (len(self.bounce_path(0)) > len(self.bounce_path(1))):
if (0 in directions):
res += draw_bounce(0, tikz_options['color_bounce_0'])
if (1 in directions):
res += draw_bounce(1, tikz_options['color_bounce_1'])
else:
if (1 in directions):
res += draw_bounce(1, tikz_options['color_bounce_1'])
if (0 in directions):
res += draw_bounce(0, tikz_options['color_bounce_0'])
return res
def _to_tikz_tree(self):
'\n Return the tikz code to display a node inside the boxes which are\n nodes.\n See :meth:`ParallelogramPolyomino.box_is_node` for more information.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 0, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1, 0, 0]]\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_tree()\n False\n sage: pp.set_options(\n ....: drawing_components=dict(diagram=False, tree=True)\n ....: )\n sage: pp.to_tikz() == pp._to_tikz_tree()\n True\n sage: pp.set_options(\n ....: drawing_components=dict(diagram=True, tree=True)\n ....: )\n sage: print(pp.to_tikz()) # indirect doctest\n <BLANKLINE>\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (0.000000, 1.000000);\n \\draw[color=black, line width=1] (4.000000, 2.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (1.000000, 4.000000);\n \\draw[color=black, line width=1] (2.000000, 0.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (1.000000, 4.000000) --\n (1.000000, 1.000000);\n \\draw[color=black, line width=1] (2.000000, 3.000000) --\n (2.000000, 0.000000);\n \\draw[color=black, line width=1] (3.000000, 3.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 3.000000) --\n (3.000000, 3.000000);\n \\draw[color=black, line width=1] (0.000000, 2.000000) --\n (4.000000, 2.000000);\n \\draw[color=black, line width=1] (0.000000, 1.000000) --\n (4.000000, 1.000000);\n \\filldraw[color=black] (0.500000, 2.500000) circle (3.5pt);\n \\filldraw[color=black] (0.500000, 1.500000) circle (3.5pt);\n \\filldraw[color=black] (2.500000, 0.500000) circle (3.5pt);\n \\filldraw[color=black] (1.500000, 2.500000) circle (3.5pt);\n \\filldraw[color=black] (2.500000, 2.500000) circle (3.5pt);\n \\filldraw[color=black] (3.500000, 1.500000) circle (3.5pt);\n \\filldraw[color=black] (0.500000, 3.500000) circle (3.5pt);\n '
res = ''
tikz_options = self.get_tikz_options()
if (self.size() == 1):
return res
grid_height = (self.height() + 1)
drawing_tool = _drawing_tool(tikz_options, XY=(lambda v: [(v[0] + 0.5), (((grid_height - 1) - v[1]) - 0.5)]))
for node in self.get_BS_nodes():
res += drawing_tool.draw_point([node[1], node[0]])
res += drawing_tool.draw_point([0, 0])
return res
def _get_node_position_at_row(self, row):
'\n Return the position of the leftmost cell in the row indexed by ``row``\n of the array obtained with ``get_array``.\n\n INPUT:\n\n - ``row`` -- the index of the row\n\n OUTPUT:\n\n A [row,column] position of the cell.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [\n ....: [0, 0, 0, 0, 1, 0, 1, 0, 1],\n ....: [1, 0, 0, 0, 1, 1, 0, 0, 0]\n ....: ]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 0 0]\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 0 1]\n sage: pp._get_node_position_at_row(0)\n [0, 0]\n sage: pp._get_node_position_at_row(1)\n [1, 0]\n sage: pp._get_node_position_at_row(2)\n [2, 0]\n sage: pp._get_node_position_at_row(3)\n [3, 0]\n sage: pp._get_node_position_at_row(4)\n [4, 1]\n sage: pp._get_node_position_at_row(5)\n [5, 2]\n '
h = row
for w in range(self.width()):
if (self[h][w] == 1):
return [h, w]
return None
def _get_node_position_at_column(self, column):
'\n Return the position of the topmost cell in the column indexed by\n ``column`` of the array obtained with ``get_array``.\n\n INPUT:\n\n - ``column`` -- the index of the column\n\n OUTPUT:\n\n A [row,column] position of the cell.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: pp._get_node_position_at_column(0)\n [0, 0]\n sage: pp._get_node_position_at_column(1)\n [1, 1]\n sage: pp._get_node_position_at_column(2)\n [1, 2]\n '
w = column
for h in range(self.height()):
if (self[h][w] == 1):
return [h, w]
return None
def get_node_position_from_box(self, box_position, direction, nb_crossed_nodes=None):
'\n This function starts from a cell inside a parallelogram polyomino and\n a direction.\n\n If ``direction`` is equal to 0, the function selects the column\n associated with the y-coordinate of ``box_position`` and then returns\n the topmost cell of the column that is on the top of ``box_position``\n (the cell of ``box_position`` is included).\n\n If ``direction`` is equal to 1, the function selects the row\n associated with the x-coordinate of ``box_position`` and then returns\n the leftmost cell of the row that is on the left of ``box_position``.\n (the cell of ``box_position`` is included).\n\n This function updates the entry of ``nb_crossed_nodes``. The function\n increases the entry of ``nb_crossed_nodes`` by the number of boxes that\n is a node (see ``box_is_node``) located on the top if ``direction``\n is 0 (resp. on the left if ``direction`` is 1) of ``box_position``\n (cell at ``box_position`` is excluded).\n\n INPUT:\n\n - ``box_position`` -- the position of the statring cell.\n\n - ``direction`` -- the direction (0 or 1).\n\n - ``nb_crossed_nodes`` -- ``[0]`` (default) a list containing just one\n integer.\n\n OUTPUT:\n\n A [row,column] position of the cell.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: matrix(pp.get_array())\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: l = [0]\n sage: pp.get_node_position_from_box([3, 2], 0, l)\n [1, 2]\n sage: l\n [1]\n sage: l = [0]\n sage: pp.get_node_position_from_box([3, 2], 1, l)\n [3, 1]\n sage: l\n [1]\n sage: l = [0]\n sage: pp.get_node_position_from_box([1, 2], 0, l)\n [1, 2]\n sage: l\n [0]\n sage: l = [0]\n sage: pp.get_node_position_from_box([1, 2], 1, l)\n [1, 0]\n sage: l\n [2]\n sage: l = [0]\n sage: pp.get_node_position_from_box([3, 1], 0, l)\n [1, 1]\n sage: l\n [2]\n sage: l = [0]\n sage: pp.get_node_position_from_box([3, 1], 1, l)\n [3, 1]\n sage: l\n [0]\n '
if (nb_crossed_nodes is None):
nb_crossed_nodes = [0]
pos = list(box_position)
if (self[pos[0]][pos[1]] == 0):
return None
while (self[pos[0]][pos[1]] != 0):
pos[direction] -= 1
if self.box_is_node(pos):
nb_crossed_nodes[0] += 1
pos[direction] += 1
return pos
def box_is_node(self, pos) -> bool:
"\n Return True if the box contains a node in the context of the\n Aval-Boussicault bijection between parallelogram polyomino and binary\n tree.\n\n A box is a node if there is no cell on the top of the box in the\n same column or on the left of the box.in the same row.\n\n INPUT:\n\n - ``pos`` -- the [x,y] coordinate of the box.\n\n OUTPUT:\n\n A boolean\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 1 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: pp.box_is_node([2,1])\n True\n sage: pp.box_is_node([2,0])\n False\n sage: pp.box_is_node([1,1])\n False\n "
if (self[pos[0]][pos[1]] == 0):
return False
if (self[(pos[0] - 1)][pos[1]] == 0):
return True
if (self[pos[0]][(pos[1] - 1)] == 0):
return True
return False
def box_is_root(self, box) -> bool:
'\n Return ``True`` if the box contains the root of the tree : it\n is the top-left box of the parallelogram polyomino.\n\n INPUT:\n\n - ``box`` -- the x,y coordinate of the cell.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.box_is_root([0, 0])\n True\n sage: pp.box_is_root([0, 1])\n False\n '
return ((box[0] == 0) and (box[1] == 0))
def _get_number_of_nodes_in_the_bounding_path(self, box, direction):
'\n When we draw the bounding path from ``box`` to the top-left cell of\n ``self``, the path is crossing some cells containing some nodes\n defined by the Boussicault-Socci bijection\n (see :meth:`_to_ordered_tree_Bou_Socci`).\n\n This function returns a list of numbers that represent the number of\n nodes minus 1 that the path is crossing between each bounding.\n The starting box is excluded from the count of nodes.\n\n This function is a specialized tool for\n :meth:`_get_path_in_pair_of_tree_from_row()` and\n :meth:`_get_path_in_pair_of_tree_from_column()`\n each number is reduced by one to compute the path in the ordered tree\n of those functions.\n\n INPUT:\n\n - ``box`` -- the x,y coordinate of the starting point of the bounding\n path.\n - ``direction`` -- the initial direction of the bounding path (1 or 0,\n 1 for left and 0 for top).\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp._get_number_of_nodes_in_the_bounding_path([4, 2], 1)\n [0, 0, 2, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([3, 2], 1)\n [0, 0, 1, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([2, 2], 1)\n [0, 0, 0, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 2], 1)\n [0, 1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([4, 2], 0)\n [0, 1, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([3, 2], 0)\n [0, 1, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([2, 2], 0)\n [0, 1, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 2], 0)\n [0, 1, -1]\n\n sage: pp._get_number_of_nodes_in_the_bounding_path([4, 1], 1)\n [0, 0, 2, -1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([3, 1], 1)\n [0, 0, 1, -1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([2, 1], 1)\n [0, 0, 0, -1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 1], 1)\n [0, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([4, 1], 0)\n [0, 0, 2]\n sage: pp._get_number_of_nodes_in_the_bounding_path([3, 1], 0)\n [0, 0, 1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([2, 1], 0)\n [0, 0, 0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 1], 0)\n [0, 0, -1]\n\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 0], 1)\n [0, -1]\n sage: pp._get_number_of_nodes_in_the_bounding_path([0, 0], 1)\n []\n sage: pp._get_number_of_nodes_in_the_bounding_path([1, 0], 0)\n [0]\n sage: pp._get_number_of_nodes_in_the_bounding_path([0, 0], 0)\n []\n '
path = []
while (not self.box_is_root(box)):
nb_sons = [0]
box = self.get_node_position_from_box(box, direction, nb_sons)
direction = (1 - direction)
path.append((nb_sons[0] - 1))
path.reverse()
return path
def _get_path_in_pair_of_tree_from_row(self, line):
'\n When we draw the bounding path from the left-most cell of ``line`` to\n the top-left cell of ``self``, the path is bounding in some cells that\n are nodes in the ordered tree of the Boussicault-Socci bijection.\n This function returns the path of the bounding path inside the ordered\n tree.\n\n The path in the ordered tree is encoded as a list of integers.\n The first integer represents the son choice between the sons of the\n root.\n Recursively, an integer represent the son choice between the sons of\n the current father.\n\n The bijection is described in the paper [BRS2015]_\n at page 7, the first (resp. second) ordered tree is obtained by\n gluing all roots of the ordered forest F_e (resp. F_s) to a virtual\n root. An example can be read, page 8, Figure 6.\n\n INPUT:\n\n - ``line`` -- the x coordinate of the line.\n\n OUTPUT:\n\n A list of integers\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp._get_path_in_pair_of_tree_from_row(4)\n [0, 0, 2]\n sage: pp._get_path_in_pair_of_tree_from_row(3)\n [0, 0, 1]\n sage: pp._get_path_in_pair_of_tree_from_row(2)\n [0, 0, 0]\n sage: pp._get_path_in_pair_of_tree_from_row(1)\n [0]\n sage: pp._get_path_in_pair_of_tree_from_row(0)\n []\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp._get_path_in_pair_of_tree_from_row(4)\n [0, 2]\n sage: pp._get_path_in_pair_of_tree_from_row(3)\n [0, 1]\n sage: pp._get_path_in_pair_of_tree_from_row(2)\n [0, 0]\n sage: pp._get_path_in_pair_of_tree_from_row(1)\n [0]\n sage: pp._get_path_in_pair_of_tree_from_row(0)\n []\n\n '
pos = self._get_node_position_at_row(line)
return self._get_number_of_nodes_in_the_bounding_path(pos, 0)
def _get_path_in_pair_of_tree_from_column(self, column):
'\n When we draw the bounding path from the top-most cell of ``column``\n to the top-left cell of ``self``, the path is bounding in some cells\n that are nodes in the ordered tree of the Boussicault-Socci bijection.\n This function returns the path of the bounding path inside the ordered\n tree.\n\n The path in the ordered tree is encoded as a list of integers.\n The first integer represents the son choice between the sons of the\n root.\n Recursively, an integer represent the son choice between the sons of\n the current father.\n\n The bijection is described in the paper [BRS2015]_\n at page 7, the first (resp. second) ordered tree is obtained by\n gluing all roots of the ordered forest F_e (resp. F_s) to a virtual\n root. An example can be read, page 8, Figure 6.\n\n INPUT:\n\n - ``column`` -- the y coordinate of the column.\n\n OUTPUT:\n\n A list of integers\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp._get_path_in_pair_of_tree_from_column(2)\n [0, 1]\n sage: pp._get_path_in_pair_of_tree_from_column(1)\n [0, 0]\n sage: pp._get_path_in_pair_of_tree_from_column(0)\n []\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp._get_path_in_pair_of_tree_from_column(2)\n [0, 0]\n sage: pp._get_path_in_pair_of_tree_from_row(1)\n [0]\n sage: pp._get_path_in_pair_of_tree_from_row(0)\n []\n '
pos = self._get_node_position_at_column(column)
return self._get_number_of_nodes_in_the_bounding_path(pos, 1)
def get_BS_nodes(self):
"\n Return the list of cells containing node of the left and right planar\n tree in the Boussicault-Socci bijection.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 1 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: sorted(pp.get_BS_nodes())\n [[0, 1], [1, 0], [1, 2], [2, 1], [3, 1], [4, 1]]\n\n You can draw the point inside the parallelogram polyomino by typing\n (the left nodes are in blue, and the right node are in red) ::\n\n sage: pp.set_options(drawing_components=dict(tree=True))\n sage: view(pp) # not tested\n "
result = []
for h in range(1, self.height()):
result.append(self._get_node_position_at_row(h))
for w in range(1, self.width()):
result.append(self._get_node_position_at_column(w))
return result
def get_right_BS_nodes(self):
"\n Return the list of cells containing node of the right planar tree in\n the Boussicault-Socci bijection between parallelogram polyominoes\n and pair of ordered trees.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 1 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: sorted(pp.get_right_BS_nodes())\n [[1, 0], [1, 2]]\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: sorted(pp.get_right_BS_nodes())\n [[1, 0], [1, 1], [1, 2], [2, 1], [3, 1], [4, 1]]\n\n You can draw the point inside the parallelogram polyomino by typing,\n (the left nodes are in blue, and the right node are in red) ::\n\n sage: pp.set_options(drawing_components=dict(tree=True))\n sage: view(pp) # not tested\n "
result = []
for h in range(1, self.height()):
path2 = self._get_path_in_pair_of_tree_from_row(h)
if ((len(path2) % 2) == 1):
result.append(self._get_node_position_at_row(h))
for w in range(1, self.width()):
path2 = self._get_path_in_pair_of_tree_from_column(w)
if ((len(path2) % 2) == 0):
result.append(self._get_node_position_at_column(w))
return result
def get_left_BS_nodes(self):
"\n Return the list of cells containing node of the left planar tree in\n the Boussicault-Socci bijection between parallelogram polyominoes\n and pair of ordered trees.\n\n OUTPUT:\n\n A list of [row,column] position of cells.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 1, 0, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 1 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: sorted(pp.get_left_BS_nodes())\n [[0, 1], [2, 1], [3, 1], [4, 1]]\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0]]\n ....: )\n sage: pp.set_options(display='drawing')\n sage: pp\n [1 0 0]\n [1 1 1]\n [0 1 1]\n [0 1 1]\n [0 1 1]\n sage: sorted(pp.get_left_BS_nodes())\n []\n\n You can draw the point inside the parallelogram polyomino by typing\n (the left nodes are in blue, and the right node are in red) ::\n\n sage: pp.set_options(drawing_components=dict(tree=True))\n sage: view(pp) # not tested\n "
result = []
for h in range(1, self.height()):
path2 = self._get_path_in_pair_of_tree_from_row(h)
if ((len(path2) % 2) == 0):
result.append(self._get_node_position_at_row(h))
for w in range(1, self.width()):
path2 = self._get_path_in_pair_of_tree_from_column(w)
if ((len(path2) % 2) == 1):
result.append(self._get_node_position_at_column(w))
return result
def to_tikz(self):
'\n Return the tikz code of the parallelogram polyomino.\n\n This code is the code present inside a tikz latex environment.\n\n We can modify the output with the options.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0,0,0,1,1,0,1,0,0,1,1,1],[1,1,1,0,0,1,1,0,0,1,0,0]]\n ....: )\n sage: print(pp.to_tikz())\n <BLANKLINE>\n \\draw[color=black, line width=1] (0.000000, 6.000000) --\n (0.000000, 3.000000);\n \\draw[color=black, line width=1] (6.000000, 2.000000) --\n (6.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 6.000000) --\n (3.000000, 6.000000);\n \\draw[color=black, line width=1] (3.000000, 0.000000) --\n (6.000000, 0.000000);\n \\draw[color=black, line width=1] (1.000000, 6.000000) --\n (1.000000, 3.000000);\n \\draw[color=black, line width=1] (2.000000, 6.000000) --\n (2.000000, 2.000000);\n \\draw[color=black, line width=1] (3.000000, 6.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (4.000000, 4.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (5.000000, 4.000000) --\n (5.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 5.000000) --\n (3.000000, 5.000000);\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (5.000000, 4.000000);\n \\draw[color=black, line width=1] (0.000000, 3.000000) --\n (5.000000, 3.000000);\n \\draw[color=black, line width=1] (2.000000, 2.000000) --\n (6.000000, 2.000000);\n \\draw[color=black, line width=1] (3.000000, 1.000000) --\n (6.000000, 1.000000);\n sage: pp.set_options(\n ....: drawing_components=dict(\n ....: diagram=True,\n ....: tree=True,\n ....: bounce_0=True,\n ....: bounce_1=True\n ....: )\n ....: )\n sage: print(pp.to_tikz())\n <BLANKLINE>\n \\draw[color=black, line width=1] (0.000000, 6.000000) --\n (0.000000, 3.000000);\n \\draw[color=black, line width=1] (6.000000, 2.000000) --\n (6.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 6.000000) --\n (3.000000, 6.000000);\n \\draw[color=black, line width=1] (3.000000, 0.000000) --\n (6.000000, 0.000000);\n \\draw[color=black, line width=1] (1.000000, 6.000000) --\n (1.000000, 3.000000);\n \\draw[color=black, line width=1] (2.000000, 6.000000) --\n (2.000000, 2.000000);\n \\draw[color=black, line width=1] (3.000000, 6.000000) --\n (3.000000, 0.000000);\n \\draw[color=black, line width=1] (4.000000, 4.000000) --\n (4.000000, 0.000000);\n \\draw[color=black, line width=1] (5.000000, 4.000000) --\n (5.000000, 0.000000);\n \\draw[color=black, line width=1] (0.000000, 5.000000) --\n (3.000000, 5.000000);\n \\draw[color=black, line width=1] (0.000000, 4.000000) --\n (5.000000, 4.000000);\n \\draw[color=black, line width=1] (0.000000, 3.000000) --\n (5.000000, 3.000000);\n \\draw[color=black, line width=1] (2.000000, 2.000000) --\n (6.000000, 2.000000);\n \\draw[color=black, line width=1] (3.000000, 1.000000) --\n (6.000000, 1.000000);\n \\draw[color=blue, line width=3] (0.000000, 5.000000) --\n (3.000000, 5.000000);\n \\draw[color=blue, line width=3] (3.000000, 5.000000) --\n (3.000000, 2.000000);\n \\draw[color=blue, line width=3] (3.000000, 2.000000) --\n (5.000000, 2.000000);\n \\draw[color=blue, line width=3] (5.000000, 2.000000) --\n (5.000000, 0.000000);\n \\draw[color=blue, line width=3] (5.000000, 0.000000) --\n (6.000000, 0.000000);\n \\draw[color=red, line width=2] (1.000000, 6.000000) --\n (1.000000, 3.000000);\n \\draw[color=red, line width=2] (1.000000, 3.000000) --\n (5.000000, 3.000000);\n \\draw[color=red, line width=2] (5.000000, 3.000000) --\n (5.000000, 0.000000);\n \\draw[color=red, line width=2] (5.000000, 0.000000) --\n (6.000000, 0.000000);\n \\filldraw[color=black] (0.500000, 4.500000) circle (3.5pt);\n \\filldraw[color=black] (0.500000, 3.500000) circle (3.5pt);\n \\filldraw[color=black] (2.500000, 2.500000) circle (3.5pt);\n \\filldraw[color=black] (3.500000, 1.500000) circle (3.5pt);\n \\filldraw[color=black] (3.500000, 0.500000) circle (3.5pt);\n \\filldraw[color=black] (1.500000, 5.500000) circle (3.5pt);\n \\filldraw[color=black] (2.500000, 5.500000) circle (3.5pt);\n \\filldraw[color=black] (3.500000, 3.500000) circle (3.5pt);\n \\filldraw[color=black] (4.500000, 3.500000) circle (3.5pt);\n \\filldraw[color=black] (5.500000, 1.500000) circle (3.5pt);\n \\filldraw[color=black] (0.500000, 5.500000) circle (3.5pt);\n '
res = ''
drawing_components = self.get_options()['drawing_components']
if (('diagram' in drawing_components) and drawing_components['diagram']):
res += self._to_tikz_diagram()
directions = []
if (('bounce_0' in drawing_components) and drawing_components['bounce_0']):
directions.append(0)
if (('bounce_1' in drawing_components) and drawing_components['bounce_1']):
directions.append(1)
if (len(directions) != 0):
res += self._to_tikz_bounce(directions)
if (('tree' in drawing_components) and drawing_components['tree']):
res += self._to_tikz_tree()
return res
def geometry(self) -> list:
'\n Return a pair [h, w] containing the height and the width of the\n parallelogram polyomino.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 1, 1, 1, 1], [1, 1, 1, 1, 0]]\n ....: )\n sage: pp.geometry()\n [1, 4]\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.geometry()\n [1, 1]\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.geometry()\n [0, 1]\n '
return [self.height(), self.width()]
def _plot_diagram(self):
'\n Return a plot of the diagram representing ``self``\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 1, 1, 1, 1], [1, 1, 1, 1, 0]]\n ....: )\n sage: pp._plot_diagram() # needs sage.plot\n Graphics object consisting of 7 graphics primitives\n\n sage: pp = ParallelogramPolyomino([\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]\n ....: ])\n sage: pp._plot_diagram() # needs sage.plot\n Graphics object consisting of 25 graphics primitives\n '
G = Graphics()
for (i, u, v) in zip(range((self.height() - 1)), self.upper_widths()[1:], self.lower_widths()):
G += line([(u, ((- i) - 1)), (v, ((- i) - 1))], rgbcolor=(0, 0, 0))
for (i, u, v) in zip(range((self.width() - 1)), self.upper_heights()[1:], self.lower_heights()):
G += line([((i + 1), (- u)), ((i + 1), (- v))], rgbcolor=(0, 0, 0))
lower_heights = ([0] + self.lower_heights())
for i in range(self.width()):
if (lower_heights[i] != lower_heights[(i + 1)]):
G += line([(i, (- lower_heights[i])), (i, (- lower_heights[(i + 1)]))], rgbcolor=(0, 0, 0), thickness=2)
upper_heights = (self.upper_heights() + [self.height()])
for i in range(self.width()):
if (upper_heights[i] != upper_heights[(i + 1)]):
G += line([((i + 1), (- upper_heights[i])), ((i + 1), (- upper_heights[(i + 1)]))], rgbcolor=(0, 0, 0), thickness=2)
lower_widths = (self.lower_widths() + [self.width()])
for i in range(self.height()):
if (lower_widths[i] != lower_widths[(i + 1)]):
G += line([(lower_widths[i], ((- i) - 1)), (lower_widths[(i + 1)], ((- i) - 1))], rgbcolor=(0, 0, 0), thickness=2)
upper_widths = ([0] + self.upper_widths())
for i in range(self.height()):
if (upper_widths[i] != upper_widths[(i + 1)]):
G += line([(upper_widths[i], (- i)), (upper_widths[(i + 1)], (- i))], rgbcolor=(0, 0, 0), thickness=2)
return G
def _plot_bounce(self, directions=None):
'\n Return a plot of the bounce paths of ``self``.\n\n INPUT:\n\n - ``directions`` -- direction(s) `0` and/or `1` of the bounce paths.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 1, 1, 1, 1], [1, 1, 1, 1, 0]]\n ....: )\n sage: pp._plot_bounce(directions=[1]) # needs sage.plot\n Graphics object consisting of 1 graphics primitive\n\n sage: pp = ParallelogramPolyomino([\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]\n ....: ])\n sage: pp._plot_bounce(directions=[0,1]) # needs sage.plot\n Graphics object consisting of 9 graphics primitives\n\n '
if (directions is None):
directions = [0, 1]
G = Graphics()
if (0 in directions):
(a, b) = (1, 0)
for (bounce, u) in enumerate(self.bounce_path(direction=0)):
if (bounce & 1):
(u, v) = ((a + u), b)
else:
(u, v) = (a, (b + u))
G += line([((a - 0.1), (- b)), ((u - 0.1), (- v))], rgbcolor=(1, 0, 0), thickness=1.5)
(a, b) = (u, v)
if (1 in directions):
(a, b) = (0, 1)
for (bounce, u) in enumerate(self.bounce_path(direction=1)):
if (bounce & 1):
(u, v) = (a, (b + u))
else:
(u, v) = ((a + u), b)
G += line([(a, ((- b) + 0.1)), (u, ((- v) + 0.1))], rgbcolor=(0, 0, 1), thickness=1.5)
(a, b) = (u, v)
return G
def _plot_bounce_values(self, bounce=0):
'\n Return a plot containing the value of bounce along the specified bounce path.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 1, 1, 1, 1], [1, 1, 1, 1, 0]]\n ....: )\n sage: pp._plot_bounce_values() # needs sage.plot\n Graphics object consisting of 4 graphics primitives\n\n sage: pp = ParallelogramPolyomino([\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]\n ....: ])\n sage: pp._plot_bounce_values(bounce=1) # needs sage.plot\n Graphics object consisting of 10 graphics primitives\n '
G = Graphics()
if (bounce == 0):
(a, b) = (0, (- 1))
for (bounce, u) in enumerate(self.bounce_path(direction=0)):
if (bounce & 1):
(u, v) = ((a + u), b)
else:
(u, v) = (a, (b + u))
for i in range(a, (u + 1)):
for j in range(b, (v + 1)):
if ((i, j) != (a, b)):
G += text(str(((bounce // 2) + 1)), ((i + 0.5), ((- j) - 0.5)), rgbcolor=(0, 0, 0))
(a, b) = (u, v)
else:
(a, b) = ((- 1), 0)
for (bounce, u) in enumerate(self.bounce_path(direction=1)):
if (bounce & 1):
(u, v) = (a, (b + u))
else:
(u, v) = ((a + u), b)
for i in range(a, (u + 1)):
for j in range(b, (v + 1)):
if ((i, j) != (a, b)):
G += text(str(((bounce // 2) + 1)), ((i + 0.5), ((- j) - 0.5)), rgbcolor=(0, 0, 0))
(a, b) = (u, v)
return G
def _plot_tree(self):
'\n Return a plot of the nodes of the tree.\n\n TESTS::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 1, 1, 1, 1], [1, 1, 1, 1, 0]]\n ....: )\n sage: pp._plot_tree() # needs sage.plot\n Graphics object consisting of 2 graphics primitives\n\n sage: pp = ParallelogramPolyomino([\n ....: [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n ....: [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0]\n ....: ])\n sage: pp._plot_tree() # needs sage.plot\n Graphics object consisting of 2 graphics primitives\n '
G = Graphics()
G += point(points=(((v + 0.5), ((- u) - 0.5)) for (u, v) in self.get_BS_nodes()), size=20)
G += point([0.5, (- 0.5)], size=20)
return G
def plot(self):
'\n Return a plot of ``self``.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,1],[1,0]])\n sage: pp.plot() # needs sage.plot\n Graphics object consisting of 4 graphics primitives\n sage: pp.set_options(\n ....: drawing_components=dict(\n ....: diagram=True,\n ....: bounce_0=True,\n ....: bounce_1=True,\n ....: bounce_values=0,\n ....: )\n ....: )\n sage: pp.plot() # needs sage.plot\n Graphics object consisting of 7 graphics primitives\n '
G = Graphics()
drawing_components = self.get_options()['drawing_components']
if (('diagram' in drawing_components) and drawing_components['diagram']):
G += self._plot_diagram()
directions = []
if (('bounce_0' in drawing_components) and drawing_components['bounce_0']):
directions.append(0)
if (('bounce_1' in drawing_components) and drawing_components['bounce_1']):
directions.append(1)
if (len(directions) != 0):
G += self._plot_bounce(directions)
if (('bounce_values' in drawing_components) and (drawing_components['bounce_values'] is not False)):
G += self._plot_bounce_values()
if (('tree' in drawing_components) and drawing_components['tree']):
G += self._plot_tree()
G.set_aspect_ratio(1)
G.axes(False)
return G
def size(self) -> int:
'\n Return the size of the parallelogram polyomino.\n\n The size of a parallelogram polyomino is its half-perimeter.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino(\n ....: [[0, 0, 0, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 1, 0, 0]]\n ....: )\n sage: pp.size()\n 8\n\n sage: pp = ParallelogramPolyomino([[0, 1], [1, 0]])\n sage: pp.size()\n 2\n\n sage: pp = ParallelogramPolyomino([[1], [1]])\n sage: pp.size()\n 1\n '
return len(self.upper_path())
def _latex_(self):
'\n Return a LaTeX version of ``self``.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,1],[1,0]])\n sage: latex(pp)\n <BLANKLINE>\n \\begin{tikzpicture}[scale=1]\n ...\n \\end{tikzpicture}\n\n For more on the latex options, see\n :meth:`ParallelogramPolyominoes.options`.\n '
return self.get_options()._dispatch(self, '_latex_', 'latex')
def _latex_drawing(self):
'\n Return a LaTeX version of ``self`` in a drawing style.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,1],[1,0]])\n sage: print(pp._latex_drawing())\n <BLANKLINE>\n \\begin{tikzpicture}[scale=1]\n ...\n \\end{tikzpicture}\n '
latex.add_package_to_preamble_if_available('tikz')
tikz_options = self.get_tikz_options()
res = ('\n\\begin{tikzpicture}[scale=%s]' % tikz_options['scale'])
res += self.to_tikz()
res += '\n\\end{tikzpicture}'
return res
def _latex_list(self):
"\n Return a LaTeX version of ``self`` in a list style.\n\n EXAMPLES::\n\n sage: pp = ParallelogramPolyomino([[0,1],[1,0]])\n sage: pp._latex_list()\n '\\\\[[[0, 1], [1, 0]]\\\\]'\n "
return ('\\[%s\\]' % self._repr_list())
|
class ParallelogramPolyominoesFactory(SetFactory):
'\n The parallelogram polyominoes factory.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(size=4)\n sage: PPS\n Parallelogram polyominoes of size 4\n\n sage: sorted(PPS)\n [[[0, 0, 0, 1], [1, 0, 0, 0]],\n [[0, 0, 1, 1], [1, 0, 1, 0]],\n [[0, 0, 1, 1], [1, 1, 0, 0]],\n [[0, 1, 0, 1], [1, 1, 0, 0]],\n [[0, 1, 1, 1], [1, 1, 1, 0]]]\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS\n Parallelogram polyominoes\n sage: PPS.cardinality()\n +Infinity\n '
def __call__(self, size=None, policy=None):
'\n Return a family of parallelogram polyominoes enumerated with the\n parameter constraints.\n\n INPUT:\n\n - ``size`` -- integer (default: ``None``), the size of the parallelogram\n polyominoes contained in the family.\n If set to ``None``, the family returned contains all\n the parallelogram polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(size=4)\n sage: PPS\n Parallelogram polyominoes of size 4\n sage: sorted(PPS)\n [[[0, 0, 0, 1], [1, 0, 0, 0]],\n [[0, 0, 1, 1], [1, 0, 1, 0]],\n [[0, 0, 1, 1], [1, 1, 0, 0]],\n [[0, 1, 0, 1], [1, 1, 0, 0]],\n [[0, 1, 1, 1], [1, 1, 1, 0]]]\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS\n Parallelogram polyominoes\n sage: PPS.cardinality()\n +Infinity\n\n sage: PPS = ParallelogramPolyominoes(size=None)\n sage: PPS\n Parallelogram polyominoes\n sage: PPS.cardinality()\n +Infinity\n '
if (policy is None):
policy = self._default_policy
if isinstance(size, (Integer, int)):
return ParallelogramPolyominoes_size(size, policy)
if (size is None):
return ParallelogramPolyominoes_all(policy)
raise ValueError('invalid argument for Parallelogram Polyominoes Factory')
@lazy_attribute
def _default_policy(self):
'\n Return a default policy.\n\n EXAMPLES::\n\n sage: str(ParallelogramPolyominoes._default_policy) == (\n ....: "Set factory policy for " +\n ....: "<class \'sage.combinat.parallelogram_polyomino" +\n ....: ".ParallelogramPolyomino\'> " +\n ....: "with parent Parallelogram polyominoes" +\n ....: "[=Factory for parallelogram polyominoes(())]"\n ....: )\n True\n '
return TopMostParentPolicy(self, (), ParallelogramPolyomino)
def _repr_(self) -> str:
'\n Return the string representation of the parallelogram polyominoes\n factory.\n\n EXAMPLES::\n\n sage: ParallelogramPolyominoes\n Factory for parallelogram polyominoes\n '
return 'Factory for parallelogram polyominoes'
|
class ParallelogramPolyominoes_size(ParentWithSetFactory, UniqueRepresentation):
'\n The parallelogram polyominoes of size `n`.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(4)\n sage: PPS\n Parallelogram polyominoes of size 4\n sage: sorted(PPS)\n [[[0, 0, 0, 1], [1, 0, 0, 0]],\n [[0, 0, 1, 1], [1, 0, 1, 0]],\n [[0, 0, 1, 1], [1, 1, 0, 0]],\n [[0, 1, 0, 1], [1, 1, 0, 0]],\n [[0, 1, 1, 1], [1, 1, 1, 0]]]\n '
def __init__(self, size, policy):
'\n Construct a set of Parallelogram Polyominoes of a given size.\n\n EXAMPLES::\n\n sage: ParallelogramPolyominoes(4)\n Parallelogram polyominoes of size 4\n '
self._size = size
ParentWithSetFactory.__init__(self, (size,), policy, category=FiniteEnumeratedSets())
def _repr_(self) -> str:
'\n Return the string representation of the set of\n parallelogram polyominoes\n\n EXAMPLES::\n\n sage: ParallelogramPolyominoes(4)\n Parallelogram polyominoes of size 4\n '
return ('Parallelogram polyominoes of size %s' % self._size)
def an_element(self):
'\n Return an element of a parallelogram polyomino of a given size.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(4)\n sage: PPS.an_element() in PPS\n True\n '
return next(self.__iter__())
def check_element(self, el, check):
'\n Check is a given element `el` is in the set of parallelogram\n polyominoes of a fixed size.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(3)\n sage: ParallelogramPolyomino( # indirect doctest\n ....: [[0, 1, 1], [1, 1, 0]]\n ....: ) in PPS\n True\n '
if (el.size() != self.size()):
raise ValueError(('the parallelogram polyomino has a wrong size: %s' % el.size()))
def cardinality(self):
'\n Return the number of parallelogram polyominoes.\n\n The number of parallelogram polyominoes of size n is given by\n the Catalan number `c_{n-1}`.\n\n EXAMPLES::\n\n sage: ParallelogramPolyominoes(1).cardinality()\n 1\n sage: ParallelogramPolyominoes(2).cardinality()\n 1\n sage: ParallelogramPolyominoes(3).cardinality()\n 2\n sage: ParallelogramPolyominoes(4).cardinality()\n 5\n\n sage: all(\n ....: ParallelogramPolyominoes(i).cardinality()\n ....: == len(list(ParallelogramPolyominoes(i)))\n ....: for i in range(1,7)\n ....: )\n True\n '
return catalan_number((self.size() - 1))
def __iter__(self):
'\n Return a parallelogram polyomino generator.\n\n EXAMPLES::\n\n sage: len(list(ParallelogramPolyominoes(4))) == 5\n True\n sage: all(\n ....: pp in ParallelogramPolyominoes()\n ....: for pp in ParallelogramPolyominoes(4)\n ....: )\n True\n '
from sage.combinat.dyck_word import DyckWords
for dyck in DyckWords((self.size() - 1)):
(yield ParallelogramPolyomino.from_dyck_word(dyck))
def get_options(self):
"\n Return all the options associated with all the elements of\n the set of parallelogram polyominoes with a fixed size.\n\n EXAMPLES::\n\n sage: pps = ParallelogramPolyominoes(5)\n sage: pps.get_options()\n Current options for ParallelogramPolyominoes_size\n - display: 'list'\n ...\n "
return self.options
def size(self):
'\n Return the size of the parallelogram polyominoes generated by this\n parent.\n\n EXAMPLES::\n\n sage: ParallelogramPolyominoes(0).size()\n 0\n sage: ParallelogramPolyominoes(1).size()\n 1\n sage: ParallelogramPolyominoes(5).size()\n 5\n '
return self._size
def set_options(self, *get_value, **set_value):
'\n Set new options to the object.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes(3)\n sage: PPS.set_options(\n ....: drawing_components=dict(\n ....: diagram = True,\n ....: bounce_0 = True,\n ....: bounce_1 = True,\n ....: )\n ....: )\n sage: pp = PPS[0]\n sage: view(pp) # not tested\n '
self.options(*get_value, **set_value)
options = ParallelogramPolyominoesOptions
'\n The options for ParallelogramPolyominoes.\n '
|
class ParallelogramPolyominoes_all(ParentWithSetFactory, DisjointUnionEnumeratedSets):
'\n This class enumerates all the parallelogram polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS\n Parallelogram polyominoes\n '
def __init__(self, policy):
'\n Construct the set of all parallelogram polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS\n Parallelogram polyominoes\n\n sage: ParallelogramPolyomino([[0, 1, 1], [1, 1, 0]]) in PPS\n True\n\n sage: PPS = ParallelogramPolyominoes()\n sage: next(PPS.__iter__()) in PPS\n True\n '
ParentWithSetFactory.__init__(self, (), policy, category=FiniteEnumeratedSets())
DisjointUnionEnumeratedSets.__init__(self, Family(PositiveIntegers(), (lambda n: ParallelogramPolyominoes_size(n, policy=self.facade_policy()))), facade=True, keepkey=False, category=self.category())
def _repr_(self) -> str:
'\n Return a string representation of the set of parallelogram polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS\n Parallelogram polyominoes\n '
return 'Parallelogram polyominoes'
def check_element(self, el, check):
'\n Check is a given element `el` is in the set of parallelogram\n polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: ParallelogramPolyomino( # indirect doctest\n ....: [[0, 1, 1], [1, 1, 0]]\n ....: ) in PPS\n True\n '
pass
def get_options(self):
"\n Return all the options associated with the set of\n parallelogram polyominoes.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: options = PPS.get_options()\n sage: options\n Current options for ParallelogramPolyominoes_size\n - display: 'list'\n ...\n "
return self.options
def set_options(self, *get_value, **set_value):
'\n Set new options to the object.\n\n EXAMPLES::\n\n sage: PPS = ParallelogramPolyominoes()\n sage: PPS.set_options(\n ....: drawing_components=dict(\n ....: diagram = True,\n ....: bounce_0 = True,\n ....: bounce_1 = True,\n ....: )\n ....: )\n sage: pp = next(iter(PPS))\n sage: view(pp) # not tested\n '
self.options(*get_value, **set_value)
options = ParallelogramPolyominoesOptions
'\n The options for ParallelogramPolyominoes.\n '
|
def is_a(x, n=None) -> bool:
'\n Check whether a list is a parking function.\n\n If a size `n` is specified, checks if a list is a parking function\n of size `n`.\n\n TESTS::\n\n sage: from sage.combinat.parking_functions import is_a\n sage: is_a([1,1,2])\n True\n sage: is_a([1,2,1])\n True\n sage: is_a([1,1,4])\n False\n sage: is_a([3,1,1], 3)\n True\n '
if (not isinstance(x, list)):
return False
A = sorted(x)
return check_NDPF(A, n)
|
class ParkingFunction(ClonableArray, metaclass=InheritComparisonClasscallMetaclass):
"\n A Parking Function.\n\n A *parking function* of size `n` is a sequence `(a_1, \\ldots,a_n)`\n of positive integers such that if `b_1 \\leq b_2 \\leq \\cdots \\leq b_n` is\n the increasing rearrangement of `a_1, \\ldots, a_n`, then `b_i \\leq i`.\n\n A *parking function* of size `n` is a pair `(L, D)` of two sequences\n `L` and `D` where `L` is a permutation and `D` is an area sequence\n of a Dyck Path of size `n` such that `D[i] \\geq 0`, `D[i+1] \\leq D[i]+1`\n and if `D[i+1] = D[i]+1` then `L[i+1] > L[i]`.\n\n The number of parking functions of size `n` is equal to the number\n of rooted forests on `n` vertices and is equal to `(n+1)^{n-1}`.\n\n INPUT:\n\n - ``pf`` -- (default: ``None``) a list whose increasing rearrangement\n satisfies `b_i \\leq i`\n\n - ``labelling`` -- (default: ``None``) a labelling of the Dyck path\n\n - ``area_sequence`` -- (default: ``None``) an area sequence of a Dyck path\n\n - ``labelled_dyck_word`` -- (default: ``None``) a Dyck word with 1's\n replaced by labelling\n\n OUTPUT:\n\n A parking function\n\n EXAMPLES::\n\n sage: ParkingFunction([])\n []\n sage: ParkingFunction([1])\n [1]\n sage: ParkingFunction([2])\n Traceback (most recent call last):\n ...\n ValueError: [2] is not a parking function\n sage: ParkingFunction([1,2])\n [1, 2]\n sage: ParkingFunction([1,1,2])\n [1, 1, 2]\n sage: ParkingFunction([1,4,1])\n Traceback (most recent call last):\n ...\n ValueError: [1, 4, 1] is not a parking function\n sage: ParkingFunction(labelling=[3,1,2], area_sequence=[0,0,1])\n [2, 2, 1]\n sage: ParkingFunction([2,2,1]).to_labelled_dyck_word()\n [3, 0, 1, 2, 0, 0]\n sage: ParkingFunction(labelled_dyck_word=[3,0,1,2,0,0])\n [2, 2, 1]\n sage: ParkingFunction(labelling=[3,1,2], area_sequence=[0,1,1])\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 2] is not a valid labeling of area sequence [0, 1, 1]\n "
@staticmethod
def __classcall_private__(cls, pf=None, labelling=None, area_sequence=None, labelled_dyck_word=None):
'\n Construct a parking function based on the input.\n\n TESTS::\n\n sage: PF = ParkingFunction([1,2])\n sage: isinstance(PF, ParkingFunctions().element_class)\n True\n '
if isinstance(pf, ParkingFunction):
return pf
if (pf is not None):
PF = ParkingFunctions()
return PF.element_class(PF, pf)
elif (labelling is not None):
if (area_sequence is None):
raise ValueError('must also provide area sequence along with labelling')
if (len(area_sequence) != len(labelling)):
raise ValueError(('%s must be the same size as the labelling %s' % (area_sequence, labelling)))
if any((((area_sequence[i] < area_sequence[(i + 1)]) and (labelling[i] > labelling[(i + 1)])) for i in range((len(labelling) - 1)))):
raise ValueError(('%s is not a valid labeling of area sequence %s' % (labelling, area_sequence)))
return from_labelling_and_area_sequence(labelling, area_sequence)
elif (labelled_dyck_word is not None):
return from_labelled_dyck_word(labelled_dyck_word)
elif (area_sequence is not None):
DW = DyckWord(area_sequence)
return ParkingFunction(labelling=list(range(1, (DW.size() + 1))), area_sequence=DW)
raise ValueError('did not manage to make this into a parking function')
def __init__(self, parent, lst):
"\n TESTS::\n\n sage: ParkingFunction([1, 1, 2, 2, 5, 6])\n [1, 1, 2, 2, 5, 6]\n\n sage: PF = ParkingFunction([1, 1, 2, 2, 5, 6])\n sage: PF[0]\n 1\n sage: PF[2]\n 2\n\n sage: PF4 = ParkingFunctions(4)\n sage: a = PF4.list()[36]\n sage: b = PF4([1,3,2,1])\n sage: type(a)\n <class 'sage.combinat.parking_functions.ParkingFunctions_n_with_category.element_class'>\n sage: type(b)\n <class 'sage.combinat.parking_functions.ParkingFunctions_n_with_category.element_class'>\n\n Some checks for more general inputs::\n\n sage: PF = ParkingFunction((1, 1, 2, 2, 5, 6))\n sage: PF = ParkingFunction(Permutation([4,2,3,1]))\n "
if (not isinstance(lst, list)):
try:
lst = list(lst)
except TypeError:
raise TypeError('input must be convertible to a list')
if (parent is None):
parent = ParkingFunctions_n(len(lst))
ClonableArray.__init__(self, parent, lst)
def check(self):
'\n Check that ``self`` is a valid parking function.\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([1, 1, 2, 2, 5, 6])\n sage: PF.check()\n '
if (not check_NDPF(sorted(self), len(self))):
raise ValueError(f'{list(self)} is not a parking function')
def grade(self):
'\n Return the length of the parking function.\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([1, 1, 2, 2, 5, 6])\n sage: PF.grade()\n 6\n '
return len(self)
def __call__(self, n):
'\n Return the image of ``n`` under the parking function.\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([1, 1, 2, 2, 5, 6])\n sage: PF(3)\n 2\n sage: PF(6)\n 6\n '
return self[(n - 1)]
def diagonal_reading_word(self) -> Permutation:
'\n Return a diagonal word of the labelled Dyck path corresponding to parking\n function (see [Hag08]_ p. 75).\n\n OUTPUT:\n\n - returns a word, read diagonally from NE to SW of the pretty\n print of the labelled Dyck path that corresponds to ``self``\n and the same size as ``self``\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.diagonal_reading_word()\n [5, 1, 7, 4, 6, 3, 2]\n\n ::\n\n sage: ParkingFunction([1, 1, 1]).diagonal_reading_word()\n [3, 2, 1]\n sage: ParkingFunction([1, 2, 3]).diagonal_reading_word()\n [3, 2, 1]\n sage: ParkingFunction([1, 1, 3, 4]).diagonal_reading_word()\n [2, 4, 3, 1]\n\n ::\n\n sage: ParkingFunction([1, 1, 1]).diagonal_word()\n [3, 2, 1]\n sage: ParkingFunction([1, 2, 3]).diagonal_word()\n [3, 2, 1]\n sage: ParkingFunction([1, 4, 3, 1]).diagonal_word()\n [4, 2, 3, 1]\n '
L = self.to_labelling_permutation()
D = self.to_area_sequence()
m = max(D)
data = [L[((- j) - 1)] for i in range((m + 1)) for j in range(len(L)) if (D[((- j) - 1)] == (m - i))]
return Permutation(data)
diagonal_word = diagonal_reading_word
def parking_permutation(self) -> Permutation:
'\n Return the sequence of parking spots that are taken by cars 1\n through `n` and corresponding to the parking function.\n\n For example, ``parking_permutation(PF) = [6, 1, 5, 2, 3, 4,\n 7]`` means that spot 6 is taken by car 1, spot 1 by car 2,\n spot 5 by car 3, spot 2 is taken by car 4, spot 3 is taken by\n car 5, spot 4 is taken by car 6 and spot 7 is taken by car 7.\n\n OUTPUT:\n\n - the permutation of parking spots that corresponds to\n the parking function and which is the same size as parking\n function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.parking_permutation()\n [6, 1, 5, 2, 3, 4, 7]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).parking_permutation()\n [3, 1, 2, 4]\n sage: ParkingFunction([4,1,1,1]).parking_permutation()\n [4, 1, 2, 3]\n sage: ParkingFunction([2,1,4,1]).parking_permutation()\n [2, 1, 4, 3]\n '
return self.cars_permutation().inverse()
@combinatorial_map(name='to car permutation')
def cars_permutation(self) -> Permutation:
'\n Return the sequence of cars that take parking spots 1 through `n`\n and corresponding to the parking function.\n\n For example, ``cars_permutation(PF) = [2, 4, 5, 6, 3, 1, 7]``\n means that car 2 takes spots 1, car 4 takes spot 2, ..., car 1\n takes spot 6 and car 7 takes spot 7.\n\n\n OUTPUT:\n\n - the permutation of cars corresponding to the parking function\n and which is the same size as parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.cars_permutation()\n [2, 4, 5, 6, 3, 1, 7]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).cars_permutation()\n [2, 3, 1, 4]\n sage: ParkingFunction([4,1,1,1]).cars_permutation()\n [2, 3, 4, 1]\n sage: ParkingFunction([2,1,4,1]).cars_permutation()\n [2, 1, 4, 3]\n '
out = {}
for i in range(len(self)):
j = 0
while ((self[i] + j) in out):
j += 1
out[(self[i] + j)] = i
data = [(out[(i + 1)] + 1) for i in range(len(self))]
return Permutation(data)
def jump_list(self) -> list:
'\n Return the displacements of cars that corresponds to the parking function.\n\n For example, ``jump_list(PF) = [0, 0, 0, 0, 1, 3, 2]``\n means that car 1 through 4 parked in their preferred spots,\n car 5 had to park one spot farther (jumped or was displaced by one\n spot), car 6 had to jump 3 spots, and car 7 had to jump two spots.\n\n\n OUTPUT:\n\n - the displacements sequence of parked cars which corresponds\n to the parking function and which is the same size as parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.jump_list()\n [0, 0, 0, 0, 1, 3, 2]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).jump_list()\n [0, 0, 1, 0]\n sage: ParkingFunction([4,1,1,1]).jump_list()\n [0, 0, 1, 2]\n sage: ParkingFunction([2,1,4,1]).jump_list()\n [0, 0, 0, 2]\n '
pi = self.parking_permutation()
return [(pi[i] - self[i]) for i in range(len(self))]
def jump(self) -> Integer:
'\n Return the sum of the differences between the parked and\n preferred parking spots.\n\n See [Shin]_ p. 18.\n\n OUTPUT:\n\n - the sum of the differences between the parked and preferred parking\n spots\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.jump()\n 6\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).jump()\n 1\n sage: ParkingFunction([4,1,1,1]).jump()\n 3\n sage: ParkingFunction([2,1,4,1]).jump()\n 2\n '
return sum(self.jump_list())
def lucky_cars(self):
'\n Return the cars that can park in their preferred spots. For example,\n ``lucky_cars(PF) = [1, 2, 7]`` means that cars 1, 2 and 7 parked in\n their preferred spots and all the other cars did not.\n\n\n OUTPUT:\n\n - the cars that can park in their preferred spots\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.lucky_cars()\n [1, 2, 3, 4]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).lucky_cars()\n [1, 2, 4]\n sage: ParkingFunction([4,1,1,1]).lucky_cars()\n [1, 2]\n sage: ParkingFunction([2,1,4,1]).lucky_cars()\n [1, 2, 3]\n '
w = self.jump_list()
return [(i + 1) for i in range(len(w)) if (w[i] == 0)]
def luck(self) -> Integer:
'\n Return the number of cars that parked in their preferred parking spots\n (see [Shin]_ p. 33).\n\n OUTPUT:\n\n - the number of cars that parked in their preferred parking spots\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.luck()\n 4\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).luck()\n 3\n sage: ParkingFunction([4,1,1,1]).luck()\n 2\n sage: ParkingFunction([2,1,4,1]).luck()\n 3\n '
return len(self.lucky_cars())
def primary_dinversion_pairs(self) -> list[tuple[(int, int)]]:
'\n Return the primary descent inversion pairs of a labelled Dyck path\n corresponding to the parking function.\n\n OUTPUT:\n\n - the pairs `(i, j)` such that `i < j`, and `i^{th}` area = `j^{th}` area,\n and `i^{th}` label < `j^{th}` label\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.primary_dinversion_pairs()\n [(0, 4), (1, 5), (2, 5)]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).primary_dinversion_pairs()\n [(0, 3), (2, 3)]\n sage: ParkingFunction([4,1,1,1]).primary_dinversion_pairs()\n []\n sage: ParkingFunction([2,1,4,1]).primary_dinversion_pairs()\n [(0, 3)]\n '
L = self.to_labelling_permutation()
D = self.to_area_sequence()
return [(i, j) for j in range(len(D)) for i in range(j) if ((D[i] == D[j]) and (L[i] < L[j]))]
def secondary_dinversion_pairs(self) -> list[tuple[(int, int)]]:
'\n Return the secondary descent inversion pairs of a labelled Dyck path\n corresponding to the parking function.\n\n OUTPUT:\n\n - the pairs `(i, j)` such that `i < j`, and `i^{th}` area = `j^{th}` area +1,\n and `i^{th}` label > `j^{th}` label\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.secondary_dinversion_pairs()\n [(1, 4), (2, 4), (3, 6)]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).secondary_dinversion_pairs()\n [(1, 2)]\n sage: ParkingFunction([4,1,1,1]).secondary_dinversion_pairs()\n [(1, 3)]\n sage: ParkingFunction([2,1,4,1]).secondary_dinversion_pairs()\n [(1, 3)]\n '
L = self.to_labelling_permutation()
D = self.to_area_sequence()
return [(i, j) for j in range(len(D)) for i in range(j) if ((D[i] == (D[j] + 1)) and (L[i] > L[j]))]
def dinversion_pairs(self) -> list[tuple[(int, int)]]:
'\n Return the descent inversion pairs of a labelled Dyck path\n corresponding to the parking function.\n\n OUTPUT:\n\n - the primary and secondary diversion pairs\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.dinversion_pairs()\n [(0, 4), (1, 5), (2, 5), (1, 4), (2, 4), (3, 6)]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).dinversion_pairs()\n [(0, 3), (2, 3), (1, 2)]\n sage: ParkingFunction([4,1,1,1]).dinversion_pairs()\n [(1, 3)]\n sage: ParkingFunction([2,1,4,1]).dinversion_pairs()\n [(0, 3), (1, 3)]\n '
return (self.primary_dinversion_pairs() + self.secondary_dinversion_pairs())
def dinv(self) -> int:
'\n Return the number of inversions of a labelled Dyck path corresponding\n to the parking function (see [Hag08]_ p. 74).\n\n Same as the cardinality of :meth:`dinversion_pairs`.\n\n OUTPUT:\n\n - the number of dinversion pairs\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.dinv()\n 6\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).dinv()\n 3\n sage: ParkingFunction([4,1,1,1]).dinv()\n 1\n sage: ParkingFunction([2,1,4,1]).dinv()\n 2\n '
return len(self.dinversion_pairs())
def area(self) -> Integer:
'\n Return the area of the labelled Dyck path corresponding to the\n parking function.\n\n OUTPUT:\n\n - the sum of squares under and over the main diagonal the Dyck Path,\n corresponding to the parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.area()\n 6\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).area()\n 1\n sage: ParkingFunction([4,1,1,1]).area()\n 3\n sage: ParkingFunction([2,1,4,1]).area()\n 2\n '
return sum(self.to_area_sequence())
@combinatorial_map(name='to ides composition')
def ides_composition(self):
'\n Return the\n :meth:`~sage.combinat.permutation.Permutation.descents_composition`\n of the inverse of the :meth:`diagonal_reading_word` of\n corresponding parking function.\n\n For example, ``ides_composition(PF) = [4, 2, 1]`` means that\n the descents of the inverse of the permutation\n :meth:`diagonal_reading_word` of the parking function with\n word ``PF`` are at the 4th and 6th positions.\n\n OUTPUT:\n\n - the descents composition of the inverse of the\n :meth:`diagonal_reading_word` of the parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.ides_composition()\n [2, 1, 1, 2, 1]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).ides_composition()\n [2, 2]\n sage: ParkingFunction([4,1,1,1]).ides_composition()\n [2, 1, 1]\n sage: ParkingFunction([4,3,1,1]).ides_composition()\n [3, 1]\n '
return self.diagonal_reading_word().inverse().descents_composition()
def ides(self):
'\n Return the :meth:`~sage.combinat.permutation.Permutation.descents`\n sequence of the inverse of the :meth:`diagonal_reading_word`\n of ``self``.\n\n .. WARNING::\n\n Here we use the standard convention that descent labels\n start at `1`. This behaviour has been changed in\n :trac:`20555`.\n\n For example, ``ides(PF) = [2, 3, 4, 6]`` means that descents are at\n the 2nd, 3rd, 4th and 6th positions in the inverse of the\n :meth:`diagonal_reading_word` of the parking function (see [GXZ]_ p. 2).\n\n OUTPUT:\n\n - the descents sequence of the inverse of the\n :meth:`diagonal_reading_word` of the parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.ides()\n [2, 3, 4, 6]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).ides()\n [2]\n sage: ParkingFunction([4,1,1,1]).ides()\n [2, 3]\n sage: ParkingFunction([4,3,1,1]).ides()\n [3]\n '
return self.diagonal_reading_word().inverse().descents()
def touch_points(self):
'\n Return the sequence of touch points which corresponds to the\n labelled Dyck path after initial step.\n\n For example, ``touch_points(PF) = [4, 7]`` means that after\n the initial step, the path touches the main diagonal at points\n `(4, 4)` and `(7, 7)`.\n\n OUTPUT:\n\n - the sequence of touch points after the initial step of the\n labelled Dyck path that corresponds to the parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.touch_points()\n [4, 7]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).touch_points()\n [2, 3, 4]\n sage: ParkingFunction([4,1,1,1]).touch_points()\n [3, 4]\n sage: ParkingFunction([2,1,4,1]).touch_points()\n [3, 4]\n '
return self.to_dyck_word().touch_points()
@combinatorial_map(name='to touch composition')
def touch_composition(self):
'\n Return the composition of the labelled Dyck path corresponding\n to the parking function.\n\n For example, ``touch_composition(PF) = [4, 3]`` means that the\n first touch is four diagonal units from the starting point,\n and the second is three units further (see [GXZ]_ p. 2).\n\n OUTPUT:\n\n - the length between the corresponding touch points which\n of the labelled Dyck path that corresponds to the parking function\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.touch_composition()\n [4, 3]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).touch_composition()\n [2, 1, 1]\n sage: ParkingFunction([4,1,1,1]).touch_composition()\n [3, 1]\n sage: ParkingFunction([2,1,4,1]).touch_composition()\n [3, 1]\n '
return self.to_dyck_word().touch_composition()
diagonal_composition = touch_composition
@combinatorial_map(name='to labelling permutation')
def to_labelling_permutation(self) -> Permutation:
'\n Return the labelling of the support Dyck path of the parking function.\n\n OUTPUT:\n\n - the labelling of the Dyck path\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_labelling_permutation()\n [2, 6, 4, 5, 3, 7, 1]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_labelling_permutation()\n [2, 3, 1, 4]\n sage: ParkingFunction([4,1,1,1]).to_labelling_permutation()\n [2, 3, 4, 1]\n sage: ParkingFunction([2,1,4,1]).to_labelling_permutation()\n [2, 4, 1, 3]\n '
from sage.combinat.words.word import Word
return Word(self).standard_permutation().inverse()
def to_area_sequence(self) -> list:
'\n Return the area sequence of the support Dyck path of the\n parking function.\n\n OUTPUT:\n\n - the area sequence of the Dyck path\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_area_sequence()\n [0, 1, 1, 2, 0, 1, 1]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_area_sequence()\n [0, 1, 0, 0]\n sage: ParkingFunction([4,1,1,1]).to_area_sequence()\n [0, 1, 2, 0]\n sage: ParkingFunction([2,1,4,1]).to_area_sequence()\n [0, 1, 1, 0]\n '
w = sorted(self)
return [((i + 1) - wi) for (i, wi) in enumerate(w)]
def to_labelling_area_sequence_pair(self):
'\n Return a pair consisting of a labelling and an area sequence\n of a Dyck path which corresponds to the given parking\n function.\n\n OUTPUT:\n\n - returns a pair ``(L, D)`` where ``L`` is a labelling and ``D`` is the\n area sequence of the underlying Dyck path\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_labelling_area_sequence_pair()\n ([2, 6, 4, 5, 3, 7, 1], [0, 1, 1, 2, 0, 1, 1])\n\n ::\n\n sage: ParkingFunction([1, 1, 1]).to_labelling_area_sequence_pair()\n ([1, 2, 3], [0, 1, 2])\n sage: ParkingFunction([1, 2, 3]).to_labelling_area_sequence_pair()\n ([1, 2, 3], [0, 0, 0])\n sage: ParkingFunction([1, 1, 2]).to_labelling_area_sequence_pair()\n ([1, 2, 3], [0, 1, 1])\n sage: ParkingFunction([1, 1, 3, 1]).to_labelling_area_sequence_pair()\n ([1, 2, 4, 3], [0, 1, 2, 1])\n '
return (self.to_labelling_permutation(), self.to_area_sequence())
@combinatorial_map(name='to dyck word')
def to_dyck_word(self) -> DyckWord:
'\n Return the support Dyck word of the parking function.\n\n OUTPUT:\n\n - the Dyck word of the corresponding parking function\n\n .. SEEALSO:: :meth:`DyckWord`\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_dyck_word()\n [1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_dyck_word()\n [1, 1, 0, 0, 1, 0, 1, 0]\n sage: ParkingFunction([4,1,1,1]).to_dyck_word()\n [1, 1, 1, 0, 0, 0, 1, 0]\n sage: ParkingFunction([2,1,4,1]).to_dyck_word()\n [1, 1, 0, 1, 0, 0, 1, 0]\n '
return DyckWord(area_sequence=self.to_area_sequence())
def to_labelled_dyck_word(self):
'\n Return the labelled Dyck word corresponding to the parking function.\n\n This is a representation of the parking function as a list\n where the entries of 1 in the Dyck word are replaced with the\n corresponding label.\n\n OUTPUT:\n\n - the labelled Dyck word of the corresponding parking function\n which is twice the size of parking function word\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_labelled_dyck_word()\n [2, 6, 0, 4, 5, 0, 0, 0, 3, 7, 0, 1, 0, 0]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_labelled_dyck_word()\n [2, 3, 0, 0, 1, 0, 4, 0]\n sage: ParkingFunction([4,1,1,1]).to_labelled_dyck_word()\n [2, 3, 4, 0, 0, 0, 1, 0]\n sage: ParkingFunction([2,1,4,1]).to_labelled_dyck_word()\n [2, 4, 0, 1, 0, 0, 3, 0]\n '
dw = self.to_dyck_word()
out = list(self.to_labelling_permutation())
for i in range((2 * len(out))):
if (dw[i] == 0):
out.insert(i, 0)
return out
def to_labelling_dyck_word_pair(self) -> tuple[(Permutation, DyckWord)]:
'\n Return the pair ``(L, D)`` where ``L`` is a labelling and\n ``D`` is the Dyck word of the parking function.\n\n OUTPUT:\n\n - the pair ``(L, D)``, where ``L`` is the labelling and ``D`` is\n the Dyck word of the parking function\n\n .. SEEALSO:: :meth:`DyckWord`\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_labelling_dyck_word_pair()\n ([2, 6, 4, 5, 3, 7, 1], [1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0])\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_labelling_dyck_word_pair()\n ([2, 3, 1, 4], [1, 1, 0, 0, 1, 0, 1, 0])\n sage: ParkingFunction([4,1,1,1]).to_labelling_dyck_word_pair()\n ([2, 3, 4, 1], [1, 1, 1, 0, 0, 0, 1, 0])\n sage: ParkingFunction([2,1,4,1]).to_labelling_dyck_word_pair()\n ([2, 4, 1, 3], [1, 1, 0, 1, 0, 0, 1, 0])\n '
return (self.to_labelling_permutation(), self.to_dyck_word())
@combinatorial_map(name='to non-decreasing parking function')
def to_NonDecreasingParkingFunction(self) -> PF:
'\n Return the non-decreasing parking function which underlies the\n parking function.\n\n OUTPUT:\n\n - a sorted parking function\n\n .. SEEALSO:: :meth:`NonDecreasingParkingFunction`\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.to_NonDecreasingParkingFunction()\n [1, 1, 2, 2, 5, 5, 6]\n\n ::\n\n sage: ParkingFunction([3,1,1,4]).to_NonDecreasingParkingFunction()\n [1, 1, 3, 4]\n sage: ParkingFunction([4,1,1,1]).to_NonDecreasingParkingFunction()\n [1, 1, 1, 4]\n sage: ParkingFunction([2,1,4,1]).to_NonDecreasingParkingFunction()\n [1, 1, 2, 4]\n sage: ParkingFunction([4,1,2,1]).to_NonDecreasingParkingFunction()\n [1, 1, 2, 4]\n '
return ParkingFunction(sorted(self))
def characteristic_quasisymmetric_function(self, q=None, R=QQ[('q', 't')].fraction_field()):
"\n Return the characteristic quasisymmetric function of ``self``.\n\n The characteristic function of the Parking Function is the sum\n over all permutation labellings of the Dyck path `q^{dinv(PF)}\n F_{ides(PF)}` where `ides(PF)` (:meth:`ides_composition`) is\n the descent composition of diagonal reading word of the\n parking function.\n\n INPUT:\n\n - ``q`` -- (default: ``q = R('q')``) a parameter for the\n generating function power\n\n - ``R`` -- (default: ``R = QQ['q','t'].fraction_field()``) the\n base ring to do the calculations over\n\n OUTPUT:\n\n - an element of the quasisymmetric functions over the ring ``R``\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: R = QQ['q','t'].fraction_field()\n sage: (q,t) = R.gens()\n sage: cqf = sum(t**PF.area() * PF.characteristic_quasisymmetric_function()\n ....: for PF in ParkingFunctions(3)); cqf\n (q^3+q^2*t+q*t^2+t^3+q*t)*F[1, 1, 1] + (q^2+q*t+t^2+q+t)*F[1, 2]\n + (q^2+q*t+t^2+q+t)*F[2, 1] + F[3]\n sage: s = SymmetricFunctions(R).s()\n sage: s(cqf.to_symmetric_function())\n (q^3+q^2*t+q*t^2+t^3+q*t)*s[1, 1, 1] + (q^2+q*t+t^2+q+t)*s[2, 1] + s[3]\n sage: s(cqf.to_symmetric_function()).nabla(power=-1)\n s[1, 1, 1]\n\n ::\n\n sage: p = ParkingFunction([3, 1, 2])\n sage: p.characteristic_quasisymmetric_function() # needs sage.modules\n q*F[2, 1]\n sage: pf = ParkingFunction([1,2,7,2,1,2,3,2,1])\n sage: pf.characteristic_quasisymmetric_function() # needs sage.modules\n q^2*F[1, 1, 1, 2, 1, 3]\n "
from sage.combinat.ncsf_qsym.qsym import QuasiSymmetricFunctions
if (q is None):
q = R('q')
elif (q not in R):
raise ValueError(('q=%s must be an element of the base ring %s' % (q, R)))
F = QuasiSymmetricFunctions(R).Fundamental()
return ((q ** self.dinv()) * F(self.ides_composition()))
def pretty_print(self, underpath=True):
'\n Displays a parking function as a lattice path consisting of a\n Dyck path and a labelling with the labels displayed along the\n edges of the Dyck path.\n\n INPUT:\n\n - ``underpath`` -- if the length of the parking function is\n less than or equal to 9 then display the labels under the\n path if ``underpath`` is True otherwise display them to the\n right of the path (default: ``True``)\n\n EXAMPLES::\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.pretty_print()\n ___\n _|1x\n |7x .\n _____|3 . .\n |5x x . . .\n _|4x . . . .\n |6x . . . . .\n |2 . . . . . .\n\n sage: PF = ParkingFunction([6, 1, 5, 2, 2, 1, 5])\n sage: PF.pretty_print(underpath = false)\n ___\n _| x 1\n | x . 7\n _____| . . 3\n | x x . . . 5\n _| x . . . . 4\n | x . . . . . 6\n | . . . . . . 2\n\n ::\n\n sage: ParkingFunction([3, 1, 1, 4]).pretty_print()\n _\n _|4\n ___|1 .\n |3x . .\n |2 . . .\n\n sage: ParkingFunction([1,1,1]).pretty_print()\n _____\n |3x x\n |2x .\n |1 . .\n\n sage: ParkingFunction([4,1,1,1]).pretty_print()\n _\n _____|1\n |4x x .\n |3x . .\n |2 . . .\n\n sage: ParkingFunction([2,1,4,1]).pretty_print()\n _\n ___|3\n _|1x .\n |4x . .\n |2 . . .\n\n sage: ParkingFunction([2,1,4,1]).pretty_print(underpath = false)\n _\n ___| 3\n _| x . 1\n | x . . 4\n | . . . 2\n\n sage: pf = ParkingFunction([1,2,3,7,3,2,1,2,3,2,1])\n sage: pf.pretty_print()\n _________\n _______| x x x x 4\n | x x x x x x x . 9\n | x x x x x x . . 5\n _| x x x x x . . . 3\n | x x x x x . . . . 10\n | x x x x . . . . . 8\n | x x x . . . . . . 6\n _| x x . . . . . . . 2\n | x x . . . . . . . . 11\n | x . . . . . . . . . 7\n | . . . . . . . . . . 1\n '
L = self.to_labelling_permutation()
dw = self.to_dyck_word()
if (len(L) <= 9):
dw.pretty_print(labelling=L, underpath=underpath)
else:
dw.pretty_print(labelling=L, underpath=False)
|
def from_labelling_and_area_sequence(L, D) -> PF:
'\n Return the parking function corresponding to the labelling area\n sequence pair.\n\n INPUT:\n\n - ``L`` -- a labelling permutation\n\n - ``D`` -- an area sequence for a Dyck word\n\n OUTPUT:\n\n - the parking function corresponding the labelling permutation ``L``\n and ``D`` an area sequence of the corresponding Dyck path\n\n EXAMPLES::\n\n sage: from sage.combinat.parking_functions import from_labelling_and_area_sequence\n sage: from_labelling_and_area_sequence([2, 6, 4, 5, 3, 7, 1], [0, 1, 1, 2, 0, 1, 1])\n [6, 1, 5, 2, 2, 1, 5]\n\n ::\n\n sage: from_labelling_and_area_sequence([1, 2, 3], [0, 1, 2])\n [1, 1, 1]\n sage: from_labelling_and_area_sequence([1, 2, 3], [0, 0, 0])\n [1, 2, 3]\n sage: from_labelling_and_area_sequence([1, 2, 3], [0, 1, 1])\n [1, 1, 2]\n sage: from_labelling_and_area_sequence([1, 2, 4, 3], [0, 1, 2, 1])\n [1, 1, 3, 1]\n\n TESTS::\n\n sage: PF = from_labelling_and_area_sequence([1, 2, 4, 3], [0, 1, 2, 1])\n sage: isinstance(PF, ParkingFunctions().element_class)\n True\n '
PF = ParkingFunctions_all()
return PF.element_class(PF, [((L.index(i) + 1) - D[L.index(i)]) for i in range(1, (len(L) + 1))])
|
def from_labelled_dyck_word(LDW) -> PF:
'\n Return the parking function corresponding to the labelled Dyck word.\n\n INPUT:\n\n - ``LDW`` -- labelled Dyck word\n\n OUTPUT:\n\n - the parking function corresponding to the labelled Dyck\n word that is half the size of ``LDW``\n\n EXAMPLES::\n\n sage: from sage.combinat.parking_functions import from_labelled_dyck_word\n sage: LDW = [2, 6, 0, 4, 5, 0, 0, 0, 3, 7, 0, 1, 0, 0]\n sage: from_labelled_dyck_word(LDW)\n [6, 1, 5, 2, 2, 1, 5]\n\n ::\n\n sage: from_labelled_dyck_word([2, 3, 0, 0, 1, 0, 4, 0])\n [3, 1, 1, 4]\n sage: from_labelled_dyck_word([2, 3, 4, 0, 0, 0, 1, 0])\n [4, 1, 1, 1]\n sage: from_labelled_dyck_word([2, 4, 0, 1, 0, 0, 3, 0])\n [2, 1, 4, 1]\n '
L = [ell for ell in LDW if (ell != 0)]
D = DyckWord([Integer((not x.is_zero())) for x in LDW])
return from_labelling_and_area_sequence(L, D.to_area_sequence())
|
class ParkingFunctions(UniqueRepresentation, Parent):
'\n Return the combinatorial class of Parking Functions.\n\n A *parking function* of size `n` is a sequence `(a_1, \\ldots,a_n)`\n of positive integers such that if `b_1 \\leq b_2 \\leq \\cdots \\leq b_n` is\n the increasing rearrangement of `a_1, \\ldots, a_n`, then `b_i \\leq i`.\n\n A *parking function* of size `n` is a pair `(L, D)` of two sequences\n `L` and `D` where `L` is a permutation and `D` is an area sequence\n of a Dyck Path of size n such that `D[i] \\geq 0`, `D[i+1] \\leq D[i]+1`\n and if `D[i+1] = D[i]+1` then `L[i+1] > L[i]`.\n\n The number of parking functions of size `n` is equal to the number\n of rooted forests on `n` vertices and is equal to `(n+1)^{n-1}`.\n\n EXAMPLES:\n\n Here are all parking functions of size 3::\n\n sage: from sage.combinat.parking_functions import ParkingFunctions\n sage: ParkingFunctions(3).list()\n [[1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 3], [1, 3, 1],\n [3, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 2, 3], [1, 3, 2],\n [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n If no size is specified, then ParkingFunctions returns the\n combinatorial class of all parking functions. ::\n\n sage: PF = ParkingFunctions(); PF\n Parking functions\n sage: [] in PF\n True\n sage: [1] in PF\n True\n sage: [2] in PF\n False\n sage: [1,3,1] in PF\n True\n sage: [1,4,1] in PF\n False\n\n If the size `n` is specified, then ParkingFunctions returns\n the combinatorial class of all parking functions of size `n`.\n\n ::\n\n sage: PF = ParkingFunctions(0)\n sage: PF.list()\n [[]]\n sage: PF = ParkingFunctions(1)\n sage: PF.list()\n [[1]]\n sage: PF = ParkingFunctions(3)\n sage: PF.list()\n [[1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 3],\n [1, 3, 1], [3, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1],\n [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n ::\n\n sage: PF3 = ParkingFunctions(3); PF3\n Parking functions of size 3\n sage: [] in PF3\n False\n sage: [1] in PF3\n False\n sage: [1,3,1] in PF3\n True\n sage: [1,4,1] in PF3\n False\n\n TESTS::\n\n sage: PF = ParkingFunctions(5)\n sage: TestSuite(PF).run()\n sage: len(PF.list()) == PF.cardinality()\n True\n '
@staticmethod
def __classcall_private__(cls, n=None):
"\n Return the correct parent based on input.\n\n TESTS::\n\n sage: type(ParkingFunctions(5))\n <class 'sage.combinat.parking_functions.ParkingFunctions_n_with_category'>\n sage: type(ParkingFunctions())\n <class 'sage.combinat.parking_functions.ParkingFunctions_all_with_category'>\n "
if (n is None):
return ParkingFunctions_all()
if ((not isinstance(n, (Integer, int))) or (n < 0)):
raise ValueError(('%s is not a non-negative integer' % n))
return ParkingFunctions_n(n)
|
class ParkingFunctions_all(ParkingFunctions):
def __init__(self):
'\n TESTS::\n\n sage: PF = ParkingFunctions()\n sage: TestSuite(PF).run()\n '
cat = (InfiniteEnumeratedSets() & SetsWithGrading())
Parent.__init__(self, category=cat)
Element = ParkingFunction
def _repr_(self) -> str:
"\n TESTS::\n\n sage: repr(ParkingFunctions())\n 'Parking functions'\n "
return 'Parking functions'
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: [] in ParkingFunctions()\n True\n sage: [1] in ParkingFunctions()\n True\n sage: [2] in ParkingFunctions()\n False\n sage: [1,3,1] in ParkingFunctions()\n True\n sage: [1,4,1] in ParkingFunctions()\n False\n '
if isinstance(x, ParkingFunction):
return True
return is_a(x)
def graded_component(self, n):
'\n Return the graded component.\n\n EXAMPLES::\n\n sage: PF = ParkingFunctions()\n sage: PF.graded_component(4) == ParkingFunctions(4)\n True\n sage: it = iter(ParkingFunctions()) # indirect doctest\n sage: [next(it) for i in range(8)]\n [[], [1], [1, 1], [1, 2], [2, 1], [1, 1, 1], [1, 1, 2], [1, 2, 1]]\n '
return ParkingFunctions_n(n)
def __iter__(self) -> Iterator:
'\n Return an iterator.\n\n TESTS::\n\n sage: it = iter(ParkingFunctions()) # indirect doctest\n sage: [next(it) for i in range(8)]\n [[], [1], [1, 1], [1, 2], [2, 1], [1, 1, 1], [1, 1, 2], [1, 2, 1]]\n '
n = 0
while True:
for pf in ParkingFunctions_n(n):
(yield self.element_class(self, list(pf)))
n += 1
def _coerce_map_from_(self, S):
'\n Coercion from the homogeneous component to the graded set.\n\n EXAMPLES::\n\n sage: PF = ParkingFunctions()\n sage: PF3 = ParkingFunctions(3)\n sage: x = PF([1,3,2])\n sage: y = PF3([1,3,2])\n sage: PF(y).parent()\n Parking functions\n sage: x == y\n True\n '
if isinstance(S, ParkingFunctions_n):
return True
return False
|
class ParkingFunctions_n(ParkingFunctions):
'\n The combinatorial class of parking functions of size `n`.\n\n A *parking function* of size `n` is a sequence `(a_1, \\ldots,a_n)`\n of positive integers such that if `b_1 \\leq b_2 \\leq \\cdots \\leq b_n` is\n the increasing rearrangement of `a_1, \\ldots, a_n`, then `b_i \\leq i`.\n\n A *parking function* of size `n` is a pair `(L, D)` of two sequences\n `L` and `D` where `L` is a permutation and `D` is an area sequence\n of a Dyck Path of size `n` such that `D[i] \\geq 0`, `D[i+1] \\leq D[i]+1`\n and if `D[i+1] = D[i]+1` then `L[i+1] > L[i]`.\n\n The number of parking functions of size `n` is equal to the number\n of rooted forests on `n` vertices and is equal to `(n+1)^{n-1}`.\n\n EXAMPLES::\n\n sage: PF = ParkingFunctions(3)\n sage: PF.list()\n [[1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 3],\n [1, 3, 1], [3, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1],\n [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n sage: [ParkingFunctions(i).cardinality() for i in range(6)]\n [1, 1, 3, 16, 125, 1296]\n\n .. WARNING::\n\n The precise order in which the parking function are generated or\n listed is not fixed, and may change in the future.\n\n TESTS:\n\n Check that :trac:`15216` is fixed::\n\n sage: PF = ParkingFunctions()\n sage: PF3 = ParkingFunctions(3)\n sage: [1,1,1] in PF3\n True\n sage: PF3([1,1,1]) in PF3\n True\n sage: PF3([1,1,1]) in PF\n True\n sage: PF([1,1,1]) in PF\n True\n sage: PF3(PF3([1,1,1]))\n [1, 1, 1]\n '
def __init__(self, n):
'\n TESTS::\n\n sage: PF = ParkingFunctions(3)\n sage: TestSuite(PF).run()\n '
self.n = n
Parent.__init__(self, category=FiniteEnumeratedSets())
Element = ParkingFunction
def _repr_(self) -> str:
"\n TESTS::\n\n sage: repr(ParkingFunctions(3))\n 'Parking functions of size 3'\n "
return ('Parking functions of size %s' % self.n)
def __contains__(self, x) -> bool:
'\n TESTS::\n\n sage: PF3 = ParkingFunctions(3); PF3\n Parking functions of size 3\n sage: [] in PF3\n False\n sage: [1] in PF3\n False\n sage: [1,3,1] in PF3\n True\n sage: [1,1,1] in PF3\n True\n sage: [1,4,1] in PF3\n False\n sage: ParkingFunction([1,2]) in PF3\n False\n sage: all(p in PF3 for p in PF3)\n True\n '
if (isinstance(x, ParkingFunction) and (len(x) == self.n)):
return True
return is_a(x, self.n)
def cardinality(self) -> Integer:
'\n Return the number of parking functions of size ``n``.\n\n The cardinality is equal to `(n+1)^{n-1}`.\n\n EXAMPLES::\n\n sage: [ParkingFunctions(i).cardinality() for i in range(6)]\n [1, 1, 3, 16, 125, 1296]\n '
return Integer(((self.n + 1) ** (self.n - 1)))
def __iter__(self) -> Iterator:
'\n Return an iterator for parking functions of size `n`.\n\n .. WARNING::\n\n The precise order in which the parking function are\n generated is not fixed, and may change in the future.\n\n EXAMPLES::\n\n sage: PF = ParkingFunctions(0)\n sage: [e for e in PF] # indirect doctest\n [[]]\n sage: PF = ParkingFunctions(1)\n sage: [e for e in PF] # indirect doctest\n [[1]]\n sage: PF = ParkingFunctions(2)\n sage: [e for e in PF] # indirect doctest\n [[1, 1], [1, 2], [2, 1]]\n sage: PF = ParkingFunctions(3)\n sage: [e for e in PF] # indirect doctest\n [[1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 3],\n [1, 3, 1], [3, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 1],\n [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n\n TESTS::\n\n sage: PF = ParkingFunctions(5)\n sage: [e for e in PF] == PF.list()\n True\n sage: PF = ParkingFunctions(6)\n sage: [e for e in PF] == PF.list()\n True\n '
def iterator_rec(n):
'\n TESTS::\n\n sage: PF = ParkingFunctions(2)\n sage: [e for e in PF] # indirect doctest\n [[1, 1], [1, 2], [2, 1]]\n '
if (n == 0):
(yield [])
return
if (n == 1):
(yield [1])
return
for res1 in iterator_rec((n - 1)):
for i in range(res1[(- 1)], (n + 1)):
(yield (res1 + [i]))
return
for res in iterator_rec(self.n):
for pi in Permutations(res):
(yield self.element_class(self, list(pi)))
return
def random_element(self) -> PF:
'\n Return a random parking function of size `n`.\n\n The algorithm uses a circular parking space with `n+1`\n spots. Then all `n` cars can park and there remains one empty\n spot. Spots are then renumbered so that the empty spot is `0`.\n\n The probability distribution is uniform on the set of\n `(n+1)^{n-1}` parking functions of size `n`.\n\n EXAMPLES::\n\n sage: pf = ParkingFunctions(8)\n sage: a = pf.random_element(); a # random\n [5, 7, 2, 4, 2, 5, 1, 3]\n sage: a in pf\n True\n '
n = self.n
Zm = Zmod((n + 1))
fun = [Zm(randint(0, n)) for i in range(n)]
free = [Zm(j) for j in range((n + 1))]
for car in fun:
position = car
while (position not in free):
position += Zm.one()
free.remove(position)
return self.element_class(self, [(i - free[0]).lift() for i in fun])
|
class Partition(CombinatorialElement):
'\n A partition `p` of a nonnegative integer `n` is a\n non-increasing list of positive integers (the *parts* of the\n partition) with total sum `n`.\n\n A partition is often represented as a diagram consisting of **cells**,\n or **boxes**, placed in rows on top of each other such that the number of\n cells in the `i^{th}` row, reading from top to bottom, is the `i^{th}`\n part of the partition. The rows are left-justified (and become shorter\n and shorter the farther down one goes). This diagram is called the\n **Young diagram** of the partition, or more precisely its Young diagram\n in English notation. (French and Russian notations are variations on this\n representation.)\n\n The coordinate system related to a partition applies from the top\n to the bottom and from left to right. So, the corners of the\n partition ``[5, 3, 1]`` are ``[[0,4], [1,2], [2,0]]``.\n\n For display options, see :meth:`Partitions.options`.\n\n .. NOTE::\n\n Partitions are 0 based with coordinates in the form of (row-index,\n column-index). For example consider the partition\n ``mu=Partition([4,3,2,2])``, the first part is ``mu[0]`` (which is 4),\n the second is ``mu[1]``, and so on, and the upper-left cell in English\n convention is ``(0, 0)``.\n\n A partition can be specified in one of the following ways:\n\n - a list (the default)\n - using exponential notation\n - by Frobenius coordinates\n - specifying its `0-1` sequence\n - specifying the core and the quotient\n\n See the examples below.\n\n EXAMPLES:\n\n Creating partitions though parents::\n\n sage: mu = Partitions(8)([3,2,1,1,1]); mu\n [3, 2, 1, 1, 1]\n sage: nu = Partition([3,2,1,1,1]); nu\n [3, 2, 1, 1, 1]\n sage: mu == nu\n True\n sage: mu is nu\n False\n sage: mu in Partitions()\n True\n sage: mu.parent()\n Partitions of the integer 8\n sage: mu.size()\n 8\n sage: mu.category()\n Category of elements of Partitions of the integer 8\n sage: nu.parent()\n Partitions\n sage: nu.category()\n Category of elements of Partitions\n sage: mu[0]\n 3\n sage: mu[1]\n 2\n sage: mu[2]\n 1\n sage: mu.pp()\n ***\n **\n *\n *\n *\n sage: mu.removable_cells()\n [(0, 2), (1, 1), (4, 0)]\n sage: mu.down_list()\n [[2, 2, 1, 1, 1], [3, 1, 1, 1, 1], [3, 2, 1, 1]]\n sage: mu.addable_cells()\n [(0, 3), (1, 2), (2, 1), (5, 0)]\n sage: mu.up_list()\n [[4, 2, 1, 1, 1], [3, 3, 1, 1, 1], [3, 2, 2, 1, 1], [3, 2, 1, 1, 1, 1]]\n sage: mu.conjugate()\n [5, 2, 1]\n sage: mu.dominates(nu)\n True\n sage: nu.dominates(mu)\n True\n\n Creating partitions using ``Partition``::\n\n sage: Partition([3,2,1])\n [3, 2, 1]\n sage: Partition(exp=[2,1,1])\n [3, 2, 1, 1]\n sage: Partition(core=[2,1], quotient=[[2,1],[3],[1,1,1]])\n [11, 5, 5, 3, 2, 2, 2]\n sage: Partition(frobenius_coordinates=([3,2],[4,0]))\n [4, 4, 1, 1, 1]\n sage: Partitions().from_zero_one([1, 1, 1, 1, 0, 1, 0])\n [5, 4]\n sage: [2,1] in Partitions()\n True\n sage: [2,1,0] in Partitions()\n True\n sage: Partition([1,2,3])\n Traceback (most recent call last):\n ...\n ValueError: [1, 2, 3] is not an element of Partitions\n\n Sage ignores trailing zeros at the end of partitions::\n\n sage: Partition([3,2,1,0])\n [3, 2, 1]\n sage: Partitions()([3,2,1,0])\n [3, 2, 1]\n sage: Partitions(6)([3,2,1,0])\n [3, 2, 1]\n\n TESTS:\n\n Check that only trailing zeros are stripped::\n\n sage: TestSuite( Partition([]) ).run()\n sage: TestSuite( Partition([4,3,2,2,2,1]) ).run()\n sage: Partition([3,2,2,2,1,0,0,0])\n [3, 2, 2, 2, 1]\n sage: Partition([3,0,2,2,2,1,0])\n Traceback (most recent call last):\n ...\n ValueError: [3, 0, 2, 2, 2, 1, 0] is not an element of Partitions\n sage: Partition([0,7,3])\n Traceback (most recent call last):\n ...\n ValueError: [0, 7, 3] is not an element of Partitions\n '
@staticmethod
def __classcall_private__(cls, mu=None, **keyword):
'\n This constructs a list from optional arguments and delegates the\n construction of a :class:`Partition` to the ``element_class()`` call\n of the appropriate parent.\n\n EXAMPLES::\n\n sage: Partition([3,2,1])\n [3, 2, 1]\n sage: Partition(exp=[2,1,1])\n [3, 2, 1, 1]\n sage: Partition(core=[2,1], quotient=[[2,1],[3],[1,1,1]])\n [11, 5, 5, 3, 2, 2, 2]\n '
l = len(keyword)
if (l == 0):
if (mu is not None):
if isinstance(mu, Partition):
return mu
return _Partitions(list(mu))
if (l == 1):
if ('beta_numbers' in keyword):
return _Partitions.from_beta_numbers(keyword['beta_numbers'])
elif ('exp' in keyword):
return _Partitions.from_exp(keyword['exp'])
elif ('frobenius_coordinates' in keyword):
return _Partitions.from_frobenius_coordinates(keyword['frobenius_coordinates'])
elif ('zero_one' in keyword):
return _Partitions.from_zero_one(keyword['zero_one'])
if ((l == 2) and ('core' in keyword) and ('quotient' in keyword)):
return _Partitions.from_core_and_quotient(keyword['core'], keyword['quotient'])
raise ValueError('incorrect syntax for Partition()')
def __setstate__(self, state):
"\n In order to maintain backwards compatibility and be able to unpickle a\n old pickle from ``Partition_class`` we have to override the default\n ``__setstate__``.\n\n EXAMPLES::\n\n sage: loads(b'x\\x9ck`J.NLO\\xd5K\\xce\\xcfM\\xca\\xccK,\\xd1+H,*\\xc9,\\xc9\\xcc\\xcf\\xe3\\n\\x80\\xb1\\xe2\\x93s\\x12\\x8b\\x8b\\xb9\\n\\x195\\x1b\\x0b\\x99j\\x0b\\x995BY\\xe33\\x12\\x8b3\\nY\\xfc\\x80\\xac\\x9c\\xcc\\xe2\\x92B\\xd6\\xd8B6\\r\\x88IE\\x99y\\xe9\\xc5z\\x99y%\\xa9\\xe9\\xa9E\\\\\\xb9\\x89\\xd9\\xa9\\xf10N!{(\\xa3qkP!G\\x06\\x90a\\x04dp\\x82\\x18\\x86@\\x06Wji\\x92\\x1e\\x00x0.\\xb5')\n [3, 2, 1]\n sage: loads(dumps( Partition([3,2,1]) )) # indirect doctest\n [3, 2, 1]\n "
if isinstance(state, dict):
self._set_parent(_Partitions)
self.__dict__ = state
else:
self._set_parent(state[0])
self.__dict__ = state[1]
def __init__(self, parent, mu):
'\n Initialize ``self``.\n\n We assume that ``mu`` is a weakly decreasing list of\n non-negative elements in ``ZZ``.\n\n EXAMPLES::\n\n sage: p = Partition([3,1])\n sage: TestSuite(p).run()\n\n TESTS:\n\n Fix that tuples raise the correct error::\n\n sage: Partition((3,1,7))\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 7] is not an element of Partitions\n '
if isinstance(mu, Partition):
CombinatorialElement.__init__(self, parent, mu._list)
else:
if (mu and (not mu[(- 1)])):
mu = mu[:(- 1)]
while (mu and (not mu[(- 1)])):
mu.pop()
CombinatorialElement.__init__(self, parent, mu)
@cached_method
def __hash__(self):
'\n Return the hash of ``self``.\n\n TESTS::\n\n sage: P = Partition([4,2,2,1])\n sage: hash(P) == hash(P)\n True\n '
return hash(tuple(self._list))
def _repr_(self):
'\n Return a string representation of ``self`` depending on\n :meth:`Partitions.options`.\n\n EXAMPLES::\n\n sage: mu=Partition([7,7,7,3,3,2,1,1,1,1,1,1,1]); mu # indirect doctest\n [7, 7, 7, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1]\n sage: Partitions.options.display="diagram"; mu\n *******\n *******\n *******\n ***\n ***\n **\n *\n *\n *\n *\n *\n *\n *\n sage: Partitions.options.display="list"; mu\n [7, 7, 7, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1]\n sage: Partitions.options.display="compact_low"; mu\n 1^7,2,3^2,7^3\n sage: Partitions.options.display="compact_high"; mu\n 7^3,3^2,2,1^7\n sage: Partitions.options.display="exp_low"; mu\n 1^7, 2, 3^2, 7^3\n sage: Partitions.options.display="exp_high"; mu\n 7^3, 3^2, 2, 1^7\n\n sage: Partitions.options.convention="French"\n sage: mu = Partition([7,7,7,3,3,2,1,1,1,1,1,1,1]); mu # indirect doctest\n 7^3, 3^2, 2, 1^7\n sage: Partitions.options.display="diagram"; mu\n *\n *\n *\n *\n *\n *\n *\n **\n ***\n ***\n *******\n *******\n *******\n sage: Partitions.options.display="list"; mu\n [7, 7, 7, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1]\n sage: Partitions.options.display="compact_low"; mu\n 1^7,2,3^2,7^3\n sage: Partitions.options.display="compact_high"; mu\n 7^3,3^2,2,1^7\n sage: Partitions.options.display="exp_low"; mu\n 1^7, 2, 3^2, 7^3\n sage: Partitions.options.display="exp_high"; mu\n 7^3, 3^2, 2, 1^7\n\n sage: Partitions.options._reset()\n '
return self.parent().options._dispatch(self, '_repr_', 'display')
def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(Partitions(5).list())\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 TESTS::\n\n sage: unicode_art(Partitions(5).list())\n ⎡ ┌┐ ⎤\n ⎢ ┌┬┐ ├┤ ⎥\n ⎢ ┌┬┬┐ ┌┬┐ ├┼┘ ├┤ ⎥\n ⎢ ┌┬┬┬┐ ┌┬┬┐ ├┼┴┘ ├┼┤ ├┤ ├┤ ⎥\n ⎢ ┌┬┬┬┬┐ ├┼┴┴┘ ├┼┼┘ ├┤ ├┼┘ ├┤ ├┤ ⎥\n ⎣ └┴┴┴┴┘, └┘ , └┴┘ , └┘ , └┘ , └┘ , └┘ ⎦\n sage: Partitions.options.convention = "French"\n sage: unicode_art(Partitions(5).list())\n ⎡ ┌┐ ⎤\n ⎢ ┌┐ ├┤ ⎥\n ⎢ ┌┐ ┌┐ ├┤ ├┤ ⎥\n ⎢ ┌┐ ┌┬┐ ├┤ ├┼┐ ├┤ ├┤ ⎥\n ⎢ ┌┬┬┬┬┐ ├┼┬┬┐ ├┼┼┐ ├┼┬┐ ├┼┤ ├┼┐ ├┤ ⎥\n ⎣ └┴┴┴┴┘, └┴┴┴┘, └┴┴┘, └┴┴┘, └┴┘, └┴┘, └┘ ⎦\n sage: Partitions.options._reset()\n '
from sage.typeset.unicode_art import UnicodeArt
if (not self._list):
return UnicodeArt('∅', baseline=0)
if (self.parent().options.convention == 'English'):
data = list(self)
else:
data = list(reversed(self))
txt = [(('┌' + ('┬' * (data[0] - 1))) + '┐')]
for i in range((len(data) - 1)):
p = data[i]
q = data[(i + 1)]
if (p < q):
txt += [((('├' + ('┼' * p)) + ('┬' * ((q - p) - 1))) + '┐')]
elif (p == q):
txt += [(('├' + ('┼' * (p - 1))) + '┤')]
else:
txt += [((('├' + ('┼' * q)) + ('┴' * ((p - q) - 1))) + '┘')]
txt += [(('└' + ('┴' * (data[(- 1)] - 1))) + '┘')]
return UnicodeArt(txt, baseline=0)
def _repr_list(self):
'\n Return a string representation of ``self`` as a list.\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_list())\n [7, 7, 7, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1]\n '
return ('[%s]' % ', '.join((('%s' % m) for m in self)))
def _repr_exp_low(self):
'\n Return a string representation of ``self`` in exponential form (lowest\n first).\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_exp_low())\n 1^7, 2, 3^2, 7^3\n sage: print(Partition([])._repr_exp_low())\n -\n '
if (not self._list):
return '-'
exp = self.to_exp()
return ('%s' % ', '.join((('%s%s' % ((m + 1), ('' if (e == 1) else ('^%s' % e)))) for (m, e) in enumerate(exp) if (e > 0))))
def _repr_exp_high(self):
'\n Return a string representation of ``self`` in exponential form (highest\n first).\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_exp_high())\n 7^3, 3^2, 2, 1^7\n\n sage: print(Partition([])._repr_exp_high())\n -\n '
if (not self._list):
return '-'
exp = self.to_exp()[::(- 1)]
M = max(self)
return ', '.join((('%s%s' % ((M - m), ('' if (e == 1) else ('^%s' % e)))) for (m, e) in enumerate(exp) if (e > 0)))
def _repr_compact_low(self):
'\n Return a string representation of ``self`` in compact form (exponential\n form with lowest first).\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_compact_low())\n 1^7,2,3^2,7^3\n sage: print(Partition([])._repr_compact_low())\n -\n '
if (not self._list):
return '-'
exp = self.to_exp()
return ('%s' % ','.join((('%s%s' % ((m + 1), ('' if (e == 1) else ('^%s' % e)))) for (m, e) in enumerate(exp) if (e > 0))))
def _repr_compact_high(self):
'\n Return a string representation of ``self`` in compact form (exponential\n form with highest first).\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_compact_high())\n 7^3,3^2,2,1^7\n sage: print(Partition([])._repr_compact_low())\n -\n '
if (not self._list):
return '-'
exp = self.to_exp()[::(- 1)]
M = max(self)
return ('%s' % ','.join((('%s%s' % ((M - m), ('' if (e == 1) else ('^%s' % e)))) for (m, e) in enumerate(exp) if (e > 0))))
def _repr_diagram(self):
'\n Return a representation of ``self`` as a Ferrers diagram.\n\n EXAMPLES::\n\n sage: print(Partition([7,7,7,3,3,2,1,1,1,1,1,1,1])._repr_diagram())\n *******\n *******\n *******\n ***\n ***\n **\n *\n *\n *\n *\n *\n *\n *\n '
return self.ferrers_diagram()
def level(self):
'\n Return the level of ``self``, which is always 1.\n\n This method exists only for compatibility with\n :class:`PartitionTuples`.\n\n EXAMPLES::\n\n sage: Partition([4,3,2]).level()\n 1\n '
return 1
def components(self):
'\n Return a list containing the shape of ``self``.\n\n This method exists only for compatibility with\n :class:`PartitionTuples`.\n\n EXAMPLES::\n\n sage: Partition([3,2]).components()\n [[3, 2]]\n '
return [self]
def _latex_(self):
'\n Return a LaTeX version of ``self``.\n\n For more on the latex options, see :meth:`Partitions.options`.\n\n EXAMPLES::\n\n sage: mu = Partition([2, 1])\n sage: Partitions.options.latex=\'diagram\'; latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\\\\n \\lr{\\ast}&\\lr{\\ast}\\\\\n \\lr{\\ast}\\\\\n \\end{array}$}\n }\n sage: Partitions.options.latex=\'exp_high\'; latex(mu) # indirect doctest\n 2,1\n sage: Partitions.options.latex=\'exp_low\'; latex(mu) # indirect doctest\n 1,2\n sage: Partitions.options.latex=\'list\'; latex(mu) # indirect doctest\n [2, 1]\n sage: Partitions.options.latex=\'young_diagram\'; latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\cline{1-2}\n \\lr{\\phantom{x}}&\\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\end{array}$}\n }\n\n sage: Partitions.options(latex="young_diagram", convention="french")\n sage: Partitions.options.latex=\'exp_high\'; latex(mu) # indirect doctest\n 2,1\n sage: Partitions.options.latex=\'exp_low\'; latex(mu) # indirect doctest\n 1,2\n sage: Partitions.options.latex=\'list\'; latex(mu) # indirect doctest\n [2, 1]\n sage: Partitions.options.latex=\'young_diagram\'; latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{2}c}\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\lr{\\phantom{x}}&\\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\end{array}$}\n }\n\n sage: Partitions.options._reset()\n '
return self.parent().options._dispatch(self, '_latex_', 'latex')
def _latex_young_diagram(self):
'\n LaTeX output as a Young diagram.\n\n EXAMPLES::\n\n sage: print(Partition([2, 1])._latex_young_diagram())\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\cline{1-2}\n \\lr{\\phantom{x}}&\\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\end{array}$}\n }\n sage: print(Partition([])._latex_young_diagram())\n {\\emptyset}\n '
if (not self._list):
return '{\\emptyset}'
from sage.combinat.output import tex_from_array
return tex_from_array([(['\\phantom{x}'] * row_size) for row_size in self._list])
def _latex_diagram(self):
"\n LaTeX output as a Ferrers' diagram.\n\n EXAMPLES::\n\n sage: print(Partition([2, 1])._latex_diagram())\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\\\\n \\lr{\\ast}&\\lr{\\ast}\\\\\n \\lr{\\ast}\\\\\n \\end{array}$}\n }\n sage: print(Partition([])._latex_diagram())\n {\\emptyset}\n "
if (not self._list):
return '{\\emptyset}'
entry = self.parent().options('latex_diagram_str')
from sage.combinat.output import tex_from_array
return tex_from_array([([entry] * row_size) for row_size in self._list], False)
def _latex_list(self):
'\n LaTeX output as a list.\n\n EXAMPLES::\n\n sage: print(Partition([2, 1])._latex_list())\n [2, 1]\n sage: print(Partition([])._latex_list())\n []\n '
return repr(self._list)
def _latex_exp_low(self):
'\n LaTeX output in exponential notation (lowest first).\n\n EXAMPLES::\n\n sage: print(Partition([2,2,1])._latex_exp_low())\n 1,2^{2}\n sage: print(Partition([])._latex_exp_low())\n {\\emptyset}\n '
if (not self._list):
return '{\\emptyset}'
exp = self.to_exp()
return ('%s' % ','.join((('%s%s' % ((m + 1), ('' if (e == 1) else ('^{%s}' % e)))) for (m, e) in enumerate(exp) if (e > 0))))
def _latex_exp_high(self):
'\n LaTeX output in exponential notation (highest first).\n\n EXAMPLES::\n\n sage: print(Partition([2,2,1])._latex_exp_high())\n 2^{2},1\n sage: print(Partition([])._latex_exp_high())\n {\\emptyset}\n '
if (not self._list):
return '{\\emptyset}'
exp = self.to_exp()[::(- 1)]
M = max(self)
return ('%s' % ','.join((('%s%s' % ((M - m), ('' if (e == 1) else ('^{%s}' % e)))) for (m, e) in enumerate(exp) if (e > 0))))
def ferrers_diagram(self):
'\n Return the Ferrers diagram of ``self``.\n\n EXAMPLES::\n\n sage: mu = Partition([5,5,2,1])\n sage: Partitions.options(diagram_str=\'*\', convention="english")\n sage: print(mu.ferrers_diagram())\n *****\n *****\n **\n *\n sage: Partitions.options(diagram_str=\'#\')\n sage: print(mu.ferrers_diagram())\n #####\n #####\n ##\n #\n sage: Partitions.options.convention="french"\n sage: print(mu.ferrers_diagram())\n #\n ##\n #####\n #####\n sage: print(Partition([]).ferrers_diagram())\n -\n sage: Partitions.options(diagram_str=\'-\')\n sage: print(Partition([]).ferrers_diagram())\n (/)\n sage: Partitions.options._reset()\n '
diag_str = self.parent().options.diagram_str
if (not self._list):
return ('-' if (diag_str != '-') else '(/)')
if (self.parent().options.convention == 'English'):
return '\n'.join(((diag_str * p) for p in self))
else:
return '\n'.join(((diag_str * p) for p in reversed(self)))
def pp(self):
"\n Print the Ferrers diagram.\n\n See :meth:`ferrers_diagram` for more on the Ferrers diagram.\n\n EXAMPLES::\n\n sage: Partition([5,5,2,1]).pp()\n *****\n *****\n **\n *\n sage: Partitions.options.convention='French'\n sage: Partition([5,5,2,1]).pp()\n *\n **\n *****\n *****\n sage: Partitions.options._reset()\n "
print(self.ferrers_diagram())
def __truediv__(self, p):
'\n Return the skew partition ``self / p``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2,1])\n sage: p/[1,1]\n [3, 2, 1] / [1, 1]\n sage: p/[3,2,1]\n [3, 2, 1] / [3, 2, 1]\n sage: p/Partition([1,1])\n [3, 2, 1] / [1, 1]\n sage: p/[2,2,2]\n Traceback (most recent call last):\n ...\n ValueError: to form a skew partition p/q, q must be contained in p\n '
if (not self.contains(p)):
raise ValueError('to form a skew partition p/q, q must be contained in p')
return SkewPartition([self[:], p])
def stretch(self, k):
'\n Return the partition obtained by multiplying each part with the\n given number.\n\n EXAMPLES::\n\n sage: p = Partition([4,2,2,1,1])\n sage: p.stretch(3)\n [12, 6, 6, 3, 3]\n '
return _Partitions([(k * p) for p in self])
def power(self, k):
"\n Return the cycle type of the `k`-th power of any permutation\n with cycle type ``self`` (thus describes the powermap of\n symmetric groups).\n\n Equivalent to GAP's ``PowerPartition``.\n\n EXAMPLES::\n\n sage: p = Partition([5,3])\n sage: p.power(1)\n [5, 3]\n sage: p.power(2)\n [5, 3]\n sage: p.power(3)\n [5, 1, 1, 1]\n sage: p.power(4)\n [5, 3]\n\n Now let us compare this to the power map on `S_8`::\n\n sage: # needs sage.groups\n sage: G = SymmetricGroup(8)\n sage: g = G([(1,2,3,4,5),(6,7,8)]); g\n (1,2,3,4,5)(6,7,8)\n sage: g^2\n (1,3,5,2,4)(6,8,7)\n sage: g^3\n (1,4,2,5,3)\n sage: g^4\n (1,5,4,3,2)(6,7,8)\n\n ::\n\n sage: Partition([3,2,1]).power(3)\n [2, 1, 1, 1, 1]\n "
res = []
for i in self:
g = gcd(i, k)
res.extend(([ZZ((i // g))] * int(g)))
res.sort(reverse=True)
return Partition(res)
def __next__(self):
'\n Return the partition that lexicographically follows ``self``, of the\n same size. If ``self`` is the last partition, then return ``False``.\n\n EXAMPLES::\n\n sage: next(Partition([4]))\n [3, 1]\n sage: next(Partition([1,1,1,1]))\n False\n '
p = self
n = 0
m = 0
for i in p:
n += i
m += 1
next_p = (p[:] + ([1] * (n - len(p))))
if (p == ([1] * n)):
return False
h = 0
for i in next_p:
if (i != 1):
h += 1
if (next_p[(h - 1)] == 2):
m += 1
next_p[(h - 1)] = 1
h -= 1
else:
r = (next_p[(h - 1)] - 1)
t = ((m - h) + 1)
next_p[(h - 1)] = r
while (t >= r):
h += 1
next_p[(h - 1)] = r
t -= r
if (t == 0):
m = h
else:
m = (h + 1)
if (t > 1):
h += 1
next_p[(h - 1)] = t
return self.parent()(next_p[:m])
next = __next__
def size(self):
'\n Return the size of ``self``.\n\n EXAMPLES::\n\n sage: Partition([2,2]).size()\n 4\n sage: Partition([3,2,1]).size()\n 6\n '
return sum(self)
def sign(self):
"\n Return the sign of any permutation with cycle type ``self``.\n\n This function corresponds to a homomorphism from the symmetric\n group `S_n` into the cyclic group of order 2, whose kernel\n is exactly the alternating group `A_n`. Partitions of sign\n `1` are called even partitions while partitions of sign\n `-1` are called odd.\n\n EXAMPLES::\n\n sage: Partition([5,3]).sign()\n 1\n sage: Partition([5,2]).sign()\n -1\n\n Zolotarev's lemma states that the Legendre symbol\n `\\left(\\frac{a}{p}\\right)` for an integer\n `a \\pmod p` (`p` a prime number), can be computed\n as sign(p_a), where sign denotes the sign of a permutation and\n p_a the permutation of the residue classes `\\pmod p`\n induced by modular multiplication by `a`, provided\n `p` does not divide `a`.\n\n We verify this in some examples.\n\n ::\n\n sage: F = GF(11) # needs sage.rings.finite_rings\n sage: a = F.multiplicative_generator();a # needs sage.rings.finite_rings\n 2\n sage: plist = [int(a*F(x)) for x in range(1,11)]; plist # needs sage.rings.finite_rings\n [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]\n\n This corresponds to the permutation (1, 2, 4, 8, 5, 10, 9, 7, 3, 6)\n (acting the set `\\{1,2,...,10\\}`) and to the partition\n [10].\n\n ::\n\n sage: p = PermutationGroupElement('(1, 2, 4, 8, 5, 10, 9, 7, 3, 6)') # needs sage.groups\n sage: p.sign() # needs sage.groups\n -1\n sage: Partition([10]).sign()\n -1\n sage: kronecker_symbol(11,2)\n -1\n\n Now replace `2` by `3`::\n\n sage: plist = [int(F(3*x)) for x in range(1,11)]; plist # needs sage.rings.finite_rings\n [3, 6, 9, 1, 4, 7, 10, 2, 5, 8]\n sage: list(range(1, 11))\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: p = PermutationGroupElement('(3,4,8,7,9)') # needs sage.groups\n sage: p.sign() # needs sage.groups\n 1\n sage: kronecker_symbol(3,11)\n 1\n sage: Partition([5,1,1,1,1,1]).sign()\n 1\n\n In both cases, Zolotarev holds.\n\n REFERENCES:\n\n - :wikipedia:`Zolotarev%27s_lemma`\n "
return ((- 1) ** (self.size() - self.length()))
def k_size(self, k):
"\n Given a partition ``self`` and a ``k``, return the size of the\n `k`-boundary.\n\n This is the same as the length method\n :meth:`sage.combinat.core.Core.length` of the\n :class:`sage.combinat.core.Core` object, with the exception that here we\n don't require ``self`` to be a `k+1`-core.\n\n EXAMPLES::\n\n sage: Partition([2, 1, 1]).k_size(1)\n 2\n sage: Partition([2, 1, 1]).k_size(2)\n 3\n sage: Partition([2, 1, 1]).k_size(3)\n 3\n sage: Partition([2, 1, 1]).k_size(4)\n 4\n\n .. SEEALSO::\n\n :meth:`k_boundary`, :meth:`SkewPartition.size`\n "
return self.k_boundary(k).size()
def boundary(self):
"\n Return the integer coordinates of points on the boundary of ``self``.\n\n For the following description, picture the Ferrer's diagram of ``self``\n using the French convention. Recall that the French convention puts\n the longest row on the bottom and the shortest row on the top. In\n addition, interpret the Ferrer's diagram as 1 x 1 cells in the Euclidean\n plane. So if ``self`` was the partition [3, 1], the lower-left vertices\n of the 1 x 1 cells in the Ferrer's diagram would be (0, 0), (1, 0),\n (2, 0), and (0, 1).\n\n The boundary of a partition is the set `\\{ \\text{NE}(d) \\mid \\forall\n d\\:\\text{diagonal} \\}`. That is, for every diagonal line `y = x + b`\n where `b \\in \\mathbb{Z}`, we find the northeasternmost (NE) point on\n that diagonal which is also in the Ferrer's diagram.\n\n The boundary will go from bottom-right to top-left.\n\n EXAMPLES:\n\n Consider the partition (1) depicted as a square on a cartesian plane\n with vertices (0, 0), (1, 0), (1, 1), and (0, 1). Three of those\n vertices in the appropriate order form the boundary::\n\n sage: Partition([1]).boundary()\n [(1, 0), (1, 1), (0, 1)]\n\n The partition (3, 1) can be visualized as three squares on a cartesian\n plane. The coordinates of the appropriate vertices form the boundary::\n\n sage: Partition([3, 1]).boundary()\n [(3, 0), (3, 1), (2, 1), (1, 1), (1, 2), (0, 2)]\n\n TESTS::\n\n sage: Partition([1]).boundary()\n [(1, 0), (1, 1), (0, 1)]\n sage: Partition([2, 1]).boundary()\n [(2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]\n sage: Partition([3, 1]).boundary()\n [(3, 0), (3, 1), (2, 1), (1, 1), (1, 2), (0, 2)]\n sage: Partition([2, 1, 1]).boundary()\n [(2, 0), (2, 1), (1, 1), (1, 2), (1, 3), (0, 3)]\n\n .. SEEALSO::\n\n :meth:`k_rim`. You might have been looking for :meth:`k_boundary`\n instead.\n "
def horizontal_piece(xy, bdy):
(start_x, start_y) = xy
if (not bdy):
h_piece = [(start_x, start_y)]
else:
stop_x = bdy[(- 1)][0]
y = start_y
h_piece = [(x, y) for x in range(start_x, stop_x)]
h_piece = list(reversed(h_piece))
return h_piece
bdy = []
for (i, part) in enumerate(self):
(cell_x, cell_y) = ((part - 1), i)
(x, y) = ((cell_x + 1), (cell_y + 1))
bdy += horizontal_piece((x, (y - 1)), bdy)
bdy.append((x, y))
(top_left_x, top_left_y) = (0, len(self))
bdy += horizontal_piece((top_left_x, top_left_y), bdy)
return bdy
def k_rim(self, k):
'\n Return the ``k``-rim of ``self`` as a list of integer coordinates.\n\n The `k`-rim of a partition is the "line between" (or "intersection of")\n the `k`-boundary and the `k`-interior. (Section 2.3 of [HM2011]_)\n\n It will be output as an ordered list of integer coordinates, where the\n origin is `(0, 0)`. It will start at the top-left of the `k`-rim (using\n French convention) and end at the bottom-right.\n\n EXAMPLES:\n\n Consider the partition (3, 1) split up into its 1-interior and\n 1-boundary:\n\n .. image:: ../../media/k-rim.JPG\n :height: 180px\n :align: center\n\n The line shown in bold is the 1-rim, and that information is equivalent\n to the integer coordinates of the points that occur along that line::\n\n sage: Partition([3, 1]).k_rim(1)\n [(3, 0), (2, 0), (2, 1), (1, 1), (0, 1), (0, 2)]\n\n TESTS::\n\n sage: Partition([1]).k_rim(0)\n [(1, 0), (1, 1), (0, 1)]\n sage: Partition([3, 1]).k_rim(0)\n [(3, 0), (3, 1), (2, 1), (1, 1), (1, 2), (0, 2)]\n sage: Partition([3, 1]).k_rim(1)\n [(3, 0), (2, 0), (2, 1), (1, 1), (0, 1), (0, 2)]\n sage: Partition([3, 1]).k_rim(2)\n [(3, 0), (2, 0), (1, 0), (1, 1), (0, 1), (0, 2)]\n sage: Partition([3, 1]).k_rim(3)\n [(3, 0), (2, 0), (1, 0), (1, 1), (0, 1), (0, 2)]\n\n .. SEEALSO::\n\n :meth:`k_interior`, :meth:`k_boundary`, :meth:`boundary`\n '
interior_rim = self.k_interior(k).boundary()
interior_top_left_y = interior_rim[(- 1)][1]
v_piece = [(0, y) for y in range((interior_top_left_y + 1), (len(self) + 1))]
interior_bottom_right_x = interior_rim[0][0]
if self:
ptn_bottom_right_x = self[0]
else:
ptn_bottom_right_x = 0
h_piece = [(x, 0) for x in range(ptn_bottom_right_x, interior_bottom_right_x, (- 1))]
rim = ((h_piece + interior_rim) + v_piece)
return rim
def k_row_lengths(self, k):
'\n Return the ``k``-row-shape of the partition ``self``.\n\n This is equivalent to taking the `k`-boundary of the partition and then\n returning the row-shape of that. We do *not* discard rows of length 0.\n (Section 2.2 of [LLMS2013]_)\n\n EXAMPLES::\n\n sage: Partition([6, 1]).k_row_lengths(2)\n [2, 1]\n\n sage: Partition([4, 4, 4, 3, 2]).k_row_lengths(2)\n [0, 1, 1, 1, 2]\n\n .. SEEALSO::\n\n :meth:`k_column_lengths`, :meth:`k_boundary`,\n :meth:`SkewPartition.row_lengths`,\n :meth:`SkewPartition.column_lengths`\n '
return self.k_boundary(k).row_lengths()
def k_column_lengths(self, k):
"\n Return the ``k``-column-shape of the partition ``self``.\n\n This is the 'column' analog of :meth:`k_row_lengths`.\n\n EXAMPLES::\n\n sage: Partition([6, 1]).k_column_lengths(2)\n [1, 0, 0, 0, 1, 1]\n\n sage: Partition([4, 4, 4, 3, 2]).k_column_lengths(2)\n [1, 1, 1, 2]\n\n .. SEEALSO::\n\n :meth:`k_row_lengths`, :meth:`k_boundary`,\n :meth:`SkewPartition.row_lengths`,\n :meth:`SkewPartition.column_lengths`\n "
return self.k_boundary(k).column_lengths()
def has_rectangle(self, h, w):
"\n Return ``True`` if the Ferrer's diagram of ``self`` has ``h``\n (*or more*) rows of length ``w`` (*exactly*).\n\n INPUT:\n\n - ``h`` -- An integer `h \\geq 1`. The (*minimum*) height of the\n rectangle.\n\n - ``w`` -- An integer `w \\geq 1`. The width of the rectangle.\n\n EXAMPLES::\n\n sage: Partition([3, 3, 3, 3]).has_rectangle(2, 3)\n True\n sage: Partition([3, 3]).has_rectangle(2, 3)\n True\n sage: Partition([4, 3]).has_rectangle(2, 3)\n False\n sage: Partition([3]).has_rectangle(2, 3)\n False\n\n TESTS::\n\n sage: Partition([1, 1, 1]).has_rectangle(4, 1)\n False\n sage: Partition([1, 1, 1]).has_rectangle(3, 1)\n True\n sage: Partition([1, 1, 1]).has_rectangle(2, 1)\n True\n sage: Partition([1, 1, 1]).has_rectangle(1, 2)\n False\n sage: Partition([3]).has_rectangle(1, 3)\n True\n sage: Partition([3]).has_rectangle(1, 2)\n False\n sage: Partition([3]).has_rectangle(2, 3)\n False\n\n .. SEEALSO::\n\n :meth:`has_k_rectangle`\n "
assert (h >= 1)
assert (w >= 1)
num_rows_of_len_w = self.to_exp(w)[(w - 1)]
return (num_rows_of_len_w >= h)
def has_k_rectangle(self, k):
"\n Return ``True`` if the Ferrer's diagram of ``self`` contains `k-i+1`\n rows (*or more*) of length `i` (*exactly*) for any `i` in `[1, k]`.\n\n This is mainly a helper function for :meth:`is_k_reducible` and\n :meth:`is_k_irreducible`, the only difference between this function and\n :meth:`is_k_reducible` being that this function allows any partition as\n input while :meth:`is_k_reducible` requires the input to be `k`-bounded.\n\n EXAMPLES:\n\n The partition [1, 1, 1] has at least 2 rows of length 1::\n\n sage: Partition([1, 1, 1]).has_k_rectangle(2)\n True\n\n The partition [1, 1, 1] does *not* have 4 rows of length 1, 3 rows of\n length 2, 2 rows of length 3, nor 1 row of length 4::\n\n sage: Partition([1, 1, 1]).has_k_rectangle(4)\n False\n\n TESTS::\n\n sage: Partition([1]).has_k_rectangle(1)\n True\n sage: Partition([1]).has_k_rectangle(2)\n False\n sage: Partition([1, 1, 1]).has_k_rectangle(3)\n True\n sage: Partition([1, 1, 1]).has_k_rectangle(2)\n True\n sage: Partition([1, 1, 1]).has_k_rectangle(4)\n False\n sage: Partition([3]).has_k_rectangle(3)\n True\n sage: Partition([3]).has_k_rectangle(2)\n False\n sage: Partition([3]).has_k_rectangle(4)\n False\n\n .. SEEALSO::\n\n :meth:`is_k_irreducible`, :meth:`is_k_reducible`,\n :meth:`has_rectangle`\n "
return any((self.has_rectangle(a, b) for (a, b) in [(((k - i) + 1), i) for i in range(1, (k + 1))]))
def is_k_bounded(self, k):
'\n Return ``True`` if the partition ``self`` is bounded by ``k``.\n\n EXAMPLES::\n\n sage: Partition([4, 3, 1]).is_k_bounded(4)\n True\n sage: Partition([4, 3, 1]).is_k_bounded(7)\n True\n sage: Partition([4, 3, 1]).is_k_bounded(3)\n False\n '
assert (k >= 0)
if self.is_empty():
return True
else:
return (self[0] <= k)
def is_k_reducible(self, k):
"\n Return ``True`` if the partition ``self`` is ``k``-reducible.\n\n A `k`-bounded partition is `k`-*reducible* if its Ferrer's diagram\n contains `k-i+1` rows (or more) of length `i` (exactly) for some\n `i \\in [1, k]`.\n\n (Also, a `k`-bounded partition is `k`-reducible if and only if it is not `k`-irreducible.)\n\n EXAMPLES:\n\n The partition [1, 1, 1] has at least 2 rows of length 1::\n\n sage: Partition([1, 1, 1]).is_k_reducible(2)\n True\n\n The partition [1, 1, 1] does *not* have 4 rows of length 1, 3 rows of\n length 2, 2 rows of length 3, nor 1 row of length 4::\n\n sage: Partition([1, 1, 1]).is_k_reducible(4)\n False\n\n .. SEEALSO::\n\n :meth:`is_k_irreducible`, :meth:`has_k_rectangle`\n "
if (not self.is_k_bounded(k)):
raise ValueError('we only talk about k-reducible / k-irreducible for k-bounded partitions')
return self.has_k_rectangle(k)
def is_k_irreducible(self, k):
"\n Return ``True`` if the partition ``self`` is ``k``-irreducible.\n\n A `k`-bounded partition is `k`-*irreducible* if its Ferrer's diagram\n does *not* contain `k-i+1` rows (or more) of length `i` (exactly) for\n every `i \\in [1, k]`.\n\n (Also, a `k`-bounded partition is `k`-irreducible if and only if it is\n not `k`-reducible.)\n\n EXAMPLES:\n\n The partition [1, 1, 1] has at least 2 rows of length 1::\n\n sage: Partition([1, 1, 1]).is_k_irreducible(2)\n False\n\n The partition [1, 1, 1] does *not* have 4 rows of length 1, 3 rows of\n length 2, 2 rows of length 3, nor 1 row of length 4::\n\n sage: Partition([1, 1, 1]).is_k_irreducible(4)\n True\n\n .. SEEALSO::\n\n :meth:`is_k_reducible`, :meth:`has_k_rectangle`\n "
return (not self.is_k_reducible(k))
def is_symmetric(self):
'\n Return ``True`` if the partition ``self`` equals its own transpose.\n\n EXAMPLES::\n\n sage: Partition([2, 1]).is_symmetric()\n True\n sage: Partition([3, 1]).is_symmetric()\n False\n '
return (self == self.conjugate())
def next_within_bounds(self, min=[], max=None, partition_type=None):
"\n Get the next partition lexicographically that contains ``min`` and is\n contained in ``max``.\n\n INPUT:\n\n - ``min`` -- (default ``[]``, the empty partition) The\n 'minimum partition' that ``next_within_bounds(self)`` must contain.\n\n - ``max`` -- (default ``None``) The 'maximum partition' that\n ``next_within_bounds(self)`` must be contained in. If set to ``None``,\n then there is no restriction.\n\n - ``partition_type`` -- (default ``None``) The type of partitions\n allowed. For example, 'strict' for strictly decreasing partitions, or\n ``None`` to allow any valid partition.\n\n EXAMPLES::\n\n sage: m = [1, 1]\n sage: M = [3, 2, 1]\n sage: Partition([1, 1]).next_within_bounds(min=m, max=M)\n [1, 1, 1]\n sage: Partition([1, 1, 1]).next_within_bounds(min=m, max=M)\n [2, 1]\n sage: Partition([2, 1]).next_within_bounds(min=m, max=M)\n [2, 1, 1]\n sage: Partition([2, 1, 1]).next_within_bounds(min=m, max=M)\n [2, 2]\n sage: Partition([2, 2]).next_within_bounds(min=m, max=M)\n [2, 2, 1]\n sage: Partition([2, 2, 1]).next_within_bounds(min=m, max=M)\n [3, 1]\n sage: Partition([3, 1]).next_within_bounds(min=m, max=M)\n [3, 1, 1]\n sage: Partition([3, 1, 1]).next_within_bounds(min=m, max=M)\n [3, 2]\n sage: Partition([3, 2]).next_within_bounds(min=m, max=M)\n [3, 2, 1]\n sage: Partition([3, 2, 1]).next_within_bounds(min=m, max=M) == None\n True\n\n .. SEEALSO::\n\n :meth:`next`\n "
if (max is not None):
assert _Partitions(max).contains(_Partitions(self))
assert _Partitions(self).contains(_Partitions(min))
if ((max is not None) and _Partitions(max).is_empty()):
return None
p = list(self)
min = list(min)
if (max is None):
return _Partitions((p + [1]))
p = (p + ([0] * (len(max) - len(p))))
min = (min + ([0] * (len(max) - len(min))))
next_p = copy(p)
def condition(a, b):
if (partition_type in ('strict', 'strictly decreasing')):
return (a < (b - 1))
elif (partition_type in (None, 'weak', 'weakly decreasing')):
return (a < b)
else:
raise ValueError('unrecognized partition type')
for r in range((len(p) - 1), (- 1), (- 1)):
if (r == 0):
if ((max is None) or (p[r] < max[r])):
next_p[r] += 1
break
else:
return None
elif (((max is None) or (p[r] < max[r])) and condition(p[r], p[(r - 1)])):
next_p[r] += 1
break
else:
next_p[r] = min[r]
continue
return _Partitions(next_p)
def row_standard_tableaux(self):
'\n Return the :class:`row standard tableaux\n <sage.combinat.tableau.RowStandardTableaux>` of shape ``self``.\n\n EXAMPLES::\n\n sage: Partition([3,2,2,1]).row_standard_tableaux()\n Row standard tableaux of shape [3, 2, 2, 1]\n '
return tableau.RowStandardTableaux(self)
def standard_tableaux(self):
'\n Return the :class:`standard tableaux<StandardTableaux>`\n of shape ``self``.\n\n EXAMPLES::\n\n sage: Partition([3,2,2,1]).standard_tableaux()\n Standard tableaux of shape [3, 2, 2, 1]\n '
return tableau.StandardTableaux(self)
def up(self):
'\n Return a generator for partitions that can be obtained from ``self``\n by adding a cell.\n\n EXAMPLES::\n\n sage: list(Partition([2,1,1]).up())\n [[3, 1, 1], [2, 2, 1], [2, 1, 1, 1]]\n sage: list(Partition([3,2]).up())\n [[4, 2], [3, 3], [3, 2, 1]]\n sage: [p for p in Partition([]).up()]\n [[1]]\n '
p = self
previous = (p.get_part(0) + 1)
for (i, current) in enumerate(p):
if (current < previous):
(yield Partition(((p[:i] + [(current + 1)]) + p[(i + 1):])))
previous = current
(yield Partition((p + [1])))
def up_list(self):
'\n Return a list of the partitions that can be formed from ``self`` by\n adding a cell.\n\n EXAMPLES::\n\n sage: Partition([2,1,1]).up_list()\n [[3, 1, 1], [2, 2, 1], [2, 1, 1, 1]]\n sage: Partition([3,2]).up_list()\n [[4, 2], [3, 3], [3, 2, 1]]\n sage: Partition([]).up_list()\n [[1]]\n '
return list(self.up())
def down(self):
'\n Return a generator for partitions that can be obtained from ``self``\n by removing a cell.\n\n EXAMPLES::\n\n sage: [p for p in Partition([2,1,1]).down()]\n [[1, 1, 1], [2, 1]]\n sage: [p for p in Partition([3,2]).down()]\n [[2, 2], [3, 1]]\n sage: [p for p in Partition([3,2,1]).down()]\n [[2, 2, 1], [3, 1, 1], [3, 2]]\n\n TESTS:\n\n We check that :trac:`11435` is fixed::\n\n sage: Partition([]).down_list() #indirect doctest\n []\n '
p = self
l = len(p)
for i in range((l - 1)):
if (p[i] > p[(i + 1)]):
(yield Partition(((p[:i] + [(p[i] - 1)]) + p[(i + 1):])))
if (l >= 1):
last = p[(- 1)]
if (last == 1):
(yield Partition(p[:(- 1)]))
else:
(yield Partition((p[:(- 1)] + [(p[(- 1)] - 1)])))
def down_list(self):
'\n Return a list of the partitions that can be obtained from ``self``\n by removing a cell.\n\n EXAMPLES::\n\n sage: Partition([2,1,1]).down_list()\n [[1, 1, 1], [2, 1]]\n sage: Partition([3,2]).down_list()\n [[2, 2], [3, 1]]\n sage: Partition([3,2,1]).down_list()\n [[2, 2, 1], [3, 1, 1], [3, 2]]\n sage: Partition([]).down_list() #checks :trac:`11435`\n []\n '
return [p for p in self.down()]
@combinatorial_map(name='cell poset')
def cell_poset(self, orientation='SE'):
'\n Return the Young diagram of ``self`` as a poset. The optional\n keyword variable ``orientation`` determines the order relation\n of the poset.\n\n The poset always uses the set of cells of the Young diagram\n of ``self`` as its ground set. The order relation of the poset\n depends on the ``orientation`` variable (which defaults to\n ``"SE"``). Concretely, ``orientation`` has to be specified to\n one of the strings ``"NW"``, ``"NE"``, ``"SW"``, and ``"SE"``,\n standing for "northwest", "northeast", "southwest" and\n "southeast", respectively. If ``orientation`` is ``"SE"``, then\n the order relation of the poset is such that a cell `u` is\n greater or equal to a cell `v` in the poset if and only if `u`\n lies weakly southeast of `v` (this means that `u` can be\n reached from `v` by a sequence of south and east steps; the\n sequence is allowed to consist of south steps only, or of east\n steps only, or even be empty). Similarly the order relation is\n defined for the other three orientations. The Young diagram is\n supposed to be drawn in English notation.\n\n The elements of the poset are the cells of the Young diagram\n of ``self``, written as tuples of zero-based coordinates (so\n that `(3, 7)` stands for the `8`-th cell of the `4`-th row,\n etc.).\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: p = Partition([3,3,1])\n sage: Q = p.cell_poset(); Q\n Finite poset containing 7 elements\n sage: sorted(Q)\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]\n sage: sorted(Q.maximal_elements())\n [(1, 2), (2, 0)]\n sage: Q.minimal_elements()\n [(0, 0)]\n sage: sorted(Q.upper_covers((1, 0)))\n [(1, 1), (2, 0)]\n sage: Q.upper_covers((1, 1))\n [(1, 2)]\n\n sage: # needs sage.graphs\n sage: P = p.cell_poset(orientation="NW"); P\n Finite poset containing 7 elements\n sage: sorted(P)\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]\n sage: sorted(P.minimal_elements())\n [(1, 2), (2, 0)]\n sage: P.maximal_elements()\n [(0, 0)]\n sage: P.upper_covers((2, 0))\n [(1, 0)]\n sage: sorted(P.upper_covers((1, 2)))\n [(0, 2), (1, 1)]\n sage: sorted(P.upper_covers((1, 1)))\n [(0, 1), (1, 0)]\n sage: sorted([len(P.upper_covers(v)) for v in P])\n [0, 1, 1, 1, 1, 2, 2]\n\n sage: # needs sage.graphs\n sage: R = p.cell_poset(orientation="NE"); R\n Finite poset containing 7 elements\n sage: sorted(R)\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]\n sage: R.maximal_elements()\n [(0, 2)]\n sage: R.minimal_elements()\n [(2, 0)]\n sage: sorted([len(R.upper_covers(v)) for v in R])\n [0, 1, 1, 1, 1, 2, 2]\n sage: R.is_isomorphic(P)\n False\n sage: R.is_isomorphic(P.dual())\n False\n\n Linear extensions of ``p.cell_poset()`` are in 1-to-1 correspondence\n with standard Young tableaux of shape `p`::\n\n sage: all( len(p.cell_poset().linear_extensions()) # needs sage.graphs\n ....: == len(p.standard_tableaux())\n ....: for n in range(8) for p in Partitions(n) )\n True\n\n This is not the case for northeast orientation::\n\n sage: q = Partition([3, 1])\n sage: q.cell_poset(orientation="NE").is_chain() # needs sage.graphs\n True\n\n TESTS:\n\n We check that the posets are really what they should be for size\n up to `7`::\n\n sage: def check_NW(n):\n ....: for p in Partitions(n):\n ....: P = p.cell_poset(orientation="NW")\n ....: for c in p.cells():\n ....: for d in p.cells():\n ....: if P.le(c, d) != (c[0] >= d[0]\n ....: and c[1] >= d[1]):\n ....: return False\n ....: return True\n sage: all( check_NW(n) for n in range(8) ) # needs sage.graphs\n True\n\n sage: def check_NE(n):\n ....: for p in Partitions(n):\n ....: P = p.cell_poset(orientation="NE")\n ....: for c in p.cells():\n ....: for d in p.cells():\n ....: if P.le(c, d) != (c[0] >= d[0]\n ....: and c[1] <= d[1]):\n ....: return False\n ....: return True\n sage: all( check_NE(n) for n in range(8) ) # needs sage.graphs\n True\n\n sage: def test_duality(n, ori1, ori2):\n ....: for p in Partitions(n):\n ....: P = p.cell_poset(orientation=ori1)\n ....: Q = p.cell_poset(orientation=ori2)\n ....: for c in p.cells():\n ....: for d in p.cells():\n ....: if P.lt(c, d) != Q.lt(d, c):\n ....: return False\n ....: return True\n sage: all( test_duality(n, "NW", "SE") for n in range(8) ) # needs sage.graphs\n True\n sage: all( test_duality(n, "NE", "SW") for n in range(8) ) # needs sage.graphs\n True\n sage: all( test_duality(n, "NE", "SE") for n in range(4) ) # needs sage.graphs\n False\n '
from sage.combinat.posets.posets import Poset
covers = {}
if (orientation == 'NW'):
for (i, row) in enumerate(self):
if (i == 0):
covers[(0, 0)] = []
for j in range(1, row):
covers[(0, j)] = [(0, (j - 1))]
else:
covers[(i, 0)] = [((i - 1), 0)]
for j in range(1, row):
covers[(i, j)] = [((i - 1), j), (i, (j - 1))]
elif (orientation == 'NE'):
for (i, row) in enumerate(self):
if (i == 0):
covers[(0, (row - 1))] = []
for j in range((row - 1)):
covers[(0, j)] = [(0, (j + 1))]
else:
covers[(i, (row - 1))] = [((i - 1), (row - 1))]
for j in range((row - 1)):
covers[(i, j)] = [((i - 1), j), (i, (j + 1))]
elif (orientation == 'SE'):
l = (len(self) - 1)
for (i, row) in enumerate(self):
if (i == l):
covers[(i, (row - 1))] = []
for j in range((row - 1)):
covers[(i, j)] = [(i, (j + 1))]
else:
next_row = self[(i + 1)]
if (row == next_row):
covers[(i, (row - 1))] = [((i + 1), (row - 1))]
for j in range((row - 1)):
covers[(i, j)] = [((i + 1), j), (i, (j + 1))]
else:
covers[(i, (row - 1))] = []
for j in range(next_row):
covers[(i, j)] = [((i + 1), j), (i, (j + 1))]
for j in range(next_row, (row - 1)):
covers[(i, j)] = [(i, (j + 1))]
elif (orientation == 'SW'):
l = (len(self) - 1)
for (i, row) in enumerate(self):
if (i == l):
covers[(i, 0)] = []
for j in range(1, row):
covers[(i, j)] = [(i, (j - 1))]
else:
covers[(i, 0)] = [((i + 1), 0)]
next_row = self[(i + 1)]
for j in range(1, next_row):
covers[(i, j)] = [((i + 1), j), (i, (j - 1))]
for j in range(next_row, row):
covers[(i, j)] = [(i, (j - 1))]
return Poset(covers)
def frobenius_coordinates(self):
'\n Return a pair of sequences of Frobenius coordinates aka beta numbers\n of the partition.\n\n These are two strictly decreasing sequences of nonnegative integers\n of the same length.\n\n EXAMPLES::\n\n sage: Partition([]).frobenius_coordinates()\n ([], [])\n sage: Partition([1]).frobenius_coordinates()\n ([0], [0])\n sage: Partition([3,3,3]).frobenius_coordinates()\n ([2, 1, 0], [2, 1, 0])\n sage: Partition([9,1,1,1,1,1,1]).frobenius_coordinates()\n ([8], [6])\n\n '
mu = self
muconj = mu.conjugate()
if (len(mu) <= len(muconj)):
a = [x for x in (((val - i) - 1) for (i, val) in enumerate(mu)) if (x >= 0)]
b = [x for x in (((muconj[i] - i) - 1) for i in range(len(a))) if (x >= 0)]
else:
b = [x for x in (((val - i) - 1) for (i, val) in enumerate(muconj)) if (x >= 0)]
a = [x for x in (((mu[i] - i) - 1) for i in range(len(b))) if (x >= 0)]
return (a, b)
def frobenius_rank(self):
'\n Return the Frobenius rank of the partition ``self``.\n\n The Frobenius rank of a partition\n `\\lambda = (\\lambda_1, \\lambda_2, \\lambda_3, \\cdots)` is\n defined to be the largest `i` such that `\\lambda_i \\geq i`.\n In other words, it is the number of cells on the main diagonal\n of `\\lambda`. In yet other words, it is the size of the largest\n square fitting into the Young diagram of `\\lambda`.\n\n EXAMPLES::\n\n sage: Partition([]).frobenius_rank()\n 0\n sage: Partition([1]).frobenius_rank()\n 1\n sage: Partition([3,3,3]).frobenius_rank()\n 3\n sage: Partition([9,1,1,1,1,1]).frobenius_rank()\n 1\n sage: Partition([2,1,1,1,1,1]).frobenius_rank()\n 1\n sage: Partition([2,2,1,1,1,1]).frobenius_rank()\n 2\n sage: Partition([3,2]).frobenius_rank()\n 2\n sage: Partition([3,2,2]).frobenius_rank()\n 2\n sage: Partition([8,4,4,4,4]).frobenius_rank()\n 4\n sage: Partition([8,4,1]).frobenius_rank()\n 2\n sage: Partition([3,3,1]).frobenius_rank()\n 2\n '
for (i, x) in enumerate(self):
if (x <= i):
return i
return len(self)
def beta_numbers(self, length=None):
'\n Return the set of beta numbers corresponding to ``self``.\n\n The optional argument ``length`` specifies the length of the beta set\n (which must be at least the length of ``self``).\n\n For more on beta numbers, see :meth:`frobenius_coordinates`.\n\n EXAMPLES::\n\n sage: Partition([4,3,2]).beta_numbers()\n [6, 4, 2]\n sage: Partition([4,3,2]).beta_numbers(5)\n [8, 6, 4, 1, 0]\n sage: Partition([]).beta_numbers()\n []\n sage: Partition([]).beta_numbers(3)\n [2, 1, 0]\n sage: Partition([6,4,1,1]).beta_numbers()\n [9, 6, 2, 1]\n sage: Partition([6,4,1,1]).beta_numbers(6)\n [11, 8, 4, 3, 1, 0]\n sage: Partition([1,1,1]).beta_numbers()\n [3, 2, 1]\n sage: Partition([1,1,1]).beta_numbers(4)\n [4, 3, 2, 0]\n '
true_length = len(self)
if (length is None):
length = true_length
elif (length < true_length):
raise ValueError('length must be at least the length of the partition')
beta = [(((l + length) - i) - 1) for (i, l) in enumerate(self)]
if (length > true_length):
beta.extend(list(range(((length - true_length) - 1), (- 1), (- 1))))
return beta
def crank(self):
'\n Return the Dyson crank of ``self``.\n\n The Dyson crank of a partition `\\lambda` is defined as follows:\n If `\\lambda` contains at least one `1`, then the crank is\n `\\mu(\\lambda) - \\omega(\\lambda)`, where `\\omega(\\lambda)` is the\n number of `1`s in `\\lambda`, and `\\mu(\\lambda)` is the number of\n parts of `\\lambda` larger than `\\omega(\\lambda)`. If `\\lambda`\n contains no `1`, then the crank is simply the largest part of\n `\\lambda`.\n\n REFERENCES:\n\n - [AG1988]_\n\n EXAMPLES::\n\n sage: Partition([]).crank()\n 0\n sage: Partition([3,2,2]).crank()\n 3\n sage: Partition([5,4,2,1,1]).crank()\n 0\n sage: Partition([1,1,1]).crank()\n -3\n sage: Partition([6,4,4,3]).crank()\n 6\n sage: Partition([6,3,3,1,1]).crank()\n 1\n sage: Partition([6]).crank()\n 6\n sage: Partition([5,1]).crank()\n 0\n sage: Partition([4,2]).crank()\n 4\n sage: Partition([4,1,1]).crank()\n -1\n sage: Partition([3,3]).crank()\n 3\n sage: Partition([3,2,1]).crank()\n 1\n sage: Partition([3,1,1,1]).crank()\n -3\n sage: Partition([2,2,2]).crank()\n 2\n sage: Partition([2,2,1,1]).crank()\n -2\n sage: Partition([2,1,1,1,1]).crank()\n -4\n sage: Partition([1,1,1,1,1,1]).crank()\n -6\n '
l = len(self)
if (l == 0):
return 0
if (self[(- 1)] > 1):
return self[0]
ind_1 = self.index(1)
w = (l - ind_1)
m = len([x for x in self if (x > w)])
return (m - w)
def t_completion(self, t):
'\n Return the ``t``-completion of the partition ``self``.\n\n If `\\lambda = (\\lambda_1, \\lambda_2, \\lambda_3, \\ldots)` is a\n partition and `t` is an integer greater or equal to\n `\\left\\lvert \\lambda \\right\\rvert + \\lambda_1`, then the\n `t`-*completion of* `\\lambda` is defined as the partition\n `(t - \\left\\lvert \\lambda \\right\\rvert, \\lambda_1, \\lambda_2,\n \\lambda_3, \\ldots)` of `t`. This partition is denoted by `\\lambda[t]`\n in [BOR2009]_, by `\\lambda_{[t]}` in [BdVO2012]_, and by `\\lambda(t)`\n in [CO2010]_.\n\n EXAMPLES::\n\n sage: Partition([]).t_completion(0)\n []\n sage: Partition([]).t_completion(1)\n [1]\n sage: Partition([]).t_completion(2)\n [2]\n sage: Partition([]).t_completion(3)\n [3]\n sage: Partition([2, 1]).t_completion(5)\n [2, 2, 1]\n sage: Partition([2, 1]).t_completion(6)\n [3, 2, 1]\n sage: Partition([4, 2, 2, 1]).t_completion(13)\n [4, 4, 2, 2, 1]\n sage: Partition([4, 2, 2, 1]).t_completion(19)\n [10, 4, 2, 2, 1]\n sage: Partition([4, 2, 2, 1]).t_completion(10)\n Traceback (most recent call last):\n ...\n ValueError: 10-completion is not defined\n sage: Partition([4, 2, 2, 1]).t_completion(5)\n Traceback (most recent call last):\n ...\n ValueError: 5-completion is not defined\n '
if (self._list and (t < (self.size() + self._list[0]))):
raise ValueError(f'{t}-completion is not defined')
return Partition(([(t - self.size())] + self._list))
def larger_lex(self, rhs):
'\n Return ``True`` if ``self`` is larger than ``rhs`` in lexicographic\n order. Otherwise return ``False``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2])\n sage: p.larger_lex([3,1])\n True\n sage: p.larger_lex([1,4])\n True\n sage: p.larger_lex([3,2,1])\n False\n sage: p.larger_lex([3])\n True\n sage: p.larger_lex([5])\n False\n sage: p.larger_lex([3,1,1,1,1,1,1,1])\n True\n '
return CombinatorialElement.__gt__(self, rhs)
def dominates(self, p2):
'\n Return ``True`` if ``self`` dominates the partition ``p2``. Otherwise\n it returns ``False``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2])\n sage: p.dominates([3,1])\n True\n sage: p.dominates([2,2])\n True\n sage: p.dominates([2,1,1])\n True\n sage: p.dominates([3,3])\n False\n sage: p.dominates([4])\n False\n sage: Partition([4]).dominates(p)\n False\n sage: Partition([]).dominates([1])\n False\n sage: Partition([]).dominates([])\n True\n sage: Partition([1]).dominates([])\n True\n '
p1 = self
sum1 = 0
sum2 = 0
min_length = min(len(p1), len(p2))
if (min_length == 0):
return (not p2)
for i in range(min_length):
sum1 += p1[i]
sum2 += p2[i]
if (sum2 > sum1):
return False
return (sum(p1) >= sum(p2))
def cells(self):
'\n Return the coordinates of the cells of ``self``.\n\n EXAMPLES::\n\n sage: Partition([2,2]).cells()\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n sage: Partition([3,2]).cells()\n [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]\n '
res = []
for i in range(len(self)):
for j in range(self[i]):
res.append((i, j))
return res
def generalized_pochhammer_symbol(self, a, alpha):
'\n Return the generalized Pochhammer symbol\n `(a)_{self}^{(\\alpha)}`. This is the product over all\n cells `(i,j)` in ``self`` of `a - (i-1) / \\alpha + j - 1`.\n\n EXAMPLES::\n\n sage: Partition([2,2]).generalized_pochhammer_symbol(2,1)\n 12\n '
res = 1
for (i, j) in self.cells():
res *= (((a - ((i - 1) / alpha)) + j) - 1)
return res
def get_part(self, i, default=Integer(0)):
'\n Return the `i^{th}` part of ``self``, or ``default`` if it does\n not exist.\n\n EXAMPLES::\n\n sage: p = Partition([2,1])\n sage: p.get_part(0), p.get_part(1), p.get_part(2)\n (2, 1, 0)\n sage: p.get_part(10,-1)\n -1\n sage: Partition([]).get_part(0)\n 0\n '
if (i < len(self._list)):
return self._list[i]
else:
return default
@combinatorial_map(name='partition to minimal Dyck word')
def to_dyck_word(self, n=None):
'\n Return the ``n``-Dyck word whose corresponding partition is\n ``self`` (or, if ``n`` is not specified, the `n`-Dyck word with\n smallest `n` to satisfy this property).\n\n If `w` is an `n`-Dyck word (that is, a Dyck word with `n` open\n symbols and `n` close symbols), then the Dyck path corresponding\n to `w` can be regarded as a lattice path in the northeastern\n half of an `n \\times n`-square. The region to the northeast of\n this Dyck path can be regarded as a partition. It is called the\n partition corresponding to the Dyck word `w`. (See\n :meth:`~sage.combinat.dyck_word.DyckWord.to_partition`.)\n\n For every partition `\\lambda` and every nonnegative integer `n`,\n there exists at most one `n`-Dyck word `w` such that the\n partition corresponding to `w` is `\\lambda` (in fact, such `w`\n exists if and only if `\\lambda_i + i \\leq n` for every `i`,\n where `\\lambda` is written in the form\n `(\\lambda_1, \\lambda_2, \\ldots, \\lambda_k)` with `\\lambda_k > 0`).\n This method computes this `w` for a given `\\lambda` and `n`.\n If `n` is not specified, this method computes the `w` for the\n smallest possible `n` for which such an `w` exists.\n (The minimality of `n` means that the partition demarcated by the\n Dyck path touches the diagonal.)\n\n EXAMPLES::\n\n sage: Partition([2,2]).to_dyck_word()\n [1, 1, 0, 0, 1, 1, 0, 0]\n sage: Partition([2,2]).to_dyck_word(4)\n [1, 1, 0, 0, 1, 1, 0, 0]\n sage: Partition([2,2]).to_dyck_word(5)\n [1, 1, 1, 0, 0, 1, 1, 0, 0, 0]\n sage: Partition([6,3,1]).to_dyck_word()\n [1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]\n sage: Partition([]).to_dyck_word()\n []\n sage: Partition([]).to_dyck_word(3)\n [1, 1, 1, 0, 0, 0]\n\n The partition corresponding to ``self.dyck_word()`` is ``self``\n indeed::\n\n sage: all( p.to_dyck_word().to_partition() == p\n ....: for p in Partitions(5) )\n True\n '
from sage.combinat.dyck_word import DyckWord
if (not self._list):
if (n is None):
return DyckWord([])
return DyckWord((([1] * n) + ([0] * n)))
list_of_word = []
if (n is None):
n = max((((i + l) + 1) for (i, l) in enumerate(self)))
list_of_word.extend(([1] * (n - self.length())))
copy_part = list(self)
while copy_part:
c = copy_part.pop()
list_of_word.extend(([0] * c))
for i in range(len(copy_part)):
copy_part[i] -= c
list_of_word.append(1)
list_of_word.extend(([0] * (n - self[0])))
return DyckWord(list_of_word)
@combinatorial_map(order=2, name='conjugate partition')
def conjugate(self):
'\n Return the conjugate partition of the partition ``self``. This\n is also called the associated partition or the transpose in the\n literature.\n\n EXAMPLES::\n\n sage: Partition([2,2]).conjugate()\n [2, 2]\n sage: Partition([6,3,1]).conjugate()\n [3, 2, 2, 1, 1, 1]\n\n The conjugate partition is obtained by transposing the Ferrers\n diagram of the partition (see :meth:`.ferrers_diagram`)::\n\n sage: print(Partition([6,3,1]).ferrers_diagram())\n ******\n ***\n *\n sage: print(Partition([6,3,1]).conjugate().ferrers_diagram())\n ***\n **\n **\n *\n *\n *\n '
if (not self):
par = Partitions_n(0)
return par.element_class(par, [])
par = Partitions_n(sum(self))
return par.element_class(par, conjugate(self))
def suter_diagonal_slide(self, n, exp=1):
"\n Return the image of ``self`` in `Y_n` under Suter's diagonal slide\n `\\sigma_n`, where the notations used are those defined in [Sut2002]_.\n\n The set `Y_n` is defined as the set of all partitions\n `\\lambda` such that the hook length of the `(0, 0)`-cell (i.e. the\n northwestern most cell in English notation) of `\\lambda` is less\n than `n`, including the empty partition.\n\n The map `\\sigma_n` sends a partition (with non-zero entries)\n `(\\lambda_1, \\lambda_2, \\ldots, \\lambda_m) \\in Y_n` to the partition\n `(\\lambda_2 + 1, \\lambda_3 + 1, \\ldots, \\lambda_m + 1,\n \\underbrace{1, 1, \\ldots, 1}_{n - m - \\lambda_1\\text{ ones}})`.\n In other words, it pads the partition with trailing zeroes\n until it has length `n - \\lambda_1`, then removes its first\n part, and finally adds `1` to each part.\n\n By Theorem 2.1 of [Sut2002]_, the dihedral group `D_n` with\n `2n` elements acts on `Y_n` by letting the primitive rotation\n act as `\\sigma_n` and the reflection act as conjugation of\n partitions (:meth:`conjugate()`). This action is faithful if\n `n \\geq 3`.\n\n INPUT:\n\n - ``n`` -- nonnegative integer\n\n - ``exp`` -- (default: 1) how many times `\\sigma_n` should be applied\n\n OUTPUT:\n\n The result of applying Suter's diagonal slide `\\sigma_n` to\n ``self``, assuming that ``self`` lies in `Y_n`. If the\n optional argument ``exp`` is set, then the slide\n `\\sigma_n` is applied not just once, but ``exp`` times\n (note that ``exp`` is allowed to be negative, since\n the slide has finite order).\n\n EXAMPLES::\n\n sage: Partition([5,4,1]).suter_diagonal_slide(8)\n [5, 2]\n sage: Partition([5,4,1]).suter_diagonal_slide(9)\n [5, 2, 1]\n sage: Partition([]).suter_diagonal_slide(7)\n [1, 1, 1, 1, 1, 1]\n sage: Partition([]).suter_diagonal_slide(1)\n []\n sage: Partition([]).suter_diagonal_slide(7, exp=-1)\n [6]\n sage: Partition([]).suter_diagonal_slide(1, exp=-1)\n []\n sage: P7 = Partitions(7)\n sage: all( p == p.suter_diagonal_slide(9, exp=-1).suter_diagonal_slide(9)\n ....: for p in P7 )\n True\n sage: all( p == p.suter_diagonal_slide(9, exp=3)\n ....: .suter_diagonal_slide(9, exp=3)\n ....: .suter_diagonal_slide(9, exp=3)\n ....: for p in P7 )\n True\n sage: all( p == p.suter_diagonal_slide(9, exp=6)\n ....: .suter_diagonal_slide(9, exp=6)\n ....: .suter_diagonal_slide(9, exp=6)\n ....: for p in P7 )\n True\n sage: all( p == p.suter_diagonal_slide(9, exp=-1)\n ....: .suter_diagonal_slide(9, exp=1)\n ....: for p in P7 )\n True\n\n Check of the assertion in [Sut2002]_ that `\\sigma_n\\bigl( \\sigma_n(\n \\lambda^{\\prime})^{\\prime} \\bigr) = \\lambda`::\n\n sage: all( p.suter_diagonal_slide(8).conjugate()\n ....: == p.conjugate().suter_diagonal_slide(8, exp=-1)\n ....: for p in P7 )\n True\n\n Check of Claim 1 in [Sut2002]_::\n\n sage: P5 = Partitions(5)\n sage: all( all( (p.suter_diagonal_slide(6) in q.suter_diagonal_slide(6).down())\n ....: or (q.suter_diagonal_slide(6) in p.suter_diagonal_slide(6).down())\n ....: for p in q.down() )\n ....: for q in P5 )\n True\n\n TESTS:\n\n Check for ``exp = 0``::\n\n sage: P = Partitions(4)\n sage: all(p == p.suter_diagonal_slide(7, 0) for p in P)\n True\n\n Check for invalid input::\n\n sage: p = Partition([2,1])\n sage: p.hook_length(0, 0)\n 3\n sage: p.suter_diagonal_slide(2)\n Traceback (most recent call last):\n ...\n ValueError: the hook length must be less than n\n "
if ((len(self) > 0) and ((len(self) + self._list[0]) > n)):
raise ValueError('the hook length must be less than n')
ret = self
exp = (exp % n)
if (exp > (n / 2)):
exp -= n
while (exp != 0):
leng = len(ret)
if (exp > 0):
if (leng == 0):
ret = Partition(([1] * (n - 1)))
exp -= 1
continue
res = [(i + 1) for i in ret._list[1:]]
res += ([1] * ((n - leng) - ret._list[0]))
ret = Partition(res)
exp -= 1
else:
if (leng == 0):
ret = Partition([(n - 1)])
exp += 1
continue
res = [((n - leng) - 1)]
res.extend([(i - 1) for i in ret._list if (i > 1)])
ret = Partition(res)
exp += 1
return ret
@combinatorial_map(name='reading tableau')
def reading_tableau(self):
'\n Return the RSK recording tableau of the reading word of the\n (standard) tableau `T` labeled down (in English convention)\n each column to the shape of ``self``.\n\n For an example of the tableau `T`, consider the partition\n `\\lambda = (3,2,1)`, then we have::\n\n 1 4 6\n 2 5\n 3\n\n For more, see :func:`~sage.combinat.rsk.RSK()`.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).reading_tableau()\n [[1, 3, 6], [2, 5], [4]]\n '
st = tableau.StandardTableaux(self).first()
return st.reading_word_permutation().right_tableau()
@combinatorial_map(name='initial tableau')
def initial_tableau(self):
'\n Return the :class:`standard tableau<StandardTableau>` which has the\n numbers `1, 2, \\ldots, n` where `n` is the :meth:`size` of ``self``\n entered in order from left to right along the rows of each component,\n where the components are ordered from left to right.\n\n EXAMPLES::\n\n sage: Partition([3,2,2]).initial_tableau()\n [[1, 2, 3], [4, 5], [6, 7]]\n '
sigma = list(accumulate(([1] + self._list)))
tab = [list(range(sigma[i], sigma[(i + 1)])) for i in range((len(sigma) - 1))]
return tableau.StandardTableau(tab)
def initial_column_tableau(self):
'\n Return the initial column tableau of shape ``self``.\n\n The initial column tableau of shape self is the standard tableau\n that has the numbers `1` to `n`, where `n` is the :meth:`size` of ``self``,\n entered in order from top to bottom and then left to right down the\n columns of ``self``.\n\n EXAMPLES::\n\n sage: Partition([3,2]).initial_column_tableau()\n [[1, 3, 5], [2, 4]]\n '
return self.conjugate().initial_tableau().conjugate()
def garnir_tableau(self, *cell):
'\n Return the Garnir tableau of shape ``self`` corresponding to the cell\n ``cell``. If ``cell`` `= (a,c)` then `(a+1,c)` must belong to the\n diagram of ``self``.\n\n The Garnir tableaux play an important role in integral and\n non-semisimple representation theory because they determine the\n "straightening" rules for the Specht modules over an arbitrary ring.\n\n The Garnir tableaux are the "first" non-standard tableaux which arise\n when you act by simple transpositions. If `(a,c)` is a cell in the\n Young diagram of a partition, which is not at the bottom of its\n column, then the corresponding Garnir tableau has the integers\n `1, 2, \\ldots, n` entered in order from left to right along the rows\n of the diagram up to the cell `(a,c-1)`, then along the cells\n `(a+1,1)` to `(a+1,c)`, then `(a,c)` until the end of row `a` and\n then continuing from left to right in the remaining positions. The\n examples below probably make this clearer!\n\n .. NOTE::\n\n The function also sets ``g._garnir_cell``, where ``g`` is the\n resulting Garnir tableau, equal to ``cell`` which is used by\n some other functions.\n\n EXAMPLES::\n\n sage: g = Partition([5,3,3,2]).garnir_tableau((0,2)); g.pp()\n 1 2 6 7 8\n 3 4 5\n 9 10 11\n 12 13\n sage: g.is_row_strict(); g.is_column_strict()\n True\n False\n\n sage: Partition([5,3,3,2]).garnir_tableau(0,2).pp()\n 1 2 6 7 8\n 3 4 5\n 9 10 11\n 12 13\n sage: Partition([5,3,3,2]).garnir_tableau(2,1).pp()\n 1 2 3 4 5\n 6 7 8\n 9 12 13\n 10 11\n sage: Partition([5,3,3,2]).garnir_tableau(2,2).pp()\n Traceback (most recent call last):\n ...\n ValueError: (row+1, col) must be inside the diagram\n\n .. SEEALSO::\n\n - :meth:`top_garnir_tableau`\n '
try:
(row, col) = cell
except ValueError:
(row, col) = cell[0]
if (((row + 1) >= len(self)) or (col >= self[(row + 1)])):
raise ValueError('(row+1, col) must be inside the diagram')
g = self.initial_tableau().to_list()
a = g[row][col]
g[row][col:] = list(range(((a + col) + 1), (g[(row + 1)][col] + 1)))
g[(row + 1)][:(col + 1)] = list(range(a, ((a + col) + 1)))
g = tableau.Tableau(g)
g._garnir_cell = (row, col)
return g
def top_garnir_tableau(self, e, cell):
'\n Return the most dominant *standard* tableau which dominates the\n corresponding Garnir tableau and has the same ``e``-residue.\n\n The Garnir tableau play an important role in integral and non-semisimple\n representation theory because they determine the "straightening" rules\n for the Specht modules. The *top Garnir tableaux* arise in the graded\n representation theory of the symmetric groups and higher level Hecke\n algebras. They were introduced in [KMR2012]_.\n\n If the Garnir node is ``cell=(r,c)`` and `m` and `M` are the entries\n in the cells ``(r,c)`` and ``(r+1,c)``, respectively, in the initial\n tableau then the top ``e``-Garnir tableau is obtained by inserting the\n numbers `m, m+1, \\ldots, M` in order from left to right first in the\n cells in row ``r+1`` which are not in the ``e``-Garnir belt, then in\n the cell in rows ``r`` and ``r+1`` which are in the Garnir belt and\n then, finally, in the remaining cells in row ``r`` which are not in\n the Garnir belt. All other entries in the tableau remain unchanged.\n\n If ``e = 0``, or if there are no ``e``-bricks in either row ``r``\n or ``r+1``, then the top Garnir tableau is the corresponding Garnir\n tableau.\n\n EXAMPLES::\n\n sage: Partition([5,4,3,2]).top_garnir_tableau(2,(0,2)).pp()\n 1 2 4 5 8\n 3 6 7 9\n 10 11 12\n 13 14\n sage: Partition([5,4,3,2]).top_garnir_tableau(3,(0,2)).pp()\n 1 2 3 4 5\n 6 7 8 9\n 10 11 12\n 13 14\n sage: Partition([5,4,3,2]).top_garnir_tableau(4,(0,2)).pp()\n 1 2 6 7 8\n 3 4 5 9\n 10 11 12\n 13 14\n sage: Partition([5,4,3,2]).top_garnir_tableau(0,(0,2)).pp()\n 1 2 6 7 8\n 3 4 5 9\n 10 11 12\n 13 14\n\n TESTS::\n\n sage: Partition([5,4,3,2]).top_garnir_tableau(0,(3,2)).pp()\n Traceback (most recent call last):\n ...\n ValueError: (4,2)=(row+1,col) must be inside the diagram\n\n REFERENCES:\n\n - [KMR2012]_\n '
(row, col) = cell
if (((row + 1) >= len(self)) or (col >= self[(row + 1)])):
raise ValueError(('(%s,%s)=(row+1,col) must be inside the diagram' % ((row + 1), col)))
g = self.garnir_tableau(cell)
if (e == 0):
return g
a = (e * int(((self[row] - col) / e)))
b = (e * int(((col + 1) / e)))
if ((a == 0) or (b == 0)):
return g
t = g.to_list()
m = g[(row + 1)][0]
t[row][col:(a + col)] = [((((m + col) - b) + 1) + i) for i in range(a)]
t[(row + 1)][((col - b) + 1):(col + 1)] = [(((((m + a) + col) - b) + 1) + i) for i in range(b)]
return tableau.StandardTableau(t)
@cached_method
def young_subgroup(self):
'\n Return the corresponding Young, or parabolic, subgroup of the symmetric\n group.\n\n The Young subgroup of a partition\n `\\lambda = (\\lambda_1, \\lambda_2, \\ldots, \\lambda_{\\ell})` of `n` is\n the group:\n\n .. MATH::\n\n S_{\\lambda_1} \\times S_{\\lambda_2} \\times \\cdots \\times\n S_{\\lambda_{\\ell}}\n\n embedded into `S_n` in the standard way (i.e.,\n the `S_{\\lambda_i}` factor acts on the numbers from\n `\\lambda_1 + \\lambda_2 + \\cdots + \\lambda_{i-1} + 1` to\n `\\lambda_1 + \\lambda_2 + \\cdots + \\lambda_i`).\n\n EXAMPLES::\n\n sage: Partition([4,2]).young_subgroup() # needs sage.groups\n Permutation Group with generators [(), (5,6), (3,4), (2,3), (1,2)]\n '
gens = []
m = 0
for row in self:
gens.extend([(c, (c + 1)) for c in range((m + 1), (m + row))])
m += row
gens.append(list(range(1, (self.size() + 1))))
return PermutationGroup(gens)
def young_subgroup_generators(self):
'\n Return an indexing set for the generators of the corresponding Young\n subgroup. Here the generators correspond to the simple adjacent\n transpositions `s_i = (i \\; i+1)`.\n\n EXAMPLES::\n\n sage: Partition([4,2]).young_subgroup_generators()\n [1, 2, 3, 5]\n sage: Partition([1,1,1]).young_subgroup_generators()\n []\n sage: Partition([2,2]).young_subgroup_generators()\n [1, 3]\n\n .. SEEALSO::\n\n :meth:`young_subgroup`\n '
gens = []
m = 0
for row in self:
gens.extend(list(range((m + 1), (m + row))))
m += row
return gens
@cached_method
def _initial_degree(self, e, multicharge=(0,)):
'\n Return the Brundan-Kleshchev-Wang degree of the initial row tableau\n of shape ``self``.\n\n This degree depends only the shape of the tableau and it is\n used as the base case for computing the degrees of all tableau\n of shape ``self``, which is why this method is cached. See\n :meth:`sage.combinat.tableau.Tableau.degree` for more information.\n\n EXAMPLES::\n\n sage: Partition([5,3,2])._initial_degree(0)\n 0\n sage: Partition([5,3,2])._initial_degree(2)\n 4\n sage: Partition([5,3,2])._initial_degree(3)\n 2\n sage: Partition([5,3,2])._initial_degree(4)\n 1\n '
if (e == 0):
return ZZ.zero()
else:
return sum(((m // e) for m in self))
def degree(self, e):
'\n Return the ``e``-th degree of ``self``.\n\n The `e`-th degree of a partition `\\lambda` is the sum of the `e`-th\n degrees of the standard tableaux of shape `\\lambda`. The `e`-th degree\n is the exponent of `\\Phi_e(q)` in the Gram determinant of the Specht\n module for a semisimple Iwahori-Hecke algebra of type `A` with\n parameter `q`.\n\n INPUT:\n\n - ``e`` -- an integer `e > 1`\n\n OUTPUT:\n\n A non-negative integer.\n\n EXAMPLES::\n\n sage: Partition([4,3]).degree(2)\n 28\n sage: Partition([4,3]).degree(3)\n 15\n sage: Partition([4,3]).degree(4)\n 8\n sage: Partition([4,3]).degree(5)\n 13\n sage: Partition([4,3]).degree(6)\n 0\n sage: Partition([4,3]).degree(7)\n 0\n\n Therefore, the Gram determinant of `S(5,3)` when the Hecke parameter\n `q` is "generic" is\n\n .. MATH::\n\n q^N \\Phi_2(q)^{28} \\Phi_3(q)^{15} \\Phi_4(q)^8 \\Phi_5(q)^{13}\n\n for some integer `N`. Compare with :meth:`prime_degree`.\n '
return sum((t.degree(e) for t in self.standard_tableaux()))
def prime_degree(self, p):
'\n Return the prime degree for the prime integer``p`` for ``self``.\n\n INPUT:\n\n - ``p`` -- a prime integer\n\n OUTPUT:\n\n A non-negative integer\n\n The degree of a partition `\\lambda` is the sum of the\n `e`-:meth:`degree` of the standard tableaux of shape `\\lambda`, for\n `e` a power of the prime `p`. The prime degree gives the exponent of\n `p` in the Gram determinant of the integral Specht module of the\n symmetric group.\n\n EXAMPLES::\n\n sage: Partition([4,3]).prime_degree(2)\n 36\n sage: Partition([4,3]).prime_degree(3)\n 15\n sage: Partition([4,3]).prime_degree(5)\n 13\n sage: Partition([4,3]).prime_degree(7)\n 0\n\n Therefore, the Gram determinant of `S(5,3)` when `q = 1` is\n `2^{36} 3^{15} 5^{13}`. Compare with :meth:`degree`.\n '
ps = [p]
while ((ps[(- 1)] * p) < self.size()):
ps.append((ps[(- 1)] * p))
return sum((t.degree(pk) for pk in ps for t in self.standard_tableaux()))
def arm_length(self, i, j):
'\n Return the length of the arm of cell `(i,j)` in ``self``.\n\n The arm of cell `(i,j)` is the cells that appear to the right of\n cell `(i,j)`.\n\n The cell coordinates are zero-based, i. e., the northwesternmost\n cell is `(0,0)`.\n\n INPUT:\n\n - ``i, j`` -- two integers\n\n OUTPUT:\n\n An integer or a ``ValueError``\n\n EXAMPLES::\n\n sage: p = Partition([2,2,1])\n sage: p.arm_length(0, 0)\n 1\n sage: p.arm_length(0, 1)\n 0\n sage: p.arm_length(2, 0)\n 0\n sage: Partition([3,3]).arm_length(0, 0)\n 2\n sage: Partition([3,3]).arm_length(*[0,0])\n 2\n '
p = self
if ((i < len(p)) and (j < p[i])):
return (p[i] - (j + 1))
raise ValueError('the cell is not in the diagram')
def arm_lengths(self, flat=False):
'\n Return a tableau of shape ``self`` where each cell is filled with\n its arm length.\n\n The optional boolean parameter ``flat`` provides the option of\n returning a flat list.\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).arm_lengths()\n [[1, 0], [1, 0], [0]]\n sage: Partition([2,2,1]).arm_lengths(flat=True)\n [1, 0, 1, 0, 0]\n sage: Partition([3,3]).arm_lengths()\n [[2, 1, 0], [2, 1, 0]]\n sage: Partition([3,3]).arm_lengths(flat=True)\n [2, 1, 0, 2, 1, 0]\n '
p = self
if (not flat):
return [[(pi - (j + 1)) for j in range(pi)] for pi in p]
return [(pi - (j + 1)) for pi in p for j in range(pi)]
def arm_cells(self, i, j):
'\n Return the list of the cells of the arm of cell `(i,j)` in ``self``.\n\n The arm of cell `c = (i,j)` is the boxes that appear to the right of\n `c`.\n\n The cell coordinates are zero-based, i. e., the northwesternmost\n cell is `(0,0)`.\n\n INPUT:\n\n - ``i, j`` -- two integers\n\n OUTPUT:\n\n A list of pairs of integers\n\n EXAMPLES::\n\n sage: Partition([4,4,3,1]).arm_cells(1,1)\n [(1, 2), (1, 3)]\n\n sage: Partition([]).arm_cells(0,0)\n Traceback (most recent call last):\n ...\n ValueError: the cell is not in the diagram\n '
p = self
if ((i < len(p)) and (j < p[i])):
return [(i, x) for x in range((j + 1), p[i])]
raise ValueError('the cell is not in the diagram')
def leg_length(self, i, j):
'\n Return the length of the leg of cell `(i,j)` in ``self``.\n\n The leg of cell `c = (i,j)` is defined to be the cells below `c`\n (in English convention).\n\n The cell coordinates are zero-based, i. e., the northwesternmost\n cell is `(0,0)`.\n\n INPUT:\n\n - ``i, j`` -- two integers\n\n OUTPUT:\n\n An integer or a ``ValueError``\n\n EXAMPLES::\n\n sage: p = Partition([2,2,1])\n sage: p.leg_length(0, 0)\n 2\n sage: p.leg_length(0,1)\n 1\n sage: p.leg_length(2,0)\n 0\n sage: Partition([3,3]).leg_length(0, 0)\n 1\n sage: cell = [0,0]; Partition([3,3]).leg_length(*cell)\n 1\n '
conj = self.conjugate()
if ((j < len(conj)) and (i < conj[j])):
return (conj[j] - (i + 1))
raise ValueError('the cell is not in the diagram')
def leg_lengths(self, flat=False):
'\n Return a tableau of shape ``self`` with each cell filled in with\n its leg length. The optional boolean parameter ``flat`` provides\n the option of returning a flat list.\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).leg_lengths()\n [[2, 1], [1, 0], [0]]\n sage: Partition([2,2,1]).leg_lengths(flat=True)\n [2, 1, 1, 0, 0]\n sage: Partition([3,3]).leg_lengths()\n [[1, 1, 1], [0, 0, 0]]\n sage: Partition([3,3]).leg_lengths(flat=True)\n [1, 1, 1, 0, 0, 0]\n '
p = self
conj = p.conjugate()
if (not flat):
return [[(conj[j] - (i + 1)) for j in range(pi)] for (i, pi) in enumerate(p)]
return [(conj[j] - (i + 1)) for (i, pi) in enumerate(p) for j in range(pi)]
def leg_cells(self, i, j):
'\n Return the list of the cells of the leg of cell `(i,j)` in ``self``.\n\n The leg of cell `c = (i,j)` is defined to be the cells below `c` (in\n English convention).\n\n The cell coordinates are zero-based, i. e., the northwesternmost\n cell is `(0,0)`.\n\n INPUT:\n\n - ``i, j`` -- two integers\n\n OUTPUT:\n\n A list of pairs of integers\n\n EXAMPLES::\n\n sage: Partition([4,4,3,1]).leg_cells(1,1)\n [(2, 1)]\n sage: Partition([4,4,3,1]).leg_cells(0,1)\n [(1, 1), (2, 1)]\n\n sage: Partition([]).leg_cells(0,0)\n Traceback (most recent call last):\n ...\n ValueError: the cell is not in the diagram\n '
l = self.leg_length(i, j)
return [(x, j) for x in range((i + 1), ((i + l) + 1))]
def attacking_pairs(self):
'\n Return a list of the attacking pairs of the Young diagram of\n ``self``.\n\n A pair of cells `(c, d)` of a Young diagram (in English notation) is\n said to be attacking if one of the following conditions holds:\n\n 1. `c` and `d` lie in the same row with `c` strictly to the west\n of `d`.\n\n 2. `c` is in the row immediately to the south of `d`, and `c`\n lies strictly east of `d`.\n\n This particular method returns each pair `(c, d)` as a tuple,\n where each of `c` and `d` is given as a tuple `(i, j)` with\n `i` and `j` zero-based (so `i = 0` means that the cell lies\n in the topmost row).\n\n EXAMPLES::\n\n sage: p = Partition([3, 2])\n sage: p.attacking_pairs()\n [((0, 0), (0, 1)),\n ((0, 0), (0, 2)),\n ((0, 1), (0, 2)),\n ((1, 0), (1, 1)),\n ((1, 1), (0, 0))]\n sage: Partition([]).attacking_pairs()\n []\n '
attacking_pairs = []
for (i, r) in enumerate(self):
for j in range(r):
for k in range((j + 1), r):
attacking_pairs.append(((i, j), (i, k)))
if (i == 0):
continue
for k in range(j):
attacking_pairs.append(((i, j), ((i - 1), k)))
return attacking_pairs
def dominated_partitions(self, rows=None):
'\n Return a list of the partitions dominated by `n`. If ``rows`` is\n specified, then it only returns the ones whose number of rows\n is at most ``rows``.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).dominated_partitions()\n [[3, 2, 1], [3, 1, 1, 1], [2, 2, 2], [2, 2, 1, 1], [2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]\n sage: Partition([3,2,1]).dominated_partitions(rows=3)\n [[3, 2, 1], [2, 2, 2]]\n '
n = sum(self)
P = Partitions_n(n)
if rows:
return [P(x) for x in ZS1_iterator_nk(n, rows) if self.dominates(x)]
else:
return [P(x) for x in ZS1_iterator(n) if self.dominates(x)]
def contains(self, x):
'\n Return ``True`` if ``x`` is a partition whose Ferrers diagram is\n contained in the Ferrers diagram of ``self``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2,1])\n sage: p.contains([2,1])\n True\n sage: all(p.contains(mu) for mu in Partitions(3))\n True\n sage: all(p.contains(mu) for mu in Partitions(4))\n False\n '
return ((len(self) >= len(x)) and all(((self[i] >= x[i]) for i in range(len(x)))))
def hook_product(self, a):
'\n Return the Jack hook-product.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).hook_product(x) # needs sage.symbolic\n (2*x + 3)*(x + 2)^2\n sage: Partition([2,2]).hook_product(x) # needs sage.symbolic\n 2*(x + 2)*(x + 1)\n '
nu = self.conjugate()
res = 1
for i in range(len(self)):
for j in range(self[i]):
res *= (((a * ((self[i] - j) - 1)) + nu[j]) - i)
return res
def hook_polynomial(self, q, t):
'\n Return the two-variable hook polynomial.\n\n EXAMPLES::\n\n sage: R.<q,t> = PolynomialRing(QQ)\n sage: a = Partition([2,2]).hook_polynomial(q,t)\n sage: a == (1 - t)*(1 - q*t)*(1 - t^2)*(1 - q*t^2)\n True\n sage: a = Partition([3,2,1]).hook_polynomial(q,t)\n sage: a == (1 - t)^3*(1 - q*t^2)^2*(1 - q^2*t^3)\n True\n '
nu = self.conjugate()
res = 1
for i in range(len(self)):
for j in range(self[i]):
res *= (1 - ((q ** ((self[i] - j) - 1)) * (t ** (nu[j] - i))))
return res
def hook_length(self, i, j):
'\n Return the length of the hook of cell `(i,j)` in ``self``.\n\n The (length of the) hook of cell `(i,j)` of a partition `\\lambda`\n is\n\n .. MATH::\n\n \\lambda_i + \\lambda^{\\prime}_j - i - j + 1\n\n where `\\lambda^{\\prime}` is the conjugate partition. In English\n convention, the hook length is the number of cells horizontally\n to the right and vertically below the cell `(i,j)` (including\n that cell).\n\n EXAMPLES::\n\n sage: p = Partition([2,2,1])\n sage: p.hook_length(0, 0)\n 4\n sage: p.hook_length(0, 1)\n 2\n sage: p.hook_length(2, 0)\n 1\n sage: Partition([3,3]).hook_length(0, 0)\n 4\n sage: cell = [0,0]; Partition([3,3]).hook_length(*cell)\n 4\n '
return ((self.leg_length(i, j) + self.arm_length(i, j)) + 1)
def hooks(self):
'\n Return a sorted list of the hook lengths in ``self``.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).hooks()\n [5, 3, 3, 1, 1, 1]\n '
res = []
for row in self.hook_lengths():
res += row
res.sort(reverse=True)
return res
def hook_lengths(self):
'\n Return a tableau of shape ``self`` with the cells filled in with the\n hook lengths.\n\n In each cell, put the sum of one plus the number of cells\n horizontally to the right and vertically below the cell (the\n hook length).\n\n For example, consider the partition ``[3,2,1]`` of 6 with Ferrers\n diagram::\n\n # # #\n # #\n #\n\n When we fill in the cells with the hook lengths, we obtain::\n\n 5 3 1\n 3 1\n 1\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).hook_lengths()\n [[4, 2], [3, 1], [1]]\n sage: Partition([3,3]).hook_lengths()\n [[4, 3, 2], [3, 2, 1]]\n sage: Partition([3,2,1]).hook_lengths()\n [[5, 3, 1], [3, 1], [1]]\n sage: Partition([2,2]).hook_lengths()\n [[3, 2], [2, 1]]\n sage: Partition([5]).hook_lengths()\n [[5, 4, 3, 2, 1]]\n\n REFERENCES:\n\n - http://mathworld.wolfram.com/HookLengthFormula.html\n '
p = self
conj = p.conjugate()
return [[((((p[i] - (i + 1)) + conj[j]) - (j + 1)) + 1) for j in range(p[i])] for i in range(len(p))]
def upper_hook(self, i, j, alpha):
'\n Return the upper hook length of the cell `(i,j)` in ``self``.\n When ``alpha = 1``, this is just the normal hook length.\n\n The upper hook length of a cell `(i,j)` in a partition\n `\\kappa` is defined by\n\n .. MATH::\n\n h^*_\\kappa(i,j) = \\kappa^\\prime_j - i + \\alpha(\\kappa_i - j + 1).\n\n EXAMPLES::\n\n sage: p = Partition([2,1])\n sage: p.upper_hook(0,0,1)\n 3\n sage: p.hook_length(0,0)\n 3\n sage: [ p.upper_hook(i,j,x) for i,j in p.cells() ] # needs sage.symbolic\n [2*x + 1, x, x]\n '
p = self
conj = self.conjugate()
return ((conj[j] - (i + 1)) + (alpha * (p[i] - j)))
def upper_hook_lengths(self, alpha):
'\n Return a tableau of shape ``self`` with the cells filled in with the\n upper hook lengths. When ``alpha = 1``, these are just the normal hook\n lengths.\n\n The upper hook length of a cell `(i,j)` in a partition\n `\\kappa` is defined by\n\n .. MATH::\n\n h^*_\\kappa(i,j) = \\kappa^\\prime_j - i + \\alpha(\\kappa_i - j + 1).\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).upper_hook_lengths(x) # needs sage.symbolic\n [[3*x + 2, 2*x + 1, x], [2*x + 1, x], [x]]\n sage: Partition([3,2,1]).upper_hook_lengths(1)\n [[5, 3, 1], [3, 1], [1]]\n sage: Partition([3,2,1]).hook_lengths()\n [[5, 3, 1], [3, 1], [1]]\n '
p = self
conj = p.conjugate()
return [[((conj[j] - (i + 1)) + (alpha * (p[i] - j))) for j in range(p[i])] for i in range(len(p))]
def lower_hook(self, i, j, alpha):
'\n Return the lower hook length of the cell `(i,j)` in ``self``.\n When ``alpha = 1``, this is just the normal hook length.\n\n The lower hook length of a cell `(i,j)` in a partition\n `\\kappa` is defined by\n\n .. MATH::\n\n h_*^\\kappa(i,j) = \\kappa^\\prime_j - i + 1 + \\alpha(\\kappa_i - j).\n\n EXAMPLES::\n\n sage: p = Partition([2,1])\n sage: p.lower_hook(0,0,1)\n 3\n sage: p.hook_length(0,0)\n 3\n sage: [ p.lower_hook(i,j,x) for i,j in p.cells() ] # needs sage.symbolic\n [x + 2, 1, 1]\n '
p = self
conj = self.conjugate()
return ((conj[j] - i) + (alpha * (p[i] - (j + 1))))
def lower_hook_lengths(self, alpha):
'\n Return a tableau of shape ``self`` with the cells filled in with the\n lower hook lengths. When ``alpha = 1``, these are just the normal hook\n lengths.\n\n The lower hook length of a cell `(i,j)` in a partition\n `\\kappa` is defined by\n\n .. MATH::\n\n h_*^\\kappa(i,j) = \\kappa^\\prime_j - i + 1 + \\alpha(\\kappa_i - j).\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).lower_hook_lengths(x) # needs sage.symbolic\n [[2*x + 3, x + 2, 1], [x + 2, 1], [1]]\n sage: Partition([3,2,1]).lower_hook_lengths(1)\n [[5, 3, 1], [3, 1], [1]]\n sage: Partition([3,2,1]).hook_lengths()\n [[5, 3, 1], [3, 1], [1]]\n '
p = self
conj = p.conjugate()
return [[((conj[j] - i) + (alpha * (p[i] - (j + 1)))) for j in range(p[i])] for i in range(len(p))]
def weighted_size(self):
'\n Return the weighted size of ``self``.\n\n The weighted size of a partition `\\lambda` is\n\n .. MATH::\n\n \\sum_i i \\cdot \\lambda_i,\n\n where `\\lambda = (\\lambda_0, \\lambda_1, \\lambda_2, \\cdots )`.\n\n This also the sum of the leg length of every cell in `\\lambda`, or\n\n .. MATH::\n\n \\sum_i \\binom{\\lambda^{\\prime}_i}{2}\n\n where `\\lambda^{\\prime}` is the conjugate partition of `\\lambda`.\n\n EXAMPLES::\n\n sage: Partition([2,2]).weighted_size()\n 2\n sage: Partition([3,3,3]).weighted_size()\n 9\n sage: Partition([5,2]).weighted_size()\n 2\n sage: Partition([]).weighted_size()\n 0\n '
p = self
return sum([(i * p[i]) for i in range(len(p))])
def is_empty(self):
'\n Return ``True`` if ``self`` is the empty partition.\n\n EXAMPLES::\n\n sage: Partition([]).is_empty()\n True\n sage: Partition([2,1,1]).is_empty()\n False\n '
return (len(self) == 0)
def length(self):
'\n Return the number of parts in ``self``.\n\n EXAMPLES::\n\n sage: Partition([3,2]).length()\n 2\n sage: Partition([2,2,1]).length()\n 3\n sage: Partition([]).length()\n 0\n '
return len(self)
def to_exp(self, k=0):
'\n Return a list of the multiplicities of the parts of a partition.\n Use the optional parameter ``k`` to get a return list of length at\n least ``k``.\n\n EXAMPLES::\n\n sage: Partition([3,2,2,1]).to_exp()\n [1, 2, 1]\n sage: Partition([3,2,2,1]).to_exp(5)\n [1, 2, 1, 0, 0]\n\n TESTS::\n\n sage: [parent(x) for x in Partition([3,2,2,1]).to_exp(5)]\n [Integer Ring, Integer Ring, Integer Ring, Integer Ring, Integer Ring]\n '
p = self
if (len(p) > 0):
k = max(k, p[0])
a = ([ZZ.zero()] * k)
for i in p:
a[(i - 1)] += 1
return a
def evaluation(self):
'\n Return the evaluation of ``self``.\n\n The **commutative evaluation**, often shortened to **evaluation**, of\n a word (we think of a partition as a word in `\\{1, 2, 3, \\ldots\\}`)\n is its image in the free commutative monoid. In other words,\n this counts how many occurrences there are of each letter.\n\n This is also is known as **Parikh vector** and **abelianization** and\n has the same output as :meth:`to_exp()`.\n\n EXAMPLES::\n\n sage: Partition([4,3,1,1]).evaluation()\n [2, 0, 1, 1]\n '
return self.to_exp()
def to_exp_dict(self):
'\n Return a dictionary containing the multiplicities of the parts of\n ``self``.\n\n EXAMPLES::\n\n sage: p = Partition([4,2,2,1])\n sage: d = p.to_exp_dict()\n sage: d[4]\n 1\n sage: d[2]\n 2\n sage: d[1]\n 1\n sage: 5 in d\n False\n '
d = {}
for part in self:
d[part] = (d.get(part, 0) + 1)
return d
def centralizer_size(self, t=0, q=0):
'\n Return the size of the centralizer of any permutation of cycle type\n ``self``.\n\n If `m_i` is the multiplicity of `i` as a part of `p`, this is given by\n\n .. MATH::\n\n \\prod_i m_i! i^{m_i}.\n\n Including the optional parameters `t` and `q` gives the `q,t` analog,\n which is the former product times\n\n .. MATH::\n\n \\prod_{i=1}^{\\mathrm{length}(p)} \\frac{1 - q^{p_i}}{1 - t^{p_i}}.\n\n See Section 1.3, p. 24, in [Ke1991]_.\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).centralizer_size()\n 8\n sage: Partition([2,2,2]).centralizer_size()\n 48\n sage: Partition([2,2,1]).centralizer_size(q=2, t=3)\n 9/16\n sage: Partition([]).centralizer_size()\n 1\n sage: Partition([]).centralizer_size(q=2, t=4)\n 1\n\n TESTS::\n\n sage: Partition([2,2,2]).aut()\n 48\n '
size = prod((((i ** mi) * factorial(mi)) for (i, mi) in self.to_exp_dict().items()))
if (t or q):
size *= prod((((ZZ.one() - (q ** j)) / (ZZ.one() - (t ** j))) for j in self))
return size
aut = centralizer_size
def content(self, r, c, multicharge=(0,)):
'\n Return the content of the cell at row `r` and column `c`.\n\n The content of a cell is `c - r`.\n\n For consistency with partition tuples there is also an optional\n ``multicharge`` argument which is an offset to the usual content. By\n setting the ``multicharge`` equal to the 0-element of the ring\n `\\ZZ/e\\ZZ`, the corresponding `e`-residue will be returned. This is\n the content modulo `e`.\n\n The content (and residue) do not strictly depend on the partition,\n however, this method is included because it is often useful in the\n context of partitions.\n\n EXAMPLES::\n\n sage: Partition([2,1]).content(1,0)\n -1\n sage: p = Partition([3,2])\n sage: sum([p.content(*c) for c in p.cells()])\n 2\n\n and now we return the 3-residue of a cell::\n\n sage: Partition([2,1]).content(1,0, multicharge=[IntegerModRing(3)(0)])\n 2\n '
return ((c - r) + multicharge[0])
def residue(self, r, c, l):
'\n Return the ``l``-residue of the cell at row ``r`` and column ``c``.\n\n The `\\ell`-residue of a cell is `c - r` modulo `\\ell`.\n\n This does not strictly depend upon the partition, however, this method\n is included because it is often useful in the context of partitions.\n\n EXAMPLES::\n\n sage: Partition([2,1]).residue(1, 0, 3)\n 2\n '
return ((c - r) % l)
@cached_method
def block(self, e, multicharge=(0,)):
'\n Return a dictionary `\\beta` that determines the block associated to\n the partition ``self`` and the\n :meth:`~sage.combinat.tableau_residues.ResidueSequence.quantum_characteristic` ``e``.\n\n INPUT:\n\n - ``e`` -- the quantum characteristic\n\n - ``multicharge`` -- the multicharge (default `(0,)`)\n\n OUTPUT:\n\n - A dictionary giving the multiplicities of the residues in the\n partition tuple ``self``\n\n In more detail, the value ``beta[i]`` is equal to the\n number of nodes of residue ``i``. This corresponds to\n the positive root\n\n .. MATH::\n\n \\sum_{i\\in I} \\beta_i \\alpha_i \\in Q^+,\n\n a element of the positive root lattice of the corresponding\n Kac-Moody algebra. See [DJM1998]_ and [BK2009]_ for more details.\n\n This is a useful statistics because two Specht modules for a\n Hecke algebra of type `A` belong to the same block if and only if they\n correspond to same element `\\beta` of the root lattice, given above.\n\n We return a dictionary because when the quantum characteristic is `0`,\n the Cartan type is `A_{\\infty}`, in which case the simple roots are\n indexed by the integers.\n\n EXAMPLES::\n\n sage: Partition([4,3,2]).block(0)\n {-2: 1, -1: 2, 0: 2, 1: 2, 2: 1, 3: 1}\n sage: Partition([4,3,2]).block(2)\n {0: 4, 1: 5}\n sage: Partition([4,3,2]).block(2, multicharge=(1,))\n {0: 5, 1: 4}\n sage: Partition([4,3,2]).block(3)\n {0: 3, 1: 3, 2: 3}\n sage: Partition([4,3,2]).block(4)\n {0: 2, 1: 2, 2: 2, 3: 3}\n '
block = {}
Ie = IntegerModRing(e)
for (r, c) in self.cells():
i = Ie(((multicharge[0] + c) - r))
block[i] = (block.get(i, 0) + 1)
return block
def defect(self, e, multicharge=(0,)):
'\n Return the ``e``-defect or the ``e``-weight of ``self``.\n\n The `e`-defect is the number of (connected) `e`-rim hooks that\n can be removed from the partition.\n\n The defect of a partition is given by\n\n .. MATH::\n\n \\text{defect}(\\beta) = (\\Lambda, \\beta) - \\tfrac12(\\beta, \\beta),\n\n where `\\Lambda = \\sum_r \\Lambda_{\\kappa_r}` for the multicharge\n `(\\kappa_1, \\ldots, \\kappa_{\\ell})` and\n `\\beta = \\sum_{(r,c)} \\alpha_{(c-r) \\pmod e}`, with the sum\n being over the cells in the partition.\n\n INPUT:\n\n - ``e`` -- the quantum characteristic\n\n - ``multicharge`` -- the multicharge (default `(0,)`)\n\n OUTPUT:\n\n - a non-negative integer, which is the defect of the block\n containing the partition ``self``\n\n EXAMPLES::\n\n sage: Partition([4,3,2]).defect(2)\n 3\n sage: Partition([0]).defect(2)\n 0\n sage: Partition([3]).defect(2)\n 1\n sage: Partition([6]).defect(2)\n 3\n sage: Partition([9]).defect(2)\n 4\n sage: Partition([12]).defect(2)\n 6\n sage: Partition([4,3,2]).defect(3)\n 3\n sage: Partition([0]).defect(3)\n 0\n sage: Partition([3]).defect(3)\n 1\n sage: Partition([6]).defect(3)\n 2\n sage: Partition([9]).defect(3)\n 3\n sage: Partition([12]).defect(3)\n 4\n\n TESTS::\n\n sage: all(mu.core(e).size() + e * mu.defect(e) == 9\n ....: for mu in Partitions(9) for e in [2,3,4])\n True\n '
beta = self.block(e, multicharge)
Ie = IntegerModRing(e)
return (beta.get(multicharge[0], 0) - sum((((beta[r] ** 2) - (beta[r] * beta.get(Ie((r + 1)), 0))) for r in beta)))
def contents_tableau(self, multicharge=(0,)):
'\n Return the tableau which has ``(k,r,c)``-th cell equal to the\n content ``multicharge[k] - r + c`` of the cell.\n\n EXAMPLES::\n\n sage: Partition([2,1]).contents_tableau()\n [[0, 1], [-1]]\n sage: Partition([3,2,1,1]).contents_tableau().pp()\n 0 1 2\n -1 0\n -2\n -3\n sage: Partition([3,2,1,1]).contents_tableau([ IntegerModRing(3)(0)] ).pp()\n 0 1 2\n 2 0\n 1\n 0\n '
return tableau.Tableau([[((multicharge[0] - r) + c) for c in range(self[r])] for r in range(len(self))])
def is_restricted(self, e, multicharge=(0,)):
'\n Return ``True`` is this is an ``e``-restricted partition.\n\n An `e`-restricted partition is a partition such that the\n difference of consecutive parts is always strictly less\n than `e`, where partitions are considered to have an infinite\n number of `0` parts. I.e., the last part must be strictly\n less than `e`.\n\n EXAMPLES::\n\n sage: Partition([4,3,3,2]).is_restricted(2)\n False\n sage: Partition([4,3,3,2]).is_restricted(3)\n True\n sage: Partition([4,3,3,2]).is_restricted(4)\n True\n sage: Partition([4]).is_restricted(4)\n False\n '
return ((not self) or ((self[(- 1)] < e) and all((((self[r] - self[(r + 1)]) < e) for r in range((len(self) - 1))))))
def is_regular(self, e, multicharge=(0,)):
'\n Return ``True`` is this is an ``e``-regular partition.\n\n A partition is `e`-regular if it does not have `e` equal\n non-zero parts.\n\n EXAMPLES::\n\n sage: Partition([4,3,3,3]).is_regular(2)\n False\n sage: Partition([4,3,3,3]).is_regular(3)\n False\n sage: Partition([4,3,3,3]).is_regular(4)\n True\n '
return all(((self[r] > self[((r + e) - 1)]) for r in range(((len(self) - e) + 1))))
def conjugacy_class_size(self):
'\n Return the size of the conjugacy class of the symmetric group\n indexed by ``self``.\n\n EXAMPLES::\n\n sage: Partition([2,2,2]).conjugacy_class_size()\n 15\n sage: Partition([2,2,1]).conjugacy_class_size()\n 15\n sage: Partition([2,1,1]).conjugacy_class_size()\n 6\n '
return (factorial(sum(self)) / self.centralizer_size())
def corners(self):
'\n Return a list of the corners of the partition ``self``.\n\n A corner of a partition `\\lambda` is a cell of the Young diagram\n of `\\lambda` which can be removed from the Young diagram while\n still leaving a straight shape behind.\n\n The entries of the list returned are pairs of the form `(i,j)`,\n where `i` and `j` are the coordinates of the respective corner.\n The coordinates are counted from `0`.\n\n .. NOTE::\n\n This is referred to as an "inner corner" in [Sag2001]_.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).corners()\n [(0, 2), (1, 1), (2, 0)]\n sage: Partition([3,3,1]).corners()\n [(1, 2), (2, 0)]\n sage: Partition([]).corners()\n []\n '
p = self
if p.is_empty():
return []
lcors = [[0, (p[0] - 1)]]
nn = len(p)
if (nn == 1):
return [tuple(c) for c in lcors]
lcors_index = 0
for i in range(1, nn):
if (p[i] == p[(i - 1)]):
lcors[lcors_index][0] += 1
else:
lcors.append([i, (p[i] - 1)])
lcors_index += 1
return [tuple(c) for c in lcors]
inside_corners = corners
removable_cells = corners
def corners_residue(self, i, l):
'\n Return a list of the corners of the partition ``self`` having\n ``l``-residue ``i``.\n\n A corner of a partition `\\lambda` is a cell of the Young diagram\n of `\\lambda` which can be removed from the Young diagram while\n still leaving a straight shape behind. See :meth:`residue` for\n the definition of the ``l``-residue.\n\n The entries of the list returned are pairs of the form `(i,j)`,\n where `i` and `j` are the coordinates of the respective corner.\n The coordinates are counted from `0`.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).corners_residue(0, 3)\n [(1, 1)]\n sage: Partition([3,2,1]).corners_residue(1, 3)\n [(2, 0)]\n sage: Partition([3,2,1]).corners_residue(2, 3)\n [(0, 2)]\n '
return [x for x in self.corners() if (self.residue(*x, l=l) == i)]
inside_corners_residue = corners_residue
removable_cells_residue = corners_residue
def outside_corners(self):
'\n Return a list of the outside corners of the partition ``self``.\n\n An outside corner (also called a cocorner) of a partition\n `\\lambda` is a cell on `\\ZZ^2` which does not belong to\n the Young diagram of `\\lambda` but can be added to this Young\n diagram to still form a straight-shape Young diagram.\n\n The entries of the list returned are pairs of the form `(i,j)`,\n where `i` and `j` are the coordinates of the respective corner.\n The coordinates are counted from `0`.\n\n .. NOTE::\n\n These are called "outer corners" in [Sag2001]_.\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).outside_corners()\n [(0, 2), (2, 1), (3, 0)]\n sage: Partition([2,2]).outside_corners()\n [(0, 2), (2, 0)]\n sage: Partition([6,3,3,1,1,1]).outside_corners()\n [(0, 6), (1, 3), (3, 1), (6, 0)]\n sage: Partition([]).outside_corners()\n [(0, 0)]\n '
p = self._list
if (not p):
return [(0, 0)]
res = [(0, p[0])]
res.extend(((n, j) for (n, (i, j)) in enumerate(zip(p[:(- 1)], p[1:]), start=1) if (i != j)))
res.append((len(p), 0))
return res
addable_cells = outside_corners
def outside_corners_residue(self, i, l):
'\n Return a list of the outside corners of the partition ``self``\n having ``l``-residue ``i``.\n\n An outside corner (also called a cocorner) of a partition\n `\\lambda` is a cell on `\\ZZ^2` which does not belong to\n the Young diagram of `\\lambda` but can be added to this Young\n diagram to still form a straight-shape Young diagram. See\n :meth:`residue` for the definition of the ``l``-residue.\n\n The entries of the list returned are pairs of the form `(i,j)`,\n where `i` and `j` are the coordinates of the respective corner.\n The coordinates are counted from `0`.\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).outside_corners_residue(0, 3)\n [(0, 3), (3, 0)]\n sage: Partition([3,2,1]).outside_corners_residue(1, 3)\n [(1, 2)]\n sage: Partition([3,2,1]).outside_corners_residue(2, 3)\n [(2, 1)]\n '
return [x for x in self.outside_corners() if (self.residue(*x, l=l) == i)]
addable_cells_residue = outside_corners_residue
def rim(self):
'\n Return the rim of ``self``.\n\n The rim of a partition `\\lambda` is defined as the cells which belong\n to `\\lambda` and which are adjacent to cells not in `\\lambda`.\n\n EXAMPLES:\n\n The rim of the partition `[5,5,2,1]` consists of the cells marked with\n ``#`` below::\n\n ****#\n *####\n ##\n #\n\n sage: Partition([5,5,2,1]).rim()\n [(3, 0), (2, 0), (2, 1), (1, 1), (1, 2), (1, 3), (1, 4), (0, 4)]\n\n sage: Partition([2,2,1]).rim()\n [(2, 0), (1, 0), (1, 1), (0, 1)]\n sage: Partition([2,2]).rim()\n [(1, 0), (1, 1), (0, 1)]\n sage: Partition([6,3,3,1,1]).rim()\n [(4, 0), (3, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (0, 3), (0, 4), (0, 5)]\n sage: Partition([]).rim()\n []\n '
p = self
res = []
prevLen = 1
for i in range((len(p) - 1), (- 1), (- 1)):
for c in range((prevLen - 1), p[i]):
res.append((i, c))
prevLen = p[i]
return res
def outer_rim(self):
'\n Return the outer rim of ``self``.\n\n The outer rim of a partition `\\lambda` is defined as the cells which do\n not belong to `\\lambda` and which are adjacent to cells in `\\lambda`.\n\n EXAMPLES:\n\n The outer rim of the partition `[4,1]` consists of the cells marked\n with ``#`` below::\n\n ****#\n *####\n ##\n\n ::\n\n sage: Partition([4,1]).outer_rim()\n [(2, 0), (2, 1), (1, 1), (1, 2), (1, 3), (1, 4), (0, 4)]\n\n sage: Partition([2,2,1]).outer_rim()\n [(3, 0), (3, 1), (2, 1), (2, 2), (1, 2), (0, 2)]\n sage: Partition([2,2]).outer_rim()\n [(2, 0), (2, 1), (2, 2), (1, 2), (0, 2)]\n sage: Partition([6,3,3,1,1]).outer_rim()\n [(5, 0), (5, 1), (4, 1), (3, 1), (3, 2), (3, 3), (2, 3), (1, 3), (1, 4), (1, 5), (1, 6), (0, 6)]\n sage: Partition([]).outer_rim()\n [(0, 0)]\n '
p = self
res = []
prevLen = 0
for i in range((len(p) - 1), (- 1), (- 1)):
for c in range(prevLen, (p[i] + 1)):
res.append(((i + 1), c))
prevLen = p[i]
res.append((0, prevLen))
return res
def zero_one_sequence(self):
"\n Compute the finite `0-1` sequence of the partition.\n\n The full `0-1` sequence is the sequence (infinite in both\n directions) indicating the steps taken when following the\n outer rim of the diagram of the partition. We use the convention\n that in English convention, a 1 corresponds to an East step, and\n a 0 corresponds to a North step.\n\n Note that every full `0-1` sequence starts with infinitely many 0's and\n ends with infinitely many 1's.\n\n One place where these arise is in the affine symmetric group where\n one takes an affine permutation `w` and every `i` such that\n `w(i) \\leq 0` corresponds to a 1 and `w(i) > 0` corresponds to a 0.\n See pages 24-25 of [LLMSSZ2013]_ for connections to affine Grassmannian\n elements (note there they use the French convention for their\n partitions).\n\n These are also known as **path sequences**, **Maya diagrams**,\n **plus-minus diagrams**, **Comet code** [Sta-EC2]_, among others.\n\n OUTPUT:\n\n The finite `0-1` sequence is obtained from the full `0-1`\n sequence by omitting all heading 0's and trailing 1's. The\n output sequence is finite, starts with a 1 and ends with a\n 0 (unless it is empty, for the empty partition). Its length\n is the sum of the first part of the partition with the\n length of the partition.\n\n EXAMPLES::\n\n sage: Partition([5,4]).zero_one_sequence()\n [1, 1, 1, 1, 0, 1, 0]\n sage: Partition([]).zero_one_sequence()\n []\n sage: Partition([2]).zero_one_sequence()\n [1, 1, 0]\n\n TESTS::\n\n sage: all(Partitions().from_zero_one(mu.zero_one_sequence()) == mu for n in range(10) for mu in Partitions(n))\n True\n "
tmp = set(((self[i] - i) for i in range(len(self))))
return [Integer((i not in tmp)) for i in range(((- len(self)) + 1), (self.get_part(0) + 1))]
def core(self, length):
'\n Return the ``length``-core of the partition -- in the literature\n the core is commonly referred to as the `k`-core, `p`-core,\n `r`-core, ... .\n\n The `r`-core of a partition `\\lambda` can be obtained by\n repeatedly removing rim hooks of size `r` from (the Young diagram\n of) `\\lambda` until this is no longer possible. The remaining\n partition is the core.\n\n EXAMPLES::\n\n sage: Partition([6,3,2,2]).core(3)\n [2, 1, 1]\n sage: Partition([]).core(3)\n []\n sage: Partition([8,7,7,4,1,1,1,1,1]).core(3)\n [2, 1, 1]\n\n TESTS::\n\n sage: Partition([3,3,3,2,1]).core(3)\n []\n sage: Partition([10,8,7,7]).core(4)\n []\n sage: Partition([21,15,15,9,6,6,6,3,3]).core(3)\n []\n '
p = self
remainder = (len(p) % length)
part = (p[:] + ([0] * remainder))
part = [((part[(i - 1)] + len(part)) - i) for i in range(1, (len(part) + 1))]
for e in range(length):
k = e
for i in reversed(range(1, (len(part) + 1))):
if ((part[(i - 1)] % length) == e):
part[(i - 1)] = k
k += length
part.sort()
part.reverse()
part = [((part[(i - 1)] - len(part)) + i) for i in range(1, (len(part) + 1))]
return Partition([x for x in part if (x != 0)])
def quotient(self, length):
'\n Return the quotient of the partition -- in the literature the\n quotient is commonly referred to as the `k`-quotient, `p`-quotient,\n `r`-quotient, ... .\n\n The `r`-quotient of a partition `\\lambda` is a list of `r`\n partitions (labelled from `0` to `r-1`), constructed in the following\n way. Label each cell in the Young diagram of `\\lambda` with its\n content modulo `r`. Let `R_i` be the set of rows ending in a cell\n labelled `i`, and `C_i` be the set of columns ending in a cell\n labelled `i`. Then the `j`-th component of the quotient of\n `\\lambda` is the partition defined by intersecting `R_j` with\n `C_{j+1}`. (See Theorem 2.7.37 in [JK1981]_.)\n\n EXAMPLES::\n\n sage: Partition([7,7,5,3,3,3,1]).quotient(3)\n ([2], [1], [2, 2, 2])\n\n TESTS::\n\n sage: Partition([8,7,7,4,1,1,1,1,1]).quotient(3)\n ([2, 1], [2, 2], [2])\n sage: Partition([10,8,7,7]).quotient(4)\n ([2], [3], [2], [1])\n sage: Partition([6,3,3]).quotient(3)\n ([1], [1], [2])\n sage: Partition([3,3,3,2,1]).quotient(3)\n ([1], [1, 1], [1])\n sage: Partition([6,6,6,3,3,3]).quotient(3)\n ([2, 1], [2, 1], [2, 1])\n sage: Partition([21,15,15,9,6,6,6,3,3]).quotient(3)\n ([5, 2, 1], [5, 2, 1], [7, 3, 2])\n sage: Partition([21,15,15,9,6,6,3,3]).quotient(3)\n ([5, 2], [5, 2, 1], [7, 3, 1])\n sage: Partition([14,12,11,10,10,10,10,9,6,4,3,3,2,1]).quotient(5)\n ([3, 3], [2, 2, 1], [], [3, 3, 3], [1])\n\n sage: all(p == Partition(core=p.core(k), quotient=p.quotient(k))\n ....: for i in range(10) for p in Partitions(i)\n ....: for k in range(1,6))\n True\n '
p = self
remainder = (len(p) % length)
part = (p[:] + ([0] * (length - remainder)))
part = [((part[(i - 1)] + len(part)) - i) for i in range(1, (len(part) + 1))]
result = ([None] * length)
for e in range(length):
k = e
tmp = []
for i in reversed(range(len(part))):
if ((part[i] % length) == e):
tmp.append(ZZ(((part[i] - k) // length)))
k += length
a = [i for i in tmp if (i != 0)]
a.reverse()
result[e] = a
from .partition_tuple import PartitionTuple
return PartitionTuple(result)
def is_core(self, k):
'\n Return ``True`` if the Partition ``self`` is a ``k``-core.\n\n A partition is said to be a *`k`-core* if it has no hooks of length\n `k`. Equivalently, a partition is said to be a `k`-core if it is its\n own `k`-core (where the latter is defined as in :meth:`core`).\n\n Visually, this can be checked by trying to remove border strips of size\n `k` from ``self``. If this is not possible, then ``self`` is a\n `k`-core.\n\n EXAMPLES:\n\n In the partition (2, 1), a hook length of 2 does not occur, but a hook\n length of 3 does::\n\n sage: p = Partition([2, 1])\n sage: p.is_core(2)\n True\n sage: p.is_core(3)\n False\n\n sage: q = Partition([12, 8, 5, 5, 2, 2, 1])\n sage: q.is_core(4)\n False\n sage: q.is_core(5)\n True\n sage: q.is_core(0)\n True\n\n .. SEEALSO::\n\n :meth:`core`, :class:`Core`\n '
return (k not in self.hooks())
def k_interior(self, k):
'\n Return the partition consisting of the cells of ``self`` whose hook\n lengths are greater than ``k``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2,1])\n sage: p.hook_lengths()\n [[5, 3, 1], [3, 1], [1]]\n sage: p.k_interior(2)\n [2, 1]\n sage: p.k_interior(3)\n [1]\n\n sage: p = Partition([])\n sage: p.k_interior(3)\n []\n '
return Partition([len([i for i in row if (i > k)]) for row in self.hook_lengths()])
def k_boundary(self, k):
'\n Return the skew partition formed by removing the cells of the\n ``k``-interior, see :meth:`k_interior`.\n\n EXAMPLES::\n\n sage: p = Partition([3,2,1])\n sage: p.k_boundary(2)\n [3, 2, 1] / [2, 1]\n sage: p.k_boundary(3)\n [3, 2, 1] / [1]\n\n sage: p = Partition([12,8,5,5,2,2,1])\n sage: p.k_boundary(4)\n [12, 8, 5, 5, 2, 2, 1] / [8, 5, 2, 2]\n '
return SkewPartition([self, self.k_interior(k)])
def add_cell(self, i, j=None):
'\n Return a partition corresponding to ``self`` with a cell added in\n row ``i``. (This does not change ``self``.)\n\n EXAMPLES::\n\n sage: Partition([3, 2, 1, 1]).add_cell(0)\n [4, 2, 1, 1]\n sage: cell = [4, 0]; Partition([3, 2, 1, 1]).add_cell(*cell)\n [3, 2, 1, 1, 1]\n '
if (j is None):
if (i >= len(self)):
j = 0
else:
j = self[i]
if ((i, j) in self.outside_corners()):
pl = self.to_list()
if (i == len(pl)):
pl.append(1)
else:
pl[i] += 1
return Partition(pl)
raise ValueError(f'[{i}, {j}] is not an addable cell')
def remove_cell(self, i, j=None):
'\n Return the partition obtained by removing a cell at the end of row\n ``i`` of ``self``.\n\n EXAMPLES::\n\n sage: Partition([2,2]).remove_cell(1)\n [2, 1]\n sage: Partition([2,2,1]).remove_cell(2)\n [2, 2]\n sage: #Partition([2,2]).remove_cell(0)\n\n ::\n\n sage: Partition([2,2]).remove_cell(1,1)\n [2, 1]\n sage: #Partition([2,2]).remove_cell(1,0)\n '
if (i >= len(self)):
raise ValueError('i must be less than the length of the partition')
if (j is None):
j = (self[i] - 1)
if ((i, j) not in self.corners()):
raise ValueError(('[%d,%d] is not a corner of the partition' % (i, j)))
if (self[i] == 1):
return Partition(self[:(- 1)])
else:
return Partition(((self[:i] + [(self[i:(i + 1)][0] - 1)]) + self[(i + 1):]))
def k_irreducible(self, k):
'\n Return the partition with all `r \\times (k+1-r)` rectangles removed.\n\n If ``self`` is a `k`-bounded partition, then this method will return the partition\n where all rectangles of dimension `r \\times (k+1-r)` for `1 \\leq r \\leq k`\n have been deleted.\n\n If ``self`` is not a `k`-bounded partition then the method will raise an error.\n\n INPUT:\n\n - ``k`` -- a non-negative integer\n\n OUTPUT:\n\n - a partition\n\n EXAMPLES::\n\n sage: Partition([3,2,2,1,1,1]).k_irreducible(4)\n [3, 2, 2, 1, 1, 1]\n sage: Partition([3,2,2,1,1,1]).k_irreducible(3)\n []\n sage: Partition([3,3,3,2,2,2,2,2,1,1,1,1]).k_irreducible(3)\n [2, 1]\n '
pexp = self.to_exp()
return Partition(sum(([(r + 1)] for r in range((len(pexp) - 1), (- 1), (- 1)) for m in range((pexp[r] % (k - r)))), []))
def k_skew(self, k):
'\n Return the `k`-skew partition.\n\n The `k`-skew diagram of a `k`-bounded partition is the skew diagram\n denoted `\\lambda/^k` satisfying the conditions:\n\n 1. row `i` of `\\lambda/^k` has length `\\lambda_i`,\n\n 2. no cell in `\\lambda/^k` has hook-length exceeding `k`,\n\n 3. every square above the diagram of `\\lambda/^k` has hook\n length exceeding `k`.\n\n REFERENCES:\n\n - [LM2004]_\n\n EXAMPLES::\n\n sage: p = Partition([4,3,2,2,1,1])\n sage: p.k_skew(4)\n [9, 5, 3, 2, 1, 1] / [5, 2, 1]\n '
if (len(self) == 0):
return SkewPartition([[], []])
if (self[0] > k):
raise ValueError(f'the partition must be {k}-bounded')
s = Partition(self[1:]).k_skew(k)
s_inner = list(s.inner())
s_outer = list(s.outer())
s_conj_rl = s.conjugate().row_lengths()
kdiff = (k - self[0])
if (s_outer == []):
spot = 0
else:
spot = s_outer[0]
for i in range(len(s_conj_rl)):
if (s_conj_rl[i] <= kdiff):
spot = i
break
outer = ([(self[0] + spot)] + s_outer[:])
if (spot > 0):
inner = ([spot] + s_inner[:])
else:
inner = s_inner[:]
return SkewPartition([outer, inner])
def to_core(self, k):
"\n Maps the `k`-bounded partition ``self`` to its corresponding `k+1`-core.\n\n See also :meth:`k_skew`.\n\n EXAMPLES::\n\n sage: p = Partition([4,3,2,2,1,1])\n sage: c = p.to_core(4); c\n [9, 5, 3, 2, 1, 1]\n sage: type(c)\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: c.to_bounded_partition() == p\n True\n "
from sage.combinat.core import Core
return Core(self.k_skew(k)[0], (k + 1))
def from_kbounded_to_reduced_word(self, k):
'\n Maps a `k`-bounded partition to a reduced word for an element in\n the affine permutation group.\n\n This uses the fact that there is a bijection between `k`-bounded\n partitions and `(k+1)`-cores and an action of the affine nilCoxeter\n algebra of type `A_k^{(1)}` on `(k+1)`-cores as described in [LM2006b]_.\n\n EXAMPLES::\n\n sage: p = Partition([2,1,1])\n sage: p.from_kbounded_to_reduced_word(2)\n [2, 1, 2, 0]\n sage: p = Partition([3,1])\n sage: p.from_kbounded_to_reduced_word(3)\n [3, 2, 1, 0]\n sage: p.from_kbounded_to_reduced_word(2)\n Traceback (most recent call last):\n ...\n ValueError: the partition must be 2-bounded\n sage: p = Partition([])\n sage: p.from_kbounded_to_reduced_word(2)\n []\n '
p = self.k_skew(k)[0]
result = []
while (not p.is_empty()):
corners = p.corners()
c = (p.content(corners[0][0], corners[0][1]) % (k + 1))
result.append(Integer(c))
list = [x for x in corners if ((p.content(x[0], x[1]) % (k + 1)) == c)]
for x in list:
p = p.remove_cell(x[0])
return result
def from_kbounded_to_grassmannian(self, k):
'\n Maps a `k`-bounded partition to a Grassmannian element in\n the affine Weyl group of type `A_k^{(1)}`.\n\n For details, see the documentation of the method\n :meth:`from_kbounded_to_reduced_word` .\n\n EXAMPLES::\n\n sage: p = Partition([2,1,1])\n sage: p.from_kbounded_to_grassmannian(2) # needs sage.modules\n [-1 1 1]\n [-2 2 1]\n [-2 1 2]\n sage: p = Partition([])\n sage: p.from_kbounded_to_grassmannian(2) # needs sage.modules\n [1 0 0]\n [0 1 0]\n [0 0 1]\n '
return WeylGroup(['A', k, 1]).from_reduced_word(self.from_kbounded_to_reduced_word(k))
def to_list(self):
"\n Return ``self`` as a list.\n\n EXAMPLES::\n\n sage: p = Partition([2,1]).to_list(); p\n [2, 1]\n sage: type(p)\n <class 'list'>\n\n TESTS::\n\n sage: p = Partition([2,1])\n sage: pl = p.to_list()\n sage: pl[0] = 0; p\n [2, 1]\n "
return self._list[:]
def add_vertical_border_strip(self, k):
'\n Return a list of all the partitions that can be obtained by adding\n a vertical border strip of length ``k`` to ``self``.\n\n EXAMPLES::\n\n sage: Partition([]).add_vertical_border_strip(0)\n [[]]\n sage: Partition([3,2,1]).add_vertical_border_strip(0)\n [[3, 2, 1]]\n sage: Partition([]).add_vertical_border_strip(2)\n [[1, 1]]\n sage: Partition([2,2]).add_vertical_border_strip(2)\n [[3, 3], [3, 2, 1], [2, 2, 1, 1]]\n sage: Partition([3,2,2]).add_vertical_border_strip(2)\n [[4, 3, 2], [4, 2, 2, 1], [3, 3, 3], [3, 3, 2, 1], [3, 2, 2, 1, 1]]\n '
if (k == 0):
return [self]
shelf = []
res = []
i = 0
ell = len(self._list)
while (i < ell):
tmp = 1
while (((i + 1) < ell) and (self._list[i] == self._list[(i + 1)])):
tmp += 1
i += 1
if ((i == (ell - 1)) and (i > 0) and (self._list[i] != self._list[(i - 1)])):
tmp = 1
shelf.append(tmp)
i += 1
shelf.append(k)
for iv in IntegerListsBackend_invlex(k, length=len(shelf), ceiling=shelf, check=False)._iter():
tmp = (self._list + ([0] * k))
j = 0
for t in range(len(iv)):
for _ in range(iv[t]):
tmp[j] += 1
j += 1
j = sum(shelf[:(t + 1)])
while (not tmp[(- 1)]):
tmp.pop()
res.append(_Partitions(tmp))
return res
def add_horizontal_border_strip(self, k):
'\n Return a list of all the partitions that can be obtained by adding\n a horizontal border strip of length ``k`` to ``self``.\n\n EXAMPLES::\n\n sage: Partition([]).add_horizontal_border_strip(0)\n [[]]\n sage: Partition([3,2,1]).add_horizontal_border_strip(0)\n [[3, 2, 1]]\n sage: Partition([]).add_horizontal_border_strip(2)\n [[2]]\n sage: Partition([2,2]).add_horizontal_border_strip(2)\n [[4, 2], [3, 2, 1], [2, 2, 2]]\n sage: Partition([3,2,2]).add_horizontal_border_strip(2)\n [[5, 2, 2], [4, 3, 2], [4, 2, 2, 1], [3, 3, 2, 1], [3, 2, 2, 2]]\n '
if (k == 0):
return [self]
L = self._list
res = []
mapping = [0]
shelf = [k]
for i in range((len(L) - 1)):
val = (L[i] - L[(i + 1)])
if (not val):
continue
mapping.append((i + 1))
shelf.append(val)
if L:
mapping.append(len(L))
shelf.append(L[(- 1)])
for iv in IntegerListsBackend_invlex(k, length=len(shelf), ceiling=shelf, check=False)._iter():
tmp = (self._list + [0])
for (i, val) in enumerate(iv):
if val:
tmp[mapping[i]] += val
if (not tmp[(- 1)]):
tmp.pop()
res.append(_Partitions(tmp))
return res
def vertical_border_strip_cells(self, k):
'\n Return a list of all the vertical border strips of length ``k``\n which can be added to ``self``, where each horizontal border strip is\n a ``generator`` of cells.\n\n EXAMPLES::\n\n sage: list(Partition([]).vertical_border_strip_cells(0))\n []\n sage: list(Partition([3,2,1]).vertical_border_strip_cells(0))\n []\n sage: list(Partition([]).vertical_border_strip_cells(2))\n [[(0, 0), (1, 0)]]\n sage: list(Partition([2,2]).vertical_border_strip_cells(2))\n [[(0, 2), (1, 2)],\n [(0, 2), (2, 0)],\n [(2, 0), (3, 0)]]\n sage: list(Partition([3,2,2]).vertical_border_strip_cells(2))\n [[(0, 3), (1, 2)],\n [(0, 3), (3, 0)],\n [(1, 2), (2, 2)],\n [(1, 2), (3, 0)],\n [(3, 0), (4, 0)]]\n '
if (k == 0):
return []
shelf = []
i = 0
ell = len(self._list)
while (i < ell):
tmp = 1
while (((i + 1) < ell) and (self._list[i] == self._list[(i + 1)])):
tmp += 1
i += 1
if ((i == (ell - 1)) and (i > 0) and (self._list[i] != self._list[(i - 1)])):
tmp = 1
shelf.append(tmp)
i += 1
shelf.append(k)
tmp = (self._list + ([0] * k))
for iv in IntegerListsBackend_invlex(k, length=len(shelf), ceiling=shelf, check=False)._iter():
j = 0
current_strip = []
for t in range(len(iv)):
for _ in range(iv[t]):
current_strip.append((j, tmp[j]))
j += 1
j = sum(shelf[:(t + 1)])
(yield current_strip)
def horizontal_border_strip_cells(self, k):
'\n Return a list of all the horizontal border strips of length ``k``\n which can be added to ``self``, where each horizontal border strip is\n a ``generator`` of cells.\n\n EXAMPLES::\n\n sage: list(Partition([]).horizontal_border_strip_cells(0))\n []\n sage: list(Partition([3,2,1]).horizontal_border_strip_cells(0))\n []\n sage: list(Partition([]).horizontal_border_strip_cells(2))\n [[(0, 0), (0, 1)]]\n sage: list(Partition([2,2]).horizontal_border_strip_cells(2))\n [[(0, 2), (0, 3)], [(0, 2), (2, 0)], [(2, 0), (2, 1)]]\n sage: list(Partition([3,2,2]).horizontal_border_strip_cells(2))\n [[(0, 3), (0, 4)],\n [(0, 3), (1, 2)],\n [(0, 3), (3, 0)],\n [(1, 2), (3, 0)],\n [(3, 0), (3, 1)]]\n '
if (k == 0):
return list()
L = self._list
shelf = [k]
mapping = [0]
for i in range((len(L) - 1)):
val = (L[i] - L[(i + 1)])
if (not val):
continue
mapping.append((i + 1))
shelf.append(val)
if L:
mapping.append(len(L))
shelf.append(L[(- 1)])
L.append(0)
for iv in IntegerListsBackend_invlex(k, length=len(shelf), ceiling=shelf, check=False)._iter():
tmp = []
for (i, val) in enumerate(iv):
tmp.extend(((mapping[i], (L[mapping[i]] + j)) for j in range(val)))
(yield tmp)
def remove_horizontal_border_strip(self, k):
'\n Return the partitions obtained from ``self`` by removing an\n horizontal border strip of length ``k``.\n\n EXAMPLES::\n\n sage: Partition([5,3,1]).remove_horizontal_border_strip(0).list()\n [[5, 3, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(1).list()\n [[5, 3], [5, 2, 1], [4, 3, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(2).list()\n [[5, 2], [5, 1, 1], [4, 3], [4, 2, 1], [3, 3, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(3).list()\n [[5, 1], [4, 2], [4, 1, 1], [3, 3], [3, 2, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(4).list()\n [[4, 1], [3, 2], [3, 1, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(5).list()\n [[3, 1]]\n sage: Partition([5,3,1]).remove_horizontal_border_strip(6).list()\n []\n\n The result is returned as an instance of\n :class:`Partitions_with_constraints`::\n\n sage: Partition([5,3,1]).remove_horizontal_border_strip(5)\n The subpartitions of [5, 3, 1] obtained by removing a horizontal border strip of length 5\n\n TESTS::\n\n sage: Partition([3,2,2]).remove_horizontal_border_strip(2).list()\n [[3, 2], [2, 2, 1]]\n sage: Partition([3,2,2]).remove_horizontal_border_strip(2).first().parent()\n The subpartitions of [3, 2, 2] obtained by removing a horizontal border strip of length 2\n sage: Partition([]).remove_horizontal_border_strip(0).list()\n [[]]\n sage: Partition([]).remove_horizontal_border_strip(6).list()\n []\n '
return Partitions_with_constraints(n=(self.size() - k), min_length=(len(self) - 1), max_length=len(self), floor=(self[1:] + [0]), ceiling=self[:], max_slope=0, name=f'The subpartitions of {self} obtained by removing a horizontal border strip of length {k}')
def k_conjugate(self, k):
'\n Return the ``k``-conjugate of ``self``.\n\n The `k`-conjugate is the partition that is given by the columns of\n the `k`-skew diagram of the partition.\n\n We can also define the `k`-conjugate in the following way. Let `P`\n denote the bijection from `(k+1)`-cores to `k`-bounded partitions. The\n `k`-conjugate of a `(k+1)`-core `\\lambda` is\n\n .. MATH::\n\n \\lambda^{(k)} = P^{-1}\\left( (P(\\lambda))^{\\prime} \\right).\n\n EXAMPLES::\n\n sage: p = Partition([4,3,2,2,1,1])\n sage: p.k_conjugate(4)\n [3, 2, 2, 1, 1, 1, 1, 1, 1]\n '
return Partition(self.k_skew(k).conjugate().row_lengths())
def arms_legs_coeff(self, i, j):
'\n This is a statistic on a cell `c = (i,j)` in the diagram of partition\n `p` given by\n\n .. MATH::\n\n \\frac{ 1 - q^a \\cdot t^{\\ell + 1} }{ 1 - q^{a + 1} \\cdot t^{\\ell} }\n\n where `a` is the arm length of `c` and `\\ell` is the leg length of `c`.\n\n The coordinates ``i`` and ``j`` of the cell are understood to be\n `0`-based, so that ``(0, 0)`` is the northwesternmost cell (in\n English notation).\n\n EXAMPLES::\n\n sage: Partition([3,2,1]).arms_legs_coeff(1,1)\n (-t + 1)/(-q + 1)\n sage: Partition([3,2,1]).arms_legs_coeff(0,0)\n (-q^2*t^3 + 1)/(-q^3*t^2 + 1)\n sage: Partition([3,2,1]).arms_legs_coeff(*[0,0])\n (-q^2*t^3 + 1)/(-q^3*t^2 + 1)\n '
QQqt = PolynomialRing(QQ, ['q', 't'])
(q, t) = QQqt.gens()
if ((i < len(self)) and (j < self[i])):
res = (1 - ((q ** self.arm_length(i, j)) * (t ** (self.leg_length(i, j) + 1))))
res /= (1 - ((q ** (self.arm_length(i, j) + 1)) * (t ** self.leg_length(i, j))))
return res
return ZZ.one()
def atom(self):
'\n Return a list of the standard tableaux of size ``self.size()`` whose\n atom is equal to ``self``.\n\n EXAMPLES::\n\n sage: Partition([2,1]).atom()\n [[[1, 2], [3]]]\n sage: Partition([3,2,1]).atom()\n [[[1, 2, 3, 6], [4, 5]], [[1, 2, 3], [4, 5], [6]]]\n '
res = []
for tab in tableau.StandardTableaux_size(self.size()):
if (tab.atom() == self):
res.append(tab)
return res
def k_atom(self, k):
'\n Return a list of the standard tableaux of size ``self.size()`` whose\n ``k``-atom is equal to ``self``.\n\n EXAMPLES::\n\n sage: p = Partition([3,2,1])\n sage: p.k_atom(1)\n []\n sage: p.k_atom(3)\n [[[1, 1, 1, 2, 3], [2]],\n [[1, 1, 1, 3], [2, 2]],\n [[1, 1, 1, 2], [2], [3]],\n [[1, 1, 1], [2, 2], [3]]]\n sage: Partition([3,2,1]).k_atom(4)\n [[[1, 1, 1, 3], [2, 2]], [[1, 1, 1], [2, 2], [3]]]\n\n TESTS::\n\n sage: Partition([1]).k_atom(1)\n [[[1]]]\n sage: Partition([1]).k_atom(2)\n [[[1]]]\n sage: Partition([]).k_atom(1)\n [[]]\n '
res = [tableau.Tableau([])]
for i in range(len(self)):
res = (x.promotion_operator(self[((- i) - 1)]) for x in res)
res = sum(res, [])
res = (y.catabolism_projector(Partition(self[((- i) - 1):]).k_split(k)) for y in res)
res = [i for i in res if i]
return res
def k_split(self, k):
'\n Return the ``k``-split of ``self``.\n\n EXAMPLES::\n\n sage: Partition([4,3,2,1]).k_split(3)\n []\n sage: Partition([4,3,2,1]).k_split(4)\n [[4], [3, 2], [1]]\n sage: Partition([4,3,2,1]).k_split(5)\n [[4, 3], [2, 1]]\n sage: Partition([4,3,2,1]).k_split(6)\n [[4, 3, 2], [1]]\n sage: Partition([4,3,2,1]).k_split(7)\n [[4, 3, 2, 1]]\n sage: Partition([4,3,2,1]).k_split(8)\n [[4, 3, 2, 1]]\n '
if (self == []):
return []
elif (k < self[0]):
return []
else:
res = []
part = list(self)
while (part and (((part[0] + len(part)) - 1) >= k)):
p = (k - part[0])
res.append(part[:(p + 1)])
part = part[(p + 1):]
if part:
res.append(part)
return res
def jacobi_trudi(self):
'\n Return the Jacobi-Trudi matrix of ``self`` thought of as a skew\n partition. See :meth:`SkewPartition.jacobi_trudi()\n <sage.combinat.skew_partition.SkewPartition.jacobi_trudi>`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: part = Partition([3,2,1])\n sage: jt = part.jacobi_trudi(); jt\n [h[3] h[1] 0]\n [h[4] h[2] h[]]\n [h[5] h[3] h[1]]\n sage: s = SymmetricFunctions(QQ).schur()\n sage: h = SymmetricFunctions(QQ).homogeneous()\n sage: h( s(part) )\n h[3, 2, 1] - h[3, 3] - h[4, 1, 1] + h[5, 1]\n sage: jt.det()\n h[3, 2, 1] - h[3, 3] - h[4, 1, 1] + h[5, 1]\n '
return SkewPartition([self, []]).jacobi_trudi()
def character_polynomial(self):
'\n Return the character polynomial associated to the partition ``self``.\n\n The character polynomial `q_\\mu` associated to a partition `\\mu`\n is defined by\n\n .. MATH::\n\n q_\\mu(x_1, x_2, \\ldots, x_k) = \\downarrow \\sum_{\\alpha \\vdash k}\n \\frac{ \\chi^\\mu_\\alpha }{1^{a_1}2^{a_2}\\cdots k^{a_k}a_1!a_2!\\cdots\n a_k!} \\prod_{i=1}^{k} (ix_i-1)^{a_i}\n\n where `k` is the size of `\\mu`, and `a_i` is the multiplicity of\n `i` in `\\alpha`.\n\n It is computed in the following manner:\n\n 1. Expand the Schur function `s_\\mu` in the power-sum basis,\n\n 2. Replace each `p_i` with `ix_i-1`,\n\n 3. Apply the umbral operator `\\downarrow` to the resulting polynomial.\n\n EXAMPLES::\n\n sage: Partition([1]).character_polynomial() # needs sage.modules\n x - 1\n sage: Partition([1,1]).character_polynomial() # needs sage.modules\n 1/2*x0^2 - 3/2*x0 - x1 + 1\n sage: Partition([2,1]).character_polynomial() # needs sage.modules\n 1/3*x0^3 - 2*x0^2 + 8/3*x0 - x2\n '
k = self.size()
P = PolynomialRing(QQ, k, 'x')
x = P.gens()
from sage.combinat.sf.sf import SymmetricFunctions
Sym = SymmetricFunctions(QQ)
s = Sym.schur()
p = Sym.power()
ps_mu = p(s(self))
items = ps_mu.monomial_coefficients().items()
partition_to_monomial = (lambda part: prod([((i * x[(i - 1)]) - 1) for i in part]))
res = [[partition_to_monomial(mc[0]), mc[1]] for mc in items]
res = [prod(pair) for pair in res]
res = sum(res)
from sage.combinat.misc import umbral_operation
return umbral_operation(res)
def dimension(self, smaller=None, k=1):
'\n Return the number of paths from the ``smaller`` partition to\n the partition ``self``, where each step consists of adding a\n `k`-ribbon while keeping a partition.\n\n Note that a 1-ribbon is just a single cell, so this counts paths\n in the Young graph when `k = 1`.\n\n Note also that the default case (`k = 1` and ``smaller = []``)\n gives the dimension of the irreducible representation of the\n symmetric group corresponding to ``self``.\n\n INPUT:\n\n - ``smaller`` -- a partition (default: an empty list ``[]``)\n\n - `k` -- a positive integer (default: 1)\n\n OUTPUT:\n\n The number of such paths\n\n EXAMPLES:\n\n Looks at the number of ways of getting from ``[5,4]`` to the empty\n partition, removing one cell at a time::\n\n sage: mu = Partition([5,4])\n sage: mu.dimension()\n 42\n\n Same, but removing one 3-ribbon at a time. Note that the 3-core of\n ``mu`` is empty::\n\n sage: mu.dimension(k=3)\n 3\n\n The 2-core of ``mu`` is not the empty partition::\n\n sage: mu.dimension(k=2)\n 0\n\n Indeed, the 2-core of ``mu`` is ``[1]``::\n\n sage: mu.dimension(Partition([1]),k=2)\n 2\n\n TESTS:\n\n Checks that the sum of squares of dimensions of characters of the\n symmetric group is the order of the group::\n\n sage: all(sum(mu.dimension()^2 for mu in Partitions(i))==factorial(i) for i in range(10))\n True\n\n A check coming from the theory of `k`-differentiable posets::\n\n sage: k = 2; core = Partition([2,1])\n sage: all(sum(mu.dimension(core,k=2)^2\n ....: for mu in Partitions(3+i*2) if mu.core(2) == core)\n ....: == 2^i*factorial(i) for i in range(10))\n True\n\n Checks that the dimension satisfies the obvious recursion relation::\n\n sage: test = lambda larger, smaller: larger.dimension(smaller) == sum(mu.dimension(smaller) for mu in larger.down())\n sage: all(test(larger,smaller) for l in range(1,8) for s in range(8)\n ....: for larger in Partitions(l) for smaller in Partitions(s) if smaller != larger)\n True\n\n ALGORITHM:\n\n Depending on the parameters given, different simplifications\n occur. When `k=1` and ``smaller`` is empty, this function uses\n the hook formula. When `k=1` and ``smaller`` is not empty, it\n uses a formula from [ORV]_.\n\n When `k \\neq 1`, we first check that both ``self`` and\n ``smaller`` have the same `k`-core, then use the `k`-quotients\n and the same algorithm on each of the `k`-quotients.\n\n AUTHORS:\n\n - Paul-Olivier Dehaye (2011-06-07)\n '
larger = self
if (smaller is None):
smaller = Partition([])
if (k == 1):
if (smaller == Partition([])):
return (factorial(larger.size()) / prod(larger.hooks()))
elif (not larger.contains(smaller)):
return 0
else:
def inv_factorial(i):
if (i < 0):
return 0
else:
return (1 / factorial(i))
len_range = list(range(larger.length()))
from sage.matrix.constructor import matrix
M = matrix(QQ, [[inv_factorial((((larger.get_part(i) - smaller.get_part(j)) - i) + j)) for i in len_range] for j in len_range])
return (factorial((larger.size() - smaller.size())) * M.determinant())
else:
larger_core = larger.core(k)
smaller_core = smaller.core(k)
if (smaller_core != larger_core):
return 0
larger_quotients = larger.quotient(k)
smaller_quotients = smaller.quotient(k)
def multinomial_with_partitions(sizes, path_counts):
return (prod(path_counts) * multinomial(sizes))
sizes = [(larger_quotients[i].size() - smaller_quotients[i].size()) for i in range(k)]
path_counts = [larger_quotients[i].dimension(smaller_quotients[i]) for i in range(k)]
return multinomial_with_partitions(sizes, path_counts)
def plancherel_measure(self):
'\n Return the probability of ``self`` under the Plancherel probability\n measure on partitions of the same size.\n\n This probability distribution comes from the uniform distribution\n on permutations via the Robinson-Schensted correspondence.\n\n See :wikipedia:`Plancherel\\_measure`\n and :meth:`Partitions_n.random_element_plancherel`.\n\n EXAMPLES::\n\n sage: Partition([]).plancherel_measure()\n 1\n sage: Partition([1]).plancherel_measure()\n 1\n sage: Partition([2]).plancherel_measure()\n 1/2\n sage: [mu.plancherel_measure() for mu in Partitions(3)]\n [1/6, 2/3, 1/6]\n sage: Partition([5,4]).plancherel_measure()\n 7/1440\n\n TESTS::\n\n sage: all(sum(mu.plancherel_measure() for mu in Partitions(n))==1 for n in range(10))\n True\n '
return ((self.dimension() ** 2) / factorial(self.size()))
def outline(self, variable=None):
'\n Return the outline of the partition ``self``.\n\n This is a piecewise linear function, normalized so that the area\n under the partition ``[1]`` is 2.\n\n INPUT:\n\n - variable -- a variable (default: ``\'x\'`` in the symbolic ring)\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: [Partition([5,4]).outline()(x=i) for i in range(-10,11)]\n [10, 9, 8, 7, 6, 5, 6, 5, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n sage: Partition([]).outline()\n abs(x)\n sage: Partition([1]).outline()\n abs(x + 1) + abs(x - 1) - abs(x)\n sage: y = SR.var("y")\n sage: Partition([6,5,1]).outline(variable=y)\n abs(y + 6) - abs(y + 5) + abs(y + 4) - abs(y + 3)\n + abs(y - 1) - abs(y - 2) + abs(y - 3)\n\n TESTS::\n\n sage: integrate(Partition([1]).outline()-abs(x),(x,-10,10)) # needs sage.symbolic\n 2\n '
if (variable is None):
variable = var('x')
outside_contents = [self.content(*c) for c in self.outside_corners()]
inside_contents = [self.content(*c) for c in self.corners()]
return (sum((abs((variable + c)) for c in outside_contents)) - sum((abs((variable + c)) for c in inside_contents)))
def dual_equivalence_graph(self, directed=False, coloring=None):
"\n Return the dual equivalence graph of ``self``.\n\n Two permutations `p` and `q` in the symmetric group `S_n`\n differ by an `i`-*elementary dual equivalence (or dual Knuth)\n relation* (where `i` is an integer with `1 < i < n`) when the\n following two conditions are satisfied:\n\n - In the one-line notation of the permutation `p`, the letter\n `i` does not appear inbetween `i-1` and `i+1`.\n\n - The permutation `q` is obtained from `p` by switching two\n of the three letters `i-1, i, i+1` (in its one-line\n notation) -- namely, the leftmost and the rightmost one\n in order of their appearance in `p`.\n\n Notice that this is equivalent to the statement that the\n permutations `p^{-1}` and `q^{-1}` differ by an elementary\n Knuth equivalence at positions `i-1, i, i+1`.\n\n Two standard Young tableaux of shape `\\lambda` differ by an\n `i`-elementary dual equivalence relation (of color `i`), if\n their reading words differ by an `i`-elementary dual\n equivalence relation.\n\n The *dual equivalence graph* of the partition `\\lambda` is the\n edge-colored graph whose vertices are the standard Young\n tableaux of shape `\\lambda`, and whose edges colored by `i` are\n given by the `i`-elementary dual equivalences.\n\n INPUT:\n\n - ``directed`` -- (default: ``False``) whether to have the dual\n equivalence graph be directed (where we have a directed edge\n `S \\to T` if `i` appears to the left of `i+1` in the\n reading word of `T`; otherwise we have the directed edge\n `T \\to S`)\n\n - ``coloring`` -- (optional) a function which sends each\n integer `i > 1` to a color (as a string, e.g., ``'red'`` or\n ``'black'``) to be used when visually representing the\n resulting graph using dot2tex; the default choice is\n ``2 -> 'red', 3 -> 'blue', 4 -> 'green', 5 -> 'purple',\n 6 -> 'brown', 7 -> 'orange', 8 -> 'yellow', anything greater\n than 8 -> 'black'``.\n\n REFERENCES:\n\n - [As2008b]_\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: P = Partition([3,1,1])\n sage: G = P.dual_equivalence_graph()\n sage: G.edges(sort=True)\n [([[1, 2, 3], [4], [5]], [[1, 2, 4], [3], [5]], 3),\n ([[1, 2, 4], [3], [5]], [[1, 2, 5], [3], [4]], 4),\n ([[1, 2, 4], [3], [5]], [[1, 3, 4], [2], [5]], 2),\n ([[1, 2, 5], [3], [4]], [[1, 3, 5], [2], [4]], 2),\n ([[1, 3, 4], [2], [5]], [[1, 3, 5], [2], [4]], 4),\n ([[1, 3, 5], [2], [4]], [[1, 4, 5], [2], [3]], 3)]\n sage: G = P.dual_equivalence_graph(directed=True)\n sage: G.edges(sort=True)\n [([[1, 2, 4], [3], [5]], [[1, 2, 3], [4], [5]], 3),\n ([[1, 2, 5], [3], [4]], [[1, 2, 4], [3], [5]], 4),\n ([[1, 3, 4], [2], [5]], [[1, 2, 4], [3], [5]], 2),\n ([[1, 3, 5], [2], [4]], [[1, 2, 5], [3], [4]], 2),\n ([[1, 3, 5], [2], [4]], [[1, 3, 4], [2], [5]], 4),\n ([[1, 4, 5], [2], [3]], [[1, 3, 5], [2], [4]], 3)]\n\n TESTS::\n\n sage: # needs sage.graphs\n sage: G = Partition([1]).dual_equivalence_graph()\n sage: G.vertices(sort=False)\n [[[1]]]\n sage: G = Partition([]).dual_equivalence_graph()\n sage: G.vertices(sort=False)\n [[]]\n sage: P = Partition([3,1,1])\n sage: G = P.dual_equivalence_graph(coloring=lambda x: 'red')\n sage: G2 = P.dual_equivalence_graph(coloring={2: 'black', 3: 'blue',\n ....: 4: 'cyan', 5: 'grey'})\n sage: G is G2\n False\n sage: G == G2\n True\n "
try:
if directed:
G = self._DDEG.copy(immutable=False)
else:
G = self._DEG.copy(immutable=False)
if have_dot2tex():
if (coloring is None):
d = {2: 'red', 3: 'blue', 4: 'green', 5: 'purple', 6: 'brown', 7: 'orange', 8: 'yellow'}
def coloring(i):
if (i in d):
return d[i]
return 'black'
elif isinstance(coloring, dict):
d = coloring
coloring = (lambda x: d[x])
G.set_latex_options(format='dot2tex', edge_labels=True, color_by_label=coloring)
return G
except AttributeError:
pass
T = list(tableau.StandardTableaux(self))
n = sum(self)
edges = []
to_perms = {t: t.reading_word_permutation() for t in T}
to_tab = {to_perms[k]: k for k in to_perms}
Perm = permutation.Permutations()
for t in T:
pt = list(to_perms[t])
for i in range(2, n):
ii = pt.index(i)
iip = pt.index((i + 1))
iim = pt.index((i - 1))
l = sorted([iim, ii, iip])
if (l[0] != ii):
continue
x = pt[:]
(x[l[0]], x[l[2]]) = (x[l[2]], x[l[0]])
if (ii < iip):
e = [t, to_tab[Perm(x)], i]
edges.append(e)
else:
e = [to_tab[Perm(x)], t, i]
edges.append(e)
if directed:
from sage.graphs.digraph import DiGraph
self._DDEG = DiGraph([T, edges], format='vertices_and_edges', immutable=True, multiedges=True)
else:
from sage.graphs.graph import Graph
self._DEG = Graph([T, edges], format='vertices_and_edges', immutable=True, multiedges=True)
return self.dual_equivalence_graph(directed, coloring)
def specht_module(self, base_ring=None):
'\n Return the Specht module corresponding to ``self``.\n\n EXAMPLES::\n\n sage: SM = Partition([2,2,1]).specht_module(QQ); SM\n Specht module of [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)] over Rational Field\n sage: s = SymmetricFunctions(QQ).s()\n sage: s(SM.frobenius_image()) # needs sage.modules\n s[2, 2, 1]\n '
from sage.combinat.specht_module import SpechtModule
from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra
if (base_ring is None):
from sage.rings.rational_field import QQ
base_ring = QQ
R = SymmetricGroupAlgebra(base_ring, sum(self))
return SpechtModule(R, self)
def specht_module_dimension(self, base_ring=None):
'\n Return the dimension of the Specht module corresponding to ``self``.\n\n This is equal to the number of standard tableaux of shape ``self`` when\n over a field of characteristic `0`.\n\n INPUT:\n\n - ``base_ring`` -- (default: `\\QQ`) the base ring\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).specht_module_dimension()\n 5\n sage: Partition([2,2,1]).specht_module_dimension(GF(2)) # needs sage.rings.finite_rings\n 5\n '
from sage.categories.fields import Fields
if ((base_ring is None) or ((base_ring in Fields()) and (base_ring.characteristic() == 0))):
from sage.combinat.tableau import StandardTableaux
return StandardTableaux(self).cardinality()
from sage.combinat.specht_module import specht_module_rank
return specht_module_rank(self, base_ring)
def simple_module_dimension(self, base_ring=None):
'\n Return the dimension of the simple module corresponding to ``self``.\n\n When the base ring is a field of characteristic `0`, this is equal\n to the dimension of the Specht module.\n\n INPUT:\n\n - ``base_ring`` -- (default: `\\QQ`) the base ring\n\n EXAMPLES::\n\n sage: Partition([2,2,1]).simple_module_dimension()\n 5\n sage: Partition([2,2,1]).specht_module_dimension(GF(3)) # needs sage.rings.finite_rings\n 5\n sage: Partition([2,2,1]).simple_module_dimension(GF(3)) # needs sage.rings.finite_rings\n 4\n\n sage: for la in Partitions(6, regular=3):\n ....: print(la, la.specht_module_dimension(), la.simple_module_dimension(GF(3)))\n [6] 1 1\n [5, 1] 5 4\n [4, 2] 9 9\n [4, 1, 1] 10 6\n [3, 3] 5 1\n [3, 2, 1] 16 4\n [2, 2, 1, 1] 9 9\n '
from sage.categories.fields import Fields
if ((base_ring is None) or ((base_ring in Fields()) and (base_ring.characteristic() == 0))):
from sage.combinat.tableau import StandardTableaux
return StandardTableaux(self).cardinality()
from sage.combinat.specht_module import simple_module_rank
return simple_module_rank(self, base_ring)
|
class Partitions(UniqueRepresentation, Parent):
"\n ``Partitions(n, **kwargs)`` returns the combinatorial class of\n integer partitions of `n` subject to the constraints given by the\n keywords.\n\n Valid keywords are: ``starting``, ``ending``, ``min_part``,\n ``max_part``, ``max_length``, ``min_length``, ``length``,\n ``max_slope``, ``min_slope``, ``inner``, ``outer``, ``parts_in``,\n ``regular``, and ``restricted``. They have the following meanings:\n\n - ``starting=p`` specifies that the partitions should all be less\n than or equal to `p` in lex order. This argument cannot be combined\n with any other (see :trac:`15467`).\n\n - ``ending=p`` specifies that the partitions should all be greater than\n or equal to `p` in lex order. This argument cannot be combined with any\n other (see :trac:`15467`).\n\n - ``length=k`` specifies that the partitions have\n exactly `k` parts.\n\n - ``min_length=k`` specifies that the partitions have\n at least `k` parts.\n\n - ``min_part=k`` specifies that all parts of the\n partitions are at least `k`.\n\n - ``inner=p`` specifies that the partitions must contain the\n partition `p`.\n\n - ``outer=p`` specifies that the partitions\n be contained inside the partition `p`.\n\n - ``min_slope=k`` specifies that the partitions have slope at least\n `k`; the slope at position `i` is the difference between the\n `(i+1)`-th part and the `i`-th part.\n\n - ``parts_in=S`` specifies that the partitions have parts in the set\n `S`, which can be any sequence of pairwise distinct positive\n integers. This argument cannot be combined with any other\n (see :trac:`15467`).\n\n - ``regular=ell`` specifies that the partitions are `\\ell`-regular,\n and can only be combined with the ``max_length`` or ``max_part``, but\n not both, keywords if `n` is not specified\n\n - ``restricted=ell`` specifies that the partitions are `\\ell`-restricted,\n and cannot be combined with any other keywords\n\n The ``max_*`` versions, along with ``inner`` and ``ending``, work\n analogously.\n\n Right now, the ``parts_in``, ``starting``, ``ending``, ``regular``, and\n ``restricted`` keyword arguments are mutually exclusive, both of each\n other and of other keyword arguments. If you specify, say, ``parts_in``,\n all other keyword arguments will be ignored; ``starting``, ``ending``,\n ``regular``, and ``restricted`` work the same way.\n\n EXAMPLES:\n\n If no arguments are passed, then the combinatorial class\n of all integer partitions is returned::\n\n sage: Partitions()\n Partitions\n sage: [2,1] in Partitions()\n True\n\n If an integer `n` is passed, then the combinatorial class of integer\n partitions of `n` is returned::\n\n sage: Partitions(3)\n Partitions of the integer 3\n sage: Partitions(3).list()\n [[3], [2, 1], [1, 1, 1]]\n\n If ``starting=p`` is passed, then the combinatorial class of partitions\n greater than or equal to `p` in lexicographic order is returned::\n\n sage: Partitions(3, starting=[2,1])\n Partitions of the integer 3 starting with [2, 1]\n sage: Partitions(3, starting=[2,1]).list()\n [[2, 1], [1, 1, 1]]\n\n If ``ending=p`` is passed, then the combinatorial class of\n partitions at most `p` in lexicographic order is returned::\n\n sage: Partitions(3, ending=[2,1])\n Partitions of the integer 3 ending with [2, 1]\n sage: Partitions(3, ending=[2,1]).list()\n [[3], [2, 1]]\n\n Using ``max_slope=-1`` yields partitions into distinct parts -- each\n part differs from the next by at least 1. Use a different\n ``max_slope`` to get parts that differ by, say, 2::\n\n sage: Partitions(7, max_slope=-1).list()\n [[7], [6, 1], [5, 2], [4, 3], [4, 2, 1]]\n sage: Partitions(15, max_slope=-1).cardinality()\n 27\n\n The number of partitions of `n` into odd parts equals the number of\n partitions into distinct parts. Let's test that for `n` from 10 to 20::\n\n sage: def test(n):\n ....: return (Partitions(n, max_slope=-1).cardinality()\n ....: == Partitions(n, parts_in=[1,3..n]).cardinality())\n sage: all(test(n) for n in [10..20]) # needs sage.libs.gap\n True\n\n The number of partitions of `n` into distinct parts that differ by\n at least 2 equals the number of partitions into parts that equal 1\n or 4 modulo 5; this is one of the Rogers-Ramanujan identities::\n\n sage: def test(n):\n ....: return (Partitions(n, max_slope=-2).cardinality()\n ....: == Partitions(n, parts_in=([1,6..n] + [4,9..n])).cardinality())\n sage: all(test(n) for n in [10..20]) # needs sage.libs.gap\n True\n\n Here are some more examples illustrating ``min_part``, ``max_part``,\n and ``length``::\n\n sage: Partitions(5,min_part=2)\n Partitions of the integer 5 satisfying constraints min_part=2\n sage: Partitions(5,min_part=2).list()\n [[5], [3, 2]]\n\n ::\n\n sage: Partitions(3,max_length=2).list()\n [[3], [2, 1]]\n\n ::\n\n sage: Partitions(10, min_part=2, length=3).list()\n [[6, 2, 2], [5, 3, 2], [4, 4, 2], [4, 3, 3]]\n\n Some examples using the ``regular`` keyword::\n\n sage: Partitions(regular=4)\n 4-Regular Partitions\n sage: Partitions(regular=4, max_length=3)\n 4-Regular Partitions with max length 3\n sage: Partitions(regular=4, max_part=3)\n 4-Regular 3-Bounded Partitions\n sage: Partitions(3, regular=4)\n 4-Regular Partitions of the integer 3\n\n Some examples using the ``restricted`` keyword::\n\n sage: Partitions(restricted=4)\n 4-Restricted Partitions\n sage: Partitions(3, restricted=4)\n 4-Restricted Partitions of the integer 3\n\n Here are some further examples using various constraints::\n\n sage: [x for x in Partitions(4)]\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: [x for x in Partitions(4, length=2)]\n [[3, 1], [2, 2]]\n sage: [x for x in Partitions(4, min_length=2)]\n [[3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: [x for x in Partitions(4, max_length=2)]\n [[4], [3, 1], [2, 2]]\n sage: [x for x in Partitions(4, min_length=2, max_length=2)]\n [[3, 1], [2, 2]]\n sage: [x for x in Partitions(4, max_part=2)]\n [[2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: [x for x in Partitions(4, min_part=2)]\n [[4], [2, 2]]\n sage: [x for x in Partitions(4, outer=[3,1,1])]\n [[3, 1], [2, 1, 1]]\n sage: [x for x in Partitions(4, outer=[infinity, 1, 1])]\n [[4], [3, 1], [2, 1, 1]]\n sage: [x for x in Partitions(4, inner=[1,1,1])]\n [[2, 1, 1], [1, 1, 1, 1]]\n sage: [x for x in Partitions(4, max_slope=-1)]\n [[4], [3, 1]]\n sage: [x for x in Partitions(4, min_slope=-1)]\n [[4], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: [x for x in Partitions(11, max_slope=-1, min_slope=-3, min_length=2, max_length=4)]\n [[7, 4], [6, 5], [6, 4, 1], [6, 3, 2], [5, 4, 2], [5, 3, 2, 1]]\n sage: [x for x in Partitions(11, max_slope=-1, min_slope=-3, min_length=2, max_length=4, outer=[6,5,2])]\n [[6, 5], [6, 4, 1], [6, 3, 2], [5, 4, 2]]\n\n Note that if you specify ``min_part=0``, then it will treat the minimum\n part as being 1 (see :trac:`13605`)::\n\n sage: [x for x in Partitions(4, length=3, min_part=0)]\n [[2, 1, 1]]\n sage: [x for x in Partitions(4, min_length=3, min_part=0)]\n [[2, 1, 1], [1, 1, 1, 1]]\n\n Except for very special cases, counting is done by brute force iteration\n through all the partitions. However the iteration itself has a reasonable\n complexity (see :class:`IntegerListsLex`), which allows for\n manipulating large partitions::\n\n sage: Partitions(1000, max_length=1).list()\n [[1000]]\n\n In particular, getting the first element is also constant time::\n\n sage: Partitions(30, max_part=29).first()\n [29, 1]\n\n TESTS::\n\n sage: TestSuite(Partitions(0)).run() # needs sage.libs.flint\n sage: TestSuite(Partitions(5)).run() # needs sage.libs.flint\n sage: TestSuite(Partitions(5, min_part=2)).run() # needs sage.libs.flint\n\n sage: repr( Partitions(5, min_part=2) )\n 'Partitions of the integer 5 satisfying constraints min_part=2'\n\n sage: P = Partitions(5, min_part=2)\n sage: P.first().parent()\n Partitions...\n sage: [2,1] in P\n False\n sage: [2,2,1] in P\n False\n sage: [3,2] in P\n True\n\n sage: Partitions(5, inner=[2,1], min_length=3).list()\n [[3, 1, 1], [2, 2, 1], [2, 1, 1, 1]]\n sage: Partitions(5, inner=Partition([2,2]), min_length=3).list()\n [[2, 2, 1]]\n sage: Partitions(7, inner=(2, 2), min_length=3).list()\n [[4, 2, 1], [3, 3, 1], [3, 2, 2], [3, 2, 1, 1], [2, 2, 2, 1], [2, 2, 1, 1, 1]]\n sage: Partitions(5, inner=[2,0,0,0,0,0]).list()\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1]]\n sage: Partitions(6, length=2, max_slope=-1).list()\n [[5, 1], [4, 2]]\n\n sage: Partitions(length=2, max_slope=-1).list()\n Traceback (most recent call last):\n ...\n ValueError: the size must be specified with any keyword argument\n\n sage: Partitions(max_part = 3)\n 3-Bounded Partitions\n\n Check that :trac:`14145` has been fixed::\n\n sage: 1 in Partitions()\n False\n\n Check :trac:`15467`::\n\n sage: Partitions(5,parts_in=[1,2,3,4], length=4)\n Traceback (most recent call last):\n ...\n ValueError: the parameters 'parts_in', 'starting' and 'ending' cannot be combined with anything else\n sage: Partitions(5,starting=[3,2], length=2)\n Traceback (most recent call last):\n ...\n ValueError: the parameters 'parts_in', 'starting' and 'ending' cannot be combined with anything else\n sage: Partitions(5,ending=[3,2], length=2)\n Traceback (most recent call last):\n ...\n ValueError: the parameters 'parts_in', 'starting' and 'ending' cannot be combined with anything else\n sage: Partitions(NN, length=2)\n Traceback (most recent call last):\n ...\n ValueError: the size must be specified with any keyword argument\n sage: Partitions(('la','la','laaaa'), max_part=8)\n Traceback (most recent call last):\n ...\n ValueError: n must be an integer or be equal to one of None, NN, NonNegativeIntegers()\n\n Check that calling ``Partitions`` with ``outer=a`` no longer\n mutates ``a`` (:trac:`16234`)::\n\n sage: a = [4,3,2,1,1,1,1]\n sage: for p in Partitions(8, outer=a, min_slope=-1):\n ....: print(p)\n [3, 3, 2]\n [3, 2, 2, 1]\n [3, 2, 1, 1, 1]\n [2, 2, 2, 1, 1]\n [2, 2, 1, 1, 1, 1]\n [2, 1, 1, 1, 1, 1, 1]\n sage: a\n [4, 3, 2, 1, 1, 1, 1]\n\n Check that ``inner`` and ``outer`` indeed accept a partition as\n argument (:trac:`18423`)::\n\n sage: P = Partitions(5, inner=Partition([2,1]), outer=Partition([3,2])); P\n Partitions of the integer 5 satisfying constraints inner=[2, 1], outer=[3, 2]\n sage: P.list()\n [[3, 2]]\n "
@staticmethod
def __classcall_private__(cls, n=None, **kwargs):
'\n Return the correct parent based upon the input.\n\n TESTS::\n\n sage: P = Partitions()\n sage: P2 = Partitions(NN)\n sage: P is P2\n True\n sage: P2 = Partitions(NonNegativeIntegers())\n sage: P is P2\n True\n sage: P = Partitions(4)\n sage: P2 = Partitions(int(4))\n sage: P is P2\n True\n\n Check that :trac:`17898` is fixed::\n\n sage: P = Partitions(5, min_slope=0)\n sage: list(P)\n [[5], [1, 1, 1, 1, 1]]\n '
if (n == infinity):
raise ValueError('n cannot be infinite')
if isinstance(n, (int, Integer)):
if (len(kwargs) == 0):
return Partitions_n(n)
if (len(kwargs) == 1):
if ('max_part' in kwargs):
return PartitionsGreatestLE(n, kwargs['max_part'])
if ('length' in kwargs):
return Partitions_nk(n, kwargs['length'])
if ((len(kwargs) > 1) and (('parts_in' in kwargs) or ('starting' in kwargs) or ('ending' in kwargs))):
raise ValueError(("the parameters 'parts_in', 'starting' and " + "'ending' cannot be combined with anything else"))
if ('parts_in' in kwargs):
return Partitions_parts_in(n, kwargs['parts_in'])
elif ('starting' in kwargs):
return Partitions_starting(n, kwargs['starting'])
elif ('ending' in kwargs):
return Partitions_ending(n, kwargs['ending'])
elif ('regular' in kwargs):
return RegularPartitions_n(n, kwargs['regular'])
elif ('restricted' in kwargs):
return RestrictedPartitions_n(n, kwargs['restricted'])
kwargs['name'] = ('Partitions of the integer %s satisfying constraints %s' % (n, ', '.join([('%s=%s' % (key, kwargs[key])) for key in sorted(kwargs)])))
kwargs['min_part'] = max(1, kwargs.get('min_part', 1))
kwargs['max_slope'] = min(0, kwargs.get('max_slope', 0))
if (kwargs.get('min_slope', (- float('inf'))) > 0):
raise ValueError('the minimum slope must be non-negative')
if ('outer' in kwargs):
kwargs['max_length'] = min(len(kwargs['outer']), kwargs.get('max_length', infinity))
kwargs['ceiling'] = tuple(kwargs['outer'])
del kwargs['outer']
if ('inner' in kwargs):
inner = [x for x in kwargs['inner'] if (x > 0)]
kwargs['floor'] = inner
kwargs['min_length'] = max(len(inner), kwargs.get('min_length', 0))
del kwargs['inner']
return Partitions_with_constraints(n, **kwargs)
elif ((n is None) or (n is NN) or (n is NonNegativeIntegers())):
if (len(kwargs) > 0):
if (len(kwargs) == 1):
if ('max_part' in kwargs):
return Partitions_all_bounded(kwargs['max_part'])
if ('regular' in kwargs):
return RegularPartitions_all(kwargs['regular'])
if ('restricted' in kwargs):
return RestrictedPartitions_all(kwargs['restricted'])
elif (len(kwargs) == 2):
if ('regular' in kwargs):
if ((kwargs['regular'] < 1) or (kwargs['regular'] not in ZZ)):
raise ValueError('the regularity must be a positive integer')
if ('max_part' in kwargs):
return RegularPartitions_bounded(kwargs['regular'], kwargs['max_part'])
if ('max_length' in kwargs):
return RegularPartitions_truncated(kwargs['regular'], kwargs['max_length'])
raise ValueError('the size must be specified with any keyword argument')
return Partitions_all()
raise ValueError('n must be an integer or be equal to one of None, NN, NonNegativeIntegers()')
def __init__(self, is_infinite=False):
'\n Initialize ``self``.\n\n INPUT:\n\n - ``is_infinite`` -- (Default: ``False``) If ``True``, then the number\n of partitions in this set is infinite.\n\n EXAMPLES::\n\n sage: Partitions()\n Partitions\n sage: Partitions(2)\n Partitions of the integer 2\n '
if is_infinite:
Parent.__init__(self, category=InfiniteEnumeratedSets())
else:
Parent.__init__(self, category=FiniteEnumeratedSets())
Element = Partition
class options(GlobalOptions):
'\n Sets and displays the global options for elements of the partition,\n skew partition, and partition tuple classes. If no parameters are\n set, then the function returns a copy of the options dictionary.\n\n The ``options`` to partitions can be accessed as the method\n :obj:`Partitions.options` of :class:`Partitions` and\n related parent classes.\n\n @OPTIONS@\n\n EXAMPLES::\n\n sage: P = Partition([4,2,2,1])\n sage: P\n [4, 2, 2, 1]\n sage: Partitions.options.display="exp"\n sage: P\n 1, 2^2, 4\n sage: Partitions.options.display="exp_high"\n sage: P\n 4, 2^2, 1\n\n It is also possible to use user defined functions for the ``display`` and\n ``latex`` options::\n\n sage: Partitions.options(display=lambda mu: \'<%s>\' % \',\'.join(\'%s\'%m for m in mu._list)); P\n <4,2,2,1>\n sage: Partitions.options(latex=lambda mu: \'\\\\Diagram{%s}\' % \',\'.join(\'%s\'%m for m in mu._list)); latex(P)\n \\Diagram{4,2,2,1}\n sage: Partitions.options(display="diagram", diagram_str="#")\n sage: P\n ####\n ##\n ##\n #\n sage: Partitions.options(diagram_str="*", convention="french")\n sage: print(P.ferrers_diagram())\n *\n **\n **\n ****\n\n Changing the ``convention`` for partitions also changes the ``convention``\n option for tableaux and vice versa::\n\n sage: T = Tableau([[1,2,3],[4,5]])\n sage: T.pp()\n 4 5\n 1 2 3\n sage: Tableaux.options.convention="english"\n sage: print(P.ferrers_diagram())\n ****\n **\n **\n *\n sage: T.pp()\n 1 2 3\n 4 5\n sage: Partitions.options._reset()\n '
NAME = 'Partitions'
module = 'sage.combinat.partition'
display = dict(default='list', description='Specifies how partitions should be printed', values=dict(list='displayed as a list', exp_low='in exponential form (lowest first)', exp_high='in exponential form (highest first)', diagram='as a Ferrers diagram', compact_low='compact form of ``exp_low``', compact_high='compact form of ``exp_high``'), alias=dict(exp='exp_low', compact='compact_low', array='diagram', ferrers_diagram='diagram', young_diagram='diagram'), case_sensitive=False)
latex = dict(default='young_diagram', description='Specifies how partitions should be latexed', values=dict(diagram='latex as a Ferrers diagram', young_diagram='latex as a Young diagram', list='latex as a list', exp_high='latex as a list in exponential notation (highest first)', exp_low='as a list latex in exponential notation (lowest first)'), alias=dict(exp='exp_low', array='diagram', ferrers_diagram='diagram'), case_sensitive=False)
diagram_str = dict(default='*', description='The character used for the cells when printing Ferrers diagrams', checker=(lambda char: isinstance(char, str)))
latex_diagram_str = dict(default='\\ast', description='The character used for the cells when latexing Ferrers diagrams', checker=(lambda char: isinstance(char, str)))
convention = dict(link_to=(tableau.Tableaux.options, 'convention'))
notation = dict(alt_name='convention')
def __reversed__(self):
'\n A reversed iterator.\n\n EXAMPLES::\n\n sage: [x for x in reversed(Partitions(4))]\n [[1, 1, 1, 1], [2, 1, 1], [2, 2], [3, 1], [4]]\n '
if (not self.is_finite()):
raise NotImplementedError('the set is infinite, so this needs a custom reverse iterator')
for i in reversed(range(self.cardinality())):
(yield self[i])
def _element_constructor_(self, lst):
'\n Construct an element with ``self`` as parent.\n\n EXAMPLES::\n\n sage: P = Partitions()\n sage: p = P([3,3,1]); p\n [3, 3, 1]\n sage: P(p) is p\n True\n sage: P([3, 2, 1, 0])\n [3, 2, 1]\n\n sage: PT = PartitionTuples()\n sage: elt = PT([[4,4,2,2,1]]); elt\n ([4, 4, 2, 2, 1])\n sage: P(elt)\n [4, 4, 2, 2, 1]\n\n TESTS::\n\n sage: Partition([3/2])\n Traceback (most recent call last):\n ...\n ValueError: all parts of [3/2] should be nonnegative integers\n\n '
if isinstance(lst, PartitionTuple):
if (lst.level() != 1):
raise ValueError(f'{lst} is not an element of {self}')
lst = lst[0]
if (lst.parent() is self):
return lst
try:
lst = list(map(ZZ, lst))
except TypeError:
raise ValueError(('all parts of %s should be nonnegative integers' % repr(lst)))
if (lst in self):
return self.element_class(self, lst)
raise ValueError(('%s is not an element of %s' % (lst, self)))
def __contains__(self, x):
'\n Check if ``x`` is contained in ``self``.\n\n TESTS::\n\n sage: P = Partitions()\n sage: Partition([2,1]) in P\n True\n sage: [2,1] in P\n True\n sage: [3,2,1] in P\n True\n sage: [1,2] in P\n False\n sage: [] in P\n True\n sage: [0] in P\n True\n\n Check that types that represent integers are not excluded::\n\n sage: P = Partitions()\n sage: [3/1, 2/2] in P\n True\n sage: Partition([3/1, 2]) in P\n True\n\n Check that non-integers and non-lists are excluded::\n\n sage: P = Partitions()\n sage: [2,1.5] in P\n False\n\n sage: 0 in P\n False\n\n '
if isinstance(x, Partition):
return True
if isinstance(x, (list, tuple)):
return ((not x) or (all((((a in ZZ) and (a >= b)) for (a, b) in zip(x, x[1:]))) and (x[(- 1)] in ZZ) and (x[(- 1)] >= 0)))
return False
def subset(self, *args, **kwargs):
'\n Return ``self`` if no arguments are given, otherwise raises a\n ``ValueError``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, starting=[3,1]); P\n Partitions of the integer 5 starting with [3, 1]\n sage: P.subset()\n Partitions of the integer 5 starting with [3, 1]\n sage: P.subset(ending=[3,1])\n Traceback (most recent call last):\n ...\n ValueError: invalid combination of arguments\n '
if ((len(args) != 0) or (len(kwargs) != 0)):
raise ValueError('invalid combination of arguments')
return self
|
class Partitions_all(Partitions):
'\n Class of all partitions.\n\n TESTS::\n\n sage: TestSuite( sage.combinat.partition.Partitions_all() ).run()\n '
def __init__(self):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: P = Partitions()\n sage: P.category()\n Category of infinite enumerated sets\n sage: Partitions().cardinality()\n +Infinity\n sage: TestSuite(P).run()\n '
Partitions.__init__(self, is_infinite=True)
def subset(self, size=None, **kwargs):
'\n Return the subset of partitions of a given size and additional\n keyword arguments.\n\n EXAMPLES::\n\n sage: P = Partitions()\n sage: P.subset(4)\n Partitions of the integer 4\n '
if (size is None):
return self
return Partitions(size, **kwargs)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: Partitions() # indirect doctest\n Partitions\n '
return 'Partitions'
def __iter__(self):
'\n An iterator for all partitions.\n\n EXAMPLES::\n\n sage: p = Partitions()\n sage: it = p.__iter__()\n sage: [next(it) for i in range(10)]\n [[], [1], [2], [1, 1], [3], [2, 1], [1, 1, 1], [4], [3, 1], [2, 2]]\n '
n = 0
while True:
for p in ZS1_iterator(n):
(yield self.element_class(self, p))
n += 1
def __reversed__(self):
'\n A reversed iterator for all partitions.\n\n This reverse iterates through partitions of fixed `n` and incrementing\n `n` after reaching the end.\n\n EXAMPLES::\n\n sage: p = Partitions()\n sage: revit = p.__reversed__()\n sage: [next(revit) for i in range(10)]\n [[], [1], [1, 1], [2], [1, 1, 1], [2, 1], [3], [1, 1, 1, 1], [2, 1, 1], [2, 2]]\n '
n = 0
while True:
for p in reversed(list(ZS1_iterator(n))):
(yield self.element_class(self, p))
n += 1
def from_frobenius_coordinates(self, frobenius_coordinates):
'\n Return a partition from a pair of sequences of Frobenius coordinates.\n\n EXAMPLES::\n\n sage: Partitions().from_frobenius_coordinates(([],[]))\n []\n sage: Partitions().from_frobenius_coordinates(([0],[0]))\n [1]\n sage: Partitions().from_frobenius_coordinates(([1],[1]))\n [2, 1]\n sage: Partitions().from_frobenius_coordinates(([6,3,2],[4,1,0]))\n [7, 5, 5, 1, 1]\n '
if (len(frobenius_coordinates) != 2):
raise ValueError(('%s is not a valid partition, two sequences of coordinates are needed' % str(frobenius_coordinates)))
else:
a = frobenius_coordinates[0]
b = frobenius_coordinates[1]
if (len(a) != len(b)):
raise ValueError(('%s is not a valid partition, the sequences of coordinates need to be the same length' % str(frobenius_coordinates)))
r = len(a)
if (r == 0):
return self.element_class(self, [])
tmp = [((a[i] + i) + 1) for i in range(r)]
if (a[(- 1)] < 0):
raise ValueError(('%s is not a partition, no coordinate can be negative' % str(frobenius_coordinates)))
if (b[(- 1)] >= 0):
tmp.extend(([r] * b[(r - 1)]))
else:
raise ValueError(('%s is not a partition, no coordinate can be negative' % str(frobenius_coordinates)))
for i in range((r - 1), 0, (- 1)):
if ((b[(i - 1)] - b[i]) > 0):
tmp.extend(([i] * ((b[(i - 1)] - b[i]) - 1)))
else:
raise ValueError(('%s is not a partition, the coordinates need to be strictly decreasing' % str(frobenius_coordinates)))
return self.element_class(self, tmp)
def from_beta_numbers(self, beta):
'\n Return a partition corresponding to a sequence of beta numbers.\n\n A sequence of beta numbers is a strictly increasing sequence\n `0 \\leq b_1 < \\cdots < b_k` of non-negative integers. The\n corresponding partition `\\mu = (\\mu_k, \\ldots, \\mu_1)` is\n given by `\\mu_i = [1,i) \\setminus \\{ b_1, \\ldots, b_i \\}`. This gives\n a bijection from the set of partitions with at most `k` non-zero parts\n to the set of strictly increasing sequences of non-negative integers\n of length `k`.\n\n EXAMPLES::\n\n sage: Partitions().from_beta_numbers([0,1,2,4,5,8])\n [3, 1, 1]\n sage: Partitions().from_beta_numbers([0,2,3,6])\n [3, 1, 1]\n '
beta.sort()
offset = 0
while ((offset < (len(beta) - 1)) and (beta[offset] == offset)):
offset += 1
beta = beta[offset:]
mu = [((beta[i] - offset) - i) for i in range(len(beta))]
return self.element_class(self, list(reversed(mu)))
def from_exp(self, exp):
'\n Return a partition from its list of multiplicities.\n\n EXAMPLES::\n\n sage: Partitions().from_exp([2,2,1])\n [3, 2, 2, 1, 1]\n '
p = []
for i in reversed(range(len(exp))):
p += ([(i + 1)] * exp[i])
return self.element_class(self, p)
def from_zero_one(self, seq):
"\n Return a partition from its `0-1` sequence.\n\n The full `0-1` sequence is the sequence (infinite in both\n directions) indicating the steps taken when following the\n outer rim of the diagram of the partition. We use the convention\n that in English convention, a 1 corresponds to an East step, and\n a 0 corresponds to a North step.\n\n Note that every full `0-1` sequence starts with infinitely many 0's and\n ends with infinitely many 1's.\n\n .. SEEALSO::\n\n :meth:`Partition.zero_one_sequence()`\n\n INPUT:\n\n The input should be a finite sequence of 0's and 1's. The\n heading 0's and trailing 1's will be discarded.\n\n EXAMPLES::\n\n sage: Partitions().from_zero_one([])\n []\n sage: Partitions().from_zero_one([1,0])\n [1]\n sage: Partitions().from_zero_one([1, 1, 1, 1, 0, 1, 0])\n [5, 4]\n\n Heading 0's and trailing 1's are correctly handled::\n\n sage: Partitions().from_zero_one([0,0,1,1,1,1,0,1,0,1,1,1])\n [5, 4]\n\n TESTS::\n\n sage: all(Partitions().from_zero_one(mu.zero_one_sequence()) == mu for n in range(10) for mu in Partitions(n))\n True\n "
tmp = [i for i in range(len(seq)) if (seq[i] == 0)]
return self.element_class(self, [(tmp[i] - i) for i in range((len(tmp) - 1), (- 1), (- 1))])
def from_core_and_quotient(self, core, quotient):
'\n Return a partition from its core and quotient.\n\n Algorithm from mupad-combinat.\n\n EXAMPLES::\n\n sage: Partitions().from_core_and_quotient([2,1], [[2,1],[3],[1,1,1]])\n [11, 5, 5, 3, 2, 2, 2]\n\n TESTS::\n\n sage: Partitions().from_core_and_quotient([2,1], [[2,1],[2,3,1],[1,1,1]])\n Traceback (most recent call last):\n ...\n ValueError: the quotient [[2, 1], [2, 3, 1], [1, 1, 1]] must be a tuple of partitions\n\n We check that :trac:`11412` is actually fixed::\n\n sage: test = lambda x, k: x == Partition(core=x.core(k),\n ....: quotient=x.quotient(k))\n sage: all(test(mu,k) for k in range(1,5)\n ....: for n in range(10) for mu in Partitions(n))\n True\n sage: test2 = lambda core, mus: (\n ....: Partition(core=core, quotient=mus).core(mus.level()) == core\n ....: and\n ....: Partition(core=core, quotient=mus).quotient(mus.level()) == mus)\n sage: all(test2(core,mus) # long time (5s on sage.math, 2011)\n ....: for k in range(1,10)\n ....: for n_core in range(10-k)\n ....: for core in Partitions(n_core)\n ....: if core.core(k) == core\n ....: for n_mus in range(10-k)\n ....: for mus in PartitionTuples(k,n_mus))\n True\n '
from .partition_tuple import PartitionTuple, PartitionTuples
if (quotient not in PartitionTuples()):
raise ValueError(('the quotient %s must be a tuple of partitions' % quotient))
components = PartitionTuple(quotient).components()
length = len(components)
k = ((length * max((len(q) for q in components))) + len(core))
v = ([(core[i] - i) for i in range(len(core))] + [(- i) for i in range(len(core), k)])
w = [[x for x in v if (((x - i) % length) == 0)] for i in range(1, (length + 1))]
new_w = []
for i in range(length):
lw = len(w[i])
lq = len(components[i])
new_w += [(w[i][j] + (length * components[i][j])) for j in range(lq)]
new_w += [w[i][j] for j in range(lq, lw)]
new_w.sort(reverse=True)
return self.element_class(self, [(new_w[i] + i) for i in range(len(new_w))])
|
class Partitions_all_bounded(Partitions):
def __init__(self, k):
'\n TESTS::\n\n sage: TestSuite( sage.combinat.partition.Partitions_all_bounded(3) ).run() # long time\n '
self.k = k
Partitions.__init__(self, is_infinite=True)
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(max_part=3)\n sage: Partition([2,1]) in P\n True\n sage: [2,1] in P\n True\n sage: [3,2,1] in P\n True\n sage: [1,2] in P\n False\n sage: [5,1] in P\n False\n sage: [0] in P\n True\n sage: [] in P\n True\n '
return ((not x) or ((x[0] <= self.k) and (x in _Partitions)))
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import Partitions_all_bounded\n sage: Partitions_all_bounded(3)\n 3-Bounded Partitions\n '
return ('%d-Bounded Partitions' % self.k)
def __iter__(self):
'\n An iterator for all `k`-bounded partitions.\n\n EXAMPLES::\n\n sage: p = Partitions(max_part=3)\n sage: it = p.__iter__()\n sage: [next(it) for i in range(10)]\n [[], [1], [2], [1, 1], [3], [2, 1], [1, 1, 1], [3, 1], [2, 2], [2, 1, 1]]\n '
n = 0
while True:
for p in Partitions(n, max_part=self.k):
(yield self.element_class(self, p))
n += 1
|
class Partitions_n(Partitions):
'\n Partitions of the integer `n`.\n\n TESTS::\n\n sage: TestSuite( sage.combinat.partition.Partitions_n(0) ).run() # needs sage.libs.flint\n sage: TestSuite( sage.combinat.partition.Partitions_n(0) ).run() # needs sage.libs.flint\n '
def __init__(self, n):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: TestSuite( Partitions(5) ).run()\n '
Partitions.__init__(self)
self.n = n
def __contains__(self, x):
'\n Check if ``x`` is contained in ``self``.\n\n TESTS::\n\n sage: p = Partitions(5)\n sage: [2,1] in p\n False\n sage: [2,2,1] in p\n True\n sage: [3,2] in p\n True\n sage: [2,3] in p\n False\n '
return ((x in _Partitions) and (sum(x) == self.n))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: Partitions(5) # indirect doctest\n Partitions of the integer 5\n '
return ('Partitions of the integer %s' % self.n)
def _an_element_(self):
'\n Return a partition in ``self``.\n\n EXAMPLES::\n\n sage: Partitions(4).an_element() # indirect doctest\n [3, 1]\n sage: Partitions(0).an_element()\n []\n sage: Partitions(1).an_element()\n [1]\n '
if (self.n == 0):
lst = []
elif (self.n == 1):
lst = [1]
else:
lst = [(self.n - 1), 1]
return self.element_class(self, lst)
def cardinality(self, algorithm='flint'):
"\n Return the number of partitions of the specified size.\n\n INPUT:\n\n - ``algorithm`` - (default: ``'flint'``)\n\n - ``'flint'`` -- use FLINT (currently the fastest)\n - ``'gap'`` -- use GAP (VERY *slow*)\n - ``'pari'`` -- use PARI. Speed seems the same as GAP until\n `n` is in the thousands, in which case PARI is faster.\n\n It is possible to associate with every partition of the integer `n` a\n conjugacy class of permutations in the symmetric group on `n` points\n and vice versa. Therefore the number of partitions `p_n` is the number\n of conjugacy classes of the symmetric group on `n` points.\n\n EXAMPLES::\n\n sage: v = Partitions(5).list(); v\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: len(v)\n 7\n sage: Partitions(5).cardinality(algorithm='gap') # needs sage.libs.gap\n 7\n\n ::\n\n sage: # needs sage.libs.flint\n sage: Partitions(3).cardinality()\n 3\n sage: number_of_partitions(5, algorithm='flint')\n 7\n sage: Partitions(10).cardinality()\n 42\n sage: Partitions(40).cardinality()\n 37338\n sage: Partitions(100).cardinality()\n 190569292\n\n ::\n\n sage: # needs sage.libs.pari\n sage: Partitions(3).cardinality(algorithm='pari')\n 3\n sage: Partitions(5).cardinality(algorithm='pari')\n 7\n sage: Partitions(10).cardinality(algorithm='pari')\n 42\n\n A generating function for `p_n` is given by the reciprocal of\n Euler's function:\n\n .. MATH::\n\n \\sum_{n=0}^{\\infty} p_n x^n = \\prod_{k=1}^{\\infty} \\frac{1}{1-x^k}.\n\n We use Sage to verify that the first several coefficients do\n indeed agree::\n\n sage: q = PowerSeriesRing(QQ, 'q', default_prec=9).gen()\n sage: prod([(1-q^k)^(-1) for k in range(1,9)]) # partial product of\n 1 + q + 2*q^2 + 3*q^3 + 5*q^4 + 7*q^5 + 11*q^6 + 15*q^7 + 22*q^8 + O(q^9)\n sage: [Partitions(k).cardinality() for k in range(2,10)] # needs sage.libs.flint\n [2, 3, 5, 7, 11, 15, 22, 30]\n\n Another consistency test for ``n`` up to 500::\n\n sage: len([n for n in [1..500] # needs sage.libs.flint sage.libs.pari\n ....: if Partitions(n).cardinality() != Partitions(n).cardinality(algorithm='pari')])\n 0\n\n For negative inputs, the result is zero (the algorithm is ignored)::\n\n sage: Partitions(-5).cardinality()\n 0\n\n REFERENCES:\n\n - :wikipedia:`Partition\\_(number\\_theory)`\n "
if (self.n < 0):
return ZZ.zero()
if (algorithm == 'flint'):
return cached_number_of_partitions(self.n)
elif (algorithm == 'gap'):
from sage.libs.gap.libgap import libgap
return ZZ(libgap.NrPartitions(ZZ(self.n)))
elif (algorithm == 'pari'):
return ZZ(pari(ZZ(self.n)).numbpart())
raise ValueError(("unknown algorithm '%s'" % algorithm))
def random_element(self, measure='uniform'):
"\n Return a random partitions of `n` for the specified measure.\n\n INPUT:\n\n - ``measure`` -- ``'uniform'`` or ``'Plancherel'``\n (default: ``'uniform'``)\n\n .. SEEALSO::\n\n - :meth:`random_element_uniform`\n - :meth:`random_element_plancherel`\n\n EXAMPLES::\n\n sage: Partitions(5).random_element() # random # needs sage.libs.flint\n [2, 1, 1, 1]\n sage: Partitions(5).random_element(measure='Plancherel') # random # needs sage.libs.flint\n [2, 1, 1, 1]\n "
if (measure == 'uniform'):
return self.random_element_uniform()
elif (measure == 'Plancherel'):
return self.random_element_plancherel()
else:
raise ValueError(('Unknown measure: %s' % measure))
def random_element_uniform(self):
'\n Return a random partition of `n` with uniform probability.\n\n EXAMPLES::\n\n sage: Partitions(5).random_element_uniform() # random # needs sage.libs.flint\n [2, 1, 1, 1]\n sage: Partitions(20).random_element_uniform() # random # needs sage.libs.flint\n [9, 3, 3, 2, 2, 1]\n\n TESTS::\n\n sage: all(Part.random_element_uniform() in Part # needs sage.libs.flint\n ....: for Part in map(Partitions, range(10)))\n True\n\n Check that :trac:`18752` is fixed::\n\n sage: P = Partitions(5)\n sage: la = P.random_element_uniform() # needs sage.libs.flint\n sage: la.parent() is P # needs sage.libs.flint\n True\n\n ALGORITHM:\n\n - It is a python Implementation of RANDPAR, see [NW1978]_. The\n complexity is unknown, there may be better algorithms.\n\n .. TODO::\n\n Check in Knuth AOCP4.\n\n - There is also certainly a lot of room for optimizations, see\n comments in the code.\n\n AUTHOR:\n\n - Florent Hivert (2009-11-23)\n '
n = self.n
res = []
while (n > 0):
rand = randrange(0, (n * cached_number_of_partitions(n)))
for j in range(1, (n + 1)):
d = 1
r = (n - j)
while (r >= 0):
rand -= (d * cached_number_of_partitions(r))
if (rand < 0):
break
d += 1
r -= j
else:
continue
break
res.extend(([d] * j))
n = r
res.sort(reverse=True)
return self.element_class(self, res)
def random_element_plancherel(self):
'\n Return a random partition of `n` (for the Plancherel measure).\n\n This probability distribution comes from the uniform distribution\n on permutations via the Robinson-Schensted correspondence.\n\n See :wikipedia:`Plancherel\\_measure`\n and :meth:`Partition.plancherel_measure`.\n\n EXAMPLES::\n\n sage: Partitions(5).random_element_plancherel() # random\n [2, 1, 1, 1]\n sage: Partitions(20).random_element_plancherel() # random\n [9, 3, 3, 2, 2, 1]\n\n TESTS::\n\n sage: all(Part.random_element_plancherel() in Part\n ....: for Part in map(Partitions, range(10)))\n True\n\n Check that :trac:`18752` is fixed::\n\n sage: P = Partitions(5)\n sage: la = P.random_element_plancherel()\n sage: la.parent() is P\n True\n\n ALGORITHM:\n\n - insert by Robinson-Schensted a uniform random permutations of n and\n returns the shape of the resulting tableau. The complexity is\n `O(n\\ln(n))` which is likely optimal. However, the implementation\n could be optimized.\n\n AUTHOR:\n\n - Florent Hivert (2009-11-23)\n '
T = permutation.Permutations(self.n).random_element().left_tableau()
return self.element_class(self, [len(row) for row in T])
def first(self):
'\n Return the lexicographically first partition of a positive integer\n `n`. This is the partition ``[n]``.\n\n EXAMPLES::\n\n sage: Partitions(4).first()\n [4]\n '
return self.element_class(self, [self.n])
def next(self, p):
'\n Return the lexicographically next partition after the partition ``p``.\n\n EXAMPLES::\n\n sage: Partitions(4).next([4])\n [3, 1]\n sage: Partitions(4).next([1,1,1,1]) is None\n True\n '
found = False
for i in self:
if found:
return i
if (i == p):
found = True
return None
def last(self):
'\n Return the lexicographically last partition of the positive\n integer `n`. This is the all-ones partition.\n\n EXAMPLES::\n\n sage: Partitions(4).last()\n [1, 1, 1, 1]\n '
return self.element_class(self, ([1] * self.n))
def __iter__(self):
'\n An iterator for the partitions of `n`.\n\n EXAMPLES::\n\n sage: [x for x in Partitions(4)]\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n\n TESTS::\n\n sage: all(isinstance(i, Integer) for p in Partitions(4) for i in p)\n True\n\n '
for p in ZS1_iterator(self.n):
(yield self.element_class(self, [Integer(i) for i in p]))
def subset(self, **kwargs):
'\n Return a subset of ``self`` with the additional optional arguments.\n\n EXAMPLES::\n\n sage: P = Partitions(5); P\n Partitions of the integer 5\n sage: P.subset(starting=[3,1])\n Partitions of the integer 5 starting with [3, 1]\n '
return Partitions(self.n, **kwargs)
|
class Partitions_nk(Partitions):
'\n Partitions of the integer `n` of length equal to `k`.\n\n TESTS::\n\n sage: TestSuite( sage.combinat.partition.Partitions_nk(0,0) ).run()\n sage: TestSuite( sage.combinat.partition.Partitions_nk(0,0) ).run()\n '
def __init__(self, n, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: TestSuite( Partitions(5, length=2) ).run()\n '
Partitions.__init__(self)
self.n = n
self.k = k
def __contains__(self, x):
'\n Check if ``x`` is contained in ``self``.\n\n TESTS::\n\n sage: p = Partitions(5, length=2)\n sage: [2,1] in p\n False\n sage: [2,2,1] in p\n False\n sage: [3,2] in p\n True\n sage: [2,3] in p\n False\n sage: [4,1] in p\n True\n sage: [1,1,1,1,1] in p\n False\n sage: [5] in p\n False\n '
return ((x in _Partitions) and (sum(x) == self.n) and (len(x) == self.k))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: Partitions(5, length=2) # indirect doctest\n Partitions of the integer 5 of length 2\n '
return 'Partitions of the integer {} of length {}'.format(self.n, self.k)
def _an_element_(self):
'\n Return a partition in ``self``.\n\n EXAMPLES::\n\n sage: Partitions(4, length=1).an_element() # indirect doctest\n [4]\n sage: Partitions(4, length=2).an_element()\n [3, 1]\n sage: Partitions(4, length=3).an_element()\n [2, 1, 1]\n sage: Partitions(4, length=4).an_element()\n [1, 1, 1, 1]\n\n sage: Partitions(1, length=1).an_element()\n [1]\n\n sage: Partitions(0, length=0).an_element()\n []\n '
if (self.n == 0):
if (self.k == 0):
lst = []
else:
from sage.categories.sets_cat import EmptySetError
raise EmptySetError
elif (self.n >= self.k > 0):
lst = ([((self.n - self.k) + 1)] + ([1] * (self.k - 1)))
else:
from sage.categories.sets_cat import EmptySetError
raise EmptySetError
return self.element_class(self, lst)
def __iter__(self):
'\n An iterator for all partitions of `n` of length `k`.\n\n EXAMPLES::\n\n sage: p = Partitions(9, length=3)\n sage: it = p.__iter__()\n sage: list(it)\n [[7, 1, 1], [6, 2, 1], [5, 3, 1], [5, 2, 2], [4, 4, 1], [4, 3, 2], [3, 3, 3]]\n\n sage: p = Partitions(9, length=10)\n sage: list(p.__iter__())\n []\n\n sage: p = Partitions(0, length=0)\n sage: list(p.__iter__())\n [[]]\n\n sage: from sage.combinat.partition import number_of_partitions_length\n sage: all( len(Partitions(n, length=k).list()) # needs sage.libs.flint\n ....: == number_of_partitions_length(n, k)\n ....: for n in range(9) for k in range(n+2) )\n True\n\n TESTS::\n\n sage: partitions = Partitions(9, length=3)\n sage: all(isinstance(i, Integer) for p in partitions for i in p)\n True\n\n '
for p in ZS1_iterator_nk((self.n - self.k), self.k):
v = [Integer((i + 1)) for i in p]
adds = ([Integer(1)] * (self.k - len(v)))
(yield self.element_class(self, (v + adds)))
def cardinality(self, algorithm='hybrid'):
"\n Return the number of partitions of the specified size with the\n specified length.\n\n INPUT:\n\n - ``algorithm`` -- (default: ``'hybrid'``) the algorithm to compute\n the cardinality and can be one of the following:\n\n * ``'hybrid'`` - use a hybrid algorithm which uses heuristics to\n reduce the complexity\n * ``'gap'`` - use GAP\n\n EXAMPLES::\n\n sage: v = Partitions(5, length=2).list(); v\n [[4, 1], [3, 2]]\n sage: len(v)\n 2\n sage: Partitions(5, length=2).cardinality()\n 2\n\n More generally, the number of partitions of `n` of length `2`\n is `\\left\\lfloor \\frac{n}{2} \\right\\rfloor`::\n\n sage: all( Partitions(n, length=2).cardinality()\n ....: == n // 2 for n in range(10) )\n True\n\n The number of partitions of `n` of length `1` is `1` for `n`\n positive::\n\n sage: all( Partitions(n, length=1).cardinality() == 1\n ....: for n in range(1, 10) )\n True\n\n Further examples::\n\n sage: # needs sage.libs.flint\n sage: Partitions(5, length=3).cardinality()\n 2\n sage: Partitions(6, length=3).cardinality()\n 3\n sage: Partitions(8, length=4).cardinality()\n 5\n sage: Partitions(8, length=5).cardinality()\n 3\n sage: Partitions(15, length=6).cardinality()\n 26\n sage: Partitions(0, length=0).cardinality()\n 1\n sage: Partitions(0, length=1).cardinality()\n 0\n sage: Partitions(1, length=0).cardinality()\n 0\n sage: Partitions(1, length=4).cardinality()\n 0\n\n TESTS:\n\n We check the hybrid approach gives the same results as GAP::\n\n sage: N = [0, 1, 2, 3, 5, 10, 20, 500, 850]\n sage: K = [0, 1, 2, 3, 5, 10, 11, 20, 21, 250, 499, 500]\n sage: all(Partitions(n, length=k).cardinality() # needs sage.libs.flint\n ....: == Partitions(n,length=k).cardinality('gap')\n ....: for n in N for k in K)\n True\n sage: P = Partitions(4562, length=2800)\n sage: P.cardinality() == P.cardinality('gap') # needs sage.libs.flint\n True\n "
return number_of_partitions_length(self.n, self.k, algorithm)
def subset(self, **kwargs):
'\n Return a subset of ``self`` with the additional optional arguments.\n\n EXAMPLES::\n\n sage: P = Partitions(5, length=2); P\n Partitions of the integer 5 of length 2\n sage: P.subset(max_part=3)\n Partitions of the integer 5 satisfying constraints length=2, max_part=3\n '
return Partitions(self.n, length=self.k, **kwargs)
|
class Partitions_parts_in(Partitions):
'\n Partitions of `n` with parts in a given set `S`.\n\n This is invoked indirectly when calling\n ``Partitions(n, parts_in=parts)``, where ``parts`` is a list of\n pairwise distinct integers.\n\n TESTS::\n\n sage: TestSuite( sage.combinat.partition.Partitions_parts_in(6, parts=[2,1]) ).run() # needs sage.libs.gap\n '
@staticmethod
def __classcall_private__(cls, n, parts):
'\n Normalize the input to ensure a unique representation.\n\n TESTS::\n\n sage: P = Partitions(4, parts_in=[2,1])\n sage: P2 = Partitions(4, parts_in=(1,2))\n sage: P is P2\n True\n '
parts = tuple(sorted(parts))
return super().__classcall__(cls, Integer(n), parts)
def __init__(self, n, parts):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: TestSuite(Partitions(5, parts_in=[1,2,3])).run() # needs sage.libs.gap\n '
Partitions.__init__(self)
self.n = n
self.parts = list(parts)
def __contains__(self, x):
'\n TESTS::\n\n sage: p = Partitions(5, parts_in=[1,2])\n sage: [2,1,1,1] in p\n True\n sage: [4,1] in p\n False\n '
return ((x in _Partitions) and (sum(x) == self.n) and all(((p in self.parts) for p in x)))
def _repr_(self):
'\n TESTS::\n\n sage: Partitions(5, parts_in=[1,2,3]) # indirect doctest\n Partitions of the integer 5 with parts in [1, 2, 3]\n '
return ('Partitions of the integer %s with parts in %s' % (self.n, self.parts))
def cardinality(self):
"\n Return the number of partitions with parts in ``self``. Wraps GAP's\n ``NrRestrictedPartitions``.\n\n EXAMPLES::\n\n sage: Partitions(15, parts_in=[2,3,7]).cardinality() # needs sage.libs.gap\n 5\n\n If you can use all parts 1 through `n`, we'd better get `p(n)`::\n\n sage: (Partitions(20, parts_in=[1..20]).cardinality() # needs sage.libs.gap\n ....: == Partitions(20).cardinality())\n True\n\n TESTS:\n\n Let's check the consistency of GAP's function and our own\n algorithm that actually generates the partitions::\n\n sage: # needs sage.libs.gap\n sage: ps = Partitions(15, parts_in=[1,2,3])\n sage: ps.cardinality() == len(ps.list())\n True\n sage: ps = Partitions(15, parts_in=[])\n sage: ps.cardinality() == len(ps.list())\n True\n sage: ps = Partitions(3000, parts_in=[50,100,500,1000])\n sage: ps.cardinality() == len(ps.list())\n True\n sage: ps = Partitions(10, parts_in=[3,6,9])\n sage: ps.cardinality() == len(ps.list())\n True\n sage: ps = Partitions(0, parts_in=[1,2])\n sage: ps.cardinality() == len(ps.list())\n True\n "
if self.parts:
from sage.libs.gap.libgap import libgap
return ZZ(libgap.NrRestrictedPartitions(ZZ(self.n), self.parts))
return Integer((self.n == 0))
def first(self):
'\n Return the lexicographically first partition of a positive\n integer `n` with the specified parts, or ``None`` if no such\n partition exists.\n\n EXAMPLES::\n\n sage: Partitions(9, parts_in=[3,4]).first()\n [3, 3, 3]\n sage: Partitions(6, parts_in=[1..6]).first()\n [6]\n sage: Partitions(30, parts_in=[4,7,8,10,11]).first()\n [11, 11, 8]\n '
try:
return self.element_class(self, self._findfirst(self.n, self.parts[:]))
except TypeError:
return None
def _findfirst(self, n, parts):
'\n TESTS::\n\n sage: p = Partitions(9, parts_in=[3,4])\n sage: p._findfirst(p.n, p.parts[:])\n [3, 3, 3]\n sage: p._findfirst(0, p.parts[:])\n []\n sage: p._findfirst(p.n, [10])\n\n '
if (n == 0):
return []
else:
while parts:
p = parts.pop()
for k in range(n.quo_rem(p)[0], 0, (- 1)):
try:
return ((k * [p]) + self._findfirst((n - (k * p)), parts[:]))
except TypeError:
pass
def last(self):
'\n Return the lexicographically last partition of the positive\n integer `n` with the specified parts, or ``None`` if no such\n partition exists.\n\n EXAMPLES::\n\n sage: Partitions(15, parts_in=[2,3]).last()\n [3, 2, 2, 2, 2, 2, 2]\n sage: Partitions(30, parts_in=[4,7,8,10,11]).last()\n [7, 7, 4, 4, 4, 4]\n sage: Partitions(10, parts_in=[3,6]).last() is None\n True\n sage: Partitions(50, parts_in=[11,12,13]).last()\n [13, 13, 12, 12]\n sage: Partitions(30, parts_in=[4,7,8,10,11]).last()\n [7, 7, 4, 4, 4, 4]\n\n TESTS::\n\n sage: Partitions(6, parts_in=[1..6]).last()\n [1, 1, 1, 1, 1, 1]\n sage: Partitions(0, parts_in=[]).last()\n []\n sage: Partitions(50, parts_in=[11,12]).last() is None\n True\n '
try:
return self.element_class(self, self._findlast(self.n, self.parts))
except TypeError:
return None
def _findlast(self, n, parts):
'\n Return the lexicographically largest partition of `n` using the\n given parts, or ``None`` if no such partition exists. This function\n is not intended to be called directly.\n\n INPUT:\n\n - ``n`` -- nonnegative integer\n\n - ``parts`` -- a sorted list of positive integers.\n\n OUTPUT:\n\n A list of integers in weakly decreasing order, or ``None``. The\n output is just a list, not a partition object.\n\n EXAMPLES::\n\n sage: ps = Partitions(1, parts_in=[1])\n sage: ps._findlast(15, [2,3])\n [3, 2, 2, 2, 2, 2, 2]\n sage: ps._findlast(9, [2,4]) is None\n True\n sage: ps._findlast(0, [])\n []\n sage: ps._findlast(100, [9,17,31])\n [31, 17, 17, 17, 9, 9]\n '
if (n < 0):
return None
elif (n == 0):
return []
elif parts:
p = parts[0]
(q, r) = n.quo_rem(p)
if (r == 0):
return ([p] * q)
else:
for (i, p) in enumerate(parts[1:]):
rest = self._findlast((n - p), parts[:(i + 2)])
if (rest is not None):
return ([p] + rest)
return None
def __iter__(self):
'\n An iterator through the partitions of `n` with all parts belonging\n to a particular set.\n\n EXAMPLES::\n\n sage: [x for x in Partitions(5, parts_in=[1,2,3])]\n [[3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n '
for p in self._other_iterator(self.n, self.parts):
(yield self.element_class(self, p))
def _fast_iterator(self, n, parts):
"\n A fast iterator for the partitions of ``n`` which returns lists and\n not partition types. This function is not intended to be called\n directly.\n\n INPUT:\n\n - ``n`` -- nonnegative integer.\n\n - ``parts`` -- a list of parts to use. This list will be\n destroyed, so pass things here with ``foo[:]`` (or something\n equivalent) if you want to preserve your list. In particular,\n the ``__iter__`` method needs to use ``self.parts[:]``, or else we\n forget which parts we're using!\n\n OUTPUT:\n\n A generator object for partitions of `n` with parts in\n ``parts``.\n\n If the parts in ``parts`` are sorted in increasing order, this\n function returns weakly decreasing lists. If ``parts`` is not\n sorted, your lists won't be, either.\n\n EXAMPLES::\n\n sage: P = Partitions(4, parts_in=[2,4])\n sage: it = P._fast_iterator(4, [2,4])\n sage: next(it)\n [4]\n sage: type(_)\n <class 'list'>\n "
if (n == 0):
(yield [])
else:
while parts:
p = parts.pop()
for k in range(n.quo_rem(p)[0], 0, (- 1)):
for q in self._fast_iterator((n - (k * p)), parts[:]):
(yield ((k * [p]) + q))
def _other_iterator(self, n, parts):
"\n A fast iterator for the partitions of ``n`` which returns lists and\n not partition types. This function is not intended to be called\n directly.\n\n INPUT:\n\n - ``n`` -- nonnegative integer.\n\n - ``parts`` -- a list of parts to use.\n\n OUTPUT:\n\n A generator object for partitions of `n` with parts in\n ``parts``.\n\n EXAMPLES::\n\n sage: P = Partitions(4, parts_in=[2,4])\n sage: it = P._other_iterator(4, [2,4])\n sage: next(it)\n [4]\n sage: type(_)\n <class 'list'>\n "
sorted_parts = sorted(parts, reverse=True)
for vec in weighted_iterator_fast(n, sorted_parts):
(yield sum((([pi] * multi) for (pi, multi) in zip(sorted_parts, vec)), []))
|
class Partitions_starting(Partitions):
'\n All partitions with a given start.\n '
@staticmethod
def __classcall_private__(cls, n, starting_partition):
'\n Normalize the input to ensure a unique representation.\n\n TESTS::\n\n sage: P = Partitions(4, starting=[2,1])\n sage: P2 = Partitions(4, starting=[2,1])\n sage: P is P2\n True\n '
starting_partition = Partition(starting_partition)
return super().__classcall__(cls, Integer(n), starting_partition)
def __init__(self, n, starting_partition):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: Partitions(3, starting=[2,1])\n Partitions of the integer 3 starting with [2, 1]\n sage: Partitions(3, starting=[2,1]).list()\n [[2, 1], [1, 1, 1]]\n\n sage: Partitions(7, starting=[2,2,1]).list()\n [[2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]]\n\n sage: Partitions(7, starting=[3,2]).list()\n [[3, 1, 1, 1, 1],\n [2, 2, 2, 1],\n [2, 2, 1, 1, 1],\n [2, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1]]\n\n sage: Partitions(4, starting=[3,2]).list()\n [[3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n\n sage: Partitions(3, starting=[1,1]).list()\n []\n\n TESTS::\n\n sage: p = Partitions(3, starting=[2,1])\n sage: TestSuite(p).run()\n '
Partitions.__init__(self)
self.n = n
self._starting = starting_partition
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Partitions(3, starting=[2,1]) # indirect doctest\n Partitions of the integer 3 starting with [2, 1]\n '
return f'Partitions of the integer {self.n} starting with {self._starting}'
def __contains__(self, x):
'\n Checks if ``x`` is contained in ``self``.\n\n EXAMPLES::\n\n sage: p = Partitions(3, starting=[2,1])\n sage: [1,1] in p\n False\n sage: [2,1] in p\n True\n sage: [1,1,1] in p\n True\n sage: [3] in p\n False\n '
return ((x in Partitions_n(self.n)) and (x <= self._starting))
def first(self):
'\n Return the first partition in ``self``.\n\n EXAMPLES::\n\n sage: Partitions(3, starting=[2,1]).first()\n [2, 1]\n sage: Partitions(3, starting=[1,1,1]).first()\n [1, 1, 1]\n sage: Partitions(3, starting=[1,1]).first()\n False\n sage: Partitions(3, starting=[3,1]).first()\n [3]\n sage: Partitions(3, starting=[2,2]).first()\n [2, 1]\n '
if (sum(self._starting) == self.n):
return self._starting
if ((k := self._starting.size()) < self.n):
mu = (list(self._starting) + ([1] * (self.n - k)))
return next(Partition(mu))
return self.element_class(self, Partitions(self.n, outer=self._starting).first())
def next(self, part):
'\n Return the next partition after ``part`` in ``self``.\n\n EXAMPLES::\n\n sage: Partitions(3, starting=[2,1]).next(Partition([2,1]))\n [1, 1, 1]\n '
return next(part)
|
class Partitions_ending(Partitions):
'\n All partitions with a given ending.\n '
@staticmethod
def __classcall_private__(cls, n, ending_partition):
'\n Normalize the input to ensure a unique representation.\n\n TESTS::\n\n sage: P = Partitions(4)\n sage: P2 = Partitions(4)\n sage: P is P2\n True\n '
ending_partition = Partition(ending_partition)
return super().__classcall__(cls, Integer(n), ending_partition)
def __init__(self, n, ending_partition):
'\n Initializes ``self``.\n\n EXAMPLES::\n\n sage: Partitions(4, ending=[1,1,1,1]).list()\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: Partitions(4, ending=[2,2]).list()\n [[4], [3, 1], [2, 2]]\n sage: Partitions(4, ending=[4]).list()\n [[4]]\n sage: Partitions(4, ending=[5]).list()\n []\n\n TESTS::\n\n sage: p = Partitions(4, ending=[1,1,1,1])\n sage: TestSuite(p).run()\n '
Partitions.__init__(self)
self.n = n
self._ending = ending_partition
self._ending_size_is_not_same = (n != sum(self._ending))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: Partitions(4, ending=[1,1,1,1]) # indirect doctest\n Partitions of the integer 4 ending with [1, 1, 1, 1]\n '
return f'Partitions of the integer {self.n} ending with {self._ending}'
def __contains__(self, x):
'\n Checks if ``x`` is contained in ``self``.\n\n EXAMPLES::\n\n sage: p = Partitions(4, ending=[2,2])\n sage: [4] in p\n True\n sage: [2,1,1] in p\n False\n sage: [2,1] in p\n False\n '
return ((x in Partitions_n(self.n)) and (x >= self._ending))
def first(self):
'\n Return the first partition in ``self``.\n\n EXAMPLES::\n\n sage: Partitions(4, ending=[1,1,1,1]).first()\n [4]\n sage: Partitions(4, ending=[5]).first() is None\n True\n '
if (self._ending and (self.n <= self._ending[0]) and (not ((self.n == self._ending[0]) and (len(self._ending) == 1)))):
return None
return self.element_class(self, [self.n])
def next(self, part):
'\n Return the next partition after ``part`` in ``self``.\n\n EXAMPLES::\n sage: Partitions(4, ending=[1,1,1,1,1]).next(Partition([4]))\n [3, 1]\n sage: Partitions(4, ending=[3,2]).next(Partition([3,1])) is None\n True\n sage: Partitions(4, ending=[1,1,1,1]).next(Partition([4]))\n [3, 1]\n sage: Partitions(4, ending=[1,1,1,1]).next(Partition([1,1,1,1])) is None\n True\n sage: Partitions(4, ending=[3]).next(Partition([3,1])) is None\n True\n '
if (part == self._ending):
return None
mu = next(part)
if (self._ending_size_is_not_same and (mu < self._ending)):
return None
return mu
|
class PartitionsInBox(Partitions):
'\n All partitions which fit in an `h \\times w` box.\n\n EXAMPLES::\n\n sage: PartitionsInBox(2,2)\n Integer partitions which fit in a 2 x 2 box\n sage: PartitionsInBox(2,2).list()\n [[], [1], [1, 1], [2], [2, 1], [2, 2]]\n '
def __init__(self, h, w):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: p = PartitionsInBox(2,2)\n sage: TestSuite(p).run()\n '
Partitions.__init__(self)
self.h = h
self.w = w
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionsInBox(2,2) # indirect doctest\n Integer partitions which fit in a 2 x 2 box\n '
return ('Integer partitions which fit in a %s x %s box' % (self.h, self.w))
def __contains__(self, x):
'\n Checks if ``x`` is contained in ``self``.\n\n EXAMPLES::\n\n sage: [] in PartitionsInBox(2,2)\n True\n sage: [2,1] in PartitionsInBox(2,2)\n True\n sage: [3,1] in PartitionsInBox(2,2)\n False\n sage: [2,1,1] in PartitionsInBox(2,2)\n False\n sage: [3,1] in PartitionsInBox(3, 2)\n False\n sage: [3,1] in PartitionsInBox(2, 3)\n True\n '
return ((x in _Partitions) and (len(x) <= self.h) and ((len(x) == 0) or (x[0] <= self.w)))
def list(self):
"\n Return a list of all the partitions inside a box of height `h` and\n width `w`.\n\n EXAMPLES::\n\n sage: PartitionsInBox(2,2).list()\n [[], [1], [1, 1], [2], [2, 1], [2, 2]]\n sage: PartitionsInBox(2,3).list()\n [[], [1], [1, 1], [2], [2, 1], [2, 2], [3], [3, 1], [3, 2], [3, 3]]\n\n TESTS:\n\n Check :trac:`10890`::\n\n sage: type(PartitionsInBox(0,0)[0])\n <class 'sage.combinat.partition.PartitionsInBox_with_category.element_class'>\n "
h = self.h
w = self.w
if (h == 0):
return [self.element_class(self, [])]
else:
l = [[i] for i in range((w + 1))]
add = (lambda x: [(x + [i]) for i in range((x[(- 1)] + 1))])
for i in range((h - 1)):
new_list = []
for element in l:
new_list += add(element)
l = new_list
return [self.element_class(self, [x for x in p if (x != 0)]) for p in l]
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: PartitionsInBox(2, 3).cardinality()\n 10\n\n TESTS:\n\n Check the corner case::\n\n sage: PartitionsInBox(0, 0).cardinality()\n 1\n\n sage: PartitionsInBox(0, 1).cardinality()\n 1\n\n sage: all(PartitionsInBox(a, b).cardinality() ==\n ....: len(PartitionsInBox(a, b).list())\n ....: for a in range(6) for b in range(6))\n True\n\n '
return binomial((self.h + self.w), self.w)
|
class Partitions_constraints(IntegerListsLex):
'\n For unpickling old constrained ``Partitions_constraints`` objects created\n with sage <= 3.4.1. See :class:`Partitions`.\n '
def __setstate__(self, data):
"\n TESTS::\n\n sage: dmp = b'x\\x9ck`J.NLO\\xd5K\\xce\\xcfM\\xca\\xccK,\\xd1+H,*\\xc9,\\xc9\\xcc\\xcf\\xe3\\n\\x80\\xb1\\x8a\\xe3\\x93\\x81DIQbf^I1W!\\xa3fc!Sm!\\xb3F(7\\x92x!Km!k(GnbE<\\xc8\\x88B6\\x88\\xb9E\\x99y\\xe9\\xc5z@\\x05\\xa9\\xe9\\xa9E\\\\\\xb9\\x89\\xd9\\xa9\\xf10N!{(\\xa3QkP!Gq(c^\\x06\\x90c\\x0c\\xe4p\\x96&\\xe9\\x01\\x00\\xc2\\xe53\\xfd'\n sage: sp = loads(dmp); sp\n Integer lists of sum 3 satisfying certain constraints\n sage: sp.list()\n [[2, 1], [1, 1, 1]]\n "
n = data['n']
self.__class__ = Partitions_with_constraints
constraints = {'max_slope': 0, 'min_part': 1}
constraints.update(data['constraints'])
self.__init__(n, **constraints)
|
class Partitions_with_constraints(IntegerListsLex):
'\n Partitions which satisfy a set of constraints.\n\n EXAMPLES::\n\n sage: P = Partitions(6, inner=[1,1], max_slope=-1)\n sage: list(P)\n [[5, 1], [4, 2], [3, 2, 1]]\n\n TESTS::\n\n sage: P = Partitions(6, min_part=2, max_slope=-1)\n sage: TestSuite(P).run()\n\n Test that :trac:`15525` is fixed::\n\n sage: loads(dumps(P)) == P\n True\n '
Element = Partition
options = Partitions.options
|
class RegularPartitions(Partitions):
'\n Base class for `\\ell`-regular partitions.\n\n Let `\\ell` be a positive integer. A partition `\\lambda` is\n `\\ell`-*regular* if `m_i < \\ell` for all `i`, where `m_i` is the\n multiplicity of `i` in `\\lambda`.\n\n .. NOTE::\n\n This is conjugate to the notion of `\\ell`-*restricted* partitions,\n where the difference between any two consecutive\n parts is `< \\ell`.\n\n INPUT:\n\n - ``ell`` -- the positive integer `\\ell`\n - ``is_infinite`` -- boolean; if the subset of `\\ell`-regular\n partitions is infinite\n '
def __init__(self, ell, is_infinite=False):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=2)\n sage: TestSuite(P).run()\n '
self._ell = ell
Partitions.__init__(self, is_infinite)
def ell(self):
'\n Return the value `\\ell`.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=2)\n sage: P.ell()\n 2\n '
return self._ell
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(regular=3)\n sage: [5] in P\n True\n sage: [] in P\n True\n sage: [3, 3, 2, 2] in P\n True\n sage: [3, 3, 3, 1] in P\n False\n sage: [4, 0, 0, 0, 0, 0] in P\n True\n sage: Partition([4,2,2,1]) in P\n True\n sage: Partition([4,2,2,2]) in P\n False\n sage: Partition([10,1]) in P\n True\n '
if (not Partitions.__contains__(self, x)):
return False
if isinstance(x, Partition):
return (max((x.to_exp() + [0])) < self._ell)
return all(((x.count(i) < self._ell) for i in set(x) if (i > 0)))
def _fast_iterator(self, n, max_part):
'\n A fast (recursive) iterator which returns a list.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=3)\n sage: list(P._fast_iterator(5, 5))\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1]]\n sage: list(P._fast_iterator(5, 3))\n [[3, 2], [3, 1, 1], [2, 2, 1]]\n sage: list(P._fast_iterator(5, 6))\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1]]\n '
if (n == 0):
(yield [])
return
if (n < max_part):
max_part = n
bdry = (self._ell - 1)
for i in reversed(range(1, (max_part + 1))):
for p in self._fast_iterator((n - i), i):
if (p.count(i) < bdry):
(yield ([i] + p))
|
class RegularPartitions_all(RegularPartitions):
'\n The class of all `\\ell`-regular partitions.\n\n INPUT:\n\n - ``ell`` -- the positive integer `\\ell`\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RegularPartitions`\n '
def __init__(self, ell):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=4)\n sage: TestSuite(P).run()\n\n 1-regular partitions::\n\n sage: P = Partitions(regular=1)\n sage: P in FiniteEnumeratedSets()\n True\n sage: TestSuite(P).run()\n '
RegularPartitions.__init__(self, ell, bool((ell > 1)))
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RegularPartitions_all\n sage: RegularPartitions_all(3)\n 3-Regular Partitions\n '
return '{}-Regular Partitions'.format(self._ell)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=3)\n sage: it = P.__iter__()\n sage: [next(it) for x in range(10)]\n [[], [1], [2], [1, 1], [3], [2, 1], [4], [3, 1], [2, 2], [2, 1, 1]]\n\n Check that 1-regular partitions works (:trac:`20584`)::\n\n sage: P = Partitions(regular=1)\n sage: list(P)\n [[]]\n '
if (self._ell == 1):
(yield self.element_class(self, []))
return
n = 0
while True:
for p in self._fast_iterator(n, n):
(yield self.element_class(self, p))
n += 1
|
class RegularPartitions_truncated(RegularPartitions):
'\n The class of `\\ell`-regular partitions with max length `k`.\n\n INPUT:\n\n - ``ell`` -- the integer `\\ell`\n - ``max_len`` -- integer; the maximum length\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RegularPartitions`\n '
def __init__(self, ell, max_len):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=4, max_length=3)\n sage: TestSuite(P).run()\n '
self._max_len = max_len
RegularPartitions.__init__(self, ell, bool((ell > 1)))
def max_length(self):
'\n Return the maximum length of the partitions of ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=4, max_length=3)\n sage: P.max_length()\n 3\n '
return self._max_len
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(regular=4, max_length=3)\n sage: [3, 3, 3] in P\n True\n sage: [] in P\n True\n sage: [4, 2, 1, 1] in P\n False\n '
return ((len(x) <= self._max_len) and RegularPartitions.__contains__(self, x))
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RegularPartitions_truncated\n sage: RegularPartitions_truncated(4, 3)\n 4-Regular Partitions with max length 3\n '
return '{}-Regular Partitions with max length {}'.format(self._ell, self._max_len)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=3, max_length=2)\n sage: it = P.__iter__()\n sage: [next(it) for x in range(10)]\n [[], [1], [2], [1, 1], [3], [2, 1], [4], [3, 1], [2, 2], [5]]\n\n Check that 1-regular partitions works (:trac:`20584`)::\n\n sage: P = Partitions(regular=1, max_length=2)\n sage: list(P)\n [[]]\n '
if (self._ell == 1):
(yield self.element_class(self, []))
return
n = 0
while True:
for p in self._fast_iterator(n, n):
(yield self.element_class(self, p))
n += 1
def _fast_iterator(self, n, max_part, depth=0):
'\n A fast (recursive) iterator which returns a list.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=2, max_length=2)\n sage: list(P._fast_iterator(5, 5))\n [[5], [4, 1], [3, 2]]\n sage: list(P._fast_iterator(5, 3))\n [[3, 2]]\n sage: list(P._fast_iterator(5, 6))\n [[5], [4, 1], [3, 2]]\n '
if ((n == 0) or (depth >= self._max_len)):
(yield [])
return
if ((depth + 1) == self._max_len):
if (max_part >= n):
(yield [n])
return
if (n < max_part):
max_part = n
bdry = (self._ell - 1)
for i in reversed(range(1, (max_part + 1))):
for p in self._fast_iterator((n - i), i, (depth + 1)):
if (p.count(i) < bdry):
(yield ([i] + p))
|
class RegularPartitions_bounded(RegularPartitions):
'\n The class of `\\ell`-regular `k`-bounded partitions.\n\n INPUT:\n\n - ``ell`` -- the integer `\\ell`\n - ``k`` -- integer; the value `k`\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RegularPartitions`\n '
def __init__(self, ell, k):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=4, max_part=3)\n sage: TestSuite(P).run()\n\n 1-regular partitions::\n\n sage: P = Partitions(regular=1, max_part=3)\n sage: P in FiniteEnumeratedSets()\n True\n sage: TestSuite(P).run()\n '
self.k = k
RegularPartitions.__init__(self, ell, False)
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(regular=4, max_part=3)\n sage: [3, 3, 3] in P\n True\n sage: [] in P\n True\n sage: [4, 2, 1] in P\n False\n '
return ((len(x) == 0) or ((x[0] <= self.k) and RegularPartitions.__contains__(self, x)))
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RegularPartitions_bounded\n sage: RegularPartitions_bounded(4, 3)\n 4-Regular 3-Bounded Partitions\n '
return '{}-Regular {}-Bounded Partitions'.format(self._ell, self.k)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(regular=2, max_part=3)\n sage: list(P)\n [[3, 2, 1], [3, 2], [3, 1], [3], [2, 1], [2], [1], []]\n\n Check that 1-regular partitions works (:trac:`20584`)::\n\n sage: P = Partitions(regular=1, max_part=3)\n sage: list(P)\n [[]]\n '
k = self.k
for n in reversed(range((((k * (k + 1)) / 2) * self._ell))):
for p in self._fast_iterator(n, k):
(yield self.element_class(self, p))
|
class RegularPartitions_n(RegularPartitions, Partitions_n):
'\n The class of `\\ell`-regular partitions of `n`.\n\n INPUT:\n\n - ``n`` -- the integer `n` to partition\n - ``ell`` -- the integer `\\ell`\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RegularPartitions`\n '
def __init__(self, n, ell):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, regular=3)\n sage: TestSuite(P).run()\n\n 1-regular partitions::\n\n sage: P = Partitions(5, regular=1)\n sage: TestSuite(P).run()\n '
RegularPartitions.__init__(self, ell)
Partitions_n.__init__(self, n)
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RegularPartitions_n\n sage: RegularPartitions_n(3, 5)\n 5-Regular Partitions of the integer 3\n '
return '{}-Regular Partitions of the integer {}'.format(self._ell, self.n)
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(5, regular=3)\n sage: [3, 1, 1] in P\n True\n sage: [3, 2, 1] in P\n False\n '
return (RegularPartitions.__contains__(self, x) and (sum(x) == self.n))
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, regular=3)\n sage: list(P)\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1]]\n '
for p in self._fast_iterator(self.n, self.n):
(yield self.element_class(self, p))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, regular=3)\n sage: P.cardinality() # needs sage.libs.flint\n 5\n sage: P = Partitions(5, regular=6)\n sage: P.cardinality() # needs sage.libs.flint\n 7\n sage: P.cardinality() == Partitions(5).cardinality() # needs sage.libs.flint\n True\n\n TESTS:\n\n Check the corner case::\n\n sage: P = Partitions(0, regular=3)\n sage: P.cardinality() # needs sage.libs.flint\n 1\n\n Check for 1-regular partitions::\n\n sage: P = Partitions(0, regular=1)\n sage: P.cardinality() # needs sage.libs.flint\n 1\n sage: P = Partitions(5, regular=1)\n sage: P.cardinality() # needs sage.libs.flint\n 0\n\n '
if (self._ell > self.n):
return Partitions_n.cardinality(self)
return ZZ.sum((1 for x in self))
def _an_element_(self):
'\n Return a partition in ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, regular=2)\n sage: P._an_element_()\n [4, 1]\n\n sage: P = Partitions(0, regular=1)\n sage: P._an_element_()\n []\n\n sage: P = Partitions(5, regular=1)\n sage: P._an_element_()\n Traceback (most recent call last):\n ...\n EmptySetError\n '
if ((self._ell == 1) and (self.n > 0)):
from sage.categories.sets_cat import EmptySetError
raise EmptySetError
return Partitions_n._an_element_(self)
|
class OrderedPartitions(Partitions):
'\n The class of ordered partitions of `n`. If `k` is specified, then this\n contains only the ordered partitions of length `k`.\n\n An *ordered partition* of a nonnegative integer `n` means a list of\n positive integers whose sum is `n`. This is the same as a composition\n of `n`.\n\n .. NOTE::\n\n It is recommended that you use :meth:`Compositions` instead as\n :meth:`OrderedPartitions` wraps GAP.\n\n EXAMPLES::\n\n sage: OrderedPartitions(3)\n Ordered partitions of 3\n sage: OrderedPartitions(3).list() # needs sage.libs.gap\n [[3], [2, 1], [1, 2], [1, 1, 1]]\n sage: OrderedPartitions(3,2)\n Ordered partitions of 3 of length 2\n sage: OrderedPartitions(3,2).list() # needs sage.libs.gap\n [[2, 1], [1, 2]]\n\n sage: OrderedPartitions(10, k=2).list() # needs sage.libs.gap\n [[9, 1], [8, 2], [7, 3], [6, 4], [5, 5], [4, 6], [3, 7], [2, 8], [1, 9]]\n sage: OrderedPartitions(4).list() # needs sage.libs.gap\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 3], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n\n '
@staticmethod
def __classcall_private__(cls, n, k=None):
'\n Normalize the input to ensure a unique representation.\n\n TESTS::\n\n sage: P = OrderedPartitions(3,2)\n sage: P2 = OrderedPartitions(3,2)\n sage: P is P2\n True\n '
if (k is not None):
k = Integer(k)
return super().__classcall__(cls, Integer(n), k)
def __init__(self, n, k):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: o = OrderedPartitions(4,2)\n\n TESTS::\n\n sage: TestSuite( OrderedPartitions(5,3) ).run() # needs sage.libs.gap\n '
Partitions.__init__(self)
self.n = n
self.k = k
def __contains__(self, x):
'\n Check to see if ``x`` is an element of ``self``.\n\n EXAMPLES::\n\n sage: o = OrderedPartitions(4,2)\n sage: [2,1] in o\n False\n sage: [2,2] in o\n True\n sage: [1,2,1] in o\n False\n '
C = composition.Compositions(self.n, length=self.k)
return (C(x) in composition.Compositions(self.n, length=self.k))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: OrderedPartitions(3) # indirect doctest\n Ordered partitions of 3\n sage: OrderedPartitions(3,2) # indirect doctest\n Ordered partitions of 3 of length 2\n '
string = ('Ordered partitions of %s' % self.n)
if (self.k is not None):
string += (' of length %s' % self.k)
return string
def list(self):
'\n Return a list of partitions in ``self``.\n\n EXAMPLES::\n\n sage: OrderedPartitions(3).list() # needs sage.libs.gap\n [[3], [2, 1], [1, 2], [1, 1, 1]]\n sage: OrderedPartitions(3,2).list() # needs sage.libs.gap\n [[2, 1], [1, 2]]\n '
from sage.libs.gap.libgap import libgap
n = self.n
k = self.k
if (k is None):
ans = libgap.OrderedPartitions(ZZ(n))
else:
ans = libgap.OrderedPartitions(ZZ(n), ZZ(k))
result = ans.sage()
result.reverse()
return result
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.libs.gap\n sage: OrderedPartitions(3).cardinality()\n 4\n sage: OrderedPartitions(3,2).cardinality()\n 2\n sage: OrderedPartitions(10,2).cardinality()\n 9\n sage: OrderedPartitions(15).cardinality()\n 16384\n '
from sage.libs.gap.libgap import libgap
n = self.n
k = self.k
if (k is None):
ans = libgap.NrOrderedPartitions(n)
else:
ans = libgap.NrOrderedPartitions(n, k)
return ZZ(ans)
|
class PartitionsGreatestLE(UniqueRepresentation, IntegerListsLex):
'\n The class of all (unordered) "restricted" partitions of the integer `n`\n having parts less than or equal to the integer `k`.\n\n EXAMPLES::\n\n sage: PartitionsGreatestLE(10, 2)\n Partitions of 10 having parts less than or equal to 2\n sage: PartitionsGreatestLE(10, 2).list()\n [[2, 2, 2, 2, 2],\n [2, 2, 2, 2, 1, 1],\n [2, 2, 2, 1, 1, 1, 1],\n [2, 2, 1, 1, 1, 1, 1, 1],\n [2, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n\n sage: [4,3,2,1] in PartitionsGreatestLE(10, 2)\n False\n sage: [2,2,2,2,2] in PartitionsGreatestLE(10, 2)\n True\n sage: PartitionsGreatestLE(10, 2).first().parent()\n Partitions...\n '
def __init__(self, n, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: p = PartitionsGreatestLE(10, 2)\n sage: p.n, p.k\n (10, 2)\n sage: TestSuite(p).run()\n '
IntegerListsLex.__init__(self, n, max_slope=0, min_part=1, max_part=k)
self.n = n
self.k = k
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: PartitionsGreatestLE(10, 2) # indirect doctest\n Partitions of 10 having parts less than or equal to 2\n '
return ('Partitions of %s having parts less than or equal to %s' % (self.n, self.k))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: PartitionsGreatestLE(9, 5).cardinality() # needs sage.libs.gap\n 23\n\n TESTS::\n\n sage: all(PartitionsGreatestLE(n, a).cardinality() == # needs sage.libs.gap\n ....: len(PartitionsGreatestLE(n, a).list())\n ....: for n in range(20) for a in range(6))\n True\n\n '
return sum((number_of_partitions_length(self.n, i) for i in range((self.k + 1))))
Element = Partition
options = Partitions.options
|
class PartitionsGreatestEQ(UniqueRepresentation, IntegerListsLex):
'\n The class of all (unordered) "restricted" partitions of the integer `n`\n having all its greatest parts equal to the integer `k`.\n\n EXAMPLES::\n\n sage: PartitionsGreatestEQ(10, 2)\n Partitions of 10 having greatest part equal to 2\n sage: PartitionsGreatestEQ(10, 2).list()\n [[2, 2, 2, 2, 2],\n [2, 2, 2, 2, 1, 1],\n [2, 2, 2, 1, 1, 1, 1],\n [2, 2, 1, 1, 1, 1, 1, 1],\n [2, 1, 1, 1, 1, 1, 1, 1, 1]]\n\n sage: [4,3,2,1] in PartitionsGreatestEQ(10, 2)\n False\n sage: [2,2,2,2,2] in PartitionsGreatestEQ(10, 2)\n True\n\n The empty partition has no maximal part, but it is contained in\n the set of partitions with any specified maximal part::\n\n sage: PartitionsGreatestEQ(0, 2).list()\n [[]]\n\n TESTS::\n\n sage: [1]*10 in PartitionsGreatestEQ(10, 2)\n False\n\n sage: PartitionsGreatestEQ(10, 2).first().parent()\n Partitions...\n\n '
def __init__(self, n, k):
'\n Initialize ``self``.\n\n TESTS::\n\n sage: p = PartitionsGreatestEQ(10, 2)\n sage: p.n, p.k\n (10, 2)\n sage: TestSuite(p).run()\n '
IntegerListsLex.__init__(self, n, max_slope=0, max_part=k, floor=[k])
self.n = n
self.k = k
def _repr_(self):
'\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: PartitionsGreatestEQ(10, 2) # indirect doctest\n Partitions of 10 having greatest part equal to 2\n '
return ('Partitions of %s having greatest part equal to %s' % (self.n, self.k))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: PartitionsGreatestEQ(10, 2).cardinality()\n 5\n\n TESTS::\n\n sage: all(PartitionsGreatestEQ(n, a).cardinality() == # needs sage.libs.flint\n ....: len(PartitionsGreatestEQ(n, a).list())\n ....: for n in range(20) for a in range(6))\n True\n\n '
if (not self.n):
return 1
return number_of_partitions_length(self.n, self.k)
Element = Partition
options = Partitions.options
|
class RestrictedPartitions_generic(Partitions):
'\n Base class for `\\ell`-restricted partitions.\n\n Let `\\ell` be a positive integer. A partition `\\lambda` is\n `\\ell`-*restricted* if `\\lambda_i - \\lambda_{i+1} < \\ell` for all `i`,\n including rows of length 0.\n\n .. NOTE::\n\n This is conjugate to the notion of `\\ell`-*regular* partitions,\n where the multiplicity of any parts is at most `\\ell`.\n\n INPUT:\n\n - ``ell`` -- the positive integer `\\ell`\n - ``is_infinite`` -- boolean; if the subset of `\\ell`-restricted\n partitions is infinite\n '
def __init__(self, ell, is_infinite=False):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(restricted=2)\n sage: TestSuite(P).run()\n '
self._ell = ell
Partitions.__init__(self, is_infinite)
def ell(self):
'\n Return the value `\\ell`.\n\n EXAMPLES::\n\n sage: P = Partitions(restricted=2)\n sage: P.ell()\n 2\n '
return self._ell
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(restricted=3)\n sage: [5] in P\n False\n sage: [2] in P\n True\n sage: [] in P\n True\n sage: [3, 3, 3, 3, 2, 2] in P\n True\n sage: [3, 3, 3, 1] in P\n True\n sage: [8, 3, 3, 1] in P\n False\n sage: [2, 0, 0, 0, 0, 0] in P\n True\n sage: Partition([4,2,2,1]) in P\n True\n sage: Partition([4,2,2,2]) in P\n True\n sage: Partition([6,6,6,6,4,3,2]) in P\n True\n sage: Partition([7,6,6,2]) in P\n False\n sage: Partition([6,5]) in P\n False\n sage: Partition([10,1]) in P\n False\n sage: Partition([3,3] + [1]*10) in P\n True\n '
if (not Partitions.__contains__(self, x)):
return False
if (x == []):
return True
return (all((((x[i] - x[(i + 1)]) < self._ell) for i in range((len(x) - 1)))) and (x[(- 1)] < self._ell))
def _fast_iterator(self, n, max_part):
'\n A fast (recursive) iterator which returns a list.\n\n EXAMPLES::\n\n sage: P = Partitions(restricted=3)\n sage: list(P._fast_iterator(5, 5))\n [[3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: list(P._fast_iterator(5, 2))\n [[2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n\n TESTS::\n\n sage: for n in range(10):\n ....: for ell in range(2, n):\n ....: Pres = Partitions(n, restricted=ell)\n ....: Preg = Partitions(n, regular=ell)\n ....: assert set(Pres) == set(p.conjugate() for p in Preg)\n '
if (n == 0):
(yield [])
return
if (n < max_part):
max_part = n
for i in range(max_part, 0, (- 1)):
for p in self._fast_iterator((n - i), i):
if ((p and ((i - p[0]) >= self._ell)) or ((not p) and (i >= self._ell))):
break
(yield ([i] + p))
|
class RestrictedPartitions_all(RestrictedPartitions_generic):
'\n The class of all `\\ell`-restricted partitions.\n\n INPUT:\n\n - ``ell`` -- the positive integer `\\ell`\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RestrictedPartitions_generic`\n '
def __init__(self, ell):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(restricted=4)\n sage: TestSuite(P).run()\n '
RestrictedPartitions_generic.__init__(self, ell, True)
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RestrictedPartitions_all\n sage: RestrictedPartitions_all(3)\n 3-Restricted Partitions\n '
return '{}-Restricted Partitions'.format(self._ell)
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(restricted=3)\n sage: it = P.__iter__()\n sage: [next(it) for x in range(10)]\n [[], [1], [2], [1, 1], [2, 1], [1, 1, 1],\n [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n '
n = 0
while True:
for p in self._fast_iterator(n, n):
(yield self.element_class(self, p))
n += 1
|
class RestrictedPartitions_n(RestrictedPartitions_generic, Partitions_n):
'\n The class of `\\ell`-restricted partitions of `n`.\n\n INPUT:\n\n - ``n`` -- the integer `n` to partition\n - ``ell`` -- the integer `\\ell`\n\n .. SEEALSO::\n\n :class:`~sage.combinat.partition.RestrictedPartitions_generic`\n '
def __init__(self, n, ell):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, restricted=3)\n sage: TestSuite(P).run()\n '
RestrictedPartitions_generic.__init__(self, ell)
Partitions_n.__init__(self, n)
def _repr_(self):
'\n TESTS::\n\n sage: from sage.combinat.partition import RestrictedPartitions_n\n sage: RestrictedPartitions_n(3, 5)\n 5-Restricted Partitions of the integer 3\n '
return '{}-Restricted Partitions of the integer {}'.format(self._ell, self.n)
def __contains__(self, x):
'\n TESTS::\n\n sage: P = Partitions(5, regular=3)\n sage: [3, 1, 1] in P\n True\n sage: [3, 2, 1] in P\n False\n '
return (RestrictedPartitions_generic.__contains__(self, x) and (sum(x) == self.n))
def __iter__(self):
'\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, restricted=3)\n sage: list(P)\n [[3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n '
for p in self._fast_iterator(self.n, self.n):
(yield self.element_class(self, p))
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, restricted=3)\n sage: P.cardinality() # needs sage.libs.flint\n 5\n sage: P = Partitions(5, restricted=6)\n sage: P.cardinality() # needs sage.libs.flint\n 7\n sage: P.cardinality() == Partitions(5).cardinality() # needs sage.libs.flint\n True\n '
if (self._ell > self.n):
return Partitions_n.cardinality(self)
return ZZ.sum((ZZ.one() for x in self))
def _an_element_(self):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: P = Partitions(5, restricted=3)\n sage: P.an_element()\n [2, 1, 1, 1]\n\n sage: Partitions(0, restricted=3).an_element()\n []\n sage: Partitions(1, restricted=3).an_element()\n [1]\n '
return self.element_class(self, Partitions_n._an_element_(self).conjugate())
|
def number_of_partitions(n, algorithm='default'):
"\n Return the number of partitions of `n` with, optionally, at most `k`\n parts.\n\n The options of :meth:`number_of_partitions()` are being deprecated\n :trac:`13072` in favour of :meth:`Partitions_n.cardinality()` so that\n :meth:`number_of_partitions()` can become a stripped down version of\n the fastest algorithm available (currently this is using FLINT).\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``algorithm`` -- (default: 'default')\n [Will be deprecated except in Partition().cardinality() ]\n\n - ``'default'`` -- If ``k`` is not ``None``, then use Gap (very slow).\n If ``k`` is ``None``, use FLINT.\n\n - ``'flint'`` -- use FLINT\n\n EXAMPLES::\n\n sage: v = Partitions(5).list(); v\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: len(v)\n 7\n\n The input must be a nonnegative integer or a ``ValueError`` is raised.\n\n ::\n\n sage: number_of_partitions(-5)\n Traceback (most recent call last):\n ...\n ValueError: n (=-5) must be a nonnegative integer\n\n ::\n\n sage: # needs sage.libs.flint\n sage: number_of_partitions(10)\n 42\n sage: number_of_partitions(3)\n 3\n sage: number_of_partitions(10)\n 42\n sage: number_of_partitions(40)\n 37338\n sage: number_of_partitions(100)\n 190569292\n sage: number_of_partitions(100000)\n 27493510569775696512677516320986352688173429315980054758203125984302147328114964173055050741660736621590157844774296248940493063070200461792764493033510116079342457190155718943509725312466108452006369558934464248716828789832182345009262853831404597021307130674510624419227311238999702284408609370935531629697851569569892196108480158600569421098519\n\n A generating function for the number of partitions `p_n` is given by the\n reciprocal of Euler's function:\n\n .. MATH::\n\n \\sum_{n=0}^{\\infty} p_n x^n = \\prod_{k=1}^{\\infty} \\left(\n \\frac{1}{1-x^k} \\right).\n\n We use Sage to verify that the first several coefficients do\n instead agree::\n\n sage: q = PowerSeriesRing(QQ, 'q', default_prec=9).gen()\n sage: prod([(1-q^k)^(-1) for k in range(1,9)]) # partial product of\n 1 + q + 2*q^2 + 3*q^3 + 5*q^4 + 7*q^5 + 11*q^6 + 15*q^7 + 22*q^8 + O(q^9)\n sage: [number_of_partitions(k) for k in range(2,10)] # needs sage.libs.flint\n [2, 3, 5, 7, 11, 15, 22, 30]\n\n REFERENCES:\n\n - :wikipedia:`Partition\\_(number\\_theory)`\n\n TESTS::\n\n sage: # needs sage.libs.flint\n sage: n = 500 + randint(0,500)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1500 + randint(0,1500)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 1000000 + randint(0,1000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0\n True\n sage: n = 100000000 + randint(0,100000000)\n sage: number_of_partitions( n - (n % 385) + 369) % 385 == 0 # long time (4s on sage.math, 2011)\n True\n\n "
n = ZZ(n)
if (n < 0):
raise ValueError(('n (=%s) must be a nonnegative integer' % n))
elif (n == 0):
return ZZ.one()
if (algorithm == 'default'):
algorithm = 'flint'
if (algorithm == 'flint'):
return cached_number_of_partitions(n)
raise ValueError(("unknown algorithm '%s'" % algorithm))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.