code
stringlengths
17
6.64M
def number_of_partitions_length(n, k, algorithm='hybrid'): "\n Return the number of partitions of `n` with length `k`.\n\n This is a wrapper for GAP's ``NrPartitions`` function.\n\n EXAMPLES::\n\n sage: # needs sage.libs.gap\n sage: from sage.combinat.partition import number_of_partitions_length\n sage: number_of_partitions_length(5, 2)\n 2\n sage: number_of_partitions_length(10, 2)\n 5\n sage: number_of_partitions_length(10, 4)\n 9\n sage: number_of_partitions_length(10, 0)\n 0\n sage: number_of_partitions_length(10, 1)\n 1\n sage: number_of_partitions_length(0, 0)\n 1\n sage: number_of_partitions_length(0, 1)\n 0\n " if (algorithm == 'hybrid'): if (n < k): return ZZ.zero() if ((n == k) and (n >= 0)): return ZZ.one() if (n <= 0): return ZZ.zero() if (k <= 0): return ZZ.zero() if (k == 1): return ZZ.one() if (k == 2): return (n // 2) if (n <= (k * 2)): return number_of_partitions((n - k)) from sage.libs.gap.libgap import libgap return ZZ(libgap.NrPartitions(ZZ(n), ZZ(k)))
def _int_or_half_int(k): '\n Check if ``k`` is an integer or half integer.\n\n OUTPUT:\n\n If ``k`` is not in `1/2 \\ZZ`, then this raises a ``ValueError``.\n Otherwise, we return the pair:\n\n - boolean; ``True`` if ``k`` is an integer and ``False`` if a half integer\n - integer; the floor of ``k``\n\n TESTS::\n\n sage: from sage.combinat.partition_algebra import _int_or_half_int\n sage: _int_or_half_int(2)\n (True, 2)\n sage: _int_or_half_int(3/2)\n (False, 1)\n sage: _int_or_half_int(1.5)\n (False, 1)\n sage: _int_or_half_int(2.)\n (True, 2)\n sage: _int_or_half_int(2.1)\n Traceback (most recent call last):\n ...\n ValueError: k must be an integer or an integer + 1/2\n ' if (k in ZZ): return (True, ZZ(k)) try: k = QQ(k) if (k.denominator() == 2): return (False, k.floor()) except (ValueError, TypeError): pass raise ValueError('k must be an integer or an integer + 1/2')
class SetPartitionsXkElement(SetPartition): '\n An element for the classes of ``SetPartitionXk`` where ``X`` is some\n letter.\n ' def check(self): '\n Check to make sure this is a set partition.\n\n EXAMPLES::\n\n sage: A2p5 = SetPartitionsAk(2.5)\n sage: x = A2p5.first(); x\n {{-3, -2, -1, 1, 2, 3}}\n sage: x.check()\n sage: y = A2p5.next(x); y\n {{-3, 3}, {-2, -1, 1, 2}}\n sage: y.check()\n ' for s in self: assert isinstance(s, (set, frozenset, Set_generic))
def SetPartitionsAk(k): '\n Return the combinatorial class of set partitions of type `A_k`.\n\n EXAMPLES::\n\n sage: A3 = SetPartitionsAk(3); A3\n Set partitions of {1, ..., 3, -1, ..., -3}\n\n sage: A3.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: A3.last() #random\n {{-1}, {-2}, {3}, {1}, {-3}, {2}}\n sage: A3.random_element() #random\n {{1, 3, -3, -1}, {2, -2}}\n\n sage: A3.cardinality()\n 203\n\n sage: A2p5 = SetPartitionsAk(2.5); A2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block\n sage: A2p5.cardinality()\n 52\n\n sage: A2p5.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: A2p5.last() #random\n {{-1}, {-2}, {2}, {3, -3}, {1}}\n sage: A2p5.random_element() #random\n {{-1}, {-2}, {3, -3}, {1, 2}}\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsAkhalf_k(k) return SetPartitionsAk_k(k)
class SetPartitionsAk_k(SetPartitions_set): def __init__(self, k): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3); A3\n Set partitions of {1, ..., 3, -1, ..., -3}\n sage: A3 == loads(dumps(A3))\n True\n ' self.k = k set_k = frozenset((list(range(1, (k + 1))) + [(- x) for x in range(1, (k + 1))])) SetPartitions_set.__init__(self, set_k) Element = SetPartitionsXkElement def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsAk(3)\n Set partitions of {1, ..., 3, -1, ..., -3}\n ' return ('Set partitions of {1, ..., %s, -1, ..., -%s}' % (self.k, self.k))
class SetPartitionsAkhalf_k(SetPartitions_set): def __init__(self, k): '\n TESTS::\n\n sage: A2p5 = SetPartitionsAk(2.5); A2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block\n sage: A2p5 == loads(dumps(A2p5))\n True\n ' self.k = k set_k = frozenset((list(range(1, (k + 2))) + [(- x) for x in range(1, (k + 1))])) SetPartitions_set.__init__(self, set_k) Element = SetPartitionsXkElement def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsAk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block\n ' s = (self.k + 1) return ('Set partitions of {1, ..., %s, -1, ..., -%s} with %s and -%s in the same block' % (s, s, s, s)) def __contains__(self, x): '\n TESTS::\n\n sage: A2p5 = SetPartitionsAk(2.5)\n sage: all(sp in A2p5 for sp in A2p5)\n True\n sage: A3 = SetPartitionsAk(3)\n sage: len([x for x in A3 if x in A2p5])\n 52\n sage: A2p5.cardinality()\n 52\n ' if (x not in SetPartitionsAk_k((self.k + 1))): return False for part in x: if (((self.k + 1) in part) and (((- self.k) - 1) not in part)): return False return True def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsAk(1.5).list() #random\n [{{1, 2, -2, -1}},\n {{2, -2, -1}, {1}},\n {{2, -2}, {1, -1}},\n {{-1}, {1, 2, -2}},\n {{-1}, {2, -2}, {1}}]\n\n ::\n\n sage: ks = [ 1.5, 2.5, 3.5 ]\n sage: aks = map(SetPartitionsAk, ks)\n sage: all(ak.cardinality() == len(ak.list()) for ak in aks)\n True\n ' kp = frozenset([((- self.k) - 1)]) for sp in SetPartitions_set.__iter__(self): res = [] for part in sp: if ((self.k + 1) in part): res.append(part.union(kp)) else: res.append(part) (yield self.element_class(self, res))
def SetPartitionsSk(k): '\n Return the combinatorial class of set partitions of type `S_k`.\n\n There is a bijection between these set partitions and the\n permutations of `1, \\ldots, k`.\n\n EXAMPLES::\n\n sage: S3 = SetPartitionsSk(3); S3\n Set partitions of {1, ..., 3, -1, ..., -3} with propagating number 3\n sage: S3.cardinality()\n 6\n\n sage: S3.list() #random\n [{{2, -2}, {3, -3}, {1, -1}},\n {{1, -1}, {2, -3}, {3, -2}},\n {{2, -1}, {3, -3}, {1, -2}},\n {{1, -2}, {2, -3}, {3, -1}},\n {{1, -3}, {2, -1}, {3, -2}},\n {{1, -3}, {2, -2}, {3, -1}}]\n sage: S3.first() #random\n {{2, -2}, {3, -3}, {1, -1}}\n sage: S3.last() #random\n {{1, -3}, {2, -2}, {3, -1}}\n sage: S3.random_element() #random\n {{1, -3}, {2, -1}, {3, -2}}\n\n sage: S3p5 = SetPartitionsSk(3.5); S3p5\n Set partitions of {1, ..., 4, -1, ..., -4} with 4 and -4 in the same block and propagating number 4\n sage: S3p5.cardinality()\n 6\n\n sage: S3p5.list() #random\n [{{2, -2}, {3, -3}, {1, -1}, {4, -4}},\n {{2, -3}, {1, -1}, {4, -4}, {3, -2}},\n {{2, -1}, {3, -3}, {1, -2}, {4, -4}},\n {{2, -3}, {1, -2}, {4, -4}, {3, -1}},\n {{1, -3}, {2, -1}, {4, -4}, {3, -2}},\n {{1, -3}, {2, -2}, {4, -4}, {3, -1}}]\n sage: S3p5.first() #random\n {{2, -2}, {3, -3}, {1, -1}, {4, -4}}\n sage: S3p5.last() #random\n {{1, -3}, {2, -2}, {4, -4}, {3, -1}}\n sage: S3p5.random_element() #random\n {{1, -3}, {2, -2}, {4, -4}, {3, -1}}\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsSkhalf_k(k) return SetPartitionsSk_k(k)
class SetPartitionsSk_k(SetPartitionsAk_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsSk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with propagating number 3\n ' return (SetPartitionsAk_k._repr_(self) + (' with propagating number %s' % self.k)) def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: S3 = SetPartitionsSk(3)\n sage: all(sp in S3 for sp in S3)\n True\n sage: S3.cardinality()\n 6\n sage: len([x for x in A3 if x in S3])\n 6\n ' if (not SetPartitionsAk_k.__contains__(self, x)): return False if (propagating_number(x) != self.k): return False return True def cardinality(self): '\n Return k!.\n\n TESTS::\n\n sage: SetPartitionsSk(2).cardinality()\n 2\n sage: SetPartitionsSk(3).cardinality()\n 6\n sage: SetPartitionsSk(4).cardinality()\n 24\n sage: SetPartitionsSk(5).cardinality()\n 120\n ' return factorial(self.k) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsSk(3).list() #random\n [{{2, -2}, {3, -3}, {1, -1}},\n {{1, -1}, {2, -3}, {3, -2}},\n {{2, -1}, {3, -3}, {1, -2}},\n {{1, -2}, {2, -3}, {3, -1}},\n {{1, -3}, {2, -1}, {3, -2}},\n {{1, -3}, {2, -2}, {3, -1}}]\n sage: ks = list(range(1, 6))\n sage: sks = map(SetPartitionsSk, ks)\n sage: all(sk.cardinality() == len(sk.list()) for sk in sks)\n True\n ' for p in Permutations(self.k): res = [] for i in range(self.k): res.append(Set([(i + 1), (- p[i])])) (yield self.element_class(self, res))
class SetPartitionsSkhalf_k(SetPartitionsAkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: S2p5 = SetPartitionsSk(2.5)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in S2p5 for sp in S2p5)\n True\n sage: len([x for x in A3 if x in S2p5])\n 2\n sage: S2p5.cardinality()\n 2\n ' if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False if (propagating_number(x) != (self.k + 1)): return False return True def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsSk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number 3\n ' s = (self.k + 1) return (SetPartitionsAkhalf_k._repr_(self) + (' and propagating number %s' % s)) def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsSk(2.5).cardinality()\n 2\n sage: SetPartitionsSk(3.5).cardinality()\n 6\n sage: SetPartitionsSk(4.5).cardinality()\n 24\n\n ::\n\n sage: ks = [2.5, 3.5, 4.5, 5.5]\n sage: sks = [SetPartitionsSk(k) for k in ks]\n sage: all(sk.cardinality() == len(sk.list()) for sk in sks)\n True\n ' return factorial(self.k) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsSk(3.5).list() #random indirect test\n [{{2, -2}, {3, -3}, {1, -1}, {4, -4}},\n {{2, -3}, {1, -1}, {4, -4}, {3, -2}},\n {{2, -1}, {3, -3}, {1, -2}, {4, -4}},\n {{2, -3}, {1, -2}, {4, -4}, {3, -1}},\n {{1, -3}, {2, -1}, {4, -4}, {3, -2}},\n {{1, -3}, {2, -2}, {4, -4}, {3, -1}}]\n ' for p in Permutations(self.k): res = [] for i in range(self.k): res.append(Set([(i + 1), (- p[i])])) res.append(Set([(self.k + 1), ((- self.k) - 1)])) (yield self.element_class(self, res))
def SetPartitionsIk(k): '\n Return the combinatorial class of set partitions of type `I_k`.\n\n These are set partitions with a propagating number of less than `k`.\n Note that the identity set partition `\\{\\{1, -1\\}, \\ldots, \\{k, -k\\}\\}`\n is not in `I_k`.\n\n EXAMPLES::\n\n sage: I3 = SetPartitionsIk(3); I3\n Set partitions of {1, ..., 3, -1, ..., -3} with propagating number < 3\n sage: I3.cardinality()\n 197\n\n sage: I3.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: I3.last() #random\n {{-1}, {-2}, {3}, {1}, {-3}, {2}}\n sage: I3.random_element() #random\n {{-1}, {-3, -2}, {2, 3}, {1}}\n\n sage: I2p5 = SetPartitionsIk(2.5); I2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number < 3\n sage: I2p5.cardinality()\n 50\n\n sage: I2p5.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: I2p5.last() #random\n {{-1}, {-2}, {2}, {3, -3}, {1}}\n sage: I2p5.random_element() #random\n {{-1}, {-2}, {1, 3, -3}, {2}}\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsIkhalf_k(k) return SetPartitionsIk_k(k)
class SetPartitionsIk_k(SetPartitionsAk_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsIk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with propagating number < 3\n ' return (SetPartitionsAk_k._repr_(self) + (' with propagating number < %s' % self.k)) def __contains__(self, x): '\n TESTS::\n\n sage: I3 = SetPartitionsIk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in I3 for sp in I3)\n True\n sage: len([x for x in A3 if x in I3])\n 197\n sage: I3.cardinality()\n 197\n ' if (not SetPartitionsAk_k.__contains__(self, x)): return False if (propagating_number(x) >= self.k): return False return True def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsIk(2).cardinality()\n 13\n ' return len(self.list()) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsIk(2).list() #random indirect test\n [{{1, 2, -1, -2}},\n {{2, -1, -2}, {1}},\n {{2}, {1, -1, -2}},\n {{-1}, {1, 2, -2}},\n {{-2}, {1, 2, -1}},\n {{1, 2}, {-1, -2}},\n {{2}, {-1, -2}, {1}},\n {{-1}, {2, -2}, {1}},\n {{-2}, {2, -1}, {1}},\n {{-1}, {2}, {1, -2}},\n {{-2}, {2}, {1, -1}},\n {{-1}, {-2}, {1, 2}},\n {{-1}, {-2}, {2}, {1}}]\n ' for sp in SetPartitionsAk_k.__iter__(self): if (propagating_number(sp) < self.k): (yield sp)
class SetPartitionsIkhalf_k(SetPartitionsAkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: I2p5 = SetPartitionsIk(2.5)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in I2p5 for sp in I2p5)\n True\n sage: len([x for x in A3 if x in I2p5])\n 50\n sage: I2p5.cardinality()\n 50\n ' if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False if (propagating_number(x) >= (self.k + 1)): return False return True def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsIk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and propagating number < 3\n ' return (SetPartitionsAkhalf_k._repr_(self) + (' and propagating number < %s' % (self.k + 1))) def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsIk(1.5).cardinality()\n 4\n sage: SetPartitionsIk(2.5).cardinality()\n 50\n sage: SetPartitionsIk(3.5).cardinality()\n 871\n ' return len(self.list()) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsIk(1.5).list() #random\n [{{1, 2, -2, -1}},\n {{2, -2, -1}, {1}},\n {{-1}, {1, 2, -2}},\n {{-1}, {2, -2}, {1}}]\n ' for sp in SetPartitionsAkhalf_k.__iter__(self): if (propagating_number(sp) < (self.k + 1)): (yield sp)
def SetPartitionsBk(k): '\n Return the combinatorial class of set partitions of type `B_k`.\n\n These are the set partitions where every block has size 2.\n\n EXAMPLES::\n\n sage: B3 = SetPartitionsBk(3); B3\n Set partitions of {1, ..., 3, -1, ..., -3} with block size 2\n\n sage: B3.first() #random\n {{2, -2}, {1, -3}, {3, -1}}\n sage: B3.last() #random\n {{1, 2}, {3, -2}, {-3, -1}}\n sage: B3.random_element() #random\n {{2, -1}, {1, -3}, {3, -2}}\n\n sage: B3.cardinality()\n 15\n\n sage: B2p5 = SetPartitionsBk(2.5); B2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2\n\n sage: B2p5.first() #random\n {{2, -1}, {3, -3}, {1, -2}}\n sage: B2p5.last() #random\n {{1, 2}, {3, -3}, {-1, -2}}\n sage: B2p5.random_element() #random\n {{2, -2}, {3, -3}, {1, -1}}\n\n sage: B2p5.cardinality()\n 3\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsBkhalf_k(k) return SetPartitionsBk_k(k)
class SetPartitionsBk_k(SetPartitionsAk_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsBk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2\n ' return (SetPartitionsAk_k._repr_(self) + ' with block size 2') def __contains__(self, x): '\n TESTS::\n\n sage: B3 = SetPartitionsBk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: len([x for x in A3 if x in B3])\n 15\n sage: B3.cardinality()\n 15\n ' if (not SetPartitionsAk_k.__contains__(self, x)): return False for part in x: if (len(part) != 2): return False return True def cardinality(self): '\n Return the number of set partitions in `B_k` where `k` is an integer.\n\n This is given by (2k)!! = (2k-1)\\*(2k-3)\\*...\\*5\\*3\\*1.\n\n EXAMPLES::\n\n sage: SetPartitionsBk(3).cardinality()\n 15\n sage: SetPartitionsBk(2).cardinality()\n 3\n sage: SetPartitionsBk(1).cardinality()\n 1\n sage: SetPartitionsBk(4).cardinality()\n 105\n sage: SetPartitionsBk(5).cardinality()\n 945\n ' c = 1 for i in range(1, (2 * self.k), 2): c *= i return c def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsBk(1).list()\n [{{-1, 1}}]\n\n ::\n\n sage: SetPartitionsBk(2).list() #random\n [{{2, -1}, {1, -2}}, {{2, -2}, {1, -1}}, {{1, 2}, {-1, -2}}]\n sage: SetPartitionsBk(3).list() #random\n [{{2, -2}, {1, -3}, {3, -1}},\n {{2, -1}, {1, -3}, {3, -2}},\n {{1, -3}, {2, 3}, {-1, -2}},\n {{3, -1}, {1, -2}, {2, -3}},\n {{3, -2}, {1, -1}, {2, -3}},\n {{1, 3}, {2, -3}, {-1, -2}},\n {{2, -1}, {3, -3}, {1, -2}},\n {{2, -2}, {3, -3}, {1, -1}},\n {{1, 2}, {3, -3}, {-1, -2}},\n {{-3, -2}, {2, 3}, {1, -1}},\n {{1, 3}, {-3, -2}, {2, -1}},\n {{1, 2}, {3, -1}, {-3, -2}},\n {{-3, -1}, {2, 3}, {1, -2}},\n {{1, 3}, {-3, -1}, {2, -2}},\n {{1, 2}, {3, -2}, {-3, -1}}]\n\n Check to make sure that the number of elements generated is the\n same as what is given by cardinality()\n\n ::\n\n sage: bks = [SetPartitionsBk(i) for i in range(1, 6)]\n sage: all(bk.cardinality() == len(bk.list()) for bk in bks)\n True\n ' for sp in SetPartitions(self._set, ([2] * (len(self._set) // 2))): (yield self.element_class(self, sp))
class SetPartitionsBkhalf_k(SetPartitionsAkhalf_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsBk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2\n ' return (SetPartitionsAkhalf_k._repr_(self) + ' and with block size 2') def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: B2p5 = SetPartitionsBk(2.5)\n sage: all(sp in B2p5 for sp in B2p5)\n True\n sage: len([x for x in A3 if x in B2p5])\n 3\n sage: B2p5.cardinality()\n 3\n ' if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False for part in x: if (len(part) != 2): return False return True def cardinality(self): '\n TESTS::\n\n sage: B3p5 = SetPartitionsBk(3.5)\n sage: B3p5.cardinality()\n 15\n ' return len(self.list()) def __iter__(self): '\n TESTS::\n\n sage: B3p5 = SetPartitionsBk(3.5)\n sage: B3p5.cardinality()\n 15\n\n ::\n\n sage: B3p5.list() #random\n [{{2, -2}, {1, -3}, {4, -4}, {3, -1}},\n {{2, -1}, {1, -3}, {4, -4}, {3, -2}},\n {{1, -3}, {2, 3}, {4, -4}, {-1, -2}},\n {{2, -3}, {1, -2}, {4, -4}, {3, -1}},\n {{2, -3}, {1, -1}, {4, -4}, {3, -2}},\n {{1, 3}, {4, -4}, {2, -3}, {-1, -2}},\n {{2, -1}, {3, -3}, {1, -2}, {4, -4}},\n {{2, -2}, {3, -3}, {1, -1}, {4, -4}},\n {{1, 2}, {3, -3}, {4, -4}, {-1, -2}},\n {{-3, -2}, {2, 3}, {1, -1}, {4, -4}},\n {{1, 3}, {-3, -2}, {2, -1}, {4, -4}},\n {{1, 2}, {-3, -2}, {4, -4}, {3, -1}},\n {{-3, -1}, {2, 3}, {1, -2}, {4, -4}},\n {{1, 3}, {-3, -1}, {2, -2}, {4, -4}},\n {{1, 2}, {-3, -1}, {4, -4}, {3, -2}}]\n ' set = (list(range(1, (self.k + 1))) + [(- x) for x in range(1, (self.k + 1))]) for sp in SetPartitions(set, ([2] * (len(set) // 2))): (yield self.element_class(self, (Set(list(sp)) + Set([Set([(self.k + 1), ((- self.k) - 1)])]))))
def SetPartitionsPk(k): '\n Return the combinatorial class of set partitions of type `P_k`.\n\n These are the planar set partitions.\n\n EXAMPLES::\n\n sage: P3 = SetPartitionsPk(3); P3\n Set partitions of {1, ..., 3, -1, ..., -3} that are planar\n sage: P3.cardinality()\n 132\n\n sage: P3.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: P3.last() #random\n {{-1}, {-2}, {3}, {1}, {-3}, {2}}\n sage: P3.random_element() #random\n {{1, 2, -1}, {-3}, {3, -2}}\n\n sage: P2p5 = SetPartitionsPk(2.5); P2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and that are planar\n sage: P2p5.cardinality()\n 42\n\n sage: P2p5.first() #random\n {{1, 2, 3, -1, -3, -2}}\n sage: P2p5.last() #random\n {{-1}, {-2}, {2}, {3, -3}, {1}}\n sage: P2p5.random_element() #random\n {{1, 2, 3, -3}, {-1, -2}}\n\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsPkhalf_k(k) return SetPartitionsPk_k(k)
class SetPartitionsPk_k(SetPartitionsAk_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsPk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} that are planar\n ' return (SetPartitionsAk_k._repr_(self) + ' that are planar') def __contains__(self, x): '\n TESTS::\n\n sage: P3 = SetPartitionsPk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: len([x for x in A3 if x in P3])\n 132\n sage: P3.cardinality()\n 132\n sage: all(sp in P3 for sp in P3)\n True\n ' if (not SetPartitionsAk_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsPk(2).cardinality()\n 14\n sage: SetPartitionsPk(3).cardinality()\n 132\n sage: SetPartitionsPk(4).cardinality()\n 1430\n ' return catalan_number((2 * self.k)) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsPk(2).list() #random indirect test\n [{{1, 2, -1, -2}},\n {{2, -1, -2}, {1}},\n {{2}, {1, -1, -2}},\n {{-1}, {1, 2, -2}},\n {{-2}, {1, 2, -1}},\n {{2, -2}, {1, -1}},\n {{1, 2}, {-1, -2}},\n {{2}, {-1, -2}, {1}},\n {{-1}, {2, -2}, {1}},\n {{-2}, {2, -1}, {1}},\n {{-1}, {2}, {1, -2}},\n {{-2}, {2}, {1, -1}},\n {{-1}, {-2}, {1, 2}},\n {{-1}, {-2}, {2}, {1}}]\n ' for sp in SetPartitionsAk_k.__iter__(self): if is_planar(sp): (yield self.element_class(self, sp))
class SetPartitionsPkhalf_k(SetPartitionsAkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: P2p5 = SetPartitionsPk(2.5)\n sage: all(sp in P2p5 for sp in P2p5)\n True\n sage: len([x for x in A3 if x in P2p5])\n 42\n sage: P2p5.cardinality()\n 42\n ' if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def _repr_(self): "\n TESTS::\n\n sage: repr( SetPartitionsPk(2.5) )\n 'Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and that are planar'\n " return (SetPartitionsAkhalf_k._repr_(self) + ' and that are planar') def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsPk(2.5).cardinality()\n 42\n sage: SetPartitionsPk(1.5).cardinality()\n 5\n ' return len(self.list()) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsPk(1.5).list() #random\n [{{1, 2, -2, -1}},\n {{2, -2, -1}, {1}},\n {{2, -2}, {1, -1}},\n {{-1}, {1, 2, -2}},\n {{-1}, {2, -2}, {1}}]\n ' for sp in SetPartitionsAkhalf_k.__iter__(self): if is_planar(sp): (yield self.element_class(self, sp))
def SetPartitionsTk(k): '\n Return the combinatorial class of set partitions of type `T_k`.\n\n These are planar set partitions where every block is of size 2.\n\n EXAMPLES::\n\n sage: T3 = SetPartitionsTk(3); T3\n Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 and that are planar\n sage: T3.cardinality()\n 5\n\n sage: T3.first() #random\n {{1, -3}, {2, 3}, {-1, -2}}\n sage: T3.last() #random\n {{1, 2}, {3, -1}, {-3, -2}}\n sage: T3.random_element() #random\n {{1, -3}, {2, 3}, {-1, -2}}\n\n sage: T2p5 = SetPartitionsTk(2.5); T2p5\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 and that are planar\n sage: T2p5.cardinality()\n 2\n\n sage: T2p5.first() #random\n {{2, -2}, {3, -3}, {1, -1}}\n sage: T2p5.last() #random\n {{1, 2}, {3, -3}, {-1, -2}}\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsTkhalf_k(k) return SetPartitionsTk_k(k)
class SetPartitionsTk_k(SetPartitionsBk_k): def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsTk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 and that are planar\n ' return (SetPartitionsBk_k._repr_(self) + ' and that are planar') def __contains__(self, x): '\n TESTS::\n\n sage: T3 = SetPartitionsTk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in T3 for sp in T3)\n True\n sage: len([x for x in A3 if x in T3])\n 5\n sage: T3.cardinality()\n 5\n ' if (not SetPartitionsBk_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsTk(2).cardinality()\n 2\n sage: SetPartitionsTk(3).cardinality()\n 5\n sage: SetPartitionsTk(4).cardinality()\n 14\n sage: SetPartitionsTk(5).cardinality()\n 42\n ' return catalan_number(self.k) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsTk(3).list() #random\n [{{1, -3}, {2, 3}, {-1, -2}},\n {{2, -2}, {3, -3}, {1, -1}},\n {{1, 2}, {3, -3}, {-1, -2}},\n {{-3, -2}, {2, 3}, {1, -1}},\n {{1, 2}, {3, -1}, {-3, -2}}]\n ' for sp in SetPartitionsBk_k.__iter__(self): if is_planar(sp): (yield self.element_class(self, sp))
class SetPartitionsTkhalf_k(SetPartitionsBkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: T2p5 = SetPartitionsTk(2.5)\n sage: all(sp in T2p5 for sp in T2p5)\n True\n sage: len([x for x in A3 if x in T2p5])\n 2\n sage: T2p5.cardinality()\n 2\n ' if (not SetPartitionsBkhalf_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsTk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 and that are planar\n ' return (SetPartitionsBkhalf_k._repr_(self) + ' and that are planar') def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsTk(2.5).cardinality()\n 2\n sage: SetPartitionsTk(3.5).cardinality()\n 5\n sage: SetPartitionsTk(4.5).cardinality()\n 14\n ' return catalan_number(self.k) def __iter__(self): '\n TESTS::\n\n sage: SetPartitionsTk(3.5).list() #random\n [{{1, -3}, {2, 3}, {4, -4}, {-1, -2}},\n {{2, -2}, {3, -3}, {1, -1}, {4, -4}},\n {{1, 2}, {3, -3}, {4, -4}, {-1, -2}},\n {{-3, -2}, {2, 3}, {1, -1}, {4, -4}},\n {{1, 2}, {-3, -2}, {4, -4}, {3, -1}}]\n ' for sp in SetPartitionsBkhalf_k.__iter__(self): if is_planar(sp): (yield self.element_class(self, sp))
def SetPartitionsRk(k): '\n Return the combinatorial class of set partitions of type `R_k`.\n\n EXAMPLES::\n\n sage: SetPartitionsRk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive\n and negative entry in each block\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsRkhalf_k(k) return SetPartitionsRk_k(k)
class SetPartitionsRk_k(SetPartitionsAk_k): def __init__(self, k): '\n TESTS::\n\n sage: R3 = SetPartitionsRk(3); R3\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block\n sage: R3 == loads(dumps(R3))\n True\n ' self.k = k SetPartitionsAk_k.__init__(self, k) def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsRk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block\n ' return (SetPartitionsAk_k._repr_(self) + ' with at most 1 positive and negative entry in each block') def __contains__(self, x): '\n TESTS::\n\n sage: R3 = SetPartitionsRk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in R3 for sp in R3)\n True\n sage: len([x for x in A3 if x in R3])\n 34\n sage: R3.cardinality()\n 34\n ' if (not SetPartitionsAk_k.__contains__(self, x)): return False for block in x: if (len(block) > 2): return False negatives = 0 positives = 0 for i in block: if (i < 0): negatives += 1 else: positives += 1 if ((negatives > 1) or (positives > 1)): return False return True def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsRk(2).cardinality()\n 7\n sage: SetPartitionsRk(3).cardinality()\n 34\n sage: SetPartitionsRk(4).cardinality()\n 209\n sage: SetPartitionsRk(5).cardinality()\n 1546\n ' return sum((((binomial(self.k, l) ** 2) * factorial(l)) for l in range((self.k + 1)))) def __iter__(self): '\n TESTS::\n\n sage: len(SetPartitionsRk(3).list() ) == SetPartitionsRk(3).cardinality()\n True\n ' positives = Set(range(1, (self.k + 1))) negatives = Set(((- i) for i in positives)) (yield self.element_class(self, to_set_partition([], self.k))) for n in range(1, (self.k + 1)): for top in Subsets(positives, n): t = list(top) for bottom in Subsets(negatives, n): b = list(bottom) for permutation in Permutations(n): l = [[t[i], b[(permutation[i] - 1)]] for i in range(n)] (yield self.element_class(self, to_set_partition(l, k=self.k)))
class SetPartitionsRkhalf_k(SetPartitionsAkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: R2p5 = SetPartitionsRk(2.5)\n sage: all(sp in R2p5 for sp in R2p5)\n True\n sage: len([x for x in A3 if x in R2p5])\n 7\n sage: R2p5.cardinality()\n 7\n ' if (not SetPartitionsAkhalf_k.__contains__(self, x)): return False for block in x: if (len(block) > 2): return False negatives = 0 positives = 0 for i in block: if (i < 0): negatives += 1 else: positives += 1 if ((negatives > 1) or (positives > 1)): return False return True def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsRk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block\n ' return (SetPartitionsAkhalf_k._repr_(self) + ' and with at most 1 positive and negative entry in each block') def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsRk(2.5).cardinality()\n 7\n sage: SetPartitionsRk(3.5).cardinality()\n 34\n sage: SetPartitionsRk(4.5).cardinality()\n 209\n ' return sum((((binomial(self.k, l) ** 2) * factorial(l)) for l in range((self.k + 1)))) def __iter__(self): '\n TESTS::\n\n sage: R2p5 = SetPartitionsRk(2.5)\n sage: L = list(R2p5); L #random due to sets\n [{{-2}, {-1}, {3, -3}, {2}, {1}},\n {{-2}, {3, -3}, {2}, {1, -1}},\n {{-1}, {3, -3}, {2}, {1, -2}},\n {{-2}, {2, -1}, {3, -3}, {1}},\n {{-1}, {2, -2}, {3, -3}, {1}},\n {{2, -2}, {3, -3}, {1, -1}},\n {{2, -1}, {3, -3}, {1, -2}}]\n sage: len(L)\n 7\n ' positives = Set(range(1, (self.k + 1))) negatives = Set(((- i) for i in positives)) (yield self.element_class(self, to_set_partition([[(self.k + 1), ((- self.k) - 1)]], (self.k + 1)))) for n in range(1, (self.k + 1)): for top in Subsets(positives, n): t = list(top) for bottom in Subsets(negatives, n): b = list(bottom) for permutation in Permutations(n): l = ([[t[i], b[(permutation[i] - 1)]] for i in range(n)] + [[(self.k + 1), ((- self.k) - 1)]]) (yield self.element_class(self, to_set_partition(l, k=(self.k + 1))))
def SetPartitionsPRk(k): '\n Return the combinatorial class of set partitions of type `PR_k`.\n\n EXAMPLES::\n\n sage: SetPartitionsPRk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive\n and negative entry in each block and that are planar\n ' (is_int, k) = _int_or_half_int(k) if (not is_int): return SetPartitionsPRkhalf_k(k) return SetPartitionsPRk_k(k)
class SetPartitionsPRk_k(SetPartitionsRk_k): def __init__(self, k): '\n TESTS::\n\n sage: PR3 = SetPartitionsPRk(3); PR3\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block and that are planar\n sage: PR3 == loads(dumps(PR3))\n True\n ' self.k = k SetPartitionsRk_k.__init__(self, k) def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsPRk(3)\n Set partitions of {1, ..., 3, -1, ..., -3} with at most 1 positive and negative entry in each block and that are planar\n ' return (SetPartitionsRk_k._repr_(self) + ' and that are planar') def __contains__(self, x): '\n TESTS::\n\n sage: PR3 = SetPartitionsPRk(3)\n sage: A3 = SetPartitionsAk(3)\n sage: all(sp in PR3 for sp in PR3)\n True\n sage: len([x for x in A3 if x in PR3])\n 20\n sage: PR3.cardinality()\n 20\n ' if (not SetPartitionsRk_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsPRk(2).cardinality()\n 6\n sage: SetPartitionsPRk(3).cardinality()\n 20\n sage: SetPartitionsPRk(4).cardinality()\n 70\n sage: SetPartitionsPRk(5).cardinality()\n 252\n ' return binomial((2 * self.k), self.k) def __iter__(self): '\n TESTS::\n\n sage: len(SetPartitionsPRk(3).list() ) == SetPartitionsPRk(3).cardinality()\n True\n ' positives = Set(range(1, (self.k + 1))) negatives = Set(((- i) for i in positives)) (yield self.element_class(self, to_set_partition([], self.k))) for n in range(1, (self.k + 1)): for top in Subsets(positives, n): t = sorted(top) for bottom in Subsets(negatives, n): b = list(bottom) b.sort(reverse=True) l = [[t[i], b[i]] for i in range(n)] (yield self.element_class(self, to_set_partition(l, k=self.k)))
class SetPartitionsPRkhalf_k(SetPartitionsRkhalf_k): def __contains__(self, x): '\n TESTS::\n\n sage: A3 = SetPartitionsAk(3)\n sage: PR2p5 = SetPartitionsPRk(2.5)\n sage: all(sp in PR2p5 for sp in PR2p5)\n True\n sage: len([x for x in A3 if x in PR2p5])\n 6\n sage: PR2p5.cardinality()\n 6\n ' if (not SetPartitionsRkhalf_k.__contains__(self, x)): return False if (not is_planar(x)): return False return True def _repr_(self): '\n TESTS::\n\n sage: SetPartitionsPRk(2.5)\n Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with at most 1 positive and negative entry in each block and that are planar\n ' return (SetPartitionsRkhalf_k._repr_(self) + ' and that are planar') def cardinality(self): '\n TESTS::\n\n sage: SetPartitionsPRk(2.5).cardinality()\n 6\n sage: SetPartitionsPRk(3.5).cardinality()\n 20\n sage: SetPartitionsPRk(4.5).cardinality()\n 70\n ' return binomial((2 * self.k), self.k) def __iter__(self): '\n TESTS::\n\n sage: next(iter(SetPartitionsPRk(2.5)))\n {{-3, 3}, {-2}, {-1}, {1}, {2}}\n sage: len(list(SetPartitionsPRk(2.5)))\n 6\n ' positives = Set(range(1, (self.k + 1))) negatives = Set(((- i) for i in positives)) (yield self.element_class(self, to_set_partition([[(self.k + 1), ((- self.k) - 1)]], k=(self.k + 1)))) for n in range(1, (self.k + 1)): for top in Subsets(positives, n): t = sorted(top) for bottom in Subsets(negatives, n): b = list(bottom) b.sort(reverse=True) l = ([[t[i], b[i]] for i in range(n)] + [[(self.k + 1), ((- self.k) - 1)]]) (yield self.element_class(self, to_set_partition(l, k=(self.k + 1))))
class PartitionAlgebra_generic(CombinatorialFreeModule): def __init__(self, R, cclass, n, k, name=None, prefix=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: s = PartitionAlgebra_sk(QQ, 3, 1)\n sage: TestSuite(s).run()\n sage: s == loads(dumps(s))\n True\n ' self.k = k self.n = n self._indices = cclass self._name = (('Generic partition algebra with k = %s and n = %s and basis %s' % (self.k, self.n, cclass)) if (name is None) else name) self._prefix = ('' if (prefix is None) else prefix) CombinatorialFreeModule.__init__(self, R, cclass, category=AlgebrasWithBasis(R)) def one_basis(self): '\n Return the basis index for the unit of the algebra.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: s = PartitionAlgebra_sk(ZZ, 3, 1)\n sage: len(s.one().support()) # indirect doctest\n 1\n ' return self.basis().keys()(identity(ceil(self.k))) def product_on_basis(self, left, right): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: s = PartitionAlgebra_sk(QQ, 3, 1)\n sage: t12 = s(Set([Set([1,-2]),Set([2,-1]),Set([3,-3])]))\n sage: t12^2 == s(1) #indirect doctest\n True\n ' (sp, l) = set_partition_composition(left, right) sp = self.basis().keys()(sp) return self.term(sp, (self.n ** l))
class PartitionAlgebraElement_generic(CombinatorialFreeModule.Element): pass
class PartitionAlgebraElement_ak(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_ak(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_ak(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra A_%s(%s)' % (k, n)) cclass = SetPartitionsAk(k) self._element_class = PartitionAlgebraElement_ak PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='A')
class PartitionAlgebraElement_bk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_bk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_bk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra B_%s(%s)' % (k, n)) cclass = SetPartitionsBk(k) self._element_class = PartitionAlgebraElement_bk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='B')
class PartitionAlgebraElement_sk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_sk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_sk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra S_%s(%s)' % (k, n)) cclass = SetPartitionsSk(k) self._element_class = PartitionAlgebraElement_sk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='S')
class PartitionAlgebraElement_pk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_pk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_pk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra P_%s(%s)' % (k, n)) cclass = SetPartitionsPk(k) self._element_class = PartitionAlgebraElement_pk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='P')
class PartitionAlgebraElement_tk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_tk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_tk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra T_%s(%s)' % (k, n)) cclass = SetPartitionsTk(k) self._element_class = PartitionAlgebraElement_tk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='T')
class PartitionAlgebraElement_rk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_rk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_rk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra R_%s(%s)' % (k, n)) cclass = SetPartitionsRk(k) self._element_class = PartitionAlgebraElement_rk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='R')
class PartitionAlgebraElement_prk(PartitionAlgebraElement_generic): pass
class PartitionAlgebra_prk(PartitionAlgebra_generic): def __init__(self, R, k, n, name=None): '\n EXAMPLES::\n\n sage: from sage.combinat.partition_algebra import *\n sage: p = PartitionAlgebra_prk(QQ, 3, 1)\n sage: p == loads(dumps(p))\n True\n ' if (name is None): name = ('Partition algebra PR_%s(%s)' % (k, n)) cclass = SetPartitionsPRk(k) self._element_class = PartitionAlgebraElement_prk PartitionAlgebra_generic.__init__(self, R, cclass, n, k, name=name, prefix='PR')
def is_planar(sp): '\n Return ``True`` if the diagram corresponding to the set partition is\n planar; otherwise, it returns ``False``.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: pa.is_planar( pa.to_set_partition([[1,-2],[2,-1]]))\n False\n sage: pa.is_planar( pa.to_set_partition([[1,-1],[2,-2]]))\n True\n ' to_consider = [x for x in map(list, sp) if (len(x) > 1)] n = len(to_consider) for i in range(n): ap = [x for x in to_consider[i] if (x > 0)] an = [(- x) for x in to_consider[i] if (x < 0)] if (ap and an): for j in range(n): if (i == j): continue bp = [x for x in to_consider[j] if (x > 0)] bn = [(- x) for x in to_consider[j] if (x < 0)] if ((not bn) or (not bp)): continue if (max(bp) > max(ap)): if (min(bn) < min(an)): return False for row in [ap, an]: if (len(row) > 1): row.sort() for s in range((len(row) - 1)): if ((row[s] + 1) == row[(s + 1)]): continue else: rng = list(range((row[s] + 1), row[(s + 1)])) for j in range(n): if (i == j): continue if (row is ap): sr = Set(rng) else: sr = Set(((- x) for x in rng)) sj = Set(to_consider[j]) intersection = sr.intersection(sj) if intersection: if (sj != intersection): return False return True
def to_graph(sp): '\n Return a graph representing the set partition ``sp``.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: g = pa.to_graph( pa.to_set_partition([[1,-2],[2,-1]])); g\n Graph on 4 vertices\n\n sage: g.vertices(sort=False) #random\n [1, 2, -2, -1]\n sage: g.edges(sort=False) #random\n [(1, -2, None), (2, -1, None)]\n ' g = Graph() for part in sp: part_list = list(part) if part_list: g.add_vertex(part_list[0]) for i in range(1, len(part_list)): g.add_vertex(part_list[i]) g.add_edge(part_list[(i - 1)], part_list[i]) return g
def pair_to_graph(sp1, sp2): '\n Return a graph consisting of the disjoint union of the graphs of set\n partitions ``sp1`` and ``sp2`` along with edges joining the bottom\n row (negative numbers) of ``sp1`` to the top row (positive numbers)\n of ``sp2``.\n\n The vertices of the graph ``sp1`` appear in the result as pairs\n ``(k, 1)``, whereas the vertices of the graph ``sp2`` appear as\n pairs ``(k, 2)``.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: sp1 = pa.to_set_partition([[1,-2],[2,-1]])\n sage: sp2 = pa.to_set_partition([[1,-2],[2,-1]])\n sage: g = pa.pair_to_graph( sp1, sp2 ); g\n Graph on 8 vertices\n\n ::\n\n sage: g.vertices(sort=False) #random\n [(1, 2), (-1, 1), (-2, 2), (-1, 2), (-2, 1), (2, 1), (2, 2), (1, 1)]\n sage: g.edges(sort=False) #random\n [((1, 2), (-1, 1), None),\n ((1, 2), (-2, 2), None),\n ((-1, 1), (2, 1), None),\n ((-1, 2), (2, 2), None),\n ((-2, 1), (1, 1), None),\n ((-2, 1), (2, 2), None)]\n\n Another example which used to be wrong until :trac:`15958`::\n\n sage: sp3 = pa.to_set_partition([[1, -1], [2], [-2]])\n sage: sp4 = pa.to_set_partition([[1], [-1], [2], [-2]])\n sage: g = pa.pair_to_graph( sp3, sp4 ); g\n Graph on 8 vertices\n\n sage: g.vertices(sort=True)\n [(-2, 1), (-2, 2), (-1, 1), (-1, 2), (1, 1), (1, 2), (2, 1), (2, 2)]\n sage: g.edges(sort=True)\n [((-2, 1), (2, 2), None), ((-1, 1), (1, 1), None),\n ((-1, 1), (1, 2), None)]\n ' g = Graph() for part in sp1: part_list = list(part) if part_list: g.add_vertex((part_list[0], 1)) if (part_list[0] < 0): g.add_edge((part_list[0], 1), ((- part_list[0]), 2)) for i in range(1, len(part_list)): g.add_vertex((part_list[i], 1)) if (part_list[i] < 0): g.add_edge((part_list[i], 1), ((- part_list[i]), 2)) g.add_edge((part_list[(i - 1)], 1), (part_list[i], 1)) for part in sp2: part_list = list(part) if part_list: g.add_vertex((part_list[0], 2)) for i in range(1, len(part_list)): g.add_vertex((part_list[i], 2)) g.add_edge((part_list[(i - 1)], 2), (part_list[i], 2)) return g
def propagating_number(sp): '\n Return the propagating number of the set partition ``sp``.\n\n The propagating number is the number of blocks with both a\n positive and negative number.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: sp1 = pa.to_set_partition([[1,-2],[2,-1]])\n sage: sp2 = pa.to_set_partition([[1,2],[-2,-1]])\n sage: pa.propagating_number(sp1)\n 2\n sage: pa.propagating_number(sp2)\n 0\n ' return sum((1 for part in sp if (min(part) < 0 < max(part))))
def to_set_partition(l, k=None): '\n Convert a list of a list of numbers to a set partitions.\n\n Each list of numbers in the outer list specifies the numbers\n contained in one of the blocks in the set partition.\n\n If k is specified, then the set partition will be a set partition\n of 1, ..., k, -1, ..., -k. Otherwise, k will default to the minimum\n number needed to contain all of the specified numbers.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: pa.to_set_partition([[1,-1],[2,-2]]) == pa.identity(2)\n True\n ' if (k is None): if (not l): return Set([]) else: k = max((max(map(abs, x)) for x in l)) to_be_added = Set((list(range(1, (k + 1))) + [(- x) for x in range(1, (k + 1))])) sp = [] for part in l: spart = Set(part) to_be_added -= spart sp.append(spart) for singleton in to_be_added: sp.append(Set([singleton])) return Set(sp)
def identity(k): '\n Return the identity set partition 1, -1, ..., k, -k\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: pa.identity(2)\n {{2, -2}, {1, -1}}\n ' return Set((Set([i, (- i)]) for i in range(1, (k + 1))))
def set_partition_composition(sp1, sp2): '\n Return a tuple consisting of the composition of the set partitions\n sp1 and sp2 and the number of components removed from the middle\n rows of the graph.\n\n EXAMPLES::\n\n sage: import sage.combinat.partition_algebra as pa\n sage: sp1 = pa.to_set_partition([[1,-2],[2,-1]])\n sage: sp2 = pa.to_set_partition([[1,-2],[2,-1]])\n sage: pa.set_partition_composition(sp1, sp2) == (pa.identity(2), 0)\n True\n ' g = pair_to_graph(sp1, sp2) connected_components = g.connected_components(sort=False) res = [] total_removed = 0 for cc in connected_components: new_cc = [x for x in cc if (not (((x[0] < 0) and (x[1] == 1)) or ((x[0] > 0) and (x[1] == 2))))] if (not new_cc): if (len(cc) > 1): total_removed += 1 else: res.append(Set((x[0] for x in new_cc))) return (Set(res), total_removed)
class KleshchevPartition(Partition): '\n Abstract base class for Kleshchev partitions. See\n :class:`~KleshchevPartitions`.\n ' def conormal_cells(self, i=None): '\n Return a dictionary of the cells of ``self`` which are conormal.\n\n Following [Kle1995]_, the *conormal* cells are computed by\n reading up (or down) the rows of the partition and marking all\n of the addable and removable cells of `e`-residue `i` and then\n recursively removing all adjacent pairs of removable and addable\n cells (in that order) from this list. The addable `i`-cells that\n remain at the end of the this process are the conormal `i`-cells.\n\n When computing conormal cells you can either read the cells in order\n from top to bottom (this corresponds to labeling the simple modules\n of the symmetric group by regular partitions) or from bottom to top\n (corresponding to labeling the simples by restricted partitions).\n By default we read down the partition but this can be changed by\n setting ``convention = \'RS\'``.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of conormal cells\n is returned, which gives the conormal cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention="regular")\n sage: KP([5,4,4,3,2]).conormal_cells()\n {0: [(1, 4)], 1: [(5, 0), (4, 2)]}\n sage: KP([5,4,4,3,2]).conormal_cells(0)\n [(1, 4)]\n sage: KP([5,4,4,3,2]).conormal_cells(1)\n [(5, 0), (4, 2)]\n sage: KP = KleshchevPartitions(3, convention="restricted")\n sage: KP([5,4,4,3,2]).conormal_cells()\n {0: [(1, 4), (3, 3)], 2: [(0, 5)]}\n ' conormals = defaultdict(list) carry = defaultdict(int) KP = self.parent() rows = list(range((len(self) + 1))) if (KP._convention[1] == 'G'): rows.reverse() for row in rows: if (row == len(self)): res = (KP._multicharge[0] - row) if (carry[res] == 0): conormals[res].append((row, 0)) else: carry[res] += 1 else: res = (((KP._multicharge[0] + self[row]) - row) - 1) if ((row == (len(self) - 1)) or (self[row] > self[(row + 1)])): carry[res] -= 1 if ((row == 0) or (self[(row - 1)] > self[row])): if (carry[(res + 1)] >= 0): conormals[(res + 1)].append((row, self[row])) else: carry[(res + 1)] += 1 return (dict(conormals) if (i is None) else conormals[i]) def cogood_cells(self, i=None): '\n Return a list of the cells of ``self`` that are cogood.\n\n The cogood `i`-cell is the \'last\' conormal `i`-cell. As with the\n conormal cells we can choose to read either up or down the partition as\n specified by :meth:`~KleshchevPartitions.convention`.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of cogood cells\n is returned, which gives the cogood cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention="regular")\n sage: KP([5,4,4,3,2]).cogood_cells()\n {0: (1, 4), 1: (4, 2)}\n sage: KP([5,4,4,3,2]).cogood_cells(0)\n (1, 4)\n sage: KP([5,4,4,3,2]).cogood_cells(1)\n (4, 2)\n sage: KP = KleshchevPartitions(4, convention=\'restricted\')\n sage: KP([5,4,4,3,2]).cogood_cells()\n {1: (0, 5), 2: (4, 2), 3: (1, 4)}\n sage: KP([5,4,4,3,2]).cogood_cells(0)\n sage: KP([5,4,4,3,2]).cogood_cells(2)\n (4, 2)\n ' conormal_cells = self.conormal_cells(i) if (i is None): return {i: conormal_cells[i][(- 1)] for i in conormal_cells} elif (not conormal_cells): return None return conormal_cells[(- 1)] def normal_cells(self, i=None): "\n Return a dictionary of the cells of the partition that are normal.\n\n Following [Kle1995]_, the *normal* cells are computed by\n reading up (or down) the rows of the partition and marking all\n of the addable and removable cells of `e`-residue `i` and then\n recursively removing all adjacent pairs of removable and\n addable cells (in that order) from this list. The removable\n `i`-cells that remain at the end of the this process are the\n normal `i`-cells.\n\n When computing normal cells you can either read the cells in order\n from top to bottom (this corresponds to labeling the simple modules\n of the symmetric group by regular partitions) or from bottom to top\n (corresponding to labeling the simples by restricted partitions).\n By default we read down the partition but this can be changed by\n setting ``convention = 'RS'``.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of normal cells\n is returned, which gives the normal cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention='regular')\n sage: KP([5,4,4,3,2]).normal_cells()\n {1: [(2, 3), (0, 4)]}\n sage: KP([5,4,4,3,2]).normal_cells(1)\n [(2, 3), (0, 4)]\n sage: KP = KleshchevPartitions(3, convention='restricted')\n sage: KP([5,4,4,3,2]).normal_cells()\n {0: [(4, 1)], 2: [(3, 2)]}\n sage: KP([5,4,4,3,2]).normal_cells(2)\n [(3, 2)]\n " normals = defaultdict(list) carry = defaultdict(int) KP = self.parent() rows = list(range((len(self) + 1))) if (KP._convention[1] == 'S'): rows.reverse() for row in rows: if (row == len(self)): carry[(KP._multicharge[0] - row)] += 1 else: res = (((KP._multicharge[0] + self[row]) - row) - 1) if ((row == (len(self) - 1)) or (self[row] > self[(row + 1)])): if (carry[res] == 0): normals[res].insert(0, (row, (self[row] - 1))) else: carry[res] -= 1 if ((row == 0) or (self[(row - 1)] > self[row])): carry[(res + 1)] += 1 return (dict(normals) if (i is None) else normals[i]) def good_cells(self, i=None): "\n Return a list of the cells of ``self`` that are good.\n\n The good `i`-cell is the 'first' normal `i`-cell. As with the normal\n cells we can choose to read either up or down the partition as\n specified by :meth:`~KleshchevPartitions.convention`.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of good cells\n is returned, which gives the good cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP3 = KleshchevPartitions(3, convention='regular')\n sage: KP3([5,4,4,3,2]).good_cells()\n {1: (2, 3)}\n sage: KP3([5,4,4,3,2]).good_cells(1)\n (2, 3)\n sage: KP4 = KleshchevPartitions(4, convention='restricted')\n sage: KP4([5,4,4,3,2]).good_cells()\n {1: (2, 3)}\n sage: KP4([5,4,4,3,2]).good_cells(0)\n sage: KP4([5,4,4,3,2]).good_cells(1)\n (2, 3)\n " normal_cells = self.normal_cells(i) if (i is None): return {j: normal_cells[j][0] for j in normal_cells} elif (not normal_cells): return None return normal_cells[0] def good_residue_sequence(self): "\n Return a sequence of good nodes from the empty partition\n to ``self``, or ``None`` if no such sequence exists.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention='regular')\n sage: KP([5,4,4,3,2]).good_residue_sequence()\n [0, 2, 1, 1, 0, 2, 0, 2, 1, 1, 0, 2, 0, 2, 2, 0, 1, 1]\n sage: KP = KleshchevPartitions(3, convention='restricted')\n sage: KP([5,4,4,3,2]).good_residue_sequence()\n [0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 0, 2, 1, 2, 1, 0]\n " if (not self): return [] good_cells = self.good_cells() assert good_cells res = sorted(good_cells)[0] (r, c) = good_cells[res] good_seq = type(self)(self.parent(), self.remove_cell(r, c)).good_residue_sequence() good_seq.append(self.parent()._index_set(res)) return good_seq def good_cell_sequence(self): "\n Return a sequence of good nodes from the empty partition\n to ``self``, or ``None`` if no such sequence exists.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention='regular')\n sage: KP([5,4,4,3,2]).good_cell_sequence()\n [(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2),\n (3, 0), (2, 1), (1, 2), (3, 1), (0, 3), (1, 3),\n (2, 2), (3, 2), (4, 0), (4, 1), (0, 4), (2, 3)]\n sage: KP = KleshchevPartitions(3, convention='restricted')\n sage: KP([5,4,4,3,2]).good_cell_sequence()\n [(0, 0), (0, 1), (1, 0), (0, 2), (1, 1), (2, 0),\n (0, 3), (2, 1), (1, 2), (1, 3), (3, 0), (3, 1),\n (2, 2), (4, 0), (2, 3), (3, 2), (0, 4), (4, 1)]\n " if (not self): return [] good_cells = self.good_cells() assert good_cells cell = good_cells[sorted(good_cells)[0]] good_seq = type(self)(self.parent(), self.remove_cell(*cell)).good_cell_sequence() good_seq.append(cell) return good_seq def mullineux_conjugate(self): "\n Return the partition tuple that is the Mullineux conjugate of ``self``.\n\n It follows from results in [BK2009]_, [Mat2015]_ that if `\\nu` is the\n Mullineux conjugate of the Kleshchev partition tuple `\\mu` then the\n simple module `D^\\nu =(D^\\mu)^{\\text{sgn}}` is obtained from `D^\\mu`\n by twisting by the `\\text{sgn}`-automorphism with is the\n Iwahori-Hecke algebra analogue of tensoring with the one\n dimensional sign representation.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, convention='regular')\n sage: KP([5,4,4,3,2]).mullineux_conjugate()\n [9, 7, 1, 1]\n sage: KP = KleshchevPartitions(3, convention='restricted')\n sage: KP([5,4,4,3,2]).mullineux_conjugate()\n [3, 2, 2, 2, 2, 2, 2, 1, 1, 1]\n sage: KP = KleshchevPartitions(3, [2], convention='regular')\n sage: mc = KP([5,4,4,3,2]).mullineux_conjugate(); mc\n [9, 7, 1, 1]\n sage: mc.parent().multicharge()\n (1,)\n sage: KP = KleshchevPartitions(3, [2], convention='restricted')\n sage: mc = KP([5,4,4,3,2]).mullineux_conjugate(); mc\n [3, 2, 2, 2, 2, 2, 2, 1, 1, 1]\n sage: mc.parent().multicharge()\n (1,)\n " P = self.parent() if (not self): size = None if isinstance(P, KleshchevPartitions_size): size = P._size KP = KleshchevPartitions(P._e, [(- c) for c in P._multicharge], size=size, convention=P._convention) return KP.element_class(KP, []) good_cells = self.good_cells() assert good_cells (r, c) = sorted(good_cells.values())[0] mu = P.element_class(P, self.remove_cell(r, c)).mullineux_conjugate() KP = mu.parent() return KP.element_class(KP, mu.add_cell(*mu.cogood_cells(((r - c) - self.parent()._multicharge[0])))) def is_regular(self): '\n Return ``True`` if ``self`` is a `e`-regular partition tuple.\n\n A partition tuple is `e`-regular if we can get to the empty partition\n tuple by successively removing a sequence of good cells in the down\n direction. Equivalently, all partitions are `0`-regular and if `e > 0`\n then a partition is `e`-regular if no `e` non-zero parts of ``self``\n are equal.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(2)\n sage: KP([2,1,1]).is_regular()\n False\n sage: KP = KleshchevPartitions(3)\n sage: KP([2,1,1]).is_regular()\n True\n sage: KP([]).is_regular()\n True\n ' if ((self.size() == 0) or (self.parent()._e == 0)): return True KP = self.parent() return super().is_regular(KP._e, KP._multicharge) def is_restricted(self): "\n Return ``True`` if ``self`` is an `e`-restricted partition tuple.\n\n A partition tuple is `e`-restricted if we can get to the empty\n partition tuple by successively removing a sequence of good cells in\n the up direction. Equivalently, all partitions are `0`-restricted and\n if `e > 0` then a partition is `e`-restricted if the difference of\n successive parts of ``self`` are always strictly less than `e`.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(2, convention='regular')\n sage: KP([3,1]).is_restricted()\n False\n sage: KP = KleshchevPartitions(3, convention='regular')\n sage: KP([3,1]).is_restricted()\n True\n sage: KP([]).is_restricted()\n True\n " if ((self.size() == 0) or (self.parent()._e == 0)): return True KP = self.parent() return super().is_restricted(KP._e, KP._multicharge)
class KleshchevPartitionTuple(PartitionTuple): '\n Abstract base class for Kleshchev partition tuples. See\n :class:`~KleshchevPartitions`.\n ' def conormal_cells(self, i=None): '\n Return a dictionary of the cells of the partition that are conormal.\n\n Following [Kle1995]_, the *conormal* cells are computed by\n reading up (or down) the rows of the partition and marking all\n of the addable and removable cells of `e`-residue `i` and then\n recursively removing all adjacent pairs of removable and addable\n cells (in that order) from this list. The addable `i`-cells that\n remain at the end of the this process are the conormal `i`-cells.\n\n When computing conormal cells you can either read the cells in order\n from top to bottom (this corresponds to labeling the simple modules\n of the symmetric group by regular partitions) or from bottom to top\n (corresponding to labeling the simples by restricted partitions).\n By default we read down the partition but this can be changed by\n setting ``convention = \'RS\'``.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of conormal cells\n is returned, which gives the conormal cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1], convention="left regular")\n sage: KP([[4, 2], [5, 3, 1]]).conormal_cells()\n {0: [(1, 2, 1), (1, 1, 3), (1, 0, 5)],\n 1: [(1, 3, 0), (0, 2, 0), (0, 1, 2), (0, 0, 4)]}\n sage: KP([[4, 2], [5, 3, 1]]).conormal_cells(1)\n [(1, 3, 0), (0, 2, 0), (0, 1, 2), (0, 0, 4)]\n sage: KP([[4, 2], [5, 3, 1]]).conormal_cells(2)\n []\n sage: KP = KleshchevPartitions(3, [0,1], convention="right restricted")\n sage: KP([[4, 2], [5, 3, 1]]).conormal_cells(0)\n [(1, 0, 5), (1, 1, 3), (1, 2, 1)]\n ' conormals = defaultdict(list) carry = defaultdict(int) part_lens = [len(part) for part in self] KP = self.parent() if (KP._convention[0] == 'L'): rows = [(k, r) for (k, ell) in enumerate(part_lens) for r in range((ell + 1))] else: rows = [(k, r) for (k, ell) in reversed(list(enumerate(part_lens))) for r in range((ell + 1))] if (KP._convention[1] == 'G'): rows.reverse() for row in rows: (k, r) = row if (r == part_lens[k]): res = (KP._multicharge[k] - r) if (carry[res] == 0): conormals[res].append((k, r, 0)) else: carry[res] += 1 else: part = self[k] res = (KP._multicharge[k] + ((part[r] - r) - 1)) if ((r == (part_lens[k] - 1)) or (part[r] > part[(r + 1)])): carry[res] -= 1 if ((r == 0) or (part[(r - 1)] > part[r])): if (carry[(res + 1)] == 0): conormals[(res + 1)].append((k, r, part[r])) else: carry[(res + 1)] += 1 if (i is None): return dict(conormals) return conormals[i] def cogood_cells(self, i=None): '\n Return a list of the cells of the partition that are cogood.\n\n The cogood `i`-cell is the \'last\' conormal `i`-cell. As with the\n conormal cells we can choose to read either up or down the partition\n as specified by :meth:`~KleshchevPartitions.convention`.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of cogood cells\n is returned, which gives the cogood cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1])\n sage: pt = KP([[4, 2], [5, 3, 1]])\n sage: pt.cogood_cells()\n {0: (1, 2, 1), 1: (1, 3, 0)}\n sage: pt.cogood_cells(0)\n (1, 2, 1)\n sage: KP = KleshchevPartitions(4, [0,1], convention="left regular")\n sage: pt = KP([[5, 2, 2], [6, 1, 1]])\n sage: pt.cogood_cells()\n {1: (0, 0, 5), 2: (1, 3, 0)}\n sage: pt.cogood_cells(0) is None\n True\n sage: pt.cogood_cells(1) is None\n False\n ' conormal_cells = self.conormal_cells(i) if (i is None): return {j: conormal_cells[j][(- 1)] for j in conormal_cells} elif (not conormal_cells): return None return conormal_cells[(- 1)] def normal_cells(self, i=None): '\n Return a dictionary of the removable cells of the partition that\n are normal.\n\n Following [Kle1995]_, the *normal* cells are computed by\n reading up (or down) the rows of the partition and marking all\n of the addable and removable cells of `e`-residue `i` and then\n recursively removing all adjacent pairs of removable and\n addable cells (in that order) from this list. The removable\n `i`-cells that remain at the end of the this process are the\n normal `i`-cells.\n\n When computing normal cells you can either read the cells in order\n from top to bottom (this corresponds to labeling the simple modules\n of the symmetric group by regular partitions) or from bottom to top\n (corresponding to labeling the simples by restricted partitions).\n By default we read down the partition but this can be changed by\n setting ``convention = \'RS\'``.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of normal cells\n is returned, which gives the normal cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1], convention="left restricted")\n sage: KP([[4, 2], [5, 3, 1]]).normal_cells()\n {2: [(1, 0, 4), (1, 1, 2), (1, 2, 0)]}\n sage: KP([[4, 2], [5, 3, 1]]).normal_cells(1)\n []\n sage: KP = KleshchevPartitions(3, [0,1], convention="left regular")\n sage: KP([[4, 2], [5, 3, 1]]).normal_cells()\n {0: [(0, 1, 1), (0, 0, 3)], 2: [(1, 2, 0), (1, 1, 2), (1, 0, 4)]}\n sage: KP = KleshchevPartitions(3, [0,1], convention="right regular")\n sage: KP([[4, 2], [5, 3, 1]]).normal_cells()\n {2: [(1, 2, 0), (1, 1, 2), (1, 0, 4)]}\n sage: KP = KleshchevPartitions(3, [0,1], convention="right restricted")\n sage: KP([[4, 2], [5, 3, 1]]).normal_cells()\n {0: [(0, 0, 3), (0, 1, 1)], 2: [(1, 0, 4), (1, 1, 2), (1, 2, 0)]}\n ' normals = defaultdict(list) carry = defaultdict(int) part_lens = [len(part) for part in self] KP = self.parent() if (KP._convention[0] == 'L'): rows = [(k, r) for (k, ell) in enumerate(part_lens) for r in range((ell + 1))] else: rows = [(k, r) for (k, ell) in reversed(list(enumerate(part_lens))) for r in range((ell + 1))] if (KP._convention[1] == 'S'): rows.reverse() for row in rows: (k, r) = row if (r == part_lens[k]): carry[(KP._multicharge[k] - r)] += 1 else: part = self[k] res = (KP._multicharge[k] + ((part[r] - r) - 1)) if ((r == (part_lens[k] - 1)) or (part[r] > part[(r + 1)])): if (carry[res] == 0): normals[res].insert(0, (k, r, (part[r] - 1))) else: carry[res] -= 1 if ((r == 0) or (part[(r - 1)] > part[r])): carry[(res + 1)] += 1 if (i is None): return dict(normals) return normals[i] def good_cells(self, i=None): '\n Return a list of the cells of the partition tuple which are good.\n\n The good `i`-cell is the \'first\' normal `i`-cell. As with the normal\n cells we can choose to read either up or down the partition as specified\n by :meth:`~KleshchevPartitions.convention`.\n\n INPUT:\n\n - ``i`` -- (optional) a residue\n\n OUTPUT:\n\n If no residue ``i`` is specified then a dictionary of good cells\n is returned, which gives the good cells for ``0 <= i < e``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1])\n sage: pt = KP([[4, 2], [5, 3, 1]])\n sage: pt.good_cells()\n {2: (1, 0, 4)}\n sage: pt.good_cells(2)\n (1, 0, 4)\n sage: KP = KleshchevPartitions(4, [0,1], convention="left regular")\n sage: pt = KP([[5, 2, 2], [6, 2, 1]])\n sage: pt.good_cells()\n {0: (0, 0, 4), 2: (1, 0, 5), 3: (0, 2, 1)}\n sage: pt.good_cells(1) is None\n True\n ' normal_cells = self.normal_cells(i) if (i is None): return {j: normal_cells[j][0] for j in normal_cells} elif (not normal_cells): return None return normal_cells[0] def good_residue_sequence(self): '\n Return a sequence of good nodes from the empty partition to ``self``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1])\n sage: KP([[4, 2], [5, 3, 1]]).good_residue_sequence()\n [0, 1, 2, 1, 2, 0, 1, 0, 2, 2, 0, 1, 0, 2, 2]\n ' if (self.size() == 0): return [] good_cells = self.good_cells() assert good_cells res = sorted(good_cells.keys())[0] (k, r, c) = good_cells[res] good_seq = type(self)(self.parent(), self.remove_cell(k, r, c)).good_residue_sequence() good_seq.append(self.parent()._index_set(res)) return good_seq def good_cell_sequence(self): '\n Return a sequence of good nodes from the empty partition to ``self``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3,[0,1])\n sage: KP([[4, 2], [5, 3, 1]]).good_cell_sequence()\n [(0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), (0, 1, 0),\n (1, 1, 0), (1, 1, 1), (1, 0, 2), (1, 2, 0), (0, 0, 2),\n (0, 1, 1), (1, 0, 3), (0, 0, 3), (1, 1, 2), (1, 0, 4)]\n ' if (self.size() == 0): return [] good_cells = self.good_cells() assert good_cells cell = good_cells[sorted(good_cells)[0]] good_seq = type(self)(self.parent(), self.remove_cell(*cell)).good_cell_sequence() good_seq.append(cell) return good_seq def mullineux_conjugate(self): '\n Return the partition that is the Mullineux conjugate of ``self``.\n\n It follows from results in [Kle1996]_ [Bru1998]_ that if `\\nu` is the\n Mullineux conjugate of the Kleshchev partition tuple `\\mu` then the\n simple module `D^\\nu =(D^\\mu)^{\\text{sgn}}` is obtained from `D^\\mu`\n by twisting by the `\\text{sgn}`-automorphism with is the Hecke algebra\n analogue of tensoring with the one dimensional sign representation.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(3, [0,1])\n sage: mc = KP([[4, 2], [5, 3, 1]]).mullineux_conjugate(); mc\n ([2, 2, 1, 1], [3, 2, 2, 1, 1])\n sage: mc.parent()\n Kleshchev partitions with e=3 and multicharge=(0,2)\n\n ' P = self.parent() if (self.size() == 0): size = None if isinstance(P, KleshchevPartitions_size): size = P._size KP = KleshchevPartitions(P._e, [(- c) for c in P._multicharge], size=size, convention=P._convention) return KP.element_class(KP, ([[]] * P._level)) good_cells = self.good_cells() assert good_cells (k, r, c) = sorted(good_cells.values())[0] mu = P.element_class(P, self.remove_cell(k, r, c)).mullineux_conjugate() KP = mu.parent() return KP.element_class(KP, mu.add_cell(*mu.cogood_cells(((r - c) - self.parent()._multicharge[k])))) def is_regular(self): '\n Return ``True`` if ``self`` is a `e`-regular partition tuple.\n\n A partition tuple is `e`-regular if we can get to the\n empty partition tuple by successively removing a sequence\n of good cells in the down direction.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(2, [0,2], convention="right restricted")\n sage: KP([[3,2,1], [2,1,1]]).is_regular()\n False\n sage: KP = KleshchevPartitions(4, [0,2], convention="right restricted")\n sage: KP([[3,2,1], [2,1,1]]).is_regular()\n True\n sage: KP([[], []]).is_regular()\n True\n ' if (self.size() == 0): return True KP = self.parent() return _is_regular(self.to_list(), KP._multicharge, KP._convention) def is_restricted(self): '\n Return ``True`` if ``self`` is an `e`-restricted partition tuple.\n\n A partition tuple is `e`-restricted if we can get to the\n empty partition tuple by successively removing a sequence\n of good cells in the up direction.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(2, [0,2], convention="left regular")\n sage: KP([[3,2,1], [3,1]]).is_restricted()\n False\n sage: KP = KleshchevPartitions(3, [0,2], convention="left regular")\n sage: KP([[3,2,1], [3,1]]).is_restricted()\n True\n sage: KP([[], []]).is_restricted()\n True\n ' if (self.size() == 0): return True KP = self.parent() return _is_restricted(self.to_list(), KP._multicharge, KP._convention)
class KleshchevCrystalMixin(): '\n Mixin class for the crystal structure of a Kleshchev partition.\n ' def epsilon(self, i): '\n Return the Kashiwara crystal operator `\\varepsilon_i` applied to ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: [x.epsilon(i) for i in C.index_set()]\n [0, 3, 0]\n ' return len(self.normal_cells(i)) def phi(self, i): '\n Return the Kashiwara crystal operator `\\varphi_i` applied to ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: [x.phi(i) for i in C.index_set()]\n [3, 2, 0]\n ' return len(self.conormal_cells(i)) def Epsilon(self): '\n Return `\\varepsilon` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: x.Epsilon()\n 3*Lambda[1]\n ' P = self.parent() WLR = P.weight_lattice_realization() La = WLR.fundamental_weights() n = self.normal_cells() return WLR.sum(((len(n[i]) * La[i]) for i in P.index_set() if (i in n))) def Phi(self): '\n Return `\\phi` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: x.Phi()\n 3*Lambda[0] + 2*Lambda[1]\n ' P = self.parent() WLR = P.weight_lattice_realization() La = WLR.fundamental_weights() c = self.conormal_cells() return WLR.sum(((len(c[i]) * La[i]) for i in P.index_set() if (i in c))) def weight(self): '\n Return the weight of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1], [3,2,1,1]])\n sage: x.weight()\n 3*Lambda[0] - Lambda[1] - 5*delta\n sage: x.Phi() - x.Epsilon()\n 3*Lambda[0] - Lambda[1]\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="right regular")\n sage: y = C([[5,1,1], [4,2,2,1,1]])\n sage: y.weight()\n 6*Lambda[0] - 4*Lambda[1] - 4*delta\n sage: y.Phi() - y.Epsilon()\n 6*Lambda[0] - 4*Lambda[1]\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: y = C([[5,1,1], [4,2,2,1,1]])\n sage: y.weight()\n 6*Lambda[0] - 4*Lambda[1] - 4*delta\n sage: y.Phi() - y.Epsilon()\n 6*Lambda[0] - 4*Lambda[1]\n ' WLR = self.parent().weight_lattice_realization() alpha = WLR.simple_roots() La = WLR.fundamental_weights() r = self.parent()._multicharge wt = WLR.sum((La[ZZ(x)] for x in r)) return (wt - WLR.sum((alpha[self.content(*c, multicharge=r)] for c in self.cells())))
class KleshchevPartitionCrystal(KleshchevPartition, KleshchevCrystalMixin): '\n Kleshchev partition with the crystal structure.\n ' 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: C = crystals.KleshchevPartitions(3, convention="left regular")\n sage: x = C([5,4,1])\n sage: x.e(0)\n sage: x.e(1)\n [5, 4]\n ' P = self.parent() cell = self.good_cells(i) if (cell is None): return None (r, _) = cell mu = list(self) mu[r] -= 1 return type(self)(P, mu) 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: C = crystals.KleshchevPartitions(3, convention="left regular")\n sage: x = C([5,4,1])\n sage: x.f(0)\n [5, 5, 1]\n sage: x.f(1)\n sage: x.f(2)\n [5, 4, 2]\n ' P = self.parent() cell = self.cogood_cells(i) if (cell is None): return None (r, c) = cell mu = list(self) if (c == 0): mu.append(1) else: mu[r] += 1 return type(self)(P, mu)
class KleshchevPartitionTupleCrystal(KleshchevPartitionTuple, KleshchevCrystalMixin): '\n Kleshchev partition tuple with the crystal structure.\n ' 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: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: x.e(0)\n sage: x.e(1)\n ([5, 4, 1], [2, 2, 1, 1])\n ' P = self.parent() cell = self.good_cells(i) if (cell is None): return None (k, r, _) = cell mu = self.to_list() mu[k][r] -= 1 return type(self)(P, mu) 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: C = crystals.KleshchevPartitions(3, [0,2], convention="left regular")\n sage: x = C([[5,4,1],[3,2,1,1]])\n sage: x.f(0)\n ([5, 5, 1], [3, 2, 1, 1])\n sage: x.f(1)\n ([5, 4, 1], [3, 2, 2, 1])\n sage: x.f(2)\n ' P = self.parent() cell = self.cogood_cells(i) if (cell is None): return None (k, r, c) = cell mu = self.to_list() if (c == 0): mu[k].append(1) else: mu[k][r] += 1 return type(self)(P, mu)
class KleshchevPartitions(PartitionTuples): '\n Kleshchev partitions\n\n A partition (tuple) `\\mu` is Kleshchev if it can be recursively\n obtained by adding a sequence of good nodes to the empty\n :class:`PartitionTuple` of the same :meth:`~PartitionTuple.level`\n and multicharge.\n\n There are four different conventions that are used in the literature for\n Kleshchev partitions, depending on whether we read partitions from top\n to bottom (regular) or bottom to top (restricted) and whether we read\n partition tuples from left to right or right to left. All of these\n conventions are supported::\n\n sage: KleshchevPartitions(2, [0,0], size=2, convention=\'left regular\')[:]\n [([1], [1]), ([2], [])]\n sage: KleshchevPartitions(2, [0,0], size=2, convention=\'left restricted\')[:]\n [([1], [1]), ([], [1, 1])]\n sage: KleshchevPartitions(2, [0,0], size=2, convention=\'right regular\')[:]\n [([1], [1]), ([], [2])]\n sage: KleshchevPartitions(2, [0,0], size=2, convention=\'right restricted\')[:]\n [([1], [1]), ([1, 1], [])]\n\n By default, the ``left restricted`` convention is used. As a shorthand,\n ``LG``, ``LS``, ``RG`` and ``RS``, respectively, can be used to specify\n the ``convention``. With the ``left`` convention the partition tuples\n should be ordered with the most dominant partitions in the partition\n tuple on the left and with the ``right`` convention the most dominant\n partition is on the right.\n\n The :class:`~KleshchevPartitions` class will automatically convert\n between these four different conventions::\n\n sage: KPlg = KleshchevPartitions(2, [0,0], size=2, convention=\'left regular\')\n sage: KPls = KleshchevPartitions(2, [0,0], size=2, convention=\'left restricted\')\n sage: [KPlg(mu) for mu in KPls]\n [([1], [1]), ([2], [])]\n\n EXAMPLES::\n\n sage: sorted(KleshchevPartitions(5,[3,2,1],1, convention=\'RS\'))\n [([], [], [1]), ([], [1], []), ([1], [], [])]\n sage: sorted(KleshchevPartitions(5, [3,2,1], 1, convention=\'LS\'))\n [([], [], [1]), ([], [1], []), ([1], [], [])]\n sage: sorted(KleshchevPartitions(5, [3,2,1], 3))\n [([], [], [1, 1, 1]),\n ([], [], [2, 1]),\n ([], [], [3]),\n ([], [1], [1, 1]),\n ([], [1], [2]),\n ([], [1, 1], [1]),\n ([], [2], [1]),\n ([], [3], []),\n ([1], [], [1, 1]),\n ([1], [], [2]),\n ([1], [1], [1]),\n ([1], [2], []),\n ([1, 1], [1], []),\n ([2], [], [1]),\n ([2], [1], []),\n ([3], [], [])]\n sage: sorted(KleshchevPartitions(5, [3,2,1], 3, convention="left regular"))\n [([], [], [1, 1, 1]),\n ([], [1], [1, 1]),\n ([], [1], [2]),\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, 1], [], [1]),\n ([1, 1], [1], []),\n ([1, 1, 1], [], []),\n ([2], [], [1]),\n ([2], [1], []),\n ([2, 1], [], []),\n ([3], [], [])]\n\n REFERENCES:\n\n - [AM2000]_\n - [Ariki2001]_\n - [BK2009]_\n - [Kle2009]_\n ' @staticmethod def __classcall_private__(cls, e, multicharge=(0,), size=None, convention='left restricted'): "\n This is a factory class which returns the appropriate parent based on\n the values of `level` and `size`.\n\n EXAMPLES::\n\n sage: sorted(KleshchevPartitions(5, [3,2,1], 1, convention='RS'))\n [([], [], [1]), ([], [1], []), ([1], [], [])]\n sage: sorted(KleshchevPartitions(5, [3,2,1], 1, convention='LS'))\n [([], [], [1]), ([], [1], []), ([1], [], [])]\n " if ((size is None) and (multicharge in ZZ)): size = ZZ(multicharge) multicharge = (0,) I = IntegerModRing(e) multicharge = tuple([I(x) for x in multicharge]) convention = convention.upper() if ('S' in convention): convention = (convention[0] + 'S') elif ('G' in convention): convention = (convention[0] + 'G') if (convention not in ['RG', 'LG', 'RS', 'LS']): raise ValueError('invalid convention') if (size is None): return KleshchevPartitions_all(e, multicharge, convention) return KleshchevPartitions_size(e, multicharge, size, convention) def multicharge(self): "\n Return the multicharge of ``self``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(6, [2])\n sage: KP.multicharge()\n (2,)\n sage: KP = KleshchevPartitions(5, [3,0,1], 1, convention='LS')\n sage: KP.multicharge()\n (3, 0, 1)\n " return self._multicharge def convention(self): '\n Return the convention of ``self``.\n\n EXAMPLES::\n\n sage: KP = KleshchevPartitions(4)\n sage: KP.convention()\n \'restricted\'\n sage: KP = KleshchevPartitions(6, [4], 3, convention="right regular")\n sage: KP.convention()\n \'regular\'\n sage: KP = KleshchevPartitions(5, [3,0,1], 1)\n sage: KP.convention()\n \'left restricted\'\n sage: KP = KleshchevPartitions(5, [3,0,1], 1, convention=\'right regular\')\n sage: KP.convention()\n \'right regular\'\n ' if (self._convention[1] == 'S'): convention = 'restricted' else: convention = 'regular' if (self._level == 1): return convention if (self._convention[0] == 'R'): return ('right ' + convention) return ('left ' + convention) def _element_constructor_(self, mu): "\n Return ``mu`` as an element of :class:`~KleshchevPartitions`, or\n or raise an error if ``mu`` is not a Kleshchev partition (tuple).\n\n The main purpose of the element constructor code is to allow automatic\n conversion between the four possible conventions for Kleshchev\n partitions.\n\n EXAMPLES::\n\n sage: KPlg = KleshchevPartitions(2, [0,0], size=2, convention='left regular')\n sage: KPls = KleshchevPartitions(2, [0,0], size=2, convention='left restricted')\n sage: [KPlg(mu) for mu in KPls] # indirect doc test\n [([1], [1]), ([2], [])]\n\n " if isinstance(mu, (KleshchevPartition, KleshchevPartitionTuple)): KPmu = mu.parent() if (KPmu == self): return mu if ((KPmu._level != self._level) or (KPmu._e != self._e)): raise ValueError(('%s is not an element of %s' % (mu, self))) if (KPmu._convention[1] != self._convention[1]): mu = [nu.conjugate() for nu in mu] if ((self._level > 1) and (KPmu._convention[0] == self._convention[0])): mu = mu[::(- 1)] return super()._element_constructor_(mu)
class KleshchevPartitions_all(KleshchevPartitions): '\n Class of all Kleshchev partitions.\n\n .. RUBRIC:: Crystal structure\n\n We consider type `A_{e-1}^{(1)}` crystals, and let `r = (r_i |\n r_i \\in \\ZZ / e \\ZZ)` be a finite sequence of length `k`, which\n is the *level*, and `\\lambda = \\sum_i \\Lambda_{r_i}`. We will\n model the highest weight `U_q(\\mathfrak{g})`-crystal `B(\\lambda)`\n by a particular subset of partition tuples of level `k`.\n\n Consider a partition tuple `\\mu` with multicharge `r`.\n We define `e_i(\\mu)` as the partition tuple obtained after the\n deletion of the `i`-:meth:`good cell\n <~sage.combinat.partition_kleshchev.KleshchevPartitionTuple.good_cell>`\n to `\\mu` and `0` if there is no `i`-good cell. We define `f_i(\\mu)` as\n the partition tuple obtained by the addition of the `i`-:meth:`cogood cell\n <~sage.combinat.partition_kleshchev.KleshchevPartitionTuple.cogood_cell>`\n to `\\mu` and `0` if there is no `i`-good cell.\n\n The crystal `B(\\lambda)` is the crystal generated by the empty\n partition tuple. We can compute the weight of an element `\\mu` by taking\n `\\lambda - \\sum_{i=0}^n c_i \\alpha_i` where `c_i` is the number of cells\n of `n`-residue `i` in `\\mu`. Partition tuples in the crystal are known\n as *Kleshchev partitions*.\n\n .. NOTE::\n\n We can describe normal (not restricted) Kleshchev partition tuples\n in `B(\\lambda)` as partition tuples `\\mu` such that\n `\\mu^{(t)}_{r_t - r_{t+1} + x} < \\mu^{(t+1)}_x`\n for all `x \\geq 1` and `1 \\leq t \\leq k - 1`.\n\n INPUT:\n\n - ``e`` -- for type `A_{e-1}^{(1)}` or `0`\n - ``multicharge`` -- the multicharge sequence `r`\n - ``convention`` -- (default: ``\'LS\'``) the reading convention\n\n EXAMPLES:\n\n We first do an example of a level 1 crystal::\n\n sage: C = crystals.KleshchevPartitions(3, [0], convention="left restricted")\n sage: C\n Kleshchev partitions with e=3\n sage: mg = C.highest_weight_vector()\n sage: mg\n []\n sage: mg.f(0)\n [1]\n sage: mg.f(1)\n sage: mg.f(2)\n sage: mg.f_string([0,2,1,0])\n [1, 1, 1, 1]\n sage: mg.f_string([0,1,2,0])\n [2, 2]\n sage: GC = C.subcrystal(max_depth=5).digraph()\n sage: B = crystals.LSPaths([\'A\',2,1], [1,0,0])\n sage: GB = B.subcrystal(max_depth=5).digraph()\n sage: GC.is_isomorphic(GB, edge_labels=True)\n True\n\n Now a higher level crystal::\n\n sage: C = crystals.KleshchevPartitions(3, [0,2], convention="right restricted")\n sage: mg = C.highest_weight_vector()\n sage: mg\n ([], [])\n sage: mg.f(0)\n ([1], [])\n sage: mg.f(2)\n ([], [1])\n sage: mg.f_string([0,1,2,0])\n ([2, 2], [])\n sage: mg.f_string([0,2,1,0])\n ([1, 1, 1, 1], [])\n sage: mg.f_string([2,0,1,0])\n ([2], [2])\n sage: GC = C.subcrystal(max_depth=5).digraph()\n sage: B = crystals.LSPaths([\'A\',2,1], [1,0,1])\n sage: GB = B.subcrystal(max_depth=5).digraph()\n sage: GC.is_isomorphic(GB, edge_labels=True)\n True\n\n The ordering of the residues gives a different representation of the\n higher level crystals (but it is still isomorphic)::\n\n sage: C2 = crystals.KleshchevPartitions(3, [2,0], convention="right restricted")\n sage: mg2 = C2.highest_weight_vector()\n sage: mg2.f_string([0,1,2,0])\n ([2], [2])\n sage: mg2.f_string([0,2,1,0])\n ([1, 1, 1], [1])\n sage: mg2.f_string([2,0,1,0])\n ([2, 1], [1])\n sage: GC2 = C2.subcrystal(max_depth=5).digraph()\n sage: GC.is_isomorphic(GC2, edge_labels=True)\n True\n\n TESTS:\n\n We check that all conventions give isomorphic crystals::\n\n sage: CLS = crystals.KleshchevPartitions(3, [2,0], convention="left restricted")\n sage: CRS = crystals.KleshchevPartitions(3, [2,0], convention="right restricted")\n sage: CLG = crystals.KleshchevPartitions(3, [2,0], convention="left regular")\n sage: CRG = crystals.KleshchevPartitions(3, [2,0], convention="right regular")\n sage: C = [CLS, CRS, CLG, CRG]\n sage: G = [B.subcrystal(max_depth=6).digraph() for B in C]\n sage: G[0].is_isomorphic(G[1], edge_labels=True)\n True\n sage: G[0].is_isomorphic(G[2], edge_labels=True)\n True\n sage: G[0].is_isomorphic(G[3], edge_labels=True)\n True\n\n REFERENCES:\n\n - [Ariki1996]_\n - [Ariki2001]_\n - [Tingley2007]_\n - [TingleyLN]_\n - [Vazirani2002]_\n ' def __init__(self, e, multicharge, convention): '\n Initializes ``self``.\n\n EXAMPLES::\n\n sage: K = KleshchevPartitions(4, [2])\n sage: TestSuite(K).run() # long time\n sage: K = KleshchevPartitions(4, [0,2,1])\n sage: TestSuite(K).run() # long time\n\n sage: K = KleshchevPartitions(0, [2])\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(0, [0,2,1])\n sage: TestSuite(K).run() # long time\n ' if ((e not in NN) or (e == 1)): raise ValueError('e must belong to {0,2,3,4,5,6,...}') if (e > 0): from sage.combinat.root_system.cartan_type import CartanType from sage.categories.highest_weight_crystals import HighestWeightCrystals from sage.categories.regular_crystals import RegularCrystals self._cartan_type = CartanType(['A', (e - 1), 1]) cat = (HighestWeightCrystals(), RegularCrystals().Infinite()) else: cat = InfiniteEnumeratedSets() self._level = len(multicharge) if (self._level == 1): self.Element = KleshchevPartitionCrystal self._element_constructor_ = getattr_from_other_class(self, Partitions, '_element_constructor_') else: self.Element = KleshchevPartitionTupleCrystal super().__init__(category=cat) self._e = e self._index_set = IntegerModRing(e) self._multicharge = multicharge self._convention = convention if (e > 0): if (self._level == 1): self.module_generators = (self.element_class(self, []),) else: self.module_generators = (self.element_class(self, ([[]] * self._level)),) def _repr_(self): '\n EXAMPLES::\n\n sage: KleshchevPartitions(4, [2])\n Kleshchev partitions with e=4\n sage: KleshchevPartitions(3,[0,0,0])\n Kleshchev partitions with e=3 and multicharge=(0,0,0)\n sage: KleshchevPartitions(3,[0,0,1])\n Kleshchev partitions with e=3 and multicharge=(0,0,1)\n ' if (self._level == 1): return ('Kleshchev partitions with e=%s' % self._e) return ('Kleshchev partitions with e=%s and multicharge=(%s)' % (self._e, ','.join((('%s' % m) for m in self._multicharge)))) def __contains__(self, mu): '\n Containment test for Kleshchev partitions.\n\n EXAMPLES::\n\n sage: PartitionTuple([[3,2],[2]]) in KleshchevPartitions(2, [0,0], 7)\n False\n sage: PartitionTuple([[],[2,1],[3,2]]) in KleshchevPartitions(5, [0,0,1], 7)\n False\n sage: PartitionTuple([[],[2,1],[3,2]]) in KleshchevPartitions(5, [0,1,1], 7)\n False\n sage: PartitionTuple([[],[2,1],[3,2]]) in KleshchevPartitions(5, [0,1,1], 8)\n True\n sage: all(mu in PartitionTuples(3,8) for mu in KleshchevPartitions(2, [0,0,0], 8))\n True\n ' if isinstance(mu, (KleshchevPartition, KleshchevPartitionTuple)): if (mu.level() != self._level): return False mu = self.element_class(self, list(mu)) if (self._convention[1] == 'G'): return mu.is_regular() return mu.is_restricted() try: mu = self.element_class(self, mu) except ValueError: return False return (mu in self) def __iter__(self): "\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = iter(KleshchevPartitions(2))\n sage: [next(it) for _ in range(10)]\n [[], [1], [1, 1], [2, 1], [1, 1, 1], [2, 1, 1],\n [1, 1, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: it = iter(KleshchevPartitions(2, convention='LG'))\n sage: [next(it) for _ in range(10)]\n [[], [1], [2], [3], [2, 1], [4], [3, 1], [5], [4, 1], [3, 2]]\n\n sage: it = iter(KleshchevPartitions(2, [0,1], convention='LS'))\n sage: [next(it) for _ in range(10)]\n [([], []),\n ([1], []),\n ([], [1]),\n ([1], [1]),\n ([], [1, 1]),\n ([1, 1], [1]),\n ([1], [1, 1]),\n ([], [2, 1]),\n ([], [1, 1, 1]),\n ([2, 1], [1])]\n sage: it = iter(KleshchevPartitions(2, [0,1], convention='RS'))\n sage: [next(it) for _ in range(10)]\n [([], []),\n ([1], []),\n ([], [1]),\n ([1, 1], []),\n ([1], [1]),\n ([2, 1], []),\n ([1, 1, 1], []),\n ([1, 1], [1]),\n ([1], [1, 1]),\n ([2, 1, 1], [])]\n sage: it = iter(KleshchevPartitions(2, [0,1], convention='LG'))\n sage: [next(it) for _ in range(10)]\n [([], []),\n ([1], []),\n ([], [1]),\n ([2], []),\n ([1], [1]),\n ([3], []),\n ([2, 1], []),\n ([2], [1]),\n ([1], [2]),\n ([4], [])]\n sage: it = iter(KleshchevPartitions(2, [0,1], convention='RG'))\n sage: [next(it) for _ in range(10)]\n [([], []),\n ([1], []),\n ([], [1]),\n ([1], [1]),\n ([], [2]),\n ([2], [1]),\n ([1], [2]),\n ([], [3]),\n ([], [2, 1]),\n ([2, 1], [1])]\n\n sage: it = iter(KleshchevPartitions(3, [0,1,2]))\n sage: [next(it) for _ in range(10)]\n [([], [], []), ([1], [], []), ([], [1], []), ([], [], [1]),\n ([1], [1], []), ([1], [], [1]), ([], [1, 1], []),\n ([], [1], [1]), ([], [], [2]), ([], [], [1, 1])]\n " if (self._level == 1): if (self._e == 0): P = Partitions() elif (self._convention[1] == 'G'): P = Partitions(regular=self._e) else: P = Partitions(restricted=self._e) for mu in P: (yield self.element_class(self, list(mu))) else: next_level = [self.element_class(self, ([[]] * len(self._multicharge)))] while True: cur = next_level next_level = [] for mu in cur: (yield mu) mu_list = mu.to_list() for cell in sorted(mu.cogood_cells().values()): data = [list(p) for p in mu_list] (k, r, c) = cell if (c == 0): data[k].append(1) else: data[k][r] += 1 nu = self.element_class(self, data) good_cells = nu.good_cells().values() if (self._convention[1] == 'S'): if all(((cell >= c) for c in good_cells)): next_level.append(nu) elif all(((cell <= c) for c in good_cells)): next_level.append(nu) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: KleshchevPartitions(3, [0,0,0,0], size=4).an_element()\n ([1], [1], [1], [1])\n ' return self[12]
class KleshchevPartitions_size(KleshchevPartitions): '\n Kleshchev partitions of a fixed size.\n ' def __init__(self, e, multicharge=(0,), size=0, convention='RS'): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: K = KleshchevPartitions(4, 2)\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(4, 4, convention='left regular')\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(4, 4, convention='left restricted')\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(4, [0,2,1], 4, convention='left regular')\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(0, 2, convention='right restricted')\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(0, [0,2,1], 4, convention='left restricted')\n sage: TestSuite(K).run()\n sage: K = KleshchevPartitions(0, [0,2,1], 4, convention='left regular')\n sage: TestSuite(K).run()\n\n We verify that we obtain the same size for all conventions\n and that the result is equal to the number of elements in\n the crystal at the corresponding depth::\n\n sage: B = crystals.LSPaths(['A',2,1], [1,0,1])\n sage: nd4 = (B.subcrystal(max_depth=4).cardinality()\n ....: - B.subcrystal(max_depth=3).cardinality())\n sage: K = KleshchevPartitions(3, [0,2], 4, convention='RS')\n sage: K.cardinality() == nd4\n True\n sage: K = KleshchevPartitions(3, [0,2], 4, convention='RG')\n sage: K.cardinality() == nd4\n True\n sage: K = KleshchevPartitions(3, [0,2], 4, convention='LS')\n sage: K.cardinality() == nd4\n True\n sage: K = KleshchevPartitions(3, [0,2], 4, convention='LG')\n sage: K.cardinality() == nd4\n True\n " self._level = len(multicharge) if (self._level == 1): self.Element = KleshchevPartition self._element_constructor_ = getattr_from_other_class(self, Partitions, '_element_constructor_') else: self.Element = KleshchevPartitionTuple super().__init__(category=FiniteEnumeratedSets()) self._size = size self._e = e self._I = IntegerModRing(e) self._multicharge = tuple((self._I(m) for m in multicharge)) self._convention = convention def _repr_(self): '\n EXAMPLES::\n\n sage: KleshchevPartitions(4, [0,0], 3)\n Kleshchev partitions with e=4 and multicharge=(0,0) and size 3\n ' if (self._level == 1): return ('Kleshchev partitions with e=%s and size %s' % (self._e, self._size)) return ('Kleshchev partitions with e=%s and multicharge=(%s) and size %s' % (self._e, ','.join((('%s' % m) for m in self._multicharge)), self._size)) def __contains__(self, mu): "\n Check if ``mu`` is in ``self``.\n\n TESTS::\n\n sage: PartitionTuple([[3,2],[2]]) in KleshchevPartitions(2,[0,0],7)\n False\n sage: PartitionTuple([[3,2],[],[],[],[2]]) in KleshchevPartitions(5,[0,0,0,0,0],7)\n False\n sage: PartitionTuple([[2,1],[],[1,1],[],[2]]) in KleshchevPartitions(5,[0,0,0,0,0],7, convention='RG')\n False\n sage: PartitionTuple([[2,1],[],[1,1],[],[3]]) in KleshchevPartitions(2,[0,0,0,0,0],9, convention='RS')\n False\n sage: all(mu in PartitionTuples(3,8) for mu in KleshchevPartitions(0,[0,0,0],8))\n True\n " if isinstance(mu, (KleshchevPartition, KleshchevPartitionTuple)): if (not ((mu.level() == self._level) and (mu.size() == self._size))): return False mu = self.element_class(self, list(mu)) if (self._convention[1] == 'G'): return mu.is_regular() return mu.is_restricted() try: mu = self.element_class(self, mu) except ValueError: return False return (mu in self) def __iter__level_one(self): '\n Iterate over all Kleshchev partitions of level one and a fixed size.\n\n EXAMPLES::\n\n sage: KleshchevPartitions(2,0)[:] # indirect doctest\n [[]]\n sage: KleshchevPartitions(2,1)[:] # indirect doctest\n [[1]]\n sage: KleshchevPartitions(2,2)[:] # indirect doctest\n [[1, 1]]\n sage: KleshchevPartitions(3,2)[:] # indirect doctest\n [[2], [1, 1]]\n ' if (self._size == 0): (yield self.element_class(self, [])) else: if (self._e == 0): P = Partitions(self._size) elif (self._convention[1] == 'G'): P = Partitions(self._size, regular=self._e) else: P = Partitions(self._size, restricted=self._e) for mu in P: (yield self.element_class(self, list(mu))) def __iter__higher_levels(self): '\n Iterate over all KleshchevPartitions of a fixed level greater than 1\n and a fixed size.\n\n EXAMPLES::\n\n sage: KleshchevPartitions(2,[0,0],1)[:] # indirect doctest\n [([], [1])]\n sage: KleshchevPartitions(2,[0,0],2)[:] # indirect doctest\n [([1], [1]), ([], [1, 1])]\n sage: KleshchevPartitions(3,[0,0],2)[:] # indirect doctest\n [([1], [1]), ([], [2]), ([], [1, 1])]\n ' if (self._size == 0): (yield self.element_class(self, ([[]] * len(self._multicharge)))) return for mu in KleshchevPartitions_size(self._e, self._multicharge, size=(self._size - 1), convention=self._convention): mu_list = mu.to_list() for cell in mu.cogood_cells().values(): data = [list(p) for p in mu_list] (k, r, c) = cell if (c == 0): data[k].append(1) else: data[k][r] += 1 nu = self.element_class(self, data) good_cells = nu.good_cells().values() if (self._convention[1] == 'S'): if all(((cell >= c) for c in good_cells)): (yield nu) elif all(((cell <= c) for c in good_cells)): (yield nu) @lazy_attribute def __iter__(self): "\n Wrapper to return the correct iterator which is different for\n :class:`Partitions` (level 1) and for :class:PartitionTuples`\n (higher levels).\n\n EXAMPLES::\n\n sage: KleshchevPartitions(3, 3, convention='RS')[:]\n [[2, 1], [1, 1, 1]]\n sage: KleshchevPartitions(3, 3, convention='RG')[:]\n [[3], [2, 1]]\n sage: KleshchevPartitions(3, [0], 3)[:]\n [[2, 1], [1, 1, 1]]\n sage: KleshchevPartitions(3, [0,0], 3)[:]\n [([1], [2]), ([1], [1, 1]), ([], [2, 1]), ([], [1, 1, 1])]\n sage: KleshchevPartitions(2, [0,1], size=0)[:]\n [([], [])]\n sage: KleshchevPartitions(2, [0,1], size=1)[:]\n [([1], []), ([], [1])]\n sage: KleshchevPartitions(2, [0,1], size=2)[:]\n [([1], [1]), ([], [1, 1])]\n sage: KleshchevPartitions(3, [0,1,2], size=2)[:]\n [([1], [1], []), ([1], [], [1]), ([], [1, 1], []),\n ([], [1], [1]), ([], [], [2]), ([], [], [1, 1])]\n " if (self.level() == 1): return self.__iter__level_one return self.__iter__higher_levels def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: KleshchevPartitions(4, [0,0,0,0], 4).an_element()\n ([1], [1], [1], [1])\n sage: KleshchevPartitions(4, [2], 4).an_element()\n [3, 1]\n ' return self[0] Element = KleshchevPartitionTuple
def _a_good_cell(kpt, multicharge, convention): "\n Return a good cell from ``kpt`` considered as a Kleshchev partition\n with ``multicharge`` under ``convention``.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_kleshchev import _a_good_cell\n sage: I2 = IntegerModRing(2)\n sage: _a_good_cell([[3,2,1], [3,1,1]], [I2(0),I2(2)], 'RS')\n (1, 2, 0)\n sage: _a_good_cell([[3,1,1], [3,2]], [I2(0),I2(2)], 'LG')\n (1, 1, 1)\n sage: I3 = IntegerModRing(3)\n sage: _a_good_cell([[3,2,1], [3,1,1]], [I3(0),I3(2)], 'RS')\n (0, 2, 0)\n sage: _a_good_cell([[3,1,1], [3,2]], [I3(0),I3(2)], 'LG')\n (1, 0, 2)\n sage: _a_good_cell([[], []], [I3(0),I3(2)], 'RS') is None\n True\n sage: _a_good_cell([[1,1], []], [I3(0),I3(2)], 'LS') is None\n True\n " carry = defaultdict(int) ret = None if (convention[0] == 'L'): rows = [(k, r) for (k, part) in enumerate(kpt) for r in range((len(part) + 1))] else: rows = [(k, r) for (k, part) in reversed(list(enumerate(kpt))) for r in range((len(part) + 1))] if (convention[1] == 'S'): rows.reverse() for row in rows: (k, r) = row if (r == len(kpt[k])): carry[(multicharge[k] - r)] += 1 else: res = (((multicharge[k] + kpt[k][r]) - r) - 1) if ((r == (len(kpt[k]) - 1)) or (kpt[k][r] > kpt[k][(r + 1)])): if (carry[res] == 0): ret = (k, r, (kpt[k][r] - 1)) else: carry[res] -= 1 if ((r == 0) or (kpt[k][(r - 1)] > kpt[k][r])): carry[(res + 1)] += 1 return ret
def _is_regular(kpt, multicharge, convention): "\n Return ``True`` if ``kpt`` is a ``multicharge``-regular\n Kleshchev partition.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_kleshchev import _is_regular\n sage: I2 = IntegerModRing(2)\n sage: _is_regular([[3,1,1], [3,2]], [I2(0),I2(2)], 'LS')\n False\n sage: I3 = IntegerModRing(3)\n sage: _is_regular([[3,1,1], [3,2]], [I3(0),I3(2)], 'LS')\n True\n sage: _is_regular([[], []], [I3(0),I3(2)], 'LS')\n True\n " if all(((part == []) for part in kpt)): return True convention = (convention[0] + 'G') cell = _a_good_cell(kpt, multicharge, convention) while (cell is not None): (k, r, _) = cell if (kpt[k][r] == 1): kpt[k].pop() else: kpt[k][r] -= 1 cell = _a_good_cell(kpt, multicharge, convention) return all(((part == []) for part in kpt))
def _is_restricted(kpt, multicharge, convention): "\n Return ``True`` if ``kpt`` is an ``multicharge``-restricted\n Kleshchev partition.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_kleshchev import _is_restricted\n sage: I2 = IntegerModRing(2)\n sage: _is_restricted([[3,2,1], [3,1,1]], [I2(0),I2(2)], 'RG')\n False\n sage: I3 = IntegerModRing(3)\n sage: _is_restricted([[3,2,1], [3,1,1]], [I3(0),I3(2)], 'RG')\n True\n sage: _is_restricted([[], []], [I3(0),I3(2)], 'RG')\n True\n " if all(((not part) for part in kpt)): return True convention = (convention[0] + 'S') cell = _a_good_cell(kpt, multicharge, convention) while (cell is not None): (k, r, _) = cell if (kpt[k][r] == 1): kpt[k].pop() else: kpt[k][r] -= 1 cell = _a_good_cell(kpt, multicharge, convention) return all(((not part) for part in kpt))
class ShiftingSequenceSpace(Singleton, Parent): "\n A helper for :class:`ShiftingOperatorAlgebra` that contains all\n tuples with entries in `\\ZZ` of finite support with no trailing `0`'s.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_shifting_algebras import ShiftingSequenceSpace\n sage: S = ShiftingSequenceSpace()\n sage: (1, -1) in S\n True\n sage: (1, -1, 0, 9) in S\n True\n sage: [1, -1] in S\n False\n sage: (0.5, 1) in S\n False\n " def __init__(self): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_shifting_algebras import ShiftingSequenceSpace\n sage: S = ShiftingSequenceSpace()\n ' Parent.__init__(self, facade=(tuple,), category=Sets().Infinite().Facade()) def __contains__(self, seq): '\n Return ``True`` if and only if ``seq`` is a valid shifting sequence.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_shifting_algebras import ShiftingSequenceSpace\n sage: S = ShiftingSequenceSpace()\n sage: (1, -1) in S\n True\n sage: (1, -1, 0, 9) in S\n True\n sage: (1, -1, 0) in S\n False\n sage: () in S\n True\n sage: [1, -1] in S\n False\n sage: (0.5, 1) in S\n False\n ' return (isinstance(seq, tuple) and all(((i in ZZ) for i in seq)) and ((not seq) or seq[(- 1)])) def check(self, seq): '\n Verify that ``seq`` is a valid shifting sequence.\n\n If it is not, raise a ``ValueError``.\n\n EXAMPLES::\n\n sage: from sage.combinat.partition_shifting_algebras import ShiftingSequenceSpace\n sage: S = ShiftingSequenceSpace()\n sage: S.check((1, -1))\n sage: S.check((1, -1, 0, 9))\n sage: S.check([1, -1])\n Traceback (most recent call last):\n ...\n ValueError: invalid index [1, -1]\n sage: S.check((0.5, 1))\n Traceback (most recent call last):\n ...\n ValueError: invalid index (0.500000000000000, 1)\n ' if (not self.__contains__(seq)): raise ValueError('invalid index {}'.format(seq))
class ShiftingOperatorAlgebra(CombinatorialFreeModule): '\n An algebra of shifting operators.\n\n Let `R` be a commutative ring. The algebra of shifting operators\n is isomorphic as an `R`-algebra to the Laurent polynomial ring\n `R[x_1^\\pm, x_2^\\pm, x_3^\\pm, \\ldots]`. Moreover, the monomials of\n the shifting operator algebra act on any integer sequence `\\lambda\n = (\\lambda_1, \\lambda_2, \\ldots, \\lambda_{\\ell})` as follows. Let\n `S` be our algebra of shifting operators. Then, for any monomial\n `s = x_1^{a_1}x_2^{a_2} \\cdots x_r^{a_r} \\in S` where `a_i \\in\n \\ZZ` and `r \\geq \\ell`, we get that `s.\\lambda = (\\lambda_1\n + a_1, \\lambda_2 + a_2,\\ldots,\\lambda_r+a_r)` where we pad\n `\\lambda` with `r-\\ell` zeros. In particular, we can recover\n Young\'s raising operator, `R_{ij}`, for `i < j`, acting on\n partitions by having `\\frac{x_i}{x_j}` act on a partition\n `\\lambda`.\n\n One can extend the action of these shifting operators to a basis\n of symmetric functions, but at the expense of no longer actually\n having a well-defined operator. Formally, to extend the action of\n the shifting operators on a symmetric function basis `B =\n \\{b_{\\lambda}\\}_{\\lambda}`, we define an `R`-module homomorphism\n `\\phi : R[x_1^\\pm, x_2^\\pm, \\ldots] \\to B`. Then we compute\n `x_1^{a_1} \\cdots x_r^{a_r}.b_\\lambda` by first computing\n `(x_1^{a_1} \\cdots x_r^{a_r})x_1^{\\lambda_1} \\cdots\n x_\\ell^{\\lambda_\\ell}` and then applying `\\phi` to the result. For\n examples of what this looks like with specific bases, see below.\n\n This implementation is consistent with how many references work\n formally with raising operators. For instance, see exposition\n surrounding [BMPS2018]_ Equation (4.1).\n\n We follow the following convention for creating elements: ``S(1,\n 0, -1, 2)`` is the shifting operator that raises the first part by\n `1`, lowers the third part by `1`, and raises the fourth part by\n `2`.\n\n In addition to acting on partitions (or any integer sequence), the\n shifting operators can also act on symmetric functions in a basis\n `B` when a conversion to `B` has been registered, preferably using\n :meth:`build_and_register_conversion`.\n\n For a definition of raising operators, see [BMPS2018]_ Definition\n 2.1. See :meth:`ij` to create operators using the notation in\n [BMPS2018]_.\n\n INPUT:\n\n - ``base_ring`` -- (default: ``QQ[\'t\']``) the base ring\n\n - ``prefix`` -- (default: ``"S"``) the label for the shifting operators\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n\n sage: elm = S[1, -1, 2]; elm\n S(1, -1, 2)\n sage: elm([5, 4])\n [([6, 3, 2], 1)]\n\n The shifting operator monomials can act on a complete homogeneous symmetric\n function or a Schur function::\n\n sage: s = SymmetricFunctions(QQ[\'t\']).s()\n sage: h = SymmetricFunctions(QQ[\'t\']).h()\n\n sage: elm(s[5, 4])\n s[6, 3, 2]\n sage: elm(h[5, 4])\n h[6, 3, 2]\n\n sage: S[1, -1](s[5, 4])\n s[6, 3]\n sage: S[1, -1](h[5, 4])\n h[6, 3]\n\n In fact, we can extend this action by linearity::\n\n sage: elm = (1 - S[1,-1]) * (1 - S[4])\n sage: elm == S([]) - S([1, -1]) - S([4]) + S([5, -1])\n True\n sage: elm(s[2, 2, 1])\n s[2, 2, 1] - s[3, 1, 1] - s[6, 2, 1] + s[7, 1, 1]\n\n sage: elm = (1 - S[1,-1]) * (1 - S[0,1,-1])\n sage: elm == 1 - S[0,1,-1] - S[1,-1] + S[1,0,-1]\n True\n sage: elm(s[2, 2, 1])\n s[2, 2, 1] - s[3, 1, 1] + s[3, 2]\n\n The algebra also comes equipped with homomorphisms to various\n symmetric function bases; these homomorphisms are how the action of\n ``S`` on the specific symmetric function bases is implemented::\n\n sage: elm = S([3,1,2]); elm\n S(3, 1, 2)\n sage: h(elm)\n h[3, 2, 1]\n sage: s(elm)\n 0\n\n However, not all homomorphisms are equivalent, so the action is basis\n dependent::\n\n sage: elm = S([3,2,1]); elm\n S(3, 2, 1)\n sage: h(elm)\n h[3, 2, 1]\n sage: s(elm)\n s[3, 2, 1]\n sage: s(elm) == s(h(elm))\n False\n\n We can also use raising operators to implement the Jacobi-Trudi identity::\n\n sage: op = (1-S[(1,-1)]) * (1-S[(1,0,-1)]) * (1-S[(0,1,-1)])\n sage: s(op(h[3,2,1]))\n s[3, 2, 1]\n ' def __init__(self, base_ring=QQ['t'], prefix='S'): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra(QQ['t'])\n sage: TestSuite(S).run()\n " indices = ShiftingSequenceSpace() cat = Algebras(base_ring).WithBasis() CombinatorialFreeModule.__init__(self, base_ring, indices, prefix=prefix, bracket=False, category=cat) sym = SymmetricFunctions(base_ring) self._sym_h = sym.h() self._sym_s = sym.s() self._sym_h.register_conversion(self.module_morphism(self._supp_to_h, codomain=self._sym_h)) self._sym_s.register_conversion(self.module_morphism(self._supp_to_s, codomain=self._sym_s)) def _repr_(self): '\n Return a string describing ``self``.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S\n Shifting Operator Algebra over Univariate Polynomial Ring in t\n over Rational Field\n ' return 'Shifting Operator Algebra over {}'.format(self.base_ring()) def __getitem__(self, seq): '\n Return the shifting operator whose index is ``seq``.\n\n This method is only for basis indices.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S[1, 1, -9]\n S(1, 1, -9)\n sage: S[(1, 1, -9)]\n S(1, 1, -9)\n sage: S[5]\n S(5,)\n ' if (not isinstance(seq, tuple)): if (seq in ZZ): seq = (seq,) else: seq = tuple(seq) return self._element_constructor_(seq) def _prepare_seq(self, seq): '\n Standardize the input ``seq`` to be a basis element of ``self``.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S._prepare_seq([0, 2, 0])\n (0, 2)\n sage: S._prepare_seq((0, 0, 0, 0))\n ()\n sage: S._prepare_seq(Partition([5,2,2,1]))\n (5, 2, 2, 1)\n ' seq = tuple(seq) index = (len(seq) - 1) while ((index >= 0) and (seq[index] == 0)): index -= 1 seq = seq[:(index + 1)] self._indices.check(seq) return seq def _element_constructor_(self, seq): '\n Return the shifting operator whose index is ``seq``.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S._element_constructor_([1, 1, -9])\n S(1, 1, -9)\n sage: S[1, 1, -9]\n S(1, 1, -9)\n sage: S[0, 1, 0]\n S(0, 1)\n ' if (seq in self.base_ring()): return self.term(self.one_basis(), self.base_ring()(seq)) return self.monomial(self._prepare_seq(seq)) def product_on_basis(self, x, y): '\n Return the product of basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S.product_on_basis((0, 5, 2), (3, 2, -2, 5))\n S(3, 7, 0, 5)\n sage: S.product_on_basis((1, -2, 0, 3, -6), (-1, 2, 2))\n S(0, 0, 2, 3, -6)\n sage: S.product_on_basis((1, -2, -2), (-1, 2, 2))\n S()\n ' if (len(x) < len(y)): (x, y) = (y, x) x = list(x) for (i, val) in enumerate(y): x[i] += val index = (len(x) - 1) while ((index >= 0) and (x[index] == 0)): index -= 1 return self.monomial(tuple(x[:(index + 1)])) @cached_method def one_basis(self): '\n Return the index of the basis element for `1`.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra()\n sage: S.one_basis()\n ()\n ' return () def _supp_to_h(self, supp): '\n This is a helper function that is not meant to be called directly.\n\n Given the support of an element\n `x_1^{\\gamma_1} x_2^{\\gamma_2} \\cdots x_\\ell^{\\gamma_\\ell}` in the\n ``ShiftingOperatorAlgebra`` and a\n symmetric function algebra basis `b` generated by\n `\\{b_1, b_2, b_3,\\ldots\\}`, return the element\n `b_{\\gamma_1} b_{\\gamma_2} \\cdots b_{\\gamma_\\ell}` where `b_0 = 1` and\n `b_{-n} = 0` for all positive\n integers `n`. The canonical example for `b` in this case would be `h`.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra(QQ)\n sage: h = SymmetricFunctions(QQ).h()\n sage: S._supp_to_h(S([3,2,1]).support_of_term())\n h[3, 2, 1]\n sage: S._supp_to_h(S([2,3,1]).support_of_term())\n h[3, 2, 1]\n sage: S._supp_to_h(S([2,3,-1]).support_of_term()) == h.zero()\n True\n sage: S._supp_to_h(S([2,3,0]).support_of_term())\n h[3, 2]\n ' gamma = sorted(supp, reverse=True) if (gamma in _Partitions): return self._sym_h(gamma) else: return self._sym_h.zero() def _supp_to_s(self, gamma): '\n This is a helper function that is not meant to be called directly.\n\n Given the support of an element `x_1^{\\gamma_1} x_2^{\\gamma_2} \\cdots\n x_\\ell^{\\gamma_\\ell}` in the ``ShiftingOperatorAlgebra``, return\n the appropriate `s_\\gamma` in the Schur basis using\n "Schur function straightening" in [BMPS2018]_ Proposition 4.1.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra(QQ)\n sage: s = SymmetricFunctions(QQ).s()\n sage: S._supp_to_s(S([3,2,1]).support_of_term())\n s[3, 2, 1]\n sage: S._supp_to_s(S([2,3,1]).support_of_term())\n 0\n sage: S._supp_to_s(S([2,4,-1,1]).support_of_term())\n s[3, 3]\n sage: S._supp_to_s(S([3,2,0]).support_of_term())\n s[3, 2]\n ' def number_of_noninversions(lis): return sum((1 for (i, val) in enumerate(lis) for j in range((i + 1), len(lis)) if (val < lis[j]))) rho = list(range((len(gamma) - 1), (- 1), (- 1))) combined = [(g + r) for (g, r) in zip(gamma, rho)] if ((len(set(combined)) == len(combined)) and all(((e >= 0) for e in combined))): sign = ((- 1) ** number_of_noninversions(combined)) sort_combined = sorted(combined, reverse=True) new_gamma = [(sc - r) for (sc, r) in zip(sort_combined, rho)] return (sign * self._sym_s(_Partitions(new_gamma))) else: return self._sym_s.zero() def build_and_register_conversion(self, support_map, codomain): "\n Build a module homomorphism from a map sending integer sequences to\n ``codomain`` and registers the result into Sage's conversion model.\n\n The intended use is to define a morphism from\n ``self`` to a basis `B` of symmetric functions that will be used by\n :class:`ShiftingOperatorAlgebra` to define the action of the\n operators on `B`.\n\n .. NOTE::\n\n The actions on the complete homogeneous symmetric functions and\n on the Schur functions by morphisms are already registered.\n\n .. WARNING::\n\n Because :class:`ShiftingOperatorAlgebra` inherits from\n :class:`UniqueRepresentation`, once you register a conversion, this\n will apply to all instances of :class:`ShiftingOperatorAlgebra`\n over the same base ring with the same prefix.\n\n INPUT:\n\n - ``support_map`` -- a map from integer sequences to ``codomain``\n\n - ``codomain`` -- the codomain of ``support_map``, usually a basis\n of symmetric functions\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra(QQ)\n sage: sym = SymmetricFunctions(QQ)\n sage: p = sym.p()\n sage: zero_map = lambda part: p.zero()\n sage: S.build_and_register_conversion(zero_map, p)\n sage: p(2*S([1,0,-1]) + S([2,1,0]) - 3*S([0,1,3]))\n 0\n sage: op = S((1, -1))\n sage: op(2*p[4,3] + 5*p[2,2] + 7*p[2]) == p.zero()\n True\n\n For a more illustrative example, we can implement a simple\n (but not mathematically justified!) conversion on the monomial basis::\n\n sage: S = ShiftingOperatorAlgebra(QQ)\n sage: sym = SymmetricFunctions(QQ)\n sage: m = sym.m()\n sage: def supp_map(gamma):\n ....: gsort = sorted(gamma, reverse=True)\n ....: return m(gsort) if gsort in Partitions() else m.zero()\n sage: S.build_and_register_conversion(supp_map, m)\n sage: op = S.ij(0, 1)\n sage: op(2*m[4,3] + 5*m[2,2] + 7*m[2]) == 2*m[5, 2] + 5*m[3, 1]\n True\n " module_morphism = self.module_morphism(support_map, codomain=codomain) codomain.register_conversion(module_morphism) def ij(self, i, j): '\n Return the raising operator `R_{ij}` as notated in [BMPS2018]_ Definition 2.1.\n\n Shorthand element constructor that allows you to create raising\n operators using the familiar `R_{ij}` notation found in\n [BMPS2018]_ Definition 2.1, with the exception that indices\n here are 0-based, not 1-based.\n\n EXAMPLES:\n\n Create the raising operator which raises part 0 and lowers part 2\n (indices are 0-based)::\n\n sage: R = ShiftingOperatorAlgebra()\n sage: R.ij(0, 2)\n S(1, 0, -1)\n ' if (i not in NonNegativeIntegerSemiring()): raise ValueError('i (={}) must be a natural number'.format(i)) if (j not in NonNegativeIntegerSemiring()): raise ValueError('j (={}) must be a natural number'.format(j)) if (not (i < j)): raise ValueError('index j (={j}) must be greater than index i (={i})'.format(i=i, j=j)) seq = ([0] * (max(i, j) + 1)) seq[i] = 1 seq[j] = (- 1) return self._element_constructor_(seq) class Element(CombinatorialFreeModule.Element): '\n An element of a :class:`ShiftingOperatorAlgebra`.\n ' def __call__(self, operand): '\n Call method for shifting sequence operators to act on objects.\n\n EXAMPLES::\n\n sage: S = ShiftingOperatorAlgebra(QQ)\n sage: op = S([1,1]) + 2*S([0,1,0,1])\n sage: sorted(op([1,1,1,1])) == sorted([([2,2,1,1], 1), ([1,2,1,2], 2)])\n True\n sage: sorted(op(Partition([1,1,1,1]))) == sorted([([2,2,1,1], 1), ([1,2,1,2], 2)])\n True\n sage: sym = SymmetricFunctions(QQ)\n sage: h = sym.h()\n sage: op(h[1,1,1,1])\n 3*h[2, 2, 1, 1]\n sage: s = sym.s()\n sage: op(s[1,1,1,1])\n s[2, 2, 1, 1]\n sage: e = sym.e()\n sage: sorted(op(e[1,1,1,1])) == sorted([([2,2,1,1], 1), ([1,2,1,2], 2)])\n True\n ' P = self.parent() if isinstance(operand, (list, tuple, Composition, Partition)): def add_lists(x, y): if (len(x) < len(y)): (x, y) = (y, x) x = list(x) for (i, val) in enumerate(y): x[i] += val return x return [(add_lists(index, operand), coeff) for (index, coeff) in self] R = self.base_ring() lift_operand = P._from_dict({P._prepare_seq(p): R(c) for (p, c) in operand}, coerce=False) result = (self * lift_operand) operand_parent = operand.parent() try: return operand_parent(result) except TypeError: return [(list(index), coeff) for (index, coeff) in result]
class PartitionTuple(CombinatorialElement): '\n A tuple of :class:`Partition`.\n\n A tuple of partition comes equipped with many of methods available to\n partitions. The ``level`` of the PartitionTuple is the length of the tuple.\n\n This is an ordered `k`-tuple of partitions\n `\\mu=(\\mu^{(1)},\\mu^{(2)},...,\\mu^{(k)})`. If\n\n .. MATH::\n\n n = \\lvert \\mu \\rvert = \\lvert \\mu^{(1)} \\rvert +\n \\lvert \\mu^{(2)} \\rvert + \\cdots + \\lvert \\mu^{(k)} \\rvert\n\n then `\\mu` is a `k`-partition of `n`.\n\n In representation theory PartitionTuples arise as the natural indexing\n set for the ordinary irreducible representations of:\n\n - the wreath products of cyclic groups with symmetric groups\n - the Ariki-Koike algebras, or the cyclotomic Hecke algebras of\n the complex reflection groups of type `G(r,1,n)`\n - the degenerate cyclotomic Hecke algebras of type `G(r,1,n)`\n\n When these algebras are not semisimple, partition tuples index an important\n class of modules for the algebras which are generalisations of the Specht\n modules of the symmetric groups.\n\n Tuples of partitions also index the standard basis of the higher level\n combinatorial Fock spaces. As a consequence, the combinatorics of partition\n tuples encapsulates the canonical bases of crystal graphs for the irreducible\n integrable highest weight modules of the (quantized) affine special linear\n groups and the (quantized) affine general linear groups. By the\n categorification theorems of Ariki, Varagnolo-Vasserot, Stroppel-Webster and\n others, in characteristic zero the degenerate and non-degenerate cyclotomic\n Hecke algebras, via their Khovanov-Lauda-Rouquier grading, categorify the\n canonical bases of the quantum affine special and general linear groups.\n\n Partitions are naturally in bijection with 1-tuples of partitions. Most of the\n combinatorial operations defined on partitions extend to PartitionTuples in\n a meaningful way. For example, the semisimple branching rules for the Specht\n modules are described by adding and removing cells from partition tuples and\n the modular branching rules correspond to adding and removing good and\n cogood nodes, which is the underlying combinatorics for the associated\n crystal graphs.\n\n .. WARNING::\n\n In the literature, the cells of a partition tuple are usually written\n in the form `(r,c,k)`, where `r` is the row index, `c` is the column\n index, and `k` is the component index. In sage, if ``mu`` is a\n partition tuple then ``mu[k]`` most naturally refers to the `k`-th\n component of ``mu``, so we use the convention of the `(k,r,c)`-th cell\n in a partition tuple refers to the cell in component `k`, row `r`, and\n column `c`.\n\n INPUT:\n\n Anything which can reasonably be interpreted as a tuple of partitions.\n That is, a list or tuple of partitions or valid input to\n :class:`Partition`.\n\n EXAMPLES::\n\n sage: mu=PartitionTuple( [[3,2],[2,1],[],[1,1,1,1]] ); mu\n ([3, 2], [2, 1], [], [1, 1, 1, 1])\n sage: nu=PartitionTuple( ([3,2],[2,1],[],[1,1,1,1]) ); nu\n ([3, 2], [2, 1], [], [1, 1, 1, 1])\n sage: mu == nu\n True\n sage: mu is nu\n False\n sage: mu in PartitionTuples()\n True\n sage: mu.parent()\n Partition tuples\n\n sage: lam=PartitionTuples(3)([[3,2],[],[1,1,1,1]]); lam\n ([3, 2], [], [1, 1, 1, 1])\n sage: lam.level()\n 3\n sage: lam.size()\n 9\n sage: lam.category()\n Category of elements of Partition tuples of level 3\n sage: lam.parent()\n Partition tuples of level 3\n sage: lam[0]\n [3, 2]\n sage: lam[1]\n []\n sage: lam[2]\n [1, 1, 1, 1]\n sage: lam.pp()\n *** - *\n ** *\n *\n *\n sage: lam.removable_cells()\n [(0, 0, 2), (0, 1, 1), (2, 3, 0)]\n sage: lam.down_list()\n [([2, 2], [], [1, 1, 1, 1]), ([3, 1], [], [1, 1, 1, 1]), ([3, 2], [], [1, 1, 1])]\n sage: lam.addable_cells()\n [(0, 0, 3), (0, 1, 2), (0, 2, 0), (1, 0, 0), (2, 0, 1), (2, 4, 0)]\n sage: lam.up_list()\n [([4, 2], [], [1, 1, 1, 1]), ([3, 3], [], [1, 1, 1, 1]), ([3, 2, 1], [], [1, 1, 1, 1]), ([3, 2], [1], [1, 1, 1, 1]), ([3, 2], [], [2, 1, 1, 1]), ([3, 2], [], [1, 1, 1, 1, 1])]\n sage: lam.conjugate()\n ([4], [], [2, 2, 1])\n sage: lam.dominates( PartitionTuple([[3],[1],[2,2,1]]) )\n False\n sage: lam.dominates( PartitionTuple([[3],[2],[1,1,1]]))\n True\n\n TESTS::\n\n sage: TestSuite( PartitionTuple([4,3,2]) ).run()\n sage: TestSuite( PartitionTuple([[4,3,2],[],[],[3,2,1]]) ).run()\n\n .. SEEALSO::\n\n - :class:`PartitionTuples`\n - :class:`Partitions`\n ' Element = Partition @staticmethod def __classcall_private__(self, mu): "\n This delegates the construction of a :class:`PartitionTuple` to the\n ``element_class()`` call of the appropriate\n :class:`PartitionTuples_level`.\n\n TESTS::\n\n sage: mu=PartitionTuple([[1,1],[1]])\n sage: mu.category()\n Category of elements of Partition tuples\n sage: type(mu)\n <class 'sage.combinat.partition_tuple.PartitionTuples_all_with_category.element_class'>\n " if isinstance(mu, (Partition, PartitionTuple)): return mu if ((mu == []) or (mu == [[]])): return _Partitions([]) try: mu = [_Partitions(mu)] except ValueError: try: mu = [_Partitions(nu) for nu in mu] except ValueError: raise ValueError(('%s is not a tuple of Partitions' % mu)) if (len(mu) == 1): return _Partitions(mu[0]) else: return PartitionTuples_all().element_class(PartitionTuples_all(), mu) def __init__(self, parent, mu): '\n Initialize ``self`` and checks that the input determines a tuple of\n partitions.\n\n EXAMPLES::\n\n sage: PartitionTuple([])\n []\n sage: P = PartitionTuple([[2,1,1,0],[2,1]]); P\n ([2, 1, 1], [2, 1])\n sage: TestSuite(P).run()\n sage: PartitionTuple([[],[],[2,1,2,1]])\n Traceback (most recent call last):\n ...\n ValueError: [[], [], [2, 1, 2, 1]] is not a tuple of Partitions\n\n ' mu = [_Partitions(nu) for nu in mu] CombinatorialElement.__init__(self, parent, mu) def level(self): '\n Return the level of this partition tuple.\n\n The level is the length of the tuple.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1,1,0],[2,1]]).level()\n 2\n sage: PartitionTuple([[],[],[2,1,1]]).level()\n 3\n ' return len(self._list) def __len__(self): '\n Return the length of this partition tuple.\n\n The length is also known as the level.\n\n EXAMPLES::\n\n sage: len( PartitionTuple([[2,1],[3,2],[1,1,1]]) )\n 3\n\n ' return self.level() def _repr_(self, compact=None): '\n Return a string representation of ``self`` depending on\n :meth:`PartitionTuples.options`.\n\n EXAMPLES::\n\n sage: mu=PartitionTuple(([2,1],[3,2],[1,1,1])) # indirect doctest\n\n sage: PartitionTuples.options(display="list"); mu\n ([2, 1], [3, 2], [1, 1, 1])\n sage: PartitionTuples.options(display="diagram"); mu\n ** *** *\n * ** *\n *\n sage: PartitionTuples.options(display="compact_low"); mu\n 1,2|2,3|1^3\n sage: PartitionTuples.options(display="compact_high"); mu\n 2,1|3,2|1^3\n sage: PartitionTuples.options(display="exp_low"); mu\n 1, 2 | 2, 3 | 1^3\n sage: PartitionTuples.options(display="exp_high"); mu\n 2, 1 | 3, 2 | 1^3\n sage: PartitionTuples.options._reset()\n\n sage: Partitions.options(convention="French")\n sage: PartitionTuples.options(display="diagram"); mu\n *\n * ** *\n ** *** *\n sage: PartitionTuples.options(display="list"); mu\n ([2, 1], [3, 2], [1, 1, 1])\n sage: PartitionTuples.options(display="compact_low"); mu\n 1,2|2,3|1^3\n sage: PartitionTuples.options(display="compact_high"); mu\n 2,1|3,2|1^3\n sage: PartitionTuples.options(display="exp_low"); mu\n 1, 2 | 2, 3 | 1^3\n sage: PartitionTuples.options(display="exp_high"); mu\n 2, 1 | 3, 2 | 1^3\n sage: PartitionTuples.options._reset()\n ' return self.parent().options._dispatch(self, '_repr_', 'display') def _repr_diagram(self): '\n Return a string representation of ``self`` as a Ferrers diagram.\n\n EXAMPLES::\n\n sage: print(PartitionTuple(([2,1],[3,2],[1,1,1]))._repr_diagram())\n ** *** *\n * ** *\n *\n ' return self.diagram() def _repr_list(self): "\n Return a string representation of ``self`` as a list.\n\n EXAMPLES::\n\n sage: PartitionTuple(([2,1],[3,2],[1,1,1]))._repr_list()\n '([2, 1], [3, 2], [1, 1, 1])'\n " return (('(' + ', '.join((nu._repr_() for nu in self))) + ')') def _repr_exp_low(self): "\n Return a string representation of ``self`` in compact form (exponential\n form with highest first).\n\n EXAMPLES::\n\n sage: PartitionTuple(([2,1],[3,2],[1,1,1]))._repr_exp_low()\n '1, 2 | 2, 3 | 1^3'\n sage: PartitionTuple(([],[3,2],[1,1,1]))._repr_exp_low()\n '- | 2, 3 | 1^3'\n " return ' | '.join((nu._repr_exp_low() for nu in self)) def _repr_exp_high(self): "\n Return a string representation of ``self`` in compact form (exponential\n form with highest first).\n\n EXAMPLES::\n\n sage: PartitionTuple(([2,1],[3,2],[1,1,1,1,1,1,1,1,1,1]))._repr_exp_high()\n '2, 1 | 3, 2 | 1^10'\n sage: PartitionTuple(([],[3,2],[1,1,1]))._repr_exp_high()\n '- | 3, 2 | 1^3'\n " return ' | '.join((nu._repr_exp_high() for nu in self)) def _repr_compact_low(self): "\n Return a string representation of ``self`` in compact form (exponential\n form with highest first).\n\n EXAMPLES::\n\n sage: PartitionTuple(([2,1],[3,2],[1,1,1]))._repr_compact_low()\n '1,2|2,3|1^3'\n sage: PartitionTuple(([],[3,2],[1,1,1]))._repr_compact_low()\n '-|2,3|1^3'\n " return ('%s' % '|'.join((mu._repr_compact_low() for mu in self))) def _repr_compact_high(self): "\n Return a string representation of ``self`` in compact form (exponential\n form with highest first).\n\n EXAMPLES::\n\n sage: PartitionTuple(([2,1],[3,2],[1,1,1]))._repr_compact_high()\n '2,1|3,2|1^3'\n sage: PartitionTuple(([],[3,2],[1,1,1]))._repr_compact_high()\n '-|3,2|1^3'\n " return '|'.join((mu._repr_compact_high() for mu in self)) __str__ = (lambda self: self._repr_()) def _latex_(self): '\n Return a LaTeX version of ``self``.\n\n For more on the latex options, see :meth:`Partitions.option`.\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1]])\n sage: PartitionTuples.options(latex=\'diagram\'); latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{@{\\hspace{.6ex}}c@{\\hspace{.6ex}}}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\\\\n \\lr{\\ast}&\\lr{\\ast}\\\\\n \\lr{\\ast}\\\\\n \\end{array}$},\\raisebox{-.6ex}{$\\begin{array}[b]{*{1}c}\\\\\n \\lr{\\ast}\\\\\n \\lr{\\ast}\\\\\n \\lr{\\ast}\\\\\n \\end{array}$}\n }\n sage: PartitionTuples.options(latex=\'exp_high\'); latex(mu) # indirect doctest\n (2,1|1^{3})\n sage: PartitionTuples.options(latex=\'exp_low\'); latex(mu) # indirect doctest\n (1,2|1^{3})\n sage: PartitionTuples.options(latex=\'list\'); latex(mu) # indirect doctest\n [[2, 1], [1, 1, 1]]\n sage: PartitionTuples.options(latex=\'young_diagram\'); latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{2}c}\\cline{1-2}\n \\lr{\\phantom{x}}&\\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\end{array}$},\\raisebox{-.6ex}{$\\begin{array}[b]{*{1}c}\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\end{array}$}\n }\n\n sage: PartitionTuples.options(latex="young_diagram", convention="french")\n sage: PartitionTuples.options(latex=\'exp_high\'); latex(mu) # indirect doctest\n (2,1|1^{3})\n sage: PartitionTuples.options(latex=\'exp_low\'); latex(mu) # indirect doctest\n (1,2|1^{3})\n sage: PartitionTuples.options(latex=\'list\'); latex(mu) # indirect doctest\n [[2, 1], [1, 1, 1]]\n sage: PartitionTuples.options(latex=\'young_diagram\'); latex(mu) # indirect doctest\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{2}c}\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\lr{\\phantom{x}}&\\lr{\\phantom{x}}\\\\\\cline{1-2}\n \\end{array}$},\\raisebox{-.6ex}{$\\begin{array}[t]{*{1}c}\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\lr{\\phantom{x}}\\\\\\cline{1-1}\n \\end{array}$}\n }\n\n sage: PartitionTuples.options._reset()\n ' return self.parent().options._dispatch(self, '_latex_', 'latex') def _latex_young_diagram(self): '\n LaTeX output as a Young diagram.\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1]])._latex_young_diagram()\n ' from sage.combinat.output import tex_from_array_tuple return tex_from_array_tuple([[(['\\phantom{x}'] * row) for row in mu] for mu in self._list]) def _latex_diagram(self): "\n LaTeX output as a Ferrers' diagram.\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1]])._latex_diagram()\n " entry = self.parent().options('latex_diagram_str') from sage.combinat.output import tex_from_array_tuple return tex_from_array_tuple([[([entry] * row) for row in mu] for mu in self._list], with_lines=False) def _latex_list(self): '\n LaTeX output as a list.\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1]])._latex_list()\n ' return repr(self._list) def _latex_exp_low(self): '\n LaTeX output in exponential notation (lowest first).\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1,1,1,1,1,1,1,1]])._latex_exp_low()\n ' txt = '|'.join((','.join((('%s%s' % ((a + 1), ('' if (e == 1) else ('^{%s}' % e)))) for (a, e) in enumerate(mu))) for mu in self.to_exp())) return (('(' + txt) + ')') def _latex_exp_high(self): '\n LaTeX output in exponential notation (highest first).\n\n EXAMPLES::\n\n sage: mu = PartitionTuple([[2, 1],[1,1,1,1,1,1,1,1,1,1]])._latex_exp_high()\n ' txt = '|'.join((','.join([('%s%s' % ((a + 1), ('' if (e == 1) else ('^{%s}' % e)))) for (a, e) in enumerate(mu)][::(- 1)]) for mu in self.to_exp())) return (('(' + txt) + ')') def components(self): '\n Return a list containing the shape of this partition.\n\n This function exists in order to give a uniform way of iterating over\n the \\"components\\" of partition tuples of level 1 (partitions) and for\n higher levels.\n\n EXAMPLES::\n\n sage: for t in PartitionTuple([[2,1],[3,2],[3]]).components():\n ....: print(\'%s\\n\' % t.ferrers_diagram())\n **\n *\n <BLANKLINE>\n ***\n **\n <BLANKLINE>\n ***\n <BLANKLINE>\n sage: for t in PartitionTuple([3,2]).components():\n ....: print(\'%s\\n\' % t.ferrers_diagram())\n ***\n **\n ' return [t for t in self] def diagram(self): '\n Return a string for the Ferrers diagram of ``self``.\n\n EXAMPLES::\n\n sage: print(PartitionTuple([[2,1],[3,2],[1,1,1]]).diagram())\n ** *** *\n * ** *\n *\n sage: print(PartitionTuple([[3,2],[2,1],[],[1,1,1,1]]).diagram())\n *** ** - *\n ** * *\n *\n *\n sage: PartitionTuples.options(convention="french")\n sage: print(PartitionTuple([[3,2],[2,1],[],[1,1,1,1]]).diagram())\n *\n *\n ** * *\n *** ** - *\n sage: PartitionTuples.options._reset()\n ' col_len = [((mu and mu[0]) or 1) for mu in self] row_max = max((len(mu) for mu in self)) diag = [] diag_str = PartitionTuples.options('diagram_str') for row in range(row_max): line = '' for c in range(len(self)): if ((row == 0) and (self[c] == [])): line += ' -' elif (row < len(self[c])): line += ' {:{}}'.format((diag_str * self[c][row]), col_len[c]) else: line += ' {:{}}'.format('', col_len[c]) diag.append(line.rstrip()) if (PartitionTuples.options('convention') == 'English'): return '\n'.join(map(str, diag)) else: return '\n'.join(map(str, diag[::(- 1)])) ferrers_diagram = diagram def pp(self): '\n Pretty prints this partition tuple. See :meth:`diagram`.\n\n EXAMPLES::\n\n sage: PartitionTuple([[5,5,2,1],[3,2]]).pp()\n ***** ***\n ***** **\n **\n *\n ' print(self.diagram()) def size(self): '\n Return the size of a partition tuple.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[],[2,2]]).size()\n 7\n sage: PartitionTuple([[],[],[1],[3,2,1]]).size()\n 7\n ' return sum((mu.size() for mu in self)) def row_standard_tableaux(self): '\n Return the :class:`row standard tableau tuples\n <sage.combinat.tableau_tuple.RowStandardTableauTuples>`\n of shape ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[3,2,2,1],[2,2,1],[3]]).row_standard_tableaux()\n Row standard tableau tuples of shape ([], [3, 2, 2, 1], [2, 2, 1], [3])\n ' from .tableau_tuple import RowStandardTableauTuples return RowStandardTableauTuples(shape=self) def standard_tableaux(self): '\n Return the :class:`standard tableau tuples<StandardTableauTuples>`\n of shape ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[3,2,2,1],[2,2,1],[3]]).standard_tableaux()\n Standard tableau tuples of shape ([], [3, 2, 2, 1], [2, 2, 1], [3])\n ' from .tableau_tuple import StandardTableauTuples return StandardTableauTuples(shape=self) def up(self): '\n Generator (iterator) for the partition tuples that are obtained from\n ``self`` by adding a cell.\n\n EXAMPLES::\n\n sage: [mu for mu in PartitionTuple([[],[3,1],[1,1]]).up()]\n [([1], [3, 1], [1, 1]), ([], [4, 1], [1, 1]), ([], [3, 2], [1, 1]), ([], [3, 1, 1], [1, 1]), ([], [3, 1], [2, 1]), ([], [3, 1], [1, 1, 1])]\n sage: [mu for mu in PartitionTuple([[],[],[],[]]).up()]\n [([1], [], [], []), ([], [1], [], []), ([], [], [1], []), ([], [], [], [1])]\n ' for c in range(len(self)): for nu in self[c].up(): up = [tau for tau in self] up[c] = nu (yield PartitionTuple(up)) def up_list(self): '\n Return a list of the partition tuples that can be formed from ``self``\n by adding a cell.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[3,1],[1,1]]).up_list()\n [([1], [3, 1], [1, 1]), ([], [4, 1], [1, 1]), ([], [3, 2], [1, 1]), ([], [3, 1, 1], [1, 1]), ([], [3, 1], [2, 1]), ([], [3, 1], [1, 1, 1])]\n sage: PartitionTuple([[],[],[],[]]).up_list()\n [([1], [], [], []), ([], [1], [], []), ([], [], [1], []), ([], [], [], [1])]\n\n ' return [mu for mu in self.up()] def down(self): '\n Generator (iterator) for the partition tuples that are obtained from\n ``self`` by removing a cell.\n\n EXAMPLES::\n\n sage: [mu for mu in PartitionTuple([[],[3,1],[1,1]]).down()]\n [([], [2, 1], [1, 1]), ([], [3], [1, 1]), ([], [3, 1], [1])]\n sage: [mu for mu in PartitionTuple([[],[],[]]).down()]\n []\n\n ' for c in range(len(self)): for nu in self[c].down(): down = [tau for tau in self] down[c] = nu (yield PartitionTuple(down)) def down_list(self): '\n Return a list of the partition tuples that can be formed from ``self``\n by removing a cell.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[3,1],[1,1]]).down_list()\n [([], [2, 1], [1, 1]), ([], [3], [1, 1]), ([], [3, 1], [1])]\n sage: PartitionTuple([[],[],[]]).down_list()\n []\n ' return [mu for mu in self.down()] def cells(self): '\n Return the coordinates of the cells of ``self``. Coordinates are given\n as (component index, row index, column index) and are 0 based.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[1],[1,1,1]]).cells()\n [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (2, 0, 0), (2, 1, 0), (2, 2, 0)]\n ' return [(c, a, b) for c in range(len(self)) for (a, b) in self[c].cells()] def content(self, k, r, c, multicharge): '\n Return the content of the cell.\n\n Let `m_k =` ``multicharge[k]``, then the content of a cell is\n `m_k + c - r`.\n\n If the ``multicharge`` is a list of integers then it simply offsets the\n values of the contents in each component. On the other hand, if the\n ``multicharge`` belongs to `\\ZZ/e\\ZZ` then the corresponding\n `e`-residue is returned (that is, the content mod `e`).\n\n As with the content method for partitions, the content of a cell does\n not technically depend on the partition tuple, but this method is\n included because it is often useful.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content(0,1,0, [0,0,0])\n -1\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content(0,1,0, [1,0,0])\n 0\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content(2,1,0, [0,0,0])\n -1\n\n and now we return the 3-residue of a cell::\n\n sage: multicharge = [IntegerModRing(3)(c) for c in [0,0,0]]\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content(0,1,0, multicharge)\n 2\n\n ' return ((multicharge[k] - r) + c) def content_tableau(self, multicharge): '\n Return the tableau which has (k,r,c)th entry equal to the content\n ``multicharge[k]-r+c`` of this cell.\n\n As with the content function, by setting the ``multicharge``\n appropriately the tableau containing the residues is returned.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content_tableau([0,0,0])\n ([[0, 1], [-1]], [[0, 1]], [[0], [-1], [-2]])\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content_tableau([0,0,1]).pp()\n 0 1 0 1 1\n -1 0\n -1\n\n as with the content function the multicharge can be used to return the\n tableau containing the residues of the cells::\n\n sage: multicharge=[ IntegerModRing(3)(c) for c in [0,0,1] ]\n sage: PartitionTuple([[2,1],[2],[1,1,1]]).content_tableau(multicharge).pp()\n 0 1 0 1 1\n 2 0\n 2\n ' from sage.combinat.tableau_tuple import TableauTuple return TableauTuple([[[((multicharge[k] - r) + c) for c in range(self[k][r])] for r in range(len(self[k]))] for k in range(len(self))]) def conjugate(self): '\n Return the conjugate partition tuple of ``self``.\n\n The conjugate partition tuple is obtained by reversing the order of the\n components and then swapping the rows and columns in each component.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[1],[1,1,1]]).conjugate()\n ([3], [1], [2, 1])\n ' return PartitionTuple([nu.conjugate() for nu in self[::(- 1)]]) def dominates(self, mu): '\n Return ``True`` if the PartitionTuple dominates or equals `\\mu` and\n ``False`` otherwise.\n\n Given partition tuples `\\mu=(\\mu^{(1)},...,\\mu^{(m)})` and `\\nu=(\\nu^{(1)},...,\\nu^{(n)})`\n then `\\mu` dominates `\\nu` if\n\n .. MATH::\n\n \\sum_{k=1}^{l-1} |\\mu^{(k)}| +\\sum_{r \\geq 1} \\mu^{(l)}_r\n \\geq \\sum_{k=1}^{l-1} |\\nu^{(k)}| + \\sum_{r \\geq 1} \\nu^{(l)}_r\n\n EXAMPLES::\n\n sage: mu=PartitionTuple([[1,1],[2],[2,1]])\n sage: nu=PartitionTuple([[1,1],[1,1],[2,1]])\n sage: mu.dominates(mu)\n True\n sage: mu.dominates(nu)\n True\n sage: nu.dominates(mu)\n False\n sage: tau=PartitionTuple([[],[2,1],[]])\n sage: tau.dominates([[2,1],[],[]])\n False\n sage: tau.dominates([[],[],[2,1]])\n True\n ' try: mu = PartitionTuple(mu) except ValueError: raise ValueError(('%s must be a PartitionTuple' % mu)) if (mu == self): return True level = 0 ssum = 0 musum = 0 while ((level < self.level()) and (level < mu.level())): row = 0 while ((row < len(self[level])) and (row < len(mu[level]))): ssum += self[level][row] musum += mu[level][row] if (musum > ssum): return False row += 1 if (row < len(self[level])): ssum += sum(self[level][row:]) elif (row < len(mu[level])): musum += sum(mu[level][row:]) if (musum > ssum): return False level += 1 return True @cached_method def initial_tableau(self): '\n Return the :class:`StandardTableauTuple` which has the numbers\n `1, 2, \\ldots, n`, where `n` is the :meth:`size` of ``self``,\n entered in order from left to right along the rows of each component,\n where the components are ordered from left to right.\n\n EXAMPLES::\n\n sage: PartitionTuple([ [2,1],[3,2] ]).initial_tableau()\n ([[1, 2], [3]], [[4, 5, 6], [7, 8]])\n ' from .tableau_tuple import StandardTableauTuples return StandardTableauTuples(self).first() @cached_method def initial_column_tableau(self): '\n Return the initial column tableau of shape ``self``.\n\n The initial column tableau of shape `\\lambda` is the standard tableau\n that has the numbers `1` to `n`, where `n` is the :meth:`size`\n of `\\lambda`, entered in order from top to bottom, and then left\n to right, down the columns of each component, starting from the\n rightmost component and working to the left.\n\n EXAMPLES::\n\n sage: PartitionTuple([ [3,1],[3,2] ]).initial_column_tableau()\n ([[6, 8, 9], [7]], [[1, 3, 5], [2, 4]])\n ' return self.conjugate().initial_tableau().conjugate() def garnir_tableau(self, *cell): '\n Return the Garnir tableau of shape ``self`` corresponding to the cell\n ``cell``.\n\n If ``cell`` `= (k,a,c)` then `(k,a+1,c)` must belong to the diagram of\n the :class:`PartitionTuple`. If this is not the case then we return\n ``False``.\n\n .. NOTE::\n\n The function also sets ``g._garnir_cell`` equal to ``cell``\n which is used by some other functions.\n\n The Garnir tableaux play an important role in integral and\n non-semisimple representation theory because they determine the\n "straightening" rules for the Specht modules over an arbitrary ring.\n\n The Garnir tableau are the "first" non-standard tableaux which arise\n when you act by simple transpositions. If `(k,a,c)` is a cell in the\n Young diagram of a partition, which is not at the bottom of its\n column, then the corresponding Garnir tableau has the integers\n `1, 2, \\ldots, n` entered in order from left to right along the rows\n of the diagram up to the cell `(k,a,c-1)`, then along the cells\n `(k,a+1,1)` to `(k,a+1,c)`, then `(k,a,c)` until the end of row `a`\n and then continuing from left to right in the remaining positions.\n The examples below probably make this clearer!\n\n EXAMPLES::\n\n sage: PartitionTuple([[5,3],[2,2],[4,3]]).garnir_tableau((0,0,2)).pp()\n 1 2 6 7 8 9 10 13 14 15 16\n 3 4 5 11 12 17 18 19\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((0,0,2)).pp()\n 1 2 6 7 8 12 13 16 17 18 19\n 3 4 5 14 15 20 21 22\n 9 10 11\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((0,1,2)).pp()\n 1 2 3 4 5 12 13 16 17 18 19\n 6 7 11 14 15 20 21 22\n 8 9 10\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((1,0,0)).pp()\n 1 2 3 4 5 13 14 16 17 18 19\n 6 7 8 12 15 20 21 22\n 9 10 11\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((1,0,1)).pp()\n 1 2 3 4 5 12 15 16 17 18 19\n 6 7 8 13 14 20 21 22\n 9 10 11\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((2,0,1)).pp()\n 1 2 3 4 5 12 13 16 19 20 21\n 6 7 8 14 15 17 18 22\n 9 10 11\n sage: PartitionTuple([[5,3,3],[2,2],[4,3]]).garnir_tableau((2,1,1)).pp()\n Traceback (most recent call last):\n ...\n ValueError: (comp, row+1, col) must be inside the diagram\n\n .. SEEALSO::\n\n - :meth:`top_garnir_tableau`\n ' try: (comp, row, col) = cell except ValueError: (comp, row, col) = cell[0] if ((comp >= len(self)) or ((row + 1) >= len(self[comp])) or (col >= self[comp][(row + 1)])): raise ValueError('(comp, row+1, col) must be inside the diagram') g = self.initial_tableau().to_list() a = g[comp][row][col] g[comp][row][col:] = list(range(((a + col) + 1), (g[comp][(row + 1)][col] + 1))) g[comp][(row + 1)][:(col + 1)] = list(range(a, ((a + col) + 1))) from .tableau_tuple import TableauTuple g = TableauTuple(g) g._garnir_cell = (comp, row, col) return g def top_garnir_tableau(self, e, cell): '\n Return the most dominant *standard* tableau which dominates the\n corresponding Garnir tableau and has the same residue that has shape\n ``self`` and is determined by ``e`` and ``cell``.\n\n The Garnir tableau play an important role in integral and\n non-semisimple representation theory because they determine the\n "straightening" rules for the Specht modules over an arbitrary ring.\n The *top Garnir tableaux* arise in the graded representation theory of\n the symmetric groups and higher level Hecke algebras. They were\n introduced in [KMR2012]_.\n\n If the Garnir node is ``cell=(k,r,c)`` and `m` and `M` are the entries\n in the cells ``(k,r,c)`` and ``(k,r+1,c)``, respectively, in the\n initial tableau then the top ``e``-Garnir tableau is obtained by\n inserting the numbers `m, m+1, \\ldots, M` in order from left to right\n first in the cells in row ``r+1`` which are not in the ``e``-Garnir\n belt, then in the cell in rows ``r`` and ``r+1`` which are in the\n Garnir belt and then, finally, in the remaining cells in row ``r``\n which are not in the Garnir belt. All other entries in the tableau\n remain unchanged.\n\n If ``e = 0``, or if there are no ``e``-bricks in either row ``r`` or\n ``r+1``, then the top Garnir tableau is the corresponding Garnir\n tableau.\n\n EXAMPLES::\n\n sage: PartitionTuple([[3,3,2],[5,4,3,2]]).top_garnir_tableau(2,(1,0,2)).pp()\n 1 2 3 9 10 12 13 16\n 4 5 6 11 14 15 17\n 7 8 18 19 20\n 21 22\n sage: PartitionTuple([[3,3,2],[5,4,3,2]]).top_garnir_tableau(2,(1,0,1)).pp()\n 1 2 3 9 10 11 12 13\n 4 5 6 14 15 16 17\n 7 8 18 19 20\n 21 22\n sage: PartitionTuple([[3,3,2],[5,4,3,2]]).top_garnir_tableau(3,(1,0,1)).pp()\n 1 2 3 9 12 13 14 15\n 4 5 6 10 11 16 17\n 7 8 18 19 20\n 21 22\n\n sage: PartitionTuple([[3,3,2],[5,4,3,2]]).top_garnir_tableau(3,(3,0,1)).pp()\n Traceback (most recent call last):\n ...\n ValueError: (comp, row+1, col) must be inside the diagram\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.partition.Partition_tuple.garnir_tableau`\n ' (comp, row, col) = cell if ((comp >= len(self)) or ((row + 1) >= len(self[comp])) or (col >= self[comp][(row + 1)])): raise ValueError('(comp, row+1, col) must be inside the diagram') g = self.garnir_tableau(cell) if (e == 0): return a = (e * int(((self[comp][row] - col) / e))) b = (e * int(((col + 1) / e))) if ((a == 0) or (b == 0)): return self.garnir_tableau(cell) t = g.to_list() m = t[comp][(row + 1)][0] t[comp][row][col:(a + col)] = [((((m + col) - b) + 1) + i) for i in range(a)] t[comp][(row + 1)][((col - b) + 1):(col + 1)] = [(((((m + a) + col) - b) + 1) + i) for i in range(b)] from .tableau_tuple import StandardTableauTuple return StandardTableauTuple(t) def arm_length(self, k, r, c): '\n Return the length of the arm of cell ``(k, r, c)`` in ``self``.\n\n INPUT:\n\n - ``k`` -- The component\n - ``r`` -- The row\n - ``c`` -- The cell\n\n OUTPUT:\n\n - The arm length as an integer\n\n The arm of cell ``(k, r, c)`` is the number of cells in the ``k``-th\n component which are to the right of the cell in row ``r`` and column\n ``c``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).arm_length(2,0,0)\n 1\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).arm_length(2,0,1)\n 0\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).arm_length(2,2,0)\n 0\n ' try: return (self[k][r] - (c + 1)) except IndexError: raise ValueError(('The cell %s is not in the diagram' % ((k, r, c),))) def leg_length(self, k, r, c): '\n Return the length of the leg of cell ``(k, r, c)`` in ``self``.\n\n INPUT:\n\n - ``k`` -- The component\n - ``r`` -- The row\n - ``c`` -- The cell\n\n OUTPUT:\n\n - The leg length as an integer\n\n The leg of cell ``(k, r, c)`` is the number of cells in the ``k``-th\n component which are below the node in row ``r`` and column ``c``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).leg_length(2,0,0)\n 2\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).leg_length(2,0,1)\n 1\n sage: PartitionTuple([[],[2,1],[2,2,1],[3]]).leg_length(2,2,0)\n 0\n ' try: return self[k].leg_length(r, c) except IndexError: raise ValueError('The cell is not in the diagram') def contains(self, mu): '\n Return ``True`` if this partition tuple contains `\\mu`.\n\n If `\\lambda=(\\lambda^{(1)}, \\ldots, \\lambda^{(l)})` and\n `\\mu=(\\mu^{(1)}, \\ldots, \\mu^{(m)})` are two partition tuples then\n `\\lambda` contains `\\mu` if `m \\leq l` and\n `\\mu^{(i)}_r \\leq \\lambda^{(i)}_r` for `1 \\leq i \\leq m` and `r \\geq 0`.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[2],[2,1]]).contains( PartitionTuple([[1,1],[2],[2,1]]) )\n True\n ' return ((mu.level() <= self.level()) and all((self[c].contains(mu[c]) for c in range(len(mu))))) def hook_length(self, k, r, c): "\n Return the length of the hook of cell ``(k, r, c)`` in the partition.\n\n The hook of cell ``(k, r, c)`` is defined as the cells to the right or\n below (in the English convention). If your coordinates are in the\n form ``(k,r,c)``, use Python's \\*-operator.\n\n EXAMPLES::\n\n sage: mu=PartitionTuple([[1,1],[2],[2,1]])\n sage: [ mu.hook_length(*c) for c in mu.cells()]\n [2, 1, 2, 1, 3, 1, 1]\n " try: return self[k].hook_length(r, c) except IndexError: raise ValueError('The cell is not in the diagram') def to_exp(self, k=0): '\n Return a tuple of the multiplicities of the parts of a partition.\n\n Use the optional parameter ``k`` to get a return list of length at\n least ``k``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[2],[2,1]]).to_exp()\n ([2], [0, 1], [1, 1])\n sage: PartitionTuple([[1,1],[2,2,2,2],[2,1]]).to_exp()\n ([2], [0, 4], [1, 1])\n\n ' return tuple((self[c].to_exp(k) for c in range(len(self)))) def removable_cells(self): '\n Return a list of the removable cells of this partition tuple.\n\n All indices are of the form ``(k, r, c)``, where ``r`` is the\n row-index, ``c`` is the column index and ``k`` is the component.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[2],[2,1]]).removable_cells()\n [(0, 1, 0), (1, 0, 1), (2, 0, 1), (2, 1, 0)]\n sage: PartitionTuple([[1,1],[4,3],[2,1,1]]).removable_cells()\n [(0, 1, 0), (1, 0, 3), (1, 1, 2), (2, 0, 1), (2, 2, 0)]\n\n ' return [(k, r, c) for k in range(len(self)) for (r, c) in self[k].removable_cells()] corners = removable_cells def addable_cells(self): '\n Return a list of the removable cells of this partition tuple.\n\n All indices are of the form ``(k, r, c)``, where ``r`` is the\n row-index, ``c`` is the column index and ``k`` is the component.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[2],[2,1]]).addable_cells()\n [(0, 0, 1), (0, 2, 0), (1, 0, 2), (1, 1, 0), (2, 0, 2), (2, 1, 1), (2, 2, 0)]\n sage: PartitionTuple([[1,1],[4,3],[2,1,1]]).addable_cells()\n [(0, 0, 1), (0, 2, 0), (1, 0, 4), (1, 1, 3), (1, 2, 0), (2, 0, 2), (2, 1, 1), (2, 3, 0)]\n\n ' return [(k, r, c) for k in range(len(self)) for (r, c) in self[k].addable_cells()] outside_corners = addable_cells def add_cell(self, k, r, c): '\n Return the partition tuple obtained by adding a cell in row ``r``,\n column ``c``, and component ``k``.\n\n This does not change ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[4,3],[2,1,1]]).add_cell(0,0,1)\n ([2, 1], [4, 3], [2, 1, 1])\n ' if ((k, r, c) in self.addable_cells()): mu = self.to_list() if (c == 0): mu[k].append(1) else: mu[k][r] += 1 return PartitionTuple(mu) else: raise ValueError(('%s is not an addable cell' % ((k, r, c),))) def remove_cell(self, k, r, c): '\n Return the partition tuple obtained by removing a cell in row ``r``,\n column ``c``, and component ``k``.\n\n This does not change ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[4,3],[2,1,1]]).remove_cell(0,1,0)\n ([1], [4, 3], [2, 1, 1])\n ' if ((k, r, c) in self.removable_cells()): mu = self.to_list() mu[k][r] -= 1 return PartitionTuple(mu) else: raise ValueError(('%s is not a removable cell' % ((k, r, c),))) def to_list(self): '\n Return ``self`` as a list of lists.\n\n EXAMPLES::\n\n sage: PartitionTuple([[1,1],[4,3],[2,1,1]]).to_list()\n [[1, 1], [4, 3], [2, 1, 1]]\n\n TESTS::\n\n sage: all(mu==PartitionTuple(mu.to_list()) for mu in PartitionTuples(4,4)) # needs sage.libs.flint\n True\n ' return [mu.to_list() for mu in self] def young_subgroup(self): '\n Return the corresponding Young, or parabolic, subgroup of the\n symmetric group.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[4,2],[1]]).young_subgroup() # needs sage.groups\n Permutation Group with generators [(), (8,9), (6,7), (5,6), (4,5), (1,2)]\n ' gens = [] m = 0 for comp in self: for row in comp: gens.extend([(c, (c + 1)) for c in range((m + 1), (m + row))]) m += row gens.append(list(range(1, (self.size() + 1)))) return PermutationGroup(gens) def young_subgroup_generators(self): '\n Return an indexing set for the generators of the corresponding Young\n subgroup.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[4,2],[1]]).young_subgroup_generators()\n [1, 4, 5, 6, 8]\n ' gens = [] m = 0 for comp in self: for row in comp: gens.extend([c for c in range((m + 1), (m + row))]) m += row return gens @cached_method def _initial_degree(self, e, multicharge): '\n Return the Brundan-Kleshchev-Wang degree of the initial tableau\n of shape ``self``.\n\n This degree depends only the shape of the tableau and it is\n used as the base case for computing the degrees of all tableau of\n shape ``self``, which is why this method is cached. See\n :meth:`sage.combinat.tableau.Tableau.degree` for more information.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[2,2]])._initial_degree(0,(0,0))\n 1\n sage: PartitionTuple([[2,1],[2,2]])._initial_degree(2,(0,0))\n 4\n sage: PartitionTuple([[2,1],[2,2]])._initial_degree(3,(0,0))\n 1\n sage: PartitionTuple([[2,1],[2,2]])._initial_degree(4,(0,0))\n 1\n ' if (e == 0): deg = 0 else: deg = sum((mu._initial_degree(e) for mu in self)) I = IntegerModRing(e) multires = [I(k) for k in multicharge] for (k, r, c) in self.cells(): res = I(((multicharge[k] - r) + c)) for l in range((k + 1), self.level()): if (res == multires[l]): deg += 1 return deg def degree(self, e): '\n Return the ``e``-th degree of ``self``.\n\n The `e`-th degree is the sum of the degrees of the standard\n tableaux of shape `\\lambda`. The `e`-th degree is the exponent\n of `\\Phi_e(q)` in the Gram determinant of the Specht module for a\n semisimple cyclotomic Hecke algebra of type `A` with parameter `q`.\n\n For this calculation the multicharge `(\\kappa_1, \\ldots, \\kappa_l)`\n is chosen so that `\\kappa_{r+1} - \\kappa_r > n`, where `n` is\n the :meth:`size` of `\\lambda` as this ensures that the Hecke algebra\n is semisimple.\n\n INPUT:\n\n - ``e`` -- an integer `e > 1`\n\n OUTPUT:\n\n A non-negative integer.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[2,2]]).degree(2)\n 532\n sage: PartitionTuple([[2,1],[2,2]]).degree(3)\n 259\n sage: PartitionTuple([[2,1],[2,2]]).degree(4)\n 196\n sage: PartitionTuple([[2,1],[2,2]]).degree(5)\n 105\n sage: PartitionTuple([[2,1],[2,2]]).degree(6)\n 105\n sage: PartitionTuple([[2,1],[2,2]]).degree(7)\n 0\n\n Therefore, the Gram determinant of `S(2,1|2,2)` when the Hecke parameter\n `q` is "generic" is\n\n .. MATH::\n\n q^N \\Phi_2(q)^{532}\\Phi_3(q)^{259}\\Phi_4(q)^{196}\\Phi_5(q)^{105}\\Phi_6(q)^{105}\n\n for some integer `N`. Compare with :meth:`prime_degree`.\n ' multicharge = tuple([(i * self.size()) for i in range(self.size())]) return sum((t.degree(e, multicharge) for t in self.standard_tableaux())) def prime_degree(self, p): '\n Return the ``p``-th prime degree of ``self``.\n\n The degree of a partition `\\lambda` is the sum of the `e`-degrees`\n of the standard tableaux of shape `\\lambda` (see :meth:`degree`),\n for `e` a power of the prime `p`. The prime degree gives the\n exponent of `p` in the Gram determinant of the integral Specht\n module of the symmetric group.\n\n The `p`-th degree is the sum of the degrees of the standard tableaux\n of shape `\\lambda`. The `p`-th degree is the exponent of `p` in the\n Gram determinant of a semisimple cyclotomic Hecke algebra of type `A`\n with parameter `q = 1`.\n\n As with :meth:`degree`, for this calculation the multicharge\n `(\\kappa_1, \\ldots, \\kappa_l)` is chosen so that\n `\\kappa_{r+1} - \\kappa_r > n`, where `n` is the :meth:`size`\n of `\\lambda` as this ensures that the Hecke algebra is semisimple.\n\n INPUT:\n\n - ``e`` -- an integer `e > 1`\n - ``multicharge`` -- an `l`-tuple of integers, where `l` is\n the :meth:`level` of ``self``\n\n OUTPUT:\n\n A non-negative integer\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,1],[2,2]]).prime_degree(2)\n 728\n sage: PartitionTuple([[2,1],[2,2]]).prime_degree(3)\n 259\n sage: PartitionTuple([[2,1],[2,2]]).prime_degree(5)\n 105\n sage: PartitionTuple([[2,1],[2,2]]).prime_degree(7)\n 0\n\n Therefore, the Gram determinant of `S(2,1|2,2)` when `q=1` is\n `2^{728} 3^{259}5^{105}`. Compare with :meth:`degree`.\n ' ps = [p] while ((ps[(- 1)] * p) < self.size()): ps.append((ps[(- 1)] * p)) multicharge = tuple([(i * self.size()) for i in range(self.size())]) return sum((t.degree(pk, multicharge) for pk in ps for t in self.standard_tableaux())) @cached_method def block(self, e, multicharge): '\n Return a dictionary `\\beta` that determines the block associated to\n the partition ``self`` and the\n :meth:`~sage.combinat.tableau_residues.ResidueSequence.quantum_characteristic` ``e``.\n\n INPUT:\n\n - ``e`` -- the quantum characteristic\n\n - ``multicharge`` -- the multicharge (default `(0,)`)\n\n OUTPUT:\n\n - a dictionary giving the multiplicities of the residues in the\n partition tuple ``self``\n\n In more detail, the value ``beta[i]`` is equal to the\n number of nodes of residue ``i``. This corresponds to\n the positive root\n\n .. MATH::\n\n \\sum_{i\\in I} \\beta_i \\alpha_i \\in Q^+,\n\n a element of the positive root lattice of the corresponding\n Kac-Moody algebra. See [DJM1998]_ and [BK2009]_ for more details.\n\n This is a useful statistics because two Specht modules for a cyclotomic\n Hecke algebra of type `A` belong to the same block if and only if they\n correspond to same element `\\beta` of the root lattice, given above.\n\n We return a dictionary because when the quantum characteristic is `0`,\n the Cartan type is `A_{\\infty}`, in which case the simple roots are\n indexed by the integers.\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,2],[2,2]]).block(0,(0,0))\n {-1: 2, 0: 4, 1: 2}\n sage: PartitionTuple([[2,2],[2,2]]).block(2,(0,0))\n {0: 4, 1: 4}\n sage: PartitionTuple([[2,2],[2,2]]).block(2,(0,1))\n {0: 4, 1: 4}\n sage: PartitionTuple([[2,2],[2,2]]).block(3,(0,2))\n {0: 3, 1: 2, 2: 3}\n sage: PartitionTuple([[2,2],[2,2]]).block(3,(0,2))\n {0: 3, 1: 2, 2: 3}\n sage: PartitionTuple([[2,2],[2,2]]).block(3,(3,2))\n {0: 3, 1: 2, 2: 3}\n sage: PartitionTuple([[2,2],[2,2]]).block(4,(0,0))\n {0: 4, 1: 2, 3: 2}\n ' block = {} Ie = IntegerModRing(e) for (k, r, c) in self.cells(): i = Ie(((multicharge[k] + c) - r)) block[i] = (block.get(i, 0) + 1) return block def defect(self, e, multicharge): '\n Return the ``e``-defect or the ``e``-weight ``self``.\n\n The `e`-defect is the number of (connected) `e`-rim hooks\n that can be removed from the partition.\n\n The defect of a partition tuple is given by\n\n .. MATH::\n\n \\text{defect}(\\beta) = (\\Lambda, \\beta) - \\tfrac12(\\beta, \\beta),\n\n where `\\Lambda = \\sum_r \\Lambda_{\\kappa_r}` for the multicharge\n `(\\kappa_1, \\ldots, \\kappa_{\\ell})` and\n `\\beta = \\sum_{(r,c)} \\alpha_{(c-r) \\pmod e}`, with the sum\n being over the cells in the partition.\n\n INPUT:\n\n - ``e`` -- the quantum characteristic\n\n - ``multicharge`` -- the multicharge (default `(0,)`)\n\n OUTPUT:\n\n - a non-negative integer, which is the defect of the block\n containing the partition tuple ``self``\n\n EXAMPLES::\n\n sage: PartitionTuple([[2,2],[2,2]]).defect(0,(0,0))\n 0\n sage: PartitionTuple([[2,2],[2,2]]).defect(2,(0,0))\n 8\n sage: PartitionTuple([[2,2],[2,2]]).defect(2,(0,1))\n 8\n sage: PartitionTuple([[2,2],[2,2]]).defect(3,(0,2))\n 5\n sage: PartitionTuple([[2,2],[2,2]]).defect(3,(0,2))\n 5\n sage: PartitionTuple([[2,2],[2,2]]).defect(3,(3,2))\n 2\n sage: PartitionTuple([[2,2],[2,2]]).defect(4,(0,0))\n 0\n ' beta = self.block(e, multicharge) Ie = IntegerModRing(e) return (sum((beta.get(r, 0) for r in multicharge)) - sum((((beta[r] ** 2) - (beta[r] * beta.get(Ie((r + 1)), 0))) for r in beta)))
class PartitionTuples(UniqueRepresentation, Parent): '\n Class of all partition tuples.\n\n For more information about partition tuples, see :class:`PartitionTuple`.\n\n This is a factory class which returns the appropriate parent based on\n the values of ``level``, ``size``, and ``regular``\n\n INPUT:\n\n - ``level`` -- the length of the tuple\n\n - ``size`` -- the total number of cells\n\n - ``regular`` -- a positive integer or a tuple of non-negative\n integers; if an integer, the highest multiplicity an entry may\n have in a component plus `1`\n\n If a level `k` is specified and ``regular`` is a tuple of integers\n `\\ell_1, \\ldots, \\ell_k`, then this specifies partition tuples `\\mu`\n such that `\\mu_i` is `\\ell_i`-regular, where `0` here\n represents `\\infty`-regular partitions (equivalently, partitions\n without restrictions). If ``regular`` is an integer `\\ell`, then\n we set `\\ell_i = \\ell` for all `i`.\n\n TESTS::\n\n sage: [ [2,1],[],[3] ] in PartitionTuples()\n True\n sage: ( [2,1],[],[3] ) in PartitionTuples()\n True\n sage: ( [] ) in PartitionTuples()\n True\n sage: PartitionTuples(level=1, regular=(0,))\n Partitions\n sage: PartitionTuples(level=1, size=3, regular=(0,))\n Partitions of the integer 3\n\n Check that :trac:`14145` has been fixed::\n\n sage: 1 in PartitionTuples()\n False\n ' @staticmethod def __classcall_private__(klass, level=None, size=None, regular=None): '\n Return the correct parent object based upon the input.\n\n TESTS::\n\n sage: PartitionTuples()\n Partition tuples\n sage: PartitionTuples(3)\n Partition tuples of level 3\n sage: PartitionTuples(size=3)\n Partition tuples of size 3\n sage: PartitionTuples(3,8)\n Partition tuples of level 3 and size 8\n sage: PartitionTuples(level=3, regular=(0,2,4))\n (0, 2, 4)-Regular partition tuples of level 3\n sage: PartitionTuples(level=1,regular=(4,)) is PartitionTuples(level=1, regular=4)\n True\n ' if ((level is not None) and ((not isinstance(level, (int, Integer))) or (level < 1))): raise ValueError('the level must be a positive integer') if ((size is not None) and ((not isinstance(size, (int, Integer))) or (size < 0))): raise ValueError('the size must be a non-negative integer') if isinstance(regular, (list, tuple)): if (level is None): raise ValueError('When no level is specified, regular must be a positive integer') if (len(regular) != level): raise ValueError('regular must be a list of length {}, got {}'.format(level, regular)) if (regular == 0): raise ValueError('regular must be a positive integer or a tuple of non-negative integers') if (level is None): if (size is None): if (regular is None): return PartitionTuples_all() return RegularPartitionTuples_all(regular) if (regular is None): return PartitionTuples_size(size) return RegularPartitionTuples_size(size, regular) elif (level == 1): if isinstance(regular, (list, tuple)): regular = regular[0] if (size is None): if ((regular is None) or (regular == 0)): return _Partitions return RegularPartitions_all(regular) if ((regular is None) or (regular == 0)): return Partitions_n(size) return RegularPartitions_n(size, regular) if (regular is not None): if (not isinstance(regular, (list, tuple))): regular = ((regular,) * level) else: regular = tuple(regular) if (size is None): if (regular is None): return PartitionTuples_level(level) return RegularPartitionTuples_level(level, regular) if (regular is None): return PartitionTuples_level_size(level, size) return RegularPartitionTuples_level_size(level, size, regular) Element = PartitionTuple options = Partitions.options _level = None _size = None def _element_constructor_(self, mu): '\n Constructs an element of :class:`PartitionTuple`.\n\n INPUT:\n\n - ``mu`` -- a tuple of partitions\n\n OUTPUT:\n\n - The corresponding :class:`PartitionTuple` object\n\n TESTS::\n\n sage: PartitionTuple([[2],[2],[]]).parent()\n Partition tuples\n sage: parts = PartitionTuples(3)\n sage: parts([[2,1],[1],[2,2,2]]).parent() is parts\n True\n sage: PartitionTuples._element_constructor_(PartitionTuples(), [[2,1],[3,2],[1,1,1]])\n ([2, 1], [3, 2], [1, 1, 1])\n sage: parts([[1,2]])\n Traceback (most recent call last):\n ...\n ValueError: [[1, 2]] is not a Partition tuples of level 3\n ' if ((mu == []) or (mu == ()) or (mu == [[]])): if (mu not in self): raise ValueError('{} is not a {}'.format(mu, self)) return self.element_class(self, [_Partitions([])]) try: mu = [_Partitions(mu)] except ValueError: try: mu = [_Partitions(nu) for nu in mu] except ValueError: raise ValueError('{} is not a {}'.format(mu, self)) if (mu not in self): raise ValueError('{} is not a {}'.format(mu, self)) return self.element_class(self, mu) def __contains__(self, mu): '\n Return ``True`` if `\\mu` is in ``self``.\n\n TESTS::\n\n sage: PartitionTuple([[3,2],[2]]) in PartitionTuples()\n True\n sage: PartitionTuple([[3,2],[],[],[],[2]]) in PartitionTuples()\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[2]]) in PartitionTuples()\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[3]]) in PartitionTuples()\n True\n sage: all(mu in PartitionTuples() for mu in PartitionTuples(3,8)) # needs sage.libs.flint\n True\n sage: [5,1,1] in PartitionTuples()\n True\n sage: [[5,1,1]] in PartitionTuples()\n True\n sage: la = Partition([3,3,1])\n sage: PT = PartitionTuples()\n sage: la in PT\n True\n sage: PT(la)\n ([3, 3, 1])\n\n Check that :trac:`14145` is fixed::\n\n sage: 1 in PartitionTuples()\n False\n ' if isinstance(mu, (PartitionTuple, Partition)): return True if isinstance(mu, (tuple, list)): if (not mu): return True if (mu[0] in ZZ): return (mu in _Partitions) return all(((m in _Partitions) for m in mu)) return False def __getitem__(self, r): '\n The default implementation of ``__getitem__()`` for enumerated sets\n does not allow slices, so we override it.\n\n EXAMPLES::\n\n sage: PartitionTuples()[10:20] # needs sage.libs.flint\n [([1, 1, 1]),\n ([2], []),\n ([1, 1], []),\n ([1], [1]),\n ([], [2]),\n ([], [1, 1]),\n ([1], [], []),\n ([], [1], []),\n ([], [], [1]),\n ([], [], [], [])]\n ' if isinstance(r, (int, Integer)): return self.unrank(r) elif isinstance(r, slice): start = (0 if (r.start is None) else r.start) stop = r.stop if ((stop is None) and (not self.is_finite())): raise ValueError('infinite set') else: raise ValueError('r must be an integer or a slice') count = 0 parts = [] for t in self: if (count == stop): break if (count >= start): parts.append(t) count += 1 if ((count == stop) or (stop is None)): return parts raise IndexError('value out of range') def level(self): '\n Return the level or ``None`` if it is not defined.\n\n EXAMPLES::\n\n sage: PartitionTuples().level() is None\n True\n sage: PartitionTuples(7).level()\n 7\n ' return self._level def size(self): '\n Return the size or ``None`` if it is not defined.\n\n EXAMPLES::\n\n sage: PartitionTuples().size() is None\n True\n sage: PartitionTuples(size=7).size()\n 7\n ' return self._size def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples().an_element()\n ([1, 1, 1, 1], [2, 1, 1], [3, 1], [4])\n ' return PartitionTuple(([1, 1, 1, 1], [2, 1, 1], [3, 1], [4]))
class PartitionTuples_all(PartitionTuples): '\n Class of partition tuples of a arbitrary level and arbitrary sum.\n ' def __init__(self): '\n Initializes the class.\n\n EXAMPLES::\n\n sage: TestSuite( PartitionTuples() ).run() # needs sage.libs.flint\n ' super().__init__(category=InfiniteEnumeratedSets()) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples()\n Partition tuples\n ' return 'Partition tuples' def __iter__(self): '\n Iterate through the infinite class of partition tuples of arbitrary\n level and size.\n\n EXAMPLES::\n\n sage: PartitionTuples()[:20] # needs sage.libs.flint\n [([]),\n ([1]),\n ([], []),\n ([2]),\n ([1, 1]),\n ([1], []),\n ([], [1]),\n ([], [], []),\n ([3]),\n ([2, 1]),\n ([1, 1, 1]),\n ([2], []),\n ([1, 1], []),\n ([1], [1]),\n ([], [2]),\n ([], [1, 1]),\n ([1], [], []),\n ([], [1], []),\n ([], [], [1]),\n ([], [], [], [])]\n ' for size in NN: for level in range((size + 1)): for mu in PartitionTuples_level_size((level + 1), (size - level)): (yield self._element_constructor_(mu)) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples().an_element()\n ([1, 1, 1, 1], [2, 1, 1], [3, 1], [4])\n ' return self.element_class(self, ([1, 1, 1, 1], [2, 1, 1], [3, 1], [4]))
class PartitionTuples_level(PartitionTuples): '\n Class of partition tuples of a fixed level, but summing to an arbitrary\n integer.\n ' def __init__(self, level, category=None): '\n Initializes this class.\n\n EXAMPLES::\n\n sage: PartitionTuples(4)\n Partition tuples of level 4\n sage: PartitionTuples(level=6)\n Partition tuples of level 6\n sage: TestSuite( PartitionTuples(level=4) ).run() # needs sage.libs.flint\n ' if (level not in NN): raise ValueError('level must be a non-negative integer') if (category is None): category = InfiniteEnumeratedSets() super().__init__(category=category) self._level = level def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(2)\n Partition tuples of level 2\n ' return 'Partition tuples of level {}'.format(self._level) def __contains__(self, mu): '\n Return ``True`` if `\\mu` is in ``self``.\n\n TESTS::\n\n sage: PartitionTuple([[3,2],[2]]) in PartitionTuples(2)\n True\n sage: PartitionTuple([[3,2],[2]]) in PartitionTuples(level=2)\n True\n sage: PartitionTuple([[2,2,1],[2]]) in PartitionTuples(level=2)\n True\n sage: PartitionTuple([[2,2,1],[],[2]]) in PartitionTuples(level=2)\n False\n sage: all(mu in PartitionTuples(3) for mu in PartitionTuples(3,8)) # needs sage.libs.flint\n True\n\n Check that :trac:`14145` is fixed::\n\n sage: 1 in PartitionTuples(level=2)\n False\n ' return (PartitionTuples.__contains__(self, mu) and (len(mu) == self._level)) def __iter__(self): '\n Iterate through the infinite class of partition tuples of fixed level.\n\n EXAMPLES::\n\n sage: parts = PartitionTuples(3)\n sage: [parts[k] for k in range(20)] # needs sage.libs.flint\n [([], [], []),\n ([1], [], []),\n ([], [1], []),\n ([], [], [1]),\n ([2], [], []),\n ([1, 1], [], []),\n ([1], [1], []),\n ([1], [], [1]),\n ([], [2], []),\n ([], [1, 1], []),\n ([], [1], [1]),\n ([], [], [2]),\n ([], [], [1, 1]),\n ([3], [], []),\n ([2, 1], [], []),\n ([1, 1, 1], [], []),\n ([2], [1], []),\n ([1, 1], [1], []),\n ([2], [], [1]),\n ([1, 1], [], [1])]\n ' for size in NN: for mu in PartitionTuples_level_size(self._level, size): (yield self.element_class(self, list(mu))) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=4).an_element()\n ([], [1], [2], [3])\n ' return self.element_class(self, tuple(([l] for l in range(self.level()))))
class PartitionTuples_size(PartitionTuples): '\n Class of partition tuples of a fixed size, but arbitrary level.\n ' def __init__(self, size): '\n Initialize this class.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=4)\n Partition tuples of size 4\n sage: PartitionTuples(size=6)\n Partition tuples of size 6\n\n sage: TestSuite( PartitionTuples(size=6) ).run() # needs sage.libs.flint\n ' if (size not in NN): raise ValueError('size must be a non-negative integer') super().__init__(category=InfiniteEnumeratedSets()) self._size = size def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=4) # indirect doctest\n Partition tuples of size 4\n ' return 'Partition tuples of size {}'.format(self._size) def __contains__(self, mu): '\n Return ``True`` if `\\mu` is in ``self``.\n\n TESTS::\n\n sage: PartitionTuple([[3,2],[2]]) in PartitionTuples(size=7)\n True\n sage: PartitionTuple([[3,2],[],[],[],[2]]) in PartitionTuples(size=7)\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[2]]) in PartitionTuples(size=7)\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[3]]) in PartitionTuples(size=7)\n False\n sage: all(mu in PartitionTuples(size=8) for mu in PartitionTuples(3,8)) # needs sage.libs.flint\n True\n sage: [3, 2, 1] in PartitionTuples(size=7)\n False\n\n Check that :trac:`14145` is fixed::\n\n sage: 1 in PartitionTuples(size=7)\n False\n ' if (mu in _Partitions): return (self._size == sum(mu)) return (PartitionTuples.__contains__(self, mu) and (self._size == sum(map(sum, mu)))) def __iter__(self): '\n Iterates through the infinite class of partition tuples of a fixed size.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=3)[:20] # needs sage.libs.flint\n [([3]),\n ([2, 1]),\n ([1, 1, 1]),\n ([3], []),\n ([2, 1], []),\n ([1, 1, 1], []),\n ([2], [1]),\n ([1, 1], [1]),\n ([1], [2]),\n ([1], [1, 1]),\n ([], [3]),\n ([], [2, 1]),\n ([], [1, 1, 1]),\n ([3], [], []),\n ([2, 1], [], []),\n ([1, 1, 1], [], []),\n ([2], [1], []),\n ([1, 1], [1], []),\n ([2], [], [1]),\n ([1, 1], [], [1])]\n ' for level in NN: for mu in PartitionTuples_level_size(level, self._size): (yield self.element_class(self, list(mu))) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=4).an_element()\n ([1], [1], [1], [1])\n ' return self.element_class(self, tuple(([1] for l in range(self._size))))
class PartitionTuples_level_size(PartitionTuples): '\n Class of partition tuples with a fixed level and a fixed size.\n ' def __init__(self, level, size): '\n Initializes this class.\n\n EXAMPLES::\n\n sage: TestSuite( PartitionTuples(4,2) ).run() # needs sage.libs.flint sage.libs.pari\n sage: TestSuite( PartitionTuples(level=4, size=5) ).run() # needs sage.libs.flint sage.libs.pari\n ' if (not ((level in NN) and (size in NN))): raise ValueError('n and level must be non-negative integers') super().__init__(category=FiniteEnumeratedSets()) self._level = level self._size = size def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(4,2)\n Partition tuples of level 4 and size 2\n sage: PartitionTuples(size=2,level=4)\n Partition tuples of level 4 and size 2\n ' return 'Partition tuples of level {} and size {}'.format(self._level, self._size) def __contains__(self, mu): '\n Return ``True`` if ``mu`` is in ``self``.\n\n TESTS::\n\n sage: PartitionTuple([[3,2],[2]]) in PartitionTuples(2,7)\n True\n sage: PartitionTuple([[3,2],[],[],[],[2]]) in PartitionTuples(5,7)\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[2]]) in PartitionTuples(5,7)\n True\n sage: PartitionTuple([[2,1],[],[1,1],[],[3]]) in PartitionTuples(2,8)\n False\n sage: all(mu in PartitionTuples(3,8) for mu in PartitionTuples(3,8)) # needs sage.libs.flint\n True\n\n Check that :trac:`14145` is fixed::\n\n sage: 1 in PartitionTuples(5,7)\n False\n ' if ((self._level == 1) and (mu in _Partitions)): return (self._size == sum(mu)) return (PartitionTuples.__contains__(self, mu) and (self._level == len(mu)) and (self._size == sum(map(sum, mu)))) def __iter__(self): '\n Iterates through the finite class of partition tuples of a fixed level\n and a fixed size.\n\n EXAMPLES::\n\n sage: # needs sage.libs.flint\n sage: PartitionTuples(2,0).list() #indirect doctest\n [([], [])]\n sage: PartitionTuples(2,1).list() #indirect doctest\n [([1], []), ([], [1])]\n sage: PartitionTuples(2,2).list() #indirect doctest\n [([2], []), ([1, 1], []), ([1], [1]), ([], [2]), ([], [1, 1])]\n sage: PartitionTuples(3,2).list() #indirect doctest\n [([2], [], []),\n ([1, 1], [], []),\n ([1], [1], []),\n ([1], [], [1]),\n ([], [2], []),\n ([], [1, 1], []),\n ([], [1], [1]),\n ([], [], [2]),\n ([], [], [1, 1])]\n ' p = [Partitions_n(i) for i in range((self._size + 1))] for iv in IntegerVectors(self._size, self._level): for cp in itertools.product(*[p[i] for i in iv]): (yield self._element_constructor_(cp)) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=4,size=4).an_element()\n ([1], [], [], [3])\n ' mu = [[] for _ in itertools.repeat(None, self._level)] if (self._size > 0): if (self._level == 1): mu = [(self._size - 1), 1] else: mu[0] = [1] mu[(- 1)] = [(self._size - 1)] return self.element_class(self, mu) def cardinality(self): '\n Return the number of ``level``-tuples of partitions of size ``n``.\n\n Wraps a pari function call using :pari:`eta`.\n\n EXAMPLES::\n\n sage: PartitionTuples(2,3).cardinality() # needs sage.libs.pari\n 10\n sage: PartitionTuples(2,8).cardinality() # needs sage.libs.pari\n 185\n\n TESTS:\n\n The following calls used to fail (:trac:`11476`)::\n\n sage: # needs sage.libs.pari\n sage: PartitionTuples(17,2).cardinality()\n 170\n sage: PartitionTuples(2,17).cardinality()\n 8470\n sage: PartitionTuples(100,13).cardinality()\n 110320020147886800\n sage: PartitionTuples(13,90).cardinality()\n 91506473741200186152352843611\n\n These answers were checked against Gap4 (the last of which takes an\n awful long time for gap to compute).\n ' eta = pari(f'Ser(x,x,{self.size()})').eta() return ZZ((1 / (eta ** self.level())).polcoef(self.size(), pari('x'))) def __setstate__(self, state): '\n In order to maintain backwards compatibility and be able to unpickle a\n old pickle from PartitionTuples_nk we have to override the default\n ``__setstate__``.\n\n TESTS::\n\n sage: loads(b"x\\x9cM\\x90\\xcdN\\xc30\\x0c\\x80\\xd5\\xc1\\x06\\xeb\\x80\\xf1{\\xe0\\r\\xe0\\xd2\\x0b\\x07\\x1e\\x02)B\\x88\\x9c-7\\xb5\\xba\\xa8MR\')\\x12\\x07$8p\\xe0\\xadq\\x996q\\xb1b\\xfb\\xb3\\xf59\\x9f3\\x93\\xb0\\xa5\\xca\\x04W[\\x8f\\xb9\\x1a0f\\x9bm\\xf0\\xe5\\xf3\\xee\\xf5:\\x0e=%\\xf0]\\xc9\\xc5\\xfd\\x17\\xcf>\\xf8\\xe0N_\\x83\\xf5\\xd2\\xc5\\x1e\\xd0L\\x10\\xf46e>T\\xba\\x04r55\\x8d\\xf5-\\xcf\\x95p&\\xf87\\x8a\\x19\\x1c\\xe5Mh\\xc0\\xa3#^(\\xbd\\x00\\xd3`F>Rz\\t\\x063\\xb5!\\xbe\\xf3\\xf1\\xd4\\x98\\x90\\xc4K\\xa5\\x0b\\xbf\\xb5\\x8b\\xb2,U\\xd6\\x0bD\\xb1t\\xd8\\x11\\xec\\x12.u\\xf1\\xf0\\xfd\\xc2+\\xbd\\x82\\x96<E\\xcc!&>Qz\\x0e5&\\xe2S\\xa5\\xd70X\\xd3\\xf5\\x04\\xe2\\x91\\xc4\\x95\\xcf\\x9e\\n\\x11\\xa3\\x9e\\x1c\\xf9<\\t\\xa6\\x1cG#\\x83\\xbcV\\xfaf\\x7f\\xd9\\xce\\xfc\\xef\\xb4s\\xa5o\\xf7#\\x13\\x01\\x03\\xa6$!J\\x81/~t\\xd1m\\xc4\\xe5Q\\\\.\\xff\\xfd\\x8e\\t\\x14\\rmW\\\\\\xa9\\xb1\\xae~\\x01/\\x8f\\x85\\x02")\n Partition tuples of level 7 and size 3\n sage: loads(dumps( PartitionTuples(7,3) )) # indirect doctest for unpickling a Tableau element\n Partition tuples of level 7 and size 3\n ' if isinstance(state, dict): parts = PartitionTuples(state['k'], state['n']) self.__class__ = parts.__class__ self.__dict__ = parts.__dict__ else: super().__setstate__(state)
class RegularPartitionTuples(PartitionTuples): '\n Abstract base class for `\\ell`-regular partition tuples.\n ' def __init__(self, regular, **kwds): '\n Initialize ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(regular=3)\n sage: TestSuite(RPT).run() # needs sage.libs.flint\n ' if ((regular not in ZZ) or (regular < 1)): raise ValueError('regular must be an integer greater than 1') self._ell = regular PartitionTuples.__init__(self, **kwds) def __contains__(self, mu): '\n Check if ``mu`` is an `\\ell`-regular partition tuple.\n\n TESTS::\n\n sage: RPT = PartitionTuples(regular=2)\n sage: [[11,1], [2]] in RPT\n True\n sage: Partition([4,1]) in RPT\n True\n sage: [5,4,3,2,1] in RPT\n True\n sage: [[6,3,1], [], [], [3,1], [1], [1], [1]] in RPT\n True\n sage: [[10], [1], [1,1], [4,2]] in RPT\n False\n sage: [[5,2], [17, 1], [], [3,3,1], [1,1]] in RPT\n False\n sage: RPT = PartitionTuples(4,2,3)\n sage: elt = RPT([[1], [], [], [1]])\n sage: elt in RPT\n True\n ' if (not PartitionTuples.__contains__(self, mu)): return False if isinstance(mu, Partition): return (max((mu.to_exp() + [0])) < self._ell) if isinstance(mu, PartitionTuple): return all(((max((nu.to_exp() + [0])) < self._ell) for nu in mu)) if (not mu): return True if (mu in _Partitions): return all(((mu.count(i) < self._ell) for i in set(mu) if (i > 0))) return all(((list(nu).count(i) < self._ell) for nu in mu for i in set(nu) if (i > 0))) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples(regular=2).an_element()\n ([1], [], [], [2])\n ' if (self._level is None): lvl = 4 else: lvl = self._level if (self._size is None): size = 3 else: size = self._size elt = RegularPartitionTuples_level_size(lvl, size, self._ell).an_element() return self.element_class(self, list(elt))
class RegularPartitionTuples_all(RegularPartitionTuples): '\n Class of `\\ell`-regular partition tuples.\n ' def __init__(self, regular): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: RPT = PartitionTuples(regular=3)\n sage: TestSuite(RPT).run() # needs sage.libs.flint\n ' RegularPartitionTuples.__init__(self, regular, category=InfiniteEnumeratedSets()) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(regular=3)\n 3-Regular partition tuples\n ' return '{}-Regular partition tuples'.format(self._ell) def __iter__(self): '\n Iterate through the class of `\\ell`-regular partition tuples.\n\n EXAMPLES::\n\n sage: PartitionTuples(regular=2)[:20] # needs sage.libs.flint\n [([]),\n ([], []),\n ([1]),\n ([], [], []),\n ([1], []),\n ([], [1]),\n ([2]),\n ([], [], [], []),\n ([1], [], []),\n ([], [1], []),\n ([], [], [1]),\n ([2], []),\n ([1], [1]),\n ([], [2]),\n ([3]),\n ([2, 1]),\n ([], [], [], [], []),\n ([1], [], [], []),\n ([], [1], [], []),\n ([], [], [1], [])]\n ' for N in NN: for size in range((N + 1)): for mu in RegularPartitionTuples_level_size(((N - size) + 1), size, self._ell): (yield self.element_class(self, list(mu)))
class RegularPartitionTuples_level(PartitionTuples_level): '\n Regular Partition tuples of a fixed level.\n\n INPUT:\n\n - ``level`` -- a non-negative Integer; the level\n - ``regular`` -- a positive integer or a tuple of non-negative\n integers; if an integer, the highest multiplicity an entry may\n have in a component plus `1` with `0` representing `\\infty`-regular\n (equivalently, partitions without restrictions)\n\n ``regular`` is a tuple of integers `(\\ell_1, \\ldots, \\ell_k)` that\n specifies partition tuples `\\mu` such that `\\mu_i` is `\\ell_i`-regular.\n If ``regular`` is an integer `\\ell`, then we set `\\ell_i = \\ell` for\n all `i`.\n\n EXAMPLES::\n\n sage: RPT = PartitionTuples(level=4, regular=(2,3,0,2))\n sage: RPT[:24] # needs sage.libs.flint\n [([], [], [], []),\n ([1], [], [], []),\n ([], [1], [], []),\n ([], [], [1], []),\n ([], [], [], [1]),\n ([2], [], [], []),\n ([1], [1], [], []),\n ([1], [], [1], []),\n ([1], [], [], [1]),\n ([], [2], [], []),\n ([], [1, 1], [], []),\n ([], [1], [1], []),\n ([], [1], [], [1]),\n ([], [], [2], []),\n ([], [], [1, 1], []),\n ([], [], [1], [1]),\n ([], [], [], [2]),\n ([3], [], [], []),\n ([2, 1], [], [], []),\n ([2], [1], [], []),\n ([2], [], [1], []),\n ([2], [], [], [1]),\n ([1], [2], [], []),\n ([1], [1, 1], [], [])]\n sage: [[1,1],[3],[5,5,5],[7,2]] in RPT\n False\n sage: [[3,1],[3],[5,5,5],[7,2]] in RPT\n True\n sage: [[3,1],[3],[5,5,5]] in RPT\n False\n ' def __init__(self, level, regular): '\n Initialize ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(level=2, regular=(0,0))\n sage: RPT.category()\n Category of infinite enumerated sets\n sage: RPT = PartitionTuples(level=4, regular=3)\n sage: TestSuite(RPT).run() # needs sage.libs.flint\n ' if (level not in NN): raise ValueError('level must be a non-negative integer') if (not isinstance(regular, tuple)): regular = ((regular,) * level) if any(((r != 1) for r in regular)): category = InfiniteEnumeratedSets() else: category = FiniteEnumeratedSets() if any(((r not in NN) for r in regular)): raise ValueError('regular must be a tuple of non-negative integers') if (len(regular) != level): raise ValueError('regular must be a tuple with length {}'.format(level)) PartitionTuples_level.__init__(self, level, category=category) self._ell = regular def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=4, regular=3)\n 3-Regular partition tuples of level 4\n sage: PartitionTuples(level=4, regular=(2,3,0,2))\n (2, 3, 0, 2)-Regular partition tuples of level 4\n ' if (self._ell[1:] == self._ell[:(- 1)]): return '{}-Regular partition tuples of level {}'.format(self._ell[0], self._level) return '{}-Regular partition tuples of level {}'.format(self._ell, self._level) def __contains__(self, mu): '\n Return ``True`` if ``mu`` is in ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(level=4, regular=2)\n sage: [[4,2,1], [], [2], [2]] in RPT\n True\n sage: [[10], [1], [1,1], [4,2]] in RPT\n False\n sage: [[5,2], [], [3,3,1], [1,1]] in RPT\n False\n sage: [4, 3, 2] in RPT\n False\n\n sage: RPT = PartitionTuples(level=3, regular=(2,1,4))\n sage: [[4], [2], [5]] in RPT\n False\n sage: [[4], [], [5]] in RPT\n True\n sage: [[4,3], [], [5]] in RPT\n True\n sage: [[4,4], [], [5]] in RPT\n False\n sage: [[4,3], [5]] in RPT\n False\n sage: [5, 4, 3] in RPT\n False\n sage: [] in RPT\n False\n sage: [[], [], []] in RPT\n True\n sage: [[], [], [], [2]] in RPT\n False\n\n sage: from sage.combinat.partition_tuple import RegularPartitionTuples_level\n sage: RPT = RegularPartitionTuples_level(1, (3,)); RPT\n 3-Regular partition tuples of level 1\n sage: [[2,2]] in RPT\n True\n sage: [[2,2,2]] in RPT\n False\n ' if (self._level == 1): try: if (mu[0] in ZZ): return (mu in RegularPartitions_all(self._ell[0])) except (TypeError, ValueError): return False return (mu[0] in RegularPartitions_all(self._ell[0])) if (mu not in PartitionTuples_level(self._level)): return False if isinstance(mu, Partition): return False if isinstance(mu, PartitionTuple): return all(((max((p.to_exp() + [0])) < ell) for (p, ell) in zip(mu, self._ell) if (ell > 0))) return all(((p in RegularPartitions_all(ell)) for (p, ell) in zip(mu, self._ell) if (ell > 0))) def __iter__(self): '\n Iterate through the class of `\\ell`-regular partition tuples\n of a fixed level.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=3, regular=(2,1,4))[:24] # needs sage.libs.flint\n [([], [], []),\n ([1], [], []),\n ([], [], [1]),\n ([2], [], []),\n ([1], [], [1]),\n ([], [], [2]),\n ([], [], [1, 1]),\n ([3], [], []),\n ([2, 1], [], []),\n ([2], [], [1]),\n ([1], [], [2]),\n ([1], [], [1, 1]),\n ([], [], [3]),\n ([], [], [2, 1]),\n ([], [], [1, 1, 1]),\n ([4], [], []),\n ([3, 1], [], []),\n ([3], [], [1]),\n ([2, 1], [], [1]),\n ([2], [], [2]),\n ([2], [], [1, 1]),\n ([1], [], [3]),\n ([1], [], [2, 1]),\n ([1], [], [1, 1, 1])]\n sage: PartitionTuples(level=4, regular=2)[:20] # needs sage.libs.flint\n [([], [], [], []),\n ([1], [], [], []),\n ([], [1], [], []),\n ([], [], [1], []),\n ([], [], [], [1]),\n ([2], [], [], []),\n ([1], [1], [], []),\n ([1], [], [1], []),\n ([1], [], [], [1]),\n ([], [2], [], []),\n ([], [1], [1], []),\n ([], [1], [], [1]),\n ([], [], [2], []),\n ([], [], [1], [1]),\n ([], [], [], [2]),\n ([3], [], [], []),\n ([2, 1], [], [], []),\n ([2], [1], [], []),\n ([2], [], [1], []),\n ([2], [], [], [1])]\n ' for size in NN: for mu in RegularPartitionTuples_level_size(self._level, size, self._ell): (yield self.element_class(self, list(mu)))
class RegularPartitionTuples_size(RegularPartitionTuples): '\n Class of `\\ell`-regular partition tuples with a fixed size.\n ' def __init__(self, size, regular): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: RPT = PartitionTuples(size=4, regular=3)\n sage: TestSuite(RPT).run() # needs sage.libs.flint\n ' if (size not in NN): raise ValueError('size must be a non-negative integer') RegularPartitionTuples.__init__(self, regular, category=InfiniteEnumeratedSets()) self._size = size def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=4, regular=3)\n 3-Regular partition tuples of size 4\n ' return '{}-Regular partition tuples of size {}'.format(self._ell, self._size) def __contains__(self, mu): '\n Return ``True`` if ``mu`` is in ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(size=4, regular=2)\n sage: [[2, 1], [1]] in RPT\n True\n sage: [3, 1] in RPT\n True\n sage: [[1], [], [], [2,1]] in RPT\n True\n sage: [[1], [1], [1], [1]] in RPT\n True\n sage: [[1], [1,1,1]] in RPT\n False\n sage: [[2,1,1]] in RPT\n False\n sage: [2,1,1] in RPT\n False\n sage: RPT = PartitionTuples(size=7, regular=2)\n sage: [[], [3,2,2,1], [1], [1]] in RPT\n False\n sage: RPT = PartitionTuples(size=9, regular=2)\n sage: [4, 3, 2] in RPT\n True\n ' return (((mu in RegularPartitions_all(self._ell)) and (self._size == sum(mu))) or (RegularPartitionTuples.__contains__(self, mu) and (self._size == sum(map(sum, mu))))) def __iter__(self): '\n Iterate through the class of `\\ell`-regular partition tuples\n of a fixed size.\n\n EXAMPLES::\n\n sage: PartitionTuples(size=4, regular=2)[:10] # needs sage.libs.flint\n [([4]),\n ([3, 1]),\n ([4], []),\n ([3, 1], []),\n ([3], [1]),\n ([2, 1], [1]),\n ([2], [2]),\n ([1], [3]),\n ([1], [2, 1]),\n ([], [4])]\n ' for level in PositiveIntegers(): for mu in RegularPartitionTuples_level_size(level, self._size, self._ell): (yield self.element_class(self, list(mu)))
class RegularPartitionTuples_level_size(PartitionTuples_level_size): '\n Class of `\\ell`-regular partition tuples with a fixed level and\n a fixed size.\n\n INPUT:\n\n - ``level`` -- a non-negative Integer; the level\n - ``size`` -- a non-negative Integer; the size\n - ``regular`` -- a positive integer or a tuple of non-negative\n integers; if an integer, the highest multiplicity an entry may\n have in a component plus `1` with `0` representing `\\infty`-regular\n (equivalently, partitions without restrictions)\n\n ``regular`` is a tuple of integers `(\\ell_1, \\ldots, \\ell_k)` that\n specifies partition tuples `\\mu` such that `\\mu_i` is `\\ell_i`-regular.\n If ``regular`` is an integer `\\ell`, then we set `\\ell_i = \\ell` for\n all `i`.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=3, size=7, regular=(2,1,3))[0:24] # needs sage.libs.flint\n [([7], [], []),\n ([6, 1], [], []),\n ([5, 2], [], []),\n ([4, 3], [], []),\n ([4, 2, 1], [], []),\n ([6], [], [1]),\n ([5, 1], [], [1]),\n ([4, 2], [], [1]),\n ([3, 2, 1], [], [1]),\n ([5], [], [2]),\n ([5], [], [1, 1]),\n ([4, 1], [], [2]),\n ([4, 1], [], [1, 1]),\n ([3, 2], [], [2]),\n ([3, 2], [], [1, 1]),\n ([4], [], [3]),\n ([4], [], [2, 1]),\n ([3, 1], [], [3]),\n ([3, 1], [], [2, 1]),\n ([3], [], [4]),\n ([3], [], [3, 1]),\n ([3], [], [2, 2]),\n ([3], [], [2, 1, 1]),\n ([2, 1], [], [4])]\n ' def __init__(self, level, size, regular): '\n Initialize ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(4,2,3)\n sage: TestSuite(RPT).run() # needs sage.libs.flint sage.libs.pari\n ' if (size not in NN): raise ValueError('size must be a non-negative integer') if (not ((level in ZZ) and (level > 0))): raise ValueError('level must be a positive integer') if (not isinstance(regular, tuple)): regular = ((regular,) * level) if (len(regular) != level): raise ValueError(f'regular must be a list with length {level}') if any(((i not in NN) for i in regular)): raise ValueError('regular must be a list of non-negative integers') PartitionTuples_level_size.__init__(self, level, size) self._ell = regular def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=3, size=7, regular=(2,1,4))\n (2, 1, 4)-Regular partition tuples of level 3 and size 7\n sage: PartitionTuples(4,2,3)\n 3-Regular partition tuples of level 4 and size 2\n sage: PartitionTuples(size=2,level=4,regular=3)\n 3-Regular partition tuples of level 4 and size 2\n ' if (self._ell[1:] == self._ell[:(- 1)]): return '{}-Regular partition tuples of level {} and size {}'.format(self._ell[0], self._level, self._size) return '{}-Regular partition tuples of level {} and size {}'.format(self._ell, self._level, self._size) def __contains__(self, mu): '\n Return ``True`` if `\\mu` is in ``self``.\n\n TESTS::\n\n sage: RPT = PartitionTuples(level=3, size=7, regular=(2,1,4))\n sage: RPT\n (2, 1, 4)-Regular partition tuples of level 3 and size 7\n sage: [[3,1],[],[3]] in RPT\n True\n sage: [[3],[1],[3]] in RPT\n False\n sage: [[3,2],[],[3]] in RPT\n False\n sage: [[3,3],[],[1]] in RPT\n False\n sage: RPT = PartitionTuples(4,3,2)\n sage: [[], [], [2], [1]] in RPT\n True\n sage: [[1], [1], [], [1]] in RPT\n True\n sage: [[1,1,1], [], [], []] in RPT\n False\n sage: RPT = PartitionTuples(9, 3, 2)\n sage: [4, 3, 2] in RPT\n False\n ' if (mu not in RegularPartitionTuples_level(self._level, self._ell)): return False return (self._size == sum(map(sum, mu))) def __iter__(self): '\n Iterate through the finite class of `\\ell`-regular partition tuples\n of a fixed level and a fixed size.\n\n EXAMPLES::\n\n sage: list(PartitionTuples(3,3,2)) # needs sage.libs.pari\n [([3], [], []),\n ([2, 1], [], []),\n ([2], [1], []),\n ([2], [], [1]),\n ([1], [2], []),\n ([1], [1], [1]),\n ([1], [], [2]),\n ([], [3], []),\n ([], [2, 1], []),\n ([], [2], [1]),\n ([], [1], [2]),\n ([], [], [3]),\n ([], [], [2, 1])]\n ' for iv in IntegerVectors(self._size, self._level): p = [(RegularPartitions_n(v, ell) if (ell > 0) else Partitions_n(v)) for (v, ell) in zip(iv, self._ell)] for cp in itertools.product(*[p[i] for i in range(self._level)]): (yield self._element_constructor_(cp)) def _an_element_(self): '\n Return a generic element.\n\n EXAMPLES::\n\n sage: PartitionTuples(level=4, size=4, regular=3).an_element()\n ([1], [], [], [3])\n ' mu = [[] for _ in itertools.repeat(None, self._level)] if (self._size > 0): if (self._level == 1): mu = [[(self._size - 1), 1]] else: mu[0] = [1] mu[(- 1)] = [(self._size - 1)] return self.element_class(self, mu)
class DyckPath(PathTableau): '\n An instance is the sequence of nonnegative\n integers given by the heights of a Dyck word.\n\n INPUT:\n\n * a sequence of nonnegative integers\n * a two row standard skew tableau\n * a Dyck word\n * a noncrossing perfect matching\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([0,1,2,1,0])\n [0, 1, 2, 1, 0]\n\n sage: w = DyckWord([1,1,0,0])\n sage: path_tableaux.DyckPath(w)\n [0, 1, 2, 1, 0]\n\n sage: p = PerfectMatching([(1,2), (3,4)])\n sage: path_tableaux.DyckPath(p)\n [0, 1, 0, 1, 0]\n\n sage: t = Tableau([[1,2,4],[3,5,6]])\n sage: path_tableaux.DyckPath(t)\n [0, 1, 2, 1, 2, 1, 0]\n\n sage: st = SkewTableau([[None, 1,4],[2,3]])\n sage: path_tableaux.DyckPath(st)\n [1, 2, 1, 0, 1]\n\n Here we illustrate the slogan that promotion = rotation::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.to_perfect_matching()\n [(0, 5), (1, 4), (2, 3)]\n\n sage: t = t.promotion()\n sage: t.to_perfect_matching()\n [(0, 3), (1, 2), (4, 5)]\n\n sage: t = t.promotion()\n sage: t.to_perfect_matching()\n [(0, 1), (2, 5), (3, 4)]\n\n sage: t = t.promotion()\n sage: t.to_perfect_matching()\n [(0, 5), (1, 4), (2, 3)]\n ' @staticmethod def __classcall_private__(cls, ot): '\n This ensures that a tableau is only ever constructed as an\n ``element_class`` call of an appropriate parent.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,1,0])\n\n sage: t.parent()\n <sage.combinat.path_tableaux.dyck_path.DyckPaths_with_category object at ...>\n ' return DyckPaths()(ot) def __init__(self, parent, ot, check=True): '\n Initialize a Dyck path.\n\n TESTS::\n\n sage: D = path_tableaux.DyckPath(Tableau([[1,2], [3,4]]))\n sage: TestSuite(D).run()\n\n sage: D = path_tableaux.DyckPath(PerfectMatching([(1,4), (2,3), (5,6)]))\n sage: TestSuite(D).run()\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: TestSuite(t).run()\n\n sage: path_tableaux.DyckPath(PerfectMatching([(1, 3), (2, 4), (5, 6)]))\n Traceback (most recent call last):\n ...\n ValueError: the perfect matching must be non crossing\n sage: path_tableaux.DyckPath(Tableau([[1,2,5],[3,5,6]]))\n Traceback (most recent call last):\n ...\n ValueError: the tableau must be standard\n sage: path_tableaux.DyckPath(Tableau([[1,2,4],[3,5,6],[7]]))\n Traceback (most recent call last):\n ...\n ValueError: the tableau must have at most two rows\n sage: path_tableaux.DyckPath(SkewTableau([[None, 1,4],[2,3],[5]]))\n Traceback (most recent call last):\n ...\n ValueError: the skew tableau must have at most two rows\n sage: path_tableaux.DyckPath([0,1,2.5,1,0])\n Traceback (most recent call last):\n ...\n ValueError: [0, 1, 2.50000000000000, 1, 0] is not a sequence of integers\n sage: path_tableaux.DyckPath(Partition([3,2,1]))\n Traceback (most recent call last):\n ...\n ValueError: invalid input [3, 2, 1]\n ' w = None if isinstance(ot, DyckWord): w = ot.heights() elif isinstance(ot, PerfectMatching): if ot.is_noncrossing(): u = ([1] * ot.size()) for a in ot.arcs(): u[(a[1] - 1)] = 0 w = DyckWord(u).heights() else: raise ValueError('the perfect matching must be non crossing') elif isinstance(ot, Tableau): if (len(ot) > 2): raise ValueError('the tableau must have at most two rows') if ot.is_standard(): u = ([1] * ot.size()) for i in ot[1]: u[(i - 1)] = 0 w = DyckWord(u).heights() else: raise ValueError('the tableau must be standard') elif isinstance(ot, SkewTableau): if (len(ot) > 2): raise ValueError('the skew tableau must have at most two rows') c = ot.to_chain() w = ([0] * len(c)) for (i, a) in enumerate(c): if (len(a) == 1): w[i] = a[0] else: w[i] = (a[0] - a[1]) elif isinstance(ot, (list, tuple)): try: w = tuple([Integer(a) for a in ot]) except TypeError: raise ValueError(('%s is not a sequence of integers' % ot)) if (w is None): raise ValueError(('invalid input %s' % ot)) PathTableau.__init__(self, parent, w, check=check) def check(self): '\n Check that ``self`` is a valid path.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([0,1,0,-1,0]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: [0, 1, 0, -1, 0] has a negative entry\n\n sage: path_tableaux.DyckPath([0,1,3,1,0]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: [0, 1, 3, 1, 0] is not a Dyck path\n ' if any(((a < 0) for a in self)): raise ValueError(('%s has a negative entry' % str(self))) for i in range((len(self) - 1)): if (abs((self[(i + 1)] - self[i])) != 1): raise ValueError(('%s is not a Dyck path' % str(self))) def local_rule(self, i): '\n This has input a list of objects. This method first takes\n the list of objects of length three consisting of the `(i-1)`-st,\n `i`-th and `(i+1)`-term and applies the rule. It then replaces\n the `i`-th object by the object returned by the rule.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.local_rule(3)\n [0, 1, 2, 1, 2, 1, 0]\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.local_rule(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not a valid integer\n sage: t.local_rule(5)\n [0, 1, 2, 3, 2, 1, 0]\n sage: t.local_rule(6)\n Traceback (most recent call last):\n ...\n ValueError: 6 is not a valid integer\n ' def _rule(x): '\n This is the rule on a sequence of three letters.\n ' return abs(((x[0] - x[1]) + x[2])) if (not ((i > 0) and (i < (len(self) - 1)))): raise ValueError(('%d is not a valid integer' % i)) with self.clone() as result: result[i] = _rule(self[(i - 1):(i + 2)]) return result def is_skew(self): '\n Return ``True`` if ``self`` is skew and ``False`` if not.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([0,1,2,1]).is_skew()\n False\n\n sage: path_tableaux.DyckPath([1,0,1,2,1]).is_skew()\n True\n ' return (self[0] != 0) @combinatorial_map(name='to Dyck word') def to_DyckWord(self): '\n Converts ``self`` to a Dyck word.\n\n EXAMPLES::\n\n sage: c = path_tableaux.DyckPath([0,1,2,1,0])\n sage: c.to_DyckWord()\n [1, 1, 0, 0]\n ' return DyckWord(heights_sequence=list(self)) def descents(self): '\n Return the descent set of ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([0,1,2,1,2,1,0,1,0]).descents()\n {3, 6}\n ' result = set() for i in range(1, (len(self) - 1)): if ((self[i] < self[(i - 1)]) and (self[i] < self[(i + 1)])): result.add(i) return result def to_word(self): '\n Return the word in the alphabet `\\{0,1\\}` associated to ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([1,0,1,2,1]).to_word()\n [0, 1, 1, 0]\n ' return [(((self[(i + 1)] - self[i]) + 1) // 2) for i in range((self.size() - 1))] def to_perfect_matching(self): '\n Return the perfect matching associated to ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPath([0,1,2,1,2,1,0,1,0]).to_perfect_matching()\n [(0, 5), (1, 2), (3, 4), (6, 7)]\n\n TESTS::\n\n sage: path_tableaux.DyckPath([1,2,1,2,1,0,1]).to_perfect_matching()\n Traceback (most recent call last):\n ...\n ValueError: [1, 2, 1, 2, 1, 0, 1] does not start at 0\n ' if self.is_skew(): raise ValueError(('%s does not start at 0' % str(self))) w = self.to_word() y = DyckWord(w) pairs = set() for (i, a) in enumerate(y): c = y.associated_parenthesis(i) if (i < c): pairs.add((i, c)) return PerfectMatching(pairs) def to_tableau(self): '\n Return the skew tableau associated to ``self``.\n\n EXAMPLES::\n\n sage: T = path_tableaux.DyckPath([0,1,2,3,2,3])\n sage: T.to_tableau()\n [[1, 2, 3, 5], [4]]\n\n sage: U = path_tableaux.DyckPath([2,3,2,3])\n sage: U.to_tableau()\n [[None, None, 1, 3], [2]]\n ' w = self.to_word() top = [(i + 1) for (i, a) in enumerate(w) if (a == 1)] bot = [(i + 1) for (i, a) in enumerate(w) if (a == 0)] if self.is_skew(): return SkewTableau([(([None] * self[0]) + top), bot]) else: return StandardTableau([top, bot])
class DyckPaths(PathTableaux): '\n The parent class for DyckPath.\n ' def _an_element_(self): '\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.DyckPaths()._an_element_()\n [0, 1, 2, 1, 0]\n ' return DyckPath([0, 1, 2, 1, 0]) Element = DyckPath
class FriezePattern(PathTableau, metaclass=InheritComparisonClasscallMetaclass): "\n A frieze pattern.\n\n We encode a frieze pattern as a sequence in a fixed ground field.\n\n INPUT:\n\n - ``fp`` -- a sequence of elements of ``field``\n - ``field`` -- (default: ``QQ``) the ground field\n\n EXAMPLES::\n\n sage: t = path_tableaux.FriezePattern([1,2,1,2,3,1])\n sage: path_tableaux.CylindricalDiagram(t)\n [0, 1, 2, 1, 2, 3, 1, 0]\n [ , 0, 1, 1, 3, 5, 2, 1, 0]\n [ , , 0, 1, 4, 7, 3, 2, 1, 0]\n [ , , , 0, 1, 2, 1, 1, 1, 1, 0]\n [ , , , , 0, 1, 1, 2, 3, 4, 1, 0]\n [ , , , , , 0, 1, 3, 5, 7, 2, 1, 0]\n [ , , , , , , 0, 1, 2, 3, 1, 1, 1, 0]\n [ , , , , , , , 0, 1, 2, 1, 2, 3, 1, 0]\n\n sage: TestSuite(t).run()\n\n sage: t = path_tableaux.FriezePattern([1,2,7,5,3,7,4,1])\n sage: path_tableaux.CylindricalDiagram(t)\n [0, 1, 2, 7, 5, 3, 7, 4, 1, 0]\n [ , 0, 1, 4, 3, 2, 5, 3, 1, 1, 0]\n [ , , 0, 1, 1, 1, 3, 2, 1, 2, 1, 0]\n [ , , , 0, 1, 2, 7, 5, 3, 7, 4, 1, 0]\n [ , , , , 0, 1, 4, 3, 2, 5, 3, 1, 1, 0]\n [ , , , , , 0, 1, 1, 1, 3, 2, 1, 2, 1, 0]\n [ , , , , , , 0, 1, 2, 7, 5, 3, 7, 4, 1, 0]\n [ , , , , , , , 0, 1, 4, 3, 2, 5, 3, 1, 1, 0]\n [ , , , , , , , , 0, 1, 1, 1, 3, 2, 1, 2, 1, 0]\n [ , , , , , , , , , 0, 1, 2, 7, 5, 3, 7, 4, 1, 0]\n\n sage: TestSuite(t).run()\n\n sage: t = path_tableaux.FriezePattern([1,3,4,5,1])\n sage: path_tableaux.CylindricalDiagram(t)\n [ 0, 1, 3, 4, 5, 1, 0]\n [ , 0, 1, 5/3, 7/3, 2/3, 1, 0]\n [ , , 0, 1, 2, 1, 3, 1, 0]\n [ , , , 0, 1, 1, 4, 5/3, 1, 0]\n [ , , , , 0, 1, 5, 7/3, 2, 1, 0]\n [ , , , , , 0, 1, 2/3, 1, 1, 1, 0]\n [ , , , , , , 0, 1, 3, 4, 5, 1, 0]\n\n sage: TestSuite(t).run()\n\n This constructs the examples from [HJ18]_::\n\n sage: # needs sage.rings.number_field\n sage: x = polygen(ZZ, 'x')\n sage: K.<sqrt3> = NumberField(x^2 - 3)\n sage: t = path_tableaux.FriezePattern([1, sqrt3, 2, sqrt3, 1, 1], field=K)\n sage: path_tableaux.CylindricalDiagram(t)\n [ 0, 1, sqrt3, 2, sqrt3, 1, 1, 0]\n [ , 0, 1, sqrt3, 2, sqrt3, sqrt3 + 1, 1, 0]\n [ , , 0, 1, sqrt3, 2, sqrt3 + 2, sqrt3, 1, 0]\n [ , , , 0, 1, sqrt3, sqrt3 + 2, 2, sqrt3, 1, 0]\n [ , , , , 0, 1, sqrt3 + 1, sqrt3, 2, sqrt3, 1, 0]\n [ , , , , , 0, 1, 1, sqrt3, 2, sqrt3, 1, 0]\n [ , , , , , , 0, 1, sqrt3 + 1, sqrt3 + 2, sqrt3 + 2, sqrt3 + 1, 1, 0]\n [ , , , , , , , 0, 1, sqrt3, 2, sqrt3, 1, 1, 0]\n sage: TestSuite(t).run()\n\n sage: # needs sage.rings.number_field\n sage: K.<sqrt2> = NumberField(x^2 - 2)\n sage: t = path_tableaux.FriezePattern([1, sqrt2, 1, sqrt2, 3, 2*sqrt2, 5, 3*sqrt2, 1],\n ....: field=K)\n sage: path_tableaux.CylindricalDiagram(t)\n [ 0, 1, sqrt2, 1, sqrt2, 3, 2*sqrt2, 5, 3*sqrt2, 1, 0]\n [ , 0, 1, sqrt2, 3, 5*sqrt2, 7, 9*sqrt2, 11, 2*sqrt2, 1, 0]\n [ , , 0, 1, 2*sqrt2, 7, 5*sqrt2, 13, 8*sqrt2, 3, sqrt2, 1, 0]\n [ , , , 0, 1, 2*sqrt2, 3, 4*sqrt2, 5, sqrt2, 1, sqrt2, 1, 0]\n [ , , , , 0, 1, sqrt2, 3, 2*sqrt2, 1, sqrt2, 3, 2*sqrt2, 1, 0]\n [ , , , , , 0, 1, 2*sqrt2, 3, sqrt2, 3, 5*sqrt2, 7, 2*sqrt2, 1, 0]\n [ , , , , , , 0, 1, sqrt2, 1, 2*sqrt2, 7, 5*sqrt2, 3, sqrt2, 1, 0]\n [ , , , , , , , 0, 1, sqrt2, 5, 9*sqrt2, 13, 4*sqrt2, 3, 2*sqrt2, 1, 0]\n [ , , , , , , , , 0, 1, 3*sqrt2, 11, 8*sqrt2, 5, 2*sqrt2, 3, sqrt2, 1, 0]\n [ , , , , , , , , , 0, 1, 2*sqrt2, 3, sqrt2, 1, sqrt2, 1, sqrt2, 1, 0]\n [ , , , , , , , , , , 0, 1, sqrt2, 1, sqrt2, 3, 2*sqrt2, 5, 3*sqrt2, 1, 0]\n sage: TestSuite(t).run()\n " @staticmethod def __classcall_private__(cls, fp, field=QQ): "\n This is the preprocessing for creating friezes.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,1])\n [1, 2, 1, 2, 3, 1]\n\n TESTS::\n\n sage: path_tableaux.FriezePattern(2)\n Traceback (most recent call last):\n ...\n ValueError: invalid input 2\n\n sage: x = polygen(ZZ, 'x')\n sage: K.<sqrt3> = NumberField(x^2 - 3) # needs sage.rings.number_field\n sage: t = path_tableaux.FriezePattern([1,sqrt3,2,sqrt3,1,1]) # needs sage.rings.number_field\n Traceback (most recent call last):\n ...\n ValueError: [1, sqrt3, 2, sqrt3, 1, 1] is not a sequence in the field Rational Field\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,1], field=Integers())\n Traceback (most recent call last):\n ...\n ValueError: Integer Ring must be a field\n " if (field not in Fields()): raise ValueError(f'{field} must be a field') if isinstance(fp, (list, tuple)): try: fp = [field(a) for a in fp] except TypeError: raise ValueError(f'{fp} is not a sequence in the field {field}') else: raise ValueError(f'invalid input {fp}') fp.insert(0, field(0)) fp.append(field(0)) return FriezePatterns(field)(tuple(fp)) def check(self): '\n Check that ``self`` is a valid frieze pattern.\n\n TESTS::\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,1]) # indirect test\n [1, 2, 1, 2, 3, 1]\n ' pass def _repr_(self): '\n Return the string representation of ``self``.\n\n This removes the leading and trailing zero.\n\n TESTS::\n\n sage: t = path_tableaux.FriezePattern([1,2,1,2,3,1])\n sage: repr(t) == t._repr_() # indirect test\n True\n ' return repr(self[1:(- 1)]) def local_rule(self, i): '\n Return the `i`-th local rule on ``self``.\n\n This interprets ``self`` as a list of objects. This method first takes\n the list of objects of length three consisting of the `(i-1)`-st,\n `i`-th and `(i+1)`-term and applies the rule. It then replaces\n the `i`-th object by the object returned by the rule.\n\n EXAMPLES::\n\n sage: t = path_tableaux.FriezePattern([1,2,1,2,3,1])\n sage: t.local_rule(3)\n [1, 2, 5, 2, 3, 1]\n\n sage: t = path_tableaux.FriezePattern([1,2,1,2,3,1])\n sage: t.local_rule(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not a valid integer\n ' def _rule(x): '\n This is the rule on a sequence of three scalars.\n ' return (((x[0] * x[2]) + 1) / x[1]) if (not (0 < i < (len(self) - 1))): raise ValueError(f'{i} is not a valid integer') with self.clone() as result: result[i] = _rule(self[(i - 1):(i + 2)]) return result def is_skew(self): '\n Return ``True`` if ``self`` is skew and ``False`` if not.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,1]).is_skew()\n False\n\n sage: path_tableaux.FriezePattern([2,2,1,2,3,1]).is_skew()\n True\n ' return (self[1] != 1) def width(self): '\n Return the width of ``self``.\n\n If the first and last terms of ``self`` are 1 then this is the\n length of ``self`` plus two and otherwise is undefined.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,1]).width()\n 8\n\n sage: path_tableaux.FriezePattern([1,2,1,2,3,4]).width() is None\n True\n ' if ((self[1] == 1) and (self[(- 2)] == 1)): return len(self) else: return None def is_positive(self): "\n Return ``True`` if all elements of ``self`` are positive.\n\n This implies that all entries of ``CylindricalDiagram(self)``\n are positive.\n\n .. WARNING::\n\n There are orders on all fields. These may not be ordered fields\n as they may not be compatible with the field operations. This\n method is intended to be used with ordered fields only.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,7,5,3,7,4,1]).is_positive()\n True\n\n sage: path_tableaux.FriezePattern([1,-3,4,5,1]).is_positive()\n False\n\n sage: x = polygen(ZZ, 'x')\n sage: K.<sqrt3> = NumberField(x^2 - 3) # needs sage.rings.number_field\n sage: path_tableaux.FriezePattern([1,sqrt3,1], K).is_positive() # needs sage.rings.number_field\n True\n " return all(((a > 0) for a in self[1:(- 1)])) def is_integral(self): '\n Return ``True`` if all entries of the frieze pattern are\n positive integers.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,7,5,3,7,4,1]).is_integral()\n True\n\n sage: path_tableaux.FriezePattern([1,3,4,5,1]).is_integral()\n False\n ' n = len(self) cd = CylindricalDiagram(self).diagram return all(((k in ZZ) for (i, a) in enumerate(cd) for k in a[(i + 1):((n + i) - 2)])) def triangulation(self): "\n Plot a regular polygon with some diagonals.\n\n If ``self`` is positive and integral then this will be a triangulation.\n\n .. PLOT::\n :width: 400 px\n\n G = path_tableaux.FriezePattern([1,2,7,5,3,7,4,1]).triangulation()\n sphinx_plot(G)\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePattern([1,2,7,5,3,7,4,1]).triangulation() # needs sage.plot sage.symbolic\n Graphics object consisting of 25 graphics primitives\n\n sage: path_tableaux.FriezePattern([1,2,1/7,5,3]).triangulation() # needs sage.plot sage.symbolic\n Graphics object consisting of 12 graphics primitives\n\n\n sage: x = polygen(ZZ, 'x')\n sage: K.<sqrt2> = NumberField(x^2 - 2) # needs sage.rings.number_field\n sage: path_tableaux.FriezePattern([1,sqrt2,1,sqrt2,3,2*sqrt2,5,3*sqrt2,1], # needs sage.plot sage.rings.number_field sage.symbolic\n ....: field=K).triangulation()\n Graphics object consisting of 24 graphics primitives\n " n = (len(self) - 1) cd = CylindricalDiagram(self).diagram from sage.plot.plot import Graphics from sage.plot.line import line from sage.plot.text import text from sage.functions.trig import sin, cos from sage.symbolic.constants import pi G = Graphics() G.set_aspect_ratio(1.0) vt = [(cos((((2 * theta) * pi) / n)), sin((((2 * theta) * pi) / n))) for theta in range((n + 1))] for (i, p) in enumerate(vt): G += text(str(i), [(1.05 * p[0]), (1.05 * p[1])]) for (i, r) in enumerate(cd): for (j, a) in enumerate(r[:n]): if (a == 1): G += line([vt[i], vt[j]]) G.axes(False) return G def plot(self, model='UHP'): "\n Plot the frieze as an ideal hyperbolic polygon.\n\n This is only defined up to isometry of the hyperbolic plane.\n\n We are identifying the boundary of the hyperbolic plane with the\n real projective line.\n\n The option ``model`` must be one of\n\n * ``'UHP'`` - (default) for the upper half plane model\n * ``'PD'`` - for the Poincare disk model\n * ``'KM'`` - for the Klein model\n\n The hyperboloid model is not an option as this does not implement\n boundary points.\n\n .. PLOT::\n :width: 400 px\n\n t = path_tableaux.FriezePattern([1,2,7,5,3,7,4,1])\n sphinx_plot(t.plot())\n\n EXAMPLES::\n\n sage: # needs sage.plot sage.symbolic\n sage: t = path_tableaux.FriezePattern([1,2,7,5,3,7,4,1])\n sage: t.plot()\n Graphics object consisting of 18 graphics primitives\n sage: t.plot(model='UHP')\n Graphics object consisting of 18 graphics primitives\n sage: t.plot(model='PD')\n Traceback (most recent call last):\n ...\n TypeError: '>' not supported between instances of 'NotANumber' and 'Pi'\n sage: t.plot(model='KM')\n Graphics object consisting of 18 graphics primitives\n " from sage.geometry.hyperbolic_space.hyperbolic_interface import HyperbolicPlane from sage.plot.plot import Graphics models = {'UHP': HyperbolicPlane().UHP(), 'PD': HyperbolicPlane().PD(), 'KM': HyperbolicPlane().KM()} if (model not in models): raise ValueError(f'{model} must be one of ``UHP``, ``PD``, ``KM``') M = models[model] U = HyperbolicPlane().UHP() cd = CylindricalDiagram(self).diagram num = cd[0][:(- 1)] den = cd[1][2:] vt = [M(U.get_point((x / (x + y)))) for (x, y) in zip(num, den)] gd = [M.get_geodesic(vt[(i - 1)], vt[i]) for i in range(len(vt))] return sum([a.plot() for a in gd], Graphics()).plot() def change_ring(self, R): '\n Return ``self`` as a frieze pattern with coefficients in ``R``.\n\n This assumes that there is a canonical coerce map from the base ring of ``self``\n to ``R``.\n\n EXAMPLES::\n\n sage: fp = path_tableaux.FriezePattern([1,2,7,5,3,7,4,1])\n sage: fp.change_ring(RealField()) # needs sage.rings.real_mpfr\n [0.000000000000000, 1.00000000000000, ...\n 4.00000000000000, 1.00000000000000, 0.000000000000000]\n sage: fp.change_ring(GF(7))\n Traceback (most recent call last):\n ...\n TypeError: no base extension defined\n ' if R.has_coerce_map_from(self.parent().base_ring()): return FriezePattern(list(self), field=R) else: raise TypeError('no base extension defined')
class FriezePatterns(PathTableaux): '\n The set of all frieze patterns.\n\n EXAMPLES::\n\n sage: P = path_tableaux.FriezePatterns(QQ)\n sage: fp = P((1, 1, 1))\n sage: fp\n [1]\n sage: path_tableaux.CylindricalDiagram(fp)\n [1, 1, 1]\n [ , 1, 2, 1]\n [ , , 1, 1, 1]\n ' def __init__(self, field): '\n Initialize ``self``.\n\n TESTS::\n\n sage: P = path_tableaux.FriezePatterns(QQ)\n sage: TestSuite(P).run()\n ' Parent.__init__(self, base=field, category=Sets()) def _an_element_(self): '\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.FriezePatterns(QQ)._an_element_()\n [1, 1, 1]\n ' return FriezePattern((1, 1, 1)) Element = FriezePattern
class PathTableau(ClonableArray, metaclass=InheritComparisonClasscallMetaclass): '\n This is the abstract base class for a path tableau.\n ' @abstract_method def local_rule(self, i): '\n This is the abstract local rule defined in any coboundary category.\n\n This has input a list of objects. This method first takes\n the list of objects of length three consisting of the `(i-1)`-st,\n `i`-th and `(i+1)`-term and applies the rule. It then replaces\n the `i`-th object by the object returned by the rule.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.local_rule(3)\n [0, 1, 2, 1, 2, 1, 0]\n ' def size(self): '\n Return the size or length of ``self``.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.size()\n 7\n ' return len(self) def initial_shape(self): '\n Return the initial shape of ``self``.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.initial_shape()\n 0\n ' return self[0] def final_shape(self): '\n Return the final shape of ``self``.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.final_shape()\n 0\n ' return self[(- 1)] def promotion(self): '\n Return the promotion operator applied to ``self``.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.promotion()\n [0, 1, 2, 1, 0, 1, 0]\n ' with self.clone() as result: for i in range(1, (self.size() - 1)): result = result.local_rule(i) return result def evacuation(self): '\n Return the evacuation operator applied to ``self``.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.evacuation()\n [0, 1, 2, 3, 2, 1, 0]\n ' if (self.size() < 3): return self L = list(self) result = [] P = self.parent() for i in range(self.size()): L = list(P(L).promotion()) result.append(L.pop()) result.reverse() return P(result) def commutor(self, other, verbose=False): '\n Return the commutor of ``self`` with ``other``.\n\n If ``verbose=True`` then the function will print\n the rectangle.\n\n EXAMPLES::\n\n sage: t1 = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t2 = path_tableaux.DyckPath([0,1,2,1,0])\n sage: t1.commutor(t2)\n ([0, 1, 2, 1, 0], [0, 1, 2, 3, 2, 1, 0])\n sage: t1.commutor(t2,verbose=True)\n [0, 1, 2, 1, 0]\n [1, 2, 3, 2, 1]\n [2, 3, 4, 3, 2]\n [3, 4, 5, 4, 3]\n [2, 3, 4, 3, 2]\n [1, 2, 3, 2, 1]\n [0, 1, 2, 1, 0]\n ([0, 1, 2, 1, 0], [0, 1, 2, 3, 2, 1, 0])\n\n TESTS::\n\n sage: t1 = path_tableaux.DyckPath([])\n sage: t2 = path_tableaux.DyckPath([0,1,2,1,0])\n sage: t1.commutor(t2)\n Traceback (most recent call last):\n ...\n ValueError: this requires nonempty lists\n sage: t1 = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t2 = path_tableaux.DyckPath([])\n sage: t1.commutor(t2)\n Traceback (most recent call last):\n ...\n ValueError: this requires nonempty lists\n sage: t1 = path_tableaux.DyckPath([0,1,2,3,2,1])\n sage: t2 = path_tableaux.DyckPath([0,1,2,1,0])\n sage: t1.commutor(t2)\n Traceback (most recent call last):\n ...\n ValueError: [0, 1, 2, 3, 2, 1], [0, 1, 2, 1, 0] is not a composable pair\n ' n = self.size() m = len(other) if ((n == 0) or (m == 0)): raise ValueError('this requires nonempty lists') if ((n == 1) or (m == 1)): return (other, self) P = self.parent() row = list(other) col = list(self) if (col[(- 1)] != row[0]): raise ValueError(('%s, %s is not a composable pair' % (self, other))) path = P((col + row[1:])) for i in range(1, n): if verbose: print(path[(n - i):((n + m) - i)]) for j in range((m - 1)): path = path.local_rule(((n + j) - i)) if verbose: print(path[:m]) return (P(path[:m]), P(path[(m - 1):])) def cactus(self, i, j): '\n Return the action of the generator `s_{i,j}` of the cactus\n group on ``self``.\n\n INPUT:\n\n ``i`` -- a positive integer\n ``j`` -- a positive integer weakly greater than ``i``\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.cactus(1,5)\n [0, 1, 0, 1, 2, 1, 0]\n\n sage: t.cactus(1,6)\n [0, 1, 2, 1, 0, 1, 0]\n\n sage: t.cactus(1,7) == t.evacuation()\n True\n sage: t.cactus(1,7).cactus(1,6) == t.promotion()\n True\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.cactus(1,8)\n Traceback (most recent call last):\n ...\n ValueError: integers out of bounds\n sage: t.cactus(0,3)\n Traceback (most recent call last):\n ...\n ValueError: integers out of bounds\n ' if (not (0 < i <= j <= self.size())): raise ValueError('integers out of bounds') if (i == j): return self if (i == 1): h = list(self)[:j] t = list(self)[j:] T = self.parent()(h) L = (list(T.evacuation()) + t) return self.parent()(L) return self.cactus(1, j).cactus(1, ((j - i) + 1)).cactus(1, j) def _test_involution_rule(self, **options): '\n Check that the local rule gives an involution.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t._test_involution_rule()\n ' tester = self._tester(**options) for i in range((self.size() - 2)): tester.assertEqual(self.local_rule((i + 1)).local_rule((i + 1)), self) def _test_involution_cactus(self, **options): '\n Check that the cactus group generators are involutions.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t._test_involution_cactus()\n ' tester = self._tester(**options) for i in range(2, (self.size() + 1)): tester.assertEqual(self.cactus(1, i).cactus(1, i), self) def _test_promotion(self, **options): '\n Check that promotion can be expressed in terms of the cactus generators.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t._test_promotion()\n ' tester = self._tester(**options) n = self.size() tester.assertEqual(self.cactus(1, (n - 1)).cactus(1, n).promotion(), self) def _test_commutation(self, **options): '\n Check the commutation relations in the presentation of the cactus group.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t._test_commutation()\n ' from itertools import combinations tester = self._tester(**options) n = self.size() if (n < 5): return for (i, j, r, s) in combinations(range(1, (n + 1)), 4): lhs = self.cactus(i, j).cactus(r, s) rhs = self.cactus(r, s).cactus(i, j) tester.assertEqual(lhs, rhs) def _test_coboundary(self, **options): '\n Check the coboundary relations in the presentation of the cactus group.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t._test_coboundary()\n ' from itertools import combinations tester = self._tester(**options) n = self.size() if (n < 4): return for (i, j, r, s) in combinations(range(1, (n + 3)), 4): lhs = self.cactus(i, (s - 2)).cactus((j - 1), (r - 1)) rhs = self.cactus((((i + s) - r) - 1), (((i + s) - j) - 1)).cactus(i, (s - 2)) tester.assertEqual(lhs, rhs) def orbit(self): '\n Return the orbit of ``self`` under the action of the cactus group.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: t.orbit()\n {[0, 1, 0, 1, 0, 1, 0],\n [0, 1, 0, 1, 2, 1, 0],\n [0, 1, 2, 1, 0, 1, 0],\n [0, 1, 2, 1, 2, 1, 0],\n [0, 1, 2, 3, 2, 1, 0]}\n ' orb = set() rec = set([self]) while rec: new = set() for a in rec: for i in range(2, self.size()): b = a.cactus(1, i) if ((b not in orb) and (b not in rec)): new.add(b) orb = orb.union(rec) rec = new.copy() return orb def dual_equivalence_graph(self): "\n Return the graph with vertices the orbit of ``self``\n and edges given by the action of the cactus group generators.\n\n In most implementations the generators `s_{i,i+1}` will act\n as the identity operators. The usual dual equivalence graphs\n are given by replacing the label `i,i+2` by `i` and removing\n edges with other labels.\n\n EXAMPLES::\n\n sage: s = path_tableaux.DyckPath([0,1,2,3,2,3,2,1,0])\n sage: s.dual_equivalence_graph().adjacency_matrix() # needs sage.graphs sage.modules\n [0 1 1 1 0 1 0 1 1 0 0 0 0 0]\n [1 0 1 1 1 1 1 0 1 0 0 1 1 0]\n [1 1 0 1 1 1 0 1 0 1 1 1 0 0]\n [1 1 1 0 1 0 1 1 1 1 0 1 1 0]\n [0 1 1 1 0 0 1 0 0 1 1 0 1 1]\n [1 1 1 0 0 0 1 1 1 1 1 0 1 0]\n [0 1 0 1 1 1 0 1 0 1 1 1 0 1]\n [1 0 1 1 0 1 1 0 1 1 1 1 1 0]\n [1 1 0 1 0 1 0 1 0 1 0 1 1 0]\n [0 0 1 1 1 1 1 1 1 0 0 1 1 1]\n [0 0 1 0 1 1 1 1 0 0 0 1 1 1]\n [0 1 1 1 0 0 1 1 1 1 1 0 1 1]\n [0 1 0 1 1 1 0 1 1 1 1 1 0 1]\n [0 0 0 0 1 0 1 0 0 1 1 1 1 0]\n sage: s = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: s.dual_equivalence_graph().edges(sort=True) # needs sage.graphs\n [([0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 2, 1, 0], '4,7'),\n ([0, 1, 0, 1, 0, 1, 0], [0, 1, 2, 1, 0, 1, 0], '2,5'),\n ([0, 1, 0, 1, 0, 1, 0], [0, 1, 2, 1, 2, 1, 0], '2,7'),\n ([0, 1, 0, 1, 2, 1, 0], [0, 1, 2, 1, 0, 1, 0], '2,6'),\n ([0, 1, 0, 1, 2, 1, 0], [0, 1, 2, 1, 2, 1, 0], '1,4'),\n ([0, 1, 0, 1, 2, 1, 0], [0, 1, 2, 3, 2, 1, 0], '2,7'),\n ([0, 1, 2, 1, 0, 1, 0], [0, 1, 2, 1, 2, 1, 0], '4,7'),\n ([0, 1, 2, 1, 0, 1, 0], [0, 1, 2, 3, 2, 1, 0], '3,7'),\n ([0, 1, 2, 1, 2, 1, 0], [0, 1, 2, 3, 2, 1, 0], '3,6')]\n " from sage.graphs.graph import Graph from itertools import combinations G = Graph() orb = self.orbit() for a in orb: for (i, j) in combinations(range(1, (self.size() + 1)), 2): b = a.cactus(i, j) if (a != b): G.add_edge(a, b, ('%d,%d' % (i, j))) return G
class PathTableaux(UniqueRepresentation, Parent): '\n The abstract parent class for PathTableau.\n ' def __init__(self): '\n Initialize ``self``.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPaths()\n sage: TestSuite(t).run()\n\n sage: f = path_tableaux.FriezePatterns(QQ)\n sage: TestSuite(f).run()\n ' Parent.__init__(self, category=Sets()) def _element_constructor_(self, *args, **kwds): '\n Construct an object as an element of ``self``, if possible.\n\n TESTS::\n\n sage: path_tableaux.DyckPath([0,1,2,1,0]) # indirect doctest\n [0, 1, 2, 1, 0]\n ' return self.element_class(self, *args, **kwds)
class CylindricalDiagram(SageObject): '\n Cylindrical growth diagrams.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: path_tableaux.CylindricalDiagram(t)\n [0, 1, 2, 3, 2, 1, 0]\n [ , 0, 1, 2, 1, 0, 1, 0]\n [ , , 0, 1, 0, 1, 2, 1, 0]\n [ , , , 0, 1, 2, 3, 2, 1, 0]\n [ , , , , 0, 1, 2, 1, 0, 1, 0]\n [ , , , , , 0, 1, 0, 1, 2, 1, 0]\n [ , , , , , , 0, 1, 2, 3, 2, 1, 0]\n ' def __init__(self, T): '\n Initialize ``self`` from the\n :class:`~sage.combinat.path_tableaux.path_tableau.PathTableau`\n object ``T``.\n\n TESTS::\n\n sage: T = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: D = path_tableaux.CylindricalDiagram(T)\n sage: TestSuite(D).run()\n\n sage: path_tableaux.CylindricalDiagram(2)\n Traceback (most recent call last):\n ...\n ValueError: 2 must be a path tableau\n ' if (not isinstance(T, PathTableau)): raise ValueError('{0} must be a path tableau'.format(str(T))) n = len(T) result = ([([None] * ((2 * n) - 1))] * n) for i in range(n): result[i] = (([''] * i) + list(T)) T = T.promotion() self.path_tableau = T self.diagram = result def _repr_(self): '\n Return a string representation of ``self``\n\n TESTS::\n\n sage: cd = path_tableaux.CylindricalDiagram(path_tableaux.DyckPath([0,1,2,1,2,1,0]))\n sage: repr(cd) == cd._repr_() # indirect test\n True\n\n sage: cd = path_tableaux.CylindricalDiagram(path_tableaux.FriezePattern([1,3,4,5,1]))\n sage: repr(cd) == cd._repr_() # indirect test\n True\n\n sage: print(path_tableaux.DyckPath([0,1,2,1,2,1,0])) # indirect test\n [0, 1, 2, 1, 2, 1, 0]\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: path_tableaux.CylindricalDiagram(t)\n [0, 1, 2, 3, 2, 1, 0]\n [ , 0, 1, 2, 1, 0, 1, 0]\n [ , , 0, 1, 0, 1, 2, 1, 0]\n [ , , , 0, 1, 2, 3, 2, 1, 0]\n [ , , , , 0, 1, 2, 1, 0, 1, 0]\n [ , , , , , 0, 1, 0, 1, 2, 1, 0]\n [ , , , , , , 0, 1, 2, 3, 2, 1, 0]\n ' data = [[str(x) for x in row] for row in self.diagram] if (not data[0]): data[0] = [''] max_width = max((max((len(x) for x in row)) for row in data if row)) return '\n'.join(((('[' + ', '.join((((' ' * (max_width - len(x))) + x) for x in row))) + ']') for row in data)) def __eq__(self, other): '\n Check equality.\n\n EXAMPLES::\n\n sage: t1 = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: T1 = path_tableaux.CylindricalDiagram(t1)\n sage: t2 = path_tableaux.DyckPath([0,1,2,1,2,1,0])\n sage: T2 = path_tableaux.CylindricalDiagram(t2)\n sage: T1 == T2\n False\n sage: T1 == path_tableaux.CylindricalDiagram(t1)\n True\n ' return (isinstance(other, CylindricalDiagram) and (self.diagram == other.diagram)) def __ne__(self, other): '\n Check inequality.\n\n EXAMPLES::\n\n sage: t1 = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: T1 = path_tableaux.CylindricalDiagram(t1)\n sage: t2 = path_tableaux.DyckPath([0,1,2,1,2,1,0])\n sage: T2 = path_tableaux.CylindricalDiagram(t2)\n sage: T1 != T2\n True\n sage: T1 != path_tableaux.CylindricalDiagram(t1)\n False\n ' return (not (self == other)) def _latex_(self): '\n Return a `\\LaTeX` representation of ``self``\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: latex(path_tableaux.CylindricalDiagram(t))\n \\begin{array}{ccccccccccccc}\n 0 & 1 & 2 & 3 & 2 & 1 & 0\\\\\n & 0 & 1 & 2 & 1 & 0 & 1 & 0\\\\\n & & 0 & 1 & 0 & 1 & 2 & 1 & 0\\\\\n & & & 0 & 1 & 2 & 3 & 2 & 1 & 0\\\\\n & & & & 0 & 1 & 2 & 1 & 0 & 1 & 0\\\\\n & & & & & 0 & 1 & 0 & 1 & 2 & 1 & 0\\\\\n & & & & & & 0 & 1 & 2 & 3 & 2 & 1 & 0\n \\end{array}\n\n sage: t = path_tableaux.FriezePattern([1,3,4,5,1])\n sage: latex(path_tableaux.CylindricalDiagram(t))\n \\begin{array}{ccccccccccccc}\n 0 & 1 & 3 & 4 & 5 & 1 & 0\\\\\n & 0 & 1 & \\frac{5}{3} & \\frac{7}{3} & \\frac{2}{3} & 1 & 0\\\\\n & & 0 & 1 & 2 & 1 & 3 & 1 & 0\\\\\n & & & 0 & 1 & 1 & 4 & \\frac{5}{3} & 1 & 0\\\\\n & & & & 0 & 1 & 5 & \\frac{7}{3} & 2 & 1 & 0\\\\\n & & & & & 0 & 1 & \\frac{2}{3} & 1 & 1 & 1 & 0\\\\\n & & & & & & 0 & 1 & 3 & 4 & 5 & 1 & 0\n \\end{array}\n\n ' D = self.diagram m = len(D[(- 1)]) result = (('\\begin{array}{' + ('c' * m)) + '}\n') result += '\\\\ \n'.join((' & '.join((latex(a) for a in x)) for x in D)) result += '\n \\end{array}\n' return result def __len__(self): '\n Return the length of ``self``.\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: len(path_tableaux.CylindricalDiagram(t))\n 7\n ' return len(self.diagram) def _ascii_art_(self): '\n Return an ascii art representation of ``self``\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: ascii_art(path_tableaux.CylindricalDiagram(t))\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n\n sage: t = path_tableaux.FriezePattern([1,3,4,5,1])\n sage: ascii_art(path_tableaux.CylindricalDiagram(t))\n 0 1 3 4 5 1 0\n 0 1 5/3 7/3 2/3 1 0\n 0 1 2 1 3 1 0\n 0 1 1 4 5/3 1 0\n 0 1 5 7/3 2 1 0\n 0 1 2/3 1 1 1 0\n 0 1 3 4 5 1 0\n ' from sage.typeset.ascii_art import ascii_art from sage.misc.misc_c import prod data = [[ascii_art(x) for x in row] for row in self.diagram] if (not data[0]): data[0] = [ascii_art('')] max_width = max((max((len(x) for x in row)) for row in data if row)) return prod((sum(((ascii_art((' ' * ((max_width - len(x)) + 1))) + x) for x in row), ascii_art('')) for row in data), ascii_art('')) def _unicode_art_(self): '\n Return a unicode art representation of ``self``\n\n TESTS::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: unicode_art(path_tableaux.CylindricalDiagram(t))\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n\n sage: t = path_tableaux.FriezePattern([1,3,4,5,1])\n sage: unicode_art(path_tableaux.CylindricalDiagram(t))\n 0 1 3 4 5 1 0\n 0 1 5/3 7/3 2/3 1 0\n 0 1 2 1 3 1 0\n 0 1 1 4 5/3 1 0\n 0 1 5 7/3 2 1 0\n 0 1 2/3 1 1 1 0\n 0 1 3 4 5 1 0\n ' from sage.typeset.unicode_art import unicode_art from sage.misc.misc_c import prod data = [[unicode_art(x) for x in row] for row in self.diagram] if (not data[0]): data[0] = [unicode_art('')] max_width = max((max((len(x) for x in row)) for row in data if row)) return prod((sum(((unicode_art((' ' * ((max_width - len(x)) + 1))) + x) for x in row), unicode_art('')) for row in data), unicode_art('')) def pp(self): '\n A pretty print utility method.\n\n EXAMPLES::\n\n sage: t = path_tableaux.DyckPath([0,1,2,3,2,1,0])\n sage: path_tableaux.CylindricalDiagram(t).pp()\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n 0 1 2 1 0 1 0\n 0 1 0 1 2 1 0\n 0 1 2 3 2 1 0\n\n sage: t = path_tableaux.FriezePattern([1,3,4,5,1])\n sage: path_tableaux.CylindricalDiagram(t).pp()\n 0 1 3 4 5 1 0\n 0 1 5/3 7/3 2/3 1 0\n 0 1 2 1 3 1 0\n 0 1 1 4 5/3 1 0\n 0 1 5 7/3 2 1 0\n 0 1 2/3 1 1 1 0\n 0 1 3 4 5 1 0\n ' data = [[str(x) for x in row] for row in self.diagram] if (not data[0]): data[0] = [''] max_width = max((max((len(x) for x in row)) for row in data if row)) print('\n'.join((' '.join((((' ' * (max_width - len(x))) + x) for x in row)) for row in data)))
class SemistandardPathTableau(PathTableau): '\n An instance is a sequence of lists. Usually the entries will be non-negative integers\n in which case this is the chain of partitions of a (skew) semistandard tableau.\n In general the entries are elements of an ordered abelian group; each list is weakly\n decreasing and successive lists are interleaved.\n\n INPUT:\n\n Can be any of the following\n\n * a sequence of partitions\n * a sequence of lists/tuples\n * a semistandard tableau\n * a semistandard skew tableau\n * a Gelfand-Tsetlin pattern\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableau([[],[2],[2,1]])\n [(), (2,), (2, 1)]\n\n sage: gt = GelfandTsetlinPattern([[2,1],[2]])\n sage: path_tableaux.SemistandardPathTableau(gt)\n [(), (2,), (2, 1)]\n\n sage: st = SemistandardTableau([[1,1],[2]])\n sage: path_tableaux.SemistandardPathTableau(st)\n [(), (2,), (2, 1)]\n\n sage: st = SkewTableau([[1,1],[2]])\n sage: path_tableaux.SemistandardPathTableau(st)\n [(), (2,), (2, 1)]\n\n sage: st = SkewTableau([[None,1,1],[2]])\n sage: path_tableaux.SemistandardPathTableau(st)\n [(1,), (3, 0), (3, 1, 0)]\n\n sage: path_tableaux.SemistandardPathTableau([[],[5/2],[7/2,2]])\n [(), (5/2,), (7/2, 2)]\n\n sage: path_tableaux.SemistandardPathTableau([[],[2.5],[3.5,2]])\n [(), (2.50000000000000,), (3.50000000000000, 2)]\n ' @staticmethod def __classcall_private__(cls, st, check=True): '\n Ensure that a tableau is only ever constructed as an\n ``element_class`` call of an appropriate parent.\n\n EXAMPLES::\n\n sage: t = path_tableaux.SemistandardPathTableau([[],[2]])\n sage: t.parent()\n <sage.combinat.path_tableaux.semistandard.SemistandardPathTableaux_with_category object at ...>\n ' return SemistandardPathTableaux()(st, check=check) def __init__(self, parent, st, check=True): '\n Initialize a semistandard tableau.\n\n TESTS::\n\n sage: path_tableaux.SemistandardPathTableau([(), 3, (3, 2)])\n Traceback (most recent call last):\n ...\n ValueError: [(), 3, (3, 2)] is not a sequence of lists\n ' w = None if isinstance(st, SemistandardPathTableau): w = list(st) elif isinstance(st, GelfandTsetlinPattern): w = list(st) w.reverse() w = [(), *w] elif isinstance(st, (Tableau, SkewTableau)): w = st.to_chain() elif isinstance(st, (list, tuple)): if any(((not isinstance(a, (list, tuple))) for a in st)): raise ValueError(f'{st} is not a sequence of lists') w = st else: raise ValueError(f'invalid input {st} is of type {type(st)}') m = max(((len(a) - i) for (i, a) in enumerate(w))) w = [(list(a) + ([0] * ((m + i) - len(a)))) for (i, a) in enumerate(w)] w = tuple([tuple(a) for a in w]) PathTableau.__init__(self, parent, w, check=check) def check(self): '\n Check that ``self`` is a valid path.\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableau([[],[3],[2,2]]) # indirect test\n Traceback (most recent call last):\n ...\n ValueError: [(), (3,), (2, 2)] does not satisfy the required inequalities in row 1\n\n sage: path_tableaux.SemistandardPathTableau([[],[3/2],[2,5/2]]) # indirect test\n Traceback (most recent call last):\n ...\n ValueError: [(), (3/2,), (2, 5/2)] does not satisfy the required inequalities in row 1\n\n\n TESTS::\n\n sage: path_tableaux.SemistandardPathTableau([[],[2],[1,2]])\n Traceback (most recent call last):\n ...\n ValueError: [(), (2,), (1, 2)] does not satisfy the required inequalities in row 1\n\n sage: path_tableaux.SemistandardPathTableau([[],[2],[1,2]],check=False)\n [(), (2,), (1, 2)]\n ' for i in range(1, (len(self) - 1)): if (not all(((r >= s) for (r, s) in zip(self[(i + 1)], self[i])))): raise ValueError(f'{self} does not satisfy the required inequalities in row {i}') if (not all(((r >= s) for (r, s) in zip(self[i], self[(i + 1)][1:])))): raise ValueError(f'{self} does not satisfy the required inequalities in row {i}') def size(self): '\n Return the size or length of ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableau([[],[3],[3,2],[3,3,1],[3,3,2,1]]).size()\n 5\n ' return len(self) def is_skew(self): '\n Return ``True`` if ``self`` is skew.\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableau([[],[2]]).is_skew()\n False\n sage: path_tableaux.SemistandardPathTableau([[2,1]]).is_skew()\n True\n ' return bool(self[0]) def is_integral(self) -> bool: '\n Return ``True`` if all entries are non-negative integers.\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableau([[],[3],[3,2]]).is_integral()\n True\n sage: path_tableaux.SemistandardPathTableau([[],[5/2],[7/2,2]]).is_integral()\n False\n sage: path_tableaux.SemistandardPathTableau([[],[3],[3,-2]]).is_integral()\n False\n ' return all(((i in NN) for a in self for i in a)) def local_rule(self, i): '\n This is the Bender-Knuth involution.\n\n This is implemented by toggling the entries of the `i`-th list.\n The allowed range for ``i`` is ``0 < i < len(self)-1`` so any row except\n the first and last can be changed.\n\n EXAMPLES::\n\n sage: pt = path_tableaux.SemistandardPathTableau([[],[3],[3,2],[3,3,1],[3,3,2,1]])\n sage: pt.local_rule(1)\n [(), (2,), (3, 2), (3, 3, 1), (3, 3, 2, 1)]\n sage: pt.local_rule(2)\n [(), (3,), (3, 2), (3, 3, 1), (3, 3, 2, 1)]\n sage: pt.local_rule(3)\n [(), (3,), (3, 2), (3, 2, 2), (3, 3, 2, 1)]\n\n TESTS::\n\n sage: pt = path_tableaux.SemistandardPathTableau([[],[3],[3,2],[3,3,1],[3,3,2,1]])\n sage: pt.local_rule(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not defined on [(), (3,), (3, 2), (3, 3, 1), (3, 3, 2, 1)]\n sage: pt.local_rule(4)\n Traceback (most recent call last):\n ...\n ValueError: 4 is not defined on [(), (3,), (3, 2), (3, 3, 1), (3, 3, 2, 1)]\n ' def toggle(i, j): "\n Return the toggle of entry 'self[i][j]'.\n " if (j == 0): left = self[(i + 1)][0] else: left = min(self[(i + 1)][j], self[(i - 1)][(j - 1)]) if (j == (len(self[i]) - 1)): right = self[(i + 1)][(j + 1)] else: right = max(self[(i + 1)][(j + 1)], self[(i - 1)][j]) return ((left + right) - self[i][j]) if (not (0 < i < (self.size() - 1))): raise ValueError(f'{i} is not defined on {self}') with self.clone() as result: result[i] = tuple([toggle(i, k) for k in range(len(self[i]))]) return result def rectify(self, inner=None, verbose=False): '\n Rectify ``self``.\n\n This gives the usual rectification of a skew standard tableau and gives a\n generalisation to skew semistandard tableaux. The usual construction uses\n jeu de taquin but here we use the Bender-Knuth involutions.\n\n EXAMPLES::\n\n sage: st = SkewTableau([[None, None, None, 4],[None,None,1,6],[None,None,5],[2,3]])\n sage: path_tableaux.SemistandardPathTableau(st).rectify()\n [(), (1,), (1, 1), (2, 1, 0), (3, 1, 0, 0), (3, 2, 0, 0, 0), (4, 2, 0, 0, 0, 0)]\n sage: path_tableaux.SemistandardPathTableau(st).rectify(verbose=True)\n [[(3, 2, 2), (3, 3, 2, 0), (3, 3, 2, 1, 0), (3, 3, 2, 2, 0, 0), (4, 3, 2, 2, 0, 0, 0), (4, 3, 3, 2, 0, 0, 0, 0), (4, 4, 3, 2, 0, 0, 0, 0, 0)],\n [(3, 2), (3, 3, 0), (3, 3, 1, 0), (3, 3, 2, 0, 0), (4, 3, 2, 0, 0, 0), (4, 3, 3, 0, 0, 0, 0), (4, 4, 3, 0, 0, 0, 0, 0)],\n [(3,), (3, 1), (3, 1, 1), (3, 2, 1, 0), (4, 2, 1, 0, 0), (4, 3, 1, 0, 0, 0), (4, 4, 1, 0, 0, 0, 0)],\n [(), (1,), (1, 1), (2, 1, 0), (3, 1, 0, 0), (3, 2, 0, 0, 0), (4, 2, 0, 0, 0, 0)]]\n\n TESTS::\n\n sage: S = SemistandardSkewTableaux([[5,3,3],[3,1]],[3,2,2])\n sage: LHS = [path_tableaux.SemistandardPathTableau(st.rectify()) for st in S]\n sage: RHS = [path_tableaux.SemistandardPathTableau(st).rectify() for st in S]\n sage: LHS == RHS\n True\n\n sage: st = SkewTableau([[None, None, None, 4],[None,None,1,6],[None,None,5],[2,3]])\n sage: pt = path_tableaux.SemistandardPathTableau(st)\n sage: SP = [path_tableaux.SemistandardPathTableau(it) for it in StandardTableaux([3,2,2])]\n sage: len(set(pt.rectify(inner=ip) for ip in SP))\n 1\n ' if (not self.is_skew()): return self n = len(self) pp = self[0] P = self.parent() if (inner is None): initial = [pp[:r] for r in range(len(pp))] elif (_Partitions(inner[(- 1)]) == _Partitions(pp)): initial = list(inner)[:(- 1)] else: raise ValueError(f'the final shape{inner[(- 1)]} must agree with the initial shape {pp}') r = len(initial) path = P.element_class(P, (initial + list(self))) if verbose: rect = [self] for i in range(r): for j in range((n - 1)): path = path.local_rule(((r + j) - i)) if verbose: rect.append(P.element_class(P, list(path)[((r - i) - 1):(((r + n) - i) - 1)])) if verbose: return rect else: return P.element_class(P, list(path)[:n]) @combinatorial_map(name='to semistandard tableau') def to_tableau(self): '\n Convert ``self`` to a :class:`SemistandardTableau`.\n\n The :class:`SemistandardSkewTableau` is not implemented so this returns a :class:`SkewTableau`\n\n EXAMPLES::\n\n sage: pt = path_tableaux.SemistandardPathTableau([[],[3],[3,2],[3,3,1],[3,3,2,1],[4,3,3,1,0]])\n sage: pt.to_tableau()\n [[1, 1, 1, 5], [2, 2, 3], [3, 4, 5], [4]]\n\n TESTS::\n\n sage: SST = SemistandardTableaux(shape=[5,5,3], eval=[2,2,3,4,2])\n sage: all(st == path_tableaux.SemistandardPathTableau(st).to_tableau() # needs sage.modules\n ....: for st in SST)\n True\n ' from sage.combinat.tableau import from_chain if (not self.is_integral()): raise ValueError(f'{self} must have all entries nonnegative integers') lt = [[i for i in a if (i > 0)] for a in self] if self.is_skew(): return SkewTableaux().from_chain(lt) else: return from_chain(lt) @combinatorial_map(name='to Gelfand-Tsetlin pattern') def to_pattern(self): '\n Convert ``self`` to a Gelfand-Tsetlin pattern.\n\n EXAMPLES::\n\n sage: pt = path_tableaux.SemistandardPathTableau([[],[3],[3,2],[3,3,1],[3,3,2,1],[4,3,3,1]])\n sage: pt.to_pattern()\n [[4, 3, 3, 1, 0], [3, 3, 2, 1], [3, 3, 1], [3, 2], [3]]\n\n TESTS::\n\n sage: pt = path_tableaux.SemistandardPathTableau([[3,2],[3,3,1],[3,3,2,1],[4,3,3,1]])\n sage: pt.to_pattern()\n Traceback (most recent call last):\n ...\n ValueError: [(3, 2), (3, 3, 1), (3, 3, 2, 1), (4, 3, 3, 1, 0)] cannot be a skew tableau\n\n sage: GT = GelfandTsetlinPatterns(top_row=[5,5,3])\n sage: all(gt == path_tableaux.SemistandardPathTableau(gt).to_pattern() for gt in GT)\n True\n\n sage: GT = GelfandTsetlinPatterns(top_row=[5,5,3])\n sage: all(gt.to_tableau() == path_tableaux.SemistandardPathTableau(gt).to_tableau() for gt in GT)\n True\n ' if self.is_skew(): raise ValueError(f'{self} cannot be a skew tableau') lt = list(self) lt.reverse() if (not lt[(- 1)]): lt.pop() return GelfandTsetlinPattern([list(a) for a in lt]) def _test_jdt_promotion(self, **options): '\n Check that promotion agrees with :meth:`Tableau.promotion_inverse`\n constructed using jeu de taquin.\n\n TESTS::\n\n sage: pt = path_tableaux.SemistandardPathTableau([(),(1,),(2,1),(4,2),(4,3,1),(4,3,3)])\n sage: pt._test_jdt_promotion()\n\n sage: pt = path_tableaux.SemistandardPathTableau([(),(1,),(2,1),(4,2),(4,3,1),(9/2,3,3)])\n sage: pt._test_jdt_promotion()\n Traceback (most recent call last):\n ...\n ValueError: [(), (1,), (2, 1), (4, 2, 0), (4, 3, 1, 0), (9/2, 3, 3, 0, 0)] must have all entries nonnegative integers\n ' if (not self.is_integral()): raise ValueError(f'{self} must have all entries nonnegative integers') tester = self._tester(**options) LHS = self.promotion().to_tableau() RHS = self.to_tableau().promotion_inverse((len(self) - 2)) tester.assertEqual(LHS, RHS)
class SemistandardPathTableaux(PathTableaux): '\n The parent class for :class:`SemistandardPathTableau`.\n ' def _an_element_(self): '\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: path_tableaux.SemistandardPathTableaux()._an_element_()\n [(), (2,), (2, 1)]\n ' return SemistandardPathTableau([[], [2], [2, 1]]) Element = SemistandardPathTableau
class PerfectMatching(SetPartition): "\n A perfect matching.\n\n A *perfect matching* of a set `X` is a set partition of `X` where\n all parts have size 2.\n\n A perfect matching can be created from a list of pairs or from a\n fixed point-free involution as follows::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m\n [('a', 'e'), ('b', 'c'), ('d', 'f')]\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]);n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: isinstance(m,PerfectMatching)\n True\n\n The parent, which is the set of perfect matchings of the ground set, is\n automatically created::\n\n sage: n.parent()\n Perfect matchings of {1, 2, 3, 4, 5, 6, 7, 8}\n\n If the ground set is ordered, one can, for example, ask if the matching is\n non crossing::\n\n sage: PerfectMatching([(1, 4), (2, 3), (5, 6)]).is_noncrossing()\n True\n\n TESTS::\n\n sage: m = PerfectMatching([]); m\n []\n sage: m.parent()\n Perfect matchings of {}\n " @staticmethod def __classcall_private__(cls, parts): "\n Create a perfect matching from ``parts`` with the appropriate parent.\n\n This function tries to recognize the input (it can be either a list or\n a tuple of pairs, or a fix-point free involution given as a list or as\n a permutation), constructs the parent (enumerated set of\n PerfectMatchings of the ground set) and calls the __init__ function to\n construct our object.\n\n EXAMPLES::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m\n [('a', 'e'), ('b', 'c'), ('d', 'f')]\n sage: isinstance(m, PerfectMatching)\n True\n sage: n = PerfectMatching([3, 8, 1, 7, 6, 5, 4, 2]);n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.parent()\n Perfect matchings of {1, 2, 3, 4, 5, 6, 7, 8}\n sage: PerfectMatching([(1, 4), (2, 3), (5, 6)]).is_noncrossing()\n True\n\n The function checks that the given list or permutation is\n a valid perfect matching (i.e. a list of pairs with pairwise\n disjoint elements or a fix point free involution) and raises\n a :class:`ValueError` otherwise::\n\n sage: PerfectMatching([(1, 2, 3), (4, 5)])\n Traceback (most recent call last):\n ...\n ValueError: [(1, 2, 3), (4, 5)] is not an element of\n Perfect matchings of {1, 2, 3, 4, 5}\n\n TESTS::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])\n sage: TestSuite(m).run()\n sage: m = PerfectMatching([])\n sage: TestSuite(m).run()\n sage: PerfectMatching(6)\n Traceback (most recent call last):\n ...\n TypeError: 'sage.rings.integer.Integer' object is not iterable\n sage: PerfectMatching([(1,2,3)])\n Traceback (most recent call last):\n ...\n ValueError: [(1, 2, 3)] is not an element of\n Perfect matchings of {1, 2, 3}\n\n sage: PerfectMatching([(1,1)])\n Traceback (most recent call last):\n ...\n ValueError: [(1)] is not an element of Perfect matchings of {1}\n\n sage: PerfectMatching(Permutation([4,2,1,3]))\n Traceback (most recent call last):\n ...\n ValueError: permutation p (= [4, 2, 1, 3]) is not a\n fixed point free involution\n " if ((isinstance(parts, list) and all((isinstance(x, (int, Integer)) for x in parts))) or isinstance(parts, Permutation)): s = Permutation(parts) if (not all(((e == 2) for e in s.cycle_type()))): raise ValueError('permutation p (= {}) is not a fixed point free involution'.format(s)) parts = s.to_cycles() base_set = frozenset((e for p in parts for e in p)) P = PerfectMatchings(base_set) return P(parts) def __init__(self, parent, s, check=True, sort=True): '\n Initialize ``self``.\n\n TESTS::\n\n sage: PM = PerfectMatchings(6)\n sage: x = PM.element_class(PM, [[5,6],[3,4],[1,2]])\n\n Use the ``sort`` argument when you do not care if the result\n is sorted. Be careful with its use as you can get inconsistent\n results when then input is not sorted::\n\n sage: y = PM.element_class(PM, [[5,6],[3,4],[1,2]], sort=False)\n sage: y\n [(5, 6), (3, 4), (1, 2)]\n sage: x == y\n False\n ' self._latex_options = {} if sort: data = sorted(map(frozenset, s), key=min) else: data = list(map(frozenset, s)) ClonableArray.__init__(self, parent, data, check=check) def _repr_(self): "\n Return a string representation of the matching ``self``.\n\n EXAMPLES::\n\n sage: PerfectMatching([('a','e'), ('b','c'), ('d','f')])\n [('a', 'e'), ('b', 'c'), ('d', 'f')]\n sage: PerfectMatching([3,8,1,7,6,5,4,2])\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n " return (('[' + ', '.join(((('(' + repr(sorted(x))[1:(- 1)]) + ')') for x in self))) + ']') def _latex_(self): '\n A latex representation of ``self`` using the ``tikzpicture`` package.\n\n EXAMPLES::\n\n sage: P = PerfectMatching([(1,3),(2,5),(4,6)])\n sage: latex(P) # random # needs sage.graphs sage.plot\n \\begin{tikzpicture}\n ...\n \\end{tikzpicture}\n\n TESTS:\n\n Above we added ``random`` since warnings might be displayed\n once. The second time, there should be no warnings::\n\n sage: print(P._latex_()) # needs sage.graphs sage.plot\n \\begin{tikzpicture}\n ...\n \\end{tikzpicture}\n\n .. TODO::\n\n This should probably call the latex method of\n :class:`SetPartition` with appropriate defaults.\n ' G = self.to_graph() G.set_pos(G.layout_circular()) G.set_latex_options(vertex_size=0.4, edge_thickness=0.04) return G._latex_() def standardization(self): "\n Return the standardization of ``self``.\n\n See :meth:`SetPartition.standardization` for details.\n\n EXAMPLES::\n\n sage: n = PerfectMatching([('c','b'),('d','f'),('e','a')])\n sage: n.standardization()\n [(1, 5), (2, 3), (4, 6)]\n\n " P = PerfectMatchings((2 * len(self))) return P(SetPartition.standardization(self)) def partner(self, x): "\n Return the element in the same pair than ``x``\n in the matching ``self``.\n\n EXAMPLES::\n\n sage: m = PerfectMatching([(-3, 1), (2, 4), (-2, 7)])\n sage: m.partner(4)\n 2\n sage: n = PerfectMatching([('c','b'),('d','f'),('e','a')])\n sage: n.partner('c')\n 'b'\n " for (a, b) in self: if (a == x): return b if (b == x): return a raise ValueError(('%s in not an element of the %s' % (x, self))) def loops_iterator(self, other=None): '\n Iterate through the loops of ``self``.\n\n INPUT:\n\n - ``other`` -- a perfect matching of the same set of ``self``.\n (if the second argument is empty, the method :meth:`an_element` is\n called on the parent of the first)\n\n OUTPUT:\n\n If we draw the two perfect matchings simultaneously as edges of a\n graph, the graph obtained is a union of cycles of even lengths.\n The function returns an iterator for these cycles (each cycle is\n given as a list).\n\n EXAMPLES::\n\n sage: o = PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])\n sage: p = PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])\n sage: it = o.loops_iterator(p)\n sage: next(it)\n [1, 7, 2, 4, 3, 8, 5, 6]\n sage: next(it)\n Traceback (most recent call last):\n ...\n StopIteration\n ' if (other is None): other = self.parent().an_element() elif (self.parent() != other.parent()): raise ValueError(('%s is not a matching of the ground set of %s' % (other, self))) remain = self.base_set().set() while remain: a = remain.pop() b = self.partner(a) remain.remove(b) loop = [a, b] c = other.partner(b) while (c != a): b = self.partner(c) remain.remove(c) loop.append(c) remain.remove(b) loop.append(b) c = other.partner(b) (yield loop) def loops(self, other=None): "\n Return the loops of ``self``.\n\n INPUT:\n\n - ``other`` -- a perfect matching of the same set of ``self``.\n (if the second argument is empty, the method :meth:`an_element` is\n called on the parent of the first)\n\n OUTPUT:\n\n If we draw the two perfect matchings simultaneously as edges of a\n graph, the graph obtained is a union of cycles of even lengths.\n The function returns the list of these cycles (each cycle is given\n as a list).\n\n EXAMPLES::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])\n sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])\n sage: loops = m.loops(n)\n sage: loops # random\n [['a', 'e', 'c', 'b'], ['d', 'f']]\n\n sage: o = PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])\n sage: p = PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])\n sage: o.loops(p)\n [[1, 7, 2, 4, 3, 8, 5, 6]]\n\n TESTS:\n\n Test whether the shorter element of ``loops`` is ``['d', 'f']``\n and the longer element is the cycle ``['a', 'e', 'c', 'b']`` or\n its reverse, or one of their cyclic permutations::\n\n sage: loops = sorted(loops, key=len)\n sage: sorted(loops[0])\n ['d', 'f']\n sage: G = SymmetricGroup(4) # needs sage.groups\n sage: g = G([(1,2,3,4)]) # needs sage.groups\n sage: ((loops[1] in [permutation_action(g**i, ['a', 'e', 'c', 'b']) # needs sage.groups\n ....: for i in range(4)])\n ....: or (loops[1] in [permutation_action(g**i, ['a', 'b', 'c', 'e'])\n ....: for i in range(4)]))\n True\n " return list(self.loops_iterator(other)) def loop_type(self, other=None): "\n Return the loop type of ``self``.\n\n INPUT:\n\n - ``other`` -- a perfect matching of the same set of ``self``.\n (if the second argument is empty, the method :meth:`an_element` is\n called on the parent of the first)\n\n OUTPUT:\n\n If we draw the two perfect matchings simultaneously as edges of a\n graph, the graph obtained is a union of cycles of even\n lengths. The function returns the ordered list of the semi-length\n of these cycles (considered as a partition)\n\n EXAMPLES::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])\n sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])\n sage: m.loop_type(n)\n [2, 1]\n\n TESTS::\n\n sage: m = PerfectMatching([]); m.loop_type()\n []\n " return Partition(sorted(((len(l) // 2) for l in self.loops_iterator(other)), reverse=True)) def number_of_loops(self, other=None): "\n Return the number of loops of ``self``.\n\n INPUT:\n\n - ``other`` -- a perfect matching of the same set of ``self``.\n (if the second argument is empty, the method :meth:`an_element` is\n called on the parent of the first)\n\n OUTPUT:\n\n If we draw the two perfect matchings simultaneously as edges of a\n graph, the graph obtained is a union of cycles of even lengths.\n The function returns their numbers.\n\n EXAMPLES::\n\n sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])\n sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])\n sage: m.number_of_loops(n)\n 2\n " return Integer(len(list(self.loops_iterator(other)))) def Weingarten_function(self, d, other=None): "\n Return the Weingarten function of two pairings.\n\n This function is the value of some integrals over the orthogonal\n groups `O_N`. With the convention of [CM]_, the method returns\n `Wg^{O(d)}(other,self)`.\n\n EXAMPLES::\n\n sage: var('N') # needs sage.symbolic\n N\n sage: m = PerfectMatching([(1,3),(2,4)])\n sage: n = PerfectMatching([(1,2),(3,4)])\n sage: factor(m.Weingarten_function(N, n)) # needs sage.symbolic\n -1/((N + 2)*(N - 1)*N)\n " if (other is None): other = self.parent().an_element() W = self.parent().Weingarten_matrix(d) return W[other.rank()][self.rank()] def to_graph(self): '\n Return the graph corresponding to the perfect matching.\n\n OUTPUT:\n\n The realization of ``self`` as a graph.\n\n EXAMPLES::\n\n sage: PerfectMatching([[1,3], [4,2]]).to_graph().edges(sort=True, # needs sage.graphs\n ....: labels=False)\n [(1, 3), (2, 4)]\n sage: PerfectMatching([[1,4], [3,2]]).to_graph().edges(sort=True, # needs sage.graphs\n ....: labels=False)\n [(1, 4), (2, 3)]\n sage: PerfectMatching([]).to_graph().edges(sort=True, labels=False) # needs sage.graphs\n []\n ' from sage.graphs.graph import Graph return Graph([list(p) for p in self], format='list_of_edges') def to_noncrossing_set_partition(self): '\n Return the noncrossing set partition (on half as many elements)\n corresponding to the perfect matching if the perfect matching is\n noncrossing, and otherwise gives an error.\n\n OUTPUT:\n\n The realization of ``self`` as a noncrossing set partition.\n\n EXAMPLES::\n\n sage: PerfectMatching([[1,3], [4,2]]).to_noncrossing_set_partition()\n Traceback (most recent call last):\n ...\n ValueError: matching must be non-crossing\n sage: PerfectMatching([[1,4], [3,2]]).to_noncrossing_set_partition()\n {{1, 2}}\n sage: PerfectMatching([]).to_noncrossing_set_partition()\n {}\n ' if (not self.is_noncrossing()): raise ValueError('matching must be non-crossing') else: perm = self.to_permutation() perm2 = Permutation([(perm[(2 * i)] // 2) for i in range((len(perm) // 2))]) return SetPartition(perm2.cycle_tuples())
class PerfectMatchings(SetPartitions_set): "\n Perfect matchings of a ground set.\n\n INPUT:\n\n - ``s`` -- an iterable of hashable objects or an integer\n\n EXAMPLES:\n\n If the argument ``s`` is an integer `n`, it will be transformed\n into the set `\\{1, \\ldots, n\\}`::\n\n sage: M = PerfectMatchings(6); M\n Perfect matchings of {1, 2, 3, 4, 5, 6}\n sage: PerfectMatchings([-1, -3, 1, 2])\n Perfect matchings of {1, 2, -3, -1}\n\n One can ask for the list, the cardinality or an element of a set of\n perfect matching::\n\n sage: PerfectMatchings(4).list()\n [[(1, 2), (3, 4)], [(1, 3), (2, 4)], [(1, 4), (2, 3)]]\n sage: PerfectMatchings(8).cardinality()\n 105\n sage: M = PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))\n sage: x = M.an_element()\n sage: x # random\n [('a', 'c'), ('b', 'e'), ('d', 'f')]\n sage: all(PerfectMatchings(i).an_element() in PerfectMatchings(i)\n ....: for i in range(2,11,2))\n True\n\n TESTS:\n\n Test that ``x = M.an_element()`` is actually a perfect matching::\n\n sage: set().union(*x) == M.base_set()\n True\n sage: sum([len(a) for a in x]) == M.base_set().cardinality()\n True\n\n sage: M = PerfectMatchings(6)\n sage: TestSuite(M).run()\n\n sage: M = PerfectMatchings([])\n sage: M.list()\n [[]]\n sage: TestSuite(M).run()\n\n sage: PerfectMatchings(0).list()\n [[]]\n\n sage: M = PerfectMatchings(5)\n sage: M.list()\n []\n sage: TestSuite(M).run()\n\n ::\n\n sage: S = PerfectMatchings(4)\n sage: elt = S([[1,3],[2,4]]); elt\n [(1, 3), (2, 4)]\n sage: S = PerfectMatchings([])\n sage: S([])\n []\n " @staticmethod def __classcall_private__(cls, s): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: S = PerfectMatchings(4)\n sage: T = PerfectMatchings([1,2,3,4])\n sage: S is T\n True\n ' if isinstance(s, (int, Integer)): s = frozenset(range(1, (s + 1))) else: try: if (s.cardinality() == infinity): raise ValueError('the set must be finite') except AttributeError: pass s = frozenset(s) return super().__classcall__(cls, s) def _repr_(self): '\n Return a description of ``self``.\n\n TESTS::\n\n sage: PerfectMatchings([-1, -3, 1, 2])\n Perfect matchings of {1, 2, -3, -1}\n ' return ('Perfect matchings of %s' % Set(self._set)) def __iter__(self): '\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: PerfectMatchings(4).list()\n [[(1, 2), (3, 4)], [(1, 3), (2, 4)], [(1, 4), (2, 3)]]\n ' s = list(self._set) if (len(s) % 2): return for val in perfect_matchings_iterator((len(s) // 2)): (yield self.element_class(self, ((s[a], s[b]) for (a, b) in val), check=False, sort=False)) def __contains__(self, x): "\n Test if ``x`` is an element of ``self``.\n\n EXAMPLES::\n\n sage: m = PerfectMatching([(1,2),(4,3)])\n sage: m in PerfectMatchings(4)\n True\n sage: m in PerfectMatchings((0, 1, 2, 3))\n False\n sage: all(m in PerfectMatchings(6) for m in PerfectMatchings(6))\n True\n\n Note that the class of ``x`` does not need to be ``PerfectMatching``:\n if the data defines a perfect matching of the good set, the function\n returns ``True``::\n\n sage: [(1, 4), (2, 3)] in PerfectMatchings(4)\n True\n sage: [(1, 3, 6), (2, 4), (5,)] in PerfectMatchings(6)\n False\n sage: [('a', 'b'), ('a', 'c')] in PerfectMatchings(\n ....: ('a', 'b', 'c', 'd'))\n False\n\n TESTS::\n\n sage: SA = PerfectMatchings([1,2,3,7])\n sage: Set([Set([1,2]),Set([3,7])]) in SA\n True\n sage: Set([Set([1,2]),Set([2,3])]) in SA\n False\n sage: Set([]) in SA\n False\n " if (not all(((len(p) == 2) for p in x))): return False base_set = Set([e for p in x for e in p]) return ((len(base_set) == (2 * len(x))) and (base_set == Set(self._set))) def base_set(self): '\n Return the base set of ``self``.\n\n EXAMPLES::\n\n sage: PerfectMatchings(3).base_set()\n {1, 2, 3}\n ' return Set(self._set) def base_set_cardinality(self): '\n Return the cardinality of the base set of ``self``.\n\n EXAMPLES::\n\n sage: PerfectMatchings(3).base_set_cardinality()\n 3\n ' return len(self._set) def cardinality(self): '\n Return the cardinality of the set of perfect matchings ``self``.\n\n This is `1*3*5*...*(2n-1)`, where `2n` is the size of the ground set.\n\n EXAMPLES::\n\n sage: PerfectMatchings(8).cardinality()\n 105\n sage: PerfectMatchings([1,2,3,4]).cardinality()\n 3\n sage: PerfectMatchings(3).cardinality()\n 0\n sage: PerfectMatchings([]).cardinality()\n 1\n ' n = len(self._set) if (n % 2): return Integer(0) else: return Integer(prod(range(1, n, 2))) def random_element(self): "\n Return a random element of ``self``.\n\n EXAMPLES::\n\n sage: M = PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))\n sage: x = M.random_element()\n sage: x # random\n [('a', 'b'), ('c', 'd'), ('e', 'f')]\n\n TESTS::\n\n sage: x in M\n True\n sage: p = PerfectMatchings(13).random_element()\n Traceback (most recent call last):\n ...\n ValueError: there is no perfect matching on an odd number of elements\n " n = len(self._set) if (n % 2): raise ValueError('there is no perfect matching on an odd number of elements') k = (n // 2) p = Permutations(n).random_element() l = list(self._set) return self.element_class(self, [(l[(p[(2 * i)] - 1)], l[(p[((2 * i) + 1)] - 1)]) for i in range(k)], check=False) @cached_method def Weingarten_matrix(self, N): "\n Return the Weingarten matrix corresponding to the set of\n PerfectMatchings ``self``.\n\n It is a useful theoretical tool to compute polynomial integrals\n over the orthogonal group `O_N` (see [CM]_).\n\n EXAMPLES::\n\n sage: M = PerfectMatchings(4).Weingarten_matrix(var('N')) # needs sage.symbolic\n sage: N*(N-1)*(N+2)*M.apply_map(factor) # needs sage.symbolic\n [N + 1 -1 -1]\n [ -1 N + 1 -1]\n [ -1 -1 N + 1]\n " G = matrix([[(N ** p1.number_of_loops(p2)) for p1 in self] for p2 in self]) return (G ** (- 1)) Element = PerfectMatching
class Permutation(CombinatorialElement): "\n A permutation.\n\n Converts ``l`` to a permutation on `\\{1, 2, \\ldots, n\\}`.\n\n INPUT:\n\n - ``l`` -- Can be any one of the following:\n\n - an instance of :class:`Permutation`,\n\n - list of integers, viewed as one-line permutation notation. The\n construction checks that you give an acceptable entry. To avoid\n the check, use the ``check`` option.\n\n - string, expressing the permutation in cycle notation.\n\n - list of tuples of integers, expressing the permutation in cycle\n notation.\n\n - a :class:`PermutationGroupElement`\n\n - a pair of two standard tableaux of the same shape. This yields\n the permutation obtained from the pair using the inverse of the\n Robinson-Schensted algorithm.\n\n - ``check`` (boolean) -- whether to check that input is correct. Slows\n the function down, but ensures that nothing bad happens. This is set to\n ``True`` by default.\n\n .. WARNING::\n\n Since :trac:`13742` the input is checked for correctness : it is not\n accepted unless it actually is a permutation on `\\{1, \\ldots, n\\}`. It\n means that some :meth:`Permutation` objects cannot be created anymore\n without setting ``check=False``, as there is no certainty that\n its functions can handle them, and this should be fixed in a much\n better way ASAP (the functions should be rewritten to handle those\n cases, and new tests be added).\n\n .. WARNING::\n\n There are two possible conventions for multiplying permutations, and\n the one currently enabled in Sage by default is the one which has\n `(pq)(i) = q(p(i))` for any permutations `p \\in S_n` and `q \\in S_n`\n and any `1 \\leq i \\leq n`. (This equation looks less strange when\n the action of permutations on numbers is written from the right:\n then it takes the form `i^{pq} = (i^p)^q`, which is an associativity\n law). There is an alternative convention, which has\n `(pq)(i) = p(q(i))` instead. The conventions can be switched at\n runtime using\n :meth:`sage.combinat.permutation.Permutations.options`.\n It is best for code not to rely on this setting being set to a\n particular standard, but rather use the methods\n :meth:`left_action_product` and :meth:`right_action_product` for\n multiplying permutations (these methods don't depend on the setting).\n See :trac:`14885` for more details.\n\n .. NOTE::\n\n The ``bruhat*`` methods refer to the *strong* Bruhat order. To use\n the *weak* Bruhat order, look under ``permutohedron*``.\n\n EXAMPLES::\n\n sage: Permutation([2,1])\n [2, 1]\n sage: Permutation([2, 1, 4, 5, 3])\n [2, 1, 4, 5, 3]\n sage: Permutation('(1,2)')\n [2, 1]\n sage: Permutation('(1,2)(3,4,5)')\n [2, 1, 4, 5, 3]\n sage: Permutation( ((1,2),(3,4,5)) )\n [2, 1, 4, 5, 3]\n sage: Permutation( [(1,2),(3,4,5)] )\n [2, 1, 4, 5, 3]\n sage: Permutation( ((1,2)) )\n [2, 1]\n sage: Permutation( (1,2) )\n [2, 1]\n sage: Permutation( ((1,2),) )\n [2, 1]\n sage: Permutation( ((1,),) )\n [1]\n sage: Permutation( (1,) )\n [1]\n sage: Permutation( () )\n []\n sage: Permutation( ((),) )\n []\n sage: p = Permutation((1, 2, 5)); p\n [2, 5, 3, 4, 1]\n sage: type(p)\n <class 'sage.combinat.permutation.StandardPermutations_n_with_category.element_class'>\n\n Construction from a string in cycle notation::\n\n sage: p = Permutation( '(4,5)' ); p\n [1, 2, 3, 5, 4]\n\n The size of the permutation is the maximum integer appearing; add\n a 1-cycle to increase this::\n\n sage: p2 = Permutation( '(4,5)(10)' ); p2\n [1, 2, 3, 5, 4, 6, 7, 8, 9, 10]\n sage: len(p); len(p2)\n 5\n 10\n\n We construct a :class:`Permutation` from a\n :class:`PermutationGroupElement`::\n\n sage: g = PermutationGroupElement([2,1,3]) # needs sage.groups\n sage: Permutation(g) # needs sage.groups\n [2, 1, 3]\n\n From a pair of tableaux of the same shape. This uses the inverse\n of the Robinson-Schensted algorithm::\n\n sage: # needs sage.combinat\n sage: p = [[1, 4, 7], [2, 5], [3], [6]]\n sage: q = [[1, 2, 5], [3, 6], [4], [7]]\n sage: P = Tableau(p)\n sage: Q = Tableau(q)\n sage: Permutation( (p, q) )\n [3, 6, 5, 2, 7, 4, 1]\n sage: Permutation( [p, q] )\n [3, 6, 5, 2, 7, 4, 1]\n sage: Permutation( (P, Q) )\n [3, 6, 5, 2, 7, 4, 1]\n sage: Permutation( [P, Q] )\n [3, 6, 5, 2, 7, 4, 1]\n\n TESTS::\n\n sage: Permutation([()])\n []\n sage: Permutation('()')\n []\n sage: Permutation(())\n []\n sage: Permutation( [1] )\n [1]\n\n From a pair of empty tableaux ::\n\n sage: Permutation( ([], []) ) # needs sage.combinat\n []\n sage: Permutation( [[], []] ) # needs sage.combinat\n []\n " @staticmethod @rename_keyword(deprecation=35233, check_input='check') def __classcall_private__(cls, l, check=True): '\n Return a permutation in the general permutations parent.\n\n EXAMPLES::\n\n sage: P = Permutation([2,1]); P\n [2, 1]\n sage: P.parent()\n Standard permutations\n ' if isinstance(l, Permutation): return l elif isinstance(l, PermutationGroupElement): l = l.domain() elif isinstance(l, str): if ((l == '()') or (l == '')): return from_cycles(0, []) cycles = l.split(')(') cycles[0] = cycles[0][1:] cycles[(- 1)] = cycles[(- 1)][:(- 1)] cycle_list = [] for c in cycles: cycle_list.append([int(_) for _ in c.split(',')]) return from_cycles(max((max(c) for c in cycle_list)), cycle_list) elif (isinstance(l, (tuple, list)) and (len(l) == 2) and all((isinstance(x, Tableau) for x in l))): return RSK_inverse(*l, output='permutation') elif (isinstance(l, (tuple, list)) and (len(l) == 2) and all((isinstance(x, list) for x in l))): (P, Q) = (Tableau(_) for _ in l) return RSK_inverse(P, Q, 'permutation') elif (isinstance(l, tuple) or (isinstance(l, list) and l and all((isinstance(x, tuple) for x in l)))): if (l and (isinstance(l[0], (int, Integer)) or (len(l[0]) > 0))): if isinstance(l[0], tuple): n = max((max(x) for x in l)) return from_cycles(n, [list(x) for x in l]) else: n = max(l) return from_cycles(n, [list(l)]) elif (len(l) <= 1): return Permutations()([]) else: raise ValueError(('cannot convert l (= %s) to a Permutation' % l)) return Permutations()(l, check=check) @rename_keyword(deprecation=35233, check_input='check') def __init__(self, parent, l, check=True): '\n Constructor. Checks that INPUT is not a mess, and calls\n :class:`CombinatorialElement`. It should not, because\n :class:`CombinatorialElement` is deprecated.\n\n INPUT:\n\n - ``l`` -- a list of ``int`` variables\n\n - ``check`` (boolean) -- whether to check that input is\n correct. Slows the function down, but ensures that nothing bad\n happens.\n\n This is set to ``True`` by default.\n\n TESTS::\n\n sage: Permutation([1,2,3])\n [1, 2, 3]\n sage: Permutation([1,2,2,4])\n Traceback (most recent call last):\n ...\n ValueError: an element appears twice in the input\n sage: Permutation([1,2,4,-1])\n Traceback (most recent call last):\n ...\n ValueError: the elements must be strictly positive integers\n sage: Permutation([1,2,4,5])\n Traceback (most recent call last):\n ...\n ValueError: The permutation has length 4 but its maximal element is\n 5. Some element may be repeated, or an element is missing, but there\n is something wrong with its length.\n ' l = list(l) if (check and (len(l) > 0)): lst = list(l) for i in lst: try: i = int(i) except TypeError: raise ValueError('the elements must be integer variables') if (i < 1): raise ValueError('the elements must be strictly positive integers') lst.sort() if (int(lst[(- 1)]) != len(lst)): raise ValueError((((((('The permutation has length ' + str(len(lst))) + ' but its maximal element is ') + str(int(lst[(- 1)]))) + '. Some element ') + 'may be repeated, or an element is missing') + ', but there is something wrong with its length.')) previous = (lst[0] - 1) for i in lst: if (i == previous): raise ValueError('an element appears twice in the input') previous = i CombinatorialElement.__init__(self, parent, l) def __setstate__(self, state): "\n In order to maintain backwards compatibility and be able to unpickle a\n old pickle from ``Permutation_class`` we have to override the default\n ``__setstate__``.\n\n EXAMPLES::\n\n sage: loads(b'x\\x9ck`J.NLO\\xd5K\\xce\\xcfM\\xca\\xccK,\\xd1+H-\\xca--I,\\xc9\\xcc\\xcf\\xe3\\n@\\xb0\\xe3\\x93s\\x12\\x8b\\x8b\\xb9\\n\\x195\\x1b'\n ....: b'\\x0b\\x99j\\x0b\\x995BY\\xe33\\x12\\x8b3\\nY\\xfc\\x80\\xac\\x9c\\xcc\\xe2\\x92B\\xd6\\xd8B6\\r\\x88iE\\x99y\\xe9\\xc5z\\x99y%\\xa9\\xe9'\n ....: b'\\xa9E\\\\\\xb9\\x89\\xd9\\xa9\\xf10N!{(\\xa3qkP!G\\x06\\x90a\\x04dp\\x82\\x18\\x86@\\x06Wji\\x92\\x1e\\x00i\\x8d0q')\n [3, 2, 1]\n sage: loads(dumps( Permutation([3,2,1]) )) # indirect doctest\n [3, 2, 1]\n " if isinstance(state, dict): self._set_parent(Permutations()) self.__dict__ = state else: self._set_parent(state[0]) self.__dict__ = state[1] @cached_method def __hash__(self): '\n TESTS::\n\n sage: d = {}\n sage: p = Permutation([1,2,3])\n sage: d[p] = 1\n sage: d[p]\n 1\n ' try: return hash(tuple(self._list)) except TypeError: return hash(str(self._list)) def __str__(self) -> str: "\n TESTS::\n\n sage: Permutations.options.display='list'\n sage: p = Permutation([2,1,3])\n sage: str(p)\n '[2, 1, 3]'\n sage: Permutations.options.display='cycle'\n sage: str(p)\n '(1,2)'\n sage: Permutations.options.display='singleton'\n sage: str(p)\n '(1,2)(3)'\n sage: Permutations.options.display='list'\n " return repr(self) def _repr_(self) -> str: "\n TESTS::\n\n sage: p = Permutation([2,1,3])\n sage: p\n [2, 1, 3]\n sage: Permutations.options.display='cycle'\n sage: p\n (1,2)\n sage: Permutations.options.display='singleton'\n sage: p\n (1,2)(3)\n sage: Permutations.options.display='reduced_word'\n sage: p\n [1]\n sage: Permutations.options._reset()\n " display = self.parent().options.display if (display == 'list'): return repr(self._list) elif (display == 'cycle'): return self.cycle_string() elif (display == 'singleton'): return self.cycle_string(singletons=True) elif (display == 'reduced_word'): return repr(self.reduced_word()) raise ValueError('unknown display option') def _latex_(self): '\n Return a `\\LaTeX` representation of ``self``.\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: latex(p)\n [2, 1, 3]\n sage: Permutations.options.latex=\'cycle\'\n sage: latex(p)\n (1 \\; 2)\n sage: Permutations.options.latex=\'singleton\'\n sage: latex(p)\n (1 \\; 2)(3)\n sage: Permutations.options.latex=\'reduced_word\'\n sage: latex(p)\n s_{1}\n sage: latex(Permutation([1,2,3]))\n 1\n sage: Permutations.options.latex_empty_str="e"\n sage: latex(Permutation([1,2,3]))\n e\n sage: Permutations.options.latex=\'twoline\'\n sage: latex(p)\n \\begin{pmatrix} 1 & 2 & 3 \\\\ 2 & 1 & 3 \\end{pmatrix}\n sage: Permutations.options._reset()\n ' display = self.parent().options.latex if (display == 'reduced_word'): let = self.parent().options.generator_name redword = self.reduced_word() if (not redword): return self.parent().options.latex_empty_str return ' '.join((('%s_{%s}' % (let, i)) for i in redword)) if (display == 'twoline'): return ('\\begin{pmatrix} %s \\\\ %s \\end{pmatrix}' % (' & '.join((('%s' % i) for i in range(1, (len(self._list) + 1)))), ' & '.join((('%s' % i) for i in self._list)))) if (display == 'list'): return repr(self._list) if (display == 'cycle'): ret = self.cycle_string() else: ret = self.cycle_string(singletons=True) return ret.replace(',', ' \\; ') def _gap_(self, gap): "\n Return a GAP version of this permutation.\n\n EXAMPLES::\n\n sage: gap(Permutation([1,2,3])) # needs sage.libs.gap\n ()\n sage: gap(Permutation((1,2,3))) # needs sage.libs.gap\n (1,2,3)\n sage: type(_) # needs sage.libs.gap\n <class 'sage.interfaces.gap.GapElement'>\n " return self.to_permutation_group_element()._gap_(gap) def size(self) -> Integer: '\n Return the size of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([3,4,1,2,5]).size()\n 5\n ' return len(self) grade = size def cycle_string(self, singletons=False) -> str: "\n Return a string of the permutation in cycle notation.\n\n If ``singletons=True``, it includes 1-cycles in the string.\n\n EXAMPLES::\n\n sage: Permutation([1,2,3]).cycle_string()\n '()'\n sage: Permutation([2,1,3]).cycle_string()\n '(1,2)'\n sage: Permutation([2,3,1]).cycle_string()\n '(1,2,3)'\n sage: Permutation([2,1,3]).cycle_string(singletons=True)\n '(1,2)(3)'\n " cycles = self.to_cycles(singletons=singletons) if (not cycles): return '()' else: return ''.join(((('(' + ','.join((str(l) for l in x))) + ')') for x in cycles)) def __next__(self): '\n Return the permutation that follows ``self`` in lexicographic order on\n the symmetric group containing ``self``. If ``self`` is the last\n permutation, then ``next`` returns ``False``.\n\n EXAMPLES::\n\n sage: p = Permutation([1, 3, 2])\n sage: next(p)\n [2, 1, 3]\n sage: p = Permutation([4,3,2,1])\n sage: next(p)\n False\n\n TESTS::\n\n sage: p = Permutation([])\n sage: next(p)\n False\n ' p = self[:] n = len(self) first = (- 1) for i in reversed(range((n - 1))): if (p[i] < p[(i + 1)]): first = i break if (first == (- 1)): return False j = (n - 1) while (p[j] < p[first]): j -= 1 (p[j], p[first]) = (p[first], p[j]) first_half = p[:(first + 1)] last_half = p[(first + 1):] last_half.reverse() p = (first_half + last_half) return Permutations()(p) next = __next__ def prev(self): '\n Return the permutation that comes directly before ``self`` in\n lexicographic order on the symmetric group containing ``self``.\n If ``self`` is the first permutation, then it returns ``False``.\n\n EXAMPLES::\n\n sage: p = Permutation([1,2,3])\n sage: p.prev()\n False\n sage: p = Permutation([1,3,2])\n sage: p.prev()\n [1, 2, 3]\n\n TESTS::\n\n sage: p = Permutation([])\n sage: p.prev()\n False\n\n Check that :trac:`16913` is fixed::\n\n sage: Permutation([1,4,3,2]).prev()\n [1, 4, 2, 3]\n ' p = self[:] n = len(self) first = (- 1) for i in reversed(range((n - 1))): if (p[i] > p[(i + 1)]): first = i break if (first == (- 1)): return False j = (n - 1) while (p[j] > p[first]): j -= 1 (p[j], p[first]) = (p[first], p[j]) first_half = p[:(first + 1)] last_half = p[(first + 1):] last_half.reverse() p = (first_half + last_half) return Permutations()(p) def to_tableau_by_shape(self, shape): '\n Return a tableau of shape ``shape`` with the entries\n in ``self``. The tableau is such that the reading word (i. e.,\n the word obtained by reading the tableau row by row, starting\n from the top row in English notation, with each row being\n read from left to right) is ``self``.\n\n EXAMPLES::\n\n sage: T = Permutation([3,4,1,2,5]).to_tableau_by_shape([3,2]); T # needs sage.combinat\n [[1, 2, 5], [3, 4]]\n sage: T.reading_word_permutation() # needs sage.combinat\n [3, 4, 1, 2, 5]\n ' if (sum(shape) != len(self)): raise ValueError('the size of the partition must be the size of self') t = [] w = list(self) for i in reversed(shape): t = ([w[:i]] + t) w = w[i:] return Tableau(t) def to_cycles(self, singletons=True, use_min=True): '\n Return the permutation ``self`` as a list of disjoint cycles.\n\n The cycles are returned in the order of increasing smallest\n elements, and each cycle is returned as a tuple which starts\n with its smallest element.\n\n If ``singletons=False`` is given, the list does not contain the\n singleton cycles.\n\n If ``use_min=False`` is given, the cycles are returned in the\n order of increasing *largest* (not smallest) elements, and\n each cycle starts with its largest element.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3,4]).to_cycles()\n [(1, 2), (3,), (4,)]\n sage: Permutation([2,1,3,4]).to_cycles(singletons=False)\n [(1, 2)]\n sage: Permutation([2,1,3,4]).to_cycles(use_min=True)\n [(1, 2), (3,), (4,)]\n sage: Permutation([2,1,3,4]).to_cycles(use_min=False)\n [(4,), (3,), (2, 1)]\n sage: Permutation([2,1,3,4]).to_cycles(singletons=False, use_min=False)\n [(2, 1)]\n\n sage: Permutation([4,1,5,2,6,3]).to_cycles()\n [(1, 4, 2), (3, 5, 6)]\n sage: Permutation([4,1,5,2,6,3]).to_cycles(use_min=False)\n [(6, 3, 5), (4, 2, 1)]\n\n sage: Permutation([6, 4, 5, 2, 3, 1]).to_cycles()\n [(1, 6), (2, 4), (3, 5)]\n sage: Permutation([6, 4, 5, 2, 3, 1]).to_cycles(use_min=False)\n [(6, 1), (5, 3), (4, 2)]\n\n The algorithm is of complexity `O(n)` where `n` is the size of the\n given permutation.\n\n TESTS::\n\n sage: from sage.combinat.permutation import from_cycles\n sage: for n in range(1,6):\n ....: for p in Permutations(n):\n ....: if from_cycles(n, p.to_cycles()) != p:\n ....: print("There is a problem with {}".format(p))\n ....: break\n sage: size = 10000\n sage: sample = (Permutations(size).random_element() for i in range(5))\n sage: all(from_cycles(size, p.to_cycles()) == p for p in sample)\n True\n\n Note: there is an alternative implementation called ``_to_cycle_set``\n which could be slightly (10%) faster for some input (typically for\n permutations of size in the range [100, 10000]). You can run the\n following benchmarks. For small permutations::\n\n sage: for size in range(9): # not tested\n ....: print(size)\n ....: lp = Permutations(size).list()\n ....: timeit(\'[p.to_cycles(False) for p in lp]\')\n ....: timeit(\'[p._to_cycles_set(False) for p in lp]\')\n ....: timeit(\'[p._to_cycles_list(False) for p in lp]\')\n ....: timeit(\'[p._to_cycles_orig(False) for p in lp]\')\n\n and larger ones::\n\n sage: for size in [10, 20, 50, 75, 100, 200, 500, 1000, # not tested\n ....: 2000, 5000, 10000, 15000, 20000, 30000,\n ....: 50000, 80000, 100000]:\n ....: print(size)\n ....: lp = [Permutations(size).random_element() for i in range(20)]\n ....: timeit("[p.to_cycles() for p in lp]")\n ....: timeit("[p._to_cycles_set() for p in lp]")\n ....: timeit("[p._to_cycles_list() for p in lp]")\n ' cycles = [] l = self[:] if use_min: groundset = range(len(l)) else: groundset = reversed(range(len(l))) for i in groundset: if (not l[i]): continue cycleFirst = (i + 1) cycle = [cycleFirst] (l[i], next) = (False, l[i]) while (next != cycleFirst): cycle.append(next) (l[(next - 1)], next) = (False, l[(next - 1)]) if (singletons or (len(cycle) > 1)): cycles.append(tuple(cycle)) return cycles cycle_tuples = to_cycles def _to_cycles_orig(self, singletons=True): '\n Return the permutation ``self`` as a list of disjoint cycles.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3,4])._to_cycles_orig()\n [(1, 2), (3,), (4,)]\n sage: Permutation([2,1,3,4])._to_cycles_orig(singletons=False)\n [(1, 2)]\n ' p = self[:] cycles = [] toConsider = (- 1) l = [(i + 1) for i in range(len(p))] cycle = [] while l: if (toConsider == (- 1)): if singletons: if cycle: cycles.append(tuple(cycle)) elif (len(cycle) > 1): cycles.append(tuple(cycle)) toConsider = l[0] l.remove(toConsider) cycle = [toConsider] cycleFirst = toConsider next = p[(toConsider - 1)] if (next == cycleFirst): toConsider = (- 1) else: cycle.append(next) l.remove(next) toConsider = next if singletons: if cycle: cycles.append(tuple(cycle)) elif (len(cycle) > 1): cycles.append(tuple(cycle)) return cycles def _to_cycles_set(self, singletons=True): '\n Return the permutation ``self`` as a list of disjoint cycles.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3,4])._to_cycles_set()\n [(1, 2), (3,), (4,)]\n sage: Permutation([2,1,3,4])._to_cycles_set(singletons=False)\n [(1, 2)]\n\n TESTS::\n\n sage: all((p._to_cycles_set(False) == p._to_cycles_orig(False)\n ....: for i in range(7) for p in Permutations(i)))\n True\n ' p = self[:] cycles = [] if (not singletons): L = set(((i + 1) for (i, pi) in enumerate(p) if (pi != (i + 1)))) else: L = set(range(1, (len(p) + 1))) while L: cycleFirst = L.pop() next = p[(cycleFirst - 1)] cycle = [cycleFirst] while (next != cycleFirst): cycle.append(next) L.remove(next) next = p[(next - 1)] cycles.append(tuple(cycle)) return cycles def _to_cycles_list(self, singletons=True): '\n Return the permutation ``self`` as a list of disjoint cycles.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3,4])._to_cycles_list()\n [(1, 2), (3,), (4,)]\n sage: Permutation([2,1,3,4])._to_cycles_list(singletons=False)\n [(1, 2)]\n\n TESTS::\n\n sage: all((p._to_cycles_list(False) == p._to_cycles_orig(False)\n ....: for i in range(7) for p in Permutations(i)))\n True\n ' p = self[:] cycles = [] if (not singletons): L = [(i + 1) for (i, pi) in enumerate(p) if (pi != (i + 1))] else: L = list(range(1, (len(p) + 1))) from bisect import bisect_left while L: cycleFirst = L.pop(0) next = p[(cycleFirst - 1)] cycle = [cycleFirst] while (next != cycleFirst): cycle.append(next) L.pop(bisect_left(L, next)) next = p[(next - 1)] cycles.append(tuple(cycle)) return cycles def to_permutation_group_element(self): '\n Return a PermutationGroupElement equal to ``self``.\n\n EXAMPLES::\n\n sage: Permutation([2,1,4,3]).to_permutation_group_element() # needs sage.groups\n (1,2)(3,4)\n sage: Permutation([1,2,3]).to_permutation_group_element() # needs sage.groups\n ()\n ' grp = SymmetricGroup(len(self)) return grp.element_class(self.to_cycles(singletons=False), grp, check=False) def signature(self) -> Integer: '\n Return the signature of the permutation ``self``. This is\n `(-1)^l`, where `l` is the number of inversions of ``self``.\n\n .. NOTE::\n\n :meth:`sign` can be used as an alias for :meth:`signature`.\n\n EXAMPLES::\n\n sage: Permutation([4, 2, 3, 1, 5]).signature()\n -1\n sage: Permutation([1,3,2,5,4]).sign()\n 1\n sage: Permutation([]).sign()\n 1\n ' return ((- 1) ** (len(self) - len(self.to_cycles()))) sign = signature def is_even(self) -> bool: '\n Return ``True`` if the permutation ``self`` is even and\n ``False`` otherwise.\n\n EXAMPLES::\n\n sage: Permutation([1,2,3]).is_even()\n True\n sage: Permutation([2,1,3]).is_even()\n False\n ' return (self.signature() == 1) def to_matrix(self): "\n Return a matrix representing the permutation.\n\n EXAMPLES::\n\n sage: Permutation([1,2,3]).to_matrix() # needs sage.modules\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n Alternatively::\n\n sage: matrix(Permutation([1,3,2])) # needs sage.modules\n [1 0 0]\n [0 0 1]\n [0 1 0]\n\n Notice that matrix multiplication corresponds to permutation\n multiplication only when the permutation option mult='r2l'\n\n ::\n\n sage: Permutations.options.mult='r2l'\n sage: p = Permutation([2,1,3])\n sage: q = Permutation([3,1,2])\n sage: (p*q).to_matrix() # needs sage.modules\n [0 0 1]\n [0 1 0]\n [1 0 0]\n sage: p.to_matrix()*q.to_matrix() # needs sage.modules\n [0 0 1]\n [0 1 0]\n [1 0 0]\n sage: Permutations.options.mult='l2r'\n sage: (p*q).to_matrix() # needs sage.modules\n [1 0 0]\n [0 0 1]\n [0 1 0]\n " entries = {((v - 1), i): 1 for (i, v) in enumerate(self)} M = MatrixSpace(ZZ, len(self), sparse=True) return M(entries) _matrix_ = to_matrix @combinatorial_map(name='to alternating sign matrix') def to_alternating_sign_matrix(self): '\n Return a matrix representing the permutation in the\n :class:`AlternatingSignMatrix` class.\n\n EXAMPLES::\n\n sage: m = Permutation([1,2,3]).to_alternating_sign_matrix(); m # needs sage.combinat sage.modules\n [1 0 0]\n [0 1 0]\n [0 0 1]\n sage: parent(m) # needs sage.combinat sage.modules\n Alternating sign matrices of size 3\n ' from sage.combinat.alternating_sign_matrix import AlternatingSignMatrix return AlternatingSignMatrix(self.to_matrix().rows()) def __mul__(self, rp): '\n TESTS::\n\n sage: # needs sage.groups sage.modules\n sage: SGA = SymmetricGroupAlgebra(QQ, 3)\n sage: SM = SGA.specht_module([2,1])\n sage: p213 = Permutations(3)([2,1,3])\n sage: p213 * SGA.an_element()\n 3*[1, 2, 3] + [1, 3, 2] + [2, 1, 3] + 2*[3, 1, 2]\n sage: p213 * SM.an_element()\n 2*B[0] - 4*B[1]\n ' if ((not isinstance(rp, Permutation)) and isinstance(rp, Element)): return get_coercion_model().bin_op(self, rp, operator.mul) return Permutation._mul_(self, rp) def _mul_(self, rp) -> Permutation: "\n TESTS::\n\n sage: p213 = Permutation([2,1,3])\n sage: p312 = Permutation([3,1,2])\n sage: Permutations.options.mult='l2r'\n sage: p213*p312\n [1, 3, 2]\n sage: Permutations.options.mult='r2l'\n sage: p213*p312\n [3, 2, 1]\n sage: Permutations.options.mult='l2r'\n " if (self.parent().options.mult == 'l2r'): return self._left_to_right_multiply_on_right(rp) else: return self._left_to_right_multiply_on_left(rp) def __rmul__(self, lp) -> Permutation: "\n TESTS::\n\n sage: p213 = Permutation([2,1,3])\n sage: p312 = Permutation([3,1,2])\n sage: Permutations.options.mult='l2r'\n sage: p213*p312\n [1, 3, 2]\n sage: Permutations.options.mult='r2l'\n sage: p213*p312\n [3, 2, 1]\n sage: Permutations.options.mult='l2r'\n\n sage: SGA = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: SGA.an_element() * Permutations(3)(p213) # needs sage.groups sage.modules\n 3*[1, 2, 3] + [2, 1, 3] + 2*[2, 3, 1] + [3, 2, 1]\n " if ((not isinstance(lp, Permutation)) and isinstance(lp, Element)): return get_coercion_model().bin_op(lp, self, operator.mul) if (self.parent().options.mult == 'l2r'): return self._left_to_right_multiply_on_left(lp) else: return self._left_to_right_multiply_on_right(lp) def left_action_product(self, lp): '\n Return the permutation obtained by composing ``self`` with\n ``lp`` in such an order that ``lp`` is applied first and\n ``self`` is applied afterwards.\n\n This is usually denoted by either ``self * lp`` or ``lp * self``\n depending on the conventions used by the author. If the value\n of a permutation `p \\in S_n` on an integer\n `i \\in \\{ 1, 2, \\cdots, n \\}` is denoted by `p(i)`, then this\n should be denoted by ``self * lp`` in order to have\n associativity (i.e., in order to have\n `(p \\cdot q)(i) = p(q(i))` for all `p`, `q` and `i`). If, on\n the other hand, the value of a permutation `p \\in S_n` on an\n integer `i \\in \\{ 1, 2, \\cdots, n \\}` is denoted by `i^p`, then\n this should be denoted by ``lp * self`` in order to have\n associativity (i.e., in order to have\n `i^{p \\cdot q} = (i^p)^q` for all `p`, `q` and `i`).\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: q = Permutation([3,1,2])\n sage: p.left_action_product(q)\n [3, 2, 1]\n sage: q.left_action_product(p)\n [1, 3, 2]\n ' return Permutations()(left_action_product(self._list, lp[:])) _left_to_right_multiply_on_left = left_action_product def right_action_product(self, rp): '\n Return the permutation obtained by composing ``self`` with\n ``rp`` in such an order that ``self`` is applied first and\n ``rp`` is applied afterwards.\n\n This is usually denoted by either ``self * rp`` or ``rp * self``\n depending on the conventions used by the author. If the value\n of a permutation `p \\in S_n` on an integer\n `i \\in \\{ 1, 2, \\cdots, n \\}` is denoted by `p(i)`, then this\n should be denoted by ``rp * self`` in order to have\n associativity (i.e., in order to have\n `(p \\cdot q)(i) = p(q(i))` for all `p`, `q` and `i`). If, on\n the other hand, the value of a permutation `p \\in S_n` on an\n integer `i \\in \\{ 1, 2, \\cdots, n \\}` is denoted by `i^p`, then\n this should be denoted by ``self * rp`` in order to have\n associativity (i.e., in order to have\n `i^{p \\cdot q} = (i^p)^q` for all `p`, `q` and `i`).\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: q = Permutation([3,1,2])\n sage: p.right_action_product(q)\n [1, 3, 2]\n sage: q.right_action_product(p)\n [3, 2, 1]\n ' return Permutations()(right_action_product(self._list, rp[:])) _left_to_right_multiply_on_right = right_action_product def __call__(self, i): '\n Return the image of the integer `i` under ``self``.\n\n EXAMPLES::\n\n sage: p = Permutation([2, 1, 4, 5, 3])\n sage: p(1)\n 2\n sage: p = Permutation(((1,2),(4,3,5)))\n sage: p(4)\n 3\n sage: p(2)\n 1\n sage: p = Permutation([5,2,1,6,3,7,4])\n sage: list(map(p, range(1,8)))\n [5, 2, 1, 6, 3, 7, 4]\n\n TESTS::\n\n sage: p = Permutation([5,2,1,6,3,7,4])\n sage: p(-1)\n Traceback (most recent call last):\n ...\n TypeError: i (= -1) must be between 1 and 7\n sage: p(10)\n Traceback (most recent call last):\n ...\n TypeError: i (= 10) must be between 1 and 7\n ' if (isinstance(i, (int, Integer)) and (1 <= i <= len(self))): return self[(i - 1)] raise TypeError(('i (= %s) must be between 1 and %s' % (i, len(self)))) def rank(self) -> Integer: '\n Return the rank of ``self`` in the lexicographic ordering on the\n symmetric group to which ``self`` belongs.\n\n EXAMPLES::\n\n sage: Permutation([1,2,3]).rank()\n 0\n sage: Permutation([1, 2, 4, 6, 3, 5]).rank()\n 10\n sage: perms = Permutations(6).list()\n sage: [p.rank() for p in perms] == list(range(factorial(6)))\n True\n ' n = len(self) factoradic = self.to_lehmer_code() return sum(((factoradic[((n - 1) - i)] * factorial(i)) for i in reversed(range(n)))) def to_inversion_vector(self): '\n Return the inversion vector of ``self``.\n\n The inversion vector of a permutation `p \\in S_n` is defined as\n the vector `(v_1, v_2, \\ldots, v_n)`, where `v_i` is the\n number of elements larger than `i` that appear to the left\n of `i` in the permutation `p`.\n\n The algorithm is of complexity `O(n\\log(n))` where `n` is the size of\n the given permutation.\n\n EXAMPLES::\n\n sage: Permutation([5,9,1,8,2,6,4,7,3]).to_inversion_vector()\n [2, 3, 6, 4, 0, 2, 2, 1, 0]\n sage: Permutation([8,7,2,1,9,4,6,5,10,3]).to_inversion_vector()\n [3, 2, 7, 3, 4, 3, 1, 0, 0, 0]\n sage: Permutation([3,2,4,1,5]).to_inversion_vector()\n [3, 1, 0, 0, 0]\n\n TESTS::\n\n sage: from sage.combinat.permutation import from_inversion_vector\n sage: all(from_inversion_vector(p.to_inversion_vector()) == p\n ....: for n in range(6) for p in Permutations(n))\n True\n\n sage: P = Permutations(1000)\n sage: sample = (P.random_element() for i in range(5))\n sage: all(from_inversion_vector(p.to_inversion_vector()) == p\n ....: for p in sample)\n True\n ' p = self._list l = len(p) if (l < 4): if (l == 0): return [] if (l == 1): return [0] if (l == 2): return [(p[0] - 1), 0] if (l == 3): if (p[0] == 1): return [0, (p[1] - 2), 0] if (p[0] == 2): if (p[1] == 1): return [1, 0, 0] return [2, 0, 0] return [p[1], 1, 0] if (l < 411): return self._to_inversion_vector_small() return self._to_inversion_vector_divide_and_conquer() def _to_inversion_vector_orig(self): '\n Return the inversion vector of ``self``.\n\n The inversion vector of a permutation `p \\in S_n` is defined as\n the vector `(v_1 , v_2 , \\ldots , v_n)`, where `v_i` is the\n number of elements larger than `i` that appear to the left\n of `i` in the permutation `p`.\n\n (This implementation is probably not the most efficient one.)\n\n EXAMPLES::\n\n sage: p = Permutation([5,9,1,8,2,6,4,7,3])\n sage: p._to_inversion_vector_orig()\n [2, 3, 6, 4, 0, 2, 2, 1, 0]\n ' p = self._list iv = ([0] * len(p)) for i in range(len(p)): for pj in p: if (pj > (i + 1)): iv[i] += 1 elif (pj == (i + 1)): break return iv def _to_inversion_vector_small(self): '\n Return the inversion vector of ``self``.\n\n The inversion vector of a permutation `p \\in S_n` is defined as\n the vector `(v_1, v_2, \\ldots, v_n)`, where `v_i` is the\n number of elements larger than `i` that appear to the left\n of `i` in the permutation `p`.\n\n (This implementation is the best choice for ``5 < size < 420``\n approximately.)\n\n EXAMPLES::\n\n sage: p = Permutation([5,9,1,8,2,6,4,7,3])\n sage: p._to_inversion_vector_small()\n [2, 3, 6, 4, 0, 2, 2, 1, 0]\n ' p = self._list l = (len(p) + 1) iv = ([0] * l) checked = ([1] * l) for pi in reversed(p): checked[pi] = 0 iv[pi] = sum(checked[pi:]) return iv[1:] def _to_inversion_vector_divide_and_conquer(self): '\n Return the inversion vector of a permutation ``self``.\n\n The inversion vector of a permutation `p \\in S_n` is defined as\n the vector `(v_1, v_2, \\ldots, v_n)`, where `v_i` is the\n number of elements larger than `i` that appear to the left\n of `i` in the permutation `p`.\n\n (This implementation is the best choice for ``size > 410``\n approximately.)\n\n EXAMPLES::\n\n sage: p = Permutation([5,9,1,8,2,6,4,7,3])\n sage: p._to_inversion_vector_divide_and_conquer()\n [2, 3, 6, 4, 0, 2, 2, 1, 0]\n ' def merge_and_countv(ivA_A, ivB_B): (ivA, A) = ivA_A (ivB, B) = ivB_B C = [] (i, j) = (0, 0) ivC = [] (lA, lB) = (len(A), len(B)) while ((i < lA) and (j < lB)): if (B[j] < A[i]): C.append(B[j]) ivC.append(((ivB[j] + lA) - i)) j += 1 else: C.append(A[i]) ivC.append(ivA[i]) i += 1 if (i < lA): C.extend(A[i:]) ivC.extend(ivA[i:]) else: C.extend(B[j:]) ivC.extend(ivB[j:]) return (ivC, C) def base_case(L): s = sorted(L) d = dict(((j, i) for (i, j) in enumerate(s))) iv = ([0] * len(L)) checked = ([1] * len(L)) for pi in reversed(L): dpi = d[pi] checked[dpi] = 0 iv[dpi] = sum(checked[dpi:]) return (iv, s) def sort_and_countv(L): if (len(L) < 250): return base_case(L) l = (len(L) // 2) return merge_and_countv(sort_and_countv(L[:l]), sort_and_countv(L[l:])) return sort_and_countv(self._list)[0] def inversions(self) -> list: '\n Return a list of the inversions of ``self``.\n\n An inversion of a permutation `p` is a pair `(i, j)` such that\n `i < j` and `p(i) > p(j)`.\n\n EXAMPLES::\n\n sage: Permutation([3,2,4,1,5]).inversions()\n [(1, 2), (1, 4), (2, 4), (3, 4)]\n ' p = self[:] n = len(p) return [tuple([(i + 1), (j + 1)]) for i in range((n - 1)) for j in range((i + 1), n) if (p[i] > p[j])] def stack_sort(self) -> Permutation: '\n Return the stack sort of a permutation.\n\n This is another permutation obtained through the\n process of sorting using one stack. If the result is the identity\n permutation, the original permutation is *stack-sortable*.\n\n See :wikipedia:`Stack-sortable_permutation`\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,5,3,4,9,7,8,6])\n sage: p.stack_sort()\n [1, 2, 3, 4, 5, 7, 6, 8, 9]\n\n sage: S5 = Permutations(5)\n sage: len([1 for s in S5 if s.stack_sort() == S5.one()])\n 42\n\n TESTS::\n\n sage: p = Permutation([])\n sage: p.stack_sort()\n []\n sage: p = Permutation([1])\n sage: p.stack_sort()\n [1]\n ' stack: list[int] = [] sorted_p: list[int] = [] for j in self: if stack: for i in reversed(stack): if (i < j): sorted_p.append(i) stack.pop() else: break stack.append(j) sorted_p.extend(reversed(stack)) return Permutation(sorted_p) def to_digraph(self) -> DiGraph: '\n Return a digraph representation of ``self``.\n\n EXAMPLES::\n\n sage: d = Permutation([3, 1, 2]).to_digraph() # needs sage.graphs\n sage: d.edges(sort=True, labels=False) # needs sage.graphs\n [(1, 3), (2, 1), (3, 2)]\n sage: P = Permutations(range(1, 10))\n sage: d = Permutation(P.random_element()).to_digraph() # needs sage.graphs\n sage: all(c.is_cycle() # needs sage.graphs\n ....: for c in d.strongly_connected_components_subgraphs())\n True\n\n TESTS::\n\n sage: d = Permutation([1]).to_digraph() # needs sage.graphs\n sage: d.edges(sort=True, labels=False) # needs sage.graphs\n [(1, 1)]\n ' return DiGraph([self, enumerate(self, start=1)], format='vertices_and_edges', loops=True) def show(self, representation='cycles', orientation='landscape', **args): '\n Display the permutation as a drawing.\n\n INPUT:\n\n - ``representation`` -- different kinds of drawings are available\n\n - ``"cycles"`` (default) -- the permutation is displayed as a\n collection of directed cycles\n\n - ``"braid"`` -- the permutation is displayed as segments linking\n each element `1, ..., n` to its image on a parallel line.\n\n When using this drawing, it is also possible to display the\n permutation horizontally (``orientation = "landscape"``, default\n option) or vertically (``orientation = "portrait"``).\n\n - ``"chord-diagram"`` -- the permutation is displayed as a directed\n graph, all of its vertices being located on a circle.\n\n All additional arguments are forwarded to the ``show`` subcalls.\n\n EXAMPLES::\n\n sage: P20 = Permutations(20)\n sage: P20.random_element().show(representation="cycles") # needs sage.graphs sage.plot\n sage: P20.random_element().show(representation="chord-diagram") # needs sage.graphs sage.plot\n sage: P20.random_element().show(representation="braid") # needs sage.plot\n sage: P20.random_element().show(representation="braid", # needs sage.plot\n ....: orientation=\'portrait\')\n\n TESTS::\n\n sage: P20.random_element().show(representation="modern_art")\n Traceback (most recent call last):\n ...\n ValueError: The value of \'representation\' must be equal to \'cycles\', \'chord-diagram\' or \'braid\'\n ' if ((representation == 'cycles') or (representation == 'chord-diagram')): d = self.to_digraph() if (representation == 'cycles'): d.show(**args) else: d.show(layout='circular', **args) elif (representation == 'braid'): from sage.plot.line import line from sage.plot.text import text if (orientation == 'landscape'): r = (lambda x, y: (x, y)) elif (orientation == 'portrait'): r = (lambda x, y: ((- y), x)) else: raise ValueError(("The value of 'orientation' must be either " + "'landscape' or 'portrait'.")) p = self[:] L = line([r(1, 1)]) for i in range(len(p)): L += line([r(i, 1.0), r((p[i] - 1), 0)]) L += (text(str(i), r(i, 1.05)) + text(str(i), r((p[i] - 1), (- 0.05)))) return L.show(axes=False, **args) else: raise ValueError(("The value of 'representation' must be equal to " + "'cycles', 'chord-diagram' or 'braid'")) def number_of_inversions(self) -> Integer: '\n Return the number of inversions in ``self``.\n\n An inversion of a permutation is a pair of elements `(i, j)`\n with `i < j` and `p(i) > p(j)`.\n\n REFERENCES:\n\n - http://mathworld.wolfram.com/PermutationInversion.html\n\n EXAMPLES::\n\n sage: Permutation([3, 2, 4, 1, 5]).number_of_inversions()\n 4\n sage: Permutation([1, 2, 6, 4, 7, 3, 5]).number_of_inversions()\n 6\n ' return sum(self.to_inversion_vector()) def noninversions(self, k) -> list: '\n Return the list of all ``k``-noninversions in ``self``.\n\n If `k` is an integer and `p \\in S_n` is a permutation, then\n a `k`-noninversion in `p` is defined as a strictly increasing\n sequence `(i_1, i_2, \\ldots, i_k)` of elements of\n `\\{ 1, 2, \\ldots, n \\}` satisfying\n `p(i_1) < p(i_2) < \\cdots < p(i_k)`. (In other words, a\n `k`-noninversion in `p` can be regarded as a `k`-element\n subset of `\\{ 1, 2, \\ldots, n \\}` on which `p` restricts\n to an increasing map.)\n\n EXAMPLES::\n\n sage: p = Permutation([3, 2, 4, 1, 5])\n sage: p.noninversions(1)\n [[3], [2], [4], [1], [5]]\n sage: p.noninversions(2)\n [[3, 4], [3, 5], [2, 4], [2, 5], [4, 5], [1, 5]]\n sage: p.noninversions(3)\n [[3, 4, 5], [2, 4, 5]]\n sage: p.noninversions(4)\n []\n sage: p.noninversions(5)\n []\n\n TESTS::\n\n sage: q = Permutation([])\n sage: q.noninversions(1)\n []\n ' if (k > len(self)): return [] return [list(pos) for pos in itertools.combinations(self, k) if all(((pos[i] < pos[(i + 1)]) for i in range((k - 1))))] def number_of_noninversions(self, k) -> Integer: '\n Return the number of ``k``-noninversions in ``self``.\n\n If `k` is an integer and `p \\in S_n` is a permutation, then\n a `k`-noninversion in `p` is defined as a strictly increasing\n sequence `(i_1, i_2, \\ldots, i_k)` of elements of\n `\\{ 1, 2, \\ldots, n \\}` satisfying\n `p(i_1) < p(i_2) < \\cdots < p(i_k)`. (In other words, a\n `k`-noninversion in `p` can be regarded as a `k`-element\n subset of `\\{ 1, 2, \\ldots, n \\}` on which `p` restricts\n to an increasing map.)\n\n The number of `k`-noninversions in `p` has been denoted by\n `\\mathrm{noninv}_k(p)` in [RSW2011]_, where conjectures\n and results regarding this number have been stated.\n\n EXAMPLES::\n\n sage: p = Permutation([3, 2, 4, 1, 5])\n sage: p.number_of_noninversions(1)\n 5\n sage: p.number_of_noninversions(2)\n 6\n sage: p.number_of_noninversions(3)\n 2\n sage: p.number_of_noninversions(4)\n 0\n sage: p.number_of_noninversions(5)\n 0\n\n The number of `2`-noninversions of a permutation `p \\in S_n`\n is `\\binom{n}{2}` minus its number of inversions::\n\n sage: b = binomial(5, 2) # needs sage.symbolic\n sage: all( x.number_of_noninversions(2) == b - x.number_of_inversions() # needs sage.symbolic\n ....: for x in Permutations(5) )\n True\n\n We also check some corner cases::\n\n sage: all( x.number_of_noninversions(1) == 5 for x in Permutations(5) )\n True\n sage: all( x.number_of_noninversions(0) == 1 for x in Permutations(5) )\n True\n sage: Permutation([]).number_of_noninversions(1)\n 0\n sage: Permutation([]).number_of_noninversions(0)\n 1\n sage: Permutation([2, 1]).number_of_noninversions(3)\n 0\n ' if (k > len(self)): return 0 return sum((1 for pos in itertools.combinations(self, k) if all(((pos[i] < pos[(i + 1)]) for i in range((k - 1)))))) def length(self) -> Integer: '\n Return the Coxeter length of ``self``.\n\n The length of a permutation `p` is given by the number of inversions\n of `p`.\n\n EXAMPLES::\n\n sage: Permutation([5, 1, 3, 4, 2]).length()\n 6\n ' return self.number_of_inversions() def absolute_length(self) -> Integer: '\n Return the absolute length of ``self``\n\n The absolute length is the length of the shortest expression\n of the element as a product of reflections.\n\n For permutations in the symmetric groups, the absolute\n length is the size minus the number of its disjoint\n cycles.\n\n EXAMPLES::\n\n sage: Permutation([4,2,3,1]).absolute_length() # needs sage.combinat\n 1\n ' return (self.size() - len(self.cycle_type())) @combinatorial_map(order=2, name='inverse') def inverse(self) -> Permutation: '\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([3,8,5,10,9,4,6,1,7,2]).inverse()\n [8, 10, 1, 6, 3, 7, 9, 2, 5, 4]\n sage: Permutation([2, 4, 1, 5, 3]).inverse()\n [3, 1, 5, 2, 4]\n sage: ~Permutation([2, 4, 1, 5, 3])\n [3, 1, 5, 2, 4]\n ' w = list(range(len(self))) for (i, j) in enumerate(self): w[(j - 1)] = (i + 1) return Permutations()(w) __invert__ = inverse def _icondition(self, i): "\n Return a string which shows the relative positions of `i-1,i,i+1` in\n ``self``, along with the actual positions of these three letters in\n ``self``. The string represents the letters `i-1,i,i+1` by `1,2,3`,\n respectively.\n\n .. NOTE::\n\n An imove (that is, an iswitch or an ishift) can only be applied\n when the relative positions of `i-1,i,i+1` are one of '213',\n '132', '231', or '312'. ``None`` is returned in the other cases\n to signal that an imove cannot be applied.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3])._icondition(2)\n ('213', 1, 0, 2)\n sage: Permutation([1,3,2])._icondition(2)\n ('132', 0, 2, 1)\n sage: Permutation([2,3,1])._icondition(2)\n ('231', 2, 0, 1)\n sage: Permutation([3,1,2])._icondition(2)\n ('312', 1, 2, 0)\n sage: Permutation([1,2,3])._icondition(2)\n (None, 0, 1, 2)\n sage: Permutation([1,3,2,4])._icondition(3)\n ('213', 2, 1, 3)\n sage: Permutation([2,1,3])._icondition(3)\n Traceback (most recent call last):\n ...\n ValueError: i (= 3) must be between 2 and n-1\n\n .. SEEALSO::\n\n :meth:`ishift`, :meth:`iswitch`\n " if (i not in range(2, len(self))): raise ValueError(('i (= %s) must be between 2 and n-1' % i)) pos_i = self.index(i) pos_ip1 = self.index((i + 1)) pos_im1 = self.index((i - 1)) if ((pos_i < pos_im1) and (pos_im1 < pos_ip1)): state = '213' elif ((pos_im1 < pos_ip1) and (pos_ip1 < pos_i)): state = '132' elif ((pos_i < pos_ip1) and (pos_ip1 < pos_im1)): state = '231' elif ((pos_ip1 < pos_im1) and (pos_im1 < pos_i)): state = '312' else: state = None return (state, pos_im1, pos_i, pos_ip1) def ishift(self, i): "\n Return the ``i``-shift of ``self``. If an ``i``-shift of ``self``\n can't be performed, then ``self`` is returned.\n\n An `i`-shift can be applied when `i` is not inbetween `i-1` and\n `i+1`. The `i`-shift moves `i` to the other side, and leaves the\n relative positions of `i-1` and `i+1` in place. All other entries\n of the permutations are also left in place.\n\n EXAMPLES:\n\n Here, `2` is to the left of both `1` and `3`. A `2`-shift\n can be applied which moves the `2` to the right and leaves `1` and\n `3` in their same relative order::\n\n sage: Permutation([2,1,3]).ishift(2)\n [1, 3, 2]\n\n All entries other than `i`, `i-1` and `i+1` are unchanged::\n\n sage: Permutation([2,4,1,3]).ishift(2)\n [1, 4, 3, 2]\n\n Since `2` is between `1` and `3` in ``[1,2,3]``, a `2`-shift cannot\n be applied to ``[1,2,3]`` ::\n\n sage: Permutation([1,2,3]).ishift(2)\n [1, 2, 3]\n " state = self._icondition(i) if (state[0] is None): return self (state, pos_im1, pos_i, pos_ip1) = state l = list(self) if (state == '213'): l[pos_i] = (i - 1) l[pos_im1] = (i + 1) l[pos_ip1] = i elif (state == '132'): l[pos_im1] = i l[pos_ip1] = (i - 1) l[pos_i] = (i + 1) elif (state == '231'): l[pos_i] = (i + 1) l[pos_ip1] = (i - 1) l[pos_im1] = i elif (state == '312'): l[pos_ip1] = i l[pos_im1] = (i + 1) l[pos_i] = (i - 1) else: raise ValueError('invalid state') return Permutations()(l) def iswitch(self, i): "\n Return the ``i``-switch of ``self``. If an ``i``-switch of ``self``\n can't be performed, then ``self`` is returned.\n\n An `i`-switch can be applied when the subsequence of ``self`` formed\n by the entries `i-1`, `i` and `i+1` is neither increasing nor\n decreasing. In this case, this subsequence is reversed (i. e., its\n leftmost element and its rightmost element switch places), while all\n other letters of ``self`` are kept in place.\n\n EXAMPLES:\n\n Here, `2` is to the left of both `1` and `3`. A `2`-switch can be\n applied which moves the `2` to the right and switches the relative\n order between `1` and `3`::\n\n sage: Permutation([2,1,3]).iswitch(2)\n [3, 1, 2]\n\n All entries other than `i-1`, `i` and `i+1` are unchanged::\n\n sage: Permutation([2,4,1,3]).iswitch(2)\n [3, 4, 1, 2]\n\n Since `2` is between `1` and `3` in ``[1,2,3]``, a `2`-switch\n cannot be applied to ``[1,2,3]`` ::\n\n sage: Permutation([1,2,3]).iswitch(2)\n [1, 2, 3]\n " if (i not in range(2, len(self))): raise ValueError(('i (= %s) must between 2 and n-1' % i)) state = self._icondition(i) if (state[0] is None): return self (state, pos_im1, pos_i, pos_ip1) = state l = list(self) if (state == '213'): l[pos_i] = (i + 1) l[pos_ip1] = i elif (state == '132'): l[pos_im1] = i l[pos_i] = (i - 1) elif (state == '231'): l[pos_i] = (i - 1) l[pos_im1] = i elif (state == '312'): l[pos_ip1] = i l[pos_i] = (i + 1) else: raise ValueError('invalid state') return Permutations()(l) def runs(self, as_tuple=False): '\n Return a list of the runs in the nonempty permutation\n ``self``.\n\n A run in a permutation is defined to be a maximal (with\n respect to inclusion) nonempty increasing substring (i. e.,\n contiguous subsequence). For instance, the runs in the\n permutation ``[6,1,7,3,4,5,2]`` are ``[6]``, ``[1,7]``,\n ``[3,4,5]`` and ``[2]``.\n\n Runs in an empty permutation are not defined.\n\n INPUT:\n\n - ``as_tuple`` -- boolean (default: ``False``) choice of\n output format\n\n OUTPUT:\n\n a list of lists or a tuple of tuples\n\n REFERENCES:\n\n - http://mathworld.wolfram.com/PermutationRun.html\n\n EXAMPLES::\n\n sage: Permutation([1,2,3,4]).runs()\n [[1, 2, 3, 4]]\n sage: Permutation([4,3,2,1]).runs()\n [[4], [3], [2], [1]]\n sage: Permutation([2,4,1,3]).runs()\n [[2, 4], [1, 3]]\n sage: Permutation([1]).runs()\n [[1]]\n\n The example from above::\n\n sage: Permutation([6,1,7,3,4,5,2]).runs()\n [[6], [1, 7], [3, 4, 5], [2]]\n sage: Permutation([6,1,7,3,4,5,2]).runs(as_tuple=True)\n ((6,), (1, 7), (3, 4, 5), (2,))\n\n The number of runs in a nonempty permutation equals its\n number of descents plus 1::\n\n sage: all( len(p.runs()) == p.number_of_descents() + 1\n ....: for p in Permutations(6) )\n True\n ' p = self[:] runs = [] current_value = p[0] current_run = [p[0]] for i in p[1:]: if (i < current_value): runs.append(current_run) current_run = [i] else: current_run.append(i) current_value = i runs.append(current_run) if as_tuple: return tuple((tuple(r) for r in runs)) return runs def decreasing_runs(self, as_tuple=False): '\n Decreasing runs of the permutation.\n\n INPUT:\n\n - ``as_tuple`` -- boolean (default: ``False``) choice of output\n format\n\n OUTPUT:\n\n a list of lists or a tuple of tuples\n\n .. SEEALSO::\n\n :meth:`runs`\n\n EXAMPLES::\n\n sage: s = Permutation([2,8,3,9,6,4,5,1,7])\n sage: s.decreasing_runs()\n [[2], [8, 3], [9, 6, 4], [5, 1], [7]]\n sage: s.decreasing_runs(as_tuple=True)\n ((2,), (8, 3), (9, 6, 4), (5, 1), (7,))\n ' n = len(self) s_bar = self.complement() if as_tuple: return tuple((tuple((((n + 1) - i) for i in r)) for r in s_bar.runs())) return [[((n + 1) - i) for i in r] for r in s_bar.runs()] def longest_increasing_subsequence_length(self) -> Integer: '\n Return the length of the longest increasing subsequences of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([2,3,1,4]).longest_increasing_subsequence_length()\n 3\n sage: all(i.longest_increasing_subsequence_length() == len(RSK(i)[0][0]) # needs sage.combinat\n ....: for i in Permutations(5))\n True\n sage: Permutation([]).longest_increasing_subsequence_length()\n 0\n ' from bisect import bisect r: list[int] = [] for x in self._list: idx = bisect(r, x) if (idx == len(r)): r.append(x) else: r[idx] = x return len(r) def longest_increasing_subsequences(self): '\n Return the list of the longest increasing subsequences of ``self``.\n\n A theorem of Schensted ([Sch1961]_) states that an increasing\n subsequence of length `i` ends with the value entered in the `i`-th\n column of the p-tableau. The algorithm records which column of the\n p-tableau each value of the permutation is entered into, creates a\n digraph to record all increasing subsequences, and reads the paths\n from a source to a sink; these are the longest increasing subsequences.\n\n EXAMPLES::\n\n sage: Permutation([2,3,4,1]).longest_increasing_subsequences() # needs sage.graphs\n [[2, 3, 4]]\n sage: Permutation([5, 7, 1, 2, 6, 4, 3]).longest_increasing_subsequences() # needs sage.graphs\n [[1, 2, 6], [1, 2, 4], [1, 2, 3]]\n\n .. NOTE::\n\n This algorithm could be made faster using a balanced search tree\n for each column instead of sorted lists. See discussion on\n :trac:`31451`.\n ' n = self.size() if (n == 0): return [[]] from bisect import insort, bisect first_row_p_tableau = [] columns = [] D = DiGraph((n + 2)) for x in self._list: j = bisect(first_row_p_tableau, x) if (j == len(first_row_p_tableau)): if columns: for k in columns[(- 1)]: if (k >= x): break D.add_edge(k, x) first_row_p_tableau.append(x) columns.append([x]) else: first_row_p_tableau[j] = x insort(columns[j], x) if j: for k in columns[(j - 1)]: if (k > x): break D.add_edge(k, x) for i in columns[0]: D.add_edge(0, i) for i in columns[(- 1)]: D.add_edge(i, (n + 1)) return sorted([p[1:(- 1)] for p in D.all_paths(0, (n + 1))], reverse=True) def longest_increasing_subsequences_number(self): '\n Return the number of increasing subsequences of maximal length\n in ``self``.\n\n The list of longest increasing subsequences of a permutation is\n given by :meth:`longest_increasing_subsequences`, and the\n length of these subsequences is given by\n :meth:`longest_increasing_subsequence_length`.\n\n The algorithm is similar to :meth:`longest_increasing_subsequences`.\n Namely, the longest increasing subsequences are encoded as increasing\n sequences in a ranked poset from a smallest to a largest element. Their\n number can be obtained via dynamic programming: for each `v` in the poset\n we compute the number of paths from a smallest element to `v`.\n\n EXAMPLES::\n\n sage: sum(p.longest_increasing_subsequences_number()\n ....: for p in Permutations(8))\n 120770\n\n sage: p = Permutations(50).random_element()\n sage: (len(p.longest_increasing_subsequences()) == # needs sage.graphs\n ....: p.longest_increasing_subsequences_number())\n True\n ' n = self.size() if (n == 0): return 1 from bisect import insort, bisect count: list[int] = ([0] * (n + 1)) first_row_p_tableau = [] columns = [] for x in self._list: j = bisect(first_row_p_tableau, x) if (j == len(first_row_p_tableau)): first_row_p_tableau.append(x) columns.append([x]) else: first_row_p_tableau[j] = x insort(columns[j], x) if (j == 0): count[x] = 1 else: for k in columns[(j - 1)]: if (k > x): break count[x] += count[k] return sum((count[x] for x in columns[(- 1)])) def cycle_type(self): '\n Return a partition of ``len(self)`` corresponding to the cycle\n type of ``self``.\n\n This is a non-increasing sequence of the cycle lengths of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([3,1,2,4]).cycle_type() # needs sage.combinat\n [3, 1]\n ' cycle_type = [len(c) for c in self.to_cycles()] cycle_type.sort(reverse=True) from sage.combinat.partition import Partition return Partition(cycle_type) @combinatorial_map(name='forget cycles') def forget_cycles(self): '\n Return the image of ``self`` under the map which forgets cycles.\n\n Consider a permutation `\\sigma` written in standard cyclic form:\n\n .. MATH::\n\n \\sigma\n = (a_{1,1}, \\ldots, a_{1,k_1})\n (a_{2,1}, \\ldots, a_{2,k_2})\n \\cdots\n (a_{m,1}, \\ldots, a_{m,k_m}),\n\n where `a_{1,1} < a_{2,1} < \\cdots < a_{m,1}` and `a_{j,1} < a_{j,i}`\n for all `1 \\leq j \\leq m` and `2 \\leq i \\leq k_j` where we include\n cycles of length 1 as well. The image of the forget cycle map `\\phi`\n is given by\n\n .. MATH::\n\n \\phi(\\sigma) = [a_{1,1}, \\ldots, a_{1,k_1}, a_{2,1}, \\ldots,\n a_{2,k_2}, \\ldots, a_{m,1}, \\ldots, a_{m,k_m}],\n\n considered as a permutation in 1-line notation.\n\n .. SEEALSO::\n\n :meth:`fundamental_transformation`, which is a similar map that\n is defined by instead taking `a_{j,1} > a_{j,i}` and is\n bijective.\n\n EXAMPLES::\n\n sage: P = Permutations(5)\n sage: x = P([1, 5, 3, 4, 2])\n sage: x.forget_cycles()\n [1, 2, 5, 3, 4]\n\n We select all permutations with a cycle composition of `[2, 3, 1]`\n in `S_6`::\n\n sage: P = Permutations(6)\n sage: l = [p for p in P if [len(t) for t in p.to_cycles()] == [1,3,2]]\n\n Next we apply `\\phi` and then take the inverse, and then view the\n results as a poset under the Bruhat order::\n\n sage: l = [p.forget_cycles().inverse() for p in l]\n sage: B = Poset([l, lambda x,y: x.bruhat_lequal(y)]) # needs sage.combinat sage.graphs\n sage: R.<q> = QQ[]\n sage: sum(q^B.rank_function()(x) for x in B) # needs sage.combinat sage.graphs\n q^5 + 2*q^4 + 3*q^3 + 3*q^2 + 2*q + 1\n\n We check the statement in [CC2013]_ that the posets\n `C_{[1,3,1,1]}` and `C_{[1,3,2]}` are isomorphic::\n\n sage: l2 = [p for p in P if [len(t) for t in p.to_cycles()] == [1,3,1,1]]\n sage: l2 = [p.forget_cycles().inverse() for p in l2]\n sage: B2 = Poset([l2, lambda x,y: x.bruhat_lequal(y)]) # needs sage.combinat sage.graphs\n sage: B.is_isomorphic(B2) # needs sage.combinat sage.graphs\n True\n\n .. SEEALSO::\n\n :meth:`fundamental_transformation`.\n ' ret = [] for t in self.to_cycles(): ret += list(t) return Permutations()(ret) @combinatorial_map(name='foata_bijection') def foata_bijection(self) -> Permutation: '\n Return the image of the permutation ``self`` under the Foata\n bijection `\\phi`.\n\n The bijection shows that `\\mathrm{maj}` (the major index)\n and `\\mathrm{inv}` (the number of inversions) are\n equidistributed: if `\\phi(P) = Q`, then `\\mathrm{maj}(P) =\n \\mathrm{inv}(Q)`.\n\n The Foata bijection `\\phi` is a bijection on the set of words with\n no two equal letters. It can be defined by induction on the size\n of the word: Given a word `w_1 w_2 \\cdots w_n`, start with\n `\\phi(w_1) = w_1`. At the `i`-th step, if\n `\\phi(w_1 w_2 \\cdots w_i) = v_1 v_2 \\cdots v_i`, we define\n `\\phi(w_1 w_2 \\cdots w_i w_{i+1})` by placing `w_{i+1}` on the end of\n the word `v_1 v_2 \\cdots v_i` and breaking the word up into blocks\n as follows. If `w_{i+1} > v_i`, place a vertical line to the right\n of each `v_k` for which `w_{i+1} > v_k`. Otherwise, if\n `w_{i+1} < v_i`, place a vertical line to the right of each `v_k`\n for which `w_{i+1} < v_k`. In either case, place a vertical line at\n the start of the word as well. Now, within each block between\n vertical lines, cyclically shift the entries one place to the\n right.\n\n For instance, to compute `\\phi([1,4,2,5,3])`, the sequence of\n words is\n\n * `1`,\n * `|1|4 \\to 14`,\n * `|14|2 \\to 412`,\n * `|4|1|2|5 \\to 4125`,\n * `|4|125|3 \\to 45123`.\n\n So `\\phi([1,4,2,5,3]) = [4,5,1,2,3]`.\n\n See section 2 of [FS1978]_, and the proof of Proposition 1.4.6\n in [EnumComb1]_.\n\n .. SEEALSO::\n\n :meth:`foata_bijection_inverse` for the inverse map.\n\n EXAMPLES::\n\n sage: Permutation([1,2,4,3]).foata_bijection()\n [4, 1, 2, 3]\n sage: Permutation([2,5,1,3,4]).foata_bijection()\n [2, 1, 3, 5, 4]\n\n sage: P = Permutation([2,5,1,3,4])\n sage: P.major_index() == P.foata_bijection().number_of_inversions()\n True\n\n sage: all( P.major_index() == P.foata_bijection().number_of_inversions()\n ....: for P in Permutations(4) )\n True\n\n The example from [FS1978]_::\n\n sage: Permutation([7,4,9,2,6,1,5,8,3]).foata_bijection()\n [4, 7, 2, 6, 1, 9, 5, 8, 3]\n\n Border cases::\n\n sage: Permutation([]).foata_bijection()\n []\n sage: Permutation([1]).foata_bijection()\n [1]\n ' M: list[int] = [] for e in self: k = len(M) if (k <= 1): M.append(e) continue a = M[(- 1)] M_prime = ([0] * (k + 1)) if (a > e): index_list = ([(- 1)] + [i for (i, val) in enumerate(M) if (val > e)]) else: index_list = ([(- 1)] + [i for (i, val) in enumerate(M) if (val < e)]) for j in range(1, len(index_list)): start = (index_list[(j - 1)] + 1) end = index_list[j] M_prime[start] = M[end] for x in range((start + 1), (end + 1)): M_prime[x] = M[(x - 1)] M_prime[k] = e M = M_prime return Permutations()(M) @combinatorial_map(name='foata_bijection_inverse') def foata_bijection_inverse(self) -> Permutation: '\n Return the image of the permutation ``self`` under the inverse\n of the Foata bijection `\\phi`.\n\n See :meth:`foata_bijection` for the definition of the Foata\n bijection.\n\n EXAMPLES::\n\n sage: Permutation([4, 1, 2, 3]).foata_bijection()\n [1, 2, 4, 3]\n\n TESTS::\n\n sage: all( P.foata_bijection().foata_bijection_inverse() == P\n ....: for P in Permutations(5) )\n True\n\n Border cases::\n\n sage: Permutation([]).foata_bijection_inverse()\n []\n sage: Permutation([1]).foata_bijection_inverse()\n [1]\n ' L = list(self) Mrev = [] while L: e = L.pop() Mrev.append(e) k = len(L) if (k <= 1): continue L_prime = ([0] * k) a = L[0] if (a > e): index_list = [i for (i, val) in enumerate(L) if (val > e)] else: index_list = [i for (i, val) in enumerate(L) if (val < e)] index_list.append(k) for j in range(1, len(index_list)): start = index_list[(j - 1)] end = (index_list[j] - 1) L_prime[end] = L[start] for x in range(start, end): L_prime[x] = L[(x + 1)] L = L_prime return Permutations()(reversed(Mrev)) @combinatorial_map(name='fundamental_transformation') def fundamental_transformation(self) -> Permutation: '\n Return the image of the permutation ``self`` under the\n Renyi-Foata-Schuetzenberger fundamental transformation.\n\n The fundamental transformation is a bijection from the\n set of all permutations of `\\{1, 2, \\ldots, n\\}` to\n itself, which transforms any such permutation `w`\n as follows:\n Write `w` in cycle form, with each cycle starting with\n its highest element, and the cycles being sorted in\n increasing order of their highest elements.\n Drop the parentheses in the resulting expression, thus\n reading it as a one-line notation of a new permutation\n `u`.\n Then, `u` is the image of `w` under the fundamental\n transformation.\n\n See [EnumComb1]_, Proposition 1.3.1.\n\n .. SEEALSO::\n\n :meth:`fundamental_transformation_inverse`\n for the inverse map.\n\n :meth:`forget_cycles` for a similar (but non-bijective)\n map where each cycle is starting from its lowest element.\n\n EXAMPLES::\n\n sage: Permutation([5, 1, 3, 4, 2]).fundamental_transformation()\n [3, 4, 5, 2, 1]\n sage: Permutations(5)([1, 5, 3, 4, 2]).fundamental_transformation()\n [1, 3, 4, 5, 2]\n sage: Permutation([8, 4, 7, 2, 9, 6, 5, 1, 3]).fundamental_transformation()\n [4, 2, 6, 8, 1, 9, 3, 7, 5]\n\n Comparison with :meth:`forget_cycles`::\n\n sage: P = Permutation([(1,3,4),(2,5)])\n sage: P\n [3, 5, 4, 1, 2]\n sage: P.forget_cycles()\n [1, 3, 4, 2, 5]\n sage: P.fundamental_transformation()\n [4, 1, 3, 5, 2]\n\n TESTS:\n\n Border cases::\n\n sage: Permutation([]).fundamental_transformation()\n []\n sage: Permutation([1]).fundamental_transformation()\n [1]\n ' cycles = self.to_cycles(use_min=False) return Permutations()([a for c in reversed(cycles) for a in c]) @combinatorial_map(name='fundamental_transformation_inverse') def fundamental_transformation_inverse(self): '\n Return the image of the permutation ``self`` under the\n inverse of the Renyi-Foata-Schuetzenberger fundamental\n transformation.\n\n The inverse of the fundamental transformation is a\n bijection from the set of all permutations of\n `\\{1, 2, \\ldots, n\\}` to itself, which transforms any\n such permutation `w` as follows:\n Let `I = \\{ i_1 < i_2 < \\cdots < i_k \\}` be the set of\n all left-to-right maxima of `w` (that is, of all indices\n `j` such that `w(j)` is bigger than each of\n `w(1), w(2), \\ldots, w(j-1)`).\n The image of `w` under the inverse of the fundamental\n transformation is the permutation `u` that sends\n `w(i-1)` to `w(i)` for all `i \\notin I` (notice that\n this makes sense, since `1 \\in I` whenever `n > 0`),\n while sending each `w(i_p - 1)` (with `p \\geq 2`)\n to `w(i_{p-1})`. Here, we set `i_{k+1} = n+1`.\n\n See [EnumComb1]_, Proposition 1.3.1.\n\n .. SEEALSO::\n\n :meth:`fundamental_transformation`\n for the inverse map.\n\n EXAMPLES::\n\n sage: Permutation([3, 4, 5, 2, 1]).fundamental_transformation_inverse()\n [5, 1, 3, 4, 2]\n sage: Permutation([4, 2, 6, 8, 1, 9, 3, 7, 5]).fundamental_transformation_inverse()\n [8, 4, 7, 2, 9, 6, 5, 1, 3]\n\n TESTS::\n\n sage: all(P.fundamental_transformation_inverse().\n ....: fundamental_transformation() == P\n ....: for P in Permutations(4))\n True\n\n sage: all(P.fundamental_transformation().\n ....: fundamental_transformation_inverse() == P\n ....: for P in Permutations(3))\n True\n\n Border cases::\n\n sage: Permutation([]).fundamental_transformation_inverse()\n []\n sage: Permutation([1]).fundamental_transformation_inverse()\n [1]\n ' n = len(self) record_value = 0 previous_record = None previous_entry = None res = ([0] * (n + 1)) for entry in self: if (entry > record_value): record_value = entry if (previous_record is not None): res[previous_entry] = previous_record previous_record = entry else: res[previous_entry] = entry previous_entry = entry if (n > 0): res[previous_entry] = previous_record return Permutations()(res[1:]) def destandardize(self, weight, ordered_alphabet=None): "\n Return destandardization of ``self`` with respect to ``weight`` and ``ordered_alphabet``.\n\n INPUT:\n\n - ``weight`` -- list or tuple of nonnegative integers that sum to `n` if ``self``\n is a permutation in `S_n`.\n\n - ``ordered_alphabet`` -- (default: ``None``) a list or tuple specifying the ordered alphabet the\n destandardized word is over\n\n OUTPUT: word over the ``ordered_alphabet`` which standardizes to ``self``\n\n Let `weight = (w_1,w_2,\\ldots,w_\\ell)`. Then this methods looks for an increasing\n sequence of `1,2,\\ldots, w_1` and labels all letters in it by 1, then an increasing\n sequence of `w_1+1,w_1+2,\\ldots,w_1+w_2` and labels all these letters by 2, etc..\n If an increasing sequence for the specified ``weight`` does not exist, an error is\n returned. The output is a word ``w`` over the specified ordered alphabet with\n evaluation ``weight`` such that ``w.standard_permutation()`` is ``self``.\n\n EXAMPLES::\n\n sage: p = Permutation([1,2,5,3,6,4])\n sage: p.destandardize([3,1,2]) # needs sage.combinat\n word: 113132\n sage: p = Permutation([2,1,3])\n sage: p.destandardize([2,1])\n Traceback (most recent call last):\n ...\n ValueError: Standardization with weight [2, 1] is not possible!\n\n TESTS::\n\n sage: p = Permutation([4,1,2,3,5,6])\n sage: p.destandardize([2,1,3], ordered_alphabet = [1,'a',3]) # needs sage.combinat\n word: 311a33\n sage: p.destandardize([2,1,3], ordered_alphabet = [1,'a'])\n Traceback (most recent call last):\n ...\n ValueError: Not enough letters in the alphabet are specified compared to the weight\n " ides = self.idescents() partial = [0] for a in weight: partial.append((partial[(- 1)] + a)) if (not set(ides).issubset(set(partial))): raise ValueError('Standardization with weight {} is not possible!'.format(weight)) if (ordered_alphabet is None): ordered_alphabet = list(range(1, (len(weight) + 1))) elif (len(weight) > len(ordered_alphabet)): raise ValueError('Not enough letters in the alphabet are specified compared to the weight') q = self.inverse() s = ([0] * len(self)) for i in range((len(partial) - 1)): for j in range(partial[i], partial[(i + 1)]): s[(q[j] - 1)] = ordered_alphabet[i] from sage.combinat.words.word import Word return Word(s) def to_lehmer_code(self) -> list: '\n Return the Lehmer code of the permutation ``self``.\n\n The Lehmer code of a permutation `p` is defined as the\n list `[c[1],c[2],...,c[n]]`, where `c[i]` is the number of\n `j>i` such that `p(j)<p(i)`.\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: p.to_lehmer_code()\n [1, 0, 0]\n sage: q = Permutation([3,1,2])\n sage: q.to_lehmer_code()\n [2, 0, 0]\n\n sage: Permutation([1]).to_lehmer_code()\n [0]\n sage: Permutation([]).to_lehmer_code()\n []\n\n TESTS::\n\n sage: from sage.combinat.permutation import from_lehmer_code\n sage: all(from_lehmer_code(p.to_lehmer_code()) == p\n ....: for n in range(6) for p in Permutations(n))\n True\n\n sage: P = Permutations(1000)\n sage: sample = (P.random_element() for i in range(5))\n sage: all(from_lehmer_code(p.to_lehmer_code()) == p\n ....: for p in sample)\n True\n\n ' l = len(self._list) if (l < 577): return self._to_lehmer_code_small() else: return self.inverse().to_inversion_vector() def _to_lehmer_code_small(self) -> list: '\n Return the Lehmer code of the permutation ``self``.\n\n The Lehmer code of a permutation `p` is defined as the\n list `(c_1, c_2, \\ldots, c_n)`, where `c_i` is the number\n of `j > i` such that `p(j) < p(i)`.\n\n (best choice for `size<577` approximately)\n\n EXAMPLES::\n\n sage: p = Permutation([7, 6, 10, 2, 3, 4, 8, 1, 9, 5])\n sage: p._to_lehmer_code_small()\n [6, 5, 7, 1, 1, 1, 2, 0, 1, 0]\n ' p = self._list l = len(p) lehmer = [] checked = ([1] * l) for pi in p: checked[(pi - 1)] = 0 lehmer.append(sum(checked[:pi])) return lehmer def to_lehmer_cocode(self) -> list: '\n Return the Lehmer cocode of the permutation ``self``.\n\n The Lehmer cocode of a permutation `p` is defined as the\n list `(c_1, c_2, \\ldots, c_n)`, where `c_i` is the number\n of `j < i` such that `p(j) > p(i)`.\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: p.to_lehmer_cocode()\n [0, 1, 0]\n sage: q = Permutation([3,1,2])\n sage: q.to_lehmer_cocode()\n [0, 1, 1]\n ' p = self[:] n = len(p) cocode = ([0] * n) for i in range(1, n): for j in range(i): if (p[j] > p[i]): cocode[i] += 1 return cocode def reduced_word(self): '\n Return a reduced word of the permutation ``self``.\n\n See :meth:`reduced_words` for the definition of reduced words and\n a way to compute them all.\n\n .. WARNING::\n\n This does not respect the multiplication convention.\n\n EXAMPLES::\n\n sage: Permutation([3,5,4,6,2,1]).reduced_word()\n [2, 1, 4, 3, 2, 4, 3, 5, 4, 5]\n\n Permutation([1]).reduced_word_lexmin()\n []\n Permutation([]).reduced_word_lexmin()\n []\n ' code = self.to_lehmer_code() return [((i + ci) - j) for (i, ci) in enumerate(code) for j in range(ci)] def reduced_words_iterator(self): '\n Return an iterator for the reduced words of ``self``.\n\n EXAMPLES::\n\n sage: next(Permutation([5,2,3,4,1]).reduced_words_iterator())\n [1, 2, 3, 4, 3, 2, 1]\n\n ' def aux(p): is_identity = True for d in range((len(p) - 1)): e = (d + 1) if (p[d] > p[e]): is_identity = False (p[d], p[e]) = (p[e], p[d]) for x in aux(p): x.append(e) (yield x) (p[d], p[e]) = (p[e], p[d]) if is_identity: (yield []) return aux(self[:]) def reduced_words(self): '\n Return a list of the reduced words of ``self``.\n\n The notion of a reduced word is based on the well-known fact\n that every permutation can be written as a product of adjacent\n transpositions. In more detail: If `n` is a nonnegative integer,\n we can define the transpositions `s_i = (i, i+1) \\in S_n`\n for all `i \\in \\{ 1, 2, \\ldots, n-1 \\}`, and every `p \\in S_n`\n can then be written as a product `s_{i_1} s_{i_2} \\cdots s_{i_k}`\n for some sequence `(i_1, i_2, \\ldots, i_k)` of elements of\n `\\{ 1, 2, \\ldots, n-1 \\}` (here `\\{ 1, 2, \\ldots, n-1 \\}` denotes\n the empty set when `n \\leq 1`). Fixing a `p`, the sequences\n `(i_1, i_2, \\ldots, i_k)` of smallest length satisfying\n `p = s_{i_1} s_{i_2} \\cdots s_{i_k}` are called the reduced words\n of `p`. (Their length is the Coxeter length of `p`, and can be\n computed using :meth:`length`.)\n\n Note that the product of permutations is defined here in such\n a way that `(pq)(i) = p(q(i))` for all permutations `p` and `q`\n and each `i \\in \\{ 1, 2, \\ldots, n \\}` (this is the same\n convention as in :meth:`left_action_product`, but not the\n default semantics of the `*` operator on permutations in Sage).\n Thus, for instance, `s_2 s_1` is the permutation obtained by\n first transposing `1` with `2` and then transposing `2` with `3`.\n\n .. SEEALSO::\n\n :meth:`reduced_word`, :meth:`reduced_word_lexmin`\n\n EXAMPLES::\n\n sage: Permutation([2,1,3]).reduced_words()\n [[1]]\n sage: Permutation([3,1,2]).reduced_words()\n [[2, 1]]\n sage: Permutation([3,2,1]).reduced_words()\n [[1, 2, 1], [2, 1, 2]]\n sage: Permutation([3,2,4,1]).reduced_words()\n [[1, 2, 3, 1], [1, 2, 1, 3], [2, 1, 2, 3]]\n\n Permutation([1]).reduced_words()\n [[]]\n Permutation([]).reduced_words()\n [[]]\n ' return list(self.reduced_words_iterator()) def reduced_word_lexmin(self): '\n Return a lexicographically minimal reduced word of the permutation\n ``self``.\n\n See :meth:`reduced_words` for the definition of reduced words and\n a way to compute them all.\n\n EXAMPLES::\n\n sage: Permutation([3,4,2,1]).reduced_word_lexmin()\n [1, 2, 1, 3, 2]\n\n Permutation([1]).reduced_word_lexmin()\n []\n Permutation([]).reduced_word_lexmin()\n []\n ' cocode = self.inverse().to_lehmer_cocode() rw = [] for i in range(len(cocode)): piece = [(j + 1) for j in range((i - cocode[i]), i)] piece.reverse() rw += piece return rw def rothe_diagram(self): '\n Return the Rothe diagram of ``self``.\n\n EXAMPLES::\n\n sage: p = Permutation([4,2,1,3])\n sage: D = p.rothe_diagram(); D # needs sage.combinat\n [(0, 0), (0, 1), (0, 2), (1, 0)]\n sage: D.pp() # needs sage.combinat\n O O O .\n O . . .\n . . . .\n . . . .\n ' from sage.combinat.diagram import RotheDiagram return RotheDiagram(self) def number_of_reduced_words(self): '\n Return the number of reduced words of ``self`` without explicitly\n computing them all.\n\n EXAMPLES::\n\n sage: p = Permutation([6,4,2,5,1,8,3,7])\n sage: len(p.reduced_words()) == p.number_of_reduced_words() # needs sage.combinat\n True\n ' Tx = self.rothe_diagram().peelable_tableaux() return sum(map(_tableau_contribution, Tx)) def fixed_points(self) -> list: '\n Return a list of the fixed points of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4]).fixed_points()\n [1, 4]\n sage: Permutation([1,2,3,4]).fixed_points()\n [1, 2, 3, 4]\n ' return [i for (i, v) in enumerate(self, start=1) if (i == v)] def number_of_fixed_points(self) -> Integer: '\n Return the number of fixed points of ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4]).number_of_fixed_points()\n 2\n sage: Permutation([1,2,3,4]).number_of_fixed_points()\n 4\n ' return len(self.fixed_points()) def is_derangement(self) -> bool: '\n Return whether ``self`` is a derangement.\n\n A permutation `\\sigma` is a derangement if `\\sigma` has no\n fixed points.\n\n EXAMPLES::\n\n sage: P = Permutation([1,4,2,3])\n sage: P.is_derangement()\n False\n sage: P = Permutation([2,3,1])\n sage: P.is_derangement()\n True\n ' return (not self.fixed_points()) def is_simple(self) -> bool: '\n Return whether ``self`` is simple.\n\n A permutation is simple if it does not send any proper sub-interval\n to a sub-interval.\n\n For instance, ``[6,1,3,5,2,4]`` is not simple because it maps the\n interval ``[3,4,5,6]`` to ``[2,3,4,5]``, whereas ``[2,6,3,5,1,4]`` is\n simple.\n\n See :oeis:`A111111`\n\n EXAMPLES::\n\n sage: g = Permutation([4,2,3,1])\n sage: g.is_simple()\n False\n\n sage: g = Permutation([6,1,3,5,2,4])\n sage: g.is_simple()\n False\n\n sage: g = Permutation([2,6,3,5,1,4])\n sage: g.is_simple()\n True\n\n sage: [len([pi for pi in Permutations(n) if pi.is_simple()])\n ....: for n in range(6)]\n [1, 1, 2, 0, 2, 6]\n ' n = len(self) if (n <= 2): return True left = right = self._list[0] end = 1 while (end < (n - 1)): elt = self._list[end] if (elt < left): left = elt elif (elt > right): right = elt if ((right - left) == end): return False elif ((right - left) == (n - 1)): break end += 1 for start in range(1, (n - 1)): left = right = self._list[start] end = (start + 1) while (end < n): elt = self._list[end] if (elt < left): left = elt elif (elt > right): right = elt if ((right - left) == (end - start)): return False elif ((right - left) > ((n - 1) - start)): break end += 1 return True def recoils(self) -> list: '\n Return the list of the positions of the recoils of ``self``.\n\n A recoil of a permutation `p` is an integer `i` such that `i+1`\n appears to the left of `i` in `p`.\n Here, the positions are being counted starting at `0`.\n (Note that it is the positions, not the recoils themselves, which\n are being listed.)\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).recoils()\n [2, 3]\n sage: Permutation([]).recoils()\n []\n ' p = self recoils = [] for i in range(len(p)): if ((p[i] != len(self)) and (self.index((p[i] + 1)) < i)): recoils.append(i) return recoils def number_of_recoils(self) -> Integer: '\n Return the number of recoils of the permutation ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).number_of_recoils()\n 2\n ' return len(self.recoils()) def recoils_composition(self) -> Composition: '\n Return the recoils composition of ``self``.\n\n The recoils composition of a permutation `p \\in S_n` is the\n composition of `n` whose descent set is the set of the recoils\n of `p` (not their positions). In other words, this is the\n descents composition of `p^{-1}`.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4]).recoils_composition()\n [2, 2]\n sage: Permutation([]).recoils_composition()\n []\n ' return self.inverse().descents_composition() def descents(self, final_descent=False, side='right', positive=False, from_zero=False, index_set=None): "\n Return the list of the descents of ``self``.\n\n A descent of a permutation `p` is an integer `i` such that\n `p(i) > p(i+1)`.\n\n .. WARNING::\n\n By default, the descents are returned as elements in the\n index set, i.e., starting at `1`. If you want them to\n start at `0`, set the keyword ``from_zero`` to ``True``.\n\n INPUT:\n\n - ``final_descent`` -- boolean (default ``False``);\n if ``True``, the last position of a non-empty\n permutation is also considered as a descent\n\n - ``side`` -- ``'right'`` (default) or ``'left'``;\n if ``'left'``, return the descents of the inverse permutation\n\n - ``positive`` -- boolean (default ``False``);\n if ``True``, return the positions that are not descents\n\n - ``from_zero`` -- boolean (default ``False``);\n if ``True``, return the positions starting from `0`\n\n - ``index_set`` -- list (default: ``[1, ..., n-1]`` where ``self``\n is a permutation of ``n``); the index set to check for descents\n\n EXAMPLES::\n\n sage: Permutation([3,1,2]).descents()\n [1]\n sage: Permutation([1,4,3,2]).descents()\n [2, 3]\n sage: Permutation([1,4,3,2]).descents(final_descent=True)\n [2, 3, 4]\n sage: Permutation([1,4,3,2]).descents(index_set=[1,2])\n [2]\n sage: Permutation([1,4,3,2]).descents(from_zero=True)\n [1, 2]\n\n TESTS:\n\n Check that the original error of :trac:`23891` is fixed::\n\n sage: Permutations(4)([1,4,3,2]).weak_covers()\n [[1, 3, 4, 2], [1, 4, 2, 3]]\n " if (index_set is None): index_set = range(1, len(self)) if (side == 'right'): p = self else: p = self.inverse() descents = [] for i in index_set: if (p[(i - 1)] > p[i]): if (not positive): descents.append(i) elif positive: descents.append(i) if final_descent: descents.append(len(p)) if from_zero: return [(i - 1) for i in descents] return descents def idescents(self, final_descent=False, from_zero=False): "\n Return a list of the idescents of ``self``, that is the list of\n the descents of ``self``'s inverse.\n\n A descent of a permutation ``p`` is an integer ``i`` such that\n ``p(i) > p(i+1)``.\n\n .. WARNING::\n\n By default, the descents are returned as elements in the\n index set, i.e., starting at `1`. If you want them to\n start at `0`, set the keyword ``from_zero`` to ``True``.\n\n INPUT:\n\n - ``final_descent`` -- boolean (default ``False``);\n if ``True``, the last position of a non-empty\n permutation is also considered as a descent\n\n - ``from_zero`` -- optional boolean (default ``False``);\n if ``False``, return the positions starting from `1`\n\n EXAMPLES::\n\n sage: Permutation([2,3,1]).idescents()\n [1]\n sage: Permutation([1,4,3,2]).idescents()\n [2, 3]\n sage: Permutation([1,4,3,2]).idescents(final_descent=True)\n [2, 3, 4]\n sage: Permutation([1,4,3,2]).idescents(from_zero=True)\n [1, 2]\n " return self.inverse().descents(final_descent=final_descent, from_zero=from_zero) def idescents_signature(self, final_descent=False): '\n Return the list obtained as follows: Each position in ``self``\n is mapped to `-1` if it is an idescent and `1` if it is not an\n idescent.\n\n See :meth:`idescents` for a definition of idescents.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).idescents()\n [2, 3]\n sage: Permutation([1,4,3,2]).idescents_signature()\n [1, -1, -1, 1]\n ' idescents = self.idescents(final_descent=final_descent) d = {True: (- 1), False: 1} return [d[((i + 1) in idescents)] for i in range(len(self))] def number_of_descents(self, final_descent=False) -> Integer: '\n Return the number of descents of ``self``.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).number_of_descents()\n 2\n sage: Permutation([1,4,3,2]).number_of_descents(final_descent=True)\n 3\n ' return len(self.descents(final_descent)) def number_of_idescents(self, final_descent=False) -> Integer: '\n Return the number of idescents of ``self``.\n\n See :meth:`idescents` for a definition of idescents.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).number_of_idescents()\n 2\n sage: Permutation([1,4,3,2]).number_of_idescents(final_descent=True)\n 3\n ' return len(self.idescents(final_descent)) @combinatorial_map(name='descent composition') def descents_composition(self) -> Composition: '\n Return the descent composition of ``self``.\n\n The descent composition of a permutation `p \\in S_n` is defined\n as the composition of `n` whose descent set equals the descent\n set of `p`. Here, the descent set of `p` is defined as the set\n of all `i \\in \\{ 1, 2, \\ldots, n-1 \\}` satisfying\n `p(i) > p(i+1)`. The descent set\n of a composition `c = (i_1, i_2, \\ldots, i_k)` is defined as\n the set `\\{ i_1, i_1 + i_2, i_1 + i_2 + i_3, \\ldots,\n i_1 + i_2 + \\cdots + i_{k-1} \\}`.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4]).descents_composition()\n [2, 2]\n sage: Permutation([4,1,6,7,2,3,8,5]).descents_composition()\n [1, 3, 3, 1]\n sage: Permutation([]).descents_composition()\n []\n ' if (len(self) == 0): return Composition([]) d = ([0] + self.descents(final_descent=True)) return Composition([(d[(i + 1)] - d[i]) for i in range((len(d) - 1))]) def descent_polynomial(self): "\n Return the descent polynomial of the permutation ``self``.\n\n The descent polynomial of a permutation `p` is the product of\n all the ``z[p(i)]`` where ``i`` ranges over the descents of\n ``p``.\n\n A descent of a permutation ``p`` is an integer ``i`` such that\n ``p(i) > p(i+1)``.\n\n REFERENCES:\n\n - [GS1984]_\n\n EXAMPLES::\n\n sage: Permutation([2,1,3]).descent_polynomial()\n z1\n sage: Permutation([4,3,2,1]).descent_polynomial()\n z1*z2^2*z3^3\n\n .. TODO::\n\n This docstring needs to be fixed. First, the definition\n does not match the implementation (or the examples).\n Second, this doesn't seem to be defined in [GS1984]_\n (the descent monomial in their (7.23) is different).\n " p = self z = [] P = PolynomialRing(ZZ, len(p), 'z') z = P.gens() result = 1 pol = 1 for i in range((len(p) - 1)): pol *= z[(p[i] - 1)] if (p[i] > p[(i + 1)]): result *= pol return result def major_index(self, final_descent=False) -> Integer: '\n Return the major index of ``self``.\n\n The major index of a permutation `p` is the sum of the descents of `p`.\n Since our permutation indices are 0-based, we need to add the\n number of descents.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3]).major_index()\n 1\n sage: Permutation([3,4,1,2]).major_index()\n 2\n sage: Permutation([4,3,2,1]).major_index()\n 6\n ' descents = self.descents(final_descent) return sum(descents) def multi_major_index(self, composition): '\n Return the multimajor index of this permutation with respect to ``composition``.\n\n INPUT:\n\n - ``composition`` -- a composition of the :meth:`size` of this permutation\n\n EXAMPLES::\n\n sage: p = Permutation([5, 6, 2, 1, 3, 7, 4])\n sage: p.multi_major_index([3, 2, 2])\n [2, 0, 1]\n sage: p.multi_major_index([7]) == [p.major_index()]\n True\n sage: p.multi_major_index([1]*7)\n [0, 0, 0, 0, 0, 0, 0]\n sage: Permutation([]).multi_major_index([])\n []\n\n TESTS::\n\n sage: p.multi_major_index([1, 3, 3, 7])\n Traceback (most recent call last):\n ...\n ValueError: size of the composition should be equal to size of the permutation\n\n REFERENCES:\n\n - [JS2000]_\n ' composition = Composition(composition) if (self.size() != composition.size()): raise ValueError('size of the composition should be equal to size of the permutation') descents = self.descents() partial_sum = ([0] + composition.partial_sums()) multimajor_index = [] for j in range(1, len(partial_sum)): a = partial_sum[(j - 1)] b = partial_sum[j] from bisect import bisect_right, bisect_left start = bisect_right(descents, a) end = bisect_left(descents, b) multimajor_index.append((sum(descents[start:end]) - ((end - start) * a))) return multimajor_index def imajor_index(self, final_descent=False) -> Integer: '\n Return the inverse major index of the permutation ``self``, which is\n the major index of the inverse of ``self``.\n\n The major index of a permutation `p` is the sum of the descents of `p`.\n Since our permutation indices are 0-based, we need to add the\n number of descents.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3]).imajor_index()\n 1\n sage: Permutation([3,4,1,2]).imajor_index()\n 2\n sage: Permutation([4,3,2,1]).imajor_index()\n 6\n ' return sum(self.idescents(final_descent)) def to_major_code(self, final_descent=False): '\n Return the major code of the permutation ``self``.\n\n The major code of a permutation `p` is defined as the sequence\n `(m_1-m_2, m_2-m_3, \\ldots, m_n)`, where `m_i` is the major\n index of the permutation obtained by erasing all letters smaller than\n `i` from `p`.\n\n With the ``final_descent`` option, the last position of a\n non-empty permutation is also considered as a descent.\n This has an effect on the computation of major indices.\n\n REFERENCES:\n\n - Carlitz, L. *q-Bernoulli and Eulerian Numbers*.\n Trans. Amer. Math. Soc. 76 (1954) 332-350.\n http://www.ams.org/journals/tran/1954-076-02/S0002-9947-1954-0060538-2/\n\n - Skandera, M. *An Eulerian Partner for Inversions*.\n Sém. Lothar. Combin. 46 (2001) B46d.\n http://www.lehigh.edu/~mas906/papers/partner.ps\n\n EXAMPLES::\n\n sage: Permutation([9,3,5,7,2,1,4,6,8]).to_major_code()\n [5, 0, 1, 0, 1, 2, 0, 1, 0]\n sage: Permutation([2,8,4,3,6,7,9,5,1]).to_major_code()\n [8, 3, 3, 1, 4, 0, 1, 0, 0]\n ' p = self n = len(p) major_indices = ([0] * (n + 1)) smaller = p[:] P = Permutations() for i in range(n): major_indices[i] = P(smaller).major_index(final_descent) smaller.remove(1) smaller = [(i - 1) for i in smaller] major_code = [(major_indices[i] - major_indices[(i + 1)]) for i in range(n)] return major_code def peaks(self) -> list: '\n Return a list of the peaks of the permutation ``self``.\n\n A peak of a permutation `p` is an integer `i` such that\n `p(i-1) < p(i)` and `p(i) > p(i+1)`.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4,5]).peaks()\n [1]\n sage: Permutation([4,1,3,2,6,5]).peaks()\n [2, 4]\n sage: Permutation([]).peaks()\n []\n ' p = self peaks = [] for i in range(1, (len(p) - 1)): if ((p[(i - 1)] <= p[i]) and (p[i] > p[(i + 1)])): peaks.append(i) return peaks def number_of_peaks(self) -> Integer: '\n Return the number of peaks of the permutation ``self``.\n\n A peak of a permutation `p` is an integer `i` such that\n `p(i-1) < p(i)` and `p(i) > p(i+1)`.\n\n EXAMPLES::\n\n sage: Permutation([1,3,2,4,5]).number_of_peaks()\n 1\n sage: Permutation([4,1,3,2,6,5]).number_of_peaks()\n 2\n ' return len(self.peaks()) def saliances(self) -> list: '\n Return a list of the saliances of the permutation ``self``.\n\n A saliance of a permutation `p` is an integer `i` such that\n `p(i) > p(j)` for all `j > i`.\n\n EXAMPLES::\n\n sage: Permutation([2,3,1,5,4]).saliances()\n [3, 4]\n sage: Permutation([5,4,3,2,1]).saliances()\n [0, 1, 2, 3, 4]\n ' p = self saliances = [] for i in range(len(p)): is_saliance = True for j in range((i + 1), len(p)): if (p[i] <= p[j]): is_saliance = False if is_saliance: saliances.append(i) return saliances def number_of_saliances(self) -> Integer: '\n Return the number of saliances of ``self``.\n\n A saliance of a permutation `p` is an integer `i` such that\n `p(i) > p(j)` for all `j > i`.\n\n EXAMPLES::\n\n sage: Permutation([2,3,1,5,4]).number_of_saliances()\n 2\n sage: Permutation([5,4,3,2,1]).number_of_saliances()\n 5\n ' return len(self.saliances()) def bruhat_lequal(self, p2) -> bool: '\n Return ``True`` if ``self`` is less or equal to ``p2`` in\n the Bruhat order.\n\n The Bruhat order (also called strong Bruhat order or Chevalley\n order) on the symmetric group `S_n` is the partial order on `S_n`\n determined by the following condition: If `p` is a permutation,\n and `i` and `j` are two indices satisfying `p(i) > p(j)` and\n `i < j` (that is, `(i, j)` is an inversion of `p` with `i < j`),\n then `p \\circ (i, j)` (the permutation obtained by first\n switching `i` with `j` and then applying `p`) is smaller than `p`\n in the Bruhat order.\n\n One can show that a permutation `p \\in S_n` is less or equal to\n a permutation `q \\in S_n` in the Bruhat order if and only if\n for every `i \\in \\{ 0, 1, \\cdots , n \\}` and\n `j \\in \\{ 1, 2, \\cdots , n \\}`, the number of the elements among\n `p(1), p(2), \\cdots, p(j)` that are greater than `i` is `\\leq`\n to the number of the elements among `q(1), q(2), \\cdots, q(j)`\n that are greater than `i`.\n\n This method assumes that ``self`` and ``p2`` are permutations\n of the same integer `n`.\n\n EXAMPLES::\n\n sage: Permutation([2,4,3,1]).bruhat_lequal(Permutation([3,4,2,1]))\n True\n\n sage: Permutation([2,1,3]).bruhat_lequal(Permutation([2,3,1]))\n True\n sage: Permutation([2,1,3]).bruhat_lequal(Permutation([3,1,2]))\n True\n sage: Permutation([2,1,3]).bruhat_lequal(Permutation([1,2,3]))\n False\n sage: Permutation([1,3,2]).bruhat_lequal(Permutation([2,1,3]))\n False\n sage: Permutation([1,3,2]).bruhat_lequal(Permutation([2,3,1]))\n True\n sage: Permutation([2,3,1]).bruhat_lequal(Permutation([1,3,2]))\n False\n sage: sorted( [len([b for b in Permutations(3) if a.bruhat_lequal(b)])\n ....: for a in Permutations(3)] )\n [1, 2, 2, 4, 4, 6]\n\n sage: Permutation([]).bruhat_lequal(Permutation([]))\n True\n ' p1 = self n1 = len(p1) if (n1 == 0): return True if ((p1[0] > p2[0]) or (p1[(n1 - 1)] < p2[(n1 - 1)])): return False for i in range(1, n1): c = 0 for j in range((n1 - 2)): if (p2[j] > i): c += 1 if (p1[j] > i): c -= 1 if (c < 0): return False return True def weak_excedences(self) -> list: '\n Return all the numbers ``self[i]`` such that ``self[i] >= i+1``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2,5]).weak_excedences()\n [1, 4, 3, 5]\n ' res = [] for i in range(len(self)): if (self[i] >= (i + 1)): res.append(self[i]) return res def bruhat_inversions(self) -> list: '\n Return the list of inversions of ``self`` such that the application of\n this inversion to ``self`` decreases its number of inversions by\n exactly 1.\n\n Equivalently, it returns the list of pairs `(i,j)` such that `i < j`,\n such that `p(i) > p(j)` and such that there exists no `k` (strictly)\n between `i` and `j` satisfying `p(i) > p(k) > p(j)`.\n\n EXAMPLES::\n\n sage: Permutation([5,2,3,4,1]).bruhat_inversions()\n [[0, 1], [0, 2], [0, 3], [1, 4], [2, 4], [3, 4]]\n sage: Permutation([6,1,4,5,2,3]).bruhat_inversions()\n [[0, 1], [0, 2], [0, 3], [2, 4], [2, 5], [3, 4], [3, 5]]\n ' return list(self.bruhat_inversions_iterator()) def bruhat_inversions_iterator(self): '\n Return the iterator for the inversions of ``self`` such that the\n application of this inversion to ``self`` decreases its number of\n inversions by exactly 1.\n\n EXAMPLES::\n\n sage: list(Permutation([5,2,3,4,1]).bruhat_inversions_iterator())\n [[0, 1], [0, 2], [0, 3], [1, 4], [2, 4], [3, 4]]\n sage: list(Permutation([6,1,4,5,2,3]).bruhat_inversions_iterator())\n [[0, 1], [0, 2], [0, 3], [2, 4], [2, 5], [3, 4], [3, 5]]\n ' p = self n = len(p) for i in range((n - 1)): for j in range((i + 1), n): if (p[i] > p[j]): ok = True for k in range((i + 1), j): if ((p[i] > p[k]) and (p[k] > p[j])): ok = False break if ok: (yield [i, j]) def bruhat_succ(self) -> list: '\n Return a list of the permutations strictly greater than ``self`` in\n the Bruhat order (on the symmetric group containing ``self``) such\n that there is no permutation between one of those and ``self``.\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutation([6,1,4,5,2,3]).bruhat_succ()\n [[6, 4, 1, 5, 2, 3],\n [6, 2, 4, 5, 1, 3],\n [6, 1, 5, 4, 2, 3],\n [6, 1, 4, 5, 3, 2]]\n ' return list(self.bruhat_succ_iterator()) def bruhat_succ_iterator(self): '\n An iterator for the permutations that are strictly greater than\n ``self`` in the Bruhat order (on the symmetric group containing\n ``self``) such that there is no permutation between one\n of those and ``self``.\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: [x for x in Permutation([6,1,4,5,2,3]).bruhat_succ_iterator()]\n [[6, 4, 1, 5, 2, 3],\n [6, 2, 4, 5, 1, 3],\n [6, 1, 5, 4, 2, 3],\n [6, 1, 4, 5, 3, 2]]\n ' p = self n = len(p) P = Permutations() for z in P([((n + 1) - x) for x in p]).bruhat_inversions_iterator(): pp = p[:] pp[z[0]] = p[z[1]] pp[z[1]] = p[z[0]] (yield P(pp)) def bruhat_pred(self) -> list: '\n Return a list of the permutations strictly smaller than ``self``\n in the Bruhat order (on the symmetric group containing ``self``) such\n that there is no permutation between one of those and ``self``.\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutation([6,1,4,5,2,3]).bruhat_pred()\n [[1, 6, 4, 5, 2, 3],\n [4, 1, 6, 5, 2, 3],\n [5, 1, 4, 6, 2, 3],\n [6, 1, 2, 5, 4, 3],\n [6, 1, 3, 5, 2, 4],\n [6, 1, 4, 2, 5, 3],\n [6, 1, 4, 3, 2, 5]]\n ' return list(self.bruhat_pred_iterator()) def bruhat_pred_iterator(self): '\n An iterator for the permutations strictly smaller than ``self`` in\n the Bruhat order (on the symmetric group containing ``self``) such\n that there is no permutation between one of those and ``self``.\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: [x for x in Permutation([6,1,4,5,2,3]).bruhat_pred_iterator()]\n [[1, 6, 4, 5, 2, 3],\n [4, 1, 6, 5, 2, 3],\n [5, 1, 4, 6, 2, 3],\n [6, 1, 2, 5, 4, 3],\n [6, 1, 3, 5, 2, 4],\n [6, 1, 4, 2, 5, 3],\n [6, 1, 4, 3, 2, 5]]\n ' p = self P = Permutations() for z in p.bruhat_inversions_iterator(): pp = p[:] pp[z[0]] = p[z[1]] pp[z[1]] = p[z[0]] (yield P(pp)) def bruhat_smaller(self): '\n Return the combinatorial class of permutations smaller than or\n equal to ``self`` in the Bruhat order (on the symmetric group\n containing ``self``).\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutation([4,1,2,3]).bruhat_smaller().list()\n [[1, 2, 3, 4],\n [1, 2, 4, 3],\n [1, 3, 2, 4],\n [1, 4, 2, 3],\n [2, 1, 3, 4],\n [2, 1, 4, 3],\n [3, 1, 2, 4],\n [4, 1, 2, 3]]\n ' return StandardPermutations_bruhat_smaller(self) def bruhat_greater(self): '\n Return the combinatorial class of permutations greater than or\n equal to ``self`` in the Bruhat order (on the symmetric group\n containing ``self``).\n\n See :meth:`bruhat_lequal` for the definition of the Bruhat order.\n\n EXAMPLES::\n\n sage: Permutation([4,1,2,3]).bruhat_greater().list()\n [[4, 1, 2, 3],\n [4, 1, 3, 2],\n [4, 2, 1, 3],\n [4, 2, 3, 1],\n [4, 3, 1, 2],\n [4, 3, 2, 1]]\n ' return StandardPermutations_bruhat_greater(self) def permutohedron_lequal(self, p2, side='right') -> bool: '\n Return ``True`` if ``self`` is less or equal to ``p2`` in the\n permutohedron order.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side=\'left\'``, then they will be done in\n the left permutohedron.\n\n For every nonnegative integer `n`, the right (resp. left)\n permutohedron order (also called the right (resp. left) weak\n order, or the right (resp. left) weak Bruhat order) is a partial\n order on the symmetric group `S_n`. It can be defined in various\n ways, including the following ones:\n\n - Two permutations `u` and `v` in `S_n` satisfy `u \\leq v` in\n the right (resp. left) permutohedron order if and only if\n the (Coxeter) length of the permutation `v^{-1} \\circ u`\n (resp. of the permutation `u \\circ v^{-1}`) equals the\n length of `v` minus the length of `u`. Here, `p \\circ q` means\n the permutation obtained by applying `q` first and then `p`.\n (Recall that the Coxeter length of a permutation is its number\n of inversions.)\n\n - Two permutations `u` and `v` in `S_n` satisfy `u \\leq v` in\n the right (resp. left) permutohedron order if and only if\n every pair `(i, j)` of elements of `\\{ 1, 2, \\cdots, n \\}`\n such that `i < j` and `u^{-1}(i) > u^{-1}(j)` (resp.\n `u(i) > u(j)`) also satisfies `v^{-1}(i) > v^{-1}(j)`\n (resp. `v(i) > v(j)`).\n\n - A permutation `v \\in S_n` covers a permutation `u \\in S_n` in\n the right (resp. left) permutohedron order if and only if we\n have `v = u \\circ (i, i + 1)` (resp. `v = (i, i + 1) \\circ u`)\n for some `i \\in \\{ 1, 2, \\cdots, n - 1 \\}` satisfying\n `u(i) < u(i + 1)` (resp. `u^{-1}(i) < u^{-1}(i + 1)`). Here,\n again, `p \\circ q` means the permutation obtained by applying\n `q` first and then `p`.\n\n The right and the left permutohedron order are mutually\n isomorphic, with the isomorphism being the map sending every\n permutation to its inverse. Each of these orders endows the\n symmetric group `S_n` with the structure of a graded poset\n (the rank function being the Coxeter length).\n\n .. WARNING::\n\n The permutohedron order is not to be mistaken for the\n strong Bruhat order (:meth:`bruhat_lequal`), despite both\n orders being occasionally referred to as the Bruhat order.\n\n EXAMPLES::\n\n sage: p = Permutation([3,2,1,4])\n sage: p.permutohedron_lequal(Permutation([4,2,1,3]))\n False\n sage: p.permutohedron_lequal(Permutation([4,2,1,3]), side=\'left\')\n True\n sage: p.permutohedron_lequal(p)\n True\n\n sage: Permutation([2,1,3]).permutohedron_lequal(Permutation([2,3,1]))\n True\n sage: Permutation([2,1,3]).permutohedron_lequal(Permutation([3,1,2]))\n False\n sage: Permutation([2,1,3]).permutohedron_lequal(Permutation([1,2,3]))\n False\n sage: Permutation([1,3,2]).permutohedron_lequal(Permutation([2,1,3]))\n False\n sage: Permutation([1,3,2]).permutohedron_lequal(Permutation([2,3,1]))\n False\n sage: Permutation([2,3,1]).permutohedron_lequal(Permutation([1,3,2]))\n False\n sage: Permutation([2,1,3]).permutohedron_lequal(Permutation([2,3,1]), side=\'left\')\n False\n sage: sorted( [len([b for b in Permutations(3) if a.permutohedron_lequal(b)])\n ....: for a in Permutations(3)] )\n [1, 2, 2, 3, 3, 6]\n sage: sorted( [len([b for b in Permutations(3) if a.permutohedron_lequal(b, side="left")])\n ....: for a in Permutations(3)] )\n [1, 2, 2, 3, 3, 6]\n\n sage: Permutation([]).permutohedron_lequal(Permutation([]))\n True\n ' p1 = self l1 = p1.number_of_inversions() l2 = p2.number_of_inversions() if (l1 > l2): return False if (side == 'right'): prod = p1._left_to_right_multiply_on_right(p2.inverse()) else: prod = p1._left_to_right_multiply_on_left(p2.inverse()) return (prod.number_of_inversions() == (l2 - l1)) def permutohedron_succ(self, side='right'): "\n Return a list of the permutations strictly greater than ``self``\n in the permutohedron order such that there is no permutation\n between any of those and ``self``.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side='left'``, then they will be done in\n the left permutohedron.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: p = Permutation([4,2,1,3])\n sage: p.permutohedron_succ()\n [[4, 2, 3, 1]]\n sage: p.permutohedron_succ(side='left')\n [[4, 3, 1, 2]]\n " p = self n = len(p) P = Permutations() succ = [] if (side == 'right'): rise = (lambda perm: [i for i in range((n - 1)) if (perm[i] < perm[(i + 1)])]) for i in rise(p): pp = p[:] pp[i] = p[(i + 1)] pp[(i + 1)] = p[i] succ.append(P(pp)) else: advance = (lambda perm: [i for i in range(1, n) if (perm.index(i) < perm.index((i + 1)))]) for i in advance(p): pp = p[:] pp[p.index(i)] = (i + 1) pp[p.index((i + 1))] = i succ.append(P(pp)) return succ def permutohedron_pred(self, side='right') -> list: "\n Return a list of the permutations strictly smaller than ``self``\n in the permutohedron order such that there is no permutation\n between any of those and ``self``.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side='left'``, then they will be done in\n the left permutohedron.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: p = Permutation([4,2,1,3])\n sage: p.permutohedron_pred()\n [[2, 4, 1, 3], [4, 1, 2, 3]]\n sage: p.permutohedron_pred(side='left')\n [[4, 1, 2, 3], [3, 2, 1, 4]]\n " p = self n = len(p) P = Permutations() pred = [] if (side == 'right'): for d in p.descents(): pp = p[:] pp[(d - 1)] = p[d] pp[d] = p[(d - 1)] pred.append(P(pp)) else: recoil = (lambda perm: [i for i in range(1, n) if (perm.index(i) > perm.index((i + 1)))]) for i in recoil(p): pp = p[:] pp[p.index(i)] = (i + 1) pp[p.index((i + 1))] = i pred.append(P(pp)) return pred def permutohedron_smaller(self, side='right') -> list: "\n Return a list of permutations smaller than or equal to ``self``\n in the permutohedron order.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side='left'``, then they will be done in\n the left permutohedron.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: Permutation([4,2,1,3]).permutohedron_smaller()\n [[1, 2, 3, 4],\n [1, 2, 4, 3],\n [1, 4, 2, 3],\n [2, 1, 3, 4],\n [2, 1, 4, 3],\n [2, 4, 1, 3],\n [4, 1, 2, 3],\n [4, 2, 1, 3]]\n\n ::\n\n sage: Permutation([4,2,1,3]).permutohedron_smaller(side='left')\n [[1, 2, 3, 4],\n [1, 3, 2, 4],\n [2, 1, 3, 4],\n [2, 3, 1, 4],\n [3, 1, 2, 4],\n [3, 2, 1, 4],\n [4, 1, 2, 3],\n [4, 2, 1, 3]]\n " return transitive_ideal((lambda x: x.permutohedron_pred(side)), self) def permutohedron_greater(self, side='right') -> list: "\n Return a list of permutations greater than or equal to ``self``\n in the permutohedron order.\n\n By default, the computations are done in the right permutohedron.\n If you pass the option ``side='left'``, then they will be done in\n the left permutohedron.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: Permutation([4,2,1,3]).permutohedron_greater()\n [[4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 2, 1]]\n sage: Permutation([4,2,1,3]).permutohedron_greater(side='left')\n [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 2, 1]]\n " return transitive_ideal((lambda x: x.permutohedron_succ(side)), self) def right_permutohedron_interval_iterator(self, other): '\n Return an iterator on the permutations (represented as integer\n lists) belonging to the right permutohedron interval where\n ``self`` is the minimal element and ``other`` the maximal element.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: p = Permutation([2, 1, 4, 5, 3]); q = Permutation([2, 5, 4, 1, 3])\n sage: p.right_permutohedron_interval(q) # indirect doctest # needs sage.graphs sage.modules\n [[2, 4, 5, 1, 3], [2, 4, 1, 5, 3], [2, 1, 4, 5, 3],\n [2, 1, 5, 4, 3], [2, 5, 1, 4, 3], [2, 5, 4, 1, 3]]\n ' if (len(self) != len(other)): raise ValueError('len({}) and len({}) must be equal'.format(self, other)) if (not self.permutohedron_lequal(other)): raise ValueError('{} must be lower or equal than {} for the right permutohedron order'.format(self, other)) d = DiGraph() d.add_vertices(range(1, (len(self) + 1))) d.add_edges([(j, i) for (i, j) in self.inverse().inversions()]) d.add_edges([(other[i], other[j]) for i in range((len(other) - 1)) for j in range(i, len(other)) if (other[i] < other[j])]) return d.topological_sort_generator() def right_permutohedron_interval(self, other): '\n Return the list of the permutations belonging to the right\n permutohedron interval where ``self`` is the minimal element and\n ``other`` the maximal element.\n\n See :meth:`permutohedron_lequal` for the definition of the\n permutohedron orders.\n\n EXAMPLES::\n\n sage: p = Permutation([2, 1, 4, 5, 3]); q = Permutation([2, 5, 4, 1, 3])\n sage: p.right_permutohedron_interval(q) # needs sage.graphs sage.modules\n [[2, 4, 5, 1, 3], [2, 4, 1, 5, 3], [2, 1, 4, 5, 3],\n [2, 1, 5, 4, 3], [2, 5, 1, 4, 3], [2, 5, 4, 1, 3]]\n\n TESTS::\n\n sage: # needs sage.graphs sage.modules\n sage: Permutation([]).right_permutohedron_interval(Permutation([]))\n [[]]\n sage: Permutation([3, 1, 2]).right_permutohedron_interval(Permutation([3, 1, 2]))\n [[3, 1, 2]]\n sage: Permutation([1, 3, 2, 4]).right_permutohedron_interval(Permutation([3, 4, 2, 1]))\n [[3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [1, 3, 4, 2],\n [1, 3, 2, 4], [3, 2, 4, 1], [3, 2, 1, 4], [3, 1, 2, 4]]\n sage: Permutation([2, 1, 4, 5, 3]).right_permutohedron_interval(Permutation([2, 5, 4, 1, 3]))\n [[2, 4, 5, 1, 3], [2, 4, 1, 5, 3], [2, 1, 4, 5, 3],\n [2, 1, 5, 4, 3], [2, 5, 1, 4, 3], [2, 5, 4, 1, 3]]\n sage: Permutation([2, 5, 4, 1, 3]).right_permutohedron_interval(Permutation([2, 1, 4, 5, 3]))\n Traceback (most recent call last):\n ...\n ValueError: [2, 5, 4, 1, 3] must be lower or equal than [2, 1, 4, 5, 3] for the right permutohedron order\n sage: Permutation([2, 4, 1, 3]).right_permutohedron_interval(Permutation([2, 1, 4, 5, 3]))\n Traceback (most recent call last):\n ...\n ValueError: len([2, 4, 1, 3]) and len([2, 1, 4, 5, 3]) must be equal\n ' P = Permutations() return [P(p) for p in self.right_permutohedron_interval_iterator(other)] def permutohedron_join(self, other, side='right') -> Permutation: '\n Return the join of the permutations ``self`` and ``other``\n in the right permutohedron order (or, if ``side`` is set to\n ``\'left\'``, in the left permutohedron order).\n\n The permutohedron orders (see :meth:`permutohedron_lequal`)\n are lattices; the join operation refers to this lattice\n structure. In more elementary terms, the join of two\n permutations `\\pi` and `\\psi` in the symmetric group `S_n`\n is the permutation in `S_n` whose set of inversion is the\n transitive closure of the union of the set of inversions of\n `\\pi` with the set of inversions of `\\psi`.\n\n .. SEEALSO::\n\n :meth:`permutohedron_lequal`, :meth:`permutohedron_meet`.\n\n ALGORITHM:\n\n It is enough to construct the join of any two permutations\n `\\pi` and `\\psi` in `S_n` with respect to the right weak\n order. (The join of `\\pi` and `\\psi` with respect to the\n left weak order is the inverse of the join of `\\pi^{-1}`\n and `\\psi^{-1}` with respect to the right weak order.)\n Start with an empty list `l` (denoted ``xs`` in the actual\n code). For `i = 1, 2, \\ldots, n` (in this order), we insert\n `i` into this list in the rightmost possible position such\n that any letter in `\\{ 1, 2, ..., i-1 \\}` which appears\n further right than `i` in either `\\pi` or `\\psi` (or both)\n must appear further right than `i` in the resulting list.\n After all numbers are inserted, we are left with a list\n which is precisely the join of `\\pi` and `\\psi` (in\n one-line notation). This algorithm is due to Markowsky,\n [Mar1994]_ (Theorem 1 (a)).\n\n AUTHORS:\n\n Viviane Pons and Darij Grinberg, 18 June 2014.\n\n EXAMPLES::\n\n sage: p = Permutation([3,1,2])\n sage: q = Permutation([1,3,2])\n sage: p.permutohedron_join(q)\n [3, 1, 2]\n sage: r = Permutation([2,1,3])\n sage: r.permutohedron_join(p)\n [3, 2, 1]\n\n ::\n\n sage: p = Permutation([3,2,4,1])\n sage: q = Permutation([4,2,1,3])\n sage: p.permutohedron_join(q)\n [4, 3, 2, 1]\n sage: r = Permutation([3,1,2,4])\n sage: p.permutohedron_join(r)\n [3, 2, 4, 1]\n sage: q.permutohedron_join(r)\n [4, 3, 2, 1]\n sage: s = Permutation([1,4,2,3])\n sage: s.permutohedron_join(r)\n [4, 3, 1, 2]\n\n The universal property of the join operation is\n satisfied::\n\n sage: def test_uni_join(p, q):\n ....: j = p.permutohedron_join(q)\n ....: if not p.permutohedron_lequal(j):\n ....: return False\n ....: if not q.permutohedron_lequal(j):\n ....: return False\n ....: for r in p.permutohedron_greater():\n ....: if q.permutohedron_lequal(r) and not j.permutohedron_lequal(r):\n ....: return False\n ....: return True\n sage: all( test_uni_join(p, q) for p in Permutations(3) for q in Permutations(3) )\n True\n sage: test_uni_join(Permutation([6, 4, 7, 3, 2, 5, 8, 1]), Permutation([7, 3, 1, 2, 5, 4, 6, 8]))\n True\n\n Border cases::\n\n sage: p = Permutation([])\n sage: p.permutohedron_join(p)\n []\n sage: p = Permutation([1])\n sage: p.permutohedron_join(p)\n [1]\n\n The left permutohedron::\n\n sage: p = Permutation([3,1,2])\n sage: q = Permutation([1,3,2])\n sage: p.permutohedron_join(q, side="left")\n [3, 2, 1]\n sage: r = Permutation([2,1,3])\n sage: r.permutohedron_join(p, side="left")\n [3, 1, 2]\n ' if (side == 'left'): return self.inverse().permutohedron_join(other.inverse()).inverse() n = self.size() xs: list[int] = [] for i in range(1, (n + 1)): u = self.index(i) must_be_right = [f for f in self[(u + 1):] if (f < i)] v = other.index(i) must_be_right += [f for f in other[(v + 1):] if (f < i)] must_be_right = sorted(set(must_be_right)) for (j, q) in enumerate(xs): if (q in must_be_right): xs = ((xs[:j] + [i]) + xs[j:]) break else: xs.append(i) return Permutations(n)(xs) def permutohedron_meet(self, other, side='right') -> Permutation: '\n Return the meet of the permutations ``self`` and ``other``\n in the right permutohedron order (or, if ``side`` is set to\n ``\'left\'``, in the left permutohedron order).\n\n The permutohedron orders (see :meth:`permutohedron_lequal`)\n are lattices; the meet operation refers to this lattice\n structure. It is connected to the join operation by the\n following simple symmetry property: If `\\pi` and `\\psi`\n are two permutations `\\pi` and `\\psi` in the symmetric group\n `S_n`, and if `w_0` denotes the permutation\n `(n, n-1, \\ldots, 1) \\in S_n`, then\n\n .. MATH::\n\n \\pi \\wedge \\psi = w_0 \\circ ((w_0 \\circ \\pi) \\vee (w_0 \\circ \\psi))\n = ((\\pi \\circ w_0) \\vee (\\psi \\circ w_0)) \\circ w_0\n\n and\n\n .. MATH::\n\n \\pi \\vee \\psi = w_0 \\circ ((w_0 \\circ \\pi) \\wedge (w_0 \\circ \\psi))\n = ((\\pi \\circ w_0) \\wedge (\\psi \\circ w_0)) \\circ w_0,\n\n where `\\wedge` means meet and `\\vee` means join.\n\n .. SEEALSO::\n\n :meth:`permutohedron_lequal`, :meth:`permutohedron_join`.\n\n AUTHORS:\n\n Viviane Pons and Darij Grinberg, 18 June 2014.\n\n EXAMPLES::\n\n sage: p = Permutation([3,1,2])\n sage: q = Permutation([1,3,2])\n sage: p.permutohedron_meet(q)\n [1, 3, 2]\n sage: r = Permutation([2,1,3])\n sage: r.permutohedron_meet(p)\n [1, 2, 3]\n\n ::\n\n sage: p = Permutation([3,2,4,1])\n sage: q = Permutation([4,2,1,3])\n sage: p.permutohedron_meet(q)\n [2, 1, 3, 4]\n sage: r = Permutation([3,1,2,4])\n sage: p.permutohedron_meet(r)\n [3, 1, 2, 4]\n sage: q.permutohedron_meet(r)\n [1, 2, 3, 4]\n sage: s = Permutation([1,4,2,3])\n sage: s.permutohedron_meet(r)\n [1, 2, 3, 4]\n\n The universal property of the meet operation is\n satisfied::\n\n sage: def test_uni_meet(p, q):\n ....: m = p.permutohedron_meet(q)\n ....: if not m.permutohedron_lequal(p):\n ....: return False\n ....: if not m.permutohedron_lequal(q):\n ....: return False\n ....: for r in p.permutohedron_smaller():\n ....: if r.permutohedron_lequal(q) and not r.permutohedron_lequal(m):\n ....: return False\n ....: return True\n sage: all( test_uni_meet(p, q) for p in Permutations(3) for q in Permutations(3) )\n True\n sage: test_uni_meet(Permutation([6, 4, 7, 3, 2, 5, 8, 1]), Permutation([7, 3, 1, 2, 5, 4, 6, 8]))\n True\n\n Border cases::\n\n sage: p = Permutation([])\n sage: p.permutohedron_meet(p)\n []\n sage: p = Permutation([1])\n sage: p.permutohedron_meet(p)\n [1]\n\n The left permutohedron::\n\n sage: p = Permutation([3,1,2])\n sage: q = Permutation([1,3,2])\n sage: p.permutohedron_meet(q, side="left")\n [1, 2, 3]\n sage: r = Permutation([2,1,3])\n sage: r.permutohedron_meet(p, side="left")\n [2, 1, 3]\n ' return self.reverse().permutohedron_join(other.reverse(), side=side).reverse() def has_pattern(self, patt) -> bool: '\n Test whether the permutation ``self`` contains the pattern\n ``patt``.\n\n EXAMPLES::\n\n sage: Permutation([3,5,1,4,6,2]).has_pattern([1,3,2]) # needs sage.combinat\n True\n ' p = self n = len(p) l = len(patt) if (l > n): return False for pos in itertools.combinations(range(n), l): if (to_standard([p[z] for z in pos]) == patt): return True return False def avoids(self, patt) -> bool: '\n Test whether the permutation ``self`` avoids the pattern\n ``patt``.\n\n EXAMPLES::\n\n sage: Permutation([6,2,5,4,3,1]).avoids([4,2,3,1]) # needs sage.combinat\n False\n sage: Permutation([6,1,2,5,4,3]).avoids([4,2,3,1]) # needs sage.combinat\n True\n sage: Permutation([6,1,2,5,4,3]).avoids([3,4,1,2]) # needs sage.combinat\n True\n ' return (not self.has_pattern(patt)) def pattern_positions(self, patt) -> list: '\n Return the list of positions where the pattern ``patt`` appears\n in the permutation ``self``.\n\n EXAMPLES::\n\n sage: Permutation([3,5,1,4,6,2]).pattern_positions([1,3,2]) # needs sage.combinat\n [[0, 1, 3], [2, 3, 5], [2, 4, 5]]\n ' p = self return [list(pos) for pos in itertools.combinations(range(len(p)), len(patt)) if (to_standard([p[z] for z in pos]) == patt)] @combinatorial_map(name='Simion-Schmidt map') def simion_schmidt(self, avoid=[1, 2, 3]): '\n Implements the Simion-Schmidt map which sends an arbitrary permutation\n to a pattern avoiding permutation, where the permutation pattern is one\n of four length-three patterns. This method also implements the bijection\n between (for example) ``[1,2,3]``- and ``[1,3,2]``-avoiding permutations.\n\n INPUT:\n\n - ``avoid`` -- one of the patterns ``[1,2,3]``, ``[1,3,2]``, ``[3,1,2]``, ``[3,2,1]``.\n\n EXAMPLES::\n\n sage: P = Permutations(6)\n sage: p = P([4,5,1,6,3,2])\n sage: pl = [ [1,2,3], [1,3,2], [3,1,2], [3,2,1] ]\n sage: for q in pl: # needs sage.combinat\n ....: s = p.simion_schmidt(q)\n ....: print("{} {}".format(s, s.has_pattern(q)))\n [4, 6, 1, 5, 3, 2] False\n [4, 2, 1, 3, 5, 6] False\n [4, 5, 3, 6, 2, 1] False\n [4, 5, 1, 6, 2, 3] False\n ' if (len(list(self)) <= 2): return self targetPermutation = [self[0]] extreme = self[0] nonMinima = [] if ((avoid == [1, 2, 3]) or (avoid == [1, 3, 2])): for i in range(1, len(list(self))): if (self[i] < extreme): targetPermutation.append(self[i]) extreme = self[i] else: targetPermutation.append(None) nonMinima.append(self[i]) nonMinima.sort() if (avoid == [1, 3, 2]): nonMinima.reverse() if ((avoid == [3, 2, 1]) or (avoid == [3, 1, 2])): for i in range(1, len(list(self))): if (self[i] > extreme): targetPermutation.append(self[i]) extreme = self[i] else: targetPermutation.append(None) nonMinima.append(self[i]) nonMinima.sort() if (avoid == [3, 2, 1]): nonMinima.reverse() for i in range(1, len(list(self))): if (targetPermutation[i] is None): targetPermutation[i] = nonMinima.pop() return Permutations()(targetPermutation) @combinatorial_map(order=2, name='reverse') def reverse(self): '\n Return the permutation obtained by reversing the list.\n\n EXAMPLES::\n\n sage: Permutation([3,4,1,2]).reverse()\n [2, 1, 4, 3]\n sage: Permutation([1,2,3,4,5]).reverse()\n [5, 4, 3, 2, 1]\n ' return self.__class__(self.parent(), [i for i in reversed(self)]) @combinatorial_map(order=2, name='complement') def complement(self): '\n Return the complement of the permutation ``self``.\n\n The complement of a permutation `w \\in S_n` is defined as the\n permutation in `S_n` sending each `i` to `n + 1 - w(i)`.\n\n EXAMPLES::\n\n sage: Permutation([1,2,3]).complement()\n [3, 2, 1]\n sage: Permutation([1, 3, 2]).complement()\n [3, 1, 2]\n ' n = len(self) return self.__class__(self.parent(), [((n - x) + 1) for x in self]) @combinatorial_map(name='permutation poset') def permutation_poset(self): '\n Return the permutation poset of ``self``.\n\n The permutation poset of a permutation `p` is the poset with\n vertices `(i, p(i))` for `i = 1, 2, \\ldots, n` (where `n` is the\n size of `p`) and order inherited from `\\ZZ \\times \\ZZ`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.graphs\n sage: Permutation([3,1,5,4,2]).permutation_poset().cover_relations()\n [[(2, 1), (5, 2)],\n [(2, 1), (3, 5)],\n [(2, 1), (4, 4)],\n [(1, 3), (3, 5)],\n [(1, 3), (4, 4)]]\n sage: Permutation([]).permutation_poset().cover_relations()\n []\n sage: Permutation([1,3,2]).permutation_poset().cover_relations()\n [[(1, 1), (2, 3)], [(1, 1), (3, 2)]]\n sage: Permutation([1,2]).permutation_poset().cover_relations()\n [[(1, 1), (2, 2)]]\n sage: P = Permutation([1,5,2,4,3])\n\n This should hold for any `P`::\n\n sage: P.permutation_poset().greene_shape() == P.RS_partition() # needs sage.combinat sage.graphs\n True\n ' from sage.combinat.posets.posets import Poset n = len(self) posetdict = {} for i in range(n): u = self[i] posetdict[((i + 1), u)] = [((j + 1), self[j]) for j in range((i + 1), n) if (u < self[j])] return Poset(posetdict) def dict(self): '\n Return a dictionary corresponding to the permutation.\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: d = p.dict()\n sage: d[1]\n 2\n sage: d[2]\n 1\n sage: d[3]\n 3\n ' return dict(enumerate(self, start=1)) def action(self, a): '\n Return the action of the permutation ``self`` on a list ``a``.\n\n The action of a permutation `p \\in S_n` on an `n`-element list\n `(a_1, a_2, \\ldots, a_n)` is defined to be\n `(a_{p(1)}, a_{p(2)}, \\ldots, a_{p(n)})`.\n\n EXAMPLES::\n\n sage: p = Permutation([2,1,3])\n sage: a = list(range(3))\n sage: p.action(a)\n [1, 0, 2]\n sage: b = [1,2,3,4]\n sage: p.action(b)\n Traceback (most recent call last):\n ...\n ValueError: len(a) must equal len(self)\n\n sage: q = Permutation([2,3,1])\n sage: a = list(range(3))\n sage: q.action(a)\n [1, 2, 0]\n ' if (len(a) != len(self)): raise ValueError('len(a) must equal len(self)') return [a[(i - 1)] for i in self] def robinson_schensted(self): '\n Return the pair of standard tableaux obtained by running the\n Robinson-Schensted algorithm on ``self``.\n\n This can also be done by running\n :func:`~sage.combinat.rsk.RSK` on ``self`` (with the optional argument\n ``check_standard=True`` to return standard Young tableaux).\n\n EXAMPLES::\n\n sage: Permutation([6,2,3,1,7,5,4]).robinson_schensted() # needs sage.combinat\n [[[1, 3, 4], [2, 5], [6, 7]], [[1, 3, 5], [2, 6], [4, 7]]]\n ' return RSK(self, check_standard=True) def _rsk_iter(self): '\n An iterator for RSK.\n\n Yields pairs ``[i, p(i)]`` for a permutation ``p``.\n\n EXAMPLES::\n\n sage: for x in Permutation([6,2,3,1,7,5,4])._rsk_iter(): x\n (1, 6)\n (2, 2)\n (3, 3)\n (4, 1)\n (5, 7)\n (6, 5)\n (7, 4)\n ' return zip(range(1, (len(self) + 1)), self) @combinatorial_map(name='Robinson-Schensted insertion tableau') def left_tableau(self): '\n Return the left standard tableau after performing the RSK\n algorithm on ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).left_tableau() # needs sage.combinat\n [[1, 2], [3], [4]]\n ' return RSK(self, check_standard=True)[0] @combinatorial_map(name='Robinson-Schensted recording tableau') def right_tableau(self): '\n Return the right standard tableau after performing the RSK\n algorithm on ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).right_tableau() # needs sage.combinat\n [[1, 2], [3], [4]]\n ' return RSK(self, check_standard=True)[1] def increasing_tree(self, compare=min): '\n Return the increasing tree associated to ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).increasing_tree() # needs sage.graphs\n 1[., 2[3[4[., .], .], .]]\n sage: Permutation([4,1,3,2]).increasing_tree() # needs sage.graphs\n 1[4[., .], 2[3[., .], .]]\n\n By passing the option ``compare=max`` one can have the decreasing\n tree instead::\n\n sage: Permutation([2,3,4,1]).increasing_tree(max) # needs sage.graphs\n 4[3[2[., .], .], 1[., .]]\n sage: Permutation([2,3,1,4]).increasing_tree(max) # needs sage.graphs\n 4[3[2[., .], 1[., .]], .]\n ' from sage.combinat.binary_tree import LabelledBinaryTree as LBT def rec(perm): if (len(perm) == 0): return LBT(None) mn = compare(perm) k = perm.index(mn) return LBT([rec(perm[:k]), rec(perm[(k + 1):])], label=mn) return rec(self) @combinatorial_map(name='Increasing tree') def increasing_tree_shape(self, compare=min): '\n Return the shape of the increasing tree associated with the\n permutation.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).increasing_tree_shape() # needs sage.graphs\n [., [[[., .], .], .]]\n sage: Permutation([4,1,3,2]).increasing_tree_shape() # needs sage.graphs\n [[., .], [[., .], .]]\n\n By passing the option ``compare=max`` one can have the decreasing\n tree instead::\n\n sage: Permutation([2,3,4,1]).increasing_tree_shape(max) # needs sage.graphs\n [[[., .], .], [., .]]\n sage: Permutation([2,3,1,4]).increasing_tree_shape(max) # needs sage.graphs\n [[[., .], [., .]], .]\n ' return self.increasing_tree(compare).shape() def binary_search_tree(self, left_to_right=True): '\n Return the binary search tree associated to ``self``.\n\n If `w` is a word, then the binary search tree associated to `w`\n is defined as the result of starting with an empty binary tree,\n and then inserting the letters of `w` one by one into this tree.\n Here, the insertion is being done according to the method\n :meth:`~sage.combinat.binary_tree.LabelledBinaryTree.binary_search_insert`,\n and the word `w` is being traversed from left to right.\n\n A permutation is regarded as a word (using one-line notation),\n and thus a binary search tree associated to a permutation is\n defined.\n\n If the optional keyword variable ``left_to_right`` is set to\n ``False``, the word `w` is being traversed from right to left\n instead.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).binary_search_tree() # needs sage.graphs\n 1[., 4[3[2[., .], .], .]]\n sage: Permutation([4,1,3,2]).binary_search_tree() # needs sage.graphs\n 4[1[., 3[2[., .], .]], .]\n\n By passing the option ``left_to_right=False`` one can have\n the insertion going from right to left::\n\n sage: Permutation([1,4,3,2]).binary_search_tree(False) # needs sage.graphs\n 2[1[., .], 3[., 4[., .]]]\n sage: Permutation([4,1,3,2]).binary_search_tree(False) # needs sage.graphs\n 2[1[., .], 3[., 4[., .]]]\n\n TESTS::\n\n sage: Permutation([]).binary_search_tree() # needs sage.graphs\n .\n ' from sage.combinat.binary_tree import LabelledBinaryTree as LBT res = LBT(None) if left_to_right: gen = self else: gen = self[::(- 1)] for i in gen: res = res.binary_search_insert(i) return res @combinatorial_map(name='Binary search tree (left to right)') def binary_search_tree_shape(self, left_to_right=True): '\n Return the shape of the binary search tree of the permutation\n (a non labelled binary tree).\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).binary_search_tree_shape() # needs sage.graphs\n [., [[[., .], .], .]]\n sage: Permutation([4,1,3,2]).binary_search_tree_shape() # needs sage.graphs\n [[., [[., .], .]], .]\n\n By passing the option ``left_to_right=False`` one can have\n the insertion going from right to left::\n\n sage: Permutation([1,4,3,2]).binary_search_tree_shape(False) # needs sage.graphs\n [[., .], [., [., .]]]\n sage: Permutation([4,1,3,2]).binary_search_tree_shape(False) # needs sage.graphs\n [[., .], [., [., .]]]\n ' from sage.combinat.binary_tree import binary_search_tree_shape return binary_search_tree_shape(list(self), left_to_right) def sylvester_class(self, left_to_right=False): '\n Iterate over the equivalence class of the permutation ``self``\n under sylvester congruence.\n\n Sylvester congruence is an equivalence relation on the set `S_n`\n of all permutations of `n`. It is defined as the smallest\n equivalence relation such that every permutation of the form\n `uacvbw` with `u`, `v` and `w` being words and `a`, `b` and `c`\n being letters satisfying `a \\leq b < c` is equivalent to the\n permutation `ucavbw`. (Here, permutations are regarded as words\n by way of one-line notation.) This definition comes from [HNT2005]_,\n Definition 8, where it is more generally applied to arbitrary\n words.\n\n The equivalence class of a permutation `p \\in S_n` under sylvester\n congruence is called the *sylvester class* of `p`. It is an\n interval in the right permutohedron order (see\n :meth:`permutohedron_lequal`) on `S_n`.\n\n This is related to the\n :meth:`~sage.combinat.binary_tree.LabelledBinaryTree.sylvester_class`\n method in that the equivalence class of a permutation `\\pi` under\n sylvester congruence is the sylvester class of the right-to-left\n binary search tree of `\\pi`. However, the present method\n yields permutations, while the method on labelled binary trees\n yields plain lists.\n\n If the variable ``left_to_right`` is set to ``True``, the method\n instead iterates over the equivalence class of ``self`` with\n respect to the *left* sylvester congruence. The left sylvester\n congruence is easiest to define by saying that two permutations\n are equivalent under it if and only if their reverses\n (:meth:`reverse`) are equivalent under (standard) sylvester\n congruence.\n\n EXAMPLES:\n\n The sylvester class of a permutation in `S_5`::\n\n sage: p = Permutation([3, 5, 1, 2, 4])\n sage: sorted(p.sylvester_class()) # needs sage.combinat sage.graphs\n [[1, 3, 2, 5, 4],\n [1, 3, 5, 2, 4],\n [1, 5, 3, 2, 4],\n [3, 1, 2, 5, 4],\n [3, 1, 5, 2, 4],\n [3, 5, 1, 2, 4],\n [5, 1, 3, 2, 4],\n [5, 3, 1, 2, 4]]\n\n The sylvester class of a permutation `p` contains `p`::\n\n sage: all(p in p.sylvester_class() for p in Permutations(4)) # needs sage.combinat sage.graphs\n True\n\n Small cases::\n\n sage: list(Permutation([]).sylvester_class()) # needs sage.combinat sage.graphs\n [[]]\n\n sage: list(Permutation([1]).sylvester_class()) # needs sage.combinat sage.graphs\n [[1]]\n\n The sylvester classes in `S_3`::\n\n sage: [sorted(p.sylvester_class()) for p in Permutations(3)] # needs sage.combinat sage.graphs\n [[[1, 2, 3]],\n [[1, 3, 2], [3, 1, 2]],\n [[2, 1, 3]],\n [[2, 3, 1]],\n [[1, 3, 2], [3, 1, 2]],\n [[3, 2, 1]]]\n\n The left sylvester classes in `S_3`::\n\n sage: [sorted(p.sylvester_class(left_to_right=True)) # needs sage.combinat sage.graphs\n ....: for p in Permutations(3)]\n [[[1, 2, 3]],\n [[1, 3, 2]],\n [[2, 1, 3], [2, 3, 1]],\n [[2, 1, 3], [2, 3, 1]],\n [[3, 1, 2]],\n [[3, 2, 1]]]\n\n A left sylvester class in `S_5`::\n\n sage: p = Permutation([4, 2, 1, 5, 3])\n sage: sorted(p.sylvester_class(left_to_right=True)) # needs sage.combinat sage.graphs\n [[4, 2, 1, 3, 5],\n [4, 2, 1, 5, 3],\n [4, 2, 3, 1, 5],\n [4, 2, 3, 5, 1],\n [4, 2, 5, 1, 3],\n [4, 2, 5, 3, 1],\n [4, 5, 2, 1, 3],\n [4, 5, 2, 3, 1]]\n ' parself = self.parent() t = self.binary_search_tree(left_to_right=left_to_right) for u in t.sylvester_class(left_to_right=left_to_right): (yield parself(u)) @combinatorial_map(name='Robinson-Schensted tableau shape') def RS_partition(self): '\n Return the shape of the tableaux obtained by applying the RSK\n algorithm to ``self``.\n\n EXAMPLES::\n\n sage: Permutation([1,4,3,2]).RS_partition() # needs sage.combinat\n [2, 1, 1]\n ' return RSK(self)[1].shape() def remove_extra_fixed_points(self): '\n Return the permutation obtained by removing any fixed points at\n the end of ``self``.\n\n However, return ``[1]`` rather than ``[]`` if ``self`` is the\n identity permutation.\n\n This is mostly a helper method for\n :mod:`sage.combinat.schubert_polynomial`, where it is\n used to normalize finitary permutations of\n `\\{1,2,3,\\ldots\\}`.\n\n EXAMPLES::\n\n sage: Permutation([2,1,3]).remove_extra_fixed_points()\n [2, 1]\n sage: Permutation([1,2,3,4]).remove_extra_fixed_points()\n [1]\n sage: Permutation([2,1]).remove_extra_fixed_points()\n [2, 1]\n sage: Permutation([]).remove_extra_fixed_points()\n [1]\n\n .. SEEALSO::\n\n :meth:`retract_plain`\n ' if (not self): return Permutations()([1]) i = (len(self) - 1) while (i >= 1): if (i != (self[i] - 1)): break i -= 1 return Permutations()(self[:(i + 1)]) def retract_plain(self, m): '\n Return the plain retract of the permutation ``self`` in `S_n`\n to `S_m`, where `m \\leq n`. If this retract is undefined, then\n ``None`` is returned.\n\n If `p \\in S_n` is a permutation, and `m` is a nonnegative integer\n less or equal to `n`, then the plain retract of `p` to `S_m` is\n defined only if every `i > m` satisfies `p(i) = i`. In this case,\n it is defined as the permutation written\n `(p(1), p(2), \\ldots, p(m))` in one-line notation.\n\n EXAMPLES::\n\n sage: Permutation([4,1,2,3,5]).retract_plain(4)\n [4, 1, 2, 3]\n sage: Permutation([4,1,2,3,5]).retract_plain(3)\n\n sage: Permutation([1,3,2,4,5,6]).retract_plain(3)\n [1, 3, 2]\n sage: Permutation([1,3,2,4,5,6]).retract_plain(2)\n\n sage: Permutation([1,2,3,4,5]).retract_plain(1)\n [1]\n sage: Permutation([1,2,3,4,5]).retract_plain(0)\n []\n\n sage: all( p.retract_plain(3) == p for p in Permutations(3) )\n True\n\n .. SEEALSO::\n\n :meth:`retract_direct_product`, :meth:`retract_okounkov_vershik`,\n :meth:`remove_extra_fixed_points`\n ' n = len(self) p = list(self) for i in range(m, n): if (p[i] != (i + 1)): return None return Permutations(m)(p[:m]) def retract_direct_product(self, m): '\n Return the direct-product retract of the permutation\n ``self`` `\\in S_n` to `S_m`, where `m \\leq n`. If this retract\n is undefined, then ``None`` is returned.\n\n If `p \\in S_n` is a permutation, and `m` is a nonnegative integer\n less or equal to `n`, then the direct-product retract of `p` to\n `S_m` is defined only if `p([m]) = [m]`, where `[m]` denotes the\n interval `\\{1, 2, \\ldots, m\\}`. In this case, it is defined as the\n permutation written `(p(1), p(2), \\ldots, p(m))` in one-line\n notation.\n\n EXAMPLES::\n\n sage: Permutation([4,1,2,3,5]).retract_direct_product(4)\n [4, 1, 2, 3]\n sage: Permutation([4,1,2,3,5]).retract_direct_product(3)\n\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(5)\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(4)\n [1, 4, 2, 3]\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(3)\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(2)\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(1)\n [1]\n sage: Permutation([1,4,2,3,6,5]).retract_direct_product(0)\n []\n\n sage: all( p.retract_direct_product(3) == p for p in Permutations(3) )\n True\n\n .. SEEALSO::\n\n :meth:`retract_plain`, :meth:`retract_okounkov_vershik`\n ' n = len(self) p = list(self) for i in range(m, n): if (p[i] <= m): return None return Permutations(m)(p[:m]) def retract_okounkov_vershik(self, m): '\n Return the Okounkov-Vershik retract of the permutation\n ``self`` `\\in S_n` to `S_m`, where `m \\leq n`.\n\n If `p \\in S_n` is a permutation, and `m` is a nonnegative integer\n less or equal to `n`, then the Okounkov-Vershik retract of `p` to\n `S_m` is defined as the permutation in `S_m` which sends every\n `i \\in \\{1, 2, \\ldots, m\\}` to `p^{k_i}(i)`, where `k_i` is the\n smallest positive integer `k` satisfying `p^k(i) \\leq m`.\n\n In other words, the Okounkov-Vershik retract of `p` is the\n permutation whose disjoint cycle decomposition is obtained by\n removing all letters strictly greater than `m` from the\n decomposition of `p` into disjoint cycles (and removing all\n cycles which are emptied in the process).\n\n When `m = n-1`, the Okounkov-Vershik retract (as a map\n `S_n \\to S_{n-1}`) is the map `\\widetilde{p}_n` introduced in\n Section 7 of [VO2005]_, and appears as (3.20) in\n [CST2010]_. In the general case, the Okounkov-Vershik retract\n of a permutation in `S_n` to `S_m` can be obtained by first\n taking its Okounkov-Vershik retract to `S_{n-1}`, then that\n of the resulting permutation to `S_{n-2}`, etc. until arriving\n in `S_m`.\n\n EXAMPLES::\n\n sage: Permutation([4,1,2,3,5]).retract_okounkov_vershik(4)\n [4, 1, 2, 3]\n sage: Permutation([4,1,2,3,5]).retract_okounkov_vershik(3)\n [3, 1, 2]\n sage: Permutation([4,1,2,3,5]).retract_okounkov_vershik(2)\n [2, 1]\n sage: Permutation([4,1,2,3,5]).retract_okounkov_vershik(1)\n [1]\n sage: Permutation([4,1,2,3,5]).retract_okounkov_vershik(0)\n []\n\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(5)\n [1, 4, 2, 3, 5]\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(4)\n [1, 4, 2, 3]\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(3)\n [1, 3, 2]\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(2)\n [1, 2]\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(1)\n [1]\n sage: Permutation([1,4,2,3,6,5]).retract_okounkov_vershik(0)\n []\n\n sage: Permutation([6,5,4,3,2,1]).retract_okounkov_vershik(5)\n [1, 5, 4, 3, 2]\n sage: Permutation([6,5,4,3,2,1]).retract_okounkov_vershik(4)\n [1, 2, 4, 3]\n\n sage: Permutation([1,5,2,6,3,7,4,8]).retract_okounkov_vershik(4)\n [1, 3, 2, 4]\n\n sage: all( p.retract_direct_product(3) == p for p in Permutations(3) )\n True\n\n .. SEEALSO::\n\n :meth:`retract_plain`, :meth:`retract_direct_product`\n ' res = [] for i in range(1, (m + 1)): j = self(i) while (j > m): j = self(j) res.append(j) return Permutations(m)(res) def hyperoctahedral_double_coset_type(self): '\n Return the coset-type of ``self`` as a partition.\n\n ``self`` must be a permutation of even size `2n`. The coset-type\n determines the double class of the permutation, that is its image in\n `H_n \\backslash S_{2n} / H_n`, where `H_n` is the `n`-th\n hyperoctahedral group.\n\n The coset-type is determined as follows. Consider the perfect matching\n `\\{\\{1,2\\},\\{3,4\\},\\dots,\\{2n-1,2n\\}\\}` and its image by ``self``, and\n draw them simultaneously as edges of a graph whose vertices are labeled\n by `1,2,\\dots,2n`. The coset-type is the ordered sequence of the\n semi-lengths of the cycles of this graph (see Chapter VII of [Mac1995]_ for\n more details, particularly Section VII.2).\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: p = Permutation([3, 4, 6, 1, 5, 7, 2, 8])\n sage: p.hyperoctahedral_double_coset_type()\n [3, 1]\n sage: all(p.hyperoctahedral_double_coset_type() ==\n ....: p.inverse().hyperoctahedral_double_coset_type()\n ....: for p in Permutations(4))\n True\n sage: Permutation([]).hyperoctahedral_double_coset_type()\n []\n sage: Permutation([3,1,2]).hyperoctahedral_double_coset_type()\n Traceback (most recent call last):\n ...\n ValueError: [3, 1, 2] is a permutation of odd size and has no coset-type\n ' from sage.combinat.perfect_matching import PerfectMatchings n = len(self) if ((n % 2) == 1): raise ValueError(('%s is a permutation of odd size and has no coset-type' % self)) S = PerfectMatchings(n)([(((2 * i) + 1), ((2 * i) + 2)) for i in range((n // 2))]) return S.loop_type(S.apply_permutation(self)) def shifted_concatenation(self, other, side='right'): '\n Return the right (or left) shifted concatenation of ``self``\n with a permutation ``other``. These operations are also known\n as the Loday-Ronco over and under operations.\n\n INPUT:\n\n - ``other`` -- a permutation, a list, a tuple, or any iterable\n representing a permutation.\n\n - ``side`` -- (default: ``"right"``) the string "left" or "right".\n\n OUTPUT:\n\n If ``side`` is ``"right"``, the method returns the permutation\n obtained by concatenating ``self`` with the letters of ``other``\n incremented by the size of ``self``. This is what is called\n ``side / other`` in [LR0102066]_, and denoted as the "over"\n operation.\n Otherwise, i. e., when ``side`` is ``"left"``, the method\n returns the permutation obtained by concatenating the letters\n of ``other`` incremented by the size of ``self`` with ``self``.\n This is what is called ``side \\ other`` in [LR0102066]_\n (which seems to use the `(\\sigma \\pi)(i) = \\pi(\\sigma(i))`\n convention for the product of permutations).\n\n EXAMPLES::\n\n sage: Permutation([]).shifted_concatenation(Permutation([]), "right")\n []\n sage: Permutation([]).shifted_concatenation(Permutation([]), "left")\n []\n sage: Permutation([2, 4, 1, 3]).shifted_concatenation(Permutation([3, 1, 2]), "right")\n [2, 4, 1, 3, 7, 5, 6]\n sage: Permutation([2, 4, 1, 3]).shifted_concatenation(Permutation([3, 1, 2]), "left")\n [7, 5, 6, 2, 4, 1, 3]\n ' if (side == 'right'): return Permutations()((list(self) + [(a + len(self)) for a in other])) elif (side == 'left'): return Permutations()(([(a + len(self)) for a in other] + list(self))) else: raise ValueError(('%s must be "left" or "right"' % side)) def shifted_shuffle(self, other): '\n Return the shifted shuffle of two permutations ``self`` and ``other``.\n\n INPUT:\n\n - ``other`` -- a permutation, a list, a tuple, or any iterable\n representing a permutation.\n\n OUTPUT:\n\n The list of the permutations appearing in the shifted\n shuffle of the permutations ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: Permutation([]).shifted_shuffle(Permutation([]))\n [[]]\n sage: Permutation([1, 2, 3]).shifted_shuffle(Permutation([1]))\n [[4, 1, 2, 3], [1, 2, 3, 4], [1, 2, 4, 3], [1, 4, 2, 3]]\n sage: Permutation([1, 2]).shifted_shuffle(Permutation([2, 1]))\n [[4, 1, 3, 2], [4, 3, 1, 2], [1, 4, 3, 2],\n [1, 4, 2, 3], [1, 2, 4, 3], [4, 1, 2, 3]]\n sage: Permutation([1]).shifted_shuffle([1])\n [[2, 1], [1, 2]]\n sage: p = Permutation([3, 1, 5, 4, 2])\n sage: len(p.shifted_shuffle(Permutation([2, 1, 4, 3])))\n 126\n\n The shifted shuffle product is associative. We can test this on an\n admittedly toy example::\n\n sage: all( all( all( sorted(flatten([abs.shifted_shuffle(c) # needs sage.graphs sage.modules\n ....: for abs in a.shifted_shuffle(b)]))\n ....: == sorted(flatten([a.shifted_shuffle(bcs)\n ....: for bcs in b.shifted_shuffle(c)]))\n ....: for c in Permutations(2) )\n ....: for b in Permutations(2) )\n ....: for a in Permutations(2) )\n True\n\n The ``shifted_shuffle`` method on permutations gives the same\n permutations as the ``shifted_shuffle`` method on words (but is\n faster)::\n\n sage: all( all( sorted(p1.shifted_shuffle(p2)) # needs sage.combinat sage.graphs sage.modules sage.rings.finite_rings\n ....: == sorted([Permutation(p) for p in\n ....: Word(p1).shifted_shuffle(Word(p2))])\n ....: for p2 in Permutations(3) )\n ....: for p1 in Permutations(2) )\n True\n ' return self.shifted_concatenation(other, 'right').right_permutohedron_interval(self.shifted_concatenation(other, 'left')) def nth_roots(self, n): "\n Return all n-th roots of ``self`` (as a generator).\n\n An n-th root of the permutation `\\sigma` is a permutation `\\gamma` such that `\\gamma^n = \\sigma`.\n\n Note that the number of n-th roots only depends on the cycle type of ``self``.\n\n EXAMPLES::\n\n sage: sigma = Permutations(5).identity()\n sage: list(sigma.nth_roots(3))\n [[1, 4, 3, 5, 2], [1, 5, 3, 2, 4], [1, 2, 4, 5, 3], [1, 2, 5, 3, 4], [4, 2, 3, 5, 1], [5, 2, 3, 1, 4], [3, 2, 5, 4, 1],\n [5, 2, 1, 4, 3], [2, 5, 3, 4, 1], [5, 1, 3, 4, 2], [2, 3, 1, 4, 5], [3, 1, 2, 4, 5], [2, 4, 3, 1, 5], [4, 1, 3, 2, 5],\n [3, 2, 4, 1, 5], [4, 2, 1, 3, 5], [1, 3, 4, 2, 5], [1, 4, 2, 3, 5], [1, 3, 5, 4, 2], [1, 5, 2, 4, 3], [1, 2, 3, 4, 5]]\n\n sage: sigma = Permutation('(1, 3)')\n sage: list(sigma.nth_roots(2))\n []\n\n For n >= 6, this algorithm begins to be more efficient than naive search\n (look at all permutations and test their n-th power).\n\n .. SEEALSO::\n\n * :meth:`has_nth_root`\n * :meth:`number_of_nth_roots`\n\n TESTS:\n\n We compute the number of square roots of the identity (i.e. involutions in `S_n`, :oeis:`A000085`)::\n\n sage: [len(list(Permutations(n).identity().nth_roots(2))) for n in range(2,8)]\n [2, 4, 10, 26, 76, 232]\n\n sage: list(Permutation('(1)').nth_roots(2))\n [[1]]\n\n sage: list(Permutation('').nth_roots(2))\n [[]]\n\n sage: sigma = Permutations(6).random_element()\n sage: list(sigma.nth_roots(1)) == [sigma]\n True\n\n sage: list(Permutations(4).identity().nth_roots(-1))\n Traceback (most recent call last):\n ...\n ValueError: n must be at least 1\n " from sage.combinat.partition import Partitions from sage.combinat.set_partition import SetPartitions from itertools import product from sage.arith.misc import divisors, gcd def merging_cycles(list_of_cycles): "\n Generate all l-cycles such that its n-th power is the product\n of cycles in 'cycles' (which contains gcd(l, n) cycles of length l/gcd(l, n))\n " lC = len(list_of_cycles) lperm = len(list_of_cycles[0]) l = (lC * lperm) perm = ([0] * l) for j in range(lperm): perm[(j * lC)] = list_of_cycles[0][j] for p in Permutations((lC - 1)): for indices in product(*[range(lperm) for _ in range((lC - 1))]): new_perm = list(perm) for i in range((lC - 1)): for j in range(lperm): new_perm[((p[i] + ((indices[i] + j) * lC)) % l)] = list_of_cycles[(i + 1)][j] (yield Permutation(tuple(new_perm))) def rewind(L, n): '\n Construct the list M such that ``M[(j * n) % len(M)] == L[j]``.\n ' M = ([0] * len(L)) m = len(M) for j in range(m): M[((j * n) % m)] = L[j] return M if (n < 1): raise ValueError('n must be at least 1') P = Permutations(self.size()) cycles = {} for c in self.cycle_tuples(singletons=True): lc = len(c) if (lc not in cycles): cycles[lc] = [] cycles[lc].append(c) possibilities = [[] for m in cycles] for (i, m) in enumerate(cycles): N = len(cycles[m]) parts = [x for x in divisors(n) if (gcd((m * x), n) == x)] b = False for X in Partitions(N, parts_in=parts): for partition in SetPartitions(N, X): b = True poss = [P.identity()] for pa in partition: poss = [(p * q) for p in poss for q in merging_cycles([rewind(cycles[m][(i - 1)], (n // len(pa))) for i in pa])] possibilities[i] += poss if (not b): return for L in product(*possibilities): (yield P.prod(L)) def has_nth_root(self, n) -> bool: "\n Decide if ``self`` has n-th roots.\n\n An n-th root of the permutation `\\sigma` is a permutation `\\gamma` such that `\\gamma^n = \\sigma`.\n\n Note that the number of n-th roots only depends on the cycle type of ``self``.\n\n EXAMPLES::\n\n sage: sigma = Permutations(5).identity()\n sage: sigma.has_nth_root(3)\n True\n\n sage: sigma = Permutation('(1, 3)')\n sage: sigma.has_nth_root(2)\n False\n\n .. SEEALSO::\n\n * :meth:`nth_roots`\n * :meth:`number_of_nth_roots`\n\n TESTS:\n\n We compute the number of permutations that have square roots (i.e. squares in `S_n`, :oeis:`A003483`)::\n\n sage: [len([p for p in Permutations(n) if p.has_nth_root(2)]) for n in range(2, 7)]\n [1, 3, 12, 60, 270]\n\n sage: Permutation('(1)').has_nth_root(2)\n True\n\n sage: Permutation('').has_nth_root(2)\n True\n\n sage: sigma = Permutations(6).random_element()\n sage: sigma.has_nth_root(1)\n True\n\n sage: Permutations(4).identity().has_nth_root(-1)\n Traceback (most recent call last):\n ...\n ValueError: n must be at least 1\n " from sage.combinat.partition import Partitions from sage.arith.misc import divisors, gcd if (n < 1): raise ValueError('n must be at least 1') cycles = self.cycle_type().to_exp_dict() for (m, N) in cycles.items(): parts = [x for x in divisors(n) if (gcd((m * x), n) == x)] if Partitions(N, parts_in=parts).is_empty(): return False return True def number_of_nth_roots(self, n): "\n Return the number of n-th roots of ``self``.\n\n An n-th root of the permutation `\\sigma` is a permutation `\\gamma` such that `\\gamma^n = \\sigma`.\n\n Note that the number of n-th roots only depends on the cycle type of ``self``.\n\n EXAMPLES::\n\n sage: Sigma = Permutations(5).identity()\n sage: Sigma.number_of_nth_roots(3)\n 21\n\n sage: Sigma = Permutation('(1, 3)')\n sage: Sigma.number_of_nth_roots(2)\n 0\n\n .. SEEALSO::\n\n * :meth:`nth_roots`\n * :meth:`has_nth_root`\n\n TESTS:\n\n We compute the number of square roots of the identity (i.e. involutions in `S_n`, :oeis:`A000085`), then the number of cubic roots::\n\n sage: [Permutations(n).identity().number_of_nth_roots(2) for n in range(2, 10)]\n [2, 4, 10, 26, 76, 232, 764, 2620]\n\n sage: [Permutations(n).identity().number_of_nth_roots(3) for n in range(2, 10)]\n [1, 3, 9, 21, 81, 351, 1233, 5769]\n\n sage: Permutation('(1)').number_of_nth_roots(2)\n 1\n\n sage: Permutation('').number_of_nth_roots(2)\n 1\n\n sage: Sigma = Permutations(6).random_element()\n sage: Sigma.number_of_nth_roots(1)\n 1\n\n sage: Permutations(4).identity().number_of_nth_roots(-1)\n Traceback (most recent call last):\n ...\n ValueError: n must be at least 1\n " from sage.combinat.partition import Partitions from sage.combinat.set_partition import SetPartitions from sage.arith.misc import divisors, gcd from sage.misc.misc_c import prod if (n < 1): raise ValueError('n must be at least 1') cycles = self.cycle_type().to_exp_dict() result = 1 for (m, N) in cycles.items(): parts = [x for x in divisors(n) if (gcd((m * x), n) == x)] result *= sum(((SetPartitions(N, pa).cardinality() * prod(((factorial((x - 1)) * (m ** (x - 1))) for x in pa))) for pa in Partitions(N, parts_in=parts))) if (not result): return 0 return result
def _tableau_contribution(T): '\n Get the number of SYT of shape(``T``).\n\n EXAMPLES::\n\n sage: T = Tableau([[1,1,1],[2]]) # needs sage.combinat\n sage: from sage.combinat.permutation import _tableau_contribution\n sage: _tableau_contribution(T) # needs sage.combinat\n 3\n ' from sage.combinat.tableau import StandardTableaux return StandardTableaux(T.shape()).cardinality()
class Permutations(UniqueRepresentation, Parent): "\n Permutations.\n\n ``Permutations(n)`` returns the class of permutations of ``n``, if ``n``\n is an integer, list, set, or string.\n\n ``Permutations(n, k)`` returns the class of length-``k`` partial\n permutations of ``n`` (where ``n`` is any of the above things); ``k``\n must be a nonnegative integer. A length-`k` partial permutation of `n`\n is defined as a `k`-tuple of pairwise distinct elements of\n `\\{ 1, 2, \\ldots, n \\}`.\n\n Valid keyword arguments are: 'descents', 'bruhat_smaller',\n 'bruhat_greater', 'recoils_finer', 'recoils_fatter', 'recoils',\n and 'avoiding'. With the exception of 'avoiding', you cannot\n specify ``n`` or ``k`` along with a keyword.\n\n ``Permutations(descents=(list,n))`` returns the class of permutations of\n `n` with descents in the positions specified by ``list``. This uses the\n slightly nonstandard convention that the images of `1,2,...,n` under the\n permutation are regarded as positions `0,1,...,n-1`, so for example the\n presence of `1` in ``list`` signifies that the permutations `\\pi` should\n satisfy `\\pi(2) > \\pi(3)`.\n Note that ``list`` is supposed to be a list of positions of the descents,\n not the descents composition. It does *not* return the class of\n permutations with descents composition ``list``.\n\n ``Permutations(bruhat_smaller=p)`` and ``Permutations(bruhat_greater=p)``\n return the class of permutations smaller-or-equal or greater-or-equal,\n respectively, than the given permutation ``p`` in the Bruhat order.\n (The Bruhat order is defined in\n :meth:`~sage.combinat.permutation.Permutation.bruhat_lequal`.\n It is also referred to as the *strong* Bruhat order.)\n\n ``Permutations(recoils=p)`` returns the class of permutations whose\n recoils composition is ``p``. Unlike the ``descents=(list, n)`` syntax,\n this actually takes a *composition* as input.\n\n ``Permutations(recoils_fatter=p)`` and ``Permutations(recoils_finer=p)``\n return the class of permutations whose recoils composition is fatter or\n finer, respectively, than the given composition ``p``.\n\n ``Permutations(n, avoiding=P)`` returns the class of permutations of ``n``\n avoiding ``P``. Here ``P`` may be a single permutation or a list of\n permutations; the returned class will avoid all patterns in ``P``.\n\n EXAMPLES::\n\n sage: p = Permutations(3); p\n Standard permutations of 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\n ::\n\n sage: p = Permutations(3, 2); p\n Permutations of {1,...,3} of length 2\n sage: p.list()\n [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]\n\n ::\n\n sage: p = Permutations(['c', 'a', 't']); p\n Permutations of the set ['c', 'a', 't']\n sage: p.list()\n [['c', 'a', 't'],\n ['c', 't', 'a'],\n ['a', 'c', 't'],\n ['a', 't', 'c'],\n ['t', 'c', 'a'],\n ['t', 'a', 'c']]\n\n ::\n\n sage: p = Permutations(['c', 'a', 't'], 2); p\n Permutations of the set ['c', 'a', 't'] of length 2\n sage: p.list()\n [['c', 'a'], ['c', 't'], ['a', 'c'], ['a', 't'], ['t', 'c'], ['t', 'a']]\n\n ::\n\n sage: p = Permutations([1,1,2]); p\n Permutations of the multi-set [1, 1, 2]\n sage: p.list()\n [[1, 1, 2], [1, 2, 1], [2, 1, 1]]\n\n ::\n\n sage: p = Permutations([1,1,2], 2); p\n Permutations of the multi-set [1, 1, 2] of length 2\n sage: p.list() # needs sage.libs.gap\n [[1, 1], [1, 2], [2, 1]]\n\n ::\n\n sage: p = Permutations(descents=([1], 4)); p\n Standard permutations of 4 with descents [1]\n sage: p.list() # needs sage.graphs sage.modules\n [[2, 4, 1, 3], [3, 4, 1, 2], [1, 4, 2, 3], [1, 3, 2, 4], [2, 3, 1, 4]]\n\n ::\n\n sage: p = Permutations(bruhat_smaller=[1,3,2,4]); p\n Standard permutations that are less than or equal\n to [1, 3, 2, 4] in the Bruhat order\n sage: p.list()\n [[1, 2, 3, 4], [1, 3, 2, 4]]\n\n ::\n\n sage: p = Permutations(bruhat_greater=[4,2,3,1]); p\n Standard permutations that are greater than or equal\n to [4, 2, 3, 1] in the Bruhat order\n sage: p.list()\n [[4, 2, 3, 1], [4, 3, 2, 1]]\n\n ::\n\n sage: p = Permutations(recoils_finer=[2,1]); p\n Standard permutations whose recoils composition is finer than [2, 1]\n sage: p.list() # needs sage.graphs sage.modules\n [[3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\n ::\n\n sage: p = Permutations(recoils_fatter=[2,1]); p\n Standard permutations whose recoils composition is fatter than [2, 1]\n sage: p.list() # needs sage.graphs sage.modules\n [[3, 1, 2], [3, 2, 1], [1, 3, 2]]\n\n ::\n\n sage: p = Permutations(recoils=[2,1]); p\n Standard permutations whose recoils composition is [2, 1]\n sage: p.list() # needs sage.graphs sage.modules\n [[3, 1, 2], [1, 3, 2]]\n\n ::\n\n sage: p = Permutations(4, avoiding=[1,3,2]); p\n Standard permutations of 4 avoiding [[1, 3, 2]]\n sage: p.list()\n [[4, 1, 2, 3],\n [4, 2, 1, 3],\n [4, 2, 3, 1],\n [4, 3, 1, 2],\n [4, 3, 2, 1],\n [3, 4, 1, 2],\n [3, 4, 2, 1],\n [2, 3, 4, 1],\n [3, 2, 4, 1],\n [1, 2, 3, 4],\n [2, 1, 3, 4],\n [2, 3, 1, 4],\n [3, 1, 2, 4],\n [3, 2, 1, 4]]\n\n ::\n\n sage: p = Permutations(5, avoiding=[[3,4,1,2], [4,2,3,1]]); p\n Standard permutations of 5 avoiding [[3, 4, 1, 2], [4, 2, 3, 1]]\n sage: p.cardinality() # needs sage.combinat\n 88\n sage: p.random_element().parent() is p # needs sage.combinat\n True\n " @staticmethod def __classcall_private__(cls, n=None, k=None, **kwargs): '\n Return the correct parent based upon input.\n\n EXAMPLES::\n\n sage: Permutations()\n Standard permutations\n sage: Permutations(5, 3)\n Permutations of {1,...,5} of length 3\n sage: Permutations([1,2,3,4,6])\n Permutations of the set [1, 2, 3, 4, 6]\n sage: Permutations([1,2,3,4,5])\n Standard permutations of 5\n ' valid_args = ['descents', 'bruhat_smaller', 'bruhat_greater', 'recoils_finer', 'recoils_fatter', 'recoils', 'avoiding'] number_of_arguments = 0 if (n is not None): number_of_arguments += 1 elif (k is not None): number_of_arguments += 1 for key in kwargs: if (key not in valid_args): raise ValueError(('unknown keyword argument: %s' % key)) if (key not in ['avoiding']): number_of_arguments += 1 if (number_of_arguments == 0): if ('avoiding' in kwargs): a = kwargs['avoiding'] if (len(a) == 0): return StandardPermutations_all() if (a in StandardPermutations_all()): a = (a,) return StandardPermutations_all_avoiding(a) return StandardPermutations_all() if (number_of_arguments != 1): raise ValueError('you must specify exactly one argument') if (n is not None): if isinstance(n, (int, Integer)): if (k is None): if ('avoiding' in kwargs): a = kwargs['avoiding'] if (not a): return StandardPermutations_n(n) if ((len(a) == 1) and (a[0] != 1)): a = a[0] if (a in StandardPermutations_all()): if (a == [1, 2]): return StandardPermutations_avoiding_12(n) elif (a == [2, 1]): return StandardPermutations_avoiding_21(n) elif (a == [1, 2, 3]): return StandardPermutations_avoiding_123(n) elif (a == [1, 3, 2]): return StandardPermutations_avoiding_132(n) elif (a == [2, 1, 3]): return StandardPermutations_avoiding_213(n) elif (a == [2, 3, 1]): return StandardPermutations_avoiding_231(n) elif (a == [3, 1, 2]): return StandardPermutations_avoiding_312(n) elif (a == [3, 2, 1]): return StandardPermutations_avoiding_321(n) else: return StandardPermutations_avoiding_generic(n, (a,)) elif isinstance(a, (list, tuple)): a = tuple(map(Permutation, a)) return StandardPermutations_avoiding_generic(n, a) else: raise ValueError(('do not know how to avoid %s' % a)) else: return StandardPermutations_n(n) else: return Permutations_nk(n, k) elif (len(set(n)) == len(n)): if (list(n) == list(range(1, (len(n) + 1)))): if (k is None): return StandardPermutations_n(len(n)) else: return Permutations_nk(len(n), k) elif (k is None): return Permutations_set(n) else: return Permutations_setk(n, k) elif (k is None): return Permutations_mset(n) else: return Permutations_msetk(n, k) elif ('descents' in kwargs): if isinstance(kwargs['descents'], tuple): args = kwargs['descents'] return StandardPermutations_descents(tuple(args[0]), args[1]) else: return StandardPermutations_descents(kwargs['descents']) elif ('bruhat_smaller' in kwargs): return StandardPermutations_bruhat_smaller(Permutation(kwargs['bruhat_smaller'])) elif ('bruhat_greater' in kwargs): return StandardPermutations_bruhat_greater(Permutation(kwargs['bruhat_greater'])) elif ('recoils_finer' in kwargs): return StandardPermutations_recoilsfiner(Composition(kwargs['recoils_finer'])) elif ('recoils_fatter' in kwargs): return StandardPermutations_recoilsfatter(Composition(kwargs['recoils_fatter'])) elif ('recoils' in kwargs): return StandardPermutations_recoils(Composition(kwargs['recoils'])) Element = Permutation class options(GlobalOptions): "\n Set the global options for elements of the permutation class. The\n defaults are for permutations to be displayed in list notation and\n the multiplication done from left to right (like in GAP) -- that\n is, `(\\pi \\psi)(i) = \\psi(\\pi(i))` for all `i`.\n\n .. NOTE::\n\n These options have no effect on permutation group elements.\n\n @OPTIONS@\n\n EXAMPLES::\n\n sage: p213 = Permutation([2,1,3])\n sage: p312 = Permutation([3,1,2])\n sage: Permutations.options(mult='l2r', display='list')\n sage: Permutations.options.display\n list\n sage: p213\n [2, 1, 3]\n sage: Permutations.options.display='cycle'\n sage: p213\n (1,2)\n sage: Permutations.options.display='singleton'\n sage: p213\n (1,2)(3)\n sage: Permutations.options.display='list'\n\n ::\n\n sage: Permutations.options.mult\n l2r\n sage: p213*p312\n [1, 3, 2]\n sage: Permutations.options.mult='r2l'\n sage: p213*p312\n [3, 2, 1]\n sage: Permutations.options._reset()\n " NAME = 'Permutations' module = 'sage.combinat.permutation' display = dict(default='list', description='Specifies how the permutations should be printed', values=dict(list='the permutations are displayed in list notation (aka 1-line notation)', cycle='the permutations are displayed in cycle notation (i. e., as products of disjoint cycles)', singleton='the permutations are displayed in cycle notation with singleton cycles shown as well', reduced_word='the permutations are displayed as reduced words'), alias=dict(word='reduced_word', reduced_expression='reduced_word'), case_sensitive=False) latex = dict(default='list', description='Specifies how the permutations should be latexed', values=dict(list='latex as a list in one-line notation', twoline='latex in two-line notation', cycle='latex in cycle notation', singleton='latex in cycle notation with singleton cycles shown as well', reduced_word='latex as reduced words'), alias=dict(word='reduced_word', reduced_expression='reduced_word', oneline='list'), case_sensitive=False) latex_empty_str = dict(default='1', description='The LaTeX representation of a reduced word when said word is empty', checker=(lambda char: isinstance(char, str))) generator_name = dict(default='s', description='the letter used in latexing the reduced word', checker=(lambda char: isinstance(char, str))) mult = dict(default='l2r', description='The multiplication of permutations', values=dict(l2r='left to right: `(p_1 \\cdot p_2)(x) = p_2(p_1(x))`', r2l='right to left: `(p_1 \\cdot p_2)(x) = p_1(p_2(x))`'), case_sensitive=False)
class Permutations_nk(Permutations): '\n Length-`k` partial permutations of `\\{1, 2, \\ldots, n\\}`.\n ' def __init__(self, n, k): '\n TESTS::\n\n sage: P = Permutations(3,2)\n sage: TestSuite(P).run()\n ' self.n = ZZ(n) self._k = ZZ(k) Permutations.__init__(self, category=FiniteEnumeratedSets()) class Element(ClonableArray): '\n A length-`k` partial permutation of `[n]`.\n ' def check(self): '\n Verify that ``self`` is a valid length-`k` partial\n permutation of `[n]`.\n\n EXAMPLES::\n\n sage: S = Permutations(4, 2)\n sage: elt = S([3, 1])\n sage: elt.check()\n ' if (self not in self.parent()): raise ValueError('Invalid permutation') def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: [1,2] in Permutations(3,2)\n True\n sage: [1,1] in Permutations(3,2)\n False\n sage: [3,2,1] in Permutations(3,2)\n False\n sage: [3,1] in Permutations(3,2)\n True\n ' if (len(x) != self._k): return False r = list(range(1, (self.n + 1))) for i in x: if (i in r): r.remove(i) else: return False return True def _repr_(self) -> str: '\n TESTS::\n\n sage: Permutations(3,2)\n Permutations of {1,...,3} of length 2\n ' return ('Permutations of {1,...,%s} of length %s' % (self.n, self._k)) def __iter__(self) -> Iterator[Permutation]: '\n EXAMPLES::\n\n sage: [p for p in Permutations(3,2)]\n [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]\n sage: [p for p in Permutations(3,0)]\n [[]]\n sage: [p for p in Permutations(3,4)]\n []\n ' for x in itertools.permutations(range(1, (self.n + 1)), int(self._k)): (yield self.element_class(self, x, check=False)) def cardinality(self) -> Integer: '\n EXAMPLES::\n\n sage: Permutations(3,0).cardinality()\n 1\n sage: Permutations(3,1).cardinality()\n 3\n sage: Permutations(3,2).cardinality()\n 6\n sage: Permutations(3,3).cardinality()\n 6\n sage: Permutations(3,4).cardinality()\n 0\n ' if (0 <= self._k <= self.n): return (factorial(self.n) // factorial((self.n - self._k))) return ZZ.zero() def random_element(self): '\n EXAMPLES::\n\n sage: s = Permutations(3,2).random_element()\n sage: s in Permutations(3,2)\n True\n ' return sample(range(1, (self.n + 1)), self._k)
class Permutations_mset(Permutations): '\n Permutations of a multiset `M`.\n\n A permutation of a multiset `M` is represented by a list that\n contains exactly the same elements as `M` (with the same\n multiplicities), but possibly in different order. If `M` is\n a proper set there are `|M| !` such permutations.\n Otherwise, if the first element appears `k_1` times, the\n second element appears `k_2` times and so on, the number\n of permutations is `|M|! / (k_1! k_2! \\ldots)`, which\n is sometimes called a multinomial coefficient.\n\n EXAMPLES::\n\n sage: mset = [1,1,2,2,2]\n sage: from sage.combinat.permutation import Permutations_mset\n sage: P = Permutations_mset(mset); P\n Permutations of the multi-set [1, 1, 2, 2, 2]\n sage: sorted(P)\n [[1, 1, 2, 2, 2],\n [1, 2, 1, 2, 2],\n [1, 2, 2, 1, 2],\n [1, 2, 2, 2, 1],\n [2, 1, 1, 2, 2],\n [2, 1, 2, 1, 2],\n [2, 1, 2, 2, 1],\n [2, 2, 1, 1, 2],\n [2, 2, 1, 2, 1],\n [2, 2, 2, 1, 1]]\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(GF(2), 2, 2)\n sage: A = MS([1,0,1,1])\n sage: rows = A.rows()\n sage: rows[0].set_immutable()\n sage: rows[1].set_immutable()\n sage: P = Permutations_mset(rows); P\n Permutations of the multi-set [(1, 0), (1, 1)]\n sage: sorted(P)\n [[(1, 0), (1, 1)], [(1, 1), (1, 0)]]\n ' @staticmethod def __classcall_private__(cls, mset): "\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(['c','a','c'])\n sage: S2 = Permutations(('c','a','c'))\n sage: S1 is S2\n True\n " return super().__classcall__(cls, tuple(mset)) def __init__(self, mset): "\n TESTS::\n\n sage: S = Permutations(['c','a','c'])\n sage: TestSuite(S).run()\n " self.mset = mset Permutations.__init__(self, category=FiniteEnumeratedSets()) def __contains__(self, x) -> bool: '\n EXAMPLES::\n\n sage: p = Permutations([1,2,2])\n sage: [1,2,2] in p\n True\n sage: [] in p\n False\n sage: [2,2] in p\n False\n sage: [1,1] in p\n False\n sage: [2,1] in p\n False\n sage: [2,1,2] in p\n True\n ' s = list(self.mset) if (len(x) != len(s)): return False for i in x: if (i in s): s.remove(i) else: return False return True class Element(ClonableArray): '\n A permutation of an arbitrary multiset.\n ' def check(self): "\n Verify that ``self`` is a valid permutation of the underlying\n multiset.\n\n EXAMPLES::\n\n sage: S = Permutations(['c','a','c'])\n sage: elt = S(['c','c','a'])\n sage: elt.check()\n " if (self not in self.parent()): raise ValueError('Invalid permutation') def _repr_(self) -> str: "\n TESTS::\n\n sage: Permutations(['c','a','c'])\n Permutations of the multi-set ['c', 'a', 'c']\n " return ('Permutations of the multi-set %s' % list(self.mset)) def __iter__(self): "\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: [ p for p in Permutations(['c','t','t'])] # indirect doctest\n [['c', 't', 't'], ['t', 'c', 't'], ['t', 't', 'c']]\n\n TESTS:\n\n The empty multiset::\n\n sage: list(sage.combinat.permutation.Permutations_mset([]))\n [[]]\n " mset = self.mset n = len(mset) from array import array mset_list = array('I', sorted((mset.index(x) for x in mset))) (yield self.element_class(self, map_to_list(mset_list, mset, n), check=False)) if (n <= 1): return while next_perm(mset_list): (yield self.element_class(self, map_to_list(mset_list, mset, n), check=False)) def cardinality(self): '\n Return the cardinality of the set.\n\n EXAMPLES::\n\n sage: Permutations([1,2,2]).cardinality()\n 3\n sage: Permutations([1,1,2,2,2]).cardinality()\n 10\n ' lmset = list(self.mset) mset_list = [lmset.index(x) for x in lmset] d = {} for i in mset_list: d[i] = (d.get(i, 0) + 1) return ZZ(multinomial(d.values())) def rank(self, p): '\n Return the rank of ``p`` in lexicographic order.\n\n INPUT:\n\n - ``p`` -- a permutation of `M`\n\n ALGORITHM:\n\n The algorithm uses the recurrence from the solution to exercise 4 in\n [Knu2011]_, Section 7.2.1.2:\n\n .. MATH::\n\n \\mathrm{rank}(p_1 \\ldots p_n) =\n \\mathrm{rank}(p_2 \\ldots p_n)\n + \\frac{1}{n} \\genfrac{(}{)}{0pt}{0}{n}{n_1, \\ldots, n_t}\n \\sum_{j=1}^t n_j \\left[ x_j < p_1 \\right],\n\n where `x_j, n_j` are the distinct elements of `p` with their\n multiplicities, `n` is the sum of `n_1, \\ldots, n_t`,\n `\\genfrac{(}{)}{0pt}{1}{n}{n_1, \\ldots, n_t}` is the multinomial\n coefficient `\\frac{n!}{n_1! \\ldots n_t!}`, and\n `\\sum_{j=1}^t n_j \\left[ x_j < p_1 \\right]` means "the number of\n elements to the right of the first element that are less than the first\n element".\n\n EXAMPLES::\n\n sage: mset = [1, 1, 2, 3, 4, 5, 5, 6, 9]\n sage: p = Permutations(mset)\n sage: p.rank(list(sorted(mset)))\n 0\n sage: p.rank(list(reversed(sorted(mset)))) == p.cardinality() - 1\n True\n sage: p.rank([3, 1, 4, 1, 5, 9, 2, 6, 5])\n 30991\n\n TESTS::\n\n sage: from sage.combinat.permutation import Permutations_mset\n sage: p = Permutations_mset([])\n sage: p.rank([])\n 0\n sage: p = Permutations_mset([1, 1, 2, 3, 4, 5, 5, 6, 9])\n sage: p.rank([1, 2, 3, 4, 5, 6, 9])\n Traceback (most recent call last):\n ...\n ValueError: Invalid permutation\n\n Try with greater-than-unity multiplicity in the least and greatest\n elements::\n\n sage: mset = list(range(10)) * 3\n sage: p = Permutations_mset(mset)\n sage: p.rank(list(sorted(mset)))\n 0\n sage: p.rank(list(reversed(sorted(mset))))\n 4386797336285844479999999\n sage: p.cardinality()\n 4386797336285844480000000\n\n Should match ``StandardPermutations_n`` when `M` is the set\n `\\{1, 2, \\ldots, n\\}`::\n\n sage: ps = Permutations(4)\n sage: pm = Permutations_mset(list(range(1, 5)))\n sage: ps.rank([2, 3, 1, 4]) == pm.rank([2, 3, 1, 4])\n True\n ' self(p).check() m = {} r = 0 for n in range(1, (len(p) + 1)): p1 = p[(- n)] m[p1] = (m.get(p1, 0) + 1) r += ((multinomial(m.values()) * sum((nj for (xj, nj) in m.items() if (xj < p1)))) // n) return r def unrank(self, r): '\n Return the permutation of `M` having lexicographic rank ``r``.\n\n INPUT:\n\n - ``r`` -- an integer between ``0`` and ``self.cardinality()-1``\n inclusive\n\n ALGORITHM:\n\n The algorithm is adapted from the solution to exercise 4 in [Knu2011]_,\n Section 7.2.1.2.\n\n EXAMPLES::\n\n sage: mset = [1, 1, 2, 3, 4, 5, 5, 6, 9]\n sage: p = Permutations(mset)\n sage: p.unrank(30991)\n [3, 1, 4, 1, 5, 9, 2, 6, 5]\n sage: p.rank(p.unrank(10))\n 10\n sage: p.unrank(0) == list(sorted(mset))\n True\n sage: p.unrank(p.cardinality()-1) == list(reversed(sorted(mset)))\n True\n\n TESTS::\n\n sage: from sage.combinat.permutation import Permutations_mset\n sage: p = Permutations_mset([])\n sage: p.unrank(0)\n []\n sage: p.unrank(1)\n Traceback (most recent call last):\n ...\n ValueError: r must be between 0 and 0 inclusive\n sage: p = Permutations_mset([1, 1, 2, 3, 4, 5, 5, 6, 9])\n sage: p.unrank(-1)\n Traceback (most recent call last):\n ...\n ValueError: r must be between 0 and 90719 inclusive\n sage: p.unrank(p.cardinality())\n Traceback (most recent call last):\n ...\n ValueError: r must be between 0 and 90719 inclusive\n\n Try with a cardinality that exceeds the precise integer range of a\n float::\n\n sage: mset = list(range(10)) * 3\n sage: p = Permutations_mset(mset)\n sage: p.unrank(p.rank(mset)) == mset\n True\n sage: p.unrank(p.cardinality()-1) == list(reversed(sorted(mset)))\n True\n\n Exhaustive check of roundtrip and lexicographic order for a single\n multiset::\n\n sage: p = Permutations_mset([2, 2, 3, 3, 3, 5, 5, 5, 5, 5])\n sage: prev = None\n sage: for rank, perm in enumerate(p):\n ....: perm = tuple(perm)\n ....: assert p.rank(perm) == rank, (rank, perm, p.rank(perm))\n ....: assert tuple(p.unrank(rank)) == perm, (rank, perm, p.unrank(rank))\n ....: assert prev is None or prev < perm\n ....: prev = perm\n\n Should match ``StandardPermutations_n`` when `M` is the set\n `\\{1, 2, \\ldots, n\\}`::\n\n sage: ps = Permutations(4)\n sage: pm = Permutations_mset(list(range(1, 5)))\n sage: ps.unrank(5) == pm.unrank(5)\n True\n ' range_error = ValueError(('r must be between %d and %d inclusive' % (0, (self.cardinality() - 1)))) if (r < 0): raise range_error mset = list(sorted(self.mset)) m = {} for x in mset: m[x] = (m.get(x, 0) + 1) from bisect import bisect_left p = [] while mset: n = len(mset) mult = multinomial(m.values()) ti = ((r * n) // mult) if (ti >= n): raise range_error ci = bisect_left(mset, mset[ti], max(0, ((ti + 1) - m[mset[ti]])), (ti + 1)) r -= ((ci * mult) // n) pi = mset.pop(ci) m[pi] -= 1 if (m[pi] == 0): del m[pi] p.append(pi) if (r > 0): raise range_error return p
class Permutations_set(Permutations): '\n Permutations of an arbitrary given finite set.\n\n Here, a "permutation of a finite set `S`" means a list of the\n elements of `S` in which every element of `S` occurs exactly\n once. This is not to be confused with bijections from `S` to\n `S`, which are also often called permutations in literature.\n ' @staticmethod def __classcall_private__(cls, s): "\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(['c','a','t'])\n sage: S2 = Permutations(('c','a','t'))\n sage: S1 is S2\n True\n " return super().__classcall__(cls, tuple(s)) def __init__(self, s): "\n TESTS::\n\n sage: S = Permutations(['c','a','t'])\n sage: TestSuite(S).run()\n " Permutations.__init__(self, category=FiniteEnumeratedSets()) self._set = s def __contains__(self, x) -> bool: "\n EXAMPLES::\n\n sage: p = Permutations([4,-1,'cthulhu'])\n sage: [4,-1,'cthulhu'] in p\n True\n sage: [] in p\n False\n sage: [4,'cthulhu','fhtagn'] in p\n False\n sage: [4,'cthulhu',4,-1] in p\n False\n sage: [-1,'cthulhu',4] in p\n True\n " s = list(self._set) if (len(x) != len(s)): return False for i in x: if (i in s): s.remove(i) else: return False return True def _repr_(self) -> str: "\n TESTS::\n\n sage: Permutations(['c','a','t'])\n Permutations of the set ['c', 'a', 't']\n " return ('Permutations of the set %s' % list(self._set)) class Element(ClonableArray): '\n A permutation of an arbitrary set.\n ' def check(self): "\n Verify that ``self`` is a valid permutation of the underlying\n set.\n\n EXAMPLES::\n\n sage: S = Permutations(['c','a','t'])\n sage: elt = S(['t','c','a'])\n sage: elt.check()\n " if (self not in self.parent()): raise ValueError('Invalid permutation') def __iter__(self) -> Iterator: "\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: S = Permutations(['c','a','t'])\n sage: S.list()\n [['c', 'a', 't'],\n ['c', 't', 'a'],\n ['a', 'c', 't'],\n ['a', 't', 'c'],\n ['t', 'c', 'a'],\n ['t', 'a', 'c']]\n " for p in itertools.permutations(self._set, len(self._set)): (yield self.element_class(self, p, check=False)) def cardinality(self) -> Integer: '\n Return the cardinality of the set.\n\n EXAMPLES::\n\n sage: Permutations([1,2,3]).cardinality()\n 6\n ' return factorial(len(self._set)) def random_element(self): '\n EXAMPLES::\n\n sage: s = Permutations([1,2,3]).random_element()\n sage: s.parent() is Permutations([1,2,3])\n True\n ' return sample(self._set, len(self._set))
class Permutations_msetk(Permutations_mset): '\n Length-`k` partial permutations of a multiset.\n\n A length-`k` partial permutation of a multiset `M` is\n represented by a list of length `k` whose entries are\n elements of `M`, appearing in the list with a multiplicity\n not higher than their respective multiplicity in `M`.\n ' @staticmethod def __classcall__(cls, mset, k): "\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(['c','a','c'], 2)\n sage: S2 = Permutations(('c','a','c'), 2)\n sage: S1 is S2\n True\n " return super().__classcall__(cls, tuple(mset), k) def __init__(self, mset, k): '\n TESTS::\n\n sage: P = Permutations([1,2,2],2)\n sage: TestSuite(P).run() # needs sage.libs.gap\n ' Permutations_mset.__init__(self, mset) self._k = k def __contains__(self, x): '\n EXAMPLES::\n\n sage: p = Permutations([1,2,2],2)\n sage: [1,2,2] in p\n False\n sage: [2,2] in p\n True\n sage: [1,1] in p\n False\n sage: [2,1] in p\n True\n ' if (len(x) != self._k): return False s = list(self.mset) for i in x: if (i in s): s.remove(i) else: return False return True def _repr_(self): '\n TESTS::\n\n sage: Permutations([1,2,2], 2)\n Permutations of the multi-set [1, 2, 2] of length 2\n ' return ('Permutations of the multi-set %s of length %s' % (list(self.mset), self._k)) def cardinality(self): '\n Return the cardinality of the set.\n\n EXAMPLES::\n\n sage: Permutations([1,2,2], 2).cardinality() # needs sage.libs.gap\n 3\n ' return ZZ.sum((1 for z in self)) def __iter__(self): '\n EXAMPLES::\n\n sage: Permutations([1,2,2], 2).list() # needs sage.libs.gap\n [[1, 2], [2, 1], [2, 2]]\n ' mset = self.mset lmset = list(mset) mset_list = [lmset.index(x) for x in lmset] indices = libgap.Arrangements(mset_list, self._k).sage() for ktuple in indices: (yield self.element_class(self, [lmset[x] for x in ktuple], check=False))
class Permutations_setk(Permutations_set): '\n Length-`k` partial permutations of an arbitrary given finite set.\n\n Here, a "length-`k` partial permutation of a finite set `S`" means\n a list of length `k` whose entries are pairwise distinct and all\n belong to `S`.\n ' @staticmethod def __classcall_private__(cls, s, k): "\n Normalize arguments to ensure a unique representation.\n\n TESTS::\n\n sage: S1 = Permutations(['c','a','t'], 2)\n sage: S2 = Permutations(('c','a','t'), 2)\n sage: S1 is S2\n True\n " return super().__classcall__(cls, tuple(s), k) def __init__(self, s, k): '\n TESTS::\n\n sage: P = Permutations([1,2,4],2)\n sage: TestSuite(P).run()\n ' Permutations_set.__init__(self, s) self._k = k def __contains__(self, x): '\n EXAMPLES::\n\n sage: p = Permutations([1,2,4],2)\n sage: [1,2,4] in p\n False\n sage: [2,2] in p\n False\n sage: [1,4] in p\n True\n sage: [2,1] in p\n True\n ' if (len(x) != self._k): return False s = list(self._set) return (all(((i in s) for i in x)) and (len(set(x)) == len(x))) def _repr_(self): "\n TESTS::\n\n sage: repr(Permutations([1,2,4],2))\n 'Permutations of the set [1, 2, 4] of length 2'\n " return ('Permutations of the set %s of length %s' % (list(self._set), self._k)) def __iter__(self): '\n EXAMPLES::\n\n sage: [i for i in Permutations([1,2,4],2)]\n [[1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2]]\n ' for perm in itertools.permutations(self._set, int(self._k)): (yield self.element_class(self, perm, check=False)) def random_element(self): '\n EXAMPLES::\n\n sage: s = Permutations([1,2,4], 2).random_element()\n sage: s in Permutations([1,2,4], 2)\n True\n ' return sample(self._set, self._k)
class Arrangements(Permutations): '\n An arrangement of a multiset ``mset`` is an ordered selection\n without repetitions. It is represented by a list that contains\n only elements from ``mset``, but maybe in a different order.\n\n ``Arrangements`` returns the combinatorial class of\n arrangements of the multiset ``mset`` that contain ``k`` elements.\n\n EXAMPLES::\n\n sage: mset = [1,1,2,3,4,4,5]\n sage: Arrangements(mset, 2).list() # needs sage.libs.gap\n [[1, 1],\n [1, 2],\n [1, 3],\n [1, 4],\n [1, 5],\n [2, 1],\n [2, 3],\n [2, 4],\n [2, 5],\n [3, 1],\n [3, 2],\n [3, 4],\n [3, 5],\n [4, 1],\n [4, 2],\n [4, 3],\n [4, 4],\n [4, 5],\n [5, 1],\n [5, 2],\n [5, 3],\n [5, 4]]\n sage: Arrangements(mset, 2).cardinality() # needs sage.libs.gap\n 22\n sage: Arrangements( ["c","a","t"], 2 ).list()\n [[\'c\', \'a\'], [\'c\', \'t\'], [\'a\', \'c\'], [\'a\', \'t\'], [\'t\', \'c\'], [\'t\', \'a\']]\n sage: Arrangements( ["c","a","t"], 3 ).list()\n [[\'c\', \'a\', \'t\'],\n [\'c\', \'t\', \'a\'],\n [\'a\', \'c\', \'t\'],\n [\'a\', \'t\', \'c\'],\n [\'t\', \'c\', \'a\'],\n [\'t\', \'a\', \'c\']]\n ' @staticmethod def __classcall_private__(cls, mset, k): '\n Return the correct parent.\n\n EXAMPLES::\n\n sage: A1 = Arrangements( ["c","a","t"], 2)\n sage: A2 = Arrangements( ("c","a","t"), 2)\n sage: A1 is A2\n True\n ' mset = tuple(mset) if ([mset.index(_) for _ in mset] == list(range(len(mset)))): return Arrangements_setk(mset, k) return Arrangements_msetk(mset, k) def cardinality(self): '\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: A = Arrangements([1,1,2,3,4,4,5], 2)\n sage: A.cardinality() # needs sage.libs.gap\n 22\n ' one = ZZ.one() return sum((one for p in self))
class Arrangements_msetk(Arrangements, Permutations_msetk): '\n Arrangements of length `k` of a multiset `M`.\n ' def _repr_(self): '\n TESTS::\n\n sage: Arrangements([1,2,2],2)\n Arrangements of the multi-set [1, 2, 2] of length 2\n ' return ('Arrangements of the multi-set %s of length %s' % (list(self.mset), self._k))
class Arrangements_setk(Arrangements, Permutations_setk): '\n Arrangements of length `k` of a set `S`.\n ' def _repr_(self): '\n TESTS::\n\n sage: Arrangements([1,2,3],2)\n Arrangements of the set [1, 2, 3] of length 2\n ' return ('Arrangements of the set %s of length %s' % (list(self._set), self._k))
class StandardPermutations_all(Permutations): '\n All standard permutations.\n ' def __init__(self): '\n TESTS::\n\n sage: SP = Permutations()\n sage: TestSuite(SP).run()\n ' cat = (InfiniteEnumeratedSets() & SetsWithGrading()) Permutations.__init__(self, category=cat) def _repr_(self): '\n TESTS::\n\n sage: Permutations()\n Standard permutations\n ' return 'Standard permutations' def __contains__(self, x): '\n TESTS::\n\n sage: [] in Permutations()\n True\n sage: [1] in Permutations()\n True\n sage: [2] in Permutations()\n False\n sage: [1,2] in Permutations()\n True\n sage: [2,1] in Permutations()\n True\n sage: [1,2,2] in Permutations()\n False\n sage: [3,1,5,2] in Permutations()\n False\n sage: [3,4,1,5,2] in Permutations()\n True\n ' if isinstance(x, Permutation): return True elif isinstance(x, list): s = sorted(x[:]) if (s != list(range(1, (len(x) + 1)))): return False return True else: return False def __iter__(self): '\n Iterate over ``self``.\n\n TESTS::\n\n sage: it = iter(Permutations())\n sage: [next(it) for i in range(10)]\n [[], [1], [1, 2], [2, 1], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n ' n = 0 while True: for p in itertools.permutations(range(1, (n + 1))): (yield self.element_class(self, p, check=False)) n += 1 def graded_component(self, n): '\n Return the graded component.\n\n EXAMPLES::\n\n sage: P = Permutations()\n sage: P.graded_component(4) == Permutations(4)\n True\n ' return StandardPermutations_n(n)
class StandardPermutations_n_abstract(Permutations): '\n Abstract base class for subsets of permutations of the\n set `\\{1, 2, \\ldots, n\\}`.\n\n .. WARNING::\n\n Anything inheriting from this class should override the\n ``__contains__`` method.\n ' def __init__(self, n, category=None): "\n TESTS:\n\n We skip the descent and reduced word methods because they do\n not respect the ordering for multiplication::\n\n sage: SP = Permutations(3)\n sage: TestSuite(SP).run(skip=['_test_reduced_word', '_test_has_descent'])\n\n sage: SP.options.mult='r2l'\n sage: TestSuite(SP).run()\n sage: SP.options._reset()\n " self.n = ZZ(n) if (category is None): category = FiniteEnumeratedSets() Permutations.__init__(self, category=category) @rename_keyword(deprecation=35233, check_input='check') def _element_constructor_(self, x, check=True): '\n Construct an element of ``self`` from ``x``.\n\n TESTS::\n\n sage: P = Permutations(5)\n sage: P([2,3,1])\n [2, 3, 1, 4, 5]\n\n sage: # needs sage.groups\n sage: G = SymmetricGroup(4)\n sage: P = Permutations(4)\n sage: x = G([4,3,1,2]); x\n (1,4,2,3)\n sage: P(x)\n [4, 3, 1, 2]\n sage: G(P(x))\n (1,4,2,3)\n\n sage: # needs sage.groups\n sage: P = PermutationGroup([[(1,3,5),(2,4)],[(1,3)]])\n sage: x = P([(3,5),(2,4)]); x\n (2,4)(3,5)\n sage: Permutations(6)(SymmetricGroup(6)(x))\n [1, 4, 5, 2, 3, 6]\n sage: Permutations(6)(x) # known bug\n [1, 4, 5, 2, 3, 6]\n ' if (len(x) < self.n): x = (list(x) + list(range((len(x) + 1), (self.n + 1)))) return self.element_class(self, x, check=check) def __contains__(self, x): '\n TESTS::\n\n sage: [] in Permutations(0)\n True\n sage: [1,2] in Permutations(2)\n True\n sage: [1,2] in Permutations(3)\n False\n sage: [3,2,1] in Permutations(3)\n True\n ' return (Permutations.__contains__(self, x) and (len(x) == self.n))
class StandardPermutations_n(StandardPermutations_n_abstract): '\n Permutations of the set `\\{1, 2, \\ldots, n\\}`.\n\n These are also called permutations of size `n`, or the elements\n of the `n`-th symmetric group.\n\n .. TODO::\n\n Have a :meth:`reduced_word` which works in both multiplication\n conventions.\n ' def __init__(self, n): "\n Initialize ``self``.\n\n TESTS::\n\n sage: P = Permutations(5)\n sage: P.options.mult = 'r2l'\n sage: TestSuite(P).run(skip='_test_descents')\n sage: P.options._reset()\n " cat = (FiniteWeylGroups().Irreducible() & FinitePermutationGroups()) StandardPermutations_n_abstract.__init__(self, n, category=cat) def _repr_(self): '\n TESTS::\n\n sage: Permutations(3)\n Standard permutations of 3\n ' return ('Standard permutations of %s' % self.n) def __iter__(self): '\n EXAMPLES::\n\n sage: [p for p in Permutations(0)]\n [[]]\n sage: [p for p in Permutations(3)]\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n ' for p in itertools.permutations(range(1, (self.n + 1))): (yield self.element_class(self, p, check=False)) def _coerce_map_from_(self, G): "\n Return a coerce map or ``True`` if there exists a coerce map\n from ``G``.\n\n .. WARNING::\n\n The coerce maps between ``Permutations(n)`` and\n ``SymmetricGroup(n)`` exist, but do not respect the\n multiplication when the global variable\n ``Permutations.options.mult`` (see\n :meth:`sage.combinat.permutation.Permutations.options` )\n is set to ``'r2l'``. (Indeed, the multiplication\n in ``Permutations(n)`` depends on this global\n variable, while the multiplication in\n ``SymmetricGroup(n)`` does not.)\n\n EXAMPLES::\n\n sage: P = Permutations(6)\n sage: P.has_coerce_map_from(SymmetricGroup(6)) # needs sage.groups\n True\n sage: P.has_coerce_map_from(SymmetricGroup(5)) # needs sage.groups\n True\n sage: P.has_coerce_map_from(SymmetricGroup(7)) # needs sage.groups\n False\n sage: P.has_coerce_map_from(Permutations(5))\n True\n sage: P.has_coerce_map_from(Permutations(7))\n False\n\n sage: P.has_coerce_map_from(groups.misc.Cactus(5)) # needs sage.graphs sage.groups\n True\n sage: P.has_coerce_map_from(groups.misc.Cactus(7)) # needs sage.graphs sage.groups\n False\n " if isinstance(G, SymmetricGroup): D = G.domain() if ((len(D) > self.n) or (list(D) != list(range(1, (len(D) + 1))))): return False return self._from_permutation_group_element if (isinstance(G, StandardPermutations_n) and (G.n <= self.n)): return True if (isinstance(G, CactusGroup) and (G.n() <= self.n)): return self._from_cactus_group_element return super()._coerce_map_from_(G) def _from_permutation_group_element(self, x): '\n Return an element of ``self`` from a permutation group element.\n\n TESTS::\n\n sage: P = Permutations(4)\n sage: G = SymmetricGroup(4) # needs sage.groups\n sage: x = G([4,3,1,2]) # needs sage.groups\n sage: P._from_permutation_group_element(x) # needs sage.groups\n [4, 3, 1, 2]\n ' return self(x.domain()) def _from_cactus_group_element(self, x): '\n Return an element of ``self`` from a cactus group element.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: J3 = groups.misc.Cactus(3)\n sage: s12,s13,s23 = J3.gens()\n sage: elt = s12 * s23 * s13\n sage: P5 = Permutations(5)\n sage: P5._from_cactus_group_element(elt)\n [1, 3, 2, 4, 5]\n ' return self(x.to_permutation()) def as_permutation_group(self): '\n Return ``self`` as a permutation group.\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: PG = P.as_permutation_group(); PG # needs sage.groups\n Symmetric group of order 4! as a permutation group\n\n sage: G = SymmetricGroup(4) # needs sage.groups\n sage: PG is G # needs sage.groups\n True\n ' from sage.groups.perm_gps.permgroup_named import SymmetricGroup return SymmetricGroup(self.n) def identity(self): '\n Return the identity permutation of size `n`.\n\n EXAMPLES::\n\n sage: Permutations(4).identity()\n [1, 2, 3, 4]\n sage: Permutations(0).identity()\n []\n ' return self.element_class(self, range(1, (self.n + 1)), check=False) one = identity def unrank(self, r): '\n EXAMPLES::\n\n sage: SP3 = Permutations(3)\n sage: l = list(map(SP3.unrank, range(6)))\n sage: l == SP3.list()\n True\n sage: SP0 = Permutations(0)\n sage: l = list(map(SP0.unrank, range(1)))\n sage: l == SP0.list()\n True\n ' if ((r >= factorial(self.n)) or (r < 0)): raise ValueError else: return from_rank(self.n, r) def rank(self, p=None): '\n Return the rank of ``self`` or ``p`` depending on input.\n\n If a permutation ``p`` is given, return the rank of ``p``\n in ``self``. Otherwise return the dimension of the\n underlying vector space spanned by the (simple) roots.\n\n EXAMPLES::\n\n sage: P = Permutations(5)\n sage: P.rank()\n 4\n\n sage: SP3 = Permutations(3)\n sage: list(map(SP3.rank, SP3))\n [0, 1, 2, 3, 4, 5]\n sage: SP0 = Permutations(0)\n sage: list(map(SP0.rank, SP0))\n [0]\n ' if (p is None): return (self.n - 1) if (p in self): return Permutation(p).rank() raise ValueError('p not in self') def random_element(self): '\n EXAMPLES::\n\n sage: s = Permutations(4).random_element(); s # random\n [1, 2, 4, 3]\n sage: s in Permutations(4)\n True\n ' return self.element_class(self, sample(range(1, (self.n + 1)), self.n), check=False) def cardinality(self): '\n Return the number of permutations of size `n`, which is `n!`.\n\n EXAMPLES::\n\n sage: Permutations(0).cardinality()\n 1\n sage: Permutations(3).cardinality()\n 6\n sage: Permutations(4).cardinality()\n 24\n ' return factorial(self.n) def degree(self): '\n Return the degree of ``self``.\n\n This is the cardinality `n` of the set ``self`` acts on.\n\n EXAMPLES::\n\n sage: Permutations(0).degree()\n 0\n sage: Permutations(1).degree()\n 1\n sage: Permutations(5).degree()\n 5\n ' return self.n def degrees(self): '\n Return the degrees of ``self``.\n\n These are the degrees of the fundamental invariants of the\n ring of polynomial invariants.\n\n EXAMPLES::\n\n sage: Permutations(3).degrees()\n (2, 3)\n sage: Permutations(7).degrees()\n (2, 3, 4, 5, 6, 7)\n ' return tuple((Integer(i) for i in range(2, (self.n + 1)))) def codegrees(self): '\n Return the codegrees of ``self``.\n\n EXAMPLES::\n\n sage: Permutations(3).codegrees()\n (0, 1)\n sage: Permutations(7).codegrees()\n (0, 1, 2, 3, 4, 5)\n ' return tuple((Integer(i) for i in range((self.n - 1)))) def element_in_conjugacy_classes(self, nu): '\n Return a permutation with cycle type ``nu``.\n\n If the size of ``nu`` is smaller than the size of permutations in\n ``self``, then some fixed points are added.\n\n EXAMPLES::\n\n sage: PP = Permutations(5)\n sage: PP.element_in_conjugacy_classes([2,2]) # needs sage.combinat\n [2, 1, 4, 3, 5]\n sage: PP.element_in_conjugacy_classes([5, 5]) # needs sage.combinat\n Traceback (most recent call last):\n ...\n ValueError: the size of the partition (=10) should be at most the size of the permutations (=5)\n ' from sage.combinat.partition import Partition nu = Partition(nu) if (nu.size() > self.n): raise ValueError(('the size of the partition (=%s) should be at most the size of the permutations (=%s)' % (nu.size(), self.n))) l = [] i = 0 for nui in nu: for j in range((nui - 1)): l.append(((i + j) + 2)) l.append((i + 1)) i += nui for i in range(nu.size(), self.n): l.append((i + 1)) return self.element_class(self, l, check=False) def conjugacy_classes_representatives(self): '\n Return a complete list of representatives of conjugacy classes\n in ``self``.\n\n Let `S_n` be the symmetric group on `n` letters. The conjugacy\n classes are indexed by partitions `\\lambda` of `n`. The ordering\n of the conjugacy classes is reverse lexicographic order of\n the partitions.\n\n EXAMPLES::\n\n sage: G = Permutations(5)\n sage: G.conjugacy_classes_representatives() # needs sage.combinat sage.libs.flint\n [[1, 2, 3, 4, 5],\n [2, 1, 3, 4, 5],\n [2, 1, 4, 3, 5],\n [2, 3, 1, 4, 5],\n [2, 3, 1, 5, 4],\n [2, 3, 4, 1, 5],\n [2, 3, 4, 5, 1]]\n\n TESTS:\n\n Check some border cases::\n\n sage: S = Permutations(0)\n sage: S.conjugacy_classes_representatives() # needs sage.combinat sage.libs.flint\n [[]]\n sage: S = Permutations(1)\n sage: S.conjugacy_classes_representatives() # needs sage.combinat sage.libs.flint\n [[1]]\n ' from sage.combinat.partition import Partitions_n return [self.element_in_conjugacy_classes(la) for la in reversed(Partitions_n(self.n))] def conjugacy_classes_iterator(self): '\n Iterate over the conjugacy classes of ``self``.\n\n EXAMPLES::\n\n sage: G = Permutations(4)\n sage: list(G.conjugacy_classes_iterator()) == G.conjugacy_classes() # needs sage.combinat sage.graphs sage.groups\n True\n ' from sage.combinat.partition import Partitions_n from sage.groups.perm_gps.symgp_conjugacy_class import PermutationsConjugacyClass for la in reversed(Partitions_n(self.n)): (yield PermutationsConjugacyClass(self, la)) def conjugacy_classes(self): '\n Return a list of the conjugacy classes of ``self``.\n\n EXAMPLES::\n\n sage: G = Permutations(4)\n sage: G.conjugacy_classes() # needs sage.combinat sage.graphs sage.groups\n [Conjugacy class of cycle type [1, 1, 1, 1] in Standard permutations of 4,\n Conjugacy class of cycle type [2, 1, 1] in Standard permutations of 4,\n Conjugacy class of cycle type [2, 2] in Standard permutations of 4,\n Conjugacy class of cycle type [3, 1] in Standard permutations of 4,\n Conjugacy class of cycle type [4] in Standard permutations of 4]\n ' return list(self.conjugacy_classes_iterator()) def conjugacy_class(self, g): '\n Return the conjugacy class of ``g`` in ``self``.\n\n INPUT:\n\n - ``g`` -- a partition or an element of ``self``\n\n EXAMPLES::\n\n sage: G = Permutations(5)\n sage: g = G([2,3,4,1,5])\n sage: G.conjugacy_class(g) # needs sage.combinat sage.graphs sage.groups\n Conjugacy class of cycle type [4, 1] in Standard permutations of 5\n sage: G.conjugacy_class(Partition([2, 1, 1, 1])) # needs sage.combinat sage.graphs sage.groups\n Conjugacy class of cycle type [2, 1, 1, 1] in Standard permutations of 5\n ' from sage.groups.perm_gps.symgp_conjugacy_class import PermutationsConjugacyClass return PermutationsConjugacyClass(self, g) def algebra(self, base_ring, category=None): '\n Return the symmetric group algebra associated to ``self``.\n\n INPUT:\n\n - ``base_ring`` -- a ring\n - ``category`` -- a category (default: the category of ``self``)\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: P = Permutations(4)\n sage: A = P.algebra(QQ); A\n Symmetric group algebra of order 4 over Rational Field\n sage: A.category()\n Join of Category of Coxeter group algebras over Rational Field\n and Category of finite group algebras over Rational Field\n and Category of finite dimensional cellular algebras\n with basis over Rational Field\n sage: A = P.algebra(QQ, category=Monoids())\n sage: A.category()\n Category of finite dimensional cellular monoid algebras over Rational Field\n ' from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra return SymmetricGroupAlgebra(base_ring, self, category=category) @cached_method def index_set(self): '\n Return the index set for the descents of the symmetric group ``self``.\n\n This is `\\{ 1, 2, \\ldots, n-1 \\}`, where ``self`` is `S_n`.\n\n EXAMPLES::\n\n sage: P = Permutations(8)\n sage: P.index_set()\n (1, 2, 3, 4, 5, 6, 7)\n ' return tuple(range(1, self.n)) def cartan_type(self): "\n Return the Cartan type of ``self``.\n\n The symmetric group `S_n` is a Coxeter group of type `A_{n-1}`.\n\n EXAMPLES::\n\n sage: A = SymmetricGroup([2,3,7]); A.cartan_type() # needs sage.combinat sage.groups\n ['A', 2]\n sage: A = SymmetricGroup([]); A.cartan_type() # needs sage.combinat sage.groups\n ['A', 0]\n " from sage.combinat.root_system.cartan_type import CartanType return CartanType(['A', max((self.n - 1), 0)]) def simple_reflection(self, i): '\n For `i` in the index set of ``self`` (that is, for `i` in\n `\\{ 1, 2, \\ldots, n-1 \\}`, where ``self`` is `S_n`), this\n returns the elementary transposition `s_i = (i,i+1)`.\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: P.simple_reflection(2)\n [1, 3, 2, 4]\n sage: P.simple_reflections()\n Finite family {1: [2, 1, 3, 4], 2: [1, 3, 2, 4], 3: [1, 2, 4, 3]}\n ' g = list(range(1, (self.n + 1))) g[(i - 1)] = (i + 1) g[i] = i return self.element_class(self, g, check=False) class Element(Permutation): def has_left_descent(self, i, mult=None): "\n Check if ``i`` is a left descent of ``self``.\n\n A *left descent* of a permutation `\\pi \\in S_n` means an index\n `i \\in \\{ 1, 2, \\ldots, n-1 \\}` such that\n `s_i \\circ \\pi` has smaller length than `\\pi`. Thus, a left\n descent of `\\pi` is an index `i \\in \\{ 1, 2, \\ldots, n-1 \\}`\n satisfying `\\pi^{-1}(i) > \\pi^{-1}(i+1)`.\n\n .. WARNING::\n\n The methods :meth:`descents` and :meth:`idescents` behave\n differently than their Weyl group counterparts. In\n particular, the indexing is 0-based. This could lead to\n errors. Instead, construct the descent set as in the example.\n\n .. WARNING::\n\n This ignores the multiplication convention in order\n to be consistent with other Coxeter operations in\n permutations (e.g., computing :meth:`reduced_word`).\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: x = P([3, 2, 4, 1])\n sage: (~x).descents()\n [1, 2]\n sage: [i for i in P.index_set() if x.has_left_descent(i)]\n [1, 2]\n\n TESTS::\n\n sage: P = Permutations(4)\n sage: x = P([3, 2, 4, 1])\n sage: x.has_left_descent(2, mult='l2r')\n doctest:warning\n ...\n DeprecationWarning: The mult option is deprecated and ignored.\n See https://github.com/sagemath/sage/issues/27467 for details.\n True\n sage: x.has_left_descent(2, mult='r2l')\n True\n " if (mult is not None): from sage.misc.superseded import deprecation deprecation(27467, 'The mult option is deprecated and ignored.') for val in self._list: if (val == i): return False if (val == (i + 1)): return True def has_right_descent(self, i, mult=None): "\n Check if ``i`` is a right descent of ``self``.\n\n A *right descent* of a permutation `\\pi \\in S_n` means an index\n `i \\in \\{ 1, 2, \\ldots, n-1 \\}` such that\n `\\pi \\circ s_i` has smaller length than `\\pi`. Thus, a right\n descent of `\\pi` is an index `i \\in \\{ 1, 2, \\ldots, n-1 \\}`\n satisfying `\\pi(i) > \\pi(i+1)`.\n\n .. WARNING::\n\n The methods :meth:`descents` and :meth:`idescents` behave\n differently than their Weyl group counterparts. In\n particular, the indexing is 0-based. This could lead to\n errors. Instead, construct the descent set as in the example.\n\n .. WARNING::\n\n This ignores the multiplication convention in order\n to be consistent with other Coxeter operations in\n permutations (e.g., computing :meth:`reduced_word`).\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: x = P([3, 2, 4, 1])\n sage: x.descents()\n [1, 3]\n sage: [i for i in P.index_set() if x.has_right_descent(i)]\n [1, 3]\n\n TESTS::\n\n sage: P = Permutations(4)\n sage: x = P([3, 2, 4, 1])\n sage: x.has_right_descent(3, mult='l2r')\n doctest:warning\n ...\n DeprecationWarning: The mult option is deprecated and ignored.\n See https://github.com/sagemath/sage/issues/27467 for details.\n True\n sage: x.has_right_descent(3, mult='r2l')\n True\n " if (mult is not None): from sage.misc.superseded import deprecation deprecation(27467, 'The mult option is deprecated and ignored.') return (self[(i - 1)] > self[i]) def __mul__(self, other): "\n Multiply ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: P.simple_reflection(1) * Permutation([6,5,4,3,2,1])\n [5, 6, 4, 3, 2, 1]\n sage: Permutations.options.mult='r2l'\n sage: P.simple_reflection(1) * Permutation([6,5,4,3,2,1])\n [6, 5, 4, 3, 1, 2]\n sage: Permutations.options.mult='l2r'\n " if (not isinstance(other, StandardPermutations_n.Element)): return Permutation.__mul__(self, other) P = self.parent() if (other.parent() is not P): mul_order = P.options.mult if (mul_order == 'l2r'): p = right_action_product(self._list, other._list) elif (mul_order == 'r2l'): p = left_action_product(self._list, other._list) return Permutations(len(p))(p) return self._mul_(other) def _mul_(self, other): '\n Multiply ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: P.prod(P.group_generators()).parent() is P\n True\n ' mul_order = self.parent().options.mult if (mul_order == 'l2r'): p = right_action_same_n(self._list, other._list) elif (mul_order == 'r2l'): p = left_action_same_n(self._list, other._list) return self.__class__(self.parent(), p) @combinatorial_map(order=2, name='inverse') def inverse(self): '\n Return the inverse of ``self``.\n\n EXAMPLES::\n\n sage: P = Permutations(4)\n sage: w0 = P([4,3,2,1])\n sage: w0.inverse() == w0\n True\n sage: w0.inverse().parent() is P\n True\n sage: P([3,2,4,1]).inverse()\n [4, 2, 1, 3]\n ' w = list(range(len(self))) for (i, j) in enumerate(self): w[(j - 1)] = (i + 1) return self.__class__(self.parent(), w) __invert__ = inverse def apply_simple_reflection_left(self, i): '\n Return ``self`` multiplied by the simple reflection ``s[i]``\n on the left.\n\n This acts by switching the entries in positions `i` and `i+1`.\n\n .. WARNING::\n\n This ignores the multiplication convention in order\n to be consistent with other Coxeter operations in\n permutations (e.g., computing :meth:`reduced_word`).\n\n EXAMPLES::\n\n sage: W = Permutations(3)\n sage: w = W([2,3,1])\n sage: w.apply_simple_reflection_left(1)\n [1, 3, 2]\n sage: w.apply_simple_reflection_left(2)\n [3, 2, 1]\n ' s = self.parent().simple_reflections()[i] p = right_action_same_n(self._list, s._list) return self.__class__(self.parent(), p) def apply_simple_reflection_right(self, i): '\n Return ``self`` multiplied by the simple reflection ``s[i]``\n on the right.\n\n This acts by switching the entries `i` and `i+1`.\n\n .. WARNING::\n\n This ignores the multiplication convention in order\n to be consistent with other Coxeter operations in\n permutations (e.g., computing :meth:`reduced_word`).\n\n EXAMPLES::\n\n sage: W = Permutations(3)\n sage: w = W([2,3,1])\n sage: w.apply_simple_reflection_right(1)\n [3, 2, 1]\n sage: w.apply_simple_reflection_right(2)\n [2, 1, 3]\n ' s = self.parent().simple_reflections()[i] p = left_action_same_n(self._list, s._list) return self.__class__(self.parent(), p)
def from_permutation_group_element(pge, parent=None): '\n Return a :class:`Permutation` given a :class:`PermutationGroupElement`\n ``pge``.\n\n EXAMPLES::\n\n sage: import sage.combinat.permutation as permutation\n sage: pge = PermutationGroupElement([(1,2),(3,4)]) # needs sage.groups\n sage: permutation.from_permutation_group_element(pge) # needs sage.groups\n [2, 1, 4, 3]\n ' if (not isinstance(pge, PermutationGroupElement)): raise TypeError(('pge (= %s) must be a PermutationGroupElement' % pge)) if (parent is None): parent = Permutations(len(pge.domain())) return parent(pge.domain())