code stringlengths 17 6.64M |
|---|
class FreeCommutativeAdditiveSemigroup(UniqueRepresentation, Parent):
"\n An example of a commutative additive monoid: the free commutative monoid\n\n This class illustrates a minimal implementation of a commutative additive monoid.\n\n EXAMPLES::\n\n sage: S = CommutativeAdditiveSemigroups().example(); S\n An example of a commutative semigroup: the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n\n sage: S.category()\n Category of commutative additive semigroups\n\n This is the free semigroup generated by::\n\n sage: S.additive_semigroup_generators()\n Family (a, b, c, d)\n\n with product rule given by `a \\times b = a` for all `a, b`::\n\n sage: (a,b,c,d) = S.additive_semigroup_generators()\n\n We conclude by running systematic tests on this commutative monoid::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_additive_associativity() . . . pass\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n "
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
"\n The free commutative monoid\n\n INPUT:\n\n - ``alphabet`` -- a tuple of strings: the generators of the semigroup\n\n EXAMPLES::\n\n sage: M = CommutativeAdditiveSemigroups().example(alphabet=('a','b','c')); M\n An example of a commutative semigroup: the free commutative semigroup generated by ('a', 'b', 'c')\n\n TESTS::\n\n sage: TestSuite(M).run()\n "
self.alphabet = alphabet
Parent.__init__(self, category=CommutativeAdditiveSemigroups())
def _repr_(self):
'\n EXAMPLES::\n\n sage: M = CommutativeAdditiveSemigroups().example(alphabet=(\'a\',\'b\',\'c\'))\n sage: M._repr_()\n "An example of a commutative semigroup: the free commutative semigroup generated by (\'a\', \'b\', \'c\')"\n\n '
return ('An example of a commutative semigroup: the free commutative semigroup generated by %s' % (self.alphabet,))
def summation(self, x, y):
'\n Returns the product of ``x`` and ``y`` in the semigroup, as per\n :meth:`CommutativeAdditiveSemigroups.ParentMethods.summation`.\n\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: (a,b,c,d) = F.additive_semigroup_generators()\n sage: F.summation(a,b)\n a + b\n sage: (a+b) + (a+c)\n 2*a + b + c\n '
assert (x in self)
assert (y in self)
return self(((a, (x.value[a] + y.value[a])) for a in self.alphabet))
@cached_method
def additive_semigroup_generators(self):
'\n Returns the generators of the semigroup.\n\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: F.additive_semigroup_generators()\n Family (a, b, c, d)\n '
return Family([self(((a, 1),)) for a in self.alphabet])
def an_element(self):
'\n Returns an element of the semigroup.\n\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: F.an_element()\n a + 2*b + 3*c + 4*d\n '
return self(((a, (ord(a) - 96)) for a in self.alphabet))
class Element(ElementWrapper):
def __init__(self, parent, iterable):
"\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: x = F.element_class(F, (('a',4), ('b', 0), ('a', 2), ('c', 1), ('d', 5)))\n sage: x\n 2*a + c + 5*d\n sage: x.value\n {'a': 2, 'b': 0, 'c': 1, 'd': 5}\n sage: x.parent()\n An example of a commutative semigroup: the free commutative semigroup generated by ('a', 'b', 'c', 'd')\n\n Internally, elements are represented as dense dictionaries which\n associate to each generator of the monoid its multiplicity. In\n order to get an element, we wrap the dictionary into an element\n via :class:`ElementWrapper`::\n\n sage: x.value\n {'a': 2, 'b': 0, 'c': 1, 'd': 5}\n "
d = {a: 0 for a in parent.alphabet}
for (a, c) in iterable:
d[a] = c
ElementWrapper.__init__(self, parent, d)
def _repr_(self):
'\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: F.an_element() # indirect doctest\n a + 2*b + 3*c + 4*d\n\n sage: F(())\n 0\n '
d = self.value
result = ' + '.join(((('%s*%s' % (d[a], a)) if (d[a] != 1) else a) for a in sorted(d.keys()) if (d[a] != 0)))
return ('0' if (result == '') else result)
def __hash__(self):
"\n EXAMPLES::\n\n sage: F = CommutativeAdditiveSemigroups().example()\n sage: type(hash(F.an_element()))\n <... 'int'>\n "
return hash(tuple(self.value.items()))
|
class HighestWeightCrystalOfTypeA(UniqueRepresentation, Parent):
'\n An example of a crystal: the highest weight crystal of type `A_n`\n of highest weight `\\omega_1`.\n\n The purpose of this class is to provide a minimal template for\n implementing crystals. See\n :class:`~sage.combinat.crystals.letters.CrystalOfLetters` for a\n full featured and optimized implementation.\n\n EXAMPLES::\n\n sage: C = Crystals().example()\n sage: C\n Highest weight crystal of type A_3 of highest weight omega_1\n sage: C.category()\n Category of classical crystals\n\n The elements of this crystal are in the set `\\{1,\\ldots,n+1\\}`::\n\n sage: C.list()\n [1, 2, 3, 4]\n sage: C.module_generators[0]\n 1\n\n The crystal operators themselves correspond to the elementary\n transpositions::\n\n sage: b = C.module_generators[0]\n sage: b.f(1)\n 2\n sage: b.f(1).e(1) == b\n True\n\n Only the following basic operations are implemented:\n\n - :meth:`~sage.categories.crystals.Crystals.cartan_type` or an attribute _cartan_type\n - an attribute module_generators\n - :meth:`.Element.e`\n - :meth:`.Element.f`\n\n All the other usual crystal operations are inherited from the\n categories; for example::\n\n sage: C.cardinality()\n 4\n\n TESTS::\n\n sage: C = Crystals().example()\n sage: TestSuite(C).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n '
def __init__(self, n=3):
'\n EXAMPLES::\n\n sage: C = sage.categories.examples.crystals.HighestWeightCrystalOfTypeA(n=4)\n sage: C == Crystals().example(n=4)\n True\n '
Parent.__init__(self, category=ClassicalCrystals())
self.n = n
self._cartan_type = CartanType(['A', n])
self.module_generators = [self(1)]
def _repr_(self):
'\n EXAMPLES::\n\n sage: Crystals().example()\n Highest weight crystal of type A_3 of highest weight omega_1\n '
return ('Highest weight crystal of type A_%s of highest weight omega_1' % self.n)
_an_element_ = EnumeratedSets.ParentMethods._an_element_
class Element(ElementWrapper):
def e(self, i):
'\n Returns the action of `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = Crystals().example(4)\n sage: [[c,i,c.e(i)] for i in C.index_set() for c in C if c.e(i) is not None]\n [[2, 1, 1], [3, 2, 2], [4, 3, 3], [5, 4, 4]]\n '
assert (i in self.index_set())
if (self.value == (i + 1)):
return self.parent()((self.value - 1))
else:
return None
def f(self, i):
'\n Returns the action of `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = Crystals().example(4)\n sage: [[c,i,c.f(i)] for i in C.index_set() for c in C if c.f(i) is not None]\n [[1, 1, 2], [2, 2, 3], [3, 3, 4], [4, 4, 5]]\n '
assert (i in self.index_set())
if (self.value == i):
return self.parent()((self.value + 1))
else:
return None
|
class NaiveCrystal(UniqueRepresentation, Parent):
'\n This is an example of a "crystal" which does not come from any kind of\n representation, designed primarily to test the Stembridge local rules with.\n The crystal has vertices labeled 0 through 5, with 0 the highest weight.\n\n The code here could also possibly be generalized to create a class that\n automatically builds a crystal from an edge-colored digraph, if someone\n feels adventurous.\n\n Currently, only the methods :meth:`highest_weight_vector`, :meth:`e`, and :meth:`f` are\n guaranteed to work.\n\n EXAMPLES::\n\n sage: C = Crystals().example(choice=\'naive\')\n sage: C.highest_weight_vector()\n 0\n '
def __init__(self):
"\n EXAMPLES::\n\n sage: C = sage.categories.examples.crystals.NaiveCrystal()\n sage: C == Crystals().example(choice='naive')\n True\n "
Parent.__init__(self, category=ClassicalCrystals())
self.n = 2
self._cartan_type = CartanType(['A', 2])
self.G = DiGraph(5)
self.G.add_edges([[0, 1, 1], [1, 2, 1], [2, 3, 1], [3, 5, 1], [0, 4, 2], [4, 5, 2]])
self.module_generators = [self(0)]
def __repr__(self):
"\n EXAMPLES::\n\n sage: Crystals().example(choice='naive')\n A broken crystal, defined by digraph, of dimension five.\n "
return 'A broken crystal, defined by digraph, of dimension five.'
class Element(ElementWrapper):
def e(self, i):
"\n Returns the action of `e_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = Crystals().example(choice='naive')\n sage: [[c,i,c.e(i)] for i in C.index_set() for c in [C(j) for j in [0..5]] if c.e(i) is not None]\n [[1, 1, 0], [2, 1, 1], [3, 1, 2], [5, 1, 3], [4, 2, 0], [5, 2, 4]]\n "
assert (i in self.index_set())
for edge in self.parent().G.edges(sort=False):
if ((edge[1] == int(str(self))) and (edge[2] == i)):
return self.parent()(edge[0])
return None
def f(self, i):
"\n Returns the action of `f_i` on ``self``.\n\n EXAMPLES::\n\n sage: C = Crystals().example(choice='naive')\n sage: [[c,i,c.f(i)] for i in C.index_set() for c in [C(j) for j in [0..5]] if c.f(i) is not None]\n [[0, 1, 1], [1, 1, 2], [2, 1, 3], [3, 1, 5], [0, 2, 4], [4, 2, 5]]\n "
assert (i in self.index_set())
for edge in self.parent().G.edges_incident(int(str(self))):
if (edge[2] == i):
return self.parent()(edge[1])
return None
|
class Surface(UniqueRepresentation, Parent):
'\n An example of a CW complex: a (2-dimensional) surface.\n\n This class illustrates a minimal implementation of a CW complex.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example(); X\n An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2)\n\n sage: X.category()\n Category of finite finite dimensional CW complexes\n\n We conclude by running systematic tests on this manifold::\n\n sage: TestSuite(X).run()\n '
def __init__(self, bdy=(1, 2, 1, 2)):
'\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example((1, 2)); X\n An example of a CW complex: the surface given by the boundary map (1, 2)\n\n TESTS::\n\n sage: TestSuite(X).run()\n '
self._bdy = bdy
self._edges = frozenset(bdy)
Parent.__init__(self, category=CWComplexes().Finite())
def _repr_(self):
'\n TESTS::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: CWComplexes().example()\n An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2)\n '
return 'An example of a CW complex: the surface given by the boundary map {}'.format(self._bdy)
def cells(self):
'\n Return the cells of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: C = X.cells()\n sage: sorted((d, C[d]) for d in C.keys())\n [(0, (0-cell v,)),\n (1, (0-cell e1, 0-cell e2)),\n (2, (2-cell f,))]\n '
d = {0: (self.element_class(self, 0, 'v'),)}
d[1] = tuple([self.element_class(self, 0, ('e' + str(e))) for e in self._edges])
d[2] = (self.an_element(),)
return Family(d)
def an_element(self):
'\n Return an element of the CW complex, as per\n :meth:`Sets.ParentMethods.an_element`.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: X.an_element()\n 2-cell f\n '
return self.element_class(self, 2, 'f')
class Element(Element):
'\n A cell in a CW complex.\n '
def __init__(self, parent, dim, name):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: f = X.an_element()\n sage: TestSuite(f).run()\n '
Element.__init__(self, parent)
self._dim = dim
self._name = name
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: X.an_element()\n 2-cell f\n '
return '{}-cell {}'.format(self._dim, self._name)
def __eq__(self, other):
"\n Check equality.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: f = X.an_element()\n sage: f == X(2, 'f')\n True\n sage: e1 = X(1, 'e1')\n sage: e1 == f\n False\n "
return (isinstance(other, Surface.Element) and (self.parent() is other.parent()) and (self._dim == other._dim) and (self._name == other._name))
def dimension(self):
'\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.cw_complexes import CWComplexes\n sage: X = CWComplexes().example()\n sage: f = X.an_element()\n sage: f.dimension()\n 2\n '
return self._dim
|
class PositiveIntegerMonoid(UniqueRepresentation, Parent):
'\n\n An example of a facade parent: the positive integers viewed as a\n multiplicative monoid\n\n This class illustrates a minimal implementation of a facade parent\n which models a subset of a set.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n\n TESTS::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_one() . . . pass\n running ._test_pickling() . . . pass\n running ._test_prod() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
'\n EXAMPLES::\n\n sage: from sage.categories.examples.facade_sets import PositiveIntegerMonoid\n sage: S = PositiveIntegerMonoid(); S\n An example of facade set: the monoid of positive integers\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
Parent.__init__(self, facade=ZZ, category=Monoids())
def _repr_(self):
'\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example() # indirect doctest\n\n '
return 'An example of facade set: the monoid of positive integers'
def _element_constructor_(self, object):
'\n Construction of elements\n\n Since ``self`` is a strict subset of the parent it is a facade\n for, it is mandatory to override this method. This method\n indirectly influences membership testing (see\n :meth:`Parent.__contains__`).\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n sage: S(1)\n 1\n sage: S(int(1))\n 1\n sage: S(2/1)\n 2\n sage: (parent(S(1)) == ZZ, parent(S(int(1))) == ZZ, parent(S(2/1)))\n (True, True, Integer Ring)\n sage: S(1), S(int(1)), S(2/1)\n (1, 1, 2)\n sage: 1 in S\n True\n sage: 2/1 in S, int(1) in S\n (True, True)\n sage: -1 in S, 1/2 in S\n (False, False)\n '
object = ZZ(object)
if (object > ZZ(0)):
return object
else:
raise ValueError('%s should be positive')
|
class IntegersCompletion(UniqueRepresentation, Parent):
'\n An example of a facade parent: the set of integers completed with\n `+-\\infty`\n\n This class illustrates a minimal implementation of a facade parent\n that models the union of several other parents.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example("union"); S\n An example of a facade set: the integers completed by +-infinity\n\n TESTS::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
'\n EXAMPLES::\n\n sage: from sage.categories.examples.facade_sets import IntegersCompletion\n sage: S = IntegersCompletion(); S\n An example of a facade set: the integers completed by +-infinity\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
Parent.__init__(self, facade=(ZZ, FiniteEnumeratedSet([(- infinity), (+ infinity)])), category=Sets())
def _repr_(self):
'\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example() # indirect doctest\n '
return 'An example of a facade set: the integers completed by +-infinity'
|
class PBWBasisCrossProduct(CombinatorialFreeModule):
'\n This class illustrates an implementation of a filtered algebra\n with basis: the universal enveloping algebra of the Lie algebra\n of `\\RR^3` under the cross product.\n\n The Lie algebra is generated by `x,y,z` with brackets defined by\n `[x, y] = z`, `[y, z] = x`, and `[x, z] = -y`. The universal enveloping\n algebra has a (PBW) basis consisting of monomials `x^i y^j z^k`.\n Despite these monomials not commuting with each other, we\n nevertheless label them by the elements of the free abelian monoid\n on three generators.\n\n INPUT:\n\n - ``R`` -- base ring\n\n The implementation involves the following:\n\n - A set of algebra generators -- the set of generators `x,y,z`.\n\n - The index of the unit element -- the unit element in the monoid\n of monomials.\n\n - A product -- this is given on basis elements by using\n :meth:`product_on_basis`.\n\n - A degree function -- this is determined on the basis elements\n by using :meth:`degree_on_basis` which returns the sum of exponents\n of the monomial.\n '
def __init__(self, base_ring):
'\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: x,y,z = A.algebra_generators()\n sage: TestSuite(A).run(elements=[x*y+z])\n '
I = IndexedFreeAbelianMonoid(['x', 'y', 'z'], prefix='U')
CombinatorialFreeModule.__init__(self, base_ring, I, bracket=False, prefix='', sorting_key=self._sort_key, category=FilteredAlgebrasWithBasis(base_ring))
def _sort_key(self, x):
"\n Return the key used to sort the terms.\n\n INPUT:\n\n - ``x`` -- a basis index (here an element in a free Abelian monoid)\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: S = sorted(A.an_element().support()); S\n [1, U['x'], U['x']^2*U['y']^2*U['z']^3, U['y']]\n sage: [A._sort_key(m) for m in S]\n [(0, []), (-1, ['x']), (-7, ['x', 'x', 'y', 'y', 'z', 'z', 'z']),\n (-1, ['y'])]\n "
return ((- len(x)), x.to_word_list())
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Filtered().example()\n An example of a filtered algebra with basis:\n the universal enveloping algebra of\n Lie algebra of RR^3 with cross product over Rational Field\n '
return 'An example of a filtered algebra with basis: the universal enveloping algebra of Lie algebra of RR^3 with cross product over {}'.format(self.base_ring())
def algebra_generators(self):
"\n Return the algebra generators of ``self``.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: list(A.algebra_generators())\n [U['x'], U['y'], U['z']]\n "
G = self._indices.monoid_generators()
I = sorted(G.keys())
return Family(I, (lambda x: self.monomial(G[x])))
def one_basis(self):
'\n Return the index of the unit of ``self``.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: A.one_basis()\n 1\n '
return self._indices.one()
def degree_on_basis(self, m):
"\n The degree of the basis element of ``self`` labelled by ``m``.\n\n INPUT:\n\n - ``m`` -- an element of the free abelian monoid\n\n OUTPUT: an integer, the degree of the corresponding basis element\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: x = A.algebra_generators()['x']\n sage: A.degree_on_basis((x^4).leading_support())\n 4\n sage: a = A.an_element(); a\n U['x']^2*U['y']^2*U['z']^3 + 2*U['x'] + 3*U['y'] + 1\n sage: A.degree_on_basis(a.leading_support())\n 1\n sage: s = sorted(a.support(), key=str)[2]; s\n U['x']^2*U['y']^2*U['z']^3\n sage: A.degree_on_basis(s)\n 7\n "
return len(m)
def product_on_basis(self, s, t):
"\n Return the product of two basis elements indexed by ``s`` and ``t``.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: G = A.algebra_generators()\n sage: x,y,z = G['x'], G['y'], G['z']\n sage: A.product_on_basis(x.leading_support(), y.leading_support())\n U['x']*U['y']\n sage: y*x\n U['x']*U['y'] - U['z']\n sage: x*y*x\n U['x']^2*U['y'] - U['x']*U['z']\n sage: z*y*x\n U['x']*U['y']*U['z'] - U['x']^2 + U['y']^2 - U['z']^2\n "
if (len(s) == 0):
return self.monomial(t)
if (len(t) == 0):
return self.monomial(s)
if (s.trailing_support() <= t.leading_support()):
return self.monomial((s * t))
if (len(t) == 1):
if (len(s) == 1):
a = s.leading_support()
b = t.leading_support()
cur = self.monomial((s * t))
if (a <= b):
return cur
if (a == 'z'):
if (b == 'y'):
return (cur - self.monomial(self._indices.gen('x')))
return (cur + self.monomial(self._indices.gen('y')))
return (cur - self.monomial(self._indices.gen('z')))
cur = self.monomial(t)
for a in reversed(s.to_word_list()):
cur = (self.monomial(self._indices.gen(a)) * cur)
return cur
cur = self.monomial(s)
for a in t.to_word_list():
cur = (cur * self.monomial(self._indices.gen(a)))
return cur
|
class FilteredPartitionModule(CombinatorialFreeModule):
"\n This class illustrates an implementation of a filtered module\n with basis: the free module on the set of all partitions.\n\n INPUT:\n\n - ``R`` -- base ring\n\n The implementation involves the following:\n\n - A choice of how to represent elements. In this case, the basis\n elements are partitions. The algebra is constructed as a\n :class:`CombinatorialFreeModule\n <sage.combinat.free_module.CombinatorialFreeModule>` on the\n set of partitions, so it inherits all of the methods for such\n objects, and has operations like addition already defined.\n\n ::\n\n sage: A = ModulesWithBasis(QQ).Filtered().example() # needs sage.modules\n\n - If the algebra is called ``A``, then its basis function is\n stored as ``A.basis``. Thus the function can be used to\n find a basis for the degree `d` piece: essentially, just call\n ``A.basis(d)``. More precisely, call ``x`` for\n each ``x`` in ``A.basis(d)``.\n\n ::\n\n sage: [m for m in A.basis(4)] # needs sage.modules\n [P[4], P[3, 1], P[2, 2], P[2, 1, 1], P[1, 1, 1, 1]]\n\n - For dealing with basis elements: :meth:`degree_on_basis`, and\n :meth:`_repr_term`. The first of these defines the degree of any\n monomial, and then the :meth:`degree\n <FilteredModules.Element.degree>` method for elements --\n see the next item -- uses it to compute the degree for a linear\n combination of monomials. The last of these determines the\n print representation for monomials, which automatically produces\n the print representation for general elements.\n\n ::\n\n sage: A.degree_on_basis(Partition([4,3])) # needs sage.modules\n 7\n sage: A._repr_term(Partition([4,3])) # needs sage.modules\n 'P[4, 3]'\n\n - There is a class for elements, which inherits from\n :class:`IndexedFreeModuleElement\n <sage.modules.with_basis.indexed_element.IndexedFreeModuleElement>`.\n An element is determined by a dictionary whose keys are partitions and\n whose corresponding values are the coefficients. The class implements\n two things: an :meth:`is_homogeneous\n <FilteredModules.Element.is_homogeneous>` method and a\n :meth:`degree <FilteredModules.Element.degree>` method.\n\n ::\n\n sage: p = A.monomial(Partition([3,2,1])); p # needs sage.modules\n P[3, 2, 1]\n sage: p.is_homogeneous() # needs sage.modules\n True\n sage: p.degree() # needs sage.modules\n 6\n "
def __init__(self, base_ring):
'\n EXAMPLES::\n\n sage: A = ModulesWithBasis(QQ).Filtered().example(); A # needs sage.modules\n An example of a filtered module with basis: the free module on partitions over Rational Field\n sage: TestSuite(A).run() # needs sage.modules\n '
CombinatorialFreeModule.__init__(self, base_ring, Partitions(), category=FilteredModulesWithBasis(base_ring))
basis = FilteredModulesWithBasis.ParentMethods.__dict__['basis']
def degree_on_basis(self, t):
"\n The degree of the basis element indexed by the partition ``t``\n in this filtered module.\n\n INPUT:\n\n - ``t`` -- the index of an element of the basis of this module,\n i.e. a partition\n\n OUTPUT: an integer, the degree of the corresponding basis element\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = ModulesWithBasis(QQ).Filtered().example()\n sage: A.degree_on_basis(Partition((2,1)))\n 3\n sage: A.degree_on_basis(Partition((4,2,1,1,1,1)))\n 10\n sage: type(A.degree_on_basis(Partition((1,1))))\n <class 'sage.rings.integer.Integer'>\n "
return t.size()
def _repr_(self):
'\n Print representation of ``self``.\n\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).Filtered().example() # indirect doctest # needs sage.modules\n An example of a filtered module with basis: the free module on partitions over Rational Field\n '
return ('An example of a filtered module with basis: the free module on partitions over %s' % self.base_ring())
def _repr_term(self, t):
"\n Print representation for the basis element represented by the\n partition ``t``.\n\n This governs the behavior of the print representation of all elements\n of the algebra.\n\n EXAMPLES::\n\n sage: A = ModulesWithBasis(QQ).Filtered().example() # needs sage.modules\n sage: A._repr_term(Partition((4,2,1))) # needs sage.modules\n 'P[4, 2, 1]'\n "
return ('P' + t._repr_())
|
class DihedralGroup(UniqueRepresentation, Parent):
'\n An example of finite Coxeter group: the `n`-th dihedral group of order `2n`.\n\n The purpose of this class is to provide a minimal template for\n implementing finite Coxeter groups. See\n :class:`~sage.groups.perm_gps.permgroup_named.DihedralGroup` for a\n full featured and optimized implementation.\n\n EXAMPLES::\n\n sage: G = FiniteCoxeterGroups().example()\n\n This group is generated by two simple reflections `s_1` and `s_2`\n subject to the relation `(s_1s_2)^n = 1`::\n\n sage: G.simple_reflections()\n Finite family {1: (1,), 2: (2,)}\n\n sage: s1, s2 = G.simple_reflections()\n sage: (s1*s2)^5 == G.one()\n True\n\n An element is represented by its reduced word (a tuple of elements\n of `self.index_set()`)::\n\n sage: G.an_element()\n (1, 2)\n\n sage: list(G)\n [(),\n (1,),\n (2,),\n (1, 2),\n (2, 1),\n (1, 2, 1),\n (2, 1, 2),\n (1, 2, 1, 2),\n (2, 1, 2, 1),\n (1, 2, 1, 2, 1)]\n\n This reduced word is unique, except for the longest element where\n the chosen reduced word is `(1,2,1,2\\dots)`::\n\n sage: G.long_element()\n (1, 2, 1, 2, 1)\n\n TESTS::\n\n sage: TestSuite(G).run()\n\n sage: c = FiniteCoxeterGroups().example(3).cayley_graph()\n sage: c.edges(sort=True)\n [((), (1,), 1),\n ((), (2,), 2),\n ((1,), (), 1),\n ((1,), (1, 2), 2),\n ((1, 2), (1,), 2),\n ((1, 2), (1, 2, 1), 1),\n ((1, 2, 1), (1, 2), 1),\n ((1, 2, 1), (2, 1), 2),\n ((2,), (), 2),\n ((2,), (2, 1), 1),\n ((2, 1), (1, 2, 1), 2),\n ((2, 1), (2,), 1)]\n '
def __init__(self, n=5):
'\n Construct the `n`-th DihedralGroup of order `2 n`.\n\n INPUT:\n\n - `n` -- an integer with `n \\geq 2`\n\n EXAMPLES::\n\n sage: from sage.categories.examples.finite_coxeter_groups import DihedralGroup\n sage: DihedralGroup(3)\n The 3-th dihedral group of order 6\n '
assert (n >= 2)
Parent.__init__(self, category=FiniteCoxeterGroups())
self.n = n
def _repr_(self):
'\n EXAMPLES::\n\n sage: FiniteCoxeterGroups().example()\n The 5-th dihedral group of order 10\n sage: FiniteCoxeterGroups().example(6)\n The 6-th dihedral group of order 12\n '
return ('The %s-th dihedral group of order %s' % (self.n, (2 * self.n)))
def __contains__(self, x):
'\n Check in the element x is in the mathematical parent self.\n\n EXAMPLES::\n\n sage: D5 = FiniteCoxeterGroups().example()\n sage: D5.an_element() in D5\n True\n sage: 1 in D5\n False\n\n (also tested by :meth:`test_an_element` :meth:`test_some_elements`)\n '
from sage.structure.all import parent
return (parent(x) is self)
@cached_method
def one(self):
'\n Implements :meth:`Monoids.ParentMethods.one`.\n\n EXAMPLES::\n\n sage: D6 = FiniteCoxeterGroups().example(6)\n sage: D6.one()\n ()\n '
return self(())
def index_set(self):
'\n Implements :meth:`CoxeterGroups.ParentMethods.index_set`.\n\n EXAMPLES::\n\n sage: D4 = FiniteCoxeterGroups().example(4)\n sage: D4.index_set()\n (1, 2)\n '
return (1, 2)
def degrees(self):
'\n Return the degrees of ``self``.\n\n EXAMPLES::\n\n sage: FiniteCoxeterGroups().example(6).degrees()\n (2, 6)\n '
from sage.rings.integer_ring import ZZ
return (ZZ(2), ZZ(self.n))
def coxeter_matrix(self):
'\n Return the Coxeter matrix of ``self``.\n\n EXAMPLES::\n\n sage: FiniteCoxeterGroups().example(6).coxeter_matrix()\n [1 6]\n [6 1]\n '
return CoxeterMatrix([[1, self.n], [self.n, 1]])
class Element(ElementWrapper):
wrapped_class = tuple
__lt__ = ElementWrapper._lt_by_value
def has_right_descent(self, i, positive=False, side='right'):
'\n Implements :meth:`SemiGroups.ElementMethods.has_right_descent`.\n\n EXAMPLES::\n\n sage: D6 = FiniteCoxeterGroups().example(6)\n sage: s = D6.simple_reflections()\n sage: s[1].has_descent(1)\n True\n sage: s[1].has_descent(1)\n True\n sage: s[1].has_descent(2)\n False\n sage: D6.one().has_descent(1)\n False\n sage: D6.one().has_descent(2)\n False\n sage: D6.long_element().has_descent(1)\n True\n sage: D6.long_element().has_descent(2)\n True\n\n TESTS::\n\n sage: D6._test_has_descent()\n '
reduced_word = self.value
if (len(reduced_word) == self.parent().n):
return (not positive)
elif (len(reduced_word) == 0):
return positive
else:
return ((i == reduced_word[(0 if (side == 'left') else (- 1))]) == (not positive))
def apply_simple_reflection_right(self, i):
'\n Implements :meth:`CoxeterGroups.ElementMethods.apply_simple_reflection`.\n\n EXAMPLES::\n\n sage: D5 = FiniteCoxeterGroups().example(5)\n sage: [i^2 for i in D5] # indirect doctest\n [(), (), (), (1, 2, 1, 2), (2, 1, 2, 1), (), (), (2, 1), (1, 2), ()]\n sage: [i^5 for i in D5] # indirect doctest\n [(), (1,), (2,), (), (), (1, 2, 1), (2, 1, 2), (), (), (1, 2, 1, 2, 1)]\n '
from copy import copy
reduced_word = copy(self.value)
n = self.parent().n
if (len(reduced_word) == n):
if (((i == 1) and is_odd(n)) or ((i == 2) and is_even(n))):
return self.parent()(reduced_word[:(- 1)])
else:
return self.parent()(reduced_word[1:])
elif (((len(reduced_word) == (n - 1)) and (not self.has_descent(i))) and (reduced_word[0] == 2)):
return self.parent()(((1,) + reduced_word))
elif self.has_descent(i):
return self.parent()(reduced_word[:(- 1)])
else:
return self.parent()((reduced_word + (i,)))
|
class KroneckerQuiverPathAlgebra(CombinatorialFreeModule):
'\n An example of a finite dimensional algebra with basis: the path\n algebra of the Kronecker quiver.\n\n This class illustrates a minimal implementation of a finite\n dimensional algebra with basis. See\n :class:`sage.quivers.algebra.PathAlgebra` for a full-featured\n implementation of path algebras.\n '
def __init__(self, base_ring):
'\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: TestSuite(A).run()\n '
basis_keys = ['x', 'y', 'a', 'b']
self._nonzero_products = {'xx': 'x', 'xa': 'a', 'xb': 'b', 'yy': 'y', 'ay': 'a', 'by': 'b'}
CombinatorialFreeModule.__init__(self, base_ring, basis_keys, category=FiniteDimensionalAlgebrasWithBasis(base_ring))
def _repr_(self):
'\n EXAMPLES::\n\n sage: FiniteDimensionalAlgebrasWithBasis(QQ).example() # indirect doctest\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n '
return ('An example of a finite dimensional algebra with basis: the path algebra of the Kronecker quiver (containing the arrows a:x->y and b:x->y) over %s ' % self.base_ring())
def one(self):
'\n Return the unit of this algebra.\n\n .. SEEALSO:: :meth:`AlgebrasWithBasis.ParentMethods.one_basis`\n\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()\n sage: A.one()\n x + y\n '
return self.sum_of_monomials(['x', 'y'])
def product_on_basis(self, w1, w2):
'\n Return the product of the two basis elements indexed by ``w1`` and ``w2``.\n\n .. SEEALSO:: :meth:`AlgebrasWithBasis.ParentMethods.product_on_basis`.\n\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()\n\n Here is the multiplication table for the algebra::\n\n sage: matrix([[p*q for q in A.basis()] for p in A.basis()])\n [x 0 a b]\n [0 y 0 0]\n [0 a 0 0]\n [0 b 0 0]\n\n Here we take some products of linear combinations of basis elements::\n\n sage: x, y, a, b = A.basis()\n sage: a * (1-b)^2 * x\n 0\n sage: x*a + b*y\n a + b\n sage: x*x\n x\n sage: x*y\n 0\n sage: x*a*y\n a\n '
if ((w1 + w2) in self._nonzero_products):
return self.monomial(self._nonzero_products[(w1 + w2)])
else:
return self.zero()
@cached_method
def algebra_generators(self):
"\n Return algebra generators for this algebra.\n\n .. SEEALSO:: :meth:`Algebras.ParentMethods.algebra_generators`.\n\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: A.algebra_generators()\n Finite family {'x': x, 'y': y, 'a': a, 'b': b}\n "
return self.basis()
def _repr_term(self, p):
'\n This method customizes the string representation of the basis\n element indexed by ``p``.\n\n In this example, we just return the string representation of\n ``p`` itself.\n\n EXAMPLES::\n\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example()\n sage: A.one()\n x + y\n '
return str(p)
|
class AbelianLieAlgebra(Parent, UniqueRepresentation):
'\n An example of a finite dimensional Lie algebra with basis:\n the abelian Lie algebra.\n\n Let `R` be a commutative ring, and `M` an `R`-module. The\n *abelian Lie algebra* on `M` is the `R`-Lie algebra\n obtained by endowing `M` with the trivial Lie bracket\n (`[a, b] = 0` for all `a, b \\in M`).\n\n This class illustrates a minimal implementation of a finite dimensional\n Lie algebra with basis.\n\n INPUT:\n\n - ``R`` -- base ring\n\n - ``n`` -- (optional) a nonnegative integer (default: ``None``)\n\n - ``M`` -- an `R`-module (default: the free `R`-module of\n rank ``n``) to serve as the ground space for the Lie algebra\n\n - ``ambient`` -- (optional) a Lie algebra; if this is set,\n then the resulting Lie algebra is declared a Lie subalgebra\n of ``ambient``\n\n OUTPUT:\n\n The abelian Lie algebra on `M`.\n '
@staticmethod
def __classcall_private__(cls, R, n=None, M=None, ambient=None):
'\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: from sage.categories.examples.finite_dimensional_lie_algebras_with_basis import AbelianLieAlgebra\n sage: A1 = AbelianLieAlgebra(QQ, n=3)\n sage: A2 = AbelianLieAlgebra(QQ, M=FreeModule(QQ, 3))\n sage: A3 = AbelianLieAlgebra(QQ, 3, FreeModule(QQ, 3))\n sage: A1 is A2 and A2 is A3\n True\n\n sage: A1 = AbelianLieAlgebra(QQ, 2)\n sage: A2 = AbelianLieAlgebra(ZZ, 2)\n sage: A1 is A2\n False\n\n sage: A1 = AbelianLieAlgebra(QQ, 0)\n sage: A2 = AbelianLieAlgebra(QQ, 1)\n sage: A1 is A2\n False\n '
if (M is None):
M = FreeModule(R, n)
else:
M = M.change_ring(R)
n = M.dimension()
return super().__classcall__(cls, R, n=n, M=M, ambient=ambient)
def __init__(self, R, n=None, M=None, ambient=None):
'\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: TestSuite(L).run()\n '
self._M = M
cat = LieAlgebras(R).FiniteDimensional().WithBasis()
if (ambient is None):
ambient = self
else:
cat = cat.Subobjects()
self._ambient = ambient
Parent.__init__(self, base=R, category=cat)
def _repr_(self):
'\n EXAMPLES::\n\n sage: LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n An example of a finite dimensional Lie algebra with basis:\n the 3-dimensional abelian Lie algebra over Rational Field\n '
ret = 'An example of a finite dimensional Lie algebra with basis: the {}-dimensional abelian Lie algebra over {}'.format(self.dimension(), self.base_ring())
B = self._M.basis_matrix()
if (not B.is_one()):
ret += ' with basis matrix:\n{!r}'.format(B)
return ret
def _element_constructor_(self, x):
'\n Construct an element of ``self`` from ``x``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L(0)\n (0, 0, 0)\n sage: M = FreeModule(ZZ, 3)\n sage: L(M([1, -2, 2]))\n (1, -2, 2)\n sage: a,b,c = L.lie_algebra_generators()\n sage: X = L.subalgebra([a+b, 2*a+c])\n sage: x,y = X.basis()\n sage: L(x)\n (1, 0, 1/2)\n sage: L(x+y)\n (1, 1, 0)\n '
if isinstance(x, AbelianLieAlgebra.Element):
x = x.value
return self.element_class(self, self._M(x))
@cached_method
def zero(self):
'\n Return the zero element.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.zero()\n (0, 0, 0)\n '
return self.element_class(self, self._M.zero())
def basis_matrix(self):
'\n Return the basis matrix of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.basis_matrix()\n [1 0 0]\n [0 1 0]\n [0 0 1]\n '
return self._M.basis_matrix()
def ambient(self):
'\n Return the ambient Lie algebra of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: S = L.subalgebra([2*a+b, b + c])\n sage: S.ambient() == L\n True\n '
return self._ambient
def subalgebra(self, gens):
'\n Return the Lie subalgebra of ``self`` generated by the\n elements of the iterable ``gens``.\n\n This currently requires the ground ring `R` to be a field.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: L.subalgebra([2*a+b, b + c])\n An example of a finite dimensional Lie algebra with basis:\n the 2-dimensional abelian Lie algebra over Rational Field with\n basis matrix:\n [ 1 0 -1/2]\n [ 0 1 1]\n '
N = self._M.subspace([g.value for g in gens])
return AbelianLieAlgebra(self.base_ring(), M=N, ambient=self._ambient)
ideal = subalgebra
def is_ideal(self, A):
'\n Return if ``self`` is an ideal of the ambient space ``A``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: L.is_ideal(L)\n True\n sage: S1 = L.subalgebra([2*a+b, b + c])\n sage: S1.is_ideal(L)\n True\n sage: S2 = L.subalgebra([2*a+b])\n sage: S2.is_ideal(S1)\n True\n sage: S1.is_ideal(S2)\n False\n '
if (not isinstance(A, AbelianLieAlgebra)):
return super().is_ideal(A)
if ((A == self) or (A == self._ambient)):
return True
if (self._ambient != A._ambient):
return False
return self._M.is_submodule(A._M)
def basis(self):
'\n Return the basis of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.basis()\n Finite family {0: (1, 0, 0), 1: (0, 1, 0), 2: (0, 0, 1)}\n '
d = {i: self.element_class(self, b) for (i, b) in enumerate(self._M.basis())}
return Family(d)
lie_algebra_generators = basis
def gens(self):
'\n Return the generators of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.gens()\n ((1, 0, 0), (0, 1, 0), (0, 0, 1))\n '
return tuple(self._M.basis())
def module(self):
'\n Return an `R`-module which is isomorphic to the\n underlying `R`-module of ``self``.\n\n See\n :meth:`sage.categories.lie_algebras.LieAlgebras.module` for\n an explanation.\n\n In this particular example, this returns the module `M`\n that was used to construct ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.module()\n Vector space of dimension 3 over Rational Field\n\n sage: a, b, c = L.lie_algebra_generators()\n sage: S = L.subalgebra([2*a+b, b + c])\n sage: S.module()\n Vector space of degree 3 and dimension 2 over Rational Field\n Basis matrix:\n [ 1 0 -1/2]\n [ 0 1 1]\n '
return self._M
def from_vector(self, v, order=None):
'\n Return the element of ``self`` corresponding to the\n vector ``v`` in ``self.module()``.\n\n Implement this if you implement :meth:`module`; see the\n documentation of\n :meth:`sage.categories.lie_algebras.LieAlgebras.module`\n for how this is to be done.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: u = L.from_vector(vector(QQ, (1, 0, 0))); u\n (1, 0, 0)\n sage: parent(u) is L\n True\n '
return self.element_class(self, self._M(v))
class Element(BaseExample.Element):
def __iter__(self):
'\n Iterate over ``self`` by returning pairs ``(i, c)`` where ``i``\n is the index of the basis element and ``c`` is the corresponding\n coefficient.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: elt = 2*a - c\n sage: list(elt)\n [(0, 2), (2, -1)]\n '
zero = self.parent().base_ring().zero()
for (i, c) in self.value.items():
if (c != zero):
(yield (i, c))
def __getitem__(self, i):
'\n Redirect the ``__getitem__()`` to the wrapped element unless\n ``i`` is a basis index.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: elt = 2*a + b - c\n sage: elt[0]\n 2\n sage: elt[2]\n -1\n '
return self.value.__getitem__(i)
def _bracket_(self, y):
'\n Return the Lie bracket ``[self, y]``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: a.bracket(c)\n (0, 0, 0)\n sage: a.bracket(b).bracket(c)\n (0, 0, 0)\n '
return self.parent().zero()
def lift(self):
'\n Return the lift of ``self`` to the universal enveloping algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: elt = 2*a + 2*b + 3*c\n sage: elt.lift() # needs sage.combinat\n 2*b0 + 2*b1 + 3*b2\n '
UEA = self.parent().universal_enveloping_algebra()
gens = UEA.gens()
return UEA.sum(((c * gens[i]) for (i, c) in self.value.items()))
def to_vector(self, order=None, sparse=False):
'\n Return ``self`` as a vector in\n ``self.parent().module()``.\n\n See the docstring of the latter method for the meaning\n of this.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: elt = 2*a + 2*b + 3*c\n sage: elt.to_vector()\n (2, 2, 3)\n '
if sparse:
return self.value.sparse_vector()
return self.value
def monomial_coefficients(self, copy=True):
'\n Return the monomial coefficients of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: elt = 2*a + 2*b + 3*c\n sage: elt.monomial_coefficients()\n {0: 2, 1: 2, 2: 3}\n '
return self.value.monomial_coefficients(copy)
|
class Example(UniqueRepresentation, Parent):
'\n An example of a finite enumerated set: `\\{1,2,3\\}`\n\n This class provides a minimal implementation of a finite enumerated set.\n\n See :class:`~sage.sets.finite_enumerated_set.FiniteEnumeratedSet` for a\n full featured implementation.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.cardinality()\n 3\n sage: C.list()\n [1, 2, 3]\n sage: C.an_element()\n 1\n\n This checks that the different methods of the enumerated set `C`\n return consistent results::\n\n sage: TestSuite(C).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
'\n TESTS::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C\n An example of a finite enumerated set: {1,2,3}\n sage: C.category()\n Category of facade finite enumerated sets\n sage: TestSuite(C).run()\n '
self._set = [Integer(_) for _ in [1, 2, 3]]
Parent.__init__(self, facade=IntegerRing(), category=FiniteEnumeratedSets())
def _repr_(self):
'\n TESTS::\n\n sage: FiniteEnumeratedSets().example() # indirect doctest\n An example of a finite enumerated set: {1,2,3}\n '
return 'An example of a finite enumerated set: {1,2,3}'
def __contains__(self, o):
'\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: 1 in C\n True\n sage: 0 in C\n False\n '
return (o in self._set)
def __iter__(self):
'\n EXAMPLES::\n\n sage: list(FiniteEnumeratedSets().example()) # indirect doctest\n [1, 2, 3]\n\n '
return iter(self._set)
|
class IsomorphicObjectOfFiniteEnumeratedSet(UniqueRepresentation, Parent):
def __init__(self, ambient=Example()):
'\n TESTS::\n\n sage: C = FiniteEnumeratedSets().IsomorphicObjects().example()\n sage: C\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: C.category()\n Category of facade isomorphic objects of finite enumerated sets\n sage: TestSuite(C).run()\n '
self._ambient = ambient
Parent.__init__(self, facade=IntegerRing(), category=FiniteEnumeratedSets().IsomorphicObjects())
def ambient(self):
'\n Returns the ambient space for ``self``, as per\n :meth:`Sets.Subquotients.ParentMethods.ambient()\n <sage.categories.sets_cat.Sets.Subquotients.ParentMethods.ambient>`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().IsomorphicObjects().example(); C\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: C.ambient()\n An example of a finite enumerated set: {1,2,3}\n '
return self._ambient
def lift(self, x):
'\n INPUT:\n\n - ``x`` -- an element of ``self``\n\n Lifts ``x`` to the ambient space for ``self``, as per\n :meth:`Sets.Subquotients.ParentMethods.lift()\n <sage.categories.sets_cat.Sets.Subquotients.ParentMethods.lift>`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().IsomorphicObjects().example(); C\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: C.lift(9)\n 3\n '
return x.sqrt()
def retract(self, x):
'\n INPUT:\n\n - ``x`` -- an element of the ambient space for ``self``\n\n Retracts ``x`` from the ambient space to ``self``, as per\n :meth:`Sets.Subquotients.ParentMethods.retract()\n <sage.categories.sets_cat.Sets.Subquotients.ParentMethods.retract>`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().IsomorphicObjects().example(); C\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: C.retract(3)\n 9\n '
return (x ** 2)
def __contains__(self, x):
'\n Membership testing by checking whether the preimage by the\n bijection is in the ambient space.\n\n EXAMPLES::\n\n sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: list(A)\n [1, 4, 9]\n sage: 4 in A\n True\n sage: 3 in A\n False\n sage: None in A\n False\n\n TODO: devise a robust implementation, and move it up to\n ``FiniteEnumeratedSets.IsomorphicObjects``.\n '
try:
return (self.lift(x) in self.ambient())
except Exception:
return False
|
class IntegerModMonoid(UniqueRepresentation, Parent):
'\n An example of a finite monoid: the integers mod `n`\n\n This class illustrates a minimal implementation of a finite monoid.\n\n EXAMPLES::\n\n sage: S = FiniteMonoids().example(); S\n An example of a finite multiplicative monoid: the integers modulo 12\n\n sage: S.category()\n Category of finitely generated finite enumerated monoids\n\n We conclude by running systematic tests on this monoid::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_one() . . . pass\n running ._test_pickling() . . . pass\n running ._test_prod() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self, n=12):
'\n EXAMPLES::\n\n sage: M = FiniteMonoids().example(6); M\n An example of a finite multiplicative monoid: the integers modulo 6\n\n TESTS::\n\n sage: TestSuite(M).run()\n '
self.n = n
Parent.__init__(self, category=Monoids().Finite().FinitelyGenerated())
def _repr_(self):
"\n TESTS::\n\n sage: M = FiniteMonoids().example()\n sage: M._repr_()\n 'An example of a finite multiplicative monoid: the integers modulo 12'\n "
return ('An example of a finite multiplicative monoid: the integers modulo %s' % self.n)
def semigroup_generators(self):
'\n\n Returns a set of generators for ``self``, as per\n :meth:`Semigroups.ParentMethods.semigroup_generators`.\n Currently this returns all integers mod `n`, which is of\n course far from optimal!\n\n EXAMPLES::\n\n sage: M = FiniteMonoids().example()\n sage: M.semigroup_generators()\n Family (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)\n '
return Family(tuple((self(ZZ(i)) for i in range(self.n))))
@cached_method
def one(self):
'\n Return the one of the monoid, as per :meth:`Monoids.ParentMethods.one`.\n\n EXAMPLES::\n\n sage: M = FiniteMonoids().example()\n sage: M.one()\n 1\n\n '
return self(ZZ.one())
def product(self, x, y):
'\n Return the product of two elements `x` and `y` of the monoid, as\n per :meth:`Semigroups.ParentMethods.product`.\n\n EXAMPLES::\n\n sage: M = FiniteMonoids().example()\n sage: M.product(M(3), M(5))\n 3\n '
return self(((x.value * y.value) % self.n))
def an_element(self):
'\n Returns an element of the monoid, as per :meth:`Sets.ParentMethods.an_element`.\n\n EXAMPLES::\n\n sage: M = FiniteMonoids().example()\n sage: M.an_element()\n 6\n '
return self((ZZ(42) % self.n))
class Element(ElementWrapper):
wrapped_class = Integer
|
class LeftRegularBand(UniqueRepresentation, Parent):
'\n An example of a finite semigroup\n\n This class provides a minimal implementation of a finite semigroup.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(); S\n An example of a finite semigroup:\n the left regular band generated by (\'a\', \'b\', \'c\', \'d\')\n\n This is the semigroup generated by::\n\n sage: S.semigroup_generators()\n Family (\'a\', \'b\', \'c\', \'d\')\n\n such that `x^2 = x` and `x y x = xy` for any `x` and `y` in `S`::\n\n sage: S(\'dab\')\n \'dab\'\n sage: S(\'dab\') * S(\'acb\')\n \'dabc\'\n\n It follows that the elements of `S` are strings without\n repetitions over the alphabet `a`, `b`, `c`, `d`::\n\n sage: sorted(S.list())\n [\'a\', \'ab\', \'abc\', \'abcd\', \'abd\', \'abdc\', \'ac\', \'acb\', \'acbd\', \'acd\',\n \'acdb\', \'ad\', \'adb\', \'adbc\', \'adc\', \'adcb\', \'b\', \'ba\', \'bac\',\n \'bacd\', \'bad\', \'badc\', \'bc\', \'bca\', \'bcad\', \'bcd\', \'bcda\', \'bd\',\n \'bda\', \'bdac\', \'bdc\', \'bdca\', \'c\', \'ca\', \'cab\', \'cabd\', \'cad\',\n \'cadb\', \'cb\', \'cba\', \'cbad\', \'cbd\', \'cbda\', \'cd\', \'cda\', \'cdab\',\n \'cdb\', \'cdba\', \'d\', \'da\', \'dab\', \'dabc\', \'dac\', \'dacb\', \'db\',\n \'dba\', \'dbac\', \'dbc\', \'dbca\', \'dc\', \'dca\', \'dcab\', \'dcb\', \'dcba\']\n\n It also follows that there are finitely many of them::\n\n sage: S.cardinality()\n 64\n\n Indeed::\n\n sage: 4 * ( 1 + 3 * (1 + 2 * (1 + 1)))\n 64\n\n As expected, all the elements of `S` are idempotents::\n\n sage: all( x.is_idempotent() for x in S )\n True\n\n Now, let us look at the structure of the semigroup::\n\n sage: S = FiniteSemigroups().example(alphabet = (\'a\',\'b\',\'c\'))\n sage: S.cayley_graph(side="left", simple=True).plot() # needs sage.graphs sage.plot\n Graphics object consisting of 60 graphics primitives\n sage: S.j_transversal_of_idempotents() # random (arbitrary choice) # needs sage.graphs\n [\'acb\', \'ac\', \'ab\', \'bc\', \'a\', \'c\', \'b\']\n\n We conclude by running systematic tests on this semigroup::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
"\n A left regular band.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(); S\n An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')\n sage: S = FiniteSemigroups().example(alphabet=('x','y')); S\n An example of a finite semigroup: the left regular band generated by ('x', 'y')\n sage: TestSuite(S).run()\n "
self.alphabet = alphabet
Parent.__init__(self, category=Semigroups().Finite().FinitelyGenerated())
def _repr_(self):
'\n TESTS::\n\n sage: S = FiniteSemigroups().example()\n sage: S._repr_()\n "An example of a finite semigroup: the left regular band generated by (\'a\', \'b\', \'c\', \'d\')"\n '
return ('An example of a finite semigroup: the left regular band generated by %s' % (self.alphabet,))
def product(self, x, y):
"\n Returns the product of two elements of the semigroup.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: S('a') * S('b')\n 'ab'\n sage: S('a') * S('b') * S('a')\n 'ab'\n sage: S('a') * S('a')\n 'a'\n\n "
assert (x in self)
assert (y in self)
x = x.value
y = y.value
return self((x + ''.join((c for c in y if (c not in x)))))
@cached_method
def semigroup_generators(self):
"\n Returns the generators of the semigroup.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('x','y'))\n sage: S.semigroup_generators()\n Family ('x', 'y')\n\n "
return Family([self(i) for i in self.alphabet])
def an_element(self):
'\n Returns an element of the semigroup.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: S.an_element()\n \'cdab\'\n\n sage: S = FiniteSemigroups().example(("b"))\n sage: S.an_element()\n \'b\'\n '
return self(''.join((self.alphabet[2:] + self.alphabet[0:2])))
class Element(ElementWrapper):
wrapped_class = str
__lt__ = ElementWrapper._lt_by_value
|
class SymmetricGroup(UniqueRepresentation, Parent):
'\n An example of finite Weyl group: the symmetric group, with\n elements in list notation.\n\n The purpose of this class is to provide a minimal template for\n implementing finite Weyl groups. See\n :class:`~sage.groups.perm_gps.permgroup_named.SymmetricGroup` for\n a full featured and optimized implementation.\n\n EXAMPLES::\n\n sage: S = FiniteWeylGroups().example()\n sage: S\n The symmetric group on {0, ..., 3}\n sage: S.category()\n Category of finite irreducible Weyl groups\n\n The elements of this group are permutations of the set `\\{0,\\ldots,3\\}`::\n\n sage: S.one()\n (0, 1, 2, 3)\n sage: S.an_element()\n (1, 2, 3, 0)\n\n The group itself is generated by the elementary transpositions::\n\n sage: S.simple_reflections()\n Finite family {0: (1, 0, 2, 3), 1: (0, 2, 1, 3), 2: (0, 1, 3, 2)}\n\n Only the following basic operations are implemented:\n\n - :meth:`.one`\n - :meth:`.product`\n - :meth:`.simple_reflection`\n - :meth:`.cartan_type`\n - :meth:`.Element.has_right_descent`.\n\n All the other usual Weyl group operations are inherited from the\n categories::\n\n sage: S.cardinality()\n 24\n sage: S.long_element()\n (3, 2, 1, 0)\n sage: S.cayley_graph(side="left").plot() # needs sage.graphs sage.plot\n Graphics object consisting of 120 graphics primitives\n\n Alternatively, one could have implemented\n :meth:`sage.categories.coxeter_groups.CoxeterGroups.ElementMethods.apply_simple_reflection`\n instead of :meth:`.simple_reflection` and :meth:`.product`. See\n ``CoxeterGroups().example()``.\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
def __init__(self, n=4):
'\n EXAMPLES::\n\n sage: S = sage.categories.examples.finite_weyl_groups.SymmetricGroup(4)\n sage: S == FiniteWeylGroups().example(4)\n True\n '
Parent.__init__(self, category=FiniteWeylGroups().Irreducible())
self.n = n
def _repr_(self):
'\n EXAMPLES::\n\n sage: FiniteWeylGroups().example()\n The symmetric group on {0, ..., 3}\n\n '
return ('The symmetric group on {0, ..., %s}' % (self.n - 1))
@cached_method
def one(self):
'\n Implements :meth:`Monoids.ParentMethods.one`.\n\n EXAMPLES::\n\n sage: FiniteWeylGroups().example().one()\n (0, 1, 2, 3)\n '
return self(tuple(range(self.n)))
def index_set(self):
'\n Implements :meth:`CoxeterGroups.ParentMethods.index_set`.\n\n EXAMPLES::\n\n sage: FiniteWeylGroups().example().index_set()\n [0, 1, 2]\n '
return list(range((self.n - 1)))
def simple_reflection(self, i):
'\n Implement :meth:`CoxeterGroups.ParentMethods.simple_reflection`\n by returning the transposition `(i, i+1)`.\n\n EXAMPLES::\n\n sage: FiniteWeylGroups().example().simple_reflection(2)\n (0, 1, 3, 2)\n '
assert (i in self.index_set())
return self(((tuple(range(i)) + ((i + 1), i)) + tuple(range((i + 2), self.n))))
def cartan_type(self):
"\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: FiniteWeylGroups().example().cartan_type() # needs sage.modules\n ['A', 3] relabelled by {1: 0, 2: 1, 3: 2}\n "
from sage.combinat.root_system.cartan_type import CartanType
C = CartanType(['A', (self.n - 1)])
C = C.relabel((lambda i: (i - 1)))
return C
def product(self, x, y):
'\n Implements :meth:`Semigroups.ParentMethods.product`.\n\n EXAMPLES::\n\n sage: s = FiniteWeylGroups().example().simple_reflections()\n sage: s[1] * s[2]\n (0, 2, 3, 1)\n '
assert (x in self)
assert (y in self)
return self(tuple((x.value[i] for i in y.value)))
def degrees(self):
'\n Return the degrees of ``self``.\n\n EXAMPLES::\n\n sage: W = FiniteWeylGroups().example()\n sage: W.degrees()\n (2, 3, 4)\n '
from sage.rings.integer_ring import ZZ
return tuple((ZZ(i) for i in range(2, (self.n + 1))))
class Element(ElementWrapper):
def has_right_descent(self, i):
'\n Implements :meth:`CoxeterGroups.ElementMethods.has_right_descent`.\n\n EXAMPLES::\n\n sage: S = FiniteWeylGroups().example()\n sage: s = S.simple_reflections()\n sage: (s[1] * s[2]).has_descent(2)\n True\n sage: S._test_has_descent()\n '
return (self.value[i] > self.value[(i + 1)])
|
class GradedConnectedCombinatorialHopfAlgebraWithPrimitiveGenerator(CombinatorialFreeModule):
'\n This class illustrates an implementation of a graded Hopf algebra\n with basis that has one primitive generator of degree 1 and basis\n elements indexed by non-negative integers.\n\n This Hopf algebra example differs from what topologists refer to as\n a graded Hopf algebra because the twist operation in the tensor rule\n satisfies\n\n .. MATH::\n\n (\\mu \\otimes \\mu) \\circ (id \\otimes \\tau \\otimes id) \\circ\n (\\Delta \\otimes \\Delta) = \\Delta \\circ \\mu\n\n where `\\tau(x\\otimes y) = y\\otimes x`.\n\n '
def __init__(self, base_ring):
'\n EXAMPLES::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: TestSuite(H).run()\n\n '
CombinatorialFreeModule.__init__(self, base_ring, NonNegativeIntegers(), category=GradedHopfAlgebrasWithBasis(base_ring).Connected())
@cached_method
def one_basis(self):
'\n Returns 0, which index the unit of the Hopf algebra.\n\n OUTPUT:\n\n - the non-negative integer 0\n\n EXAMPLES::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.one_basis()\n 0\n sage: H.one()\n P0\n\n '
return self.basis().keys()(0)
def degree_on_basis(self, i):
'\n The degree of a non-negative integer is itself\n\n INPUT:\n\n - ``i`` -- a non-negative integer\n\n OUTPUT:\n\n - a non-negative integer\n\n TESTS::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.degree_on_basis(45)\n 45\n\n '
return i
def _repr_(self):
'\n Representation of the graded connected Hopf algebra\n\n EXAMPLES::\n\n sage: GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n An example of a graded connected Hopf algebra with basis over Rational Field\n\n '
return ('An example of a graded connected Hopf algebra with basis over %s' % self.base_ring())
def _repr_term(self, i):
"\n Representation for the basis element indexed by the integer ``i``.\n\n EXAMPLES::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H._repr_term(45)\n 'P45'\n\n "
return ('P' + repr(i))
def product_on_basis(self, i, j):
'\n The product of two basis elements.\n\n The product of elements of degree ``i`` and ``j`` is an element\n of degree ``i+j``.\n\n INPUT:\n\n - ``i``, ``j`` -- non-negative integers\n\n OUTPUT:\n\n - a basis element indexed by ``i+j``\n\n TESTS::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.monomial(4) * H.monomial(5)\n P9\n\n '
return self.monomial((i + j))
def coproduct_on_basis(self, i):
'\n The coproduct of a basis element.\n\n .. MATH::\n\n \\Delta(P_i) = \\sum_{j=0}^i P_{i-j} \\otimes P_j\n\n INPUT:\n\n - ``i`` -- a non-negative integer\n\n OUTPUT:\n\n - an element of the tensor square of ``self``\n\n TESTS::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.monomial(3).coproduct()\n P0 # P3 + 3*P1 # P2 + 3*P2 # P1 + P3 # P0\n '
return self.sum_of_terms(((((i - j), j), binomial(i, j)) for j in range((i + 1))))
|
class GradedPartitionModule(CombinatorialFreeModule):
"\n This class illustrates an implementation of a graded module\n with basis: the free module over partitions.\n\n INPUT:\n\n - ``R`` -- base ring\n\n The implementation involves the following:\n\n - A choice of how to represent elements. In this case, the basis\n elements are partitions. The algebra is constructed as a\n :class:`CombinatorialFreeModule\n <sage.combinat.free_module.CombinatorialFreeModule>` on the\n set of partitions, so it inherits all of the methods for such\n objects, and has operations like addition already defined.\n\n ::\n\n sage: A = GradedModulesWithBasis(QQ).example() # needs sage.modules\n\n - A basis function - this module is graded by the non-negative\n integers, so there is a function defined in this module,\n creatively called :func:`basis`, which takes an integer\n `d` as input and returns a family of partitions representing a basis\n for the algebra in degree `d`.\n\n ::\n\n sage: A.basis(2) # needs sage.modules\n Lazy family (Term map from Partitions to An example of a graded module with basis: the free module on partitions over Rational Field(i))_{i in Partitions of the integer 2}\n sage: A.basis(6)[Partition([3,2,1])] # needs sage.modules\n P[3, 2, 1]\n\n - If the algebra is called ``A``, then its basis function is\n stored as ``A.basis``. Thus the function can be used to\n find a basis for the degree `d` piece: essentially, just call\n ``A.basis(d)``. More precisely, call ``x`` for\n each ``x`` in ``A.basis(d)``.\n\n ::\n\n sage: [m for m in A.basis(4)] # needs sage.modules\n [P[4], P[3, 1], P[2, 2], P[2, 1, 1], P[1, 1, 1, 1]]\n\n - For dealing with basis elements: :meth:`degree_on_basis`, and\n :meth:`_repr_term`. The first of these defines the degree of any\n monomial, and then the :meth:`degree\n <GradedModules.Element.degree>` method for elements --\n see the next item -- uses it to compute the degree for a linear\n combination of monomials. The last of these determines the\n print representation for monomials, which automatically produces\n the print representation for general elements.\n\n ::\n\n sage: A.degree_on_basis(Partition([4,3])) # needs sage.modules\n 7\n sage: A._repr_term(Partition([4,3])) # needs sage.modules\n 'P[4, 3]'\n\n - There is a class for elements, which inherits from\n :class:`IndexedFreeModuleElement\n <sage.modules.with_basis.indexed_element.IndexedFreeModuleElement>`.\n An element is determined by a dictionary whose keys are partitions and\n whose corresponding values are the coefficients. The class implements\n two things: an :meth:`is_homogeneous\n <GradedModules.Element.is_homogeneous>` method and a\n :meth:`degree <GradedModules.Element.degree>` method.\n\n ::\n\n sage: p = A.monomial(Partition([3,2,1])); p # needs sage.modules\n P[3, 2, 1]\n sage: p.is_homogeneous() # needs sage.modules\n True\n sage: p.degree() # needs sage.modules\n 6\n "
def __init__(self, base_ring):
'\n EXAMPLES::\n\n sage: A = GradedModulesWithBasis(QQ).example(); A # needs sage.modules\n An example of a graded module with basis: the free module on partitions over Rational Field\n sage: TestSuite(A).run() # needs sage.modules\n '
CombinatorialFreeModule.__init__(self, base_ring, Partitions(), category=GradedModulesWithBasis(base_ring))
basis = FilteredModulesWithBasis.ParentMethods.__dict__['basis']
def degree_on_basis(self, t):
"\n The degree of the element determined by the partition ``t`` in\n this graded module.\n\n INPUT:\n\n - ``t`` -- the index of an element of the basis of this module,\n i.e. a partition\n\n OUTPUT: an integer, the degree of the corresponding basis element\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = GradedModulesWithBasis(QQ).example()\n sage: A.degree_on_basis(Partition((2,1)))\n 3\n sage: A.degree_on_basis(Partition((4,2,1,1,1,1)))\n 10\n sage: type(A.degree_on_basis(Partition((1,1))))\n <class 'sage.rings.integer.Integer'>\n "
return t.size()
def _repr_(self):
'\n Print representation\n\n EXAMPLES::\n\n sage: GradedModulesWithBasis(QQ).example() # indirect doctest # needs sage.modules\n An example of a graded module with basis: the free module on partitions over Rational Field\n '
return ('An example of a graded module with basis: the free module on partitions over %s' % self.base_ring())
def _repr_term(self, t):
"\n Print representation for the basis element represented by the\n partition ``t``.\n\n This governs the behavior of the print representation of all elements\n of the algebra.\n\n EXAMPLES::\n\n sage: A = GradedModulesWithBasis(QQ).example() # needs sage.modules\n sage: A._repr_term(Partition((4,2,1))) # needs sage.modules\n 'P[4, 2, 1]'\n "
return ('P' + t._repr_())
|
class Cycle(UniqueRepresentation, Parent):
'\n An example of a graph: the cycle of length `n`.\n\n This class illustrates a minimal implementation of a graph.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example(); C\n An example of a graph: the 5-cycle\n\n sage: C.category()\n Category of graphs\n\n We conclude by running systematic tests on this graph::\n\n sage: TestSuite(C).run()\n '
def __init__(self, n=5):
'\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example(6); C\n An example of a graph: the 6-cycle\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
self._n = n
Parent.__init__(self, category=Graphs())
def _repr_(self):
'\n TESTS::\n\n sage: from sage.categories.graphs import Graphs\n sage: Graphs().example()\n An example of a graph: the 5-cycle\n '
return 'An example of a graph: the {}-cycle'.format(self._n)
def an_element(self):
'\n Return an element of the graph, as per\n :meth:`Sets.ParentMethods.an_element`.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.an_element()\n 0\n '
return self(0)
def vertices(self):
'\n Return the vertices of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.vertices()\n [0, 1, 2, 3, 4]\n '
return [self(i) for i in range(self._n)]
def edges(self):
'\n Return the edges of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.edges()\n [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]\n '
return [self((i, ((i + 1) % self._n))) for i in range(self._n)]
class Element(ElementWrapper):
def dimension(self):
'\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: e = C.edges()[0]\n sage: e.dimension()\n 2\n sage: v = C.vertices()[0]\n sage: v.dimension()\n 1\n '
if isinstance(self.value, tuple):
return 2
return 1
|
class MyGroupAlgebra(CombinatorialFreeModule):
'\n An example of a Hopf algebra with basis: the group algebra of a group\n\n This class illustrates a minimal implementation of a Hopf algebra with basis.\n '
def __init__(self, R, G):
'\n EXAMPLES::\n\n sage: from sage.categories.examples.hopf_algebras_with_basis import MyGroupAlgebra\n sage: A = MyGroupAlgebra(QQ, DihedralGroup(6))\n sage: A.category()\n Category of finite dimensional Hopf algebras with basis over Rational Field\n sage: TestSuite(A).run()\n '
self._group = G
CombinatorialFreeModule.__init__(self, R, G, category=HopfAlgebrasWithBasis(R))
def _repr_(self):
'\n EXAMPLES::\n\n sage: HopfAlgebrasWithBasis(QQ).example() # indirect doctest\n An example of Hopf algebra with basis: the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n '
return ('An example of Hopf algebra with basis: the group algebra of the %s over %s' % (self._group, self.base_ring()))
@cached_method
def one_basis(self):
'\n Returns the one of the group, which index the one of this algebra,\n as per :meth:`AlgebrasWithBasis.ParentMethods.one_basis`.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: A.one_basis()\n ()\n sage: A.one()\n B[()]\n '
return self._group.one()
def product_on_basis(self, g1, g2):
'\n Product, on basis elements, as per\n :meth:`AlgebrasWithBasis.ParentMethods.product_on_basis`.\n\n The product of two basis elements is induced by the product of\n the corresponding elements of the group.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: (a, b) = A._group.gens()\n sage: a*b\n (1,2)\n sage: A.product_on_basis(a, b)\n B[(1,2)]\n '
return self.basis()[(g1 * g2)]
@cached_method
def algebra_generators(self):
'\n Return the generators of this algebra, as per :meth:`~.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators`.\n\n They correspond to the generators of the group.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis: the group algebra of the Dihedral group of order 6 as a permutation group over Rational Field\n sage: A.algebra_generators()\n Finite family {(1,2,3): B[(1,2,3)], (1,3): B[(1,3)]}\n '
return Family(self._group.gens(), self.monomial)
def coproduct_on_basis(self, g):
'\n Coproduct, on basis elements, as per :meth:`HopfAlgebrasWithBasis.ParentMethods.coproduct_on_basis`.\n\n The basis elements are group like: `\\Delta(g) = g \\otimes g`.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: (a, b) = A._group.gens()\n sage: A.coproduct_on_basis(a)\n B[(1,2,3)] # B[(1,2,3)]\n '
g = self.monomial(g)
return tensor([g, g])
def counit_on_basis(self, g):
'\n Counit, on basis elements, as per :meth:`HopfAlgebrasWithBasis.ParentMethods.counit_on_basis`.\n\n The counit on the basis elements is 1.\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: (a, b) = A._group.gens()\n sage: A.counit_on_basis(a)\n 1\n '
return self.base_ring().one()
def antipode_on_basis(self, g):
'\n Antipode, on basis elements, as per :meth:`HopfAlgebrasWithBasis.ParentMethods.antipode_on_basis`.\n\n It is given, on basis elements, by `\\nu(g) = g^{-1}`\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: (a, b) = A._group.gens()\n sage: A.antipode_on_basis(a)\n B[(1,3,2)]\n '
return self.monomial((~ g))
|
class NonNegativeIntegers(UniqueRepresentation, Parent):
"\n An example of infinite enumerated set: the non negative integers\n\n This class provides a minimal implementation of an infinite enumerated set.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN\n An example of an infinite enumerated set: the non negative integers\n sage: NN.cardinality()\n +Infinity\n sage: NN.list()\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n sage: NN.element_class\n <class 'sage.rings.integer.Integer'>\n sage: it = iter(NN)\n sage: [next(it), next(it), next(it), next(it), next(it)]\n [0, 1, 2, 3, 4]\n sage: x = next(it); type(x)\n <class 'sage.rings.integer.Integer'>\n sage: x.parent()\n Integer Ring\n sage: x+3\n 8\n sage: NN(15)\n 15\n sage: NN.first()\n 0\n\n This checks that the different methods of `NN` return consistent\n results::\n\n sage: TestSuite(NN).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n "
def __init__(self):
'\n TESTS::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN\n An example of an infinite enumerated set: the non negative integers\n sage: NN.category()\n Category of infinite enumerated sets\n sage: TestSuite(NN).run()\n '
Parent.__init__(self, category=InfiniteEnumeratedSets())
def _repr_(self):
'\n TESTS::\n\n sage: InfiniteEnumeratedSets().example() # indirect doctest\n An example of an infinite enumerated set: the non negative integers\n '
return 'An example of an infinite enumerated set: the non negative integers'
def __contains__(self, elt):
'\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: 1 in NN\n True\n sage: -1 in NN\n False\n '
return (Integer(elt) >= Integer(0))
def __iter__(self):
'\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: g = iter(NN)\n sage: next(g), next(g), next(g), next(g)\n (0, 1, 2, 3)\n '
i = Integer(0)
while True:
(yield self._element_constructor_(i))
i += 1
def __call__(self, elt):
'\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN(3) # indirect doctest\n 3\n sage: NN(3).parent()\n Integer Ring\n sage: NN(-1)\n Traceback (most recent call last):\n ...\n ValueError: Value -1 is not a non negative integer.\n '
if (elt in self):
return self._element_constructor_(elt)
raise ValueError(('Value %s is not a non negative integer.' % elt))
def an_element(self):
'\n EXAMPLES::\n\n sage: InfiniteEnumeratedSets().example().an_element()\n 42\n '
return self._element_constructor_(Integer(42))
def next(self, o):
'\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN.next(3)\n 4\n '
return self._element_constructor_((o + 1))
def _element_constructor_(self, i):
"\n The default implementation of _element_constructor_ assumes\n that the constructor of the element class takes the parent as\n parameter. This is not the case for ``Integer``, so we need to\n provide an implementation.\n\n\n TESTS::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: x = NN(42); x\n 42\n sage: type(x)\n <class 'sage.rings.integer.Integer'>\n sage: x.parent()\n Integer Ring\n "
return self.element_class(i)
Element = Integer
|
class LieAlgebraFromAssociative(Parent, UniqueRepresentation):
'\n An example of a Lie algebra: a Lie algebra generated by\n a set of elements of an associative algebra.\n\n This class illustrates a minimal implementation of a Lie algebra.\n\n Let `R` be a commutative ring, and `A` an associative\n `R`-algebra. The Lie algebra `A` (sometimes denoted `A^-`)\n is defined to be the `R`-module `A` with Lie bracket given by\n the commutator in `A`: that is, `[a, b] := ab - ba` for all\n `a, b \\in A`.\n\n What this class implements is not precisely `A^-`, however;\n it is the Lie subalgebra of `A^-` generated by the elements\n of the iterable ``gens``. This specific implementation does not\n provide a reasonable containment test (i.e., it does not allow\n you to check if a given element `a` of `A^-` belongs to this\n Lie subalgebra); it, however, allows computing inside it.\n\n INPUT:\n\n - ``gens`` -- a nonempty iterable consisting of elements of an\n associative algebra `A`\n\n OUTPUT:\n\n The Lie subalgebra of `A^-` generated by the elements of\n ``gens``\n\n EXAMPLES:\n\n We create a model of `\\mathfrak{sl}_2` using matrices::\n\n sage: gens = [matrix([[0,1],[0,0]]), matrix([[0,0],[1,0]]), matrix([[1,0],[0,-1]])]\n sage: for g in gens:\n ....: g.set_immutable()\n sage: L = LieAlgebras(QQ).example(gens)\n sage: e,f,h = L.lie_algebra_generators()\n sage: e.bracket(f) == h\n True\n sage: h.bracket(e) == 2*e\n True\n sage: h.bracket(f) == -2*f\n True\n '
@staticmethod
def __classcall_private__(cls, gens):
'\n Normalize input to ensure a unique representation.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: L1 = LieAlgebras(QQ).example()\n sage: gens = list(S3.algebra_generators())\n sage: L2 = LieAlgebras(QQ).example(gens)\n sage: L1 is L2\n True\n '
return super().__classcall__(cls, tuple(gens))
def __init__(self, gens):
'\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat\n sage: TestSuite(L).run() # needs sage.combinat\n '
if (not gens):
raise ValueError('need at least one generator')
self._gens = gens
self._A = gens[0].parent()
R = self._A.base_ring()
Parent.__init__(self, base=R, category=LieAlgebras(R))
def _repr_(self):
'\n EXAMPLES::\n\n sage: LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n An example of a Lie algebra: the Lie algebra from the associative algebra\n Symmetric group algebra of order 3 over Rational Field\n generated by ([2, 1, 3], [2, 3, 1])\n '
return 'An example of a Lie algebra: the Lie algebra from the associative algebra {} generated by {}'.format(self._A, self._gens)
def _element_constructor_(self, value):
'\n Return an element of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: S3 = SymmetricGroupAlgebra(ZZ, 3)\n sage: gens = S3.algebra_generators()\n sage: L = LieAlgebras(QQ).example()\n sage: L(3*gens[0] + gens[1])\n 3*[2, 1, 3] + [2, 3, 1]\n '
return self.element_class(self, self._A(value))
def zero(self):
'\n Return the element 0.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: L.zero() # needs sage.combinat sage.groups\n 0\n '
return self.element_class(self, self._A.zero())
def lie_algebra_generators(self):
'\n Return the generators of ``self`` as a Lie algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: L.lie_algebra_generators() # needs sage.combinat sage.groups\n Family ([2, 1, 3], [2, 3, 1])\n '
return Family([self.element_class(self, g) for g in self._gens])
class Element(ElementWrapper):
'\n Wrap an element as a Lie algebra element.\n '
def __eq__(self, rhs):
'\n Check equality.\n\n This check is rather restrictive: ``self`` and ``rhs`` are only\n revealed as equal if they are equal *and* have the same parent\n (or both are zero).\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: L = LieAlgebras(QQ).example()\n sage: x, y = L.lie_algebra_generators()\n sage: x == x\n True\n sage: x.bracket(y) == -y.bracket(x)\n True\n sage: x == y\n False\n sage: x.bracket(x) == L.zero()\n True\n sage: x.bracket(x) == 0\n True\n '
if (not isinstance(rhs, LieAlgebraFromAssociative.Element)):
return ((self.value == 0) and (rhs == 0))
return ((self.parent() == rhs.parent()) and (self.value == rhs.value))
def __ne__(self, rhs):
'\n Check not-equals.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: L = LieAlgebras(QQ).example()\n sage: x, y = L.lie_algebra_generators()\n sage: x != y\n True\n sage: x != 0\n True\n sage: x != x\n False\n sage: x.bracket(y) != -y.bracket(x)\n False\n '
return (not self.__eq__(rhs))
def __bool__(self) -> bool:
'\n Check non-zero.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: bool(sum(L.lie_algebra_generators())) # needs sage.combinat sage.groups\n True\n sage: bool(L.zero()) # needs sage.combinat sage.groups\n False\n '
return bool(self.value)
def _add_(self, rhs):
'\n Add ``self`` and ``rhs``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.groups\n sage: x + y # needs sage.combinat sage.groups\n [2, 1, 3] + [2, 3, 1]\n '
return self.__class__(self.parent(), (self.value + rhs.value))
def _sub_(self, rhs):
'\n Subtract ``self`` and ``rhs``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.groups\n sage: x - y # needs sage.combinat sage.groups\n [2, 1, 3] - [2, 3, 1]\n '
return self.__class__(self.parent(), (self.value - rhs.value))
def _acted_upon_(self, scalar, self_on_left=False):
'\n Return the action of a scalar on ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.groups\n sage: 3 * x # needs sage.combinat sage.groups\n 3*[2, 1, 3]\n '
if (hasattr(scalar, 'parent') and (scalar.parent() != self.base_ring())):
if self.base_ring().has_coerce_map_from(scalar.parent()):
scalar = self.base_ring()(scalar)
else:
return None
if self_on_left:
return self.__class__(self.parent(), (self.value * scalar))
return self.__class__(self.parent(), (scalar * self.value))
def __truediv__(self, x, self_on_left=False):
'\n Division by coefficients.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.groups\n sage: y / 4 # needs sage.combinat sage.groups\n 1/4*[2, 3, 1]\n '
if self_on_left:
return (self * (~ x))
return ((~ x) * self)
def __neg__(self):
'\n Return the negation of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.groups\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.groups\n sage: -x # needs sage.combinat sage.groups\n -[2, 1, 3]\n '
return self.__class__(self.parent(), (- self.value))
def __getitem__(self, i):
'\n Redirect the ``__getitem__()`` to the wrapped element.\n\n EXAMPLES::\n\n sage: gens = [matrix([[0,1],[0,0]]), matrix([[0,0],[1,0]]), matrix([[1,0],[0,-1]])]\n sage: for g in gens:\n ....: g.set_immutable()\n sage: L = LieAlgebras(QQ).example(gens)\n sage: e,f,h = L.lie_algebra_generators()\n sage: h[0,0]\n 1\n sage: h[1,1]\n -1\n sage: h[0,1]\n 0\n '
return self.value.__getitem__(i)
def _bracket_(self, rhs):
'\n Return the Lie bracket ``[self, rhs]``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: L = LieAlgebras(QQ).example()\n sage: x,y = L.lie_algebra_generators()\n sage: elt = 2*x - y\n sage: elt.bracket(elt)\n 0\n sage: elt.bracket(x)\n -[1, 3, 2] + [3, 2, 1]\n sage: elt2 = x.bracket(y) + x\n sage: elt.bracket(elt2)\n -2*[2, 1, 3] + 4*[2, 3, 1] - 4*[3, 1, 2] + 2*[3, 2, 1]\n '
return self.__class__(self.parent(), ((self.value * rhs.value) - (rhs.value * self.value)))
|
class AbelianLieAlgebra(CombinatorialFreeModule):
'\n An example of a Lie algebra: the abelian Lie algebra.\n\n This class illustrates a minimal implementation of a Lie algebra with\n a distinguished basis.\n '
def __init__(self, R, gens):
'\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: TestSuite(L).run()\n '
cat = LieAlgebras(R).WithBasis()
CombinatorialFreeModule.__init__(self, R, gens, category=cat)
def _construct_UEA(self):
'\n Construct the universal enveloping algebra of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: L._construct_UEA()\n Polynomial algebra with generators indexed by Partitions over Rational Field\n '
return IndexedPolynomialRing(self.base_ring(), self._indices)
def _repr_(self):
'\n EXAMPLES::\n\n sage: LieAlgebras(QQ).WithBasis().example()\n An example of a Lie algebra: the abelian Lie algebra on the\n generators indexed by Partitions over Rational Field\n '
return 'An example of a Lie algebra: the abelian Lie algebra on the generators indexed by {} over {}'.format(self.basis().keys(), self.base_ring())
def lie_algebra_generators(self):
'\n Return the generators of ``self`` as a Lie algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: L.lie_algebra_generators()\n Lazy family (Term map from Partitions to\n An example of a Lie algebra: the abelian Lie algebra on the\n generators indexed by Partitions over Rational\n Field(i))_{i in Partitions}\n '
return self.basis()
def bracket_on_basis(self, x, y):
'\n Return the Lie bracket on basis elements indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: L.bracket_on_basis(Partition([4,1]), Partition([2,2,1]))\n 0\n '
return self.zero()
class Element(CombinatorialFreeModule.Element):
def lift(self):
'\n Return the lift of ``self`` to the universal enveloping algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: elt = L.an_element()\n sage: elt.lift()\n 3*P[F[2]] + 2*P[F[1]] + 2*P[F[]]\n '
UEA = self.parent().universal_enveloping_algebra()
I = UEA._indices
return UEA.sum_of_terms(((I.gen(t), c) for (t, c) in self))
|
class IndexedPolynomialRing(CombinatorialFreeModule):
'\n Polynomial ring whose generators are indexed by an arbitrary set.\n\n .. TODO::\n\n Currently this is just used as the universal enveloping algebra\n for the example of the abelian Lie algebra. This should be\n factored out into a more complete class.\n '
def __init__(self, R, indices, **kwds):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: UEA = L.universal_enveloping_algebra()\n sage: TestSuite(UEA).run()\n '
if ('category' not in kwds):
kwds['category'] = Algebras(R).WithBasis()
if ('prefix' not in kwds):
kwds['prefix'] = 'P'
kwds['sorting_key'] = (lambda x: x.to_word_list())
kwds['sorting_reverse'] = True
M = IndexedFreeAbelianMonoid(indices, bracket='')
CombinatorialFreeModule.__init__(self, R, M, **kwds)
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: L.universal_enveloping_algebra()\n Polynomial algebra with generators indexed by Partitions over Rational Field\n '
return 'Polynomial algebra with generators indexed by {} over {}'.format(self._indices._indices, self.base_ring())
def one_basis(self):
'\n Return the index of element `1`.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: UEA = L.universal_enveloping_algebra()\n sage: UEA.one_basis()\n 1\n sage: UEA.one_basis().parent()\n Free abelian monoid indexed by Partitions\n '
return self._indices.one()
def product_on_basis(self, x, y):
'\n Return the product of the monomials indexed by ``x`` and ``y``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: UEA = L.universal_enveloping_algebra()\n sage: I = UEA._indices\n sage: UEA.product_on_basis(I.an_element(), I.an_element())\n P[F[]^4*F[1]^4*F[2]^6]\n '
return self.monomial((x * y))
def algebra_generators(self):
'\n Return the algebra generators of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: UEA = L.universal_enveloping_algebra()\n sage: UEA.algebra_generators()\n Lazy family (algebra generator map(i))_{i in Partitions}\n '
I = self._indices
return Family(I._indices, (lambda x: self.monomial(I.gen(x))), name='algebra generator map')
|
class FreeMagma(UniqueRepresentation, Parent):
"\n An example of magma.\n\n The purpose of this class is to provide a minimal template for\n implementing a magma.\n\n EXAMPLES::\n\n sage: M = Magmas().example(); M\n An example of a magma: the free magma generated by ('a', 'b', 'c', 'd')\n\n This is the free magma generated by::\n\n sage: M.magma_generators()\n Family ('a', 'b', 'c', 'd')\n sage: a, b, c, d = M.magma_generators()\n\n and with a non-associative product given by::\n\n sage: a * (b * c) * (d * a * b)\n '((a*(b*c))*((d*a)*b))'\n sage: a * (b * c) == (a * b) * c\n False\n\n TESTS::\n\n sage: TestSuite(M).run()\n "
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
"\n The free magma.\n\n INPUT:\n\n - ``alphabet`` -- a tuple of strings; the generators of the magma\n\n EXAMPLES::\n\n sage: from sage.categories.examples.magmas import FreeMagma\n sage: F = FreeMagma(('a', 'b', 'c')); F\n An example of a magma: the free magma generated by ('a', 'b', 'c')\n\n TESTS::\n\n sage: F == loads(dumps(F))\n True\n "
if any(((('(' in x) or (')' in x) or ('*' in x)) for x in alphabet)):
raise ValueError("alphabet must not contain characters '(', ')' or '*'")
self.alphabet = alphabet
Parent.__init__(self, category=Magmas().FinitelyGenerated())
def _repr_(self):
'\n EXAMPLES::\n\n sage: from sage.categories.examples.magmas import FreeMagma\n sage: FreeMagma((\'a\', \'b\', \'c\'))._repr_()\n "An example of a magma: the free magma generated by (\'a\', \'b\', \'c\')"\n '
return ('An example of a magma: the free magma generated by %s' % (self.alphabet,))
def product(self, x, y):
"\n Return the product of ``x`` and ``y`` in the magma, as per\n :meth:`Magmas.ParentMethods.product`.\n\n EXAMPLES::\n\n sage: F = Magmas().example()\n sage: F('a') * F.an_element()\n '(a*(((a*b)*c)*d))'\n "
assert (x in self)
assert (y in self)
return self(('(%s*%s)' % (x.value, y.value)))
@cached_method
def magma_generators(self):
"\n Return the generators of the magma.\n\n EXAMPLES::\n\n sage: F = Magmas().example()\n sage: F.magma_generators()\n Family ('a', 'b', 'c', 'd')\n "
return Family([self(i) for i in self.alphabet])
def an_element(self):
"\n Return an element of the magma.\n\n EXAMPLES::\n\n sage: F = Magmas().example()\n sage: F.an_element()\n '(((a*b)*c)*d)'\n "
gens = self.magma_generators()
x = gens.first()
for y in gens.iterator_range(1):
x *= y
return x
def _element_constructor_(self, x):
"\n Construct an element of this magma from the data ``x``.\n\n INPUT:\n\n - ``x`` -- a string\n\n EXAMPLES::\n\n sage: F = Magmas().example(); F\n An example of a magma: the free magma generated by ('a', 'b', 'c', 'd')\n sage: F._element_constructor_('a')\n 'a'\n sage: F._element_constructor_('(a*(b*c))')\n '(a*(b*c))'\n "
return self.element_class(self, x)
class Element(ElementWrapper):
'\n The class for elements of the free magma.\n '
wrapped_class = str
|
class Plane(UniqueRepresentation, Parent):
'\n An example of a manifold: the `n`-dimensional plane.\n\n This class illustrates a minimal implementation of a manifold.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: M = Manifolds(QQ).example(); M\n An example of a Rational Field manifold: the 3-dimensional plane\n\n sage: M.category()\n Category of manifolds over Rational Field\n\n We conclude by running systematic tests on this manifold::\n\n sage: TestSuite(M).run()\n '
def __init__(self, n=3, base_ring=None):
'\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: M = Manifolds(QQ).example(6); M\n An example of a Rational Field manifold: the 6-dimensional plane\n\n TESTS::\n\n sage: TestSuite(M).run()\n '
self._n = n
Parent.__init__(self, base=base_ring, category=Manifolds(base_ring))
def _repr_(self):
'\n TESTS::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(QQ).example()\n An example of a Rational Field manifold: the 3-dimensional plane\n '
return 'An example of a {} manifold: the {}-dimensional plane'.format(self.base_ring(), self._n)
def dimension(self):
'\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: M = Manifolds(QQ).example()\n sage: M.dimension()\n 3\n '
return self._n
def an_element(self):
'\n Return an element of the manifold, as per\n :meth:`Sets.ParentMethods.an_element`.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: M = Manifolds(QQ).example()\n sage: M.an_element()\n (0, 0, 0)\n '
zero = self.base_ring().zero()
return self(tuple(([zero] * self._n)))
Element = ElementWrapper
|
class FreeMonoid(FreeSemigroup):
"\n An example of a monoid: the free monoid\n\n This class illustrates a minimal implementation of a monoid. For a\n full featured implementation of free monoids, see :func:`FreeMonoid`.\n\n EXAMPLES::\n\n sage: S = Monoids().example(); S\n An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')\n\n sage: S.category()\n Category of monoids\n\n This is the free semigroup generated by::\n\n sage: S.semigroup_generators()\n Family ('a', 'b', 'c', 'd')\n\n with product rule given by concatenation of words::\n\n sage: S('dab') * S('acb')\n 'dabacb'\n\n and unit given by the empty word::\n\n sage: S.one()\n ''\n\n We conclude by running systematic tests on this monoid::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_one() . . . pass\n running ._test_pickling() . . . pass\n running ._test_prod() . . . pass\n running ._test_some_elements() . . . pass\n "
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
"\n The free monoid\n\n INPUT:\n\n - ``alphabet`` -- a tuple of strings: the generators of the monoid\n\n EXAMPLES::\n\n sage: M = Monoids().example(alphabet=('a','b','c')); M\n An example of a monoid: the free monoid generated by ('a', 'b', 'c')\n\n TESTS::\n\n sage: TestSuite(M).run()\n\n "
self.alphabet = alphabet
Parent.__init__(self, category=Monoids())
def _repr_(self):
'\n TESTS::\n\n sage: M = Monoids().example(alphabet=(\'a\',\'b\',\'c\'))\n sage: M._repr_()\n "An example of a monoid: the free monoid generated by (\'a\', \'b\', \'c\')"\n\n '
return ('An example of a monoid: the free monoid generated by %s' % (self.alphabet,))
@cached_method
def one(self):
"\n Returns the one of the monoid, as per :meth:`Monoids.ParentMethods.one`.\n\n EXAMPLES::\n\n sage: M = Monoids().example(); M\n An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')\n sage: M.one()\n ''\n\n "
return self('')
@cached_method
def monoid_generators(self):
"\n Return the generators of this monoid.\n\n EXAMPLES::\n\n sage: M = Monoids().example(); M\n An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')\n sage: M.monoid_generators()\n Finite family {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}\n sage: a,b,c,d = M.monoid_generators()\n sage: a*d*c*b\n 'adcb'\n "
return Family(self.alphabet, self)
class Element(ElementWrapper):
wrapped_class = str
|
class FiniteSetsOrderedByInclusion(UniqueRepresentation, Parent):
'\n An example of a poset: finite sets ordered by inclusion\n\n This class provides a minimal implementation of a poset\n\n EXAMPLES::\n\n sage: P = Posets().example(); P\n An example of a poset: sets ordered by inclusion\n\n We conclude by running systematic tests on this poset::\n\n sage: TestSuite(P).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
"\n EXAMPLES::\n\n sage: P = Posets().example(); P\n An example of a poset: sets ordered by inclusion\n sage: P.category()\n Category of posets\n sage: type(P)\n <class 'sage.categories.examples.posets.FiniteSetsOrderedByInclusion_with_category'>\n sage: TestSuite(P).run()\n "
Parent.__init__(self, category=Posets())
def _repr_(self):
"\n TESTS::\n\n sage: S = Posets().example()\n sage: S._repr_()\n 'An example of a poset: sets ordered by inclusion'\n "
return 'An example of a poset: sets ordered by inclusion'
def le(self, x, y):
'\n Returns whether `x` is a subset of `y`\n\n EXAMPLES::\n\n sage: P = Posets().example()\n sage: P.le( P(Set([1,3])), P(Set([1,2,3])) )\n True\n sage: P.le( P(Set([1,3])), P(Set([1,3])) )\n True\n sage: P.le( P(Set([1,2])), P(Set([1,3])) )\n False\n '
return x.value.issubset(y.value)
def an_element(self):
'\n Returns an element of this poset\n\n EXAMPLES::\n\n sage: B = Posets().example()\n sage: B.an_element()\n {1, 4, 6}\n '
return self(Set([1, 4, 6]))
class Element(ElementWrapper):
wrapped_class = Set_object_enumerated
|
class PositiveIntegersOrderedByDivisibilityFacade(UniqueRepresentation, Parent):
'\n An example of a facade poset: the positive integers ordered by divisibility\n\n This class provides a minimal implementation of a facade poset\n\n EXAMPLES::\n\n sage: P = Posets().example("facade"); P\n An example of a facade poset: the positive integers ordered by divisibility\n\n sage: P(5)\n 5\n sage: P(0)\n Traceback (most recent call last):\n ...\n ValueError: Can\'t coerce `0` in any parent `An example of a facade poset: the positive integers ordered by divisibility` is a facade for\n\n sage: 3 in P\n True\n sage: 0 in P\n False\n '
element_class = type(Set([]))
def __init__(self):
'\n EXAMPLES::\n\n sage: P = Posets().example("facade"); P\n An example of a facade poset: the positive integers ordered by divisibility\n sage: P.category()\n Category of facade posets\n sage: type(P)\n <class \'sage.categories.examples.posets.PositiveIntegersOrderedByDivisibilityFacade_with_category\'>\n sage: TestSuite(P).run()\n '
Parent.__init__(self, facade=(PositiveIntegers(),), category=Posets())
def _repr_(self):
'\n TESTS::\n\n sage: S = Posets().example("facade")\n sage: S._repr_()\n \'An example of a facade poset: the positive integers ordered by divisibility\'\n '
return 'An example of a facade poset: the positive integers ordered by divisibility'
def le(self, x, y):
'\n Returns whether `x` is divisible by `y`\n\n EXAMPLES::\n\n sage: P = Posets().example("facade")\n sage: P.le(3, 6)\n True\n sage: P.le(3, 3)\n True\n sage: P.le(3, 7)\n False\n '
return x.divides(y)
|
class LeftZeroSemigroup(UniqueRepresentation, Parent):
"\n An example of a semigroup.\n\n This class illustrates a minimal implementation of a semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().example(); S\n An example of a semigroup: the left zero semigroup\n\n This is the semigroup that contains all sorts of objects::\n\n sage: S.some_elements()\n [3, 42, 'a', 3.4, 'raton laveur']\n\n with product rule given by `a \\times b = a` for all `a, b`::\n\n sage: S('hello') * S('world')\n 'hello'\n sage: S(3)*S(1)*S(2)\n 3\n sage: S(3)^12312321312321\n 3\n\n TESTS::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n "
def __init__(self):
'\n The left zero semigroup\n\n EXAMPLES::\n\n sage: S = Semigroups().example(); S\n An example of a semigroup: the left zero semigroup\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
Parent.__init__(self, category=Semigroups())
def _repr_(self):
"\n\n EXAMPLES::\n\n sage: Semigroups().example()._repr_()\n 'An example of a semigroup: the left zero semigroup'\n\n "
return 'An example of a semigroup: the left zero semigroup'
def product(self, x, y):
"\n Returns the product of ``x`` and ``y`` in the semigroup, as per\n :meth:`Semigroups.ParentMethods.product`.\n\n EXAMPLES::\n\n sage: S = Semigroups().example()\n sage: S('hello') * S('world')\n 'hello'\n sage: S(3)*S(1)*S(2)\n 3\n\n "
assert (x in self)
assert (y in self)
return x
def an_element(self):
'\n Returns an element of the semigroup.\n\n EXAMPLES::\n\n sage: Semigroups().example().an_element()\n 42\n\n '
return self(42)
def some_elements(self):
"\n Returns a list of some elements of the semigroup.\n\n EXAMPLES::\n\n sage: Semigroups().example().some_elements()\n [3, 42, 'a', 3.4, 'raton laveur']\n\n "
return [self(i) for i in [3, 42, 'a', 3.4, 'raton laveur']]
class Element(ElementWrapper):
def is_idempotent(self):
'\n Trivial implementation of ``Semigroups.Element.is_idempotent``\n since all elements of this semigroup are idempotent!\n\n EXAMPLES::\n\n sage: S = Semigroups().example()\n sage: S.an_element().is_idempotent()\n True\n sage: S(17).is_idempotent()\n True\n\n '
return True
|
class FreeSemigroup(UniqueRepresentation, Parent):
'\n An example of semigroup.\n\n The purpose of this class is to provide a minimal template for\n implementing of a semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().example("free"); S\n An example of a semigroup: the free semigroup generated by (\'a\', \'b\', \'c\', \'d\')\n\n This is the free semigroup generated by::\n\n sage: S.semigroup_generators()\n Family (\'a\', \'b\', \'c\', \'d\')\n\n and with product given by concatenation::\n\n sage: S(\'dab\') * S(\'acb\')\n \'dabacb\'\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
"\n The free semigroup.\n\n INPUT:\n\n - ``alphabet`` -- a tuple of strings: the generators of the semigroup\n\n EXAMPLES::\n\n sage: from sage.categories.examples.semigroups import FreeSemigroup\n sage: F = FreeSemigroup(('a','b','c')); F\n An example of a semigroup: the free semigroup generated by ('a', 'b', 'c')\n\n TESTS::\n\n sage: F == loads(dumps(F))\n True\n "
self.alphabet = alphabet
Parent.__init__(self, category=Semigroups().FinitelyGenerated())
def _repr_(self):
'\n EXAMPLES::\n\n sage: from sage.categories.examples.semigroups import FreeSemigroup\n sage: FreeSemigroup((\'a\',\'b\',\'c\'))._repr_()\n "An example of a semigroup: the free semigroup generated by (\'a\', \'b\', \'c\')"\n\n '
return ('An example of a semigroup: the free semigroup generated by %s' % (self.alphabet,))
def product(self, x, y):
"\n Returns the product of ``x`` and ``y`` in the semigroup, as per\n :meth:`Semigroups.ParentMethods.product`.\n\n EXAMPLES::\n\n sage: F = Semigroups().example('free')\n sage: F.an_element() * F('a')^5\n 'abcdaaaaa'\n\n "
assert (x in self)
assert (y in self)
return self((x.value + y.value))
@cached_method
def semigroup_generators(self):
"\n Returns the generators of the semigroup.\n\n EXAMPLES::\n\n sage: F = Semigroups().example('free')\n sage: F.semigroup_generators()\n Family ('a', 'b', 'c', 'd')\n\n "
return Family([self(i) for i in self.alphabet])
def an_element(self):
"\n Returns an element of the semigroup.\n\n EXAMPLES::\n\n sage: F = Semigroups().example('free')\n sage: F.an_element()\n 'abcd'\n\n "
return self(''.join(self.alphabet))
def _element_constructor_(self, x):
"\n Construct an element of this semigroup from the data ``x``.\n\n INPUT:\n\n - ``x`` -- a string\n\n EXAMPLES::\n\n sage: F = Semigroups().example('free'); F\n An example of a semigroup: the free semigroup generated by ('a', 'b', 'c', 'd')\n sage: F._element_constructor_('a')\n 'a'\n sage: F._element_constructor_('bad')\n 'bad'\n\n TESTS::\n\n sage: F._element_constructor_('z')\n Traceback (most recent call last):\n ...\n assert a in self.alphabet\n AssertionError\n sage: bad = F._element_constructor_('bad'); bad\n 'bad'\n sage: bad in F\n True\n\n sage: S = Semigroups().Subquotients().example()\n sage: type(S._element_constructor_(17))\n <class 'sage.categories.examples.semigroups.QuotientOfLeftZeroSemigroup_with_category.element_class'>\n\n "
for a in x:
assert (a in self.alphabet)
return self.element_class(self, x)
class Element(ElementWrapper):
'\n The class for elements of the free semigroup.\n '
wrapped_class = str
|
class QuotientOfLeftZeroSemigroup(UniqueRepresentation, Parent):
'\n Example of a quotient semigroup\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example(); S\n An example of a (sub)quotient semigroup: a quotient of the left zero semigroup\n\n This is the quotient of::\n\n sage: S.ambient()\n An example of a semigroup: the left zero semigroup\n\n obtained by setting `x=42` for any `x\\geq 42`::\n\n sage: S(100)\n 42\n sage: S(100) == S(42)\n True\n\n The product is inherited from the ambient semigroup::\n\n sage: S(1)*S(2) == S(1)\n True\n\n TESTS::\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def _element_constructor_(self, x):
"\n Convert ``x`` into an element of this semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S._element_constructor_(17)\n 17\n\n TESTS::\n\n sage: S = Semigroups().Subquotients().example()\n sage: type(S._element_constructor_(17))\n <class 'sage.categories.examples.semigroups.QuotientOfLeftZeroSemigroup_with_category.element_class'>\n\n "
return self.retract(self.ambient()(x))
def __init__(self, category=None):
'\n This quotient of the left zero semigroup of integers obtained by\n setting `x=42` for any `x\\geq 42`.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example(); S\n An example of a (sub)quotient semigroup: a quotient of the left zero semigroup\n sage: S.ambient()\n An example of a semigroup: the left zero semigroup\n sage: S(100)\n 42\n sage: S(100) == S(42)\n True\n sage: S(1)*S(2) == S(1)\n True\n\n TESTS::\n\n sage: TestSuite(S).run()\n '
if (category is None):
category = Semigroups().Quotients()
Parent.__init__(self, category=category)
def _repr_(self):
"\n\n EXAMPLES::\n\n sage: Semigroups().Subquotients().example()._repr_()\n 'An example of a (sub)quotient semigroup: a quotient of the left zero semigroup'\n\n "
return 'An example of a (sub)quotient semigroup: a quotient of the left zero semigroup'
def ambient(self):
'\n Returns the ambient semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S.ambient()\n An example of a semigroup: the left zero semigroup\n\n '
return Semigroups().example()
def lift(self, x):
'\n Lift the element ``x`` into the ambient semigroup.\n\n INPUT:\n\n - ``x`` -- an element of ``self``.\n\n OUTPUT:\n\n - an element of ``self.ambient()``.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: x = S.an_element(); x\n 42\n sage: S.lift(x)\n 42\n sage: S.lift(x) in S.ambient()\n True\n sage: y = S.ambient()(100); y\n 100\n sage: S.lift(S(y))\n 42\n\n '
assert (x in self)
return x.value
def the_answer(self):
'\n Returns the Answer to Life, the Universe, and Everything as an\n element of this semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S.the_answer()\n 42\n\n '
return self.retract(self.ambient()(42))
def an_element(self):
'\n Returns an element of the semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S.an_element()\n 42\n\n '
return self.the_answer()
def some_elements(self):
'\n Returns a list of some elements of the semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S.some_elements()\n [1, 2, 3, 8, 42, 42]\n\n '
return [self.retract(self.ambient()(i)) for i in [1, 2, 3, 8, 42, 100]]
def retract(self, x):
'\n Returns the retract ``x`` onto an element of this semigroup.\n\n INPUT:\n\n - ``x`` -- an element of the ambient semigroup (``self.ambient()``).\n\n OUTPUT:\n\n - an element of ``self``.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: L = S.ambient()\n sage: S.retract(L(17))\n 17\n sage: S.retract(L(42))\n 42\n sage: S.retract(L(171))\n 42\n\n TESTS::\n\n sage: S.retract(L(171)) in S\n True\n\n '
from sage.rings.integer_ring import ZZ
assert ((x in self.ambient()) and (x.value in ZZ))
if (x.value > 42):
return self.the_answer()
return self.element_class(self, x)
class Element(ElementWrapper):
pass
|
class IncompleteSubquotientSemigroup(UniqueRepresentation, Parent):
def __init__(self, category=None):
'\n An incompletely implemented subquotient semigroup, for testing purposes\n\n EXAMPLES::\n\n sage: S = sage.categories.examples.semigroups.IncompleteSubquotientSemigroup()\n sage: S\n A subquotient of An example of a semigroup: the left zero semigroup\n\n TESTS::\n\n sage: S._test_not_implemented_methods()\n Traceback (most recent call last):\n ...\n AssertionError: Not implemented method: lift\n\n sage: TestSuite(S).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . fail\n Traceback (most recent call last):\n ...\n NotImplementedError: <abstract method retract at ...>\n ------------------------------------------------------------\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . fail\n Traceback (most recent call last):\n ...\n AssertionError: Not implemented method: lift\n ------------------------------------------------------------\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n The following tests failed: _test_associativity, _test_not_implemented_methods\n '
Parent.__init__(self, category=Semigroups().Subquotients().or_subcategory(category))
def ambient(self):
'\n Returns the ambient semigroup.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S.ambient()\n An example of a semigroup: the left zero semigroup\n\n '
return Semigroups().example()
class Element(ElementWrapper):
pass
|
class PrimeNumbers(UniqueRepresentation, Parent):
'\n An example of parent in the category of sets: the set of prime numbers.\n\n The elements are represented as plain integers in `\\ZZ` (facade\n implementation).\n\n This is a minimal implementations. For more advanced examples of\n implementations, see also::\n\n sage: P = Sets().example("facade")\n sage: P = Sets().example("inherits")\n sage: P = Sets().example("wrapper")\n\n EXAMPLES::\n\n sage: P = Sets().example()\n sage: P(12)\n Traceback (most recent call last):\n ...\n AssertionError: 12 is not a prime number\n sage: a = P.an_element()\n sage: a.parent()\n Integer Ring\n sage: x = P(13); x\n 13\n sage: type(x)\n <class \'sage.rings.integer.Integer\'>\n sage: x.parent()\n Integer Ring\n sage: 13 in P\n True\n sage: 12 in P\n False\n sage: y = x+1; y\n 14\n sage: type(y)\n <class \'sage.rings.integer.Integer\'>\n\n sage: TestSuite(P).run(verbose=True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
'\n TESTS::\n\n sage: from sage.categories.examples.sets_cat import PrimeNumbers\n sage: P = PrimeNumbers()\n sage: P.category()\n Category of facade sets\n sage: P is Sets().example()\n True\n '
Parent.__init__(self, facade=IntegerRing(), category=Sets())
def _repr_(self):
'\n TESTS::\n\n sage: Sets().example() # indirect doctest\n Set of prime numbers (basic implementation)\n '
return 'Set of prime numbers (basic implementation)'
def an_element(self):
'\n Implements :meth:`Sets.ParentMethods.an_element`.\n\n TESTS::\n\n sage: P = Sets().example()\n sage: x = P.an_element(); x\n 47\n sage: x.parent()\n Integer Ring\n '
return self(47)
def __contains__(self, p):
'\n TESTS::\n\n sage: P = Sets().example()\n sage: 13 in P\n True\n sage: 12 in P\n False\n '
return (isinstance(p, Integer) and p.is_prime())
def _element_constructor_(self, e):
'\n TESTS::\n\n sage: P = Sets().example()\n sage: P._element_constructor_(13) == 13\n True\n sage: P._element_constructor_(13).parent()\n Integer Ring\n sage: P._element_constructor_(14)\n Traceback (most recent call last):\n ...\n AssertionError: 14 is not a prime number\n '
p = self.element_class(e)
assert is_prime(p), ('%s is not a prime number' % p)
return p
element_class = Integer
|
class PrimeNumbers_Abstract(UniqueRepresentation, Parent):
'\n This class shows how to write a parent while keeping the choice of the\n datastructure for the children open. Different class with fixed\n datastructure will then be constructed by inheriting from\n :class:`PrimeNumbers_Abstract`.\n\n This is used by::\n\n sage: P = Sets().example("facade")\n sage: P = Sets().example("inherits")\n sage: P = Sets().example("wrapper")\n '
def __init__(self):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n '
Parent.__init__(self, category=Sets())
def _repr_(self):
'\n TESTS::\n\n sage: Sets().example("inherits") # indirect doctest\n Set of prime numbers\n '
return 'Set of prime numbers'
def an_element(self):
'\n Implements :meth:`Sets.ParentMethods.an_element`.\n\n TESTS::\n\n sage: P = Sets().example("inherits")\n sage: x = P.an_element(); x\n 47\n sage: x.parent()\n Set of prime numbers\n '
return self._from_integer_(47)
def _element_constructor_(self, i):
'\n Constructs an element of self from an integer, testing that\n this integer is indeed prime.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: P(13) # indirect doctest\n 13\n sage: P(42)\n Traceback (most recent call last):\n ...\n ValueError: 42 is not a prime number\n '
if (i in self):
return self._from_integer_(i)
else:
raise ValueError(('%s is not a prime number' % i))
@abstract_method
def _from_integer_(self, i):
'\n Fast construction of an element of self from an integer.\n\n No prime checking is performed. To be defined.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: P._from_integer_(13)\n 13\n sage: P._from_integer_(42) # Do not do that at home kids!\n 42\n sage: P(42)\n Traceback (most recent call last):\n ...\n ValueError: 42 is not a prime number\n '
def next(self, i):
'\n Return the next prime number.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: x = P.next(P.an_element()); x\n 53\n sage: x.parent()\n Set of prime numbers\n '
assert (i in self)
return self._from_integer_((Integer(i) + 1).next_prime())
def some_elements(self):
'\n Return some prime numbers.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: P.some_elements()\n [47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n '
x = self.an_element()
res = [x]
for i in range(10):
x = self.next(x)
res.append(x)
return res
class Element(Element):
def is_prime(self):
'\n Return whether ``self`` is a prime number.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: x = P.an_element()\n sage: P.an_element().is_prime()\n True\n '
return True
def next(self):
'\n Return the next prime number.\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: p = P.an_element(); p\n 47\n sage: p.next()\n 53\n\n .. NOTE::\n\n This method is not meant to implement the protocol iterator,\n and thus not subject to Python 2 vs Python 3 incompatibilities.\n '
return self.parent().next(self)
|
class PrimeNumbers_Inherits(PrimeNumbers_Abstract):
'\n An example of parent in the category of sets: the set of prime numbers.\n In this implementation, the element are stored as object of a new class\n which inherits from the class Integer (technically :class:`IntegerWrapper`).\n\n EXAMPLES::\n\n sage: P = Sets().example("inherits")\n sage: P\n Set of prime numbers\n sage: P(12)\n Traceback (most recent call last):\n ...\n ValueError: 12 is not a prime number\n sage: a = P.an_element()\n sage: a.parent()\n Set of prime numbers\n sage: x = P(13); x\n 13\n sage: x.is_prime()\n True\n sage: type(x)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class\'>\n sage: x.parent()\n Set of prime numbers\n sage: P(13) in P\n True\n sage: y = x+1; y\n 14\n sage: type(y)\n <class \'sage.rings.integer.Integer\'>\n sage: y.parent()\n Integer Ring\n sage: type(P(13)+P(17))\n <class \'sage.rings.integer.Integer\'>\n sage: type(P(2)+P(3))\n <class \'sage.rings.integer.Integer\'>\n\n sage: z = P.next(x); z\n 17\n sage: type(z)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class\'>\n sage: z.parent()\n Set of prime numbers\n\n sage: TestSuite(P).run(verbose=True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n\n See also::\n\n sage: P = Sets().example("facade")\n sage: P = Sets().example("inherits")\n sage: P = Sets().example("wrapper")\n '
def __init__(self):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n sage: type(P(13)+P(17))\n <class \'sage.rings.integer.Integer\'>\n sage: type(P(2)+P(3))\n <class \'sage.rings.integer.Integer\'>\n '
super().__init__()
self._populate_coercion_lists_(embedding=IntegerRing())
def __contains__(self, p):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n sage: 13 in P, P(13) in P\n (True, True)\n sage: 12 in P\n False\n '
return ((isinstance(p, self.element_class) and (p.parent() is self)) or (isinstance(p, Integer) and p.is_prime()))
def _from_integer_(self, p):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n sage: P._from_integer_(13)\n 13\n sage: P._from_integer_(42) # Don\'t do that at home kids!\n 42\n '
return self.element_class(self, p)
class Element(IntegerWrapper, PrimeNumbers_Abstract.Element):
def __init__(self, parent, p):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n sage: P(12)\n Traceback (most recent call last):\n ...\n ValueError: 12 is not a prime number\n sage: x = P(13); type(x)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class\'>\n sage: x.parent() is P\n True\n '
IntegerWrapper.__init__(self, parent, p)
|
class PrimeNumbers_Wrapper(PrimeNumbers_Abstract):
'\n An example of parent in the category of sets: the set of prime numbers.\n\n In this second alternative implementation, the prime integer are stored as\n a attribute of a sage object by inheriting from :class:`ElementWrapper`. In\n this case we need to ensure conversion and coercion from this parent and\n its element to ``ZZ`` and ``Integer``.\n\n EXAMPLES::\n\n sage: P = Sets().example("wrapper")\n sage: P(12)\n Traceback (most recent call last):\n ...\n ValueError: 12 is not a prime number\n sage: a = P.an_element()\n sage: a.parent()\n Set of prime numbers (wrapper implementation)\n sage: x = P(13); x\n 13\n sage: type(x)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Wrapper_with_category.element_class\'>\n sage: x.parent()\n Set of prime numbers (wrapper implementation)\n sage: 13 in P\n True\n sage: 12 in P\n False\n sage: y = x+1; y\n 14\n sage: type(y)\n <class \'sage.rings.integer.Integer\'>\n\n sage: z = P.next(x); z\n 17\n sage: type(z)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Wrapper_with_category.element_class\'>\n sage: z.parent()\n Set of prime numbers (wrapper implementation)\n\n TESTS::\n\n sage: TestSuite(P).run()\n '
def __init__(self):
'\n TESTS::\n\n sage: P = Sets().example("wrapper")\n sage: P.category()\n Category of sets\n sage: P(13) == 13\n True\n sage: ZZ(P(13)) == 13\n True\n sage: P(13) + 1 == 14\n True\n '
Parent.__init__(self, category=Sets())
from sage.rings.integer_ring import IntegerRing
from sage.categories.homset import Hom
self.mor = Hom(self, IntegerRing())((lambda z: z.value))
self._populate_coercion_lists_(embedding=self.mor)
def _repr_(self):
'\n TESTS::\n\n sage: Sets().example("wrapper") # indirect doctest\n Set of prime numbers (wrapper implementation)\n '
return 'Set of prime numbers (wrapper implementation)'
def __contains__(self, p):
'\n TESTS::\n\n sage: P = Sets().example("wrapper")\n sage: 13 in P\n True\n sage: 12 in P\n False\n '
return ((isinstance(p, self.element_class) and (p.parent() == self)) or (isinstance(p, Integer) and p.is_prime()))
def _from_integer_(self, e):
'\n TESTS::\n\n sage: P = Sets().example("wrapper")\n sage: P._from_integer_(13).parent()\n Set of prime numbers (wrapper implementation)\n sage: P._from_integer_(14) # Don\'t do that at home kids!\n 14\n sage: P._element_constructor_(14)\n Traceback (most recent call last):\n ...\n ValueError: 14 is not a prime number\n '
return self.element_class(self, Integer(e))
from sage.structure.element_wrapper import ElementWrapper
class Element(ElementWrapper, PrimeNumbers_Abstract.Element):
def _integer_(self, IntRing):
'\n Convert to an integer.\n\n TESTS::\n\n sage: P = Sets().example("wrapper")\n sage: x = P.an_element()\n sage: Integer(x) # indirect doctest\n 47\n '
return IntRing(self.value)
|
class PrimeNumbers_Facade(PrimeNumbers_Abstract):
'\n An example of parent in the category of sets: the set of prime numbers.\n\n In this alternative implementation, the elements are represented\n as plain integers in `\\ZZ` (facade implementation).\n\n EXAMPLES::\n\n sage: P = Sets().example("facade")\n sage: P(12)\n Traceback (most recent call last):\n ...\n ValueError: 12 is not a prime number\n sage: a = P.an_element()\n sage: a.parent()\n Integer Ring\n sage: x = P(13); x\n 13\n sage: type(x)\n <class \'sage.rings.integer.Integer\'>\n sage: x.parent()\n Integer Ring\n sage: 13 in P\n True\n sage: 12 in P\n False\n sage: y = x+1; y\n 14\n sage: type(y)\n <class \'sage.rings.integer.Integer\'>\n\n sage: z = P.next(x); z\n 17\n sage: type(z)\n <class \'sage.rings.integer.Integer\'>\n sage: z.parent()\n Integer Ring\n\n The disadvantage of this implementation is that the elements do not know\n that they are prime, so that prime testing is slow::\n\n sage: pf = Sets().example("facade").an_element()\n sage: timeit("pf.is_prime()") # random\n 625 loops, best of 3: 4.1 us per loop\n\n compared to the other implementations where prime testing is only done if\n needed during the construction of the element, and later on the elements\n "know" that they are prime::\n\n sage: pw = Sets().example("wrapper").an_element()\n sage: timeit("pw.is_prime()") # random\n 625 loops, best of 3: 859 ns per loop\n\n sage: pi = Sets().example("inherits").an_element()\n sage: timeit("pw.is_prime()") # random\n 625 loops, best of 3: 854 ns per loop\n\n Note also that the ``next`` method for the elements does not exist::\n\n sage: pf.next()\n Traceback (most recent call last):\n ...\n AttributeError: \'sage.rings.integer.Integer\' object has no attribute \'next\'...\n\n unlike in the other implementations::\n\n sage: pw.next()\n 53\n sage: pi.next()\n 53\n\n TESTS::\n\n sage: TestSuite(P).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_nonzero_equal() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n '
def __init__(self):
'\n TESTS::\n\n sage: P = Sets().example("inherits")\n '
Parent.__init__(self, facade=IntegerRing(), category=Sets())
def _repr_(self):
'\n TESTS::\n\n sage: Sets().example("facade") # indirect doctest\n Set of prime numbers (facade implementation)\n '
return 'Set of prime numbers (facade implementation)'
def __contains__(self, p):
'\n TESTS::\n\n sage: P = Sets().example("facade")\n sage: 13 in P\n True\n sage: 12 in P\n False\n '
return (isinstance(p, Integer) and p.is_prime())
def _from_integer_(self, e):
'\n TESTS::\n\n sage: P = Sets().example("facade")\n sage: P._from_integer_(13).parent()\n Integer Ring\n sage: P._from_integer_(14) # Don\'t do that at home kids!\n 14\n sage: P._element_constructor_(14)\n Traceback (most recent call last):\n ...\n ValueError: 14 is not a prime number\n '
return self.element_class(e)
element_class = Integer
|
class NonNegativeIntegers(UniqueRepresentation, Parent):
'\n Non negative integers graded by themselves.\n\n EXAMPLES::\n\n sage: E = SetsWithGrading().example(); E\n Non negative integers\n sage: E in Sets().Infinite()\n True\n sage: E.graded_component(0)\n {0}\n sage: E.graded_component(100)\n {100}\n '
def __init__(self):
'\n TESTS::\n\n sage: TestSuite(SetsWithGrading().example()).run()\n '
Parent.__init__(self, category=SetsWithGrading().Infinite(), facade=IntegerRing())
def an_element(self):
'\n Return 0.\n\n EXAMPLES::\n\n sage: SetsWithGrading().example().an_element()\n 0\n '
return 0
def _repr_(self):
'\n TESTS::\n\n sage: SetsWithGrading().example() # indirect example\n Non negative integers\n '
return 'Non negative integers'
def graded_component(self, grade):
'\n Return the component with grade ``grade``.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example()\n sage: N.graded_component(65)\n {65}\n '
return FiniteEnumeratedSet([grade])
def grading(self, elt):
'\n Return the grade of ``elt``.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example()\n sage: N.grading(10)\n 10\n '
return elt
def generating_series(self, var='z'):
"\n Return `1 / (1-z)`.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example(); N\n Non negative integers\n sage: f = N.generating_series(); f\n 1/(-z + 1)\n sage: LaurentSeriesRing(ZZ,'z')(f)\n 1 + z + z^2 + z^3 + z^4 + z^5 + z^6 + z^7 + z^8 + z^9 + z^10 + z^11 + z^12 + z^13 + z^14 + z^15 + z^16 + z^17 + z^18 + z^19 + O(z^20)\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.integer import Integer
R = PolynomialRing(IntegerRing(), var)
z = R.gen()
return (Integer(1) / (Integer(1) - z))
|
class SubsetAlgebra(UniqueRepresentation, Parent):
'\n An example of parent endowed with several realizations\n\n We consider an algebra `A(S)` whose bases are indexed by the\n subsets `s` of a given set `S`. We consider three natural basis of\n this algebra: ``F``, ``In``, and ``Out``. In the first basis, the\n product is given by the union of the indexing sets. That is, for any\n `s, t\\subset S`\n\n .. MATH::\n\n F_s F_t = F_{s\\cup t}\n\n The ``In`` basis and ``Out`` basis are defined respectively by:\n\n .. MATH::\n\n In_s = \\sum_{t\\subset s} F_t\n \\qquad\\text{and}\\qquad\n F_s = \\sum_{t\\supset s} Out_t\n\n Each such basis gives a realization of `A`, where the elements are\n represented by their expansion in this basis.\n\n This parent, and its code, demonstrate how to implement this\n algebra and its three realizations, with coercions and mixed\n arithmetic between them.\n\n .. SEEALSO::\n\n - :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`\n - the `Implementing Algebraic Structures\n <../../../../../thematic_tutorials/tutorial-implementing-algebraic-structures>`_\n thematic tutorial.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.base_ring()\n Rational Field\n\n The three bases of ``A``::\n\n sage: F = A.F() ; F\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: In = A.In() ; In\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: Out = A.Out(); Out\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n\n One can quickly define all the bases using the following shortcut::\n\n sage: A.inject_shorthands()\n Defining F as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n Defining In as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the In basis\n Defining Out as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n\n Accessing the basis elements is done with :meth:`basis()` method::\n\n sage: F.basis().list()\n [F[{}], F[{1}], F[{2}], F[{3}], F[{1, 2}], F[{1, 3}], F[{2, 3}], F[{1, 2, 3}]]\n\n To access a particular basis element, you can use the :meth:`from_set`\n method::\n\n sage: F.from_set(2,3)\n F[{2, 3}]\n sage: In.from_set(1,3)\n In[{1, 3}]\n\n or as a convenient shorthand, one can use the following notation::\n\n sage: F[2,3]\n F[{2, 3}]\n sage: In[1,3]\n In[{1, 3}]\n\n Some conversions::\n\n sage: F(In[2,3])\n F[{}] + F[{2}] + F[{3}] + F[{2, 3}]\n sage: In(F[2,3])\n In[{}] - In[{2}] - In[{3}] + In[{2, 3}]\n\n sage: Out(F[3])\n Out[{3}] + Out[{1, 3}] + Out[{2, 3}] + Out[{1, 2, 3}]\n sage: F(Out[3])\n F[{3}] - F[{1, 3}] - F[{2, 3}] + F[{1, 2, 3}]\n\n sage: Out(In[2,3])\n Out[{}] + Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}] + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}]\n\n We can now mix expressions::\n\n sage: (1 + Out[1]) * In[2,3]\n Out[{}] + 2*Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}] + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}]\n\n '
def __init__(self, R, S):
"\n EXAMPLES::\n\n sage: from sage.categories.examples.with_realizations import SubsetAlgebra\n sage: A = SubsetAlgebra(QQ, Set((1,2,3))); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: Sets().WithRealizations().example() is A\n True\n sage: TestSuite(A).run()\n\n TESTS::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: F, In, Out = A.realizations()\n sage: type(F.coerce_map_from(In))\n <class 'sage.modules.with_basis.morphism.TriangularModuleMorphismByLinearity_with_category'>\n sage: type(In.coerce_map_from(F))\n <class 'sage.modules.with_basis.morphism.TriangularModuleMorphismByLinearity_with_category'>\n sage: type(F.coerce_map_from(Out))\n <class 'sage.modules.with_basis.morphism.TriangularModuleMorphismByLinearity_with_category'>\n sage: type(Out.coerce_map_from(F))\n <class 'sage.modules.with_basis.morphism.TriangularModuleMorphismByLinearity_with_category'>\n sage: In.coerce_map_from(Out)\n Composite map:\n From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the In basis\n Defn: Generic morphism:\n From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n then\n Generic morphism:\n From: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: Out.coerce_map_from(In)\n Composite map:\n From: The subset algebra of {1, 2, 3} over Rational Field in the In basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n Defn: Generic morphism:\n From: The subset algebra of {1, 2, 3} over Rational Field in the In basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n then\n Generic morphism:\n From: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n "
assert (R in Rings())
self._base = R
self._S = S
Parent.__init__(self, category=Algebras(R).Commutative().WithRealizations())
F = self.F()
In = self.In()
Out = self.Out()
category = self.Bases()
key = self.indices_key
In_to_F = In.module_morphism((F.sum_of_monomials * Subsets), codomain=F, category=category, triangular='upper', unitriangular=True, key=key)
In_to_F.register_as_coercion()
(~ In_to_F).register_as_coercion()
F_to_Out = F.module_morphism((Out.sum_of_monomials * self.supsets), codomain=Out, category=category, triangular='lower', unitriangular=True, key=key)
F_to_Out.register_as_coercion()
(~ F_to_Out).register_as_coercion()
_shorthands = ['F', 'In', 'Out']
def a_realization(self):
'\n Returns the default realization of ``self``\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.a_realization()\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n '
return self.F()
def base_set(self):
'\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.base_set()\n {1, 2, 3}\n '
return self._S
def indices(self):
'\n The objects that index the basis elements of this algebra.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.indices()\n Subsets of {1, 2, 3}\n '
return Subsets(self._S)
def indices_key(self, x):
'\n A key function on a set which gives a linear extension\n of the inclusion order.\n\n INPUT:\n\n - ``x`` -- set\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: sorted(A.indices(), key=A.indices_key)\n [{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]\n '
return (len(x), list(x))
def supsets(self, set):
'\n Returns all the subsets of `S` containing ``set``\n\n INPUT:\n\n - ``set`` -- a subset of the base set `S` of ``self``\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.supsets(Set((2,)))\n [{1, 2, 3}, {2, 3}, {1, 2}, {2}]\n '
S = self.base_set()
return [S.difference(s) for s in Subsets(S.difference(set))]
def _repr_(self):
'\n EXAMPLES::\n\n sage: Sets().WithRealizations().example() # indirect doctest\n The subset algebra of {1, 2, 3} over Rational Field\n '
return ('The subset algebra of %s over %s' % (self.base_set(), self.base_ring()))
class Bases(Category_realization_of_parent):
'\n The category of the realizations of the subset algebra\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: C = A.Bases(); C\n Category of bases of The subset algebra of {1, 2, 3} over Rational Field\n sage: C.super_categories()\n [Category of realizations of The subset algebra of {1, 2, 3} over Rational Field,\n Join of Category of algebras with basis over Rational Field and\n Category of commutative algebras over Rational Field and\n Category of realizations of unital magmas]\n '
A = self.base()
category = Algebras(A.base_ring()).Commutative()
return [A.Realizations(), category.Realizations().WithBasis()]
class ParentMethods():
def from_set(self, *args):
'\n Construct the monomial indexed by the set containing the\n elements passed as arguments.\n\n EXAMPLES::\n\n sage: In = Sets().WithRealizations().example().In(); In\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: In.from_set(2,3)\n In[{2, 3}]\n\n As a shorthand, one can construct elements using the following\n notation::\n\n sage: In[2,3]\n In[{2, 3}]\n '
return self.monomial(Set(args))
def __getitem__(self, s):
'\n This method implements a convenient shorthand for constructing\n basis elements of this algebra.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example()\n sage: In = A.In()\n sage: In[2,3]\n In[{2, 3}]\n sage: F = A.F()\n sage: F[1,3]\n F[{1, 3}]\n '
from sage.rings.integer import Integer
if isinstance(s, Integer):
return self.from_set(*(s,))
else:
return self.from_set(*s)
def _repr_(self):
'\n EXAMPLES::\n\n sage: Sets().WithRealizations().example().In() # indirect doctest\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n '
return ('%s in the %s basis' % (self.realization_of(), self._realization_name()))
@cached_method
def one(self):
'\n Returns the unit of this algebra.\n\n This default implementation takes the unit in the\n fundamental basis, and coerces it in ``self``.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: In = A.In(); Out = A.Out()\n sage: In.one()\n In[{}]\n sage: Out.one()\n Out[{}] + Out[{1}] + Out[{2}] + Out[{3}] + Out[{1, 2}] + Out[{1, 3}] + Out[{2, 3}] + Out[{1, 2, 3}]\n '
return self(self.realization_of().F().one())
class Fundamental(CombinatorialFreeModule, BindableClass):
'\n The Subset algebra, in the fundamental basis\n\n INPUT:\n\n - ``A`` -- a parent with realization in :class:`SubsetAlgebra`\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example()\n sage: A.F()\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: A.Fundamental()\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n '
def __init__(self, A):
'\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: F = A.F(); F\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: TestSuite(F).run()\n '
CombinatorialFreeModule.__init__(self, A.base_ring(), A.indices(), category=A.Bases(), prefix='F', sorting_key=A.indices_key)
def product_on_basis(self, left, right):
'\n Product of basis elements, as per :meth:`AlgebrasWithBasis.ParentMethods.product_on_basis`.\n\n INPUT:\n\n - ``left``, ``right`` -- sets indexing basis elements\n\n EXAMPLES::\n\n sage: F = Sets().WithRealizations().example().F(); F\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: S = F.basis().keys(); S\n Subsets of {1, 2, 3}\n sage: F.product_on_basis(S([]), S([]))\n F[{}]\n sage: F.product_on_basis(S({1}), S({3}))\n F[{1, 3}]\n sage: F.product_on_basis(S({1,2}), S({2,3}))\n F[{1, 2, 3}]\n '
return self.monomial(left.union(right))
def one_basis(self):
"\n Returns the index of the basis element which is equal to '1'.\n\n EXAMPLES::\n\n sage: F = Sets().WithRealizations().example().F(); F\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: F.one_basis()\n {}\n sage: F.one()\n F[{}]\n "
return Set([])
one = AlgebrasWithBasis.ParentMethods.one
F = Fundamental
class In(CombinatorialFreeModule, BindableClass):
"\n The Subset Algebra, in the ``In`` basis\n\n INPUT:\n\n - ``A`` -- a parent with realization in :class:`SubsetAlgebra`\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example()\n sage: A.In()\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n\n TESTS:\n\n The product in this basis is computed by converting to the fundamental\n basis, computing the product there, and then converting back::\n\n sage: In = Sets().WithRealizations().example().In(); In\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: x = In.an_element()\n sage: y = In.an_element()\n sage: In.product\n <bound method ....product_by_coercion ...>\n sage: In.product.__module__\n 'sage.categories.magmas'\n sage: In.product(x, y)\n -21*In[{}] - 2*In[{1}] + 19*In[{2}] + 53*In[{1, 2}]\n "
def __init__(self, A):
'\n EXAMPLES::\n\n sage: In = Sets().WithRealizations().example().In(); In\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: TestSuite(In).run()\n '
CombinatorialFreeModule.__init__(self, A.base_ring(), A.indices(), category=A.Bases(), prefix='In', sorting_key=A.indices_key)
class Out(CombinatorialFreeModule, BindableClass):
"\n The Subset Algebra, in the `Out` basis\n\n INPUT:\n\n - ``A`` -- a parent with realization in :class:`SubsetAlgebra`\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example()\n sage: A.Out()\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n\n TESTS:\n\n The product in this basis is computed by converting to the fundamental\n basis, computing the product there, and then converting back::\n\n sage: Out = Sets().WithRealizations().example().Out(); Out\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n sage: x = Out.an_element()\n sage: y = Out.an_element()\n sage: Out.product\n <bound method ....product_by_coercion ...>\n sage: Out.product.__module__\n 'sage.categories.magmas'\n sage: Out.product(x, y)\n Out[{}] + 4*Out[{1}] + 9*Out[{2}] + Out[{1, 2}]\n "
def __init__(self, A):
'\n EXAMPLES::\n\n sage: Out = Sets().WithRealizations().example().Out(); Out\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n sage: TestSuite(Out).run()\n '
CombinatorialFreeModule.__init__(self, A.base_ring(), A.indices(), category=A.Bases(), prefix='Out', sorting_key=A.indices_key)
|
class FacadeSets(CategoryWithAxiom):
def example(self, choice='subset'):
"\n Returns an example of facade set, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n INPUT:\n\n - ``choice`` -- 'union' or 'subset' (default: 'subset').\n\n EXAMPLES::\n\n sage: Sets().Facade().example()\n An example of facade set: the monoid of positive integers\n sage: Sets().Facade().example(choice='union')\n An example of a facade set: the integers completed by +-infinity\n sage: Sets().Facade().example(choice='subset')\n An example of facade set: the monoid of positive integers\n "
import sage.categories.examples.facade_sets as examples
if (choice == 'union'):
return examples.IntegersCompletion()
elif (choice == 'subset'):
return examples.PositiveIntegerMonoid()
else:
raise TypeError("choice should be 'union' or 'subset'")
class ParentMethods():
def _element_constructor_(self, element):
'\n Coerce ``element`` into ``self``\n\n INPUT:\n\n - ``element`` -- any object\n\n This default implementation returns ``element`` if\n ``self`` is a facade for ``parent(element)`. Otherwise it\n attempts in turn to coerce ``element`` into each parent\n ``self`` is a facade for.\n\n This implementation is only valid for a facade parent\n which models the full union of the parents it is a facade\n for. Other facade parents should redefine\n :meth:`element_constructor` appropriately.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example("union"); S\n An example of a facade set: the integers completed by +-infinity\n sage: S(1)\n 1\n sage: S(1/2)\n Traceback (most recent call last):\n ...\n ValueError: Can\'t coerce `1/2` in any parent `An example of a facade set: the integers completed by +-infinity` is a facade for\n sage: S(2/1)\n 2\n sage: S(2/1).parent()\n Integer Ring\n sage: S(int(1))\n 1\n sage: S(int(1)).parent()\n Integer Ring\n\n Facade parents that model strict subsets should redefine\n :meth:`element_constructor`::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n sage: S(-1)\n Traceback (most recent call last):\n ...\n ValueError: %s should be positive\n '
if self.is_parent_of(element):
return element
else:
parents = self.facade_for()
if (parents is True):
raise NotImplementedError
for parent in self.facade_for():
try:
return parent(element)
except Exception:
pass
raise ValueError(("Can't coerce `%s` in any parent `%s` is a facade for" % (element, self)))
def facade_for(self):
'\n Returns the parents this set is a facade for\n\n This default implementation assumes that ``self`` has\n an attribute ``_facade_for``, typically initialized by\n :meth:`Parent.__init__`. If the attribute is not present, the method\n raises a NotImplementedError.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n sage: S.facade_for()\n (Integer Ring,)\n\n Check that :trac:`13801` is corrected::\n\n sage: class A(Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category=Sets(), facade=True)\n sage: a = A()\n sage: a.facade_for()\n Traceback (most recent call last):\n ...\n NotImplementedError: this parent did not specify which parents it is a facade for\n '
try:
return self._facade_for
except AttributeError:
raise NotImplementedError('this parent did not specify which parents it is a facade for')
def is_parent_of(self, element):
'\n Returns whether ``self`` is the parent of ``element``\n\n INPUT:\n\n - ``element`` -- any object\n\n Since ``self`` is a facade domain, this actually tests\n whether the parent of ``element`` is any of the parent\n ``self`` is a facade for.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n sage: S.is_parent_of(1)\n True\n sage: S.is_parent_of(1/2)\n False\n\n This method differs from :meth:`__contains__` in two\n ways. First, this does not take into account the fact\n that ``self`` may be a strict subset of the parent(s)\n it is a facade for::\n\n sage: -1 in S, S.is_parent_of(-1)\n (False, True)\n\n Furthermore, there is no coercion attempted::\n\n sage: int(1) in S, S.is_parent_of(int(1))\n (True, False)\n\n .. warning::\n\n this implementation does not handle facade parents of facade\n parents. Is this a feature we want generically?\n '
parents = self.facade_for()
if (parents is True):
return True
from sage.structure.element import parent
return (parent(element) in parents)
def __contains__(self, element):
'\n Membership testing\n\n Returns whether ``element`` is in one of the parents\n ``self`` is a facade for.\n\n .. warning::\n\n this default implementation is currently\n overridden by :meth:`Parent.__contains__`.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example("union"); S\n An example of a facade set: the integers completed by +-infinity\n sage: 1 in S, -5 in S, oo in S, -oo in S, int(1) in S, 2/1 in S\n (True, True, True, True, True, True)\n sage: 1/2 in S, "bla" in S\n (False, False)\n '
return any(((element in parent) for parent in self.facade_for()))
def _an_element_(self):
'\n Try to return an element of ``self``, as per\n :meth:`Sets.ParentMethods.an_element`.\n\n For each parent ``self`` is a facade for, this default\n implementation tries the method ``an_element`` until it finds an\n element in ``self``. If none is found, this raises a\n :class:`NotImplementedError`.\n\n EXAMPLES::\n\n sage: S = Sets().Facade().example(); S\n An example of facade set: the monoid of positive integers\n sage: S.an_element()\n 1\n '
for parent in self.facade_for():
x = parent.an_element()
if (x in self):
return x
raise NotImplementedError
|
class Fields(CategoryWithAxiom):
"\n The category of (commutative) fields, i.e. commutative rings where\n all non-zero elements have multiplicative inverses\n\n EXAMPLES::\n\n sage: K = Fields()\n sage: K\n Category of fields\n sage: Fields().super_categories()\n [Category of euclidean domains, Category of division rings]\n\n sage: K(IntegerRing())\n Rational Field\n sage: K(PolynomialRing(GF(3), 'x'))\n Fraction Field of Univariate Polynomial Ring in x over\n Finite Field of size 3\n sage: K(RealField()) # needs sage.rings.real_mpfr\n Real Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Fields()).run()\n "
_base_category_class_and_axiom = (DivisionRings, 'Commutative')
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Fields().extra_super_categories()\n [Category of euclidean domains]\n\n '
return [EuclideanDomains()]
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: GF(4, "a") in Fields() # needs sage.rings.finite_rings\n True\n sage: QQ in Fields()\n True\n sage: ZZ in Fields()\n False\n sage: IntegerModRing(4) in Fields()\n False\n sage: InfinityRing in Fields()\n False\n\n This implementation will not be needed anymore once every\n field in Sage will be properly declared in the category\n :class:`Fields() <Fields>`.\n\n Caveat: this should eventually be fixed::\n\n sage: gap.Rationals in Fields() # needs sage.libs.gap\n False\n\n typically by implementing the method :meth:`category`\n appropriately for Gap objects::\n\n sage: GR = gap.Rationals # needs sage.libs.gap\n sage: GR.category = lambda: Fields() # needs sage.libs.gap\n sage: GR in Fields() # needs sage.libs.gap\n True\n\n The following tests against a memory leak fixed in :trac:`13370`. In order\n to prevent non-deterministic deallocation of fields that have been created\n in other doctests, we introduced a strong reference to all previously created\n uncollected objects in :trac:`19244`. ::\n\n sage: import gc\n sage: _ = gc.collect()\n sage: permstore = [X for X in gc.get_objects() if isinstance(X, sage.rings.finite_rings.integer_mod_ring.IntegerModRing_generic)]\n sage: n = len(permstore)\n sage: for i in prime_range(100): # needs sage.libs.pari\n ....: R = ZZ.quotient(i)\n ....: t = R in Fields()\n\n First, we show that there are now more quotient rings in cache than before::\n\n sage: len([X for X in gc.get_objects() if isinstance(X, sage.rings.finite_rings.integer_mod_ring.IntegerModRing_generic)]) > n\n True\n\n When we delete the last quotient ring created in the loop and then do a garbage\n collection, all newly created rings vanish::\n\n sage: del R\n sage: _ = gc.collect()\n sage: len([X for X in gc.get_objects() if isinstance(X, sage.rings.finite_rings.integer_mod_ring.IntegerModRing_generic)]) - n\n 0\n\n '
import sage.rings.ring
try:
return (self._contains_helper(x) or sage.rings.ring._is_Field(x))
except Exception:
return False
@lazy_class_attribute
def _contains_helper(cls):
"\n Helper for containment tests in the category of fields.\n\n This helper just tests whether the given object's category\n is already known to be a sub-category of the category of\n fields. There are, however, rings that are initialised\n as plain commutative rings and found out to be fields\n only afterwards. Hence, this helper alone is not enough\n for a proper containment test.\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: P.<x> = QQ[]\n sage: Q = P.quotient(x^2 + 2)\n sage: Q.category()\n Category of commutative no zero divisors quotients of algebras\n over (number fields and quotient fields and metric spaces)\n sage: F = Fields()\n sage: F._contains_helper(Q)\n False\n sage: Q in F # This changes the category!\n True\n sage: F._contains_helper(Q)\n True\n\n "
return Category_contains_method_by_parent_class(cls())
def _call_(self, x):
"\n Construct a field from the data in ``x``\n\n EXAMPLES::\n\n sage: K = Fields()\n sage: K\n Category of fields\n sage: Fields().super_categories()\n [Category of euclidean domains, Category of division rings]\n\n sage: K(IntegerRing()) # indirect doctest\n Rational Field\n sage: K(PolynomialRing(GF(3), 'x')) # indirect doctest\n Fraction Field of Univariate Polynomial Ring in x over\n Finite Field of size 3\n sage: K(RealField()) # needs sage.rings.real_mpfr\n Real Field with 53 bits of precision\n "
try:
return x.fraction_field()
except AttributeError:
raise TypeError(('unable to associate a field to %s' % x))
Finite = LazyImport('sage.categories.finite_fields', 'FiniteFields', at_startup=True)
class ParentMethods():
def is_field(self, proof=True):
'\n Returns True as ``self`` is a field.\n\n EXAMPLES::\n\n sage: QQ.is_field()\n True\n sage: Parent(QQ,category=Fields()).is_field()\n True\n '
return True
def is_integrally_closed(self):
'\n Return ``True``, as per :meth:`IntegralDomain.is_integrally_closed`:\n for every field `F`, `F` is its own field of fractions,\n hence every element of `F` is integral over `F`.\n\n EXAMPLES::\n\n sage: QQ.is_integrally_closed()\n True\n sage: QQbar.is_integrally_closed() # needs sage.rings.number_field\n True\n sage: Z5 = GF(5); Z5\n Finite Field of size 5\n sage: Z5.is_integrally_closed()\n True\n '
return True
def _gcd_univariate_polynomial(self, a, b):
'\n Return the gcd of ``a`` and ``b`` as a monic polynomial.\n\n INPUT:\n\n - ``a``, ``b`` -- two univariate polynomials defined over ``self``\n\n .. WARNING::\n\n If the base ring is inexact, the results may not be\n entirely stable.\n\n EXAMPLES::\n\n sage: R.<x> = QQbar[] # needs sage.rings.number_field\n sage: QQbar._gcd_univariate_polynomial(2*x, 2*x^2) # needs sage.rings.number_field\n x\n\n TESTS::\n\n sage: fields = []\n sage: fields += [RR, CC] # needs sage.rings.real_mpfr\n sage: fields.append(QQbar) # needs sage.rings.number_field\n sage: for A in fields:\n ....: g = A._gcd_univariate_polynomial\n ....: R.<x> = A[]\n ....: z = R.zero()\n ....: assert(g(2*x, 2*x^2) == x and\n ....: g(z, 2*x) == x and\n ....: g(2*x, z) == x and\n ....: g(z, z) == z)\n\n sage: # needs sage.rings.real_mpfr\n sage: R.<x> = RR[]\n sage: (x^3).gcd(x^5 + 1)\n 1.00000000000000\n sage: (x^3).gcd(x^5 + x^2)\n x^2\n sage: f = (x+3)^2 * (x-1)\n sage: g = (x+3)^5\n sage: f.gcd(g)\n x^2 + 6.00000000000000*x + 9.00000000000000\n\n The following example illustrates the fact that for inexact\n base rings, the returned gcd is often 1 due to rounding::\n\n sage: # needs sage.rings.real_mpfr\n sage: f = (x+RR.pi())^2 * (x-1)\n sage: g = (x+RR.pi())^5\n sage: f.gcd(g)\n 1.00000000000000\n\n Check :trac:`23012`::\n\n sage: # needs sage.libs.pari\n sage: R.<x> = QQ[]\n sage: Q = R.quotient(x^2 - 1) # Not a field\n sage: P.<x> = Q[]\n sage: def always_True(*args, **kwds): return True\n sage: Q.is_field = always_True\n sage: Q in Fields()\n True\n sage: Q._gcd_univariate_polynomial(x, x)\n x\n '
while b:
(q, r) = a.quo_rem(b)
(a, b) = (b, r)
if a:
a = a.monic()
return a
def _xgcd_univariate_polynomial(self, a, b):
'\n Return an extended gcd of ``a`` and ``b``.\n\n INPUT:\n\n - ``a``, ``b`` -- two univariate polynomials defined over ``self``\n\n OUTPUT:\n\n A tuple ``(d, u, v)`` of polynomials such that ``d`` is the\n greatest common divisor (monic or zero) of ``a`` and ``b``,\n and ``u``, ``v`` satisfy ``d = u*a + v*b``.\n\n .. WARNING::\n\n If the base ring is inexact, the results may not be\n entirely stable.\n\n ALGORITHM:\n\n This uses the extended Euclidean algorithm; see for example\n [Coh1993]_, Algorithm 3.2.2.\n\n EXAMPLES::\n\n sage: P.<x> = QQ[]\n sage: F = (x^2 + 2)*x^3; G = (x^2+2)*(x-3)\n sage: g, u, v = QQ._xgcd_univariate_polynomial(F,G)\n sage: g, u, v\n (x^2 + 2, 1/27, -1/27*x^2 - 1/9*x - 1/3)\n sage: u*F + v*G\n x^2 + 2\n\n ::\n\n sage: g, u, v = QQ._xgcd_univariate_polynomial(x,P(0)); g, u, v\n (x, 1, 0)\n sage: g == u*x + v*P(0)\n True\n sage: g, u, v = QQ._xgcd_univariate_polynomial(P(0),x); g, u, v\n (x, 0, 1)\n sage: g == u*P(0) + v*x\n True\n\n TESTS::\n\n sage: fields = []\n sage: fields += [RR, CC] # needs sage.rings.real_mpfr\n sage: fields.append(QQbar) # needs sage.rings.number_field\n sage: for A in fields:\n ....: g = A._xgcd_univariate_polynomial\n ....: R.<x> = A[]\n ....: z, h = R(0), R(1/2)\n ....: assert(g(2*x, 2*x^2) == (x, h, z) and\n ....: g(z, 2*x) == (x, z, h) and\n ....: g(2*x, z) == (x, h, z) and\n ....: g(z, z) == (z, z, z))\n\n sage: P.<x> = QQ[]\n sage: F = (x^2 + 2)*x^3; G = (x^2+2)*(x-3)\n sage: g, u, v = QQ._xgcd_univariate_polynomial(F,G)\n sage: g, u, v\n (x^2 + 2, 1/27, -1/27*x^2 - 1/9*x - 1/3)\n sage: u*F + v*G\n x^2 + 2\n\n We check that the behavior of xgcd with zero elements is\n compatible with gcd (:trac:`17671`)::\n\n sage: # needs sage.rings.number_field\n sage: R.<x> = QQbar[]\n sage: zero = R.zero()\n sage: zero.xgcd(2*x)\n (x, 0, 1/2)\n sage: (2*x).xgcd(zero)\n (x, 1/2, 0)\n sage: zero.xgcd(zero)\n (0, 0, 0)\n '
R = a.parent()
zero = R.zero()
if (not b):
if (not a):
return (zero, zero, zero)
c = (~ a.leading_coefficient())
return ((c * a), R(c), zero)
elif (not a):
c = (~ b.leading_coefficient())
return ((c * b), zero, R(c))
(u, d, v1, v3) = (R.one(), a, zero, b)
while v3:
(q, r) = d.quo_rem(v3)
(u, d, v1, v3) = (v1, v3, (u - (v1 * q)), r)
v = ((d - (a * u)) // b)
if d:
c = (~ d.leading_coefficient())
(d, u, v) = ((c * d), (c * u), (c * v))
return (d, u, v)
def is_perfect(self):
"\n Return whether this field is perfect, i.e., its characteristic is\n `p=0` or every element has a `p`-th root.\n\n EXAMPLES::\n\n sage: QQ.is_perfect()\n True\n sage: GF(2).is_perfect()\n True\n sage: FunctionField(GF(2), 'x').is_perfect()\n False\n\n "
if (self.characteristic() == 0):
return True
else:
raise NotImplementedError
def _test_characteristic_fields(self, **options):
"\n Run generic tests on the method :meth:`.characteristic`.\n\n EXAMPLES::\n\n sage: QQ._test_characteristic_fields()\n\n .. NOTE::\n\n We cannot call this method ``_test_characteristic`` since that\n would overwrite the method in the super category, and for\n cython classes just calling\n ``super(sage.categories.fields.Fields().parent_class,\n self)._test_characteristic`` doesn't have the desired effect.\n\n .. SEEALSO::\n\n :meth:`sage.categories.rings.Rings.ParentMethods._test_characteristic`\n "
tester = self._tester(**options)
try:
char = self.characteristic()
tester.assertTrue((char.is_zero() or char.is_prime()))
except AttributeError:
return
except NotImplementedError:
return
def fraction_field(self):
'\n Returns the *fraction field* of ``self``, which is ``self``.\n\n EXAMPLES::\n\n sage: QQ.fraction_field() is QQ\n True\n '
return self
def _squarefree_decomposition_univariate_polynomial(self, f):
"\n Return the square-free decomposition of ``f`` over this field.\n\n This is a helper method for\n :meth:`sage.rings.polynomial.squarefree_decomposition`.\n\n INPUT:\n\n - ``f`` -- a univariate non-zero polynomial over this field\n\n ALGORITHM: For rings of characteristic zero, we use the algorithm\n described in [Yun1976]_. Other fields may provide their own\n implementation by overriding this method.\n\n EXAMPLES::\n\n sage: x = polygen(QQ)\n sage: p = 37 * (x-1)^3 * (x-2)^3 * (x-1/3)^7 * (x-3/7)\n sage: p.squarefree_decomposition()\n (37*x - 111/7) * (x^2 - 3*x + 2)^3 * (x - 1/3)^7\n sage: p = 37 * (x-2/3)^2\n sage: p.squarefree_decomposition()\n (37) * (x - 2/3)^2\n sage: x = polygen(GF(3))\n sage: x.squarefree_decomposition()\n x\n sage: f = QQbar['x'](1) # needs sage.rings.number_field\n sage: f.squarefree_decomposition() # needs sage.rings.number_field\n 1\n "
from sage.structure.factorization import Factorization
if (f.degree() == 0):
return Factorization([], unit=f[0])
if (self.characteristic() != 0):
raise NotImplementedError('square-free decomposition not implemented for this polynomial')
factors = []
cur = f
f = [f]
while (cur.degree() > 0):
cur = cur.gcd(cur.derivative())
f.append(cur)
g = []
for i in range((len(f) - 1)):
g.append((f[i] // f[(i + 1)]))
a = []
for i in range((len(g) - 1)):
a.append((g[i] // g[(i + 1)]))
a.append(g[(- 1)])
unit = f[(- 1)]
for i in range(len(a)):
if (a[i].degree() > 0):
factors.append((a[i], (i + 1)))
else:
unit = (unit * (a[i].constant_coefficient() ** (i + 1)))
return Factorization(factors, unit=unit, sort=False)
def vector_space(self, *args, **kwds):
'\n Gives an isomorphism of this field with a vector space over a subfield.\n\n This method is an alias for ``free_module``, which may have more documentation.\n\n INPUT:\n\n - ``base`` -- a subfield or morphism into this field (defaults to the base field)\n\n - ``basis`` -- a basis of the field as a vector space\n over the subfield; if not given, one is chosen automatically\n\n - ``map`` -- whether to return maps from and to the vector space\n\n OUTPUT:\n\n - ``V`` -- a vector space over ``base``\n - ``from_V`` -- an isomorphism from ``V`` to this field\n - ``to_V`` -- the inverse isomorphism from this field to ``V``\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: K.<a> = Qq(125)\n sage: V, fr, to = K.vector_space()\n sage: v = V([1, 2, 3])\n sage: fr(v, 7)\n (3*a^2 + 2*a + 1) + O(5^7)\n '
return self.free_module(*args, **kwds)
class ElementMethods():
def euclidean_degree(self):
'\n Return the degree of this element as an element of an Euclidean\n domain.\n\n In a field, this returns 0 for all but the zero element (for\n which it is undefined).\n\n EXAMPLES::\n\n sage: QQ.one().euclidean_degree()\n 0\n '
if self.is_zero():
raise ValueError('euclidean degree not defined for the zero element')
from sage.rings.integer_ring import ZZ
return ZZ.zero()
def quo_rem(self, other):
'\n Return the quotient with remainder of the division of this element\n by ``other``.\n\n INPUT:\n\n - ``other`` -- an element of the field\n\n EXAMPLES::\n\n sage: f,g = QQ(1), QQ(2)\n sage: f.quo_rem(g)\n (1/2, 0)\n '
if other.is_zero():
raise ZeroDivisionError
return ((self / other), self.parent().zero())
def is_unit(self):
'\n Returns True if ``self`` has a multiplicative inverse.\n\n EXAMPLES::\n\n sage: QQ(2).is_unit()\n True\n sage: QQ(0).is_unit()\n False\n '
return (not self.is_zero())
@coerce_binop
def gcd(self, other):
'\n Greatest common divisor.\n\n .. NOTE::\n\n Since we are in a field and the greatest common divisor is only\n determined up to a unit, it is correct to either return zero or\n one. Note that fraction fields of unique factorization domains\n provide a more sophisticated gcd.\n\n EXAMPLES::\n\n sage: K = GF(5)\n sage: K(2).gcd(K(1))\n 1\n sage: K(0).gcd(K(0))\n 0\n sage: all(x.gcd(y) == (0 if x == 0 and y == 0 else 1)\n ....: for x in K for y in K)\n True\n\n For field of characteristic zero, the gcd of integers is considered\n as if they were elements of the integer ring::\n\n sage: gcd(15.0,12.0)\n 3.00000000000000\n\n But for other floating point numbers, the gcd is just `0.0` or `1.0`::\n\n sage: gcd(3.2, 2.18)\n 1.00000000000000\n\n sage: gcd(0.0, 0.0)\n 0.000000000000000\n\n AUTHOR:\n\n - Simon King (2011-02) -- :trac:`10771`\n - Vincent Delecroix (2015) -- :trac:`17671`\n '
P = self.parent()
try:
has_zero_char = (P.characteristic() == 0)
except (AttributeError, NotImplementedError):
has_zero_char = False
if has_zero_char:
from sage.rings.integer_ring import ZZ
try:
return P(ZZ(self).gcd(ZZ(other)))
except TypeError:
pass
if ((self == P.zero()) and (other == P.zero())):
return P.zero()
return P.one()
@coerce_binop
def lcm(self, other):
'\n Least common multiple.\n\n .. NOTE::\n\n Since we are in a field and the least common multiple is only\n determined up to a unit, it is correct to either return zero or\n one. Note that fraction fields of unique factorization domains\n provide a more sophisticated lcm.\n\n EXAMPLES::\n\n sage: GF(2)(1).lcm(GF(2)(0))\n 0\n sage: GF(2)(1).lcm(GF(2)(1))\n 1\n\n For field of characteristic zero, the lcm of integers is considered\n as if they were elements of the integer ring::\n\n sage: lcm(15.0,12.0)\n 60.0000000000000\n\n But for others floating point numbers, it is just `0.0` or `1.0`::\n\n sage: lcm(3.2, 2.18)\n 1.00000000000000\n\n sage: lcm(0.0, 0.0)\n 0.000000000000000\n\n AUTHOR:\n\n - Simon King (2011-02) -- :trac:`10771`\n - Vincent Delecroix (2015) -- :trac:`17671`\n '
P = self.parent()
try:
has_zero_char = (P.characteristic() == 0)
except (AttributeError, NotImplementedError):
has_zero_char = False
if has_zero_char:
from sage.rings.integer_ring import ZZ
try:
return P(ZZ(self).lcm(ZZ(other)))
except TypeError:
pass
if (self.is_zero() or other.is_zero()):
return P.zero()
return P.one()
@coerce_binop
def xgcd(self, other):
'\n Compute the extended gcd of ``self`` and ``other``.\n\n INPUT:\n\n - ``other`` -- an element with the same parent as ``self``\n\n OUTPUT:\n\n A tuple ``(r, s, t)`` of elements in the parent of ``self`` such\n that ``r = s * self + t * other``. Since the computations are done\n over a field, ``r`` is zero if ``self`` and ``other`` are zero,\n and one otherwise.\n\n AUTHORS:\n\n - Julian Rueth (2012-10-19): moved here from\n :class:`sage.structure.element.FieldElement`\n\n EXAMPLES::\n\n sage: K = GF(5)\n sage: K(2).xgcd(K(1))\n (1, 3, 0)\n sage: K(0).xgcd(K(4))\n (1, 0, 4)\n sage: K(1).xgcd(K(1))\n (1, 1, 0)\n sage: GF(5)(0).xgcd(GF(5)(0))\n (0, 0, 0)\n\n The xgcd of non-zero floating point numbers will be a triple of\n floating points. But if the input are two integral floating points\n the result is a floating point version of the standard gcd on\n `\\ZZ`::\n\n sage: xgcd(12.0, 8.0)\n (4.00000000000000, 1.00000000000000, -1.00000000000000)\n\n sage: xgcd(3.1, 2.98714)\n (1.00000000000000, 0.322580645161290, 0.000000000000000)\n\n sage: xgcd(0.0, 1.1)\n (1.00000000000000, 0.000000000000000, 0.909090909090909)\n '
P = self.parent()
try:
has_zero_char = (P.characteristic() == 0)
except (AttributeError, NotImplementedError):
has_zero_char = False
if has_zero_char:
from sage.rings.integer_ring import ZZ
try:
return tuple((P(x) for x in ZZ(self).xgcd(ZZ(other))))
except TypeError:
pass
if (not self.is_zero()):
return (P.one(), (~ self), P.zero())
if (not other.is_zero()):
return (P.one(), P.zero(), (~ other))
return (P.zero(), P.zero(), P.zero())
def factor(self):
'\n Return a factorization of ``self``.\n\n Since ``self`` is either a unit or zero, this function is trivial.\n\n EXAMPLES::\n\n sage: x = GF(7)(5)\n sage: x.factor()\n 5\n sage: RR(0).factor()\n Traceback (most recent call last):\n ...\n ArithmeticError: factorization of 0.000000000000000 is not defined\n '
if (not self):
raise ArithmeticError('factorization of {!r} is not defined'.format(self))
from sage.structure.factorization import Factorization
return Factorization([], self)
def inverse_of_unit(self):
"\n Return the inverse of this element.\n\n EXAMPLES::\n\n sage: x = polygen(ZZ, 'x')\n sage: NumberField(x^7 + 2, 'a')(2).inverse_of_unit() # needs sage.rings.number_field\n 1/2\n\n Trying to invert the zero element typically raises a\n :class:`ZeroDivisionError`::\n\n sage: QQ(0).inverse_of_unit()\n Traceback (most recent call last):\n ...\n ZeroDivisionError: rational division by zero\n\n To catch that exception in a way that also works for non-units\n in more general rings, use something like::\n\n sage: try:\n ....: QQ(0).inverse_of_unit()\n ....: except ArithmeticError:\n ....: pass\n\n Also note that some “fields” allow one to invert the zero element::\n\n sage: RR(0).inverse_of_unit()\n +infinity\n "
return (~ self)
|
class FilteredAlgebras(FilteredModulesCategory):
'\n The category of filtered algebras.\n\n An algebra `A` over a commutative ring `R` is *filtered* if\n `A` is endowed with a structure of a filtered `R`-module\n (whose underlying `R`-module structure is identical with\n that of the `R`-algebra `A`) such that the indexing set `I`\n (typically `I = \\NN`) is also an additive abelian monoid,\n the unity `1` of `A` belongs to `F_0`, and we have\n `F_i \\cdot F_j \\subseteq F_{i+j}` for all `i, j \\in I`.\n\n EXAMPLES::\n\n sage: Algebras(ZZ).Filtered()\n Category of filtered algebras over Integer Ring\n sage: Algebras(ZZ).Filtered().super_categories()\n [Category of algebras over Integer Ring,\n Category of filtered modules over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(Algebras(ZZ).Filtered()).run()\n\n REFERENCES:\n\n - :wikipedia:`Filtered_algebra`\n '
class ParentMethods():
@abstract_method(optional=True)
def graded_algebra(self):
'\n Return the associated graded algebra to ``self``.\n\n .. TODO::\n\n Implement a version of the associated graded algebra\n which does not require ``self`` to have a\n distinguished basis.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(ZZ).Filtered().example()\n sage: A.graded_algebra()\n Graded Algebra of An example of a filtered algebra with basis:\n the universal enveloping algebra of\n Lie algebra of RR^3 with cross product over Integer Ring\n '
|
class FilteredAlgebrasWithBasis(FilteredModulesCategory):
'\n The category of filtered algebras with a distinguished\n homogeneous basis.\n\n A filtered algebra with basis over a commutative ring `R`\n is a filtered algebra over `R` endowed with the structure\n of a filtered module with basis (with the same underlying\n filtered-module structure). See\n :class:`~sage.categories.filtered_algebras.FilteredAlgebras` and\n :class:`~sage.categories.filtered_modules_with_basis.FilteredModulesWithBasis`\n for these two notions.\n\n EXAMPLES::\n\n sage: C = AlgebrasWithBasis(ZZ).Filtered(); C\n Category of filtered algebras with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of algebras with basis over Integer Ring,\n Category of filtered algebras over Integer Ring,\n Category of filtered modules with basis over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class ParentMethods():
def graded_algebra(self):
"\n Return the associated graded algebra to ``self``.\n\n See :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`\n for the definition and the properties of this.\n\n If the filtered algebra ``self`` with basis is called `A`,\n then this method returns `\\operatorname{gr} A`. The method\n :meth:`to_graded_conversion` returns the canonical\n `R`-module isomorphism `A \\to \\operatorname{gr} A` induced\n by the basis of `A`, and the method\n :meth:`from_graded_conversion` returns the inverse of this\n isomorphism. The method :meth:`projection` projects\n elements of `A` onto `\\operatorname{gr} A` according to\n their place in the filtration on `A`.\n\n .. WARNING::\n\n When not overridden, this method returns the default\n implementation of an associated graded algebra --\n namely, ``AssociatedGradedAlgebra(self)``, where\n ``AssociatedGradedAlgebra`` is\n :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`.\n But many instances of :class:`FilteredAlgebrasWithBasis`\n override this method, as the associated graded algebra\n often is (isomorphic) to a simpler object (for instance,\n the associated graded algebra of a graded algebra can be\n identified with the graded algebra itself). Generic code\n that uses associated graded algebras (such as the code\n of the :meth:`induced_graded_map` method below) should\n make sure to only communicate with them via the\n :meth:`to_graded_conversion`,\n :meth:`from_graded_conversion`, and\n :meth:`projection` methods (in particular,\n do not expect there to be a conversion from ``self``\n to ``self.graded_algebra()``; this currently does not\n work for Clifford algebras). Similarly, when\n overriding :meth:`graded_algebra`, make sure to\n accordingly redefine these three methods, unless their\n definitions below still apply to your case (this will\n happen whenever the basis of your :meth:`graded_algebra`\n has the same indexing set as ``self``, and the partition\n of this indexing set according to degree is the same as\n for ``self``).\n\n .. TODO::\n\n Maybe the thing about the conversion from ``self``\n to ``self.graded_algebra()`` on the Clifford at least\n could be made to work? (I would still warn the user\n against ASSUMING that it must work -- as there is\n probably no way to guarantee it in all cases, and\n we shouldn't require users to mess with\n element constructors.)\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(ZZ).Filtered().example()\n sage: A.graded_algebra()\n Graded Algebra of An example of a filtered algebra with basis:\n the universal enveloping algebra of\n Lie algebra of RR^3 with cross product over Integer Ring\n "
from sage.algebras.associated_graded import AssociatedGradedAlgebra
return AssociatedGradedAlgebra(self)
def to_graded_conversion(self):
"\n Return the canonical `R`-module isomorphism\n `A \\to \\operatorname{gr} A` induced by the basis of `A`\n (where `A = ` ``self``).\n\n This is an isomorphism of `R`-modules, not of algebras. See\n the class documentation :class:`AssociatedGradedAlgebra`.\n\n .. SEEALSO::\n\n :meth:`from_graded_conversion`\n\n EXAMPLES::\n\n sage: A = Algebras(QQ).WithBasis().Filtered().example()\n sage: p = A.an_element() + A.algebra_generators()['x'] + 2; p\n U['x']^2*U['y']^2*U['z']^3 + 3*U['x'] + 3*U['y'] + 3\n sage: q = A.to_graded_conversion()(p); q\n bar(U['x']^2*U['y']^2*U['z']^3) + 3*bar(U['x'])\n + 3*bar(U['y']) + 3*bar(1)\n sage: q.parent() is A.graded_algebra()\n True\n "
base_one = self.base_ring().one()
return self.module_morphism(diagonal=(lambda x: base_one), codomain=self.graded_algebra())
def from_graded_conversion(self):
"\n Return the inverse of the canonical `R`-module isomorphism\n `A \\to \\operatorname{gr} A` induced by the basis of `A`\n (where `A = ` ``self``). This inverse is an isomorphism\n `\\operatorname{gr} A \\to A`.\n\n This is an isomorphism of `R`-modules, not of algebras. See\n the class documentation :class:`AssociatedGradedAlgebra`.\n\n .. SEEALSO::\n\n :meth:`to_graded_conversion`\n\n EXAMPLES::\n\n sage: A = Algebras(QQ).WithBasis().Filtered().example()\n sage: p = A.an_element() + A.algebra_generators()['x'] + 2; p\n U['x']^2*U['y']^2*U['z']^3 + 3*U['x'] + 3*U['y'] + 3\n sage: q = A.to_graded_conversion()(p)\n sage: A.from_graded_conversion()(q) == p\n True\n sage: q.parent() is A.graded_algebra()\n True\n "
base_one = self.base_ring().one()
return self.graded_algebra().module_morphism(diagonal=(lambda x: base_one), codomain=self)
def projection(self, i):
"\n Return the `i`-th projection `p_i : F_i \\to G_i` (in the\n notations of the class documentation\n :class:`AssociatedGradedAlgebra`, where `A = ` ``self``).\n\n This method actually does not return the map `p_i` itself,\n but an extension of `p_i` to the whole `R`-module `A`.\n This extension is the composition of the `R`-module\n isomorphism `A \\to \\operatorname{gr} A` with the canonical\n projection of the graded `R`-module `\\operatorname{gr} A`\n onto its `i`-th graded component `G_i`. The codomain of\n this map is `\\operatorname{gr} A`, although its actual\n image is `G_i`. The map `p_i` is obtained from this map\n by restricting its domain to `F_i` and its image to `G_i`.\n\n EXAMPLES::\n\n sage: A = Algebras(QQ).WithBasis().Filtered().example()\n sage: p = A.an_element() + A.algebra_generators()['x'] + 2; p\n U['x']^2*U['y']^2*U['z']^3 + 3*U['x'] + 3*U['y'] + 3\n sage: q = A.projection(7)(p); q\n bar(U['x']^2*U['y']^2*U['z']^3)\n sage: q.parent() is A.graded_algebra()\n True\n sage: A.projection(8)(p)\n 0\n "
base_zero = self.base_ring().zero()
base_one = self.base_ring().one()
grA = self.graded_algebra()
proj = (lambda x: (base_one if (self.degree_on_basis(x) == i) else base_zero))
return self.module_morphism(diagonal=proj, codomain=grA)
def induced_graded_map(self, other, f):
'\n Return the graded linear map between the associated graded\n algebras of ``self`` and ``other`` canonically induced by\n the filtration-preserving map ``f : self -> other``.\n\n Let `A` and `B` be two filtered algebras with basis, and let\n `(F_i)_{i \\in I}` and `(G_i)_{i \\in I}` be their\n filtrations. Let `f : A \\to B` be a linear map which\n preserves the filtration (i.e., satisfies `f(F_i) \\subseteq\n G_i` for all `i \\in I`). Then, there is a canonically\n defined graded linear map\n `\\operatorname{gr} f : \\operatorname{gr} A \\to\n \\operatorname{gr} B` which satisfies\n\n .. MATH::\n\n (\\operatorname{gr} f) (p_i(a)) = p_i(f(a))\n \\qquad \\text{for all } i \\in I \\text{ and } a \\in F_i ,\n\n where the `p_i` on the left hand side is the canonical\n projection from `F_i` onto the `i`-th graded component\n of `\\operatorname{gr} A`, while the `p_i` on the right\n hand side is the canonical projection from `G_i` onto\n the `i`-th graded component of `\\operatorname{gr} B`.\n\n INPUT:\n\n - ``other`` -- a filtered algebra with basis\n\n - ``f`` -- a filtration-preserving linear map from ``self``\n to ``other`` (can be given as a morphism or as a function)\n\n OUTPUT:\n\n The graded linear map `\\operatorname{gr} f`.\n\n EXAMPLES:\n\n **Example 1.**\n\n We start with the universal enveloping algebra of the\n Lie algebra `\\RR^3` (with the cross product serving as\n Lie bracket)::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example(); A\n An example of a filtered algebra with basis: the\n universal enveloping algebra of Lie algebra of RR^3\n with cross product over Rational Field\n sage: M = A.indices(); M\n Free abelian monoid indexed by {\'x\', \'y\', \'z\'}\n sage: x,y,z = [A.basis()[M.gens()[i]] for i in "xyz"]\n\n Let us define a stupid filtered map from ``A`` to\n itself::\n\n sage: def map_on_basis(m):\n ....: d = m.dict()\n ....: i = d.get(\'x\', 0); j = d.get(\'y\', 0); k = d.get(\'z\', 0)\n ....: g = (y ** (i+j)) * (z ** k)\n ....: if i > 0:\n ....: g += i * (x ** (i-1)) * (y ** j) * (z ** k)\n ....: return g\n sage: f = A.module_morphism(on_basis=map_on_basis,\n ....: codomain=A)\n sage: f(x)\n U[\'y\'] + 1\n sage: f(x*y*z)\n U[\'y\']^2*U[\'z\'] + U[\'y\']*U[\'z\']\n sage: f(x*x*y*z)\n U[\'y\']^3*U[\'z\'] + 2*U[\'x\']*U[\'y\']*U[\'z\']\n sage: f(A.one())\n 1\n sage: f(y*z)\n U[\'y\']*U[\'z\']\n\n (There is nothing here that is peculiar to this\n universal enveloping algebra; we are only using its\n module structure, and we could just as well be using\n a polynomial algebra in its stead.)\n\n We now compute `\\operatorname{gr} f` ::\n\n sage: grA = A.graded_algebra(); grA\n Graded Algebra of An example of a filtered algebra with\n basis: the universal enveloping algebra of Lie algebra\n of RR^3 with cross product over Rational Field\n sage: xx, yy, zz = [A.to_graded_conversion()(i) for i in [x, y, z]]\n sage: xx+yy*zz\n bar(U[\'y\']*U[\'z\']) + bar(U[\'x\'])\n sage: grf = A.induced_graded_map(A, f); grf\n Generic endomorphism of Graded Algebra of An example\n of a filtered algebra with basis: the universal\n enveloping algebra of Lie algebra of RR^3 with cross\n product over Rational Field\n sage: grf(xx)\n bar(U[\'y\'])\n sage: grf(xx*yy*zz)\n bar(U[\'y\']^2*U[\'z\'])\n sage: grf(xx*xx*yy*zz)\n bar(U[\'y\']^3*U[\'z\'])\n sage: grf(grA.one())\n bar(1)\n sage: grf(yy*zz)\n bar(U[\'y\']*U[\'z\'])\n sage: grf(yy*zz-2*yy)\n bar(U[\'y\']*U[\'z\']) - 2*bar(U[\'y\'])\n\n **Example 2.**\n\n We shall now construct `\\operatorname{gr} f` for a\n different map `f` out of the same ``A``; the new map\n `f` will lead into a graded algebra already, namely into\n the algebra of symmetric functions::\n\n sage: # needs sage.combinat sage.modules\n sage: h = SymmetricFunctions(QQ).h()\n sage: def map_on_basis(m): # redefining map_on_basis\n ....: d = m.dict()\n ....: i = d.get(\'x\', 0); j = d.get(\'y\', 0); k = d.get(\'z\', 0)\n ....: g = (h[1] ** i) * (h[2] ** (j // 2) * (h[3] ** (k // 3)))\n ....: g += i * (h[1] ** (i+j+k))\n ....: return g\n sage: f = A.module_morphism(on_basis=map_on_basis,\n ....: codomain=h) # redefining f\n sage: f(x)\n 2*h[1]\n sage: f(y)\n h[]\n sage: f(z)\n h[]\n sage: f(y**2)\n h[2]\n sage: f(x**2)\n 3*h[1, 1]\n sage: f(x*y*z)\n h[1] + h[1, 1, 1]\n sage: f(x*x*y*y*z)\n 2*h[1, 1, 1, 1, 1] + h[2, 1, 1]\n sage: f(A.one())\n h[]\n\n The algebra ``h`` of symmetric functions in the `h`-basis\n is already graded, so its associated graded algebra is\n implemented as itself::\n\n sage: # needs sage.combinat sage.modules\n sage: grh = h.graded_algebra(); grh is h\n True\n sage: grf = A.induced_graded_map(h, f); grf\n Generic morphism:\n From: Graded Algebra of An example of a filtered\n algebra with basis: the universal enveloping\n algebra of Lie algebra of RR^3 with cross\n product over Rational Field\n To: Symmetric Functions over Rational Field\n in the homogeneous basis\n sage: grf(xx)\n 2*h[1]\n sage: grf(yy)\n 0\n sage: grf(zz)\n 0\n sage: grf(yy**2)\n h[2]\n sage: grf(xx**2)\n 3*h[1, 1]\n sage: grf(xx*yy*zz)\n h[1, 1, 1]\n sage: grf(xx*xx*yy*yy*zz)\n 2*h[1, 1, 1, 1, 1]\n sage: grf(grA.one())\n h[]\n\n **Example 3.**\n\n After having had a graded algebra as the codomain, let us try to\n have one as the domain instead. Our new ``f`` will go from ``h``\n to ``A``::\n\n sage: # needs sage.combinat sage.modules\n sage: def map_on_basis(lam): # redefining map_on_basis\n ....: return x ** (sum(lam)) + y ** (len(lam))\n sage: f = h.module_morphism(on_basis=map_on_basis,\n ....: codomain=A) # redefining f\n sage: f(h[1])\n U[\'x\'] + U[\'y\']\n sage: f(h[2])\n U[\'x\']^2 + U[\'y\']\n sage: f(h[1, 1])\n U[\'x\']^2 + U[\'y\']^2\n sage: f(h[2, 2])\n U[\'x\']^4 + U[\'y\']^2\n sage: f(h[3, 2, 1])\n U[\'x\']^6 + U[\'y\']^3\n sage: f(h.one())\n 2\n sage: grf = h.induced_graded_map(A, f); grf\n Generic morphism:\n From: Symmetric Functions over Rational Field\n in the homogeneous basis\n To: Graded Algebra of An example of a filtered\n algebra with basis: the universal enveloping\n algebra of Lie algebra of RR^3 with cross\n product over Rational Field\n sage: grf(h[1])\n bar(U[\'x\']) + bar(U[\'y\'])\n sage: grf(h[2])\n bar(U[\'x\']^2)\n sage: grf(h[1, 1])\n bar(U[\'x\']^2) + bar(U[\'y\']^2)\n sage: grf(h[2, 2])\n bar(U[\'x\']^4)\n sage: grf(h[3, 2, 1])\n bar(U[\'x\']^6)\n sage: grf(h.one())\n 2*bar(1)\n\n **Example 4.**\n\n The construct `\\operatorname{gr} f` also makes sense when `f`\n is a filtration-preserving map between graded algebras. ::\n\n sage: # needs sage.combinat sage.modules\n sage: def map_on_basis(lam): # redefining map_on_basis\n ....: return h[lam] + h[len(lam)]\n sage: f = h.module_morphism(on_basis=map_on_basis,\n ....: codomain=h) # redefining f\n sage: f(h[1])\n 2*h[1]\n sage: f(h[2])\n h[1] + h[2]\n sage: f(h[1, 1])\n h[1, 1] + h[2]\n sage: f(h[2, 1])\n h[2] + h[2, 1]\n sage: f(h.one())\n 2*h[]\n sage: grf = h.induced_graded_map(h, f); grf\n Generic endomorphism of Symmetric Functions over Rational\n Field in the homogeneous basis\n sage: grf(h[1])\n 2*h[1]\n sage: grf(h[2])\n h[2]\n sage: grf(h[1, 1])\n h[1, 1] + h[2]\n sage: grf(h[2, 1])\n h[2, 1]\n sage: grf(h.one())\n 2*h[]\n\n **Example 5.**\n\n For another example, let us compute `\\operatorname{gr} f` for a\n map `f` between two Clifford algebras::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(ZZ, 2, [1,2,3])\n sage: B = CliffordAlgebra(Q, names=[\'u\',\'v\']); B\n The Clifford algebra of the Quadratic form in 2\n variables over Integer Ring with coefficients:\n [ 1 2 ]\n [ * 3 ]\n sage: m = Matrix(ZZ, [[1, 2], [1, -1]])\n sage: f = B.lift_module_morphism(m, names=[\'x\',\'y\'])\n sage: A = f.domain(); A\n The Clifford algebra of the Quadratic form in 2\n variables over Integer Ring with coefficients:\n [ 6 0 ]\n [ * 3 ]\n sage: x, y = A.gens()\n sage: f(x)\n u + v\n sage: f(y)\n 2*u - v\n sage: f(x**2)\n 6\n sage: f(x*y)\n -3*u*v + 3\n sage: grA = A.graded_algebra(); grA\n The exterior algebra of rank 2 over Integer Ring\n sage: A.to_graded_conversion()(x)\n x\n sage: A.to_graded_conversion()(y)\n y\n sage: A.to_graded_conversion()(x*y)\n x*y\n sage: u = A.to_graded_conversion()(x*y+1); u\n x*y + 1\n sage: A.from_graded_conversion()(u)\n x*y + 1\n sage: A.projection(2)(x*y+1)\n x*y\n sage: A.projection(1)(x+2*y-2)\n x + 2*y\n sage: grf = A.induced_graded_map(B, f); grf\n Generic morphism:\n From: The exterior algebra of rank 2 over Integer Ring\n To: The exterior algebra of rank 2 over Integer Ring\n sage: grf(A.to_graded_conversion()(x))\n u + v\n sage: grf(A.to_graded_conversion()(y))\n 2*u - v\n sage: grf(A.to_graded_conversion()(x**2))\n 6\n sage: grf(A.to_graded_conversion()(x*y))\n -3*u*v\n sage: grf(grA.one())\n 1\n '
grA = self.graded_algebra()
grB = other.graded_algebra()
from sage.categories.graded_modules_with_basis import GradedModulesWithBasis
cat = GradedModulesWithBasis(self.base_ring())
from_gr = self.from_graded_conversion()
def on_basis(m):
i = grA.degree_on_basis(m)
lifted_img_of_m = f(from_gr(grA.monomial(m)))
return other.projection(i)(lifted_img_of_m)
return grA.module_morphism(on_basis=on_basis, codomain=grB, category=cat)
class ElementMethods():
pass
|
class FilteredHopfAlgebrasWithBasis(FilteredModulesCategory):
'\n The category of filtered Hopf algebras with a distinguished basis.\n\n A filtered Hopf algebra with basis over a commutative ring `R`\n is a filtered Hopf algebra over `R` (that is, a Hopf algebra\n equipped with a module filtration such that all structure\n maps of the Hopf algebra respect the filtration) equipped with\n an `R`-module basis that makes it a filtered `R`-module with\n basis (see\n :class:`~sage.categories.filtered_modules_with_basis.FilteredModulesWithBasis`\n for the notion of a filtered module with basis).\n\n EXAMPLES::\n\n sage: C = HopfAlgebrasWithBasis(ZZ).Filtered(); C\n Category of filtered Hopf algebras with basis over Integer Ring\n sage: C.super_categories()\n [Category of Hopf algebras with basis over Integer Ring,\n Category of filtered algebras with basis over Integer Ring,\n Category of filtered coalgebras with basis over Integer Ring]\n\n sage: C is HopfAlgebras(ZZ).WithBasis().Filtered()\n True\n sage: C is HopfAlgebras(ZZ).Filtered().WithBasis()\n False\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class WithRealizations(WithRealizationsCategory):
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: HopfAlgebrasWithBasis(QQ).Filtered().WithRealizations().super_categories()\n [Join of Category of Hopf algebras over Rational Field\n and Category of filtered algebras over Rational Field\n and Category of filtered coalgebras over Rational Field]\n\n TESTS::\n\n sage: TestSuite(HopfAlgebrasWithBasis(QQ).Filtered().WithRealizations()).run()\n '
from sage.categories.hopf_algebras import HopfAlgebras
R = self.base_category().base_ring()
return [HopfAlgebras(R).Filtered()]
class Connected(CategoryWithAxiom_over_base_ring):
class ParentMethods():
@cached_method
def antipode_on_basis(self, index):
'\n The antipode on the basis element indexed by ``index``.\n\n INPUT:\n\n - ``index`` -- an element of the index set\n\n For a filtered connected Hopf algebra, we can define\n an antipode recursively by\n\n .. MATH::\n\n S(x) := -\\sum_{x^L \\neq x} S(x^L) \\times x^R + \\epsilon(x)\n\n for all `x`, using the Sweedler notation.\n Also, `S(x) = x` for all `x` with `|x| = 0`.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.monomial(0).antipode() # indirect doctest\n P0\n sage: H.monomial(1).antipode() # indirect doctest\n -P1\n sage: H.monomial(2).antipode() # indirect doctest\n P2\n sage: H.monomial(3).antipode() # indirect doctest\n -P3\n '
if (self.monomial(index) == self.one()):
return self.one()
S = self.antipode_on_basis
x__S_Id = tensor([self, self]).module_morphism((lambda ab: (S(ab[0]) * self.monomial(ab[1]))), codomain=self)
smi = self.monomial(index)
return ((- x__S_Id((smi.coproduct() - tensor([smi, self.one()])))) + smi.counit())
def antipode(self, elem):
'\n Return the antipode of ``self`` applied to ``elem``.\n\n TESTS::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example() # needs sage.modules\n sage: H.antipode(H.monomial(14)) # needs sage.modules\n P14\n\n sage: H.monomial(0).antipode() # needs sage.modules\n P0\n sage: H.monomial(2).antipode() # needs sage.modules\n P2\n sage: (2*H.monomial(1) + 3*H.monomial(4)).antipode() # needs sage.modules\n -2*P1 + 3*P4\n '
return self.linear_combination(((self.antipode_on_basis(mon), coeff) for (mon, coeff) in elem.monomial_coefficients(copy=False).items()))
class ElementMethods():
pass
|
class FilteredModulesCategory(RegressiveCovariantConstructionCategory, Category_over_base_ring):
def __init__(self, base_category):
'\n EXAMPLES::\n\n sage: C = Algebras(QQ).Filtered()\n sage: C\n Category of filtered algebras over Rational Field\n sage: C.base_category()\n Category of algebras over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of algebras over Rational Field,\n Category of filtered vector spaces over Rational Field]\n\n sage: AlgebrasWithBasis(QQ).Filtered().base_ring()\n Rational Field\n sage: HopfAlgebrasWithBasis(QQ).Filtered().base_ring()\n Rational Field\n '
super().__init__(base_category, base_category.base_ring())
_functor_category = 'Filtered'
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Filtered() # indirect doctest\n Category of filtered algebras with basis over Rational Field\n '
return 'filtered {}'.format(self.base_category()._repr_object_names())
|
class FilteredModules(FilteredModulesCategory):
'\n The category of filtered modules over a given ring `R`.\n\n A *filtered module* over a ring `R` with a totally ordered\n indexing set `I` (typically `I = \\NN`) is an `R`-module `M` equipped\n with a family `(F_i)_{i \\in I}` of `R`-submodules satisfying\n `F_i \\subseteq F_j` for all `i,j \\in I` having `i \\leq j`, and\n `M = \\bigcup_{i \\in I} F_i`. This family is called a *filtration*\n of the given module `M`.\n\n EXAMPLES::\n\n sage: Modules(ZZ).Filtered()\n Category of filtered modules over Integer Ring\n sage: Modules(ZZ).Filtered().super_categories()\n [Category of modules over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).Filtered()).run()\n\n REFERENCES:\n\n - :wikipedia:`Filtration_(mathematics)`\n '
def extra_super_categories(self):
"\n Add :class:`VectorSpaces` to the super categories of ``self`` if\n the base ring is a field.\n\n EXAMPLES::\n\n sage: Modules(QQ).Filtered().is_subcategory(VectorSpaces(QQ))\n True\n sage: Modules(ZZ).Filtered().extra_super_categories()\n []\n\n This makes sure that ``Modules(QQ).Filtered()`` returns an\n instance of :class:`FilteredModules` and not a join category of\n an instance of this class and of ``VectorSpaces(QQ)``::\n\n sage: type(Modules(QQ).Filtered())\n <class 'sage.categories.vector_spaces.VectorSpaces.Filtered_with_category'>\n\n .. TODO::\n\n Get rid of this workaround once there is a more systematic\n approach for the alias ``Modules(QQ)`` -> ``VectorSpaces(QQ)``.\n Probably the latter should be a category with axiom, and\n covariant constructions should play well with axioms.\n "
from sage.categories.modules import Modules
from sage.categories.fields import Fields
base_ring = self.base_ring()
if (base_ring in Fields()):
return [Modules(base_ring)]
else:
return []
class SubcategoryMethods():
@cached_method
def Connected(self):
"\n Return the full subcategory of the connected objects of ``self``.\n\n A filtered `R`-module `M` with filtration\n `(F_0, F_1, F_2, \\ldots)` (indexed by `\\NN`)\n is said to be *connected* if `F_0` is isomorphic\n to `R`.\n\n EXAMPLES::\n\n sage: Modules(ZZ).Filtered().Connected()\n Category of filtered connected modules over Integer Ring\n sage: Coalgebras(QQ).Filtered().Connected()\n Category of filtered connected coalgebras over Rational Field\n sage: AlgebrasWithBasis(QQ).Filtered().Connected()\n Category of filtered connected algebras with basis over Rational Field\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).Filtered().Connected()).run()\n sage: Coalgebras(QQ).Filtered().Connected.__module__\n 'sage.categories.filtered_modules'\n "
return self._with_axiom('Connected')
class Connected(CategoryWithAxiom_over_base_ring):
pass
|
class FilteredModulesWithBasis(FilteredModulesCategory):
'\n The category of filtered modules with a distinguished basis.\n\n A *filtered module with basis* over a ring `R` means\n (for the purpose of this code) a filtered `R`-module `M`\n with filtration `(F_i)_{i \\in I}` (typically `I = \\NN`)\n endowed with a basis `(b_j)_{j \\in J}` of `M` and a partition\n `J = \\bigsqcup_{i \\in I} J_i` of the set `J` (it is allowed\n that some `J_i` are empty) such that for every `n \\in I`,\n the subfamily `(b_j)_{j \\in U_n}`, where\n `U_n = \\bigcup_{i \\leq n} J_i`, is a basis of the\n `R`-submodule `F_n`.\n\n For every `i \\in I`, the `R`-submodule of `M` spanned by\n `(b_j)_{j \\in J_i}` is called the `i`-*th graded component*\n (aka the `i`-*th homogeneous component*) of the filtered\n module with basis `M`; the elements of this submodule are\n referred to as *homogeneous elements of degree* `i`.\n The `R`-module `M` is the direct sum of its `i`-th graded\n components over all `i \\in I`, and thus becomes a graded\n `R`-module with basis.\n Conversely, any graded `R`-module with basis canonically\n becomes a filtered `R`-module with basis (by defining\n `F_n = \\bigoplus_{i \\leq n} G_i` where `G_i` is the `i`-th\n graded component, and defining `J_i` as the indexing set\n of the basis of the `i`-th graded component). Hence, the\n notion of a filtered `R`-module with basis is equivalent\n to the notion of a graded `R`-module with basis.\n\n However, the *category* of filtered `R`-modules with basis is not\n the category of graded `R`-modules with basis. Indeed, the *morphisms*\n of filtered `R`-modules with basis are defined to be morphisms of\n `R`-modules which send each `F_n` of the domain to the corresponding\n `F_n` of the target; in contrast, the morphisms of graded `R`-modules\n with basis must preserve each homogeneous component. Also,\n the notion of a filtered algebra with basis differs from\n that of a graded algebra with basis.\n\n .. NOTE::\n\n Currently, to make use of the functionality of this class,\n an instance of ``FilteredModulesWithBasis`` should fulfill\n the contract of a :class:`CombinatorialFreeModule` (most\n likely by inheriting from it). It should also have the\n indexing set `J` encoded as its ``_indices`` attribute,\n and ``_indices.subset(size=i)`` should yield the subset\n `J_i` (as an iterable). If the latter conditions are not\n satisfied, then :meth:`basis` must be overridden.\n\n .. NOTE::\n\n One should implement a ``degree_on_basis`` method in the parent\n class in order to fully utilize the methods of this category.\n This might become a required abstract method in the future.\n\n EXAMPLES::\n\n sage: C = ModulesWithBasis(ZZ).Filtered(); C\n Category of filtered modules with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of filtered modules over Integer Ring,\n Category of modules with basis over Integer Ring]\n sage: C is ModulesWithBasis(ZZ).Filtered()\n True\n\n TESTS::\n\n sage: C = ModulesWithBasis(ZZ).Filtered()\n sage: TestSuite(C).run()\n sage: C = ModulesWithBasis(QQ).Filtered()\n sage: TestSuite(C).run()\n '
class ParentMethods():
@cached_method
def basis(self, d=None):
"\n Return the basis for (the ``d``-th homogeneous component\n of) ``self``.\n\n INPUT:\n\n - ``d`` -- (optional, default ``None``) nonnegative integer\n or ``None``\n\n OUTPUT:\n\n If ``d`` is ``None``, returns the basis of the module.\n Otherwise, returns the basis of the homogeneous component\n of degree ``d`` (i.e., the subfamily of the basis of the\n whole module which consists only of the basis vectors\n lying in `F_d \\setminus \\bigcup_{i<d} F_i`).\n\n The basis is always returned as a family.\n\n EXAMPLES::\n\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: A.basis(4)\n Lazy family (Term map from Partitions to An example of a\n filtered module with basis: the free module on partitions\n over Integer Ring(i))_{i in Partitions of the integer 4}\n\n Without arguments, the full basis is returned::\n\n sage: A.basis()\n Lazy family (Term map from Partitions to An example of a\n filtered module with basis: the free module on partitions\n over Integer Ring(i))_{i in Partitions}\n sage: A.basis()\n Lazy family (Term map from Partitions to An example of a\n filtered module with basis: the free module on partitions\n over Integer Ring(i))_{i in Partitions}\n\n Checking this method on a filtered algebra. Note that this\n will typically raise a :class:`NotImplementedError` when this\n feature is not implemented. ::\n\n sage: A = AlgebrasWithBasis(ZZ).Filtered().example()\n sage: A.basis(4)\n Traceback (most recent call last):\n ...\n NotImplementedError: infinite set\n\n Without arguments, the full basis is returned::\n\n sage: A.basis()\n Lazy family (Term map from Free abelian monoid indexed by\n {'x', 'y', 'z'} to An example of a filtered algebra with\n basis: the universal enveloping algebra of Lie algebra\n of RR^3 with cross product over Integer Ring(i))_{i in\n Free abelian monoid indexed by {'x', 'y', 'z'}}\n\n An example with a graded algebra::\n\n sage: E.<x,y> = ExteriorAlgebra(QQ)\n sage: E.basis()\n Lazy family (Term map from Subsets of {0,1} to\n The exterior algebra of rank 2 over Rational Field(i))_{i in\n Subsets of {0,1}}\n "
if (d is None):
from sage.sets.family import Family
return Family(self._indices, self.monomial)
else:
return self.homogeneous_component_basis(d)
def homogeneous_component_basis(self, d):
"\n Return a basis for the ``d``-th homogeneous component of ``self``.\n\n EXAMPLES::\n\n sage: A = GradedModulesWithBasis(ZZ).example()\n sage: A.homogeneous_component_basis(4)\n Lazy family (Term map\n from Partitions\n to An example of a graded module with basis: the free module\n on partitions over Integer Ring(i))_{i in Partitions of the integer 4}\n\n sage: # needs sage.modules\n sage: cat = GradedModulesWithBasis(ZZ)\n sage: C = CombinatorialFreeModule(ZZ, ['a', 'b'], category=cat)\n sage: C.degree_on_basis = lambda x: 1 if x == 'a' else 2\n sage: C.homogeneous_component_basis(1)\n Finite family {'a': B['a']}\n sage: C.homogeneous_component_basis(2)\n Finite family {'b': B['b']}\n "
from sage.sets.family import Family
try:
S = self._indices.subset(size=d)
except (AttributeError, ValueError, TypeError):
S = [i for i in list(self._indices) if (self.degree_on_basis(i) == d)]
return Family(S, self.monomial)
def homogeneous_component(self, d):
'\n Return the ``d``-th homogeneous component of ``self``.\n\n EXAMPLES::\n\n sage: A = GradedModulesWithBasis(ZZ).example()\n sage: A.homogeneous_component(4)\n Degree 4 homogeneous component of An example of a graded module\n with basis: the free module on partitions over Integer Ring\n '
from sage.categories.modules_with_basis import ModulesWithBasis
from sage.categories.filtered_algebras import FilteredAlgebras
if (self.base_ring() in FilteredAlgebras):
raise NotImplementedError('this is only a natural module over the degree 0 component of the filtered algebra and coordinate rings are not yet implemented for submodules')
category = ModulesWithBasis(self.category().base_ring())
M = self.submodule(self.homogeneous_component_basis(d), category=category, already_echelonized=True)
M.rename('Degree {} homogeneous component of {}'.format(d, self))
return M
def graded_algebra(self):
'\n Return the associated graded module to ``self``.\n\n See :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`\n for the definition and the properties of this.\n\n If the filtered module ``self`` with basis is called `A`,\n then this method returns `\\operatorname{gr} A`. The method\n :meth:`to_graded_conversion` returns the canonical\n `R`-module isomorphism `A \\to \\operatorname{gr} A` induced\n by the basis of `A`, and the method\n :meth:`from_graded_conversion` returns the inverse of this\n isomorphism. The method :meth:`projection` projects\n elements of `A` onto `\\operatorname{gr} A` according to\n their place in the filtration on `A`.\n\n .. WARNING::\n\n When not overridden, this method returns the default\n implementation of an associated graded module --\n namely, ``AssociatedGradedAlgebra(self)``, where\n ``AssociatedGradedAlgebra`` is\n :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`.\n But some instances of :class:`FilteredModulesWithBasis`\n override this method, as the associated graded module\n often is (isomorphic) to a simpler object (for instance,\n the associated graded module of a graded module can be\n identified with the graded module itself). Generic code\n that uses associated graded modules (such as the code\n of the :meth:`induced_graded_map` method below) should\n make sure to only communicate with them via the\n :meth:`to_graded_conversion`,\n :meth:`from_graded_conversion` and\n :meth:`projection` methods (in particular,\n do not expect there to be a conversion from ``self``\n to ``self.graded_algebra()``; this currently does not\n work for Clifford algebras). Similarly, when\n overriding :meth:`graded_algebra`, make sure to\n accordingly redefine these three methods, unless their\n definitions below still apply to your case (this will\n happen whenever the basis of your :meth:`graded_algebra`\n has the same indexing set as ``self``, and the partition\n of this indexing set according to degree is the same as\n for ``self``).\n\n EXAMPLES::\n\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: A.graded_algebra()\n Graded Module of An example of a filtered module with basis:\n the free module on partitions over Integer Ring\n '
from sage.algebras.associated_graded import AssociatedGradedAlgebra
return AssociatedGradedAlgebra(self)
def to_graded_conversion(self):
'\n Return the canonical `R`-module isomorphism\n `A \\to \\operatorname{gr} A` induced by the basis of `A`\n (where `A = ` ``self``).\n\n This is an isomorphism of `R`-modules. See\n the class documentation :class:`AssociatedGradedAlgebra`.\n\n .. SEEALSO::\n\n :meth:`from_graded_conversion`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = Modules(QQ).WithBasis().Filtered().example()\n sage: p = -2 * A.an_element(); p\n -4*P[] - 4*P[1] - 6*P[2]\n sage: q = A.to_graded_conversion()(p); q\n -4*Bbar[[]] - 4*Bbar[[1]] - 6*Bbar[[2]]\n sage: q.parent() is A.graded_algebra()\n True\n '
base_one = self.base_ring().one()
return self.module_morphism(diagonal=(lambda x: base_one), codomain=self.graded_algebra())
def from_graded_conversion(self):
'\n Return the inverse of the canonical `R`-module isomorphism\n `A \\to \\operatorname{gr} A` induced by the basis of `A`\n (where `A = ` ``self``). This inverse is an isomorphism\n `\\operatorname{gr} A \\to A`.\n\n This is an isomorphism of `R`-modules. See\n the class documentation :class:`AssociatedGradedAlgebra`.\n\n .. SEEALSO::\n\n :meth:`to_graded_conversion`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = Modules(QQ).WithBasis().Filtered().example()\n sage: p = -2 * A.an_element(); p\n -4*P[] - 4*P[1] - 6*P[2]\n sage: q = A.to_graded_conversion()(p); q\n -4*Bbar[[]] - 4*Bbar[[1]] - 6*Bbar[[2]]\n sage: A.from_graded_conversion()(q) == p\n True\n sage: q.parent() is A.graded_algebra()\n True\n '
base_one = self.base_ring().one()
return self.graded_algebra().module_morphism(diagonal=(lambda x: base_one), codomain=self)
def projection(self, i):
'\n Return the `i`-th projection `p_i : F_i \\to G_i` (in the\n notations of the class documentation\n :class:`AssociatedGradedAlgebra`, where `A = ` ``self``).\n\n This method actually does not return the map `p_i` itself,\n but an extension of `p_i` to the whole `R`-module `A`.\n This extension is the composition of the `R`-module\n isomorphism `A \\to \\operatorname{gr} A` with the canonical\n projection of the graded `R`-module `\\operatorname{gr} A`\n onto its `i`-th graded component `G_i`. The codomain of\n this map is `\\operatorname{gr} A`, although its actual\n image is `G_i`. The map `p_i` is obtained from this map\n by restricting its domain to `F_i` and its image to `G_i`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = Modules(ZZ).WithBasis().Filtered().example()\n sage: p = -2 * A.an_element(); p\n -4*P[] - 4*P[1] - 6*P[2]\n sage: q = A.projection(2)(p); q\n -6*Bbar[[2]]\n sage: q.parent() is A.graded_algebra()\n True\n sage: A.projection(3)(p)\n 0\n '
base_zero = self.base_ring().zero()
base_one = self.base_ring().one()
grA = self.graded_algebra()
proj = (lambda x: (base_one if (self.degree_on_basis(x) == i) else base_zero))
return self.module_morphism(diagonal=proj, codomain=grA)
def induced_graded_map(self, other, f):
'\n Return the graded linear map between the associated graded\n modules of ``self`` and ``other`` canonically induced by\n the filtration-preserving map ``f : self -> other``.\n\n Let `A` and `B` be two filtered modules with basis, and let\n `(F_i)_{i \\in I}` and `(G_i)_{i \\in I}` be their\n filtrations. Let `f : A \\to B` be a linear map which\n preserves the filtration (i.e., satisfies `f(F_i) \\subseteq\n G_i` for all `i \\in I`). Then, there is a canonically\n defined graded linear map\n `\\operatorname{gr} f : \\operatorname{gr} A \\to\n \\operatorname{gr} B` which satisfies\n\n .. MATH::\n\n (\\operatorname{gr} f) (p_i(a)) = p_i(f(a))\n \\qquad \\text{for all } i \\in I \\text{ and } a \\in F_i ,\n\n where the `p_i` on the left hand side is the canonical\n projection from `F_i` onto the `i`-th graded component\n of `\\operatorname{gr} A`, while the `p_i` on the right\n hand side is the canonical projection from `G_i` onto\n the `i`-th graded component of `\\operatorname{gr} B`.\n\n INPUT:\n\n - ``other`` -- a filtered algebra with basis\n\n - ``f`` -- a filtration-preserving linear map from ``self``\n to ``other`` (can be given as a morphism or as a function)\n\n OUTPUT:\n\n The graded linear map `\\operatorname{gr} f`.\n\n EXAMPLES:\n\n **Example 1.**\n\n We start with the free `\\QQ`-module with basis the set of all\n partitions::\n\n sage: A = Modules(QQ).WithBasis().Filtered().example(); A # needs sage.combinat sage.modules\n An example of a filtered module with basis: the free module\n on partitions over Rational Field\n sage: M = A.indices(); M # needs sage.combinat sage.modules\n Partitions\n sage: p1, p2, p21, p321 = [A.basis()[Partition(i)] # needs sage.combinat sage.modules\n ....: for i in [[1], [2], [2,1], [3,2,1]]]\n\n Let us define a map from ``A`` to itself which acts on the\n basis by sending every partition `\\lambda` to the sum of\n the conjugates of all partitions `\\mu` for which\n `\\lambda / \\mu` is a horizontal strip::\n\n sage: # needs sage.combinat sage.modules\n sage: def map_on_basis(lam):\n ....: def mus(k):\n ....: return lam.remove_horizontal_border_strip(k)\n ....: return A.sum_of_monomials([Partition(mu).conjugate()\n ....: for k in range(sum(lam) + 1)\n ....: for mu in mus(k)])\n sage: f = A.module_morphism(on_basis=map_on_basis,\n ....: codomain=A)\n sage: f(p1)\n P[] + P[1]\n sage: f(p2)\n P[] + P[1] + P[1, 1]\n sage: f(p21)\n P[1] + P[1, 1] + P[2] + P[2, 1]\n sage: f(p21 - p1)\n -P[] + P[1, 1] + P[2] + P[2, 1]\n sage: f(p321)\n P[2, 1] + P[2, 1, 1] + P[2, 2] + P[2, 2, 1]\n + P[3, 1] + P[3, 1, 1] + P[3, 2] + P[3, 2, 1]\n\n We now compute `\\operatorname{gr} f` ::\n\n sage: # needs sage.combinat sage.modules\n sage: grA = A.graded_algebra(); grA\n Graded Module of An example of a filtered module with basis:\n the free module on partitions over Rational Field\n sage: pp1, pp2, pp21, pp321 = [A.to_graded_conversion()(i)\n ....: for i in [p1, p2, p21, p321]]\n sage: pp2 + 4 * pp21\n Bbar[[2]] + 4*Bbar[[2, 1]]\n sage: grf = A.induced_graded_map(A, f); grf\n Generic endomorphism of Graded Module of\n An example of a filtered module with basis:\n the free module on partitions over Rational Field\n sage: grf(pp1)\n Bbar[[1]]\n sage: grf(pp2 + 4 * pp21)\n Bbar[[1, 1]] + 4*Bbar[[2, 1]]\n\n **Example 2.**\n\n We shall now construct `\\operatorname{gr} f` for a\n different map `f` out of the same ``A``; the new map\n `f` will lead into a graded algebra already, namely into\n the algebra of symmetric functions::\n\n sage: # needs sage.combinat sage.modules\n sage: h = SymmetricFunctions(QQ).h()\n sage: def map_on_basis(lam): # redefining map_on_basis\n ....: def mus(k):\n ....: return lam.remove_horizontal_border_strip(k)\n ....: return h.sum_of_monomials([Partition(mu).conjugate()\n ....: for k in range(sum(lam) + 1)\n ....: for mu in mus(k)])\n sage: f = A.module_morphism(on_basis=map_on_basis,\n ....: codomain=h) # redefining f\n sage: f(p1)\n h[] + h[1]\n sage: f(p2)\n h[] + h[1] + h[1, 1]\n sage: f(A.zero())\n 0\n sage: f(p2 - 3*p1)\n -2*h[] - 2*h[1] + h[1, 1]\n\n The algebra ``h`` of symmetric functions in the `h`-basis\n is already graded, so its associated graded algebra is\n implemented as itself::\n\n sage: # needs sage.combinat sage.modules\n sage: grh = h.graded_algebra(); grh is h\n True\n sage: grf = A.induced_graded_map(h, f); grf\n Generic morphism:\n From: Graded Module of An example of a filtered\n module with basis: the free module on partitions\n over Rational Field\n To: Symmetric Functions over Rational Field\n in the homogeneous basis\n sage: grf(pp1)\n h[1]\n sage: grf(pp2)\n h[1, 1]\n sage: grf(pp321)\n h[3, 2, 1]\n sage: grf(pp2 - 3*pp1)\n -3*h[1] + h[1, 1]\n sage: grf(pp21)\n h[2, 1]\n sage: grf(grA.zero())\n 0\n\n **Example 3.**\n\n After having had a graded module as the codomain, let us try to\n have one as the domain instead. Our new ``f`` will go from ``h``\n to ``A``::\n\n sage: # needs sage.combinat sage.modules\n sage: def map_on_basis(lam): # redefining map_on_basis\n ....: def mus(k):\n ....: return lam.remove_horizontal_border_strip(k)\n ....: return A.sum_of_monomials([Partition(mu).conjugate()\n ....: for k in range(sum(lam) + 1)\n ....: for mu in mus(k)])\n sage: f = h.module_morphism(on_basis=map_on_basis,\n ....: codomain=A) # redefining f\n sage: f(h[1])\n P[] + P[1]\n sage: f(h[2])\n P[] + P[1] + P[1, 1]\n sage: f(h[1, 1])\n P[1] + P[2]\n sage: f(h[2, 2])\n P[1, 1] + P[2, 1] + P[2, 2]\n sage: f(h[3, 2, 1])\n P[2, 1] + P[2, 1, 1] + P[2, 2] + P[2, 2, 1]\n + P[3, 1] + P[3, 1, 1] + P[3, 2] + P[3, 2, 1]\n sage: f(h.one())\n P[]\n sage: grf = h.induced_graded_map(A, f); grf\n Generic morphism:\n From: Symmetric Functions over Rational Field\n in the homogeneous basis\n To: Graded Module of An example of a filtered\n module with basis: the free module on partitions\n over Rational Field\n sage: grf(h[1])\n Bbar[[1]]\n sage: grf(h[2])\n Bbar[[1, 1]]\n sage: grf(h[1, 1])\n Bbar[[2]]\n sage: grf(h[2, 2])\n Bbar[[2, 2]]\n sage: grf(h[3, 2, 1])\n Bbar[[3, 2, 1]]\n sage: grf(h.one())\n Bbar[[]]\n\n **Example 4.**\n\n The construct `\\operatorname{gr} f` also makes sense when `f`\n is a filtration-preserving map between graded modules. ::\n\n sage: # needs sage.combinat sage.modules\n sage: def map_on_basis(lam): # redefining map_on_basis\n ....: def mus(k):\n ....: return lam.remove_horizontal_border_strip(k)\n ....: return h.sum_of_monomials([Partition(mu).conjugate()\n ....: for k in range(sum(lam) + 1)\n ....: for mu in mus(k)])\n sage: f = h.module_morphism(on_basis=map_on_basis,\n ....: codomain=h) # redefining f\n sage: f(h[1])\n h[] + h[1]\n sage: f(h[2])\n h[] + h[1] + h[1, 1]\n sage: f(h[1, 1])\n h[1] + h[2]\n sage: f(h[2, 1])\n h[1] + h[1, 1] + h[2] + h[2, 1]\n sage: f(h.one())\n h[]\n sage: grf = h.induced_graded_map(h, f); grf\n Generic endomorphism of\n Symmetric Functions over Rational Field in the homogeneous basis\n sage: grf(h[1])\n h[1]\n sage: grf(h[2])\n h[1, 1]\n sage: grf(h[1, 1])\n h[2]\n sage: grf(h[2, 1])\n h[2, 1]\n sage: grf(h.one())\n h[]\n '
grA = self.graded_algebra()
grB = other.graded_algebra()
from sage.categories.graded_modules_with_basis import GradedModulesWithBasis
cat = GradedModulesWithBasis(self.base_ring())
from_gr = self.from_graded_conversion()
def on_basis(m):
i = grA.degree_on_basis(m)
lifted_img_of_m = f(from_gr(grA.monomial(m)))
return other.projection(i)(lifted_img_of_m)
return grA.module_morphism(on_basis=on_basis, codomain=grB, category=cat)
class ElementMethods():
def is_homogeneous(self):
'\n Return whether the element ``self`` is homogeneous.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A(Partition((3,2,1)))\n sage: y = A(Partition((4,4,1)))\n sage: z = A(Partition((2,2,2)))\n sage: (3*x).is_homogeneous()\n True\n sage: (x - y).is_homogeneous()\n False\n sage: (x+2*z).is_homogeneous()\n True\n\n Here is an example with a graded algebra::\n\n sage: # needs sage.combinat sage.modules\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: (x, y) = (S[2], S[3])\n sage: (3*x).is_homogeneous()\n True\n sage: (x^3 - y^2).is_homogeneous()\n True\n sage: ((x + y)^2).is_homogeneous()\n False\n\n Let us now test a filtered algebra (but remember that the\n notion of homogeneity now depends on the choice of a\n basis, or at least on a definition of homogeneous\n components)::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: x,y,z = A.algebra_generators()\n sage: (x*y).is_homogeneous()\n True\n sage: (y*x).is_homogeneous()\n False\n sage: A.one().is_homogeneous()\n True\n sage: A.zero().is_homogeneous()\n True\n sage: (A.one()+x).is_homogeneous()\n False\n '
degree_on_basis = self.parent().degree_on_basis
degree = None
for m in self.support():
if (degree is None):
degree = degree_on_basis(m)
elif (degree != degree_on_basis(m)):
return False
return True
@abstract_method(optional=True)
def degree_on_basis(self, m):
'\n Return the degree of the basis element indexed by ``m``\n in ``self``.\n\n EXAMPLES::\n\n sage: A = GradedModulesWithBasis(QQ).example() # needs sage.combinat sage.modules\n sage: A.degree_on_basis(Partition((2,1))) # needs sage.combinat sage.modules\n 3\n sage: A.degree_on_basis(Partition((4,2,1,1,1,1))) # needs sage.combinat sage.modules\n 10\n '
def homogeneous_degree(self):
'\n The degree of a nonzero homogeneous element ``self`` in the\n filtered module.\n\n .. NOTE::\n\n This raises an error if the element is not homogeneous.\n To compute the maximum of the degrees of the homogeneous\n summands of a (not necessarily homogeneous) element, use\n :meth:`maximal_degree` instead.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A(Partition((3,2,1)))\n sage: y = A(Partition((4,4,1)))\n sage: z = A(Partition((2,2,2)))\n sage: x.degree()\n 6\n sage: (x + 2*z).degree()\n 6\n sage: (y - x).degree()\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n\n An example in a graded algebra::\n\n sage: # needs sage.combinat sage.modules\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: (x, y) = (S[2], S[3])\n sage: x.homogeneous_degree()\n 2\n sage: (x^3 + 4*y^2).homogeneous_degree()\n 6\n sage: ((1 + x)^3).homogeneous_degree()\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n\n Let us now test a filtered algebra (but remember that the\n notion of homogeneity now depends on the choice of a\n basis)::\n\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: x,y,z = A.algebra_generators()\n sage: (x*y).homogeneous_degree()\n 2\n sage: (y*x).homogeneous_degree()\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n sage: A.one().homogeneous_degree()\n 0\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S() # needs sage.combinat sage.modules\n sage: S.zero().degree() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n ValueError: the zero element does not have a well-defined degree\n '
if (not self.support()):
raise ValueError('the zero element does not have a well-defined degree')
if (not self.is_homogeneous()):
raise ValueError('element is not homogeneous')
return self.parent().degree_on_basis(self.leading_support())
degree = homogeneous_degree
def maximal_degree(self):
'\n The maximum of the degrees of the homogeneous components\n of ``self``.\n\n This is also the smallest `i` such that ``self`` belongs\n to `F_i`. Hence, it does not depend on the basis of the\n parent of ``self``.\n\n .. SEEALSO:: :meth:`homogeneous_degree`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A(Partition((3,2,1)))\n sage: y = A(Partition((4,4,1)))\n sage: z = A(Partition((2,2,2)))\n sage: x.maximal_degree()\n 6\n sage: (x + 2*z).maximal_degree()\n 6\n sage: (y - x).maximal_degree()\n 9\n sage: (3*z).maximal_degree()\n 6\n\n Now, we test this on a graded algebra::\n\n sage: # needs sage.combinat sage.modules\n sage: S = NonCommutativeSymmetricFunctions(QQ).S()\n sage: (x, y) = (S[2], S[3])\n sage: x.maximal_degree()\n 2\n sage: (x^3 + 4*y^2).maximal_degree()\n 6\n sage: ((1 + x)^3).maximal_degree()\n 6\n\n Let us now test a filtered algebra::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).Filtered().example()\n sage: x,y,z = A.algebra_generators()\n sage: (x*y).maximal_degree()\n 2\n sage: (y*x).maximal_degree()\n 2\n sage: A.one().maximal_degree()\n 0\n sage: A.zero().maximal_degree()\n Traceback (most recent call last):\n ...\n ValueError: the zero element does not have a well-defined degree\n sage: (A.one()+x).maximal_degree()\n 1\n\n TESTS::\n\n sage: S = NonCommutativeSymmetricFunctions(QQ).S() # needs sage.combinat sage.modules\n sage: S.zero().degree() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n ValueError: the zero element does not have a well-defined degree\n '
if self.is_zero():
raise ValueError('the zero element does not have a well-defined degree')
degree_on_basis = self.parent().degree_on_basis
return max((degree_on_basis(m) for m in self.support()))
def homogeneous_component(self, n):
"\n Return the homogeneous component of degree ``n`` of the\n element ``self``.\n\n Let `m` be an element of a filtered `R`-module `M` with\n basis. Then, `m` can be uniquely written in the form\n `m = \\sum_{i \\in I} m_i`, where each `m_i` is a\n homogeneous element of degree `i`. For `n \\in I`, we\n define the homogeneous component of degree `n` of the\n element `m` to be `m_n`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A.an_element(); x\n 2*P[] + 2*P[1] + 3*P[2]\n sage: x.homogeneous_component(-1)\n 0\n sage: x.homogeneous_component(0)\n 2*P[]\n sage: x.homogeneous_component(1)\n 2*P[1]\n sage: x.homogeneous_component(2)\n 3*P[2]\n sage: x.homogeneous_component(3)\n 0\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Graded().example()\n sage: x = A.an_element(); x\n 2*P[] + 2*P[1] + 3*P[2]\n sage: x.homogeneous_component(-1)\n 0\n sage: x.homogeneous_component(0)\n 2*P[]\n sage: x.homogeneous_component(1)\n 2*P[1]\n sage: x.homogeneous_component(2)\n 3*P[2]\n sage: x.homogeneous_component(3)\n 0\n\n sage: A = AlgebrasWithBasis(ZZ).Filtered().example()\n sage: G = A.algebra_generators()\n sage: g = A.an_element() - 2 * G['x'] * G['y']; g\n U['x']^2*U['y']^2*U['z']^3 - 2*U['x']*U['y']\n + 2*U['x'] + 3*U['y'] + 1\n sage: g.homogeneous_component(-1)\n 0\n sage: g.homogeneous_component(0)\n 1\n sage: g.homogeneous_component(2)\n -2*U['x']*U['y']\n sage: g.homogeneous_component(5)\n 0\n sage: g.homogeneous_component(7)\n U['x']^2*U['y']^2*U['z']^3\n sage: g.homogeneous_component(8)\n 0\n\n TESTS:\n\n Check that this really returns ``A.zero()`` and not a plain ``0``::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A.an_element()\n sage: x.homogeneous_component(3).parent() is A\n True\n "
degree_on_basis = self.parent().degree_on_basis
return self.parent().sum_of_terms(((i, c) for (i, c) in self if (degree_on_basis(i) == n)))
def truncate(self, n):
"\n Return the sum of the homogeneous components of degree\n strictly less than ``n`` of ``self``.\n\n See :meth:`homogeneous_component` for the notion of a\n homogeneous component.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A.an_element(); x\n 2*P[] + 2*P[1] + 3*P[2]\n sage: x.truncate(0)\n 0\n sage: x.truncate(1)\n 2*P[]\n sage: x.truncate(2)\n 2*P[] + 2*P[1]\n sage: x.truncate(3)\n 2*P[] + 2*P[1] + 3*P[2]\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Graded().example()\n sage: x = A.an_element(); x\n 2*P[] + 2*P[1] + 3*P[2]\n sage: x.truncate(0)\n 0\n sage: x.truncate(1)\n 2*P[]\n sage: x.truncate(2)\n 2*P[] + 2*P[1]\n sage: x.truncate(3)\n 2*P[] + 2*P[1] + 3*P[2]\n\n sage: A = AlgebrasWithBasis(ZZ).Filtered().example()\n sage: G = A.algebra_generators()\n sage: g = A.an_element() - 2 * G['x'] * G['y']; g\n U['x']^2*U['y']^2*U['z']^3 - 2*U['x']*U['y']\n + 2*U['x'] + 3*U['y'] + 1\n sage: g.truncate(-1)\n 0\n sage: g.truncate(0)\n 0\n sage: g.truncate(2)\n 2*U['x'] + 3*U['y'] + 1\n sage: g.truncate(3)\n -2*U['x']*U['y'] + 2*U['x'] + 3*U['y'] + 1\n sage: g.truncate(5)\n -2*U['x']*U['y'] + 2*U['x'] + 3*U['y'] + 1\n sage: g.truncate(7)\n -2*U['x']*U['y'] + 2*U['x'] + 3*U['y'] + 1\n sage: g.truncate(8)\n U['x']^2*U['y']^2*U['z']^3 - 2*U['x']*U['y']\n + 2*U['x'] + 3*U['y'] + 1\n\n TESTS:\n\n Check that this really return ``A.zero()`` and not a plain ``0``::\n\n sage: # needs sage.combinat sage.modules\n sage: A = ModulesWithBasis(ZZ).Filtered().example()\n sage: x = A.an_element()\n sage: x.truncate(0).parent() is A\n True\n "
degree_on_basis = self.parent().degree_on_basis
return self.parent().sum_of_terms(((i, c) for (i, c) in self if (degree_on_basis(i) < n)))
class Subobjects(SubobjectsCategory):
class ParentMethods():
def degree_on_basis(self, m):
'\n Return the degree of the basis element indexed by ``m``\n in ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z, y])\n sage: B = S.basis()\n sage: [B[0].lift(), B[1].lift(), B[2].lift()]\n [x, y, x*y - y*z]\n sage: S.degree_on_basis(0)\n 1\n sage: S.degree_on_basis(1)\n 1\n sage: S.degree_on_basis(2)\n 2\n '
return self.basis()[m].lift().degree()
class ElementMethods():
def degree(self):
'\n Return the degree of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z, y])\n sage: B = S.basis()\n sage: [B[0].lift(), B[1].lift(), B[2].lift()]\n [x, y, x*y - y*z]\n sage: B[0].degree()\n 1\n sage: B[1].degree()\n 1\n sage: (B[0] + 3*B[1]).degree()\n 1\n\n The degree of inhomogeneous elements is not defined\n (following the behavior of the exterior algebra)::\n\n sage: (B[0] + B[2]).degree() # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n\n We can still get the maximal degree::\n\n sage: (B[0] + B[2]).maximal_degree() # needs sage.modules\n 2\n '
return self.lift().degree()
def maximal_degree(self):
'\n The maximum of the degrees of the homogeneous components\n of ``self``.\n\n This is also the smallest `i` such that ``self`` belongs\n to `F_i`. Hence, it does not depend on the basis of the\n parent of ``self``.\n\n .. SEEALSO:: :meth:`homogeneous_degree`\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: F = E.submodule([x + 1, x*y - 1])\n sage: B = F.basis()\n sage: [B[0].lift(), B[1].lift()]\n [-x*y + 1, x*y + x]\n sage: B[0].maximal_degree()\n 2\n sage: B[1].maximal_degree()\n 2\n '
return self.lift().maximal_degree()
|
class FiniteComplexReflectionGroups(CategoryWithAxiom):
"\n The category of finite complex reflection groups.\n\n See :class:`ComplexReflectionGroups` for the definition of complex\n reflection group. In the finite case, most of the information\n about the group can be recovered from its *degrees* and\n *codegrees*, and to a lesser extent to the explicit realization as\n subgroup of `GL(V)`. Hence the most important optional methods to\n implement are:\n\n - :meth:`ComplexReflectionGroups.Finite.ParentMethods.degrees`,\n - :meth:`ComplexReflectionGroups.Finite.ParentMethods.codegrees`,\n - :meth:`ComplexReflectionGroups.Finite.ElementMethods.to_matrix`.\n\n Finite complex reflection groups are completely classified. In\n particular, if the group is irreducible, then it's uniquely\n determined by its degrees and codegrees and whether it's\n reflection representation is *primitive* or not (see [LT2009]_\n Chapter 2.1 for the definition of primitive).\n\n .. SEEALSO:: :wikipedia:`Complex_reflection_groups`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().Finite()\n Category of finite complex reflection groups\n sage: ComplexReflectionGroups().Finite().super_categories()\n [Category of complex reflection groups,\n Category of finite groups,\n Category of finite finitely generated semigroups]\n\n An example of a finite reflection group::\n\n sage: W = ComplexReflectionGroups().Finite().example(); W # optional - gap3\n Reducible real reflection group of rank 4 and type A2 x B2\n\n sage: W.reflections() # optional - gap3\n Finite family {1: (1,8)(2,5)(9,12), 2: (1,5)(2,9)(8,12),\n 3: (3,10)(4,7)(11,14), 4: (3,6)(4,11)(10,13),\n 5: (1,9)(2,8)(5,12), 6: (4,14)(6,13)(7,11),\n 7: (3,13)(6,10)(7,14)}\n\n ``W`` is in the category of complex reflection groups::\n\n sage: W in ComplexReflectionGroups().Finite() # optional - gap3\n True\n "
def example(self):
'\n Return an example of a complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: ComplexReflectionGroups().Finite().example() # optional - gap3\n Reducible real reflection group of rank 4 and type A2 x B2\n '
from sage.combinat.root_system.reflection_group_real import ReflectionGroup
return ReflectionGroup((1, 1, 3), (2, 1, 2))
class SubcategoryMethods():
@cached_method
def WellGenerated(self):
"\n Return the full subcategory of well-generated objects of ``self``.\n\n A finite complex generated group is *well generated* if it\n is isomorphic to a subgroup of the general linear group\n `GL_n` generated by `n` reflections.\n\n .. SEEALSO::\n\n :meth:`ComplexReflectionGroups.Finite.ParentMethods.is_well_generated`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: C = ComplexReflectionGroups().Finite().WellGenerated(); C\n Category of well generated finite complex reflection groups\n\n Here is an example of a finite well-generated complex\n reflection group::\n\n sage: W = C.example(); W # optional - gap3\n Reducible complex reflection group of rank 4 and type A2 x G(3,1,2)\n\n All finite Coxeter groups are well generated::\n\n sage: CoxeterGroups().Finite().is_subcategory(C)\n True\n sage: SymmetricGroup(3) in C # needs sage.groups\n True\n\n .. NOTE::\n\n The category of well generated finite complex\n reflection groups is currently implemented as an\n axiom. See discussion on :trac:`11187`. This may be a\n bit of overkill. Still it's nice to have a full\n subcategory.\n\n TESTS::\n\n sage: TestSuite(W).run() # optional - gap3\n sage: C = ComplexReflectionGroups().Finite().WellGenerated()\n sage: TestSuite(C).run()\n sage: CoxeterGroups().Finite().WellGenerated.__module__\n 'sage.categories.finite_complex_reflection_groups'\n\n We check that the axioms are properly ordered in\n ``sage.categories.category_with_axiom.axioms`` and yield\n desired output (well generated does not appear)::\n\n sage: CoxeterGroups().Finite()\n Category of finite Coxeter groups\n "
return self._with_axiom('WellGenerated')
class ParentMethods():
@abstract_method(optional=True)
def degrees(self):
'\n Return the degrees of ``self``.\n\n OUTPUT: a tuple of Sage integers\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,4) # needs sage.combinat\n sage: W.degrees() # needs sage.combinat\n (2, 3, 4)\n\n sage: W = ColoredPermutations(3,3) # needs sage.combinat\n sage: W.degrees() # needs sage.combinat\n (3, 6, 9)\n\n sage: W = ReflectionGroup(31) # optional - gap3\n sage: W.degrees() # optional - gap3\n (8, 12, 20, 24)\n '
@abstract_method(optional=True)
def codegrees(self):
'\n Return the codegrees of ``self``.\n\n OUTPUT: a tuple of Sage integers\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,4) # needs sage.combinat\n sage: W.codegrees() # needs sage.combinat\n (2, 1, 0)\n\n sage: W = ColoredPermutations(3,3) # needs sage.combinat\n sage: W.codegrees() # needs sage.combinat\n (6, 3, 0)\n\n sage: W = ReflectionGroup(31) # optional - gap3\n sage: W.codegrees() # optional - gap3\n (28, 16, 12, 0)\n '
def _test_degrees(self, **options):
'\n Test the method :meth:`degrees`.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().Finite().example(); W # optional - gap3\n Reducible real reflection group of rank 4 and type A2 x B2\n sage: W._test_degrees() # optional - gap3\n\n sage: W = SymmetricGroup(5) # needs sage.groups\n sage: W._test_degrees() # needs sage.groups\n\n We now break the implementation of W.degrees and check that this is caught::\n\n sage: W.degrees = lambda: (1/1,5) # needs sage.groups\n sage: W._test_degrees() # needs sage.groups\n Traceback (most recent call last):\n ...\n AssertionError: the degrees should be integers\n\n sage: W.degrees = lambda: (1,2,3) # needs sage.groups\n sage: W._test_degrees() # needs sage.groups\n Traceback (most recent call last):\n ...\n AssertionError: the degrees should be larger than 2\n\n We restore W to its normal state::\n\n sage: del W.degrees # needs sage.groups\n sage: W._test_degrees() # needs sage.groups\n\n See the documentation for :class:`TestSuite` for more information.\n '
from sage.structure.element import parent
from sage.rings.integer_ring import ZZ
tester = self._tester(**options)
degrees = self.degrees()
tester.assertIsInstance(degrees, tuple, 'the degrees method should return a tuple')
tester.assertTrue(all(((parent(d) is ZZ) for d in degrees)), 'the degrees should be integers')
tester.assertTrue(all(((d >= 2) for d in degrees)), 'the degrees should be larger than 2')
tester.assertEqual(len(degrees), self.rank(), 'the number of degrees should coincide with the rank')
tester.assertEqual(sum(((d - 1) for d in degrees)), self.number_of_reflections(), 'the sum of the degrees should be consistent with the number of reflections')
def _test_codegrees(self, **options):
'\n Test the method :meth:`degrees`.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: W = ComplexReflectionGroups().Finite().example(); W # optional - gap3\n Reducible real reflection group of rank 4 and type A2 x B2\n sage: W._test_codegrees() # optional - gap3\n\n sage: W = SymmetricGroup(5) # needs sage.groups\n sage: W._test_codegrees() # needs sage.groups\n\n We now break the implementation of W.degrees and check that this is caught::\n\n sage: W.codegrees = lambda: (1/1,5) # needs sage.groups\n sage: W._test_codegrees() # needs sage.groups\n Traceback (most recent call last):\n ...\n AssertionError: the codegrees should be integers\n\n sage: W.codegrees = lambda: (2,1,-1) # needs sage.groups\n sage: W._test_codegrees() # needs sage.groups\n Traceback (most recent call last):\n ...\n AssertionError: the codegrees should be nonnegative\n\n We restore W to its normal state::\n\n sage: del W.codegrees # needs sage.groups\n sage: W._test_codegrees() # needs sage.groups\n\n See the documentation for :class:`TestSuite` for more information.\n '
from sage.structure.element import parent
from sage.rings.integer_ring import ZZ
tester = self._tester(**options)
codegrees = self.codegrees()
tester.assertIsInstance(codegrees, tuple, 'the codegrees method should return a tuple')
tester.assertTrue(all(((parent(d) is ZZ) for d in codegrees)), 'the codegrees should be integers')
tester.assertTrue(all(((d >= 0) for d in codegrees)), 'the codegrees should be nonnegative')
tester.assertEqual(len(codegrees), self.rank(), 'the number of codegrees should coincide with the rank')
tester.assertEqual(sum(((d + 1) for d in codegrees)), self.number_of_reflection_hyperplanes(), 'the sum of the codegrees should be consistent with the number of reflection hyperplanes')
@cached_method
def number_of_reflection_hyperplanes(self):
'\n Return the number of reflection hyperplanes of ``self``.\n\n This is also the number of distinguished reflections. For\n real groups, this coincides with the number of\n reflections.\n\n This implementation uses that it is given by the sum of\n the codegrees of ``self`` plus its rank.\n\n .. SEEALSO:: :meth:`number_of_reflections`\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: W = ColoredPermutations(1,3)\n sage: W.number_of_reflection_hyperplanes()\n 3\n sage: W = ColoredPermutations(2,3)\n sage: W.number_of_reflection_hyperplanes()\n 9\n sage: W = ColoredPermutations(4,3)\n sage: W.number_of_reflection_hyperplanes()\n 15\n sage: W = ReflectionGroup((4,2,3)) # optional - gap3\n sage: W.number_of_reflection_hyperplanes() # optional - gap3\n 15\n '
from sage.rings.integer_ring import ZZ
return ZZ.sum(((codeg + 1) for codeg in self.codegrees()))
@cached_method
def number_of_reflections(self):
'\n Return the number of reflections of ``self``.\n\n For real groups, this coincides with the number of\n reflection hyperplanes.\n\n This implementation uses that it is given by the sum of\n the degrees of ``self`` minus its rank.\n\n .. SEEALSO:: :meth:`number_of_reflection_hyperplanes`\n\n EXAMPLES::\n\n sage: [SymmetricGroup(i).number_of_reflections() # needs sage.groups\n ....: for i in range(int(8))]\n [0, 0, 1, 3, 6, 10, 15, 21]\n\n sage: # needs sage.combinat sage.groups\n sage: W = ColoredPermutations(1,3)\n sage: W.number_of_reflections()\n 3\n sage: W = ColoredPermutations(2,3)\n sage: W.number_of_reflections()\n 9\n sage: W = ColoredPermutations(4,3)\n sage: W.number_of_reflections()\n 21\n sage: W = ReflectionGroup((4,2,3)) # optional - gap3\n sage: W.number_of_reflections() # optional - gap3\n 15\n '
from sage.rings.integer_ring import ZZ
return ZZ.sum(((deg - 1) for deg in self.degrees()))
@cached_method
def rank(self):
'\n Return the rank of ``self``.\n\n The rank of ``self`` is the dimension of the smallest\n faithfull reflection representation of ``self``.\n\n This default implementation uses that the rank is the\n number of :meth:`degrees`.\n\n .. SEEALSO:: :meth:`ComplexReflectionGroups.rank`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = ColoredPermutations(1,3)\n sage: W.rank()\n 2\n sage: W = ColoredPermutations(2,3)\n sage: W.rank()\n 3\n sage: W = ColoredPermutations(4,3)\n sage: W.rank()\n 3\n\n sage: # optional - gap3, needs sage.combinat sage.groups\n sage: W = ReflectionGroup((4,2,3))\n sage: W.rank()\n 3\n '
return len(self.degrees())
@cached_method
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n It is given by the product of the degrees of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: W = ColoredPermutations(1,3)\n sage: W.cardinality()\n 6\n sage: W = ColoredPermutations(2,3)\n sage: W.cardinality()\n 48\n sage: W = ColoredPermutations(4,3)\n sage: W.cardinality()\n 384\n\n sage: # optional - gap3, needs sage.combinat sage.groups\n sage: W = ReflectionGroup((4,2,3))\n sage: W.cardinality()\n 192\n '
from sage.rings.integer_ring import ZZ
return ZZ.prod(self.degrees())
def is_well_generated(self) -> bool:
'\n Return whether ``self`` is well-generated.\n\n A finite complex reflection group is *well generated* if\n the number of its simple reflections coincides with its rank.\n\n .. SEEALSO:: :meth:`ComplexReflectionGroups.Finite.WellGenerated`\n\n .. NOTE::\n\n - All finite real reflection groups are well generated.\n - The complex reflection groups of type `G(r,1,n)` and\n of type `G(r,r,n)` are well generated.\n - The complex reflection groups of type `G(r,p,n)`\n with `1 < p < r` are *not* well generated.\n\n - The direct product of two well generated finite\n complex reflection group is still well generated.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: W.is_well_generated() # needs sage.combinat\n True\n\n sage: W = ColoredPermutations(4,3) # needs sage.combinat\n sage: W.is_well_generated() # needs sage.combinat\n True\n\n sage: # optional - gap3, needs sage.combinat sage.groups\n sage: W = ReflectionGroup((4,2,3))\n sage: W.is_well_generated()\n False\n sage: W = ReflectionGroup((4,4,3))\n sage: W.is_well_generated()\n True\n '
return (self.number_of_simple_reflections() == self.rank())
def is_real(self):
'\n Return whether ``self`` is real.\n\n A complex reflection group is *real* if it is isomorphic\n to a reflection group in `GL(V)` over a real vector space `V`.\n Equivalently its character table has real entries.\n\n This implementation uses the following statement: an\n irreducible complex reflection group is real if and only\n if `2` is a degree of ``self`` with multiplicity one.\n Hence, in general we just need to compare the number of\n occurrences of `2` as degree of ``self`` and the number of\n irreducible components.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: W.is_real() # needs sage.combinat\n True\n\n sage: W = ColoredPermutations(4,3) # needs sage.combinat\n sage: W.is_real() # needs sage.combinat sage.groups\n False\n\n .. TODO::\n\n Add an example of non real finite complex reflection\n group that is generated by order 2 reflections.\n '
return (self.degrees().count(2) == self.number_of_irreducible_components())
@cached_method
def base_change_matrix(self):
'\n Return the base change from the standard basis of the vector\n space of ``self`` to the basis given by the independent roots of\n ``self``.\n\n .. TODO::\n\n For non-well-generated groups there is a conflict with\n construction of the matrix for an element.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: W.base_change_matrix() # optional - gap3\n [1 0]\n [0 1]\n\n sage: W = ReflectionGroup(23) # optional - gap3\n sage: W.base_change_matrix() # optional - gap3\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n sage: W = ReflectionGroup((3,1,2)) # optional - gap3\n sage: W.base_change_matrix() # optional - gap3\n [1 0]\n [1 1]\n\n sage: W = ReflectionGroup((4,2,2)) # optional - gap3\n sage: W.base_change_matrix() # optional - gap3\n [ 1 0]\n [E(4) 1]\n '
from sage.matrix.constructor import Matrix
return Matrix(list(self.independent_roots())).inverse()
def milnor_fiber_poset(self):
'\n Return the Milnor fiber poset of ``self``.\n\n The *Milnor fiber poset* of a finite complex reflection group `W`\n is defined as the poset of (right) standard cosets `gW_J`,\n where `J` is a subset of the index set `I` of `W`, ordered\n by reverse inclusion. This is conjecturally a meet semilattice\n if and only if `W` is well-generated.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(3, 2)\n sage: P = W.milnor_fiber_poset()\n sage: P\n Finite meet-semilattice containing 34 elements\n sage: R.<x> = ZZ[]\n sage: sum(x**P.rank(elt) for elt in P)\n 18*x^2 + 15*x + 1\n\n sage: # optional - gap3\n sage: W = ReflectionGroup(4)\n sage: P = W.milnor_fiber_poset(); P\n Finite meet-semilattice containing 41 elements\n sage: sum(x**P.rank(elt) for elt in P)\n 24*x^2 + 16*x + 1\n\n sage: # optional - gap3\n sage: W = ReflectionGroup([4,2,2])\n sage: W.is_well_generated()\n False\n sage: P = W.milnor_fiber_poset(); P\n Finite poset containing 47 elements\n sage: sum(x**P.rank(elt) for elt in P)\n 16*x^3 + 24*x^2 + 6*x + 1\n sage: P.is_meet_semilattice()\n False\n '
I = self.index_set()
data = {}
next_reprs = {(): list(self)}
next_cosets = {(): [frozenset([g]) for g in next_reprs[()]]}
next_level = {(i, ()) for i in range(len(next_cosets[()]))}
while next_level:
cur = next_level
cosets = next_cosets
reprs = next_reprs
next_level = set()
next_cosets = {}
next_reprs = {}
for Y in cur:
(index, J) = Y
for i in I:
if (i in J):
continue
Jp = tuple(sorted((J + (i,))))
found_coset = False
if (Jp in next_cosets):
rep = reprs[J][index]
for (ii, C) in enumerate(next_cosets[Jp]):
if (rep in C):
found_coset = True
Yp = (reprs[J][index], J)
Xp = (next_reprs[Jp][ii], Jp)
if (Xp in data):
data[Xp].append(Yp)
else:
data[Xp] = [Yp]
else:
next_cosets[Jp] = []
next_reprs[Jp] = []
if found_coset:
continue
next_level.add((len(next_cosets[Jp]), Jp))
H = set(cosets[J][index])
to_test = [(g, i) for g in H]
while to_test:
(g, j) = to_test.pop()
gp = g.apply_simple_reflection(j, side='right')
if (gp in H):
continue
H.add(gp)
to_test.extend(((gp, j) for j in Jp))
rep = min(H, key=(lambda g: g.length()))
next_cosets[Jp].append(frozenset(H))
next_reprs[Jp].append(rep)
Yp = (reprs[J][index], J)
Xp = (rep, Jp)
if (Xp in data):
data[Xp].append(Yp)
else:
data[Xp] = [Yp]
if self.is_well_generated():
from sage.combinat.posets.lattices import MeetSemilattice
return MeetSemilattice(data)
from sage.combinat.posets.posets import Poset
return Poset(data)
class ElementMethods():
@abstract_method(optional=True)
def to_matrix(self):
'\n Return the matrix presentation of ``self`` acting on a\n vector space `V`.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: [t.to_matrix() for t in W] # optional - gap3\n [\n [1 0] [ 1 1] [-1 0] [-1 -1] [ 0 1] [ 0 -1]\n [0 1], [ 0 -1], [ 1 1], [ 1 0], [-1 -1], [-1 0]\n ]\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: [t.to_matrix() for t in W] # needs sage.combinat sage.groups\n [\n [1 0 0] [1 0 0] [0 1 0] [0 0 1] [0 1 0] [0 0 1]\n [0 1 0] [0 0 1] [1 0 0] [1 0 0] [0 0 1] [0 1 0]\n [0 0 1], [0 1 0], [0 0 1], [0 1 0], [1 0 0], [1 0 0]\n ]\n\n A different representation is given by the\n colored permutations::\n\n sage: W = ColoredPermutations(3, 1) # needs sage.combinat\n sage: [t.to_matrix() for t in W] # needs sage.combinat sage.groups\n [[1], [zeta3], [-zeta3 - 1]]\n '
def _matrix_(self):
'\n Return ``self`` as a matrix.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: [matrix(t) for t in W] # optional - gap3\n [\n [1 0] [ 1 1] [-1 0] [-1 -1] [ 0 1] [ 0 -1]\n [0 1], [ 0 -1], [ 1 1], [ 1 0], [-1 -1], [-1 0]\n ]\n '
return self.to_matrix()
def character_value(self):
'\n Return the value at ``self`` of the character of the\n reflection representation given by :meth:`to_matrix`.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3); W # needs sage.combinat\n 1-colored permutations of size 3\n sage: [t.character_value() for t in W] # needs sage.combinat sage.groups\n [3, 1, 1, 0, 0, 1]\n\n Note that this could be a different (faithful)\n representation than that given by the corresponding root\n system::\n\n sage: W = ReflectionGroup((1,1,3)); W # optional - gap3\n Irreducible real reflection group of rank 2 and type A2\n sage: [t.character_value() for t in W] # optional - gap3\n [2, 0, 0, -1, -1, 0]\n\n sage: W = ColoredPermutations(2,2); W # needs sage.combinat\n 2-colored permutations of size 2\n sage: [t.character_value() for t in W] # needs sage.combinat sage.groups\n [2, 0, 0, -2, 0, 0, 0, 0]\n\n sage: W = ColoredPermutations(3,1); W # needs sage.combinat\n 3-colored permutations of size 1\n sage: [t.character_value() for t in W] # needs sage.combinat sage.groups\n [1, zeta3, -zeta3 - 1]\n '
return self.to_matrix().trace()
def reflection_length(self, in_unitary_group=False):
'\n Return the reflection length of ``self``.\n\n This is the minimal numbers of reflections needed to\n obtain ``self``.\n\n INPUT:\n\n - ``in_unitary_group`` -- (default: ``False``) if ``True``,\n the reflection length is computed in the unitary group\n which is the dimension of the move space of ``self``\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 1, 2, 2]\n\n sage: W = ReflectionGroup((2,1,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 1, 1, 2, 2, 2]\n\n sage: W = ReflectionGroup((2,2,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 2]\n\n sage: W = ReflectionGroup((3,1,2)) # optional - gap3\n sage: sorted([t.reflection_length() for t in W]) # optional - gap3\n [0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n '
W = self.parent()
if (in_unitary_group or W.is_real()):
from sage.matrix.special import identity_matrix
I = identity_matrix(self.parent().rank())
return (W.rank() - (self.canonical_matrix() - I).right_nullity())
else:
return len(self.reduced_word_in_reflections())
class Irreducible(CategoryWithAxiom):
def example(self):
'\n Return an example of an irreducible complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: C = ComplexReflectionGroups().Finite().Irreducible()\n sage: C.example() # optional - gap3\n Irreducible complex reflection group of rank 3 and type G(4,2,3)\n '
from sage.combinat.root_system.reflection_group_real import ReflectionGroup
return ReflectionGroup((4, 2, 3))
class ParentMethods():
def coxeter_number(self):
'\n Return the Coxeter number of an irreducible\n reflection group.\n\n This is defined as `\\frac{N + N^*}{n}` where\n `N` is the number of reflections, `N^*` is the\n number of reflection hyperplanes, and `n` is the\n rank of ``self``.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup(31) # optional - gap3\n sage: W.coxeter_number() # optional - gap3\n 30\n '
return ((self.number_of_reflection_hyperplanes() + self.number_of_reflections()) // self.rank())
def absolute_order_ideal(self, gens=None, in_unitary_group=True, return_lengths=False):
"\n Return all elements in ``self`` below given elements in the\n absolute order of ``self``.\n\n This order is defined by\n\n .. MATH::\n\n \\omega \\leq_R \\tau \\Leftrightarrow \\ell_R(\\omega) +\n \\ell_R(\\omega^{-1} \\tau) = \\ell_R(\\tau),\n\n where `\\ell_R` denotes the reflection length.\n\n This is, if ``in_unitary_group`` is ``False``, then\n\n .. MATH::\n\n \\ell_R(w) = \\min\\{ \\ell: w = r_1\\cdots r_\\ell, r_i \\in R \\},\n\n and otherwise\n\n .. MATH::\n\n \\ell_R(w) = \\dim\\operatorname{im}(w - 1).\n\n .. NOTE::\n\n If ``gens`` are not given, ``self`` is assumed to be\n well-generated.\n\n INPUT:\n\n - ``gens`` -- (default: ``None``) if one or more elements\n are given, the order ideal in the absolute order generated\n by ``gens`` is returned.\n Otherwise, the standard Coxeter element is used as unique\n maximal element.\n\n - ``in_unitary_group`` (default:``True``) determines the\n length function used to compute the order.\n For real groups, both possible orders coincide, and for\n complex non-real groups, the order in the unitary group\n is much faster to compute.\n\n - ``return_lengths`` (default:``False``) whether or not\n to also return the lengths of the elements.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.absolute_order_ideal())\n [[], [1], [1, 2], [1, 2, 1], [2]]\n\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.absolute_order_ideal(W.from_reduced_word([2,1])))\n [[], [1], [1, 2, 1], [2], [2, 1]]\n\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.absolute_order_ideal(W.from_reduced_word([2])))\n [[], [2]]\n\n sage: W = CoxeterGroup(['A', 3]) # needs sage.combinat sage.groups\n sage: len(list(W.absolute_order_ideal())) # needs sage.combinat sage.groups\n 14\n\n sage: W = CoxeterGroup(['A', 2]) # needs sage.combinat sage.groups\n sage: for (w, l) in W.absolute_order_ideal(return_lengths=True): # needs sage.combinat sage.groups\n ....: print(w.reduced_word(), l)\n [1, 2] 2\n [1, 2, 1] 1\n [2] 1\n [1] 1\n [] 0\n "
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
if (gens is None):
seeds = [(self.coxeter_element(), self.rank())]
else:
if (gens in self):
gens = [gens]
seeds = [(gen, gen.reflection_length(in_unitary_group=in_unitary_group)) for gen in gens]
R = self.reflections()
def succ(seed):
(w, w_len) = seed
w_len -= 1
resu = []
for t in R:
u = (w * t)
if (u.reflection_length(in_unitary_group=in_unitary_group) == w_len):
resu.append((u, w_len))
return resu
step = RecursivelyEnumeratedSet(seeds, succ, structure='graded', enumeration='breadth')
if return_lengths:
return step
return (x[0] for x in step)
@cached_method
def noncrossing_partition_lattice(self, c=None, L=None, in_unitary_group=True):
"\n Return the interval `[1,c]` in the absolute order of\n ``self`` as a finite lattice.\n\n .. SEEALSO:: :meth:`absolute_order_ideal`\n\n INPUT:\n\n - ``c`` -- (default: ``None``) if an element ``c`` in ``self`` is\n given, it is used as the maximal element in the interval\n\n - ``L`` -- (default: ``None``) if a subset ``L`` (must be hashable!)\n of ``self`` is given, it is used as the underlying set (only\n cover relations are checked).\n\n - ``in_unitary_group`` -- (default: ``False``) if ``False``, the\n relation is given by `\\sigma \\leq \\tau` if\n `l_R(\\sigma) + l_R(\\sigma^{-1}\\tau) = l_R(\\tau)`;\n if ``True``, the relation is given by `\\sigma \\leq \\tau` if\n `\\dim(\\mathrm{Fix}(\\sigma)) + \\dim(\\mathrm{Fix}(\\sigma^{-1}\\tau))\n = \\dim(\\mathrm{Fix}(\\tau))`\n\n .. NOTE::\n\n If ``L`` is given, the parameter ``c`` is ignored.\n\n EXAMPLES::\n\n sage: W = SymmetricGroup(4) # needs sage.combinat sage.groups\n sage: W.noncrossing_partition_lattice() # needs sage.combinat sage.groups\n Finite lattice containing 14 elements\n\n sage: W = WeylGroup(['G', 2]) # needs sage.combinat sage.groups\n sage: W.noncrossing_partition_lattice() # needs sage.combinat sage.groups\n Finite lattice containing 8 elements\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.noncrossing_partition_lattice())\n [[], [1], [1, 2], [1, 2, 1], [2]]\n\n sage: c21 = W.from_reduced_word([2,1]) # optional - gap3\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.noncrossing_partition_lattice(c21))\n [[], [1], [1, 2, 1], [2], [2, 1]]\n\n sage: c2 = W.from_reduced_word([2]) # optional - gap3\n sage: sorted(w.reduced_word() # optional - gap3\n ....: for w in W.noncrossing_partition_lattice(c2))\n [[], [2]]\n "
from sage.combinat.posets.posets import Poset
from sage.combinat.posets.lattices import LatticePoset
R = self.reflections()
if (L is None):
L = list(self.absolute_order_ideal(gens=c, in_unitary_group=in_unitary_group, return_lengths=True))
else:
L = [(pi, pi.reflection_length()) for pi in L]
rels = []
ref_lens = dict(L)
for (pi, l) in L:
for t in R:
tau = (pi * t)
if ((tau in ref_lens) and ((l + 1) == ref_lens[tau])):
rels.append((pi, tau))
P = Poset(([], rels), cover_relations=True, facade=True)
if P.is_lattice():
P = LatticePoset(P)
return P
def generalized_noncrossing_partitions(self, m, c=None, positive=False):
'\n Return the set of all chains of length ``m`` in the\n noncrossing partition lattice of ``self``, see\n :meth:`noncrossing_partition_lattice`.\n\n .. NOTE::\n\n ``self`` is assumed to be well-generated.\n\n INPUT:\n\n - ``c`` -- (default: ``None``) if an element ``c`` in ``self``\n is given, it is used as the maximal element in the interval\n\n - ``positive`` -- (default: ``False``) if ``True``, only those\n generalized noncrossing partitions of full support are returned\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n\n sage: chains = W.generalized_noncrossing_partitions(2) # optional - gap3\n sage: sorted([w.reduced_word() for w in chain] # optional - gap3\n ....: for chain in chains)\n [[[], [], [1, 2]],\n [[], [1], [2]],\n [[], [1, 2], []],\n [[], [1, 2, 1], [1]],\n [[], [2], [1, 2, 1]],\n [[1], [], [2]],\n [[1], [2], []],\n [[1, 2], [], []],\n [[1, 2, 1], [], [1]],\n [[1, 2, 1], [1], []],\n [[2], [], [1, 2, 1]],\n [[2], [1, 2, 1], []]]\n\n sage: chains = W.generalized_noncrossing_partitions(2, # optional - gap3\n ....: positive=True)\n sage: sorted([w.reduced_word() for w in chain] # optional - gap3\n ....: for chain in chains)\n [[[], [1, 2], []],\n [[], [1, 2, 1], [1]],\n [[1], [2], []],\n [[1, 2], [], []],\n [[1, 2, 1], [], [1]],\n [[1, 2, 1], [1], []],\n [[2], [1, 2, 1], []]]\n '
from sage.combinat.combination import Combinations
NC = self.noncrossing_partition_lattice(c=c)
one = self.one()
if (c is None):
c = self.coxeter_element()
chains = NC.chains()
NCm = set()
iter = chains.breadth_first_search_iterator()
next(iter)
chain = next(iter)
while (len(chain) <= m):
chain.append(c)
for i in range((len(chain) - 1), 0, (- 1)):
chain[i] = ((chain[(i - 1)] ** (- 1)) * chain[i])
k = ((m + 1) - len(chain))
for positions in Combinations(range((m + 1)), k):
ncm = []
for l in range((m + 1)):
if (l in positions):
ncm.append(one)
else:
l_prime = (l - len([i for i in positions if (i <= l)]))
ncm.append(chain[l_prime])
if ((not positive) or prod(ncm[:(- 1)]).has_full_support()):
NCm.add(tuple(ncm))
try:
chain = next(iter)
except StopIteration:
chain = list(range((m + 1)))
return NCm
def absolute_poset(self, in_unitary_group=False):
"\n Return the poset induced by the absolute order of ``self``\n as a finite lattice.\n\n INPUT:\n\n - ``in_unitary_group`` -- (default: ``False``) if ``False``,\n the relation is given by ``\\sigma \\leq \\tau`` if\n `l_R(\\sigma) + l_R(\\sigma^{-1}\\tau) = l_R(\\tau)`\n If ``True``, the relation is given by `\\sigma \\leq \\tau` if\n `\\dim(\\mathrm{Fix}(\\sigma)) + \\dim(\\mathrm{Fix}(\\sigma^{-1}\\tau))\n = \\dim(\\mathrm{Fix}(\\tau))`\n\n .. SEEALSO:: :meth:`noncrossing_partition_lattice`\n\n EXAMPLES::\n\n sage: P = ReflectionGroup((1,1,3)).absolute_poset(); P # optional - gap3\n Finite poset containing 6 elements\n\n sage: sorted(w.reduced_word() for w in P) # optional - gap3\n [[], [1], [1, 2], [1, 2, 1], [2], [2, 1]]\n\n sage: W = ReflectionGroup(4); W # optional - gap3\n Irreducible complex reflection group of rank 2 and type ST4\n sage: W.absolute_poset() # optional - gap3\n Finite poset containing 24 elements\n\n TESTS::\n\n sage: # needs sage.combinat sage.groups\n sage: W1 = CoxeterGroup(['A', 2])\n sage: W2 = WeylGroup(['A', 2])\n sage: W3 = SymmetricGroup(3)\n sage: W1.absolute_poset()\n Finite poset containing 6 elements\n sage: W2.absolute_poset()\n Finite poset containing 6 elements\n sage: W3.absolute_poset()\n Finite poset containing 6 elements\n "
return self.noncrossing_partition_lattice(L=tuple(self), in_unitary_group=in_unitary_group)
class WellGenerated(CategoryWithAxiom):
def example(self):
'\n Return an example of a well-generated complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: C = ComplexReflectionGroups().Finite().WellGenerated()\n sage: C.example() # optional - gap3\n Reducible complex reflection group of rank 4 and type A2 x G(3,1,2)\n '
from sage.combinat.root_system.reflection_group_real import ReflectionGroup
return ReflectionGroup((1, 1, 3), (3, 1, 2))
class ParentMethods():
def _test_well_generated(self, **options):
'\n Check if ``self`` is well-generated.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((3,1,2)) # optional - gap3\n sage: W._test_well_generated() # optional - gap3\n '
tester = self._tester(**options)
tester.assertEqual(self.number_of_simple_reflections(), self.rank())
def is_well_generated(self):
'\n Return ``True`` as ``self`` is well-generated.\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((3,1,2)) # optional - gap3\n sage: W.is_well_generated() # optional - gap3\n True\n '
return True
coxeter_element = CoxeterGroups.ParentMethods.coxeter_element
standard_coxeter_elements = CoxeterGroups.ParentMethods.standard_coxeter_elements
@cached_method
def coxeter_elements(self):
'\n Return the (unique) conjugacy class in ``self`` containing all\n Coxeter elements.\n\n A Coxeter element is an element that has an eigenvalue\n `e^{2\\pi i/h}` where `h` is the Coxeter number.\n\n In case of finite Coxeter groups, these are exactly the\n elements that are conjugate to one (or, equivalently,\n all) standard Coxeter element, this is, to an element\n that is the product of the simple generators in some\n order.\n\n .. SEEALSO:: :meth:`~sage.categories.coxeter_groups.standard_coxeter_elements`\n\n EXAMPLES::\n\n sage: W = ReflectionGroup((1,1,3)) # optional - gap3\n sage: sorted(c.reduced_word() # optional - gap3\n ....: for c in W.coxeter_elements())\n [[1, 2], [2, 1]]\n\n sage: W = ReflectionGroup((1,1,4)) # optional - gap3\n sage: sorted(c.reduced_word() # optional - gap3\n ....: for c in W.coxeter_elements())\n [[1, 2, 1, 3, 2], [1, 2, 3], [1, 3, 2],\n [2, 1, 3], [2, 1, 3, 2, 1], [3, 2, 1]]\n '
return self.coxeter_element().conjugacy_class()
def milnor_fiber_complex(self):
'\n Return the Milnor fiber complex of ``self``.\n\n The *Milnor fiber complex* of a finite well-generated\n complex reflection group `W` is the simplicial complex whose\n face poset is given by :meth:`milnor_fiber_poset`. When `W`\n is an irreducible Shephard group, it is also an equivariant\n strong deformation retract of the Milnor fiber `f_1^{-1}(1)`,\n where `f_1: V \\to \\CC` is the polynomial invariant of smallest\n degree acting on the reflection representation `V`.\n\n When `W` is a Coxeter group, this is isomorphic to the\n :wikipedia:`Coxeter complex <Coxeter_complex>` of `W`.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(3, 2)\n sage: C = W.milnor_fiber_complex()\n sage: C.homology()\n {0: 0, 1: Z x Z x Z x Z}\n\n sage: W = ReflectionGroup(5) # optional - gap3\n sage: C = W.milnor_fiber_complex() # optional - gap3\n sage: C.homology() # optional - gap3\n {0: 0, 1: Z^25}\n '
I = self.index_set()
cosets = {}
for i in I:
Ip = tuple([j for j in I if (j != i)])
cosets[Ip] = []
for g in self:
if any(((g in C) for C in cosets[Ip])):
continue
H = {g}
to_test = [(g, j) for j in Ip]
while to_test:
(h, j) = to_test.pop()
hp = h.apply_simple_reflection(j, side='right')
if (hp in H):
continue
H.add(hp)
to_test.extend(((hp, j) for j in Ip))
cosets[Ip].append(frozenset(H))
verts = {}
for Ip in cosets:
for C in cosets[Ip]:
verts[(C, Ip)] = len(verts)
facets = [[verts[k] for k in verts if (g in k[0])] for g in self]
from sage.topology.simplicial_complex import SimplicialComplex
return SimplicialComplex(facets)
class Irreducible(CategoryWithAxiom):
'\n The category of finite irreducible well-generated\n finite complex reflection groups.\n '
def example(self):
'\n Return an example of an irreducible well-generated\n complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n sage: C = ComplexReflectionGroups().Finite().WellGenerated().Irreducible()\n sage: C.example() # needs sage.combinat\n 4-colored permutations of size 3\n '
from sage.combinat.colored_permutations import ColoredPermutations
return ColoredPermutations(4, 3)
class ParentMethods():
def coxeter_number(self):
'\n Return the Coxeter number of a well-generated,\n irreducible reflection group. This is defined to be\n the order of a regular element in ``self``, and is\n equal to the highest degree of ``self``.\n\n .. SEEALSO:: :meth:`ComplexReflectionGroups.Finite.Irreducible`\n\n .. NOTE::\n\n This method overwrites the more general\n method for complex reflection groups since\n the expression given here is quicker to\n compute.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: W.coxeter_number() # needs sage.combinat\n 3\n\n sage: W = ColoredPermutations(4,3) # needs sage.combinat\n sage: W.coxeter_number() # needs sage.combinat\n 12\n\n sage: W = ReflectionGroup((4,4,3)) # optional - gap3\n sage: W.coxeter_number() # optional - gap3\n 8\n '
return max(self.degrees())
def number_of_reflections_of_full_support(self):
'\n Return the number of reflections with full\n support.\n\n EXAMPLES::\n\n sage: W = Permutations(4)\n sage: W.number_of_reflections_of_full_support()\n 1\n\n sage: W = ColoredPermutations(1,4) # needs sage.combinat\n sage: W.number_of_reflections_of_full_support()\n 1\n\n sage: W = CoxeterGroup("B3") # needs sage.combinat sage.groups\n sage: W.number_of_reflections_of_full_support() # needs sage.combinat sage.groups\n 3\n\n sage: W = ColoredPermutations(3,3) # needs sage.combinat\n sage: W.number_of_reflections_of_full_support() # needs sage.combinat\n 3\n '
n = self.rank()
h = self.coxeter_number()
l = self.cardinality()
return (((n * h) * prod((d for d in self.codegrees() if (d != 0)))) // l)
@cached_method
def rational_catalan_number(self, p, polynomial=False):
'\n Return the ``p``-th rational Catalan number\n associated to ``self``.\n\n It is defined by\n\n .. MATH::\n\n \\prod_{i = 1}^n \\frac{p + (p(d_i-1)) \\mod h)}{d_i},\n\n where `d_1, \\ldots, d_n` are the degrees and\n `h` is the Coxeter number. See [STW2016]_\n for this formula.\n\n INPUT:\n\n - ``polynomial`` -- optional boolean (default ``False``)\n if ``True``, return instead the `q`-analogue as a\n polynomial in `q`\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: [W.rational_catalan_number(p) for p in [5,7,8]] # needs sage.combinat\n [7, 12, 15]\n\n sage: W = ColoredPermutations(2,2) # needs sage.combinat\n sage: [W.rational_catalan_number(p) for p in [7,9,11]] # needs sage.combinat\n [10, 15, 21]\n\n TESTS::\n\n sage: W = ColoredPermutations(1,4) # needs sage.combinat\n sage: W.rational_catalan_number(3, polynomial=True) # needs sage.combinat\n q^6 + q^4 + q^3 + q^2 + 1\n '
from sage.arith.misc import GCD as gcd
from sage.combinat.q_analogues import q_int
h = self.coxeter_number()
if (not (gcd(h, p) == 1)):
raise ValueError(('parameter p = %s is not coprime to the Coxeter number %s' % (p, h)))
if polynomial:
f = q_int
else:
def f(n):
return n
num = prod((f((p + ((p * (deg - 1)) % h))) for deg in self.degrees()))
den = prod((f(deg) for deg in self.degrees()))
return (num // den)
def fuss_catalan_number(self, m, positive=False, polynomial=False):
'\n Return the ``m``-th Fuss-Catalan number\n associated to ``self``.\n\n This is defined by\n\n .. MATH::\n\n \\prod_{i = 1}^n \\frac{d_i + mh}{d_i},\n\n where `d_1, \\ldots, d_n` are the degrees and\n `h` is the Coxeter number.\n\n INPUT:\n\n - ``positive`` -- optional boolean (default ``False``)\n if ``True``, return instead the positive Fuss-Catalan\n number\n - ``polynomial`` -- optional boolean (default ``False``)\n if ``True``, return instead the `q`-analogue as a\n polynomial in `q`\n\n See [Ar2006]_ for further information.\n\n .. NOTE::\n\n - For the symmetric group `S_n`, it reduces to the\n Fuss-Catalan number `\\frac{1}{mn+1}\\binom{(m+1)n}{n}`.\n - The Fuss-Catalan numbers for `G(r, 1, n)` all\n coincide for `r > 1`.\n\n EXAMPLES::\n\n sage: W = ColoredPermutations(1,3) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [5, 12, 22]\n\n sage: W = ColoredPermutations(1,4) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [14, 55, 140]\n\n sage: W = ColoredPermutations(1,5) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [42, 273, 969]\n\n sage: W = ColoredPermutations(2,2) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [6, 15, 28]\n\n sage: W = ColoredPermutations(2,3) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [20, 84, 220]\n\n sage: W = ColoredPermutations(2,4) # needs sage.combinat\n sage: [W.fuss_catalan_number(i) for i in [1,2,3]] # needs sage.combinat\n [70, 495, 1820]\n\n TESTS::\n\n sage: # needs sage.combinat sage.groups\n sage: W = ColoredPermutations(2,4)\n sage: W.fuss_catalan_number(2, positive=True)\n 330\n sage: W = ColoredPermutations(2,2)\n sage: W.fuss_catalan_number(2, polynomial=True)\n q^16 + q^14 + 2*q^12 + 2*q^10 + 3*q^8 + 2*q^6 +\n 2*q^4 + q^2 + 1\n '
h = self.coxeter_number()
if positive:
p = ((m * h) - 1)
else:
p = ((m * h) + 1)
return self.rational_catalan_number(p, polynomial=polynomial)
def catalan_number(self, positive=False, polynomial=False):
'\n Return the Catalan number associated to ``self``.\n\n It is defined by\n\n .. MATH::\n\n \\prod_{i = 1}^n \\frac{d_i + h}{d_i},\n\n where `d_1, \\ldots, d_n` are the degrees and where\n `h` is the Coxeter number.\n See [Ar2006]_ for further information.\n\n INPUT:\n\n - ``positive`` -- optional boolean (default ``False``)\n if ``True``, return instead the positive Catalan\n number\n - ``polynomial`` -- optional boolean (default ``False``)\n if ``True``, return instead the `q`-analogue as a\n polynomial in `q`\n\n .. NOTE::\n\n - For the symmetric group `S_n`, it reduces to the\n Catalan number `\\frac{1}{n+1} \\binom{2n}{n}`.\n - The Catalan numbers for `G(r,1,n)` all coincide\n for `r > 1`.\n\n EXAMPLES::\n\n sage: [ColoredPermutations(1,n).catalan_number() # needs sage.combinat\n ....: for n in [3,4,5]]\n [5, 14, 42]\n\n sage: [ColoredPermutations(2,n).catalan_number() # needs sage.combinat\n ....: for n in [3,4,5]]\n [20, 70, 252]\n\n sage: [ReflectionGroup((2,2,n)).catalan_number() # optional - gap3\n ....: for n in [3,4,5]]\n [14, 50, 182]\n\n TESTS::\n\n sage: # needs sage.combinat sage.groups\n sage: W = ColoredPermutations(3,6)\n sage: W.catalan_number(positive=True)\n 462\n sage: W = ColoredPermutations(2,2)\n sage: W.catalan_number(polynomial=True)\n q^8 + q^6 + 2*q^4 + q^2 + 1\n '
return self.fuss_catalan_number(1, positive=positive, polynomial=polynomial)
|
class FiniteCoxeterGroups(CategoryWithAxiom):
'\n The category of finite Coxeter groups.\n\n EXAMPLES::\n\n sage: CoxeterGroups.Finite()\n Category of finite Coxeter groups\n sage: FiniteCoxeterGroups().super_categories()\n [Category of finite generalized Coxeter groups,\n Category of Coxeter groups]\n\n sage: G = CoxeterGroups().Finite().example()\n sage: G.cayley_graph(side = "right").plot()\n Graphics object consisting of 40 graphics primitives\n\n Here are some further examples::\n\n sage: WeylGroups().Finite().example()\n The symmetric group on {0, ..., 3}\n\n sage: WeylGroup(["B", 3])\n Weyl Group of type [\'B\', 3] (as a matrix group acting on the ambient space)\n\n Those other examples will eventually be also in this category::\n\n sage: SymmetricGroup(4)\n Symmetric group of order 4! as a permutation group\n sage: DihedralGroup(5)\n Dihedral group of order 10 as a permutation group\n '
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: CoxeterGroups().Finite().super_categories()\n [Category of finite generalized Coxeter groups,\n Category of Coxeter groups]\n '
from sage.categories.complex_reflection_groups import ComplexReflectionGroups
return [ComplexReflectionGroups().Finite().WellGenerated()]
class ParentMethods():
"\n Ambiguity resolution: the implementation of ``some_elements``\n is preferable to that of :class:`FiniteGroups`. The same holds\n for ``__iter__``, although a breadth first search would be more\n natural; at least this maintains backward compatibility after\n :trac:`13589`.\n\n TESTS::\n\n sage: W = FiniteCoxeterGroups().example(3)\n\n sage: W.some_elements.__module__\n 'sage.categories.complex_reflection_or_generalized_coxeter_groups'\n sage: W.__iter__.__module__\n 'sage.categories.coxeter_groups'\n\n sage: W.some_elements()\n [(1,), (2,), (), (1, 2)]\n sage: list(W)\n [(), (1,), (2,), (1, 2), (2, 1), (1, 2, 1)]\n "
__iter__ = CoxeterGroups.ParentMethods.__dict__['__iter__']
@lazy_attribute
def w0(self):
'\n Return the longest element of ``self``.\n\n This attribute is deprecated, use :meth:`long_element` instead.\n\n EXAMPLES::\n\n sage: D8 = FiniteCoxeterGroups().example(8)\n sage: D8.w0\n (1, 2, 1, 2, 1, 2, 1, 2)\n sage: D3 = FiniteCoxeterGroups().example(3)\n sage: D3.w0\n (1, 2, 1)\n '
return self.long_element()
def long_element(self, index_set=None, as_word=False):
"\n Return the longest element of ``self``, or of the\n parabolic subgroup corresponding to the given ``index_set``.\n\n INPUT:\n\n - ``index_set`` -- a subset (as a list or iterable) of the\n nodes of the Dynkin diagram; (default: all of them)\n\n - ``as_word`` -- boolean (default ``False``). If ``True``, then\n return instead a reduced decomposition of the longest element.\n\n Should this method be called maximal_element? longest_element?\n\n EXAMPLES::\n\n sage: D10 = FiniteCoxeterGroups().example(10)\n sage: D10.long_element()\n (1, 2, 1, 2, 1, 2, 1, 2, 1, 2)\n sage: D10.long_element([1])\n (1,)\n sage: D10.long_element([2])\n (2,)\n sage: D10.long_element([])\n ()\n\n sage: D7 = FiniteCoxeterGroups().example(7)\n sage: D7.long_element()\n (1, 2, 1, 2, 1, 2, 1)\n\n One can require instead a reduced word for w0::\n\n sage: A3 = CoxeterGroup(['A', 3])\n sage: A3.long_element(as_word=True)\n [1, 2, 1, 3, 2, 1]\n "
if (index_set is None):
index_set = self.index_set()
w = self.one()
if as_word:
word = []
while True:
i = w.first_descent(index_set=index_set, positive=True)
if (i is None):
if as_word:
return word
else:
return w
else:
if as_word:
word.append(i)
w = w.apply_simple_reflection(i)
@cached_method
def bruhat_poset(self, facade=False):
'\n Return the Bruhat poset of ``self``.\n\n .. SEEALSO::\n\n :meth:`bhz_poset`, :meth:`shard_poset`, :meth:`weak_poset`\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 2])\n sage: P = W.bruhat_poset()\n sage: P\n Finite poset containing 6 elements\n sage: P.show()\n\n Here are some typical operations on this poset::\n\n sage: W = WeylGroup(["A", 3])\n sage: P = W.bruhat_poset()\n sage: u = W.from_reduced_word([3,1])\n sage: v = W.from_reduced_word([3,2,1,2,3])\n sage: P(u) <= P(v)\n True\n sage: len(P.interval(P(u), P(v)))\n 10\n sage: P.is_join_semilattice()\n False\n\n By default, the elements of `P` are aware that they belong\n to `P`::\n\n sage: P.an_element().parent()\n Finite poset containing 24 elements\n\n If instead one wants the elements to be plain elements of\n the Coxeter group, one can use the ``facade`` option::\n\n sage: P = W.bruhat_poset(facade = True)\n sage: P.an_element().parent()\n Weyl Group of type [\'A\', 3] (as a matrix group acting on the ambient space)\n\n .. SEEALSO:: :func:`Poset` for more on posets and facade posets.\n\n TESTS::\n\n sage: [len(WeylGroup(["A", n]).bruhat_poset().cover_relations()) for n in [1,2,3]]\n [1, 8, 58]\n\n .. TODO::\n\n - Use the symmetric group in the examples (for nicer\n output), and print the edges for a stronger test.\n - The constructed poset should be lazy, in order to\n handle large / infinite Coxeter groups.\n '
from sage.combinat.posets.posets import Poset
covers = tuple(([u, v] for v in self for u in v.bruhat_lower_covers()))
return Poset((self, covers), cover_relations=True, facade=facade)
def shard_poset(self, side='right'):
"\n Return the shard intersection order attached to `W`.\n\n This is a lattice structure on `W`, introduced in [Rea2009]_. It\n contains the noncrossing partition lattice, as the induced lattice\n on the subset of `c`-sortable elements.\n\n The partial order is given by simultaneous inclusion of inversion sets\n and subgroups attached to every element.\n\n The precise description used here can be found in [STW2018]_.\n\n Another implementation for the symmetric groups is\n available as :func:`~sage.combinat.shard_order.shard_poset`.\n\n .. SEEALSO::\n\n :meth:`bhz_poset`, :meth:`bruhat_poset`, :meth:`weak_poset`\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A',3], base_ring=ZZ)\n sage: SH = W.shard_poset(); SH\n Finite lattice containing 24 elements\n sage: SH.is_graded()\n True\n sage: SH.characteristic_polynomial()\n q^3 - 11*q^2 + 23*q - 13\n sage: SH.f_polynomial()\n 34*q^3 + 22*q^2 + q\n "
from sage.combinat.posets.lattices import LatticePoset
data = {w: (frozenset((u.lift() for u in w.covered_reflections_subgroup())), frozenset((~ w).inversions_as_reflections())) for w in self}
def shard_comparison(u, v):
(Gu, Nu) = data[u]
(Gv, Nv) = data[v]
return (Gu.issubset(Gv) and Nu.issubset(Nv))
return LatticePoset([self, shard_comparison])
def bhz_poset(self):
"\n Return the Bergeron-Hohlweg-Zabrocki partial order on the Coxeter\n group.\n\n This is a partial order on the elements of a finite\n Coxeter group `W`, which is distinct from the Bruhat\n order, the weak order and the shard intersection order. It\n was defined in [BHZ2005]_.\n\n This partial order is not a lattice, as there is no unique\n maximal element. It can be succintly defined as follows.\n\n Let `u` and `v` be two elements of the Coxeter group `W`. Let\n `S(u)` be the support of `u`. Then `u \\leq v` if and only\n if `v_{S(u)} = u` (here `v = v^I v_I` denotes the usual\n parabolic decomposition with respect to the standard parabolic\n subgroup `W_I`).\n\n .. SEEALSO::\n\n :meth:`bruhat_poset`, :meth:`shard_poset`, :meth:`weak_poset`\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A',3], base_ring=ZZ)\n sage: P = W.bhz_poset(); P\n Finite poset containing 24 elements\n sage: P.relations_number()\n 103\n sage: P.chain_polynomial()\n 34*q^4 + 90*q^3 + 79*q^2 + 24*q + 1\n sage: len(P.maximal_elements())\n 13\n "
from sage.graphs.digraph import DiGraph
from sage.combinat.posets.posets import Poset
def covered_by(ux, vy):
(u, iu, Su) = ux
(v, iv, Sv) = vy
if (len(Sv) != (len(Su) + 1)):
return False
if (not all(((u in Sv) for u in Su))):
return False
return all(((v * iu).has_descent(x, positive=True) for x in Su))
vertices = [(u, u.inverse(), tuple(set(u.reduced_word_reverse_iterator()))) for u in self]
dg = DiGraph([vertices, covered_by])
dg.relabel((lambda x: x[0]))
return Poset(dg, cover_relations=True)
def degrees(self):
'\n Return the degrees of the Coxeter group.\n\n The output is an increasing list of integers.\n\n EXAMPLES::\n\n sage: CoxeterGroup([\'A\', 4]).degrees()\n (2, 3, 4, 5)\n sage: CoxeterGroup([\'B\', 4]).degrees()\n (2, 4, 6, 8)\n sage: CoxeterGroup([\'D\', 4]).degrees()\n (2, 4, 4, 6)\n sage: CoxeterGroup([\'F\', 4]).degrees()\n (2, 6, 8, 12)\n sage: CoxeterGroup([\'E\', 8]).degrees()\n (2, 8, 12, 14, 18, 20, 24, 30)\n sage: CoxeterGroup([\'H\', 3]).degrees()\n (2, 6, 10)\n\n sage: WeylGroup([["A",3], ["A",3], ["B",2]]).degrees()\n (2, 3, 4, 2, 3, 4, 2, 4)\n\n TESTS::\n\n sage: CoxeterGroup([\'A\', 4]).degrees()\n (2, 3, 4, 5)\n sage: SymmetricGroup(3).degrees()\n (2, 3)\n '
from sage.rings.qqbar import QQbar
from sage.rings.integer_ring import ZZ
def degrees_of_irreducible_component(I):
'Return the degrees for the irreducible component indexed by I'
s = self.simple_reflections()
c = self.prod((s[i] for i in I))
roots = c.matrix().change_ring(QQbar).charpoly().roots()
args = ((z.rational_argument(), m) for (z, m) in roots)
args = [((z if (z >= 0) else (1 + z)), m) for (z, m) in args]
h = max((z.denominator() for (z, m) in args))
return tuple(sorted((ZZ(((z * h) + 1)) for (z, m) in args if z for i in range(m))))
return sum((degrees_of_irreducible_component(I) for I in self.irreducible_component_index_sets()), ())
def codegrees(self):
'\n Return the codegrees of the Coxeter group.\n\n These are just the degrees minus 2.\n\n EXAMPLES::\n\n sage: CoxeterGroup([\'A\', 4]).codegrees()\n (0, 1, 2, 3)\n sage: CoxeterGroup([\'B\', 4]).codegrees()\n (0, 2, 4, 6)\n sage: CoxeterGroup([\'D\', 4]).codegrees()\n (0, 2, 2, 4)\n sage: CoxeterGroup([\'F\', 4]).codegrees()\n (0, 4, 6, 10)\n sage: CoxeterGroup([\'E\', 8]).codegrees()\n (0, 6, 10, 12, 16, 18, 22, 28)\n sage: CoxeterGroup([\'H\', 3]).codegrees()\n (0, 4, 8)\n\n sage: WeylGroup([["A",3], ["A",3], ["B",2]]).codegrees()\n (0, 1, 2, 0, 1, 2, 0, 2)\n '
return tuple(((d - 2) for d in self.degrees()))
@cached_method
def weak_poset(self, side='right', facade=False):
'\n INPUT:\n\n - ``side`` -- "left", "right", or "twosided" (default: "right")\n - ``facade`` -- a boolean (default: ``False``)\n\n Returns the left (resp. right) poset for weak order. In\n this poset, `u` is smaller than `v` if some reduced word\n of `u` is a right (resp. left) factor of some reduced word\n of `v`.\n\n .. SEEALSO::\n\n :meth:`bhz_poset`, :meth:`bruhat_poset`, :meth:`shard_poset`\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A", 2])\n sage: P = W.weak_poset()\n sage: P\n Finite lattice containing 6 elements\n sage: P.show()\n\n This poset is in fact a lattice::\n\n sage: W = WeylGroup(["B", 3])\n sage: P = W.weak_poset(side = "left")\n sage: P.is_lattice()\n True\n\n so this method has an alias :meth:`weak_lattice`::\n\n sage: W.weak_lattice(side = "left") is W.weak_poset(side = "left")\n True\n\n As a bonus feature, one can create the left-right weak\n poset::\n\n sage: W = WeylGroup(["A",2])\n sage: P = W.weak_poset(side = "twosided")\n sage: P.show()\n sage: len(P.hasse_diagram().edges(sort=False))\n 8\n\n This is the transitive closure of the union of left and\n right order. In this poset, `u` is smaller than `v` if\n some reduced word of `u` is a factor of some reduced word\n of `v`. Note that this is not a lattice::\n\n sage: P.is_lattice()\n False\n\n By default, the elements of `P` are aware of that they\n belong to `P`::\n\n sage: P.an_element().parent()\n Finite poset containing 6 elements\n\n If instead one wants the elements to be plain elements of\n the Coxeter group, one can use the ``facade`` option::\n\n sage: P = W.weak_poset(facade = True)\n sage: P.an_element().parent()\n Weyl Group of type [\'A\', 2] (as a matrix group acting on the ambient space)\n\n .. SEEALSO:: :func:`Poset` for more on posets and facade posets.\n\n TESTS::\n\n sage: [len(WeylGroup(["A", n]).weak_poset(side = "right").cover_relations()) for n in [1,2,3]]\n [1, 6, 36]\n sage: [len(WeylGroup(["A", n]).weak_poset(side = "left" ).cover_relations()) for n in [1,2,3]]\n [1, 6, 36]\n\n .. TODO::\n\n - Use the symmetric group in the examples (for nicer\n output), and print the edges for a stronger test.\n - The constructed poset should be lazy, in order to\n handle large / infinite Coxeter groups.\n '
from sage.combinat.posets.posets import Poset
from sage.combinat.posets.lattices import LatticePoset
if (side == 'twosided'):
covers = tuple(([u, v] for u in self for v in (u.upper_covers(side='left') + u.upper_covers(side='right'))))
return Poset((self, covers), cover_relations=True, facade=facade)
covers = tuple(([u, v] for u in self for v in u.upper_covers(side=side)))
return LatticePoset((self, covers), cover_relations=True, facade=facade)
weak_lattice = weak_poset
def inversion_sequence(self, word):
'\n Return the inversion sequence corresponding to the ``word``\n in indices of simple generators of ``self``.\n\n If ``word`` corresponds to `[w_0,w_1,...w_k]`, the output is\n `[w_0,w_0w_1w_0,\\ldots,w_0w_1\\cdots w_k \\cdots w_1 w_0]`.\n\n INPUT:\n\n - ``word`` -- a word in the indices of the simple\n generators of ``self``.\n\n EXAMPLES::\n\n sage: CoxeterGroup(["A", 2]).inversion_sequence([1,2,1])\n [\n [-1 1] [ 0 -1] [ 1 0]\n [ 0 1], [-1 0], [ 1 -1]\n ]\n\n sage: [t.reduced_word() for t in CoxeterGroup(["A",3]).inversion_sequence([2,1,3,2,1,3])]\n [[2], [1, 2, 1], [2, 3, 2], [1, 2, 3, 2, 1], [3], [1]]\n\n '
return [self.from_reduced_word((word[:(i + 1)] + list(reversed(word[:i])))) for i in range(len(word))]
def reflections_from_w0(self):
"\n Return the reflections of ``self`` using the inversion set\n of ``w_0``.\n\n EXAMPLES::\n\n sage: WeylGroup(['A',2]).reflections_from_w0()\n [\n [0 1 0] [0 0 1] [1 0 0]\n [1 0 0] [0 1 0] [0 0 1]\n [0 0 1], [1 0 0], [0 1 0]\n ]\n\n sage: WeylGroup(['A',3]).reflections_from_w0()\n [\n [0 1 0 0] [0 0 1 0] [1 0 0 0] [0 0 0 1] [1 0 0 0] [1 0 0 0]\n [1 0 0 0] [0 1 0 0] [0 0 1 0] [0 1 0 0] [0 0 0 1] [0 1 0 0]\n [0 0 1 0] [1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 1 0] [0 0 0 1]\n [0 0 0 1], [0 0 0 1], [0 0 0 1], [1 0 0 0], [0 1 0 0], [0 0 1 0]\n ]\n "
return self.long_element().inversions_as_reflections()
@cached_method
def m_cambrian_lattice(self, c, m=1, on_roots=False):
'\n Return the `m`-Cambrian lattice on `m`-delta sequences.\n\n See :arxiv:`1503.00710` and :arxiv:`math/0611106`.\n\n The `m`-delta sequences are certain `m`-colored minimal\n factorizations of `c` into reflections.\n\n INPUT:\n\n - `c` -- a Coxeter element of ``self`` (as a tuple, or\n as an element of ``self``)\n\n - `m` -- a positive integer (optional, default 1)\n\n - ``on_roots`` (optional, default ``False``) -- if\n ``on_roots`` is ``True``, the lattice is realized on\n roots rather than on reflections. In order for this to\n work, the ElementMethod ``reflection_to_root`` must be\n available.\n\n EXAMPLES::\n\n sage: CoxeterGroup(["A",2]).m_cambrian_lattice((1,2))\n Finite lattice containing 5 elements\n\n sage: CoxeterGroup(["A",2]).m_cambrian_lattice((1,2),2)\n Finite lattice containing 12 elements\n '
from sage.combinat.posets.lattices import LatticePoset
if hasattr(c, 'reduced_word'):
c = c.reduced_word()
c = list(c)
sorting_word = self.long_element().coxeter_sorting_word(c)
if on_roots:
if (not hasattr(self.long_element(), 'reflection_to_root')):
raise ValueError("The parameter 'on_root=True' needs the ElementMethod 'reflection_to_root'")
inv_woc = [t.reflection_to_root() for t in self.inversion_sequence(sorting_word)]
S = [s.reflection_to_root() for s in self.simple_reflections()]
PhiP = [t.reflection_to_root() for t in self.reflections()]
else:
inv_woc = self.inversion_sequence(sorting_word)
S = self.simple_reflections()
T = self.reflections_from_w0()
Twords = {t: t.reduced_word() for t in T}
elements = set()
covers = []
bottom_elt = frozenset(((s, 0) for s in S))
new = {bottom_elt}
while new:
new_element = new.pop()
elements.add(new_element)
for t in new_element:
if (t[1] < m):
cov_element = [s for s in new_element if (s != t)]
cov_element.append((t[0], (t[1] + 1)))
idx_t0 = inv_woc.index(t[0])
for t_conj in ([(i, t[1]) for i in inv_woc[idx_t0:]] + [(i, (t[1] + 1)) for i in inv_woc[:idx_t0]]):
if (t_conj in cov_element):
cov_element.remove(t_conj)
if on_roots:
tmp = t_conj[0].weyl_action(t[0].associated_reflection())
if (tmp in PhiP):
cov_element.append((tmp, t_conj[1]))
else:
cov_element.append(((- tmp), (t_conj[1] - 1)))
else:
tmp = ((t[0] * t_conj[0]) * t[0])
invs = self.inversion_sequence((Twords[t[0]] + Twords[t_conj[0]]))
plus_or_minus = invs.count(tmp)
if (plus_or_minus % 2):
cov_element.append((tmp, t_conj[1]))
else:
cov_element.append((tmp, (t_conj[1] - 1)))
cov_element = frozenset(cov_element)
if (cov_element not in elements):
new.add(cov_element)
covers.append((new_element, cov_element))
return LatticePoset([elements, covers], cover_relations=True)
def cambrian_lattice(self, c, on_roots=False):
'\n Return the `c`-Cambrian lattice on delta sequences.\n\n See :arxiv:`1503.00710` and :arxiv:`math/0611106`.\n\n Delta sequences are certain 2-colored minimal factorizations\n of ``c`` into reflections.\n\n INPUT:\n\n - ``c`` -- a standard Coxeter element in ``self``\n (as a tuple, or as an element of ``self``)\n\n - ``on_roots`` (optional, default ``False``) -- if\n ``on_roots`` is ``True``, the lattice is realized on\n roots rather than on reflections. In order for this to\n work, the ElementMethod ``reflection_to_root`` must be\n available.\n\n EXAMPLES::\n\n sage: CoxeterGroup(["A", 2]).cambrian_lattice((1,2))\n Finite lattice containing 5 elements\n\n sage: CoxeterGroup(["B", 2]).cambrian_lattice((1,2))\n Finite lattice containing 6 elements\n\n sage: CoxeterGroup(["G", 2]).cambrian_lattice((1,2))\n Finite lattice containing 8 elements\n '
return self.m_cambrian_lattice(c=c, m=1, on_roots=on_roots)
def is_real(self):
"\n Return ``True`` since ``self`` is a real reflection group.\n\n EXAMPLES::\n\n sage: CoxeterGroup(['F',4]).is_real()\n True\n sage: CoxeterGroup(['H',4]).is_real()\n True\n "
return True
def permutahedron(self, point=None, base_ring=None):
"\n Return the permutahedron of ``self``,\n\n This is the convex hull of the point ``point`` in the weight\n basis under the action of ``self`` on the underlying vector\n space `V`.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.root_system.reflection_group_real.permutahedron`\n\n INPUT:\n\n - ``point`` -- optional, a point given by its coordinates in\n the weight basis (default is `(1, 1, 1, \\ldots)`)\n - ``base_ring`` -- optional, the base ring of the polytope\n\n .. NOTE::\n\n The result is expressed in the root basis coordinates.\n\n .. NOTE::\n\n If function is too slow, switching the base ring to\n :class:`RDF` will almost certainly speed things up.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['H',3], base_ring=RDF)\n sage: W.permutahedron()\n doctest:warning\n ...\n UserWarning: This polyhedron data is numerically complicated; cdd could not convert between the inexact V and H representation without loss of data. The resulting object might show inconsistencies.\n A 3-dimensional polyhedron in RDF^3 defined as the convex hull of 120 vertices\n\n sage: W = CoxeterGroup(['I',7])\n sage: W.permutahedron()\n A 2-dimensional polyhedron in AA^2 defined as the convex hull of 14 vertices\n sage: W.permutahedron(base_ring=RDF)\n A 2-dimensional polyhedron in RDF^2 defined as the convex hull of 14 vertices\n\n sage: W = ReflectionGroup(['A',3]) # optional - gap3\n sage: W.permutahedron() # optional - gap3\n A 3-dimensional polyhedron in QQ^3 defined as the convex hull\n of 24 vertices\n\n sage: W = ReflectionGroup(['A',3],['B',2]) # optional - gap3\n sage: W.permutahedron() # optional - gap3\n A 5-dimensional polyhedron in QQ^5 defined as the convex hull of 192 vertices\n\n TESTS::\n\n sage: W = ReflectionGroup(['A',3]) # optional - gap3\n sage: W.permutahedron([3,5,8]) # optional - gap3\n A 3-dimensional polyhedron in QQ^3 defined as the convex hull\n of 24 vertices\n\n\n .. PLOT::\n :width: 300 px\n\n W = CoxeterGroup(['I',7])\n p = W.permutahedron()\n sphinx_plot(p)\n\n "
n = self.one().canonical_matrix().rank()
weights = self.fundamental_weights()
if (point is None):
from sage.rings.integer_ring import ZZ
point = ([ZZ.one()] * n)
v = sum(((point[(i - 1)] * weights[i]) for i in weights.keys()))
vertices = [(v * w) for w in self]
if (base_ring is None):
if isinstance(v.base_ring(), (sage.rings.abc.UniversalCyclotomicField, sage.rings.abc.AlgebraicField_common)):
from sage.rings.qqbar import AA
vertices = [v.change_ring(AA) for v in vertices]
base_ring = AA
from sage.geometry.polyhedron.constructor import Polyhedron
return Polyhedron(vertices=vertices, base_ring=base_ring)
def coxeter_poset(self):
'\n Return the Coxeter poset of ``self``.\n\n Let `W` be a Coxeter group. The *Coxeter poset* is defined as\n the set of (right) standard cosets `gW_J`, where `J` is a\n subset of the index set `I` of `W`, ordered by reverse inclusion.\n\n This is equal to the face poset of the :meth:`Coxeter complex\n <coxeter_complex()>`.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup([\'A\', 3])\n sage: P = W.coxeter_poset()\n sage: P\n Finite meet-semilattice containing 75 elements\n sage: P.rank()\n 3\n\n sage: W = WeylGroup([\'B\', 3])\n sage: P = W.coxeter_poset()\n sage: P\n Finite meet-semilattice containing 147 elements\n sage: P.rank()\n 3\n\n sage: W = CoxeterGroup([\'I\', 7])\n sage: P = W.coxeter_poset()\n sage: P\n Finite meet-semilattice containing 29 elements\n sage: P.rank()\n 2\n\n sage: W = CoxeterGroup([\'H\', 3])\n sage: P = W.coxeter_poset()\n sage: P\n Finite meet-semilattice containing 363 elements\n sage: P.rank()\n 3\n\n sage: # optional - gap3\n sage: W = CoxeterGroup([\'H\', 3], implementation="permutation")\n sage: P = W.coxeter_poset()\n sage: P\n Finite meet-semilattice containing 363 elements\n sage: P.rank()\n 3\n '
I = self.index_set()
data = {}
next_level = {(g, ()) for g in self}
while next_level:
cur = next_level
next_level = set()
for Y in cur:
(g, J) = Y
for i in I:
if (i in J):
continue
Jp = tuple(sorted((J + (i,))))
gp = g.coset_representative(Jp, side='right')
X = (gp, Jp)
if (X in data):
data[X].append(Y)
else:
data[X] = [Y]
next_level.add(X)
from sage.combinat.posets.lattices import MeetSemilattice
return MeetSemilattice(data)
def coxeter_complex(self):
'\n Return the Coxeter complex of ``self``.\n\n Let `W` be a Coxeter group, and let `X` be the corresponding Tits\n cone, which is constructed as the `W` orbit of the fundamental\n chamber in the reflection representation. The *Coxeter complex*\n of `W` is the simplicial complex `(X \\setminus \\{0\\}) / \\RR_{>0}`.\n The face poset of this simplicial complex is given by the\n :meth:`coxeter_poset()`. When `W` is a finite group, then the\n Coxeter complex is homeomorphic to an `(n-1)`-dimensional sphere,\n where `n` is the rank of `W`.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup([\'A\', 3])\n sage: C = W.coxeter_complex()\n sage: C\n Simplicial complex with 14 vertices and 24 facets\n sage: C.homology()\n {0: 0, 1: 0, 2: Z}\n\n sage: W = WeylGroup([\'B\', 3])\n sage: C = W.coxeter_complex()\n sage: C\n Simplicial complex with 26 vertices and 48 facets\n sage: C.homology()\n {0: 0, 1: 0, 2: Z}\n\n sage: W = CoxeterGroup([\'I\', 7])\n sage: C = W.coxeter_complex()\n sage: C\n Simplicial complex with 14 vertices and 14 facets\n sage: C.homology()\n {0: 0, 1: Z}\n\n sage: W = CoxeterGroup([\'H\', 3])\n sage: C = W.coxeter_complex()\n sage: C\n Simplicial complex with 62 vertices and 120 facets\n sage: C.homology()\n {0: 0, 1: 0, 2: Z}\n\n sage: # optional - gap3\n sage: W = CoxeterGroup([\'H\', 3], implementation="permutation")\n sage: C = W.coxeter_complex()\n sage: C\n Simplicial complex with 62 vertices and 120 facets\n sage: C.homology()\n {0: 0, 1: 0, 2: Z}\n '
I = self.index_set()
facets = {}
Ip = {i: tuple([j for j in I if (j != i)]) for i in I}
for g in self:
V = []
for i in I:
gp = g
D = gp.descents(side='right')
if (D and (D[0] == i)):
D.pop(0)
while D:
gp = gp.apply_simple_reflection(D[0])
D = gp.descents(side='right')
if (D and (D[0] == i)):
D.pop(0)
V.append((gp, Ip[i]))
facets[g] = V
verts = set()
for F in facets.values():
verts.update(F)
labels = {x: i for (i, x) in enumerate(verts)}
result = [[labels[v] for v in F] for F in facets.values()]
from sage.topology.simplicial_complex import SimplicialComplex
return SimplicialComplex(result)
class ElementMethods():
@cached_in_parent_method
def bruhat_upper_covers(self):
'\n Returns all the elements that cover ``self`` in Bruhat order.\n\n EXAMPLES::\n\n sage: W = WeylGroup(["A",4])\n sage: w = W.from_reduced_word([3,2])\n sage: print([v.reduced_word() for v in w.bruhat_upper_covers()])\n [[4, 3, 2], [3, 4, 2], [2, 3, 2], [3, 1, 2], [3, 2, 1]]\n\n sage: W = WeylGroup(["B",6])\n sage: w = W.from_reduced_word([1,2,1,4,5])\n sage: C = w.bruhat_upper_covers()\n sage: len(C)\n 9\n sage: print([v.reduced_word() for v in C])\n [[6, 4, 5, 1, 2, 1], [4, 5, 6, 1, 2, 1], [3, 4, 5, 1, 2, 1], [2, 3, 4, 5, 1, 2],\n [1, 2, 3, 4, 5, 1], [4, 5, 4, 1, 2, 1], [4, 5, 3, 1, 2, 1], [4, 5, 2, 3, 1, 2],\n [4, 5, 1, 2, 3, 1]]\n sage: ww = W.from_reduced_word([5,6,5])\n sage: CC = ww.bruhat_upper_covers()\n sage: print([v.reduced_word() for v in CC])\n [[6, 5, 6, 5], [4, 5, 6, 5], [5, 6, 4, 5], [5, 6, 5, 4], [5, 6, 5, 3], [5, 6, 5, 2],\n [5, 6, 5, 1]]\n\n Recursive algorithm: write `w` for ``self``. If `i` is a\n non-descent of `w`, then the covers of `w` are exactly\n `\\{ws_i, u_1s_i, u_2s_i,..., u_js_i\\}`, where the `u_k`\n are those covers of `ws_i` that have a descent at `i`.\n '
i = self.first_descent(positive=True, side='right')
if (i is not None):
wsi = self.apply_simple_reflection(i, side='right')
return ([u.apply_simple_reflection(i, side='right') for u in wsi.bruhat_upper_covers() if u.has_descent(i, side='right')] + [wsi])
return []
def coxeter_knuth_neighbor(self, w):
"\n Return the Coxeter-Knuth (oriented) neighbors of the reduced word `w` of ``self``.\n\n INPUT:\n\n - ``w`` -- reduced word of ``self``\n\n The Coxeter-Knuth relations are given by `a a+1 a \\sim a+1 a a+1`, `abc \\sim acb`\n if `b<a<c` and `abc \\sim bac` if `a<c<b`. This method returns all neighbors of\n ``w`` under the Coxeter-Knuth relations oriented from left to right.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',4], prefix='s')\n sage: word = [1,2,1,3,2]\n sage: w = W.from_reduced_word(word)\n sage: w.coxeter_knuth_neighbor(word)\n {(1, 2, 3, 1, 2), (2, 1, 2, 3, 2)}\n\n sage: word = [1,2,1,3,2,4,3]\n sage: w = W.from_reduced_word(word)\n sage: w.coxeter_knuth_neighbor(word)\n {(1, 2, 1, 3, 4, 2, 3), (1, 2, 3, 1, 2, 4, 3), (2, 1, 2, 3, 2, 4, 3)}\n\n TESTS::\n\n sage: W = WeylGroup(['B',4], prefix='s')\n sage: word = [1,2]\n sage: w = W.from_reduced_word(word)\n sage: w.coxeter_knuth_neighbor(word)\n Traceback (most recent call last):\n ...\n NotImplementedError: this has only been implemented in finite type A so far\n "
C = self.parent().cartan_type()
if (not (C[0] == 'A')):
raise NotImplementedError('this has only been implemented in finite type A so far')
d = []
for i in range(2, len(w)):
v = list(w)
if (w[(i - 2)] == w[i]):
if (w[i] == (w[(i - 1)] - 1)):
v[(i - 2)] = w[(i - 1)]
v[i] = w[(i - 1)]
v[(i - 1)] = w[i]
d += [tuple(v)]
elif ((w[(i - 1)] < w[(i - 2)]) and (w[(i - 2)] < w[i])):
v[i] = w[(i - 1)]
v[(i - 1)] = w[i]
d += [tuple(v)]
elif ((w[(i - 2)] < w[i]) and (w[i] < w[(i - 1)])):
v[(i - 2)] = w[(i - 1)]
v[(i - 1)] = w[(i - 2)]
d += [tuple(v)]
return set(d)
def coxeter_knuth_graph(self):
"\n Return the Coxeter-Knuth graph of type `A`.\n\n The Coxeter-Knuth graph of type `A` is generated by the Coxeter-Knuth relations which are\n given by `a a+1 a \\sim a+1 a a+1`, `abc \\sim acb` if `b<a<c` and `abc \\sim bac` if `a<c<b`.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',4], prefix='s')\n sage: w = W.from_reduced_word([1,2,1,3,2])\n sage: D = w.coxeter_knuth_graph()\n sage: D.vertices(sort=True)\n [(1, 2, 1, 3, 2),\n (1, 2, 3, 1, 2),\n (2, 1, 2, 3, 2),\n (2, 1, 3, 2, 3),\n (2, 3, 1, 2, 3)]\n sage: D.edges(sort=True)\n [((1, 2, 1, 3, 2), (1, 2, 3, 1, 2), None),\n ((1, 2, 1, 3, 2), (2, 1, 2, 3, 2), None),\n ((2, 1, 2, 3, 2), (2, 1, 3, 2, 3), None),\n ((2, 1, 3, 2, 3), (2, 3, 1, 2, 3), None)]\n\n sage: w = W.from_reduced_word([1,3])\n sage: D = w.coxeter_knuth_graph()\n sage: D.vertices(sort=True)\n [(1, 3), (3, 1)]\n sage: D.edges(sort=False)\n []\n\n TESTS::\n\n sage: W = WeylGroup(['B',4], prefix='s')\n sage: w = W.from_reduced_word([1,2])\n sage: w.coxeter_knuth_graph()\n Traceback (most recent call last):\n ...\n NotImplementedError: this has only been implemented in finite type A so far\n "
from sage.graphs.graph import Graph
R = [tuple(v) for v in self.reduced_words()]
G = Graph()
G.add_vertices(R)
G.add_edges(([v, vp] for v in R for vp in self.coxeter_knuth_neighbor(v)))
return G
def is_coxeter_element(self):
"\n Return whether this is a Coxeter element.\n\n This is, whether ``self`` has an eigenvalue `e^{2\\pi i/h}`\n where `h` is the Coxeter number.\n\n .. SEEALSO:: :meth:`~sage.categories.finite_complex_reflection_groups.coxeter_elements`\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A',2])\n sage: c = prod(W.gens())\n sage: c.is_coxeter_element()\n True\n sage: W.one().is_coxeter_element()\n False\n\n sage: W = WeylGroup(['G', 2])\n sage: c = prod(W.gens())\n sage: c.is_coxeter_element()\n True\n sage: W.one().is_coxeter_element()\n False\n "
return (self in self.parent().coxeter_elements())
def covered_reflections_subgroup(self):
"\n Return the subgroup of `W` generated by the conjugates by `w`\n of the simple reflections indexed by right descents of `w`.\n\n This is used to compute the shard intersection order on `W`.\n\n EXAMPLES::\n\n sage: W = CoxeterGroup(['A',3], base_ring=ZZ)\n sage: len(W.long_element().covered_reflections_subgroup())\n 24\n sage: s = W.simple_reflection(1)\n sage: Gs = s.covered_reflections_subgroup()\n sage: len(Gs)\n 2\n sage: s in [u.lift() for u in Gs]\n True\n sage: len(W.one().covered_reflections_subgroup())\n 1\n "
W = self.parent()
winv = (~ self)
cov_down = [((self * W.simple_reflection(i)) * winv) for i in self.descents(side='right')]
return W.submonoid(cov_down)
|
class FiniteCrystals(CategoryWithAxiom):
'\n The category of finite crystals.\n\n EXAMPLES::\n\n sage: C = FiniteCrystals()\n sage: C\n Category of finite crystals\n sage: C.super_categories()\n [Category of crystals, Category of finite enumerated sets]\n sage: C.example()\n Highest weight crystal of type A_3 of highest weight omega_1\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: B = FiniteCrystals().example()\n sage: TestSuite(B).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: FiniteCrystals().extra_super_categories()\n [Category of finite enumerated sets]\n '
return [FiniteEnumeratedSets()]
def example(self, n=3):
'\n Returns an example of highest weight crystals, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: B = FiniteCrystals().example(); B\n Highest weight crystal of type A_3 of highest weight omega_1\n '
from sage.categories.crystals import Crystals
return Crystals().example(n)
class TensorProducts(TensorProductsCategory):
'\n The category of finite crystals constructed by tensor\n product of finite crystals.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: FiniteCrystals().TensorProducts().extra_super_categories()\n [Category of finite crystals]\n '
return [self.base_category()]
|
class FiniteDimensionalAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of finite dimensional algebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = FiniteDimensionalAlgebrasWithBasis(QQ); C\n Category of finite dimensional algebras with basis over Rational Field\n sage: C.super_categories()\n [Category of algebras with basis over Rational Field,\n Category of finite dimensional magmatic algebras with basis over Rational Field]\n sage: C.example() # needs sage.modules\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n\n TESTS::\n\n sage: # needs sage.graphs sage.modules\n sage: TestSuite(C).run()\n sage: C is Algebras(QQ).FiniteDimensional().WithBasis()\n True\n sage: C is Algebras(QQ).WithBasis().FiniteDimensional()\n True\n '
class ParentMethods():
@cached_method
def radical_basis(self):
"\n Return a basis of the Jacobson radical of this algebra.\n\n .. NOTE::\n\n This implementation handles algebras over fields of\n characteristic zero (using Dixon's lemma) or fields of\n characteristic `p` in which we can compute `x^{1/p}`\n [FR1985]_, [Eb1989]_.\n\n OUTPUT:\n\n - a list of elements of ``self``.\n\n .. SEEALSO:: :meth:`radical`, :class:`Algebras.Semisimple`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: A.radical_basis()\n (a, b)\n\n We construct the group algebra of the Klein Four-Group\n over the rationals::\n\n sage: A = KleinFourGroup().algebra(QQ) # needs sage.groups sage.modules\n\n This algebra belongs to the category of finite dimensional\n algebras over the rationals::\n\n sage: A in Algebras(QQ).FiniteDimensional().WithBasis() # needs sage.groups sage.modules\n True\n\n Since the field has characteristic `0`, Maschke's Theorem\n tells us that the group algebra is semisimple. So its\n radical is the zero ideal::\n\n sage: A in Algebras(QQ).Semisimple() # needs sage.groups sage.modules\n True\n sage: A.radical_basis() # needs sage.groups sage.modules\n ()\n\n Let's work instead over a field of characteristic `2`::\n\n sage: A = KleinFourGroup().algebra(GF(2)) # needs sage.groups sage.modules\n sage: A in Algebras(GF(2)).Semisimple() # needs sage.groups sage.modules\n False\n sage: A.radical_basis() # needs sage.groups sage.modules\n (() + (1,2)(3,4), (3,4) + (1,2)(3,4), (1,2) + (1,2)(3,4))\n\n We now implement the algebra `A = K[x] / (x^p-1)`, where `K`\n is a finite field of characteristic `p`, and check its\n radical; alas, we currently need to wrap `A` to make it a\n proper :class:`ModulesWithBasis`::\n\n sage: # needs sage.modules\n sage: class AnAlgebra(CombinatorialFreeModule):\n ....: def __init__(self, F):\n ....: R.<x> = PolynomialRing(F)\n ....: I = R.ideal(x**F.characteristic()-F.one())\n ....: self._xbar = R.quotient(I).gen()\n ....: basis_keys = [self._xbar**i for i in range(F.characteristic())]\n ....: CombinatorialFreeModule.__init__(self, F, basis_keys,\n ....: category=Algebras(F).FiniteDimensional().WithBasis())\n ....: def one(self):\n ....: return self.basis()[self.base_ring().one()]\n ....: def product_on_basis(self, w1, w2):\n ....: return self.from_vector(vector(w1*w2))\n sage: AnAlgebra(GF(3)).radical_basis()\n (B[1] + 2*B[xbar^2], B[xbar] + 2*B[xbar^2])\n sage: AnAlgebra(GF(16,'a')).radical_basis() # needs sage.rings.finite_rings\n (B[1] + B[xbar],)\n sage: AnAlgebra(GF(49,'a')).radical_basis() # needs sage.rings.finite_rings\n (B[1] + 6*B[xbar^6], B[xbar] + 6*B[xbar^6], B[xbar^2] + 6*B[xbar^6],\n B[xbar^3] + 6*B[xbar^6], B[xbar^4] + 6*B[xbar^6], B[xbar^5] + 6*B[xbar^6])\n\n TESTS::\n\n sage: A = KleinFourGroup().algebra(GF(2)) # needs sage.groups sage.modules\n sage: A.radical_basis() # needs sage.groups sage.modules\n (() + (1,2)(3,4), (3,4) + (1,2)(3,4), (1,2) + (1,2)(3,4))\n\n sage: A = KleinFourGroup().algebra(QQ, category=Monoids()) # needs sage.groups sage.modules\n sage: A.radical_basis.__module__ # needs sage.groups sage.modules\n 'sage.categories.finite_dimensional_algebras_with_basis'\n sage: A.radical_basis() # needs sage.groups sage.modules\n ()\n "
F = self.base_ring()
if (not F.is_field()):
raise NotImplementedError('the base ring must be a field')
p = F.characteristic()
from sage.matrix.constructor import matrix
from sage.modules.free_module_element import vector
product_on_basis = self.product_on_basis
if (p == 0):
keys = list(self.basis().keys())
cache = [{(i, j): c for i in keys for (j, c) in product_on_basis(y, i)} for y in keys]
mat = [[sum(((x.get((j, i), 0) * c) for ((i, j), c) in y.items())) for x in cache] for y in cache]
mat = matrix(self.base_ring(), mat)
rad_basis = mat.kernel().basis()
else:
if hasattr(self.base_ring().one(), 'nth_root'):
root_fcn = (lambda s, x: x.nth_root(s))
else:
root_fcn = (lambda s, x: (x ** (1 / s)))
(s, n) = (1, self.dimension())
B = [b.on_left_matrix() for b in self.basis()]
I = B[0].parent().one()
while (s <= n):
BB = (B + [I])
G = matrix([[(((- 1) ** s) * (b * bb).characteristic_polynomial()[(n - s)]) for bb in BB] for b in B])
C = G.left_kernel().basis()
if (1 < s < F.order()):
C = [vector(F, [root_fcn(s, ci) for ci in c]) for c in C]
B = [sum(((ci * b) for (ci, b) in zip(c, B))) for c in C]
s = (p * s)
e = vector(self.one())
rad_basis = [(b * e) for b in B]
return tuple([self.from_vector(vec) for vec in rad_basis])
@cached_method
def radical(self):
'\n Return the Jacobson radical of ``self``.\n\n This uses :meth:`radical_basis`, whose default\n implementation handles algebras over fields of\n characteristic zero or fields of characteristic `p` in\n which we can compute `x^{1/p}`.\n\n .. SEEALSO:: :meth:`radical_basis`, :meth:`semisimple_quotient`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: radical = A.radical(); radical\n Radical of An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n\n The radical is an ideal of `A`, and thus a finite\n dimensional non unital associative algebra::\n\n sage: # needs sage.graphs sage.modules\n sage: from sage.categories.associative_algebras import AssociativeAlgebras\n sage: radical in AssociativeAlgebras(QQ).WithBasis().FiniteDimensional()\n True\n sage: radical in Algebras(QQ)\n False\n\n sage: # needs sage.graphs sage.modules\n sage: radical.dimension()\n 2\n sage: radical.basis()\n Finite family {0: B[0], 1: B[1]}\n sage: radical.ambient() is A\n True\n sage: [c.lift() for c in radical.basis()]\n [a, b]\n\n .. TODO::\n\n - Tell Sage that the radical is in fact an ideal;\n - Pickling by construction, as ``A.center()``;\n - Lazy evaluation of ``_repr_``.\n\n TESTS::\n\n sage: # needs sage.graphs sage.modules\n sage: TestSuite(radical).run()\n '
category = AssociativeAlgebras(self.base_ring()).WithBasis().FiniteDimensional().Subobjects()
radical = self.submodule(self.radical_basis(), category=category, already_echelonized=True)
radical.rename('Radical of {}'.format(self))
return radical
@cached_method
def semisimple_quotient(self):
"\n Return the semisimple quotient of ``self``.\n\n This is the quotient of ``self`` by its radical.\n\n .. SEEALSO:: :meth:`radical`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: a,b,x,y = sorted(A.basis())\n sage: S = A.semisimple_quotient(); S\n Semisimple quotient of An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: S in Algebras(QQ).Semisimple()\n True\n sage: S.basis()\n Finite family {'x': B['x'], 'y': B['y']}\n sage: xs,ys = sorted(S.basis())\n sage: (xs + ys) * xs\n B['x']\n\n Sanity check: the semisimple quotient of the `n`-th\n descent algebra of the symmetric group is of dimension the\n number of partitions of `n`::\n\n sage: [ DescentAlgebra(QQ,n).B().semisimple_quotient().dimension() # needs sage.combinat sage.modules\n ....: for n in range(6) ]\n [1, 1, 2, 3, 5, 7]\n sage: [Partitions(n).cardinality() for n in range(10)] # needs sage.combinat\n [1, 1, 2, 3, 5, 7, 11, 15, 22, 30]\n\n .. TODO::\n\n - Pickling by construction, as ``A.semisimple_quotient()``?\n - Lazy evaluation of ``_repr_``\n\n TESTS::\n\n sage: TestSuite(S).run() # needs sage.graphs sage.modules\n "
ring = self.base_ring()
category = Algebras(ring).WithBasis().FiniteDimensional().Quotients().Semisimple()
result = self.quotient_module(self.radical(), category=category)
result.rename('Semisimple quotient of {}'.format(self))
return result
@cached_method
def center_basis(self):
'\n Return a basis of the center of ``self``.\n\n OUTPUT:\n\n - a list of elements of ``self``.\n\n .. SEEALSO:: :meth:`center`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: A.center_basis()\n (x + y,)\n '
return self.annihilator_basis(self.algebra_generators(), self.bracket)
@cached_method
def center(self):
'\n Return the center of ``self``.\n\n .. SEEALSO:: :meth:`center_basis`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: center = A.center(); center\n Center of An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: center in Algebras(QQ).WithBasis().FiniteDimensional().Commutative()\n True\n sage: center.dimension()\n 1\n sage: center.basis()\n Finite family {0: B[0]}\n sage: center.ambient() is A\n True\n sage: [c.lift() for c in center.basis()]\n [x + y]\n\n The center of a semisimple algebra is semisimple::\n\n sage: A = DihedralGroup(6).algebra(QQ) # needs sage.groups sage.modules\n sage: A.center() in Algebras(QQ).Semisimple() # needs sage.groups sage.modules\n True\n\n .. TODO::\n\n - Pickling by construction, as ``A.center()``?\n - Lazy evaluation of ``_repr_``\n\n TESTS::\n\n sage: TestSuite(center).run() # needs sage.graphs sage.modules\n '
category = Algebras(self.base_ring()).FiniteDimensional().Subobjects().Commutative().WithBasis()
if (self in Algebras.Semisimple):
category = category.Semisimple()
center = self.submodule(self.center_basis(), category=category, already_echelonized=True)
center.rename('Center of {}'.format(self))
return center
def principal_ideal(self, a, side='left'):
"\n Construct the ``side`` principal ideal generated by ``a``.\n\n EXAMPLES:\n\n In order to highlight the difference between left and\n right principal ideals, our first example deals with a non\n commutative algebra::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: x, y, a, b = A.basis()\n\n In this algebra, multiplication on the right by `x`\n annihilates all basis elements but `x`::\n\n sage: x*x, y*x, a*x, b*x # needs sage.graphs sage.modules\n (x, 0, 0, 0)\n\n so the left ideal generated by `x` is one-dimensional::\n\n sage: Ax = A.principal_ideal(x, side='left'); Ax # needs sage.graphs sage.modules\n Free module generated by {0} over Rational Field\n sage: [B.lift() for B in Ax.basis()] # needs sage.graphs sage.modules\n [x]\n\n Multiplication on the left by `x` annihilates\n only `x` and fixes the other basis elements::\n\n sage: x*x, x*y, x*a, x*b # needs sage.graphs sage.modules\n (x, 0, a, b)\n\n so the right ideal generated by `x` is 3-dimensional::\n\n sage: xA = A.principal_ideal(x, side='right'); xA # needs sage.graphs sage.modules\n Free module generated by {0, 1, 2} over Rational Field\n sage: [B.lift() for B in xA.basis()] # needs sage.graphs sage.modules\n [x, a, b]\n\n .. SEEALSO::\n\n - :meth:`peirce_summand`\n "
return self.submodule([((a * b) if (side == 'right') else (b * a)) for b in self.basis()])
@cached_method
def orthogonal_idempotents_central_mod_radical(self):
'\n Return a family of orthogonal idempotents of ``self`` that project\n on the central orthogonal idempotents of the semisimple quotient.\n\n OUTPUT:\n\n - a list of orthogonal idempotents obtained by lifting the central\n orthogonal idempotents of the semisimple quotient.\n\n ALGORITHM:\n\n The orthogonal idempotents of `A` are obtained by lifting the\n central orthogonal idempotents of the semisimple quotient\n `\\overline{A}`.\n\n Namely, let `(\\overline{f_i})` be the central orthogonal\n idempotents of the semisimple quotient of `A`. We\n recursively construct orthogonal idempotents of `A` by the\n following procedure: assuming `(f_i)_{i < n}` is a set of\n already constructed orthogonal idempotent, we construct\n `f_k` by idempotent lifting of `(1-f) g (1-f)`, where `g`\n is any lift of `\\overline{e_k}` and `f=\\sum_{i<k} f_i`.\n\n See [CR1962]_ for correctness and termination proofs.\n\n .. SEEALSO::\n\n - :meth:`Algebras.SemiSimple.FiniteDimensional.WithBasis.ParentMethods.central_orthogonal_idempotents`\n - :meth:`idempotent_lift`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: A.orthogonal_idempotents_central_mod_radical() # needs sage.rings.number_field\n (x, y)\n\n ::\n\n sage: # needs sage.modules sage.rings.number_field\n sage: Z12 = Monoids().Finite().example(); Z12\n An example of a finite multiplicative monoid: the integers modulo 12\n sage: A = Z12.algebra(QQ)\n sage: idempotents = A.orthogonal_idempotents_central_mod_radical()\n sage: sorted(idempotents, key=str)\n [-B[0] + 1/2*B[4] + 1/2*B[8],\n 1/2*B[4] - 1/2*B[8],\n 1/2*B[9] + 1/2*B[3] - B[0],\n 1/2*B[9] - 1/2*B[3],\n 1/4*B[1] + 1/4*B[11] - 1/4*B[5] - 1/4*B[7],\n 1/4*B[1] - 1/2*B[9] + 1/4*B[5] - 1/4*B[7] + 1/2*B[3] - 1/4*B[11],\n 1/4*B[1] - 1/2*B[9] - 1/2*B[3] + 1/4*B[11] + 1/4*B[5] + 1/4*B[7] + B[0] - 1/2*B[4] - 1/2*B[8],\n 1/4*B[1] - 1/4*B[5] + 1/4*B[7] - 1/4*B[11] - 1/2*B[4] + 1/2*B[8],\n B[0]]\n sage: sum(idempotents) == 1\n True\n sage: all(e*e == e for e in idempotents)\n True\n sage: all(e*f == 0 and f*e == 0\n ....: for e in idempotents for f in idempotents if e != f)\n True\n\n This is best tested with::\n\n sage: A.is_identity_decomposition_into_orthogonal_idempotents(idempotents) # needs sage.graphs sage.modules sage.rings.number_field\n True\n\n We construct orthogonal idempotents for the algebra of the\n `0`-Hecke monoid::\n\n sage: # needs sage.combinat sage.graphs sage.groups sage.modules\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: A = HeckeMonoid(SymmetricGroup(4)).algebra(QQ)\n sage: idempotents = A.orthogonal_idempotents_central_mod_radical()\n sage: A.is_identity_decomposition_into_orthogonal_idempotents(idempotents)\n True\n '
one = self.one()
idempotents = []
f = self.zero()
for g in self.semisimple_quotient().central_orthogonal_idempotents():
fi = self.idempotent_lift((((one - f) * g.lift()) * (one - f)))
idempotents.append(fi)
f = (f + fi)
return tuple(idempotents)
def idempotent_lift(self, x):
"\n Lift an idempotent of the semisimple quotient into an idempotent of ``self``.\n\n Let `A` be this finite dimensional algebra and `\\pi` be\n the projection `A \\rightarrow \\overline{A}` on its\n semisimple quotient. Let `\\overline{x}` be an idempotent\n of `\\overline A`, and `x` any lift thereof in `A`. This\n returns an idempotent `e` of `A` such that `\\pi(e)=\\pi(x)`\n and `e` is a polynomial in `x`.\n\n INPUT:\n\n - `x` -- an element of `A` that projects on an idempotent\n `\\overline x` of the semisimple quotient of `A`.\n Alternatively one may give as input the idempotent\n `\\overline{x}`, in which case some lift thereof will be\n taken for `x`.\n\n OUTPUT: the idempotent `e` of ``self``\n\n ALGORITHM:\n\n Iterate the formula `1 - (1 - x^2)^2` until having an\n idempotent.\n\n See [CR1962]_ for correctness and termination proofs.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example()\n sage: S = A.semisimple_quotient()\n sage: A.idempotent_lift(S.basis()['x'])\n x\n sage: A.idempotent_lift(A.basis()['y'])\n y\n\n .. TODO::\n\n Add some non trivial example\n "
if (not self.is_parent_of(x)):
x = x.lift()
p = self.semisimple_quotient().retract(x)
if ((p * p) != p):
raise ValueError(('%s does not retract to an idempotent.' % p))
x_prev = None
one = self.one()
while (x != x_prev):
tmp = x
x = (one - ((one - (x ** 2)) ** 2))
x_prev = tmp
return x
@cached_method
def cartan_invariants_matrix(self):
'\n Return the Cartan invariants matrix of the algebra.\n\n OUTPUT: a matrix of non negative integers\n\n Let `A` be this finite dimensional algebra and\n `(S_i)_{i\\in I}` be representatives of the right simple\n modules of `A`. Note that their adjoints `S_i^*` are\n representatives of the left simple modules.\n\n Let `(P^L_i)_{i\\in I}` and `(P^R_i)_{i\\in I}` be\n respectively representatives of the corresponding\n indecomposable projective left and right modules of `A`.\n In particular, we assume that the indexing is consistent\n so that `S_i^*=\\operatorname{top} P^L_i` and\n `S_i=\\operatorname{top} P^R_i`.\n\n The *Cartan invariant matrix* `(C_{i,j})_{i,j\\in I}` is a\n matrix of non negative integers that encodes much of the\n representation theory of `A`; namely:\n\n - `C_{i,j}` counts how many times `S_i^*\\otimes S_j`\n appears as composition factor of `A` seen as a bimodule\n over itself;\n\n - `C_{i,j}=\\dim Hom_A(P^R_j, P^R_i)`;\n\n - `C_{i,j}` counts how many times `S_j` appears as\n composition factor of `P^R_i`;\n\n - `C_{i,j}=\\dim Hom_A(P^L_i, P^L_j)`;\n\n - `C_{i,j}` counts how many times `S_i^*` appears as\n composition factor of `P^L_j`.\n\n In the commutative case, the Cartan invariant matrix is\n diagonal. In the context of solving systems of\n multivariate polynomial equations of dimension zero, `A`\n is the quotient of the polynomial ring by the ideal\n generated by the equations, the simple modules correspond\n to the roots, and the numbers `C_{i,i}` give the\n multiplicities of those roots.\n\n .. NOTE::\n\n For simplicity, the current implementation assumes\n that the index set `I` is of the form\n `\\{0,\\dots,n-1\\}`. Better indexations will be possible\n in the future.\n\n ALGORITHM:\n\n The Cartan invariant matrix of `A` is computed from the\n dimension of the summands of its Peirce decomposition.\n\n .. SEEALSO::\n\n - :meth:`peirce_decomposition`\n - :meth:`isotypic_projective_modules`\n\n EXAMPLES:\n\n For a semisimple algebra, in particular for group algebras\n in characteristic zero, the Cartan invariants matrix is\n the identity::\n\n sage: A3 = SymmetricGroup(3).algebra(QQ) # needs sage.groups sage.modules\n sage: A3.cartan_invariants_matrix() # needs sage.groups sage.modules\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n For the path algebra of a quiver, the Cartan invariants\n matrix counts the number of paths between two vertices::\n\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example()\n sage: A.cartan_invariants_matrix() # needs sage.modules sage.rings.number_field\n [1 2]\n [0 1]\n\n In the commutative case, the Cartan invariant matrix is diagonal::\n\n sage: Z12 = Monoids().Finite().example(); Z12\n An example of a finite multiplicative monoid: the integers modulo 12\n sage: A = Z12.algebra(QQ) # needs sage.modules\n sage: A.cartan_invariants_matrix() # needs sage.modules sage.rings.number_field\n [1 0 0 0 0 0 0 0 0]\n [0 1 0 0 0 0 0 0 0]\n [0 0 2 0 0 0 0 0 0]\n [0 0 0 1 0 0 0 0 0]\n [0 0 0 0 2 0 0 0 0]\n [0 0 0 0 0 1 0 0 0]\n [0 0 0 0 0 0 1 0 0]\n [0 0 0 0 0 0 0 2 0]\n [0 0 0 0 0 0 0 0 1]\n\n With the algebra of the `0`-Hecke monoid::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: A = HeckeMonoid(SymmetricGroup(4)).algebra(QQ)\n sage: A.cartan_invariants_matrix() # needs sage.rings.number_field\n [1 0 0 0 0 0 0 0]\n [0 2 1 0 1 1 0 0]\n [0 1 1 0 1 0 0 0]\n [0 0 0 1 0 1 1 0]\n [0 1 1 0 1 0 0 0]\n [0 1 0 1 0 2 1 0]\n [0 0 0 1 0 1 1 0]\n [0 0 0 0 0 0 0 1]\n '
from sage.matrix.constructor import Matrix
from sage.rings.integer_ring import ZZ
A_quo = self.semisimple_quotient()
idempotents_quo = A_quo.central_orthogonal_idempotents()
dim_simples = [A_quo.principal_ideal(e).dimension().sqrt() for e in idempotents_quo]
idempotents = self.orthogonal_idempotents_central_mod_radical()
def C(i, j):
summand = self.peirce_summand(idempotents[i], idempotents[j])
return (summand.dimension() / (dim_simples[i] * dim_simples[j]))
m = Matrix(ZZ, len(idempotents), C)
m.set_immutable()
return m
def isotypic_projective_modules(self, side='left'):
'\n Return the isotypic projective ``side`` ``self``-modules.\n\n Let `P_i` be representatives of the indecomposable\n projective ``side``-modules of this finite dimensional\n algebra `A`, and `S_i` be the associated simple modules.\n\n The regular ``side`` representation of `A` can be\n decomposed as a direct sum `A = \\bigoplus_i Q_i` where\n each `Q_i` is an isotypic projective module; namely `Q_i`\n is the direct sum of `\\dim S_i` copies of the\n indecomposable projective module `P_i`. This decomposition\n is not unique.\n\n The isotypic projective modules are constructed as\n `Q_i=e_iA`, where the `(e_i)_i` is the decomposition of\n the identity into orthogonal idempotents obtained by\n lifting the central orthogonal idempotents of the\n semisimple quotient of `A`.\n\n INPUT:\n\n - ``side`` -- \'left\' or \'right\' (default: \'left\')\n\n OUTPUT: a list of subspaces of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules sage.rings.number_field\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: Q = A.isotypic_projective_modules(side="left"); Q\n [Free module generated by {0} over Rational Field,\n Free module generated by {0, 1, 2} over Rational Field]\n sage: [[x.lift() for x in Qi.basis()]\n ....: for Qi in Q]\n [[x],\n [y, a, b]]\n\n We check that the sum of the dimensions of the isotypic\n projective modules is the dimension of ``self``::\n\n sage: sum([Qi.dimension() for Qi in Q]) == A.dimension() # needs sage.graphs sage.modules sage.rings.number_field\n True\n\n .. SEEALSO::\n\n - :meth:`orthogonal_idempotents_central_mod_radical`\n - :meth:`peirce_decomposition`\n '
return [self.principal_ideal(e, side) for e in self.orthogonal_idempotents_central_mod_radical()]
@cached_method
def peirce_summand(self, ei, ej):
'\n Return the Peirce decomposition summand `e_i A e_j`.\n\n INPUT:\n\n - ``self`` -- an algebra `A`\n\n - ``ei``, ``ej`` -- two idempotents of `A`\n\n OUTPUT: `e_i A e_j`, as a subspace of `A`.\n\n .. SEEALSO::\n\n - :meth:`peirce_decomposition`\n - :meth:`principal_ideal`\n\n EXAMPLES::\n\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example()\n sage: idemp = A.orthogonal_idempotents_central_mod_radical() # needs sage.rings.number_field\n sage: A.peirce_summand(idemp[0], idemp[1]) # needs sage.rings.number_field\n Free module generated by {0, 1} over Rational Field\n sage: A.peirce_summand(idemp[1], idemp[0]) # needs sage.rings.number_field\n Free module generated by {} over Rational Field\n\n We recover the `2\\times2` block of `\\QQ[S_4]`\n corresponding to the unique simple module of dimension `2`\n of the symmetric group `S_4`::\n\n sage: A4 = SymmetricGroup(4).algebra(QQ) # needs sage.groups\n sage: e = A4.central_orthogonal_idempotents()[2] # needs sage.groups sage.rings.number_field\n sage: A4.peirce_summand(e, e) # needs sage.groups sage.rings.number_field\n Free module generated by {0, 1, 2, 3} over Rational Field\n\n TESTS:\n\n We check each idempotent belong to its own Peirce summand\n (see :trac:`24687`)::\n\n sage: # needs sage.groups\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: M = HeckeMonoid(SymmetricGroup(4))\n sage: A = M.algebra(QQ)\n sage: Idms = A.orthogonal_idempotents_central_mod_radical() # needs sage.rings.number_field\n sage: all(A.peirce_summand(e, e).retract(e) # needs sage.rings.number_field\n ....: in A.peirce_summand(e, e) for e in Idms)\n True\n '
B = self.basis()
phi = self.module_morphism(on_basis=(lambda k: ((ei * B[k]) * ej)), codomain=self, triangular='lower')
ideal = phi.matrix(side='right').image()
return self.submodule([self.from_vector(v) for v in ideal.basis()], already_echelonized=True)
def peirce_decomposition(self, idempotents=None, check=True):
'\n Return a Peirce decomposition of ``self``.\n\n Let `(e_i)_i` be a collection of orthogonal idempotents of\n `A` with sum `1`. The *Peirce decomposition* of `A` is the\n decomposition of `A` into the direct sum of the subspaces\n `e_i A e_j`.\n\n With the default collection of orthogonal idempotents, one has\n\n .. MATH::\n\n \\dim e_i A e_j = C_{i,j} \\dim S_i \\dim S_j\n\n where `(S_i)_i` are the simple modules of `A` and\n `(C_{i,j})_{i, j}` is the Cartan invariants matrix.\n\n INPUT:\n\n - ``idempotents`` -- a list of orthogonal idempotents\n `(e_i)_{i=0,\\ldots,n}` of the algebra that sum to `1`\n (default: the idempotents returned by\n :meth:`orthogonal_idempotents_central_mod_radical`)\n\n - ``check`` -- (default: ``True``) whether to check that the\n idempotents are indeed orthogonal and idempotent and\n sum to `1`\n\n OUTPUT:\n\n A list of lists `l` such that ``l[i][j]`` is the subspace\n `e_i A e_j`.\n\n .. SEEALSO::\n\n - :meth:`orthogonal_idempotents_central_mod_radical`\n - :meth:`cartan_invariants_matrix`\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups sage.modules sage.rings.number_field\n sage: A = Algebras(QQ).FiniteDimensional().WithBasis().example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: A.orthogonal_idempotents_central_mod_radical()\n (x, y)\n sage: decomposition = A.peirce_decomposition(); decomposition\n [[Free module generated by {0} over Rational Field,\n Free module generated by {0, 1} over Rational Field],\n [Free module generated by {} over Rational Field,\n Free module generated by {0} over Rational Field]]\n sage: [ [[x.lift() for x in decomposition[i][j].basis()]\n ....: for j in range(2)]\n ....: for i in range(2)]\n [[[x], [a, b]],\n [[], [y]]]\n\n We recover that the group algebra of the symmetric group\n `S_4` is a block matrix algebra::\n\n sage: # needs sage.groups sage.modules sage.rings.number_field\n sage: A = SymmetricGroup(4).algebra(QQ)\n sage: decomposition = A.peirce_decomposition() # long time\n sage: [[decomposition[i][j].dimension() # long time (4s)\n ....: for j in range(len(decomposition))]\n ....: for i in range(len(decomposition))]\n [[9, 0, 0, 0, 0],\n [0, 9, 0, 0, 0],\n [0, 0, 4, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1]]\n\n The dimension of each block is `d^2`, where `d` is the\n dimension of the corresponding simple module of `S_4`. The\n latter are given by::\n\n sage: [p.standard_tableaux().cardinality() for p in Partitions(4)] # needs sage.combinat\n [1, 3, 2, 3, 1]\n '
if (idempotents is None):
idempotents = self.orthogonal_idempotents_central_mod_radical()
if check:
if (not self.is_identity_decomposition_into_orthogonal_idempotents(idempotents)):
raise ValueError('Not a decomposition of the identity into orthogonal idempotents')
return [[self.peirce_summand(ei, ej) for ej in idempotents] for ei in idempotents]
def is_identity_decomposition_into_orthogonal_idempotents(self, l):
'\n Return whether ``l`` is a decomposition of the identity\n into orthogonal idempotents.\n\n INPUT:\n\n - ``l`` -- a list or iterable of elements of ``self``\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.modules\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: x,y,a,b = A.algebra_generators(); x,y,a,b\n (x, y, a, b)\n sage: A.is_identity_decomposition_into_orthogonal_idempotents([A.one()])\n True\n sage: A.is_identity_decomposition_into_orthogonal_idempotents([x, y])\n True\n sage: A.is_identity_decomposition_into_orthogonal_idempotents([x + a, y - a])\n True\n\n Here the idempotents do not sum up to `1`::\n\n sage: A.is_identity_decomposition_into_orthogonal_idempotents([x]) # needs sage.graphs sage.modules\n False\n\n Here `1+x` and `-x` are neither idempotent nor orthogonal::\n\n sage: A.is_identity_decomposition_into_orthogonal_idempotents([1 + x, -x]) # needs sage.graphs sage.modules\n False\n\n With the algebra of the `0`-Hecke monoid::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: A = HeckeMonoid(SymmetricGroup(4)).algebra(QQ)\n sage: idempotents = A.orthogonal_idempotents_central_mod_radical() # needs sage.rings.number_field\n sage: A.is_identity_decomposition_into_orthogonal_idempotents(idempotents) # needs sage.rings.number_field\n True\n\n Here are some more counterexamples:\n\n 1. Some orthogonal elements summing to `1` but not being\n idempotent::\n\n sage: # needs sage.libs.pari sage.modules\n sage: class PQAlgebra(CombinatorialFreeModule):\n ....: def __init__(self, F, p):\n ....: # Construct the quotient algebra F[x] / p,\n ....: # where p is a univariate polynomial.\n ....: R = parent(p); x = R.gen()\n ....: I = R.ideal(p)\n ....: self._xbar = R.quotient(I).gen()\n ....: basis_keys = [self._xbar**i for i in range(p.degree())]\n ....: CombinatorialFreeModule.__init__(self, F, basis_keys,\n ....: category=Algebras(F).FiniteDimensional().WithBasis())\n ....: def x(self):\n ....: return self(self._xbar)\n ....: def one(self):\n ....: return self.basis()[self.base_ring().one()]\n ....: def product_on_basis(self, w1, w2):\n ....: return self.from_vector(vector(w1*w2))\n sage: R.<x> = PolynomialRing(QQ)\n sage: A = PQAlgebra(QQ, x**3 - x**2 + x + 1); y = A.x()\n sage: a, b = y, 1 - y\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a, b))\n False\n\n For comparison::\n\n sage: # needs sage.libs.pari sage.modules\n sage: A = PQAlgebra(QQ, x**2 - x); y = A.x()\n sage: a, b = y, 1-y\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a, b))\n True\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a, A.zero(), b))\n True\n sage: A = PQAlgebra(QQ, x**3 - x**2 + x - 1); y = A.x()\n sage: a = (y**2 + 1) / 2\n sage: b = 1 - a\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a, b))\n True\n\n 2. Some idempotents summing to 1 but not orthogonal::\n\n sage: # needs sage.libs.pari sage.modules\n sage: R.<x> = PolynomialRing(GF(2))\n sage: A = PQAlgebra(GF(2), x)\n sage: a = A.one()\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a,))\n True\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a, a, a))\n False\n\n 3. Some orthogonal idempotents not summing to the identity::\n\n sage: # needs sage.libs.pari sage.modules\n sage: A.is_identity_decomposition_into_orthogonal_idempotents((a,a))\n False\n sage: A.is_identity_decomposition_into_orthogonal_idempotents(())\n False\n '
return ((self.sum(l) == self.one()) and all((((e * e) == e) for e in l)) and all(((((e * f) == 0) and ((f * e) == 0)) for (i, e) in enumerate(l) for f in l[:i])))
@cached_method
def is_commutative(self):
'\n Return whether ``self`` is a commutative algebra.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S4 = SymmetricGroupAlgebra(QQ, 4)\n sage: S4.is_commutative()\n False\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S2.is_commutative()\n True\n '
B = list(self.basis())
try:
B.remove(self.one())
except ValueError:
pass
return all((((b * bp) == (bp * b)) for (i, b) in enumerate(B) for bp in B[(i + 1):]))
class ElementMethods():
def to_matrix(self, base_ring=None, action=operator.mul, side='left'):
'\n Return the matrix of the action of ``self`` on the algebra.\n\n INPUT:\n\n - ``base_ring`` -- the base ring for the matrix to be constructed\n - ``action`` -- a bivariate function (default: :func:`operator.mul`)\n - ``side`` -- \'left\' or \'right\' (default: \'left\')\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: QS3 = SymmetricGroupAlgebra(QQ, 3)\n sage: a = QS3([2,1,3])\n sage: a.to_matrix(side=\'left\')\n [0 0 1 0 0 0]\n [0 0 0 0 1 0]\n [1 0 0 0 0 0]\n [0 0 0 0 0 1]\n [0 1 0 0 0 0]\n [0 0 0 1 0 0]\n sage: a.to_matrix(side=\'right\')\n [0 0 1 0 0 0]\n [0 0 0 1 0 0]\n [1 0 0 0 0 0]\n [0 1 0 0 0 0]\n [0 0 0 0 0 1]\n [0 0 0 0 1 0]\n sage: a.to_matrix(base_ring=RDF, side="left")\n [0.0 0.0 1.0 0.0 0.0 0.0]\n [0.0 0.0 0.0 0.0 1.0 0.0]\n [1.0 0.0 0.0 0.0 0.0 0.0]\n [0.0 0.0 0.0 0.0 0.0 1.0]\n [0.0 1.0 0.0 0.0 0.0 0.0]\n [0.0 0.0 0.0 1.0 0.0 0.0]\n\n AUTHORS: Mike Hansen, ...\n '
basis = self.parent().basis()
action_left = action
if (side == 'right'):
action = (lambda x: action_left(basis[x], self))
else:
action = (lambda x: action_left(self, basis[x]))
endo = self.parent().module_morphism(on_basis=action, codomain=self.parent())
return endo.matrix(base_ring=base_ring)
_matrix_ = to_matrix
on_left_matrix = to_matrix
def __invert__(self):
'\n Return the inverse of ``self`` if it exists, and\n otherwise raise an error.\n\n .. WARNING::\n\n This always returns the inverse or fails on elements\n that are not invertible when the base ring is a field.\n In other cases, it may fail to find an inverse even\n if one exists if we cannot solve a linear system of\n equations over (the fraction field of) the base ring.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: QS3 = SymmetricGroupAlgebra(QQ, 3)\n sage: P = Permutation\n sage: a = 3 * QS3(P([1,2,3])) + QS3(P([1,3,2])) + QS3(P([2,1,3]))\n sage: b = ~a; b\n 9/20*[1, 2, 3] - 7/40*[1, 3, 2] - 7/40*[2, 1, 3]\n + 3/40*[2, 3, 1] + 3/40*[3, 1, 2] - 1/20*[3, 2, 1]\n sage: a * b\n [1, 2, 3]\n sage: ~b == a\n True\n\n sage: # needs sage.groups sage.modules\n sage: a = 3 * QS3.one()\n sage: b = ~a\n sage: b * a == QS3.one()\n True\n sage: b == 1/3 * QS3.one()\n True\n sage: ~b == a\n True\n\n sage: R.<t> = QQ[]\n sage: RS3 = SymmetricGroupAlgebra(R, 3) # needs sage.groups sage.modules\n sage: a = RS3(P([1,2,3])) - RS3(P([1,3,2])) + RS3(P([2,1,3])); ~a # needs sage.groups sage.modules\n -1/2*[1, 3, 2] + 1/2*[2, 1, 3] + 1/2*[2, 3, 1] + 1/2*[3, 1, 2]\n\n Some examples on elements that do not have an inverse::\n\n sage: c = 2 * QS3(P([1,2,3])) + QS3(P([1,3,2])) + QS3(P([2,1,3])) # needs sage.groups sage.modules\n sage: ~c # needs sage.groups sage.modules\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= 2*[1, 2, 3] + [1, 3, 2] + [2, 1, 3])\n\n sage: # needs sage.groups sage.modules\n sage: ZS3 = SymmetricGroupAlgebra(ZZ, 3)\n sage: aZ = 3 * ZS3(P([1,2,3])) + ZS3(P([1,3,2])) + ZS3(P([2,1,3]))\n sage: ~aZ\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= 3*[1, 2, 3] + [1, 3, 2] + [2, 1, 3])\n sage: x = 2 * ZS3.one()\n sage: ~x\n Traceback (most recent call last):\n ...\n ValueError: cannot invert self (= 2*[1, 2, 3])\n\n TESTS:\n\n An algebra that does not define ``one_basis()``::\n\n sage: I = DescentAlgebra(QQ, 3).I() # needs sage.combinat sage.modules\n sage: a = 3 * I.one() # needs sage.combinat sage.modules\n sage: ~a == 1/3 * I.one() # needs sage.combinat sage.modules\n True\n '
alg = self.parent()
R = alg.base_ring()
ob = None
try:
ob = alg.one_basis()
except (AttributeError, TypeError, ValueError):
pass
if (ob is not None):
mc = self.monomial_coefficients(copy=False)
if ((len(mc) == 1) and (ob in mc)):
try:
return alg.term(ob, R((~ mc[ob])))
except (ValueError, TypeError):
raise ValueError(('cannot invert self (= %s)' % self))
e = alg.one().to_vector()
A = self.to_matrix()
try:
inv = A.solve_right(e)
inv.change_ring(R)
return alg.from_vector(inv)
except (ValueError, TypeError):
raise ValueError(('cannot invert self (= %s)' % self))
class Cellular(CategoryWithAxiom_over_base_ring):
'\n Cellular algebras.\n\n Let `R` be a commutative ring. A `R`-algebra `A` is a\n *cellular algebra* if it has a *cell datum*, which is\n a tuple `(\\Lambda, i, M, C)`, where `\\Lambda` is finite\n poset with order `\\ge`, if `\\mu \\in \\Lambda` then `T(\\mu)`\n is a finite set and\n\n .. MATH::\n\n C \\colon \\coprod_{\\mu\\in\\Lambda}T(\\mu) \\times T(\\mu)\n \\longrightarrow A; (\\mu,s,t) \\mapsto c^\\mu_{st}\n \\text{ is an injective map}\n\n such that the following holds:\n\n * The set `\\{c^\\mu_{st}\\mid \\mu\\in\\Lambda, s,t\\in T(\\mu)\\}` is a\n basis of `A`.\n * If `a \\in A` and `\\mu\\in\\Lambda, s,t \\in T(\\mu)` then:\n\n .. MATH::\n\n a c^\\mu_{st} = \\sum_{u\\in T(\\mu)} r_a(s,u) c^\\mu_{ut}\n \\pmod{A^{>\\mu}},\n\n where `A^{>\\mu}` is spanned by\n\n .. MATH::\n\n \\{ c^\\nu_{ab} \\mid \\nu > \\mu \\text{ and } a,b \\in T(\\nu) \\}.\n\n Moreover, the scalar `r_a(s,u)` depends only on `a`, `s` and\n `u` and, in particular, is independent of `t`.\n\n * The map `\\iota \\colon A \\longrightarrow A; c^\\mu_{st} \\mapsto\n c^\\mu_{ts}` is an algebra anti-isomorphism.\n\n A *cellular basis* for `A` is any basis of the form\n `\\{c^\\mu_{st} \\mid \\mu \\in \\Lambda, s,t \\in T(\\mu)\\}`.\n\n Note that in particular, the scalars `r_a(u, s)` in the second\n condition do not depend on `t`.\n\n REFERENCES:\n\n - [GrLe1996]_\n - [KX1998]_\n - [Mat1999]_\n - :wikipedia:`Cellular_algebra`\n - http://webusers.imj-prg.fr/~bernhard.keller/ictp2006/lecturenotes/xi.pdf\n '
class ParentMethods():
def _test_cellular(self, **options):
'\n Check that ``self`` satisfies the properties of a\n cellular algebra.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.combinat sage.modules\n sage: S._test_cellular() # needs sage.combinat sage.modules\n '
tester = self._tester(**options)
cell_basis = self.cellular_basis()
B = cell_basis.basis()
P = self.cell_poset()
for mu in P:
C = self.cell_module_indices(mu)
for s in C:
t = C[0]
vals = []
basis_elt = B[(mu, s, t)]
for a in B:
elt = (a * basis_elt)
tester.assertTrue(all(((P.lt(i[0], mu) or (i[2] == t)) for i in elt.support())))
vals.append([elt[(mu, u, t)] for u in C])
for t in C[1:]:
basis_elt = B[(mu, s, t)]
for (i, a) in enumerate(B):
elt = (a * basis_elt)
tester.assertTrue(all(((P.lt(i[0], mu) or (i[2] == t)) for i in elt.support())))
tester.assertEqual(vals[i], [elt[(mu, u, t)] for u in C])
@abstract_method
def cell_poset(self):
'\n Return the cell poset of ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 4) # needs sage.groups sage.modules\n sage: S.cell_poset() # needs sage.groups sage.modules\n Finite poset containing 5 elements\n '
@abstract_method
def cell_module_indices(self, mu):
'\n Return the indices of the cell module of ``self``\n indexed by ``mu`` .\n\n This is the finite set `M(\\lambda)`.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: S.cell_module_indices([2,1]) # needs sage.groups sage.modules\n Standard tableaux of shape [2, 1]\n '
@abstract_method(optional=True)
def _to_cellular_element(self, i):
'\n Return the image of the basis index ``i`` in the\n cellular basis of ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: S._to_cellular_element # no implementation currently uses this # needs sage.groups sage.modules\n NotImplemented\n '
@abstract_method(optional=True)
def _from_cellular_index(self, x):
'\n Return the image in ``self`` from the index of the\n cellular basis ``x``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: S = SymmetricGroupAlgebra(QQ, 3)\n sage: mu = Partition([2,1])\n sage: s = StandardTableau([[1,2],[3]])\n sage: t = StandardTableau([[1,3],[2]])\n sage: S._from_cellular_index((mu, s, t))\n 1/4*[1, 3, 2] - 1/4*[2, 3, 1] + 1/4*[3, 1, 2] - 1/4*[3, 2, 1]\n '
def cellular_involution(self, x):
'\n Return the cellular involution of ``x`` in ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: for b in S.basis(): b, S.cellular_involution(b) # needs sage.groups sage.modules\n ([1, 2, 3], [1, 2, 3])\n ([1, 3, 2], 49/48*[1, 3, 2] + 7/48*[2, 3, 1]\n - 7/48*[3, 1, 2] - 1/48*[3, 2, 1])\n ([2, 1, 3], [2, 1, 3])\n ([2, 3, 1], -7/48*[1, 3, 2] - 1/48*[2, 3, 1]\n + 49/48*[3, 1, 2] + 7/48*[3, 2, 1])\n ([3, 1, 2], 7/48*[1, 3, 2] + 49/48*[2, 3, 1]\n - 1/48*[3, 1, 2] - 7/48*[3, 2, 1])\n ([3, 2, 1], -1/48*[1, 3, 2] - 7/48*[2, 3, 1]\n + 7/48*[3, 1, 2] + 49/48*[3, 2, 1])\n '
C = self.cellular_basis()
if (C is self):
M = x.monomial_coefficients(copy=False)
return self._from_dict({(i[0], i[2], i[1]): M[i] for i in M}, remove_zeros=False)
return self(C(x).cellular_involution())
@cached_method
def cells(self):
'\n Return the cells of ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: dict(S.cells()) # needs sage.groups sage.modules\n {[1, 1, 1]: Standard tableaux of shape [1, 1, 1],\n [2, 1]: Standard tableaux of shape [2, 1],\n [3]: Standard tableaux of shape [3]}\n '
from sage.sets.family import Family
return Family(self.cell_poset(), self.cell_module_indices)
def cellular_basis(self):
'\n Return the cellular basis of ``self``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: S.cellular_basis() # needs sage.groups sage.modules\n Cellular basis of Symmetric group algebra of order 3\n over Rational Field\n '
from sage.algebras.cellular_basis import CellularBasis
return CellularBasis(self)
def cell_module(self, mu, **kwds):
'\n Return the cell module indexed by ``mu``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: S.cell_module(Partition([2,1])) # needs sage.combinat sage.groups sage.modules\n Cell module indexed by [2, 1] of Cellular basis of\n Symmetric group algebra of order 3 over Rational Field\n '
from sage.modules.with_basis.cell_module import CellModule
return CellModule(self.cellular_basis(), mu, **kwds)
@cached_method
def simple_module_parameterization(self):
'\n Return a parameterization of the simple modules of ``self``.\n\n The set of simple modules are parameterized by\n `\\lambda \\in \\Lambda` such that the cell module\n bilinear form `\\Phi_{\\lambda} \\neq 0`.\n\n EXAMPLES::\n\n sage: S = SymmetricGroupAlgebra(QQ, 4) # needs sage.groups sage.modules\n sage: S.simple_module_parameterization() # needs sage.groups sage.modules\n ([1, 1, 1, 1], [2, 1, 1], [2, 2], [3, 1], [4])\n\n sage: S = SymmetricGroupAlgebra(GF(3), 4) # needs sage.groups sage.modules\n sage: S.simple_module_parameterization() # needs sage.groups sage.modules\n ([2, 1, 1], [2, 2], [3, 1], [4])\n\n sage: S = SymmetricGroupAlgebra(GF(4), 4) # needs sage.groups sage.modules\n sage: S.simple_module_parameterization() # needs sage.groups sage.modules\n ([3, 1], [4])\n '
return tuple([mu for mu in self.cell_poset() if self.cell_module(mu).nonzero_bilinear_form()])
class ElementMethods():
def cellular_involution(self):
'\n Return the cellular involution on ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S = SymmetricGroupAlgebra(QQ, 4)\n sage: elt = S([3,1,2,4])\n sage: ci = elt.cellular_involution(); ci\n 7/48*[1, 3, 2, 4] + 49/48*[2, 3, 1, 4]\n - 1/48*[3, 1, 2, 4] - 7/48*[3, 2, 1, 4]\n sage: ci.cellular_involution()\n [3, 1, 2, 4]\n '
return self.parent().cellular_involution(self)
class TensorProducts(TensorProductsCategory):
'\n The category of cellular algebras constructed by tensor\n product of cellular algebras.\n '
@cached_method
def extra_super_categories(self):
'\n Tensor products of cellular algebras are cellular.\n\n EXAMPLES::\n\n sage: cat = Algebras(QQ).FiniteDimensional().WithBasis()\n sage: cat.Cellular().TensorProducts().extra_super_categories()\n [Category of finite dimensional cellular algebras with basis\n over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
@cached_method
def cell_poset(self):
'\n Return the cell poset of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: T = S2.tensor(S3)\n sage: T.cell_poset() # needs sage.combinat sage.graphs\n Finite poset containing 6 elements\n '
ret = self._sets[0].cell_poset()
for A in self._sets[1:]:
ret = ret.product(A.cell_poset())
return ret
def cell_module_indices(self, mu):
'\n Return the indices of the cell module of ``self``\n indexed by ``mu`` .\n\n This is the finite set `M(\\lambda)`.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: T = S2.tensor(S3)\n sage: T.cell_module_indices(([1,1], [2,1]))\n The Cartesian product of (Standard tableaux of shape [1, 1],\n Standard tableaux of shape [2, 1])\n '
from sage.categories.cartesian_product import cartesian_product
return cartesian_product([self._sets[i].cell_module_indices(x) for (i, x) in enumerate(mu)])
@lazy_attribute
def cellular_involution(self):
'\n Return the image of the cellular involution of the basis\n element indexed by ``i``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: T = S2.tensor(S3)\n sage: for b in T.basis(): b, T.cellular_involution(b)\n ([1, 2] # [1, 2, 3], [1, 2] # [1, 2, 3])\n ([1, 2] # [1, 3, 2],\n 49/48*[1, 2] # [1, 3, 2] + 7/48*[1, 2] # [2, 3, 1]\n - 7/48*[1, 2] # [3, 1, 2] - 1/48*[1, 2] # [3, 2, 1])\n ([1, 2] # [2, 1, 3], [1, 2] # [2, 1, 3])\n ([1, 2] # [2, 3, 1],\n -7/48*[1, 2] # [1, 3, 2] - 1/48*[1, 2] # [2, 3, 1]\n + 49/48*[1, 2] # [3, 1, 2] + 7/48*[1, 2] # [3, 2, 1])\n ([1, 2] # [3, 1, 2],\n 7/48*[1, 2] # [1, 3, 2] + 49/48*[1, 2] # [2, 3, 1]\n - 1/48*[1, 2] # [3, 1, 2] - 7/48*[1, 2] # [3, 2, 1])\n ([1, 2] # [3, 2, 1],\n -1/48*[1, 2] # [1, 3, 2] - 7/48*[1, 2] # [2, 3, 1]\n + 7/48*[1, 2] # [3, 1, 2] + 49/48*[1, 2] # [3, 2, 1])\n ([2, 1] # [1, 2, 3], [2, 1] # [1, 2, 3])\n ([2, 1] # [1, 3, 2],\n 49/48*[2, 1] # [1, 3, 2] + 7/48*[2, 1] # [2, 3, 1]\n - 7/48*[2, 1] # [3, 1, 2] - 1/48*[2, 1] # [3, 2, 1])\n ([2, 1] # [2, 1, 3], [2, 1] # [2, 1, 3])\n ([2, 1] # [2, 3, 1],\n -7/48*[2, 1] # [1, 3, 2] - 1/48*[2, 1] # [2, 3, 1]\n + 49/48*[2, 1] # [3, 1, 2] + 7/48*[2, 1] # [3, 2, 1])\n ([2, 1] # [3, 1, 2],\n 7/48*[2, 1] # [1, 3, 2] + 49/48*[2, 1] # [2, 3, 1]\n - 1/48*[2, 1] # [3, 1, 2] - 7/48*[2, 1] # [3, 2, 1])\n ([2, 1] # [3, 2, 1],\n -1/48*[2, 1] # [1, 3, 2] - 7/48*[2, 1] # [2, 3, 1]\n + 7/48*[2, 1] # [3, 1, 2] + 49/48*[2, 1] # [3, 2, 1])\n '
if (self.cellular_basis() is self):
def func(x):
M = x.monomial_coefficients(copy=False)
return self._from_dict({(i[0], i[2], i[1]): M[i] for i in M}, remove_zeros=False)
return self.module_morphism(function=func, codomain=self)
def on_basis(i):
return self._tensor_of_elements([A.basis()[i[j]].cellular_involution() for (j, A) in enumerate(self._sets)])
return self.module_morphism(on_basis, codomain=self)
@cached_method
def _to_cellular_element(self, i):
'\n Return the image of the basis index ``i`` in the\n cellular basis of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: T = S2.tensor(S3)\n sage: all(T(T._to_cellular_element(k)).leading_support() == k\n ....: for k in T.basis().keys())\n True\n '
C = [A.cellular_basis() for A in self._sets]
elts = [C[j](self._sets[j].basis()[ij]) for (j, ij) in enumerate(i)]
from sage.categories.tensor import tensor
T = tensor(C)
temp = T._tensor_of_elements(elts)
B = self.cellular_basis()
M = temp.monomial_coefficients(copy=False)
def convert_index(i):
mu = []
s = []
t = []
for (a, b, c) in i:
mu.append(a)
s.append(b)
t.append(c)
C = self.cell_module_indices(mu)
return (tuple(mu), C(s), C(t))
return B._from_dict({convert_index(i): M[i] for i in M}, remove_zeros=False)
@cached_method
def _from_cellular_index(self, x):
'\n Return the image in ``self`` from the index of the\n cellular basis ``x``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroupAlgebra(QQ, 2)\n sage: S3 = SymmetricGroupAlgebra(QQ, 3)\n sage: T = S2.tensor(S3)\n sage: C = T.cellular_basis()\n sage: all(C(T._from_cellular_index(k)).leading_support() == k\n ....: for k in C.basis().keys())\n True\n '
elts = [A(A.cellular_basis().basis()[(x[0][i], x[1][i], x[2][i])]) for (i, A) in enumerate(self._sets)]
return self._tensor_of_elements(elts)
class SubcategoryMethods():
@cached_method
def Cellular(self):
"\n Return the full subcategory of the cellular objects\n of ``self``.\n\n .. SEEALSO:: :wikipedia:`Cellular_algebra`\n\n EXAMPLES::\n\n sage: Algebras(QQ).FiniteDimensional().WithBasis().Cellular()\n Category of finite dimensional cellular algebras with basis\n over Rational Field\n\n TESTS::\n\n sage: cat = Algebras(QQ).FiniteDimensional().WithBasis()\n sage: TestSuite(cat.Cellular()).run()\n sage: HopfAlgebras(QQ).FiniteDimensional().WithBasis().Cellular.__module__\n 'sage.categories.finite_dimensional_algebras_with_basis'\n "
return self._with_axiom('Cellular')
|
def FiniteDimensionalBialgebrasWithBasis(base_ring):
'\n The category of finite dimensional bialgebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = FiniteDimensionalBialgebrasWithBasis(QQ); C\n Category of finite dimensional bialgebras with basis over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of bialgebras with basis over Rational Field,\n Category of finite dimensional algebras with basis over Rational Field]\n sage: C is Bialgebras(QQ).WithBasis().FiniteDimensional()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
from sage.categories.bialgebras_with_basis import BialgebrasWithBasis
return BialgebrasWithBasis(base_ring).FiniteDimensional()
|
def FiniteDimensionalCoalgebrasWithBasis(base_ring):
'\n The category of finite dimensional coalgebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = FiniteDimensionalCoalgebrasWithBasis(QQ); C\n Category of finite dimensional coalgebras with basis over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of coalgebras with basis over Rational Field,\n Category of finite dimensional vector spaces with basis over Rational Field]\n sage: C is Coalgebras(QQ).WithBasis().FiniteDimensional()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
from sage.categories.coalgebras_with_basis import CoalgebrasWithBasis
return CoalgebrasWithBasis(base_ring).FiniteDimensional()
|
class FiniteDimensionalGradedLieAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional graded Lie algebras with a basis.\n\n A grading of a Lie algebra `\\mathfrak{g}` is a direct sum decomposition\n `\\mathfrak{g} = \\bigoplus_{i} V_i` such that `[V_i,V_j] \\subset V_{i+j}`.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(ZZ).WithBasis().FiniteDimensional().Graded(); C\n Category of finite dimensional graded Lie algebras with basis over Integer Ring\n sage: C.super_categories()\n [Category of graded Lie algebras with basis over Integer Ring,\n Category of finite dimensional Lie algebras with basis over Integer Ring]\n\n sage: C is LieAlgebras(ZZ).WithBasis().FiniteDimensional().Graded()\n True\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis().Graded()\n sage: TestSuite(C).run()\n '
class ParentMethods():
def _test_grading(self, **options):
"\n Tests that the Lie bracket respects the grading.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = LieAlgebras(QQ).WithBasis().Graded()\n sage: C = C.FiniteDimensional().Stratified().Nilpotent()\n sage: L = LieAlgebra(QQ, {('x','y'): {'z': 1}},\n ....: nilpotent=True, category=C)\n sage: L._test_grading()\n sage: L = LieAlgebra(QQ, {('x','y'): {'x': 1}},\n ....: nilpotent=True, category=C)\n sage: L._test_grading()\n Traceback (most recent call last):\n ...\n AssertionError: Lie bracket [x, y] has degree 1, not degree 2\n\n See the documentation for :class:`TestSuite` for more information.\n "
tester = self._tester(**options)
from sage.misc.misc import some_tuples
for (X, Y) in some_tuples(self.basis(), 2, tester._max_runs):
i = X.degree()
j = Y.degree()
Z = self.bracket(X, Y)
if (Z == 0):
continue
Zdeg = Z.degree()
tester.assertEqual(Zdeg, (i + j), msg=('Lie bracket [%s, %s] has degree %s, not degree %s ' % (X, Y, Zdeg, (i + j))))
tester.assertIn(Z.to_vector(), self.homogeneous_component_as_submodule((i + j)), msg=('Lie bracket [%s, %s] is not in the homogeneous component of degree %s' % (X, Y, (i + j))))
@cached_method
def homogeneous_component_as_submodule(self, d):
"\n Return the ``d``-th homogeneous component of ``self``\n as a submodule.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ).WithBasis().Graded()\n sage: C = C.FiniteDimensional().Stratified().Nilpotent()\n sage: L = LieAlgebra(QQ, {('x','y'): {'z': 1}}, # needs sage.combinat sage.modules\n ....: nilpotent=True, category=C)\n sage: L.homogeneous_component_as_submodule(2) # needs sage.combinat sage.modules\n Sparse vector space of degree 3 and dimension 1 over Rational Field\n Basis matrix:\n [0 0 1]\n "
B = self.homogeneous_component_basis(d)
return self.module().submodule([X.to_vector() for X in B])
class Stratified(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional stratified Lie algebras with a basis.\n\n A stratified Lie algebra is a graded Lie algebra that is generated\n as a Lie algebra by its homogeneous component of degree 1. That is\n to say, for a graded Lie algebra `L = \\bigoplus_{k=1}^M L_k`,\n we have `L_{k+1} = [L_1, L_k]`.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ).WithBasis().Graded().Stratified().FiniteDimensional()\n sage: C\n Category of finite dimensional stratified Lie algebras with basis over Rational Field\n\n A finite-dimensional stratified Lie algebra is nilpotent::\n\n sage: C is C.Nilpotent()\n True\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).WithBasis().Graded().FiniteDimensional().Stratified()\n sage: TestSuite(C).run()\n '
class ParentMethods():
def _test_generated_by_degree_one(self, **options):
"\n Tests that the Lie algebra is generated by the homogeneous\n component of degree one.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by\n :meth:`_tester`\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ).WithBasis().Graded()\n sage: C = C.FiniteDimensional().Stratified().Nilpotent()\n sage: sc = {('x','y'): {'z': 1}}\n sage: L.<x,y,z> = LieAlgebra(QQ, sc, nilpotent=True, category=C) # needs sage.combinat sage.modules\n sage: L._test_generated_by_degree_one() # needs sage.combinat sage.modules\n\n sage: sc = {('x','y'): {'z': 1}, ('a','b'): {'c':1}, ('z','c'): {'m':1}}\n sage: L.<a,b,c,m,x,y,z> = LieAlgebra(QQ, sc, nilpotent=True, category=C) # needs sage.combinat sage.modules\n sage: L._test_generated_by_degree_one() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n AssertionError: [a, b, x, y] does not generate Nilpotent Lie algebra\n on 7 generators (a, b, c, m, x, y, z) over Rational Field\n\n See the documentation for :class:`TestSuite` for more information.\n "
tester = self._tester(**options)
V1 = self.homogeneous_component_as_submodule(1)
B1 = V1.basis()
m = self.module()
V = V1
d = 0
i = 0
while (V.dimension() > d):
if (i > tester._max_runs):
return
B = V.basis()
d = V.dimension()
V = m.submodule((B + [self.bracket(X, Y).to_vector() for X in B1 for Y in B]))
tester.assertEqual(V, m, msg=('%s does not generate %s' % ([self(X) for X in B1], self)))
def degree_on_basis(self, m):
"\n Return the degree of the basis element indexed by ``m``.\n\n If the degrees of the basis elements are not defined,\n they will be computed. By assumption the stratification\n `L_1 \\oplus \\cdots \\oplus L_s` of ``self`` is such that each\n component `L_k` is spanned by some subset of the basis.\n\n The degree of a basis element `X` is therefore the largest\n index `k` such that `X \\in L_k \\oplus \\cdots \\oplus L_s`. The\n space `L_k \\oplus \\cdots \\oplus L_s` is by assumption the\n `k`-th term of the lower central series.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = LieAlgebras(QQ).WithBasis().Graded()\n sage: C = C.FiniteDimensional().Stratified().Nilpotent()\n sage: sc = {('X','Y'): {'Z': 1}}\n sage: L.<X,Y,Z> = LieAlgebra(QQ, sc, nilpotent=True, category=C)\n sage: L.degree_on_basis(X.leading_support())\n 1\n sage: X.degree()\n 1\n sage: Y.degree()\n 1\n sage: L[X, Y]\n Z\n sage: Z.degree()\n 2\n "
if (not hasattr(self, '_basis_degrees')):
lcs = self.lower_central_series(submodule=True)
self._basis_degrees = {}
for k in reversed(range((len(lcs) - 1))):
for X in self.basis():
if (X in self._basis_degrees):
continue
if (X.to_vector() in lcs[k]):
self._basis_degrees[X] = (k + 1)
m = self.basis()[m]
return self._basis_degrees[m]
|
class FiniteDimensionalHopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of finite dimensional Hopf algebras with a\n distinguished basis.\n\n EXAMPLES::\n\n sage: FiniteDimensionalHopfAlgebrasWithBasis(QQ)\n Category of finite dimensional Hopf algebras with basis over Rational Field\n sage: FiniteDimensionalHopfAlgebrasWithBasis(QQ).super_categories()\n [Category of Hopf algebras with basis over Rational Field,\n Category of finite dimensional algebras with basis over Rational Field]\n\n TESTS::\n\n sage: TestSuite(FiniteDimensionalHopfAlgebrasWithBasis(ZZ)).run()\n '
class ParentMethods():
pass
class ElementMethods():
pass
|
class FiniteDimensionalLieAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional Lie algebras with a basis.\n\n .. TODO::\n\n Many of these tests should use non-abelian Lie algebras and need to\n be added after :trac:`16820`.\n '
_base_category_class_and_axiom = (LieAlgebras.FiniteDimensional, 'WithBasis')
def example(self, n=3):
'\n Return an example of a finite dimensional Lie algebra with basis as per\n :meth:`Category.example <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis()\n sage: C.example() # needs sage.modules\n An example of a finite dimensional Lie algebra with basis:\n the 3-dimensional abelian Lie algebra over Rational Field\n\n Other dimensions can be specified as an optional argument::\n\n sage: C.example(5) # needs sage.modules\n An example of a finite dimensional Lie algebra with basis:\n the 5-dimensional abelian Lie algebra over Rational Field\n '
from sage.categories.examples.finite_dimensional_lie_algebras_with_basis import Example
return Example(self.base_ring(), n)
Nilpotent = LazyImport('sage.categories.finite_dimensional_nilpotent_lie_algebras_with_basis', 'FiniteDimensionalNilpotentLieAlgebrasWithBasis')
class ParentMethods():
@cached_method
def _construct_UEA(self):
"\n Construct the universal enveloping algebra of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.libs.singular sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: UEA = L._construct_UEA(); UEA\n Noncommutative Multivariate Polynomial Ring in b0, b1, b2\n over Rational Field, nc-relations: {}\n sage: UEA.relations(add_commutative=True)\n {b1*b0: b0*b1, b2*b0: b0*b2, b2*b1: b1*b2}\n\n ::\n\n sage: # needs sage.combinat sage.libs.singular sage.modules\n sage: L.<x,y,z> = LieAlgebra(QQ, {('x','y'): {'z':1},\n ....: ('y','z'): {'x':1},\n ....: ('z','x'):{'y':1}})\n sage: UEA = L._construct_UEA(); UEA\n Noncommutative Multivariate Polynomial Ring in x, y, z over Rational Field,\n nc-relations: {...}\n sage: sorted(UEA.relations().items(), key=str)\n [(y*x, x*y - z), (z*x, x*z + y), (z*y, y*z - x)]\n\n Singular's ``nc_algebra`` does not work over `\\ZZ/6\\ZZ`,\n so we fallback to the PBW basis in this case::\n\n sage: L = lie_algebras.pwitt(Zmod(6), 6) # needs sage.combinat sage.modules\n sage: L._construct_UEA() # needs sage.combinat sage.libs.singular sage.modules\n Universal enveloping algebra of\n The 6-Witt Lie algebra over Ring of integers modulo 6\n in the Poincare-Birkhoff-Witt basis\n "
from sage.algebras.free_algebra import FreeAlgebra
I = self._basis_ordering
try:
names = [str(x) for x in I]
def names_map(x):
return x
F = FreeAlgebra(self.base_ring(), names)
except ValueError:
names = ['b{}'.format(i) for i in range(self.dimension())]
self._UEA_names_map = {g: names[i] for (i, g) in enumerate(I)}
names_map = self._UEA_names_map.__getitem__
F = FreeAlgebra(self.base_ring(), names)
d = F.gens_dict()
rels = {}
S = self.structure_coefficients(True)
def get_var(g):
return d[names_map(g)]
for k in S.keys():
g0 = get_var(k[0])
g1 = get_var(k[1])
if (g0 < g1):
rels[(g1 * g0)] = ((g0 * g1) - F.sum(((val * get_var(g)) for (g, val) in S[k])))
else:
rels[(g0 * g1)] = ((g1 * g0) + F.sum(((val * get_var(g)) for (g, val) in S[k])))
try:
return F.g_algebra(rels)
except RuntimeError:
return self.pbw_basis()
@lazy_attribute
def _basis_ordering(self):
'\n Return the indices of the basis of ``self`` as a tuple in\n a fixed order.\n\n Override this attribute to get a specific ordering of the basis.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L._basis_ordering # needs sage.modules\n (0, 1, 2)\n '
return tuple(self.basis().keys())
@lazy_attribute
def _basis_key_inverse(self):
'\n A dictionary for keys to their appropriate index given by\n ``self._basis_ordering``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: G = SymmetricGroup(3)\n sage: S = GroupAlgebra(G, QQ)\n sage: L = LieAlgebra(associative=S)\n sage: [L._basis_key_inverse[k] for k in L._basis_ordering]\n [0, 1, 2, 3, 4, 5]\n '
return {k: i for (i, k) in enumerate(self._basis_ordering)}
def _basis_key(self, x):
"\n Return a key for sorting for the index ``x``.\n\n TESTS::\n\n sage: L = lie_algebras.three_dimensional_by_rank(QQ, 3, # needs sage.groups sage.modules\n ....: names=['E','F','H'])\n sage: PBW = L.pbw_basis() # needs sage.groups sage.modules\n sage: PBW._basis_key('E') < PBW._basis_key('H') # needs sage.groups sage.modules\n True\n\n ::\n\n sage: L = lie_algebras.sl(QQ, 2) # needs sage.groups sage.modules\n sage: def neg_key(x):\n ....: return -L.basis().keys().index(x)\n sage: PBW = L.pbw_basis(basis_key=neg_key) # needs sage.groups sage.modules\n sage: prod(PBW.gens()) # indirect doctest # needs sage.groups sage.modules\n PBW[-alpha[1]]*PBW[alphacheck[1]]*PBW[alpha[1]]\n - 4*PBW[-alpha[1]]*PBW[alpha[1]] + PBW[alphacheck[1]]^2\n - 2*PBW[alphacheck[1]]\n\n Check that :trac:`23266` is fixed::\n\n sage: # needs sage.groups sage.modules\n sage: sl2 = lie_algebras.sl(QQ, 2, 'matrix')\n sage: sl2.indices()\n {'e1', 'f1', 'h1'}\n sage: type(sl2.basis().keys())\n <class 'list'>\n sage: Usl2 = sl2.pbw_basis()\n sage: Usl2._basis_key(2)\n 2\n sage: Usl2._basis_key(3)\n Traceback (most recent call last):\n ...\n KeyError: 3\n "
return self._basis_key_inverse[x]
def _dense_free_module(self, R=None):
'\n Return a dense free module associated to ``self`` over ``R``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L._dense_free_module() # needs sage.modules\n Vector space of dimension 3 over Rational Field\n '
if (R is None):
R = self.base_ring()
from sage.modules.free_module import FreeModule
return FreeModule(R, self.dimension())
module = _dense_free_module
def from_vector(self, v, order=None):
'\n Return the element of ``self`` corresponding to the\n vector ``v`` in ``self.module()``.\n\n Implement this if you implement :meth:`module`; see the\n documentation of\n :meth:`sage.categories.lie_algebras.LieAlgebras.module`\n for how this is to be done.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: u = L.from_vector(vector(QQ, (1, 0, 0))); u # needs sage.modules\n (1, 0, 0)\n sage: parent(u) is L # needs sage.modules\n True\n '
if (order is None):
order = self._basis_ordering
B = self.basis()
return self.sum(((v[i] * B[k]) for (i, k) in enumerate(order) if (v[i] != 0)))
def killing_matrix(self, x, y):
"\n Return the Killing matrix of ``x`` and ``y``, where ``x``\n and ``y`` are two elements of ``self``.\n\n The Killing matrix is defined as the matrix corresponding\n to the action of\n `\\operatorname{ad}_x \\circ \\operatorname{ad}_y` in the\n basis of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: a, b, c = L.lie_algebra_generators() # needs sage.modules\n sage: L.killing_matrix(a, b) # needs sage.modules\n [0 0 0]\n [0 0 0]\n [0 0 0]\n\n ::\n\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}}) # needs sage.combinat sage.modules\n sage: L.killing_matrix(y, x) # needs sage.combinat sage.modules\n [ 0 -1]\n [ 0 0]\n "
return (x.adjoint_matrix() * y.adjoint_matrix())
def killing_form(self, x, y):
'\n Return the Killing form on ``x`` and ``y``, where ``x``\n and ``y`` are two elements of ``self``.\n\n The Killing form is defined as\n\n .. MATH::\n\n \\langle x \\mid y \\rangle\n = \\operatorname{tr}\\left( \\operatorname{ad}_x\n \\circ \\operatorname{ad}_y \\right).\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: a, b, c = L.lie_algebra_generators() # needs sage.modules\n sage: L.killing_form(a, b) # needs sage.modules\n 0\n '
return self.killing_matrix(x, y).trace()
@cached_method
def killing_form_matrix(self):
'\n Return the matrix of the Killing form of ``self``.\n\n The rows and the columns of this matrix are indexed by the\n elements of the basis of ``self`` (in the order provided by\n :meth:`basis`).\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.killing_form_matrix()\n [0 0 0]\n [0 0 0]\n [0 0 0]\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example(0)\n sage: m = L.killing_form_matrix(); m\n []\n sage: parent(m)\n Full MatrixSpace of 0 by 0 dense matrices over Rational Field\n '
from sage.matrix.constructor import matrix
B = self.basis()
m = matrix(self.base_ring(), [[self.killing_form(x, y) for x in B] for y in B])
m.set_immutable()
return m
@cached_method
def structure_coefficients(self, include_zeros=False):
'\n Return the structure coefficients of ``self``.\n\n INPUT:\n\n - ``include_zeros`` -- (default: ``False``) if ``True``, then\n include the `[x, y] = 0` pairs in the output\n\n OUTPUT:\n\n A dictionary whose keys are pairs of basis indices `(i, j)`\n with `i < j`, and whose values are the corresponding\n *elements* `[b_i, b_j]` in the Lie algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.structure_coefficients() # needs sage.modules\n Finite family {}\n sage: L.structure_coefficients(True) # needs sage.modules\n Finite family {(0, 1): (0, 0, 0), (0, 2): (0, 0, 0), (1, 2): (0, 0, 0)}\n\n ::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: G = SymmetricGroup(3)\n sage: S = GroupAlgebra(G, QQ)\n sage: L = LieAlgebra(associative=S)\n sage: L.structure_coefficients()\n Finite family {((2,3), (1,2)): (1,2,3) - (1,3,2),\n ((2,3), (1,3)): -(1,2,3) + (1,3,2),\n ((1,2,3), (2,3)): -(1,2) + (1,3),\n ((1,2,3), (1,2)): (2,3) - (1,3),\n ((1,2,3), (1,3)): -(2,3) + (1,2),\n ((1,3,2), (2,3)): (1,2) - (1,3),\n ((1,3,2), (1,2)): -(2,3) + (1,3),\n ((1,3,2), (1,3)): (2,3) - (1,2),\n ((1,3), (1,2)): -(1,2,3) + (1,3,2)}\n '
d = {}
B = self.basis()
K = list(B.keys())
zero = self.zero()
for (i, x) in enumerate(K):
for y in K[(i + 1):]:
bx = B[x]
by = B[y]
val = self.bracket(bx, by)
if ((not include_zeros) and (val == zero)):
continue
if (self._basis_key(x) > self._basis_key(y)):
d[(y, x)] = (- val)
else:
d[(x, y)] = val
return Family(d)
def centralizer_basis(self, S):
'\n Return a basis of the centralizer of ``S`` in ``self``.\n\n INPUT:\n\n - ``S`` -- a subalgebra of ``self`` or a list of elements that\n represent generators for a subalgebra\n\n .. SEEALSO::\n\n :meth:`centralizer`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: L.centralizer_basis([a + b, 2*a + c])\n [(1, 0, 0), (0, 1, 0), (0, 0, 1)]\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(QQ, 2)\n sage: H.centralizer_basis(H)\n [z]\n\n sage: # needs sage.combinat sage.groupssage.modules\n sage: D = DescentAlgebra(QQ, 4).D()\n sage: L = LieAlgebra(associative=D)\n sage: L.centralizer_basis(L)\n [D{},\n D{1} + D{1, 2} + D{2, 3} + D{3},\n D{1, 2, 3} + D{1, 3} + D{2}]\n sage: D.center_basis()\n (D{},\n D{1} + D{1, 2} + D{2, 3} + D{3},\n D{1, 2, 3} + D{1, 3} + D{2})\n '
from sage.matrix.constructor import matrix
if (S is self):
from sage.matrix.special import identity_matrix
m = identity_matrix(self.base_ring(), self.dimension())
elif isinstance(S, (list, tuple)):
m = matrix([v.to_vector() for v in self.echelon_form(S)])
else:
m = self.subalgebra(S).basis_matrix()
S = self.structure_coefficients()
sc = {}
for k in S.keys():
v = S[k].to_vector()
sc[k] = v
sc[(k[1], k[0])] = (- v)
X = self.basis().keys()
d = len(X)
c_mat = matrix(self.base_ring(), [[sum(((m[(i, j)] * sc[(x, xp)][k]) for (j, xp) in enumerate(X) if ((x, xp) in sc))) for x in X] for i in range(d) for k in range(d)])
C = c_mat.right_kernel().basis_matrix()
return [self.from_vector(c) for c in C]
def centralizer(self, S):
'\n Return the centralizer of ``S`` in ``self``.\n\n INPUT:\n\n - ``S`` -- a subalgebra of ``self`` or a list of elements that\n represent generators for a subalgebra\n\n .. SEEALSO::\n\n :meth:`centralizer_basis`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: S = L.centralizer([a + b, 2*a + c]); S\n An example of a finite dimensional Lie algebra with basis:\n the 3-dimensional abelian Lie algebra over Rational Field\n sage: S.basis_matrix()\n [1 0 0]\n [0 1 0]\n [0 0 1]\n '
return self.subalgebra(self.centralizer_basis(S))
def center(self):
'\n Return the center of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: Z = L.center(); Z\n An example of a finite dimensional Lie algebra with basis: the\n 3-dimensional abelian Lie algebra over Rational Field\n sage: Z.basis_matrix()\n [1 0 0]\n [0 1 0]\n [0 0 1]\n '
return self.centralizer(self)
@cached_method
def derivations_basis(self):
'\n Return a basis for the Lie algebra of derivations\n of ``self`` as matrices.\n\n A derivation `D` of an algebra is an endomorphism of `A`\n such that\n\n .. MATH::\n\n D([a, b]) = [D(a), b] + [a, D(b)]\n\n for all `a, b \\in A`. The set of all derivations\n form a Lie algebra.\n\n EXAMPLES:\n\n We construct the derivations of the Heisenberg Lie algebra::\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(QQ, 1)\n sage: H.derivations_basis()\n (\n [1 0 0] [0 1 0] [0 0 0] [0 0 0] [0 0 0] [0 0 0]\n [0 0 0] [0 0 0] [1 0 0] [0 1 0] [0 0 0] [0 0 0]\n [0 0 1], [0 0 0], [0 0 0], [0 0 1], [1 0 0], [0 1 0]\n )\n\n We construct the derivations of `\\mathfrak{sl}_2`::\n\n sage: # needs sage.combinat sage.modules\n sage: sl2 = lie_algebras.sl(QQ, 2)\n sage: sl2.derivations_basis()\n (\n [ 1 0 0] [ 0 1 0] [ 0 0 0]\n [ 0 0 0] [ 0 0 -1/2] [ 1 0 0]\n [ 0 0 -1], [ 0 0 0], [ 0 -2 0]\n )\n\n We verify these are derivations::\n\n sage: # needs sage.combinat sage.modules\n sage: D = [sl2.module_morphism(matrix=M, codomain=sl2)\n ....: for M in sl2.derivations_basis()]\n sage: all(d(a.bracket(b)) == d(a).bracket(b) + a.bracket(d(b))\n ....: for a in sl2.basis() for b in sl2.basis() for d in D)\n True\n\n REFERENCES:\n\n :wikipedia:`Derivation_(differential_algebra)`\n '
from sage.matrix.constructor import matrix
R = self.base_ring()
B = self.basis()
keys = list(B.keys())
scoeffs = {(j, y, i): c for y in keys for i in keys for (j, c) in self.bracket(B[y], B[i])}
zero = R.zero()
data = {}
N = len(keys)
for (ii, i) in enumerate(keys):
for (ij, j) in enumerate(keys[(ii + 1):]):
ijp = ((ij + ii) + 1)
for (il, l) in enumerate(keys):
row = ((ii + (N * il)) + ((N ** 2) * ij))
for (ik, k) in enumerate(keys):
data[(row, (ik + (N * il)))] = (data.get((row, (ik + (N * il))), zero) + scoeffs.get((k, i, j), zero))
data[(row, (ii + (N * ik)))] = (data.get((row, (ii + (N * ik))), zero) - scoeffs.get((l, k, j), zero))
data[(row, (ijp + (N * ik)))] = (data.get((row, (ijp + (N * ik))), zero) - scoeffs.get((l, i, k), zero))
mat = matrix(R, data, sparse=True)
return tuple([matrix(R, N, N, list(b)) for b in mat.right_kernel().basis()])
@cached_method
def inner_derivations_basis(self):
'\n Return a basis for the Lie algebra of inner derivations\n of ``self`` as matrices.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(QQ, 1)\n sage: H.inner_derivations_basis()\n (\n [0 0 0] [0 0 0]\n [0 0 0] [0 0 0]\n [1 0 0], [0 1 0]\n )\n '
from sage.matrix.constructor import matrix
R = self.base_ring()
IDer = matrix(R, [b.adjoint_matrix().list() for b in self.basis()])
N = self.dimension()
return tuple([matrix(R, N, N, list(b)) for b in IDer.row_module().basis()])
def subalgebra(self, *gens, **kwds):
'\n Return the subalgebra of ``self`` generated by ``gens``.\n\n INPUT:\n\n - ``gens`` -- a list of generators of the subalgebra\n - ``category`` -- (optional) a subcategory of subobjects of finite\n dimensional Lie algebras with basis\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(QQ, 2)\n sage: p1,p2,q1,q2,z = H.basis()\n sage: S = H.subalgebra([p1, q1])\n sage: S.basis().list()\n [p1, q1, z]\n sage: S.basis_matrix()\n [1 0 0 0 0]\n [0 0 1 0 0]\n [0 0 0 0 1]\n\n Passing an extra category to a subalgebra::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, 3, step=2)\n sage: x,y,z = L.homogeneous_component_basis(1)\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis()\n sage: C = C.Subobjects().Graded().Stratified()\n sage: S = L.subalgebra([x, y], category=C)\n sage: S.homogeneous_component_basis(2).list()\n [X_12]\n '
from sage.algebras.lie_algebras.subalgebra import LieSubalgebra_finite_dimensional_with_basis
if ((len(gens) == 1) and isinstance(gens[0], (list, tuple))):
gens = gens[0]
category = kwds.pop('category', None)
return LieSubalgebra_finite_dimensional_with_basis(self, gens, category=category, **kwds)
def ideal(self, *gens, **kwds):
'\n Return the ideal of ``self`` generated by ``gens``.\n\n INPUT:\n\n - ``gens`` -- a list of generators of the ideal\n - ``category`` -- (optional) a subcategory of subobjects of finite\n dimensional Lie algebras with basis\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(QQ, 2)\n sage: p1,p2,q1,q2,z = H.basis()\n sage: I = H.ideal([p1 - p2, q1 - q2])\n sage: I.basis().list()\n [-p1 + p2, -q1 + q2, z]\n sage: I.reduce(p1 + p2 + q1 + q2 + z)\n 2*p1 + 2*q1\n\n Passing an extra category to an ideal::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y,z> = LieAlgebra(QQ, abelian=True)\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis()\n sage: C = C.Subobjects().Graded().Stratified()\n sage: I = L.ideal(x, y, category=C)\n sage: I.homogeneous_component_basis(1).list()\n [x, y]\n '
from sage.algebras.lie_algebras.subalgebra import LieSubalgebra_finite_dimensional_with_basis
if ((len(gens) == 1) and isinstance(gens[0], (list, tuple))):
gens = gens[0]
category = kwds.pop('category', None)
return LieSubalgebra_finite_dimensional_with_basis(self, gens, ideal=True, category=category, **kwds)
@cached_method
def is_ideal(self, A):
"\n Return if ``self`` is an ideal of ``A``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: I = L.ideal([2*a - c, b + c])\n sage: I.is_ideal(L)\n True\n\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'):{'x':1}}) # needs sage.combinat sage.modules\n sage: L.is_ideal(L) # needs sage.combinat sage.modules\n True\n\n sage: F = LieAlgebra(QQ, 'F', representation='polynomial') # needs sage.combinat sage.modules\n sage: L.is_ideal(F) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: A must be a finite dimensional Lie algebra\n with basis\n "
if (A == self):
return True
if (A not in LieAlgebras(self.base_ring()).FiniteDimensional().WithBasis()):
raise NotImplementedError('A must be a finite dimensional Lie algebra with basis')
from sage.matrix.constructor import matrix
B = self.basis()
AB = A.basis()
try:
b_mat = matrix(A.base_ring(), [A.bracket(b, ab).to_vector() for b in B for ab in AB])
except (ValueError, TypeError):
return False
return b_mat.row_space().is_submodule(self.module())
def quotient(self, I, names=None, category=None):
'\n Return the quotient of ``self`` by the ideal ``I``.\n\n A quotient Lie algebra.\n\n INPUT:\n\n - ``I`` -- an ideal or a list of generators of the ideal\n - ``names`` -- (optional) a string or a list of strings;\n names for the basis elements of the quotient. If ``names`` is a\n string, the basis will be named ``names_1``,...,``names_n``.\n\n EXAMPLES:\n\n The Engel Lie algebra as a quotient of the free nilpotent Lie algebra\n of step 3 with 2 generators::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<X,Y,Z,W,U> = LieAlgebra(QQ, 2, step=3)\n sage: E = L.quotient(U); E\n Lie algebra quotient L/I of dimension 4 over Rational Field where\n L: Free Nilpotent Lie algebra on 5 generators (X, Y, Z, W, U)\n over Rational Field\n I: Ideal (U)\n sage: E.basis().list()\n [X, Y, Z, W]\n sage: E(X).bracket(E(Y))\n Z\n sage: Y.bracket(Z)\n -U\n sage: E(Y).bracket(E(Z))\n 0\n sage: E(U)\n 0\n\n Quotients when the base ring is not a field are not implemented::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.Heisenberg(ZZ, 1)\n sage: L.quotient(L.an_element())\n Traceback (most recent call last):\n ...\n NotImplementedError: quotients over non-fields not implemented\n '
from sage.algebras.lie_algebras.quotient import LieQuotient_finite_dimensional_with_basis
return LieQuotient_finite_dimensional_with_basis(I, ambient=self, names=names, category=category)
def product_space(self, L, submodule=False):
"\n Return the product space ``[self, L]``.\n\n INPUT:\n\n - ``L`` -- a Lie subalgebra of ``self``\n - ``submodule`` -- (default: ``False``) if ``True``, then the\n result is forced to be a submodule of ``self``\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: a,b,c = L.lie_algebra_generators()\n sage: X = L.subalgebra([a, b + c])\n sage: L.product_space(X)\n An example of a finite dimensional Lie algebra with basis:\n the 0-dimensional abelian Lie algebra over Rational Field\n with basis matrix: []\n sage: Y = L.subalgebra([a, 2*b - c])\n sage: X.product_space(Y)\n An example of a finite dimensional Lie algebra with basis:\n the 0-dimensional abelian Lie algebra over Rational Field\n with basis matrix: []\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: H = lie_algebras.Heisenberg(ZZ, 4)\n sage: Hp = H.product_space(H, submodule=True).basis()\n sage: [H.from_vector(v) for v in Hp]\n [z]\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'):{'x':1}})\n sage: Lp = L.product_space(L) # not implemented\n sage: Lp # not implemented\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: (x,)\n sage: Lp.product_space(L) # not implemented\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: (x,)\n sage: L.product_space(Lp) # not implemented\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: (x,)\n sage: Lp.product_space(Lp) # not implemented\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: ()\n "
from sage.matrix.constructor import matrix
if (self in LieAlgebras(self.base_ring()).Subobjects()):
A = self.ambient()
elif (L in LieAlgebras(L.base_ring()).Subobjects()):
A = L.ambient()
else:
A = self
if (L not in self.category()):
LB = [self.from_vector(b) for b in L.basis()]
else:
LB = L.basis()
B = self.basis()
b_mat = matrix(A.base_ring(), [A.bracket(b, lb).to_vector() for b in B for lb in LB])
if ((submodule is True) or (not (self.is_ideal(A) and L.is_ideal(A)))):
return b_mat.row_space()
b_mat.echelonize()
r = b_mat.rank()
gens = [A.from_vector(row) for row in b_mat.rows()[:r]]
return A.ideal(gens)
@cached_method
def derived_subalgebra(self):
"\n Return the derived subalgebra of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.derived_subalgebra()\n An example of a finite dimensional Lie algebra with basis:\n the 0-dimensional abelian Lie algebra over Rational Field\n with basis matrix:\n []\n\n If ``self`` is semisimple, then the derived subalgebra is ``self``::\n\n sage: # needs sage.combinat sage.modules\n sage: sl3 = LieAlgebra(QQ, cartan_type=['A', 2])\n sage: sl3.derived_subalgebra()\n Lie algebra of ['A', 2] in the Chevalley basis\n sage: sl3 is sl3.derived_subalgebra()\n True\n\n "
if self.is_semisimple():
return self
else:
return self.product_space(self)
@cached_method
def derived_series(self):
"\n Return the derived series `(\\mathfrak{g}^{(i)})_i` of ``self``\n where the rightmost\n `\\mathfrak{g}^{(k)} = \\mathfrak{g}^{(k+1)} = \\cdots`.\n\n We define the derived series of a Lie algebra `\\mathfrak{g}`\n recursively by `\\mathfrak{g}^{(0)} := \\mathfrak{g}` and\n\n .. MATH::\n\n \\mathfrak{g}^{(k+1)} =\n [\\mathfrak{g}^{(k)}, \\mathfrak{g}^{(k)}]\n\n and recall that\n `\\mathfrak{g}^{(k)} \\supseteq \\mathfrak{g}^{(k+1)}`.\n Alternatively we can express this as\n\n .. MATH::\n\n \\mathfrak{g} \\supseteq [\\mathfrak{g}, \\mathfrak{g}] \\supseteq\n \\bigl[ [\\mathfrak{g}, \\mathfrak{g}], [\\mathfrak{g},\n \\mathfrak{g}] \\bigr] \\supseteq\n \\biggl[ \\bigl[ [\\mathfrak{g}, \\mathfrak{g}], [\\mathfrak{g},\n \\mathfrak{g}] \\bigr], \\bigl[ [\\mathfrak{g}, \\mathfrak{g}],\n [\\mathfrak{g}, \\mathfrak{g}] \\bigr] \\biggr] \\supseteq \\cdots.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.derived_series()\n (An example of a finite dimensional Lie algebra with basis:\n the 3-dimensional abelian Lie algebra over Rational Field,\n An example of a finite dimensional Lie algebra with basis:\n the 0-dimensional abelian Lie algebra over Rational Field\n with basis matrix: [])\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.derived_series() # not implemented\n (Lie algebra on 2 generators (x, y) over Rational Field,\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: (x,),\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: ())\n "
L = [self]
while (L[(- 1)].dimension() > 0):
p = L[(- 1)].derived_subalgebra()
if (L[(- 1)].dimension() == p.dimension()):
break
L.append(p)
return tuple(L)
@cached_method
def lower_central_series(self, submodule=False):
"\n Return the lower central series `(\\mathfrak{g}_{i})_i`\n of ``self`` where the rightmost\n `\\mathfrak{g}_k = \\mathfrak{g}_{k+1} = \\cdots`.\n\n INPUT:\n\n - ``submodule`` -- (default: ``False``) if ``True``, then the\n result is given as submodules of ``self``\n\n We define the lower central series of a Lie algebra `\\mathfrak{g}`\n recursively by `\\mathfrak{g}_0 := \\mathfrak{g}` and\n\n .. MATH::\n\n \\mathfrak{g}_{k+1} = [\\mathfrak{g}, \\mathfrak{g}_{k}]\n\n and recall that `\\mathfrak{g}_{k} \\supseteq \\mathfrak{g}_{k+1}`.\n Alternatively we can express this as\n\n .. MATH::\n\n \\mathfrak{g} \\supseteq [\\mathfrak{g}, \\mathfrak{g}] \\supseteq\n \\bigl[ [\\mathfrak{g}, \\mathfrak{g}], \\mathfrak{g} \\bigr]\n \\supseteq\\biggl[\\bigl[ [\\mathfrak{g}, \\mathfrak{g}],\n \\mathfrak{g} \\bigr], \\mathfrak{g}\\biggr] \\supseteq \\cdots.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.derived_series()\n (An example of a finite dimensional Lie algebra with basis:\n the 3-dimensional abelian Lie algebra over Rational Field,\n An example of a finite dimensional Lie algebra with basis:\n the 0-dimensional abelian Lie algebra over Rational Field\n with basis matrix: [])\n\n The lower central series as submodules::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.lower_central_series(submodule=True)\n (Sparse vector space of dimension 2 over Rational Field,\n Vector space of degree 2 and dimension 1 over Rational Field\n Basis matrix: [1 0])\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.lower_central_series() # not implemented\n (Lie algebra on 2 generators (x, y) over Rational Field,\n Subalgebra generated of\n Lie algebra on 2 generators (x, y) over Rational Field\n with basis: (x,))\n "
if submodule:
L = [self.module()]
else:
L = [self]
while (L[(- 1)].dimension() > 0):
s = self.product_space(L[(- 1)], submodule=submodule)
if (L[(- 1)].dimension() == s.dimension()):
break
L.append(s)
return tuple(L)
def is_abelian(self):
"\n Return if ``self`` is an abelian Lie algebra.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.is_abelian()\n True\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.is_abelian()\n False\n "
return (len(self.structure_coefficients()) == 0)
def is_solvable(self):
"\n Return if ``self`` is a solvable Lie algebra.\n\n A Lie algebra is solvable if the derived series eventually\n becomes `0`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.is_solvable()\n True\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.is_solvable() # not implemented\n False\n "
return (not self.derived_series()[(- 1)].dimension())
def is_nilpotent(self):
'\n Return if ``self`` is a nilpotent Lie algebra.\n\n A Lie algebra is nilpotent if the lower central series eventually\n becomes `0`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.is_nilpotent()\n True\n '
return (not self.lower_central_series()[(- 1)].dimension())
def is_semisimple(self):
'\n Return if ``self`` if a semisimple Lie algebra.\n\n A Lie algebra is semisimple if the solvable radical is zero. In\n characteristic 0, this is equivalent to saying the Killing form\n is non-degenerate.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.is_semisimple()\n False\n '
return (not self.killing_form_matrix().is_singular())
@cached_method(key=(lambda self, M, d, s, n: (M, d, s)))
def chevalley_eilenberg_complex(self, M=None, dual=False, sparse=True, ncpus=None):
"\n Return the Chevalley-Eilenberg complex of ``self``.\n\n Let `\\mathfrak{g}` be a Lie algebra and `M` be a right\n `\\mathfrak{g}`-module. The *Chevalley-Eilenberg complex*\n is the chain complex on\n\n .. MATH::\n\n C_{\\bullet}(\\mathfrak{g}, M) =\n M \\otimes \\bigwedge\\nolimits^{\\bullet} \\mathfrak{g},\n\n where the differential is given by\n\n .. MATH::\n\n d(m \\otimes g_1 \\wedge \\cdots \\wedge g_p) =\n \\sum_{i=1}^p (-1)^{i+1}\n (m g_i) \\otimes g_1 \\wedge \\cdots \\wedge\n \\hat{g}_i \\wedge \\cdots \\wedge g_p +\n \\sum_{1 \\leq i < j \\leq p} (-1)^{i+j}\n m \\otimes [g_i, g_j] \\wedge\n g_1 \\wedge \\cdots \\wedge \\hat{g}_i\n \\wedge \\cdots \\wedge \\hat{g}_j\n \\wedge \\cdots \\wedge g_p.\n\n INPUT:\n\n - ``M`` -- (default: the trivial 1-dimensional module)\n the module `M`\n - ``dual`` -- (default: ``False``) if ``True``, causes\n the dual of the complex to be computed\n - ``sparse`` -- (default: ``True``) whether to use sparse\n or dense matrices\n - ``ncpus`` -- (optional) how many cpus to use\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.sl(ZZ, 2)\n sage: C = L.chevalley_eilenberg_complex(); C\n Chain complex with at most 4 nonzero terms over Integer Ring\n sage: ascii_art(C)\n [ 2 0 0] [0]\n [ 0 -1 0] [0]\n [0 0 0] [ 0 0 2] [0]\n 0 <-- C_0 <-------- C_1 <----------- C_2 <---- C_3 <-- 0\n\n sage: # long time, needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['C',2])\n sage: C = L.chevalley_eilenberg_complex()\n sage: [C.free_module_rank(i) for i in range(11)]\n [1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]\n\n sage: # needs sage.combinat sage.modules\n sage: g = lie_algebras.sl(QQ, 2)\n sage: E, F, H = g.basis()\n sage: n = g.subalgebra([F, H])\n sage: ascii_art(n.chevalley_eilenberg_complex())\n [0]\n [0 0] [2]\n 0 <-- C_0 <------ C_1 <---- C_2 <-- 0\n\n REFERENCES:\n\n - :wikipedia:`Lie_algebra_cohomology#Chevalley-Eilenberg_complex`\n - [Wei1994]_ Chapter 7\n\n .. TODO::\n\n Currently this is only implemented for coefficients\n given by the trivial module `R`, where `R` is the\n base ring and `g R = 0` for all `g \\in \\mathfrak{g}`.\n Allow generic coefficient modules `M`.\n "
if dual:
return self.chevalley_eilenberg_complex(M, dual=False, sparse=sparse, ncpus=ncpus).dual()
if (M is not None):
raise NotImplementedError('only implemented for the default (the trivial module)')
from itertools import combinations
from sage.arith.misc import binomial
from sage.matrix.matrix_space import MatrixSpace
R = self.base_ring()
zero = R.zero()
mone = (- R.one())
if (M is not None):
raise NotImplementedError('coefficient module M cannot be passed')
B = self.basis()
K = list(B.keys())
B = [B[k] for k in K]
Ind = list(range(len(K)))
M = self.module()
ambient = M.is_ambient()
def sgn(k, X):
'\n Insert a new entry ``k`` into a strictly increasing\n list ``X`` in such a way that the resulting list is\n still strictly increasing.\n The return value is the pair ``(s, Y)``, where ``Y``\n is the resulting list (as tuple) and ``s`` is the\n Koszul sign incurred by the insertion (with the\n understanding that ``k`` originally stood to the\n left of the list).\n If ``k`` is already in ``X``, then the return value\n is ``(zero, None)``.\n '
Y = list(X)
for i in range((len(X) - 1), (- 1), (- 1)):
val = X[i]
if (val == k):
return (zero, None)
if (k > val):
Y.insert((i + 1), k)
return ((mone ** (i + 1)), tuple(Y))
Y.insert(0, k)
return (R.one(), tuple(Y))
from sage.parallel.decorate import parallel
@parallel(ncpus=ncpus)
def compute_diff(k):
'\n Build the ``k``-th differential (in parallel).\n '
indices = {tuple(X): i for (i, X) in enumerate(combinations(Ind, (k - 1)))}
if sparse:
data = {}
row = 0
else:
data = []
if (not sparse):
zero = ([zero] * len(indices))
for X in combinations(Ind, k):
if (not sparse):
ret = list(zero)
for i in range(k):
Y = list(X)
Y.pop(i)
for j in range((i + 1), k):
Z = tuple((Y[:(j - 1)] + Y[j:]))
elt = ((mone ** (i + j)) * B[X[i]].bracket(B[X[j]]))
if ambient:
vec = elt.to_vector()
else:
vec = M.coordinate_vector(elt.to_vector())
for (key, coeff) in vec.iteritems():
(s, A) = sgn(key, Z)
if (A is None):
continue
if sparse:
coords = (row, indices[A])
if (coords in data):
data[coords] += (s * coeff)
else:
data[coords] = (s * coeff)
else:
ret[indices[A]] += (s * coeff)
if sparse:
row += 1
else:
data.append(ret)
nrows = binomial(len(Ind), k)
ncols = binomial(len(Ind), (k - 1))
MS = MatrixSpace(R, nrows, ncols, sparse=sparse)
ret = MS(data).transpose()
ret.set_immutable()
return ret
chain_data = {X[0][0]: M for (X, M) in compute_diff(list(range(1, (len(Ind) + 1))))}
from sage.homology.chain_complex import ChainComplex
try:
return ChainComplex(chain_data, degree_of_differential=(- 1))
except TypeError:
return chain_data
def homology(self, deg=None, M=None, sparse=True, ncpus=None):
"\n Return the Lie algebra homology of ``self``.\n\n The Lie algebra homology is the homology of the\n Chevalley-Eilenberg chain complex.\n\n INPUT:\n\n - ``deg`` -- the degree of the homology (optional)\n - ``M`` -- (default: the trivial module) a right module\n of ``self``\n - ``sparse`` -- (default: ``True``) whether to use sparse\n matrices for the Chevalley-Eilenberg chain complex\n - ``ncpus`` -- (optional) how many cpus to use when\n computing the Chevalley-Eilenberg chain complex\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.cross_product(QQ)\n sage: L.homology()\n {0: Vector space of dimension 1 over Rational Field,\n 1: Vector space of dimension 0 over Rational Field,\n 2: Vector space of dimension 0 over Rational Field,\n 3: Vector space of dimension 1 over Rational Field}\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.pwitt(GF(5), 5)\n sage: L.homology()\n {0: Vector space of dimension 1 over Finite Field of size 5,\n 1: Vector space of dimension 0 over Finite Field of size 5,\n 2: Vector space of dimension 1 over Finite Field of size 5,\n 3: Vector space of dimension 1 over Finite Field of size 5,\n 4: Vector space of dimension 0 over Finite Field of size 5,\n 5: Vector space of dimension 1 over Finite Field of size 5}\n\n sage: # needs sage.combinat sage.modules\n sage: d = {('x', 'y'): {'y': 2}}\n sage: L.<x,y> = LieAlgebra(ZZ, d)\n sage: L.homology()\n {0: Z, 1: Z x C2, 2: 0}\n\n .. SEEALSO::\n\n :meth:`chevalley_eilenberg_complex`\n "
C = self.chevalley_eilenberg_complex(M=M, sparse=sparse, ncpus=ncpus)
return C.homology(deg=deg)
def cohomology(self, deg=None, M=None, sparse=True, ncpus=None):
"\n Return the Lie algebra cohomology of ``self``.\n\n The Lie algebra cohomology is the cohomology of the\n Chevalley-Eilenberg cochain complex (which is the dual\n of the Chevalley-Eilenberg chain complex).\n\n Let `\\mathfrak{g}` be a Lie algebra and `M` a left\n `\\mathfrak{g}`-module. It is known that `H^0(\\mathfrak{g}; M)`\n is the subspace of `\\mathfrak{g}`-invariants of `M`:\n\n .. MATH::\n\n H^0(\\mathfrak{g}; M) = M^{\\mathfrak{g}}\n = \\{ m \\in M \\mid g m = 0\n \\text{ for all } g \\in \\mathfrak{g} \\}.\n\n Additionally, `H^1(\\mathfrak{g}; M)` is the space of\n derivations `\\mathfrak{g} \\to M`\n modulo the space of inner derivations, and\n `H^2(\\mathfrak{g}; M)` is the space of equivalence classes\n of Lie algebra extensions of `\\mathfrak{g}` by `M`.\n\n INPUT:\n\n - ``deg`` -- the degree of the homology (optional)\n - ``M`` -- (default: the trivial module) a right module\n of ``self``\n - ``sparse`` -- (default: ``True``) whether to use sparse\n matrices for the Chevalley-Eilenberg chain complex\n - ``ncpus`` -- (optional) how many cpus to use when\n computing the Chevalley-Eilenberg chain complex\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.so(QQ, 4)\n sage: L.cohomology()\n {0: Vector space of dimension 1 over Rational Field,\n 1: Vector space of dimension 0 over Rational Field,\n 2: Vector space of dimension 0 over Rational Field,\n 3: Vector space of dimension 2 over Rational Field,\n 4: Vector space of dimension 0 over Rational Field,\n 5: Vector space of dimension 0 over Rational Field,\n 6: Vector space of dimension 1 over Rational Field}\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.Heisenberg(QQ, 2)\n sage: L.cohomology()\n {0: Vector space of dimension 1 over Rational Field,\n 1: Vector space of dimension 4 over Rational Field,\n 2: Vector space of dimension 5 over Rational Field,\n 3: Vector space of dimension 5 over Rational Field,\n 4: Vector space of dimension 4 over Rational Field,\n 5: Vector space of dimension 1 over Rational Field}\n\n sage: # needs sage.combinat sage.modules\n sage: d = {('x', 'y'): {'y': 2}}\n sage: L.<x,y> = LieAlgebra(ZZ, d)\n sage: L.cohomology()\n {0: Z, 1: Z, 2: C2}\n\n .. SEEALSO::\n\n :meth:`chevalley_eilenberg_complex`\n\n REFERENCES:\n\n - :wikipedia:`Lie_algebra_cohomology`\n "
C = self.chevalley_eilenberg_complex(M=M, dual=True, sparse=sparse, ncpus=ncpus)
return C.homology(deg=deg)
def as_finite_dimensional_algebra(self):
'\n Return ``self`` as a :class:`FiniteDimensionalAlgebra`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.cross_product(QQ)\n sage: x, y, z = L.basis()\n sage: F = L.as_finite_dimensional_algebra()\n sage: X, Y, Z = F.basis()\n sage: x.bracket(y)\n Z\n sage: X * Y\n Z\n '
from sage.matrix.constructor import matrix
K = self._basis_ordering
mats = []
R = self.base_ring()
S = dict(self.structure_coefficients())
V = self._dense_free_module()
zero_vec = V.zero()
for k in K:
M = []
for kp in K:
if ((k, kp) in S):
M.append((- S[(k, kp)].to_vector()))
elif ((kp, k) in S):
M.append(S[(kp, k)].to_vector())
else:
M.append(zero_vec)
mats.append(matrix(R, M))
from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra import FiniteDimensionalAlgebra
return FiniteDimensionalAlgebra(R, mats, names=self._names)
def morphism(self, on_generators, codomain=None, base_map=None, check=True):
"\n Return a Lie algebra morphism defined by images of a Lie\n generating subset of ``self``.\n\n INPUT:\n\n - ``on_generators`` -- dictionary ``{X: Y}`` of the images `Y`\n in ``codomain`` of elements `X` of ``domain``\n - ``codomain`` -- a Lie algebra (optional); this is inferred\n from the values of ``on_generators`` if not given\n - ``base_map`` -- a homomorphism from the base ring to something\n coercing into the codomain\n - ``check`` -- (default: ``True``) boolean; if ``False`` the\n values on the Lie brackets implied by ``on_generators`` will\n not be checked for contradictory values\n\n .. NOTE::\n\n The keys of ``on_generators`` need to generate ``domain``\n as a Lie algebra.\n\n .. SEEALSO::\n\n :class:`sage.algebras.lie_algebras.morphism.LieAlgebraMorphism_from_generators`\n\n EXAMPLES:\n\n A quotient type Lie algebra morphism ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<X,Y,Z,W> = LieAlgebra(QQ, {('X','Y'): {'Z': 1},\n ....: ('X','Z'): {'W': 1}})\n sage: K.<A,B> = LieAlgebra(QQ, abelian=True)\n sage: L.morphism({X: A, Y: B})\n Lie algebra morphism:\n From: Lie algebra on 4 generators (X, Y, Z, W) over Rational Field\n To: Abelian Lie algebra on 2 generators (A, B) over Rational Field\n Defn: X |--> A\n Y |--> B\n Z |--> 0\n W |--> 0\n\n The reverse map `A \\mapsto X`, `B \\mapsto Y` does not define a Lie\n algebra morphism, since `[A,B] = 0`, but `[X,Y] \\neq 0`::\n\n sage: # needs sage.combinat sage.modules\n sage: K.morphism({A:X, B: Y})\n Traceback (most recent call last):\n ...\n ValueError: this does not define a Lie algebra morphism;\n contradictory values for brackets of length 2\n\n However, it is still possible to create a morphism that acts nontrivially\n on the coefficients, even though it's not a Lie algebra morphism\n (since it isn't linear)::\n\n sage: # needs sage.combinat sage.modules sage.rings.number_fields\n sage: R.<x> = ZZ[]\n sage: K.<i> = NumberField(x^2 + 1)\n sage: cc = K.hom([-i])\n sage: L.<X,Y,Z,W> = LieAlgebra(K, {('X','Y'): {'Z': 1},\n ....: ('X','Z'): {'W': 1}})\n sage: M.<A,B> = LieAlgebra(K, abelian=True)\n sage: phi = L.morphism({X: A, Y: B}, base_map=cc)\n sage: phi(X)\n A\n sage: phi(i*X)\n -i*A\n "
from sage.algebras.lie_algebras.morphism import LieAlgebraMorphism_from_generators
return LieAlgebraMorphism_from_generators(on_generators, domain=self, codomain=codomain, base_map=base_map, check=check)
@cached_method
def universal_polynomials(self):
"\n Return the family of universal polynomials of ``self``.\n\n The *universal polynomials* of a Lie algebra `L` with\n basis `\\{e_i\\}_{i \\in I}` and structure coefficients\n `[e_i, e_j] = \\tau_{ij}^a e_a` is given by\n\n .. MATH::\n\n P_{aij} = \\sum_{u \\in I} \\tau_{ij}^u X_{au}\n - \\sum_{s,t \\in I} \\tau_{st}^a X_{si} X_{tj},\n\n where `a,i,j \\in I`.\n\n REFERENCES:\n\n - [AM2020]_\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: L.universal_polynomials()\n Finite family {('x', 'x', 'y'): X01*X10 - X00*X11 + X00,\n ('y', 'x', 'y'): X10}\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['A',1])\n sage: list(L.universal_polynomials())\n [-2*X01*X10 + 2*X00*X11 - 2*X00,\n -2*X02*X10 + 2*X00*X12 + X01,\n -2*X02*X11 + 2*X01*X12 - 2*X02,\n X01*X20 - X00*X21 - 2*X10,\n X02*X20 - X00*X22 + X11,\n X02*X21 - X01*X22 - 2*X12,\n -2*X11*X20 + 2*X10*X21 - 2*X20,\n -2*X12*X20 + 2*X10*X22 + X21,\n -2*X12*X21 + 2*X11*X22 - 2*X22]\n\n sage: # long time, needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['B', 2])\n sage: al = RootSystem(['B', 2]).root_lattice().simple_roots()\n sage: k = list(L.basis().keys())[0]\n sage: UP = L.universal_polynomials()\n sage: len(UP)\n 450\n sage: UP[al[2], al[1], -al[1]]\n X0_7*X4_1 - X0_1*X4_7 - 2*X0_7*X5_1 + 2*X0_1*X5_7 + X2_7*X7_1\n - X2_1*X7_7 - X3_7*X8_1 + X3_1*X8_7 + X0_4\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
I = self.basis().keys()
n = len(I)
s_coeffs = self.structure_coefficients(True)
zero = self.base_ring().zero()
def sc(i, j):
if (i == j):
return zero
if (i > j):
return (- s_coeffs[(I[j], I[i])])
return s_coeffs[(I[i], I[j])]
d = {}
keys = []
if (n >= 10):
vs = 'X{}_{}'
else:
vs = 'X{}{}'
R = PolynomialRing(self.base_ring(), ','.join((vs.format(i, j) for i in range(n) for j in range(n))))
X = [[R.gen((i + (n * j))) for i in range(n)] for j in range(n)]
for a in range(n):
for i in range(n):
for j in range((i + 1), n):
k = (I[a], I[i], I[j])
keys.append(k)
if (i != j):
s = sc(i, j)
d[k] = (R.sum(((s[I[u]] * X[a][u]) for u in range(n))) - R.sum((((sc(s, t)[I[a]] * X[s][i]) * X[t][j]) for s in range(n) for t in range(n) if (s != t))))
else:
d[k] = (- R.sum((((sc(s, t)[I[a]] * X[s][i]) * X[t][j]) for s in range(n) for t in range(n) if (s != t))))
return Family(keys, d.__getitem__)
@cached_method
def universal_commutative_algebra(self):
"\n Return the universal commutative algebra associated to ``self``.\n\n Let `I` be the index set of the basis of ``self``. Let\n `\\mathcal{P} = \\{P_{a,i,j}\\}_{a,i,j \\in I}` denote the\n universal polynomials of a Lie algebra `L`. The *universal\n commutative algebra* associated to `L` is the quotient\n ring `R[X_{ij}]_{i,j \\in I} / (\\mathcal{P})`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: A = L.universal_commutative_algebra()\n sage: a, b, c, d = A.gens()\n sage: a, b, c, d\n (X00bar, X01bar, 0, X11bar)\n sage: a*d - a\n 0\n "
P = list(self.universal_polynomials())
R = P[0].parent()
return R.quotient(P)
def casimir_element(self, order=2, UEA=None, force_generic=False):
"\n Return the Casimir element in the universal enveloping algebra\n of ``self``.\n\n A *Casimir element* of order `k` is a distinguished basis element\n for the center of `U(\\mathfrak{g})` of homogeneous degree `k`\n (that is, it is an element of `U_k \\setminus U_{k-1}`, where\n `\\{U_i\\}_{i=0}^{\\infty}` is the natural filtration of\n `U(\\mathfrak{g})`). When `\\mathfrak{g}` is a simple Lie algebra,\n then this spans `Z(U(\\mathfrak{g}))_k`.\n\n INPUT:\n\n - ``order`` -- (default: ``2``) the order of the Casimir element\n - ``UEA`` -- (optional) the universal enveloping algebra to\n return the result in\n - ``force_generic`` -- (default: ``False``) if ``True`` for the\n quadratic order, then this uses the default algorithm; otherwise\n this is ignored\n\n ALGORITHM:\n\n For the quadratic order (i.e., ``order=2``), then this uses\n `K^{ij}`, the inverse of the Killing form matrix, to compute\n `C_{(2)} = \\sum_{i,j} K^{ij} X_i \\cdots X_j`, where `\\{X_1, \\ldots,\n X_n\\}` is a basis for `\\mathfrak{g}`. Otherwise this solves the\n system of equations\n\n .. MATH::\n\n f_{aj}^b \\kappa^{jc\\cdots d} + f_{aj}^c \\kappa^{cj\\cdots d}\n \\cdots + f_{aj}^d \\kappa^{bc \\cdots j}\n\n for the symmetric tensor `\\kappa^{i_1 \\cdots i_k}`, where `k` is\n the ``order``. This system comes from `[X_i, C_{(k)}] = 0` with\n\n .. MATH::\n\n C_{(k)} = \\sum_{i_1, \\ldots, i_k}^n\n \\kappa^{i_1 \\cdots i_k} X_{i_1} \\cdots X_{i_k}.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['A', 1])\n sage: C = L.casimir_element(); C\n 1/8*b1^2 + 1/2*b0*b2 - 1/4*b1\n sage: U = L.universal_enveloping_algebra()\n sage: all(g * C == C * g for g in U.gens())\n True\n sage: U = L.pbw_basis()\n sage: C = L.casimir_element(UEA=U); C\n 1/2*PBW[alpha[1]]*PBW[-alpha[1]] + 1/8*PBW[alphacheck[1]]^2\n - 1/4*PBW[alphacheck[1]]\n sage: all(g * C == C * g for g in U.algebra_generators())\n True\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['B', 2])\n sage: U = L.pbw_basis()\n sage: C = L.casimir_element(UEA=U)\n sage: all(g * C == C * g for g in U.algebra_generators())\n True\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['C', 3])\n sage: U = L.pbw_basis()\n sage: C = L.casimir_element(UEA=U)\n sage: all(g * C == C * g for g in U.algebra_generators())\n True\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['A', 1])\n sage: C4 = L.casimir_element(order=4, UEA=L.pbw_basis()); C4\n 4*PBW[alpha[1]]^2*PBW[-alpha[1]]^2\n + 2*PBW[alpha[1]]*PBW[alphacheck[1]]^2*PBW[-alpha[1]]\n + 1/4*PBW[alphacheck[1]]^4 - PBW[alphacheck[1]]^3\n - 4*PBW[alpha[1]]*PBW[-alpha[1]] + 2*PBW[alphacheck[1]]\n sage: all(g * C4 == C4 * g for g in L.pbw_basis().algebra_generators())\n True\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.Heisenberg(QQ, 2)\n sage: L.casimir_element()\n 0\n\n TESTS::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=['A', 1])\n sage: L.casimir_element(1)\n Traceback (most recent call last):\n ...\n ValueError: invalid order\n sage: 4 * L.casimir_element() == L.casimir_element(force_generic=True)\n True\n\n .. TODO::\n\n Use the symmetry of the tensor to reduce the number of\n equations and/or variables to solve.\n "
if (order < 2):
raise ValueError('invalid order')
if (UEA is None):
UEA = self.universal_enveloping_algebra()
B = self.basis()
if ((order == 2) and (not force_generic)):
try:
K = self.killing_form_matrix().inverse()
return UEA.sum((((K[(i, j)] * UEA(x)) * UEA(y)) for (i, x) in enumerate(B) for (j, y) in enumerate(B) if K[(i, j)]))
except (ValueError, TypeError, ZeroDivisionError):
pass
keys = self.get_order()
dim = len(keys)
s_coeffs = dict(self.structure_coefficients())
for k in list(s_coeffs.keys()):
s_coeffs[(k[1], k[0])] = (- s_coeffs[k])
from sage.matrix.constructor import matrix
from itertools import product
eqns = matrix.zero(self.base_ring(), (dim ** (order + 1)), (dim ** order), sparse=True)
for (ii, p) in enumerate(product(range(dim), repeat=(order + 1))):
i = p[0]
a = keys[i]
for (j, b) in enumerate(keys):
if ((a, b) not in s_coeffs):
continue
sc_val = s_coeffs[(a, b)]
for k in range(order):
c = keys[p[(k + 1)]]
if (not sc_val[c]):
continue
pp = list(p[1:])
pp[k] = j
jj = sum((((dim ** m) * pp[m]) for m in range(order)))
eqns[(ii, jj)] += sc_val[c]
ker = eqns.right_kernel()
if (ker.dimension() == 0):
return self.zero()
tens = ker.basis()[0]
del eqns
def to_prod(index):
coeff = tens[index]
p = ([0] * order)
base = (dim ** (order - 1))
for i in range(order):
p[i] = (index // base)
index %= base
base //= dim
p.reverse()
return (coeff * UEA.prod((UEA(B[keys[i]]) for i in p)))
return UEA.sum((to_prod(index) for index in tens.support()))
class ElementMethods():
def adjoint_matrix(self, sparse=False):
"\n Return the matrix of the adjoint action of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.an_element().adjoint_matrix()\n [0 0 0]\n [0 0 0]\n [0 0 0]\n sage: L.an_element().adjoint_matrix(sparse=True).is_sparse()\n True\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'x':1}})\n sage: x.adjoint_matrix()\n [0 1]\n [0 0]\n sage: y.adjoint_matrix()\n [-1 0]\n [ 0 0]\n\n We verify that this forms a representation::\n\n sage: # needs sage.combinat sage.modules\n sage: sl3 = lie_algebras.sl(QQ, 3)\n sage: e1, e2 = sl3.e(1), sl3.e(2)\n sage: e12 = e1.bracket(e2)\n sage: E1, E2 = e1.adjoint_matrix(), e2.adjoint_matrix()\n sage: E1 * E2 - E2 * E1 == e12.adjoint_matrix()\n True\n "
from sage.matrix.constructor import matrix
P = self.parent()
basis = P.basis()
return matrix(self.base_ring(), [P.bracket(self, b).to_vector(sparse=sparse) for b in basis], sparse=sparse).transpose()
def to_vector(self, order=None, sparse=False):
"\n Return the vector in ``g.module()`` corresponding to the\n element ``self`` of ``g`` (where ``g`` is the parent of\n ``self``).\n\n Implement this if you implement ``g.module()``.\n See :meth:`sage.categories.lie_algebras.LieAlgebras.module`\n for how this is to be done.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example()\n sage: L.an_element().to_vector()\n (0, 0, 0)\n sage: L.an_element().to_vector(sparse=True)\n (0, 0, 0)\n\n sage: # needs sage.combinat sage.groupssage.modules\n sage: D = DescentAlgebra(QQ, 4).D()\n sage: L = LieAlgebra(associative=D)\n sage: L.an_element().to_vector()\n (1, 1, 1, 1, 1, 1, 1, 1)\n\n TESTS:\n\n Check that the error raised agrees with the one\n from ``monomial_coefficients()`` (see :trac:`25007`)::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.sp(QQ, 4, representation='matrix')\n sage: x = L.an_element()\n sage: x.monomial_coefficients()\n Traceback (most recent call last):\n ...\n NotImplementedError: the basis is not defined\n sage: x.to_vector()\n Traceback (most recent call last):\n ...\n NotImplementedError: the basis is not defined\n "
mc = self.monomial_coefficients(copy=False)
if sparse:
from sage.modules.free_module import FreeModule
M = FreeModule(self.parent().base_ring(), self.dimension(), sparse=True)
if (order is None):
order = {b: i for (i, b) in enumerate(self.parent()._basis_ordering)}
return M({order[k]: c for (k, c) in mc.items()})
else:
M = self.parent().module()
B = M.basis()
if (order is None):
order = self.parent()._basis_ordering
return M.sum(((mc[k] * B[i]) for (i, k) in enumerate(order) if (k in mc)))
_vector_ = to_vector
class Subobjects(SubobjectsCategory):
'\n A category for subalgebras of a finite dimensional Lie algebra\n with basis.\n '
class ParentMethods():
@abstract_method
def ambient(self):
'\n Return the ambient Lie algebra of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis()\n sage: L = C.example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: S = L.subalgebra([2*a + b, b + c])\n sage: S.ambient() == L\n True\n '
@abstract_method
def basis_matrix(self):
'\n Return the basis matrix of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: C = LieAlgebras(QQ).FiniteDimensional().WithBasis()\n sage: L = C.example()\n sage: a, b, c = L.lie_algebra_generators()\n sage: S = L.subalgebra([2*a + b, b + c])\n sage: S.basis_matrix()\n [ 1 0 -1/2]\n [ 0 1 1]\n '
|
class FiniteDimensionalModulesWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of finite dimensional modules with a distinguished basis\n\n EXAMPLES::\n\n sage: C = FiniteDimensionalModulesWithBasis(ZZ); C\n Category of finite dimensional modules with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of finite dimensional modules over Integer Ring,\n Category of modules with basis over Integer Ring]\n sage: C is Modules(ZZ).WithBasis().FiniteDimensional()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class ParentMethods():
def gens(self):
"\n Return the generators of ``self``.\n\n OUTPUT:\n\n A tuple containing the basis elements of ``self``.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(ZZ, ['a', 'b', 'c']) # needs sage.modules\n sage: F.gens() # needs sage.modules\n (B['a'], B['b'], B['c'])\n "
return tuple(self.basis())
def annihilator(self, S, action=operator.mul, side='right', category=None):
'\n Return the annihilator of a finite set.\n\n INPUT:\n\n - ``S`` -- a finite set\n\n - ``action`` -- a function (default: :obj:`operator.mul`)\n\n - ``side`` -- \'left\' or \'right\' (default: \'right\')\n\n - ``category`` -- a category\n\n Assumptions:\n\n - ``action`` takes elements of ``self`` as first argument\n and elements of ``S`` as second argument;\n\n - The codomain is any vector space, and ``action`` is\n linear on its first argument; typically it is bilinear;\n\n - If ``side`` is \'left\', this is reversed.\n\n OUTPUT:\n\n The subspace of the elements `x` of ``self`` such that\n ``action(x,s) = 0`` for all `s\\in S`. If ``side`` is\n \'left\' replace the above equation by ``action(s,x) = 0``.\n\n If ``self`` is a ring, ``action`` an action of ``self`` on\n a module `M` and `S` is a subset of `M`, we recover the\n :wikipedia:`Annihilator_%28ring_theory%29`. Similarly this\n can be used to compute torsion or orthogonals.\n\n .. SEEALSO:: :meth:`annihilator_basis` for lots of examples.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = FiniteDimensionalAlgebrasWithBasis(QQ).example(); F\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: x, y, a, b = F.basis()\n sage: A = F.annihilator([a + 3*b + 2*y]); A\n Free module generated by {0} over Rational Field\n sage: [b.lift() for b in A.basis()]\n [-1/2*a - 3/2*b + x]\n\n The category can be used to specify other properties of\n this subspace, like that this is a subalgebra::\n\n sage: # needs sage.modules\n sage: center = F.annihilator(F.basis(), F.bracket,\n ....: category=Algebras(QQ).Subobjects())\n sage: (e,) = center.basis()\n sage: e.lift()\n x + y\n sage: e * e == e\n True\n\n Taking annihilator is order reversing for inclusion::\n\n sage: # needs sage.modules\n sage: A = F.annihilator([]); A .rename("A")\n sage: Ax = F.annihilator([x]); Ax .rename("Ax")\n sage: Ay = F.annihilator([y]); Ay .rename("Ay")\n sage: Axy = F.annihilator([x,y]); Axy.rename("Axy")\n sage: P = Poset(([A, Ax, Ay, Axy], attrcall("is_submodule"))) # needs sage.combinat sage.graphs\n sage: sorted(P.cover_relations(), key=str) # needs sage.combinat sage.graphs\n [[Ax, A], [Axy, Ax], [Axy, Ay], [Ay, A]]\n '
return self.submodule(self.annihilator_basis(S, action, side), already_echelonized=True, category=category)
def annihilator_basis(self, S, action=operator.mul, side='right'):
'\n Return a basis of the annihilator of a finite set of elements.\n\n INPUT:\n\n - ``S`` -- a finite set of objects\n\n - ``action`` -- a function (default: :obj:`operator.mul`)\n\n - ``side`` -- \'left\' or \'right\' (default: \'right\'):\n on which side of ``self`` the elements of `S` acts.\n\n See :meth:`annihilator` for the assumptions and definition\n of the annihilator.\n\n EXAMPLES:\n\n By default, the action is the standard `*` operation. So\n our first example is about an algebra::\n\n sage: # needs sage.graphs sage.modules\n sage: F = FiniteDimensionalAlgebrasWithBasis(QQ).example(); F\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver\n (containing the arrows a:x->y and b:x->y) over Rational Field\n sage: x,y,a,b = F.basis()\n\n In this algebra, multiplication on the right by `x`\n annihilates all basis elements but `x`::\n\n sage: x*x, y*x, a*x, b*x # needs sage.graphs sage.modules\n (x, 0, 0, 0)\n\n So the annihilator is the subspace spanned by `y`, `a`, and `b`::\n\n sage: F.annihilator_basis([x]) # needs sage.graphs sage.modules\n (y, a, b)\n\n The same holds for `a` and `b`::\n\n sage: x*a, y*a, a*a, b*a # needs sage.graphs sage.modules\n (a, 0, 0, 0)\n sage: F.annihilator_basis([a]) # needs sage.graphs sage.modules\n (y, a, b)\n\n On the other hand, `y` annihilates only `x`::\n\n sage: F.annihilator_basis([y]) # needs sage.graphs sage.modules\n (x,)\n\n Here is a non trivial annihilator::\n\n sage: F.annihilator_basis([a + 3*b + 2*y]) # needs sage.graphs sage.modules\n (-1/2*a - 3/2*b + x,)\n\n Let\'s check it::\n\n sage: (-1/2*a - 3/2*b + x) * (a + 3*b + 2*y) # needs sage.graphs sage.modules\n 0\n\n Doing the same calculations on the left exchanges the\n roles of `x` and `y`::\n\n sage: # needs sage.graphs sage.modules\n sage: F.annihilator_basis([y], side="left")\n (x, a, b)\n sage: F.annihilator_basis([a], side="left")\n (x, a, b)\n sage: F.annihilator_basis([b], side="left")\n (x, a, b)\n sage: F.annihilator_basis([x], side="left")\n (y,)\n sage: F.annihilator_basis([a + 3*b + 2*x], side="left")\n (-1/2*a - 3/2*b + y,)\n\n By specifying an inner product, this method can be used to\n compute the orthogonal of a subspace::\n\n sage: # needs sage.graphs sage.modules\n sage: x,y,a,b = F.basis()\n sage: def scalar(u,v):\n ....: return vector([sum(u[i]*v[i] for i in F.basis().keys())])\n sage: F.annihilator_basis([x + y, a + b], scalar)\n (x - y, a - b)\n\n By specifying the standard Lie bracket as action, one can\n compute the commutator of a subspace of `F`::\n\n sage: F.annihilator_basis([a + b], action=F.bracket) # needs sage.graphs sage.modules\n (x + y, a, b)\n\n In particular one can compute a basis of the center of the\n algebra. In our example, it is reduced to the identity::\n\n sage: F.annihilator_basis(F.algebra_generators(), action=F.bracket) # needs sage.graphs sage.modules\n (x + y,)\n\n But see also\n :meth:`FiniteDimensionalAlgebrasWithBasis.ParentMethods.center_basis`.\n '
from sage.matrix.constructor import matrix
if (side == 'right'):
action_left = action
action = (lambda b, s: action_left(s, b))
mat = matrix(self.base_ring(), self.dimension(), 0)
for s in S:
mat = mat.augment(matrix(self.base_ring(), [action(s, b)._vector_() for b in self.basis()]))
return tuple(map(self.from_vector, mat.left_kernel().basis()))
@cached_method
def _dense_free_module(self, base_ring=None):
"\n Return a dense free module of the same dimension as ``self``.\n\n INPUT:\n\n - ``base_ring`` -- a ring or ``None``\n\n If ``base_ring`` is ``None``, then the base ring of ``self``\n is used.\n\n This method is mostly used by ``_vector_``\n\n EXAMPLES::\n\n sage: C = CombinatorialFreeModule(QQ['x'], ['a','b','c']); C # needs sage.modules\n Free module generated by {'a', 'b', 'c'} over\n Univariate Polynomial Ring in x over Rational Field\n sage: C._dense_free_module() # needs sage.modules\n Ambient free module of rank 3 over the principal ideal domain\n Univariate Polynomial Ring in x over Rational Field\n sage: C._dense_free_module(QQ['x,y']) # needs sage.modules\n Ambient free module of rank 3 over the integral domain\n Multivariate Polynomial Ring in x, y over Rational Field\n "
if (base_ring is None):
base_ring = self.base_ring()
from sage.modules.free_module import FreeModule
return FreeModule(base_ring, self.dimension())
def from_vector(self, vector, order=None, coerce=True):
"\n Build an element of ``self`` from a vector.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: p_mult = matrix([[0,0,0], [0,0,-1], [0,0,0]])\n sage: q_mult = matrix([[0,0,1], [0,0,0], [0,0,0]])\n sage: A = algebras.FiniteDimensional(\n ....: QQ, [p_mult, q_mult, matrix(QQ, 3, 3)], 'p,q,z')\n sage: A.from_vector(vector([1,0,2]))\n p + 2*z\n "
if (order is None):
try:
order = sorted(self.basis().keys())
except AttributeError:
order = range(self.dimension())
if ((not coerce) or (vector.base_ring() is self.base_ring())):
return self._from_dict({order[i]: c for (i, c) in vector.items()}, coerce=False)
R = self.base_ring()
return self._from_dict({order[i]: R(c) for (i, c) in vector.items() if R(c)}, coerce=False, remove_zeros=False)
def echelon_form(self, elements, row_reduced=False, order=None):
'\n Return a basis in echelon form of the subspace spanned by\n a finite set of elements.\n\n INPUT:\n\n - ``elements`` -- a list or finite iterable of elements of ``self``\n - ``row_reduced`` -- (default: ``False``) whether to compute the\n basis for the row reduced echelon form\n - ``order`` -- (optional) either something that can\n be converted into a tuple or a key function\n\n OUTPUT:\n\n A list of elements of ``self`` whose expressions as vectors\n form a matrix in echelon form. If ``base_ring`` is specified,\n then the calculation is achieved in this base ring.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")\n sage: x = X.basis()\n sage: V = X.echelon_form([x[0]-x[1], x[0]-x[2], x[1]-x[2]]); V\n [x[0] - x[2], x[1] - x[2]]\n sage: matrix(list(map(vector, V)))\n [ 1 0 -1]\n [ 0 1 -1]\n\n ::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, [1,2,3,4])\n sage: B = F.basis()\n sage: elements = [B[1]-17*B[2]+6*B[3], B[1]-17*B[2]+B[4]]\n sage: F.echelon_form(elements)\n [B[1] - 17*B[2] + B[4], 6*B[3] - B[4]]\n\n ::\n\n sage: F = CombinatorialFreeModule(QQ, [\'a\',\'b\',\'c\']) # needs sage.modules\n sage: a,b,c = F.basis() # needs sage.modules\n sage: F.echelon_form([8*a+b+10*c, -3*a+b-c, a-b-c]) # needs sage.modules\n [B[\'a\'] + B[\'c\'], B[\'b\'] + 2*B[\'c\']]\n\n ::\n\n sage: R.<x,y> = QQ[]\n sage: C = CombinatorialFreeModule(R, range(3), prefix=\'x\') # needs sage.modules\n sage: x = C.basis() # needs sage.modules\n sage: C.echelon_form([x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]) # needs sage.modules sage.rings.function_field\n [x[0] - x[2], x[1] - x[2]]\n\n ::\n\n sage: M = MatrixSpace(QQ, 3, 3) # needs sage.modules\n sage: A = M([[0, 0, 2], [0, 0, 0], [0, 0, 0]]) # needs sage.modules\n sage: M.echelon_form([A, A]) # needs sage.modules\n [\n [0 0 1]\n [0 0 0]\n [0 0 0]\n ]\n\n TESTS:\n\n We convert the input elements to ``self``::\n\n sage: E.<x,y,z> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: E.echelon_form([1, x + 2]) # needs sage.modules\n [1, x]\n '
elements = [self(y) for y in elements]
if (order is not None):
order = self._compute_support_order(elements, order)
from sage.matrix.constructor import matrix
mat = matrix(self.base_ring(), [g._vector_(order=order) for g in elements])
if (row_reduced and (self.base_ring() not in Fields())):
try:
mat = mat.rref().change_ring(self.base_ring())
except (ValueError, TypeError):
raise ValueError('unable to compute the row reduced echelon form')
else:
mat.echelonize()
ret = [self.from_vector(vec, order=order) for vec in mat if vec]
return ret
def invariant_module(self, S, action=operator.mul, action_on_basis=None, side='left', **kwargs):
"\n Return the submodule of ``self`` invariant under the action\n of ``S``.\n\n For a semigroup `S` acting on a module `M`, the invariant\n submodule is given by\n\n .. MATH::\n\n M^S = \\{m \\in M : s \\cdot m = m,\\, \\forall s \\in S\\}.\n\n INPUT:\n\n - ``S`` -- a finitely-generated semigroup\n - ``action`` -- a function (default: :obj:`operator.mul`)\n - ``side`` -- ``'left'`` or ``'right'`` (default: ``'right'``);\n which side of ``self`` the elements of ``S`` acts\n - ``action_on_basis`` -- (optional) define the action of ``S``\n on the basis of ``self``\n\n OUTPUT:\n\n - :class:`~sage.modules.with_basis.invariant.FiniteDimensionalInvariantModule`\n\n EXAMPLES:\n\n We build the invariant module of the permutation representation\n of the symmetric group::\n\n sage: # needs sage.groups sage.modules\n sage: G = SymmetricGroup(3); G.rename('S3')\n sage: M = FreeModule(ZZ, [1,2,3], prefix='M'); M.rename('M')\n sage: action = lambda g, x: M.term(g(x))\n sage: I = M.invariant_module(G, action_on_basis=action); I\n (S3)-invariant submodule of M\n sage: I.basis()\n Finite family {0: B[0]}\n sage: [I.lift(b) for b in I.basis()]\n [M[1] + M[2] + M[3]]\n sage: G.rename(); M.rename() # reset the names\n\n We can construct the invariant module of any module that has\n an action of ``S``. In this example, we consider the dihedral\n group `G = D_4` and the subgroup `H < G` of all rotations. We\n construct the `H`-invariant module of the group algebra `\\QQ[G]`::\n\n sage: # needs sage.groups\n sage: G = groups.permutation.Dihedral(4)\n sage: H = G.subgroup(G.gen(0))\n sage: H\n Subgroup generated by [(1,2,3,4)]\n of (Dihedral group of order 8 as a permutation group)\n sage: H.cardinality()\n 4\n\n sage: # needs sage.groups sage.modules\n sage: A = G.algebra(QQ)\n sage: I = A.invariant_module(H)\n sage: [I.lift(b) for b in I.basis()]\n [() + (1,2,3,4) + (1,3)(2,4) + (1,4,3,2),\n (2,4) + (1,2)(3,4) + (1,3) + (1,4)(2,3)]\n sage: all(h * I.lift(b) == I.lift(b)\n ....: for b in I.basis() for h in H)\n True\n "
if (action_on_basis is not None):
from sage.modules.with_basis.representation import Representation
M = Representation(S, self, action_on_basis, side=side)
else:
M = self
from sage.modules.with_basis.invariant import FiniteDimensionalInvariantModule
return FiniteDimensionalInvariantModule(M, S, action=action, side=side, **kwargs)
def twisted_invariant_module(self, G, chi, action=operator.mul, action_on_basis=None, side='left', **kwargs):
"\n Create the isotypic component of the action of ``G`` on\n ``self`` with irreducible character given by ``chi``.\n\n .. SEEALSO::\n\n -:class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule`\n\n INPUT:\n\n - ``G`` -- a finitely-generated group\n - ``chi`` -- a list/tuple of character values or an instance of\n :class:`~sage.groups.class_function.ClassFunction_gap`\n - ``action`` -- a function (default: :obj:`operator.mul`)\n - ``action_on_basis`` -- (optional) define the action of ``g``\n on the basis of ``self``\n - ``side`` -- ``'left'`` or ``'right'`` (default: ``'right'``);\n which side of ``self`` the elements of ``S`` acts\n\n OUTPUT:\n\n - :class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule`\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: M = CombinatorialFreeModule(QQ, [1,2,3])\n sage: G = SymmetricGroup(3)\n sage: def action(g,x): return(M.term(g(x))) # permute coordinates\n sage: T = M.twisted_invariant_module(G, [2,0,-1],\n ....: action_on_basis=action)\n sage: import __main__; __main__.action = action\n sage: TestSuite(T).run()\n "
if (action_on_basis is not None):
from sage.modules.with_basis.representation import Representation
from sage.categories.modules import Modules
category = kwargs.pop('category', Modules(self.base_ring()).WithBasis())
M = Representation(G, self, action_on_basis, side=side, category=category)
else:
M = self
from sage.modules.with_basis.invariant import FiniteDimensionalTwistedInvariantModule
return FiniteDimensionalTwistedInvariantModule(M, G, chi, action, side, **kwargs)
class ElementMethods():
def dense_coefficient_list(self, order=None):
'\n Return a list of *all* coefficients of ``self``.\n\n By default, this list is ordered in the same way as the\n indexing set of the basis of the parent of ``self``.\n\n INPUT:\n\n - ``order`` -- (optional) an ordering of the basis indexing set\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: v = vector([0, -1, -3])\n sage: v.dense_coefficient_list()\n [0, -1, -3]\n sage: v.dense_coefficient_list([2,1,0])\n [-3, -1, 0]\n sage: sorted(v.coefficients())\n [-3, -1]\n '
if (order is None):
try:
order = sorted(self.parent().basis().keys())
except AttributeError:
order = range(self.parent().dimension())
return [self[i] for i in order]
def _vector_(self, order=None):
"\n Return ``self`` as a vector.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: v = vector([0, -1, -3])\n sage: v._vector_()\n (0, -1, -3)\n sage: C = CombinatorialFreeModule(QQ['x'], ['a','b','c'])\n sage: C.an_element()._vector_()\n (2, 2, 3)\n "
if (order is None):
dense_free_module = self.parent()._dense_free_module()
else:
from sage.modules.free_module import FreeModule
dense_free_module = FreeModule(self.parent().base_ring(), len(order))
return dense_free_module.element_class(dense_free_module, self.dense_coefficient_list(order), coerce=True, copy=False)
class MorphismMethods():
def matrix(self, base_ring=None, side='left'):
'\n Return the matrix of this morphism in the distinguished\n bases of the domain and codomain.\n\n INPUT:\n\n - ``base_ring`` -- a ring (default: ``None``, meaning the\n base ring of the codomain)\n\n - ``side`` -- "left" or "right" (default: "left")\n\n If ``side`` is "left", this morphism is considered as\n acting on the left; i.e. each column of the matrix\n represents the image of an element of the basis of the\n domain.\n\n The order of the rows and columns matches with the order\n in which the bases are enumerated.\n\n .. SEEALSO:: :func:`Modules.WithBasis.ParentMethods.module_morphism`\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(ZZ, [1,2]); x = X.basis()\n sage: Y = CombinatorialFreeModule(ZZ, [3,4]); y = Y.basis()\n sage: phi = X.module_morphism(on_basis={1: y[3] + 3*y[4],\n ....: 2: 2*y[3] + 5*y[4]}.__getitem__,\n ....: codomain=Y)\n sage: phi.matrix()\n [1 2]\n [3 5]\n sage: phi.matrix(side="right")\n [1 3]\n [2 5]\n\n sage: phi.matrix().parent() # needs sage.modules\n Full MatrixSpace of 2 by 2 dense matrices over Integer Ring\n sage: phi.matrix(QQ).parent() # needs sage.modules\n Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n\n The resulting matrix is immutable::\n\n sage: phi.matrix().is_mutable() # needs sage.modules\n False\n\n The zero morphism has a zero matrix::\n\n sage: Hom(X, Y).zero().matrix() # needs sage.modules\n [0 0]\n [0 0]\n\n .. TODO::\n\n Add support for morphisms where the codomain has a\n different base ring than the domain::\n\n sage: Y = CombinatorialFreeModule(QQ, [3,4]); y = Y.basis() # needs sage.modules\n sage: phi = X.module_morphism(on_basis={1: y[3] + 3*y[4], # needs sage.modules\n ....: 2: 2*y[3] + 5/2*y[4]}.__getitem__,\n ....: codomain=Y)\n sage: phi.matrix().parent() # not implemented # needs sage.modules\n Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n\n This currently does not work because, in this case,\n the morphism is just in the category of commutative\n additive groups (i.e. the intersection of the\n categories of modules over `\\ZZ` and over `\\QQ`)::\n\n sage: phi.parent().homset_category() # needs sage.modules\n Category of commutative additive semigroups\n sage: phi.parent().homset_category() # not implemented, needs sage.modules\n Category of finite dimensional modules with basis over Integer Ring\n\n TESTS:\n\n Check that :trac:`23216` is fixed::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [])\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3])\n sage: Hom(X, Y).zero().matrix()\n []\n sage: Hom(X, Y).zero().matrix().parent()\n Full MatrixSpace of 3 by 0 dense matrices over Rational Field\n '
if (base_ring is None):
base_ring = self.codomain().base_ring()
on_basis = self.on_basis()
basis_keys = self.domain().basis().keys()
from sage.matrix.matrix_space import MatrixSpace
if isinstance(basis_keys, list):
nrows = len(basis_keys)
else:
nrows = basis_keys.cardinality()
MS = MatrixSpace(base_ring, nrows, self.codomain().dimension())
m = MS([on_basis(x)._vector_() for x in basis_keys])
if (side == 'left'):
m = m.transpose()
m.set_immutable()
return m
def __invert__(self):
'\n Return the inverse morphism of ``self``.\n\n This is achieved by inverting the ``self.matrix()``.\n An error is raised if ``self`` is not invertible.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: category = FiniteDimensionalModulesWithBasis(ZZ)\n sage: X = CombinatorialFreeModule(ZZ, [1,2], category=category); X.rename("X"); x = X.basis()\n sage: Y = CombinatorialFreeModule(ZZ, [3,4], category=category); Y.rename("Y"); y = Y.basis()\n sage: phi = X.module_morphism(on_basis={1: y[3] + 3*y[4], 2: 2*y[3] + 5*y[4]}.__getitem__,\n ....: codomain=Y, category=category)\n sage: psi = ~phi\n sage: psi\n Generic morphism:\n From: Y\n To: X\n sage: psi.parent()\n Set of Morphisms from Y to X in Category of finite dimensional modules with basis over Integer Ring\n sage: psi(y[3])\n -5*B[1] + 3*B[2]\n sage: psi(y[4])\n 2*B[1] - B[2]\n sage: psi.matrix()\n [-5 2]\n [ 3 -1]\n sage: psi(phi(x[1])), psi(phi(x[2]))\n (B[1], B[2])\n sage: phi(psi(y[3])), phi(psi(y[4]))\n (B[3], B[4])\n\n We check that this function complains if the morphism is not invertible::\n\n sage: phi = X.module_morphism(on_basis={1: y[3] + y[4], 2: y[3] + y[4]}.__getitem__, # needs sage.modules\n ....: codomain=Y, category=category)\n sage: ~phi # needs sage.modules\n Traceback (most recent call last):\n ...\n RuntimeError: morphism is not invertible\n\n sage: phi = X.module_morphism(on_basis={1: y[3] + y[4], 2: y[3] + 5*y[4]}.__getitem__, # needs sage.modules\n ....: codomain=Y, category=category)\n sage: ~phi # needs sage.modules\n Traceback (most recent call last):\n ...\n RuntimeError: morphism is not invertible\n '
mat = self.matrix()
try:
inv_mat = mat.parent()((~ mat))
except (ZeroDivisionError, TypeError):
raise RuntimeError('morphism is not invertible')
return self.codomain().module_morphism(matrix=inv_mat, codomain=self.domain(), category=self.category_for())
def kernel_basis(self):
'\n Return a basis of the kernel of ``self`` in echelon form.\n\n EXAMPLES::\n\n sage: SGA = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: f = SGA.module_morphism(lambda x: SGA(x**2), codomain=SGA) # needs sage.groups sage.modules\n sage: f.kernel_basis() # needs sage.groups sage.modules\n ([1, 2, 3] - [3, 2, 1], [1, 3, 2] - [3, 2, 1], [2, 1, 3] - [3, 2, 1])\n '
return tuple(map(self.domain().from_vector, self.matrix().right_kernel_matrix().rows()))
def kernel(self):
'\n Return the kernel of ``self`` as a submodule of the domain.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: SGA = SymmetricGroupAlgebra(QQ, 3)\n sage: f = SGA.module_morphism(lambda x: SGA(x**2), codomain=SGA)\n sage: K = f.kernel()\n sage: K\n Free module generated by {0, 1, 2} over Rational Field\n sage: K.ambient()\n Symmetric group algebra of order 3 over Rational Field\n '
D = self.domain()
return D.submodule(self.kernel_basis(), already_echelonized=True, category=self.category_for())
def image_basis(self):
'\n Return a basis for the image of ``self`` in echelon form.\n\n EXAMPLES::\n\n sage: SGA = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: f = SGA.module_morphism(lambda x: SGA(x**2), codomain=SGA) # needs sage.groups sage.modules\n sage: f.image_basis() # needs sage.groups sage.modules\n ([1, 2, 3], [2, 3, 1], [3, 1, 2])\n '
C = self.codomain()
return tuple(C.echelon_form(map(self, self.domain().basis())))
def image(self):
'\n Return the image of ``self`` as a submodule of the codomain.\n\n EXAMPLES::\n\n sage: SGA = SymmetricGroupAlgebra(QQ, 3) # needs sage.groups sage.modules\n sage: f = SGA.module_morphism(lambda x: SGA(x**2), codomain=SGA) # needs sage.groups sage.modules\n sage: f.image() # needs sage.groups sage.modules\n Free module generated by {0, 1, 2} over Rational Field\n '
C = self.codomain()
return C.submodule(self.image_basis(), already_echelonized=True, category=self.category_for())
class TensorProducts(TensorProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a (finite) tensor product of\n finite dimensional modules is a finite dimensional module.\n\n EXAMPLES::\n\n sage: C = ModulesWithBasis(ZZ).FiniteDimensional().TensorProducts()\n sage: C.extra_super_categories()\n [Category of finite dimensional modules with basis over Integer Ring]\n sage: C.FiniteDimensional()\n Category of tensor products of\n finite dimensional modules with basis over Integer Ring\n\n '
return [self.base_category()]
|
class FiniteDimensionalNilpotentLieAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional nilpotent Lie algebras with basis.\n\n TESTS::\n\n sage: C1 = LieAlgebras(QQ).FiniteDimensional().WithBasis().Nilpotent()\n sage: C2 = LieAlgebras(QQ).FiniteDimensional().Nilpotent().WithBasis()\n sage: C3 = LieAlgebras(QQ).Nilpotent().FiniteDimensional().WithBasis()\n sage: C4 = LieAlgebras(QQ).Nilpotent().WithBasis().FiniteDimensional()\n sage: C5 = LieAlgebras(QQ).WithBasis().Nilpotent().FiniteDimensional()\n sage: C6 = LieAlgebras(QQ).WithBasis().FiniteDimensional().Nilpotent()\n sage: C1 is C2\n True\n sage: C2 is C3\n True\n sage: C3 is C4\n True\n sage: C4 is C5\n True\n sage: C5 is C6\n True\n sage: TestSuite(C1).run()\n '
_base_category_class_and_axiom = (LieAlgebras.FiniteDimensional.WithBasis, 'Nilpotent')
class ParentMethods():
def _test_nilpotency(self, **options):
"\n Tests that ``self`` is nilpotent and has the correct step.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by\n :meth:`_tester`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, {('X','Y'): {'Z': 1}}, nilpotent=True)\n sage: L._test_nilpotency()\n sage: L = LieAlgebra(QQ, {('X','Y'): {'Z': 1}},\n ....: nilpotent=True, step=3)\n sage: L._test_nilpotency()\n Traceback (most recent call last):\n ...\n AssertionError: claimed nilpotency step 3\n does not match the actual nilpotency step 2\n sage: L = LieAlgebra(QQ, {('X','Y'): {'X': 1}}, nilpotent=True)\n sage: L._test_nilpotency()\n Traceback (most recent call last):\n ...\n AssertionError: final term of lower central series is non-zero\n\n See the documentation for :class:`TestSuite` for more information.\n "
tester = self._tester(**options)
lcs = self.lower_central_series(submodule=True)
tester.assertEqual(lcs[(- 1)].dimension(), 0, msg='final term of lower central series is non-zero')
step = self.step()
tester.assertEqual((len(lcs) - 1), step, msg=('claimed nilpotency step %d does not match the actual nilpotency step %d' % (step, (len(lcs) - 1))))
def lie_group(self, name='G', **kwds):
"\n Return the Lie group associated to ``self``.\n\n INPUT:\n\n - ``name`` -- string (default: ``'G'``);\n the name (symbol) given to the Lie group\n\n EXAMPLES:\n\n We define the Heisenberg group::\n\n sage: L = lie_algebras.Heisenberg(QQ, 1) # needs sage.combinat sage.modules\n sage: G = L.lie_group('G'); G # needs sage.combinat sage.modules sage.symbolic\n Lie group G of Heisenberg algebra of rank 1 over Rational Field\n\n We test multiplying elements of the group::\n\n sage: # needs sage.combinat sage.modules sage.symbolic\n sage: p, q, z = L.basis()\n sage: g = G.exp(p); g\n exp(p1)\n sage: h = G.exp(q); h\n exp(q1)\n sage: g * h\n exp(p1 + q1 + 1/2*z)\n\n We extend an element of the Lie algebra to a left-invariant\n vector field::\n\n sage: X = G.left_invariant_extension(2*p + 3*q, name='X'); X # needs sage.combinat sage.modules sage.symbolic\n Vector field X on the Lie group G of\n Heisenberg algebra of rank 1 over Rational Field\n sage: X.at(G.one()).display() # needs sage.combinat sage.modules sage.symbolic\n X = 2 ∂/∂x_0 + 3 ∂/∂x_1\n sage: X.display() # needs sage.combinat sage.modules sage.symbolic\n X = 2 ∂/∂x_0 + 3 ∂/∂x_1 + (3/2*x_0 - x_1) ∂/∂x_2\n\n .. SEEALSO::\n\n :class:`~sage.groups.lie_gps.nilpotent_lie_group.NilpotentLieGroup`\n "
from sage.groups.lie_gps.nilpotent_lie_group import NilpotentLieGroup
return NilpotentLieGroup(self, name, **kwds)
def step(self):
"\n Return the nilpotency step of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, {('X','Y'): {'Z': 1}}, nilpotent=True)\n sage: L.step()\n 2\n sage: sc = {('X','Y'): {'Z': 1}, ('X','Z'): {'W': 1}}\n sage: LieAlgebra(QQ, sc, nilpotent=True).step()\n 3\n "
if (not hasattr(self, '_step')):
self._step = (len(self.lower_central_series(submodule=True)) - 1)
return self._step
def is_nilpotent(self):
"\n Return ``True`` since ``self`` is nilpotent.\n\n EXAMPLES::\n\n sage: L = LieAlgebra(QQ, {('x','y'): {'z': 1}}, nilpotent=True) # needs sage.combinat sage.modules\n sage: L.is_nilpotent() # needs sage.combinat sage.modules\n True\n "
return True
|
class FiniteDimensionalSemisimpleAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of finite dimensional semisimple algebras with a distinguished basis\n\n EXAMPLES::\n\n sage: from sage.categories.finite_dimensional_semisimple_algebras_with_basis import FiniteDimensionalSemisimpleAlgebrasWithBasis\n sage: C = FiniteDimensionalSemisimpleAlgebrasWithBasis(QQ); C\n Category of finite dimensional semisimple algebras with basis over Rational Field\n\n This category is best constructed as::\n\n sage: D = Algebras(QQ).Semisimple().FiniteDimensional().WithBasis(); D\n Category of finite dimensional semisimple algebras with basis over Rational Field\n sage: D is C\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
_base_category_class_and_axiom = (SemisimpleAlgebras.FiniteDimensional, 'WithBasis')
class ParentMethods():
def radical_basis(self, **keywords):
"\n Return a basis of the Jacobson radical of this algebra.\n\n - ``keywords`` -- for compatibility; ignored.\n\n OUTPUT: the empty list since this algebra is semisimple.\n\n EXAMPLES::\n\n sage: A = SymmetricGroup(4).algebra(QQ) # needs sage.groups sage.modules\n sage: A.radical_basis() # needs sage.groups sage.modules\n ()\n\n TESTS::\n\n sage: A.radical_basis.__module__ # needs sage.groups sage.modules\n 'sage.categories.finite_dimensional_semisimple_algebras_with_basis'\n "
return ()
@cached_method
def central_orthogonal_idempotents(self):
"\n Return a maximal list of central orthogonal\n idempotents of ``self``.\n\n *Central orthogonal idempotents* of an algebra `A`\n are idempotents `(e_1, \\ldots, e_n)` in the center\n of `A` such that `e_i e_j = 0` whenever `i \\neq j`.\n\n With the maximality condition, they sum up to `1`\n and are uniquely determined (up to order).\n\n EXAMPLES:\n\n For the algebra of the (abelian) alternating group `A_3`,\n we recover three idempotents corresponding to the three\n one-dimensional representations `V_i` on which `(1,2,3)`\n acts on `V_i` as multiplication by the `i`-th power of a\n cube root of unity::\n\n sage: # needs sage.groups sage.rings.number_field\n sage: R = CyclotomicField(3)\n sage: A3 = AlternatingGroup(3).algebra(R)\n sage: idempotents = A3.central_orthogonal_idempotents()\n sage: idempotents\n (1/3*() + 1/3*(1,2,3) + 1/3*(1,3,2),\n 1/3*() - (1/3*zeta3+1/3)*(1,2,3) - (-1/3*zeta3)*(1,3,2),\n 1/3*() - (-1/3*zeta3)*(1,2,3) - (1/3*zeta3+1/3)*(1,3,2))\n sage: A3.is_identity_decomposition_into_orthogonal_idempotents(idempotents)\n True\n\n For the semisimple quotient of a quiver algebra,\n we recover the vertices of the quiver::\n\n sage: # needs sage.graphs sage.modules\n sage: A = FiniteDimensionalAlgebrasWithBasis(QQ).example(); A\n An example of a finite dimensional algebra with basis:\n the path algebra of the Kronecker quiver (containing\n the arrows a:x->y and b:x->y) over Rational Field\n sage: Aquo = A.semisimple_quotient()\n sage: Aquo.central_orthogonal_idempotents()\n (B['x'], B['y'])\n "
return tuple([x.lift() for x in self.center().central_orthogonal_idempotents()])
class Commutative(CategoryWithAxiom_over_base_ring):
class ParentMethods():
@cached_method
def _orthogonal_decomposition(self, generators=None):
"\n Return a maximal list of orthogonal quasi-idempotents of\n this finite dimensional semisimple commutative algebra.\n\n INPUT:\n\n - ``generators`` -- a list of generators of\n ``self`` (default: the basis of ``self``)\n\n OUTPUT:\n\n A list of quasi-idempotent elements of ``self``.\n\n Each quasi-idempotent `e` spans a one\n dimensional (non unital) subalgebra of\n ``self``, and cannot be decomposed as a sum\n `e=e_1+e_2` of quasi-idempotents elements.\n All together, they form a basis of ``self``.\n\n Up to the order and scalar factors, the result\n is unique. In particular it does not depend on\n the provided generators which are only used\n for improved efficiency.\n\n ALGORITHM:\n\n Thanks to Schur's Lemma, a commutative\n semisimple algebra `A` is a direct sum of\n dimension 1 subalgebras. The algorithm is\n recursive and proceeds as follows:\n\n 0. If `A` is of dimension 1, return a non zero\n element.\n\n 1. Otherwise: find one of the generators such\n that the morphism `x \\mapsto ax` has at\n least two (right) eigenspaces.\n\n 2. Decompose both eigenspaces recursively.\n\n EXAMPLES:\n\n We compute an orthogonal decomposition of the\n center of the algebra of the symmetric group\n `S_4`::\n\n sage: Z4 = SymmetricGroup(4).algebra(QQ).center() # needs sage.groups sage.modules\n sage: Z4._orthogonal_decomposition() # needs sage.groups sage.modules\n (B[0] + B[1] + B[2] + B[3] + B[4],\n B[0] + 1/3*B[1] - 1/3*B[2] - 1/3*B[4],\n B[0] + B[2] - 1/2*B[3],\n B[0] - 1/3*B[1] - 1/3*B[2] + 1/3*B[4],\n B[0] - B[1] + B[2] + B[3] - B[4])\n\n .. TODO::\n\n Improve speed by using matrix operations\n only, or even better delegating to a\n multivariate polynomial solver.\n "
if (self.dimension() == 1):
return self.basis().list()
category = Algebras(self.base_ring()).Semisimple().WithBasis().FiniteDimensional().Commutative().Subobjects()
if (generators is None):
generators = self.basis().list()
for gen in generators:
phi = self.module_morphism(on_basis=(lambda i: (gen * self.term(i))), codomain=self)
eigenspaces = phi.matrix().eigenspaces_right()
if (len(eigenspaces) >= 2):
subalgebras = [self.submodule(map(self.from_vector, eigenspace.basis()), category=category) for (eigenvalue, eigenspace) in eigenspaces]
return tuple([idempotent.lift() for subalgebra in subalgebras for idempotent in subalgebra._orthogonal_decomposition()])
raise Exception(('Unable to fully decompose %s!' % self))
@cached_method
def central_orthogonal_idempotents(self):
'\n Return the central orthogonal idempotents of\n this semisimple commutative algebra.\n\n Those idempotents form a maximal decomposition\n of the identity into primitive orthogonal\n idempotents.\n\n OUTPUT:\n\n A list of orthogonal idempotents of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A4 = SymmetricGroup(4).algebra(QQ)\n sage: Z4 = A4.center()\n sage: idempotents = Z4.central_orthogonal_idempotents()\n sage: idempotents\n (1/24*B[0] + 1/24*B[1] + 1/24*B[2] + 1/24*B[3] + 1/24*B[4],\n 3/8*B[0] + 1/8*B[1] - 1/8*B[2] - 1/8*B[4],\n 1/6*B[0] + 1/6*B[2] - 1/12*B[3],\n 3/8*B[0] - 1/8*B[1] - 1/8*B[2] + 1/8*B[4],\n 1/24*B[0] - 1/24*B[1] + 1/24*B[2] + 1/24*B[3] - 1/24*B[4])\n\n Lifting those idempotents from the center, we\n recognize among them the sum and alternating\n sum of all permutations::\n\n sage: [e.lift() for e in idempotents] # needs sage.groups sage.modules\n [1/24*() + 1/24*(3,4) + 1/24*(2,3) + 1/24*(2,3,4) + 1/24*(2,4,3)\n + 1/24*(2,4) + 1/24*(1,2) + 1/24*(1,2)(3,4) + 1/24*(1,2,3)\n + 1/24*(1,2,3,4) + 1/24*(1,2,4,3) + 1/24*(1,2,4) + 1/24*(1,3,2)\n + 1/24*(1,3,4,2) + 1/24*(1,3) + 1/24*(1,3,4) + 1/24*(1,3)(2,4)\n + 1/24*(1,3,2,4) + 1/24*(1,4,3,2) + 1/24*(1,4,2) + 1/24*(1,4,3)\n + 1/24*(1,4) + 1/24*(1,4,2,3) + 1/24*(1,4)(2,3),\n ...,\n 1/24*() - 1/24*(3,4) - 1/24*(2,3) + 1/24*(2,3,4) + 1/24*(2,4,3)\n - 1/24*(2,4) - 1/24*(1,2) + 1/24*(1,2)(3,4) + 1/24*(1,2,3)\n - 1/24*(1,2,3,4) - 1/24*(1,2,4,3) + 1/24*(1,2,4) + 1/24*(1,3,2)\n - 1/24*(1,3,4,2) - 1/24*(1,3) + 1/24*(1,3,4) + 1/24*(1,3)(2,4)\n - 1/24*(1,3,2,4) - 1/24*(1,4,3,2) + 1/24*(1,4,2) + 1/24*(1,4,3)\n - 1/24*(1,4) - 1/24*(1,4,2,3) + 1/24*(1,4)(2,3)]\n\n We check that they indeed form a decomposition\n of the identity of `Z_4` into orthogonal idempotents::\n\n sage: Z4.is_identity_decomposition_into_orthogonal_idempotents(idempotents) # needs sage.groups sage.modules\n True\n '
return tuple([((e.leading_coefficient() / (e * e).leading_coefficient()) * e) for e in self._orthogonal_decomposition()])
|
class FiniteEnumeratedSets(CategoryWithAxiom):
'\n The category of finite enumerated sets\n\n EXAMPLES::\n\n sage: FiniteEnumeratedSets()\n Category of finite enumerated sets\n sage: FiniteEnumeratedSets().super_categories()\n [Category of enumerated sets, Category of finite sets]\n sage: FiniteEnumeratedSets().all_super_categories()\n [Category of finite enumerated sets,\n Category of enumerated sets,\n Category of finite sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n TESTS::\n\n sage: C = FiniteEnumeratedSets()\n sage: TestSuite(C).run()\n sage: sorted(C.Algebras(QQ).super_categories(), key=str)\n [Category of finite dimensional vector spaces with basis over Rational Field,\n Category of set algebras over Rational Field]\n\n .. TODO::\n\n :class:`sage.combinat.debruijn_sequence.DeBruijnSequences` should\n not inherit from this class. If that is solved, then\n :class:`FiniteEnumeratedSets` shall be turned into a subclass of\n :class:`~sage.categories.category_singleton.Category_singleton`.\n '
def _call_(self, X):
'\n Construct an object in this category from the data in ``X``.\n\n EXAMPLES::\n\n sage: FiniteEnumeratedSets()(GF(3))\n Finite Field of size 3\n sage: Partitions(3) # needs sage.combinat\n Partitions of the integer 3\n\n For now, lists, tuples, sets, Sets are coerced into finite\n enumerated sets::\n\n sage: FiniteEnumeratedSets()([1, 2, 3])\n {1, 2, 3}\n sage: FiniteEnumeratedSets()((1, 2, 3))\n {1, 2, 3}\n sage: FiniteEnumeratedSets()(set([1, 2, 3]))\n {1, 2, 3}\n sage: FiniteEnumeratedSets()(Set([1, 2, 3]))\n {1, 2, 3}\n '
return EnumeratedSets()._call_(X)
class ParentMethods():
def __len__(self):
'\n Return the number of elements of ``self``.\n\n EXAMPLES::\n\n sage: len(GF(5))\n 5\n sage: len(MatrixSpace(GF(2), 3, 3)) # needs sage.modules\n 512\n '
return int(self.cardinality())
def _cardinality_from_iterator(self, *ignored_args, **ignored_kwds):
'\n Return the cardinality of ``self``.\n\n This brute force implementation of :meth:`cardinality`\n iterates through the elements of ``self`` to count them.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example(); C\n An example of a finite enumerated set: {1,2,3}\n sage: C._cardinality_from_iterator()\n 3\n\n TESTS:\n\n This is the default implementation of :meth:`cardinality`\n from the category ``FiniteEnumeratedSet()``. To test this,\n we need a fresh example::\n\n sage: from sage.categories.examples.finite_enumerated_sets import Example\n sage: class FreshExample(Example): pass\n sage: C = FreshExample(); C.rename("FreshExample")\n sage: C.cardinality\n <bound method FiniteEnumeratedSets.ParentMethods._cardinality_from_iterator of FreshExample>\n\n This method shall return an ``Integer``; we test this\n here, because :meth:`_test_enumerated_set_iter_cardinality`\n does not do it for us::\n\n sage: type(C._cardinality_from_iterator())\n <class \'sage.rings.integer.Integer\'>\n\n We ignore additional inputs since during doctests classes which\n override ``cardinality()`` call up to the category rather than\n their own ``cardinality()`` method (see :trac:`13688`)::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._cardinality_from_iterator(algorithm=\'testing\')\n 3\n\n Here is a more complete example::\n\n sage: class TestParent(Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category=FiniteEnumeratedSets())\n ....: def __iter__(self):\n ....: yield 1\n ....: return\n ....: def cardinality(self, dummy_arg):\n ....: return 1 # we don\'t want to change the semantics of cardinality()\n sage: P = TestParent()\n sage: P.cardinality(-1)\n 1\n sage: v = P.list(); v\n [1]\n sage: P.cardinality()\n 1\n sage: P.cardinality(\'use alt algorithm\') # Used to break here: see trac #13688\n 1\n sage: P.cardinality(dummy_arg=\'use alg algorithm\') # Used to break here: see trac #13688\n 1\n '
c = 0
for _ in self:
c += 1
return Integer(c)
cardinality = _cardinality_from_iterator
def _cardinality_from_list(self, *ignored_args, **ignored_kwds):
"\n The cardinality of ``self``.\n\n This implementation of :meth:`cardinality` computes the\n cardinality from :meth:`list` (which is\n cached). Reciprocally, calling ``self.list()`` makes this\n method the default implementation of :meth:`cardinality`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._cardinality_from_list()\n 3\n\n We ignore additional inputs since during doctests classes which\n override ``cardinality()`` call up to the category rather than\n their own ``cardinality()`` method (see :trac:`13688`)::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._cardinality_from_list(algorithm='testing')\n 3\n "
return Integer(len(self.tuple()))
def _unrank_from_list(self, r):
'\n The ``r``-th element of ``self``\n\n INPUT:\n\n - ``r`` -- an integer between ``0`` and ``n-1``,\n where ``n`` is the cardinality of ``self``.\n\n OUTPUT: the ``r``-th element of ``self``\n\n This implementation of :meth:`unrank` uses the method\n :meth:`list` (which is cached). Reciprocally, calling\n ``self.list()`` makes this method the default\n implementation of :meth:`unrank`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._unrank_from_list(1)\n 2\n '
lst = self.tuple()
try:
return lst[r]
except IndexError:
raise ValueError(('the value must be in the range from %s to %s' % (0, (len(lst) - 1))))
def tuple(self):
'\n Return a :class:`tuple`of the elements of ``self``.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.tuple()\n (1, 2, 3)\n sage: C.tuple() is C.tuple()\n True\n '
try:
if (self._list is not None):
return self._tuple_from_list()
except AttributeError:
pass
if (self.list != self._list_default):
return tuple(self.list())
return self._tuple_from_iterator()
_tuple_default = tuple
def _list_from_iterator(self):
'\n Return a list of the elements of ``self`` after cached.\n\n It moreover overrides the following methods to use this cache:\n\n - ``self.__iter__()``\n - ``self.cardinality()``\n - ``self.unrank()``\n\n .. SEEALSO:: :meth:`_cardinality_from_list`,\n :meth:`_iterator_from_list`, and :meth:`_unrank_from_list`\n\n .. WARNING::\n\n The overriding of ``self.__iter__`` to use the cache\n is ignored upon calls such as ``for x in C:`` or\n ``list(C)`` (which essentially ruins its purpose).\n Indeed, Python looks up the ``__iter__`` method\n directly in the class of ``C``, bypassing ``C``\'s\n dictionary (see the Python reference manual,\n `Special method lookup for new-style classes <http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes>`_)\n\n Let\'s take an example::\n\n sage: class Example(Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category = FiniteEnumeratedSets())\n ....: def __iter__(self):\n ....: print("hello!")\n ....: for x in [1,2,3]: yield x\n sage: C = Example()\n sage: list(C)\n hello!\n ...\n [1, 2, 3]\n sage: list(C)\n hello!\n ...\n [1, 2, 3]\n\n Note that ``hello!`` actually gets printed more than once in\n the calls to ``list(C)``. That\'s because of the\n implicit calls to :meth:`__len__`, which also relies\n on :meth:`__iter__`. Let\'s call :meth:`list`::\n\n sage: C.list()\n hello!\n [1, 2, 3]\n sage: C.list()\n [1, 2, 3]\n\n Now we would want the original iterator of ``C`` not\n to be called anymore, but that\'s not the case::\n\n sage: list(C)\n hello!\n [1, 2, 3]\n\n TESTS:\n\n To test if the caching and overriding works, we need a\n fresh finite enumerated set example, because the caching\n mechanism has already been triggered::\n\n sage: from sage.categories.examples.finite_enumerated_sets import Example\n sage: class FreshExample(Example): pass\n sage: C = FreshExample(); C.rename("FreshExample")\n sage: C.list\n <bound method EnumeratedSets.ParentMethods.list of FreshExample>\n sage: C.unrank\n <bound method EnumeratedSets.ParentMethods._unrank_from_iterator of FreshExample>\n sage: C.cardinality\n <bound method FiniteEnumeratedSets.ParentMethods._cardinality_from_iterator of FreshExample>\n sage: l1 = C.list(); l1\n [1, 2, 3]\n sage: C.list\n <bound method EnumeratedSets.ParentMethods.list of FreshExample>\n sage: C.unrank\n <bound method FiniteEnumeratedSets.ParentMethods._unrank_from_list of FreshExample>\n sage: C.cardinality\n <bound method FiniteEnumeratedSets.ParentMethods._cardinality_from_list of FreshExample>\n sage: C.__iter__\n <bound method EnumeratedSets.ParentMethods._iterator_from_list of FreshExample>\n\n We finally check that nothing breaks before and after\n calling explicitly the method ``.list()``::\n\n sage: class FreshExample(Example): pass\n sage: import __main__; __main__.FreshExample = FreshExample # Fake FreshExample being defined in a python module\n sage: C = FreshExample()\n sage: TestSuite(C).run()\n sage: C.list()\n [1, 2, 3]\n sage: TestSuite(C).run()\n '
try:
if (self._list is not None):
return list(self._list)
except AttributeError:
pass
result = tuple(self.__iter__())
try:
self._list = result
self.__iter__ = self._iterator_from_list
self.cardinality = self._cardinality_from_list
self.tuple = self._tuple_from_list
self.unrank = self._unrank_from_list
except AttributeError:
pass
return list(result)
def unrank_range(self, start=None, stop=None, step=None):
'\n Return the range of elements of ``self`` starting at ``start``,\n ending at ``stop``, and stepping by ``step``.\n\n See also ``unrank()``.\n\n EXAMPLES::\n\n sage: F = FiniteEnumeratedSet([1,2,3])\n sage: F.unrank_range(1)\n [2, 3]\n sage: F.unrank_range(stop=2)\n [1, 2]\n sage: F.unrank_range(stop=2, step=2)\n [1]\n sage: F.unrank_range(start=1, step=2)\n [2]\n sage: F.unrank_range(stop=-1)\n [1, 2]\n\n sage: F = FiniteEnumeratedSet([1,2,3,4])\n sage: F.unrank_range(stop=10)\n [1, 2, 3, 4]\n '
try:
return list(self._list[start:stop:step])
except AttributeError:
pass
card = self.cardinality()
try:
return list(self._list[start:stop:step])
except AttributeError:
pass
if ((start is None) and (stop is not None) and (stop >= 0) and (step is None)):
if (stop < card):
it = self.__iter__()
return [next(it) for j in range(stop)]
return self.list()
return list(self.tuple()[start:stop:step])
def iterator_range(self, start=None, stop=None, step=None):
'\n Iterate over the range of elements of ``self`` starting\n at ``start``, ending at ``stop``, and stepping by ``step``.\n\n .. SEEALSO::\n\n ``unrank()``, ``unrank_range()``\n\n EXAMPLES::\n\n sage: F = FiniteEnumeratedSet([1,2,3])\n sage: list(F.iterator_range(1))\n [2, 3]\n sage: list(F.iterator_range(stop=2))\n [1, 2]\n sage: list(F.iterator_range(stop=2, step=2))\n [1]\n sage: list(F.iterator_range(start=1, step=2))\n [2]\n sage: list(F.iterator_range(start=1, stop=2))\n [2]\n sage: list(F.iterator_range(start=0, stop=1))\n [1]\n sage: list(F.iterator_range(start=0, stop=3, step=2))\n [1, 3]\n sage: list(F.iterator_range(stop=-1))\n [1, 2]\n\n sage: F = FiniteEnumeratedSet([1,2,3,4])\n sage: list(F.iterator_range(start=1, stop=3))\n [2, 3]\n sage: list(F.iterator_range(stop=10))\n [1, 2, 3, 4]\n '
L = None
try:
L = self._list
except AttributeError:
pass
card = self.cardinality()
try:
L = self._list
except AttributeError:
pass
if ((L is None) and (start is None) and (stop is not None) and (stop >= 0) and (step is None)):
if (stop < card):
it = self.__iter__()
for j in range(stop):
(yield next(it))
return
(yield from self)
return
if (L is None):
L = self.tuple()
(yield from L[start:stop:step])
def _random_element_from_unrank(self):
'\n A random element in ``self``.\n\n ``self.random_element()`` returns a random element in\n ``self`` with uniform probability.\n\n This is the default implementation from the category\n ``EnumeratedSet()`` which uses the method ``unrank``.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: n = C.random_element()\n sage: n in C\n True\n\n sage: n = C._random_element_from_unrank()\n sage: n in C\n True\n\n TODO: implement _test_random which checks uniformness\n '
from sage.misc.prandom import randint
c = self.cardinality()
r = randint(0, (c - 1))
return self.unrank(r)
random_element = _random_element_from_unrank
@cached_method
def _last_from_iterator(self):
'\n The last element of ``self``.\n\n ``self.last()`` returns the last element of ``self``.\n\n This is the default (brute force) implementation from the\n category ``FiniteEnumeratedSet()`` which can be used when\n the method ``__iter__`` is provided. Its complexity is\n `O(n)` where `n` is the size of ``self``.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.last()\n 3\n sage: C._last_from_iterator()\n 3\n '
for i in self:
pass
return i
last = _last_from_iterator
def _last_from_unrank(self):
'\n The last element of ``self``.\n\n ``self.last()`` returns the last element of ``self``\n\n This is a generic implementation from the category\n ``FiniteEnumeratedSet()`` which can be used when the\n method ``unrank`` is provided.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._last_from_unrank()\n 3\n '
return self.unrank((self.cardinality() - 1))
def _test_enumerated_set_iter_cardinality(self, **options):
'\n Checks that the methods :meth:`.cardinality` and\n :meth:`.__iter__` are consistent. Also checks that\n :meth:`.cardinality` returns an ``Integer``.\n\n For efficiency reasons, those tests are not run if\n :meth:`.cardinality` is\n :meth:`._cardinality_from_iterator`, or if ``self`` is too\n big.\n\n .. SEEALSO:: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C._test_enumerated_set_iter_cardinality()\n\n Let us now break the class::\n\n sage: from sage.categories.examples.finite_enumerated_sets import Example\n sage: class CCls(Example):\n ....: def cardinality(self):\n ....: return 4\n sage: CC = CCls()\n sage: CC._test_enumerated_set_iter_cardinality()\n Traceback (most recent call last):\n ...\n AssertionError: 4 != 3\n '
tester = self._tester(**options)
if (self.cardinality != self._cardinality_from_iterator):
card = self.cardinality()
if (card <= tester._max_runs):
tester.assertEqual(card, self._cardinality_from_iterator())
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n A Cartesian product of finite enumerated sets is a finite\n enumerated set.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of finite enumerated sets]\n '
return [FiniteEnumeratedSets()]
class ParentMethods():
"\n TESTS:\n\n Ideally, these tests should be just after the declaration of the\n associated attributes. But doing this way, Sage will not consider\n them as a doctest.\n\n We check that Cartesian products of finite enumerated sets\n inherit various methods from `Sets.CartesianProducts`\n and not from :class:`EnumeratedSets.Finite`::\n\n sage: C = cartesian_product([Partitions(10), Permutations(20)]) # needs sage.combinat\n sage: C in EnumeratedSets().Finite() # needs sage.combinat\n True\n\n sage: C.random_element.__module__ # needs sage.combinat\n 'sage.categories.sets_cat'\n\n sage: C.cardinality.__module__ # needs sage.combinat\n 'sage.categories.sets_cat'\n\n sage: C.__iter__.__module__ # needs sage.combinat\n 'sage.categories.sets_cat'\n "
random_element = raw_getattr(Sets.CartesianProducts.ParentMethods, 'random_element')
cardinality = raw_getattr(Sets.CartesianProducts.ParentMethods, 'cardinality')
__iter__ = raw_getattr(Sets.CartesianProducts.ParentMethods, '__iter__')
def last(self):
'\n Return the last element\n\n EXAMPLES::\n\n sage: C = cartesian_product([Zmod(42), Partitions(10), # needs sage.combinat\n ....: IntegerRange(5)])\n sage: C.last() # needs sage.combinat\n (41, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 4)\n '
return self._cartesian_product_of_elements(tuple((c.last() for c in self.cartesian_factors())))
def rank(self, x):
"\n Return the rank of an element of this Cartesian product.\n\n The *rank* of ``x`` is its position in the\n enumeration. It is an integer between ``0`` and\n ``n-1`` where ``n`` is the cardinality of this set.\n\n .. SEEALSO::\n\n - :meth:`EnumeratedSets.ParentMethods.rank`\n - :meth:`unrank`\n\n EXAMPLES::\n\n sage: C = cartesian_product([GF(2), GF(11), GF(7)])\n sage: C.rank(C((1,2,5)))\n 96\n sage: C.rank(C((0,0,0)))\n 0\n\n sage: for c in C: print(C.rank(c))\n 0\n 1\n 2\n 3\n 4\n 5\n ...\n 150\n 151\n 152\n 153\n\n sage: # needs sage.combinat\n sage: F1 = FiniteEnumeratedSet('abcdefgh')\n sage: F2 = IntegerRange(250)\n sage: F3 = Partitions(20)\n sage: C = cartesian_product([F1, F2, F3])\n sage: c = C(('a', 86, [7,5,4,4]))\n sage: C.rank(c)\n 54213\n sage: C.unrank(54213)\n ('a', 86, [7, 5, 4, 4])\n "
from sage.rings.integer_ring import ZZ
x = self(x)
b = ZZ.one()
rank = ZZ.zero()
for (f, c) in zip(reversed(x.cartesian_factors()), reversed(self.cartesian_factors())):
rank += (b * c.rank(f))
b *= c.cardinality()
return rank
def unrank(self, i):
'\n Return the ``i``-th element of this Cartesian product.\n\n INPUT:\n\n - ``i`` -- integer between ``0`` and ``n-1`` where\n ``n`` is the cardinality of this set.\n\n .. SEEALSO::\n\n - :meth:`EnumeratedSets.ParentMethods.unrank`\n - :meth:`rank`\n\n EXAMPLES::\n\n sage: C = cartesian_product([GF(3), GF(11), GF(7), GF(5)])\n sage: c = C.unrank(123); c\n (0, 3, 3, 3)\n sage: C.rank(c)\n 123\n\n sage: c = C.unrank(857); c\n (2, 2, 3, 2)\n sage: C.rank(c)\n 857\n\n sage: C.unrank(2500)\n Traceback (most recent call last):\n ...\n IndexError: index i (=2) is greater than the cardinality\n '
from sage.rings.integer_ring import ZZ
i = ZZ(i)
if (i < 0):
raise IndexError('i (={}) must be a non-negative integer')
elt = []
for c in reversed(self.cartesian_factors()):
card = c.cardinality()
elt.insert(0, c.unrank((i % card)))
i //= card
if i:
raise IndexError('index i (={}) is greater than the cardinality'.format(i))
return self._cartesian_product_of_elements(elt)
class IsomorphicObjects(IsomorphicObjectsCategory):
def example(self):
'\n Returns an example of isomorphic object of a finite\n enumerated set, as per :meth:`Category.example\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: FiniteEnumeratedSets().IsomorphicObjects().example()\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n '
from sage.categories.examples.finite_enumerated_sets import IsomorphicObjectOfFiniteEnumeratedSet
return IsomorphicObjectOfFiniteEnumeratedSet()
class ParentMethods():
def cardinality(self):
'\n Returns the cardinality of ``self`` which is the same\n as that of the ambient set ``self`` is isomorphic to.\n\n EXAMPLES::\n\n sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: A.cardinality()\n 3\n '
return self.ambient().cardinality()
def __iter__(self):
'\n Returns an iterator over ``self``, using the bijection\n with the ambient space.\n\n EXAMPLES::\n\n sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n sage: list(A) # indirect doctest\n [1, 4, 9]\n '
for x in self.ambient():
(yield self.retract(x))
|
class FiniteFields(CategoryWithAxiom):
'\n The category of finite fields.\n\n EXAMPLES::\n\n sage: K = FiniteFields(); K\n Category of finite enumerated fields\n\n A finite field is a finite monoid with the structure of a field;\n it is currently assumed to be enumerated::\n\n sage: K.super_categories()\n [Category of fields,\n Category of finite commutative rings,\n Category of finite enumerated sets]\n\n Some examples of membership testing and coercion::\n\n sage: FiniteField(17) in K\n True\n sage: RationalField() in K\n False\n sage: K(RationalField())\n Traceback (most recent call last):\n ...\n TypeError: unable to canonically associate a finite field to Rational Field\n\n TESTS::\n\n sage: K is Fields().Finite()\n True\n sage: TestSuite(K).run()\n '
def extra_super_categories(self):
'\n Any finite field is assumed to be endowed with an enumeration.\n\n TESTS::\n\n sage: Fields().Finite().extra_super_categories()\n [Category of finite enumerated sets]\n sage: FiniteFields().is_subcategory(FiniteEnumeratedSets())\n True\n '
return [EnumeratedSets().Finite()]
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: GF(4, "a") in FiniteFields() # needs sage.rings.finite_rings\n True\n sage: QQ in FiniteFields()\n False\n sage: IntegerModRing(4) in FiniteFields()\n False\n '
from sage.categories.fields import Fields
return ((x in Fields()) and x.is_finite())
def _call_(self, x):
'\n EXAMPLES::\n\n sage: FiniteFields()(GF(4, "a")) # needs sage.rings.finite_rings\n Finite Field in a of size 2^2\n sage: FiniteFields()(RationalField()) # indirect doctest\n Traceback (most recent call last):\n ...\n TypeError: unable to canonically associate a finite field to Rational Field\n '
raise TypeError(('unable to canonically associate a finite field to %s' % x))
class ParentMethods():
pass
class ElementMethods():
pass
|
class FiniteGroups(CategoryWithAxiom):
'\n The category of finite (multiplicative) groups.\n\n EXAMPLES::\n\n sage: C = FiniteGroups(); C\n Category of finite groups\n sage: C.super_categories()\n [Category of finite monoids, Category of groups]\n sage: C.example()\n General Linear Group of degree 2 over Finite Field of size 3\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
def example(self):
'\n Return an example of finite group, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: G = FiniteGroups().example(); G\n General Linear Group of degree 2 over Finite Field of size 3\n '
from sage.groups.matrix_gps.linear import GL
return GL(2, 3)
class ParentMethods():
def semigroup_generators(self):
'\n Returns semigroup generators for self.\n\n For finite groups, the group generators are also semigroup\n generators. Hence, this default implementation calls\n :meth:`~sage.categories.groups.Groups.ParentMethods.group_generators`.\n\n EXAMPLES::\n\n sage: A = AlternatingGroup(4)\n sage: A.semigroup_generators()\n Family ((2,3,4), (1,2,3))\n '
return self.group_generators()
def monoid_generators(self):
'\n Return monoid generators for ``self``.\n\n For finite groups, the group generators are also monoid\n generators. Hence, this default implementation calls\n :meth:`~sage.categories.groups.Groups.ParentMethods.group_generators`.\n\n EXAMPLES::\n\n sage: A = AlternatingGroup(4)\n sage: A.monoid_generators()\n Family ((2,3,4), (1,2,3))\n '
return self.group_generators()
def cardinality(self):
"\n Returns the cardinality of ``self``, as per\n :meth:`EnumeratedSets.ParentMethods.cardinality`.\n\n This default implementation calls :meth:`.order` if\n available, and otherwise resorts to\n :meth:`._cardinality_from_iterator`. This is for backward\n compatibility only. Finite groups should override this\n method instead of :meth:`.order`.\n\n EXAMPLES:\n\n We need to use a finite group which uses this default\n implementation of cardinality::\n\n sage: G = groups.misc.SemimonomialTransformation(GF(5), 3); G\n Semimonomial transformation group over Finite Field of size 5 of degree 3\n sage: G.cardinality.__module__\n 'sage.categories.finite_groups'\n sage: G.cardinality()\n 384\n "
try:
o = self.order
except AttributeError:
return self._cardinality_from_iterator()
else:
return o()
def some_elements(self):
'\n Return some elements of ``self``.\n\n EXAMPLES::\n\n sage: A = AlternatingGroup(4)\n sage: A.some_elements()\n Family ((2,3,4), (1,2,3))\n '
return self.group_generators()
def cayley_graph_disabled(self, connecting_set=None):
'\n\n AUTHORS:\n\n - Bobby Moretti (2007-08-10)\n\n - Robert Miller (2008-05-01): editing\n '
if (connecting_set is None):
connecting_set = self.group_generators()
else:
for g in connecting_set:
if (g not in self):
raise RuntimeError('each element of the connecting set must be in the group')
connecting_set = [self(g) for g in connecting_set]
from sage.graphs.digraph import DiGraph
arrows = {}
for x in self:
arrows[x] = {}
for g in connecting_set:
xg = (x * g)
if (not (xg == x)):
arrows[x][xg] = g
return DiGraph(arrows, implementation='networkx')
def conjugacy_classes(self):
'\n Return a list with all the conjugacy classes of the group.\n\n This will eventually be a fall-back method for groups not defined\n over GAP. Right now, it just raises a\n :class:`NotImplementedError`, until we include a non-GAP\n way of listing the conjugacy classes representatives.\n\n EXAMPLES::\n\n sage: from sage.groups.group import FiniteGroup\n sage: G = FiniteGroup()\n sage: G.conjugacy_classes()\n Traceback (most recent call last):\n ...\n NotImplementedError: Listing the conjugacy classes for group <sage.groups.group.FiniteGroup object at ...> is not implemented\n '
raise NotImplementedError(('Listing the conjugacy classes for group %s is not implemented' % self))
def conjugacy_classes_representatives(self):
'\n Return a list of the conjugacy classes representatives of the group.\n\n EXAMPLES::\n\n sage: G = SymmetricGroup(3)\n sage: G.conjugacy_classes_representatives()\n [(), (1,2), (1,2,3)]\n '
return [C.representative() for C in self.conjugacy_classes()]
class ElementMethods():
pass
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
"\n Implement Maschke's theorem.\n\n In characteristic 0 all finite group algebras are semisimple.\n\n EXAMPLES::\n\n sage: FiniteGroups().Algebras(QQ).is_subcategory(Algebras(QQ).Semisimple())\n True\n sage: FiniteGroups().Algebras(FiniteField(7)).is_subcategory(Algebras(FiniteField(7)).Semisimple())\n False\n sage: FiniteGroups().Algebras(ZZ).is_subcategory(Algebras(ZZ).Semisimple())\n False\n sage: FiniteGroups().Algebras(Fields()).is_subcategory(Algebras(Fields()).Semisimple())\n False\n\n sage: Cat = CommutativeAdditiveGroups().Finite()\n sage: Cat.Algebras(QQ).is_subcategory(Algebras(QQ).Semisimple())\n True\n sage: Cat.Algebras(GF(7)).is_subcategory(Algebras(GF(7)).Semisimple())\n False\n sage: Cat.Algebras(ZZ).is_subcategory(Algebras(ZZ).Semisimple())\n False\n sage: Cat.Algebras(Fields()).is_subcategory(Algebras(Fields()).Semisimple())\n False\n "
from sage.categories.fields import Fields
K = self.base_ring()
if ((K in Fields()) and (K.characteristic() == 0)):
from sage.categories.algebras import Algebras
return [Algebras(self.base_ring()).Semisimple()]
else:
return []
class ParentMethods():
def __init_extra__(self):
"\n Implement Maschke's theorem.\n\n EXAMPLES::\n\n sage: G = groups.permutation.Dihedral(8)\n sage: A = G.algebra(GF(5))\n sage: A in Algebras.Semisimple\n True\n sage: A = G.algebra(Zmod(4))\n sage: A in Algebras.Semisimple\n False\n\n sage: G = groups.misc.AdditiveCyclic(4)\n sage: Cat = CommutativeAdditiveGroups().Finite()\n sage: A = G.algebra(GF(5), category=Cat)\n sage: A in Algebras.Semisimple\n True\n sage: A = G.algebra(GF(2), category=Cat)\n sage: A in Algebras.Semisimple\n False\n "
base_ring = self.base_ring()
group = self.group()
from sage.categories.fields import Fields
if ((base_ring in Fields) and (base_ring.characteristic() > 0) and hasattr(group, 'cardinality') and ((group.cardinality() % base_ring.characteristic()) != 0)):
self._refine_category_(self.category().Semisimple())
|
class FiniteLatticePosets(CategoryWithAxiom):
'\n The category of finite lattices, i.e. finite partially ordered\n sets which are also lattices.\n\n EXAMPLES::\n\n sage: FiniteLatticePosets()\n Category of finite lattice posets\n sage: FiniteLatticePosets().super_categories()\n [Category of lattice posets, Category of finite posets]\n sage: FiniteLatticePosets().example()\n NotImplemented\n\n .. SEEALSO::\n\n :class:`FinitePosets`, :class:`LatticePosets`, :class:`~sage.combinat.posets.lattices.FiniteLatticePoset`\n\n TESTS::\n\n sage: C = FiniteLatticePosets()\n sage: C is FiniteLatticePosets().Finite()\n True\n sage: TestSuite(C).run()\n\n '
class ParentMethods():
def join_irreducibles(self):
'\n Return the join-irreducible elements of this finite lattice.\n\n A *join-irreducible element* of ``self`` is an element\n `x` that is not minimal and that can not be written as\n the join of two elements different from `x`.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0:[1,2],1:[3],2:[3,4],3:[5],4:[5]}) # needs sage.graphs sage.modules\n sage: L.join_irreducibles() # needs sage.graphs sage.modules\n [1, 2, 4]\n\n .. SEEALSO::\n\n - Dual function: :meth:`meet_irreducibles`\n - Other: :meth:`~sage.combinat.posets.lattices.FiniteLatticePoset.double_irreducibles`,\n :meth:`join_irreducibles_poset`\n '
return [x for x in self if (len(self.lower_covers(x)) == 1)]
def join_irreducibles_poset(self):
'\n Return the poset of join-irreducible elements of this finite lattice.\n\n A *join-irreducible element* of ``self`` is an element `x`\n that is not minimal and can not be written as the join of two\n elements different from `x`.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0:[1,2,3],1:[4],2:[4],3:[4]}) # needs sage.graphs sage.modules\n sage: L.join_irreducibles_poset() # needs sage.graphs sage.modules\n Finite poset containing 3 elements\n\n .. SEEALSO::\n\n - Dual function: :meth:`meet_irreducibles_poset`\n - Other: :meth:`join_irreducibles`\n '
return self.subposet(self.join_irreducibles())
def meet_irreducibles(self):
'\n Return the meet-irreducible elements of this finite lattice.\n\n A *meet-irreducible element* of ``self`` is an element\n `x` that is not maximal and that can not be written as\n the meet of two elements different from `x`.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0:[1,2],1:[3],2:[3,4],3:[5],4:[5]}) # needs sage.graphs sage.modules\n sage: L.meet_irreducibles() # needs sage.graphs sage.modules\n [1, 3, 4]\n\n .. SEEALSO::\n\n - Dual function: :meth:`join_irreducibles`\n - Other: :meth:`~sage.combinat.posets.lattices.FiniteLatticePoset.double_irreducibles`,\n :meth:`meet_irreducibles_poset`\n '
return [x for x in self if (len(self.upper_covers(x)) == 1)]
def meet_irreducibles_poset(self):
'\n Return the poset of join-irreducible elements of this finite lattice.\n\n A *meet-irreducible element* of ``self`` is an element `x`\n that is not maximal and can not be written as the meet of two\n elements different from `x`.\n\n EXAMPLES::\n\n sage: L = LatticePoset({0:[1,2,3],1:[4],2:[4],3:[4]}) # needs sage.graphs sage.modules\n sage: L.join_irreducibles_poset() # needs sage.graphs sage.modules\n Finite poset containing 3 elements\n\n .. SEEALSO::\n\n - Dual function: :meth:`join_irreducibles_poset`\n - Other: :meth:`meet_irreducibles`\n '
return self.subposet(self.meet_irreducibles())
def irreducibles_poset(self):
'\n Return the poset of meet- or join-irreducibles of the lattice.\n\n A *join-irreducible* element of a lattice is an element with\n exactly one lower cover. Dually a *meet-irreducible* element\n has exactly one upper cover.\n\n This is the smallest poset with completion by cuts being\n isomorphic to the lattice. As a special case this returns\n one-element poset from one-element lattice.\n\n .. SEEALSO::\n\n :meth:`~sage.combinat.posets.posets.FinitePoset.completion_by_cuts`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.graphs sage.modules\n sage: L = LatticePoset({1: [2, 3, 4], 2: [5, 6], 3: [5],\n ....: 4: [6], 5: [9, 7], 6: [9, 8], 7: [10],\n ....: 8: [10], 9: [10], 10: [11]})\n sage: L_ = L.irreducibles_poset()\n sage: sorted(L_)\n [2, 3, 4, 7, 8, 9, 10, 11]\n sage: L_.completion_by_cuts().is_isomorphic(L)\n True\n\n TESTS::\n\n sage: LatticePoset().irreducibles_poset() # needs sage.graphs\n Finite poset containing 0 elements\n sage: posets.ChainPoset(1).irreducibles_poset() # needs sage.graphs\n Finite poset containing 1 elements\n '
if (self.cardinality() == 1):
from sage.combinat.posets.posets import Poset
return Poset({self[0]: []})
return self.subposet((self.join_irreducibles() + self.meet_irreducibles()))
def is_lattice_morphism(self, f, codomain):
'\n Return whether ``f`` is a morphism of posets from ``self``\n to ``codomain``.\n\n A map `f : P \\to Q` is a poset morphism if\n\n .. MATH::\n\n x \\leq y \\Rightarrow f(x) \\leq f(y)\n\n for all `x,y \\in P`.\n\n INPUT:\n\n - ``f`` -- a function from ``self`` to ``codomain``\n - ``codomain`` -- a lattice\n\n EXAMPLES:\n\n We build the boolean lattice of `\\{2,2,3\\}` and the\n lattice of divisors of `60`, and check that the map\n `b \\mapsto 5 \\prod_{x\\in b} x` is a morphism of lattices::\n\n sage: D = LatticePoset((divisors(60), attrcall("divides"))) # needs sage.graphs sage.modules\n sage: B = LatticePoset((Subsets([2,2,3]), attrcall("issubset"))) # needs sage.graphs sage.modules\n sage: def f(b): return D(5*prod(b))\n sage: B.is_lattice_morphism(f, D) # needs sage.graphs sage.modules\n True\n\n We construct the boolean lattice `B_2`::\n\n sage: B = posets.BooleanLattice(2) # needs sage.graphs\n sage: B.cover_relations() # needs sage.graphs\n [[0, 1], [0, 2], [1, 3], [2, 3]]\n\n And the same lattice with new top and bottom elements\n numbered respectively `-1` and `3`::\n\n sage: G = DiGraph({-1:[0], 0:[1,2], 1:[3], 2:[3], 3:[4]}) # needs sage.graphs\n sage: L = LatticePoset(G) # needs sage.graphs sage.modules\n sage: L.cover_relations() # needs sage.graphs sage.modules\n [[-1, 0], [0, 1], [0, 2], [1, 3], [2, 3], [3, 4]]\n\n sage: f = {B(0): L(0), B(1): L(1), B(2): L(2), B(3): L(3)}.__getitem__ # needs sage.graphs sage.modules\n sage: B.is_lattice_morphism(f, L) # needs sage.graphs sage.modules\n True\n\n sage: f = {B(0): L(-1),B(1): L(1), B(2): L(2), B(3): L(3)}.__getitem__ # needs sage.graphs sage.modules\n sage: B.is_lattice_morphism(f, L) # needs sage.graphs sage.modules\n False\n\n sage: f = {B(0): L(0), B(1): L(1), B(2): L(2), B(3): L(4)}.__getitem__ # needs sage.graphs sage.modules\n sage: B.is_lattice_morphism(f, L) # needs sage.graphs sage.modules\n False\n\n .. SEEALSO::\n\n :meth:`~sage.categories.finite_posets.FinitePosets.ParentMethods.is_poset_morphism`\n '
from sage.combinat.subset import Subsets
for (x, y) in Subsets(self, 2):
if (f(self.join(x, y)) != codomain.join(f(x), f(y))):
return False
if (f(self.meet(x, y)) != codomain.meet(f(x), f(y))):
return False
return True
|
class FiniteMonoids(CategoryWithAxiom):
'\n The category of finite (multiplicative) :class:`monoids <Monoids>`.\n\n A finite monoid is a :class:`finite sets <FiniteSets>` endowed\n with an associative unital binary operation `*`.\n\n EXAMPLES::\n\n sage: FiniteMonoids()\n Category of finite monoids\n sage: FiniteMonoids().super_categories()\n [Category of monoids, Category of finite semigroups]\n\n TESTS::\n\n sage: TestSuite(FiniteMonoids()).run()\n '
class ParentMethods():
def nerve(self):
'\n The nerve (classifying space) of this monoid.\n\n OUTPUT:\n\n the nerve `BG` (if `G` denotes this monoid), as a\n simplicial set. The `k`-dimensional simplices of this\n object are indexed by products of `k` elements in the\n monoid:\n\n .. MATH::\n\n a_1 * a_2 * \\cdots * a_k\n\n The 0th face of this is obtained by deleting `a_1`, and\n the `k`-th face is obtained by deleting `a_k`. The other\n faces are obtained by multiplying elements: the 1st face\n is\n\n .. MATH::\n\n (a1 * a_2) * \\cdots * a_k\n\n and so on. See :wikipedia:`Nerve_(category_theory)`, which\n describes the construction of the nerve as a simplicial\n set.\n\n A simplex in this simplicial set will be degenerate if in\n the corresponding product of `k` elements, one of those\n elements is the identity. So we only need to keep track of\n the products of non-identity elements. Similarly, if a\n product `a_{i-1} a_i` is the identity element, then the\n corresponding face of the simplex will be a degenerate\n simplex.\n\n EXAMPLES:\n\n The nerve (classifying space) of the cyclic group of order\n 2 is infinite-dimensional real projective space. ::\n\n sage: Sigma2 = groups.permutation.Cyclic(2) # needs sage.groups\n sage: BSigma2 = Sigma2.nerve() # needs sage.groups\n sage: BSigma2.cohomology(4, base_ring=GF(2)) # needs sage.groups sage.modules\n Vector space of dimension 1 over Finite Field of size 2\n\n The `k`-simplices of the nerve are named after the chains\n of `k` non-unit elements to be multiplied. The group\n `\\Sigma_2` has two elements, written ``()`` (the identity\n element) and ``(1,2)`` in Sage. So the 1-cells and 2-cells\n in `B\\Sigma_2` are::\n\n sage: BSigma2.n_cells(1) # needs sage.groups\n [(1,2)]\n sage: BSigma2.n_cells(2) # needs sage.groups\n [(1,2) * (1,2)]\n\n Another construction of the group, with different names\n for its elements::\n\n sage: # needs sage.groups\n sage: C2 = groups.misc.MultiplicativeAbelian([2])\n sage: BC2 = C2.nerve()\n sage: BC2.n_cells(0)\n [1]\n sage: BC2.n_cells(1)\n [f]\n sage: BC2.n_cells(2)\n [f * f]\n\n With mod `p` coefficients, `B \\Sigma_p` should have its\n first nonvanishing homology group in dimension `p`::\n\n sage: Sigma3 = groups.permutation.Symmetric(3) # needs sage.groups\n sage: BSigma3 = Sigma3.nerve() # needs sage.groups\n sage: BSigma3.homology(range(4), base_ring=GF(3)) # needs sage.groups\n {0: Vector space of dimension 0 over Finite Field of size 3,\n 1: Vector space of dimension 0 over Finite Field of size 3,\n 2: Vector space of dimension 0 over Finite Field of size 3,\n 3: Vector space of dimension 1 over Finite Field of size 3}\n\n Note that we can construct the `n`-skeleton for\n `B\\Sigma_2` for relatively large values of `n`, while for\n `B\\Sigma_3`, the complexes get large pretty quickly::\n\n sage: # needs sage.groups\n sage: Sigma2.nerve().n_skeleton(14)\n Simplicial set with 15 non-degenerate simplices\n sage: BSigma3 = Sigma3.nerve()\n sage: BSigma3.n_skeleton(3)\n Simplicial set with 156 non-degenerate simplices\n sage: BSigma3.n_skeleton(4)\n Simplicial set with 781 non-degenerate simplices\n\n Finally, note that the classifying space of the order `p`\n cyclic group is smaller than that of the symmetric group\n on `p` letters, and its first homology group appears\n earlier::\n\n sage: # needs sage.groups\n sage: C3 = groups.misc.MultiplicativeAbelian([3])\n sage: list(C3)\n [1, f, f^2]\n sage: BC3 = C3.nerve()\n sage: BC3.n_cells(1)\n [f, f^2]\n sage: BC3.n_cells(2)\n [f * f, f * f^2, f^2 * f, f^2 * f^2]\n sage: len(BSigma3.n_cells(2))\n 25\n sage: len(BC3.n_cells(3))\n 8\n sage: len(BSigma3.n_cells(3))\n 125\n sage: BC3.homology(range(4), base_ring=GF(3))\n {0: Vector space of dimension 0 over Finite Field of size 3,\n 1: Vector space of dimension 1 over Finite Field of size 3,\n 2: Vector space of dimension 1 over Finite Field of size 3,\n 3: Vector space of dimension 1 over Finite Field of size 3}\n sage: BC5 = groups.permutation.Cyclic(5).nerve()\n sage: BC5.homology(range(4), base_ring=GF(5))\n {0: Vector space of dimension 0 over Finite Field of size 5,\n 1: Vector space of dimension 1 over Finite Field of size 5,\n 2: Vector space of dimension 1 over Finite Field of size 5,\n 3: Vector space of dimension 1 over Finite Field of size 5}\n '
from sage.topology.simplicial_set_examples import Nerve
return Nerve(self)
def rhodes_radical_congruence(self, base_ring=None):
'\n Return the Rhodes radical congruence of the semigroup.\n\n The Rhodes radical congruence is the congruence induced on S by the\n map `S \\rightarrow kS \\rightarrow kS / rad kS` with k a field.\n\n INPUT:\n\n - ``base_ring`` (default: `\\QQ`) a field\n\n OUTPUT:\n\n - A list of couples (m, n) with `m \\neq n` in the lexicographic\n order for the enumeration of the monoid ``self``.\n\n EXAMPLES::\n\n sage: M = Monoids().Finite().example()\n sage: M.rhodes_radical_congruence() # needs sage.modules\n [(0, 6), (2, 8), (4, 10)]\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: from sage.monoids.hecke_monoid import HeckeMonoid\n sage: H3 = HeckeMonoid(SymmetricGroup(3))\n sage: H3.repr_element_method(style="reduced")\n sage: H3.rhodes_radical_congruence()\n [([1, 2], [2, 1]), ([1, 2], [1, 2, 1]), ([2, 1], [1, 2, 1])]\n\n By Maschke\'s theorem, every group algebra over `\\QQ`\n is semisimple hence the Rhodes radical of a group must be trivial::\n\n sage: SymmetricGroup(3).rhodes_radical_congruence() # needs sage.groups sage.modules\n []\n sage: DihedralGroup(10).rhodes_radical_congruence() # needs sage.groups sage.modules\n []\n\n REFERENCES:\n\n - [Rho69]_\n '
from sage.rings.rational_field import QQ
if (base_ring is None):
base_ring = QQ
kS = self.algebra(base_ring)
kSrad = kS.radical()
res = []
for m in self:
for n in self:
if ((m == n) or ((n, m) in res)):
continue
try:
kSrad.retract((kS(m) - kS(n)))
except ValueError:
pass
else:
res.append((m, n))
return res
class ElementMethods():
def pseudo_order(self):
"\n Return the pair `[k, j]` with `k` minimal and `0\\leq j <k` such\n that ``self^k == self^j``.\n\n Note that `j` is uniquely determined.\n\n EXAMPLES::\n\n sage: M = FiniteMonoids().example(); M\n An example of a finite multiplicative monoid: the integers modulo 12\n\n sage: x = M(2)\n sage: [ x^i for i in range(7) ]\n [1, 2, 4, 8, 4, 8, 4]\n sage: x.pseudo_order()\n [4, 2]\n\n sage: x = M(3)\n sage: [ x^i for i in range(7) ]\n [1, 3, 9, 3, 9, 3, 9]\n sage: x.pseudo_order()\n [3, 1]\n\n sage: x = M(4)\n sage: [ x^i for i in range(7) ]\n [1, 4, 4, 4, 4, 4, 4]\n sage: x.pseudo_order()\n [2, 1]\n\n sage: x = M(5)\n sage: [ x^i for i in range(7) ]\n [1, 5, 1, 5, 1, 5, 1]\n sage: x.pseudo_order()\n [2, 0]\n\n .. TODO::\n\n more appropriate name? see, for example, Jean-Eric Pin's\n lecture notes on semigroups.\n "
self_powers = {self.parent().one(): 0}
k = 1
self_power_k = self
while (self_power_k not in self_powers):
self_powers[self_power_k] = k
k += 1
self_power_k = (self_power_k * self)
return [k, self_powers[self_power_k]]
|
class FinitePermutationGroups(CategoryWithAxiom):
'\n The category of finite permutation groups, i.e. groups concretely\n represented as groups of permutations acting on a finite set.\n\n It is currently assumed that any finite permutation group comes\n endowed with a distinguished finite set of generators (method\n ``group_generators``); this is the case for all the existing\n implementations in Sage.\n\n EXAMPLES::\n\n sage: C = PermutationGroups().Finite(); C\n Category of finite enumerated permutation groups\n sage: C.super_categories()\n [Category of permutation groups,\n Category of finite groups,\n Category of finite finitely generated semigroups]\n\n sage: C.example()\n Dihedral group of order 6 as a permutation group\n\n TESTS::\n\n sage: C is FinitePermutationGroups()\n True\n sage: TestSuite(C).run()\n\n sage: G = FinitePermutationGroups().example()\n sage: TestSuite(G).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_inverse() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_one() . . . pass\n running ._test_pickling() . . . pass\n running ._test_prod() . . . pass\n running ._test_some_elements() . . . pass\n '
def example(self):
'\n Returns an example of finite permutation group, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: G = FinitePermutationGroups().example(); G\n Dihedral group of order 6 as a permutation group\n '
from sage.groups.perm_gps.permgroup_named import DihedralGroup
return DihedralGroup(3)
def extra_super_categories(self):
'\n Any permutation group is assumed to be endowed with a finite set of generators.\n\n TESTS:\n\n sage: PermutationGroups().Finite().extra_super_categories()\n [Category of finitely generated magmas]\n '
return [Magmas().FinitelyGenerated()]
class ParentMethods():
def cycle_index(self, parent=None):
"\n Return the *cycle index* of ``self``.\n\n INPUT:\n\n - ``self`` - a permutation group `G`\n - ``parent`` -- a free module with basis indexed by partitions,\n or behave as such, with a ``term`` and ``sum`` method\n (default: the symmetric functions over the rational field in the `p` basis)\n\n The *cycle index* of a permutation group `G`\n (:wikipedia:`Cycle_index`) is a gadget counting the\n elements of `G` by cycle type, averaged over the group:\n\n .. MATH::\n\n P = \\frac{1}{|G|} \\sum_{g\\in G} p_{ \\operatorname{cycle\\ type}(g) }\n\n EXAMPLES:\n\n Among the permutations of the symmetric group `S_4`, there is\n the identity, 6 cycles of length 2, 3 products of two cycles\n of length 2, 8 cycles of length 3, and 6 cycles of length 4::\n\n sage: S4 = SymmetricGroup(4)\n sage: P = S4.cycle_index()\n sage: 24 * P\n p[1, 1, 1, 1] + 6*p[2, 1, 1] + 3*p[2, 2] + 8*p[3, 1] + 6*p[4]\n\n If `l = (l_1,\\dots,l_k)` is a partition, ``|G| P[l]`` is the number\n of elements of `G` with cycles of length `(p_1,\\dots,p_k)`::\n\n sage: 24 * P[ Partition([3,1]) ]\n 8\n\n The cycle index plays an important role in the enumeration of\n objects modulo the action of a group (Pólya enumeration), via\n the use of symmetric functions and plethysms. It is therefore\n encoded as a symmetric function, expressed in the powersum\n basis::\n\n sage: P.parent()\n Symmetric Functions over Rational Field in the powersum basis\n\n This symmetric function can have some nice properties; for\n example, for the symmetric group `S_n`, we get the complete\n symmetric function `h_n`::\n\n sage: S = SymmetricFunctions(QQ); h = S.h()\n sage: h( P )\n h[4]\n\n .. TODO::\n\n Add some simple examples of Pólya enumeration, once\n it will be easy to expand symmetric functions on any\n alphabet.\n\n Here are the cycle indices of some permutation groups::\n\n sage: 6 * CyclicPermutationGroup(6).cycle_index()\n p[1, 1, 1, 1, 1, 1] + p[2, 2, 2] + 2*p[3, 3] + 2*p[6]\n\n sage: 60 * AlternatingGroup(5).cycle_index()\n p[1, 1, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 24*p[5]\n\n sage: for G in TransitiveGroups(5): # long time\n ....: G.cardinality() * G.cycle_index()\n p[1, 1, 1, 1, 1] + 4*p[5]\n p[1, 1, 1, 1, 1] + 5*p[2, 2, 1] + 4*p[5]\n p[1, 1, 1, 1, 1] + 5*p[2, 2, 1] + 10*p[4, 1] + 4*p[5]\n p[1, 1, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 24*p[5]\n p[1, 1, 1, 1, 1] + 10*p[2, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 20*p[3, 2] + 30*p[4, 1] + 24*p[5]\n\n Permutation groups with arbitrary domains are supported\n (see :trac:`22765`)::\n\n sage: G = PermutationGroup([['b','c','a']], domain=['a','b','c'])\n sage: G.cycle_index()\n 1/3*p[1, 1, 1] + 2/3*p[3]\n\n One may specify another parent for the result::\n\n sage: F = CombinatorialFreeModule(QQ, Partitions())\n sage: P = CyclicPermutationGroup(6).cycle_index(parent = F)\n sage: 6 * P\n B[[1, 1, 1, 1, 1, 1]] + B[[2, 2, 2]] + 2*B[[3, 3]] + 2*B[[6]]\n sage: P.parent() is F\n True\n\n This parent should be a module with basis indexed by partitions::\n\n sage: CyclicPermutationGroup(6).cycle_index(parent = QQ)\n Traceback (most recent call last):\n ...\n ValueError: `parent` should be a module with basis indexed by partitions\n\n REFERENCES:\n\n - [Ke1991]_\n\n AUTHORS:\n\n - Nicolas Borie and Nicolas M. Thiéry\n\n TESTS::\n\n sage: P = PermutationGroup([]); P\n Permutation Group with generators [()]\n sage: P.cycle_index()\n p[1]\n sage: P = PermutationGroup([[(1)]]); P\n Permutation Group with generators [()]\n sage: P.cycle_index()\n p[1]\n "
from sage.categories.modules import Modules
if (parent is None):
from sage.rings.rational_field import QQ
from sage.combinat.sf.sf import SymmetricFunctions
parent = SymmetricFunctions(QQ).powersum()
elif (parent not in Modules.WithBasis):
raise ValueError('`parent` should be a module with basis indexed by partitions')
base_ring = parent.base_ring()
return (parent.sum_of_terms(([C.an_element().cycle_type(), base_ring(C.cardinality())] for C in self.conjugacy_classes())) / self.cardinality())
@cached_method
def profile_series(self, variable='z'):
"\n Return the (finite) generating series of the (finite) profile of the group.\n\n The profile of a permutation group G is the counting function that\n maps each nonnegative integer n onto the number of orbits of the\n action induced by G on the n-subsets of its domain.\n If f is the profile of G, f(n) is thus the number of orbits of\n n-subsets of G.\n\n INPUT:\n\n - ``variable`` -- a variable, or variable name as a string (default: `'z'`)\n\n OUTPUT:\n\n - A polynomial in ``variable`` with nonnegative integer coefficients.\n By default, a polynomial in z over ZZ.\n\n .. SEEALSO::\n\n - :meth:`profile`\n\n EXAMPLES::\n\n sage: C8 = CyclicPermutationGroup(8)\n sage: C8.profile_series()\n z^8 + z^7 + 4*z^6 + 7*z^5 + 10*z^4 + 7*z^3 + 4*z^2 + z + 1\n sage: D8 = DihedralGroup(8)\n sage: poly_D8 = D8.profile_series()\n sage: poly_D8\n z^8 + z^7 + 4*z^6 + 5*z^5 + 8*z^4 + 5*z^3 + 4*z^2 + z + 1\n sage: poly_D8.parent()\n Univariate Polynomial Ring in z over Rational Field\n sage: D8.profile_series(variable='y')\n y^8 + y^7 + 4*y^6 + 5*y^5 + 8*y^4 + 5*y^3 + 4*y^2 + y + 1\n sage: u = var('u') # needs sage.symbolic\n sage: D8.profile_series(u).parent() # needs sage.symbolic\n Symbolic Ring\n "
from sage.rings.integer_ring import ZZ
if isinstance(variable, str):
variable = ZZ[variable].gen()
cycle_poly = self.cycle_index()
return cycle_poly.expand(2).subs(x0=1, x1=variable)
profile_polynomial = profile_series
def profile(self, n, using_polya=True):
'\n Return the value in ``n`` of the profile of the group ``self``.\n\n Optional argument ``using_polya`` allows to change the default method.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n - ``using_polya`` (optional) -- a boolean: if ``True`` (default), the computation\n uses Pólya enumeration (and all values of the profile are cached, so this\n should be the method used in case several of them are needed);\n if ``False``, uses the GAP interface to compute the orbit.\n\n OUTPUT:\n\n - A nonnegative integer that is the number of orbits of ``n``-subsets\n under the action induced by ``self`` on the subsets of its domain\n (i.e. the value of the profile of ``self`` in ``n``)\n\n .. SEEALSO::\n\n - :meth:`profile_series`\n\n EXAMPLES::\n\n sage: C6 = CyclicPermutationGroup(6)\n sage: C6.profile(2)\n 3\n sage: C6.profile(3)\n 4\n sage: D8 = DihedralGroup(8)\n sage: D8.profile(4, using_polya=False)\n 8\n\n '
if using_polya:
return self.profile_polynomial()[n]
else:
from sage.libs.gap.libgap import libgap
subs_n = libgap.Combinations(list(self.domain()), n)
return len(libgap.Orbits(self, subs_n, libgap.OnSets))
class ElementMethods():
pass
|
class FinitePosets(CategoryWithAxiom):
'\n The category of finite posets i.e. finite sets with a partial\n order structure.\n\n EXAMPLES::\n\n sage: FinitePosets()\n Category of finite posets\n sage: FinitePosets().super_categories()\n [Category of posets, Category of finite sets]\n sage: FinitePosets().example()\n NotImplemented\n\n .. SEEALSO:: :class:`~sage.categories.posets.Posets`, :func:`Poset`\n\n TESTS::\n\n sage: C = FinitePosets()\n sage: C is Posets().Finite()\n True\n sage: TestSuite(C).run()\n\n '
class ParentMethods():
def is_lattice(self):
'\n Return whether the poset is a lattice.\n\n A poset is a lattice if all pairs of elements have\n both a least upper bound ("join") and a greatest lower bound\n ("meet") in the poset.\n\n EXAMPLES::\n\n sage: P = Poset([[1, 3, 2], [4], [4, 5, 6], [6], [7], [7], [7], []])\n sage: P.is_lattice()\n True\n\n sage: P = Poset([[1, 2], [3], [3], []])\n sage: P.is_lattice()\n True\n\n sage: P = Poset({0: [2, 3], 1: [2, 3]})\n sage: P.is_lattice()\n False\n\n sage: P = Poset({1: [2, 3, 4], 2: [5, 6], 3: [5, 7], 4: [6, 7], 5: [8, 9],\n ....: 6: [8, 10], 7: [9, 10], 8: [11], 9: [11], 10: [11]})\n sage: P.is_lattice()\n False\n\n TESTS::\n\n sage: P = Poset()\n sage: P.is_lattice()\n True\n\n .. SEEALSO::\n\n - Weaker properties: :meth:`~sage.combinat.posets.posets.FinitePoset.is_join_semilattice`,\n :meth:`~sage.combinat.posets.posets.FinitePoset.is_meet_semilattice`\n '
return ((self.cardinality() == 0) or (self.has_bottom() and self.is_join_semilattice()))
def is_self_dual(self):
'\n Return whether the poset is *self-dual*.\n\n A poset is self-dual if it is isomorphic to its dual poset.\n\n EXAMPLES::\n\n sage: P = Poset({1: [3, 4], 2: [3, 4]})\n sage: P.is_self_dual()\n True\n\n sage: P = Poset({1: [2, 3]})\n sage: P.is_self_dual()\n False\n\n TESTS::\n\n sage: P = Poset()\n sage: P.is_self_dual()\n True\n\n .. SEEALSO::\n\n - Stronger properties: :meth:`~sage.combinat.posets.lattices.FiniteLatticePoset.is_orthocomplemented` (for lattices)\n - Other: :meth:`~sage.combinat.posets.posets.FinitePoset.dual`\n '
if (sorted(self._hasse_diagram.in_degree()) != sorted(self._hasse_diagram.out_degree())):
return False
levels_orig = [len(x) for x in self._hasse_diagram.level_sets()]
dual_poset_hasse = self._hasse_diagram.reverse()
levels_dual = [len(x) for x in dual_poset_hasse.level_sets()]
if (levels_orig != levels_dual):
return False
return self._hasse_diagram.is_isomorphic(dual_poset_hasse)
def is_poset_isomorphism(self, f, codomain):
'\n Return whether `f` is an isomorphism of posets from\n ``self`` to ``codomain``.\n\n INPUT:\n\n - ``f`` -- a function from ``self`` to ``codomain``\n - ``codomain`` -- a poset\n\n EXAMPLES:\n\n We build the poset `D` of divisors of 30, and check that\n it is isomorphic to the boolean lattice `B` of the subsets\n of `\\{2,3,5\\}` ordered by inclusion, via the reverse\n function `f: B \\to D, b \\mapsto \\prod_{x\\in b} x`::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: B = Poset(([frozenset(s) for s in Subsets([2,3,5])], attrcall("issubset")))\n sage: def f(b): return D(prod(b))\n sage: B.is_poset_isomorphism(f, D)\n True\n\n On the other hand, `f` is not an isomorphism to the chain\n of divisors of 30, ordered by usual comparison::\n\n sage: P = Poset((divisors(30), operator.le))\n sage: def f(b): return P(prod(b))\n sage: B.is_poset_isomorphism(f, P)\n False\n\n A non surjective case::\n\n sage: B = Poset(([frozenset(s) for s in Subsets([2,3])], attrcall("issubset")))\n sage: def f(b): return D(prod(b))\n sage: B.is_poset_isomorphism(f, D)\n False\n\n A non injective case::\n\n sage: B = Poset(([frozenset(s) for s in Subsets([2,3,5,6])], attrcall("issubset")))\n sage: def f(b): return D(gcd(prod(b), 30))\n sage: B.is_poset_isomorphism(f, D)\n False\n\n .. note:: since ``D`` and ``B`` are not facade posets, ``f`` is\n responsible for the conversions between integers and subsets to\n elements of ``D`` and ``B`` and back.\n\n .. SEEALSO:: :meth:`FiniteLatticePosets.ParentMethods.is_lattice_morphism`\n '
image = {f(x) for x in self}
if (len(image) != self.cardinality()):
return False
if (len(image) != codomain.cardinality()):
return False
for x in self:
if ({f(y) for y in self.upper_covers(x)} != set(codomain.upper_covers(f(x)))):
return False
return True
def is_poset_morphism(self, f, codomain):
'\n Return whether `f` is a morphism of posets from ``self``\n to ``codomain``, that is\n\n .. MATH::\n\n x\\leq y \\Longrightarrow f(x) \\leq f(y)\n\n for all `x` and `y` in ``self``.\n\n INPUT:\n\n - ``f`` -- a function from ``self`` to ``codomain``\n - ``codomain`` -- a poset\n\n EXAMPLES:\n\n We build the boolean lattice of the subsets of\n `\\{2,3,5,6\\}` and the lattice of divisors of `30`, and\n check that the map `b \\mapsto \\gcd(\\prod_{x\\in b} x, 30)`\n is a morphism of posets::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: B = Poset(([frozenset(s) for s in Subsets([2,3,5,6])], attrcall("issubset")))\n sage: def f(b): return D(gcd(prod(b), 30))\n sage: B.is_poset_morphism(f, D)\n True\n\n .. note:: since ``D`` and ``B`` are not facade posets, ``f`` is responsible\n for the conversions between integers and subsets to elements of\n ``D`` and ``B`` and back.\n\n `f` is also a morphism of posets to the chain of divisors\n of 30, ordered by usual comparison::\n\n sage: P = Poset((divisors(30), operator.le))\n sage: def f(b): return P(gcd(prod(b), 30))\n sage: B.is_poset_morphism(f, P)\n True\n\n FIXME: should this be ``is_order_preserving_morphism``?\n\n .. SEEALSO:: :meth:`is_poset_isomorphism`\n\n TESTS:\n\n Base cases::\n\n sage: P = posets.ChainPoset(2)\n sage: Q = posets.AntichainPoset(2)\n sage: f = lambda x: 1-x\n sage: P.is_poset_morphism(f, P)\n False\n sage: P.is_poset_morphism(f, Q)\n False\n sage: Q.is_poset_morphism(f, Q)\n True\n sage: Q.is_poset_morphism(f, P)\n True\n\n sage: P = Poset(); P\n Finite poset containing 0 elements\n sage: P.is_poset_morphism(f, P)\n True\n\n '
for x in self:
for y in self.upper_covers(x):
if (not codomain.is_lequal(f(x), f(y))):
return False
return True
def order_ideal_generators(self, ideal, direction='down'):
'\n Return the antichain of (minimal) generators of the order\n ideal (resp. order filter) ``ideal``.\n\n INPUT:\n\n - ``ideal`` -- an order ideal `I` (resp. order filter)\n of ``self``, as a list (or iterable); this should be\n an order ideal if ``direction`` is set to ``\'down\'``,\n and an order filter if ``direction`` is set to\n ``\'up\'``.\n - ``direction`` -- ``\'up\'`` or ``\'down\'`` (default:\n ``\'down\'``).\n\n The antichain of (minimal) generators of an order ideal\n `I` in a poset `P` is the set of all minimal elements of\n `P`. In the case of an order filter, the definition is\n similar, but with "maximal" used instead of "minimal".\n\n EXAMPLES:\n\n We build the boolean lattice of all subsets of `\\{1,2,3\\}`\n ordered by inclusion, and compute an order ideal there::\n\n sage: P = Poset((Subsets([1,2,3]), attrcall("issubset")))\n sage: I = P.order_ideal([Set([1,2]), Set([2,3]), Set([1])])\n sage: sorted(sorted(p) for p in I)\n [[], [1], [1, 2], [2], [2, 3], [3]]\n\n Then, we retrieve the generators of this ideal::\n\n sage: gen = P.order_ideal_generators(I)\n sage: sorted(sorted(p) for p in gen)\n [[1, 2], [2, 3]]\n\n If ``direction`` is \'up\', then this instead computes\n the minimal generators for an order filter::\n\n sage: I = P.order_filter([Set([1,2]), Set([2,3]), Set([1])])\n sage: sorted(sorted(p) for p in I)\n [[1], [1, 2], [1, 2, 3], [1, 3], [2, 3]]\n sage: gen = P.order_ideal_generators(I, direction=\'up\')\n sage: sorted(sorted(p) for p in gen)\n [[1], [2, 3]]\n\n Complexity: `O(n+m)` where `n` is the cardinality of `I`,\n and `m` the number of upper covers of elements of `I`.\n '
if (direction == 'down'):
covers = self.upper_covers
else:
covers = self.lower_covers
ideal_as_set = set(ideal)
from sage.sets.set import Set
return Set((x for x in ideal if all(((y not in ideal_as_set) for y in covers(x)))))
def order_filter_generators(self, filter):
'\n Generators for an order filter\n\n INPUT:\n\n - ``filter`` -- an order filter of ``self``, as a list (or iterable)\n\n EXAMPLES::\n\n sage: P = Poset((Subsets([1,2,3]), attrcall("issubset")))\n sage: I = P.order_filter([Set([1,2]), Set([2,3]), Set([1])])\n sage: sorted(sorted(p) for p in I)\n [[1], [1, 2], [1, 2, 3], [1, 3], [2, 3]]\n sage: gen = P.order_filter_generators(I)\n sage: sorted(sorted(p) for p in gen)\n [[1], [2, 3]]\n\n .. SEEALSO:: :meth:`order_ideal_generators`\n '
return self.order_ideal_generators(filter, direction='up')
def order_ideal_complement_generators(self, antichain, direction='up'):
'\n Return the Panyushev complement of the antichain\n ``antichain``.\n\n Given an antichain `A` of a poset `P`, the Panyushev\n complement of `A` is defined to be the antichain consisting\n of the minimal elements of the order filter `B`, where `B`\n is the (set-theoretic) complement of the order ideal of\n `P` generated by `A`.\n\n Setting the optional keyword variable ``direction`` to\n ``\'down\'`` leads to the inverse Panyushev complement being\n computed instead of the Panyushev complement. The inverse\n Panyushev complement of an antichain `A` is the antichain\n whose Panyushev complement is `A`. It can be found as the\n antichain consisting of the maximal elements of the order\n ideal `C`, where `C` is the (set-theoretic) complement of\n the order filter of `P` generated by `A`.\n\n :meth:`panyushev_complement` is an alias for this method.\n\n Panyushev complementation is related (actually, isomorphic)\n to rowmotion (:meth:`rowmotion`).\n\n INPUT:\n\n - ``antichain`` -- an antichain of ``self``, as a list (or\n iterable), or, more generally, generators of an order ideal\n (resp. order filter)\n - ``direction`` -- \'up\' or \'down\' (default: \'up\')\n\n OUTPUT:\n\n - the generating antichain of the complement order filter\n (resp. order ideal) of the order ideal (resp. order filter)\n generated by the antichain ``antichain``\n\n EXAMPLES::\n\n sage: P = Poset( ( [1,2,3], [ [1,3], [2,3] ] ) )\n sage: P.order_ideal_complement_generators([1])\n {2}\n sage: P.order_ideal_complement_generators([3])\n set()\n sage: P.order_ideal_complement_generators([1,2])\n {3}\n sage: P.order_ideal_complement_generators([1,2,3])\n set()\n\n sage: P.order_ideal_complement_generators([1], direction="down")\n {2}\n sage: P.order_ideal_complement_generators([3], direction="down")\n {1, 2}\n sage: P.order_ideal_complement_generators([1,2], direction="down")\n set()\n sage: P.order_ideal_complement_generators([1,2,3], direction="down")\n set()\n\n .. WARNING::\n\n This is a brute force implementation, building the\n order ideal generated by the antichain, and searching\n for order filter generators of its complement\n '
if (direction == 'up'):
I = self.order_ideal(antichain)
else:
I = self.order_filter(antichain)
I_comp = set(self).difference(I)
return set(self.order_ideal_generators(I_comp, direction=direction))
panyushev_complement = order_ideal_complement_generators
def rowmotion(self, order_ideal):
'\n The image of the order ideal ``order_ideal`` under rowmotion\n in ``self``.\n\n Rowmotion on a finite poset `P` is an automorphism of the set\n `J(P)` of all order ideals of `P`. One way to define it is as\n follows: Given an order ideal `I \\in J(P)`, we let `F` be the\n set-theoretic complement of `I` in `P`. Furthermore we let\n `A` be the antichain consisting of all minimal elements of\n `F`. Then, the rowmotion of `I` is defined to be the order\n ideal of `P` generated by the antichain `A` (that is, the\n order ideal consisting of each element of `P` which has some\n element of `A` above it).\n\n Rowmotion is related (actually, isomorphic) to Panyushev\n complementation (:meth:`panyushev_complement`).\n\n INPUT:\n\n - ``order_ideal`` -- an order ideal of ``self``, as a set\n\n OUTPUT:\n\n - the image of ``order_ideal`` under rowmotion, as a set again\n\n EXAMPLES::\n\n sage: P = Poset( {1: [2, 3], 2: [], 3: [], 4: [8], 5: [], 6: [5], 7: [1, 4], 8: []} )\n sage: I = Set({2, 6, 1, 7})\n sage: P.rowmotion(I)\n {1, 3, 4, 5, 6, 7}\n\n sage: P = Poset( {} )\n sage: I = Set({})\n sage: P.rowmotion(I)\n {}\n '
result = order_ideal
for i in reversed(self.linear_extension()):
result = self.order_ideal_toggle(result, i)
return result
def birational_free_labelling(self, linear_extension=None, prefix='x', base_field=None, reduced=False, addvars=None, labels=None, min_label=None, max_label=None):
'\n Return the birational free labelling of ``self``.\n\n Let us hold back defining this, and introduce birational\n toggles and birational rowmotion first. These notions have\n been introduced in [EP2013]_ as generalizations of the notions\n of toggles (:meth:`~sage.categories.posets.Posets.ParentMethods.order_ideal_toggle`)\n and :meth:`rowmotion <rowmotion>` on order ideals of a finite poset. They\n have been studied further in [GR2013]_.\n\n Let `\\mathbf{K}` be a field, and `P` be a finite poset. Let\n `\\widehat{P}` denote the poset obtained from `P` by adding a\n new element `1` which is greater than all existing elements\n of `P`, and a new element `0` which is smaller than all\n existing elements of `P` and `1`. Now, a `\\mathbf{K}`-*labelling\n of* `P` will mean any function from `\\widehat{P}` to `\\mathbf{K}`.\n The image of an element `v` of `\\widehat{P}` under this labelling\n will be called the *label* of this labelling at `v`. The set\n of all `\\mathbf{K}`-labellings of `P` is clearly\n `\\mathbf{K}^{\\widehat{P}}`.\n\n For any `v \\in P`, we now define a rational map\n `T_v : \\mathbf{K}^{\\widehat{P}} \\dashrightarrow\n \\mathbf{K}^{\\widehat{P}}` as follows: For every `f \\in\n \\mathbf{K}^{\\widehat{P}}`, the image `T_v f` should send every\n element `u \\in \\widehat{P}` distinct from `v` to `f(u)` (so the\n labels at all `u \\neq v` don\'t change), while `v` is sent to\n\n .. MATH::\n\n \\frac{1}{f(v)} \\cdot\n \\frac{\\sum_{u \\lessdot v} f(u)}\n {\\sum_{u \\gtrdot v} \\frac{1}{f(u)}}\n\n (both sums are over all `u \\in \\widehat{P}` satisfying the\n respectively given conditions). Here, `\\lessdot` and `\\gtrdot`\n mean (respectively) "covered by" and "covers", interpreted with\n respect to the poset `\\widehat{P}`. This rational map `T_v`\n is an involution and is called the *(birational)* `v`-*toggle*; see\n :meth:`birational_toggle` for its implementation.\n\n Now, *birational rowmotion* is defined as the composition\n `T_{v_1} \\circ T_{v_2} \\circ \\cdots \\circ T_{v_n}`, where\n `(v_1, v_2, \\ldots, v_n)` is a linear extension of `P`\n (written as a linear ordering of the elements of `P`). This\n is a rational map\n `\\mathbf{K}^{\\widehat{P}} \\dashrightarrow \\mathbf{K}^{\\widehat{P}}`\n which does not depend on the choice of the linear extension;\n it is denoted by `R`. See :meth:`birational_rowmotion` for\n its implementation.\n\n The definitions of birational toggles and birational\n rowmotion extend to the case of `\\mathbf{K}` being any semifield\n rather than necessarily a field (although it becomes less\n clear what constitutes a rational map in this generality).\n The most useful case is that of the :class:`tropical semiring\n <sage.rings.semirings.tropical_semiring.TropicalSemiring>`,\n in which case birational rowmotion relates to classical\n constructions such as promotion of rectangular semistandard\n Young tableaux (page 5 of [EP2013b]_ and future work, via the\n related notion of birational *promotion*) and rowmotion on\n order ideals of the poset ([EP2013]_).\n\n The *birational free labelling* is a special labelling\n defined for every finite poset `P` and every linear extension\n `(v_1, v_2, \\ldots, v_n)` of `P`. It is given by sending\n every element `v_i` in `P` to `x_i`, sending the element `0`\n of `\\widehat{P}` to `a`, and sending the element `1` of\n `\\widehat{P}` to `b`, where the ground field `\\mathbf{K}` is the\n field of rational functions in `n+2` indeterminates\n `a, x_1, x_2, \\ldots, x_n, b` over `\\mathbb Q`.\n\n In Sage, a labelling `f` of a poset `P` is encoded as a\n `4`-tuple `(\\mathbf{K}, d, u, v)`, where `\\mathbf{K}` is the\n ground field of the labelling (i. e., its target), `d` is the\n dictionary containing the values of `f` at the elements of\n `P` (the keys being the respective elements of `P`), `u`\n is the label of `f` at `0`, and `v` is the label of `f` at\n `1`.\n\n .. WARNING::\n\n The dictionary `d` is labelled by the elements of `P`.\n If `P` is a poset with ``facade`` option set to\n ``False``, these might not be what they seem to be!\n (For instance, if\n ``P == Poset({1: [2, 3]}, facade=False)``, then the\n value of `d` at `1` has to be accessed by ``d[P(1)]``, not\n by ``d[1]``.)\n\n .. WARNING::\n\n Dictionaries are mutable. They do compare correctly,\n but are not hashable and need to be cloned to avoid\n spooky action at a distance. Be careful!\n\n INPUT:\n\n - ``linear_extension`` -- (default: the default linear\n extension of ``self``) a linear extension of ``self``\n (as a linear extension or as a list), or more generally\n a list of all elements of all elements of ``self`` each\n occurring exactly once\n\n - ``prefix`` -- (default: ``\'x\'``) the prefix to name\n the indeterminates corresponding to the elements of\n ``self`` in the labelling (so, setting it to\n ``\'frog\'`` will result in these indeterminates being\n called ``frog1, frog2, ..., frogn`` rather than\n ``x1, x2, ..., xn``).\n\n - ``base_field`` -- (default: ``QQ``) the base field to\n be used instead of `\\QQ` to define the rational\n function field over; this is not going to be the base\n field of the labelling, because the latter will have\n indeterminates adjoined!\n\n - ``reduced`` -- (default: ``False``) if set to\n ``True``, the result will be the *reduced* birational\n free labelling, which differs from the regular one by\n having `0` and `1` both sent to `1` instead of `a` and\n `b` (the indeterminates `a` and `b` then also won\'t\n appear in the ground field)\n\n - ``addvars`` -- (default: ``\'\'``) a string containing\n names of extra variables to be adjoined to the ground\n field (these don\'t have an effect on the labels)\n\n - ``labels`` -- (default: ``\'x\'``) Either a function\n that takes an element of the poset and returns a name\n for the indeterminate corresponding to that element,\n or a string containing a comma-separated list of\n indeterminates that will be assigned to elements in\n the order of ``linear_extension``. If the\n list contains more indeterminates than needed, the\n excess will be ignored. If it contains too few, then\n the needed indeterminates will be constructed from\n ``prefix``.\n\n - ``min_label`` -- (default: ``\'a\'``) a string to be\n used as the label for the element `0` of `\\widehat{P}`\n\n - ``max_label`` -- (default: ``\'b\'``) a string to be\n used as the label for the element `1` of `\\widehat{P}`\n\n OUTPUT:\n\n The birational free labelling of the poset ``self`` and the\n linear extension ``linear_extension``. Or, if ``reduced``\n is set to ``True``, the reduced birational free labelling.\n\n EXAMPLES:\n\n We construct the birational free labelling on a simple\n poset::\n\n sage: P = Poset({1: [2, 3]})\n sage: l = P.birational_free_labelling(); l\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(l[1].items())\n [(1, x1), (2, x2), (3, x3)]\n\n sage: l = P.birational_free_labelling(linear_extension=[1, 3, 2]); l\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(l[1].items())\n [(1, x1), (2, x3), (3, x2)]\n\n sage: l = P.birational_free_labelling(linear_extension=[1, 3, 2], reduced=True, addvars="spam, eggs"); l\n (Fraction Field of Multivariate Polynomial Ring in x1, x2, x3, spam, eggs over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(l[1].items())\n [(1, x1), (2, x3), (3, x2)]\n\n sage: l = P.birational_free_labelling(linear_extension=[1, 3, 2], prefix="wut", reduced=True, addvars="spam, eggs"); l\n (Fraction Field of Multivariate Polynomial Ring in wut1, wut2, wut3, spam, eggs over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(l[1].items())\n [(1, wut1), (2, wut3), (3, wut2)]\n\n sage: l = P.birational_free_labelling(linear_extension=[1, 3, 2], reduced=False, addvars="spam, eggs"); l\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b, spam, eggs over Rational Field,\n {...},\n a,\n b)\n sage: sorted(l[1].items())\n [(1, x1), (2, x3), (3, x2)]\n sage: l[1][2]\n x3\n\n Illustrating labelling with a function::\n\n sage: P = posets.ChainPoset(2).product(posets.ChainPoset(2))\n sage: l = P.birational_free_labelling(labels=lambda e : \'x_\' + str(e[0]) + str(e[1]))\n sage: sorted(l[1].items())\n [((0, 0), x_00), ((0, 1), x_01), ((1, 0), x_10), ((1, 1), x_11)]\n sage: l[2]\n a\n\n The same, but with ``min_label`` and ``max_label`` provided::\n\n sage: P = posets.ChainPoset(2).product(posets.ChainPoset(2))\n sage: l = P.birational_free_labelling(labels=lambda e : \'x_\' + str(e[0]) + str(e[1]), min_label="lambda", max_label="mu")\n sage: sorted(l[1].items())\n [((0, 0), x_00), ((0, 1), x_01), ((1, 0), x_10), ((1, 1), x_11)]\n sage: l[2]\n lambda\n sage: l[3]\n mu\n\n Illustrating labelling with a comma separated list of labels::\n\n sage: l = P.birational_free_labelling(labels=\'w,x,y,z\')\n sage: sorted(l[1].items())\n [((0, 0), w), ((0, 1), x), ((1, 0), y), ((1, 1), z)]\n sage: l = P.birational_free_labelling(labels=\'w,x,y,z,m\')\n sage: sorted(l[1].items())\n [((0, 0), w), ((0, 1), x), ((1, 0), y), ((1, 1), z)]\n sage: l = P.birational_free_labelling(labels=\'w\')\n sage: sorted(l[1].items())\n [((0, 0), w), ((0, 1), x1), ((1, 0), x2), ((1, 1), x3)]\n\n Illustrating the warning about facade::\n\n sage: P = Poset({1: [2, 3]}, facade=False)\n sage: l = P.birational_free_labelling(linear_extension=[1, 3, 2], reduced=False, addvars="spam, eggs"); l\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b, spam, eggs over Rational Field,\n {...},\n a,\n b)\n sage: l[1][2]\n Traceback (most recent call last):\n ...\n KeyError: 2\n sage: l[1][P(2)]\n x3\n\n Another poset::\n\n sage: P = posets.SSTPoset([2,1])\n sage: lext = sorted(P)\n sage: l = P.birational_free_labelling(linear_extension=lext, addvars="ohai")\n sage: l\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, x5, x6, x7, x8, b, ohai over Rational Field,\n {...},\n a,\n b)\n sage: sorted(l[1].items())\n [([[1, 1], [2]], x1), ([[1, 1], [3]], x2), ([[1, 2], [2]], x3), ([[1, 2], [3]], x4),\n ([[1, 3], [2]], x5), ([[1, 3], [3]], x6), ([[2, 2], [3]], x7), ([[2, 3], [3]], x8)]\n\n See :meth:`birational_rowmotion`, :meth:`birational_toggle` and\n :meth:`birational_toggles` for more substantial examples of what\n one can do with the birational free labelling.\n\n TESTS:\n\n The ``linear_extension`` keyword does not have to be given an\n actual linear extension::\n\n sage: P = posets.ChainPoset(2).product(posets.ChainPoset(3))\n sage: P\n Finite lattice containing 6 elements\n sage: lex = [(1,0),(0,0),(1,1),(0,1),(1,2),(0,2)]\n sage: l = P.birational_free_labelling(linear_extension=lex,\n ....: prefix="u", reduced=True)\n sage: l\n (Fraction Field of Multivariate Polynomial Ring in u1, u2, u3, u4, u5, u6 over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(l[1].items())\n [((0, 0), u2),\n ((0, 1), u4),\n ((0, 2), u6),\n ((1, 0), u1),\n ((1, 1), u3),\n ((1, 2), u5)]\n\n For comparison, the standard linear extension::\n\n sage: l = P.birational_free_labelling(prefix="u", reduced=True); l\n (Fraction Field of Multivariate Polynomial Ring in u1, u2, u3, u4, u5, u6 over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(l[1].items())\n [((0, 0), u1),\n ((0, 1), u2),\n ((0, 2), u3),\n ((1, 0), u4),\n ((1, 1), u5),\n ((1, 2), u6)]\n\n If you want your linear extension to be tested for being a\n linear extension, just call the ``linear_extension`` method\n on the poset::\n\n sage: lex = [(0,0),(0,1),(1,0),(1,1),(0,2),(1,2)]\n sage: l = P.birational_free_labelling(linear_extension=P.linear_extension(lex),\n ....: prefix="u", reduced=True)\n sage: l\n (Fraction Field of Multivariate Polynomial Ring in u1, u2, u3, u4, u5, u6 over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(l[1].items())\n [((0, 0), u1),\n ((0, 1), u2),\n ((0, 2), u5),\n ((1, 0), u3),\n ((1, 1), u4),\n ((1, 2), u6)]\n\n Nonstandard base field::\n\n sage: P = Poset({1: [3], 2: [3,4]})\n sage: lex = [1, 2, 4, 3]\n sage: l = P.birational_free_labelling(linear_extension=lex,\n ....: prefix="aaa",\n ....: base_field=Zmod(13))\n sage: l\n (Fraction Field of Multivariate Polynomial Ring in a, aaa1, aaa2, aaa3, aaa4, b over Ring of integers modulo 13,\n {...},\n a,\n b)\n sage: l[1][4]\n aaa3\n\n The empty poset::\n\n sage: P = Poset({})\n sage: P.birational_free_labelling(reduced=False, addvars="spam, eggs")\n (Fraction Field of Multivariate Polynomial Ring in a, b, spam, eggs over Rational Field,\n {},\n a,\n b)\n sage: P.birational_free_labelling(reduced=True, addvars="spam, eggs")\n (Fraction Field of Multivariate Polynomial Ring in spam, eggs over Rational Field,\n {},\n 1,\n 1)\n sage: P.birational_free_labelling(reduced=True)\n (Multivariate Polynomial Ring in no variables over Rational Field,\n {},\n 1,\n 1)\n sage: P.birational_free_labelling(prefix="zzz")\n (Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field,\n {},\n a,\n b)\n sage: P.birational_free_labelling(labels="x,y,z", min_label="spam", max_label="eggs")\n (Fraction Field of Multivariate Polynomial Ring in spam, eggs over Rational Field,\n {},\n spam,\n eggs)\n '
if (base_field is None):
from sage.rings.rational_field import QQ
base_field = QQ
if (linear_extension is None):
linear_extension = self.linear_extension()
n = self.cardinality()
label_list = []
if labels:
if callable(labels):
label_list = [labels(e) for e in linear_extension]
else:
label_list = labels.split(',')
if (len(label_list) > n):
label_list = label_list[:n]
elif (len(label_list) < n):
label_list += [(prefix + str(i)) for i in range(1, ((n + 1) - len(label_list)))]
else:
label_list = [(prefix + str(i)) for i in range(1, (n + 1))]
if (not reduced):
if (min_label is None):
min_label = 'a'
if (max_label is None):
max_label = 'b'
label_list = (([min_label] + label_list) + [max_label])
if addvars:
label_list += addvars.split(',')
varstring = ','.join(label_list)
varnum = len(label_list)
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
PR = PolynomialRing(base_field, varstring, varnum)
if reduced:
xs = tuple(PR.gens()[:n])
else:
xs = tuple(PR.gens()[1:(n + 1)])
if (not reduced):
a = PR.gens()[0]
b = PR.gens()[(n + 1)]
else:
a = PR.one()
b = PR.one()
FF = PR.fraction_field()
dct = {self(p): xs[i] for (i, p) in enumerate(linear_extension)}
return (FF, dct, a, b)
def birational_toggle(self, v, labelling):
'\n Return the result of applying the birational `v`-toggle `T_v`\n to the `\\mathbf{K}`-labelling ``labelling`` of the poset ``self``.\n\n See the documentation of :meth:`birational_free_labelling`\n for a definition of this toggle and of `\\mathbf{K}`-labellings as\n well as an explanation of how `\\mathbf{K}`-labellings are to be\n encoded to be understood by Sage. This implementation allows\n `\\mathbf{K}` to be a semifield, not just a field. The birational\n `v`-toggle is only a rational map, so an exception (most\n likely, :class:`ZeroDivisionError`) will be thrown if the\n denominator is zero.\n\n INPUT:\n\n - ``v`` -- an element of ``self`` (must have ``self`` as\n parent if ``self`` is a ``facade=False`` poset)\n\n - ``labelling`` -- a `\\mathbf{K}`-labelling of ``self`` in the\n sense as defined in the documentation of\n :meth:`birational_free_labelling`\n\n OUTPUT:\n\n The `\\mathbf{K}`-labelling `T_v f` of ``self``, where `f` is\n ``labelling``.\n\n EXAMPLES:\n\n Let us start with the birational free labelling of the\n "V"-poset (the three-element poset with Hasse diagram looking\n like a "V")::\n\n sage: V = Poset({1: [2, 3]})\n sage: s = V.birational_free_labelling(); s\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(s[1].items())\n [(1, x1), (2, x2), (3, x3)]\n\n The image of `s` under the `1`-toggle `T_1` is::\n\n sage: s1 = V.birational_toggle(1, s); s1\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(s1[1].items())\n [(1, a*x2*x3/(x1*x2 + x1*x3)), (2, x2), (3, x3)]\n\n Now let us apply the `2`-toggle `T_2` (to the old ``s``)::\n\n sage: s2 = V.birational_toggle(2, s); s2\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(s2[1].items())\n [(1, x1), (2, x1*b/x2), (3, x3)]\n\n On the other hand, we can also apply `T_2` to the image of `s`\n under `T_1`::\n\n sage: s12 = V.birational_toggle(2, s1); s12\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(s12[1].items())\n [(1, a*x2*x3/(x1*x2 + x1*x3)), (2, a*x3*b/(x1*x2 + x1*x3)), (3, x3)]\n\n Each toggle is an involution::\n\n sage: all( V.birational_toggle(i, V.birational_toggle(i, s)) == s\n ....: for i in V )\n True\n\n We can also start with a less generic labelling::\n\n sage: t = (QQ, {1: 3, 2: 6, 3: 7}, 2, 10)\n sage: t1 = V.birational_toggle(1, t); t1\n (Rational Field, {...}, 2, 10)\n sage: sorted(t1[1].items())\n [(1, 28/13), (2, 6), (3, 7)]\n sage: t13 = V.birational_toggle(3, t1); t13\n (Rational Field, {...}, 2, 10)\n sage: sorted(t13[1].items())\n [(1, 28/13), (2, 6), (3, 40/13)]\n\n However, labellings have to be sufficiently generic, lest\n denominators vanish::\n\n sage: t = (QQ, {1: 3, 2: 5, 3: -5}, 1, 15)\n sage: t1 = V.birational_toggle(1, t)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: rational division by zero\n\n We don\'t get into zero-division issues in the tropical\n semiring (unless the zero of the tropical semiring appears\n in the labelling)::\n\n sage: TT = TropicalSemiring(QQ)\n sage: t = (TT, {1: TT(2), 2: TT(4), 3: TT(1)}, TT(6), TT(0))\n sage: t1 = V.birational_toggle(1, t); t1\n (Tropical semiring over Rational Field, {...}, 6, 0)\n sage: sorted(t1[1].items())\n [(1, 8), (2, 4), (3, 1)]\n sage: t12 = V.birational_toggle(2, t1); t12\n (Tropical semiring over Rational Field, {...}, 6, 0)\n sage: sorted(t12[1].items())\n [(1, 8), (2, 4), (3, 1)]\n sage: t123 = V.birational_toggle(3, t12); t123\n (Tropical semiring over Rational Field, {...}, 6, 0)\n sage: sorted(t123[1].items())\n [(1, 8), (2, 4), (3, 7)]\n\n We turn to more interesting posets. Here is the `6`-element\n poset arising from the weak order on `S_3`::\n\n sage: P = posets.SymmetricGroupWeakOrderPoset(3)\n sage: sorted(list(P))\n [\'123\', \'132\', \'213\', \'231\', \'312\', \'321\']\n sage: t = (TT, {\'123\': TT(4), \'132\': TT(2), \'213\': TT(3), \'231\': TT(1), \'321\': TT(1), \'312\': TT(2)}, TT(7), TT(1))\n sage: t1 = P.birational_toggle(\'123\', t); t1\n (Tropical semiring over Rational Field, {...}, 7, 1)\n sage: sorted(t1[1].items())\n [(\'123\', 6), (\'132\', 2), (\'213\', 3), (\'231\', 1), (\'312\', 2), (\'321\', 1)]\n sage: t13 = P.birational_toggle(\'213\', t1); t13\n (Tropical semiring over Rational Field, {...}, 7, 1)\n sage: sorted(t13[1].items())\n [(\'123\', 6), (\'132\', 2), (\'213\', 4), (\'231\', 1), (\'312\', 2), (\'321\', 1)]\n\n Let us verify on this example some basic properties of\n toggles. First of all, again let us check that `T_v` is an\n involution for every `v`::\n\n sage: all( P.birational_toggle(v, P.birational_toggle(v, t)) == t\n ....: for v in P )\n True\n\n Furthermore, two toggles `T_v` and `T_w` commute unless\n one of `v` or `w` covers the other::\n\n sage: all( P.covers(v, w) or P.covers(w, v)\n ....: or P.birational_toggle(v, P.birational_toggle(w, t))\n ....: == P.birational_toggle(w, P.birational_toggle(v, t))\n ....: for v in P for w in P )\n True\n\n TESTS:\n\n Setting ``facade`` to ``False`` does not break\n ``birational_toggle``::\n\n sage: P = Poset({\'x\': [\'y\', \'w\'], \'y\': [\'z\'], \'w\': [\'z\']}, facade=False)\n sage: lex = [\'x\', \'y\', \'w\', \'z\']\n sage: t = P.birational_free_labelling(linear_extension=lex)\n sage: all( P.birational_toggle(v, P.birational_toggle(v, t)) == t\n ....: for v in P )\n True\n sage: t4 = P.birational_toggle(P(\'z\'), t); t4\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, b over Rational Field,\n {...},\n a,\n b)\n sage: t4[1][P(\'x\')]\n x1\n sage: t4[1][P(\'y\')]\n x2\n sage: t4[1][P(\'w\')]\n x3\n sage: t4[1][P(\'z\')]\n (x2*b + x3*b)/x4\n\n The one-element poset::\n\n sage: P = Poset({8: []})\n sage: t = P.birational_free_labelling()\n sage: t8 = P.birational_toggle(8, t); t8\n (Fraction Field of Multivariate Polynomial Ring in a, x1, b over Rational Field,\n {...},\n a,\n b)\n sage: t8[1][8]\n a*b/x1\n '
FF = labelling[0]
a = labelling[2]
b = labelling[3]
newdict = labelling[1].copy()
uppers = self.upper_covers(v)
if (len(uppers) == 0):
x = (FF.one() / b)
else:
x = FF.sum(((FF.one() / newdict[j]) for j in uppers))
x = (FF.one() / x)
lowers = self.lower_covers(v)
if (len(lowers) == 0):
y = a
else:
y = FF.sum((newdict[j] for j in lowers))
newdict[v] = ((x * y) / newdict[v])
return (FF, newdict, a, b)
def birational_toggles(self, vs, labelling):
"\n Return the result of applying a sequence of birational\n toggles (specified by ``vs``) to the `\\mathbf{K}`-labelling\n ``labelling`` of the poset ``self``.\n\n See the documentation of :meth:`birational_free_labelling`\n for a definition of birational toggles and `\\mathbf{K}`-labellings\n and for an explanation of how `\\mathbf{K}`-labellings are to be\n encoded to be understood by Sage. This implementation allows\n `\\mathbf{K}` to be a semifield, not just a field. The birational\n `v`-toggle is only a rational map, so an exception (most\n likely, :class:`ZeroDivisionError`) will be thrown if the\n denominator is zero.\n\n INPUT:\n\n - ``vs`` -- an iterable comprising elements of ``self``\n (which must have ``self`` as parent if ``self`` is a\n ``facade=False`` poset)\n\n - ``labelling`` -- a `\\mathbf{K}`-labelling of ``self`` in the\n sense as defined in the documentation of\n :meth:`birational_free_labelling`\n\n OUTPUT:\n\n The `\\mathbf{K}`-labelling `T_{v_n} T_{v_{n-1}} \\cdots T_{v_1} f`\n of ``self``, where `f` is ``labelling`` and\n `(v_1, v_2, \\ldots, v_n)` is ``vs`` (written as list).\n\n EXAMPLES::\n\n sage: P = posets.SymmetricGroupBruhatOrderPoset(3)\n sage: sorted(list(P))\n ['123', '132', '213', '231', '312', '321']\n sage: TT = TropicalSemiring(ZZ)\n sage: t = (TT, {'123': TT(4), '132': TT(2), '213': TT(3), '231': TT(1), '321': TT(1), '312': TT(2)}, TT(7), TT(1))\n sage: tA = P.birational_toggles(['123', '231', '312'], t); tA\n (Tropical semiring over Integer Ring, {...}, 7, 1)\n sage: sorted(tA[1].items())\n [('123', 6), ('132', 2), ('213', 3), ('231', 2), ('312', 1), ('321', 1)]\n sage: tAB = P.birational_toggles(['132', '213', '321'], tA); tAB\n (Tropical semiring over Integer Ring, {...}, 7, 1)\n sage: sorted(tAB[1].items())\n [('123', 6), ('132', 6), ('213', 5), ('231', 2), ('312', 1), ('321', 1)]\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [4]})\n sage: Qx = PolynomialRing(QQ, 'x').fraction_field()\n sage: x = Qx.gen()\n sage: t = (Qx, {1: 1, 2: x, 3: (x+1)/x, 4: x^2}, 1, 1)\n sage: t1 = P.birational_toggles((i for i in range(1, 5)), t); t1\n (Fraction Field of Univariate Polynomial Ring in x over Rational Field,\n {...},\n 1,\n 1)\n sage: sorted(t1[1].items())\n [(1, (x^2 + x)/(x^2 + x + 1)), (2, (x^3 + x^2)/(x^2 + x + 1)), (3, x^4/(x^2 + x + 1)), (4, 1)]\n sage: t2 = P.birational_toggles(reversed(range(1, 5)), t)\n sage: sorted(t2[1].items())\n [(1, 1/x^2), (2, (x^2 + x + 1)/x^4), (3, (x^2 + x + 1)/(x^3 + x^2)), (4, (x^2 + x + 1)/x^3)]\n\n Facade set to ``False`` works::\n\n sage: P = Poset({'x': ['y', 'w'], 'y': ['z'], 'w': ['z']}, facade=False)\n sage: lex = ['x', 'y', 'w', 'z']\n sage: t = P.birational_free_labelling(linear_extension=lex)\n sage: sorted(P.birational_toggles([P('x'), P('y')], t)[1].items())\n [(x, a*x2*x3/(x1*x2 + x1*x3)), (y, a*x3*x4/(x1*x2 + x1*x3)), (w, x3), (z, x4)]\n "
l = labelling
for v in vs:
l = self.birational_toggle(v, l)
return l
def birational_rowmotion(self, labelling):
'\n Return the result of applying birational rowmotion to the\n `\\mathbf{K}`-labelling ``labelling`` of the poset ``self``.\n\n See the documentation of :meth:`birational_free_labelling`\n for a definition of birational rowmotion and\n `\\mathbf{K}`-labellings and for an explanation of how\n `\\mathbf{K}`-labellings are to be encoded to be understood\n by Sage. This implementation allows `\\mathbf{K}` to be a\n semifield, not just a field. Birational rowmotion is only\n a rational map, so an exception (most likely,\n :class:`ZeroDivisionError`) will be thrown if the\n denominator is zero.\n\n INPUT:\n\n - ``labelling`` -- a `\\mathbf{K}`-labelling of ``self`` in the\n sense as defined in the documentation of\n :meth:`birational_free_labelling`\n\n OUTPUT:\n\n The image of the `\\mathbf{K}`-labelling `f` under birational\n rowmotion.\n\n EXAMPLES::\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [4]})\n sage: lex = [1, 2, 3, 4]\n sage: t = P.birational_free_labelling(linear_extension=lex); t\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(t[1].items())\n [(1, x1), (2, x2), (3, x3), (4, x4)]\n sage: t = P.birational_rowmotion(t); t\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, b over Rational Field,\n {...},\n a,\n b)\n sage: sorted(t[1].items())\n [(1, a*b/x4), (2, (x1*x2*b + x1*x3*b)/(x2*x4)),\n (3, (x1*x2*b + x1*x3*b)/(x3*x4)), (4, (x2*b + x3*b)/x4)]\n\n A result of [GR2013]_ states that applying birational rowmotion\n `n+m` times to a `\\mathbf{K}`-labelling `f` of the poset\n `[n] \\times [m]` gives back `f`. Let us check this::\n\n sage: def test_rectangle_periodicity(n, m, k):\n ....: P = posets.ChainPoset(n).product(posets.ChainPoset(m))\n ....: t0 = P.birational_free_labelling(P)\n ....: t = t0\n ....: for i in range(k):\n ....: t = P.birational_rowmotion(t)\n ....: return t == t0\n sage: test_rectangle_periodicity(2, 2, 4)\n True\n sage: test_rectangle_periodicity(2, 2, 2)\n False\n sage: test_rectangle_periodicity(2, 3, 5) # long time\n True\n\n While computations with the birational free labelling quickly\n run out of memory due to the complexity of the rational\n functions involved, it is computationally cheap to check\n properties of birational rowmotion on examples in the tropical\n semiring::\n\n sage: def test_rectangle_periodicity_tropical(n, m, k):\n ....: P = posets.ChainPoset(n).product(posets.ChainPoset(m))\n ....: TT = TropicalSemiring(ZZ)\n ....: t0 = (TT, {v: TT(randint(0, 99)) for v in P}, TT(0), TT(124))\n ....: t = t0\n ....: for i in range(k):\n ....: t = P.birational_rowmotion(t)\n ....: return t == t0\n sage: test_rectangle_periodicity_tropical(7, 6, 13)\n True\n\n Tropicalization is also what relates birational rowmotion to\n classical rowmotion on order ideals. In fact, if `T` denotes\n the :class:`tropical semiring\n <sage.rings.semirings.tropical_semiring.TropicalSemiring>` of\n `\\ZZ` and `P` is a finite poset, then we can define an embedding\n `\\phi` from the set `J(P)` of all order ideals of `P` into the\n set `T^{\\widehat{P}}` of all `T`-labellings of `P` by sending\n every `I \\in J(P)` to the indicator function of `I` extended by\n the value `1` at the element `0` and the value `0` at the\n element `1`. This map `\\phi` has the property that\n `R \\circ \\phi = \\phi \\circ r`, where `R` denotes birational\n rowmotion, and `r` denotes :meth:`classical rowmotion <rowmotion>`\n on `J(P)`. An example::\n\n sage: P = posets.IntegerPartitions(5)\n sage: TT = TropicalSemiring(ZZ)\n sage: def indicator_labelling(I):\n ....: # send order ideal `I` to a `T`-labelling of `P`.\n ....: dct = {v: TT(v in I) for v in P}\n ....: return (TT, dct, TT(1), TT(0))\n sage: all(indicator_labelling(P.rowmotion(I))\n ....: == P.birational_rowmotion(indicator_labelling(I))\n ....: for I in P.order_ideals_lattice(facade=True))\n True\n\n TESTS:\n\n Facade set to false works::\n\n sage: P = Poset({1: [2, 3], 2: [4], 3: [4]}, facade=False)\n sage: lex = [1, 2, 3, 4]\n sage: t = P.birational_free_labelling(linear_extension=lex); t\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, b over Rational Field,\n {...},\n a,\n b)\n sage: t = P.birational_rowmotion(t); t\n (Fraction Field of Multivariate Polynomial Ring in a, x1, x2, x3, x4, b over Rational Field,\n {...},\n a,\n b)\n sage: t[1][P(2)]\n (x1*x2*b + x1*x3*b)/(x2*x4)\n sage: t = P.birational_rowmotion(t)\n sage: t[1][P(2)]\n a*b/x3\n '
l = labelling
for v in reversed(self.linear_extension()):
l = self.birational_toggle(v, l)
return l
def panyushev_orbits(self, element_constructor=set):
'\n Return the Panyushev orbits of antichains in ``self``.\n\n The Panyushev orbit of an antichain is its orbit under\n Panyushev complementation (see\n :meth:`panyushev_complement`).\n\n INPUT:\n\n - ``element_constructor`` (defaults to ``set``) -- a type\n constructor (``set``, ``tuple``, ``list``, ``frozenset``,\n ``iter``, etc.) which is to be applied to the antichains\n before they are returned.\n\n OUTPUT:\n\n - the partition of the set of all antichains of ``self`` into\n orbits under Panyushev complementation. This is returned as\n a list of lists ``L`` such that for each ``L`` and ``i``,\n cyclically:\n ``self.order_ideal_complement_generators(L[i]) == L[i+1]``.\n The entries ``L[i]`` are sets by default, but depending on\n the optional keyword variable ``element_constructors``\n they can also be tuples, lists etc.\n\n EXAMPLES::\n\n sage: P = Poset( ( [1,2,3], [ [1,3], [2,3] ] ) )\n sage: orb = P.panyushev_orbits()\n sage: sorted(sorted(o) for o in orb)\n [[set(), {1, 2}, {3}], [{2}, {1}]]\n sage: orb = P.panyushev_orbits(element_constructor=list)\n sage: sorted(sorted(o) for o in orb)\n [[[], [1, 2], [3]], [[1], [2]]]\n sage: orb = P.panyushev_orbits(element_constructor=frozenset)\n sage: sorted(sorted(o) for o in orb)\n [[frozenset(), frozenset({1, 2}), frozenset({3})],\n [frozenset({2}), frozenset({1})]]\n sage: orb = P.panyushev_orbits(element_constructor=tuple)\n sage: sorted(sorted(o) for o in orb)\n [[(), (1, 2), (3,)], [(1,), (2,)]]\n sage: P = Poset( {} )\n sage: P.panyushev_orbits()\n [[set()]]\n '
AC = set(self.antichains(element_constructor=frozenset))
orbits = []
while AC:
A = AC.pop()
orbit = [A]
while True:
A = frozenset(self.order_ideal_complement_generators(A))
if (A not in AC):
break
orbit.append(A)
AC.remove(A)
orbits.append([element_constructor(elt) for elt in orbit])
return orbits
def rowmotion_orbits(self, element_constructor=set):
'\n Return the rowmotion orbits of order ideals in ``self``.\n\n The rowmotion orbit of an order ideal is its orbit under\n rowmotion (see :meth:`rowmotion`).\n\n INPUT:\n\n - ``element_constructor`` (defaults to ``set``) -- a type\n constructor (``set``, ``tuple``, ``list``, ``frozenset``,\n ``iter``, etc.) which is to be applied to the antichains\n before they are returned.\n\n OUTPUT:\n\n - the partition of the set of all order ideals of ``self``\n into orbits under rowmotion. This is returned as\n a list of lists ``L`` such that for each ``L`` and ``i``,\n cyclically: ``self.rowmotion(L[i]) == L[i+1]``.\n The entries ``L[i]`` are sets by default, but depending on\n the optional keyword variable ``element_constructors``\n they can also be tuples, lists etc.\n\n EXAMPLES::\n\n sage: P = Poset( {1: [2, 3], 2: [], 3: [], 4: [2]} )\n sage: sorted(len(o) for o in P.rowmotion_orbits())\n [3, 5]\n sage: orb = P.rowmotion_orbits(element_constructor=list)\n sage: sorted(sorted(e) for e in orb)\n [[[], [4, 1], [4, 1, 2, 3]], [[1], [1, 3], [4], [4, 1, 2], [4, 1, 3]]]\n sage: orb = P.rowmotion_orbits(element_constructor=tuple)\n sage: sorted(sorted(e) for e in orb)\n [[(), (4, 1), (4, 1, 2, 3)], [(1,), (1, 3), (4,), (4, 1, 2), (4, 1, 3)]]\n sage: P = Poset({})\n sage: P.rowmotion_orbits(element_constructor=tuple)\n [[()]]\n '
pan_orbits = self.panyushev_orbits(element_constructor=list)
return [[element_constructor(self.order_ideal(oideal)) for oideal in orbit] for orbit in pan_orbits]
def rowmotion_orbits_plots(self):
'\n Return plots of the rowmotion orbits of order ideals in ``self``.\n\n The rowmotion orbit of an order ideal is its orbit under\n rowmotion (see :meth:`rowmotion`).\n\n EXAMPLES::\n\n sage: P = Poset( {1: [2, 3], 2: [], 3: [], 4: [2]} )\n sage: P.rowmotion_orbits_plots()\n Graphics Array of size 2 x 5\n sage: P = Poset({})\n sage: P.rowmotion_orbits_plots()\n Graphics Array of size 1 x 1\n\n '
from sage.plot.plot import graphics_array
plot_of_orb_plots = []
max_orbit_size = 0
for orb in self.rowmotion_orbits():
orb_plots = []
if (len(orb) > max_orbit_size):
max_orbit_size = len(orb)
for oi in orb:
oiplot = self.order_ideal_plot(oi)
orb_plots.append(oiplot)
plot_of_orb_plots.append(orb_plots)
return graphics_array(plot_of_orb_plots, ncols=max_orbit_size)
def toggling_orbits(self, vs, element_constructor=set):
'\n Return the orbits of order ideals in ``self`` under the\n operation of toggling the vertices ``vs[0], vs[1], ...``\n in this order.\n\n See :meth:`~sage.categories.posets.Posets.ParentMethods.order_ideal_toggle` for a definition of toggling.\n\n .. WARNING::\n\n The orbits are those under the composition of toggles,\n *not* under the single toggles themselves. Thus, for\n example, if ``vs == [1,2]``, then the orbits have the\n form `(I, T_2 T_1 I, T_2 T_1 T_2 T_1 I, \\ldots)`\n (where `I` denotes an order ideal and `T_i` means\n toggling at `i`) rather than\n `(I, T_1 I, T_2 T_1 I, T_1 T_2 T_1 I, \\ldots)`.\n\n INPUT:\n\n - ``vs``: a list (or other iterable) of elements of ``self``\n (but since the output depends on the order, sets should\n not be used as ``vs``).\n\n OUTPUT:\n\n - a partition of the order ideals of ``self``, as a list of\n sets ``L`` such that for each ``L`` and ``i``, cyclically:\n ``self.order_ideal_toggles(L[i], vs) == L[i+1]``.\n\n EXAMPLES::\n\n sage: P = Poset( {1: [2, 4], 2: [], 3: [4], 4: []} )\n sage: sorted(len(o) for o in P.toggling_orbits([1, 2]))\n [2, 3, 3]\n sage: P = Poset( {1: [3], 2: [1, 4], 3: [], 4: [3]} )\n sage: sorted(len(o) for o in P.toggling_orbits((1, 2, 4, 3)))\n [3, 3]\n '
OI = set(self.order_ideals_lattice(facade=True))
orbits = []
while OI:
A = OI.pop()
orbit = [A]
while True:
A = self.order_ideal_toggles(A, vs)
if (A not in OI):
break
orbit.append(A)
OI.remove(A)
orbits.append([element_constructor(_) for _ in orbit])
return orbits
def toggling_orbits_plots(self, vs):
'\n Return plots of the orbits of order ideals in ``self`` under the\n operation of toggling the vertices ``vs[0], vs[1], ...``\n in this order.\n\n See :meth:`toggling_orbits` for more information.\n\n EXAMPLES::\n\n sage: P = Poset( {1: [2, 3], 2: [], 3: [], 4: [2]} )\n sage: P.toggling_orbits_plots([1,2,3,4])\n Graphics Array of size 2 x 5\n sage: P = Poset({})\n sage: P.toggling_orbits_plots([])\n Graphics Array of size 1 x 1\n\n '
from sage.plot.plot import graphics_array
plot_of_orb_plots = []
max_orbit_size = 0
for orb in self.toggling_orbits(vs):
orb_plots = []
if (len(orb) > max_orbit_size):
max_orbit_size = len(orb)
for oi in orb:
oiplot = self.order_ideal_plot(oi)
orb_plots.append(oiplot)
plot_of_orb_plots.append(orb_plots)
return graphics_array(plot_of_orb_plots, ncols=max_orbit_size)
def panyushev_orbit_iter(self, antichain, element_constructor=set, stop=True, check=True):
'\n Iterate over the Panyushev orbit of an antichain\n ``antichain`` of ``self``.\n\n The Panyushev orbit of an antichain is its orbit under\n Panyushev complementation (see\n :meth:`panyushev_complement`).\n\n INPUT:\n\n - ``antichain`` -- an antichain of ``self``, given as an\n iterable.\n\n - ``element_constructor`` (defaults to ``set``) -- a type\n constructor (``set``, ``tuple``, ``list``, ``frozenset``,\n ``iter``, etc.) which is to be applied to the antichains\n before they are yielded.\n\n - ``stop`` -- a Boolean (default: ``True``) determining\n whether the iterator should stop once it completes its\n cycle (this happens when it is set to ``True``) or go on\n forever (this happens when it is set to ``False``).\n\n - ``check`` -- a Boolean (default: ``True``) determining\n whether ``antichain`` should be checked for being an\n antichain.\n\n OUTPUT:\n\n - an iterator over the orbit of the antichain ``antichain``\n under Panyushev complementation. This iterator `I` has the\n property that ``I[0] == antichain`` and each `i` satisfies\n ``self.order_ideal_complement_generators(I[i]) == I[i+1]``,\n where ``I[i+1]`` has to be understood as ``I[0]`` if it is\n undefined.\n The entries ``I[i]`` are sets by default, but depending on\n the optional keyword variable ``element_constructors``\n they can also be tuples, lists etc.\n\n EXAMPLES::\n\n sage: P = Poset( ( [1,2,3], [ [1,3], [2,3] ] ) )\n sage: list(P.panyushev_orbit_iter(set([1, 2])))\n [{1, 2}, {3}, set()]\n sage: list(P.panyushev_orbit_iter([1, 2]))\n [{1, 2}, {3}, set()]\n sage: list(P.panyushev_orbit_iter([2, 1]))\n [{1, 2}, {3}, set()]\n sage: list(P.panyushev_orbit_iter(set([1, 2]), element_constructor=list))\n [[1, 2], [3], []]\n sage: list(P.panyushev_orbit_iter(set([1, 2]), element_constructor=frozenset))\n [frozenset({1, 2}), frozenset({3}), frozenset()]\n sage: list(P.panyushev_orbit_iter(set([1, 2]), element_constructor=tuple))\n [(1, 2), (3,), ()]\n\n sage: P = Poset( {} )\n sage: list(P.panyushev_orbit_iter([]))\n [set()]\n\n sage: P = Poset({ 1: [2, 3], 2: [4], 3: [4], 4: [] })\n sage: Piter = P.panyushev_orbit_iter([2], stop=False)\n sage: next(Piter)\n {2}\n sage: next(Piter)\n {3}\n sage: next(Piter)\n {2}\n sage: next(Piter)\n {3}\n '
if check:
if (not self.is_antichain_of_poset(antichain)):
raise ValueError('the given antichain is not an antichain')
starter = set(antichain)
(yield element_constructor(starter))
next = starter
if stop:
while True:
next = self.order_ideal_complement_generators(next)
if (next == starter):
break
(yield element_constructor(next))
else:
while True:
next = self.order_ideal_complement_generators(next)
(yield element_constructor(next))
def rowmotion_orbit_iter(self, oideal, element_constructor=set, stop=True, check=True):
'\n Iterate over the rowmotion orbit of an order ideal\n ``oideal`` of ``self``.\n\n The rowmotion orbit of an order ideal is its orbit under\n rowmotion (see :meth:`rowmotion`).\n\n INPUT:\n\n - ``oideal`` -- an order ideal of ``self``, given as an\n iterable.\n\n - ``element_constructor`` (defaults to ``set``) -- a type\n constructor (``set``, ``tuple``, ``list``, ``frozenset``,\n ``iter``, etc.) which is to be applied to the order\n ideals before they are yielded.\n\n - ``stop`` -- a Boolean (default: ``True``) determining\n whether the iterator should stop once it completes its\n cycle (this happens when it is set to ``True``) or go on\n forever (this happens when it is set to ``False``).\n\n - ``check`` -- a Boolean (default: ``True``) determining\n whether ``oideal`` should be checked for being an\n order ideal.\n\n OUTPUT:\n\n - an iterator over the orbit of the order ideal ``oideal``\n under rowmotion. This iterator `I` has the property that\n ``I[0] == oideal`` and that every `i` satisfies\n ``self.rowmotion(I[i]) == I[i+1]``, where ``I[i+1]`` has\n to be understood as ``I[0]`` if it is undefined.\n The entries ``I[i]`` are sets by default, but depending on\n the optional keyword variable ``element_constructors``\n they can also be tuples, lists etc.\n\n EXAMPLES::\n\n sage: P = Poset( ( [1,2,3], [ [1,3], [2,3] ] ) )\n sage: list(P.rowmotion_orbit_iter(set([1, 2])))\n [{1, 2}, {1, 2, 3}, set()]\n sage: list(P.rowmotion_orbit_iter([1, 2]))\n [{1, 2}, {1, 2, 3}, set()]\n sage: list(P.rowmotion_orbit_iter([2, 1]))\n [{1, 2}, {1, 2, 3}, set()]\n sage: list(P.rowmotion_orbit_iter(set([1, 2]), element_constructor=list))\n [[1, 2], [1, 2, 3], []]\n sage: list(P.rowmotion_orbit_iter(set([1, 2]), element_constructor=frozenset))\n [frozenset({1, 2}), frozenset({1, 2, 3}), frozenset()]\n sage: list(P.rowmotion_orbit_iter(set([1, 2]), element_constructor=tuple))\n [(1, 2), (1, 2, 3), ()]\n\n sage: P = Poset( {} )\n sage: list(P.rowmotion_orbit_iter([]))\n [set()]\n\n sage: P = Poset({ 1: [2, 3], 2: [4], 3: [4], 4: [] })\n sage: Piter = P.rowmotion_orbit_iter([1, 2, 3], stop=False)\n sage: next(Piter)\n {1, 2, 3}\n sage: next(Piter)\n {1, 2, 3, 4}\n sage: next(Piter)\n set()\n sage: next(Piter)\n {1}\n sage: next(Piter)\n {1, 2, 3}\n\n sage: P = Poset({ 1: [4], 2: [4, 5], 3: [5] })\n sage: list(P.rowmotion_orbit_iter([1, 2], element_constructor=list))\n [[1, 2], [1, 2, 3, 4], [2, 3, 5], [1], [2, 3], [1, 2, 3, 5], [1, 2, 4], [3]]\n '
if check:
if (not self.is_order_ideal(oideal)):
raise ValueError('the given order ideal is not an order ideal')
starter = set(oideal)
(yield element_constructor(starter))
next = starter
if stop:
while True:
next = self.rowmotion(next)
if (next == starter):
break
(yield element_constructor(next))
else:
while True:
next = self.rowmotion(next)
(yield element_constructor(next))
def toggling_orbit_iter(self, vs, oideal, element_constructor=set, stop=True, check=True):
'\n Iterate over the orbit of an order ideal ``oideal`` of\n ``self`` under the operation of toggling the vertices\n ``vs[0], vs[1], ...`` in this order.\n\n See :meth:`~sage.categories.posets.Posets.ParentMethods.order_ideal_toggle` for a definition of toggling.\n\n .. WARNING::\n\n The orbit is that under the composition of toggles,\n *not* under the single toggles themselves. Thus, for\n example, if ``vs == [1,2]``, then the orbit has the\n form `(I, T_2 T_1 I, T_2 T_1 T_2 T_1 I, \\ldots)`\n (where `I` denotes ``oideal`` and `T_i` means\n toggling at `i`) rather than\n `(I, T_1 I, T_2 T_1 I, T_1 T_2 T_1 I, \\ldots)`.\n\n INPUT:\n\n - ``vs``: a list (or other iterable) of elements of ``self``\n (but since the output depends on the order, sets should\n not be used as ``vs``).\n\n - ``oideal`` -- an order ideal of ``self``, given as an\n iterable.\n\n - ``element_constructor`` (defaults to ``set``) -- a type\n constructor (``set``, ``tuple``, ``list``, ``frozenset``,\n ``iter``, etc.) which is to be applied to the order\n ideals before they are yielded.\n\n - ``stop`` -- a Boolean (default: ``True``) determining\n whether the iterator should stop once it completes its\n cycle (this happens when it is set to ``True``) or go on\n forever (this happens when it is set to ``False``).\n\n - ``check`` -- a Boolean (default: ``True``) determining\n whether ``oideal`` should be checked for being an\n order ideal.\n\n OUTPUT:\n\n - an iterator over the orbit of the order ideal ``oideal``\n under toggling the vertices in the list ``vs`` in this\n order. This iterator `I` has the property that\n ``I[0] == oideal`` and that every `i` satisfies\n ``self.order_ideal_toggles(I[i], vs) == I[i+1]``, where\n ``I[i+1]`` has to be understood as ``I[0]`` if it is\n undefined.\n The entries ``I[i]`` are sets by default, but depending on\n the optional keyword variable ``element_constructors``\n they can also be tuples, lists etc.\n\n EXAMPLES::\n\n sage: P = Poset( ( [1,2,3], [ [1,3], [2,3] ] ) )\n sage: list(P.toggling_orbit_iter([1, 3, 1], set([1, 2])))\n [{1, 2}]\n sage: list(P.toggling_orbit_iter([1, 2, 3], set([1, 2])))\n [{1, 2}, set(), {1, 2, 3}]\n sage: list(P.toggling_orbit_iter([3, 2, 1], set([1, 2])))\n [{1, 2}, {1, 2, 3}, set()]\n sage: list(P.toggling_orbit_iter([3, 2, 1], set([1, 2]), element_constructor=list))\n [[1, 2], [1, 2, 3], []]\n sage: list(P.toggling_orbit_iter([3, 2, 1], set([1, 2]), element_constructor=frozenset))\n [frozenset({1, 2}), frozenset({1, 2, 3}), frozenset()]\n sage: list(P.toggling_orbit_iter([3, 2, 1], set([1, 2]), element_constructor=tuple))\n [(1, 2), (1, 2, 3), ()]\n sage: list(P.toggling_orbit_iter([3, 2, 1], [2, 1], element_constructor=tuple))\n [(1, 2), (1, 2, 3), ()]\n\n sage: P = Poset( {} )\n sage: list(P.toggling_orbit_iter([], []))\n [set()]\n\n sage: P = Poset({ 1: [2, 3], 2: [4], 3: [4], 4: [] })\n sage: Piter = P.toggling_orbit_iter([1, 2, 4, 3], [1, 2, 3], stop=False)\n sage: next(Piter)\n {1, 2, 3}\n sage: next(Piter)\n {1}\n sage: next(Piter)\n set()\n sage: next(Piter)\n {1, 2, 3}\n sage: next(Piter)\n {1}\n '
if check:
if (not self.is_order_ideal(oideal)):
raise ValueError('the given order ideal is not an order ideal')
starter = set(oideal)
(yield element_constructor(starter))
next = starter
if stop:
while True:
next = self.order_ideal_toggles(next, vs)
if (next == starter):
break
(yield element_constructor(next))
else:
while True:
next = self.order_ideal_toggles(next, vs)
(yield element_constructor(next))
def order_ideals_lattice(self, as_ideals=True, facade=None):
'\n Return the lattice of order ideals of a poset ``self``,\n ordered by inclusion.\n\n The lattice of order ideals of a poset `P` is usually\n denoted by `J(P)`. Its underlying set is the set of order\n ideals of `P`, and its partial order is given by\n inclusion.\n\n The order ideals of `P` are in a canonical bijection\n with the antichains of `P`. The bijection maps every\n order ideal to the antichain formed by its maximal\n elements. By setting the ``as_ideals`` keyword variable to\n ``False``, one can make this method apply this bijection\n before returning the lattice.\n\n INPUT:\n\n - ``as_ideals`` -- Boolean, if ``True`` (default) returns\n a poset on the set of order ideals, otherwise on the set\n of antichains\n - ``facade`` -- Boolean or ``None`` (default). Whether to\n return a facade lattice or not. By default return facade\n lattice if the poset is a facade poset.\n\n EXAMPLES::\n\n sage: P = posets.PentagonPoset()\n sage: P.cover_relations()\n [[0, 1], [0, 2], [1, 4], [2, 3], [3, 4]]\n sage: J = P.order_ideals_lattice(); J\n Finite lattice containing 8 elements\n sage: sorted(sorted(e) for e in J)\n [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 2], [0, 2, 3]]\n\n As a lattice on antichains::\n\n sage: J2 = P.order_ideals_lattice(False); J2\n Finite lattice containing 8 elements\n sage: sorted(J2)\n [(), (0,), (1,), (1, 2), (1, 3), (2,), (3,), (4,)]\n\n TESTS::\n\n sage: J = posets.DiamondPoset(4, facade = True).order_ideals_lattice(); J\n Finite lattice containing 6 elements\n sage: sorted(sorted(e) for e in J)\n [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 2]]\n sage: sorted(sorted(sorted(e) for e in c) for c in J.cover_relations())\n [[[], [0]], [[0], [0, 1]], [[0], [0, 2]], [[0, 1], [0, 1, 2]], [[0, 1, 2], [0, 1, 2, 3]], [[0, 1, 2], [0, 2]]]\n\n sage: P = Poset({1:[2]})\n sage: J_facade = P.order_ideals_lattice()\n sage: J_nonfacade = P.order_ideals_lattice(facade=False)\n sage: type(J_facade[0]) == type(J_nonfacade[0])\n False\n '
from sage.combinat.posets.lattices import LatticePoset
if (facade is None):
facade = self._is_facade
if as_ideals:
from sage.misc.call import attrcall
from sage.sets.set import Set
ideals = [Set(self.order_ideal(antichain)) for antichain in self.antichains()]
return LatticePoset((ideals, attrcall('issubset')), facade=facade)
else:
from sage.misc.cachefunc import cached_function
antichains = [tuple(a) for a in self.antichains()]
@cached_function
def is_above(a, xb):
return any((self.is_lequal(xa, xb) for xa in a))
def compare(a, b):
return all((is_above(a, xb) for xb in b))
return LatticePoset((antichains, compare), facade=facade)
@abstract_method(optional=True)
def antichains(self):
'\n Return all antichains of ``self``.\n\n EXAMPLES::\n\n sage: A = posets.PentagonPoset().antichains(); A\n Set of antichains of Finite lattice containing 5 elements\n sage: list(A)\n [[], [0], [1], [1, 2], [1, 3], [2], [3], [4]]\n '
def directed_subsets(self, direction):
'\n Return the order filters (resp. order ideals) of ``self``, as lists.\n\n If ``direction`` is \'up\', returns the order filters (upper sets).\n\n If ``direction`` is \'down\', returns the order ideals (lower sets).\n\n INPUT:\n\n - ``direction`` -- \'up\' or \'down\'\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True)\n sage: A = P.directed_subsets(\'up\')\n sage: sorted(list(A))\n [[], [1, 2, 4, 3, 6, 12], [2, 4, 3, 6, 12], [2, 4, 6, 12], [3, 6, 12], [4, 3, 6, 12], [4, 6, 12], [4, 12], [6, 12], [12]]\n\n TESTS::\n\n sage: list(Poset().directed_subsets(\'up\'))\n [[]]\n '
if ((direction != 'up') and (direction != 'down')):
raise ValueError("direction must be either 'up' or 'down'")
return self.antichains().map((lambda elements: self.directed_subset(elements, direction)))
|
class FiniteSemigroups(CategoryWithAxiom):
"\n The category of finite (multiplicative) semigroups.\n\n A finite semigroup is a :class:`finite set <FiniteSets>` endowed\n with an associative binary operation `*`.\n\n .. WARNING::\n\n Finite semigroups in Sage used to be automatically endowed\n with an :class:`enumerated set <EnumeratedSets>` structure;\n the default enumeration is then obtained by iteratively\n multiplying the semigroup generators. This forced any finite\n semigroup to either implement an enumeration, or provide\n semigroup generators; this was often inconvenient.\n\n Instead, finite semigroups that provide a distinguished finite\n set of generators with :meth:`semigroup_generators` should now\n explicitly declare themselves in the category of\n :class:`finitely generated semigroups\n <Semigroups.FinitelyGeneratedSemigroup>`::\n\n sage: Semigroups().FinitelyGenerated()\n Category of finitely generated semigroups\n\n This is a backward incompatible change.\n\n EXAMPLES::\n\n sage: C = FiniteSemigroups(); C\n Category of finite semigroups\n sage: C.super_categories()\n [Category of semigroups, Category of finite sets]\n sage: sorted(C.axioms())\n ['Associative', 'Finite']\n sage: C.example()\n An example of a finite semigroup:\n the left regular band generated by ('a', 'b', 'c', 'd')\n\n TESTS::\n\n sage: TestSuite(C).run()\n "
class ParentMethods():
def idempotents(self):
"\n Returns the idempotents of the semigroup\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('x','y'))\n sage: sorted(S.idempotents())\n ['x', 'xy', 'y', 'yx']\n "
return [x for x in self if x.is_idempotent()]
@cached_method
def j_classes(self):
"\n Returns the `J`-classes of the semigroup.\n\n Two elements `u` and `v` of a monoid are in the same `J`-class\n if `u` divides `v` and `v` divides `u`.\n\n OUTPUT:\n\n All the `J`-classes of self, as a list of lists.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('a','b', 'c'))\n sage: sorted(map(sorted, S.j_classes())) # needs sage.graphs\n [['a'], ['ab', 'ba'], ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'],\n ['ac', 'ca'], ['b'], ['bc', 'cb'], ['c']]\n "
return self.cayley_graph(side='twosided', simple=True).strongly_connected_components()
@cached_method
def j_classes_of_idempotents(self):
"\n Returns all the idempotents of self, grouped by J-class.\n\n OUTPUT:\n\n a list of lists.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('a','b', 'c'))\n sage: sorted(map(sorted, S.j_classes_of_idempotents())) # needs sage.graphs\n [['a'], ['ab', 'ba'], ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'],\n ['ac', 'ca'], ['b'], ['bc', 'cb'], ['c']]\n "
return [l for l in ([x for x in cl if attrcall('is_idempotent')(x)] for cl in self.j_classes()) if (len(l) > 0)]
@cached_method
def j_transversal_of_idempotents(self):
"\n Returns a list of one idempotent per regular J-class\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('a','b', 'c'))\n\n The chosen elements depend on the order of each `J`-class,\n and that order is random when using Python 3. ::\n\n sage: sorted(S.j_transversal_of_idempotents()) # random # needs sage.graphs\n ['a', 'ab', 'abc', 'ac', 'b', 'c', 'cb']\n "
def first_idempotent(l):
for x in l:
if x.is_idempotent():
return x
return None
return [x for x in (first_idempotent(_) for _ in self.j_classes()) if (x is not None)]
|
class FiniteSets(CategoryWithAxiom):
'\n The category of finite sets.\n\n EXAMPLES::\n\n sage: C = FiniteSets(); C\n Category of finite sets\n sage: C.super_categories()\n [Category of sets]\n sage: C.all_super_categories()\n [Category of finite sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n sage: C.example()\n NotImplemented\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: C is Sets().Finite()\n True\n '
class ParentMethods():
def is_finite(self):
'\n Return ``True`` since ``self`` is finite.\n\n EXAMPLES::\n\n sage: C = FiniteEnumeratedSets().example()\n sage: C.is_finite()\n True\n '
return True
class Subquotients(SubquotientsCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: FiniteSets().Subquotients().extra_super_categories()\n [Category of finite sets]\n\n This implements the fact that a subquotient (and therefore\n a quotient or subobject) of a finite set is finite::\n\n sage: FiniteSets().Subquotients().is_subcategory(FiniteSets())\n True\n sage: FiniteSets().Quotients ().is_subcategory(FiniteSets())\n True\n sage: FiniteSets().Subobjects ().is_subcategory(FiniteSets())\n True\n '
return [FiniteSets()]
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: FiniteSets().Algebras(QQ).extra_super_categories()\n [Category of finite dimensional vector spaces with basis over Rational Field]\n\n This implements the fact that the algebra of a finite set\n is finite dimensional::\n\n sage: FiniteMonoids().Algebras(QQ).is_subcategory(AlgebrasWithBasis(QQ).FiniteDimensional())\n True\n '
from sage.categories.modules_with_basis import ModulesWithBasis
return [ModulesWithBasis(self.base_ring()).FiniteDimensional()]
|
class FiniteWeylGroups(CategoryWithAxiom):
'\n The category of finite Weyl groups.\n\n EXAMPLES::\n\n sage: C = FiniteWeylGroups()\n sage: C\n Category of finite Weyl groups\n sage: C.super_categories()\n [Category of finite Coxeter groups, Category of Weyl groups]\n sage: C.example()\n The symmetric group on {0, ..., 3}\n\n TESTS::\n\n sage: W = FiniteWeylGroups().example()\n sage: TestSuite(W).run()\n '
class ParentMethods():
pass
class ElementMethods():
pass
|
class FinitelyGeneratedLambdaBracketAlgebras(CategoryWithAxiom_over_base_ring):
'\n The category of finitely generated lambda bracket algebras.\n\n EXAMPLES::\n\n sage: from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras\n sage: LambdaBracketAlgebras(QQbar).FinitelyGenerated() # needs sage.rings.number_field\n Category of finitely generated lambda bracket algebras over Algebraic Field\n '
_base_category_class_and_axiom = (LambdaBracketAlgebras, 'FinitelyGeneratedAsLambdaBracketAlgebra')
class ParentMethods():
def ngens(self):
"\n The number of generators of this Lie conformal algebra.\n\n EXAMPLES::\n\n sage: Vir = lie_conformal_algebras.Virasoro(QQ) # needs sage.combinat sage.modules\n sage: Vir.ngens() # needs sage.combinat sage.modules\n 2\n\n sage: V = lie_conformal_algebras.Affine(QQ, 'A2') # needs sage.combinat sage.modules\n sage: V.ngens() # needs sage.combinat sage.modules\n 9\n "
return len(self.gens())
def gen(self, i):
"\n The ``i``-th generator of this Lie conformal algebra.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1')\n sage: V.gens()\n (B[alpha[1]], B[alphacheck[1]], B[-alpha[1]], B['K'])\n sage: V.gen(0)\n B[alpha[1]]\n sage: V.1\n B[alphacheck[1]]\n "
return self.gens()[i]
def some_elements(self):
"\n Some elements of this Lie conformal algebra.\n\n This method returns a list with elements containing at\n least the generators.\n\n EXAMPLES::\n\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1', # needs sage.combinat sage.modules\n ....: names=('e', 'h', 'f'))\n sage: V.some_elements() # needs sage.combinat sage.modules\n [e, h, f, K, ...]\n sage: all(v.parent() is V for v in V.some_elements()) # needs sage.combinat sage.modules\n True\n "
S = list(self.gens())
from sage.misc.misc import some_tuples
for (x, y) in some_tuples(S, 2, 0, max_samples=self.ngens()):
S.append((x.T() + (2 * y.T(2))))
return S
class Graded(GradedModulesCategory):
'\n The category of H-graded finitely generated Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras\n over Algebraic Field\n '
def _repr_object_names(self):
'\n The names of the objects of ``self``.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
|
class FinitelyGeneratedLieConformalAlgebras(CategoryWithAxiom_over_base_ring):
'\n The category of finitely generated Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).FinitelyGenerated() # needs sage.rings.number_field\n Category of finitely generated Lie conformal algebras over Algebraic Field\n '
_base_category_class_and_axiom = (LieConformalAlgebras, 'FinitelyGeneratedAsLambdaBracketAlgebra')
class ParentMethods():
def some_elements(self):
"\n Some elements of this Lie conformal algebra.\n\n Returns a list with elements containing at least the\n generators.\n\n EXAMPLES::\n\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1', # needs sage.combinat sage.modules\n ....: names=('e', 'h', 'f'))\n sage: V.some_elements() # needs sage.combinat sage.modules\n [e, h, f, K, ...]\n sage: all(v.parent() is V for v in V.some_elements()) # needs sage.combinat sage.modules\n True\n "
S = list(self.gens())
from sage.misc.misc import some_tuples
for (x, y) in some_tuples(S, 2, 0, max_samples=self.ngens()):
S.append((x.T() + (2 * y.T(2))))
return S
class Super(SuperModulesCategory):
'\n The category of super finitely generated Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(AA).FinitelyGenerated().Super() # needs sage.rings.number_field\n Category of super finitely generated Lie conformal algebras\n over Algebraic Real Field\n '
class Graded(GradedModulesCategory):
'\n The category of H-graded super finitely generated Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).FinitelyGenerated().Super().Graded() # needs sage.rings.number_field\n Category of H-graded super finitely generated Lie conformal algebras\n over Algebraic Field\n '
def _repr_object_names(self):
'\n The names of the objects of ``self``.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar).FinitelyGenerated() # needs sage.rings.number_field\n sage: C.Super().Graded() # needs sage.rings.number_field\n Category of H-graded super finitely generated\n Lie conformal algebras over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
class Graded(GradedModulesCategory):
'\n The category of H-graded finitely generated Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras\n over Algebraic Field\n '
def _repr_object_names(self):
'\n The names of the objects of ``self``.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras with basis\n over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
|
class FinitelyGeneratedMagmas(CategoryWithAxiom):
"\n The category of finitely generated (multiplicative) magmas.\n\n See :meth:`Magmas.SubcategoryMethods.FinitelyGeneratedAsMagma` for\n details.\n\n EXAMPLES::\n\n sage: C = Magmas().FinitelyGeneratedAsMagma(); C\n Category of finitely generated magmas\n sage: C.super_categories()\n [Category of magmas]\n sage: sorted(C.axioms())\n ['FinitelyGeneratedAsMagma']\n\n TESTS::\n\n sage: TestSuite(C).run()\n "
_base_category_class_and_axiom = (Magmas, 'FinitelyGeneratedAsMagma')
class ParentMethods():
@abstract_method
def magma_generators(self):
"\n Return distinguished magma generators for ``self``.\n\n OUTPUT: a finite family\n\n This method should be implemented by all\n :class:`finitely generated magmas <FinitelyGeneratedMagmas>`.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: S.magma_generators()\n Family ('a', 'b', 'c', 'd')\n "
|
class FinitelyGeneratedSemigroups(CategoryWithAxiom):
"\n The category of finitely generated (multiplicative) semigroups.\n\n A :class:`finitely generated semigroup <Semigroups>` is a\n :class:`semigroup <Semigroups>` endowed with a distinguished\n finite set of generators (see\n :meth:`FinitelyGeneratedSemigroups.ParentMethods.semigroup_generators`).\n This makes it into an :class:`enumerated set <EnumeratedSets>`.\n\n EXAMPLES::\n\n sage: C = Semigroups().FinitelyGenerated(); C\n Category of finitely generated semigroups\n sage: C.super_categories()\n [Category of semigroups,\n Category of finitely generated magmas,\n Category of enumerated sets]\n sage: sorted(C.axioms())\n ['Associative', 'Enumerated', 'FinitelyGeneratedAsMagma']\n sage: C.example()\n An example of a semigroup: the free semigroup generated\n by ('a', 'b', 'c', 'd')\n\n TESTS::\n\n sage: TestSuite(C).run()\n "
_base_category_class_and_axiom = (Semigroups, 'FinitelyGeneratedAsMagma')
@cached_method
def extra_super_categories(self):
'\n State that a finitely generated semigroup is endowed with a\n default enumeration.\n\n EXAMPLES::\n\n sage: Semigroups().FinitelyGenerated().extra_super_categories()\n [Category of enumerated sets]\n\n '
return [EnumeratedSets()]
def example(self):
"\n EXAMPLES::\n\n sage: Semigroups().FinitelyGenerated().example()\n An example of a semigroup: the free semigroup generated\n by ('a', 'b', 'c', 'd')\n "
return Semigroups().example('free')
class ParentMethods():
@abstract_method
def semigroup_generators(self):
"\n Return distinguished semigroup generators for ``self``.\n\n OUTPUT: a finite family\n\n This method should be implemented by all semigroups in\n :class:`FinitelyGeneratedSemigroups`.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: S.semigroup_generators()\n Family ('a', 'b', 'c', 'd')\n "
def succ_generators(self, side='twosided'):
'\n Return the successor function of the ``side``-sided Cayley\n graph of ``self``.\n\n This is a function that maps an element of ``self`` to all\n the products of ``x`` by a generator of this semigroup,\n where the product is taken on the left, right, or both\n sides.\n\n INPUT:\n\n - ``side``: "left", "right", or "twosided"\n\n .. TODO:: Design choice:\n\n - find a better name for this method\n - should we return a set? a family?\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: S.succ_generators("left" )(S(\'ca\'))\n (\'ac\', \'bca\', \'ca\', \'dca\')\n sage: S.succ_generators("right")(S(\'ca\'))\n (\'ca\', \'cab\', \'ca\', \'cad\')\n sage: S.succ_generators("twosided" )(S(\'ca\'))\n (\'ac\', \'bca\', \'ca\', \'dca\', \'ca\', \'cab\', \'ca\', \'cad\')\n\n '
left = ((side == 'left') or (side == 'twosided'))
right = ((side == 'right') or (side == 'twosided'))
generators = self.semigroup_generators()
return (lambda x: ((tuple(((g * x) for g in generators)) if left else ()) + (tuple(((x * g) for g in generators)) if right else ())))
def __iter__(self):
"\n Return an iterator over the elements of ``self``.\n\n This brute force implementation recursively multiplies\n together the distinguished semigroup generators.\n\n .. SEEALSO:: :meth:`semigroup_generators`\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('x','y'))\n sage: it = S.__iter__()\n sage: sorted(it)\n ['x', 'xy', 'y', 'yx']\n "
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
return iter(RecursivelyEnumeratedSet(self.semigroup_generators(), self.succ_generators(side='right'), enumeration='breadth'))
def ideal(self, gens, side='twosided'):
'\n Return the ``side``-sided ideal generated by ``gens``.\n\n This brute force implementation recursively multiplies the\n elements of ``gens`` by the distinguished generators of\n this semigroup.\n\n .. SEEALSO:: :meth:`semigroup_generators`\n\n INPUT:\n\n - ``gens`` -- a list (or iterable) of elements of ``self``\n - ``side`` -- [default: "twosided"] "left", "right" or "twosided"\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example()\n sage: sorted(S.ideal([S(\'cab\')], side="left"))\n [\'abc\', \'abcd\', \'abdc\', \'acb\', \'acbd\', \'acdb\', \'adbc\',\n \'adcb\', \'bac\', \'bacd\', \'badc\', \'bca\', \'bcad\', \'bcda\',\n \'bdac\', \'bdca\', \'cab\', \'cabd\', \'cadb\', \'cba\', \'cbad\',\n \'cbda\', \'cdab\', \'cdba\', \'dabc\', \'dacb\', \'dbac\', \'dbca\',\n \'dcab\', \'dcba\']\n sage: list(S.ideal([S(\'cab\')], side="right"))\n [\'cab\', \'cabd\']\n sage: sorted(S.ideal([S(\'cab\')], side="twosided"))\n [\'abc\', \'abcd\', \'abdc\', \'acb\', \'acbd\', \'acdb\', \'adbc\',\n \'adcb\', \'bac\', \'bacd\', \'badc\', \'bca\', \'bcad\', \'bcda\',\n \'bdac\', \'bdca\', \'cab\', \'cabd\', \'cadb\', \'cba\', \'cbad\',\n \'cbda\', \'cdab\', \'cdba\', \'dabc\', \'dacb\', \'dbac\', \'dbca\',\n \'dcab\', \'dcba\']\n sage: sorted(S.ideal([S(\'cab\')]))\n [\'abc\', \'abcd\', \'abdc\', \'acb\', \'acbd\', \'acdb\', \'adbc\',\n \'adcb\', \'bac\', \'bacd\', \'badc\', \'bca\', \'bcad\', \'bcda\',\n \'bdac\', \'bdca\', \'cab\', \'cabd\', \'cadb\', \'cba\', \'cbad\',\n \'cbda\', \'cdab\', \'cdba\', \'dabc\', \'dacb\', \'dbac\', \'dbca\',\n \'dcab\', \'dcba\']\n '
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
return RecursivelyEnumeratedSet(gens, self.succ_generators(side=side))
class Finite(CategoryWithAxiom):
class ParentMethods():
def some_elements(self):
"\n Return an iterable containing some elements of the semigroup.\n\n OUTPUT: the ten first elements of the semigroup, if they exist.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().example(alphabet=('x','y'))\n sage: sorted(S.some_elements())\n ['x', 'xy', 'y', 'yx']\n sage: S = FiniteSemigroups().example(alphabet=('x','y','z'))\n sage: X = S.some_elements()\n sage: len(X)\n 10\n sage: all(x in S for x in X)\n True\n "
return list(itertools.islice(self, 10))
|
class FunctionFields(Category):
'\n The category of function fields.\n\n EXAMPLES:\n\n We create the category of function fields::\n\n sage: C = FunctionFields()\n sage: C\n Category of function fields\n\n TESTS::\n\n sage: TestSuite(FunctionFields()).run()\n '
@cached_method
def super_categories(self):
'\n Returns the Category of which this is a direct sub-Category\n For a list off all super categories see all_super_categories\n\n EXAMPLES::\n\n sage: FunctionFields().super_categories()\n [Category of fields]\n '
return [Fields()]
def _call_(self, x):
'\n Constructs an object in this category from the data in ``x``,\n or throws a TypeError.\n\n EXAMPLES::\n\n sage: C = FunctionFields()\n sage: K.<x> = FunctionField(QQ)\n sage: C(K)\n Rational function field in x over Rational Field\n sage: Ky.<y> = K[]\n sage: L = K.extension(y^2 - x) # needs sage.rings.function_field\n sage: C(L) # needs sage.rings.function_field\n Function field in y defined by y^2 - x\n sage: C(L.equation_order()) # needs sage.rings.function_field\n Function field in y defined by y^2 - x\n '
try:
return x.function_field()
except AttributeError:
raise TypeError(('unable to canonically associate a function field to %s' % x))
class ParentMethods():
pass
class ElementMethods():
pass
|
class GSets(Category):
'\n The category of `G`-sets, for a group `G`.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(3) # needs sage.groups\n sage: GSets(S) # needs sage.groups\n Category of G-sets for Symmetric group of order 3! as a permutation group\n\n TODO: should this derive from Category_over_base?\n '
def __init__(self, G):
'\n TESTS::\n\n sage: S8 = SymmetricGroup(8) # needs sage.groups\n sage: TestSuite(GSets(S8)).run() # needs sage.groups\n '
Category.__init__(self)
self.__G = G
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: GSets(SymmetricGroup(8)) # indirect doctests # needs sage.groups\n Category of G-sets for Symmetric group of order 8! as a permutation group\n '
return ('G-sets for %s' % self.__G)
def super_categories(self):
'\n EXAMPLES::\n\n sage: GSets(SymmetricGroup(8)).super_categories() # needs sage.groups\n [Category of sets]\n '
return [Sets()]
@classmethod
def an_instance(cls):
'\n Returns an instance of this class.\n\n EXAMPLES::\n\n sage: GSets.an_instance() # indirect doctest # needs sage.groups\n Category of G-sets for Symmetric group of order 8! as a permutation group\n '
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
G = SymmetricGroup(8)
return cls(G)
|
class GcdDomains(Category_singleton):
'\n The category of gcd domains\n domains where gcd can be computed but where there is no guarantee of\n factorisation into irreducibles\n\n EXAMPLES::\n\n sage: GcdDomains()\n Category of gcd domains\n sage: GcdDomains().super_categories()\n [Category of integral domains]\n\n TESTS::\n\n sage: TestSuite(GcdDomains()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: GcdDomains().super_categories()\n [Category of integral domains]\n '
return [IntegralDomains()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of gcd domains defines no additional\n structure: a ring morphism between two gcd domains is a gcd\n domain morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: GcdDomains().additional_structure()\n '
return None
class ParentMethods():
pass
class ElementMethods():
pass
|
class GeneralizedCoxeterGroups(Category_singleton):
'\n The category of generalized Coxeter groups.\n\n A generalized Coxeter group is a group with a presentation of\n the following form:\n\n .. MATH::\n\n \\langle s_i \\mid s_i^{p_i}, s_i s_j \\cdots = s_j s_i \\cdots \\rangle,\n\n where `p_i > 1`, `i \\in I`, and the factors in the braid relation\n occur `m_{ij} = m_{ji}` times for all `i \\neq j \\in I`.\n\n EXAMPLES::\n\n sage: from sage.categories.generalized_coxeter_groups import GeneralizedCoxeterGroups\n sage: C = GeneralizedCoxeterGroups(); C\n Category of generalized Coxeter groups\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.generalized_coxeter_groups import GeneralizedCoxeterGroups\n sage: GeneralizedCoxeterGroups().super_categories()\n [Category of complex reflection or generalized Coxeter groups]\n '
return [ComplexReflectionOrGeneralizedCoxeterGroups()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, all the structure generalized Coxeter groups have in\n addition to groups (simple reflections, ...) is already\n defined in the super category.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: from sage.categories.generalized_coxeter_groups import GeneralizedCoxeterGroups\n sage: GeneralizedCoxeterGroups().additional_structure()\n '
return None
class Finite(CategoryWithAxiom):
'\n The category of finite generalized Coxeter groups.\n '
def extra_super_categories(self):
'\n Implement that a finite generalized Coxeter group is a\n well-generated complex reflection group.\n\n EXAMPLES::\n\n sage: from sage.categories.generalized_coxeter_groups import GeneralizedCoxeterGroups\n sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups\n\n sage: Cat = GeneralizedCoxeterGroups().Finite()\n sage: Cat.extra_super_categories()\n [Category of well generated finite complex reflection groups]\n sage: Cat.is_subcategory(ComplexReflectionGroups().Finite().WellGenerated())\n True\n '
from sage.categories.complex_reflection_groups import ComplexReflectionGroups
return [ComplexReflectionGroups().Finite().WellGenerated()]
|
class GradedAlgebras(GradedModulesCategory):
'\n The category of graded algebras\n\n EXAMPLES::\n\n sage: GradedAlgebras(ZZ)\n Category of graded algebras over Integer Ring\n sage: GradedAlgebras(ZZ).super_categories()\n [Category of filtered algebras over Integer Ring,\n Category of graded modules over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(GradedAlgebras(ZZ)).run()\n '
class ParentMethods():
def graded_algebra(self):
'\n Return the associated graded algebra to ``self``.\n\n Since ``self`` is already graded, this just returns\n ``self``.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).m() # needs sage.combinat sage.modules\n sage: m.graded_algebra() is m # needs sage.combinat sage.modules\n True\n '
return self
class ElementMethods():
pass
class SubcategoryMethods():
def SignedTensorProducts(self):
'\n Return the full subcategory of objects of ``self`` constructed\n as signed tensor products.\n\n .. SEEALSO::\n\n - :class:`~sage.categories.signed_tensor.SignedTensorProductsCategory`\n - :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction`\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Graded().SignedTensorProducts()\n Category of signed tensor products of graded algebras with basis\n over Rational Field\n '
return SignedTensorProductsCategory.category_of(self)
class SignedTensorProducts(SignedTensorProductsCategory):
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Algebras(QQ).Graded().SignedTensorProducts().extra_super_categories()\n [Category of graded algebras over Rational Field]\n sage: Algebras(QQ).Graded().SignedTensorProducts().super_categories()\n [Category of graded algebras over Rational Field]\n\n Meaning: a signed tensor product of algebras is an algebra\n '
return [self.base_category()]
|
class GradedAlgebrasWithBasis(GradedModulesCategory):
'\n The category of graded algebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = GradedAlgebrasWithBasis(ZZ); C\n Category of graded algebras with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of filtered algebras with basis over Integer Ring,\n Category of graded algebras over Integer Ring,\n Category of graded modules with basis over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class ParentMethods():
def graded_algebra(self):
'\n Return the associated graded algebra to ``self``.\n\n This is ``self``, because ``self`` is already graded.\n See :meth:`~sage.categories.filtered_algebras_with_basis.FilteredAlgebrasWithBasis.graded_algebra`\n for the general behavior of this method, and see\n :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`\n for the definition and properties of associated graded\n algebras.\n\n EXAMPLES::\n\n sage: m = SymmetricFunctions(QQ).m() # needs sage.combinat sage.modules\n sage: m.graded_algebra() is m # needs sage.combinat sage.modules\n True\n\n TESTS:\n\n Let us check that the three methods\n :meth:`to_graded_conversion`, :meth:`from_graded_conversion`\n and :meth:`projection` (which form the interface of the\n associated graded algebra) work correctly here::\n\n sage: # needs sage.combinat sage.modules\n sage: to_gr = m.to_graded_conversion()\n sage: from_gr = m.from_graded_conversion()\n sage: m[2] == to_gr(m[2]) == from_gr(m[2])\n True\n sage: u = 3*m[1] - (1/2)*m[3]\n sage: u == to_gr(u) == from_gr(u)\n True\n sage: m.zero() == to_gr(m.zero()) == from_gr(m.zero())\n True\n sage: p2 = m.projection(2)\n sage: p2(m[2] - 4*m[1,1] + 3*m[1] - 2*m[[]])\n -4*m[1, 1] + m[2]\n sage: p2(4*m[1])\n 0\n sage: p2(m.zero()) == m.zero()\n True\n '
return self
def free_graded_module(self, generator_degrees, names=None):
"\n Create a finitely generated free graded module over ``self``\n\n INPUT:\n\n - ``generator_degrees`` -- tuple of integers defining the\n number of generators of the module and their degrees\n\n - ``names`` -- (optional) the names of the generators. If\n ``names`` is a comma-separated string like ``'a, b,\n c'``, then those will be the names. Otherwise, for\n example if ``names`` is ``abc``, then the names will be\n ``abc[d,i]``.\n\n By default, if all generators are in distinct degrees,\n then the ``names`` of the generators will have the form\n ``g[d]`` where ``d`` is the degree of the generator. If\n the degrees are not distinct, then the generators will be\n called ``g[d,i]`` where ``d`` is the degree and ``i`` is\n its index in the list of generators in that degree.\n\n See :mod:`sage.modules.fp_graded.free_module` for more\n examples and details.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: Q = QuadraticForm(QQ, 3, [1,2,3,4,5,6])\n sage: Cl = CliffordAlgebra(Q)\n sage: M = Cl.free_graded_module((0, 2, 3))\n sage: M.gens()\n (g[0], g[2], g[3])\n sage: N.<xy, z> = Cl.free_graded_module((1, 2))\n sage: N.generators()\n (xy, z)\n "
try:
return self._free_graded_module_class(self, generator_degrees, names=names)
except AttributeError:
from sage.modules.fp_graded.free_module import FreeGradedModule
return FreeGradedModule(self, generator_degrees, names=names)
def formal_series_ring(self):
'\n Return the completion of all formal linear combinations of\n ``self`` with finite linear combinations in each homogeneous\n degree (computed lazily).\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: NCSF = NonCommutativeSymmetricFunctions(QQ)\n sage: S = NCSF.Complete()\n sage: L = S.formal_series_ring()\n sage: L\n Lazy completion of Non-Commutative Symmetric Functions over\n the Rational Field in the Complete basis\n '
from sage.rings.lazy_series_ring import LazyCompletionGradedAlgebra
return LazyCompletionGradedAlgebra(self)
completion = formal_series_ring
class ElementMethods():
pass
class SignedTensorProducts(SignedTensorProductsCategory):
'\n The category of algebras with basis constructed by signed tensor\n product of algebras with basis.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Cat = AlgebrasWithBasis(QQ).Graded()\n sage: Cat.SignedTensorProducts().extra_super_categories()\n [Category of graded algebras with basis over Rational Field]\n sage: Cat.SignedTensorProducts().super_categories()\n [Category of graded algebras with basis over Rational Field,\n Category of signed tensor products of graded algebras over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
'\n Implements operations on tensor products of super algebras\n with basis.\n '
@cached_method
def one_basis(self):
'\n Return the index of the one of this signed tensor product of\n algebras, as per ``AlgebrasWithBasis.ParentMethods.one_basis``.\n\n It is the tuple whose operands are the indices of the\n ones of the operands, as returned by their\n :meth:`.one_basis` methods.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A.<x,y> = ExteriorAlgebra(QQ)\n sage: A.one_basis()\n 0\n sage: B = tensor((A, A, A))\n sage: B.one_basis()\n (0, 0, 0)\n sage: B.one()\n 1 # 1 # 1\n '
if all((hasattr(module, 'one_basis') for module in self._sets)):
return tuple((module.one_basis() for module in self._sets))
else:
raise NotImplementedError
def product_on_basis(self, t0, t1):
'\n The product of the algebra on the basis, as per\n ``AlgebrasWithBasis.ParentMethods.product_on_basis``.\n\n EXAMPLES:\n\n Test the sign in the super tensor product::\n\n sage: # needs sage.combinat sage.modules\n sage: A = SteenrodAlgebra(3)\n sage: x = A.Q(0)\n sage: y = x.coproduct()\n sage: y^2\n 0\n\n TODO: optimize this implementation!\n '
basic = tensor_signed(((module.monomial(x0) * module.monomial(x1)) for (module, x0, x1) in zip(self._sets, t0, t1)))
n = len(self._sets)
parity0 = [self._sets[idx].degree_on_basis(x0) for (idx, x0) in enumerate(t0)]
parity1 = [self._sets[idx].degree_on_basis(x1) for (idx, x1) in enumerate(t1)]
parity = sum(((parity0[i] * parity1[j]) for j in range(n) for i in range((j + 1), n)))
return (((- 1) ** parity) * basic)
|
def GradedBialgebras(base_ring):
'\n The category of graded bialgebras\n\n EXAMPLES::\n\n sage: C = GradedBialgebras(QQ); C\n Join of Category of graded algebras over Rational Field\n and Category of bialgebras over Rational Field\n and Category of graded coalgebras over Rational Field\n sage: C is Bialgebras(QQ).Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
from sage.categories.bialgebras import Bialgebras
return Bialgebras(base_ring).Graded()
|
def GradedBialgebrasWithBasis(base_ring):
'\n The category of graded bialgebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = GradedBialgebrasWithBasis(QQ); C\n Join of Category of ...\n sage: sorted(C.super_categories(), key=str)\n [Category of bialgebras with basis over Rational Field,\n Category of graded algebras with basis over Rational Field,\n Category of graded coalgebras with basis over Rational Field]\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
from sage.categories.bialgebras_with_basis import BialgebrasWithBasis
return BialgebrasWithBasis(base_ring).Graded()
|
class GradedCoalgebras(GradedModulesCategory):
'\n The category of graded coalgebras\n\n EXAMPLES::\n\n sage: C = GradedCoalgebras(QQ); C\n Category of graded coalgebras over Rational Field\n sage: C is Coalgebras(QQ).Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class SubcategoryMethods():
def SignedTensorProducts(self):
'\n Return the full subcategory of objects of ``self`` constructed\n as signed tensor products.\n\n .. SEEALSO::\n\n - :class:`~sage.categories.signed_tensor.SignedTensorProductsCategory`\n - :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction`\n\n EXAMPLES::\n\n sage: CoalgebrasWithBasis(QQ).Graded().SignedTensorProducts()\n Category of signed tensor products of graded coalgebras with basis\n over Rational Field\n '
return SignedTensorProductsCategory.category_of(self)
class SignedTensorProducts(SignedTensorProductsCategory):
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Coalgebras(QQ).Graded().SignedTensorProducts().extra_super_categories()\n [Category of graded coalgebras over Rational Field]\n sage: Coalgebras(QQ).Graded().SignedTensorProducts().super_categories()\n [Category of graded coalgebras over Rational Field]\n\n Meaning: a signed tensor product of coalgebras is a coalgebra\n '
return [self.base_category()]
|
class GradedCoalgebrasWithBasis(GradedModulesCategory):
'\n The category of graded coalgebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = GradedCoalgebrasWithBasis(QQ); C\n Category of graded coalgebras with basis over Rational Field\n sage: C is Coalgebras(QQ).WithBasis().Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class SignedTensorProducts(SignedTensorProductsCategory):
'\n The category of coalgebras with basis constructed by signed tensor\n product of coalgebras with basis.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Cat = CoalgebrasWithBasis(QQ).Graded()\n sage: Cat.SignedTensorProducts().extra_super_categories()\n [Category of graded coalgebras with basis over Rational Field]\n sage: Cat.SignedTensorProducts().super_categories()\n [Category of graded coalgebras with basis over Rational Field,\n Category of signed tensor products of graded coalgebras over Rational Field]\n '
return [self.base_category()]
|
def GradedHopfAlgebras(base_ring):
'\n The category of graded Hopf algebras.\n\n EXAMPLES::\n\n sage: C = GradedHopfAlgebras(QQ); C\n Join of Category of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of graded coalgebras over Rational Field\n sage: C is HopfAlgebras(QQ).Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n\n .. NOTE::\n\n This is not a graded Hopf algebra as is typically defined\n in algebraic topology as the product in the tensor square\n `(x \\otimes y) (a \\otimes b) = (xa) \\otimes (yb)` does\n not carry an additional sign. For this, instead use\n :class:`super Hopf algebras\n <sage.categories.hopf_algebras.HopfAlgebras.Super>`.\n '
from sage.categories.hopf_algebras import HopfAlgebras
return HopfAlgebras(base_ring).Graded()
|
class GradedHopfAlgebrasWithBasis(GradedModulesCategory):
'\n The category of graded Hopf algebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = GradedHopfAlgebrasWithBasis(ZZ); C\n Category of graded Hopf algebras with basis over Integer Ring\n sage: C.super_categories()\n [Category of filtered Hopf algebras with basis over Integer Ring,\n Category of graded algebras with basis over Integer Ring,\n Category of graded coalgebras with basis over Integer Ring]\n\n sage: C is HopfAlgebras(ZZ).WithBasis().Graded()\n True\n sage: C is HopfAlgebras(ZZ).Graded().WithBasis()\n False\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
def example(self):
'\n Return an example of a graded Hopf algebra with\n a distinguished basis.\n\n TESTS::\n\n sage: GradedHopfAlgebrasWithBasis(QQ).example() # needs sage.modules\n An example of a graded connected Hopf algebra with basis over Rational Field\n '
from sage.categories.examples.graded_connected_hopf_algebras_with_basis import GradedConnectedCombinatorialHopfAlgebraWithPrimitiveGenerator
return GradedConnectedCombinatorialHopfAlgebraWithPrimitiveGenerator(self.base())
class ParentMethods():
pass
class ElementMethods():
pass
class WithRealizations(WithRealizationsCategory):
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: GradedHopfAlgebrasWithBasis(QQ).WithRealizations().super_categories()\n [Join of Category of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of graded coalgebras over Rational Field]\n\n TESTS::\n\n sage: TestSuite(GradedHopfAlgebrasWithBasis(QQ).WithRealizations()).run()\n\n '
from sage.categories.graded_hopf_algebras import GradedHopfAlgebras
R = self.base_category().base_ring()
return [GradedHopfAlgebras(R)]
class Connected(CategoryWithAxiom_over_base_ring):
def example(self):
'\n Return an example of a graded connected Hopf algebra with\n a distinguished basis.\n\n TESTS::\n\n sage: GradedHopfAlgebrasWithBasis(QQ).Connected().example() # needs sage.modules\n An example of a graded connected Hopf algebra with basis over Rational Field\n '
from sage.categories.examples.graded_connected_hopf_algebras_with_basis import GradedConnectedCombinatorialHopfAlgebraWithPrimitiveGenerator
return GradedConnectedCombinatorialHopfAlgebraWithPrimitiveGenerator(self.base())
class ParentMethods():
def counit_on_basis(self, i):
'\n The default counit of a graded connected Hopf algebra.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n OUTPUT:\n\n - an element of the base ring\n\n .. MATH::\n\n c(i) := \\begin{cases}\n 1 & \\hbox{if $i$ indexes the $1$ of the algebra}\\\\\n 0 & \\hbox{otherwise}.\n \\end{cases}\n\n EXAMPLES::\n\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example() # needs sage.modules\n sage: H.monomial(4).counit() # indirect doctest # needs sage.modules\n 0\n sage: H.monomial(0).counit() # indirect doctest # needs sage.modules\n 1\n '
if (i == self.one_basis()):
return self.base_ring().one()
return self.base_ring().zero()
@cached_method
def antipode_on_basis(self, index):
'\n The antipode on the basis element indexed by ``index``.\n\n INPUT:\n\n - ``index`` -- an element of the index set\n\n For a graded connected Hopf algebra, we can define\n an antipode recursively by\n\n .. MATH::\n\n S(x) := -\\sum_{x^L \\neq x} S(x^L) \\times x^R\n\n when `|x| > 0`, and by `S(x) = x` when `|x| = 0`.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: H = GradedHopfAlgebrasWithBasis(QQ).Connected().example()\n sage: H.monomial(0).antipode() # indirect doctest\n P0\n sage: H.monomial(1).antipode() # indirect doctest\n -P1\n sage: H.monomial(2).antipode() # indirect doctest\n P2\n sage: H.monomial(3).antipode() # indirect doctest\n -P3\n '
if (self.monomial(index) == self.one()):
return self.one()
S = self.antipode_on_basis
x__S_Id = tensor([self, self]).module_morphism((lambda ab: (S(ab[0]) * self.monomial(ab[1]))), codomain=self)
return (- x__S_Id((self.monomial(index).coproduct() - tensor([self.monomial(index), self.one()]))))
class ElementMethods():
pass
|
class GradedLieAlgebras(GradedModulesCategory):
'\n Category of graded Lie algebras.\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).Graded()\n sage: TestSuite(C).run()\n '
class SubcategoryMethods():
def Stratified(self):
'\n Return the full subcategory of stratified objects of ``self``.\n\n A Lie algebra is stratified if it is graded and generated as a\n Lie algebra by its component of degree one.\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ).Graded().Stratified()\n Category of stratified Lie algebras over Rational Field\n '
return self._with_axiom('Stratified')
class Stratified(CategoryWithAxiom_over_base_ring):
'\n Category of stratified Lie algebras.\n\n A graded Lie algebra `L = \\bigoplus_{k=1}^M L_k` (where\n possibly `M = \\infty`) is called *stratified* if it is generated\n by `L_1`; in other words, we have `L_{k+1} = [L_1, L_k]`.\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).Graded().Stratified()\n sage: TestSuite(C).run()\n '
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional stratified Lie algebras.\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ).Graded().Stratified().FiniteDimensional()\n Category of finite dimensional stratified Lie algebras over Rational Field\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).Graded().Stratified().FiniteDimensional()\n sage: TestSuite(C).run()\n '
def extra_super_categories(self):
'\n Implements the fact that a finite dimensional stratified Lie\n algebra is nilpotent.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ).Graded().Stratified().FiniteDimensional()\n sage: C.extra_super_categories()\n [Category of nilpotent Lie algebras over Rational Field]\n sage: C is C.Nilpotent()\n True\n sage: C.is_subcategory(LieAlgebras(QQ).Nilpotent())\n True\n '
from sage.categories.lie_algebras import LieAlgebras
return [LieAlgebras(self.base_ring()).Nilpotent()]
|
class GradedLieAlgebrasWithBasis(GradedModulesCategory):
'\n The category of graded Lie algebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(ZZ).WithBasis().Graded(); C\n Category of graded Lie algebras with basis over Integer Ring\n sage: C.super_categories()\n [Category of graded modules with basis over Integer Ring,\n Category of Lie algebras with basis over Integer Ring,\n Category of graded Lie algebras over Integer Ring]\n\n sage: C is LieAlgebras(ZZ).WithBasis().Graded()\n True\n sage: C is LieAlgebras(ZZ).Graded().WithBasis()\n False\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
FiniteDimensional = LazyImport('sage.categories.finite_dimensional_graded_lie_algebras_with_basis', 'FiniteDimensionalGradedLieAlgebrasWithBasis', as_name='FiniteDimensional')
|
class GradedLieConformalAlgebrasCategory(GradedModulesCategory):
@cached_method
def Super(self, base_ring=None):
'\n Return the super-analogue category of ``self``.\n\n INPUT:\n\n - ``base_ring`` -- this is ignored\n\n EXAMPLES::\n\n sage: # needs sage.rings.number_field\n sage: C = LieConformalAlgebras(QQbar)\n sage: C.Graded().Super() is C.Super().Graded()\n True\n sage: Cp = C.WithBasis()\n sage: Cp.Graded().Super() is Cp.Super().Graded()\n True\n '
return self.base_category().Super(base_ring).Graded()
def _repr_object_names(self):
'\n The names of the objects of ``self``.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).Graded() # needs sage.rings.number_field\n Category of H-graded Lie conformal algebras over Algebraic Field\n\n sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
|
class GradedLieConformalAlgebras(GradedLieConformalAlgebrasCategory):
'\n The category of graded Lie conformal algebras.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar).Graded(); C # needs sage.rings.number_field\n Category of H-graded Lie conformal algebras over Algebraic Field\n\n sage: CS = LieConformalAlgebras(QQ).Graded().Super(); CS\n Category of H-graded super Lie conformal algebras over Rational Field\n sage: CS is LieConformalAlgebras(QQ).Super().Graded()\n True\n '
|
class GradedModulesCategory(RegressiveCovariantConstructionCategory, Category_over_base_ring):
def __init__(self, base_category):
'\n EXAMPLES::\n\n sage: C = GradedAlgebras(QQ)\n sage: C\n Category of graded algebras over Rational Field\n sage: C.base_category()\n Category of algebras over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of filtered algebras over Rational Field,\n Category of graded vector spaces over Rational Field]\n\n sage: AlgebrasWithBasis(QQ).Graded().base_ring()\n Rational Field\n sage: GradedHopfAlgebrasWithBasis(QQ).base_ring()\n Rational Field\n\n TESTS::\n\n sage: GradedModules(ZZ)\n Category of graded modules over Integer Ring\n sage: Modules(ZZ).Graded()\n Category of graded modules over Integer Ring\n sage: GradedModules(ZZ) is Modules(ZZ).Graded()\n True\n '
super().__init__(base_category, base_category.base_ring())
_functor_category = 'Graded'
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Graded() # indirect doctest\n Category of graded algebras with basis over Rational Field\n '
return 'graded {}'.format(self.base_category()._repr_object_names())
@classmethod
def default_super_categories(cls, category, *args):
'\n Return the default super categories of ``category.Graded()``.\n\n Mathematical meaning: every graded object (module, algebra,\n etc.) is a filtered object with the (implicit) filtration\n defined by `F_i = \\bigoplus_{j \\leq i} G_j`.\n\n INPUT:\n\n - ``cls`` -- the class ``GradedModulesCategory``\n - ``category`` -- a category\n\n OUTPUT: a (join) category\n\n In practice, this returns ``category.Filtered()``, joined\n together with the result of the method\n :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>`\n (that is the join of ``category.Filtered()`` and ``cat`` for\n each ``cat`` in the super categories of ``category``).\n\n EXAMPLES:\n\n Consider ``category=Algebras()``, which has ``cat=Modules()``\n as super category. Then, a grading of an algebra `G`\n is also a filtration of `G`::\n\n sage: Algebras(QQ).Graded().super_categories()\n [Category of filtered algebras over Rational Field,\n Category of graded vector spaces over Rational Field]\n\n This resulted from the following call::\n\n sage: sage.categories.graded_modules.GradedModulesCategory.default_super_categories(Algebras(QQ))\n Join of Category of filtered algebras over Rational Field\n and Category of graded vector spaces over Rational Field\n '
cat = super().default_super_categories(category, *args)
return Category.join([category.Filtered(), cat])
|
class GradedModules(GradedModulesCategory):
'\n The category of graded modules.\n\n We consider every graded module `M = \\bigoplus_i M_i` as a\n filtered module under the (natural) filtration given by\n\n .. MATH::\n\n F_i = \\bigoplus_{j < i} M_j.\n\n EXAMPLES::\n\n sage: GradedModules(ZZ)\n Category of graded modules over Integer Ring\n sage: GradedModules(ZZ).super_categories()\n [Category of filtered modules over Integer Ring]\n\n The category of graded modules defines the graded structure which\n shall be preserved by morphisms::\n\n sage: Modules(ZZ).Graded().additional_structure()\n Category of graded modules over Integer Ring\n\n TESTS::\n\n sage: TestSuite(GradedModules(ZZ)).run()\n '
class ParentMethods():
pass
class ElementMethods():
pass
|
class GradedModulesWithBasis(GradedModulesCategory):
'\n The category of graded modules with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = GradedModulesWithBasis(ZZ); C\n Category of graded modules with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of filtered modules with basis over Integer Ring,\n Category of graded modules over Integer Ring]\n sage: C is ModulesWithBasis(ZZ).Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
class ParentMethods():
def degree_negation(self, element):
'\n Return the image of ``element`` under the degree negation\n automorphism of the graded module ``self``.\n\n The degree negation is the module automorphism which scales\n every homogeneous element of degree `k` by `(-1)^k` (for all\n `k`). This assumes that the module ``self`` is `\\ZZ`-graded.\n\n INPUT:\n\n - ``element`` -- element of the module ``self``\n\n EXAMPLES::\n\n sage: E.<a,b> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: E.degree_negation((1 + a) * (1 + b)) # needs sage.modules\n a*b - a - b + 1\n sage: E.degree_negation(E.zero()) # needs sage.modules\n 0\n\n sage: P = GradedModulesWithBasis(ZZ).example(); P # needs sage.combinat sage.modules\n An example of a graded module with basis:\n the free module on partitions over Integer Ring\n sage: pbp = lambda x: P.basis()[Partition(list(x))]\n sage: p = pbp([3,1]) - 2 * pbp([2]) + 4 * pbp([1]) # needs sage.combinat sage.modules\n sage: P.degree_negation(p) # needs sage.combinat sage.modules\n -4*P[1] - 2*P[2] + P[3, 1]\n '
base_one = self.base_ring().one()
base_minusone = (- base_one)
diag = (lambda x: (base_one if ((self.degree_on_basis(x) % 2) == 0) else base_minusone))
return self.sum_of_terms([(key, (diag(key) * value)) for (key, value) in element.monomial_coefficients(copy=False).items()])
def submodule(self, gens, check=True, already_echelonized=False, unitriangular=False, support_order=None, category=None, *args, **opts):
'\n Return the submodule spanned by a finite set of elements.\n\n INPUT:\n\n - ``gens`` -- a list or family of elements of ``self``\n - ``check`` -- (default: ``True``) whether to verify that the\n elements of ``gens`` are in ``self``\n - ``already_echelonized`` -- (default: ``False``) whether\n the elements of ``gens`` are already in (not necessarily\n reduced) echelon form\n - ``unitriangular`` -- (default: ``False``) whether\n the lift morphism is unitriangular\n - ``support_order`` -- (optional) either something that can\n be converted into a tuple or a key function\n - ``category`` -- (optional) the category of the submodule\n\n If ``already_echelonized`` is ``False``, then the\n generators are put in reduced echelon form using\n :meth:`echelonize`, and reindexed by `0,1,...`.\n\n .. WARNING::\n\n At this point, this method only works for finite\n dimensional submodules and if matrices can be\n echelonized over the base ring.\n\n If in addition ``unitriangular`` is ``True``, then\n the generators are made such that the coefficients of\n the pivots are 1, so that lifting map is unitriangular.\n\n The basis of the submodule uses the same index set as the\n generators, and the lifting map sends `y_i` to `gens[i]`.\n\n .. SEEALSO::\n\n - :meth:`ModulesWithBasis.FiniteDimensional.ParentMethods.quotient_module`\n - :class:`sage.modules.with_basis.subquotient.SubmoduleWithBasis`\n\n EXAMPLES:\n\n A graded submodule of a graded module generated by homogeneous\n elements is naturally graded::\n\n sage: # needs sage.combinat sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z])\n sage: S.category()\n Join of\n Category of graded vector spaces with basis over Rational Field and\n Category of subobjects of filtered modules with basis over Rational Field and\n Category of finite dimensional vector spaces with basis over Rational Field\n sage: S.basis()[0].degree()\n 1\n sage: S.basis()[1].degree()\n 2\n\n We check on the echelonized basis::\n\n sage: Sp = E.submodule([1, x + y + 5, x*y - y*z + x + y - 2]) # needs sage.combinat sage.modules\n sage: Sp.category() # needs sage.combinat sage.modules\n Join of\n Category of graded vector spaces with basis over Rational Field and\n Category of subobjects of filtered modules with basis over Rational Field and\n Category of finite dimensional vector spaces with basis over Rational Field\n\n If it is generated by inhomogeneous elements, then it is\n filtered by default::\n\n sage: F = E.submodule([x + y*z, x*z + y*x]) # needs sage.combinat sage.modules\n sage: F.category() # needs sage.combinat sage.modules\n Join of\n Category of subobjects of filtered modules with basis over Rational Field and\n Category of filtered vector spaces with basis over Rational Field and\n Category of finite dimensional vector spaces with basis over Rational Field\n\n If ``category`` is specified, then it does not give any extra\n structure to the submodule (we can think of this as applying\n the forgetful functor)::\n\n sage: # needs sage.combinat sage.modules\n sage: SM = E.submodule([x + y, x*y - y*z],\n ....: category=ModulesWithBasis(QQ))\n sage: SM.category()\n Join of\n Category of finite dimensional vector spaces with basis over Rational Field and\n Category of subobjects of sets\n sage: FM = E.submodule([x + 1, x*y - x*y*z],\n ....: category=ModulesWithBasis(QQ))\n sage: FM.category()\n Join of\n Category of finite dimensional vector spaces with basis over Rational Field and\n Category of subobjects of sets\n\n If we have specified that this is a graded submodule of a graded\n module, then the echelonized elements must be homogeneous::\n\n sage: Cat = ModulesWithBasis(QQ).Graded().Subobjects()\n sage: E.submodule([x + y, x*y - 1], category=Cat) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n ValueError: all of the generators must be homogeneous\n sage: E.submodule([x + y, x*y - x - y], category=Cat) # needs sage.combinat sage.modules\n Free module generated by {0, 1} over Rational Field\n '
from sage.sets.family import Family, AbstractFamily
if isinstance(gens, AbstractFamily):
gens = gens.map(self)
elif isinstance(gens, dict):
gens = Family(gens.keys(), gens.__getitem__)
else:
gens = [self(y) for y in gens]
support_order = self._compute_support_order(gens, support_order)
if (not already_echelonized):
gens = self.echelon_form(gens, unitriangular, order=support_order)
GMod = GradedModulesWithBasis(self.category().base_ring())
if (category is None):
if all((g.is_homogeneous() for g in gens)):
category = GMod.Subobjects()
elif (category.is_subcategory(GMod.Subobjects()) and (not all((g.is_homogeneous() for g in gens)))):
raise ValueError('all of the generators must be homogeneous')
from sage.modules.with_basis.subquotient import SubmoduleWithBasis
return SubmoduleWithBasis(gens, *args, ambient=self, support_order=support_order, unitriangular=unitriangular, category=category, **opts)
def quotient_module(self, submodule, check=True, already_echelonized=False, category=None):
'\n Construct the quotient module ``self`` / ``submodule``.\n\n INPUT:\n\n - ``submodule`` -- a submodule with basis of ``self``, or\n something that can be turned into one via\n ``self.submodule(submodule)``\n - ``check``, ``already_echelonized`` -- passed down to\n :meth:`ModulesWithBasis.ParentMethods.submodule`\n - ``category`` -- (optional) the category of the quotient module\n\n .. WARNING::\n\n At this point, this only supports quotients by free\n submodules admitting a basis in unitriangular echelon\n form. In this case, the quotient is also a free\n module, with a basis consisting of the retract of a\n subset of the basis of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z, y])\n sage: Q = E.quotient_module(S)\n sage: Q.category()\n Join of\n Category of quotients of graded modules with basis over Rational Field and\n Category of graded vector spaces with basis over Rational Field and\n Category of finite dimensional vector spaces with basis over Rational Field\n\n .. SEEALSO::\n\n - :meth:`Modules.WithBasis.ParentMethods.submodule`\n - :meth:`Rings.ParentMethods.quotient`\n - :class:`sage.modules.with_basis.subquotient.QuotientModuleWithBasis`\n '
from sage.modules.with_basis.subquotient import SubmoduleWithBasis, QuotientModuleWithBasis
if (not isinstance(submodule, SubmoduleWithBasis)):
submodule = self.submodule(submodule, check=check, unitriangular=True, already_echelonized=already_echelonized)
GMod = GradedModulesWithBasis(self.category().base_ring())
if (category is None):
if all((g.is_homogeneous() for g in submodule.basis())):
category = GMod.Quotients()
elif (category.is_subcategory(GMod.Quotients()) and (not all((g.is_homogeneous() for g in submodule.basis())))):
raise ValueError('all of the basis elements must be homogeneous')
return QuotientModuleWithBasis(submodule, category=category)
class ElementMethods():
def degree_negation(self):
'\n Return the image of ``self`` under the degree negation\n automorphism of the graded module to which ``self`` belongs.\n\n The degree negation is the module automorphism which scales\n every homogeneous element of degree `k` by `(-1)^k` (for all\n `k`). This assumes that the module to which ``self`` belongs\n (that is, the module ``self.parent()``) is `\\ZZ`-graded.\n\n EXAMPLES::\n\n sage: E.<a,b> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: ((1 + a) * (1 + b)).degree_negation() # needs sage.modules\n a*b - a - b + 1\n sage: E.zero().degree_negation() # needs sage.modules\n 0\n\n sage: P = GradedModulesWithBasis(ZZ).example(); P # needs sage.combinat sage.modules\n An example of a graded module with basis:\n the free module on partitions over Integer Ring\n sage: pbp = lambda x: P.basis()[Partition(list(x))]\n sage: p = pbp([3,1]) - 2 * pbp([2]) + 4 * pbp([1]) # needs sage.combinat sage.modules\n sage: p.degree_negation() # needs sage.combinat sage.modules\n -4*P[1] - 2*P[2] + P[3, 1]\n '
return self.parent().degree_negation(self)
class Quotients(QuotientsCategory):
class ParentMethods():
def degree_on_basis(self, m):
'\n Return the degree of the basis element indexed by ``m``\n in ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z, y])\n sage: Q = E.quotient_module(S)\n sage: B = Q.basis()\n sage: [B[i].lift() for i in Q.indices()]\n [1, z, x*z, y*z, x*y*z]\n sage: [Q.degree_on_basis(i) for i in Q.indices()]\n [0, 1, 2, 2, 3]\n '
return self.basis()[m].lift().degree()
class ElementMethods():
def degree(self):
'\n Return the degree of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: E.<x,y,z> = ExteriorAlgebra(QQ)\n sage: S = E.submodule([x + y, x*y - y*z, y])\n sage: Q = E.quotient_module(S)\n sage: B = Q.basis()\n sage: [B[i].lift() for i in Q.indices()]\n [1, z, x*z, y*z, x*y*z]\n sage: [B[i].degree() for i in Q.indices()]\n [0, 1, 2, 2, 3]\n '
return self.lift().degree()
|
class Graphs(Category_singleton):
'\n The category of graphs.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs(); C\n Category of graphs\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: Graphs().super_categories()\n [Category of simplicial complexes]\n '
return [SimplicialComplexes()]
class ParentMethods():
@abstract_method
def vertices(self):
'\n Return the vertices of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.vertices()\n [0, 1, 2, 3, 4]\n '
@abstract_method
def edges(self):
'\n Return the edges of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.edges()\n [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]\n '
def dimension(self):
'\n Return the dimension of ``self`` as a CW complex.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.dimension()\n 1\n '
if self.edges():
return 1
return 0
def facets(self):
'\n Return the facets of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: C.facets()\n [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]\n '
return self.edges()
def faces(self):
'\n Return the faces of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().example()\n sage: sorted(C.faces(), key=lambda x: (x.dimension(), x.value))\n [0, 1, 2, 3, 4, (0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]\n '
return set(self.edges()).union(self.vertices())
class Connected(CategoryWithAxiom):
'\n The category of connected graphs.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: C = Graphs().Connected()\n sage: TestSuite(C).run()\n '
def extra_super_categories(self):
'\n Return the extra super categories of ``self``.\n\n A connected graph is also a metric space.\n\n EXAMPLES::\n\n sage: from sage.categories.graphs import Graphs\n sage: Graphs().Connected().super_categories() # indirect doctest\n [Category of connected topological spaces,\n Category of connected simplicial complexes,\n Category of graphs,\n Category of metric spaces]\n '
return [Sets().Metric()]
|
class GroupAlgebras(AlgebrasCategory):
'\n The category of group algebras over a given base ring.\n\n EXAMPLES::\n\n sage: C = Groups().Algebras(ZZ); C\n Category of group algebras over Integer Ring\n sage: C.super_categories()\n [Category of Hopf algebras with basis over Integer Ring,\n Category of monoid algebras over Integer Ring]\n\n We can also construct this category with::\n\n sage: C is GroupAlgebras(ZZ)\n True\n\n Here is how to create the group algebra of a group `G`::\n\n sage: G = DihedralGroup(5) # needs sage.groups\n sage: QG = G.algebra(QQ); QG # needs sage.groups sage.modules\n Algebra of\n Dihedral group of order 10 as a permutation group over Rational Field\n\n and an example of computation::\n\n sage: g = G.an_element(); g # needs sage.groups sage.modules\n (1,4)(2,3)\n sage: (QG.term(g) + 1)**3 # needs sage.groups sage.modules\n 4*() + 4*(1,4)(2,3)\n\n .. TODO::\n\n - Check which methods would be better located in\n ``Monoid.Algebras`` or ``Groups.Finite.Algebras``.\n\n TESTS::\n\n sage: # needs sage.groups sage.modules\n sage: A = GroupAlgebras(QQ).example(GL(3, GF(11)))\n sage: A.one_basis()\n [1 0 0]\n [0 1 0]\n [0 0 1]\n sage: A = SymmetricGroupAlgebra(QQ, 4) # needs sage.combinat\n sage: x = Permutation([4,3,2,1])\n sage: A.product_on_basis(x, x) # needs sage.combinat\n [1, 2, 3, 4]\n\n sage: C = GroupAlgebras(ZZ)\n sage: TestSuite(C).run()\n '
def extra_super_categories(self):
'\n Implement the fact that the algebra of a group is a Hopf\n algebra.\n\n EXAMPLES::\n\n sage: C = Groups().Algebras(QQ)\n sage: C.extra_super_categories()\n [Category of Hopf algebras over Rational Field]\n sage: sorted(C.super_categories(), key=str)\n [Category of Hopf algebras with basis over Rational Field,\n Category of monoid algebras over Rational Field]\n '
from sage.categories.hopf_algebras import HopfAlgebras
return [HopfAlgebras(self.base_ring())]
def example(self, G=None):
"\n Return an example of group algebra.\n\n EXAMPLES::\n\n sage: GroupAlgebras(QQ['x']).example() # needs sage.groups sage.modules\n Algebra of Dihedral group of order 8 as a permutation group\n over Univariate Polynomial Ring in x over Rational Field\n\n An other group can be specified as optional argument::\n\n sage: GroupAlgebras(QQ).example(AlternatingGroup(4)) # needs sage.groups sage.modules\n Algebra of\n Alternating group of order 4!/2 as a permutation group over Rational Field\n "
from sage.groups.perm_gps.permgroup_named import DihedralGroup
if (G is None):
G = DihedralGroup(4)
return G.algebra(self.base_ring())
class ParentMethods():
def __init_extra__(self):
'\n Enable coercion from the defining group.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = GroupAlgebra(SymmetricGroup(4), QQ)\n sage: B = GroupAlgebra(SymmetricGroup(3), ZZ)\n sage: A.has_coerce_map_from(B)\n True\n sage: B.has_coerce_map_from(A)\n False\n sage: A.has_coerce_map_from(ZZ)\n True\n sage: A.has_coerce_map_from(CC)\n False\n sage: A.has_coerce_map_from(SymmetricGroup(5))\n False\n sage: A.has_coerce_map_from(SymmetricGroup(2))\n True\n '
if (not self.base_ring().has_coerce_map_from(self.group())):
self._populate_coercion_lists_(coerce_list=[self.group()])
def _latex_(self):
'\n Latex string of ``self``.\n\n EXAMPLES::\n\n sage: A = GroupAlgebra(KleinFourGroup(), ZZ) # needs sage.groups sage.modules\n sage: latex(A) # indirect doctest # needs sage.groups sage.modules\n \\Bold{Z}[\\langle (3,4), (1,2) \\rangle]\n '
from sage.misc.latex import latex
return ('%s[%s]' % (latex(self.base_ring()), latex(self.group())))
def group(self):
'\n Return the underlying group of the group algebra.\n\n EXAMPLES::\n\n sage: GroupAlgebras(QQ).example(GL(3, GF(11))).group() # needs sage.groups sage.modules\n General Linear Group of degree 3 over Finite Field of size 11\n sage: SymmetricGroup(10).algebra(QQ).group() # needs sage.groups sage.modules\n Symmetric group of order 10! as a permutation group\n '
return self.basis().keys()
@cached_method
def center_basis(self):
'\n Return a basis of the center of the group algebra.\n\n The canonical basis of the center of the group algebra\n is the family `(f_\\sigma)_{\\sigma\\in C}`, where `C` is\n any collection of representatives of the conjugacy\n classes of the group, and `f_\\sigma` is the sum of the\n elements in the conjugacy class of `\\sigma`.\n\n OUTPUT:\n\n - ``tuple`` of elements of ``self``\n\n .. WARNING::\n\n - This method requires the underlying group to\n have a method ``conjugacy_classes``\n (every permutation group has one, thanks GAP!).\n\n EXAMPLES::\n\n sage: SymmetricGroup(3).algebra(QQ).center_basis() # needs sage.groups sage.modules\n ((), (2,3) + (1,2) + (1,3), (1,2,3) + (1,3,2))\n\n .. SEEALSO::\n\n - :meth:`Groups.Algebras.ElementMethods.central_form`\n - :meth:`Monoids.Algebras.ElementMethods.is_central`\n '
return tuple([self.sum_of_monomials(conj) for conj in self.basis().keys().conjugacy_classes()])
def coproduct_on_basis(self, g):
'\n Return the coproduct of the element ``g`` of the basis.\n\n Each basis element ``g`` is group-like. This method is\n used to compute the coproduct of any element.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = CyclicPermutationGroup(6).algebra(ZZ); A\n Algebra of\n Cyclic group of order 6 as a permutation group over Integer Ring\n sage: g = CyclicPermutationGroup(6).an_element(); g\n (1,2,3,4,5,6)\n sage: A.coproduct_on_basis(g)\n (1,2,3,4,5,6) # (1,2,3,4,5,6)\n sage: a = A.an_element(); a\n () + 3*(1,2,3,4,5,6) + 3*(1,3,5)(2,4,6)\n sage: a.coproduct()\n () # () + 3*(1,2,3,4,5,6) # (1,2,3,4,5,6) + 3*(1,3,5)(2,4,6) # (1,3,5)(2,4,6)\n '
from sage.categories.tensor import tensor
g = self.term(g)
return tensor([g, g])
def antipode_on_basis(self, g):
'\n Return the antipode of the element ``g`` of the basis.\n\n Each basis element ``g`` is group-like, and so has\n antipode `g^{-1}`. This method is used to compute the\n antipode of any element.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = CyclicPermutationGroup(6).algebra(ZZ); A\n Algebra of\n Cyclic group of order 6 as a permutation group over Integer Ring\n sage: g = CyclicPermutationGroup(6).an_element(); g\n (1,2,3,4,5,6)\n sage: A.antipode_on_basis(g)\n (1,6,5,4,3,2)\n sage: a = A.an_element(); a\n () + 3*(1,2,3,4,5,6) + 3*(1,3,5)(2,4,6)\n sage: a.antipode()\n () + 3*(1,5,3)(2,6,4) + 3*(1,6,5,4,3,2)\n '
return self.term((~ g))
def counit_on_basis(self, g):
'\n Return the counit of the element ``g`` of the basis.\n\n Each basis element ``g`` is group-like, and so has\n counit `1`. This method is used to compute the\n counit of any element.\n\n EXAMPLES::\n\n sage: A = CyclicPermutationGroup(6).algebra(ZZ); A # needs sage.groups sage.modules\n Algebra of\n Cyclic group of order 6 as a permutation group over Integer Ring\n sage: g = CyclicPermutationGroup(6).an_element(); g # needs sage.groups sage.modules\n (1,2,3,4,5,6)\n sage: A.counit_on_basis(g) # needs sage.groups sage.modules\n 1\n '
return self.base_ring().one()
def counit(self, x):
'\n Return the counit of the element ``x`` of the group\n algebra.\n\n This is the sum of all coefficients of ``x`` with respect\n to the standard basis of the group algebra.\n\n EXAMPLES::\n\n sage: A = CyclicPermutationGroup(6).algebra(ZZ); A # needs sage.groups sage.modules\n Algebra of\n Cyclic group of order 6 as a permutation group over Integer Ring\n sage: a = A.an_element(); a # needs sage.groups sage.modules\n () + 3*(1,2,3,4,5,6) + 3*(1,3,5)(2,4,6)\n sage: a.counit() # needs sage.groups sage.modules\n 7\n '
return self.base_ring().sum(x.coefficients())
def is_integral_domain(self, proof=True):
"\n Return ``True`` if ``self`` is an integral domain.\n\n This is false unless ``self.base_ring()`` is an integral\n domain, and even then it is false unless ``self.group()``\n has no nontrivial elements of finite order. I don't know\n if this condition suffices, but it obviously does if the\n group is abelian and finitely generated.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S2 = SymmetricGroup(2)\n sage: GroupAlgebra(S2).is_integral_domain()\n False\n sage: S1 = SymmetricGroup(1)\n sage: GroupAlgebra(S1).is_integral_domain()\n True\n sage: GroupAlgebra(S1, IntegerModRing(4)).is_integral_domain()\n False\n sage: GroupAlgebra(AbelianGroup(1)).is_integral_domain()\n True\n sage: GroupAlgebra(AbelianGroup(2, [0,2])).is_integral_domain()\n False\n sage: GroupAlgebra(GL(2, ZZ)).is_integral_domain() # not implemented\n False\n "
from sage.sets.set import Set
ans = False
try:
if self.base_ring().is_integral_domain():
if self.group().is_finite():
if (self.group().order() > 1):
ans = False
else:
ans = True
elif self.group().is_abelian():
invs = self.group().invariants()
if (Set(invs) != Set([0])):
ans = False
else:
ans = True
else:
raise NotImplementedError
else:
ans = False
except (AttributeError, NotImplementedError):
if proof:
raise NotImplementedError('cannot determine whether self is an integral domain')
return ans
class ElementMethods():
def central_form(self):
'\n Return ``self`` expressed in the canonical basis of the center\n of the group algebra.\n\n INPUT:\n\n - ``self`` -- an element of the center of the group algebra\n\n OUTPUT:\n\n - A formal linear combination of the conjugacy class\n representatives representing its coordinates in the\n canonical basis of the center. See\n :meth:`Groups.Algebras.ParentMethods.center_basis` for\n details.\n\n .. WARNING::\n\n - This method requires the underlying group to\n have a method ``conjugacy_classes_representatives``\n (every permutation group has one, thanks GAP!).\n - This method does not check that the element is\n indeed central. Use the method\n :meth:`Monoids.Algebras.ElementMethods.is_central`\n for this purpose.\n - This function has a complexity linear in the\n number of conjugacy classes of the group. One\n could easily implement a function whose\n complexity is linear in the size of the support\n of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: QS3 = SymmetricGroup(3).algebra(QQ)\n sage: A = QS3([2,3,1]) + QS3([3,1,2])\n sage: A.central_form()\n B[(1,2,3)]\n sage: QS4 = SymmetricGroup(4).algebra(QQ)\n sage: B = sum(len(s.cycle_type()) * QS4(s) for s in Permutations(4))\n sage: B.central_form()\n 4*B[()] + 3*B[(1,2)] + 2*B[(1,2)(3,4)] + 2*B[(1,2,3)] + B[(1,2,3,4)]\n\n The following test fails due to a bug involving combinatorial free modules and\n the coercion system (see :trac:`28544`)::\n\n sage: # needs sage.groups sage.modules\n sage: G = PermutationGroup([[(1,2,3),(4,5)], [(3,4)]])\n sage: QG = GroupAlgebras(QQ).example(G)\n sage: s = sum(QG.basis())\n sage: s.central_form() # not tested\n B[()] + B[(4,5)] + B[(3,4,5)] + B[(2,3)(4,5)]\n + B[(2,3,4,5)] + B[(1,2)(3,4,5)] + B[(1,2,3,4,5)]\n\n .. SEEALSO::\n\n - :meth:`Groups.Algebras.ParentMethods.center_basis`\n - :meth:`Monoids.Algebras.ElementMethods.is_central`\n '
from sage.combinat.free_module import CombinatorialFreeModule
conj_classes_reps = self.parent().basis().keys().conjugacy_classes_representatives()
Z = CombinatorialFreeModule(self.base_ring(), conj_classes_reps)
return sum(((self[i] * Z.basis()[i]) for i in Z.basis().keys()))
|
class Groupoid(CategoryWithParameters):
'\n The category of groupoids, for a set (usually a group) `G`.\n\n FIXME:\n\n - Groupoid or Groupoids ?\n - definition and link with :wikipedia:`Groupoid`\n - Should Groupoid inherit from Category_over_base?\n\n EXAMPLES::\n\n sage: Groupoid(DihedralGroup(3))\n Groupoid with underlying set Dihedral group of order 6 as a permutation group\n '
def __init__(self, G=None):
'\n TESTS::\n\n sage: S8 = SymmetricGroup(8)\n sage: C = Groupoid(S8)\n sage: TestSuite(C).run()\n '
CategoryWithParameters.__init__(self)
if (G is None):
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
G = SymmetricGroup(8)
self.__G = G
def _repr_(self):
'\n EXAMPLES::\n\n sage: S8 = SymmetricGroup(8)\n sage: Groupoid(S8)\n Groupoid with underlying set Symmetric group of order 8! as a permutation group\n '
return ('Groupoid with underlying set %s' % self.__G)
def _make_named_class_key(self, name):
'\n The parent/element classes of all groupoids coincide.\n\n EXAMPLES::\n\n sage: Groupoid(DihedralGroup(3)).parent_class is Groupoid(ZZ).parent_class\n True\n\n '
return None
def super_categories(self):
'\n EXAMPLES::\n\n sage: Groupoid(DihedralGroup(3)).super_categories()\n [Category of sets]\n '
return [Sets()]
@classmethod
def an_instance(cls):
'\n Returns an instance of this class.\n\n EXAMPLES::\n\n sage: Groupoid.an_instance() # indirect doctest\n Groupoid with underlying set Symmetric group of order 8! as a permutation group\n '
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
G = SymmetricGroup(8)
return cls(G)
|
class Groups(CategoryWithAxiom):
'\n The category of (multiplicative) groups, i.e. monoids with\n inverses.\n\n EXAMPLES::\n\n sage: Groups()\n Category of groups\n sage: Groups().super_categories()\n [Category of monoids, Category of inverse unital magmas]\n\n TESTS::\n\n sage: TestSuite(Groups()).run()\n '
_base_category_class_and_axiom = (Monoids, 'Inverse')
def example(self):
'\n EXAMPLES::\n\n sage: Groups().example() # needs sage.modules\n General Linear Group of degree 4 over Rational Field\n '
from sage.rings.rational_field import QQ
from sage.groups.matrix_gps.linear import GL
return GL(4, QQ)
@staticmethod
def free(index_set=None, names=None, **kwds):
"\n Return the free group.\n\n INPUT:\n\n - ``index_set`` -- (optional) an index set for the generators; if\n an integer, then this represents `\\{0, 1, \\ldots, n-1\\}`\n\n - ``names`` -- a string or list/tuple/iterable of strings\n (default: ``'x'``); the generator names or name prefix\n\n When the index set is an integer or only variable names are given,\n this returns :class:`~sage.groups.free_group.FreeGroup_class`, which\n currently has more features due to the interface with GAP than\n :class:`~sage.groups.indexed_free_group.IndexedFreeGroup`.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: Groups.free(index_set=ZZ)\n Free group indexed by Integer Ring\n sage: Groups().free(ZZ)\n Free group indexed by Integer Ring\n sage: Groups().free(5)\n Free Group on generators {x0, x1, x2, x3, x4}\n sage: F.<x,y,z> = Groups().free(); F\n Free Group on generators {x, y, z}\n "
from sage.rings.integer_ring import ZZ
if ((index_set in ZZ) or ((index_set is None) and (names is not None))):
from sage.groups.free_group import FreeGroup
if (names is None):
return FreeGroup(index_set, **kwds)
return FreeGroup(index_set, names, **kwds)
from sage.groups.indexed_free_group import IndexedFreeGroup
return IndexedFreeGroup(index_set, **kwds)
class ParentMethods():
def group_generators(self):
'\n Return group generators for ``self``.\n\n This default implementation calls :meth:`gens`, for\n backward compatibility.\n\n EXAMPLES::\n\n sage: A = AlternatingGroup(4) # needs sage.groups\n sage: A.group_generators() # needs sage.groups\n Family ((2,3,4), (1,2,3))\n '
from sage.sets.family import Family
try:
return Family(self.gens())
except AttributeError:
raise NotImplementedError('no generators are implemented for this group')
def monoid_generators(self):
'\n Return the generators of ``self`` as a monoid.\n\n Let `G` be a group with generating set `X`. In general, the\n generating set of `G` as a monoid is given by `X \\cup X^{-1}`,\n where `X^{-1}` is the set of inverses of `X`. If `G` is a finite\n group, then the generating set as a monoid is `X`.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: A = AlternatingGroup(4)\n sage: A.monoid_generators()\n Family ((2,3,4), (1,2,3))\n sage: F.<x,y> = FreeGroup()\n sage: F.monoid_generators()\n Family (x, y, x^-1, y^-1)\n '
G = self.group_generators()
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
if (G not in FiniteEnumeratedSets()):
raise NotImplementedError('currently only implemented for finitely generated groups')
from sage.sets.family import Family
return Family((tuple(G) + tuple(((~ x) for x in G))))
def _test_inverse(self, **options):
'\n Run generic tests on the method :meth:`.__invert__`.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: G = SymmetricGroup(3) # needs sage.groups\n sage: G._test_inverse() # needs sage.groups\n '
tester = self._tester(**options)
for x in tester.some_elements():
tester.assertEqual((x * (~ x)), self.one())
tester.assertEqual(((~ x) * x), self.one())
def semidirect_product(self, N, mapping, check=True):
'\n The semi-direct product of two groups\n\n EXAMPLES::\n\n sage: G = Groups().example() # needs sage.modules\n sage: G.semidirect_product(G, Morphism(G, G)) # needs sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: semidirect product of General Linear Group of degree 4\n over Rational Field and General Linear Group of degree 4 over Rational Field\n not yet implemented\n '
raise NotImplementedError(('semidirect product of %s and %s not yet implemented' % (self, N)))
def holomorph(self):
'\n The holomorph of a group\n\n The holomorph of a group `G` is the semidirect product\n `G \\rtimes_{id} Aut(G)`, where `id` is the identity function\n on `Aut(G)`, the automorphism group of `G`.\n\n See :wikipedia:`Holomorph (mathematics)`\n\n EXAMPLES::\n\n sage: G = Groups().example() # needs sage.modules\n sage: G.holomorph() # needs sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: holomorph of General Linear Group of degree 4\n over Rational Field not yet implemented\n '
raise NotImplementedError(('holomorph of %s not yet implemented' % self))
def cayley_table(self, names='letters', elements=None):
'\n Return the "multiplication" table of this multiplicative group,\n which is also known as the "Cayley table".\n\n .. note:: The order of the elements in the row and column\n headings is equal to the order given by the table\'s\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`\n method. The association between the actual elements and the\n names/symbols used in the table can also be retrieved as\n a dictionary with the\n :meth:`~sage.matrix.operation_table.OperationTable.translation`\n method.\n\n For groups, this routine should behave identically to the\n :meth:`~sage.categories.magmas.Magmas.ParentMethods.multiplication_table`\n method for magmas, which applies in greater generality.\n\n INPUT:\n\n - ``names`` - the type of names used, values are:\n\n * ``\'letters\'`` - lowercase ASCII letters are used\n for a base 26 representation of the elements\'\n positions in the list given by :meth:`list`,\n padded to a common width with leading \'a\'s.\n * ``\'digits\'`` - base 10 representation of the\n elements\' positions in the list given by\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`,\n padded to a common width with leading zeros.\n * ``\'elements\'`` - the string representations\n of the elements themselves.\n * a list - a list of strings, where the length\n of the list equals the number of elements.\n\n - ``elements`` - default = ``None``. A list of\n elements of the group, in forms that can be\n coerced into the structure, eg. their string\n representations. This may be used to impose an\n alternate ordering on the elements, perhaps when\n this is used in the context of a particular structure.\n The default is to use whatever ordering is provided by the\n the group, which is reported by the\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`\n method. Or the ``elements`` can be a subset\n which is closed under the operation. In particular,\n this can be used when the base set is infinite.\n\n OUTPUT:\n\n An object representing the multiplication table. This is\n an :class:`~sage.matrix.operation_table.OperationTable` object\n and even more documentation can be found there.\n\n EXAMPLES:\n\n Permutation groups, matrix groups and abelian groups\n can all compute their multiplication tables. ::\n\n sage: # needs sage.groups\n sage: G = DiCyclicGroup(3)\n sage: T = G.cayley_table()\n sage: T.column_keys()\n ((), (5,6,7), ..., (1,4,2,3)(5,7))\n sage: T\n * a b c d e f g h i j k l\n +------------------------\n a| a b c d e f g h i j k l\n b| b c a e f d i g h l j k\n c| c a b f d e h i g k l j\n d| d e f a b c j k l g h i\n e| e f d b c a l j k i g h\n f| f d e c a b k l j h i g\n g| g h i j k l d e f a b c\n h| h i g k l j f d e c a b\n i| i g h l j k e f d b c a\n j| j k l g h i a b c d e f\n k| k l j h i g c a b f d e\n l| l j k i g h b c a e f d\n\n ::\n\n sage: M = SL(2, 2) # needs sage.modules\n sage: M.cayley_table() # needs sage.modules\n * a b c d e f\n +------------\n a| a b c d e f\n b| b a d c f e\n c| c e a f b d\n d| d f b e a c\n e| e c f a d b\n f| f d e b c a\n <BLANKLINE>\n\n ::\n\n sage: A = AbelianGroup([2, 3]) # needs sage.groups\n sage: A.cayley_table() # needs sage.groups\n * a b c d e f\n +------------\n a| a b c d e f\n b| b c a e f d\n c| c a b f d e\n d| d e f a b c\n e| e f d b c a\n f| f d e c a b\n\n Lowercase ASCII letters are the default symbols used\n for the table, but you can also specify the use of\n decimal digit strings, or provide your own strings\n (in the proper order if they have meaning).\n Also, if the elements themselves are not too complex,\n you can choose to just use the string representations\n of the elements themselves. ::\n\n sage: C = CyclicPermutationGroup(11) # needs sage.groups\n sage: C.cayley_table(names=\'digits\') # needs sage.groups\n * 00 01 02 03 04 05 06 07 08 09 10\n +---------------------------------\n 00| 00 01 02 03 04 05 06 07 08 09 10\n 01| 01 02 03 04 05 06 07 08 09 10 00\n 02| 02 03 04 05 06 07 08 09 10 00 01\n 03| 03 04 05 06 07 08 09 10 00 01 02\n 04| 04 05 06 07 08 09 10 00 01 02 03\n 05| 05 06 07 08 09 10 00 01 02 03 04\n 06| 06 07 08 09 10 00 01 02 03 04 05\n 07| 07 08 09 10 00 01 02 03 04 05 06\n 08| 08 09 10 00 01 02 03 04 05 06 07\n 09| 09 10 00 01 02 03 04 05 06 07 08\n 10| 10 00 01 02 03 04 05 06 07 08 09\n\n ::\n\n sage: G = QuaternionGroup() # needs sage.groups\n sage: names = [\'1\', \'I\', \'-1\', \'-I\', \'J\', \'-K\', \'-J\', \'K\']\n sage: G.cayley_table(names=names) # needs sage.groups\n * 1 I -1 -I J -K -J K\n +------------------------\n 1| 1 I -1 -I J -K -J K\n I| I -1 -I 1 K J -K -J\n -1| -1 -I 1 I -J K J -K\n -I| -I 1 I -1 -K -J K J\n J| J -K -J K -1 -I 1 I\n -K| -K -J K J I -1 -I 1\n -J| -J K J -K 1 I -1 -I\n K| K J -K -J -I 1 I -1\n\n ::\n\n sage: A = AbelianGroup([2, 2]) # needs sage.groups\n sage: A.cayley_table(names=\'elements\') # needs sage.groups\n * 1 f1 f0 f0*f1\n +------------------------\n 1| 1 f1 f0 f0*f1\n f1| f1 1 f0*f1 f0\n f0| f0 f0*f1 1 f1\n f0*f1| f0*f1 f0 f1 1\n\n The :meth:`~sage.matrix.operation_table.OperationTable.change_names`\n routine behaves similarly, but changes an existing table "in-place."\n ::\n\n sage: # needs sage.groups\n sage: G = AlternatingGroup(3)\n sage: T = G.cayley_table()\n sage: T.change_names(\'digits\')\n sage: T\n * 0 1 2\n +------\n 0| 0 1 2\n 1| 1 2 0\n 2| 2 0 1\n\n For an infinite group, you can still work with finite sets of\n elements, provided the set is closed under multiplication.\n Elements will be coerced into the group as part of setting\n up the table. ::\n\n sage: # needs sage.modules\n sage: G = SL(2,ZZ); G\n Special Linear Group of degree 2 over Integer Ring\n sage: identity = matrix(ZZ, [[1,0], [0,1]])\n sage: G.cayley_table(elements=[identity, -identity])\n * a b\n +----\n a| a b\n b| b a\n\n The\n :class:`~sage.matrix.operation_table.OperationTable`\n class provides even greater flexibility, including changing\n the operation. Here is one such example, illustrating the\n computation of commutators. ``commutator`` is defined as\n a function of two variables, before being used to build\n the table. From this, the commutator subgroup seems obvious,\n and creating a Cayley table with just these three elements\n confirms that they form a closed subset in the group.\n ::\n\n sage: # needs sage.groups sage.modules\n sage: from sage.matrix.operation_table import OperationTable\n sage: G = DiCyclicGroup(3)\n sage: commutator = lambda x, y: x*y*x^-1*y^-1\n sage: T = OperationTable(G, commutator); T\n . a b c d e f g h i j k l\n +------------------------\n a| a a a a a a a a a a a a\n b| a a a a a a c c c c c c\n c| a a a a a a b b b b b b\n d| a a a a a a a a a a a a\n e| a a a a a a c c c c c c\n f| a a a a a a b b b b b b\n g| a b c a b c a c b a c b\n h| a b c a b c b a c b a c\n i| a b c a b c c b a c b a\n j| a b c a b c a c b a c b\n k| a b c a b c b a c b a c\n l| a b c a b c c b a c b a\n sage: trans = T.translation()\n sage: comm = [trans[\'a\'], trans[\'b\'], trans[\'c\']]\n sage: comm\n [(), (5,6,7), (5,7,6)]\n sage: P = G.cayley_table(elements=comm)\n sage: P\n * a b c\n +------\n a| a b c\n b| b c a\n c| c a b\n\n .. TODO::\n\n Arrange an ordering of elements into cosets of a normal\n subgroup close to size `\\sqrt{n}`. Then the quotient\n group structure is often apparent in the table. See\n comments on :trac:`7555`.\n\n AUTHOR:\n\n - Rob Beezer (2010-03-15)\n\n '
from sage.matrix.operation_table import OperationTable
import operator
return OperationTable(self, operation=operator.mul, names=names, elements=elements)
def conjugacy_class(self, g):
"\n Return the conjugacy class of the element ``g``.\n\n This is a fall-back method for groups not defined over GAP.\n\n EXAMPLES::\n\n sage: A = AbelianGroup([2, 2]) # needs sage.groups\n sage: c = A.conjugacy_class(A.an_element()) # needs sage.groups\n sage: type(c) # needs sage.groups\n <class 'sage.groups.conjugacy_classes.ConjugacyClass_with_category'>\n "
from sage.groups.conjugacy_classes import ConjugacyClass
return ConjugacyClass(self, g)
class ElementMethods():
def conjugacy_class(self):
'\n Return the conjugacy class of ``self``.\n\n EXAMPLES::\n\n sage: D = DihedralGroup(5) # needs sage.groups\n sage: g = D((1,3,5,2,4)) # needs sage.groups\n sage: g.conjugacy_class() # needs sage.groups\n Conjugacy class of (1,3,5,2,4)\n in Dihedral group of order 10 as a permutation group\n\n sage: H = MatrixGroup([matrix(GF(5), 2, [1,2, -1,1]), # needs sage.modules\n ....: matrix(GF(5), 2, [1,1, 0,1])])\n sage: h = H(matrix(GF(5), 2, [1,2, -1,1])) # needs sage.modules\n sage: h.conjugacy_class() # needs sage.groups sage.modules\n Conjugacy class of [1 2]\n [4 1]\n in Matrix group over Finite Field of size 5 with 2 generators (\n [1 2] [1 1]\n [4 1], [0 1]\n )\n\n sage: G = SL(2, GF(2)) # needs sage.modules\n sage: g = G.gens()[0] # needs sage.modules\n sage: g.conjugacy_class() # needs sage.modules\n Conjugacy class of [1 1]\n [0 1] in Special Linear Group of degree 2 over Finite Field of size 2\n\n sage: G = SL(2, QQ) # needs sage.modules\n sage: g = G([[1,1], [0,1]]) # needs sage.modules\n sage: g.conjugacy_class() # needs sage.groups sage.modules\n Conjugacy class of [1 1]\n [0 1] in Special Linear Group of degree 2 over Rational Field\n '
return self.parent().conjugacy_class(self)
Finite = LazyImport('sage.categories.finite_groups', 'FiniteGroups', at_startup=True)
Lie = LazyImport('sage.categories.lie_groups', 'LieGroups', 'Lie')
Algebras = LazyImport('sage.categories.group_algebras', 'GroupAlgebras', at_startup=True)
class Commutative(CategoryWithAxiom):
'\n Category of commutative (abelian) groups.\n\n A group `G` is *commutative* if `xy = yx` for all `x,y \\in G`.\n '
@staticmethod
def free(index_set=None, names=None, **kwds):
"\n Return the free commutative group.\n\n INPUT:\n\n - ``index_set`` -- (optional) an index set for the generators; if\n an integer, then this represents `\\{0, 1, \\ldots, n-1\\}`\n\n - ``names`` -- a string or list/tuple/iterable of strings\n (default: ``'x'``); the generator names or name prefix\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: Groups.Commutative.free(index_set=ZZ)\n Free abelian group indexed by Integer Ring\n sage: Groups().Commutative().free(ZZ)\n Free abelian group indexed by Integer Ring\n sage: Groups().Commutative().free(5)\n Multiplicative Abelian group isomorphic to Z x Z x Z x Z x Z\n sage: F.<x,y,z> = Groups().Commutative().free(); F\n Multiplicative Abelian group isomorphic to Z x Z x Z\n "
from sage.rings.integer_ring import ZZ
if (names is not None):
if isinstance(names, str):
if ((',' not in names) and (index_set in ZZ)):
names = [(names + repr(i)) for i in range(index_set)]
else:
names = names.split(',')
names = tuple(names)
if (index_set is None):
index_set = ZZ(len(names))
if (index_set in ZZ):
from sage.groups.abelian_gps.abelian_group import AbelianGroup
return AbelianGroup(index_set, names=names, **kwds)
if (index_set in ZZ):
from sage.groups.abelian_gps.abelian_group import AbelianGroup
return AbelianGroup(index_set, **kwds)
from sage.groups.indexed_free_group import IndexedFreeAbelianGroup
return IndexedFreeAbelianGroup(index_set, names=names, **kwds)
class CartesianProducts(CartesianProductsCategory):
'\n The category of groups constructed as Cartesian products of groups.\n\n This construction gives the direct product of groups. See\n :wikipedia:`Direct_product` and :wikipedia:`Direct_product_of_groups`\n for more information.\n '
def extra_super_categories(self):
'\n A Cartesian product of groups is endowed with a natural\n group structure.\n\n EXAMPLES::\n\n sage: C = Groups().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of groups]\n sage: sorted(C.super_categories(), key=str)\n [Category of Cartesian products of inverse unital magmas,\n Category of Cartesian products of monoids,\n Category of groups]\n '
return [self.base_category()]
class ParentMethods():
@cached_method
def group_generators(self):
'\n Return the group generators of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: C5 = CyclicPermutationGroup(5)\n sage: C4 = CyclicPermutationGroup(4)\n sage: S4 = SymmetricGroup(3)\n sage: C = cartesian_product([C5, C4, S4])\n sage: C.group_generators()\n Family (((1,2,3,4,5), (), ()),\n ((), (1,2,3,4), ()),\n ((), (), (1,2)),\n ((), (), (2,3)))\n\n We check the other portion of :trac:`16718` is fixed::\n\n sage: len(C.j_classes()) # needs sage.groups\n 1\n\n An example with an infinitely generated group (a better output\n is needed)::\n\n sage: # needs sage.groups\n sage: G = Groups.free([1,2])\n sage: H = Groups.free(ZZ)\n sage: C = cartesian_product([G, H])\n sage: C.monoid_generators()\n Lazy family (gen(i))_{i in The Cartesian product of (...)}\n '
F = self.cartesian_factors()
ids = tuple((G.one() for G in F))
def lift(i, gen):
cur = list(ids)
cur[i] = gen
return self._cartesian_product_of_elements(cur)
from sage.sets.family import Family
cat = FiniteEnumeratedSets()
if all((((G.group_generators() in cat) or isinstance(G.group_generators(), (tuple, list))) for G in F)):
ret = [lift(i, gen) for (i, G) in enumerate(F) for gen in G.group_generators()]
return Family(ret)
gens_prod = cartesian_product([Family(G.group_generators(), (lambda g: (i, g))) for (i, G) in enumerate(F)])
return Family(gens_prod, lift, name='gen')
def order(self):
"\n Return the cardinality of self.\n\n EXAMPLES::\n\n sage: C = cartesian_product([SymmetricGroup(10), SL(2, GF(3))]) # needs sage.groups sage.rings.finite_rings\n sage: C.order() # needs sage.groups sage.rings.finite_rings\n 87091200\n\n TESTS::\n\n sage: C.order.__module__ # needs sage.groups sage.rings.finite_rings\n 'sage.categories.groups'\n\n .. TODO::\n\n this method is just here to prevent\n ``FiniteGroups.ParentMethods`` to call\n ``_cardinality_from_iterator``.\n "
from sage.misc.misc_c import prod
return prod((c.cardinality() for c in self.cartesian_factors()))
class Topological(TopologicalSpacesCategory):
'\n Category of topological groups.\n\n A topological group `G` is a group which has a topology such that\n multiplication and taking inverses are continuous functions.\n\n REFERENCES:\n\n - :wikipedia:`Topological_group`\n '
|
class HTrivialSemigroups(CategoryWithAxiom):
def Finite_extra_super_categories(self):
'\n Implement the fact that a finite `H`-trivial is aperiodic\n\n EXAMPLES::\n\n sage: Semigroups().HTrivial().Finite_extra_super_categories()\n [Category of aperiodic semigroups]\n sage: Semigroups().HTrivial().Finite() is Semigroups().Aperiodic().Finite()\n True\n '
return [Semigroups().Aperiodic()]
def Inverse_extra_super_categories(self):
'\n Implement the fact that an `H`-trivial inverse semigroup is `J`-trivial.\n\n .. TODO::\n\n Generalization for inverse semigroups.\n\n Recall that there are two invertibility axioms for a semigroup `S`:\n\n - One stating the existence, for all `x`, of a local inverse\n `y` satisfying `x=xyx` and `y=yxy`;\n - One stating the existence, for all `x`, of a global\n inverse `y` satisfying `xy=yx=1`, where `1` is the unit\n of `S` (which must of course exist).\n\n It is sufficient to have local inverses for `H`-triviality\n to imply `J`-triviality. However, at this stage, only the\n second axiom is implemented in Sage (see\n :meth:`Magmas.Unital.SubcategoryMethods.Inverse`). Therefore\n this fact is only implemented for semigroups with global\n inverses, that is groups. However the trivial group is the\n unique `H`-trivial group, so this is rather boring.\n\n EXAMPLES::\n\n sage: Semigroups().HTrivial().Inverse_extra_super_categories()\n [Category of j trivial semigroups]\n sage: Monoids().HTrivial().Inverse()\n Category of h trivial groups\n '
return [self.JTrivial()]
|
class HeckeModules(Category_module):
"\n The category of Hecke modules.\n\n A Hecke module is a module `M` over the \\emph{anemic} Hecke\n algebra, i.e., the Hecke algebra generated by Hecke operators\n `T_n` with `n` coprime to the level of `M`. (Every Hecke module\n defines a level function, which is a positive integer.) The\n reason we require that `M` only be a module over the anemic Hecke\n algebra is that many natural maps, e.g., degeneracy maps,\n Atkin-Lehner operators, etc., are `\\Bold{T}`-module homomorphisms; but\n they are homomorphisms over the anemic Hecke algebra.\n\n EXAMPLES:\n\n We create the category of Hecke modules over `\\QQ`::\n\n sage: C = HeckeModules(RationalField()); C\n Category of Hecke modules over Rational Field\n\n TODO: check that this is what we want::\n\n sage: C.super_categories()\n [Category of vector spaces with basis over Rational Field]\n\n # [Category of vector spaces over Rational Field]\n\n Note that the base ring can be an arbitrary commutative ring::\n\n sage: HeckeModules(IntegerRing())\n Category of Hecke modules over Integer Ring\n sage: HeckeModules(FiniteField(5))\n Category of Hecke modules over Finite Field of size 5\n\n The base ring doesn't have to be a principal ideal domain::\n\n sage: HeckeModules(PolynomialRing(IntegerRing(), 'x'))\n Category of Hecke modules over Univariate Polynomial Ring in x over Integer Ring\n\n TESTS::\n\n sage: TestSuite(HeckeModules(ZZ)).run()\n "
def __init__(self, R):
'\n TESTS::\n\n sage: TestSuite(HeckeModules(ZZ)).run()\n\n sage: HeckeModules(Partitions(3)).run() # needs sage.combinat\n Traceback (most recent call last):\n ...\n TypeError: R (=Partitions of the integer 3) must be a commutative ring\n '
from .commutative_rings import CommutativeRings
if (R not in CommutativeRings()):
raise TypeError(('R (=%s) must be a commutative ring' % R))
Category_module.__init__(self, R)
def super_categories(self):
'\n EXAMPLES::\n\n sage: HeckeModules(QQ).super_categories()\n [Category of vector spaces with basis over Rational Field]\n '
R = self.base_ring()
return [ModulesWithBasis(R)]
def _repr_object_names(self):
"\n Return the names of the objects of this category.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`\n\n EXAMPLES::\n\n sage: HeckeModules(QQ)._repr_object_names()\n 'Hecke modules over Rational Field'\n sage: HeckeModules(QQ)\n Category of Hecke modules over Rational Field\n "
return 'Hecke modules over {}'.format(self.base())
class ParentMethods():
def _Hom_(self, Y, category):
'\n Return the homset from ``self`` to ``Y`` in the category ``category``\n\n INPUT:\n\n - ``Y`` -- an Hecke module\n - ``category`` -- a subcategory of :class:`HeckeModules()\n <HeckeModules>` or ``None``\n\n The sole purpose of this method is to construct the homset\n as a :class:`~sage.modular.hecke.homspace.HeckeModuleHomspace`. If\n ``category`` is specified and is not a subcategory of\n :class:`HeckeModules`, a :class:`TypeError` is raised instead\n\n This method is not meant to be called directly. Please use\n :func:`sage.categories.homset.Hom` instead.\n\n EXAMPLES::\n\n sage: # needs sage.modular\n sage: M = ModularForms(Gamma0(7), 4)\n sage: H = M._Hom_(M, category=HeckeModules(QQ)); H\n Set of Morphisms\n from Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(7) of weight 4 over Rational Field\n to Modular Forms space of dimension 3 for Congruence Subgroup Gamma0(7) of weight 4 over Rational Field\n in Category of Hecke modules over Rational Field\n sage: H.__class__\n <class \'sage.modular.hecke.homspace.HeckeModuleHomspace_with_category\'>\n sage: TestSuite(H).run(skip=["_test_elements", "_test_an_element", "_test_elements_eq",\n ....: "_test_elements_eq_reflexive", "_test_elements_eq_transitive",\n ....: "_test_elements_eq_symmetric", "_test_elements_neq", "_test_some_elements",\n ....: "_test_zero", "_test_additive_associativity",\n ....: "_test_one", "_test_associativity", "_test_prod"])\n\n Fixing :meth:`_test_zero` (``__call__`` should accept a\n function as input) and :meth:`_test_elements*` (modular\n form morphisms elements should inherit from categories) is\n :trac:`12879`.\n\n TESTS::\n\n sage: H = M._Hom_(M, category=HeckeModules(GF(5))); H # needs sage.modular sage.rings.finite_rings\n Traceback (most recent call last):\n ...\n TypeError: Category of Hecke modules over Finite Field of size 5\n is not a subcategory of Category of Hecke modules over Rational Field\n '
if ((category is not None) and (not category.is_subcategory(HeckeModules(self.base_ring())))):
raise TypeError(('%s is not a subcategory of %s' % (category, HeckeModules(self.base_ring()))))
from sage.modular.hecke.homspace import HeckeModuleHomspace
return HeckeModuleHomspace(self, Y, category=category)
class Homsets(HomsetsCategory):
'\n TESTS::\n\n sage: TestSuite(HeckeModules(ZZ).Homsets()).run()\n\n sage: HeckeModules(QQ).Homsets().base_ring()\n Rational Field\n '
def extra_super_categories(self):
'\n TESTS:\n\n Check that Hom sets of Hecke modules are in the correct\n category (see :trac:`17359`)::\n\n sage: HeckeModules(ZZ).Homsets().super_categories()\n [Category of modules over Integer Ring, Category of homsets]\n sage: HeckeModules(QQ).Homsets().super_categories()\n [Category of vector spaces over Rational Field, Category of homsets]\n '
from sage.categories.modules import Modules
return [Modules(self.base_category().base_ring())]
class ParentMethods():
pass
|
class HighestWeightCrystals(Category_singleton):
'\n The category of highest weight crystals.\n\n A crystal is highest weight if it is acyclic; in particular, every\n connected component has a unique highest weight element, and that\n element generate the component.\n\n EXAMPLES::\n\n sage: C = HighestWeightCrystals()\n sage: C\n Category of highest weight crystals\n sage: C.super_categories()\n [Category of crystals]\n sage: C.example()\n Highest weight crystal of type A_3 of highest weight omega_1\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: B = HighestWeightCrystals().example()\n sage: TestSuite(B).run(verbose = True)\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_enumerated_set_contains() . . . pass\n running ._test_enumerated_set_iter_cardinality() . . . pass\n running ._test_enumerated_set_iter_list() . . . pass\n running ._test_eq() . . . pass\n running ._test_fast_iter() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n running ._test_stembridge_local_axioms() . . . pass\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: HighestWeightCrystals().super_categories()\n [Category of crystals]\n '
return [Crystals()]
def example(self):
'\n Returns an example of highest weight crystals, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: B = HighestWeightCrystals().example(); B\n Highest weight crystal of type A_3 of highest weight omega_1\n '
from sage.categories.crystals import Crystals
return Crystals().example()
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of highest weight crystals defines no\n additional structure: it only guarantees the existence of a\n unique highest weight element in each component.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: HighestWeightCrystals().additional_structure()\n '
return None
class ParentMethods():
@cached_method
def highest_weight_vectors(self):
"\n Returns the highest weight vectors of ``self``\n\n This default implementation selects among the module\n generators those that are highest weight, and caches the result.\n A crystal element `b` is highest weight if `e_i(b)=0` for all `i` in the\n index set.\n\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C.highest_weight_vectors()\n (1,)\n\n ::\n\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(C, C, C, generators=[[C(2),C(1),C(1)],\n ....: [C(1),C(2),C(1)]])\n sage: T.highest_weight_vectors()\n ([2, 1, 1], [1, 2, 1])\n "
return tuple((g for g in self.module_generators if g.is_highest_weight()))
def highest_weight_vector(self):
"\n Returns the highest weight vector if there is a single one;\n otherwise, raises an error.\n\n Caveat: this assumes that :meth:`.highest_weight_vectors`\n returns a list or tuple.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C.highest_weight_vector()\n 1\n "
hw = self.highest_weight_vectors()
if (len(hw) == 1):
return hw[0]
else:
raise RuntimeError('The crystal does not have exactly one highest weight vector')
@cached_method
def lowest_weight_vectors(self):
"\n Return the lowest weight vectors of ``self``.\n\n This default implementation selects among all elements of the crystal\n those that are lowest weight, and cache the result.\n A crystal element `b` is lowest weight if `f_i(b)=0` for all `i` in the\n index set.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C.lowest_weight_vectors()\n (6,)\n\n ::\n\n sage: C = crystals.Letters(['A',2])\n sage: T = crystals.TensorProduct(C, C, C,generators=[[C(2),C(1),C(1)],\n ....: [C(1),C(2),C(1)]])\n sage: T.lowest_weight_vectors()\n ([3, 2, 3], [3, 3, 2])\n "
return tuple((g for g in self if g.is_lowest_weight()))
def __iter__(self, index_set=None, max_depth=float('inf')):
"\n Return the iterator of ``self``.\n\n INPUT:\n\n - ``index_set`` -- (Default: ``None``) The index set; if ``None``\n then use the index set of the crystal\n\n - ``max_depth`` -- (Default: infinity) The maximum depth to build\n\n EXAMPLES::\n\n sage: C = crystals.LSPaths(['A',2,1],[0,1,0])\n sage: sorted([p for p in C.__iter__(max_depth=3)], key=str)\n [(-Lambda[0] + 2*Lambda[2] - delta,),\n (-Lambda[0] + Lambda[1] + 1/2*Lambda[2] - delta, Lambda[0] - 1/2*Lambda[2]),\n (1/2*Lambda[0] + Lambda[1] - Lambda[2] - 1/2*delta, -1/2*Lambda[0] + Lambda[2] - 1/2*delta),\n (2*Lambda[0] - Lambda[2],),\n (Lambda[0] - Lambda[1] + Lambda[2],),\n (Lambda[1],)]\n sage: [p for p in C.__iter__(index_set=[0, 1], max_depth=3)]\n [(Lambda[1],), (Lambda[0] - Lambda[1] + Lambda[2],), (-Lambda[0] + 2*Lambda[2] - delta,)]\n "
if (index_set is None):
index_set = self.index_set()
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
return RecursivelyEnumeratedSet(self.module_generators, (lambda x: [x.f(i) for i in index_set]), structure='graded', max_depth=max_depth).breadth_first_search_iterator()
@cached_method
def q_dimension(self, q=None, prec=None, use_product=False):
"\n Return the `q`-dimension of ``self``.\n\n Let `B(\\lambda)` denote a highest weight crystal. Recall that\n the degree of the `\\mu`-weight space of `B(\\lambda)` (under\n the principal gradation) is equal to\n `\\langle \\rho^{\\vee}, \\lambda - \\mu \\rangle` where\n `\\langle \\rho^{\\vee}, \\alpha_i \\rangle = 1` for all `i \\in I`\n (in particular, take `\\rho^{\\vee} = \\sum_{i \\in I} h_i`).\n\n The `q`-dimension of a highest weight crystal `B(\\lambda)` is\n defined as\n\n .. MATH::\n\n \\dim_q B(\\lambda) := \\sum_{j \\geq 0} \\dim(B_j) q^j,\n\n where `B_j` denotes the degree `j` portion of `B(\\lambda)`. This\n can be expressed as the product\n\n .. MATH::\n\n \\dim_q B(\\lambda) = \\prod_{\\alpha^{\\vee} \\in \\Delta_+^{\\vee}}\n \\left( \\frac{1 - q^{\\langle \\lambda + \\rho, \\alpha^{\\vee}\n \\rangle}}{1 - q^{\\langle \\rho, \\alpha^{\\vee} \\rangle}}\n \\right)^{\\mathrm{mult}\\, \\alpha},\n\n where `\\Delta_+^{\\vee}` denotes the set of positive coroots.\n Taking the limit as `q \\to 1` gives the dimension of `B(\\lambda)`.\n For more information, see [Ka1990]_ Section 10.10.\n\n INPUT:\n\n - ``q`` -- the (generic) parameter `q`\n\n - ``prec`` -- (default: ``None``) The precision of the power\n series ring to use if the crystal is not known to be finite\n (i.e. the number of terms returned).\n If ``None``, then the result is returned as a lazy power series.\n\n - ``use_product`` -- (default: ``False``) if we have a finite\n crystal and ``True``, use the product formula\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux(['A',2], shape=[2,1])\n sage: qdim = C.q_dimension(); qdim\n q^4 + 2*q^3 + 2*q^2 + 2*q + 1\n sage: qdim(1)\n 8\n sage: len(C) == qdim(1)\n True\n sage: C.q_dimension(use_product=True) == qdim\n True\n sage: C.q_dimension(prec=20)\n q^4 + 2*q^3 + 2*q^2 + 2*q + 1\n sage: C.q_dimension(prec=2)\n 2*q + 1\n\n sage: R.<t> = QQ[]\n sage: C.q_dimension(q=t^2)\n t^8 + 2*t^6 + 2*t^4 + 2*t^2 + 1\n\n sage: C = crystals.Tableaux(['A',2], shape=[5,2])\n sage: C.q_dimension()\n q^10 + 2*q^9 + 4*q^8 + 5*q^7 + 6*q^6 + 6*q^5\n + 6*q^4 + 5*q^3 + 4*q^2 + 2*q + 1\n\n sage: C = crystals.Tableaux(['B',2], shape=[2,1])\n sage: qdim = C.q_dimension(); qdim\n q^10 + 2*q^9 + 3*q^8 + 4*q^7 + 5*q^6 + 5*q^5\n + 5*q^4 + 4*q^3 + 3*q^2 + 2*q + 1\n sage: qdim == C.q_dimension(use_product=True)\n True\n\n sage: C = crystals.Tableaux(['D',4], shape=[2,1])\n sage: C.q_dimension()\n q^16 + 2*q^15 + 4*q^14 + 7*q^13 + 10*q^12 + 13*q^11\n + 16*q^10 + 18*q^9 + 18*q^8 + 18*q^7 + 16*q^6 + 13*q^5\n + 10*q^4 + 7*q^3 + 4*q^2 + 2*q + 1\n\n We check with a finite tensor product::\n\n sage: TP = crystals.TensorProduct(C, C)\n sage: TP.cardinality()\n 25600\n sage: qdim = TP.q_dimension(use_product=True); qdim # long time\n q^32 + 2*q^31 + 8*q^30 + 15*q^29 + 34*q^28 + 63*q^27 + 110*q^26\n + 175*q^25 + 276*q^24 + 389*q^23 + 550*q^22 + 725*q^21\n + 930*q^20 + 1131*q^19 + 1362*q^18 + 1548*q^17 + 1736*q^16\n + 1858*q^15 + 1947*q^14 + 1944*q^13 + 1918*q^12 + 1777*q^11\n + 1628*q^10 + 1407*q^9 + 1186*q^8 + 928*q^7 + 720*q^6\n + 498*q^5 + 342*q^4 + 201*q^3 + 117*q^2 + 48*q + 26\n sage: qdim(1) # long time\n 25600\n sage: TP.q_dimension() == qdim # long time\n True\n\n The `q`-dimensions of infinite crystals are returned\n as formal power series::\n\n sage: C = crystals.LSPaths(['A',2,1], [1,0,0])\n sage: C.q_dimension(prec=5)\n 1 + q + 2*q^2 + 2*q^3 + 4*q^4 + O(q^5)\n sage: C.q_dimension(prec=10)\n 1 + q + 2*q^2 + 2*q^3 + 4*q^4 + 5*q^5 + 7*q^6\n + 9*q^7 + 13*q^8 + 16*q^9 + O(q^10)\n sage: qdim = C.q_dimension(); qdim\n 1 + q + 2*q^2 + 2*q^3 + 4*q^4 + 5*q^5 + 7*q^6 + O(q^7)\n sage: qdim[:16]\n [1, 1, 2, 2, 4, 5, 7, 9, 13, 16, 22, 27, 36, 44, 57, 70]\n "
from sage.rings.integer_ring import ZZ
WLR = self.weight_lattice_realization()
I = self.index_set()
mg = self.highest_weight_vectors()
max_deg = (float('inf') if (prec is None) else (prec - 1))
def iter_by_deg(gens):
next = set(gens)
deg = (- 1)
while (next and (deg < max_deg)):
deg += 1
(yield len(next))
todo = next
next = set()
while todo:
x = todo.pop()
for i in I:
y = x.f(i)
if (y is not None):
next.add(y)
from sage.categories.finite_crystals import FiniteCrystals
if (self in FiniteCrystals()):
if (q is None):
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
q = PolynomialRing(ZZ, 'q').gen(0)
if use_product:
pos_coroots = [x.associated_coroot() for x in WLR.positive_roots()]
rho = WLR.rho()
P = q.parent()
ret = P.zero()
for v in self.highest_weight_vectors():
hw = v.weight()
ret += P.prod((((1 - (q ** (rho + hw).scalar(ac))) / (1 - (q ** rho.scalar(ac)))) for ac in pos_coroots))
return P(ret)
elif (prec is None):
from sage.rings.lazy_series_ring import LazyPowerSeriesRing
if (q is None):
P = LazyPowerSeriesRing(ZZ, names='q')
else:
P = q.parent()
if (not isinstance(P, LazyPowerSeriesRing)):
raise TypeError('the parent of q must be a lazy power series ring')
ret = P(iter_by_deg(mg))
return ret
from sage.rings.power_series_ring import PowerSeriesRing, PowerSeriesRing_generic
if (q is None):
q = PowerSeriesRing(ZZ, 'q', default_prec=prec).gen(0)
P = q.parent()
ret = P.sum(((c * (q ** deg)) for (deg, c) in enumerate(iter_by_deg(mg))))
if ((ret.degree() == max_deg) and isinstance(P, PowerSeriesRing_generic)):
ret = P(ret, prec)
return ret
connected_components_generators = highest_weight_vectors
def _Hom_(self, Y, category=None, **options):
"\n Return the homset from ``self`` to ``Y`` in the\n category ``category``.\n\n INPUT:\n\n - ``Y`` -- a crystal\n - ``category`` -- a subcategory of :class:`HighestWeightCrysals`()\n or ``None``\n\n The sole purpose of this method is to construct the homset as a\n :class:`~sage.categories.highest_weight_crystals.HighestWeightCrystalHomset`.\n If ``category`` is specified and is not a subcategory of\n :class:`HighestWeightCrystals`, a :class:`TypeError` is raised\n instead\n\n This method is not meant to be called directly. Please use\n :func:`sage.categories.homset.Hom` instead.\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux(['A',2], shape=[2,1])\n sage: H = B._Hom_(B)\n sage: H\n Set of Crystal Morphisms from The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n to The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n sage: type(H)\n <class 'sage.categories.highest_weight_crystals.HighestWeightCrystalHomset_with_category'>\n\n TESTS:\n\n Check that we fallback first to trying a crystal homset\n (:trac:`19458`)::\n\n sage: Binf = crystals.infinity.Tableaux(['A',2])\n sage: Bi = crystals.elementary.Elementary(Binf.cartan_type(), 1)\n sage: tens = Bi.tensor(Binf)\n sage: Hom(Binf, tens)\n Set of Crystal Morphisms from ...\n "
if (category is None):
category = self.category()
elif (not category.is_subcategory(Crystals())):
raise TypeError('{} is not a subcategory of Crystals()'.format(category))
if (Y not in Crystals()):
raise TypeError('{} is not a crystal'.format(Y))
return HighestWeightCrystalHomset(self, Y, category=category, **options)
def digraph(self, subset=None, index_set=None, depth=None):
"\n Return the DiGraph associated to ``self``.\n\n INPUT:\n\n - ``subset`` -- (optional) a subset of vertices for\n which the digraph should be constructed\n\n - ``index_set`` -- (optional) the index set to draw arrows\n\n - ``depth`` -- the depth to draw; optional only for finite crystals\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: T.digraph()\n Digraph on 8 vertices\n sage: S = T.subcrystal(max_depth=2)\n sage: len(S)\n 5\n sage: G = T.digraph(subset=list(S))\n sage: G.is_isomorphic(T.digraph(depth=2), edge_labels=True)\n True\n\n TESTS:\n\n The following example demonstrates the speed improvement.\n The speedup in non-affine types is small however::\n\n sage: depth = 5\n sage: C = crystals.AlcovePaths(['A',2,1], [1,1,0])\n sage: general_digraph = Crystals().parent_class.digraph\n sage: S = C.subcrystal(max_depth=depth, direction='lower')\n sage: %timeit C.digraph(depth=depth) # not tested\n 10 loops, best of 3: 48.9 ms per loop\n sage: %timeit general_digraph(C, subset=S) # not tested\n 10 loops, best of 3: 96.5 ms per loop\n sage: G1 = C.digraph(depth=depth)\n sage: G2 = general_digraph(C, subset=S)\n sage: G1.is_isomorphic(G2, edge_labels=True)\n True\n "
if (subset is not None):
return Crystals().parent_class.digraph(self, subset, index_set)
if ((self not in Crystals().Finite()) and (depth is None)):
raise NotImplementedError('crystals not known to be finite must specify either the subset or depth')
from sage.graphs.digraph import DiGraph
if (index_set is None):
index_set = self.index_set()
rank = 0
d = {g: {} for g in self.module_generators}
visited = set(d.keys())
while ((depth is None) or (rank < depth)):
recently_visited = set()
for x in visited:
d.setdefault(x, {})
for i in index_set:
xfi = x.f(i)
if (xfi is not None):
d[x][xfi] = i
recently_visited.add(xfi)
if (not recently_visited):
break
rank += 1
visited = recently_visited
G = DiGraph(d)
from sage.graphs.dot2tex_utils import have_dot2tex
if have_dot2tex():
G.set_latex_options(format='dot2tex', edge_labels=True, color_by_label=self.cartan_type()._index_set_coloring)
return G
class ElementMethods():
def string_parameters(self, word=None):
'\n Return the string parameters of ``self`` corresponding to the\n reduced word ``word``.\n\n Given a reduced expression `w = s_{i_1} \\cdots s_{i_k}`,\n the string parameters of `b \\in B` corresponding to `w`\n are `(a_1, \\ldots, a_k)` such that\n\n .. MATH::\n\n \\begin{aligned}\n e_{i_m}^{a_m} \\cdots e_{i_1}^{a_1} b & \\neq 0 \\\\\n e_{i_m}^{a_m+1} \\cdots e_{i_1}^{a_1} b & = 0\n \\end{aligned}\n\n for all `1 \\leq m \\leq k`.\n\n For connected components isomorphic to `B(\\lambda)` or\n `B(\\infty)`, if `w = w_0` is the longest element of the\n Weyl group, then the path determined by the string\n parametrization terminates at the highest weight vector.\n\n INPUT:\n\n - ``word`` -- a word in the alphabet of the index set; if not\n specified and we are in finite type, then this will be some\n reduced expression for the long element determined by the\n Weyl group\n\n EXAMPLES::\n\n sage: B = crystals.infinity.NakajimaMonomials([\'A\',3])\n sage: mg = B.highest_weight_vector()\n sage: w0 = [1,2,1,3,2,1]\n sage: mg.string_parameters(w0)\n [0, 0, 0, 0, 0, 0]\n sage: mg.f_string([1]).string_parameters(w0)\n [1, 0, 0, 0, 0, 0]\n sage: mg.f_string([1,1,1]).string_parameters(w0)\n [3, 0, 0, 0, 0, 0]\n sage: mg.f_string([1,1,1,2,2]).string_parameters(w0)\n [1, 2, 2, 0, 0, 0]\n sage: mg.f_string([1,1,1,2,2]) == mg.f_string([1,1,2,2,1])\n True\n sage: x = mg.f_string([1,1,1,2,2,1,3,3,2,1,1,1])\n sage: x.string_parameters(w0)\n [4, 1, 1, 2, 2, 2]\n sage: x.string_parameters([3,2,1,3,2,3])\n [2, 3, 7, 0, 0, 0]\n sage: x == mg.f_string([1]*7 + [2]*3 + [3]*2)\n True\n\n ::\n\n sage: B = crystals.infinity.Tableaux("A5")\n sage: b = B(rows=[[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,6,6,6,6,6,6],\n ....: [2,2,2,2,2,2,2,2,2,4,5,5,5,6],\n ....: [3,3,3,3,3,3,3,5],\n ....: [4,4,4,6,6,6],\n ....: [5,6]])\n sage: b.string_parameters([1,2,1,3,2,1,4,3,2,1,5,4,3,2,1])\n [0, 1, 1, 1, 1, 0, 4, 4, 3, 0, 11, 10, 7, 7, 6]\n\n sage: B = crystals.infinity.Tableaux("G2")\n sage: b = B(rows=[[1,1,1,1,1,3,3,0,-3,-3,-2,-2,-1,-1,-1,-1],[2,3,3,3]])\n sage: b.string_parameters([2,1,2,1,2,1])\n [5, 13, 11, 15, 4, 4]\n sage: b.string_parameters([1,2,1,2,1,2])\n [7, 12, 15, 8, 10, 0]\n\n ::\n\n sage: C = crystals.Tableaux([\'C\',2], shape=[2,1])\n sage: mg = C.highest_weight_vector()\n sage: lw = C.lowest_weight_vectors()[0]\n sage: lw.string_parameters([1,2,1,2])\n [1, 2, 3, 1]\n sage: lw.string_parameters([2,1,2,1])\n [1, 3, 2, 1]\n sage: lw.e_string([2,1,1,1,2,2,1]) == mg\n True\n sage: lw.e_string([1,2,2,1,1,1,2]) == mg\n True\n\n TESTS::\n\n sage: B = crystals.infinity.NakajimaMonomials([\'B\',3])\n sage: mg = B.highest_weight_vector()\n sage: mg.string_parameters()\n [0, 0, 0, 0, 0, 0, 0, 0, 0]\n sage: w0 = WeylGroup([\'B\',3]).long_element().reduced_word()\n sage: def f_word(params):\n ....: return reversed([index for i, index in enumerate(w0)\n ....: for _ in range(params[i])])\n sage: all(mg.f_string( f_word(x.value.string_parameters(w0)) ) == x.value\n ....: for x in B.subcrystal(max_depth=4))\n True\n\n sage: B = crystals.infinity.NakajimaMonomials([\'A\',2,1])\n sage: mg = B.highest_weight_vector()\n sage: mg.string_parameters()\n Traceback (most recent call last):\n ...\n ValueError: the word must be specified because the\n Weyl group is not finite\n '
if (word is None):
if (not self.cartan_type().is_finite()):
raise ValueError('the word must be specified because the Weyl group is not finite')
from sage.combinat.root_system.weyl_group import WeylGroup
word = WeylGroup(self.cartan_type()).long_element().reduced_word()
x = self
params = []
for i in word:
count = 0
y = x.e(i)
while (y is not None):
x = y
y = x.e(i)
count += 1
params.append(count)
return params
class TensorProducts(TensorProductsCategory):
'\n The category of highest weight crystals constructed by tensor\n product of highest weight crystals.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: HighestWeightCrystals().TensorProducts().extra_super_categories()\n [Category of highest weight crystals]\n '
return [self.base_category()]
class ParentMethods():
'\n Implements operations on tensor products of crystals.\n '
@cached_method
def highest_weight_vectors(self):
"\n Return the highest weight vectors of ``self``.\n\n This works by using a backtracing algorithm since if\n `b_2 \\otimes b_1` is highest weight then `b_1` is\n highest weight.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux(['D',4], shape=[2,2])\n sage: D = crystals.Tableaux(['D',4], shape=[1])\n sage: T = crystals.TensorProduct(D, C)\n sage: T.highest_weight_vectors()\n ([[[1]], [[1, 1], [2, 2]]],\n [[[3]], [[1, 1], [2, 2]]],\n [[[-2]], [[1, 1], [2, 2]]])\n sage: L = filter(lambda x: x.is_highest_weight(), T)\n sage: tuple(L) == T.highest_weight_vectors()\n True\n\n TESTS:\n\n We check this works with Kashiwara's convention for\n tensor products::\n\n sage: C = crystals.Tableaux(['B',3], shape=[2,2])\n sage: D = crystals.Tableaux(['B',3], shape=[1])\n sage: T = crystals.TensorProduct(D, C)\n sage: T.options(convention='Kashiwara')\n sage: T.highest_weight_vectors()\n ([[[1, 1], [2, 2]], [[1]]],\n [[[1, 1], [2, 2]], [[3]]],\n [[[1, 1], [2, 2]], [[-2]]])\n sage: T.options._reset()\n sage: T.highest_weight_vectors()\n ([[[1]], [[1, 1], [2, 2]]],\n [[[3]], [[1, 1], [2, 2]]],\n [[[-2]], [[1, 1], [2, 2]]])\n "
return tuple(self.highest_weight_vectors_iterator())
def highest_weight_vectors_iterator(self):
'\n Iterate over the highest weight vectors of ``self``.\n\n This works by using a backtracing algorithm since if\n `b_2 \\otimes b_1` is highest weight then `b_1` is\n highest weight.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux([\'D\',4], shape=[2,2])\n sage: D = crystals.Tableaux([\'D\',4], shape=[1])\n sage: T = crystals.TensorProduct(D, C)\n sage: tuple(T.highest_weight_vectors_iterator())\n ([[[1]], [[1, 1], [2, 2]]],\n [[[3]], [[1, 1], [2, 2]]],\n [[[-2]], [[1, 1], [2, 2]]])\n sage: L = filter(lambda x: x.is_highest_weight(), T)\n sage: tuple(L) == tuple(T.highest_weight_vectors_iterator())\n True\n\n TESTS:\n\n We check this works with Kashiwara\'s convention for\n tensor products::\n\n sage: C = crystals.Tableaux([\'B\',3], shape=[2,2])\n sage: D = crystals.Tableaux([\'B\',3], shape=[1])\n sage: T = crystals.TensorProduct(D, C)\n sage: T.options(convention=\'Kashiwara\')\n sage: tuple(T.highest_weight_vectors_iterator())\n ([[[1, 1], [2, 2]], [[1]]],\n [[[1, 1], [2, 2]], [[3]]],\n [[[1, 1], [2, 2]], [[-2]]])\n sage: T.options._reset()\n sage: tuple(T.highest_weight_vectors_iterator())\n ([[[1]], [[1, 1], [2, 2]]],\n [[[3]], [[1, 1], [2, 2]]],\n [[[-2]], [[1, 1], [2, 2]]])\n\n This currently is not implemented for infinite crystals::\n\n sage: P = RootSystem([\'A\',3,1]).weight_lattice(extended=True)\n sage: M = crystals.NakajimaMonomials(P.fundamental_weight(0))\n sage: T = tensor([M, M])\n sage: list(T.highest_weight_vectors_iterator())\n Traceback (most recent call last):\n ...\n NotImplementedError: not implemented for infinite crystals\n\n Check that :trac:`30493` is fixed::\n\n sage: CW = CartanType("G", 2)\n sage: C = crystals.Letters(CW)\n sage: C.highest_weight_vectors()\n (1,)\n sage: T = crystals.TensorProduct(C)\n sage: T.highest_weight_vectors()\n ([1],)\n '
if (len(self.crystals) == 1):
for b in self.crystals[0].highest_weight_vectors():
(yield self.element_class(self, [b]))
return
I = self.index_set()
try:
T_elts = [C.list() for C in self.crystals[:(- 1)]]
except (TypeError, NotImplementedError, AttributeError):
raise NotImplementedError('not implemented for infinite crystals')
from sage.categories.regular_crystals import RegularCrystals
if (self in RegularCrystals):
def hw_test(b2, i, d):
return (d < 0)
else:
def hw_test(b2, i, d):
return ((d < 0) and (b2.e(i) is not None))
T_len = [len(elts) for elts in T_elts]
m = (len(self.crystals) - 1)
for b in self.crystals[(- 1)].highest_weight_vectors():
T_pos = (m - 1)
T_cur = ([0] * m)
path = (([None] * m) + [b])
T_phi = (([None] * (m - 1)) + [{i: b.phi(i) for i in I}])
while (T_pos < m):
if (T_cur[T_pos] == T_len[T_pos]):
T_cur[T_pos] = 0
T_pos += 1
continue
b2 = T_elts[T_pos][T_cur[T_pos]]
T_cur[T_pos] += 1
b1_phi = T_phi[T_pos]
b1_phi_minus_b2_epsilon = {}
for i in I:
d = (b1_phi[i] - b2.epsilon(i))
if hw_test(b2, i, d):
break
b1_phi_minus_b2_epsilon[i] = d
else:
path[T_pos] = b2
if T_pos:
T_pos -= 1
T_phi[T_pos] = {i: (b2.phi(i) + max(0, b1_phi_minus_b2_epsilon[i])) for i in I}
else:
(yield self.element_class(self, path))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.