code
stringlengths
17
6.64M
def WeakTableau(t, k, inner_shape=[], representation='core'): '\n This is the dispatcher method for the element class of weak `k`-tableaux.\n\n Standard weak `k`-tableaux correspond to saturated chains in the weak order.\n There are three formulations of weak tableaux, one in terms of cores, one in terms\n of `k`-bounded partitions, and one in terms of factorizations of affine Grassmannian\n elements. For semistandard weak `k`-tableaux, all letters of the same value have to\n satisfy the conditions of a horizontal strip. In the affine Grassmannian formulation this\n means that all factors are cyclically decreasing elements. For more information, see\n for example [LLMSSZ2013]_.\n\n INPUT:\n\n - ``t`` -- a weak `k`-tableau in the specified representation:\n\n - for the \'core\' representation ``t`` is a list of lists where each subtableaux\n should have a `k+1`-core shape; ``None`` is allowed as an entry for skew weak\n `k`-tableaux\n - for the \'bounded\' representation ``t`` is a list of lists where each subtableaux\n should have a `k`-bounded shape; ``None`` is allowed as an entry for skew weak\n `k`-tableaux\n - for the \'factorized_permutation\' representation ``t`` is either a list of\n cyclically decreasing Weyl group elements or a list of reduced words of cyclically\n decreasing Weyl group elements; to indicate a skew tableau in this representation,\n ``inner_shape`` should be the inner shape as a `(k+1)`-core\n\n - ``k`` -- positive integer\n\n - ``inner_shape`` -- this entry is only relevant for the \'factorized_permutation\'\n representation and specifies the inner shape in case the tableau is skew\n (default: ``[]``)\n\n - ``representation`` -- \'core\', \'bounded\', or \'factorized_permutation\'\n (default: \'core\')\n\n EXAMPLES:\n\n Here is an example of a weak 3-tableau in core representation::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.shape()\n [5, 2, 1]\n sage: t.weight()\n (2, 2, 2)\n sage: type(t)\n <class \'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class\'>\n\n And now we give a skew weak 3-tableau in core representation::\n\n sage: ts = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3)\n sage: ts.shape()\n ([5, 2, 1], [1, 1])\n sage: ts.weight()\n (2, 2)\n sage: type(ts)\n <class \'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class\'>\n\n Next we create the analogue of the first example in bounded representation::\n\n sage: tb = WeakTableau([[1,1,2],[2,3],[3]], 3, representation="bounded")\n sage: tb.shape()\n [3, 2, 1]\n sage: tb.weight()\n (2, 2, 2)\n sage: type(tb)\n <class \'sage.combinat.k_tableau.WeakTableaux_bounded_with_category.element_class\'>\n sage: tb.to_core_tableau()\n [[1, 1, 2, 2, 3], [2, 3], [3]]\n sage: t == tb.to_core_tableau()\n True\n\n And the analogue of the skew example in bounded representation::\n\n sage: tbs = WeakTableau([[None, 1, 2], [None, 2], [1]], 3, representation = "bounded")\n sage: tbs.shape()\n ([3, 2, 1], [1, 1])\n sage: tbs.weight()\n (2, 2)\n sage: tbs.to_core_tableau()\n [[None, 1, 1, 2, 2], [None, 2], [1]]\n sage: ts.to_bounded_tableau() == tbs\n True\n\n Finally we do the same examples for the factorized permutation representation::\n\n sage: tf = WeakTableau([[2,0],[3,2],[1,0]], 3, representation = "factorized_permutation")\n sage: tf.shape()\n [5, 2, 1]\n sage: tf.weight()\n (2, 2, 2)\n sage: type(tf)\n <class \'sage.combinat.k_tableau.WeakTableaux_factorized_permutation_with_category.element_class\'>\n sage: tf.to_core_tableau() == t\n True\n\n sage: tfs = WeakTableau([[0,3],[2,1]], 3, inner_shape = [1,1], representation = \'factorized_permutation\')\n sage: tfs.shape()\n ([5, 2, 1], [1, 1])\n sage: tfs.weight()\n (2, 2)\n sage: type(tfs)\n <class \'sage.combinat.k_tableau.WeakTableaux_factorized_permutation_with_category.element_class\'>\n sage: tfs.to_core_tableau()\n [[None, 1, 1, 2, 2], [None, 2], [1]]\n\n Another way to pass from one representation to another is as follows::\n\n sage: ts\n [[None, 1, 1, 2, 2], [None, 2], [1]]\n sage: ts.parent()._representation\n \'core\'\n sage: ts.representation(\'bounded\')\n [[None, 1, 2], [None, 2], [1]]\n\n To test whether a given semistandard tableau is a weak `k`-tableau in the bounded representation,\n one can ask::\n\n sage: t = Tableau([[1,1,2],[2,3],[3]])\n sage: t.is_k_tableau(3)\n True\n sage: t = SkewTableau([[None, 1, 2], [None, 2], [1]])\n sage: t.is_k_tableau(3)\n True\n sage: t = SkewTableau([[None, 1, 1], [None, 2], [2]])\n sage: t.is_k_tableau(3)\n False\n\n TESTS::\n\n sage: t = WeakTableau([[2,0],[3,2],[1,0]], 3, representation = "bla")\n Traceback (most recent call last):\n ...\n NotImplementedError: The representation option needs to be \'core\', \'bounded\', or \'factorized_permutation\'\n ' if (representation == 'core'): return WeakTableau_core(t, k) elif (representation == 'bounded'): return WeakTableau_bounded(t, k) elif (representation == 'factorized_permutation'): return WeakTableau_factorized_permutation(t, k, inner_shape=inner_shape) else: raise NotImplementedError("The representation option needs to be 'core', 'bounded', or 'factorized_permutation'")
def WeakTableaux(k, shape, weight, representation='core'): "\n This is the dispatcher method for the parent class of weak `k`-tableaux.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- shape of the weak `k`-tableaux; for the 'core' and\n 'factorized_permutation' representation, the shape is inputted as a `(k+1)`-core;\n for the 'bounded' representation, the shape is inputted as a `k`-bounded partition;\n for skew tableaux, the shape is inputted as a tuple of the outer and inner shape\n - ``weight`` -- the weight of the weak `k`-tableaux as a list or tuple\n - ``representation`` -- ``'core'``, ``'bounded'``, or ``'factorized_permutation'`` (default: ``'core'``)\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1])\n sage: T.list()\n [[[1, 3, 4, 5, 6], [2, 6], [4]],\n [[1, 2, 4, 5, 6], [3, 6], [4]],\n [[1, 2, 3, 4, 6], [4, 6], [5]],\n [[1, 2, 3, 4, 5], [4, 5], [6]]]\n sage: T.cardinality()\n 4\n\n sage: T = WeakTableaux(3, [[5,2,1], [2]], [1,1,1,1])\n sage: T.list()\n [[[None, None, 2, 3, 4], [1, 4], [2]],\n [[None, None, 1, 2, 4], [2, 4], [3]],\n [[None, None, 1, 2, 3], [2, 3], [4]]]\n\n sage: T = WeakTableaux(3, [3,2,1], [1,1,1,1,1,1], representation = 'bounded')\n sage: T.list()\n [[[1, 3, 5], [2, 6], [4]],\n [[1, 2, 5], [3, 6], [4]],\n [[1, 2, 3], [4, 6], [5]],\n [[1, 2, 3], [4, 5], [6]]]\n\n sage: T = WeakTableaux(3, [[3,2,1], [2]], [1,1,1,1], representation = 'bounded')\n sage: T.list()\n [[[None, None, 3], [1, 4], [2]],\n [[None, None, 1], [2, 4], [3]],\n [[None, None, 1], [2, 3], [4]]]\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1], representation = 'factorized_permutation')\n sage: T.list()\n [[s0, s3, s2, s1, s3, s0],\n [s0, s3, s2, s3, s1, s0],\n [s0, s2, s3, s2, s1, s0],\n [s2, s0, s3, s2, s1, s0]]\n\n sage: T = WeakTableaux(3, [[5,2,1], [2]], [1,1,1,1], representation = 'factorized_permutation')\n sage: T.list()\n [[s0, s3, s2, s3], [s0, s2, s3, s2], [s2, s0, s3, s2]]\n " if (representation == 'core'): return WeakTableaux_core(k, shape, weight) elif (representation == 'bounded'): return WeakTableaux_bounded(k, shape, weight) elif (representation == 'factorized_permutation'): return WeakTableaux_factorized_permutation(k, shape, weight) else: raise NotImplementedError("The representation option needs to be 'core', 'bounded', or 'factorized_permutation'")
class WeakTableau_abstract(ClonableList, metaclass=InheritComparisonClasscallMetaclass): '\n Abstract class for the various element classes of WeakTableau.\n ' def shape(self): "\n Return the shape of ``self``.\n\n When the tableau is straight, the outer shape is returned.\n When the tableau is skew, the tuple of the outer and inner shape is returned.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.shape()\n [5, 2, 1]\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.shape()\n ([5, 2, 1], [2])\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t.shape()\n [3, 2, 1]\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.shape()\n ([3, 2, 1], [2])\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t.shape()\n [5, 2, 1]\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.shape()\n ([5, 2, 1], [2])\n " return self.parent().shape() def weight(self): "\n Return the weight of ``self``.\n\n The weight is a tuple whose `i`-th entry is the number of labels `i` in the\n bounded representation of ``self``.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.weight()\n (2, 2, 2)\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.weight()\n (1, 1, 1, 1)\n sage: t = WeakTableau([[None,2,3],[3]],2)\n sage: t.weight()\n (0, 1, 1)\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t.weight()\n (3, 2, 1)\n sage: t = WeakTableau([[1,1,2],[2,3],[3]], 3, representation = 'bounded')\n sage: t.weight()\n (2, 2, 2)\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.weight()\n (1, 1, 1, 1)\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t.weight()\n (3, 2, 1)\n sage: t = WeakTableau([[2,0],[3,2],[1,0]], 3, representation = 'factorized_permutation')\n sage: t.weight()\n (2, 2, 2)\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.weight()\n (2, 2)\n " return self.parent()._weight def size(self): '\n Return the size of the shape of ``self``.\n\n In the bounded representation, the size of the shape is the number of boxes in the\n outer shape minus the number of boxes in the inner shape. For the core and\n factorized permutation representation, the size is the length of the outer shape\n minus the length of the inner shape.\n\n .. SEEALSO:: :meth:`sage.combinat.core.Core.length`\n\n EXAMPLES::\n\n sage: t = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3)\n sage: t.shape()\n ([5, 2, 1], [1, 1])\n sage: t.size()\n 4\n sage: t = WeakTableau([[1,1,2],[2,3],[3]], 3, representation="bounded")\n sage: t.shape()\n [3, 2, 1]\n sage: t.size()\n 6\n ' return self.parent().size() def intermediate_shapes(self): "\n Return the intermediate shapes of ``self``.\n\n A (skew) tableau with letters `1,2,\\ldots,\\ell` can be viewed as a sequence of shapes,\n where the `i`-th shape is given by the shape of the subtableau on letters `1,2,\\ldots,i`.\n The output is the list of these shapes.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: t.intermediate_shapes()\n [[], [2], [4, 1], [5, 2, 1]]\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.intermediate_shapes()\n [[2], [2, 1], [3, 1, 1], [4, 1, 1], [5, 2, 1]]\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t.intermediate_shapes()\n [[], [3], [3, 2], [3, 2, 1]]\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.intermediate_shapes()\n [[2], [3], [3, 1], [3, 1, 1], [3, 2, 1]]\n\n sage: t = WeakTableau([[0],[3],[2],[3]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.intermediate_shapes()\n [[2], [2, 1], [3, 1, 1], [4, 1, 1], [5, 2, 1]]\n " if (self.parent()._representation in ['core', 'bounded']): return intermediate_shapes(self) else: return intermediate_shapes(self.to_core_tableau()) def pp(self): "\n Return a pretty print string of the tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3)\n sage: t.pp()\n . 1 1 2 2\n . 2\n 1\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.pp()\n [s2*s0, s3*s2]\n " if (self.parent()._representation in ['core', 'bounded']): print(self._repr_diagram()) else: print(self) def __hash__(self): "\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1], representation='core')\n sage: t = T[0]\n sage: hash(t) == hash(t)\n True\n sage: T = WeakTableaux(3, [2,2,1], [1,1,1,1,1], representation='bounded')\n sage: t = T[0]\n sage: hash(t) == hash(t)\n True\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1], representation='factorized_permutation')\n sage: t = T[0]\n sage: hash(t) == hash(t)\n True\n " if (self.parent()._representation in ['core', 'bounded']): return (hash(tuple((tuple(x) for x in self))) + hash(self.parent().k)) else: return super().__hash__() def _latex_(self): "\n Return a latex method for the tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3)\n sage: latex(t)\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{5}c}\\cline{1-5}\n \\lr{}&\\lr{1}&\\lr{1}&\\lr{2}&\\lr{2}\\\\\\cline{1-5}\n \\lr{}&\\lr{2}\\\\\\cline{1-2}\n \\lr{1}\\\\\\cline{1-1}\n \\end{array}$}\n }\n\n sage: t = WeakTableau([[0,3],[2,1]], 3, inner_shape = [1,1], representation = 'factorized_permutation')\n sage: latex(t)\n [s_{0}s_{3},s_{2}s_{1}]\n " def chi(x): if (x is None): return '' if (x in ZZ): return x return ('%s' % x) if (self.parent()._representation in ['core', 'bounded']): t = [[chi(x) for x in row] for row in self] from .output import tex_from_array return tex_from_array(t) else: return ((('[' + ''.join(((self[i]._latex_() + ',') for i in range((len(self) - 1))))) + self[(len(self) - 1)]._latex_()) + ']') def representation(self, representation='core'): "\n Return the analogue of ``self`` in the specified representation.\n\n INPUT:\n\n - ``representation`` -- 'core', 'bounded', or 'factorized_permutation' (default: 'core')\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: t.parent()._representation\n 'core'\n sage: t.representation('bounded')\n [[1, 1, 2, 4], [2, 3, 5], [3, 4], [5, 6], [6], [7]]\n sage: t.representation('factorized_permutation')\n [s0, s3*s1, s2*s1, s0*s4, s3*s0, s4*s2, s1*s0]\n\n sage: tb = WeakTableau([[1, 1, 2, 4], [2, 3, 5], [3, 4], [5, 6], [6], [7]], 4, representation = 'bounded')\n sage: tb.parent()._representation\n 'bounded'\n sage: tb.representation('core') == t\n True\n sage: tb.representation('factorized_permutation')\n [s0, s3*s1, s2*s1, s0*s4, s3*s0, s4*s2, s1*s0]\n\n sage: tp = WeakTableau([[0],[3,1],[2,1],[0,4],[3,0],[4,2],[1,0]], 4, representation = 'factorized_permutation')\n sage: tp.parent()._representation\n 'factorized_permutation'\n sage: tp.representation('core') == t\n True\n sage: tp.representation('bounded') == tb\n True\n " t = self if (self.parent()._representation in ['bounded', 'factorized_permutation']): t = t.to_core_tableau() if (representation == 'core'): return t elif (representation == 'bounded'): return t.to_bounded_tableau() elif (representation == 'factorized_permutation'): return t.to_factorized_permutation_tableau() else: raise ValueError("The representation must be one of 'core', 'bounded', or 'factorized_permutation'")
class WeakTableaux_abstract(UniqueRepresentation, Parent): '\n Abstract class for the various parent classes of WeakTableaux.\n ' def shape(self): "\n Return the shape of the tableaux of ``self``.\n\n When ``self`` is the class of straight tableaux, the outer shape is returned.\n When ``self`` is the class of skew tableaux, the tuple of the outer and inner\n shape is returned.\n\n Note that in the 'core' and 'factorized_permutation' representation, the shapes\n are `(k+1)`-cores. In the 'bounded' representation, the shapes are `k`-bounded\n partitions.\n\n If the user wants to access the skew shape (even if the inner shape is empty),\n please use ``self._shape``.\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [5,2,2], [2,2,2,1])\n sage: T.shape()\n [5, 2, 2]\n sage: T._shape\n ([5, 2, 2], [])\n sage: T = WeakTableaux(3, [[5,2,2], [1]], [2,1,2,1])\n sage: T.shape()\n ([5, 2, 2], [1])\n\n sage: T = WeakTableaux(3, [3,2,2], [2,2,2,1], representation = 'bounded')\n sage: T.shape()\n [3, 2, 2]\n sage: T._shape\n ([3, 2, 2], [])\n sage: T = WeakTableaux(3, [[3,2,2], [1]], [2,1,2,1], representation = 'bounded')\n sage: T.shape()\n ([3, 2, 2], [1])\n\n sage: T = WeakTableaux(3, [4,1], [2,2], representation = 'factorized_permutation')\n sage: T.shape()\n [4, 1]\n sage: T._shape\n ([4, 1], [])\n sage: T = WeakTableaux(4, [[6,2,1], [2]], [2,1,1,1], representation = 'factorized_permutation')\n sage: T.shape()\n ([6, 2, 1], [2])\n " if self._skew: return (self._outer_shape, self._inner_shape) return self._outer_shape def size(self): "\n Return the size of the shape.\n\n In the bounded representation, the size of the shape is the number of boxes in the\n outer shape minus the number of boxes in the inner shape. For the core and\n factorized permutation representation, the size is the length of the outer shape\n minus the length of the inner shape.\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1])\n sage: T.size()\n 6\n sage: T = WeakTableaux(3, [3,2,1], [1,1,1,1,1,1], representation = 'bounded')\n sage: T.size()\n 6\n sage: T = WeakTableaux(4, [[6,2,1], [2]], [2,1,1,1], 'factorized_permutation')\n sage: T.size()\n 5\n " if (self._representation == 'bounded'): return (self._outer_shape.size() - self._inner_shape.size()) else: return (self._outer_shape.length() - self._inner_shape.length()) def representation(self, representation='core'): "\n Return the analogue of ``self`` in the specified representation.\n\n INPUT:\n\n - ``representation`` -- 'core', 'bounded', or 'factorized_permutation' (default: 'core')\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1])\n sage: T._representation\n 'core'\n sage: T.representation('bounded')\n Bounded weak 3-Tableaux of (skew) 3-bounded shape [3, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('factorized_permutation')\n Factorized permutation (skew) weak 3-Tableaux of shape [5, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n\n sage: T = WeakTableaux(3, [3,2,1], [1,1,1,1,1,1], representation = 'bounded')\n sage: T._representation\n 'bounded'\n sage: T.representation('core')\n Core weak 3-Tableaux of (skew) core shape [5, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('bounded')\n Bounded weak 3-Tableaux of (skew) 3-bounded shape [3, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('bounded') == T\n True\n sage: T.representation('factorized_permutation')\n Factorized permutation (skew) weak 3-Tableaux of shape [5, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('factorized_permutation') == T\n False\n\n sage: T = WeakTableaux(3, [5,2,1], [1,1,1,1,1,1], representation = 'factorized_permutation')\n sage: T._representation\n 'factorized_permutation'\n sage: T.representation('core')\n Core weak 3-Tableaux of (skew) core shape [5, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('bounded')\n Bounded weak 3-Tableaux of (skew) 3-bounded shape [3, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n sage: T.representation('factorized_permutation')\n Factorized permutation (skew) weak 3-Tableaux of shape [5, 2, 1] and weight (1, 1, 1, 1, 1, 1)\n " outer_shape = self._outer_shape inner_shape = self._inner_shape weight = self._weight if ((self._representation in ['core', 'factorized_permutation']) and (representation == 'bounded')): outer_shape = outer_shape.to_bounded_partition() inner_shape = inner_shape.to_bounded_partition() if ((self._representation == 'bounded') and (representation in ['core', 'factorized_permutation'])): outer_shape = outer_shape.to_core(self.k) inner_shape = inner_shape.to_core(self.k) return WeakTableaux(self.k, [outer_shape, inner_shape], weight, representation=representation)
class WeakTableau_core(WeakTableau_abstract): '\n A (skew) weak `k`-tableau represented in terms of `(k+1)`-cores.\n ' @staticmethod def __classcall_private__(cls, t, k): "\n Implements the shortcut ``WeakTableau_core(t, k)`` to ``WeakTableaux_core(k, shape , weight)(t)``\n where ``shape`` is the shape of the tableau and ``weight`` is its weight.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_core\n sage: t = WeakTableau_core([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class'>\n sage: TestSuite(t).run()\n sage: t.parent()._skew\n False\n\n sage: t = WeakTableau_core([[None, None, 1, 1, 2], [1, 2], [2]],3)\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class'>\n sage: TestSuite(t).run()\n sage: t.parent()._skew\n True\n " if isinstance(t, cls): return t tab = SkewTableau(list(t)) outer = Core(tab.outer_shape(), (k + 1)) inner = Core(tab.inner_shape(), (k + 1)) weight = WeakTableau_bounded.from_core_tableau(t, k).weight() return WeakTableaux_core(k, [outer, inner], weight)(t) def __init__(self, parent, t): "\n Initialization of weak `k`-tableau ``t`` in core representation.\n\n INPUT:\n\n - ``t`` -- weak tableau in core representation; the input is supposed to be a list\n of lists specifying the rows of the tableau;\n ``None`` is allowed as an entry for skew weak `k`-tableaux\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_core, WeakTableaux_core\n sage: T = WeakTableaux_core(3,[5,2,1],[2,2,2])\n sage: t = T([[1, 1, 2, 2, 3], [2, 3], [3]]); t\n [[1, 1, 2, 2, 3], [2, 3], [3]]\n sage: c = WeakTableau_core([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: T = WeakTableaux_core(3,[5,2,1],[2,2,2])\n sage: t = T([[1, 1, 2, 2, 3], [2, 3], [3]]); t\n [[1, 1, 2, 2, 3], [2, 3], [3]]\n sage: c == t\n True\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class'>\n sage: t.parent()\n Core weak 3-Tableaux of (skew) core shape [5, 2, 1] and weight (2, 2, 2)\n sage: TestSuite(t).run()\n\n sage: t = WeakTableau_core([[None, None, 1, 1, 2], [1, 2], [2]],3); t\n [[None, None, 1, 1, 2], [1, 2], [2]]\n sage: t.weight()\n (2, 2)\n sage: t.shape()\n ([5, 2, 1], [2])\n sage: TestSuite(t).run()\n " self.k = parent.k ClonableList.__init__(self, parent, t) def _repr_diagram(self): '\n Return a string representation of ``self`` as a diagram.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: print(t._repr_diagram())\n . . 2 3 4\n 1 4\n 2\n ' t = SkewTableau(list(self)) return t._repr_diagram() def shape_core(self): '\n Return the shape of ``self`` as a `(k+1)`-core.\n\n When the tableau is straight, the outer shape is returned as a core. When the\n tableau is skew, the tuple of the outer and inner shape is returned as cores.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: t.shape_core()\n [5, 2, 1]\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.shape_core()\n ([5, 2, 1], [2])\n ' return self.shape() def shape_bounded(self): '\n Return the shape of ``self`` as a `k`-bounded partition.\n\n When the tableau is straight, the outer shape is returned as a `k`-bounded\n partition. When the tableau is skew, the tuple of the outer and inner shape is\n returned as `k`-bounded partitions.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: t.shape_bounded()\n [3, 2, 1]\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.shape_bounded()\n ([3, 2, 1], [2])\n ' if self.parent()._skew: return tuple([r.to_bounded_partition() for r in self.shape_core()]) return self.shape_core().to_bounded_partition() def check(self): '\n Check that ``self`` is a valid weak `k`-tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2], [2]], 2)\n sage: t.check()\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.check()\n\n TESTS::\n\n sage: T = WeakTableaux(2, [3,1], [1,1,1,1])\n sage: t = T([[1,2,3],[3]])\n Traceback (most recent call last):\n ...\n ValueError: The weight of the parent does not agree with the weight of the tableau!\n\n sage: t = WeakTableau([[1, 2, 2], [1]], 2)\n Traceback (most recent call last):\n ...\n ValueError: The tableau is not semistandard!\n ' if (not (self.parent()._weight == WeakTableau_bounded.from_core_tableau(self, self.k).weight())): raise ValueError('The weight of the parent does not agree with the weight of the tableau!') t = SkewTableau(list(self)) if (t not in SemistandardSkewTableaux()): raise ValueError('The tableau is not semistandard!') outer = Core(t.outer_shape(), (self.k + 1)) inner = Core(t.inner_shape(), (self.k + 1)) if (self.parent()._outer_shape != outer): raise ValueError('The outer shape of the parent does not agree with the outer shape of the tableau!') if (self.parent()._inner_shape != inner): raise ValueError('The inner shape of the parent does not agree with the inner shape of the tableau!') self.to_bounded_tableau().check() def to_bounded_tableau(self): "\n Return the bounded representation of the weak `k`-tableau ``self``.\n\n Each restricted subtableau of the output is a `k`-bounded partition.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: c = t.to_bounded_tableau(); c\n [[1, 1, 2], [2, 3], [3]]\n sage: type(c)\n <class 'sage.combinat.k_tableau.WeakTableaux_bounded_with_category.element_class'>\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.to_bounded_tableau()\n [[None, None, 3], [1, 4], [2]]\n sage: t.to_bounded_tableau().to_core_tableau() == t\n True\n " shapes = [Core(p, (self.k + 1)).to_bounded_partition() for p in self.intermediate_shapes()] if self.parent()._skew: l = [([None] * i) for i in shapes[0]] else: l = [] for i in range(1, len(shapes)): p = shapes[i] if (len(l) < len(p)): l += [[]] l_new = [] for j in range(len(l)): l_new += [(l[j] + ([i] * (p[j] - len(l[j]))))] l = l_new return WeakTableau_bounded(l, self.k) def to_factorized_permutation_tableau(self): "\n Return the factorized permutation representation of the weak `k`-tableau ``self``.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: c = t.to_factorized_permutation_tableau(); c\n [s2*s0, s3*s2, s1*s0]\n sage: type(c)\n <class 'sage.combinat.k_tableau.WeakTableaux_factorized_permutation_with_category.element_class'>\n sage: c.to_core_tableau() == t\n True\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: c = t.to_factorized_permutation_tableau(); c\n [s0, s3, s2, s3]\n sage: c._inner_shape\n [2]\n sage: c.to_core_tableau() == t\n True\n\n TESTS::\n\n sage: t = WeakTableau([], 4)\n sage: c = t.to_factorized_permutation_tableau(); c\n [1]\n sage: c._inner_shape\n []\n sage: c.to_core_tableau() == t\n True\n " shapes = [Core(p, (self.k + 1)).to_grassmannian() for p in self.intermediate_shapes()] perms = [(shapes[i] * shapes[(i - 1)].inverse()) for i in range((len(shapes) - 1), 0, (- 1))] return WeakTableau_factorized_permutation(perms, self.k, inner_shape=self.parent()._inner_shape) def residues_of_entries(self, v): '\n Return a list of residues of cells of weak `k`-tableau ``self`` labeled by ``v``.\n\n INPUT:\n\n - ``v`` -- a label of a cell in ``self``\n\n OUTPUT:\n\n - a list of residues\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: t.residues_of_entries(1)\n [0, 1]\n\n sage: t = WeakTableau([[None, None, 1, 1, 4], [1, 4], [3]], 3)\n sage: t.residues_of_entries(1)\n [2, 3]\n ' S = set((((j - i) % (self.k + 1)) for i in range(len(self)) for j in range(len(self[i])) if (self[i][j] == v))) return sorted(S) def dictionary_of_coordinates_at_residues(self, v): '\n Return a dictionary assigning to all residues of ``self`` with label ``v`` a list\n of cells with the given residue.\n\n INPUT:\n\n - ``v`` -- a label of a cell in ``self``\n\n OUTPUT:\n\n - dictionary assigning coordinates in ``self`` to residues\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: t.dictionary_of_coordinates_at_residues(3)\n {0: [(0, 4), (1, 1)], 2: [(2, 0)]}\n\n sage: t = WeakTableau([[None, None, 1, 1, 4], [1, 4], [3]], 3)\n sage: t.dictionary_of_coordinates_at_residues(1)\n {2: [(0, 2)], 3: [(0, 3), (1, 0)]}\n\n sage: t = WeakTableau([], 3)\n sage: t.dictionary_of_coordinates_at_residues(1)\n {}\n ' d = {} for r in self.residues_of_entries(v): d[r] = [] for i in range(len(self)): for j in range(len(self[i])): if ((self[i][j] == v) and (((j - i) % (self.k + 1)) == r)): d[r] += [(i, j)] return d def list_of_standard_cells(self): '\n Return a list of lists of the coordinates of the standard cells of ``self``.\n\n INPUT:\n\n - ``self`` -- a weak `k`-tableau in core representation with partition weight\n\n OUTPUT:\n\n - a list of lists of coordinates\n\n .. WARNING::\n\n This method currently only works for straight weak tableaux with partition\n weight.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.list_of_standard_cells()\n [[(0, 1), (1, 0), (2, 0)], [(0, 0), (0, 2), (1, 1)]]\n sage: t = WeakTableau([[1, 1, 1, 2], [2, 2, 3]], 5)\n sage: t.list_of_standard_cells()\n [[(0, 2), (1, 1), (1, 2)], [(0, 1), (1, 0)], [(0, 0), (0, 3)]]\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: t.list_of_standard_cells()\n [[(0, 1), (1, 0), (2, 0), (0, 5), (3, 0), (4, 0), (5, 0)], [(0, 0), (0, 2), (1, 1), (2, 1), (1, 2), (3, 1)]]\n\n TESTS::\n\n sage: t = WeakTableau([],3)\n sage: t.list_of_standard_cells()\n []\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: t.list_of_standard_cells()\n Traceback (most recent call last):\n ...\n ValueError: This method only works for straight tableaux!\n\n sage: t = WeakTableau([[1,2],[2]], 3)\n sage: t.list_of_standard_cells()\n Traceback (most recent call last):\n ...\n ValueError: This method only works for weak tableaux with partition weight!\n ' if self.parent()._skew: raise ValueError('This method only works for straight tableaux!') if (self.weight() not in Partitions(sum(self.weight()))): raise ValueError('This method only works for weak tableaux with partition weight!') if (not self): return [] mu = Partition(self.weight()).conjugate() already_used = [] out = [] for i in range(self[0].count(1)): standard_cells = [(0, ((self[0].count(1) - i) - 1))] r = ((self[0].count(1) - i) - 1) for v in range(1, mu[i]): D = self.dictionary_of_coordinates_at_residues((v + 1)) new_D = {a: b for (a, b) in D.items() if all(((x not in already_used) for x in b))} r = ((r - min([((self.k + 1) - ((x - r) % (self.k + 1))) for x in new_D])) % (self.k + 1)) standard_cells.append(new_D[r][(- 1)]) already_used += new_D[r] out.append(standard_cells) return out def k_charge(self, algorithm='I'): '\n Return the `k`-charge of ``self``.\n\n INPUT:\n\n - ``algorithm`` -- (default: "I") if "I", computes `k`-charge using the `I`\n algorithm, otherwise uses the `J`-algorithm\n\n OUTPUT:\n\n - a nonnegative integer\n\n For the definition of `k`-charge and the various algorithms to compute it see\n Section 3.3 of [LLMSSZ2013]_.\n\n .. SEEALSO:: :meth:`k_charge_I` and :meth:`k_charge_J`\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.k_charge()\n 2\n sage: t = WeakTableau([[1, 3, 4, 5, 6], [2, 6], [4]], 3)\n sage: t.k_charge()\n 8\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: t.k_charge()\n 12\n\n TESTS::\n\n sage: T = WeakTableaux(4, [13,9,5,3,2,1,1], [4,3,3,2,2,1,1,1])\n sage: T.cardinality()\n 6\n sage: all(t.k_charge_I() == t.k_charge_J() for t in T)\n True\n ' if (algorithm == 'I'): return self.k_charge_I() return self.k_charge_J() def k_charge_I(self): '\n Return the `k`-charge of ``self`` using the `I`-algorithm.\n\n For the definition of `k`-charge and the `I`-algorithm see Section 3.3 of [LLMSSZ2013]_.\n\n OUTPUT:\n\n - a nonnegative integer\n\n .. SEEALSO:: :meth:`k_charge` and :meth:`k_charge_J`\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.k_charge_I()\n 2\n sage: t = WeakTableau([[1, 3, 4, 5, 6], [2, 6], [4]], 3)\n sage: t.k_charge_I()\n 8\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: t.k_charge_I()\n 12\n\n TESTS::\n\n sage: t = WeakTableau([[None, None, 1, 1, 4], [1, 4], [3]], 3)\n sage: t.k_charge_I()\n Traceback (most recent call last):\n ...\n ValueError: k-charge is not defined for skew weak tableaux\n ' if self.parent()._skew: raise ValueError('k-charge is not defined for skew weak tableaux') stt = self.list_of_standard_cells() kch = 0 for sw in stt: Ii = 0 for r in range((len(sw) - 1)): if (sw[r][1] < sw[(r + 1)][1]): Ii += (1 + abs(self.parent().diag(sw[(r + 1)], sw[r]))) else: Ii += (- abs(self.parent().diag(sw[r], sw[(r + 1)]))) kch += Ii return kch def k_charge_J(self): "\n Return the `k`-charge of ``self`` using the `J`-algorithm.\n\n For the definition of `k`-charge and the `J`-algorithm see Section 3.3 of [LLMSSZ2013]_.\n\n OUTPUT:\n\n - a nonnegative integer\n\n .. SEEALSO:: :meth:`k_charge` and :meth:`k_charge_I`\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: t.k_charge_J()\n 2\n sage: t = WeakTableau([[1, 3, 4, 5, 6], [2, 6], [4]], 3)\n sage: t.k_charge_J()\n 8\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: t.k_charge_J()\n 12\n\n TESTS::\n\n sage: t = WeakTableau([[None, None, 1, 1, 4], [1, 4], [3]], 3)\n sage: t.k_charge_I()\n Traceback (most recent call last):\n ...\n ValueError: k-charge is not defined for skew weak tableaux\n\n sage: t = WeakTableau([[1, 1, 2, 3], [2, 4, 4], [3, 6], [5]], 4, representation='bounded')\n sage: t.k_charge() == t.k_charge(algorithm = 'J')\n True\n " if self.parent()._skew: raise ValueError('k-charge is not defined for skew weak tableaux') stt = self.list_of_standard_cells() kch = 0 for sw in stt: Ji = 0 for i in range((len(sw) - 1)): c = ((self._height_of_restricted_subword(sw, (i + 2)) + 1), 0) cdi = self.parent().circular_distance(((- c[0]) % (self.k + 1)), ((sw[i][1] - sw[i][0]) % (self.k + 1))) cdi1 = self.parent().circular_distance(((- c[0]) % (self.k + 1)), ((sw[(i + 1)][1] - sw[(i + 1)][0]) % (self.k + 1))) if (cdi > cdi1): Ji += 1 kch += (Ji + self.parent().diag(sw[(i + 1)], c)) return kch def _height_of_restricted_subword(self, sw, r): '\n Return the row of the highest addable cell of the subtableau of ``self`` with letters `\\le r`\n (excluding letters `r` in standard subwords before ``sw``).\n\n Restrict the weak `k`-tableau ``self`` to letters `\\le r` and remove all letters\n `r` that appeared in a previous standard subword selected by\n :meth:`list_of_standard_cells`.\n\n INPUT:\n\n - ``sw`` -- one of the subwords of standard cells of ``self``\n - ``r`` -- nonnegative integer\n\n OUTPUT:\n\n - a nonnegative integer\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n sage: s = t.list_of_standard_cells()[0]; s\n [(0, 1), (1, 0), (2, 0)]\n sage: t._height_of_restricted_subword(s,2)\n 1\n\n sage: t = WeakTableau([[1, 3, 4, 5, 6], [2, 6], [4]], 3)\n sage: s = t.list_of_standard_cells()[0]; s\n [(0, 0), (1, 0), (0, 1), (2, 0), (0, 3), (1, 1)]\n sage: t._height_of_restricted_subword(s,4)\n 2\n\n sage: t = WeakTableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n sage: s = t.list_of_standard_cells()[0]; s\n [(0, 1), (1, 0), (2, 0), (0, 5), (3, 0), (4, 0), (5, 0)]\n sage: t._height_of_restricted_subword(s,6)\n 4\n ' R = [v for v in self.shape().to_partition().cells() if (self[v[0]][v[1]] < r)] L = [v for v in sw if (self[v[0]][v[1]] <= r)] return max((v[0] for v in (L + R)))
class WeakTableaux_core(WeakTableaux_abstract): '\n The class of (skew) weak `k`-tableaux in the core representation of shape ``shape``\n (as `k+1`-core) and weight ``weight``.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- the shape of the `k`-tableaux represented as a `(k+1)`-core; if the\n tableaux are skew, the shape is a tuple of the outer and inner shape (both as\n `(k+1)`-cores)\n - ``weight`` -- the weight of the `k`-tableaux\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [4,1], [2,2])\n sage: T.list()\n [[[1, 1, 2, 2], [2]]]\n\n sage: T = WeakTableaux(3, [[5,2,1], [2]], [1,1,1,1])\n sage: T.list()\n [[[None, None, 2, 3, 4], [1, 4], [2]],\n [[None, None, 1, 2, 4], [2, 4], [3]],\n [[None, None, 1, 2, 3], [2, 3], [4]]]\n ' @staticmethod def __classcall_private__(cls, k, shape, weight): '\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_core\n sage: T = WeakTableaux_core(3, [2,1], [1,1,1])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_core(3, [[5,2,1], [2]], [1,1,1,1])\n sage: TestSuite(T).run()\n ' if ((shape == []) or (shape[0] in ZZ)): shape = (Core(shape, (k + 1)), Core([], (k + 1))) else: shape = tuple([Core(r, (k + 1)) for r in shape]) return super().__classcall__(cls, k, shape, tuple(weight)) def __init__(self, k, shape, weight): '\n Initializes the parent class of (skew) weak `k`-tableaux in core representation.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``outer_shape`` -- the outer shape of the `k`-tableaux represented as a\n `(k+1)`-core\n - ``weight`` -- the weight of the `k`-tableaux\n - ``inner_shape`` -- the inner shape of the skew `k`-tableaux represented as a\n `(k+1)`-core; for straight tableaux the inner shape does not need to be\n specified (default: [])\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_core\n sage: T = WeakTableaux_core(3, [4,1], [2,2])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_core(3, [[5,2,1], [2]], [1,1,1,1])\n sage: TestSuite(T).run()\n ' self.k = k self._skew = bool(shape[1]) self._outer_shape = shape[0] self._inner_shape = shape[1] self._shape = (self._outer_shape, self._inner_shape) self._weight = weight self._representation = 'core' Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): "\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_core\n sage: repr(WeakTableaux_core(3, [2,1], [1,1,1]))\n 'Core weak 3-Tableaux of (skew) core shape [2, 1] and weight (1, 1, 1)'\n sage: repr(WeakTableaux_core(3, [[5,2,1], [2]], [1,1,1,1]))\n 'Core weak 3-Tableaux of (skew) core shape ([5, 2, 1], [2]) and weight (1, 1, 1, 1)'\n " return ('Core weak %s-Tableaux of (skew) core shape %s and weight %s' % (self.k, self.shape(), self._weight)) def __iter__(self): '\n TESTS::\n\n sage: T = WeakTableaux(3, [4,1], [2,2])\n sage: T.list()\n [[[1, 1, 2, 2], [2]]]\n sage: T = WeakTableaux(3, [5,2,2], [2,2,2,1])\n sage: T.list()\n [[[1, 1, 3, 3, 4], [2, 2], [3, 3]], [[1, 1, 2, 2, 3], [2, 3], [3, 4]]]\n sage: T = WeakTableaux(3, [[5,2,2], [1]], [2,1,2,1])\n sage: T.list()\n [[[None, 1, 3, 3, 4], [1, 2], [3, 3]],\n [[None, 1, 2, 3, 3], [1, 3], [2, 4]],\n [[None, 1, 1, 2, 3], [2, 3], [3, 4]]]\n ' for t in WeakTableaux_bounded(self.k, [self._outer_shape.to_bounded_partition(), self._inner_shape.to_bounded_partition()], self._weight): (yield t.to_core_tableau()) def diag(self, c, ha): '\n Return the number of diagonals strictly between cells ``c`` and ``ha`` of the same residue as ``c``.\n\n INPUT:\n\n - ``c`` -- a cell in the lattice\n - ``ha`` -- another cell in the lattice with bigger row and smaller column than `c`\n\n OUTPUT:\n\n - a nonnegative integer\n\n EXAMPLES::\n\n sage: T = WeakTableaux(4, [5,2,2], [2,2,2,1])\n sage: T.diag((1,2),(4,0))\n 0\n ' return divmod((((c[1] - c[0]) - (ha[1] - ha[0])) - 1), (self.k + 1))[0] def circular_distance(self, cr, r): '\n Return the shortest counterclockwise distance between ``cr`` and ``r`` modulo `k+1`.\n\n INPUT:\n\n - ``cr``, ``r`` -- nonnegative integers between `0` and `k`\n\n OUTPUT:\n\n - a positive integer\n\n EXAMPLES::\n\n sage: T = WeakTableaux(10, [], [])\n sage: T.circular_distance(8, 6)\n 2\n sage: T.circular_distance(8, 8)\n 0\n sage: T.circular_distance(8, 9)\n 10\n ' return (self.k - (((r + self.k) - cr) % (self.k + 1))) Element = WeakTableau_core
class WeakTableau_bounded(WeakTableau_abstract): '\n A (skew) weak `k`-tableau represented in terms of `k`-bounded partitions.\n ' @staticmethod def __classcall_private__(cls, t, k): "\n Implements the shortcut ``WeakTableau_bounded(t, k)`` to ``WeakTableaux_bounded(k, shape, weight)(t)``\n where ``shape`` is the shape of the tableau and ``weight`` is its weight.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_bounded\n sage: t = WeakTableau_bounded([[1,1,2],[2,3],[3]],3)\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_bounded_with_category.element_class'>\n sage: TestSuite(t).run()\n sage: t.parent()._skew\n False\n\n sage: t = WeakTableau_bounded([[None, None, 1], [1, 2], [2]], 3)\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_bounded_with_category.element_class'>\n sage: TestSuite(t).run()\n sage: t.parent()._skew\n True\n " if isinstance(t, cls): return t tab = SkewTableau(list(t)) outer = tab.outer_shape() inner = tab.inner_shape() weight = tuple(tab.weight()) if (outer.conjugate().length() > k): raise ValueError(('The shape of %s is not %s-bounded' % (t, k))) return WeakTableaux_bounded(k, [outer, inner], weight)(t) def __init__(self, parent, t): "\n Initialization of (skew) weak `k`-tableau ``t`` in `k`-bounded representation.\n\n INPUT:\n\n - ``t`` -- weak tableau in `k`-bounded representation; the input is supposed to be\n a list of iterables specifying the rows of the tableau; ``None`` is allowed as an\n entry for skew weak `k`-tableaux\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_bounded, WeakTableaux_bounded\n sage: c = WeakTableau_bounded([[1,1,2],[2,3],[3]],3)\n sage: T = WeakTableaux_bounded(3,[3,2,1],[2,2,2])\n sage: t = T([[1,1,2],[2,3],[3]]); t\n [[1, 1, 2], [2, 3], [3]]\n sage: c == t\n True\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_bounded_with_category.element_class'>\n sage: t.parent()\n Bounded weak 3-Tableaux of (skew) 3-bounded shape [3, 2, 1] and weight (2, 2, 2)\n sage: TestSuite(t).run()\n\n sage: t = WeakTableau_bounded([[None, None, 1], [2, 4], [3]], 3)\n sage: t.shape()\n ([3, 2, 1], [2])\n sage: t.weight()\n (1, 1, 1, 1)\n sage: TestSuite(t).run()\n\n sage: t = T([[1,1,3],[2,2],[3]])\n Traceback (most recent call last):\n ...\n ValueError: This is not a proper weak 3-tableau\n " k = parent.k self.k = k if (parent._outer_shape.conjugate().length() > k): raise ValueError(('%s is not a %s-bounded tableau' % (t, k))) ClonableList.__init__(self, parent, [list(r) for r in t]) def _repr_diagram(self): "\n Return a string representation of ``self`` as a diagram.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: print(t._repr_diagram())\n . . 1\n 2 4\n 3\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: print(t._repr_diagram())\n 1 1 1\n 2 2\n 3\n " t = SkewTableau(list(self)) return t._repr_diagram() def shape_core(self): "\n Return the shape of ``self`` as `(k+1)`-core.\n\n When the tableau is straight, the outer shape is returned as a `(k+1)`-core.\n When the tableau is skew, the tuple of the outer and inner shape is returned as\n `(k+1)`-cores.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t.shape_core()\n [5, 2, 1]\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.shape_core()\n ([5, 2, 1], [2])\n " if self.parent()._skew: return tuple([r.to_core(self.k) for r in self.shape_bounded()]) return self.shape_bounded().to_core(self.k) def shape_bounded(self): "\n Return the shape of ``self`` as `k`-bounded partition.\n\n When the tableau is straight, the outer shape is returned as a `k`-bounded\n partition. When the tableau is skew, the tuple of the outer and inner shape is\n returned as `k`-bounded partitions.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t.shape_bounded()\n [3, 2, 1]\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.shape_bounded()\n ([3, 2, 1], [2])\n " return self.shape() def check(self): "\n Check that ``self`` is a valid weak `k`-tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1,1],[2]], 2, representation = 'bounded')\n sage: t.check()\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.check()\n\n TESTS::\n\n sage: t = WeakTableau([[1,1,3],[2,2],[3]], 3, representation = 'bounded')\n Traceback (most recent call last):\n ...\n ValueError: This is not a proper weak 3-tableau\n\n sage: T = WeakTableaux(3, [3,1], [2,1], representation = 'bounded')\n sage: t = T([[None, 1,1], [2]])\n Traceback (most recent call last):\n ...\n ValueError: The inner shape of the parent does not agree with the inner shape of the tableau!\n\n sage: t = WeakTableau([[1,1],[1]], 3, representation = 'bounded')\n Traceback (most recent call last):\n ...\n ValueError: The tableaux is not semistandard!\n " t = SkewTableau(list(self)) if (t not in SemistandardSkewTableaux()): raise ValueError('The tableaux is not semistandard!') if (not (self.parent()._weight == tuple(t.weight()))): raise ValueError('The weight of the parent does not agree with the weight of the tableau!') outer = t.outer_shape() inner = t.inner_shape() if (self.parent()._outer_shape != outer): raise ValueError('The outer shape of the parent does not agree with the outer shape of the tableau!') if (self.parent()._inner_shape != inner): raise ValueError('The inner shape of the parent does not agree with the inner shape of the tableau!') if (not t.is_k_tableau(self.k)): raise ValueError(('This is not a proper weak %s-tableau' % self.k)) def _is_k_tableau(self): "\n Checks whether ``self`` is a valid weak `k`-tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1,1,1],[2,2],[3]], 3, representation = 'bounded')\n sage: t._is_k_tableau()\n True\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t._is_k_tableau()\n True\n " shapes = self.intermediate_shapes() kshapes = [la.k_conjugate(self.k) for la in shapes] return all((kshapes[(i + 1)].contains(kshapes[i]) for i in range((len(shapes) - 1)))) def to_core_tableau(self): "\n Return the weak `k`-tableau ``self`` where the shape of each restricted tableau is a `(k+1)`-core.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1,1,2,4],[2,3,5],[3,4],[5,6],[6],[7]], 4, representation = 'bounded')\n sage: c = t.to_core_tableau(); c\n [[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]]\n sage: type(c)\n <class 'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class'>\n sage: t = WeakTableau([], 4, representation = 'bounded')\n sage: t.to_core_tableau()\n []\n\n sage: from sage.combinat.k_tableau import WeakTableau_bounded\n sage: t = WeakTableau([[1,1,2],[2,3],[3]], 3, representation = 'bounded')\n sage: WeakTableau_bounded.from_core_tableau(t.to_core_tableau(),3)\n [[1, 1, 2], [2, 3], [3]]\n sage: t == WeakTableau_bounded.from_core_tableau(t.to_core_tableau(),3)\n True\n\n sage: t = WeakTableau([[None, None, 1], [2, 4], [3]], 3, representation = 'bounded')\n sage: t.to_core_tableau()\n [[None, None, 1, 2, 4], [2, 4], [3]]\n sage: t == WeakTableau_bounded.from_core_tableau(t.to_core_tableau(),3)\n True\n " shapes = [p.to_core(self.k) for p in self.intermediate_shapes()] if self.parent()._skew: l = [([None] * i) for i in shapes[0]] else: l = [] for i in range(1, len(shapes)): p = shapes[i] if (len(l) < len(p)): l += [[]] l_new = [] for j in range(len(l)): l_new += [(l[j] + ([i] * (p[j] - len(l[j]))))] l = l_new return WeakTableau_core(l, self.k) @classmethod def from_core_tableau(cls, t, k): '\n Construct weak `k`-bounded tableau from in `k`-core tableau.\n\n EXAMPLES::\n\n sage: from sage.combinat.k_tableau import WeakTableau_bounded\n sage: WeakTableau_bounded.from_core_tableau([[1, 1, 2, 2, 3], [2, 3], [3]], 3)\n [[1, 1, 2], [2, 3], [3]]\n\n sage: WeakTableau_bounded.from_core_tableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n [[None, None, 3], [1, 4], [2]]\n\n sage: WeakTableau_bounded.from_core_tableau([[None,2,3],[3]], 2)\n [[None, 2], [3]]\n ' t = SkewTableau(list(t)) shapes = [Core(p, (k + 1)).to_bounded_partition() for p in intermediate_shapes(t)] if (t.inner_shape() == Partition([])): l = [] else: l = [([None] * i) for i in shapes[0]] for i in range(1, len(shapes)): p = shapes[i] if (len(l) < len(p)): l += [[]] l_new = [] for j in range(len(l)): l_new += [(l[j] + ([i] * (p[j] - len(l[j]))))] l = l_new return cls(l, k) def k_charge(self, algorithm='I'): '\n Return the `k`-charge of ``self``.\n\n INPUT:\n\n - ``algorithm`` -- (default: "I") if "I", computes `k`-charge using the `I`\n algorithm, otherwise uses the `J`-algorithm\n\n OUTPUT:\n\n - a nonnegative integer\n\n For the definition of `k`-charge and the various algorithms to compute it see Section 3.3 of [LLMSSZ2013]_.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[1, 1, 2], [2, 3], [3]], 3, representation = \'bounded\')\n sage: t.k_charge()\n 2\n sage: t = WeakTableau([[1, 3, 5], [2, 6], [4]], 3, representation = \'bounded\')\n sage: t.k_charge()\n 8\n sage: t = WeakTableau([[1, 1, 2, 4], [2, 3, 5], [3, 4], [5, 6], [6], [7]], 4, representation = \'bounded\')\n sage: t.k_charge()\n 12\n ' return self.to_core_tableau().k_charge(algorithm=algorithm)
class WeakTableaux_bounded(WeakTableaux_abstract): "\n The class of (skew) weak `k`-tableaux in the bounded representation of shape ``shape``\n (as `k`-bounded partition or tuple of `k`-bounded partitions in the skew case) and\n weight ``weight``.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- the shape of the `k`-tableaux represented as a `k`-bounded partition;\n if the tableaux are skew, the shape is a tuple of the outer and inner shape each\n represented as a `k`-bounded partition\n - ``weight`` -- the weight of the `k`-tableaux\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [3,1], [2,2], representation = 'bounded')\n sage: T.list()\n [[[1, 1, 2], [2]]]\n\n sage: T = WeakTableaux(3, [[3,2,1], [2]], [1,1,1,1], representation = 'bounded')\n sage: T.list()\n [[[None, None, 3], [1, 4], [2]],\n [[None, None, 1], [2, 4], [3]],\n [[None, None, 1], [2, 3], [4]]]\n " @staticmethod def __classcall_private__(cls, k, shape, weight): '\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_bounded\n sage: T = WeakTableaux_bounded(3, [2,1], [1,1,1])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_bounded(3, [[3,2,1], [2]], [1,1,1,1])\n sage: TestSuite(T).run()\n ' if ((shape == []) or (shape[0] in ZZ)): shape = (Partition(shape), Partition([])) else: shape = tuple([Partition(r) for r in shape]) return super().__classcall__(cls, k, shape, tuple(weight)) def __init__(self, k, shape, weight): '\n Initializes the parent class of (skew) weak `k`-tableaux in bounded representation.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- the shape of the `k`-tableaux represented as a `k`-bounded\n partition; if the tableaux are skew, the shape is a tuple of the outer and inner\n shape each represented as a `k`-bounded partition\n - ``weight`` -- the weight of the `k`-tableaux\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_bounded\n sage: T = WeakTableaux_bounded(3, [3,1], [2,2])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_bounded(3, [[3,2,1], [2]], [1,1,1,1])\n sage: TestSuite(T).run()\n ' self.k = k self._skew = bool(shape[1]) self._outer_shape = Partition(shape[0]) self._inner_shape = Partition(shape[1]) self._shape = (self._outer_shape, self._inner_shape) self._weight = tuple(weight) self._representation = 'bounded' Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): "\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_bounded\n sage: repr(WeakTableaux_bounded(3, [2,1], [1,1,1]))\n 'Bounded weak 3-Tableaux of (skew) 3-bounded shape [2, 1] and weight (1, 1, 1)'\n sage: repr(WeakTableaux_bounded(3, [[3,2,1], [2]], [1,1,1,1]))\n 'Bounded weak 3-Tableaux of (skew) 3-bounded shape ([3, 2, 1], [2]) and weight (1, 1, 1, 1)'\n " return ('Bounded weak %s-Tableaux of (skew) %s-bounded shape %s and weight %s' % (self.k, self.k, self.shape(), self._weight)) def __iter__(self): "\n TESTS::\n\n sage: T = WeakTableaux(3, [3,1], [2,2], representation = 'bounded')\n sage: T.list()\n [[[1, 1, 2], [2]]]\n sage: T = WeakTableaux(3, [3,2,2], [2,2,2,1], representation = 'bounded')\n sage: T.list()\n [[[1, 1, 4], [2, 2], [3, 3]], [[1, 1, 2], [2, 3], [3, 4]]]\n sage: T = WeakTableaux(3, [[3,2,2], [1]], [2,1,2,1], representation = 'bounded')\n sage: T.list()\n [[[None, 1, 4], [1, 2], [3, 3]],\n [[None, 1, 3], [1, 3], [2, 4]],\n [[None, 1, 1], [2, 3], [3, 4]]]\n " for t in SemistandardSkewTableaux([self._outer_shape, self._inner_shape], self._weight): if t.is_k_tableau(self.k): (yield self(t)) Element = WeakTableau_bounded
class WeakTableau_factorized_permutation(WeakTableau_abstract): '\n A weak (skew) `k`-tableau represented in terms of factorizations of affine\n permutations into cyclically decreasing elements.\n ' @staticmethod def straighten_input(t, k): "\n Straightens input.\n\n INPUT:\n\n - ``t`` -- a list of reduced words or a list of elements in the Weyl group of type\n `A_k^{(1)}`\n - ``k`` -- a positive integer\n\n EXAMPLES::\n\n sage: from sage.combinat.k_tableau import WeakTableau_factorized_permutation\n sage: WeakTableau_factorized_permutation.straighten_input([[2,0],[3,2],[1,0]], 3)\n (s2*s0, s3*s2, s1*s0)\n sage: W = WeylGroup(['A',4,1])\n sage: WeakTableau_factorized_permutation.straighten_input([W.an_element(),W.an_element()], 4)\n (s0*s1*s2*s3*s4, s0*s1*s2*s3*s4)\n\n TESTS::\n\n sage: WeakTableau_factorized_permutation.straighten_input([W.an_element(),W.an_element()], 3)\n Traceback (most recent call last):\n ...\n ValueError: inconsistent number of rows: should be 4 but got 5\n " W = WeylGroup(['A', k, 1], prefix='s') if (len(t) > 0): if isinstance(t[0], (list, tuple)): w_tuple = tuple((W.from_reduced_word(p) for p in t)) else: w_tuple = tuple((W(r) for r in t)) else: w_tuple = tuple([W.one()]) return w_tuple @staticmethod def __classcall_private__(cls, t, k, inner_shape=[]): "\n Implements the shortcut ``WeakTableau_factorized_permutation(t, k)`` to\n ``WeakTableaux_factorized_permutation(k, shape, weight)(t)``\n where ``shape`` is the shape of the tableau as a `(k+1)`-core (or a tuple of\n `(k+1)`-cores if the tableau is skew) and ``weight`` is its weight.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_factorized_permutation\n sage: t = WeakTableau_factorized_permutation([[2,0],[3,2],[1,0]], 3)\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_factorized_permutation_with_category.element_class'>\n sage: TestSuite(t).run()\n\n sage: t = WeakTableau_factorized_permutation([[0,3],[2,1]], 3, inner_shape = [1,1])\n sage: t.check()\n sage: TestSuite(t).run()\n\n sage: t = WeakTableau_factorized_permutation([], 3); t\n [1]\n sage: t.check()\n sage: TestSuite(t).run()\n " if isinstance(t, cls): return t W = WeylGroup(['A', k, 1], prefix='s') w = cls.straighten_input(t, k) weight = tuple((w[i].length() for i in range((len(w) - 1), (- 1), (- 1)))) inner_shape = Core(inner_shape, (k + 1)) outer_shape = (W.prod(w) * W(inner_shape.to_grassmannian())).affine_grassmannian_to_core() return WeakTableaux_factorized_permutation(k, [outer_shape, inner_shape], weight)(w) def __init__(self, parent, t): "\n Initialization of (skew) weak `k`-tableau ``t`` in factorized permutation representation.\n\n INPUT:\n\n - ``t`` -- (skew) weak tableau in factorized permutation representation; the input\n can either be a list of reduced words of cyclically decreasing elements, or a\n list of cyclically decreasing elements; when the tableau is skew, the inner\n shape needs to be specified as a `(k+1)`-core\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableau_factorized_permutation, WeakTableaux_factorized_permutation\n sage: c = WeakTableau_factorized_permutation([[2,0],[3,2],[1,0]], 3)\n sage: T = WeakTableaux_factorized_permutation(3, [5,2,1],[2,2,2])\n sage: t = T([[2,0],[3,2],[1,0]]); t\n [s2*s0, s3*s2, s1*s0]\n sage: c == t\n True\n sage: type(t)\n <class 'sage.combinat.k_tableau.WeakTableaux_factorized_permutation_with_category.element_class'>\n sage: t.parent()\n Factorized permutation (skew) weak 3-Tableaux of shape [5, 2, 1] and weight (2, 2, 2)\n sage: TestSuite(t).run()\n\n sage: t = WeakTableau_factorized_permutation([[2,0],[3,2]], 3, inner_shape = [2]); t\n [s2*s0, s3*s2]\n sage: t._inner_shape\n [2]\n sage: t.weight()\n (2, 2)\n sage: t.shape()\n ([5, 2, 1], [2])\n sage: TestSuite(t).run()\n\n sage: t = T([[3,0],[0,3],[1,0]])\n Traceback (most recent call last):\n ...\n ValueError: The outer shape of the parent does not agree with the outer shape of the tableau!\n\n sage: t = WeakTableau_factorized_permutation([], 3); t\n [1]\n sage: t.parent()._outer_shape\n []\n sage: t.parent()._weight\n (0,)\n " self.k = parent.k self._inner_shape = parent._inner_shape ClonableList.__init__(self, parent, self.straighten_input(t, parent.k)) def shape_core(self): "\n Return the shape of ``self`` as a `(k+1)`-core.\n\n When the tableau is straight, the outer shape is returned as a core.\n When the tableau is skew, the tuple of the outer and inner shape is returned as\n cores.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t.shape_core()\n [5, 2, 1]\n\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.shape()\n ([5, 2, 1], [2])\n " return self.shape() def shape_bounded(self): "\n Return the shape of ``self`` as a `k`-bounded partition.\n\n When the tableau is straight, the outer shape is returned as a `k`-bounded\n partition. When the tableau is skew, the tuple of the outer and inner shape is\n returned as `k`-bounded partitions.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t.shape_bounded()\n [3, 2, 1]\n\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.shape_bounded()\n ([3, 2, 1], [2])\n " if self.parent()._skew: return tuple([r.to_bounded_partition() for r in self.shape_core()]) return self.shape_core().to_bounded_partition() def check(self): "\n Check that ``self`` is a valid weak `k`-tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t.check()\n\n TESTS::\n\n sage: t = WeakTableau([[2,0],[3,2]], 3, representation = 'factorized_permutation')\n Traceback (most recent call last):\n ...\n ValueError: this only works on type 'A' affine Grassmannian elements\n\n sage: T = WeakTableaux(3, [4,1], [2,1], representation = 'factorized_permutation')\n sage: t = T([[2],[1],[0]])\n Traceback (most recent call last):\n ...\n ValueError: The weight of the parent does not agree with the weight of the tableau!\n " weight = tuple((self[i].length() for i in range((len(self) - 1), (- 1), (- 1)))) if (not (self.parent()._weight == weight)): raise ValueError('The weight of the parent does not agree with the weight of the tableau!') W = self[0].parent() outer = (W.prod(self) * W(self._inner_shape.to_grassmannian())).affine_grassmannian_to_core() if (self.parent()._outer_shape != outer): raise ValueError('The outer shape of the parent does not agree with the outer shape of the tableau!') if (not self._is_k_tableau()): raise ValueError(('This is not a proper weak %s-tableau' % self.k)) def _is_k_tableau(self): "\n Checks whether ``self`` is a valid weak `k`-tableau.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[2],[0,3],[2,1,0]], 3, representation = 'factorized_permutation')\n sage: t._is_k_tableau()\n True\n\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t._is_k_tableau()\n True\n " W = self[0].parent() if (W.prod(self) * W(self.parent()._inner_shape.to_grassmannian())).is_affine_grassmannian(): return all((r.is_pieri_factor() for r in self)) return False def to_core_tableau(self): "\n Return the weak `k`-tableau ``self`` where the shape of each restricted tableau is a `(k+1)`-core.\n\n EXAMPLES::\n\n sage: t = WeakTableau([[0], [3,1], [2,1], [0,4], [3,0], [4,2], [1,0]], 4, representation = 'factorized_permutation'); t\n [s0, s3*s1, s2*s1, s0*s4, s3*s0, s4*s2, s1*s0]\n sage: c = t.to_core_tableau(); c\n [[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]]\n sage: type(c)\n <class 'sage.combinat.k_tableau.WeakTableaux_core_with_category.element_class'>\n sage: t = WeakTableau([[]], 4, representation = 'factorized_permutation'); t\n [1]\n sage: t.to_core_tableau()\n []\n\n sage: from sage.combinat.k_tableau import WeakTableau_factorized_permutation\n sage: t = WeakTableau([[2,0],[3,2],[1,0]], 3, representation = 'factorized_permutation')\n sage: WeakTableau_factorized_permutation.from_core_tableau(t.to_core_tableau(), 3)\n [s2*s0, s3*s2, s1*s0]\n sage: t == WeakTableau_factorized_permutation.from_core_tableau(t.to_core_tableau(), 3)\n True\n\n sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation')\n sage: t.to_core_tableau()\n [[None, None, 1, 1, 2], [1, 2], [2]]\n sage: t == WeakTableau_factorized_permutation.from_core_tableau(t.to_core_tableau(), 3)\n True\n " W = self[0].parent() factor = W(self._inner_shape.to_grassmannian()) shapes = [factor] for i in range((len(self) - 1), (- 1), (- 1)): factor = (self[i] * factor) shapes += [factor.affine_grassmannian_to_core()] if self.parent()._skew: l = [([None] * i) for i in self._inner_shape] else: l = [] for i in range(1, len(shapes)): p = shapes[i] if (len(l) < len(p)): l += [[]] l_new = [] for j in range(len(l)): l_new += [(l[j] + ([i] * (p[j] - len(l[j]))))] l = l_new return WeakTableau_core(l, self.k) @classmethod def from_core_tableau(cls, t, k): '\n Construct weak factorized affine permutation tableau from a `k`-core tableau.\n\n EXAMPLES::\n\n sage: from sage.combinat.k_tableau import WeakTableau_factorized_permutation\n sage: WeakTableau_factorized_permutation.from_core_tableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n [s2*s0, s3*s2, s1*s0]\n sage: WeakTableau_factorized_permutation.from_core_tableau([[1, 1, 2, 3, 4, 4, 5, 5, 6], [2, 3, 5, 5, 6], [3, 4, 7], [5, 6], [6], [7]], 4)\n [s0, s3*s1, s2*s1, s0*s4, s3*s0, s4*s2, s1*s0]\n sage: WeakTableau_factorized_permutation.from_core_tableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3)\n [s0*s3, s2*s1]\n ' t = SkewTableau(list(t)) shapes = [Core(p, (k + 1)).to_grassmannian() for p in intermediate_shapes(t)] perms = [(shapes[i] * shapes[(i - 1)].inverse()) for i in range((len(shapes) - 1), 0, (- 1))] return cls(perms, k, inner_shape=t.inner_shape()) def k_charge(self, algorithm='I'): "\n Return the `k`-charge of ``self``.\n\n OUTPUT:\n\n - a nonnegative integer\n\n EXAMPLES::\n\n sage: t = WeakTableau([[2,0],[3,2],[1,0]], 3, representation = 'factorized_permutation')\n sage: t.k_charge()\n 2\n sage: t = WeakTableau([[0],[3],[2],[1],[3],[0]], 3, representation = 'factorized_permutation')\n sage: t.k_charge()\n 8\n sage: t = WeakTableau([[0],[3,1],[2,1],[0,4],[3,0],[4,2],[1,0]], 4, representation = 'factorized_permutation')\n sage: t.k_charge()\n 12\n " return self.to_core_tableau().k_charge(algorithm=algorithm)
class WeakTableaux_factorized_permutation(WeakTableaux_abstract): "\n The class of (skew) weak `k`-tableaux in the factorized permutation representation of shape ``shape`` (as `k+1`-core\n or tuple of `(k+1)`-cores in the skew case) and weight ``weight``.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- the shape of the `k`-tableaux represented as a `(k+1)`-core;\n in the skew case the shape is a tuple of the outer and inner shape both as `(k+1)`-cores\n - ``weight`` -- the weight of the `k`-tableaux\n\n EXAMPLES::\n\n sage: T = WeakTableaux(3, [4,1], [2,2], representation = 'factorized_permutation')\n sage: T.list()\n [[s3*s2, s1*s0]]\n\n sage: T = WeakTableaux(4, [[6,2,1], [2]], [2,1,1,1], representation = 'factorized_permutation')\n sage: T.list()\n [[s0, s4, s3, s4*s2], [s0, s3, s4, s3*s2], [s3, s0, s4, s3*s2]]\n " @staticmethod def __classcall_private__(cls, k, shape, weight): '\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_factorized_permutation\n sage: T = WeakTableaux_factorized_permutation(3, [2,1], [1,1,1])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_factorized_permutation(4, [[6,2,1], [2]], [2,1,1,1])\n sage: TestSuite(T).run() # long time\n ' if ((shape == []) or (shape[0] in ZZ)): shape = (Core(shape, (k + 1)), Core([], (k + 1))) else: shape = tuple([Core(r, (k + 1)) for r in shape]) return super().__classcall__(cls, k, shape, tuple(weight)) def __init__(self, k, shape, weight): '\n Initializes the parent class of weak `k`-tableaux in factorized permutation representation.\n\n INPUT:\n\n - ``k`` -- positive integer\n - ``shape`` -- the shape of the `k`-tableaux represented as a `(k+1)`-core;\n in the skew case the shape is a tuple of the outer and inner shape both as\n `(k+1)`-cores\n - ``weight`` -- the weight of the `k`-tableaux\n\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_factorized_permutation\n sage: T = WeakTableaux_factorized_permutation(3, [4,1], [2,2])\n sage: TestSuite(T).run()\n sage: T = WeakTableaux_factorized_permutation(4, [[6,2,1], [2]], [2,1,1,1])\n sage: TestSuite(T).run() # long time\n ' self.k = k self._skew = bool(shape[1]) self._outer_shape = Core(shape[0], (k + 1)) self._inner_shape = Core(shape[1], (k + 1)) self._shape = (self._outer_shape, self._inner_shape) self._weight = weight self._representation = 'factorized_permutation' Parent.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): "\n TESTS::\n\n sage: from sage.combinat.k_tableau import WeakTableaux_factorized_permutation\n sage: repr(WeakTableaux_factorized_permutation(3, [2,1], [1,1,1]))\n 'Factorized permutation (skew) weak 3-Tableaux of shape [2, 1] and weight (1, 1, 1)'\n sage: repr(WeakTableaux_factorized_permutation(4, [[6,2,1], [2]], [2,1,1,1]))\n 'Factorized permutation (skew) weak 4-Tableaux of shape ([6, 2, 1], [2]) and weight (2, 1, 1, 1)'\n " return ('Factorized permutation (skew) weak %s-Tableaux of shape %s and weight %s' % (self.k, self.shape(), self._weight)) def __iter__(self): "\n TESTS::\n\n sage: T = WeakTableaux(3, [4,1], [2,2], representation = 'factorized_permutation')\n sage: T.list()\n [[s3*s2, s1*s0]]\n sage: T = WeakTableaux(3, [5,2,2], [2,2,2,1], representation = 'factorized_permutation')\n sage: T.list()\n [[s0, s3*s2, s0*s3, s1*s0], [s3, s2*s0, s3*s2, s1*s0]]\n sage: T = WeakTableaux(4, [[6,2,1], [2]], [2,1,1,1], representation = 'factorized_permutation')\n sage: T.list()\n [[s0, s4, s3, s4*s2], [s0, s3, s4, s3*s2], [s3, s0, s4, s3*s2]]\n " for t in WeakTableaux_core(self.k, self.shape(), self._weight): (yield WeakTableau_factorized_permutation.from_core_tableau(t, self.k)) Element = WeakTableau_factorized_permutation
class StrongTableau(ClonableList, metaclass=InheritComparisonClasscallMetaclass): "\n A (standard) strong `k`-tableau is a (saturated) chain in Bruhat order.\n\n Combinatorially, it is a sequence of embedded `k+1`-cores (subject to some conditions)\n together with a set of markings.\n\n A strong cover in terms of cores corresponds to certain translated ribbons. A marking\n corresponds to the choice of one of the translated ribbons, which is indicated by\n marking the head (southeast most cell in French notation) of the chosen ribbon. For\n more information, see [LLMS2006]_ and [LLMSSZ2013]_.\n\n In Sage, a strong `k`-tableau is created by specifying `k`, a standard strong\n tableau together with its markings, and a weight `\\mu`. Here the standard tableau is\n represented by a sequence of `k+1`-cores\n\n .. MATH::\n\n \\lambda^{(0)} \\subseteq \\lambda^{(1)} \\subseteq \\cdots \\subseteq \\lambda^{(m)}\n\n where each of the `\\lambda^{(i)}` is a `k+1`-core. The standard tableau is a filling\n of the diagram for the core `\\lambda^{(m)}/\\lambda^{(0)}` where a strong cover\n is represented by letters `\\pm i` in the skew shape `\\lambda^{(i)}/\\lambda^{(i-1)}`.\n Each skew `(k+1)`-core `\\lambda^{(i)}/\\lambda^{(i-1)}` is a ribbon or multiple\n copies of the same ribbon which are separated by `k+1` diagonals. Precisely one of\n the copies of the ribbons will be marked in the largest diagonal of the connected\n component (the 'head' of the ribbon). The marked cells are indicated by negative\n signs.\n\n The strong tableau is stored as a standard strong marked tableau (referred to as the\n standard part of the strong tableau) and a vector representing the weight.\n\n EXAMPLES::\n\n sage: StrongTableau( [[-1, -2, -3], [3]], 2, [3] )\n [[-1, -1, -1], [1]]\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])\n [[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4]]\n\n Alternatively, the strong `k`-tableau can also be entered directly in semistandard\n format and then the standard tableau and the weight are computed and stored::\n\n sage: T = StrongTableau([[-1,-1,-1],[1]], 2); T\n [[-1, -1, -1], [1]]\n sage: T.to_standard_list()\n [[-1, -2, -3], [3]]\n sage: T.weight()\n (3,)\n sage: T = StrongTableau([[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4]], 3); T\n [[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4]]\n sage: T.to_standard_list()\n [[-1, -2, -4, -7], [-3, 6, -6, 8], [4, 7], [-5, -8]]\n sage: T.weight()\n (2, 2, 3, 1)\n " def __init__(self, parent, T): '\n INPUT:\n\n - ``parent`` -- an instance of ``StrongTableaux``\n - ``T`` -- standard marked strong (possibly skew) `k`-tableau or a semistandard\n marked strong (possibly skew) `k`-tableau with inner cells represented by\n ``None``\n\n EXAMPLES::\n\n sage: T = StrongTableau( [[-1, -2, -3]], 3 ); T\n [[-1, -2, -3]]\n sage: T\n [[-1, -2, -3]]\n sage: T.weight()\n (1, 1, 1)\n sage: T.size()\n 3\n sage: T.parent()\n Set of strong 3-tableaux of shape [3] and of weight (1, 1, 1)\n sage: StrongTableau( [[-1, -2, -3], [3]], 2 )\n [[-1, -2, -3], [3]]\n sage: StrongTableau( [[-1, -1, 2], [-2]], 2 )\n [[-1, -1, 2], [-2]]\n sage: T = StrongTableau( [[-1, -2, 3], [-3]], 2, weight=[2,1] ); T\n [[-1, -1, 2], [-2]]\n sage: T = StrongTableau( [[-1, -2, 3], [-3]], 2, weight=[0,2,1] ); T\n [[-2, -2, 3], [-3]]\n sage: T.weight()\n (0, 2, 1)\n sage: T.size()\n 3\n sage: T.parent()\n Set of strong 2-tableaux of shape [3, 1] and of weight (0, 2, 1)\n sage: StrongTableau( [[-1, -2, 3], [-3]], 2, weight=[1,2] )\n Traceback (most recent call last):\n ...\n ValueError: The weight=(1, 2) and the markings on the standard tableau=[[-1, -2, 3], [-3]] do not agree.\n sage: StrongTableau( [[None, None, -2, -4], [None, None], [-1, -3], [2, 4], [-5], [5], [5], [5]], 4 )\n [[None, None, -2, -4], [None, None], [-1, -3], [2, 4], [-5], [5], [5], [5]]\n sage: StrongTableau( [[None, None, -2, -4], [None, None], [-1, -3], [2, 4], [-5], [5], [5], [5]], 4, weight=[2,2,1] )\n [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]]\n sage: StrongTableau( [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]]\n\n TESTS::\n\n sage: T = StrongTableau([], 3); T\n []\n sage: T.weight()\n ()\n sage: T.parent()\n Set of strong 3-tableaux of shape [] and of weight ()\n sage: T = StrongTableau( [[None, None], [None, None]], 4, weight=() ); T\n [[None, None], [None, None]]\n sage: T.size()\n 0\n ' self.k = parent.k self._tableau = T ClonableList.__init__(self, parent, T) @staticmethod def __classcall_private__(cls, T, k, weight=None): '\n Straighten input and implement the shortcut ``StrongTableau(T, k, weight=None)``\n to ``StrongTableaux(k, shape, weight)(T)``.\n\n TESTS::\n\n sage: t = StrongTableau( [[-1, -2, -3]], 3 )\n sage: t.parent()\n Set of strong 3-tableaux of shape [3] and of weight (1, 1, 1)\n sage: TestSuite(t).run()\n sage: t = StrongTableau( [[-1, -2, 3], [-3]], 2, weight=[2,1] )\n sage: TestSuite(t).run()\n sage: StrongTableau([[-1,-1,-1]], 3)\n [[-1, -1, -1]]\n sage: StrongTableau([[None, None, None], [None]], 2)\n [[None, None, None], [None]]\n\n sage: StrongTableau([[-1, -2, -2], [1]], 2)\n Traceback (most recent call last):\n ...\n ValueError: Unable to parse strong marked tableau : [[-1, -2, -2], [1]]\n\n sage: StrongTableau([[-1,-1,-1,-1]], 3)\n Traceback (most recent call last):\n ...\n ValueError: [4] is not a 4-core\n\n sage: StrongTableau([[-1, -2], [2]], 3)\n Traceback (most recent call last):\n ...\n ValueError: The marks in [[-1, -2], [2]] are not correctly placed.\n\n sage: StrongTableau([[None, None, None], [None]], 3)\n Traceback (most recent call last):\n ...\n ValueError: [3, 1] is not a 4-core\n\n sage: StrongTableau([[None, -1, 2], [-2]], 2, [2])\n Traceback (most recent call last):\n ...\n ValueError: The weight=(2,) and the markings on the standard tableau=[[None, -1, 2], [-2]] do not agree.\n ' if isinstance(T, cls): return T outer_shape = Core([len(t) for t in T], (k + 1)) loop = (row.count(None) for row in T) inner_shape = Core([x for x in loop if x], (k + 1)) Te = ([v for row in T for v in row if (v is not None)] + [0]) count_marks = tuple((Te.count((- (i + 1))) for i in range((- min(Te))))) if (not all(((v == 1) for v in count_marks))): if ((weight is not None) and (tuple(weight) != count_marks)): raise ValueError(('Weight = %s and tableau = %s do not agree' % (weight, T))) tijseq = StrongTableaux.marked_CST_to_transposition_sequence(T, k) if ((tijseq is None) or (len(tijseq) < sum(list(count_marks)))): raise ValueError(('Unable to parse strong marked tableau : %s' % T)) T = StrongTableaux.transpositions_to_standard_strong(tijseq, k, [([None] * r) for r in inner_shape]) T = T.set_weight(count_marks) return T elif (weight is not None): count_marks = tuple(weight) return StrongTableaux.__classcall__(StrongTableaux, k, (outer_shape, inner_shape), count_marks)(T) def check(self): '\n Check that ``self`` is a valid strong `k`-tableau.\n\n This function verifies that the outer and inner shape of the parent class is equal to\n the outer and inner shape of the tableau, that the tableau portion of ``self`` is\n a valid standard tableau, that the marks are placed correctly and that the size\n and weight agree.\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -1, -2], [2]], 2)\n sage: T.check()\n sage: T = StrongTableau([[None, None, 2, -4, -4], [-1, 4], [-2]], 3)\n sage: T.check()\n\n TESTS::\n\n sage: ST = StrongTableaux(2, [3,1], [1,1,1,1])\n sage: ST([[-1,-2,3],[-3]])\n Traceback (most recent call last):\n ...\n ValueError: The size of the tableau [[-1, -2, 3], [-3]] and weight (1, 1, 1, 1) do not match\n sage: ST([[-1,-3],[-2],[3]])\n Traceback (most recent call last):\n ...\n ValueError: The outer shape of the parent does not agree with the outer shape of the tableau!\n\n sage: StrongTableau([[-1, -2, 2], [1]], 2)\n Traceback (most recent call last):\n ...\n ValueError: The marks in [[-1, -2, 2], [1]] are not correctly placed.\n\n sage: StrongTableau([[-1, -2, 3], [3]], 2)\n Traceback (most recent call last):\n ...\n ValueError: The marks in [[-1, -2, 3], [3]] are not correctly placed.\n\n sage: StrongTableau([[-1,-2,-4,7],[-3,6,-6,8],[4,-7],[-5,-8]], 3, [2,2,3,1])\n Traceback (most recent call last):\n ...\n ValueError: The weight=(2, 2, 3, 1) and the markings on the standard tableau=[[-1, -2, -4, 7], [-3, 6, -6, 8], [4, -7], [-5, -8]] do not agree.\n ' T = SkewTableau(self.to_standard_list()) outer = Core(T.outer_shape(), (self.k + 1)) inner = Core(T.inner_shape(), (self.k + 1)) if (self.parent()._outer_shape != outer): raise ValueError('The outer shape of the parent does not agree with the outer shape of the tableau!') if (self.parent()._inner_shape != inner): raise ValueError('The inner shape of the parent does not agree with the inner shape of the tableau!') if (not self._is_valid_marked()): raise ValueError(('The marks in %s are not correctly placed.' % self.to_standard_list())) if (not self._is_valid_standard()): raise ValueError(('At least one shape in %s is not a valid %s-core.' % (self.to_standard_list(), (self.k + 1)))) if (not ((self.outer_shape().length() - self.inner_shape().length()) == self.size())): raise ValueError(('The size of the tableau %s and weight %s do not match' % (self.to_standard_list(), self.weight()))) if (not self.is_column_strict_with_weight(self.weight())): raise ValueError(('The weight=%s and the markings on the standard tableau=%s do not agree.' % (self.weight(), self.to_standard_list()))) def __hash__(self): '\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: t = StrongTableau([[-1, -1, -2], [2]], 2)\n sage: hash(t) == hash(t)\n True\n ' return (hash(tuple((tuple(x) for x in self))) + hash(self.parent().k)) def _is_valid_marked(self): '\n Check the validity of marks of a potential tableau ``self``.\n\n This method is called by method :meth:`check` and is not meant to be\n accessed by the user.\n\n This method first checks that there is one marked cell for the size of the\n tableau. Then, for each marked cell, it verifies that the cell below and to the\n right is not a positive value.\n\n In other words this checks that the marked cells are at the head of the connected\n components. This function verifies that the markings of ``self`` are\n consistent with a strong marked standard tableau.\n\n INPUT:\n\n - ``self`` -- a list of lists representing a potential *standard* marked tableau\n\n OUTPUT:\n\n - a boolean, ``True`` if the marks are properly placed in the tableau\n\n EXAMPLES::\n\n sage: all( T._is_valid_marked() for T in StrongTableaux.standard_marked_iterator(3, 6))\n True\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3)._is_valid_marked()\n True\n sage: StrongTableau([[-1, -2, 3], [3]], 2)\n Traceback (most recent call last):\n ...\n ValueError: The marks in [[-1, -2, 3], [3]] are not correctly placed.\n\n Marking in the wrong place::\n\n sage: StrongTableau([[None, None, -4, 5, -5], [None, None], [-1, -3], [2], [-2], [2], [3]], 4)\n Traceback (most recent call last):\n ...\n ValueError: The marks in [[None, None, -4, 5, -5], [None, None], [-1, -3], [2], [-2], [2], [3]] are not correctly placed.\n\n No marking on a 2::\n\n sage: StrongTableau([[None, None, -4, 5, -5], [None, None], [-1, -3], [2], [2], [2], [3]], 4)\n Traceback (most recent call last):\n ...\n ValueError: Unable to parse strong marked tableau : [[None, None, -4, 5, -5], [None, None], [-1, -3], [2], [2], [2], [3]]\n\n TESTS::\n\n sage: StrongTableau([[None, None, None], [None]], 2)._is_valid_marked()\n True\n sage: StrongTableau([], 4)._is_valid_marked()\n True\n ' T = self.to_standard_list() size = Core([len(t) for t in T], (self.k + 1)).length() inner_size = Core([y for y in (len([x for x in row if (x is None)]) for row in T) if (y > 0)], (self.k + 1)).length() if (len(set((v for v in flatten(list(T)) if ((v in ZZ) and (v < 0))))) != (size - inner_size)): return False for i in range(len(T)): for j in range(len(T[i])): v = T[i][j] if ((v is not None) and (v < 0) and (((i != 0) and (T[(i - 1)][j] == abs(v))) or ((j < (len(T[i]) - 1)) and (T[i][(j + 1)] == abs(v))))): return False return True def _is_valid_standard(self): '\n Test if ``self`` has a valid strong (un)marked standard part of the tableau.\n\n This method is called by method :meth:`check` and is not meant to be\n accessed by the user.\n\n This methods returns ``True`` if every intermediate shape (restricted to values\n less than or equal to `i` for each `i`) is a `k+1`-core and that the length\n of the `i+1`-restricted core is the length of the `i`-restricted core plus 1.\n\n OUTPUT:\n\n - a boolean, ``True`` means the standard strong marked tableau is valid\n\n EXAMPLES::\n\n sage: all( T._is_valid_standard() for T in StrongTableaux.standard_marked_iterator(4, 6))\n True\n\n Inner shape is not a 3-core::\n\n sage: StrongTableau([[None, None, None], [-1]], 2)\n Traceback (most recent call last):\n ...\n ValueError: [3] is not a 3-core\n\n Restrict to 1 and 2 is not a 5-core::\n\n sage: StrongTableau([[None, None, -4, 5, -5], [None, None], [-1, -3], [-2], [2], [3], [3]], 4)\n Traceback (most recent call last):\n ...\n ValueError: At least one shape in [[None, None, -4, 5, -5], [None, None], [-1, -3], [-2], [2], [3], [3]] is not a valid 5-core.\n\n TESTS::\n\n sage: StrongTableau([[None, None, None], [None]], 2)._is_valid_standard()\n True\n sage: StrongTableau([], 4)._is_valid_standard()\n True\n ' Tshapes = intermediate_shapes(self.to_unmarked_standard_list()) if (not all((Partition(la).is_core((self.k + 1)) for la in Tshapes))): return False Tsizes = [Core(lam, (self.k + 1)).length() for lam in Tshapes] return all(((Tsizes[i] == (Tsizes[(i + 1)] - 1)) for i in range((len(Tsizes) - 1)))) def is_column_strict_with_weight(self, mu): '\n Test if ``self`` is a column strict tableau with respect to the weight ``mu``.\n\n INPUT:\n\n - ``mu`` -- a vector of weights\n\n OUTPUT:\n\n - a boolean, ``True`` means the underlying column strict strong marked tableau is valid\n\n EXAMPLES::\n\n sage: StrongTableau([[-1, -2, -3], [3]], 2).is_column_strict_with_weight([3])\n True\n sage: StrongTableau([[-1, -2, 3], [-3]], 2).is_column_strict_with_weight([3])\n False\n\n TESTS::\n\n sage: StrongTableau([[None, None, None], [None]], 2).is_column_strict_with_weight([])\n True\n sage: StrongTableau([], 4).is_column_strict_with_weight([])\n True\n ' ss = 0 for i in range(len(mu)): for j in range((mu[i] - 1)): if (self.content_of_marked_head(((ss + j) + 1)) >= self.content_of_marked_head(((ss + j) + 2))): return False ss += mu[i] return True def _repr_diagram(self): "\n Return a string representing the pretty print of the tableau.\n\n EXAMPLES::\n\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])._repr_diagram()\n ' -1 -1 -2 -3\\n -2 3 -3 4\\n 2 3\\n -3 -4'\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)._repr_diagram()\n ' . . -1 -2\\n . .\\n -1 -2\\n 1 2\\n -3\\n 3\\n 3\\n 3'\n sage: StrongTableau([], 4)._repr_diagram()\n ''\n " return SkewTableau(self.to_list())._repr_diagram() def _repr_list(self): "\n Return a string representing the list of lists of the tableau.\n\n EXAMPLES::\n\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])._repr_list()\n '[[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4]]'\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)._repr_list()\n '[[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]]'\n sage: StrongTableau([], 4)._repr_list()\n '[]'\n " return repr(self.to_list()) def _repr_compact(self): "\n Return a compact string representation of ``self``.\n\n EXAMPLES::\n\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])._repr_compact()\n '-1,-1,-2,-3/-2,3,-3,4/2,3/-3,-4'\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)._repr_compact()\n '.,.,-1,-2/.,./-1,-2/1,2/-3/3/3/3'\n sage: StrongTableau([],4)._repr_compact()\n '-'\n " return SkewTableau(self.to_list())._repr_compact() def _repr_(self): '\n Return a representation of ``self``.\n\n To display a strong marked tableau we display the semistandard version.\n\n EXAMPLES::\n\n sage: StrongTableau( [[-1, -2, -3]], 3 )\n [[-1, -2, -3]]\n sage: StrongTableau( [[-1, -2, -3]], 3 , weight=[3])\n [[-1, -1, -1]]\n sage: StrongTableau( [], 3 )\n []\n sage: T = StrongTableau([[-1,-2,3],[-3]],2)\n sage: T\n [[-1, -2, 3], [-3]]\n sage: Tableaux.options(display="diagram")\n sage: T\n -1 -2 3\n -3\n sage: Tableaux.options(convention="French")\n sage: T\n -3\n -1 -2 3\n sage: Tableaux.options(display="compact")\n sage: T\n -1,-2,3/-3\n sage: Tableaux.options(display="list",convention="English")\n ' return self.parent().options._dispatch(self, '_repr_', 'display') def cell_of_marked_head(self, v): '\n Return location of marked head labeled by ``v`` in the standard part of ``self``.\n\n Return the coordinates of the ``v``-th marked cell in the strong standard tableau\n ``self``. If there is no mark, then the value returned is `(0, r)` where `r` is\n the length of the first row.\n\n INPUT:\n\n - ``v`` -- an integer representing the label in the standard tableau\n\n OUTPUT:\n\n - a pair of the coordinates of the marked cell with entry ``v``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -3, 4, -5], [-2], [-4]], 3)\n sage: [ T.cell_of_marked_head(i) for i in range(1,7)]\n [(0, 0), (1, 0), (0, 1), (2, 0), (0, 3), (0, 4)]\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: [ T.cell_of_marked_head(i) for i in range(1,7)]\n [(2, 0), (0, 2), (2, 1), (0, 3), (4, 0), (0, 4)]\n\n TESTS::\n\n sage: StrongTableau([],4).cell_of_marked_head(4)\n (0, 0)\n ' T = self.to_standard_list() if (T == []): return (0, 0) for i in range(len(T)): for j in range(len(T[i])): if (T[i][j] == (- v)): return (i, j) return (0, len(T[0])) def content_of_marked_head(self, v): '\n Return the diagonal of the marked label ``v`` in the standard part of ``self``.\n\n Return the content (the `j-i` coordinate of the cell) of the ``v``-th marked cell\n in the strong standard tableau ``self``. If there is no mark, then the value\n returned is the size of first row.\n\n INPUT:\n\n - ``v`` -- an integer representing the label in the standard tableau\n\n OUTPUT:\n\n - an integer representing the residue of the location of the mark\n\n EXAMPLES::\n\n sage: [ StrongTableau([[-1, -3, 4, -5], [-2], [-4]], 3).content_of_marked_head(i) for i in range(1,7)]\n [0, -1, 1, -2, 3, 4]\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: [ T.content_of_marked_head(i) for i in range(1,7)]\n [-2, 2, -1, 3, -4, 4]\n\n TESTS::\n\n sage: StrongTableau([],4).content_of_marked_head(4)\n 0\n ' c = self.cell_of_marked_head(v) return (c[1] - c[0]) def cells_of_marked_ribbon(self, v): '\n Return a list of all cells the marked ribbon labeled by ``v`` in the standard part of ``self``.\n\n Return the list of coordinates of the cells which are in the marked\n ribbon with label ``v`` in the standard part of the tableau. Note that\n the result is independent of the weight of the tableau.\n\n The cells are listed from largest content (where the mark is located)\n to the smallest. Hence, the first entry in this list will be the marked cell.\n\n INPUT:\n\n - ``v`` -- the entry of the standard tableau\n\n OUTPUT:\n\n - a list of pairs representing the coordinates of the cells of\n the marked ribbon\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -1, -2, -2, 3], [2, -3], [-3]],3)\n sage: T.to_standard_list()\n [[-1, -2, -3, -4, 6], [4, -6], [-5]]\n sage: T.cells_of_marked_ribbon(1)\n [(0, 0)]\n sage: T.cells_of_marked_ribbon(4)\n [(0, 3)]\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3)\n sage: T.cells_of_marked_ribbon(6)\n [(1, 2), (1, 1)]\n sage: T.cells_of_marked_ribbon(9)\n []\n sage: T = StrongTableau([[None, None, -1, -1, 3], [1, -3], [-3]],3)\n sage: T.to_standard_list()\n [[None, None, -1, -2, 4], [2, -4], [-3]]\n sage: T.cells_of_marked_ribbon(1)\n [(0, 2)]\n\n TESTS::\n\n sage: StrongTableau([],3).cells_of_marked_ribbon(1)\n []\n ' d = self.content_of_marked_head(v) T = SkewTableau(self.to_unmarked_standard_list()) cells = [] while (d is not None): adt = [c for c in T.cells_by_content(d) if (T[c[0]][c[1]] == v)] if (adt == []): d = None else: d -= 1 cells += adt return cells def cell_of_highest_head(self, v): '\n Return the cell of the highest head of label ``v`` in the standard part of ``self``.\n\n Return the cell where the head of the ribbon in the highest row is located\n in the underlying standard tableau. If there is no cell with entry ``v`` then\n the cell returned is `(0, r)` where `r` is the length of the first row.\n\n This cell is calculated by iterating through the diagonals of the tableau.\n\n INPUT:\n\n - ``v`` -- an integer indicating the label in the standard tableau\n\n OUTPUT:\n\n - a pair of integers indicating the coordinates of the head of the highest\n ribbon with label ``v``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,2,-3],[-2,3],[3]], 1)\n sage: [T.cell_of_highest_head(v) for v in range(1,5)]\n [(0, 0), (1, 0), (2, 0), (0, 3)]\n sage: T = StrongTableau([[None,None,-3,4],[3,-4]],2)\n sage: [T.cell_of_highest_head(v) for v in range(1,5)]\n [(1, 0), (1, 1), (0, 4), (0, 4)]\n\n TESTS::\n\n sage: StrongTableau([],2).cell_of_highest_head(1)\n (0, 0)\n ' Tlist = SkewTableau(self.to_standard_list()) if (Tlist == []): return (0, 0) r = len(Tlist[0]) dout = (0, r) for d in range((- len(Tlist)), (r + 1)): for c in Tlist.cells_by_content(d): if (nabs(Tlist[c[0]][c[1]]) == v): dout = c if ((dout != (0, r)) and ((dout[1] - dout[0]) != d)): return dout return dout def content_of_highest_head(self, v): '\n Return the diagonal of the highest head of the cells labeled ``v`` in the standard part of ``self``.\n\n Return the content of the cell of the head in the highest row of all ribbons labeled by ``v`` of\n the underlying standard tableau. If there is no cell with entry ``v`` then\n the value returned is the length of the first row.\n\n INPUT:\n\n - ``v`` -- an integer representing the label in the standard tableau\n\n OUTPUT:\n\n - an integer representing the content of the head of the highest\n ribbon with label ``v``\n\n EXAMPLES::\n\n sage: [StrongTableau([[-1,2,-3],[-2,3],[3]], 1).content_of_highest_head(v) for v in range(1,5)]\n [0, -1, -2, 3]\n\n TESTS::\n\n sage: StrongTableau([], 4).content_of_highest_head(1)\n 0\n sage: StrongTableau([[-1,-1]], 4).content_of_highest_head(3)\n 2\n ' c = self.cell_of_highest_head(v) return (c[1] - c[0]) def cells_head_dictionary(self): '\n Return a dictionary with the locations of the heads of all markings.\n\n Return a dictionary of values and lists of cells where the heads with the values\n are located.\n\n OUTPUT:\n\n - a dictionary with keys the entries in the tableau and values are the coordinates\n of the heads with those entries\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,-4,7],[-3,6,-6,8],[4,-7],[-5,-8]], 3)\n sage: T.cells_head_dictionary()\n {1: [(0, 0)],\n 2: [(0, 1)],\n 3: [(1, 0)],\n 4: [(2, 0), (0, 2)],\n 5: [(3, 0)],\n 6: [(1, 2)],\n 7: [(2, 1), (0, 3)],\n 8: [(3, 1), (1, 3)]}\n sage: T = StrongTableau([[None, 4, -4, -6, -7, 8, 8, -8], [None, -5, 8, 8, 8], [-3, 6]],3)\n sage: T.cells_head_dictionary()\n {1: [(2, 0)],\n 2: [(0, 2)],\n 3: [(1, 1)],\n 4: [(2, 1), (0, 3)],\n 5: [(0, 4)],\n 6: [(1, 4), (0, 7)]}\n sage: StrongTableau([[None, None], [None, -1]], 4).cells_head_dictionary()\n {1: [(1, 1)]}\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).cells_head_dictionary()\n {}\n sage: StrongTableau([],4).cells_head_dictionary()\n {}\n ' return StrongTableaux.cells_head_dictionary(self.to_unmarked_standard_list()) def cells_of_heads(self, v): '\n Return a list of cells of the heads with label ``v`` in the standard part of ``self``.\n\n A list of cells which are heads of the ribbons with label ``v`` in the\n standard part of the tableau ``self``. If there is no cell labelled by ``v`` then return the empty\n list.\n\n INPUT:\n\n - ``v`` -- an integer label\n\n OUTPUT:\n\n - a list of pairs of integers of the coordinates of the heads of the ribbons\n with label ``v``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.cells_of_heads(1)\n [(2, 0)]\n sage: T.cells_of_heads(2)\n [(3, 0), (0, 2)]\n sage: T.cells_of_heads(3)\n [(2, 1)]\n sage: T.cells_of_heads(4)\n [(3, 1), (0, 3)]\n sage: T.cells_of_heads(5)\n [(4, 0)]\n sage: T.cells_of_heads(6)\n []\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).cells_of_heads(1)\n []\n sage: StrongTableau([],4).cells_of_heads(1)\n []\n ' dout = self.cells_head_dictionary() if (v in dout): return dout[v] else: return [] def contents_of_heads(self, v): '\n A list of contents of the cells which are heads of the ribbons with label ``v``.\n\n If there is no cell labelled by ``v`` then return the empty list.\n\n INPUT:\n\n - ``v`` -- an integer label\n\n OUTPUT:\n\n - a list of integers of the content of the heads of the ribbons with label ``v``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.contents_of_heads(1)\n [-2]\n sage: T.contents_of_heads(2)\n [-3, 2]\n sage: T.contents_of_heads(3)\n [-1]\n sage: T.contents_of_heads(4)\n [-2, 3]\n sage: T.contents_of_heads(5)\n [-4]\n sage: T.contents_of_heads(6)\n []\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).contents_of_heads(1)\n []\n sage: StrongTableau([],4).contents_of_heads(1)\n []\n ' return [(c[1] - c[0]) for c in self.cells_of_heads(v)] def entries_by_content(self, diag): '\n Return the entries on the diagonal of ``self``.\n\n Return the entries in the tableau that are in the cells `(i,j)` with\n `j-i` equal to ``diag`` (that is, with content equal to ``diag``).\n\n INPUT:\n\n - ``diag`` -- an integer indicating the diagonal\n\n OUTPUT:\n\n - a list (perhaps empty) of labels on the diagonal ``diag``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.entries_by_content(0)\n []\n sage: T.entries_by_content(1)\n []\n sage: T.entries_by_content(2)\n [-1]\n sage: T.entries_by_content(-2)\n [-1, 2]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).entries_by_content(1)\n []\n sage: StrongTableau([],4).entries_by_content(1)\n []\n ' return SkewTableau(self.to_list()).entries_by_content(diag) def entries_by_content_standard(self, diag): '\n Return the entries on the diagonal of the standard part of ``self``.\n\n Return the entries in the tableau that are in the cells `(i,j)` with\n `j-i` equal to ``diag`` (that is, with content equal to ``diag``) in the\n standard tableau.\n\n INPUT:\n\n - ``diag`` -- an integer indicating the diagonal\n\n OUTPUT:\n\n - a list (perhaps empty) of labels on the diagonal ``diag``\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.entries_by_content_standard(0)\n []\n sage: T.entries_by_content_standard(1)\n []\n sage: T.entries_by_content_standard(2)\n [-2]\n sage: T.entries_by_content_standard(-2)\n [-1, 4]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).entries_by_content_standard(1)\n []\n sage: StrongTableau([],4).entries_by_content_standard(1)\n []\n ' return SkewTableau(self.to_standard_list()).entries_by_content(diag) def ribbons_above_marked(self, v): '\n Number of ribbons of label ``v`` higher than the marked ribbon in the standard part.\n\n Return the number of copies of the ribbon with label ``v`` in the standard part\n of ``self`` which are in a higher row than the marked ribbon. Note that the result\n is independent of the weight of the tableau.\n\n INPUT:\n\n - ``v`` -- the entry of the standard tableau\n\n OUTPUT:\n\n - an integer representing the number of copies of the ribbon above the marked\n ribbon\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3)\n sage: T.ribbons_above_marked(4)\n 1\n sage: T.ribbons_above_marked(6)\n 0\n sage: T.ribbons_above_marked(9)\n 0\n sage: StrongTableau([[-1,-2,-3,-4],[2,3,4],[3,4],[4]], 1).ribbons_above_marked(4)\n 3\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).ribbons_above_marked(1)\n 0\n sage: StrongTableau([],4).ribbons_above_marked(1)\n 0\n ' d = self.content_of_marked_head(v) count = 0 for i in range((self.k + 1), (len(self.to_standard_list()) + d), (self.k + 1)): count += int((v in self.entries_by_content_standard((d - i)))) return count def height_of_ribbon(self, v): '\n The number of rows occupied by one of the ribbons with label ``v``.\n\n The number of rows occupied by the marked ribbon with label ``v``\n (and by consequence the number of rows occupied by any ribbon with the same label)\n in the standard part of ``self``.\n\n INPUT:\n\n - ``v`` -- the label of the standard marked tableau\n\n OUTPUT:\n\n - a non-negative integer representing the number of rows\n occupied by the ribbon which is marked\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -1, -2, -2, 3], [2, -3], [-3]],3)\n sage: T.to_standard_list()\n [[-1, -2, -3, -4, 6], [4, -6], [-5]]\n sage: T.height_of_ribbon(1)\n 1\n sage: T.height_of_ribbon(4)\n 1\n sage: T = StrongTableau([[None,None,1,-2],[None,-3,4,-5],[-1,3],[-4,5]], 3)\n sage: T.height_of_ribbon(3)\n 2\n sage: T.height_of_ribbon(6)\n 0\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).height_of_ribbon(1)\n 0\n sage: StrongTableau([],4).height_of_ribbon(1)\n 0\n ' return len(set((c[0] for c in self.cells_of_marked_ribbon(v)))) def number_of_connected_components(self, v): '\n Number of connected components of ribbons with label ``v`` in the standard part.\n\n The number of connected components is calculated by finding the number of cells\n with label ``v`` in the standard part of the tableau and dividing by the number\n of cells in the ribbon.\n\n INPUT:\n\n - ``v`` -- the label of the standard marked tableau\n\n OUTPUT:\n\n - a non-negative integer representing the number of connected\n components\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -1, -2, -2, 3], [2, -3], [-3]],3)\n sage: T.to_standard_list()\n [[-1, -2, -3, -4, 6], [4, -6], [-5]]\n sage: T.number_of_connected_components(1)\n 1\n sage: T.number_of_connected_components(4)\n 2\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3)\n sage: T.number_of_connected_components(6)\n 1\n sage: T.number_of_connected_components(9)\n 0\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).number_of_connected_components(1)\n 0\n sage: StrongTableau([],4).number_of_connected_components(1)\n 0\n ' sz = len(self.cells_of_marked_ribbon(v)) if (sz == 0): return 0 T = self.to_standard_list() nocells = (len([i for i in range(len(T)) for j in range(len(T[i])) if (T[i][j] == v)]) + 1) return ZZ((nocells / sz)) def intermediate_shapes(self): '\n Return the intermediate shapes of ``self``.\n\n A (skew) tableau with letters `1, 2, \\ldots, \\ell` can be viewed as a sequence of\n shapes, where the `i`-th shape is given by the shape of the subtableau on letters\n `1, 2, \\ldots, i`.\n\n The output is the list of these shapes. The marked cells are ignored so to\n recover the strong tableau one would need the intermediate shapes and the\n :meth:`content_of_marked_head` for each pair of adjacent shapes in the list.\n\n OUTPUT:\n\n - a list of lists of integers representing `k+1`-cores\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])\n sage: T.intermediate_shapes()\n [[], [2], [3, 1, 1], [4, 3, 2, 1], [4, 4, 2, 2]]\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.intermediate_shapes()\n [[2, 2], [3, 2, 1, 1], [4, 2, 2, 2], [4, 2, 2, 2, 1, 1, 1, 1]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).intermediate_shapes()\n [[2, 1]]\n sage: StrongTableau([],4).intermediate_shapes()\n [[]]\n ' return intermediate_shapes(self.to_unmarked_list()) def pp(self): '\n Print the strong tableau ``self`` in pretty print format.\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])\n sage: T.pp()\n -1 -1 -2 -3\n -2 3 -3 4\n 2 3\n -3 -4\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.pp()\n . . -1 -2\n . .\n -1 -2\n 1 2\n -3\n 3\n 3\n 3\n sage: Tableaux.options(convention="French")\n sage: T.pp()\n 3\n 3\n 3\n -3\n 1 2\n -1 -2\n . .\n . . -1 -2\n sage: Tableaux.options(convention="English")\n ' print(self._repr_diagram()) def outer_shape(self): '\n Return the outer shape of ``self``.\n\n This method returns the outer shape of ``self`` as viewed as a ``Core``.\n The outer shape of a strong tableau is always a `(k+1)`-core.\n\n OUTPUT:\n\n - a `(k+1)`-core\n\n EXAMPLES::\n\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).outer_shape()\n [4, 2, 2, 2, 1, 1, 1, 1]\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1]).outer_shape()\n [4, 4, 2, 2]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).outer_shape()\n [2, 1]\n sage: StrongTableau([],4).outer_shape()\n []\n ' return self.parent().outer_shape() def inner_shape(self): '\n Return the inner shape of ``self``.\n\n If ``self`` is a strong skew tableau, then this method returns the inner shape\n (the shape of the cells labelled with ``None``).\n If ``self`` is not skew, then the inner shape is empty.\n\n OUTPUT:\n\n - a `(k+1)`-core\n\n EXAMPLES::\n\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).inner_shape()\n [2, 2]\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1]).inner_shape()\n []\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).inner_shape()\n [2, 1]\n sage: StrongTableau([],4).inner_shape()\n []\n ' return self.parent().inner_shape() def shape(self): "\n Return the shape of ``self``.\n\n If ``self`` is a skew tableau then return a pair of `k+1`-cores consisting of the\n outer and the inner shape. If ``self`` is strong tableau with no inner shape then\n return a `k+1`-core.\n\n INPUT:\n\n - ``form`` - optional argument to indicate 'inner', 'outer' or 'skew' (default : 'outer')\n\n OUTPUT:\n\n - a `k+1`-core or a pair of `k+1`-cores if form is not 'inner' or 'outer'\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4)\n sage: T.shape()\n ([4, 2, 2, 2, 1, 1, 1, 1], [2, 2])\n sage: StrongTableau([[-1, -2, 3], [-3]], 2).shape()\n [3, 1]\n sage: type(StrongTableau([[-1, -2, 3], [-3]], 2).shape())\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n\n TESTS::\n\n sage: StrongTableau([[None, None, None], [None]], 2).shape()\n ([3, 1], [3, 1])\n sage: StrongTableau([],4).shape()\n []\n " return self.parent().shape() def weight(self): '\n Return the weight of the tableau.\n\n The weight is a list of non-negative integers indicating the number of 1s,\n number of 2s, number of 3s, etc.\n\n OUTPUT:\n\n - a list of non-negative integers\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3); T.weight()\n (1, 1, 1, 1, 1)\n sage: T.set_weight([3,1,1]).weight()\n (3, 1, 1)\n sage: StrongTableau([[-1,-1,-2,-3],[-2,3,-3,4],[2,3],[-3,-4]], 3).weight()\n (2, 2, 3, 1)\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).weight()\n ()\n sage: StrongTableau([],4).weight()\n ()\n ' return self.parent()._weight def size(self): '\n Return the size of the strong tableau.\n\n The size of the strong tableau is the sum of the entries in the\n :meth:`weight`. It will also be equal to the length of the\n outer shape (as a `k+1`-core) minus the length of the inner shape.\n\n .. SEEALSO:: :meth:`sage.combinat.core.Core.length`\n\n OUTPUT:\n\n - a non-negative integer\n\n EXAMPLES::\n\n sage: StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3).size()\n 5\n sage: StrongTableau([[None, None, -1, 2], [-2], [-3]], 3).size()\n 3\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).size()\n 0\n sage: StrongTableau([],4).size()\n 0\n ' return sum(self.weight()) def to_list(self): '\n Return the marked column strict (possibly skew) tableau as a list of lists.\n\n OUTPUT:\n\n - a list of lists of integers or ``None``\n\n EXAMPLES::\n\n sage: StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3).set_weight([2,1,1,1]).to_list()\n [[-1, -1, -2, 3], [-3], [-4]]\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).to_list()\n [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]]\n sage: StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3, [3,1,1]).to_list()\n [[-1, -1, -1, 2], [-2], [-3]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_list()\n [[None, None], [None]]\n sage: StrongTableau([],4).to_list()\n []\n ' def f(v): if (v is None): return None else: return (sgn(v) * min([i for i in range((len(self.weight()) + 1)) if (sum(self.weight()[:i]) >= abs(v))])) return [[f(v) for v in row] for row in self.to_standard_list()] def to_unmarked_list(self): '\n Return the tableau as a list of lists with markings removed.\n\n Return the list of lists of the rows of the tableau where the markings have been\n removed.\n\n OUTPUT:\n\n - a list of lists of integers or ``None``\n\n EXAMPLES::\n\n sage: T = StrongTableau( [[-1, -2, -3, 4], [-4], [-5]], 3, [3,1,1])\n sage: T.to_unmarked_list()\n [[1, 1, 1, 2], [2], [3]]\n sage: TT = T.set_weight([2,1,1,1])\n sage: TT.to_unmarked_list()\n [[1, 1, 2, 3], [3], [4]]\n sage: StrongTableau( [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).to_unmarked_list()\n [[None, None, 1, 2], [None, None], [1, 2], [1, 2], [3], [3], [3], [3]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_unmarked_list()\n [[None, None], [None]]\n sage: StrongTableau([],4).to_unmarked_list()\n []\n ' return [[nabs(v) for v in row] for row in self.to_list()] def to_standard_list(self): '\n Return the underlying standard strong tableau as a list of lists.\n\n Internally, for a strong tableau the standard strong tableau and its weight\n is stored separately. This method returns the underlying standard part.\n\n OUTPUT:\n\n - a list of lists of integers or ``None``\n\n EXAMPLES::\n\n sage: StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3, [3,1,1]).to_standard_list()\n [[-1, -2, -3, 4], [-4], [-5]]\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).to_standard_list()\n [[None, None, -2, -4], [None, None], [-1, -3], [2, 4], [-5], [5], [5], [5]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_standard_list()\n [[None, None], [None]]\n sage: StrongTableau([],4).to_standard_list()\n []\n ' return self._tableau def to_standard_tableau(self): '\n Return the underlying standard strong tableau as a ``StrongTableau`` object.\n\n Internally, for a strong tableau the standard strong tableau and its weight\n is stored separately. This method returns the underlying standard part as a\n ``StrongTableau``.\n\n OUTPUT:\n\n - a strong tableau with standard weight\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -2, -3, 4], [-4], [-5]], 3, [3,1,1])\n sage: T.to_standard_tableau()\n [[-1, -2, -3, 4], [-4], [-5]]\n sage: T.to_standard_tableau() == T.to_standard_list()\n False\n sage: StrongTableau([[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).to_standard_tableau()\n [[None, None, -2, -4], [None, None], [-1, -3], [2, 4], [-5], [5], [5], [5]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_standard_tableau()\n [[None, None], [None]]\n sage: StrongTableau([],4).to_standard_tableau()\n []\n ' return StrongTableau(self._tableau, self.k) def to_unmarked_standard_list(self): '\n Return the standard part of the tableau as a list of lists with markings removed.\n\n Return the list of lists of the rows of the tableau where the markings have been\n removed.\n\n OUTPUT:\n\n - a list of lists of integers or ``None``\n\n EXAMPLES::\n\n sage: StrongTableau( [[-1, -2, -3, 4], [-4], [-5]], 3, [3,1,1]).to_unmarked_standard_list()\n [[1, 2, 3, 4], [4], [5]]\n sage: StrongTableau( [[None, None, -1, -2], [None, None], [-1, -2], [1, 2], [-3], [3], [3], [3]], 4).to_unmarked_standard_list()\n [[None, None, 2, 4], [None, None], [1, 3], [2, 4], [5], [5], [5], [5]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_unmarked_standard_list()\n [[None, None], [None]]\n sage: StrongTableau([],4).to_unmarked_standard_list()\n []\n ' return [[nabs(l) for l in x] for x in self.to_standard_list()] def _latex_(self): '\n Return a latex method for the tableau.\n\n EXAMPLES::\n\n sage: T = StrongTableau( [[None, -1, -2, 3], [2, -3]], 2, weight=[2,1] )\n sage: Tableaux.options(convention = "English")\n sage: latex(T)\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[b]{*{4}c}\\cline{1-4}\n \\lr{}&\\lr{1^\\ast}&\\lr{1^\\ast}&\\lr{2}\\\\\\cline{1-4}\n \\lr{1}&\\lr{2^\\ast}\\\\\\cline{1-2}\n \\end{array}$}\n }\n sage: Tableaux.options(convention = "French")\n sage: latex(T)\n {\\def\\lr#1{\\multicolumn{1}{|@{\\hspace{.6ex}}c@{\\hspace{.6ex}}|}{\\raisebox{-.3ex}{$#1$}}}\n \\raisebox{-.6ex}{$\\begin{array}[t]{*{4}c}\\cline{1-2}\n \\lr{1}&\\lr{2^\\ast}\\\\\\cline{1-4}\n \\lr{}&\\lr{1^\\ast}&\\lr{1^\\ast}&\\lr{2}\\\\\\cline{1-4}\n \\end{array}$}\n }\n ' def chi(x): if (x is None): return '' if (x in ZZ): s = ('%s' % abs(x)) if (x < 0): s += '^\\ast' return s return ('%s' % x) T = [[chi(x) for x in row] for row in self.to_list()] from .output import tex_from_array return tex_from_array(T) def restrict(self, r): '\n Restrict the standard part of the tableau to the labels `1, 2, \\ldots, r`.\n\n Return the tableau consisting of the labels of the standard part of ``self``\n restricted to the labels of `1` through ``r``. The result is another\n ``StrongTableau`` object.\n\n INPUT:\n\n - ``r`` -- an integer\n\n OUTPUT:\n\n - A strong tableau\n\n EXAMPLES::\n\n sage: T = StrongTableau([[None, None, -4, 5, -5], [None, None], [-1, -3], [-2], [2], [2], [3]], 4, weight=[1,1,1,1,1])\n sage: T.restrict(3)\n [[None, None], [None, None], [-1, -3], [-2], [2], [2], [3]]\n sage: TT = T.restrict(0)\n sage: TT\n [[None, None], [None, None]]\n sage: TT == StrongTableau( [[None, None], [None, None]], 4 )\n True\n sage: T.restrict(5) == T\n True\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).restrict(1)\n [[None, None], [None]]\n sage: StrongTableau([],4).restrict(1)\n []\n ' rr = sum(self.weight()[:r]) rest_tab = [y for y in ([x for x in row if ((x is None) or (abs(x) <= rr))] for row in self.to_standard_list()) if y] new_parent = StrongTableaux(self.k, (Core([len(x) for x in rest_tab], (self.k + 1)), self.inner_shape()), self.weight()[:r]) return new_parent(rest_tab) def set_weight(self, mu): '\n Sets a new weight ``mu`` for ``self``.\n\n This method first tests if the underlying standard tableau is column-strict with\n respect to the weight ``mu``. If it is, then it changes the weight and returns\n the tableau; otherwise it raises an error.\n\n INPUT:\n\n - ``mu`` -- a list of non-negative integers representing the new weight\n\n EXAMPLES::\n\n sage: StrongTableau( [[-1, -2, -3], [3]], 2 ).set_weight( [3] )\n [[-1, -1, -1], [1]]\n sage: StrongTableau( [[-1, -2, -3], [3]], 2 ).set_weight( [0,3] )\n [[-2, -2, -2], [2]]\n sage: StrongTableau( [[-1, -2, 3], [-3]], 2 ).set_weight( [2, 0, 1] )\n [[-1, -1, 3], [-3]]\n sage: StrongTableau( [[-1, -2, 3], [-3]], 2 ).set_weight( [3] )\n Traceback (most recent call last):\n ...\n ValueError: [[-1, -2, 3], [-3]] is not a semistandard strong tableau with respect to the partition [3]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).set_weight([])\n [[None, None], [None]]\n sage: StrongTableau([],4).set_weight([])\n []\n ' if ((sum(mu) != self.size()) or self.is_column_strict_with_weight(mu)): return StrongTableaux.__classcall__(StrongTableaux, self.k, (self.outer_shape(), self.inner_shape()), tuple(mu))(self.to_standard_list()) else: raise ValueError(('%s is not a semistandard strong tableau with respect to the partition %s' % (self, mu))) def left_action(self, tij): '\n Action of transposition ``tij`` on ``self`` by adding marked ribbons.\n\n Computes the left action of the transposition ``tij`` on the tableau.\n If ``tij`` acting on the element of the affine Grassmannian raises the length by 1,\n then this function will add a cell to the standard tableau.\n\n INPUT:\n\n - ``tij`` -- a transposition represented as a pair `(i, j)`.\n\n OUTPUT:\n\n - ``self`` after it has been modified by the action of the transposition ``tij``\n\n EXAMPLES::\n\n sage: StrongTableau( [[None, -1, -2, -3], [3], [-4]], 3, weight=[1,1,1,1] ).left_action([0,1])\n [[None, -1, -2, -3, 5], [3, -5], [-4]]\n sage: StrongTableau( [[None, -1, -2, -3], [3], [-4]], 3, weight=[1,1,1,1] ).left_action([4,5])\n [[None, -1, -2, -3, -5], [3, 5], [-4]]\n sage: T = StrongTableau( [[None, -1, -2, -3], [3], [-4]], 3, weight=[1,1,1,1] )\n sage: T.left_action([-3,-2])\n [[None, -1, -2, -3], [3], [-4], [-5]]\n sage: T = StrongTableau( [[None, -1, -2, -3], [3], [-4]], 3, weight=[3,1] )\n sage: T.left_action([-3,-2])\n [[None, -1, -1, -1], [1], [-2], [-3]]\n sage: T\n [[None, -1, -1, -1], [1], [-2]]\n sage: T.check()\n sage: T.weight()\n (3, 1)\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).left_action([-2,-1])\n [[None, None], [None], [-1]]\n sage: StrongTableau([],4).left_action([0,1])\n [[-1]]\n ' T = StrongTableaux._left_action_list(copy.deepcopy(self.to_standard_list()), tij, (self.size() + 1), self.k) return StrongTableau(T, self.k, (self.weight() + (1,))) def follows_tableau(self): '\n Return a list of strong marked tableaux with length one longer than ``self``.\n\n Return list of all strong tableaux obtained from ``self`` by extending to a core\n which follows the shape of ``self`` in the strong order.\n\n OUTPUT:\n\n - a list of strong tableaux which follow ``self`` in strong order\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1])\n sage: T.follows_tableau()\n [[[-1, -1, -2, -3, 5, 5, -5], [-2, 3, -3, 4], [2, 3], [-3, -4]],\n [[-1, -1, -2, -3, 5], [-2, 3, -3, 4], [2, 3, 5], [-3, -4], [-5]],\n [[-1, -1, -2, -3, 5], [-2, 3, -3, 4], [2, 3, -5], [-3, -4], [5]],\n [[-1, -1, -2, -3, -5], [-2, 3, -3, 4], [2, 3, 5], [-3, -4], [5]],\n [[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4], [-5], [5], [5]]]\n sage: StrongTableau([[-1,-2],[-3,-4]],3).follows_tableau()\n [[[-1, -2, 5, 5, -5], [-3, -4]], [[-1, -2, 5], [-3, -4], [-5]],\n [[-1, -2, -5], [-3, -4], [5]], [[-1, -2], [-3, -4], [-5], [5], [5]]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).follows_tableau()\n [[[None, None, -1], [None]], [[None, None], [None, -1]], [[None, None], [None], [-1]]]\n sage: StrongTableau([],4).follows_tableau()\n [[[-1]]]\n ' v = (self.size() + 1) out = [] for T in StrongTableaux.follows_tableau_unsigned_standard(self.to_standard_list(), self.k): for m in StrongTableaux.cells_head_dictionary(T)[v]: TT = copy.deepcopy(T) TT[m[0]][m[1]] = (- v) out.append(StrongTableau(TT, self.k, (self.weight() + (1,)))) return out def spin_of_ribbon(self, v): '\n Return the spin of the ribbon with label ``v`` in the standard part of ``self``.\n\n The spin of a ribbon is an integer statistic. It is the sum of `(h-1) r` plus\n the number of connected components above the marked one where `h` is the height\n of the marked ribbon and `r` is the number of connected components.\n\n .. SEEALSO:: :meth:`height_of_ribbon`, :meth:`number_of_connected_components`,\n :meth:`ribbons_above_marked`\n\n INPUT:\n\n - ``v`` -- a label of the standard part of the tableau\n\n OUTPUT:\n\n - an integer value representing the spin of the ribbon with label ``v``.\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1,-2,5,6],[-3,-4,-7,8],[-5,-6],[7,-8]], 3)\n sage: [T.spin_of_ribbon(v) for v in range(1,9)]\n [0, 0, 0, 0, 0, 0, 1, 0]\n sage: T = StrongTableau([[None,None,-1,-3],[-2,3,-3,4],[2,3],[-3,-4]], 3)\n sage: [T.spin_of_ribbon(v) for v in range(1,7)]\n [0, 1, 0, 0, 1, 0]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).spin_of_ribbon(1)\n 0\n sage: StrongTableau([],4).spin_of_ribbon(1)\n 0\n ' return (((self.height_of_ribbon(v) - 1) * self.number_of_connected_components(v)) + self.ribbons_above_marked(v)) def spin(self): "\n Return the spin statistic of the tableau ``self``.\n\n The spin is an integer statistic on a strong marked tableau. It is\n the sum of `(h-1) r` plus the number of connected components above the\n marked one where `h` is the height of the marked ribbon and `r` is\n the number of connected components.\n\n .. SEEALSO:: :meth:`height_of_ribbon`, :meth:`number_of_connected_components`,\n :meth:`ribbons_above_marked`\n\n The `k`-Schur functions with a parameter `t` can be defined as\n\n .. MATH::\n\n s^{(k)}_\\lambda[X; t] = \\sum_T t^{spin(T)} m_{weight(T)}[X]\n\n where the sum is over all column strict marked strong `k`-tableaux\n of shape `\\lambda` and partition content.\n\n OUTPUT:\n\n - an integer value representing the spin.\n\n EXAMPLES::\n\n sage: StrongTableau([[-1,-2,5,6],[-3,-4,-7,8],[-5,-6],[7,-8]], 3, [2,2,3,1]).spin()\n 1\n sage: StrongTableau([[-1,-2,-4,-7],[-3,6,-6,8],[4,7],[-5,-8]], 3, [2,2,3,1]).spin()\n 2\n sage: StrongTableau([[None,None,-1,-3],[-2,3,-3,4],[2,3],[-3,-4]], 3).spin()\n 2\n sage: ks3 = SymmetricFunctions(QQ['t'].fraction_field()).kschur(3)\n sage: t = ks3.realization_of().t\n sage: m = ks3.ambient().realization_of().m()\n sage: myks221 = sum(sum(t**T.spin() for T in StrongTableaux(3,[3,2,1],weight=mu))*m(mu) for mu in Partitions(5, max_part=3))\n sage: myks221 == m(ks3[2,2,1])\n True\n sage: h = ks3.ambient().realization_of().h()\n sage: Core([4,4,2,2],4).to_bounded_partition()\n [2, 2, 2, 2]\n sage: ks3[2,2,2,2].lift().scalar(h[3,3,2]) == sum( t**T.spin() for T in StrongTableaux(3, [4,4,2,2], weight=[3,3,2]) )\n True\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).spin()\n 0\n sage: StrongTableau([],4).spin()\n 0\n " return sum((self.spin_of_ribbon(v) for v in range(1, (self.size() + 1)))) def to_transposition_sequence(self): '\n Return a list of transpositions corresponding to ``self``.\n\n Given a strong column strict tableau ``self`` returns the list of transpositions\n which when applied to the left of an empty tableau gives the corresponding strong\n standard tableau.\n\n OUTPUT:\n\n - a list of pairs of values ``[i,j]`` representing the transpositions `t_{ij}`\n\n EXAMPLES::\n\n sage: T = StrongTableau([[-1, -1, -1], [1]],2)\n sage: T.to_transposition_sequence()\n [[2, 3], [1, 2], [0, 1]]\n sage: T = StrongTableau([[-1, -1, 2], [-2]],2)\n sage: T.to_transposition_sequence()\n [[-1, 0], [1, 2], [0, 1]]\n sage: T = StrongTableau([[None, -1, 2, -3], [-2, 3]],2)\n sage: T.to_transposition_sequence()\n [[3, 4], [-1, 0], [1, 2]]\n\n TESTS::\n\n sage: StrongTableau([[None, None], [None]], 4).to_transposition_sequence()\n []\n sage: StrongTableau([],4).to_transposition_sequence()\n []\n ' return StrongTableaux.marked_CST_to_transposition_sequence(self.to_standard_list(), self.k)
class StrongTableaux(UniqueRepresentation, Parent): def __init__(self, k, shape, weight): '\n TESTS::\n\n sage: strongT = StrongTableaux(2, [3,1], weight=[2,1])\n sage: TestSuite(strongT).run()\n\n sage: strongT = StrongTableaux(0, [2,2], weight=[2,2])\n Traceback (most recent call last):\n ...\n ValueError: The input k has to be a positive integer\n ' self._outer_shape = shape[0] self._inner_shape = shape[1] self.k = k if (weight is None): self._weight = ((1,) * (self._outer_shape.length() - self._inner_shape.length())) else: self._weight = weight Parent.__init__(self, category=FiniteEnumeratedSets()) @staticmethod def __classcall_private__(cls, k, shape, weight=None): '\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: ST3 = StrongTableaux(3, [2,2], weight=[1,1,1,1])\n sage: TestSuite(ST3).run()\n ' if (k <= 0): raise ValueError('The input k has to be a positive integer') if ((shape == []) or (shape[0] in ZZ)): outer_shape = Core(shape, (k + 1)) inner_shape = Core([], (k + 1)) else: outer_shape = Core(shape[0], (k + 1)) inner_shape = Core(shape[1], (k + 1)) if (weight is not None): weight = tuple(weight) return super().__classcall__(cls, k, (outer_shape, inner_shape), weight) def _repr_(self): '\n Return the representation of ``self``.\n\n EXAMPLES::\n\n sage: StrongTableaux(3, [2,2], weight=[1,1,1,1])\n Set of strong 3-tableaux of shape [2, 2] and of weight (1, 1, 1, 1)\n sage: StrongTableaux(3, [2,2])\n Set of strong 3-tableaux of shape [2, 2] and of weight (1, 1, 1, 1)\n sage: StrongTableaux(3, [[2,2],[1]], weight=[0,0,2,1])\n Set of strong 3-tableaux of shape [[2, 2], [1]] and of weight (0, 0, 2, 1)\n sage: StrongTableaux(3, [[],[]], weight=[])\n Set of strong 3-tableaux of shape [] and of weight ()\n ' if (self._inner_shape == Core([], (self.k + 1))): s = ('Set of strong %s-tableaux' % self.k) s += (' of shape %s' % self._outer_shape) else: s = ('Set of strong %s-tableaux' % self.k) s += (' of shape [%s, %s]' % (self._outer_shape, self._inner_shape)) s += ('%sand of weight %s' % (' ', self._weight)) return s options = Tableaux.options def an_element(self): '\n Return the first generated element of the class of ``StrongTableaux``.\n\n EXAMPLES::\n\n sage: ST = StrongTableaux(3, [3], weight=[3])\n sage: ST.an_element()\n [[-1, -1, -1]]\n ' return next(iter(self)) def outer_shape(self): "\n Return the outer shape of the class of strong tableaux.\n\n OUTPUT:\n\n - a `k+1`-core\n\n EXAMPLES::\n\n sage: StrongTableaux( 2, [3,1] ).outer_shape()\n [3, 1]\n sage: type(StrongTableaux( 2, [3,1] ).outer_shape())\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: StrongTableaux( 4, [[2,1], [1]] ).outer_shape()\n [2, 1]\n " return self._outer_shape def inner_shape(self): "\n Return the inner shape of the class of strong tableaux.\n\n OUTPUT:\n\n - a `k+1`-core\n\n EXAMPLES::\n\n sage: StrongTableaux( 2, [3,1] ).inner_shape()\n []\n sage: type(StrongTableaux( 2, [3,1] ).inner_shape())\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: StrongTableaux( 4, [[2,1], [1]] ).inner_shape()\n [1]\n " return self._inner_shape def shape(self): "\n Return the shape of ``self``.\n\n If the ``self`` has an inner shape return a pair consisting of an inner and\n an outer shape. If the inner shape is empty then return only the outer shape.\n\n OUTPUT:\n\n - a `k+1`-core or a pair of `k+1`-cores\n\n EXAMPLES::\n\n sage: StrongTableaux( 2, [3,1] ).shape()\n [3, 1]\n sage: type(StrongTableaux( 2, [3,1] ).shape())\n <class 'sage.combinat.core.Cores_length_with_category.element_class'>\n sage: StrongTableaux( 4, [[2,1], [1]] ).shape()\n ([2, 1], [1])\n " if self._inner_shape: return (self._outer_shape, self._inner_shape) return self._outer_shape def __iter__(self): '\n TESTS::\n\n sage: ST = StrongTableaux(3, [4,1], weight=[2,2])\n sage: ST.list()\n [[[-1, -1, -2, -2], [2]], [[-1, -1, 2, -2], [-2]]]\n sage: ST = StrongTableaux(3, [5,2,2], weight=[2,2,2,1])\n sage: ST.cardinality()\n 14\n sage: StrongTableaux(3, [5,2,2], weight=[3,3,1]).list()\n [[[-1, -1, -1, -2, -2], [-2, 2], [2, -3]], [[-1, -1, -1, 2, -2], [-2, -2], [2, -3]], [[-1, -1, -1, -2, -3], [-2, -2], [2, 2]]]\n sage: StrongTableaux(3, [4,1,1]).cardinality()\n 10\n sage: StrongTableaux(3, [5,2,2], weight=[6,1]).list() # there are no strong column strict tableaux of shape [5,2,2] and weight (6,1)\n []\n sage: StrongTableaux(3, [[5,2,2], [3,1,1]], weight=[2,1]).list()\n [[[None, None, None, -1, -1], [None, 1], [None, -2]],\n [[None, None, None, 1, -1], [None, -1], [None, -2]],\n [[None, None, None, -1, -2], [None, -1], [None, 1]]]\n sage: StrongTableaux(2, [[4,3,3,2,2,1,1], [2,1,1]], weight=[1,1,1,1]).cardinality()\n 150\n sage: StrongTableaux(2, [[7,5,3,1], [2,1,1]], weight=[2,2]).cardinality()\n 18\n sage: StrongTableaux(2, [[3,1],[3,1]]).list()\n [[[None, None, None], [None]]]\n sage: StrongTableaux(4, []).list()\n [[]]\n ' size = sum(self._weight) if (size == 0): (yield self([([None] * row) for row in self._inner_shape])) else: for unT in StrongTableaux.standard_unmarked_iterator(self.k, size, self._outer_shape, self._inner_shape): (yield from StrongTableaux.marked_given_unmarked_and_weight_iterator(unT, self.k, self._weight)) @classmethod def standard_unmarked_iterator(cls, k, size, outer_shape=None, inner_shape=[]): '\n An iterator for standard unmarked strong tableaux.\n\n An iterator which generates all unmarked tableaux of a given ``size`` which are\n contained in ``outer_shape`` and which contain the ``inner_shape``.\n\n These are built recursively by building all standard marked strong tableaux of\n size ``size`` `-1` and adding all possible covers.\n\n If ``outer_shape`` is ``None`` then there is no restriction on the shape of the\n tableaux which are created.\n\n INPUT:\n\n - ``k``, ``size`` - a positive integers\n - ``outer_shape`` - a list representing a `k+1`-core (default: ``None``)\n - ``inner_shape`` - a list representing a `k+1`-core (default: [])\n\n OUTPUT:\n\n - an iterator which lists all standard strong unmarked tableaux with ``size``\n cells and which are contained in ``outer_shape`` and contain ``inner_shape``\n\n EXAMPLES::\n\n sage: list(StrongTableaux.standard_unmarked_iterator(2, 3))\n [[[1, 2, 3], [3]], [[1, 2], [3], [3]], [[1, 3, 3], [2]], [[1, 3], [2], [3]]]\n sage: list(StrongTableaux.standard_unmarked_iterator(2, 1, inner_shape=[1,1]))\n [[[None, 1, 1], [None]], [[None, 1], [None], [1]]]\n sage: len(list(StrongTableaux.standard_unmarked_iterator(4,4)))\n 10\n sage: len(list(StrongTableaux.standard_unmarked_iterator(4,6)))\n 98\n sage: len(list(StrongTableaux.standard_unmarked_iterator(4,4, inner_shape=[2,2])))\n 92\n sage: len(list(StrongTableaux.standard_unmarked_iterator(4,4, outer_shape=[5,2,2,1], inner_shape=[2,2])))\n 10\n\n TESTS::\n\n sage: list(StrongTableaux.standard_unmarked_iterator(2,0, outer_shape=[3,1], inner_shape=[3,1]))\n [[[None, None, None], [None]]]\n sage: list(StrongTableaux.standard_unmarked_iterator(4,0, outer_shape=[]))\n [[]]\n ' if (size == 0): if ((outer_shape is None) or Core(outer_shape, (k + 1)).contains(inner_shape)): (yield [([None] * inner_shape[i]) for i in range(len(inner_shape))]) else: for T in cls.standard_unmarked_iterator(k, (size - 1), outer_shape, inner_shape): for TT in cls.follows_tableau_unsigned_standard(T, k): if ((outer_shape is None) or Core(outer_shape, (k + 1)).contains([len(r) for r in TT])): (yield TT) @classmethod def marked_given_unmarked_and_weight_iterator(cls, unmarkedT, k, weight): '\n An iterator generating strong marked tableaux from an unmarked strong tableau.\n\n Iterator which lists all marked tableaux of weight ``weight`` such that the\n standard unmarked part of the tableau is equal to ``unmarkedT``.\n\n INPUT:\n\n - ``unmarkedT`` - a list of lists representing a strong unmarked tableau\n - ``k`` - a positive integer\n - ``weight`` - a list of non-negative integers indicating the weight\n\n OUTPUT:\n\n - an iterator that returns ``StrongTableau`` objects\n\n EXAMPLES::\n\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[1,2,3],[3]], 2, [3])\n sage: list(ST)\n [[[-1, -1, -1], [1]]]\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[1,2,3],[3]], 2, [0,3])\n sage: list(ST)\n [[[-2, -2, -2], [2]]]\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[1,2,3],[3]], 2, [1,2])\n sage: list(ST)\n [[[-1, -2, -2], [2]]]\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[1,2,3],[3]], 2, [2,1])\n sage: list(ST)\n [[[-1, -1, 2], [-2]], [[-1, -1, -2], [2]]]\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[None, None, 1, 2, 4], [2, 4], [3]], 3, [3,1])\n sage: list(ST)\n []\n sage: ST = StrongTableaux.marked_given_unmarked_and_weight_iterator([[None, None, 1, 2, 4], [2, 4], [3]], 3, [2,2])\n sage: list(ST)\n [[[None, None, -1, -1, 2], [1, -2], [-2]],\n [[None, None, -1, -1, -2], [1, 2], [-2]]]\n\n TESTS::\n\n sage: list(StrongTableaux.marked_given_unmarked_and_weight_iterator([[None, None, None],[None]], 2, []))\n [[[None, None, None], [None]]]\n sage: list(StrongTableaux.marked_given_unmarked_and_weight_iterator([], 4, weight=[]))\n [[]]\n ' td = StrongTableaux.cells_head_dictionary(unmarkedT) if (td == {}): (yield StrongTableau(unmarkedT, k, [])) else: import itertools dsc = Composition(weight).descents() for m in itertools.product(*[td[key] for key in sorted(td)]): if all(((((m[i][1] - m[i][0]) < (m[(i + 1)][1] - m[(i + 1)][0])) or (i in dsc)) for i in range((len(m) - 1)))): (yield StrongTableaux.add_marking(unmarkedT, m, k, weight)) @classmethod def add_marking(cls, unmarkedT, marking, k, weight): '\n Add markings to a partially marked strong tableau.\n\n Given a partially marked standard tableau and a list of cells where the marks\n should be placed along with a ``weight``, return the semi-standard marked strong\n tableau. The marking should complete the marking so that the result is a\n strong standard marked tableau.\n\n INPUT:\n\n - ``unmarkedT`` - a list of lists which is a partially marked strong `k`-tableau\n - ``marking`` - a list of pairs of coordinates where cells are to be marked\n - ``k`` - a positive integer\n - ``weight`` - a tuple of the weight of the output tableau\n\n OUTPUT:\n\n - a ``StrongTableau`` object\n\n EXAMPLES::\n\n sage: StrongTableaux.add_marking([[None,1,2],[2]], [(0,1), (1,0)], 2, [1,1])\n [[None, -1, 2], [-2]]\n sage: StrongTableaux.add_marking([[None,1,2],[2]], [(0,1), (1,0)], 2, [2])\n Traceback (most recent call last):\n ...\n ValueError: The weight=(2,) and the markings on the standard tableau=[[None, -1, 2], [-2]] do not agree.\n sage: StrongTableaux.add_marking([[None,1,2],[2]], [(0,1), (0,2)], 2, [2])\n [[None, -1, -1], [1]]\n\n TESTS::\n\n sage: StrongTableaux.add_marking([[None,None,None],[None]], [], 2, [])\n [[None, None, None], [None]]\n sage: StrongTableaux.add_marking([], [], 2, [])\n []\n ' def msgn(c, v): if (c in marking): return (- v) else: return v return StrongTableau([[msgn((i, j), unmarkedT[i][j]) for j in range(len(unmarkedT[i]))] for i in range(len(unmarkedT))], k, weight) @classmethod def _left_action_list(cls, Tlist, tij, v, k): '\n Act by the transposition ``tij`` if it increases the size of the tableau by 1.\n\n This method modifies the tableau ``Tlist`` instead of returning a copy.\n\n INPUT:\n\n - ``Tlist`` - a partial standard strong `k`-tableau as a list of lists\n - ``tij`` - a pair of integers representing a transposition\n - ``v`` - the label to add to the tableau\n - ``k`` - a positive integer\n\n OUTPUT:\n\n - a list of lists, in particular, it is ``Tlist``\n\n EXAMPLES::\n\n sage: StrongTableaux._left_action_list( [[None]], [1,2], 10, 2 )\n [[None, -10]]\n sage: StrongTableaux._left_action_list( [[None]], [1,2], 10, 1 )\n [[None, -10], [10]]\n sage: StrongTableaux._left_action_list( [[None]], [2,3], 10, 1 )\n Traceback (most recent call last):\n ...\n ValueError: [2, 3] is not a single step up in the strong lattice\n sage: StrongTableaux._left_action_list( [[None]], [3,4], 10, 1 )\n [[None, 10], [10]]\n sage: T = StrongTableaux._left_action_list( [[None]], [1,2], 10, 2 )\n sage: StrongTableaux._left_action_list( T, [2,3], 4, 2 )\n [[None, -10, -4], [4]]\n sage: T\n [[None, -10, -4], [4]]\n ' innershape = Core([len(r) for r in Tlist], (k + 1)) outershape = innershape.affine_symmetric_group_action(tij, transposition=True) if (outershape.length() == (innershape.length() + 1)): for c in SkewPartition([outershape.to_partition(), innershape.to_partition()]).cells(): while (c[0] >= len(Tlist)): Tlist.append([]) Tlist[c[0]].append(v) if ((len(Tlist[c[0]]) - c[0]) == tij[1]): Tlist[c[0]][(- 1)] = (- Tlist[c[0]][(- 1)]) return Tlist else: raise ValueError(('%s is not a single step up in the strong lattice' % tij)) @classmethod def follows_tableau_unsigned_standard(cls, Tlist, k): '\n Return a list of strong tableaux one longer in length than ``Tlist``.\n\n Return list of all standard strong tableaux obtained from ``Tlist`` by extending to\n a core which follows the shape of ``Tlist`` in the strong order. It does not put\n the markings on the last entry that it adds but it does keep the markings on all\n entries smaller. The objects returned are not ``StrongTableau`` objects (and\n cannot be) because the last entry will not properly marked.\n\n INPUT:\n\n - ``Tlist`` -- a filling of a `k+1`-core as a list of lists\n - ``k`` - an integer\n\n OUTPUT:\n\n - a list of strong tableaux which follow ``Tlist`` in strong order\n\n EXAMPLES::\n\n sage: StrongTableaux.follows_tableau_unsigned_standard([[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4]], 3)\n [[[-1, -1, -2, -3, 5, 5, 5], [-2, 3, -3, 4], [2, 3], [-3, -4]],\n [[-1, -1, -2, -3, 5], [-2, 3, -3, 4], [2, 3, 5], [-3, -4], [5]],\n [[-1, -1, -2, -3], [-2, 3, -3, 4], [2, 3], [-3, -4], [5], [5], [5]]]\n sage: StrongTableaux.follows_tableau_unsigned_standard([[None,-1],[-2,-3]],3)\n [[[None, -1, 4, 4, 4], [-2, -3]], [[None, -1, 4], [-2, -3], [4]],\n [[None, -1], [-2, -3], [4], [4], [4]]]\n\n TESTS::\n\n sage: StrongTableaux.follows_tableau_unsigned_standard([[None, None, None], [None]], 2)\n [[[None, None, None, 1], [None, 1]], [[None, None, None], [None], [1]]]\n sage: StrongTableaux.follows_tableau_unsigned_standard([], 4)\n [[[1]]]\n ' v = (1 + max((abs(v) for rows in Tlist for v in rows if (v is not None)), default=0)) out = [] sh = Core([len(r) for r in Tlist], (k + 1)) for ga in sh.strong_covers(): T = copy.deepcopy(Tlist) T += [[] for _ in repeat(None, (len(ga) - len(T)))] for c in SkewPartition([ga.to_partition(), sh.to_partition()]).cells(): T[c[0]] += [v] out.append(T) return out @classmethod def standard_marked_iterator(cls, k, size, outer_shape=None, inner_shape=[]): '\n An iterator for generating standard strong marked tableaux.\n\n An iterator which generates all standard marked `k`-tableaux of a given ``size``\n which are contained in ``outer_shape`` and contain the ``inner_shape``.\n If ``outer_shape`` is ``None`` then there is no restriction on the shape of the\n tableaux which are created.\n\n INPUT:\n\n - ``k`` - a positive integer\n - ``size`` - a positive integer\n - ``outer_shape`` - a list which is a `k+1`-core (default: ``None``)\n - ``inner_shape`` - a list which is a `k+1`-core (default: [])\n\n OUTPUT:\n\n - an iterator which returns the standard marked tableaux with ``size`` cells\n and that are contained in ``outer_shape`` and contain ``inner_shape``\n\n EXAMPLES::\n\n sage: list(StrongTableaux.standard_marked_iterator(2, 3))\n [[[-1, -2, 3], [-3]], [[-1, -2, -3], [3]], [[-1, -2], [-3], [3]], [[-1, 3, -3], [-2]], [[-1, 3], [-2], [-3]], [[-1, -3], [-2], [3]]]\n sage: list(StrongTableaux.standard_marked_iterator(2, 1, inner_shape=[1,1]))\n [[[None, 1, -1], [None]], [[None, 1], [None], [-1]], [[None, -1], [None], [1]]]\n sage: len(list(StrongTableaux.standard_marked_iterator(4,4)))\n 10\n sage: len(list(StrongTableaux.standard_marked_iterator(4,6)))\n 140\n sage: len(list(StrongTableaux.standard_marked_iterator(4,4, inner_shape=[2,2])))\n 200\n sage: len(list(StrongTableaux.standard_marked_iterator(4,4, outer_shape=[5,2,2,1], inner_shape=[2,2])))\n 24\n\n TESTS::\n\n sage: list(StrongTableaux.standard_marked_iterator(2,0,inner_shape=[3,1]))\n [[[None, None, None], [None]]]\n sage: list(StrongTableaux.standard_marked_iterator(4,0))\n [[]]\n ' for T in cls.standard_unmarked_iterator(k, size, outer_shape, inner_shape): (yield from cls.marked_given_unmarked_and_weight_iterator(T, k, ([1] * size))) @classmethod def cells_head_dictionary(cls, T): '\n Return a dictionary with the locations of the heads of all markings.\n\n Return a dictionary of values and lists of cells where the heads with the values\n are located in a strong standard unmarked tableau ``T``.\n\n INPUT:\n\n - ``T`` -- a strong standard unmarked tableau as a list of lists\n\n OUTPUT:\n\n - a dictionary with keys the entries in the tableau and values are the coordinates\n of the heads with those entries\n\n EXAMPLES::\n\n sage: StrongTableaux.cells_head_dictionary([[1,2,4,7],[3,6,6,8],[4,7],[5,8]])\n {1: [(0, 0)],\n 2: [(0, 1)],\n 3: [(1, 0)],\n 4: [(2, 0), (0, 2)],\n 5: [(3, 0)],\n 6: [(1, 2)],\n 7: [(2, 1), (0, 3)],\n 8: [(3, 1), (1, 3)]}\n sage: StrongTableaux.cells_head_dictionary([[None, 2, 2, 4, 5, 6, 6, 6], [None, 3, 6, 6, 6], [1, 4]])\n {1: [(2, 0)],\n 2: [(0, 2)],\n 3: [(1, 1)],\n 4: [(2, 1), (0, 3)],\n 5: [(0, 4)],\n 6: [(1, 4), (0, 7)]}\n\n TESTS::\n\n sage: StrongTableaux.cells_head_dictionary([[None, None, None],[None]])\n {}\n sage: StrongTableaux.cells_head_dictionary([])\n {}\n ' if (T == []): return {} ST = SkewTableau(T) dout = {} for i in range((- len(T)), len(T[0])): nextv = ST.entries_by_content((i + 1)) for c in ST.cells_by_content(i): v = T[c[0]][c[1]] if (v not in nextv): if (v in dout): dout[v] += [c] else: dout[v] = [c] return dout @classmethod def marked_CST_to_transposition_sequence(self, T, k): '\n Return a list of transpositions corresponding to ``T``.\n\n Given a strong column strict tableau ``T`` returns the list of transpositions\n which when applied to the left of an empty tableau gives the corresponding strong\n standard tableau.\n\n INPUT:\n\n - ``T`` -- a non-empty column strict tableau as a list of lists\n - ``k`` -- a positive integer\n\n OUTPUT:\n\n - a list of pairs of values ``[i,j]`` representing the transpositions `t_{ij}`\n\n EXAMPLES::\n\n sage: CST_to_trans = StrongTableaux.marked_CST_to_transposition_sequence\n sage: CST_to_trans([[-1, -1, -1], [1]], 2)\n [[2, 3], [1, 2], [0, 1]]\n sage: CST_to_trans([], 2)\n []\n sage: CST_to_trans([[-2, -2, -2], [2]], 2)\n [[2, 3], [1, 2], [0, 1]]\n sage: CST_to_trans([[-1, -2, -2, -2, -2], [-2, 2], [2]], 3)\n [[4, 5], [3, 4], [2, 3], [1, 2], [-1, 0], [0, 1]]\n sage: CST_to_trans([[-1, -2, -5, 5, -5, 5, -5], [-3, -4, 5, 5], [5]],3)\n [[5, 7], [3, 5], [2, 3], [0, 1], [-1, 0], [1, 2], [0, 1]]\n sage: CST_to_trans([[-1, -2, -3, 4, -7], [-4, -6], [-5, 6]],3)\n [[4, 5], [-1, 1], [-2, -1], [-1, 0], [2, 3], [1, 2], [0, 1]]\n\n TESTS::\n\n sage: StrongTableaux.marked_CST_to_transposition_sequence([[None, None, None], [None]], 2)\n []\n sage: StrongTableaux.marked_CST_to_transposition_sequence([], 4)\n []\n ' LL = list(T) if ((not LL) or all(((v is None) for v in sum(LL, [])))): return [] marks = ([v for row in T for v in row if ((v is not None) and (v < 0))] + [0]) m = (- min(marks)) transeq = [] sh = Core([len(r) for r in T], (k + 1)) j = max(((c - r) for (r, row) in enumerate(LL) for (c, val) in enumerate(row) if (val == (- m)))) P = sh.to_partition() for l in range(k): msh = sh.affine_symmetric_group_action([(j - l), (j + 1)], transposition=True) mP = msh.to_partition() if (msh.length() == (sh.length() - 1)): valcells = [] regcells = [] valid = True for (x, y) in SkewPartition([P, mP]).cells(): if ((y - x) != j): if (LL[x][y] != m): valid = False break valcells.append(LL[x][y]) else: regcells.append(LL[x][y]) if (valid and (regcells == [(- m)])): mcells = mP.cells() MM = [[LL[a][b] for b in range(len(LL[a])) if ((a, b) in mcells)] for a in range(len(mP))] transeq = self.marked_CST_to_transposition_sequence(MM, k) if (transeq is not None): return ([[(j - l), (j + 1)]] + transeq) @classmethod def transpositions_to_standard_strong(self, transeq, k, emptyTableau=[]): '\n Return a strong tableau corresponding to a sequence of transpositions.\n\n This method returns the action by left multiplication on the empty strong tableau\n by transpositions specified by ``transeq``.\n\n INPUT:\n\n - ``transeq`` -- a sequence of transpositions `t_{ij}` (a list of pairs).\n - ``emptyTableau`` -- (default: ``[]``) an empty list or a skew strong tableau\n possibly consisting of ``None`` entries\n\n OUTPUT:\n\n - a ``StrongTableau`` object\n\n EXAMPLES::\n\n sage: StrongTableaux.transpositions_to_standard_strong([[0,1]], 2)\n [[-1]]\n sage: StrongTableaux.transpositions_to_standard_strong([[-2,-1], [2,3]], 2, [[None, None]])\n [[None, None, -1], [1], [-2]]\n sage: StrongTableaux.transpositions_to_standard_strong([[2, 3], [1, 2], [0, 1]], 2)\n [[-1, -2, -3], [3]]\n sage: StrongTableaux.transpositions_to_standard_strong([[-1, 0], [1, 2], [0, 1]], 2)\n [[-1, -2, 3], [-3]]\n sage: StrongTableaux.transpositions_to_standard_strong([[3, 4], [-1, 0], [1, 2]], 2, [[None]])\n [[None, -1, 2, -3], [-2, 3]]\n\n TESTS::\n\n sage: StrongTableaux.transpositions_to_standard_strong([], 2, [[None, None, None], [None]])\n [[None, None, None], [None]]\n sage: StrongTableaux.transpositions_to_standard_strong([], 4, [])\n []\n ' out = copy.deepcopy(emptyTableau) for i in range(1, (len(transeq) + 1)): out = StrongTableaux._left_action_list(out, transeq[(- i)], i, k) return StrongTableau(out, k, weight=((1,) * len(transeq))) Element = StrongTableau
def nabs(v): '\n Return the absolute value of ``v`` or ``None``.\n\n INPUT:\n\n - ``v`` -- either an integer or ``None``\n\n OUTPUT:\n\n - either a non-negative integer or ``None``\n\n EXAMPLES::\n\n sage: from sage.combinat.k_tableau import nabs\n sage: nabs(None)\n sage: nabs(-3)\n 3\n sage: nabs(None)\n ' if (v is None): return v else: return abs(v)
def intermediate_shapes(t): '\n Return the intermediate shapes of tableau ``t``.\n\n A (skew) tableau with letters `1, 2,\\ldots, \\ell` can be viewed as a sequence of\n shapes, where the `i`-th shape is given by the shape of the subtableau on letters\n `1, 2, \\ldots, i`. The output is the list of these shapes.\n\n OUTPUT:\n\n - a list of lists representing partitions\n\n EXAMPLES::\n\n sage: from sage.combinat.k_tableau import intermediate_shapes\n sage: t = WeakTableau([[1, 1, 2, 2, 3], [2, 3], [3]],3)\n sage: intermediate_shapes(t)\n [[], [2], [4, 1], [5, 2, 1]]\n\n sage: t = WeakTableau([[None, None, 2, 3, 4], [1, 4], [2]], 3)\n sage: intermediate_shapes(t)\n [[2], [2, 1], [3, 1, 1], [4, 1, 1], [5, 2, 1]]\n ' shapes = [] t = SkewTableau(list(t)) for i in range((len(t.weight()) + 1)): shapes += [t.restrict(i).outer_shape()] return shapes
class KazhdanLusztigPolynomial(UniqueRepresentation, SageObject): '\n A Kazhdan-Lusztig polynomial.\n\n INPUT:\n\n - ``W`` -- a Weyl Group\n - ``q`` -- an indeterminate\n\n OPTIONAL:\n\n - ``trace`` -- if ``True``, then this displays the trace: the intermediate\n results. This is instructive and fun.\n\n The parent of ``q`` may be a :class:`PolynomialRing` or a\n :class:`LaurentPolynomialRing`.\n\n EXAMPLES::\n\n sage: W = WeylGroup("B3",prefix="s")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: R.<q> = LaurentPolynomialRing(QQ)\n sage: KL = KazhdanLusztigPolynomial(W,q)\n sage: KL.P(s2,s3*s2*s3*s1*s2)\n 1 + q\n\n A faster implementation (using the optional package Coxeter 3) is given by::\n\n sage: W = CoxeterGroup([\'B\', 3], implementation=\'coxeter3\') # optional - coxeter3\n sage: W.kazhdan_lusztig_polynomial([2], [3,2,3,1,2]) # optional - coxeter3\n q + 1\n ' def __init__(self, W, q, trace=False): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup("B3",prefix="s")\n sage: R.<q> = LaurentPolynomialRing(QQ)\n sage: KL = KazhdanLusztigPolynomial(W,q)\n sage: TestSuite(KL).run()\n ' self._coxeter_group = W self._q = q self._trace = trace self._one = W.one() self._base_ring = q.parent() if isinstance(q, Polynomial): self._base_ring_type = 'polynomial' elif isinstance(q, LaurentPolynomial): self._base_ring_type = 'laurent' else: self._base_ring_type = 'unknown' @cached_method def R(self, x, y): '\n Return the Kazhdan-Lusztig `R` polynomial.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of the underlying Coxeter group\n\n EXAMPLES::\n\n sage: R.<q>=QQ[]\n sage: W = WeylGroup("A2", prefix="s")\n sage: [s1,s2]=W.simple_reflections()\n sage: KL = KazhdanLusztigPolynomial(W, q)\n sage: [KL.R(x,s2*s1) for x in [1,s1,s2,s1*s2]]\n [q^2 - 2*q + 1, q - 1, q - 1, 0]\n ' if (x == 1): x = self._one if (y == 1): y = self._one if (x == y): return self._base_ring.one() if (not x.bruhat_le(y)): return self._base_ring.zero() if (y.length() == 0): if (x.length() == 0): return self._base_ring.one() else: return self._base_ring.zero() s = self._coxeter_group.simple_reflection(y.first_descent(side='left')) if ((s * x).length() < x.length()): ret = self.R((s * x), (s * y)) if self._trace: print((' R(%s,%s)=%s' % (x, y, ret))) return ret else: ret = (((self._q - 1) * self.R((s * x), y)) + (self._q * self.R((s * x), (s * y)))) if self._trace: print((' R(%s,%s)=%s' % (x, y, ret))) return ret @cached_method def R_tilde(self, x, y): '\n Return the Kazhdan-Lusztig `\\tilde{R}` polynomial.\n\n Information about the `\\tilde{R}` polynomials can be found in\n [Dy1993]_ and [BB2005]_.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of the underlying Coxeter group\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: W = WeylGroup("A2", prefix="s")\n sage: [s1,s2] = W.simple_reflections()\n sage: KL = KazhdanLusztigPolynomial(W, q)\n sage: [KL.R_tilde(x,s2*s1) for x in [1,s1,s2,s1*s2]]\n [q^2, q, q, 0]\n ' if (x == 1): x = self._one if (y == 1): y = self._one if (not x.bruhat_le(y)): return self._base_ring.zero() if (x == y): return self._base_ring.one() s = self._coxeter_group.simple_reflection(y.first_descent(side='right')) if ((x * s).length() < x.length()): ret = self.R_tilde((x * s), (y * s)) if self._trace: print((' R_tilde(%s,%s)=%s' % (x, y, ret))) return ret else: ret = (self.R_tilde((x * s), (y * s)) + (self._q * self.R_tilde(x, (y * s)))) if self._trace: print((' R_tilde(%s,%s)=%s' % (x, y, ret))) return ret @cached_method def P(self, x, y): '\n Return the Kazhdan-Lusztig `P` polynomial.\n\n If the rank is large, this runs slowly at first but speeds up\n as you do repeated calculations due to the caching.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of the underlying Coxeter group\n\n .. SEEALSO::\n\n :mod:`~sage.libs.coxeter3.coxeter_group.CoxeterGroup.kazhdan_lusztig_polynomial`\n for a faster implementation using Fokko Ducloux\'s Coxeter3 C++ library.\n\n EXAMPLES::\n\n sage: R.<q> = QQ[]\n sage: W = WeylGroup("A3", prefix="s")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: KL = KazhdanLusztigPolynomial(W, q)\n sage: KL.P(s2,s2*s1*s3*s2)\n q + 1\n ' if (x == 1): x = self._one if (y == 1): y = self._one if (x == y): return self._base_ring.one() if (not x.bruhat_le(y)): return self._base_ring.zero() if (y.length() == 0): if (x.length() == 0): return self._base_ring.one() else: return self._base_ring.zero() p = sum((((- self.R(x, t)) * self.P(t, y)) for t in self._coxeter_group.bruhat_interval(x, y) if (t != x))) tr = (((y.length() - x.length()) + 1) // 2) ret = p.truncate(tr) if self._trace: print(' P({},{})={}'.format(x, y, ret)) return ret
class KeyPolynomial(CombinatorialFreeModule.Element): '\n A key polynomial.\n\n Key polynomials are polynomials that form a basis for a polynomial ring\n and are indexed by weak compositions.\n\n Elements should be created by first creating the basis\n :class:`KeyPolynomialBasis` and passing a list representing the indexing\n composition.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: f = k([4,3,2,1]) + k([1,2,3,4]); f\n k[1, 2, 3, 4] + k[4, 3, 2, 1]\n sage: f in k\n True\n ' def _mul_(self, other): '\n Multiply the elements ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k([4,3,2]) * k([1,1,1])\n k[5, 4, 3]\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k([4,3,2,0]) * k([1,1,1,0])\n k[5, 4, 3, 0]\n ' return self.parent().from_polynomial((self.expand() * other.expand())) def expand(self): '\n Return ``self`` written in the monomial basis (i.e., as an element\n in the corresponding polynomial ring).\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: f = k([4,3,2,1])\n sage: f.expand()\n z_3*z_2^2*z_1^3*z_0^4\n\n sage: f = k([1,2,3])\n sage: f.expand()\n z_2^3*z_1^2*z_0 + z_2^3*z_1*z_0^2 + z_2^2*z_1^3*z_0\n + 2*z_2^2*z_1^2*z_0^2 + z_2^2*z_1*z_0^3 + z_2*z_1^3*z_0^2\n + z_2*z_1^2*z_0^3\n ' P = self.parent() R = P._polynomial_ring out = R.zero() z = P.poly_gens() for (m, c) in self.monomial_coefficients().items(): (w, mu) = sorting_word(m) monom = R.prod(((z[i] ** mi) for (i, mi) in enumerate(mu) if mi)) out += (c * isobaric_divided_difference(monom, w)) return out to_polynomial = expand def pi(self, w): '\n Apply the operator `\\pi_w` to ``self``.\n\n ``w`` may be either a ``Permutation`` or a list of indices of simple\n transpositions (1-based).\n\n The convention is to apply from left to right so if\n ``w = [w1, w2, ..., wm]`` then we apply\n `\\pi_{w_2 \\cdots w_m} \\circ \\pi_{w_1}`\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k([3,2,1]).pi(2)\n k[3, 1, 2]\n sage: k([3,2,1]).pi([2,1])\n k[1, 3, 2]\n sage: k([3,2,1]).pi(Permutation([3,2,1]))\n k[1, 2, 3]\n sage: f = k([3,2,1]) + k([3,2,1,1])\n sage: f.pi(2)\n k[3, 1, 2] + k[3, 1, 2, 1]\n sage: k.one().pi(1)\n k[]\n\n sage: k([3,2,1,0]).pi(2).pi(2)\n k[3, 1, 2]\n sage: (-k([3,2,1,0]) + 4*k([3,1,2,0])).pi(2)\n 3*k[3, 1, 2]\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k([3,2,1,0]).pi(2)\n k[3, 1, 2, 0]\n sage: k([3,2,1,0]).pi([2,1])\n k[1, 3, 2, 0]\n sage: k([3,2,1,0]).pi(Permutation([3,2,1,4]))\n k[1, 2, 3, 0]\n sage: f = k([3,2,1,0]) + k([3,2,1,1])\n sage: f.pi(2)\n k[3, 1, 2, 0] + k[3, 1, 2, 1]\n sage: k.one().pi(1)\n k[0, 0, 0, 0]\n\n TESTS:\n\n We check that this is consistent with the definition via the\n isobaric divided difference oerators::\n\n sage: from sage.combinat.key_polynomial import isobaric_divided_difference as idd\n sage: k = KeyPolynomials(QQ, 4)\n sage: S4 = Permutations(4)\n sage: f = k([4,2,2,0])\n sage: all(idd(f.expand(), w.reduced_word()) == f.pi(w).expand() for w in S4)\n True\n\n sage: f = k([4,2,0,1]) - 3 * k([2,0,1,2])\n sage: all(idd(f.expand(), w.reduced_word()) == f.pi(w).expand() for w in S4)\n True\n ' P = self.parent() if isinstance(w, Permutation): w = w.reduced_word() if (not isinstance(w, Collection)): w = [w] if ((not w) or (not self)): return self N = (max(w) + 1) if ((P._k is not None) and (N > P._k)): raise ValueError(f'pi_{(N - 1)} does not exist for this polynomial ring') ret = P.element_class(P, {}) for (m, c) in self._monomial_coefficients.items(): m = list(m) n = len(m) for i in w: if (i > n): continue if (i == n): m += [0] n += 1 if (m[(i - 1)] <= m[i]): continue (m[(i - 1)], m[i]) = (m[i], m[(i - 1)]) m = P._indices(m) if (P._k is None): m = m.trim() if (m in ret._monomial_coefficients): ret._monomial_coefficients[m] += c else: ret._monomial_coefficients[m] = c if (not ret._monomial_coefficients[m]): del ret._monomial_coefficients return ret isobaric_divided_difference = pi def divided_difference(self, w): '\n Apply the divided difference operator `\\partial_w` to ``self``.\n\n The convention is to apply from left to right so if\n ``w = [w1, w2, ..., wm]`` then we apply\n `\\partial_{w_2 \\cdots w_m} \\circ \\partial_{w_1}`\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k([3,2,1]).divided_difference(2)\n k[3, 1, 1]\n sage: k([3,2,1]).divided_difference([2,3])\n k[3, 1]\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k([3,2,1,0]).divided_difference(2)\n k[3, 1, 1, 0]\n ' if (not isinstance(w, Collection)): w = [w] f = self.expand() for wi in w: f = divided_difference(f, wi) return self.parent().from_polynomial(f)
class KeyPolynomialBasis(CombinatorialFreeModule): "\n The key polynomial basis for a polynomial ring.\n\n For a full definition, see\n `SymmetricFunctions.com <https://www.symmetricfunctions.com/key.htm>`_.\n Key polynomials are indexed by weak compositions with no trailing zeros,\n and `\\sigma` is the permutation of shortest length which sorts the\n indexing composition into a partition.\n\n EXAMPLES:\n\n Key polynomials are a basis, indexed by (weak) compositions,\n for polynomial rings::\n\n sage: k = KeyPolynomials(QQ)\n sage: k([3,0,1,2])\n k[3, 0, 1, 2]\n sage: k([3,0,1,2])/2\n 1/2*k[3, 0, 1, 2]\n sage: R = k.polynomial_ring(); R\n Infinite polynomial ring in z over Rational Field\n\n sage: K = KeyPolynomials(GF(5)); K\n Key polynomial basis over Finite Field of size 5\n sage: 2*K([3,0,1,2])\n 2*k[3, 0, 1, 2]\n sage: 5*(K([3,0,1,2]) + K([3,1,1]))\n 0\n\n We can expand them in the standard monomial basis::\n\n sage: k([3,0,1,2]).expand()\n z_3^2*z_2*z_0^3 + z_3^2*z_1*z_0^3 + z_3*z_2^2*z_0^3\n + 2*z_3*z_2*z_1*z_0^3 + z_3*z_1^2*z_0^3 + z_2^2*z_1*z_0^3\n + z_2*z_1^2*z_0^3\n\n sage: k([0,0,2]).expand()\n z_2^2 + z_2*z_1 + z_2*z_0 + z_1^2 + z_1*z_0 + z_0^2\n\n If we have a polynomial, we can express it in the key basis::\n\n sage: z = R.gen()\n sage: k.from_polynomial(z[2]^2*z[1]*z[0])\n k[1, 1, 2] - k[1, 2, 1]\n\n sage: f = z[3]^2*z[2]*z[0]^3 + z[3]^2*z[1]*z[0]^3 + z[3]*z[2]^2*z[0]^3 + \\\n ....: 2*z[3]*z[2]*z[1]*z[0]^3 + z[3]*z[1]^2*z[0]^3 + z[2]^2*z[1]*z[0]^3 + \\\n ....: z[2]*z[1]^2*z[0]^3\n sage: k.from_polynomial(f)\n k[3, 0, 1, 2]\n\n Since the ring of key polynomials may be regarded as a different choice of\n basis for a polynomial ring, it forms an algebra, so we have\n multiplication::\n\n sage: k([10,5,2])*k([1,1,1])\n k[11, 6, 3]\n\n We can also multiply by polynomials in the monomial basis::\n\n sage: k([10,9,1])*z[0]\n k[11, 9, 1]\n sage: z[0] * k([10,9,1])\n k[11, 9, 1]\n sage: k([10,9,1])*(z[0] + z[3])\n k[10, 9, 1, 1] + k[11, 9, 1]\n\n When the sorting permutation is the longest element, the key polynomial\n agrees with the Schur polynomial::\n\n sage: s = SymmetricFunctions(QQ).schur()\n sage: k([1,2,3]).expand()\n z_2^3*z_1^2*z_0 + z_2^3*z_1*z_0^2 + z_2^2*z_1^3*z_0\n + 2*z_2^2*z_1^2*z_0^2 + z_2^2*z_1*z_0^3 + z_2*z_1^3*z_0^2\n + z_2*z_1^2*z_0^3\n sage: s[3,2,1].expand(3)\n x0^3*x1^2*x2 + x0^2*x1^3*x2 + x0^3*x1*x2^2 + 2*x0^2*x1^2*x2^2\n + x0*x1^3*x2^2 + x0^2*x1*x2^3 + x0*x1^2*x2^3\n\n The polynomial expansions can be computed using crystals and expressed in\n terms of the key basis::\n\n sage: T = crystals.Tableaux(['A',3],shape=[2,1])\n sage: f = T.demazure_character([3,2,1])\n sage: k.from_polynomial(f)\n k[1, 0, 0, 2]\n\n The default behavior is to work in a polynomial ring with infinitely many\n variables. One can work in a specicfied number of variables::\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k([3,0,1,2]).expand()\n z_0^3*z_1^2*z_2 + z_0^3*z_1*z_2^2 + z_0^3*z_1^2*z_3\n + 2*z_0^3*z_1*z_2*z_3 + z_0^3*z_2^2*z_3 + z_0^3*z_1*z_3^2 + z_0^3*z_2*z_3^2\n\n sage: k([0,0,2,0]).expand()\n z_0^2 + z_0*z_1 + z_1^2 + z_0*z_2 + z_1*z_2 + z_2^2\n\n sage: k([0,0,2,0]).expand().parent()\n Multivariate Polynomial Ring in z_0, z_1, z_2, z_3 over Rational Field\n\n If working in a specified number of variables, the length of the indexing\n composition must be the same as the number of variables::\n\n sage: k([0,0,2])\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= [0, 0, 2]) an element of self\n (=Key polynomial basis over Rational Field)\n\n One can also work in a specified polynomial ring::\n\n sage: k = KeyPolynomials(QQ['x0', 'x1', 'x2', 'x3'])\n sage: k([0,2,0,0])\n k[0, 2, 0, 0]\n sage: k([4,0,0,0]).expand()\n x0^4\n\n If one wishes to use a polynomial ring as coefficients for the key\n polynomials, pass the keyword argument ``poly_coeffs=True``::\n\n sage: k = KeyPolynomials(QQ['q'], poly_coeffs=True)\n sage: R = k.base_ring(); R\n Univariate Polynomial Ring in q over Rational Field\n sage: R.inject_variables()\n Defining q\n sage: (q^2 + q + 1)*k([0,2,2,0,3,2])\n (q^2+q+1)*k[0, 2, 2, 0, 3, 2]\n " Element = KeyPolynomial @staticmethod def __classcall_private__(cls, R=None, k=None, poly_ring=None, poly_coeffs=False): "\n Normalize input.\n\n EXAMPLES::\n\n sage: KeyPolynomials(InfinitePolynomialRing(QQ, ['x', 'y']))\n Traceback (most recent call last):\n ...\n ValueError: polynomial ring has too many generators\n\n sage: KeyPolynomials(QQ['t0','t1','t2','t3'])\n Key polynomial basis over Rational Field\n\n sage: KeyPolynomials(QQ['t'])\n Key polynomial basis over Rational Field\n\n sage: KeyPolynomials(InfinitePolynomialRing(QQ['t'], 'z'))\n Key polynomial basis over Univariate Polynomial Ring in t over Rational Field\n\n sage: KeyPolynomials(QQ)\n Key polynomial basis over Rational Field\n\n sage: KeyPolynomials(QQ, 3)\n Key polynomial basis over Rational Field\n " poly_type = (PolynomialRing_commutative, MPolynomialRing_base, InfinitePolynomialRing_sparse) if isinstance(R, poly_type): if isinstance(R, poly_type[0:2]): k = R.ngens() if (isinstance(R, InfinitePolynomialRing_sparse) and (R.ngens() > 1)): raise ValueError('polynomial ring has too many generators') if isinstance(R.base_ring(), poly_type[0:2]): return cls.__classcall__(cls, k=k, poly_ring=R) if poly_coeffs: return cls.__classcall__(cls, R=R) return cls.__classcall__(cls, k=k, poly_ring=R) else: return cls.__classcall__(cls, R=R, k=k) def __init__(self, R=None, k=None, poly_ring=None): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: R = GF(3)['t'].fraction_field()\n sage: k = KeyPolynomials(QQ)\n sage: TestSuite(k).run()\n sage: k = KeyPolynomials(R)\n sage: TestSuite(k).run()\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: TestSuite(k).run()\n sage: k = KeyPolynomials(R, 4)\n sage: TestSuite(k).run()\n " self._k = k if (self._k is not None): def build_index(m): return self._indices(m) else: def build_index(m): return self._indices(reversed(m)).trim() self._build_index = build_index if (R is not None): if poly_ring: raise ValueError('specify only one of base_ring or poly_ring (not both)') if k: self._polynomial_ring = PolynomialRing(R, 'z_', k) else: self._polynomial_ring = InfinitePolynomialRing(R, 'z') if (poly_ring is not None): if (R is not None): raise ValueError('specify only one of base_ring or poly_ring (not both)') R = poly_ring.base_ring() self._polynomial_ring = poly_ring self._name = 'Key polynomial basis' CombinatorialFreeModule.__init__(self, R, IntegerVectors(k=k), category=GradedAlgebrasWithBasis(R), prefix='k', bracket=False) def _coerce_map_from_(self, R): '\n Return the coercion map from ``R`` if it exists.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: m1 = k([3, 2, 4, 0]); m1\n k[3, 2, 4]\n sage: m2 = k(Composition([3, 2, 4])); m2\n k[3, 2, 4]\n sage: m1 == m2\n True\n\n sage: R = k.polynomial_ring()\n sage: z = R.gen()\n sage: z[0] * k([4, 3, 3, 2])\n k[5, 3, 3, 2]\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: k(X([4, 3, 2, 1]))\n k[3, 2, 1]\n ' P = self._polynomial_ring if (R is P): return self.from_polynomial from sage.combinat.schubert_polynomial import SchubertPolynomialRing_xbasis if isinstance(R, SchubertPolynomialRing_xbasis): return self.from_schubert_polynomial phi = P.coerce_map_from(R) if (phi is not None): return (self.coerce_map_from(P) * phi) return None def _monomial(self, x): '\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k([3, 2, 3, 4, 0])\n k[3, 2, 3, 4]\n sage: k = KeyPolynomials(QQ, 5)\n sage: k([3, 2, 3, 4, 0])\n k[3, 2, 3, 4, 0]\n ' if self._k: return self._from_dict({x: self.base_ring().one()}, remove_zeros=False) return self._from_dict({x.trim(): self.base_ring().one()}, remove_zeros=False) def __getitem__(self, c): "\n This method implements the abuses of notations ``k[2,1]``,\n ``k[[2,1]]``, etc.\n\n INPUT:\n\n - ``c`` -- anything that can represent an index of a basis element\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k[3]\n k[3]\n sage: k[3, 0, 2]\n k[3, 0, 2]\n sage: k[3, 1, 2, 0, 0]\n k[3, 1, 2]\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k[3, 0, 1, 0]\n k[3, 0, 1, 0]\n sage: k[3]\n Traceback (most recent call last):\n ...\n ValueError: [3] doesn't satisfy correct constraints\n " C = self._indices if (not isinstance(c, C.element_class)): if (c in ZZ): c = C([c]) else: c = C(c) return self._monomial(c) @cached_method def one_basis(self): '\n Return the basis element indexing the identity.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k.one_basis()\n []\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k.one_basis()\n [0, 0, 0, 0]\n ' if self._k: return self._indices(([0] * self._k)) return self._indices([]) def degree_on_basis(self, alpha): '\n Return the degree of the basis element indexed by ``alpha``.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k.degree_on_basis([2,1,0,2])\n 5\n\n sage: k = KeyPolynomials(QQ, 5)\n sage: k.degree_on_basis([2,1,0,2,0])\n 5\n ' return ZZ(sum(alpha)) def polynomial_ring(self): '\n Return the polynomial ring associated to ``self``.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k.polynomial_ring()\n Infinite polynomial ring in z over Rational Field\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k.polynomial_ring()\n Multivariate Polynomial Ring in z_0, z_1, z_2, z_3 over Rational Field\n ' return self._polynomial_ring def poly_gens(self): '\n Return the polynomial generators for the polynomial ring\n associated to ``self``.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: k.poly_gens()\n z_*\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: k.poly_gens()\n (z_0, z_1, z_2, z_3)\n ' if self._k: return self._polynomial_ring.gens() return self._polynomial_ring.gen() def from_polynomial(self, f): "\n Expand a polynomial in terms of the key basis.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(QQ)\n sage: z = k.poly_gens(); z\n z_*\n sage: p = z[0]^4*z[1]^2*z[2]*z[3] + z[0]^4*z[1]*z[2]^2*z[3]\n sage: k.from_polynomial(p)\n k[4, 1, 2, 1]\n\n sage: all(k(c) == k.from_polynomial(k(c).expand()) for c in IntegerVectors(n=5, k=4))\n True\n\n sage: T = crystals.Tableaux(['A', 4], shape=[4,2,1,1])\n sage: k.from_polynomial(T.demazure_character([2]))\n k[4, 1, 2, 1]\n\n " if (f not in self._polynomial_ring): try: from sage.calculus.var import var f = f.substitute(list(((d == var(f'z_{i}')) for (i, d) in enumerate(f.variables())))) f = self._polynomial_ring(f) except AttributeError: raise ValueError(f'f must be an element of {self._polynomial_ring}') out = self.zero() while f: M = f.monomials()[0] c = f.monomial_coefficient(M) new_term = self._from_dict({self._build_index(*M.exponents()): c}) f -= new_term.expand() out += new_term return out def from_schubert_polynomial(self, x): '\n Expand a Schubert polynomial in the key basis.\n\n EXAMPLES::\n\n sage: k = KeyPolynomials(ZZ)\n sage: X = SchubertPolynomialRing(ZZ)\n sage: f = X([2,1,5,4,3])\n sage: k.from_schubert_polynomial(f)\n k[1, 0, 2, 1] + k[2, 0, 2] + k[3, 0, 0, 1]\n sage: k.from_schubert_polynomial(2)\n 2*k[]\n sage: k(f)\n k[1, 0, 2, 1] + k[2, 0, 2] + k[3, 0, 0, 1]\n\n sage: k = KeyPolynomials(GF(7), 4)\n sage: k.from_schubert_polynomial(f)\n k[1, 0, 2, 1] + k[2, 0, 2, 0] + k[3, 0, 0, 1]\n\n TESTS::\n\n sage: k = KeyPolynomials(ZZ)\n sage: k.from_schubert_polynomial(k([3,2]))\n Traceback (most recent call last):\n ...\n ValueError: not a Schubert polynomial\n\n sage: k = KeyPolynomials(ZZ)\n sage: X = SchubertPolynomialRing(ZZ)\n sage: it = iter(Compositions())\n sage: for _ in range(50):\n ....: C = next(it)\n ....: assert k.from_schubert_polynomial(X(k[C])) == k[C], C\n\n sage: k = KeyPolynomials(ZZ, 4)\n sage: X = SchubertPolynomialRing(ZZ)\n sage: it = iter(k.basis().keys())\n sage: for _ in range(50):\n ....: C = next(it)\n ....: assert k.from_schubert_polynomial(X(k[C])) == k[C], C\n ' if (x in self.base_ring()): return self(x) from sage.combinat.schubert_polynomial import SchubertPolynomial_class if (not isinstance(x, SchubertPolynomial_class)): raise ValueError('not a Schubert polynomial') from sage.combinat.diagram import RotheDiagram out = self.zero() if (self._k is not None): def build_elt(wt): wt = list(wt) wt += ([0] * (self._k - len(wt))) return self[wt] else: def build_elt(wt): return self[wt] for (m, c) in x.monomial_coefficients().items(): D = RotheDiagram(m) a = self.zero() for d in D.peelable_tableaux(): a += build_elt(d.left_key_tableau().weight()) out += (c * a) return out
def divided_difference(f, i): '\n Apply the ``i``-th divided difference operator to the polynomial ``f``.\n\n EXAMPLES::\n\n sage: from sage.combinat.key_polynomial import divided_difference\n sage: k = KeyPolynomials(QQ)\n sage: z = k.poly_gens()\n sage: f = z[1]*z[2]^3 + z[1]*z[2]*z[3]\n sage: divided_difference(f, 3)\n z_3^2*z_1 + z_3*z_2*z_1 + z_2^2*z_1\n\n sage: k = KeyPolynomials(QQ, 4)\n sage: z = k.poly_gens()\n sage: f = z[1]*z[2]^3 + z[1]*z[2]*z[3]\n sage: divided_difference(f, 3)\n z_1*z_2^2 + z_1*z_2*z_3 + z_1*z_3^2\n\n sage: k = KeyPolynomials(QQ)\n sage: R = k.polynomial_ring(); R\n Infinite polynomial ring in z over Rational Field\n sage: z = R.gen()\n sage: divided_difference(z[1]*z[2]^3, 2)\n -z_2^2*z_1 - z_2*z_1^2\n sage: divided_difference(z[1]*z[2]*z[3], 3)\n 0\n sage: divided_difference(z[1]*z[2]*z[3], 4)\n z_2*z_1\n sage: divided_difference(z[1]*z[2]*z[4], 4)\n -z_2*z_1\n\n sage: k = KeyPolynomials(QQ, 5)\n sage: z = k.polynomial_ring().gens()\n sage: divided_difference(z[1]*z[2]^3, 2)\n -z_1^2*z_2 - z_1*z_2^2\n sage: divided_difference(z[1]*z[2]*z[3], 3)\n 0\n sage: divided_difference(z[1]*z[2]*z[3], 4)\n z_1*z_2\n sage: divided_difference(z[1]*z[2]*z[4], 4)\n -z_1*z_2\n ' P = parent(f) if isinstance(P, InfinitePolynomialRing_sparse): z = P.gen() else: z = P.gens() si_f = f.subs({z[i]: z[(i - 1)], z[(i - 1)]: z[i]}) return ((si_f - f) // (z[i] - z[(i - 1)]))
def isobaric_divided_difference(f, w): '\n Apply the isobaric divided difference operator `\\pi_w` to the\n polynomial `f`.\n\n ``w`` may be either a single index or a list of\n indices of simple transpositions.\n\n .. WARNING::\n\n The simple transpositions should be applied from left to right.\n\n EXAMPLES::\n\n sage: from sage.combinat.key_polynomial import isobaric_divided_difference as idd\n sage: R.<z> = InfinitePolynomialRing(GF(3))\n sage: idd(z[1]^4*z[2]^2*z[4], 4)\n 0\n\n sage: idd(z[1]^4*z[2]^2*z[3]*z[4], 3)\n z_4*z_3^2*z_2*z_1^4 + z_4*z_3*z_2^2*z_1^4\n\n sage: idd(z[1]^4*z[2]^2*z[3]*z[4], [3, 4])\n z_4^2*z_3*z_2*z_1^4 + z_4*z_3^2*z_2*z_1^4 + z_4*z_3*z_2^2*z_1^4\n\n sage: idd(z[1]^4*z[2]^2*z[3]*z[4], [4, 3])\n z_4*z_3^2*z_2*z_1^4 + z_4*z_3*z_2^2*z_1^4\n\n sage: idd(z[1]^2*z[2], [3, 2])\n z_3*z_2^2 + z_3*z_2*z_1 + z_3*z_1^2 + z_2^2*z_1 + z_2*z_1^2\n ' P = parent(f) if isinstance(P, InfinitePolynomialRing_sparse): z = P.gen() else: z = P.gens() if (not hasattr(w, '__iter__')): w = [w] for i in w: fp = (z[(i - 1)] * f) si_fp = fp.subs({z[i]: z[(i - 1)], z[(i - 1)]: z[i]}) f = ((si_fp - fp) // (z[i] - z[(i - 1)])) return f
def sorting_word(alpha): '\n Get a reduced word for the permutation which sorts ``alpha``\n into a partition.\n\n The result is a list ``l = [i0, i1, i2, ...]`` where each ``ij``\n is a positive integer such that it applies the simple\n transposition `(i_j, i_j+1)`. The transpositions are applied\n starting with ``i0``, then ``i1`` is applied, followed by ``i2``,\n and so on. See :meth:`sage.combinat.permutation.Permutation.reduced_words`\n for the convention used.\n\n EXAMPLES::\n\n sage: IV = IntegerVectors()\n sage: from sage.combinat.key_polynomial import sorting_word\n sage: list(sorting_word(IV([2,3,2]))[0])\n [1]\n sage: sorting_word(IV([2,3,2]))[1]\n [3, 2, 2]\n sage: list(sorting_word(IV([5,6,7]))[0])\n [1, 2, 1]\n sage: list(sorting_word(IV([0,3,2]))[0])\n [2, 1]\n sage: list(sorting_word(IV([0,3,0,2]))[0])\n [2, 3, 1]\n sage: list(sorting_word(IV([3,2,1]))[0])\n []\n sage: list(sorting_word(IV([2,3,3]))[0])\n [2, 1]\n ' w = [] L = list(alpha) n = len(L) for i in range((n - 1)): for j in range(((n - i) - 1)): if (L[j] < L[(j + 1)]): w.append((j + 1)) (L[j], L[(j + 1)]) = (L[(j + 1)], L[j]) return (reversed(w), L)
class PuzzlePiece(): '\n Abstract class for puzzle pieces.\n\n This abstract class contains information on how to test equality of\n puzzle pieces, and sets color and plotting options.\n ' def __eq__(self, other) -> bool: "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: delta1 = DeltaPiece('a','b','c')\n sage: delta == delta1\n True\n sage: delta1 = DeltaPiece('A','b','c')\n sage: delta == delta1\n False\n " if isinstance(other, PuzzlePiece): return (self.border() == other.border()) else: return False def __hash__(self): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: hash(delta) == hash(delta)\n True\n " return hash((type(self), self.border())) def border(self) -> tuple: "\n Return the border of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: sorted(delta.border())\n ['a', 'b', 'c']\n " return tuple((self.edge_label(edge) for edge in self.edges())) def color(self) -> str: "\n Return the color of ``self``.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: delta.color()\n 'white'\n sage: delta = DeltaPiece('0','0','0')\n sage: delta.color()\n 'red'\n sage: delta = DeltaPiece('1','1','1')\n sage: delta.color()\n 'blue'\n sage: delta = DeltaPiece('2','2','2')\n sage: delta.color()\n 'green'\n sage: delta = DeltaPiece('2','K','2')\n sage: delta.color()\n 'orange'\n sage: delta = DeltaPiece('2','T1/2','2')\n sage: delta.color()\n 'yellow'\n " colors = {('0', '0', '0'): 'red', ('1', '1', '1'): 'blue', ('2', '2', '2'): 'green'} border = self.border() if (border in colors): color = colors[border] elif ('K' in border): color = 'orange' elif ('10' in border): color = 'white' elif any((label.startswith('T') for label in border)): color = 'yellow' else: color = 'white' return color def _plot_label(self, label, coords, fontcolor=(0.3, 0.3, 0.3), fontsize=15, rotation=0): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('2','K','2')\n sage: delta._plot_label('1',(1,1)) # not tested\n " if (label in ('0', '1', '2')): return text(label, coords, color=fontcolor, fontsize=fontsize, rotation=rotation) else: return Graphics() def _plot_piece(self, coords, border_color=(0.5, 0.5, 0.5), border_thickness=1, style='fill'): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('2','K','2')\n sage: delta._plot_piece([(1,1),(1,2),(2,2)]) # not tested\n " if (style == 'fill'): P = polygon(coords, color=self.color()) P += polygon(coords, fill=False, color=border_color, thickness=border_thickness) return P elif (style == 'edges'): if isinstance(self, DeltaPiece): edges = ('north_west', 'south', 'north_east') elif isinstance(self, NablaPiece): edges = ('south_west', 'north', 'south_east') else: edges = self.edges() P = Graphics() for (i, edge) in enumerate(edges): P += line([coords[i], coords[((i + 1) % 3)]], color=self.edge_color(edge), thickness=border_thickness) return P else: return NotImplemented def edge_color(self, edge) -> str: "\n Color of the specified edge of ``self`` (to be used when plotting the\n piece).\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('1','0','10')\n sage: delta.edge_color('south')\n 'blue'\n sage: delta.edge_color('north_west')\n 'red'\n sage: delta.edge_color('north_east')\n 'white'\n " edge_label = self.edge_label(edge) colors = {'1': 'blue', '0': 'red'} if (edge_label in colors): color = colors[edge_label] elif ('K' in edge_label): color = 'orange' elif edge_label.startswith('T'): color = 'yellow' else: color = 'white' return color def edge_label(self, edge) -> str: "\n Return the edge label of ``edge``.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('2','K','2')\n sage: delta.edge_label('south')\n '2'\n sage: delta.edge_label('north_east')\n '2'\n sage: delta.edge_label('north_west')\n 'K'\n " return self._edge_labels[edge] __getitem__ = edge_label
class NablaPiece(PuzzlePiece): "\n Nabla Piece takes as input three labels, inputted as strings. They label\n the North, Southeast and Southwest edges, respectively.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: NablaPiece('a','b','c')\n c\\a/b\n " def __init__(self, north, south_east, south_west): "\n INPUT:\n\n - ``north``, ``south_east``, ``south_west`` -- strings, which label the edges\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: NablaPiece('1','2','3')\n 3\\1/2\n " self._edge_labels = dict(north=north, south_east=south_east, south_west=south_west) def __eq__(self, other) -> bool: "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: n = NablaPiece('a','b','c')\n sage: n1 = NablaPiece('a','b','c')\n sage: n == n1\n True\n sage: n1 = NablaPiece('A','b','c')\n sage: n == n1\n False\n " if isinstance(other, NablaPiece): return ((self.border() == other.border()) and (self._edge_labels == other._edge_labels)) else: return False def __hash__(self): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: n = NablaPiece('a','b','c')\n sage: hash(n) == hash(n)\n True\n " return hash((NablaPiece, self.border())) def __repr__(self) -> str: "\n Print the labels of the Nabla piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: NablaPiece('1','2','3')\n 3\\1/2\n " return ('%s\\%s/%s' % (self['south_west'], self['north'], self['south_east'])) def clockwise_rotation(self) -> NablaPiece: "\n Rotate the Nabla piece by 120 degree clockwise.\n\n OUTPUT:\n\n - Nabla piece\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: nabla = NablaPiece('1','2','3')\n sage: nabla.clockwise_rotation()\n 2\\3/1\n " return NablaPiece(north=self['south_west'], south_east=self['north'], south_west=self['south_east']) def half_turn_rotation(self) -> DeltaPiece: "\n Rotate the Nabla piece by 180 degree.\n\n OUTPUT:\n\n - Delta piece\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: nabla = NablaPiece('1','2','3')\n sage: nabla.half_turn_rotation()\n 2/1\\3\n " return DeltaPiece(south=self['north'], north_west=self['south_east'], north_east=self['south_west']) def edges(self) -> tuple: "\n Return the tuple of edge names.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import NablaPiece\n sage: nabla = NablaPiece('1','2','3')\n sage: nabla.edges()\n ('north', 'south_east', 'south_west')\n " return ('north', 'south_east', 'south_west')
class DeltaPiece(PuzzlePiece): "\n Delta Piece takes as input three labels, inputted as strings. They label\n the South, Northwest and Northeast edges, respectively.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: DeltaPiece('a','b','c')\n b/a\\c\n " def __init__(self, south, north_west, north_east): "\n INPUT:\n\n - ``south``, ``north_west``, ``north_east`` -- strings, which label the edges\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: DeltaPiece('1','2','3')\n 2/1\\3\n " self._edge_labels = dict(south=south, north_west=north_west, north_east=north_east) def __eq__(self, other) -> bool: "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: delta1 = DeltaPiece('a','b','c')\n sage: delta == delta1\n True\n sage: delta1 = DeltaPiece('A','b','c')\n sage: delta == delta1\n False\n " if isinstance(other, DeltaPiece): return ((self.border() == other.border()) and (self._edge_labels == other._edge_labels)) else: return False def __hash__(self): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: hash(delta) == hash(delta)\n True\n " return hash((DeltaPiece, self.border())) def __repr__(self) -> str: "\n Print the labels of the Delta piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: DeltaPiece('1','2','3')\n 2/1\\3\n " return ('%s/%s\\%s' % (self['north_west'], self['south'], self['north_east'])) def clockwise_rotation(self) -> DeltaPiece: "\n Rotate the Delta piece by 120 degree clockwise.\n\n OUTPUT:\n\n - Delta piece\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: delta.clockwise_rotation()\n 1/3\\2\n " return DeltaPiece(south=self['north_east'], north_west=self['south'], north_east=self['north_west']) def half_turn_rotation(self) -> NablaPiece: "\n Rotate the Delta piece by 180 degree.\n\n OUTPUT:\n\n - Nabla piece\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: delta.half_turn_rotation()\n 3\\1/2\n " return NablaPiece(north=self['south'], south_east=self['north_west'], south_west=self['north_east']) def edges(self) -> tuple: "\n Return the tuple of edge names.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: delta.edges()\n ('south', 'north_west', 'north_east')\n " return ('south', 'north_west', 'north_east')
class RhombusPiece(PuzzlePiece): "\n Class of rhombi pieces.\n\n To construct a rhombus piece we input a delta and a nabla piece.\n The delta and nabla pieces are joined along the south and north edge,\n respectively.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: RhombusPiece(delta,nabla)\n 2/\\3 6\\/5\n " def __init__(self, north_piece, south_piece): "\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: RhombusPiece(delta,nabla)\n 2/\\3 6\\/5\n " self._north_piece = north_piece self._south_piece = south_piece self._edge_labels = dict(north_west=north_piece['north_west'], north_east=north_piece['north_east'], south_east=south_piece['south_east'], south_west=south_piece['south_west']) def __eq__(self, other) -> bool: "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: r = RhombusPiece(delta,nabla)\n sage: r == r\n True\n sage: delta1 = DeltaPiece('A','b','c')\n sage: r == RhombusPiece(delta1,nabla)\n False\n " if isinstance(other, RhombusPiece): return ((self.border() == other.border()) and (self._north_piece == other._north_piece) and (self._south_piece == other._south_piece) and (self._edge_labels == other._edge_labels)) else: return False def __hash__(self): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: r = RhombusPiece(delta,nabla)\n sage: hash(r) == hash(r)\n True\n " return hash((RhombusPiece, self.border())) def __iter__(self): "\n Return the list of the north and south piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: r = RhombusPiece(delta,nabla)\n sage: list(r)\n [2/1\\3, 6\\4/5]\n " (yield self._north_piece) (yield self._south_piece) def north_piece(self) -> DeltaPiece: "\n Return the north piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: r = RhombusPiece(delta,nabla)\n sage: r.north_piece()\n 2/1\\3\n " return self._north_piece def south_piece(self) -> NablaPiece: "\n Return the south piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: r = RhombusPiece(delta,nabla)\n sage: r.south_piece()\n 6\\4/5\n " return self._south_piece def __repr__(self) -> str: "\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: RhombusPiece(delta,nabla)\n 2/\\3 6\\/5\n " return ('%s/\\%s %s\\/%s' % (self['north_west'], self['north_east'], self['south_west'], self['south_east'])) def edges(self) -> tuple: "\n Return the tuple of edge names.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, NablaPiece, RhombusPiece\n sage: delta = DeltaPiece('1','2','3')\n sage: nabla = NablaPiece('4','5','6')\n sage: RhombusPiece(delta,nabla).edges()\n ('north_west', 'north_east', 'south_east', 'south_west')\n " return ('north_west', 'north_east', 'south_east', 'south_west')
class PuzzlePieces(): "\n Construct a valid set of puzzle pieces.\n\n This class constructs the set of valid puzzle pieces. It can take a list of\n forbidden border labels as input. These labels are forbidden from appearing\n on the south edge of a puzzle filling. The user can add valid nabla or\n delta pieces and specify which rotations of these pieces are legal. For\n example, ``rotations=0`` does not add any additional pieces (only the piece\n itself), ``rotations=60`` adds six pieces (the pieces and its rotations by\n 60, 120, 180, 240, 300), etc..\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, NablaPiece\n sage: forbidden_border_labels = ['10']\n sage: pieces = PuzzlePieces(forbidden_border_labels)\n sage: pieces.add_piece(NablaPiece('0','0','0'), rotations=60)\n sage: pieces.add_piece(NablaPiece('1','1','1'), rotations=60)\n sage: pieces.add_piece(NablaPiece('1','0','10'), rotations=60)\n sage: pieces\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n\n The user can obtain the list of valid rhombi pieces as follows::\n\n sage: sorted([p for p in pieces.rhombus_pieces()], key=str)\n [0/\\0 0\\/0, 0/\\0 1\\/10, 0/\\10 10\\/0, 0/\\10 1\\/1, 1/\\0 0\\/1,\n 1/\\1 10\\/0, 1/\\1 1\\/1, 10/\\1 0\\/0, 10/\\1 1\\/10]\n " def __init__(self, forbidden_border_labels=None): "\n INPUT:\n\n - ``forbidden_border_labels`` -- list of forbidden border labels given as strings\n\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces\n sage: forbidden_border_labels = ['10']\n sage: pieces = PuzzlePieces(forbidden_border_labels)\n sage: pieces\n Nablas : []\n Deltas : []\n\n sage: PuzzlePieces('10')\n Traceback (most recent call last):\n ...\n TypeError: Input must be a list\n " self._nabla_pieces = set() self._delta_pieces = set() if (forbidden_border_labels is None): forbidden_border_labels = [] if (not isinstance(forbidden_border_labels, list)): raise TypeError('Input must be a list') self._forbidden_border_labels = forbidden_border_labels def __eq__(self, other) -> bool: '\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_grassmannian_pieces\n sage: x = H_grassmannian_pieces()\n sage: y = H_grassmannian_pieces()\n sage: x == y\n True\n ' if isinstance(other, type(self)): return (self.__dict__ == other.__dict__) else: return False def __hash__(self): '\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_grassmannian_pieces\n sage: x = H_grassmannian_pieces()\n sage: hash(x) == hash(x)\n True\n ' return hash((type(self), repr(self))) def add_piece(self, piece, rotations=120): "\n Add ``piece`` to the list of pieces.\n\n INPUT:\n\n - ``piece`` -- a nabla piece or a delta piece\n - ``rotations`` -- (default: 120) 0, 60, 120, 180\n\n The user can add valid nabla or delta pieces and specify\n which rotations of these pieces are legal. For example, ``rotations=0``\n does not add any additional pieces (only the piece itself), ``rotations=60`` adds\n six pieces (namely three delta and three nabla pieces), while\n ``rotations=120`` adds only delta or nabla (depending on which piece ``self`` is).\n ``rotations=180`` adds the piece and its 180 degree rotation, i.e. one delta and one\n nabla piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces = PuzzlePieces()\n sage: pieces\n Nablas : []\n Deltas : []\n sage: pieces.add_piece(delta)\n sage: pieces\n Nablas : []\n Deltas : [a/c\\b, b/a\\c, c/b\\a]\n\n sage: pieces = PuzzlePieces()\n sage: pieces.add_piece(delta,rotations=0)\n sage: pieces\n Nablas : []\n Deltas : [b/a\\c]\n\n sage: pieces = PuzzlePieces()\n sage: pieces.add_piece(delta,rotations=60)\n sage: pieces\n Nablas : [a\\b/c, b\\c/a, c\\a/b]\n Deltas : [a/c\\b, b/a\\c, c/b\\a]\n " if isinstance(piece, NablaPiece): pieces_list = self._nabla_pieces else: pieces_list = self._delta_pieces pieces_list.add(piece) if (rotations == 120): pieces_list.add(piece.clockwise_rotation()) pieces_list.add(piece.clockwise_rotation().clockwise_rotation()) elif (rotations == 180): self.add_piece(piece.half_turn_rotation(), rotations=0) elif (rotations == 60): self.add_piece(piece, rotations=120) self.add_piece(piece.half_turn_rotation(), rotations=120) def add_forbidden_label(self, label): "\n Add forbidden border labels.\n\n INPUT:\n\n - ``label`` -- string specifying a new forbidden label\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces\n sage: pieces = PuzzlePieces()\n sage: pieces.add_forbidden_label('1')\n sage: pieces._forbidden_border_labels\n ['1']\n sage: pieces.add_forbidden_label('2')\n sage: pieces._forbidden_border_labels\n ['1', '2']\n " self._forbidden_border_labels.append(label) def add_T_piece(self, label1, label2): "\n Add a nabla and delta piece with ``label1`` and ``label2``.\n\n This method adds a nabla piece with edges ``label2``\\ T``label1``|``label2`` / ``label1``.\n and a delta piece with edges ``label1``/ T``label1``|``label2`` \\ ``label2``.\n It also adds T``label1``|``label2`` to the forbidden list.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces\n sage: pieces = PuzzlePieces()\n sage: pieces.add_T_piece('1','3')\n sage: pieces\n Nablas : [3\\T1|3/1]\n Deltas : [1/T1|3\\3]\n sage: pieces._forbidden_border_labels\n ['T1|3']\n " self.add_forbidden_label(('T%s|%s' % (label1, label2))) self.add_piece(NablaPiece(('T%s|%s' % (label1, label2)), label1, label2), rotations=180) def __repr__(self) -> str: "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: pieces = PuzzlePieces()\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces.add_piece(delta,rotations=60)\n sage: pieces\n Nablas : [a\\b/c, b\\c/a, c\\a/b]\n Deltas : [a/c\\b, b/a\\c, c/b\\a]\n " s = ('Nablas : %s\n' % sorted([p for p in self._nabla_pieces], key=str)) s += ('Deltas : %s' % sorted([p for p in self._delta_pieces], key=str)) return s def delta_pieces(self): "\n Return the delta pieces as a set.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: pieces = PuzzlePieces()\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces.add_piece(delta,rotations=60)\n sage: sorted([p for p in pieces.delta_pieces()], key=str)\n [a/c\\b, b/a\\c, c/b\\a]\n " return self._delta_pieces def nabla_pieces(self): "\n Return the nabla pieces as a set.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: pieces = PuzzlePieces()\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces.add_piece(delta,rotations=60)\n sage: sorted([p for p in pieces.nabla_pieces()], key=str)\n [a\\b/c, b\\c/a, c\\a/b]\n " return self._nabla_pieces def rhombus_pieces(self) -> set: "\n Return a set of all allowable rhombus pieces.\n\n Allowable rhombus pieces are those where the south edge of the delta\n piece equals the north edge of the nabla piece.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: pieces = PuzzlePieces()\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces.add_piece(delta,rotations=60)\n sage: sorted([p for p in pieces.rhombus_pieces()], key=str)\n [a/\\b b\\/a, b/\\c c\\/b, c/\\a a\\/c]\n " rhombi = set() for nabla in self._nabla_pieces: for delta in self._delta_pieces: if (delta['south'] == nabla['north']): rhombi.add(RhombusPiece(delta, nabla)) return rhombi def boundary_deltas(self) -> tuple: "\n Return deltas with south edges not in the forbidden list.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzlePieces, DeltaPiece\n sage: pieces = PuzzlePieces(['a'])\n sage: delta = DeltaPiece('a','b','c')\n sage: pieces.add_piece(delta,rotations=60)\n sage: sorted([p for p in pieces.boundary_deltas()], key=str)\n [a/c\\b, c/b\\a]\n " return tuple((delta for delta in self.delta_pieces() if (delta['south'] not in self._forbidden_border_labels)))
def H_grassmannian_pieces(): '\n Define the puzzle pieces used in computing the cohomology of the Grassmannian.\n\n REFERENCES:\n\n .. [KTW] Allen Knutson, Terence Tao, Christopher Woodward,\n The honeycomb model of GL(n) tensor products II: Puzzles determine facets of the Littlewood-Richardson cone,\n :arxiv:`math/0107011`\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_grassmannian_pieces\n sage: H_grassmannian_pieces()\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n ' forbidden_border_labels = ['10'] pieces = PuzzlePieces(forbidden_border_labels) pieces.add_piece(NablaPiece('0', '0', '0'), rotations=60) pieces.add_piece(NablaPiece('1', '1', '1'), rotations=60) pieces.add_piece(NablaPiece('1', '0', '10'), rotations=60) return pieces
def HT_grassmannian_pieces(): '\n Define the puzzle pieces used in computing the torus-equivariant cohomology of the Grassmannian.\n\n REFERENCES:\n\n .. [KT2003] Allen Knutson, Terence Tao, Puzzles and (equivariant) cohomology of Grassmannians,\n Duke Math. J. 119 (2003) 221\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import HT_grassmannian_pieces\n sage: HT_grassmannian_pieces()\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1, 1\\T0|1/0]\n Deltas : [0/0\\0, 0/1\\10, 0/T0|1\\1, 1/10\\0, 1/1\\1, 10/0\\1]\n ' pieces = H_grassmannian_pieces() pieces.add_T_piece('0', '1') return pieces
def K_grassmannian_pieces(): '\n Define the puzzle pieces used in computing the K-theory of the Grassmannian.\n\n REFERENCES:\n\n .. [Buch00] \\A. Buch, A Littlewood-Richardson rule for the K-theory of Grassmannians, :arxiv:`math.AG/0004137`\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import K_grassmannian_pieces\n sage: K_grassmannian_pieces()\n Nablas : [0\\0/0, 0\\10/1, 0\\K/1, 10\\1/0, 1\\0/10, 1\\0/K, 1\\1/1, K\\1/0]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1, K/K\\K]\n ' pieces = H_grassmannian_pieces() pieces.add_forbidden_label('K') pieces.add_piece(NablaPiece('0', 'K', '1'), rotations=120) pieces.add_piece(DeltaPiece('K', 'K', 'K'), rotations=0) return pieces
def H_two_step_pieces(): '\n Define the puzzle pieces used in two step flags.\n\n This rule is currently only conjecturally true. See [BuchKreschTamvakis03]_.\n\n REFERENCES:\n\n .. [BuchKreschTamvakis03] \\A. Buch, A. Kresch, H. Tamvakis, Gromov-Witten invariants on Grassmannian, :arxiv:`math/0306388`\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_two_step_pieces\n sage: H_two_step_pieces()\n Nablas : [(21)0\\21/0, 0\\(21)0/21, 0\\0/0, 0\\10/1, 0\\20/2, 10\\1/0, 10\\2(10)/2, 1\\0/10, 1\\1/1, 1\\21/2,\n 2(10)\\2/10, 20\\2/0, 21\\0/(21)0, 21\\2/1, 2\\0/20, 2\\1/21, 2\\10/2(10), 2\\2/2]\n Deltas : [(21)0/0\\21, 0/0\\0, 0/1\\10, 0/21\\(21)0, 0/2\\20, 1/10\\0, 1/1\\1, 1/2\\21, 10/0\\1, 10/2\\2(10),\n 2(10)/10\\2, 2/2(10)\\10, 2/20\\0, 2/21\\1, 2/2\\2, 20/0\\2, 21/(21)0\\0, 21/1\\2]\n ' forbidden_border_labels = ['10', '20', '21', '(21)0', '2(10)'] pieces = PuzzlePieces(forbidden_border_labels) for i in ('0', '1', '2'): pieces.add_piece(DeltaPiece(i, i, i), rotations=60) for (i, j) in (('1', '0'), ('2', '0'), ('2', '1')): pieces.add_piece(DeltaPiece((i + j), i, j), rotations=60) pieces.add_piece(DeltaPiece('(21)0', '21', '0'), rotations=60) pieces.add_piece(DeltaPiece('2(10)', '2', '10'), rotations=60) return pieces
def HT_two_step_pieces(): '\n Define the puzzle pieces used in computing the equivariant two step puzzle pieces.\n\n For the puzzle pieces, see Figure 26 on page 22 of [CoskunVakil06]_.\n\n REFERENCES:\n\n .. [CoskunVakil06] \\I. Coskun, R. Vakil, Geometric positivity in the cohomology of homogeneous spaces\n and generalized Schubert calculus, :arxiv:`math/0610538`\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import HT_two_step_pieces\n sage: HT_two_step_pieces()\n Nablas : [(21)0\\21/0, 0\\(21)0/21, 0\\0/0, 0\\10/1, 0\\20/2, 10\\1/0, 10\\2(10)/2,\n 1\\0/10, 1\\1/1, 1\\21/2, 1\\T0|1/0, 2(10)\\2/10, 20\\2/0, 21\\0/(21)0, 21\\2/1, 21\\T0|21/0,\n 21\\T10|21/10, 2\\0/20, 2\\1/21, 2\\10/2(10), 2\\2/2, 2\\T0|2/0, 2\\T10|2/10, 2\\T1|2/1]\n Deltas : [(21)0/0\\21, 0/0\\0, 0/1\\10, 0/21\\(21)0, 0/2\\20, 0/T0|1\\1, 0/T0|21\\21, 0/T0|2\\2,\n 1/10\\0, 1/1\\1, 1/2\\21, 1/T1|2\\2, 10/0\\1, 10/2\\2(10), 10/T10|21\\21, 10/T10|2\\2, 2(10)/10\\2,\n 2/2(10)\\10, 2/20\\0, 2/21\\1, 2/2\\2, 20/0\\2, 21/(21)0\\0, 21/1\\2]\n ' pieces = H_two_step_pieces() for (label1, label2) in (('0', '1'), ('0', '2'), ('1', '2'), ('10', '2'), ('0', '21'), ('10', '21')): pieces.add_T_piece(label1, label2) return pieces
def BK_pieces(max_letter): '\n The puzzle pieces used in computing the Belkale-Kumar coefficients for any\n partial flag variety in type `A`.\n\n There are two types of puzzle pieces:\n\n - a triangle, with each edge labeled with the same letter;\n - a rhombus, with edges labeled `i`, `j`, `i`, `j` in clockwise order with\n `i > j`.\n\n Each of these is rotated by 60 degrees, but not reflected.\n\n We model the rhombus pieces as two triangles: a delta piece north-west\n label `i`, north-east label `j` and south label `i(j)`; and a nabla piece\n with south-east label `i`, south-west label `j` and north label `i(j)`.\n\n INPUT:\n\n - ``max_letter`` -- positive integer specifying the number of steps in the\n partial flag variety, equivalently, the number of elements in the\n alphabet for the edge labels. The smallest label is `1`.\n\n REFERENCES:\n\n .. [KnutsonPurbhoo10] \\A. Knutson, K. Purbhoo, Product and puzzle formulae\n for `GL_n` Belkale-Kumar coefficients, :arxiv:`1008.4979`\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import BK_pieces\n sage: BK_pieces(3)\n Nablas : [1\\1/1, 1\\2(1)/2, 1\\3(1)/3, 2(1)\\2/1, 2\\1/2(1), 2\\2/2, 2\\3(2)/3, 3(1)\\3/1, 3(2)\\3/2, 3\\1/3(1), 3\\2/3(2), 3\\3/3]\n Deltas : [1/1\\1, 1/2\\2(1), 1/3\\3(1), 2(1)/1\\2, 2/2(1)\\1, 2/2\\2, 2/3\\3(2), 3(1)/1\\3, 3(2)/2\\3, 3/3(1)\\1, 3/3(2)\\2, 3/3\\3]\n\n ' forbidden_border_labels = [('%s(%s)' % (i, j)) for i in range(1, (max_letter + 1)) for j in range(1, i)] pieces = PuzzlePieces(forbidden_border_labels) for i in range(1, (max_letter + 1)): piece = DeltaPiece(('%s' % i), ('%s' % i), ('%s' % i)) pieces.add_piece(piece, rotations=60) for j in range(1, i): piece = DeltaPiece(north_west=('%s' % i), north_east=('%s' % j), south=('%s(%s)' % (i, j))) pieces.add_piece(piece, rotations=60) return pieces
class PuzzleFilling(): '\n Create partial puzzles and provides methods to build puzzles from them.\n ' def __init__(self, north_west_labels, north_east_labels): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling('0101','0101')\n sage: P\n {}\n " self._nw_labels = tuple(north_west_labels) self._ne_labels = tuple(north_east_labels) self._squares = {} self._n = len(self._nw_labels) self._kink_coordinates = (1, self._n) def __getitem__(self, key): '\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: puzzle = ps(\'0101\',\'1001\')[0]\n sage: puzzle\n {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\10 1\\/1,\n (1, 4): 1/\\1 10\\/0,\n (2, 2): 0/0\\0,\n (2, 3): 1/\\0 0\\/1,\n (2, 4): 0/\\0 0\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}\n sage: puzzle[(1,2)] # indirect doctest\n 1/\\1 10\\/0\n ' return self._squares[key] def kink_coordinates(self) -> tuple: "\n Provide the coordinates of the kinks.\n\n The kink coordinates are the coordinates up to which the puzzle has already\n been built. The kink starts in the north corner and then moves down the diagonals\n as the puzzles is built.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling('0101','0101')\n sage: P\n {}\n sage: P.kink_coordinates()\n (1, 4)\n " return self._kink_coordinates def is_in_south_edge(self) -> bool: "\n Check whether kink coordinates of partial puzzle is in south corner.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling('0101','0101')\n sage: P.is_in_south_edge()\n False\n " (i, j) = self.kink_coordinates() return (i == j) def north_west_label_of_kink(self): "\n Return north-west label of kink.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling('0101','0101')\n sage: P.north_west_label_of_kink()\n '1'\n " (i, j) = self.kink_coordinates() if (i == 1): return self._nw_labels[(j - 1)] else: return self._squares[((i - 1), j)]['south_east'] def north_east_label_of_kink(self): "\n Return north east label of kink.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling('0101','0101')\n sage: P.north_east_label_of_kink()\n '0'\n " (i, j) = self.kink_coordinates() if (j == self._n): return self._ne_labels[(i - 1)] else: return self._squares[(i, (j + 1))]['south_west'] def is_completed(self): '\n Whether partial puzzle is complete (completely filled) or not.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import PuzzleFilling\n sage: P = PuzzleFilling(\'0101\',\'0101\')\n sage: P.is_completed()\n False\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: puzzle = ps(\'0101\',\'1001\')[0]\n sage: puzzle.is_completed()\n True\n ' (i, _) = self.kink_coordinates() return (i == (self._n + 1)) def south_labels(self): '\n Return south labels for completed puzzle.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: ps(\'0101\',\'1001\')[0].south_labels()\n (\'1\', \'0\', \'1\', \'0\')\n ' return tuple([self[(i, i)]['south'] for i in range(1, (self._n + 1))]) def add_piece(self, piece): "\n Add ``piece`` to partial puzzle.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, PuzzleFilling\n sage: piece = DeltaPiece('0','1','0')\n sage: P = PuzzleFilling('0101','0101'); P\n {}\n sage: P.add_piece(piece); P\n {(1, 4): 1/0\\0}\n " (i, j) = self.kink_coordinates() self._squares[(i, j)] = piece if isinstance(piece, DeltaPiece): i += 1 j = self._n else: j -= 1 self._kink_coordinates = (i, j) def add_pieces(self, pieces): "\n Add ``piece`` to partial puzzle.\n\n INPUT:\n\n - ``pieces`` -- tuple of pieces\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, PuzzleFilling\n sage: P = PuzzleFilling('0101','0101'); P\n {}\n sage: piece = DeltaPiece('0','1','0')\n sage: pieces = [piece,piece]\n sage: P.add_pieces(pieces)\n sage: P\n {(1, 4): 1/0\\0, (2, 4): 1/0\\0}\n " (i, j) = self.kink_coordinates() for piece in pieces: self._squares[(i, j)] = piece if isinstance(piece, DeltaPiece): i += 1 j = self._n else: j -= 1 self._kink_coordinates = (i, j) def copy(self): "\n Return copy of ``self``.\n\n EXAMPLES::\n\n\n sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece, PuzzleFilling\n sage: piece = DeltaPiece('0','1','0')\n sage: P = PuzzleFilling('0101','0101'); P\n {}\n sage: PP = P.copy()\n sage: P.add_piece(piece); P\n {(1, 4): 1/0\\0}\n sage: PP\n {}\n " PP = PuzzleFilling(self._nw_labels, self._ne_labels) PP._squares = self._squares.copy() PP._kink_coordinates = self._kink_coordinates PP._n = self._n return PP def contribution(self): '\n Return equivariant contributions from ``self`` in polynomial ring.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("HT")\n sage: puzzles = ps(\'0101\',\'1001\')\n sage: sorted([p.contribution() for p in puzzles], key=str)\n [1, y1 - y3]\n ' R = PolynomialRing(Integers(), 'y', (self._n + 1)) y = R.gens() z = R.one() for i in range(1, (self._n + 1)): for j in range((i + 1), (self._n + 1)): if self[(i, j)].north_piece()['south'].startswith('T'): z *= (y[i] - y[j]) if self[(i, j)].north_piece()['south'].startswith('K'): z *= (- 1) return z def __repr__(self): "\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_grassmannian_pieces, PuzzleFilling\n sage: P = PuzzleFilling('0101','0101'); P\n {}\n sage: P.__repr__()\n '{}'\n " from pprint import pformat return pformat(self._squares) def __iter__(self): '\n Iterator.\n\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: puzzle = ps(\'0101\',\'1001\')[0]\n sage: puzzle\n {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\10 1\\/1,\n (1, 4): 1/\\1 10\\/0,\n (2, 2): 0/0\\0,\n (2, 3): 1/\\0 0\\/1,\n (2, 4): 0/\\0 0\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}\n sage: [p for p in puzzle]\n [1/\\1 10\\/0,\n 0/\\10 1\\/1,\n 0/\\0 0\\/0,\n 1/\\1 10\\/0,\n 1/\\0 0\\/1,\n 0/\\0 1\\/10,\n 0/1\\10,\n 0/0\\0,\n 1/1\\1,\n 10/0\\1]\n ' for d in range(self._n): for k in range((d + 1)): (yield self[((k + 1), ((self._n - d) + k))]) def plot(self, labels=True, style='fill'): '\n Plot completed puzzle.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: puzzle = ps(\'0101\',\'1001\')[0]\n sage: puzzle.plot() #not tested\n sage: puzzle.plot(style=\'fill\') #not tested\n sage: puzzle.plot(style=\'edges\') #not tested\n ' P = Graphics() coords = [(k, (- d)) for d in range(self._n) for k in range((- d), (d + 1), 2)] for ((k, d), piece) in zip(coords, self): if isinstance(piece, RhombusPiece): for (i, triangle) in enumerate(piece): P += triangle._plot_piece([(k, (d - (2 * i))), ((k - 1), (d - 1)), ((k + 1), (d - 1))], style=style) if labels: P += piece._plot_label(piece['north_west'], ((k - 0.5), (d - 0.5)), rotation=60) P += piece._plot_label(piece['north_east'], ((k + 0.5), (d - 0.5)), rotation=(- 60)) P += piece._plot_label(piece.north_piece()['south'], (k, (d - 1))) else: P += piece._plot_piece([(k, d), ((k - 1), (d - 1)), ((k + 1), (d - 1))], style=style) if labels: P += piece._plot_label(piece['north_west'], ((k - 0.5), (d - 0.5)), rotation=60) P += piece._plot_label(piece['north_east'], ((k + 0.5), (d - 0.5)), rotation=(- 60)) P += piece._plot_label(piece['south'], (k, (d - 1))) P.set_aspect_ratio(1.73) P.axes(False) return P def _latex_(self): "\n Return latex version of ``self``.\n\n Note that you might need to add tikz to the preamble::\n\n sage: latex.extra_preamble(r'''\\usepackage{tikz}''')\n sage: from sage.combinat.knutson_tao_puzzles import *\n\n sage: ps = KnutsonTaoPuzzleSolver(H_grassmannian_pieces())\n sage: solns = ps('0101', '0101')\n sage: view(solns[0], viewer='pdf') # not tested\n\n sage: ps = KnutsonTaoPuzzleSolver(HT_two_step_pieces())\n sage: solns = ps(list('10212'), list('12012'))\n sage: view(solns[0], viewer='pdf') # not tested\n\n sage: ps = KnutsonTaoPuzzleSolver(K_grassmannian_pieces())\n sage: solns = ps('0101', '0101')\n sage: view(solns[0], viewer='pdf') # not tested\n " from collections import defaultdict label_colors = defaultdict((lambda : None)) label_colors.update({'0': 'red', '1': 'blue', '2': 'green'}) edge_colors = defaultdict((lambda : None)) edge_colors.update({'0': 'red', '1': 'blue', '2': 'green', 'K': 'orange'}) s = '\\begin{tikzpicture}[yscale=1.73]' coords = [(k, (- d)) for d in range(self._n) for k in range((- d), (d + 1), 2)] def tikztriangle_fill(color, k, d, i, *args): s = ('\\path[color=%s, fill=%s!10]' % (color, color)) s += ('(%s, %s) -- (%s, %s)' % (k, (d - (2 * i)), (k - 1), (d - 1))) s += ('-- (%s, %s)' % ((k + 1), (d - 1))) s += ('-- (%s, %s)' % (k, (d - (2 * i)))) s += ';\n' return s def tikztriangle_edges(color, k, d, i, label1, label2, label3): s = '' if (i == 1): return s tikzcmd = ('\\draw[color=%s, fill=none] (%s, %s) -- (%s, %s);' + '\n') if edge_colors[label1]: s += (tikzcmd % (edge_colors[label1], (k - 1), (d - 1), (k + 1), (d - 1))) if edge_colors[label2]: s += (tikzcmd % (edge_colors[label2], k, (d - (2 * i)), (k - 1), (d - 1))) if edge_colors[label3]: s += (tikzcmd % (edge_colors[label3], (k + 1), (d - 1), k, (d - (2 * i)))) return s def tikzlabels(color, k, d, i, label1, label2, label3): s = ('\\path[] (%s, %s)' % (k, (d - (2 * i)))) s += ('-- (%s, %s) ' % ((k - 1), (d - 1))) if label_colors[label2]: s += ('node[midway, color=%s] {$%s$} ' % (label_colors[label2], label2)) s += ('-- (%s, %s) ' % ((k + 1), (d - 1))) if label_colors[label1]: s += ('node[midway, color=%s] {$%s$} ' % (label_colors[label1], label1)) s += ('-- (%s, %s) ' % (k, (d - (2 * i)))) if label_colors[label3]: s += ('node[midway, color=%s] {$%s$} ' % (label_colors[label3], label3)) s += ';\n' return s for ((k, d), piece) in zip(coords, self): for tikzcmd in (tikztriangle_fill, tikztriangle_edges, tikzlabels): if isinstance(piece, RhombusPiece): for (i, triangle) in enumerate([piece.north_piece(), piece.south_piece()]): if (i == 0): s += tikzcmd(triangle.color(), k, d, i, *triangle.border()) else: s += tikzcmd(triangle.color(), k, d, i, '', '', '') else: color = piece.color() s += tikzcmd(color, k, d, 0, *piece.border()) s += '\\end{tikzpicture}' return s
class KnutsonTaoPuzzleSolver(UniqueRepresentation): '\n Return puzzle solver function used to create all puzzles with given boundary conditions.\n\n This class implements a generic algorithm to solve Knutson-Tao puzzles.\n An instance of this class will be callable: the arguments are the\n labels of north-east and north-west sides of the puzzle boundary; the\n output is the list of the fillings of the puzzle with the specified\n pieces.\n\n INPUT:\n\n - ``puzzle_pieces`` -- takes either a collection of puzzle pieces or\n a string indicating a pre-programmed collection of puzzle pieces:\n\n - ``H`` -- cohomology of the Grassmannian\n - ``HT`` -- equivariant cohomology of the Grassmannian\n - ``K`` -- K-theory\n - ``H2step`` -- cohomology of the *2-step* Grassmannian\n - ``HT2step`` -- equivariant cohomology of the *2-step* Grassmannian\n - ``BK`` -- Belkale-Kumar puzzle pieces\n\n - ``max_letter`` -- (default: None) None or a positive integer. This is\n only required only for Belkale-Kumar puzzles.\n\n EXAMPLES:\n\n Each puzzle piece is an edge-labelled triangle oriented in such a way\n that it has a south edge (called a *delta* piece) or a north edge\n (called a *nabla* piece). For example, the puzzle pieces corresponding\n to the cohomology of the Grassmannian are the following::\n\n sage: from sage.combinat.knutson_tao_puzzles import H_grassmannian_pieces\n sage: H_grassmannian_pieces()\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n\n In the string representation, the nabla pieces are depicted as\n ``c\\a/b``, where `a` is the label of the north edge, `b` is the label\n of the south-east edge, `c` is the label of the south-west edge.\n A similar string representation exists for the delta pieces.\n\n To create a puzzle solver, one specifies a collection of puzzle pieces::\n\n sage: KnutsonTaoPuzzleSolver(H_grassmannian_pieces())\n Knutson-Tao puzzle solver with pieces:\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n\n The following shorthand to create the above puzzle solver is also supported::\n\n sage: KnutsonTaoPuzzleSolver(\'H\')\n Knutson-Tao puzzle solver with pieces:\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n\n The solver will compute all fillings of the puzzle with the given\n puzzle pieces. The user specifies the labels of north-east and\n north-west sides of the puzzle boundary and the output is a list of the\n fillings of the puzzle with the specified pieces. For example, there is\n one solution to the puzzle whose north-west and north-east edges are\n both labeled \'0\'::\n\n sage: ps = KnutsonTaoPuzzleSolver(\'H\')\n sage: ps(\'0\', \'0\')\n [{(1, 1): 0/0\\0}]\n\n There are two solutions to the puzzle whose north-west and north-east\n edges are both labeled \'0101\'::\n\n sage: ps = KnutsonTaoPuzzleSolver(\'H\')\n sage: solns = ps(\'0101\', \'0101\')\n sage: len(solns)\n 2\n sage: solns.sort(key=str)\n sage: solns\n [{(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 0/\\0 0\\/0,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\10 1\\/1,\n (2, 4): 1/\\1 10\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\0 1\\/10,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): 10/\\1 0\\/0,\n (2, 4): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (4, 4): 1/1\\1}]\n\n The pieces in a puzzle filling are indexed by pairs of non-negative\n integers `(i, j)` with `1 \\leq i \\leq j \\leq n`, where `n` is the\n length of the word labelling the triangle edge. The pieces indexed by\n `(i, i)` are the triangles along the south edge of the puzzle. ::\n\n sage: f = solns[0]\n sage: [f[i, i] for i in range(1,5)]\n [0/0\\0, 1/1\\1, 1/1\\1, 10/0\\1]\n\n The pieces indexed by `(i, j)` for `j > i` are a pair consisting of\n a delta piece and nabla piece glued together along the south edge and\n north edge, respectively (these pairs are called *rhombi*). ::\n\n sage: f = solns[0]\n sage: f[1, 2]\n 1/\\0 0\\/1\n\n There are various methods and options to display puzzle solutions.\n A single puzzle can be displayed using the plot method of the puzzle::\n\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: puzzle = ps(\'0101\',\'1001\')[0]\n sage: puzzle.plot() #not tested\n sage: puzzle.plot(style=\'fill\') #not tested\n sage: puzzle.plot(style=\'edges\') #not tested\n\n To plot several puzzle solutions, use the plot method of the puzzle\n solver::\n\n sage: ps = KnutsonTaoPuzzleSolver(\'K\')\n sage: solns = ps(\'0101\', \'0101\')\n sage: ps.plot(solns) # not tested\n\n The code can also generate a PDF of a puzzle (using LaTeX and *tikz*)::\n\n sage: latex.extra_preamble(r\'\'\'\\usepackage{tikz}\'\'\')\n sage: ps = KnutsonTaoPuzzleSolver(\'H\')\n sage: solns = ps(\'0101\', \'0101\')\n sage: view(solns[0], viewer=\'pdf\') # not tested\n\n\n Below are examples of using each of the currently supported puzzles.\n\n Cohomology of the Grassmannian::\n\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: solns = ps(\'0101\', \'0101\')\n sage: sorted(solns, key=str)\n [{(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 0/\\0 0\\/0,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\10 1\\/1,\n (2, 4): 1/\\1 10\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\0 1\\/10,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): 10/\\1 0\\/0,\n (2, 4): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (4, 4): 1/1\\1}]\n\n Equivariant puzzles::\n\n sage: ps = KnutsonTaoPuzzleSolver("HT")\n sage: solns = ps(\'0101\', \'0101\')\n sage: sorted(solns, key=str)\n [{(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 0/\\0 0\\/0,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\1 1\\/0,\n (2, 4): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (4, 4): 1/1\\1}, {(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 0/\\0 0\\/0,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\10 1\\/1,\n (2, 4): 1/\\1 10\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\0 1\\/10,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): 10/\\1 0\\/0,\n (2, 4): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (4, 4): 1/1\\1}]\n\n K-Theory puzzles::\n\n sage: ps = KnutsonTaoPuzzleSolver("K")\n sage: solns = ps(\'0101\', \'0101\')\n sage: sorted(solns, key=str)\n [{(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 0/\\0 0\\/0,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\10 1\\/1,\n (2, 4): 1/\\1 10\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\0 1\\/10,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): 10/\\1 0\\/0,\n (2, 4): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (4, 4): 1/1\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\0 1\\/K,\n (1, 4): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): K/\\K 0\\/1,\n (2, 4): 1/\\1 K\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}]\n\n Two-step puzzles::\n\n sage: ps = KnutsonTaoPuzzleSolver("H2step")\n sage: solns = ps(\'01201\', \'01021\')\n sage: sorted(solns, key=str)\n [{(1, 1): 0/0\\0,\n (1, 2): 1/\\0 0\\/1,\n (1, 3): 2/\\0 0\\/2,\n (1, 4): 0/\\0 0\\/0,\n (1, 5): 1/\\0 0\\/1,\n (2, 2): 1/2\\21,\n (2, 3): 2/\\2 21\\/1,\n (2, 4): 0/\\10 2\\/21,\n (2, 5): 1/\\1 10\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 21/\\2 1\\/1,\n (3, 5): 0/\\0 2\\/20,\n (4, 4): 1/1\\1,\n (4, 5): 20/\\2 1\\/10,\n (5, 5): 10/0\\1}, {(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 2/\\1 1\\/2,\n (1, 4): 0/\\0 1\\/10,\n (1, 5): 1/\\0 0\\/1,\n (2, 2): 0/2\\20,\n (2, 3): 2/\\2 20\\/0,\n (2, 4): 10/\\1 2\\/20,\n (2, 5): 1/\\1 1\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 20/\\2 0\\/0,\n (3, 5): 1/\\0 2\\/2(10),\n (4, 4): 0/0\\0,\n (4, 5): 2(10)/\\2 0\\/1,\n (5, 5): 1/1\\1}, {(1, 1): 0/2\\20,\n (1, 2): 1/\\21 20\\/0,\n (1, 3): 2/\\2 21\\/1,\n (1, 4): 0/\\0 2\\/20,\n (1, 5): 1/\\0 0\\/1,\n (2, 2): 0/0\\0,\n (2, 3): 1/\\0 0\\/1,\n (2, 4): 20/\\2 0\\/0,\n (2, 5): 1/\\1 2\\/21,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (3, 5): 21/\\0 0\\/21,\n (4, 4): 10/0\\1,\n (4, 5): 21/\\2 1\\/1,\n (5, 5): 1/1\\1}]\n\n Two-step equivariant puzzles::\n\n sage: ps = KnutsonTaoPuzzleSolver("HT2step")\n sage: solns = ps(\'10212\', \'12012\')\n sage: sorted(solns, key=str)\n [{(1, 1): 1/1\\1,\n (1, 2): 0/\\(21)0 1\\/2,\n (1, 3): 2/\\1 (21)0\\/0,\n (1, 4): 1/\\1 1\\/1,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 2/2\\2,\n (2, 3): 0/\\2 2\\/0,\n (2, 4): 1/\\2 2\\/1,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 1/1\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\(21)0 1\\/2,\n (1, 3): 2/\\1 (21)0\\/0,\n (1, 4): 1/\\1 1\\/1,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 2/2\\2,\n (2, 3): 0/\\2 2\\/0,\n (2, 4): 1/\\21 2\\/2,\n (2, 5): 2/\\2 21\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 2/\\0 0\\/2,\n (3, 5): 1/\\0 0\\/1,\n (4, 4): 2/2\\2,\n (4, 5): 1/\\1 2\\/21,\n (5, 5): 21/1\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\(21)0 1\\/2,\n (1, 3): 2/\\1 (21)0\\/0,\n (1, 4): 1/\\1 1\\/1,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 2/2\\2,\n (2, 3): 0/\\20 2\\/2,\n (2, 4): 1/\\21 20\\/0,\n (2, 5): 2/\\2 21\\/1,\n (3, 3): 2/2\\2,\n (3, 4): 0/\\0 2\\/20,\n (3, 5): 1/\\0 0\\/1,\n (4, 4): 20/0\\2,\n (4, 5): 1/\\1 2\\/21,\n (5, 5): 21/1\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\1 1\\/0,\n (1, 3): 2/\\1 1\\/2,\n (1, 4): 1/\\1 1\\/1,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 0/2\\20,\n (2, 3): 2/\\2 20\\/0,\n (2, 4): 1/\\2 2\\/1,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 1/1\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\1 1\\/0,\n (1, 3): 2/\\1 1\\/2,\n (1, 4): 1/\\1 1\\/1,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 0/2\\20,\n (2, 3): 2/\\2 20\\/0,\n (2, 4): 1/\\21 2\\/2,\n (2, 5): 2/\\2 21\\/1,\n (3, 3): 0/0\\0,\n (3, 4): 2/\\0 0\\/2,\n (3, 5): 1/\\0 0\\/1,\n (4, 4): 2/2\\2,\n (4, 5): 1/\\1 2\\/21,\n (5, 5): 21/1\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\10 1\\/1,\n (1, 3): 2/\\10 10\\/2,\n (1, 4): 1/\\1 10\\/0,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 1/2\\21,\n (2, 3): 2/\\2 21\\/1,\n (2, 4): 0/\\2 2\\/0,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 10/0\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}, {(1, 1): 1/1\\1,\n (1, 2): 0/\\10 1\\/1,\n (1, 3): 2/\\10 10\\/2,\n (1, 4): 1/\\1 10\\/0,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 1/2\\21,\n (2, 3): 2/\\2 21\\/1,\n (2, 4): 0/\\20 2\\/2,\n (2, 5): 2/\\2 20\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 2/\\1 1\\/2,\n (3, 5): 0/\\0 1\\/10,\n (4, 4): 2/2\\2,\n (4, 5): 10/\\1 2\\/20,\n (5, 5): 20/0\\2}, {(1, 1): 1/2\\21,\n (1, 2): 0/\\20 21\\/1,\n (1, 3): 2/\\2 20\\/0,\n (1, 4): 1/\\1 2\\/21,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\1 1\\/0,\n (2, 4): 21/\\2 1\\/1,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 1/1\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}, {(1, 1): 1/2\\21,\n (1, 2): 0/\\20 21\\/1,\n (1, 3): 2/\\2 20\\/0,\n (1, 4): 1/\\1 2\\/21,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 1/1\\1,\n (2, 3): 0/\\10 1\\/1,\n (2, 4): 21/\\2 10\\/0,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 10/0\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}, {(1, 1): 1/2\\21,\n (1, 2): 0/\\21 21\\/0,\n (1, 3): 2/\\2 21\\/1,\n (1, 4): 1/\\1 2\\/21,\n (1, 5): 2/\\1 1\\/2,\n (2, 2): 0/1\\10,\n (2, 3): 1/\\1 10\\/0,\n (2, 4): 21/\\2 1\\/1,\n (2, 5): 2/\\2 2\\/2,\n (3, 3): 0/0\\0,\n (3, 4): 1/\\0 0\\/1,\n (3, 5): 2/\\0 0\\/2,\n (4, 4): 1/1\\1,\n (4, 5): 2/\\1 1\\/2,\n (5, 5): 2/2\\2}]\n\n\n Belkale-Kumar puzzles (the following example is Figure 2 of [KnutsonPurbhoo10]_)::\n\n sage: ps = KnutsonTaoPuzzleSolver(\'BK\', 3)\n sage: solns = ps(\'12132\', \'23112\')\n sage: len(solns)\n 1\n sage: solns[0].south_labels()\n (\'3\', \'2\', \'1\', \'2\', \'1\')\n sage: solns\n [{(1, 1): 1/3\\3(1),\n (1, 2): 2/\\3(2) 3(1)\\/1,\n (1, 3): 1/\\3(1) 3(2)\\/2,\n (1, 4): 3/\\3 3(1)\\/1,\n (1, 5): 2/\\2 3\\/3(2),\n (2, 2): 1/2\\2(1),\n (2, 3): 2/\\2 2(1)\\/1,\n (2, 4): 1/\\2(1) 2\\/2,\n (2, 5): 3(2)/\\3 2(1)\\/1,\n (3, 3): 1/1\\1,\n (3, 4): 2/\\1 1\\/2,\n (3, 5): 1/\\1 1\\/1,\n (4, 4): 2/2\\2,\n (4, 5): 1/\\1 2\\/2(1),\n (5, 5): 2(1)/1\\2}]\n ' def __init__(self, puzzle_pieces): '\n Knutson-Tao puzzle solver.\n\n TESTS:\n\n Check that UniqueRepresentation works::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver, H_grassmannian_pieces\n sage: ps = KnutsonTaoPuzzleSolver(H_grassmannian_pieces())\n sage: qs = KnutsonTaoPuzzleSolver("H")\n sage: ps\n Knutson-Tao puzzle solver with pieces:\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n sage: qs\n Knutson-Tao puzzle solver with pieces:\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n sage: ps == qs\n True\n ' self._puzzle_pieces = puzzle_pieces self._rhombus_pieces = tuple(puzzle_pieces.rhombus_pieces()) self._bottom_deltas = tuple(puzzle_pieces.boundary_deltas()) @staticmethod def __classcall_private__(cls, puzzle_pieces, max_letter=None): '\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import *\n sage: KnutsonTaoPuzzleSolver(H_grassmannian_pieces()) == KnutsonTaoPuzzleSolver("H") # indirect doctest\n True\n sage: KnutsonTaoPuzzleSolver(HT_grassmannian_pieces()) == KnutsonTaoPuzzleSolver("HT")\n True\n sage: KnutsonTaoPuzzleSolver(K_grassmannian_pieces()) == KnutsonTaoPuzzleSolver("K")\n True\n sage: KnutsonTaoPuzzleSolver(H_two_step_pieces()) == KnutsonTaoPuzzleSolver("H2step")\n True\n sage: KnutsonTaoPuzzleSolver(HT_two_step_pieces()) == KnutsonTaoPuzzleSolver("HT2step")\n True\n sage: KnutsonTaoPuzzleSolver(BK_pieces(3)) == KnutsonTaoPuzzleSolver("BK",3)\n True\n ' if isinstance(puzzle_pieces, str): if (puzzle_pieces == 'H'): puzzle_pieces = H_grassmannian_pieces() elif (puzzle_pieces == 'HT'): puzzle_pieces = HT_grassmannian_pieces() elif (puzzle_pieces == 'K'): puzzle_pieces = K_grassmannian_pieces() elif (puzzle_pieces == 'H2step'): puzzle_pieces = H_two_step_pieces() elif (puzzle_pieces == 'HT2step'): puzzle_pieces = HT_two_step_pieces() elif (puzzle_pieces == 'BK'): if (max_letter is not None): puzzle_pieces = BK_pieces(max_letter) else: raise ValueError('max_letter needs to be specified') return super().__classcall__(cls, puzzle_pieces) def __call__(self, lamda, mu, algorithm='strips'): '\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver("H")\n sage: ps(\'0101\',\'1001\')\n [{(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\10 1\\/1,\n (1, 4): 1/\\1 10\\/0,\n (2, 2): 0/0\\0,\n (2, 3): 1/\\0 0\\/1,\n (2, 4): 0/\\0 0\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}]\n sage: ps(\'0101\',\'1001\',algorithm=\'pieces\')\n [{(1, 1): 0/1\\10,\n (1, 2): 1/\\1 10\\/0,\n (1, 3): 0/\\10 1\\/1,\n (1, 4): 1/\\1 10\\/0,\n (2, 2): 0/0\\0,\n (2, 3): 1/\\0 0\\/1,\n (2, 4): 0/\\0 0\\/0,\n (3, 3): 1/1\\1,\n (3, 4): 0/\\0 1\\/10,\n (4, 4): 10/0\\1}]\n ' (lamda, mu) = (tuple(lamda), tuple(mu)) if (algorithm == 'pieces'): return list(self._fill_puzzle_by_pieces(lamda, mu)) elif (algorithm == 'strips'): return list(self._fill_puzzle_by_strips(lamda, mu)) solutions = __call__ def __repr__(self) -> str: "\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: KnutsonTaoPuzzleSolver('H')\n Knutson-Tao puzzle solver with pieces:\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n " return ('Knutson-Tao puzzle solver with pieces:\n%s' % self._puzzle_pieces) def puzzle_pieces(self): "\n The puzzle pieces used for filling in the puzzles.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: ps.puzzle_pieces()\n Nablas : [0\\0/0, 0\\10/1, 10\\1/0, 1\\0/10, 1\\1/1]\n Deltas : [0/0\\0, 0/1\\10, 1/10\\0, 1/1\\1, 10/0\\1]\n " return self._puzzle_pieces def _fill_piece(self, nw_label, ne_label, pieces) -> list[PuzzlePiece]: "\n Fillings of a piece.\n\n INPUT:\n\n - ``nw_label``, ``nw_label`` -- label\n - ``pieces`` -- puzzle pieces used for the filling\n\n OUTPUT:\n\n - list of the fillings\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: ps._fill_piece('0', '0', ps._bottom_deltas)\n [0/0\\0]\n " output = [] for piece in pieces: if ((piece['north_west'] == nw_label) and (piece['north_east'] == ne_label)): output.append(piece) return output @cached_method def _fill_strip(self, nw_labels, ne_label, pieces, final_pieces=None): "\n Fillings of a strip of height 1.\n\n INPUT:\n\n - ``nw_labels`` -- tuple of labels\n - ``nw_label`` -- label\n - ``pieces`` -- puzzle pieces used for the filling\n - ``final_pieces`` -- pieces used for the last piece to be filled in\n\n OUTPUT:\n\n - list of lists of the fillings\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: ps._fill_strip(('0',), '0', ps._rhombus_pieces, ps._bottom_deltas)\n [[0/0\\0]]\n sage: ps._fill_strip(('0','0'), '0', ps._rhombus_pieces, ps._bottom_deltas)\n [[0/\\0 0\\/0, 0/0\\0]]\n sage: sorted(ps._fill_strip(('0',), '0', ps._rhombus_pieces), key=str)\n [[0/\\0 0\\/0], [0/\\0 1\\/10]]\n sage: sorted(ps._fill_strip(('0','1'), '0', ps._rhombus_pieces), key =str)\n [[1/\\0 0\\/1, 0/\\0 0\\/0], [1/\\0 0\\/1, 0/\\0 1\\/10]]\n\n TESTS::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: ps._fill_strip(('0',), 'goo', ps._rhombus_pieces)\n []\n " if (final_pieces is None): final_pieces = pieces output = [] if (len(nw_labels) == 1): X = self._fill_piece(nw_labels[0], ne_label, final_pieces) if X: output = [[x] for x in X] else: partial_fillings = self._fill_strip(nw_labels[1:], ne_label, pieces) for partial_filling in partial_fillings: ne_label = partial_filling[(- 1)]['south_west'] for piece in self._fill_piece(nw_labels[0], ne_label, final_pieces): output.append((partial_filling + [piece])) return output def _fill_puzzle_by_pieces(self, lamda, mu): "\n Fill puzzle pieces for given outer labels ``lambda`` and ``mu``.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: list(ps._fill_puzzle_by_pieces('0', '0'))\n [{(1, 1): 0/0\\0}]\n " queue = [PuzzleFilling(lamda, mu)] while queue: PP = queue.pop() ne_label = PP.north_east_label_of_kink() nw_label = PP.north_west_label_of_kink() if PP.is_in_south_edge(): pieces = self._bottom_deltas else: pieces = self._rhombus_pieces for piece in self._fill_piece(nw_label, ne_label, pieces): PPcopy = PP.copy() PPcopy.add_piece(piece) if PPcopy.is_completed(): (yield PPcopy) else: queue.append(PPcopy) def _fill_puzzle_by_strips(self, lamda, mu): "\n Fill puzzle pieces by strips for given outer labels ``lambda`` and ``mu``.\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: list(ps._fill_puzzle_by_strips('0', '0'))\n [{(1, 1): 0/0\\0}]\n sage: list(ps._fill_puzzle_by_strips('01', '01'))\n [{(1, 1): 0/0\\0, (1, 2): 1/\\0 0\\/1, (2, 2): 1/1\\1}]\n " queue = [PuzzleFilling(lamda, mu)] while queue: PP = queue.pop() (i, _) = PP.kink_coordinates() if (i == 1): nw_labels = PP._nw_labels else: nw_labels = tuple((PP._squares[((i - 1), k)]['south_east'] for k in range(i, (len(lamda) + 1)))) ne_label = PP._ne_labels[(i - 1)] deltas = self._bottom_deltas rhombi = self._rhombus_pieces for row in self._fill_strip(nw_labels, ne_label, rhombi, deltas): PPcopy = PP.copy() PPcopy.add_pieces(row) if PPcopy.is_completed(): (yield PPcopy) else: queue.append(PPcopy) def plot(self, puzzles): "\n Return plot of puzzles.\n\n INPUT:\n\n - ``puzzles`` -- list of puzzles\n\n EXAMPLES::\n\n sage: from sage.combinat.knutson_tao_puzzles import KnutsonTaoPuzzleSolver\n sage: ps = KnutsonTaoPuzzleSolver('K')\n sage: solns = ps('0101', '0101')\n sage: ps.plot(solns) # not tested\n " g = [p.plot() for p in puzzles] m = len([gg.axes(False) for gg in g]) return graphics_array(g, ((m + 3) / 4), 4) def structure_constants(self, lamda, mu, nu=None): "\n Compute cohomology structure coefficients from puzzles.\n\n INPUT:\n\n - ``pieces`` -- puzzle pieces to be used\n - ``lambda``, ``mu`` -- edge labels of puzzle for northwest and north east side\n - ``nu`` -- (default: ``None``) If ``nu`` is not specified a dictionary is returned with\n the structure coefficients corresponding to all south labels; if ``nu`` is given, only\n the coefficients with the specified label is returned.\n\n OUTPUT: dictionary\n\n EXAMPLES:\n\n Note: In order to standardize the output of the following examples,\n we output a sorted list of items from the dictionary instead of the\n dictionary itself.\n\n Grassmannian cohomology::\n\n sage: ps = KnutsonTaoPuzzleSolver('H')\n sage: cp = ps.structure_constants('0101', '0101')\n sage: sorted(cp.items(), key=str)\n [(('0', '1', '1', '0'), 1), (('1', '0', '0', '1'), 1)]\n sage: ps.structure_constants('001001', '001010', '010100')\n 1\n\n Equivariant cohomology::\n\n sage: ps = KnutsonTaoPuzzleSolver('HT')\n sage: cp = ps.structure_constants('0101', '0101')\n sage: sorted(cp.items(), key=str)\n [(('0', '1', '0', '1'), y2 - y3),\n (('0', '1', '1', '0'), 1),\n (('1', '0', '0', '1'), 1)]\n\n K-theory::\n\n sage: ps = KnutsonTaoPuzzleSolver('K')\n sage: cp = ps.structure_constants('0101', '0101')\n sage: sorted(cp.items(), key=str)\n [(('0', '1', '1', '0'), 1), (('1', '0', '0', '1'), 1), (('1', '0', '1', '0'), -1)]\n\n Two-step::\n\n sage: ps = KnutsonTaoPuzzleSolver('H2step')\n sage: cp = ps.structure_constants('01122', '01122')\n sage: sorted(cp.items(), key=str)\n [(('0', '1', '1', '2', '2'), 1)]\n sage: cp = ps.structure_constants('01201', '01021')\n sage: sorted(cp.items(), key=str)\n [(('0', '2', '1', '1', '0'), 1),\n (('1', '2', '0', '0', '1'), 1),\n (('2', '0', '1', '0', '1'), 1)]\n\n Two-step equivariant::\n\n sage: ps = KnutsonTaoPuzzleSolver('HT2step')\n sage: cp = ps.structure_constants('10212', '12012')\n sage: sorted(cp.items(), key=str)\n [(('1', '2', '0', '1', '2'), y1*y2 - y2*y3 - y1*y4 + y3*y4),\n (('1', '2', '0', '2', '1'), y1 - y3),\n (('1', '2', '1', '0', '2'), y2 - y4),\n (('1', '2', '1', '2', '0'), 1),\n (('1', '2', '2', '0', '1'), 1),\n (('2', '1', '0', '1', '2'), y1 - y3),\n (('2', '1', '1', '0', '2'), 1)]\n " from collections import defaultdict R = PolynomialRing(Integers(), 'y', (len(lamda) + 1)) z = defaultdict(R.zero) for p in self(lamda, mu): z[p.south_labels()] += p.contribution() if (nu is None): return dict(z) else: return z[tuple(nu)]
class LittlewoodRichardsonTableau(SemistandardTableau): '\n A semistandard tableau is Littlewood-Richardson with respect to\n the sequence of partitions `(\\mu^{(1)}, \\ldots, \\mu^{(k)})` if,\n when restricted to each alphabet `\\{|\\mu^{(1)}|+\\cdots+|\\mu^{(i-1)}|+1,\n \\ldots, |\\mu^{(1)}|+\\cdots+|\\mu^{(i)}|-1\\}`, is Yamanouchi.\n\n INPUT:\n\n - ``t`` -- Littlewood-Richardson tableau; the input is supposed to be\n a list of lists specifying the rows of the tableau\n\n EXAMPLES::\n\n sage: from sage.combinat.lr_tableau import LittlewoodRichardsonTableau\n sage: LittlewoodRichardsonTableau([[1,1,3],[2,3],[4]], [[2,1],[2,1]])\n [[1, 1, 3], [2, 3], [4]]\n ' @staticmethod def __classcall_private__(cls, t, weight): "\n Implements the shortcut ``LittlewoodRichardsonTableau(t, weight)`` to\n ``LittlewoodRichardsonTableaux(shape , weight)(t)``\n where ``shape`` is the shape of the tableau.\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n sage: t = LR([[1, 1, 3], [2, 3], [4]])\n sage: t.check()\n sage: type(t)\n <class 'sage.combinat.lr_tableau.LittlewoodRichardsonTableaux_with_category.element_class'>\n sage: TestSuite(t).run()\n sage: from sage.combinat.lr_tableau import LittlewoodRichardsonTableau\n sage: LittlewoodRichardsonTableau([[1,1,3],[2,3],[4]], [[2,1],[2,1]])\n [[1, 1, 3], [2, 3], [4]]\n " if isinstance(t, cls): return t tab = SemistandardTableau(list(t)) shape = tab.shape() return LittlewoodRichardsonTableaux(shape, weight)(t) def __init__(self, parent, t): "\n Initialize ``self``.\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n sage: t = LR([[1, 1, 3], [2, 3], [4]])\n sage: from sage.combinat.lr_tableau import LittlewoodRichardsonTableau\n sage: s = LittlewoodRichardsonTableau([[1,1,3],[2,3],[4]], [[2,1],[2,1]])\n sage: s == t\n True\n sage: type(t)\n <class 'sage.combinat.lr_tableau.LittlewoodRichardsonTableaux_with_category.element_class'>\n sage: t.parent()\n Littlewood-Richardson Tableaux of shape [3, 2, 1] and weight ([2, 1], [2, 1])\n sage: TestSuite(t).run()\n " self._shape = parent._shape self._weight = parent._weight super().__init__(parent, list(t)) def check(self): '\n Check that ``self`` is a valid Littlewood-Richardson tableau.\n\n EXAMPLES::\n\n sage: from sage.combinat.lr_tableau import LittlewoodRichardsonTableau\n sage: t = LittlewoodRichardsonTableau([[1,1,3],[2,3],[4]], [[2,1],[2,1]])\n sage: t.check()\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n sage: LR([[1, 1, 2], [3, 3], [4]])\n Traceback (most recent call last):\n ...\n ValueError: [[1, 1, 2], [3, 3], [4]] is not an element of\n Littlewood-Richardson Tableaux of shape [3, 2, 1] and weight ([2, 1], [2, 1])\n sage: LR([[1, 1, 2, 3], [3], [4]])\n Traceback (most recent call last):\n ...\n ValueError: [[1, 1, 2, 3], [3], [4]] is not an element of\n Littlewood-Richardson Tableaux of shape [3, 2, 1] and weight ([2, 1], [2, 1])\n sage: LR([[1, 1, 3], [3, 3], [4]])\n Traceback (most recent call last):\n ...\n ValueError: weight of the parent does not agree with the weight of the tableau\n ' super().check() if (not ([i for a in self.parent()._weight for i in a] == self.weight())): raise ValueError('weight of the parent does not agree with the weight of the tableau') if (not (self.shape() == self.parent()._shape)): raise ValueError('shape of the parent does not agree with the shape of the tableau')
class LittlewoodRichardsonTableaux(SemistandardTableaux): '\n Littlewood-Richardson tableaux.\n\n A semistandard tableau `t` is *Littlewood-Richardson* with respect to\n the sequence of partitions `(\\mu^{(1)}, \\ldots, \\mu^{(k)})` (called\n the weight) if `t` is Yamanouchi when restricted to each alphabet\n `\\{|\\mu^{(1)}| + \\cdots + |\\mu^{(i-1)}| + 1, \\ldots,\n |\\mu^{(1)}| + \\cdots + |\\mu^{(i)}| - 1\\}`.\n\n INPUT:\n\n - ``shape`` -- the shape of the Littlewood-Richardson tableaux\n - ``weight`` -- the weight is a sequence of partitions\n\n EXAMPLES::\n\n sage: LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n Littlewood-Richardson Tableaux of shape [3, 2, 1] and weight ([2, 1], [2, 1])\n ' @staticmethod def __classcall_private__(cls, shape, weight): '\n Straighten arguments before unique representation.\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n sage: TestSuite(LR).run()\n sage: LittlewoodRichardsonTableaux([3,2,1],[[2,1]])\n Traceback (most recent call last):\n ...\n ValueError: the sizes of shapes and sequence of weights do not match\n ' shape = Partition(shape) weight = tuple((Partition(a) for a in weight)) if (shape.size() != sum((a.size() for a in weight))): raise ValueError('the sizes of shapes and sequence of weights do not match') return super().__classcall__(cls, shape, weight) def __init__(self, shape, weight): '\n Initializes the parent class of Littlewood-Richardson tableaux.\n\n INPUT:\n\n - ``shape`` -- the shape of the Littlewood-Richardson tableaux\n - ``weight`` -- the weight is a sequence of partitions\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n sage: TestSuite(LR).run()\n ' self._shape = shape self._weight = weight self._heights = [a.length() for a in self._weight] super().__init__(category=FiniteEnumeratedSets()) def _repr_(self): '\n TESTS::\n\n sage: LittlewoodRichardsonTableaux([3,2,1],[[2,1],[2,1]])\n Littlewood-Richardson Tableaux of shape [3, 2, 1] and weight ([2, 1], [2, 1])\n ' return ('Littlewood-Richardson Tableaux of shape %s and weight %s' % (self._shape, self._weight)) def __iter__(self): '\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1], [[2,1],[2,1]])\n sage: LR.list()\n [[[1, 1, 3], [2, 3], [4]], [[1, 1, 3], [2, 4], [3]]]\n ' from sage.libs.lrcalc.lrcalc import lrskew if (not self._weight): (yield self.element_class(self, [])) return for nu in Partitions((self._shape.size() - self._weight[(- 1)].size()), outer=self._shape): for s in lrskew(self._shape, nu, weight=self._weight[(- 1)]): for t in LittlewoodRichardsonTableaux(nu, self._weight[:(- 1)]): shift = sum((a.length() for a in self._weight[:(- 1)])) (yield self.element_class(self, _tableau_join(t, s, shift=shift))) def __contains__(self, t): '\n Check if ``t`` is contained in ``self``.\n\n TESTS::\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1], [[2,1],[2,1]])\n sage: SST = SemistandardTableaux([3,2,1], [2,1,2,1])\n sage: [t for t in SST if t in LR]\n [[[1, 1, 3], [2, 3], [4]], [[1, 1, 3], [2, 4], [3]]]\n sage: [t for t in SST if t in LR] == LR.list()\n True\n\n sage: LR = LittlewoodRichardsonTableaux([3,2,1], [[2,1],[2,1]])\n sage: T = [[1,1,3], [2,3], [4]]\n sage: T in LR\n True\n ' return (SemistandardTableaux.__contains__(self, t) and is_littlewood_richardson(t, self._heights)) Element = LittlewoodRichardsonTableau
def is_littlewood_richardson(t, heights): '\n Return whether semistandard tableau ``t`` is Littleword-Richardson\n with respect to ``heights``.\n\n A tableau is Littlewood-Richardson with respect to ``heights`` given\n by `(h_1, h_2, \\ldots)` if each subtableau with respect to the\n alphabets `\\{1, 2, \\ldots, h_1\\}`, `\\{h_1+1, \\ldots, h_1+h_2\\}`,\n etc. is Yamanouchi.\n\n EXAMPLES::\n\n sage: from sage.combinat.lr_tableau import is_littlewood_richardson\n sage: t = Tableau([[1,1,2,3,4],[2,3,3],[3]])\n sage: is_littlewood_richardson(t,[2,2])\n False\n sage: t = Tableau([[1,1,3],[2,3],[4,4]])\n sage: is_littlewood_richardson(t,[2,2])\n True\n sage: t = Tableau([[7],[8]])\n sage: is_littlewood_richardson(t,[2,3,3])\n False\n sage: is_littlewood_richardson([[2],[3]],[3,3])\n False\n ' from sage.combinat.words.word import Word partial = [sum((heights[i] for i in range(j))) for j in range((len(heights) + 1))] try: w = t.to_word() except AttributeError: w = sum(reversed(t), []) for i in range(len(heights)): subword = Word([j for j in w if ((partial[i] + 1) <= j <= partial[(i + 1)])], alphabet=list(range((partial[i] + 1), (partial[(i + 1)] + 1)))) if (not subword.is_yamanouchi()): return False return True
def _tableau_join(t1, t2, shift=0): "\n Join semistandard tableau ``t1`` with semistandard tableau ``t2``\n shifted by ``shift``.\n\n Concatenate the rows of ``t1`` and ``t2``, dropping any ``None``'s\n from ``t2``. This method is intended for the case when the outer\n shape of ``t1`` is equal to the inner shape of ``t2``.\n\n EXAMPLES::\n\n sage: from sage.combinat.lr_tableau import _tableau_join\n sage: _tableau_join([[1,2]],[[None,None,2],[3]],shift=5)\n [[1, 2, 7], [8]]\n " return [([e1 for e1 in row1] + [(e2 + shift) for e2 in row2 if (e2 is not None)]) for (row1, row2) in zip_longest(t1, t2, fillvalue=[])]
def DLXCPP(rows): "\n Solves the Exact Cover problem by using the Dancing Links algorithm\n described by Knuth.\n\n Consider a matrix M with entries of 0 and 1, and compute a subset\n of the rows of this matrix which sum to the vector of all 1's.\n\n The dancing links algorithm works particularly well for sparse\n matrices, so the input is a list of lists of the form::\n\n [\n [i_11,i_12,...,i_1r]\n ...\n [i_m1,i_m2,...,i_ms]\n ]\n\n where M[j][i_jk] = 1.\n\n The first example below corresponds to the matrix::\n\n 1110\n 1010\n 0100\n 0001\n\n which is exactly covered by::\n\n 1110\n 0001\n\n and\n\n ::\n\n 1010\n 0100\n 0001\n\n If soln is a solution given by DLXCPP(rows) then\n\n [ rows[soln[0]], rows[soln[1]], ... rows[soln[len(soln)-1]] ]\n\n is an exact cover.\n\n Solutions are given as a list.\n\n EXAMPLES::\n\n sage: rows = [[0,1,2]]\n sage: rows+= [[0,2]]\n sage: rows+= [[1]]\n sage: rows+= [[3]]\n sage: [x for x in DLXCPP(rows)]\n [[3, 0], [3, 1, 2]]\n " if (not rows): return x = dlx_solver(rows) while x.search(): (yield x.get_solution())
def AllExactCovers(M): '\n Solves the exact cover problem on the matrix M (treated as a dense\n binary matrix).\n\n EXAMPLES: No exact covers::\n\n sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) # needs sage.modules\n sage: [cover for cover in AllExactCovers(M)] # needs sage.modules\n []\n\n Two exact covers::\n\n sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) # needs sage.modules\n sage: [cover for cover in AllExactCovers(M)] # needs sage.modules\n [[(1, 1, 0), (0, 0, 1)], [(1, 0, 1), (0, 1, 0)]]\n ' rows = [] for R in M.rows(): row = [] for i in range(len(R)): if R[i]: row.append(i) rows.append(row) for s in DLXCPP(rows): (yield [M.row(i) for i in s])
def OneExactCover(M): '\n Solves the exact cover problem on the matrix M (treated as a dense\n binary matrix).\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]]) # no exact covers\n sage: print(OneExactCover(M))\n None\n sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) # two exact covers\n sage: OneExactCover(M)\n [(1, 1, 0), (0, 0, 1)]\n ' for s in AllExactCovers(M): return s
class LatinSquare(): def __init__(self, *args): '\n Latin squares.\n\n This class implements a latin square of order n with rows and\n columns indexed by the set 0, 1, ..., n-1 and symbols from the same\n set. The underlying latin square is a matrix(ZZ, n, n). If L is a\n latin square, then the cell at row r, column c is empty if and only\n if L[r, c] < 0. In this way we allow partial latin squares and can\n speak of completions to latin squares, etc.\n\n There are two ways to declare a latin square:\n\n Empty latin square of order n::\n\n sage: n = 3\n sage: L = LatinSquare(n)\n sage: L\n [-1 -1 -1]\n [-1 -1 -1]\n [-1 -1 -1]\n\n Latin square from a matrix::\n\n sage: M = matrix(ZZ, [[0, 1], [2, 3]])\n sage: LatinSquare(M)\n [0 1]\n [2 3]\n ' if ((len(args) == 1) and isinstance(args[0], (Integer, int))): self.square = matrix(ZZ, args[0], args[0]) self.clear_cells() elif ((len(args) == 2) and all((isinstance(a, (Integer, int)) for a in args))): self.square = matrix(ZZ, args[0], args[1]) self.clear_cells() elif ((len(args) == 1) and isinstance(args[0], Matrix_integer_dense)): self.square = args[0] else: raise TypeError('bad input for latin square') def dumps(self): '\n Since the latin square class does not hold any other private\n variables we just call dumps on self.square:\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(2) == loads(dumps(back_circulant(2)))\n True\n ' from sage.misc.persist import dumps return dumps(self.square) def __str__(self): '\n The string representation of a latin square is the same as the\n underlying matrix.\n\n EXAMPLES::\n\n sage: print(LatinSquare(matrix(ZZ, [[0, 1], [2, 3]])).__str__())\n [0 1]\n [2 3]\n ' return str(self.square) def __repr__(self): '\n The representation of a latin square is the same as the underlying\n matrix.\n\n EXAMPLES::\n\n sage: print(LatinSquare(matrix(ZZ, [[0, 1], [2, 3]])).__repr__())\n [0 1]\n [2 3]\n ' return repr(self.square) def __getitem__(self, rc): '\n If L is a LatinSquare then this method allows us to evaluate L[r,\n c].\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(3)\n sage: B[1, 1]\n 2\n ' r = rc[0] c = rc[1] return self.square[(r, c)] def __setitem__(self, rc, val): '\n If L is a LatinSquare then this method allows us to set L[r, c].\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(3)\n sage: B[1, 1] = 10\n sage: B[1, 1]\n 10\n ' r = rc[0] c = rc[1] self.square[(r, c)] = val def set_immutable(self): '\n A latin square is immutable if the underlying matrix is immutable.\n\n EXAMPLES::\n\n sage: L = LatinSquare(matrix(ZZ, [[0, 1], [2, 3]]))\n sage: L.set_immutable()\n sage: {L : 0} # this would fail without set_immutable()\n {[0 1]\n [2 3]: 0}\n ' self.square.set_immutable() def __hash__(self): '\n The hash of a latin square is precisely the hash of the underlying\n matrix.\n\n EXAMPLES::\n\n sage: L = LatinSquare(matrix(ZZ, [[0, 1], [2, 3]]))\n sage: L.set_immutable()\n sage: L.__hash__()\n 1677951251422179082 # 64-bit\n -479138038 # 32-bit\n ' return hash(self.square) def __eq__(self, Q): '\n Two latin squares are equal if the underlying matrices are equal.\n\n EXAMPLES::\n\n sage: A = LatinSquare(matrix(ZZ, [[0, 1], [2, 3]]))\n sage: B = LatinSquare(matrix(ZZ, [[0, 4], [2, 3]]))\n sage: A == B\n False\n sage: B[0, 1] = 1\n sage: A == B\n True\n ' return (self.square == Q.square) def __copy__(self): '\n To copy a latin square we must copy the underlying matrix.\n\n EXAMPLES::\n\n sage: A = LatinSquare(matrix(ZZ, [[0, 1], [2, 3]]))\n sage: B = copy(A)\n sage: B\n [0 1]\n [2 3]\n ' C = LatinSquare(self.square.nrows(), self.square.ncols()) from copy import copy C.square = copy(self.square) return C def clear_cells(self): '\n Mark every cell in self as being empty.\n\n EXAMPLES::\n\n sage: A = LatinSquare(matrix(ZZ, [[0, 1], [2, 3]]))\n sage: A.clear_cells()\n sage: A\n [-1 -1]\n [-1 -1]\n ' for r in range(self.square.nrows()): for c in range(self.square.ncols()): self.square[(r, c)] = (- 1) def nrows(self): '\n Number of rows in the latin square.\n\n EXAMPLES::\n\n sage: LatinSquare(3).nrows()\n 3\n ' return self.square.nrows() def ncols(self): '\n Number of columns in the latin square.\n\n EXAMPLES::\n\n sage: LatinSquare(3).ncols()\n 3\n ' return self.square.ncols() def row(self, x): '\n Return row x of the latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(3).row(0)\n (0, 1, 2)\n ' return self.square.row(x) def column(self, x): '\n Return column x of the latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(3).column(0)\n (0, 1, 2)\n ' return self.square.column(x) def list(self): '\n Convert the latin square into a list, in a row-wise manner.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(3).list()\n [0, 1, 2, 1, 2, 0, 2, 0, 1]\n ' return self.square.list() def nr_filled_cells(self): '\n Return the number of filled cells (i.e. cells with a positive\n value) in the partial latin square self.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: LatinSquare(matrix([[0, -1], [-1, 0]])).nr_filled_cells()\n 2\n ' s = 0 for r in range(self.nrows()): for c in range(self.ncols()): if (self[(r, c)] >= 0): s += 1 return s def actual_row_col_sym_sizes(self): '\n Bitrades sometimes end up in partial latin squares with unused\n rows, columns, or symbols. This function works out the actual\n number of used rows, columns, and symbols.\n\n .. warning::\n\n We assume that the unused rows/columns occur in the lower\n right of self, and that the used symbols are in the range\n {0, 1, ..., m} (no holes in that list).\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(3)\n sage: B[0,2] = B[1,2] = B[2,2] = -1\n sage: B[0,0] = B[2,1] = -1\n sage: B\n [-1 1 -1]\n [ 1 2 -1]\n [ 2 -1 -1]\n sage: B.actual_row_col_sym_sizes()\n (3, 2, 2)\n ' row_max = self.nrows() col_max = self.ncols() sym_max = self.nr_distinct_symbols() while self.is_empty_row((row_max - 1)): row_max -= 1 while self.is_empty_column((col_max - 1)): col_max -= 1 return (row_max, col_max, sym_max) def is_empty_column(self, c): '\n Check if column c of the partial latin square self is empty.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = back_circulant(4)\n sage: L.is_empty_column(0)\n False\n sage: L[0,0] = L[1,0] = L[2,0] = L[3,0] = -1\n sage: L.is_empty_column(0)\n True\n ' return (list(set(self.column(c))) == [(- 1)]) def is_empty_row(self, r): '\n Check if row r of the partial latin square self is empty.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = back_circulant(4)\n sage: L.is_empty_row(0)\n False\n sage: L[0,0] = L[0,1] = L[0,2] = L[0,3] = -1\n sage: L.is_empty_row(0)\n True\n ' return (list(set(self.row(r))) == [(- 1)]) def nr_distinct_symbols(self): '\n Return the number of distinct symbols in the partial latin square\n self.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(5).nr_distinct_symbols()\n 5\n sage: L = LatinSquare(10)\n sage: L.nr_distinct_symbols()\n 0\n sage: L[0, 0] = 0\n sage: L[0, 1] = 1\n sage: L.nr_distinct_symbols()\n 2\n ' symbols = set(flatten([list(x) for x in list(self.square)])) return sum((1 for x in symbols if (x >= 0))) def apply_isotopism(self, row_perm, col_perm, sym_perm): '\n An isotopism is a permutation of the rows, columns, and symbols of\n a partial latin square self. Use isotopism() to convert a tuple\n (indexed from 0) to a Permutation object.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(5)\n sage: B\n [0 1 2 3 4]\n [1 2 3 4 0]\n [2 3 4 0 1]\n [3 4 0 1 2]\n [4 0 1 2 3]\n sage: alpha = isotopism((0,1,2,3,4))\n sage: beta = isotopism((1,0,2,3,4))\n sage: gamma = isotopism((2,1,0,3,4))\n sage: B.apply_isotopism(alpha, beta, gamma)\n [3 4 2 0 1]\n [0 2 3 1 4]\n [1 3 0 4 2]\n [4 0 1 2 3]\n [2 1 4 3 0]\n ' Q = LatinSquare(self.nrows(), self.ncols()) for r in range(self.nrows()): for c in range(self.ncols()): try: if (self[(r, c)] < 0): s2 = (- 1) else: s2 = (sym_perm[self[(r, c)]] - 1) except IndexError: s2 = self[(r, c)] Q[((row_perm[r] - 1), (col_perm[c] - 1))] = s2 return Q def filled_cells_map(self): '\n Number the filled cells of self with integers from {1, 2, 3, ...}.\n\n INPUT:\n\n - ``self`` -- partial latin square self (empty cells\n have negative values)\n\n OUTPUT:\n\n A dictionary ``cells_map`` where ``cells_map[(i,j)] = m`` means that\n ``(i,j)`` is the ``m``-th filled cell in ``P``,\n while ``cells_map[m] = (i,j)``.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: (a, b, c, G) = alternating_group_bitrade_generators(1)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: D = T1.filled_cells_map()\n sage: {i: v for i,v in D.items() if i in ZZ}\n {1: (0, 0),\n 2: (0, 2),\n 3: (0, 3),\n 4: (1, 1),\n 5: (1, 2),\n 6: (1, 3),\n 7: (2, 0),\n 8: (2, 1),\n 9: (2, 2),\n 10: (3, 0),\n 11: (3, 1),\n 12: (3, 3)}\n sage: {i: v for i,v in D.items() if i not in ZZ}\n {(0, 0): 1,\n (0, 2): 2,\n (0, 3): 3,\n (1, 1): 4,\n (1, 2): 5,\n (1, 3): 6,\n (2, 0): 7,\n (2, 1): 8,\n (2, 2): 9,\n (3, 0): 10,\n (3, 1): 11,\n (3, 3): 12}\n ' cells_map = {} k = 1 for r in range(self.nrows()): for c in range(self.ncols()): e = self[(r, c)] if (e < 0): continue cells_map[(r, c)] = k cells_map[k] = (r, c) k += 1 return cells_map def top_left_empty_cell(self): '\n Return the least [r, c] such that self[r, c] is an empty cell. If\n all cells are filled then we return None.\n\n INPUT:\n\n - ``self`` - LatinSquare\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(5)\n sage: B[3, 4] = -1\n sage: B.top_left_empty_cell()\n [3, 4]\n ' for r in range(self.nrows()): for c in range(self.ncols()): if (self[(r, c)] < 0): return [r, c] return None def is_partial_latin_square(self): '\n self is a partial latin square if it is an n by n matrix, and each\n symbol in [0, 1, ..., n-1] appears at most once in each row, and at\n most once in each column.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: LatinSquare(4).is_partial_latin_square()\n True\n sage: back_circulant(3).gcs().is_partial_latin_square()\n True\n sage: back_circulant(6).is_partial_latin_square()\n True\n ' assert (self.nrows() == self.ncols()) n = self.nrows() for r in range(n): vals_in_row = {} for c in range(n): e = self[(r, c)] if (e < 0): continue if (e >= n): return False if (e in vals_in_row): return False vals_in_row[e] = True for c in range(n): vals_in_col = {} for r in range(n): e = self[(r, c)] if (e < 0): continue if (e >= n): return False if (e in vals_in_col): return False vals_in_col[e] = True return True def is_latin_square(self): '\n self is a latin square if it is an n by n matrix, and each symbol\n in [0, 1, ..., n-1] appears exactly once in each row, and exactly\n once in each column.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: elementary_abelian_2group(4).is_latin_square()\n True\n\n ::\n\n sage: forward_circulant(7).is_latin_square()\n True\n ' if (self.nrows() != self.ncols()): return False if any(((x < 0) for x in self.list())): return False if (not self.is_partial_latin_square()): return False return True def permissable_values(self, r, c): '\n Find all values that do not appear in row r and column c of the\n latin square self. If self[r, c] is filled then we return the empty\n list.\n\n INPUT:\n\n - ``self`` - LatinSquare\n\n - ``r`` - int; row of the latin square\n\n - ``c`` - int; column of the latin square\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = back_circulant(5)\n sage: L[0, 0] = -1\n sage: L.permissable_values(0, 0)\n [0]\n ' if (self[(r, c)] >= 0): return [] assert (self.nrows() == self.ncols()) n = self.nrows() vals = {} for e in range(n): vals[e] = True for i in range(n): if (self[(i, c)] >= 0): del vals[self[(i, c)]] for j in range(n): if (self[(r, j)] >= 0): try: del vals[self[(r, j)]] except KeyError: pass return list(vals) def random_empty_cell(self): '\n Find an empty cell of self, uniformly at random.\n\n INPUT:\n\n - ``self`` - LatinSquare\n\n OUTPUT:\n\n - ``[r, c]`` - cell such that self[r, c] is empty, or returns\n None if self is a (full) latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: P = back_circulant(2)\n sage: P[1,1] = -1\n sage: P.random_empty_cell()\n [1, 1]\n ' cells = {} for r in range(self.nrows()): for c in range(self.ncols()): if (self[(r, c)] < 0): cells[(r, c)] = True cells = list(cells) if (not cells): return None rc = cells[ZZ.random_element(len(cells))] return [rc[0], rc[1]] def is_uniquely_completable(self): '\n Return True if the partial latin square self has exactly one\n completion to a latin square. This is just a wrapper for the\n current best-known algorithm, Dancing Links by Knuth. See\n dancing_links.spyx\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(4).gcs().is_uniquely_completable()\n True\n\n ::\n\n sage: G = elementary_abelian_2group(3).gcs()\n sage: G.is_uniquely_completable()\n True\n\n ::\n\n sage: G[0, 0] = -1\n sage: G.is_uniquely_completable()\n False\n ' return self.dlxcpp_has_unique_completion() def is_completable(self): '\n Return True if the partial latin square can be completed to a\n latin square.\n\n EXAMPLES:\n\n The following partial latin square has no completion because there\n is nowhere that we can place the symbol 0 in the third row::\n\n sage: B = LatinSquare(3)\n\n ::\n\n sage: B[0, 0] = 0\n sage: B[1, 1] = 0\n sage: B[2, 2] = 1\n\n ::\n\n sage: B\n [ 0 -1 -1]\n [-1 0 -1]\n [-1 -1 1]\n\n ::\n\n sage: B.is_completable()\n False\n\n ::\n\n sage: B[2, 2] = 0\n sage: B.is_completable()\n True\n ' return bool(dlxcpp_find_completions(self, nr_to_find=1)) def gcs(self): '\n A greedy critical set of a latin square self is found by\n successively removing elements in a row-wise (bottom-up) manner,\n checking for unique completion at each step.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: A = elementary_abelian_2group(3)\n sage: G = A.gcs()\n sage: A\n [0 1 2 3 4 5 6 7]\n [1 0 3 2 5 4 7 6]\n [2 3 0 1 6 7 4 5]\n [3 2 1 0 7 6 5 4]\n [4 5 6 7 0 1 2 3]\n [5 4 7 6 1 0 3 2]\n [6 7 4 5 2 3 0 1]\n [7 6 5 4 3 2 1 0]\n sage: G\n [ 0 1 2 3 4 5 6 -1]\n [ 1 0 3 2 5 4 -1 -1]\n [ 2 3 0 1 6 -1 4 -1]\n [ 3 2 1 0 -1 -1 -1 -1]\n [ 4 5 6 -1 0 1 2 -1]\n [ 5 4 -1 -1 1 0 -1 -1]\n [ 6 -1 4 -1 2 -1 0 -1]\n [-1 -1 -1 -1 -1 -1 -1 -1]\n ' n = self.nrows() from copy import copy G = copy(self) for r in range((n - 1), (- 1), (- 1)): for c in range((n - 1), (- 1), (- 1)): e = G[(r, c)] G[(r, c)] = (- 1) if (not G.dlxcpp_has_unique_completion()): G[(r, c)] = e return G def dlxcpp_has_unique_completion(self): '\n Check if the partial latin square self of order n can be embedded\n in precisely one latin square of order n.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(2).dlxcpp_has_unique_completion()\n True\n sage: P = LatinSquare(2)\n sage: P.dlxcpp_has_unique_completion()\n False\n sage: P[0, 0] = 0\n sage: P.dlxcpp_has_unique_completion()\n True\n ' return (len(dlxcpp_find_completions(self, nr_to_find=2)) == 1) def vals_in_row(self, r): '\n Return a dictionary with key e if and only if row r of self has\n the symbol e.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(3)\n sage: B[0, 0] = -1\n sage: back_circulant(3).vals_in_row(0)\n {0: True, 1: True, 2: True}\n ' n = self.ncols() vals_in_row = {} for c in range(n): e = self[(r, c)] if (e >= 0): vals_in_row[e] = True return vals_in_row def vals_in_col(self, c): '\n Return a dictionary with key e if and only if column c of self has\n the symbol e.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(3)\n sage: B[0, 0] = -1\n sage: back_circulant(3).vals_in_col(0)\n {0: True, 1: True, 2: True}\n ' n = self.nrows() vals_in_col = {} for r in range(n): e = self[(r, c)] if (e >= 0): vals_in_col[e] = True return vals_in_col def latex(self): '\n Return LaTeX code for the latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: print(back_circulant(3).latex())\n \\begin{array}{|c|c|c|}\\hline 0 & 1 & 2\\\\\\hline 1 & 2 & 0\\\\\\hline 2 & 0 & 1\\\\\\hline\\end{array}\n ' a = '' a += (('\\begin{array}{' + (self.ncols() * '|c')) + '|}') for r in range(self.nrows()): a += '\\hline ' for c in range(self.ncols()): s = self[(r, c)] if (s < 0): a += '~' else: a += str(s) if (c < (self.ncols() - 1)): a += ' & ' else: a += '\\\\' a += '\\hline' a += '\\end{array}' return a def disjoint_mate_dlxcpp_rows_and_map(self, allow_subtrade): '\n Internal function for find_disjoint_mates.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(4)\n sage: B.disjoint_mate_dlxcpp_rows_and_map(allow_subtrade = True)\n ([[0, 16, 32],\n [1, 17, 32],\n [2, 18, 32],\n [3, 19, 32],\n [4, 16, 33],\n [5, 17, 33],\n [6, 18, 33],\n [7, 19, 33],\n [8, 16, 34],\n [9, 17, 34],\n [10, 18, 34],\n [11, 19, 34],\n [12, 16, 35],\n [13, 17, 35],\n [14, 18, 35],\n [15, 19, 35],\n [0, 20, 36],\n [1, 21, 36],\n [2, 22, 36],\n [3, 23, 36],\n [4, 20, 37],\n [5, 21, 37],\n [6, 22, 37],\n [7, 23, 37],\n [8, 20, 38],\n [9, 21, 38],\n [10, 22, 38],\n [11, 23, 38],\n [12, 20, 39],\n [13, 21, 39],\n [14, 22, 39],\n [15, 23, 39],\n [0, 24, 40],\n [1, 25, 40],\n [2, 26, 40],\n [3, 27, 40],\n [4, 24, 41],\n [5, 25, 41],\n [6, 26, 41],\n [7, 27, 41],\n [8, 24, 42],\n [9, 25, 42],\n [10, 26, 42],\n [11, 27, 42],\n [12, 24, 43],\n [13, 25, 43],\n [14, 26, 43],\n [15, 27, 43],\n [0, 28, 44],\n [1, 29, 44],\n [2, 30, 44],\n [3, 31, 44],\n [4, 28, 45],\n [5, 29, 45],\n [6, 30, 45],\n [7, 31, 45],\n [8, 28, 46],\n [9, 29, 46],\n [10, 30, 46],\n [11, 31, 46],\n [12, 28, 47],\n [13, 29, 47],\n [14, 30, 47],\n [15, 31, 47]],\n {(0, 16, 32): (0, 0, 0),\n (0, 20, 36): (1, 0, 0),\n (0, 24, 40): (2, 0, 0),\n (0, 28, 44): (3, 0, 0),\n (1, 17, 32): (0, 0, 1),\n (1, 21, 36): (1, 0, 1),\n (1, 25, 40): (2, 0, 1),\n (1, 29, 44): (3, 0, 1),\n (2, 18, 32): (0, 0, 2),\n (2, 22, 36): (1, 0, 2),\n (2, 26, 40): (2, 0, 2),\n (2, 30, 44): (3, 0, 2),\n (3, 19, 32): (0, 0, 3),\n (3, 23, 36): (1, 0, 3),\n (3, 27, 40): (2, 0, 3),\n (3, 31, 44): (3, 0, 3),\n (4, 16, 33): (0, 1, 0),\n (4, 20, 37): (1, 1, 0),\n (4, 24, 41): (2, 1, 0),\n (4, 28, 45): (3, 1, 0),\n (5, 17, 33): (0, 1, 1),\n (5, 21, 37): (1, 1, 1),\n (5, 25, 41): (2, 1, 1),\n (5, 29, 45): (3, 1, 1),\n (6, 18, 33): (0, 1, 2),\n (6, 22, 37): (1, 1, 2),\n (6, 26, 41): (2, 1, 2),\n (6, 30, 45): (3, 1, 2),\n (7, 19, 33): (0, 1, 3),\n (7, 23, 37): (1, 1, 3),\n (7, 27, 41): (2, 1, 3),\n (7, 31, 45): (3, 1, 3),\n (8, 16, 34): (0, 2, 0),\n (8, 20, 38): (1, 2, 0),\n (8, 24, 42): (2, 2, 0),\n (8, 28, 46): (3, 2, 0),\n (9, 17, 34): (0, 2, 1),\n (9, 21, 38): (1, 2, 1),\n (9, 25, 42): (2, 2, 1),\n (9, 29, 46): (3, 2, 1),\n (10, 18, 34): (0, 2, 2),\n (10, 22, 38): (1, 2, 2),\n (10, 26, 42): (2, 2, 2),\n (10, 30, 46): (3, 2, 2),\n (11, 19, 34): (0, 2, 3),\n (11, 23, 38): (1, 2, 3),\n (11, 27, 42): (2, 2, 3),\n (11, 31, 46): (3, 2, 3),\n (12, 16, 35): (0, 3, 0),\n (12, 20, 39): (1, 3, 0),\n (12, 24, 43): (2, 3, 0),\n (12, 28, 47): (3, 3, 0),\n (13, 17, 35): (0, 3, 1),\n (13, 21, 39): (1, 3, 1),\n (13, 25, 43): (2, 3, 1),\n (13, 29, 47): (3, 3, 1),\n (14, 18, 35): (0, 3, 2),\n (14, 22, 39): (1, 3, 2),\n (14, 26, 43): (2, 3, 2),\n (14, 30, 47): (3, 3, 2),\n (15, 19, 35): (0, 3, 3),\n (15, 23, 39): (1, 3, 3),\n (15, 27, 43): (2, 3, 3),\n (15, 31, 47): (3, 3, 3)})\n ' assert (self.nrows() == self.ncols()) n = self.nrows() dlx_rows = [] cmap = {} max_column_nr = (- 1) for r in range(n): valsrow = self.vals_in_row(r) for c in range(n): valscol = self.vals_in_col(c) if (self[(r, c)] < 0): continue for e in sorted(set((list(valsrow) + list(valscol)))): c_OFFSET = (e + (c * n)) r_OFFSET = ((e + (r * n)) + (n * n)) xy_OFFSET = ((((2 * n) * n) + (r * n)) + c) cmap[(c_OFFSET, r_OFFSET, xy_OFFSET)] = (r, c, e) if ((not allow_subtrade) and (self[(r, c)] == e)): continue if (e not in valsrow): continue if (e not in valscol): continue dlx_rows.append([c_OFFSET, r_OFFSET, xy_OFFSET]) if (max_column_nr < max(c_OFFSET, r_OFFSET, xy_OFFSET)): max_column_nr = max(c_OFFSET, r_OFFSET, xy_OFFSET) used_columns = flatten(dlx_rows) for i in range((max_column_nr + 1)): if (i not in used_columns): dlx_rows.append([i]) return (dlx_rows, cmap) def find_disjoint_mates(self, nr_to_find=None, allow_subtrade=False): '\n .. warning::\n\n If allow_subtrade is ``True`` then we may return a partial\n latin square that is *not* disjoint to ``self``. In that case,\n use bitrade(P, Q) to get an actual bitrade.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B = back_circulant(4)\n sage: g = B.find_disjoint_mates(allow_subtrade = True)\n sage: B1 = next(g)\n sage: B0, B1 = bitrade(B, B1)\n sage: assert is_bitrade(B0, B1)\n sage: print(B0)\n [-1 1 2 -1]\n [-1 2 -1 0]\n [-1 -1 -1 -1]\n [-1 0 1 2]\n sage: print(B1)\n [-1 2 1 -1]\n [-1 0 -1 2]\n [-1 -1 -1 -1]\n [-1 1 2 0]\n ' assert (self.nrows() == self.ncols()) (dlx_rows, cmap) = self.disjoint_mate_dlxcpp_rows_and_map(allow_subtrade) nr_found = 0 for x in DLXCPP(dlx_rows): nr_found += 1 from copy import deepcopy Q = deepcopy(self) for y in x: if (len(dlx_rows[y]) == 1): continue (r, c, e) = cmap[tuple(dlx_rows[y])] Q[(r, c)] = e (yield Q) if ((nr_to_find is not None) and (nr_found >= nr_to_find)): return def contained_in(self, Q): '\n Return True if self is a subset of Q?\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: P = elementary_abelian_2group(2)\n sage: P[0, 0] = -1\n sage: P.contained_in(elementary_abelian_2group(2))\n True\n sage: back_circulant(4).contained_in(elementary_abelian_2group(2))\n False\n ' for r in range(self.nrows()): for c in range(self.ncols()): if ((self[(r, c)] >= 0) and (Q[(r, c)] < 0)): return False if ((self[(r, c)] >= 0) and (self[(r, c)] != Q[(r, c)])): return False return True
def genus(T1, T2): "\n Return the genus of hypermap embedding associated with the bitrade\n (T1, T2).\n\n Informally, we compute the [tau_1, tau_2, tau_3]\n permutation representation of the bitrade. Each cycle of tau_1,\n tau_2, and tau_3 gives a rotation scheme for a black, white, and\n star vertex (respectively). The genus then comes from Euler's\n formula.\n\n For more details see Carlo Hamalainen: *Partitioning\n 3-homogeneous latin bitrades*. To appear in Geometriae Dedicata,\n available at :arxiv:`0710.0938`\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: (a, b, c, G) = alternating_group_bitrade_generators(1)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: genus(T1, T2)\n 1\n sage: (a, b, c, G) = pq_group_bitrade_generators(3, 7)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: genus(T1, T2)\n 3\n " (cells_map, t1, t2, t3) = tau123(T1, T2) return (((((len(t1.to_cycles()) + len(t2.to_cycles())) + len(t3.to_cycles())) - T1.nr_filled_cells()) - 2) // (- 2))
def tau123(T1, T2): '\n Compute the tau_i representation for a bitrade (T1, T2).\n\n See the\n functions tau1, tau2, and tau3 for the mathematical definitions.\n\n OUTPUT:\n\n - (cells_map, t1, t2, t3)\n\n where cells_map is a map to/from the filled cells of T1, and t1,\n t2, t3 are the tau1, tau2, tau3 permutations.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: (a, b, c, G) = pq_group_bitrade_generators(3, 7)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: T1\n [ 0 1 3 -1 -1 -1 -1]\n [ 1 2 4 -1 -1 -1 -1]\n [ 2 3 5 -1 -1 -1 -1]\n [ 3 4 6 -1 -1 -1 -1]\n [ 4 5 0 -1 -1 -1 -1]\n [ 5 6 1 -1 -1 -1 -1]\n [ 6 0 2 -1 -1 -1 -1]\n sage: T2\n [ 1 3 0 -1 -1 -1 -1]\n [ 2 4 1 -1 -1 -1 -1]\n [ 3 5 2 -1 -1 -1 -1]\n [ 4 6 3 -1 -1 -1 -1]\n [ 5 0 4 -1 -1 -1 -1]\n [ 6 1 5 -1 -1 -1 -1]\n [ 0 2 6 -1 -1 -1 -1]\n sage: (cells_map, t1, t2, t3) = tau123(T1, T2)\n sage: D = cells_map\n sage: {i: v for i,v in D.items() if i in ZZ}\n {1: (0, 0),\n 2: (0, 1),\n 3: (0, 2),\n 4: (1, 0),\n 5: (1, 1),\n 6: (1, 2),\n 7: (2, 0),\n 8: (2, 1),\n 9: (2, 2),\n 10: (3, 0),\n 11: (3, 1),\n 12: (3, 2),\n 13: (4, 0),\n 14: (4, 1),\n 15: (4, 2),\n 16: (5, 0),\n 17: (5, 1),\n 18: (5, 2),\n 19: (6, 0),\n 20: (6, 1),\n 21: (6, 2)}\n sage: {i: v for i,v in D.items() if i not in ZZ}\n {(0, 0): 1,\n (0, 1): 2,\n (0, 2): 3,\n (1, 0): 4,\n (1, 1): 5,\n (1, 2): 6,\n (2, 0): 7,\n (2, 1): 8,\n (2, 2): 9,\n (3, 0): 10,\n (3, 1): 11,\n (3, 2): 12,\n (4, 0): 13,\n (4, 1): 14,\n (4, 2): 15,\n (5, 0): 16,\n (5, 1): 17,\n (5, 2): 18,\n (6, 0): 19,\n (6, 1): 20,\n (6, 2): 21}\n sage: cells_map_as_square(cells_map, max(T1.nrows(), T1.ncols()))\n [ 1 2 3 -1 -1 -1 -1]\n [ 4 5 6 -1 -1 -1 -1]\n [ 7 8 9 -1 -1 -1 -1]\n [10 11 12 -1 -1 -1 -1]\n [13 14 15 -1 -1 -1 -1]\n [16 17 18 -1 -1 -1 -1]\n [19 20 21 -1 -1 -1 -1]\n sage: t1\n [3, 1, 2, 6, 4, 5, 9, 7, 8, 12, 10, 11, 15, 13, 14, 18, 16, 17, 21, 19, 20]\n sage: t2\n [4, 8, 15, 7, 11, 18, 10, 14, 21, 13, 17, 3, 16, 20, 6, 19, 2, 9, 1, 5, 12]\n sage: t3\n [20, 18, 10, 2, 21, 13, 5, 3, 16, 8, 6, 19, 11, 9, 1, 14, 12, 4, 17, 15, 7]\n\n ::\n\n sage: t1.to_cycles()\n [(1, 3, 2), (4, 6, 5), (7, 9, 8), (10, 12, 11), (13, 15, 14), (16, 18, 17), (19, 21, 20)]\n sage: t2.to_cycles()\n [(1, 4, 7, 10, 13, 16, 19), (2, 8, 14, 20, 5, 11, 17), (3, 15, 6, 18, 9, 21, 12)]\n sage: t3.to_cycles()\n [(1, 20, 15), (2, 18, 4), (3, 10, 8), (5, 21, 7), (6, 13, 11), (9, 16, 14), (12, 19, 17)]\n\n The product t1\\*t2\\*t3 is the identity, i.e. it fixes every point::\n\n sage: len((t1*t2*t3).fixed_points()) == T1.nr_filled_cells()\n True\n ' assert is_bitrade(T1, T2) cells_map = T1.filled_cells_map() t1 = tau1(T1, T2, cells_map) t2 = tau2(T1, T2, cells_map) t3 = tau3(T1, T2, cells_map) return (cells_map, t1, t2, t3)
def isotopism(p): "\n Return a Permutation object that represents an isotopism (for rows,\n columns or symbols of a partial latin square).\n\n Technically, all this function does is take as input a\n representation of a permutation of `0,...,n-1` and return a\n :class:`Permutation` object defined on `1,...,n`.\n\n For a definition of isotopism, see the :wikipedia:`wikipedia section on\n isotopism <Latin_square#Equivalence_classes_of_Latin_squares>`.\n\n INPUT:\n\n According to the type of input (see examples below):\n\n - an integer `n` -- the function returns the identity on `1,...,n`.\n\n - a string representing a permutation in disjoint cycles notation,\n e.g. `(0,1,2)(3,4,5)` -- the corresponding permutation is returned,\n shifted by 1 to act on `1,...,n`.\n\n - list/tuple of tuples -- assumes disjoint cycle notation, see previous\n entry.\n\n - a list of integers -- the function adds `1` to each member of the\n list, and returns the corresponding permutation.\n\n - a :class:`PermutationGroupElement` ``p`` -- returns a permutation\n describing ``p`` **without** any shift.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: isotopism(5) # identity on 5 points\n [1, 2, 3, 4, 5]\n\n ::\n\n sage: G = PermutationGroup(['(1,2,3)(4,5)'])\n sage: g = G.gen(0)\n sage: isotopism(g)\n [2, 3, 1, 5, 4]\n\n ::\n\n sage: isotopism([0,3,2,1]) # 0 goes to 0, 1 goes to 3, etc.\n [1, 4, 3, 2]\n\n ::\n\n sage: isotopism( (0,1,2) ) # single cycle, presented as a tuple\n [2, 3, 1]\n\n ::\n\n sage: x = isotopism( ((0,1,2), (3,4)) ) # tuple of cycles\n sage: x\n [2, 3, 1, 5, 4]\n sage: x.to_cycles()\n [(1, 2, 3), (4, 5)]\n " if isinstance(p, (Integer, int)): return Permutation(range(1, (p + 1))) if isinstance(p, PermutationGroupElement): return Permutation(list(p.tuple())) if isinstance(p, list): return Permutation([(x + 1) for x in p]) if isinstance(p, tuple): if isinstance(p[0], Integer): return Permutation(tuple(((x + 1) for x in p))) if isinstance(p[0], tuple): x = isotopism(p[0]) for i in range(1, len(p)): x = x._left_to_right_multiply_on_left(isotopism(p[i])) return x raise TypeError('unable to convert {!r} to isotopism'.format(p))
def cells_map_as_square(cells_map, n): '\n Return a LatinSquare with cells numbered from 1, 2, ... to given\n the dictionary cells_map.\n\n .. note::\n\n The value n should be the maximum of the number of rows and\n columns of the original partial latin square\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: (a, b, c, G) = alternating_group_bitrade_generators(1)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: T1\n [ 0 -1 3 1]\n [-1 1 0 2]\n [ 1 3 2 -1]\n [ 2 0 -1 3]\n\n There are 12 filled cells in T::\n\n sage: cells_map_as_square(T1.filled_cells_map(), max(T1.nrows(), T1.ncols()))\n [ 1 -1 2 3]\n [-1 4 5 6]\n [ 7 8 9 -1]\n [10 11 -1 12]\n ' assert (n > 1) L = LatinSquare(n, n) for r in range(n): for c in range(n): try: L[(r, c)] = cells_map[(r, c)] except KeyError: L[(r, c)] = (- 1) return L
def beta1(rce, T1, T2): '\n Find the unique (x, c, e) in T2 such that (r, c, e) is in T1.\n\n INPUT:\n\n\n - ``rce`` - tuple (or list) (r, c, e) in T1\n\n - ``T1, T2`` - latin bitrade\n\n\n OUTPUT: (x, c, e) in T2.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: beta1([0, 0, 0], T1, T2)\n (1, 0, 0)\n ' r = rce[0] c = rce[1] e = rce[2] assert (T1[(r, c)] == e) assert (e >= 0) for x in range(T1.nrows()): if (T2[(x, c)] == e): return (x, c, e) raise ValueError
def beta2(rce, T1, T2): '\n Find the unique (r, x, e) in T2 such that (r, c, e) is in T1.\n\n INPUT:\n\n - ``rce`` - tuple (or list) (r, c, e) in T1\n\n - ``T1, T2`` - latin bitrade\n\n\n OUTPUT:\n\n - (r, x, e) in T2.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: beta2([0, 0, 0], T1, T2)\n (0, 1, 0)\n ' r = rce[0] c = rce[1] e = rce[2] assert (T1[(r, c)] == e) assert (e >= 0) for x in range(T1.ncols()): if (T2[(r, x)] == e): return (r, x, e) raise ValueError
def beta3(rce, T1, T2): '\n Find the unique (r, c, x) in T2 such that (r, c, e) is in T1.\n\n INPUT:\n\n\n - ``rce`` - tuple (or list) (r, c, e) in T1\n\n - ``T1, T2`` - latin bitrade\n\n\n OUTPUT:\n\n - (r, c, x) in T2.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: beta3([0, 0, 0], T1, T2)\n (0, 0, 4)\n ' r = rce[0] c = rce[1] e = rce[2] assert (T1[(r, c)] == e) assert (e >= 0) for x in range(T1.nrows()): if (T2[(r, c)] == x): return (r, c, x) raise ValueError
def tau1(T1, T2, cells_map): '\n The definition of `\\tau_1` is\n\n .. MATH::\n\n \\tau_1 : T1 \\rightarrow T1 \\\\\n \\tau_1 = \\beta_2^{-1} \\beta_3\n\n where the composition is left to right and `\\beta_i : T2 \\rightarrow T1`\n changes just the `i^{th}` coordinate of a triple.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: (cells_map, t1, t2, t3) = tau123(T1, T2)\n sage: t1 = tau1(T1, T2, cells_map)\n sage: t1\n [2, 3, 4, 5, 1, 7, 8, 9, 10, 6, 12, 13, 14, 15, 11, 17, 18, 19, 20, 16, 22, 23, 24, 25, 21]\n sage: t1.to_cycles()\n [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15), (16, 17, 18, 19, 20), (21, 22, 23, 24, 25)]\n ' x = ((int((len(cells_map) / 2)) + 1) * [(- 1)]) for r in range(T1.nrows()): for c in range(T1.ncols()): e = T1[(r, c)] if (e < 0): continue (r2, c2, e2) = beta2((r, c, e), T1, T2) (r3, c3, e3) = beta3((r2, c2, e2), T2, T1) x[cells_map[(r, c)]] = cells_map[(r3, c3)] x.pop(0) return Permutation(x)
def tau2(T1, T2, cells_map): '\n The definition of `\\tau_2` is\n\n .. MATH::\n\n \\tau_2 : T1 \\rightarrow T1 \\\\\n \\tau_2 = \\beta_3^{-1} \\beta_1\n\n where the composition is left to right and `\\beta_i : T2 \\rightarrow T1`\n changes just the `i^{th}` coordinate of a triple.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: (cells_map, t1, t2, t3) = tau123(T1, T2)\n sage: t2 = tau2(T1, T2, cells_map)\n sage: t2\n [21, 22, 23, 24, 25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\n sage: t2.to_cycles()\n [(1, 21, 16, 11, 6), (2, 22, 17, 12, 7), (3, 23, 18, 13, 8), (4, 24, 19, 14, 9), (5, 25, 20, 15, 10)]\n ' x = ((int((len(cells_map) / 2)) + 1) * [(- 1)]) for r in range(T1.nrows()): for c in range(T1.ncols()): e = T1[(r, c)] if (e < 0): continue (r2, c2, e2) = beta3((r, c, e), T1, T2) (r3, c3, e3) = beta1((r2, c2, e2), T2, T1) x[cells_map[(r, c)]] = cells_map[(r3, c3)] x.pop(0) return Permutation(x)
def tau3(T1, T2, cells_map): '\n The definition of `\\tau_3` is\n\n .. MATH::\n\n \\tau_3 : T1 \\rightarrow T1 \\\\\n \\tau_3 = \\beta_1^{-1} \\beta_2\n\n where the composition is left to right and `\\beta_i : T2 \\rightarrow T1`\n changes just the `i^{th}` coordinate of a triple.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n sage: (cells_map, t1, t2, t3) = tau123(T1, T2)\n sage: t3 = tau3(T1, T2, cells_map)\n sage: t3\n [10, 6, 7, 8, 9, 15, 11, 12, 13, 14, 20, 16, 17, 18, 19, 25, 21, 22, 23, 24, 5, 1, 2, 3, 4]\n sage: t3.to_cycles()\n [(1, 10, 14, 18, 22), (2, 6, 15, 19, 23), (3, 7, 11, 20, 24), (4, 8, 12, 16, 25), (5, 9, 13, 17, 21)]\n ' x = ((int((len(cells_map) / 2)) + 1) * [(- 1)]) for r in range(T1.nrows()): for c in range(T1.ncols()): e = T1[(r, c)] if (e < 0): continue (r2, c2, e2) = beta1((r, c, e), T1, T2) (r3, c3, e3) = beta2((r2, c2, e2), T2, T1) x[cells_map[(r, c)]] = cells_map[(r3, c3)] x.pop(0) return Permutation(x)
def back_circulant(n): '\n The back-circulant latin square of order n is the Cayley table for\n (Z_n, +), the integers under addition modulo n.\n\n INPUT:\n\n - ``n`` -- int; order of the latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: back_circulant(5)\n [0 1 2 3 4]\n [1 2 3 4 0]\n [2 3 4 0 1]\n [3 4 0 1 2]\n [4 0 1 2 3]\n ' assert (n >= 1) L = LatinSquare(n, n) for r in range(n): for c in range(n): L[(r, c)] = ((r + c) % n) return L
def forward_circulant(n): '\n The forward-circulant latin square of order n is the Cayley table\n for the operation r + c = (n-c+r) mod n.\n\n INPUT:\n\n - ``n`` -- int; order of the latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: forward_circulant(5)\n [0 4 3 2 1]\n [1 0 4 3 2]\n [2 1 0 4 3]\n [3 2 1 0 4]\n [4 3 2 1 0]\n ' assert (n >= 1) L = LatinSquare(n, n) for r in range(n): for c in range(n): L[(r, c)] = (((n - c) + r) % n) return L
def direct_product(L1, L2, L3, L4): "\n The 'direct product' of four latin squares L1, L2, L3, L4 of order\n n is the latin square of order 2n consisting of\n\n ::\n\n -----------\n | L1 | L2 |\n -----------\n | L3 | L4 |\n -----------\n\n where the subsquares L2 and L3 have entries offset by n.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: direct_product(back_circulant(4), back_circulant(4), elementary_abelian_2group(2), elementary_abelian_2group(2))\n [0 1 2 3 4 5 6 7]\n [1 2 3 0 5 6 7 4]\n [2 3 0 1 6 7 4 5]\n [3 0 1 2 7 4 5 6]\n [4 5 6 7 0 1 2 3]\n [5 4 7 6 1 0 3 2]\n [6 7 4 5 2 3 0 1]\n [7 6 5 4 3 2 1 0]\n " assert (L1.nrows() == L2.nrows() == L3.nrows() == L4.nrows()) assert (L1.ncols() == L2.ncols() == L3.ncols() == L4.ncols()) assert (L1.nrows() == L1.ncols()) n = L1.nrows() D = LatinSquare((2 * n), (2 * n)) for r in range(n): for c in range(n): D[(r, c)] = L1[(r, c)] D[(r, (c + n))] = (L2[(r, c)] + n) D[((r + n), c)] = (L3[(r, c)] + n) D[((r + n), (c + n))] = L4[(r, c)] return D
def elementary_abelian_2group(s): '\n Return the latin square based on the Cayley table for the\n elementary abelian 2-group of order 2s.\n\n INPUT:\n\n - ``s`` -- int; order of the latin square will be 2s.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: elementary_abelian_2group(3)\n [0 1 2 3 4 5 6 7]\n [1 0 3 2 5 4 7 6]\n [2 3 0 1 6 7 4 5]\n [3 2 1 0 7 6 5 4]\n [4 5 6 7 0 1 2 3]\n [5 4 7 6 1 0 3 2]\n [6 7 4 5 2 3 0 1]\n [7 6 5 4 3 2 1 0]\n ' assert (s > 0) if (s == 1): L = LatinSquare(2, 2) L[(0, 0)] = 0 L[(0, 1)] = 1 L[(1, 0)] = 1 L[(1, 1)] = 0 return L else: L_prev = elementary_abelian_2group((s - 1)) L = LatinSquare((2 ** s), (2 ** s)) offset = (L.nrows() // 2) for r in range(L_prev.nrows()): for c in range(L_prev.ncols()): L[(r, c)] = L_prev[(r, c)] L[((r + offset), c)] = (L_prev[(r, c)] + offset) L[(r, (c + offset))] = (L_prev[(r, c)] + offset) L[((r + offset), (c + offset))] = L_prev[(r, c)] return L
def coin(): '\n Simulate a fair coin (returns True or False) using\n ZZ.random_element(2).\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import coin\n sage: x = coin()\n sage: x == 0 or x == 1\n True\n ' return (ZZ.random_element(2) == 0)
def next_conjugate(L): '\n Permute L[r, c] = e to the conjugate L[c, e] = r.\n\n We assume that L is an n by n matrix and has values in the range 0,\n 1, ..., n-1.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = back_circulant(6)\n sage: L\n [0 1 2 3 4 5]\n [1 2 3 4 5 0]\n [2 3 4 5 0 1]\n [3 4 5 0 1 2]\n [4 5 0 1 2 3]\n [5 0 1 2 3 4]\n sage: next_conjugate(L)\n [0 1 2 3 4 5]\n [5 0 1 2 3 4]\n [4 5 0 1 2 3]\n [3 4 5 0 1 2]\n [2 3 4 5 0 1]\n [1 2 3 4 5 0]\n sage: L == next_conjugate(next_conjugate(next_conjugate(L)))\n True\n ' assert (L.nrows() == L.ncols()) n = L.nrows() C = LatinSquare(n, n) for r in range(n): for c in range(n): e = L[(r, c)] assert ((e >= 0) and (e < n)) C[(c, e)] = r return C
def row_containing_sym(L, c, x): '\n Given an improper latin square L with L[r1, c] = L[r2, c] = x,\n return r1 or r2 with equal probability. This is an internal\n function and should only be used in LatinSquare_generator().\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = matrix([(0, 1, 0, 3), (3, 0, 2, 1), (1, 0, 3, 2), (2, 3, 1, 0)])\n sage: L\n [0 1 0 3]\n [3 0 2 1]\n [1 0 3 2]\n [2 3 1 0]\n sage: c = row_containing_sym(L, 1, 0)\n sage: c == 1 or c == 2\n True\n ' r1 = (- 1) r2 = (- 1) for r in range(L.nrows()): if ((r1 >= 0) and (r2 >= 0)): break if ((L[(r, c)] == x) and (r1 < 0)): r1 = r continue if ((L[(r, c)] == x) and (r2 < 0)): r2 = r break assert ((r1 >= 0) and (r2 >= 0)) return (r1 if coin() else r2)
def column_containing_sym(L, r, x): '\n Given an improper latin square L with L[r, c1] = L[r, c2] = x,\n return c1 or c2 with equal probability. This is an internal\n function and should only be used in LatinSquare_generator().\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: L = matrix([(1, 0, 2, 3), (0, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)])\n sage: L\n [1 0 2 3]\n [0 2 3 0]\n [2 3 0 1]\n [3 0 1 2]\n sage: c = column_containing_sym(L, 1, 0)\n sage: c == 0 or c == 3\n True\n ' c1 = (- 1) c2 = (- 1) for c in range(L.ncols()): if ((c1 >= 0) and (c2 >= 0)): break if ((L[(r, c)] == x) and (c1 < 0)): c1 = c continue if ((L[(r, c)] == x) and (c2 < 0)): c2 = c break assert ((c1 >= 0) and (c2 >= 0)) return (c1 if coin() else c2)
def LatinSquare_generator(L_start, check_assertions=False): '\n Generator for a sequence of uniformly distributed latin squares,\n given L_start as the initial latin square.\n\n This code implements\n the Markov chain algorithm of Jacobson and Matthews (1996), see\n below for the BibTex entry. This generator will never throw the\n ``StopIteration`` exception, so it provides an infinite sequence of\n latin squares.\n\n EXAMPLES:\n\n Use the back circulant latin square of order 4 as the initial\n square and print the next two latin squares given by the Markov\n chain::\n\n sage: from sage.combinat.matrices.latin import *\n sage: g = LatinSquare_generator(back_circulant(4))\n sage: next(g).is_latin_square()\n True\n\n REFERENCES:\n\n .. [JacMat96] Mark T. Jacobson and Peter Matthews, "Generating uniformly\n distributed random Latin squares", Journal of Combinatorial Designs,\n 4 (1996)\n ' if check_assertions: assert L_start.is_latin_square() n = L_start.nrows() r1 = r2 = c1 = c2 = x = y = z = (- 1) proper = True from copy import copy L = copy(L_start) L_cer = LatinSquare(n, n) L_erc = LatinSquare(n, n) while True: if proper: if check_assertions: assert L.is_latin_square() for r in range(n): for c in range(n): e = L[(r, c)] L_cer[(c, e)] = r L_erc[(e, r)] = c (yield L) r1 = ZZ.random_element(n) c1 = ZZ.random_element(n) x = L[(r1, c1)] y = x while (y == x): y = ZZ.random_element(n) if check_assertions: r2 = 0 c2 = 0 while (L[(r1, c2)] != y): c2 += 1 while (L[(r2, c1)] != y): r2 += 1 assert (L_erc[(y, r1)] == c2) assert (L_cer[(c1, y)] == r2) c2 = L_erc[(y, r1)] r2 = L_cer[(c1, y)] if check_assertions: assert (L[(r1, c2)] == y) if check_assertions: assert (L[(r2, c1)] == y) L[(r1, c1)] = y L[(r1, c2)] = x L[(r2, c1)] = x z = L[(r2, c2)] if (z == x): L[(r2, c2)] = y else: proper = False else: r1 = row_containing_sym(L, c2, x) c1 = column_containing_sym(L, r2, x) if check_assertions: assert (L[(r1, c2)] == x) if check_assertions: assert (L[(r2, c1)] == x) if coin(): (y, z) = (z, y) L[(r2, c2)] = z L[(r1, c2)] = y L[(r2, c1)] = y if (L[(r1, c1)] == y): L[(r1, c1)] = x proper = True else: z = L[(r1, c1)] (x, y) = (y, x) r2 = r1 c2 = c1 proper = False
def group_to_LatinSquare(G): '\n Construct a latin square on the symbols [0, 1, ..., n-1] for a\n group with an n by n Cayley table.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import group_to_LatinSquare\n\n sage: group_to_LatinSquare(DihedralGroup(2))\n [0 1 2 3]\n [1 0 3 2]\n [2 3 0 1]\n [3 2 1 0]\n\n ::\n\n sage: G = libgap.Group(PermutationGroupElement((1,2,3)))\n sage: group_to_LatinSquare(G)\n [0 1 2]\n [1 2 0]\n [2 0 1]\n ' if isinstance(G, GapElement): rows = (list(x) for x in list(libgap.MultiplicationTable(G))) new_rows = [] for x in rows: new_rows.append([(int(xx) - 1) for xx in x]) return matrix(new_rows) T = G.cayley_table() return matrix(ZZ, T.table())
def alternating_group_bitrade_generators(m): '\n Construct generators a, b, c for the alternating group on 3m+1\n points, such that a\\*b\\*c = 1.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: a, b, c, G = alternating_group_bitrade_generators(1)\n sage: (a, b, c, G)\n ((1,2,3), (1,4,2), (2,4,3), Permutation Group with generators [(1,2,3), (1,4,2)])\n sage: a*b*c\n ()\n\n ::\n\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: T1\n [ 0 -1 3 1]\n [-1 1 0 2]\n [ 1 3 2 -1]\n [ 2 0 -1 3]\n sage: T2\n [ 1 -1 0 3]\n [-1 0 2 1]\n [ 2 1 3 -1]\n [ 0 3 -1 2]\n ' assert (m >= 1) a = tuple(range(1, (((2 * m) + 1) + 1))) b = (tuple(range((m + 1), 0, (- 1))) + tuple(range(((2 * m) + 2), (((3 * m) + 1) + 1)))) a = PermutationConstructor(a) b = PermutationConstructor(b) c = PermutationConstructor(((a * b) ** (- 1))) G = PermutationGroup([a, b]) return (a, b, c, G)
def pq_group_bitrade_generators(p, q): '\n Generators for a group of order pq where p and q are primes such\n that (q % p) == 1.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: pq_group_bitrade_generators(3,7)\n ((2,3,5)(4,7,6), (1,2,3,4,5,6,7), (1,4,2)(3,5,6), Permutation Group with generators [(2,3,5)(4,7,6), (1,2,3,4,5,6,7)])\n ' assert is_prime(p) assert is_prime(q) assert ((q % p) == 1) F = FiniteField(q) fgen = F.multiplicative_generator() beta = (fgen ** ((q - 1) / p)) assert (beta != 1) assert (((beta ** p) % q) == 1) Q = tuple(range(1, (q + 1))) P = [] seenValues = {} for i in range(2, q): if (i in seenValues): continue cycle = [] for k in range(p): x = ((1 + ((i - 1) * (beta ** k))) % q) if (x == 0): x = q seenValues[x] = True cycle.append(x) P.append(tuple(map(Integer, cycle))) G = PermutationGroup([P, Q]) assert (G.order() == (p * q)) assert (not G.is_abelian()) a = PermutationConstructor(P) b = PermutationConstructor(Q) c = PermutationConstructor(((a * b) ** (- 1))) return (a, b, c, PermutationGroup([P, Q]))
def p3_group_bitrade_generators(p): '\n Generators for a group of order p3 where p is a prime.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: p3_group_bitrade_generators(3)\n ((2,6,7)(3,8,9),\n (1,2,3)(4,7,8)(5,6,9),\n (1,9,2)(3,7,4)(5,8,6),\n Permutation Group with generators [(2,6,7)(3,8,9), (1,2,3)(4,7,8)(5,6,9)])\n ' assert is_prime(p) F = libgap.FreeGroup(3) (a, b, c) = F.GeneratorsOfGroup() rels = [] rels.append((a ** p)) rels.append((b ** p)) rels.append((c ** p)) rels.append(((a * b) * (((b * a) * c) ** (- 1)))) rels.append(((c * a) * ((a * c) ** (- 1)))) rels.append(((c * b) * ((b * c) ** (- 1)))) G = F.FactorGroupFpGroupByRels(rels) (u, v, _) = G.GeneratorsOfGroup() iso = libgap.IsomorphismPermGroup(G) x = PermutationConstructor(libgap.Image(iso, u)) y = PermutationConstructor(libgap.Image(iso, v)) return (x, y, ((x * y) ** (- 1)), PermutationGroup([x, y]))
def check_bitrade_generators(a, b, c): "\n Three group elements a, b, c will generate a bitrade if a\\*b\\*c = 1\n and the subgroups a, b, c intersect (pairwise) in just the\n identity.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: a, b, c, G = p3_group_bitrade_generators(3)\n sage: check_bitrade_generators(a, b, c)\n True\n sage: check_bitrade_generators(a, b, gap('()'))\n False\n " A = PermutationGroup([a]) B = PermutationGroup([b]) C = PermutationGroup([c]) if ((a * b) != (c ** (- 1))): return False X = libgap.Intersection(libgap.Intersection(A, B), C) return (X.Size() == 1)
def is_bitrade(T1, T2): '\n Combinatorially, a pair (T1, T2) of partial latin squares is a\n bitrade if they are disjoint, have the same shape, and have row and\n column balance. For definitions of each of these terms see the\n relevant function in this file.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_bitrade(T1, T2)\n True\n ' return (is_disjoint(T1, T2) and is_same_shape(T1, T2) and is_row_and_col_balanced(T1, T2))
def is_primary_bitrade(a, b, c, G): '\n A bitrade generated from elements a, b, c is primary if a, b, c =\n G.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: (a, b, c, G) = p3_group_bitrade_generators(5)\n sage: is_primary_bitrade(a, b, c, G)\n True\n ' return (G == PermutationGroup([a, b, c]))
def tau_to_bitrade(t1, t2, t3): '\n Given permutations t1, t2, t3 that represent a latin bitrade,\n convert them to an explicit latin bitrade (T1, T2). The result is\n unique up to isotopism.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: _, t1, t2, t3 = tau123(T1, T2)\n sage: U1, U2 = tau_to_bitrade(t1, t2, t3)\n sage: assert is_bitrade(U1, U2)\n sage: U1\n [0 1 2 3 4]\n [1 2 3 4 0]\n [2 3 4 0 1]\n [3 4 0 1 2]\n [4 0 1 2 3]\n sage: U2\n [4 0 1 2 3]\n [0 1 2 3 4]\n [1 2 3 4 0]\n [2 3 4 0 1]\n [3 4 0 1 2]\n ' c1 = t1.to_cycles() c2 = t2.to_cycles() c3 = t3.to_cycles() pt_to_cycle1 = {} pt_to_cycle2 = {} pt_to_cycle3 = {} for i in range(len(c1)): for j in range(len(c1[i])): pt_to_cycle1[c1[i][j]] = i for i in range(len(c2)): for j in range(len(c2[i])): pt_to_cycle2[c2[i][j]] = i for i in range(len(c3)): for j in range(len(c3[i])): pt_to_cycle3[c3[i][j]] = i n = max(len(c1), len(c2), len(c3)) T1 = LatinSquare(n) T2 = LatinSquare(n) for r in range(len(c1)): for c in range(len(c2)): for s in range(len(c3)): nr_common = len(reduce(set.intersection, [set(c1[r]), set(c2[c]), set(c3[s])])) assert (nr_common in [0, 1]) if (nr_common == 1): T1[(r, c)] = s for cycle in c1: for pt1 in cycle: pt2 = t1[(pt1 - 1)] pt3 = t2[(pt2 - 1)] assert (t3[(pt3 - 1)] == pt1) r = pt_to_cycle1[pt1] c = pt_to_cycle2[pt2] s = pt_to_cycle3[pt3] T2[(r, c)] = s return (T1, T2)
def bitrade_from_group(a, b, c, G): '\n Given group elements a, b, c in G such that abc = 1 and the\n subgroups a, b, c intersect (pairwise) only in the identity,\n construct a bitrade (T1, T2) where rows, columns, and symbols\n correspond to cosets of a, b, and c, respectively.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: a, b, c, G = alternating_group_bitrade_generators(1)\n sage: (T1, T2) = bitrade_from_group(a, b, c, G)\n sage: T1\n [ 0 -1 3 1]\n [-1 1 0 2]\n [ 1 3 2 -1]\n [ 2 0 -1 3]\n sage: T2\n [ 1 -1 0 3]\n [-1 0 2 1]\n [ 2 1 3 -1]\n [ 0 3 -1 2]\n ' hom = libgap.ActionHomomorphism(G, libgap.RightCosets(G, libgap.TrivialSubgroup(G)), libgap.OnRight) t1 = libgap.Image(hom, a) t2 = libgap.Image(hom, b) t3 = libgap.Image(hom, c) t1 = Permutation(str(t1).replace('\n', '')) t2 = Permutation(str(t2).replace('\n', '')) t3 = Permutation(str(t3).replace('\n', '')) return tau_to_bitrade(t1, t2, t3)
def is_disjoint(T1, T2): '\n The partial latin squares T1 and T2 are disjoint if T1[r, c] !=\n T2[r, c] or T1[r, c] == T2[r, c] == -1 for each cell [r, c].\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import is_disjoint, back_circulant, isotopism\n sage: is_disjoint(back_circulant(2), back_circulant(2))\n False\n\n ::\n\n sage: T1 = back_circulant(5)\n sage: x = isotopism( (0,1,2,3,4) )\n sage: y = isotopism(5) # identity\n sage: z = isotopism(5) # identity\n sage: T2 = T1.apply_isotopism(x, y, z)\n sage: is_disjoint(T1, T2)\n True\n ' for i in range(T1.nrows()): for j in range(T1.ncols()): if ((T1[(i, j)] < 0) and (T2[(i, j)] < 0)): continue if (T1[(i, j)] == T2[(i, j)]): return False return True
def is_same_shape(T1, T2): '\n Two partial latin squares T1, T2 have the same shape if T1[r, c] =\n 0 if and only if T2[r, c] = 0.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: is_same_shape(elementary_abelian_2group(2), back_circulant(4))\n True\n sage: is_same_shape(LatinSquare(5), LatinSquare(5))\n True\n sage: is_same_shape(forward_circulant(5), LatinSquare(5))\n False\n ' for i in range(T1.nrows()): for j in range(T1.ncols()): if ((T1[(i, j)] < 0) and (T2[(i, j)] < 0)): continue if ((T1[(i, j)] >= 0) and (T2[(i, j)] >= 0)): continue return False return True
def is_row_and_col_balanced(T1, T2): '\n Partial latin squares T1 and T2 are balanced if the symbols\n appearing in row r of T1 are the same as the symbols appearing in\n row r of T2, for each r, and if the same condition holds on\n columns.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: T1 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]])\n sage: T2 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]])\n sage: is_row_and_col_balanced(T1, T2)\n True\n sage: T2 = matrix([[0,3,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]])\n sage: is_row_and_col_balanced(T1, T2)\n False\n ' for r in range(T1.nrows()): val1 = set((x for x in T1.row(r) if (x >= 0))) val2 = set((x for x in T2.row(r) if (x >= 0))) if (val1 != val2): return False for c in range(T1.ncols()): val1 = set((x for x in T1.column(c) if (x >= 0))) val2 = set((x for x in T2.column(c) if (x >= 0))) if (val1 != val2): return False return True
def dlxcpp_rows_and_map(P): '\n Internal function for ``dlxcpp_find_completions``. Given a partial\n latin square P we construct a list of rows of a 0-1 matrix M such\n that an exact cover of M corresponds to a completion of P to a\n latin square.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: dlxcpp_rows_and_map(LatinSquare(2))\n ([[0, 4, 8],\n [1, 5, 8],\n [2, 4, 9],\n [3, 5, 9],\n [0, 6, 10],\n [1, 7, 10],\n [2, 6, 11],\n [3, 7, 11]],\n {(0, 4, 8): (0, 0, 0),\n (0, 6, 10): (1, 0, 0),\n (1, 5, 8): (0, 0, 1),\n (1, 7, 10): (1, 0, 1),\n (2, 4, 9): (0, 1, 0),\n (2, 6, 11): (1, 1, 0),\n (3, 5, 9): (0, 1, 1),\n (3, 7, 11): (1, 1, 1)})\n ' assert (P.nrows() == P.ncols()) n = P.nrows() dlx_rows = [] cmap = {} for r in range(n): valsrow = P.vals_in_row(r) for c in range(n): valscol = P.vals_in_col(c) for e in range(n): c_OFFSET = (e + (c * n)) r_OFFSET = ((e + (r * n)) + (n * n)) xy_OFFSET = ((((2 * n) * n) + (r * n)) + c) cmap[(c_OFFSET, r_OFFSET, xy_OFFSET)] = (r, c, e) if ((P[(r, c)] >= 0) and (P[(r, c)] != e)): continue if ((P[(r, c)] < 0) and (e in valsrow)): continue if ((P[(r, c)] < 0) and (e in valscol)): continue dlx_rows.append([c_OFFSET, r_OFFSET, xy_OFFSET]) return (dlx_rows, cmap)
def dlxcpp_find_completions(P, nr_to_find=None): '\n Return a list of all latin squares L of the same order as P such\n that P is contained in L. The optional parameter nr_to_find\n limits the number of latin squares that are found.\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: dlxcpp_find_completions(LatinSquare(2))\n [[0 1]\n [1 0], [1 0]\n [0 1]]\n\n ::\n\n sage: dlxcpp_find_completions(LatinSquare(2), 1)\n [[0 1]\n [1 0]]\n ' assert (P.nrows() == P.ncols()) (dlx_rows, cmap) = dlxcpp_rows_and_map(P) SOLUTIONS = {} for x in DLXCPP(dlx_rows): x.sort() SOLUTIONS[tuple(x)] = True if ((nr_to_find is not None) and (len(SOLUTIONS) >= nr_to_find)): break comps = [] for i in SOLUTIONS: soln = list(i) from copy import deepcopy Q = deepcopy(P) for x in soln: (r, c, e) = cmap[tuple(dlx_rows[x])] if (Q[(r, c)] >= 0): assert (Q[(r, c)] == e) else: Q[(r, c)] = e comps.append(Q) return comps
def bitrade(T1, T2): '\n Form the bitrade (Q1, Q2) from (T1, T2) by setting empty the cells\n (r, c) such that T1[r, c] == T2[r, c].\n\n EXAMPLES::\n\n sage: from sage.combinat.matrices.latin import *\n sage: B1 = back_circulant(5)\n sage: alpha = isotopism((0,1,2,3,4))\n sage: beta = isotopism((1,0,2,3,4))\n sage: gamma = isotopism((2,1,0,3,4))\n sage: B2 = B1.apply_isotopism(alpha, beta, gamma)\n sage: T1, T2 = bitrade(B1, B2)\n sage: T1\n [ 0 1 -1 3 4]\n [ 1 -1 -1 4 0]\n [ 2 -1 4 0 1]\n [ 3 4 0 1 2]\n [ 4 0 1 2 3]\n sage: T2\n [ 3 4 -1 0 1]\n [ 0 -1 -1 1 4]\n [ 1 -1 0 4 2]\n [ 4 0 1 2 3]\n [ 2 1 4 3 0]\n ' assert (T1.nrows() == T1.ncols()) assert (T2.nrows() == T2.ncols()) assert (T1.nrows() == T2.nrows()) n = T1.nrows() from copy import copy Q1 = copy(T1) Q2 = copy(T2) for r in range(n): for c in range(n): if (T1[(r, c)] == T2[(r, c)]): Q1[(r, c)] = (- 1) Q2[(r, c)] = (- 1) return (Q1, Q2)
class DoublyLinkedList(): "\n A doubly linked list class that provides constant time hiding and\n unhiding of entries.\n\n Note that this list's indexing is 1-based.\n\n EXAMPLES::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3]); dll\n Doubly linked list of [1, 2, 3]: [1, 2, 3]\n sage: dll.hide(1); dll\n Doubly linked list of [1, 2, 3]: [2, 3]\n sage: dll.unhide(1); dll\n Doubly linked list of [1, 2, 3]: [1, 2, 3]\n sage: dll.hide(2); dll\n Doubly linked list of [1, 2, 3]: [1, 3]\n sage: dll.unhide(2); dll\n Doubly linked list of [1, 2, 3]: [1, 2, 3]\n " def __init__(self, l): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll == loads(dumps(dll))\n True\n ' n = len(l) self.l = l self.next_value = {} self.next_value['begin'] = l[0] self.next_value[l[(n - 1)]] = 'end' for i in range((n - 1)): self.next_value[l[i]] = l[(i + 1)] self.prev_value = {} self.prev_value['end'] = l[(- 1)] self.prev_value[l[0]] = 'begin' for i in range(1, n): self.prev_value[l[i]] = l[(i - 1)] def __eq__(self, other): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll2 = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll == dll2\n True\n sage: dll.hide(1)\n sage: dll == dll2\n False\n ' return (isinstance(other, DoublyLinkedList) and (self.l == other.l) and (self.next_value == other.next_value) and (self.prev_value == other.prev_value)) def __ne__(self, other): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll2 = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll != dll2\n False\n sage: dll.hide(1)\n sage: dll != dll2\n True\n ' return (not (self == other)) def __repr__(self): "\n TESTS::\n\n sage: repr(sage.combinat.misc.DoublyLinkedList([1,2,3]))\n 'Doubly linked list of [1, 2, 3]: [1, 2, 3]'\n " return ('Doubly linked list of %s: %s' % (self.l, list(self))) def __iter__(self): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: list(dll)\n [1, 2, 3]\n ' j = self.next_value['begin'] while (j != 'end'): (yield j) j = self.next_value[j] def hide(self, i): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll.hide(1)\n sage: list(dll)\n [2, 3]\n ' self.next_value[self.prev_value[i]] = self.next_value[i] self.prev_value[self.next_value[i]] = self.prev_value[i] def unhide(self, i): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll.hide(1); dll.unhide(1)\n sage: list(dll)\n [1, 2, 3]\n ' self.next_value[self.prev_value[i]] = i self.prev_value[self.next_value[i]] = i def head(self): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll.head()\n 1\n sage: dll.hide(1)\n sage: dll.head()\n 2\n ' return self.next_value['begin'] def next(self, j): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll.next(1)\n 2\n sage: dll.hide(2)\n sage: dll.next(1)\n 3\n ' return self.next_value[j] def prev(self, j): '\n TESTS::\n\n sage: dll = sage.combinat.misc.DoublyLinkedList([1,2,3])\n sage: dll.prev(3)\n 2\n sage: dll.hide(2)\n sage: dll.prev(3)\n 1\n ' return self.prev_value[j]
def _monomial_exponent_to_lower_factorial(me, x): '\n Converts a tuple of exponents to the monomial obtained by replacing\n each me[i] with `x_i*(x_i - 1)*\\cdots*(x_i - a_i + 1)`\n\n EXAMPLES::\n\n sage: from sage.combinat.misc import _monomial_exponent_to_lower_factorial\n sage: R.<x,y,z> = QQ[]\n sage: a = R.gens()\n sage: _monomial_exponent_to_lower_factorial(([1,0,0]),a)\n x\n sage: _monomial_exponent_to_lower_factorial(([2,0,0]),a)\n x^2 - x\n sage: _monomial_exponent_to_lower_factorial(([0,2,0]),a)\n y^2 - y\n sage: _monomial_exponent_to_lower_factorial(([1,1,0]),a)\n x*y\n sage: _monomial_exponent_to_lower_factorial(([1,1,2]),a)\n x*y*z^2 - x*y*z\n sage: _monomial_exponent_to_lower_factorial(([2,2,2]),a)\n x^2*y^2*z^2 - x^2*y^2*z - x^2*y*z^2 - x*y^2*z^2 + x^2*y*z + x*y^2*z + x*y*z^2 - x*y*z\n ' terms = [] for i in range(len(me)): for j in range(me[i]): terms.append((x[i] - j)) return prod(terms)
def umbral_operation(poly): "\n Returns the umbral operation `\\downarrow` applied to poly.\n\n The umbral operation replaces each instance of\n `x_i^{a_i}` with\n `x_i*(x_i - 1)*\\cdots*(x_i - a_i + 1)`.\n\n EXAMPLES::\n\n sage: P = PolynomialRing(QQ, 2, 'x')\n sage: x = P.gens()\n sage: from sage.combinat.misc import umbral_operation\n sage: umbral_operation(x[0]^3) == x[0]*(x[0]-1)*(x[0]-2)\n True\n sage: umbral_operation(x[0]*x[1])\n x0*x1\n sage: umbral_operation(x[0]+x[1])\n x0 + x1\n sage: umbral_operation(x[0]^2*x[1]^2) == x[0]*(x[0]-1)*x[1]*(x[1]-1)\n True\n " x = poly.parent().gens() exponents = poly.exponents() coefficients = poly.coefficients() length = len(exponents) return sum([(coefficients[i] * _monomial_exponent_to_lower_factorial(exponents[i], x)) for i in range(length)])
class IterableFunctionCall(): "\n This class wraps functions with a yield statement (generators) by\n an object that can be iterated over. For example,\n\n EXAMPLES::\n\n sage: def f(): yield 'a'; yield 'b'\n\n This does not work::\n\n sage: for z in f: print(z)\n Traceback (most recent call last):\n ...\n TypeError: 'function' object is not iterable\n\n Use IterableFunctionCall if you want something like the above to\n work::\n\n sage: from sage.combinat.misc import IterableFunctionCall\n sage: g = IterableFunctionCall(f)\n sage: for z in g: print(z)\n a\n b\n\n If your function takes arguments, just put them after the function\n name. You needn't enclose them in a tuple or anything, just put them\n there::\n\n sage: def f(n, m): yield 'a' * n; yield 'b' * m; yield 'foo'\n sage: g = IterableFunctionCall(f, 2, 3)\n sage: for z in g: print(z)\n aa\n bbb\n foo\n " def __init__(self, f, *args, **kwargs): '\n EXAMPLES::\n\n sage: from sage.combinat.misc import IterableFunctionCall\n sage: IterableFunctionCall(iter, [1,2,3])\n Iterable function call <built-in function iter> with args=([1, 2, 3],) and kwargs={}\n ' self.f = f self.args = args self.kwargs = kwargs def __iter__(self): '\n EXAMPLES::\n\n sage: from sage.combinat.misc import IterableFunctionCall\n sage: list(iter(IterableFunctionCall(iter, [1,2,3])))\n [1, 2, 3]\n ' return self.f(*self.args, **self.kwargs) def __repr__(self): "\n EXAMPLES::\n\n sage: from sage.combinat.misc import IterableFunctionCall\n sage: repr(IterableFunctionCall(iter, [1,2,3]))\n 'Iterable function call <built-in function iter> with args=([1, 2, 3],) and kwargs={}'\n " return ('Iterable function call %s with args=%s and kwargs=%s' % (self.f, self.args, self.kwargs))
def check_integer_list_constraints(l, **kwargs): '\n EXAMPLES::\n\n sage: from sage.combinat.misc import check_integer_list_constraints\n sage: cilc = check_integer_list_constraints\n sage: l = [[2,1,3],[1,2],[3,3],[4,1,1]]\n sage: cilc(l, min_part=2)\n [[3, 3]]\n sage: cilc(l, max_part=2)\n [[1, 2]]\n sage: cilc(l, length=2)\n [[1, 2], [3, 3]]\n sage: cilc(l, max_length=2)\n [[1, 2], [3, 3]]\n sage: cilc(l, min_length=3)\n [[2, 1, 3], [4, 1, 1]]\n sage: cilc(l, max_slope=0)\n [[3, 3], [4, 1, 1]]\n sage: cilc(l, min_slope=1)\n [[1, 2]]\n sage: cilc(l, outer=[2,2])\n [[1, 2]]\n sage: cilc(l, inner=[2,2])\n [[3, 3]]\n\n ::\n\n sage: cilc([1,2,3], length=3, singleton=True)\n [1, 2, 3]\n sage: cilc([1,2,3], length=2, singleton=True) is None\n True\n ' if (('singleton' in kwargs) and kwargs['singleton']): singleton = True result = [l] n = sum(l) del kwargs['singleton'] else: singleton = False if l: n = sum(l[0]) result = l else: return [] min_part = kwargs.get('min_part', None) max_part = kwargs.get('max_part', None) min_length = kwargs.get('min_length', None) max_length = kwargs.get('max_length', None) min_slope = kwargs.get('min_slope', None) max_slope = kwargs.get('max_slope', None) length = kwargs.get('length', None) inner = kwargs.get('inner', None) outer = kwargs.get('outer', None) if (outer is not None): max_length = len(outer) for i in range(max_length): if (outer[i] == 'inf'): outer[i] = (n + 1) if (inner is not None): min_length = len(inner) if (length is not None): max_length = length min_length = length filters = {} filters['length'] = (lambda x: (len(x) == length)) filters['min_part'] = (lambda x: (min(x) >= min_part)) filters['max_part'] = (lambda x: (max(x) <= max_part)) filters['min_length'] = (lambda x: (len(x) >= min_length)) filters['max_length'] = (lambda x: (len(x) <= max_length)) filters['min_slope'] = (lambda x: (min(((x[(i + 1)] - x[i]) for i in range((len(x) - 1))), default=(min_slope + 1)) >= min_slope)) filters['max_slope'] = (lambda x: (max(((x[(i + 1)] - x[i]) for i in range((len(x) - 1))), default=(max_slope - 1)) <= max_slope)) filters['outer'] = (lambda x: ((len(outer) >= len(x)) and (min(((outer[i] - x[i]) for i in range(len(x)))) >= 0))) filters['inner'] = (lambda x: ((len(x) >= len(inner)) and (max(((inner[i] - x[i]) for i in range(len(inner)))) <= 0))) for key in kwargs: result = [x for x in result if filters[key](x)] if singleton: try: return result[0] except IndexError: return None else: return result
class OrderedMultisetPartitionIntoSets(ClonableArray, metaclass=InheritComparisonClasscallMetaclass): '\n Ordered Multiset Partition into sets\n\n An *ordered multiset partition into sets* `c` of a multiset `X` is a list\n `[c_1, \\ldots, c_r]` of nonempty subsets of `X` (note: not\n sub-multisets), called the *blocks* of `c`, whose multi-union is `X`.\n\n EXAMPLES:\n\n The simplest way to create an ordered multiset partition into sets is by\n specifying its blocks as a list or tuple::\n\n sage: OrderedMultisetPartitionIntoSets([[3],[2,1]])\n [{3}, {1,2}]\n sage: OrderedMultisetPartitionIntoSets(((3,), (1,2)))\n [{3}, {1,2}]\n sage: OrderedMultisetPartitionIntoSets([set([i]) for i in range(2,5)])\n [{2}, {3}, {4}]\n\n REFERENCES:\n\n - [HRW2015]_\n - [HRS2016]_\n - [LM2018]_\n ' @staticmethod def __classcall_private__(cls, co): "\n Create an ordered multiset partition into sets (i.e., a list of sets)\n from the passed arguments with the appropriate parent.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[3], [2,1]])\n [{3}, {1,2}]\n sage: c = OrderedMultisetPartitionsIntoSets()([{2}, {3}, {4}, {5}]); c\n [{2}, {3}, {4}, {5}]\n sage: d = OrderedMultisetPartitionsIntoSets((1,1,1,2,3,5))([{1}, {5, 1, 3}, {2, 1}]); d\n [{1}, {1,3,5}, {1,2}]\n\n TESTS::\n\n sage: c.parent() == OrderedMultisetPartitionsIntoSets([2,3,4,5])\n False\n sage: d.parent() == OrderedMultisetPartitionsIntoSets([1,1,1,2,3,5])\n True\n sage: repr(OrderedMultisetPartitionIntoSets([]).parent())\n 'Ordered Multiset Partitions into Sets of multiset {{}}'\n " if (not co): P = OrderedMultisetPartitionsIntoSets([]) return P.element_class(P, []) else: X = _concatenate(co) P = OrderedMultisetPartitionsIntoSets(_get_weight(X)) return P.element_class(P, co) def __init__(self, parent, data): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: c = OrderedMultisetPartitionsIntoSets(7)([[1,3], [1,2]])\n sage: OrderedMultisetPartitionIntoSets([[1,3], [1,2]]) == c\n True\n sage: c.weight()\n {1: 2, 2: 1, 3: 1}\n\n TESTS::\n\n sage: OMP = OrderedMultisetPartitionIntoSets\n sage: c0 = OMP([])\n sage: OMP([[]]) == c0\n True\n sage: TestSuite(c0).run()\n\n sage: d = OMP([[1, 3], [1, 'a', 'b']])\n sage: TestSuite(d).run()\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets()\n sage: d = OMPs([['a','b','c'],['a','b'],['a']])\n sage: TestSuite(d).run()\n\n sage: c.size() == 7\n True\n sage: d.size() == None\n True\n " co = [block for block in data if block] if (not _has_nonempty_sets(co)): raise ValueError(('cannot view %s as an ordered partition of %s' % (co, parent._Xtup))) ClonableArray.__init__(self, parent, [frozenset(k) for k in co]) self._multiset = _get_multiset(co) self._weight = _get_weight(self._multiset) self._order = sum((len(block) for block in self)) if all((((a in ZZ) and (a > 0)) for a in self._multiset)): self._n = ZZ(sum(self._multiset)) else: self._n = None def check(self): "\n Check that we are a valid ordered multiset partition into sets.\n\n EXAMPLES::\n\n sage: c = OrderedMultisetPartitionsIntoSets(4)([[1], [1,2]])\n sage: c.check()\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets()\n sage: c = OMPs([[1], [1], ['a']])\n sage: c.check()\n\n TESTS::\n\n sage: c = OMPs([[1, 1], [1, 4]])\n Traceback (most recent call last):\n ...\n ValueError: cannot convert [[1, 1], [1, 4]] into an element\n of Ordered Multiset Partitions into Sets\n " if (self not in self.parent()): raise ValueError('{} not an element of {}'.format(self, self.parent())) def _repr_(self): '\n Return a string representation of ``self.``\n\n EXAMPLES::\n\n sage: A = OrderedMultisetPartitionIntoSets([[4], [1,2,4], [2,3], [1]])\n sage: A\n [{4}, {1,2,4}, {2,3}, {1}]\n ' return self._repr_tight() def _repr_normal(self): '\n Viewing ``self`` as a list `[A_1, \\ldots, A_r]` of sets,\n return the standard Sage string representation of `[A_1, \\ldots, A_r]`.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[4,1,3], [3,2,5]])._repr_normal()\n \'[{1, 3, 4}, {2, 3, 5}]\'\n sage: OrderedMultisetPartitionIntoSets([[4,1,3,11], [3,\'a\',5]])._repr_normal()\n "[{1, 11, 3, 4}, {3, 5, \'a\'}]"\n ' if self._n: string_parts = map((lambda k: str(sorted(k))), self) else: string_parts = map((lambda k: str(sorted(k, key=str))), self) string_parts = ', '.join(string_parts).replace('[', '{').replace(']', '}') return (('[' + string_parts) + ']') def _repr_tight(self): "\n Starting from the standard Sage string representation of ``self``\n as a list `[A_1, \\ldots, A_r]` of sets, return the shorter string\n gotten by deleting spaces within ``repr(A_i)``.\n\n EXAMPLES::\n\n sage: A = OrderedMultisetPartitionIntoSets([[4], [1,2,4], [2,3], [1]])\n sage: A._repr_normal()\n '[{4}, {1, 2, 4}, {2, 3}, {1}]'\n sage: A._repr_tight()\n '[{4}, {1,2,4}, {2,3}, {1}]'\n " repr = self._repr_normal() return repr.replace(', ', ',').replace('},{', '}, {') def __hash__(self): '\n Return the hash of ``self``.\n\n The parent is not included as part of the hash.\n\n EXAMPLES::\n\n sage: OMP = OrderedMultisetPartitionsIntoSets(4)\n sage: A = OMP([[1], [1, 2]])\n sage: B = OMP([{1}, {1, 2}])\n sage: hash(A) == hash(B)\n True\n ' return sum((hash(x) for x in self)) def __eq__(self, y): '\n Check equality of ``self`` and ``y``.\n\n The parent is not included as part of the equality check.\n\n TESTS::\n\n sage: OMP_n = OrderedMultisetPartitionsIntoSets(4)\n sage: OMP_X = OrderedMultisetPartitionsIntoSets([1,1,2])\n sage: OMP_Ad = OrderedMultisetPartitionsIntoSets(2, 3)\n sage: mu = [[1], [1, 2]]\n sage: OMP_n(mu) == OMP_X(mu) == OMP_Ad(mu)\n True\n sage: OMP_n(mu) == mu\n False\n sage: OMP_n(mu) == OMP_n([{1}, {3}])\n False\n sage: OMP_n(mu) == OMP_X([[1], [1,2]])\n True\n ' if (not isinstance(y, OrderedMultisetPartitionIntoSets)): return False return (list(self) == list(y)) def __ne__(self, y): '\n Check lack of equality of ``self`` and ``y``.\n\n The parent is not included as part of the equality check.\n\n TESTS::\n\n sage: OMP = OrderedMultisetPartitionsIntoSets(4)\n sage: mu = [[1], [1, 2]]\n sage: OMP(mu).__ne__(mu)\n True\n sage: nu = [[1], [2], [1]]\n sage: OMP(mu).__ne__(OMP(nu))\n True\n ' return (not (self == y)) def __add__(self, other): '\n Return the concatenation of two ordered multiset partitions into sets.\n\n This operation represents the product in Hopf algebra of ordered multiset\n partitions into sets in its natural basis [LM2018]_.\n\n EXAMPLES::\n\n sage: OMP = OrderedMultisetPartitionIntoSets\n sage: OMP([[1],[1],[1,3]]) + OMP([[4,1],[2]])\n [{1}, {1}, {1,3}, {1,4}, {2}]\n\n TESTS::\n\n sage: OMP([]) + OMP([]) == OMP([])\n True\n sage: OMP([[1],[1],[1,3]]) + OMP([]) == OMP([[1],[1],[1,3]])\n True\n ' co = (list(self) + list(other)) X = _concatenate(co) return OrderedMultisetPartitionsIntoSets(_get_weight(X))(co) @combinatorial_map(order=2, name='reversal') def reversal(self): '\n Return the reverse ordered multiset partition into sets of ``self``.\n\n Given an ordered multiset partition into sets `(B_1, B_2, \\ldots, B_k)`,\n its reversal is defined to be the ordered multiset partition into sets\n `(B_k, \\ldots, B_2, B_1)`.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[1], [1, 3], [2, 3, 4]]); C\n [{1}, {1,3}, {2,3,4}]\n sage: C.reversal()\n [{2,3,4}, {1,3}, {1}]\n ' return self.parent()(list(reversed(self))) def shape_from_cardinality(self): '\n Return a composition that records the cardinality of each block of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.shape_from_cardinality()\n [3, 1, 4]\n sage: OrderedMultisetPartitionIntoSets([]).shape_from_cardinality() == Composition([])\n True\n ' return Composition([len(k) for k in self]) def shape_from_size(self): "\n Return a composition that records the sum of entries of each\n block of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.shape_from_size()\n [8, 2, 13]\n\n TESTS::\n\n sage: OrderedMultisetPartitionIntoSets([]).shape_from_size() == Composition([])\n True\n sage: D = OrderedMultisetPartitionIntoSets([['a', 'b'], ['a']]); D\n [{'a','b'}, {'a'}]\n sage: D.shape_from_size() == None\n True\n " if (self._n is not None): return Composition([sum(k) for k in self]) def letters(self): '\n Return the set of distinct elements occurring within the blocks\n of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.letters()\n frozenset({1, 2, 3, 4, 7})\n ' return _union_of_sets(list(self)) def multiset(self, as_dict=False): '\n Return the multiset corresponding to ``self``.\n\n INPUT:\n\n - ``as_dict`` -- (default: ``False``) whether to return the multiset\n as a tuple of a dict of multiplicities\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.multiset()\n (1, 1, 2, 2, 3, 3, 4, 7)\n sage: C.multiset(as_dict=True)\n {1: 2, 2: 2, 3: 2, 4: 1, 7: 1}\n sage: OrderedMultisetPartitionIntoSets([]).multiset() == ()\n True\n ' if as_dict: return self._weight else: return self._multiset def max_letter(self): "\n Return the maximum letter appearing in ``self.letters()`` of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]])\n sage: C.max_letter()\n 7\n sage: D = OrderedMultisetPartitionIntoSets([['a','b','c'],['a','b'],['a'],['b','c','f'],['c','d']])\n sage: D.max_letter()\n 'f'\n sage: C = OrderedMultisetPartitionIntoSets([])\n sage: C.max_letter()\n " if (not self.letters()): return None else: return max(self.letters()) def size(self): "\n Return the size of ``self`` (that is, the sum of all integers in\n all blocks) if ``self`` is a list of subsets of positive integers.\n\n Else, return ``None``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.size()\n 23\n sage: C.size() == sum(k for k in C.shape_from_size())\n True\n sage: OrderedMultisetPartitionIntoSets([[7,1],[3]]).size()\n 11\n\n TESTS::\n\n sage: OrderedMultisetPartitionIntoSets([]).size() == 0\n True\n sage: OrderedMultisetPartitionIntoSets([['a','b'],['a','b','c']]).size() is None\n True\n " return self._n def order(self): '\n Return the total number of elements in all blocks of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3, 4, 1], [2], [1, 2, 3, 7]]); C\n [{1,3,4}, {2}, {1,2,3,7}]\n sage: C.order()\n 8\n sage: C.order() == sum(C.weight().values())\n True\n sage: C.order() == sum(k for k in C.shape_from_cardinality())\n True\n sage: OrderedMultisetPartitionIntoSets([[7,1],[3]]).order()\n 3\n ' return self._order def length(self): '\n Return the number of blocks of ``self``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[7,1],[3]]).length()\n 2\n ' return len(self) def weight(self, as_weak_comp=False): "\n Return a dictionary, with keys being the letters in ``self.letters()``\n and values being their (positive) frequency.\n\n Alternatively, if ``as_weak_comp`` is ``True``, count the number of instances\n `n_i` for each distinct positive integer `i` across all blocks of ``self``.\n Return as a list `[n_1, n_2, n_3, ..., n_k]`, where `k` is the max letter\n appearing in ``self.letters()``.\n\n EXAMPLES::\n\n sage: c = OrderedMultisetPartitionIntoSets([[6,1],[1,3],[1,3,6]])\n sage: c.weight()\n {1: 3, 3: 2, 6: 2}\n sage: c.weight(as_weak_comp=True)\n [3, 0, 2, 0, 0, 2]\n\n TESTS::\n\n sage: OrderedMultisetPartitionIntoSets([]).weight() == {}\n True\n\n sage: c = OrderedMultisetPartitionIntoSets([['a','b'],['a','b','c'],['b'],['b'],['c']])\n sage: c.weight()\n {'a': 2, 'b': 4, 'c': 2}\n sage: c.weight(as_weak_comp=True)\n Traceback (most recent call last):\n ...\n ValueError: {'a': 2, 'b': 4, 'c': 2} is not a numeric multiset\n " from pprint import pformat w = self._weight if as_weak_comp: if all(((v in ZZ) for v in w)): w = [w.get(i, 0) for i in range(1, (self.max_letter() + 1))] else: raise ValueError(('%s is not a numeric multiset' % pformat(w))) return w def deconcatenate(self, k=2): "\n Return the list of `k`-deconcatenations of ``self``.\n\n A `k`-tuple `(C_1, \\ldots, C_k)` of ordered multiset partitions into sets\n represents a `k`-deconcatenation of an ordered multiset partition into sets\n `C` if `C_1 + \\cdots + C_k = C`.\n\n .. NOTE::\n\n This is not to be confused with ``self.split_blocks()``,\n which splits each block of ``self`` before making `k`-tuples\n of ordered multiset partitions into sets.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[7,1],[3,4,5]]).deconcatenate()\n [([{1,7}, {3,4,5}], []), ([{1,7}], [{3,4,5}]), ([], [{1,7}, {3,4,5}])]\n sage: OrderedMultisetPartitionIntoSets([['b','c'],['a']]).deconcatenate()\n [([{'b','c'}, {'a'}], []), ([{'b','c'}], [{'a'}]), ([], [{'b','c'}, {'a'}])]\n sage: OrderedMultisetPartitionIntoSets([['a','b','c']]).deconcatenate(3)\n [([{'a','b','c'}], [], []),\n ([], [{'a','b','c'}], []),\n ([], [], [{'a','b','c'}])]\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionIntoSets([['a'],['b'],['c'],['d'],['e']]); C\n [{'a'}, {'b'}, {'c'}, {'d'}, {'e'}]\n sage: all( len(C.deconcatenate(k))\n ....: == binomial(C.length() + k-1, k-1)\n ....: for k in range(1, 5) )\n True\n " P = OrderedMultisetPartitionsIntoSets(alphabet=self.letters(), max_length=self.length()) out = [] for c in IntegerListsLex(self.length(), length=k): ps = [sum(c[:i]) for i in range((k + 1))] out.append(tuple([P(self[ps[i]:ps[(i + 1)]]) for i in range((len(ps) - 1))])) return out def split_blocks(self, k=2): '\n Return a dictionary representing the `k`-splittings of ``self``.\n\n A `k`-tuple `(A^1, \\ldots, A^k)` of ordered multiset partitions into sets\n represents a `k`-splitting of an ordered multiset partition into sets\n `A = [b_1, \\ldots, b_r]` if one can express each block `b_i` as\n an (ordered) disjoint union of sets `b_i = b^1_i \\sqcup \\cdots\n \\sqcup b^k_i` (some possibly empty) so that each `A^j` is the\n ordered multiset partition into sets corresponding to the list `[b^j_1,\n b^j_2, \\ldots, b^j_r]`, excising empty sets appearing therein.\n\n This operation represents the coproduct in Hopf algebra of ordered\n multiset partitions into sets in its natural basis [LM2018]_.\n\n EXAMPLES::\n\n sage: sorted(OrderedMultisetPartitionIntoSets([[1,2],[3,4]]).split_blocks(), key=str)\n [([], [{1,2}, {3,4}]),\n ([{1,2}, {3,4}], []),\n ([{1,2}, {3}], [{4}]),\n ([{1,2}, {4}], [{3}]),\n ([{1,2}], [{3,4}]),\n ([{1}, {3,4}], [{2}]),\n ([{1}, {3}], [{2}, {4}]),\n ([{1}, {4}], [{2}, {3}]),\n ([{1}], [{2}, {3,4}]),\n ([{2}, {3,4}], [{1}]),\n ([{2}, {3}], [{1}, {4}]),\n ([{2}, {4}], [{1}, {3}]),\n ([{2}], [{1}, {3,4}]),\n ([{3,4}], [{1,2}]),\n ([{3}], [{1,2}, {4}]),\n ([{4}], [{1,2}, {3}])]\n sage: sorted(OrderedMultisetPartitionIntoSets([[1,2]]).split_blocks(3), key=str)\n [([], [], [{1,2}]), ([], [{1,2}], []), ([], [{1}], [{2}]),\n ([], [{2}], [{1}]), ([{1,2}], [], []), ([{1}], [], [{2}]),\n ([{1}], [{2}], []), ([{2}], [], [{1}]), ([{2}], [{1}], [])]\n sage: OrderedMultisetPartitionIntoSets([[4],[4]]).split_blocks()\n {([], [{4}, {4}]): 1, ([{4}], [{4}]): 2, ([{4}, {4}], []): 1}\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionIntoSets([[1,2],[4,5,6]]); C\n [{1,2}, {4,5,6}]\n sage: sum(C.split_blocks().values()) == 2**len(C[0]) * 2**len(C[1])\n True\n sage: sum(C.split_blocks(3).values()) == (1+2)**len(C[0]) * (1+2)**len(C[1])\n True\n sage: C = OrderedMultisetPartitionIntoSets([])\n sage: C.split_blocks(3) == {(C, C, C): 1}\n True\n ' P = OrderedMultisetPartitionsIntoSets(alphabet=self.letters(), max_length=self.length()) if (not self): return {tuple(([self] * k)): 1} out = {} for t in product(*[_split_block(block, k) for block in self]): tt = tuple([P([l for l in c if l]) for c in zip(*t)]) out[tt] = (out.get(tt, 0) + 1) return out def finer(self, strong=False): "\n Return the set of ordered multiset partitions into sets that are finer\n than ``self``.\n\n An ordered multiset partition into sets `A` is finer than another `B`\n if, reading left-to-right, every block of `B` is the union of some\n consecutive blocks of `A`.\n\n If optional argument ``strong`` is set to ``True``, then return\n only those `A` whose blocks are deconcatenations of blocks of `B`.\n (Here, we view blocks of `B` as sorted lists instead of sets.)\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[3,2]]).finer()\n sage: len(C)\n 3\n sage: sorted(C, key=str)\n [[{2,3}], [{2}, {3}], [{3}, {2}]]\n sage: OrderedMultisetPartitionIntoSets([]).finer()\n {[]}\n sage: O = OrderedMultisetPartitionsIntoSets([1, 1, 'a', 'b'])\n sage: o = O([{1}, {'a', 'b'}, {1}])\n sage: sorted(o.finer(), key=str)\n [[{1}, {'a','b'}, {1}], [{1}, {'a'}, {'b'}, {1}], [{1}, {'b'}, {'a'}, {1}]]\n sage: o.finer() & o.fatter() == set([o])\n True\n " P = OrderedMultisetPartitionsIntoSets(self._multiset) if (not self): return set([self]) CP = product(*[_refine_block(block, strong) for block in self]) return set((P(_concatenate(map(list, c))) for c in CP)) def is_finer(self, co): '\n Return ``True`` if the ordered multiset partition into sets ``self``\n is finer than the composition ``co``; otherwise, return ``False``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[4],[1],[2]]).is_finer([[1,4],[2]])\n True\n sage: OrderedMultisetPartitionIntoSets([[1],[4],[2]]).is_finer([[1,4],[2]])\n True\n sage: OrderedMultisetPartitionIntoSets([[1,4],[1],[1]]).is_finer([[1,4],[2]])\n False\n ' X = _concatenate(co) if (self.weight() != OrderedMultisetPartitionsIntoSets(_get_weight(X))(co).weight()): return False co1 = list(map(set, self)) co2 = list(map(set, co)) while (co1[0] == co2[0]): co1 = co1[1:] co2 = co2[1:] while (co1[(- 1)] == co2[(- 1)]): co1 = co1[:(- 1)] co2 = co2[:(- 1)] co1 = OrderedMultisetPartitionIntoSets(co1) co2 = OrderedMultisetPartitionIntoSets(co2) return (co1 in co2.finer()) def fatten(self, grouping): '\n Return the ordered multiset partition into sets fatter than ``self``,\n obtained by grouping together consecutive parts according to ``grouping``\n (whenever this does not violate the strictness condition).\n\n INPUT:\n\n - ``grouping`` -- a composition (or list) whose sum is the length\n of ``self``\n\n EXAMPLES:\n\n Let us start with the composition::\n\n sage: C = OrderedMultisetPartitionIntoSets([[4,1,5], [2], [7,1]]); C\n [{1,4,5}, {2}, {1,7}]\n\n With ``grouping`` equal to `(1, 1, 1)`, `C` is left unchanged::\n\n sage: C.fatten([1,1,1])\n [{1,4,5}, {2}, {1,7}]\n\n With ``grouping`` equal to `(2,1)` or `(1,2)`, a union of consecutive\n parts is achieved::\n\n sage: C.fatten([2,1])\n [{1,2,4,5}, {1,7}]\n sage: C.fatten([1,2])\n [{1,4,5}, {1,2,7}]\n\n However, the ``grouping`` `(3)` will throw an error, as `1` cannot\n appear twice in any block of ``C``::\n\n sage: C.fatten(Composition([3]))\n Traceback (most recent call last):\n ...\n ValueError: [{1,4,5,2,1,7}] is not a valid ordered multiset partition into sets\n ' if (sum(list(grouping)) != self.length()): raise ValueError(('%s is not a composition of ``self.length()`` (=%s)' % (grouping, self.length()))) valid = True result = [] for i in range(len(grouping)): result_i = self[sum(grouping[:i]):sum(grouping[:(i + 1)])] strict_size = sum(map(len, result_i)) size = len(_union_of_sets(result_i)) if (size < strict_size): valid = False result.append(_concatenate(result_i)) if (not valid): str_rep = '[' for i in range(len(grouping)): st = ','.join((str(k) for k in result[i])) str_rep += (('{' + st) + '}') str_rep = (str_rep.replace('}{', '}, {') + ']') raise ValueError(('%s is not a valid ordered multiset partition into sets' % str_rep)) else: return OrderedMultisetPartitionsIntoSets(self._multiset)(result) def fatter(self): "\n Return the set of ordered multiset partitions into sets which are fatter\n than ``self``.\n\n An ordered multiset partition into sets `A` is fatter than another `B`\n if, reading left-to-right, every block of `A` is the union of some\n consecutive blocks of `B`.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([{1,4,5}, {2}, {1,7}]).fatter()\n sage: len(C)\n 3\n sage: sorted(C)\n [[{1,4,5}, {2}, {1,7}], [{1,4,5}, {1,2,7}], [{1,2,4,5}, {1,7}]]\n sage: sorted(OrderedMultisetPartitionIntoSets([['a','b'],['c'],['a']]).fatter())\n [[{'a','b'}, {'c'}, {'a'}], [{'a','b'}, {'a','c'}], [{'a','b','c'}, {'a'}]]\n\n Some extreme cases::\n\n sage: list(OrderedMultisetPartitionIntoSets([['a','b','c']]).fatter())\n [[{'a','b','c'}]]\n sage: list(OrderedMultisetPartitionIntoSets([]).fatter())\n [[]]\n sage: A = OrderedMultisetPartitionIntoSets([[1], [2], [3], [4]])\n sage: B = OrderedMultisetPartitionIntoSets([[1,2,3,4]])\n sage: A.fatter().issubset(B.finer())\n True\n " out = set() for c in composition_iterator_fast(self.length()): try: out.add(self.fatten(c)) except ValueError: pass return out def minimaj(self): "\n Return the minimaj statistic on ordered multiset partitions into sets.\n\n We define `minimaj` via an example:\n\n 1. Sort the block in ``self`` as prescribed by ``self.minimaj_word()``,\n keeping track of the original separation into blocks::\n\n in: [{1,5,7}, {2,4}, {5,6}, {4,6,8}, {1,3}, {1,2,3}]\n out: ( 5,7,1 / 2,4 / 5,6 / 4,6,8 / 3,1 / 1,2,3 )\n\n 2. Record the indices where descents in this word occur::\n\n word: (5, 7, 1 / 2, 4 / 5, 6 / 4, 6, 8 / 3, 1 / 1, 2, 3)\n indices: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n descents: { 2, 7, 10, 11 }\n\n 3. Compute the sum of the descents::\n\n minimaj = 2 + 7 + 10 + 11 = 30\n\n REFERENCES:\n\n - [HRW2015]_\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([{1,5,7}, {2,4}, {5,6}, {4,6,8}, {1,3}, {1,2,3}])\n sage: C, C.minimaj_word()\n ([{1,5,7}, {2,4}, {5,6}, {4,6,8}, {1,3}, {1,2,3}],\n (5, 7, 1, 2, 4, 5, 6, 4, 6, 8, 3, 1, 1, 2, 3))\n sage: C.minimaj()\n 30\n sage: C = OrderedMultisetPartitionIntoSets([{2,4}, {1,2,3}, {1,6,8}, {2,3}])\n sage: C, C.minimaj_word()\n ([{2,4}, {1,2,3}, {1,6,8}, {2,3}], (2, 4, 1, 2, 3, 6, 8, 1, 2, 3))\n sage: C.minimaj()\n 9\n sage: OrderedMultisetPartitionIntoSets([]).minimaj()\n 0\n sage: C = OrderedMultisetPartitionIntoSets([['b','d'],['a','b','c'],['b']])\n sage: C, C.minimaj_word()\n ([{'b','d'}, {'a','b','c'}, {'b'}], ('d', 'b', 'c', 'a', 'b', 'b'))\n sage: C.minimaj()\n 4\n " D = _descents(self.minimaj_word()) return (sum(D) + len(D)) def minimaj_word(self): '\n Return an ordering of ``self._multiset`` derived from the minimaj\n ordering on blocks of ``self``.\n\n .. SEEALSO::\n\n :meth:`OrderedMultisetPartitionIntoSets.minimaj_blocks()`.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([[2,1], [1,2,3], [1,2], [3], [1]]); C\n [{1,2}, {1,2,3}, {1,2}, {3}, {1}]\n sage: C.minimaj_blocks()\n ((1, 2), (2, 3, 1), (1, 2), (3,), (1,))\n sage: C.minimaj_word()\n (1, 2, 2, 3, 1, 1, 2, 3, 1)\n ' return _concatenate(self.minimaj_blocks()) def minimaj_blocks(self): '\n Return the minimaj ordering on blocks of ``self``.\n\n We define the ordering via the example below.\n\n Sort the blocks `[B_1,...,B_k]` of ``self`` from right to left via:\n\n 1. Sort the last block `B_k` in increasing order, call it the word `W_k`\n\n 2. If blocks `B_{i+1}, \\ldots, B_k` have been converted to words\n `W_{i+1}, \\ldots, W_k`, use the letters in `B_i` to make the unique\n word `W_i` that has a factorization `W_i = (u, v)` satisfying:\n\n - letters of `u` and `v` appear in increasing order, with `v`\n possibly empty;\n - letters in `vu` appear in increasing order;\n - ``v[-1]`` is the largest letter `a \\in B_i` satisfying\n ``a <= W_{i+1}[0]``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionIntoSets([[1,5,7], [2,4], [5,6], [4,6,8], [1,3], [1,2,3]])\n [{1,5,7}, {2,4}, {5,6}, {4,6,8}, {1,3}, {1,2,3}]\n sage: _.minimaj_blocks()\n ((5, 7, 1), (2, 4), (5, 6), (4, 6, 8), (3, 1), (1, 2, 3))\n sage: OrderedMultisetPartitionIntoSets([]).minimaj_blocks()\n ()\n ' if (not self): return () C = [sorted(self[(- 1)])] for i in range(1, len(self)): lower = [] upper = [] for j in self[((- 1) - i)]: if (j <= C[0][0]): lower.append(j) else: upper.append(j) C = ([(sorted(upper) + sorted(lower))] + C) return tuple(map(tuple, C)) def to_tableaux_words(self): '\n Return a sequence of lists corresponding to row words\n of (skew-)tableaux.\n\n OUTPUT:\n\n The minimaj bijection `\\phi` of [BCHOPSY2017]_\n applied to ``self``.\n\n .. TODO::\n\n Implement option for mapping to sequence of (skew-)tableaux?\n\n EXAMPLES::\n\n sage: co = ((1,2,4),(4,5),(3,),(4,6,1),(2,3,1),(1,),(2,5))\n sage: OrderedMultisetPartitionIntoSets(co).to_tableaux_words()\n [[5, 1], [3, 1], [6], [5, 4, 2], [1, 4, 3, 4, 2, 1, 2]]\n ' if (not self): return [] bb = self.minimaj_blocks() b = [block[0] for block in bb] beginning = ([0] + running_total(self.shape_from_cardinality())) w = _concatenate(bb) D = (([0] + _descents(w)) + [len(w)]) pieces = [b] for i in range((len(D) - 1)): p = [w[j] for j in range((D[i] + 1), (D[(i + 1)] + 1)) if (j not in beginning)] pieces = ([p[::(- 1)]] + pieces) return pieces def major_index(self): '\n Return the major index of ``self``.\n\n The major index is a statistic on ordered multiset partitions into sets,\n which we define here via an example.\n\n 1. Sort each block in the list ``self`` in descending order to create\n a word `w`, keeping track of the original separation into blocks::\n\n in: [{3,4,5}, {2,3,4}, {1}, {4,5}]\n out: [ 5,4,3 / 4,3,2 / 1 / 5,4 ]\n\n 2. Create a sequence `v = (v_0, v_1, v_2, \\ldots)` of length\n ``self.order()+1``, built recursively by:\n\n 1. `v_0 = 0`\n 2. `v_j = v_{j-1} + \\delta(j)`, where `\\delta(j) = 1` if `j` is\n the index of an end of a block, and zero otherwise.\n\n ::\n\n in: [ 5,4,3 / 4,3,2 / 1 / 5,4]\n out: (0, 0,0,1, 1,1,2, 3, 3,4)\n\n 3. Compute `\\sum_j v_j`, restricted to descent positions in `w`, i.e.,\n sum over those `j` with `w_j > w_{j+1}`::\n\n in: w: [5, 4, 3, 4, 3, 2, 1, 5, 4]\n v: (0 0, 0, 1, 1, 1, 2, 3, 3, 4)\n maj := 0 +0 +1 +1 +2 +3 = 7\n\n REFERENCES:\n\n - [HRW2015]_\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionIntoSets([{1,5,7}, {2,4}, {5,6}, {4,6,8}, {1,3}, {1,2,3}])\n sage: C.major_index()\n 27\n sage: C = OrderedMultisetPartitionIntoSets([{3,4,5}, {2,3,4}, {1}, {4,5}])\n sage: C.major_index()\n 7\n ' ew = [enumerate(sorted(k)) for k in self] w = [] v = [0] for eblock in ew: for (i, wj) in sorted(eblock, reverse=True): vj = v[(- 1)] if (i == 0): vj += 1 v.append(vj) w.append(wj) maj = [v[(j + 1)] for j in range((len(w) - 1)) if (w[j] > w[(j + 1)])] return sum(maj) def shuffle_product(self, other, overlap=False): '\n Return the shuffles (with multiplicity) of blocks of ``self``\n with blocks of ``other``.\n\n In case optional argument ``overlap`` is ``True``, instead return\n the allowable overlapping shuffles. An overlapping shuffle `C` is\n allowable if, whenever one of its blocks `c` comes from the union\n `c = a \\cup b` of a block of ``self`` and a block of ``other``,\n then this union is disjoint.\n\n .. SEEALSO::\n\n :meth:`Composition.shuffle_product()`\n\n EXAMPLES::\n\n sage: A = OrderedMultisetPartitionIntoSets([[2,1,3], [1,2]]); A\n [{1,2,3}, {1,2}]\n sage: B = OrderedMultisetPartitionIntoSets([[3,4]]); B\n [{3,4}]\n sage: C = OrderedMultisetPartitionIntoSets([[4,5]]); C\n [{4,5}]\n sage: list(A.shuffle_product(B))\n [[{1,2,3}, {1,2}, {3,4}], [{3,4}, {1,2,3}, {1,2}], [{1,2,3}, {3,4}, {1,2}]]\n sage: list(A.shuffle_product(B, overlap=True))\n [[{1,2,3}, {1,2}, {3,4}], [{1,2,3}, {3,4}, {1,2}],\n [{3,4}, {1,2,3}, {1,2}], [{1,2,3}, {1,2,3,4}]]\n sage: list(A.shuffle_product(C, overlap=True))\n [[{1,2,3}, {1,2}, {4,5}], [{1,2,3}, {4,5}, {1,2}], [{4,5}, {1,2,3}, {1,2}],\n [{1,2,3,4,5}, {1,2}], [{1,2,3}, {1,2,4,5}]]\n ' other = OrderedMultisetPartitionIntoSets(other) P = OrderedMultisetPartitionsIntoSets((self._multiset + other._multiset)) if (not overlap): for term in ShuffleProduct(self, other, element_constructor=P): (yield term) else: A = list(map(tuple, self)) B = list(map(tuple, other)) for term in ShuffleProduct_overlapping(A, B): if (len(_concatenate(map(frozenset, term))) == len(P._Xtup)): (yield P(term))
class OrderedMultisetPartitionsIntoSets(UniqueRepresentation, Parent): "\n Ordered Multiset Partitions into Sets.\n\n An *ordered multiset partition into sets* `c` of a multiset `X` is\n a list of nonempty subsets (not multisets), called the *blocks* of `c`,\n whose multi-union is `X`.\n\n The number of blocks of `c` is called its *length*. The *order* of `c`\n is the cardinality of the multiset `X`. If, additionally, `X` is a\n multiset of positive integers, then the *size* of `c` is the sum of\n all elements of `X`.\n\n The user may wish to focus on ordered multiset partitions into sets\n of a given size, or over a given alphabet. Hence, this class allows\n a variety of arguments as input.\n\n INPUT:\n\n Expects one or two arguments, with different behaviors resulting:\n\n - One Argument:\n\n + `X` -- a dictionary or list or tuple\n (representing a multiset for `c`),\n or an integer (representing the size of `c`)\n\n - Two Arguments:\n\n + `A` -- a list (representing allowable letters within blocks of `c`),\n or a positive integer (representing the maximal allowable letter)\n + `n` -- a nonnegative integer (the total number of letters within `c`)\n\n Optional keyword arguments are as follows:\n (See corresponding methods in see :class:`OrderedMultisetPartitionIntoSets` for more details.)\n\n - ``weight=X`` (list or dictionary `X`) specifies the multiset for `c`\n - ``size=n`` (integer `n`) specifies the size of `c`\n - ``alphabet=A`` (iterable `A`) specifies allowable elements for the blocks of `c`\n - ``length=k`` (integer `k`) specifies the number of blocks in the partition\n - ``min_length=k`` (integer `k`) specifies minimum number of blocks in the partition\n - ``max_length=k`` (integer `k`) specifies maximum number of blocks in the partition\n - ``order=n`` (integer `n`) specifies the cardinality of the multiset that `c` partitions\n - ``min_order=n`` (integer `n`) specifies minimum number of elements in the partition\n - ``max_order=n`` (integer `n`) specifies maximum number of elements in the partition\n\n EXAMPLES:\n\n Passing one argument to :class:`OrderedMultisetPartitionsIntoSets`:\n\n There are 5 ordered multiset partitions into sets of the multiset\n `\\{\\{1, 1, 4\\}\\}`::\n\n sage: OrderedMultisetPartitionsIntoSets([1,1,4]).cardinality()\n 5\n\n Here is the list of them::\n\n sage: OrderedMultisetPartitionsIntoSets([1,1,4]).list()\n [[{1}, {1}, {4}], [{1}, {1,4}], [{1}, {4}, {1}], [{1,4}, {1}], [{4}, {1}, {1}]]\n\n By chance, there are also 5 ordered multiset partitions into sets of\n the integer 3::\n\n sage: OrderedMultisetPartitionsIntoSets(3).cardinality()\n 5\n\n Here is the list of them::\n\n sage: OrderedMultisetPartitionsIntoSets(3).list()\n [[{3}], [{1,2}], [{2}, {1}], [{1}, {2}], [{1}, {1}, {1}]]\n\n Passing two arguments to :class:`OrderedMultisetPartitionsIntoSets`:\n\n There are also 5 ordered multiset partitions into sets of order 2\n over the alphabet `\\{1, 4\\}`::\n\n sage: OrderedMultisetPartitionsIntoSets([1, 4], 2)\n Ordered Multiset Partitions into Sets of order 2 over alphabet {1, 4}\n sage: OrderedMultisetPartitionsIntoSets([1, 4], 2).cardinality()\n 5\n\n Here is the list of them::\n\n sage: OrderedMultisetPartitionsIntoSets([1, 4], 2).list()\n [[{1,4}], [{1}, {1}], [{1}, {4}], [{4}, {1}], [{4}, {4}]]\n\n If no arguments are passed to :class:`OrderedMultisetPartitionsIntoSets`,\n then the code returns all ordered multiset partitions into sets::\n\n sage: OrderedMultisetPartitionsIntoSets()\n Ordered Multiset Partitions into Sets\n sage: [] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [[2,3], [1]] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [['a','b'], ['a']] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [[-2,3], [3]] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [[2], [3,3]] in OrderedMultisetPartitionsIntoSets()\n False\n\n The following examples show how to test whether or not an object\n is an ordered multiset partition into sets::\n\n sage: [[3,2],[2]] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [[3,2],[2]] in OrderedMultisetPartitionsIntoSets(7)\n True\n sage: [[3,2],[2]] in OrderedMultisetPartitionsIntoSets([2,2,3])\n True\n sage: [[3,2],[2]] in OrderedMultisetPartitionsIntoSets(5)\n False\n\n .. RUBRIC:: Optional keyword arguments\n\n Passing keyword arguments that are incompatible with required requirements\n results in an error; otherwise, the collection of ordered multiset partitions\n into sets is restricted accordingly:\n\n *The* ``weight`` *keyword:*\n\n This is used to specify which multiset `X` is to be considered,\n if this multiset was not passed as one of the required arguments for\n :class:`OrderedMultisetPartitionsIntoSets`. In principle, it is a dictionary,\n but weak compositions are also allowed. For example, the ordered multiset\n partitions into sets of integer 4 are listed by weight below::\n\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[0,0,0,1])\n Ordered Multiset Partitions into Sets of integer 4 with constraint: weight={4: 1}\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[0,0,0,1]).list()\n [[{4}]]\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[1,0,1]).list()\n [[{1}, {3}], [{1,3}], [{3}, {1}]]\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[0,2]).list()\n [[{2}, {2}]]\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[0,1,1]).list()\n []\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[2,1]).list()\n [[{1}, {1}, {2}], [{1}, {1,2}], [{1}, {2}, {1}], [{1,2}, {1}], [{2}, {1}, {1}]]\n sage: O1 = OrderedMultisetPartitionsIntoSets(weight=[2,0,1])\n sage: O2 = OrderedMultisetPartitionsIntoSets(weight={1:2, 3:1})\n sage: O1 == O2\n True\n sage: OrderedMultisetPartitionsIntoSets(4, weight=[4]).list()\n [[{1}, {1}, {1}, {1}]]\n\n *The* ``size`` *keyword:*\n\n This is used to constrain the sum of entries across all blocks of the ordered\n multiset partition into sets. (This size is not pre-determined when alphabet\n `A` and order `d` are passed as required arguments.) For example, the ordered\n multiset partitions into sets of order 3 over the alphabet `[1,2,4]` that have\n size equal to 5 are as follows::\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets\n sage: OMPs([1,2,4], 3, size=5).list()\n [[{1,2}, {2}], [{2}, {1,2}], [{2}, {2}, {1}],\n [{2}, {1}, {2}], [{1}, {2}, {2}]]\n\n *The* ``alphabet`` *option:*\n\n This is used to constrain which integers appear across all blocks of the\n ordered multiset partition into sets. For example, the ordered multiset\n partitions into sets of integer 4 are listed for different choices of alphabet\n below. Note that ``alphabet`` is allowed to be an integer or an iterable::\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets\n sage: OMPs(4, alphabet=3).list()\n [[{1,3}], [{3}, {1}],\n [{1,2}, {1}], [{2}, {2}],\n [{2}, {1}, {1}], [{1}, {3}],\n [{1}, {1,2}], [{1}, {2}, {1}],\n [{1}, {1}, {2}], [{1}, {1}, {1}, {1}]]\n sage: OMPs(4, alphabet=3) == OMPs(4, alphabet=[1,2,3])\n True\n sage: OMPs(4, alphabet=[3]).list()\n []\n sage: OMPs(4, alphabet=[1,3]).list()\n [[{1,3}], [{3}, {1}], [{1}, {3}], [{1}, {1}, {1}, {1}]]\n sage: OMPs(4, alphabet=[2]).list()\n [[{2}, {2}]]\n sage: OMPs(4, alphabet=[1,2]).list()\n [[{1,2}, {1}], [{2}, {2}], [{2}, {1}, {1}], [{1}, {1,2}],\n [{1}, {2}, {1}], [{1}, {1}, {2}], [{1}, {1}, {1}, {1}]]\n sage: OMPs(4, alphabet=4).list() == OMPs(4).list()\n True\n\n *The* ``length``, ``min_length``, *and* ``max_length`` *options:*\n\n These are used to constrain the number of blocks within the ordered multiset\n partitions into sets. For example, the ordered multiset partitions into sets\n of integer 4 of length exactly 2, at least 2, and at most 2 are given by::\n\n sage: OrderedMultisetPartitionsIntoSets(4, length=2).list()\n [[{3}, {1}], [{1,2}, {1}], [{2}, {2}], [{1}, {3}], [{1}, {1,2}]]\n sage: OrderedMultisetPartitionsIntoSets(4, min_length=3).list()\n [[{2}, {1}, {1}], [{1}, {2}, {1}], [{1}, {1}, {2}], [{1}, {1}, {1}, {1}]]\n sage: OrderedMultisetPartitionsIntoSets(4, max_length=2).list()\n [[{4}], [{1,3}], [{3}, {1}], [{1,2}, {1}], [{2}, {2}], [{1}, {3}],\n [{1}, {1,2}]]\n\n *The* ``order``, ``min_order``, *and* ``max_order`` *options:*\n\n These are used to constrain the number of elements across all blocks of the\n ordered multiset partitions into sets. For example, the ordered multiset\n partitions into sets of integer 4 are listed by order below::\n\n sage: OrderedMultisetPartitionsIntoSets(4, order=1).list()\n [[{4}]]\n sage: OrderedMultisetPartitionsIntoSets(4, order=2).list()\n [[{1,3}], [{3}, {1}], [{2}, {2}], [{1}, {3}]]\n sage: OrderedMultisetPartitionsIntoSets(4, order=3).list()\n [[{1,2}, {1}], [{2}, {1}, {1}], [{1}, {1,2}], [{1}, {2}, {1}], [{1}, {1}, {2}]]\n sage: OrderedMultisetPartitionsIntoSets(4, order=4).list()\n [[{1}, {1}, {1}, {1}]]\n\n Also, here is a use of ``max_order``, giving the ordered multiset\n partitions into sets of integer 4 with order 1 or 2::\n\n sage: OrderedMultisetPartitionsIntoSets(4, max_order=2).list()\n [[{4}], [{1,3}], [{3}, {1}], [{2}, {2}], [{1}, {3}]]\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets(8, length=3); C.cardinality()\n 72\n sage: TestSuite(C).run()\n " @staticmethod def __classcall_private__(self, *args, **constraints): "\n Return the correct parent based upon the input:\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets()\n Ordered Multiset Partitions into Sets\n sage: OrderedMultisetPartitionsIntoSets(4)\n Ordered Multiset Partitions into Sets of integer 4\n sage: OrderedMultisetPartitionsIntoSets(4, max_order=2)\n Ordered Multiset Partitions into Sets of integer 4 with constraint: max_order=2\n\n sage: OrderedMultisetPartitionsIntoSets({1:2, 3:1})\n Ordered Multiset Partitions into Sets of multiset {{1, 1, 3}}\n sage: OrderedMultisetPartitionsIntoSets({1:2, 3:1}) == OrderedMultisetPartitionsIntoSets([1,1,3])\n True\n sage: OrderedMultisetPartitionsIntoSets({'a':2, 'c':1}, length=2)\n Ordered Multiset Partitions into Sets of multiset {{a, a, c}} with constraint: length=2\n sage: OrderedMultisetPartitionsIntoSets({'a':2, 'c':1}, length=4).list()\n []\n\n sage: OrderedMultisetPartitionsIntoSets(4, 3)\n Ordered Multiset Partitions into Sets of order 3 over alphabet {1, 2, 3, 4}\n sage: OrderedMultisetPartitionsIntoSets(['a', 'd'], 3)\n Ordered Multiset Partitions into Sets of order 3 over alphabet {a, d}\n sage: OrderedMultisetPartitionsIntoSets([2,4], 3, min_length=2)\n Ordered Multiset Partitions into Sets of order 3 over alphabet {2, 4}\n with constraint: min_length=2\n\n TESTS:\n\n The alphabet and order keywords cannot be used if they are also passed\n as required arguments, even if the values are compatible::\n\n sage: OrderedMultisetPartitionsIntoSets([1,2,4], 4, alphabet=[2,4], order=3)\n Traceback (most recent call last):\n ...\n ValueError: cannot pass alphabet as first argument and keyword argument\n sage: OrderedMultisetPartitionsIntoSets([1,2,4], 4, order=4)\n Traceback (most recent call last):\n ...\n ValueError: cannot pass order as second argument and keyword argument\n\n The weight, size, and order keywords cannot be used if a multiset is\n passed as a required argument, even if the values are compatible::\n\n sage: OrderedMultisetPartitionsIntoSets([1,1,4], weight={1:3, 2:1}).list()\n Traceback (most recent call last):\n ...\n ValueError: cannot pass multiset as first argument and weight as keyword argument\n sage: OrderedMultisetPartitionsIntoSets([1,1,4], size=6).list()\n Traceback (most recent call last):\n ...\n ValueError: cannot pass multiset as first argument and size as keyword argument\n sage: OrderedMultisetPartitionsIntoSets([1,1,4], weight={1:3, 2:1}, order=2).list()\n Traceback (most recent call last):\n ...\n ValueError: cannot pass multiset as first argument and ['order', 'weight'] as keyword arguments\n\n The size keyword cannot be used if it is also passed as a required argument,\n even if the value is compatible::\n\n sage: OrderedMultisetPartitionsIntoSets(5, size=5)\n Traceback (most recent call last):\n ...\n ValueError: cannot pass size as first argument and keyword argument\n " constraints = dict(constraints) if ('weight' in constraints): w = constraints['weight'] if (not isinstance(w, dict)): if ((len(w) > 0) and isinstance(w[0], (list, tuple))): w = dict(w) else: w = {(i + 1): w[i] for i in range(len(w)) if (w[i] > 0)} if (not all((((a in ZZ) and (a > 0)) for a in w.values()))): raise ValueError(('%s must be a dictionary of letter-frequencies or a weak composition' % w)) else: constraints['weight'] = tuple(w.items()) if ('alphabet' in constraints): A = constraints['alphabet'] if (A in ZZ): A = range(1, (A + 1)) constraints['alphabet'] = frozenset(A) if (len(args) == 2): alph = args[0] order = args[1] if (alph in ZZ): alph = range(1, (alph + 1)) if ((alph and (len(set(alph)) == len(alph))) and ((order in ZZ) and (order >= 0))): if ('alphabet' in constraints): raise ValueError('cannot pass alphabet as first argument and keyword argument') elif ('order' in constraints): raise ValueError('cannot pass order as second argument and keyword argument') if (constraints == {}): return OrderedMultisetPartitionsIntoSets_alph_d(frozenset(alph), order) else: return OrderedMultisetPartitionsIntoSets_alph_d_constraints(frozenset(alph), order, **constraints) elif ((frozenset(alph) == frozenset()) and (order == 0)): return OrderedMultisetPartitionsIntoSets_alph_d_constraints(frozenset(alph), order, **constraints) else: raise ValueError(('alphabet=%s must be a nonempty set and order=%s must be a nonnegative integer' % (alph, order))) elif (len(args) == 1): X = args[0] if isinstance(X, (list, tuple)): tmp = {} for i in X: tmp[i] = (tmp.get(i, 0) + 1) X = tmp if isinstance(X, dict): over_determined = set(['size', 'weight', 'alphabet', 'order', 'min_order', 'max_order']).intersection(set(constraints)) if over_determined: if (len(over_determined) > 1): suff = 's' offenses = str(sorted(over_determined)) else: suff = '' offenses = str(over_determined.pop()) raise ValueError(('cannot pass multiset as first argument and %s as keyword argument%s' % (offenses, suff))) X_items = tuple(X.items()) if (constraints == {}): return OrderedMultisetPartitionsIntoSets_X(X_items) else: return OrderedMultisetPartitionsIntoSets_X_constraints(X_items, **constraints) elif ((X in ZZ) and (X >= 0)): if ('size' in constraints): raise ValueError('cannot pass size as first argument and keyword argument') if (constraints == {}): return OrderedMultisetPartitionsIntoSets_n(X) else: return OrderedMultisetPartitionsIntoSets_n_constraints(X, **constraints) else: raise ValueError(('%s must be a nonnegative integer or a list or dictionary representing a multiset' % X)) elif (len(args) > 2): raise ValueError('OrderedMultisetPartitonsIntoSets takes 1, 2, or 3 arguments') else: if ('weight' in constraints): X = constraints.pop('weight') return OrderedMultisetPartitionsIntoSets(dict(X), **constraints) elif ('size' in constraints): n = constraints.pop('size') return OrderedMultisetPartitionsIntoSets(n, **constraints) elif (('alphabet' in constraints) and ('order' in constraints)): A = constraints.pop('alphabet') d = constraints.pop('order') return OrderedMultisetPartitionsIntoSets(A, d, **constraints) return OrderedMultisetPartitionsIntoSets_all_constraints(**constraints) def __init__(self, is_finite=None, **constraints): '\n Initialize ``self``.\n\n TESTS::\n\n sage: c = {"length":4, "max_order":6, "alphabet":[2,4,5,6]}\n sage: OrderedMultisetPartitionsIntoSets(**c).constraints\n {\'alphabet\': frozenset({2, 4, 5, 6}), \'length\': 4, \'max_order\': 6}\n sage: OrderedMultisetPartitionsIntoSets(17, **c).constraints\n {\'alphabet\': frozenset({2, 4, 5, 6}), \'length\': 4, \'max_order\': 6}\n sage: OrderedMultisetPartitionsIntoSets(17, **c).full_constraints\n {\'alphabet\': frozenset({2, 4, 5, 6}), \'length\': 4, \'max_order\': 6, \'size\': 17}\n\n sage: c = {"length":4, "min_length":5, "max_order":6, "order":5, "alphabet":4}\n sage: OrderedMultisetPartitionsIntoSets(**c).full_constraints\n {\'alphabet\': frozenset({1, 2, 3, 4}), \'length\': 4, \'order\': 5}\n sage: OrderedMultisetPartitionsIntoSets(**c).constraints\n {\'length\': 4}\n sage: OrderedMultisetPartitionsIntoSets(4, 5, **c).constraints\n Traceback (most recent call last):\n ...\n ValueError: cannot pass alphabet as first argument and keyword argument\n\n sage: c = {"weight":[2,2,0,3], "min_length":5, "max_order":6, "order":5, "alphabet":4}\n sage: OrderedMultisetPartitionsIntoSets(**c).constraints\n Traceback (most recent call last):\n ...\n ValueError: cannot pass multiset as first argument and [\'alphabet\', \'max_order\', \'order\'] as keyword arguments\n ' constraints = dict(constraints) if ('alphabet' in constraints): if (constraints['alphabet'] in ZZ): constraints['alphabet'] = frozenset(range(1, (constraints['alphabet'] + 1))) else: constraints['alphabet'] = frozenset(constraints['alphabet']) if ('weight' in constraints): X = dict(constraints['weight']) constraints['weight'] = X constraints.pop('alphabet', None) constraints.pop('min_order', None) constraints.pop('order', None) constraints.pop('max_order', None) constraints.pop('size', None) if ('length' in constraints): constraints.pop('min_length', None) constraints.pop('max_length', None) min_k = constraints.get('min_length', 0) max_k = constraints.get('max_length', infinity) assert (min_k <= max_k), ('min_length=%s <= max_length=%s' % (min_k, max_k)) if (min_k == max_k): constraints['length'] = constraints.pop('min_length', constraints.pop('max_length')) if ('order' in constraints): constraints.pop('min_order', None) constraints.pop('max_order', None) min_ord = constraints.get('min_order', 0) max_ord = constraints.get('max_order', infinity) assert (min_ord <= max_ord), ('min_order=%s <= max_order=%s' % (min_ord, max_ord)) if (min_ord == max_ord): constraints['order'] = constraints.pop('min_order', constraints.pop('max_order')) self.constraints = {} for (key, val) in constraints.items(): if val: self.constraints[key] = val elif ((key in ('size', 'order', 'length')) and (val is not None)): self.constraints[key] = val self.full_constraints = dict(self.constraints) if hasattr(self, '_X'): self.full_constraints['weight'] = dict(self._X) self.constraints.pop('weight', None) if hasattr(self, '_n'): self.full_constraints['size'] = self._n self.constraints.pop('size', None) if hasattr(self, '_alphabet'): self.full_constraints['alphabet'] = self._alphabet self.constraints.pop('alphabet', None) self.full_constraints['order'] = self._order self.constraints.pop('order', None) if (is_finite or _is_finite(constraints)): Parent.__init__(self, category=FiniteEnumeratedSets()) else: Parent.__init__(self, category=InfiniteEnumeratedSets()) def _repr_(self): '\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: OrderedMultisetPartitionsIntoSets()\n Ordered Multiset Partitions into Sets\n ' return 'Ordered Multiset Partitions into Sets' def _constraint_repr_(self, cdict=None): '\n Return a string representation of all constraints\n appearing within ``self.constraints``.\n\n A helper method for ``self._repr_()``.\n\n EXAMPLES::\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets()\n sage: c = {"length":4, "max_order":6, "alphabet":frozenset([2,4,5,6])}\n sage: OMPs._constraint_repr_(c)\n \' with constraints: alphabet={2, 4, 5, 6}, length=4, max_order=6\'\n sage: c = {"size":14}\n sage: OMPs._constraint_repr_(c)\n \' with constraint: size=14\'\n ' if (not cdict): cdict = dict(self.constraints) if ('alphabet' in cdict): if (not all(((l in ZZ) for l in cdict['alphabet']))): A = sorted(cdict['alphabet'], key=str) else: A = sorted(cdict['alphabet']) cdict['alphabet'] = (('{' + repr(A)[1:(- 1)]) + '}') constr = '' ss = [('%s=%s' % item) for item in cdict.items()] ss = sorted(ss) if (len(ss) > 1): constr = (' with constraints: ' + ', '.join(ss)) elif (len(ss) == 1): constr = (' with constraint: ' + ', '.join(ss)) return constr def _element_constructor_(self, lst): '\n Construct an element of ``self`` from ``lst``.\n\n EXAMPLES::\n\n sage: P = OrderedMultisetPartitionsIntoSets()\n sage: A = P([[3],[3,1]]) ; A # indirect doctest\n [{3}, {1,3}]\n sage: P1 = OrderedMultisetPartitionsIntoSets(7, alphabet=3)\n sage: A1 = P1([[3],[3,1]]); A1\n [{3}, {1,3}]\n sage: P2 = OrderedMultisetPartitionsIntoSets(alphabet=3)\n sage: A2 = P2([[3],[3,1]]); A2\n [{3}, {1,3}]\n sage: A == A1 == A2\n True\n sage: P = OrderedMultisetPartitionsIntoSets(3)\n sage: P([[3],[3,1]])\n Traceback (most recent call last):\n ...\n ValueError: cannot convert [[3], [3, 1]] into an element of\n Ordered Multiset Partitions into Sets of integer 3\n ' if (not lst): omp = [] else: omp = [list(z) for z in lst] if (omp in self): return self.element_class(self, list(map(frozenset, omp))) else: raise ValueError(('cannot convert %s into an element of %s' % (lst, self))) Element = OrderedMultisetPartitionIntoSets def __contains__(self, x): '\n Return if ``x`` is contained in ``self``.\n\n TESTS::\n\n sage: [[2,1], [1,3]] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [[2,1], [1,3]] in OrderedMultisetPartitionsIntoSets(7)\n True\n sage: [[2,2], [1,3]] in OrderedMultisetPartitionsIntoSets()\n False\n sage: [] in OrderedMultisetPartitionsIntoSets()\n True\n sage: [] in OrderedMultisetPartitionsIntoSets(0)\n True\n sage: [] in OrderedMultisetPartitionsIntoSets(2)\n False\n sage: [[2, 1]] in OrderedMultisetPartitionsIntoSets(3, length=2)\n False\n sage: [[2, -1]] in OrderedMultisetPartitionsIntoSets()\n True\n ' if (not isinstance(x, (OrderedMultisetPartitionIntoSets, list, tuple))): return False return (_has_nonempty_sets(x) and self._satisfies_constraints(x)) def _satisfies_constraints(self, x): '\n Check whether or not ``x`` satisfies all of the constraints\n appearing within ``self.full_constraints`` (Boolean output).\n\n .. NOTE::\n\n This test will cause an infinite recursion with\n ``self._element_constructor_()`` if the ``__contains__``\n method in ``OrderedMultisetPartitionsIntoSets_X`` is removed.\n\n TESTS::\n\n sage: c = {"length":3, "max_order":5, "alphabet":[1,2,4], "size":12}\n sage: OMPs = OrderedMultisetPartitionsIntoSets(**c)\n sage: OMPs._satisfies_constraints([{2,4}, {1}, {1,4}])\n True\n sage: failures = {((2,4), (2,4)), ((1,2,4), (1,), (1,4)),\n ....: ((2,4), (3,), (3,)), ((2,4), (1,), (2,4))}\n sage: any(OMPs._satisfies_constraints(x) for x in failures)\n False\n sage: c = {"max_length":4, "weight":{1:2, 2:1, 4:2}}\n sage: OMPs = OrderedMultisetPartitionsIntoSets(**c)\n sage: OMPs._satisfies_constraints([{2,4}, {1}, {1,4}])\n True\n sage: failures = {((2,), (4,), (1,), (1,), (4,)), ((1,), (1,), (2,4), (2,4))}\n sage: any(OMPs._satisfies_constraints(x) for x in failures)\n False\n ' X = _concatenate(x) P = OrderedMultisetPartitionsIntoSets_X(tuple(_get_weight(X).items())) x = P.element_class(P, [frozenset(block) for block in x]) constr = self.full_constraints tsts = [] if ('size' in constr): tsts.append((x.size() == constr['size'])) if ('weight' in constr): tsts.append((x.weight() == constr['weight'])) if ('alphabet' in constr): tsts.append(frozenset(x.letters()).issubset(constr['alphabet'])) if ('length' in constr): tsts.append((x.length() == constr['length'])) if ('min_length' in constr): tsts.append((x.length() >= constr['min_length'])) if ('max_length' in constr): tsts.append((x.length() <= constr['max_length'])) if ('order' in constr): tsts.append((x.order() == constr['order'])) if ('min_order' in constr): tsts.append((x.order() >= constr['min_order'])) if ('max_order' in constr): tsts.append((x.order() <= constr['max_order'])) return all(tsts) def _from_list(self, lst): "\n Return an ordered multiset partition into sets of singleton blocks, whose\n singletons are the elements ``lst``.\n\n If any of the elements of ``lst`` are zero (or '0'), then use\n these as breaks points for the blocks.\n\n .. SEEALSO::\n\n :meth:`OrderedMultisetPartitionsIntoSets._from_list_with_zeros()`.\n\n INPUT:\n\n - ``lst`` -- an iterable\n\n EXAMPLES::\n\n sage: OMPs = OrderedMultisetPartitionsIntoSets()\n sage: OMPs._from_list([1,4,0,8])\n [{1,4}, {8}]\n sage: OMPs._from_list([1,4,8])\n [{1}, {4}, {8}]\n sage: OMPs._from_list([1,4,8,0]) == OrderedMultisetPartitionIntoSets([[1,4,8]])\n True\n sage: OMPs._from_list('abaa')\n [{'a'}, {'b'}, {'a'}, {'a'}]\n sage: OMPs._from_list('ab0a0a')\n [{'a','b'}, {'a'}, {'a'}]\n\n TESTS::\n\n sage: OMPs._from_list([1,0,2,3,1]) == OrderedMultisetPartitionIntoSets([[1], [2,3,1]])\n True\n sage: OMPs._from_list([1,2,'3',0,1]) == OrderedMultisetPartitionIntoSets([{1,2,'3'}, [1]])\n True\n " if (all(((a in ZZ) for a in lst)) and any(((a < 0) for a in lst))): raise ValueError('`_from_list` does not expect to see negative integers; received {}'.format(str(lst))) if ((0 in list(lst)) or ('0' in list(lst))): return self._from_list_with_zeros(lst) d = [frozenset([x]) for x in lst] c = self.element_class(self, d) if isinstance(self, OrderedMultisetPartitionsIntoSets_all_constraints): P = OrderedMultisetPartitionsIntoSets(_get_weight(lst)) return P.element_class(P, c) else: return self.element_class(self, c) def _from_list_with_zeros(self, lst_with_zeros): "\n Return an ordered multiset partition into sets from a list of nonnegative\n integers (or their string equivalents).\n\n Blocks are separated by zeros. Consecutive zeros are ignored.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets()._from_list([1,2,4])\n [{1}, {2}, {4}]\n sage: OrderedMultisetPartitionsIntoSets()._from_list_with_zeros([1,2,4])\n [{1,2,4}]\n sage: OrderedMultisetPartitionsIntoSets()._from_list_with_zeros([1,0,2,0,0,4])\n [{1}, {2}, {4}]\n sage: OrderedMultisetPartitionsIntoSets()._from_list_with_zeros('abc00a0b')\n [{'a','b','c'}, {'a'}, {'b'}]\n " from_zero_lst = list(lst_with_zeros) if (from_zero_lst[(- 1)] not in {0, '0'}): from_zero_lst += [0] co = [] block = [] for a in from_zero_lst: if (a in {0, '0'}): if block: co.append(block) block = [] else: block.append(a) if (co in self): c = self.element_class(self, map(frozenset, co)) if isinstance(self, OrderedMultisetPartitionsIntoSets_all_constraints): P = OrderedMultisetPartitionsIntoSets(c.weight()) return P.element_class(P, c) else: return c else: raise ValueError(('ordered multiset partitions into sets do not have repeated entries within blocks (%s received)' % str(co))) def __iter__(self): '\n Iterate over ordered multiset partitions into sets.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets(3).list()\n [[{3}], [{1,2}], [{2}, {1}], [{1}, {2}], [{1}, {1}, {1}]]\n sage: OrderedMultisetPartitionsIntoSets(0).list()\n [[]]\n sage: C = OrderedMultisetPartitionsIntoSets()\n sage: it = C.__iter__()\n sage: [next(it) for i in range(16)]\n [[], [{1}], [{2}], [{1}, {1}], [{3}], [{1,2}], [{2}, {1}],\n [{1}, {2}], [{1}, {1}, {1}], [{4}], [{1,3}], [{3}, {1}],\n [{1,2}, {1}], [{2}, {2}], [{2}, {1}, {1}], [{1}, {3}]]\n\n TESTS::\n\n sage: OrderedMultisetPartitionsIntoSets(alphabet=[1,3], max_length=2).list()\n [[], [{1}], [{3}], [{1,3}], [{1}, {1}], [{1}, {3}],\n [{3}, {1}], [{3}, {3}], [{1,3}, {1}], [{1,3}, {3}],\n [{1}, {1,3}], [{3}, {1,3}], [{1,3}, {1,3}]]\n sage: C = OrderedMultisetPartitionsIntoSets(min_length=2, max_order=2)\n sage: it = C.__iter__()\n sage: [next(it) for i in range(15)]\n [[{1}, {1}], [{2}, {1}], [{1}, {2}], [{3}, {1}], [{2}, {2}],\n [{1}, {3}], [{4}, {1}], [{3}, {2}], [{2}, {3}], [{1}, {4}],\n [{5}, {1}], [{4}, {2}], [{3}, {3}], [{2}, {4}], [{1}, {5}]]\n sage: OrderedMultisetPartitionsIntoSets(alphabet=[1,3], min_length=2).list()\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n ' iterator = _base_iterator(self.full_constraints) if iterator: for co in iterator: if self._satisfies_constraints(co): (yield self.element_class(self, co)) elif ('alphabet' in self.constraints): A = self.constraints['alphabet'] max = self.constraints.get('max_length', infinity) max = self.constraints.get('length', max) max = (max * len(A)) max = self.constraints.get('max_order', max) max_ell = self.constraints.get('order', max) ell = 0 while (True and (ell <= max_ell)): for co in _iterator_order(A, ell): if self._satisfies_constraints(co): (yield self.element_class(self, co)) ell += 1 else: n = 0 while True: for co in _iterator_size(n): if self._satisfies_constraints(co): (yield self.element_class(self, co)) n += 1 def subset(self, size): '\n Return a subset of all ordered multiset partitions into sets.\n\n INPUT:\n\n - ``size`` -- an integer representing a slice of all ordered\n multiset partitions into sets\n\n The slice alluded to above is taken with respect to length, or\n to order, or to size, depending on the constraints of ``self``.\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionsIntoSets(weight={2:2, 3:1, 5:1})\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of multiset {{2, 2, 3, 5}} with constraint: length=3\n sage: C = OrderedMultisetPartitionsIntoSets(weight={2:2, 3:1, 5:1}, min_length=2)\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of multiset {{2, 2, 3, 5}} with constraint: length=3\n sage: C = OrderedMultisetPartitionsIntoSets(alphabet=[2,3,5])\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of order 3 over alphabet {2, 3, 5}\n sage: C = OrderedMultisetPartitionsIntoSets(order=5)\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of integer 3 with constraint: order=5\n sage: C = OrderedMultisetPartitionsIntoSets(alphabet=[2,3,5], order=5, length=3)\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of order 3 over alphabet {2, 3, 5} with constraint: length=3\n sage: C = OrderedMultisetPartitionsIntoSets()\n sage: C.subset(3)\n Ordered Multiset Partitions into Sets of integer 3\n sage: C.subset(3) == OrderedMultisetPartitionsIntoSets(3)\n True\n ' fc = self.full_constraints if ('weight' in fc): return OrderedMultisetPartitionsIntoSets(fc['weight'], length=size, **self.constraints) elif (('alphabet' in fc) and ('size' in fc)): add_length = dict(self.constraints) add_length['length'] = size return OrderedMultisetPartitionsIntoSets(fc['alphabet'], fc['order'], **add_length) if ('alphabet' in fc): no_alpha = {k: v for (k, v) in self.constraints.items() if (k != 'alphabet')} return OrderedMultisetPartitionsIntoSets(fc['alphabet'], size, **no_alpha) return OrderedMultisetPartitionsIntoSets(size, **self.constraints)
class OrderedMultisetPartitionsIntoSets_all_constraints(OrderedMultisetPartitionsIntoSets): "\n All ordered multiset partitions into sets (with or without constraints).\n\n EXAMPLES::\n\n sage: C = OrderedMultisetPartitionsIntoSets(); C\n Ordered Multiset Partitions into Sets\n sage: [[1],[1,'a']] in C\n True\n\n sage: OrderedMultisetPartitionsIntoSets(weight=[2,0,1], length=2)\n Ordered Multiset Partitions into Sets of multiset {{1, 1, 3}} with constraint: length=2\n\n TESTS::\n\n sage: OMP = OrderedMultisetPartitionsIntoSets()\n sage: TestSuite(OMP).run() # long time\n\n sage: C = OrderedMultisetPartitionsIntoSets(weight=[2,0,1], length=2)\n sage: TestSuite(C).run()\n\n sage: D1 = OrderedMultisetPartitionsIntoSets(weight={1:2, 3:1}, min_length=2, max_length=2)\n sage: D2 = OrderedMultisetPartitionsIntoSets({1:2, 3:1}, min_length=2, max_length=2)\n sage: D3 = OrderedMultisetPartitionsIntoSets(5, weight={1:2, 3:1}, length=2)\n sage: D4 = OrderedMultisetPartitionsIntoSets([1,3], 3, weight={1:2, 3:1}, length=2)\n sage: D5 = OrderedMultisetPartitionsIntoSets([1,3], 3, size=5, length=2)\n sage: all(C != D for D in [D1, D2, D3, D4, D5])\n True\n sage: all(Set(C) == Set(D) for D in [D1, D2, D3, D4, D5])\n True\n sage: E = OrderedMultisetPartitionsIntoSets({1:2, 3:1}, min_length=2)\n sage: Set(C) == Set(E)\n False\n " def _repr_(self): "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: OrderedMultisetPartitionsIntoSets(min_length=3, max_order=5)\n Ordered Multiset Partitions into Sets with constraints: max_order=5, min_length=3\n sage: OrderedMultisetPartitionsIntoSets(min_length=3, max_order=5, alphabet=[1,'a'])\n Ordered Multiset Partitions into Sets with constraints:\n alphabet={1, 'a'}, max_order=5, min_length=3\n " return ('Ordered Multiset Partitions into Sets' + self._constraint_repr_())
class OrderedMultisetPartitionsIntoSets_n(OrderedMultisetPartitionsIntoSets): '\n Ordered multiset partitions into sets of a fixed integer `n`.\n ' def __init__(self, n): '\n Initialize ``self``.\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets(Integer(4))\n sage: TestSuite(C).run()\n sage: C2 = OrderedMultisetPartitionsIntoSets(int(4))\n sage: C is C2\n True\n sage: C3 = OrderedMultisetPartitionsIntoSets(7/2)\n Traceback (most recent call last):\n ...\n ValueError: 7/2 must be a nonnegative integer or a list or\n dictionary representing a multiset\n ' self._n = n OrderedMultisetPartitionsIntoSets.__init__(self, True) def _repr_(self): '\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: OrderedMultisetPartitionsIntoSets(3)\n Ordered Multiset Partitions into Sets of integer 3\n ' return ('Ordered Multiset Partitions into Sets of integer %s' % self._n) def cardinality(self): '\n Return the number of elements in ``self``.\n\n TESTS::\n\n sage: len(OrderedMultisetPartitionsIntoSets(10).list())\n 1500\n sage: OrderedMultisetPartitionsIntoSets(10).cardinality()\n 1500\n ' if (self._n <= 5): orders = {0: 1, 1: 1, 2: 2, 3: 5, 4: 11, 5: 25} return ZZ(orders[self._n]) t = PowerSeriesRing(ZZ, 't').gen().O((self._n + 1)) partspoly = prod(((1 + (t ** k)) for k in range(1, (self._n + 1)))).dict() deg = 0 for alpha in composition_iterator_fast(self._n): deg += prod((partspoly[d] for d in alpha)) return ZZ(deg) def _an_element_(self): '\n Return a typical element of ``self``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets(13).an_element()\n [{2,3}, {2,3}, {1,2}]\n sage: OrderedMultisetPartitionsIntoSets(14).an_element()\n [{2,3}, {2,3}, {4}]\n ' alpha = Compositions(self._n, max_part=((self._n // 3) + 1)).an_element() out = [] for a in alpha: if (a in {1, 2, 4}): out.append([a]) elif (a % 2): out.append([((a // 2) + 1), (a // 2)]) else: out.append([(a // 2), ((a // 2) - 1), 1]) return self.element_class(self, map(frozenset, out)) def random_element(self): '\n Return a random element of ``self``.\n\n This method does not return elements of ``self`` with uniform probability,\n but it does cover all elements. The scheme is as follows:\n\n - produce a random composition `C`;\n - choose a random partition of `c` into distinct parts for each `c` in `C`.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets(5).random_element() # random\n [{1,2}, {1}, {1}]\n sage: OrderedMultisetPartitionsIntoSets(5).random_element() # random\n [{2}, {1,2}]\n\n sage: OMP = OrderedMultisetPartitionsIntoSets(5)\n sage: d = {}\n sage: for _ in range(1100):\n ....: x = OMP.random_element()\n ....: d[x] = d.get(x, 0) + 1\n sage: d.values() # random\n [72, 73, 162, 78, 135, 75, 109, 65, 135, 134, 62]\n ' C = Compositions(self._n).random_element() co = [IntegerListsLex(c, min_part=1, max_part=c, min_slope=1).random_element() for c in C] return self.element_class(self, map(frozenset, co)) def __iter__(self): '\n Iterate over ``self``.\n\n TESTS::\n\n sage: O = OrderedMultisetPartitionsIntoSets(6)\n sage: it = O.__iter__()\n sage: [next(it) for _ in range(10)]\n [[{6}], [{2,4}], [{1,5}], [{1,2,3}],\n [{5}, {1}], [{2,3}, {1}], [{1,4}, {1}],\n [{4}, {2}], [{1,3}, {2}], [{4}, {1}, {1}]]\n ' for co in _iterator_size(self._n): (yield self.element_class(self, co))
class OrderedMultisetPartitionsIntoSets_n_constraints(OrderedMultisetPartitionsIntoSets): '\n Class of ordered multiset partitions into sets of a fixed integer `n`\n satisfying constraints.\n ' def __init__(self, n, **constraints): '\n Mimic class ``OrderedMultisetPartitionsIntoSets_n`` to initialize.\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets(6, length=3)\n sage: TestSuite(C).run()\n\n sage: C = OrderedMultisetPartitionsIntoSets(6, weight=[3,0,1], length=3)\n sage: TestSuite(C).run()\n ' self._n = n OrderedMultisetPartitionsIntoSets.__init__(self, True, size=n, **constraints) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: O = OrderedMultisetPartitionsIntoSets(14, length=4, max_order=6, alphabet={2,4,5,6})\n sage: O\n Ordered Multiset Partitions into Sets of integer 14 with constraints:\n alphabet={2, 4, 5, 6}, length=4, max_order=6\n ' cdict = dict(self.constraints) cdict.pop('size', None) base_repr = ('Ordered Multiset Partitions into Sets of integer %s' % self._n) return (base_repr + self._constraint_repr_(cdict))
class OrderedMultisetPartitionsIntoSets_X(OrderedMultisetPartitionsIntoSets): '\n Class of ordered multiset partitions into sets of a fixed multiset `X`.\n ' def __init__(self, X): '\n Initialize ``self``.\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets([1,1,4])\n sage: TestSuite(C).run()\n\n sage: C2 = OrderedMultisetPartitionsIntoSets({1:2, 4:1})\n sage: C is C2\n True\n ' self._X = X if all((((k in ZZ) and (k > 0)) for (k, v) in X)): self._Xtup = tuple([k for (k, v) in sorted(X) for _ in range(v)]) else: self._Xtup = tuple([k for (k, v) in sorted(X, key=str) for _ in range(v)]) OrderedMultisetPartitionsIntoSets.__init__(self, True) def _repr_(self): "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: repr(OrderedMultisetPartitionsIntoSets([1,1,4]))\n 'Ordered Multiset Partitions into Sets of multiset {{1, 1, 4}}'\n " ms_rep = (('{{' + ', '.join(map(str, self._Xtup))) + '}}') return ('Ordered Multiset Partitions into Sets' + (' of multiset %s' % ms_rep)) def __contains__(self, x): "\n Return if ``x`` is contained in ``self``.\n\n TESTS::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import OrderedMultisetPartitionsIntoSets_X as OMPX\n sage: [[2,1], [1,3]] in OMPX(((1,2), (2,1), (3,1)))\n True\n sage: co = OrderedMultisetPartitionIntoSets([[2,1], [1,3]])\n sage: co in OMPX(((1,2), (2,1), (3,1)))\n True\n sage: [[2,1], [2,3]] in OMPX(((1,2), (2,1), (3,1)))\n False\n sage: [] in OMPX(())\n True\n sage: [[2, -1], [2,'a']] in OMPX(((2,2), (-1,1), ('a',1)))\n True\n " if (not isinstance(x, (OrderedMultisetPartitionIntoSets, list, tuple))): return False x_Xtup = sorted(_concatenate(x), key=str) self_Xtup = sorted(self._Xtup, key=str) return (_has_nonempty_sets(x) and (x_Xtup == self_Xtup)) def cardinality(self): '\n Return the number of ordered partitions of multiset ``X``.\n\n TESTS::\n\n sage: len(OrderedMultisetPartitionsIntoSets([2,2,2,3,4,5]).list())\n 535\n sage: OrderedMultisetPartitionsIntoSets([2,2,2,3,4,5]).cardinality()\n 535\n ' if (self._Xtup == ()): return ZZ(0) deg = 0 for alpha in Permutations_mset(self._Xtup): fattest = _break_at_descents(alpha) deg += prod(((2 ** (len(k) - 1)) for k in fattest)) return ZZ(deg) def _an_element_(self): '\n Return a typical element of ``self``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets([2,2,2,3,4,5]).an_element()\n [{2}, {2}, {2,3,4}, {5}]\n sage: OrderedMultisetPartitionsIntoSets([2,2,2,3,4,4,5]).an_element()\n [{2}, {2}, {2,3}, {4}, {4,5}]\n ' if (not self._Xtup): return self.element_class(self, []) alpha = Permutations_mset(self._Xtup).an_element() co = _break_at_descents(alpha) elt = [] for i in range(len(co)): if (len(co[i]) == 1): elt.append(co[i]) else: break elt.append(co[i][:((len(co[i]) // 2) + 1)]) elt.append(co[i][((len(co[i]) // 2) + 1):]) elt.extend(co[(i + 1):]) return self.element_class(self, map(frozenset, elt)) def random_element(self): '\n Return a random element of ``self``.\n\n This method does not return elements of ``self`` with uniform probability,\n but it does cover all elements. The scheme is as follows:\n\n - produce a random permutation ``p`` of the multiset;\n - create blocks of an OMP ``fat`` by breaking ``p`` after non-ascents;\n - take a random element of ``fat.finer()``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets([1,1,3]).random_element() # random\n [{1}, {1,3}]\n sage: OrderedMultisetPartitionsIntoSets([1,1,3]).random_element() # random\n [{3}, {1}, {1}]\n\n sage: OMP = OrderedMultisetPartitionsIntoSets([1,1,3,3])\n sage: d = {}\n sage: for _ in range(1000):\n ....: x = OMP.random_element()\n ....: d[x] = d.get(x, 0) + 1\n sage: d.values() # random\n [102, 25, 76, 24, 66, 88, 327, 27, 83, 83, 239, 72, 88]\n ' if (not self._Xtup): return self.element_class(self, []) alpha = Permutations_mset(self._Xtup).random_element() co = _break_at_descents(alpha) finer = self.element_class(self, map(frozenset, co)).finer() return FiniteEnumeratedSets()(finer).random_element() def __iter__(self): "\n Iterate over ``self``.\n\n TESTS::\n\n sage: O = OrderedMultisetPartitionsIntoSets(['a', 'b', 'a'])\n sage: sorted(O, key=str)\n [[{'a','b'}, {'a'}],\n [{'a'}, {'a','b'}],\n [{'a'}, {'a'}, {'b'}],\n [{'a'}, {'b'}, {'a'}],\n [{'b'}, {'a'}, {'a'}]]\n\n sage: O = OrderedMultisetPartitionsIntoSets([1, 1, 2])\n sage: list(O)\n [[{1}, {1}, {2}], [{1}, {1,2}], [{1}, {2}, {1}],\n [{1,2}, {1}], [{2}, {1}, {1}]]\n " for co in _iterator_weight(weight=dict(self._X)): (yield self.element_class(self, co))
class OrderedMultisetPartitionsIntoSets_X_constraints(OrderedMultisetPartitionsIntoSets): '\n Class of ordered multiset partitions into sets of a fixed multiset `X`\n satisfying constraints.\n ' def __init__(self, X, **constraints): '\n Mimic class ``OrderedMultisetPartitionsIntoSets_X`` to initialize.\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets([1,1,2,4], length=3)\n sage: TestSuite(C).run()\n\n sage: C = OrderedMultisetPartitionsIntoSets([1,1,2,4], max_length=3)\n sage: TestSuite(C).run()\n ' self._X = X self._Xtup = tuple((k for (k, v) in sorted(X) for _ in range(v))) OrderedMultisetPartitionsIntoSets.__init__(self, True, weight=X, **constraints) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: O = OrderedMultisetPartitionsIntoSets([2,2,2,3,4,4,5], min_length=4, max_length=5)\n sage: O\n Ordered Multiset Partitions into Sets of multiset {{2, 2, 2, 3, 4, 4, 5}}\n with constraints: max_length=5, min_length=4\n ' cdict = dict(self.constraints) cdict.pop('weight', None) ms_rep = (('{{' + ', '.join(map(str, self._Xtup))) + '}}') base_repr = ('Ordered Multiset Partitions into Sets' + (' of multiset %s' % ms_rep)) return (base_repr + self._constraint_repr_(cdict))
class OrderedMultisetPartitionsIntoSets_alph_d(OrderedMultisetPartitionsIntoSets): '\n Class of ordered multiset partitions into sets of specified order `d`\n over a fixed alphabet `A`.\n ' def __init__(self, A, d): '\n Initialize ``self``.\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets(3, 2)\n sage: TestSuite(C).run()\n\n sage: C2 = OrderedMultisetPartitionsIntoSets([1,2,3], 2)\n sage: C is C2\n True\n\n sage: list(OrderedMultisetPartitionsIntoSets([1,2,3], 2))\n [[{1,2}], [{1,3}], [{2,3}], [{1}, {1}], [{1}, {2}], [{1}, {3}], [{2}, {1}],\n [{2}, {2}], [{2}, {3}], [{3}, {1}], [{3}, {2}], [{3}, {3}]]\n ' self._alphabet = A self._order = d OrderedMultisetPartitionsIntoSets.__init__(self, True) def _repr_(self): "\n Return a string representation of ``self``.\n\n TESTS::\n\n sage: repr(OrderedMultisetPartitionsIntoSets(3, 2))\n 'Ordered Multiset Partitions into Sets of order 2 over alphabet {1, 2, 3}'\n sage: repr(OrderedMultisetPartitionsIntoSets([1,3], 2))\n 'Ordered Multiset Partitions into Sets of order 2 over alphabet {1, 3}'\n " A_rep = ('Ordered Multiset Partitions into Sets of order ' + str(self._order)) A_rep += (' over alphabet {%s}' % ', '.join(map(str, sorted(self._alphabet)))) return A_rep def _an_element_(self): '\n Return a typical element of ``OrderedMultisetPartitionIntoSets_alph_d``.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets([2,3,4,5], 3).an_element()\n [{2,4,5}]\n ' alpha = Compositions(self._order, max_part=len(self._alphabet)).an_element() co = [Subsets_sk(self._alphabet, a).an_element() for a in alpha] return self.element_class(self, map(frozenset, co)) def random_element(self): '\n Return a random element of ``self``.\n\n This method does not return elements of ``self`` with uniform probability,\n but it does cover all elements. The scheme is as follows:\n\n - produce a random composition `C`;\n - choose random subsets of ``self._alphabet`` of size `c` for each `c` in `C`.\n\n EXAMPLES::\n\n sage: OrderedMultisetPartitionsIntoSets([1,4], 3).random_element() # random\n [{4}, {1,4}]\n sage: OrderedMultisetPartitionsIntoSets([1,3], 4).random_element() # random\n [{1,3}, {1}, {3}]\n\n sage: OMP = OrderedMultisetPartitionsIntoSets([2,3,4], 2)\n sage: d = {}\n sage: for _ in range(1200):\n ....: x = OMP.random_element()\n ....: d[x] = d.get(x, 0) + 1\n sage: d.values() # random\n [192, 68, 73, 61, 69, 60, 77, 204, 210, 66, 53, 67]\n ' if (not self._alphabet): return self.element_class(self, []) alpha = Compositions(self._order, max_part=len(self._alphabet)).random_element() co = [Subsets_sk(self._alphabet, a).random_element() for a in alpha] return self.element_class(self, map(frozenset, co)) def __iter__(self): "\n Iterate over ``self``.\n\n TESTS::\n\n sage: O = OrderedMultisetPartitionsIntoSets(['a', 'b'], 3)\n sage: it = O.__iter__()\n sage: sorted([next(it) for _ in range(O.cardinality())], key=str)\n [[{'a','b'}, {'a'}], [{'a','b'}, {'b'}], [{'a'}, {'a','b'}],\n [{'a'}, {'a'}, {'a'}], [{'a'}, {'a'}, {'b'}], [{'a'}, {'b'}, {'a'}],\n [{'a'}, {'b'}, {'b'}], [{'b'}, {'a','b'}], [{'b'}, {'a'}, {'a'}],\n [{'b'}, {'a'}, {'b'}], [{'b'}, {'b'}, {'a'}], [{'b'}, {'b'}, {'b'}]]\n " for co in _iterator_order(self._alphabet, self._order): (yield self.element_class(self, co)) def cardinality(self): "\n Return the number of ordered partitions of order ``self._order`` on\n alphabet ``self._alphabet``.\n\n TESTS::\n\n sage: len(OrderedMultisetPartitionsIntoSets([1, 'a'], 3).list())\n 12\n sage: OrderedMultisetPartitionsIntoSets([1, 'a'], 3).cardinality()\n 12\n " if (self._order == 0): return ZZ(0) min_length = (self._order // len(self._alphabet)) max_length = self._order deg = 0 for k in range(min_length, (max_length + 1)): for alpha in IntegerListsLex(self._order, length=k, min_part=1, max_part=len(self._alphabet)): deg += prod((binomial(len(self._alphabet), a) for a in alpha)) return ZZ(deg)
class OrderedMultisetPartitionsIntoSets_alph_d_constraints(OrderedMultisetPartitionsIntoSets): '\n Class of ordered multiset partitions into sets of specified order `d`\n over a fixed alphabet `A` satisfying constraints.\n ' def __init__(self, A, d, **constraints): '\n Mimic class ``OrderedMultisetPartitionsIntoSets_alph_d`` to initialize.\n\n EXAMPLES::\n\n sage: list(OrderedMultisetPartitionsIntoSets(3, 2, length=3))\n []\n sage: list(OrderedMultisetPartitionsIntoSets([1,2,4], 2, length=1))\n [[{1,2}], [{1,4}], [{2,4}]]\n\n TESTS::\n\n sage: C = OrderedMultisetPartitionsIntoSets(3, 2, length=3)\n sage: TestSuite(C).run()\n\n sage: C = OrderedMultisetPartitionsIntoSets([1,2,4], 4, min_length=3)\n sage: TestSuite(C).run()\n ' self._alphabet = A self._order = d OrderedMultisetPartitionsIntoSets.__init__(self, True, alphabet=A, order=d, **constraints) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: O = OrderedMultisetPartitionsIntoSets([2,3,4,5], 4, length=3)\n sage: O\n Ordered Multiset Partitions into Sets of order 4 over alphabet {2, 3, 4, 5}\n with constraint: length=3\n sage: O = OrderedMultisetPartitionsIntoSets([2,3,4,5], 4, max_length=4, size=10)\n sage: O\n Ordered Multiset Partitions into Sets of order 4 over alphabet {2, 3, 4, 5}\n with constraints: max_length=4, size=10\n ' cdict = dict(self.constraints) cdict.pop('alphabet', None) cdict.pop('order', None) base_repr = ('Ordered Multiset Partitions into Sets of order ' + str(self._order)) base_repr += (' over alphabet {%s}' % ', '.join(map(str, sorted(self._alphabet)))) return (base_repr + self._constraint_repr_(cdict))
def _get_multiset(co): '\n Construct the multiset (as a sorted tuple) suggested by the lists\n of lists ``co``.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _get_multiset\n sage: L = ((1,), (1, 6), (6, 7), (1,), (1, 3))\n sage: _get_multiset(L)\n (1, 1, 1, 1, 3, 6, 6, 7)\n ' return tuple(sorted(_concatenate(co), key=str))
def _get_weight(lst): '\n Construct the multiset (as a dictionary) suggested by the\n multiset-as-list ``lst``.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _get_weight\n sage: L = (1, 1, 1, 3, 1, 6, 6, 7)\n sage: _get_weight(L)\n {1: 4, 3: 1, 6: 2, 7: 1}\n ' out = {} for k in lst: out[k] = (out.get(k, 0) + 1) return out
def _has_nonempty_sets(x): '\n Blocks should be nonempty sets/lists/tuples of distinct elements.\n\n TESTS::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _has_nonempty_sets\n sage: _has_nonempty_sets([[2,4], {1}, (1,4)])\n True\n sage: _has_nonempty_sets([[2,4], {}, (1,4)])\n False\n sage: _has_nonempty_sets([(2,4), (1,1), (1,4)])\n False\n ' return all(((isinstance(block, (list, tuple, set, frozenset, Set_object)) and block and (len(set(block)) == len(block))) for block in x))
def _union_of_sets(list_of_sets): '\n Return the union of a list of iterables as a frozenset.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _union_of_sets\n sage: L = ([1,2,3], Set([1,5,6]), [], range(5,8))\n sage: _union_of_sets(L)\n frozenset({1, 2, 3, 5, 6, 7})\n ' return reduce((lambda a, b: (frozenset(a) | frozenset(b))), list_of_sets, frozenset())
def _concatenate(list_of_iters): '\n Return the concatenation of a list of iterables as a tuple.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _concatenate\n sage: L = ([1,2,3], Set([4,5,6]), [], range(7,11))\n sage: _concatenate(L)\n (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n ' return tuple([val for block in list_of_iters for val in block])
def _is_finite(constraints): '\n Return ``True`` if the dictionary ``constraints`` corresponds to\n a finite collection of ordered multiset partitions into sets.\n\n If either ``weight`` or ``size`` is among the constraints, then\n the constraints represent a finite collection of ordered multiset\n partitions into sets. If both are absent, one needs ``alphabet`` to be\n present (plus a bound on length or order) in order to have a\n finite collection of ordered multiset partitions into sets.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _is_finite\n sage: W = {"weight": {1:3, 2:3, 4:1}, "length": 5}\n sage: S = {"size": 44, "min_length": 5}\n sage: AO = {"alphabet": range(44), "max_order": 5}\n sage: all(_is_finite(constr) for constr in (W, S, AO))\n True\n sage: AL = {"alphabet": range(44), "min_order": 5}\n sage: _is_finite(AL)\n False\n ' if (('weight' in constraints) or ('size' in constraints)): return True elif ('alphabet' in constraints): Bounds = set(['length', 'max_length', 'order', 'max_order']) return (Bounds.intersection(set(constraints)) != set())
def _base_iterator(constraints): '\n Return a base iterator for ordered multiset partitions into sets or ``None``.\n\n If the keys within ``constraints`` dictionary correspond to a finite set\n of ordered multiset partitions into sets, return an iterator. Else,\n return ``None``.\n\n OUTPUT:\n\n Tuples of ``frozenset`` objects representing ordered multiset partitions\n into sets.\n\n EXAMPLES:\n\n If key ``weight`` is present, ignore all other constraints\n (passes to ``_iterator_weight``)::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _base_iterator\n sage: OMP = OrderedMultisetPartitionIntoSets\n sage: constraints = {"weight": {1:3, 2:3, 4:1}, "length": 5}\n sage: it = _base_iterator(constraints)\n sage: sorted(OMP(next(it)) for _ in range(4)) # note the partitions of length 6 and 7\n [[{1}, {1}, {1}, {2}, {2}, {2}, {4}],\n [{1}, {1}, {1}, {2}, {2}, {2,4}],\n [{1}, {1}, {1,2}, {2}, {2}, {4}],\n [{1}, {1}, {1,2}, {2}, {2,4}]]\n\n If key ``size`` is present, pass to ``_iterator_size``, which then\n takes into account whether or not keys ``length`` and ``alphabet``\n are among the constraints::\n\n sage: constraints = {"size": 5}\n sage: it = _base_iterator(constraints)\n sage: [OMP(next(it)) for _ in range(8)]\n [[{5}], [{2,3}], [{1,4}], [{4}, {1}], [{1,3}, {1}],\n [{3}, {2}], [{1,2}, {2}], [{3}, {1}, {1}]]\n\n sage: constraintsL = {"size": 6, "length":2}\n sage: it = _base_iterator(constraintsL)\n sage: [OMP(next(it)) for _ in range(8)]\n [[{5}, {1}], [{2,3}, {1}], [{1,4}, {1}], [{4}, {2}],\n [{1,3}, {2}], [{3}, {3}], [{3}, {1,2}], [{1,2}, {3}]]\n\n sage: constraintsA = {"size": 6, "alphabet":frozenset([2, 3])}\n sage: it = _base_iterator(constraintsA)\n sage: list(it)\n [(frozenset({3}), frozenset({3})),\n (frozenset({2}), frozenset({2}), frozenset({2}))]\n\n If key ``alphabet`` is present, the slice may still be infinite, in\n which case ``None`` is returned. Else, use to ``_iterator_order``::\n\n sage: constraints = {"alphabet": frozenset([3, 4]), "min_length":2}\n sage: _base_iterator(constraints) is None\n True\n sage: constraints = {"alphabet": frozenset([3, 4]), "max_length":2}\n sage: it = _base_iterator(constraints)\n sage: list(map(OMP, it))\n [[], [{3}], [{4}], [{3,4}], [{3}, {3}], [{3}, {4}],\n [{4}, {3}], [{4}, {4}], [{3,4}, {3}], [{3,4}, {4}],\n [{3}, {3,4}], [{4}, {3,4}], [{3,4}, {3,4}]]\n ' if ('weight' in constraints): return _iterator_weight(constraints['weight']) elif ('size' in constraints): return _iterator_size(constraints['size'], constraints.get('length', None), constraints.get('alphabet', None)) elif ('alphabet' in constraints): A = constraints['alphabet'] min_k = constraints.get('min_length', 0) max_k = constraints.get('max_length', infinity) min_ord = constraints.get('min_order', 0) max_ord = constraints.get('max_order', (max_k * len(A))) max_k = min(max_k, max_ord) if ('length' in constraints): min_k = max_k = constraints['length'] min_ord = max(min_ord, min_k) max_ord = min(max_ord, (len(A) * max_k)) if ('order' in constraints): min_ord = max_ord = constraints['order'] max_k = min(max_k, max_ord) if min_ord: min_k = max(1, min_k, (min_ord // len(A))) if (infinity not in (max_k, max_ord)): return chain(*(_iterator_order(A, ord, range(min_k, (max_k + 1))) for ord in range(min_ord, (max_ord + 1)))) return None
def _iterator_weight(weight): "\n An iterator for the ordered multiset partitions into sets with weight given by\n the dictionary (or weak composition) ``weight``.\n\n The dictionary ``weight`` may contain values equal to `0`;\n the corresponding keys are ignored.\n\n OUTPUT:\n\n Tuples of ``frozenset`` objects representing ordered multiset partitions\n into sets.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _iterator_weight\n sage: weight = {1:2, 'b':1}\n sage: OMP = OrderedMultisetPartitionsIntoSets(weight)\n sage: l = list(_iterator_weight(weight))\n\n sage: sorted(map(OMP, l), key=str) == sorted(map(OMP,\n ....: [[{1}, {1}, {'b'}], [{1}, {1,'b'}], [{1}, {'b'}, {1}],\n ....: [{1,'b'}, {1}], [{'b'}, {1}, {1}]]), key=str)\n True\n sage: OMP = OrderedMultisetPartitionsIntoSets({1:3, 3:1})\n sage: list(map(OMP, _iterator_weight([3,0,1])))\n [[{1}, {1}, {1}, {3}], [{1}, {1}, {1,3}], [{1}, {1}, {3}, {1}],\n [{1}, {1,3}, {1}], [{1}, {3}, {1}, {1}],\n [{1,3}, {1}, {1}], [{3}, {1}, {1}, {1}]]\n\n TESTS::\n\n sage: list(_iterator_weight([2,0,1]))\n [(frozenset({1}), frozenset({1}), frozenset({3})),\n (frozenset({1}), frozenset({1, 3})),\n (frozenset({1}), frozenset({3}), frozenset({1})),\n (frozenset({1, 3}), frozenset({1})),\n (frozenset({3}), frozenset({1}), frozenset({1}))]\n sage: list(_iterator_weight([]))\n [()]\n " if isinstance(weight, (list, tuple)): weight = {(k + 1): val for (k, val) in enumerate(weight) if val} keys = tuple(set(weight)) multiset = [] for (i, key) in enumerate(keys): multiset += ([i] * weight[key]) for alpha in Permutations_mset(multiset): co = _break_at_descents(alpha, weak=True) for A in OrderedMultisetPartitionIntoSets(co).finer(strong=True): B = tuple([frozenset([keys[i] for i in block]) for block in A]) (yield B)
def _iterator_size(size, length=None, alphabet=None): '\n An iterator for the ordered multiset partitions into sets of integer `n`.\n\n The degree `n` part of ordered multiset partitions into sets contains all\n sequences of subsets of `\\NN_+` whose total sum adds up to `n`.\n\n If optional argument ``alphabet`` is given, it should be a ``Set`` object.\n Then only yield those `c` with all letters taken from ``alphabet``.\n\n OUTPUT:\n\n Tuples of ``frozenset`` objects representing ordered multiset partitions\n into sets.\n\n TESTS::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _iterator_size\n sage: OMP = OrderedMultisetPartitionsIntoSets(3)\n sage: list(map(OMP, _iterator_size(3)))\n [[{3}], [{1,2}], [{2}, {1}], [{1}, {2}], [{1}, {1}, {1}]]\n\n sage: OMP = OrderedMultisetPartitionsIntoSets(5, alphabet=(1,3))\n sage: list(map(OMP, _iterator_size(5, alphabet={1,3})))\n [[{1,3}, {1}], [{3}, {1}, {1}], [{1}, {1,3}], [{1}, {3}, {1}],\n [{1}, {1}, {3}], [{1}, {1}, {1}, {1}, {1}]]\n\n sage: list(_iterator_size(2))\n [(frozenset({2}),), (frozenset({1}), frozenset({1}))]\n ' if alphabet: min_p = min(alphabet) max_p = max(alphabet) for alpha in IntegerListsLex(size, length=length, min_part=1, max_part=min(size, sum(alphabet))): for p in product(*[IntegerListsLex(a, min_slope=1, min_part=min_p, max_part=min(a, max_p)) for a in alpha]): if frozenset(_concatenate(p)).issubset(frozenset(alphabet)): (yield tuple((frozenset(k) for k in p))) else: for alpha in IntegerListsLex(size, length=length, min_part=1, max_part=size): for p in product(*[IntegerListsLex(a, min_slope=1, min_part=1) for a in alpha]): (yield tuple((frozenset(k) for k in p)))
def _iterator_order(A, d, lengths=None): '\n An iterator for the ordered multiset partitions into sets of order `d`\n over alphabet `A`.\n\n If optional argument ``lengths`` is given, it should be a list of integers.\n Then only yield those ordered multiset partitions into sets with length\n in ``lengths``.\n\n OUTPUT:\n\n Tuples of ``frozenset`` objects representing ordered multiset partitions\n into sets.\n\n TESTS::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _iterator_order\n sage: OMP = OrderedMultisetPartitionsIntoSets([1,4], 3)\n sage: list(map(OMP, _iterator_order({1,4}, 3)))\n [[{1,4}, {1}], [{1,4}, {4}], [{1}, {1,4}], [{4}, {1,4}], [{1}, {1}, {1}],\n [{1}, {1}, {4}], [{1}, {4}, {1}], [{1}, {4}, {4}], [{4}, {1}, {1}],\n [{4}, {1}, {4}], [{4}, {4}, {1}], [{4}, {4}, {4}]]\n sage: list(map(OMP, _iterator_order([1,4], 3, [3])))\n [[{1}, {1}, {1}], [{1}, {1}, {4}], [{1}, {4}, {1}], [{1}, {4}, {4}],\n [{4}, {1}, {1}], [{4}, {1}, {4}], [{4}, {4}, {1}], [{4}, {4}, {4}]]\n\n sage: OMP = OrderedMultisetPartitionsIntoSets([1,2,4], 3)\n sage: list(map(OMP, _iterator_order([1,2,4], 3, [1,2])))[:10]\n [[{1,2,4}], [{1,2}, {1}], [{1,2}, {2}], [{1,2}, {4}], [{1,4}, {1}],\n [{1,4}, {2}], [{1,4}, {4}], [{2,4}, {1}], [{2,4}, {2}], [{2,4}, {4}]]\n\n sage: list(_iterator_order([1,4], 3, [1]))\n []\n sage: list(_iterator_order([1,4], 3, [2]))\n [(frozenset({1, 4}), frozenset({1})), (frozenset({1, 4}), frozenset({4})),\n (frozenset({1}), frozenset({1, 4})), (frozenset({4}), frozenset({1, 4}))]\n sage: list(_iterator_order([1,4], 3, [4]))\n []\n sage: list(_iterator_order([1,4], 0, [3]))\n []\n sage: list(_iterator_order([1,4], 0, [0,3]))\n [()]\n sage: list(_iterator_order([1,4], 0))\n [()]\n ' A = frozenset(A) n = len(A) if (not lengths): if d: lengths = range(max(1, (d // n)), (d + 1)) else: lengths = (0,) for k in lengths: if ((not k) and (not d)): (yield ()) else: for alpha in IntegerListsLex(d, length=k, min_part=1, max_part=n): for co in product(*[Subsets_sk(A, a) for a in alpha]): (yield tuple((frozenset(X) for X in co)))
def _descents(w) -> list: '\n Return descent positions in the word ``w``.\n\n EXAMPLES::\n\n sage: from sage.combinat.multiset_partition_into_sets_ordered import _descents\n sage: _descents([1, 2, 3, 2, 2, 1, 4, 3]) == [2, 4, 6]\n True\n sage: _descents([])\n []\n ' return [j for j in range((len(w) - 1)) if (w[j] > w[(j + 1)])]