code
stringlengths
17
6.64M
@cached_function(key=(lambda n, k, a: (n, k))) def eulerian_number(n, k, algorithm='recursive') -> Integer: '\n Return the Eulerian number of index ``(n, k)``.\n\n This is the coefficient of `t^k` in the Eulerian polynomial `A_n(t)`.\n\n INPUT:\n\n - ``n`` -- integer\n\n - ``k`` -- integer between ``0`` and ``n - 1``\n\n - ``algorithm`` -- ``"recursive"`` (default) or ``"formula"``\n\n OUTPUT:\n\n an integer\n\n .. SEEALSO:: :func:`eulerian_polynomial`\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import eulerian_number\n sage: [eulerian_number(5,i) for i in range(5)]\n [1, 26, 66, 26, 1]\n\n TESTS::\n\n sage: [eulerian_number(6,i,"formula") for i in range(6)]\n [1, 57, 302, 302, 57, 1]\n sage: [eulerian_number(3,i) for i in range(-1, 4)]\n [0, 1, 4, 1, 0]\n ' n = ZZ(n) if ((k < 0) or (k > (n - 1))): return ZZ.zero() if ((k == 0) or (k == (n - 1))): return ZZ.one() if (algorithm == 'recursive'): s = ((n - k) * eulerian_number((n - 1), (k - 1), algorithm=algorithm)) s += ((k + 1) * eulerian_number((n - 1), k, algorithm=algorithm)) return s return sum((((((- 1) ** m) * (n + 1).binomial(m)) * (((k + 1) - m) ** n)) for m in range((k + 1))))
@cached_function(key=(lambda n, a: n)) def eulerian_polynomial(n, algorithm='derivative'): '\n Return the Eulerian polynomial of index ``n``.\n\n This is the generating polynomial counting permutations in the\n symmetric group `S_n` according to their number of descents.\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``algorithm`` -- ``"derivative"`` (default) or ``"coeffs"``\n\n OUTPUT:\n\n polynomial in one variable ``t``\n\n .. SEEALSO:: :func:`eulerian_number`\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import eulerian_polynomial\n sage: eulerian_polynomial(5)\n t^4 + 26*t^3 + 66*t^2 + 26*t + 1\n\n TESTS::\n\n sage: eulerian_polynomial(7)(1) == factorial(7)\n True\n\n sage: eulerian_polynomial(6, algorithm=\'coeffs\')\n t^5 + 57*t^4 + 302*t^3 + 302*t^2 + 57*t + 1\n\n REFERENCES:\n\n - :wikipedia:`Eulerian_number`\n ' n = ZZ(n) R = PolynomialRing(ZZ, 't') if (n < 0): return R.zero() if (n == 1): return R.one() t = R.gen() if (algorithm == 'derivative'): A = eulerian_polynomial((n - 1), algorithm=algorithm) return (((t * (1 - t)) * A.derivative()) + ((1 + ((n - 1) * t)) * A)) elif (algorithm == 'coeffs'): return R([eulerian_number(n, k, 'formula') for k in range(n)])
def fibonacci(n, algorithm='pari') -> Integer: '\n Return the `n`-th Fibonacci number.\n\n The Fibonacci sequence `F_n` is defined by the initial\n conditions `F_1 = F_2 = 1` and the recurrence relation\n `F_{n+2} = F_{n+1} + F_n`. For negative `n` we\n define `F_n = (-1)^{n+1}F_{-n}`, which is consistent with\n the recurrence relation.\n\n INPUT:\n\n - ``algorithm`` -- a string:\n\n * ``"pari"`` - (default) use the PARI C library\'s\n :pari:`fibo` function\n\n * ``"gap"`` - use GAP\'s Fibonacci function\n\n .. NOTE::\n\n PARI is tens to hundreds of times faster than GAP here.\n Moreover, PARI works for every large input whereas GAP does not.\n\n EXAMPLES::\n\n sage: fibonacci(10) # needs sage.libs.pari\n 55\n sage: fibonacci(10, algorithm=\'gap\') # needs sage.libs.gap\n 55\n\n ::\n\n sage: fibonacci(-100) # needs sage.libs.pari\n -354224848179261915075\n sage: fibonacci(100) # needs sage.libs.pari\n 354224848179261915075\n\n ::\n\n sage: fibonacci(0) # needs sage.libs.pari\n 0\n sage: fibonacci(1/2)\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n ' n = ZZ(n) if (algorithm == 'pari'): return ZZ(pari(n).fibonacci()) elif (algorithm == 'gap'): from sage.libs.gap.libgap import libgap return libgap.Fibonacci(n).sage() else: raise ValueError('no algorithm {}'.format(algorithm))
def lucas_number1(n, P, Q): '\n Return the `n`-th Lucas number "of the first kind" (this is not\n standard terminology). The Lucas sequence `L^{(1)}_n` is\n defined by the initial conditions `L^{(1)}_1 = 0`,\n `L^{(1)}_2 = 1` and the recurrence relation\n `L^{(1)}_{n+2} = P \\cdot L^{(1)}_{n+1} - Q \\cdot L^{(1)}_n`.\n\n Wraps GAP\'s ``Lucas(...)[1]``.\n\n `P=1`, `Q=-1` gives the Fibonacci sequence.\n\n INPUT:\n\n - ``n`` -- integer\n\n - ``P, Q`` -- integer or rational numbers\n\n OUTPUT: integer or rational number\n\n EXAMPLES::\n\n sage: # needs sage.libs.gap\n sage: lucas_number1(5,1,-1)\n 5\n sage: lucas_number1(6,1,-1)\n 8\n sage: lucas_number1(7,1,-1)\n 13\n sage: lucas_number1(7,1,-2)\n 43\n sage: lucas_number1(5,2,3/5)\n 229/25\n sage: lucas_number1(5,2,1.5)\n 1/4\n\n There was a conjecture that the sequence `L_n` defined by\n `L_{n+2} = L_{n+1} + L_n`, `L_1=1`,\n `L_2=3`, has the property that `n` prime implies\n that `L_n` is prime. ::\n\n sage: def lucas(n):\n ....: return Integer((5/2)*lucas_number1(n,1,-1) + (1/2)*lucas_number2(n,1,-1))\n sage: [[lucas(n), is_prime(lucas(n)), n+1, is_prime(n+1)] for n in range(15)] # needs sage.libs.gap\n [[1, False, 1, False],\n [3, True, 2, True],\n [4, False, 3, True],\n [7, True, 4, False],\n [11, True, 5, True],\n [18, False, 6, False],\n [29, True, 7, True],\n [47, True, 8, False],\n [76, False, 9, False],\n [123, False, 10, False],\n [199, True, 11, True],\n [322, False, 12, False],\n [521, True, 13, True],\n [843, False, 14, False],\n [1364, False, 15, False]]\n\n Can you use Sage to find a counterexample to the conjecture?\n ' n = ZZ(n) P = QQ(P) Q = QQ(Q) from sage.libs.gap.libgap import libgap return libgap.Lucas(P, Q, n)[0].sage()
def lucas_number2(n, P, Q): '\n Return the `n`-th Lucas number "of the second kind" (this is not\n standard terminology). The Lucas sequence `L^{(2)}_n` is\n defined by the initial conditions `L^{(2)}_1 = 2`,\n `L^{(2)}_2 = P` and the recurrence relation\n `L^{(2)}_{n+2} = P \\cdot L^{(2)}_{n+1} - Q \\cdot L^{(2)}_n`.\n\n Wraps GAP\'s Lucas(...)[2].\n\n INPUT:\n\n\n - ``n`` - integer\n\n - ``P, Q`` - integer or rational numbers\n\n\n OUTPUT: integer or rational number\n\n EXAMPLES::\n\n sage: [lucas_number2(i,1,-1) for i in range(10)] # needs sage.libs.gap\n [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]\n sage: [fibonacci(i-1)+fibonacci(i+1) for i in range(10)] # needs sage.libs.pari\n [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]\n\n ::\n\n sage: # needs sage.libs.gap\n sage: n = lucas_number2(5,2,3); n\n 2\n sage: type(n)\n <class \'sage.rings.integer.Integer\'>\n sage: n = lucas_number2(5,2,-3/9); n\n 418/9\n sage: type(n)\n <class \'sage.rings.rational.Rational\'>\n\n The case `P=1`, `Q=-1` is the Lucas sequence in Brualdi\'s Introductory\n Combinatorics, 4th ed., Prentice-Hall, 2004::\n\n sage: [lucas_number2(n,1,-1) for n in range(10)] # needs sage.libs.gap\n [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]\n ' n = ZZ(n) P = QQ(P) Q = QQ(Q) from sage.libs.gap.libgap import libgap return libgap.Lucas(P, Q, n)[1].sage()
def stirling_number1(n, k, algorithm='gap') -> Integer: '\n Return the `n`-th Stirling number `S_1(n,k)` of the first kind.\n\n This is the number of permutations of `n` points with `k` cycles.\n\n See :wikipedia:`Stirling_numbers_of_the_first_kind`.\n\n INPUT:\n\n - ``n`` -- nonnegative machine-size integer\n - ``k`` -- nonnegative machine-size integer\n - ``algorithm``:\n\n * ``"gap"`` (default) -- use GAP\'s ``Stirling1`` function\n * ``"flint"`` -- use flint\'s ``arith_stirling_number_1u`` function\n\n EXAMPLES::\n\n sage: # needs sage.libs.gap\n sage: stirling_number1(3,2)\n 3\n sage: stirling_number1(5,2)\n 50\n sage: 9*stirling_number1(9,5) + stirling_number1(9,4)\n 269325\n sage: stirling_number1(10,5)\n 269325\n\n Indeed, `S_1(n,k) = S_1(n-1,k-1) + (n-1)S_1(n-1,k)`.\n\n TESTS::\n\n sage: stirling_number1(10,5, algorithm=\'flint\') # needs sage.libs.flint\n 269325\n\n sage: s_sage = stirling_number1(50,3, algorithm="mutta")\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm: mutta\n ' n = ZZ(n) k = ZZ(k) if (algorithm == 'gap'): from sage.libs.gap.libgap import libgap return libgap.Stirling1(n, k).sage() if (algorithm == 'flint'): import sage.libs.flint.arith return sage.libs.flint.arith.stirling_number_1(n, k) raise ValueError(('unknown algorithm: %s' % algorithm))
def stirling_number2(n, k, algorithm=None) -> Integer: '\n Return the `n`-th Stirling number `S_2(n,k)` of the second kind.\n\n This is the number of ways to partition a set of `n` elements into `k`\n pairwise disjoint nonempty subsets. The `n`-th Bell number is the\n sum of the `S_2(n,k)`\'s, `k=0,...,n`.\n\n See :wikipedia:`Stirling_numbers_of_the_second_kind`.\n\n INPUT:\n\n - ``n`` -- nonnegative machine-size integer\n - ``k`` -- nonnegative machine-size integer\n - ``algorithm``:\n\n * ``None`` (default) -- use native implementation\n * ``"flint"`` -- use flint\'s ``arith_stirling_number_2`` function\n * ``"gap"`` -- use GAP\'s ``Stirling2`` function\n * ``"maxima"`` -- use Maxima\'s ``stirling2`` function\n\n EXAMPLES:\n\n Print a table of the first several Stirling numbers of the second kind::\n\n sage: for n in range(10):\n ....: for k in range(10):\n ....: print(str(stirling_number2(n,k)).rjust(k and 6))\n 1 0 0 0 0 0 0 0 0 0\n 0 1 0 0 0 0 0 0 0 0\n 0 1 1 0 0 0 0 0 0 0\n 0 1 3 1 0 0 0 0 0 0\n 0 1 7 6 1 0 0 0 0 0\n 0 1 15 25 10 1 0 0 0 0\n 0 1 31 90 65 15 1 0 0 0\n 0 1 63 301 350 140 21 1 0 0\n 0 1 127 966 1701 1050 266 28 1 0\n 0 1 255 3025 7770 6951 2646 462 36 1\n\n Stirling numbers satisfy `S_2(n,k) = S_2(n-1,k-1) + kS_2(n-1,k)`::\n\n sage: 5*stirling_number2(9,5) + stirling_number2(9,4)\n 42525\n sage: stirling_number2(10,5)\n 42525\n\n TESTS::\n\n sage: stirling_number2(500,501)\n 0\n sage: stirling_number2(500,500)\n 1\n sage: stirling_number2(500,499)\n 124750\n sage: stirling_number2(500,498)\n 7739801875\n sage: stirling_number2(500,497)\n 318420320812125\n sage: stirling_number2(500,0)\n 0\n sage: stirling_number2(500,1)\n 1\n sage: stirling_number2(500,2)\n 1636695303948070935006594848413799576108321023021532394741645684048066898202337277441635046162952078575443342063780035504608628272942696526664263794687\n sage: stirling_number2(500,3)\n 6060048632644989473730877846590553186337230837666937173391005972096766698597315914033083073801260849147094943827552228825899880265145822824770663507076289563105426204030498939974727520682393424986701281896187487826395121635163301632473646\n sage: stirling_number2(500,30)\n 13707767141249454929449108424328432845001327479099713037876832759323918134840537229737624018908470350134593241314462032607787062188356702932169472820344473069479621239187226765307960899083230982112046605340713218483809366970996051181537181362810003701997334445181840924364501502386001705718466534614548056445414149016614254231944272872440803657763210998284198037504154374028831561296154209804833852506425742041757849726214683321363035774104866182331315066421119788248419742922490386531970053376982090046434022248364782970506521655684518998083846899028416459701847828711541840099891244700173707021989771147674432503879702222276268661726508226951587152781439224383339847027542755222936463527771486827849728880\n sage: stirling_number2(500,31)\n 5832088795102666690960147007601603328246123996896731854823915012140005028360632199516298102446004084519955789799364757997824296415814582277055514048635928623579397278336292312275467402957402880590492241647229295113001728653772550743446401631832152281610081188041624848850056657889275564834450136561842528589000245319433225808712628826136700651842562516991245851618481622296716433577650218003181535097954294609857923077238362717189185577756446945178490324413383417876364657995818830270448350765700419876347023578011403646501685001538551891100379932684279287699677429566813471166558163301352211170677774072447414719380996777162087158124939742564291760392354506347716119002497998082844612434332155632097581510486912\n sage: n = stirling_number2(20,11); n\n 1900842429486\n sage: type(n)\n <class \'sage.rings.integer.Integer\'>\n sage: n_gap = stirling_number2(20, 11, algorithm=\'gap\'); n_gap # needs sage.libs.gap\n 1900842429486\n sage: type(n_gap) # needs sage.libs.gap\n <class \'sage.rings.integer.Integer\'>\n sage: n_flint = stirling_number2(20, 11, algorithm=\'flint\'); n_flint # needs sage.libs.flint\n 1900842429486\n sage: type(n_flint) # needs sage.libs.flint\n <class \'sage.rings.integer.Integer\'>\n\n Sage\'s implementation splitting the computation of the Stirling\n numbers of the second kind in two cases according to `n`, let us\n check the result it gives agree with both flint and gap.\n\n For `n<200`::\n\n sage: for n in Subsets(range(100,200), 5).random_element(): # needs sage.libs.flint sage.libs.gap\n ....: for k in Subsets(range(n), 5).random_element():\n ....: s_sage = stirling_number2(n,k)\n ....: s_flint = stirling_number2(n,k, algorithm = "flint")\n ....: s_gap = stirling_number2(n,k, algorithm = "gap")\n ....: if not (s_sage == s_flint and s_sage == s_gap):\n ....: print("Error with n<200")\n\n For `n\\geq 200`::\n\n sage: for n in Subsets(range(200,300), 5).random_element(): # needs sage.libs.flint sage.libs.gap\n ....: for k in Subsets(range(n), 5).random_element():\n ....: s_sage = stirling_number2(n,k)\n ....: s_flint = stirling_number2(n,k, algorithm = "flint")\n ....: s_gap = stirling_number2(n,k, algorithm = "gap")\n ....: if not (s_sage == s_flint and s_sage == s_gap):\n ....: print("Error with n<200")\n\n sage: stirling_number2(20, 3, algorithm="maxima") # needs sage.symbolic\n 580606446\n\n sage: s_sage = stirling_number2(5, 3, algorithm="namba")\n Traceback (most recent call last):\n ...\n ValueError: unknown algorithm: namba\n ' n = ZZ(n) k = ZZ(k) if (algorithm is None): return _stirling_number2(n, k) if (algorithm == 'gap'): from sage.libs.gap.libgap import libgap return libgap.Stirling2(n, k).sage() if (algorithm == 'flint'): import sage.libs.flint.arith return sage.libs.flint.arith.stirling_number_2(n, k) if (algorithm == 'maxima'): return ZZ(maxima.stirling2(n, k)) raise ValueError(('unknown algorithm: %s' % algorithm))
def polygonal_number(s, n): "\n Return the `n`-th `s`-gonal number.\n\n Polygonal sequences are represented by dots forming a regular polygon.\n Two famous sequences are the triangular numbers (3rd column of Pascal's\n Triangle) and the square numbers. The `n`-th term in a polygonal sequence\n is defined by\n\n .. MATH::\n\n P(s, n) = \\frac{n^2(s-2) - n(s-4)}{2},\n\n where `s` is the number of sides of the polygon.\n\n INPUT:\n\n - ``s`` -- integer greater than 1; the number of sides of the polygon\n\n - ``n`` -- integer; the index of the returned `s`-gonal number\n\n OUTPUT: an integer\n\n EXAMPLES:\n\n The triangular numbers::\n\n sage: [polygonal_number(3, n) for n in range(10)]\n [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]\n\n sage: [polygonal_number(3, n) for n in range(-10, 0)]\n [45, 36, 28, 21, 15, 10, 6, 3, 1, 0]\n\n The square numbers::\n\n sage: [polygonal_number(4, n) for n in range(10)]\n [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n\n The pentagonal numbers::\n\n sage: [polygonal_number(5, n) for n in range(10)]\n [0, 1, 5, 12, 22, 35, 51, 70, 92, 117]\n\n The hexagonal numbers::\n\n sage: [polygonal_number(6, n) for n in range(10)]\n [0, 1, 6, 15, 28, 45, 66, 91, 120, 153]\n\n The input is converted into an integer::\n\n sage: polygonal_number(3.0, 2.0)\n 3\n\n A non-integer input returns an error::\n\n sage: polygonal_number(3.5, 1) # needs sage.rings.real_mpfr\n Traceback (most recent call last):\n ...\n TypeError: Attempt to coerce non-integral RealNumber to Integer\n\n `s` must be greater than 1::\n\n sage: polygonal_number(1, 4)\n Traceback (most recent call last):\n ...\n ValueError: s (=1) must be greater than 1\n\n REFERENCES:\n\n - :wikipedia:`Polygonal_number`\n " s = ZZ(s) n = ZZ(n) if (s < 2): raise ValueError(('s (=%s) must be greater than 1' % s)) return ((((n ** 2) * (s - 2)) - (n * (s - 4))) // 2)
class CombinatorialObject(SageObject): def __init__(self, l, copy=True): "\n CombinatorialObject provides a thin wrapper around a list. The main\n differences are that __setitem__ is disabled so that\n CombinatorialObjects are shallowly immutable, and the intention is\n that they are semantically immutable.\n\n Because of this, CombinatorialObjects provide a __hash__\n function which computes the hash of the string representation of a\n list and the hash of its parent's class. Thus, each\n CombinatorialObject should have a unique string representation.\n\n .. SEEALSO::\n\n :class:`CombinatorialElement` if you want a combinatorial\n object which is an element of a parent.\n\n .. WARNING::\n\n This class is slowly being deprecated. Use\n :class:`~sage.structure.list_clone.ClonableList` instead.\n\n INPUT:\n\n - ``l`` -- a list or any object that can be converted to a\n list by calling ``list()``.\n\n - ``copy`` -- (boolean, default ``True``) if ``False``, then\n ``l`` must be a ``list``, which is assigned to ``self._list``\n without copying.\n\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c == loads(dumps(c))\n True\n sage: c._list\n [1, 2, 3]\n sage: c._hash is None\n True\n\n For efficiency, you can specify ``copy=False`` if you know what\n you are doing::\n\n sage: from sage.combinat.combinat import CombinatorialObject\n sage: x = [3, 2, 1]\n sage: C = CombinatorialObject(x, copy=False)\n sage: C\n [3, 2, 1]\n sage: x[0] = 5\n sage: C\n [5, 2, 1]\n\n TESTS:\n\n Test indirectly that we copy the input (see :trac:`18184`)::\n\n sage: # needs sage.combinat\n sage: L = IntegerListsLex(element_class=Partition)\n sage: x = [3, 2, 1]\n sage: P = L(x)\n sage: x[0] = 5\n sage: list(P)\n [3, 2, 1]\n " if copy: self._list = list(l) else: self._list = l self._hash = None def __str__(self): "\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: str(c)\n '[1, 2, 3]'\n " return str(self._list) def _repr_(self): "\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c.__repr__()\n '[1, 2, 3]'\n " return repr(self._list) def __eq__(self, other): "\n Test equality of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c == [1,2,3]\n True\n sage: c == [2,3,4]\n False\n sage: c == d\n False\n sage: c == c\n True\n\n .. WARNING::\n\n :class:`CombinatorialObject` must come **before** :class:`Element`\n for this to work because :class:`Element` is ahead of\n :class:`CombinatorialObject` in the MRO (method resolution\n order)::\n\n sage: from sage.structure.element import Element\n sage: class Bar(Element, CombinatorialObject):\n ....: def __init__(self, l):\n ....: CombinatorialObject.__init__(self, l)\n sage: L = [Bar([4-i]) for i in range(4)]\n sage: sorted(L)\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'Bar' and 'Bar'\n " if isinstance(other, CombinatorialObject): return (self._list == other._list) else: return (self._list == other) def __lt__(self, other): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c < d\n True\n sage: c < [2,3,4]\n True\n sage: c < c\n False\n\n Check that :trac:`14065` is fixed::\n\n sage: from sage.structure.element import Element\n sage: class Foo(CombinatorialObject, Element): pass\n sage: L = [Foo([4-i]) for i in range(4)]; L\n [[4], [3], [2], [1]]\n sage: sorted(L)\n [[1], [2], [3], [4]]\n sage: f = Foo([4])\n sage: f is None\n False\n sage: f is not None\n True\n ' if isinstance(other, CombinatorialObject): return (self._list < other._list) else: return (self._list < other) def __le__(self, other): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c <= c\n True\n sage: c <= d\n True\n sage: c <= [1,2,3]\n True\n ' if isinstance(other, CombinatorialObject): return (self._list <= other._list) else: return (self._list <= other) def __gt__(self, other): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c > c\n False\n sage: c > d\n False\n sage: c > [1,2,3]\n False\n ' if isinstance(other, CombinatorialObject): return (self._list > other._list) else: return (self._list > other) def __ge__(self, other): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c >= c\n True\n sage: c >= d\n False\n sage: c >= [1,2,3]\n True\n ' if isinstance(other, CombinatorialObject): return (self._list >= other._list) else: return (self._list >= other) def __ne__(self, other): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: d = CombinatorialObject([2,3,4])\n sage: c != c\n False\n sage: c != d\n True\n sage: c != [1,2,3]\n False\n ' if isinstance(other, CombinatorialObject): return (self._list != other._list) else: return (self._list != other) def __add__(self, other): "\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c + [4]\n [1, 2, 3, 4]\n sage: type(_)\n <class 'list'>\n " return (self._list + other) def __hash__(self): '\n Compute the hash of ``self`` by computing the hash of the string\n representation of self._list. The hash is cached and stored in\n self._hash.\n\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c._hash is None\n True\n sage: hash(c) #random\n 1335416675971793195\n sage: c._hash #random\n 1335416675971793195\n ' if (self._hash is None): self._hash = hash(str(self._list)) return self._hash def __bool__(self) -> bool: '\n Return ``True`` if ``self`` is non-zero.\n\n We consider a list to be zero if it has length zero.\n\n TESTS::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: not c\n False\n sage: c = CombinatorialObject([])\n sage: not c\n True\n\n Check that :trac:`14065` is fixed::\n\n sage: from sage.structure.element import Element\n sage: class Foo(CombinatorialObject, Element): pass\n ...\n sage: f = Foo([4])\n sage: not f\n False\n sage: f = Foo([])\n sage: not f\n True\n\n .. WARNING::\n\n :class:`CombinatorialObject` must come **before** :class:`Element`\n for this to work because :class:`Element` is ahead of\n :class:`CombinatorialObject` in the MRO (method resolution\n order)::\n\n sage: from sage.structure.element import Element\n sage: class Bar(Element, CombinatorialObject):\n ....: def __init__(self, l):\n ....: CombinatorialObject.__init__(self, l)\n sage: b = Bar([4])\n sage: not b\n False\n\n ' return bool(self._list) def __len__(self) -> Integer: '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: len(c)\n 3\n sage: c.__len__()\n 3\n ' return len(self._list) def __getitem__(self, key): "\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c[0]\n 1\n sage: c[1:]\n [2, 3]\n sage: type(_)\n <class 'list'>\n " return self._list[key] def __iter__(self): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: list(iter(c))\n [1, 2, 3]\n ' return iter(self._list) def __contains__(self, item): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: 1 in c\n True\n sage: 5 in c\n False\n ' return (item in self._list) def index(self, key): '\n EXAMPLES::\n\n sage: c = CombinatorialObject([1,2,3])\n sage: c.index(1)\n 0\n sage: c.index(3)\n 2\n ' return self._list.index(key)
class CombinatorialElement(CombinatorialObject, Element, metaclass=InheritComparisonClasscallMetaclass): '\n ``CombinatorialElement`` is both a :class:`CombinatorialObject`\n and an :class:`Element`. So it represents a list which is an\n element of some parent.\n\n A ``CombinatorialElement`` subclass also automatically supports\n the ``__classcall__`` mechanism.\n\n .. WARNING::\n\n This class is slowly being deprecated. Use\n :class:`~sage.structure.list_clone.ClonableList` instead.\n\n INPUT:\n\n - ``parent`` -- the :class:`Parent` class for this element.\n\n - ``lst`` -- a list or any object that can be converted to a\n list by calling ``list()``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: from sage.combinat.combinat import CombinatorialElement\n sage: e = CombinatorialElement(Partitions(6), [3,2,1])\n sage: e == loads(dumps(e))\n True\n sage: parent(e)\n Partitions of the integer 6\n sage: list(e)\n [3, 2, 1]\n\n Check classcalls::\n\n sage: class Foo(CombinatorialElement): # needs sage.combinat\n ....: @staticmethod\n ....: def __classcall__(cls, x):\n ....: return x\n sage: Foo(17) # needs sage.combinat\n 17\n ' def __init__(self, parent, *args, **kwds): '\n Initialize this ``CombinatorialElement`` with a parent and a\n list.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import CombinatorialElement\n sage: e = CombinatorialElement(ZZ, list=(3,2,1))\n sage: e._list\n [3, 2, 1]\n sage: e.parent()\n Integer Ring\n\n TESTS::\n\n sage: CombinatorialElement(ZZ)\n Traceback (most recent call last):\n ...\n TypeError: ...__init__() takes exactly 2 arguments (1 given)\n sage: CombinatorialElement(ZZ, 1, 2)\n Traceback (most recent call last):\n ...\n TypeError: ...__init__() takes exactly 2 arguments (3 given)\n sage: CombinatorialElement(ZZ, 1, list=2)\n Traceback (most recent call last):\n ...\n TypeError: ...__init__() takes exactly 2 arguments (3 given)\n sage: CombinatorialElement(ZZ, a=1, b=2)\n Traceback (most recent call last):\n ...\n TypeError: ...__init__() takes exactly 2 arguments (3 given)\n ' if ((len(args) == 1) and (not kwds)): L = args[0] elif ((len(kwds) == 1) and (not args)): (L,) = kwds.values() else: raise TypeError('__init__() takes exactly 2 arguments ({} given)'.format(((1 + len(args)) + len(kwds)))) super().__init__(L) super(CombinatorialObject, self).__init__(parent)
class CombinatorialClass(Parent, metaclass=ClasscallMetaclass): "\n This class is deprecated, and will disappear as soon as all derived\n classes in Sage's library will have been fixed. Please derive\n directly from Parent and use the category :class:`EnumeratedSets`,\n :class:`FiniteEnumeratedSets`, or :class:`InfiniteEnumeratedSets`, as\n appropriate.\n\n For examples, see::\n\n sage: FiniteEnumeratedSets().example()\n An example of a finite enumerated set: {1,2,3}\n sage: InfiniteEnumeratedSets().example()\n An example of an infinite enumerated set: the non negative integers\n " def __init__(self, category=None): "\n TESTS::\n\n sage: C = sage.combinat.combinat.CombinatorialClass()\n sage: C.category()\n Category of enumerated sets\n sage: C.__class__\n <class 'sage.combinat.combinat.CombinatorialClass_with_category'>\n sage: isinstance(C, Parent)\n True\n sage: C = sage.combinat.combinat.CombinatorialClass(category = FiniteEnumeratedSets())\n sage: C.category()\n Category of finite enumerated sets\n " Parent.__init__(self, category=EnumeratedSets().or_subcategory(category)) def is_finite(self) -> bool: '\n Return whether ``self`` is finite or not.\n\n EXAMPLES::\n\n sage: Partitions(5).is_finite() # needs sage.combinat\n True\n sage: Permutations().is_finite()\n False\n ' return (self.cardinality() != infinity) def __getitem__(self, i): '\n Return the combinatorial object of rank i.\n\n EXAMPLES::\n\n sage: class C(CombinatorialClass):\n ....: def __iter__(self):\n ....: return iter([1,2,3])\n sage: c = C()\n sage: c[0]\n 1\n sage: c[2]\n 3\n sage: c[4]\n Traceback (most recent call last):\n ...\n ValueError: the value must be between 0 and 2 inclusive\n ' return self.unrank(i) def __str__(self) -> str: "\n Return a string representation of self.\n\n EXAMPLES::\n\n sage: str(Partitions(5)) # needs sage.combinat\n 'Partitions of the integer 5'\n " return repr(self) def _repr_(self) -> str: "\n EXAMPLES::\n\n sage: repr(Partitions(5)) # indirect doctest # needs sage.combinat\n 'Partitions of the integer 5'\n " if (hasattr(self, '_name') and self._name): return self._name else: return 'Combinatorial Class -- REDEFINE ME!' def __contains__(self, x) -> bool: '\n Test whether or not the combinatorial class contains the object x.\n This raises a NotImplementedError as a default since _all_\n subclasses of CombinatorialClass should override this.\n\n Note that we could replace this with a default implementation that\n just iterates through the elements of the combinatorial class and\n checks for equality. However, since we use __contains__ for\n type checking, this operation should be cheap and should be\n implemented manually for each combinatorial class.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: x in C # needs sage.symbolic\n Traceback (most recent call last):\n ...\n NotImplementedError\n ' raise NotImplementedError def __eq__(self, other): "\n Compare two different combinatorial classes.\n\n For now, the comparison is done just on their repr's.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: p5 = Partitions(5)\n sage: p6 = Partitions(6)\n sage: repr(p5) == repr(p6)\n False\n sage: p5 == p6\n False\n " return (repr(self) == repr(other)) def __ne__(self, other): '\n Test unequality of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: p5 = Partitions(5) # needs sage.combinat\n sage: p6 = Partitions(6) # needs sage.combinat\n sage: p5 != p6 # needs sage.combinat\n True\n ' return (not (self == other)) def __hash__(self): '\n Create a hash value. This is based on the string representation.\n\n Note that in Python 3 objects that define __eq__ do not inherit their __hash__\n function. Without an explicit __hash__ they are no longer hashable.\n\n TESTS::\n\n sage: C = CombinatorialClass()\n sage: hash(C) == hash(repr(C))\n True\n ' return hash(repr(self)) def __cardinality_from_iterator(self) -> (Integer | infinity): '\n Default implementation of cardinality which just goes through the iterator\n of the combinatorial class to count the number of objects.\n\n EXAMPLES::\n\n sage: class C(CombinatorialClass):\n ....: def __iter__(self):\n ....: return iter([1,2,3])\n sage: C().cardinality() #indirect doctest\n 3\n ' c = Integer(0) one = Integer(1) for _ in self: c += one return c cardinality = __cardinality_from_iterator def __call__(self, x): "\n Return x as an element of the combinatorial class's object class.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: p5 = Partitions(5)\n sage: a = [2,2,1]\n sage: type(a)\n <class 'list'>\n sage: a = p5(a)\n sage: type(a)\n <class 'sage.combinat.partition.Partitions_n_with_category.element_class'>\n sage: p5([2,1])\n Traceback (most recent call last):\n ...\n ValueError: [2, 1] is not an element of Partitions of the integer 5\n " if (x in self): return self._element_constructor_(x) else: raise ValueError(('%s not in %s' % (x, self))) Element = CombinatorialObject @lazy_attribute def element_class(self): "\n This function is a temporary helper so that a CombinatorialClass\n behaves as a parent for creating elements. This will disappear when\n combinatorial classes will be turned into actual parents (in the\n category EnumeratedSets).\n\n TESTS::\n\n sage: P5 = Partitions(5) # needs sage.combinat\n sage: P5.element_class # needs sage.combinat\n <class 'sage.combinat.partition.Partitions_n_with_category.element_class'>\n " return self.Element def _element_constructor_(self, x): "\n This function is a temporary helper so that a CombinatorialClass\n behaves as a parent for creating elements. This will disappear when\n combinatorial classes will be turned into actual parents (in the\n category EnumeratedSets).\n\n TESTS::\n\n sage: P5 = Partitions(5) # needs sage.combinat\n sage: p = P5([3,2]) # indirect doctest # needs sage.combinat\n sage: type(p) # needs sage.combinat\n <class 'sage.combinat.partition.Partitions_n_with_category.element_class'>\n " return self.element_class(x) def __list_from_iterator(self): '\n The default implementation of list which builds the list from the\n iterator.\n\n EXAMPLES::\n\n sage: class C(CombinatorialClass):\n ....: def __iter__(self):\n ....: return iter([1,2,3])\n sage: C().list() #indirect doctest\n [1, 2, 3]\n ' return [x for x in self] list = __list_from_iterator Element = CombinatorialObject def __iterator_from_next(self) -> Iterator: '\n An iterator to use when the .first() and .next(x) methods are provided.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.first = lambda: 0\n sage: C.next = lambda c: c+1\n sage: it = iter(C) # indirect doctest\n sage: [next(it) for _ in range(4)]\n [0, 1, 2, 3]\n ' f = self.first() (yield f) while True: try: f = self.next(f) except (TypeError, ValueError): break if ((f is None) or (f is False)): break else: (yield f) def __iterator_from_previous(self): '\n An iterator to use when .last() and .previous() are provided. Note\n that this requires the combinatorial class to be finite. It is not\n recommended to implement combinatorial classes using last and\n previous.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.last = lambda: 4\n sage: def prev(c):\n ....: if c <= 1:\n ....: return None\n ....: else:\n ....: return c-1\n sage: C.previous = prev\n sage: it = iter(C) # indirect doctest\n sage: [next(it) for _ in range(4)]\n [1, 2, 3, 4]\n ' l = self.last() li = [l] while True: try: l = self.previous(l) except (TypeError, ValueError): break if (l is None): break else: li.append(l) return reversed(li) def __iterator_from_unrank(self) -> Iterator: '\n An iterator to use when .unrank() is provided.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: l = [1,2,3]\n sage: C.unrank = lambda c: l[c]\n sage: list(C) # indirect doctest\n [1, 2, 3]\n ' r = 0 u = self.unrank(r) (yield u) while True: r += 1 try: u = self.unrank(r) except (TypeError, ValueError, IndexError): break if (u is None): break else: (yield u) def __iterator_from_list(self) -> Iterator: '\n An iterator to use when .list() is provided()\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1, 2, 3]\n sage: list(C) # indirect doctest\n [1, 2, 3]\n ' (yield from self.list()) def __iter__(self): '\n Allows the combinatorial class to be treated as an iterator. Default\n implementation.\n\n EXAMPLES::\n\n sage: p5 = Partitions(5) # needs sage.combinat\n sage: [i for i in p5] # needs sage.combinat\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: C = CombinatorialClass()\n sage: iter(C)\n Traceback (most recent call last):\n ...\n NotImplementedError: iterator called but not implemented\n ' if ((self.first != self.__first_from_iterator) and (self.next != self.__next_from_iterator)): return self.__iterator_from_next() elif ((self.last != self.__last_from_iterator) and (self.previous != self.__previous_from_iterator)): return self.__iterator_from_previous() elif (self.unrank != self.__unrank_from_iterator): return self.__iterator_from_unrank() elif (self.list != self.__list_from_iterator): return self.__iterator_from_list() else: raise NotImplementedError('iterator called but not implemented') def __unrank_from_iterator(self, r): '\n Default implementation of unrank which goes through the iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.unrank(1) # indirect doctest\n 2\n ' counter = 0 for u in self: if (counter == r): return u counter += 1 raise ValueError(('the value must be between %s and %s inclusive' % (0, (counter - 1)))) unrank = __unrank_from_iterator def __random_element_from_unrank(self): '\n Default implementation of random which uses unrank.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.random_element() # random # indirect doctest\n 1\n ' c = self.cardinality() r = randint(0, (c - 1)) return self.unrank(r) random_element = __random_element_from_unrank def __rank_from_iterator(self, obj): '\n Default implementation of rank which uses iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.rank(3) # indirect doctest\n 2\n ' r = 0 for i in self: if (i == obj): return r r += 1 raise ValueError rank = __rank_from_iterator def __first_from_iterator(self): '\n Default implementation for first which uses iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.first() # indirect doctest\n 1\n ' for i in self: return i first = __first_from_iterator def __last_from_iterator(self): '\n Default implementation for first which uses iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.last() # indirect doctest\n 3\n ' for i in self: pass return i last = __last_from_iterator def __next_from_iterator(self, obj): '\n Default implementation for next which uses iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.next(2) # indirect doctest\n 3\n ' found = False for i in self: if found: return i if (i == obj): found = True return None next = __next_from_iterator def __previous_from_iterator(self, obj): '\n Default implementation for next which uses iterator.\n\n EXAMPLES::\n\n sage: C = CombinatorialClass()\n sage: C.list = lambda: [1,2,3]\n sage: C.previous(2) # indirect doctest\n 1\n ' prev = None for i in self: if (i == obj): break prev = i return prev previous = __previous_from_iterator def filter(self, f, name=None): '\n Return the combinatorial subclass of f which consists of the\n elements x of ``self`` such that f(x) is ``True``.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n sage: P.list() # needs sage.combinat\n [[3, 2, 1]]\n ' return FilteredCombinatorialClass(self, f, name=name) def union(self, right_cc, name=None): '\n Return the combinatorial class representing the union of ``self`` and\n ``right_cc``.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(2).union(Permutations_CC(1))\n sage: P.list()\n [[1, 2], [2, 1], [1]]\n ' if (not isinstance(right_cc, CombinatorialClass)): raise TypeError('right_cc must be a CombinatorialClass') return UnionCombinatorialClass(self, right_cc, name=name) def map(self, f, name=None, *, is_injective=True): "\n Return the image `\\{f(x) | x \\in \\text{self}\\}` of this combinatorial\n class by `f`, as a combinatorial class.\n\n INPUT:\n\n - ``is_injective`` -- boolean (default: ``True``) whether to assume\n that ``f`` is injective.\n\n EXAMPLES::\n\n sage: R = Permutations(3).map(attrcall('reduced_word')); R\n Image of Standard permutations of 3 by\n The map *.reduced_word() from Standard permutations of 3\n sage: R.cardinality()\n 6\n sage: R.list()\n [[], [2], [1], [1, 2], [2, 1], [2, 1, 2]]\n sage: [ r for r in R]\n [[], [2], [1], [1, 2], [2, 1], [2, 1, 2]]\n\n If the function is not injective, then there may be repeated elements::\n\n sage: P = Partitions(4) # needs sage.combinat\n sage: P.list() # needs sage.combinat\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n sage: P.map(len).list() # needs sage.combinat\n [1, 2, 2, 3, 4]\n\n Use ``is_injective=False`` to get a correct result in this case::\n\n sage: P.map(len, is_injective=False).list() # needs sage.combinat\n [1, 2, 3, 4]\n\n TESTS::\n\n sage: R = Permutations(3).map(attrcall('reduced_word'))\n sage: R == loads(dumps(R))\n True\n " return MapCombinatorialClass(self, f, name, is_injective=is_injective)
class FilteredCombinatorialClass(CombinatorialClass): def __init__(self, combinatorial_class, f, name=None): '\n A filtered combinatorial class F is a subset of another\n combinatorial class C specified by a function f that takes in an\n element c of C and returns True if and only if c is in F.\n\n TESTS::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n Filtered subclass of Standard permutations of 3\n ' self.f = f self.combinatorial_class = combinatorial_class self._name = name def __repr__(self): "\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n sage: P.__repr__()\n 'Filtered subclass of Standard permutations of 3'\n sage: P._name = 'Permutations avoiding [1, 2]'\n sage: P.__repr__()\n 'Permutations avoiding [1, 2]'\n " if self._name: return self._name else: return ('Filtered subclass of ' + repr(self.combinatorial_class)) def __contains__(self, x) -> bool: "\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n sage: 'cat' in P\n False\n sage: [4,3,2,1] in P\n False\n sage: Permutation([1,2,3]) in P # needs sage.combinat\n False\n sage: Permutation([3,2,1]) in P # needs sage.combinat\n True\n " return ((x in self.combinatorial_class) and self.f(x)) def cardinality(self) -> Integer: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n sage: P.cardinality() # needs sage.combinat\n 1\n ' c = 0 for _ in self: c += 1 return c def __iter__(self) -> Iterator: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))\n sage: list(P) # needs sage.combinat\n [[3, 2, 1]]\n ' for x in self.combinatorial_class: if self.f(x): (yield x)
class UnionCombinatorialClass(CombinatorialClass): def __init__(self, left_cc, right_cc, name=None): '\n A UnionCombinatorialClass is a union of two other combinatorial\n classes.\n\n TESTS::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P == loads(dumps(P))\n True\n ' self.left_cc = left_cc self.right_cc = right_cc self._name = name def __repr__(self) -> str: '\n TESTS::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: print(repr(Permutations_CC(3).union(Permutations_CC(2))))\n Union combinatorial class of\n Standard permutations of 3\n and\n Standard permutations of 2\n ' if self._name: return self._name else: return ('Union combinatorial class of \n %s\nand\n %s' % (self.left_cc, self.right_cc)) def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: [1,2] in P\n True\n sage: [3,2,1] in P\n True\n sage: [1,2,3,4] in P\n False\n ' return ((x in self.left_cc) or (x in self.right_cc)) def cardinality(self) -> (Integer | infinity): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.cardinality()\n 8\n ' return (self.left_cc.cardinality() + self.right_cc.cardinality()) def list(self): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.list()\n [[1, 2, 3],\n [1, 3, 2],\n [2, 1, 3],\n [2, 3, 1],\n [3, 1, 2],\n [3, 2, 1],\n [1, 2],\n [2, 1]]\n ' return (self.left_cc.list() + self.right_cc.list()) def __iter__(self) -> Iterator: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: list(P)\n [[1, 2, 3],\n [1, 3, 2],\n [2, 1, 3],\n [2, 3, 1],\n [3, 1, 2],\n [3, 2, 1],\n [1, 2],\n [2, 1]]\n ' for x in self.left_cc: (yield x) for x in self.right_cc: (yield x) def first(self): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.first()\n [1, 2, 3]\n ' return self.left_cc.first() def last(self): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.last()\n [2, 1]\n ' return self.right_cc.last() def rank(self, x): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.rank(Permutation([2,1]))\n 7\n sage: P.rank(Permutation([1,2,3]))\n 0\n ' try: return self.left_cc.rank(x) except (TypeError, ValueError): return (self.left_cc.cardinality() + self.right_cc.rank(x)) def unrank(self, x): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3).union(Permutations_CC(2))\n sage: P.unrank(7)\n [2, 1]\n sage: P.unrank(0)\n [1, 2, 3]\n ' try: return self.left_cc.unrank(x) except (TypeError, ValueError): return self.right_cc.unrank((x - self.left_cc.cardinality()))
class Permutations_CC(CombinatorialClass): '\n A testing class for :class:`CombinatorialClass` since :class:`Permutations`\n no longer inherits from :class:`CombinatorialClass` in :trac:`14772`.\n ' def __init__(self, n): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(4)\n sage: loads(dumps(P)) == P\n True\n ' from sage.combinat.permutation import StandardPermutations_n self._permutations = StandardPermutations_n(n) def __repr__(self) -> str: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: Permutations_CC(3)\n Standard permutations of 3\n ' return repr(self._permutations) def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3)\n sage: [1, 3, 2] in P\n True\n ' return (x in self._permutations) def __iter__(self): '\n EXAMPLES::\n\n sage: from sage.combinat.combinat import Permutations_CC\n sage: P = Permutations_CC(3)\n sage: P.list()\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n ' return iter(self._permutations)
class MapCombinatorialClass(ImageSubobject, CombinatorialClass): "\n The image of a combinatorial class through a function.\n\n INPUT:\n\n - ``is_injective`` -- boolean (default: ``True``) whether to assume\n that ``f`` is injective.\n\n See :meth:`CombinatorialClass.map` for examples\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: R = SymmetricGroup(10).map(attrcall('reduced_word'))\n sage: R.an_element()\n [9, 8, 7, 6, 5, 4, 3, 2]\n sage: R.cardinality()\n 3628800\n sage: i = iter(R)\n sage: next(i), next(i), next(i)\n ([], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1])\n " def __init__(self, cc, f, name=None, *, is_injective=True): "\n TESTS::\n\n sage: Partitions(3).map(attrcall('conjugate')) # needs sage.combinat\n Image of Partitions of the integer 3 by The map *.conjugate()\n from Partitions of the integer 3\n " ImageSubobject.__init__(self, f, cc, is_injective=is_injective) self.cc = cc self.f = f if name: self.rename(name)
class InfiniteAbstractCombinatorialClass(CombinatorialClass): '\n This is an internal class that should not be used directly. A class which\n inherits from InfiniteAbstractCombinatorialClass inherits the standard\n methods list and count.\n\n If self._infinite_cclass_slice exists then self.__iter__ returns an\n iterator for self, otherwise raise NotImplementedError. The method\n self._infinite_cclass_slice is supposed to accept any integer as an\n argument and return something which is iterable.\n ' def cardinality(self) -> (Integer | infinity): '\n Count the elements of the combinatorial class.\n\n EXAMPLES::\n\n sage: R = InfiniteAbstractCombinatorialClass()\n doctest:warning...\n DeprecationWarning: this class is deprecated, do not use\n See https://github.com/sagemath/sage/issues/31545 for details.\n\n sage: R.cardinality()\n +Infinity\n ' return infinity def list(self): '\n Return an error since ``self`` is an infinite combinatorial class.\n\n EXAMPLES::\n\n sage: R = InfiniteAbstractCombinatorialClass()\n sage: R.list()\n Traceback (most recent call last):\n ...\n NotImplementedError: infinite list\n ' raise NotImplementedError('infinite list') def __iter__(self) -> Iterator: '\n Return an iterator for the infinite combinatorial class ``self`` if\n possible or raise a NotImplementedError.\n\n EXAMPLES::\n\n sage: R = InfiniteAbstractCombinatorialClass()\n sage: next(iter(R))\n Traceback (most recent call last):\n ...\n NotImplementedError\n\n sage: c = iter(Compositions()) # indirect doctest\n sage: next(c), next(c), next(c), next(c), next(c), next(c)\n ([], [1], [1, 1], [2], [1, 1, 1], [1, 2])\n sage: next(c), next(c), next(c), next(c), next(c), next(c)\n ([2, 1], [3], [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3])\n ' try: finite = self._infinite_cclass_slice except AttributeError: raise NotImplementedError i = 0 while True: (yield from finite(i)) i += 1
def tuples(S, k, algorithm='itertools'): '\n Return a list of all `k`-tuples of elements of a given set ``S``.\n\n This function accepts the set ``S`` in the form of any iterable\n (list, tuple or iterator), and returns a list of `k`-tuples.\n If ``S`` contains duplicate entries, then you should expect the\n method to return tuples multiple times!\n\n Recall that `k`-tuples are ordered (in the sense that two `k`-tuples\n differing in the order of their entries count as different) and\n can have repeated entries (even if ``S`` is a list with no\n repetition).\n\n INPUT:\n\n - ``S`` -- the base set\n - ``k`` -- the length of the tuples\n - ``algorithm`` -- can be one of the following:\n\n * ``\'itertools\'`` - (default) use python\'s itertools\n * ``\'native\'`` - use a native Sage implementation\n\n .. NOTE::\n\n The ordering of the list of tuples depends on the algorithm.\n\n EXAMPLES::\n\n sage: S = [1,2]\n sage: tuples(S,3)\n [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n sage: mset = ["s","t","e","i","n"]\n sage: tuples(mset, 2)\n [(\'s\', \'s\'), (\'s\', \'t\'), (\'s\', \'e\'), (\'s\', \'i\'), (\'s\', \'n\'),\n (\'t\', \'s\'), (\'t\', \'t\'), (\'t\', \'e\'), (\'t\', \'i\'), (\'t\', \'n\'),\n (\'e\', \'s\'), (\'e\', \'t\'), (\'e\', \'e\'), (\'e\', \'i\'), (\'e\', \'n\'),\n (\'i\', \'s\'), (\'i\', \'t\'), (\'i\', \'e\'), (\'i\', \'i\'), (\'i\', \'n\'),\n (\'n\', \'s\'), (\'n\', \'t\'), (\'n\', \'e\'), (\'n\', \'i\'), (\'n\', \'n\')]\n\n ::\n\n sage: K.<a> = GF(4, \'a\') # needs sage.rings.finite_rings\n sage: mset = [x for x in K if x != 0] # needs sage.rings.finite_rings\n sage: tuples(mset, 2) # needs sage.rings.finite_rings\n [(a, a), (a, a + 1), (a, 1), (a + 1, a), (a + 1, a + 1),\n (a + 1, 1), (1, a), (1, a + 1), (1, 1)]\n\n We check that the implementations agree (up to ordering)::\n\n sage: tuples(S, 3, \'native\')\n [(1, 1, 1), (2, 1, 1), (1, 2, 1), (2, 2, 1),\n (1, 1, 2), (2, 1, 2), (1, 2, 2), (2, 2, 2)]\n\n Lastly we check on a multiset::\n\n sage: S = [1,1,2]\n sage: sorted(tuples(S, 3)) == sorted(tuples(S, 3, \'native\'))\n True\n\n AUTHORS:\n\n - Jon Hanke (2006-08)\n ' if (algorithm == 'itertools'): import itertools return list(itertools.product(S, repeat=k)) if (algorithm == 'native'): return _tuples_native(S, k) raise ValueError('invalid algorithm')
def _tuples_native(S, k): '\n Return a list of all `k`-tuples of elements of a given set ``S``.\n\n This is a helper method used in :meth:`tuples`. It returns the\n same as ``tuples(S, k, algorithm="native")``.\n\n EXAMPLES::\n\n sage: S = [1,2,2]\n sage: from sage.combinat.combinat import _tuples_native\n sage: _tuples_native(S,2)\n [(1, 1), (2, 1), (2, 1), (1, 2), (2, 2), (2, 2),\n (1, 2), (2, 2), (2, 2)]\n ' if (k <= 0): return [()] if (k == 1): return [(x,) for x in S] ans = [] for s in S: for x in _tuples_native(S, (k - 1)): y = list(x) y.append(s) ans.append(tuple(y)) return ans
def number_of_tuples(S, k, algorithm='naive') -> Integer: '\n Return the size of ``tuples(S, k)`` when `S` is a set. More\n generally, return the size of ``tuples(set(S), k)``. (So,\n unlike :meth:`tuples`, this method removes redundant entries from\n `S`.)\n\n INPUT:\n\n - ``S`` -- the base set\n - ``k`` -- the length of the tuples\n - ``algorithm`` -- can be one of the following:\n\n * ``\'naive\'`` - (default) use the naive counting `|S|^k`\n * ``\'gap\'`` - wraps GAP\'s ``NrTuples``\n\n .. WARNING::\n\n When using ``algorithm=\'gap\'``, ``S`` must be a list of objects\n that have string representations that can be interpreted by the GAP\n interpreter. If ``S`` consists of at all complicated Sage\n objects, this function might *not* do what you expect.\n\n EXAMPLES::\n\n sage: S = [1,2,3,4,5]\n sage: number_of_tuples(S,2)\n 25\n sage: number_of_tuples(S,2, algorithm="gap") # needs sage.libs.gap\n 25\n sage: S = [1,1,2,3,4,5]\n sage: number_of_tuples(S,2)\n 25\n sage: number_of_tuples(S,2, algorithm="gap") # needs sage.libs.gap\n 25\n sage: number_of_tuples(S,0)\n 1\n sage: number_of_tuples(S,0, algorithm="gap") # needs sage.libs.gap\n 1\n ' if (algorithm == 'naive'): return (ZZ(len(set(S))) ** k) if (algorithm == 'gap'): k = ZZ(k) from sage.libs.gap.libgap import libgap S = libgap.eval(str(S)) return libgap.NrTuples(S, k).sage() raise ValueError('invalid algorithm')
def unordered_tuples(S, k, algorithm='itertools'): '\n Return a list of all unordered tuples of length ``k`` of the set ``S``.\n\n An unordered tuple of length `k` of set `S` is a unordered selection\n with repetitions of `S` and is represented by a sorted list of length\n `k` containing elements from `S`.\n\n Unlike :meth:`tuples`, the result of this method does not depend on\n how often an element appears in `S`; only the *set* `S` is being\n used. For example, ``unordered_tuples([1, 1, 1], 2)`` will return\n ``[(1, 1)]``. If you want it to return\n ``[(1, 1), (1, 1), (1, 1)]``, use Python\'s\n ``itertools.combinations_with_replacement`` instead.\n\n INPUT:\n\n - ``S`` -- the base set\n - ``k`` -- the length of the tuples\n - ``algorithm`` -- can be one of the following:\n\n * ``\'itertools\'`` - (default) use python\'s itertools\n * ``\'gap\'`` - wraps GAP\'s ``UnorderedTuples``\n\n .. WARNING::\n\n When using ``algorithm=\'gap\'``, ``S`` must be a list of objects\n that have string representations that can be interpreted by the GAP\n interpreter. If ``S`` consists of at all complicated Sage\n objects, this function might *not* do what you expect.\n\n EXAMPLES::\n\n sage: S = [1,2]\n sage: unordered_tuples(S, 3)\n [(1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]\n\n We check that this agrees with GAP::\n\n sage: unordered_tuples(S, 3, algorithm=\'gap\') # needs sage.libs.gap\n [(1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]\n\n We check the result on strings::\n\n sage: S = ["a","b","c"]\n sage: unordered_tuples(S, 2)\n [(\'a\', \'a\'), (\'a\', \'b\'), (\'a\', \'c\'), (\'b\', \'b\'), (\'b\', \'c\'), (\'c\', \'c\')]\n sage: unordered_tuples(S, 2, algorithm=\'gap\') # needs sage.libs.gap\n [(\'a\', \'a\'), (\'a\', \'b\'), (\'a\', \'c\'), (\'b\', \'b\'), (\'b\', \'c\'), (\'c\', \'c\')]\n\n Lastly we check on a multiset::\n\n sage: S = [1,1,2]\n sage: unordered_tuples(S, 3) == unordered_tuples(S, 3, \'gap\') # needs sage.libs.gap\n True\n sage: unordered_tuples(S, 3)\n [(1, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 2)]\n ' if (algorithm == 'itertools'): import itertools return list(itertools.combinations_with_replacement(sorted(set(S)), k)) if (algorithm == 'gap'): k = ZZ(k) from sage.libs.gap.libgap import libgap S = libgap.eval(str(S)) return [tuple(x) for x in libgap.UnorderedTuples(S, k).sage()] raise ValueError('invalid algorithm')
def number_of_unordered_tuples(S, k, algorithm='naive') -> Integer: '\n Return the size of ``unordered_tuples(S, k)`` when `S` is a set.\n\n INPUT:\n\n - ``S`` -- the base set\n - ``k`` -- the length of the tuples\n - ``algorithm`` -- can be one of the following:\n\n * ``\'naive\'`` - (default) use the naive counting `\\binom{|S|+k-1}{k}`\n * ``\'gap\'`` - wraps GAP\'s ``NrUnorderedTuples``\n\n .. WARNING::\n\n When using ``algorithm=\'gap\'``, ``S`` must be a list of objects\n that have string representations that can be interpreted by the GAP\n interpreter. If ``S`` consists of at all complicated Sage\n objects, this function might *not* do what you expect.\n\n EXAMPLES::\n\n sage: S = [1,2,3,4,5]\n sage: number_of_unordered_tuples(S,2)\n 15\n sage: number_of_unordered_tuples(S,2, algorithm="gap") # needs sage.libs.gap\n 15\n sage: S = [1,1,2,3,4,5]\n sage: number_of_unordered_tuples(S,2)\n 15\n sage: number_of_unordered_tuples(S,2, algorithm="gap") # needs sage.libs.gap\n 15\n sage: number_of_unordered_tuples(S,0)\n 1\n sage: number_of_unordered_tuples(S,0, algorithm="gap") # needs sage.libs.gap\n 1\n ' if (algorithm == 'naive'): return ZZ(((len(set(S)) + k) - 1)).binomial(k) if (algorithm == 'gap'): k = ZZ(k) from sage.libs.gap.libgap import libgap S = libgap.eval(str(S)) return libgap.NrUnorderedTuples(S, k).sage() raise ValueError('invalid algorithm')
def unshuffle_iterator(a, one=1) -> Iterator: '\n Iterate over the unshuffles of a list (or tuple) ``a``, also\n yielding the signs of the respective permutations.\n\n If `n` and `k` are integers satisfying `0 \\leq k \\leq n`, then\n a `(k, n-k)`-*unshuffle* means a permutation `\\pi \\in S_n` such\n that `\\pi(1) < \\pi(2) < \\cdots < \\pi(k)` and\n `\\pi(k+1) < \\pi(k+2) < \\cdots < \\pi(n)`. This method provides,\n for a list `a = (a_1, a_2, \\ldots, a_n)` of length `n`, an iterator\n yielding all pairs:\n\n .. MATH::\n\n \\Bigl( \\bigl( (a_{\\pi(1)}, a_{\\pi(2)}, \\ldots, a_{\\pi(k)}),\n (a_{\\pi(k+1)}, a_{\\pi(k+2)}, \\ldots, a_{\\pi(n)}) \\bigl),\n (-1)^{\\pi} \\Bigr)\n\n for all `k \\in \\{0, 1, \\ldots, n\\}` and all `(k, n-k)`-unshuffles\n `\\pi`. The optional variable ``one`` can be set to a different\n value which results in the `(-1)^{\\pi}` component being multiplied\n by said value.\n\n The iterator does not yield these in order of increasing `k`.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinat import unshuffle_iterator\n sage: list(unshuffle_iterator([1, 3, 4]))\n [(((), (1, 3, 4)), 1), (((1,), (3, 4)), 1), (((3,), (1, 4)), -1),\n (((1, 3), (4,)), 1), (((4,), (1, 3)), 1), (((1, 4), (3,)), -1),\n (((3, 4), (1,)), 1), (((1, 3, 4), ()), 1)]\n sage: list(unshuffle_iterator([3, 1]))\n [(((), (3, 1)), 1), (((3,), (1,)), 1), (((1,), (3,)), -1),\n (((3, 1), ()), 1)]\n sage: list(unshuffle_iterator([8]))\n [(((), (8,)), 1), (((8,), ()), 1)]\n sage: list(unshuffle_iterator([]))\n [(((), ()), 1)]\n sage: list(unshuffle_iterator([3, 1], 3/2))\n [(((), (3, 1)), 3/2), (((3,), (1,)), 3/2), (((1,), (3,)), -3/2),\n (((3, 1), ()), 3/2)]\n ' from sage.combinat.subset import powerset n = len(a) for I in powerset(range(n)): sorted_I = tuple(sorted(I)) nonI = list(range(n)) for j in reversed(sorted_I): nonI.pop(j) sorted_nonI = tuple(nonI) sign = True for i in sorted_I: if (i % 2): sign = (not sign) if ((len(sorted_I) % 4) > 1): sign = (not sign) (yield ((tuple([a[i] for i in sorted_I]), tuple([a[i] for i in sorted_nonI])), (one if sign else (- one))))
def bell_polynomial(n: Integer, k: Integer): '\n Return the Bell Polynomial\n\n .. MATH::\n\n B_{n,k}(x_0, x_1, \\ldots, x_{n-k}) =\n \\sum_{\\sum{j_i}=k, \\sum{(i+1) j_i}=n}\n \\frac{n!}{j_0!j_1!\\cdots j_{n-k}!}\n \\left(\\frac{x_0}{(0+1)!}\\right)^{j_0}\n \\left(\\frac{x_1}{(1+1)!}\\right)^{j_1} \\cdots\n \\left(\\frac{x_{n-k}}{(n-k+1)!}\\right)^{j_{n-k}}.\n\n INPUT:\n\n - ``n`` -- integer\n\n - ``k`` -- integer\n\n OUTPUT:\n\n - a polynomial in `n-k+1` variables over `\\ZZ`\n\n EXAMPLES::\n\n sage: bell_polynomial(6,2) # needs sage.combinat\n 10*x2^2 + 15*x1*x3 + 6*x0*x4\n sage: bell_polynomial(6,3) # needs sage.combinat\n 15*x1^3 + 60*x0*x1*x2 + 15*x0^2*x3\n\n TESTS:\n\n Check that :trac:`18338` is fixed::\n\n sage: bell_polynomial(0,0).parent() # needs sage.combinat\n Multivariate Polynomial Ring in x over Integer Ring\n\n sage: for n in (0..4): # needs sage.combinat\n ....: print([bell_polynomial(n,k).coefficients() for k in (0..n)])\n [[1]]\n [[], [1]]\n [[], [1], [1]]\n [[], [1], [3], [1]]\n [[], [1], [3, 4], [6], [1]]\n\n\n REFERENCES:\n\n - [Bel1927]_\n\n AUTHORS:\n\n - Blair Sutton (2009-01-26)\n - Thierry Monteil (2015-09-29): the result must always be a polynomial.\n ' from sage.combinat.partition import Partitions R = PolynomialRing(ZZ, 'x', ((n - k) + 1)) vars = R.gens() result = R.zero() for p in Partitions(n, length=k): factorial_product = 1 power_factorial_product = 1 for (part, count) in p.to_exp_dict().items(): factorial_product *= factorial(count) power_factorial_product *= (factorial(part) ** count) coefficient = (factorial(n) // (factorial_product * power_factorial_product)) result += (coefficient * prod([vars[(i - 1)] for i in p])) return result
def fibonacci_sequence(start, stop=None, algorithm=None) -> Iterator: '\n Return an iterator over the Fibonacci sequence, for all fibonacci\n numbers `f_n` from ``n = start`` up to (but\n not including) ``n = stop``\n\n INPUT:\n\n - ``start`` -- starting value\n\n - ``stop`` -- stopping value\n\n - ``algorithm`` -- (default: ``None``) passed on to\n fibonacci function (or not passed on if None, i.e., use the\n default)\n\n EXAMPLES::\n\n sage: fibs = [i for i in fibonacci_sequence(10, 20)]; fibs # needs sage.libs.pari\n [55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]\n\n ::\n\n sage: sum([i for i in fibonacci_sequence(100, 110)]) # needs sage.libs.pari\n 69919376923075308730013\n\n .. SEEALSO::\n\n :func:`fibonacci_xrange`\n\n AUTHORS:\n\n - Bobby Moretti\n ' if (stop is None): stop = ZZ(start) start = ZZ(0) else: start = ZZ(start) stop = ZZ(stop) if algorithm: for n in range(start, stop): (yield fibonacci(n, algorithm=algorithm)) else: for n in range(start, stop): (yield fibonacci(n))
def fibonacci_xrange(start, stop=None, algorithm='pari') -> Iterator: '\n Return an iterator over all of the Fibonacci numbers in the given\n range, including ``f_n = start`` up to, but not\n including, ``f_n = stop``.\n\n EXAMPLES::\n\n sage: fibs_in_some_range = [i for i in fibonacci_xrange(10^7, 10^8)] # needs sage.libs.pari\n sage: len(fibs_in_some_range) # needs sage.libs.pari\n 4\n sage: fibs_in_some_range # needs sage.libs.pari\n [14930352, 24157817, 39088169, 63245986]\n\n ::\n\n sage: fibs = [i for i in fibonacci_xrange(10, 100)]; fibs # needs sage.libs.pari\n [13, 21, 34, 55, 89]\n\n ::\n\n sage: list(fibonacci_xrange(13, 34)) # needs sage.libs.pari\n [13, 21]\n\n A solution to the second Project Euler problem::\n\n sage: sum([i for i in fibonacci_xrange(10^6) if is_even(i)]) # needs sage.libs.pari\n 1089154\n\n .. SEEALSO::\n\n :func:`fibonacci_sequence`\n\n AUTHORS:\n\n - Bobby Moretti\n ' if (stop is None): stop = ZZ(start) start = ZZ(0) else: start = ZZ(start) stop = ZZ(stop) fn = 0 n = 0 while (fn < start): n += 1 fn = fibonacci(n) while True: fn = fibonacci(n) n += 1 if (fn < stop): (yield fn) else: return
def bernoulli_polynomial(x, n: Integer): "\n Return the ``n``-th Bernoulli polynomial evaluated at ``x``.\n\n The generating function for the Bernoulli polynomials is\n\n .. MATH::\n\n \\frac{t e^{xt}}{e^t-1}= \\sum_{n=0}^\\infty B_n(x) \\frac{t^n}{n!},\n\n and they are given directly by\n\n .. MATH::\n\n B_n(x) = \\sum_{i=0}^n \\binom{n}{i}B_{n-i}x^i.\n\n One has `B_n(x) = - n\\zeta(1 - n,x)`, where\n `\\zeta(s,x)` is the Hurwitz zeta function. Thus, in a\n certain sense, the Hurwitz zeta function generalizes the\n Bernoulli polynomials to non-integer values of n.\n\n EXAMPLES::\n\n sage: # needs sage.libs.flint\n sage: y = QQ['y'].0\n sage: bernoulli_polynomial(y, 5)\n y^5 - 5/2*y^4 + 5/3*y^3 - 1/6*y\n sage: bernoulli_polynomial(y, 5)(12)\n 199870\n sage: bernoulli_polynomial(12, 5)\n 199870\n sage: bernoulli_polynomial(y^2 + 1, 5)\n y^10 + 5/2*y^8 + 5/3*y^6 - 1/6*y^2\n sage: P.<t> = ZZ[]\n sage: p = bernoulli_polynomial(t, 6)\n sage: p.parent()\n Univariate Polynomial Ring in t over Rational Field\n\n We verify an instance of the formula which is the origin of\n the Bernoulli polynomials (and numbers)::\n\n sage: power_sum = sum(k^4 for k in range(10))\n sage: 5*power_sum == bernoulli_polynomial(10, 5) - bernoulli(5) # needs sage.libs.flint\n True\n\n TESTS::\n\n sage: x = polygen(QQ, 'x')\n sage: bernoulli_polynomial(x, 0).parent()\n Univariate Polynomial Ring in x over Rational Field\n\n REFERENCES:\n\n - :wikipedia:`Bernoulli_polynomials`\n " try: n = ZZ(n) if (n < 0): raise TypeError except TypeError: raise ValueError('the second argument must be a non-negative integer') if (n == 0): return (x ** 0) if (n == 1): return (x - (ZZ.one() / 2)) k = n.mod(2) coeffs = (([0] * k) + sum(([(n.binomial(i) * bernoulli((n - i))), 0] for i in range(k, (n + 1), 2)), [])) coeffs[(- 3)] = ((- n) / 2) if isinstance(x, Polynomial): try: return x.parent()(coeffs)(x) except TypeError: pass x2 = (x * x) xi = (x ** k) s = 0 for i in range(k, (n - 1), 2): s += (coeffs[i] * xi) t = xi xi *= x2 s += (xi - (((t * x) * n) / 2)) return s
def Combinations(mset, k=None): '\n Return the combinatorial class of combinations of the multiset\n ``mset``. If ``k`` is specified, then it returns the combinatorial\n class of combinations of ``mset`` of size ``k``.\n\n A *combination* of a multiset `M` is an unordered selection of `k`\n objects of `M`, where every object can appear at most as many\n times as it appears in `M`.\n\n The combinatorial classes correctly handle the cases where ``mset`` has\n duplicate elements.\n\n EXAMPLES::\n\n sage: C = Combinations(range(4)); C\n Combinations of [0, 1, 2, 3]\n sage: C.list()\n [[],\n [0],\n [1],\n [2],\n [3],\n [0, 1],\n [0, 2],\n [0, 3],\n [1, 2],\n [1, 3],\n [2, 3],\n [0, 1, 2],\n [0, 1, 3],\n [0, 2, 3],\n [1, 2, 3],\n [0, 1, 2, 3]]\n sage: C.cardinality()\n 16\n\n ::\n\n sage: C2 = Combinations(range(4),2); C2\n Combinations of [0, 1, 2, 3] of length 2\n sage: C2.list()\n [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]\n sage: C2.cardinality()\n 6\n\n ::\n\n sage: Combinations([1,2,2,3]).list()\n [[],\n [1],\n [2],\n [3],\n [1, 2],\n [1, 3],\n [2, 2],\n [2, 3],\n [1, 2, 2],\n [1, 2, 3],\n [2, 2, 3],\n [1, 2, 2, 3]]\n\n ::\n\n sage: Combinations([1,2,3], 2).list()\n [[1, 2], [1, 3], [2, 3]]\n\n ::\n\n sage: mset = [1,1,2,3,4,4,5]\n sage: Combinations(mset,2).list()\n [[1, 1],\n [1, 2],\n [1, 3],\n [1, 4],\n [1, 5],\n [2, 3],\n [2, 4],\n [2, 5],\n [3, 4],\n [3, 5],\n [4, 4],\n [4, 5]]\n\n ::\n\n sage: mset = ["d","a","v","i","d"]\n sage: Combinations(mset,3).list()\n [[\'d\', \'d\', \'a\'],\n [\'d\', \'d\', \'v\'],\n [\'d\', \'d\', \'i\'],\n [\'d\', \'a\', \'v\'],\n [\'d\', \'a\', \'i\'],\n [\'d\', \'v\', \'i\'],\n [\'a\', \'v\', \'i\']]\n\n ::\n\n sage: X = Combinations([1,2,3,4,5],3)\n sage: [x for x in X]\n [[1, 2, 3],\n [1, 2, 4],\n [1, 2, 5],\n [1, 3, 4],\n [1, 3, 5],\n [1, 4, 5],\n [2, 3, 4],\n [2, 3, 5],\n [2, 4, 5],\n [3, 4, 5]]\n\n It is possible to take combinations of Sage objects::\n\n sage: Combinations([vector([1,1]), vector([2,2]), vector([3,3])], 2).list() # needs sage.modules\n [[(1, 1), (2, 2)], [(1, 1), (3, 3)], [(2, 2), (3, 3)]]\n\n TESTS:\n\n Run the test suites::\n\n sage: C = Combinations([2,3])\n sage: TestSuite(C).run()\n sage: C = Combinations([2,3], 1)\n sage: TestSuite(C).run()\n\n We check that the code works even for non mutable objects::\n\n sage: l = [vector((0,0)), vector((0,1))] # needs sage.modules\n sage: Combinations(l).list() # needs sage.modules\n [[], [(0, 0)], [(0, 1)], [(0, 0), (0, 1)]]\n ' is_unique = False if isinstance(mset, (int, Integer)): mset = list(range(mset)) is_unique = True elif isinstance(mset, range): mset = list(mset) is_unique = True else: mset = list(mset) for (i, e) in enumerate(mset): if (mset.index(e) != i): break else: is_unique = True if is_unique: if (k is None): return Combinations_set(mset) else: return Combinations_setk(mset, k) elif (k is None): return Combinations_mset(mset) else: return Combinations_msetk(mset, k)
class Combinations_mset(Parent): def __init__(self, mset): '\n TESTS::\n\n sage: C = Combinations(range(4))\n sage: C == loads(dumps(C))\n True\n ' self.mset = mset Parent.__init__(self, category=FiniteEnumeratedSets()) def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: c = Combinations(range(4))\n sage: all( i in c for i in c )\n True\n sage: [3,4] in c\n False\n sage: [0,0] in c\n False\n ' try: x = list(x) except TypeError: return False return (all(((i in self.mset) for i in x)) and (len(set(x)) == len(x))) def __eq__(self, other) -> bool: '\n Test for equality.\n\n EXAMPLES::\n\n sage: c = Combinations([1,2,2,3])\n sage: c == Combinations((1,2,2,3))\n True\n sage: c == Combinations([3,4,4,6])\n False\n ' return (isinstance(other, Combinations_mset) and (self.mset == other.mset)) def __ne__(self, other) -> bool: '\n Test for unequality.\n\n EXAMPLES::\n\n sage: c = Combinations([1,2,2])\n sage: c != Combinations([1,2,3,3])\n True\n ' return (not (self == other)) def __repr__(self) -> str: "\n TESTS::\n\n sage: repr(Combinations(range(4)))\n 'Combinations of [0, 1, 2, 3]'\n " return 'Combinations of {}'.format(self.mset) def __iter__(self): "\n TESTS::\n\n sage: Combinations(['a','a','b']).list() #indirect doctest\n [[], ['a'], ['b'], ['a', 'a'], ['a', 'b'], ['a', 'a', 'b']]\n " for k in range((len(self.mset) + 1)): (yield from Combinations_msetk(self.mset, k)) def cardinality(self) -> Integer: "\n TESTS::\n\n sage: Combinations([1,2,3]).cardinality()\n 8\n sage: Combinations(['a','a','b']).cardinality() # needs sage.libs.gap\n 6\n " return ZZ.sum((Combinations_msetk(self.mset, k).cardinality() for k in range((len(self.mset) + 1))))
class Combinations_set(Combinations_mset): def __iter__(self): '\n EXAMPLES::\n\n sage: Combinations([1,2,3]).list() #indirect doctest\n [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]\n ' for k in range((len(self.mset) + 1)): (yield from Combinations_setk(self.mset, k)) def unrank(self, r): '\n EXAMPLES::\n\n sage: c = Combinations([1,2,3])\n sage: c.list() == list(map(c.unrank, range(c.cardinality())))\n True\n ' k = 0 n = len(self.mset) b = binomial(n, k) while (r >= b): r -= b k += 1 b = binomial(n, k) return [self.mset[i] for i in from_rank(r, n, k)] def rank(self, x): '\n EXAMPLES::\n\n sage: c = Combinations([1,2,3])\n sage: list(range(c.cardinality())) == list(map(c.rank, c))\n True\n ' x = [self.mset.index(i) for i in x] r = 0 n = len(self.mset) for i in range(len(x)): r += binomial(n, i) r += rank(x, n) return r def cardinality(self): '\n Return the size of Combinations(set).\n\n EXAMPLES::\n\n sage: Combinations(range(16000)).cardinality() == 2^16000\n True\n ' return (ZZ(2) ** len(self.mset))
class Combinations_msetk(Parent): def __init__(self, mset, k): '\n TESTS::\n\n sage: C = Combinations([1,2,3],2)\n sage: C == loads(dumps(C))\n True\n ' self.mset = mset self.k = k Parent.__init__(self, category=FiniteEnumeratedSets()) def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: c = Combinations(range(4),2)\n sage: all( i in c for i in c )\n True\n sage: [0,1] in c\n True\n sage: [0,1,2] in c\n False\n sage: [3,4] in c\n False\n sage: [0,0] in c\n False\n ' try: x = list(x) except TypeError: return False return ((x in Combinations_mset(self.mset)) and (len(x) == self.k)) def __eq__(self, other) -> bool: '\n Test for equality.\n\n EXAMPLES::\n\n sage: c = Combinations([1,2,2,3],3)\n sage: c == Combinations((1,2,2,3), 3)\n True\n sage: c == Combinations([1,2,2,3], 2)\n False\n ' return (isinstance(other, Combinations_msetk) and (self.mset == other.mset) and (self.k == other.k)) def __ne__(self, other) -> bool: '\n Test for unequality.\n\n EXAMPLES::\n\n sage: c = Combinations([1,2,2,3],3)\n sage: c != Combinations((1,2,2,3), 2)\n True\n ' return (not (self == other)) def __repr__(self) -> str: "\n TESTS::\n\n sage: repr(Combinations([1,2,2,3],2))\n 'Combinations of [1, 2, 2, 3] of length 2'\n " return 'Combinations of {} of length {}'.format(self.mset, self.k) def __iter__(self): "\n EXAMPLES::\n\n sage: Combinations(['a','a','b'],2).list() # indirect doctest\n [['a', 'a'], ['a', 'b']]\n " items = [self.mset.index(x) for x in self.mset] indices = sorted(set(items)) counts = ([0] * len(indices)) for i in items: counts[indices.index(i)] += 1 for iv in IntegerVectors(self.k, len(indices), outer=counts): (yield sum([([self.mset[indices[i]]] * iv[i]) for i in range(len(indices))], [])) def cardinality(self) -> Integer: "\n Return the size of combinations(mset, k).\n\n IMPLEMENTATION: Wraps GAP's NrCombinations.\n\n EXAMPLES::\n\n sage: mset = [1,1,2,3,4,4,5]\n sage: Combinations(mset,2).cardinality() # needs sage.libs.gap\n 12\n " from sage.libs.gap.libgap import libgap items = [self.mset.index(i) for i in self.mset] nc = libgap.function_factory('NrCombinations') return ZZ(nc(items, ZZ(self.k)))
class Combinations_setk(Combinations_msetk): def _iterator(self, items, n): '\n An iterator for all the n-combinations of items.\n\n EXAMPLES::\n\n sage: it = Combinations([1,2,3,4],3)._iterator([1,2,3,4],3)\n sage: list(it)\n [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]\n ' for combination in itertools.combinations(items, n): (yield list(combination)) def _iterator_zero(self): '\n An iterator which just returns the empty list.\n\n EXAMPLES::\n\n sage: it = Combinations([1,2,3,4,5],3)._iterator_zero()\n sage: list(it)\n [[]]\n ' (yield []) def __iter__(self): "\n Uses Python's :func:`itertools.combinations` to iterate through all\n of the combinations.\n\n EXAMPLES::\n\n sage: Combinations([1,2,3,4,5],3).list() # indirect doctest\n [[1, 2, 3],\n [1, 2, 4],\n [1, 2, 5],\n [1, 3, 4],\n [1, 3, 5],\n [1, 4, 5],\n [2, 3, 4],\n [2, 3, 5],\n [2, 4, 5],\n [3, 4, 5]]\n " if (self.k == 0): return self._iterator_zero() else: return self._iterator(self.mset, self.k) def list(self) -> list: '\n EXAMPLES::\n\n sage: Combinations([1,2,3,4,5],3).list()\n [[1, 2, 3],\n [1, 2, 4],\n [1, 2, 5],\n [1, 3, 4],\n [1, 3, 5],\n [1, 4, 5],\n [2, 3, 4],\n [2, 3, 5],\n [2, 4, 5],\n [3, 4, 5]]\n ' return list(self) def unrank(self, r): '\n EXAMPLES::\n\n sage: c = Combinations([1,2,3], 2)\n sage: c.list() == list(map(c.unrank, range(c.cardinality())))\n True\n ' return [self.mset[i] for i in from_rank(r, len(self.mset), self.k)] def rank(self, x): '\n EXAMPLES::\n\n sage: c = Combinations([1,2,3], 2)\n sage: list(range(c.cardinality())) == list(map(c.rank, c.list()))\n True\n ' x = [self.mset.index(i) for i in x] return rank(x, len(self.mset)) def cardinality(self) -> Integer: '\n Return the size of combinations(set, k).\n\n EXAMPLES::\n\n sage: Combinations(range(16000), 5).cardinality()\n 8732673194560003200\n ' return ZZ(binomial(len(self.mset), self.k))
def rank(comb, n, check=True): "\n Return the rank of ``comb`` in the subsets of ``range(n)`` of size ``k``\n where ``k`` is the length of ``comb``.\n\n The algorithm used is based on combinadics and James McCaffrey's\n MSDN article. See: :wikipedia:`Combinadic`.\n\n EXAMPLES::\n\n sage: import sage.combinat.combination as combination\n sage: combination.rank((), 3)\n 0\n sage: combination.rank((0,), 3)\n 0\n sage: combination.rank((1,), 3)\n 1\n sage: combination.rank((2,), 3)\n 2\n sage: combination.rank((0,1), 3)\n 0\n sage: combination.rank((0,2), 3)\n 1\n sage: combination.rank((1,2), 3)\n 2\n sage: combination.rank((0,1,2), 3)\n 0\n\n sage: combination.rank((0,1,2,3), 3)\n Traceback (most recent call last):\n ...\n ValueError: len(comb) must be <= n\n sage: combination.rank((0,0), 2)\n Traceback (most recent call last):\n ...\n ValueError: comb must be a subword of (0,1,...,n)\n\n sage: combination.rank([1,2], 3)\n 2\n sage: combination.rank([0,1,2], 3)\n 0\n " k = len(comb) if check: if (k > n): raise ValueError('len(comb) must be <= n') comb = [int(i) for i in comb] for i in range((k - 1)): if (comb[(i + 1)] <= comb[i]): raise ValueError('comb must be a subword of (0,1,...,n)') r = k t = 0 for i in range(k): t += binomial(((n - 1) - comb[i]), r) r -= 1 return ((binomial(n, k) - t) - 1)
def from_rank(r, n, k): "\n Return the combination of rank ``r`` in the subsets of\n ``range(n)`` of size ``k`` when listed in lexicographic order.\n\n The algorithm used is based on factoradics and presented in [DGH2020]_.\n It is there compared to the other from the literature.\n\n EXAMPLES::\n\n sage: import sage.combinat.combination as combination\n sage: combination.from_rank(0,3,0)\n ()\n sage: combination.from_rank(0,3,1)\n (0,)\n sage: combination.from_rank(1,3,1)\n (1,)\n sage: combination.from_rank(2,3,1)\n (2,)\n sage: combination.from_rank(0,3,2)\n (0, 1)\n sage: combination.from_rank(1,3,2)\n (0, 2)\n sage: combination.from_rank(2,3,2)\n (1, 2)\n sage: combination.from_rank(0,3,3)\n (0, 1, 2)\n\n TESTS::\n\n sage: from sage.combinat.combination import from_rank\n sage: def _comb_largest(a,b,x):\n ....: w = a - 1\n ....: while binomial(w,b) > x:\n ....: w -= 1\n ....: return w\n sage: def from_rank_comb_largest(r, n, k):\n ....: a = n\n ....: b = k\n ....: x = binomial(n, k) - 1 - r # x is the 'dual' of m\n ....: comb = [None] * k\n ....: for i in range(k):\n ....: comb[i] = _comb_largest(a, b, x)\n ....: x = x - binomial(comb[i], b)\n ....: a = comb[i]\n ....: b = b - 1\n ....: for i in range(k):\n ....: comb[i] = (n - 1) - comb[i]\n ....: return tuple(comb)\n sage: all(from_rank(r, n, k) == from_rank_comb_largest(r, n, k) # needs sage.symbolic\n ....: for n in range(10) for k in range(n+1) for r in range(binomial(n,k)))\n True\n " if (k < 0): raise ValueError('k must be > 0') if (k > n): raise ValueError('k must be <= n') if ((n == 0) or (k == 0)): return () if (n < 0): raise ValueError('n must be >= 0') B = binomial(n, k) if ((r < 0) or (r >= B)): raise ValueError('r must satisfy 0 <= r < binomial(n, k)') if (k == 1): return (r,) n0 = n D = ([0] * k) inverse = False if (k < (n0 / 2)): inverse = True k = (n - k) r = ((B - 1) - r) B = ((B * k) // n0) m = 0 i = 0 j = 0 m2 = 0 d = 0 while (d < (k - 1)): if (B > r): if (i < (k - 2)): if (((n0 - 1) - m) == 0): B = 1 else: B = ((B * ((k - 1) - i)) // ((n0 - 1) - m)) d += 1 if inverse: for e in range(m2, (m + i)): D[j] = e j += 1 m2 = ((m + i) + 1) else: D[i] = (m + i) i += 1 n0 -= 1 else: r -= B if (((n0 - 1) - m) == 0): B = 1 else: B = ((B * (((n0 - m) - k) + i)) // ((n0 - 1) - m)) m += 1 if inverse: for e in range(m2, (((n0 + r) + i) - B)): D[j] = e j += 1 for e in range(((((n0 + r) + i) + 1) - B), n): D[j] = e j += 1 else: D[(k - 1)] = ((((n0 + r) + k) - 1) - B) return tuple(D)
class ChooseNK(Combinations_setk): def __setstate__(self, state): '\n For unpickling old ``ChooseNK`` objects.\n\n TESTS::\n\n sage: loads(b"x\\x9ck`J.NLO\\xd5K\\xce\\xcfM\\xca\\xccK,\\xd1K\\xce\\xc8\\xcf"\n ....: b"/N\\x8d\\xcf\\xcb\\xe6r\\x06\\xb3\\xfc\\xbc\\xb9\\n\\x195\\x1b\\x0b"\n ....: b"\\x99j\\x0b\\x995B\\x99\\xe2\\xf3\\nY :\\x8a2\\xf3\\xd2\\x8b\\xf52"\n ....: b"\\xf3JR\\xd3S\\x8b\\xb8r\\x13\\xb3S\\xe3a\\x9cB\\xd6PF\\xd3\\xd6\\xa0"\n ....: b"B6\\xa0\\xfa\\xecB\\xf6\\x0c \\xd7\\x08\\xc8\\xe5(M\\xd2\\x03\\x00{"\n ....: b"\\x82$\\xd8")\n Combinations of [0, 1, 2, 3, 4] of length 2\n ' self.__class__ = Combinations_setk Combinations_setk.__init__(self, list(range(state['_n'])), state['_k'])
def combinatorial_map_trivial(f=None, order=None, name=None): "\n Combinatorial map decorator\n\n See :ref:`sage.combinat.combinatorial_map` for a description of\n this decorator and its purpose. This default implementation does\n nothing.\n\n INPUT:\n\n\n - ``f`` -- (default: ``None``, if combinatorial_map is used as a decorator) a function\n - ``name`` -- (default: ``None``) the name for nicer outputs on combinatorial maps\n - ``order`` -- (default: ``None``) the order of the combinatorial map, if it is known. Is not used, but might be helpful later\n\n OUTPUT:\n\n - ``f`` unchanged\n\n EXAMPLES::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_map_trivial as combinatorial_map\n sage: class MyPermutation():\n ....: @combinatorial_map\n ....: def reverse(self):\n ....: '''\n ....: Reverse the permutation\n ....: '''\n ....: # ... code ...\n ....: @combinatorial_map(name='descent set of permutation')\n ....: def descent_set(self):\n ....: '''\n ....: The descent set of the permutation\n ....: '''\n ....: # ... code ...\n\n sage: MyPermutation.reverse\n <function MyPermutation.reverse at ...>\n\n sage: MyPermutation.descent_set\n <function MyPermutation.descent_set at ...>\n " if (f is None): return (lambda f: f) else: return f
def combinatorial_map_wrapper(f=None, order=None, name=None): "\n Combinatorial map decorator (basic example).\n\n See :ref:`sage.combinat.combinatorial_map` for a description of\n the ``combinatorial_map`` decorator and its purpose. This\n implementation, together with :func:`combinatorial_maps_in_class`\n illustrates how to use this decorator as a hook to instrument the\n Sage code.\n\n INPUT:\n\n - ``f`` -- (default: ``None``, if combinatorial_map is used as a decorator) a function\n - ``name`` -- (default: ``None``) the name for nicer outputs on combinatorial maps\n - ``order`` -- (default: ``None``) the order of the combinatorial map, if it is known. Is not used, but might be helpful later\n\n OUTPUT:\n\n - A combinatorial map. This is an instance of the :class:`CombinatorialMap`.\n\n EXAMPLES:\n\n We define a class illustrating the use of this implementation of\n the :obj:`combinatorial_map` decorator with its various arguments::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_map_wrapper as combinatorial_map\n sage: class MyPermutation():\n ....: @combinatorial_map()\n ....: def reverse(self):\n ....: '''\n ....: Reverse the permutation\n ....: '''\n ....: pass\n ....: @combinatorial_map(order=2)\n ....: def inverse(self):\n ....: '''\n ....: The inverse of the permutation\n ....: '''\n ....: pass\n ....: @combinatorial_map(name='descent set of permutation')\n ....: def descent_set(self):\n ....: '''\n ....: The descent set of the permutation\n ....: '''\n ....: pass\n ....: def major_index(self):\n ....: '''\n ....: The major index of the permutation\n ....: '''\n ....: pass\n sage: MyPermutation.reverse\n Combinatorial map: reverse\n sage: MyPermutation.descent_set\n Combinatorial map: descent set of permutation\n sage: MyPermutation.inverse\n Combinatorial map: inverse\n\n One can now determine all the combinatorial maps associated with a\n given object as follows::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_maps_in_class\n sage: X = combinatorial_maps_in_class(MyPermutation); X # random\n [Combinatorial map: reverse,\n Combinatorial map: descent set of permutation,\n Combinatorial map: inverse]\n\n The method ``major_index`` defined about is not a combinatorial map::\n\n sage: MyPermutation.major_index\n <function MyPermutation.major_index at ...>\n\n But one can define a function that turns ``major_index`` into a combinatorial map::\n\n sage: def major_index(p):\n ....: return p.major_index()\n sage: major_index\n <function major_index at ...>\n sage: combinatorial_map(major_index)\n Combinatorial map: major_index\n\n " if (f is None): return (lambda f: CombinatorialMap(f, order=order, name=name)) else: return CombinatorialMap(f, order=order, name=name)
class CombinatorialMap(): '\n This is a wrapper class for methods that are *combinatorial maps*.\n\n For further details and doctests, see\n :ref:`sage.combinat.combinatorial_map` and\n :func:`combinatorial_map_wrapper`.\n ' def __init__(self, f, order=None, name=None): '\n Constructor for combinatorial maps.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_map_wrapper as combinatorial_map\n sage: def f(x):\n ....: "doc of f"\n ....: return x\n sage: x = combinatorial_map(f); x\n Combinatorial map: f\n sage: x.__doc__\n \'doc of f\'\n sage: x.__name__\n \'f\'\n sage: x.__module__\n \'__main__\'\n ' import types if (not isinstance(f, types.FunctionType)): raise ValueError('only plain functions are supported') self._f = f self._order = order self._name = name if hasattr(f, '__doc__'): self.__doc__ = f.__doc__ if hasattr(f, '__name__'): self.__name__ = f.__name__ else: self.__name__ = '...' if hasattr(f, '__module__'): self.__module__ = f.__module__ def __repr__(self): "\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: p = Permutation([1,3,2,4])\n sage: p.left_tableau.__repr__()\n 'Combinatorial map: Robinson-Schensted insertion tableau'\n " return ('Combinatorial map: %s' % self.name()) def _sage_src_lines_(self): '\n Return the source code location for the wrapped function.\n\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: p = Permutation([1,3,2,4])\n sage: cm = p.left_tableau; cm\n Combinatorial map: Robinson-Schensted insertion tableau\n sage: (src, lines) = cm._sage_src_lines_()\n sage: src[0]\n " @combinatorial_map(name=\'Robinson-Schensted insertion tableau\')\\n"\n sage: lines # random\n 2653\n ' from sage.misc.sageinspect import sage_getsourcelines return sage_getsourcelines(self._f) def __get__(self, inst, cls=None): '\n Bounds the method of self to the given instance.\n\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: p = Permutation([1,3,2,4])\n sage: p.left_tableau #indirect doctest\n Combinatorial map: Robinson-Schensted insertion tableau\n ' self._inst = inst return self def __call__(self, *args, **kwds): '\n Calls the combinatorial map.\n\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: p = Permutation([1,3,2,4])\n sage: cm = type(p).left_tableau; cm\n Combinatorial map: Robinson-Schensted insertion tableau\n sage: cm(p) # needs sage.combinat\n [[1, 2, 4], [3]]\n sage: cm(Permutation([4,3,2,1])) # needs sage.combinat\n [[1], [2], [3], [4]]\n ' if (self._inst is not None): return self._f(self._inst, *args, **kwds) else: return self._f(*args, **kwds) def unbounded_map(self): '\n Return the unbounded version of ``self``.\n\n You can use this method to return a function which takes as input\n an element in the domain of the combinatorial map.\n See the example below.\n\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: from sage.combinat.permutation import Permutation\n sage: pi = Permutation([1,3,2])\n sage: f = pi.reverse\n sage: F = f.unbounded_map()\n sage: F(pi)\n [2, 3, 1]\n ' return self._f def order(self): '\n Returns the order of ``self``, or ``None`` if the order is not known.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_map\n sage: class CombinatorialClass:\n ....: @combinatorial_map(order=2)\n ....: def to_self_1(): pass\n ....: @combinatorial_map()\n ....: def to_self_2(): pass\n sage: CombinatorialClass.to_self_1.order()\n 2\n sage: CombinatorialClass.to_self_2.order() is None\n True\n ' return self._order def name(self): "\n Returns the name of a combinatorial map.\n This is used for the string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.combinatorial_map import combinatorial_map\n sage: class CombinatorialClass:\n ....: @combinatorial_map(name='map1')\n ....: def to_self_1(): pass\n ....: @combinatorial_map()\n ....: def to_self_2(): pass\n sage: CombinatorialClass.to_self_1.name()\n 'map1'\n sage: CombinatorialClass.to_self_2.name()\n 'to_self_2'\n " if (self._name is not None): return self._name else: return self._f.__name__
def combinatorial_maps_in_class(cls): '\n Return the combinatorial maps of the class as a list of combinatorial maps.\n\n For further details and doctests, see\n :ref:`sage.combinat.combinatorial_map` and\n :func:`combinatorial_map_wrapper`.\n\n EXAMPLES::\n\n sage: sage.combinat.combinatorial_map.combinatorial_map = sage.combinat.combinatorial_map.combinatorial_map_wrapper\n sage: from importlib import reload\n sage: _ = reload(sage.combinat.permutation)\n sage: from sage.combinat.combinatorial_map import combinatorial_maps_in_class\n sage: p = Permutation([1,3,2,4])\n sage: cmaps = combinatorial_maps_in_class(p)\n sage: cmaps # random\n [Combinatorial map: Robinson-Schensted insertion tableau,\n Combinatorial map: Robinson-Schensted recording tableau,\n Combinatorial map: Robinson-Schensted tableau shape,\n Combinatorial map: complement,\n Combinatorial map: descent composition,\n Combinatorial map: inverse, ...]\n sage: p.left_tableau in cmaps\n True\n sage: p.right_tableau in cmaps\n True\n sage: p.complement in cmaps\n True\n ' result = set() for method in dir(cls): entry = getattr(cls, method) if isinstance(entry, CombinatorialMap): result.add(entry) return list(result)
class Composition(CombinatorialElement): '\n Integer compositions\n\n A composition of a nonnegative integer `n` is a list\n `(i_1, \\ldots, i_k)` of positive integers with total sum `n`.\n\n EXAMPLES:\n\n The simplest way to create a composition is by specifying its\n entries as a list, tuple (or other iterable)::\n\n sage: Composition([3,1,2])\n [3, 1, 2]\n sage: Composition((3,1,2))\n [3, 1, 2]\n sage: Composition(i for i in range(2,5))\n [2, 3, 4]\n\n You can also create a composition from its code. The *code* of\n a composition `(i_1, i_2, \\ldots, i_k)` of `n` is a list of length `n`\n that consists of a `1` followed by `i_1-1` zeros, then a `1` followed\n by `i_2-1` zeros, and so on.\n\n ::\n\n sage: Composition([4,1,2,3,5]).to_code()\n [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n sage: Composition(code=_)\n [4, 1, 2, 3, 5]\n sage: Composition([3,1,2,3,5]).to_code()\n [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n sage: Composition(code=_)\n [3, 1, 2, 3, 5]\n\n You can also create the composition of `n` corresponding to a subset of\n `\\{1, 2, \\ldots, n-1\\}` under the bijection that maps the composition\n `(i_1, i_2, \\ldots, i_k)` of `n` to the subset\n `\\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \\ldots, i_1 + \\cdots + i_{k-1}\\}`\n (see :meth:`to_subset`)::\n\n sage: Composition(from_subset=({1, 2, 4}, 5))\n [1, 1, 2, 1]\n sage: Composition([1, 1, 2, 1]).to_subset()\n {1, 2, 4}\n\n The following notation equivalently specifies the composition from the\n set `\\{i_1 - 1, i_1 + i_2 - 1, i_1 + i_2 + i_3 - 1, \\dots, i_1 + \\cdots\n + i_{k-1} - 1, n-1\\}` or `\\{i_1 - 1, i_1 + i_2 - 1, i_1 + i_2 + i_3\n - 1, \\dots, i_1 + \\cdots + i_{k-1} - 1\\}` and `n`. This provides\n compatibility with Python\'s `0`-indexing.\n\n ::\n\n sage: Composition(descents=[1,0,4,8,11])\n [1, 1, 3, 4, 3]\n sage: Composition(descents=[0,1,3,4])\n [1, 1, 2, 1]\n sage: Composition(descents=([0,1,3],5))\n [1, 1, 2, 1]\n sage: Composition(descents=({0,1,3},5))\n [1, 1, 2, 1]\n\n An integer composition may be regarded as a sequence. Thus it is an\n instance of the Python abstract base class ``Sequence`` allows us to check if objects\n behave "like" sequences based on implemented methods. Note that\n ``collections.abc.Sequence`` is not the same as\n :class:`sage.structure.sequence.Sequence`::\n\n sage: import collections.abc\n sage: C = Composition([3,2,3])\n sage: isinstance(C, collections.abc.Sequence)\n True\n sage: issubclass(C.__class__, collections.abc.Sequence)\n True\n\n Typically, instances of ``collections.abc.Sequence`` have a ``.count`` method.\n ``Composition.count`` counts the number of parts of a specified size::\n\n sage: C.count(3)\n 2\n\n EXAMPLES::\n\n sage: C = Composition([3,1,2])\n sage: TestSuite(C).run()\n ' @staticmethod def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=None): '\n This constructs a list from optional arguments and delegates the\n construction of a :class:`Composition` to the ``element_class()`` call\n of the appropriate parent.\n\n EXAMPLES::\n\n sage: Composition([3,2,1])\n [3, 2, 1]\n sage: Composition(from_subset=({1, 2, 4}, 5))\n [1, 1, 2, 1]\n sage: Composition(descents=[1,0,4,8,11])\n [1, 1, 3, 4, 3]\n sage: Composition([4,1,2,3,5]).to_code()\n [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n sage: Composition(code=_)\n [4, 1, 2, 3, 5]\n ' if (descents is not None): if isinstance(descents, tuple): return Compositions().from_descents(descents[0], nps=descents[1]) else: return Compositions().from_descents(descents) elif (code is not None): return Compositions().from_code(code) elif (from_subset is not None): return Compositions().from_subset(*from_subset) elif isinstance(co, Composition): return co else: return Compositions()(list(co)) def _ascii_art_(self): '\n TESTS::\n\n sage: # needs sage.combinat\n sage: ascii_art(Compositions(4).list())\n [ * ]\n [ * ** * * ]\n [ * * ** *** * ** * ]\n [ *, * , * , * , **, ** , ***, **** ]\n sage: Partitions.options(diagram_str=\'#\', convention="French")\n sage: ascii_art(Compositions(4).list())\n [ # ]\n [ # # # ## ]\n [ # # ## # # ## ### ]\n [ #, ##, #, ###, #, ##, #, #### ]\n sage: Partitions.options._reset()\n ' from sage.typeset.ascii_art import ascii_art return ascii_art(self.to_skew_partition()) def _unicode_art_(self): '\n TESTS::\n\n sage: # needs sage.combinat\n sage: unicode_art(Compositions(4).list())\n ⎡ ┌┐ ⎤\n ⎢ ├┤ ┌┬┐ ┌┐ ┌┐ ⎥\n ⎢ ├┤ ├┼┘ ┌┼┤ ┌┬┬┐ ├┤ ┌┬┐ ┌┐ ⎥\n ⎢ ├┤ ├┤ ├┼┘ ├┼┴┘ ┌┼┤ ┌┼┼┘ ┌┬┼┤ ┌┬┬┬┐ ⎥\n ⎣ └┘, └┘ , └┘ , └┘ , └┴┘, └┴┘ , └┴┴┘, └┴┴┴┘ ⎦\n sage: Partitions.options(diagram_str=\'#\', convention="French")\n sage: unicode_art(Compositions(4).list())\n ⎡ ┌┐ ⎤\n ⎢ ├┤ ┌┐ ┌┐ ┌┬┐ ⎥\n ⎢ ├┤ ├┤ ├┼┐ ┌┐ └┼┤ ┌┬┐ ┌┬┬┐ ⎥\n ⎢ ├┤ ├┼┐ └┼┤ ├┼┬┐ ├┤ └┼┼┐ └┴┼┤ ┌┬┬┬┐ ⎥\n ⎣ └┘, └┴┘, └┘, └┴┴┘, └┘, └┴┘, └┘, └┴┴┴┘ ⎦\n sage: Partitions.options._reset()\n ' from sage.typeset.unicode_art import unicode_art return unicode_art(self.to_skew_partition()) def __setstate__(self, state): '\n In order to maintain backwards compatibility and be able to unpickle a\n old pickle from ``Composition_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,\\x011\\n\\xf2\\x8b3K2\\xf3\\xf3\\xb8\\x9c\\x11\\xec\\xf8\\xe4\\x9c\\xc4\\xe2b\\xaeBF\\xcd\\xc6B\\xa6\\xdaBf\\x8dP\\xd6\\xf8\\x8c\\xc4\\xe2\\x8cB\\x16? +\'\\xb3\\xb8\\xa4\\x905\\xb6\\x90M\\x03bZQf^z\\xb1^f^Ijzj\\x11Wnbvj<\\x8cS\\xc8\\x1e\\xcah\\xd8\\x1aT\\xc8\\x91\\x01d\\x18\\x01\\x19\\x9c\\x19P\\x11\\xae\\xd4\\xd2$=\\x00eW0g")\n [1, 2, 1]\n sage: loads(dumps( Composition([1,2,1]) )) # indirect doctest\n [1, 2, 1]\n ' if isinstance(state, dict): self._set_parent(Compositions()) self.__dict__ = state else: self._set_parent(state[0]) self.__dict__ = state[1] @combinatorial_map(order=2, name='conjugate') def conjugate(self) -> Composition: '\n Return the conjugate of the composition ``self``.\n\n The conjugate of a composition `I` is defined as the\n complement (see :meth:`complement`) of the reverse composition\n (see :meth:`reversed`) of `I`.\n\n An equivalent definition of the conjugate goes by saying that\n the ribbon shape of the conjugate of a composition `I` is the\n conjugate of the ribbon shape of `I`. (The ribbon shape of a\n composition is returned by :meth:`to_skew_partition`.)\n\n This implementation uses the algorithm from mupad-combinat.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).conjugate()\n [1, 1, 3, 3, 1, 3]\n\n The ribbon shape of the conjugate of `I` is the conjugate of\n the ribbon shape of `I`::\n\n sage: all( I.conjugate().to_skew_partition() # needs sage.combinat\n ....: == I.to_skew_partition().conjugate()\n ....: for I in Compositions(4) )\n True\n\n TESTS::\n\n sage: parent(list(Compositions(1))[0].conjugate())\n Compositions of 1\n sage: parent(list(Compositions(0))[0].conjugate())\n Compositions of 0\n ' comp = self if (not comp): return self n = len(comp) coofcp = [(sigmaj - j) for (j, sigmaj) in enumerate(accumulate(comp))] cocjg = [] for i in range((n - 1)): ni = (n - i) cocjg += [(i + 1) for _ in range((coofcp[(ni - 1)] - coofcp[(ni - 2)]))] cocjg += [n for j in range(coofcp[0])] return self.parent()(([cocjg[0]] + [((cocjg[i] - cocjg[(i - 1)]) + 1) for i in range(1, len(cocjg))])) @combinatorial_map(order=2, name='reversed') def reversed(self) -> Composition: '\n Return the reverse composition of ``self``.\n\n The reverse composition of a composition `(i_1, i_2, \\ldots, i_k)`\n is defined as the composition `(i_k, i_{k-1}, \\ldots, i_1)`.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).reversed()\n [3, 1, 2, 1, 3, 1, 1]\n ' return self.parent()(reversed(self)) @combinatorial_map(order=2, name='complement') def complement(self) -> Composition: '\n Return the complement of the composition ``self``.\n\n The complement of a composition `I` is defined as follows:\n\n If `I` is the empty composition, then the complement is the empty\n composition as well. Otherwise, let `S` be the descent set of `I`\n (that is, the subset\n `\\{ i_1, i_1 + i_2, \\ldots, i_1 + i_2 + \\cdots + i_{k-1} \\}`\n of `\\{ 1, 2, \\ldots, |I|-1 \\}`, where `I` is written as\n `(i_1, i_2, \\ldots, i_k)`). Then, the complement of `I` is\n defined as the composition of size `|I|` whose descent set is\n `\\{ 1, 2, \\ldots, |I|-1 \\} \\setminus S`.\n\n The complement of a composition `I` also is the reverse\n composition (:meth:`reversed`) of the conjugate\n (:meth:`conjugate`) of `I`.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).conjugate()\n [1, 1, 3, 3, 1, 3]\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).complement()\n [3, 1, 3, 3, 1, 1]\n ' return self.conjugate().reversed() def __add__(self, other) -> Composition: '\n Return the concatenation of two compositions.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3]) + Composition([4, 1, 2])\n [1, 1, 3, 4, 1, 2]\n\n TESTS::\n\n sage: Composition([]) + Composition([]) == Composition([])\n True\n ' return Compositions()((list(self) + list(other))) def size(self) -> int: '\n Return the size of ``self``, that is the sum of its parts.\n\n EXAMPLES::\n\n sage: Composition([7,1,3]).size()\n 11\n ' return sum(self) @staticmethod def sum(compositions) -> Composition: '\n Return the concatenation of the given compositions.\n\n INPUT:\n\n - ``compositions`` -- a list (or iterable) of compositions\n\n EXAMPLES::\n\n sage: Composition.sum([Composition([1, 1, 3]), Composition([4, 1, 2]), Composition([3,1])])\n [1, 1, 3, 4, 1, 2, 3, 1]\n\n Any iterable can be provided as input::\n\n sage: Composition.sum([Composition([i,i]) for i in [4,1,3]])\n [4, 4, 1, 1, 3, 3]\n\n Empty inputs are handled gracefully::\n\n sage: Composition.sum([]) == Composition([])\n True\n ' return sum(compositions, Compositions()([])) def near_concatenation(self, other): '\n Return the near-concatenation of two nonempty compositions\n ``self`` and ``other``.\n\n The near-concatenation `I \\odot J` of two nonempty compositions\n `I` and `J` is defined as the composition\n `(i_1, i_2, \\ldots , i_{n-1}, i_n + j_1, j_2, j_3, \\ldots , j_m)`,\n where `(i_1, i_2, \\ldots , i_n) = I` and\n `(j_1, j_2, \\ldots , j_m) = J`.\n\n This method returns ``None`` if one of the two input\n compositions is empty.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3]).near_concatenation(Composition([4, 1, 2]))\n [1, 1, 7, 1, 2]\n sage: Composition([6]).near_concatenation(Composition([1, 5]))\n [7, 5]\n sage: Composition([1, 5]).near_concatenation(Composition([6]))\n [1, 11]\n\n TESTS::\n\n sage: Composition([]).near_concatenation(Composition([]))\n <BLANKLINE>\n sage: Composition([]).near_concatenation(Composition([2, 1]))\n <BLANKLINE>\n sage: Composition([3, 2]).near_concatenation(Composition([]))\n <BLANKLINE>\n ' if ((not self) or (not other)): return None return Compositions()(((list(self)[:(- 1)] + [(self[(- 1)] + other[0])]) + list(other)[1:])) def ribbon_decomposition(self, other, check=True): '\n Return a pair describing the ribbon decomposition of a composition\n ``self`` with respect to a composition ``other`` of the same size.\n\n If `I` and `J` are two compositions of the same nonzero size, then\n the ribbon decomposition of `I` with respect to `J` is defined as\n follows: Write `I` and `J` as `I = (i_1, i_2, \\ldots , i_n)` and\n `J = (j_1, j_2, \\ldots , j_m)`. Then, the equality\n `I = I_1 \\bullet I_2 \\bullet \\ldots \\bullet I_m` holds for a\n unique `m`-tuple `(I_1, I_2, \\ldots , I_m)` of compositions such\n that each `I_k` has size `j_k` and for a unique choice of `m-1`\n signs `\\bullet` each of which is either the concatenation sign\n `\\cdot` or the near-concatenation sign `\\odot` (see\n :meth:`__add__` and :meth:`near_concatenation` for the definitions\n of these two signs). This `m`-tuple and this choice of signs\n together are said to form the ribbon decomposition of `I` with\n respect to `J`. If `I` and `J` are empty, then the same definition\n applies, except that there are `0` rather than `m-1` signs.\n\n See Section 4.8 of [NCSF1]_.\n\n INPUT:\n\n - ``other`` -- composition of same size as ``self``\n\n - ``check`` -- (default: ``True``) a Boolean determining whether\n to check the input compositions for having the same size\n\n OUTPUT:\n\n - a pair ``(u, v)``, where ``u`` is a tuple of compositions\n (corresponding to the `m`-tuple `(I_1, I_2, \\ldots , I_m)` in\n the above definition), and ``v`` is a tuple of `0`s and `1`s\n (encoding the choice of signs `\\bullet` in the above definition,\n with a `0` standing for `\\cdot` and a `1` standing for `\\odot`).\n\n EXAMPLES::\n\n sage: Composition([3, 1, 1, 3, 1]).ribbon_decomposition([4, 3, 2])\n (([3, 1], [1, 2], [1, 1]), (0, 1))\n sage: Composition([9, 6]).ribbon_decomposition([1, 3, 6, 3, 2])\n (([1], [3], [5, 1], [3], [2]), (1, 1, 1, 1))\n sage: Composition([9, 6]).ribbon_decomposition([1, 3, 5, 1, 3, 2])\n (([1], [3], [5], [1], [3], [2]), (1, 1, 0, 1, 1))\n sage: Composition([1, 1, 1, 1, 1]).ribbon_decomposition([3, 2])\n (([1, 1, 1], [1, 1]), (0,))\n sage: Composition([4, 2]).ribbon_decomposition([6])\n (([4, 2],), ())\n sage: Composition([]).ribbon_decomposition([])\n ((), ())\n\n Let us check that the defining property\n `I = I_1 \\bullet I_2 \\bullet \\ldots \\bullet I_m` is satisfied::\n\n sage: def compose_back(u, v):\n ....: comp = u[0]\n ....: r = len(v)\n ....: if len(u) != r + 1:\n ....: raise ValueError("something is wrong")\n ....: for i in range(r):\n ....: if v[i] == 0:\n ....: comp += u[i + 1]\n ....: else:\n ....: comp = comp.near_concatenation(u[i + 1])\n ....: return comp\n sage: all( all( all( compose_back(*(I.ribbon_decomposition(J))) == I\n ....: for J in Compositions(n) )\n ....: for I in Compositions(n) )\n ....: for n in range(1, 5) )\n True\n\n TESTS::\n\n sage: Composition([3, 1, 1, 3, 1]).ribbon_decomposition([4, 3, 1])\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 1, 3, 1] is not the same size as [4, 3, 1]\n\n AUTHORS:\n\n - Darij Grinberg (2013-08-29)\n ' if (check and (sum(self) != sum(other))): raise ValueError('{} is not the same size as {}'.format(self, other)) factors = [] signs = [] I_iter = iter(self) i = 0 for j in other: current_factor = [] current_factor_size = 0 while True: if (i == 0): try: i = next(I_iter) except StopIteration: factors.append(Compositions()(current_factor)) return (tuple(factors), tuple(signs)) if ((current_factor_size + i) <= j): current_factor.append(i) current_factor_size += i i = 0 else: if (j == current_factor_size): signs.append(0) else: current_factor.append((j - current_factor_size)) i -= (j - current_factor_size) signs.append(1) factors.append(Compositions()(current_factor)) break return (tuple(factors), tuple(signs)) def join(self, other, check=True) -> Composition: '\n Return the join of ``self`` with a composition ``other`` of the\n same size.\n\n The join of two compositions `I` and `J` of size `n` is the\n coarsest composition of `n` which refines each of `I` and `J`. It\n can be described as the composition whose descent set is the\n union of the descent sets of `I` and `J`. It is also the\n concatenation of `I_1, I_2, \\cdots , I_m`, where\n `I = I_1 \\bullet I_2 \\bullet \\ldots \\bullet I_m` is the ribbon\n decomposition of `I` with respect to `J` (see\n :meth:`ribbon_decomposition`).\n\n INPUT:\n\n - ``other`` -- composition of same size as ``self``\n\n - ``check`` -- (default: ``True``) a Boolean determining whether\n to check the input compositions for having the same size\n\n OUTPUT:\n\n - the join of the compositions ``self`` and ``other``\n\n EXAMPLES::\n\n sage: Composition([3, 1, 1, 3, 1]).join([4, 3, 2])\n [3, 1, 1, 2, 1, 1]\n sage: Composition([9, 6]).join([1, 3, 6, 3, 2])\n [1, 3, 5, 1, 3, 2]\n sage: Composition([9, 6]).join([1, 3, 5, 1, 3, 2])\n [1, 3, 5, 1, 3, 2]\n sage: Composition([1, 1, 1, 1, 1]).join([3, 2])\n [1, 1, 1, 1, 1]\n sage: Composition([4, 2]).join([3, 3])\n [3, 1, 2]\n sage: Composition([]).join([])\n []\n\n Let us verify on small examples that the join\n of `I` and `J` refines both of `I` and `J`::\n\n sage: all( all( I.join(J).is_finer(I) and\n ....: I.join(J).is_finer(J)\n ....: for J in Compositions(4) )\n ....: for I in Compositions(4) )\n True\n\n and is the coarsest composition to do so::\n\n sage: all( all( all( K.is_finer(I.join(J))\n ....: for K in I.finer()\n ....: if K.is_finer(J) )\n ....: for J in Compositions(3) )\n ....: for I in Compositions(3) )\n True\n\n Let us check that the join of `I` and `J` is indeed the\n concatenation of `I_1, I_2, \\cdots , I_m`, where\n `I = I_1 \\bullet I_2 \\bullet \\ldots \\bullet I_m` is the ribbon\n decomposition of `I` with respect to `J`::\n\n sage: all( all( Composition.sum(I.ribbon_decomposition(J)[0])\n ....: == I.join(J) for J in Compositions(4) )\n ....: for I in Compositions(4) )\n True\n\n Also, the descent set of the join of `I` and `J` is the\n union of the descent sets of `I` and `J`::\n\n sage: all( all( I.to_subset().union(J.to_subset())\n ....: == I.join(J).to_subset()\n ....: for J in Compositions(4) )\n ....: for I in Compositions(4) )\n True\n\n TESTS::\n\n sage: Composition([3, 1, 1, 3, 1]).join([4, 3, 1])\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 1, 3, 1] is not the same size as [4, 3, 1]\n\n .. SEEALSO::\n\n :meth:`meet`, :meth:`ribbon_decomposition`\n\n AUTHORS:\n\n - Darij Grinberg (2013-09-05)\n ' if (check and (sum(self) != sum(other))): raise ValueError('{} is not the same size as {}'.format(self, other)) factors: list[int] = [] I_iter = iter(self) i = 0 for j in other: current_factor_size = 0 while True: if (i == 0): try: i = next(I_iter) except StopIteration: return Compositions()(factors) if ((current_factor_size + i) <= j): factors.append(i) current_factor_size += i i = 0 else: if (not (j == current_factor_size)): factors.append((j - current_factor_size)) i -= (j - current_factor_size) break return self.parent()(factors) sup = join def meet(self, other, check=True) -> Composition: '\n Return the meet of ``self`` with a composition ``other`` of the\n same size.\n\n The meet of two compositions `I` and `J` of size `n` is the\n finest composition of `n` which is coarser than each of `I` and\n `J`. It can be described as the composition whose descent set is\n the intersection of the descent sets of `I` and `J`.\n\n INPUT:\n\n - ``other`` -- composition of same size as ``self``\n\n - ``check`` -- (default: ``True``) a Boolean determining whether\n to check the input compositions for having the same size\n\n OUTPUT:\n\n - the meet of the compositions ``self`` and ``other``\n\n EXAMPLES::\n\n sage: Composition([3, 1, 1, 3, 1]).meet([4, 3, 2])\n [4, 5]\n sage: Composition([9, 6]).meet([1, 3, 6, 3, 2])\n [15]\n sage: Composition([9, 6]).meet([1, 3, 5, 1, 3, 2])\n [9, 6]\n sage: Composition([1, 1, 1, 1, 1]).meet([3, 2])\n [3, 2]\n sage: Composition([4, 2]).meet([3, 3])\n [6]\n sage: Composition([]).meet([])\n []\n sage: Composition([1]).meet([1])\n [1]\n\n Let us verify on small examples that the meet\n of `I` and `J` is coarser than both of `I` and `J`::\n\n sage: all( all( I.is_finer(I.meet(J)) and\n ....: J.is_finer(I.meet(J))\n ....: for J in Compositions(4) )\n ....: for I in Compositions(4) )\n True\n\n and is the finest composition to do so::\n\n sage: all( all( all( I.meet(J).is_finer(K)\n ....: for K in I.fatter()\n ....: if J.is_finer(K) )\n ....: for J in Compositions(3) )\n ....: for I in Compositions(3) )\n True\n\n The descent set of the meet of `I` and `J` is the\n intersection of the descent sets of `I` and `J`::\n\n sage: def test_meet(n):\n ....: return all( all( I.to_subset().intersection(J.to_subset())\n ....: == I.meet(J).to_subset()\n ....: for J in Compositions(n) )\n ....: for I in Compositions(n) )\n sage: all( test_meet(n) for n in range(1, 5) )\n True\n\n TESTS::\n\n sage: Composition([3, 1, 1, 3, 1]).meet([4, 3, 1])\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 1, 3, 1] is not the same size as [4, 3, 1]\n\n .. SEEALSO::\n\n :meth:`join`\n\n AUTHORS:\n\n - Darij Grinberg (2013-09-05)\n ' if (check and (sum(self) != sum(other))): raise ValueError('{} is not the same size as {}'.format(self, other)) factors = [] current_part = 0 I_iter = iter(self) i = 0 for j in other: current_factor_size = 0 while True: if (i == 0): try: i = next(I_iter) except StopIteration: factors.append(current_part) return Compositions()(factors) if ((current_factor_size + i) <= j): current_part += i current_factor_size += i i = 0 else: if (j == current_factor_size): factors.append(current_part) current_part = 0 else: i -= (j - current_factor_size) current_part += (j - current_factor_size) break return self.parent()(factors) inf = meet def finer(self): '\n Return the set of compositions which are finer than ``self``.\n\n EXAMPLES::\n\n sage: C = Composition([3,2]).finer()\n sage: C.cardinality()\n 8\n sage: C.list()\n [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 1, 1], [1, 2, 2], [2, 1, 1, 1], [2, 1, 2], [3, 1, 1], [3, 2]]\n\n sage: Composition([]).finer()\n {[]}\n ' if (not self): return FiniteEnumeratedSet([self]) else: return cartesian_product([Compositions(i) for i in self]).map(Composition.sum) def is_finer(self, co2) -> bool: '\n Return ``True`` if the composition ``self`` is finer than the\n composition ``co2``; otherwise, return ``False``.\n\n EXAMPLES::\n\n sage: Composition([4,1,2]).is_finer([3,1,3])\n False\n sage: Composition([3,1,3]).is_finer([4,1,2])\n False\n sage: Composition([1,2,2,1,1,2]).is_finer([5,1,3])\n True\n sage: Composition([2,2,2]).is_finer([4,2])\n True\n ' co1 = self if (sum(co1) != sum(co2)): raise ValueError(('compositions self (= %s) and co2 (= %s) must be of the same size' % (self, co2))) sum1 = 0 sum2 = 0 i1 = 0 for j2 in co2: sum2 += j2 while (sum1 < sum2): sum1 += co1[i1] i1 += 1 if (sum1 > sum2): return False return True def fatten(self, grouping) -> Composition: '\n Return the composition fatter than ``self``, obtained by grouping\n together consecutive parts according to ``grouping``.\n\n INPUT:\n\n - ``grouping`` -- a composition whose sum is the length of ``self``\n\n EXAMPLES:\n\n Let us start with the composition::\n\n sage: c = Composition([4,5,2,7,1])\n\n With ``grouping`` equal to `(1, \\ldots, 1)`, `c` is left unchanged::\n\n sage: c.fatten(Composition([1,1,1,1,1]))\n [4, 5, 2, 7, 1]\n\n With ``grouping`` equal to `(\\ell)` where `\\ell` is the length of\n `c`, this yields the coarsest composition above `c`::\n\n sage: c.fatten(Composition([5]))\n [19]\n\n Other values for ``grouping`` yield (all the) other compositions\n coarser than `c`::\n\n sage: c.fatten(Composition([2,1,2]))\n [9, 2, 8]\n sage: c.fatten(Composition([3,1,1]))\n [11, 7, 1]\n\n TESTS::\n\n sage: Composition([]).fatten(Composition([]))\n []\n sage: c.fatten(Composition([3,1,1])).__class__ == c.__class__\n True\n ' parent = self.parent() result = ([0] * len(grouping)) j = 0 for (i, gi) in enumerate(grouping): result[i] = sum(self[j:(j + gi)]) j += gi return parent(result) def fatter(self): '\n Return the set of compositions which are fatter than ``self``.\n\n Complexity for generation: `O(|c|)` memory, `O(|r|)` time where `|c|`\n is the size of ``self`` and `r` is the result.\n\n EXAMPLES::\n\n sage: C = Composition([4,5,2]).fatter()\n sage: C.cardinality()\n 4\n sage: list(C)\n [[4, 5, 2], [4, 7], [9, 2], [11]]\n\n Some extreme cases::\n\n sage: list(Composition([5]).fatter())\n [[5]]\n sage: list(Composition([]).fatter())\n [[]]\n sage: list(Composition([1,1,1,1]).fatter()) == list(Compositions(4))\n True\n ' return Compositions(len(self)).map(self.fatten) def refinement_splitting(self, J) -> list[Composition]: '\n Return the refinement splitting of ``self`` according to ``J``.\n\n INPUT:\n\n - ``J`` -- A composition such that ``self`` is finer than ``J``\n\n OUTPUT:\n\n - the unique list of compositions `(I^{(p)})_{p=1, \\ldots , m}`,\n obtained by splitting `I`, such that\n `|I^{(p)}| = J_p` for all `p = 1, \\ldots, m`.\n\n .. SEEALSO::\n\n :meth:`refinement_splitting_lengths`\n\n EXAMPLES::\n\n sage: Composition([1,2,2,1,1,2]).refinement_splitting([5,1,3])\n [[1, 2, 2], [1], [1, 2]]\n sage: Composition([]).refinement_splitting([])\n []\n sage: Composition([3]).refinement_splitting([2])\n Traceback (most recent call last):\n ...\n ValueError: compositions self (= [3]) and J (= [2]) must be of the same size\n sage: Composition([2,1]).refinement_splitting([1,2])\n Traceback (most recent call last):\n ...\n ValueError: composition J (= [2, 1]) does not refine self (= [1, 2])\n ' I = self if (sum(I) != sum(J)): raise ValueError(('compositions self (= %s) and J (= %s) must be of the same size' % (I, J))) sum1 = 0 sum2 = 0 i1 = (- 1) decomp = [] for j2 in J: new_comp = [] sum2 += j2 while (sum1 < sum2): i1 += 1 new_comp.append(I[i1]) sum1 += new_comp[(- 1)] if (sum1 > sum2): raise ValueError(('composition J (= %s) does not refine self (= %s)' % (I, J))) decomp.append(Compositions()(new_comp)) return decomp def refinement_splitting_lengths(self, J): '\n Return the lengths of the compositions in the refinement splitting of\n ``self`` according to ``J``.\n\n .. SEEALSO::\n\n :meth:`refinement_splitting` for the definition of refinement splitting\n\n EXAMPLES::\n\n sage: Composition([1,2,2,1,1,2]).refinement_splitting_lengths([5,1,3])\n [3, 1, 2]\n sage: Composition([]).refinement_splitting_lengths([])\n []\n sage: Composition([3]).refinement_splitting_lengths([2])\n Traceback (most recent call last):\n ...\n ValueError: compositions self (= [3]) and J (= [2]) must be of the same size\n sage: Composition([2,1]).refinement_splitting_lengths([1,2])\n Traceback (most recent call last):\n ...\n ValueError: composition J (= [2, 1]) does not refine self (= [1, 2])\n ' return Compositions()([len(p) for p in self.refinement_splitting(J)]) def major_index(self) -> int: '\n Return the major index of ``self``. The major index is\n defined as the sum of the descents.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).major_index()\n 31\n ' lv = len(self) if (lv == 1): return 0 return sum([((lv - (i + 1)) * ci) for (i, ci) in enumerate(self)]) def to_code(self) -> list: '\n Return the code of the composition ``self``.\n\n The code of a composition `I` is a list of length\n `\\mathrm{size}(I)` of 1s and 0s such that there is a 1\n wherever a new part starts. (Exceptional case: When the\n composition is empty, the code is ``[0]``.)\n\n EXAMPLES::\n\n sage: Composition([4,1,2,3,5]).to_code()\n [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n\n TESTS::\n\n sage: Composition([]).to_code()\n [0]\n ' if (not self): return [0] code = [] for i in self: code += ([1] + ([0] * (i - 1))) return code def partial_sums(self, final=True) -> list: '\n The partial sums of the sequence defined by the entries of the\n composition.\n\n If `I = (i_1, \\ldots, i_m)` is a composition, then the partial sums of\n the entries of the composition are\n `[i_1, i_1 + i_2, \\ldots, i_1 + i_2 + \\cdots + i_m]`.\n\n INPUT:\n\n - ``final`` -- (default: ``True``) whether or not to include the final\n partial sum, which is always the size of the composition.\n\n .. SEEALSO::\n\n :meth:`to_subset`\n\n EXAMPLES::\n\n sage: Composition([1,1,3,1,2,1,3]).partial_sums()\n [1, 2, 5, 6, 8, 9, 12]\n\n With ``final = False``, the last partial sum is not included::\n\n sage: Composition([1,1,3,1,2,1,3]).partial_sums(final=False)\n [1, 2, 5, 6, 8, 9]\n ' s = 0 partial_sums = [] for i in self: s += i partial_sums.append(s) if (final is False): partial_sums.pop() return partial_sums def to_subset(self, final=False): '\n The subset corresponding to ``self`` under the bijection (see below)\n between compositions of `n` and subsets of `\\{1, 2, \\ldots, n-1\\}`.\n\n The bijection maps a composition `(i_1, \\ldots, i_k)` of `n` to\n `\\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \\ldots, i_1 + \\cdots + i_{k-1}\\}`.\n\n INPUT:\n\n - ``final`` -- (default: ``False``) whether or not to include the final\n partial sum, which is always the size of the composition.\n\n .. SEEALSO::\n\n :meth:`partial_sums`\n\n EXAMPLES::\n\n sage: Composition([1,1,3,1,2,1,3]).to_subset()\n {1, 2, 5, 6, 8, 9}\n sage: for I in Compositions(3): print(I.to_subset())\n {1, 2}\n {1}\n {2}\n {}\n\n With ``final=True``, the sum of all the elements of the composition is\n included in the subset::\n\n sage: Composition([1,1,3,1,2,1,3]).to_subset(final=True)\n {1, 2, 5, 6, 8, 9, 12}\n\n TESTS:\n\n We verify that ``to_subset`` is indeed a bijection for compositions of\n size `n = 8`::\n\n sage: n = 8\n sage: all(Composition(from_subset=(S, n)).to_subset() == S\n ....: for S in Subsets(n-1))\n True\n sage: all(Composition(from_subset=(I.to_subset(), n)) == I\n ....: for I in Compositions(n))\n True\n ' from sage.sets.set import Set return Set(self.partial_sums(final=final)) def descents(self, final_descent=False) -> list: '\n This gives one fewer than the partial sums of the composition.\n\n This is here to maintain some sort of backward compatibility, even\n through the original implementation was broken (it gave the wrong\n answer). The same information can be found in :meth:`partial_sums`.\n\n .. SEEALSO::\n\n :meth:`partial_sums`\n\n INPUT:\n\n - ``final_descent`` -- (Default: ``False``) a boolean integer\n\n OUTPUT:\n\n - the list of partial sums of ``self`` with each part\n decremented by `1`. This includes the sum of all entries when\n ``final_descent`` is ``True``.\n\n EXAMPLES::\n\n sage: c = Composition([2,1,3,2])\n sage: c.descents()\n [1, 2, 5]\n sage: c.descents(final_descent=True)\n [1, 2, 5, 7]\n ' return [(i - 1) for i in self.partial_sums(final=final_descent)] def peaks(self) -> list: '\n Return a list of the peaks of the composition ``self``.\n\n The peaks of a composition are the descents which do not\n immediately follow another descent.\n\n EXAMPLES::\n\n sage: Composition([1, 1, 3, 1, 2, 1, 3]).peaks()\n [4, 7]\n ' descents = set(((d - 1) for d in self.to_subset(final=True))) return [(i + 1) for i in range(len(self)) if ((i not in descents) and ((i + 1) in descents))] @combinatorial_map(name='to partition') def to_partition(self): '\n Return the partition obtained by sorting ``self`` into decreasing\n order.\n\n EXAMPLES::\n\n sage: Composition([2,1,3]).to_partition() # needs sage.combinat\n [3, 2, 1]\n sage: Composition([4,2,2]).to_partition() # needs sage.combinat\n [4, 2, 2]\n sage: Composition([]).to_partition() # needs sage.combinat\n []\n ' from sage.combinat.partition import Partition return Partition(sorted(self, reverse=True)) def to_skew_partition(self, overlap=1): '\n Return the skew partition obtained from ``self``.\n\n This is a skew partition whose rows have the entries of\n ``self`` as their length, taken in reverse order (so the first\n entry of ``self`` is the length of the lowermost row,\n etc.). The parameter ``overlap`` indicates the number of cells\n on each row that are directly below cells of the previous\n row. When it is set to `1` (its default value), the result is\n the ribbon shape of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: Composition([3,4,1]).to_skew_partition()\n [6, 6, 3] / [5, 2]\n sage: Composition([3,4,1]).to_skew_partition(overlap=0)\n [8, 7, 3] / [7, 3]\n sage: Composition([]).to_skew_partition()\n [] / []\n sage: Composition([1,2]).to_skew_partition()\n [2, 1] / []\n sage: Composition([2,1]).to_skew_partition()\n [2, 2] / [1]\n ' from sage.combinat.skew_partition import SkewPartition outer = [] inner = [] sum_outer = (- overlap) for k in self[:(- 1)]: outer.append(((k + sum_outer) + overlap)) sum_outer += (k - overlap) inner.append((sum_outer + overlap)) if self: outer.append(((self[(- 1)] + sum_outer) + overlap)) else: return SkewPartition([[], []]) return SkewPartition([[x for x in reversed(outer) if (x != 0)], [x for x in reversed(inner) if (x != 0)]]) def shuffle_product(self, other, overlap=False): '\n The (overlapping) shuffles of ``self`` and ``other``.\n\n Suppose `I = (i_1, \\ldots, i_k)` and `J = (j_1, \\ldots, j_l)` are two\n compositions. A *shuffle* of `I` and `J` is a composition of length\n `k + l` that contains both `I` and `J` as subsequences.\n\n More generally, an *overlapping shuffle* of `I` and `J` is obtained by\n distributing the elements of `I` and `J` (preserving the relative\n ordering of these elements) among the positions of an empty list; an\n element of `I` and an element of `J` are permitted to share the same\n position, in which case they are replaced by their sum. In particular,\n a shuffle of `I` and `J` is an overlapping shuffle of `I` and `J`.\n\n INPUT:\n\n - ``other`` -- composition\n\n - ``overlap`` -- boolean (default: ``False``); if ``True``, the\n overlapping shuffle product is returned.\n\n OUTPUT:\n\n An enumerated set (allowing for multiplicities)\n\n EXAMPLES:\n\n The shuffle product of `[2,2]` and `[1,1,3]`::\n\n sage: alph = Composition([2,2])\n sage: beta = Composition([1,1,3])\n sage: S = alph.shuffle_product(beta); S # needs sage.combinat\n Shuffle product of [2, 2] and [1, 1, 3]\n sage: S.list() # needs sage.combinat\n [[2, 2, 1, 1, 3], [2, 1, 2, 1, 3], [2, 1, 1, 2, 3], [2, 1, 1, 3, 2],\n [1, 2, 2, 1, 3], [1, 2, 1, 2, 3], [1, 2, 1, 3, 2], [1, 1, 2, 2, 3],\n [1, 1, 2, 3, 2], [1, 1, 3, 2, 2]]\n\n The *overlapping* shuffle product of `[2,2]` and `[1,1,3]`::\n\n sage: alph = Composition([2,2])\n sage: beta = Composition([1,1,3])\n sage: O = alph.shuffle_product(beta, overlap=True); O # needs sage.combinat\n Overlapping shuffle product of [2, 2] and [1, 1, 3]\n sage: O.list() # needs sage.combinat\n [[2, 2, 1, 1, 3], [2, 1, 2, 1, 3], [2, 1, 1, 2, 3], [2, 1, 1, 3, 2],\n [1, 2, 2, 1, 3], [1, 2, 1, 2, 3], [1, 2, 1, 3, 2], [1, 1, 2, 2, 3],\n [1, 1, 2, 3, 2], [1, 1, 3, 2, 2],\n [3, 2, 1, 3], [2, 3, 1, 3], [3, 1, 2, 3], [2, 1, 3, 3], [3, 1, 3, 2],\n [2, 1, 1, 5], [1, 3, 2, 3], [1, 2, 3, 3], [1, 3, 3, 2], [1, 2, 1, 5],\n [1, 1, 5, 2], [1, 1, 2, 5],\n [3, 3, 3], [3, 1, 5], [1, 3, 5]]\n\n Note that the shuffle product of two compositions can include the same\n composition more than once since a composition can be a shuffle of two\n compositions in several ways. For example::\n\n sage: # needs sage.combinat\n sage: w1 = Composition([1])\n sage: S = w1.shuffle_product(w1); S\n Shuffle product of [1] and [1]\n sage: S.list()\n [[1, 1], [1, 1]]\n sage: O = w1.shuffle_product(w1, overlap=True); O\n Overlapping shuffle product of [1] and [1]\n sage: O.list()\n [[1, 1], [1, 1], [2]]\n\n TESTS::\n\n sage: empty = Composition([])\n sage: empty.shuffle_product(empty).list() # needs sage.combinat\n [[]]\n ' if overlap: from sage.combinat.shuffle import ShuffleProduct_overlapping return ShuffleProduct_overlapping(self, other, Compositions()) else: from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2 return ShuffleProduct_w1w2(self, other) def wll_gt(self, co2) -> bool: '\n Return ``True`` if the composition ``self`` is greater than the\n composition ``co2`` with respect to the wll-ordering; otherwise,\n return ``False``.\n\n The wll-ordering is a total order on the set of all compositions\n defined as follows: A composition `I` is greater than a\n composition `J` if and only if one of the following conditions\n holds:\n\n - The size of `I` is greater than the size of `J`.\n\n - The size of `I` equals the size of `J`, but the length of `I`\n is greater than the length of `J`.\n\n - The size of `I` equals the size of `J`, and the length of `I`\n equals the length of `J`, but `I` is lexicographically\n greater than `J`.\n\n ("wll-ordering" is short for "weight, length, lexicographic\n ordering".)\n\n EXAMPLES::\n\n sage: Composition([4,1,2]).wll_gt([3,1,3])\n True\n sage: Composition([7]).wll_gt([4,1,2])\n False\n sage: Composition([8]).wll_gt([4,1,2])\n True\n sage: Composition([3,2,2,2]).wll_gt([5,2])\n True\n sage: Composition([]).wll_gt([3])\n False\n sage: Composition([2,1]).wll_gt([2,1])\n False\n sage: Composition([2,2,2]).wll_gt([4,2])\n True\n sage: Composition([4,2]).wll_gt([2,2,2])\n False\n sage: Composition([1,1,2]).wll_gt([2,2])\n True\n sage: Composition([2,2]).wll_gt([1,3])\n True\n sage: Composition([2,1,2]).wll_gt([])\n True\n ' co1 = self if (sum(co1) > sum(co2)): return True elif (sum(co1) < sum(co2)): return False if (len(co1) > len(co2)): return True if (len(co1) < len(co2)): return False for i in range(len(co1)): if (co1[i] > co2[i]): return True elif (co1[i] < co2[i]): return False return False def count(self, n): '\n Return the number of parts of size ``n``.\n\n EXAMPLES::\n\n sage: C = Composition([3,2,3])\n sage: C.count(3)\n 2\n sage: C.count(2)\n 1\n sage: C.count(1)\n 0\n ' return sum(((i == n) for i in self)) def specht_module(self, base_ring=None): '\n Return the Specht module corresponding to ``self``.\n\n EXAMPLES::\n\n sage: SM = Composition([1,2,2]).specht_module(QQ); SM # needs sage.combinat sage.modules\n Specht module of [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)] over Rational Field\n sage: s = SymmetricFunctions(QQ).s() # needs sage.combinat sage.modules\n sage: s(SM.frobenius_image()) # needs sage.combinat 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)) cells = [] for (i, row) in enumerate(self): for j in range(row): cells.append((i, j)) return SpechtModule(R, cells) def specht_module_dimension(self, base_ring=None): '\n Return the dimension of the Specht module corresponding to ``self``.\n\n INPUT:\n\n - ``base_ring`` -- (default: `\\QQ`) the base ring\n\n EXAMPLES::\n\n sage: Composition([1,2,2]).specht_module_dimension() # needs sage.combinat sage.modules\n 5\n sage: Composition([1,2,2]).specht_module_dimension(GF(2)) # needs sage.combinat sage.modules sage.rings.finite_rings\n 5\n ' from sage.combinat.specht_module import specht_module_rank return specht_module_rank(self, base_ring)
class Compositions(UniqueRepresentation, Parent): "\n Set of integer compositions.\n\n A composition `c` of a nonnegative integer `n` is a list of\n positive integers with total sum `n`.\n\n .. SEEALSO::\n\n - :class:`Composition`\n - :class:`Partitions`\n - :class:`IntegerVectors`\n\n EXAMPLES:\n\n There are 8 compositions of 4::\n\n sage: Compositions(4).cardinality()\n 8\n\n Here is the list of them::\n\n sage: Compositions(4).list()\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]\n\n You can use the ``.first()`` method to get the 'first' composition of\n a number::\n\n sage: Compositions(4).first()\n [1, 1, 1, 1]\n\n You can also calculate the 'next' composition given the current\n one::\n\n sage: Compositions(4).next([1,1,2])\n [1, 2, 1]\n\n If `n` is not specified, this returns the combinatorial class of\n all (non-negative) integer compositions::\n\n sage: Compositions()\n Compositions of non-negative integers\n sage: [] in Compositions()\n True\n sage: [2,3,1] in Compositions()\n True\n sage: [-2,3,1] in Compositions()\n False\n\n If `n` is specified, it returns the class of compositions of `n`::\n\n sage: Compositions(3)\n Compositions of 3\n sage: list(Compositions(3))\n [[1, 1, 1], [1, 2], [2, 1], [3]]\n sage: Compositions(3).cardinality()\n 4\n\n The following examples show how to test whether or not an object\n is a composition::\n\n sage: [3,4] in Compositions()\n True\n sage: [3,4] in Compositions(7)\n True\n sage: [3,4] in Compositions(5)\n False\n\n Similarly, one can check whether or not an object is a composition\n which satisfies further constraints::\n\n sage: [4,2] in Compositions(6, inner=[2,2])\n True\n sage: [4,2] in Compositions(6, inner=[2,3])\n False\n sage: [4,1] in Compositions(5, inner=[2,1], max_slope = 0)\n True\n\n An example with incompatible constraints::\n\n sage: [4,2] in Compositions(6, inner=[2,2], min_part=3)\n False\n\n The options ``length``, ``min_length``, and ``max_length`` can be used\n to set length constraints on the compositions. For example, the\n compositions of 4 of length equal to, at least, and at most 2 are\n given by::\n\n sage: Compositions(4, length=2).list()\n [[3, 1], [2, 2], [1, 3]]\n sage: Compositions(4, min_length=2).list()\n [[3, 1], [2, 2], [2, 1, 1], [1, 3], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(4, max_length=2).list()\n [[4], [3, 1], [2, 2], [1, 3]]\n\n Setting both ``min_length`` and ``max_length`` to the same value is\n equivalent to setting ``length`` to this value::\n\n sage: Compositions(4, min_length=2, max_length=2).list()\n [[3, 1], [2, 2], [1, 3]]\n\n The options ``inner`` and ``outer`` can be used to set part-by-part\n containment constraints. The list of compositions of 4 bounded\n above by ``[3,1,2]`` is given by::\n\n sage: list(Compositions(4, outer=[3,1,2]))\n [[3, 1], [2, 1, 1], [1, 1, 2]]\n\n ``outer`` sets ``max_length`` to the length of its argument. Moreover, the\n parts of ``outer`` may be infinite to clear the constraint on specific\n parts. This is the list of compositions of 4 of length at most 3\n such that the first and third parts are at most 1::\n\n sage: Compositions(4, outer=[1,oo,1]).list()\n [[1, 3], [1, 2, 1]]\n\n This is the list of compositions of 4 bounded below by ``[1,1,1]``::\n\n sage: Compositions(4, inner=[1,1,1]).list()\n [[2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n\n The options ``min_slope`` and ``max_slope`` can be used to set constraints\n on the slope, that is the difference ``p[i+1]-p[i]`` of two\n consecutive parts. The following is the list of weakly increasing\n compositions of 4::\n\n sage: Compositions(4, min_slope=0).list()\n [[4], [2, 2], [1, 3], [1, 1, 2], [1, 1, 1, 1]]\n\n Here are the weakly decreasing ones::\n\n sage: Compositions(4, max_slope=0).list()\n [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n\n The following is the list of compositions of 4 such that two\n consecutive parts differ by at most one::\n\n sage: Compositions(4, min_slope=-1, max_slope=1).list()\n [[4], [2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n\n The constraints can be combined together in all reasonable ways.\n This is the list of compositions of 5 of length between 2 and 4\n such that the difference between consecutive parts is between -2\n and 1::\n\n sage: Compositions(5, max_slope=1, min_slope=-2, min_length=2, max_length=4).list()\n [[3, 2], [3, 1, 1], [2, 3], [2, 2, 1], [2, 1, 2], [2, 1, 1, 1], [1, 2, 2], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2]]\n\n We can do the same thing with an outer constraint::\n\n sage: Compositions(5, max_slope=1, min_slope=-2, min_length=2, max_length=4, outer=[2,5,2]).list()\n [[2, 3], [2, 2, 1], [2, 1, 2], [1, 2, 2]]\n\n However, providing incoherent constraints may yield strange\n results. It is up to the user to ensure that the inner and outer\n compositions themselves satisfy the parts and slope constraints.\n\n Note that setting ``min_part=0`` is not allowed::\n\n sage: Compositions(2, length=3, min_part=0)\n Traceback (most recent call last):\n ...\n ValueError: setting min_part=0 is not allowed for Compositions\n\n Instead you must use ``IntegerVectors``::\n\n sage: list(IntegerVectors(2, 3))\n [[2, 0, 0], [1, 1, 0], [1, 0, 1], [0, 2, 0], [0, 1, 1], [0, 0, 2]]\n\n The generation algorithm is constant amortized time, and handled\n by the generic tool :class:`IntegerListsLex`.\n\n TESTS::\n\n sage: C = Compositions(4, length=2)\n sage: C == loads(dumps(C))\n True\n\n sage: Compositions(6, min_part=2, length=3)\n Compositions of the integer 6 satisfying constraints length=3, min_part=2\n\n sage: [2, 1] in Compositions(3, length=2)\n True\n sage: [2,1,2] in Compositions(5, min_part=1)\n True\n sage: [2,1,2] in Compositions(5, min_part=2)\n False\n\n sage: Compositions(4, length=2).cardinality()\n 3\n sage: Compositions(4, min_length=2).cardinality()\n 7\n sage: Compositions(4, max_length=2).cardinality()\n 4\n sage: Compositions(4, max_part=2).cardinality()\n 5\n sage: Compositions(4, min_part=2).cardinality()\n 2\n sage: Compositions(4, outer=[3,1,2]).cardinality()\n 3\n\n sage: Compositions(4, length=2).list()\n [[3, 1], [2, 2], [1, 3]]\n sage: Compositions(4, min_length=2).list()\n [[3, 1], [2, 2], [2, 1, 1], [1, 3], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(4, max_length=2).list()\n [[4], [3, 1], [2, 2], [1, 3]]\n sage: Compositions(4, max_part=2).list()\n [[2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(4, min_part=2).list()\n [[4], [2, 2]]\n sage: Compositions(4, outer=[3,1,2]).list()\n [[3, 1], [2, 1, 1], [1, 1, 2]]\n sage: Compositions(3, outer = Composition([3,2])).list()\n [[3], [2, 1], [1, 2]]\n sage: Compositions(4, outer=[1,oo,1]).list()\n [[1, 3], [1, 2, 1]]\n sage: Compositions(4, inner=[1,1,1]).list()\n [[2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(4, inner=Composition([1,2])).list()\n [[2, 2], [1, 3], [1, 2, 1]]\n sage: Compositions(4, min_slope=0).list()\n [[4], [2, 2], [1, 3], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(4, min_slope=-1, max_slope=1).list()\n [[4], [2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n sage: Compositions(5, max_slope=1, min_slope=-2, min_length=2, max_length=4).list()\n [[3, 2], [3, 1, 1], [2, 3], [2, 2, 1], [2, 1, 2], [2, 1, 1, 1], [1, 2, 2], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2]]\n sage: Compositions(5, max_slope=1, min_slope=-2, min_length=2, max_length=4, outer=[2,5,2]).list()\n [[2, 3], [2, 2, 1], [2, 1, 2], [1, 2, 2]]\n " @staticmethod def __classcall_private__(self, n=None, **kwargs): '\n Return the correct parent based upon the input.\n\n EXAMPLES::\n\n sage: C = Compositions(3)\n sage: C2 = Compositions(int(3))\n sage: C is C2\n True\n ' if (n is None): if kwargs: raise ValueError('incorrect number of arguments') return Compositions_all() elif (not kwargs): if isinstance(n, (int, Integer)): return Compositions_n(n) else: raise ValueError('n must be an integer') else: txt = 'Compositions of the integer %s satisfying constraints %s' kwargs['name'] = (txt % (n, ', '.join((f'{key}={kwargs[key]}' for key in sorted(kwargs))))) kwargs['element_class'] = Composition if ('min_part' not in kwargs): kwargs['min_part'] = 1 elif (kwargs['min_part'] == 0): raise ValueError('setting min_part=0 is not allowed for Compositions') if ('outer' in kwargs): kwargs['ceiling'] = list(kwargs['outer']) if ('max_length' in kwargs): kwargs['max_length'] = min(len(kwargs['outer']), kwargs['max_length']) else: kwargs['max_length'] = len(kwargs['outer']) del kwargs['outer'] if ('inner' in kwargs): inner = list(kwargs['inner']) kwargs['floor'] = inner del kwargs['inner'] if ('min_length' in kwargs): kwargs['min_length'] = max(len(inner), kwargs['min_length']) else: kwargs['min_length'] = len(inner) return IntegerListsLex(n, **kwargs) def __init__(self, is_infinite=False, category=None): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: C = Compositions()\n sage: TestSuite(C).run()\n ' if (category is None): category = EnumeratedSets() if is_infinite: Parent.__init__(self, category=category.Infinite()) else: Parent.__init__(self, category=category.Finite()) Element = Composition def _element_constructor_(self, lst) -> Composition: '\n Construct an element with ``self`` as parent.\n\n EXAMPLES::\n\n sage: P = Compositions()\n sage: P([3,3,1]) # indirect doctest\n [3, 3, 1]\n ' if isinstance(lst, Composition): lst = list(lst) elt = self.element_class(self, lst) if (elt not in self): raise ValueError(('%s not in %s' % (elt, self))) return elt def __contains__(self, x) -> bool: '\n TESTS::\n\n sage: [2,1,3] in Compositions()\n True\n sage: [] in Compositions()\n True\n sage: [-2,-1] in Compositions()\n False\n sage: [0,0] in Compositions()\n True\n ' if isinstance(x, Composition): return True elif isinstance(x, list): for i in x: if ((not isinstance(i, (int, Integer))) and (i not in ZZ)): return False if (i < 0): return False return True else: return False def from_descents(self, descents, nps=None) -> Composition: '\n Return a composition from the list of descents.\n\n INPUT:\n\n - ``descents`` -- an iterable\n\n - ``nps`` -- (default: ``None``) an integer or ``None``\n\n OUTPUT:\n\n - The composition of ``nps`` whose descents are listed in\n ``descents``, assuming that ``nps`` is not ``None`` (otherwise,\n the last element of ``descents`` is removed from ``descents``, and\n ``nps`` is set to be this last element plus 1).\n\n EXAMPLES::\n\n sage: [x-1 for x in Composition([1, 1, 3, 4, 3]).to_subset()]\n [0, 1, 4, 8]\n sage: Compositions().from_descents([1,0,4,8],12)\n [1, 1, 3, 4, 3]\n sage: Compositions().from_descents([1,0,4,8,11])\n [1, 1, 3, 4, 3]\n ' d = [(x + 1) for x in sorted(descents)] if (nps is None): nps = d.pop() return self.from_subset(d, nps) def from_subset(self, S, n) -> Composition: '\n The composition of `n` corresponding to the subset ``S`` of\n `\\{1, 2, \\ldots, n-1\\}` under the bijection that maps the composition\n `(i_1, i_2, \\ldots, i_k)` of `n` to the subset\n `\\{i_1, i_1 + i_2, i_1 + i_2 + i_3, \\ldots, i_1 + \\cdots + i_{k-1}\\}`\n (see :meth:`Composition.to_subset`).\n\n INPUT:\n\n - ``S`` -- an iterable, a subset of `\\{1, 2, \\ldots, n-1\\}`\n\n - ``n`` -- an integer\n\n EXAMPLES::\n\n sage: Compositions().from_subset([2,1,5,9], 12)\n [1, 1, 3, 4, 3]\n sage: Compositions().from_subset({2,1,5,9}, 12)\n [1, 1, 3, 4, 3]\n\n sage: Compositions().from_subset([], 12)\n [12]\n sage: Compositions().from_subset([], 0)\n []\n\n TESTS::\n\n sage: Compositions().from_subset([2,1,5,9],9)\n Traceback (most recent call last):\n ...\n ValueError: S (=[1, 2, 5, 9]) is not a subset of {1, ..., 8}\n ' d = sorted(S) if (not d): if (n == 0): return self.element_class(self, []) else: return self.element_class(self, [n]) if (n <= d[(- 1)]): raise ValueError(('S (=%s) is not a subset of {1, ..., %s}' % (d, (n - 1)))) else: d.append(n) co = [d[0]] for i in range((len(d) - 1)): co.append((d[(i + 1)] - d[i])) return self.element_class(self, co) def from_code(self, code) -> Composition: '\n Return the composition from its code. The code of a composition\n `I` is a list of length `\\mathrm{size}(I)` consisting of 1s and\n 0s such that there is a 1 wherever a new part starts.\n (Exceptional case: When the composition is empty, the code is\n ``[0]``.)\n\n EXAMPLES::\n\n sage: Composition([4,1,2,3,5]).to_code()\n [1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n sage: Compositions().from_code(_)\n [4, 1, 2, 3, 5]\n sage: Composition([3,1,2,3,5]).to_code()\n [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]\n sage: Compositions().from_code(_)\n [3, 1, 2, 3, 5]\n ' if (code == [0]): return self.element_class(self, []) L = [x for x in range(len(code)) if (code[x] == 1)] c = ([(L[i] - L[(i - 1)]) for i in range(1, len(L))] + [(len(code) - L[(- 1)])]) return self.element_class(self, c)
class Compositions_constraints(IntegerListsLex): def __setstate__(self, data): "\n TESTS::\n\n # This is the unpickling sequence for Compositions(4, max_part=2) in sage <= 4.1.1\n sage: pg_Compositions_constraints = unpickle_global('sage.combinat.composition', 'Compositions_constraints')\n sage: si = unpickle_newobj(pg_Compositions_constraints, ())\n sage: pg_make_integer = unpickle_global('sage.rings.integer', 'make_integer')\n sage: unpickle_build(si, {'constraints':{'max_part':pg_make_integer('2')}, 'n':pg_make_integer('4')})\n sage: si\n Integer lists of sum 4 satisfying certain constraints\n sage: si.list()\n [[2, 2], [2, 1, 1], [1, 2, 1], [1, 1, 2], [1, 1, 1, 1]]\n " n = data['n'] self.__class__ = IntegerListsLex constraints = {'min_part': 1, 'element_class': Composition} constraints.update(data['constraints']) self.__init__(n, **constraints)
class Compositions_all(Compositions): '\n Class of all compositions.\n ' def __init__(self): '\n Initialize ``self``.\n\n TESTS::\n\n sage: C = Compositions()\n sage: TestSuite(C).run()\n ' cat = AdditiveMonoids() Compositions.__init__(self, True, category=cat) def _repr_(self) -> str: "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: repr(Compositions())\n 'Compositions of non-negative integers'\n " return 'Compositions of non-negative integers' def subset(self, size=None): '\n Return the set of compositions of the given size.\n\n EXAMPLES::\n\n sage: C = Compositions()\n sage: C.subset(4)\n Compositions of 4\n sage: C.subset(size=3)\n Compositions of 3\n ' if (size is None): return self return Compositions(size) def zero(self): '\n Return the zero of the additive monoid.\n\n This is the empty composition.\n\n EXAMPLES::\n\n sage: C = Compositions()\n sage: C.zero()\n []\n ' return Composition([]) def _an_element_(self): '\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: C = Compositions()\n sage: C.an_element()\n []\n ' return self.zero() def __iter__(self): '\n Iterate over all compositions.\n\n TESTS::\n\n sage: C = Compositions()\n sage: it = C.__iter__()\n sage: [next(it) for i in range(10)]\n [[], [1], [1, 1], [2], [1, 1, 1], [1, 2], [2, 1], [3], [1, 1, 1, 1], [1, 1, 2]]\n ' n = 0 while True: for c in Compositions(n): (yield self.element_class(self, list(c))) n += 1
class Compositions_n(Compositions): '\n Class of compositions of a fixed `n`.\n ' @staticmethod def __classcall_private__(cls, n): '\n Standardize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: C = Compositions(5)\n sage: C2 = Compositions(int(5))\n sage: C3 = Compositions(ZZ(5))\n sage: C is C2\n True\n sage: C is C3\n True\n ' return super().__classcall__(cls, Integer(n)) def __init__(self, n): '\n TESTS::\n\n sage: C = Compositions(3)\n sage: C == loads(dumps(C))\n True\n sage: TestSuite(C).run()\n ' self.n = n Compositions.__init__(self, False) def _repr_(self) -> str: "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: repr(Compositions(3))\n 'Compositions of 3'\n " return ('Compositions of %s' % self.n) def __contains__(self, x) -> bool: '\n TESTS::\n\n sage: [2,1,3] in Compositions(6)\n True\n sage: [2,1,2] in Compositions(6)\n False\n sage: [] in Compositions(0)\n True\n sage: [0] in Compositions(0)\n True\n ' return ((x in Compositions()) and (sum(x) == self.n)) def cardinality(self) -> Integer: '\n Return the number of compositions of `n`.\n\n TESTS::\n\n sage: Compositions(3).cardinality()\n 4\n sage: Compositions(0).cardinality()\n 1\n ' if (self.n >= 1): return (ZZ(2) ** (self.n - 1)) elif (self.n == 0): return ZZ.one() else: return ZZ.zero() def random_element(self) -> Composition: '\n Return a random ``Composition`` with uniform probability.\n\n This method generates a random binary word starting with a 1\n and then uses the bijection between compositions and their code.\n\n EXAMPLES::\n\n sage: Compositions(5).random_element() # random\n [2, 1, 1, 1]\n sage: Compositions(0).random_element()\n []\n sage: Compositions(1).random_element()\n [1]\n\n TESTS::\n\n sage: all(Compositions(10).random_element() in Compositions(10) for i in range(20))\n True\n ' from sage.misc.prandom import choice if (self.n == 0): return Compositions()([]) return Compositions().from_code(([1] + [choice([0, 1]) for _ in range((self.n - 1))])) def __iter__(self): '\n Iterate over the compositions of `n`.\n\n TESTS::\n\n sage: Compositions(4).list()\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]\n sage: Compositions(0).list()\n [[]]\n ' for c in composition_iterator_fast(self.n): (yield self.element_class(self, c))
def composition_iterator_fast(n): "\n Iterator over compositions of ``n`` yielded as lists.\n\n TESTS::\n\n sage: from sage.combinat.composition import composition_iterator_fast\n sage: L = list(composition_iterator_fast(4)); L\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]\n sage: type(L[0])\n <class 'list'>\n " if (n < 0): return if (n == 0): (yield []) return s = Integer(0) cur = [Integer(0)] while cur: cur[(- 1)] += 1 s += 1 if (s == n): (yield list(cur)) s -= cur.pop() else: cur.append(Integer(0))
class SignedCompositions(Compositions_n): '\n The class of signed compositions of `n`.\n\n EXAMPLES::\n\n sage: SC3 = SignedCompositions(3); SC3\n Signed compositions of 3\n sage: SC3.cardinality()\n 18\n sage: len(SC3.list())\n 18\n sage: SC3.first()\n [1, 1, 1]\n sage: SC3.last()\n [-3]\n sage: SC3.random_element() # random\n [1, -1, 1]\n sage: SC3.list()\n [[1, 1, 1],\n [1, 1, -1],\n [1, -1, 1],\n [1, -1, -1],\n [-1, 1, 1],\n [-1, 1, -1],\n [-1, -1, 1],\n [-1, -1, -1],\n [1, 2],\n [1, -2],\n [-1, 2],\n [-1, -2],\n [2, 1],\n [2, -1],\n [-2, 1],\n [-2, -1],\n [3],\n [-3]]\n\n TESTS::\n\n sage: SC = SignedCompositions(3)\n sage: TestSuite(SC).run()\n ' def __repr__(self): '\n TESTS::\n\n sage: SignedCompositions(3)\n Signed compositions of 3\n ' return ('Signed compositions of %s' % self.n) def __contains__(self, x): '\n TESTS::\n\n sage: [] in SignedCompositions(0)\n True\n sage: [0] in SignedCompositions(0)\n False\n sage: [2,1,3] in SignedCompositions(6)\n True\n sage: [-2, 1, -3] in SignedCompositions(6)\n True\n ' if isinstance(x, list): for z in x: if ((not isinstance(z, (int, Integer))) and (z not in ZZ)): return False if (z == 0): return False elif (not isinstance(x, Composition)): return False return (sum((abs(i) for i in x)) == self.n) def cardinality(self): '\n Return the number of elements in ``self``.\n\n The number of signed compositions of `n` is equal to\n\n .. MATH::\n\n \\sum_{i=1}^{n+1} \\binom{n-1}{i-1} 2^i\n\n EXAMPLES::\n\n sage: SC4 = SignedCompositions(4)\n sage: SC4.cardinality() == len(SC4.list())\n True\n sage: SignedCompositions(3).cardinality()\n 18\n ' return ZZ.sum(((binomial((self.n - 1), (i - 1)) * (2 ** i)) for i in range(1, (self.n + 1)))) def __iter__(self): '\n TESTS::\n\n sage: SignedCompositions(0).list() #indirect doctest\n [[]]\n sage: SignedCompositions(1).list() #indirect doctest\n [[1], [-1]]\n sage: SignedCompositions(2).list() #indirect doctest\n [[1, 1], [1, -1], [-1, 1], [-1, -1], [2], [-2]]\n ' for comp in Compositions_n.__iter__(self): l = len(comp) for sign in itertools.product([1, (- 1)], repeat=l): (yield [(sign[i] * comp[i]) for i in range(l)])
class CompositionTableau(CombinatorialElement, metaclass=ClasscallMetaclass): '\n A composition tableau.\n\n A *composition tableau* `t` of shape `I = (I_1, \\ldots, I_{\\ell})` is an\n array of boxes in rows, `I_i` boxes in row `i`, filled with positive\n integers such that:\n\n 1) the entries in the rows of `t` weakly decrease from left to right,\n 2) the left-most column of `t` strictly increase from top to bottom.\n 3) Add zero entries to the rows of `t` until the resulting array is\n rectangular of shape `\\ell \\times m`. For `1 \\leq i < j \\leq \\ell,\n 2 \\leq k \\leq m` and `(t(j,k) \\neq 0`, and also if `t(j,k) \\geq t(i,k))`\n implies `t(j,k) > t(i,k-1).`\n\n INPUT:\n\n - ``t`` -- A list of lists\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[2,2]])\n [[1], [2, 2]]\n sage: CompositionTableau([[1],[3,2],[4,4]])\n [[1], [3, 2], [4, 4]]\n sage: CompositionTableau([])\n []\n ' @staticmethod def __classcall_private__(self, t): '\n This ensures that a composition tableau is only ever constructed as\n an ``element_class`` call of an appropriate parent.\n\n TESTS::\n\n sage: t = CompositionTableau([[1],[2,2]])\n sage: TestSuite(t).run()\n\n sage: t.parent()\n Composition Tableaux\n sage: t.category()\n Category of elements of Composition Tableaux\n ' if isinstance(t, CompositionTableau): return t return CompositionTableaux_all().element_class(CompositionTableaux_all(), t) def __init__(self, parent, t): '\n Initialize a composition tableau.\n\n TESTS::\n\n sage: t = CompositionTableaux()([[1],[2,2]])\n sage: s = CompositionTableaux(3)([[1],[2,2]])\n sage: s == t\n True\n sage: t.parent()\n Composition Tableaux\n sage: s.parent()\n Composition Tableaux of size 3 and maximum entry 3\n sage: r = CompositionTableaux()(s)\n sage: r.parent()\n Composition Tableaux\n ' if isinstance(t, CompositionTableau): CombinatorialElement.__init__(self, parent, t._list) return if (not all((isinstance(row, list) for row in t))): raise ValueError('a composition tableau must be a list of lists') if any(((not r) for r in t)): raise ValueError('a composition tableau must be a list of non-empty lists') for row in t: if any(((row[i] < row[(i + 1)]) for i in range((len(row) - 1)))): raise ValueError('rows must weakly decrease from left to right') first_col = [row[0] for row in t if (t != [[]])] if any(((first_col[i] >= first_col[(i + 1)]) for i in range((len(t) - 1)))): raise ValueError('leftmost column must strictly increase from top to bottom') l = len(t) m = max((len(r) for r in t), default=0) TT = [(row + ([0] * (m - len(row)))) for row in t] for i in range(l): for j in range((i + 1), l): for k in range(1, m): if (TT[j][k] and (TT[i][k] <= TT[j][k] <= TT[i][(k - 1)])): raise ValueError('triple condition must be satisfied') CombinatorialElement.__init__(self, parent, t) def _repr_diagram(self) -> str: '\n Return a string representation of ``self`` as an array.\n\n EXAMPLES::\n\n sage: t = CompositionTableau([[1],[3,2],[4,4]])\n sage: print(t._repr_diagram())\n 1\n 3 2\n 4 4\n ' return '\n'.join((''.join((('%3s' % str(x)) for x in row)) for row in self)) def __call__(self, *cell): '\n Return the value in the corresponding cell of ``self``.\n\n EXAMPLES::\n\n sage: t = CompositionTableau([[1],[3,2],[4,4]])\n sage: t(1,1)\n 2\n sage: t(2,0)\n 4\n sage: t(2,2)\n Traceback (most recent call last):\n ...\n IndexError: the cell (2,2) is not contained in [[1], [3, 2], [4, 4]]\n ' try: (i, j) = cell except ValueError: (i, j) = cell[0] try: return self[i][j] except IndexError: raise IndexError(('the cell (%d,%d) is not contained in %s' % (i, j, self))) def pp(self): '\n Return a pretty print string of ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[3,2],[4,4]]).pp()\n 1\n 3 2\n 4 4\n ' print(self._repr_diagram()) def size(self): '\n Return the number of boxes in ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[3,2],[4,4]]).size()\n 5\n ' return sum((len(row) for row in self)) def weight(self): '\n Return a composition where entry `i` is the number of times that `i` appears in\n ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[3,2],[4,4]]).weight()\n [1, 1, 1, 2, 0]\n ' w = {i: 0 for i in range(1, (self.size() + 1))} for row in self: for i in row: w[i] += 1 return Composition([w[i] for i in range(1, (self.size() + 1))]) def descent_set(self): '\n Return the set of all `i` that do *not* have `i+1` appearing strictly\n to the left of `i` in ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[3,2],[4,4]]).descent_set()\n [1, 3]\n ' cols = {} for row in self: for (col, i) in enumerate(row): cols[i] = col return sorted((i for i in cols if (((i + 1) in cols) and (cols[(i + 1)] >= cols[i])))) def descent_composition(self): '\n Return the composition corresponding to the set of all `i` that do\n not have `i+1` appearing strictly to the left of `i` in ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1],[3,2],[4,4]]).descent_composition()\n [1, 2, 2]\n ' return Composition(from_subset=(self.descent_set(), self.size())) def shape_composition(self): '\n Return a Composition object which is the shape of ``self``.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1,1],[3,2],[4,4,3]]).shape_composition()\n [2, 2, 3]\n sage: CompositionTableau([[2,1],[3],[4]]).shape_composition()\n [2, 1, 1]\n ' return Composition([len(row) for row in self]) def shape_partition(self): '\n Return a partition which is the shape of ``self`` sorted into weakly\n decreasing order.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1,1],[3,2],[4,4,3]]).shape_partition()\n [3, 2, 2]\n sage: CompositionTableau([[2,1],[3],[4]]).shape_partition()\n [2, 1, 1]\n ' return Partition(sorted((len(row) for row in self), reverse=True)) def is_standard(self): '\n Return ``True`` if ``self`` is a standard composition tableau and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: CompositionTableau([[1,1],[3,2],[4,4,3]]).is_standard()\n False\n sage: CompositionTableau([[2,1],[3],[4]]).is_standard()\n True\n ' entries = sum(self, []) return (sorted(entries) == list(range(1, (self.size() + 1))))
class CompositionTableaux(UniqueRepresentation, Parent): '\n Composition tableaux.\n\n INPUT:\n\n Keyword arguments:\n\n - ``size`` -- the size of the composition tableaux\n - ``shape`` -- the shape of the composition tableaux\n - ``max_entry`` -- the maximum entry for the composition tableaux\n\n Positional arguments:\n\n - The first argument is interpreted as ``size`` or ``shape`` depending on\n whether it is an integer or a composition.\n\n EXAMPLES::\n\n sage: CT = CompositionTableaux(3); CT\n Composition Tableaux of size 3 and maximum entry 3\n sage: list(CT)\n [[[1], [2], [3]],\n [[1], [2, 2]],\n [[1], [3, 2]],\n [[1], [3, 3]],\n [[2], [3, 3]],\n [[1, 1], [2]],\n [[1, 1], [3]],\n [[2, 1], [3]],\n [[2, 2], [3]],\n [[1, 1, 1]],\n [[2, 1, 1]],\n [[2, 2, 1]],\n [[2, 2, 2]],\n [[3, 1, 1]],\n [[3, 2, 1]],\n [[3, 2, 2]],\n [[3, 3, 1]],\n [[3, 3, 2]],\n [[3, 3, 3]]]\n\n sage: CT = CompositionTableaux([1,2,1]); CT\n Composition tableaux of shape [1, 2, 1] and maximum entry 4\n sage: list(CT)\n [[[1], [2, 2], [3]],\n [[1], [2, 2], [4]],\n [[1], [3, 2], [4]],\n [[1], [3, 3], [4]],\n [[2], [3, 3], [4]]]\n\n sage: CT = CompositionTableaux(shape=[1,2,1],max_entry=3); CT\n Composition tableaux of shape [1, 2, 1] and maximum entry 3\n sage: list(CT)\n [[[1], [2, 2], [3]]]\n\n sage: CT = CompositionTableaux(2,max_entry=3); CT\n Composition Tableaux of size 2 and maximum entry 3\n sage: list(CT)\n [[[1], [2]],\n [[1], [3]],\n [[2], [3]],\n [[1, 1]],\n [[2, 1]],\n [[2, 2]],\n [[3, 1]],\n [[3, 2]],\n [[3, 3]]]\n\n sage: CT = CompositionTableaux(0); CT\n Composition Tableaux of size 0 and maximum entry 0\n sage: list(CT)\n [[]]\n ' @staticmethod def __classcall_private__(cls, *args, **kwargs): '\n This is a factory class which returns the appropriate parent based on\n arguments. See the documentation for :class:`CompositionTableaux` for\n more information.\n\n TESTS::\n\n sage: CT = CompositionTableaux(3); CT\n Composition Tableaux of size 3 and maximum entry 3\n sage: CT = CompositionTableaux(size=3); CT\n Composition Tableaux of size 3 and maximum entry 3\n sage: CT = CompositionTableaux([1,2]); CT\n Composition tableaux of shape [1, 2] and maximum entry 3\n sage: CT = CompositionTableaux(shape=[1,2]); CT\n Composition tableaux of shape [1, 2] and maximum entry 3\n sage: CT = CompositionTableaux(shape=[]); CT\n Composition tableaux of shape [] and maximum entry 0\n sage: CT = CompositionTableaux(0); CT\n Composition Tableaux of size 0 and maximum entry 0\n sage: CT = CompositionTableaux(max_entry=3); CT\n Composition tableaux with maximum entry 3\n sage: CT = CompositionTableaux([1,2],max_entry=3); CT\n Composition tableaux of shape [1, 2] and maximum entry 3\n sage: CT = CompositionTableaux(size=2,shape=[1,2]); CT\n Traceback (most recent call last):\n ...\n ValueError: size and shape are different sizes\n ' n = kwargs.get('n', None) size = kwargs.get('size', n) comp = kwargs.get('comp', None) shape = kwargs.get('shape', comp) max_entry = kwargs.get('max_entry', None) if args: if isinstance(args[0], (int, Integer)): if (size is not None): raise ValueError('size was specified more than once') else: size = args[0] else: if (shape is not None): raise ValueError('the shape was specified more than once') shape = args[0] if (size is not None): if (not isinstance(size, (int, Integer))): raise ValueError('size must be an integer') elif (size < 0): raise ValueError('size must be non-negative') if (shape is not None): if (shape not in Compositions()): raise ValueError('shape must be a composition') if any(((i == 0) for i in shape)): raise ValueError('shape must have non-zero parts') shape = Composition(shape) if ((size is not None) and (shape is not None)): if (sum(shape) != size): raise ValueError('size and shape are different sizes') if (max_entry is not None): if (not isinstance(max_entry, (int, Integer))): raise ValueError('max_entry must be an integer') elif (max_entry <= 0): raise ValueError('max_entry must be positive') if (shape is not None): return CompositionTableaux_shape(shape, max_entry) if (size is not None): return CompositionTableaux_size(size, max_entry) return CompositionTableaux_all(max_entry) def __init__(self, **kwds): '\n Initialize ``self``.\n\n TESTS::\n\n sage: CT = CompositionTableaux()\n sage: TestSuite(CT).run()\n ' if ('max_entry' in kwds): self.max_entry = kwds['max_entry'] kwds.pop('max_entry') else: self.max_entry = None super().__init__(**kwds) Element = CompositionTableau def _element_constructor_(self, t): '\n Construct an object from ``t`` as an element of ``self``, if\n possible.\n\n INPUT:\n\n - ``t`` -- data which can be interpreted as a composition tableau\n\n OUTPUT:\n\n - The corresponding CompositionTableau object\n\n TESTS::\n\n sage: CT = CompositionTableaux(3)\n sage: CT([[1],[2,2]]).parent() is CT\n True\n sage: CT([[1],[1,2]])\n Traceback (most recent call last):\n ...\n ValueError: [[1], [1, 2]] is not an element of Composition Tableaux of size 3 and maximum entry 3\n ' if (t not in self): raise ValueError(('%s is not an element of %s' % (t, self))) return self.element_class(self, t) def __contains__(self, T): '\n Return ``True`` if ``T`` can be interpreted as\n :class:`CompositionTableau`.\n\n TESTS::\n\n sage: [[1],[2,2]] in CompositionTableaux(3)\n True\n sage: [[1],[2,2]] in CompositionTableaux(shape=[1,2])\n True\n sage: CompositionTableau([[1],[2,2]]) in CompositionTableaux()\n True\n sage: [[1],[2,2],[2]] in CompositionTableaux()\n False\n ' if isinstance(T, CompositionTableau): return True first_col = [row[0] for row in T] if any(((first_col[i] >= first_col[(i + 1)]) for i in range((len(T) - 1)))): return False for row in T: if any(((row[i] < row[(i + 1)]) for i in range((len(row) - 1)))): return False l = len(T) m = max((len(r) for r in T), default=0) TT = [(row + ([0] * (m - len(row)))) for row in T] for i in range(l): for j in range((i + 1), l): for k in range(1, m): if ((TT[j][k] != 0) and (TT[j][k] >= TT[i][k]) and (TT[j][k] <= TT[i][(k - 1)])): return False return True
class CompositionTableaux_all(CompositionTableaux, DisjointUnionEnumeratedSets): '\n All composition tableaux.\n ' def __init__(self, max_entry=None): '\n Initialize ``self``.\n\n TESTS::\n\n sage: CT = CompositionTableaux()\n sage: TestSuite(CT).run()\n ' self.max_entry = max_entry CT_n = (lambda n: CompositionTableaux_size(n, max_entry)) DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), CT_n), facade=True, keepkey=False) def _repr_(self): '\n TESTS::\n\n sage: CompositionTableaux(3)\n Composition Tableaux of size 3 and maximum entry 3\n\n sage: CompositionTableaux()\n Composition Tableaux\n ' if (self.max_entry is not None): return f'Composition tableaux with maximum entry {self.max_entry}' return 'Composition Tableaux' def an_element(self): '\n Return a particular element of ``self``.\n\n EXAMPLES::\n\n sage: CT = CompositionTableaux()\n sage: CT.an_element()\n [[1, 1], [2]]\n ' return self.element_class(self, [[1, 1], [2]])
class CompositionTableaux_size(CompositionTableaux): '\n Composition tableaux of a fixed size `n`.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer.\n - ``max_entry`` -- a nonnegative integer. This keyword argument defaults to ``n``.\n\n OUTPUT:\n\n - The class of composition tableaux of size ``n``.\n ' def __init__(self, n, max_entry=None): '\n Initializes the class of composition tableaux of size ``n``.\n\n TESTS::\n\n sage: CT = CompositionTableaux(4)\n sage: TestSuite(CT).run()\n ' if (max_entry is None): max_entry = n super().__init__(max_entry=max_entry, category=FiniteEnumeratedSets()) self.size = n def __contains__(self, x): '\n TESTS::\n\n sage: [[1],[2,2]] in CompositionTableaux(3)\n True\n sage: [[1],[2,2]] in CompositionTableaux(4)\n False\n ' return (CompositionTableaux.__contains__(self, x) and (sum(map(len, x)) == self.size)) def __iter__(self): '\n EXAMPLES::\n\n sage: [t for t in CompositionTableaux(3)]\n [[[1], [2], [3]],\n [[1], [2, 2]],\n [[1], [3, 2]],\n [[1], [3, 3]],\n [[2], [3, 3]],\n [[1, 1], [2]],\n [[1, 1], [3]],\n [[2, 1], [3]],\n [[2, 2], [3]],\n [[1, 1, 1]],\n [[2, 1, 1]],\n [[2, 2, 1]],\n [[2, 2, 2]],\n [[3, 1, 1]],\n [[3, 2, 1]],\n [[3, 2, 2]],\n [[3, 3, 1]],\n [[3, 3, 2]],\n [[3, 3, 3]]]\n\n sage: CompositionTableaux(3)[0].parent() is CompositionTableaux(3)\n True\n ' for comp in Compositions(self.size): for T in CompositionTableaux_shape(comp, self.max_entry): (yield self.element_class(self, T)) def _repr_(self): '\n TESTS::\n\n sage: CompositionTableaux(3)\n Composition Tableaux of size 3 and maximum entry 3\n ' return ('Composition Tableaux of size %s and maximum entry %s' % (str(self.size), str(self.max_entry))) def _an_element_(self): '\n Return a particular element of ``self``.\n\n EXAMPLES::\n\n sage: CT = CompositionTableaux(4)\n sage: CT.an_element()\n [[1, 1, 1], [2]]\n sage: CompositionTableaux(0).an_element()\n []\n sage: CompositionTableaux(1).an_element()\n [[1]]\n ' if (self.size == 0): return self.element_class(self, []) if (self.size == 1): return self.element_class(self, [[1]]) return self.element_class(self, [([1] * (self.size - 1)), [2]])
class CompositionTableaux_shape(CompositionTableaux): '\n Composition tableaux of a fixed shape ``comp`` with a given max entry.\n\n INPUT:\n\n - ``comp`` -- a composition.\n - ``max_entry`` -- a nonnegative integer. This keyword argument defaults\n to the size of ``comp``.\n ' def __init__(self, comp, max_entry=None): '\n Initialize ``self``.\n\n TESTS::\n\n sage: CT = CompositionTableaux([1,2])\n sage: TestSuite(CT).run()\n\n sage: CT = CompositionTableaux([1,2], max_entry=4)\n sage: TestSuite(CT).run()\n ' if (max_entry is None): max_entry = sum(comp) super().__init__(max_entry=max_entry, category=FiniteEnumeratedSets()) self.shape = comp def __iter__(self): '\n An iterator for composition tableaux of a given shape.\n\n EXAMPLES::\n\n sage: [t for t in CompositionTableaux([1,2])]\n [[[1], [2, 2]], [[1], [3, 2]], [[1], [3, 3]], [[2], [3, 3]]]\n sage: [t for t in CompositionTableaux([1,2],max_entry=4)]\n [[[1], [2, 2]],\n [[1], [3, 2]],\n [[1], [3, 3]],\n [[1], [4, 2]],\n [[1], [4, 3]],\n [[1], [4, 4]],\n [[2], [3, 3]],\n [[2], [4, 3]],\n [[2], [4, 4]],\n [[3], [4, 4]]]\n ' if (sum(self.shape) == 0): (yield CompositionTableau([])) else: for z in CompositionTableauxBacktracker(self.shape, self.max_entry): (yield CompositionTableau(z)) def __contains__(self, x): '\n TESTS::\n\n sage: [[2],[4,3]] in CompositionTableaux([1,2])\n True\n sage: [[2],[3,2]] in CompositionTableaux([1,2])\n False\n ' return (CompositionTableaux.__contains__(self, x) and ([len(r) for r in x] == self.shape)) def _repr_(self): '\n TESTS::\n\n sage: CompositionTableaux([1,2,1])\n Composition tableaux of shape [1, 2, 1] and maximum entry 4\n sage: CompositionTableaux([1,2,1],max_entry=3)\n Composition tableaux of shape [1, 2, 1] and maximum entry 3\n ' return ('Composition tableaux of shape %s and maximum entry %s' % (str(self.shape), str(self.max_entry))) def an_element(self): '\n Return a particular element of :class:`CompositionTableaux_shape`.\n\n EXAMPLES::\n\n sage: CT = CompositionTableaux([1,2,1])\n sage: CT.an_element()\n [[1], [2, 2], [3]]\n ' if (self.shape == []): return self.element_class(self, []) t = [([i] * len) for (i, len) in enumerate(self.shape, start=1)] return self.element_class(self, t)
class CompositionTableauxBacktracker(GenericBacktracker): '\n A backtracker class for generating sets of composition tableaux.\n ' def __init__(self, shape, max_entry=None): '\n EXAMPLES::\n\n sage: from sage.combinat.composition_tableau import CompositionTableauxBacktracker\n sage: n = CompositionTableauxBacktracker([1,3,2])\n sage: n._ending_position\n (2, 1)\n sage: n._initial_state\n (0, 0)\n ' self._shape = shape self._n = sum(shape) self._initial_data = [([None] * s) for s in shape] if (max_entry is None): max_entry = sum(shape) self.max_entry = max_entry ending_row = (len(shape) - 1) ending_col = (shape[(- 1)] - 1) self._ending_position = (ending_row, ending_col) starting_row = 0 starting_col = 0 GenericBacktracker.__init__(self, self._initial_data, (starting_row, starting_col)) def _rec(self, obj, state): '\n EXAMPLES::\n\n sage: from sage.combinat.composition_tableau import CompositionTableauxBacktracker\n sage: n = CompositionTableauxBacktracker([1,3,2])\n sage: obj = [ [None], [None, None, None], [None, None] ]\n sage: list(n._rec(obj, n._initial_state))\n [([[1], [None, None, None], [None, None]], (1, 0), False),\n ([[2], [None, None, None], [None, None]], (1, 0), False),\n ([[3], [None, None, None], [None, None]], (1, 0), False),\n ([[4], [None, None, None], [None, None]], (1, 0), False),\n ([[5], [None, None, None], [None, None]], (1, 0), False),\n ([[6], [None, None, None], [None, None]], (1, 0), False)]\n ' obj_copy = copy.deepcopy(obj) N = max((len(u) for u in obj_copy)) for a in range(len(obj_copy)): Na = len(obj_copy[a]) obj_copy[a] += ([0] * (N - Na)) (i, j) = state new_state = self.get_next_pos(i, j) yld = bool((new_state is None)) for k in range(1, (self.max_entry + 1)): if ((j != 0) and (obj[i][(j - 1)] < k)): continue if ((j == 0) and (i != 0) and (k <= obj[(i - 1)][j])): continue if ((j != 0) and (i != 0) and any(((k == obj_copy[m][j]) for m in range(i)))): continue if ((j != 0) and (i != 0) and any((((obj_copy[m][j] < k) and (k <= obj_copy[m][(j - 1)])) for m in range(i)))): continue obj[i][j] = k obj_copy[i][j] = k (yield (copy.deepcopy(obj), new_state, yld)) def get_next_pos(self, ii, jj): '\n EXAMPLES::\n\n sage: from sage.combinat.composition_tableau import CompositionTableauxBacktracker\n sage: T = CompositionTableau([[2,1],[5,4,3,2],[6],[7,7,6]])\n sage: n = CompositionTableauxBacktracker(T.shape_composition())\n sage: n.get_next_pos(1,1)\n (1, 2)\n ' if ((ii, jj) == self._ending_position): return None for j in range((jj + 1), self._shape[ii]): if (self._shape[ii] >= j): return (ii, j) return ((ii + 1), 0)
def Constellations(*data, **options): '\n Build a set of constellations.\n\n INPUT:\n\n - ``profile`` -- an optional profile\n\n - ``length`` -- an optional length\n\n - ``degree`` -- an optional degree\n\n - ``connected`` -- an optional boolean\n\n EXAMPLES::\n\n sage: Constellations(4,2)\n Connected constellations of length 4 and degree 2 on {1, 2}\n\n sage: Constellations([[3,2,1],[3,3],[3,3]])\n Connected constellations with profile ([3, 2, 1], [3, 3], [3, 3]) on {1, 2, 3, 4, 5, 6}\n ' profile = options.get('profile', None) length = options.get('length', None) degree = options.get('degree', None) connected = options.get('connected', True) domain = options.get('domain', None) if (domain is not None): domain = tuple(domain) if data: if (len(data) == 1): if isinstance(data[0], (tuple, list)): profile = data[0] else: length = Integer(data[0]) elif (len(data) == 2): length = Integer(data[0]) degree = Integer(data[1]) if profile: profile = tuple(map(Partition, profile)) return Constellations_p(profile, domain, bool(connected)) elif ((degree is not None) and (length is not None)): if (domain is None): sym = SymmetricGroup(degree) else: sym = SymmetricGroup(domain) if (len(sym.domain()) != degree): raise ValueError('the size of the domain should be equal to the degree') return Constellations_ld(Integer(length), Integer(degree), sym, bool(connected)) else: raise ValueError('you must either provide a profile or a pair (length, degree)')
def Constellation(g=None, mutable=False, connected=True, check=True): "\n Constellation\n\n INPUT:\n\n - ``g`` -- a list of permutations\n\n - ``mutable`` -- whether the result is mutable or not. Default is ``False``.\n\n - ``connected`` -- whether the result should be connected. Default is\n ``True``.\n\n - ``check`` -- whether or not to check. If it is ``True``, then the\n list ``g`` must contains no ``None``.\n\n EXAMPLES:\n\n Simple initialization::\n\n sage: Constellation(['(0,1)','(0,3)(1,2)','(0,3,1,2)'])\n Constellation of length 3 and degree 4\n g0 (0,1)(2)(3)\n g1 (0,3)(1,2)\n g2 (0,3,1,2)\n\n One of the permutation can be omitted::\n\n sage: Constellation(['(0,1)', None, '(0,4)(1,2,3)'])\n Constellation of length 3 and degree 5\n g0 (0,1)(2)(3)(4)\n g1 (0,3,2,1,4)\n g2 (0,4)(1,2,3)\n\n One can define mutable constellations::\n\n sage: Constellation(([0,2,1], [2,1,0], [1,2,0]), mutable=True)\n Constellation of length 3 and degree 3\n g0 (0)(1,2)\n g1 (0,2)(1)\n g2 (0,1,2)\n " l = len(g) (sym, _) = perms_sym_init([x for x in g if (x is not None)]) d = len(sym.domain()) return Constellations(l, d, domain=sym.domain(), connected=connected)(g, mutable=mutable, check=check)
class Constellation_class(Element): '\n Constellation\n\n A constellation or a tuple of permutations `(g_0,g_1,...,g_k)`\n such that the product `g_0 g_1 ... g_k` is the identity.\n ' def __init__(self, parent, g, connected, mutable, check): "\n TESTS::\n\n sage: c = Constellation([[1,2,0],[0,2,1],[1,0,2],None])\n sage: c == loads(dumps(c))\n True\n sage: g0 = '(0,1)(2,4)'\n sage: g1 = '(0,3)(1,4)'\n sage: g2 = '(2,4,3)'\n sage: g3 = '(0,3)(1,2)'\n sage: c0 = Constellation([g0,g1,g2,g3])\n sage: c0 == Constellation([None,g1,g2,g3])\n True\n sage: c0 == Constellation([g0,None,g2,g3])\n True\n sage: c0 == Constellation([g0,g1,None,g3])\n True\n sage: c0 == Constellation([g0,g1,g2,None])\n True\n " Element.__init__(self, parent) self._connected = connected self._mutable = mutable self._g = g if check: self._check() def __hash__(self): '\n Return a hash for ``self``.\n\n EXAMPLES::\n\n sage: c = Constellation(([0,2,1],[2,1,0],[1,2,0]), mutable=False)\n sage: hash(c) == hash(tuple(c._g))\n True\n ' if self._mutable: raise ValueError('cannot hash mutable constellation') return hash(tuple(self._g)) def set_immutable(self): '\n Do nothing, as ``self`` is already immutable.\n\n EXAMPLES::\n\n sage: c = Constellation(([0,2,1],[2,1,0],[1,2,0]), mutable=False)\n sage: c.set_immutable()\n sage: c.is_mutable()\n False\n ' self._mutable = False def is_mutable(self): '\n Return ``False`` as ``self`` is immutable.\n\n EXAMPLES::\n\n sage: c = Constellation(([0,2,1],[2,1,0],[1,2,0]), mutable=False)\n sage: c.is_mutable()\n False\n ' return self._mutable def switch(self, i, j0, j1): "\n Perform the multiplication by the transposition `(j0, j1)` between the\n permutations `g_i` and `g_{i+1}`.\n\n The modification is local in the sense that it modifies `g_i`\n and `g_{i+1}` but does not modify the product `g_i g_{i+1}`. The new\n constellation is\n\n .. MATH::\n\n (g_0, \\ldots, g_{i-1}, g_{i} (j0 j1), (j0 j1) g_{i+1}, g_{i+2}, \\ldots, g_k)\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)(2,3,4)','(1,4)',None], mutable=True); c\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,4)(2)(3)\n g2 (0,1,3,2,4)\n sage: c.is_mutable()\n True\n sage: c.switch(1,2,3); c\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,4)(2,3)\n g2 (0,1,3,4)(2)\n sage: c._check()\n sage: c.switch(2,1,3); c\n Constellation of length 3 and degree 5\n g0 (0,1,4,2,3)\n g1 (0)(1,4)(2,3)\n g2 (0,3,4)(1)(2)\n sage: c._check()\n sage: c.switch(0,0,1); c\n Constellation of length 3 and degree 5\n g0 (0)(1,4,2,3)\n g1 (0,4,1)(2,3)\n g2 (0,3,4)(1)(2)\n sage: c._check()\n " if (not self._mutable): raise ValueError('this constellation is immutable. Take a mutable copy first.') S = SymmetricGroup(list(range(self.degree()))) tr = S((j0, j1)) i = int(i) if ((i < 0) or (i >= len(self._g))): raise ValueError('index out of range') ii = (i + 1) if (ii == len(self._g)): ii = 0 self._g[i] = (self._g[i] * tr) self._g[ii] = (tr * self._g[ii]) def euler_characteristic(self): "\n Return the Euler characteristic of the surface.\n\n ALGORITHM:\n\n Hurwitz formula\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)', '(0,2)', None])\n sage: c.euler_characteristic()\n 2\n\n sage: c = Constellation(['(0,1,2,3)','(1,3,0,2)', '(0,3,1,2)', None])\n sage: c.euler_characteristic()\n -4\n\n TESTS::\n\n sage: parent(c.euler_characteristic())\n Integer Ring\n " return Integer(((self.degree() * 2) - sum((sum(((j - 1) for j in self.profile(i))) for i in range(self.length()))))) def genus(self): "\n Return the genus of the surface.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)', '(0,2)', None])\n sage: c.genus()\n 0\n\n sage: c = Constellation(['(0,1)(2,3,4)','(1,3,4)(2,0)', None])\n sage: c.genus()\n 1\n\n TESTS::\n\n sage: parent(c.genus())\n Integer Ring\n " return (1 - (self.euler_characteristic() // 2)) def _check(self): '\n Check that the constellation is valid and if not raise ValueError.\n\n TESTS::\n\n sage: c = Constellation([[0,1],[1,0]], mutable=True, check=False)\n sage: c._check()\n Traceback (most recent call last):\n ...\n ValueError: the product is not identity\n\n sage: c = Constellation([[0,1],[0,1]], mutable=True, check=False)\n sage: c._check()\n Traceback (most recent call last):\n ...\n ValueError: not connected\n ' d = self.degree() Sd = self.parent()._sym if (prod(self._g, Sd.one()) != Sd.one()): raise ValueError('the product is not identity') if (self._connected and (not perms_are_connected(self._g, d))): raise ValueError('not connected') def __copy__(self): '\n Return a copy of ``self``.\n\n TESTS::\n\n sage: c = Constellation([[0,2,1],[1,0,2],[2,1,0],None])\n sage: c == copy(c)\n True\n sage: c is copy(c)\n False\n sage: c = Constellation([[0,2,1],[1,0,2],[2,1,0],None],mutable=True)\n sage: c == copy(c)\n True\n sage: c is copy(c)\n False\n ' return self.parent()([gg for gg in self._g], check=False, mutable=self._mutable) copy = __copy__ def mutable_copy(self): '\n Return a mutable copy of ``self``.\n\n EXAMPLES::\n\n sage: c = Constellation(([0,2,1],[2,1,0],[1,2,0]), mutable=False)\n sage: d = c.mutable_copy()\n sage: d.is_mutable()\n True\n ' return self.parent()([gg for gg in self._g], check=False, mutable=True) def is_connected(self): "\n Test of connectedness.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)(2)', None, '(0,1)(2)'], connected=False)\n sage: c.is_connected()\n False\n sage: c = Constellation(['(0,1,2)', None], connected=False)\n sage: c.is_connected()\n True\n " if self._connected: return True else: return perms_are_connected(self._g, self.degree()) def connected_components(self): "\n Return the connected components.\n\n OUTPUT:\n\n A list of connected constellations.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)(2)', None, '(0,1)(2)'], connected=False)\n sage: cc = c.connected_components(); cc\n [Constellation of length 3 and degree 2\n g0 (0,1)\n g1 (0)(1)\n g2 (0,1),\n Constellation of length 3 and degree 1\n g0 (0)\n g1 (0)\n g2 (0)]\n sage: all(c2.is_connected() for c2 in cc)\n True\n\n sage: c = Constellation(['(0,1,2)', None], connected=False)\n sage: c.connected_components()\n [Constellation of length 2 and degree 3\n g0 (0,1,2)\n g1 (0,2,1)]\n " if self._connected: return [self] G = Graph() G.add_vertices(list(range(self.degree()))) for p in self._g: G.add_edges(enumerate(p.domain()), loops=False) m = G.connected_components(sort=False) if (len(m) == 1): return [self] for mm in m: mm.sort() m.sort() g = [[] for _ in repeat(None, len(m))] m_inv = ([None] * self.degree()) for (t, mt) in enumerate(m): for (i, mti) in enumerate(mt): m_inv[mti] = i for k in range(self.length()): tmp = ([None] * len(mt)) for (i, mti) in enumerate(mt): tmp[i] = m_inv[self._g[k](mti)] g[t].append(tmp) return [Constellation(g=g[i], check=False) for i in range(len(m))] def _richcmp_(self, other, op): "\n Do the comparison.\n\n TESTS::\n\n sage: Constellation(['(0,1,2)', None]) == Constellation(['(0,1,2)', None])\n True\n sage: Constellation(['(0,1)','(0,2)',None]) == Constellation(['(0,1)',None,'(0,2)'])\n False\n\n sage: Constellation(['(0,1,2)', None]) != Constellation(['(0,1,2)', None])\n False\n sage: Constellation(['(0,1)','(0,2)',None]) != Constellation(['(0,1)',None,'(0,2)'])\n True\n\n sage: c1 = Constellation([[1,2,0],None])\n sage: c2 = Constellation([[2,0,1],None])\n sage: c1 < c2\n True\n sage: c2 > c1\n True\n " if (not isinstance(other, Constellation_class)): return (op == op_NE) if (op == op_EQ): return (self._g == other._g) if (op == op_NE): return (self._g != other._g) lx = self.length() rx = other.length() if (lx != rx): return richcmp_not_equal(lx, rx, op) lx = self.degree() rx = other.degree() if (lx != rx): return richcmp_not_equal(lx, rx, op) for i in range((self.length() - 1)): lx = self._g[i] rx = other._g[i] if (lx != rx): return richcmp_not_equal(lx, rx, op) return rich_to_bool(op, 0) def is_isomorphic(self, other, return_map=False): '\n Test of isomorphism.\n\n Return ``True`` if the constellations are isomorphic\n (*i.e.* related by a common conjugacy) and return the permutation that\n conjugate the two permutations if ``return_map`` is ``True`` in\n such a way that ``self.relabel(m) == other``.\n\n ALGORITHM:\n\n uses canonical labels obtained from the method :meth:`relabel`.\n\n EXAMPLES::\n\n sage: c = Constellation([[1,0,2],[2,1,0],[0,2,1],None])\n sage: d = Constellation([[2,1,0],[0,2,1],[1,0,2],None])\n sage: answer, mapping = c.is_isomorphic(d,return_map=True)\n sage: answer\n True\n sage: c.relabel(mapping) == d\n True\n ' if return_map: if (not ((self.degree() == other.degree()) and (self.length() == other.length()))): return (False, None) (sn, sn_map) = self.relabel(return_map=True) (on, on_map) = other.relabel(return_map=True) if (sn != on): return (False, None) return (True, (sn_map * (~ on_map))) return ((self.degree() == other.degree()) and (self.length() == other.length()) and (self.relabel() == other.relabel())) def _repr_(self): "\n Return a string representation.\n\n EXAMPLES::\n\n sage: c = Constellation([[1,0,2],[2,1,0],[0,2,1],None])\n sage: c._repr_()\n 'Constellation of length 4 and degree 3\\ng0 (0,1)(2)\\ng1 (0,2)(1)\\ng2 (0)(1,2)\\ng3 (0,2)(1)'\n " s = 'Constellation of length {} and degree {}'.format(self.length(), self.degree()) for i in range(self.length()): s += '\ng{} {}'.format(i, self._g[i].cycle_string(True)) return s def degree(self): "\n Return the degree of the constellation.\n\n The degree of a constellation is the number `n` that\n corresponds to the symmetric group `S(n)` in which the\n permutations of the constellation are defined.\n\n EXAMPLES::\n\n sage: c = Constellation([])\n sage: c.degree()\n 0\n sage: c = Constellation(['(0,1)',None])\n sage: c.degree()\n 2\n sage: c = Constellation(['(0,1)','(0,3,2)(1,5)',None,'(4,3,2,1)'])\n sage: c.degree()\n 6\n\n TESTS::\n\n sage: parent(c.degree())\n Integer Ring\n " return self.parent()._degree def length(self): "\n Return the number of permutations.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)','(0,2)','(0,3)',None])\n sage: c.length()\n 4\n sage: c = Constellation(['(0,1,3)',None,'(1,2)'])\n sage: c.length()\n 3\n\n TESTS::\n\n sage: parent(c.length())\n Integer Ring\n " return Integer(len(self._g)) def profile(self, i=None): "\n Return the profile of ``self``.\n\n The profile of a constellation is the tuple of partitions\n associated to the conjugacy classes of the permutations of the\n constellation.\n\n This is also called the passport.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1,2)(3,4)','(0,3)',None])\n sage: c.profile()\n ([3, 2], [2, 1, 1, 1], [5])\n " if (i is None): return tuple((self.profile(j) for j in range(self.length()))) else: parts = [len(cy) for cy in self._g[i].cycle_tuples(True)] return Partition(sorted(parts, reverse=True)) passport = profile def g(self, i=None): "\n Return the permutation `g_i` of the constellation.\n\n INPUT:\n\n - i -- integer or ``None`` (default)\n\n If ``None`` , return instead the list of all `g_i`.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1,2)(3,4)','(0,3)',None])\n sage: c.g(0)\n (0,1,2)(3,4)\n sage: c.g(1)\n (0,3)\n sage: c.g(2)\n (0,4,3,2,1)\n sage: c.g()\n [(0,1,2)(3,4), (0,3), (0,4,3,2,1)]\n " from copy import copy if (i is None): return copy(self._g) else: gi = self._g[i] return gi.parent()(gi) def relabel(self, perm=None, return_map=False): '\n Relabel ``self``.\n\n If ``perm`` is provided then relabel with respect to ``perm``. Otherwise\n use canonical labels. In that case, if ``return_map`` is provided, the\n return also the map used for canonical labels.\n\n Algorithm:\n\n the cycle for g(0) are adjacent and the cycle are joined with\n respect to the other permutations. The minimum is taken for\n all possible renumerotations.\n\n EXAMPLES::\n\n sage: c = Constellation([\'(0,1)(2,3,4)\',\'(1,4)\',None]); c\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,4)(2)(3)\n g2 (0,1,3,2,4)\n sage: c2 = c.relabel(); c2\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,2)(3)(4)\n g2 (0,1,4,3,2)\n\n The map returned when the option ``return_map`` is set to\n ``True`` can be used to set the relabelling::\n\n sage: c3, perm = c.relabel(return_map=True)\n sage: c3 == c2 and c3 == c.relabel(perm=perm)\n True\n\n sage: S5 = SymmetricGroup(range(5))\n sage: d = c.relabel(S5([4,3,1,0,2])); d\n Constellation of length 3 and degree 5\n g0 (0,2,1)(3,4)\n g1 (0)(1)(2,3)(4)\n g2 (0,1,2,4,3)\n sage: d.is_isomorphic(c)\n True\n\n We check that after a random relabelling the new constellation is\n isomorphic to the initial one::\n\n sage: c = Constellation([\'(0,1)(2,3,4)\',\'(1,4)\',None])\n sage: p = S5.random_element()\n sage: cc = c.relabel(perm=p)\n sage: cc.is_isomorphic(c)\n True\n\n Check that it works for "non standard" labels::\n\n sage: c = Constellation([((\'a\',\'b\'),(\'c\',\'d\',\'e\')),(\'b\',\'d\'), None])\n sage: c.relabel()\n Constellation of length 3 and degree 5\n g0 (\'a\',\'b\')(\'c\',\'d\',\'e\')\n g1 (\'a\')(\'b\',\'c\')(\'d\')(\'e\')\n g2 (\'a\',\'b\',\'e\',\'d\',\'c\')\n ' if (perm is not None): g = [([None] * self.degree()) for _ in range(self.length())] for i in range(len(perm.domain())): for k in range(self.length()): g[k][perm(i)] = perm(self._g[k](i)) return Constellation(g=g, check=False, mutable=self.is_mutable()) if return_map: try: return (self._normal_form, self._normal_form_map) except AttributeError: pass else: try: return self._normal_form except AttributeError: pass if (not self.is_connected()): raise ValueError('no canonical labels implemented for non connected constellation') domain = list(self.parent()._sym.domain()) index = {e: i for (i, e) in enumerate(domain)} g = [[index[gg(i)] for i in domain] for gg in self._g] (c_win, m_win) = perms_canonical_labels(g) c_win = [[domain[i] for i in gg] for gg in c_win] m_win = self.parent()._sym([domain[i] for i in m_win]) c_win = self.parent()(c_win, mutable=False, check=False) if (not self.is_mutable()): self._normal_form = c_win self._normal_form_map = m_win c_win._normal_form = c_win c_win._normal_form_map = m_win if return_map: return (c_win, m_win) else: return c_win def braid_group_action(self, i): "\n Act on ``self`` as the braid group generator that exchanges\n position `i` and `i+1`.\n\n INPUT:\n\n - ``i`` -- integer in `[0, n-1]` where `n` is the length of ``self``\n\n EXAMPLES::\n\n sage: sigma = lambda c, i: c.braid_group_action(i)\n\n sage: c = Constellation(['(0,1)(2,3,4)','(1,4)',None]); c\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,4)(2)(3)\n g2 (0,1,3,2,4)\n sage: sigma(c, 1)\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0,1,3,2,4)\n g2 (0,3)(1)(2)(4)\n\n Check the commutation relation::\n\n sage: c = Constellation(['(0,1)(2,3,4)','(1,4)','(2,5)(0,4)',None])\n sage: d = Constellation(['(0,1,3,5)','(2,3,4)','(0,3,5)',None])\n sage: c13 = sigma(sigma(c, 0), 2)\n sage: c31 = sigma(sigma(c, 2), 0)\n sage: c13 == c31\n True\n sage: d13 = sigma(sigma(d, 0), 2)\n sage: d31 = sigma(sigma(d, 2), 0)\n sage: d13 == d31\n True\n\n Check the braid relation::\n\n sage: c121 = sigma(sigma(sigma(c, 1), 2), 1)\n sage: c212 = sigma(sigma(sigma(c, 2), 1), 2)\n sage: c121 == c212\n True\n sage: d121 = sigma(sigma(sigma(d, 1), 2), 1)\n sage: d212 = sigma(sigma(sigma(d, 2), 1), 2)\n sage: d121 == d212\n True\n " if ((i < 0) or (i >= self.length())): txt = 'i should be between 0 and {}' raise ValueError(txt.format((self.length() - 1))) j = (i + 1) if (j == self.length()): j = 0 h = self.copy() si = self._g[i] sj = self._g[j] h._g[i] = sj h._g[j] = (((~ sj) * si) * sj) return h def braid_group_orbit(self): "\n Return the graph of the action of the braid group.\n\n The action is considered up to isomorphism of constellation.\n\n EXAMPLES::\n\n sage: c = Constellation(['(0,1)(2,3,4)','(1,4)',None]); c\n Constellation of length 3 and degree 5\n g0 (0,1)(2,3,4)\n g1 (0)(1,4)(2)(3)\n g2 (0,1,3,2,4)\n sage: G = c.braid_group_orbit()\n sage: G.num_verts()\n 4\n sage: G.num_edges()\n 12\n " from sage.graphs.digraph import DiGraph G = DiGraph(multiedges=True, loops=True) waiting = [self.relabel()] while waiting: c = waiting.pop() G.add_vertex(c) for i in range(self.length()): cc = self.braid_group_action(i).relabel() if (cc not in G): waiting.append(cc) G.add_edge(c, cc, i) return G
class Constellations_ld(UniqueRepresentation, Parent): '\n Constellations of given length and degree.\n\n EXAMPLES::\n\n sage: C = Constellations(2,3); C\n Connected constellations of length 2 and degree 3 on {1, 2, 3}\n sage: C([[2,3,1],[3,1,2]])\n Constellation of length 2 and degree 3\n g0 (1,2,3)\n g1 (1,3,2)\n sage: C.cardinality()\n 2\n sage: Constellations(2,3,connected=False).cardinality()\n 6\n ' Element = Constellation_class def __init__(self, length, degree, sym=None, connected=True): "\n TESTS::\n\n sage: TestSuite(Constellations(length=6,degree=4)).run(skip='_test_cardinality')\n " from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets Parent.__init__(self, category=FiniteEnumeratedSets()) self._length = length self._degree = degree if (self._length < 0): raise ValueError('length should be a non-negative integer') if (self._degree < 0): raise ValueError('degree should be a non-negative integer') self._sym = sym self._connected = bool(connected) def is_empty(self): '\n Return whether this set of constellations is empty.\n\n EXAMPLES::\n\n sage: Constellations(2, 3).is_empty()\n False\n sage: Constellations(1, 2).is_empty()\n True\n sage: Constellations(1, 2, connected=False).is_empty()\n False\n ' return (self._connected and (self._length == 1) and (self._degree > 1)) def __contains__(self, elt): '\n TESTS::\n\n sage: C = Constellations(2, 3, connected=True)\n sage: D = Constellations(2, 3, connected=False)\n sage: e1 = [[3,1,2], None]\n sage: e2 = [[1,2,3], None]\n sage: C(e1) in C\n True\n sage: D(e1) in C\n True\n sage: D(e1) in D\n True\n sage: D(e2) in C\n False\n sage: D(e2) in D\n True\n\n sage: e1 in C and e1 in D\n True\n sage: e2 in C\n False\n sage: e2 in D\n True\n ' if isinstance(elt, (tuple, list)): try: self(elt, check=True) except (ValueError, TypeError): return False else: return True elif (not isinstance(elt, Constellation_class)): return False return ((elt.parent() is self) or ((elt.length() == self._length) and (elt.degree() == self._degree) and ((not self._connected) or elt.is_connected()))) def _repr_(self): "\n TESTS::\n\n sage: Constellations(3,3)._repr_()\n 'Connected constellations of length 3 and degree 3 on {1, 2, 3}'\n sage: Constellations(3,3,connected=False)._repr_()\n 'Constellations of length 3 and degree 3 on {1, 2, 3}'\n " s = 'of length {} and degree {} on {}'.format(self._length, self._degree, self._sym.domain()) if self._connected: return ('Connected constellations ' + s) else: return ('Constellations ' + s) def __iter__(self): '\n Iterator over all constellations of given degree and length.\n\n EXAMPLES::\n\n sage: const = Constellations(3,3); const\n Connected constellations of length 3 and degree 3 on {1, 2, 3}\n sage: len([v for v in const])\n 26\n\n One can check the first few terms of sequence :oeis:`220754`::\n\n sage: Constellations(4,1).cardinality()\n 1\n sage: Constellations(4,2).cardinality()\n 7\n sage: Constellations(4,3).cardinality()\n 194\n sage: Constellations(4,4).cardinality() # long time\n 12858\n ' from itertools import product if (self._length == 1): if (self._degree == 1): (yield self([[0]])) return S = self._sym for p in product(S, repeat=(self._length - 1)): if (self._connected and (not perms_are_connected(p, self._degree))): continue (yield self((list(p) + [None]), check=False)) def random_element(self, mutable=False): '\n Return a random element.\n\n This is found by trial and rejection, starting from\n a random list of permutations.\n\n EXAMPLES::\n\n sage: const = Constellations(3,3)\n sage: const.random_element()\n Constellation of length 3 and degree 3\n ...\n ...\n ...\n sage: c = const.random_element()\n sage: c.degree() == 3 and c.length() == 3\n True\n ' from sage.groups.perm_gps.permgroup import PermutationGroup l = self._length d = self._degree Sd = self._sym g = [Sd.random_element() for _ in range((l - 1))] G = PermutationGroup(g) while ((not (G.degree() == d)) or (self._connected and (not G.is_transitive()))): g = [Sd.random_element() for _ in range((l - 1))] G = PermutationGroup(g) return self(([sigma.domain() for sigma in g] + [None]), mutable=mutable) def _element_constructor_(self, *data, **options): '\n Build an element of ``self``.\n\n EXAMPLES::\n\n sage: C = Constellations(2,3)\n sage: C([[2,3,1],[3,1,2]])\n Constellation of length 2 and degree 3\n g0 (1,2,3)\n g1 (1,3,2)\n sage: C([[3,2,1],[3,2,1]])\n Traceback (most recent call last):\n ...\n ValueError: not connected\n ' if ((len(data) == 1) and isinstance(data[0], (list, tuple)) and (len(data[0]) == self._length)): g = list(data[0]) else: g = list(data) if (len(g) != self._length): raise ValueError('must be a list of length {}'.format(self._length)) if (g.count(None) == 0): i = None elif (g.count(None) == 1): i = g.index(None) del g[i] else: raise ValueError('at most one permutation can be None') g = [self._sym(w) for w in g] if (i is not None): h = self._sym.one() for p in g[i:]: h *= p for p in g[:i]: h *= p g.insert(i, (~ h)) mutable = options.pop('mutable', False) if options.pop('check', True): c = self.element_class(self, g, self._connected, mutable, True) if (c.degree() != self._degree): raise ValueError('degree is not {}'.format(self._degree)) if (c.length() != self._length): raise ValueError('length is not {}'.format(self._length)) return c else: return self.element_class(self, g, self._connected, mutable, False) def _an_element_(self): "\n Return a constellation in ``self``.\n\n EXAMPLES::\n\n sage: Constellations(2, 3).an_element()\n Constellation of length 2 and degree 3\n g0 (1,3,2)\n g1 (1,2,3)\n\n sage: Constellations(3, 5,domain='abcde').an_element()\n Constellation of length 3 and degree 5\n g0 ('a','e','d','c','b')\n g1 ('a','b','c','d','e')\n g2 ('a')('b')('c')('d')('e')\n\n sage: Constellations(0, 0).an_element()\n Constellation of length 0 and degree 0\n\n sage: Constellations(1, 1).an_element()\n Constellation of length 1 and degree 1\n g0 (1)\n\n sage: Constellations(1, 2).an_element()\n Traceback (most recent call last):\n ...\n EmptySetError\n " if self.is_empty(): from sage.categories.sets_cat import EmptySetError raise EmptySetError if ((self._degree == 0) and (self._length == 0)): return self([]) elif (self._length == 1): return self(self._sym.one()) d = self._degree domain = self._sym.domain().list() if self._connected: g = [([domain[(d - 1)]] + domain[:(d - 1)]), (domain[1:] + [domain[0]])] g += ([domain[:]] * (self._length - 2)) else: g = ([domain[:]] * self._length) return self(g) def braid_group_action(self): '\n Return a list of graphs that corresponds to the braid group action on\n ``self`` up to isomorphism.\n\n OUTPUT:\n\n - list of graphs\n\n EXAMPLES::\n\n sage: C = Constellations(3,3)\n sage: C.braid_group_action()\n [Looped multi-digraph on 3 vertices,\n Looped multi-digraph on 1 vertex,\n Looped multi-digraph on 3 vertices]\n ' G = [] for c in self: c = c.relabel() if any(((c in g) for g in G)): continue G.append(c.braid_group_orbit()) return G def braid_group_orbits(self): '\n Return the orbits under the action of braid group.\n\n EXAMPLES::\n\n sage: C = Constellations(3,3)\n sage: O = C.braid_group_orbits()\n sage: len(O)\n 3\n sage: [x.profile() for x in O[0]]\n [([1, 1, 1], [3], [3]), ([3], [1, 1, 1], [3]), ([3], [3], [1, 1, 1])]\n sage: [x.profile() for x in O[1]]\n [([3], [3], [3])]\n sage: [x.profile() for x in O[2]]\n [([2, 1], [2, 1], [3]), ([2, 1], [3], [2, 1]), ([3], [2, 1], [2, 1])]\n ' return [g.vertices(sort=True) for g in self.braid_group_action()]
class Constellations_p(UniqueRepresentation, Parent): '\n Constellations with fixed profile.\n\n EXAMPLES::\n\n sage: C = Constellations([[3,1],[3,1],[2,2]]); C\n Connected constellations with profile ([3, 1], [3, 1], [2, 2]) on {1, 2, 3, 4}\n sage: C.cardinality()\n 24\n sage: C.first()\n Constellation of length 3 and degree 4\n g0 (1)(2,3,4)\n g1 (1,2,3)(4)\n g2 (1,2)(3,4)\n sage: C.last()\n Constellation of length 3 and degree 4\n g0 (1,4,3)(2)\n g1 (1,4,2)(3)\n g2 (1,2)(3,4)\n\n Note that the cardinality can also be computed using characters of the\n symmetric group (Frobenius formula)::\n\n sage: P = Partitions(4)\n sage: p1 = Partition([3,1])\n sage: p2 = Partition([3,1])\n sage: p3 = Partition([2,2])\n sage: i1 = P.cardinality() - P.rank(p1) - 1\n sage: i2 = P.cardinality() - P.rank(p2) - 1\n sage: i3 = P.cardinality() - P.rank(p3) - 1\n sage: s = 0\n sage: for c in SymmetricGroup(4).irreducible_characters():\n ....: v = c.values()\n ....: s += v[i1] * v[i2] * v[i3] / v[0]\n sage: c1 = p1.conjugacy_class_size()\n sage: c2 = p2.conjugacy_class_size()\n sage: c3 = p3.conjugacy_class_size()\n sage: c1 * c2 * c3 / factorial(4)**2 * s\n 1\n\n The number obtained above is up to isomorphism. And we can check::\n\n sage: len(C.isomorphism_representatives())\n 1\n ' def __init__(self, profile, domain=None, connected=True): '\n OPTIONS:\n\n - ``profile`` -- a list of integer partitions of the same integer\n\n - ``connected`` -- a boolean (default: ``True``) that specify\n if we consider only connected constellations.\n\n TESTS::\n\n sage: C = Constellations([(3,1),(3,1),(2,2)])\n sage: TestSuite(C).run()\n ' l = Integer(len(profile)) d = Integer(sum(profile[0])) for p in profile: if (sum(p) != d): raise ValueError('all partition in the passport should have the same sum.') if (domain is None): sym = SymmetricGroup(d) else: sym = SymmetricGroup(domain) if (len(sym.domain()) != d): raise ValueError('the size of the domain should be equal to the degree') self._cd = Constellations_ld(l, d, sym, connected) self._profile = profile from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): '\n TESTS::\n\n sage: Constellations(profile=[[3,2,1],[3,3],[3,3]])\n Connected constellations with profile ([3, 2, 1], [3, 3], [3, 3]) on {1, 2, 3, 4, 5, 6}\n ' s = 'with profile {} on {}'.format(self._profile, self._cd._sym.domain()) if self._cd._connected: return ('Connected constellations ' + s) return ('Constellations ' + s) def isomorphism_representatives(self): '\n Return a set of isomorphism representative of ``self``.\n\n EXAMPLES::\n\n sage: C = Constellations([[5], [4,1], [3,2]])\n sage: C.cardinality()\n 240\n sage: ir = sorted(C.isomorphism_representatives())\n sage: len(ir)\n 2\n sage: ir[0]\n Constellation of length 3 and degree 5\n g0 (1,2,3,4,5)\n g1 (1)(2,3,4,5)\n g2 (1,5,3)(2,4)\n sage: ir[1]\n Constellation of length 3 and degree 5\n g0 (1,2,3,4,5)\n g1 (1)(2,5,3,4)\n g2 (1,5)(2,3,4)\n ' result = set() for c in self: cc = c.relabel() if (cc not in result): result.add(cc) return result def _element_constructor_(self, *data, **options): '\n Build an element of ``self``.\n\n TESTS::\n\n sage: C = Constellations([(3,1),(3,1),(2,2)])\n sage: c = C([(2,3,4),(1,2,3),((1,2),(3,4))]); c\n Constellation of length 3 and degree 4\n g0 (1)(2,3,4)\n g1 (1,2,3)(4)\n g2 (1,2)(3,4)\n sage: C([(1,2,3),(3,2,4),None])\n Traceback (most recent call last):\n ...\n ValueError: wrong profile\n ' c = self._cd(*data, **options) if (options.get('check', True) and (c.profile() != self._profile)): raise ValueError('wrong profile') return c def __iter__(self): "\n Iterator of the elements in ``self``.\n\n TESTS::\n\n sage: C = Constellations([(3,1),(3,1),(2,2)])\n sage: for c in C: print(c)\n Constellation of length 3 and degree 4\n g0 (1)(2,3,4)\n g1 (1,2,3)(4)\n g2 (1,2)(3,4)\n Constellation of length 3 and degree 4\n g0 (1)(2,3,4)\n g1 (1,4,2)(3)\n g2 (1,4)(2,3)\n ...\n Constellation of length 3 and degree 4\n g0 (1,4,3)(2)\n g1 (1,2,3)(4)\n g2 (1,4)(2,3)\n Constellation of length 3 and degree 4\n g0 (1,4,3)(2)\n g1 (1,4,2)(3)\n g2 (1,2)(3,4)\n\n sage: C = Constellations([(3,1),(3,1),(2,2)], domain='abcd')\n sage: for c in sorted(C): print(c)\n Constellation of length 3 and degree 4\n g0 ('a')('b','c','d')\n g1 ('a','b','c')('d')\n g2 ('a','b')('c','d')\n ...\n Constellation of length 3 and degree 4\n g0 ('a','d','c')('b')\n g1 ('a','d','b')('c')\n g2 ('a','b')('c','d')\n " if (self._cd._length == 1): if (self._cd._degree == 1): (yield self([[0]])) return S = self._cd._sym profile = list(self._profile)[:(- 1)] for p in product(*[S.conjugacy_class(pi) for pi in profile]): if (self._cd._connected and (not perms_are_connected(p, self._cd._degree))): continue c = self._cd((list(p) + [None]), check=False) if (c.profile() == self._profile): (yield c)
def perm_sym_domain(g): "\n Return the domain of a single permutation (before initialization).\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perm_sym_domain\n sage: perm_sym_domain([1,2,3,4])\n {1, 2, 3, 4}\n sage: perm_sym_domain(((1,2),(0,4)))\n {0, 1, 2, 4}\n sage: sorted(perm_sym_domain('(1,2,0,5)'))\n [0, 1, 2, 5]\n " if isinstance(g, (tuple, list)): if isinstance(g[0], tuple): return set().union(*g) else: return set(g) elif isinstance(g, str): assert (g.startswith('(') and g.endswith(')')) domain = set().union(*[a for cyc in g[1:(- 1)].split(')(') for a in cyc.split(',')]) if all((s.isdigit() for s in domain)): return [int(x) for x in domain] else: return domain elif (parent(g) in Groups): return g.domain() else: raise TypeError
def perms_sym_init(g, sym=None): "\n Initialize a list of permutations (in the same symmetric group).\n\n OUTPUT:\n\n - ``sym`` -- a symmetric group\n\n - ``gg`` -- a list of permutations\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perms_sym_init\n sage: S, g = perms_sym_init([[0,2,1,3], [1,3,2,0]])\n sage: S.domain()\n {0, 1, 2, 3}\n sage: g\n [(1,2), (0,1,3)]\n\n sage: S, g = perms_sym_init(['(2,1)', '(0,3)'])\n sage: S.domain()\n {0, 1, 2, 3}\n sage: g\n [(1,2), (0,3)]\n\n sage: S, g = perms_sym_init([(1,0), (2,1)])\n sage: S.domain()\n {0, 1, 2}\n sage: g\n [(0,1), (1,2)]\n\n sage: S, g = perms_sym_init([((1,0),(2,3)), '(0,1,4)'])\n sage: S.domain()\n {0, 1, 2, 3, 4}\n sage: g\n [(0,1)(2,3), (0,1,4)]\n " if ((g is None) or (len(g) == 0)): if (sym is None): sym = SymmetricGroup(0) return (sym, [sym([])]) if (sym is None): domain = set().union(*[perm_sym_domain(gg) for gg in g]) if all(((isinstance(s, (int, Integer)) and (s > 0)) for s in domain)): domain = max(domain) else: domain = sorted(domain) sym = SymmetricGroup(domain) try: return (sym, [sym(u) for u in g]) except (ValueError, TypeError): return (sym, None)
def perms_are_connected(g, n): '\n Checks that the action of the generated group is transitive\n\n INPUT:\n\n - a list of permutations of `[0, n-1]` (in a SymmetricGroup)\n\n - an integer `n`\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perms_are_connected\n sage: S = SymmetricGroup(range(3))\n sage: perms_are_connected([S([0,1,2]),S([0,2,1])],3)\n False\n sage: perms_are_connected([S([0,1,2]),S([1,2,0])],3)\n True\n ' from sage.graphs.graph import Graph G = Graph() if g: G.add_vertices(g[0].domain()) for p in g: G.add_edges(p.dict().items(), loops=False) return G.is_connected()
def perms_canonical_labels_from(x, y, j0, verbose=False): '\n Return canonical labels for ``x``, ``y`` that starts at ``j0``\n\n .. WARNING::\n\n The group generated by ``x`` and the elements of ``y`` should be\n transitive.\n\n INPUT:\n\n - ``x`` -- list - a permutation of `[0, ..., n]` as a list\n\n - ``y`` -- list of permutations of `[0, ..., n]` as a list of lists\n\n - ``j0`` -- an index in [0, ..., n]\n\n OUTPUT:\n\n mapping: a permutation that specify the new labels\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perms_canonical_labels_from\n sage: perms_canonical_labels_from([0,1,2],[[1,2,0]], 0)\n [0, 1, 2]\n sage: perms_canonical_labels_from([1,0,2], [[2,0,1]], 0)\n [0, 1, 2]\n sage: perms_canonical_labels_from([1,0,2], [[2,0,1]], 1)\n [1, 0, 2]\n sage: perms_canonical_labels_from([1,0,2], [[2,0,1]], 2)\n [2, 1, 0]\n ' n = len(x) k = 0 mapping = ([None] * n) waiting = [[] for _ in repeat(None, len(y))] while (k < n): if verbose: print('complete from {}'.format(j0)) mapping[j0] = k waiting[0].append(j0) k += 1 j = x[j0] while (j != j0): mapping[j] = k waiting[0].append(j) k += 1 j = x[j] if verbose: print('completed cycle mapping = {}'.format(mapping)) if verbose: print('try to find somebody in {}'.format(waiting)) l = 0 while (l < len(waiting)): i = 0 while (i < len(waiting[l])): j1 = waiting[l][i] if (mapping[y[l][j1]] is None): break i += 1 if (i == len(waiting[l])): if (l < (len(waiting) - 1)): waiting[(l + 1)].extend(waiting[l]) waiting[l] = [] l += 1 i = 0 else: j0 = y[l][j1] if (l < (len(waiting) - 1)): waiting[(l + 1)].extend(waiting[l][:(i + 1)]) del waiting[l][:(i + 1)] break return mapping
def perm_invert(p): '\n Return the inverse of the permutation `p`.\n\n INPUT:\n\n a permutation of {0,..,n-1} given by a list of values\n\n OUTPUT:\n\n a permutation of {0,..,n-1} given by a list of values\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perm_invert\n sage: perm_invert([3,2,0,1])\n [2, 3, 1, 0]\n ' q = ([None] * len(p)) for (i, j) in enumerate(p): q[j] = i return q
def perm_conjugate(p, s): '\n Return the conjugate of the permutation `p` by the permutation `s`.\n\n INPUT:\n\n two permutations of {0,..,n-1} given by lists of values\n\n OUTPUT:\n\n a permutation of {0,..,n-1} given by a list of values\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perm_conjugate\n sage: perm_conjugate([3,1,2,0], [3,2,0,1])\n [0, 3, 2, 1]\n ' q = ([None] * len(p)) for i in range(len(p)): q[s[i]] = s[p[i]] return q
def perms_canonical_labels(p, e=None): '\n Relabel a list with a common conjugation such that two conjugated\n lists are relabeled the same way.\n\n INPUT:\n\n - ``p`` is a list of at least 2 permutations\n\n - ``e`` is None or a list of integer in the domain of the\n permutations. If provided, then the renumbering algorithm is\n only performed from the elements of ``e``.\n\n OUTPUT:\n\n - a pair made of a list of permutations (as a list of lists) and a\n list that corresponds to the conjugacy used.\n\n EXAMPLES::\n\n sage: from sage.combinat.constellation import perms_canonical_labels\n sage: l0 = [[2,0,3,1], [3,1,2,0], [0,2,1,3]]\n sage: l, m = perms_canonical_labels(l0); l\n [[1, 2, 3, 0], [0, 3, 2, 1], [2, 1, 0, 3]]\n\n sage: S = SymmetricGroup(range(4))\n sage: [~S(m) * S(u) * S(m) for u in l0] == list(map(S, l))\n True\n\n sage: perms_canonical_labels([])\n Traceback (most recent call last):\n ...\n ValueError: input must have length >= 2\n ' if (not (len(p) > 1)): raise ValueError('input must have length >= 2') n = len(p[0]) c_win = None m_win = list(range(n)) x = p[0] y = p[1:] if (e is None): e = list(range(n)) while e: i = e.pop() m_test = perms_canonical_labels_from(x, y, i) c_test = [perm_conjugate(u, m_test) for u in p] if ((c_win is None) or (c_test < c_win)): c_win = c_test m_win = m_test return (c_win, m_win)
class Core(CombinatorialElement): '\n A `k`-core is an integer partition from which no rim hook of size `k`\n can be removed.\n\n EXAMPLES::\n\n sage: c = Core([2,1],4); c\n [2, 1]\n sage: c = Core([3,1],4); c\n Traceback (most recent call last):\n ...\n ValueError: [3, 1] is not a 4-core\n ' @staticmethod def __classcall_private__(cls, part, k): "\n Implement the shortcut ``Core(part, k)`` to ``Cores(k,l)(part)``\n where `l` is the length of the core.\n\n TESTS::\n\n sage: c = Core([2,1],4); c\n [2, 1]\n sage: c.parent()\n 4-Cores of length 3\n sage: type(c)\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n\n sage: Core([2,1],3)\n Traceback (most recent call last):\n ...\n ValueError: [2, 1] is not a 3-core\n " if isinstance(part, cls): return part part = Partition(part) if (not part.is_core(k)): raise ValueError(('%s is not a %s-core' % (part, k))) l = sum(part.k_boundary(k).row_lengths()) return Cores(k, l)(part) def __init__(self, parent, core): "\n TESTS::\n\n sage: C = Cores(4,3)\n sage: c = C([2,1]); c\n [2, 1]\n sage: type(c)\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: c.parent()\n 4-Cores of length 3\n sage: TestSuite(c).run()\n\n sage: C = Cores(3,3)\n sage: C([2,1])\n Traceback (most recent call last):\n ...\n ValueError: [2, 1] is not a 3-core\n " k = parent.k part = Partition(core) if (not part.is_core(k)): raise ValueError(('%s is not a %s-core' % (part, k))) CombinatorialElement.__init__(self, parent, core) def __eq__(self, other): '\n Test for equality.\n\n EXAMPLES::\n\n sage: c = Core([4,2,1,1],5)\n sage: d = Core([4,2,1,1],5)\n sage: e = Core([4,2,1,1],6)\n sage: c == [4,2,1,1]\n False\n sage: c == d\n True\n sage: c == e\n False\n ' if isinstance(other, Core): return ((self._list == other._list) and (self.parent().k == other.parent().k)) return False def __ne__(self, other): '\n Test for un-equality.\n\n EXAMPLES::\n\n sage: c = Core([4,2,1,1],5)\n sage: d = Core([4,2,1,1],5)\n sage: e = Core([4,2,1,1],6)\n sage: c != [4,2,1,1]\n True\n sage: c != d\n False\n sage: c != e\n True\n ' return (not (self == other)) def __hash__(self): '\n Compute the hash of ``self`` by computing the hash of the\n underlying list and of the additional parameter.\n\n The hash is cached and stored in ``self._hash``.\n\n EXAMPLES::\n\n sage: c = Core([4,2,1,1],3)\n sage: c._hash is None\n True\n sage: hash(c) #random\n 1335416675971793195\n sage: c._hash #random\n 1335416675971793195\n\n TESTS::\n\n sage: c = Core([4,2,1,1],5)\n sage: d = Core([4,2,1,1],6)\n sage: hash(c) == hash(d)\n False\n ' if (self._hash is None): self._hash = (hash(tuple(self._list)) + hash(self.parent().k)) return self._hash def _latex_(self): '\n Output the LaTeX representation of this core as a partition.\n\n See the ``_latex_`` method of :class:`Partition`.\n\n EXAMPLES::\n\n sage: c = Core([2,1],4)\n sage: latex(c)\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 ' return self.to_partition()._latex_() def k(self): '\n Return `k` of the `k`-core ``self``.\n\n EXAMPLES::\n\n sage: c = Core([2,1],4)\n sage: c.k()\n 4\n ' return self.parent().k @combinatorial_map(name='to partition') def to_partition(self): '\n Turn the core ``self`` into the partition identical to ``self``.\n\n EXAMPLES::\n\n sage: mu = Core([2,1,1],3)\n sage: mu.to_partition()\n [2, 1, 1]\n ' return Partition(self) @combinatorial_map(name='to bounded partition') def to_bounded_partition(self): '\n Bijection between `k`-cores and `(k-1)`-bounded partitions.\n\n This maps the `k`-core ``self`` to the corresponding `(k-1)`-bounded partition.\n This bijection is achieved by deleting all cells in ``self`` of hook length\n greater than `k`.\n\n EXAMPLES::\n\n sage: gamma = Core([9,5,3,2,1,1], 5)\n sage: gamma.to_bounded_partition()\n [4, 3, 2, 2, 1, 1]\n ' k_boundary = self.to_partition().k_boundary(self.k()) return Partition(k_boundary.row_lengths()) def size(self): '\n Return the size of ``self`` as a partition.\n\n EXAMPLES::\n\n sage: Core([2,1],4).size()\n 3\n sage: Core([4,2],3).size()\n 6\n ' return self.to_partition().size() def length(self): '\n Return the length of ``self``.\n\n The length of a `k`-core is the size of the corresponding `(k-1)`-bounded partition\n which agrees with the length of the corresponding Grassmannian element,\n see :meth:`to_grassmannian`.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3); c.length()\n 4\n sage: c.to_grassmannian().length() # needs sage.modules\n 4\n\n sage: Core([9,5,3,2,1,1], 5).length()\n 13\n ' return self.to_bounded_partition().size() def to_grassmannian(self): "\n Bijection between `k`-cores and Grassmannian elements in the affine Weyl group of type `A_{k-1}^{(1)}`.\n\n For further details, see the documentation of the method\n :meth:`~sage.combinat.partition.Partition.from_kbounded_to_reduced_word` and\n :meth:`~sage.combinat.partition.Partition.from_kbounded_to_grassmannian`.\n\n EXAMPLES::\n\n sage: c = Core([3,1,1],3)\n sage: w = c.to_grassmannian(); w # needs sage.modules\n [-1 1 1]\n [-2 2 1]\n [-2 1 2]\n sage: c.parent()\n 3-Cores of length 4\n sage: w.parent() # needs sage.modules\n Weyl Group of type ['A', 2, 1] (as a matrix group acting on the root space)\n\n sage: c = Core([],3)\n sage: c.to_grassmannian() # needs sage.modules\n [1 0 0]\n [0 1 0]\n [0 0 1]\n " bp = self.to_bounded_partition() return bp.from_kbounded_to_grassmannian((self.k() - 1)) def affine_symmetric_group_simple_action(self, i): '\n Return the action of the simple transposition `s_i` of the affine symmetric group on ``self``.\n\n This gives the action of the affine symmetric group of type `A_k^{(1)}` on the `k`-core\n ``self``. If ``self`` has outside (resp. inside) corners of content `i` modulo `k`, then\n these corners are added (resp. removed). Otherwise the action is trivial.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3)\n sage: c.affine_symmetric_group_simple_action(0) # needs sage.modules\n [3, 1]\n sage: c.affine_symmetric_group_simple_action(1) # needs sage.modules\n [5, 3, 1]\n sage: c.affine_symmetric_group_simple_action(2) # needs sage.modules\n [4, 2]\n\n This action corresponds to the left action by the `i`-th simple reflection in the affine\n symmetric group::\n\n sage: c = Core([4,2],3)\n sage: W = c.to_grassmannian().parent() # needs sage.modules\n sage: i = 0\n sage: (c.affine_symmetric_group_simple_action(i).to_grassmannian() # needs sage.modules\n ....: == W.simple_reflection(i)*c.to_grassmannian())\n True\n sage: i = 1\n sage: (c.affine_symmetric_group_simple_action(i).to_grassmannian() # needs sage.modules\n ....: == W.simple_reflection(i)*c.to_grassmannian())\n True\n ' mu = self.to_partition() corners = [p for p in mu.outside_corners() if ((mu.content(p[0], p[1]) % self.k()) == i)] if (not corners): corners = [p for p in mu.corners() if ((mu.content(p[0], p[1]) % self.k()) == i)] if (not corners): return self for p in corners: mu = mu.remove_cell(p[0]) else: for p in corners: mu = mu.add_cell(p[0]) return Core(mu, self.k()) def affine_symmetric_group_action(self, w, transposition=False): '\n Return the (left) action of the affine symmetric group on ``self``.\n\n INPUT:\n\n - ``w`` is a tuple of integers `[w_1,\\ldots,w_m]` with `0\\le w_j<k`.\n If transposition is set to be True, then `w = [w_0,w_1]` is\n interpreted as a transposition `t_{w_0, w_1}`\n (see :meth:`_transposition_to_reduced_word`).\n\n The output is the (left) action of the product of the corresponding simple transpositions\n on ``self``, that is `s_{w_1} \\cdots s_{w_m}(self)`. See :meth:`affine_symmetric_group_simple_action`.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3)\n sage: c.affine_symmetric_group_action([0,1,0,2,1])\n [8, 6, 4, 2]\n sage: c.affine_symmetric_group_action([0,2], transposition=True)\n [4, 2, 1, 1]\n\n sage: c = Core([11,8,5,5,3,3,1,1,1],4)\n sage: c.affine_symmetric_group_action([2,5],transposition=True)\n [11, 8, 7, 6, 5, 4, 3, 2, 1]\n ' c = self if transposition: w = self._transposition_to_reduced_word(w) w.reverse() for i in w: c = c.affine_symmetric_group_simple_action(i) return c def _transposition_to_reduced_word(self, t): '\n Converts the transposition `t = [r,s]` to a reduced word.\n\n INPUT:\n\n - a tuple `[r,s]` such that `r` and `s` are not equivalent mod `k`\n\n OUTPUT:\n\n - a list of integers in `\\{0,1,\\ldots,k-1\\}` representing a reduced word for the transposition `t`\n\n EXAMPLES::\n\n sage: c = Core([],4)\n sage: c._transposition_to_reduced_word([2, 5])\n [2, 3, 0, 3, 2]\n sage: c._transposition_to_reduced_word([2, 5]) == c._transposition_to_reduced_word([5,2])\n True\n sage: c._transposition_to_reduced_word([2, 2])\n Traceback (most recent call last):\n ...\n ValueError: t_0 and t_1 cannot be equal mod k\n\n sage: c = Core([],30)\n sage: c._transposition_to_reduced_word([4, 12])\n [4, 5, 6, 7, 8, 9, 10, 11, 10, 9, 8, 7, 6, 5, 4]\n\n sage: c = Core([],3)\n sage: c._transposition_to_reduced_word([4, 12])\n [1, 2, 0, 1, 2, 0, 2, 1, 0, 2, 1]\n ' k = self.k() if (((t[0] - t[1]) % k) == 0): raise ValueError('t_0 and t_1 cannot be equal mod k') if (t[0] > t[1]): return self._transposition_to_reduced_word([t[1], t[0]]) else: resu = [(i % k) for i in range(t[0], (t[1] - ((t[1] - t[0]) // k)))] resu += [((((t[1] - ((t[1] - t[0]) // k)) - 2) - i) % k) for i in range((((t[1] - ((t[1] - t[0]) // k)) - t[0]) - 1))] return resu def weak_le(self, other): '\n Weak order comparison on cores.\n\n INPUT:\n\n - ``other`` -- another `k`-core\n\n OUTPUT: a boolean\n\n This returns whether ``self`` <= ``other`` in weak order.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3)\n sage: x = Core([5,3,1],3)\n sage: c.weak_le(x) # needs sage.modules\n True\n sage: c.weak_le([5,3,1]) # needs sage.modules\n True\n\n sage: x = Core([4,2,2,1,1],3)\n sage: c.weak_le(x) # needs sage.modules\n False\n\n sage: x = Core([5,3,1],6)\n sage: c.weak_le(x)\n Traceback (most recent call last):\n ...\n ValueError: the two cores do not have the same k\n ' if (type(self) is type(other)): if (self.k() != other.k()): raise ValueError('the two cores do not have the same k') else: other = Core(other, self.k()) w = self.to_grassmannian() v = other.to_grassmannian() return w.weak_le(v, side='left') def weak_covers(self): '\n Return a list of all elements that cover ``self`` in weak order.\n\n EXAMPLES::\n\n sage: c = Core([1],3)\n sage: c.weak_covers() # needs sage.modules\n [[1, 1], [2]]\n\n sage: c = Core([4,2],3)\n sage: c.weak_covers() # needs sage.modules\n [[5, 3, 1]]\n ' w = self.to_grassmannian() S = w.upper_covers(side='left') S = (x for x in S if x.is_affine_grassmannian()) return [x.affine_grassmannian_to_core() for x in set(S)] def strong_le(self, other): '\n Strong order (Bruhat) comparison on cores.\n\n INPUT:\n\n - ``other`` -- another `k`-core\n\n OUTPUT: a boolean\n\n This returns whether ``self`` <= ``other`` in Bruhat (or strong) order.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3)\n sage: x = Core([4,2,2,1,1],3)\n sage: c.strong_le(x)\n True\n sage: c.strong_le([4,2,2,1,1])\n True\n\n sage: x = Core([4,1],4)\n sage: c.strong_le(x)\n Traceback (most recent call last):\n ...\n ValueError: the two cores do not have the same k\n ' if (type(self) is type(other)): if (self.k() != other.k()): raise ValueError('the two cores do not have the same k') else: other = Core(other, self.k()) return other.contains(self) def contains(self, other): '\n Checks whether ``self`` contains ``other``.\n\n INPUT:\n\n - ``other`` -- another `k`-core or a list\n\n OUTPUT: a boolean\n\n This returns ``True`` if the Ferrers diagram of ``self`` contains the\n Ferrers diagram of ``other``.\n\n EXAMPLES::\n\n sage: c = Core([4,2],3)\n sage: x = Core([4,2,2,1,1],3)\n sage: x.contains(c)\n True\n sage: c.contains(x)\n False\n ' la = self.to_partition() mu = Core(other, self.k()).to_partition() return la.contains(mu) def strong_covers(self): '\n Return a list of all elements that cover ``self`` in strong order.\n\n EXAMPLES::\n\n sage: c = Core([1],3)\n sage: c.strong_covers()\n [[2], [1, 1]]\n sage: c = Core([4,2],3)\n sage: c.strong_covers()\n [[5, 3, 1], [4, 2, 1, 1]]\n ' S = Cores(self.k(), length=(self.length() + 1)) return [ga for ga in S if ga.contains(self)] def strong_down_list(self): '\n Return a list of all elements that are covered by ``self`` in strong order.\n\n EXAMPLES::\n\n sage: c = Core([1],3)\n sage: c.strong_down_list()\n [[]]\n sage: c = Core([5,3,1],3)\n sage: c.strong_down_list()\n [[4, 2], [3, 1, 1]]\n ' if (not self): return [] return [ga for ga in Cores(self.k(), length=(self.length() - 1)) if self.contains(ga)]
def Cores(k, length=None, **kwargs): '\n A `k`-core is a partition from which no rim hook of size `k` can be removed.\n Alternatively, a `k`-core is an integer partition such that the Ferrers\n diagram for the partition contains no cells with a hook of size (a multiple of) `k`.\n\n The `k`-cores generally have two notions of size which are\n useful for different applications. One is the number of cells in the\n Ferrers diagram with hook less than `k`, the other is the total\n number of cells of the Ferrers diagram. In the implementation in\n Sage, the first of notion is referred to as the ``length`` of the `k`-core\n and the second is the ``size`` of the `k`-core. The class\n of Cores requires that either the size or the length of the elements in\n the class is specified.\n\n EXAMPLES:\n\n We create the set of the `4`-cores of length `6`. Here the length of a `k`-core is the size\n of the corresponding `(k-1)`-bounded partition, see also :meth:`~sage.combinat.core.Core.length`::\n\n sage: C = Cores(4, 6); C\n 4-Cores of length 6\n sage: C.list()\n [[6, 3], [5, 2, 1], [4, 1, 1, 1], [4, 2, 2], [3, 3, 1, 1], [3, 2, 1, 1, 1], [2, 2, 2, 1, 1, 1]]\n sage: C.cardinality()\n 7\n sage: C.an_element()\n [6, 3]\n\n We may also list the set of `4`-cores of size `6`, where the size is the number of boxes in the\n core, see also :meth:`~sage.combinat.core.Core.size`::\n\n sage: C = Cores(4, size=6); C\n 4-Cores of size 6\n sage: C.list()\n [[4, 1, 1], [3, 2, 1], [3, 1, 1, 1]]\n sage: C.cardinality()\n 3\n sage: C.an_element()\n [4, 1, 1]\n ' if ((length is None) and ('size' in kwargs)): return Cores_size(k, kwargs['size']) if (length is not None): return Cores_length(k, length) raise ValueError('you need to either specify the length or size of the cores considered')
class Cores_length(UniqueRepresentation, Parent): '\n The class of `k`-cores of length `n`.\n ' def __init__(self, k, n): '\n TESTS::\n\n sage: C = Cores(3, 4)\n sage: TestSuite(C).run()\n\n ' self.k = k self.n = n Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): "\n TESTS::\n\n sage: repr(Cores(4, 3)) #indirect doctest\n '4-Cores of length 3'\n " return ('%s-Cores of length %s' % (self.k, self.n)) def list(self): '\n Return the list of all `k`-cores of length `n`.\n\n EXAMPLES::\n\n sage: C = Cores(3,4)\n sage: C.list()\n [[4, 2], [3, 1, 1], [2, 2, 1, 1]]\n ' return [la.to_core((self.k - 1)) for la in Partitions(self.n, max_part=(self.k - 1))] def from_partition(self, part): '\n Converts the partition ``part`` into a core (as the identity map).\n\n This is the inverse method to :meth:`~sage.combinat.core.Core.to_partition`.\n\n EXAMPLES::\n\n sage: C = Cores(3,4)\n sage: c = C.from_partition([4,2]); c\n [4, 2]\n\n sage: mu = Partition([2,1,1])\n sage: C = Cores(3,3)\n sage: C.from_partition(mu).to_partition() == mu\n True\n\n sage: mu = Partition([])\n sage: C = Cores(3,0)\n sage: C.from_partition(mu).to_partition() == mu\n True\n ' return Core(part, self.k) Element = Core
class Cores_size(UniqueRepresentation, Parent): '\n The class of `k`-cores of size `n`.\n ' def __init__(self, k, n): '\n TESTS::\n\n sage: C = Cores(3, size = 4)\n sage: TestSuite(C).run()\n ' self.k = k self.n = n Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): "\n TESTS::\n\n sage: repr(Cores(4, size = 3)) #indirect doctest\n '4-Cores of size 3'\n " return ('%s-Cores of size %s' % (self.k, self.n)) def list(self): '\n Return the list of all `k`-cores of size `n`.\n\n EXAMPLES::\n\n sage: C = Cores(3, size = 4)\n sage: C.list()\n [[3, 1], [2, 1, 1]]\n ' return [Core(x, self.k) for x in Partitions(self.n) if x.is_core(self.k)] def from_partition(self, part): '\n Convert the partition ``part`` into a core (as the identity map).\n\n This is the inverse method to :meth:`to_partition`.\n\n EXAMPLES::\n\n sage: C = Cores(3,size=4)\n sage: c = C.from_partition([2,1,1]); c\n [2, 1, 1]\n\n sage: mu = Partition([2,1,1])\n sage: C = Cores(3,size=4)\n sage: C.from_partition(mu).to_partition() == mu\n True\n\n sage: mu = Partition([])\n sage: C = Cores(3,size=0)\n sage: C.from_partition(mu).to_partition() == mu\n True\n ' return Core(part, self.k) Element = Core
class AffineCrystalFromClassical(UniqueRepresentation, Parent): '\n This abstract class can be used for affine crystals that are constructed\n from a classical crystal. The zero arrows can be implemented using\n different methods (for example using a Dynkin diagram automorphisms or\n virtual crystals).\n\n This is a helper class, mostly used to implement Kirillov-Reshetikhin\n crystals (see:\n :func:`~sage.combinat.crystals.kirillov_reshetikhin.KirillovReshetikhinCrystal`).\n\n For general information about crystals see :mod:`sage.combinat.crystals`.\n\n INPUT:\n\n - ``cartan_type`` -- the Cartan type of the resulting affine crystal\n\n - ``classical_crystal`` -- instance of a classical crystal\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: A.list()\n [[[1]], [[2]], [[3]]]\n sage: A.cartan_type()\n [\'A\', 2, 1]\n sage: A.index_set()\n (0, 1, 2)\n sage: b = A(rows=[[1]])\n sage: b.weight()\n -Lambda[0] + Lambda[1]\n sage: b.classical_weight()\n (1, 0, 0)\n sage: [x.s(0) for x in A.list()]\n [[[3]], [[2]], [[1]]]\n sage: [x.s(1) for x in A.list()]\n [[[2]], [[1]], [[3]]]\n ' @staticmethod def __classcall__(cls, cartan_type, *args, **options): '\n TESTS::\n\n sage: n = 1\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1) # indirect doctest\n sage: B = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1) # indirect doctest\n sage: A is B\n True\n ' ct = CartanType(cartan_type) return super().__classcall__(cls, ct, *args, **options) def __init__(self, cartan_type, classical_crystal, category=None): '\n Input is an affine Cartan type ``cartan_type``, a classical crystal\n ``classical_crystal``, and automorphism and its inverse\n ``automorphism`` and ``inverse_automorphism``, and the Dynkin node\n ``dynkin_node``.\n\n EXAMPLES::\n\n sage: n = 1\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1) # indirect doctest\n sage: A.list()\n [[[1]], [[2]]]\n sage: A.cartan_type()\n [\'A\', 1, 1]\n sage: A.index_set()\n (0, 1)\n\n .. NOTE::\n\n :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassical`\n is an abstract class, so we can\'t test it directly.\n\n TESTS::\n\n sage: TestSuite(A).run()\n ' if (category is None): category = RegularLoopCrystals() self._cartan_type = cartan_type Parent.__init__(self, category=category) self.classical_crystal = classical_crystal self.module_generators = [self.retract(gen) for gen in self.classical_crystal.module_generators] self.element_class._latex_ = (lambda x: x.lift()._latex_()) def _repr_(self): '\n EXAMPLES::\n\n sage: n = 1\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1) # indirect doctest\n An affine crystal for type [\'A\', 1, 1]\n ' return 'An affine crystal for type {}'.format(self.cartan_type()) def cardinality(self): '\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux([\'A\',3],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',3,1],C,pr,pr_inverse,1)\n sage: A.cardinality() == C.cardinality()\n True\n ' return self.classical_crystal.cardinality() def __iter__(self): '\n Construct the iterator from the underlying classical crystal.\n\n TESTS::\n\n sage: n = 1\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1) # indirect doctest\n sage: A.list() # indirect doctest\n [[[1]], [[2]]]\n ' for x in self.classical_crystal: (yield self.retract(x)) def lift(self, affine_elt): '\n Lift an affine crystal element to the corresponding classical\n crystal element.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A.list()[0]\n sage: A.lift(b)\n [[1]]\n sage: A.lift(b).parent()\n The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]]\n ' return affine_elt.lift() def retract(self, classical_elt): '\n Transform a classical crystal element to the corresponding\n affine crystal element.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: t = C(rows=[[1]])\n sage: t.parent()\n The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]]\n sage: A.retract(t)\n [[1]]\n sage: A.retract(t).parent() is A\n True\n ' return self.element_class(self, classical_elt) def _element_constructor_(self, *value, **options): '\n Coerces ``value`` into ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]]) # indirect doctest\n sage: b\n [[1]]\n sage: b.parent()\n An affine crystal for type [\'A\', 2, 1]\n sage: A(b) is b\n True\n ' if ((len(value) == 1) and isinstance(value[0], self.element_class) and (value[0].parent() == self)): return value[0] else: return self.retract(self.classical_crystal(*value, **options)) def __contains__(self, x): '\n Checks whether ``x`` is an element of ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: A.__contains__(b)\n True\n ' return (x.parent() is self)
class AffineCrystalFromClassicalElement(ElementWrapper): '\n Elements of crystals that are constructed from a classical crystal.\n\n The elements inherit many of their methods from the classical crystal\n using lift and retract.\n\n This class is not instantiated directly but rather ``__call__``-ed from\n :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassical`.\n The syntax of this is governed by the (classical) crystal.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: b._repr_()\n \'[[1]]\'\n ' def classical_weight(self): '\n Return the classical weight corresponding to ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: b.classical_weight()\n (1, 0, 0)\n ' return self.lift().weight() def lift(self): '\n Lift an affine crystal element to the corresponding classical\n crystal element.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A.list()[0]\n sage: b.lift()\n [[1]]\n sage: b.lift().parent()\n The crystal of tableaux of type [\'A\', 2] and shape(s) [[1]]\n ' return self.value def pp(self): "\n Method for pretty printing.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['D',3,2],1,1)\n sage: t=K(rows=[[1]])\n sage: t.pp()\n 1\n " return self.lift().pp() @abstract_method def e0(self): '\n Assumes that `e_0` is implemented separately.\n ' @abstract_method def f0(self): '\n Assumes that `f_0` is implemented separately.\n ' def e(self, i): '\n Return the action of `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: b.e(0)\n [[3]]\n sage: b.e(1)\n ' if (i == self.parent()._cartan_type.special_node()): return self.e0() else: x = self.lift().e(i) if (x is None): return None else: return self.parent().retract(x) def f(self, i): '\n Return the action of `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[3]])\n sage: b.f(0)\n [[1]]\n sage: b.f(2)\n ' if (i == self.parent()._cartan_type.special_node()): return self.f0() else: x = self.lift().f(i) if (x is None): return None else: return self.parent().retract(x) def epsilon0(self): '\n Uses `\\varepsilon_0` from the super class, but should be implemented\n if a faster implementation exists.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.epsilon0() for x in A.list()]\n [1, 0, 0]\n ' return super().epsilon(0) def epsilon(self, i): '\n Return the maximal time the crystal operator `e_i`\n can be applied to ``self``.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.epsilon(0) for x in A.list()]\n [1, 0, 0]\n sage: [x.epsilon(1) for x in A.list()]\n [0, 1, 0]\n ' if (i == self.parent()._cartan_type.special_node()): return self.epsilon0() else: return self.lift().epsilon(i) def phi0(self): '\n Uses `\\varphi_0` from the super class, but should be implemented\n if a faster implementation exists.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.phi0() for x in A.list()]\n [0, 0, 1]\n ' return super().phi(0) def phi(self, i): '\n Returns the maximal time the crystal operator `f_i` can be applied to self.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.phi(0) for x in A.list()]\n [0, 0, 1]\n sage: [x.phi(1) for x in A.list()]\n [1, 0, 0]\n ' if (i == self.parent()._cartan_type.special_node()): return self.phi0() else: return self.lift().phi(i) def _richcmp_(self, other, op): "\n Elements of this crystal are compared using the comparison in\n the underlying classical crystal.\n\n Non elements of the crystal are not comparable with elements of the\n crystal, so we return ``NotImplemented``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: b = K(rows=[[1]])\n sage: c = K(rows=[[2]])\n\n sage: b == c\n False\n sage: b == b\n True\n\n sage: b != c\n True\n sage: b != b\n False\n\n sage: c < b\n False\n sage: b < b\n False\n sage: b < c\n True\n\n sage: b > c\n False\n sage: b > b\n False\n sage: c > b\n True\n\n sage: b <= c\n True\n sage: b <= b\n True\n sage: c <= b\n False\n\n sage: c >= b\n True\n sage: b >= b\n True\n sage: b >= c\n False\n " return richcmp(self.value, other.value, op)
class AffineCrystalFromClassicalAndPromotion(AffineCrystalFromClassical): '\n Crystals that are constructed from a classical crystal and a\n Dynkin diagram automorphism `\\sigma`. In type `A_n`, the Dynkin\n diagram automorphism is `i \\to i+1 \\pmod n+1` and the\n corresponding map on the crystal is the promotion operation\n `\\mathrm{pr}` on tableaux. The affine crystal operators are given\n by `f_0= \\mathrm{pr}^{-1} f_{\\sigma(0)} \\mathrm{pr}`.\n\n INPUT:\n\n - ``cartan_type`` -- the Cartan type of the resulting affine crystal\n\n - ``classical_crystal`` -- instance of a classical crystal\n\n - ``automorphism, inverse_automorphism`` -- a function on the\n elements of the ``classical_crystal``\n\n - ``dynkin_node`` -- an integer specifying the classical node in the\n image of the zero node under the automorphism sigma\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: A.list()\n [[[1]], [[2]], [[3]]]\n sage: A.cartan_type()\n [\'A\', 2, 1]\n sage: A.index_set()\n (0, 1, 2)\n sage: b = A(rows=[[1]])\n sage: b.weight()\n -Lambda[0] + Lambda[1]\n sage: b.classical_weight()\n (1, 0, 0)\n sage: [x.s(0) for x in A.list()]\n [[[3]], [[2]], [[1]]]\n sage: [x.s(1) for x in A.list()]\n [[[2]], [[1]], [[3]]]\n ' def __init__(self, cartan_type, classical_crystal, p_automorphism, p_inverse_automorphism, dynkin_node, category=None): '\n Input is an affine Cartan type ``cartan_type``, a classical crystal\n ``classical_crystal``, and promotion automorphism and its inverse\n ``p_automorphism`` and ``p_inverse_automorphism``, and the Dynkin\n node ``dynkin_node``.\n\n EXAMPLES::\n\n sage: n = 1\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: A.list()\n [[[1]], [[2]]]\n sage: A.cartan_type()\n [\'A\', 1, 1]\n sage: A.index_set()\n (0, 1)\n\n TESTS::\n\n sage: TestSuite(A).run()\n ' AffineCrystalFromClassical.__init__(self, cartan_type, classical_crystal, category) self.p_automorphism = p_automorphism self.p_inverse_automorphism = p_inverse_automorphism self.dynkin_node = dynkin_node def automorphism(self, x): '\n Give the analogue of the affine Dynkin diagram automorphism on\n the level of crystals.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A.list()[0]\n sage: A.automorphism(b)\n [[2]]\n ' return self.retract(self.p_automorphism(x.lift())) def inverse_automorphism(self, x): '\n Give the analogue of the inverse of the affine Dynkin diagram\n automorphism on the level of crystals.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A.list()[0]\n sage: A.inverse_automorphism(b)\n [[3]]\n ' return self.retract(self.p_inverse_automorphism(x.lift()))
class AffineCrystalFromClassicalAndPromotionElement(AffineCrystalFromClassicalElement): '\n Elements of crystals that are constructed from a classical crystal\n and a Dynkin diagram automorphism. In type `A`, the automorphism is\n the promotion operation on tableaux.\n\n This class is not instantiated directly but rather ``__call__``-ed from\n :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassicalAndPromotion`.\n The syntax of this is governed by the (classical) crystal.\n\n Since this class inherits from\n :class:`~sage.combinat.crystals.affine.AffineCrystalFromClassicalElement`,\n the methods that need to be implemented are :meth:`e0`, :meth:`f0` and\n possibly :meth:`epsilon0` and :meth:`phi0` if more efficient\n algorithms exist.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: b._repr_()\n \'[[1]]\'\n ' def e0(self): '\n Implement `e_0` using the automorphism as\n `e_0 = \\operatorname{pr}^{-1} e_{dynkin_node} \\operatorname{pr}`\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[1]])\n sage: b.e0()\n [[3]]\n ' x = self.parent().automorphism(self).e(self.parent().dynkin_node) if (x is None): return None else: return self.parent().inverse_automorphism(x) def f0(self): '\n Implement `f_0` using the automorphism as\n `f_0 = \\operatorname{pr}^{-1} f_{dynkin_node} \\operatorname{pr}`\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: b = A(rows=[[3]])\n sage: b.f0()\n [[1]]\n ' x = self.parent().automorphism(self).f(self.parent().dynkin_node) if (x is None): return None else: return self.parent().inverse_automorphism(x) def epsilon0(self): '\n Implement `epsilon_0` using the automorphism.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.epsilon0() for x in A.list()]\n [1, 0, 0]\n ' x = self.parent().automorphism(self) return x.lift().epsilon(self.parent().dynkin_node) def phi0(self): '\n Implement `phi_0` using the automorphism.\n\n EXAMPLES::\n\n sage: n = 2\n sage: C = crystals.Tableaux([\'A\',n],shape=[1])\n sage: pr = attrcall("promotion")\n sage: pr_inverse = attrcall("promotion_inverse")\n sage: A = crystals.AffineFromClassicalAndPromotion([\'A\',n,1],C,pr,pr_inverse,1)\n sage: [x.phi0() for x in A.list()]\n [0, 0, 1]\n ' x = self.parent().automorphism(self) return x.lift().phi(self.parent().dynkin_node)
class AffineFactorizationCrystal(UniqueRepresentation, Parent): "\n The crystal on affine factorizations with a cut-point, as introduced\n by [MS2015]_.\n\n INPUT:\n\n - ``w`` -- an element in an (affine) Weyl group or a skew shape of `k`-bounded partitions (if `k` was specified)\n\n - ``n`` -- the number of factors in the factorization\n\n - ``x`` -- (default: ``None``) the cut point; if not specified it is determined as the minimal missing residue in ``w``\n\n - ``k`` -- (default: ``None``) positive integer, specifies that ``w`` is `k`-bounded or a `k+1`-core when specified\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,3,2,1])\n sage: B = crystals.AffineFactorization(w,3); B\n Crystal on affine factorizations of type A2 associated to s2*s3*s2*s1\n sage: B.list()\n [(1, s2, s3*s2*s1),\n (1, s3*s2, s3*s1),\n (1, s3*s2*s1, s3),\n (s3, s2, s3*s1),\n (s3, s2*s1, s3),\n (s3*s2, s1, s3),\n (s3*s2*s1, 1, s3),\n (s3*s2*s1, s3, 1),\n (s3*s2, 1, s3*s1),\n (s3*s2, s3, s1),\n (s3*s2, s3*s1, 1),\n (s2, 1, s3*s2*s1),\n (s2, s3, s2*s1),\n (s2, s3*s2, s1),\n (s2, s3*s2*s1, 1)]\n\n We can also access the crystal by specifying a skew shape in terms of `k`-bounded partitions::\n\n sage: crystals.AffineFactorization([[3,1,1],[1]], 3, k=3)\n Crystal on affine factorizations of type A2 associated to s2*s3*s2*s1\n\n We can compute the highest weight elements::\n\n sage: hw = [w for w in B if w.is_highest_weight()]\n sage: hw\n [(1, s2, s3*s2*s1)]\n sage: hw[0].weight()\n (3, 1, 0)\n\n And show that this crystal is isomorphic to the tableau model of the same weight::\n\n sage: C = crystals.Tableaux(['A',2],shape=[3,1])\n sage: GC = C.digraph()\n sage: GB = B.digraph()\n sage: GC.is_isomorphic(GB, edge_labels=True)\n True\n\n The crystal operators themselves move elements between adjacent factors::\n\n sage: b = hw[0];b\n (1, s2, s3*s2*s1)\n sage: b.f(1)\n (1, s3*s2, s3*s1)\n\n The cut point `x` is not supposed to occur in the reduced words for `w`::\n\n sage: B = crystals.AffineFactorization([[3,2],[2]],4,x=0,k=3)\n Traceback (most recent call last):\n ...\n ValueError: x cannot be in reduced word of s0*s3*s2\n " @staticmethod def __classcall_private__(cls, w, n, x=None, k=None): '\n Classcall to mend the input.\n\n TESTS::\n\n sage: A = crystals.AffineFactorization([[3,1],[1]], 4, k=3); A\n Crystal on affine factorizations of type A3 associated to s3*s2*s1\n sage: AC = crystals.AffineFactorization([Core([4,1],4),Core([1],4)], 4, k=3)\n sage: AC is A\n True\n ' if (k is not None): from sage.combinat.core import Core from sage.combinat.partition import Partition W = WeylGroup(['A', k, 1], prefix='s') if isinstance(w[0], Core): w = [w[0].to_bounded_partition(), w[1].to_bounded_partition()] else: w = [Partition(w[0]), Partition(w[1])] w0 = W.from_reduced_word(w[0].from_kbounded_to_reduced_word(k)) w1 = W.from_reduced_word(w[1].from_kbounded_to_reduced_word(k)) w = (w0 * w1.inverse()) return super().__classcall__(cls, w, n, x) def __init__(self, w, n, x=None): "\n EXAMPLES::\n\n sage: B = crystals.AffineFactorization([[3,2],[2]],4,x=0,k=3)\n Traceback (most recent call last):\n ...\n ValueError: x cannot be in reduced word of s0*s3*s2\n\n sage: B = crystals.AffineFactorization([[3,2],[2]],4,k=3)\n sage: B.x\n 1\n sage: B.w\n s0*s3*s2\n sage: B.k\n 3\n sage: B.n\n 4\n\n TESTS::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,3,2,1])\n sage: B = crystals.AffineFactorization(w,3)\n sage: TestSuite(B).run() # long time\n " Parent.__init__(self, category=ClassicalCrystals()) self.n = n self.k = (w.parent().n - 1) self.w = w cartan_type = CartanType(['A', (n - 1)]) self._cartan_type = cartan_type from sage.combinat.sf.sf import SymmetricFunctions from sage.rings.rational_field import QQ Sym = SymmetricFunctions(QQ) s = Sym.schur() support = s(w.stanley_symmetric_function()).support() support = [(([0] * (n - len(mu))) + [mu[((len(mu) - i) - 1)] for i in range(len(mu))]) for mu in support] generators = [tuple(p) for mu in support for p in affine_factorizations(w, n, mu)] self.module_generators = [self(t) for t in generators] if (x is None): if generators: x = min(set(range((self.k + 1))).difference(set(sum([i.reduced_word() for i in generators[0]], [])))) else: x = 0 if (x in set(w.reduced_word())): raise ValueError('x cannot be in reduced word of {}'.format(w)) self.x = x def _repr_(self): "\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([3,2,1])\n sage: crystals.AffineFactorization(w,4)\n Crystal on affine factorizations of type A3 associated to s3*s2*s1\n\n sage: crystals.AffineFactorization([[3,1],[1]], 4, k=3)\n Crystal on affine factorizations of type A3 associated to s3*s2*s1\n " return 'Crystal on affine factorizations of type A{} associated to {}'.format((self.n - 1), self.w) _an_element_ = EnumeratedSets.ParentMethods._an_element_ @lazy_attribute def _tableaux_isomorphism(self): "\n Return the isomorphism from ``self`` to the tableaux model.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([3,2,1])\n sage: B = crystals.AffineFactorization(w,4)\n sage: B._tableaux_isomorphism\n ['A', 3] Crystal morphism:\n From: Crystal on affine factorizations of type A3 associated to s3*s2*s1\n To: The crystal of tableaux of type ['A', 3] and shape(s) [[3]]\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,1,3,2])\n sage: B = crystals.AffineFactorization(w,3)\n sage: B._tableaux_isomorphism\n ['A', 2] Crystal morphism:\n From: Crystal on affine factorizations of type A2 associated to s2*s3*s1*s2\n To: The crystal of tableaux of type ['A', 2] and shape(s) [[2, 2]]\n " from sage.combinat.crystals.tensor_product import CrystalOfTableaux def mg_to_shape(mg): l = list(mg.weight().to_vector()) while (l and (l[(- 1)] == 0)): l.pop() return l sh = [mg_to_shape(mg) for mg in self.highest_weight_vectors()] C = CrystalOfTableaux(self.cartan_type(), shapes=sh) phi = FactorizationToTableaux(Hom(self, C, category=self.category())) phi.register_as_coercion() return phi class Element(ElementWrapper): def e(self, i): '\n Return the action of `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.AffineFactorization([[3,1],[1]], 4, k=3)\n sage: W = B.w.parent()\n sage: t = B((W.one(),W.one(),W.from_reduced_word([3]),W.from_reduced_word([2,1]))); t\n (1, 1, s3, s2*s1)\n sage: t.e(1)\n (1, 1, 1, s3*s2*s1)\n ' if (i not in self.index_set()): raise ValueError('i must be in the index set') b = self.bracketing(i) if (not b[0]): return None W = self.parent().w.parent() x = self.parent().x k = self.parent().k n = self.parent().n a = min(b[0]) left = [j for j in self.value[((n - i) - 1)].reduced_word() if (j != ((a + x) % (k + 1)))] right = [((j - x) % (k + 1)) for j in self.value[(n - i)].reduced_word()] m = max([j for j in range(a) if (((j + x) % (k + 1)) not in left)]) right += [(m + 1)] right.sort(reverse=True) right = [((j + x) % (k + 1)) for j in right] t = ((([self.value[j] for j in range(((n - i) - 1))] + [W.from_reduced_word(left)]) + [W.from_reduced_word(right)]) + [self.value[j] for j in range(((n - i) + 1), n)]) return self.parent()(tuple(t)) def f(self, i): '\n Return the action of `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.AffineFactorization([[3,1],[1]], 4, k=3)\n sage: W = B.w.parent()\n sage: t = B((W.one(),W.one(),W.from_reduced_word([3]),W.from_reduced_word([2,1]))); t\n (1, 1, s3, s2*s1)\n sage: t.f(2)\n (1, s3, 1, s2*s1)\n sage: t.f(1)\n (1, 1, s3*s2, s1)\n ' if (i not in self.index_set()): raise ValueError('i must be in the index set') b = self.bracketing(i) if (not b[1]): return None W = self.parent().w.parent() x = self.parent().x k = self.parent().k n = self.parent().n a = max(b[1]) right = [j for j in self.value[(n - i)].reduced_word() if (j != ((a + x) % (k + 1)))] left = [((j - x) % (k + 1)) for j in self.value[((n - i) - 1)].reduced_word()] m = min([j for j in range((a + 1), (k + 2)) if (((j + x) % (k + 1)) not in right)]) left += [(m - 1)] left.sort(reverse=True) left = [((j + x) % (k + 1)) for j in left] t = ((([self.value[j] for j in range(((n - i) - 1))] + [W.from_reduced_word(left)]) + [W.from_reduced_word(right)]) + [self.value[j] for j in range(((n - i) + 1), n)]) return self.parent()(tuple(t)) def bracketing(self, i): '\n Removes all bracketed letters between `i`-th and `i+1`-th entry.\n\n EXAMPLES::\n\n sage: B = crystals.AffineFactorization([[3,1],[1]], 3, k=3, x=4)\n sage: W = B.w.parent()\n sage: t = B((W.one(),W.from_reduced_word([3]),W.from_reduced_word([2,1]))); t\n (1, s3, s2*s1)\n sage: t.bracketing(1)\n [[3], [2, 1]]\n ' n = self.parent().n x = self.parent().x k = self.parent().k right = self.value[(n - i)].reduced_word() left = self.value[((n - i) - 1)].reduced_word() right_n = [((j - x) % (k + 1)) for j in right] left_n = [((j - x) % (k + 1)) for j in left] left_unbracketed = [] while left_n: m = max(left_n) left_n.remove(m) l = [j for j in right_n if (j > m)] if l: right_n.remove(min(l)) else: left_unbracketed += [m] return [[j for j in left_unbracketed], [j for j in right_n]] def to_tableau(self): "\n Return the tableau representation of ``self``.\n\n Uses the recording tableau of a minor variation of\n Edelman-Greene insertion. See Theorem 4.11 in [MS2015]_.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,1,3,2])\n sage: B = crystals.AffineFactorization(w,3)\n sage: for x in B:\n ....: x\n ....: x.to_tableau().pp()\n (1, s2*s1, s3*s2)\n 1 1\n 2 2\n (s2, s1, s3*s2)\n 1 1\n 2 3\n (s2, s3*s1, s2)\n 1 2\n 2 3\n (s2*s1, 1, s3*s2)\n 1 1\n 3 3\n (s2*s1, s3, s2)\n 1 2\n 3 3\n (s2*s1, s3*s2, 1)\n 2 2\n 3 3\n " return self.parent()._tableaux_isomorphism(self)
def affine_factorizations(w, l, weight=None): "\n Return all factorizations of ``w`` into ``l`` factors or of weight ``weight``.\n\n INPUT:\n\n - ``w`` -- an (affine) permutation or element of the (affine) Weyl group\n\n - ``l`` -- nonnegative integer\n\n - ``weight`` -- (default: None) tuple of nonnegative integers specifying the length of the factors\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([3,2,3,1,0,1])\n sage: from sage.combinat.crystals.affine_factorization import affine_factorizations\n sage: affine_factorizations(w,4)\n [[s2, s3, s0, s2*s1*s0],\n [s2, s3, s2*s0, s1*s0],\n [s2, s3, s2*s1*s0, s1],\n [s2, s3*s2, s0, s1*s0],\n [s2, s3*s2, s1*s0, s1],\n [s2, s3*s2*s1, s0, s1],\n [s3*s2, s3, s0, s1*s0],\n [s3*s2, s3, s1*s0, s1],\n [s3*s2, s3*s1, s0, s1],\n [s3*s2*s1, s3, s0, s1]]\n\n sage: W = WeylGroup(['A',2], prefix='s')\n sage: w0 = W.long_element()\n sage: affine_factorizations(w0,3)\n [[1, s1, s2*s1],\n [1, s2*s1, s2],\n [s1, 1, s2*s1],\n [s1, s2, s1],\n [s1, s2*s1, 1],\n [s2, s1, s2],\n [s2*s1, 1, s2],\n [s2*s1, s2, 1]]\n sage: affine_factorizations(w0,3,(0,1,2))\n [[1, s1, s2*s1]]\n sage: affine_factorizations(w0,3,(1,1,1))\n [[s1, s2, s1], [s2, s1, s2]]\n sage: W = WeylGroup(['A',3], prefix='s')\n sage: w0 = W.long_element()\n sage: affine_factorizations(w0,6,(1,1,1,1,1,1)) # long time\n [[s1, s2, s1, s3, s2, s1],\n [s1, s2, s3, s1, s2, s1],\n [s1, s2, s3, s2, s1, s2],\n [s1, s3, s2, s1, s3, s2],\n [s1, s3, s2, s3, s1, s2],\n [s2, s1, s2, s3, s2, s1],\n [s2, s1, s3, s2, s1, s3],\n [s2, s1, s3, s2, s3, s1],\n [s2, s3, s1, s2, s1, s3],\n [s2, s3, s1, s2, s3, s1],\n [s2, s3, s2, s1, s2, s3],\n [s3, s1, s2, s1, s3, s2],\n [s3, s1, s2, s3, s1, s2],\n [s3, s2, s1, s2, s3, s2],\n [s3, s2, s1, s3, s2, s3],\n [s3, s2, s3, s1, s2, s3]]\n sage: affine_factorizations(w0,6,(0,0,0,1,2,3))\n [[1, 1, 1, s1, s2*s1, s3*s2*s1]]\n " if (weight is None): if (l == 0): if w.is_one(): return [[]] else: return [] else: return [([u] + p) for (u, v) in w.left_pieri_factorizations() for p in affine_factorizations(v, (l - 1))] else: if (l != len(weight)): return [] if (l == 0): if w.is_one(): return [[]] else: return [] else: return [([u] + p) for (u, v) in w.left_pieri_factorizations(max_length=weight[0]) if (u.length() == weight[0]) for p in affine_factorizations(v, (l - 1), weight[1:])]
class FactorizationToTableaux(CrystalMorphism): def _call_(self, x): "\n Return the image of ``x`` under ``self``.\n\n TESTS::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,1,3,2])\n sage: B = crystals.AffineFactorization(w,3)\n sage: phi = B._tableaux_isomorphism\n sage: [phi(b) for b in B]\n [[[1, 1], [2, 2]],\n [[1, 1], [2, 3]],\n [[1, 2], [2, 3]],\n [[1, 1], [3, 3]],\n [[1, 2], [3, 3]],\n [[2, 2], [3, 3]]]\n " p = [] q = [] for (i, factor) in enumerate(reversed(x.value)): word = factor.reduced_word() p += ([(i + 1)] * len(word)) q += sorted(reversed(word)) C = self.codomain() return C(RSK(p, q, insertion=RSK.rules.EG)[1]) def is_isomorphism(self): "\n Return ``True`` as this is an isomorphism.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3,1], prefix='s')\n sage: w = W.from_reduced_word([2,1,3,2])\n sage: B = crystals.AffineFactorization(w,3)\n sage: phi = B._tableaux_isomorphism\n sage: phi.is_isomorphism()\n True\n\n TESTS::\n\n sage: W = WeylGroup(['A',4,1], prefix='s')\n sage: w = W.from_reduced_word([2,1,3,2,4,3,2,1])\n sage: B = crystals.AffineFactorization(w, 4) # long time\n sage: phi = B._tableaux_isomorphism # long time\n sage: all(phi(b).e(i) == phi(b.e(i)) and # long time\n ....: phi(b).f(i) == phi(b.f(i))\n ....: for b in B for i in B.index_set())\n True\n sage: set(phi(b) for b in B) == set(phi.codomain()) # long time\n True\n " return True is_embedding = is_isomorphism is_surjective = is_isomorphism
class AffinizationOfCrystal(UniqueRepresentation, Parent): "\n An affinization of a crystal.\n\n Let `\\mathfrak{g}` be a Kac-Moody algebra of affine type. The\n affinization of a finite `U_q^{\\prime}(\\mathfrak{g})`-crystal `B`\n is the (infinite) `U_q(\\mathfrak{g})`-crystal with underlying set:\n\n .. MATH::\n\n B^{\\mathrm{aff}} = \\{ b(m) \\mid b \\in B, m \\in \\ZZ \\}\n\n and crystal structure determined by:\n\n .. MATH::\n\n \\begin{aligned}\n e_i(b(m)) & =\n \\begin{cases}\n (e_0 b)(m+1) & i = 0, \\\\\n (e_i b)(m) & i \\neq 0,\n \\end{cases} \\\\\n f_i(b(m)) &=\n \\begin{cases}\n (f_0 b)(m-1) & i = 0, \\\\\n (f_i b)(m) & i \\neq 0,\n \\end{cases} \\\\\n \\mathrm{wt}(b(m)) &= \\mathrm{wt}(b) + m \\delta.\n \\end{aligned}\n\n EXAMPLES:\n\n We first construct a Kirillov-Reshetikhin crystal and then take it's\n corresponding affinization::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 2, 2)\n sage: A = K.affinization()\n\n Next we construct an affinization crystal from a tensor product of KR\n crystals::\n\n sage: KT = crystals.TensorProductOfKirillovReshetikhinTableaux(['C',2,1], [[1,2],[2,1]])\n sage: A = crystals.AffinizationOf(KT)\n\n REFERENCES:\n\n - [HK2002]_ Chapter 10\n " def __init__(self, B): '\n Initialize ``self``.\n\n EXAMPLES:\n\n We skip the Stembridge axioms test since this is an abstract crystal::\n\n sage: A = crystals.KirillovReshetikhin([\'A\',2,1], 2, 2).affinization()\n sage: TestSuite(A).run(skip="_test_stembridge_local_axioms") # long time\n ' if (not B.cartan_type().is_affine()): raise ValueError('must be an affine crystal') if (B.cardinality() == Infinity): raise ValueError('must be finite crystal') self._B = B self._cartan_type = B.cartan_type() Parent.__init__(self, category=(RegularCrystals(), InfiniteEnumeratedSets())) self.module_generators = tuple([self.element_class(self, b, 0) for b in B.module_generators]) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: crystals.KirillovReshetikhin(['A',2,1], 1, 1).affinization()\n Affinization of Kirillov-Reshetikhin crystal of type ['A', 2, 1] with (r,s)=(1,1)\n " return 'Affinization of {}'.format(self._B) class Element(Element): '\n An element in an affinization crystal.\n ' def __init__(self, parent, b, m): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: mg = A.module_generators[0]\n sage: TestSuite(mg).run()\n " self._b = b self._m = m Element.__init__(self, parent) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: A.module_generators[0]\n [[1, 1], [2, 2]](0)\n sage: KT = crystals.TensorProductOfKirillovReshetikhinTableaux(['C',2,1], [[1,2],[2,1]])\n sage: A = crystals.AffinizationOf(KT)\n sage: A.module_generators[0]\n [[1, 1]] (X) [[1], [2]](0)\n " return '{!r}({})'.format(self._b, self._m) def _latex_(self): "\n Return a LaTeX representation of ``self``.\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: latex(A.module_generators[0])\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{1}&\\lr{1}\\\\\\cline{1-2}\n \\lr{2}&\\lr{2}\\\\\\cline{1-2}\n \\end{array}$}\n } (0)\n " from sage.misc.latex import latex return (latex(self._b) + '({})'.format(self._m)) def __hash__(self): "\n TESTS::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: mg = A.module_generators[0]\n sage: hash(mg) == hash(mg._b) ^^ hash(mg._m)\n True\n " return (hash(self._b) ^ hash(self._m)) def _richcmp_(self, other, op): "\n Comparison.\n\n TESTS::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg == mg\n True\n sage: mg == mg.f(2).e(2)\n True\n sage: KT = crystals.TensorProductOfKirillovReshetikhinTableaux(['C',2,1], [[1,2],[2,1]])\n sage: A = crystals.AffinizationOf(KT)\n sage: A(KT.module_generators[3], 1).f(0) == A.module_generators[0]\n True\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg != mg.f(2)\n True\n sage: mg != mg.f(2).e(2)\n False\n\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2, 2).affinization()\n sage: S = A.subcrystal(max_depth=2)\n sage: sorted(S)\n [[[1, 1], [2, 2]](0),\n [[1, 1], [2, 3]](0),\n [[1, 2], [2, 3]](0),\n [[1, 1], [3, 3]](0),\n [[1, 1], [2, 3]](1),\n [[1, 2], [2, 3]](1),\n [[1, 2], [3, 3]](1),\n [[2, 2], [3, 3]](2)]\n " return richcmp((self._m, self._b), (other._m, other._b), op) def e(self, i): "\n Return the action of `e_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2,2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg.e(0)\n [[1, 2], [2, 3]](1)\n sage: mg.e(1)\n sage: mg.e(0).e(1)\n [[1, 1], [2, 3]](1)\n " bp = self._b.e(i) if (bp is None): return None if (i == 0): return self.__class__(self.parent(), bp, (self._m + 1)) return self.__class__(self.parent(), bp, self._m) def f(self, i): "\n Return the action of `f_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2,2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg.f(2)\n [[1, 1], [2, 3]](0)\n sage: mg.f(2).f(2).f(0)\n sage: mg.f_string([2,1,1])\n sage: mg.f_string([2,1])\n [[1, 2], [2, 3]](0)\n sage: mg.f_string([2,1,0])\n [[1, 1], [2, 2]](-1)\n " bp = self._b.f(i) if (bp is None): return None if (i == 0): return self.__class__(self.parent(), bp, (self._m - 1)) return self.__class__(self.parent(), bp, self._m) def epsilon(self, i): "\n Return `\\varepsilon_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2,2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg.epsilon(0)\n 2\n sage: mg.epsilon(1)\n 0\n " return self._b.epsilon(i) def phi(self, i): "\n Return `\\varphi_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2,2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg.phi(0)\n 0\n sage: mg.phi(2)\n 2\n " return self._b.phi(i) def weight(self): "\n Return the weight of ``self``.\n\n The weight `\\mathrm{wt}` of an element is:\n\n .. MATH::\n\n \\mathrm{wt}\\bigl( b(m) \\bigr) = \\mathrm{wt}(b) + m \\delta,\n\n where `\\delta` is the null root.\n\n EXAMPLES::\n\n sage: A = crystals.KirillovReshetikhin(['A',2,1], 2,2).affinization()\n sage: mg = A.module_generators[0]\n sage: mg.weight()\n -2*Lambda[0] + 2*Lambda[2]\n sage: mg.e(0).weight()\n -Lambda[1] + Lambda[2] + delta\n sage: mg.e(0).e(0).weight()\n 2*Lambda[0] - 2*Lambda[1] + 2*delta\n " WLR = self.parent().weight_lattice_realization() La = WLR.fundamental_weights() return (WLR.sum(((c * La[i]) for (i, c) in self._b.weight())) + (self._m * WLR.null_root()))
class CrystalOfAlcovePaths(UniqueRepresentation, Parent): '\n Crystal of alcove paths generated from a "straight-line" path to the\n negative of a given dominant weight.\n\n INPUT:\n\n - ``cartan_type`` -- Cartan type of a finite or affine untwisted root\n system.\n\n - ``weight`` -- Dominant weight as a list of (integral) coefficients of\n the fundamental weights.\n\n - ``highest_weight_crystal`` -- (Default: ``True``) If ``True``\n returns the highest weight crystal. If ``False`` returns an\n object which is close to being isomorphic to the tensor product\n of Kirillov-Reshetikhin crystals of column shape in the\n following sense: We get all the vertices, but only some of the\n edges. We\'ll call the included edges pseudo-Demazure. They are\n all non-zero edges and the 0-edges not at the end of a 0-string\n of edges, i.e. not those with `f_{0}(b) = b\'` with\n `\\varphi_0(b) =1`. (Whereas Demazure 0-edges are those that\n are not at the beginning of a zero string.) In this case the\n weight `[c_1, c_2, \\ldots, c_k]` represents\n `\\sum_{i=1}^k c_i \\omega_i`.\n\n .. NOTE::\n\n If ``highest_weight_crystal`` = ``False``, since we do not\n get the full crystal, ``TestSuite`` will fail on the\n Stembridge axioms.\n\n .. SEEALSO::\n\n - :class:`Crystals`\n\n EXAMPLES:\n\n The following example appears in Figure 2 of [LP2008]_::\n\n sage: C = crystals.AlcovePaths([\'G\',2],[0,1])\n sage: G = C.digraph()\n sage: GG = DiGraph({\n ....: () : {(0) : 2 },\n ....: (0) : {(0,8) : 1 },\n ....: (0,1) : {(0,1,7) : 2 },\n ....: (0,1,2) : {(0,1,2,9) : 1 },\n ....: (0,1,2,3) : {(0,1,2,3,4) : 2 },\n ....: (0,1,2,6) : {(0,1,2,3) : 1 },\n ....: (0,1,2,9) : {(0,1,2,6) : 1 },\n ....: (0,1,7) : {(0,1,2) : 2 },\n ....: (0,1,7,9) : {(0,1,2,9) : 2 },\n ....: (0,5) : {(0,1) : 1, (0,5,7) : 2 },\n ....: (0,5,7) : {(0,5,7,9) : 1 },\n ....: (0,5,7,9) : {(0,1,7,9) : 1 },\n ....: (0,8) : {(0,5) : 1 },\n ....: })\n sage: G.is_isomorphic(GG)\n True\n sage: for (u,v,i) in G.edges(sort=True):\n ....: print((u.integer_sequence() , v.integer_sequence(), i))\n ([], [0], 2)\n ([0], [0, 8], 1)\n ([0, 1], [0, 1, 7], 2)\n ([0, 1, 2], [0, 1, 2, 9], 1)\n ([0, 1, 2, 3], [0, 1, 2, 3, 4], 2)\n ([0, 1, 2, 6], [0, 1, 2, 3], 1)\n ([0, 1, 2, 9], [0, 1, 2, 6], 1)\n ([0, 1, 7], [0, 1, 2], 2)\n ([0, 1, 7, 9], [0, 1, 2, 9], 2)\n ([0, 5], [0, 1], 1)\n ([0, 5], [0, 5, 7], 2)\n ([0, 5, 7], [0, 5, 7, 9], 1)\n ([0, 5, 7, 9], [0, 1, 7, 9], 1)\n ([0, 8], [0, 5], 1)\n\n Alcove path crystals are a discrete version of Littelmann paths.\n We verify that the alcove path crystal is isomorphic to the LS\n path crystal::\n\n sage: C1 = crystals.AlcovePaths([\'C\',3],[2,1,0])\n sage: g1 = C1.digraph() #long time\n sage: C2 = crystals.LSPaths([\'C\',3],[2,1,0])\n sage: g2 = C2.digraph() #long time\n sage: g1.is_isomorphic(g2, edge_labels=True) #long time\n True\n\n The preferred initialization method is via explicit weights rather than a Cartan type\n and the coefficients of the fundamental weights::\n\n sage: R = RootSystem([\'C\',3])\n sage: P = R.weight_lattice()\n sage: La = P.fundamental_weights()\n sage: C = crystals.AlcovePaths(2*La[1]+La[2]); C\n Highest weight crystal of alcove paths of type [\'C\', 3] and weight 2*Lambda[1] + Lambda[2]\n sage: C1==C\n True\n\n We now explain the data structure::\n\n sage: C = crystals.AlcovePaths([\'A\',2],[2,0]) ; C\n Highest weight crystal of alcove paths of type [\'A\', 2] and weight 2*Lambda[1]\n sage: C._R.lambda_chain()\n [(alpha[1], 0), (alpha[1] + alpha[2], 0), (alpha[1], 1), (alpha[1] + alpha[2], 1)]\n\n The previous list gives the initial "straight line" path from the\n fundamental alcove `A_o` to its translation `A_o - \\lambda` where\n `\\lambda = 2\\omega_1` in this example. The initial path for weight\n `\\lambda` is called the `\\lambda`-chain. This path is constructed from\n the ordered pairs `(\\beta, k)`, by crossing the hyperplane orthogonal to\n `\\beta` at height `-k`. We can view a plot of this path as follows::\n\n sage: x=C( () )\n sage: x.plot() # not tested - outputs a pdf\n\n An element of the crystal is given by a subset of the `\\lambda`-chain.\n This subset indicates the hyperplanes where the initial path should be\n folded. The highest weight element is given by the empty subset. ::\n\n sage: x\n ()\n sage: x.f(1).f(2)\n ((alpha[1], 1), (alpha[1] + alpha[2], 1))\n sage: x.f(1).f(2).integer_sequence()\n [2, 3]\n sage: C([2,3])\n ((alpha[1], 1), (alpha[1] + alpha[2], 1))\n sage: C([2,3]).is_admissible() #check if a valid vertex\n True\n sage: C([1,3]).is_admissible() #check if a valid vertex\n False\n\n Alcove path crystals now works in affine type (:trac:`14143`)::\n\n sage: C = crystals.AlcovePaths([\'A\',2,1],[1,0,0]) ; C\n Highest weight crystal of alcove paths of type [\'A\', 2, 1] and weight Lambda[0]\n sage: x=C( () )\n sage: x.f(0)\n ((alpha[0], 0),)\n sage: C.R\n Root system of type [\'A\', 2, 1]\n sage: C.weight\n Lambda[0]\n\n Test that the tensor products of Kirillov-Reshetikhin crystals\n minus non-pseudo-Demazure arrows is in bijection with alcove path\n construction::\n\n sage: K = crystals.KirillovReshetikhin([\'B\',3,1],2,1)\n sage: T = crystals.TensorProduct(K,K)\n sage: g = T.digraph() #long time\n sage: for e in g.edges(sort=False): #long time\n ....: if e[0].phi(0) == 1 and e[2] == 0:\n ....: g.delete_edge(e)\n\n sage: C = crystals.AlcovePaths([\'B\',3,1],[0,2,0], highest_weight_crystal=False)\n sage: g2 = C.digraph() #long time\n sage: g.is_isomorphic(g2, edge_labels = True) #long time\n True\n\n .. NOTE::\n\n In type `C_n^{(1)}`, the Kirillov-Reshetikhin crystal is not connected\n when restricted to pseudo-Demazure arrows, hence the previous example will\n fail for type `C_n^{(1)}` crystals.\n\n ::\n\n sage: R = RootSystem([\'B\',3])\n sage: P = R.weight_lattice()\n sage: La = P.fundamental_weights()\n sage: D = crystals.AlcovePaths(2*La[2], highest_weight_crystal=False)\n sage: C == D\n True\n\n .. WARNING:: Weights from finite root systems index non-highest weight crystals.\n ' @staticmethod def __classcall_private__(cls, starting_weight, cartan_type=None, highest_weight_crystal=None): "\n Classcall to mend the input.\n\n Internally, the\n :class:`~sage.combinat.crystals.alcove_path.CrystalOfAlcovePaths`\n code works with a ``starting_weight`` that is in the weight space\n associated to the crystal. The user can, however, also input a\n ``cartan_type`` and the coefficients of the fundamental weights as\n ``starting_weight``. This code transforms the input into the right\n format (also necessary for :class:`UniqueRepresentation`).\n\n TESTS::\n\n sage: C = crystals.AlcovePaths(['A',2,1], [1,0,0])\n sage: C2 = crystals.AlcovePaths(CartanType(['A',2,1]), (1,0,0))\n sage: C is C2\n True\n sage: R = RootSystem(['B',2,1])\n sage: La = R.weight_space().basis()\n sage: B1 = crystals.AlcovePaths(['B',2,1],[0,0,1])\n sage: B2 = crystals.AlcovePaths(La[2])\n sage: B1 is B2\n True\n " if isinstance(cartan_type, bool): highest_weight_crystal = cartan_type elif isinstance(cartan_type, (list, tuple)): (cartan_type, starting_weight) = (CartanType(starting_weight), cartan_type) if (highest_weight_crystal is False): if (not cartan_type.is_affine()): raise ValueError('non-highest weight crystals only valid for affine types') cartan_type = cartan_type.classical() if cartan_type.is_affine(): extended = True else: extended = False R = RootSystem(cartan_type) P = R.weight_space(extended=extended) Lambda = P.basis() offset = R.index_set()[Integer(0)] starting_weight = P.sum(((starting_weight[(j - offset)] * Lambda[j]) for j in R.index_set())) if (highest_weight_crystal is None): highest_weight_crystal = True if (not starting_weight.is_dominant()): raise ValueError('{0} is not a dominant weight'.format(starting_weight)) return super().__classcall__(cls, starting_weight, highest_weight_crystal) def __init__(self, starting_weight, highest_weight_crystal): '\n Initialize ``self``.\n\n TESTS::\n\n sage: C = crystals.AlcovePaths([\'G\',2],[0,1])\n sage: TestSuite(C).run()\n\n sage: C = crystals.AlcovePaths([\'A\',2,1],[1,0,0])\n sage: TestSuite(C).run() #long time\n\n sage: C = crystals.AlcovePaths([\'A\',2,1],[1,0],False)\n sage: TestSuite(C).run(skip="_test_stembridge_local_axioms") #long time\n\n Check that :trac:`20292` is fixed::\n\n sage: A = crystals.AlcovePaths([\'A\',2], [1,0])\n sage: A.category()\n Category of classical crystals\n ' cartan_type = starting_weight.parent().cartan_type() self.weight = starting_weight self.R = RootSystem(cartan_type) self._highest_weight_crystal = highest_weight_crystal self._cartan_type = cartan_type if (cartan_type.is_finite() and highest_weight_crystal): Parent.__init__(self, category=ClassicalCrystals()) self._R = RootsWithHeight(starting_weight) self._finite_cartan_type = True elif (cartan_type.is_finite() and (not highest_weight_crystal)): Parent.__init__(self, category=LoopCrystals().Finite()) self._R = RootsWithHeight(starting_weight) self._finite_cartan_type = True self._cartan_type = cartan_type.affine() else: assert highest_weight_crystal Parent.__init__(self, category=HighestWeightCrystals()) self._R = RootsWithHeight(starting_weight) self._finite_cartan_type = False self.module_generators = (self.element_class(self, ()),) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2,1], [1,0,0])\n sage: C\n Highest weight crystal of alcove paths of type ['A', 2, 1] and weight Lambda[0]\n sage: C = crystals.AlcovePaths(['A',2,1], [1,0], False)\n sage: C\n Crystal of alcove paths of type ['A', 2, 1] and weight Lambda[1]\n " if self._highest_weight_crystal: return ('Highest weight crystal of alcove paths of type %s and weight %s' % (self._cartan_type, self.weight)) return ('Crystal of alcove paths of type %s and weight %s' % (self._cartan_type, self.weight)) def _element_constructor_(self, data): "\n Construct an element of ``self`` from ``data``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[3,2])\n sage: C([8,9])\n ((alpha[1], 2), (alpha[1] + alpha[2], 4))\n " if isinstance(data, tuple): return self.element_class(self, data) elif isinstance(data, list): lambda_chain = self._R.lambda_chain() return self.element_class(self, tuple(sorted([lambda_chain[i] for i in data]))) def vertices(self): "\n Return a list of all the vertices of the crystal.\n\n The vertices are represented as lists of integers recording the folding\n positions.\n\n One can compute all vertices of the crystal by finding all the\n admissible subsets of the `\\lambda`-chain (see method\n is_admissible, for definition). We use the breadth first\n search algorithm.\n\n .. WARNING::\n\n This method is (currently) only useful for the case when\n ``highest_weight_crystal = False``, where you cannot always\n reach all vertices of the crystal using crystal operators,\n starting from the highest weight vertex. This method is\n typically slower than generating the crystal graph using\n crystal operators.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['C',2],[1,0])\n sage: C.vertices()\n [[], [0], [0, 1], [0, 1, 2]]\n sage: C = crystals.AlcovePaths(['C',2,1],[2,1],False)\n sage: len(C.vertices())\n 80\n\n The number of elements reachable using the crystal operators from the\n module generator::\n\n sage: len(list(C))\n 55\n " lambda_chain = self._R.lambda_chain() len_lambda_chain = len(lambda_chain) W = WeylGroup(self._R._cartan_type, prefix='s') s = W.simple_reflections() highest_weight_crystal = self._highest_weight_crystal if highest_weight_crystal: successors = 'bruhat_upper_covers' else: successors = 'quantum_bruhat_successors' lst = [] for i in range(len_lambda_chain): associated_reflection = lambda_chain[i].root.associated_reflection() if (len(associated_reflection) == 1): lst.append((prod([s[j] for j in associated_reflection]), [i])) l = copy(lst) while True: lst2 = [] for x in lst: suc = getattr(x[0], successors)() for j in range((x[1][(- 1)] + 1), len_lambda_chain): temp = (x[0] * prod([s[k] for k in lambda_chain[j].root.associated_reflection()])) if (temp in suc): lst2.append((temp, (x[1] + [j]))) l.append((temp, (x[1] + [j]))) if (lst2 == []): break else: lst = lst2 return ([[]] + [i[1] for i in l])
class CrystalOfAlcovePathsElement(ElementWrapper): "\n Crystal of alcove paths element.\n\n INPUT:\n\n - ``data`` -- a list of folding positions in the lambda chain (indexing\n starts at 0) or a tuple of :class:`RootsWithHeight` giving folding\n positions in the lambda chain.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[3,2])\n sage: x = C ( () )\n sage: x.f(1).f(2)\n ((alpha[1], 2), (alpha[1] + alpha[2], 4))\n sage: x.f(1).f(2).integer_sequence()\n [8, 9]\n sage: C([8,9])\n ((alpha[1], 2), (alpha[1] + alpha[2], 4))\n " def __iter__(self): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[1,0])\n sage: lst = list(C)\n sage: for i in lst[2]: i\n (alpha[1], 0)\n (alpha[1] + alpha[2], 0)\n " return iter(self.value) def is_admissible(self): "\n Diagnostic test to check if ``self`` is a valid element of the crystal.\n\n If ``self.value`` is given by\n\n .. MATH::\n\n (\\beta_1, i_1), (\\beta_2, i_2), \\ldots, (\\beta_k, i_k),\n\n for highest weight crystals this checks if the sequence\n\n .. MATH::\n\n 1 \\rightarrow s_{\\beta_1} \\rightarrow\n s_{\\beta_1}s_{\\beta_2} \\rightarrow \\cdots \\rightarrow\n s_{\\beta_1}s_{\\beta_2} \\ldots s_{\\beta_k}\n\n is a path in the Bruhat graph. If ``highest_weight_crystal=False``,\n then the method checks if the above sequence is a path in the quantum\n Bruhat graph.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[1,1]); C\n Highest weight crystal of alcove paths of type ['A', 2] and weight Lambda[1] + Lambda[2]\n sage: roots = sorted(C._R._root_lattice.positive_roots()); roots\n [alpha[1], alpha[1] + alpha[2], alpha[2]]\n sage: r1 = C._R(roots[0],0); r1\n (alpha[1], 0)\n sage: r2 = C._R(roots[2],0); r2\n (alpha[2], 0)\n sage: r3 = C._R(roots[1],1); r3\n (alpha[1] + alpha[2], 1)\n sage: x = C( ( r1,r2) )\n sage: x.is_admissible()\n True\n sage: x = C( (r3,) ); x\n ((alpha[1] + alpha[2], 1),)\n sage: x.is_admissible()\n False\n sage: C = crystals.AlcovePaths(['C',2,1],[2,1],False)\n sage: C([7,8]).is_admissible()\n True\n sage: C = crystals.AlcovePaths(['A',2],[3,2])\n sage: C([2,3]).is_admissible()\n True\n\n .. TODO:: Better doctest\n " W = WeylGroup(self.parent()._R._cartan_type, prefix='s') s = W.simple_reflections() highest_weight_crystal = self.parent()._highest_weight_crystal if highest_weight_crystal: successors = 'bruhat_upper_covers' else: successors = 'quantum_bruhat_successors' w = W.one() for i in self: t = prod([s[j] for j in i.root.associated_reflection()]) successor = (w * t) if (successor not in getattr(w, successors)()): return False w = successor return True def _latex_(self): "\n Return a `\\LaTeX` representation of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[1,1])\n sage: C([1,2])._latex_()\n [(\\alpha_{1} + \\alpha_{2}, 0), (\\alpha_{1}, 0)]\n " return [(latex(i.root), i.height) for i in self.value] @cached_in_parent_method def integer_sequence(self): "\n Return a list of integers corresponding to positions in\n the `\\lambda`-chain where it is folded.\n\n .. TODO::\n\n Incorporate this method into the ``_repr_`` for finite Cartan type.\n\n .. NOTE::\n\n Only works for finite Cartan types and indexing starts at 0.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[3,2])\n sage: x = C( () )\n sage: x.f(1).f(2).integer_sequence()\n [8, 9]\n " lambda_chain = self.parent()._R.lambda_chain() return [lambda_chain.index(j) for j in self.value] def phi(self, i): "\n Return the distance to the end of the `i`-string.\n\n This method overrides the generic implementation in the category of\n crystals since this computation is more efficient.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[1,1])\n sage: [c.phi(1) for c in C]\n [1, 0, 0, 1, 0, 2, 1, 0]\n sage: [c.phi(2) for c in C]\n [1, 2, 1, 0, 0, 0, 0, 1]\n " highest_weight_crystal = self.parent()._highest_weight_crystal (positions, gi) = self._gi(i) m = max(gi) if ((not highest_weight_crystal) and (i == 0)): raise NotImplementedError M = ((Integer(m) / 2) - (Integer(1) / 2)) return M def epsilon(self, i): "\n Return the distance to the start of the `i`-string.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[1,1])\n sage: [c.epsilon(1) for c in C]\n [0, 1, 0, 0, 1, 0, 1, 2]\n sage: [c.epsilon(2) for c in C]\n [0, 0, 1, 2, 1, 1, 0, 0]\n " j = 0 temp = self temp = temp.e(i) while (temp is not None): j += 1 temp = temp.e(i) return j def weight(self): "\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[2,0])\n sage: for i in C: i.weight()\n (2, 0, 0)\n (1, 1, 0)\n (0, 2, 0)\n (0, -1, 0)\n (-1, 0, 0)\n (-2, -2, 0)\n sage: B = crystals.AlcovePaths(['A',2,1],[1,0,0])\n sage: p = B.module_generators[0].f_string([0,1,2])\n sage: p.weight()\n Lambda[0] - delta\n\n TESTS:\n\n Check that crystal morphisms work (:trac:`19481`)::\n\n sage: C1 = crystals.AlcovePaths(['A',2],[1,0])\n sage: C2 = crystals.AlcovePaths(['A',2],[2,0])\n sage: phi = C1.crystal_morphism(C2.module_generators, scaling_factors={1:2, 2:2})\n sage: [phi(x) for x in C1]\n [(), ((alpha[1], 0),), ((alpha[1], 0), (alpha[1] + alpha[2], 0))]\n\n Check that all weights are of level 0 in the KR crystal setting\n (:trac:`20292`)::\n\n sage: A = crystals.AlcovePaths(['A',2,1], [1,0], highest_weight_crystal=False)\n sage: all(x.weight().level() == 0 for x in A)\n True\n " root_space = self.parent().R.root_space() weight = (- self.parent().weight) for i in self.value[::(- 1)]: root = root_space(i.root) weight = (((- i.height) * root) + weight.reflection(root)) WLR = self.parent().weight_lattice_realization() if (self.cartan_type().is_affine() and self.parent()._highest_weight_crystal): wt = WLR._from_dict({i: Integer(c) for (i, c) in (- weight)}, remove_zeros=False) return wt La = WLR.fundamental_weights() wt = WLR.sum(((Integer(c) * La[i]) for (i, c) in (- weight))) if self.cartan_type().is_affine(): assert (not self.parent()._highest_weight_crystal) wt -= (La[0] * wt.level()) return wt def plot(self): "\n Return a plot ``self``.\n\n .. NOTE::\n\n Currently only implemented for types `A_2`, `B_2`, and `C_2`.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[2,0])\n sage: x = C( () ).f(1).f(2)\n sage: x.plot() # Not tested - creates a pdf\n " ct = self.parent()._R._cartan_type.dual() word = self.parent()._R.word() integer_sequence = self.integer_sequence() foldings = [False for i in word] for i in integer_sequence: foldings[i] = True affine_ambient_space = RootSystem(ct.affine()).ambient_space() return (affine_ambient_space.plot() + affine_ambient_space.plot_alcove_walk(word, foldings=foldings, labels=False)) def _richcmp_(self, other, op): "\n Comparison of ``self.value`` and ``other.value``.\n\n For inequalities, ``self.value`` is compared to\n ``other.value`` in dictionary order.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['B',2],[1,0])\n sage: lst = list(C)\n sage: lst[2] == lst[2]\n True\n sage: lst[2] == lst[1]\n False\n sage: lst[2] != lst[2]\n False\n sage: lst[2] != lst[1]\n True\n\n sage: C = crystals.AlcovePaths(['A',2],[2,0])\n sage: x = C(())\n sage: x < x.f(1)\n True\n sage: a = x.f(1) ; b = x.f(1).f(1).f(2)\n sage: a < b\n False\n\n sage: C = crystals.AlcovePaths(['A',2],[2,0])\n sage: x = C( () )\n sage: x > x.f(1)\n False\n sage: a = x.f(1) ; b = x.f(1).f(1).f(2)\n sage: a > b\n True\n " return richcmp(self.value, other.value, op) def __hash__(self): "\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['B',2],[1,0])\n sage: lst = list(C)\n sage: hash(lst[2]) == hash(lst[2])\n True\n " return hash(self.value) def _folding_data(self, i): '\n Compute information needed to build the graph `g_{\\alpha_i}`.\n Results of this method are sent to _gi for further processing.\n\n INPUT:\n\n - ``i`` -- element of the index_set of the underlying root_system.\n\n OUTPUT:\n\n A dictionary where the keys are of type RootsWithHeight which record\n positions where `\\pm \\alpha_i` shows up in the folded `\\lambda` chain.\n The values are `1` if `\\alpha_i` is in the corresponding position in\n the folded `\\lambda`-chain, `-1` if `-\\alpha_i` is in the corresponding\n position in the folded `\\lambda`-chain.\n\n .. NOTE::\n\n *infinity* is a special key that records the "sign at infinity".\n\n ::\n\n sage: C = crystals.AlcovePaths([\'A\',2],[1,1])\n sage: x = C( () ).f(1)\n sage: fd = x._folding_data(2); fd # # random output\n {(alpha[2], 0): 1, (alpha[1] + alpha[2], 1): 1, \'infinity\': 1}\n sage: fd[\'infinity\']\n 1\n sage: sorted(fd.values())\n [1, 1, 1]\n ' Parent = self.parent() finite_cartan_type = Parent._finite_cartan_type J = list(self.value) R = Parent._R weight = Parent.weight signs = {} if (finite_cartan_type and (i == 0)): Beta = R._root_lattice.highest_root() elif (i in self.index_set()): Beta = R._root_lattice.simple_root(i) max_height_Beta = weight.scalar(Beta.associated_coroot()) if (not J): for k in range(max_height_Beta): x = R(Beta, k) signs[x] = self._sign(Beta) signs['infinity'] = self._sign(Beta) else: for k in range(max_height_Beta): x = R(Beta, k) if (x <= J[0]): signs[x] = self._sign(Beta) for j in range(len(J)): Beta = Beta.reflection(J[j].root) sign_Beta = self._sign(Beta) max_height_Beta = weight.scalar((sign_Beta * Beta).associated_coroot()) c1 = (J[j]._cmp_v[0] * max_height_Beta) if (j == (len(J) - 1)): c2 = max_height_Beta else: c2 = min(max_height_Beta, ((J[(j + 1)]._cmp_v[0] * max_height_Beta) + 1)) for k in range(int(c1), int(c2)): x = R((sign_Beta * Beta), k) if (((j < (len(J) - 1)) and (J[j] < x <= J[(j + 1)])) or ((j == (len(J) - 1)) and (J[j] < x))): signs[x] = sign_Beta signs['infinity'] = sign_Beta if (finite_cartan_type and (i == 0)): signs = {x: (- signs[x]) for x in signs} return signs def e(self, i): "\n Return the `i`-th crystal raising operator on ``self``.\n\n INPUT:\n\n - ``i`` -- element of the index set of the underlying root system.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['A',2],[2,0]); C\n Highest weight crystal of alcove paths of type ['A', 2] and weight 2*Lambda[1]\n sage: x = C( () )\n sage: x.e(1)\n sage: x.f(1) == x.f(1).f(2).e(2)\n True\n " Parent = self.parent() finite_cartan_type = Parent._finite_cartan_type J = list(self.value) (positions, gi) = self._gi(i) m = max(gi) m_index = ((len(gi) - 1) - list(reversed(gi)).index(m)) if (finite_cartan_type and (i == 0)): M = ((Integer(m) / 2) + (Integer(1) / 2)) else: M = ((Integer(m) / 2) - (Integer(1) / 2)) KR_test = (finite_cartan_type and (i == 0) and (m_index < (len(gi) - 1))) KR_test = (KR_test and (M >= 1)) if ((((not finite_cartan_type) or (i != 0)) and (m_index < (len(gi) - 1))) or KR_test): J.remove(positions[m_index]) if ((m_index + 1) < len(positions)): J.append(positions[(m_index + 1)]) return_value = Parent(tuple(sorted(J))) try: return_value.i_string = (self.i_string + [['e', i]]) except AttributeError: return_value.i_string = [['e', i]] return return_value else: return None @cached_method def _gi(self, i): "\n Compute information needed to build the graph `g_{\\alpha_i}`.\n This graph is used to apply the `i`-th crystal operator.\n\n INPUT:\n\n - ``i`` - element of the index_set of the underlying root_system.\n\n OUTPUT:\n\n A tuple ``(positions, gi)``:\n\n - ``positions`` -- is a list of RootsWithHeight. These appear sorted in\n their natural order, and record where `\\pm \\alpha_i` shows up in\n the folded `\\lambda`-chain.\n\n - ``gi`` -- is a list of integers recording the height\n (up to affine transformation) of `\\pm \\alpha_i`\n in the folded `\\lambda`-chain whose location is recorded by\n ``positions``.\n\n .. NOTE::\n\n - ``positions`` has length one less than ``gi`` since it does not\n contain the position 'infinity'.\n\n - To get the real `g_{\\alpha_i}` one has to divide by 2 and add 1/2\n or divide by 2 and subtract 1/2 depending on if\n ``self._finite_cartan_type==True and i == 0``\n or not. This is done in crystal operator methods.\n\n EXAMPLES::\n\n sage: C=crystals.AlcovePaths(['A',2],[1,1])\n sage: x=C( () ).f(1)\n sage: x._gi(2)\n ([(alpha[2], 0), (alpha[1] + alpha[2], 1)], [1, 3, 5])\n " signs = self._folding_data(i) positions = sorted((x for x in signs if (x != 'infinity'))) if (not positions): return (positions, [signs['infinity']]) gi = [signs[positions[0]]] for j in range(1, len(positions)): gi.append(((gi[(j - 1)] + (signs[positions[(j - 1)]] * self._eps(positions[(j - 1)]))) + signs[positions[j]])) gi.append(((gi[(- 1)] + (signs[positions[(- 1)]] * self._eps(positions[(- 1)]))) + signs['infinity'])) return (positions, gi) def f(self, i): "\n Returns the `i`-th crystal lowering operator on ``self``.\n\n INPUT:\n\n - ``i`` -- element of the index_set of the underlying root_system.\n\n EXAMPLES::\n\n sage: C=crystals.AlcovePaths(['B',2],[1,1])\n sage: x=C( () )\n sage: x.f(1)\n ((alpha[1], 0),)\n sage: x.f(1).f(2)\n ((alpha[1], 0), (alpha[1] + alpha[2], 2))\n\n " Parent = self.parent() finite_cartan_type = Parent._finite_cartan_type J = list(self.value) (positions, gi) = self._gi(i) m = max(gi) m_index = gi.index(m) if (finite_cartan_type and (i == 0)): M = ((Integer(m) / 2) + (Integer(1) / 2)) else: M = ((Integer(m) / 2) - (Integer(1) / 2)) KR_test = (finite_cartan_type and (i == 0)) KR_test = (KR_test and (M > 1)) if ((((not finite_cartan_type) or (i != 0)) and (M > 0)) or KR_test): J.append(positions[(m_index - 1)]) if (m_index < len(positions)): J.remove(positions[m_index]) return_value = Parent(tuple(sorted(J))) try: return_value.i_string = (self.i_string + [['f', i]]) except AttributeError: return_value.i_string = [['f', i]] return return_value else: return None @staticmethod def _sign(root): "\n Return `1` if root is a positive root, and `-1` if root is a negative\n root.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import CrystalOfAlcovePathsElement\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: x = rl.from_vector(vector([0,1]))\n sage: CrystalOfAlcovePathsElement._sign(x)\n 1\n " if root.is_positive_root(): return 1 else: return (- 1) def _eps(self, root): "\n Return `-1` if root is in ``self.value``, otherwise return `1`.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['C',2],[3,2])\n sage: x = C( () ).f(1).f(2); x\n ((alpha[1], 2), (2*alpha[1] + alpha[2], 4))\n sage: x._eps(x.value[0])\n -1\n sage: R = C._R\n sage: y = R ( x.value[0].root, 1 ); y\n (alpha[1], 1)\n sage: x._eps(y)\n 1\n\n " if (root in self.value): return (- 1) else: return 1 def path(self): "\n Return the path in the (quantum) Bruhat graph corresponding\n to ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.AlcovePaths(['B', 3], [3,1,2])\n sage: b = C.highest_weight_vector().f_string([1,3,2,1,3,1])\n sage: b.path()\n [1, s1, s3*s1, s2*s3*s1, s3*s2*s3*s1]\n sage: b = C.highest_weight_vector().f_string([2,3,3,2])\n sage: b.path()\n [1, s2, s3*s2, s2*s3*s2]\n sage: b = C.highest_weight_vector().f_string([2,3,3,2,1])\n sage: b.path()\n [1, s2, s3*s2, s2*s3*s2, s1*s2*s3*s2]\n " W = WeylGroup(self.parent()._R._cartan_type, prefix='s') s = W.simple_reflections() w = W.one() ret = [w] for i in self: ret.append((ret[(- 1)] * prod((s[j] for j in i.root.associated_reflection())))) return ret
class InfinityCrystalOfAlcovePaths(UniqueRepresentation, Parent): '\n `\\mathcal{B}(\\infty)` crystal of alcove paths.\n ' @staticmethod def __classcall_private__(cls, cartan_type): "\n Normalize input to ensure a unique representation.\n\n TESTS::\n\n sage: A1 = crystals.infinity.AlcovePaths(['A',2])\n sage: A2 = crystals.infinity.AlcovePaths(CartanType(['A',2]))\n sage: A3 = crystals.infinity.AlcovePaths('A2')\n sage: A1 is A2 and A2 is A3\n True\n " cartan_type = CartanType(cartan_type) return super().__classcall__(cls, cartan_type) def __init__(self, cartan_type): "\n Initialize ``self``.\n\n TESTS::\n\n sage: A = crystals.infinity.AlcovePaths(['C',3])\n sage: TestSuite(A).run(max_runs=20)\n\n sage: A = crystals.infinity.AlcovePaths(['A',2,1])\n sage: TestSuite(A).run() # long time\n " self._cartan_type = cartan_type Parent.__init__(self, category=HighestWeightCrystals().Infinite()) self.module_generators = (self.element_class(self, (), 0),) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: crystals.infinity.AlcovePaths(['E',6])\n Infinity crystal of alcove paths of type ['E', 6]\n " return 'Infinity crystal of alcove paths of type {}'.format(self._cartan_type) class Element(ElementWrapper): def __init__(self, parent, elt, shift): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['F',4])\n sage: mg = A.highest_weight_vector()\n sage: x = mg.f_string([2,3,1,4,4,2,3,1])\n sage: TestSuite(x).run()\n " ElementWrapper.__init__(self, parent, elt) self._shift = shift def e(self, i): "\n Return the action of `e_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['D',5,1])\n sage: mg = A.highest_weight_vector()\n sage: x = mg.f_string([1,3,4,2,5,4,5,5])\n sage: x.f(4).e(5) == x.e(5).f(4)\n True\n " y = self.projection().e(i) if (y is None): return None if (not y.value): return self.parent().module_generators[0] n = self.parent()._cartan_type.rank() s = (lambda rt: int(sum(rt.associated_coroot().coefficients()))) shift = self._shift while y.is_admissible(): prev = y shift -= 1 A = CrystalOfAlcovePaths(self.parent()._cartan_type, ([shift] * n)) try: y = A(tuple([A._R(rt.root, (rt.height - s(rt.root))) for rt in y.value])) except ValueError: break shift += 1 return type(self)(self.parent(), tuple([(rt.root, (rt.height - (shift * s(rt.root)))) for rt in prev.value]), shift) def f(self, i): "\n Return the action of `f_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['E',7,1])\n sage: mg = A.highest_weight_vector()\n sage: mg.f_string([1,3,5,6,4,2,0,2,1,0,2,4,7,4,2])\n ((alpha[2], -3), (alpha[5], -1), (alpha[1], -1),\n (alpha[0] + alpha[1], -2),\n (alpha[2] + alpha[4] + alpha[5], -2),\n (alpha[5] + alpha[6], -1), (alpha[1] + alpha[3], -1),\n (alpha[5] + alpha[6] + alpha[7], -1),\n (alpha[0] + alpha[1] + alpha[3], -1),\n (alpha[1] + alpha[3] + alpha[4] + alpha[5], -1))\n " s = (lambda rt: int(sum(rt.associated_coroot().coefficients()))) y = self.projection().f(i) if (y is not None): return type(self)(self.parent(), tuple([(rt.root, (rt.height - (self._shift * s(rt.root)))) for rt in y.value]), self._shift) shift = (self._shift + 1) n = self.parent()._cartan_type.rank() A = CrystalOfAlcovePaths(self.parent()._cartan_type, ([shift] * n)) y = A(tuple([A._R(rt, (h + (shift * s(rt)))) for (rt, h) in self.value])).f(i) return type(self)(self.parent(), tuple([(rt.root, (rt.height - (shift * s(rt.root)))) for rt in y.value]), shift) def epsilon(self, i): "\n Return `\\varepsilon_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['A',7,2])\n sage: mg = A.highest_weight_vector()\n sage: x = mg.f_string([1,0,2,3,4,4,4,2,3,3,3])\n sage: [x.epsilon(i) for i in A.index_set()]\n [0, 0, 0, 3, 0]\n sage: x = mg.f_string([2,2,1,1,0,1,0,2,3,3,3,4])\n sage: [x.epsilon(i) for i in A.index_set()]\n [1, 2, 0, 1, 1]\n " return self.projection().epsilon(i) def phi(self, i): "\n Return `\\varphi_i` of ``self``.\n\n Let `A \\in \\mathcal{B}(\\infty)` Define `\\varphi_i(A) :=\n \\varepsilon_i(A) + \\langle h_i, \\mathrm{wt}(A) \\rangle`,\n where `h_i` is the `i`-th simple coroot and `\\mathrm{wt}(A)`\n is the :meth:`weight` of `A`.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['A',8,2])\n sage: mg = A.highest_weight_vector()\n sage: x = mg.f_string([1,0,2,3,4,4,4,2,3,3,3])\n sage: [x.phi(i) for i in A.index_set()]\n [1, 1, 1, 3, -2]\n sage: x = mg.f_string([2,2,1,1,0,1,0,2,3,3,3,4])\n sage: [x.phi(i) for i in A.index_set()]\n [4, -1, 0, 0, 2]\n " P = self.parent().weight_lattice_realization() h = P.simple_coroots() return (self.epsilon(i) + P(self.weight()).scalar(h[i])) def weight(self): "\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['E',6])\n sage: mg = A.highest_weight_vector()\n sage: fstr = [1,3,4,2,1,2,3,6,5,3,2,6,2]\n sage: x = mg.f_string(fstr)\n sage: al = A.weight_lattice_realization().simple_roots()\n sage: x.weight() == -sum(al[i]*fstr.count(i) for i in A.index_set())\n True\n " P = self.parent().weight_lattice_realization() y = self.projection() return (y.weight() - (self._shift * P.rho())) def projection(self, k=None): "\n Return the projection ``self`` onto `B(k \\rho)`.\n\n INPUT:\n\n - ``k`` -- (optional) if not given, defaults to the smallest\n value such that ``self`` is not ``None`` under the projection\n\n EXAMPLES::\n\n sage: A = crystals.infinity.AlcovePaths(['G',2])\n sage: mg = A.highest_weight_vector()\n sage: x = mg.f_string([2,1,1,2,2,2,1,1]); x\n ((alpha[2], -3), (alpha[1] + alpha[2], -3),\n (3*alpha[1] + 2*alpha[2], -1), (2*alpha[1] + alpha[2], -1))\n sage: x.projection()\n ((alpha[2], 0), (alpha[1] + alpha[2], 9),\n (3*alpha[1] + 2*alpha[2], 8), (2*alpha[1] + alpha[2], 14))\n sage: x.projection().parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight 3*Lambda[1] + 3*Lambda[2]\n\n sage: mg.projection().parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight 0\n sage: mg.f(1).projection().parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight Lambda[1] + Lambda[2]\n sage: mg.f(1).f(2).projection().parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight Lambda[1] + Lambda[2]\n sage: b = mg.f_string([1,2,2,1,2])\n sage: b.projection().parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight 2*Lambda[1] + 2*Lambda[2]\n sage: b.projection(3).parent()\n Highest weight crystal of alcove paths of type ['G', 2]\n and weight 3*Lambda[1] + 3*Lambda[2]\n sage: b.projection(1)\n " if (k is None): k = self._shift elif (k < self._shift): return None s = (lambda rt: int(sum(rt.associated_coroot().coefficients()))) n = self.parent()._cartan_type.rank() A = CrystalOfAlcovePaths(self.parent()._cartan_type, ([k] * n)) return A(tuple([A._R(rt, (h + (k * s(rt)))) for (rt, h) in self.value]))
class RootsWithHeight(UniqueRepresentation, Parent): "\n Data structure of the ordered pairs `(\\beta,k)`,\n where `\\beta` is a positive root and `k` is a non-negative integer. A total\n order is implemented on this set, and depends on the weight.\n\n INPUT:\n\n - ``cartan_type`` -- Cartan type of a finite or affine untwisted root\n system\n\n - ``weight`` -- dominant weight as a list of (integral) coefficients of\n the fundamental weights\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[1,1]); R\n Roots with height of Cartan type ['A', 2] and dominant weight Lambda[1] + Lambda[2]\n\n sage: r1 = R._root_lattice.from_vector(vector([1,0])); r1\n alpha[1]\n sage: r2 = R._root_lattice.from_vector(vector([1,1])); r2\n alpha[1] + alpha[2]\n\n sage: x = R(r1,0); x\n (alpha[1], 0)\n sage: y = R(r2,1); y\n (alpha[1] + alpha[2], 1)\n sage: x < y\n True\n " @staticmethod def __classcall_private__(cls, starting_weight, cartan_type=None): "\n Classcall to mend the input.\n\n Internally, the RootsWithHeight code works with a ``starting_weight`` that\n is in the ``weight_space`` associated to the crystal. The user can, however,\n also input a ``cartan_type`` and the coefficients of the fundamental weights\n as ``starting_weight``. This code transforms the input into the right\n format (also necessary for UniqueRepresentation).\n\n TESTS::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: S = RootsWithHeight(CartanType(['A',2]), (3,2))\n sage: R is S\n True\n\n sage: R = RootSystem(['B',2,1])\n sage: La = R.weight_space().basis()\n sage: C = RootsWithHeight(['B',2,1],[0,0,1])\n sage: B = RootsWithHeight(La[2])\n sage: B is C\n True\n " if (cartan_type is not None): (cartan_type, starting_weight) = (CartanType(starting_weight), cartan_type) R = RootSystem(cartan_type) P = R.weight_space() Lambda = P.basis() offset = R.index_set()[Integer(0)] starting_weight = P.sum(((starting_weight[(j - offset)] * Lambda[j]) for j in R.index_set())) return super().__classcall__(cls, starting_weight) def __init__(self, weight): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: TestSuite(R).run()\n " Parent.__init__(self, category=Sets()) cartan_type = weight.parent().cartan_type() self._cartan_type = cartan_type self._root_system = RootSystem(cartan_type) self._root_lattice = self._root_system.root_lattice() self._weight_lattice = self._root_system.weight_lattice() self.weight = weight def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: RootsWithHeight(['A',2],[3,2])\n Roots with height of Cartan type ['A', 2] and dominant weight 3*Lambda[1] + 2*Lambda[2]\n " return ('Roots with height of Cartan type %s and dominant weight %s' % (self._root_system.cartan_type(), self.weight)) def _max_height(self, root): "\n If root is `\\beta`, return `k = \\langle \\lambda, \\beta^{\\vee} \\rangle`.\n\n Only ordered pairs of the form `(\\beta, l)` for `0 \\leq l < k` are\n allowed.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: C = RootsWithHeight(['A',3],[3,2,0])\n sage: x = C._root_lattice.from_vector(vector([1,1])); x\n alpha[1] + alpha[2]\n sage: C._max_height(x)\n 5\n " return self.weight.scalar(root.associated_coroot()) @cached_method def word(self): "\n Gives the initial alcove path (`\\lambda`-chain) in terms of simple\n roots. Used for plotting the path.\n\n .. NOTE::\n\n Currently only implemented for finite Cartan types.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: R.word()\n [2, 1, 2, 0, 1, 2, 1, 0, 1, 2]\n " cartan_type = self._root_system.cartan_type() if (not cartan_type.is_finite()): raise NotImplementedError lambda_chain = [x.root for x in self.lambda_chain()] coroot_lattice = RootSystem(cartan_type).coroot_lattice() cohighest_root = coroot_lattice.highest_root() word = [] for i in range(len(lambda_chain)): beta = lambda_chain[i] for j in reversed(range(i)): beta = beta.reflection(lambda_chain[j]) coroot = beta.associated_coroot() support = coroot.support() if (len(support) == 1): word.append(support[0]) elif (coroot == (- cohighest_root)): word.append(0) else: assert False, 'should never get here' return word @cached_method def lambda_chain(self): "\n Return the unfolded `\\lambda`-chain.\n\n .. NOTE:: Only works in root systems of finite type.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[1,1]); R\n Roots with height of Cartan type ['A', 2] and dominant weight Lambda[1] + Lambda[2]\n sage: R.lambda_chain()\n [(alpha[2], 0), (alpha[1] + alpha[2], 0), (alpha[1], 0), (alpha[1] + alpha[2], 1)]\n " if (not self._root_lattice.cartan_type().is_finite()): raise ValueError('Cartan type {0} is not finite'.format(self._root_lattice.cartan_type())) l = [] for i in self._root_lattice.positive_roots(): for j in range(self._max_height(i)): l.append(self(i, j)) return sorted(l) def _element_constructor_(self, root, height): "\n Construct a :class:`RootsWithHeightElement` with ``self`` as the parent.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: x = rl.from_vector(vector([1,1])); x\n alpha[1] + alpha[2]\n sage: R = RootsWithHeight(['A',2],[1,1]); R\n Roots with height of Cartan type ['A', 2] and dominant weight Lambda[1] + Lambda[2]\n sage: y = R(x,1); y\n (alpha[1] + alpha[2], 1)\n " root = self._root_lattice.from_vector(vector(root)) return self.element_class(self, root, height) def _an_element_(self): "\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: R._an_element_()\n (alpha[1], 0)\n " return self(self._root_lattice.from_vector(vector([1])), 0)
class RootsWithHeightElement(Element): "\n Element of :class:`RootsWithHeight`.\n\n INPUT:\n\n - ``root`` -- A positive root `\\beta` in our root system\n - ``height`` -- Is an integer, such that\n `0 \\leq l \\leq \\langle \\lambda, \\beta^{\\vee} \\rangle`\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: x = rl.from_vector(vector([1,1])); x\n alpha[1] + alpha[2]\n sage: R = RootsWithHeight(['A',2],[1,1]); R\n Roots with height of Cartan type ['A', 2] and dominant weight Lambda[1] + Lambda[2]\n sage: y = R(x, 1); y\n (alpha[1] + alpha[2], 1)\n " def __init__(self, parent, root, height): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: x = rl.from_vector(vector([1,1]))\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: y = R(x, 1); y\n (alpha[1] + alpha[2], 1)\n sage: TestSuite(x).run()\n " Element.__init__(self, parent) max_height = parent._max_height(root) if (not (0 <= height < max_height)): raise ValueError(('%d out of allowed range [%d,%d)' % (height, 0, max_height))) v = [(height / max_height)] v.extend([(x / max_height) for x in root.associated_coroot().to_vector()]) self._cmp_v = tuple(v) self.root = root self.height = height def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: vec = rl.from_vector(vector([1,1])); vec\n alpha[1] + alpha[2]\n sage: R(vec,1)\n (alpha[1] + alpha[2], 1)\n " return ('(%s, %s)' % (self.root, self.height)) def __hash__(self): "\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: root = rl.from_vector(vector([1,1]))\n sage: vec = R(root,0)\n sage: hash(vec) == hash(vec)\n True\n " return hash(self._cmp_v) def __eq__(self, other): "\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: v1 = rl.from_vector(vector([1,1]))\n sage: v2 = rl.from_vector(vector([1]))\n sage: x1 = R(v1,1) ; x2 = R(v1,0) ; x3 = R(v2,1)\n sage: x1.__eq__(x1)\n True\n sage: x1.__eq__(x2)\n False\n sage: x1.__eq__(x3)\n False\n " try: return (self._cmp_v == other._cmp_v) except (NameError, AttributeError): return False def _richcmp_(self, other, op): "\n Define a total order on :class:`RootsWithHeightElement`. This defines\n the initial `\\lambda`-chain.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import RootsWithHeight\n sage: R = RootsWithHeight(['A',2],[3,2])\n sage: rl = RootSystem(['A',2]).root_lattice()\n sage: v1 = rl.from_vector(vector([1,1]))\n sage: v2 = rl.from_vector(vector([1]))\n sage: x1 = R(v1,1) ; x2 = R(v1,0) ; x3 = R(v2,1)\n sage: x1 < x2\n False\n sage: x1 < x3\n True\n " return richcmp(self._cmp_v, other._cmp_v, op)
def _test_some_specific_examples(clss=CrystalOfAlcovePaths): '\n Test against some specific (finite type) examples.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import _test_some_specific_examples\n sage: _test_some_specific_examples(crystals.AlcovePaths)\n G2 example passed.\n C3 example passed.\n B3 example 1 passed.\n B3 example 2 passed.\n True\n ' C = clss(['G', 2], [0, 1]) G = C.digraph() GT = DiGraph({(): {0: 2}, 0: {(0, 8): 1}, (0, 1): {(0, 1, 7): 2}, (0, 1, 2): {(0, 1, 2, 9): 1}, (0, 1, 2, 3): {(0, 1, 2, 3, 4): 2}, (0, 1, 2, 6): {(0, 1, 2, 3): 1}, (0, 1, 2, 9): {(0, 1, 2, 6): 1}, (0, 1, 7): {(0, 1, 2): 2}, (0, 1, 7, 9): {(0, 1, 2, 9): 2}, (0, 5): {(0, 1): 1, (0, 5, 7): 2}, (0, 5, 7): {(0, 5, 7, 9): 1}, (0, 5, 7, 9): {(0, 1, 7, 9): 1}, (0, 8): {(0, 5): 1}}) if (not G.is_isomorphic(GT)): return False else: print('G2 example passed.') C = clss(['C', 3], [0, 0, 1]) G = C.digraph() GT = DiGraph({(): {0: 3}, 0: {(0, 6): 2}, (0, 1): {(0, 1, 3): 3, (0, 1, 7): 1}, (0, 1, 2): {(0, 1, 2, 3): 3}, (0, 1, 2, 3): {(0, 1, 2, 3, 8): 2}, (0, 1, 2, 3, 4): {(0, 1, 2, 3, 4, 5): 3}, (0, 1, 2, 3, 8): {(0, 1, 2, 3, 4): 2}, (0, 1, 3): {(0, 1, 3, 7): 1}, (0, 1, 3, 7): {(0, 1, 2, 3): 1, (0, 1, 3, 7, 8): 2}, (0, 1, 3, 7, 8): {(0, 1, 2, 3, 8): 1}, (0, 1, 7): {(0, 1, 2): 1, (0, 1, 3, 7): 3}, (0, 6): {(0, 1): 2, (0, 6, 7): 1}, (0, 6, 7): {(0, 1, 7): 2}}) if (not G.is_isomorphic(GT)): return False else: print('C3 example passed.') C = clss(['B', 3], [2, 0, 0]) G = C.digraph() GT = DiGraph({(): {6: 1}, 0: {(0, 7): 2}, (0, 1): {(0, 1, 11): 3}, (0, 1, 2): {(0, 1, 2, 9): 2}, (0, 1, 2, 3): {(0, 1, 2, 3, 10): 1}, (0, 1, 2, 3, 10): {(0, 1, 2, 3, 4): 1}, (0, 1, 2, 9): {(0, 1, 2, 3): 2, (0, 1, 2, 9, 10): 1}, (0, 1, 2, 9, 10): {(0, 1, 2, 3, 10): 2}, (0, 1, 5): {(0, 1, 2): 3, (0, 1, 5, 9): 2}, (0, 1, 5, 9): {(0, 1, 2, 9): 3, (0, 1, 5, 9, 10): 1}, (0, 1, 5, 9, 10): {(0, 1, 2, 9, 10): 3}, (0, 1, 8): {(0, 1, 5): 3}, (0, 1, 8, 9): {(0, 1, 5, 9): 3, (0, 1, 8, 9, 10): 1}, (0, 1, 8, 9, 10): {(0, 1, 5, 9, 10): 3}, (0, 1, 11): {(0, 1, 8): 3}, (0, 7): {(0, 1): 2, (0, 7, 11): 3}, (0, 7, 8): {(0, 7, 8, 9): 2}, (0, 7, 8, 9): {(0, 1, 8, 9): 2}, (0, 7, 8, 9, 10): {(0, 1, 8, 9, 10): 2}, (0, 7, 11): {(0, 1, 11): 2, (0, 7, 8): 3}, 6: {0: 1, (6, 7): 2}, (6, 7): {(0, 7): 1, (6, 7, 11): 3}, (6, 7, 8): {(0, 7, 8): 1, (6, 7, 8, 9): 2}, (6, 7, 8, 9): {(6, 7, 8, 9, 10): 1}, (6, 7, 8, 9, 10): {(0, 7, 8, 9, 10): 1}, (6, 7, 11): {(0, 7, 11): 1, (6, 7, 8): 3}}) if (not G.is_isomorphic(GT)): return False else: print('B3 example 1 passed.') C = clss(['B', 3], [0, 1, 0]) G = C.digraph() GT = DiGraph({(): {0: 2}, 0: {(0, 1): 1, (0, 7): 3}, (0, 1): {(0, 1, 7): 3}, (0, 1, 2): {(0, 1, 2, 8): 2}, (0, 1, 2, 3): {(0, 1, 2, 3, 5): 1, (0, 1, 2, 3, 9): 3}, (0, 1, 2, 3, 4): {(0, 1, 2, 3, 4, 5): 1}, (0, 1, 2, 3, 4, 5): {(0, 1, 2, 3, 4, 5, 6): 2}, (0, 1, 2, 3, 5): {(0, 1, 2, 3, 5, 9): 3}, (0, 1, 2, 3, 5, 9): {(0, 1, 2, 3, 4, 5): 3}, (0, 1, 2, 3, 9): {(0, 1, 2, 3, 4): 3, (0, 1, 2, 3, 5, 9): 1}, (0, 1, 2, 5): {(0, 1, 2, 3, 5): 2}, (0, 1, 2, 8): {(0, 1, 2, 3): 2}, (0, 1, 2, 8, 9): {(0, 1, 2, 3, 9): 2}, (0, 1, 7): {(0, 1, 2): 3, (0, 1, 7, 8): 2}, (0, 1, 7, 8): {(0, 1, 7, 8, 9): 3}, (0, 1, 7, 8, 9): {(0, 1, 2, 8, 9): 3}, (0, 2): {(0, 1, 2): 1, (0, 2, 5): 2}, (0, 2, 5): {(0, 2, 5, 8): 1}, (0, 2, 5, 8): {(0, 1, 2, 5): 1}, (0, 7): {(0, 1, 7): 1, (0, 2): 3}}) if (not G.is_isomorphic(GT)): return False else: print('B3 example 2 passed.') return True
def compare_graphs(g1, g2, node1, node2): "\n Compare two edge-labeled :class:`graphs <DiGraph>` obtained from\n ``Crystal.digraph()``, starting from the root nodes of each graph.\n\n - ``g1`` -- :class:`graphs <DiGraph>`, first digraph\n - ``g2`` -- :class:`graphs <DiGraph>`, second digraph\n - ``node1`` -- element of ``g1``\n - ``node2`` -- element of ``g2``\n\n Traverse ``g1`` starting at ``node1`` and compare this graph with\n the one obtained by traversing ``g2`` starting with ``node2``.\n If the graphs match (including labels) then return ``True``.\n Return ``False`` otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import compare_graphs\n sage: G1 = crystals.Tableaux(['A',3], shape=[1,1]).digraph()\n sage: C = crystals.AlcovePaths(['A',3],[0,1,0])\n sage: G2 = C.digraph()\n sage: compare_graphs(G1, G2, C( () ), G2.vertices(sort=True)[0])\n True\n " for out_edge in g1.outgoing_edges(node1): matched = False for o2 in g2.outgoing_edges(node2): if (o2[2] == out_edge[2]): if matched: print('ERROR: Two edges with the same label for ', out_edge, ' exist.') return False matched = True result = compare_graphs(g1, g2, out_edge[1], o2[1]) if (not result): return False if (not matched): print('ERROR: No matching edge for ', out_edge, '.') return False return True
def _test_against_tableaux(R, N, k, clss=CrystalOfAlcovePaths): "\n Test :class:`~sage.combinat.crystals.alcove_path.CrystalOfAlcovePaths`\n against all of the tableaux crystals of type `R` in rank `N` with\n highest weight given by a partition of `k`.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import _test_against_tableaux\n sage: _test_against_tableaux(['A',3], 3, 2)\n ** Shape [2]\n T has 10 nodes.\n C weight [2, 0, 0]\n C has 10 nodes.\n Compare graphs: True\n ** Shape [1, 1]\n T has 6 nodes.\n C weight [0, 1, 0]\n C has 6 nodes.\n Compare graphs: True\n " from sage.combinat.partition import Partitions from sage.combinat.crystals.tensor_product import CrystalOfTableaux shapes = Partitions(k).list() for shape in shapes: print('** Shape ', shape) T = CrystalOfTableaux(R, shape=shape) ct = len(T.list()) print(' T has ', ct, ' nodes.') H = T.digraph() weight = T.module_generators[0].weight() w = [weight.scalar(RootSystem(R).ambient_space().simple_coroot(i)) for i in range(1, (N + 1))] print(' C weight ', w) C = clss(R, w) cc = len(C.list()) G = C.digraph() print(' C has ', cc, ' nodes.') if (cc != ct): print('FAIL: number of nodes differ.', cc, ct) return print(' Compare graphs: ', compare_graphs(G, H, C(()), H.vertices(sort=True)[0]))
def _test_with_lspaths_crystal(cartan_type, weight, depth=10): "\n Test if the digraphs generated are isomorphic to the ones generated by\n LS-path model.\n\n INPUT:\n\n - ``cartan_type`` -- Cartan type of a finite or affine untwisted root\n system\n - ``weight`` -- dominant weight as a list of (integral) coefficients of the\n fundamental weights\n - ``depth`` -- starting at the module generator how deep do you want to\n generate the crystal, useful for affine types\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.alcove_path import _test_with_lspaths_crystal\n sage: _test_with_lspaths_crystal(['A',3,1],[1,0,0,0],10) #long time\n True\n sage: _test_with_lspaths_crystal(['G',2,1],[1,0,0,0,0],10) #long time\n True\n " from sage.combinat.crystals.littelmann_path import CrystalOfLSPaths G1 = CrystalOfAlcovePaths(cartan_type, weight).digraph(depth=depth) C = CrystalOfLSPaths(cartan_type, weight) G2 = C.digraph(subset=C.subcrystal(max_depth=depth, direction='lower')) return G1.is_isomorphic(G2, edge_labels=True)
class CrystalOfBKKTableaux(CrystalOfWords): "\n Crystal of tableaux for type `A(m|n)`.\n\n This is an implementation of the tableaux model of the\n Benkart-Kang-Kashiwara crystal [BKK2000]_ for the Lie\n superalgebra `\\mathfrak{gl}(m+1,n+1)`.\n\n INPUT:\n\n - ``ct`` -- a super Lie Cartan type of type `A(m|n)`\n - ``shape`` -- shape specifying the highest weight; this should be\n a partition contained in a hook of height `n+1` and width `m+1`\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A', [1,1]], shape = [2,1])\n sage: T.cardinality()\n 20\n " @staticmethod def __classcall_private__(cls, ct, shape): "\n Normalize input to ensure a unique representation.\n\n TESTS::\n\n sage: crystals.Tableaux(['A', [1, 2]], shape=[2,1])\n Crystal of BKK tableaux of shape [2, 1] of gl(2|3)\n sage: crystals.Tableaux(['A', [1, 1]], shape=[3,3,3])\n Traceback (most recent call last):\n ...\n ValueError: invalid hook shape\n " ct = CartanType(ct) shape = _Partitions(shape) if ((len(shape) > (ct.m + 1)) and (shape[(ct.m + 1)] > (ct.n + 1))): raise ValueError('invalid hook shape') return super().__classcall__(cls, ct, shape) def __init__(self, ct, shape): "\n Initialize ``self``.\n\n TESTS::\n\n sage: T = crystals.Tableaux(['A', [1,1]], shape = [2,1]); T\n Crystal of BKK tableaux of shape [2, 1] of gl(2|2)\n sage: TestSuite(T).run()\n " self._shape = shape self._cartan_type = ct m = (ct.m + 1) C = CrystalOfBKKLetters(ct) tr = shape.conjugate() mg = [] for (i, col_len) in enumerate(tr): for j in range((col_len - m)): mg.append(C((i + 1))) for j in range(max(0, (m - col_len)), m): mg.append(C(((- j) - 1))) mg = list(reversed(mg)) Parent.__init__(self, category=RegularSuperCrystals()) self.module_generators = (self.element_class(self, mg),) def _repr_(self): "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: crystals.Tableaux(['A', [1, 2]], shape=[2,1])\n Crystal of BKK tableaux of shape [2, 1] of gl(2|3)\n " m = (self._cartan_type.m + 1) n = (self._cartan_type.n + 1) return 'Crystal of BKK tableaux of shape {} of gl({}|{})'.format(self.shape(), m, n) def shape(self): "\n Return the shape of ``self``.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A', [1, 2]], shape=[2,1])\n sage: T.shape()\n [2, 1]\n " return self._shape def genuine_highest_weight_vectors(self, index_set=None): "\n Return a tuple of genuine highest weight elements.\n\n A *fake highest weight vector* is one which is annihilated by\n `e_i` for all `i` in the index set, but whose weight is not\n bigger in dominance order than all other elements in the\n crystal. A *genuine highest weight vector* is a highest\n weight element that is not fake.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A', [1,1]], shape=[3,2,1])\n sage: B.genuine_highest_weight_vectors()\n ([[-2, -2, -2], [-1, -1], [1]],)\n sage: B.highest_weight_vectors()\n ([[-2, -2, -2], [-1, -1], [1]],\n [[-2, -2, -2], [-1, 2], [1]],\n [[-2, -2, 2], [-1, -1], [1]])\n " if ((index_set is None) or (index_set == self.index_set())): return self.module_generators return super().genuine_highest_weight_vectors(index_set) class Element(CrystalOfBKKTableauxElement): pass
class CrystalBacktracker(GenericBacktracker): def __init__(self, crystal, index_set=None): "\n Time complexity: `O(nF)` amortized for each produced\n element, where `n` is the size of the index set, and `F` is\n the cost of computing `e` and `f` operators.\n\n Memory complexity: `O(D)` where `D` is the depth of the crystal.\n\n Principle of the algorithm:\n\n Let `C` be a classical crystal. It's an acyclic graph where each\n connected component has a unique element without predecessors (the\n highest weight element for this component). Let's assume for\n simplicity that `C` is irreducible (i.e. connected) with highest\n weight element `u`.\n\n One can define a natural spanning tree of `C` by taking\n `u` as the root of the tree, and for any other element\n `y` taking as ancestor the element `x` such that\n there is an `i`-arrow from `x` to `y` with\n `i` minimal. Then, a path from `u` to `y`\n describes the lexicographically smallest sequence\n `i_1,\\dots,i_k` such that\n `(f_{i_k} \\circ f_{i_1})(u)=y`.\n\n Morally, the iterator implemented below just does a depth first\n search walk through this spanning tree. In practice, this can be\n achieved recursively as follows: take an element `x`, and\n consider in turn each successor `y = f_i(x)`, ignoring\n those such that `y = f_j(x^{\\prime})` for some `x^{\\prime}` and\n `j<i` (this can be tested by computing `e_j(y)`\n for `j<i`).\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.crystals import CrystalBacktracker\n sage: C = crystals.Tableaux(['B',3],shape=[3,2,1])\n sage: CB = CrystalBacktracker(C)\n sage: len(list(CB))\n 1617\n sage: CB = CrystalBacktracker(C, [1,2])\n sage: len(list(CB))\n 8\n " GenericBacktracker.__init__(self, None, None) self._crystal = crystal if (index_set is None): self._index_set = crystal.index_set() else: self._index_set = index_set def _rec(self, x, state): "\n Return an iterator for the (immediate) children of ``x`` in the search\n tree.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.crystals import CrystalBacktracker\n sage: C = crystals.Letters(['A', 5])\n sage: CB = CrystalBacktracker(C)\n sage: list(CB._rec(C(1), 'n/a'))\n [(2, 'n/a', True)]\n " if ((x is None) and (state is None)): for gen in self._crystal.highest_weight_vectors(): (yield (gen, 'n/a', True)) return for i in self._index_set: y = x.f(i) if (y is None): continue hasParent = False for j in self._index_set: if (j == i): break if (y.e(j) is not None): hasParent = True break if hasParent: continue (yield (y, 'n/a', True))
class DirectSumOfCrystals(DisjointUnionEnumeratedSets): "\n Direct sum of crystals.\n\n Given a list of crystals `B_0, \\ldots, B_k` of the same Cartan type,\n one can form the direct sum `B_0 \\oplus \\cdots \\oplus B_k`.\n\n INPUT:\n\n - ``crystals`` -- a list of crystals of the same Cartan type\n - ``keepkey`` -- a boolean\n\n The option ``keepkey`` is by default set to ``False``, assuming\n that the crystals are all distinct. In this case the elements of\n the direct sum are just represented by the elements in the\n crystals `B_i`. If the crystals are not all distinct, one should\n set the ``keepkey`` option to ``True``. In this case, the\n elements of the direct sum are represented as tuples `(i, b)`\n where `b \\in B_i`.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: C1 = crystals.Tableaux(['A',2],shape=[1,1])\n sage: B = crystals.DirectSum([C,C1])\n sage: B.list()\n [1, 2, 3, [[1], [2]], [[1], [3]], [[2], [3]]]\n sage: [b.f(1) for b in B]\n [2, None, None, None, [[2], [3]], None]\n sage: B.module_generators\n (1, [[1], [2]])\n\n ::\n\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: B.list()\n [(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3)]\n sage: B.module_generators\n ((0, 1), (1, 1))\n sage: b = B( tuple([0,C(1)]) )\n sage: b\n (0, 1)\n sage: b.weight()\n (1, 0, 0)\n\n The following is required, because\n :class:`~sage.combinat.crystals.direct_sum.DirectSumOfCrystals`\n takes the same arguments as :class:`DisjointUnionEnumeratedSets`\n (which see for details).\n\n TESTS::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: B\n Direct sum of the crystals Family (The crystal of letters for type ['A', 2], The crystal of letters for type ['A', 2])\n\n sage: TestSuite(C).run()\n " @staticmethod def __classcall_private__(cls, crystals, facade=True, keepkey=False, category=None): "\n Normalization of arguments; see :class:`UniqueRepresentation`.\n\n TESTS:\n\n We check that direct sum of crystals have unique representation::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: C = crystals.Letters(['A',2])\n sage: D1 = crystals.DirectSum([B, C])\n sage: D2 = crystals.DirectSum((B, C))\n sage: D1 is D2\n True\n sage: D3 = crystals.DirectSum([B, C, C])\n sage: D4 = crystals.DirectSum([D1, C])\n sage: D3 is D4\n True\n " if ((not isinstance(facade, bool)) or (not isinstance(keepkey, bool))): raise TypeError facade = (not keepkey) ret = [] for x in Family(crystals): if isinstance(x, DirectSumOfCrystals): ret += list(x.crystals) else: ret.append(x) category = Category.meet([Category.join(c.categories()) for c in ret]) return super().__classcall__(cls, Family(ret), facade=facade, keepkey=keepkey, category=category) def __init__(self, crystals, facade, keepkey, category, **options): "\n TESTS::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: B\n Direct sum of the crystals Family (The crystal of letters for type ['A', 2], The crystal of letters for type ['A', 2])\n sage: B.cartan_type()\n ['A', 2]\n\n sage: from sage.combinat.crystals.direct_sum import DirectSumOfCrystals\n sage: isinstance(B, DirectSumOfCrystals)\n True\n " DisjointUnionEnumeratedSets.__init__(self, crystals, keepkey=keepkey, facade=facade, category=category) self.rename('Direct sum of the crystals {}'.format(crystals)) self._keepkey = keepkey self.crystals = crystals if (len(crystals) == 0): raise ValueError('the direct sum is empty') else: assert all(((crystal.cartan_type() == crystals[0].cartan_type()) for crystal in crystals)) self._cartan_type = crystals[0].cartan_type() if keepkey: self.module_generators = tuple([self((i, b)) for (i, B) in enumerate(crystals) for b in B.module_generators]) else: self.module_generators = sum((tuple(B.module_generators) for B in crystals), ()) def weight_lattice_realization(self): "\n Return the weight lattice realization used to express weights.\n\n The weight lattice realization is the common parent which all\n weight lattice realizations of the crystals of ``self`` coerce\n into.\n\n EXAMPLES::\n\n sage: LaZ = RootSystem(['A',2,1]).weight_lattice(extended=True).fundamental_weights()\n sage: LaQ = RootSystem(['A',2,1]).weight_space(extended=True).fundamental_weights()\n sage: B = crystals.LSPaths(LaQ[1])\n sage: B.weight_lattice_realization()\n Extended weight space over the Rational Field of the Root system of type ['A', 2, 1]\n sage: C = crystals.AlcovePaths(LaZ[1])\n sage: C.weight_lattice_realization()\n Extended weight lattice of the Root system of type ['A', 2, 1]\n sage: D = crystals.DirectSum([B,C])\n sage: D.weight_lattice_realization()\n Extended weight space over the Rational Field of the Root system of type ['A', 2, 1]\n " cm = get_coercion_model() return cm.common_parent(*[crystal.weight_lattice_realization() for crystal in self.crystals]) class Element(ElementWrapper): '\n A class for elements of direct sums of crystals.\n ' def e(self, i): "\n Return the action of `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: [[b, b.e(2)] for b in B]\n [[(0, 1), None], [(0, 2), None], [(0, 3), (0, 2)], [(1, 1), None], [(1, 2), None], [(1, 3), (1, 2)]]\n " v = self.value vn = v[1].e(i) if (vn is None): return None else: return self.parent()(tuple([v[0], vn])) def f(self, i): "\n Return the action of `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: [[b,b.f(1)] for b in B]\n [[(0, 1), (0, 2)], [(0, 2), None], [(0, 3), None], [(1, 1), (1, 2)], [(1, 2), None], [(1, 3), None]]\n " v = self.value vn = v[1].f(i) if (vn is None): return None else: return self.parent()(tuple([v[0], vn])) def weight(self): "\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: b = B( tuple([0,C(2)]) )\n sage: b\n (0, 2)\n sage: b.weight()\n (0, 1, 0)\n " return self.value[1].weight() def phi(self, i): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: b = B( tuple([0,C(2)]) )\n sage: b.phi(2)\n 1\n " return self.value[1].phi(i) def epsilon(self, i): "\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',2])\n sage: B = crystals.DirectSum([C,C], keepkey=True)\n sage: b = B( tuple([0,C(2)]) )\n sage: b.epsilon(2)\n 0\n " return self.value[1].epsilon(i)
class AbstractSingleCrystalElement(Element): '\n Abstract base class for elements in crystals with a single element.\n ' def __lt__(self, other): '\n EXAMPLES::\n\n sage: La = RootSystem("D4").ambient_space().fundamental_weights()\n sage: T = crystals.elementary.T("D4",La[3]+La[4])\n sage: t = T.highest_weight_vector()\n sage: t < t.e(1)\n False\n sage: t < t\n False\n ' return False def __hash__(self): '\n TESTS::\n\n sage: C = crystals.elementary.Component("D7")\n sage: c = C.highest_weight_vector()\n sage: hash(c) # random\n 879\n ' return hash(self.parent()) def __eq__(self, other): '\n EXAMPLES::\n\n sage: La = RootSystem("A2").weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T("A2",La[1])\n sage: U = crystals.elementary.T("A2",La[2])\n sage: la = RootSystem("B2").weight_lattice().fundamental_weights()\n sage: V = crystals.elementary.T("B2",la[1])\n sage: t = T.highest_weight_vector()\n sage: u = U.highest_weight_vector()\n sage: v = V.highest_weight_vector()\n sage: [t == t, u == u, v == v]\n [True, True, True]\n sage: [t == u, u == v, t == v]\n [False, False, False]\n\n sage: C = crystals.elementary.Component("D7")\n sage: c = C.highest_weight_vector()\n sage: c == c\n True\n sage: c == c.f(7)\n False\n ' if isinstance(other, AbstractSingleCrystalElement): return (self.parent() is other.parent()) return False def __ne__(self, other): '\n EXAMPLES::\n\n sage: La = RootSystem("A2").weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T("A2",La[1])\n sage: T.highest_weight_vector() != T.highest_weight_vector()\n False\n sage: T.highest_weight_vector() != T.highest_weight_vector().e(1)\n True\n ' return (not (self == other)) def e(self, i): "\n Return `e_i` of ``self``, which is ``None`` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',2])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[1])\n sage: t = T.highest_weight_vector()\n sage: t.e(1)\n sage: t.e(2)\n " return None def f(self, i): "\n Return `f_i` of ``self``, which is ``None`` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',2])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[1])\n sage: t = T.highest_weight_vector()\n sage: t.f(1)\n sage: t.f(2)\n " return None
class TCrystal(UniqueRepresentation, Parent): "\n The crystal `T_{\\lambda}`.\n\n Let `\\lambda` be a weight. As defined in [Ka1993]_ the crystal\n `T_{\\lambda} = \\{ t_{\\lambda} \\}` is a single element crystal with the\n crystal structure defined by\n\n .. MATH::\n\n \\mathrm{wt}(t_\\lambda) = \\lambda, \\quad\n e_i t_{\\lambda} = f_i t_{\\lambda} = 0, \\quad\n \\varepsilon_i(t_{\\lambda}) = \\varphi_i(t_{\\lambda}) = -\\infty.\n\n The crystal `T_{\\lambda}` shifts the weights of the vertices in a crystal\n `B` by `\\lambda` when tensored with `B`, but leaves the graph structure of\n `B` unchanged. That is to say, for all `b \\in B`, we have `\\mathrm{wt}(b\n \\otimes t_{\\lambda}) = \\mathrm{wt}(b) + \\lambda`.\n\n INPUT:\n\n - ``cartan_type`` -- A Cartan type\n\n - ``weight`` -- An element of the weight lattice of type ``cartan_type``\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',2])\n sage: C = crystals.Tableaux(ct, shape=[1])\n sage: for x in C: x.weight()\n (1, 0, 0)\n (0, 1, 0)\n (0, 0, 1)\n sage: La = RootSystem(ct).ambient_space().fundamental_weights()\n sage: TLa = crystals.elementary.T(ct, 3*(La[1] + La[2]))\n sage: TP = crystals.TensorProduct(TLa, C)\n sage: for x in TP: x.weight()\n (7, 3, 0)\n (6, 4, 0)\n (6, 3, 1)\n sage: G = C.digraph()\n sage: H = TP.digraph()\n sage: G.is_isomorphic(H,edge_labels=True)\n True\n " @staticmethod def __classcall_private__(cls, cartan_type, weight=None): "\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',3])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: wts = RootSystem(ct).ambient_space().fundamental_weights()\n sage: X = crystals.elementary.T(['A',3], la[1])\n sage: Y = crystals.elementary.T(la[1])\n sage: X is Y\n True\n " if (weight is None): weight = cartan_type cartan_type = weight.parent().cartan_type() cartan_type = CartanType(cartan_type) return super().__classcall__(cls, cartan_type, weight) def __init__(self, cartan_type, weight): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: la = RootSystem("A2").weight_lattice().fundamental_weights()\n sage: B = crystals.elementary.T("A2", 5*la[2])\n sage: TestSuite(B).run()\n ' self._weight = weight self._cartan_type = cartan_type if (self._cartan_type.type() == 'Q'): category = SuperCrystals().Finite() else: category = (FiniteCrystals(), HighestWeightCrystals()) Parent.__init__(self, category=category) self.module_generators = (self.element_class(self),) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: la = RootSystem(['E',6]).weight_lattice().fundamental_weights()\n sage: B = crystals.elementary.T(['E',6], la[6])\n sage: B\n The T crystal of type ['E', 6] and weight Lambda[6]\n " return 'The T crystal of type {1!s} and weight {0!s}'.format(self._weight, self._cartan_type) def _element_constructor_(self, weight): '\n Construct an element of ``self`` from ``weight``.\n\n INPUT:\n\n - ``weight`` -- An element of the weight lattice\n\n EXAMPLES::\n\n sage: la = RootSystem("E8").weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T("E8",la[7]+la[8])\n sage: T(la[7]+la[8])\n Lambda[7] + Lambda[8]\n ' if (weight != self._weight): raise ValueError(('only element is t(%s)' % self._weight)) return self.element_class(self) def cardinality(self): "\n Return the cardinality of ``self``, which is always `1`.\n\n EXAMPLES::\n\n sage: La = RootSystem(['C',12]).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(['C',12], La[9])\n sage: T.cardinality()\n 1\n " return ZZ.one() def weight_lattice_realization(self): "\n Return a realization of the lattice containing the weights\n of ``self``.\n\n EXAMPLES::\n\n sage: La = RootSystem(['C',12]).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(['C',12], La[9])\n sage: T.weight_lattice_realization()\n Weight lattice of the Root system of type ['C', 12]\n\n sage: ct = CartanMatrix([[2, -4], [-5, 2]])\n sage: La = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct, La[1])\n sage: T.weight_lattice_realization()\n Weight lattice of the Root system of type\n [ 2 -4]\n [-5 2]\n " return self._weight.parent() class Element(AbstractSingleCrystalElement): '\n Element of a `T_{\\lambda}` crystal.\n ' def _repr_(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F',4])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,2*la[1]-3*la[3])\n sage: t = T.highest_weight_vector()\n sage: t\n 2*Lambda[1] - 3*Lambda[3]\n " return repr(self.parent()._weight) def _latex_(self): "\n Return a LaTeX representation of ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['B',5,1])\n sage: la = RootSystem(ct).ambient_space().fundamental_weights()\n sage: T = crystals.elementary.T(ct, 2*la[1]-3*la[3]+la[0])\n sage: t = T.highest_weight_vector()\n sage: latex(t)\n {t_{-e_{0} - 3 e_{1} - 3 e_{2} - 3 e_{deltacheck}}}\n " return (('{t_{' + self.parent()._weight._latex_()) + '}}') def epsilon(self, i): "\n Return `\\varepsilon_i` of ``self``, which is `-\\infty` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: ct = CartanType(['C',5])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[4]+la[5]-la[1]-la[2])\n sage: t = T.highest_weight_vector()\n sage: [t.epsilon(i) for i in T.index_set()]\n [-inf, -inf, -inf, -inf, -inf]\n " return float('-inf') def phi(self, i): "\n Return `\\varphi_i` of ``self``, which is `-\\infty` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: ct = CartanType(['C',5])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[4]+la[5]-la[1]-la[2])\n sage: t = T.highest_weight_vector()\n sage: [t.phi(i) for i in T.index_set()]\n [-inf, -inf, -inf, -inf, -inf]\n " return float('-inf') def weight(self): "\n Return the weight of ``self``, which is always `\\lambda`.\n\n EXAMPLES::\n\n sage: ct = CartanType(['C',5])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[4]+la[5]-la[1]-la[2])\n sage: t = T.highest_weight_vector()\n sage: t.weight()\n -Lambda[1] - Lambda[2] + Lambda[4] + Lambda[5]\n " return self.parent()._weight
class RCrystal(UniqueRepresentation, Parent): '\n The crystal `R_{\\lambda}`.\n\n For a fixed weight `\\lambda`, the crystal `R_{\\lambda} = \\{ r_{\\lambda} \\}`\n is a single element crystal with the crystal structure defined by\n\n .. MATH::\n\n \\mathrm{wt}(r_{\\lambda}) = \\lambda, \\quad\n e_i r_{\\lambda} = f_i r_{\\lambda} = 0, \\quad\n \\varepsilon_i(r_{\\lambda}) = -\\langle h_i, \\lambda\\rangle, \\quad\n \\varphi_i(r_{\\lambda}) = 0,\n\n where `\\{h_i\\}` are the simple coroots.\n\n Tensoring `R_{\\lambda}` with a crystal `B` results in shifting the weights\n of the vertices in `B` by `\\lambda` and may also cut a subset out of the\n original graph of `B`. That is, `\\mathrm{wt}(r_{\\lambda} \\otimes b) =\n \\mathrm{wt}(b) + \\lambda`, where `b \\in B`, provided `r_{\\lambda} \\otimes\n b \\neq 0`. For example, the crystal graph of `B(\\lambda)` is the same as\n the crystal graph of `R_{\\lambda} \\otimes B(\\infty)` generated from the\n component `r_{\\lambda} \\otimes u_{\\infty}`.\n\n There is also a dual version of this crystal given by\n `R^{\\vee}_{\\lambda} = \\{ r^{\\vee}_{\\lambda} \\}` with the crystal\n structure defined by\n\n .. MATH::\n\n \\mathrm{wt}(r^{\\vee}_{\\lambda}) = \\lambda, \\quad\n e_i r^{\\vee}_{\\lambda} = f_i r^{\\vee}_{\\lambda} = 0, \\quad\n \\varepsilon_i(r^{\\vee}_{\\lambda}) = 0, \\quad\n \\varphi_i(r^{\\vee}_{\\lambda}) = \\langle h_i, \\lambda\\rangle.\n\n INPUT:\n\n - ``cartan_type`` -- a Cartan type\n - ``weight`` -- an element of the weight lattice of type ``cartan_type``\n - ``dual`` -- (default: ``False``) boolean\n\n EXAMPLES:\n\n We check by tensoring `R_{\\lambda}` with `B(\\infty)` results in a\n component of `B(\\lambda)`::\n\n sage: B = crystals.infinity.Tableaux("A2")\n sage: R = crystals.elementary.R("A2", B.Lambda()[1]+B.Lambda()[2])\n sage: T = crystals.TensorProduct(R, B)\n sage: mg = T(R.highest_weight_vector(), B.highest_weight_vector())\n sage: S = T.subcrystal(generators=[mg])\n sage: sorted([x.weight() for x in S], key=str)\n [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 1, 1),\n (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0)]\n sage: C = crystals.Tableaux("A2", shape=[2,1])\n sage: sorted([x.weight() for x in C], key=str)\n [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 1, 1),\n (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0)]\n sage: GT = T.digraph(subset=S)\n sage: GC = C.digraph()\n sage: GT.is_isomorphic(GC, edge_labels=True)\n True\n ' @staticmethod def __classcall_private__(cls, cartan_type, weight=None, dual=False): "\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',3])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: X = crystals.elementary.R(['A',3], la[1])\n sage: Y = crystals.elementary.R(la[1])\n sage: X is Y\n True\n " if (weight is None): weight = cartan_type cartan_type = weight.parent().cartan_type() cartan_type = CartanType(cartan_type) return super().__classcall__(cls, cartan_type, weight, dual) def __init__(self, cartan_type, weight, dual): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: la = RootSystem("A2").weight_lattice().fundamental_weights()\n sage: B = crystals.elementary.R("A2",5*la[2])\n sage: TestSuite(B).run()\n ' self._weight = weight self._cartan_type = cartan_type self._dual = dual if (self._cartan_type.type() == 'Q'): category = SuperCrystals().Finite() else: category = (FiniteCrystals(), HighestWeightCrystals()) Parent.__init__(self, category=category) self.module_generators = (self.element_class(self),) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: la = RootSystem(['E',6]).weight_lattice().fundamental_weights()\n sage: B = crystals.elementary.R(['E',6], la[6])\n sage: B\n The R crystal of weight Lambda[6] and type ['E', 6]\n\n sage: crystals.elementary.R(['E',6], la[1], dual=True)\n The dual R crystal of weight Lambda[1] and type ['E', 6]\n " dual_str = (' dual' if self._dual else '') return 'The{} R crystal of weight {} and type {}'.format(dual_str, self._weight, self._cartan_type) def _element_constructor_(self, weight): '\n Construct an element of ``self`` from ``weight``.\n\n INPUT:\n\n - ``weight`` -- An element of the weight lattice\n\n EXAMPLES::\n\n sage: la = RootSystem("E8").weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R("E8",la[7]+la[8])\n sage: R(la[7]+la[8])\n Lambda[7] + Lambda[8]\n ' if (weight != self._weight): raise ValueError(('Only element is r(%s)' % self._weight)) return self.element_class(self) def cardinality(self): "\n Return the cardinality of ``self``, which is always `1`.\n\n EXAMPLES::\n\n sage: La = RootSystem(['C',12]).weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R(['C',12],La[9])\n sage: R.cardinality()\n 1\n " return ZZ.one() def weight_lattice_realization(self): "\n Return a realization of the lattice containing the weights\n of ``self``.\n\n EXAMPLES::\n\n sage: La = RootSystem(['C',12]).weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R(['C',12], La[9])\n sage: R.weight_lattice_realization()\n Weight lattice of the Root system of type ['C', 12]\n\n sage: ct = CartanMatrix([[2, -4], [-5, 2]])\n sage: La = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R(ct, La[1])\n sage: R.weight_lattice_realization()\n Weight lattice of the Root system of type\n [ 2 -4]\n [-5 2]\n " return self._weight.parent() class Element(AbstractSingleCrystalElement): '\n Element of a `R_{\\lambda}` crystal.\n ' def _repr_(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F',4])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,2*la[1]-3*la[3])\n sage: t = T.highest_weight_vector()\n sage: t\n 2*Lambda[1] - 3*Lambda[3]\n " return repr(self.parent()._weight) def _latex_(self): '\n Return a LaTeX representation of ``self``.\n\n EXAMPLES::\n\n sage: la = RootSystem("G2").weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R("G2",la[1])\n sage: r = R.highest_weight_vector()\n sage: latex(r)\n {r_{\\Lambda_{1}}}\n\n sage: R = crystals.elementary.R("G2", la[1], dual=True)\n sage: latex(R.highest_weight_vector())\n {r^{\\vee}_{\\Lambda_{1}}}\n ' if self.parent()._dual: return (('{r^{\\vee}_{' + self.parent()._weight._latex_()) + '}}') return (('{r_{' + self.parent()._weight._latex_()) + '}}') def epsilon(self, i): '\n Return `\\varepsilon_i` of ``self``.\n\n We have `\\varepsilon_i(r_{\\lambda}) = -\\langle h_i, \\lambda\n \\rangle` for all `i`, where `h_i` is a simple coroot.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: la = RootSystem([\'A\',2]).weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R("A2", la[1])\n sage: r = R.highest_weight_vector()\n sage: [r.epsilon(i) for i in R.index_set()]\n [-1, 0]\n\n sage: R = crystals.elementary.R("A2", la[1], dual=True)\n sage: r = R.highest_weight_vector()\n sage: [r.epsilon(i) for i in R.index_set()]\n [0, 0]\n ' if self.parent()._dual: return ZZ.zero() else: P = self.parent().weight_lattice_realization() h = P.simple_coroots() return (- P(self.weight()).scalar(h[i])) def phi(self, i): '\n Return `\\varphi_i` of ``self``, which is `0` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: la = RootSystem("C5").weight_lattice().fundamental_weights()\n sage: R = crystals.elementary.R("C5", la[4]+la[5])\n sage: r = R.highest_weight_vector()\n sage: [r.phi(i) for i in R.index_set()]\n [0, 0, 0, 0, 0]\n\n sage: R = crystals.elementary.R("C5", la[4]+la[5], dual=True)\n sage: r = R.highest_weight_vector()\n sage: [r.phi(i) for i in R.index_set()]\n [0, 0, 0, 1, 1]\n ' if self.parent()._dual: P = self.parent().weight_lattice_realization() h = P.simple_coroots() return P(self.weight()).scalar(h[i]) else: return ZZ.zero() def weight(self): "\n Return the weight of ``self``, which is always `\\lambda`.\n\n EXAMPLES::\n\n sage: ct = CartanType(['C',5])\n sage: la = RootSystem(ct).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(ct,la[4]+la[5]-la[1]-la[2])\n sage: t = T.highest_weight_vector()\n sage: t.weight()\n -Lambda[1] - Lambda[2] + Lambda[4] + Lambda[5]\n " return self.parent()._weight
class ElementaryCrystal(UniqueRepresentation, Parent): '\n The elementary crystal `B_i`.\n\n For `i` an element of the index set of type `X`, the crystal `B_i` of type\n `X` is the set\n\n .. MATH::\n\n B_i = \\{ b_i(m) : m \\in \\ZZ \\},\n\n where the crystal structure is given by\n\n .. MATH::\n\n \\begin{aligned}\n \\mathrm{wt}\\bigl(b_i(m)\\bigr) &= m\\alpha_i \\\\\n \\varphi_j\\bigl(b_i(m)\\bigr) &= \\begin{cases}\n m & \\text{ if } j=i, \\\\\n -\\infty & \\text{ if } j\\neq i,\n \\end{cases} \\\\\n \\varepsilon_j\\bigl(b_i(m)\\bigr) &= \\begin{cases}\n -m & \\text{ if } j=i, \\\\\n -\\infty & \\text{ if } j\\neq i,\n \\end{cases} \\\\\n e_j b_i(m) &= \\begin{cases}\n b_i(m+1) & \\text{ if } j=i, \\\\\n 0 & \\text{ if } j\\neq i,\n \\end{cases} \\\\\n f_j b_i(m) &= \\begin{cases}\n b_i(m-1) & \\text{ if } j=i, \\\\\n 0 & \\text{ if } j\\neq i.\n \\end{cases}\n \\end{aligned}\n\n The *Kashiwara embedding theorem* asserts there is a unique strict crystal\n embedding of crystals\n\n .. MATH::\n\n B(\\infty) \\hookrightarrow B_i \\otimes B(\\infty),\n\n satisfying certain properties (see [Ka1993]_). The above embedding\n may be iterated to obtain a new embedding\n\n .. MATH::\n\n B(\\infty) \\hookrightarrow B_{i_N} \\otimes B_{i_{N-1}}\n \\otimes \\cdots \\otimes B_{i_2} \\otimes B_{i_1} \\otimes B(\\infty),\n\n which is a foundational object in the study of *polyhedral realizations of\n crystals* (see, for example, [NZ1997]_).\n ' @staticmethod def __classcall_private__(cls, cartan_type, i): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary([\'A\',4], 3)\n sage: C = crystals.elementary.Elementary(CartanType("A4"), int(3))\n sage: B is C\n True\n ' cartan_type = CartanType(cartan_type) if (i not in cartan_type.index_set()): raise ValueError('i must an element of the index set') return super().__classcall__(cls, cartan_type, i) def __init__(self, cartan_type, i): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary("D4",3)\n sage: TestSuite(B).run()\n ' Parent.__init__(self, category=(Crystals(), InfiniteEnumeratedSets())) self._i = i self._cartan_type = cartan_type self.module_generators = (self.element_class(self, 0),) def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['B',5,1], 4)\n sage: B\n The 4-elementary crystal of type ['B', 5, 1]\n " return 'The {0!s}-elementary crystal of type {1!s}'.format(self._i, self._cartan_type) def _element_constructor_(self, m): "\n Construct an element of ``self`` from ``weight``.\n\n INPUT:\n\n - ``m`` -- An integer\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['F',4], 2)\n sage: B(0)\n 0\n sage: B(-15)\n -15\n sage: B(721)\n 721\n " return self.element_class(self, ZZ(m)) def weight_lattice_realization(self): "\n Return a realization of the lattice containing the weights\n of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['A',4, 1], 2)\n sage: B.weight_lattice_realization()\n Root lattice of the Root system of type ['A', 4, 1]\n " return self.cartan_type().root_system().root_lattice() class Element(Element): '\n Element of a `B_i` crystal.\n ' def __init__(self, parent, m): "\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['B',7],7)\n sage: elt = B(17); elt\n 17\n " self._m = m Element.__init__(self, parent) def __hash__(self): "\n TESTS::\n\n sage: B = crystals.elementary.Elementary(['B',7],7)\n sage: hash(B(17))\n 17\n " return hash(self._m) def _repr_(self): "\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['A',4],3)\n sage: B(-47)\n -47\n " return repr(self._m) def __lt__(self, other): '\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary("D4",3)\n sage: b = B(1)\n sage: c = B(-1)\n sage: b.__lt__(c)\n False\n sage: c.__lt__(b)\n True\n ' if (self.parent() is not other.parent()): return False return (Integer(self._m) < Integer(other._m)) def __eq__(self, other): '\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary("A2",1)\n sage: C = crystals.elementary.Elementary("A2",2)\n sage: D = crystals.elementary.Elementary("B2",1)\n sage: [B(0) == B(1), B(0) == C(0), B(0) == D(0), C(0) == D(0)]\n [False, False, False, False]\n sage: [B(1) == B(1), C(12) == C(12), D(-1) == D(-1)]\n [True, True, True]\n ' if isinstance(other, ElementaryCrystal.Element): return ((self.parent() is other.parent()) and (self._m == other._m)) return False def __ne__(self, other): '\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary("A2",1)\n sage: B(0) != B(2)\n True\n sage: B(0) != B(0)\n False\n ' return (not (self == other)) def _latex_(self): "\n Return a LaTeX representation of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['B',11,1],6)\n sage: latex(B(26))\n {b_{6}(26)}\n " return ('{b_{%s}(%s)}' % (self.parent()._i, self._m)) def e(self, i): "\n Return the action of `e_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['E',7],1)\n sage: B(3).e(1)\n 4\n sage: B(172).e_string([1]*171)\n 343\n sage: B(0).e(2)\n " if (i == self.parent()._i): return self.__class__(self.parent(), (self._m + 1)) else: return None def f(self, i): "\n Return the action of `f_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['E',7],1)\n sage: B(3).f(1)\n 2\n sage: B(172).f_string([1]*171)\n 1\n sage: B(0).e(2)\n " if (i == self.parent()._i): return self.__class__(self.parent(), (self._m - 1)) else: return None def epsilon(self, i): "\n Return `\\varepsilon_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['F',4],3)\n sage: [[B(j).epsilon(i) for i in B.index_set()] for j in range(5)]\n [[-inf, -inf, 0, -inf],\n [-inf, -inf, -1, -inf],\n [-inf, -inf, -2, -inf],\n [-inf, -inf, -3, -inf],\n [-inf, -inf, -4, -inf]]\n " if (i == self.parent()._i): return (- self._m) else: return float('-inf') def phi(self, i): "\n Return `\\varphi_i` of ``self``.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['E',8,1],4)\n sage: [[B(m).phi(j) for j in B.index_set()] for m in range(44,49)]\n [[-inf, -inf, -inf, -inf, 44, -inf, -inf, -inf, -inf],\n [-inf, -inf, -inf, -inf, 45, -inf, -inf, -inf, -inf],\n [-inf, -inf, -inf, -inf, 46, -inf, -inf, -inf, -inf],\n [-inf, -inf, -inf, -inf, 47, -inf, -inf, -inf, -inf],\n [-inf, -inf, -inf, -inf, 48, -inf, -inf, -inf, -inf]]\n " if (i == self.parent()._i): return self._m else: return float('-inf') def weight(self): "\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Elementary(['C',14],12)\n sage: B(-385).weight()\n -385*alpha[12]\n " Q = self.parent().weight_lattice_realization() return (self._m * Q.simple_root(self.parent()._i))
class ComponentCrystal(UniqueRepresentation, Parent): '\n The component crystal.\n\n Defined in [Ka1993]_, the component crystal `C = \\{c\\}` is the single\n element crystal whose crystal structure is defined by\n\n .. MATH::\n\n \\mathrm{wt}(c) = 0, \\quad\n e_i c = f_i c = 0, \\quad\n \\varepsilon_i(c) = \\varphi_i(c) = 0.\n\n Note `C \\cong B(0)`, where `B(0)` is the highest weight crystal of highest\n weight `0`.\n\n INPUT:\n\n - ``cartan_type`` -- a Cartan type\n ' @staticmethod def __classcall_private__(cls, cartan_type, P=None): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("A2")\n sage: D = crystals.elementary.Component(CartanType([\'A\',2]))\n sage: C is D\n True\n sage: AS = RootSystem([\'A\',2]).ambient_space()\n sage: E = crystals.elementary.Component(AS)\n sage: F = crystals.elementary.Component(CartanType([\'A\',2]), AS)\n sage: C is E and C is F\n True\n ' if (cartan_type in RootLatticeRealizations): P = cartan_type cartan_type = P.cartan_type() elif (P is None): cartan_type = CartanType(cartan_type) P = cartan_type.root_system().ambient_space() if (P is None): P = cartan_type.root_system().weight_lattice() return super().__classcall__(cls, cartan_type, P) def __init__(self, cartan_type, P): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.elementary.Component("D4")\n sage: TestSuite(B).run()\n ' self._weight_lattice_realization = P self._cartan_type = cartan_type if (self._cartan_type.type() == 'Q'): category = RegularSuperCrystals() else: category = (RegularCrystals().Finite(), HighestWeightCrystals()) Parent.__init__(self, category=category) self.module_generators = (self.element_class(self),) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("D4")\n sage: C\n The component crystal of type [\'D\', 4]\n ' return 'The component crystal of type {0!s}'.format(self._cartan_type) def _element_constructor_(self, weight): '\n Construct an element of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("E6")\n sage: c = C.highest_weight_vector()\n sage: c\n c\n ' if (weight != self.weight_lattice_realization().zero()): raise ValueError('only element is c') return self.element_class(self) def cardinality(self): '\n Return the cardinality of ``self``, which is always `1`.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("E6")\n sage: c = C.highest_weight_vector()\n sage: C.cardinality()\n 1\n ' return ZZ.one() def weight_lattice_realization(self): '\n Return the weight lattice realization of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("A2")\n sage: C.weight_lattice_realization()\n Ambient space of the Root system of type [\'A\', 2]\n\n sage: P = RootSystem([\'A\',2]).weight_lattice()\n sage: C = crystals.elementary.Component(P)\n sage: C.weight_lattice_realization() is P\n True\n ' return self._weight_lattice_realization class Element(AbstractSingleCrystalElement): '\n Element of a component crystal.\n ' def _repr_(self): '\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("F4")\n sage: c = C.highest_weight_vector()\n sage: c\n c\n ' return 'c' def _latex_(self): '\n Return a LaTeX representation of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("E7")\n sage: c = C.highest_weight_vector()\n sage: latex(c)\n {c}\n ' return '{c}' def epsilon(self, i): '\n Return `\\varepsilon_i` of ``self``, which is `0` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("C5")\n sage: c = C.highest_weight_vector()\n sage: [c.epsilon(i) for i in C.index_set()]\n [0, 0, 0, 0, 0]\n ' return 0 def phi(self, i): '\n Return `\\varphi_i` of ``self``, which is `0` for all `i`.\n\n INPUT:\n\n - ``i`` -- An element of the index set\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("C5")\n sage: c = C.highest_weight_vector()\n sage: [c.phi(i) for i in C.index_set()]\n [0, 0, 0, 0, 0]\n ' return 0 def weight(self): '\n Return the weight of ``self``, which is always `0`.\n\n EXAMPLES::\n\n sage: C = crystals.elementary.Component("F4")\n sage: c = C.highest_weight_vector()\n sage: c.weight()\n (0, 0, 0, 0)\n ' return self.parent().weight_lattice_realization().zero()
class FastCrystal(UniqueRepresentation, Parent): "\n An alternative implementation of rank 2 crystals. The root\n operators are implemented in memory by table lookup. This means\n that in comparison with the\n :class:`~sage.combinat.crystals.tensor_product.CrystalsOfTableaux`, these\n crystals are slow to instantiate but faster for computation. Implemented\n for types `A_2`, `B_2`, and `C_2`.\n\n INPUT:\n\n - ``cartan_type`` -- the Cartan type and must be either type `A_2`, `B_2`, or `C_2`\n\n - ``shape`` -- A shape is of the form ``[l1,l2]`` where ``l1`` and ``l2``\n are either integers or (in type `B_2`) half integers such that\n ``l1 - l2`` is integral. It is assumed that ``l1 >= l2 >= 0``. If\n ``l1`` and ``l2` are integers, this will produce a crystal\n isomorphic to the one obtained by\n ``crystals.Tableaux(type, shape=[l1,l2])``. Furthermore\n ``crystals.FastRankTwo(['B', 2], l1+1/2, l2+1/2)`` produces a crystal\n isomorphic to the following crystal ``T``::\n\n sage: C = crystals.Tableaux(['B',2], shape=[l1,l2]) # not tested\n sage: D = crystals.Spins(['B',2]) # not tested\n sage: T = crystals.TensorProduct(C, D, C.list()[0], D.list()[0]) # not tested\n\n - ``format`` -- (default: ``'string'``) the default representation of\n elements is in term of theBerenstein-Zelevinsky-Littelmann (BZL)\n strings ``[a1, a2, ...]`` described under metapost in\n :mod:`~sage.categories.crystals`. Alternative representations may be\n obtained by the options ``'dual_string'`` or ``'simple'``.\n In the ``'simple'`` format, the element is represented by and integer,\n and in the ``'dual_string'`` format, it is represented by the\n BZL string, but the underlying decomposition of the long Weyl group\n element into simple reflections is changed.\n\n TESTS::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[4,1])\n sage: C.cardinality()\n 24\n sage: C.cartan_type()\n ['A', 2]\n sage: TestSuite(C).run()\n sage: C = crystals.FastRankTwo(['B',2],shape=[4,1])\n sage: C.cardinality()\n 154\n sage: TestSuite(C).run()\n sage: C = crystals.FastRankTwo(['B',2],shape=[3/2,1/2])\n sage: C.cardinality()\n 16\n sage: TestSuite(C).run()\n sage: C = crystals.FastRankTwo(['C',2],shape=[2,1])\n sage: C.cardinality()\n 16\n sage: C = crystals.FastRankTwo(['C',2],shape=[3,1])\n sage: C.cardinality()\n 35\n sage: TestSuite(C).run()\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C.list()\n [[0, 0, 0],\n [1, 0, 0],\n [0, 1, 1],\n [0, 2, 1],\n [1, 2, 1],\n [0, 1, 0],\n [1, 1, 0],\n [2, 1, 0]]\n " @staticmethod def __classcall__(cls, cartan_type, shape, format='string'): "\n Normalize the input arguments to ensure unique representation\n\n EXAMPLES::\n\n sage: C1 = crystals.FastRankTwo(['A',2], shape=(4,1))\n sage: C2 = crystals.FastRankTwo(CartanType(['A',2]),shape=[4,1])\n sage: C1 is C2\n True\n " cartan_type = CartanType(cartan_type) shape = tuple(shape) if (len(shape) > 2): raise ValueError('The shape must have length <=2') shape = (shape + ((0,) * (2 - len(shape)))) return super().__classcall__(cls, cartan_type, shape, format) def __init__(self, ct, shape, format): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[4,1]); C\n The fast crystal for A2 with shape [4,1]\n sage: TestSuite(C).run()\n " Parent.__init__(self, category=ClassicalCrystals()) self._cartan_type = ct if (ct[1] != 2): raise NotImplementedError l1 = shape[0] l2 = shape[1] self.delpat = [] self.gampat = [] if (ct[0] == 'A'): self._type_a_init(l1, l2) elif ((ct[0] == 'B') or (ct[0] == 'C')): self._type_bc_init(l1, l2) else: raise NotImplementedError self.format = format self.size = len(self.delpat) self._rootoperators = [] self.shape = shape for i in range(self.size): target = [x for x in self.delpat[i]] target[0] = (target[0] - 1) e1 = (None if (target not in self.delpat) else self.delpat.index(target)) target[0] = ((target[0] + 1) + 1) f1 = (None if (target not in self.delpat) else self.delpat.index(target)) target = [x for x in self.gampat[i]] target[0] = (target[0] - 1) e2 = (None if (target not in self.gampat) else self.gampat.index(target)) target[0] = ((target[0] + 1) + 1) f2 = (None if (target not in self.gampat) else self.gampat.index(target)) self._rootoperators.append([e1, f1, e2, f2]) if ((int((2 * l1)) % 2) == 0): l1_str = ('%d' % l1) l2_str = ('%d' % l2) else: assert ((self._cartan_type[0] == 'B') and ((int((2 * l2)) % 2) == 1)) l1_str = ('%d/2' % int((2 * l1))) l2_str = ('%d/2' % int((2 * l2))) self.rename(('The fast crystal for %s2 with shape [%s,%s]' % (ct[0], l1_str, l2_str))) self.module_generators = [self(0)] self._digraph = super().digraph() self._digraph_closure = self.digraph().transitive_closure() def _type_a_init(self, l1, l2): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[1,1])\n sage: C.delpat # indirect doctest\n [[0, 0, 0], [0, 1, 0], [1, 1, 0]]\n sage: C.gampat\n [[0, 0, 0], [1, 0, 0], [0, 1, 1]]\n " for b in range(l2, (- 1), (- 1)): for a in range(l1, (l2 - 1), (- 1)): for c in range(a, (b - 1), (- 1)): a3 = (l1 - a) a2 = (((l1 + l2) - a) - b) a1 = (a - c) b1 = max(a3, (a2 - a1)) b2 = (a1 + a3) b3 = min((a2 - a3), a1) self.delpat.append([a1, a2, a3]) self.gampat.append([b1, b2, b3]) def _type_bc_init(self, l1, l2): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['B',2],shape=[1])\n sage: len(C.delpat) # indirect doctest\n 5\n sage: len(C.gampat)\n 5\n sage: C = crystals.FastRankTwo(['C',2],shape=[1])\n sage: len(C.delpat)\n 4\n sage: len(C.gampat)\n 4\n " if (self._cartan_type[0] == 'B'): [m1, m2] = [(l1 + l2), (l1 - l2)] else: [m1, m2] = [l1, l2] for b in range(m2, (- 1), (- 1)): for a in range(m1, (m2 - 1), (- 1)): for c in range(b, (a + 1)): for d in range(c, (- 1), (- 1)): a1 = (c - d) a2 = ((((m1 + m2) + c) - a) - (2 * b)) a3 = (((m1 + m2) - a) - b) a4 = (m1 - a) b1 = max(a4, ((2 * a3) - a2), (a2 - (2 * a1))) b2 = max(a3, (a1 + a4), ((a1 + (2 * a3)) - a2)) b3 = min(a2, (((2 * a2) - (2 * a3)) + a4), ((2 * a1) + a4)) b4 = min(a1, (a2 - a3), (a3 - a4)) if (self._cartan_type[0] == 'B'): self.delpat.append([a1, a2, a3, a4]) self.gampat.append([b1, b2, b3, b4]) else: self.gampat.append([a1, a2, a3, a4]) self.delpat.append([b1, b2, b3, b4]) def __call__(self, value): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C(0)\n [0, 0, 0]\n sage: C(1)\n [1, 0, 0]\n sage: x = C(0)\n sage: C(x) is x\n True\n " if (parent(value) is self): return value return self.element_class(self, value, self.format) def digraph(self): "\n Return the digraph associated to self.\n\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C.digraph()\n Digraph on 8 vertices\n " return self._digraph def cmp_elements(self, x, y): "\n Return True if and only if there is a path from x to y in the\n crystal graph.\n\n Because the crystal graph is classical, it is a directed acyclic\n graph which can be interpreted as a poset. This function implements\n the comparison function of this poset.\n\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: x = C(0)\n sage: y = C(1)\n sage: C.cmp_elements(x,y)\n -1\n sage: C.cmp_elements(y,x)\n 1\n sage: C.cmp_elements(x,x)\n 0\n " assert ((x.parent() == self) and (y.parent() == self)) if self._digraph_closure.has_edge(x, y): return (- 1) elif self._digraph_closure.has_edge(y, x): return 1 else: return 0 class Element(Element): def __init__(self, parent, value, format): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: c = C(0); c\n [0, 0, 0]\n sage: C[0].parent()\n The fast crystal for A2 with shape [2,1]\n sage: TestSuite(c).run()\n " Element.__init__(self, parent) self.value = value self.format = format def weight(self): "\n Return the weight of self.\n\n EXAMPLES::\n\n sage: [v.weight() for v in crystals.FastRankTwo(['A',2], shape=[2,1])]\n [(2, 1, 0), (1, 2, 0), (1, 1, 1), (1, 0, 2), (0, 1, 2), (2, 0, 1), (1, 1, 1), (0, 2, 1)]\n sage: [v.weight() for v in crystals.FastRankTwo(['B',2], shape=[1,0])]\n [(1, 0), (0, 1), (0, 0), (0, -1), (-1, 0)]\n sage: [v.weight() for v in crystals.FastRankTwo(['B',2], shape=[1/2,1/2])]\n [(1/2, 1/2), (1/2, -1/2), (-1/2, 1/2), (-1/2, -1/2)]\n sage: [v.weight() for v in crystals.FastRankTwo(['C',2], shape=[1,0])]\n [(1, 0), (0, 1), (0, -1), (-1, 0)]\n sage: [v.weight() for v in crystals.FastRankTwo(['C',2], shape=[1,1])]\n [(1, 1), (1, -1), (0, 0), (-1, 1), (-1, -1)]\n " delpat = self.parent().delpat[self.value] if (self.parent()._cartan_type[0] == 'A'): delpat = (delpat + [0]) [alpha1, alpha2] = self.parent().weight_lattice_realization().simple_roots() hwv = sum(((self.parent().shape[i] * self.parent().weight_lattice_realization().monomial(i)) for i in range(2))) return ((hwv - ((delpat[0] + delpat[2]) * alpha1)) - ((delpat[1] + delpat[3]) * alpha2)) def _repr_(self): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C[0]._repr_()\n '[0, 0, 0]'\n " if (self.format == 'string'): return repr(self.parent().delpat[self.value]) elif (self.format == 'dual_string'): return repr(self.parent().gampat[self.value]) elif (self.format == 'simple'): return repr(self.value) else: raise NotImplementedError def __hash__(self): "\n TESTS::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: hash(C(0))\n 0\n " return hash(self.value) def _richcmp_(self, other, op): "\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: D = crystals.FastRankTwo(['B',2],shape=[2,1])\n sage: C(0) == C(0)\n True\n sage: C(1) == C(0)\n False\n sage: C(0) == D(0)\n False\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: D = crystals.FastRankTwo(['B',2],shape=[2,1])\n sage: C(0) != C(0)\n False\n sage: C(1) != C(0)\n True\n sage: C(0) != D(0)\n True\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C(1) < C(2)\n True\n sage: C(2) < C(1)\n False\n sage: C(2) > C(1)\n True\n sage: C(1) <= C(1)\n True\n " return richcmp(self.value, other.value, op) def e(self, i): "\n Return the action of `e_i` on self.\n\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C(1).e(1)\n [0, 0, 0]\n sage: C(0).e(1) is None\n True\n " assert (i in self.index_set()) if (i == 1): r = self.parent()._rootoperators[self.value][0] else: r = self.parent()._rootoperators[self.value][2] return (self.parent()(r) if (r is not None) else None) def f(self, i): "\n Return the action of `f_i` on self.\n\n EXAMPLES::\n\n sage: C = crystals.FastRankTwo(['A',2],shape=[2,1])\n sage: C(6).f(1)\n [1, 2, 1]\n sage: C(7).f(1) is None\n True\n " assert (i in self.index_set()) if (i == 1): r = self.parent()._rootoperators[self.value][1] else: r = self.parent()._rootoperators[self.value][3] return (self.parent()(r) if (r is not None) else None)
class DecreasingHeckeFactorization(Element, metaclass=InheritComparisonClasscallMetaclass): '\n Class of decreasing factorizations in the 0-Hecke monoid.\n\n INPUT:\n\n - ``t`` -- decreasing factorization inputted as list of lists\n\n - ``max_value`` -- maximal value of entries\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[3, 2], [], [2, 1]]\n sage: h = DecreasingHeckeFactorization(t, 3); h\n (3, 2)()(2, 1)\n sage: h.excess\n 1\n sage: h.factors\n 3\n sage: h.max_value\n 3\n sage: h.value\n ((3, 2), (), (2, 1))\n\n sage: u = [[3, 2, 1], [3], [2, 1]]\n sage: h = DecreasingHeckeFactorization(u); h\n (3, 2, 1)(3)(2, 1)\n sage: h.weight()\n (2, 1, 3)\n sage: h.parent()\n Decreasing Hecke factorizations with 3 factors associated to [2, 1, 3, 2, 1] with excess 1\n ' @staticmethod def __classcall_private__(self, t, max_value=None, parent=None): '\n Assign the correct parent for ``t`` and call ``t`` as an element of that parent\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h1 = DecreasingHeckeFactorization([[3, 1], [], [3, 2]])\n sage: h1.parent()\n Fully commutative stable Grothendieck crystal of type A_2 associated to [1, 3, 2] with excess 1\n sage: h2 = DecreasingHeckeFactorization(h1)\n sage: h1 == h2\n True\n\n sage: h1 = DecreasingHeckeFactorization([[3, 1], [2, 1], [2, 1]])\n sage: F = h1.parent(); F\n Decreasing Hecke factorizations with 3 factors associated to [1, 3, 2, 1] with excess 2\n sage: h2 = F(h1)\n sage: h1 == h2\n True\n\n TESTS::\n\n sage: DecreasingHeckeFactorization([[]])\n ()\n ' _check_decreasing_hecke_factorization(t) if isinstance(t, DecreasingHeckeFactorization): u = t.value if (parent is None): parent = t.parent() else: u = t if (parent is None): if (max_value is None): letters = [x for factor in t for x in factor] max_value = (max(letters) if letters else 1) from sage.monoids.hecke_monoid import HeckeMonoid S = SymmetricGroup((max_value + 1)) H = HeckeMonoid(S) word = H.from_reduced_word((x for factor in t for x in factor)).reduced_word() factors = len(t) excess = (sum((len(l) for l in t)) - len(word)) p = permutation.from_reduced_word(word) if p.has_pattern([3, 2, 1]): word = S.from_reduced_word(word) parent = DecreasingHeckeFactorizations(word, factors, excess) else: word = S.from_reduced_word(word) parent = FullyCommutativeStableGrothendieckCrystal(word, factors, excess) return parent.element_class(parent, u) def __init__(self, parent, t): '\n Initialize a decreasing factorization for ``self`` given the relevant data.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[2, 1], [2], [], [1]]\n sage: h1 = DecreasingHeckeFactorization(t); h1\n (2, 1)(2)()(1)\n sage: h1.excess\n 1\n sage: h2 = DecreasingHeckeFactorization(t, 2)\n sage: h2.value\n ((2, 1), (2,), (), (1,))\n sage: h1 == h2\n True\n\n sage: t = [[2, 1], [2], [], [3, 1]]\n sage: h = DecreasingHeckeFactorization(t, 5)\n sage: h.max_value\n 5\n sage: h.factors\n 4\n sage: h.w\n (1, 2, 1, 3)\n\n TESTS::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t1 = [[], [3, 1], [], [2, 1], [1]]\n sage: t2 = [[], [3, 1], [], [2, 1], [2]]\n sage: h1 = DecreasingHeckeFactorization(t1, 3)\n sage: h2 = DecreasingHeckeFactorization(t2, 3)\n sage: h3 = DecreasingHeckeFactorization(t1)\n sage: h1 == h2, h1 == h3\n (False, True)\n sage: h1 != h2, h1 != h3\n (True, False)\n ' Element.__init__(self, parent) self.factors = parent.factors self.max_value = parent.max_value self.w = parent.w self.excess = parent.excess self.value = tuple((tuple(factors) for factors in t)) def _repr_(self): '\n Return the representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[], [2, 1], [2], [], [2]]\n sage: h = DecreasingHeckeFactorization(t); h\n ()(2, 1)(2)()(2)\n ' return ''.join(((('(' + repr(list(factor))[1:(- 1)]) + ')') for factor in self.value)) def __hash__(self): '\n Return hash of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[], [2, 1], [2], [], [2]]\n sage: h1 = DecreasingHeckeFactorization(t)\n sage: h2 = DecreasingHeckeFactorization(t, 3)\n sage: h3 = DecreasingHeckeFactorization(t, 2)\n sage: hash(h1) == hash(h2)\n False\n sage: hash(h1) == hash(h3)\n True\n ' return hash((self.max_value, self.value)) _richcmp_ = richcmp_by_eq_and_lt('__eq__', '__lt__') def __eq__(self, other): '\n Return True if ``self`` equals ``other`` and False otherwise.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[], [2, 1], [2], [], [2]]\n sage: h1 = DecreasingHeckeFactorization(t)\n sage: h2 = DecreasingHeckeFactorization(t, 3)\n sage: h1 == h2\n True\n ' return (isinstance(self, type(other)) and (self.value == other.value)) def __lt__(self, other): '\n Return True if ``self`` comes before ``other`` and False otherwise.\n\n We say that `h_1` comes before `h_2` if either weight of `h_1 <` weight of `h_2`\n lexicographically, or if both weights of `h_1` and `h_2` are equal,\n but `h_1 < h_2` lexicographically.\n This ordering is mainly used for sorting or comparison.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t1 = [[], [2, 1], [], [2, 1], [1]]\n sage: t2 = [[], [2, 1], [], [2, 1], [2]]\n sage: t3 = [[], [2, 1], [2], [1], [1]]\n sage: h1 = DecreasingHeckeFactorization(t1)\n sage: h2 = DecreasingHeckeFactorization(t2)\n sage: h3 = DecreasingHeckeFactorization(t3)\n sage: h1 < h2\n True\n sage: h1 < h3\n False\n ' return ((self.weight(), self.value) < (other.weight(), other.value)) def _latex_(self): '\n Return LaTeX code for ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[2], [2, 1], [], [4, 3, 1]]\n sage: h = DecreasingHeckeFactorization(t, 6)\n sage: latex(h)\n \\left(2\\right)\\left(2, 1\\right)\\left(\\;\\right)\\left(4, 3, 1\\right)\n ' s = '' for factor in self.value: if factor: s += (('\\left(' + repr(list(factor))[1:(- 1)]) + '\\right)') else: s += '\\left(\\;\\right)' return s def weight(self): '\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[2], [2, 1], [], [4, 3, 1]]\n sage: h = DecreasingHeckeFactorization(t, 6)\n sage: h.weight()\n (3, 0, 2, 1)\n ' return tuple([len(l) for l in reversed(self.value)]) def to_word(self): '\n Return the word associated to ``self`` in the 0-Hecke monoid.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[2], [], [2, 1], [4, 3, 1]]\n sage: h = DecreasingHeckeFactorization(t)\n sage: h.to_word()\n [2, 2, 1, 4, 3, 1]\n ' return [j for factors in self.value for j in factors] def to_increasing_hecke_biword(self): '\n Return the associated increasing Hecke biword of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: t = [[2], [], [2, 1],[4, 3, 1]]\n sage: h = DecreasingHeckeFactorization(t, 4)\n sage: h.to_increasing_hecke_biword()\n [[1, 1, 1, 2, 2, 4], [1, 3, 4, 1, 2, 2]]\n ' L = [[], []] for j in range(len(self.value)): L[1] += list(self.value[((- j) - 1)][::(- 1)]) L[0] += ([(j + 1)] * len(self.value[((- j) - 1)])) return L
class DecreasingHeckeFactorizations(UniqueRepresentation, Parent): '\n Set of decreasing factorizations in the 0-Hecke monoid.\n\n INPUT:\n\n - ``w`` -- an element in the symmetric group\n\n - ``factors`` -- the number of factors in the factorization\n\n - ``excess`` -- the total number of letters in the factorization minus the length of a reduced word for ``w``\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2, 1])\n sage: F = DecreasingHeckeFactorizations(w, 3, 3); F\n Decreasing Hecke factorizations with 3 factors associated to [1, 3, 2, 1] with excess 3\n sage: F.list()\n [(3, 1)(3, 1)(3, 2, 1), (3, 1)(3, 2, 1)(2, 1), (3, 2, 1)(2, 1)(2, 1)]\n ' @staticmethod def __classcall_private__(cls, w, factors, excess): '\n Classcall to mend the input.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 2 ,1])\n sage: F = DecreasingHeckeFactorizations(w, 4, 1); F\n Decreasing Hecke factorizations with 4 factors associated to [1, 2, 1] with excess 1\n\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: H = HeckeMonoid(SymmetricGroup(3+1))\n sage: w = H.from_reduced_word([1, 2 ,1])\n sage: G = DecreasingHeckeFactorizations(w, 4, 1); G\n Decreasing Hecke factorizations with 4 factors associated to [1, 2, 1] with excess 1\n sage: F is G\n True\n ' from sage.monoids.hecke_monoid import HeckeMonoid if isinstance(w.parent(), SymmetricGroup): H = HeckeMonoid(w.parent()) w = H.from_reduced_word(w.reduced_word()) if ((not w.reduced_word()) and (excess != 0)): raise ValueError('excess must be 0 for the empty word') return super().__classcall__(cls, w, factors, excess) def __init__(self, w, factors, excess): '\n Initialize a set for ``self`` given reduced word ``w`` in the symmetric group,\n number of factors ``factors`` and``excess`` extra letters.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([2, 1, 3, 2, 1])\n sage: F = DecreasingHeckeFactorizations(w, 4, 2)\n sage: F.w\n (2, 1, 3, 2, 1)\n sage: F.factors\n 4\n sage: F.excess\n 2\n sage: F.H\n 0-Hecke monoid of the Symmetric group of order 4! as a permutation group\n\n TESTS::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(2+1)\n sage: w = S.from_reduced_word([1, 2, 1])\n sage: F = DecreasingHeckeFactorizations(w, 3, 1)\n sage: TestSuite(F).run()\n ' Parent.__init__(self, category=FiniteEnumeratedSets()) self.w = tuple(w.reduced_word()) self.factors = factors self.H = w.parent() self.max_value = len(self.H.gens()) self.excess = excess def _repr_(self): '\n Return a representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([2, 1, 3, 2])\n sage: DecreasingHeckeFactorizations(w, 3, 1)\n Decreasing Hecke factorizations with 3 factors associated to [2, 1, 3, 2] with excess 1\n ' return 'Decreasing Hecke factorizations with {} factors associated to {} with excess {}'.format(self.factors, list(self.w), self.excess) def list(self): '\n Return list of all elements of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorizations\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2, 1])\n sage: F = DecreasingHeckeFactorizations(w, 3, 3)\n sage: F.list()\n [(3, 1)(3, 1)(3, 2, 1), (3, 1)(3, 2, 1)(2, 1), (3, 2, 1)(2, 1)(2, 1)]\n ' return _generate_decreasing_hecke_factorizations(self.w, self.factors, self.excess, parent=self) _an_element_ = EnumeratedSets.ParentMethods._an_element_ Element = DecreasingHeckeFactorization
class FullyCommutativeStableGrothendieckCrystal(UniqueRepresentation, Parent): '\n The crystal on fully commutative decreasing factorizations in the 0-Hecke\n monoid, as introduced by [MPPS2020]_.\n\n INPUT:\n\n - ``w`` -- an element in the symmetric group or a (skew) shape\n\n - ``factors`` -- the number of factors in the factorization\n\n - ``excess`` -- the total number of letters in the factorization minus the length of a reduced word for ``w``\n\n - ``shape`` -- (default: ``False``) indicator for input ``w``, True if ``w`` is entered as a (skew) shape and False otherwise.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2); B\n Fully commutative stable Grothendieck crystal of type A_2 associated to [1, 3, 2] with excess 2\n sage: B.list()\n [(1)(3, 1)(3, 2),\n (3, 1)(1)(3, 2),\n (3, 1)(3, 1)(2),\n (3)(3, 1)(3, 2),\n (3, 1)(3)(3, 2),\n (3, 1)(3, 2)(2)]\n\n We can also access the crystal by specifying a skew shape::\n\n sage: crystals.FullyCommutativeStableGrothendieck([[2, 2], [1]], 4, 1, shape=True)\n Fully commutative stable Grothendieck crystal of type A_3 associated to [2, 1, 3] with excess 1\n\n We can compute the highest weight elements::\n\n sage: hw = [w for w in B if w.is_highest_weight()]\n sage: hw\n [(1)(3, 1)(3, 2), (3)(3, 1)(3, 2)]\n sage: hw[0].weight()\n (2, 2, 1)\n\n The crystal operators themselves move elements between adjacent factors::\n\n sage: b = hw[0]; b\n (1)(3, 1)(3, 2)\n sage: b.f(2)\n (3, 1)(1)(3, 2)\n ' @staticmethod def __classcall_private__(cls, w, factors, excess, shape=False): '\n Classcall to mend the input.\n\n EXAMPLES::\n\n sage: A = crystals.FullyCommutativeStableGrothendieck([[3, 3], [2, 1]], 4, 1, shape=True); A\n Fully commutative stable Grothendieck crystal of type A_3 associated to [3, 2, 4] with excess 1\n sage: B = crystals.FullyCommutativeStableGrothendieck(SkewPartition([[3, 3], [2, 1]]), 4, 1, shape=True)\n sage: A is B\n True\n\n sage: C = crystals.FullyCommutativeStableGrothendieck((2, 1), 3, 2, shape=True); C\n Fully commutative stable Grothendieck crystal of type A_2 associated to [1, 3, 2] with excess 2\n sage: D = crystals.FullyCommutativeStableGrothendieck(Partition([2, 1]), 3, 2, shape=True)\n sage: C is D\n True\n ' from sage.monoids.hecke_monoid import HeckeMonoid if shape: from sage.combinat.partition import _Partitions from sage.combinat.skew_partition import SkewPartition cond1 = (isinstance(w, (tuple, list)) and (len(w) == 2) and (w[0] in _Partitions) and (w[1] in _Partitions)) cond2 = isinstance(w, SkewPartition) if (cond1 or cond2): sh = SkewPartition([w[0], w[1]]) elif (w in _Partitions): sh = SkewPartition([w, []]) else: raise ValueError('w needs to be a (skew) partition') word = _to_reduced_word(sh) max_value = (max(word) if word else 1) H = HeckeMonoid(SymmetricGroup((max_value + 1))) w = H.from_reduced_word(word) elif isinstance(w.parent(), SymmetricGroup): H = HeckeMonoid(w.parent()) w = H.from_reduced_word(w.reduced_word()) if ((not w.reduced_word()) and (excess != 0)): raise ValueError('excess must be 0 for the empty word') return super().__classcall__(cls, w, factors, excess) def __init__(self, w, factors, excess): '\n Initialize a crystal for ``self`` given reduced word ``w`` in the symmetric group,\n number of factors ``factors`` and``excess`` extra letters.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2)\n sage: B.w\n (1, 3, 2)\n sage: B.factors\n 3\n sage: B.excess\n 2\n sage: B.H\n 0-Hecke monoid of the Symmetric group of order 4! as a permutation group\n\n The reduced word ``w`` should be fully commutative, that is, its\n associated permutation should avoid the pattern 321::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 2, 1])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 4, 2)\n Traceback (most recent call last):\n ...\n ValueError: w should be fully commutative\n\n TESTS::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([2, 3, 1])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 4, 2)\n sage: TestSuite(B).run()\n ' word = w.reduced_word() p = permutation.from_reduced_word(word) if p.has_pattern([3, 2, 1]): raise ValueError('w should be fully commutative') Parent.__init__(self, category=ClassicalCrystals()) self.w = tuple(word) self.factors = factors self.H = w.parent() self.max_value = len(self.H.gens()) self.excess = excess self._cartan_type = CartanType(['A', (self.factors - 1)]) @lazy_attribute def module_generators(self): '\n Return generators for ``self`` as a crystal.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2)\n sage: B.module_generators\n ((1)(3, 1)(3, 2), (3)(3, 1)(3, 2))\n sage: C = crystals.FullyCommutativeStableGrothendieck(w, 4, 2)\n sage: C.module_generators\n (()(1)(3, 1)(3, 2),\n ()(3)(3, 1)(3, 2),\n (1)(1)(1)(3, 2),\n (1)(1)(3)(3, 2),\n (1)(3)(3)(3, 2))\n ' return tuple((self(x).to_highest_weight()[0] for x in _lowest_weights(self.w, self.factors, self.excess, parent=self))) def _repr_(self): '\n Return a representation of ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([2, 1, 3, 2])\n sage: crystals.FullyCommutativeStableGrothendieck(w, 3, 1)\n Fully commutative stable Grothendieck crystal of type A_2 associated to [2, 1, 3, 2] with excess 1\n ' return 'Fully commutative stable Grothendieck crystal of type A_{} associated to {} with excess {}'.format((self.factors - 1), list(self.w), self.excess) class Element(DecreasingHeckeFactorization): def __init__(self, parent, t): '\n Create an instance ``self`` of element ``t``.\n\n This method takes into account the constraints on the word,\n the number of factors, and excess statistic associated to the parent class.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2)\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h = DecreasingHeckeFactorization([[3, 1], [3], [3, 2]], 4)\n sage: u = B(h); u.value\n ((3, 1), (3,), (3, 2))\n sage: v = B([[3, 1], [3], [3, 2]]); v.value\n ((3, 1), (3,), (3, 2))\n ' u = t if isinstance(t, DecreasingHeckeFactorization): u = t.value _check_decreasing_hecke_factorization(t) _check_containment(t, parent) DecreasingHeckeFactorization.__init__(self, parent, u) def e(self, i): '\n Return the action of `e_i` on ``self`` using the rules described in [MPPS2020]_.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(4+1)\n sage: w = S.from_reduced_word([2, 1, 4, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 4, 3)\n sage: h = B([[4, 2], [4, 2, 1], [3, 2], [2]]); h\n (4, 2)(4, 2, 1)(3, 2)(2)\n sage: h.e(1)\n (4, 2)(4, 2, 1)(3)(3, 2)\n sage: h.e(2)\n (4, 2)(2, 1)(4, 3, 2)(2)\n sage: h.e(3)\n ' P = self.parent() m = P.factors L = list(self.value[((m - i) - 1)]) R = list(self.value[(m - i)]) b = self.bracketing(i) if (not b[0]): return None y = b[0][(- 1)] if (((y - 1) in L) and ((y - 1) in R)): L.remove((y - 1)) else: L.remove(y) R.append(y) L.sort(reverse=True) R.sort(reverse=True) s = ((([self.value[j] for j in range(((m - i) - 1))] + [L]) + [R]) + [self.value[j] for j in range(((m - i) + 1), m)]) return P.element_class(P, s) def f(self, i): '\n Return the action of `f_i` on ``self`` using the rules described in [MPPS2020]_.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(4+1)\n sage: w = S.from_reduced_word([3, 2, 1, 4, 3])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 4, 3)\n sage: h = B([[3, 2], [2, 1], [4, 3], [3, 1]]); h\n (3, 2)(2, 1)(4, 3)(3, 1)\n sage: h.f(1)\n (3, 2)(2, 1)(4, 3, 1)(3)\n sage: h.f(2)\n sage: h.f(3)\n (3, 2, 1)(1)(4, 3)(3, 1)\n ' P = self.parent() m = P.factors L = list(self.value[((m - i) - 1)]) R = list(self.value[(m - i)]) b = self.bracketing(i) if (not b[1]): return None x = b[1][0] if (((x + 1) in L) and ((x + 1) in R)): R.remove((x + 1)) else: R.remove(x) L.append(x) L.sort(reverse=True) R.sort(reverse=True) s = ((([self.value[j] for j in range(((m - i) - 1))] + [L]) + [R]) + [self.value[j] for j in range(((m - i) + 1), m)]) return P.element_class(P, s) def bracketing(self, i): '\n Remove all bracketed letters between `i`-th and `(i+1)`-th entry.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(4+1)\n sage: w = S.from_reduced_word([3, 2, 1, 4, 3])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2)\n sage: h = B([[3], [4, 2, 1], [4, 3, 1]])\n sage: h.bracketing(1)\n [[], []]\n sage: h.bracketing(2)\n [[], [2, 1]]\n ' P = self.parent() m = P.factors L = list(self.value[((m - i) - 1)]) R = list(self.value[(m - i)]) right_n = [j for j in R] left_n = [j for j in L] left_unbracketed = [] while left_n: m = max(left_n) left_n.remove(m) l = [j for j in right_n if (j >= m)] if l: right_n.remove(min(l)) else: left_unbracketed += [m] return [[j for j in left_unbracketed], [j for j in right_n]]
def _check_decreasing_hecke_factorization(t): "\n Check if ``t`` is a suitable data type for a decreasing factorization in a 0-Hecke monoid.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import _check_decreasing_hecke_factorization\n sage: _check_decreasing_hecke_factorization([[3, 2], [2, 1], [4]])\n sage: _check_decreasing_hecke_factorization([[3, 2, 2], [2, 1], [4]])\n Traceback (most recent call last):\n ...\n ValueError: each nonempty factor should be a strictly decreasing sequence\n sage: _check_decreasing_hecke_factorization([[3, 'a'], [2, 1], [4]])\n Traceback (most recent call last):\n ...\n ValueError: each nonempty factor should contain integers\n sage: _check_decreasing_hecke_factorization([[3, 2], [2, 1], 4])\n Traceback (most recent call last):\n ...\n ValueError: each factor in t should be a list or tuple\n " if (not isinstance(t, DecreasingHeckeFactorization)): if (not isinstance(t, (tuple, list))): raise ValueError('t should be a list or tuple') for factor in t: if (not isinstance(factor, (tuple, list))): raise ValueError('each factor in t should be a list or tuple') if (not all((isinstance(x, (int, Integer)) for x in factor))): raise ValueError('each nonempty factor should contain integers') for i in range((len(factor) - 1)): if (factor[i] <= factor[(i + 1)]): raise ValueError('each nonempty factor should be a strictly decreasing sequence')
def _check_containment(t, parent): '\n Check if ``t`` is an element of ``parent``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3+1)\n sage: w = S.from_reduced_word([1, 3, 2])\n sage: B = crystals.FullyCommutativeStableGrothendieck(w, 3, 2)\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization, _check_containment\n sage: h1 = DecreasingHeckeFactorization([[3, 1], [3], [3, 2]], 4)\n sage: _check_containment(h1, B)\n\n sage: h2 = DecreasingHeckeFactorization([[3, 1], [3], [], [3, 2]])\n sage: _check_containment(h2, B)\n Traceback (most recent call last):\n ...\n ValueError: number of factors do not match\n\n sage: h3 = [[3, 1], [2], [3, 2]]\n sage: _check_containment(h3, B)\n Traceback (most recent call last):\n ...\n ValueError: self and parent must be specified based on equivalent words\n\n sage: h4 = DecreasingHeckeFactorization([[3, 1], [3, 1], [3, 2]], 3)\n sage: _check_containment(h4, B)\n Traceback (most recent call last):\n ...\n ValueError: number of excess letters do not match\n ' if isinstance(t, DecreasingHeckeFactorization): factors = t.factors w = t.w excess = t.excess else: factors = len(t) max_value = parent.max_value from sage.monoids.hecke_monoid import HeckeMonoid H = HeckeMonoid(SymmetricGroup((max_value + 1))) w = tuple(H.from_reduced_word((x for factor in t for x in factor)).reduced_word()) excess = (sum((len(l) for l in t)) - len(w)) if (factors != parent.factors): raise ValueError('number of factors do not match') if (w != parent.w): raise ValueError('self and parent must be specified based on equivalent words') if (excess != parent.excess): raise ValueError('number of excess letters do not match')
def _generate_decreasing_hecke_factorizations(w, factors, ex, weight=None, parent=None): '\n Generate all decreasing factorizations of word ``w`` in a 0-Hecke monoid\n with fixed excess and number of factors.\n\n INPUT:\n\n - ``w`` -- a reduced word, expressed as an iterable\n\n - ``factors`` -- number of factors for each decreasing factorization\n\n - ``ex`` -- number of extra letters in each decreasing factorizations\n\n - ``weight`` -- (default: None) if None, returns all possible decreasing\n factorizations, otherwise return all those with the\n specified weight\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import _generate_decreasing_hecke_factorizations\n sage: _generate_decreasing_hecke_factorizations([1, 2, 1], 3, 1)\n [()(2, 1)(2, 1),\n (2)(1)(2, 1),\n (1)(2)(2, 1),\n (1)(1)(2, 1),\n (2, 1)()(2, 1),\n (2)(2, 1)(2),\n (1)(2, 1)(2),\n (1)(2, 1)(1),\n (2, 1)(2)(2),\n (2, 1)(2)(1),\n (2, 1)(1)(2),\n (2, 1)(2, 1)()]\n\n sage: _generate_decreasing_hecke_factorizations([1, 2, 1], 3, 1, weight=[1, 1, 2])\n [(2, 1)(2)(2), (2, 1)(2)(1), (2, 1)(1)(2)]\n ' if (parent is None): max_value = (max(w) if w else 1) S = SymmetricGroup((max_value + 1)) v = S.from_reduced_word(w) parent = DecreasingHeckeFactorizations(v, factors, ex) _canonical_word = (lambda w, ex: (([list(w)[0]] * ex) + list(w))) wt = (lambda t: [len(factor) for factor in reversed(t)]) L = _list_equivalent_words(_canonical_word(w, ex)) Factors = [] for word in L: F = _list_all_decreasing_runs(word, factors) for f in F: t = [[word[j] for j in range(len(word)) if (f[j] == i)] for i in range(factors, 0, (- 1))] if ((weight is None) or (weight == wt(t))): Factors.append(parent.element_class(parent, t)) return sorted(Factors, reverse=True)
def _list_all_decreasing_runs(word, m): '\n List all possible decreasing runs into ``m`` factors for ``word`` in a\n 0-Hecke monoid.\n\n EXAMPLES::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import _list_all_decreasing_runs\n sage: _list_all_decreasing_runs([2, 1, 2, 1], 3)\n [[2, 2, 1, 1], [3, 2, 1, 1], [3, 3, 1, 1], [3, 3, 2, 1], [3, 3, 2, 2]]\n ' from sage.combinat.integer_vector import IntegerVectors J = _jumps(word) jump_vector = ([1] + [int((j in J)) for j in range(1, len(word))]) I = sorted(IntegerVectors(((m - 1) - len(J)), (len(word) + 1)), reverse=True) P = [[(elt[i] + jump_vector[i]) for i in range(len(word))] for elt in I] V = [[((m + 1) - sum(elt[:(i + 1)])) for i in range(len(elt))] for elt in P] return V