code
stringlengths
17
6.64M
class CartanType(CartanType_standard_untwisted_affine): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['B',4,1])\n sage: ct\n ['B', 4, 1]\n sage: ct._repr_(compact = True)\n 'B4~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.classical()\n ['B', 4]\n sage: ct.dual()\n ['B', 4, 1]^*\n sage: ct.dual().is_untwisted_affine()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 1) CartanType_standard_untwisted_affine.__init__(self, 'B', n) def dynkin_diagram(self): "\n Return the extended Dynkin diagram for affine type `B`.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: b = CartanType(['B',3,1]).dynkin_diagram(); b\n O 0\n |\n |\n O---O=>=O\n 1 2 3\n B3~\n sage: b.edges(sort=True)\n [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 3, 2), (3, 2, 1)]\n sage: b = CartanType(['B',2,1]).dynkin_diagram(); b\n O=>=O=<=O\n 0 2 1\n B2~\n sage: b.edges(sort=True)\n [(0, 2, 2), (1, 2, 2), (2, 0, 1), (2, 1, 1)]\n sage: b = CartanType(['B',1,1]).dynkin_diagram(); b\n O<=>O\n 0 1\n B1~\n sage: b.edges(sort=True)\n [(0, 1, 2), (1, 0, 2)]\n\n " from . import cartan_type n = self.n if (n == 1): res = cartan_type.CartanType(['A', 1, 1]).dynkin_diagram() res._cartan_type = self return res if (n == 2): res = cartan_type.CartanType(['C', 2, 1]).relabel({0: 0, 1: 2, 2: 1}).dynkin_diagram() res._cartan_type = self return res from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, (i + 1)) g.set_edge_label((n - 1), n, 2) g.add_edge(0, 2) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['B',4,1])._latex_dynkin_diagram())\n \\draw (0,0.7 cm) -- (2 cm,0);\n \\draw (0,-0.7 cm) -- (2 cm,0);\n \\draw (2 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$};\n \\draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n\n sage: print(CartanType(['B',4,1]).dual()._latex_dynkin_diagram())\n \\draw (0,0.7 cm) -- (2 cm,0);\n \\draw (0,-0.7 cm) -- (2 cm,0);\n \\draw (2 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$};\n \\draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node if (self.n == 1): from . import cartan_type return cartan_type.CartanType(['A', 1, 1])._latex_dynkin_diagram(label, node, node_dist) elif (self.n == 2): from . import cartan_type return cartan_type.CartanType(['C', 2, 1])._latex_dynkin_diagram(label, node, node_dist, dual) n = self.n single_end = ((n - 2) * node_dist) ret = ('\\draw (0,0.7 cm) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (0,-0.7 cm) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (%s cm,0) -- (%s cm,0);\n' % (node_dist, single_end)) ret += ('\\draw (%s cm, 0.1 cm) -- +(%s cm,0);\n' % (single_end, node_dist)) ret += ('\\draw (%s cm, -0.1 cm) -- +(%s cm,0);\n' % (single_end, node_dist)) if dual: ret += self._latex_draw_arrow_tip(((single_end + (0.5 * node_dist)) - 0.2), 0, 180) else: ret += self._latex_draw_arrow_tip(((single_end + (0.5 * node_dist)) + 0.2), 0, 0) ret += node(0, 0.7, label(0), 'left=3pt') ret += node(0, (- 0.7), label(1), 'left=3pt') for i in range(1, n): ret += node((i * node_dist), 0, label((i + 1))) return ret def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['B',3,1]).ascii_art())\n O 0\n |\n |\n O---O=>=O\n 1 2 3\n\n sage: print(CartanType(['B',5,1]).ascii_art(label = lambda x: x+2))\n O 2\n |\n |\n O---O---O---O=>=O\n 3 4 5 6 7\n\n sage: print(CartanType(['B',2,1]).ascii_art(label = lambda x: x+2))\n O=>=O=<=O\n 2 4 3\n sage: print(CartanType(['B',1,1]).ascii_art(label = lambda x: x+2))\n O<=>O\n 2 3\n " n = self.n from .cartan_type import CartanType if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node if (n == 1): return CartanType(['A', 1, 1]).ascii_art(label, node) if (n == 2): return CartanType(['C', 2, 1]).relabel({0: 0, 1: 2, 2: 1}).ascii_art(label, node) ret = ' {} {}\n |\n |\n'.format(node(label(0)), label(0)) ret += ('---'.join((node(label(i)) for i in range(1, n))) + '=>={}\n'.format(node(label(n)))) ret += ''.join(('{!s:4}'.format(label(i)) for i in range(1, (n + 1)))) return ret def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['B', 4, 1])._default_folded_cartan_type()\n ['B', 4, 1] as a folding of ['D', 5, 1]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n if (n == 1): return CartanTypeFolded(self, ['A', 1, 1], [[0], [1]]) return CartanTypeFolded(self, ['D', (n + 1), 1], ([[i] for i in range(n)] + [[n, (n + 1)]]))
class AmbientSpace(ambient_space.AmbientSpace): "\n EXAMPLES::\n\n sage: e = RootSystem(['C',2]).ambient_space(); e\n Ambient space of the Root system of type ['C', 2]\n\n One cannot construct the ambient lattice because the fundamental\n coweights have rational coefficients::\n\n sage: e.smallest_base_ring()\n Rational Field\n\n sage: RootSystem(['B',2]).ambient_space().fundamental_weights()\n Finite family {1: (1, 0), 2: (1/2, 1/2)}\n\n TESTS::\n\n sage: TestSuite(e).run() # needs sage.graphs\n " def dimension(self): "\n EXAMPLES::\n\n sage: e = RootSystem(['C',3]).ambient_space()\n sage: e.dimension()\n 3\n " return self.root_system.cartan_type().rank() def root(self, i, j, p1, p2): "\n Note that indexing starts at 0.\n\n EXAMPLES::\n\n sage: e = RootSystem(['C',3]).ambient_space()\n sage: e.root(0, 1, 1, 1)\n (-1, -1, 0)\n " return ((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) def simple_root(self, i): "\n EXAMPLES::\n\n sage: RootSystem(['C',3]).ambient_space().simple_roots()\n Finite family {1: (1, -1, 0), 2: (0, 1, -1), 3: (0, 0, 2)}\n " if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) return (self.root((i - 1), i, 0, 1) if (i < self.n) else self.root((self.n - 1), (self.n - 1), 0, 0)) def positive_roots(self): "\n EXAMPLES::\n\n sage: RootSystem(['C',3]).ambient_space().positive_roots()\n [(1, 1, 0),\n (1, 0, 1),\n (0, 1, 1),\n (1, -1, 0),\n (1, 0, -1),\n (0, 1, -1),\n (2, 0, 0),\n (0, 2, 0),\n (0, 0, 2)]\n " res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 0, p) for i in range(j)]) res.extend([self.root(i, i, 0, 0) for i in range(self.n)]) return res def negative_roots(self): "\n EXAMPLES::\n\n sage: RootSystem(['C',3]).ambient_space().negative_roots()\n [(-1, 1, 0),\n (-1, 0, 1),\n (0, -1, 1),\n (-1, -1, 0),\n (-1, 0, -1),\n (0, -1, -1),\n (-2, 0, 0),\n (0, -2, 0),\n (0, 0, -2)]\n " res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 1, p) for i in range(j)]) res.extend([self.root(i, i, 1, 1) for i in range(self.n)]) return res def fundamental_weight(self, i): "\n EXAMPLES::\n\n sage: RootSystem(['C',3]).ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0), 2: (1, 1, 0), 3: (1, 1, 1)}\n " return self.sum((self.monomial(j) for j in range(i)))
class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['C',4])\n sage: ct\n ['C', 4]\n sage: ct._repr_(compact = True)\n 'C4'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.affine()\n ['C', 4, 1]\n sage: ct.dual()\n ['B', 4]\n\n sage: ct = CartanType(['C',1])\n sage: ct.is_simply_laced()\n True\n sage: ct.affine()\n ['C', 1, 1]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 1) CartanType_standard_finite.__init__(self, 'C', n) if (n == 1): self._add_abstract_superclass(CartanType_simply_laced) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['C',4]))\n C_{4}\n " return ('C_{%s}' % self.n) AmbientSpace = AmbientSpace def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['C',4]).coxeter_number()\n 8\n " return (2 * self.n) def dual_coxeter_number(self): "\n Return the dual Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['C',4]).dual_coxeter_number()\n 5\n " return (self.n + 1) def dual(self): '\n Types B and C are in duality:\n\n EXAMPLES::\n\n sage: CartanType(["C", 3]).dual()\n [\'B\', 3]\n ' from . import cartan_type return cartan_type.CartanType(['B', self.n]) def dynkin_diagram(self): "\n Returns a Dynkin diagram for type C.\n\n EXAMPLES::\n\n sage: c = CartanType(['C',3]).dynkin_diagram(); c # needs sage.graphs\n O---O=<=O\n 1 2 3\n C3\n sage: c.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)]\n\n sage: b = CartanType(['C',1]).dynkin_diagram(); b # needs sage.graphs\n O\n 1\n C1\n sage: b.edges(sort=True) # needs sage.graphs\n []\n " return self.dual().dynkin_diagram().dual() def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['C',4])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n\n When ``dual=True``, the Dynkin diagram for the dual Cartan\n type `B_n` is returned::\n\n sage: print(CartanType(['C',4])._latex_dynkin_diagram(dual=True))\n \\draw (0 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n\n .. SEEALSO::\n\n - :meth:`sage.combinat.root_system.type_C.CartanType._latex_dynkin_diagram`\n - :meth:`sage.combinat.root_system.type_BC_affine.CartanType._latex_dynkin_diagram`\n " if (label is None): label = (lambda i: i) return self.dual()._latex_dynkin_diagram(label=label, node=node, node_dist=node_dist, dual=(not dual)) def ascii_art(self, label=None, node=None): "\n Return a ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['C',1]).ascii_art())\n O\n 1\n sage: print(CartanType(['C',2]).ascii_art())\n O=<=O\n 1 2\n sage: print(CartanType(['C',3]).ascii_art())\n O---O=<=O\n 1 2 3\n sage: print(CartanType(['C',5]).ascii_art(label = lambda x: x+2))\n O---O---O---O=<=O\n 3 4 5 6 7\n " if (label is None): label = (lambda i: i) return self.dual().ascii_art(label=label, node=node).replace('=>=', '=<=') def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['C', 3])._default_folded_cartan_type()\n ['C', 3] as a folding of ['A', 5]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n return CartanTypeFolded(self, ['A', ((2 * n) - 1)], ([[i, ((2 * n) - i)] for i in range(1, n)] + [[n]]))
class CartanType(CartanType_standard_untwisted_affine): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['C',4,1])\n sage: ct\n ['C', 4, 1]\n sage: ct._repr_(compact = True)\n 'C4~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.classical()\n ['C', 4]\n sage: ct.dual()\n ['C', 4, 1]^*\n sage: ct.dual().is_untwisted_affine()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 1) CartanType_standard_untwisted_affine.__init__(self, 'C', n) def dynkin_diagram(self): "\n Returns the extended Dynkin diagram for affine type C.\n\n EXAMPLES::\n\n sage: c = CartanType(['C',3,1]).dynkin_diagram(); c # needs sage.graphs\n O=>=O---O=<=O\n 0 1 2 3\n C3~\n sage: c.edges(sort=True) # needs sage.graphs\n [(0, 1, 2), (1, 0, 1), (1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 2)]\n\n " n = self.n if (n == 1): from . import cartan_type res = cartan_type.CartanType(['A', 1, 1]).dynkin_diagram() res._cartan_type = self return res from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, n): g.add_edge(i, (i + 1)) g.set_edge_label(n, (n - 1), 2) g.add_edge(0, 1, 2) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['C',4,1])._latex_dynkin_diagram())\n \\draw (0, 0.1 cm) -- +(2 cm,0);\n \\draw (0, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(1.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n {\n \\pgftransformxshift{2 cm}\n \\draw (0 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(4.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n }\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n\n sage: print(CartanType(['C',4,1]).dual()._latex_dynkin_diagram())\n \\draw (0, 0.1 cm) -- +(2 cm,0);\n \\draw (0, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n {\n \\pgftransformxshift{2 cm}\n \\draw (0 cm,0) -- (4 cm,0);\n \\draw (4 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (4 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(5.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n }\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node if (self.n == 1): from . import cartan_type return cartan_type.CartanType(['A', 1, 1])._latex_dynkin_diagram(label, node, node_dist) ret = ('\\draw (0, 0.1 cm) -- +(%s cm,0);\n' % node_dist) ret += ('\\draw (0, -0.1 cm) -- +(%s cm,0);\n' % node_dist) if dual: ret += self._latex_draw_arrow_tip(((0.5 * node_dist) - 0.2), 0, 180) else: ret += self._latex_draw_arrow_tip(((0.5 * node_dist) + 0.2), 0, 0) ret += ('{\n\\pgftransformxshift{%s cm}\n' % node_dist) ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += ('}\n' + node(0, 0, label(0))) return ret def ascii_art(self, label=None, node=None): "\n Return a ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['C',5,1]).ascii_art(label = lambda x: x+2))\n O=>=O---O---O---O=<=O\n 2 3 4 5 6 7\n\n sage: print(CartanType(['C',3,1]).ascii_art())\n O=>=O---O=<=O\n 0 1 2 3\n\n sage: print(CartanType(['C',2,1]).ascii_art())\n O=>=O=<=O\n 0 1 2\n\n sage: print(CartanType(['C',1,1]).ascii_art())\n O<=>O\n 0 1\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node n = self.n from .cartan_type import CartanType if (n == 1): return CartanType(['A', 1, 1]).ascii_art(label, node) ret = ((node(label(0)) + '=>=') + '---'.join((node(label(i)) for i in range(1, n)))) ret += (('=<=' + node(label(n))) + '\n') ret += ''.join(('{!s:4}'.format(label(i)) for i in range((n + 1)))) return ret def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['C', 3, 1])._default_folded_cartan_type()\n ['C', 3, 1] as a folding of ['A', 5, 1]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded n = self.n if (n == 1): return CartanTypeFolded(self, ['A', 1, 1], [[0], [1]]) return CartanTypeFolded(self, ['A', ((2 * n) - 1), 1], (([[0]] + [[i, ((2 * n) - i)] for i in range(1, n)]) + [[n]]))
class AmbientSpace(ambient_space.AmbientSpace): def dimension(self): "\n EXAMPLES::\n\n sage: e = RootSystem(['D',3]).ambient_space()\n sage: e.dimension()\n 3\n " return self.root_system.cartan_type().rank() def root(self, i, j, p1, p2): "\n Note that indexing starts at 0.\n\n EXAMPLES::\n\n sage: e = RootSystem(['D',3]).ambient_space()\n sage: e.root(0, 1, 1, 1)\n (-1, -1, 0)\n sage: e.root(0, 0, 1, 1)\n (-1, 0, 0)\n " if (i != j): return ((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) return (((- 1) ** p1) * self.monomial(i)) def simple_root(self, i): "\n EXAMPLES::\n\n sage: RootSystem(['D',4]).ambient_space().simple_roots()\n Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1), 4: (0, 0, 1, 1)}\n " if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) return (self.root((i - 1), i, 0, 1) if (i < self.n) else self.root((self.n - 2), (self.n - 1), 0, 0)) def positive_roots(self): "\n EXAMPLES::\n\n sage: RootSystem(['D',4]).ambient_space().positive_roots()\n [(1, 1, 0, 0),\n (1, 0, 1, 0),\n (0, 1, 1, 0),\n (1, 0, 0, 1),\n (0, 1, 0, 1),\n (0, 0, 1, 1),\n (1, -1, 0, 0),\n (1, 0, -1, 0),\n (0, 1, -1, 0),\n (1, 0, 0, -1),\n (0, 1, 0, -1),\n (0, 0, 1, -1)]\n " res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 0, p) for i in range(j)]) return res def negative_roots(self): "\n EXAMPLES::\n\n sage: RootSystem(['D',4]).ambient_space().negative_roots()\n [(-1, 1, 0, 0),\n (-1, 0, 1, 0),\n (0, -1, 1, 0),\n (-1, 0, 0, 1),\n (0, -1, 0, 1),\n (0, 0, -1, 1),\n (-1, -1, 0, 0),\n (-1, 0, -1, 0),\n (0, -1, -1, 0),\n (-1, 0, 0, -1),\n (0, -1, 0, -1),\n (0, 0, -1, -1)]\n " res = [] for p in [0, 1]: for j in range(self.n): res.extend([self.root(i, j, 1, p) for i in range(j)]) return res def fundamental_weight(self, i): "\n EXAMPLES::\n\n sage: RootSystem(['D',4]).ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1/2, 1/2, 1/2, -1/2), 4: (1/2, 1/2, 1/2, 1/2)}\n " if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) n = self.dimension() if (i == n): return (self.sum((self.monomial(j) for j in range(n))) / 2) elif (i == (n - 1)): return ((self.sum((self.monomial(j) for j in range((n - 1)))) - self.monomial((n - 1))) / 2) else: return self.sum((self.monomial(j) for j in range(i)))
class CartanType(CartanType_standard_finite, CartanType_simply_laced): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['D',4])\n sage: ct\n ['D', 4]\n sage: ct._repr_(compact = True)\n 'D4'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n True\n sage: ct.dual()\n ['D', 4]\n sage: ct.affine()\n ['D', 4, 1]\n\n sage: ct = CartanType(['D',2])\n sage: ct.is_irreducible()\n False\n sage: ct.dual()\n ['D', 2]\n sage: ct.affine()\n Traceback (most recent call last):\n ...\n ValueError: ['D', 2, 1] is not a valid Cartan type\n\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 2) CartanType_standard_finite.__init__(self, 'D', n) if (n >= 3): self._add_abstract_superclass(CartanType_simple) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['D',4]))\n D_{4}\n " return ('D_{%s}' % self.n) AmbientSpace = AmbientSpace def is_atomic(self): '\n Implements :meth:`CartanType_abstract.is_atomic`\n\n `D_2` is atomic, like all `D_n`, despite being non irreducible.\n\n EXAMPLES::\n\n sage: CartanType(["D",2]).is_atomic()\n True\n sage: CartanType(["D",2]).is_irreducible()\n False\n ' return True def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['D',4]).coxeter_number()\n 6\n " return ((2 * self.n) - 2) def dual_coxeter_number(self): "\n Return the dual Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['D',4]).dual_coxeter_number()\n 6\n " return ((2 * self.n) - 2) @cached_method def dynkin_diagram(self): "\n Returns a Dynkin diagram for type D.\n\n EXAMPLES::\n\n sage: d = CartanType(['D',5]).dynkin_diagram(); d # needs sage.graphs\n O 5\n |\n |\n O---O---O---O\n 1 2 3 4\n D5\n sage: d.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 1), (2, 3, 1), (3, 2, 1),\n (3, 4, 1), (3, 5, 1), (4, 3, 1), (5, 3, 1)]\n\n sage: d = CartanType(['D',4]).dynkin_diagram(); d # needs sage.graphs\n O 4\n |\n |\n O---O---O\n 1 2 3\n D4\n sage: d.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 1), (2, 3, 1), (2, 4, 1), (3, 2, 1), (4, 2, 1)]\n\n sage: d = CartanType(['D',3]).dynkin_diagram(); d # needs sage.graphs\n O 3\n |\n |\n O---O\n 1 2\n D3\n sage: d.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (1, 3, 1), (2, 1, 1), (3, 1, 1)]\n\n\n sage: d = CartanType(['D',2]).dynkin_diagram(); d # needs sage.graphs\n O O\n 1 2\n D2\n sage: d.edges(sort=True) # needs sage.graphs\n []\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) n = self.n if (n >= 3): for i in range(1, (n - 1)): g.add_edge(i, (i + 1)) g.add_edge((n - 2), n) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['D',4])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (2 cm,0);\n \\draw (2 cm,0) -- (4 cm,0.7 cm);\n \\draw (2 cm,0) -- (4 cm,-0.7 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0.7 cm) circle (.25cm) node[right=3pt]{$4$};\n \\draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node if (self.n == 2): ret = node(0, 0, label(1)) ret += node(node_dist, 0, label(2)) return ret rt_most = ((self.n - 2) * node_dist) center_point = (rt_most - node_dist) ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % center_point) ret += ('\\draw (%s cm,0) -- (%s cm,0.7 cm);\n' % (center_point, rt_most)) ret += ('\\draw (%s cm,0) -- (%s cm,-0.7 cm);\n' % (center_point, rt_most)) for i in range((self.n - 2)): ret += node((i * node_dist), 0, label((i + 1))) ret += node(rt_most, 0.7, label(self.n), 'right=3pt') ret += node(rt_most, (- 0.7), label((self.n - 1)), 'right=3pt') return ret def ascii_art(self, label=None, node=None): "\n Return a ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['D',3]).ascii_art())\n O 3\n |\n |\n O---O\n 1 2\n sage: print(CartanType(['D',4]).ascii_art())\n O 4\n |\n |\n O---O---O\n 1 2 3\n sage: print(CartanType(['D',4]).ascii_art(label = lambda x: x+2))\n O 6\n |\n |\n O---O---O\n 3 4 5\n sage: print(CartanType(['D',6]).ascii_art(label = lambda x: x+2))\n O 8\n |\n |\n O---O---O---O---O\n 3 4 5 6 7\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node n = self.n if (n == 2): ret = '{} {}\n'.format(node(label(1)), node(label(2))) return (ret + '{!s:4}{!s:4}'.format(label(1), label(2))) ret = (((4 * (n - 3)) * ' ') + '{} {}\n'.format(node(label(n)), label(n))) ret += ((((4 * (n - 3)) * ' ') + '|\n') * 2) ret += ('---'.join((node(label(i)) for i in range(1, n))) + '\n') ret += ''.join(('{!s:4}'.format(label(i)) for i in range(1, n))) return ret
class CartanType(CartanType_standard_untwisted_affine, CartanType_simply_laced): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['D',4,1])\n sage: ct\n ['D', 4, 1]\n sage: ct._repr_(compact = True)\n 'D4~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n True\n sage: ct.classical()\n ['D', 4]\n sage: ct.dual()\n ['D', 4, 1]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 3) CartanType_standard_untwisted_affine.__init__(self, 'D', n) def dynkin_diagram(self): "\n Returns the extended Dynkin diagram for affine type D.\n\n EXAMPLES::\n\n sage: d = CartanType(['D', 6, 1]).dynkin_diagram(); d # needs sage.graphs\n 0 O O 6\n | |\n | |\n O---O---O---O---O\n 1 2 3 4 5\n D6~\n sage: d.edges(sort=True) # needs sage.graphs\n [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 3, 1),\n (3, 2, 1), (3, 4, 1), (4, 3, 1), (4, 5, 1), (4, 6, 1), (5, 4, 1), (6, 4, 1)]\n\n sage: d = CartanType(['D', 4, 1]).dynkin_diagram(); d # needs sage.graphs\n O 4\n |\n |\n O---O---O\n 1 |2 3\n |\n O 0\n D4~\n sage: d.edges(sort=True) # needs sage.graphs\n [(0, 2, 1),\n (1, 2, 1),\n (2, 0, 1),\n (2, 1, 1),\n (2, 3, 1),\n (2, 4, 1),\n (3, 2, 1),\n (4, 2, 1)]\n\n sage: d = CartanType(['D', 3, 1]).dynkin_diagram(); d # needs sage.graphs\n 0\n O-------+\n | |\n | |\n O---O---O\n 3 1 2\n D3~\n sage: d.edges(sort=True) # needs sage.graphs\n [(0, 2, 1), (0, 3, 1), (1, 2, 1), (1, 3, 1),\n (2, 0, 1), (2, 1, 1), (3, 0, 1), (3, 1, 1)]\n\n " from .dynkin_diagram import DynkinDiagram_class n = self.n if (n == 3): from . import cartan_type res = cartan_type.CartanType(['A', 3, 1]).relabel({0: 0, 1: 3, 2: 1, 3: 2}).dynkin_diagram() res._cartan_type = self return res g = DynkinDiagram_class(self) for i in range(1, (n - 1)): g.add_edge(i, (i + 1)) g.add_edge((n - 2), n) g.add_edge(0, 2) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['D',4,1])._latex_dynkin_diagram())\n \\draw (0,0.7 cm) -- (2 cm,0);\n \\draw (0,-0.7 cm) -- (2 cm,0);\n \\draw (2 cm,0) -- (2 cm,0);\n \\draw (2 cm,0) -- (4 cm,0.7 cm);\n \\draw (2 cm,0) -- (4 cm,-0.7 cm);\n \\draw[fill=white] (0 cm, 0.7 cm) circle (.25cm) node[left=3pt]{$0$};\n \\draw[fill=white] (0 cm, -0.7 cm) circle (.25cm) node[left=3pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0.7 cm) circle (.25cm) node[right=3pt]{$4$};\n \\draw[fill=white] (4 cm, -0.7 cm) circle (.25cm) node[right=3pt]{$3$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node n = self.n if (n == 3): from . import cartan_type relabel = {0: label(0), 1: label(3), 2: label(1), 3: label(2)} return cartan_type.CartanType(['A', 3, 1]).relabel(relabel)._latex_dynkin_diagram(node_dist=node_dist) rt_most = ((n - 2) * node_dist) center_point = (rt_most - node_dist) ret = ('\\draw (0,0.7 cm) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (0,-0.7 cm) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (%s cm,0) -- (%s cm,0);\n' % (node_dist, center_point)) ret += ('\\draw (%s cm,0) -- (%s cm,0.7 cm);\n' % (center_point, rt_most)) ret += ('\\draw (%s cm,0) -- (%s cm,-0.7 cm);\n' % (center_point, rt_most)) ret += node(0, 0.7, label(0), 'left=3pt') ret += node(0, (- 0.7), label(1), 'left=3pt') for i in range(1, (self.n - 2)): ret += node((i * node_dist), 0, label((i + 1))) ret += node(rt_most, 0.7, label(n), 'right=3pt') ret += node(rt_most, (- 0.7), label((n - 1)), 'right=3pt') return ret def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the extended Dynkin diagram.\n\n TESTS::\n\n sage: print(CartanType(['D',6,1]).ascii_art(label = lambda x: x+2))\n 2 O O 8\n | |\n | |\n O---O---O---O---O\n 3 4 5 6 7\n\n sage: print(CartanType(['D',4,1]).ascii_art(label = lambda x: x+2))\n O 6\n |\n |\n O---O---O\n 3 |4 5\n |\n O 2\n\n sage: print(CartanType(['D',3,1]).ascii_art(label = lambda x: x+2))\n 2\n O-------+\n | |\n | |\n O---O---O\n 5 3 4\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node n = self.n if (n == 3): from . import cartan_type return cartan_type.CartanType(['A', 3, 1]).relabel({0: 0, 1: 3, 2: 1, 3: 2}).ascii_art(label, node) if (n == 4): ret = (' {} {}\n'.format(node(label(4)), label(4)) + ' |\n |\n') ret += '{}---{}---{}\n'.format(node(label(1)), node(label(2)), node(label(3))) ret += '{!s:4}|{!s:3}{!s:4}\n'.format(label(1), label(2), label(3)) ret += ' |\n {} {}'.format(node(label(0)), label(0)) return ret ret = '{!s:>3} {}'.format(label(0), node(label(0))) ret += ((((4 * (n - 4)) - 1) * ' ') + '{} {}\n'.format(node(label(n)), label(n))) ret += ((' |' + (((4 * (n - 4)) - 1) * ' ')) + '|\n') ret += ((' |' + (((4 * (n - 4)) - 1) * ' ')) + '|\n') ret += '---'.join((node(label(i)) for i in range(1, n))) ret += ('\n' + ''.join(('{!s:4}'.format(label(i)) for i in range(1, n)))) return ret
class AmbientSpace(ambient_space.AmbientSpace): '\n The lattice behind E6, E7, or E8. The computations are based on Bourbaki,\n Groupes et Algèbres de Lie, Ch. 4,5,6 (planche V-VII).\n ' def __init__(self, root_system, baseRing): "\n Create the ambient space for the root system for E6, E7, E8.\n Specify the Base, i.e., the simple roots w.r. to the canonical\n basis for R^8.\n\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: e == loads(dumps(e))\n True\n sage: [e.weyl_dimension(v) for v in e.fundamental_weights()]\n [27, 78, 351, 2925, 351, 27]\n sage: e = RootSystem(['E',7]).ambient_space()\n sage: [e.weyl_dimension(v) for v in e.fundamental_weights()]\n [133, 912, 8645, 365750, 27664, 1539, 56]\n sage: e = RootSystem(['E',8]).ambient_space()\n sage: [e.weyl_dimension(v) for v in e.fundamental_weights()]\n [3875, 147250, 6696000, 6899079264, 146325270, 2450240, 30380, 248]\n " v = (ZZ(1) / ZZ(2)) self.rank = root_system.cartan_type().rank() ambient_space.AmbientSpace.__init__(self, root_system, baseRing) if (self.rank == 6): self.Base = [(v * (self.root(0, 7) - self.root(1, 2, 3, 4, 5, 6))), self.root(0, 1), self.root(0, 1, p1=1), self.root(1, 2, p1=1), self.root(2, 3, p1=1), self.root(3, 4, p1=1)] elif (self.rank == 7): self.Base = [(v * (self.root(0, 7) - self.root(1, 2, 3, 4, 5, 6))), self.root(0, 1), self.root(0, 1, p1=1), self.root(1, 2, p1=1), self.root(2, 3, p1=1), self.root(3, 4, p1=1), self.root(4, 5, p1=1)] elif (self.rank == 8): self.Base = [(v * (self.root(0, 7) - self.root(1, 2, 3, 4, 5, 6))), self.root(0, 1), self.root(0, 1, p1=1), self.root(1, 2, p1=1), self.root(2, 3, p1=1), self.root(3, 4, p1=1), self.root(4, 5, p1=1), self.root(5, 6, p1=1)] else: raise NotImplementedError("Type 'E' root systems only come in flavors 6, 7, 8. Please make another choice") def dimension(self): "\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: e.dimension()\n 8\n " return 8 def root(self, i1, i2=None, i3=None, i4=None, i5=None, i6=None, i7=None, i8=None, p1=0, p2=0, p3=0, p4=0, p5=0, p6=0, p7=0, p8=0): "\n Compute an element of the underlying lattice, using the specified elements of\n the standard basis, with signs dictated by the corresponding 'pi' arguments.\n We rely on the caller to provide the correct arguments.\n This is typically used to generate roots, although the generated elements\n need not be roots themselves.\n We assume that if one of the indices is not given, the rest are not as well.\n This should work for E6, E7, E8.\n\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: [ e.root(i, j, p3=1) for i in range(e.n) for j in range(i+1, e.n) ]\n [(1, 1, 0, 0, 0, 0, 0, 0),\n (1, 0, 1, 0, 0, 0, 0, 0),\n (1, 0, 0, 1, 0, 0, 0, 0),\n (1, 0, 0, 0, 1, 0, 0, 0),\n (1, 0, 0, 0, 0, 1, 0, 0),\n (1, 0, 0, 0, 0, 0, 1, 0),\n (1, 0, 0, 0, 0, 0, 0, 1),\n (0, 1, 1, 0, 0, 0, 0, 0),\n (0, 1, 0, 1, 0, 0, 0, 0),\n (0, 1, 0, 0, 1, 0, 0, 0),\n (0, 1, 0, 0, 0, 1, 0, 0),\n (0, 1, 0, 0, 0, 0, 1, 0),\n (0, 1, 0, 0, 0, 0, 0, 1),\n (0, 0, 1, 1, 0, 0, 0, 0),\n (0, 0, 1, 0, 1, 0, 0, 0),\n (0, 0, 1, 0, 0, 1, 0, 0),\n (0, 0, 1, 0, 0, 0, 1, 0),\n (0, 0, 1, 0, 0, 0, 0, 1),\n (0, 0, 0, 1, 1, 0, 0, 0),\n (0, 0, 0, 1, 0, 1, 0, 0),\n (0, 0, 0, 1, 0, 0, 1, 0),\n (0, 0, 0, 1, 0, 0, 0, 1),\n (0, 0, 0, 0, 1, 1, 0, 0),\n (0, 0, 0, 0, 1, 0, 1, 0),\n (0, 0, 0, 0, 1, 0, 0, 1),\n (0, 0, 0, 0, 0, 1, 1, 0),\n (0, 0, 0, 0, 0, 1, 0, 1),\n (0, 0, 0, 0, 0, 0, 1, 1)]\n " if ((i1 == i2) or (i2 is None)): return (((- 1) ** p1) * self.monomial(i1)) if (i3 is None): return ((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) if (i4 is None): return (((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) if (i5 is None): return ((((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) + (((- 1) ** p4) * self.monomial(i4))) if (i6 is None): return (((((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) + (((- 1) ** p4) * self.monomial(i4))) + (((- 1) ** p5) * self.monomial(i5))) if (i7 is None): return ((((((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) + (((- 1) ** p4) * self.monomial(i4))) + (((- 1) ** p5) * self.monomial(i5))) + (((- 1) ** p6) * self.monomial(i6))) if (i8 is None): return (((((((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) + (((- 1) ** p4) * self.monomial(i4))) + (((- 1) ** p5) * self.monomial(i5))) + (((- 1) ** p6) * self.monomial(i6))) + (((- 1) ** p7) * self.monomial(i7))) return ((((((((((- 1) ** p1) * self.monomial(i1)) + (((- 1) ** p2) * self.monomial(i2))) + (((- 1) ** p3) * self.monomial(i3))) + (((- 1) ** p4) * self.monomial(i4))) + (((- 1) ** p5) * self.monomial(i5))) + (((- 1) ** p6) * self.monomial(i6))) + (((- 1) ** p7) * self.monomial(i7))) + (((- 1) ** p8) * self.monomial(i8))) def simple_root(self, i): "\n There are computed as what Bourbaki calls the Base:\n a1 = e2-e3, a2 = e3-e4, a3 = e4, a4 = 1/2*(e1-e2-e3-e4)\n\n EXAMPLES::\n\n sage: LE6 = RootSystem(['E',6]).ambient_space()\n sage: LE6.simple_roots()\n Finite family {1: (1/2, -1/2, -1/2, -1/2, -1/2, -1/2, -1/2, 1/2), 2: (1, 1, 0, 0, 0, 0, 0, 0), 3: (-1, 1, 0, 0, 0, 0, 0, 0), 4: (0, -1, 1, 0, 0, 0, 0, 0), 5: (0, 0, -1, 1, 0, 0, 0, 0), 6: (0, 0, 0, -1, 1, 0, 0, 0)}\n " if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) return self.Base[(i - 1)] def negative_roots(self): "\n The negative roots.\n\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: e.negative_roots()\n [(-1, -1, 0, 0, 0, 0, 0, 0),\n (-1, 0, -1, 0, 0, 0, 0, 0),\n (-1, 0, 0, -1, 0, 0, 0, 0),\n (-1, 0, 0, 0, -1, 0, 0, 0),\n (0, -1, -1, 0, 0, 0, 0, 0),\n (0, -1, 0, -1, 0, 0, 0, 0),\n (0, -1, 0, 0, -1, 0, 0, 0),\n (0, 0, -1, -1, 0, 0, 0, 0),\n (0, 0, -1, 0, -1, 0, 0, 0),\n (0, 0, 0, -1, -1, 0, 0, 0),\n (1, -1, 0, 0, 0, 0, 0, 0),\n (1, 0, -1, 0, 0, 0, 0, 0),\n (1, 0, 0, -1, 0, 0, 0, 0),\n (1, 0, 0, 0, -1, 0, 0, 0),\n (0, 1, -1, 0, 0, 0, 0, 0),\n (0, 1, 0, -1, 0, 0, 0, 0),\n (0, 1, 0, 0, -1, 0, 0, 0),\n (0, 0, 1, -1, 0, 0, 0, 0),\n (0, 0, 1, 0, -1, 0, 0, 0),\n (0, 0, 0, 1, -1, 0, 0, 0),\n (-1/2, -1/2, -1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, 1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, 1/2, -1/2, 1/2, 1/2, -1/2)]\n " return [(- a) for a in self.positive_roots()] def positive_roots(self): "\n These are the roots positive w.r. to lexicographic ordering of the\n basis elements (e1<...<e4).\n\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: e.positive_roots()\n [(1, 1, 0, 0, 0, 0, 0, 0),\n (1, 0, 1, 0, 0, 0, 0, 0),\n (1, 0, 0, 1, 0, 0, 0, 0),\n (1, 0, 0, 0, 1, 0, 0, 0),\n (0, 1, 1, 0, 0, 0, 0, 0),\n (0, 1, 0, 1, 0, 0, 0, 0),\n (0, 1, 0, 0, 1, 0, 0, 0),\n (0, 0, 1, 1, 0, 0, 0, 0),\n (0, 0, 1, 0, 1, 0, 0, 0),\n (0, 0, 0, 1, 1, 0, 0, 0),\n (-1, 1, 0, 0, 0, 0, 0, 0),\n (-1, 0, 1, 0, 0, 0, 0, 0),\n (-1, 0, 0, 1, 0, 0, 0, 0),\n (-1, 0, 0, 0, 1, 0, 0, 0),\n (0, -1, 1, 0, 0, 0, 0, 0),\n (0, -1, 0, 1, 0, 0, 0, 0),\n (0, -1, 0, 0, 1, 0, 0, 0),\n (0, 0, -1, 1, 0, 0, 0, 0),\n (0, 0, -1, 0, 1, 0, 0, 0),\n (0, 0, 0, -1, 1, 0, 0, 0),\n (1/2, 1/2, 1/2, 1/2, 1/2, -1/2, -1/2, 1/2),\n (1/2, 1/2, 1/2, -1/2, -1/2, -1/2, -1/2, 1/2),\n (1/2, 1/2, -1/2, 1/2, -1/2, -1/2, -1/2, 1/2),\n (1/2, 1/2, -1/2, -1/2, 1/2, -1/2, -1/2, 1/2),\n (1/2, -1/2, 1/2, 1/2, -1/2, -1/2, -1/2, 1/2),\n (1/2, -1/2, 1/2, -1/2, 1/2, -1/2, -1/2, 1/2),\n (1/2, -1/2, -1/2, 1/2, 1/2, -1/2, -1/2, 1/2),\n (1/2, -1/2, -1/2, -1/2, -1/2, -1/2, -1/2, 1/2),\n (-1/2, 1/2, 1/2, 1/2, -1/2, -1/2, -1/2, 1/2),\n (-1/2, 1/2, 1/2, -1/2, 1/2, -1/2, -1/2, 1/2),\n (-1/2, 1/2, -1/2, 1/2, 1/2, -1/2, -1/2, 1/2),\n (-1/2, 1/2, -1/2, -1/2, -1/2, -1/2, -1/2, 1/2),\n (-1/2, -1/2, 1/2, 1/2, 1/2, -1/2, -1/2, 1/2),\n (-1/2, -1/2, 1/2, -1/2, -1/2, -1/2, -1/2, 1/2),\n (-1/2, -1/2, -1/2, 1/2, -1/2, -1/2, -1/2, 1/2),\n (-1/2, -1/2, -1/2, -1/2, 1/2, -1/2, -1/2, 1/2)]\n sage: e.rho()\n (0, 1, 2, 3, 4, -4, -4, 4)\n sage: E8 = RootSystem(['E',8])\n sage: e = E8.ambient_space()\n sage: e.negative_roots()\n [(-1, -1, 0, 0, 0, 0, 0, 0),\n (-1, 0, -1, 0, 0, 0, 0, 0),\n (-1, 0, 0, -1, 0, 0, 0, 0),\n (-1, 0, 0, 0, -1, 0, 0, 0),\n (-1, 0, 0, 0, 0, -1, 0, 0),\n (-1, 0, 0, 0, 0, 0, -1, 0),\n (-1, 0, 0, 0, 0, 0, 0, -1),\n (0, -1, -1, 0, 0, 0, 0, 0),\n (0, -1, 0, -1, 0, 0, 0, 0),\n (0, -1, 0, 0, -1, 0, 0, 0),\n (0, -1, 0, 0, 0, -1, 0, 0),\n (0, -1, 0, 0, 0, 0, -1, 0),\n (0, -1, 0, 0, 0, 0, 0, -1),\n (0, 0, -1, -1, 0, 0, 0, 0),\n (0, 0, -1, 0, -1, 0, 0, 0),\n (0, 0, -1, 0, 0, -1, 0, 0),\n (0, 0, -1, 0, 0, 0, -1, 0),\n (0, 0, -1, 0, 0, 0, 0, -1),\n (0, 0, 0, -1, -1, 0, 0, 0),\n (0, 0, 0, -1, 0, -1, 0, 0),\n (0, 0, 0, -1, 0, 0, -1, 0),\n (0, 0, 0, -1, 0, 0, 0, -1),\n (0, 0, 0, 0, -1, -1, 0, 0),\n (0, 0, 0, 0, -1, 0, -1, 0),\n (0, 0, 0, 0, -1, 0, 0, -1),\n (0, 0, 0, 0, 0, -1, -1, 0),\n (0, 0, 0, 0, 0, -1, 0, -1),\n (0, 0, 0, 0, 0, 0, -1, -1),\n (1, -1, 0, 0, 0, 0, 0, 0),\n (1, 0, -1, 0, 0, 0, 0, 0),\n (1, 0, 0, -1, 0, 0, 0, 0),\n (1, 0, 0, 0, -1, 0, 0, 0),\n (1, 0, 0, 0, 0, -1, 0, 0),\n (1, 0, 0, 0, 0, 0, -1, 0),\n (1, 0, 0, 0, 0, 0, 0, -1),\n (0, 1, -1, 0, 0, 0, 0, 0),\n (0, 1, 0, -1, 0, 0, 0, 0),\n (0, 1, 0, 0, -1, 0, 0, 0),\n (0, 1, 0, 0, 0, -1, 0, 0),\n (0, 1, 0, 0, 0, 0, -1, 0),\n (0, 1, 0, 0, 0, 0, 0, -1),\n (0, 0, 1, -1, 0, 0, 0, 0),\n (0, 0, 1, 0, -1, 0, 0, 0),\n (0, 0, 1, 0, 0, -1, 0, 0),\n (0, 0, 1, 0, 0, 0, -1, 0),\n (0, 0, 1, 0, 0, 0, 0, -1),\n (0, 0, 0, 1, -1, 0, 0, 0),\n (0, 0, 0, 1, 0, -1, 0, 0),\n (0, 0, 0, 1, 0, 0, -1, 0),\n (0, 0, 0, 1, 0, 0, 0, -1),\n (0, 0, 0, 0, 1, -1, 0, 0),\n (0, 0, 0, 0, 1, 0, -1, 0),\n (0, 0, 0, 0, 1, 0, 0, -1),\n (0, 0, 0, 0, 0, 1, -1, 0),\n (0, 0, 0, 0, 0, 1, 0, -1),\n (0, 0, 0, 0, 0, 0, 1, -1),\n (-1/2, -1/2, -1/2, -1/2, -1/2, -1/2, -1/2, -1/2),\n (-1/2, -1/2, -1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, -1/2, -1/2, 1/2, -1/2, 1/2, -1/2),\n (-1/2, -1/2, -1/2, -1/2, 1/2, 1/2, -1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2, -1/2, -1/2, 1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2, -1/2, 1/2, -1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2, 1/2, -1/2, -1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, -1/2, -1/2, -1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, -1/2, -1/2, 1/2, -1/2, -1/2),\n (-1/2, -1/2, 1/2, -1/2, 1/2, -1/2, -1/2, -1/2),\n (-1/2, -1/2, 1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2, -1/2, -1/2, -1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2, 1/2, -1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2, 1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, -1/2, -1/2, -1/2, -1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, -1/2, -1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, -1/2, -1/2, 1/2, -1/2, -1/2, -1/2),\n (-1/2, 1/2, -1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2, -1/2, -1/2, -1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2, 1/2, -1/2, 1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2, 1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, 1/2, -1/2, -1/2, -1/2, -1/2, -1/2),\n (-1/2, 1/2, 1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, -1/2, 1/2, -1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, -1/2, 1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2, -1/2, -1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2, -1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2, 1/2, -1/2, -1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, -1/2, -1/2, -1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, -1/2, -1/2, 1/2, -1/2, -1/2),\n (1/2, -1/2, -1/2, -1/2, 1/2, -1/2, -1/2, -1/2),\n (1/2, -1/2, -1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2, -1/2, -1/2, -1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2, 1/2, -1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2, 1/2, 1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, -1/2, -1/2, -1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, -1/2, 1/2, -1/2, 1/2, -1/2, 1/2, -1/2),\n (1/2, -1/2, 1/2, -1/2, 1/2, 1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2, -1/2, -1/2, 1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2, -1/2, 1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2, 1/2, -1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, -1/2, -1/2, -1/2, -1/2, -1/2),\n (1/2, 1/2, -1/2, -1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, -1/2, 1/2, -1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, -1/2, 1/2, 1/2, -1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2, -1/2, -1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2, -1/2, 1/2, -1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2, 1/2, -1/2, -1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, -1/2, -1/2, -1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, -1/2, -1/2, 1/2, -1/2, -1/2),\n (1/2, 1/2, 1/2, -1/2, 1/2, -1/2, -1/2, -1/2),\n (1/2, 1/2, 1/2, -1/2, 1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, 1/2, -1/2, -1/2, -1/2, -1/2),\n (1/2, 1/2, 1/2, 1/2, -1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, 1/2, 1/2, -1/2, 1/2, -1/2),\n (1/2, 1/2, 1/2, 1/2, 1/2, 1/2, -1/2, -1/2)]\n sage: e.rho()\n (0, 1, 2, 3, 4, 5, 6, 23)\n\n " v = (ZZ(1) / ZZ(2)) if (not hasattr(self, 'PosRoots')): if (self.rank == 6): self.PosRoots = (([self.root(i, j) for i in range((self.rank - 1)) for j in range((i + 1), (self.rank - 1))] + [self.root(i, j, p1=1) for i in range((self.rank - 1)) for j in range((i + 1), (self.rank - 1))]) + [(v * (((self.root(7) - self.root(6)) - self.root(5)) + self.root(0, 1, 2, 3, 4, p1=p1, p2=p2, p3=p3, p4=p4, p5=p5))) for p1 in [0, 1] for p2 in [0, 1] for p3 in [0, 1] for p4 in [0, 1] for p5 in [0, 1] if ((((((p1 + p2) + p3) + p4) + p5) % 2) == 0)]) elif (self.rank == 7): self.PosRoots = ((([self.root(i, j) for i in range((self.rank - 1)) for j in range((i + 1), (self.rank - 1))] + [self.root(i, j, p1=1) for i in range((self.rank - 1)) for j in range((i + 1), (self.rank - 1))]) + [self.root(6, 7, p1=1)]) + [(v * ((self.root(7) - self.root(6)) + self.root(0, 1, 2, 3, 4, 5, p1=p1, p2=p2, p3=p3, p4=p4, p5=p5, p6=p6))) for p1 in [0, 1] for p2 in [0, 1] for p3 in [0, 1] for p4 in [0, 1] for p5 in [0, 1] for p6 in [0, 1] if (((((((p1 + p2) + p3) + p4) + p5) + p6) % 2) == 1)]) elif (self.rank == 8): self.PosRoots = (([self.root(i, j) for i in range(self.rank) for j in range((i + 1), self.rank)] + [self.root(i, j, p1=1) for i in range(self.rank) for j in range((i + 1), self.rank)]) + [(v * (self.root(7) + self.root(0, 1, 2, 3, 4, 5, 6, p1=p1, p2=p2, p3=p3, p4=p4, p5=p5, p6=p6, p7=p7))) for p1 in [0, 1] for p2 in [0, 1] for p3 in [0, 1] for p4 in [0, 1] for p5 in [0, 1] for p6 in [0, 1] for p7 in [0, 1] if ((((((((p1 + p2) + p3) + p4) + p5) + p6) + p7) % 2) == 0)]) return self.PosRoots def fundamental_weights(self): "\n EXAMPLES::\n\n sage: e = RootSystem(['E',6]).ambient_space()\n sage: e.fundamental_weights()\n Finite family {1: (0, 0, 0, 0, 0, -2/3, -2/3, 2/3), 2: (1/2, 1/2, 1/2, 1/2, 1/2, -1/2, -1/2, 1/2), 3: (-1/2, 1/2, 1/2, 1/2, 1/2, -5/6, -5/6, 5/6), 4: (0, 0, 1, 1, 1, -1, -1, 1), 5: (0, 0, 0, 1, 1, -2/3, -2/3, 2/3), 6: (0, 0, 0, 0, 1, -1/3, -1/3, 1/3)}\n " v2 = (ZZ(1) / ZZ(2)) v3 = (ZZ(1) / ZZ(3)) if (self.rank == 6): return Family({1: ((2 * v3) * self.root(7, 6, 5, p2=1, p3=1)), 2: (v2 * self.root(0, 1, 2, 3, 4, 5, 6, 7, p6=1, p7=1)), 3: ((((5 * v2) * v3) * self.root(7, 6, 5, p2=1, p3=1)) + (v2 * self.root(0, 1, 2, 3, 4, p1=1))), 4: self.root(2, 3, 4, 5, 6, 7, p4=1, p5=1), 5: (((2 * v3) * self.root(7, 6, 5, p2=1, p3=1)) + self.root(3, 4)), 6: ((v3 * self.root(7, 6, 5, p2=1, p3=1)) + self.root(4))}) elif (self.rank == 7): return Family({1: self.root(7, 6, p2=1), 2: ((v2 * self.root(0, 1, 2, 3, 4, 5)) + self.root(6, 7, p1=1)), 3: (v2 * (self.root(0, 1, 2, 3, 4, 5, p1=1) + (3 * self.root(6, 7, p1=1)))), 4: (self.root(2, 3, 4, 5) + (2 * self.root(6, 7, p1=1))), 5: (((3 * v2) * self.root(6, 7, p1=1)) + self.root(3, 4, 5)), 6: self.root(4, 5, 6, 7, p3=1), 7: (self.root(5) + (v2 * self.root(6, 7, p1=1)))}) elif (self.rank == 8): return Family({1: (2 * self.root(7)), 2: (v2 * (self.root(0, 1, 2, 3, 4, 5, 6) + (5 * self.root(7)))), 3: (v2 * (self.root(0, 1, 2, 3, 4, 5, 6, p1=1) + (7 * self.root(7)))), 4: (self.root(2, 3, 4, 5, 6) + (5 * self.root(7))), 5: (self.root(3, 4, 5, 6) + (4 * self.root(7))), 6: (self.root(4, 5, 6) + (3 * self.root(7))), 7: (self.root(5, 6) + (2 * self.root(7))), 8: self.root(6, 7)})
class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_simply_laced): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['E',6])\n sage: ct\n ['E', 6]\n sage: ct._repr_(compact = True)\n 'E6'\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_affine()\n False\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n True\n sage: ct.affine()\n ['E', 6, 1]\n sage: ct.dual()\n ['E', 6]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " if ((n < 6) or (n > 8)): raise ValueError('Invalid Cartan Type for Type E') CartanType_standard_finite.__init__(self, 'E', n) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['E',7]))\n E_7\n " return ('E_%s' % self.n) AmbientSpace = AmbientSpace def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['E',6]).coxeter_number()\n 12\n sage: CartanType(['E',7]).coxeter_number()\n 18\n sage: CartanType(['E',8]).coxeter_number()\n 30\n " if (self.n == 6): return 12 if (self.n == 7): return 18 return 30 def dual_coxeter_number(self): "\n Return the dual Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['E',6]).dual_coxeter_number()\n 12\n sage: CartanType(['E',7]).dual_coxeter_number()\n 18\n sage: CartanType(['E',8]).dual_coxeter_number()\n 30\n " if (self.n == 6): return 12 if (self.n == 7): return 18 return 30 def dynkin_diagram(self): "\n Returns a Dynkin diagram for type E.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: e = CartanType(['E',6]).dynkin_diagram(); e\n O 2\n |\n |\n O---O---O---O---O\n 1 3 4 5 6\n E6\n sage: e.edges(sort=True)\n [(1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1),\n (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1)]\n sage: e = CartanType(['E',7]).dynkin_diagram(); e\n O 2\n |\n |\n O---O---O---O---O---O\n 1 3 4 5 6 7\n E7\n sage: e.edges(sort=True)\n [(1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1),\n (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1),\n (6, 7, 1), (7, 6, 1)]\n sage: e = CartanType(['E',8]).dynkin_diagram(); e\n O 2\n |\n |\n O---O---O---O---O---O---O\n 1 3 4 5 6 7 8\n E8\n sage: e.edges(sort=True)\n [(1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1), (4, 2, 1),\n (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1), (6, 5, 1),\n (6, 7, 1), (7, 6, 1), (7, 8, 1), (8, 7, 1)]\n\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) g.add_edge(1, 3) g.add_edge(2, 4) for i in range(3, self.n): g.add_edge(i, (i + 1)) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['E',7])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (10 cm,0);\n \\draw (4 cm, 0 cm) -- +(0,2 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$5$};\n \\draw[fill=white] (8 cm, 0 cm) circle (.25cm) node[below=4pt]{$6$};\n \\draw[fill=white] (10 cm, 0 cm) circle (.25cm) node[below=4pt]{$7$};\n \\draw[fill=white] (4 cm, 2 cm) circle (.25cm) node[right=3pt]{$2$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % ((self.n - 2) * node_dist)) ret += ('\\draw (%s cm, 0 cm) -- +(0,%s cm);\n' % ((2 * node_dist), node_dist)) ret += node(0, 0, label(1)) for i in range(1, (self.n - 1)): ret += node((i * node_dist), 0, label((i + 2))) ret += node((2 * node_dist), node_dist, label(2), 'right=3pt') return ret def ascii_art(self, label=None, node=None): "\n Return a ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['E',6]).ascii_art(label = lambda x: x+2))\n O 4\n |\n |\n O---O---O---O---O\n 3 5 6 7 8\n sage: print(CartanType(['E',7]).ascii_art(label = lambda x: x+2))\n O 4\n |\n |\n O---O---O---O---O---O\n 3 5 6 7 8 9\n sage: print(CartanType(['E',8]).ascii_art(label = lambda x: x+1))\n O 3\n |\n |\n O---O---O---O---O---O---O\n 2 4 5 6 7 8 9\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node labels = [label(i) for i in ([1, 3, 4, 5, 6] + list(range(7, (self.n + 1))))] ret = ' {} {}\n |\n |\n'.format(node(label(2)), label(2)) return (((ret + '---'.join((node(i) for i in labels))) + '\n') + ''.join(('{!s:4}'.format(i) for i in labels)))
class CartanType(CartanType_standard_untwisted_affine, CartanType_simply_laced): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['E',6,1])\n sage: ct\n ['E', 6, 1]\n sage: ct._repr_(compact = True)\n 'E6~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n True\n sage: ct.classical()\n ['E', 6]\n sage: ct.dual()\n ['E', 6, 1]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " if ((n < 6) or (n > 8)): raise ValueError('Invalid Cartan Type for Type E') CartanType_standard_untwisted_affine.__init__(self, 'E', n) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['E',7,1]))\n E_7^{(1)}\n " return ('E_%s^{(1)}' % self.n) def dynkin_diagram(self): "\n Returns the extended Dynkin diagram for affine type E.\n\n EXAMPLES::\n\n sage: e = CartanType(['E', 6, 1]).dynkin_diagram(); e # needs sage.graphs\n O 0\n |\n |\n O 2\n |\n |\n O---O---O---O---O\n 1 3 4 5 6\n E6~\n sage: e.edges(sort=True) # needs sage.graphs\n [(0, 2, 1),\n (1, 3, 1),\n (2, 0, 1),\n (2, 4, 1),\n (3, 1, 1),\n (3, 4, 1),\n (4, 2, 1),\n (4, 3, 1),\n (4, 5, 1),\n (5, 4, 1),\n (5, 6, 1),\n (6, 5, 1)]\n\n sage: # needs sage.graphs\n sage: e = CartanType(['E', 7, 1]).dynkin_diagram(); e\n O 2\n |\n |\n O---O---O---O---O---O---O\n 0 1 3 4 5 6 7\n E7~\n sage: e.edges(sort=True)\n [(0, 1, 1), (1, 0, 1), (1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1),\n (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1),\n (6, 5, 1), (6, 7, 1), (7, 6, 1)]\n sage: e = CartanType(['E', 8, 1]).dynkin_diagram(); e\n O 2\n |\n |\n O---O---O---O---O---O---O---O\n 1 3 4 5 6 7 8 0\n E8~\n sage: e.edges(sort=True)\n [(0, 8, 1), (1, 3, 1), (2, 4, 1), (3, 1, 1), (3, 4, 1),\n (4, 2, 1), (4, 3, 1), (4, 5, 1), (5, 4, 1), (5, 6, 1),\n (6, 5, 1), (6, 7, 1), (7, 6, 1), (7, 8, 1), (8, 0, 1), (8, 7, 1)]\n\n " from .dynkin_diagram import DynkinDiagram_class n = self.n g = DynkinDiagram_class(self) g.add_edge(1, 3) g.add_edge(2, 4) for i in range(3, n): g.add_edge(i, (i + 1)) if (n == 6): g.add_edge(0, 2) elif (n == 7): g.add_edge(0, 1) elif (n == 8): g.add_edge(0, 8) else: raise ValueError('Invalid Cartan Type for Type E affine') return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['E',7,1])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (12 cm,0);\n \\draw (6 cm, 0 cm) -- +(0,2 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n \\draw[fill=white] (8 cm, 0 cm) circle (.25cm) node[below=4pt]{$5$};\n \\draw[fill=white] (10 cm, 0 cm) circle (.25cm) node[below=4pt]{$6$};\n \\draw[fill=white] (12 cm, 0 cm) circle (.25cm) node[below=4pt]{$7$};\n \\draw[fill=white] (6 cm, 2 cm) circle (.25cm) node[right=3pt]{$2$};\n <BLANKLINE>\n " n = self.n if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node if (n == 7): ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % ((n - 1) * node_dist)) ret += ('\\draw (%s cm, 0 cm) -- +(0,%s cm);\n' % ((3 * node_dist), node_dist)) ret += node(0, 0, label(0)) ret += node(node_dist, 0, label(1)) for i in range(2, n): ret += node((i * node_dist), 0, label((i + 1))) ret += node((3 * node_dist), node_dist, label(2), 'right=3pt') return ret ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % ((n - 2) * node_dist)) ret += ('\\draw (%s cm, 0 cm) -- +(0,%s cm);\n' % ((2 * node_dist), node_dist)) if (n == 6): ret += ('\\draw (%s cm, %s cm) -- +(0,%s cm);\n' % ((2 * node_dist), node_dist, node_dist)) ret += node((2 * node_dist), (2 * node_dist), label(0), 'right=3pt') else: ret += ('\\draw (%s cm,0) -- +(%s cm,0);\n' % (((n - 2) * node_dist), node_dist)) ret += node(((n - 1) * node_dist), 0, label(0)) ret += node(0, 0, label(1)) for i in range(1, (n - 1)): ret += node((i * node_dist), 0, label((i + 2))) ret += node((2 * node_dist), node_dist, label(2), 'right=3pt') return ret def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['E',6,1]).ascii_art(label = lambda x: x+2))\n O 2\n |\n |\n O 4\n |\n |\n O---O---O---O---O\n 3 5 6 7 8\n sage: print(CartanType(['E',7,1]).ascii_art(label = lambda x: x+2))\n O 4\n |\n |\n O---O---O---O---O---O---O\n 2 3 5 6 7 8 9\n sage: print(CartanType(['E',8,1]).ascii_art(label = lambda x: x-3))\n O -1\n |\n |\n O---O---O---O---O---O---O---O\n -2 0 1 2 3 4 5 -3\n " n = self.n if (label is None): label = (lambda x: x) if (node is None): node = self._ascii_art_node if (n == 6): ret = ' {} {}\n |\n |\n'.format(node(label(0)), label(0)) return (ret + self.classical().ascii_art(label, node)) elif (n == 7): ret = ' {} {}\n |\n |\n'.format(node(label(2)), label(2)) labels = [label(i) for i in [0, 1, 3, 4, 5, 6, 7]] nodes = [node(i) for i in labels] return (((ret + '---'.join((n for n in nodes))) + '\n') + ''.join(('{!s:4}'.format(i) for i in labels))) elif (n == 8): ret = ' {} {}\n |\n |\n'.format(node(label(2)), label(2)) labels = [label(i) for i in [1, 3, 4, 5, 6, 7, 8, 0]] nodes = [node(i) for i in labels] return (((ret + '---'.join((n for n in nodes))) + '\n') + ''.join(('{!s:4}'.format(i) for i in labels)))
class AmbientSpace(ambient_space.AmbientSpace): '\n The lattice behind `F_4`. The computations are based on Bourbaki,\n Groupes et Algèbres de Lie, Ch. 4,5,6 (planche VIII).\n ' def __init__(self, root_system, base_ring): "\n Initialize the ambient lattice for the root system of type `F_4`.\n\n This essentially initializes ``Base`` with the coordinates of\n the simple roots in the canonical basis for `\\RR^4`.\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n\n TESTS::\n\n sage: TestSuite(e).run() # needs sage.graphs\n " ambient_space.AmbientSpace.__init__(self, root_system, base_ring) v = (ZZ(1) / ZZ(2)) self.Base = [self.root(1, 2, p2=1), self.root(2, 3, p2=1), self.root(3), (v * (((self.root(0) - self.root(1)) - self.root(2)) - self.root(3)))] def dimension(self): "\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: e.dimension()\n 4\n " return self.root_system.cartan_type().rank() def root(self, i, j=None, k=None, l=None, p1=0, p2=0, p3=0, p4=0): "\n Compute a root from base elements of the underlying lattice.\n The arguments specify the basis elements and the signs.\n Sadly, the base elements are indexed zero-based.\n We assume that if one of the indices is not given, the rest are not as well.\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: [ e.root(i,j,p2=1) for i in range(e.n) for j in range(i+1,e.n) ]\n [(1, -1, 0, 0), (1, 0, -1, 0), (1, 0, 0, -1), (0, 1, -1, 0), (0, 1, 0, -1), (0, 0, 1, -1)]\n " if ((i == j) or (j is None)): return (((- 1) ** p1) * self.monomial(i)) if (k is None): return ((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) if (l is None): return (((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) + (((- 1) ** p3) * self.monomial(k))) return ((((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) + (((- 1) ** p3) * self.monomial(k))) + (((- 1) ** p4) * self.monomial(l))) def simple_root(self, i): "\n Return the `i`-th simple root.\n\n It is computed according to what Bourbaki calls the Base:\n\n .. MATH::\n\n \\alpha_1 = \\epsilon_2-\\epsilon_3,\n \\alpha_2 = \\epsilon_3-\\epsilon_4,\n \\alpha_3 = \\epsilon_4,\n \\alpha_4 = \\frac{1}{2} \\left( \\epsilon_1-\\epsilon_2-\\epsilon_3-\\epsilon_4 \\right).\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: e.simple_roots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 1), 4: (1/2, -1/2, -1/2, -1/2)}\n " return self.Base[(i - 1)] def negative_roots(self): "\n Return the negative roots.\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: e.negative_roots()\n [(-1, 0, 0, 0),\n (0, -1, 0, 0),\n (0, 0, -1, 0),\n (0, 0, 0, -1),\n (-1, -1, 0, 0),\n (-1, 0, -1, 0),\n (-1, 0, 0, -1),\n (0, -1, -1, 0),\n (0, -1, 0, -1),\n (0, 0, -1, -1),\n (-1, 1, 0, 0),\n (-1, 0, 1, 0),\n (-1, 0, 0, 1),\n (0, -1, 1, 0),\n (0, -1, 0, 1),\n (0, 0, -1, 1),\n (-1/2, -1/2, -1/2, -1/2),\n (-1/2, -1/2, -1/2, 1/2),\n (-1/2, -1/2, 1/2, -1/2),\n (-1/2, -1/2, 1/2, 1/2),\n (-1/2, 1/2, -1/2, -1/2),\n (-1/2, 1/2, -1/2, 1/2),\n (-1/2, 1/2, 1/2, -1/2),\n (-1/2, 1/2, 1/2, 1/2)]\n " return [(- a) for a in self.positive_roots()] def positive_roots(self): "\n Return the positive roots.\n\n These are the roots which are positive with respect to the\n lexicographic ordering of the basis elements\n (`\\epsilon_1<\\epsilon_2<\\epsilon_3<\\epsilon_4`).\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: e.positive_roots()\n [(1, 0, 0, 0),\n (0, 1, 0, 0),\n (0, 0, 1, 0),\n (0, 0, 0, 1),\n (1, 1, 0, 0),\n (1, 0, 1, 0),\n (1, 0, 0, 1),\n (0, 1, 1, 0),\n (0, 1, 0, 1),\n (0, 0, 1, 1),\n (1, -1, 0, 0),\n (1, 0, -1, 0),\n (1, 0, 0, -1),\n (0, 1, -1, 0),\n (0, 1, 0, -1),\n (0, 0, 1, -1),\n (1/2, 1/2, 1/2, 1/2),\n (1/2, 1/2, 1/2, -1/2),\n (1/2, 1/2, -1/2, 1/2),\n (1/2, 1/2, -1/2, -1/2),\n (1/2, -1/2, 1/2, 1/2),\n (1/2, -1/2, 1/2, -1/2),\n (1/2, -1/2, -1/2, 1/2),\n (1/2, -1/2, -1/2, -1/2)]\n sage: e.rho()\n (11/2, 5/2, 3/2, 1/2)\n " v = (ZZ(1) / ZZ(2)) if (not hasattr(self, 'PosRoots')): self.PosRoots = ((([self.monomial(i) for i in range(self.n)] + [self.root(i, j, p2=0) for i in range(self.n) for j in range((i + 1), self.n)]) + [self.root(i, j, p2=1) for i in range(self.n) for j in range((i + 1), self.n)]) + [(v * self.root(0, 1, 2, 3, 0, p2, p3, p4)) for p2 in [0, 1] for p3 in [0, 1] for p4 in [0, 1]]) return self.PosRoots def fundamental_weights(self): "\n Return the fundamental weights of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['F',4]).ambient_space()\n sage: e.fundamental_weights()\n Finite family {1: (1, 1, 0, 0), 2: (2, 1, 1, 0), 3: (3/2, 1/2, 1/2, 1/2), 4: (1, 0, 0, 0)}\n " v = (ZZ(1) / ZZ(2)) return Family({1: (self.monomial(0) + self.monomial(1)), 2: (((2 * self.monomial(0)) + self.monomial(1)) + self.monomial(2)), 3: (v * ((((3 * self.monomial(0)) + self.monomial(1)) + self.monomial(2)) + self.monomial(3))), 4: self.monomial(0)})
class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F',4])\n sage: ct\n ['F', 4]\n sage: ct._repr_(compact = True)\n 'F4'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.dual()\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n sage: ct.affine()\n ['F', 4, 1]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " CartanType_standard_finite.__init__(self, 'F', 4) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['F',4]))\n F_4\n sage: latex(CartanType(['F',4]).dual())\n F_4 \\text{ relabelled by } \\left\\{1 : 4, 2 : 3, 3 : 2, 4 : 1\\right\\}\n " return 'F_4' AmbientSpace = AmbientSpace def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['F',4]).coxeter_number()\n 12\n " return 12 def dual_coxeter_number(self): "\n Return the dual Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['F',4]).dual_coxeter_number()\n 9\n " return 9 def dynkin_diagram(self): "\n Returns a Dynkin diagram for type F.\n\n EXAMPLES::\n\n sage: f = CartanType(['F',4]).dynkin_diagram(); f # needs sage.graphs\n O---O=>=O---O\n 1 2 3 4\n F4\n sage: f.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 1), (2, 3, 2), (3, 2, 1), (3, 4, 1), (4, 3, 1)]\n\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, 4): g.add_edge(i, (i + 1)) g.set_edge_label(2, 3, 2) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['F',4])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (2 cm,0);\n \\draw (2 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (2 cm, -0.1 cm) -- +(2 cm,0);\n \\draw (4.0 cm,0) -- +(2 cm,0);\n \\draw[shift={(3.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (%s cm, 0.1 cm) -- +(%s cm,0);\n' % (node_dist, node_dist)) ret += ('\\draw (%s cm, -0.1 cm) -- +(%s cm,0);\n' % (node_dist, node_dist)) ret += ('\\draw (%s cm,0) -- +(%s cm,0);\n' % ((node_dist * 2.0), node_dist)) if dual: ret += self._latex_draw_arrow_tip(((1.5 * node_dist) - 0.2), 0, 180) else: ret += self._latex_draw_arrow_tip(((1.5 * node_dist) + 0.2), 0, 0) for i in range(4): ret += node((i * node_dist), 0, label((i + 1))) return ret def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the extended Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['F',4]).ascii_art(label = lambda x: x+2))\n O---O=>=O---O\n 3 4 5 6\n sage: print(CartanType(['F',4]).ascii_art(label = lambda x: x-2))\n O---O=>=O---O\n -1 0 1 2\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node ret = '{}---{}=>={}---{}\n'.format(node(label(1)), node(label(2)), node(label(3)), node(label(4))) ret += ('{!s:4}' * 4).format(label(1), label(2), label(3), label(4)) return ret def dual(self): "\n Return the dual Cartan type.\n\n This uses that `F_4` is self-dual up to relabelling.\n\n EXAMPLES::\n\n sage: F4 = CartanType(['F',4])\n sage: F4.dual()\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n\n sage: F4.dynkin_diagram() # needs sage.graphs\n O---O=>=O---O\n 1 2 3 4\n F4\n sage: F4.dual().dynkin_diagram() # needs sage.graphs\n O---O=>=O---O\n 4 3 2 1\n F4 relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n " return self.relabel({1: 4, 2: 3, 3: 2, 4: 1}) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['F', 4])._default_folded_cartan_type()\n ['F', 4] as a folding of ['E', 6]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['E', 6], [[2], [4], [3, 5], [1, 6]])
class CartanType(CartanType_standard_untwisted_affine): def __init__(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F',4,1])\n sage: ct\n ['F', 4, 1]\n sage: ct._repr_(compact = True)\n 'F4~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.classical()\n ['F', 4]\n sage: ct.dual()\n ['F', 4, 1]^*\n sage: ct.dual().is_untwisted_affine()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " CartanType_standard_untwisted_affine.__init__(self, 'F', 4) def dynkin_diagram(self): "\n Returns the extended Dynkin diagram for affine type F.\n\n EXAMPLES::\n\n sage: f = CartanType(['F', 4, 1]).dynkin_diagram(); f # needs sage.graphs\n O---O---O=>=O---O\n 0 1 2 3 4\n F4~\n sage: f.edges(sort=True) # needs sage.graphs\n [(0, 1, 1), (1, 0, 1), (1, 2, 1), (2, 1, 1),\n (2, 3, 2), (3, 2, 1), (3, 4, 1), (4, 3, 1)]\n\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) for i in range(1, 4): g.add_edge(i, (i + 1)) g.set_edge_label(2, 3, 2) g.add_edge(0, 1) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['F',4,1])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (2 cm,0);\n {\n \\pgftransformxshift{2 cm}\n \\draw (0 cm,0) -- (2 cm,0);\n \\draw (2 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (2 cm, -0.1 cm) -- +(2 cm,0);\n \\draw (4.0 cm,0) -- +(2 cm,0);\n \\draw[shift={(3.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n }\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node ret = ('\\draw (0 cm,0) -- (%s cm,0);\n' % node_dist) ret += ('{\n\\pgftransformxshift{%s cm}\n' % node_dist) ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += ('}\n' + node(0, 0, label(0))) return ret def ascii_art(self, label=None, node=None): "\n Returns a ascii art representation of the extended Dynkin diagram\n\n EXAMPLES::\n\n sage: print(CartanType(['F',4,1]).ascii_art(label = lambda x: x+2))\n O---O---O=>=O---O\n 2 3 4 5 6\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node ret = '{}---{}---{}=>={}---{}\n'.format(node(label(0)), node(label(1)), node(label(2)), node(label(3)), node(label(4))) ret += (('{!s:4}' * 5) + '\n').format(label(0), label(1), label(2), label(3), label(4)) return ret def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['F', 4, 1])._default_folded_cartan_type()\n ['F', 4, 1] as a folding of ['E', 6, 1]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['E', 6, 1], [[0], [2], [4], [3, 5], [1, 6]])
class AmbientSpace(ambient_space.AmbientSpace): '\n EXAMPLES::\n\n sage: e = RootSystem([\'G\',2]).ambient_space(); e\n Ambient space of the Root system of type [\'G\', 2]\n\n One can not construct the ambient lattice because the simple\n coroots have rational coefficients::\n\n sage: e.simple_coroots()\n Finite family {1: (0, 1, -1), 2: (1/3, -2/3, 1/3)}\n sage: e.smallest_base_ring()\n Rational Field\n\n By default, this ambient space uses the barycentric projection for plotting::\n\n sage: # needs sage.symbolic\n sage: L = RootSystem(["G",2]).ambient_space()\n sage: e = L.basis()\n sage: L._plot_projection(e[0])\n (1/2, 989/1142)\n sage: L._plot_projection(e[1])\n (-1, 0)\n sage: L._plot_projection(e[2])\n (1/2, -989/1142)\n sage: L = RootSystem(["A",3]).ambient_space()\n sage: l = L.an_element(); l\n (2, 2, 3, 0)\n sage: L._plot_projection(l)\n (0, -1121/1189, 7/3)\n\n .. SEEALSO::\n\n - :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations.ParentMethods._plot_projection`\n\n TESTS::\n\n sage: TestSuite(e).run()\n sage: [WeylDim([\'G\',2],[a,b]) for a,b in [[0,0], [1,0], [0,1], [1,1]]] # indirect doctest\n [1, 7, 14, 64]\n ' def dimension(self): "\n EXAMPLES::\n\n sage: e = RootSystem(['G',2]).ambient_space()\n sage: e.dimension()\n 3\n " return 3 def simple_root(self, i): "\n EXAMPLES::\n\n sage: CartanType(['G',2]).root_system().ambient_space().simple_roots()\n Finite family {1: (0, 1, -1), 2: (1, -2, 1)}\n " return ((self.monomial(1) - self.monomial(2)) if (i == 1) else ((self.monomial(0) - (2 * self.monomial(1))) + self.monomial(2))) def positive_roots(self): "\n EXAMPLES::\n\n sage: CartanType(['G',2]).root_system().ambient_space().positive_roots()\n [(0, 1, -1), (1, -2, 1), (1, -1, 0), (1, 0, -1), (1, 1, -2), (2, -1, -1)]\n " return [self(v) for v in [[0, 1, (- 1)], [1, (- 2), 1], [1, (- 1), 0], [1, 0, (- 1)], [1, 1, (- 2)], [2, (- 1), (- 1)]]] def negative_roots(self): "\n EXAMPLES::\n\n sage: CartanType(['G',2]).root_system().ambient_space().negative_roots()\n [(0, -1, 1), (-1, 2, -1), (-1, 1, 0), (-1, 0, 1), (-1, -1, 2), (-2, 1, 1)]\n " return [self(v) for v in [[0, (- 1), 1], [(- 1), 2, (- 1)], [(- 1), 1, 0], [(- 1), 0, 1], [(- 1), (- 1), 2], [(- 2), 1, 1]]] def fundamental_weights(self): "\n EXAMPLES::\n\n sage: CartanType(['G',2]).root_system().ambient_space().fundamental_weights()\n Finite family {1: (1, 0, -1), 2: (2, -1, -1)}\n " return Family({1: self([1, 0, (- 1)]), 2: self([2, (- 1), (- 1)])}) _plot_projection = RootLatticeRealizations.ParentMethods.__dict__['_plot_projection_barycentric']
class CartanType(CartanType_standard_finite, CartanType_simple, CartanType_crystallographic): def __init__(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['G',2])\n sage: ct\n ['G', 2]\n sage: ct._repr_(compact = True)\n 'G2'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.dual()\n ['G', 2] relabelled by {1: 2, 2: 1}\n sage: ct.affine()\n ['G', 2, 1]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " CartanType_standard_finite.__init__(self, 'G', 2) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['G',2]))\n G_2\n sage: latex(CartanType(['G',2]).dual())\n G_2 \\text{ relabelled by } \\left\\{1 : 2, 2 : 1\\right\\}\n " return 'G_2' AmbientSpace = AmbientSpace def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['G',2]).coxeter_number()\n 6\n " return 6 def dual_coxeter_number(self): "\n Return the dual Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['G',2]).dual_coxeter_number()\n 4\n " return 4 def dynkin_diagram(self): "\n Returns a Dynkin diagram for type G.\n\n EXAMPLES::\n\n sage: g = CartanType(['G',2]).dynkin_diagram(); g # needs sage.graphs\n 3\n O=<=O\n 1 2\n G2\n sage: g.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 3)]\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) g.add_edge(1, 2) g.set_edge_label(2, 1, 3) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['G',2])._latex_dynkin_diagram())\n \\draw (0,0) -- (2 cm,0);\n \\draw (0, 0.15 cm) -- +(2 cm,0);\n \\draw (0, -0.15 cm) -- +(2 cm,0);\n \\draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node ret = ('\\draw (0,0) -- (%s cm,0);\n' % node_dist) ret += ('\\draw (0, 0.15 cm) -- +(%s cm,0);\n' % node_dist) ret += ('\\draw (0, -0.15 cm) -- +(%s cm,0);\n' % node_dist) if dual: ret += self._latex_draw_arrow_tip(((0.5 * node_dist) + 0.2), 0, 0) else: ret += self._latex_draw_arrow_tip(((0.5 * node_dist) - 0.2), 0, 180) ret += node(0, 0, label(1)) ret += node(node_dist, 0, label(2)) return ret def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['G',2]).ascii_art(label=lambda x: x+2))\n 3\n O=<=O\n 3 4\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node ret = ' 3\n{}=<={}\n'.format(node(label(1)), node(label(2))) return (ret + '{!s:4}{!s:4}'.format(label(1), label(2))) def dual(self): "\n Return the dual Cartan type.\n\n This uses that `G_2` is self-dual up to relabelling.\n\n EXAMPLES::\n\n sage: G2 = CartanType(['G',2])\n sage: G2.dual()\n ['G', 2] relabelled by {1: 2, 2: 1}\n\n sage: G2.dynkin_diagram() # needs sage.graphs\n 3\n O=<=O\n 1 2\n G2\n sage: G2.dual().dynkin_diagram() # needs sage.graphs\n 3\n O=<=O\n 2 1\n G2 relabelled by {1: 2, 2: 1}\n " return self.relabel({1: 2, 2: 1}) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['G', 2])._default_folded_cartan_type()\n ['G', 2] as a folding of ['D', 4]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['D', 4], [[1, 3, 4], [2]])
class CartanType(CartanType_standard_untwisted_affine): def __init__(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['G',2,1])\n sage: ct\n ['G', 2, 1]\n sage: ct._repr_(compact = True)\n 'G2~'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n False\n sage: ct.is_affine()\n True\n sage: ct.is_untwisted_affine()\n True\n sage: ct.is_crystallographic()\n True\n sage: ct.is_simply_laced()\n False\n sage: ct.classical()\n ['G', 2]\n sage: ct.dual()\n ['G', 2, 1]^*\n sage: ct.dual().is_untwisted_affine()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " CartanType_standard_untwisted_affine.__init__(self, 'G', 2) def dynkin_diagram(self): "\n Returns the extended Dynkin diagram for type G.\n\n EXAMPLES::\n\n sage: g = CartanType(['G',2,1]).dynkin_diagram(); g # needs sage.graphs\n 3\n O=<=O---O\n 1 2 0\n G2~\n sage: g.edges(sort=True) # needs sage.graphs\n [(0, 2, 1), (1, 2, 1), (2, 0, 1), (2, 1, 3)]\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self) g.add_edge(1, 2) g.set_edge_label(2, 1, 3) g.add_edge(0, 2) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2, dual=False): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['G',2,1])._latex_dynkin_diagram())\n \\draw (2 cm,0) -- (4.0 cm,0);\n \\draw (0, 0.15 cm) -- +(2 cm,0);\n \\draw (0, -0.15 cm) -- +(2 cm,0);\n \\draw (0,0) -- (2 cm,0);\n \\draw (0, 0.15 cm) -- +(2 cm,0);\n \\draw (0, -0.15 cm) -- +(2 cm,0);\n \\draw[shift={(0.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n <BLANKLINE>\n " if (label is None): label = (lambda x: x) if (node is None): node = self._latex_draw_node ret = ('\\draw (%s cm,0) -- (%s cm,0);\n' % (node_dist, (node_dist * 2.0))) ret += ('\\draw (0, 0.15 cm) -- +(%s cm,0);\n' % node_dist) ret += ('\\draw (0, -0.15 cm) -- +(%s cm,0);\n' % node_dist) ret += self.classical()._latex_dynkin_diagram(label, node, node_dist, dual) ret += node((2 * node_dist), 0, label(0)) return ret def ascii_art(self, label=None, node=None): "\n Returns an ascii art representation of the Dynkin diagram\n\n EXAMPLES::\n\n sage: print(CartanType(['G',2,1]).ascii_art(label = lambda x: x+2))\n 3\n O=<=O---O\n 3 4 2\n " if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node ret = ' 3\n{}=<={}---{}'.format(node(label(1)), node(label(2)), node(label(0))) return (ret + '\n{!s:4}{!s:4}{!s:4}'.format(label(1), label(2), label(0))) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['G', 2, 1])._default_folded_cartan_type()\n ['G', 2, 1] as a folding of ['D', 4, 1]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded return CartanTypeFolded(self, ['D', 4, 1], [[0], [1, 3, 4], [2]])
class CartanType(CartanType_standard_finite, CartanType_simple): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['H',3])\n sage: ct\n ['H', 3]\n sage: ct._repr_(compact = True)\n 'H3'\n sage: ct.rank()\n 3\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_affine()\n False\n sage: ct.is_crystallographic()\n False\n sage: ct.is_simply_laced()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n in [3, 4]) CartanType_standard_finite.__init__(self, 'H', n) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['H',3]))\n H_3\n " return 'H_{}'.format(self.n) def coxeter_diagram(self): "\n Returns a Coxeter diagram for type H.\n\n EXAMPLES::\n\n sage: ct = CartanType(['H',3])\n sage: ct.coxeter_diagram() # needs sage.graphs\n Graph on 3 vertices\n sage: ct.coxeter_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (2, 3, 5)]\n sage: ct.coxeter_matrix() # needs sage.graphs\n [1 3 2]\n [3 1 5]\n [2 5 1]\n\n sage: ct = CartanType(['H',4])\n sage: ct.coxeter_diagram() # needs sage.graphs\n Graph on 4 vertices\n sage: ct.coxeter_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (2, 3, 3), (3, 4, 5)]\n sage: ct.coxeter_matrix() # needs sage.graphs\n [1 3 2 2]\n [3 1 3 2]\n [2 3 1 5]\n [2 2 5 1]\n " from sage.graphs.graph import Graph n = self.n g = Graph(multiedges=False) for i in range(1, n): g.add_edge(i, (i + 1), 3) g.set_edge_label((n - 1), n, 5) return g def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['H',3]).coxeter_number()\n 10\n sage: CartanType(['H',4]).coxeter_number()\n 30\n " if (self.n == 3): return 10 return 30
class CartanType(CartanType_standard_finite, CartanType_simple): def __init__(self, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['I',5])\n sage: ct\n ['I', 5]\n sage: ct._repr_(compact = True)\n 'I5'\n sage: ct.rank()\n 2\n sage: ct.index_set()\n (1, 2)\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_affine()\n False\n sage: ct.is_crystallographic()\n False\n sage: ct.is_simply_laced()\n False\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (n >= 1) CartanType_standard_finite.__init__(self, 'I', n) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['I',5]))\n I_2(5)\n " return 'I_2({})'.format(self.n) def rank(self): "\n Type `I_2(p)` is of rank 2.\n\n EXAMPLES::\n\n sage: CartanType(['I', 5]).rank()\n 2\n " return 2 def index_set(self): "\n Type `I_2(p)` is indexed by `\\{1,2\\}`.\n\n EXAMPLES::\n\n sage: CartanType(['I', 5]).index_set()\n (1, 2)\n " return (1, 2) def coxeter_diagram(self): "\n Returns the Coxeter matrix for this type.\n\n EXAMPLES::\n\n sage: ct = CartanType(['I', 4])\n sage: ct.coxeter_diagram() # needs sage.graphs\n Graph on 2 vertices\n sage: ct.coxeter_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 4)]\n sage: ct.coxeter_matrix() # needs sage.graphs\n [1 4]\n [4 1]\n " from sage.graphs.graph import Graph return Graph([[1, 2, self.n]], multiedges=False) def coxeter_number(self): "\n Return the Coxeter number associated with ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['I',3]).coxeter_number()\n 3\n sage: CartanType(['I',12]).coxeter_number()\n 12\n " return self.n
class CartanType(CartanType_standard_finite): '\n Cartan Type `Q_n`\n\n .. SEEALSO:: :func:`~sage.combinat.root_systems.cartan_type.CartanType`\n ' def __init__(self, m): "\n EXAMPLES::\n\n sage: ct = CartanType(['Q',4])\n sage: ct\n ['Q', 4]\n sage: ct._repr_(compact = True)\n 'Q4'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_affine()\n False\n sage: ct.is_simply_laced()\n True\n sage: ct.dual()\n ['Q', 4]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " assert (m >= 2) CartanType_standard_finite.__init__(self, 'Q', (m - 1)) def _repr_(self, compact=False): '\n TESTS::\n\n sage: ct = CartanType([\'Q\',4])\n sage: repr(ct)\n "[\'Q\', 4]"\n sage: ct._repr_(compact=True)\n \'Q4\'\n ' format = ('%s%s' if compact else "['%s', %s]") return (format % (self.letter, (self.n + 1))) def __reduce__(self): "\n TESTS::\n\n sage: T = CartanType(['Q', 4])\n sage: T.__reduce__()\n (CartanType, ('Q', 4))\n sage: T == loads(dumps(T))\n True\n " from .cartan_type import CartanType return (CartanType, (self.letter, (self.n + 1))) def index_set(self): "\n Return the index set for Cartan type Q.\n\n The index set for type Q is of the form\n `\\{-n, \\ldots, -1, 1, \\ldots, n\\}`.\n\n EXAMPLES::\n\n sage: CartanType(['Q', 3]).index_set()\n (1, 2, -2, -1)\n " return tuple((list(range(1, (self.n + 1))) + list(range((- self.n), 0)))) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['Q',4]))\n Q_{4}\n " return ('Q_{%s}' % (self.n + 1)) def root_system(self): "\n Return the root system of ``self``.\n\n EXAMPLES::\n\n sage: Q = CartanType(['Q',3])\n sage: Q.root_system()\n Root system of type ['A', 2]\n " return RootSystem(['A', self.n]) def is_irreducible(self): "\n Return whether this Cartan type is irreducible.\n\n EXAMPLES::\n\n sage: Q = CartanType(['Q',3])\n sage: Q.is_irreducible()\n True\n " return True def is_simply_laced(self): "\n Return whether this Cartan type is simply-laced.\n\n EXAMPLES::\n\n sage: Q = CartanType(['Q',3])\n sage: Q.is_simply_laced()\n True\n " return True def dual(self): "\n Return dual of ``self``.\n\n EXAMPLES::\n\n sage: Q = CartanType(['Q',3])\n sage: Q.dual()\n ['Q', 3]\n " return self
class AmbientSpace(CombinatorialFreeModule): '\n Ambient space for affine types.\n\n This is constructed from the data in the corresponding classical\n ambient space. Namely, this space is obtained by adding two\n elements `\\delta` and `\\delta^\\vee` to the basis of the classical\n ambient space, and by endowing it with the canonical scalar product.\n\n The coefficient of an element in `\\delta^\\vee`, thus its scalar\n product with `\\delta^\\vee` gives its level, and dually for the\n colevel. The canonical projection onto the classical ambient space\n (by killing `\\delta` and `\\delta^\\vee`) maps the simple roots\n (except `\\alpha_0`) onto the corresponding classical simple roots,\n and similarly for the coroots, fundamental weights, ...\n Altogether, this uniquely determines the embedding of the root,\n coroot, weight, and coweight lattices. See :meth:`simple_root` and\n :meth:`fundamental_weight` for the details.\n\n .. WARNING::\n\n In type `BC`, the null root is in fact::\n\n sage: R = RootSystem(["BC",3,2]).ambient_space()\n sage: R.null_root() # needs sage.graphs\n 2*e[\'delta\']\n\n .. WARNING::\n\n In the literature one often considers a larger affine ambient\n space obtained from the classical ambient space by adding four\n dimensions, namely for the fundamental weight `\\Lambda_0` the\n fundamental coweight `\\Lambda^\\vee_0`, the null root `\\delta`,\n and the null coroot `c` (aka central element). In this larger\n ambient space, the scalar product is degenerate: `\\langle\n \\delta,\\delta\\rangle=0` and similarly for the null coroot.\n\n In the current implementation, `\\Lambda_0` and the null coroot\n are identified::\n\n sage: L = RootSystem(["A",3,1]).ambient_space()\n sage: Lambda = L.fundamental_weights() # needs sage.graphs\n sage: Lambda[0] # needs sage.graphs\n e[\'deltacheck\']\n sage: L.null_coroot() # needs sage.graphs\n e[\'deltacheck\']\n\n Therefore the scalar product of the null coroot with itself\n differs from the larger ambient space::\n\n sage: L.null_coroot().scalar(L.null_coroot()) # needs sage.graphs\n 1\n\n In general, scalar products between two elements that do not\n live on "opposite sides" won\'t necessarily match.\n\n EXAMPLES::\n\n sage: R = RootSystem(["A",3,1])\n sage: e = R.ambient_space(); e\n Ambient space of the Root system of type [\'A\', 3, 1]\n sage: TestSuite(e).run()\n\n Systematic checks on all affine types::\n\n sage: for ct in CartanType.samples(affine=True, crystallographic=True):\n ....: if ct.classical().root_system().ambient_space() is not None:\n ....: print(ct)\n ....: L = ct.root_system().ambient_space()\n ....: assert L\n ....: TestSuite(L).run()\n [\'A\', 1, 1]\n [\'A\', 5, 1]\n [\'B\', 1, 1]\n [\'B\', 5, 1]\n [\'C\', 1, 1]\n [\'C\', 5, 1]\n [\'D\', 3, 1]\n [\'D\', 5, 1]\n [\'E\', 6, 1]\n [\'E\', 7, 1]\n [\'E\', 8, 1]\n [\'F\', 4, 1]\n [\'G\', 2, 1]\n [\'BC\', 1, 2]\n [\'BC\', 5, 2]\n [\'B\', 5, 1]^*\n [\'C\', 4, 1]^*\n [\'F\', 4, 1]^*\n [\'G\', 2, 1]^*\n [\'BC\', 1, 2]^*\n [\'BC\', 5, 2]^*\n\n TESTS::\n\n sage: Lambda[1] # needs sage.graphs\n e[0] + e[\'deltacheck\']\n ' @classmethod def smallest_base_ring(cls, cartan_type): '\n Return the smallest base ring the ambient space can be defined on.\n\n This is the smallest base ring for the associated classical\n ambient space.\n\n .. SEEALSO:: :meth:`~sage.combinat.root_system.ambient_space.AmbientSpace.smallest_base_ring`\n\n EXAMPLES::\n\n sage: cartan_type = CartanType(["A",3,1])\n sage: cartan_type.AmbientSpace.smallest_base_ring(cartan_type)\n Integer Ring\n sage: cartan_type = CartanType(["B",3,1])\n sage: cartan_type.AmbientSpace.smallest_base_ring(cartan_type)\n Rational Field\n ' classical = cartan_type.classical() return cartan_type.classical().root_system().ambient_space().smallest_base_ring(classical) def __init__(self, root_system, base_ring): '\n EXAMPLES::\n\n sage: R = RootSystem(["A",3,1])\n sage: R.cartan_type().AmbientSpace\n <class \'sage.combinat.root_system.type_affine.AmbientSpace\'>\n sage: e = R.ambient_space(); e\n Ambient space of the Root system of type [\'A\', 3, 1]\n sage: TestSuite(R.ambient_space()).run()\n\n sage: L = RootSystem([\'A\',3]).coroot_lattice()\n sage: e.has_coerce_map_from(L)\n True\n sage: e(L.simple_root(1))\n e[0] - e[1]\n ' self.root_system = root_system classical = root_system.cartan_type().classical().root_system().ambient_space(base_ring) basis_keys = (tuple(classical.basis().keys()) + ('delta', 'deltacheck')) def sortkey(x): return ((1 if isinstance(x, str) else 0), x) CombinatorialFreeModule.__init__(self, base_ring, basis_keys, prefix='e', latex_prefix='e', sorting_key=sortkey, category=WeightLatticeRealizations(base_ring)) self._weight_space = self.root_system.weight_space(base_ring=base_ring, extended=True) self.classical().module_morphism(self.monomial, codomain=self).register_as_coercion() coroot_lattice = self.root_system.coroot_lattice() coroot_lattice.module_morphism(self.simple_coroot, codomain=self).register_as_coercion() def _name_string(self, capitalize=True, base_ring=False, type=True): '\n Utility to implement _repr_\n\n EXAMPLES::\n\n sage: RootSystem([\'A\',4,1]).ambient_lattice()\n Ambient lattice of the Root system of type [\'A\', 4, 1]\n sage: RootSystem([\'A\',4,1]).ambient_space()\n Ambient space of the Root system of type [\'A\', 4, 1]\n sage: RootSystem([\'A\',4,1]).dual.ambient_lattice()\n Coambient lattice of the Root system of type [\'A\', 4, 1]\n\n sage: RootSystem([\'A\',4,1]).ambient_lattice()._repr_()\n "Ambient lattice of the Root system of type [\'A\', 4, 1]"\n sage: RootSystem([\'A\',4,1]).ambient_lattice()._name_string()\n "Ambient lattice of the Root system of type [\'A\', 4, 1]"\n ' return self._name_string_helper('ambient', capitalize=capitalize, base_ring=base_ring, type=type) _repr_ = _name_string @cached_method def _to_classical_on_basis(self, i): '\n Implement the projection onto the corresponding classical space or lattice, on the basis.\n\n INPUT:\n\n - ``i`` -- the index of an element of the basis of ``self``,\n namely 0, 1, 2, ..., "delta", or "deltacheck"\n\n EXAMPLES::\n\n sage: L = RootSystem(["A",2,1]).ambient_space()\n sage: L._to_classical_on_basis("delta")\n (0, 0, 0)\n sage: L._to_classical_on_basis("deltacheck")\n (0, 0, 0)\n sage: L._to_classical_on_basis(0)\n (1, 0, 0)\n sage: L._to_classical_on_basis(1)\n (0, 1, 0)\n sage: L._to_classical_on_basis(2)\n (0, 0, 1)\n ' if ((i == 'delta') or (i == 'deltacheck')): return self.classical().zero() else: return self.classical().monomial(i) def is_extended(self): "\n Return whether this is a realization of the extended weight lattice: yes!\n\n .. SEEALSO::\n\n - :class:`sage.combinat.root_system.weight_space.WeightSpace`\n - :meth:`sage.combinat.root_system.weight_lattice_realizations.WeightLatticeRealizations.ParentMethods.is_extended`\n\n EXAMPLES::\n\n sage: RootSystem(['A',3,1]).ambient_space().is_extended()\n True\n " return True @cached_method def fundamental_weight(self, i): '\n Return the fundamental weight `\\Lambda_i` in this ambient space.\n\n It is constructed by taking the corresponding fundamental\n weight of the classical ambient space (or `0` for `\\Lambda_0`)\n and raising it to the appropriate level by adding a suitable\n multiple of `\\delta^\\vee`.\n\n EXAMPLES::\n\n sage: RootSystem([\'A\',3,1]).ambient_space().fundamental_weight(2) # needs sage.graphs\n e[0] + e[1] + e[\'deltacheck\']\n sage: RootSystem([\'A\',3,1]).ambient_space().fundamental_weights() # needs sage.graphs\n Finite family {0: e[\'deltacheck\'],\n 1: e[0] + e[\'deltacheck\'],\n 2: e[0] + e[1] + e[\'deltacheck\'],\n 3: e[0] + e[1] + e[2] + e[\'deltacheck\']}\n sage: RootSystem([\'A\',3]).ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (1, 1, 1, 0)}\n sage: A31wl = RootSystem([\'A\',3,1]).weight_lattice()\n sage: A31wl.fundamental_weights().map(attrcall("level")) # needs sage.graphs\n Finite family {0: 1, 1: 1, 2: 1, 3: 1}\n\n sage: RootSystem([\'B\',3,1]).ambient_space().fundamental_weights() # needs sage.graphs\n Finite family {0: e[\'deltacheck\'],\n 1: e[0] + e[\'deltacheck\'],\n 2: e[0] + e[1] + 2*e[\'deltacheck\'],\n 3: 1/2*e[0] + 1/2*e[1] + 1/2*e[2] + e[\'deltacheck\']}\n sage: RootSystem([\'B\',3]).ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0), 2: (1, 1, 0), 3: (1/2, 1/2, 1/2)}\n sage: B31wl = RootSystem([\'B\',3,1]).weight_lattice()\n sage: B31wl.fundamental_weights().map(attrcall("level")) # needs sage.graphs\n Finite family {0: 1, 1: 1, 2: 2, 3: 1}\n\n In type `BC` dual, the coefficient of \'\\delta^\\vee\' is the level\n divided by `2` to take into account that the null coroot is\n `2\\delta^\\vee`::\n\n sage: R = CartanType([\'BC\',3,2]).dual().root_system()\n sage: R.ambient_space().fundamental_weights() # needs sage.graphs\n Finite family {0: e[\'deltacheck\'],\n 1: e[0] + e[\'deltacheck\'],\n 2: e[0] + e[1] + e[\'deltacheck\'],\n 3: 1/2*e[0] + 1/2*e[1] + 1/2*e[2] + 1/2*e[\'deltacheck\']}\n sage: R.weight_lattice().fundamental_weights().map(attrcall("level")) # needs sage.graphs\n Finite family {0: 2, 1: 2, 2: 2, 3: 1}\n sage: R.ambient_space().null_coroot() # needs sage.graphs\n 2*e[\'deltacheck\']\n\n By a slight naming abuse this function also accepts "delta" as\n input so that it can be used to implement the embedding from\n the extended weight lattice::\n\n sage: RootSystem([\'A\',3,1]).ambient_space().fundamental_weight("delta")\n e[\'delta\']\n ' if (i == 'delta'): return self.monomial('delta') deltacheck = self.monomial('deltacheck') result = ((deltacheck * self._weight_space.fundamental_weight(i).level()) / deltacheck.level()) if (i != self.cartan_type().special_node()): result += self(self.classical().fundamental_weight(i)) return result @cached_method def simple_root(self, i): '\n Return the `i`-th simple root of this affine ambient space.\n\n EXAMPLES:\n\n It is built straightforwardly from the corresponding simple\n root `\\alpha_i` in the classical ambient space::\n\n sage: RootSystem(["A",3,1]).ambient_space().simple_root(1)\n e[0] - e[1]\n\n For the special node (typically `i=0`), `\\alpha_0` is built\n from the other simple roots using the column annihilator of\n the Cartan matrix and adding `\\delta`, where `\\delta` is the\n null root::\n\n sage: RootSystem(["A",3]).ambient_space().simple_roots()\n Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1)}\n sage: RootSystem(["A",3,1]).ambient_space().simple_roots() # needs sage.graphs\n Finite family {0: -e[0] + e[3] + e[\'delta\'], 1: e[0] - e[1],\n 2: e[1] - e[2], 3: e[2] - e[3]}\n\n Here is a twisted affine example::\n\n sage: B31v = RootSystem(CartanType(["B",3,1]).dual())\n sage: B31v.ambient_space().simple_roots() # needs sage.graphs\n Finite family {0: -e[0] - e[1] + e[\'delta\'], 1: e[0] - e[1],\n 2: e[1] - e[2], 3: 2*e[2]}\n\n In fact `\\delta` is really `1/a_0` times the null root (see\n the discussion in :class:`~sage.combinat.root_system.weight_space.WeightSpace`)\n but this only makes a difference in type `BC`::\n\n sage: L = RootSystem(CartanType(["BC",3,2])).ambient_space()\n sage: L.simple_roots() # needs sage.graphs\n Finite family {0: -e[0] + e[\'delta\'], 1: e[0] - e[1],\n 2: e[1] - e[2], 3: 2*e[2]}\n sage: L.null_root() # needs sage.graphs\n 2*e[\'delta\']\n\n .. NOTE::\n\n An alternative would have been to use the default\n implementation of the simple roots as linear combinations\n of the fundamental weights. However, as in type `A_n` it is\n preferable to take a slight variant to avoid rational\n coefficient (the usual `GL_n` vs `SL_n` issue).\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.root_system.weight_space.WeightSpace.simple_root`\n - :class:`~sage.combinat.root_system.weight_space.WeightSpace`\n - :meth:`CartanType.col_annihilator`\n - :meth:`null_root`\n ' cartan_type = self.cartan_type() special_node = cartan_type.special_node() if (i == special_node): return (self(self._classical_alpha_0()) + self.monomial('delta')) else: return self(self.classical().simple_root(i)) @cached_method def simple_coroot(self, i): '\n Return the `i`-th simple coroot `\\alpha_i^\\vee` of this affine ambient space.\n\n EXAMPLES::\n\n sage: RootSystem(["A",3,1]).ambient_space().simple_coroot(1)\n e[0] - e[1]\n\n It is built as the coroot associated to the simple root\n `\\alpha_i`::\n\n sage: RootSystem(["B",3,1]).ambient_space().simple_roots() # needs sage.graphs\n Finite family {0: -e[0] - e[1] + e[\'delta\'], 1: e[0] - e[1],\n 2: e[1] - e[2], 3: e[2]}\n sage: RootSystem(["B",3,1]).ambient_space().simple_coroots() # needs sage.graphs\n Finite family {0: -e[0] - e[1] + e[\'deltacheck\'], 1: e[0] - e[1],\n 2: e[1] - e[2], 3: 2*e[2]}\n\n .. TODO:: Factor out this code with the classical ambient space.\n ' return self.simple_root(i).associated_coroot() def coroot_lattice(self): '\n EXAMPLES::\n\n sage: RootSystem(["A",3,1]).ambient_lattice().coroot_lattice()\n Ambient lattice of the Root system of type [\'A\', 3, 1]\n\n .. TODO:: Factor out this code with the classical ambient space.\n ' return self def _plot_projection(self, x): '\n Implements the default projection to be used for plots\n\n For affine ambient spaces, the default implementation is to\n project onto the classical coordinates according to the\n default projection for the classical ambient space, while\n keeping an extra coordinate for the coefficient of\n `\\delta^\\vee` to keep the level information.\n\n .. SEEALSO::\n\n :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations._plot_projection`\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: L = RootSystem(["B",2,1]).ambient_space()\n sage: e = L.basis()\n sage: L._plot_projection(e[0])\n (1, 0, 0)\n sage: L._plot_projection(e[1])\n (0, 1, 0)\n sage: L._plot_projection(e["delta"])\n (0, 0, 0)\n sage: L._plot_projection(e["deltacheck"])\n (0, 0, 1)\n\n sage: # needs sage.symbolic\n sage: L = RootSystem(["A",2,1]).ambient_space()\n sage: e = L.basis()\n sage: L._plot_projection(e[0])\n (1/2, 989/1142, 0)\n sage: L._plot_projection(e[1])\n (-1, 0, 0)\n sage: L._plot_projection(e["delta"])\n (0, 0, 0)\n sage: L._plot_projection(e["deltacheck"])\n (0, 0, 1)\n ' from sage.modules.free_module_element import vector classical = self.classical() return vector((list(vector(classical._plot_projection(classical(x)))) + [x['deltacheck']])) class Element(CombinatorialFreeModule.Element): def inner_product(self, other): "\n Implement the canonical inner product of ``self`` with ``other``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['B',3,1]).ambient_space()\n sage: B = e.basis()\n sage: matrix([[x.inner_product(y) for x in B] for y in B])\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n sage: x = e.an_element(); x\n 2*e[0] + 2*e[1] + 3*e[2]\n sage: x.inner_product(x)\n 17\n\n :meth:`scalar` is an alias for this method::\n\n sage: x.scalar(x)\n 17\n\n .. TODO:: Lift to CombinatorialFreeModule.Element as canonical_inner_product\n " if (self.parent() is not other.parent()): raise TypeError('the parents must be the same') return self.base_ring().sum(((self[i] * c) for (i, c) in other)) scalar = inner_product def associated_coroot(self): "\n Return the coroot associated to ``self``.\n\n INPUT:\n\n - ``self`` -- a root\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: alpha = RootSystem(['C',2,1]).ambient_space().simple_roots()\n sage: alpha\n Finite family {0: -2*e[0] + e['delta'], 1: e[0] - e[1], 2: 2*e[1]}\n sage: alpha[0].associated_coroot()\n -e[0] + e['deltacheck']\n sage: alpha[1].associated_coroot()\n e[0] - e[1]\n sage: alpha[2].associated_coroot()\n e[1]\n " L = self.parent() c = self['delta'] self = (self - L.term('delta', c)) return (((2 * self) / self.inner_product(self)) + L.term('deltacheck', c))
class CartanType(cartan_type.CartanType_decorator, cartan_type.CartanType_crystallographic): '\n A class for dual Cartan types.\n\n The dual of a (crystallographic) Cartan type is a Cartan type with\n the same index set, but all arrows reversed in the Dynkin diagram\n (otherwise said, the Cartan matrix is transposed). It shares a lot\n of properties in common with its dual. In particular, the Weyl\n group is isomorphic to that of the dual as a Coxeter group.\n\n EXAMPLES:\n\n For all finite Cartan types, and in particular the simply laced\n ones, the dual Cartan type is given by another preexisting Cartan\n type::\n\n sage: CartanType([\'A\',4]).dual()\n [\'A\', 4]\n sage: CartanType([\'B\',4]).dual()\n [\'C\', 4]\n sage: CartanType([\'C\',4]).dual()\n [\'B\', 4]\n sage: CartanType([\'F\',4]).dual()\n [\'F\', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n\n So to exercise this class we consider some non simply laced affine\n Cartan types and also create explicitly `F_4^*` as a dual cartan\n type::\n\n sage: from sage.combinat.root_system.type_dual import CartanType as CartanTypeDual\n sage: F4d = CartanTypeDual(CartanType([\'F\',4])); F4d\n [\'F\', 4]^*\n sage: G21d = CartanType([\'G\',2,1]).dual(); G21d\n [\'G\', 2, 1]^*\n\n They share many properties with their original Cartan types::\n\n sage: F4d.is_irreducible()\n True\n sage: F4d.is_crystallographic()\n True\n sage: F4d.is_simply_laced()\n False\n sage: F4d.is_finite()\n True\n sage: G21d.is_finite()\n False\n sage: F4d.is_affine()\n False\n sage: G21d.is_affine()\n True\n\n TESTS::\n\n sage: TestSuite(F4d).run(skip=["_test_pickling"])\n sage: TestSuite(G21d).run()\n\n .. NOTE:: F4d is pickled by construction as F4.dual() hence the above failure.\n ' def __init__(self, type): '\n INPUT:\n\n - ``type`` -- a Cartan type\n\n EXAMPLES::\n\n sage: ct = CartanType([\'F\',4,1]).dual()\n sage: TestSuite(ct).run()\n\n TESTS::\n\n sage: ct1 = CartanType([\'B\',3,1]).dual()\n sage: ct2 = CartanType([\'B\',3,1]).dual()\n sage: ct3 = CartanType([\'D\',4,1]).dual()\n sage: ct1 == ct2\n True\n sage: ct1 == ct3\n False\n\n Test that the produced Cartan type is in the appropriate\n abstract classes (see :trac:`13724`)::\n\n sage: from sage.combinat.root_system import cartan_type\n sage: ct = CartanType([\'B\',3,1]).dual()\n sage: TestSuite(ct).run()\n sage: isinstance(ct, cartan_type.CartanType_simple)\n True\n sage: isinstance(ct, cartan_type.CartanType_finite)\n False\n sage: isinstance(ct, cartan_type.CartanType_affine)\n True\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n False\n\n By default, the dual of a reducible and finite type is not\n constructed as such::\n\n sage: ct = CartanType([[\'B\',4],[\'A\',2]]).dual(); ct\n C4xA2\n\n In order to exercise the dual infrastructure we force the\n construction as a dual::\n\n sage: from sage.combinat.root_system import type_dual\n sage: ct = type_dual.CartanType(CartanType([[\'B\',4],[\'A\',2]])); ct\n B4xA2^*\n sage: isinstance(ct, type_dual.CartanType)\n True\n sage: TestSuite(ct).run(skip=["_test_pickling"])\n sage: isinstance(ct, cartan_type.CartanType_finite)\n True\n sage: isinstance(ct, cartan_type.CartanType_simple)\n False\n sage: isinstance(ct, cartan_type.CartanType_affine)\n False\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n False\n ' if (not type.is_crystallographic()): raise NotImplementedError('only implemented for crystallographic Cartan types') cartan_type.CartanType_decorator.__init__(self, type) if type.is_finite(): self.__class__ = CartanType_finite elif type.is_affine(): self.__class__ = CartanType_affine abstract_classes = tuple((cls for cls in self._stable_abstract_classes if isinstance(type, cls))) if abstract_classes: self._add_abstract_superclass(abstract_classes) _stable_abstract_classes = [cartan_type.CartanType_simple] def _repr_(self, compact=False): "\n EXAMPLES::\n\n sage: CartanType(['F', 4, 1]).dual()\n ['F', 4, 1]^*\n\n sage: CartanType(['F', 4, 1]).dual()._repr_(compact = True)\n 'F4~*'\n " dual_str = self.options.dual_str if (self.is_affine() and (self.options.notation == 'Kac')): if (self._type.type() == 'B'): if compact: return ('A%s^2' % ((self.classical().rank() * 2) - 1)) return ("['A', %s, 2]" % ((self.classical().rank() * 2) - 1)) elif (self._type.type() == 'BC'): dual_str = '+' elif (self._type.type() == 'C'): if compact: return ('D%s^2' % self.rank()) return ("['D', %s, 2]" % self.rank()) elif (self._type.type() == 'F'): if compact: return 'E6^2' return "['E', 6, 2]" return (self.dual()._repr_(compact) + (dual_str if compact else ('^' + dual_str))) def _latex_(self): "\n EXAMPLES::\n\n sage: latex(CartanType(['F', 4, 1]).dual())\n F_4^{(1)\\vee}\n " return ((self._type._latex_() + '^') + self.options.dual_latex) def __reduce__(self): "\n TESTS::\n\n sage: CartanType(['F', 4, 1]).dual().__reduce__()\n (*.dual(), (['F', 4, 1],))\n " return (attrcall('dual'), (self._type,)) def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n EXAMPLES::\n\n sage: print(CartanType(['F',4,1]).dual()._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (2 cm,0);\n {\n \\pgftransformxshift{2 cm}\n \\draw (0 cm,0) -- (2 cm,0);\n \\draw (2 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (2 cm, -0.1 cm) -- +(2 cm,0);\n \\draw (4.0 cm,0) -- +(2 cm,0);\n \\draw[shift={(2.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n }\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node return self._type._latex_dynkin_diagram(label, node, node_dist, dual=True) def ascii_art(self, label=None, node=None): '\n Return an ascii art representation of this Cartan type\n\n (by hacking the ascii art representation of the dual Cartan type)\n\n EXAMPLES::\n\n sage: print(CartanType(["B", 3, 1]).dual().ascii_art())\n O 0\n |\n |\n O---O=<=O\n 1 2 3\n sage: print(CartanType(["C", 4, 1]).dual().ascii_art())\n O=<=O---O---O=>=O\n 0 1 2 3 4\n sage: print(CartanType(["G", 2, 1]).dual().ascii_art())\n 3\n O=>=O---O\n 1 2 0\n sage: print(CartanType(["F", 4, 1]).dual().ascii_art())\n O---O---O=<=O---O\n 0 1 2 3 4\n sage: print(CartanType(["BC", 4, 2]).dual().ascii_art())\n O=>=O---O---O=>=O\n 0 1 2 3 4\n ' if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node res = self._type.ascii_art(label, node) res = res.replace('=<=', '=?=') res = res.replace('=>=', '=<=') res = res.replace('=?=', '=>=') return res def __eq__(self, other): "\n Return whether ``self`` is equal to ``other``.\n\n EXAMPLES::\n\n sage: B41 = CartanType(['B', 4, 1])\n sage: B41dual = CartanType(['B', 4, 1]).dual()\n sage: F41dual = CartanType(['F', 4, 1]).dual()\n\n sage: F41dual == F41dual\n True\n sage: F41dual == B41dual\n False\n sage: B41dual == B41\n False\n " if (not isinstance(other, CartanType)): return False return (self._type == other._type) def __ne__(self, other): "\n Return whether ``self`` is equal to ``other``.\n\n EXAMPLES::\n\n sage: B41 = CartanType(['B', 4, 1])\n sage: B41dual = CartanType(['B', 4, 1]).dual()\n sage: F41dual = CartanType(['F', 4, 1]).dual()\n\n sage: F41dual != F41dual\n False\n sage: F41dual != B41dual\n True\n sage: B41dual != B41\n True\n " return (not (self == other)) def __hash__(self): "\n Compute the hash of ``self``.\n\n EXAMPLES::\n\n sage: B41 = CartanType(['B', 4, 1])\n sage: B41dual = CartanType(['B', 4, 1]).dual()\n sage: h = hash(B41dual)\n " return hash(self._type) def dual(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F', 4, 1]).dual()\n sage: ct.dual()\n ['F', 4, 1]\n " return self._type def dynkin_diagram(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['F', 4, 1]).dual()\n sage: ct.dynkin_diagram() # needs sage.graphs\n O---O---O=<=O---O\n 0 1 2 3 4\n F4~*\n " return self._type.dynkin_diagram().dual()
class AmbientSpace(ambient_space.AmbientSpace): '\n Ambient space for a dual finite Cartan type.\n\n It is constructed in the canonical way from the ambient space of\n the original Cartan type by switching the roles of simple roots,\n fundamental weights, etc.\n\n .. NOTE::\n\n Recall that, for any finite Cartan type, and in particular the\n a simply laced one, the dual Cartan type is constructed as\n another preexisting Cartan type. Furthermore the ambient space\n for an affine type is constructed from the ambient space for\n its classical type. Thus this code is not actually currently\n used.\n\n It is kept for cross-checking and for reference in case it\n could become useful, e.g., for dual of general Kac-Moody\n types.\n\n For the doctests, we need to explicitly create a dual type.\n Subsequently, since reconstruction of the dual of type `F_4`\n is the relabelled Cartan type, pickling fails on the\n ``TestSuite`` run.\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType([\'F\',4]))\n sage: L = ct.root_system().ambient_space(); L\n Ambient space of the Root system of type [\'F\', 4]^*\n sage: TestSuite(L).run(skip=["_test_elements","_test_pickling"]) # needs sage.graphs\n ' @lazy_attribute def _dual_space(self): "\n The dual of this ambient space.\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))\n sage: L = ct.root_system().ambient_space(); L\n Ambient space of the Root system of type ['F', 4]^*\n sage: L._dual_space\n Ambient space of the Root system of type ['F', 4]\n\n The basic data for this space is fetched from the dual space::\n\n sage: L._dual_space.simple_root(1)\n (0, 1, -1, 0)\n sage: L.simple_root(1)\n (0, 1, -1, 0)\n " K = self.base_ring() return self.cartan_type().dual().root_system().ambient_space(K) def dimension(self): "\n Return the dimension of this ambient space.\n\n .. SEEALSO:: :meth:`sage.combinat.root_system.ambient_space.AmbientSpace.dimension`\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))\n sage: L = ct.root_system().ambient_space()\n sage: L.dimension()\n 4\n " return self.root_system.dual.ambient_space().dimension() @cached_method def simple_root(self, i): "\n Return the ``i``-th simple root.\n\n It is constructed by looking up the corresponding simple\n coroot in the ambient space for the dual Cartan type.\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))\n sage: ct.root_system().ambient_space().simple_root(1)\n (0, 1, -1, 0)\n\n sage: ct.root_system().ambient_space().simple_roots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 2), 4: (1, -1, -1, -1)}\n\n sage: ct.dual().root_system().ambient_space().simple_coroots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 2), 4: (1, -1, -1, -1)}\n\n Note that this ambient space is isomorphic, but not equal, to\n that obtained by constructing `F_4` dual by relabelling::\n\n sage: ct = CartanType(['F',4]).dual(); ct\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n sage: ct.root_system().ambient_space().simple_roots()\n Finite family {1: (1/2, -1/2, -1/2, -1/2), 2: (0, 0, 0, 1), 3: (0, 0, 1, -1), 4: (0, 1, -1, 0)}\n " dual_coroot = self._dual_space.simple_coroot(i) return self.sum_of_terms(dual_coroot) @cached_method def fundamental_weights(self): "\n Return the fundamental weights.\n\n They are computed from the simple roots by inverting the\n Cartan matrix. This is acceptable since this is only about\n ambient spaces for finite Cartan types. Also, we do not have\n to worry about the usual `GL_n` vs `SL_n` catch because type\n `A` is self dual.\n\n An alternative would have been to start from the fundamental\n coweights in the dual ambient space, but those are not yet\n implemented.\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))\n sage: L = ct.root_system().ambient_space()\n sage: L.fundamental_weights() # needs sage.graphs\n Finite family {1: (1, 1, 0, 0), 2: (2, 1, 1, 0), 3: (3, 1, 1, 1), 4: (2, 0, 0, 0)}\n\n Note that this ambient space is isomorphic, but not equal, to\n that obtained by constructing `F_4` dual by relabelling::\n\n sage: ct = CartanType(['F',4]).dual(); ct\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n sage: ct.root_system().ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0, 0), 2: (3/2, 1/2, 1/2, 1/2), 3: (2, 1, 1, 0), 4: (1, 1, 0, 0)}\n " return self.fundamental_weights_from_simple_roots() @lazy_attribute def _plot_projection(self): "\n Return the default plot projection for ``self``.\n\n If an ambient space uses barycentric projection, then so does\n its dual.\n\n .. SEEALSO::\n\n - :meth:`sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations.ParentMethods._plot_projection`\n\n EXAMPLES::\n\n sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['G',2]))\n sage: L = ct.root_system().ambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n True\n\n sage: L = RootSystem(['G',2]).coambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n True\n " dual_space = self.cartan_type().dual().root_system().ambient_space(self.base_ring()) if (dual_space._plot_projection == dual_space._plot_projection_barycentric): return self._plot_projection_barycentric else: RootLatticeRealizations.ParentMethods.__dict__['_plot_projection']
class CartanType_finite(CartanType, cartan_type.CartanType_finite): AmbientSpace = AmbientSpace
class CartanType_affine(CartanType, cartan_type.CartanType_affine): def classical(self): "\n Return the classical Cartan type associated with self (which should\n be affine).\n\n EXAMPLES::\n\n sage: CartanType(['A',3,1]).dual().classical()\n ['A', 3]\n sage: CartanType(['B',3,1]).dual().classical()\n ['C', 3]\n sage: CartanType(['F',4,1]).dual().classical()\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n sage: CartanType(['BC',4,2]).dual().classical()\n ['B', 4]\n " return self.dual().classical().dual() def basic_untwisted(self): "\n Return the basic untwisted Cartan type associated with this affine\n Cartan type.\n\n Given an affine type `X_n^{(r)}`, the basic untwisted type is `X_n`.\n In other words, it is the classical Cartan type that is twisted to\n obtain ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', 7, 2]).basic_untwisted()\n ['A', 7]\n sage: CartanType(['E', 6, 2]).basic_untwisted()\n ['E', 6]\n sage: CartanType(['D', 4, 3]).basic_untwisted()\n ['D', 4]\n " from . import cartan_type if (self.dual().type() == 'B'): return cartan_type.CartanType(['A', ((self.classical().rank() * 2) - 1)]) elif (self.dual().type() == 'BC'): return cartan_type.CartanType(['A', (self.classical().rank() * 2)]) elif (self.dual().type() == 'C'): return cartan_type.CartanType(['D', (self.classical().rank() + 1)]) elif (self.dual().type() == 'F'): return cartan_type.CartanType(['E', 6]) elif (self.dual().type() == 'G'): return cartan_type.CartanType(['D', 4]) def special_node(self): "\n Implement :meth:`CartanType_affine.special_node`\n\n The special node of the dual of an affine type `T` is the\n special node of `T`.\n\n EXAMPLES::\n\n sage: CartanType(['A',3,1]).dual().special_node()\n 0\n sage: CartanType(['B',3,1]).dual().special_node()\n 0\n sage: CartanType(['F',4,1]).dual().special_node()\n 0\n sage: CartanType(['BC',4,2]).dual().special_node()\n 0\n " return self.dual().special_node() def _repr_(self, compact=False): "\n EXAMPLES::\n\n sage: CartanType(['F', 4, 1]).dual()\n ['F', 4, 1]^*\n\n sage: CartanType(['F', 4, 1]).dual()._repr_(compact = True)\n 'F4~*'\n " if (self.options.notation == 'Kac'): if (self._type.type() == 'B'): if compact: return ('A%s^2' % ((self.classical().rank() * 2) - 1)) return ("['A', %s, 2]" % ((self.classical().rank() * 2) - 1)) elif (self._type.type() == 'BC'): pass elif (self._type.type() == 'C'): if compact: return ('D%s^2' % self.rank()) return ("['D', %s, 2]" % self.rank()) elif (self._type.type() == 'F'): if compact: return 'E6^2' return "['E', 6, 2]" return CartanType._repr_(self, compact) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['B',4,1]).dual())\n B_{4}^{(1)\\vee}\n sage: latex(CartanType(['BC',4,2]).dual())\n BC_{4}^{(2)\\vee}\n sage: latex(CartanType(['G',2,1]).dual())\n G_2^{(1)\\vee}\n\n sage: CartanType.options['notation'] = 'Kac'\n sage: latex(CartanType(['A',7,2]))\n A_{7}^{(2)}\n sage: latex(CartanType(['B',4,1]).dual())\n A_{7}^{(2)}\n sage: latex(CartanType(['A',8,2]))\n A_{8}^{(2)}\n sage: latex(CartanType(['A',8,2]).dual())\n A_{8}^{(2)\\dagger}\n sage: latex(CartanType(['E',6,2]))\n E_6^{(2)}\n sage: latex(CartanType(['D',5,2]))\n D_{5}^{(2)}\n sage: CartanType.options._reset()\n " if (self.options('notation') == 'Kac'): if (self._type.type() == 'B'): return ('A_{%s}^{(2)}' % ((self.classical().rank() * 2) - 1)) elif (self._type.type() == 'BC'): return ('A_{%s}^{(2)\\dagger}' % (2 * self.classical().rank())) elif (self._type.type() == 'C'): return ('D_{%s}^{(2)}' % self.rank()) elif (self._type.type() == 'F'): return 'E_6^{(2)}' result = self._type._latex_() import re if re.match('.*\\^{\\(\\d\\)}$', result): return ('%s%s}' % (result[:(- 1)], self.options('dual_latex'))) else: return ('{%s}^%s' % (result, self.options('dual_latex'))) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(['A', 6, 2]).dual()._default_folded_cartan_type()\n ['BC', 3, 2]^* as a folding of ['A', 5, 1]\n sage: CartanType(['A', 5, 2])._default_folded_cartan_type()\n ['B', 3, 1]^* as a folding of ['D', 4, 1]\n sage: CartanType(['D', 4, 2])._default_folded_cartan_type()\n ['C', 3, 1]^* as a folding of ['A', 5, 1]\n sage: CartanType(['E', 6, 2])._default_folded_cartan_type()\n ['F', 4, 1]^* as a folding of ['E', 6, 1]\n sage: CartanType(['G', 2, 1]).dual()._default_folded_cartan_type()\n ['G', 2, 1]^* as a folding of ['D', 4, 1]\n " from sage.combinat.root_system.type_folded import CartanTypeFolded letter = self._type.type() if (letter == 'BC'): n = self._type.classical().rank() return CartanTypeFolded(self, ['A', ((2 * n) - 1), 1], (([[0]] + [[i, ((2 * n) - i)] for i in range(1, n)]) + [[n]])) if (letter == 'B'): n = self._type.classical().rank() return CartanTypeFolded(self, ['D', (n + 1), 1], ([[i] for i in range(n)] + [[n, (n + 1)]])) if (letter == 'C'): n = self._type.classical().rank() return CartanTypeFolded(self, ['A', ((2 * n) - 1), 1], (([[0]] + [[i, ((2 * n) - i)] for i in range(1, n)]) + [[n]])) if (letter == 'F'): return CartanTypeFolded(self, ['E', 6, 1], [[0], [2], [4], [3, 5], [1, 6]]) if (letter == 'G'): return CartanTypeFolded(self, ['D', 4, 1], [[0], [1, 3, 4], [2]]) return super()._default_folded_cartan_type()
class CartanTypeFolded(UniqueRepresentation, SageObject): '\n A Cartan type realized from a (Dynkin) diagram folding.\n\n Given a Cartan type `X`, we say `\\hat{X}` is a folded Cartan\n type of `X` if there exists a diagram folding of the Dynkin\n diagram of `\\hat{X}` onto `X`.\n\n A folding of a simply-laced Dynkin diagram `D` with index set `I` is an\n automorphism `\\sigma` of `D` where all nodes any orbit of `\\sigma` are not\n connected. The resulting Dynkin diagram `\\hat{D}` is induced by\n `I / \\sigma` where we identify edges in `\\hat{D}` which are not incident\n and add a `k`-edge if we identify `k` incident edges and the arrow is\n pointing towards the indicent note. We denote the index set of `\\hat{D}`\n by `\\hat{I}`, and by abuse of notation, we denote the folding by `\\sigma`.\n\n We also have scaling factors `\\gamma_i` for `i \\in \\hat{I}` and defined\n as the unique numbers such that the map\n `\\Lambda_j \\mapsto \\gamma_j \\sum_{i \\in \\sigma^{-1}(j)} \\Lambda_i`\n is the smallest proper embedding of the weight lattice of `X` to `\\hat{X}`.\n\n If the Cartan type is simply laced, the default folding is the one\n induced from the identity map on `D`.\n\n If `X` is affine type, the default embeddings we consider here are:\n\n .. MATH::\n\n \\begin{array}{ccl}\n C_n^{(1)}, A_{2n}^{(2)}, A_{2n}^{(2)\\dagger}, D_{n+1}^{(2)}\n & \\hookrightarrow & A_{2n-1}^{(1)}, \\\\\n A_{2n-1}^{(2)}, B_n^{(1)} & \\hookrightarrow & D_{n+1}^{(1)}, \\\\\n E_6^{(2)}, F_4^{(1)} & \\hookrightarrow & E_6^{(1)}, \\\\\n D_4^{(3)}, G_2^{(1)} & \\hookrightarrow & D_4^{(1)},\n \\end{array}\n\n and were chosen based on virtual crystals. In particular, the diagram\n foldings extend to crystal morphisms and gives a realization of\n Kirillov-Reshetikhin crystals for non-simply-laced types as simply-laced\n types. See [OSShimo03]_ and [FOS2009]_ for more details. Here we can compute\n `\\gamma_i = \\max(c) / c_i` where `(c_i)_i` are the translation factors\n of the root system. In a more type-dependent way, we can define `\\gamma_i`\n as follows:\n\n 1. There exists a unique arrow (multiple bond) in `X`.\n\n a. Suppose the arrow points towards 0. Then `\\gamma_i = 1` for all\n `i \\in I`.\n b. Otherwise `\\gamma_i` is the order of `\\sigma` for all `i` in the\n connected component of 0 after removing the arrow, else\n `\\gamma_i = 1`.\n\n 2. There is not a unique arrow. Thus `\\hat{X} = A_{2n-1}^{(1)}` and\n `\\gamma_i = 1` for all `1 \\leq i \\leq n-1`. If `i \\in \\{0, n\\}`, then\n `\\gamma_i = 2` if the arrow incident to `i` points away and is `1`\n otherwise.\n\n We note that `\\gamma_i` only depends upon `X`.\n\n If the Cartan type is finite, then we consider the classical\n foldings/embeddings induced by the above affine foldings/embeddings:\n\n .. MATH::\n\n \\begin{aligned}\n C_n & \\hookrightarrow A_{2n-1}, \\\\\n B_n & \\hookrightarrow D_{n+1}, \\\\\n F_4 & \\hookrightarrow E_6, \\\\\n G_2 & \\hookrightarrow D_4.\n \\end{aligned}\n\n For more information on Cartan types, see\n :mod:`sage.combinat.root_system.cartan_type`.\n\n Other foldings may be constructed by passing in an optional\n ``folding_of`` second argument. See below.\n\n INPUT:\n\n - ``cartan_type`` -- the Cartan type `X` to create the folded type\n\n - ``folding_of`` -- the Cartan type `\\hat{X}` which `X` is a folding of\n\n - ``orbit`` -- the orbit of the Dynkin diagram automorphism `\\sigma`\n given as a list of lists where the `a`-th list corresponds to the `a`-th\n entry in `I` or a dictionary with keys in `I` and values as lists\n\n .. NOTE::\n\n If `X` is an affine type, we assume the special node is fixed\n under `\\sigma`.\n\n EXAMPLES::\n\n sage: fct = CartanType([\'C\',4,1]).as_folding(); fct\n [\'C\', 4, 1] as a folding of [\'A\', 7, 1]\n sage: fct.scaling_factors() # needs sage.graphs\n Finite family {0: 2, 1: 1, 2: 1, 3: 1, 4: 2}\n sage: fct.folding_orbit()\n Finite family {0: (0,), 1: (1, 7), 2: (2, 6), 3: (3, 5), 4: (4,)}\n\n A simply laced Cartan type can be considered as a virtual type of\n itself::\n\n sage: fct = CartanType([\'A\',4,1]).as_folding(); fct\n [\'A\', 4, 1] as a folding of [\'A\', 4, 1]\n sage: fct.scaling_factors() # needs sage.graphs\n Finite family {0: 1, 1: 1, 2: 1, 3: 1, 4: 1}\n sage: fct.folding_orbit()\n Finite family {0: (0,), 1: (1,), 2: (2,), 3: (3,), 4: (4,)}\n\n Finite types::\n\n sage: fct = CartanType([\'C\',4]).as_folding(); fct\n [\'C\', 4] as a folding of [\'A\', 7]\n sage: fct.scaling_factors()\n Finite family {1: 1, 2: 1, 3: 1, 4: 2}\n sage: fct.folding_orbit()\n Finite family {1: (1, 7), 2: (2, 6), 3: (3, 5), 4: (4,)}\n\n sage: fct = CartanType([\'F\',4]).dual().as_folding(); fct\n [\'F\', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1} as a folding of [\'E\', 6]\n sage: fct.scaling_factors()\n Finite family {1: 1, 2: 1, 3: 2, 4: 2}\n sage: fct.folding_orbit()\n Finite family {1: (1, 6), 2: (3, 5), 3: (4,), 4: (2,)}\n\n REFERENCES:\n\n - :wikipedia:`Dynkin_diagram#Folding`\n\n .. [OSShimo03] \\M. Okado, A. Schilling, M. Shimozono.\n "Virtual crystals and fermionic formulas for type `D_{n+1}^{(2)}`,\n `A_{2n}^{(2)}`, and `C_n^{(1)}`". Representation Theory. **7** (2003).\n 101-163. :doi:`10.1.1.192.2095`, :arxiv:`0810.5067`.\n ' @staticmethod def __classcall_private__(cls, cartan_type, virtual, orbit): "\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: from sage.combinat.root_system.type_folded import CartanTypeFolded\n sage: sigma_list = [[0], [1,5], [2,4], [3]]\n sage: fct1 = CartanTypeFolded(['C',3,1], ['A',5,1], sigma_list)\n sage: sigma_tuple = tuple(map(tuple, sigma_list))\n sage: fct2 = CartanTypeFolded(CartanType(['C',3,1]), CartanType(['A',5,1]), sigma_tuple)\n sage: fct3 = CartanTypeFolded('C3~', 'A5~', {0:[0], 2:[2,4], 1:[1,5], 3:[3]})\n sage: fct1 is fct2 and fct2 is fct3\n True\n " if isinstance(cartan_type, CartanTypeFolded): return cartan_type cartan_type = CartanType(cartan_type) virtual = CartanType(virtual) if isinstance(orbit, dict): i_set = cartan_type.index_set() orb = ([None] * len(i_set)) for (k, v) in orbit.items(): orb[i_set.index(k)] = tuple(v) orbit = tuple(orb) else: orbit = tuple(map(tuple, orbit)) return super().__classcall__(cls, cartan_type, virtual, orbit) def __init__(self, cartan_type, folding_of, orbit): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: fct = CartanType(['C',4,1]).as_folding()\n sage: TestSuite(fct).run()\n sage: hash(fct) # random\n 42\n " self._cartan_type = cartan_type self._folding = folding_of self._orbit = orbit def _repr_(self): "\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['C',4,1]).as_folding()\n ['C', 4, 1] as a folding of ['A', 7, 1]\n " return '{} as a folding of {}'.format(self._cartan_type, self._folding) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: fct = CartanType(['C', 4, 1]).as_folding()\n sage: latex(fct)\n C_{4}^{(1)} \\hookrightarrow A_{7}^{(1)}\n " return ((self._cartan_type._latex_() + ' \\hookrightarrow ') + self._folding._latex_()) def cartan_type(self): "\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: fct = CartanType(['C', 4, 1]).as_folding()\n sage: fct.cartan_type()\n ['C', 4, 1]\n " return self._cartan_type def folding_of(self): "\n Return the Cartan type of the virtual space.\n\n EXAMPLES::\n\n sage: fct = CartanType(['C', 4, 1]).as_folding()\n sage: fct.folding_of()\n ['A', 7, 1]\n " return self._folding @cached_method def folding_orbit(self): "\n Return the orbits under the automorphism `\\sigma` as a\n dictionary (of tuples).\n\n EXAMPLES::\n\n sage: fct = CartanType(['C', 4, 1]).as_folding()\n sage: fct.folding_orbit()\n Finite family {0: (0,), 1: (1, 7), 2: (2, 6), 3: (3, 5), 4: (4,)}\n " return Family({i: tuple(self._orbit[pos]) for (pos, i) in enumerate(self._cartan_type.index_set())}) @cached_method def scaling_factors(self): "\n Return the scaling factors of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: fct = CartanType(['C', 4, 1]).as_folding()\n sage: fct.scaling_factors()\n Finite family {0: 2, 1: 1, 2: 1, 3: 1, 4: 2}\n sage: fct = CartanType(['BC', 4, 2]).as_folding()\n sage: fct.scaling_factors()\n Finite family {0: 1, 1: 1, 2: 1, 3: 1, 4: 2}\n sage: fct = CartanType(['BC', 4, 2]).dual().as_folding()\n sage: fct.scaling_factors()\n Finite family {0: 2, 1: 1, 2: 1, 3: 1, 4: 1}\n sage: CartanType(['BC', 4, 2]).relabel({0:4, 1:3, 2:2, 3:1, 4:0}).as_folding().scaling_factors()\n Finite family {0: 2, 1: 1, 2: 1, 3: 1, 4: 1}\n " if self._cartan_type.is_finite(): L = self._cartan_type.root_system().ambient_space() def f(i): root = L.simple_root(i) coroot = L.simple_coroot(i) return (root.leading_coefficient() / coroot.leading_coefficient()) index_set = self._cartan_type.index_set() min_f = min((f(j) for j in index_set)) return Family(dict(((i, int((f(i) / min_f))) for i in index_set))) elif self._cartan_type.is_affine(): c = self._cartan_type.translation_factors() cmax = max(c) return Family(dict(((i, int((cmax / c[i]))) for i in self._cartan_type.index_set())))
class CartanType(cartan_type.CartanType_decorator): "\n A class for Cartan types with marked nodes.\n\n INPUT:\n\n - ``ct`` -- a Cartan type\n\n - ``marked_nodes`` -- a list of marked nodes\n\n EXAMPLES:\n\n We take the Cartan type `B_4`::\n\n sage: T = CartanType(['B',4])\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 1 2 3 4\n B4\n\n And mark some of its nodes::\n\n sage: T = T.marked_nodes([2,3])\n sage: T.dynkin_diagram() # needs sage.graphs\n O---X---X=>=O\n 1 2 3 4\n B4 with nodes (2, 3) marked\n\n Markings are not additive::\n\n sage: T.marked_nodes([1,4]).dynkin_diagram() # needs sage.graphs\n X---O---O=>=X\n 1 2 3 4\n B4 with nodes (1, 4) marked\n\n And trivial relabelling are honoured nicely::\n\n sage: T = T.marked_nodes([])\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 1 2 3 4\n B4\n " @staticmethod def __classcall__(cls, ct, marked_nodes): "\n This standardizes the input of the constructor to ensure\n unique representation.\n\n EXAMPLES::\n\n sage: ct1 = CartanType(['B',2]).marked_nodes([1,2])\n sage: ct2 = CartanType(['B',2]).marked_nodes([2,1])\n sage: ct3 = CartanType(['B',2]).marked_nodes((1,2))\n sage: ct4 = CartanType(['D',4]).marked_nodes([1,2])\n sage: ct1 is ct2\n True\n sage: ct1 is ct3\n True\n sage: ct1 == ct4\n False\n " ct = cartan_type.CartanType(ct) if (not marked_nodes): return ct if any(((node not in ct.index_set()) for node in marked_nodes)): raise ValueError('invalid marked node') marked_nodes = tuple(sorted(marked_nodes)) return super().__classcall__(cls, ct, marked_nodes) def __init__(self, ct, marked_nodes): "\n Return an isomorphic Cartan type obtained by marking the\n nodes of the Dynkin diagram.\n\n TESTS:\n\n Test that the produced Cartan type is in the appropriate\n abstract classes::\n\n sage: ct = CartanType(['B',4]).marked_nodes([1,2])\n sage: TestSuite(ct).run()\n sage: from sage.combinat.root_system import cartan_type\n sage: isinstance(ct, cartan_type.CartanType_finite)\n True\n sage: isinstance(ct, cartan_type.CartanType_simple)\n True\n sage: isinstance(ct, cartan_type.CartanType_affine)\n False\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n False\n\n sage: ct = CartanType(['A',3,1]).marked_nodes([1,2])\n sage: TestSuite(ct).run()\n sage: isinstance(ct, cartan_type.CartanType_simple)\n True\n sage: isinstance(ct, cartan_type.CartanType_finite)\n False\n sage: isinstance(ct, cartan_type.CartanType_affine)\n True\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n True\n " cartan_type.CartanType_decorator.__init__(self, ct) self._marked_nodes = marked_nodes if ct.is_finite(): self.__class__ = CartanType_finite elif ct.is_affine(): self.__class__ = CartanType_affine abstract_classes = tuple((cls for cls in self._stable_abstract_classes if isinstance(ct, cls))) if abstract_classes: self._add_abstract_superclass(abstract_classes) _stable_abstract_classes = [cartan_type.CartanType_finite, cartan_type.CartanType_affine, cartan_type.CartanType_simple, cartan_type.CartanType_simply_laced, cartan_type.CartanType_crystallographic] def _repr_(self, compact=False): '\n EXAMPLES::\n\n sage: CartanType([\'F\', 4]).marked_nodes([2])\n [\'F\', 4] with node 2 marked\n\n sage: CartanType([\'F\', 4, 1]).dual().marked_nodes([0, 2])\n [\'F\', 4, 1]^* with nodes (0, 2) marked\n\n sage: CartanType([\'F\', 4, 1]).marked_nodes([0, 2])._repr_(compact = True)\n \'F4~ with nodes (0, 2) marked\'\n\n sage: D = DynkinDiagram("A2") # needs sage.graphs\n sage: D.marked_nodes([1]) # needs sage.graphs\n O---O\n 1 2\n A2 with node 1 marked\n\n sage: CM = CartanMatrix([[2,-4],[-5,2]]) # needs sage.graphs\n sage: CM.marked_nodes([1]) # needs sage.graphs\n [ 2 -4]\n [-5 2] with node 1 marked\n ' if (not compact): base = repr(self._type) else: try: base = self._type._repr_(compact=True) except TypeError: base = repr(self._type) if (len(self._marked_nodes) == 1): return (base + ' with node {} marked'.format(self._marked_nodes[0])) return (base + ' with nodes {} marked'.format(self._marked_nodes)) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',4]).marked_nodes([1, 3])\n sage: latex(ct)\n A_{4} \\text{ with nodes $\\left(1, 3\\right)$ marked}\n\n A more compact, but potentially confusing, representation can\n be obtained using the ``latex_marked`` global option::\n\n sage: CartanType.options['latex_marked'] = False\n sage: latex(ct)\n A_{4}\n sage: CartanType.options['latex_marked'] = True\n\n Kac's notations are implemented::\n\n sage: CartanType.options['notation'] = 'Kac'\n sage: latex(CartanType(['D',4,3]).marked_nodes([0]))\n D_4^{(3)} \\text{ with node $0$ marked}\n sage: CartanType.options._reset()\n " from sage.misc.latex import latex ret = self._type._latex_() if self.options('latex_marked'): if (len(self._marked_nodes) == 1): ret += ' \\text{{ with node ${}$ marked}} '.format(latex(self._marked_nodes[0])) else: ret += ' \\text{{ with nodes ${}$ marked}} '.format(latex(self._marked_nodes)) return ret def _ascii_art_node(self, label): "\n Return the ascii art for the node labeled by ``label``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',4]).marked_nodes([1, 2])\n sage: ct._ascii_art_node(1)\n 'X'\n sage: ct._ascii_art_node(3)\n 'O'\n sage: CartanType.options._reset()\n " if (label in self._marked_nodes): return self.options('marked_node_str') return 'O' def _latex_draw_node(self, x, y, label, position='below=4pt', fill='white'): "\n Draw (possibly marked [crossed out]) circular node ``i`` at the\n position ``(x,y)`` with node label ``label`` .\n\n - ``position`` -- position of the label relative to the node\n - ``anchor`` -- (optional) the anchor point for the label\n\n EXAMPLES::\n\n sage: CartanType.options(mark_special_node='both')\n sage: CartanType(['A',3,1]).marked_nodes([1,3])._latex_draw_node(0, 0, 0)\n '\\\\draw[fill=black] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\\n'\n sage: CartanType.options._reset()\n " ret = cartan_type.CartanType_abstract._latex_draw_node(self, x, y, label, position, fill) if (label in self._marked_nodes): ret += self._latex_draw_mark(x, y) return ret def _latex_draw_mark(self, x, y, color='black', thickness='thin'): "\n Draw a mark as a cross `\\times` at the point ``(x, y)``.\n\n INPUT:\n\n - ``(x, y)`` -- the coordinates of a point, in cm\n\n - ``color`` -- the color of the mark\n\n This is an internal function used to assist drawing marked points of\n the Dynkin diagrams. See e.g.\n :meth:`~sage.combinat.root_system.type_marked.CartanType._latex_dynkin_diagram`.\n\n EXAMPLES::\n\n sage: print(CartanType(['B',2]).marked_nodes([1,2])._latex_draw_mark(1, 0))\n \\draw[shift={(1, 0)}, black, thin] (0.25cm, 0.25cm) -- (-0.25cm, -0.25cm);\n \\draw[shift={(1, 0)}, black, thin] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n <BLANKLINE>\n " ret = '\\draw[shift={{({}, {})}}, {}, {}] (0.25cm, 0.25cm) -- (-0.25cm, -0.25cm);\n'.format(x, y, color, thickness) ret += '\\draw[shift={{({}, {})}}, {}, {}] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n'.format(x, y, color, thickness) return ret def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['A',4]).marked_nodes([1,3])._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (6 cm,0);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[shift={(0, 0)}, black, thin] (0.25cm, 0.25cm) -- (-0.25cm, -0.25cm);\n \\draw[shift={(0, 0)}, black, thin] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[shift={(4, 0)}, black, thin] (0.25cm, 0.25cm) -- (-0.25cm, -0.25cm);\n \\draw[shift={(4, 0)}, black, thin] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node return self._type._latex_dynkin_diagram(label, node, node_dist) def ascii_art(self, label=None, node=None): '\n Return an ascii art representation of this Cartan type.\n\n EXAMPLES::\n\n sage: print(CartanType(["G", 2]).marked_nodes([2]).ascii_art())\n 3\n O=<=X\n 1 2\n sage: print(CartanType(["B", 3, 1]).marked_nodes([0, 3]).ascii_art())\n X 0\n |\n |\n O---O=>=X\n 1 2 3\n sage: print(CartanType(["F", 4, 1]).marked_nodes([0, 2]).ascii_art())\n X---O---X=>=O---O\n 0 1 2 3 4\n ' if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node return self._type.ascii_art(label, node) def dynkin_diagram(self): '\n Return the Dynkin diagram for this Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(["G", 2]).marked_nodes([2]).dynkin_diagram() # needs sage.graphs\n 3\n O=<=X\n 1 2\n G2 with node 2 marked\n\n TESTS:\n\n To be compared with the examples in :meth:`ascii_art`::\n\n sage: CartanType(["G", 2]).relabel({1:2,2:1}).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (2, 1, 1)]\n sage: CartanType(["B", 3, 1]).relabel([1,3,2,0]).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(0, 2, 1), (1, 2, 1), (2, 0, 2), (2, 1, 1), (2, 3, 1), (3, 2, 1)]\n sage: CartanType(["F", 4, 1]).relabel(lambda n: 4-n).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(0, 1, 1), (1, 0, 1), (1, 2, 1), (2, 1, 2), (2, 3, 1), (3, 2, 1), (3, 4, 1), (4, 3, 1)]\n ' result = self._type.dynkin_diagram().copy() result._cartan_type = self return result def dual(self): '\n Implements\n :meth:`sage.combinat.root_system.cartan_type.CartanType_abstract.dual`,\n using that taking the dual and marking nodes are commuting operations.\n\n EXAMPLES::\n\n sage: T = CartanType(["BC",3, 2])\n sage: T.marked_nodes([1,3]).dual().dynkin_diagram() # needs sage.graphs\n O=>=X---O=>=X\n 0 1 2 3\n BC3~* with nodes (1, 3) marked\n sage: T.dual().marked_nodes([1,3]).dynkin_diagram() # needs sage.graphs\n O=>=X---O=>=X\n 0 1 2 3\n BC3~* with nodes (1, 3) marked\n ' return self._type.dual().marked_nodes(self._marked_nodes) def relabel(self, relabelling): '\n Return the relabelling of ``self``.\n\n EXAMPLES::\n\n sage: T = CartanType(["BC",3, 2])\n sage: T.marked_nodes([1,3]).relabel(lambda x: x+2).dynkin_diagram() # needs sage.graphs\n O=<=X---O=<=X\n 2 3 4 5\n BC3~ relabelled by {0: 2, 1: 3, 2: 4, 3: 5} with nodes (3, 5) marked\n sage: T.relabel(lambda x: x+2).marked_nodes([3,5]).dynkin_diagram() # needs sage.graphs\n O=<=X---O=<=X\n 2 3 4 5\n BC3~ relabelled by {0: 2, 1: 3, 2: 4, 3: 5} with nodes (3, 5) marked\n ' rct = self._type.relabel(relabelling) rd = rct._relabelling marked_nodes = [rd[node] for node in self._marked_nodes] return rct.marked_nodes(marked_nodes) def marked_nodes(self, marked_nodes): "\n Return ``self`` with nodes ``marked_nodes`` marked.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',12])\n sage: m = ct.marked_nodes([1,4,6,7,8,12]); m\n ['A', 12] with nodes (1, 4, 6, 7, 8, 12) marked\n sage: m.marked_nodes([2])\n ['A', 12] with node 2 marked\n sage: m.marked_nodes([]) is ct\n True\n " if (not marked_nodes): return self._type return CartanType(self._type, marked_nodes) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n If a node `a` is marked, then all nodes in the orbit of `a` are marked\n in the ambient type.\n\n EXAMPLES::\n\n sage: fct = CartanType(['D', 4, 3])._default_folded_cartan_type(); fct\n ['G', 2, 1]^* relabelled by {0: 0, 1: 2, 2: 1} as a folding of ['D', 4, 1]\n sage: fct.folding_orbit()\n Finite family {0: (0,), 1: (2,), 2: (1, 3, 4)}\n sage: CartanType(['G',2,1]).dual()._default_folded_cartan_type().folding_orbit()\n Finite family {0: (0,), 1: (1, 3, 4), 2: (2,)}\n sage: CartanType(['C',3,1]).relabel({0:1, 1:0, 2:3, 3:2}).as_folding().scaling_factors() # needs sage.graphs\n Finite family {0: 1, 1: 2, 2: 2, 3: 1}\n " from sage.combinat.root_system.type_folded import CartanTypeFolded vct = self._type._default_folded_cartan_type() sigma = vct.folding_orbit() marked_nodes = sum([sigma[i] for i in self._marked_nodes], ()) folding = vct._folding.marked_nodes(marked_nodes) return CartanTypeFolded(self, folding, sigma) def type(self): "\n Return the type of ``self`` or ``None`` if unknown.\n\n EXAMPLES::\n\n sage: ct = CartanType(['F', 4]).marked_nodes([1,3])\n sage: ct.type()\n 'F'\n " return self._type.type()
class AmbientSpace(ambient_space.AmbientSpace): '\n Ambient space for a marked finite Cartan type.\n\n It is constructed in the canonical way from the ambient space of\n the original Cartan type.\n\n EXAMPLES::\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space(); L\n Ambient space of the Root system of type [\'F\', 4] with nodes (1, 3) marked\n sage: TestSuite(L).run() # needs sage.graphs\n ' @lazy_attribute def _space(self): '\n The ambient space this is a marking of.\n\n EXAMPLES::\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space()\n sage: L._space\n Ambient space of the Root system of type [\'F\', 4]\n ' K = self.base_ring() return self.cartan_type()._type.root_system().ambient_space(K) def dimension(self): '\n Return the dimension of this ambient space.\n\n .. SEEALSO:: :meth:`sage.combinat.root_system.ambient_space.AmbientSpace.dimension`\n\n EXAMPLES::\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space()\n sage: L.dimension()\n 4\n ' return self.root_system.cartan_type()._type.root_system().ambient_space().dimension() @cached_method def simple_root(self, i): '\n Return the ``i``-th simple root.\n\n It is constructed by looking up the corresponding simple\n coroot in the ambient space for the original Cartan type.\n\n EXAMPLES::\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space()\n sage: L.simple_root(1)\n (0, 1, -1, 0)\n sage: L.simple_roots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1),\n 3: (0, 0, 0, 1), 4: (1/2, -1/2, -1/2, -1/2)}\n sage: L.simple_coroots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1),\n 3: (0, 0, 0, 2), 4: (1, -1, -1, -1)}\n ' return self.sum_of_terms(self._space.simple_root(i)) @cached_method def fundamental_weight(self, i): '\n Return the ``i``-th fundamental weight.\n\n It is constructed by looking up the corresponding simple\n coroot in the ambient space for the original Cartan type.\n\n EXAMPLES::\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space()\n sage: L.fundamental_weight(1)\n (1, 1, 0, 0)\n sage: L.fundamental_weights()\n Finite family {1: (1, 1, 0, 0), 2: (2, 1, 1, 0),\n 3: (3/2, 1/2, 1/2, 1/2), 4: (1, 0, 0, 0)}\n ' return self.sum_of_terms(self._space.fundamental_weight(i)) @lazy_attribute def _plot_projection(self): '\n A hack so that if an ambient space uses barycentric projection,\n then so does its dual.\n\n EXAMPLES::\n\n sage: L = CartanType(["G",2]).marked_nodes([1]).root_system().ambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n True\n\n sage: L = CartanType(["F",4]).marked_nodes([1,3]).root_system().ambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n False\n ' if (self._space._plot_projection == self._space._plot_projection_barycentric): return self._plot_projection_barycentric else: RootLatticeRealizations.ParentMethods.__dict__['_plot_projection']
class CartanType_finite(CartanType, cartan_type.CartanType_finite): AmbientSpace = AmbientSpace def affine(self): "\n Return the affine Cartan type associated with ``self``.\n\n EXAMPLES::\n\n sage: B4 = CartanType(['B',4]).marked_nodes([1,3])\n sage: B4.dynkin_diagram() # needs sage.graphs\n X---O---X=>=O\n 1 2 3 4\n B4 with nodes (1, 3) marked\n sage: B4.affine().dynkin_diagram() # needs sage.graphs\n O 0\n |\n |\n X---O---X=>=O\n 1 2 3 4\n B4~ with nodes (1, 3) marked\n\n TESTS:\n\n Check that we don't inadvertently change the internal\n marking of ``ct``::\n\n sage: ct = CartanType(['F', 4]).marked_nodes([1,3])\n sage: ct.affine()\n ['F', 4, 1] with nodes (1, 3) marked\n sage: ct\n ['F', 4] with nodes (1, 3) marked\n " return self._type.affine().marked_nodes(self._marked_nodes)
class CartanType_affine(CartanType, cartan_type.CartanType_affine): "\n TESTS::\n\n sage: ct = CartanType(['B',3,1]).marked_nodes([1,3])\n sage: ct\n ['B', 3, 1] with nodes (1, 3) marked\n\n sage: L = ct.root_system().ambient_space(); L\n Ambient space of the Root system of type ['B', 3, 1] with nodes (1, 3) marked\n sage: L.classical()\n Ambient space of the Root system of type ['B', 3] with nodes (1, 3) marked\n sage: TestSuite(L).run()\n " def _latex_draw_node(self, x, y, label, position='below=4pt'): "\n Draw the possibly marked (crossed out) circular node ``i`` at the\n position ``(x,y)`` with node label ``label`` .\n\n - ``position`` -- position of the label relative to the node\n - ``anchor`` -- (optional) the anchor point for the label\n\n EXAMPLES::\n\n sage: CartanType.options(mark_special_node='both')\n sage: print(CartanType(['A',3,1]).marked_nodes([0,1,3])._latex_draw_node(0, 0, 0))\n \\draw[fill=black] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[shift={(0, 0)}, lightgray, very thick] (0.25cm, 0.25cm) -- (-0.25cm, -0.25cm);\n \\draw[shift={(0, 0)}, lightgray, very thick] (0.25cm, -0.25cm) -- (-0.25cm, 0.25cm);\n <BLANKLINE>\n sage: CartanType.options._reset()\n " mark_special = ((label == self.special_node()) and (self.options('mark_special_node') in ['latex', 'both'])) if mark_special: fill = 'black' else: fill = 'white' ret = cartan_type.CartanType_abstract._latex_draw_node(self, x, y, label, position, fill) if (label in self._marked_nodes): if mark_special: ret += self._latex_draw_mark(x, y, 'lightgray', 'very thick') else: ret += self._latex_draw_mark(x, y) return ret def _ascii_art_node(self, label): "\n Return the ascii art for the node labeled by ``label``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',4, 1]).marked_nodes([0, 2])\n sage: CartanType.options(mark_special_node='both')\n sage: ct._ascii_art_node(0)\n '#'\n sage: CartanType.options._reset()\n " if (label in self._marked_nodes): if ((label == self.special_node()) and (self.options('mark_special_node') in ['printing', 'both'])): return '#' return self.options('marked_node_str') return 'O' def classical(self): "\n Return the classical Cartan type associated with ``self``.\n\n EXAMPLES::\n\n sage: T = CartanType(['A',4,1]).marked_nodes([0,2,4])\n sage: T.dynkin_diagram() # needs sage.graphs\n 0\n X-----------+\n | |\n | |\n O---X---O---X\n 1 2 3 4\n A4~ with nodes (0, 2, 4) marked\n\n sage: T0 = T.classical(); T0\n ['A', 4] with nodes (2, 4) marked\n sage: T0.dynkin_diagram() # needs sage.graphs\n O---X---O---X\n 1 2 3 4\n A4 with nodes (2, 4) marked\n " if (self._type.special_node() in self._marked_nodes): marked_nodes = list(self._marked_nodes) marked_nodes.remove(self._type.special_node()) return self._type.classical().marked_nodes(marked_nodes) return self._type.classical().marked_nodes(self._marked_nodes) def basic_untwisted(self): "\n Return the basic untwisted Cartan type associated with this affine\n Cartan type.\n\n Given an affine type `X_n^{(r)}`, the basic untwisted type is `X_n`.\n In other words, it is the classical Cartan type that is twisted to\n obtain ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', 7, 2]).marked_nodes([1,3]).basic_untwisted()\n ['A', 7] with nodes (1, 3) marked\n sage: CartanType(['D', 4, 3]).marked_nodes([0,2]).basic_untwisted()\n ['D', 4] with node 2 marked\n " if (self._type.special_node() in self._marked_nodes): marked_nodes = list(self._marked_nodes) marked_nodes.remove(self._type.special_node()) return self._type.basic_untwisted().marked_nodes(marked_nodes) return self._type.basic_untwisted().marked_nodes(self._marked_nodes) def special_node(self): "\n Return the special node of the Cartan type.\n\n .. SEEALSO:: :meth:`~sage.combinat.root_system.CartanType_affine.special_node`\n\n It is the special node of the non-marked Cartan type..\n\n EXAMPLES::\n\n sage: CartanType(['B', 3, 1]).marked_nodes([1,3]).special_node()\n 0\n " return self._type.special_node() def is_untwisted_affine(self): "\n Implement :meth:`CartanType_affine.is_untwisted_affine`.\n\n A marked Cartan type is untwisted affine if the original is.\n\n EXAMPLES::\n\n sage: CartanType(['B', 3, 1]).marked_nodes([1,3]).is_untwisted_affine()\n True\n " return self._type.is_untwisted_affine()
@richcmp_method class CartanType(SageObject, CartanType_abstract): '\n A class for reducible Cartan types.\n\n Reducible root systems are ones that can be factored as direct\n products. Strictly speaking type `D_2` (corresponding to\n orthogonal groups of degree 4) is reducible since it is\n isomorphic to `A_1\\times A_1`. However type `D_2` is not built\n using this class for our purposes.\n\n INPUT:\n\n - ``types`` -- a list of simple Cartan types\n\n EXAMPLES::\n\n sage: t1, t2 = [CartanType(x) for x in ([\'A\',1], [\'B\',2])]\n sage: CartanType([t1, t2])\n A1xB2\n sage: t = CartanType("A2xB2")\n\n A reducible Cartan type is finite (resp. crystallographic,\n simply laced) if all its components are::\n\n sage: t.is_finite()\n True\n sage: t.is_crystallographic()\n True\n sage: t.is_simply_laced()\n False\n\n This is implemented by inserting the appropriate abstract\n super classes (see :meth:`~sage.combinat.root_system.cartan_type.CartanType_abstract._add_abstract_superclass`)::\n\n sage: t.__class__.mro()\n [<class \'sage.combinat.root_system.type_reducible.CartanType_with_superclass\'>, <class \'sage.combinat.root_system.type_reducible.CartanType\'>, <class \'sage.structure.sage_object.SageObject\'>, <class \'sage.combinat.root_system.cartan_type.CartanType_finite\'>, <class \'sage.combinat.root_system.cartan_type.CartanType_crystallographic\'>, <class \'sage.combinat.root_system.cartan_type.CartanType_abstract\'>, <class \'object\'>]\n\n The index set of the reducible Cartan type is obtained by\n relabelling successively the nodes of the Dynkin diagrams of\n the components by 1,2,...::\n\n sage: t = CartanType(["A",4], ["BC",5,2], ["C",3])\n sage: t.index_set()\n (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)\n\n sage: t.dynkin_diagram() # needs sage.graphs\n O---O---O---O\n 1 2 3 4\n O=<=O---O---O---O=<=O\n 5 6 7 8 9 10\n O---O=<=O\n 11 12 13\n A4xBC5~xC3\n ' def __init__(self, types): '\n Initialize ``self``.\n\n TESTS:\n\n Internally, this relabelling is stored as a dictionary::\n\n sage: t = CartanType(["A",4], ["BC",5,2], ["C",3])\n sage: sorted(t._index_relabelling.items())\n [((0, 1), 1), ((0, 2), 2), ((0, 3), 3), ((0, 4), 4),\n ((1, 0), 5), ((1, 1), 6), ((1, 2), 7), ((1, 3), 8), ((1, 4), 9), ((1, 5), 10),\n ((2, 1), 11), ((2, 2), 12), ((2, 3), 13)]\n\n Similarly, the attribute `_shifts` specifies by how much the\n indices of the bases of the ambient spaces of the components\n are shifted in the ambient space of this Cartan type::\n\n sage: t = CartanType("A2xB2")\n sage: t._shifts\n [0, 3, 5]\n sage: A = t.root_system().ambient_space(); A\n Ambient space of the Root system of type A2xB2\n sage: A.ambient_spaces()\n [Ambient space of the Root system of type [\'A\', 2], Ambient space of the Root system of type [\'B\', 2]]\n sage: x = A.ambient_spaces()[0]([2,1,0]); x\n (2, 1, 0)\n sage: A.inject_weights(0,x)\n (2, 1, 0, 0, 0)\n sage: x = A.ambient_spaces()[1]([1,0]); x\n (1, 0)\n sage: A.inject_weights(1,x)\n (0, 0, 0, 1, 0)\n\n More tests::\n\n sage: TestSuite(t).run()\n ' self._types = types self.affine = False indices = ((None,) + tuple(((i, j) for i in range(len(types)) for j in types[i].index_set()))) self._indices = indices self._index_relabelling = dict(((indices[i], i) for i in range(1, len(indices)))) self._spaces = [t.root_system().ambient_space() for t in types] if all(((l is not None) for l in self._spaces)): self._shifts = [sum((l.dimension() for l in self._spaces[:k])) for k in range((len(types) + 1))] self.tools = root_system.type_reducible super_classes = tuple((cls for cls in (CartanType_finite, CartanType_simply_laced, CartanType_crystallographic) if all((isinstance(t, cls) for t in types)))) self._add_abstract_superclass(super_classes) def _repr_(self, compact=True): '\n EXAMPLES::\n\n sage: CartanType("A2","B2") # indirect doctest\n A2xB2\n\n sage: CartanType("A2",CartanType("F4~").dual())\n A2xF4~*\n ' return 'x'.join((t._repr_(compact=True) for t in self._types)) def _latex_(self): '\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType("A4","B2","D8"))\n A_{4} \\times B_{2} \\times D_{8}\n ' return ' \\times '.join((x._latex_() for x in self.component_types())) def __hash__(self): "\n EXAMPLES::\n\n sage: ct0 = CartanType(['A',1],['B',2])\n sage: ct1 = CartanType(['A',2],['B',3])\n sage: hash(ct0) != hash(ct1)\n True\n " return hash(repr(self._types)) def __richcmp__(self, other, op): '\n Rich comparison.\n\n EXAMPLES::\n\n sage: ct1 = CartanType([\'A\',1],[\'B\',2])\n sage: ct2 = CartanType([\'B\',2],[\'A\',1])\n sage: ct3 = CartanType([\'A\',4])\n sage: ct1 == ct1\n True\n sage: ct1 == ct2\n False\n sage: ct1 == ct3\n False\n\n TESTS:\n\n Check that :trac:`20418` is fixed::\n\n sage: ct = CartanType(["A2", "B2"])\n sage: ct == (1, 2, 1)\n False\n ' if isinstance(other, CartanType_simple): return rich_to_bool(op, 1) if (not isinstance(other, CartanType)): return NotImplemented return richcmp(self._types, other._types, op) def component_types(self): "\n A list of Cartan types making up the reducible type.\n\n EXAMPLES::\n\n sage: CartanType(['A',2],['B',2]).component_types()\n [['A', 2], ['B', 2]]\n " return self._types def type(self): '\n Returns "reducible" since the type is reducible.\n\n EXAMPLES::\n\n sage: CartanType([\'A\',2],[\'B\',2]).type()\n \'reducible\'\n ' return 'reducible' def rank(self): '\n Returns the rank of self.\n\n EXAMPLES::\n\n sage: CartanType("A2","A1").rank()\n 3\n ' return sum((t.rank() for t in self._types)) @cached_method def index_set(self): '\n Implements :meth:`CartanType_abstract.index_set`.\n\n For the moment, the index set is always of the form `\\{1, \\ldots, n\\}`.\n\n EXAMPLES::\n\n sage: CartanType("A2","A1").index_set()\n (1, 2, 3)\n ' return tuple(range(1, (self.rank() + 1))) def cartan_matrix(self, subdivide=True): '\n Return the Cartan matrix associated with ``self``. By default\n the Cartan matrix is a subdivided block matrix showing the\n reducibility but the subdivision can be suppressed with\n the option ``subdivide = False``.\n\n EXAMPLES::\n\n sage: ct = CartanType("A2","B2")\n sage: ct.cartan_matrix() # needs sage.graphs\n [ 2 -1| 0 0]\n [-1 2| 0 0]\n [-----+-----]\n [ 0 0| 2 -1]\n [ 0 0|-2 2]\n sage: ct.cartan_matrix(subdivide=False) # needs sage.graphs\n [ 2 -1 0 0]\n [-1 2 0 0]\n [ 0 0 2 -1]\n [ 0 0 -2 2]\n sage: ct.index_set() == ct.cartan_matrix().index_set() # needs sage.graphs\n True\n ' from sage.combinat.root_system.cartan_matrix import CartanMatrix return CartanMatrix(block_diagonal_matrix([t.cartan_matrix() for t in self._types], subdivide=subdivide), cartan_type=self, index_set=self.index_set()) def dynkin_diagram(self): '\n Returns a Dynkin diagram for type reducible.\n\n EXAMPLES::\n\n sage: dd = CartanType("A2xB2xF4").dynkin_diagram(); dd # needs sage.graphs\n O---O\n 1 2\n O=>=O\n 3 4\n O---O=>=O---O\n 5 6 7 8\n A2xB2xF4\n sage: dd.edges(sort=True) # needs sage.graphs\n [(1, 2, 1), (2, 1, 1), (3, 4, 2), (4, 3, 1), (5, 6, 1),\n (6, 5, 1), (6, 7, 2), (7, 6, 1), (7, 8, 1), (8, 7, 1)]\n\n sage: CartanType("F4xA2").dynkin_diagram() # needs sage.graphs\n O---O=>=O---O\n 1 2 3 4\n O---O\n 5 6\n F4xA2\n\n ' from .dynkin_diagram import DynkinDiagram_class relabelling = self._index_relabelling g = DynkinDiagram_class(self) for i in range(len(self._types)): for [e1, e2, l] in self._types[i].dynkin_diagram().edges(sort=True): g.add_edge(relabelling[(i, e1)], relabelling[(i, e2)], label=l) return g def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): '\n Return a latex representation of the Dynkin diagram.\n\n .. NOTE::\n\n The arguments ``label`` and ``dual`` is ignored.\n\n EXAMPLES::\n\n sage: print(CartanType("A2","B2")._latex_dynkin_diagram())\n {\n \\draw (0 cm,0) -- (2 cm,0);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n \\pgftransformyshift{-3 cm}\n \\draw (0 cm,0) -- (0 cm,0);\n \\draw (0 cm, 0.1 cm) -- +(2 cm,0);\n \\draw (0 cm, -0.1 cm) -- +(2 cm,0);\n \\draw[shift={(1.2, 0)}, rotate=0] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n }\n ' if (label is None): label = (lambda x: x) types = self.component_types() relabelling = self._index_relabelling ret = '{\n' ret += '\\pgftransformyshift{-3 cm}\n'.join((types[i]._latex_dynkin_diagram((lambda x: label(relabelling[(i, x)])), node, node_dist=node_dist) for i in range(len(types)))) ret += '}' return ret def ascii_art(self, label=None, node=None): '\n Return an ascii art representation of this reducible Cartan type.\n\n EXAMPLES::\n\n sage: print(CartanType("F4xA2").ascii_art(label = lambda x: x+2))\n O---O=>=O---O\n 3 4 5 6\n O---O\n 7 8\n\n sage: print(CartanType(["BC",5,2], ["A",4]).ascii_art())\n O=<=O---O---O---O=<=O\n 1 2 3 4 5 6\n O---O---O---O\n 7 8 9 10\n\n sage: print(CartanType(["A",4], ["BC",5,2], ["C",3]).ascii_art())\n O---O---O---O\n 1 2 3 4\n O=<=O---O---O---O=<=O\n 5 6 7 8 9 10\n O---O=<=O\n 11 12 13\n ' if (label is None): label = (lambda i: i) types = self.component_types() relabelling = self._index_relabelling return '\n'.join((types[i].ascii_art((lambda x: label(relabelling[(i, x)])), node) for i in range(len(types)))) @cached_method def is_finite(self): "\n EXAMPLES::\n\n sage: ct1 = CartanType(['A',2],['B',2])\n sage: ct1.is_finite()\n True\n sage: ct2 = CartanType(['A',2],['B',2,1])\n sage: ct2.is_finite()\n False\n\n TESTS::\n\n sage: isinstance(ct1, sage.combinat.root_system.cartan_type.CartanType_finite)\n True\n sage: isinstance(ct2, sage.combinat.root_system.cartan_type.CartanType_finite)\n False\n " return all((t.is_finite() for t in self.component_types())) def is_irreducible(self): "\n Report that this Cartan type is not irreducible.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',2],['B',2])\n sage: ct.is_irreducible()\n False\n " return False def dual(self): '\n EXAMPLES::\n\n sage: CartanType("A2xB2").dual()\n A2xC2\n ' return CartanType([t.dual() for t in self._types]) def is_affine(self): "\n Report that this reducible Cartan type is not affine\n\n EXAMPLES::\n\n sage: CartanType(['A',2],['B',2]).is_affine()\n False\n " return False @cached_method def coxeter_diagram(self): '\n Return the Coxeter diagram for ``self``.\n\n EXAMPLES::\n\n sage: cd = CartanType("A2xB2xF4").coxeter_diagram(); cd # needs sage.graphs\n Graph on 8 vertices\n sage: cd.edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (3, 4, 4), (5, 6, 3), (6, 7, 4), (7, 8, 3)]\n\n sage: CartanType("F4xA2").coxeter_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (2, 3, 4), (3, 4, 3), (5, 6, 3)]\n\n sage: cd = CartanType("A1xH3").coxeter_diagram(); cd # needs sage.graphs\n Graph on 4 vertices\n sage: cd.edges(sort=True) # needs sage.graphs\n [(2, 3, 3), (3, 4, 5)]\n ' from sage.graphs.graph import Graph relabelling = self._index_relabelling g = Graph(multiedges=False) g.add_vertices(self.index_set()) for (i, t) in enumerate(self._types): for [e1, e2, l] in t.coxeter_diagram().edges(sort=True): g.add_edge(relabelling[(i, e1)], relabelling[(i, e2)], label=l) return g
class AmbientSpace(ambient_space.AmbientSpace): '\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space()\n Ambient space of the Root system of type A2xB2\n\n ' def cartan_type(self): '\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space().cartan_type()\n A2xB2\n ' return self.root_system.cartan_type() def component_types(self): '\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space().component_types()\n [[\'A\', 2], [\'B\', 2]]\n ' return self.root_system.cartan_type().component_types() def dimension(self): '\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space().dimension()\n 5\n ' return sum((v.dimension() for v in self.ambient_spaces())) def ambient_spaces(self): '\n Returns a list of the irreducible Cartan types of which the\n given reducible Cartan type is a product.\n\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space().ambient_spaces()\n [Ambient space of the Root system of type [\'A\', 2],\n Ambient space of the Root system of type [\'B\', 2]]\n ' return [t.root_system().ambient_space() for t in self.component_types()] def inject_weights(self, i, v): '\n Produces the corresponding element of the lattice.\n\n INPUT:\n\n - ``i`` - an integer in range(self.components)\n\n - ``v`` - a vector in the i-th component weight lattice\n\n EXAMPLES::\n\n sage: V = RootSystem("A2xB2").ambient_space()\n sage: [V.inject_weights(i,V.ambient_spaces()[i].fundamental_weights()[1]) for i in range(2)]\n [(1, 0, 0, 0, 0), (0, 0, 0, 1, 0)]\n sage: [V.inject_weights(i,V.ambient_spaces()[i].fundamental_weights()[2]) for i in range(2)]\n [(1, 1, 0, 0, 0), (0, 0, 0, 1/2, 1/2)]\n ' shift = self.root_system.cartan_type()._shifts[i] return self._from_dict(dict([((shift + k), c) for (k, c) in v])) @cached_method def simple_root(self, i): '\n EXAMPLES::\n\n sage: A = RootSystem("A1xB2").ambient_space()\n sage: A.simple_root(2)\n (0, 0, 1, -1)\n sage: A.simple_roots()\n Finite family {1: (1, -1, 0, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 1)}\n ' if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) (i, j) = self.cartan_type()._indices[i] return self.inject_weights(i, self.ambient_spaces()[i].simple_root(j)) @cached_method def simple_coroot(self, i): '\n EXAMPLES::\n\n sage: A = RootSystem("A1xB2").ambient_space()\n sage: A.simple_coroot(2)\n (0, 0, 1, -1)\n sage: A.simple_coroots()\n Finite family {1: (1, -1, 0, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 2)}\n ' if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) (i, j) = self.cartan_type()._indices[i] return self.inject_weights(i, self.ambient_spaces()[i].simple_coroot(j)) def positive_roots(self): '\n EXAMPLES::\n\n sage: RootSystem("A1xA2").ambient_space().positive_roots()\n [(1, -1, 0, 0, 0), (0, 0, 1, -1, 0), (0, 0, 1, 0, -1), (0, 0, 0, 1, -1)]\n ' res = [] for (i, ambient_sp) in enumerate(self.ambient_spaces()): res.extend((self.inject_weights(i, v) for v in ambient_sp.positive_roots())) return res def negative_roots(self): '\n EXAMPLES::\n\n sage: RootSystem("A1xA2").ambient_space().negative_roots()\n [(-1, 1, 0, 0, 0), (0, 0, -1, 1, 0), (0, 0, -1, 0, 1), (0, 0, 0, -1, 1)]\n ' ret = [] for (i, ambient_sp) in enumerate(self.ambient_spaces()): ret.extend((self.inject_weights(i, v) for v in ambient_sp.negative_roots())) return ret def fundamental_weights(self): '\n EXAMPLES::\n\n sage: RootSystem("A2xB2").ambient_space().fundamental_weights()\n Finite family {1: (1, 0, 0, 0, 0), 2: (1, 1, 0, 0, 0), 3: (0, 0, 0, 1, 0), 4: (0, 0, 0, 1/2, 1/2)}\n ' fw = [] for (i, ambient_sp) in enumerate(self.ambient_spaces()): fw.extend((self.inject_weights(i, v) for v in ambient_sp.fundamental_weights())) return Family(dict(([i, fw[(i - 1)]] for i in range(1, (len(fw) + 1)))))
class CartanType(cartan_type.CartanType_decorator): '\n A class for relabelled Cartan types.\n ' @staticmethod def __classcall__(cls, type, relabelling): "\n This standardizes the input of the constructor to ensure\n unique representation.\n\n EXAMPLES::\n\n sage: ct1 = CartanType(['B',2]).relabel({1:2, 2:1}) # indirect doctest\n sage: ct2 = CartanType(['B',2]).relabel(lambda x: 3-x)\n sage: ct3 = CartanType(['B',2]).relabel({1:3, 2: 4})\n sage: ct4 = CartanType(['D',4]).relabel(lambda x: 3-x)\n sage: ct1 == ct2\n True\n sage: ct1 == ct3\n False\n sage: ct1 == ct4\n False\n " if isinstance(relabelling, (list, tuple, dict, FiniteFamily)): relabelling = {i: relabelling[i] for i in type.index_set()} else: relabelling = {i: relabelling(i) for i in type.index_set()} if isinstance(type, CartanType): relabelling = {i: relabelling[type._relabelling[i]] for i in type._type.index_set()} type = type._type if all(((relabelling[i] == i) for i in type.index_set())): return type relabelling = FiniteFamily(relabelling) return super().__classcall__(cls, type, relabelling) def __init__(self, type, relabelling): '\n INPUT:\n\n - ``type`` -- a Cartan type\n\n - ``relabelling`` -- a function (or a list, or a dictionary)\n\n Returns an isomorphic Cartan type obtained by relabelling the\n nodes of the Dynkin diagram. Namely the node with label ``i``\n is relabelled ``f(i)`` (or, by ``f[i]`` if ``f`` is a list or\n dictionary).\n\n EXAMPLES:\n\n We take the Cartan type `B_4`::\n\n sage: T = CartanType([\'B\',4])\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 1 2 3 4\n B4\n\n And relabel its nodes::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n\n sage: T = T.relabel(cycle)\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 2 3 4 1\n B4 relabelled by {1: 2, 2: 3, 3: 4, 4: 1}\n sage: T.dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(1, 4, 1), (2, 3, 1), (3, 2, 1), (3, 4, 1), (4, 1, 2), (4, 3, 1)]\n\n Multiple relabelling are recomposed into a single one::\n\n sage: T = T.relabel(cycle)\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 3 4 1 2\n B4 relabelled by {1: 3, 2: 4, 3: 1, 4: 2}\n\n sage: T = T.relabel(cycle)\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 4 1 2 3\n B4 relabelled by {1: 4, 2: 1, 3: 2, 4: 3}\n\n And trivial relabelling are honoured nicely::\n\n sage: T = T.relabel(cycle)\n sage: T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 1 2 3 4\n B4\n\n TESTS:\n\n Test that the produced Cartan type is in the appropriate\n abstract classes (see :trac:`13724`)::\n\n sage: ct = CartanType([\'B\',4]).relabel(cycle)\n sage: TestSuite(ct).run()\n sage: from sage.combinat.root_system import cartan_type\n sage: isinstance(ct, cartan_type.CartanType_finite)\n True\n sage: isinstance(ct, cartan_type.CartanType_simple)\n True\n sage: isinstance(ct, cartan_type.CartanType_affine)\n False\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n False\n\n sage: ct = CartanType([\'A\',3,1]).relabel({0:3,1:2, 2:1,3:0})\n sage: TestSuite(ct).run()\n sage: isinstance(ct, cartan_type.CartanType_simple)\n True\n sage: isinstance(ct, cartan_type.CartanType_finite)\n False\n sage: isinstance(ct, cartan_type.CartanType_affine)\n True\n sage: isinstance(ct, cartan_type.CartanType_crystallographic)\n True\n sage: isinstance(ct, cartan_type.CartanType_simply_laced)\n True\n\n Check for the original issues of :trac:`13724`::\n\n sage: A3 = CartanType("A3")\n sage: A3.cartan_matrix() # needs sage.graphs\n [ 2 -1 0]\n [-1 2 -1]\n [ 0 -1 2]\n sage: A3r = A3.relabel({1:2,2:3,3:1})\n sage: A3r.cartan_matrix() # needs sage.graphs\n [ 2 0 -1]\n [ 0 2 -1]\n [-1 -1 2]\n\n sage: ct = CartanType(["D",4,3]).classical(); ct\n [\'G\', 2]\n sage: ct.symmetrizer() # needs sage.graphs\n Finite family {1: 1, 2: 3}\n\n Check the underlying issue of :trac:`24892`, that the root system\n of a relabelled non-crystallographic Cartan type has an\n ``ambient_space()`` that does not result in an error (note that\n this should actually return a valid ambient space, which requires\n the non-crystallographic finite types to have them implemented)::\n\n sage: rI5 = CartanType([\'I\',5]).relabel({1:0,2:1})\n sage: rI5.root_system().ambient_space()\n ' cartan_type.CartanType_decorator.__init__(self, type) relabelling = Family(relabelling) self._relabelling = dict(relabelling.items()) self._relabelling_inverse = dict(relabelling.inverse_family().items()) self._index_set = tuple(sorted((relabelling[i] for i in type.index_set()))) if (type.is_finite() and (isinstance(type, cartan_type.SuperCartanType_standard) or type.is_crystallographic())): self.__class__ = CartanType_finite elif type.is_affine(): self.__class__ = CartanType_affine abstract_classes = tuple((cls for cls in self._stable_abstract_classes if isinstance(type, cls))) if abstract_classes: self._add_abstract_superclass(abstract_classes) _stable_abstract_classes = [cartan_type.CartanType_finite, cartan_type.CartanType_affine, cartan_type.CartanType_simple, cartan_type.CartanType_simply_laced, cartan_type.CartanType_crystallographic] def _repr_(self, compact=False): "\n EXAMPLES::\n\n sage: CartanType(['F', 4]).relabel(lambda x: 5-x)\n ['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n\n sage: CartanType(['F', 4]).relabel(lambda x: 5-x)._repr_(compact = True)\n 'F4 relabelled by {1: 4, 2: 3, 3: 2, 4: 1}'\n\n TESTS::\n\n sage: CoxeterType(['I',5]).relabel({1:0,2:1})\n Coxeter type of ['I', 5] relabelled by {1: 0, 2: 1}\n " from pprint import pformat if (self._type.is_affine() and (self._type.dual().type() == 'G') and (self.options('notation') == 'Kac')): if compact: return 'D4^3' return "['D', 4, 3]" relab = pformat(self._relabelling) return (self._type._repr_(compact=compact) + ' relabelled by {}'.format(relab)) def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A',4]).relabel(lambda x: (x+1)%4+1)\n sage: latex(ct)\n A_{4} \\text{ relabelled by } \\left\\{1 : 3, 2 : 4, 3 : 1, 4 : 2\\right\\}\n\n A more compact, but potentially confusing, representation can\n be obtained using the ``latex_relabel`` global option::\n\n sage: CartanType.options['latex_relabel'] = False\n sage: latex(ct)\n A_{4}\n sage: CartanType.options['latex_relabel'] = True\n\n Kac's notations are implemented::\n\n sage: CartanType.options['notation'] = 'Kac'\n sage: latex(CartanType(['D',4,3]))\n D_4^{(3)}\n sage: CartanType.options._reset()\n\n TESTS::\n\n sage: latex(CoxeterType(['I',5]).relabel({1:0,2:1}))\n I_2(5) \\text{ relabelled by } \\left\\{1 : 0, 2 : 1\\right\\}\n " from sage.misc.latex import latex if (self._type.is_affine() and (self._type.dual().type() == 'G') and (self.options('notation') == 'Kac')): return 'D_4^{(3)}' ret = self._type._latex_() if self.options('latex_relabel'): ret += (' \\text{ relabelled by } ' + latex(self._relabelling)) return ret def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['A',4]).relabel(lambda x: (x+1)%4+1)._latex_dynkin_diagram())\n \\draw (0 cm,0) -- (6 cm,0);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n <BLANKLINE>\n " if (label is None): label = (lambda i: i) return self._type._latex_dynkin_diagram((lambda i: label(self._relabelling[i])), node, node_dist) def ascii_art(self, label=None, node=None): '\n Return an ascii art representation of this Cartan type.\n\n EXAMPLES::\n\n sage: print(CartanType(["G", 2]).relabel({1:2,2:1}).ascii_art())\n 3\n O=<=O\n 2 1\n sage: print(CartanType(["B", 3, 1]).relabel([1,3,2,0]).ascii_art())\n O 1\n |\n |\n O---O=>=O\n 3 2 0\n sage: print(CartanType(["F", 4, 1]).relabel(lambda n: 4-n).ascii_art())\n O---O---O=>=O---O\n 4 3 2 1 0\n ' if (label is None): label = (lambda i: i) if (node is None): node = self._ascii_art_node return self._type.ascii_art((lambda i: label(self._relabelling[i])), node) def dynkin_diagram(self): '\n Returns the Dynkin diagram for this Cartan type.\n\n EXAMPLES::\n\n sage: CartanType(["G", 2]).relabel({1:2,2:1}).dynkin_diagram() # needs sage.graphs\n 3\n O=<=O\n 2 1\n G2 relabelled by {1: 2, 2: 1}\n\n TESTS:\n\n To be compared with the examples in :meth:`ascii_art`::\n\n sage: CartanType(["G", 2]).relabel({1:2,2:1}).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(1, 2, 3), (2, 1, 1)]\n sage: CartanType(["B", 3, 1]).relabel([1,3,2,0]).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(0, 2, 1), (1, 2, 1), (2, 0, 2), (2, 1, 1), (2, 3, 1), (3, 2, 1)]\n sage: CartanType(["F", 4, 1]).relabel(lambda n: 4-n).dynkin_diagram().edges(sort=True) # needs sage.graphs\n [(0, 1, 1), (1, 0, 1), (1, 2, 1), (2, 1, 2), (2, 3, 1), (3, 2, 1), (3, 4, 1), (4, 3, 1)]\n ' result = self._type.dynkin_diagram().copy() super(result.__class__, result).relabel(self._relabelling, inplace=True) result._cartan_type = self return result def index_set(self): "\n EXAMPLES::\n\n sage: ct = CartanType(['G', 2]).relabel({1:2,2:1})\n sage: ct.index_set()\n (1, 2)\n " return self._index_set def dual(self): '\n Implements :meth:`sage.combinat.root_system.cartan_type.CartanType_abstract.dual`,\n using that taking the dual and relabelling are commuting operations.\n\n EXAMPLES::\n\n sage: T = CartanType(["BC",3, 2])\n sage: cycle = {1:2, 2:3, 3:0, 0:1}\n sage: T.relabel(cycle).dual().dynkin_diagram() # needs sage.graphs\n O=>=O---O=>=O\n 1 2 3 0\n BC3~* relabelled by {0: 1, 1: 2, 2: 3, 3: 0}\n sage: T.dual().relabel(cycle).dynkin_diagram() # needs sage.graphs\n O=>=O---O=>=O\n 1 2 3 0\n BC3~* relabelled by {0: 1, 1: 2, 2: 3, 3: 0}\n ' return self._type.dual().relabel(self._relabelling) def _default_folded_cartan_type(self): "\n Return the default folded Cartan type.\n\n EXAMPLES::\n\n sage: fct = CartanType(['D', 4, 3])._default_folded_cartan_type(); fct\n ['G', 2, 1]^* relabelled by {0: 0, 1: 2, 2: 1} as a folding of ['D', 4, 1]\n sage: fct.folding_orbit()\n Finite family {0: (0,), 1: (2,), 2: (1, 3, 4)}\n sage: CartanType(['G',2,1]).dual()._default_folded_cartan_type().folding_orbit()\n Finite family {0: (0,), 1: (1, 3, 4), 2: (2,)}\n sage: CartanType(['C',3,1]).relabel({0:1, 1:0, 2:3, 3:2}).as_folding().scaling_factors() # needs sage.graphs\n Finite family {0: 1, 1: 2, 2: 2, 3: 1}\n " from sage.combinat.root_system.type_folded import CartanTypeFolded vct = self._type._default_folded_cartan_type() sigma = vct.folding_orbit() return CartanTypeFolded(self, vct._folding, {self._relabelling[i]: sigma[i] for i in self._type.index_set()}) def type(self): "\n Return the type of ``self`` or ``None`` if unknown.\n\n EXAMPLES::\n\n sage: ct = CartanType(['G', 2]).relabel({1:2,2:1})\n sage: ct.type()\n 'G'\n " return self._type.type() @cached_method def coxeter_diagram(self): "\n Return the Coxeter diagram for ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['H', 3]).relabel({1:3,2:2,3:1})\n sage: G = ct.coxeter_diagram(); G # needs sage.graphs\n Graph on 3 vertices\n sage: G.edges(sort=True) # needs sage.graphs\n [(1, 2, 5), (2, 3, 3)]\n " return self._type.coxeter_diagram().relabel(self._relabelling, inplace=False, immutable=True)
class AmbientSpace(ambient_space.AmbientSpace): '\n Ambient space for a relabelled finite Cartan type.\n\n It is constructed in the canonical way from the ambient space of\n the original Cartan type, by relabelling the simple roots,\n fundamental weights, etc.\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space(); L\n Ambient space of the Root system of type [\'F\', 4] relabelled by {1: 2, 2: 3, 3: 4, 4: 1}\n sage: TestSuite(L).run() # needs sage.graphs\n ' @lazy_attribute def _space(self): '\n The ambient space this is a relabelling of.\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space()\n sage: L._space\n Ambient space of the Root system of type [\'F\', 4]\n ' K = self.base_ring() return self.cartan_type()._type.root_system().ambient_space(K) def dimension(self): '\n Return the dimension of this ambient space.\n\n .. SEEALSO:: :meth:`sage.combinat.root_system.ambient_space.AmbientSpace.dimension`\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space()\n sage: L.dimension()\n 4\n ' return self.root_system.cartan_type()._type.root_system().ambient_space().dimension() @cached_method def simple_root(self, i): '\n Return the ``i``-th simple root.\n\n It is constructed by looking up the corresponding simple\n coroot in the ambient space for the original Cartan type.\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space()\n sage: K = CartanType(["F",4]).root_system().ambient_space()\n sage: K.simple_roots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 1), 4: (1/2, -1/2, -1/2, -1/2)}\n sage: K.simple_coroots()\n Finite family {1: (0, 1, -1, 0), 2: (0, 0, 1, -1), 3: (0, 0, 0, 2), 4: (1, -1, -1, -1)}\n sage: L.simple_root(1)\n (1/2, -1/2, -1/2, -1/2)\n\n sage: L.simple_roots()\n Finite family {1: (1/2, -1/2, -1/2, -1/2), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1), 4: (0, 0, 0, 1)}\n\n sage: L.simple_coroots()\n Finite family {1: (1, -1, -1, -1), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1), 4: (0, 0, 0, 2)}\n ' i = self.cartan_type()._relabelling_inverse[i] return self.sum_of_terms(self._space.simple_root(i)) @cached_method def fundamental_weight(self, i): '\n Return the ``i``-th fundamental weight.\n\n It is constructed by looking up the corresponding simple\n coroot in the ambient space for the original Cartan type.\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space()\n sage: K = CartanType(["F",4]).root_system().ambient_space()\n sage: K.fundamental_weights()\n Finite family {1: (1, 1, 0, 0), 2: (2, 1, 1, 0), 3: (3/2, 1/2, 1/2, 1/2), 4: (1, 0, 0, 0)}\n sage: L.fundamental_weight(1)\n (1, 0, 0, 0)\n sage: L.fundamental_weights()\n Finite family {1: (1, 0, 0, 0), 2: (1, 1, 0, 0), 3: (2, 1, 1, 0), 4: (3/2, 1/2, 1/2, 1/2)}\n ' i = self.cartan_type()._relabelling_inverse[i] return self.sum_of_terms(self._space.fundamental_weight(i)) @lazy_attribute def _plot_projection(self): '\n A hack so that if an ambient space uses barycentric projection, then so does its dual.\n\n EXAMPLES::\n\n sage: cycle = {1:2, 2:1}\n sage: L = CartanType(["G",2]).relabel(cycle).root_system().ambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n True\n\n sage: cycle = {1:2, 2:3, 3:4, 4:1}\n sage: L = CartanType(["F",4]).relabel(cycle).root_system().ambient_space()\n sage: L._plot_projection == L._plot_projection_barycentric\n False\n ' if (self._space._plot_projection == self._space._plot_projection_barycentric): return self._plot_projection_barycentric else: RootLatticeRealizations.ParentMethods.__dict__['_plot_projection']
class CartanType_finite(CartanType, cartan_type.CartanType_finite): AmbientSpace = AmbientSpace def affine(self): '\n Return the affine Cartan type associated with ``self``.\n\n EXAMPLES::\n\n sage: B4 = CartanType([\'B\',4])\n sage: B4.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 1 2 3 4\n B4\n sage: B4.affine().dynkin_diagram() # needs sage.graphs\n O 0\n |\n |\n O---O---O=>=O\n 1 2 3 4\n B4~\n\n If possible, this reuses the original label for the special node::\n\n sage: T = B4.relabel({1:2, 2:3, 3:4, 4:1}); T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 2 3 4 1\n B4 relabelled by {1: 2, 2: 3, 3: 4, 4: 1}\n sage: T.affine().dynkin_diagram() # needs sage.graphs\n O 0\n |\n |\n O---O---O=>=O\n 2 3 4 1\n B4~ relabelled by {0: 0, 1: 2, 2: 3, 3: 4, 4: 1}\n\n Otherwise, it chooses a label for the special_node in `0,1,...`::\n\n sage: T = B4.relabel({1:0, 2:1, 3:2, 4:3}); T.dynkin_diagram() # needs sage.graphs\n O---O---O=>=O\n 0 1 2 3\n B4 relabelled by {1: 0, 2: 1, 3: 2, 4: 3}\n sage: T.affine().dynkin_diagram() # needs sage.graphs\n O 4\n |\n |\n O---O---O=>=O\n 0 1 2 3\n B4~ relabelled by {0: 4, 1: 0, 2: 1, 3: 2, 4: 3}\n\n This failed before :trac:`13724`::\n\n sage: ct = CartanType(["G",2]).dual(); ct\n [\'G\', 2] relabelled by {1: 2, 2: 1}\n sage: ct.affine()\n [\'G\', 2, 1] relabelled by {0: 0, 1: 2, 2: 1}\n\n sage: ct = CartanType(["F",4]).dual(); ct\n [\'F\', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n sage: ct.affine()\n [\'F\', 4, 1] relabelled by {0: 0, 1: 4, 2: 3, 3: 2, 4: 1}\n\n Check that we don\'t inadvertently change the internal\n relabelling of ``ct``::\n\n sage: ct\n [\'F\', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}\n ' affine = self._type.affine() relabelling = self._relabelling.copy() for special_node in ([affine.special_node()] + list(range(affine.rank()))): if (special_node not in self._relabelling_inverse): relabelling[affine.special_node()] = special_node break return self._type.affine().relabel(relabelling)
class CartanType_affine(CartanType, cartan_type.CartanType_affine): "\n TESTS::\n\n sage: ct = CartanType(['D',4,3]); ct\n ['G', 2, 1]^* relabelled by {0: 0, 1: 2, 2: 1}\n\n sage: L = ct.root_system().ambient_space(); L\n Ambient space of the Root system of type ['G', 2, 1]^* relabelled by {0: 0, 1: 2, 2: 1}\n sage: L.classical()\n Ambient space of the Root system of type ['G', 2]\n sage: TestSuite(L).run()\n " def classical(self): "\n Return the classical Cartan type associated with ``self``.\n\n EXAMPLES::\n\n sage: A41 = CartanType(['A',4,1])\n sage: A41.dynkin_diagram() # needs sage.graphs\n 0\n O-----------+\n | |\n | |\n O---O---O---O\n 1 2 3 4\n A4~\n\n sage: T = A41.relabel({0:1, 1:2, 2:3, 3:4, 4:0})\n sage: T\n ['A', 4, 1] relabelled by {0: 1, 1: 2, 2: 3, 3: 4, 4: 0}\n sage: T.dynkin_diagram() # needs sage.graphs\n 1\n O-----------+\n | |\n | |\n O---O---O---O\n 2 3 4 0\n A4~ relabelled by {0: 1, 1: 2, 2: 3, 3: 4, 4: 0}\n\n sage: T0 = T.classical()\n sage: T0\n ['A', 4] relabelled by {1: 2, 2: 3, 3: 4, 4: 0}\n sage: T0.dynkin_diagram() # needs sage.graphs\n O---O---O---O\n 2 3 4 0\n A4 relabelled by {1: 2, 2: 3, 3: 4, 4: 0}\n\n " return self._type.classical().relabel(self._relabelling) def basic_untwisted(self): "\n Return the basic untwisted Cartan type associated with this affine\n Cartan type.\n\n Given an affine type `X_n^{(r)}`, the basic untwisted type is `X_n`.\n In other words, it is the classical Cartan type that is twisted to\n obtain ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A', 5, 2]).relabel({0:1, 1:0, 2:2, 3:3})\n sage: ct.basic_untwisted()\n ['A', 5]\n " return self._type.basic_untwisted() def special_node(self): "\n Returns a special node of the Dynkin diagram\n\n .. SEEALSO:: :meth:`~sage.combinat.root_system.CartanType_affine.special_node`\n\n It is obtained by relabelling of the special node of the non\n relabelled Dynkin diagram.\n\n EXAMPLES::\n\n sage: CartanType(['B', 3, 1]).special_node()\n 0\n sage: CartanType(['B', 3, 1]).relabel({1:2, 2:3, 3:0, 0:1}).special_node()\n 1\n " return self._relabelling[self._type.special_node()] def is_untwisted_affine(self): "\n Implement :meth:`CartanType_affine.is_untwisted_affine`\n\n A relabelled Cartan type is untwisted affine if the original is.\n\n EXAMPLES::\n\n sage: CartanType(['B', 3, 1]).relabel({1:2, 2:3, 3:0, 0:1}).is_untwisted_affine()\n True\n\n " return self._type.is_untwisted_affine()
class AmbientSpace(ambient_space.AmbientSpace): "\n The ambient space for (super) type `A(m|n)`.\n\n EXAMPLES::\n\n sage: R = RootSystem(['A', [2,1]])\n sage: AL = R.ambient_space(); AL\n Ambient space of the Root system of type ['A', [2, 1]]\n sage: AL.basis()\n Finite family {-3: (1, 0, 0, 0, 0),\n -2: (0, 1, 0, 0, 0),\n -1: (0, 0, 1, 0, 0),\n 1: (0, 0, 0, 1, 0),\n 2: (0, 0, 0, 0, 1)}\n " def __init__(self, root_system, base_ring, index_set=None): '\n Initialize ``self``.\n\n TESTS::\n\n sage: R = RootSystem([\'A\', [4,2]])\n sage: AL = R.ambient_space(); AL\n Ambient space of the Root system of type [\'A\', [4, 2]]\n sage: TestSuite(AL).run(skip="_test_norm_of_simple_roots")\n ' ct = root_system.cartan_type() if (index_set is None): index_set = tuple((list(range(((- ct.m) - 1), 0)) + list(range(1, (ct.n + 2))))) ambient_space.AmbientSpace.__init__(self, root_system, base_ring, index_set=index_set) @classmethod def smallest_base_ring(cls, cartan_type=None): "\n Return the smallest base ring the ambient space can be defined upon.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.root_system.ambient_space.AmbientSpace.smallest_base_ring`\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [3,1]]).ambient_space()\n sage: e.smallest_base_ring()\n Integer Ring\n " return ZZ def dimension(self): "\n Return the dimension of this ambient space.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [4,2]]).ambient_space()\n sage: e.dimension()\n 8\n " ct = self.root_system.cartan_type() return ((ct.m + ct.n) + 2) def simple_root(self, i): "\n Return the `i`-th simple root of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: list(e.simple_roots())\n [(1, -1, 0, 0, 0), (0, 1, -1, 0, 0),\n (0, 0, 1, -1, 0), (0, 0, 0, 1, -1)]\n " if (i < 0): return (self.monomial((i - 1)) - self.monomial(i)) if (i == 0): return (self.monomial((- 1)) - self.monomial(1)) return (self.monomial(i) - self.monomial((i + 1))) def positive_roots(self): "\n Return the positive roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.positive_roots()\n [(0, 1, -1, 0, 0),\n (1, 0, -1, 0, 0),\n (1, -1, 0, 0, 0),\n (0, 0, 0, 1, -1),\n (0, 0, 1, -1, 0),\n (0, 0, 1, 0, -1),\n (0, 1, 0, -1, 0),\n (0, 1, 0, 0, -1),\n (1, 0, 0, -1, 0),\n (1, 0, 0, 0, -1)]\n " return (self.positive_even_roots() + self.positive_odd_roots()) def positive_even_roots(self): "\n Return the positive even roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.positive_even_roots()\n [(0, 1, -1, 0, 0), (1, 0, -1, 0, 0),\n (1, -1, 0, 0, 0), (0, 0, 0, 1, -1)]\n " ct = self.root_system.cartan_type() ret = [] ret += [(self.monomial((- j)) - self.monomial((- i))) for i in range(1, (ct.m + 2)) for j in range((i + 1), (ct.m + 2))] ret += [(self.monomial(i) - self.monomial(j)) for i in range(1, (ct.n + 2)) for j in range((i + 1), (ct.n + 2))] return ret def positive_odd_roots(self): "\n Return the positive odd roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.positive_odd_roots()\n [(0, 0, 1, -1, 0),\n (0, 0, 1, 0, -1),\n (0, 1, 0, -1, 0),\n (0, 1, 0, 0, -1),\n (1, 0, 0, -1, 0),\n (1, 0, 0, 0, -1)]\n " ct = self.root_system.cartan_type() return [(self.monomial((- i)) - self.monomial(j)) for i in range(1, (ct.m + 2)) for j in range(1, (ct.n + 2))] def highest_root(self): "\n Return the highest root of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [4,2]]).ambient_lattice()\n sage: e.highest_root()\n (1, 0, 0, 0, 0, 0, 0, -1)\n " ct = self.root_system.cartan_type() return (self.monomial(((- ct.m) - 1)) - self.monomial((ct.n + 1))) def negative_roots(self): "\n Return the negative roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.negative_roots()\n [(0, -1, 1, 0, 0),\n (-1, 0, 1, 0, 0),\n (-1, 1, 0, 0, 0),\n (0, 0, 0, -1, 1),\n (0, 0, -1, 1, 0),\n (0, 0, -1, 0, 1),\n (0, -1, 0, 1, 0),\n (0, -1, 0, 0, 1),\n (-1, 0, 0, 1, 0),\n (-1, 0, 0, 0, 1)]\n " return (self.negative_even_roots() + self.negative_odd_roots()) def negative_even_roots(self): "\n Return the negative even roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.negative_even_roots()\n [(0, -1, 1, 0, 0), (-1, 0, 1, 0, 0),\n (-1, 1, 0, 0, 0), (0, 0, 0, -1, 1)]\n " ct = self.root_system.cartan_type() ret = [] ret += [(self.monomial((- i)) - self.monomial((- j))) for i in range(1, (ct.m + 2)) for j in range((i + 1), (ct.m + 2))] ret += [(self.monomial(j) - self.monomial(i)) for i in range(1, (ct.n + 2)) for j in range((i + 1), (ct.n + 2))] return ret def negative_odd_roots(self): "\n Return the negative odd roots of ``self``.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A', [2,1]]).ambient_lattice()\n sage: e.negative_odd_roots()\n [(0, 0, -1, 1, 0),\n (0, 0, -1, 0, 1),\n (0, -1, 0, 1, 0),\n (0, -1, 0, 0, 1),\n (-1, 0, 0, 1, 0),\n (-1, 0, 0, 0, 1)]\n " ct = self.root_system.cartan_type() return [(self.monomial(j) - self.monomial((- i))) for i in range(1, (ct.m + 2)) for j in range(1, (ct.n + 2))] def fundamental_weight(self, i): "\n Return the fundamental weight `\\Lambda_i` of ``self``.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A', [3,2]]).ambient_space()\n sage: L.fundamental_weight(-1)\n (1, 1, 1, 0, 0, 0, 0)\n sage: L.fundamental_weight(0)\n (1, 1, 1, 1, 0, 0, 0)\n sage: L.fundamental_weight(2)\n (1, 1, 1, 1, -1, -1, -2)\n sage: list(L.fundamental_weights())\n [(1, 0, 0, 0, 0, 0, 0),\n (1, 1, 0, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0, 0),\n (1, 1, 1, 1, 0, 0, 0),\n (1, 1, 1, 1, -1, -2, -2),\n (1, 1, 1, 1, -1, -1, -2)]\n\n ::\n\n sage: L = RootSystem(['A', [2,3]]).ambient_space()\n sage: La = L.fundamental_weights()\n sage: al = L.simple_roots()\n sage: I = L.index_set()\n sage: matrix([[al[i].scalar(La[j]) for i in I] for j in I])\n [ 1 0 0 0 0 0]\n [ 0 1 0 0 0 0]\n [ 0 0 1 0 0 0]\n [ 0 0 0 -1 0 0]\n [ 0 0 0 0 -1 0]\n [ 0 0 0 0 0 -1]\n " m = self.root_system.cartan_type().m n = self.root_system.cartan_type().n if (i <= 0): return self.sum((self.monomial(j) for j in range(((- m) - 1), i))) return ((self.sum((self.monomial(j) for j in range(((- m) - 1), 1))) - self.sum((self.monomial(j) for j in range((i + 1))))) - (2 * self.sum((self.monomial(j) for j in range((i + 1), (n + 2)))))) def simple_coroot(self, i): "\n Return the simple coroot `h_i` of ``self``.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A', [3,2]]).ambient_space()\n sage: L.simple_coroot(-2)\n (0, 1, -1, 0, 0, 0, 0)\n sage: L.simple_coroot(0)\n (0, 0, 0, 1, -1, 0, 0)\n sage: L.simple_coroot(2)\n (0, 0, 0, 0, 0, -1, 1)\n sage: list(L.simple_coroots())\n [(1, -1, 0, 0, 0, 0, 0),\n (0, 1, -1, 0, 0, 0, 0),\n (0, 0, 1, -1, 0, 0, 0),\n (0, 0, 0, 1, -1, 0, 0),\n (0, 0, 0, 0, -1, 1, 0),\n (0, 0, 0, 0, 0, -1, 1)]\n " if (i <= 0): return self.simple_root(i) return (- self.simple_root(i)) class Element(ambient_space.AmbientSpaceElement): def inner_product(self, lambdacheck): "\n The scalar product with elements of the coroot lattice\n embedded in the ambient space.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A', [2,1]]).ambient_space()\n sage: a = L.simple_roots()\n sage: matrix([[a[i].inner_product(a[j]) for j in L.index_set()] for i in L.index_set()])\n [ 2 -1 0 0]\n [-1 2 -1 0]\n [ 0 -1 0 1]\n [ 0 0 1 -2]\n " self_mc = self._monomial_coefficients lambdacheck_mc = lambdacheck._monomial_coefficients result = self.parent().base_ring().zero() for (t, c) in lambdacheck_mc.items(): if (t not in self_mc): continue if (t > 0): result -= (c * self_mc[t]) else: result += (c * self_mc[t]) return result scalar = inner_product dot_product = inner_product def associated_coroot(self): "\n Return the coroot associated to ``self``.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A', [3,2]]).ambient_space()\n sage: al = L.simple_roots()\n sage: al[-1].associated_coroot()\n (0, 0, 1, -1, 0, 0, 0)\n sage: al[0].associated_coroot()\n (0, 0, 0, 1, -1, 0, 0)\n sage: al[1].associated_coroot()\n (0, 0, 0, 0, -1, 1, 0)\n\n sage: a = al[-1] + al[0] + al[1]; a\n (0, 0, 1, 0, 0, -1, 0)\n sage: a.associated_coroot()\n (0, 0, 1, 0, -2, 1, 0)\n sage: h = L.simple_coroots()\n sage: h[-1] + h[0] + h[1]\n (0, 0, 1, 0, -2, 1, 0)\n\n sage: (al[-1] + al[0] + al[2]).associated_coroot()\n (0, 0, 1, 0, -1, -1, 1)\n " P = self.parent() al = P.simple_roots() h = P.simple_coroots() try: return h[al.inverse_family()[self]] except KeyError: pass V = P._dense_free_module() dep = V.linear_dependence(([self._vector_()] + [al[i]._vector_() for i in P.index_set()]))[0] I = P.index_set() return P.sum(((((- c) / dep[0]) * h[I[i]]) for (i, c) in dep[1:].items())) def has_descent(self, i, positive=False): "\n Test if ``self`` has a descent at position `i`, that is\n if ``self`` is on the strict negative side of the `i^{th}`\n simple reflection hyperplane.\n\n If ``positive`` is ``True``, tests if it is on the strict\n positive side instead.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A', [2,1]]).ambient_space()\n sage: al = L.simple_roots()\n sage: [al[i].has_descent(1) for i in L.index_set()]\n [False, False, True, False]\n sage: [(-al[i]).has_descent(1) for i in L.index_set()]\n [False, False, False, True]\n sage: [al[i].has_descent(1, True) for i in L.index_set()]\n [False, False, False, True]\n sage: [(-al[i]).has_descent(1, True) for i in L.index_set()]\n [False, False, True, False]\n sage: (al[-2] + al[0] + al[1]).has_descent(-1)\n True\n sage: (al[-2] + al[0] + al[1]).has_descent(1)\n False\n sage: (al[-2] + al[0] + al[1]).has_descent(1, positive=True)\n True\n sage: all(all(not la.has_descent(i) for i in L.index_set())\n ....: for la in L.fundamental_weights())\n True\n " s = self.scalar(self.parent().simple_roots()[i]) if (i > 0): s = (- s) if positive: return (s > 0) else: return (s < 0) def is_dominant_weight(self): "\n Test whether ``self`` is a dominant element of the weight lattice.\n\n EXAMPLES::\n\n sage: L = RootSystem(['A',2]).ambient_lattice()\n sage: Lambda = L.fundamental_weights()\n sage: [x.is_dominant() for x in Lambda]\n [True, True]\n sage: (3*Lambda[1]+Lambda[2]).is_dominant()\n True\n sage: (Lambda[1]-Lambda[2]).is_dominant()\n False\n sage: (-Lambda[1]+Lambda[2]).is_dominant()\n False\n\n Tests that the scalar products with the coroots are all\n nonnegative integers. For example, if `x` is the sum of a\n dominant element of the weight lattice plus some other element\n orthogonal to all coroots, then the implementation correctly\n reports `x` to be a dominant weight::\n\n sage: x = Lambda[1] + L([-1,-1,-1])\n sage: x.is_dominant_weight()\n True\n " alpha = self.parent().simple_roots() l = self.parent().cartan_type().symmetrizer() from sage.rings.semirings.non_negative_integer_semiring import NN return all((((l[i] * self.inner_product(alpha[i])) in NN) for i in self.parent().index_set()))
class CartanType(SuperCartanType_standard): '\n Cartan Type `A(m|n)`.\n\n .. SEEALSO:: :func:`~sage.combinat.root_systems.cartan_type.CartanType`\n ' def __init__(self, m, n): "\n EXAMPLES::\n\n sage: ct = CartanType(['A', [4,2]])\n sage: ct\n ['A', [4, 2]]\n sage: ct._repr_(compact=True)\n 'A4|2'\n\n sage: ct.is_irreducible()\n True\n sage: ct.is_finite()\n True\n sage: ct.is_affine()\n False\n sage: ct.affine() # Not tested -- to be implemented\n ['A', [4, 2], 1]\n sage: ct.dual()\n ['A', [4, 2]]\n\n TESTS::\n\n sage: TestSuite(ct).run()\n " self.m = m self.n = n self.letter = 'A' def _latex_(self): "\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: latex(CartanType(['A',[4,3]]))\n A(4|3)\n " return ('A(%s|%s)' % (self.m, self.n)) def index_set(self): "\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).index_set()\n (-2, -1, 0, 1, 2, 3)\n " return tuple(range((- self.m), (self.n + 1))) AmbientSpace = AmbientSpace def is_irreducible(self): "\n Return whether ``self`` is irreducible, which is ``True``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [3,4]]).is_irreducible()\n True\n " return True def is_affine(self): "\n Return whether ``self`` is affine or not.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).is_affine()\n False\n " return False def is_finite(self): "\n Return whether ``self`` is finite or not.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).is_finite()\n True\n " return True def dual(self): "\n Return dual of ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).dual()\n ['A', [2, 3]]\n " return self def type(self): "\n Return type of ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).type()\n 'A'\n " return 'A' def root_system(self): "\n Return root system of ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).root_system()\n Root system of type ['A', [2, 3]]\n " from sage.combinat.root_system.root_system import RootSystem return RootSystem(self) @cached_method def symmetrizer(self): "\n Return symmetrizing matrix for ``self``.\n\n EXAMPLES::\n\n sage: CartanType(['A', [2,3]]).symmetrizer()\n Finite family {-2: 1, -1: 1, 0: 1, 1: -1, 2: -1, 3: -1}\n " from sage.sets.family import Family def ell(i): return (ZZ.one() if (i <= 0) else (- ZZ.one())) return Family(self.index_set(), ell) def dynkin_diagram(self): "\n Return the Dynkin diagram of super type A.\n\n EXAMPLES::\n\n sage: a = CartanType(['A', [4,2]]).dynkin_diagram(); a # needs sage.graphs\n O---O---O---O---X---O---O\n -4 -3 -2 -1 0 1 2\n A4|2\n sage: a.edges(sort=True) # needs sage.graphs\n [(-4, -3, 1), (-3, -4, 1), (-3, -2, 1), (-2, -3, 1),\n (-2, -1, 1), (-1, -2, 1), (-1, 0, 1), (0, -1, 1),\n (0, 1, 1), (1, 0, -1), (1, 2, 1), (2, 1, 1)]\n\n TESTS::\n\n sage: a = DynkinDiagram(['A', [0,0]]); a # needs sage.graphs\n X\n 0\n A0|0\n sage: a.vertices(sort=False), a.edges(sort=False) # needs sage.graphs\n ([0], [])\n\n sage: a = DynkinDiagram(['A', [1,0]]); a # needs sage.graphs\n O---X\n -1 0\n A1|0\n sage: a.vertices(sort=True), a.edges(sort=True) # needs sage.graphs\n ([-1, 0], [(-1, 0, 1), (0, -1, 1)])\n\n sage: a = DynkinDiagram(['A', [0,1]]); a # needs sage.graphs\n X---O\n 0 1\n A0|1\n sage: a.vertices(sort=True), a.edges(sort=True) # needs sage.graphs\n ([0, 1], [(0, 1, 1), (1, 0, -1)])\n " from .dynkin_diagram import DynkinDiagram_class g = DynkinDiagram_class(self, odd_isotropic_roots=[0]) for i in range(self.m): g.add_edge(((- i) - 1), (- i)) for i in range(1, self.n): g.add_edge(i, (i + 1)) g.add_vertex(0) if (self.m > 0): g.add_edge((- 1), 0) if (self.n > 0): g.add_edge(1, 0, (- 1)) return g def cartan_matrix(self): "\n Return the Cartan matrix associated to ``self``.\n\n EXAMPLES::\n\n sage: ct = CartanType(['A', [2,3]])\n sage: ct.cartan_matrix() # needs sage.graphs\n [ 2 -1 0 0 0 0]\n [-1 2 -1 0 0 0]\n [ 0 -1 0 1 0 0]\n [ 0 0 -1 2 -1 0]\n [ 0 0 0 -1 2 -1]\n [ 0 0 0 0 -1 2]\n\n TESTS::\n\n sage: ct = CartanType(['A', [0,0]])\n sage: ct.cartan_matrix() # needs sage.graphs\n [0]\n\n sage: ct = CartanType(['A', [1,0]])\n sage: ct.cartan_matrix() # needs sage.graphs\n [ 2 -1]\n [-1 0]\n\n sage: ct = CartanType(['A', [0,1]])\n sage: ct.cartan_matrix() # needs sage.graphs\n [ 0 1]\n [-1 2]\n " return self.dynkin_diagram().cartan_matrix() def relabel(self, relabelling): "\n Return a relabelled copy of this Cartan type.\n\n INPUT:\n\n - ``relabelling`` -- a function (or a list or dictionary)\n\n OUTPUT:\n\n an isomorphic Cartan type obtained by relabelling the nodes of\n the Dynkin diagram. Namely, the node with label ``i`` is\n relabelled ``f(i)`` (or, by ``f[i]`` if ``f`` is a list or\n dictionary).\n\n EXAMPLES::\n\n sage: ct = CartanType(['A', [1,2]])\n sage: ct.dynkin_diagram() # needs sage.graphs\n O---X---O---O\n -1 0 1 2\n A1|2\n sage: f = {1:2, 2:1, 0:0, -1:-1}\n sage: ct.relabel(f)\n ['A', [1, 2]] relabelled by {-1: -1, 0: 0, 1: 2, 2: 1}\n sage: ct.relabel(f).dynkin_diagram() # needs sage.graphs\n O---X---O---O\n -1 0 2 1\n A1|2 relabelled by {-1: -1, 0: 0, 1: 2, 2: 1}\n " from . import type_relabel return type_relabel.CartanType(self, relabelling) def _latex_draw_node(self, x, y, label, position='below=4pt'): "\n Draw (possibly marked [crossed out]) circular node ``i`` at the\n position ``(x,y)`` with node label ``label`` .\n\n - ``position`` -- position of the label relative to the node\n - ``anchor`` -- (optional) the anchor point for the label\n\n EXAMPLES::\n\n sage: t = CartanType(['A', [3,2]])\n sage: print(t._latex_draw_node(0, 0, 0))\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm);\n \\draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm);\n sage: print(t._latex_draw_node(0, 0, 1))\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n " ret = '\\draw[fill={}] ({} cm, {} cm) circle (.25cm) node[{}]{{${}$}};\n'.format('white', x, y, position, label) if (label == 0): ret += '\\draw[-,thick] ({} cm, {} cm) -- ({} cm, {} cm);\n'.format((x + 0.17), (y + 0.17), (x - 0.17), (y - 0.17)) ret += '\\draw[-,thick] ({} cm, {} cm) -- ({} cm, {} cm);\n'.format((x + 0.17), (y - 0.17), (x - 0.17), (y + 0.17)) return ret def _latex_dynkin_diagram(self, label=None, node=None, node_dist=2): "\n Return a latex representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: print(CartanType(['A', [3,2]])._latex_dynkin_diagram())\n \\draw (0 cm, 0 cm) -- (10 cm, 0 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$-3$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$-2$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$-1$};\n \\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[-,thick] (6.17 cm, 0.17 cm) -- (5.83 cm, -0.17 cm);\n \\draw[-,thick] (6.17 cm, -0.17 cm) -- (5.83 cm, 0.17 cm);\n \\draw[fill=white] (8 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (10 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n\n sage: print(CartanType(['A', [0,2]])._latex_dynkin_diagram())\n \\draw (0 cm, 0 cm) -- (4 cm, 0 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm);\n \\draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm);\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};\n\n sage: print(CartanType(['A', [2,0]])._latex_dynkin_diagram())\n \\draw (0 cm, 0 cm) -- (4 cm, 0 cm);\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$-2$};\n \\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$-1$};\n \\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[-,thick] (4.17 cm, 0.17 cm) -- (3.83 cm, -0.17 cm);\n \\draw[-,thick] (4.17 cm, -0.17 cm) -- (3.83 cm, 0.17 cm);\n\n sage: print(CartanType(['A', [0,0]])._latex_dynkin_diagram())\n \\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};\n \\draw[-,thick] (0.17 cm, 0.17 cm) -- (-0.17 cm, -0.17 cm);\n \\draw[-,thick] (0.17 cm, -0.17 cm) -- (-0.17 cm, 0.17 cm);\n " if (label is None): label = (lambda i: i) if (node is None): node = self._latex_draw_node if ((self.n + self.m) > 1): ret = '\\draw (0 cm, 0 cm) -- ({} cm, 0 cm);\n'.format(((self.n + self.m) * node_dist)) else: ret = '' return (ret + ''.join((node(((self.m + i) * node_dist), 0, label(i)) for i in self.index_set()))) def ascii_art(self, label=None, node=None): "\n Return an ascii art representation of the Dynkin diagram.\n\n EXAMPLES::\n\n sage: t = CartanType(['A', [3,2]])\n sage: print(t.ascii_art())\n O---O---O---X---O---O\n -3 -2 -1 0 1 2\n sage: t = CartanType(['A', [3,7]])\n sage: print(t.ascii_art())\n O---O---O---X---O---O---O---O---O---O---O\n -3 -2 -1 0 1 2 3 4 5 6 7\n\n sage: t = CartanType(['A', [0,7]])\n sage: print(t.ascii_art())\n X---O---O---O---O---O---O---O\n 0 1 2 3 4 5 6 7\n sage: t = CartanType(['A', [0,0]])\n sage: print(t.ascii_art())\n X\n 0\n sage: t = CartanType(['A', [5,0]])\n sage: print(t.ascii_art())\n O---O---O---O---O---X\n -5 -4 -3 -2 -1 0\n " if (label is None): label = (lambda i: i) if (node is None): node = (lambda i: 'O') ret = '---'.join((node(label(i)) for i in range(1, (self.m + 1)))) if (self.m == 0): if (self.n == 0): ret = 'X' else: ret += 'X---' elif (self.n == 0): ret += '---X' else: ret += '---X---' ret += ('---'.join((node(label(i)) for i in range(1, (self.n + 1)))) + '\n') ret += ''.join(('{!s:4}'.format(label((- i))) for i in reversed(range(1, (self.m + 1))))) ret += '{!s:4}'.format(label(0)) ret += ''.join(('{!s:4}'.format(label(i)) for i in range(1, (self.n + 1)))) return ret
class WeightLatticeRealizations(Category_over_base_ring): '\n The category of weight lattice realizations over a given base ring\n\n A *weight lattice realization* `L` over a base ring `R` is a free\n module (or vector space if `R` is a field) endowed with an embedding\n of the root lattice of some root system. By restriction, this\n embedding defines an embedding of the root lattice of this root\n system, which makes `L` a root lattice realization.\n\n Typical weight lattice realizations over `\\ZZ` include the weight\n lattice, and ambient lattice. Typical weight lattice realizations\n over `\\QQ` include the weight space, and ambient space.\n\n To describe the embedding, a weight lattice realization must\n implement a method\n :meth:`~RootLatticeRealizations.ParentMethods.fundamental_weight`(i)\n returning for each `i` in the index set the image of the fundamental\n weight `\\Lambda_i` under the embedding.\n\n In order to be a proper root lattice realization, a weight lattice\n realization should also implement the scalar product with the coroot\n lattice; on the other hand, the embedding of the simple roots is\n given for free.\n\n .. SEEALSO::\n\n - :class:`~sage.combinat.root_system.root_system.RootSystem`\n - :class:`~sage.combinat.root_system.root_lattice_realizations.RootLatticeRealizations`\n - :class:`~sage.combinat.root_system.weight_space.WeightSpace`\n - :class:`~sage.combinat.root_system.ambient_space.AmbientSpace`\n\n EXAMPLES:\n\n Here, we consider the root system of type `A_7`, and embed the weight\n lattice element `x = \\Lambda_1 + 2 \\Lambda_3` in several root lattice\n realizations::\n\n sage: R = RootSystem(["A",7])\n sage: Lambda = R.weight_lattice().fundamental_weights()\n sage: x = Lambda[2] + 2 * Lambda[5]\n\n sage: L = R.weight_space()\n sage: L(x)\n Lambda[2] + 2*Lambda[5]\n\n sage: L = R.ambient_lattice()\n sage: L(x)\n (3, 3, 2, 2, 2, 0, 0, 0)\n\n We embed the weight space element `x = \\Lambda_1 + 1/2 \\Lambda_3` in\n the ambient space::\n\n sage: Lambda = R.weight_space().fundamental_weights()\n sage: x = Lambda[2] + 1/2 * Lambda[5]\n\n sage: L = R.ambient_space()\n sage: L(x)\n (3/2, 3/2, 1/2, 1/2, 1/2, 0, 0, 0)\n\n Of course, one can\'t embed the weight space in the ambient lattice::\n\n sage: L = R.ambient_lattice()\n sage: L(x)\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= Lambda[2] + 1/2*Lambda[5])\n an element of self (=Ambient lattice of the Root system of type [\'A\', 7])\n\n If `K_1` is a subring of `K_2`, then one could in theory have an\n embedding from the weight space over `K_1` to any weight lattice\n realization over `K_2`; this is not implemented::\n\n sage: K1 = QQ\n sage: K2 = QQ[\'q\']\n sage: L = R.ambient_space(K2)\n\n sage: Lambda = R.weight_space(K2).fundamental_weights()\n sage: L(Lambda[1])\n (1, 0, 0, 0, 0, 0, 0, 0)\n\n sage: Lambda = R.weight_space(K1).fundamental_weights()\n sage: L(Lambda[1])\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= Lambda[1]) an element\n of self (=Ambient space of the Root system of type [\'A\', 7])\n ' @cached_method def super_categories(self): '\n EXAMPLES::\n\n sage: from sage.combinat.root_system.weight_lattice_realizations import WeightLatticeRealizations\n sage: WeightLatticeRealizations(QQ).super_categories()\n [Category of root lattice realizations over Rational Field]\n ' return [RootLatticeRealizations(self.base_ring())] class ParentMethods(): @abstract_method def fundamental_weight(self, i): '\n Returns the `i^{th}` fundamental weight\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n By a slight notational abuse, for an affine type this method\n should also accept ``"delta"`` as input, and return the image\n of `\\delta` of the extended weight lattice in this\n realization.\n\n This should be overridden by any subclass, and typically\n be implemented as a cached method for efficiency.\n\n EXAMPLES::\n\n sage: L = RootSystem(["A",3]).ambient_lattice()\n sage: L.fundamental_weight(1)\n (1, 0, 0, 0)\n\n sage: L = RootSystem(["A",3,1]).weight_lattice(extended=True)\n sage: L.fundamental_weight(1)\n Lambda[1]\n sage: L.fundamental_weight("delta")\n delta\n\n TESTS::\n\n sage: super(sage.combinat.root_system.weight_space.WeightSpace, L).fundamental_weight(1)\n Traceback (most recent call last):\n ...\n NotImplementedError: <abstract method fundamental_weight at ...>\n ' def is_extended(self): '\n Return whether this is a realization of the extended weight lattice\n\n .. SEEALSO:: :class:`sage.combinat.root_system.weight_space.WeightSpace`\n\n EXAMPLES::\n\n sage: RootSystem(["A",3,1]).weight_lattice().is_extended()\n False\n sage: RootSystem(["A",3,1]).weight_lattice(extended=True).is_extended()\n True\n\n This method is irrelevant for finite root systems, since the\n weight lattice need not be extended to ensure that the root\n lattice embeds faithfully::\n\n sage: RootSystem(["A",3]).weight_lattice().is_extended()\n False\n ' return False def __init_extra__(self): '\n Registers the embedding of the weight lattice into ``self``\n\n Also registers the embedding of the weight space over the same\n base field `K` into ``self`` if `K` is not `\\ZZ`.\n\n If ``self`` is a realization of the extended weight lattice,\n then the embeddings from the extended weight space/lattices\n are registered instead.\n\n EXAMPLES:\n\n We embed the fundamental weight `\\Lambda_1` of the weight\n lattice in the ambient lattice::\n\n sage: R = RootSystem(["A",3])\n sage: Lambda = R.root_lattice().simple_roots()\n sage: L = R.ambient_space()\n sage: L(Lambda[2])\n (0, 1, -1, 0)\n\n .. note::\n\n More examples are given in :class:`WeightLatticeRealizations`;\n The embeddings are systematically tested in\n :meth:`_test_weight_lattice_realization`.\n ' from sage.rings.integer_ring import ZZ from .weight_space import WeightSpace K = self.base_ring() domains = [] if ((not isinstance(self, WeightSpace)) or (K is not ZZ)): domains.append(self.root_system.weight_lattice(extended=self.is_extended())) if (not isinstance(self, WeightSpace)): domains.append(self.root_system.weight_space(K, extended=self.is_extended())) for domain in domains: domain.module_morphism(self.fundamental_weight, codomain=self).register_as_coercion() def _test_weight_lattice_realization(self, **options): "\n Runs sanity checks on this weight lattice realization\n\n - scalar products between the fundamental weights and simple coroots\n - embeddings from the weight lattice and weight space\n - rho, highest_root, ...\n\n .. SEEALSO:: :class:`TestSuite`\n\n EXAMPLES::\n\n sage: RootSystem(['A',3]).weight_lattice()._test_weight_lattice_realization() # needs sage.graphs\n " from sage.rings.integer_ring import ZZ tester = self._tester(**options) try: Lambda = self.fundamental_weights() alphacheck = self.simple_coroots() except ImportError: return tester.assertEqual(tuple(Lambda.keys()), self.index_set()) for i in self.index_set(): tester.assertEqual(self.fundamental_weight(i), Lambda[i]) domains = [self.root_system.weight_space(base_ring, extended=extended) for base_ring in set([ZZ, self.base_ring()]) for extended in set([self.cartan_type().is_affine(), self.is_extended()])] for domain in domains: tester.assertIsNot(self._internal_coerce_map_from(domain), None) for i in self.index_set(): tester.assertEqual(self(domain.fundamental_weight(i)), Lambda[i]) if self.cartan_type().is_affine(): tester.assertEqual(self(domain.null_root()), self.null_root()) if self.is_extended(): a = self.cartan_type().col_annihilator() tester.assertEqual(self.null_root(), self.term('delta', a[0])) for i in self.index_set(): tester.assertEqual(domain.fundamental_weight(i).level(), Lambda[i].level()) for i in self.index_set(): assert Lambda[i].is_dominant() for j in self.index_set(): tester.assertEqual(Lambda[j].scalar(alphacheck[i]), (1 if (i == j) else 0)) tester.assertTrue(self.rho().is_dominant()) if (self.root_system.is_finite() and self.root_system.is_irreducible()): try: tester.assertTrue(self.highest_root().is_dominant()) except ImportError: pass @cached_method def fundamental_weights(self): "\n Returns the family `(\\Lambda_i)_{i\\in I}` of the fundamental weights.\n\n EXAMPLES::\n\n sage: e = RootSystem(['A',3]).ambient_lattice()\n sage: f = e.fundamental_weights()\n sage: [f[i] for i in [1,2,3]]\n [(1, 0, 0, 0), (1, 1, 0, 0), (1, 1, 1, 0)]\n " return Family(self.index_set(), self.fundamental_weight) @cached_method def simple_root(self, i): '\n Returns the `i`-th simple root\n\n This default implementation takes the `i`-th simple root in\n the weight lattice and embeds it in ``self``.\n\n EXAMPLES:\n\n Since all the weight lattice realizations in Sage currently\n implement a ``simple_root`` method, we have to call this one by\n hand::\n\n sage: from sage.combinat.root_system.weight_lattice_realizations import WeightLatticeRealizations\n sage: simple_root = WeightLatticeRealizations(QQ).parent_class.simple_root.f\n sage: L = RootSystem("A3").ambient_space()\n sage: simple_root(L, 1) # needs sage.graphs\n (1, -1, 0, 0)\n sage: simple_root(L, 2) # needs sage.graphs\n (0, 1, -1, 0)\n sage: simple_root(L, 3) # needs sage.graphs\n (1, 1, 2, 0)\n\n Note that this last root differs from the one implemented in\n ``L`` by a multiple of the vector ``(1,1,1,1)``::\n\n sage: L.simple_roots() # needs sage.graphs\n Finite family {1: (1, -1, 0, 0), 2: (0, 1, -1, 0), 3: (0, 0, 1, -1)}\n\n This is a harmless artefact of the `SL` versus `GL`\n interpretation of type `A`; see the thematic tutorial on Lie\n Methods and Related Combinatorics in Sage for details.\n ' if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) alphai = self.root_system.weight_lattice().simple_root(i) Lambda = self.fundamental_weights() return self.linear_combination(((Lambda[j], c) for (j, c) in alphai)) @cached_method def rho(self): "\n EXAMPLES::\n\n sage: RootSystem(['A',3]).ambient_lattice().rho()\n (3, 2, 1, 0)\n " return sum(self.fundamental_weights()) def reduced_word_of_alcove_morphism(self, f): '\n Return the reduced word of an alcove morphism.\n\n INPUT:\n\n - ``f`` -- a linear map from ``self`` to ``self`` which\n preserves alcoves\n\n Let `A` be the fundamental alcove. This returns a reduced word\n `i_1, \\ldots, i_k` such that the affine Weyl group element `w =\n s_{i_1} \\circ \\cdots \\circ s_{i_k}` maps the alcove `f(A)` back\n to `A`. In other words, the alcove walk `i_1, \\ldots, i_k` brings\n the fundamental alcove to the corresponding translated alcove.\n\n Let us throw in a bit of context to explain the main use\n case. It is customary to realize the alcove picture in\n the coroot or coweight lattice `R^\\vee`. The extended\n affine Weyl group is then the group of linear maps on\n `R^\\vee` which preserve the alcoves. By\n [Kac "Infinite-dimensional Lie algebra", Proposition 6.5]\n the affine Weyl group is the semidirect product of the\n associated finite Weyl group and the group of translations\n in the coroot lattice (the extended affine Weyl group uses\n the coweight lattice instead). In other words, an element\n of the extended affine Weyl group admits a unique\n decomposition of the form:\n\n .. MATH:: f = d w ,\n\n where `w` is in the Weyl group, and `d` is a function which\n maps the fundamental alcove to itself. As `d` permutes the\n walls of the fundamental alcove, it permutes accordingly the\n corresponding simple roots, which induces an automorphism of\n the Dynkin diagram.\n\n This method returns a reduced word for `w`, whereas the method\n :meth:`dynkin_diagram_automorphism_of_alcove_morphism` returns\n `d` as a permutation of the nodes of the Dynkin diagram.\n\n Nota bene: recall that the coroot (resp. coweight) lattice is\n implemented as the root (resp weight) lattice of the dual root\n system. Hence, this method is implemented for weight lattice\n realizations, but in practice is most of the time used on the\n dual side.\n\n EXAMPLES:\n\n We start with type `A` which is simply laced; hence we do not\n have to worry about the distinction between the weight and\n coweight lattice::\n\n sage: R = RootSystem(["A",2,1]).weight_lattice()\n sage: alpha = R.simple_roots() # needs sage.graphs\n sage: Lambda = R.fundamental_weights()\n\n We consider first translations by elements of the root lattice::\n\n sage: R.reduced_word_of_alcove_morphism(alpha[0].translation) # needs sage.graphs\n [1, 2, 1, 0]\n sage: R.reduced_word_of_alcove_morphism(alpha[1].translation) # needs sage.graphs\n [0, 2, 0, 1]\n sage: R.reduced_word_of_alcove_morphism(alpha[2].translation) # needs sage.graphs\n [0, 1, 0, 2]\n\n We continue with translations by elements of the classical\n weight lattice, embedded at level `0`:\n\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - Lambda[0]\n\n sage: R.reduced_word_of_alcove_morphism(omega1.translation) # needs sage.graphs\n [0, 2]\n sage: R.reduced_word_of_alcove_morphism(omega2.translation) # needs sage.graphs\n [0, 1]\n\n The following tests ensure that the code agrees with the tables\n in Kashiwara\'s private notes on affine quantum algebras (2008).\n\n TESTS::\n\n sage: # needs sage.graphs\n sage: R = RootSystem([\'A\',5,1]).weight_lattice()\n sage: alpha = R.simple_roots()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: R.reduced_word_of_alcove_morphism(omega1.translation)\n [0, 5, 4, 3, 2]\n sage: R.reduced_word_of_alcove_morphism(alpha[0].translation)\n [1, 2, 3, 4, 5, 4, 3, 2, 1, 0]\n\n sage: # needs sage.graphs\n sage: R = RootSystem([\'C\',3,1]).weight_lattice()\n sage: alpha = R.simple_roots()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = 2*(Lambda[1] - Lambda[0])\n sage: omega2 = 2*(Lambda[2] - Lambda[0])\n sage: omega3 = Lambda[3] - Lambda[0]\n sage: R.reduced_word_of_alcove_morphism(omega1.translation)\n [0, 1, 2, 3, 2, 1]\n sage: R.reduced_word_of_alcove_morphism(omega2.translation)\n [0, 1, 0, 2, 1, 3, 2, 1, 3, 2]\n sage: R.reduced_word_of_alcove_morphism(omega3.translation)\n [0, 1, 0, 2, 1, 0]\n\n sage: # needs sage.libs.gap\n sage: W = WeylGroup([\'C\',3,1])\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[1]*s[2]*s[3]*s[2]\n sage: W.from_reduced_word(R.reduced_word_of_alcove_morphism(omega2.translation)) == w*w # needs sage.graphs\n True\n sage: w = s[0]*s[1]*s[2]*s[0]*s[1]*s[0]\n sage: W.from_reduced_word(R.reduced_word_of_alcove_morphism(omega3.translation)) == w # needs sage.graphs\n True\n\n sage: # needs sage.graphs\n sage: R = RootSystem([\'D\',4,1]).weight_lattice()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - 2*Lambda[0]\n sage: omega3 = Lambda[3] - Lambda[0]\n sage: omega4 = Lambda[4] - Lambda[0]\n sage: R.reduced_word_of_alcove_morphism(omega1.translation)\n [0, 2, 3, 4, 2, 0]\n sage: R.reduced_word_of_alcove_morphism(omega2.translation)\n [0, 2, 1, 3, 2, 4, 2, 1, 3, 2]\n sage: R.reduced_word_of_alcove_morphism(omega3.translation)\n [0, 2, 1, 4, 2, 0]\n sage: R.reduced_word_of_alcove_morphism(omega4.translation)\n [0, 2, 1, 3, 2, 0]\n\n sage: # needs sage.libs.gap\n sage: W = WeylGroup([\'D\',4,1])\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[2]*s[3]*s[4]*s[2]\n sage: w1= s[1]*s[2]*s[3]*s[4]*s[2]\n sage: W.from_reduced_word(R.reduced_word_of_alcove_morphism(omega2.translation)) == w*w1 # needs sage.graphs\n True\n\n sage: R = RootSystem([\'D\',5,1]).weight_lattice()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - 2*Lambda[0]\n sage: R.reduced_word_of_alcove_morphism(omega1.translation) # needs sage.graphs\n [0, 2, 3, 4, 5, 3, 2, 0]\n\n sage: # needs sage.libs.gap\n sage: W = WeylGroup([\'D\',5,1])\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[2]*s[3]*s[4]*s[5]*s[3]*s[2]\n sage: w1= s[1]*s[2]*s[3]*s[4]*s[5]*s[3]*s[2]\n sage: W.from_reduced_word(R.reduced_word_of_alcove_morphism(omega2.translation)) == w*w1 # needs sage.graphs\n True\n ' return f(self.rho()).reduced_word() def dynkin_diagram_automorphism_of_alcove_morphism(self, f): '\n Return the Dynkin diagram automorphism induced by an alcove morphism\n\n INPUT:\n\n - ``f`` - a linear map from ``self`` to ``self`` which preserves alcoves\n\n This method returns the Dynkin diagram automorphism for\n the decomposition `f = d w` (see\n :meth:`reduced_word_of_alcove_morphism`), as a dictionary\n mapping elements of the index set to itself.\n\n EXAMPLES::\n\n sage: R = RootSystem(["A",2,1]).weight_lattice()\n sage: alpha = R.simple_roots() # needs sage.graphs\n sage: Lambda = R.fundamental_weights()\n\n Translations by elements of the root lattice induce a\n trivial Dynkin diagram automorphism::\n\n sage: # needs sage.graphs sage.libs.gap\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(alpha[0].translation)\n {0: 0, 1: 1, 2: 2}\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(alpha[1].translation)\n {0: 0, 1: 1, 2: 2}\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(alpha[2].translation)\n {0: 0, 1: 1, 2: 2}\n\n This is no more the case for translations by general\n elements of the (classical) weight lattice at level 0::\n\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - Lambda[0]\n\n sage: # needs sage.graphs sage.libs.gap\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(omega1.translation)\n {0: 1, 1: 2, 2: 0}\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(omega2.translation)\n {0: 2, 1: 0, 2: 1}\n\n sage: # needs sage.graphs sage.libs.gap\n sage: R = RootSystem([\'C\',2,1]).weight_lattice()\n sage: alpha = R.simple_roots()\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(alpha[1].translation)\n {0: 2, 1: 1, 2: 0}\n\n sage: # needs sage.graphs sage.libs.gap\n sage: R = RootSystem([\'D\',5,1]).weight_lattice()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - 2*Lambda[0]\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(omega1.translation)\n {0: 1, 1: 0, 2: 2, 3: 3, 4: 5, 5: 4}\n sage: R.dynkin_diagram_automorphism_of_alcove_morphism(omega2.translation)\n {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}\n\n Algorithm: computes `w` of the decomposition, and see how\n `f\\circ w^{-1}` permutes the simple roots.\n ' alpha = self.simple_roots() w = self.weyl_group().from_reduced_word(self.reduced_word_of_alcove_morphism(f)) winv = (~ w) assert all((alpha[i].level().is_zero() for i in self.index_set())) rank_simple_roots = dict(((alpha[i], i) for i in self.index_set())) permutation = dict() for i in self.index_set(): root = f(winv.action(alpha[i])) assert (root in rank_simple_roots) permutation[i] = rank_simple_roots[root] assert set(permutation.values()), set(self.index_set()) return permutation def reduced_word_of_translation(self, t): '\n Given an element of the root lattice, this returns a reduced\n word `i_1, \\ldots, i_k` such that the Weyl group element `s_{i_1}\n \\circ \\cdots \\circ s_{i_k}` implements the "translation"\n where `x` maps to `x + level(x)*t`. In other words, the alcove walk\n `i_1, \\ldots, i_k` brings the fundamental alcove to the\n corresponding translated alcove.\n\n .. NOTE::\n\n There are some technical conditions for `t` to actually\n be a translation; those are not tested (TODO: detail).\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: R = RootSystem(["A",2,1]).weight_lattice()\n sage: alpha = R.simple_roots()\n sage: R.reduced_word_of_translation(alpha[1])\n [0, 2, 0, 1]\n sage: R.reduced_word_of_translation(alpha[2])\n [0, 1, 0, 2]\n sage: R.reduced_word_of_translation(alpha[0])\n [1, 2, 1, 0]\n\n sage: R = RootSystem([\'D\',5,1]).weight_lattice()\n sage: Lambda = R.fundamental_weights()\n sage: omega1 = Lambda[1] - Lambda[0]\n sage: omega2 = Lambda[2] - 2*Lambda[0]\n sage: R.reduced_word_of_translation(omega1) # needs sage.graphs\n [0, 2, 3, 4, 5, 3, 2, 0]\n sage: R.reduced_word_of_translation(omega2) # needs sage.graphs\n [0, 2, 1, 3, 2, 4, 3, 5, 3, 2, 1, 4, 3, 2]\n\n A non simply laced case::\n\n sage: R = RootSystem(["C",2,1]).weight_lattice()\n sage: Lambda = R.fundamental_weights()\n sage: c = R.cartan_type().translation_factors(); c # needs sage.graphs\n Finite family {0: 1, 1: 2, 2: 1}\n sage: R.reduced_word_of_translation((Lambda[1]-Lambda[0]) * c[1]) # needs sage.graphs\n [0, 1, 2, 1]\n sage: R.reduced_word_of_translation((Lambda[2]-Lambda[0]) * c[2]) # needs sage.graphs\n [0, 1, 0]\n\n See also :meth:`_test_reduced_word_of_translation`.\n\n .. TODO::\n\n - Add a picture in the doc\n - Add a method which, given an element of the classical\n weight lattice, constructs the appropriate value for t\n ' return self.reduced_word_of_alcove_morphism(t.translation) def _test_reduced_word_of_translation(self, elements=None, **options): "\n Tests the method :meth:`reduced_word_of_translation`.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`.\n\n EXAMPLES::\n\n sage: R = RootSystem(['D',4,1]).weight_lattice()\n sage: R._test_reduced_word_of_translation() # needs sage.graphs\n\n See the documentation for :class:`TestSuite` for more information.\n " tester = self._tester(**options) if (not self.cartan_type().is_affine()): return try: alpha = self.simple_roots() except ImportError: return Lambda = self.fundamental_weights() rho = self.rho() G = self.dynkin_diagram() permutations = [] if (elements is None): c = self.cartan_type().c() elements = [(c[i] * Lambda[i]) for i in self.cartan_type().classical().index_set()] test_automorphism = (self.null_root().is_zero() and (set(self.index_set()) == set((i for i in range(len(self.index_set())))))) rank_simple_roots = dict(((alpha[i], i) for i in self.index_set())) try: W = self.weyl_group() except ImportError: return for t in elements: t = (t - (self.base_ring()((t.level() / Lambda[0].level())) * Lambda[0])) w = W.from_reduced_word(self.reduced_word_of_translation(t)) if self.null_root().is_zero(): tester.assertEqual(w.action(rho), (rho + (rho.level() * t))) if test_automorphism: permutation = [None for i in self.index_set()] for i in self.index_set(): root = w.action(alpha[i]) tester.assertIn(root, rank_simple_roots) permutation[i] = rank_simple_roots[root] tester.assertEqual(set(permutation), set(self.index_set())) for i in self.index_set(): for j in self.index_set(): tester.assertEqual(G[(permutation[i], permutation[j])], G[(i, j)]) permutations.append(permutation) if (test_automorphism and (elements is None)): pass def signs_of_alcovewalk(self, walk): "\n Let walk = `[i_1,\\ldots,i_n]` denote an alcove walk starting\n from the fundamental alcove `y_0`, crossing at step 1 the\n wall `i_1`, and so on.\n\n For each `k`, set `w_k = s_{i_1} \\circ s_{i_k}`, and denote\n by `y_k = w_k(y_0)` the alcove reached after `k` steps. Then,\n `y_k` is obtained recursively from `y_{k-1}` by applying the\n following reflection:\n\n .. MATH::\n\n y_k = s_{w_{k-1} \\alpha_{i_k}} y_{k-1}.\n\n The step is said positive if `w_{k-1} \\alpha_{i_k}` is a\n negative root (considering `w_{k-1}` as element of the\n classical Weyl group and `\\alpha_{i_k}` as a classical\n root) and negative otherwise. The algorithm implemented\n here use the equivalent property::\n\n .. MATH:: \\langle w_{k-1}^{-1} \\rho_0, \\alpha^\\vee_{i_k}\\rangle > 0\n\n Where `\\rho_0` is the sum of the classical fundamental\n weights embedded at level 0 in this space (see\n :meth:`rho_classical`), and `\\alpha^\\vee_{i_k}` is the\n simple coroot associated to `\\alpha_{i_k}`.\n\n This function returns a list of the form `[+1,+1,-1,...]`,\n where the `k^{th}` entry denotes whether the `k^{th}` step was\n positive or negative.\n\n See equation 3.4, of Ram: Alcove walks ..., :arxiv:`math/0601343v1`\n\n EXAMPLES::\n\n sage: L = RootSystem(['C',2,1]).weight_lattice()\n sage: L.signs_of_alcovewalk([1,2,0,1,2,1,2,0,1,2]) # needs sage.libs.gap\n [-1, -1, 1, -1, 1, 1, 1, 1, 1, 1]\n\n sage: L = RootSystem(['A',2,1]).weight_lattice()\n sage: L.signs_of_alcovewalk([0,1,2,1,2,0,1,2,0,1,2,0]) # needs sage.libs.gap\n [1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1]\n\n sage: L = RootSystem(['B',2,1]).coweight_lattice()\n sage: L.signs_of_alcovewalk([0,1,2,0,1,2]) # needs sage.libs.gap\n [1, -1, 1, -1, 1, 1]\n\n .. WARNING::\n\n This method currently does not work in the weight\n lattice for type BC dual because `\\rho_0` does not\n live in this lattice (but an integral multiple of it\n would do the job as well).\n " W = self.weyl_group() s = W.simple_reflections() alphacheck = self.alphacheck() rho0 = self.rho_classical() w = W.one() signs = [] for i in walk: if (w.action(rho0).scalar(alphacheck[i]) > 0): signs.append((- 1)) else: signs.append(1) w = (s[i] * w) return signs def rho_classical(self): '\n Return the embedding at level 0 of `\\rho` of the classical lattice.\n\n EXAMPLES::\n\n sage: RootSystem([\'C\',4,1]).weight_lattice().rho_classical() # needs sage.graphs\n -4*Lambda[0] + Lambda[1] + Lambda[2] + Lambda[3] + Lambda[4]\n sage: L = RootSystem([\'D\',4,1]).weight_lattice()\n sage: L.rho_classical().scalar(L.null_coroot()) # needs sage.graphs\n 0\n\n .. WARNING::\n\n In affine type BC dual, this does not live in the weight lattice::\n\n sage: L = CartanType(["BC",2,2]).dual().root_system().weight_space()\n sage: L.rho_classical() # needs sage.graphs\n -3/2*Lambda[0] + Lambda[1] + Lambda[2]\n sage: L = CartanType(["BC",2,2]).dual().root_system().weight_lattice()\n sage: L.rho_classical() # needs sage.graphs\n Traceback (most recent call last):\n ...\n ValueError: 5 is not divisible by 2\n ' rho = self.rho() Lambda = self.fundamental_weights() return (rho - ((Lambda[0] * rho.level()) / Lambda[0].level())) def embed_at_level(self, x, level=1): '\n Embed the classical weight `x` in the level ``level`` hyperplane\n\n This is achieved by translating the straightforward\n embedding of `x` by `c\\Lambda_0` for `c` some appropriate\n scalar.\n\n INPUT:\n\n - ``x`` -- an element of the corresponding classical weight/ambient lattice\n - ``level`` -- an integer or element of the base ring (default: 1)\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: L = RootSystem(["B",3,1]).weight_space()\n sage: L0 = L.classical()\n sage: alpha = L0.simple_roots()\n sage: omega = L0.fundamental_weights()\n sage: L.embed_at_level(omega[1], 1)\n Lambda[1]\n sage: L.embed_at_level(omega[2], 1)\n -Lambda[0] + Lambda[2]\n sage: L.embed_at_level(omega[3], 1)\n Lambda[3]\n sage: L.embed_at_level(alpha[1], 1)\n Lambda[0] + 2*Lambda[1] - Lambda[2]\n ' if (not self.classical().is_parent_of(x)): raise ValueError('x must be an element of the classical type') Lambda = self.fundamental_weights() result = self.sum_of_terms(x) result += ((Lambda[0] * (level - result.level())) / Lambda[0].level()) assert (result.level() == level) return result def weyl_dimension(self, highest_weight): "\n Return the dimension of the highest weight representation of highest weight ``highest_weight``.\n\n EXAMPLES::\n\n sage: RootSystem(['A',3]).ambient_lattice().weyl_dimension([2,1,0,0])\n 20\n sage: P = RootSystem(['C',2]).weight_lattice()\n sage: La = P.basis()\n sage: P.weyl_dimension(La[1]+La[2]) # needs sage.graphs\n 16\n\n sage: type(RootSystem(['A',3]).ambient_lattice().weyl_dimension([2,1,0,0]))\n <class 'sage.rings.integer.Integer'>\n " highest_weight = self(highest_weight) if (not highest_weight.is_dominant()): raise ValueError('the highest weight must be dominant') rho = self.rho() pr = self.coroot_lattice().positive_roots() from sage.rings.integer import Integer n = prod(((rho + highest_weight).scalar(x) for x in pr), Integer(1)) d = prod((rho.scalar(x) for x in pr), Integer(1)) return Integer((n / d)) @lazy_attribute def _symmetric_form_matrix(self): "\n Return the matrix for the symmetric form `( | )` in\n the weight lattice basis.\n\n Let `A` be a symmetrizable Cartan matrix with symmetrizer `D`,.\n This returns the matrix `M^t DA M`, where `M` is dependent upon\n the type given below.\n\n In finite types, `M` is the inverse of the Cartan matrix.\n\n In affine types, `M` takes the basis\n `(\\Lambda_0, \\Lambda_1, \\ldots, \\Lambda_r, \\delta)` to\n `(\\alpha_0, \\ldots, \\alpha_r, \\Lambda_0)` where `r` is the\n rank of ``self``.\n\n This is used in computing the symmetric form for affine\n root systems.\n\n EXAMPLES::\n\n sage: P = RootSystem(['B',2]).weight_lattice()\n sage: P._symmetric_form_matrix # needs sage.graphs\n [2 1]\n [1 1]\n\n sage: P = RootSystem(['C',2]).weight_lattice()\n sage: P._symmetric_form_matrix # needs sage.graphs\n [1 1]\n [1 2]\n\n sage: P = RootSystem(['C',2,1]).weight_lattice()\n sage: P._symmetric_form_matrix # needs sage.graphs\n [0 0 0 1]\n [0 1 1 1]\n [0 1 2 1]\n [1 1 1 0]\n\n sage: P = RootSystem(['A',4,2]).weight_lattice()\n sage: P._symmetric_form_matrix # needs sage.graphs\n [ 0 0 0 1/2]\n [ 0 2 2 1]\n [ 0 2 4 1]\n [1/2 1 1 0]\n\n " from sage.matrix.constructor import matrix ct = self.cartan_type() cm = ct.cartan_matrix() if (cm.det() != 0): diag = matrix.diagonal(cm.symmetrizer()) return (cm.inverse().transpose() * diag) if (not ct.is_affine()): raise ValueError('only implemented for affine types when the Cartan matrix is singular') r = ct.rank() a = ct.a() M = cm.stack(matrix(([1] + ([0] * (r - 1))))) M = matrix.block([[M, matrix(([[1]] + ([[0]] * r)))]]) M = M.inverse() if (a[0] != 1): from sage.rings.rational_field import QQ S = matrix(([(~ a[0])] + ([0] * (r - 1)))) A = cm.symmetrized_matrix().change_ring(QQ).stack(S) else: A = cm.symmetrized_matrix().stack(matrix(([1] + ([0] * (r - 1))))) A = matrix.block([[A, matrix(([[(~ a[0])]] + ([[0]] * r)))]]) return ((M.transpose() * A) * M) class ElementMethods(): def symmetric_form(self, la): "\n Return the symmetric form of ``self`` with ``la``.\n\n Return the pairing `( | )` on the weight lattice. See Chapter 6\n in Kac, Infinite Dimensional Lie Algebras for more details.\n\n .. WARNING::\n\n For affine root systems, if you are not working in the\n extended weight lattice/space, this may return incorrect\n results.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: P = RootSystem(['C',2]).weight_lattice()\n sage: al = P.simple_roots()\n sage: al[1].symmetric_form(al[1])\n 2\n sage: al[1].symmetric_form(al[2])\n -2\n sage: al[2].symmetric_form(al[1])\n -2\n sage: Q = RootSystem(['C',2]).root_lattice()\n sage: alQ = Q.simple_roots()\n sage: all(al[i].symmetric_form(al[j]) == alQ[i].symmetric_form(alQ[j])\n ....: for i in P.index_set() for j in P.index_set())\n True\n\n sage: # needs sage.graphs\n sage: P = RootSystem(['C',2,1]).weight_lattice(extended=True)\n sage: al = P.simple_roots()\n sage: al[1].symmetric_form(al[1])\n 2\n sage: al[1].symmetric_form(al[2])\n -2\n sage: al[1].symmetric_form(al[0])\n -2\n sage: al[0].symmetric_form(al[1])\n -2\n sage: Q = RootSystem(['C',2,1]).root_lattice()\n sage: alQ = Q.simple_roots()\n sage: all(al[i].symmetric_form(al[j]) == alQ[i].symmetric_form(alQ[j])\n ....: for i in P.index_set() for j in P.index_set())\n True\n sage: La = P.basis()\n sage: [La['delta'].symmetric_form(al) for al in P.simple_roots()]\n [0, 0, 0]\n sage: [La[0].symmetric_form(al) for al in P.simple_roots()]\n [1, 0, 0]\n\n sage: P = RootSystem(['C',2,1]).weight_lattice()\n sage: Q = RootSystem(['C',2,1]).root_lattice()\n sage: al = P.simple_roots() # needs sage.graphs\n sage: alQ = Q.simple_roots() # needs sage.graphs\n sage: all(al[i].symmetric_form(al[j]) == alQ[i].symmetric_form(alQ[j]) # needs sage.graphs\n ....: for i in P.index_set() for j in P.index_set())\n True\n\n The result of `(\\Lambda_0 | \\alpha_0)` should be `1`, however we\n get `0` because we are not working in the extended weight\n lattice::\n\n sage: La = P.basis()\n sage: [La[0].symmetric_form(al) for al in P.simple_roots()] # needs sage.graphs\n [0, 0, 0]\n\n TESTS:\n\n We check that `A_{2n}^{(2)}` has 3 different root lengths::\n\n sage: P = RootSystem(['A',4,2]).weight_lattice()\n sage: al = P.simple_roots() # needs sage.graphs\n sage: [al[i].symmetric_form(al[i]) for i in P.index_set()] # needs sage.graphs\n [2, 4, 8]\n\n Check that :trac:`31410` is fixed, and the symmetric form\n computed on the weight space is the same as the symmetric\n form computed on the root space::\n\n sage: def s1(ct):\n ....: L = RootSystem(ct).weight_space()\n ....: P = L.positive_roots()\n ....: rho = L.rho()\n ....: return [beta.symmetric_form(rho) for beta in P]\n\n sage: def s2(ct):\n ....: R = RootSystem(ct).root_space()\n ....: P = R.positive_roots()\n ....: rho = 1/2*sum(P)\n ....: return [beta.symmetric_form(rho) for beta in P]\n\n sage: all(s1(ct) == s2(ct) # needs sage.graphs\n ....: for ct in CartanType.samples(finite=True, crystallographic=True))\n True\n\n " P = self.parent() ct = P.cartan_type() sym = P._symmetric_form_matrix if ct.is_finite(): iset = P.index_set() else: iset = (P.index_set() + ('delta',)) return sum((((cl * sym[(iset.index(ml), iset.index(mr))]) * cr) for (ml, cl) in self for (mr, cr) in la)) def to_weight_space(self, base_ring=None): "\n Map ``self`` to the weight space.\n\n .. WARNING::\n\n Implemented for finite Cartan type.\n\n EXAMPLES::\n\n sage: b = CartanType(['B',2]).root_system().ambient_space().from_vector(vector([1,-2])); b\n (1, -2)\n sage: b.to_weight_space()\n 3*Lambda[1] - 4*Lambda[2]\n sage: b = CartanType(['B',2]).root_system().ambient_space().from_vector(vector([1/2,0])); b\n (1/2, 0)\n sage: b.to_weight_space()\n 1/2*Lambda[1]\n sage: b.to_weight_space(ZZ)\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n sage: b = CartanType(['G',2]).root_system().ambient_space().from_vector(vector([4,-5,1])); b\n (4, -5, 1)\n sage: b.to_weight_space()\n -6*Lambda[1] + 5*Lambda[2]\n " L = self.parent() if (base_ring is None): base_ring = L.base_ring() return L.root_system.weight_space(base_ring).sum_of_terms(([i, base_ring(self.scalar(L.simple_coroot(i)))] for i in L.cartan_type().index_set()))
class WeightSpace(CombinatorialFreeModule): '\n INPUT:\n\n - ``root_system`` -- a root system\n - ``base_ring`` -- a ring `R`\n - ``extended`` -- a boolean (default: False)\n\n The weight space (or lattice if ``base_ring`` is `\\ZZ`) of a root\n system is the formal free module `\\bigoplus_i R \\Lambda_i`\n generated by the fundamental weights `(\\Lambda_i)_{i\\in I}` of the\n root system.\n\n This class is also used for coweight spaces (or lattices).\n\n .. SEEALSO::\n\n - :meth:`RootSystem`\n - :meth:`RootSystem.weight_lattice` and :meth:`RootSystem.weight_space`\n - :meth:`~sage.combinat.root_system.weight_lattice_realizations.WeightLatticeRealizations`\n\n EXAMPLES::\n\n sage: Q = RootSystem([\'A\', 3]).weight_lattice(); Q\n Weight lattice of the Root system of type [\'A\', 3]\n sage: Q.simple_roots() # needs sage.graphs\n Finite family {1: 2*Lambda[1] - Lambda[2],\n 2: -Lambda[1] + 2*Lambda[2] - Lambda[3],\n 3: -Lambda[2] + 2*Lambda[3]}\n\n sage: Q = RootSystem([\'A\', 3, 1]).weight_lattice(); Q\n Weight lattice of the Root system of type [\'A\', 3, 1]\n sage: Q.simple_roots() # needs sage.graphs\n Finite family {0: 2*Lambda[0] - Lambda[1] - Lambda[3],\n 1: -Lambda[0] + 2*Lambda[1] - Lambda[2],\n 2: -Lambda[1] + 2*Lambda[2] - Lambda[3],\n 3: -Lambda[0] - Lambda[2] + 2*Lambda[3]}\n\n For infinite types, the Cartan matrix is singular, and therefore\n the embedding of the root lattice is not faithful::\n\n sage: sum(Q.simple_roots()) # needs sage.graphs\n 0\n\n In particular, the null root is zero::\n\n sage: Q.null_root() # needs sage.graphs\n 0\n\n This can be compensated by extending the basis of the weight space\n and slightly deforming the simple roots to make them linearly\n independent, without affecting the scalar product with the\n coroots. This feature is currently only implemented for affine\n types. In that case, if ``extended`` is set, then the basis of the\n weight space is extended by an element `\\delta`::\n\n sage: Q = RootSystem([\'A\', 3, 1]).weight_lattice(extended=True); Q\n Extended weight lattice of the Root system of type [\'A\', 3, 1]\n sage: Q.basis().keys()\n {0, 1, 2, 3, \'delta\'}\n\n And the simple root `\\alpha_0` associated to the special node is\n deformed as follows::\n\n sage: Q.simple_roots() # needs sage.graphs\n Finite family {0: 2*Lambda[0] - Lambda[1] - Lambda[3] + delta,\n 1: -Lambda[0] + 2*Lambda[1] - Lambda[2],\n 2: -Lambda[1] + 2*Lambda[2] - Lambda[3],\n 3: -Lambda[0] - Lambda[2] + 2*Lambda[3]}\n\n Now, the null root is nonzero::\n\n sage: Q.null_root() # needs sage.graphs\n delta\n\n .. WARNING::\n\n By a slight notational abuse, the extra basis element used to\n extend the fundamental weights is called ``\\delta`` in the\n current implementation. However, in the literature,\n ``\\delta`` usually denotes instead the null root. Most of the\n time, those two objects coincide, but not for type `BC` (aka.\n `A_{2n}^{(2)}`). Therefore we currently have::\n\n sage: Q = RootSystem(["A",4,2]).weight_lattice(extended=True)\n sage: Q.simple_root(0) # needs sage.graphs\n 2*Lambda[0] - Lambda[1] + delta\n sage: Q.null_root() # needs sage.graphs\n 2*delta\n\n whereas, with the standard notations from the literature, one\n would expect to get respectively `2\\Lambda_0 -\\Lambda_1 +1/2\n \\delta` and `\\delta`.\n\n Other than this notational glitch, the implementation remains\n correct for type `BC`.\n\n The notations may get improved in a subsequent version, which\n might require changing the index of the extra basis\n element. To guarantee backward compatibility in code not\n included in Sage, it is recommended to use the following idiom\n to get that index::\n\n sage: F = Q.basis_extension(); F\n Finite family {\'delta\': delta}\n sage: index = F.keys()[0]; index\n \'delta\'\n\n Then, for example, the coefficient of an element of the\n extended weight lattice on that basis element can be recovered\n with::\n\n sage: Q.null_root()[index] # needs sage.graphs\n 2\n\n TESTS::\n\n sage: for ct in (CartanType.samples(crystallographic=True) # needs sage.graphs\n ....: + [CartanType(["A",2], ["C",5,1])]):\n ....: TestSuite(ct.root_system().weight_lattice()).run()\n ....: TestSuite(ct.root_system().weight_space()).run()\n sage: for ct in CartanType.samples(affine=True): # needs sage.graphs\n ....: if ct.is_implemented():\n ....: P = ct.root_system().weight_space(extended=True)\n ....: TestSuite(P).run()\n ' @staticmethod def __classcall_private__(cls, root_system, base_ring, extended=False): "\n Guarantees Unique representation\n\n .. SEEALSO:: :class:`UniqueRepresentation`\n\n TESTS::\n\n sage: R = RootSystem(['A',4])\n sage: from sage.combinat.root_system.weight_space import WeightSpace\n sage: WeightSpace(R, QQ) is WeightSpace(R, QQ, False)\n True\n " return super().__classcall__(cls, root_system, base_ring, extended) def __init__(self, root_system, base_ring, extended): "\n TESTS::\n\n sage: R = RootSystem(['A',4])\n sage: from sage.combinat.root_system.weight_space import WeightSpace\n sage: Q = WeightSpace(R, QQ); Q\n Weight space over the Rational Field of the Root system of type ['A', 4]\n sage: TestSuite(Q).run() # needs sage.graphs\n\n sage: WeightSpace(R, QQ, extended=True)\n Traceback (most recent call last):\n ...\n ValueError: extended weight lattices are only implemented for affine root systems\n " basis_keys = root_system.index_set() self._extended = extended if extended: if (not root_system.cartan_type().is_affine()): raise ValueError('extended weight lattices are only implemented for affine root systems') basis_keys = (tuple(basis_keys) + ('delta',)) def sortkey(x): return ((1 if isinstance(x, str) else 0), x) else: def sortkey(x): return x self.root_system = root_system CombinatorialFreeModule.__init__(self, base_ring, basis_keys, prefix=('Lambdacheck' if root_system.dual_side else 'Lambda'), latex_prefix=('\\Lambda^\\vee' if root_system.dual_side else '\\Lambda'), sorting_key=sortkey, category=WeightLatticeRealizations(base_ring)) if (root_system.cartan_type().is_affine() and (not extended)): domain = root_system.weight_space(base_ring, extended=True) domain.module_morphism(self.fundamental_weight, codomain=self).register_as_coercion() def is_extended(self): '\n Return whether this is an extended weight lattice.\n\n .. SEEALSO:: :meth:`~sage.combinat.root_system.weight_lattice_realization.ParentMethods.is_extended`\n\n EXAMPLES::\n\n sage: RootSystem(["A",3,1]).weight_lattice().is_extended()\n False\n sage: RootSystem(["A",3,1]).weight_lattice(extended=True).is_extended()\n True\n ' return self._extended def _repr_(self): "\n TESTS::\n\n sage: RootSystem(['A',4]).weight_lattice() # indirect doctest\n Weight lattice of the Root system of type ['A', 4]\n sage: RootSystem(['B',4]).weight_space()\n Weight space over the Rational Field of the Root system of type ['B', 4]\n sage: RootSystem(['A',4]).coweight_lattice()\n Coweight lattice of the Root system of type ['A', 4]\n sage: RootSystem(['B',4]).coweight_space()\n Coweight space over the Rational Field of the Root system of type ['B', 4]\n\n " return self._name_string() def _name_string(self, capitalize=True, base_ring=True, type=True): '\n EXAMPLES::\n\n sage: RootSystem([\'A\',4]).weight_lattice()._name_string()\n "Weight lattice of the Root system of type [\'A\', 4]"\n ' return self._name_string_helper('weight', capitalize=capitalize, base_ring=base_ring, type=type, prefix=('extended ' if self.is_extended() else '')) @cached_method def fundamental_weight(self, i): '\n Returns the `i`-th fundamental weight\n\n INPUT:\n\n - ``i`` -- an element of the index set or ``"delta"``\n\n By a slight notational abuse, for an affine type this method\n also accepts ``"delta"`` as input, and returns the image of\n `\\delta` of the extended weight lattice in this realization.\n\n .. SEEALSO:: :meth:`~sage.combinat.root_system.weight_lattice_realization.ParentMethods.fundamental_weight`\n\n EXAMPLES::\n\n sage: Q = RootSystem(["A",3]).weight_lattice()\n sage: Q.fundamental_weight(1)\n Lambda[1]\n\n sage: Q = RootSystem(["A",3,1]).weight_lattice(extended=True)\n sage: Q.fundamental_weight(1)\n Lambda[1]\n sage: Q.fundamental_weight("delta")\n delta\n ' if (i == 'delta'): if (not self.cartan_type().is_affine()): raise ValueError('delta is only defined for affine weight spaces') if self.is_extended(): return self.monomial(i) else: return self.zero() else: if (i not in self.index_set()): raise ValueError('{} is not in the index set'.format(i)) return self.monomial(i) @cached_method def basis_extension(self): '\n Return the basis elements used to extend the fundamental weights\n\n EXAMPLES::\n\n sage: Q = RootSystem(["A",3,1]).weight_lattice()\n sage: Q.basis_extension()\n Family ()\n\n sage: Q = RootSystem(["A",3,1]).weight_lattice(extended=True)\n sage: Q.basis_extension()\n Finite family {\'delta\': delta}\n\n This method is irrelevant for finite types::\n\n sage: Q = RootSystem(["A",3]).weight_lattice()\n sage: Q.basis_extension()\n Family ()\n ' if self.is_extended(): return Family(['delta'], self.monomial) else: return Family([]) @cached_method def simple_root(self, j): '\n Returns the `j^{th}` simple root\n\n EXAMPLES::\n\n sage: L = RootSystem(["C",4]).weight_lattice()\n sage: L.simple_root(3) # needs sage.graphs\n -Lambda[2] + 2*Lambda[3] - Lambda[4]\n\n Its coefficients are given by the corresponding column of the\n Cartan matrix::\n\n sage: L.cartan_type().cartan_matrix()[:,2] # needs sage.graphs\n [ 0]\n [-1]\n [ 2]\n [-1]\n\n Here are all simple roots::\n\n sage: L.simple_roots() # needs sage.graphs\n Finite family {1: 2*Lambda[1] - Lambda[2],\n 2: -Lambda[1] + 2*Lambda[2] - Lambda[3],\n 3: -Lambda[2] + 2*Lambda[3] - Lambda[4],\n 4: -2*Lambda[3] + 2*Lambda[4]}\n\n For the extended weight lattice of an affine type, the simple\n root associated to the special node is deformed by adding\n `\\delta`, where `\\delta` is the null root::\n\n sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True)\n sage: L.simple_root(0) # needs sage.graphs\n 2*Lambda[0] - 2*Lambda[1] + delta\n\n In fact `\\delta` is really `1/a_0` times the null root (see\n the discussion in :class:`~sage.combinat.root_system.weight_space.WeightSpace`)\n but this only makes a difference in type `BC`::\n\n sage: L = RootSystem(CartanType(["BC",4,2])).weight_lattice(extended=True)\n sage: L.simple_root(0) # needs sage.graphs\n 2*Lambda[0] - Lambda[1] + delta\n sage: L.null_root() # needs sage.graphs\n 2*delta\n\n .. SEEALSO::\n\n - :meth:`~sage.combinat.root_system.type_affine.AmbientSpace.simple_root`\n - :meth:`CartanType.col_annihilator`\n ' if (j not in self.index_set()): raise ValueError('{} is not in the index set'.format(j)) K = self.base_ring() result = self.sum_of_terms(((i, K(c)) for (i, c) in self.root_system.dynkin_diagram().column(j))) if (self._extended and (j == self.cartan_type().special_node())): result = (result + self.monomial('delta')) return result def _repr_term(self, m): '\n Customized monomial printing for extended weight lattices\n\n EXAMPLES::\n\n sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True)\n sage: L.simple_root(0) # indirect doctest # needs sage.graphs\n 2*Lambda[0] - 2*Lambda[1] + delta\n\n sage: L = RootSystem(["C",4,1]).coweight_lattice(extended=True)\n sage: L.simple_root(0) # indirect doctest # needs sage.graphs\n 2*Lambdacheck[0] - Lambdacheck[1] + deltacheck\n ' if (m == 'delta'): return ('deltacheck' if self.root_system.dual_side else 'delta') return super()._repr_term(m) def _latex_term(self, m): '\n Customized monomial typesetting for extended weight lattices\n\n EXAMPLES::\n\n sage: L = RootSystem(["C",4,1]).weight_lattice(extended=True)\n sage: latex(L.simple_root(0)) # indirect doctest # needs sage.graphs\n 2 \\Lambda_{0} - 2 \\Lambda_{1} + \\delta\n\n sage: L = RootSystem(["C",4,1]).coweight_lattice(extended=True)\n sage: latex(L.simple_root(0)) # indirect doctest # needs sage.graphs\n 2 \\Lambda^\\vee_{0} - \\Lambda^\\vee_{1} + \\delta^\\vee\n ' if (m == 'delta'): return ('\\delta^\\vee' if self.root_system.dual_side else '\\delta') return super()._latex_term(m) @cached_method def _to_classical_on_basis(self, i): '\n Implement the projection onto the corresponding classical space or lattice, on the basis.\n\n INPUT:\n\n - ``i`` -- a vertex of the Dynkin diagram or "delta"\n\n EXAMPLES::\n\n sage: L = RootSystem(["A",2,1]).weight_space()\n sage: L._to_classical_on_basis("delta")\n 0\n sage: L._to_classical_on_basis(0)\n 0\n sage: L._to_classical_on_basis(1)\n Lambda[1]\n sage: L._to_classical_on_basis(2)\n Lambda[2]\n ' if ((i == 'delta') or (i == self.cartan_type().special_node())): return self.classical().zero() else: return self.classical().monomial(i) @cached_method def to_ambient_space_morphism(self): "\n The morphism from ``self`` to its associated ambient space.\n\n EXAMPLES::\n\n sage: CartanType(['A',2]).root_system().weight_lattice().to_ambient_space_morphism()\n Generic morphism:\n From: Weight lattice of the Root system of type ['A', 2]\n To: Ambient space of the Root system of type ['A', 2]\n\n .. warning::\n\n Implemented only for finite Cartan type.\n " if self.root_system.dual_side: raise TypeError('No implemented map from the coweight space to the ambient space') L = self.cartan_type().root_system().ambient_space() basis = L.fundamental_weights() def basis_value(basis, i): return basis[i] return self.module_morphism(on_basis=functools.partial(basis_value, basis), codomain=L)
class WeightSpaceElement(CombinatorialFreeModule.Element): def scalar(self, lambdacheck): '\n The canonical scalar product between the weight lattice and\n the coroot lattice.\n\n .. TODO::\n\n - merge with_apply_multi_module_morphism\n - allow for any root space / lattice\n - define properly the return type (depends on the base rings of the two spaces)\n - make this robust for extended weight lattices (`i` might be "delta")\n\n EXAMPLES::\n\n sage: L = RootSystem(["C",4,1]).weight_lattice()\n sage: Lambda = L.fundamental_weights()\n sage: alphacheck = L.simple_coroots()\n sage: Lambda[1].scalar(alphacheck[1])\n 1\n sage: Lambda[1].scalar(alphacheck[2])\n 0\n\n The fundamental weights and the simple coroots are dual bases::\n\n sage: matrix([ [ Lambda[i].scalar(alphacheck[j])\n ....: for i in L.index_set() ]\n ....: for j in L.index_set() ])\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n\n Note that the scalar product is not yet implemented between\n the weight space and the coweight space; in any cases, that\n won\'t be the job of this method::\n\n sage: R = RootSystem(["A",3])\n sage: alpha = R.weight_space().roots() # needs sage.graphs\n sage: alphacheck = R.coweight_space().roots() # needs sage.graphs\n sage: alpha[1].scalar(alphacheck[1]) # needs sage.graphs\n Traceback (most recent call last):\n ...\n ValueError: -Lambdacheck[1] + 2*Lambdacheck[2] - Lambdacheck[3]\n is not in the coroot space\n ' if ((lambdacheck not in self.parent().coroot_lattice()) and (lambdacheck not in self.parent().coroot_space())): raise ValueError('{} is not in the coroot space'.format(lambdacheck)) zero = self.parent().base_ring().zero() if (len(self) < len(lambdacheck)): return sum(((lambdacheck[i] * c) for (i, c) in self), zero) else: return sum(((self[i] * c) for (i, c) in lambdacheck), zero) def is_dominant(self): "\n Checks whether an element in the weight space lies in the positive cone spanned\n by the basis elements (fundamental weights).\n\n EXAMPLES::\n\n sage: W = RootSystem(['A',3]).weight_space()\n sage: Lambda = W.basis()\n sage: w = Lambda[1] + Lambda[3]\n sage: w.is_dominant()\n True\n sage: w = Lambda[1] - Lambda[2]\n sage: w.is_dominant()\n False\n\n In the extended affine weight lattice, 'delta' is orthogonal to\n the positive coroots, so adding or subtracting it should not\n affect dominance ::\n\n sage: P = RootSystem(['A',2,1]).weight_lattice(extended=true)\n sage: Lambda = P.fundamental_weights()\n sage: delta = P.null_root() # needs sage.graphs\n sage: w = Lambda[1] - delta # needs sage.graphs\n sage: w.is_dominant() # needs sage.graphs\n True\n\n " return all(((self.coefficient(i) >= 0) for i in self.parent().index_set())) def to_ambient(self): "\n Maps ``self`` to the ambient space.\n\n EXAMPLES::\n\n sage: mu = CartanType(['B',2]).root_system().weight_lattice().an_element(); mu\n 2*Lambda[1] + 2*Lambda[2]\n sage: mu.to_ambient()\n (3, 1)\n\n .. WARNING::\n\n Only implemented in finite Cartan type.\n Does not work for coweight lattices because there is no implemented map\n from the coweight lattice to the ambient space.\n\n " return self.parent().to_ambient_space_morphism()(self) def to_weight_space(self): "\n Map ``self`` to the weight space.\n\n Since `self.parent()` is the weight space, this map just returns ``self``.\n This overrides the generic method in `WeightSpaceRealizations`.\n\n EXAMPLES::\n\n sage: mu = CartanType(['A',2]).root_system().weight_lattice().an_element(); mu\n 2*Lambda[1] + 2*Lambda[2]\n sage: mu.to_weight_space()\n 2*Lambda[1] + 2*Lambda[2]\n " return self
class WeylCharacterRing(CombinatorialFreeModule): '\n A class for rings of Weyl characters.\n\n Let `K` be a compact Lie group, which we assume is semisimple and\n simply-connected. Its complexified Lie algebra `L` is the Lie algebra of a\n complex analytic Lie group `G`. The following three categories are\n equivalent: finite-dimensional representations of `K`; finite-dimensional\n representations of `L`; and finite-dimensional analytic representations of\n `G`. In every case, there is a parametrization of the irreducible\n representations by their highest weight vectors. For this theory of Weyl,\n see (for example):\n\n * Adams, *Lectures on Lie groups*\n * Broecker and Tom Dieck, *Representations of Compact Lie groups*\n * Bump, *Lie Groups*\n * Fulton and Harris, *Representation Theory*\n * Goodman and Wallach, *Representations and Invariants of the Classical Groups*\n * Hall, *Lie Groups, Lie Algebras and Representations*\n * Humphreys, *Introduction to Lie Algebras and their representations*\n * Procesi, *Lie Groups*\n * Samelson, *Notes on Lie Algebras*\n * Varadarajan, *Lie groups, Lie algebras, and their representations*\n * Zhelobenko, *Compact Lie Groups and their Representations*.\n\n Computations that you can do with these include computing their\n weight multiplicities, products (thus decomposing the tensor\n product of a representation into irreducibles) and branching\n rules (restriction to a smaller group).\n\n There is associated with `K`, `L` or `G` as above a lattice, the weight\n lattice, whose elements (called weights) are characters of a Cartan\n subgroup or subalgebra. There is an action of the Weyl group `W` on\n the lattice, and elements of a fixed fundamental domain for `W`, the\n positive Weyl chamber, are called dominant. There is for each\n representation a unique highest dominant weight that occurs with\n nonzero multiplicity with respect to a certain partial order, and\n it is called the highest weight vector.\n\n EXAMPLES::\n\n sage: L = RootSystem("A2").ambient_space()\n sage: [fw1,fw2] = L.fundamental_weights()\n sage: R = WeylCharacterRing([\'A\',2], prefix="R")\n sage: [R(1),R(fw1),R(fw2)]\n [R(0,0,0), R(1,0,0), R(1,1,0)]\n\n Here ``R(1)``, ``R(fw1)``, and ``R(fw2)`` are irreducible representations\n with highest weight vectors `0`, `\\Lambda_1`, and `\\Lambda_2` respectively\n (the first two fundamental weights).\n\n For type `A` (also `G_2`, `F_4`, `E_6` and `E_7`) we will take as the\n weight lattice not the weight lattice of the semisimple group, but for a\n larger one. For type `A`, this means we are concerned with the\n representation theory of `K = U(n)` or `G = GL(n, \\CC)` rather than `SU(n)`\n or `SU(n, \\CC)`. This is useful since the representation theory of `GL(n)`\n is ubiquitous, and also since we may then represent the fundamental\n weights (in :mod:`sage.combinat.root_system.root_system`) by vectors\n with integer entries. If you are only interested in `SL(3)`, say, use\n ``WeylCharacterRing([\'A\',2])`` as above but be aware that ``R([a,b,c])``\n and ``R([a+1,b+1,c+1])`` represent the same character of `SL(3)` since\n ``R([1,1,1])`` is the determinant.\n\n For more information, see the thematic tutorial *Lie Methods and\n Related Combinatorics in Sage*, available at:\n\n https://doc.sagemath.org/html/en/thematic_tutorials/lie.html\n ' @staticmethod def __classcall__(cls, ct, base_ring=ZZ, prefix=None, style='lattice', k=None, conjugate=False, cyclotomic_order=None, fusion_labels=None, inject_variables=False): '\n TESTS::\n\n sage: R = WeylCharacterRing("G2", style="coroots")\n sage: R.cartan_type() is CartanType("G2")\n True\n sage: R.base_ring() is ZZ\n True\n ' ct = CartanType(ct) if (prefix is None): if ct.is_atomic(): prefix = (ct[0] + str(ct[1])) else: prefix = repr(ct) return super().__classcall__(cls, ct, base_ring=base_ring, prefix=prefix, style=style, k=k, conjugate=conjugate, cyclotomic_order=cyclotomic_order, fusion_labels=fusion_labels, inject_variables=inject_variables) def __init__(self, ct, base_ring=ZZ, prefix=None, style='lattice', k=None, conjugate=False, cyclotomic_order=None, fusion_labels=None, inject_variables=False): '\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: TestSuite(A2).run()\n ' ct = CartanType(ct) self._cartan_type = ct self._rank = ct.rank() self._base_ring = base_ring self._space = RootSystem(self._cartan_type).ambient_space() self._origin = self._space.zero() if (prefix is None): if ct.is_atomic(): prefix = (ct[0] + str(ct[1])) else: prefix = repr(ct) self._prefix = prefix self._style = style self._fusion_labels = None self._field = None self._basecoer = None self._k = k if (k is not None): self._k = Integer(k) if ct.is_irreducible(): self._opposition = ct.opposition_automorphism() self._highest = self._space.highest_root() self._hip = self._highest.inner_product(self._highest) if (style == 'coroots'): self._word = self._space.weyl_group().long_element().reduced_word() if (k is not None): self._prefix += str(k) fw = self._space.fundamental_weights() def next_level(wt): return [(wt + la) for la in fw if (self.level((wt + la)) <= k)] B = list(RecursivelyEnumeratedSet([self._space.zero()], next_level)) B = [self._space.from_vector_notation(wt, style='coroots') for wt in B] else: B = self._space cat = AlgebrasWithBasis(base_ring).Commutative() if (k is None): cat = cat.Subobjects().Graded() else: cat = cat.FiniteDimensional() CombinatorialFreeModule.__init__(self, base_ring, B, category=cat) self.lift.register_as_coercion() self.register_conversion(self.retract) if (k is not None): if (ct[0] in ['A', 'D', 'E']): self._m_g = 1 elif (ct[0] in ['B', 'C', 'F']): self._m_g = 2 else: self._m_g = 3 if (ct[0] in ['B', 'F']): self._nf = 2 else: self._nf = 1 self._h_check = ct.dual_coxeter_number() self._l = (self._m_g * (self._k + self._h_check)) if conjugate: self._conj = (- 1) else: self._conj = 1 if (ct[0] == 'A'): self._fg = (ct[1] + 1) elif ((ct[0] == 'E') and (ct[1] == 6)): self._fg = 3 elif ((ct[0] == 'E') and (ct[1] == 7)): self._fg = 2 elif (ct[0] == 'D'): self._fg = 2 else: self._fg = 1 if (cyclotomic_order is None): self._cyclotomic_order = (self._fg * self._l) else: self._cyclotomic_order = cyclotomic_order self._fusion_labels = fusion_labels if fusion_labels: self.fusion_labels(labels=fusion_labels, inject_variables=inject_variables) @cached_method def ambient(self): '\n Return the weight ring of ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("A2").ambient()\n The Weight ring attached to The Weyl Character Ring of Type A2 with Integer Ring coefficients\n ' return WeightRing(self) def lift_on_basis(self, irr): '\n Expand the basis element indexed by the weight ``irr`` into the\n weight ring of ``self``.\n\n INPUT:\n\n - ``irr`` -- a dominant weight\n\n This is used to implement :meth:`lift`.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: v = A2._space([2,1,0]); v\n (2, 1, 0)\n sage: A2.lift_on_basis(v)\n 2*a2(1,1,1) + a2(1,2,0) + a2(1,0,2) + a2(2,1,0) + a2(2,0,1) + a2(0,1,2) + a2(0,2,1)\n\n This is consistent with the analogous calculation with symmetric\n Schur functions::\n\n sage: s = SymmetricFunctions(QQ).s()\n sage: s[2,1].expand(3)\n x0^2*x1 + x0*x1^2 + x0^2*x2 + 2*x0*x1*x2 + x1^2*x2 + x0*x2^2 + x1*x2^2\n ' return self.ambient()._from_dict(self._irr_weights(irr)) def demazure_character(self, hwv, word, debug=False): '\n Compute the Demazure character.\n\n INPUT:\n\n - ``hwv`` -- a (usually dominant) weight\n - ``word`` -- a Weyl group word\n\n Produces the Demazure character with highest weight ``hwv`` and\n ``word`` as an element of the weight ring. Only available if\n ``style="coroots"``. The Demazure operators are also available as\n methods of :class:`WeightRing` elements, and as methods of crystals.\n Given a\n :class:`~sage.combinat.crystals.tensor_product.CrystalOfTableaux`\n with given highest weight vector, the Demazure method on the\n crystal will give the equivalent of this method, except that\n the Demazure character of the crystal is given as a sum of\n monomials instead of an element of the :class:`WeightRing`.\n\n See :meth:`WeightRing.Element.demazure` and\n :meth:`sage.categories.classical_crystals.ClassicalCrystals.ParentMethods.demazure_character`\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2",style="coroots")\n sage: h = sum(A2.fundamental_weights()); h\n (2, 1, 0)\n sage: A2.demazure_character(h,word=[1,2])\n a2(0,0) + a2(-2,1) + a2(2,-1) + a2(1,1) + a2(-1,2)\n sage: A2.demazure_character((1,1),word=[1,2])\n a2(0,0) + a2(-2,1) + a2(2,-1) + a2(1,1) + a2(-1,2)\n ' if (self._style != 'coroots'): raise ValueError('demazure method unavailable: use style="coroots"') hwv = self._space.from_vector_notation(hwv, style='coroots') return self.ambient()._from_dict(self._demazure_weights(hwv, word=word, debug=debug)) @lazy_attribute def lift(self): '\n The embedding of ``self`` into its weight ring.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2.lift\n Generic morphism:\n From: The Weyl Character Ring of Type A2 with Integer Ring coefficients\n To: The Weight ring attached to The Weyl Character Ring of Type A2 with Integer Ring coefficients\n\n ::\n\n sage: x = -A2(2,1,1) - A2(2,2,0) + A2(3,1,0)\n sage: A2.lift(x)\n a2(1,3,0) + a2(1,0,3) + a2(3,1,0) + a2(3,0,1) + a2(0,1,3) + a2(0,3,1)\n\n As a shortcut, you may also do::\n\n sage: x.lift()\n a2(1,3,0) + a2(1,0,3) + a2(3,1,0) + a2(3,0,1) + a2(0,1,3) + a2(0,3,1)\n\n Or even::\n\n sage: a2 = WeightRing(A2)\n sage: a2(x)\n a2(1,3,0) + a2(1,0,3) + a2(3,1,0) + a2(3,0,1) + a2(0,1,3) + a2(0,3,1)\n ' return self.module_morphism(self.lift_on_basis, codomain=self.ambient(), category=AlgebrasWithBasis(self.base_ring())) def _retract(self, chi): '\n Construct a Weyl character from an invariant element of the weight ring\n\n INPUT:\n\n - ``chi`` -- a linear combination of weights which\n shall be invariant under the action of the Weyl group\n\n OUTPUT: the corresponding Weyl character\n\n Please use instead the morphism :meth:`retract` which is\n implemented using this method.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n\n ::\n\n sage: v = A2._space([3,1,0]); v\n (3, 1, 0)\n sage: chi = a2.sum_of_monomials(v.orbit()); chi\n a2(1,3,0) + a2(1,0,3) + a2(3,1,0) + a2(3,0,1) + a2(0,1,3) + a2(0,3,1)\n sage: A2._retract(chi)\n -A2(2,1,1) - A2(2,2,0) + A2(3,1,0)\n ' return self.char_from_weights(dict(chi)) @lazy_attribute def retract(self): '\n The partial inverse map from the weight ring into ``self``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: A2.retract\n Generic morphism:\n From: The Weight ring attached to The Weyl Character Ring of Type A2 with Integer Ring coefficients\n To: The Weyl Character Ring of Type A2 with Integer Ring coefficients\n\n ::\n\n sage: v = A2._space([3,1,0]); v\n (3, 1, 0)\n sage: chi = a2.sum_of_monomials(v.orbit()); chi\n a2(1,3,0) + a2(1,0,3) + a2(3,1,0) + a2(3,0,1) + a2(0,1,3) + a2(0,3,1)\n sage: A2.retract(chi)\n -A2(2,1,1) - A2(2,2,0) + A2(3,1,0)\n\n The input should be invariant::\n\n sage: A2.retract(a2.monomial(v))\n Traceback (most recent call last):\n ...\n ValueError: multiplicity dictionary may not be Weyl group invariant\n\n As a shortcut, you may use conversion::\n\n sage: A2(chi)\n -A2(2,1,1) - A2(2,2,0) + A2(3,1,0)\n sage: A2(a2.monomial(v))\n Traceback (most recent call last):\n ...\n ValueError: multiplicity dictionary may not be Weyl group invariant\n ' from sage.categories.homset import Hom from sage.categories.morphism import SetMorphism category = Algebras(self.base_ring()) return SetMorphism(Hom(self.ambient(), self, category), self._retract) def _repr_(self): '\n EXAMPLES::\n\n sage: WeylCharacterRing("A3")\n The Weyl Character Ring of Type A3 with Integer Ring coefficients\n ' if (self._k is None): return 'The Weyl Character Ring of Type {} with {} coefficients'.format(self._cartan_type._repr_(compact=True), self._base_ring) else: return 'The Fusion Ring of Type {} and level {} with {} coefficients'.format(self._cartan_type._repr_(compact=True), self._k, self._base_ring) def __call__(self, *args): '\n Construct an element of ``self``.\n\n The input can either be an object that can be coerced or\n converted into ``self`` (an element of ``self``, of the base\n ring, of the weight ring), or a dominant weight. In the later\n case, the basis element indexed by that weight is returned.\n\n To specify the weight, you may give it explicitly. Alternatively,\n you may give a tuple of integers. Normally these are the\n components of the vector in the standard realization of\n the weight lattice as a vector space. Alternatively, if\n the ring is constructed with ``style = "coroots"``, you may\n specify the weight by giving a set of integers, one for each\n fundamental weight; the weight is then the linear combination\n of the fundamental weights with these coefficients.\n\n As a syntactical shorthand, for tuples of length at least two,\n the parenthesis may be omitted.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: [A2(x) for x in [-2,-1,0,1,2]]\n [-2*A2(0,0,0), -A2(0,0,0), 0, A2(0,0,0), 2*A2(0,0,0)]\n sage: [A2(2,1,0), A2([2,1,0]), A2(2,1,0)== A2([2,1,0])]\n [A2(2,1,0), A2(2,1,0), True]\n sage: A2([2,1,0]) == A2(2,1,0)\n True\n sage: l = -2*A2(0,0,0) - A2(1,0,0) + A2(2,0,0) + 2*A2(3,0,0)\n sage: [l in A2, A2(l) == l]\n [True, True]\n sage: P.<q> = QQ[]\n sage: A2 = WeylCharacterRing([\'A\',2], base_ring = P)\n sage: [A2(x) for x in [-2,-1,0,1,2,-2*q,-q,q,2*q,(1-q)]]\n [-2*A2(0,0,0), -A2(0,0,0), 0, A2(0,0,0), 2*A2(0,0,0), -2*q*A2(0,0,0), -q*A2(0,0,0),\n q*A2(0,0,0), 2*q*A2(0,0,0), (-q+1)*A2(0,0,0)]\n sage: R.<q> = ZZ[]\n sage: A2 = WeylCharacterRing([\'A\',2], base_ring = R, style="coroots")\n sage: q*A2(1)\n q*A2(0,0)\n sage: [A2(x) for x in [-2,-1,0,1,2,-2*q,-q,q,2*q,(1-q)]]\n [-2*A2(0,0), -A2(0,0), 0, A2(0,0), 2*A2(0,0), -2*q*A2(0,0), -q*A2(0,0), q*A2(0,0), 2*q*A2(0,0), (-q+1)*A2(0,0)]\n\n ' if (len(args) > 1): args = (args,) return super().__call__(*args) def _element_constructor_(self, weight): '\n Construct a monomial from a dominant weight.\n\n INPUT:\n\n - ``weight`` -- an element of the weight space, or a tuple\n\n This method is responsible for constructing an appropriate\n dominant weight from ``weight``, and then return the monomial\n indexed by that weight. See :meth:`__call__` and\n :meth:`sage.combinat.root_system.ambient_space.AmbientSpace.from_vector`.\n\n TESTS::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2._element_constructor_([2,1,0])\n A2(2,1,0)\n ' weight = self._space.from_vector_notation(weight, style=self._style) if (not weight.is_dominant_weight()): raise ValueError('{} is not a dominant element of the weight lattice'.format(weight)) if (self._k is not None): if (self.level(weight) > self._k): raise ValueError('{} has level greater than {}'.format(weight, self._k)) return self.monomial(weight) def product_on_basis(self, a, b): "\n Compute the tensor product of two irreducible representations ``a``\n and ``b``.\n\n EXAMPLES::\n\n sage: D4 = WeylCharacterRing(['D',4])\n sage: spin_plus = D4(1/2,1/2,1/2,1/2)\n sage: spin_minus = D4(1/2,1/2,1/2,-1/2)\n sage: spin_plus * spin_minus # indirect doctest\n D4(1,0,0,0) + D4(1,1,1,0)\n sage: spin_minus * spin_plus\n D4(1,0,0,0) + D4(1,1,1,0)\n\n Uses the Brauer-Klimyk method.\n " if (sum(a.coefficients()) > sum(b.coefficients())): (a, b) = (b, a) return self._product_helper(self._irr_weights(a), b) def _product_helper(self, d1, b): '\n Helper function for :meth:`product_on_basis`.\n\n INPUT:\n\n - ``d1`` -- a dictionary of weight multiplicities\n - ``b`` -- a dominant weight\n\n If ``d1`` is the dictionary of weight multiplicities of a character,\n returns the product of that character by the irreducible character\n with highest weight ``b``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: r = A2(1,0,0)\n sage: [A2._product_helper(r.weight_multiplicities(),x) for x in A2.space().fundamental_weights()]\n [A2(1,1,0) + A2(2,0,0), A2(1,1,1) + A2(2,1,0)]\n ' d = {} for k in d1: [epsilon, g] = self.dot_reduce((b + k)) if (epsilon == 1): d[g] = (d.get(g, 0) + d1[k]) elif (epsilon == (- 1)): d[g] = (d.get(g, 0) - d1[k]) return self._from_dict(d, coerce=True) def dot_reduce(self, a): '\n Auxiliary function for :meth:`product_on_basis`.\n\n Return a pair `[\\epsilon, b]` where `b` is a dominant weight and\n `\\epsilon` is 0, 1 or -1. To describe `b`, let `w` be an element of\n the Weyl group such that `w(a + \\rho)` is dominant. If\n `w(a + \\rho) - \\rho` is dominant, then `\\epsilon` is the sign of\n `w` and `b` is `w(a + \\rho) - \\rho`. Otherwise, `\\epsilon` is zero.\n\n INPUT:\n\n - ``a`` -- a weight\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: weights = sorted(A2(2,1,0).weight_multiplicities().keys(), key=str); weights\n [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0)]\n sage: [A2.dot_reduce(x) for x in weights]\n [[0, (0, 0, 0)], [-1, (1, 1, 1)], [-1, (1, 1, 1)], [1, (1, 1, 1)], [0, (0, 0, 0)], [0, (0, 0, 0)], [1, (2, 1, 0)]]\n ' alphacheck = self._space.simple_coroots() alpha = self._space.simple_roots() [epsilon, ret] = [1, a] done = False while (not done): done = True for i in self._space.index_set(): c = ret.inner_product(alphacheck[i]) if (c == (- 1)): return [0, self._space.zero()] elif (c < (- 1)): epsilon = (- epsilon) ret -= ((1 + c) * alpha[i]) done = False break if (self._k is not None): l = self.level(ret) k = self._k if (l > k): if (l == (k + 1)): return [0, self._space.zero()] else: epsilon = (- epsilon) ret = self.affine_reflect(ret, (k + 1)) done = False return [epsilon, ret] def affine_reflect(self, wt, k=0): '\n Return the reflection of wt in the hyperplane `\\theta`.\n\n Optionally, this also shifts by a multiple `k` of `\\theta`.\n\n INPUT:\n\n - ``wt`` -- a weight\n - ``k`` -- (optional) a positive integer\n\n EXAMPLES::\n\n sage: B22 = FusionRing("B2",2)\n sage: fw = B22.fundamental_weights(); fw\n Finite family {1: (1, 0), 2: (1/2, 1/2)}\n sage: [B22.affine_reflect(x,2) for x in fw]\n [(2, 1), (3/2, 3/2)]\n ' coef = ZZ(((2 * wt.inner_product(self._highest)) / self._hip)) return (wt + ((k - coef) * self._highest)) def some_elements(self): '\n Return some elements of ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("A3").some_elements()\n [A3(1,0,0,0), A3(1,1,0,0), A3(1,1,1,0)]\n ' return [self.monomial(x) for x in self.fundamental_weights()] def one_basis(self): '\n Return the index of 1 in ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("A3").one_basis()\n (0, 0, 0, 0)\n sage: WeylCharacterRing("A3").one()\n A3(0,0,0,0)\n ' return self._space.zero() @cached_method def _irr_weights(self, hwv): '\n Compute the weights of an irreducible as a dictionary.\n\n Given a dominant weight ``hwv``, this produces a dictionary of\n weight multiplicities for the irreducible representation\n with highest weight vector ``hwv``. This method is cached\n for efficiency.\n\n INPUT:\n\n - ``hwv`` -- a dominant weight\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: v = A2.fundamental_weights()[1]; v\n (1, 0, 0)\n sage: A2._irr_weights(v)\n {(1, 0, 0): 1, (0, 1, 0): 1, (0, 0, 1): 1}\n ' if (self._style == 'coroots'): return self._demazure_weights(hwv) else: return irreducible_character_freudenthal(hwv) def _demazure_weights(self, hwv, word='long', debug=False): '\n Computes the weights of a Demazure character.\n\n This method duplicates the functionality of :meth:`_irr_weights`, under\n the assumption that ``style = "coroots"``, but allows an optional\n parameter ``word``. (This is not allowed in :meth:`_irr_weights` since\n it would interfere with the ``@cached_method``.) Produces the\n dictionary of weights for the irreducible character with highest\n weight ``hwv`` when ``word`` is omitted, or for the Demazure character\n if ``word`` is included.\n\n INPUT:\n\n - ``hwv`` -- a dominant weight\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2", style="coroots")\n sage: [B2._demazure_weights(v, word=[1,2]) for v in B2.fundamental_weights()]\n [{(1, 0): 1, (0, 1): 1}, {(-1/2, 1/2): 1, (1/2, -1/2): 1, (1/2, 1/2): 1}]\n ' alphacheck = self._space.simple_coroots() dd = {} h = tuple((int(hwv.inner_product(alphacheck[j])) for j in self._space.index_set())) dd[h] = 1 return self._demazure_helper(dd, word=word, debug=debug) def _demazure_helper(self, dd, word='long', debug=False): '\n Assumes ``style = "coroots"``. If the optional parameter ``word`` is\n specified, produces a Demazure character (defaults to the long Weyl\n group element.\n\n INPUT:\n\n - ``dd`` -- a dictionary of weights\n\n - ``word`` -- (optional) a Weyl group reduced word\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2",style="coroots")\n sage: dd = {}; dd[(1,1)]=int(1)\n sage: A2._demazure_helper(dd,word=[1,2])\n {(0, 0, 0): 1, (-1, 1, 0): 1, (1, -1, 0): 1, (1, 0, -1): 1, (0, 1, -1): 1}\n ' if (self._style != 'coroots'): raise ValueError('_demazure_helper method unavailable: use style="coroots"') index_set = self._space.index_set() alphacheck = self._space.simple_coroots() alpha = self._space.simple_roots() r = self.rank() cm = {} supp = [] for i in index_set: temp = [] cm[i] = ([0] * r) for (ind, j) in enumerate(index_set): cm[i][ind] = int(alpha[i].inner_product(alphacheck[j])) if cm[i][ind]: temp.append(ind) supp.append(temp) if debug: print(('cm[%s]=%s' % (i, cm[i]))) accum = dd if (word == 'long'): word = self._word for i in reversed(word): if debug: print(('i=%s' % i)) next = {} for v in accum: coroot = v[(i - 1)] if debug: print((' v=%s, coroot=%s' % (v, coroot))) if (coroot >= 0): mu = v for j in range((coroot + 1)): next[mu] = (next.get(mu, 0) + accum[v]) if debug: print((' mu=%s, next[mu]=%s' % (mu, next[mu]))) mu = list(mu) for k in supp[(i - 1)]: mu[k] -= cm[i][k] mu = tuple(mu) else: mu = v for j in range(((- 1) - coroot)): mu = list(mu) for k in supp[(i - 1)]: mu[k] += cm[i][k] mu = tuple(mu) next[mu] = (next.get(mu, 0) - accum[v]) if debug: print((' mu=%s, next[mu]=%s' % (mu, next[mu]))) accum = {} for v in next: accum[v] = next[v] ret = {} for v in accum: if accum[v]: ret[self._space.from_vector_notation(v, style='coroots')] = accum[v] return ret @cached_method def _weight_multiplicities(self, x): '\n Produce weight multiplicities for the (possibly reducible)\n WeylCharacter ``x``.\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2",style="coroots")\n sage: chi = 2*B2(1,0)\n sage: B2._weight_multiplicities(chi)\n {(0, 0): 2, (-1, 0): 2, (1, 0): 2, (0, -1): 2, (0, 1): 2}\n ' d = {} m = x._monomial_coefficients for k in m: c = m[k] d1 = self._irr_weights(k) for l in d1: if (l in d): d[l] += (c * d1[l]) else: d[l] = (c * d1[l]) for k in list(d): if (d[k] == 0): del d[k] else: d[k] = self._base_ring(d[k]) return d def base_ring(self): "\n Return the base ring of ``self``.\n\n EXAMPLES::\n\n sage: R = WeylCharacterRing(['A',3], base_ring = CC); R.base_ring()\n Complex Field with 53 bits of precision\n " return self._base_ring def irr_repr(self, hwv): '\n Return a string representing the irreducible character with highest\n weight vector ``hwv``.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing("B3")\n sage: [B3.irr_repr(v) for v in B3.fundamental_weights()]\n [\'B3(1,0,0)\', \'B3(1,1,0)\', \'B3(1/2,1/2,1/2)\']\n sage: B3 = WeylCharacterRing("B3", style="coroots")\n sage: [B3.irr_repr(v) for v in B3.fundamental_weights()]\n [\'B3(1,0,0)\', \'B3(0,1,0)\', \'B3(0,0,1)\']\n ' return (self._prefix + self._wt_repr(hwv)) def level(self, wt): '\n Return the level of the weight, defined to be the value of\n the weight on the coroot associated with the highest root.\n\n EXAMPLES::\n\n sage: R = FusionRing("F4",2); [R.level(x) for x in R.fundamental_weights()]\n [2, 3, 2, 1]\n sage: [CartanType("F4~").dual().a()[x] for x in [1..4]]\n [2, 3, 2, 1]\n ' return ZZ(((2 * wt.inner_product(self._highest)) / self._hip)) def _dual_helper(self, wt): '\n If `w_0` is the long Weyl group element and `wt` is an\n element of the weight lattice, this returns `-w_0(wt)`.\n\n EXAMPLES::\n\n sage: A3=WeylCharacterRing("A3")\n sage: [A3._dual_helper(x) for x in A3.fundamental_weights()]\n [(0, 0, 0, -1), (0, 0, -1, -1), (0, -1, -1, -1)]\n ' if (self.cartan_type()[0] == 'A'): return self.space()([(- x) for x in reversed(wt.to_vector().list())]) ret = 0 alphacheck = self._space.simple_coroots() fw = self._space.fundamental_weights() for i in self._space.index_set(): ret += (wt.inner_product(alphacheck[i]) * fw[self._opposition[i]]) return ret def _wt_repr(self, wt): '\n Produce a representation of a vector in either coweight or\n lattice notation (following the appendices in Bourbaki, Lie Groups and\n Lie Algebras, Chapters 4,5,6), depending on whether the parent\n :class:`WeylCharacterRing` is created with ``style="coweights"``\n or not.\n\n EXAMPLES::\n\n sage: [fw1,fw2]=RootSystem("G2").ambient_space().fundamental_weights(); fw1,fw2\n ((1, 0, -1), (2, -1, -1))\n sage: [WeylCharacterRing("G2")._wt_repr(v) for v in [fw1,fw2]]\n [\'(1,0,-1)\', \'(2,-1,-1)\']\n sage: [WeylCharacterRing("G2",style="coroots")._wt_repr(v) for v in [fw1,fw2]]\n [\'(1,0)\', \'(0,1)\']\n ' if (self._style == 'lattice'): vec = wt.to_vector() elif (self._style == 'coroots'): vec = [wt.inner_product(x) for x in self.simple_coroots()] else: raise ValueError('unknown style') hstring = str(vec[0]) for i in range(1, len(vec)): hstring = ((hstring + ',') + str(vec[i])) return (('(' + hstring) + ')') def _repr_term(self, t): '\n Representation of the monomial corresponding to a weight ``t``.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing("G2") # indirect doctest\n sage: [G2._repr_term(x) for x in G2.fundamental_weights()]\n [\'G2(1,0,-1)\', \'G2(2,-1,-1)\']\n ' if (self._fusion_labels is not None): t = tuple([t.inner_product(x) for x in self.simple_coroots()]) return self._fusion_labels[t] else: return self.irr_repr(t) def cartan_type(self): '\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("A2").cartan_type()\n [\'A\', 2]\n ' return self._cartan_type def fundamental_weights(self): '\n Return the fundamental weights.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").fundamental_weights()\n Finite family {1: (1, 0, -1), 2: (2, -1, -1)}\n ' return self._space.fundamental_weights() def simple_roots(self): '\n Return the simple roots.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").simple_roots()\n Finite family {1: (0, 1, -1), 2: (1, -2, 1)}\n ' return self._space.simple_roots() def simple_coroots(self): '\n Return the simple coroots.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").simple_coroots()\n Finite family {1: (0, 1, -1), 2: (1/3, -2/3, 1/3)}\n ' return self._space.simple_coroots() def highest_root(self): '\n Return the highest root.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").highest_root()\n (2, -1, -1)\n ' return self._space.highest_root() def positive_roots(self): '\n Return the positive roots.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").positive_roots()\n [(0, 1, -1), (1, -2, 1), (1, -1, 0), (1, 0, -1), (1, 1, -2), (2, -1, -1)]\n ' return self._space.positive_roots() def dynkin_diagram(self): '\n Return the Dynkin diagram of ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("E7").dynkin_diagram()\n O 2\n |\n |\n O---O---O---O---O---O\n 1 3 4 5 6 7\n E7\n ' return self.space().dynkin_diagram() def extended_dynkin_diagram(self): '\n Return the extended Dynkin diagram, which is the Dynkin diagram\n of the corresponding untwisted affine type.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("E7").extended_dynkin_diagram()\n O 2\n |\n |\n O---O---O---O---O---O---O\n 0 1 3 4 5 6 7\n E7~\n ' return self.cartan_type().affine().dynkin_diagram() def rank(self): '\n Return the rank.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("G2").rank()\n 2\n ' return self._rank def space(self): "\n Return the weight space associated to ``self``.\n\n EXAMPLES::\n\n sage: WeylCharacterRing(['E',8]).space()\n Ambient space of the Root system of type ['E', 8]\n " return self._space def char_from_weights(self, mdict): '\n Construct a Weyl character from an invariant linear combination\n of weights.\n\n INPUT:\n\n - ``mdict`` -- a dictionary mapping weights to coefficients,\n and representing a linear combination of weights which\n shall be invariant under the action of the Weyl group\n\n OUTPUT: the corresponding Weyl character\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: v = A2._space([3,1,0]); v\n (3, 1, 0)\n sage: d = dict([(x,1) for x in v.orbit()]); d\n {(1, 3, 0): 1,\n (1, 0, 3): 1,\n (3, 1, 0): 1,\n (3, 0, 1): 1,\n (0, 1, 3): 1,\n (0, 3, 1): 1}\n sage: A2.char_from_weights(d)\n -A2(2,1,1) - A2(2,2,0) + A2(3,1,0)\n ' return self._from_dict(self._char_from_weights(mdict), coerce=True) def _char_from_weights(self, mdict): '\n Helper method for :meth:`char_from_weights`.\n\n INPUT:\n\n - ``mdict`` -- a dictionary of weight multiplicities\n\n The output of this method is a dictionary whose keys are dominant\n weights that is the same as the :meth:`monomial_coefficients` method\n of ``self.char_from_weights()``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: v = A2._space([3,1,0])\n sage: d = dict([(x,1) for x in v.orbit()])\n sage: A2._char_from_weights(d)\n {(2, 1, 1): -1, (2, 2, 0): -1, (3, 1, 0): 1}\n ' hdict = {} ddict = mdict.copy() while ddict: highest = max(((x.inner_product(self._space.rho()), x) for x in ddict))[1] if (not highest.is_dominant()): raise ValueError('multiplicity dictionary may not be Weyl group invariant') sdict = self._irr_weights(highest) c = ddict[highest] if (highest in hdict): hdict[highest] += c else: hdict[highest] = c for k in sdict: if (k in ddict): if (ddict[k] == (c * sdict[k])): del ddict[k] else: ddict[k] = (ddict[k] - (c * sdict[k])) else: ddict[k] = ((- c) * sdict[k]) return hdict def adjoint_representation(self): '\n Return the adjoint representation as an element of the WeylCharacterRing.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing("G2",style="coroots")\n sage: G2.adjoint_representation()\n G2(0,1)\n ' return self(self.highest_root()) def maximal_subgroups(self): '\n This method is only available if the Cartan type of\n ``self`` is irreducible and of rank no greater than 8.\n This method produces a list of the maximal subgroups\n of ``self``, up to (possibly outer) automorphisms. Each line\n in the output gives the Cartan type of a maximal subgroup\n followed by a command that creates the branching rule.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("E6").maximal_subgroups()\n D5:branching_rule("E6","D5","levi")\n C4:branching_rule("E6","C4","symmetric")\n F4:branching_rule("E6","F4","symmetric")\n A2:branching_rule("E6","A2","miscellaneous")\n G2:branching_rule("E6","G2","miscellaneous")\n A2xG2:branching_rule("E6","A2xG2","miscellaneous")\n A1xA5:branching_rule("E6","A1xA5","extended")\n A2xA2xA2:branching_rule("E6","A2xA2xA2","extended")\n\n Note that there are other embeddings of (for example\n `A_2` into `E_6` as nonmaximal subgroups. These\n embeddings may be constructed by composing branching\n rules through various subgroups.\n\n Once you know which maximal subgroup you are interested\n in, to create the branching rule, you may either\n paste the command to the right of the colon from the\n above output onto the command line, or alternatively\n invoke the related method :meth:`maximal_subgroup`::\n\n sage: branching_rule("E6","G2","miscellaneous")\n miscellaneous branching rule E6 => G2\n sage: WeylCharacterRing("E6").maximal_subgroup("G2")\n miscellaneous branching rule E6 => G2\n\n It is believed that the list of maximal subgroups is complete, except that some\n subgroups may be not be invariant under outer automorphisms. It is reasonable\n to want a list of maximal subgroups that is complete up to conjugation,\n but to obtain such a list you may have to apply outer automorphisms.\n The group of outer automorphisms modulo inner automorphisms is isomorphic\n to the group of symmetries of the Dynkin diagram, and these are available\n as branching rules. The following example shows that while\n a branching rule from `D_4` to `A_1\\times C_2` is supplied,\n another different one may be obtained by composing it with the\n triality automorphism of `D_4`::\n\n sage: [D4,A1xC2]=[WeylCharacterRing(x,style="coroots") for x in ["D4","A1xC2"]]\n sage: fw = D4.fundamental_weights()\n sage: b = D4.maximal_subgroup("A1xC2")\n sage: [D4(fw).branch(A1xC2,rule=b) for fw in D4.fundamental_weights()]\n [A1xC2(1,1,0),\n A1xC2(2,0,0) + A1xC2(2,0,1) + A1xC2(0,2,0),\n A1xC2(1,1,0),\n A1xC2(2,0,0) + A1xC2(0,0,1)]\n sage: b1 = branching_rule("D4","D4","triality")*b\n sage: [D4(fw).branch(A1xC2,rule=b1) for fw in D4.fundamental_weights()]\n [A1xC2(1,1,0),\n A1xC2(2,0,0) + A1xC2(2,0,1) + A1xC2(0,2,0),\n A1xC2(2,0,0) + A1xC2(0,0,1),\n A1xC2(1,1,0)]\n ' return sage.combinat.root_system.branching_rules.maximal_subgroups(self.cartan_type()) def maximal_subgroup(self, ct): '\n Return a branching rule or a list of branching rules.\n\n INPUT:\n\n - ``ct`` -- the Cartan type of a maximal subgroup of ``self``.\n\n In rare cases where there is\n more than one maximal subgroup (up to outer automorphisms)\n with the given Cartan type, the function returns a list of\n branching rules.\n\n EXAMPLES::\n\n sage: WeylCharacterRing("E7").maximal_subgroup("A2")\n miscellaneous branching rule E7 => A2\n sage: WeylCharacterRing("E7").maximal_subgroup("A1")\n [iii branching rule E7 => A1, iv branching rule E7 => A1]\n\n For more information, see the related method :meth:`maximal_subgroups`.\n ' return sage.combinat.root_system.branching_rules.maximal_subgroups(self.cartan_type(), mode='get_rule')[ct] class Element(CombinatorialFreeModule.Element): '\n A class for Weyl characters.\n ' def cartan_type(self): '\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2([1,0,0]).cartan_type()\n [\'A\', 2]\n ' return self.parent()._cartan_type def degree(self): "\n Return the degree of ``self``.\n\n This is the dimension of the associated module.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing(['B',3])\n sage: [B3(x).degree() for x in B3.fundamental_weights()]\n [7, 21, 8]\n " L = self.parent()._space return sum(((L.weyl_dimension(k) * c) for (k, c) in self)) def branch(self, S, rule='default'): '\n Return the restriction of the character to the subalgebra.\n\n If no rule is specified, we will try to specify one.\n\n INPUT:\n\n - ``S`` -- a Weyl character ring for a Lie subgroup or subalgebra\n\n - ``rule`` -- a branching rule\n\n See :func:`~sage.combinat.root_system.branching_rules.branch_weyl_character`\n for more information about branching rules.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing([\'B\',3])\n sage: A2 = WeylCharacterRing([\'A\',2])\n sage: [B3(w).branch(A2,rule="levi") for w in B3.fundamental_weights()]\n [A2(0,0,0) + A2(1,0,0) + A2(0,0,-1),\n A2(0,0,0) + A2(1,0,0) + A2(1,1,0) + A2(1,0,-1) + A2(0,-1,-1) + A2(0,0,-1),\n A2(-1/2,-1/2,-1/2) + A2(1/2,-1/2,-1/2) + A2(1/2,1/2,-1/2) + A2(1/2,1/2,1/2)]\n ' return sage.combinat.root_system.branching_rules.branch_weyl_character(self, self.parent(), S, rule=rule) def dual(self): '\n The involution that replaces a representation with\n its contragredient. (For Fusion rings, this is the\n conjugation map.)\n\n EXAMPLES::\n\n sage: A3 = WeylCharacterRing("A3", style="coroots")\n sage: A3(1,0,0)^2\n A3(0,1,0) + A3(2,0,0)\n sage: (A3(1,0,0)^2).dual()\n A3(0,1,0) + A3(0,0,2)\n ' if (not self.parent().cartan_type().is_irreducible()): raise NotImplementedError('dual method is not implemented for reducible types') d = self.monomial_coefficients() WCR = self.parent() return sum(((d[k] * WCR._element_constructor_(self.parent()._dual_helper(k))) for k in d)) def highest_weight(self): '\n Return the parametrizing dominant weight\n of an irreducible character.\n\n This method is only available for basis elements.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing("G2", style="coroots")\n sage: [x.highest_weight() for x in [G2(1,0),G2(0,1)]]\n [(1, 0, -1), (2, -1, -1)]\n ' if (len(self.monomial_coefficients()) != 1): raise ValueError('fusion weight is valid for basis elements only') return self.leading_support() def __pow__(self, n): '\n Return the n-th power of ``self``.\n\n We override the method in :mod:`sage.monoids.monoids` since\n using the Brauer-Klimyk algorithm, it is more efficient to\n compute ``a*(a*(a*a))`` than ``(a*a)*(a*a)``.\n\n EXAMPLES::\n\n sage: B4 = WeylCharacterRing("B4",style="coroots")\n sage: spin = B4(0,0,0,1)\n sage: [spin^k for k in [0,1,3]]\n [B4(0,0,0,0), B4(0,0,0,1), 5*B4(0,0,0,1) + 4*B4(1,0,0,1) + 3*B4(0,1,0,1) + 2*B4(0,0,1,1) + B4(0,0,0,3)]\n sage: spin^-1\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= B4(0,0,0,1))\n sage: x = 2 * B4.one(); x\n 2*B4(0,0,0,0)\n sage: x^-3\n 1/8*B4(0,0,0,0)\n ' n = ZZ(n) if (not n): return self.parent().one() if (n < 0): self = (~ self) n = (- n) res = self for i in range((n - 1)): res = (self * res) return res def is_irreducible(self): "\n Return whether ``self`` is an irreducible character.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing(['B',3])\n sage: [B3(x).is_irreducible() for x in B3.fundamental_weights()]\n [True, True, True]\n sage: sum(B3(x) for x in B3.fundamental_weights()).is_irreducible()\n False\n " return (self.coefficients() == [1]) @cached_method def symmetric_power(self, k): '\n Return the `k`-th symmetric power of ``self``.\n\n INPUT:\n\n - `k` -- a nonnegative integer\n\n The algorithm is based on the\n identity `k h_k = \\sum_{r=1}^k p_k h_{k-r}` relating the power-sum\n and complete symmetric polynomials. Applying this to the\n eigenvalues of an element of the parent Lie group in the\n representation ``self``, the `h_k` become symmetric powers and\n the `p_k` become Adams operations, giving an efficient recursive\n implementation.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing("B3",style="coroots")\n sage: spin = B3(0,0,1)\n sage: spin.symmetric_power(6)\n B3(0,0,0) + B3(0,0,2) + B3(0,0,4) + B3(0,0,6)\n ' par = self.parent() if (k == 0): return par.one() if (k == 1): return self ret = par.zero() for r in range(1, (k + 1)): adam_r = self._adams_operator_helper(r) ret += par.linear_combination(((par._product_helper(adam_r, l), c) for (l, c) in self.symmetric_power((k - r)))) m = ret.weight_multiplicities() dd = {key: (val / k) for (key, val) in m.items()} return self.parent().char_from_weights(dd) @cached_method def exterior_power(self, k): '\n Return the `k`-th exterior power of ``self``.\n\n INPUT:\n\n - ``k`` -- a nonnegative integer\n\n The algorithm is based on the\n identity `k e_k = \\sum_{r=1}^k (-1)^{k-1} p_k e_{k-r}` relating the\n power-sum and elementary symmetric polynomials. Applying this to\n the eigenvalues of an element of the parent Lie group in the\n representation ``self``, the `e_k` become exterior powers and\n the `p_k` become Adams operations, giving an efficient recursive\n implementation.\n\n EXAMPLES::\n\n sage: B3 = WeylCharacterRing("B3",style="coroots")\n sage: spin = B3(0,0,1)\n sage: spin.exterior_power(6)\n B3(1,0,0) + B3(0,1,0)\n ' par = self.parent() if (k == 0): return par.one() if (k == 1): return self ret = par.zero() for r in range(1, (k + 1)): adam_r = self._adams_operator_helper(r) if is_even(r): ret -= par.linear_combination(((par._product_helper(adam_r, l), c) for (l, c) in self.exterior_power((k - r)))) else: ret += par.linear_combination(((par._product_helper(adam_r, l), c) for (l, c) in self.exterior_power((k - r)))) dd = {} m = ret.weight_multiplicities() for l in m: dd[l] = (m[l] / k) return self.parent().char_from_weights(dd) def adams_operator(self, r): '\n Return the `r`-th Adams operation of ``self``.\n\n INPUT:\n\n - ``r`` -- a positive integer\n\n This is a virtual character,\n whose weights are the weights of ``self``, each multiplied by `r`.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2(1,1,0).adams_operator(3)\n A2(2,2,2) - A2(3,2,1) + A2(3,3,0)\n ' return self.parent().char_from_weights(self._adams_operator_helper(r)) adams_operation = adams_operator def _adams_operator_helper(self, r): '\n Helper function for Adams operations.\n\n INPUT:\n\n - ``r`` -- a positive integer\n\n Return the dictionary of weight multiplicities for the Adams\n operation, needed for internal use by symmetric and exterior powers.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2(1,1,0)._adams_operator_helper(3)\n {(3, 3, 0): 1, (3, 0, 3): 1, (0, 3, 3): 1}\n ' d = self.weight_multiplicities() return {(r * key): val for (key, val) in d.items()} def symmetric_square(self): '\n Return the symmetric square of the character.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2",style="coroots")\n sage: A2(1,0).symmetric_square()\n A2(2,0)\n ' c = self.weight_multiplicities() ckeys = list(c) d = {} for j in range(len(ckeys)): for i in range((j + 1)): ci = ckeys[i] cj = ckeys[j] t = (ci + cj) if (i < j): coef = (c[ci] * c[cj]) else: coef = ((c[ci] * (c[ci] + 1)) / 2) if (t in d): d[t] += coef else: d[t] = coef for k in list(d): if (d[k] == 0): del d[k] return self.parent().char_from_weights(d) def exterior_square(self): '\n Return the exterior square of the character.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2",style="coroots")\n sage: A2(1,0).exterior_square()\n A2(0,1)\n ' c = self.weight_multiplicities() ckeys = list(c) d = {} for j in range(len(ckeys)): for i in range((j + 1)): ci = ckeys[i] cj = ckeys[j] t = (ci + cj) if (i < j): coef = (c[ci] * c[cj]) else: coef = ((c[ci] * (c[ci] - 1)) / 2) if (t in d): d[t] += coef else: d[t] = coef for k in list(d): if (d[k] == 0): del d[k] return self.parent().char_from_weights(d) def frobenius_schur_indicator(self): '\n Return:\n\n - `1` if the representation is real (orthogonal)\n\n - `-1` if the representation is quaternionic (symplectic)\n\n - `0` if the representation is complex (not self dual)\n\n The Frobenius-Schur indicator of a character `\\chi`\n of a compact group `G` is the Haar integral over the\n group of `\\chi(g^2)`. Its value is 1, -1 or 0. This\n method computes it for irreducible characters of\n compact Lie groups by checking whether the symmetric\n and exterior square characters contain the trivial\n character.\n\n .. TODO::\n\n Try to compute this directly without actually calculating\n the full symmetric and exterior squares.\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2",style="coroots")\n sage: B2(1,0).frobenius_schur_indicator()\n 1\n sage: B2(0,1).frobenius_schur_indicator()\n -1\n ' if (not self.is_irreducible()): raise ValueError('Frobenius-Schur indicator is only valid for irreducible characters') z = self.parent()._space.zero() if (self.symmetric_square().coefficient(z) != 0): return 1 if (self.exterior_square().coefficient(z) != 0): return (- 1) return 0 def weight_multiplicities(self): '\n Return the dictionary of weight multiplicities for the Weyl\n character ``self``.\n\n The character does not have to be irreducible.\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2",style="coroots")\n sage: B2(0,1).weight_multiplicities()\n {(-1/2, -1/2): 1, (-1/2, 1/2): 1, (1/2, -1/2): 1, (1/2, 1/2): 1}\n ' return self.parent()._weight_multiplicities(self) def inner_product(self, other): '\n Compute the inner product with another character.\n\n The irreducible characters are an orthonormal basis with respect\n to the usual inner product of characters, interpreted as functions\n on a compact Lie group, by Schur orthogonality.\n\n INPUT:\n\n - ``other`` -- another character\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: [f1,f2] = A2.fundamental_weights()\n sage: r1 = A2(f1)*A2(f2); r1\n A2(1,1,1) + A2(2,1,0)\n sage: r2 = A2(f1)^3; r2\n A2(1,1,1) + 2*A2(2,1,0) + A2(3,0,0)\n sage: r1.inner_product(r2)\n 3\n ' return sum(((self.coefficient(x) * other.coefficient(x)) for x in self.monomial_coefficients())) def invariant_degree(self): '\n Return the multiplicity of the trivial representation in ``self``.\n\n Multiplicities of other irreducibles may be obtained\n using :meth:`multiplicity`.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2",style="coroots")\n sage: rep = A2(1,0)^2*A2(0,1)^2; rep\n 2*A2(0,0) + A2(0,3) + 4*A2(1,1) + A2(3,0) + A2(2,2)\n sage: rep.invariant_degree()\n 2\n ' return self.coefficient(self.parent().space()(0)) def multiplicity(self, other): '\n Return the multiplicity of the irreducible ``other`` in ``self``.\n\n INPUT:\n\n - ``other`` -- an irreducible character\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2",style="coroots")\n sage: rep = B2(1,1)^2; rep\n B2(0,0) + B2(1,0) + 2*B2(0,2) + B2(2,0) + 2*B2(1,2) + B2(0,4) + B2(3,0) + B2(2,2)\n sage: rep.multiplicity(B2(0,2))\n 2\n ' if (not other.is_irreducible()): raise ValueError('{} is not irreducible'.format(other)) return self.coefficient(other.support()[0])
def irreducible_character_freudenthal(hwv, debug=False): '\n Return the dictionary of multiplicities for the irreducible\n character with highest weight `\\lambda`.\n\n The weight multiplicities are computed by the Freudenthal multiplicity\n formula. The algorithm is based on recursion relation that is stated,\n for example, in Humphrey\'s book on Lie Algebras. The multiplicities are\n invariant under the Weyl group, so to compute them it would be sufficient\n to compute them for the weights in the positive Weyl chamber. However\n after some testing it was found to be faster to compute every\n weight using the recursion, since the use of the Weyl group is\n expensive in its current implementation.\n\n INPUT:\n\n - ``hwv`` -- a dominant weight in a weight lattice.\n\n - ``L`` -- the ambient space\n\n EXAMPLES::\n\n sage: WeylCharacterRing("A2")(2,1,0).weight_multiplicities() # indirect doctest\n {(1, 1, 1): 2, (1, 2, 0): 1, (1, 0, 2): 1, (2, 1, 0): 1,\n (2, 0, 1): 1, (0, 1, 2): 1, (0, 2, 1): 1}\n ' L = hwv.parent() rho = L.rho() mdict = {} current_layer = {hwv: 1} simple_roots = L.simple_roots() positive_roots = L.positive_roots() while current_layer: next_layer = {} for mu in current_layer: if (current_layer[mu] != 0): mdict[mu] = current_layer[mu] for alpha in simple_roots: next_layer[(mu - alpha)] = None if debug: print(next_layer) for mu in next_layer: if (next_layer[mu] is None): accum = 0 for alpha in positive_roots: mu_plus_i_alpha = (mu + alpha) while (mu_plus_i_alpha in mdict): accum += (mdict[mu_plus_i_alpha] * mu_plus_i_alpha.inner_product(alpha)) mu_plus_i_alpha += alpha if (accum == 0): next_layer[mu] = 0 else: hwv_plus_rho = (hwv + rho) mu_plus_rho = (mu + rho) next_layer[mu] = (ZZ((2 * accum)) / ZZ((hwv_plus_rho.inner_product(hwv_plus_rho) - mu_plus_rho.inner_product(mu_plus_rho)))) current_layer = next_layer return mdict
class WeightRing(CombinatorialFreeModule): "\n The weight ring, which is the group algebra over a weight lattice.\n\n A Weyl character may be regarded as an element of the weight ring.\n In fact, an element of the weight ring is an element of the\n :class:`Weyl character ring <WeylCharacterRing>` if and only if it is\n invariant under the action of the Weyl group.\n\n The advantage of the weight ring over the Weyl character ring\n is that one may conduct calculations in the weight ring that\n involve sums of weights that are not Weyl group invariant.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing(['A',2])\n sage: a2 = WeightRing(A2)\n sage: wd = prod(a2(x/2)-a2(-x/2) for x in a2.space().positive_roots()); wd\n a2(-1,1,0) - a2(-1,0,1) - a2(1,-1,0) + a2(1,0,-1) + a2(0,-1,1) - a2(0,1,-1)\n sage: chi = A2([5,3,0]); chi\n A2(5,3,0)\n sage: a2(chi)\n a2(1,2,5) + 2*a2(1,3,4) + 2*a2(1,4,3) + a2(1,5,2) + a2(2,1,5)\n + 2*a2(2,2,4) + 3*a2(2,3,3) + 2*a2(2,4,2) + a2(2,5,1) + 2*a2(3,1,4)\n + 3*a2(3,2,3) + 3*a2(3,3,2) + 2*a2(3,4,1) + a2(3,5,0) + a2(3,0,5)\n + 2*a2(4,1,3) + 2*a2(4,2,2) + 2*a2(4,3,1) + a2(4,4,0) + a2(4,0,4)\n + a2(5,1,2) + a2(5,2,1) + a2(5,3,0) + a2(5,0,3) + a2(0,3,5)\n + a2(0,4,4) + a2(0,5,3)\n sage: a2(chi)*wd\n -a2(-1,3,6) + a2(-1,6,3) + a2(3,-1,6) - a2(3,6,-1) - a2(6,-1,3) + a2(6,3,-1)\n sage: sum((-1)^w.length()*a2([6,3,-1]).weyl_group_action(w) for w in a2.space().weyl_group())\n -a2(-1,3,6) + a2(-1,6,3) + a2(3,-1,6) - a2(3,6,-1) - a2(6,-1,3) + a2(6,3,-1)\n sage: a2(chi)*wd == sum((-1)^w.length()*a2([6,3,-1]).weyl_group_action(w) for w in a2.space().weyl_group())\n True\n " @staticmethod def __classcall__(cls, parent, prefix=None): '\n TESTS::\n\n sage: A3 = WeylCharacterRing("A3", style="coroots")\n sage: a3 = WeightRing(A3)\n sage: a3.cartan_type(), a3.base_ring(), a3.parent()\n ([\'A\', 3], Integer Ring, The Weyl Character Ring of Type A3 with Integer Ring coefficients)\n ' return super().__classcall__(cls, parent, prefix=prefix) def __init__(self, parent, prefix): '\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: TestSuite(a2).run()\n\n TESTS::\n\n sage: A1xA1 = WeylCharacterRing("A1xA1")\n sage: a1xa1 = WeightRing(A1xA1)\n sage: TestSuite(a1xa1).run()\n sage: a1xa1.an_element()\n a1xa1(2,2,3,0)\n ' self._parent = parent self._style = parent._style self._prefix = prefix self._space = parent._space self._cartan_type = parent._cartan_type self._rank = parent._rank self._origin = parent._origin self._base_ring = parent._base_ring if (prefix is None): if self._parent._prefix.replace('x', '_').isupper(): prefix = self._parent._prefix.lower() elif self._parent._prefix.islower(): prefix = self._parent._prefix.upper() else: prefix = (self._cartan_type[0].lower() + str(self._rank)) self._prefix = prefix category = AlgebrasWithBasis(self._base_ring).Commutative() CombinatorialFreeModule.__init__(self, self._base_ring, self._space, category=category) def _repr_(self): "\n EXAMPLES::\n\n sage: P.<q>=QQ[]\n sage: G2 = WeylCharacterRing(['G',2], base_ring = P)\n sage: WeightRing(G2) # indirect doctest\n The Weight ring attached to The Weyl Character Ring of Type G2 with Univariate Polynomial Ring in q over Rational Field coefficients\n " return ('The Weight ring attached to %s' % self._parent) def __call__(self, *args): '\n Construct an element of ``self``.\n\n The input can either be an object that can be coerced or\n converted into ``self`` (an element of ``self``, of the base\n ring, of the weight ring), or a dominant weight. In the later\n case, the basis element indexed by that weight is returned.\n\n To specify the weight, you may give it explicitly. Alternatively,\n you may give a tuple of integers. Normally these are the\n components of the vector in the standard realization of\n the weight lattice as a vector space. Alternatively, if\n the ring is constructed with style="coroots", you may\n specify the weight by giving a set of integers, one for each\n fundamental weight; the weight is then the linear combination\n of the fundamental weights with these coefficients.\n\n As a syntactical shorthand, for tuples of length at least two,\n the parenthesis may be omitted.\n\n EXAMPLES::\n\n sage: a2 = WeightRing(WeylCharacterRing([\'A\',2]))\n sage: a2(-1)\n -a2(0,0,0)\n ' if (len(args) > 1): args = (args,) return super().__call__(*args) def _element_constructor_(self, weight): '\n Construct a monomial from a weight.\n\n INPUT:\n\n - ``weight`` -- an element of the weight space, or a tuple\n\n This method is responsible for constructing an appropriate\n weight from the data in ``weight``, and then return the\n monomial indexed by that weight. See :meth:`__call__` and\n :meth:`sage.combinat.root_system.ambient_space.AmbientSpace.from_vector`.\n\n TESTS::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: A2._element_constructor_([2,1,0])\n A2(2,1,0)\n ' weight = self._space.from_vector_notation(weight, style=self._style) return self.monomial(weight) def product_on_basis(self, a, b): '\n Return the product of basis elements indexed by ``a`` and ``b``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: a2(1,0,0) * a2(0,1,0) # indirect doctest\n a2(1,1,0)\n ' return self((a + b)) def some_elements(self): '\n Return some elements of ``self``.\n\n EXAMPLES::\n\n sage: A3 = WeylCharacterRing("A3")\n sage: a3 = WeightRing(A3)\n sage: a3.some_elements()\n [a3(1,0,0,0), a3(1,1,0,0), a3(1,1,1,0)]\n ' return [self.monomial(x) for x in self.fundamental_weights()] def one_basis(self): '\n Return the index of `1`.\n\n EXAMPLES::\n\n sage: A3 = WeylCharacterRing("A3")\n sage: WeightRing(A3).one_basis()\n (0, 0, 0, 0)\n sage: WeightRing(A3).one()\n a3(0,0,0,0)\n ' return self._space.zero() def parent(self): '\n Return the parent Weyl character ring.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: a2.parent()\n The Weyl Character Ring of Type A2 with Integer Ring coefficients\n sage: a2.parent() == A2\n True\n ' return self._parent def weyl_character_ring(self): '\n Return the parent Weyl Character Ring.\n\n A synonym for ``self.parent()``.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: a2.weyl_character_ring()\n The Weyl Character Ring of Type A2 with Integer Ring coefficients\n ' return self._parent def cartan_type(self): '\n Return the Cartan type.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: WeightRing(A2).cartan_type()\n [\'A\', 2]\n ' return self._cartan_type def space(self): "\n Return the weight space realization associated to ``self``.\n\n EXAMPLES::\n\n sage: E8 = WeylCharacterRing(['E',8])\n sage: e8 = WeightRing(E8)\n sage: e8.space()\n Ambient space of the Root system of type ['E', 8]\n " return self._space def fundamental_weights(self): '\n Return the fundamental weights.\n\n EXAMPLES::\n\n sage: WeightRing(WeylCharacterRing("G2")).fundamental_weights()\n Finite family {1: (1, 0, -1), 2: (2, -1, -1)}\n ' return self._space.fundamental_weights() def simple_roots(self): '\n Return the simple roots.\n\n EXAMPLES::\n\n sage: WeightRing(WeylCharacterRing("G2")).simple_roots()\n Finite family {1: (0, 1, -1), 2: (1, -2, 1)}\n ' return self._space.simple_roots() def positive_roots(self): '\n Return the positive roots.\n\n EXAMPLES::\n\n sage: WeightRing(WeylCharacterRing("G2")).positive_roots()\n [(0, 1, -1), (1, -2, 1), (1, -1, 0), (1, 0, -1), (1, 1, -2), (2, -1, -1)]\n ' return self._space.positive_roots() def wt_repr(self, wt): '\n Return a string representing the irreducible character with\n highest weight vector ``wt``.\n\n Uses coroot notation if the associated\n Weyl character ring is defined with ``style="coroots"``.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing("G2")\n sage: [G2.ambient().wt_repr(x) for x in G2.fundamental_weights()]\n [\'g2(1,0,-1)\', \'g2(2,-1,-1)\']\n sage: G2 = WeylCharacterRing("G2",style="coroots")\n sage: [G2.ambient().wt_repr(x) for x in G2.fundamental_weights()]\n [\'g2(1,0)\', \'g2(0,1)\']\n ' return (self._prefix + self.parent()._wt_repr(wt)) def _repr_term(self, t): '\n Representation of the monomial corresponding to a weight ``t``.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing("G2")\n sage: g2 = WeightRing(G2)\n sage: [g2(x) for x in g2.fundamental_weights()] # indirect doctest\n [g2(1,0,-1), g2(2,-1,-1)]\n ' return self.wt_repr(t) class Element(CombinatorialFreeModule.Element): '\n A class for weight ring elements.\n ' def cartan_type(self): '\n Return the Cartan type.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing("A2")\n sage: a2 = WeightRing(A2)\n sage: a2([0,1,0]).cartan_type()\n [\'A\', 2]\n ' return self.parent()._cartan_type def weyl_group_action(self, w): "\n Return the action of the Weyl group element ``w`` on ``self``.\n\n EXAMPLES::\n\n sage: G2 = WeylCharacterRing(['G',2])\n sage: g2 = WeightRing(G2)\n sage: L = g2.space()\n sage: [fw1, fw2] = L.fundamental_weights()\n sage: sum(g2(fw2).weyl_group_action(w) for w in L.weyl_group())\n 2*g2(-2,1,1) + 2*g2(-1,-1,2) + 2*g2(-1,2,-1) + 2*g2(1,-2,1) + 2*g2(1,1,-2) + 2*g2(2,-1,-1)\n " return self.map_support(w.action) def character(self): "\n Assuming that ``self`` is invariant under the Weyl group, this will\n express it as a linear combination of characters. If ``self`` is\n not Weyl group invariant, this method will not terminate.\n\n EXAMPLES::\n\n sage: A2 = WeylCharacterRing(['A',2])\n sage: a2 = WeightRing(A2)\n sage: W = a2.space().weyl_group()\n sage: mu = a2(2,1,0)\n sage: nu = sum(mu.weyl_group_action(w) for w in W) ; nu\n a2(1,2,0) + a2(1,0,2) + a2(2,1,0) + a2(2,0,1) + a2(0,1,2) + a2(0,2,1)\n sage: nu.character()\n -2*A2(1,1,1) + A2(2,1,0)\n " return self.parent().parent().char_from_weights(self.monomial_coefficients()) def scale(self, k): '\n Multiply a weight by `k`.\n\n The operation is extended by linearity to the weight ring.\n\n INPUT:\n\n - ``k`` -- a nonzero integer\n\n EXAMPLES::\n\n sage: g2 = WeylCharacterRing("G2",style="coroots").ambient()\n sage: g2(2,3).scale(2)\n g2(4,6)\n ' if (k == 0): raise ValueError('parameter must be nonzero') d1 = self.monomial_coefficients() d2 = {(k * mu): coeff for (mu, coeff) in d1.items()} return self.parent()._from_dict(d2) def shift(self, mu): '\n Add `\\mu` to any weight.\n\n Extended by linearity to the weight ring.\n\n INPUT:\n\n - ``mu`` -- a weight\n\n EXAMPLES::\n\n sage: g2 = WeylCharacterRing("G2",style="coroots").ambient()\n sage: [g2(1,2).shift(fw) for fw in g2.fundamental_weights()]\n [g2(2,2), g2(1,3)]\n ' d1 = self.monomial_coefficients() d2 = {(mu + nu): val for (nu, val) in d1.items()} return self.parent()._from_dict(d2) def demazure(self, w, debug=False): '\n Return the result of applying the Demazure operator `\\partial_w`\n to ``self``.\n\n INPUT:\n\n - ``w`` -- a Weyl group element, or its reduced word\n\n If `w = s_i` is a simple reflection, the operation `\\partial_w`\n sends the weight `\\lambda` to\n\n .. MATH::\n\n \\frac{\\lambda - s_i \\cdot \\lambda + \\alpha_i}{1 + \\alpha_i},\n\n where the numerator is divisible the denominator in the weight\n ring. This is extended by multiplicativity to all `w` in the\n Weyl group.\n\n EXAMPLES::\n\n sage: B2 = WeylCharacterRing("B2",style="coroots")\n sage: b2 = WeightRing(B2)\n sage: b2(1,0).demazure([1])\n b2(1,0) + b2(-1,2)\n sage: b2(1,0).demazure([2])\n b2(1,0)\n sage: r = b2(1,0).demazure([1,2]); r\n b2(1,0) + b2(-1,2)\n sage: r.demazure([1])\n b2(1,0) + b2(-1,2)\n sage: r.demazure([2])\n b2(0,0) + b2(1,0) + b2(1,-2) + b2(-1,2)\n ' if isinstance(w, list): word = w else: word = w.reduced_word() d1 = self.monomial_coefficients() d = {} alphacheck = self.parent()._space.simple_coroots() for v in d1: d[tuple((v.inner_product(alphacheck[j]) for j in self.parent().space().index_set()))] = d1[v] return self.parent()._from_dict(self.parent().parent()._demazure_helper(d, word, debug=debug)) def demazure_lusztig(self, i, v): '\n Return the result of applying the Demazure-Lusztig operator\n `T_i` to ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set (or a reduced word or\n Weyl group element)\n - ``v`` -- an element of the base ring\n\n If `R` is the parent WeightRing, the Demazure-Lusztig operator\n `T_i` is the linear map `R \\to R` that sends (for a weight\n `\\lambda`) `R(\\lambda)` to\n\n .. MATH::\n\n (R(\\alpha_i)-1)^{-1} \\bigl(R(\\lambda) - R(s_i\\lambda)\n - v(R(\\lambda) - R(\\alpha_i + s_i \\lambda)) \\bigr)\n\n where the numerator is divisible by the denominator in `R`.\n The Demazure-Lusztig operators give a representation of the\n Iwahori--Hecke algebra associated to the Weyl group. See\n\n * Lusztig, Equivariant `K`-theory and representations of Hecke\n algebras, Proc. Amer. Math. Soc. 94 (1985), no. 2, 337-342.\n * Cherednik, *Nonsymmetric Macdonald polynomials*. IMRN 10,\n 483-515 (1995).\n\n In the examples, we confirm the braid and quadratic relations\n for type `B_2`.\n\n EXAMPLES::\n\n sage: P.<v> = PolynomialRing(QQ)\n sage: B2 = WeylCharacterRing("B2",style="coroots",base_ring=P); b2 = B2.ambient()\n sage: def T1(f): return f.demazure_lusztig(1,v)\n sage: def T2(f): return f.demazure_lusztig(2,v)\n sage: T1(T2(T1(T2(b2(1,-1)))))\n (v^2-v)*b2(0,-1) + v^2*b2(-1,1)\n sage: [T1(T1(f))==(v-1)*T1(f)+v*f for f in [b2(0,0), b2(1,0), b2(2,3)]]\n [True, True, True]\n sage: [T1(T2(T1(T2(b2(i,j))))) == T2(T1(T2(T1(b2(i,j))))) for i in [-2..2] for j in [-1,1]]\n [True, True, True, True, True, True, True, True, True, True]\n\n Instead of an index `i` one may use a reduced word or\n Weyl group element::\n\n sage: b2(1,0).demazure_lusztig([2,1],v)==T2(T1(b2(1,0)))\n True\n sage: W = B2.space().weyl_group(prefix="s")\n sage: [s1,s2]=W.simple_reflections()\n sage: b2(1,0).demazure_lusztig(s2*s1,v)==T2(T1(b2(1,0)))\n True\n ' if (i in self.parent().space().index_set()): rho = self.parent().space().from_vector_notation(self.parent().space().rho(), style='coroots') inv = self.scale((- 1)) return ((- inv.shift((- rho)).demazure([i]).shift(rho)) + (v * inv.demazure([i]))).scale((- 1)) elif isinstance(i, list): if (not i): return self elif (len(i) == 1): return self.demazure_lusztig(i[0], v) else: return self.demazure_lusztig(i[1:], v).demazure_lusztig(i[:1], v) else: try: return self.demazure_lusztig(i.reduced_word(), v) except Exception: raise ValueError('unknown index {}'.format(i))
def WeylGroup(x, prefix=None, implementation='matrix'): '\n Return the Weyl group of the root system defined by the Cartan\n type (or matrix) ``ct``.\n\n INPUT:\n\n - ``x`` -- a root system or a Cartan type (or matrix)\n\n OPTIONAL:\n\n - ``prefix`` -- changes the representation of elements from matrices\n to products of simple reflections\n\n - ``implementation`` -- one of the following:\n\n * ``\'matrix\'`` - as matrices acting on a root system\n * ``"permutation"`` - as a permutation group acting on the roots\n\n EXAMPLES:\n\n The following constructions yield the same result, namely\n a weight lattice and its corresponding Weyl group::\n\n sage: G = WeylGroup([\'F\',4])\n sage: L = G.domain()\n\n or alternatively and equivalently::\n\n sage: L = RootSystem([\'F\',4]).ambient_space()\n sage: G = L.weyl_group()\n sage: W = WeylGroup(L)\n\n Either produces a weight lattice, with access to its roots and\n weights.\n\n ::\n\n sage: G = WeylGroup([\'F\',4])\n sage: G.order()\n 1152\n sage: [s1,s2,s3,s4] = G.simple_reflections()\n sage: w = s1*s2*s3*s4; w\n [ 1/2 1/2 1/2 1/2]\n [-1/2 1/2 1/2 -1/2]\n [ 1/2 1/2 -1/2 -1/2]\n [ 1/2 -1/2 1/2 -1/2]\n sage: type(w) == G.element_class\n True\n sage: w.order()\n 12\n sage: w.length() # length function on Weyl group\n 4\n\n The default representation of Weyl group elements is as matrices.\n If you prefer, you may specify a prefix, in which case the\n elements are represented as products of simple reflections.\n\n ::\n\n sage: W=WeylGroup("C3",prefix="s")\n sage: [s1,s2,s3]=W.simple_reflections() # lets Sage parse its own output\n sage: s2*s1*s2*s3\n s1*s2*s3*s1\n sage: s2*s1*s2*s3 == s1*s2*s3*s1\n True\n sage: (s2*s3)^2==(s3*s2)^2\n True\n sage: (s1*s2*s3*s1).matrix()\n [ 0 0 -1]\n [ 0 1 0]\n [ 1 0 0]\n\n ::\n\n sage: L = G.domain()\n sage: fw = L.fundamental_weights(); fw\n Finite family {1: (1, 1, 0, 0), 2: (2, 1, 1, 0), 3: (3/2, 1/2, 1/2, 1/2), 4: (1, 0, 0, 0)}\n sage: rho = sum(fw); rho\n (11/2, 5/2, 3/2, 1/2)\n sage: w.action(rho) # action of G on weight lattice\n (5, -1, 3, 2)\n\n We can also do the same for arbitrary Cartan matrices::\n\n sage: cm = CartanMatrix([[2,-5,0],[-2,2,-1],[0,-1,2]])\n sage: W = WeylGroup(cm)\n sage: W.gens()\n (\n [-1 5 0] [ 1 0 0] [ 1 0 0]\n [ 0 1 0] [ 2 -1 1] [ 0 1 0]\n [ 0 0 1], [ 0 0 1], [ 0 1 -1]\n )\n sage: s0,s1,s2 = W.gens()\n sage: s1*s2*s1\n [ 1 0 0]\n [ 2 0 -1]\n [ 2 -1 0]\n sage: s2*s1*s2\n [ 1 0 0]\n [ 2 0 -1]\n [ 2 -1 0]\n sage: s0*s1*s0*s2*s0\n [ 9 0 -5]\n [ 2 0 -1]\n [ 0 1 -1]\n\n Same Cartan matrix, but with a prefix to display using simple reflections::\n\n sage: W = WeylGroup(cm, prefix=\'s\')\n sage: s0,s1,s2 = W.gens()\n sage: s0*s2*s1\n s2*s0*s1\n sage: (s1*s2)^3\n 1\n sage: (s0*s1)^5\n s0*s1*s0*s1*s0*s1*s0*s1*s0*s1\n sage: s0*s1*s2*s1*s2\n s2*s0*s1\n sage: s0*s1*s2*s0*s2\n s0*s1*s0\n\n TESTS::\n\n sage: TestSuite(WeylGroup(["A",3])).run()\n sage: TestSuite(WeylGroup(["A",2,1])).run() # long time\n\n sage: W = WeylGroup([\'A\',3,1])\n sage: s = W.simple_reflections()\n sage: w = s[0]*s[1]*s[2]\n sage: w.reduced_word()\n [0, 1, 2]\n sage: w = s[0]*s[2]\n sage: w.reduced_word()\n [2, 0]\n sage: W = groups.misc.WeylGroup([\'A\',3,1])\n ' if (implementation == 'permutation'): return WeylGroup_permutation(x, prefix) if (implementation != 'matrix'): raise ValueError('invalid implementation') if (x in RootLatticeRealizations): return WeylGroup_gens(x, prefix=prefix) try: ct = CartanType(x) except TypeError: ct = CartanMatrix(x) if ct.is_finite(): return WeylGroup_gens(ct.root_system().ambient_space(), prefix=prefix) return WeylGroup_gens(ct.root_system().root_space(), prefix=prefix)
class WeylGroup_gens(UniqueRepresentation, FinitelyGeneratedMatrixGroup_gap): @staticmethod def __classcall__(cls, domain, prefix=None): return super().__classcall__(cls, domain, prefix) def __init__(self, domain, prefix): "\n EXAMPLES::\n\n sage: G = WeylGroup(['B',3])\n sage: TestSuite(G).run()\n sage: cm = CartanMatrix([[2,-5,0],[-2,2,-1],[0,-1,2]])\n sage: W = WeylGroup(cm)\n sage: TestSuite(W).run() # long time\n\n TESTS::\n\n sage: W = WeylGroup(SymmetricGroup(1))\n " self._domain = domain if self.cartan_type().is_affine(): category = AffineWeylGroups() elif self.cartan_type().is_finite(): category = FiniteWeylGroups() else: category = WeylGroups() if self.cartan_type().is_irreducible(): category = category.Irreducible() self.n = domain.dimension() self._prefix = prefix gens_matrix = [self.morphism_matrix(self.domain().simple_reflection(i)) for i in self.index_set()] if (not gens_matrix): libgap_group = libgap.Group([], matrix(ZZ, 1, 1, [1])) else: libgap_group = libgap.Group(gens_matrix) degree = ZZ(self.domain().dimension()) ring = self.domain().base_ring() FinitelyGeneratedMatrixGroup_gap.__init__(self, degree, ring, libgap_group, category=category) @cached_method def cartan_type(self): "\n Return the ``CartanType`` associated to ``self``.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['F',4])\n sage: G.cartan_type()\n ['F', 4]\n " return self.domain().cartan_type() @cached_method def index_set(self): "\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['F',4])\n sage: G.index_set()\n (1, 2, 3, 4)\n sage: G = WeylGroup(['A',3,1])\n sage: G.index_set()\n (0, 1, 2, 3)\n " return self.cartan_type().index_set() def morphism_matrix(self, f): return matrix(self.domain().base_ring(), [f(b).to_vector() for b in self.domain().basis()]).transpose() def from_morphism(self, f): return self._element_constructor_(self.morphism_matrix(f)) @cached_method def simple_reflections(self): "\n Return the simple reflections of ``self``, as a family.\n\n EXAMPLES:\n\n There are the simple reflections for the symmetric group::\n\n sage: W=WeylGroup(['A',2])\n sage: s = W.simple_reflections(); s\n Finite family {1: [0 1 0]\n [1 0 0]\n [0 0 1], 2: [1 0 0]\n [0 0 1]\n [0 1 0]}\n\n As a special feature, for finite irreducible root systems,\n s[0] gives the reflection along the highest root::\n\n sage: s[0]\n [0 0 1]\n [0 1 0]\n [1 0 0]\n\n We now look at some further examples::\n\n sage: W=WeylGroup(['A',2,1])\n sage: W.simple_reflections()\n Finite family {0: [-1 1 1]\n [ 0 1 0]\n [ 0 0 1], 1: [ 1 0 0]\n [ 1 -1 1]\n [ 0 0 1], 2: [ 1 0 0]\n [ 0 1 0]\n [ 1 1 -1]}\n sage: W = WeylGroup(['F',4])\n sage: [s1,s2,s3,s4] = W.simple_reflections()\n sage: w = s1*s2*s3*s4; w\n [ 1/2 1/2 1/2 1/2]\n [-1/2 1/2 1/2 -1/2]\n [ 1/2 1/2 -1/2 -1/2]\n [ 1/2 -1/2 1/2 -1/2]\n sage: s4^2 == W.one()\n True\n sage: type(w) == W.element_class\n True\n\n " return self.domain().simple_reflections().map(self.from_morphism) def reflections(self): '\n Return the reflections of ``self``.\n\n The reflections of a Coxeter group `W` are the conjugates of\n the simple reflections. They are in bijection with the positive\n roots, for given a positive root, we may have the reflection in\n the hyperplane orthogonal to it. This method returns a family\n indexed by the positive roots taking values in the reflections.\n This requires ``self`` to be a finite Weyl group.\n\n .. NOTE::\n\n Prior to :trac:`20027`, the reflections were the keys\n of the family and the values were the positive roots.\n\n EXAMPLES::\n\n sage: W = WeylGroup("B2", prefix="s")\n sage: refdict = W.reflections(); refdict\n Finite family {(1, -1): s1, (0, 1): s2, (1, 1): s2*s1*s2, (1, 0): s1*s2*s1}\n sage: [r+refdict[r].action(r) for r in refdict.keys()]\n [(0, 0), (0, 0), (0, 0), (0, 0)]\n\n sage: W = WeylGroup([\'A\',2,1], prefix="s")\n sage: W.reflections()\n Lazy family (real root to reflection(i))_{i in\n Positive real roots of type [\'A\', 2, 1]}\n\n TESTS::\n\n sage: CM = CartanMatrix([[2,-6],[-1,2]])\n sage: W = WeylGroup(CM, prefix=\'s\')\n sage: W.reflections()\n Traceback (most recent call last):\n ...\n NotImplementedError: only implemented for finite and affine Cartan types\n ' prr = self.domain().positive_real_roots() def to_elt(alp): ref = self.domain().reflection(alp) m = Matrix([ref(x).to_vector() for x in self.domain().basis()]) return self(m.transpose()) return Family(prr, to_elt, name='real root to reflection') def _repr_(self): "\n EXAMPLES::\n\n sage: WeylGroup(['A', 1])\n Weyl Group of type ['A', 1] (as a matrix group acting on the ambient space)\n sage: WeylGroup(['A', 3, 1])\n Weyl Group of type ['A', 3, 1] (as a matrix group acting on the root space)\n " domain = self._domain._name_string(capitalize=False, base_ring=False, type=False) return ('Weyl Group of type %s (as a matrix group acting on the %s)' % (self.cartan_type(), domain)) def character_table(self): '\n Return the character table as a matrix.\n\n Each row is an irreducible character. For larger tables you\n may preface this with a command such as\n gap.eval("SizeScreen([120,40])") in order to widen the screen.\n\n EXAMPLES::\n\n sage: WeylGroup([\'A\',3]).character_table()\n CT1\n <BLANKLINE>\n 2 3 2 2 . 3\n 3 1 . . 1 .\n <BLANKLINE>\n 1a 4a 2a 3a 2b\n <BLANKLINE>\n X.1 1 -1 -1 1 1\n X.2 3 1 -1 . -1\n X.3 2 . . -1 2\n X.4 3 -1 1 . -1\n X.5 1 1 1 1 1\n ' G = libgap.Group([libgap(g) for g in self.gens()]) ctbl = libgap.CharacterTable(G) return ctbl.Display() @cached_method def one(self): "\n Return the unit element of the Weyl group.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: e = W.one(); e\n [1 0 0 0]\n [0 1 0 0]\n [0 0 1 0]\n [0 0 0 1]\n sage: type(e) == W.element_class\n True\n " return self._element_constructor_(matrix(QQ, self.n, self.n, 1)) unit = one def domain(self): "\n Return the domain of the element of ``self``, that is the\n root lattice realization on which they act.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['F',4])\n sage: G.domain()\n Ambient space of the Root system of type ['F', 4]\n sage: G = WeylGroup(['A',3,1])\n sage: G.domain()\n Root space over the Rational Field of the Root system of type ['A', 3, 1]\n " return self._domain def simple_reflection(self, i): "\n Return the `i^{th}` simple reflection.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['F',4])\n sage: G.simple_reflection(1)\n [1 0 0 0]\n [0 0 1 0]\n [0 1 0 0]\n [0 0 0 1]\n sage: W=WeylGroup(['A',2,1])\n sage: W.simple_reflection(1)\n [ 1 0 0]\n [ 1 -1 1]\n [ 0 0 1]\n " if (i not in self.index_set()): raise ValueError('i must be in the index set') return self.simple_reflections()[i] def long_element_hardcoded(self): "\n Return the long Weyl group element (hardcoded data).\n\n Do we really want to keep it? There is a generic\n implementation which works in all cases. The hardcoded should\n have a better complexity (for large classical types), but\n there is a cache, so does this really matter?\n\n EXAMPLES::\n\n sage: types = [ ['A',5],['B',3],['C',3],['D',4],['G',2],['F',4],['E',6] ]\n sage: [WeylGroup(t).long_element().length() for t in types]\n [15, 9, 9, 12, 6, 24, 36]\n sage: all(WeylGroup(t).long_element() == WeylGroup(t).long_element_hardcoded() for t in types) # long time (17s on sage.math, 2011)\n True\n " typ = self.cartan_type() if ((typ[0] == 'D') and (typ[1] % 2)): l = [(- 1) for i in range((self.n - 1))] l.append(1) m = diagonal_matrix(QQ, l) elif (typ[0] == 'A'): l = [0 for k in range((self.n ** 2))] for k in range((self.n - 1), ((self.n ** 2) - 1), (self.n - 1)): l[k] = 1 m = matrix(QQ, self.n, l) elif (typ[0] == 'E'): if (typ[1] == 6): half = QQ((1, 2)) l = [[(- half), (- half), (- half), half, 0, 0, 0, 0], [(- half), (- half), half, (- half), 0, 0, 0, 0], [(- half), half, (- half), (- half), 0, 0, 0, 0], [half, (- half), (- half), (- half), 0, 0, 0, 0], [0, 0, 0, 0, half, half, half, (- half)], [0, 0, 0, 0, half, half, (- half), half], [0, 0, 0, 0, half, (- half), half, half], [0, 0, 0, 0, (- half), half, half, half]] m = matrix(QQ, 8, l) else: raise NotImplementedError('not implemented yet for this type') elif (typ[0] == 'G'): third = QQ((1, 3)) twothirds = QQ((2, 3)) l = [[(- third), twothirds, twothirds], [twothirds, (- third), twothirds], [twothirds, twothirds, (- third)]] m = matrix(QQ, 3, l) else: m = diagonal_matrix(([(- 1)] * self.n)) return self(m) def classical(self): "\n If ``self`` is a Weyl group from an affine Cartan Type, this give\n the classical parabolic subgroup of ``self``.\n\n Caveat: we assume that 0 is a special node of the Dynkin diagram\n\n .. TODO:: extract parabolic subgroup method\n\n EXAMPLES::\n\n sage: G = WeylGroup(['A',3,1])\n sage: G.classical()\n Parabolic Subgroup of the Weyl Group of type ['A', 3, 1]\n (as a matrix group acting on the root space)\n sage: WeylGroup(['A',3]).classical()\n Traceback (most recent call last):\n ...\n ValueError: classical subgroup only defined for affine types\n " if (not self.cartan_type().is_affine()): raise ValueError('classical subgroup only defined for affine types') return ClassicalWeylSubgroup(self._domain, prefix=self._prefix)
class ClassicalWeylSubgroup(WeylGroup_gens): '\n A class for Classical Weyl Subgroup of an affine Weyl Group\n\n EXAMPLES::\n\n sage: G = WeylGroup(["A",3,1]).classical()\n sage: G\n Parabolic Subgroup of the Weyl Group of type [\'A\', 3, 1] (as a matrix group acting on the root space)\n sage: G.category()\n Category of finite irreducible Weyl groups\n sage: G.cardinality()\n 24\n sage: G.index_set()\n (1, 2, 3)\n sage: TestSuite(G).run()\n\n TESTS::\n\n sage: from sage.combinat.root_system.weyl_group import ClassicalWeylSubgroup\n sage: H = ClassicalWeylSubgroup(RootSystem(["A", 3, 1]).root_space(), prefix=None)\n sage: H is G\n True\n\n Caveat: the interface is likely to change. The current main\n application is for plots.\n\n .. TODO::\n\n implement:\n\n - Parabolic subrootsystems\n - Parabolic subgroups with a set of nodes as argument\n ' @cached_method def cartan_type(self): "\n EXAMPLES::\n\n sage: WeylGroup(['A',3,1]).classical().cartan_type()\n ['A', 3]\n sage: WeylGroup(['A',3,1]).classical().index_set()\n (1, 2, 3)\n\n Note: won't be needed, once the lattice will be a parabolic sub root system\n " return self.domain().cartan_type().classical() def simple_reflections(self): "\n EXAMPLES::\n\n sage: WeylGroup(['A',2,1]).classical().simple_reflections()\n Finite family {1: [ 1 0 0]\n [ 1 -1 1]\n [ 0 0 1],\n 2: [ 1 0 0]\n [ 0 1 0]\n [ 1 1 -1]}\n\n Note: won't be needed, once the lattice will be a parabolic sub root system\n " return Family({i: self.from_morphism(self.domain().simple_reflection(i)) for i in self.index_set()}) def __repr__(self): "\n EXAMPLES::\n\n sage: WeylGroup(['A',2,1]).classical()\n Parabolic Subgroup of the Weyl Group of type ['A', 2, 1] (as a matrix group acting on the root space)\n sage: WeylGroup(['C',4,1]).classical()\n Parabolic Subgroup of the Weyl Group of type ['C', 4, 1] (as a matrix group acting on the root space)\n sage: RootSystem(['C',3,1]).coweight_lattice().weyl_group().classical()\n Parabolic Subgroup of the Weyl Group of type ['C', 3, 1]^* (as a matrix group acting on the coweight lattice)\n sage: RootSystem(['C',4,1]).coweight_lattice().weyl_group().classical()\n Parabolic Subgroup of the Weyl Group of type ['C', 4, 1]^* (as a matrix group acting on the coweight lattice)\n " domain = self._domain._name_string(capitalize=False, base_ring=False, type=False) return ('Parabolic Subgroup of the Weyl Group of type %s (as a matrix group acting on the %s)' % (self.domain().cartan_type(), domain)) def weyl_group(self, prefix='hereditary'): "\n Return the Weyl group associated to the parabolic subgroup.\n\n EXAMPLES::\n\n sage: WeylGroup(['A',4,1]).classical().weyl_group()\n Weyl Group of type ['A', 4, 1] (as a matrix group acting on the root space)\n sage: WeylGroup(['C',4,1]).classical().weyl_group()\n Weyl Group of type ['C', 4, 1] (as a matrix group acting on the root space)\n sage: WeylGroup(['E',8,1]).classical().weyl_group()\n Weyl Group of type ['E', 8, 1] (as a matrix group acting on the root space)\n " if (prefix == 'hereditary'): prefix = self._prefix return self.domain().weyl_group(prefix) def _test_is_finite(self, **options): "\n Tests some internal invariants\n\n EXAMPLES::\n\n sage: WeylGroup(['A', 2, 1]).classical()._test_is_finite()\n sage: WeylGroup(['B', 3, 1]).classical()._test_is_finite()\n " tester = self._tester(**options) tester.assertTrue((not self.weyl_group(self._prefix).is_finite())) tester.assertTrue(self.is_finite())
class WeylGroupElement(MatrixGroupElement_gap): '\n Class for a Weyl Group elements\n ' def __init__(self, parent, g, check=False): "\n EXAMPLES::\n\n sage: G = WeylGroup(['A',2])\n sage: s1 = G.simple_reflection(1)\n sage: TestSuite(s1).run()\n " MatrixGroupElement_gap.__init__(self, parent, g, check=check) self._parent = parent def __hash__(self): return hash(self.matrix()) def to_matrix(self): "\n Return ``self`` as a matrix.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['A',2])\n sage: s1 = G.simple_reflection(1)\n sage: s1.to_matrix() == s1.matrix()\n True\n " return self.matrix() def domain(self): "\n Return the ambient lattice associated with ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',2])\n sage: s1 = W.simple_reflection(1)\n sage: s1.domain()\n Ambient space of the Root system of type ['A', 2]\n " return self._parent.domain() def _repr_(self): '\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',2,1], prefix="s")\n sage: [s0,s1,s2] = W.simple_reflections()\n sage: s0*s1\n s0*s1\n sage: W = WeylGroup([\'A\',2,1])\n sage: [s0,s1,s2]=W.simple_reflections()\n sage: s0*s1\n [ 0 -1 2]\n [ 1 -1 1]\n [ 0 0 1]\n ' if (self._parent._prefix is None): return MatrixGroupElement_gap._repr_(self) redword = self.reduced_word() if (len(redword) == 0): return '1' ret = ''.join((('%s%d*' % (self._parent._prefix, i)) for i in redword[:(- 1)])) return (ret + ('%s%d' % (self._parent._prefix, redword[(- 1)]))) def _latex_(self): '\n Return the latex representation of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',2,1], prefix="s")\n sage: [s0,s1,s2] = W.simple_reflections()\n sage: latex(s0*s1) # indirect doctest\n s_{0}s_{1}\n sage: W = WeylGroup([\'A\',2,1])\n sage: [s0,s1,s2] = W.simple_reflections()\n sage: latex(s0*s1)\n \\left(\\begin{array}{rrr}\n 0 & -1 & 2 \\\\\n 1 & -1 & 1 \\\\\n 0 & 0 & 1\n \\end{array}\\right)\n ' if (self._parent._prefix is None): return MatrixGroupElement_gap._latex_(self) redword = self.reduced_word() if (not redword): return '1' return ''.join((('%s_{%d}' % (self._parent._prefix, i)) for i in redword)) def __eq__(self, other): "\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: s = W.simple_reflections()\n sage: s[1] == s[1]\n True\n sage: s[1] == s[2]\n False\n\n Note: this implementation of :meth:`__eq__` is not much faster\n than :meth:`__cmp__`. But it turned out to be useful for\n subclasses overriding __cmp__ with something slow for specific\n purposes.\n " return ((self.__class__ == other.__class__) and (self._parent == other._parent) and (self.matrix() == other.matrix())) def _richcmp_(self, other, op): "\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: s = W.simple_reflections()\n sage: s[1] == s[1]\n True\n sage: s[1] == s[2]\n False\n " if (self._parent.cartan_type() != other._parent.cartan_type()): return richcmp_not_equal(self._parent.cartan_type(), other._parent.cartan_type(), op) return richcmp(self.matrix(), other.matrix(), op) def action(self, v): "\n Return the action of self on the vector v.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',2])\n sage: s = W.simple_reflections()\n sage: v = W.domain()([1,0,0])\n sage: s[1].action(v)\n (0, 1, 0)\n\n sage: W = WeylGroup(RootSystem(['A',2]).root_lattice())\n sage: s = W.simple_reflections()\n sage: alpha = W.domain().simple_roots()\n sage: s[1].action(alpha[1])\n -alpha[1]\n\n sage: W=WeylGroup(['A',2,1])\n sage: alpha = W.domain().simple_roots()\n sage: s = W.simple_reflections()\n sage: s[1].action(alpha[1])\n -alpha[1]\n sage: s[1].action(alpha[0])\n alpha[0] + alpha[1]\n " if (v not in self.domain()): raise ValueError(f'{v} is not in the domain') return self.domain().from_vector((self.matrix() * v.to_vector())) def has_descent(self, i, positive=False, side='right') -> bool: '\n Test if ``self`` has a descent at position ``i``.\n\n An element `w` has a descent in position `i` if `w` is\n on the strict negative side of the `i^{th}` simple reflection\n hyperplane.\n\n If ``positive`` is ``True``, tests if it is on the strict\n positive side instead.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3])\n sage: s = W.simple_reflections()\n sage: [W.one().has_descent(i) for i in W.domain().index_set()]\n [False, False, False]\n sage: [s[1].has_descent(i) for i in W.domain().index_set()]\n [True, False, False]\n sage: [s[2].has_descent(i) for i in W.domain().index_set()]\n [False, True, False]\n sage: [s[3].has_descent(i) for i in W.domain().index_set()]\n [False, False, True]\n sage: [s[3].has_descent(i, True) for i in W.domain().index_set()]\n [True, True, False]\n sage: W = WeylGroup([\'A\',3,1])\n sage: s = W.simple_reflections()\n sage: [W.one().has_descent(i) for i in W.domain().index_set()]\n [False, False, False, False]\n sage: [s[0].has_descent(i) for i in W.domain().index_set()]\n [True, False, False, False]\n sage: w = s[0] * s[1]\n sage: [w.has_descent(i) for i in W.domain().index_set()]\n [False, True, False, False]\n sage: [w.has_descent(i, side = "left") for i in W.domain().index_set()]\n [True, False, False, False]\n sage: w = s[0] * s[2]\n sage: [w.has_descent(i) for i in W.domain().index_set()]\n [True, False, True, False]\n sage: [w.has_descent(i, side = "left") for i in W.domain().index_set()]\n [True, False, True, False]\n\n sage: W = WeylGroup([\'A\',3])\n sage: W.one().has_descent(0)\n True\n sage: W.w0.has_descent(0)\n False\n ' L = self.domain() if (not hasattr(L.element_class, 'is_positive_root')): use_rho = True elif (not hasattr(L, 'rho')): use_rho = False else: use_rho = (side == 'left') element = (self if (use_rho is (side == 'left')) else (~ self)) if use_rho: s = (element.action(L.rho()).scalar(L.alphacheck()[i]) >= 0) else: s = element.action(L.alpha()[i]).is_positive_root() return (s is positive) def has_left_descent(self, i): "\n Test if ``self`` has a left descent at position ``i``.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: s = W.simple_reflections()\n sage: [W.one().has_left_descent(i) for i in W.domain().index_set()]\n [False, False, False]\n sage: [s[1].has_left_descent(i) for i in W.domain().index_set()]\n [True, False, False]\n sage: [s[2].has_left_descent(i) for i in W.domain().index_set()]\n [False, True, False]\n sage: [s[3].has_left_descent(i) for i in W.domain().index_set()]\n [False, False, True]\n sage: [(s[3]*s[2]).has_left_descent(i) for i in W.domain().index_set()]\n [False, False, True]\n " return self.has_descent(i, side='left') def has_right_descent(self, i): "\n Test if ``self`` has a right descent at position ``i``.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: s = W.simple_reflections()\n sage: [W.one().has_right_descent(i) for i in W.domain().index_set()]\n [False, False, False]\n sage: [s[1].has_right_descent(i) for i in W.domain().index_set()]\n [True, False, False]\n sage: [s[2].has_right_descent(i) for i in W.domain().index_set()]\n [False, True, False]\n sage: [s[3].has_right_descent(i) for i in W.domain().index_set()]\n [False, False, True]\n sage: [(s[3]*s[2]).has_right_descent(i) for i in W.domain().index_set()]\n [False, True, False]\n " return self.has_descent(i, side='right') def apply_simple_reflection(self, i, side='right'): s = self.parent().simple_reflections() if (side == 'right'): return (self * s[i]) return (s[i] * self) def to_permutation(self): '\n A first approximation of to_permutation ...\n\n This assumes types A,B,C,D on the ambient lattice\n\n This further assume that the basis is indexed by 0,1,...\n and returns a permutation of (5,4,2,3,1) (beuargl), as a tuple\n ' W = self.parent() e = W.domain().basis() return tuple(((c * (j + 1)) for i in e.keys() for (j, c) in self.action(e[i]))) def to_permutation_string(self): '\n EXAMPLES::\n\n sage: W = WeylGroup(["A",3])\n sage: s = W.simple_reflections()\n sage: (s[1]*s[2]*s[3]).to_permutation_string()\n \'2341\'\n ' return ''.join((str(i) for i in self.to_permutation()))
class WeylGroup_permutation(UniqueRepresentation, PermutationGroup_generic): '\n A Weyl group given as a permutation group.\n ' @staticmethod def __classcall__(cls, cartan_type, prefix=None): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: W1 = WeylGroup([\'B\',2], implementation="permutation")\n sage: W2 = WeylGroup(CartanType([\'B\',2]), implementation="permutation")\n sage: W1 is W2\n True\n ' return super().__classcall__(cls, CartanType(cartan_type), prefix) def __init__(self, cartan_type, prefix): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'F\',4], implementation="permutation")\n sage: TestSuite(W).run()\n ' self._cartan_type = cartan_type self._index_set = cartan_type.index_set() self._index_set_inverse = {ii: i for (i, ii) in enumerate(cartan_type.index_set())} self._reflection_representation = None self._prefix = prefix Q = cartan_type.root_system().root_lattice() Phi = (list(Q.positive_roots()) + [(- x) for x in Q.positive_roots()]) p = [[(Phi.index(x.weyl_action([i])) + 1) for x in Phi] for i in self._cartan_type.index_set()] cat = FiniteWeylGroups() if self._cartan_type.is_irreducible(): cat = cat.Irreducible() cat = (cat, PermutationGroups().Finite()) PermutationGroup_generic.__init__(self, gens=p, canonicalize=False, category=cat) def iteration(self, algorithm='breadth', tracking_words=True): '\n Return an iterator going through all elements in ``self``.\n\n INPUT:\n\n - ``algorithm`` (default: ``\'breadth\'``) -- must be one of\n the following:\n\n * ``\'breadth\'`` - iterate over in a linear extension of the\n weak order\n * ``\'depth\'`` - iterate by a depth-first-search\n\n - ``tracking_words`` (default: ``True``) -- whether or not to keep\n track of the reduced words and store them in ``_reduced_word``\n\n .. NOTE::\n\n The fastest iteration is the depth first algorithm without\n tracking words. In particular, ``\'depth\'`` is ~1.5x faster.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",2], implementation="permutation")\n\n sage: for w in W.iteration("breadth",True):\n ....: print("%s %s"%(w, w._reduced_word))\n () []\n (1,3)(2,6)(5,7) [1]\n (1,5)(2,4)(6,8) [0]\n (1,7,5,3)(2,4,6,8) [0, 1]\n (1,3,5,7)(2,8,6,4) [1, 0]\n (2,8)(3,7)(4,6) [1, 0, 1]\n (1,7)(3,5)(4,8) [0, 1, 0]\n (1,5)(2,6)(3,7)(4,8) [0, 1, 0, 1]\n\n sage: for w in W.iteration("depth", False): w\n ()\n (1,3)(2,6)(5,7)\n (1,5)(2,4)(6,8)\n (1,3,5,7)(2,8,6,4)\n (1,7)(3,5)(4,8)\n (1,7,5,3)(2,4,6,8)\n (2,8)(3,7)(4,6)\n (1,5)(2,6)(3,7)(4,8)\n ' from sage.combinat.root_system.reflection_group_c import Iterator return iter(Iterator(self, N=self.number_of_reflections(), algorithm=algorithm, tracking_words=tracking_words)) def __iter__(self): '\n Return an iterator going through all elements in ``self``.\n\n For options and faster iteration see :meth:`iteration`.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",2], implementation="permutation")\n sage: for w in W: print("%s %s"%(w, w._reduced_word))\n () []\n (1,3)(2,6)(5,7) [1]\n (1,5)(2,4)(6,8) [0]\n (1,7,5,3)(2,4,6,8) [0, 1]\n (1,3,5,7)(2,8,6,4) [1, 0]\n (2,8)(3,7)(4,6) [1, 0, 1]\n (1,7)(3,5)(4,8) [0, 1, 0]\n (1,5)(2,6)(3,7)(4,8) [0, 1, 0, 1]\n ' return self.iteration(algorithm='breadth', tracking_words=True) def _coerce_map_from_(self, P): '\n Return ``True`` if ``P`` is a Weyl group of the same\n Cartan type and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["B",4], implementation="permutation")\n sage: W2 = WeylGroup(["B",4])\n sage: W._coerce_map_from_(W2)\n True\n sage: W3 = WeylGroup(["B",5])\n sage: W.has_coerce_map_from(W3)\n False\n sage: W4 = CoxeterGroup(["B",4])\n sage: W.has_coerce_map_from(W4)\n False\n sage: W5 = WeylGroup(["C",4], implementation="permutation")\n sage: W.has_coerce_map_from(W5)\n False\n ' return (isinstance(P, WeylGroup_gens) and (P.cartan_type() is self.cartan_type())) @cached_method def rank(self): '\n Return the rank of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], implementation="permutation")\n sage: W.rank()\n 4\n ' return self._cartan_type.rank() def simple_reflection(self, i): '\n Return the ``i``-th simple reflection of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], implementation="permutation")\n sage: W.simple_reflection(1)\n (1,11)(2,5)(6,8)(9,10)(12,15)(16,18)(19,20)\n sage: W.simple_reflections()\n Finite family {1: (1,11)(2,5)(6,8)(9,10)(12,15)(16,18)(19,20),\n 2: (1,5)(2,12)(3,6)(7,9)(11,15)(13,16)(17,19),\n 3: (2,6)(3,13)(4,7)(5,8)(12,16)(14,17)(15,18),\n 4: (3,7)(4,14)(6,9)(8,10)(13,17)(16,19)(18,20)}\n ' return self.gens()[self._index_set_inverse[i]] @cached_method def simple_roots(self): '\n Return the simple roots of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], implementation="permutation")\n sage: W.simple_roots()\n Finite family {1: (1, 0, 0, 0), 2: (0, 1, 0, 0),\n 3: (0, 0, 1, 0), 4: (0, 0, 0, 1)}\n ' Q = self._cartan_type.root_system().root_lattice() roots = [al.to_vector() for al in Q.simple_roots()] for v in roots: v.set_immutable() return Family(self._index_set, (lambda i: roots[self._index_set_inverse[i]])) independent_roots = simple_roots @cached_method def index_set(self): '\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], implementation="permutation")\n sage: W.index_set()\n (1, 2, 3, 4)\n ' return self._index_set @cached_method def reflection_index_set(self): '\n Return the index set of reflections of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], implementation="permutation")\n sage: W.reflection_index_set()\n (1, 2, 3, 4, 5, 6)\n ' return tuple(range(1, (self.number_of_reflections() + 1))) def cartan_type(self): '\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], implementation="permutation")\n sage: W.cartan_type()\n [\'A\', 4]\n ' return self._cartan_type @cached_method def roots(self): '\n Return the roots of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'G\',2], implementation="permutation")\n sage: W.roots()\n ((1, 0),\n (0, 1),\n (1, 1),\n (3, 1),\n (2, 1),\n (3, 2),\n (-1, 0),\n (0, -1),\n (-1, -1),\n (-3, -1),\n (-2, -1),\n (-3, -2))\n ' Q = self._cartan_type.root_system().root_lattice() roots = ([x.to_vector() for x in Q.positive_roots()] + [(- x.to_vector()) for x in Q.positive_roots()]) for v in roots: v.set_immutable() return tuple(roots) def positive_roots(self): '\n Return the positive roots of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'C\',3], implementation="permutation")\n sage: W.positive_roots()\n ((1, 0, 0),\n (0, 1, 0),\n (0, 0, 1),\n (1, 1, 0),\n (0, 1, 1),\n (0, 2, 1),\n (1, 1, 1),\n (2, 2, 1),\n (1, 2, 1))\n ' return self.roots()[:self.number_of_reflections()] @cached_method def number_of_reflections(self): '\n Return the number of reflections in ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'D\',4], implementation="permutation")\n sage: W.number_of_reflections()\n 12\n ' return len(list(self._cartan_type.root_system().root_lattice().positive_roots())) @cached_method def distinguished_reflections(self): '\n Return the reflections of ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'B\',2], implementation="permutation")\n sage: W.distinguished_reflections()\n Finite family {1: (1,5)(2,4)(6,8), 2: (1,3)(2,6)(5,7),\n 3: (2,8)(3,7)(4,6), 4: (1,7)(3,5)(4,8)}\n ' Q = self._cartan_type.root_system().root_lattice() pos_roots = list(Q.positive_roots()) Phi = (pos_roots + [(- x) for x in pos_roots]) def build_elt(index): r = pos_roots[index] perm = [(Phi.index(x.reflection(r)) + 1) for x in Phi] return self.element_class(perm, self, check=False) return Family(self.reflection_index_set(), (lambda i: build_elt((i - 1)))) reflections = distinguished_reflections def simple_root_index(self, i): '\n Return the index of the simple root `\\alpha_i`.\n\n This is the position of `\\alpha_i` in the list of simple roots.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], implementation="permutation")\n sage: [W.simple_root_index(i) for i in W.index_set()]\n [0, 1, 2]\n ' return self._index_set_inverse[i] class Element(RealReflectionGroupElement): def _repr_(self): '\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], prefix="s", implementation="permutation")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: s1*s2\n s1*s2\n sage: W = WeylGroup([\'A\',3], implementation="permutation")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: s1*s2\n (1,10,2)(3,5,6)(4,8,7)(9,11,12)\n ' if (self.parent()._prefix is None): return RealReflectionGroupElement._repr_(self) redword = self.reduced_word() if (not redword): return '1' return '*'.join((('%s%d' % (self.parent()._prefix, i)) for i in redword)) def _latex_(self): '\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], prefix="s", implementation="permutation")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: s1*s2\n s1*s2\n sage: W = WeylGroup([\'A\',3], implementation="permutation")\n sage: [s1,s2,s3] = W.simple_reflections()\n sage: s1*s2\n (1,10,2)(3,5,6)(4,8,7)(9,11,12)\n ' if (self.parent()._prefix is None): return RealReflectionGroupElement._repr_(self) redword = self.reduced_word() if (not redword): return '1' return ''.join((('%s_{%d}' % (self.parent()._prefix, i)) for i in redword))
@cached_function def number_of_rooted_trees(n): "\n Return the number of rooted trees with `n` nodes.\n\n Compute the number `a(n)` of rooted trees with `n` nodes using the\n recursive formula ([SL000081]_):\n\n .. MATH::\n\n a(n+1) = \\frac{1}{n} \\sum_{k=1}^{n} \\left( \\sum_{d|k} d a(d) \\right) a(n-k+1)\n\n EXAMPLES::\n\n sage: from sage.combinat.rooted_tree import number_of_rooted_trees\n sage: [number_of_rooted_trees(i) for i in range(10)]\n [0, 1, 1, 2, 4, 9, 20, 48, 115, 286]\n\n REFERENCES:\n\n .. [SL000081] Sloane's :oeis:`A000081`\n " if (n == 0): return Integer(0) if (n == 1): return Integer(1) n = Integer(n) return (sum(((sum(((d * number_of_rooted_trees(d)) for d in k.divisors())) * number_of_rooted_trees((n - k))) for k in ZZ.range(1, n))) // (n - 1))
class RootedTree(AbstractClonableTree, NormalizedClonableList, metaclass=InheritComparisonClasscallMetaclass): '\n The class for unordered rooted trees.\n\n The *unordered rooted trees* are an inductive datatype defined\n as follows: An unordered rooted tree is a multiset of\n unordered rooted trees. The trees that belong to this\n multiset are said to be the *children* of the tree. The tree\n that has no children is called a *leaf*.\n\n The *labelled rooted trees* (:class:`LabelledRootedTree`)\n form a subclass of this class; they carry additional data.\n\n One can create a tree from any list (or more generally iterable)\n of trees or objects convertible to a tree.\n\n EXAMPLES::\n\n sage: RootedTree([])\n []\n sage: RootedTree([[], [[]]])\n [[], [[]]]\n sage: RootedTree([[[]], []])\n [[], [[]]]\n sage: O = OrderedTree([[[]], []]); O\n [[[]], []]\n sage: RootedTree(O) # this is O with the ordering forgotten\n [[], [[]]]\n\n One can also enter any small rooted tree ("small" meaning that\n no vertex has more than `15` children) by using a simple\n numerical encoding of rooted trees, namely, the\n :func:`~sage.combinat.abstract_tree.from_hexacode` function.\n (This function actually parametrizes ordered trees, and here\n we make it parametrize unordered trees by forgetting the\n ordering.) ::\n\n sage: from sage.combinat.abstract_tree import from_hexacode\n sage: RT = RootedTrees()\n sage: from_hexacode(\'32001010\', RT)\n [[[]], [[]], [[], []]]\n\n .. NOTE::\n\n Unlike an ordered tree, an (unordered) rooted tree is a\n multiset (rather than a list) of children. That is, two\n ordered trees which differ from each other by switching\n the order of children are equal to each other as (unordered)\n rooted trees. Internally, rooted trees are encoded as\n :class:`sage.structure.list_clone.NormalizedClonableList`\n instances, and instead of storing their children as an\n actual multiset, they store their children as a list which\n is sorted according to their :meth:`sort_key` value. This\n is as good as storing them as multisets, since the\n :meth:`sort_key` values are sortable and distinguish\n different (unordered) trees. However, if you wish to define\n a subclass of :class:`RootedTree` which implements rooted\n trees with extra structure (say, a class of edge-colored\n rooted trees, or a class of rooted trees with a cyclic\n order on the list of children), then the inherited\n :meth:`sort_key` method will no longer distinguish different\n trees (and, as a consequence, equal trees will be regarded\n as distinct). Thus, you will have to override the method by\n one that does distinguish different trees.\n ' @staticmethod def __classcall_private__(cls, *args, **opts): "\n Ensure that rooted trees created by the enumerated sets and directly\n are the same and that they are instances of :class:`RootedTree`.\n\n TESTS::\n\n sage: from sage.combinat.rooted_tree import (RootedTrees_all,\n ....: RootedTrees_size)\n sage: issubclass(RootedTrees_all().element_class, RootedTree)\n True\n sage: issubclass(RootedTrees_size(3).element_class, RootedTree)\n True\n sage: t0 = RootedTree([[],[[]]])\n sage: t0.parent()\n Rooted trees\n sage: type(t0)\n <class 'sage.combinat.rooted_tree.RootedTrees_all_with_category.element_class'>\n\n sage: t1 = RootedTrees()([[],[[]]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n\n sage: t1 = RootedTrees(4)([[],[[]]])\n sage: t1.parent() is t0.parent()\n True\n sage: type(t1) is type(t0)\n True\n " return cls._auto_parent.element_class(cls._auto_parent, *args, **opts) @lazy_class_attribute def _auto_parent(cls): '\n The automatic parent of the elements of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: RootedTree._auto_parent\n Rooted trees\n sage: RootedTree([]).parent()\n Rooted trees\n ' return RootedTrees_all() def __init__(self, parent=None, children=[], check=True): '\n TESTS::\n\n sage: RT4 = RootedTrees(4)\n sage: t1 = RT4([[],[[]]])\n sage: TestSuite(t1).run()\n\n Some bad inputs are refused::\n\n sage: RT4(69)\n Traceback (most recent call last):\n ...\n TypeError: input (69) is not a valid tree\n ' try: children = list(children) except TypeError: raise TypeError('input ({}) is not a valid tree'.format(children)) children = [self.__class__(parent, x) for x in children] NormalizedClonableList.__init__(self, parent, children, check=check) def sort_key(self): "\n Return a tuple of nonnegative integers encoding the rooted\n tree ``self``.\n\n The first entry of the tuple is the number of children of the\n root. Then the rest of the tuple is obtained as follows: List\n the tuples corresponding to all children (we are regarding the\n children themselves as trees). Order this list (not the\n tuples!) in lexicographically increasing order, and flatten\n it into a single tuple.\n\n This tuple characterizes the rooted tree uniquely, and can be\n used to sort the rooted trees.\n\n .. NOTE::\n\n The tree ``self`` must be normalized before calling this\n method (see :meth:`normalize`). This doesn't matter\n unless you are inside the :meth:`clone` context manager,\n because outside of it every rooted tree is already\n normalized.\n\n .. NOTE::\n\n By default, this method does not encode any extra\n structure that ``self`` might have. If you have a subclass\n inheriting from :class:`RootedTree` which allows for some\n extra structure, you need to override :meth:`sort_key` in\n order to preserve this structure (for example, the\n :class:`LabelledRootedTree` class does this in\n :meth:`LabelledRootedTree.sort_key`). See the note in the\n docstring of\n :meth:`sage.combinat.ordered_tree.OrderedTree.sort_key`\n for a pitfall.\n\n EXAMPLES::\n\n sage: RT = RootedTree\n sage: RT([[],[[]]]).sort_key()\n (2, 0, 1, 0)\n sage: RT([[[]],[]]).sort_key()\n (2, 0, 1, 0)\n " l = len(self) if (l == 0): return (0,) resu = ([l] + [u for t in self for u in t.sort_key()]) return tuple(resu) def __hash__(self): '\n Return a hash for ``self``.\n\n This is based on :meth:`sort_key`.\n\n EXAMPLES::\n\n sage: RT = RootedTree\n sage: hash(RT([[],[[]]])) == hash((2, 0, 1, 0)) # indirect doctest\n True\n ' return hash(self.sort_key()) def normalize(self): '\n Normalize ``self``.\n\n This function is at the core of the implementation of rooted\n (unordered) trees. The underlying structure is provided by\n ordered rooted trees. Every rooted tree is represented by a\n normalized element in the set of its planar embeddings.\n\n There should be no need to call ``normalize`` directly as it\n is called automatically upon creation and cloning or\n modification (by ``NormalizedClonableList``).\n\n The normalization has a recursive definition. It means first\n that every sub-tree is itself normalized, and also that\n sub-trees are sorted. Here the sort is performed according to\n the values of the :meth:`sort_key` method.\n\n EXAMPLES::\n\n sage: RT = RootedTree\n sage: RT([[],[[]]]) == RT([[[]],[]]) # indirect doctest\n True\n sage: rt1 = RT([[],[[]]])\n sage: rt2 = RT([[[]],[]])\n sage: rt1 is rt2\n False\n sage: rt1 == rt2\n True\n sage: rt1._get_list() == rt2._get_list()\n True\n ' self._require_mutable() for st in self: assert st.is_immutable(), 'Subtree {} is not normalized'.format(st) self._get_list().sort(key=(lambda t: t.sort_key())) self.set_immutable() def is_empty(self): '\n Return if ``self`` is the empty tree.\n\n For rooted trees, this always returns ``False``.\n\n .. NOTE::\n\n This is not the same as ``bool(t)``, which returns whether\n ``t`` has some child or not.\n\n EXAMPLES::\n\n sage: t = RootedTrees(4)([[],[[]]])\n sage: t.is_empty()\n False\n sage: bool(t)\n True\n sage: t = RootedTrees(1)([])\n sage: t.is_empty()\n False\n sage: bool(t)\n False\n ' return False def graft_list(self, other): '\n Return the list of trees obtained by grafting ``other`` on ``self``.\n\n Here grafting means that one takes the disjoint union of\n ``self`` and ``other``, chooses a node of ``self``,\n and adds the root of ``other`` to the list of children of\n this node. The root of the resulting tree is the root of\n ``self``. (This can be done for each node of ``self``;\n this method returns the list of all results.)\n\n This is useful for free pre-Lie algebras.\n\n EXAMPLES::\n\n sage: RT = RootedTree\n sage: x = RT([])\n sage: y = RT([x, x])\n sage: x.graft_list(x)\n [[[]]]\n sage: l = y.graft_list(x); l\n [[[], [], []], [[], [[]]], [[], [[]]]]\n sage: [parent(i) for i in l]\n [Rooted trees, Rooted trees, Rooted trees]\n\n TESTS::\n\n sage: x = RootedTrees(1)([])\n sage: y = RootedTrees(3)([x, x])\n sage: l = y.graft_list(x); l\n [[[], [], []], [[], [[]]], [[], [[]]]]\n sage: [parent(i) for i in l]\n [Rooted trees, Rooted trees, Rooted trees]\n\n sage: x = RootedTree([[[], []], []])\n sage: y = RootedTree([[], []])\n sage: len(set(x.graft_list(y)))\n 4\n ' resu = [] with self.clone() as t: t.append(other) resu += [t] for (i, sub) in enumerate(self): for new_sub in sub.graft_list(other): with self.clone() as t: t[i] = new_sub resu += [t] return resu def graft_on_root(self, other): '\n Return the tree obtained by grafting ``other`` on the root of ``self``.\n\n Here grafting means that one takes the disjoint union of\n ``self`` and ``other``, and adds the root of ``other`` to\n the list of children of ``self``. The root of the resulting\n tree is the root of ``self``.\n\n This is useful for free Nap algebras.\n\n EXAMPLES::\n\n sage: RT = RootedTree\n sage: x = RT([])\n sage: y = RT([x, x])\n sage: x.graft_on_root(x)\n [[]]\n sage: y.graft_on_root(x)\n [[], [], []]\n sage: x.graft_on_root(y)\n [[[], []]]\n ' with self.clone() as t: t.append(other) return t def single_graft(self, x, grafting_function, path_prefix=()): "\n Graft subtrees of `x` on ``self`` using the given function.\n\n Let `x_1, x_2, \\ldots, x_p` be the children of the root of\n `x`. For each `i`, the subtree of `x` comprising all\n descendants of `x_i` is joined by a new edge to\n the vertex of ``self`` specified by the `i`-th path in the\n grafting function (i.e., by the path\n ``grafting_function[i]``).\n\n The number of vertices of the result is the sum of the numbers\n of vertices of ``self`` and `x` minus one, because the root of\n `x` is not used.\n\n This is used to define the product of the Grossman-Larson algebras.\n\n INPUT:\n\n - `x` -- a rooted tree\n\n - ``grafting_function`` -- a list of paths in ``self``\n\n - ``path_prefix`` -- optional tuple (default ``()``)\n\n The ``path_prefix`` argument is only used for internal recursion.\n\n EXAMPLES::\n\n sage: LT = LabelledRootedTrees()\n sage: y = LT([LT([],label='b')], label='a')\n sage: x = LT([LT([],label='d')], label='c')\n sage: y.single_graft(x,[(0,)])\n a[b[d[]]]\n sage: t = LT([LT([],label='b'),LT([],label='c')], label='a')\n sage: s = LT([LT([],label='d'),LT([],label='e')], label='f')\n sage: t.single_graft(s,[(0,),(1,)])\n a[b[d[]], c[e[]]]\n " P = self.parent() child_grafts = [suby.single_graft(x, grafting_function, (path_prefix + (i,))) for (i, suby) in enumerate(self)] try: y1 = P(child_grafts, label=self.label()) except AttributeError: y1 = P(child_grafts) with y1.clone() as y2: for k in range(len(x)): if (grafting_function[k] == path_prefix): y2.append(x[k]) return y2
class RootedTrees(UniqueRepresentation, Parent): '\n Factory class for rooted trees.\n\n INPUT:\n\n - ``size`` -- (optional) an integer\n\n OUTPUT:\n\n the set of all rooted trees (of the given size ``size`` if\n specified)\n\n EXAMPLES::\n\n sage: RootedTrees()\n Rooted trees\n\n sage: RootedTrees(2)\n Rooted trees with 2 nodes\n ' @staticmethod def __classcall_private__(cls, n=None): '\n TESTS::\n\n sage: from sage.combinat.rooted_tree import (RootedTrees_all,\n ....: RootedTrees_size)\n sage: RootedTrees(2) is RootedTrees_size(2)\n True\n sage: RootedTrees(5).cardinality()\n 9\n sage: RootedTrees() is RootedTrees_all()\n True\n\n TESTS::\n\n sage: RootedTrees(0)\n Traceback (most recent call last):\n ...\n ValueError: n must be a positive integer\n ' if (n is None): return RootedTrees_all() if ((n not in ZZ) or (n < 1)): raise ValueError('n must be a positive integer') return RootedTrees_size(Integer(n))
class RootedTrees_all(DisjointUnionEnumeratedSets, RootedTrees): '\n Class of all (unordered, unlabelled) rooted trees.\n\n See :class:`RootedTree` for a definition.\n ' def __init__(self): '\n TESTS::\n\n sage: sum(x**len(t) # needs sage.symbolic\n ....: for t in set(RootedTree(t) for t in OrderedTrees(6)))\n x^5 + x^4 + 3*x^3 + 6*x^2 + 9*x\n sage: sum(x**len(t) for t in RootedTrees(6)) # needs sage.symbolic\n x^5 + x^4 + 3*x^3 + 6*x^2 + 9*x\n\n sage: TestSuite(RootedTrees()).run() # long time\n ' DisjointUnionEnumeratedSets.__init__(self, Family(NonNegativeIntegers(), RootedTrees_size), facade=True, keepkey=False) def _repr_(self): '\n TESTS::\n\n sage: RootedTrees()\n Rooted trees\n ' return 'Rooted trees' def __contains__(self, x): '\n TESTS::\n\n sage: S = RootedTrees()\n sage: 1 in S\n False\n sage: S([]) in S\n True\n ' return isinstance(x, self.element_class) def unlabelled_trees(self): '\n Return the set of unlabelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: RootedTrees().unlabelled_trees()\n Rooted trees\n ' return self def labelled_trees(self): "\n Return the set of labelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: RootedTrees().labelled_trees()\n Labelled rooted trees\n\n As a consequence::\n\n sage: lb = RootedTrees()([[],[[], []]]).canonical_labelling()\n sage: lb\n 1[2[], 3[4[], 5[]]]\n sage: lb.__class__\n <class 'sage.combinat.rooted_tree.LabelledRootedTrees_all_with_category.element_class'>\n sage: lb.parent()\n Labelled rooted trees\n " return LabelledRootedTrees() def _element_constructor_(self, *args, **keywords): '\n EXAMPLES::\n\n sage: B = RootedTrees()\n sage: B._element_constructor_([])\n []\n sage: B([[],[]]) # indirect doctest\n [[], []]\n ' return self.element_class(self, *args, **keywords) @cached_method def leaf(self): '\n Return a leaf tree with ``self`` as parent.\n\n EXAMPLES::\n\n sage: RootedTrees().leaf()\n []\n ' return self([]) Element = RootedTree
class RootedTrees_size(RootedTrees): '\n The enumerated set of rooted trees with a given number of nodes.\n\n The number of nodes of a rooted tree is defined recursively:\n The number of nodes of a rooted tree with `a` children is `a`\n plus the sum of the number of nodes of each of these children.\n\n TESTS::\n\n sage: from sage.combinat.rooted_tree import RootedTrees_size\n sage: for i in range(1, 6): TestSuite(RootedTrees_size(i)).run() # needs sage.combinat\n ' def __init__(self, n): '\n TESTS::\n\n sage: for i in range(1, 6): # needs sage.combinat\n ....: TestSuite(RootedTrees(i)).run()\n ' super().__init__(category=FiniteEnumeratedSets()) self._n = n def _repr_(self): '\n TESTS::\n\n sage: RootedTrees(4) # indirect doctest\n Rooted trees with 4 nodes\n ' return 'Rooted trees with {} nodes'.format(self._n) def __contains__(self, x): '\n TESTS::\n\n sage: S = RootedTrees(3)\n sage: 1 in S\n False\n sage: S([[],[]]) in S\n True\n ' return (isinstance(x, self.element_class) and (x.node_number() == self._n)) def _an_element_(self): '\n TESTS::\n\n sage: RootedTrees(4).an_element() # indirect doctest # needs sage.combinat\n [[[[]]]]\n ' return self.first() def __iter__(self): '\n An iterator for ``self``.\n\n This generates the rooted trees of given size. The algorithm\n first picks a partition for the sizes of subtrees, then picks\n appropriate tuples of smaller trees.\n\n EXAMPLES::\n\n sage: from sage.combinat.rooted_tree import *\n sage: RootedTrees(1).list()\n [[]]\n sage: RootedTrees(2).list() # needs sage.combinat\n [[[]]]\n sage: RootedTrees(3).list() # needs sage.combinat\n [[[[]]], [[], []]]\n sage: RootedTrees(4).list() # needs sage.combinat\n [[[[[]]]], [[[], []]], [[], [[]]], [[], [], []]]\n ' if (self._n == 1): (yield self._element_constructor_([])) return from sage.combinat.partition import Partitions from itertools import combinations_with_replacement, product for part in Partitions((self._n - 1)): mults = part.to_exp_dict() choices = [] for (p, mp) in mults.items(): lp = self.__class__(p).list() new_choice = [list(z) for z in combinations_with_replacement(lp, mp)] choices.append(new_choice) for c in product(*choices): (yield self.element_class(self._parent_for, sum(c, []))) def check_element(self, el, check=True): '\n Check that a given tree actually belongs to ``self``.\n\n This just checks the number of vertices.\n\n EXAMPLES::\n\n sage: RT3 = RootedTrees(3)\n sage: RT3([[],[]]) # indirect doctest\n [[], []]\n sage: RT3([[],[],[]]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: wrong number of nodes\n ' if (el.node_number() != self._n): raise ValueError('wrong number of nodes') def cardinality(self): '\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: RootedTrees(1).cardinality()\n 1\n sage: RootedTrees(3).cardinality()\n 2\n ' return number_of_rooted_trees(self._n) @lazy_attribute def _parent_for(self): '\n The parent of the elements generated by ``self``.\n\n TESTS::\n\n sage: S = RootedTrees(3)\n sage: S._parent_for\n Rooted trees\n ' return RootedTrees_all() @lazy_attribute def element_class(self): "\n TESTS::\n\n sage: S = RootedTrees(3)\n sage: S.element_class\n <class 'sage.combinat.rooted_tree.RootedTrees_all_with_category.element_class'>\n sage: S.first().__class__ == RootedTrees().first().__class__ # needs sage.combinat\n True\n " return self._parent_for.element_class def _element_constructor_(self, *args, **keywords): '\n EXAMPLES::\n\n sage: S = RootedTrees(2)\n sage: S([]) # indirect doctest\n Traceback (most recent call last):\n ...\n ValueError: wrong number of nodes\n sage: S([[]]) # indirect doctest\n [[]]\n\n sage: S = RootedTrees(1) # indirect doctest\n sage: S([])\n []\n ' res = self.element_class(self._parent_for, *args, **keywords) if (res.node_number() != self._n): raise ValueError('wrong number of nodes') return res
class LabelledRootedTree(AbstractLabelledClonableTree, RootedTree): '\n Labelled rooted trees.\n\n A labelled rooted tree is a rooted tree with a label\n attached at each node.\n\n More formally:\n The *labelled rooted trees* are an inductive datatype defined\n as follows: A labelled rooted tree is a multiset of labelled\n rooted trees, endowed with a label (which can be any object,\n including ``None``). The trees that belong to this multiset\n are said to be the *children* of the tree. (Notice that the\n labels of these children may and may not be of the same type\n as the label of the tree). A labelled rooted tree which has\n no children (so the only information it carries is its label)\n is said to be a *leaf*.\n\n Every labelled rooted tree gives rise to an unlabelled rooted\n tree (:class:`RootedTree`) by forgetting the labels. (This is\n implemented as a conversion.)\n\n INPUT:\n\n - ``children`` -- a list or tuple or more generally any iterable\n of trees or objects convertible to trees\n\n - ``label`` -- any hashable Sage object (default is ``None``)\n\n EXAMPLES::\n\n sage: x = LabelledRootedTree([], label = 3); x\n 3[]\n sage: LabelledRootedTree([x, x, x], label = 2)\n 2[3[], 3[], 3[]]\n sage: LabelledRootedTree((x, x, x), label = 2)\n 2[3[], 3[], 3[]]\n sage: LabelledRootedTree([[],[[], []]], label = 3)\n 3[None[], None[None[], None[]]]\n\n Children are reordered using the value of the :meth:`sort_key` method::\n\n sage: y = LabelledRootedTree([], label = 5); y\n 5[]\n sage: xyy2 = LabelledRootedTree((x, y, y), label = 2); xyy2\n 2[3[], 5[], 5[]]\n sage: yxy2 = LabelledRootedTree((y, x, y), label = 2); yxy2\n 2[3[], 5[], 5[]]\n sage: xyy2 == yxy2\n True\n\n Converting labelled into unlabelled rooted trees by\n forgetting the labels, and back (the labels are\n initialized as ``None``)::\n\n sage: yxy2crude = RootedTree(yxy2); yxy2crude\n [[], [], []]\n sage: LabelledRootedTree(yxy2crude)\n None[None[], None[], None[]]\n\n TESTS::\n\n sage: xyy2._get_list() == yxy2._get_list()\n True\n ' @staticmethod def __classcall_private__(cls, *args, **opts): "\n Ensure that trees created by the sets and directly are the same and\n that they are instances of :class:`LabelledRootedTree`.\n\n TESTS::\n\n sage: issubclass(LabelledRootedTrees().element_class, LabelledRootedTree)\n True\n sage: t0 = LabelledRootedTree([[],[[], []]], label = 3)\n sage: t0.parent()\n Labelled rooted trees\n sage: type(t0)\n <class 'sage.combinat.rooted_tree.LabelledRootedTrees_all_with_category.element_class'>\n " return cls._auto_parent.element_class(cls._auto_parent, *args, **opts) @lazy_class_attribute def _auto_parent(cls): '\n The automatic parent of the element of this class.\n\n When calling the constructor of an element of this class, one needs a\n parent. This class attribute specifies which parent is used.\n\n EXAMPLES::\n\n sage: LabelledRootedTree._auto_parent\n Labelled rooted trees\n sage: LabelledRootedTree([], label = 3).parent()\n Labelled rooted trees\n ' return LabelledRootedTrees() def sort_key(self): "\n Return a tuple of nonnegative integers encoding the labelled\n rooted tree ``self``.\n\n The first entry of the tuple is a pair consisting of the\n number of children of the root and the label of the root. Then\n the rest of the tuple is obtained as follows: List\n the tuples corresponding to all children (we are regarding the\n children themselves as trees). Order this list (not the\n tuples!) in lexicographically increasing order, and flatten\n it into a single tuple.\n\n This tuple characterizes the labelled rooted tree uniquely, and\n can be used to sort the labelled rooted trees provided that the\n labels belong to a type which is totally ordered.\n\n .. NOTE::\n\n The tree ``self`` must be normalized before calling this\n method (see :meth:`normalize`). This doesn't matter\n unless you are inside the :meth:`clone` context manager,\n because outside of it every rooted tree is already\n normalized.\n\n .. NOTE::\n\n This method overrides :meth:`RootedTree.sort_key`\n and returns a result different from what the latter\n would return, as it wants to encode the whole labelled\n tree including its labelling rather than just the\n unlabelled tree. Therefore, be careful with using this\n method on subclasses of :class:`RootedOrderedTree`;\n under some circumstances they could inherit it from\n another superclass instead of from :class:`RootedTree`,\n which would cause the method to forget the labelling.\n See the docstrings of :meth:`RootedTree.sort_key` and\n :meth:`sage.combinat.ordered_tree.OrderedTree.sort_key`.\n\n EXAMPLES::\n\n sage: LRT = LabelledRootedTrees(); LRT\n Labelled rooted trees\n sage: x = LRT([], label = 3); x\n 3[]\n sage: x.sort_key()\n ((0, 3),)\n sage: y = LRT([x, x, x], label = 2); y\n 2[3[], 3[], 3[]]\n sage: y.sort_key()\n ((3, 2), (0, 3), (0, 3), (0, 3))\n sage: LRT.an_element().sort_key()\n ((3, 'alpha'), (0, 3), (1, 5), (0, None), (2, 42), (0, 3), (0, 3))\n sage: lb = RootedTrees()([[],[[], []]]).canonical_labelling()\n sage: lb.sort_key()\n ((2, 1), (0, 2), (2, 3), (0, 4), (0, 5))\n " l = len(self) if (l == 0): return ((0, self.label()),) resu = ([(l, self.label())] + [u for t in self for u in t.sort_key()]) return tuple(resu) def __hash__(self): '\n Return a hash for ``self``.\n\n EXAMPLES::\n\n sage: lb = RootedTrees()([[],[[], []]]).canonical_labelling()\n sage: hash(lb) == hash(((2, 1), (0, 2), (2, 3), (0, 4), (0, 5))) # indirect doctest\n True\n ' return hash(self.sort_key()) _UnLabelled = RootedTree
class LabelledRootedTrees(UniqueRepresentation, Parent): '\n This is a parent stub to serve as a factory class for labelled\n rooted trees.\n\n EXAMPLES::\n\n sage: LRT = LabelledRootedTrees(); LRT\n Labelled rooted trees\n sage: x = LRT([], label = 3); x\n 3[]\n sage: x.parent() is LRT\n True\n sage: y = LRT([x, x, x], label = 2); y\n 2[3[], 3[], 3[]]\n sage: y.parent() is LRT\n True\n\n .. TODO::\n\n Add the possibility to restrict the labels to a fixed set.\n ' @staticmethod def __classcall_private__(cls, n=None): '\n TESTS::\n\n sage: from sage.combinat.rooted_tree import LabelledRootedTrees_all\n sage: LabelledRootedTrees_all() == LabelledRootedTrees()\n True\n ' return LabelledRootedTrees_all()
class LabelledRootedTrees_all(LabelledRootedTrees): '\n Class of all (unordered) labelled rooted trees.\n\n See :class:`LabelledRootedTree` for a definition.\n ' def __init__(self, category=None): '\n TESTS::\n\n sage: TestSuite(LabelledRootedTrees()).run()\n ' if (category is None): category = Sets() category = category.Infinite() Parent.__init__(self, category=category) def _repr_(self): '\n Return the string representation of ``self``.\n\n TESTS::\n\n sage: LabelledRootedTrees()\n Labelled rooted trees\n ' return 'Labelled rooted trees' def _an_element_(self): '\n Return a labelled tree.\n\n EXAMPLES::\n\n sage: LabelledRootedTrees().an_element() # indirect doctest\n alpha[3[], 5[None[]], 42[3[], 3[]]]\n ' LT = self._element_constructor_ t = LT([], label=3) t1 = LT([t, t], label=42) t2 = LT([[]], label=5) return LT([t, t1, t2], label='alpha') def unlabelled_trees(self): '\n Return the set of unlabelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: LabelledRootedTrees().unlabelled_trees()\n Rooted trees\n ' return RootedTrees_all() def labelled_trees(self): '\n Return the set of labelled trees associated to ``self``.\n\n EXAMPLES::\n\n sage: LabelledRootedTrees().labelled_trees()\n Labelled rooted trees\n ' return self Element = LabelledRootedTree
class Rule(UniqueRepresentation): '\n Generic base class for an insertion rule for an RSK-type correspondence.\n\n An instance of this class should implement a method\n :meth:`insertion` (which can be applied to a letter ``j``\n and a list ``r``, and modifies ``r`` in place by "bumping"\n ``j`` into it appropriately; it then returns the bumped-out\n entry or ``None`` if no such entry exists) and a method\n :meth:`reverse_insertion` (which does the same but for reverse\n bumping).\n It may also implement :meth:`_backward_format_output` and\n :meth:`_forward_format_output` if the RSK correspondence should\n return something other than (semi)standard tableaux (in the\n forward direction) and matrices or biwords (in the backward\n direction).\n The :meth:`to_pairs` method should also be overridden if\n the input for the (forward) RSK correspondence is not the\n usual kind of biwords (i.e., pairs of two `n`-tuples\n `[a_1, a_2, \\ldots, a_n]` and `[b_1, b_2, \\ldots, b_n]`\n satisfying `(a_1, b_1) \\leq (a_2, b_2) \\leq \\cdots\n \\leq (a_n, b_n)` in lexicographic order).\n Finally, it :meth:`forward_rule` and :meth:`backward_rule`\n have to be overridden if the overall structure of the\n RSK correspondence differs from that of classical RSK (see,\n e.g., the case of Hecke insertion, in which a letter bumped\n into a row may change a different row).\n ' def to_pairs(self, obj1=None, obj2=None, check=True): '\n Given a valid input for the RSK algorithm, such as\n two `n`-tuples ``obj1`` `= [a_1, a_2, \\ldots, a_n]`\n and ``obj2`` `= [b_1, b_2, \\ldots, b_n]` forming a biword\n (i.e., satisfying\n `a_1 \\leq a_2 \\leq \\cdots \\leq a_n`, and if\n `a_i = a_{i+1}`, then `b_i \\leq b_{i+1}`),\n or a matrix ("generalized permutation"), or a single word,\n return the array\n `[(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)]`.\n\n INPUT:\n\n - ``obj1, obj2`` -- anything representing a biword\n (see the doc of :meth:`forward_rule` for the\n encodings accepted).\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n biword.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import Rule\n sage: list(Rule().to_pairs([1, 2, 2, 2], [2, 1, 1, 2]))\n [(1, 2), (2, 1), (2, 1), (2, 2)]\n sage: m = Matrix(ZZ, 3, 2, [0,1,1,0,0,2]) ; m\n [0 1]\n [1 0]\n [0 2]\n sage: list(Rule().to_pairs(m))\n [(1, 2), (2, 1), (3, 2), (3, 2)]\n ' if (obj2 is None): try: itr = obj1._rsk_iter() except AttributeError: try: t = [] b = [] for (i, row) in enumerate(obj1): for (j, mult) in enumerate(row): if (mult > 0): t.extend(([(i + 1)] * mult)) b.extend(([(j + 1)] * mult)) itr = zip(t, b) except TypeError: itr = zip(range(1, (len(obj1) + 1)), obj1) else: if check: if (len(obj1) != len(obj2)): raise ValueError('the two arrays must be the same length') lt = 0 lb = 0 for (t, b) in zip(obj1, obj2): if ((t < lt) or ((t == lt) and (b < lb))): raise ValueError('invalid generalized permutation') lt = t lb = b itr = zip(obj1, obj2) return itr def forward_rule(self, obj1, obj2, check_standard=False, check=True): '\n Return a pair of tableaux obtained by applying forward\n insertion to the generalized permutation ``[obj1, obj2]``.\n\n INPUT:\n\n - ``obj1, obj2`` -- can be one of the following ways to\n represent a generalized permutation (or, equivalently,\n biword):\n\n - two lists ``obj1`` and ``obj2`` of equal length,\n to be interpreted as the top row and the bottom row of\n the biword\n\n - a matrix ``obj1`` of nonnegative integers, to be\n interpreted as the generalized permutation in matrix\n form (in this case, ``obj2`` is ``None``)\n\n - a word ``obj1`` in an ordered alphabet, to be\n interpreted as the bottom row of the biword (in this\n case, ``obj2`` is ``None``; the top row of the biword\n is understood to be `(1, 2, \\ldots, n)` by default)\n\n - any object ``obj1`` which has a method ``_rsk_iter()``,\n as long as this method returns an iterator yielding\n pairs of numbers, which then are interperted as top\n entries and bottom entries in the biword (in this case,\n ``obj2`` is ``None``)\n\n - ``check_standard`` -- (default: ``False``) check if either of the\n resulting tableaux is a standard tableau, and if so, typecast it\n as such\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n biword\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: RuleRSK().forward_rule([3,3,2,4,1], None)\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n sage: RuleRSK().forward_rule([1, 1, 1, 3, 7], None)\n [[[1, 1, 1, 3, 7]], [[1, 2, 3, 4, 5]]]\n sage: RuleRSK().forward_rule([7, 6, 3, 3, 1], None)\n [[[1, 3], [3], [6], [7]], [[1, 4], [2], [3], [5]]]\n ' itr = self.to_pairs(obj1, obj2, check=check) p = [] q = [] for (i, j) in itr: for (r, qr) in zip(p, q): j1 = self.insertion(j, r) if (j1 is None): r.append(j) qr.append(i) break else: j = j1 else: p.append([j]) q.append([i]) return self._forward_format_output(p, q, check_standard=check_standard) def backward_rule(self, p, q, output): "\n Return the generalized permutation obtained by applying reverse\n insertion to a pair of tableaux ``(p, q)``.\n\n INPUT:\n\n - ``p``, ``q`` -- two tableaux of the same shape.\n\n - ``output`` -- (default: ``'array'``) if ``q`` is semi-standard:\n\n - ``'array'`` -- as a two-line array (i.e. generalized permutation\n or biword)\n - ``'matrix'`` -- as an integer matrix\n\n and if ``q`` is standard, we can also have the output:\n\n - ``'word'`` -- as a word\n\n and additionally if ``p`` is standard, we can also have the output:\n\n - ``'permutation'`` -- as a permutation\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: t1 = Tableau([[1, 3, 4], [2], [3]])\n sage: t2 = Tableau([[1, 2, 4], [3], [5]])\n sage: RuleRSK().backward_rule(t1, t2, 'array')\n [[1, 2, 3, 4, 5], [3, 3, 2, 4, 1]]\n sage: t1 = Tableau([[1, 1, 1, 3, 7]])\n sage: t2 = Tableau([[1, 2, 3, 4, 5]])\n sage: RuleRSK().backward_rule(t1, t2, 'array')\n [[1, 2, 3, 4, 5], [1, 1, 1, 3, 7]]\n sage: t1 = Tableau([[1, 3], [3], [6], [7]])\n sage: t2 = Tableau([[1, 4], [2], [3], [5]])\n sage: RuleRSK().backward_rule(t1, t2, 'array')\n [[1, 2, 3, 4, 5], [7, 6, 3, 3, 1]]\n " from sage.combinat.tableau import SemistandardTableaux p_copy = [list(row) for row in p] if q.is_standard(): rev_word = [] d = {qij: i for (i, Li) in enumerate(q) for qij in Li} for key in sorted(d, reverse=True): i = d[key] x = p_copy[i].pop() for row in reversed(p_copy[:i]): x = self.reverse_insertion(x, row) rev_word.append(x) return self._backward_format_output(rev_word, None, output, p.is_standard(), True) if (q not in SemistandardTableaux()): raise ValueError(('q(=%s) must be a semistandard tableau' % q)) upper_row = [] lower_row = [] d = {} for (row, Li) in enumerate(q): for (col, val) in enumerate(Li): if (val in d): d[val][col] = row else: d[val] = {col: row} for (value, row_dict) in sorted(d.items(), reverse=True, key=(lambda x: x[0])): for key in sorted(row_dict, reverse=True): i = row_dict[key] x = p_copy[i].pop() for row in reversed(p_copy[:i]): x = self.reverse_insertion(x, row) lower_row.append(x) upper_row.append(value) return self._backward_format_output(lower_row, upper_row, output, p.is_standard(), False) def _forward_format_output(self, p, q, check_standard): '\n Return final output of the ``RSK`` correspondence from the\n output of the corresponding ``forward_rule``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: isinstance(RuleRSK()._forward_format_output([[1, 2, 3, 4, 5]],\n ....: [[1, 2, 3, 4, 5]], True)[0], StandardTableau)\n True\n sage: isinstance(RuleRSK()._forward_format_output([[1, 2, 3, 4, 5]],\n ....: [[1, 2, 3, 4, 5]], False)[0], SemistandardTableau)\n True\n sage: isinstance(RuleRSK()._forward_format_output([[1, 1, 1, 3, 7]],\n ....: [[1, 2, 3, 4, 5]], True)[0], SemistandardTableau)\n True\n ' from sage.combinat.tableau import SemistandardTableau, StandardTableau if check_standard: try: P = StandardTableau(p) except ValueError: P = SemistandardTableau(p) try: Q = StandardTableau(q) except ValueError: Q = SemistandardTableau(q) return [P, Q] return [SemistandardTableau(p), SemistandardTableau(q)] def _backward_format_output(self, lower_row, upper_row, output, p_is_standard, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None, 'array', False, True)\n [[1, 2, 3, 4], [4, 3, 2, 1]]\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None, 'matrix', False, True)\n [0 0 0 1]\n [0 0 1 0]\n [0 1 0 0]\n [1 0 0 0]\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None, 'word', False, True)\n word: 4321\n sage: RuleRSK()._backward_format_output([3, 2, 1, 1], [2, 1, 1, 1], 'array', False, False)\n [[1, 1, 1, 2], [1, 1, 2, 3]]\n sage: RuleRSK()._backward_format_output([3, 2, 1, 1], [2, 1, 1, 1], 'matrix', False, False)\n [2 1 0]\n [0 0 1]\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None, 'word', False, False)\n Traceback (most recent call last):\n ...\n TypeError: q must be standard to have a word as valid output\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None, 'random_type', False, False)\n Traceback (most recent call last):\n ...\n ValueError: invalid output option\n " if q_is_standard: if (output == 'word'): from sage.combinat.words.word import Word return Word(reversed(lower_row)) if (output == 'matrix'): return to_matrix(list(range(1, (len(lower_row) + 1))), list(reversed(lower_row))) if (output == 'array'): return [list(range(1, (len(lower_row) + 1))), list(reversed(lower_row))] raise ValueError('invalid output option') else: if (output == 'matrix'): return to_matrix(list(reversed(upper_row)), list(reversed(lower_row))) if (output == 'array'): return [list(reversed(upper_row)), list(reversed(lower_row))] if (output in ['permutation', 'word']): raise TypeError(('q must be standard to have a %s as valid output' % output)) raise ValueError('invalid output option')
class RuleRSK(Rule): '\n Rule for the classical Robinson-Schensted-Knuth insertion.\n\n See :func:`RSK` for the definition of this operation.\n\n EXAMPLES::\n\n sage: RSK([1, 2, 2, 2], [2, 1, 1, 2], insertion=RSK.rules.RSK)\n [[[1, 1, 2], [2]], [[1, 2, 2], [2]]]\n sage: p = Tableau([[1,2,2],[2]]); q = Tableau([[1,3,3],[2]])\n sage: RSK_inverse(p, q, insertion=RSK.rules.RSK)\n [[1, 2, 3, 3], [2, 1, 2, 2]]\n ' def insertion(self, j, r): '\n Insert the letter ``j`` from the second row of the biword\n into the row `r` using classical Schensted insertion,\n if there is bumping to be done.\n\n The row `r` is modified in place if bumping occurs. The bumped-out\n entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: qr, r = [1,2,3,4,5], [3,3,2,4,8]\n sage: j = RuleRSK().insertion(9, r)\n sage: j is None\n True\n sage: qr, r = [1,2,3,4,5], [3,3,2,4,8]\n sage: j = RuleRSK().insertion(3, r)\n sage: j\n 4\n ' if (r[(- 1)] <= j): return None y_pos = bisect_right(r, j) (j, r[y_pos]) = (r[y_pos], j) return j def reverse_insertion(self, x, row): '\n Reverse bump the row ``row`` of the current insertion tableau\n with the number ``x``.\n\n The row ``row`` is modified in place. The bumped-out entry\n is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: r = [2,3,3,4,8]\n sage: x = RuleRSK().reverse_insertion(4, r); r\n [2, 3, 4, 4, 8]\n sage: x\n 3\n ' y_pos = (bisect_left(row, x) - 1) (x, row[y_pos]) = (row[y_pos], x) return x def _backward_format_output(self, lower_row, upper_row, output, p_is_standard, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleRSK\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None,\n ....: 'permutation', True, True)\n [4, 3, 2, 1]\n sage: RuleRSK()._backward_format_output([1, 2, 3, 4], None,\n ....: 'permutation', False, True)\n Traceback (most recent call last):\n ...\n TypeError: p must be standard to have a valid permutation as output\n " if (q_is_standard and (output == 'permutation')): if (not p_is_standard): raise TypeError('p must be standard to have a valid permutation as output') from sage.combinat.permutation import Permutation return Permutation(reversed(lower_row)) return super()._backward_format_output(lower_row, upper_row, output, p_is_standard, q_is_standard)
class RuleEG(Rule): "\n Rule for Edelman-Greene insertion.\n\n For a reduced word of a permutation (i.e., an element of a type `A`\n Coxeter group), one can use Edelman-Greene insertion, an algorithm\n defined in [EG1987]_ Definition 6.20 (where it is referred to as\n Coxeter-Knuth insertion). The Edelman-Greene insertion is similar to the\n standard row insertion except that (using the notations in\n the documentation of :func:`RSK`) if `k_i` and `k_i + 1` both\n exist in row `i`, we *only* set `k_{i+1} = k_i + 1` and continue.\n\n EXAMPLES:\n\n Let us reproduce figure 6.4 in [EG1987]_::\n\n sage: RSK([2,3,2,1,2,3], insertion=RSK.rules.EG)\n [[[1, 2, 3], [2, 3], [3]], [[1, 2, 6], [3, 5], [4]]]\n\n Some more examples::\n\n sage: a = [2, 1, 2, 3, 2]\n sage: pq = RSK(a, insertion=RSK.rules.EG); pq\n [[[1, 2, 3], [2, 3]], [[1, 3, 4], [2, 5]]]\n sage: RSK(RSK_inverse(*pq, insertion=RSK.rules.EG, output='matrix'),\n ....: insertion=RSK.rules.EG)\n [[[1, 2, 3], [2, 3]], [[1, 3, 4], [2, 5]]]\n sage: RSK_inverse(*pq, insertion=RSK.rules.EG)\n [[1, 2, 3, 4, 5], [2, 1, 2, 3, 2]]\n\n The RSK algorithm (:func:`RSK`) built using the Edelman-Greene\n insertion rule ``RuleEG`` is a bijection from reduced words of\n permutations/elements of a type `A` Coxeter group to pairs\n consisting of an increasing tableau and a standard tableau\n of the same shape (see [EG1987]_ Theorem 6.25).\n The inverse of this bijection is obtained using :func:`RSK_inverse`.\n If the optional parameter ``output = 'permutation'`` is set in\n :func:`RSK_inverse`, then the function returns not the\n reduced word itself but the permutation (of smallest possible\n size) whose reduced word it is (although the order of the\n letters is reverse to the usual Sage convention)::\n\n sage: w = RSK_inverse(*pq, insertion=RSK.rules.EG, output='permutation'); w\n [4, 3, 1, 2]\n sage: list(reversed(a)) in w.reduced_words()\n True\n\n TESTS:\n\n Let us check that :func:`RSK_inverse` is the inverse of :func:`RSK`\n on the different types of inputs/outputs for Edelman-Greene.\n First we can check on the reduced words (specifically, those that can\n be obtained using the ``reduced_word()`` method from permutations)::\n\n sage: g = lambda w: RSK_inverse(*RSK(w, insertion=RSK.rules.EG),\n ....: insertion=RSK.rules.EG, output='word')\n sage: all(p.reduced_word() == list(g(p.reduced_word()))\n ....: for n in range(7) for p in Permutations(n))\n True\n\n In case of non-standard tableaux `P, Q`::\n\n sage: RSK_inverse(*RSK([1, 2, 3, 2, 1], insertion='EG'),\n ....: insertion='EG')\n [[1, 2, 3, 4, 5], [1, 2, 3, 2, 1]]\n sage: RSK_inverse(*RSK([1, 1, 1, 2], [1, 2, 3, 4],\n ....: insertion=RSK.rules.EG), insertion=RSK.rules.EG)\n [[1, 1, 1, 2], [1, 2, 3, 4]]\n sage: RSK_inverse(*RSK([1, 2, 3, 3], [2, 1, 2, 2], insertion='EG'),\n ....: insertion='EG')\n [[1, 2, 3, 3], [2, 1, 2, 2]]\n\n Since the column reading of the insertion tableau from\n Edelman-Greene insertion gives one of reduced words for the\n original permutation, we can also check for that::\n\n sage: f = lambda p: [x for row in reversed(p) for x in row]\n sage: g = lambda wd: RSK(wd, insertion=RSK.rules.EG)[0]\n sage: all(p == Permutations(n).from_reduced_word(f(g(wd)))\n ....: for n in range(6) for p in Permutations(n)\n ....: for wd in p.reduced_words())\n True\n " def insertion(self, j, r): '\n Insert the letter ``j`` from the second row of the biword\n into the row `r` using Edelman-Greene insertion,\n if there is bumping to be done.\n\n The row `r` is modified in place if bumping occurs. The bumped-out\n entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleEG\n sage: qr, r = [1,2,3,4,5], [3,3,2,4,8]\n sage: j = RuleEG().insertion(9, r)\n sage: j is None\n True\n sage: qr, r = [1,2,3,4,5], [2,3,4,5,8]\n sage: j = RuleEG().insertion(3, r); r\n [2, 3, 4, 5, 8]\n sage: j\n 4\n sage: qr, r = [1,2,3,4,5], [2,3,5,5,8]\n sage: j = RuleEG().insertion(3, r); r\n [2, 3, 3, 5, 8]\n sage: j\n 5\n ' if (r[(- 1)] <= j): return None y_pos = bisect_right(r, j) if ((r[y_pos] == (j + 1)) and (y_pos > 0) and (j == r[(y_pos - 1)])): j += 1 else: (j, r[y_pos]) = (r[y_pos], j) return j def reverse_insertion(self, x, row): '\n Reverse bump the row ``row`` of the current insertion tableau\n with the number ``x``.\n\n The row ``row`` is modified in place. The bumped-out entry\n is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleEG\n sage: r = [1,1,1,2,3,3]\n sage: x = RuleEG().reverse_insertion(3, r); r\n [1, 1, 1, 2, 3, 3]\n sage: x\n 2\n ' y_pos = (bisect_left(row, x) - 1) if ((row[y_pos] == (x - 1)) and (y_pos < (len(row) - 1)) and (row[(y_pos + 1)] == x)): x -= 1 else: (x, row[y_pos]) = (row[y_pos], x) return x def _backward_format_output(self, lower_row, upper_row, output, p_is_standard, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleEG\n sage: RuleEG()._backward_format_output([1, 2, 3, 4], None,\n ....: 'permutation', True, False)\n Traceback (most recent call last):\n ...\n TypeError: q must be standard to have a permutation as valid output\n " if (q_is_standard and (output == 'permutation')): n = 0 if list(lower_row): n = (max(list(lower_row)) + 1) from sage.combinat.permutation import Permutations return Permutations(n).from_reduced_word(list(lower_row)) else: return super()._backward_format_output(lower_row, upper_row, output, p_is_standard, q_is_standard)
class RuleHecke(Rule): '\n Rule for Hecke insertion.\n\n The Hecke RSK algorithm is similar to the classical RSK algorithm,\n but is defined using the Hecke insertion introduced in in\n [BKSTY06]_ (but using rows instead of columns).\n It is not clear in what generality it works; thus, following\n [BKSTY06]_, we shall assume that our biword `p` has top row\n `(1, 2, \\ldots, n)` (or, at least, has its top row strictly\n increasing).\n\n The Hecke RSK algorithm returns a pair of an increasing tableau\n and a set-valued standard tableau. If\n `p = ((j_0, k_0), (j_1, k_1), \\ldots, (j_{\\ell-1}, k_{\\ell-1}))`,\n then the algorithm recursively constructs pairs\n `(P_0, Q_0), (P_1, Q_1), \\ldots, (P_\\ell, Q_\\ell)` of tableaux.\n The construction of `P_{t+1}` and `Q_{t+1}` from `P_t`, `Q_t`,\n `j_t` and `k_t` proceeds as follows: Set `i = j_t`, `x = k_t`,\n `P = P_t` and `Q = Q_t`. We are going to insert `x` into the\n increasing tableau `P` and update the set-valued "recording\n tableau" `Q` accordingly. As in the classical RSK algorithm, we\n first insert `x` into row `1` of `P`, then into row `2` of the\n resulting tableau, and so on, until the construction terminates.\n The details are different: Suppose we are inserting `x` into\n row `R` of `P`. If (Case 1) there exists an entry `y` in row `R`\n such that `x < y`, then let `y` be the minimal such entry. We\n replace this entry `y` with `x` if the result is still an\n increasing tableau; in either subcase, we then continue\n recursively, inserting `y` into the next row of `P`.\n If, on the other hand, (Case 2) no such `y` exists, then we\n append `x` to the end of `R` if the result is an increasing\n tableau (Subcase 2.1), and otherwise (Subcase 2.2) do nothing.\n Furthermore, in Subcase 2.1, we add the box that we have just\n filled with `x` in `P` to the shape of `Q`, and fill it with\n the one-element set `\\{i\\}`. In Subcase 2.2, we find the\n bottommost box of the column containing the rightmost box of\n row `R`, and add `i` to the entry of `Q` in this box (this\n entry is a set, since `Q` is set-valued). In either\n subcase, we terminate the recursion, and set\n `P_{t+1} = P` and `Q_{t+1} = Q`.\n\n Notice that set-valued tableaux are encoded as tableaux whose\n entries are tuples of positive integers; each such tuple is strictly\n increasing and encodes a set (namely, the set of its entries).\n\n EXAMPLES:\n\n As an example of Hecke insertion, we reproduce\n Example 2.1 in :arxiv:`0801.1319v2`::\n\n sage: w = [5, 4, 1, 3, 4, 2, 5, 1, 2, 1, 4, 2, 4]\n sage: P,Q = RSK(w, insertion=RSK.rules.Hecke); [P,Q]\n [[[1, 2, 4, 5], [2, 4, 5], [3, 5], [4], [5]],\n [[(1,), (4,), (5,), (7,)],\n [(2,), (9,), (11, 13)],\n [(3,), (12,)],\n [(6,)],\n [(8, 10)]]]\n sage: wp = RSK_inverse(P, Q, insertion=RSK.rules.Hecke,\n ....: output=\'list\'); wp\n [5, 4, 1, 3, 4, 2, 5, 1, 2, 1, 4, 2, 4]\n sage: wp == w\n True\n ' def forward_rule(self, obj1, obj2, check_standard=False): '\n Return a pair of tableaux obtained by applying Hecke\n insertion to the generalized permutation ``[obj1, obj2]``.\n\n INPUT:\n\n - ``obj1, obj2`` -- can be one of the following ways to\n represent a generalized permutation (or, equivalently,\n biword):\n\n - two lists ``obj1`` and ``obj2`` of equal length,\n to be interpreted as the top row and the bottom row of\n the biword\n\n - a word ``obj1`` in an ordered alphabet, to be\n interpreted as the bottom row of the biword (in this\n case, ``obj2`` is ``None``; the top row of the biword\n is understood to be `(1, 2, \\ldots, n)` by default)\n\n - ``check_standard`` -- (default: ``False``) check if either of the\n resulting tableaux is a standard tableau, and if so, typecast it\n as such\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleHecke\n sage: p, q = RuleHecke().forward_rule([3,3,2,4,1], None);p\n [[1, 4], [2], [3]]\n sage: q\n [[(1, 2), (4,)], [(3,)], [(5,)]]\n sage: isinstance(p, SemistandardTableau)\n True\n sage: isinstance(q, Tableau)\n True\n ' from sage.combinat.tableau import SemistandardTableau, Tableau if (obj2 is None): obj2 = obj1 obj1 = list(range(1, (len(obj1) + 1))) p = [] q = [] for (i, j) in zip(obj1, obj2): for (ir, r) in enumerate(p): j1 = self.insertion(j, ir, r, p) if (j1 is None): if ((r[(- 1)] < j) and ((ir == 0) or (p[(ir - 1)][len(r)] < j))): r.append(j) q[ir].append((i,)) else: l = (len(r) - 1) while ((ir < len(q)) and (len(q[ir]) > l)): ir += 1 q[(ir - 1)][(- 1)] = (q[(ir - 1)][(- 1)] + (i,)) break else: j = j1 else: p.append([j]) q.append([(i,)]) return [SemistandardTableau(p), Tableau(q)] def backward_rule(self, p, q, output): "\n Return the generalized permutation obtained by applying reverse\n Hecke insertion to a pair of tableaux ``(p, q)``.\n\n INPUT:\n\n - ``p``, ``q`` -- two tableaux of the same shape\n\n - ``output`` -- (default: ``'array'``) if ``q`` is semi-standard:\n\n - ``'array'`` -- as a two-line array (i.e. generalized permutation\n or biword)\n\n and if ``q`` is standard set-valued, we can have the output:\n\n - ``'word'`` -- as a word\n - ``'list'`` -- as a list\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleHecke\n sage: t1 = Tableau([[1, 4], [2], [3]])\n sage: t2 = Tableau([[(1, 2), (4,)], [(3,)], [(5,)]])\n sage: RuleHecke().backward_rule(t1, t2, 'array')\n [[1, 2, 3, 4, 5], [3, 3, 2, 4, 1]]\n sage: t1 = Tableau([[1, 4], [2, 3]])\n sage: t2 = Tableau([[(1, 2), (4,)], [(3,)], [(5,)]])\n sage: RuleHecke().backward_rule(t1, t2, 'array')\n Traceback (most recent call last):\n ...\n ValueError: p(=[[1, 4], [2, 3]]) and\n q(=[[(1, 2), (4,)], [(3,)], [(5,)]]) must have the same shape\n " if (p.shape() != q.shape()): raise ValueError(('p(=%s) and q(=%s) must have the same shape' % (p, q))) from sage.combinat.tableau import SemistandardTableaux if (p not in SemistandardTableaux()): raise ValueError(('p(=%s) must be a semistandard tableau' % p)) p_copy = [list(row) for row in p] q_copy = [[list(v) for v in row] for row in q] upper_row = [] lower_row = [] d = {} for (ri, row) in enumerate(q): for (ci, entry) in enumerate(row): for val in entry: if (val in d): d[val][ci] = ri else: d[val] = {ci: ri} for (value, row_dict) in sorted(d.items(), key=(lambda x: (- x[0]))): for i in sorted(row_dict.values(), reverse=True): should_be_value = q_copy[i][(- 1)].pop() assert (value == should_be_value) if (not q_copy[i][(- 1)]): q_copy[i].pop() x = p_copy[i].pop() else: x = p_copy[i][(- 1)] while (i > 0): i -= 1 row = p_copy[i] x = self.reverse_insertion(i, x, row, p_copy) lower_row.append(x) upper_row.append(value) return self._backward_format_output(lower_row, upper_row, output, False, False) def insertion(self, j, ir, r, p): '\n Insert the letter ``j`` from the second row of the biword\n into the row `r` of the increasing tableau `p` using\n Hecke insertion, provided that `r` is the `ir`-th row\n of `p`, and provided that there is bumping to be done.\n\n The row `r` is modified in place if bumping occurs. The bumped-out\n entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleHecke\n sage: from bisect import bisect_right\n sage: p, q, r = [], [], [3,3,8,8,8,9]\n sage: j, ir = 8, 1\n sage: j1 = RuleHecke().insertion(j, ir, r, p)\n sage: j1 == r[bisect_right(r, j)]\n True\n ' if (r[(- 1)] <= j): return None y_pos = bisect_right(r, j) y = r[y_pos] if (((y_pos == 0) or (r[(y_pos - 1)] < j)) and ((ir == 0) or (p[(ir - 1)][y_pos] < j))): r[y_pos] = j j = y return j def reverse_insertion(self, i, x, row, p): '\n Reverse bump the row ``row`` of the current insertion tableau\n ``p`` with the number ``x``, provided that ``row`` is the\n `i`-th row of `p`.\n\n The row ``row`` is modified in place. The bumped-out entry\n is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleHecke\n sage: from bisect import bisect_left\n sage: r = [2,3,3,4,8,9]\n sage: x, i, p = 9, 1, [1, 2]\n sage: x1 = RuleHecke().reverse_insertion(i, x, r, p)\n sage: x1 == r[bisect_left(r,x) - 1]\n True\n ' y_pos = (bisect_left(row, x) - 1) y = row[y_pos] if (((y_pos == (len(row) - 1)) or (x < row[(y_pos + 1)])) and ((i == (len(p) - 1)) or (len(p[(i + 1)]) <= y_pos) or (x < p[(i + 1)][y_pos]))): row[y_pos] = x x = y return x def _backward_format_output(self, lower_row, upper_row, output, p_is_standard, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleHecke\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [1, 2, 3, 4],\n ....: 'array', False, False)\n [[4, 3, 2, 1], [9, 3, 1, 1]]\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [1, 2, 3, 4],\n ....: 'word', False, False)\n Traceback (most recent call last):\n ...\n TypeError: q must be standard to have a word as valid output\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [4, 3, 2, 1],\n ....: 'word', False, False)\n word: 9311\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [1, 2, 3, 4],\n ....: 'list', False, False)\n Traceback (most recent call last):\n ...\n TypeError: q must be standard to have a list as valid output\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [4, 3, 2, 1],\n ....: 'list', False, False)\n [9, 3, 1, 1]\n sage: RuleHecke()._backward_format_output([1, 1, 3, 9], [1, 2, 3, 4],\n ....: 'random_type', False, False)\n Traceback (most recent call last):\n ...\n ValueError: invalid output option\n " if (output == 'array'): return [list(reversed(upper_row)), list(reversed(lower_row))] is_standard = (upper_row == list(range(len(upper_row), 0, (- 1)))) if (output == 'word'): if (not is_standard): raise TypeError(('q must be standard to have a %s as valid output' % output)) from sage.combinat.words.word import Word return Word(reversed(lower_row)) if (output == 'list'): if (not is_standard): raise TypeError(('q must be standard to have a %s as valid output' % output)) return list(reversed(lower_row)) raise ValueError('invalid output option')
class RuleDualRSK(Rule): "\n Rule for dual RSK insertion.\n\n Dual RSK insertion differs from classical RSK insertion in the\n following ways:\n\n * The input (in terms of biwords) is no longer an arbitrary biword,\n but rather a strict biword (i.e., a pair of two lists\n `[a_1, a_2, \\ldots, a_n]` and `[b_1, b_2, \\ldots, b_n]` that\n satisfy the strict inequalities\n `(a_1, b_1) < (a_2, b_2) < \\cdots < (a_n, b_n)` in\n lexicographic order).\n In terms of matrices, this means that the input is not an\n arbitrary matrix with nonnegative integer entries, but rather\n a `\\{0, 1\\}`-matrix (i.e., a matrix whose entries are `0`'s\n and `1`'s).\n\n * The output still consists of two tableaux `(P, Q)` of equal\n shapes, but rather than both of them being semistandard, now\n `P` is row-strict (i.e., its transpose is semistandard) while\n `Q` is semistandard.\n\n * The main difference is in the way bumping works. Namely,\n when a number `k_i` is inserted into the `i`-th row of `P`,\n it bumps out the first integer greater **or equal to** `k_i`\n in this row (rather than greater than `k_i`).\n\n The RSK and dual RSK algorithms agree for permutation matrices.\n\n For more information, see Chapter 7, Section 14 in [Sta-EC2]_\n (where dual RSK is called `\\mathrm{RSK}^{\\ast}`) or the third\n solution to Exercise 2.7.12(a) in [GR2018v5sol]_.\n\n EXAMPLES::\n\n sage: RSK([3,3,2,4,1], insertion=RSK.rules.dualRSK)\n [[[1, 4], [2], [3], [3]], [[1, 4], [2], [3], [5]]]\n sage: RSK(Word([3,3,2,4,1]), insertion=RSK.rules.dualRSK)\n [[[1, 4], [2], [3], [3]], [[1, 4], [2], [3], [5]]]\n sage: RSK(Word([2,3,3,2,1,3,2,3]), insertion=RSK.rules.dualRSK)\n [[[1, 2, 3], [2, 3], [2, 3], [3]], [[1, 2, 8], [3, 6], [4, 7], [5]]]\n\n Using dual RSK insertion with a strict biword::\n\n sage: RSK([1,1,2,4,4,5],[2,4,1,1,3,2], insertion=RSK.rules.dualRSK)\n [[[1, 2], [1, 3], [2, 4]], [[1, 1], [2, 4], [4, 5]]]\n sage: RSK([1,1,2,3,3,4,5],[1,3,2,1,3,3,2], insertion=RSK.rules.dualRSK)\n [[[1, 2, 3], [1, 2], [3], [3]], [[1, 1, 3], [2, 4], [3], [5]]]\n sage: RSK([1, 2, 2, 2], [2, 1, 2, 4], insertion=RSK.rules.dualRSK)\n [[[1, 2, 4], [2]], [[1, 2, 2], [2]]]\n sage: RSK(Word([1,1,3,4,4]), [1,4,2,1,3], insertion=RSK.rules.dualRSK)\n [[[1, 2, 3], [1], [4]], [[1, 1, 4], [3], [4]]]\n sage: RSK([1,3,3,4,4], Word([6,1,2,1,7]), insertion=RSK.rules.dualRSK)\n [[[1, 2, 7], [1], [6]], [[1, 3, 4], [3], [4]]]\n\n Using dual RSK insertion with a `\\{0, 1\\}`-matrix::\n\n sage: RSK(matrix([[0,1],[1,1]]), insertion=RSK.rules.dualRSK)\n [[[1, 2], [2]], [[1, 2], [2]]]\n\n We can also give it something looking like a matrix::\n\n sage: RSK([[0,1],[1,1]], insertion=RSK.rules.dualRSK)\n [[[1, 2], [2]], [[1, 2], [2]]]\n\n Let us now call the inverse correspondence::\n\n sage: RSK_inverse(*RSK([1, 2, 2, 2], [2, 1, 2, 3],\n ....: insertion=RSK.rules.dualRSK),insertion=RSK.rules.dualRSK)\n [[1, 2, 2, 2], [2, 1, 2, 3]]\n sage: P,Q = RSK([1, 2, 2, 2], [2, 1, 2, 3],insertion=RSK.rules.dualRSK)\n sage: RSK_inverse(P, Q, insertion=RSK.rules.dualRSK)\n [[1, 2, 2, 2], [2, 1, 2, 3]]\n\n When applied to two standard tableaux, reverse dual RSK\n insertion behaves identically to the usual reverse RSK insertion::\n\n sage: t1 = Tableau([[1, 2, 5], [3], [4]])\n sage: t2 = Tableau([[1, 2, 3], [4], [5]])\n sage: RSK_inverse(t1, t2, insertion=RSK.rules.dualRSK)\n [[1, 2, 3, 4, 5], [1, 4, 5, 3, 2]]\n sage: RSK_inverse(t1, t2, 'word', insertion=RSK.rules.dualRSK)\n word: 14532\n sage: RSK_inverse(t1, t2, 'matrix', insertion=RSK.rules.dualRSK)\n [1 0 0 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n [0 0 1 0 0]\n [0 1 0 0 0]\n sage: RSK_inverse(t1, t2, 'permutation', insertion=RSK.rules.dualRSK)\n [1, 4, 5, 3, 2]\n sage: RSK_inverse(t1, t1, 'permutation', insertion=RSK.rules.dualRSK)\n [1, 4, 3, 2, 5]\n sage: RSK_inverse(t2, t2, 'permutation', insertion=RSK.rules.dualRSK)\n [1, 2, 5, 4, 3]\n sage: RSK_inverse(t2, t1, 'permutation', insertion=RSK.rules.dualRSK)\n [1, 5, 4, 2, 3]\n\n Let us check that forward and backward dual RSK are mutually\n inverse when the first tableau is merely transpose semistandard::\n\n sage: p = Tableau([[1,2,2],[1]]); q = Tableau([[1,2,4],[3]])\n sage: ret = RSK_inverse(p, q, insertion=RSK.rules.dualRSK); ret\n [[1, 2, 3, 4], [1, 2, 1, 2]]\n sage: RSK_inverse(p, q, 'word', insertion=RSK.rules.dualRSK)\n word: 1212\n\n In general for dual RSK::\n\n sage: p = Tableau([[1,1,2],[1]]); q = Tableau([[1,3,3],[2]])\n sage: RSK_inverse(p, q, insertion=RSK.rules.dualRSK)\n [[1, 2, 3, 3], [1, 1, 1, 2]]\n sage: RSK_inverse(p, q, 'matrix', insertion=RSK.rules.dualRSK)\n [1 0]\n [1 0]\n [1 1]\n\n TESTS:\n\n Empty objects::\n\n sage: RSK(Permutation([]), insertion=RSK.rules.dualRSK)\n [[], []]\n sage: RSK(Word([]), insertion=RSK.rules.dualRSK)\n [[], []]\n sage: RSK(matrix([[]]), insertion=RSK.rules.dualRSK)\n [[], []]\n sage: RSK([], [], insertion=RSK.rules.dualRSK)\n [[], []]\n sage: RSK([[]], insertion=RSK.rules.dualRSK)\n [[], []]\n\n Check that :func:`RSK_inverse` is the inverse of :func:`RSK` on the\n different types of inputs/outputs::\n\n sage: RSK_inverse(Tableau([]), Tableau([]),\n ....: insertion=RSK.rules.dualRSK)\n [[], []]\n sage: f = lambda p: RSK_inverse(*RSK(p, insertion=RSK.rules.dualRSK),\n ....: output='permutation', insertion=RSK.rules.dualRSK)\n sage: all(p == f(p) for n in range(7) for p in Permutations(n))\n True\n sage: all(RSK_inverse(*RSK(w, insertion=RSK.rules.dualRSK),\n ....: output='word', insertion=RSK.rules.dualRSK) == w\n ....: for n in range(4) for w in Words(5, n))\n True\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: M = IntegerMatrices([1,2,2,1], [3,1,1,1]) #this is probably wrong\n sage: all(RSK_inverse(*RSK(m, insertion=RSK.rules.dualRSK),\n ....: output='matrix', insertion=RSK.rules.dualRSK) == m\n ....: for m in M if all(x in [0, 1] for x in m))\n True\n\n sage: n = ZZ.random_element(200)\n sage: p = Permutations(n).random_element()\n sage: True if p == f(p) else p\n True\n\n Checking that the tableaux should be of same shape::\n\n sage: RSK_inverse(Tableau([[1,2,3]]), Tableau([[1,2]]),\n ....: insertion=RSK.rules.dualRSK)\n Traceback (most recent call last):\n ...\n ValueError: p(=[[1, 2, 3]]) and q(=[[1, 2]]) must have the same shape\n " def to_pairs(self, obj1=None, obj2=None, check=True): '\n Given a valid input for the dual RSK algorithm, such as\n two `n`-tuples ``obj1`` `= [a_1, a_2, \\ldots, a_n]`\n and ``obj2`` `= [b_1, b_2, \\ldots, b_n]` forming a strict\n biword (i.e., satisfying `a_1 \\leq a_2 \\leq \\cdots \\leq a_n`,\n and if `a_i = a_{i+1}`, then `b_i < b_{i+1}`) or a\n `\\{0, 1\\}`-matrix ("rook placement"), or a single word, return\n the array `[(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)]`.\n\n INPUT:\n\n - ``obj1, obj2`` -- anything representing a strict biword\n (see the doc of :meth:`forward_rule` for the\n encodings accepted)\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n strict biword\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleDualRSK\n sage: list(RuleDualRSK().to_pairs([1, 2, 2, 2], [2, 1, 2, 3]))\n [(1, 2), (2, 1), (2, 2), (2, 3)]\n sage: RuleDualRSK().to_pairs([1, 2, 2, 2], [1, 2, 3, 3])\n Traceback (most recent call last):\n ...\n ValueError: invalid strict biword\n sage: m = Matrix(ZZ, 3, 2, [0,1,1,1,0,1]) ; m\n [0 1]\n [1 1]\n [0 1]\n sage: list(RuleDualRSK().to_pairs(m))\n [(1, 2), (2, 1), (2, 2), (3, 2)]\n sage: m = Matrix(ZZ, 3, 2, [0,1,1,0,0,2]) ; m\n [0 1]\n [1 0]\n [0 2]\n sage: RuleDualRSK().to_pairs(m)\n Traceback (most recent call last):\n ...\n ValueError: dual RSK requires a {0, 1}-matrix\n ' if (obj2 is None): try: itr = obj1._rsk_iter() except AttributeError: try: t = [] b = [] for (i, row) in enumerate(obj1): for (j, mult) in enumerate(row): if (mult > 1): raise ValueError('dual RSK requires a {0, 1}-matrix') if (mult > 0): t.append((i + 1)) b.append((j + 1)) itr = zip(t, b) except TypeError: itr = zip(range(1, (len(obj1) + 1)), obj1) else: if check: if (len(obj1) != len(obj2)): raise ValueError('the two arrays must be the same length') lt = 0 lb = 0 for (t, b) in zip(obj1, obj2): if ((t < lt) or ((t == lt) and (b <= lb))): raise ValueError('invalid strict biword') lt = t lb = b itr = zip(obj1, obj2) return itr def insertion(self, j, r): '\n Insert the letter ``j`` from the second row of the biword\n into the row `r` using dual RSK insertion, if there is\n bumping to be done.\n\n The row `r` is modified in place if bumping occurs. The bumped-out\n entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleDualRSK\n sage: r = [1, 3, 4, 5]\n sage: j = RuleDualRSK().insertion(4, r); j\n 4\n sage: r\n [1, 3, 4, 5]\n sage: r = [1, 2, 3, 6, 7]\n sage: j = RuleDualRSK().insertion(4, r); j\n 6\n sage: r\n [1, 2, 3, 4, 7]\n sage: r = [1, 3]\n sage: j = RuleDualRSK().insertion(4, r); j is None\n True\n sage: r\n [1, 3]\n ' if (r[(- 1)] < j): return None y_pos = bisect_left(r, j) (j, r[y_pos]) = (r[y_pos], j) return j def reverse_insertion(self, x, row): '\n Reverse bump the row ``row`` of the current insertion tableau\n with the number ``x`` using dual RSK insertion.\n\n The row ``row`` is modified in place. The bumped-out entry\n is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleDualRSK\n sage: r = [1, 2, 4, 6, 7]\n sage: x = RuleDualRSK().reverse_insertion(6, r); r\n [1, 2, 4, 6, 7]\n sage: x\n 6\n sage: r = [1, 2, 4, 5, 7]\n sage: x = RuleDualRSK().reverse_insertion(6, r); r\n [1, 2, 4, 6, 7]\n sage: x\n 5\n ' y_pos = (bisect_right(row, x) - 1) (x, row[y_pos]) = (row[y_pos], x) return x def _backward_format_output(self, lower_row, upper_row, output, p_is_standard, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleDualRSK\n sage: RuleDualRSK()._backward_format_output([1, 2, 3, 4], None,\n ....: 'permutation', True, True)\n [4, 3, 2, 1]\n sage: RuleDualRSK()._backward_format_output([1, 2, 3, 4], None,\n ....: 'permutation', False, True)\n Traceback (most recent call last):\n ...\n TypeError: p must be standard to have a valid permutation as output\n " if (q_is_standard and (output == 'permutation')): if (not p_is_standard): raise TypeError('p must be standard to have a valid permutation as output') from sage.combinat.permutation import Permutation return Permutation(reversed(lower_row)) else: return super()._backward_format_output(lower_row, upper_row, output, p_is_standard, q_is_standard) def _forward_format_output(self, p, q, check_standard): '\n Return final output of the ``RSK`` (here, dual RSK)\n correspondence from the output of the corresponding\n ``forward_rule``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleDualRSK\n sage: isinstance(RuleDualRSK()._forward_format_output([[1,2,3,4,5]],\n ....: [[1,2,3,4,5]], True)[0], StandardTableau)\n True\n sage: isinstance(RuleDualRSK()._forward_format_output([[1,2,3,4,5]],\n ....: [[1,2,3,4,5]], False)[0], Tableau)\n True\n sage: isinstance(RuleDualRSK()._forward_format_output([[1,1,1,3,7]],\n ....: [[1,2,3,4,5]], True)[0], Tableau)\n True\n ' from sage.combinat.tableau import Tableau, StandardTableau, SemistandardTableau if (len(p) == 0): return [StandardTableau([]), StandardTableau([])] if check_standard: try: P = StandardTableau(p) except ValueError: P = Tableau(p) try: Q = StandardTableau(q) except ValueError: Q = SemistandardTableau(q) return [P, Q] return [Tableau(p), SemistandardTableau(q)]
class RuleCoRSK(RuleRSK): "\n Rule for coRSK insertion.\n\n CoRSK insertion differs from classical RSK insertion in the\n following ways:\n\n * The input (in terms of biwords) is no longer a biword,\n but rather a strict cobiword -- i.e., a pair of two lists\n `[a_1, a_2, \\ldots, a_n]` and `[b_1, b_2, \\ldots, b_n]` that\n satisfy the strict inequalities\n `(a_1, b_1) \\widetilde{<} (a_2, b_2) \\widetilde{<} \\cdots\n \\widetilde{<} (a_n, b_n)`, where\n the binary relation `\\widetilde{<}` on pairs of integers\n is defined by having `(u_1, v_1) \\widetilde{<} (u_2, v_2)`\n if and only if either `u_1 < u_2` or (`u_1 = u_2` and\n `v_1 > v_2`).\n In terms of matrices, this means that the input is not an\n arbitrary matrix with nonnegative integer entries, but rather\n a `\\{0, 1\\}`-matrix (i.e., a matrix whose entries are `0`'s\n and `1`'s).\n\n * The output still consists of two tableaux `(P, Q)` of equal\n shapes, but rather than both of them being semistandard, now\n `Q` is row-strict (i.e., its transpose is semistandard) while\n `P` is semistandard.\n\n Bumping proceeds in the same way as for RSK insertion.\n\n The RSK and coRSK algorithms agree for permutation matrices.\n\n For more information, see Section A.4 in [Ful1997]_ (specifically,\n construction (1d)) or the second solution to Exercise 2.7.12(a) in\n [GR2018v5sol]_.\n\n EXAMPLES::\n\n sage: RSK([1,2,5,3,1], insertion = RSK.rules.coRSK)\n [[[1, 1, 3], [2], [5]], [[1, 2, 3], [4], [5]]]\n sage: RSK(Word([2,3,3,2,1,3,2,3]), insertion = RSK.rules.coRSK)\n [[[1, 2, 2, 3, 3], [2, 3], [3]], [[1, 2, 3, 6, 8], [4, 7], [5]]]\n sage: RSK(Word([3,3,2,4,1]), insertion = RSK.rules.coRSK)\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n sage: from sage.combinat.rsk import to_matrix\n sage: RSK(to_matrix([1, 1, 3, 3, 4], [3, 2, 2, 1, 3]), insertion = RSK.rules.coRSK)\n [[[1, 2, 3], [2], [3]], [[1, 3, 4], [1], [3]]]\n\n Using coRSK insertion with a `\\{0, 1\\}`-matrix::\n\n sage: RSK(matrix([[0,1],[1,0]]), insertion = RSK.rules.coRSK)\n [[[1], [2]], [[1], [2]]]\n\n We can also give it something looking like a matrix::\n\n sage: RSK([[0,1],[1,0]], insertion = RSK.rules.coRSK)\n [[[1], [2]], [[1], [2]]]\n\n We can also use the inverse correspondence::\n\n sage: RSK_inverse(*RSK([1, 2, 2, 2], [2, 3, 2, 1],\n ....: insertion=RSK.rules.coRSK),insertion=RSK.rules.coRSK)\n [[1, 2, 2, 2], [2, 3, 2, 1]]\n sage: P,Q = RSK([1, 2, 2, 2], [2, 3, 2, 1],insertion=RSK.rules.coRSK)\n sage: RSK_inverse(P, Q, insertion=RSK.rules.coRSK)\n [[1, 2, 2, 2], [2, 3, 2, 1]]\n\n When applied to two standard tableaux, backwards coRSK\n insertion behaves identically to the usual backwards RSK\n insertion::\n\n sage: t1 = Tableau([[1, 2, 5], [3], [4]])\n sage: t2 = Tableau([[1, 2, 3], [4], [5]])\n sage: RSK_inverse(t1, t2, insertion=RSK.rules.coRSK)\n [[1, 2, 3, 4, 5], [1, 4, 5, 3, 2]]\n sage: RSK_inverse(t1, t2, 'word', insertion=RSK.rules.coRSK)\n word: 14532\n sage: RSK_inverse(t1, t2, 'matrix', insertion=RSK.rules.coRSK)\n [1 0 0 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n [0 0 1 0 0]\n [0 1 0 0 0]\n sage: RSK_inverse(t1, t2, 'permutation', insertion=RSK.rules.coRSK)\n [1, 4, 5, 3, 2]\n sage: RSK_inverse(t1, t1, 'permutation', insertion=RSK.rules.coRSK)\n [1, 4, 3, 2, 5]\n sage: RSK_inverse(t2, t2, 'permutation', insertion=RSK.rules.coRSK)\n [1, 2, 5, 4, 3]\n sage: RSK_inverse(t2, t1, 'permutation', insertion=RSK.rules.coRSK)\n [1, 5, 4, 2, 3]\n\n For coRSK, the first tableau is semistandard while the second tableau\n is transpose semistandard::\n\n sage: p = Tableau([[1,2,2],[5]]); q = Tableau([[1,2,4],[3]])\n sage: ret = RSK_inverse(p, q, insertion=RSK.rules.coRSK); ret\n [[1, 2, 3, 4], [1, 5, 2, 2]]\n sage: RSK_inverse(p, q, 'word', insertion=RSK.rules.coRSK)\n word: 1522\n\n TESTS:\n\n Empty objects::\n\n sage: RSK(Permutation([]), insertion=RSK.rules.coRSK)\n [[], []]\n sage: RSK(Word([]), insertion=RSK.rules.coRSK)\n [[], []]\n sage: RSK(matrix([[]]), insertion=RSK.rules.coRSK)\n [[], []]\n sage: RSK([], [], insertion=RSK.rules.coRSK)\n [[], []]\n sage: RSK([[]], insertion=RSK.rules.coRSK)\n [[], []]\n\n Check that :func:`RSK_inverse` is the inverse of :func:`RSK` on the\n different types of inputs/outputs::\n\n sage: RSK_inverse(Tableau([]), Tableau([]),\n ....: insertion=RSK.rules.coRSK)\n [[], []]\n sage: f = lambda p: RSK_inverse(*RSK(p, insertion=RSK.rules.coRSK),\n ....: output='permutation', insertion=RSK.rules.coRSK)\n sage: all(p == f(p) for n in range(7) for p in Permutations(n))\n True\n sage: all(RSK_inverse(*RSK(w, insertion=RSK.rules.coRSK),\n ....: output='word', insertion=RSK.rules.coRSK) == w\n ....: for n in range(4) for w in Words(5, n))\n True\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: M = IntegerMatrices([1,2,2,1], [3,1,1,1])\n sage: all(RSK_inverse(*RSK(m, insertion=RSK.rules.coRSK),\n ....: output='matrix', insertion=RSK.rules.coRSK) == m\n ....: for m in M if all(x in [0, 1] for x in m))\n True\n\n sage: n = ZZ.random_element(200)\n sage: p = Permutations(n).random_element()\n sage: True if p == f(p) else p\n True\n\n Checking that the tableaux should be of same shape::\n\n sage: RSK_inverse(Tableau([[1,2,3]]), Tableau([[1,2]]),\n ....: insertion=RSK.rules.dualRSK)\n Traceback (most recent call last):\n ...\n ValueError: p(=[[1, 2, 3]]) and q(=[[1, 2]]) must have the same shape\n\n Checking that the biword is a strict cobiword::\n\n sage: RSK([1,2,4,3], [1,2,3,4], insertion=RSK.rules.coRSK)\n Traceback (most recent call last):\n ...\n ValueError: invalid strict cobiword\n sage: RSK([1,2,3,3], [1,2,3,4], insertion=RSK.rules.coRSK)\n Traceback (most recent call last):\n ...\n ValueError: invalid strict cobiword\n sage: RSK([1,2,3,3], [1,2,3,3], insertion=RSK.rules.coRSK)\n Traceback (most recent call last):\n ...\n ValueError: invalid strict cobiword\n " def to_pairs(self, obj1=None, obj2=None, check=True): '\n Given a valid input for the coRSK algorithm, such as\n two `n`-tuples ``obj1`` `= [a_1, a_2, \\ldots, a_n]`\n and ``obj2`` `= [b_1, b_2, \\ldots, b_n]` forming a\n strict cobiword (i.e., satisfying\n `a_1 \\leq a_2 \\leq \\cdots \\leq a_n`, and if\n `a_i = a_{i+1}`, then `b_i > b_{i+1}`),\n or a `\\{0, 1\\}`-matrix ("rook placement"), or a\n single word, return the array\n `[(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)]`.\n\n INPUT:\n\n - ``obj1, obj2`` -- anything representing a strict\n cobiword (see the doc of :meth:`forward_rule` for\n the encodings accepted)\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n strict cobiword\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleCoRSK\n sage: list(RuleCoRSK().to_pairs([1, 2, 2, 2], [2, 3, 2, 1]))\n [(1, 2), (2, 3), (2, 2), (2, 1)]\n sage: RuleCoRSK().to_pairs([1, 2, 2, 2], [1, 2, 3, 3])\n Traceback (most recent call last):\n ...\n ValueError: invalid strict cobiword\n sage: m = Matrix(ZZ, 3, 2, [0,1,1,1,0,1]) ; m\n [0 1]\n [1 1]\n [0 1]\n sage: list(RuleCoRSK().to_pairs(m))\n [(1, 2), (2, 2), (2, 1), (3, 2)]\n sage: m = Matrix(ZZ, 3, 2, [0,1,1,0,0,2]) ; m\n [0 1]\n [1 0]\n [0 2]\n sage: RuleCoRSK().to_pairs(m)\n Traceback (most recent call last):\n ...\n ValueError: coRSK requires a {0, 1}-matrix\n ' if (obj2 is None): try: itr = obj1._rsk_iter() except AttributeError: try: t = [] b = [] for (i, row) in enumerate(obj1): for (j, mult) in reversed(list(enumerate(row))): if (mult > 1): raise ValueError('coRSK requires a {0, 1}-matrix') if (mult > 0): t.append((i + 1)) b.append((j + 1)) itr = zip(t, b) except TypeError: itr = zip(range(1, (len(obj1) + 1)), obj1) else: if check: if (len(obj1) != len(obj2)): raise ValueError('the two arrays must be the same length') lt = 0 lb = 0 for (t, b) in zip(obj1, obj2): if ((t < lt) or ((t == lt) and (b >= lb))): raise ValueError('invalid strict cobiword') lt = t lb = b itr = zip(obj1, obj2) return itr def _forward_format_output(self, p, q, check_standard): '\n Return final output of the ``RSK`` correspondence from the\n output of the corresponding ``forward_rule``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleCoRSK\n sage: isinstance(RuleCoRSK()._forward_format_output([[1,2,3,4,5]],\n ....: [[1,2,3,4,5]], True)[0], StandardTableau)\n True\n sage: isinstance(RuleCoRSK()._forward_format_output([[1,2,3,4,5]],\n ....: [[1,2,3,4,5]], False)[0], SemistandardTableau)\n True\n sage: isinstance(RuleCoRSK()._forward_format_output([[1,1,1,3,7]],\n ....: [[1,2,3,4,5]], True)[1], Tableau)\n True\n sage: isinstance(RuleCoRSK()._forward_format_output([[1,1,1,3,7]],\n ....: [[1,2,3,4,5]], False)[1], Tableau)\n True\n ' from sage.combinat.tableau import SemistandardTableau, StandardTableau, Tableau if check_standard: try: P = StandardTableau(p) except ValueError: P = SemistandardTableau(p) try: Q = StandardTableau(q) except ValueError: Q = Tableau(q) return [P, Q] return [SemistandardTableau(p), Tableau(q)] def backward_rule(self, p, q, output): "\n Return the strict cobiword obtained by applying reverse\n coRSK insertion to a pair of tableaux ``(p, q)``.\n\n INPUT:\n\n - ``p``, ``q`` -- two tableaux of the same shape\n\n - ``output`` -- (default: ``'array'``) if ``q`` is row-strict:\n\n - ``'array'`` -- as a two-line array (i.e. strict cobiword)\n - ``'matrix'`` -- as a `\\{0, 1\\}`-matrix\n\n and if ``q`` is standard, we can have the output:\n\n - ``'word'`` -- as a word\n\n and additionally if ``p`` is standard, we can also have the output:\n\n - ``'permutation'`` -- as a permutation\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleCoRSK\n sage: t1 = Tableau([[1, 1, 2], [2, 3], [4]])\n sage: t2 = Tableau([[1, 4, 5], [1, 4], [2]])\n sage: RuleCoRSK().backward_rule(t1, t2, 'array')\n [[1, 1, 2, 4, 4, 5], [4, 2, 1, 3, 1, 2]]\n " p_copy = [list(row) for row in p] if q.is_standard(): rev_word = [] d = {qij: i for (i, Li) in enumerate(q) for qij in Li} for key in sorted(d, reverse=True): i = d[key] x = p_copy[i].pop() for row in reversed(p_copy[:i]): x = self.reverse_insertion(x, row) rev_word.append(x) return self._backward_format_output(rev_word, None, output, p.is_standard(), True) upper_row = [] lower_row = [] d = {} for (row, Li) in enumerate(q): for val in Li: if (val in d): d[val].append(row) else: d[val] = [row] for (value, row_list) in sorted(d.items(), reverse=True, key=(lambda x: x[0])): for i in sorted(row_list, reverse=True): x = p_copy[i].pop() for row in reversed(p_copy[:i]): x = self.reverse_insertion(x, row) lower_row.append(x) upper_row.append(value) return self._backward_format_output(lower_row, upper_row, output, p.is_standard(), False)
class RuleSuperRSK(RuleRSK): '\n Rule for super RSK insertion.\n\n Super RSK is based on `\\epsilon`-insertion, a combination of\n row and column classical RSK insertion.\n\n Super RSK insertion differs from the classical RSK insertion in the\n following ways:\n\n * The input (in terms of biwords) is no longer an arbitrary biword,\n but rather a restricted super biword (i.e., a pair of two lists\n `[a_1, a_2, \\ldots, a_n]` and `[b_1, b_2, \\ldots, b_n]` that\n contains entries with even and odd parity and pairs with mixed\n parity entries do not repeat).\n\n * The output still consists of two tableaux `(P, Q)` of equal\n shapes, but rather than both of them being semistandard, now\n they are semistandard super tableaux.\n\n * The main difference is in the way bumping works. Instead of having\n only row bumping super RSK uses `\\epsilon`-insertion, a combination\n of classical RSK bumping along the rows and a dual RSK like bumping\n (i.e. when a number `k_i` is inserted into the `i`-th row of `P`, it\n bumps out the first integer greater **or equal to** `k_i` in the column)\n along the column.\n\n EXAMPLES::\n\n sage: RSK([1], [1], insertion=\'superRSK\')\n [[[1]], [[1]]]\n sage: RSK([1, 2], [1, 3], insertion=\'superRSK\')\n [[[1, 3]], [[1, 2]]]\n sage: RSK([1, 2, 3], [1, 3, "3p"], insertion=\'superRSK\')\n [[[1, 3], [3\']], [[1, 2], [3]]]\n sage: RSK([1, 3, "3p", "2p"], insertion=\'superRSK\')\n [[[1, 3\', 3], [2\']], [[1\', 1, 2\'], [2]]]\n sage: RSK(["1p", "2p", 2, 2, "3p", "3p", 3, 3],\n ....: ["1p", 1, "2p", 2, "3p", "3p", "3p", 3], insertion=\'superRSK\')\n [[[1\', 2, 3\', 3], [1, 3\'], [2\'], [3\']], [[1\', 2, 3\', 3], [2\', 3\'], [2], [3]]]\n sage: P = SemistandardSuperTableau([[1, \'3p\', 3], [\'2p\']])\n sage: Q = SemistandardSuperTableau([[\'1p\', 1, \'2p\'], [2]])\n sage: RSK_inverse(P, Q, insertion=RSK.rules.superRSK)\n [[1\', 1, 2\', 2], [1, 3, 3\', 2\']]\n\n We apply super RSK on Example 5.1 in [Muth2019]_::\n\n sage: P,Q = RSK(["1p", "2p", 2, 2, "3p", "3p", 3, 3],\n ....: ["3p", 1, 2, 3, "3p", "3p", "2p", "1p"], insertion=\'superRSK\')\n sage: (P, Q)\n ([[1\', 2\', 3\', 3], [1, 2, 3\'], [3\']], [[1\', 2, 2, 3\'], [2\', 3, 3], [3\']])\n sage: ascii_art((P, Q))\n ( 1\' 2\' 3\' 3 1\' 2 2 3\' )\n ( 1 2 3\' 2\' 3 3 )\n ( 3\' , 3\' )\n sage: RSK_inverse(P, Q, insertion=RSK.rules.superRSK)\n [[1\', 2\', 2, 2, 3\', 3\', 3, 3], [3\', 1, 2, 3, 3\', 3\', 2\', 1\']]\n\n Example 6.1 in [Muth2019]_::\n\n sage: P,Q = RSK(["1p", "2p", 2, 2, "3p", "3p", 3, 3],\n ....: ["3p", 1, 2, 3, "3p", "3p", "2p", "1p"], insertion=\'superRSK\')\n sage: ascii_art((P, Q))\n ( 1\' 2\' 3\' 3 1\' 2 2 3\' )\n ( 1 2 3\' 2\' 3 3 )\n ( 3\' , 3\' )\n sage: RSK_inverse(P, Q, insertion=RSK.rules.superRSK)\n [[1\', 2\', 2, 2, 3\', 3\', 3, 3], [3\', 1, 2, 3, 3\', 3\', 2\', 1\']]\n\n sage: P,Q = RSK(["1p", 1, "2p", 2, "3p", "3p", "3p", 3],\n ....: [3, "2p", 3, 2, "3p", "3p", "1p", 2], insertion=\'superRSK\')\n sage: ascii_art((P, Q))\n ( 1\' 2 2 3\' 1\' 2\' 3\' 3 )\n ( 2\' 3 3 1 2 3\' )\n ( 3\' , 3\' )\n sage: RSK_inverse(P, Q, insertion=RSK.rules.superRSK)\n [[1\', 1, 2\', 2, 3\', 3\', 3\', 3], [3, 2\', 3, 2, 3\', 3\', 1\', 2]]\n\n Let us now call the inverse correspondence::\n\n sage: P, Q = RSK([1, 2, 2, 2], [2, 1, 2, 3],\n ....: insertion=RSK.rules.superRSK)\n sage: RSK_inverse(P, Q, insertion=RSK.rules.superRSK)\n [[1, 2, 2, 2], [2, 1, 2, 3]]\n\n When applied to two tableaux with only even parity elements, reverse super\n RSK insertion behaves identically to the usual reversel RSK insertion::\n\n sage: t1 = Tableau([[1, 2, 5], [3], [4]])\n sage: t2 = Tableau([[1, 2, 3], [4], [5]])\n sage: RSK_inverse(t1, t2, insertion=RSK.rules.RSK)\n [[1, 2, 3, 4, 5], [1, 4, 5, 3, 2]]\n sage: t1 = SemistandardSuperTableau([[1, 2, 5], [3], [4]])\n sage: t2 = SemistandardSuperTableau([[1, 2, 3], [4], [5]])\n sage: RSK_inverse(t1, t2, insertion=RSK.rules.superRSK)\n [[1, 2, 3, 4, 5], [1, 4, 5, 3, 2]]\n\n TESTS:\n\n Empty objects::\n\n sage: RSK(Word([]), insertion=RSK.rules.superRSK)\n [[], []]\n sage: RSK([], [], insertion=RSK.rules.superRSK)\n [[], []]\n\n Check that :func:`RSK_inverse` is the inverse of :func:`RSK` on the\n different types of inputs/outputs::\n\n sage: from sage.combinat.shifted_primed_tableau import PrimedEntry\n sage: RSK_inverse(SemistandardSuperTableau([]),\n ....: SemistandardSuperTableau([]), insertion=RSK.rules.superRSK)\n [[], []]\n sage: f = lambda p: RSK_inverse(*RSK(p, insertion=RSK.rules.superRSK),\n ....: insertion=RSK.rules.superRSK)\n sage: all(p == f(p)[1] for n in range(5) for p in Permutations(n))\n True\n\n sage: SST = StandardSuperTableaux([3,2,1])\n sage: f = lambda P, Q: RSK(*RSK_inverse(P, Q, insertion=RSK.rules.superRSK),\n ....: insertion=RSK.rules.superRSK)\n sage: all([P, Q] == f(P, Q) for n in range(7) for la in Partitions(n)\n ....: for P in StandardSuperTableaux(la) for Q in StandardSuperTableaux(la))\n True\n\n Checking that tableaux should be of same shape::\n\n sage: RSK_inverse(SemistandardSuperTableau([[1, 2, 3]]),\n ....: SemistandardSuperTableau([[1, 2]]),\n ....: insertion=RSK.rules.superRSK)\n Traceback (most recent call last):\n ...\n ValueError: p(=[[1, 2, 3]]) and q(=[[1, 2]]) must have the same shape\n ' def to_pairs(self, obj1=None, obj2=None, check=True): "\n Given a valid input for the super RSK algorithm, such as\n two `n`-tuples ``obj1`` `= [a_1, a_2, \\ldots, a_n]`\n and ``obj2`` `= [b_1, b_2, \\ldots, b_n]` forming a restricted\n super biword (i.e., entries with even and odd parity and no\n repetition of corresponding pairs with mixed parity entries)\n return the array `[(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)]`.\n\n INPUT:\n\n - ``obj1, obj2`` -- anything representing a restricted super biword\n (see the doc of :meth:`forward_rule` for the\n encodings accepted)\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n restricted super biword\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: list(RuleSuperRSK().to_pairs([2, '1p', 1],[1, 1, '1p']))\n [(2, 1), (1', 1), (1, 1')]\n sage: list(RuleSuperRSK().to_pairs([1, '1p', '2p']))\n [(1', 1), (1, 1'), (2', 2')]\n sage: list(RuleSuperRSK().to_pairs([1, 1], ['1p', '1p']))\n Traceback (most recent call last):\n ...\n ValueError: invalid restricted superbiword\n " from sage.combinat.shifted_primed_tableau import PrimedEntry itr = None if (obj2 is None): try: itr = obj1._rsk_iter() except AttributeError: (obj2, obj1) = (obj1, []) a = (ZZ.one() / ZZ(2)) for i in range(len(obj2)): obj1.append(a) a = (a + (ZZ.one() / ZZ(2))) elif check: if (len(obj1) != len(obj2)): raise ValueError('the two arrays must be the same length') mixed_parity = [] for (t, b) in zip(obj1, obj2): if (PrimedEntry(t).is_primed() != PrimedEntry(b).is_primed()): if ((t, b) in mixed_parity): raise ValueError('invalid restricted superbiword') else: mixed_parity.append((t, b)) if itr: (obj1, obj2) = ([], []) for (i, j) in itr: obj1.append(i) obj2.append(j) for i in range(len(obj1)): obj1[i] = PrimedEntry(obj1[i]) obj2[i] = PrimedEntry(obj2[i]) return zip(obj1, obj2) def _get_col(self, t, col_index): '\n Return the column as a list of a given tableau ``t`` (list of lists)\n at index ``col_index`` (indexing starting from zero).\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: t = [[1,2,3,4], [5,6,7,8], [9,10]];\n sage: RuleSuperRSK()._get_col(t, 0)\n [1, 5, 9]\n sage: RuleSuperRSK()._get_col(t, 2)\n [3, 7]\n ' num_rows_long_enough = 0 for row in t: if (len(row) > col_index): num_rows_long_enough += 1 else: break col = [t[row_index][col_index] for row_index in range(num_rows_long_enough)] return col def _set_col(self, t, col_index, col): '\n Set the column of a given tableau ``t`` (list of lists) at\n index ``col_index`` (indexing starting from zero) as ``col``.\n\n .. NOTE::\n\n If ``length(col)`` is greater than the corresponding column in\n tableau ``t`` then only those rows of ``t`` will be set which\n have ``length(row) <= col_index``. Similarly if ``length(col)``\n is less than the corresponding column in tableau ``t`` then only\n those entries of the corresponding column in ``t`` which have row\n index less than ``length(col)`` will be set, rest will remain\n unchanged.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: t = [[1,2,3,4], [5,6,7,8], [9,10]]\n sage: col = [1, 2, 3, 4]\n sage: RuleSuperRSK()._set_col(t, 0, col); t\n [[1, 2, 3, 4], [2, 6, 7, 8], [3, 10], [4]]\n sage: col = [1]\n sage: RuleSuperRSK()._set_col(t, 2, col); t\n [[1, 2, 1, 4], [2, 6, 7, 8], [3, 10], [4]]\n ' for (row_index, val) in enumerate(col): if (row_index == len(t)): t.append([]) if (col_index == len(t[row_index])): t[row_index].append(None) t[row_index][col_index] = val def forward_rule(self, obj1, obj2, check_standard=False, check=True): '\n Return a pair of tableaux obtained by applying forward\n insertion to the restricted super biword ``[obj1, obj2]``.\n\n INPUT:\n\n - ``obj1, obj2`` -- can be one of the following ways to\n represent a generalized permutation (or, equivalently,\n biword):\n\n - two lists ``obj1`` and ``obj2`` of equal length,\n to be interpreted as the top row and the bottom row of\n the biword\n\n - a word ``obj1`` in an ordered alphabet, to be\n interpreted as the bottom row of the biword (in this\n case, ``obj2`` is ``None``; the top row of the biword\n is understood to be `(1, 2, \\ldots, n)` by default)\n\n - any object ``obj1`` which has a method ``_rsk_iter()``,\n as long as this method returns an iterator yielding\n pairs of numbers, which then are interperted as top\n entries and bottom entries in the biword (in this case,\n ``obj2`` is ``None``)\n\n - ``check_standard`` -- (default: ``False``) check if either of\n the resulting tableaux is a standard super tableau, and if so,\n typecast it as such\n\n - ``check`` -- (default: ``True``) whether to check\n that ``obj1`` and ``obj2`` actually define a valid\n restricted super biword\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: p, q = RuleSuperRSK().forward_rule([1, 2], [1, 3]); p\n [[1, 3]]\n sage: q\n [[1, 2]]\n sage: isinstance(p, SemistandardSuperTableau)\n True\n sage: isinstance(q, SemistandardSuperTableau)\n True\n ' itr = self.to_pairs(obj1, obj2, check=check) p = [] q = [] for (i, j) in itr: row_index = (- 1) col_index = (- 1) epsilon = (1 if i.is_primed() else 0) while True: if (i.is_primed() == j.is_primed()): row_index += 1 if (row_index == len(p)): p.append([j]) q.append([i]) break else: (j1, col_index) = self.insertion(j, p[row_index], epsilon=epsilon) if (j1 is None): p[row_index].append(j) q[row_index].append(i) break else: j = j1 else: col_index += 1 if ((not p) or (col_index == len(p[0]))): self._set_col(p, col_index, [j]) self._set_col(q, col_index, [i]) break else: c = self._get_col(p, col_index) (j1, row_index) = self.insertion(j, c, epsilon=epsilon) if (j1 is None): c.append(j) self._set_col(p, col_index, c) if (col_index == 0): q.append([]) q[row_index].append(i) break else: j = j1 self._set_col(p, col_index, c) return self._forward_format_output(p, q, check_standard=check_standard) def insertion(self, j, r, epsilon=0): '\n Insert the letter ``j`` from the second row of the biword\n into the row ``r`` using dual RSK insertion or classical\n Schensted insertion depending on the value of ``epsilon``,\n if there is bumping to be done.\n\n The row `r` is modified in place if bumping occurs. The bumped-out\n entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: from bisect import bisect_left, bisect_right\n sage: r = [1, 3, 3, 3, 4]\n sage: j = 3\n sage: j, y_pos = RuleSuperRSK().insertion(j, r, epsilon=0); r\n [1, 3, 3, 3, 3]\n sage: j\n 4\n sage: y_pos\n 4\n sage: r = [1, 3, 3, 3, 4]\n sage: j = 3\n sage: j, y_pos = RuleSuperRSK().insertion(j, r, epsilon=1); r\n [1, 3, 3, 3, 4]\n sage: j\n 3\n sage: y_pos\n 1\n ' bisect = (bisect_right if (epsilon == 0) else bisect_left) if ((r[(- 1)] < j) or ((r[(- 1)] == j) and (epsilon == 0))): return (None, len(r)) y_pos = bisect(r, j) (j, r[y_pos]) = (r[y_pos], j) return (j, y_pos) def _forward_format_output(self, p, q, check_standard): "\n Return final output of the ``RSK`` (here, super RSK)\n correspondence from the output of the corresponding\n ``forward_rule``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: isinstance(RuleSuperRSK()._forward_format_output(\n ....: [['1p', 1, '2p']], [['1p', '1', '2p']], True)[0],\n ....: StandardSuperTableau)\n True\n sage: isinstance(RuleSuperRSK()._forward_format_output(\n ....: [[1, '2p', 3]], [[1, 2, 3]], False)[0],\n ....: SemistandardSuperTableau)\n True\n sage: isinstance(RuleSuperRSK()._forward_format_output(\n ....: [[1, 1, 3]], [[1, 2, 3]], True)[0],\n ....: SemistandardSuperTableau)\n True\n " from sage.combinat.tableau import StandardTableau from sage.combinat.super_tableau import SemistandardSuperTableau, StandardSuperTableau if (not p): return [StandardTableau([]), StandardTableau([])] if check_standard: try: P = StandardSuperTableau(p) except ValueError: P = SemistandardSuperTableau(p) try: Q = StandardSuperTableau(q) except ValueError: Q = SemistandardSuperTableau(q) return [P, Q] return [SemistandardSuperTableau(p), SemistandardSuperTableau(q)] def backward_rule(self, p, q, output='array'): "\n Return the restricted super biword obtained by applying reverse\n super RSK insertion to a pair of tableaux ``(p, q)``.\n\n INPUT:\n\n - ``p``, ``q`` -- two tableaux of the same shape\n\n - ``output`` -- (default: ``'array'``) if ``q`` is row-strict:\n\n - ``'array'`` -- as a two-line array (i.e. restricted super biword)\n\n and if ``q`` is standard, we can have the output:\n\n - ``'word'`` -- as a word\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: t1 = SemistandardSuperTableau([['1p', '3p', '4p'], [2], [3]])\n sage: t2 = SemistandardSuperTableau([[1, 2, 4], [3], [5]])\n sage: RuleSuperRSK().backward_rule(t1, t2, 'array')\n [[1, 2, 3, 4, 5], [4', 3, 3', 2, 1']]\n sage: t1 = SemistandardSuperTableau([[1, 3], ['3p']])\n sage: t2 = SemistandardSuperTableau([[1, 2], [3]])\n sage: RuleSuperRSK().backward_rule(t1, t2, 'array')\n [[1, 2, 3], [1, 3, 3']]\n " p_copy = [list(row) for row in p] upper_row = [] lower_row = [] d = {} for (row, Li) in enumerate(q): for (col, val) in enumerate(Li): if ((val in d) and (col in d[val])): d[val][col].append(row) elif (val not in d): d[val] = {col: [row]} else: d[val][col] = [row] for (value, iter_dict) in sorted(d.items(), reverse=True, key=(lambda x: x[0])): epsilon = (1 if value.is_primed() else 0) if (epsilon == 1): iter_copy = dict(iter_dict) iter_dict = {} for (k, v) in iter_copy.items(): for vi in v: if (vi in iter_dict): iter_dict[vi].append(k) else: iter_dict[vi] = [k] for key in sorted(iter_dict, reverse=True): for rows in iter_dict[key]: (row_index, col_index) = ((rows, key) if (epsilon == 0) else (key, rows)) x = p_copy[row_index].pop() while True: if (value.is_primed() == x.is_primed()): row_index -= 1 if (row_index < 0): break (x, col_index) = self.reverse_insertion(x, p_copy[row_index], epsilon=epsilon) else: col_index -= 1 if (col_index < 0): break c = self._get_col(p_copy, col_index) (x, row_index) = self.reverse_insertion(x, c, epsilon=epsilon) self._set_col(p_copy, col_index, c) upper_row.append(value) lower_row.append(x) return self._backward_format_output(lower_row, upper_row, output, q.is_standard()) def reverse_insertion(self, x, row, epsilon=0): '\n Reverse bump the row ``row`` of the current insertion tableau\n with the number ``x`` using dual RSK insertion or classical\n Schensted insertion depending on the value of `epsilon`.\n\n The row ``row`` is modified in place. The bumped-out entry\n is returned along with the bumped position.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: from bisect import bisect_left, bisect_right\n sage: r = [1, 3, 3, 3, 4]\n sage: j = 2\n sage: j, y = RuleSuperRSK().reverse_insertion(j, r, epsilon=0); r\n [2, 3, 3, 3, 4]\n sage: j\n 1\n sage: y\n 0\n sage: r = [1, 3, 3, 3, 4]\n sage: j = 3\n sage: j, y = RuleSuperRSK().reverse_insertion(j, r, epsilon=0); r\n [3, 3, 3, 3, 4]\n sage: j\n 1\n sage: y\n 0\n sage: r = [1, 3, 3, 3, 4]\n sage: j = (3)\n sage: j, y = RuleSuperRSK().reverse_insertion(j, r, epsilon=1); r\n [1, 3, 3, 3, 4]\n sage: j\n 3\n sage: y\n 3\n ' bisect = (bisect_left if (epsilon == 0) else bisect_right) y_pos = (bisect(row, x) - 1) (x, row[y_pos]) = (row[y_pos], x) return (x, y_pos) def _backward_format_output(self, lower_row, upper_row, output, q_is_standard): "\n Return the final output of the ``RSK_inverse`` correspondence\n from the output of the corresponding ``backward_rule``.\n\n .. NOTE::\n\n The default implementation of ``backward_rule`` lists\n bumped-out entries in the order in which the reverse\n bumping happens, which is *opposite* to the order of the\n final output.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleSuperRSK\n sage: from sage.combinat.shifted_primed_tableau import PrimedEntry\n sage: RuleSuperRSK()._backward_format_output([PrimedEntry('1p'),\n ....: PrimedEntry(1), PrimedEntry('3p'), PrimedEntry(9)],\n ....: [PrimedEntry(1), PrimedEntry('2p'), PrimedEntry('3p'),\n ....: PrimedEntry(4)], 'array', False)\n [[4, 3', 2', 1], [9, 3', 1, 1']]\n sage: RuleSuperRSK()._backward_format_output([PrimedEntry(1),\n ....: PrimedEntry('2p'), PrimedEntry('3p'), PrimedEntry(4)],\n ....: [PrimedEntry('1p'), PrimedEntry(1), PrimedEntry('2p'),\n ....: PrimedEntry(2)], 'word', True)\n word: 4,3',2',1\n sage: RuleSuperRSK()._backward_format_output([PrimedEntry(1),\n ....: PrimedEntry(2), PrimedEntry(3), PrimedEntry(4)],\n ....: [PrimedEntry('1p'), PrimedEntry(1), PrimedEntry('2p'),\n ....: PrimedEntry(2)], 'word', True)\n word: 4321\n " if (output == 'array'): return [list(reversed(upper_row)), list(reversed(lower_row))] if (output == 'word'): if q_is_standard: from sage.combinat.words.word import Word return Word(reversed(lower_row)) else: raise TypeError(('q must be standard to have a %s as valid output' % output)) raise ValueError('invalid output option')
class RuleStar(Rule): "\n Rule for `\\star`-insertion.\n\n The `\\star`-insertion is similar to the classical RSK algorithm\n and is defined in [MPPS2020]_. The bottom row of the increasing\n Hecke biword is a word in the 0-Hecke monoid that is fully\n commutative. When inserting a letter `x` into a row `R`, there\n are three cases:\n\n - Case 1: If `R` is empty or `x > \\max(R)`, append `x` to row `R`\n and terminate.\n\n - Case 2: Otherwise if `x` is not in `R`, locate the smallest `y` in `R`\n with `y > x`. Bump `y` with `x` and insert `y` into the next row.\n\n - Case 3: Otherwise, if `x` is in `R`, locate the smallest `y` in `R` with\n `y \\leq x` and interval `[y,x]` contained in `R`. Row `R` remains\n unchanged and `y` is to be inserted into the next row.\n\n The `\\star`-insertion returns a pair consisting a conjugate of a\n semistandard tableau and a semistandard tableau. It is a bijection from the\n collection of all increasing Hecke biwords whose bottom row is a fully\n commutative word to pairs (P, Q) of tableaux of the same shape such that\n P is conjugate semistandard, Q is semistandard and the row reading word of\n P is fully commutative [MPPS2020]_.\n\n EXAMPLES:\n\n As an example of `\\star`-insertion, we reproduce Example 28 in [MPPS2020]_::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: p,q = RuleStar().forward_rule([1,1,2,2,4,4], [1,3,2,4,2,4])\n sage: ascii_art(p, q)\n 1 2 4 1 1 2\n 1 4 2 4\n 3 4\n sage: line1,line2 = RuleStar().backward_rule(p, q)\n sage: line1,line2\n ([1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4])\n sage: RSK_inverse(p, q, output='DecreasingHeckeFactorization', insertion='Star')\n (4, 2)()(4, 2)(3, 1)\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h = DecreasingHeckeFactorization([[4, 2], [], [4, 2], [3, 1]])\n sage: RSK_inverse(*RSK(h,insertion='Star'),insertion='Star',\n ....: output='DecreasingHeckeFactorization')\n (4, 2)()(4, 2)(3, 1)\n sage: p,q = RSK(h, insertion='Star')\n sage: ascii_art(p, q)\n 1 2 4 1 1 2\n 1 4 2 4\n 3 4\n sage: RSK_inverse(p, q, insertion='Star')\n [[1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4]]\n sage: f = RSK_inverse(p, q, output='DecreasingHeckeFactorization', insertion='Star')\n sage: f == h\n True\n\n .. WARNING::\n\n When ``output`` is set to ``'DecreasingHeckeFactorization'``, the\n inverse of `\\star`-insertion of `(P,Q)` returns a decreasing\n factorization whose number of factors is the maximum entry of `Q`::\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h1 = DecreasingHeckeFactorization([[],[3,1],[1]]); h1\n ()(3, 1)(1)\n sage: P,Q = RSK(h1, insertion='Star')\n sage: ascii_art(P, Q)\n 1 3 1 2\n 1 2\n sage: h2 = RSK_inverse(P, Q, insertion='Star',\n ....: output='DecreasingHeckeFactorization'); h2\n (3, 1)(1)\n\n TESTS:\n\n Check that :func:`RSK` is the inverse of :func:`RSK_inverse` for various\n outputs/inputs::\n\n sage: from sage.combinat.partition import Partitions_n\n sage: shapes = [shape for n in range(7) for shape in Partitions_n(n)]\n sage: row_reading = lambda T: [x for row in reversed(T) for x in row]\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: H = HeckeMonoid(SymmetricGroup(4+1))\n sage: from sage.combinat import permutation\n sage: reduce = lambda w: permutation.from_reduced_word(H.from_reduced_word(w).reduced_word())\n sage: fc = lambda w: not reduce(w).has_pattern([3,2,1])\n sage: FC_tabs = [T for shape in shapes\n ....: for T in SemistandardTableaux(shape, max_entry=4)\n ....: if fc(row_reading(T.conjugate()))]\n sage: Checks = []\n sage: for T in FC_tabs: # long time\n ....: shape = T.shape().conjugate()\n ....: P = T.conjugate()\n ....: Checks += [all((P,Q) == tuple(RSK(*RSK_inverse(P, Q,\n ....: insertion='Star', output='array'),\n ....: insertion='Star'))\n ....: for Q in SemistandardTableaux(shape, max_entry=5))]\n sage: all(Checks)\n True\n sage: Checks = []\n sage: for T in FC_tabs: # long time\n ....: shape = T.shape().conjugate()\n ....: P = T.conjugate()\n ....: Checks += [all((P,Q) == tuple(RSK(RSK_inverse(P, Q,\n ....: insertion='Star', output='DecreasingHeckeFactorization'),\n ....: insertion='Star'))\n ....: for Q in SemistandardTableaux(shape, max_entry=5))]\n sage: all(Checks)\n True\n sage: Checks = []\n sage: for T in FC_tabs:\n ....: shape = T.shape().conjugate()\n ....: P = T.conjugate()\n ....: for Q in StandardTableaux(shape, max_entry=5):\n ....: Checks += [(P,Q) == tuple(RSK(RSK_inverse(P, Q,\n ....: insertion='Star', output='word'),\n ....: insertion='Star'))]\n sage: all(Checks)\n True\n\n Check that :func:`RSK_inverse` is the inverse of :func:`RSK` on arrays\n and words::\n\n sage: S = SymmetricGroup(3+1)\n sage: from sage.combinat import permutation\n sage: FC = [x\n ....: for x in S\n ....: if (not permutation.from_reduced_word(\n ....: x.reduced_word()).has_pattern([3,2,1]) and\n ....: x.reduced_word())]\n sage: Triples = [(w, factors, ex)\n ....: for w in FC\n ....: for factors in range(2, 5+1)\n ....: for ex in range(4)]\n sage: Checks = []\n sage: for t in Triples:\n ....: B = crystals.FullyCommutativeStableGrothendieck(*t)\n ....: Checks += [all(b.to_increasing_hecke_biword() ==\n ....: RSK_inverse(*RSK(\n ....: *b.to_increasing_hecke_biword(),\n ....: insertion='Star'), insertion='Star')\n ....: for b in B)]\n sage: all(Checks)\n True\n\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: Checks = []\n sage: H = HeckeMonoid(SymmetricGroup(3+1))\n sage: reduce = lambda w: permutation.from_reduced_word(H.from_reduced_word(w).reduced_word())\n sage: fc = lambda w: not reduce(w).has_pattern([3,2,1])\n sage: words = [w for n in range(10) for w in Words(3, n) if fc(w)]\n sage: all([all(w == RSK_inverse(*RSK(w, insertion='Star'),\n ....: insertion='Star', output='word') for w in words)])\n True\n " def forward_rule(self, obj1, obj2=None, check_braid=True): '\n Return a pair of tableaux obtained by applying forward insertion\n to the increasing Hecke biword ``[obj1, obj2]``.\n\n INPUT:\n\n - ``obj1, obj2`` -- can be one of the following ways to represent a\n biword (or, equivalently, an increasing 0-Hecke factorization) that\n is fully commutative:\n\n - two lists ``obj1`` and ``obj2`` of equal length, to be\n interpreted as the top row and the bottom row of the biword.\n\n - a word ``obj1`` in an ordered alphabet, to be interpreted as\n the bottom row of the biword (in this case, ``obj2`` is ``None``;\n the top row of the biword is understood to be `(1,2,\\ldots,n)`\n by default).\n\n - a DecreasingHeckeFactorization ``obj1``, the whose increasing\n Hecke biword will be interpreted as the bottom row; the top row is\n understood to be the indices of the factors for each letter in\n this biword.\n\n - ``check_braid`` -- (default: ``True``) indicator to validate that\n input is associated to a fully commutative word in the 0-Hecke monoid,\n validation is performed if set to ``True``; otherwise, this validation\n is ignored.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: p,q = RuleStar().forward_rule([1,1,2,3,3], [2,3,3,1,3]); p,q\n ([[1, 3], [2, 3], [2]], [[1, 1], [2, 3], [3]])\n sage: p,q = RuleStar().forward_rule([2,3,3,1,3]); p,q\n ([[1, 3], [2, 3], [2]], [[1, 2], [3, 5], [4]])\n sage: p,q = RSK([1,1,2,3,3], [2,3,3,1,3], insertion=RSK.rules.Star); p,q\n ([[1, 3], [2, 3], [2]], [[1, 1], [2, 3], [3]])\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h = DecreasingHeckeFactorization([[3, 1], [3], [3, 2]])\n sage: p,q = RSK(h, insertion=RSK.rules.Star); p,q\n ([[1, 3], [2, 3], [2]], [[1, 1], [2, 3], [3]])\n\n TESTS:\n\n Empty objects::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: p,q = RuleStar().forward_rule([]); p,q\n ([], [])\n\n sage: from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization\n sage: h = DecreasingHeckeFactorization([[],[]])\n sage: p,q = RuleStar().forward_rule(h); p,q\n ([], [])\n\n Invalid inputs::\n\n sage: p,q = RuleStar().forward_rule([1,1,2,3,3], [2,2,3,1,3])\n Traceback (most recent call last):\n ...\n ValueError: [1, 1, 2, 3, 3], [2, 2, 3, 1, 3] is not an increasing factorization\n sage: p,q = RuleStar().forward_rule([1,1,2,2,4,4], [1,3,2,4,1,3])\n Traceback (most recent call last):\n ...\n ValueError: the Star insertion is not defined for non-fully commutative words\n ' if ((obj2 is None) and (obj1 is not None)): from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization if (not isinstance(obj1, DecreasingHeckeFactorization)): obj2 = obj1 obj1 = list(range(1, (len(obj1) + 1))) else: h = obj1 obj1 = sum([([(h.factors - i)] * len(h.value[i])) for i in reversed(range(h.factors))], []) obj2 = [i for f in h.value[::(- 1)] for i in reversed(f)] if (len(obj1) != len(obj2)): raise ValueError(f'{obj1} and {obj2} have different number of elements') for i in range((len(obj1) - 1)): if ((obj1[i] > obj1[(i + 1)]) or ((obj1[i] == obj1[(i + 1)]) and (obj2[i] >= obj2[(i + 1)]))): raise ValueError(f'{obj1}, {obj2} is not an increasing factorization') if check_braid: N = ((max(obj2) + 1) if obj2 else 1) from sage.monoids.hecke_monoid import HeckeMonoid from sage.groups.perm_gps.permgroup_named import SymmetricGroup H = HeckeMonoid(SymmetricGroup(N)) h = H.from_reduced_word(obj2) from sage.combinat import permutation p = permutation.from_reduced_word(h.reduced_word()) if p.has_pattern([3, 2, 1]): raise ValueError('the Star insertion is not defined for non-fully commutative words') p = [] q = [] for (i, j) in zip(obj1, obj2): for (r, qr) in zip(p, q): j1 = self.insertion(j, r) if (j1 is None): r.append(j) qr.append(i) break else: j = j1 else: p.append([j]) q.append([i]) from sage.combinat.tableau import Tableau, SemistandardTableau p = Tableau(p) q = SemistandardTableau(q) return [p, q] def backward_rule(self, p, q, output='array'): "\n Return the increasing Hecke biword obtained by applying reverse\n `\\star`-insertion to a pair of tableaux ``(p, q)``.\n\n INPUT:\n\n - ``p``, ``q`` -- two tableaux of the same shape, where ``p`` is the\n conjugate of a semistandard tableau, whose reading word is fully\n commutative and ``q`` is a semistandard tableau.\n\n - ``output`` -- (default: ``'array'``) if ``q`` is semi-standard:\n\n - ``'array'`` -- as a two-line array (i.e. generalized permutation\n or biword) that is an increasing Hecke biword\n - ``'DecreasingHeckeFactorization'`` -- as a decreasing\n factorization in the 0-Hecke monoid\n\n and if ``q`` is standard:\n\n - ``'word'`` -- as a (possibly non-reduced) word in the 0-Hecke\n monoid\n\n .. WARNING::\n\n When output is 'DecreasingHeckeFactorization', the number of factors\n in the output is the largest number in ``obj1``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: p,q = RuleStar().forward_rule([1,1,2,2,4,4], [1,3,2,4,2,4])\n sage: ascii_art(p, q)\n 1 2 4 1 1 2\n 1 4 2 4\n 3 4\n sage: line1,line2 = RuleStar().backward_rule(p, q); line1,line2\n ([1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4])\n sage: RuleStar().backward_rule(p, q, output = 'DecreasingHeckeFactorization')\n (4, 2)()(4, 2)(3, 1)\n\n TESTS:\n\n Empty objects::\n\n sage: RuleStar().backward_rule(Tableau([]), Tableau([]))\n [[], []]\n sage: RuleStar().backward_rule(Tableau([]), Tableau([]), output='word')\n word:\n sage: RuleStar().backward_rule(Tableau([]), Tableau([]),output='DecreasingHeckeFactorization')\n ()\n " from sage.combinat.tableau import SemistandardTableaux if (p.shape() != q.shape()): raise ValueError(('p(=%s) and q(=%s) must have the same shape' % (p, q))) if (q not in SemistandardTableaux()): raise ValueError(('q(=%s) must be a semistandard tableau' % q)) if (p.conjugate() not in SemistandardTableaux()): raise ValueError(('the conjugate of p(=%s) must be a semistandard tableau' % p.conjugate())) row_reading = [ele for row in reversed(p) for ele in row] N = (max((row_reading + [0])) + 1) from sage.monoids.hecke_monoid import HeckeMonoid from sage.groups.perm_gps.permgroup_named import SymmetricGroup H = HeckeMonoid(SymmetricGroup(N)) h = H.from_reduced_word(row_reading) from sage.combinat import permutation w = permutation.from_reduced_word(h.reduced_word()) if w.has_pattern([3, 2, 1]): raise ValueError(f'the row reading word of the insertion tableau {p} is not fully-commutative') p_copy = p.to_list() line1 = [] line2 = [] d = {} for (i, row) in enumerate(q): for (j, val) in enumerate(row): if (val in d): d[val][j] = i else: d[val] = {j: i} for (value, row_dict) in sorted(d.items(), key=(lambda x: (- x[0]))): for j in sorted(row_dict, reverse=True): i = row_dict[j] x = p_copy[i].pop() while (i > 0): i -= 1 row = p_copy[i] x = self.reverse_insertion(x, row) line2.append(x) line1.append(value) return self._backward_format_output(line1[::(- 1)], line2[::(- 1)], output) def insertion(self, b, r): '\n Insert the letter ``b`` from the second row of the biword into the row\n ``r`` using `\\star`-insertion defined in [MPPS2020]_.\n\n The row `r` is modified in place if bumping occurs and `b` is not in\n row `r`. The bumped-out entry, if it exists, is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: RuleStar().insertion(3, [1,2,4,5])\n 4\n sage: RuleStar().insertion(3, [1,2,3,5])\n 1\n sage: RuleStar().insertion(6, [1,2,3,5]) is None\n True\n ' if (r[(- 1)] < b): return None if (b in r): k = b while (k in r): k -= 1 k += 1 else: y_pos = bisect_right(r, b) k = r[y_pos] r[y_pos] = b return k def reverse_insertion(self, x, r): '\n Reverse bump the row ``r`` of the current insertion tableau ``p``\n with number ``x``, provided that ``r`` is the ``i``-th row of ``p``.\n\n The row ``r`` is modified in place. The bumped-out entry is returned.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: RuleStar().reverse_insertion(4, [1,2,3,5])\n 3\n sage: RuleStar().reverse_insertion(1, [1,2,3,5])\n 3\n sage: RuleStar().reverse_insertion(5, [1,2,3,5])\n 5\n ' if (x in r): y = x while (y in r): y += 1 y -= 1 else: y_pos = (bisect_left(r, x) - 1) y = r[y_pos] r[y_pos] = x x = y return x def _backward_format_output(self, obj1, obj2, output): "\n Return the final output of the ``RSK_inverse`` correspondence from\n the output of the corresponding ``backward_rule``.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import RuleStar\n sage: RuleStar()._backward_format_output([1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4], 'array')\n [[1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4]]\n sage: RuleStar()._backward_format_output([1, 1, 2, 2, 4, 4], [1, 3, 2, 4, 2, 4], 'DecreasingHeckeFactorization')\n (4, 2)()(4, 2)(3, 1)\n sage: RuleStar()._backward_format_output([1, 2, 3, 4, 5, 6], [4, 2, 4, 2, 3, 1], 'word')\n word: 424231\n " if (len(obj1) != len(obj2)): raise ValueError(f'{obj1} and {obj2} are of different lengths') if (output == 'array'): return [obj1, obj2] elif (output == 'word'): if (obj1 == list(range(1, (len(obj1) + 1)))): from sage.combinat.words.word import Word return Word(obj2) else: raise TypeError('upper row must be standard') elif (output == 'DecreasingHeckeFactorization'): from sage.combinat.crystals.fully_commutative_stable_grothendieck import DecreasingHeckeFactorization obj1.reverse() obj2.reverse() df = [] for j in range(len(obj1)): if (j == 0): df.append([]) if ((j > 0) and (obj1[j] < obj1[(j - 1)])): for _ in range((obj1[(j - 1)] - obj1[j])): df.append([]) df[(- 1)].append(obj2[j]) if obj1: for a in range((obj1[(- 1)] - 1)): df.append([]) else: df.append([]) return DecreasingHeckeFactorization(df)
class InsertionRules(): '\n Catalog of rules for RSK-like insertion algorithms.\n ' RSK = RuleRSK EG = RuleEG Hecke = RuleHecke dualRSK = RuleDualRSK coRSK = RuleCoRSK superRSK = RuleSuperRSK Star = RuleStar
def RSK(obj1=None, obj2=None, insertion=InsertionRules.RSK, check_standard=False, **options): '\n Perform the Robinson-Schensted-Knuth (RSK) correspondence.\n\n The Robinson-Schensted-Knuth (RSK) correspondence (also known\n as the RSK algorithm) is most naturally stated as a bijection\n between generalized permutations (also known as two-line arrays,\n biwords, ...) and pairs of semi-standard Young tableaux `(P, Q)`\n of identical shape. The tableau `P` is known as the insertion\n tableau, and `Q` is known as the recording tableau.\n\n The basic operation is known as row insertion `P \\leftarrow k`\n (where `P` is a given semi-standard Young tableau, and `k` is an\n integer). Row insertion is a recursive algorithm which starts by\n setting `k_0 = k`, and in its `i`-th step inserts the number `k_i`\n into the `i`-th row of `P` (we start counting the rows at `0`) by\n replacing the first integer greater than `k_i` in the row by `k_i`\n and defines `k_{i+1}` as the integer that has been replaced. If no\n integer greater than `k_i` exists in the `i`-th row, then `k_i` is\n simply appended to the row and the algorithm terminates at this point.\n\n A *generalized permutation* (or *biword*) is a list\n `((j_0, k_0), (j_1, k_1), \\ldots, (j_{\\ell-1}, k_{\\ell-1}))`\n of pairs such that the letters `j_0, j_1, \\ldots, j_{\\ell-1}`\n are weakly increasing (that is,\n `j_0 \\leq j_1 \\leq \\cdots \\leq j_{\\ell-1}`), whereas the letters\n `k_i` satisfy `k_i \\leq k_{i+1}` whenever `j_i = j_{i+1}`.\n The `\\ell`-tuple `(j_0, j_1, \\ldots, j_{\\ell-1})` is called the\n *top line* of this generalized permutation,\n whereas the `\\ell`-tuple `(k_0, k_1, \\ldots, k_{\\ell-1})` is\n called its *bottom line*.\n\n Now the RSK algorithm, applied to a generalized permutation\n `p = ((j_0, k_0), (j_1, k_1), \\ldots, (j_{\\ell-1}, k_{\\ell-1}))`\n (encoded as a lexicographically sorted list of pairs) starts by\n initializing two semi-standard tableaux `P_0` and `Q_0` as empty\n tableaux. For each nonnegative integer `t` starting at `0`, take\n the pair `(j_t, k_t)` from `p` and set\n `P_{t+1} = P_t \\leftarrow k_t`, and define `Q_{t+1}` by adding a\n new box filled with `j_t` to the tableau `Q_t` at the same\n location the row insertion on `P_t` ended (that is to say, adding\n a new box with entry `j_t` such that `P_{t+1}` and `Q_{t+1}` have\n the same shape). The iterative process stops when `t` reaches the\n size of `p`, and the pair `(P_t, Q_t)` at this point is the image\n of `p` under the Robinson-Schensted-Knuth correspondence.\n\n This correspondence has been introduced in [Knu1970]_, where it has\n been referred to as "Construction A".\n\n For more information, see Chapter 7 in [Sta-EC2]_.\n\n We also note that integer matrices are in bijection with generalized\n permutations. Furthermore, we can convert any word `w` (and, in\n particular, any permutation) to a generalized permutation by\n considering the top row to be `(1, 2, \\ldots, n)` where `n` is the\n length of `w`.\n\n The optional argument ``insertion`` allows to specify an alternative\n insertion procedure to be used instead of the standard\n Robinson-Schensted-Knuth insertion.\n\n INPUT:\n\n - ``obj1, obj2`` -- can be one of the following:\n\n - a word in an ordered alphabet (in this case, ``obj1`` is said\n word, and ``obj2`` is ``None``)\n - an integer matrix\n - two lists of equal length representing a generalized permutation\n (namely, the lists `(j_0, j_1, \\ldots, j_{\\ell-1})` and\n `(k_0, k_1, \\ldots, k_{\\ell-1})` represent the generalized\n permutation\n `((j_0, k_0), (j_1, k_1), \\ldots, (j_{\\ell-1}, k_{\\ell-1}))`)\n - any object which has a method ``_rsk_iter()`` which returns an\n iterator over the object represented as generalized permutation or\n a pair of lists (in this case, ``obj1`` is said object,\n and ``obj2`` is ``None``).\n\n - ``insertion`` -- (default: ``RSK.rules.RSK``) the following types\n of insertion are currently supported:\n\n - ``RSK.rules.RSK`` (or ``\'RSK\'``) -- Robinson-Schensted-Knuth\n insertion (:class:`~sage.combinat.rsk.RuleRSK`)\n - ``RSK.rules.EG`` (or ``\'EG\'``) -- Edelman-Greene insertion\n (only for reduced words of permutations/elements of a type `A`\n Coxeter group) (:class:`~sage.combinat.rsk.RuleEG`)\n - ``RSK.rules.Hecke`` (or ``\'hecke\'``) -- Hecke insertion (only\n guaranteed for generalized permutations whose top row is strictly\n increasing) (:class:`~sage.combinat.rsk.RuleHecke`)\n - ``RSK.rules.dualRSK`` (or ``\'dualRSK\'``) -- Dual RSK insertion\n (only for strict biwords) (:class:`~sage.combinat.rsk.RuleDualRSK`)\n - ``RSK.rules.coRSK`` (or ``\'coRSK\'``) -- CoRSK insertion (only\n for strict cobiwords) (:class:`~sage.combinat.rsk.RuleCoRSK`)\n - ``RSK.rules.superRSK`` (or ``\'super\'``) -- Super RSK insertion (only for\n restricted super biwords) (:class:`~sage.combinat.rsk.RuleSuperRSK`)\n - ``RSK.rules.Star`` (or ``\'Star\'``) -- `\\star`-insertion (only for\n fully commutative words in the 0-Hecke monoid)\n (:class:`~sage.combinat.rsk.RuleStar`)\n\n - ``check_standard`` -- (default: ``False``) check if either of the\n resulting tableaux is a standard tableau, and if so, typecast it\n as such\n\n For precise information about constraints on the input and output,\n as well as the definition of the algorithm (if it is not standard\n RSK), see the particular :class:`~sage.combinat.rsk.Rule` class.\n\n EXAMPLES:\n\n If we only input one row, it is understood that the top row\n should be `(1, 2, \\ldots, n)`::\n\n sage: RSK([3,3,2,4,1])\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n sage: RSK(Word([3,3,2,4,1]))\n [[[1, 3, 4], [2], [3]], [[1, 2, 4], [3], [5]]]\n sage: RSK(Word([2,3,3,2,1,3,2,3]))\n [[[1, 2, 2, 3, 3], [2, 3], [3]], [[1, 2, 3, 6, 8], [4, 7], [5]]]\n\n We can provide a generalized permutation::\n\n sage: RSK([1, 2, 2, 2], [2, 1, 1, 2])\n [[[1, 1, 2], [2]], [[1, 2, 2], [2]]]\n sage: RSK(Word([1,1,3,4,4]), [1,4,2,1,3])\n [[[1, 1, 3], [2], [4]], [[1, 1, 4], [3], [4]]]\n sage: RSK([1,3,3,4,4], Word([6,2,2,1,7]))\n [[[1, 2, 7], [2], [6]], [[1, 3, 4], [3], [4]]]\n\n We can provide a matrix::\n\n sage: RSK(matrix([[0,1],[2,1]]))\n [[[1, 1, 2], [2]], [[1, 2, 2], [2]]]\n\n We can also provide something looking like a matrix::\n\n sage: RSK([[0,1],[2,1]])\n [[[1, 1, 2], [2]], [[1, 2, 2], [2]]]\n\n There is also :func:`~sage.combinat.rsk.RSK_inverse` which performs\n the inverse of the bijection on a pair of semistandard tableaux. We\n note that the inverse function takes 2 separate tableaux as inputs, so\n to compose with :func:`~sage.combinat.rsk.RSK`, we need to use the\n python ``*`` on the output::\n\n sage: RSK_inverse(*RSK([1, 2, 2, 2], [2, 1, 1, 2]))\n [[1, 2, 2, 2], [2, 1, 1, 2]]\n sage: P,Q = RSK([1, 2, 2, 2], [2, 1, 1, 2])\n sage: RSK_inverse(P, Q)\n [[1, 2, 2, 2], [2, 1, 1, 2]]\n\n TESTS:\n\n Empty objects::\n\n sage: RSK(Permutation([]))\n [[], []]\n sage: RSK(Word([]))\n [[], []]\n sage: RSK(matrix([[]]))\n [[], []]\n sage: RSK([], [])\n [[], []]\n sage: RSK([[]])\n [[], []]\n sage: RSK(Word([]), insertion=RSK.rules.EG)\n [[], []]\n sage: RSK(Word([]), insertion=RSK.rules.Hecke)\n [[], []]\n\n ' if isinstance(insertion, str): if (insertion == 'RSK'): insertion = RSK.rules.RSK elif (insertion == 'EG'): insertion = RSK.rules.EG elif (insertion == 'hecke'): insertion = RSK.rules.Hecke elif (insertion == 'dualRSK'): insertion = RSK.rules.dualRSK elif (insertion == 'coRSK'): insertion = RSK.rules.coRSK elif (insertion == 'superRSK'): insertion = RSK.rules.superRSK elif (insertion == 'Star'): insertion = RSK.rules.Star else: raise ValueError('invalid input') rule = insertion() if (not isinstance(rule, Rule)): raise TypeError('the insertion must be an instance of Rule') if ((obj1 is None) and (obj2 is None)): if ('matrix' in options): obj1 = matrix(options['matrix']) else: raise ValueError('invalid input') if is_Matrix(obj1): obj1 = obj1.rows() output = rule.forward_rule(obj1, obj2, check_standard) return output
def RSK_inverse(p, q, output='array', insertion=InsertionRules.RSK): "\n Return the generalized permutation corresponding to the pair of\n tableaux `(p, q)` under the inverse of the Robinson-Schensted-Knuth\n correspondence.\n\n For more information on the bijection, see :func:`RSK`.\n\n INPUT:\n\n - ``p``, ``q`` -- two semi-standard tableaux of the same shape, or\n (in the case when Hecke insertion is used) an increasing tableau and\n a set-valued tableau of the same shape (see the note below for the\n format of the set-valued tableau)\n\n - ``output`` -- (default: ``'array'``) if ``q`` is semi-standard:\n\n - ``'array'`` -- as a two-line array (i.e. generalized permutation or\n biword)\n - ``'matrix'`` -- as an integer matrix\n\n and if ``q`` is standard, we can also have the output:\n\n - ``'word'`` -- as a word\n\n and additionally if ``p`` is standard, we can also have the output:\n\n - ``'permutation'`` -- as a permutation\n\n - ``insertion`` -- (default: ``RSK.rules.RSK``) the insertion algorithm\n used in the bijection. Currently the following are supported:\n\n - ``RSK.rules.RSK`` (or ``'RSK'``) -- Robinson-Schensted-Knuth\n insertion (:class:`~sage.combinat.rsk.RuleRSK`)\n - ``RSK.rules.EG`` (or ``'EG'``) -- Edelman-Greene insertion\n (only for reduced words of permutations/elements of a type `A`\n Coxeter group) (:class:`~sage.combinat.rsk.RuleEG`)\n - ``RSK.rules.Hecke`` (or ``'hecke'``) -- Hecke insertion (only\n guaranteed for generalized permutations whose top row is strictly\n increasing) (:class:`~sage.combinat.rsk.RuleHecke`)\n - ``RSK.rules.dualRSK`` (or ``'dualRSK'``) -- Dual RSK insertion\n (only for strict biwords) (:class:`~sage.combinat.rsk.RuleDualRSK`)\n - ``RSK.rules.coRSK`` (or ``'coRSK'``) -- CoRSK insertion (only\n for strict cobiwords) (:class:`~sage.combinat.rsk.RuleCoRSK`)\n - ``RSK.rules.superRSK`` (or ``'super'``) -- Super RSK insertion (only for\n restricted super biwords) (:class:`~sage.combinat.rsk.RuleSuperRSK`)\n - ``RSK.rules.Star`` (or ``'Star'``) -- `\\star`-insertion (only for\n fully commutative words in the 0-Hecke monoid)\n (:class:`~sage.combinat.rsk.RuleStar`)\n\n For precise information about constraints on the input and\n output, see the particular :class:`~sage.combinat.rsk.Rule` class.\n\n .. NOTE::\n\n In the case of Hecke insertion, the input variable ``q`` should\n be a set-valued tableau, encoded as a tableau whose entries are\n strictly increasing tuples of positive integers. Each such tuple\n encodes the set of its entries.\n\n EXAMPLES:\n\n If both ``p`` and ``q`` are standard::\n\n sage: t1 = Tableau([[1, 2, 5], [3], [4]])\n sage: t2 = Tableau([[1, 2, 3], [4], [5]])\n sage: RSK_inverse(t1, t2)\n [[1, 2, 3, 4, 5], [1, 4, 5, 3, 2]]\n sage: RSK_inverse(t1, t2, 'word')\n word: 14532\n sage: RSK_inverse(t1, t2, 'matrix')\n [1 0 0 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n [0 0 1 0 0]\n [0 1 0 0 0]\n sage: RSK_inverse(t1, t2, 'permutation')\n [1, 4, 5, 3, 2]\n sage: RSK_inverse(t1, t1, 'permutation')\n [1, 4, 3, 2, 5]\n sage: RSK_inverse(t2, t2, 'permutation')\n [1, 2, 5, 4, 3]\n sage: RSK_inverse(t2, t1, 'permutation')\n [1, 5, 4, 2, 3]\n\n If the first tableau is semistandard::\n\n sage: p = Tableau([[1,2,2],[3]]); q = Tableau([[1,2,4],[3]])\n sage: ret = RSK_inverse(p, q); ret\n [[1, 2, 3, 4], [1, 3, 2, 2]]\n sage: RSK_inverse(p, q, 'word')\n word: 1322\n\n In general::\n\n sage: p = Tableau([[1,2,2],[2]]); q = Tableau([[1,3,3],[2]])\n sage: RSK_inverse(p, q)\n [[1, 2, 3, 3], [2, 1, 2, 2]]\n sage: RSK_inverse(p, q, 'matrix')\n [0 1]\n [1 0]\n [0 2]\n\n Using Hecke insertion::\n\n sage: w = [5, 4, 3, 1, 4, 2, 5, 5]\n sage: pq = RSK(w, insertion=RSK.rules.Hecke)\n sage: RSK_inverse(*pq, insertion=RSK.rules.Hecke, output='list')\n [5, 4, 3, 1, 4, 2, 5, 5]\n\n .. NOTE::\n\n The constructor of ``Tableau`` accepts not only semistandard\n tableaux, but also arbitrary lists that are fillings of a\n partition diagram. (And such lists are used, e.g., for the\n set-valued tableau ``q`` that is passed to\n ``RSK_inverse(p, q, insertion='hecke')``.)\n The user is responsible for ensuring that the tableaux passed to\n ``RSK_inverse`` are of the right types (semistandard, standard,\n increasing, set-valued as needed).\n\n TESTS:\n\n From empty tableaux::\n\n sage: RSK_inverse(Tableau([]), Tableau([]))\n [[], []]\n\n Check that :func:`RSK_inverse` is the inverse of :func:`RSK` on the\n different types of inputs/outputs::\n\n sage: f = lambda p: RSK_inverse(*RSK(p), output='permutation')\n sage: all(p == f(p) for n in range(7) for p in Permutations(n))\n True\n sage: all(RSK_inverse(*RSK(w), output='word') == w for n in range(4)\n ....: for w in Words(5, n))\n True\n sage: from sage.combinat.integer_matrices import IntegerMatrices\n sage: M = IntegerMatrices([1,2,2,1], [3,1,1,1])\n sage: all(RSK_inverse(*RSK(m), output='matrix') == m for m in M)\n True\n\n sage: n = ZZ.random_element(200)\n sage: p = Permutations(n).random_element()\n sage: is_fine = True if p == f(p) else p ; is_fine\n True\n\n Both tableaux must be of the same shape::\n\n sage: RSK_inverse(Tableau([[1,2,3]]), Tableau([[1,2]]))\n Traceback (most recent call last):\n ...\n ValueError: p(=[[1, 2, 3]]) and q(=[[1, 2]]) must have the same shape\n\n Check that :trac:`20430` is fixed::\n\n sage: RSK([1,1,1,1,1,1,1,2,2,2,3], [1,1,1,1,1,1,3,2,2,2,1])\n [[[1, 1, 1, 1, 1, 1, 1, 2, 2], [2], [3]],\n [[1, 1, 1, 1, 1, 1, 1, 2, 2], [2], [3]]]\n sage: t = SemistandardTableau([[1, 1, 1, 1, 1, 1, 1, 2, 2], [2], [3]])\n sage: RSK_inverse(t, t, 'array')\n [[1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3],\n [1, 1, 1, 1, 1, 1, 3, 2, 2, 2, 1]]\n " if isinstance(insertion, str): if (insertion == 'RSK'): insertion = RSK.rules.RSK elif (insertion == 'EG'): insertion = RSK.rules.EG elif (insertion == 'hecke'): insertion = RSK.rules.Hecke elif (insertion == 'dualRSK'): insertion = RSK.rules.dualRSK elif (insertion == 'coRSK'): insertion = RSK.rules.coRSK elif (insertion == 'superRSK'): insertion = RSK.rules.superRSK elif (insertion == 'Star'): insertion = RSK.rules.Star else: raise ValueError('invalid input') rule = insertion() if (not isinstance(rule, Rule)): raise TypeError('the insertion must be an instance of Rule') if (p.shape() != q.shape()): raise ValueError(f'p(={p}) and q(={q}) must have the same shape') answer = rule.backward_rule(p, q, output) return answer
def to_matrix(t, b): '\n Return the integer matrix corresponding to a two-line array.\n\n INPUT:\n\n - ``t`` -- the top row of the array\n - ``b`` -- the bottom row of the array\n\n OUTPUT:\n\n An `m \\times n`-matrix (where `m` and `n` are the maximum entries in\n `t` and `b` respectively) whose `(i, j)`-th entry, for any `i` and `j`,\n is the number of all positions `k` satisfying `t_k = i` and `b_k = j`.\n\n EXAMPLES::\n\n sage: from sage.combinat.rsk import to_matrix\n sage: to_matrix([1, 1, 3, 3, 4], [2, 3, 1, 1, 3])\n [0 1 1]\n [0 0 0]\n [2 0 0]\n [0 0 1]\n ' n = len(b) if (len(t) != n): raise ValueError('the two arrays must be the same length') entries = {} for i in range(n): pos = ((t[i] - 1), (b[i] - 1)) if (pos in entries): entries[pos] += 1 else: entries[pos] = 1 return matrix(entries, sparse=True)
def SchubertPolynomialRing(R): '\n Return the Schubert polynomial ring over ``R`` on the X basis.\n\n This is the basis made of the Schubert polynomials.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(ZZ); X\n Schubert polynomial ring with X basis over Integer Ring\n sage: TestSuite(X).run()\n sage: X(1)\n X[1]\n sage: X([1,2,3])*X([2,1,3])\n X[2, 1]\n sage: X([2,1,3])*X([2,1,3])\n X[3, 1, 2]\n sage: X([2,1,3])+X([3,1,2,4])\n X[2, 1] + X[3, 1, 2]\n sage: a = X([2,1,3])+X([3,1,2,4])\n sage: a^2\n X[3, 1, 2] + 2*X[4, 1, 2, 3] + X[5, 1, 2, 3, 4]\n ' return SchubertPolynomialRing_xbasis(R)
class SchubertPolynomial_class(CombinatorialFreeModule.Element): def expand(self): "\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: X([2,1,3]).expand()\n x0\n sage: [X(p).expand() for p in Permutations(3)]\n [1, x0 + x1, x0, x0*x1, x0^2, x0^2*x1]\n\n TESTS:\n\n Calling .expand() should always return an element of an\n MPolynomialRing::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: f = X([1]); f\n X[1]\n sage: type(f.expand())\n <class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>\n sage: f.expand()\n 1\n sage: f = X([1,2])\n sage: type(f.expand())\n <class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>\n sage: f = X([1,3,2,4])\n sage: type(f.expand())\n <class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>\n\n Now we check for correct handling of the empty\n permutation (:trac:`23443`)::\n\n sage: X([1]).expand() * X([2,1]).expand()\n x0\n " p = symmetrica.t_SCHUBERT_POLYNOM(self) if (not isinstance(p, MPolynomial)): R = PolynomialRing(self.parent().base_ring(), 1, 'x0') p = R(p) return p def divided_difference(self, i, algorithm='sage'): "\n Return the ``i``-th divided difference operator, applied to ``self``.\n\n Here, ``i`` can be either a permutation or a positive integer.\n\n INPUT:\n\n - ``i`` -- permutation or positive integer\n\n - ``algorithm`` -- (default: ``'sage'``) either ``'sage'``\n or ``'symmetrica'``; this determines which software is\n called for the computation\n\n OUTPUT:\n\n The result of applying the ``i``-th divided difference\n operator to ``self``.\n\n If `i` is a positive integer, then the `i`-th divided\n difference operator `\\delta_i` is the linear operator sending\n each polynomial `f = f(x_1, x_2, \\ldots, x_n)` (in\n `n \\geq i+1` variables) to the polynomial\n\n .. MATH::\n\n \\frac{f - f_i}{x_i - x_{i+1}}, \\qquad \\text{ where }\n f_i = f(x_1, x_2, ..., x_{i-1}, x_{i+1}, x_i,\n x_{i+1}, ..., x_n) .\n\n If `\\sigma` is a permutation in the `n`-th symmetric group,\n then the `\\sigma`-th divided difference operator `\\delta_\\sigma`\n is the composition\n `\\delta_{i_1} \\delta_{i_2} \\cdots \\delta_{i_k}`, where\n `\\sigma = s_{i_1} \\circ s_{i_2} \\circ \\cdots \\circ s_{i_k}` is\n any reduced expression for `\\sigma` (the precise choice of\n reduced expression is immaterial).\n\n .. NOTE::\n\n The :meth:`expand` method results in a polynomial\n in `n` variables named ``x0, x1, ..., x(n-1)`` rather than\n `x_1, x_2, \\ldots, x_n`.\n The variable named ``xi`` corresponds to `x_{i+1}`.\n Thus, ``self.divided_difference(i)`` involves the variables\n ``x(i-1)`` and ``xi`` getting switched (in the numerator).\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: a = X([3,2,1])\n sage: a.divided_difference(1)\n X[2, 3, 1]\n sage: a.divided_difference([3,2,1])\n X[1]\n sage: a.divided_difference(5)\n 0\n\n Any divided difference of `0` is `0`::\n\n sage: X.zero().divided_difference(2)\n 0\n\n This is compatible when a permutation is given as input::\n\n sage: a = X([3,2,4,1])\n sage: a.divided_difference([2,3,1])\n 0\n sage: a.divided_difference(1).divided_difference(2)\n 0\n\n ::\n\n sage: a = X([4,3,2,1])\n sage: a.divided_difference([2,3,1])\n X[3, 2, 4, 1]\n sage: a.divided_difference(1).divided_difference(2)\n X[3, 2, 4, 1]\n sage: a.divided_difference([4,1,3,2])\n X[1, 4, 2, 3]\n sage: b = X([4, 1, 3, 2])\n sage: b.divided_difference(1).divided_difference(2)\n X[1, 3, 4, 2]\n sage: b.divided_difference(1).divided_difference(2).divided_difference(3)\n X[1, 3, 2]\n sage: b.divided_difference(1).divided_difference(2).divided_difference(3).divided_difference(2)\n X[1]\n sage: b.divided_difference(1).divided_difference(2).divided_difference(3).divided_difference(3)\n 0\n sage: b.divided_difference(1).divided_difference(2).divided_difference(1)\n 0\n\n TESTS:\n\n Check that :trac:`23403` is fixed::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: a = X([3,2,4,1])\n sage: a.divided_difference(2)\n 0\n sage: a.divided_difference([3,2,1])\n 0\n sage: a.divided_difference(0)\n Traceback (most recent call last):\n ...\n ValueError: cannot apply \\delta_{0} to a (= X[3, 2, 4, 1])\n " if (not self): return self Perms = Permutations() if (i in ZZ): if (algorithm == 'sage'): if (i <= 0): raise ValueError(('cannot apply \\delta_{%s} to a (= %s)' % (i, self))) res_dict = {} for (pi, coeff) in self: pi = pi[:] n = len(pi) if (n <= i): continue if (pi[(i - 1)] < pi[i]): continue (pi[(i - 1)], pi[i]) = (pi[i], pi[(i - 1)]) pi = Perms(pi).remove_extra_fixed_points() res_dict[pi] = coeff return self.parent()._from_dict(res_dict) else: return symmetrica.divdiff_schubert(i, self) elif (i in Perms): if (algorithm == 'sage'): i = Permutation(i) redw = i.reduced_word() res_dict = {} for (pi, coeff) in self: next_pi = False pi = pi[:] n = len(pi) for j in redw: if (n <= j): next_pi = True break if (pi[(j - 1)] < pi[j]): next_pi = True break (pi[(j - 1)], pi[j]) = (pi[j], pi[(j - 1)]) if next_pi: continue pi = Perms(pi).remove_extra_fixed_points() res_dict[pi] = coeff return self.parent()._from_dict(res_dict) else: return symmetrica.divdiff_perm_schubert(i, self) else: raise TypeError('i must either be an integer or permutation') def scalar_product(self, x): '\n Return the standard scalar product of ``self`` and ``x``.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: a = X([3,2,4,1])\n sage: a.scalar_product(a)\n 0\n sage: b = X([4,3,2,1])\n sage: b.scalar_product(a)\n X[1, 3, 4, 6, 2, 5]\n sage: Permutation([1, 3, 4, 6, 2, 5, 7]).to_lehmer_code()\n [0, 1, 1, 2, 0, 0, 0]\n sage: s = SymmetricFunctions(ZZ).schur()\n sage: c = s([2,1,1])\n sage: b.scalar_product(a).expand()\n x0^2*x1*x2 + x0*x1^2*x2 + x0*x1*x2^2 + x0^2*x1*x3 + x0*x1^2*x3 + x0^2*x2*x3 + 3*x0*x1*x2*x3 + x1^2*x2*x3 + x0*x2^2*x3 + x1*x2^2*x3 + x0*x1*x3^2 + x0*x2*x3^2 + x1*x2*x3^2\n sage: c.expand(4)\n x0^2*x1*x2 + x0*x1^2*x2 + x0*x1*x2^2 + x0^2*x1*x3 + x0*x1^2*x3 + x0^2*x2*x3 + 3*x0*x1*x2*x3 + x1^2*x2*x3 + x0*x2^2*x3 + x1*x2^2*x3 + x0*x1*x3^2 + x0*x2*x3^2 + x1*x2*x3^2\n ' if isinstance(x, SchubertPolynomial_class): return symmetrica.scalarproduct_schubert(self, x) else: raise TypeError('x must be a Schubert polynomial') def multiply_variable(self, i): '\n Return the Schubert polynomial obtained by multiplying ``self``\n by the variable `x_i`.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(ZZ)\n sage: a = X([3,2,4,1])\n sage: a.multiply_variable(0)\n X[4, 2, 3, 1]\n sage: a.multiply_variable(1)\n X[3, 4, 2, 1]\n sage: a.multiply_variable(2)\n X[3, 2, 5, 1, 4] - X[3, 4, 2, 1] - X[4, 2, 3, 1]\n sage: a.multiply_variable(3)\n X[3, 2, 4, 5, 1]\n ' if isinstance(i, Integer): return symmetrica.mult_schubert_variable(self, i) else: raise TypeError('i must be an integer')
class SchubertPolynomialRing_xbasis(CombinatorialFreeModule): Element = SchubertPolynomial_class def __init__(self, R): '\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: X == loads(dumps(X))\n True\n ' self._name = 'Schubert polynomial ring with X basis' self._repr_option_bracket = False CombinatorialFreeModule.__init__(self, R, Permutations(), category=GradedAlgebrasWithBasis(R), prefix='X') @cached_method def one_basis(self): '\n Return the index of the unit of this algebra.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: X.one() # indirect doctest\n X[1]\n ' return self._indices([1]) def _element_constructor_(self, x): '\n Coerce x into ``self``.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: X._element_constructor_([2,1,3])\n X[2, 1]\n sage: X._element_constructor_(Permutation([2,1,3]))\n X[2, 1]\n\n sage: R.<x1, x2, x3> = QQ[]\n sage: X(x1^2*x2)\n X[3, 2, 1]\n\n sage: S.<x> = InfinitePolynomialRing(QQ)\n sage: X(x[0]^2*x[1])\n X[3, 2, 1]\n sage: X(x[0]*x[1]^2*x[2]^2*x[3] + x[0]^2*x[1]^2*x[2]*x[3] + x[0]^2*x[1]*x[2]^2*x[3])\n X[2, 4, 5, 3, 1]\n\n sage: from sage.combinat.key_polynomial import KeyPolynomialBasis\n sage: k = KeyPolynomialBasis(QQ)\n sage: X(k([3,2,1]))\n X[4, 3, 2, 1]\n\n TESTS:\n\n We check that :trac:`12924` is fixed::\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: X._element_constructor_([1,2,1])\n Traceback (most recent call last):\n ...\n ValueError: the input [1, 2, 1] is not a valid permutation\n\n Now we check for correct handling of the empty\n permutation (:trac:`23443`)::\n\n sage: X([])\n X[1]\n\n Check the round trip from key polynomials::\n\n sage: k = KeyPolynomials(ZZ)\n sage: X = SchubertPolynomialRing(ZZ)\n sage: it = iter(Permutations())\n sage: for _ in range(50):\n ....: P = next(it)\n ....: assert X(k(X(P))) == X(P), P\n ' if isinstance(x, list): if (x not in Permutations()): raise ValueError(f'the input {x} is not a valid permutation') perm = Permutation(x).remove_extra_fixed_points() return self._from_dict({perm: self.base_ring().one()}) elif isinstance(x, Permutation): perm = x.remove_extra_fixed_points() return self._from_dict({perm: self.base_ring().one()}) elif isinstance(x, MPolynomial): return symmetrica.t_POLYNOM_SCHUBERT(x) elif isinstance(x, InfinitePolynomial): R = x.polynomial().parent() S = PolynomialRing(R.base_ring(), names=list(map(repr, reversed(R.gens())))) return symmetrica.t_POLYNOM_SCHUBERT(S(x.polynomial())) elif isinstance(x, KeyPolynomial): return self(x.expand()) else: raise TypeError def some_elements(self): '\n Return some elements.\n\n EXAMPLES::\n\n sage: X = SchubertPolynomialRing(QQ)\n sage: X.some_elements()\n [X[1], X[1] + 2*X[2, 1], -X[3, 2, 1] + X[4, 2, 1, 3]]\n ' return [self.one(), (self([1]) + (2 * self([2, 1]))), (self([4, 2, 1, 3]) - self([3, 2, 1]))] def product_on_basis(self, left, right): '\n EXAMPLES::\n\n sage: p1 = Permutation([3,2,1])\n sage: p2 = Permutation([2,1,3])\n sage: X = SchubertPolynomialRing(QQ)\n sage: X.product_on_basis(p1,p2)\n X[4, 2, 1, 3]\n ' return symmetrica.mult_schubert_schubert(left, right)
class AbstractSetPartition(ClonableArray, metaclass=InheritComparisonClasscallMetaclass): '\n Methods of set partitions which are independent of the base set\n ' def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: S([[1,3],[2,4]])\n {{1, 3}, {2, 4}}\n ' return (('{' + ', '.join(((('{' + repr(sorted(x))[1:(- 1)]) + '}') for x in self))) + '}') 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: P = SetPartitions(4)\n sage: A = SetPartition([[1], [2,3], [4]])\n sage: B = P([[1], [2,3], [4]])\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 EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = SetPartition([[1], [2,3], [4]])\n sage: B = P([[1], [2,3], [4]])\n sage: A == B\n True\n sage: C = P([[2, 3], [1], [4]])\n sage: A == C\n True\n sage: D = P([[1], [2, 4], [3]])\n sage: A == D\n False\n\n Note that this may give incorrect answers if the base set is not totally ordered::\n\n sage: a,b = frozenset([0,1]), frozenset([2,3])\n sage: p1 = SetPartition([[a], [b]])\n sage: p2 = SetPartition([[b], [a]])\n sage: p1 == p2\n False\n ' if (not isinstance(y, AbstractSetPartition)): 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 EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = SetPartition([[1], [2,3], [4]])\n sage: B = P([[1], [2,3], [4]])\n sage: A != B\n False\n sage: C = P([[2, 3], [1], [4]])\n sage: A != C\n False\n sage: D = P([[1], [2, 4], [3]])\n sage: A != D\n True\n\n Note that this may give incorrect answers if the base set is not totally ordered::\n\n sage: a,b = frozenset([0,1]), frozenset([2,3])\n sage: p1 = SetPartition([[a], [b]])\n sage: p2 = SetPartition([[b], [a]])\n sage: p1 != p2\n True\n ' return (not (self == y)) def __lt__(self, y): '\n Check that ``self`` is less than ``y``.\n\n The ordering used is lexicographic, where:\n\n - a set partition is considered as the list of its parts\n sorted by increasing smallest element;\n\n - each part is regarded as a list of its elements, sorted\n in increasing order;\n\n - the parts themselves are compared lexicographically.\n\n EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = P([[1], [2,3], [4]])\n sage: B = SetPartition([[1,2,3], [4]])\n sage: A < B\n True\n sage: C = P([[1,2,4], [3]])\n sage: B < C\n True\n sage: B < B\n False\n sage: D = P([[1,4], [2], [3]])\n sage: E = P([[1,4], [2,3]])\n sage: D < E\n True\n sage: F = P([[1,2,4], [3]])\n sage: E < C\n False\n sage: A < E\n True\n sage: A < C\n True\n ' if (not isinstance(y, AbstractSetPartition)): return False return ([sorted(i) for i in self] < [sorted(i) for i in y]) def __gt__(self, y): '\n Check that ``self`` is greater than ``y``.\n\n The ordering used is lexicographic, where:\n\n - a set partition is considered as the list of its parts\n sorted by increasing smallest element;\n\n - each part is regarded as a list of its elements, sorted\n in increasing order;\n\n - the parts themselves are compared lexicographically.\n\n EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = P([[1], [2,3], [4]])\n sage: B = SetPartition([[1,2,3], [4]])\n sage: B > A\n True\n sage: A > B\n False\n ' if (not isinstance(y, AbstractSetPartition)): return False return ([sorted(i) for i in self] > [sorted(i) for i in y]) def __le__(self, y): '\n Check that ``self`` is less than or equals ``y``.\n\n The ordering used is lexicographic, where:\n\n - a set partition is considered as the list of its parts\n sorted by increasing smallest element;\n\n - each part is regarded as a list of its elements, sorted\n in increasing order;\n\n - the parts themselves are compared lexicographically.\n\n EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = P([[1], [2,3], [4]])\n sage: B = SetPartition([[1,2,3], [4]])\n sage: A <= B\n True\n sage: A <= A\n True\n ' return ((self == y) or (self < y)) def __ge__(self, y): '\n Check that ``self`` is greater than or equals ``y``.\n\n The ordering used is lexicographic, where:\n\n - a set partition is considered as the list of its parts\n sorted by increasing smallest element;\n\n - each part is regarded as a list of its elements, sorted\n in increasing order;\n\n - the parts themselves are compared lexicographically.\n\n EXAMPLES::\n\n sage: P = SetPartitions(4)\n sage: A = P([[1], [2,3], [4]])\n sage: B = SetPartition([[1,2,3], [4]])\n sage: B >= A\n True\n sage: B >= B\n True\n ' return ((self == y) or (self > y)) def __mul__(self, other): '\n The product of the set partitions ``self`` and ``other``.\n\n The product of two set partitions `B` and `C` is defined as the\n set partition whose parts are the nonempty intersections between\n each part of `B` and each part of `C`. This product is also\n the infimum of `B` and `C` in the classical set partition\n lattice (that is, the coarsest set partition which is finer than\n each of `B` and `C`). Consequently, ``inf`` acts as an alias for\n this method.\n\n .. SEEALSO::\n\n :meth:`sup`\n\n EXAMPLES::\n\n sage: x = SetPartition([ [1,2], [3,5,4] ])\n sage: y = SetPartition(( (3,1,2), (5,4) ))\n sage: x * y\n {{1, 2}, {3}, {4, 5}}\n\n sage: S = SetPartitions(4)\n sage: sp1 = S([[2,3,4], [1]])\n sage: sp2 = S([[1,3], [2,4]])\n sage: s = S([[2,4], [3], [1]])\n sage: sp1.inf(sp2) == s\n True\n\n TESTS:\n\n Here is a different implementation of the ``__mul__`` method\n (one that was formerly used for the ``inf`` method, before it\n was realized that the methods do the same thing)::\n\n sage: def mul2(s, t):\n ....: temp = [ss.intersection(ts) for ss in s for ts in t]\n ....: temp = filter(bool, temp)\n ....: return s.__class__(s.parent(), temp)\n\n Let us check that this gives the same as ``__mul__`` on set\n partitions of `\\{1, 2, 3, 4\\}`::\n\n sage: all( all( mul2(s, t) == s * t for s in SetPartitions(4) )\n ....: for t in SetPartitions(4) )\n True\n ' new_composition = [] for B in self: for C in other: BintC = B.intersection(C) if BintC: new_composition.append(BintC) return SetPartition(new_composition) inf = __mul__ def sup(self, t): '\n Return the supremum of ``self`` and ``t`` in the classical set\n partition lattice.\n\n The supremum of two set partitions `B` and `C` is obtained as the\n transitive closure of the relation which relates `i` to `j` if\n and only if `i` and `j` are in the same part in at least\n one of the set partitions `B` and `C`.\n\n .. SEEALSO::\n\n :meth:`__mul__`\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: sp1 = S([[2,3,4], [1]])\n sage: sp2 = S([[1,3], [2,4]])\n sage: s = S([[1,2,3,4]])\n sage: sp1.sup(sp2) == s\n True\n ' res = list(self) for p in t: inters = [(i, q) for (i, q) in enumerate(res) if any(((a in q) for a in p))] for (i, _) in reversed(inters): del res[i] res.append([e for (_, q) in inters for e in q]) return self.parent()(res) def standard_form(self): '\n Return ``self`` as a list of lists.\n\n When the ground set is totally ordered, the elements of each\n block are listed in increasing order.\n\n This is not related to standard set partitions (which simply\n means set partitions of `[n] = \\{ 1, 2, \\ldots , n \\}` for some\n integer `n`) or standardization (:meth:`standardization`).\n\n EXAMPLES::\n\n sage: [x.standard_form() for x in SetPartitions(4, [2,2])] # needs sage.graphs sage.rings.finite_rings\n [[[1, 2], [3, 4]], [[1, 4], [2, 3]], [[1, 3], [2, 4]]]\n\n TESTS::\n\n sage: SetPartition([(1, 9, 8), (2, 3, 4, 5, 6, 7)]).standard_form()\n [[1, 8, 9], [2, 3, 4, 5, 6, 7]]\n ' return [sorted(i) for i in self] def base_set(self): '\n Return the base set of ``self``, which is the union of all parts\n of ``self``.\n\n EXAMPLES::\n\n sage: SetPartition([[1], [2,3], [4]]).base_set()\n {1, 2, 3, 4}\n sage: SetPartition([[1,2,3,4]]).base_set()\n {1, 2, 3, 4}\n sage: SetPartition([]).base_set()\n {}\n ' return Set((e for p in self for e in p)) def base_set_cardinality(self): '\n Return the cardinality of the base set of ``self``, which is the sum\n of the sizes of the parts of ``self``.\n\n This is also known as the *size* (sometimes the *weight*) of\n a set partition.\n\n EXAMPLES::\n\n sage: SetPartition([[1], [2,3], [4]]).base_set_cardinality()\n 4\n sage: SetPartition([[1,2,3,4]]).base_set_cardinality()\n 4\n ' return sum((len(x) for x in self)) def coarsenings(self): '\n Return a list of coarsenings of ``self``.\n\n .. SEEALSO::\n\n :meth:`refinements`\n\n EXAMPLES::\n\n sage: SetPartition([[1,3],[2,4]]).coarsenings()\n [{{1, 2, 3, 4}}, {{1, 3}, {2, 4}}]\n sage: SetPartition([[1],[2,4],[3]]).coarsenings()\n [{{1, 2, 3, 4}},\n {{1, 2, 4}, {3}},\n {{1, 3}, {2, 4}},\n {{1}, {2, 3, 4}},\n {{1}, {2, 4}, {3}}]\n sage: SetPartition([]).coarsenings()\n [{}]\n ' SP = SetPartitions(len(self)) def union(s): ret = [] for part in s: cur = [] for i in part: cur.extend(self[(i - 1)]) ret.append(cur) return ret return [self.parent()(union(s)) for s in SP] def max_block_size(self): '\n The maximum block size of the diagram.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.combinat.diagram_algebras import PartitionDiagram, PartitionDiagrams\n sage: pd = PartitionDiagram([[1,-3,-5],[2,4],[3,-1,-2],[5],[-4]])\n sage: pd.max_block_size()\n 3\n sage: sorted(d.max_block_size() for d in PartitionDiagrams(2))\n [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4]\n sage: sorted(sp.max_block_size() for sp in SetPartitions(3))\n [1, 2, 2, 2, 3]\n ' return max((len(block) for block in self)) def conjugate(self): '\n An involution exchanging singletons and circular adjacencies.\n\n This method implements the definition of the conjugate of\n a set partition defined in [Cal2005]_.\n\n INPUT:\n\n - ``self`` -- a set partition of an ordered set\n\n OUTPUT:\n\n a set partition\n\n EXAMPLES::\n\n sage: SetPartition([[1,6,7],[2,8],[3,4,5]]).conjugate()\n {{1, 4, 7}, {2, 8}, {3}, {5}, {6}}\n sage: all(sp.conjugate().conjugate()==sp for sp in SetPartitions([1,3,5,7]))\n True\n sage: SetPartition([]).conjugate()\n {}\n ' def next_one(a, support): return support[((support.index(a) + 1) % len(support))] def addback(S, terminals, rsupport): out = list(S) for a in (terminals * 2): if ((a not in out) and (next_one(a, rsupport) in out)): out.append(a) return out def pre_conjugate(sp): if (len(sp) <= 1): return SetPartition([[a] for S in sp for a in S]) if (sp.max_block_size() == 1): return SetPartition([sp.base_set()]) support = sorted((a for S in sp for a in S)) initials = [a for S in sp for a in S if (next_one(a, support) in S)] singletons = [a for S in sp for a in S if (len(S) == 1)] if ((not initials) and (not singletons)): return sp rho = pre_conjugate(SetPartition([[a for a in S if (a not in initials)] for S in sp if ((len(S) > 1) and any(((a not in initials) for a in S)))])) return SetPartition(([addback(S, singletons, support[::(- 1)]) for S in rho] + [[a] for a in initials])) support = sorted((a for S in self for a in S)) return SetPartition([[support[((- support.index(a)) - 1)] for a in S] for S in pre_conjugate(self)])
class SetPartition(AbstractSetPartition, metaclass=InheritComparisonClasscallMetaclass): '\n A partition of a set.\n\n A set partition `p` of a set `S` is a partition of `S` into subsets\n called parts and represented as a set of sets. By extension, a set\n partition of a nonnegative integer `n` is the set partition of the\n integers from 1 to `n`. The number of set partitions of `n` is called\n the `n`-th Bell number.\n\n There is a natural integer partition associated with a set partition,\n namely the nonincreasing sequence of sizes of all its parts.\n\n There is a classical lattice associated with all set partitions of\n `n`. The infimum of two set partitions is the set partition obtained\n by intersecting all the parts of both set partitions. The supremum\n is obtained by transitive closure of the relation `i` related to `j`\n if and only if they are in the same part in at least one of the set\n partitions.\n\n We will use terminology from partitions, in particular the *length* of\n a set partition `A = \\{A_1, \\ldots, A_k\\}` is the number of parts of `A`\n and is denoted by `|A| := k`. The *size* of `A` is the cardinality of `S`.\n We will also sometimes use the notation `[n] := \\{1, 2, \\ldots, n\\}`.\n\n EXAMPLES:\n\n There are 5 set partitions of the set `\\{1,2,3\\}`::\n\n sage: SetPartitions(3).cardinality() # needs sage.libs.flint\n 5\n\n Here is the list of them::\n\n sage: SetPartitions(3).list() # needs sage.graphs\n [{{1, 2, 3}}, {{1, 2}, {3}}, {{1, 3}, {2}}, {{1}, {2, 3}}, {{1}, {2}, {3}}]\n\n There are 6 set partitions of `\\{1,2,3,4\\}` whose underlying partition is\n `[2, 1, 1]`::\n\n sage: SetPartitions(4, [2,1,1]).list() # needs sage.graphs sage.rings.finite_rings\n [{{1}, {2, 4}, {3}},\n {{1}, {2}, {3, 4}},\n {{1, 4}, {2}, {3}},\n {{1, 3}, {2}, {4}},\n {{1, 2}, {3}, {4}},\n {{1}, {2, 3}, {4}}]\n\n Since :trac:`14140`, we can create a set partition directly by\n :class:`SetPartition`, which creates the base set by taking the\n union of the parts passed in::\n\n sage: s = SetPartition([[1,3],[2,4]]); s\n {{1, 3}, {2, 4}}\n sage: s.parent()\n Set partitions\n ' @staticmethod def __classcall_private__(cls, parts, check=True): '\n Create a set partition from ``parts`` with the appropriate parent.\n\n EXAMPLES::\n\n sage: s = SetPartition([[1,3],[2,4]]); s\n {{1, 3}, {2, 4}}\n sage: s.parent()\n Set partitions\n ' P = SetPartitions() return P.element_class(P, parts, check=check) def __init__(self, parent, s, check=True): '\n Initialize ``self``.\n\n Internally, a set partition is stored as iterable of blocks,\n sorted by minimal element.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: s = S([[1,3],[2,4]])\n sage: TestSuite(s).run()\n sage: SetPartition([])\n {}\n ' self._latex_options = {} ClonableArray.__init__(self, parent, sorted(map(frozenset, s), key=min), check=check) def check(self): "\n Check that we are a valid set partition.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: s = S([[1, 3], [2, 4]])\n sage: s.check()\n\n TESTS::\n\n sage: s = S([[1, 2, 3]], check=False)\n sage: s.check()\n Traceback (most recent call last):\n ...\n ValueError: {{1, 2, 3}} is not an element of Set partitions of {1, 2, 3, 4}\n\n sage: s = S([1, 2, 3])\n Traceback (most recent call last):\n ...\n TypeError: 'sage.rings.integer.Integer' object is not iterable\n " if (self not in self.parent()): raise ValueError(f'{self} is not an element of {self.parent()}') def set_latex_options(self, **kwargs): '\n Set the latex options for use in the ``_latex_`` function\n\n - ``tikz_scale`` -- (default: 1) scale for use with tikz package\n\n - ``plot`` -- (default: ``None``) ``None`` returns the set notation,\n ``linear`` returns a linear plot, ``cyclic`` returns a cyclic\n plot\n\n - ``color`` -- (default: ``\'black\'``) the arc colors\n\n - ``fill`` -- (default: ``False``) if ``True`` then fills ``color``,\n else you can pass in a color to alter the fill color -\n *only works with cyclic plot*\n\n - ``show_labels`` -- (default: ``True``) if ``True`` shows labels -\n *only works with plots*\n\n - ``radius`` -- (default: ``"1cm"``) radius of circle for cyclic\n plot - *only works with cyclic plot*\n\n - ``angle`` -- (default: 0) angle for linear plot\n\n EXAMPLES::\n\n sage: SP = SetPartition([[1,6], [3,5,4]])\n sage: SP.set_latex_options(tikz_scale=2,plot=\'linear\',fill=True,color=\'blue\',angle=45)\n sage: SP.set_latex_options(plot=\'cyclic\')\n sage: SP.latex_options()\n {\'angle\': 45,\n \'color\': \'blue\',\n \'fill\': True,\n \'plot\': \'cyclic\',\n \'radius\': \'1cm\',\n \'show_labels\': True,\n \'tikz_scale\': 2}\n ' valid_args = ['tikz_scale', 'plot', 'color', 'fill', 'show_labels', 'radius', 'angle'] for key in kwargs: if (key not in valid_args): raise ValueError(f'unknown keyword argument: {key}') if (key == 'plot'): if (not ((kwargs['plot'] == 'cyclic') or (kwargs['plot'] == 'linear') or (kwargs['plot'] is None))): raise ValueError("plot must be None, 'cyclic', or 'linear'") self._latex_options.update(kwargs) def latex_options(self): "\n Return the latex options for use in the ``_latex_`` function as a\n dictionary. The default values are set using the global options.\n\n Options can be found in :meth:`set_latex_options`\n\n EXAMPLES::\n\n sage: SP = SetPartition([[1,6], [3,5,4]]); SP.latex_options()\n {'angle': 0,\n 'color': 'black',\n 'fill': False,\n 'plot': None,\n 'radius': '1cm',\n 'show_labels': True,\n 'tikz_scale': 1}\n " opts = self._latex_options.copy() if ('tikz_scale' not in opts): opts['tikz_scale'] = 1 if ('plot' not in opts): opts['plot'] = None if ('color' not in opts): opts['color'] = 'black' if ('fill' not in opts): opts['fill'] = False if ('show_labels' not in opts): opts['show_labels'] = True if ('radius' not in opts): opts['radius'] = '1cm' if ('angle' not in opts): opts['angle'] = 0 return opts def _latex_(self): "\n Return a `\\LaTeX` string representation of ``self``.\n\n EXAMPLES::\n\n sage: x = SetPartition([[1,2], [3,5,4]])\n sage: latex(x)\n \\{\\{1, 2\\}, \\{3, 4, 5\\}\\}\n\n sage: x.set_latex_options(plot='linear', angle=25, color='red')\n sage: latex(x)\n \\begin{tikzpicture}[scale=1]\n \\node[below=.05cm] at (0,0) {$1$};\n \\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (0) at (0,0) {};\n \\node[below=.05cm] at (1,0) {$2$};\n \\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (1) at (1,0) {};\n \\node[below=.05cm] at (2,0) {$3$};\n \\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (2) at (2,0) {};\n \\node[below=.05cm] at (3,0) {$4$};\n \\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (3) at (3,0) {};\n \\node[below=.05cm] at (4,0) {$5$};\n \\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] (4) at (4,0) {};\n \\draw[color=red] (1) to [out=115,in=65] (0);\n \\draw[color=red] (3) to [out=115,in=65] (2);\n \\draw[color=red] (4) to [out=115,in=65] (3);\n \\end{tikzpicture}\n\n sage: p = SetPartition([['a','c'],['b','d'],['e']])\n sage: p.set_latex_options(plot='cyclic', color='blue', fill=True, tikz_scale=2)\n sage: latex(p)\n \\begin{tikzpicture}[scale=2]\n \\draw (0,0) circle [radius=1cm];\n \\node[label=90:a] (0) at (90:1cm) {};\n \\node[label=18:b] (1) at (18:1cm) {};\n \\node[label=-54:c] (2) at (-54:1cm) {};\n \\node[label=-126:d] (3) at (-126:1cm) {};\n \\node[label=-198:e] (4) at (-198:1cm) {};\n \\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] ...\n \\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] ...\n \\draw[-,thick,color=blue,fill=blue,fill opacity=0.1] ...\n \\fill[color=black] (0) circle (1.5pt);\n \\fill[color=black] (1) circle (1.5pt);\n \\fill[color=black] (2) circle (1.5pt);\n \\fill[color=black] (3) circle (1.5pt);\n \\fill[color=black] (4) circle (1.5pt);\n \\end{tikzpicture}\n " latex_options = self.latex_options() if (latex_options['plot'] is None): return repr(self).replace('{', '\\{').replace('}', '\\}') from sage.misc.latex import latex latex.add_package_to_preamble_if_available('tikz') res = '\\begin{{tikzpicture}}[scale={}]\n'.format(latex_options['tikz_scale']) cardinality = self.base_set_cardinality() from sage.rings.integer_ring import ZZ if all(((x in ZZ) for x in self.base_set())): sort_key = ZZ else: sort_key = str base_set = sorted(self.base_set(), key=sort_key) color = latex_options['color'] if (latex_options['plot'] == 'cyclic'): degrees = (360 // cardinality) radius = latex_options['radius'] res += '\\draw (0,0) circle [radius={}];\n'.format(radius) for (k, i) in enumerate(base_set): location = (((cardinality - k) * degrees) - 270) if latex_options['show_labels']: res += '\\node[label={}:{}]'.format(location, i) else: res += '\\node' res += ' ({}) at ({}:{}) {{}};\n'.format(k, location, radius) for partition in sorted(self, key=str): res += ('\\draw[-,thick,color=' + color) if (latex_options['fill'] is not False): if isinstance(latex_options['fill'], str): res += (',fill=' + latex_options['fill']) else: res += ',fill={},fill opacity=0.1'.format(color) res += '] ' res += ' -- '.join(('({}.center)'.format(base_set.index(j)) for j in sorted(partition, key=sort_key))) res += ' -- cycle;\n' for k in range(len(base_set)): res += '\\fill[color=black] ({}) circle (1.5pt);\n'.format(k) elif (latex_options['plot'] == 'linear'): angle = latex_options['angle'] for (k, i) in enumerate(base_set): if latex_options['show_labels']: res += '\\node[below=.05cm] at ({},0) {{${}$}};\n'.format(k, i) res += '\\node[draw,circle, inner sep=0pt, minimum width=4pt, fill=black] ' res += '({k}) at ({k},0) {{}};\n'.format(k=k) for partition in sorted(self, key=str): p = sorted(partition, key=sort_key) if (len(p) <= 1): continue for k in range(1, len(p)): res += '\\draw[color={}] ({})'.format(color, base_set.index(p[k])) res += ' to [out={},in={}] '.format((90 + angle), (90 - angle)) res += '({});\n'.format(base_set.index(p[(k - 1)])) else: raise ValueError("plot must be None, 'cyclic', or 'linear'") res += '\\end{tikzpicture}' return res cardinality = ClonableArray.__len__ size = AbstractSetPartition.base_set_cardinality def pipe(self, other): '\n Return the pipe of the set partitions ``self`` and ``other``.\n\n The pipe of two set partitions is defined as follows:\n\n For any integer `k` and any subset `I` of `\\ZZ`, let `I + k`\n denote the subset of `\\ZZ` obtained by adding `k` to every\n element of `k`.\n\n If `B` and `C` are set partitions of `[n]` and `[m]`,\n respectively, then the pipe of `B` and `C` is defined as the\n set partition\n\n .. MATH::\n\n \\{ B_1, B_2, \\ldots, B_b,\n C_1 + n, C_2 + n, \\ldots, C_c + n \\}\n\n of `[n+m]`, where `B = \\{ B_1, B_2, \\ldots, B_b \\}` and\n `C = \\{ C_1, C_2, \\ldots, C_c \\}`. This pipe is denoted by\n `B | C`.\n\n EXAMPLES::\n\n sage: SetPartition([[1,3],[2,4]]).pipe(SetPartition([[1,3],[2]]))\n {{1, 3}, {2, 4}, {5, 7}, {6}}\n sage: SetPartition([]).pipe(SetPartition([[1,2],[3,5],[4]]))\n {{1, 2}, {3, 5}, {4}}\n sage: SetPartition([[1,2],[3,5],[4]]).pipe(SetPartition([]))\n {{1, 2}, {3, 5}, {4}}\n sage: SetPartition([[1,2],[3]]).pipe(SetPartition([[1]]))\n {{1, 2}, {3}, {4}}\n ' parts = list(self) n = self.base_set_cardinality() for newpart in other: raised_newpart = Set(((i + n) for i in newpart)) parts.append(raised_newpart) return SetPartition(parts) @combinatorial_map(name='shape') def shape(self): '\n Return the integer partition whose parts are the sizes of the sets\n in ``self``.\n\n EXAMPLES::\n\n sage: S = SetPartitions(5)\n sage: x = S([[1,2], [3,5,4]])\n sage: x.shape()\n [3, 2]\n sage: y = S([[2], [3,1], [5,4]])\n sage: y.shape()\n [2, 2, 1]\n ' return Partition(sorted(map(len, self), reverse=True)) shape_partition = shape to_partition = shape @combinatorial_map(name='to permutation') def to_permutation(self): '\n Convert a set partition of `\\{1,...,n\\}` to a permutation by considering\n the blocks of the partition as cycles.\n\n The cycles are such that the number of excedences is maximised, that is,\n each cycle is of the form `(a_1,a_2, ...,a_k)` with `a_1<a_2<...<a_k`.\n\n EXAMPLES::\n\n sage: s = SetPartition([[1,3],[2,4]])\n sage: s.to_permutation()\n [3, 4, 1, 2]\n ' return Permutation(tuple(map(tuple, self.standard_form()))) def to_restricted_growth_word(self, bijection='blocks'): '\n Convert a set partition of `\\{1,...,n\\}` to a word of length `n`\n with letters in the non-negative integers such that each\n letter is at most 1 larger than all the letters before.\n\n INPUT:\n\n - ``bijection`` (default: ``blocks``) -- defines the map from\n set partitions to restricted growth functions. These are\n currently:\n\n - ``blocks``: :meth:`to_restricted_growth_word_blocks`.\n\n - ``intertwining``: :meth:`to_restricted_growth_word_intertwining`.\n\n OUTPUT:\n\n A restricted growth word.\n\n .. SEEALSO::\n\n :meth:`SetPartitions.from_restricted_growth_word`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,4],[2,8],[3,5,6,9],[7]])\n sage: P.to_restricted_growth_word()\n [0, 1, 2, 0, 2, 2, 3, 1, 2]\n\n sage: P.to_restricted_growth_word("intertwining")\n [0, 1, 2, 2, 1, 0, 3, 3, 2]\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: P.to_restricted_growth_word()\n [0, 0, 1, 0, 2, 2, 0, 3, 1, 2, 2, 4, 2]\n\n sage: P.to_restricted_growth_word("intertwining")\n [0, 0, 1, 1, 2, 0, 1, 3, 3, 3, 0, 4, 1]\n\n TESTS::\n\n sage: P = SetPartition([])\n sage: P.to_restricted_growth_word()\n []\n sage: P.to_restricted_growth_word("intertwining")\n []\n sage: S = SetPartitions(5, 2)\n sage: all(S.from_restricted_growth_word(P.to_restricted_growth_word()) == P for P in S)\n True\n\n sage: S = SetPartitions(5, 2)\n sage: all(S.from_restricted_growth_word(P.to_restricted_growth_word("intertwining"), "intertwining") == P for P in S)\n True\n ' if (bijection == 'blocks'): return self.to_restricted_growth_word_blocks() if (bijection == 'intertwining'): return self.to_restricted_growth_word_intertwining() raise ValueError('the given bijection is not valid') def to_restricted_growth_word_blocks(self): '\n Convert a set partition of `\\{1,...,n\\}` to a word of length `n`\n with letters in the non-negative integers such that each\n letter is at most 1 larger than all the letters before.\n\n The word is obtained by sorting the blocks by their minimal\n element and setting the letters at the positions of the\n elements in the `i`-th block to `i`.\n\n OUTPUT:\n\n a restricted growth word.\n\n .. SEEALSO::\n\n :meth:`to_restricted_growth_word`\n :meth:`SetPartitions.from_restricted_growth_word`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,4],[2,8],[3,5,6,9],[7]])\n sage: P.to_restricted_growth_word_blocks()\n [0, 1, 2, 0, 2, 2, 3, 1, 2]\n ' w = ([0] * self.size()) for (i, B) in enumerate(self): for j in B: w[(j - 1)] = i return w def to_restricted_growth_word_intertwining(self): '\n Convert a set partition of `\\{1,...,n\\}` to a word of length `n`\n with letters in the non-negative integers such that each\n letter is at most 1 larger than all the letters before.\n\n The `i`-th letter of the word is the numbers of crossings of\n the arc (or half-arc) in the extended arc diagram ending at\n `i`, with arcs (or half-arcs) beginning at a smaller element\n and ending at a larger element.\n\n OUTPUT:\n\n a restricted growth word.\n\n .. SEEALSO::\n\n :meth:`to_restricted_growth_word`\n :meth:`SetPartitions.from_restricted_growth_word`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,4],[2,8],[3,5,6,9],[7]])\n sage: P.to_restricted_growth_word_intertwining()\n [0, 1, 2, 2, 1, 0, 3, 3, 2]\n ' A = sorted(self.arcs()) O = (min(B) for B in self) C = [max(B) for B in self] I = ([0] * self.size()) for i in O: I[(i - 1)] = (sum((1 for (k, l) in A if (k < i < l))) + sum((1 for k in C if (k < i)))) for (i, j) in A: I[(j - 1)] = (sum((1 for (k, l) in A if (i < k < j < l))) + sum((1 for k in C if (i < k < j)))) return I def openers(self): '\n Return the minimal elements of the blocks.\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: P.openers()\n [1, 3, 5, 8, 12]\n ' return sorted([min(B) for B in self]) def closers(self): '\n Return the maximal elements of the blocks.\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: P.closers()\n [7, 8, 9, 12, 13]\n ' return sorted([max(B) for B in self]) def to_rook_placement(self, bijection='arcs'): '\n Return a set of pairs defining a placement of non-attacking rooks\n on a triangular board.\n\n The cells of the board corresponding to a set partition of\n `\\{1,...,n\\}` are the pairs `(i,j)` with `0 < i < j < n+1`.\n\n INPUT:\n\n - ``bijection`` (default: ``arcs``) -- defines the bijection\n from set partitions to rook placements. These are\n currently:\n\n - ``arcs``: :meth:`arcs`\n - ``gamma``: :meth:`to_rook_placement_gamma`\n - ``rho``: :meth:`to_rook_placement_rho`\n - ``psi``: :meth:`to_rook_placement_psi`\n\n .. SEEALSO::\n\n :meth:`SetPartitions.from_rook_placement`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: P.to_rook_placement()\n [(1, 2), (2, 4), (4, 7), (3, 9), (5, 6), (6, 10), (10, 11), (11, 13)]\n sage: P.to_rook_placement("gamma")\n [(1, 4), (3, 5), (4, 6), (5, 8), (7, 11), (8, 9), (10, 12), (12, 13)]\n sage: P.to_rook_placement("rho")\n [(1, 2), (2, 6), (3, 4), (4, 10), (5, 9), (6, 7), (10, 11), (11, 13)]\n sage: P.to_rook_placement("psi")\n [(1, 2), (2, 6), (3, 4), (5, 9), (6, 7), (7, 10), (9, 11), (11, 13)]\n ' if (bijection == 'arcs'): return self.arcs() if (bijection == 'gamma'): return self.to_rook_placement_gamma() if (bijection == 'rho'): return self.to_rook_placement_rho() if (bijection == 'psi'): return self.to_rook_placement_psi() raise ValueError('the given map is not valid') def to_rook_placement_gamma(self): '\n Return the rook diagram obtained by placing rooks according to\n Wachs and White\'s bijection gamma.\n\n Note that our index convention differs from the convention in\n [WW1991]_: regarding the rook board as a lower-right\n triangular grid, we refer with `(i,j)` to the cell in the\n `i`-th column from the right and the `j`-th row from the top.\n\n The algorithm proceeds as follows: non-attacking rooks are\n placed beginning at the left column. If `n+1-i` is an\n opener, column `i` remains empty. Otherwise, we place a rook\n into column `i`, such that the number of cells below the\n rook, which are not yet attacked by another rook, equals the\n index of the block to which `n+1-i` belongs.\n\n OUTPUT:\n\n A list of coordinates.\n\n .. SEEALSO::\n\n - :meth:`to_rook_placement`\n - :meth:`SetPartitions.from_rook_placement`\n - :meth:`SetPartitions.from_rook_placement_gamma`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,4],[2,8],[3,5,6,9],[7]])\n sage: P.to_rook_placement_gamma()\n [(1, 3), (2, 7), (4, 5), (5, 6), (6, 9)]\n\n Figure 5 in [WW1991]_::\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: r = P.to_rook_placement_gamma(); r\n [(1, 4), (3, 5), (4, 6), (5, 8), (7, 11), (8, 9), (10, 12), (12, 13)]\n\n TESTS::\n\n sage: P = SetPartition([])\n sage: P.to_rook_placement_gamma()\n []\n sage: S = SetPartitions(5, 2)\n sage: all(S.from_rook_placement(P.to_rook_placement("gamma"), "gamma") == P for P in S)\n True\n ' n = self.size() if (n == 0): return [] w = self.to_restricted_growth_word_blocks() EC = sorted([w.index(i) for i in range((max(w) + 1))]) rooks = [] R = [] for c in range(n): if (c not in EC): r = 0 w_c = w[c] while ((w_c > 0) or (r in R)): if (r not in R): w_c -= 1 r += 1 rooks.append(((n - c), (n - r))) R.append(r) return sorted(rooks) def to_rook_placement_rho(self): '\n Return the rook diagram obtained by placing rooks according to\n Wachs and White\'s bijection rho.\n\n Note that our index convention differs from the convention in\n [WW1991]_: regarding the rook board as a lower-right\n triangular grid, we refer with `(i,j)` to the cell in the\n `i`-th column from the right and the `j`-th row from the top.\n\n The algorithm proceeds as follows: non-attacking rooks are\n placed beginning at the top row. The columns corresponding\n to the closers of the set partition remain empty. Let `rs_j`\n be the number of closers which are larger than `j` and\n whose block is before the block of `j`.\n\n We then place a rook into row `j`, such that the number of\n cells to the left of the rook, which are not yet attacked by\n another rook and are not in a column corresponding to a\n closer, equals `rs_j`, unless there are not enough cells in\n this row available, in which case the row remains empty.\n\n One can show that the precisely those rows which correspond\n to openers of the set partition remain empty.\n\n OUTPUT:\n\n A list of coordinates.\n\n .. SEEALSO::\n\n - :meth:`to_rook_placement`\n - :meth:`SetPartitions.from_rook_placement`\n - :meth:`SetPartitions.from_rook_placement_rho`\n\n EXAMPLES::\n\n sage: P = SetPartition([[1,4],[2,8],[3,5,6,9],[7]])\n sage: P.to_rook_placement_rho()\n [(1, 5), (2, 6), (3, 4), (5, 9), (6, 8)]\n\n Figure 6 in [WW1991]_::\n\n sage: P = SetPartition([[1,2,4,7],[3,9],[5,6,10,11,13],[8],[12]])\n sage: r = P.to_rook_placement_rho(); r\n [(1, 2), (2, 6), (3, 4), (4, 10), (5, 9), (6, 7), (10, 11), (11, 13)]\n\n sage: sorted(P.closers() + [i for i, _ in r]) == list(range(1,14))\n True\n sage: sorted(P.openers() + [j for _, j in r]) == list(range(1,14))\n True\n\n TESTS::\n\n sage: P = SetPartition([])\n sage: P.to_rook_placement_rho()\n []\n sage: S = SetPartitions(5, 2)\n sage: all(S.from_rook_placement(P.to_rook_placement("rho"), "rho") == P for P in S)\n True\n ' n = self.size() if (n == 0): return [] w = self.to_restricted_growth_word_blocks() w_rev = w[::(- 1)] R = sorted([((n - w_rev.index(i)) - 1) for i in range((max(w) + 1))]) rs = [sum((1 for j in R if ((j > i) and (w[j] < w[i])))) for i in range(n)] EC = [(n - j) for j in R] rooks = [] for i in range(1, n): U = [j for j in range(((n + 1) - i), (n + 1)) if (j not in EC)] if (rs[i] < len(U)): j = U[rs[i]] rooks.append((((n + 1) - j), (i + 1))) EC.append(j) return sorted(rooks) def to_rook_placement_psi(self): '\n Return the rook diagram obtained by placing rooks according to\n Yip\'s bijection psi.\n\n OUTPUT:\n\n A list of coordinates.\n\n .. SEEALSO::\n\n - :meth:`to_rook_placement`\n - :meth:`SetPartitions.from_rook_placement`\n - :meth:`SetPartitions.from_rook_placement_psi`\n\n EXAMPLES:\n\n Example 36 (arXiv version: Example 4.5) in [Yip2018]_::\n\n sage: P = SetPartition([[1, 5], [2], [3, 8, 9], [4], [6, 7]])\n sage: P.to_rook_placement_psi()\n [(1, 7), (3, 8), (4, 5), (7, 9)]\n\n Note that the columns corresponding to the minimal elements\n of the blocks remain empty.\n\n TESTS::\n\n sage: P = SetPartition([])\n sage: P.to_rook_placement_psi()\n []\n sage: S = SetPartitions(5,2)\n sage: all(S.from_rook_placement(P.to_rook_placement("psi"), "psi") == P for P in S)\n True\n ' n = self.size() degrees = [] P = [sorted(e) for e in self] for j in range(n, 0, (- 1)): B = next((B for B in P if (B[(- 1)] == j))) if (len(B) == 1): P.remove(B) else: del B[(- 1)] P = sorted(P, key=(lambda B: ((- len(B)), min(B)))) b = P.index(B) i = ((j - b) - 1) degrees.append((j, i)) rooks = [] attacked_rows = [] for (j, d) in reversed(degrees): i = 1 while (d > (i + sum((1 for r in attacked_rows if (r > i))))): i += 1 attacked_rows.append(i) rooks.append((i, j)) return sorted(rooks) def apply_permutation(self, p): '\n Apply ``p`` to the underlying set of ``self``.\n\n INPUT:\n\n - ``p`` -- a permutation\n\n EXAMPLES::\n\n sage: x = SetPartition([[1,2], [3,5,4]])\n sage: p = Permutation([2,1,4,5,3])\n sage: x.apply_permutation(p)\n {{1, 2}, {3, 4, 5}}\n sage: q = Permutation([3,2,1,5,4])\n sage: x.apply_permutation(q)\n {{1, 4, 5}, {2, 3}}\n\n sage: m = PerfectMatching([(1,4),(2,6),(3,5)])\n sage: m.apply_permutation(Permutation([4,1,5,6,3,2]))\n [(1, 2), (3, 5), (4, 6)]\n ' return self.__class__(self.parent(), [Set(map(p, B)) for B in self]) def crossings_iterator(self): '\n Return the crossing arcs of a set partition on a totally ordered set.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns an iterator over the pairs of crossing\n lines (as a line correspond to a pair, the iterator\n produces pairs of pairs).\n\n EXAMPLES::\n\n sage: p = SetPartition([[1,4],[2,5,7],[3,6]])\n sage: next(p.crossings_iterator())\n ((1, 4), (2, 5))\n\n TESTS::\n\n sage: p = SetPartition([]); p.crossings()\n []\n ' arcs = sorted(self.arcs(), key=min) while arcs: (i1, j1) = arcs.pop(0) for (i2, j2) in arcs: if (i2 < j1 < j2): (yield ((i1, j1), (i2, j2))) def crossings(self): '\n Return the crossing arcs of a set partition on a totally ordered set.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns a list of the pairs of crossing lines\n (as a line correspond to a pair, it returns a list of\n pairs of pairs).\n\n EXAMPLES::\n\n sage: p = SetPartition([[1,4],[2,5,7],[3,6]])\n sage: p.crossings()\n [((1, 4), (2, 5)), ((1, 4), (3, 6)), ((2, 5), (3, 6)), ((3, 6), (5, 7))]\n\n TESTS::\n\n sage: p = SetPartition([]); p.crossings()\n []\n ' return list(self.crossings_iterator()) def number_of_crossings(self): '\n Return the number of crossings.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns the number the pairs of crossing lines.\n\n EXAMPLES::\n\n sage: p = SetPartition([[1,4],[2,5,7],[3,6]])\n sage: p.number_of_crossings()\n 4\n\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.number_of_crossings()\n 1\n ' return Integer(len(list(self.crossings_iterator()))) def is_noncrossing(self) -> bool: '\n Check if ``self`` is noncrossing.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns ``True`` if the picture obtained this\n way has no crossings.\n\n EXAMPLES::\n\n sage: p = SetPartition([[1,4],[2,5,7],[3,6]])\n sage: p.is_noncrossing()\n False\n\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.is_noncrossing()\n False\n sage: PerfectMatching([(1, 4), (2, 3), (5, 6)]).is_noncrossing()\n True\n ' it = self.crossings_iterator() try: next(it) except StopIteration: return True return False def nestings_iterator(self): '\n Iterate over the nestings of ``self``.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns an iterator over the pairs of nesting\n lines (as a line correspond to a pair, the iterator\n produces pairs of pairs).\n\n EXAMPLES::\n\n sage: n = PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])\n sage: it = n.nestings_iterator()\n sage: next(it)\n ((1, 6), (3, 5))\n sage: next(it)\n ((2, 7), (3, 5))\n sage: next(it)\n Traceback (most recent call last):\n ...\n StopIteration\n ' arcs = sorted(self.arcs(), key=min) while arcs: (i1, j1) = arcs.pop(0) for (i2, j2) in arcs: if (i2 < j2 < j1): (yield ((i1, j1), (i2, j2))) def nestings(self): '\n Return the nestings of ``self``.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns the list of the pairs of nesting lines\n (as a line correspond to a pair, it returns a list of\n pairs of pairs).\n\n EXAMPLES::\n\n sage: m = PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])\n sage: m.nestings()\n [((1, 6), (3, 5)), ((2, 7), (3, 5))]\n\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.nestings()\n [((2, 8), (4, 7)), ((2, 8), (5, 6)), ((4, 7), (5, 6))]\n\n TESTS::\n\n sage: m = PerfectMatching([]); m.nestings()\n []\n ' return list(self.nestings_iterator()) def number_of_nestings(self): '\n Return the number of nestings of ``self``.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns the number the pairs of nesting lines.\n\n EXAMPLES::\n\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.number_of_nestings()\n 3\n ' c = Integer(0) one = Integer(1) for _ in self.nestings_iterator(): c += one return c def is_nonnesting(self) -> bool: '\n Return if ``self`` is nonnesting or not.\n\n OUTPUT:\n\n We place the elements of the ground set in order on a\n line and draw the set partition by linking consecutive\n elements of each block in the upper half-plane. This\n function returns ``True`` if the picture obtained this\n way has no nestings.\n\n EXAMPLES::\n\n sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n\n [(1, 3), (2, 8), (4, 7), (5, 6)]\n sage: n.is_nonnesting()\n False\n sage: PerfectMatching([(1, 3), (2, 5), (4, 6)]).is_nonnesting()\n True\n ' it = self.nestings_iterator() try: next(it) except StopIteration: return True return False def is_atomic(self) -> bool: '\n Return if ``self`` is an atomic set partition.\n\n A (standard) set partition `A` can be split if there exist `j < i`\n such that `\\max(A_j) < \\min(A_i)` where `A` is ordered by minimal\n elements. This means we can write `A = B | C` for some nonempty set\n partitions `B` and `C`. We call a set partition *atomic* if it\n cannot be split and is nonempty. Here, the pipe symbol\n `|` is as defined in method :meth:`pipe`.\n\n EXAMPLES::\n\n sage: SetPartition([[1,3], [2]]).is_atomic()\n True\n sage: SetPartition([[1,3], [2], [4]]).is_atomic()\n False\n sage: SetPartition([[1], [2,4], [3]]).is_atomic()\n False\n sage: SetPartition([[1,2,3,4]]).is_atomic()\n True\n sage: SetPartition([[1, 4], [2], [3]]).is_atomic()\n True\n sage: SetPartition([]).is_atomic()\n False\n ' if (len(self) == 0): return False maximum_so_far = max(self[0]) for S in self[1:]: if (maximum_so_far < min(S)): return False maximum_so_far = max(maximum_so_far, max(S)) return True def standardization(self): "\n Return the standardization of ``self``.\n\n Given a set partition `A = \\{A_1, \\ldots, A_n\\}` of an ordered\n set `S`, the standardization of `A` is the set partition of\n `\\{1, 2, \\ldots, |S|\\}` obtained by replacing the elements of\n the parts of `A` by the integers `1, 2, \\ldots, |S|` in such\n a way that their relative order is preserved (i. e., the\n smallest element in the whole set partition is replaced by\n `1`, the next-smallest by `2`, and so on).\n\n EXAMPLES::\n\n sage: SetPartition([[4], [1, 3]]).standardization()\n {{1, 2}, {3}}\n sage: SetPartition([[4], [6, 3]]).standardization()\n {{1, 3}, {2}}\n sage: SetPartition([]).standardization()\n {}\n sage: SetPartition([('c','b'),('d','f'),('e','a')]).standardization()\n {{1, 5}, {2, 3}, {4, 6}}\n " r = {e: i for (i, e) in enumerate(sorted(self.base_set()), 1)} return SetPartitions(len(r))([[r[e] for e in b] for b in self]) def restriction(self, I): '\n Return the restriction of ``self`` to a subset ``I``\n (which is given as a set or list or any other iterable).\n\n EXAMPLES::\n\n sage: A = SetPartition([[1], [2,3]])\n sage: A.restriction([1,2])\n {{1}, {2}}\n sage: A.restriction([2,3])\n {{2, 3}}\n sage: A.restriction([])\n {}\n sage: A.restriction([4])\n {}\n ' ret = [] for part in self: newpart = [i for i in part if (i in I)] if (len(newpart) != 0): ret.append(newpart) return SetPartition(ret) def ordered_set_partition_action(self, s): '\n Return the action of an ordered set partition ``s`` on ``self``.\n\n Let `A = \\{A_1, A_2, \\ldots, A_k\\}` be a set partition of some\n set `S` and `s` be an ordered set partition (i.e., set composition)\n of a subset of `[k]`. Let `A^{\\downarrow}` denote the standardization\n of `A`, and `A_{\\{ i_1, i_2, \\ldots, i_m \\}}` denote the sub-partition\n `\\{A_{i_1}, A_{i_2}, \\ldots, A_{i_m}\\}` for any subset\n `\\{i_1, \\ldots, i_m\\}` of `\\{1, \\ldots, k\\}`. We define the set\n partition `s(A)` by\n\n .. MATH::\n\n s(A) = A_{s_1}^{\\downarrow} | A_{s_2}^{\\downarrow} | \\cdots\n | A_{s_q}^{\\downarrow}.\n\n where `s = (s_1, s_2, \\ldots, s_q)`. Here, the pipe symbol\n `|` is as defined in method :meth:`pipe`.\n\n This is `s[A]` in section 2.3 in [LM2011]_.\n\n INPUT:\n\n - ``s`` -- an ordered set partition with base set a subset\n of `\\{1, \\ldots, k\\}`\n\n EXAMPLES::\n\n sage: A = SetPartition([[1], [2,4], [3]])\n sage: s = OrderedSetPartition([[1,3], [2]])\n sage: A.ordered_set_partition_action(s)\n {{1}, {2}, {3, 4}}\n sage: s = OrderedSetPartition([[2,3], [1]])\n sage: A.ordered_set_partition_action(s)\n {{1, 3}, {2}, {4}}\n\n We create Figure 1 in [LM2011]_ (we note that there is a typo in the\n lower-left corner of the table in the published version of the\n paper, whereas the arXiv version gives the correct partition)::\n\n sage: A = SetPartition([[1,3], [2,9], [4,5,8], [7]])\n sage: B = SetPartition([[1,3], [2,8], [4,5,6], [7]])\n sage: C = SetPartition([[1,5], [2,8], [3,4,6], [7]])\n sage: s = OrderedSetPartition([[1,3], [2]])\n sage: t = OrderedSetPartition([[2], [3,4]])\n sage: u = OrderedSetPartition([[1], [2,3,4]])\n sage: A.ordered_set_partition_action(s)\n {{1, 2}, {3, 4, 5}, {6, 7}}\n sage: A.ordered_set_partition_action(t)\n {{1, 2}, {3, 4, 6}, {5}}\n sage: A.ordered_set_partition_action(u)\n {{1, 2}, {3, 8}, {4, 5, 7}, {6}}\n sage: B.ordered_set_partition_action(s)\n {{1, 2}, {3, 4, 5}, {6, 7}}\n sage: B.ordered_set_partition_action(t)\n {{1, 2}, {3, 4, 5}, {6}}\n sage: B.ordered_set_partition_action(u)\n {{1, 2}, {3, 8}, {4, 5, 6}, {7}}\n sage: C.ordered_set_partition_action(s)\n {{1, 4}, {2, 3, 5}, {6, 7}}\n sage: C.ordered_set_partition_action(t)\n {{1, 2}, {3, 4, 5}, {6}}\n sage: C.ordered_set_partition_action(u)\n {{1, 2}, {3, 8}, {4, 5, 6}, {7}}\n\n REFERENCES:\n\n - [LM2011]_\n ' cur = 1 ret = [] for part in s: sub_parts = [list(self[(i - 1)]) for i in part] mins = [min(i) for i in sub_parts] over_max = (max(map(max, sub_parts)) + 1) temp = [[] for _ in repeat(None, len(part))] while (min(mins) != over_max): m = min(mins) i = mins.index(m) temp[i].append(cur) cur += 1 sub_parts[i].pop(sub_parts[i].index(m)) if (len(sub_parts[i]) != 0): mins[i] = min(sub_parts[i]) else: mins[i] = over_max ret += temp return SetPartition(ret) def refinements(self): '\n Return a list of refinements of ``self``.\n\n .. SEEALSO::\n\n :meth:`coarsenings`\n\n EXAMPLES::\n\n sage: SetPartition([[1,3],[2,4]]).refinements() # needs sage.graphs sage.libs.flint\n [{{1, 3}, {2, 4}},\n {{1, 3}, {2}, {4}},\n {{1}, {2, 4}, {3}},\n {{1}, {2}, {3}, {4}}]\n sage: SetPartition([[1],[2,4],[3]]).refinements() # needs sage.graphs sage.libs.flint\n [{{1}, {2, 4}, {3}}, {{1}, {2}, {3}, {4}}]\n sage: SetPartition([]).refinements() # needs sage.graphs sage.libs.flint\n [{}]\n ' L = [SetPartitions(part) for part in self] return [SetPartition(sum(map(list, x), [])) for x in itertools.product(*L)] def strict_coarsenings(self): '\n Return all strict coarsenings of ``self``.\n\n Strict coarsening is the binary relation on set partitions\n defined as the transitive-and-reflexive closure of the\n relation `\\prec` defined as follows: For two set partitions\n `A` and `B`, we have `A \\prec B` if there exist parts\n `A_i, A_j` of `A` such that `\\max(A_i) < \\min(A_j)` and\n `B = A \\setminus \\{A_i, A_j\\} \\cup \\{ A_i \\cup A_j \\}`.\n\n EXAMPLES::\n\n sage: A = SetPartition([[1],[2,3],[4]])\n sage: A.strict_coarsenings()\n [{{1}, {2, 3}, {4}}, {{1, 2, 3}, {4}}, {{1, 4}, {2, 3}},\n {{1}, {2, 3, 4}}, {{1, 2, 3, 4}}]\n sage: SetPartition([[1],[2,4],[3]]).strict_coarsenings()\n [{{1}, {2, 4}, {3}}, {{1, 2, 4}, {3}}, {{1, 3}, {2, 4}}]\n sage: SetPartition([]).strict_coarsenings()\n [{}]\n ' todo = [self] visited = set([self]) ret = [self] while todo: A = todo.pop() for (i, part) in enumerate(A): for (j, other) in enumerate(A[(i + 1):]): if (max(part) < min(other)): next_pi = A[:i] next_pi.append(part.union(other)) next_pi += (A[(i + 1):((i + 1) + j)] + A[((i + j) + 2):]) next_pi = SetPartition(next_pi) if (next_pi not in visited): todo.append(next_pi) visited.add(next_pi) ret.append(next_pi) return ret def arcs(self): '\n Return ``self`` as a list of arcs.\n\n Assuming that the blocks are sorted, the arcs are the pairs\n of consecutive elements in the blocks.\n\n EXAMPLES::\n\n sage: A = SetPartition([[1],[2,3],[4]])\n sage: A.arcs()\n [(2, 3)]\n sage: B = SetPartition([[1,3,6,7],[2,5],[4]])\n sage: B.arcs()\n [(1, 3), (3, 6), (6, 7), (2, 5)]\n ' arcs = [] for p in self: p = sorted(p) for i in range((len(p) - 1)): arcs.append((p[i], p[(i + 1)])) return arcs def plot(self, angle=None, color='black', base_set_dict=None): "\n Return a plot of ``self``.\n\n INPUT:\n\n - ``angle`` -- (default: `\\pi/4`) the angle at which the arcs take off\n (if angle is negative, the arcs are drawn below the horizontal line)\n\n - ``color`` -- (default: ``'black'``) color of the arcs\n\n - ``base_set_dict`` -- (optional) dictionary with keys elements\n of :meth:`base_set()` and values as integer or float\n\n EXAMPLES::\n\n sage: p = SetPartition([[1,10,11],[2,3,7],[4,5,6],[8,9]])\n sage: p.plot() # needs sage.plot sage.symbolic\n Graphics object consisting of 29 graphics primitives\n\n .. PLOT::\n\n p = SetPartition([[1,10,11],[2,3,7],[4,5,6],[8,9]])\n sphinx_plot(p.plot())\n\n ::\n\n sage: p = SetPartition([[1,3,4],[2,5]])\n sage: print(p.plot().description()) # needs sage.plot sage.symbolic\n Point set defined by 1 point(s): [(0.0, 0.0)]\n Point set defined by 1 point(s): [(1.0, 0.0)]\n Point set defined by 1 point(s): [(2.0, 0.0)]\n Point set defined by 1 point(s): [(3.0, 0.0)]\n Point set defined by 1 point(s): [(4.0, 0.0)]\n Text '1' at the point (0.0,-0.1)\n Text '2' at the point (1.0,-0.1)\n Text '3' at the point (2.0,-0.1)\n Text '4' at the point (3.0,-0.1)\n Text '5' at the point (4.0,-0.1)\n Arc with center (1.0,-1.0) radii (1.41421356237...,1.41421356237...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n Arc with center (2.5,-0.5) radii (0.70710678118...,0.70710678118...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n Arc with center (2.5,-1.5) radii (2.1213203435...,2.1213203435...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n sage: p = SetPartition([['a','c'],['b','d'],['e']])\n sage: print(p.plot().description()) # needs sage.plot sage.symbolic\n Point set defined by 1 point(s): [(0.0, 0.0)]\n Point set defined by 1 point(s): [(1.0, 0.0)]\n Point set defined by 1 point(s): [(2.0, 0.0)]\n Point set defined by 1 point(s): [(3.0, 0.0)]\n Point set defined by 1 point(s): [(4.0, 0.0)]\n Text 'a' at the point (0.0,-0.1)\n Text 'b' at the point (1.0,-0.1)\n Text 'c' at the point (2.0,-0.1)\n Text 'd' at the point (3.0,-0.1)\n Text 'e' at the point (4.0,-0.1)\n Arc with center (1.0,-1.0) radii (1.41421356237...,1.41421356237...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n Arc with center (2.0,-1.0) radii (1.41421356237...,1.41421356237...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n sage: p = SetPartition([['a','c'],['b','d'],['e']])\n sage: print(p.plot(base_set_dict={'a':0,'b':1,'c':2, # needs sage.plot sage.symbolic\n ....: 'd':-2.3,'e':5.4}).description())\n Point set defined by 1 point(s): [(-2.3, 0.0)]\n Point set defined by 1 point(s): [(0.0, 0.0)]\n Point set defined by 1 point(s): [(1.0, 0.0)]\n Point set defined by 1 point(s): [(2.0, 0.0)]\n Point set defined by 1 point(s): [(5.4, 0.0)]\n Text 'a' at the point (0.0,-0.1)\n Text 'b' at the point (1.0,-0.1)\n Text 'c' at the point (2.0,-0.1)\n Text 'd' at the point (-2.3,-0.1)\n Text 'e' at the point (5.4,-0.1)\n Arc with center (-0.6...,-1.65) radii (2.3334523779...,2.3334523779...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n Arc with center (1.0,-1.0) radii (1.4142135623...,1.4142135623...)\n angle 0.0 inside the sector (0.785398163397...,2.35619449019...)\n " from sage.plot.graphics import Graphics from sage.plot.point import point from sage.plot.text import text from sage.plot.arc import arc from sage.symbolic.constants import pi from sage.functions.trig import tan, sin from sage.functions.generalized import sgn diag = Graphics() sorted_vertices_list = list(self.base_set()) sorted_vertices_list.sort() if (angle is None): angle = (pi / 4) if (base_set_dict is not None): vertices_dict = base_set_dict else: vertices_dict = {val: pos for (pos, val) in enumerate(sorted_vertices_list)} for elt in vertices_dict: pos = vertices_dict[elt] diag += point((pos, 0), size=30, color=color) diag += text(elt, (pos, ((- sgn(angle)) * 0.1)), color=color) for (k, j) in self.arcs(): (pos_k, pos_j) = (float(vertices_dict[k]), float(vertices_dict[j])) center = (((pos_k + pos_j) / 2), ((- abs((pos_j - pos_k))) / (2 * tan(angle)))) r1 = abs(((pos_j - pos_k) / (2 * sin(angle)))) sector = ((sgn(angle) * ((pi / 2) - angle)), (sgn(angle) * ((pi / 2) + angle))) diag += arc(center=center, r1=r1, sector=sector, color=color) diag.axes(False) return diag
class SetPartitions(UniqueRepresentation, Parent): "\n An (unordered) partition of a set `S` is a set of pairwise\n disjoint nonempty subsets with union `S`, and is represented\n by a sorted list of such subsets.\n\n ``SetPartitions(s)`` returns the class of all set partitions of the set\n ``s``, which can be given as a set or a string; if a string, each\n character is considered an element.\n\n ``SetPartitions(n)``, where ``n`` is an integer, returns the class of\n all set partitions of the set `\\{1, 2, \\ldots, n\\}`.\n\n You may specify a second argument `k`. If `k` is an integer,\n :class:`SetPartitions` returns the class of set partitions into `k` parts;\n if it is an integer partition, :class:`SetPartitions` returns the class of\n set partitions whose block sizes correspond to that integer partition.\n\n The Bell number `B_n`, named in honor of Eric Temple Bell,\n is the number of different partitions of a set with `n` elements.\n\n EXAMPLES::\n\n sage: S = [1,2,3,4]\n sage: SetPartitions(S, 2)\n Set partitions of {1, 2, 3, 4} with 2 parts\n sage: SetPartitions([1,2,3,4], [3,1]).list() # needs sage.graphs sage.rings.finite_rings\n [{{1}, {2, 3, 4}}, {{1, 2, 3}, {4}}, {{1, 2, 4}, {3}}, {{1, 3, 4}, {2}}]\n sage: SetPartitions(7, [3,3,1]).cardinality() # needs sage.libs.flint\n 70\n\n In strings, repeated letters are not considered distinct as of\n :trac:`14140`::\n\n sage: SetPartitions('abcde').cardinality() # needs sage.libs.flint\n 52\n sage: SetPartitions('aabcd').cardinality() # needs sage.libs.flint\n 15\n\n REFERENCES:\n\n - :wikipedia:`Partition_of_a_set`\n " @staticmethod def __classcall_private__(cls, s=None, part=None): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: T = SetPartitions([1,2,3,4])\n sage: S is T\n True\n ' if (s is None): return SetPartitions_all() if isinstance(s, (int, Integer)): s = frozenset(range(1, (s + 1))) else: try: if (s.cardinality() == infinity): raise ValueError('the set must be finite') except AttributeError: pass s = frozenset(s) if (part is not None): if isinstance(part, (int, Integer)): if (len(s) < part): raise ValueError('part must be <= len(set)') return SetPartitions_setn(s, part) else: part = sorted(part, reverse=True) if (part not in Partitions(len(s))): raise ValueError(('part must be an integer partition of %s' % len(s))) return SetPartitions_setparts(s, Partition(part)) else: return SetPartitions_set(s) def __contains__(self, x): '\n TESTS::\n\n sage: S = SetPartitions(4, [2,2])\n sage: SA = SetPartitions()\n sage: all(sp in SA for sp in S) # needs sage.graphs sage.modules sage.rings.finite_rings\n True\n sage: Set([Set([1,2]),Set([3,7])]) in SA # needs sage.graphs\n True\n sage: Set([Set([1,2]),Set([2,3])]) in SA # needs sage.graphs\n False\n sage: Set([]) in SA # needs sage.graphs\n True\n ' if (not isinstance(x, (SetPartition, set, frozenset, Set_generic))): return False base_set = set((e for p in x for e in p)) if (len(base_set) != sum(map(len, x))): return False for s in x: if (not isinstance(s, (set, frozenset, Set_generic))): return False return True def _element_constructor_(self, s, check=True): '\n Construct an element of ``self`` from ``s``.\n\n INPUT:\n\n - ``s`` -- a set of sets\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: elt = S([[1,3],[2,4]]); elt\n {{1, 3}, {2, 4}}\n sage: P = SetPartitions()\n sage: P(elt).parent() is P\n True\n sage: S = SetPartitions([])\n sage: S([])\n {}\n ' if isinstance(s, SetPartition): if isinstance(s.parent(), SetPartitions): return self.element_class(self, s, check=check) raise ValueError(('cannot convert %s into an element of %s' % (s, self))) return self.element_class(self, s, check=check) Element = SetPartition def from_restricted_growth_word(self, w, bijection='blocks'): '\n Convert a word of length `n` with letters in the non-negative\n integers such that each letter is at most 1 larger than all\n the letters before to a set partition of `\\{1,...,n\\}`.\n\n INPUT:\n\n - ``w`` -- a restricted growth word.\n\n - ``bijection`` (default: ``blocks``) -- defines the map from\n restricted growth functions to set partitions. These are\n currently:\n\n - ``blocks``: .\n\n - ``intertwining``: :meth:`from_restricted_growth_word_intertwining`.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n :meth:`SetPartition.to_restricted_growth_word`\n\n EXAMPLES::\n\n sage: SetPartitions().from_restricted_growth_word([0, 1, 2, 0, 2, 2, 3, 1, 2])\n {{1, 4}, {2, 8}, {3, 5, 6, 9}, {7}}\n\n sage: SetPartitions().from_restricted_growth_word([0, 0, 1, 0, 2, 2, 0, 3, 1, 2, 2, 4, 2])\n {{1, 2, 4, 7}, {3, 9}, {5, 6, 10, 11, 13}, {8}, {12}}\n\n sage: SetPartitions().from_restricted_growth_word([0, 0, 1, 0, 2, 2, 0, 3, 1, 2, 2, 4, 2], "intertwining")\n {{1, 2, 6, 7, 9}, {3, 4}, {5, 10, 13}, {8, 11}, {12}}\n ' if (bijection == 'blocks'): return self.from_restricted_growth_word_blocks(w) if (bijection == 'intertwining'): return self.from_restricted_growth_word_intertwining(w) raise ValueError('the given bijection is not valid') def from_restricted_growth_word_blocks(self, w): '\n Convert a word of length `n` with letters in the non-negative\n integers such that each letter is at most 1 larger than all\n the letters before to a set partition of `\\{1,...,n\\}`.\n\n ``w[i]`` is the index of the block containing ``i+1`` when\n sorting the blocks by their minimal element.\n\n INPUT:\n\n - ``w`` -- a restricted growth word.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n :meth:`from_restricted_growth_word`\n :meth:`SetPartition.to_restricted_growth_word`\n\n EXAMPLES::\n\n sage: SetPartitions().from_restricted_growth_word_blocks([0, 0, 1, 0, 2, 2, 0, 3, 1, 2, 2, 4, 2])\n {{1, 2, 4, 7}, {3, 9}, {5, 6, 10, 11, 13}, {8}, {12}}\n ' R = [] for (i, B) in enumerate(w, 1): if (len(R) <= B): R.append([i]) else: R[B].append(i) return self.element_class(self, R) def from_restricted_growth_word_intertwining(self, w): '\n Convert a word of length `n` with letters in the non-negative\n integers such that each letter is at most 1 larger than all\n the letters before to a set partition of `\\{1,...,n\\}`.\n\n The `i`-th letter of the word is the numbers of crossings of\n the arc (or half-arc) in the extended arc diagram ending at\n `i`, with arcs (or half-arcs) beginning at a smaller element\n and ending at a larger element.\n\n INPUT:\n\n - ``w`` -- a restricted growth word.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n :meth:`from_restricted_growth_word`\n :meth:`SetPartition.to_restricted_growth_word`\n\n EXAMPLES::\n\n sage: SetPartitions().from_restricted_growth_word_intertwining([0, 0, 1, 0, 2, 2, 0, 3, 1, 2, 2, 4, 2])\n {{1, 2, 6, 7, 9}, {3, 4}, {5, 10, 13}, {8, 11}, {12}}\n ' if (len(w) == 0): return self.element_class(self, []) R = [[1]] C = [1] m = 0 for i in range(1, len(w)): if (w[i] == (1 + m)): m += 1 R.append([(i + 1)]) else: l = C[w[i]] B = next((B for B in R if (l in B))) B.append((i + 1)) C.remove(l) C = ([(i + 1)] + C) return self.element_class(self, R) def from_rook_placement(self, rooks, bijection='arcs', n=None): '\n Convert a rook placement of the triangular grid to a set\n partition of `\\{1,...,n\\}`.\n\n If ``n`` is not given, it is first checked whether it can be\n determined from the parent, otherwise it is the maximal\n occurring integer in the set of rooks.\n\n INPUT:\n\n - ``rooks`` -- a list of pairs `(i,j)` satisfying\n `0 < i < j < n+1`.\n\n - ``bijection`` (default: ``arcs``) -- defines the map from\n rook placements to set partitions. These are currently:\n\n - ``arcs``: :meth:`from_arcs`.\n - ``gamma``: :meth:`from_rook_placement_gamma`.\n - ``rho``: :meth:`from_rook_placement_rho`.\n - ``psi``: :meth:`from_rook_placement_psi`.\n\n - ``n`` -- (optional) the size of the ground set.\n\n .. SEEALSO::\n\n :meth:`SetPartition.to_rook_placement`\n\n EXAMPLES::\n\n sage: SetPartitions(9).from_rook_placement([[1,4],[2,8],[3,5],[5,6],[6,9]])\n {{1, 4}, {2, 8}, {3, 5, 6, 9}, {7}}\n\n sage: SetPartitions(13).from_rook_placement([[12,13],[10,12],[8,9],[7,11],[5,8],[4,6],[3,5],[1,4]], "gamma")\n {{1, 2, 4, 7}, {3, 9}, {5, 6, 10, 11, 13}, {8}, {12}}\n\n TESTS::\n\n sage: SetPartitions().from_rook_placement([])\n {}\n sage: SetPartitions().from_rook_placement([], "gamma")\n {}\n sage: SetPartitions().from_rook_placement([], "rho")\n {}\n sage: SetPartitions().from_rook_placement([], "psi")\n {}\n sage: SetPartitions().from_rook_placement([], n=2)\n {{1}, {2}}\n sage: SetPartitions().from_rook_placement([], "gamma", 2)\n {{1}, {2}}\n sage: SetPartitions().from_rook_placement([], "rho", 2)\n {{1}, {2}}\n sage: SetPartitions().from_rook_placement([], "psi", 2)\n {{1}, {2}}\n ' if (n is None): try: n = self.base_set_cardinality() except AttributeError: n = max((max(r) for r in rooks), default=0) if (bijection == 'arcs'): return self.from_arcs(rooks, n) if (bijection == 'rho'): return self.from_rook_placement_rho(rooks, n) if (bijection == 'gamma'): return self.from_rook_placement_gamma(rooks, n) if (bijection == 'psi'): return self.from_rook_placement_psi(rooks, n) raise ValueError('the given bijection is not valid') def from_arcs(self, arcs, n): '\n Return the coarsest set partition of `\\{1,...,n\\}` such that any\n two elements connected by an arc are in the same block.\n\n INPUT:\n\n - ``n`` -- an integer specifying the size of the set\n partition to be produced.\n\n - ``arcs`` -- a list of pairs specifying which elements are\n in the same block.\n\n .. SEEALSO::\n\n - :meth:`from_rook_placement`\n - :meth:`SetPartition.to_rook_placement`\n - :meth:`SetPartition.arcs`\n\n EXAMPLES::\n\n sage: SetPartitions().from_arcs([(2,3)], 5)\n {{1}, {2, 3}, {4}, {5}}\n ' P = DisjointSet(range(1, (n + 1))) for (i, j) in arcs: P.union(i, j) return self.element_class(self, P) def from_rook_placement_gamma(self, rooks, n): "\n Return the set partition of `\\{1,...,n\\}` corresponding to the\n given rook placement by applying Wachs and White's bijection\n gamma.\n\n Note that our index convention differs from the convention in\n [WW1991]_: regarding the rook board as a lower-right\n triangular grid, we refer with `(i,j)` to the cell in the\n `i`-th column from the right and the `j`-th row from the top.\n\n INPUT:\n\n - ``n`` -- an integer specifying the size of the set\n partition to be produced.\n\n - ``rooks`` -- a list of pairs `(i,j)` such that `0 < i < j < n+1`.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n - :meth:`from_rook_placement`\n - :meth:`SetPartition.to_rook_placement`\n - :meth:`SetPartition.to_rook_placement_gamma`\n\n EXAMPLES:\n\n Figure 5 in [WW1991]_ concerns the following rook placement::\n\n sage: r = [(1, 4), (3, 5), (4, 6), (5, 8), (7, 11), (8, 9), (10, 12), (12, 13)]\n\n Note that the rook `(1, 4)`, translated into Wachs and\n White's convention, is a rook in row 4 from the top and\n column 13 from the left. The corresponding set partition\n is::\n\n sage: SetPartitions().from_rook_placement_gamma(r, 13)\n {{1, 2, 4, 7}, {3, 9}, {5, 6, 10, 11, 13}, {8}, {12}}\n " if (n == 0): return self.element_class(self, []) C = [set(range(((n + 1) - j), (n + 1))) for j in range(1, n)] for (j, i) in rooks: C[((n - j) - 1)].difference_update(range((j + 1), (i + 1))) for l in range(((n + 1) - j), (n + 1)): C[(l - 2)].discard(i) w = ([0] + [len(c) for c in C]) return self.from_restricted_growth_word_blocks(w) def from_rook_placement_rho(self, rooks, n): "\n Return the set partition of `\\{1,...,n\\}` corresponding to the\n given rook placement by applying Wachs and White's bijection\n rho.\n\n Note that our index convention differs from the convention in\n [WW1991]_: regarding the rook board as a lower-right\n triangular grid, we refer with `(i,j)` to the cell in the\n `i`-th column from the right and the `j`-th row from the top.\n\n INPUT:\n\n - ``n`` -- an integer specifying the size of the set\n partition to be produced.\n\n - ``rooks`` -- a list of pairs `(i,j)` such that `0 < i < j < n+1`.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n - :meth:`from_rook_placement`\n - :meth:`SetPartition.to_rook_placement`\n - :meth:`SetPartition.to_rook_placement_rho`\n\n EXAMPLES:\n\n Figure 5 in [WW1991]_ concerns the following rook placement::\n\n sage: r = [(1, 2), (2, 6), (3, 4), (4, 10), (5, 9), (6, 7), (10, 11), (11, 13)]\n\n Note that the rook `(1, 2)`, translated into Wachs and\n White's convention, is a rook in row 2 from the top and\n column 13 from the left. The corresponding set partition\n is::\n\n sage: SetPartitions().from_rook_placement_rho(r, 13)\n {{1, 2, 4, 7}, {3, 9}, {5, 6, 10, 11, 13}, {8}, {12}}\n " cols = [j for (j, _) in rooks] R = [j for j in range(1, (n + 1)) if (j not in cols)] C = [(set(range(((n + 1) - j), (n + 1))) if ((n - j) not in R) else set()) for j in range(1, n)] for (j, i) in rooks: C[((n - j) - 1)].difference_update(range(i, (n + 1))) for l in range(((n + 1) - j), (n + 1)): C[(l - 2)].discard(i) C_flat = [i for c in C for i in c] rs = [C_flat.count(i) for i in range(1, (n + 1))] P = [[] for _ in R] for i in range(1, (n + 1)): k = rs[(i - 1)] b = 0 while ((k > 0) or (P[b] and (P[b][(- 1)] in R))): if (P[b][(- 1)] not in R): k -= 1 b += 1 P[b].append(i) return self.element_class(self, P) def from_rook_placement_psi(self, rooks, n): "\n Return the set partition of `\\{1,...,n\\}` corresponding to the\n given rook placement by applying Yip's bijection psi.\n\n INPUT:\n\n - ``n`` -- an integer specifying the size of the set\n partition to be produced.\n\n - ``rooks`` -- a list of pairs `(i,j)` such that `0 < i < j <\n n+1`.\n\n OUTPUT:\n\n A set partition.\n\n .. SEEALSO::\n\n - :meth:`from_rook_placement`\n - :meth:`SetPartition.to_rook_placement`\n - :meth:`SetPartition.to_rook_placement_psi`\n\n EXAMPLES:\n\n Example 36 (arXiv version: Example 4.5) in [Yip2018]_\n concerns the following rook placement::\n\n sage: r = [(4,5), (1,7), (3, 8), (7,9)]\n sage: SetPartitions().from_rook_placement_psi(r, 9)\n {{1, 5}, {2}, {3, 8, 9}, {4}, {6, 7}}\n " P = [] rooks_by_column = {j: i for (i, j) in rooks} for c in range(1, (n + 1)): try: r = rooks_by_column[c] n_rooks = 1 ne = ((r - 1) + sum((1 for (i, j) in rooks if ((i > r) and (j < c))))) except KeyError: n_rooks = 0 ne = sum((1 for (i, j) in rooks if (j < c))) b = ((c - n_rooks) - ne) if (len(P) == (b - 1)): P.append([c]) else: P[(b - 1)].append(c) P = sorted(P, key=(lambda B: ((- len(B)), min(B)))) return self.element_class(self, P) def is_less_than(self, s, t) -> bool: '\n Check if `s < t` in the refinement ordering on set partitions.\n\n This means that `s` is a refinement of `t` and satisfies\n `s \\neq t`.\n\n A set partition `s` is said to be a refinement of a set\n partition `t` of the same set if and only if each part of\n `s` is a subset of a part of `t`.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: s = S([[1,3],[2,4]])\n sage: t = S([[1],[2],[3],[4]])\n sage: S.is_less_than(t, s)\n True\n sage: S.is_less_than(s, t)\n False\n sage: S.is_less_than(s, s)\n False\n ' if hasattr(s.parent(), '_set'): S = s.parent()._set else: S = s.base_set() if hasattr(t.parent(), '_set'): T = t.parent()._set else: T = t.base_set() if (S != T): raise ValueError('cannot compare partitions of different sets') if (s == t): return False for p in s: x = next(iter(p)) for t_ in t: if (x in t_): break for p_ in p: if (p_ not in t_): return False return True lt = is_less_than def is_strict_refinement(self, s, t) -> bool: "\n Return ``True`` if ``s`` is a strict refinement of ``t`` and\n satisfies `s \\neq t`.\n\n A set partition `s` is said to be a strict refinement of a set\n partition `t` of the same set if and only if one can obtain\n `t` from `s` by repeatedly combining pairs of parts whose\n convex hulls don't intersect (i. e., whenever we are combining\n two parts, the maximum of each of them should be smaller than\n the minimum of the other).\n\n EXAMPLES::\n\n sage: S = SetPartitions(4)\n sage: s = S([[1],[2],[3],[4]])\n sage: t = S([[1,3],[2,4]])\n sage: u = S([[1,2,3,4]])\n sage: S.is_strict_refinement(s, t)\n True\n sage: S.is_strict_refinement(t, u)\n False\n sage: A = SetPartition([[1,3],[2,4]])\n sage: B = SetPartition([[1,2,3,4]])\n sage: S.is_strict_refinement(s, A)\n True\n sage: S.is_strict_refinement(t, B)\n False\n " if hasattr(s.parent(), '_set'): S = s.parent()._set else: S = frozenset(s.base_set()) if hasattr(t.parent(), '_set'): T = t.parent()._set else: T = frozenset(t.base_set()) if (S != T): raise ValueError('cannot compare partitions of different sets') if (s == t): return False for p in t: L = [x for x in s if x.issubset(p)] if ((sum((len(x) for x in L)) != len(p)) or any(((max(L[i]) > min(L[(i + 1)])) for i in range((len(L) - 1))))): return False return True
class SetPartitions_all(SetPartitions): '\n All set partitions.\n ' def __init__(self): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: S = SetPartitions()\n sage: TestSuite(S).run()\n ' SetPartitions.__init__(self, category=InfiniteEnumeratedSets()) def subset(self, size=None, **kwargs): '\n Return the subset of set partitions of a given size and\n additional keyword arguments.\n\n EXAMPLES::\n\n sage: P = SetPartitions()\n sage: P.subset(4)\n Set partitions of {1, 2, 3, 4}\n ' if (size is None): return self return SetPartitions(size, **kwargs) def _repr_(self): '\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions()\n Set partitions\n ' return 'Set partitions' def __iter__(self): '\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = SetPartitions().__iter__()\n sage: [next(it) for x in range(10)]\n [{}, {{1}}, {{1, 2}}, {{1}, {2}}, {{1, 2, 3}}, {{1, 2}, {3}},\n {{1, 3}, {2}}, {{1}, {2, 3}}, {{1}, {2}, {3}}, {{1, 2, 3, 4}}]\n ' n = 0 while True: for x in SetPartitions_set(frozenset(range(1, (n + 1)))): (yield self.element_class(self, list(x))) n += 1
class SetPartitions_set(SetPartitions): '\n Set partitions of a fixed set `S`.\n ' @staticmethod def __classcall_private__(cls, s): '\n Normalize ``s`` to ensure a unique representation.\n\n EXAMPLES::\n\n sage: S1 = SetPartitions(set([2,1,4]))\n sage: S2 = SetPartitions([4,1,2])\n sage: S3 = SetPartitions((1,2,4))\n sage: S1 is S2, S1 is S3\n (True, True)\n ' return super().__classcall__(cls, frozenset(s)) def __init__(self, s): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: S = SetPartitions(3)\n sage: TestSuite(S).run()\n sage: SetPartitions(0).list()\n [{}]\n sage: SetPartitions([]).list()\n [{}]\n ' self._set = s SetPartitions.__init__(self, category=FiniteEnumeratedSets()) def _repr_(self): '\n TESTS::\n\n sage: SetPartitions([1,2,3])\n Set partitions of {1, 2, 3}\n ' return ('Set partitions of %s' % Set(self._set)) def __contains__(self, x): '\n TESTS::\n\n sage: S = SetPartitions(4, [2,2])\n sage: all(sp in S for sp in S) # needs sage.graphs sage.rings.finite_rings\n True\n sage: SetPartition([[1,3],[2,4]]) in SetPartitions(3) # needs sage.graphs\n False\n sage: SetPartition([[1,3],[2,4]]) in SetPartitions(4, [3,1]) # needs sage.graphs\n False\n sage: SetPartition([[2],[1,3,4]]) in SetPartitions(4, [3,1]) # needs sage.graphs\n True\n ' if (not SetPartitions.__contains__(self, x)): return False if (sum(map(len, x)) != len(self._set)): return False return (Set((e for p in x for e in p)) == Set(self._set)) def random_element(self): '\n Return a random set partition.\n\n This is a very naive implementation of Knuths outline in F3B,\n 7.2.1.5.\n\n EXAMPLES::\n\n sage: S = SetPartitions(10)\n sage: s = S.random_element() # needs sage.symbolic\n sage: s.parent() is S # needs sage.symbolic\n True\n sage: assert s in S, s # needs sage.symbolic\n\n sage: S = SetPartitions(["a", "b", "c"])\n sage: s = S.random_element() # needs sage.symbolic\n sage: s.parent() is S # needs sage.symbolic\n True\n sage: assert s in S, s # needs sage.symbolic\n ' base_set = list(self.base_set()) N = len(base_set) from sage.symbolic.constants import e c = (float(e) * bell_number(N)) G = GeneralDiscreteDistribution([((float(m) ** N) / (c * factorial(m))) for m in range((4 * N))]) M = (G.get_random_element() - 1) l = (randint(0, M) for i in range(N)) p = {} for (i, b) in enumerate(l): if (b in p): p[b].append(base_set[i]) else: p[b] = [base_set[i]] return self.element_class(self, p.values(), check=False) def cardinality(self): '\n Return the number of set partitions of the set `S`.\n\n The cardinality is given by the `n`-th Bell number where `n` is the\n number of elements in the set `S`.\n\n EXAMPLES::\n\n sage: # needs sage.libs.flint\n sage: SetPartitions([1,2,3,4]).cardinality()\n 15\n sage: SetPartitions(3).cardinality()\n 5\n sage: SetPartitions(3,2).cardinality()\n 3\n sage: SetPartitions([]).cardinality()\n 1\n ' return bell_number(len(self._set)) def __iter__(self): '\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(3).list()\n [{{1, 2, 3}}, {{1, 2}, {3}}, {{1, 3}, {2}}, {{1}, {2, 3}}, {{1}, {2}, {3}}]\n\n sage: SetPartitions(["a", "b"]).list()\n [{{\'a\', \'b\'}}, {{\'a\'}, {\'b\'}}]\n ' for sp in set_partition_iterator(sorted(self._set)): (yield self.element_class(self, sp, check=False)) def base_set(self): '\n Return the base set of ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(3).base_set()\n {1, 2, 3}\n\n sage: sorted(SetPartitions(["a", "b", "c"]).base_set())\n [\'a\', \'b\', \'c\']\n ' return Set(self._set) def base_set_cardinality(self): '\n Return the cardinality of the base set of ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(3).base_set_cardinality()\n 3\n ' return len(self._set)
class SetPartitions_setparts(SetPartitions_set): '\n Set partitions with fixed partition sizes corresponding to an\n integer partition `\\lambda`.\n ' @staticmethod def __classcall_private__(cls, s, parts): '\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: S = SetPartitions(4, [2,2])\n sage: T = SetPartitions([1,2,3,4], Partition([2,2]))\n sage: S is T\n True\n\n sage: S = SetPartitions(4, [3,1])\n sage: T = SetPartitions(4, (1,3))\n sage: S is T\n True\n ' if isinstance(s, (int, Integer)): s = list(range(1, (s + 1))) return super().__classcall__(cls, frozenset(s), Partition(parts)) def __init__(self, s, parts): '\n Initialize the data structure.\n\n We can assume here that ``parts`` is a :class:`Partition`.\n\n TESTS::\n\n sage: S = SetPartitions(4, [2,2])\n sage: TestSuite(S).run() # needs sage.graphs sage.libs.flint\n ' SetPartitions_set.__init__(self, s) self._parts = parts def _repr_(self): '\n TESTS::\n\n sage: SetPartitions(4, [2,2])\n Set partitions of {1, 2, 3, 4} with sizes in [2, 2]\n ' return ('Set partitions of %s with sizes in %s' % (Set(self._set), self._parts)) def shape(self): '\n Return the partition of block sizes of the set partitions in ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(5, [2,2,1]).shape()\n [2, 2, 1]\n ' return self._parts def cardinality(self): '\n Return the cardinality of ``self``.\n\n This algorithm counts for each block of the partition the\n number of ways to fill it using values from the set. Then,\n for each distinct value `v` of block size, we divide the result by\n the number of ways to arrange the blocks of size `v` in the\n set partition.\n\n For example, if we want to count the number of set partitions\n of size 13 having [3,3,3,2,2] as underlying partition we\n compute the number of ways to fill each block of the\n partition, which is `\\binom{13}{3} \\binom{10}{3} \\binom{7}{3}\n \\binom{4}{2}\\binom{2}{2}` and as we have three blocks of size\n `3` and two blocks of size `2`, we divide the result by\n `3!2!` which gives us `600600`.\n\n EXAMPLES::\n\n sage: SetPartitions(3, [2,1]).cardinality()\n 3\n sage: SetPartitions(13, Partition([3,3,3,2,2])).cardinality()\n 600600\n\n TESTS::\n\n sage: all((len(SetPartitions(size, part)) == SetPartitions(size, part).cardinality() for size in range(8) for part in Partitions(size)))\n True\n sage: sum((SetPartitions(13, p).cardinality() # needs sage.libs.flint\n ....: for p in Partitions(13))) == SetPartitions(13).cardinality()\n True\n ' from sage.misc.misc_c import prod remaining_subset_size = Integer(len(self._set)) cardinal = Integer(1) for subset_size in self._parts: cardinal *= remaining_subset_size.binomial(subset_size) remaining_subset_size -= subset_size repetitions = (Integer(rep).factorial() for rep in self._parts.to_exp_dict().values() if (rep != 1)) cardinal /= prod(repetitions) return Integer(cardinal) def _set_partition_poset(self): '\n Return the Hasse diagram of a poset whose linear extensions correspond\n to the set partitions with specified block sizes.\n\n TESTS::\n\n sage: P = SetPartitions(["a", "b", "c", "d", "e"], # needs sage.graphs\n ....: [2,2,1])._set_partition_poset()\n sage: P.cover_relations() # needs sage.graphs\n [(1, 2), (1, 3), (3, 4)]\n\n sage: n = 9\n sage: all(SetPartitions(n, mu).cardinality() == # needs sage.graphs sage.modules\n ....: len(list(SetPartitions(n, mu)._set_partition_poset().linear_extensions()))\n ....: for mu in Partitions(n))\n True\n ' c = self._parts.to_exp_dict() covers = {} i = 0 for s in sorted(c): for m in range(c[s]): first = i if (s == 1): covers[i] = [] else: for _ in range((s - 1)): covers[i] = [(i + 1)] i += 1 i += 1 if (m < (c[s] - 1)): covers[first].append(i) return HasseDiagram(covers) def __iter__(self): '\n An iterator for all the set partitions of the given set with\n the given sizes.\n\n EXAMPLES::\n\n sage: SetPartitions(3, [2,1]).list() # needs sage.graphs sage.rings.finite_rings\n [{{1}, {2, 3}}, {{1, 2}, {3}}, {{1, 3}, {2}}]\n\n sage: SetPartitions(["a", "b", "c"], [2,1]).list() # needs sage.graphs sage.rings.finite_rings\n [{{\'a\'}, {\'b\', \'c\'}}, {{\'a\', \'b\'}, {\'c\'}}, {{\'a\', \'c\'}, {\'b\'}}]\n\n TESTS::\n\n sage: n = 8\n sage: all(SetPartitions(n, mu).cardinality() # needs sage.graphs sage.rings.finite_rings\n ....: == len(list(SetPartitions(n, mu))) for mu in Partitions(n))\n True\n ' k = len(self._parts) n = len(self._set) P = self._set_partition_poset() try: s = sorted(self._set) except TypeError: s = sorted(self._set, key=str) sums = [0] for b in sorted(self._parts): sums.append((sums[(- 1)] + b)) for ext in P.linear_extensions(): pi = ([None] * n) for i in range(n): pi[ext[i]] = s[i] sp = [[pi[j] for j in range(sums[i], sums[(i + 1)])] for i in range(k)] (yield self.element_class(self, sp, check=False)) def __contains__(self, x): '\n Check containment.\n\n TESTS::\n\n sage: S = SetPartitions(4, [3,1])\n sage: Set([Set([1,2,3]), Set([4])]) in S\n True\n sage: Set([Set([1,3]), Set([2,4])]) in S\n False\n sage: Set([Set([1,2,3,4])]) in S\n False\n ' if (not SetPartitions_set.__contains__(self, x)): return False return (sorted(map(len, x), reverse=True) == self._parts) def random_element(self): '\n Return a random set partition of ``self``.\n\n ALGORITHM:\n\n Based on the cardinality method. For each block size `k_i`,\n we choose a uniformly random subset `X_i \\subseteq S_i` of\n size `k_i` of the elements `S_i` that have not yet been selected.\n Thus, we define `S_{i+1} = S_i \\setminus X_i` with `S_i = S`\n being the defining set. This is not yet proven to be uniformly\n distributed, but numerical tests show this is likely uniform.\n\n EXAMPLES::\n\n sage: S = SetPartitions(10, [4,3,2,1])\n sage: s = S.random_element()\n sage: s.parent() is S\n True\n sage: assert s in S, s\n\n sage: S = SetPartitions(["a", "b", "c", "d"], [2,2])\n sage: s = S.random_element()\n sage: s.parent() is S\n True\n sage: assert s in S, s\n ' base_set = list(self.base_set()) N = len(base_set) ret = [] for p in self._parts: X = sample(range(N), p) ret.append([base_set[i] for i in X]) for i in sorted(X, reverse=True): del base_set[i] N -= p return self.element_class(self, ret, check=False)
class SetPartitions_setn(SetPartitions_set): '\n Set partitions with a given number of blocks.\n ' @staticmethod def __classcall_private__(cls, s, k): '\n Normalize ``s`` to ensure a unique representation.\n\n EXAMPLES::\n\n sage: S1 = SetPartitions(set([2,1,4]), 2)\n sage: S2 = SetPartitions([4,1,2], 2)\n sage: S3 = SetPartitions((1,2,4), 2)\n sage: S1 is S2, S1 is S3\n (True, True)\n ' return super().__classcall__(cls, frozenset(s), k) def __init__(self, s, k): '\n TESTS::\n\n sage: S = SetPartitions(5, 3)\n sage: TestSuite(S).run()\n ' self._k = k SetPartitions_set.__init__(self, s) def _repr_(self): '\n TESTS::\n\n sage: SetPartitions(5, 3)\n Set partitions of {1, 2, 3, 4, 5} with 3 parts\n ' return ('Set partitions of %s with %s parts' % (Set(self._set), self._k)) def number_of_blocks(self): '\n Return the number of blocks of the set partitions in ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(5, 3).number_of_blocks()\n 3\n ' return self._k def cardinality(self): '\n The Stirling number of the second kind is the number of partitions\n of a set of size `n` into `k` blocks.\n\n EXAMPLES::\n\n sage: SetPartitions(5, 3).cardinality()\n 25\n sage: stirling_number2(5,3)\n 25\n ' return stirling2(len(self._set), self._k) def __iter__(self): '\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: SetPartitions(4, 2).list()\n [{{1, 3, 4}, {2}},\n {{1, 4}, {2, 3}},\n {{1, 2, 4}, {3}},\n {{1, 3}, {2, 4}},\n {{1}, {2, 3, 4}},\n {{1, 2}, {3, 4}},\n {{1, 2, 3}, {4}}]\n\n sage: SetPartitions(["a", "b", "c"], 2).list()\n [{{\'a\', \'c\'}, {\'b\'}}, {{\'a\'}, {\'b\', \'c\'}}, {{\'a\', \'b\'}, {\'c\'}}]\n ' for sp in set_partition_iterator_blocks(sorted(self._set), self._k): (yield self.element_class(self, sp, check=False)) def __contains__(self, x): '\n Check containment.\n\n TESTS::\n\n sage: S = SetPartitions(4, 2)\n sage: Set([Set([1,2,3]), Set([4])]) in S\n True\n sage: Set([Set([1,3]), Set([2,4])]) in S\n True\n sage: Set([Set([1,2,3,4])]) in S\n False\n ' if (not SetPartitions_set.__contains__(self, x)): return False return (len(x) == self._k) def random_element(self): '\n Return a random set partition of ``self``.\n\n See https://mathoverflow.net/questions/141999.\n\n EXAMPLES::\n\n sage: S = SetPartitions(10, 4)\n sage: s = S.random_element()\n sage: s.parent() is S\n True\n sage: assert s in S, s\n\n sage: S = SetPartitions(["a", "b", "c"], 2)\n sage: s = S.random_element()\n sage: s.parent() is S\n True\n sage: assert s in S, s\n ' def re(N, k): if (N == 0): return [[]] if (N == 1): return [[0]] if (stirling2((N - 1), (k - 1)) > (random() * stirling2(N, k))): return ([[(N - 1)]] + re((N - 1), (k - 1))) p = re((N - 1), k) p[randint(0, (len(p) - 1))].append((N - 1)) return p base_set = list(self.base_set()) N = len(base_set) k = self._k p = re(N, k) return self.element_class(self, [[base_set[e] for e in b] for b in p], check=False)
def cyclic_permutations_of_set_partition(set_part): '\n Return all combinations of cyclic permutations of each cell of the\n set partition.\n\n AUTHORS:\n\n - Robert L. Miller\n\n EXAMPLES::\n\n sage: from sage.combinat.set_partition import cyclic_permutations_of_set_partition\n sage: cyclic_permutations_of_set_partition([[1,2,3,4],[5,6,7]])\n [[[1, 2, 3, 4], [5, 6, 7]],\n [[1, 2, 4, 3], [5, 6, 7]],\n [[1, 3, 2, 4], [5, 6, 7]],\n [[1, 3, 4, 2], [5, 6, 7]],\n [[1, 4, 2, 3], [5, 6, 7]],\n [[1, 4, 3, 2], [5, 6, 7]],\n [[1, 2, 3, 4], [5, 7, 6]],\n [[1, 2, 4, 3], [5, 7, 6]],\n [[1, 3, 2, 4], [5, 7, 6]],\n [[1, 3, 4, 2], [5, 7, 6]],\n [[1, 4, 2, 3], [5, 7, 6]],\n [[1, 4, 3, 2], [5, 7, 6]]]\n ' return list(cyclic_permutations_of_set_partition_iterator(set_part))
def cyclic_permutations_of_set_partition_iterator(set_part): '\n Iterates over all combinations of cyclic permutations of each cell\n of the set partition.\n\n AUTHORS:\n\n - Robert L. Miller\n\n EXAMPLES::\n\n sage: from sage.combinat.set_partition import cyclic_permutations_of_set_partition_iterator\n sage: list(cyclic_permutations_of_set_partition_iterator([[1,2,3,4],[5,6,7]]))\n [[[1, 2, 3, 4], [5, 6, 7]],\n [[1, 2, 4, 3], [5, 6, 7]],\n [[1, 3, 2, 4], [5, 6, 7]],\n [[1, 3, 4, 2], [5, 6, 7]],\n [[1, 4, 2, 3], [5, 6, 7]],\n [[1, 4, 3, 2], [5, 6, 7]],\n [[1, 2, 3, 4], [5, 7, 6]],\n [[1, 2, 4, 3], [5, 7, 6]],\n [[1, 3, 2, 4], [5, 7, 6]],\n [[1, 3, 4, 2], [5, 7, 6]],\n [[1, 4, 2, 3], [5, 7, 6]],\n [[1, 4, 3, 2], [5, 7, 6]]]\n ' from sage.combinat.permutation import CyclicPermutations if (len(set_part) == 1): for i in CyclicPermutations(set_part[0]): (yield [i]) else: for right in cyclic_permutations_of_set_partition_iterator(set_part[1:]): for perm in CyclicPermutations(set_part[0]): (yield ([perm] + right))
class OrderedSetPartition(ClonableArray, metaclass=InheritComparisonClasscallMetaclass): "\n An ordered partition of a set.\n\n An ordered set partition `p` of a set `s` is a list of pairwise\n disjoint nonempty subsets of `s` such that the union of these\n subsets is `s`. These subsets are called the parts of the partition.\n\n We represent an ordered set partition as a list of sets. By\n extension, an ordered set partition of a nonnegative integer `n` is\n the set partition of the integers from `1` to `n`. The number of\n ordered set partitions of `n` is called the `n`-th ordered Bell\n number.\n\n There is a natural integer composition associated with an ordered\n set partition, that is the sequence of sizes of all its parts in\n order.\n\n The number `T_n` of ordered set partitions of\n `\\{ 1, 2, \\ldots, n \\}` is the so-called `n`-th *Fubini number*\n (also known as the `n`-th ordered Bell number; see\n :wikipedia:`Ordered Bell number`). Its exponential generating\n function is\n\n .. MATH::\n\n \\sum_n \\frac{T_n}{n!} x^n = \\frac{1}{2-e^x}.\n\n (See sequence :oeis:`A000670` in OEIS.)\n\n INPUT:\n\n - ``parts`` -- an object or iterable that defines an ordered set partition\n (e.g., a list of pairwise disjoint sets) or a packed word (e.g., a list\n of letters on some alphabet). If there is ambiguity and if the input should\n be treated as a packed word, the keyword ``from_word`` should be used.\n\n EXAMPLES:\n\n There are 13 ordered set partitions of `\\{1,2,3\\}`::\n\n sage: OrderedSetPartitions(3).cardinality()\n 13\n\n Here is the list of them::\n\n sage: OrderedSetPartitions(3).list()\n [[{1}, {2}, {3}],\n [{1}, {3}, {2}],\n [{2}, {1}, {3}],\n [{3}, {1}, {2}],\n [{2}, {3}, {1}],\n [{3}, {2}, {1}],\n [{1}, {2, 3}],\n [{2}, {1, 3}],\n [{3}, {1, 2}],\n [{1, 2}, {3}],\n [{1, 3}, {2}],\n [{2, 3}, {1}],\n [{1, 2, 3}]]\n\n There are 12 ordered set partitions of `\\{1,2,3,4\\}` whose underlying\n composition is `[1,2,1]`::\n\n sage: OrderedSetPartitions(4,[1,2,1]).list()\n [[{1}, {2, 3}, {4}],\n [{1}, {2, 4}, {3}],\n [{1}, {3, 4}, {2}],\n [{2}, {1, 3}, {4}],\n [{2}, {1, 4}, {3}],\n [{3}, {1, 2}, {4}],\n [{4}, {1, 2}, {3}],\n [{3}, {1, 4}, {2}],\n [{4}, {1, 3}, {2}],\n [{2}, {3, 4}, {1}],\n [{3}, {2, 4}, {1}],\n [{4}, {2, 3}, {1}]]\n\n Since :trac:`14140`, we can create an ordered set partition directly by\n :class:`OrderedSetPartition` which creates the parent object by taking the\n union of the partitions passed in. However it is recommended and\n (marginally) faster to create the parent first and then create the ordered\n set partition from that. ::\n\n sage: s = OrderedSetPartition([[1,3],[2,4]]); s\n [{1, 3}, {2, 4}]\n sage: s.parent()\n Ordered set partitions of {1, 2, 3, 4}\n\n We can construct the ordered set partition from a word,\n which we consider as packed::\n\n sage: OrderedSetPartition([2,4,1,2])\n [{3}, {1, 4}, {2}]\n sage: OrderedSetPartition(from_word=[2,4,1,2])\n [{3}, {1, 4}, {2}]\n sage: OrderedSetPartition(from_word='bdab')\n [{3}, {1, 4}, {2}]\n\n .. WARNING::\n\n The elements of the underlying set should be hashable.\n\n REFERENCES:\n\n :wikipedia:`Ordered_partition_of_a_set`\n " @staticmethod def __classcall_private__(cls, parts=None, from_word=None, check=True): "\n Create a set partition from ``parts`` with the appropriate parent.\n\n EXAMPLES::\n\n sage: s = OrderedSetPartition([[1,3],[2,4]]); s\n [{1, 3}, {2, 4}]\n sage: s.parent()\n Ordered set partitions of {1, 2, 3, 4}\n sage: t = OrderedSetPartition([[2,4],[1,3]]); t\n [{2, 4}, {1, 3}]\n sage: s != t\n True\n sage: OrderedSetPartition()\n []\n sage: OrderedSetPartition([])\n []\n sage: OrderedSetPartition('')\n []\n sage: OrderedSetPartition('bdab') == OrderedSetPartition(from_word='bdab')\n True\n sage: OrderedSetPartition('bdab') == OrderedSetPartition(Word('bdab'))\n True\n " if ((parts is None) and (from_word is None)): P = OrderedSetPartitions([]) return P.element_class(P, []) W = Words(infinite=False) if from_word: return OrderedSetPartitions().from_finite_word(W(from_word)) if ((parts in W) or (parts and ((parts[0] in ZZ) or isinstance(parts[0], str)))): return OrderedSetPartitions().from_finite_word(W(parts)) P = OrderedSetPartitions(set((x for p in parts for x in p))) return P.element_class(P, parts, check=check) def __init__(self, parent, s, check=True): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions(4)\n sage: s = OS([[1, 3], [2, 4]])\n sage: TestSuite(s).run()\n ' ClonableArray.__init__(self, parent, [frozenset(part) for part in s], check=check) def _repr_(self): "\n Return a string representation of ``self``.\n\n .. TODO::\n\n Sort the repr output of Sage's :class:`Set` and remove\n this method.\n\n EXAMPLES::\n\n sage: OrderedSetPartition([[1,3],[2,4]])\n [{1, 3}, {2, 4}]\n " return (('[' + ', '.join(((('{' + repr(sorted(x))[1:(- 1)]) + '}') for x in self))) + ']') def check(self): '\n Check that we are a valid ordered set partition.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions(4)\n sage: s = OS([[1, 3], [2, 4]])\n sage: s.check()\n ' par = parent(self) assert (self in par), ('%s not in %s' % (self, par)) def base_set(self): "\n Return the base set of ``self``.\n\n This is the union of all parts of ``self``.\n\n EXAMPLES::\n\n sage: OrderedSetPartition([[1], [2,3], [4]]).base_set()\n frozenset({1, 2, 3, 4})\n sage: OrderedSetPartition([[1,2,3,4]]).base_set()\n frozenset({1, 2, 3, 4})\n sage: OrderedSetPartition([]).base_set()\n frozenset()\n\n TESTS::\n\n sage: S = OrderedSetPartitions()\n sage: x = S([['a', 'c', 'e'], ['b', 'd']])\n sage: x.base_set()\n frozenset({'a', 'b', 'c', 'd', 'e'})\n " try: return parent(self)._set except AttributeError: return frozenset((x for part in self for x in part)) def base_set_cardinality(self): '\n Return the cardinality of the base set of ``self``.\n\n This is the sum of the sizes of the parts of ``self``.\n\n This is also known as the *size* (sometimes the *weight*) of\n an ordered set partition.\n\n EXAMPLES::\n\n sage: OrderedSetPartition([[1], [2,3], [4]]).base_set_cardinality()\n 4\n sage: OrderedSetPartition([[1,2,3,4]]).base_set_cardinality()\n 4\n\n TESTS::\n\n sage: S = OrderedSetPartitions()\n sage: S([[1,4],[3],[2]]).base_set_cardinality()\n 4\n ' try: return len(parent(self)._set) except AttributeError: return sum((len(part) for part in self)) size = base_set_cardinality def length(self): '\n Return the number of parts of ``self``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions(4)\n sage: s = OS([[1, 3], [2, 4]])\n sage: s.length()\n 2\n ' return len(self) @combinatorial_map(name='to composition') def to_composition(self): '\n Return the integer composition whose parts are the sizes of the sets\n in ``self``.\n\n EXAMPLES::\n\n sage: S = OrderedSetPartitions(5)\n sage: x = S([[3,5,4], [1, 2]])\n sage: x.to_composition()\n [3, 2]\n sage: y = S([[3,1], [2], [5,4]])\n sage: y.to_composition()\n [2, 1, 2]\n ' return Composition([len(p) for p in self]) @staticmethod def sum(osps): '\n Return the concatenation of the given ordered set partitions\n ``osps`` (provided they have no elements in common).\n\n INPUT:\n\n - ``osps`` -- a list (or iterable) of ordered set partitions\n\n EXAMPLES::\n\n sage: OrderedSetPartition.sum([OrderedSetPartition([[4, 1], [3]]), OrderedSetPartition([[7], [2]]), OrderedSetPartition([[5, 6]])])\n [{1, 4}, {3}, {7}, {2}, {5, 6}]\n\n Any iterable can be provided as input::\n\n sage: OrderedSetPartition.sum([OrderedSetPartition([[2*i,2*i+1]]) for i in [4,1,3]])\n [{8, 9}, {2, 3}, {6, 7}]\n\n Empty inputs are handled gracefully::\n\n sage: OrderedSetPartition.sum([]) == OrderedSetPartition([])\n True\n\n TESTS::\n\n sage: A = OrderedSetPartitions(3)([[2], [1, 3]])\n sage: B = OrderedSetPartitions([5])([[5]])\n sage: C = OrderedSetPartition.sum([A, B]); C\n [{2}, {1, 3}, {5}]\n sage: C.parent()\n Ordered set partitions of {1, 2, 3, 5}\n ' lset = set((x for osp in osps for x in osp.base_set())) return OrderedSetPartitions(lset)(sum((list(i) for i in osps), [])) def reversed(self): '\n Return the reversal of the ordered set partition ``self``.\n\n The *reversal* of an ordered set partition\n `(P_1, P_2, \\ldots, P_k)` is defined to be the ordered\n set partition `(P_k, P_{k-1}, \\ldots, P_1)`.\n\n EXAMPLES::\n\n sage: OrderedSetPartition([[1, 3], [2]]).reversed()\n [{2}, {1, 3}]\n sage: OrderedSetPartition([[1, 5], [2, 4]]).reversed()\n [{2, 4}, {1, 5}]\n sage: OrderedSetPartition([[-1], [-2], [3, 4], [0]]).reversed()\n [{0}, {3, 4}, {-2}, {-1}]\n sage: OrderedSetPartition([]).reversed()\n []\n ' par = parent(self) return par(list(reversed(self))) def complement(self): '\n Return the complement of the ordered set partition ``self``.\n\n This assumes that ``self`` is an ordered set partition of\n an interval of `\\ZZ`.\n\n Let `(P_1, P_2, \\ldots, P_k)` be an ordered set partition\n of some interval `I` of `\\ZZ`. Let `\\omega` be the unique\n strictly decreasing bijection `I \\to I`. Then, the\n *complement* of `(P_1, P_2, \\ldots, P_k)` is defined to be\n the ordered set partition\n `(\\omega(P_1), \\omega(P_2), \\ldots, \\omega(P_k))`.\n\n EXAMPLES::\n\n sage: OrderedSetPartition([[1, 2], [3]]).complement()\n [{2, 3}, {1}]\n sage: OrderedSetPartition([[1, 3], [2]]).complement()\n [{1, 3}, {2}]\n sage: OrderedSetPartition([[2, 3]]).complement()\n [{2, 3}]\n sage: OrderedSetPartition([[1, 5], [2, 3], [4]]).complement()\n [{1, 5}, {3, 4}, {2}]\n sage: OrderedSetPartition([[-1], [-2], [1, 2], [0]]).complement()\n [{1}, {2}, {-2, -1}, {0}]\n sage: OrderedSetPartition([]).complement()\n []\n ' if (len(self) <= 1): return self base_set = self.base_set() m = min(base_set) M = max(base_set) mM = (m + M) par = parent(self) return par([[(mM - i) for i in part] for part in self]) def finer(self): '\n Return the set of ordered set partitions which are finer\n than ``self``.\n\n See :meth:`is_finer` for the definition of "finer".\n\n EXAMPLES::\n\n sage: C = OrderedSetPartition([[1, 3], [2]]).finer()\n sage: C.cardinality()\n 3\n sage: C.list()\n [[{1}, {3}, {2}], [{3}, {1}, {2}], [{1, 3}, {2}]]\n\n sage: OrderedSetPartition([]).finer()\n {[]}\n\n sage: W = OrderedSetPartition([[4, 9], [-1, 2]])\n sage: W.finer().list()\n [[{9}, {4}, {2}, {-1}],\n [{9}, {4}, {-1}, {2}],\n [{9}, {4}, {-1, 2}],\n [{4}, {9}, {2}, {-1}],\n [{4}, {9}, {-1}, {2}],\n [{4}, {9}, {-1, 2}],\n [{4, 9}, {2}, {-1}],\n [{4, 9}, {-1}, {2}],\n [{4, 9}, {-1, 2}]]\n ' par = parent(self) if (not self): return FiniteEnumeratedSet([self]) return FiniteEnumeratedSet([par(sum((list(i) for i in C), [])) for C in product(*[OrderedSetPartitions(X) for X in self])]) def is_finer(self, co2): '\n Return ``True`` if the ordered set partition ``self`` is finer\n than the ordered set partition ``co2``; otherwise, return ``False``.\n\n If `A` and `B` are two ordered set partitions of the same set,\n then `A` is said to be *finer* than `B` if `B` can be obtained\n from `A` by (repeatedly) merging consecutive parts.\n In this case, we say that `B` is *fatter* than `A`.\n\n EXAMPLES::\n\n sage: A = OrderedSetPartition([[1, 3], [2]])\n sage: B = OrderedSetPartition([[1], [3], [2]])\n sage: A.is_finer(B)\n False\n sage: B.is_finer(A)\n True\n sage: C = OrderedSetPartition([[3], [1], [2]])\n sage: A.is_finer(C)\n False\n sage: C.is_finer(A)\n True\n sage: OrderedSetPartition([[2], [5], [1], [4]]).is_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n True\n sage: OrderedSetPartition([[5], [2], [1], [4]]).is_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n True\n sage: OrderedSetPartition([[2], [1], [5], [4]]).is_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n False\n sage: OrderedSetPartition([[2, 5, 1], [4]]).is_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n False\n ' co1 = self if (co1.base_set() != co2.base_set()): raise ValueError(('ordered set partitions self (= %s) and co2 (= %s) must be of the same set' % (self, co2))) i1 = 0 for j2 in co2: sum1 = set() while (len(sum1) < len(j2)): sum1 = sum1.union(co1[i1]) i1 += 1 if (not sum1.issubset(j2)): return False return True def fatten(self, grouping): '\n Return the ordered set partition fatter than ``self``, obtained\n by grouping together consecutive parts according to the integer\n composition ``grouping``.\n\n See :meth:`finer` for the definition of "fatter".\n\n INPUT:\n\n - ``grouping`` -- a composition whose sum is the length of ``self``\n\n EXAMPLES:\n\n Let us start with the ordered set partition::\n\n sage: c = OrderedSetPartition([[2, 5], [1], [3, 4]])\n\n With ``grouping`` equal to `(1, \\ldots, 1)`, `c` is left unchanged::\n\n sage: c.fatten(Composition([1,1,1]))\n [{2, 5}, {1}, {3, 4}]\n\n With ``grouping`` equal to `(\\ell)` where `\\ell` is the length of\n `c`, this yields the coarsest ordered set partition above `c`::\n\n sage: c.fatten(Composition([3]))\n [{1, 2, 3, 4, 5}]\n\n Other values for ``grouping`` yield (all the) other ordered\n set partitions coarser than `c`::\n\n sage: c.fatten(Composition([2,1]))\n [{1, 2, 5}, {3, 4}]\n sage: c.fatten(Composition([1,2]))\n [{2, 5}, {1, 3, 4}]\n\n TESTS::\n\n sage: OrderedSetPartition([]).fatten(Composition([]))\n []\n sage: c.fatten(Composition([2,1])).__class__ == c.__class__\n True\n ' result = ([None] * len(grouping)) j = 0 for i in range(len(grouping)): result[i] = set().union(*self[j:(j + grouping[i])]) j += grouping[i] return parent(self)(result) def fatter(self): '\n Return the set of ordered set partitions which are fatter\n than ``self``.\n\n See :meth:`finer` for the definition of "fatter".\n\n EXAMPLES::\n\n sage: C = OrderedSetPartition([[2, 5], [1], [3, 4]]).fatter()\n sage: C.cardinality()\n 4\n sage: sorted(C)\n [[{2, 5}, {1}, {3, 4}],\n [{2, 5}, {1, 3, 4}],\n [{1, 2, 5}, {3, 4}],\n [{1, 2, 3, 4, 5}]]\n\n sage: OrderedSetPartition([[4, 9], [-1, 2]]).fatter().list()\n [[{4, 9}, {-1, 2}], [{-1, 2, 4, 9}]]\n\n Some extreme cases::\n\n sage: list(OrderedSetPartition([[5]]).fatter())\n [[{5}]]\n sage: list(Composition([]).fatter())\n [[]]\n sage: sorted(OrderedSetPartition([[1], [2], [3], [4]]).fatter())\n [[{1}, {2}, {3}, {4}],\n [{1}, {2}, {3, 4}],\n [{1}, {2, 3}, {4}],\n [{1}, {2, 3, 4}],\n [{1, 2}, {3}, {4}],\n [{1, 2}, {3, 4}],\n [{1, 2, 3}, {4}],\n [{1, 2, 3, 4}]]\n ' return Compositions(len(self)).map(self.fatten) @staticmethod def bottom_up_osp(X, comp): '\n Return the ordered set partition obtained by listing the\n elements of the set ``X`` in increasing order, and\n placing bars between some of them according to the\n integer composition ``comp`` (namely, the bars are placed\n in such a way that the lengths of the resulting blocks are\n exactly the entries of ``comp``).\n\n INPUT:\n\n - ``X`` -- a finite set (or list or tuple)\n\n - ``comp`` -- a composition whose sum is the size of ``X``\n (can be given as a list or tuple or composition)\n\n EXAMPLES::\n\n sage: buo = OrderedSetPartition.bottom_up_osp\n sage: buo(Set([1, 4, 7, 9]), [2, 1, 1])\n [{1, 4}, {7}, {9}]\n sage: buo(Set([1, 4, 7, 9]), [1, 3])\n [{1}, {4, 7, 9}]\n sage: buo(Set([1, 4, 7, 9]), [1, 1, 1, 1])\n [{1}, {4}, {7}, {9}]\n sage: buo(range(8), [1, 4, 2, 1])\n [{0}, {1, 2, 3, 4}, {5, 6}, {7}]\n sage: buo([], [])\n []\n\n TESTS::\n\n sage: buo = OrderedSetPartition.bottom_up_osp\n sage: parent(buo(Set([1, 4, 7, 9]), [2, 1, 1]))\n Ordered set partitions of {1, 4, 9, 7}\n sage: buo((3, 5, 6), (2, 1))\n [{3, 5}, {6}]\n sage: buo([3, 5, 6], Composition([1, 2]))\n [{3}, {5, 6}]\n ' xs = sorted(X) result = ([None] * len(comp)) j = 0 for i in range(len(comp)): result[i] = set(xs[j:(j + comp[i])]) j += comp[i] return OrderedSetPartitions(X)(result) def strongly_finer(self): '\n Return the set of ordered set partitions which are strongly\n finer than ``self``.\n\n See :meth:`is_strongly_finer` for the definition of "strongly\n finer".\n\n EXAMPLES::\n\n sage: C = OrderedSetPartition([[1, 3], [2]]).strongly_finer()\n sage: C.cardinality()\n 2\n sage: C.list()\n [[{1}, {3}, {2}], [{1, 3}, {2}]]\n\n sage: OrderedSetPartition([]).strongly_finer()\n {[]}\n\n sage: W = OrderedSetPartition([[4, 9], [-1, 2]])\n sage: W.strongly_finer().list()\n [[{4}, {9}, {-1}, {2}],\n [{4}, {9}, {-1, 2}],\n [{4, 9}, {-1}, {2}],\n [{4, 9}, {-1, 2}]]\n ' par = parent(self) if (not self): return FiniteEnumeratedSet([self]) buo = OrderedSetPartition.bottom_up_osp return FiniteEnumeratedSet([par(sum((list(P) for P in C), [])) for C in product(*[[buo(X, comp) for comp in Compositions(len(X))] for X in self])]) def is_strongly_finer(self, co2): '\n Return ``True`` if the ordered set partition ``self`` is strongly\n finer than the ordered set partition ``co2``; otherwise, return\n ``False``.\n\n If `A` and `B` are two ordered set partitions of the same set,\n then `A` is said to be *strongly finer* than `B` if `B` can be\n obtained from `A` by (repeatedly) merging consecutive parts,\n provided that every time we merge two consecutive parts `C_i`\n and `C_{i+1}`, we have `\\max C_i < \\min C_{i+1}`.\n In this case, we say that `B` is *strongly fatter* than `A`.\n\n EXAMPLES::\n\n sage: A = OrderedSetPartition([[1, 3], [2]])\n sage: B = OrderedSetPartition([[1], [3], [2]])\n sage: A.is_strongly_finer(B)\n False\n sage: B.is_strongly_finer(A)\n True\n sage: C = OrderedSetPartition([[3], [1], [2]])\n sage: A.is_strongly_finer(C)\n False\n sage: C.is_strongly_finer(A)\n False\n sage: OrderedSetPartition([[2], [5], [1], [4]]).is_strongly_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n True\n sage: OrderedSetPartition([[5], [2], [1], [4]]).is_strongly_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n False\n sage: OrderedSetPartition([[2], [1], [5], [4]]).is_strongly_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n False\n sage: OrderedSetPartition([[2, 5, 1], [4]]).is_strongly_finer(OrderedSetPartition([[2, 5], [1, 4]]))\n False\n ' co1 = self if (co1.base_set() != co2.base_set()): raise ValueError(('ordered set partitions self (= %s) and co2 (= %s) must be of the same set' % (self, co2))) i1 = 0 for j2 in co2: sum1 = set() while (len(sum1) < len(j2)): next = co1[i1] if (sum1 and (max(sum1) >= min(next))): return False sum1 = sum1.union(next) i1 += 1 if (not sum1.issubset(j2)): return False return True def strongly_fatter(self): '\n Return the set of ordered set partitions which are strongly fatter\n than ``self``.\n\n See :meth:`strongly_finer` for the definition of "strongly fatter".\n\n EXAMPLES::\n\n sage: C = OrderedSetPartition([[2, 5], [1], [3, 4]]).strongly_fatter()\n sage: C.cardinality()\n 2\n sage: sorted(C)\n [[{2, 5}, {1}, {3, 4}], [{2, 5}, {1, 3, 4}]]\n\n sage: OrderedSetPartition([[4, 9], [-1, 2]]).strongly_fatter().list()\n [[{4, 9}, {-1, 2}]]\n\n Some extreme cases::\n\n sage: list(OrderedSetPartition([[5]]).strongly_fatter())\n [[{5}]]\n sage: list(OrderedSetPartition([]).strongly_fatter())\n [[]]\n sage: sorted(OrderedSetPartition([[1], [2], [3], [4]]).strongly_fatter())\n [[{1}, {2}, {3}, {4}],\n [{1}, {2}, {3, 4}],\n [{1}, {2, 3}, {4}],\n [{1}, {2, 3, 4}],\n [{1, 2}, {3}, {4}],\n [{1, 2}, {3, 4}],\n [{1, 2, 3}, {4}],\n [{1, 2, 3, 4}]]\n sage: sorted(OrderedSetPartition([[1], [3], [2], [4]]).strongly_fatter())\n [[{1}, {3}, {2}, {4}],\n [{1}, {3}, {2, 4}],\n [{1, 3}, {2}, {4}],\n [{1, 3}, {2, 4}]]\n sage: sorted(OrderedSetPartition([[4], [1], [5], [3]]).strongly_fatter())\n [[{4}, {1}, {5}, {3}], [{4}, {1, 5}, {3}]]\n ' c = [sorted(X) for X in self] l = (len(c) - 1) g = (([(- 1)] + [i for i in range(l) if (c[i][(- 1)] > c[(i + 1)][0])]) + [l]) subcomps = [OrderedSetPartition(c[(g[i] + 1):(g[(i + 1)] + 1)]) for i in range((len(g) - 1))] fattenings = [list(subcomp.fatter()) for subcomp in subcomps] return FiniteEnumeratedSet([OrderedSetPartition(sum([list(gg) for gg in fattening], [])) for fattening in product(*fattenings)]) @combinatorial_map(name='to packed word') def to_packed_word(self): "\n Return the packed word on alphabet `\\{1,2,3,\\ldots\\}`\n corresponding to ``self``.\n\n A *packed word* on alphabet `\\{1,2,3,\\ldots\\}` is any word whose\n maximum letter is the same as its total number of distinct letters.\n Let `P` be an ordered set partition of a set `X`.\n The corresponding packed word `w_1 w_2 \\cdots w_n` is constructed\n by having letter `w_i = j` if the `i`-th smallest entry in `X`\n occurs in the `j`-th block of `P`.\n\n .. SEEALSO::\n\n :meth:`Word.to_ordered_set_partition`\n\n .. WARNING::\n\n This assumes there is a total order on the underlying\n set.\n\n EXAMPLES::\n\n sage: S = OrderedSetPartitions()\n sage: x = S([[3,5], [2], [1,4,6]])\n sage: x.to_packed_word()\n word: 321313\n\n sage: x = S([['a', 'c', 'e'], ['b', 'd']])\n sage: x.to_packed_word()\n word: 12121\n " X = sorted(self.base_set()) out = {} for i in range(len(self)): for letter in self[i]: out[letter] = i W = Words(infinite=False) return W([(out[letter] + 1) for letter in X]) def number_of_inversions(self): '\n Return the number of inversions in ``self``.\n\n An inversion of an ordered set partition with blocks\n `[B_1,B_2, \\ldots, B_k]` is a pair of letters `i` and `j` with `i < j`\n such that `i` is minimal in `B_m`, `j \\in B_l`, and `l < m`.\n\n REFERENCES:\n\n - [Wilson2016]_\n\n EXAMPLES::\n\n sage: OrderedSetPartition([{2,5},{4,6},{1,3}]).number_of_inversions()\n 5\n sage: OrderedSetPartition([{1,3,8},{2,4},{5,6,7}]).number_of_inversions()\n 3\n\n TESTS::\n\n sage: OrderedSetPartition([{1,3,8},{2,4},{5,6,7}]).number_of_inversions().parent()\n Integer Ring\n ' num_invs = 0 for (m, part) in enumerate(self): i = min(part) for ell in range(m): num_invs += sum((1 for j in self[ell] if (i < j))) return ZZ(num_invs)
class OrderedSetPartitions(UniqueRepresentation, Parent): '\n Return the combinatorial class of ordered set partitions of ``s``.\n\n The optional argument ``c``, if specified, restricts the parts of\n the partition to have certain sizes (the entries of ``c``).\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions([1,2,3,4]); OS\n Ordered set partitions of {1, 2, 3, 4}\n sage: OS.cardinality()\n 75\n sage: OS.first()\n [{1}, {2}, {3}, {4}]\n sage: OS.last()\n [{1, 2, 3, 4}]\n sage: OS.random_element().parent() is OS\n True\n\n ::\n\n sage: OS = OrderedSetPartitions([1,2,3,4], [2,2]); OS\n Ordered set partitions of {1, 2, 3, 4} into parts of size [2, 2]\n sage: OS.cardinality()\n 6\n sage: OS.first()\n [{1, 2}, {3, 4}]\n sage: OS.last()\n [{3, 4}, {1, 2}]\n sage: OS.list()\n [[{1, 2}, {3, 4}],\n [{1, 3}, {2, 4}],\n [{1, 4}, {2, 3}],\n [{2, 3}, {1, 4}],\n [{2, 4}, {1, 3}],\n [{3, 4}, {1, 2}]]\n\n ::\n\n sage: OS = OrderedSetPartitions("cat")\n sage: OS # random\n Ordered set partitions of {\'a\', \'t\', \'c\'}\n sage: sorted(OS.list(), key=str)\n [[{\'a\', \'c\', \'t\'}],\n [{\'a\', \'c\'}, {\'t\'}],\n [{\'a\', \'t\'}, {\'c\'}],\n [{\'a\'}, {\'c\', \'t\'}],\n [{\'a\'}, {\'c\'}, {\'t\'}],\n [{\'a\'}, {\'t\'}, {\'c\'}],\n [{\'c\', \'t\'}, {\'a\'}],\n [{\'c\'}, {\'a\', \'t\'}],\n [{\'c\'}, {\'a\'}, {\'t\'}],\n [{\'c\'}, {\'t\'}, {\'a\'}],\n [{\'t\'}, {\'a\', \'c\'}],\n [{\'t\'}, {\'a\'}, {\'c\'}],\n [{\'t\'}, {\'c\'}, {\'a\'}]]\n\n TESTS::\n\n sage: S = OrderedSetPartitions()\n sage: x = S([[3,5], [2], [1,4,6]])\n sage: x.parent()\n Ordered set partitions\n ' @staticmethod def __classcall_private__(cls, s=None, c=None): '\n Choose the correct parent based upon input.\n\n EXAMPLES::\n\n sage: OrderedSetPartitions(4)\n Ordered set partitions of {1, 2, 3, 4}\n sage: OrderedSetPartitions(4, [1, 2, 1])\n Ordered set partitions of {1, 2, 3, 4} into parts of size [1, 2, 1]\n ' if (s is None): if (c is not None): raise NotImplementedError("cannot specify 'c' without specifying 's'") return OrderedSetPartitions_all() if isinstance(s, (int, Integer)): if (s < 0): raise ValueError('s must be non-negative') s = frozenset(range(1, (s + 1))) else: s = frozenset(s) if (c is None): return OrderedSetPartitions_s(s) if isinstance(c, (int, Integer)): return OrderedSetPartitions_sn(s, c) if (c not in Compositions(len(s))): raise ValueError(('c must be a composition of %s' % len(s))) return OrderedSetPartitions_scomp(s, Composition(c)) def __init__(self, s): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions(4)\n sage: TestSuite(OS).run()\n ' self._set = s Parent.__init__(self, category=FiniteEnumeratedSets()) def _element_constructor_(self, s): '\n Construct an element of ``self`` from ``s``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions(4)\n sage: x = OS([[1,3],[2,4]]); x\n [{1, 3}, {2, 4}]\n sage: x.parent()\n Ordered set partitions of {1, 2, 3, 4}\n ' if isinstance(s, OrderedSetPartition): raise ValueError(('cannot convert %s into an element of %s' % (s, self))) return self.element_class(self, list(s)) Element = OrderedSetPartition def __contains__(self, x): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4])\n sage: all(sp in OS for sp in OS)\n True\n sage: [[1,2], [], [3,4]] in OS\n False\n sage: [Set([1,2]), Set([3,4])] in OS\n True\n sage: [set([1,2]), set([3,4])] in OS\n True\n ' if (not isinstance(x, (OrderedSetPartition, list, tuple))): return False if (sum(map(len, x)) != len(self._set)): return False u = set() for s in x: if ((not s) or (not isinstance(s, (set, frozenset, Set_generic)))): return False u = u.union(s) return (len(u) == len(self._set)) def from_finite_word(self, w, check=True): "\n Return the unique ordered set partition of `\\{1, 2, \\ldots, n\\}` corresponding\n to a word `w` of length `n`.\n\n .. SEEALSO::\n\n :meth:`Word.to_ordered_set_partition`\n\n EXAMPLES::\n\n sage: A = OrderedSetPartitions().from_finite_word('abcabcabd'); A\n [{1, 4, 7}, {2, 5, 8}, {3, 6}, {9}]\n sage: B = OrderedSetPartitions().from_finite_word([1,2,3,1,2,3,1,2,4])\n sage: A == B\n True\n\n TESTS::\n\n sage: A = OrderedSetPartitions().from_finite_word('abcabca')\n sage: A.parent()\n Ordered set partitions\n\n sage: A = OrderedSetPartitions(7).from_finite_word('abcabca')\n sage: A.parent()\n Ordered set partitions of {1, 2, 3, 4, 5, 6, 7}\n " if isinstance(w, (list, tuple, str, FiniteWord_class)): W = Words(infinite=False) if check: try: X = self._set if ((len(X) != len(w)) or (X != frozenset(range(1, (len(w) + 1))))): raise ValueError(f'result not in {self}') except AttributeError: pass return self.element_class(self, W(w).to_ordered_set_partition()) raise TypeError(f'`from_finite_word` expects an object of type list/tuple/str/Word representing a finite word, received {w}')
class OrderedSetPartitions_s(OrderedSetPartitions): '\n Class of ordered partitions of a set `S`.\n ' def _repr_(self): '\n TESTS::\n\n sage: OrderedSetPartitions([1,2,3,4])\n Ordered set partitions of {1, 2, 3, 4}\n ' return ('Ordered set partitions of %s' % Set(self._set)) def cardinality(self): '\n EXAMPLES::\n\n sage: OrderedSetPartitions(0).cardinality()\n 1\n sage: OrderedSetPartitions(1).cardinality()\n 1\n sage: OrderedSetPartitions(2).cardinality()\n 3\n sage: OrderedSetPartitions(3).cardinality()\n 13\n sage: OrderedSetPartitions([1,2,3]).cardinality()\n 13\n sage: OrderedSetPartitions(4).cardinality()\n 75\n sage: OrderedSetPartitions(5).cardinality()\n 541\n ' N = len(self._set) return sum(((factorial(k) * stirling_number2(N, k)) for k in range((N + 1)))) def __iter__(self): '\n EXAMPLES::\n\n sage: list(OrderedSetPartitions([1,2,3]))\n [[{1}, {2}, {3}],\n [{1}, {3}, {2}],\n [{2}, {1}, {3}],\n [{3}, {1}, {2}],\n [{2}, {3}, {1}],\n [{3}, {2}, {1}],\n [{1}, {2, 3}],\n [{2}, {1, 3}],\n [{3}, {1, 2}],\n [{1, 2}, {3}],\n [{1, 3}, {2}],\n [{2, 3}, {1}],\n [{1, 2, 3}]]\n\n TESTS:\n\n Test for :issue:`35654`::\n\n sage: OrderedSetPartitions(set(),[0,0,0]).list()\n [[{}, {}, {}]]\n ' for x in Compositions(len(self._set)): for z in OrderedSetPartitions(self._set, x): (yield self.element_class(self, z, check=False))
class OrderedSetPartitions_sn(OrderedSetPartitions): def __init__(self, s, n): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4], 2)\n sage: OS == loads(dumps(OS))\n True\n ' OrderedSetPartitions.__init__(self, s) self.n = n def __contains__(self, x): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4], 2)\n sage: all(sp in OS for sp in OS)\n True\n sage: OS.cardinality()\n 14\n sage: len([x for x in OrderedSetPartitions([1,2,3,4]) if x in OS])\n 14\n ' return (OrderedSetPartitions.__contains__(self, x) and (len(x) == self.n)) def __repr__(self): '\n TESTS::\n\n sage: OrderedSetPartitions([1,2,3,4], 2)\n Ordered set partitions of {1, 2, 3, 4} into 2 parts\n ' return ('Ordered set partitions of %s into %s parts' % (Set(self._set), self.n)) def cardinality(self): '\n Return the cardinality of ``self``.\n\n The number of ordered partitions of a set of size `n` into `k`\n parts is equal to `k! S(n,k)` where `S(n,k)` denotes the Stirling\n number of the second kind.\n\n EXAMPLES::\n\n sage: OrderedSetPartitions(4,2).cardinality()\n 14\n sage: OrderedSetPartitions(4,1).cardinality()\n 1\n ' return (factorial(self.n) * stirling_number2(len(self._set), self.n)) def __iter__(self): '\n EXAMPLES::\n\n sage: [ p for p in OrderedSetPartitions([1,2,3,4], 2) ]\n [[{1, 2, 3}, {4}],\n [{1, 2, 4}, {3}],\n [{1, 3, 4}, {2}],\n [{2, 3, 4}, {1}],\n [{1, 2}, {3, 4}],\n [{1, 3}, {2, 4}],\n [{1, 4}, {2, 3}],\n [{2, 3}, {1, 4}],\n [{2, 4}, {1, 3}],\n [{3, 4}, {1, 2}],\n [{1}, {2, 3, 4}],\n [{2}, {1, 3, 4}],\n [{3}, {1, 2, 4}],\n [{4}, {1, 2, 3}]]\n ' for x in Compositions(len(self._set), length=self.n): for z in OrderedSetPartitions_scomp(self._set, x): (yield self.element_class(self, z, check=False))
class OrderedSetPartitions_scomp(OrderedSetPartitions): def __init__(self, s, comp): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4], [2,1,1])\n sage: OS == loads(dumps(OS))\n True\n ' OrderedSetPartitions.__init__(self, s) self.c = Composition(comp) def __repr__(self): '\n TESTS::\n\n sage: OrderedSetPartitions([1,2,3,4], [2,1,1])\n Ordered set partitions of {1, 2, 3, 4} into parts of size [2, 1, 1]\n ' return ('Ordered set partitions of %s into parts of size %s' % (Set(self._set), self.c)) def __contains__(self, x): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4], [2,1,1])\n sage: all(sp in OS for sp in OS)\n True\n sage: OS.cardinality()\n 12\n sage: len([x for x in OrderedSetPartitions([1,2,3,4]) if x in OS])\n 12\n ' return (OrderedSetPartitions.__contains__(self, x) and ([len(z) for z in x] == self.c)) def cardinality(self): '\n Return the cardinality of ``self``.\n\n The number of ordered set partitions of a set of length `k` with\n composition shape `\\mu` is equal to\n\n .. MATH::\n\n \\frac{k!}{\\prod_{\\mu_i \\neq 0} \\mu_i!}.\n\n EXAMPLES::\n\n sage: OrderedSetPartitions(5,[2,3]).cardinality()\n 10\n sage: OrderedSetPartitions(0, []).cardinality()\n 1\n sage: OrderedSetPartitions(0, [0]).cardinality()\n 1\n sage: OrderedSetPartitions(0, [0,0]).cardinality()\n 1\n sage: OrderedSetPartitions(5, [2,0,3]).cardinality()\n 10\n ' return multinomial(self.c) def __iter__(self): '\n TESTS::\n\n sage: [ p for p in OrderedSetPartitions([1,2,3,4], [2,1,1]) ]\n [[{1, 2}, {3}, {4}],\n [{1, 2}, {4}, {3}],\n [{1, 3}, {2}, {4}],\n [{1, 4}, {2}, {3}],\n [{1, 3}, {4}, {2}],\n [{1, 4}, {3}, {2}],\n [{2, 3}, {1}, {4}],\n [{2, 4}, {1}, {3}],\n [{3, 4}, {1}, {2}],\n [{2, 3}, {4}, {1}],\n [{2, 4}, {3}, {1}],\n [{3, 4}, {2}, {1}]]\n\n sage: len(OrderedSetPartitions([1,2,3,4], [1,1,1,1]))\n 24\n\n sage: [ x for x in OrderedSetPartitions([1,4,7], [3]) ]\n [[{1, 4, 7}]]\n\n sage: [ x for x in OrderedSetPartitions([1,4,7], [1,2]) ]\n [[{1}, {4, 7}], [{4}, {1, 7}], [{7}, {1, 4}]]\n\n sage: [ p for p in OrderedSetPartitions([], []) ]\n [[]]\n\n sage: [ p for p in OrderedSetPartitions([1], [1]) ]\n [[{1}]]\n\n Let us check that it works for large size (:trac:`16646`)::\n\n sage: OrderedSetPartitions(42).first()\n [{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12},\n {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}, {23},\n {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31}, {32}, {33}, {34},\n {35}, {36}, {37}, {38}, {39}, {40}, {41}, {42}]\n\n EXAMPLES::\n\n sage: list(OrderedSetPartitions(range(5), [2,1,2]))\n [[{0, 1}, {2}, {3, 4}],\n [{0, 1}, {3}, {2, 4}],\n ...\n [{2, 4}, {3}, {0, 1}],\n [{3, 4}, {2}, {0, 1}]]\n ' part_sizes = self.c N = len(part_sizes) if (not N): (yield self.element_class(self, [], check=False)) return l = [] lset = list(self._set) for (i, j) in enumerate(part_sizes): l.extend(([i] * j)) pi = multiset_permutation_to_ordered_set_partition(l, N) converted = [frozenset((lset[i] for i in part)) for part in pi] (yield self.element_class(self, converted, check=False)) while multiset_permutation_next_lex(l): pi = multiset_permutation_to_ordered_set_partition(l, N) converted = [frozenset((lset[i] for i in part)) for part in pi] (yield self.element_class(self, converted, check=False))
def multiset_permutation_to_ordered_set_partition(l, m): '\n Convert a multiset permutation to an ordered set partition.\n\n INPUT:\n\n - ``l`` -- a multiset permutation\n - ``m`` -- number of parts\n\n EXAMPLES::\n\n sage: from sage.combinat.set_partition_ordered import multiset_permutation_to_ordered_set_partition\n sage: l = [0, 0, 1, 1, 2]\n sage: multiset_permutation_to_ordered_set_partition(l, 3)\n [[0, 1], [2, 3], [4]]\n ' p = [[] for _ in range(m)] for (i, j) in enumerate(l): p[j].append(i) return p
def multiset_permutation_next_lex(l): '\n Return the next multiset permutation after ``l``.\n\n EXAMPLES::\n\n sage: from sage.combinat.set_partition_ordered import multiset_permutation_next_lex\n sage: l = [0, 0, 1, 1, 2]\n sage: while multiset_permutation_next_lex(l):\n ....: print(l)\n [0, 0, 1, 2, 1]\n [0, 0, 2, 1, 1]\n [0, 1, 0, 1, 2]\n [0, 1, 0, 2, 1]\n [0, 1, 1, 0, 2]\n [0, 1, 1, 2, 0]\n ...\n [1, 1, 2, 0, 0]\n [1, 2, 0, 0, 1]\n [1, 2, 0, 1, 0]\n [1, 2, 1, 0, 0]\n [2, 0, 0, 1, 1]\n [2, 0, 1, 0, 1]\n [2, 0, 1, 1, 0]\n [2, 1, 0, 0, 1]\n [2, 1, 0, 1, 0]\n [2, 1, 1, 0, 0]\n\n TESTS:\n\n Test for :issue:`35654`::\n\n sage: multiset_permutation_next_lex([])\n 0\n ' i = (len(l) - 2) while ((i >= 0) and (l[i] >= l[(i + 1)])): i -= 1 if (i <= (- 1)): return 0 j = (len(l) - 1) while (l[j] <= l[i]): j -= 1 (l[i], l[j]) = (l[j], l[i]) l[(i + 1):] = l[:i:(- 1)] return 1
class OrderedSetPartitions_all(OrderedSetPartitions): '\n Ordered set partitions of `\\{1, \\ldots, n\\}` for all\n `n \\in \\ZZ_{\\geq 0}`.\n ' def __init__(self): '\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions()\n sage: TestSuite(OS).run() # long time\n ' Parent.__init__(self, category=InfiniteEnumeratedSets()) def subset(self, size=None, **kwargs): '\n Return the subset of ordered set partitions of a given\n size and additional keyword arguments.\n\n EXAMPLES::\n\n sage: P = OrderedSetPartitions()\n sage: P.subset(4)\n Ordered set partitions of {1, 2, 3, 4}\n ' if (size is None): return self return OrderedSetPartitions(size, **kwargs) def __iter__(self): '\n Iterate over ``self``.\n\n EXAMPLES::\n\n sage: it = iter(OrderedSetPartitions())\n sage: [next(it) for _ in range(10)]\n [[], [{1}], [{1}, {2}], [{2}, {1}], [{1, 2}],\n [{1}, {2}, {3}], [{1}, {3}, {2}], [{2}, {1}, {3}],\n [{3}, {1}, {2}], [{2}, {3}, {1}]]\n ' n = 0 while True: for X in OrderedSetPartitions(n): (yield self.element_class(self, list(X), check=False)) n += 1 def _element_constructor_(self, s): '\n Construct an element of ``self`` from ``s``.\n\n EXAMPLES::\n\n sage: OS = OrderedSetPartitions()\n sage: OS([[1,3],[2,4]])\n [{1, 3}, {2, 4}]\n ' if isinstance(s, OrderedSetPartition): gset = s.parent()._set if (gset == frozenset(range(1, (len(gset) + 1)))): return self.element_class(self, list(s)) raise ValueError(('cannot convert %s into an element of %s' % (s, self))) return self.element_class(self, list(s)) def __contains__(self, x): '\n TESTS::\n\n sage: OS = OrderedSetPartitions([1,2,3,4])\n sage: AOS = OrderedSetPartitions()\n sage: all(sp in AOS for sp in OS)\n True\n sage: AOS.__contains__([[1,3], [4], [5,2]])\n True\n sage: AOS.__contains__([Set([1,3]), Set([4]), Set([5,2])])\n True\n sage: [Set([1,4]), Set([3])] in AOS\n False\n sage: [Set([1,3]), Set([4,2]), Set([2,5])] in AOS\n False\n sage: [Set([1,2]), Set()] in AOS\n False\n ' if isinstance(x, OrderedSetPartition): if (x.parent() is self): return True gset = x.parent()._set return (gset == frozenset(range(1, (len(gset) + 1)))) if (not isinstance(x, (list, tuple))): return False if (not all(((s and isinstance(s, (set, frozenset, list, tuple, Set_generic))) for s in x))): return False if (not all(((isinstance(s, (set, frozenset, Set_generic)) or (len(s) == len(set(s)))) for s in x))): return False X = set((y for p in x for y in p)) return ((len(X) == sum((len(s) for s in x))) and (X == frozenset(range(1, (len(X) + 1))))) def _coerce_map_from_(self, X): "\n Return ``True`` if there is a coercion map from ``X``.\n\n EXAMPLES::\n\n sage: OSP = OrderedSetPartitions()\n sage: OSP._coerce_map_from_(OrderedSetPartitions(3))\n True\n sage: OSP._coerce_map_from_(OrderedSetPartitions(['a','b']))\n False\n " if (X is self): return True if isinstance(X, OrderedSetPartitions): return (X._set == frozenset(range(1, (len(X._set) + 1)))) return super()._coerce_map_from_(X) def _repr_(self): '\n TESTS::\n\n sage: OrderedSetPartitions()\n Ordered set partitions\n ' return 'Ordered set partitions' class Element(OrderedSetPartition): def _richcmp_(self, other, op): '\n TESTS::\n\n sage: OSP = OrderedSetPartitions()\n sage: el1 = OSP([[1,3], [4], [2]])\n sage: el2 = OSP([[3,1], [2], [4]])\n sage: el1 == el1, el2 == el2, el1 == el2 # indirect doctest\n (True, True, False)\n sage: el1 <= el2, el1 >= el2, el2 <= el1 # indirect doctest\n (False, True, True)\n ' return richcmp([sorted(s) for s in self], [sorted(s) for s in other], op)
class SplitNK(OrderedSetPartitions_scomp): def __setstate__(self, state): '\n For unpickling old ``SplitNK`` objects.\n\n TESTS::\n\n sage: loads(b"x\\x9ck`J.NLO\\xd5K\\xce\\xcfM\\xca\\xccK,\\xd1+.\\xc8\\xc9,"\n ....: b"\\x89\\xcf\\xcb\\xe6\\n\\x061\\xfc\\xbcA\\xccBF\\xcd\\xc6B\\xa6\\xda"\n ....: b"Bf\\x8dP\\xa6\\xf8\\xbcB\\x16\\x88\\x96\\xa2\\xcc\\xbc\\xf4b\\xbd\\xcc"\n ....: b"\\xbc\\x92\\xd4\\xf4\\xd4\\"\\xae\\xdc\\xc4\\xec\\xd4x\\x18\\xa7\\x905"\n ....: b"\\x94\\xd1\\xb45\\xa8\\x90\\r\\xa8>\\xbb\\x90=\\x03\\xc85\\x02r9J\\x93"\n ....: b"\\xf4\\x00\\xb4\\xc6%f")\n Ordered set partitions of {0, 1, 2, 3, 4} into parts of size [2, 3]\n ' self.__class__ = OrderedSetPartitions_scomp n = state['_n'] k = state['_k'] OrderedSetPartitions_scomp.__init__(self, range(state['_n']), (k, (n - k)))
class generic_character(SFA_generic): def _my_key(self, la): '\n A rank function for partitions.\n\n The leading term of a homogeneous expression will\n be the partition with the largest key value.\n\n This key value is `|\\lambda|^2 + \\lambda_0` and\n using the ``max`` function on a list of Partitions.\n\n Of course it is possible that this rank function\n is equal for some partitions, but the leading\n term should be any one of these partitions.\n\n INPUT:\n\n - ``la`` -- a partition\n\n OUTPUT:\n\n - an integer\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: ht._my_key(Partition([2,1,1]))\n 18\n sage: ht._my_key(Partition([2,2]))\n 18\n sage: ht._my_key(Partition([3,1]))\n 19\n sage: ht._my_key(Partition([1,1,1,1]))\n 17\n ' if la: return ((la.size() ** 2) + la[0]) else: return 0 def _other_to_self(self, sexpr): '\n Convert an expression the target basis to the character-basis.\n\n We use triangularity to determine the expansion\n by subtracting off the leading term. The target basis\n is specified by the method ``self._other``.\n\n INPUT:\n\n - ``sexpr`` -- an element of ``self._other`` basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: h = Sym.h()\n sage: ht._other_to_self(h[2] + h([]))\n ht[] + ht[1] + ht[2]\n sage: st = SymmetricFunctions(QQ).st()\n sage: s = Sym.s()\n sage: st._other_to_self(s[1] + s([]))\n 2*st[] + st[1]\n sage: 7 * st[[]] * st[[]]\n 7*st[]\n ' if (sexpr == 0): return self(0) if (list(sexpr.support()) == [[]]): return self._from_dict({self.one_basis(): sexpr.coefficient([])}, remove_zeros=False) out = self.zero() while sexpr: mup = max(sexpr.support(), key=self._my_key) out += (sexpr.coefficient(mup) * self(mup)) sexpr -= (sexpr.coefficient(mup) * self._self_to_other_on_basis(mup)) return out def _b_power_k(self, k): '\n An expression involving Moebius inversion in the powersum generators.\n\n For a positive value of ``k``, this expression is\n\n .. MATH::\n\n \\frac{1}{k} \\sum_{d|k} \\mu(d/k) p_d.\n\n INPUT:\n\n - ``k`` -- a positive integer\n\n OUTPUT:\n\n - an expression in the powersum basis of the symmetric functions\n\n EXAMPLES::\n\n sage: st = SymmetricFunctions(QQ).st()\n sage: st._b_power_k(1)\n p[1]\n sage: st._b_power_k(2)\n -1/2*p[1] + 1/2*p[2]\n sage: st._b_power_k(6)\n 1/6*p[1] - 1/6*p[2] - 1/6*p[3] + 1/6*p[6]\n\n ' if (k == 1): return self._p([1]) if (k > 0): return ((~ k) * self._p.linear_combination(((self._p([d]), moebius((k // d))) for d in divisors(k))))
class induced_trivial_character_basis(generic_character): '\n The induced trivial symmetric group character basis of\n the symmetric functions.\n\n This is a basis of the symmetric functions that has the\n property that ``self(la).character_to_frobenius_image(n)``\n is equal to ``h([n-sum(la)]+la)``.\n\n It has the property that the (outer) structure\n constants are the analogue of the stable Kronecker\n coefficients on the complete basis.\n\n This basis is introduced in [OZ2015]_.\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.s()\n sage: h = Sym.h()\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: st = SymmetricFunctions(QQ).st()\n sage: ht(s[2,1])\n ht[1, 1] + ht[2, 1] - ht[3]\n sage: s(ht[2,1])\n s[1] - 2*s[1, 1] - 2*s[2] + s[2, 1] + s[3]\n sage: ht(h[2,1])\n ht[1] + 2*ht[1, 1] + ht[2, 1]\n sage: h(ht[2,1])\n h[1] - 2*h[1, 1] + h[2, 1]\n sage: st(ht[2,1])\n st[] + 2*st[1] + st[1, 1] + 2*st[2] + st[2, 1] + st[3]\n sage: ht(st[2,1])\n ht[1] - ht[1, 1] + ht[2, 1] - ht[3]\n sage: ht[2]*ht[1,1]\n ht[1, 1] + 2*ht[1, 1, 1] + ht[2, 1, 1]\n sage: h[4,2].kronecker_product(h[4,1,1])\n h[2, 2, 1, 1] + 2*h[3, 1, 1, 1] + h[4, 1, 1]\n sage: s(st[2,1])\n 3*s[1] - 2*s[1, 1] - 2*s[2] + s[2, 1]\n sage: st(s[2,1])\n st[] + 3*st[1] + 2*st[1, 1] + 2*st[2] + st[2, 1]\n sage: st[2]*st[1]\n st[1] + st[1, 1] + st[2] + st[2, 1] + st[3]\n sage: s[4,2].kronecker_product(s[5,1])\n s[3, 2, 1] + s[3, 3] + s[4, 1, 1] + s[4, 2] + s[5, 1]\n\n TESTS::\n\n sage: TestSuite(ht).run()\n ' def __init__(self, Sym, pfix): '\n Initialize the basis and register coercions.\n\n The coercions are set up between the ``other_basis``.\n\n INPUT:\n\n - ``Sym`` -- an instance of the symmetric function algebra\n - ``pfix`` -- a prefix to use for the basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: ht = SymmetricFunctions(QQ).ht(); ht\n Symmetric Functions over Rational Field in the induced trivial\n symmetric group character basis\n ' SFA_generic.__init__(self, Sym, basis_name='induced trivial symmetric group character', prefix=pfix, graded=False) self._other = Sym.complete() self._p = Sym.powersum() self.module_morphism(self._self_to_power_on_basis, codomain=Sym.powersum()).register_as_coercion() self.register_coercion(SetMorphism(Hom(self._other, self), self._other_to_self)) def _b_bar_power_k_r(self, k, r): '\n An expression involving Moebius inversion in the powersum generators.\n\n For a positive value of ``k``, this expression is\n\n .. MATH::\n\n \\sum_{j=0}^r (-1)^{r-j}k^j\\binom{r,j}\n \\left( \\frac{1}{k} \\sum_{d|k} \\mu(d/k) p_d \\right)_k.\n\n INPUT:\n\n - ``k``, ``r`` -- positive integers\n\n OUTPUT:\n\n - an expression in the powersum basis of the symmetric functions\n\n EXAMPLES::\n\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: ht._b_bar_power_k_r(1,1)\n p[1]\n sage: ht._b_bar_power_k_r(2,2)\n 2*p[1] + p[1, 1] - 2*p[2] - 2*p[2, 1] + p[2, 2]\n sage: ht._b_bar_power_k_r(3,2)\n 3*p[1] + p[1, 1] - 3*p[3] - 2*p[3, 1] + p[3, 3]\n\n ' p = self._p return ((k ** r) * p.prod(((self._b_power_k(k) - j) for j in range(r)))) def _b_bar_power_gamma(self, gamma): '\n An expression involving Moebius inversion in the powersum generators.\n\n For a partition `\\gamma = (1^{m_1}, 2^{m_2}, \\ldots, r^{m_r})`,\n this expression is\n\n .. MATH::\n\n {\\mathbf p}_{\\ga} = \\sum_{k \\geq 1} {\\mathbf p}_{k^{m_k}},\n\n where\n\n .. MATH::\n\n {\\mathbf p}_{k^r} = \\sum_{j=0}^r (-1)^{r-j}k^j\\binom{r,j}\n \\left( \\frac{1}{k} \\sum_{d|k} \\mu(d/k) p_d \\right)_k.\n\n INPUT:\n\n - ``gamma`` -- a partition\n\n OUTPUT:\n\n - an expression in the powersum basis of the symmetric functions\n\n EXAMPLES::\n\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: ht._b_bar_power_gamma(Partition([2,2,1]))\n 2*p[1, 1] + p[1, 1, 1] - 2*p[2, 1] - 2*p[2, 1, 1] + p[2, 2, 1]\n sage: ht._b_bar_power_gamma(Partition([1,1,1]))\n 2*p[1] - 3*p[1, 1] + p[1, 1, 1]\n sage: ht._b_bar_power_gamma(Partition([3,3,1]))\n 3*p[1, 1] + p[1, 1, 1] - 3*p[3, 1] - 2*p[3, 1, 1] + p[3, 3, 1]\n\n ' return self._p.prod((self._b_bar_power_k_r(Integer(k), Integer(r)) for (k, r) in gamma.to_exp_dict().items())) def _self_to_power_on_basis(self, lam): '\n An expansion of the induced trivial character in the powersum basis.\n\n The formula for the induced trivial character basis indexed by the\n partition ``lam`` is given by the formula\n\n .. MATH::\n\n \\sum_{\\gamma} \\left\\langle h_\\lambda, p_\\gamma \\right\\rangle\n \\frac{{\\overline {\\mathbf p}}_\\gamma}{z_\\gamma},\n\n where `{\\overline {\\mathbf p}}_\\gamma` is the\n power sum expression calculated in the method\n :meth:`_b_bar_power_gamma`.\n\n INPUT:\n\n - ``lam`` -- a partition\n\n OUTPUT:\n\n - an expression in the power sum basis\n\n EXAMPLES::\n\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: ht._self_to_power_on_basis([2,1])\n p[1] - 2*p[1, 1] + 1/2*p[1, 1, 1] + 1/2*p[2, 1]\n sage: ht._self_to_power_on_basis([1,1,1])\n 2*p[1] - 3*p[1, 1] + p[1, 1, 1]\n\n ' return self._p.sum(((c * self._b_bar_power_gamma(ga)) for (ga, c) in self._p(self._other(lam)))) @cached_method def _self_to_other_on_basis(self, lam): '\n An expansion of the induced trivial character basis in complete basis.\n\n Compute the complete expansion by first computing it in the\n powersum basis and the coercing to the complete basis.\n\n INPUT:\n\n - ``lam`` -- a partition\n\n OUTPUT:\n\n - an expression in the complete (other) basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: ht._self_to_other_on_basis(Partition([2,1]))\n h[1] - 2*h[1, 1] + h[2, 1]\n\n TESTS::\n\n sage: h = SymmetricFunctions(QQ).h()\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: st = SymmetricFunctions(QQ).st()\n sage: all(ht(h(ht[la])) == ht[la] for i in range(5) for la in Partitions(i))\n True\n sage: all(h(ht(h[la])) == h[la] for i in range(5) for la in Partitions(i))\n True\n sage: all(st(h(st[la])) == st[la] for i in range(5) for la in Partitions(i))\n True\n sage: all(h(st(h[la])) == h[la] for i in range(5) for la in Partitions(i))\n True\n ' return self._other(self._self_to_power_on_basis(lam))
class irreducible_character_basis(generic_character): '\n The irreducible symmetric group character basis of\n the symmetric functions.\n\n This is a basis of the symmetric functions that has the\n property that ``self(la).character_to_frobenius_image(n)``\n is equal to ``s([n-sum(la)]+la)``.\n\n It should also have the property that the (outer) structure\n constants are the analogue of the stable Kronecker\n coefficients on the Schur basis.\n\n This basis is introduced in [OZ2015]_.\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.s()\n sage: h = Sym.h()\n sage: ht = SymmetricFunctions(QQ).ht()\n sage: st = SymmetricFunctions(QQ).st()\n sage: st(ht[2,1])\n st[] + 2*st[1] + st[1, 1] + 2*st[2] + st[2, 1] + st[3]\n sage: ht(st[2,1])\n ht[1] - ht[1, 1] + ht[2, 1] - ht[3]\n sage: s(st[2,1])\n 3*s[1] - 2*s[1, 1] - 2*s[2] + s[2, 1]\n sage: st(s[2,1])\n st[] + 3*st[1] + 2*st[1, 1] + 2*st[2] + st[2, 1]\n sage: st[2]*st[1]\n st[1] + st[1, 1] + st[2] + st[2, 1] + st[3]\n sage: s[4,2].kronecker_product(s[5,1])\n s[3, 2, 1] + s[3, 3] + s[4, 1, 1] + s[4, 2] + s[5, 1]\n sage: st[1,1,1].counit()\n -1\n sage: all(sum(c*st(la)*st(mu).antipode() for\n ....: ((la,mu),c) in st(ga).coproduct())==st(st(ga).counit())\n ....: for ga in Partitions(3))\n True\n\n TESTS::\n\n sage: TestSuite(st).run()\n ' def __init__(self, Sym, pfix): '\n Initialize the basis and register coercions.\n\n The coercions are set up between the ``other_basis``\n\n INPUT:\n\n - ``Sym`` -- an instance of the symmetric function algebra\n - ``pfix`` -- a prefix to use for the basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: ht = SymmetricFunctions(QQ).ht(); ht\n Symmetric Functions over Rational Field in the induced trivial\n symmetric group character basis\n sage: st = SymmetricFunctions(QQ).st(); st\n Symmetric Functions over Rational Field in the irreducible\n symmetric group character basis\n ' SFA_generic.__init__(self, Sym, basis_name='irreducible symmetric group character', prefix=pfix, graded=False) self._other = Sym.Schur() self._p = Sym.powersum() self.module_morphism(self._self_to_power_on_basis, codomain=Sym.powersum()).register_as_coercion() self.register_coercion(SetMorphism(Hom(self._other, self), self._other_to_self)) def _b_power_k_r(self, k, r): '\n An expression involving Moebius inversion in the powersum generators.\n\n For a positive value of ``k``, this expression is\n\n .. MATH::\n\n \\sum_{j=0}^r (-1)^{r-j}k^j\\binom{r,j} \\left(\n \\frac{1}{k} \\sum_{d|k} \\mu(d/k) p_d \\right)_k.\n\n INPUT:\n\n - ``k``, ``r`` -- positive integers\n\n OUTPUT:\n\n - an expression in the powersum basis of the symmetric functions\n\n EXAMPLES::\n\n sage: st = SymmetricFunctions(QQ).st()\n sage: st._b_power_k_r(1,1)\n -p[] + p[1]\n sage: st._b_power_k_r(2,2)\n p[] + 4*p[1] + p[1, 1] - 4*p[2] - 2*p[2, 1] + p[2, 2]\n sage: st._b_power_k_r(3,2)\n p[] + 5*p[1] + p[1, 1] - 5*p[3] - 2*p[3, 1] + p[3, 3]\n\n ' p = self._p return p.sum(((((((- 1) ** (r - j)) * (k ** j)) * binomial(r, j)) * p.prod(((self._b_power_k(k) - (i * p.one())) for i in range(j)))) for j in range((r + 1)))) def _b_power_gamma(self, gamma): '\n An expression involving Moebius inversion in the powersum generators.\n\n For a partition `\\gamma = (1^{m_1}, 2^{m_2}, \\ldots, r^{m_r})`,\n this expression is\n\n .. MATH::\n\n {\\mathbf p}_{\\ga} = \\sum_{k \\geq 1} {\\mathbf p}_{k^{m_k}},\n\n where\n\n .. MATH::\n\n {\\mathbf p}_{k^r} = \\sum_{j=0}^r (-1)^{r-j}k^j\\binom{r,j}\n \\left( \\frac{1}{k} \\sum_{d|k} \\mu(d/k) p_d \\right)_k.\n\n INPUT:\n\n - ``gamma`` -- a partition\n\n OUTPUT:\n\n - an expression in the powersum basis of the symmetric functions\n\n EXAMPLES::\n\n sage: st = SymmetricFunctions(QQ).st()\n sage: st._b_power_gamma(Partition([2,2]))\n p[] + 4*p[1] + p[1, 1] - 4*p[2] - 2*p[2, 1] + p[2, 2]\n sage: st._b_power_gamma(Partition([1,1,1]))\n -p[] + 8*p[1] - 6*p[1, 1] + p[1, 1, 1]\n sage: st._b_power_gamma(Partition([3,1]))\n p[] - p[1, 1] - p[3] + p[3, 1]\n\n ' return self._p.prod((self._b_power_k_r(Integer(k), Integer(r)) for (k, r) in gamma.to_exp_dict().items())) def _self_to_power_on_basis(self, lam): '\n An expansion of the irreducible character in the powersum basis.\n\n The formula for the irreducible character basis indexed by the\n partition ``lam`` is given by the formula\n\n .. MATH::\n\n \\sum_{\\gamma} \\chi^{\\lambda}(\\gamma)\n \\frac{{\\mathbf p}_\\gamma}{z_\\gamma},\n\n where `\\chi^{\\lambda}(\\gamma)` is the irreducible character\n indexed by the partition `\\lambda` and evaluated at an element\n of cycle structure `\\gamma` and `{\\mathbf p}_\\gamma` is the\n power sum expression calculated in the method\n :meth:`_b_power_gamma`.\n\n INPUT:\n\n - ``lam`` -- a partition\n\n OUTPUT:\n\n - an expression in the power sum basis\n\n EXAMPLES::\n\n sage: st = SymmetricFunctions(QQ).st()\n sage: st._self_to_power_on_basis([2,1])\n 3*p[1] - 2*p[1, 1] + 1/3*p[1, 1, 1] - 1/3*p[3]\n sage: st._self_to_power_on_basis([1,1])\n p[] - p[1] + 1/2*p[1, 1] - 1/2*p[2]\n\n ' return self._p.sum(((c * self._b_power_gamma(ga)) for (ga, c) in self._p(self._other(lam)))) @cached_method def _self_to_other_on_basis(self, lam): '\n An expansion of the irreducible character basis in the Schur basis.\n\n Compute the Schur expansion by first computing it in the\n powersum basis and the coercing to the Schur basis.\n\n INPUT:\n\n - ``lam`` -- a partition\n\n OUTPUT:\n\n - an expression in the Schur basis\n\n EXAMPLES::\n\n sage: st = SymmetricFunctions(QQ).st()\n sage: st._self_to_other_on_basis(Partition([1,1]))\n s[] - s[1] + s[1, 1]\n sage: st._self_to_other_on_basis(Partition([2,1]))\n 3*s[1] - 2*s[1, 1] - 2*s[2] + s[2, 1]\n ' return self._other(self._self_to_power_on_basis(lam))
def init(): "\n Set up the conversion functions between the classical bases.\n\n EXAMPLES::\n\n sage: from sage.combinat.sf.classical import init\n sage: sage.combinat.sf.classical.conversion_functions = {}\n sage: init()\n sage: sage.combinat.sf.classical.conversion_functions[('Schur', 'powersum')]\n <built-in function t_SCHUR_POWSYM_symmetrica>\n\n The following checks if the bug described in :trac:`15312` is fixed. ::\n\n sage: change = sage.combinat.sf.classical.conversion_functions[('powersum', 'Schur')]\n sage: hideme = change({Partition([1]*47):ZZ(1)}) # long time\n sage: change({Partition([2,2]):QQ(1)})\n s[1, 1, 1, 1] - s[2, 1, 1] + 2*s[2, 2] - s[3, 1] + s[4]\n " import sage.libs.symmetrica.all as symmetrica for other_basis in translate: for basis in translate: try: conversion_functions[(other_basis, basis)] = getattr(symmetrica, 't_{}_{}'.format(translate[other_basis], translate[basis])) except AttributeError: pass
class SymmetricFunctionAlgebra_classical(sfa.SymmetricFunctionAlgebra_generic): "\n The class of classical symmetric functions.\n\n .. TODO:: delete this class once all coercions will be handled by Sage's coercion model\n\n TESTS::\n\n sage: TestSuite(SymmetricFunctions(QQ).s()).run()\n sage: TestSuite(SymmetricFunctions(QQ).h()).run()\n sage: TestSuite(SymmetricFunctions(QQ).m()).run()\n sage: TestSuite(SymmetricFunctions(QQ).e()).run()\n sage: TestSuite(SymmetricFunctions(QQ).p()).run()\n " def _element_constructor_(self, x): "\n Convert ``x`` into ``self``, if coercion failed.\n\n INPUT:\n\n - ``x`` -- an element of the symmetric functions\n\n EXAMPLES::\n\n sage: s = SymmetricFunctions(QQ).s()\n sage: s(2)\n 2*s[]\n sage: s([2,1]) # indirect doctest\n s[2, 1]\n\n sage: McdJ = SymmetricFunctions(QQ['q','t'].fraction_field()).macdonald().J()\n sage: s = SymmetricFunctions(McdJ.base_ring()).s()\n sage: s._element_constructor_(McdJ(s[2,1]))\n s[2, 1]\n\n TESTS:\n\n Check that non-Schur bases raise an error when given skew partitions\n (:trac:`19218`)::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: e([[2,1],[1]])\n Traceback (most recent call last):\n ...\n TypeError: do not know how to make x (= [[2, 1], [1]]) an element of self\n\n Check that :trac:`34576` is fixed::\n\n sage: s = SymmetricFunctions(ZZ).s()\n sage: f = s(0/2); f\n 0\n sage: f == 0\n True\n sage: f._monomial_coefficients\n {}\n\n sage: s2 = SymmetricFunctions(GF(2)).s()\n sage: f = s2(2*s[2,1]); f\n 0\n sage: f == 0\n True\n sage: f._monomial_coefficients\n {}\n " R = self.base_ring() eclass = self.element_class if isinstance(x, int): x = Integer(x) if (x in _Partitions): return eclass(self, {_Partitions(x): R.one()}) elif (sfa.is_SymmetricFunction(x) and hasattr(x, 'dual')): return self(x.dual()) elif isinstance(x, self.Element): P = x.parent() if (P is self): return x else: return eclass(self, {la: rc for (la, c) in x._monomial_coefficients.items() if (rc := R(c))}) elif isinstance(x, SymmetricFunctionAlgebra_classical.Element): P = x.parent() m = x.monomial_coefficients() try: t = conversion_functions[(P.basis_name(), self.basis_name())] except AttributeError: raise TypeError(('do not know how to convert from %s to %s' % (P.basis_name(), self.basis_name()))) if ((R == QQ) and (P.base_ring() == QQ)): if m: return self._from_dict(t(m)._monomial_coefficients, coerce=True) return self.zero() else: f = (lambda part: self._from_dict(t({part: ZZ.one()})._monomial_coefficients)) return self._apply_module_endomorphism(x, f) elif isinstance(x, hall_littlewood.HallLittlewood_generic.Element): if isinstance(x, (hall_littlewood.HallLittlewood_qp.Element, hall_littlewood.HallLittlewood_p.Element)): P = x.parent() sx = P._s._from_cache(x, P._s_cache, P._self_to_s_cache, t=P.t) return self(sx) elif isinstance(x, hall_littlewood.HallLittlewood_q.Element): return self(x.parent()._P(x)) elif isinstance(x, llt.LLT_generic.Element): P = x.parent() Rx = P.base_ring() zero = R.zero() if (not R.has_coerce_map_from(Rx)): raise TypeError(("no coerce map from x's parent's base ring (= %s) to self's base ring (= %s)" % (Rx, R))) z_elt = {} for (m, c) in x._monomial_coefficients.items(): n = sum(m) P._m_cache(n) for part in P._self_to_m_cache[n][m]: z_elt[part] = (z_elt.get(part, zero) + R((c * P._self_to_m_cache[n][m][part].subs(t=P.t)))) m = P._sym.monomial() return self(m._from_dict(z_elt)) elif isinstance(x, macdonald.MacdonaldPolynomials_generic.Element): if isinstance(x, (macdonald.MacdonaldPolynomials_j.Element, macdonald.MacdonaldPolynomials_s.Element)): P = x.parent() sx = P._s._from_cache(x, P._s_cache, P._self_to_s_cache, q=P.q, t=P.t) return self(sx) elif isinstance(x, (macdonald.MacdonaldPolynomials_q.Element, macdonald.MacdonaldPolynomials_p.Element)): J = x.parent()._J jx = J(x) sx = J._s._from_cache(jx, J._s_cache, J._self_to_s_cache, q=J.q, t=J.t) return self(sx) elif isinstance(x, (macdonald.MacdonaldPolynomials_h.Element, macdonald.MacdonaldPolynomials_ht.Element)): P = x.parent() sx = P._self_to_s(x) return self(sx) else: raise TypeError elif isinstance(x, jack.JackPolynomials_generic.Element): if isinstance(x, jack.JackPolynomials_p.Element): P = x.parent() mx = P._m._from_cache(x, P._m_cache, P._self_to_m_cache, t=P.t) return self(mx) if isinstance(x, (jack.JackPolynomials_j.Element, jack.JackPolynomials_q.Element)): return self(x.parent()._P(x)) else: raise TypeError elif isinstance(x, orthotriang.SymmetricFunctionAlgebra_orthotriang.Element): P = x.parent() if (self is P._sf_base): return P._sf_base._from_cache(x, P._base_cache, P._self_to_base_cache) else: return self(P._sf_base(x)) else: try: c = R(x) except (TypeError, ValueError): raise TypeError('do not know how to make x (= {}) an element of self'.format(x)) else: if (not c): return self.zero() return eclass(self, {_Partitions([]): c}) class Element(sfa.SymmetricFunctionAlgebra_generic.Element): '\n A symmetric function.\n ' pass
class SymmetricFunctionAlgebra_dual(classical.SymmetricFunctionAlgebra_classical): def __init__(self, dual_basis, scalar, scalar_name='', basis_name=None, prefix=None): '\n Generic dual basis of a basis of symmetric functions.\n\n INPUT:\n\n - ``dual_basis`` -- a basis of the ring of symmetric functions\n\n - ``scalar`` -- A function `z` on partitions which determines the\n scalar product on the power sum basis by\n `\\langle p_{\\mu}, p_{\\mu} \\rangle = z(\\mu)`. (Independently on the\n function chosen, the power sum basis will always be orthogonal; the\n function ``scalar`` only determines the norms of the basis elements.)\n This defaults to the function ``zee`` defined in\n ``sage.combinat.sf.sfa``, that is, the function is defined by:\n\n .. MATH::\n\n \\lambda \\mapsto \\prod_{i = 1}^\\infty m_i(\\lambda)!\n i^{m_i(\\lambda)}`,\n\n where `m_i(\\lambda)` means the number of times `i` appears in\n `\\lambda`. This default function gives the standard Hall scalar\n product on the ring of symmetric functions.\n\n - ``scalar_name`` -- (default: the empty string) a string giving a\n description of the scalar product specified by the parameter\n ``scalar``\n\n - ``basis_name`` -- (optional) a string to serve as name for the basis\n to be generated (such as "forgotten" in "the forgotten basis"); don\'t\n set it to any of the already existing basis names (such as\n ``homogeneous``, ``monomial``, ``forgotten``, etc.).\n\n - ``prefix`` -- (default: ``\'d\'`` and the prefix for ``dual_basis``)\n a string to use as the symbol for the basis\n\n OUTPUT:\n\n The basis of the ring of symmetric functions dual to the basis\n ``dual_basis`` with respect to the scalar product determined\n by ``scalar``.\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: f = e.dual_basis(prefix = "m", basis_name="Forgotten symmetric functions"); f\n Symmetric Functions over Rational Field in the Forgotten symmetric functions basis\n sage: TestSuite(f).run(elements = [f[1,1]+2*f[2], f[1]+3*f[1,1]])\n sage: TestSuite(f).run() # long time (11s on sage.math, 2011)\n\n This class defines canonical coercions between ``self`` and\n ``self^*``, as follow:\n\n Lookup for the canonical isomorphism from ``self`` to `P`\n (=powersum), and build the adjoint isomorphism from `P^*` to\n ``self^*``. Since `P` is self-adjoint for this scalar product,\n derive an isomorphism from `P` to ``self^*``, and by composition\n with the above get an isomorphism from ``self`` to ``self^*`` (and\n similarly for the isomorphism ``self^*`` to ``self``).\n\n This should be striped down to just (auto?) defining canonical\n isomorphism by adjunction (as in MuPAD-Combinat), and let\n the coercion handle the rest.\n\n Inversions may not be possible if the base ring is not a field::\n\n sage: m = SymmetricFunctions(ZZ).m()\n sage: h = m.dual_basis(lambda x: 1)\n sage: h[2,1]\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n\n By transitivity, this defines indirect coercions to and from all other bases::\n\n sage: s = SymmetricFunctions(QQ[\'t\'].fraction_field()).s()\n sage: t = QQ[\'t\'].fraction_field().gen()\n sage: zee_hl = lambda x: x.centralizer_size(t=t)\n sage: S = s.dual_basis(zee_hl)\n sage: S(s([2,1]))\n (-t/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[1, 1, 1] + ((-t^2-1)/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[2, 1] + (-t/(t^5-2*t^4+t^3-t^2+2*t-1))*d_s[3]\n\n TESTS:\n\n Regression test for :trac:`12489`. This issue improving\n equality test revealed that the conversion back from the dual\n basis did not strip cancelled terms from the dictionary::\n\n sage: y = e[1, 1, 1, 1] - 2*e[2, 1, 1] + e[2, 2]\n sage: sorted(f.element_class(f, dual = y))\n [([1, 1, 1, 1], 6), ([2, 1, 1], 2), ([2, 2], 1)]\n\n ' self._dual_basis = dual_basis self._scalar = scalar self._scalar_name = scalar_name self._to_self_cache = {} self._from_self_cache = {} self._transition_matrices = {} self._inverse_transition_matrices = {} scalar_target = scalar(sage.combinat.partition.Partition([1])).parent() scalar_target = (scalar_target.one() * dual_basis.base_ring().one()).parent() self._sym = sage.combinat.sf.sf.SymmetricFunctions(scalar_target) self._p = self._sym.power() if (prefix is None): prefix = ('d_' + dual_basis.prefix()) classical.SymmetricFunctionAlgebra_classical.__init__(self, self._sym, basis_name=basis_name, prefix=prefix) category = sage.categories.all.ModulesWithBasis(self.base_ring()) self.register_coercion(SetMorphism(Hom(self._dual_basis, self, category), self._dual_to_self)) self._dual_basis.register_coercion(SetMorphism(Hom(self, self._dual_basis, category), self._self_to_dual)) def _dual_to_self(self, x): '\n Coerce an element of the dual of ``self`` canonically into ``self``.\n\n INPUT:\n\n - ``x`` -- an element in the dual basis of ``self``\n\n OUTPUT:\n\n - returns ``x`` expressed in the basis ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: h._dual_to_self(m([2,1]) + 3*m[1,1,1])\n d_m[1, 1, 1] - d_m[2, 1]\n sage: hh = m.realization_of().h()\n sage: h._dual_to_self(m(hh([2,2,2])))\n d_m[2, 2, 2]\n\n :: Note that the result is not correct if ``x`` is not an element of the\n dual basis of ``self``\n\n sage: h._dual_to_self(m([2,1]))\n -2*d_m[1, 1, 1] + 5*d_m[2, 1] - 3*d_m[3]\n sage: h._dual_to_self(hh([2,1]))\n -2*d_m[1, 1, 1] + 5*d_m[2, 1] - 3*d_m[3]\n\n This is for internal use only. Please use instead::\n\n sage: h(m([2,1]) + 3*m[1,1,1])\n d_m[1, 1, 1] - d_m[2, 1]\n ' return self._element_class(self, dual=x) def _self_to_dual(self, x): '\n Coerce an element of ``self`` canonically into the dual.\n\n INPUT:\n\n - ``x`` -- an element of ``self``\n\n OUTPUT:\n\n - returns ``x`` expressed in the dual basis\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: h._self_to_dual(h([2,1]) + 3*h[1,1,1])\n 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3]\n\n This is for internal use only. Please use instead::\n\n sage: m(h([2,1]) + 3*h[1,1,1])\n 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3]\n\n or::\n\n sage: (h([2,1]) + 3*h[1,1,1]).dual()\n 21*m[1, 1, 1] + 11*m[2, 1] + 4*m[3]\n ' return x.dual() def _dual_basis_default(self): "\n Returns the default value for ``self.dual_basis()``\n\n This returns the basis ``self`` has been built from by\n duality.\n\n .. WARNING::\n\n This is not necessarily the dual basis for the standard\n (Hall) scalar product!\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: h.dual_basis()\n Symmetric Functions over Rational Field in the monomial basis\n sage: m2 = h.dual_basis(zee, prefix='m2')\n sage: m([2])^2\n 2*m[2, 2] + m[4]\n sage: m2([2])^2\n 2*m2[2, 2] + m2[4]\n\n TESTS::\n\n sage: h.dual_basis() is h._dual_basis_default()\n True\n " return self._dual_basis def _repr_(self): "\n Representation of ``self``.\n\n OUTPUT:\n\n - a string description of ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee); h #indirect doctests\n Dual basis to Symmetric Functions over Rational Field in the monomial basis\n sage: h = m.dual_basis(scalar=zee, scalar_name='Hall scalar product'); h #indirect doctest\n Dual basis to Symmetric Functions over Rational Field in the monomial basis with respect to the Hall scalar product\n " if hasattr(self, '_basis'): return super()._repr_() if self._scalar_name: return ((('Dual basis to %s' % self._dual_basis) + ' with respect to the ') + self._scalar_name) else: return ('Dual basis to %s' % self._dual_basis) def _precompute(self, n): "\n Compute the transition matrices between ``self`` and its dual basis for\n the homogeneous component of size `n`. The result is not returned,\n but stored in the cache.\n\n INPUT:\n\n - ``n`` -- nonnegative integer\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ['t']).elementary()\n sage: f = e.dual_basis()\n sage: f._precompute(0)\n sage: f._precompute(1)\n sage: f._precompute(2)\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(f._to_self_cache) # note: this may depend on possible previous computations!\n [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([1, 1], 2), ([2], 1)]), ([2], [([1, 1], 1), ([2], 1)])]\n sage: l(f._from_self_cache)\n [([], [([], 1)]), ([1], [([1], 1)]), ([1, 1], [([1, 1], 1), ([2], -1)]), ([2], [([1, 1], -1), ([2], 2)])]\n sage: f._transition_matrices[2]\n [1 1]\n [1 2]\n sage: f._inverse_transition_matrices[2]\n [ 2 -1]\n [-1 1]\n " base_ring = self.base_ring() zero = base_ring.zero() if ((n == 0) or (n == 1)): part = sage.combinat.partition.Partition(([1] * n)) self._to_self_cache[part] = {part: base_ring.one()} self._from_self_cache[part] = {part: base_ring.one()} self._transition_matrices[n] = matrix(base_ring, [[1]]) self._inverse_transition_matrices[n] = matrix(base_ring, [[1]]) return partitions_n = sage.combinat.partition.Partitions_n(n).list() from sage.rings.rational_field import RationalField if ((not base_ring.has_coerce_map_from(RationalField())) and (self._scalar == sage.combinat.sf.sfa.zee)): schur = self._sym.schur() d = {} for part in partitions_n: d[part] = schur(self._dual_basis(part))._monomial_coefficients transition_matrix_n = matrix(base_ring, len(partitions_n), len(partitions_n)) i = 0 for s_part in partitions_n: s_mcs = {} j = 0 for p_part in partitions_n: sp = zero for ds_part in d[s_part]: if (ds_part in d[p_part]): sp += (d[s_part][ds_part] * d[p_part][ds_part]) if (sp != zero): s_mcs[p_part] = sp transition_matrix_n[(i, j)] = sp j += 1 self._to_self_cache[s_part] = s_mcs i += 1 else: d = {} for part in partitions_n: d[part] = self._p(self._dual_basis(part))._monomial_coefficients transition_matrix_n = matrix(base_ring, len(partitions_n), len(partitions_n)) i = 0 for s_part in partitions_n: s_mcs = {} j = 0 for p_part in partitions_n: sp = zero for ds_part in d[s_part]: if (ds_part in d[p_part]): sp += ((d[s_part][ds_part] * d[p_part][ds_part]) * self._scalar(ds_part)) if (sp != zero): s_mcs[p_part] = sp transition_matrix_n[(i, j)] = sp j += 1 self._to_self_cache[s_part] = s_mcs i += 1 self._transition_matrices[n] = transition_matrix_n inverse_transition = (~ transition_matrix_n) for i in range(len(partitions_n)): d_mcs = {} for j in range(len(partitions_n)): if (inverse_transition[(i, j)] != zero): d_mcs[partitions_n[j]] = inverse_transition[(i, j)] self._from_self_cache[partitions_n[i]] = d_mcs self._inverse_transition_matrices[n] = inverse_transition def transition_matrix(self, basis, n): '\n Returns the transition matrix between the `n^{th}` homogeneous components\n of ``self`` and ``basis``.\n\n INPUT:\n\n - ``basis`` -- a target basis of the ring of symmetric functions\n - ``n`` -- nonnegative integer\n\n OUTPUT:\n\n - A transition matrix from ``self`` to ``basis`` for the elements\n of degree ``n``. The indexing order of the rows and\n columns is the order of ``Partitions(n)``.\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.schur()\n sage: e = Sym.elementary()\n sage: f = e.dual_basis()\n sage: f.transition_matrix(s, 5)\n [ 1 -1 0 1 0 -1 1]\n [-2 1 1 -1 -1 1 0]\n [-2 2 -1 -1 1 0 0]\n [ 3 -1 -1 1 0 0 0]\n [ 3 -2 1 0 0 0 0]\n [-4 1 0 0 0 0 0]\n [ 1 0 0 0 0 0 0]\n sage: Partitions(5).list()\n [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]\n sage: s(f[2,2,1])\n s[3, 2] - 2*s[4, 1] + 3*s[5]\n sage: e.transition_matrix(s, 5).inverse().transpose()\n [ 1 -1 0 1 0 -1 1]\n [-2 1 1 -1 -1 1 0]\n [-2 2 -1 -1 1 0 0]\n [ 3 -1 -1 1 0 0 0]\n [ 3 -2 1 0 0 0 0]\n [-4 1 0 0 0 0 0]\n [ 1 0 0 0 0 0 0]\n ' if (n not in self._transition_matrices): self._precompute(n) if (basis is self._dual_basis): return self._inverse_transition_matrices[n] else: return (self._inverse_transition_matrices[n] * self._dual_basis.transition_matrix(basis, n)) def product(self, left, right): '\n Return product of ``left`` and ``right``.\n\n Multiplication is done by performing the multiplication in the dual\n basis of ``self`` and then converting back to ``self``.\n\n INPUT:\n\n - ``left``, ``right`` -- elements of ``self``\n\n OUTPUT:\n\n - the product of ``left`` and ``right`` in the basis ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: a = h([2])\n sage: b = a*a; b # indirect doctest\n d_m[2, 2]\n sage: b.dual()\n 6*m[1, 1, 1, 1] + 4*m[2, 1, 1] + 3*m[2, 2] + 2*m[3, 1] + m[4]\n ' eclass = left.__class__ d_product = (left.dual() * right.dual()) return eclass(self, dual=d_product) class Element(classical.SymmetricFunctionAlgebra_classical.Element): '\n An element in the dual basis.\n\n INPUT:\n\n At least one of the following must be specified. The one (if\n any) which is not provided will be computed.\n\n - ``dictionary`` -- an internal dictionary for the\n monomials and coefficients of ``self``\n\n - ``dual`` -- self as an element of the dual basis.\n ' def __init__(self, A, dictionary=None, dual=None): "\n Create an element of a dual basis.\n\n TESTS::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee, prefix='h')\n sage: a = h([2])\n sage: ec = h._element_class\n sage: ec(h, dual=m([2]))\n -h[1, 1] + 2*h[2]\n sage: h(m([2]))\n -h[1, 1] + 2*h[2]\n sage: h([2])\n h[2]\n sage: h([2])._dual\n m[1, 1] + m[2]\n sage: m(h([2]))\n m[1, 1] + m[2]\n " if ((dictionary is None) and (dual is None)): raise ValueError('you must specify either x or dual') parent = A base_ring = parent.base_ring() zero = base_ring.zero() if (dual is None): dual_dict = {} from_self_cache = parent._from_self_cache s_mcs = dictionary for part in s_mcs: if (part not in from_self_cache): parent._precompute(sum(part)) for s_part in s_mcs: from_dictionary = from_self_cache[s_part] for part in from_dictionary: dual_dict[part] = (dual_dict.get(part, zero) + base_ring((s_mcs[s_part] * from_dictionary[part]))) dual = parent._dual_basis._from_dict(dual_dict) if (dictionary is None): dictionary = {} to_self_cache = parent._to_self_cache d_mcs = dual._monomial_coefficients for part in d_mcs: if (part not in to_self_cache): parent._precompute(sum(part)) dictionary = blas.linear_combination(((to_self_cache[d_part], d_mcs[d_part]) for d_part in d_mcs)) self._dual = dual classical.SymmetricFunctionAlgebra_classical.Element.__init__(self, A, dictionary) def dual(self): '\n Return ``self`` in the dual basis.\n\n OUTPUT:\n\n - the element ``self`` expanded in the dual basis to ``self.parent()``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: a = h([2,1])\n sage: a.parent()\n Dual basis to Symmetric Functions over Rational Field in the monomial basis\n sage: a.dual()\n 3*m[1, 1, 1] + 2*m[2, 1] + m[3]\n ' return self._dual def omega(self): '\n Return the image of ``self`` under the omega automorphism.\n\n The *omega automorphism* is defined to be the unique algebra\n endomorphism `\\omega` of the ring of symmetric functions that\n satisfies `\\omega(e_k) = h_k` for all positive integers `k`\n (where `e_k` stands for the `k`-th elementary symmetric\n function, and `h_k` stands for the `k`-th complete homogeneous\n symmetric function). It furthermore is a Hopf algebra\n endomorphism and an involution, and it is also known as the\n *omega involution*. It sends the power-sum symmetric function\n `p_k` to `(-1)^{k-1} p_k` for every positive integer `k`.\n\n The images of some bases under the omega automorphism are given by\n\n .. MATH::\n\n \\omega(e_{\\lambda}) = h_{\\lambda}, \\qquad\n \\omega(h_{\\lambda}) = e_{\\lambda}, \\qquad\n \\omega(p_{\\lambda}) = (-1)^{|\\lambda| - \\ell(\\lambda)}\n p_{\\lambda}, \\qquad\n \\omega(s_{\\lambda}) = s_{\\lambda^{\\prime}},\n\n where `\\lambda` is any partition, where `\\ell(\\lambda)` denotes\n the length (:meth:`~sage.combinat.partition.Partition.length`)\n of the partition `\\lambda`, where `\\lambda^{\\prime}` denotes the\n conjugate partition\n (:meth:`~sage.combinat.partition.Partition.conjugate`) of\n `\\lambda`, and where the usual notations for bases are used\n (`e` = elementary, `h` = complete homogeneous, `p` = powersum,\n `s` = Schur).\n\n :meth:`omega_involution` is a synonym for the :meth:`omega`\n method.\n\n OUTPUT:\n\n - the result of applying omega to ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: hh = SymmetricFunctions(QQ).homogeneous()\n sage: hh([2,1]).omega()\n h[1, 1, 1] - h[2, 1]\n sage: h([2,1]).omega()\n d_m[1, 1, 1] - d_m[2, 1]\n ' eclass = self.__class__ return eclass(self.parent(), dual=self._dual.omega()) omega_involution = omega def scalar(self, x): '\n Return the standard scalar product of ``self`` and ``x``.\n\n INPUT:\n\n - ``x`` -- element of the symmetric functions\n\n OUTPUT:\n\n - the scalar product between ``x`` and ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: a = h([2,1])\n sage: a.scalar(a)\n 2\n ' return self._dual.scalar(x) def scalar_hl(self, x): '\n Return the Hall-Littlewood scalar product of ``self`` and ``x``.\n\n INPUT:\n\n - ``x`` -- element of the same dual basis as ``self``\n\n OUTPUT:\n\n - the Hall-Littlewood scalar product between ``x`` and ``self``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(scalar=zee)\n sage: a = h([2,1])\n sage: a.scalar_hl(a)\n (-t - 2)/(t^4 - 2*t^3 + 2*t - 1)\n ' return self._dual.scalar_hl(x) def _add_(self, y): '\n Add two elements in the dual basis.\n\n INPUT:\n\n - ``y`` -- element of the same dual basis as ``self``\n\n OUTPUT:\n\n - the sum of ``self`` and ``y``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: a = h([2,1])+h([3]); a # indirect doctest\n d_m[2, 1] + d_m[3]\n sage: h[2,1]._add_(h[3])\n d_m[2, 1] + d_m[3]\n sage: a.dual()\n 4*m[1, 1, 1] + 3*m[2, 1] + 2*m[3]\n ' eclass = self.__class__ return eclass(self.parent(), dual=(self.dual() + y.dual())) def _neg_(self): '\n Return the negative of ``self``.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: -h([2,1]) # indirect doctest\n -d_m[2, 1]\n ' eclass = self.__class__ return eclass(self.parent(), dual=self.dual()._neg_()) def _sub_(self, y): '\n Subtract two elements in the dual basis.\n\n INPUT:\n\n - ``y`` -- element of the same dual basis as ``self``\n\n OUTPUT:\n\n - the difference of ``self`` and ``y``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: h([2,1])-h([3]) # indirect doctest\n d_m[2, 1] - d_m[3]\n sage: h[2,1]._sub_(h[3])\n d_m[2, 1] - d_m[3]\n ' eclass = self.__class__ return eclass(self.parent(), dual=(self.dual() - y.dual())) def _div_(self, y): '\n Divide an element ``self`` of the dual basis by ``y``.\n\n INPUT:\n\n - ``y`` -- element of base field\n\n OUTPUT:\n\n - the element ``self`` divided by ``y``\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: a = h([2,1])+h([3])\n sage: a/2 # indirect doctest\n 1/2*d_m[2, 1] + 1/2*d_m[3]\n ' return (self * (~ y)) def __invert__(self): '\n Invert ``self`` (only possible if ``self`` is a scalar\n multiple of `1` and we are working over a field).\n\n OUTPUT:\n\n - multiplicative inverse of ``self`` if possible\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: a = h(2); a\n 2*d_m[]\n sage: ~a\n 1/2*d_m[]\n sage: a = 3*h[1]\n sage: a.__invert__()\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= 3*m[1])\n ' eclass = self.__class__ return eclass(self.parent(), dual=(~ self.dual())) def expand(self, n, alphabet='x'): "\n Expand the symmetric function ``self`` as a symmetric polynomial\n in ``n`` variables.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n - ``alphabet`` -- (default: ``'x'``) a variable for the expansion\n\n OUTPUT:\n\n A monomial expansion of ``self`` in the `n` variables\n labelled by ``alphabet``.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).monomial()\n sage: zee = sage.combinat.sf.sfa.zee\n sage: h = m.dual_basis(zee)\n sage: a = h([2,1])+h([3])\n sage: a.expand(2)\n 2*x0^3 + 3*x0^2*x1 + 3*x0*x1^2 + 2*x1^3\n sage: a.dual().expand(2)\n 2*x0^3 + 3*x0^2*x1 + 3*x0*x1^2 + 2*x1^3\n sage: a.expand(2,alphabet='y')\n 2*y0^3 + 3*y0^2*y1 + 3*y0*y1^2 + 2*y1^3\n sage: a.expand(2,alphabet='x,y')\n 2*x^3 + 3*x^2*y + 3*x*y^2 + 2*y^3\n sage: h([1]).expand(0)\n 0\n sage: (3*h([])).expand(0)\n 3\n " return self._dual.expand(n, alphabet)
class SymmetricFunctionAlgebra_elementary(multiplicative.SymmetricFunctionAlgebra_multiplicative): def __init__(self, Sym): "\n A class for methods for the elementary basis of the symmetric functions.\n\n INPUT:\n\n - ``self`` -- an elementary basis of the symmetric functions\n - ``Sym`` -- an instance of the ring of symmetric functions\n\n TESTS::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: e == loads(dumps(e))\n True\n sage: TestSuite(e).run(skip=['_test_associativity', '_test_distributivity', '_test_prod'])\n sage: TestSuite(e).run(elements = [e[1,1]+e[2], e[1]+2*e[1,1]])\n " classical.SymmetricFunctionAlgebra_classical.__init__(self, Sym, 'elementary', 'e') def _dual_basis_default(self): '\n Returns the default value for ``self.dual_basis()``\n\n This method returns the dual basis to the elementary basis\n with respect to the standard scalar product, that is the\n forgotten basis.\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: e.dual_basis()\n Symmetric Functions over Rational Field in the forgotten basis\n\n TESTS::\n\n sage: e._dual_basis_default() is e.dual_basis()\n True\n ' return self.dual_basis(scalar=None, prefix='f', basis_name='forgotten') def coproduct_on_generators(self, i): '\n Returns the coproduct on ``self[i]``.\n\n INPUT:\n\n - ``self`` -- an elementary basis of the symmetric functions\n - ``i`` -- a nonnegative integer\n\n OUTPUT:\n\n - returns the coproduct on the elementary generator `e(i)`\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: e = Sym.elementary()\n sage: e.coproduct_on_generators(2)\n e[] # e[2] + e[1] # e[1] + e[2] # e[]\n sage: e.coproduct_on_generators(0)\n e[] # e[]\n ' def P(i): return (Partition([i]) if i else Partition([])) T = self.tensor_square() return T.sum_of_monomials(((P(j), P((i - j))) for j in range((i + 1)))) class Element(classical.SymmetricFunctionAlgebra_classical.Element): def omega(self): '\n Return the image of ``self`` under the omega automorphism.\n\n The *omega automorphism* is defined to be the unique algebra\n endomorphism `\\omega` of the ring of symmetric functions that\n satisfies `\\omega(e_k) = h_k` for all positive integers `k`\n (where `e_k` stands for the `k`-th elementary symmetric\n function, and `h_k` stands for the `k`-th complete homogeneous\n symmetric function). It furthermore is a Hopf algebra\n endomorphism and an involution, and it is also known as the\n *omega involution*. It sends the power-sum symmetric function\n `p_k` to `(-1)^{k-1} p_k` for every positive integer `k`.\n\n The images of some bases under the omega automorphism are given by\n\n .. MATH::\n\n \\omega(e_{\\lambda}) = h_{\\lambda}, \\qquad\n \\omega(h_{\\lambda}) = e_{\\lambda}, \\qquad\n \\omega(p_{\\lambda}) = (-1)^{|\\lambda| - \\ell(\\lambda)}\n p_{\\lambda}, \\qquad\n \\omega(s_{\\lambda}) = s_{\\lambda^{\\prime}},\n\n where `\\lambda` is any partition, where `\\ell(\\lambda)` denotes\n the length (:meth:`~sage.combinat.partition.Partition.length`)\n of the partition `\\lambda`, where `\\lambda^{\\prime}` denotes the\n conjugate partition\n (:meth:`~sage.combinat.partition.Partition.conjugate`) of\n `\\lambda`, and where the usual notations for bases are used\n (`e` = elementary, `h` = complete homogeneous, `p` = powersum,\n `s` = Schur).\n\n :meth:`omega_involution` is a synonym for the :meth:`omega`\n method.\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: a = e([2,1]); a\n e[2, 1]\n sage: a.omega()\n e[1, 1, 1] - e[2, 1]\n\n ::\n\n sage: h = SymmetricFunctions(QQ).h()\n sage: h(e([2,1]).omega())\n h[2, 1]\n ' e = self.parent() h = e.realization_of().h() return e(h._from_element(self)) omega_involution = omega def verschiebung(self, n): '\n Return the image of the symmetric function ``self`` under the\n `n`-th Verschiebung operator.\n\n The `n`-th Verschiebung operator `\\mathbf{V}_n` is defined to be\n the unique algebra endomorphism `V` of the ring of symmetric\n functions that satisfies `V(h_r) = h_{r/n}` for every positive\n integer `r` divisible by `n`, and satisfies `V(h_r) = 0` for\n every positive integer `r` not divisible by `n`. This operator\n `\\mathbf{V}_n` is a Hopf algebra endomorphism. For every\n nonnegative integer `r` with `n \\mid r`, it satisfies\n\n .. MATH::\n\n \\mathbf{V}_n(h_r) = h_{r/n},\n \\quad \\mathbf{V}_n(p_r) = n p_{r/n},\n \\quad \\mathbf{V}_n(e_r) = (-1)^{r - r/n} e_{r/n}\n\n (where `h` is the complete homogeneous basis, `p` is the\n powersum basis, and `e` is the elementary basis). For every\n nonnegative integer `r` with `n \\nmid r`, it satisfes\n\n .. MATH::\n\n \\mathbf{V}_n(h_r) = \\mathbf{V}_n(p_r) = \\mathbf{V}_n(e_r) = 0.\n\n The `n`-th Verschiebung operator is also called the `n`-th\n Verschiebung endomorphism. Its name derives from the Verschiebung\n (German for "shift") endomorphism of the Witt vectors.\n\n The `n`-th Verschiebung operator is adjoint to the `n`-th\n Frobenius operator (see :meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.frobenius`\n for its definition) with respect to the Hall scalar product\n (:meth:`~sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.scalar`).\n\n The action of the `n`-th Verschiebung operator on the Schur basis\n can also be computed explicitly. The following (probably clumsier\n than necessary) description can be obtained by solving exercise\n 7.61 in Stanley [STA]_.\n\n Let `\\lambda` be a partition. Let `n` be a positive integer. If\n the `n`-core of `\\lambda` is nonempty, then\n `\\mathbf{V}_n(s_\\lambda) = 0`. Otherwise, the following method\n computes `\\mathbf{V}_n(s_\\lambda)`: Write the partition `\\lambda`\n in the form `(\\lambda_1, \\lambda_2, ..., \\lambda_{ns})` for some\n nonnegative integer `s`. (If `n` does not divide the length of\n `\\lambda`, then this is achieved by adding trailing zeroes to\n `\\lambda`.) Set `\\beta_i = \\lambda_i + ns - i` for every\n `s \\in \\{ 1, 2, \\ldots, ns \\}`. Then,\n `(\\beta_1, \\beta_2, ..., \\beta_{ns})` is a strictly decreasing\n sequence of nonnegative integers. Stably sort the list\n `(1, 2, \\ldots, ns)` in order of (weakly) increasing remainder of\n `-1 - \\beta_i` modulo `n`. Let `\\xi` be the sign of the\n permutation that is used for this sorting. Let `\\psi` be the sign\n of the permutation that is used to stably sort the list\n `(1, 2, \\ldots, ns)` in order of (weakly) increasing remainder of\n `i - 1` modulo `n`. (Notice that `\\psi = (-1)^{n(n-1)s(s-1)/4}`.)\n Then, `\\mathbf{V}_n(s_\\lambda) = \\xi \\psi \\prod_{i=0}^{n-1}\n s_{\\lambda^{(i)}}`, where\n `(\\lambda^{(0)}, \\lambda^{(1)}, \\ldots, \\lambda^{(n - 1)})`\n is the `n`-quotient of `\\lambda`.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n OUTPUT:\n\n The result of applying the `n`-th Verschiebung operator (on the\n ring of symmetric functions) to ``self``.\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(ZZ)\n sage: e = Sym.e()\n sage: e[3].verschiebung(2)\n 0\n sage: e[4].verschiebung(4)\n -e[1]\n\n The Verschiebung endomorphisms are multiplicative::\n\n sage: all( all( e(lam).verschiebung(2) * e(mu).verschiebung(2)\n ....: == (e(lam) * e(mu)).verschiebung(2)\n ....: for mu in Partitions(4) )\n ....: for lam in Partitions(4) )\n True\n\n TESTS:\n\n Let us check that this method on the elementary basis gives the\n same result as the implementation in :mod:`sage.combinat.sf.sfa`\n on the complete homogeneous basis::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: e = Sym.e(); h = Sym.h()\n sage: all( h(e(lam)).verschiebung(3) == h(e(lam).verschiebung(3))\n ....: for lam in Partitions(6) )\n True\n sage: all( e(h(lam)).verschiebung(2) == e(h(lam).verschiebung(2))\n ....: for lam in Partitions(4) )\n True\n ' parent = self.parent() e_coords_of_self = self.monomial_coefficients().items() dct = {Partition([(i // n) for i in lam]): (((- 1) ** (sum(lam) - (sum(lam) // n))) * coeff) for (lam, coeff) in e_coords_of_self if all((((i % n) == 0) for i in lam))} result_in_e_basis = parent._from_dict(dct) return parent(result_in_e_basis) def expand(self, n, alphabet='x'): "\n Expand the symmetric function ``self`` as a symmetric polynomial\n in ``n`` variables.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n - ``alphabet`` -- (default: ``'x'``) a variable for the expansion\n\n OUTPUT:\n\n A monomial expansion of ``self`` in the `n` variables\n labelled by ``alphabet``.\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: e([2,1]).expand(3)\n x0^2*x1 + x0*x1^2 + x0^2*x2 + 3*x0*x1*x2 + x1^2*x2 + x0*x2^2 + x1*x2^2\n sage: e([1,1,1]).expand(2)\n x0^3 + 3*x0^2*x1 + 3*x0*x1^2 + x1^3\n sage: e([3]).expand(2)\n 0\n sage: e([2]).expand(3)\n x0*x1 + x0*x2 + x1*x2\n sage: e([3]).expand(4,alphabet='x,y,z,t')\n x*y*z + x*y*t + x*z*t + y*z*t\n sage: e([3]).expand(4,alphabet='y')\n y0*y1*y2 + y0*y1*y3 + y0*y2*y3 + y1*y2*y3\n sage: e([]).expand(2)\n 1\n sage: e([]).expand(0)\n 1\n sage: (3*e([])).expand(0)\n 3\n " condition = (lambda part: (max(part) > n)) return self._expand(condition, n, alphabet) def principal_specialization(self, n=infinity, q=None): '\n Return the principal specialization of a symmetric function.\n\n The *principal specialization* of order `n` at `q`\n is the ring homomorphism `ps_{n,q}` from the ring of\n symmetric functions to another commutative ring `R`\n given by `x_i \\mapsto q^{i-1}` for `i \\in \\{1,\\dots,n\\}`\n and `x_i \\mapsto 0` for `i > n`.\n Here, `q` is a given element of `R`, and we assume that\n the variables of our symmetric functions are\n `x_1, x_2, x_3, \\ldots`.\n (To be more precise, `ps_{n,q}` is a `K`-algebra\n homomorphism, where `K` is the base ring.)\n See Section 7.8 of [EnumComb2]_.\n\n The *stable principal specialization* at `q` is the ring\n homomorphism `ps_q` from the ring of symmetric functions\n to another commutative ring `R` given by\n `x_i \\mapsto q^{i-1}` for all `i`.\n This is well-defined only if the resulting infinite sums\n converge; thus, in particular, setting `q = 1` in the\n stable principal specialization is an invalid operation.\n\n INPUT:\n\n - ``n`` (default: ``infinity``) -- a nonnegative integer or\n ``infinity``, specifying whether to compute the principal\n specialization of order ``n`` or the stable principal\n specialization.\n\n - ``q`` (default: ``None``) -- the value to use for `q`; the\n default is to create a ring of polynomials in ``q``\n (or a field of rational functions in ``q``) over the\n given coefficient ring.\n\n We use the formulas from Proposition 7.8.3 of [EnumComb2]_\n (using Gaussian binomial coefficients `\\binom{u}{v}_q`):\n\n .. MATH::\n\n ps_{n,q}(e_\\lambda) = \\prod_i q^{\\binom{\\lambda_i}{2}} \\binom{n}{\\lambda_i}_q,\n\n ps_{n,1}(e_\\lambda) = \\prod_i \\binom{n}{\\lambda_i},\n\n ps_q(e_\\lambda) = \\prod_i q^{\\binom{\\lambda_i}{2}} / \\prod_{j=1}^{\\lambda_i} (1-q^j).\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: x = e[3,1]\n sage: x.principal_specialization(3)\n q^5 + q^4 + q^3\n sage: x = 5*e[1,1,1] + 3*e[2,1] + 1\n sage: x.principal_specialization(3)\n 5*q^6 + 18*q^5 + 36*q^4 + 44*q^3 + 36*q^2 + 18*q + 6\n\n By default, we return a rational functions in `q`. Sometimes\n it is better to obtain an element of the symbolic ring::\n\n sage: x.principal_specialization(q=var("q")) # needs sage.symbolic\n -3*q/((q^2 - 1)*(q - 1)^2) - 5/(q - 1)^3 + 1\n\n TESTS::\n\n sage: e.zero().principal_specialization(3)\n 0\n\n ' from sage.combinat.q_analogues import q_binomial def get_variable(ring, name): try: ring(name) except TypeError: from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing return PolynomialRing(ring, name).gen() else: raise ValueError(('the variable %s is in the base ring, pass it explicitly' % name)) if (q is None): q = get_variable(self.base_ring(), 'q') if (q == 1): if (n == infinity): raise ValueError('the stable principal specialization at q=1 is not defined') f = (lambda partition: prod((binomial(n, part) for part in partition))) elif (n == infinity): f = (lambda partition: prod((((q ** binomial(part, 2)) / prod(((1 - (q ** i)) for i in range(1, (part + 1))))) for part in partition))) else: f = (lambda partition: prod((((q ** binomial(part, 2)) * q_binomial(n, part, q=q)) for part in partition))) return self.parent()._apply_module_morphism(self, f, q.parent()) def exponential_specialization(self, t=None, q=1): '\n Return the exponential specialization of a\n symmetric function (when `q = 1`), or the\n `q`-exponential specialization (when `q \\neq 1`).\n\n The *exponential specialization* `ex` at `t` is a\n `K`-algebra homomorphism from the `K`-algebra of\n symmetric functions to another `K`-algebra `R`.\n It is defined whenever the base ring `K` is a\n `\\QQ`-algebra and `t` is an element of `R`.\n The easiest way to define it is by specifying its\n values on the powersum symmetric functions to be\n `p_1 = t` and `p_n = 0` for `n > 1`.\n Equivalently, on the homogeneous functions it is\n given by `ex(h_n) = t^n / n!`; see Proposition 7.8.4 of\n [EnumComb2]_.\n\n By analogy, the `q`-exponential specialization is a\n `K`-algebra homomorphism from the `K`-algebra of\n symmetric functions to another `K`-algebra `R` that\n depends on two elements `t` and `q` of `R` for which\n the elements `1 - q^i` for all positive integers `i`\n are invertible.\n It can be defined by specifying its values on the\n complete homogeneous symmetric functions to be\n\n .. MATH::\n\n ex_q(h_n) = t^n / [n]_q!,\n\n where `[n]_q!` is the `q`-factorial. Equivalently, for\n `q \\neq 1` and a homogeneous symmetric function `f` of\n degree `n`, we have\n\n .. MATH::\n\n ex_q(f) = (1-q)^n t^n ps_q(f),\n\n where `ps_q(f)` is the stable principal specialization of `f`\n (see :meth:`principal_specialization`).\n (See (7.29) in [EnumComb2]_.)\n\n The limit of `ex_q` as `q \\to 1` is `ex`.\n\n INPUT:\n\n - ``t`` (default: ``None``) -- the value to use for `t`;\n the default is to create a ring of polynomials in ``t``.\n\n - ``q`` (default: `1`) -- the value to use for `q`. If\n ``q`` is ``None``, then a ring (or fraction field) of\n polynomials in ``q`` is created.\n\n EXAMPLES::\n\n sage: e = SymmetricFunctions(QQ).e()\n sage: x = e[3,2]\n sage: x.exponential_specialization()\n 1/12*t^5\n sage: x = 5*e[2] + 3*e[1] + 1\n sage: x.exponential_specialization(t=var("t"), q=var("q")) # needs sage.symbolic\n 5*q*t^2/(q + 1) + 3*t + 1\n\n TESTS::\n\n sage: e.zero().exponential_specialization()\n 0\n\n ' from sage.combinat.q_analogues import q_factorial def get_variable(ring, name): try: ring(name) except TypeError: from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing return PolynomialRing(ring, name).gen() else: raise ValueError(('the variable %s is in the base ring, pass it explicitly' % name)) if (q == 1): if (t is None): t = get_variable(self.base_ring(), 't') def f(partition): n = 0 m = 1 for part in partition: n += part m *= factorial(part) return ((t ** n) / m) return self.parent()._apply_module_morphism(self, f, t.parent()) if ((q is None) and (t is None)): q = get_variable(self.base_ring(), 'q') t = get_variable(q.parent(), 't') elif (q is None): q = get_variable(t.parent(), 'q') elif (t is None): t = get_variable(q.parent(), 't') def f(partition): n = 0 m = 1 for part in partition: n += part m *= ((q ** binomial(part, 2)) / q_factorial(part, q=q)) return ((t ** n) * m) return self.parent()._apply_module_morphism(self, f, t.parent())
class HallLittlewood(UniqueRepresentation): "\n The family of Hall-Littlewood symmetric function bases.\n\n The Hall-Littlewood symmetric functions are a family of symmetric\n functions that depend on a parameter `t`.\n\n INPUT:\n\n By default the parameter for these functions is `t`, and\n whatever the parameter is, it must be in the base ring.\n\n EXAMPLES::\n\n sage: SymmetricFunctions(QQ).hall_littlewood(1)\n Hall-Littlewood polynomials with t=1 over Rational Field\n sage: SymmetricFunctions(QQ['t'].fraction_field()).hall_littlewood()\n Hall-Littlewood polynomials over Fraction Field of Univariate Polynomial Ring in t over Rational Field\n " def __repr__(self): '\n A string representing the family of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n - a string representing the class\n\n EXAMPLES::\n\n sage: SymmetricFunctions(QQ).hall_littlewood(1)\n Hall-Littlewood polynomials with t=1 over Rational Field\n ' return (self._name + (' over %s' % self._sym.base_ring())) def __init__(self, Sym, t='t'): "\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: HL = SymmetricFunctions(FractionField(QQ['t'])).hall_littlewood()\n sage: TestSuite(HL).run()\n " self._sym = Sym self.t = Sym.base_ring()(t) self._name_suffix = '' if (str(t) != 't'): self._name_suffix += (' with t=%s' % t) self._name = ('Hall-Littlewood polynomials' + self._name_suffix) def symmetric_function_ring(self): "\n The ring of symmetric functions associated to the class of Hall-Littlewood\n symmetric functions\n\n INPUT:\n\n - ``self`` -- a class of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n - returns the ring of symmetric functions\n\n EXAMPLES::\n\n sage: HL = SymmetricFunctions(FractionField(QQ['t'])).hall_littlewood()\n sage: HL.symmetric_function_ring()\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field\n " return self._sym def base_ring(self): "\n Returns the base ring of the symmetric functions where the\n Hall-Littlewood symmetric functions live\n\n INPUT:\n\n - ``self`` -- a class of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n The base ring of the symmetric functions.\n\n EXAMPLES::\n\n sage: HL = SymmetricFunctions(QQ['t'].fraction_field()).hall_littlewood(t=1)\n sage: HL.base_ring()\n Fraction Field of Univariate Polynomial Ring in t over Rational Field\n " return self._sym.base_ring() def P(self): "\n Return the algebra of symmetric functions in the Hall-Littlewood\n `P` basis. This is the same as the `HL` basis in John Stembridge's\n SF examples file.\n\n INPUT:\n\n - ``self`` -- a class of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n The class of the Hall-Littlewood `P` basis.\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P(); HLP\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field in the Hall-Littlewood P basis\n sage: SP = Sym.hall_littlewood(t=-1).P(); SP\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field in the Hall-Littlewood P with t=-1 basis\n sage: s = Sym.schur()\n sage: s(HLP([2,1]))\n (-t^2-t)*s[1, 1, 1] + s[2, 1]\n\n The Hall-Littlewood polynomials in the `P` basis at `t = 0` are the\n Schur functions::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: HLP = Sym.hall_littlewood(t=0).P()\n sage: s = Sym.schur()\n sage: s(HLP([2,1])) == s([2,1])\n True\n\n The Hall-Littlewood polynomials in the `P` basis at `t = 1` are the\n monomial symmetric functions::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: HLP = Sym.hall_littlewood(t=1).P()\n sage: m = Sym.monomial()\n sage: m(HLP([2,2,1])) == m([2,2,1])\n True\n\n We end with some examples of coercions between:\n\n 1. Hall-Littlewood `P` basis.\n\n 2. Hall-Littlewood polynomials in the `Q` basis\n\n 3. Hall-Littlewood polynomials in the `Q^\\prime` basis (via the Schurs)\n\n 4. Classical symmetric functions\n\n ::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: s = Sym.schur()\n sage: p = Sym.power()\n sage: HLP(HLQ([2])) # indirect doctest\n (-t+1)*HLP[2]\n sage: HLP(HLQp([2]))\n t*HLP[1, 1] + HLP[2]\n sage: HLP(s([2]))\n t*HLP[1, 1] + HLP[2]\n sage: HLP(p([2]))\n (t-1)*HLP[1, 1] + HLP[2]\n sage: s = HLQp.symmetric_function_ring().s()\n sage: HLQp.transition_matrix(s,3)\n [ 1 0 0]\n [ t 1 0]\n [ t^3 t^2 + t 1]\n sage: s.transition_matrix(HLP,3)\n [ 1 t t^3]\n [ 0 1 t^2 + t]\n [ 0 0 1]\n\n The method :meth:`sage.combinat.sf.sfa.SymmetricFunctionAlgebra_generic_Element.hl_creation_operator`\n is a creation operator for the `Q` basis::\n\n sage: HLQp[1].hl_creation_operator([3]).hl_creation_operator([3])\n HLQp[3, 3, 1]\n\n Transitions between bases with the parameter `t` specialized::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['y','z']))\n sage: (y,z) = Sym.base_ring().gens()\n sage: HLy = Sym.hall_littlewood(t=y)\n sage: HLz = Sym.hall_littlewood(t=z)\n sage: Qpy = HLy.Qp()\n sage: Qpz = HLz.Qp()\n sage: s = Sym.schur()\n sage: s( Qpy[3,1] + z*Qpy[2,2] )\n z*s[2, 2] + (y*z+1)*s[3, 1] + (y^2*z+y)*s[4]\n sage: s( Qpy[3,1] + y*Qpz[2,2] )\n y*s[2, 2] + (y*z+1)*s[3, 1] + (y*z^2+y)*s[4]\n sage: s( Qpy[3,1] + y*Qpy[2,2] )\n y*s[2, 2] + (y^2+1)*s[3, 1] + (y^3+y)*s[4]\n\n sage: Qy = HLy.Q()\n sage: Qz = HLz.Q()\n sage: Py = HLy.P()\n sage: Pz = HLz.P()\n sage: Pz(Qpy[2,1])\n (y*z^3+z^2+z)*HLP[1, 1, 1] + (y*z+1)*HLP[2, 1] + y*HLP[3]\n sage: Pz(Qz[2,1])\n (z^2-2*z+1)*HLP[2, 1]\n sage: Qz(Py[2])\n ((-y+z)/(z^3-z^2-z+1))*HLQ[1, 1] + (1/(-z+1))*HLQ[2]\n sage: Qy(Pz[2])\n ((y-z)/(y^3-y^2-y+1))*HLQ[1, 1] + (1/(-y+1))*HLQ[2]\n sage: Qy.hall_littlewood_family() == HLy\n True\n sage: Qy.hall_littlewood_family() == HLz\n False\n sage: Qz.symmetric_function_ring() == Qy.symmetric_function_ring()\n True\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['q']))\n sage: q = Sym.base_ring().gen()\n sage: HL = Sym.hall_littlewood(t=q)\n sage: HLQp = HL.Qp()\n sage: HLQ = HL.Q()\n sage: HLP = HL.P()\n sage: s = Sym.schur()\n sage: s(HLQp[3,2].plethysm((1-q)*s[1]))/(1-q)^2\n (-q^5-q^4)*s[1, 1, 1, 1, 1] + (q^3+q^2)*s[2, 1, 1, 1] - q*s[2, 2, 1] - q*s[3, 1, 1] + s[3, 2]\n sage: s(HLP[3,2])\n (-q^5-q^4)*s[1, 1, 1, 1, 1] + (q^3+q^2)*s[2, 1, 1, 1] - q*s[2, 2, 1] - q*s[3, 1, 1] + s[3, 2]\n\n The `P` and `Q`-Schur at `t=-1` indexed by strict partitions are a basis for\n the space algebraically generated by the odd power sum symmetric functions::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['q']))\n sage: SP = Sym.hall_littlewood(t=-1).P()\n sage: SQ = Sym.hall_littlewood(t=-1).Q()\n sage: p = Sym.power()\n sage: SP(SQ[3,2,1])\n 8*HLP[3, 2, 1]\n sage: SP(SQ[2,2,1])\n 0\n sage: p(SP[3,2,1])\n 1/45*p[1, 1, 1, 1, 1, 1] - 1/9*p[3, 1, 1, 1] - 1/9*p[3, 3] + 1/5*p[5, 1]\n sage: SP(p[3,3])\n -4*HLP[3, 2, 1] + 2*HLP[4, 2] - 2*HLP[5, 1] + HLP[6]\n sage: SQ( SQ[1]*SQ[3] -2*(1-q)*SQ[4] )\n HLQ[3, 1] + 2*q*HLQ[4]\n\n TESTS::\n\n sage: HLP(s[[]])\n HLP[]\n sage: HLQ(s[[]])\n HLQ[]\n sage: HLQp(s[[]])\n HLQp[]\n " return HallLittlewood_p(self) def Q(self): "\n Returns the algebra of symmetric functions in Hall-Littlewood `Q`\n basis. This is the same as the `Q` basis in John Stembridge's SF\n examples file.\n\n More extensive examples can be found in the documentation for the\n Hall-Littlewood `P` basis.\n\n INPUT:\n\n - ``self`` -- a class of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n - returns the class of the Hall-Littlewood `Q` basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLQ = Sym.hall_littlewood().Q(); HLQ\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field in the Hall-Littlewood Q basis\n sage: SQ = SymmetricFunctions(QQ).hall_littlewood(t=-1).Q(); SQ\n Symmetric Functions over Rational Field in the Hall-Littlewood Q with t=-1 basis\n " return HallLittlewood_q(self) def Qp(self): "\n Returns the algebra of symmetric functions in Hall-Littlewood `Q^\\prime` (Qp)\n basis. This is dual to the Hall-Littlewood `P` basis with respect to\n the standard scalar product.\n\n More extensive examples can be found in the documentation for the\n Hall-Littlewood P basis.\n\n INPUT:\n\n - ``self`` -- a class of Hall-Littlewood symmetric function bases\n\n OUTPUT:\n\n - returns the class of the Hall-Littlewood `Qp`-basis\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLQp = Sym.hall_littlewood().Qp(); HLQp\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field in the Hall-Littlewood Qp basis\n " return HallLittlewood_qp(self)
class HallLittlewood_generic(sfa.SymmetricFunctionAlgebra_generic): def __init__(self, hall_littlewood): "\n A class with methods for working with Hall-Littlewood symmetric functions which\n are common to all bases.\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n - ``hall_littlewood`` -- a class of Hall-Littlewood bases\n\n TESTS::\n\n sage: SymmetricFunctions(QQ['t'].fraction_field()).hall_littlewood().P()\n Symmetric Functions over Fraction Field of Univariate Polynomial Ring in t over Rational Field in the Hall-Littlewood P basis\n sage: SymmetricFunctions(QQ).hall_littlewood(t=2).P()\n Symmetric Functions over Rational Field in the Hall-Littlewood P with t=2 basis\n " s = self.__class__.__name__[15:].capitalize() sfa.SymmetricFunctionAlgebra_generic.__init__(self, hall_littlewood._sym, basis_name=(('Hall-Littlewood ' + s) + hall_littlewood._name_suffix), prefix=('HL' + s)) self.t = hall_littlewood.t self._sym = hall_littlewood._sym self._hall_littlewood = hall_littlewood self._s = self._sym.schur() if hasattr(self, '_s_cache'): category = sage.categories.all.ModulesWithBasis(self._sym.base_ring()) self.register_coercion(SetMorphism(Hom(self._s, self, category), self._s_to_self)) self._s.register_coercion(SetMorphism(Hom(self, self._s, category), self._self_to_s)) def _s_to_self(self, x): '\n Isomorphism from the Schur basis into ``self``\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n - ``x`` -- an element of the Schur basis\n\n OUTPUT:\n\n - an element of ``self`` equivalent to ``x``\n\n EXAMPLES::\n\n sage: P = SymmetricFunctions(QQ).hall_littlewood(t=2).P()\n sage: s = SymmetricFunctions(QQ).schur()\n sage: P._s_to_self(s[2,1])\n 6*HLP[1, 1, 1] + HLP[2, 1]\n\n This is for internal use only. Please use instead::\n\n sage: P(s[2,1])\n 6*HLP[1, 1, 1] + HLP[2, 1]\n ' return self._from_cache(x, self._s_cache, self._s_to_self_cache, t=self.t) def _self_to_s(self, x): '\n Isomorphism from ``self`` to the Schur basis\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n - ``x`` -- an element of the basis ``self``\n\n OUTPUT:\n\n - an element of the Schur basis equivalent to ``x``\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(QQ)\n sage: P = Sym.hall_littlewood(t=2).P()\n sage: s = Sym.schur()\n sage: P._self_to_s(P[2,1])\n -6*s[1, 1, 1] + s[2, 1]\n\n This is for internal use only. Please use instead::\n\n sage: s(P[2,1])\n -6*s[1, 1, 1] + s[2, 1]\n ' return self._s._from_cache(x, self._s_cache, self._self_to_s_cache, t=self.t) def transition_matrix(self, basis, n): "\n Returns the transitions matrix between ``self`` and ``basis`` for the\n homogeneous component of degree ``n``.\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n - ``basis`` -- another symmetric function basis\n - ``n`` -- a non-negative integer representing the degree\n\n OUTPUT:\n\n - Returns a `r \\times r` matrix of elements of the base ring of ``self``\n where `r` is the number of partitions of ``n``.\n The entry corresponding to row `\\mu`, column `\\nu` is the\n coefficient of ``basis`` `(\\nu)` in ``self`` `(\\mu)`\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: s = Sym.schur()\n sage: HLP.transition_matrix(s, 4)\n [ 1 -t 0 t^2 -t^3]\n [ 0 1 -t -t t^3 + t^2]\n [ 0 0 1 -t t^3]\n [ 0 0 0 1 -t^3 - t^2 - t]\n [ 0 0 0 0 1]\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQ.transition_matrix(s,3)\n [ -t + 1 t^2 - t -t^3 + t^2]\n [ 0 t^2 - 2*t + 1 -t^4 + t^3 + t^2 - t]\n [ 0 0 -t^6 + t^5 + t^4 - t^2 - t + 1]\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: HLQp.transition_matrix(s,3)\n [ 1 0 0]\n [ t 1 0]\n [ t^3 t^2 + t 1]\n " P = sage.combinat.partition.Partitions_n(n) Plist = P.list() m = [] for row_part in Plist: z = basis(self(row_part)) m.append([z.coefficient(col_part) for col_part in Plist]) return matrix(m) def product(self, left, right): "\n Multiply an element of the Hall-Littlewood symmetric function\n basis ``self`` and another symmetric function\n\n Convert to the Schur basis, do the multiplication there, and\n convert back to ``self`` basis.\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n - ``left`` -- an element of the basis ``self``\n - ``right`` -- another symmetric function\n\n OUTPUT:\n\n the product of ``left`` and ``right`` expanded in the basis ``self``\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLP([2])^2 # indirect doctest\n (t+1)*HLP[2, 2] + (-t+1)*HLP[3, 1] + HLP[4]\n\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQ([2])^2 # indirect doctest\n HLQ[2, 2] + (-t+1)*HLQ[3, 1] + (-t+1)*HLQ[4]\n\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: HLQp([2])^2 # indirect doctest\n HLQp[2, 2] + (-t+1)*HLQp[3, 1] + (-t+1)*HLQp[4]\n " return self((self._s(left) * self._s(right))) def hall_littlewood_family(self): "\n The family of Hall-Littlewood bases associated to ``self``\n\n INPUT:\n\n - ``self`` -- a Hall-Littlewood symmetric function basis\n\n OUTPUT:\n\n - returns the class of Hall-Littlewood bases\n\n EXAMPLES::\n\n sage: HLP = SymmetricFunctions(FractionField(QQ['t'])).hall_littlewood(1).P()\n sage: HLP.hall_littlewood_family()\n Hall-Littlewood polynomials with t=1 over Fraction Field of Univariate Polynomial Ring in t over Rational Field\n " return self._hall_littlewood class Element(sfa.SymmetricFunctionAlgebra_generic.Element): '\n Methods for elements of a Hall-Littlewood basis that are common to all bases.\n ' def expand(self, n, alphabet='x'): "\n Expands the symmetric function as a symmetric polynomial in ``n`` variables.\n\n INPUT:\n\n - ``self`` -- an element of a Hall-Littlewood basis\n - ``n`` -- a positive integer\n - ``alphabet`` -- a string representing a variable name (default: 'x')\n\n OUTPUT:\n\n - returns a symmetric polynomial of ``self`` in ``n`` variables\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: HLP([2]).expand(2)\n x0^2 + (-t + 1)*x0*x1 + x1^2\n sage: HLQ([2]).expand(2)\n (-t + 1)*x0^2 + (t^2 - 2*t + 1)*x0*x1 + (-t + 1)*x1^2\n sage: HLQp([2]).expand(2)\n x0^2 + x0*x1 + x1^2\n sage: HLQp([2]).expand(2, 'y')\n y0^2 + y0*y1 + y1^2\n sage: HLQp([2]).expand(1)\n x^2\n " s = self.parent().realization_of().schur() return s(self).expand(n, alphabet=alphabet) def scalar(self, x, zee=None): "\n Returns standard scalar product between ``self`` and ``x``.\n\n This is the default implementation that converts both ``self`` and ``x``\n into Schur functions and performs the scalar product that basis.\n\n The Hall-Littlewood `P` basis is dual to the `Qp` basis with respect to\n this scalar product.\n\n INPUT:\n\n - ``self`` -- an element of a Hall-Littlewood basis\n - ``x`` -- another symmetric element of the symmetric functions\n\n OUTPUT:\n\n - returns the scalar product between ``self`` and ``x``\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: HLP([2]).scalar(HLQp([2]))\n 1\n sage: HLP([2]).scalar(HLQp([1,1]))\n 0\n sage: HLP([2]).scalar(HLQ([2]), lambda mu: mu.centralizer_size(t = HLP.t))\n 1\n sage: HLP([2]).scalar(HLQ([1,1]), lambda mu: mu.centralizer_size(t = HLP.t))\n 0\n " s = self.parent().realization_of().schur() s_self = s(self) s_x = s(x) return s_self.scalar(s_x, zee) def scalar_hl(self, x, t=None): "\n Returns the Hall-Littlewood (with parameter ``t``) scalar product\n of ``self`` and ``x``.\n\n The Hall-Littlewood scalar product is defined in Macdonald's\n book [Mac1995]_. The power sum basis is orthogonal and\n `\\langle p_\\mu, p_\\mu \\rangle = z_\\mu \\prod_{i} 1/(1-t^{\\mu_i})`\n\n The Hall-Littlewood `P` basis is dual to the `Q` basis with respect to\n this scalar product.\n\n INPUT:\n\n - ``self`` -- an element of a Hall-Littlewood basis\n - ``x`` -- another symmetric element of the symmetric functions\n - ``t`` -- an optional parameter, if this parameter is not specified then\n the value of the ``t`` from the basis is used in the calculation\n\n OUTPUT:\n\n - returns the Hall-Littlewood scalar product between ``self`` and ``x``\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLP([2]).scalar_hl(HLQ([2]))\n 1\n sage: HLP([2]).scalar_hl(HLQ([1,1]))\n 0\n sage: HLQ([2]).scalar_hl(HLQ([2]))\n -t + 1\n sage: HLQ([2]).scalar_hl(HLQ([1,1]))\n 0\n sage: HLP([2]).scalar_hl(HLP([2]))\n -1/(t - 1)\n " parent = self.parent() if (t is None): t = parent.t p = parent.realization_of().power() f = (lambda part1, part2: part1.centralizer_size(t=t)) return parent._apply_multi_module_morphism(p(self), p(x), f, orthogonal=True)
class HallLittlewood_p(HallLittlewood_generic): '\n A class representing the Hall-Littlewood `P` basis of symmetric functions\n ' class Element(HallLittlewood_generic.Element): pass def __init__(self, hall_littlewood): "\n A class with methods for working with the Hall-Littlewood `P` basis\n\n The `P` basis is calculated from the Schur basis using the functions\n in :meth:`sage.combinat.sf.kfpoly`. These functions calculate Kostka-Foulkes polynomials\n using rigged configuration formulas.\n\n This change of basis is inverted to convert to the Schur basis.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``hall_littlewood`` -- a class for the family of Hall-Littlewood bases\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: P = Sym.hall_littlewood().P()\n sage: TestSuite(P).run(skip=['_test_associativity', '_test_distributivity', '_test_prod']) # products are too expensive\n sage: TestSuite(P).run(elements = [P.t*P[1,1]+P[2], P[1]+(1+P.t)*P[1,1]])\n " HallLittlewood_generic.__init__(self, hall_littlewood) self._self_to_s_cache = p_to_s_cache self._s_to_self_cache = s_to_p_cache def _q_to_p_normalization(self, m): "\n The coefficient relating the `Q` and the `P` bases.\n\n Returns the scalar coefficient that is used when converting from the\n `Q` basis to the `P` basis. Note that this assumes that ``m`` is a\n Partition object.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``m`` -- a partition\n\n OUTPUT:\n\n - returns the coefficient equal to `Q(m)/P(m)`\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLP._q_to_p_normalization(Partition([2,1]))\n t^2 - 2*t + 1\n " t = self.t coeff = ((1 - t) ** len(m)) for i in m.to_exp(): for j in range(1, (i + 1)): coeff *= ((1 - (t ** j)) / (1 - t)) return coeff def _s_to_self_base(self, part): "\n Returns a function which gives the coefficient of a partition\n in the expansion of the Schur functions ``s(part)`` in the Hall-Littlewood\n `P` basis.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``part`` -- a partition\n\n OUTPUT:\n\n - returns a function which accepts a partition ``part2`` and returns\n the coefficient of ``P(part2)`` in ``s(part)``\n This coefficient is the t-Kostka-Foulkes polynomial `K_{part,part2}(t)`\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: f21 = HLP._s_to_self_base(Partition([2,1]))\n sage: [f21(p) for p in Partitions(3)]\n [0, 1, t^2 + t]\n " from sage.combinat.sf.kfpoly import schur_to_hl t = QQt.gen() zero = self.base_ring().zero() res_dict = schur_to_hl(part, t) f = (lambda part2: res_dict.get(part2, zero)) return f def _s_cache(self, n): "\n Computes the change of basis between the `P` polynomials and the\n Schur functions for partitions of size ``n``.\n\n Uses the fact that the transformation matrix is upper-triangular in\n order to obtain the inverse transformation.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``n`` -- positive integer\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLP._s_cache(2)\n sage: l = lambda c: [ (i[0],[j for j in sorted(i[1].items())]) for i in sorted(c.items())]\n sage: l(HLP._s_to_self_cache[2])\n [([1, 1], [([1, 1], 1)]), ([2], [([1, 1], t), ([2], 1)])]\n sage: l(HLP._self_to_s_cache[2])\n [([1, 1], [([1, 1], 1)]), ([2], [([1, 1], -t), ([2], 1)])]\n sage: HLP = Sym.hall_littlewood(10).P()\n sage: HLP._s_cache(2)\n sage: l(HLP._s_to_self_cache[2])\n [([1, 1], [([1, 1], 1)]), ([2], [([1, 1], t), ([2], 1)])]\n " self._invert_morphism(n, QQt, self._self_to_s_cache, self._s_to_self_cache, to_self_function=self._s_to_self_base, upper_triangular=True, ones_on_diagonal=True)
class HallLittlewood_q(HallLittlewood_generic): class Element(HallLittlewood_generic.Element): pass def __init__(self, hall_littlewood): "\n The `Q` basis is defined as a normalization of the `P` basis.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``hall_littlewood`` -- a class for the family of Hall-Littlewood bases\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: Q = Sym.hall_littlewood().Q()\n sage: TestSuite(Q).run(skip=['_test_associativity', '_test_distributivity', '_test_prod']) # products are too expensive, long time (3s on sage.math, 2012)\n sage: TestSuite(Q).run(elements = [Q.t*Q[1,1]+Q[2], Q[1]+(1+Q.t)*Q[1,1]]) # long time (depends on previous)\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLP = Sym.hall_littlewood().P()\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQp = Sym.hall_littlewood().Qp()\n sage: s = Sym.schur(); p = Sym.power()\n sage: HLQ( HLP([2,1]) + HLP([3]) )\n (1/(t^2-2*t+1))*HLQ[2, 1] - (1/(t-1))*HLQ[3]\n sage: HLQ(HLQp([2])) # indirect doctest\n (t/(t^3-t^2-t+1))*HLQ[1, 1] - (1/(t-1))*HLQ[2]\n sage: HLQ(s([2]))\n (t/(t^3-t^2-t+1))*HLQ[1, 1] - (1/(t-1))*HLQ[2]\n sage: HLQ(p([2]))\n (1/(t^2-1))*HLQ[1, 1] - (1/(t-1))*HLQ[2]\n " HallLittlewood_generic.__init__(self, hall_littlewood) self._P = self._hall_littlewood.P() category = sage.categories.all.ModulesWithBasis(self.base_ring()) phi = self.module_morphism(diagonal=self._P._q_to_p_normalization, codomain=self._P, category=category) self._P.register_coercion(phi) self.register_coercion((~ phi)) def _p_to_q_normalization(self, m): "\n Returns the scalar coefficient on self(m) when converting from the\n `Q` basis to the `P` basis. Note that this assumes that ``m`` is a\n Partition object.\n\n Note: this is not used anymore!\n\n Returns the scalar coefficient that is used when converting from the\n `P` basis to the `Q` basis. Note that this assumes that ``m`` is a\n Partition object.\n\n INPUT:\n\n - ``self`` -- an instance of the Hall-Littlewood `P` basis\n - ``m`` -- a partition\n\n OUTPUT:\n\n - returns the coefficient equal to `P(m)/Q(m)`\n\n EXAMPLES::\n\n sage: Sym = SymmetricFunctions(FractionField(QQ['t']))\n sage: HLQ = Sym.hall_littlewood().Q()\n sage: HLQ._p_to_q_normalization(Partition([2,1]))\n 1/(t^2 - 2*t + 1)\n " t = self.t coeff = (1 / ((1 - t) ** len(m))) for i in m.to_exp(): for j in range(1, (i + 1)): coeff *= ((1 - t) / (1 - (t ** j))) return coeff