code stringlengths 17 6.64M |
|---|
class HighestWeightCrystalMorphism(CrystalMorphismByGenerators):
'\n A virtual crystal morphism whose domain is a highest weight crystal.\n\n INPUT:\n\n - ``parent`` -- a homset\n - ``on_gens`` -- a function or list that determines the image of the\n generators (if given a list, then this uses the order of the\n generators of the domain) of the domain under ``self``\n - ``cartan_type`` -- (optional) a Cartan type; the default is the\n Cartan type of the domain\n - ``virtualization`` -- (optional) a dictionary whose keys are\n in the index set of the domain and whose values are lists of\n entries in the index set of the codomain\n - ``scaling_factors`` -- (optional) a dictionary whose keys are in\n the index set of the domain and whose values are scaling factors\n for the weight, `\\varepsilon` and `\\varphi`\n - ``gens`` -- (optional) a list of generators to define the morphism;\n the default is to use the highest weight vectors of the crystal\n - ``check`` -- (default: ``True``) check if the crystal morphism is valid\n '
def __init__(self, parent, on_gens, cartan_type=None, virtualization=None, scaling_factors=None, gens=None, check=True):
"\n Construct a crystal morphism.\n\n TESTS::\n\n sage: B = crystals.infinity.Tableaux(['B',2])\n sage: C = crystals.infinity.NakajimaMonomials(['B',2])\n sage: psi = B.crystal_morphism(C.module_generators)\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n "
if (cartan_type is None):
cartan_type = parent.domain().cartan_type()
if isinstance(on_gens, dict):
gens = on_gens.keys()
I = cartan_type.index_set()
if (gens is None):
if (cartan_type == parent.domain().cartan_type()):
gens = parent.domain().highest_weight_vectors()
else:
gens = tuple((x for x in parent.domain() if x.is_highest_weight(I)))
self._hw_gens = True
elif check:
self._hw_gens = all((x.is_highest_weight(I) for x in gens))
else:
self._hw_gens = False
CrystalMorphismByGenerators.__init__(self, parent, on_gens, cartan_type, virtualization, scaling_factors, gens, check)
def _call_(self, x):
"\n Return the image of ``x`` under ``self``.\n\n TESTS::\n\n sage: B = crystals.infinity.Tableaux(['B',2])\n sage: C = crystals.infinity.NakajimaMonomials(['B',2])\n sage: psi = B.crystal_morphism(C.module_generators)\n sage: b = B.highest_weight_vector()\n sage: psi(b)\n 1\n sage: c = psi(b.f_string([1,1,1,2,2,1,2,2])); c\n Y(1,0)^-4 Y(2,0)^4 Y(2,1)^-4\n sage: c == C.highest_weight_vector().f_string([1,1,1,2,2,1,2,2])\n True\n\n sage: B = crystals.Tableaux(['B',3], shape=[1])\n sage: C = crystals.Tableaux(['D',4], shape=[2])\n sage: H = Hom(B, C)\n sage: psi = H(C.module_generators)\n sage: psi(B.module_generators[0])\n [[1, 1]]\n\n We check with the morphism defined on the lowest weight vector::\n\n sage: B = crystals.Tableaux(['A',2], shape=[1])\n sage: La = RootSystem(['A',2]).weight_lattice().fundamental_weights()\n sage: T = crystals.elementary.T(['A',2], La[2])\n sage: Bp = T.tensor(B)\n sage: C = crystals.Tableaux(['A',2], shape=[2,1])\n sage: H = Hom(Bp, C)\n sage: x = C.module_generators[0].f_string([1,2])\n sage: psi = H({Bp.lowest_weight_vectors()[0]: x})\n sage: psi\n ['A', 2] Crystal morphism:\n From: Full tensor product of the crystals\n [The T crystal of type ['A', 2] and weight Lambda[2],\n The crystal of tableaux of type ['A', 2] and shape(s) [[1]]]\n To: The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n Defn: [Lambda[2], [[3]]] |--> [[1, 3], [2]]\n sage: psi(Bp.highest_weight_vector())\n [[1, 1], [2]]\n "
if (not self._hw_gens):
return CrystalMorphismByGenerators._call_(self, x)
(mg, path) = x.to_highest_weight(self._cartan_type.index_set())
cur = self._on_gens(mg)
for i in reversed(path):
if (cur is None):
return None
s = []
sf = self._scaling_factors[i]
for j in self._virtualization[i]:
s += ([j] * sf)
cur = cur.f_string(s)
return cur
|
class HighestWeightCrystalHomset(CrystalHomset):
'\n The set of crystal morphisms from a highest weight crystal to\n another crystal.\n\n .. SEEALSO::\n\n See :class:`sage.categories.crystals.CrystalHomset` for more\n information.\n '
def __init__(self, X, Y, category=None):
"\n Initialize ``self``.\n\n TESTS::\n\n sage: B = crystals.Tableaux(['A', 2], shape=[2,1])\n sage: H = Hom(B, B)\n sage: B = crystals.infinity.Tableaux(['B',2])\n sage: H = Hom(B, B)\n "
if (category is None):
category = HighestWeightCrystals()
CrystalHomset.__init__(self, X, Y, category)
Element = HighestWeightCrystalMorphism
|
def Hom(X, Y, category=None, check=True):
'\n Create the space of homomorphisms from X to Y in the category ``category``.\n\n INPUT:\n\n - ``X`` -- an object of a category\n\n - ``Y`` -- an object of a category\n\n - ``category`` -- a category in which the morphisms must be.\n (default: the meet of the categories of ``X`` and ``Y``)\n Both ``X`` and ``Y`` must belong to that category.\n\n - ``check`` -- a boolean (default: ``True``): whether to check the\n input, and in particular that ``X`` and ``Y`` belong to\n ``category``.\n\n OUTPUT: a homset in category\n\n EXAMPLES::\n\n sage: V = VectorSpace(QQ, 3) # needs sage.modules\n sage: Hom(V, V) # needs sage.modules\n Set of Morphisms (Linear Transformations) from\n Vector space of dimension 3 over Rational Field to\n Vector space of dimension 3 over Rational Field\n sage: G = AlternatingGroup(3) # needs sage.groups\n sage: Hom(G, G) # needs sage.groups\n Set of Morphisms\n from Alternating group of order 3!/2 as a permutation group\n to Alternating group of order 3!/2 as a permutation group\n in Category of finite enumerated permutation groups\n sage: Hom(ZZ, QQ, Sets())\n Set of Morphisms from Integer Ring to Rational Field in Category of sets\n\n sage: Hom(FreeModule(ZZ, 1), FreeModule(QQ, 1)) # needs sage.modules\n Set of Morphisms\n from Ambient free module of rank 1 over the principal ideal domain Integer Ring\n to Vector space of dimension 1 over Rational Field\n in Category of commutative additive groups\n sage: Hom(FreeModule(QQ, 1), FreeModule(ZZ, 1)) # needs sage.modules\n Set of Morphisms\n from Vector space of dimension 1 over Rational Field\n to Ambient free module of rank 1 over the principal ideal domain Integer Ring\n in Category of commutative additive groups\n\n Here, we test against a memory leak that has been fixed at :trac:`11521` by\n using a weak cache::\n\n sage: # needs sage.libs.pari\n sage: for p in prime_range(10^3):\n ....: K = GF(p)\n ....: a = K(0)\n sage: import gc\n sage: gc.collect() # random\n 624\n sage: from sage.rings.finite_rings.finite_field_prime_modn import FiniteField_prime_modn as FF\n sage: L = [x for x in gc.get_objects() if isinstance(x, FF)]\n sage: len(L), L[0]\n (1, Finite Field of size 997)\n\n To illustrate the choice of the category, we consider the\n following parents as running examples::\n\n sage: X = ZZ; X\n Integer Ring\n sage: Y = SymmetricGroup(3); Y # needs sage.groups\n Symmetric group of order 3! as a permutation group\n\n By default, the smallest category containing both ``X`` and ``Y``,\n is used::\n\n sage: Hom(X, Y) # needs sage.groups\n Set of Morphisms from Integer Ring\n to Symmetric group of order 3! as a permutation group\n in Category of enumerated monoids\n\n Otherwise, if ``category`` is specified, then ``category`` is used,\n after checking that ``X`` and ``Y`` are indeed in ``category``::\n\n sage: Hom(X, Y, Magmas()) # needs sage.groups\n Set of Morphisms\n from Integer Ring\n to Symmetric group of order 3! as a permutation group\n in Category of magmas\n\n sage: Hom(X, Y, Groups()) # needs sage.groups\n Traceback (most recent call last):\n ...\n ValueError: Integer Ring is not in Category of groups\n\n A parent (or a parent class of a category) may specify how to\n construct certain homsets by implementing a method ``_Hom_(self,\n codomain, category)``. This method should either construct the\n requested homset or raise a :class:`TypeError`. This hook is currently\n mostly used to create homsets in some specific subclass of\n :class:`Homset` (e.g. :class:`sage.rings.homset.RingHomset`)::\n\n sage: Hom(QQ,QQ).__class__\n <class \'sage.rings.homset.RingHomset_generic_with_category\'>\n\n Do not call this hook directly to create homsets, as it does not\n handle unique representation::\n\n sage: Hom(QQ,QQ) == QQ._Hom_(QQ, category=QQ.category())\n True\n sage: Hom(QQ,QQ) is QQ._Hom_(QQ, category=QQ.category())\n False\n\n TESTS:\n\n Homset are unique parents::\n\n sage: k = GF(5)\n sage: H1 = Hom(k, k)\n sage: H2 = Hom(k, k)\n sage: H1 is H2\n True\n\n Moreover, if no category is provided, then the result is identical\n with the result for the meet of the categories of the domain and\n the codomain::\n\n sage: Hom(QQ, ZZ) is Hom(QQ,ZZ, Category.meet([QQ.category(), ZZ.category()]))\n True\n\n Some doc tests in :mod:`sage.rings` (need to) break the unique\n parent assumption. But if domain or codomain are not unique\n parents, then the homset will not fit. That is to say, the hom set\n found in the cache will have a (co)domain that is equal to, but\n not identical with, the given (co)domain.\n\n By :trac:`9138`, we abandon the uniqueness of homsets, if the\n domain or codomain break uniqueness::\n\n sage: from sage.rings.polynomial.multi_polynomial_ring import MPolynomialRing_polydict_domain\n sage: P.<x,y,z>=MPolynomialRing_polydict_domain(QQ, 3, order=\'degrevlex\')\n sage: Q.<x,y,z>=MPolynomialRing_polydict_domain(QQ, 3, order=\'degrevlex\')\n sage: P == Q\n True\n sage: P is Q\n False\n\n Hence, ``P`` and ``Q`` are not unique parents. By consequence, the\n following homsets aren\'t either::\n\n sage: H1 = Hom(QQ,P)\n sage: H2 = Hom(QQ,Q)\n sage: H1 == H2\n True\n sage: H1 is H2\n False\n\n It is always the most recently constructed homset that remains in\n the cache::\n\n sage: H2 is Hom(QQ,Q)\n True\n\n Variation on the theme::\n\n sage: # needs sage.modules\n sage: U1 = FreeModule(ZZ, 2)\n sage: U2 = FreeModule(ZZ, 2, inner_product_matrix=matrix([[1,0], [0,-1]]))\n sage: U1 == U2, U1 is U2\n (False, False)\n sage: V = ZZ^3\n sage: H1 = Hom(U1, V); H2 = Hom(U2, V)\n sage: H1 == H2, H1 is H2\n (False, False)\n sage: H1 = Hom(V, U1); H2 = Hom(V, U2)\n sage: H1 == H2, H1 is H2\n (False, False)\n\n Since :trac:`11900`, the meet of the categories of the given arguments is\n used to determine the default category of the homset. This can also be a\n join category, as in the following example::\n\n sage: PA = Parent(category=Algebras(QQ))\n sage: PJ = Parent(category=Rings() & Modules(QQ))\n sage: Hom(PA, PJ)\n Set of Homomorphisms\n from <sage.structure.parent.Parent object at ...>\n to <sage.structure.parent.Parent object at ...>\n sage: Hom(PA, PJ).category()\n Category of homsets of\n unital magmas and right modules over Rational Field\n and left modules over Rational Field\n sage: Hom(PA, PJ, Rngs())\n Set of Morphisms\n from <sage.structure.parent.Parent object at ...>\n to <sage.structure.parent.Parent object at ...> in Category of rngs\n\n .. TODO::\n\n - Design decision: how much of the homset comes from the\n category of ``X`` and ``Y``, and how much from the specific\n ``X`` and ``Y``. In particular, do we need several parent\n classes depending on ``X`` and ``Y``, or does the difference\n only lie in the elements (i.e. the morphism), and of course\n how the parent calls their constructors.\n - Specify the protocol for the ``_Hom_`` hook in case of ambiguity\n (e.g. if both a parent and some category thereof provide one).\n\n TESTS:\n\n Facade parents over plain Python types are supported::\n\n sage: from sage.sets.pythonclass import Set_PythonType\n sage: R = Set_PythonType(int)\n sage: S = Set_PythonType(float)\n sage: Hom(R, S)\n Set of Morphisms from Set of Python objects of class \'int\' to Set of Python objects of class \'float\' in Category of sets\n\n Checks that the domain and codomain are in the specified\n category. Case of a non parent::\n\n sage: # needs sage.graphs\n sage: S = SimplicialComplex([[1,2], [1,4]]); S.rename("S")\n sage: Hom(S, S, SimplicialComplexes())\n Set of Morphisms from S to S in Category of finite simplicial complexes\n sage: Hom(Set(), S, Sets())\n Set of Morphisms from {} to S in Category of sets\n sage: Hom(S, Set(), Sets())\n Set of Morphisms from S to {} in Category of sets\n sage: H = Hom(S, S, ChainComplexes(QQ))\n Traceback (most recent call last):\n ...\n ValueError: S is not in Category of chain complexes over Rational Field\n\n Those checks are done with the natural idiom ``X in category``,\n and not ``X.category().is_subcategory(category)`` as it used to be\n before :trac:`16275` (see :trac:`15801` for a real use case)::\n\n sage: # needs sage.graphs\n sage: class PermissiveCategory(Category):\n ....: def super_categories(self): return [Objects()]\n ....: def __contains__(self, X): return True\n sage: C = PermissiveCategory(); C.rename("Permissive category")\n sage: S.category().is_subcategory(C)\n False\n sage: S in C\n True\n sage: Hom(S, S, C)\n Set of Morphisms from S to S in Permissive category\n\n With ``check=False``, uninitialized parents, as can appear upon\n unpickling, are supported. Case of a parent::\n\n sage: cls = type(Set())\n sage: S = unpickle_newobj(cls, ()) # A non parent\n sage: H = Hom(S, S, SimplicialComplexes(), check=False)\n sage: H = Hom(S, S, Sets(), check=False)\n sage: H = Hom(S, S, ChainComplexes(QQ), check=False)\n\n Case of a non parent::\n\n sage: # needs sage.graphs\n sage: cls = type(SimplicialComplex([[1,2], [1,4]]))\n sage: S = unpickle_newobj(cls, ())\n sage: H = Hom(S, S, Sets(), check=False)\n sage: H = Hom(S, S, Groups(), check=False)\n sage: H = Hom(S, S, SimplicialComplexes(), check=False)\n\n Typical example where unpickling involves calling Hom on an\n uninitialized parent::\n\n sage: P.<x,y> = QQ[\'x,y\']\n sage: Q = P.quotient([x^2 - 1, y^2 - 1])\n sage: q = Q.an_element() # needs sage.libs.singular\n sage: explain_pickle(dumps(Q)) # needs sage.libs.singular\n pg_...\n ... = pg_dynamic_class(\'QuotientRing_generic_with_category\', (pg_QuotientRing_generic, pg_getattr(..., \'parent_class\')), None, None, pg_QuotientRing_generic)\n si... = unpickle_newobj(..., ())\n ...\n si... = pg_unpickle_MPolynomialRing_libsingular(..., (\'x\', \'y\'), ...)\n si... = ... pg_Hom(si..., si..., ...) ...\n sage: Q == loads(dumps(Q))\n True\n\n Check that the ``_Hom_`` method of the ``category`` input is used::\n\n sage: from sage.categories.category_types import Category_over_base_ring\n sage: class ModulesWithHom(Category_over_base_ring):\n ....: def super_categories(self):\n ....: return [Modules(self.base_ring())]\n ....: class ParentMethods:\n ....: def _Hom_(self, Y, category=None):\n ....: print("Modules")\n ....: raise TypeError\n sage: class AlgebrasWithHom(Category_over_base_ring):\n ....: def super_categories(self):\n ....: return [Algebras(self.base_ring()), ModulesWithHom(self.base_ring())]\n ....: class ParentMethods:\n ....: def _Hom_(self, Y, category=None):\n ....: R = self.base_ring()\n ....: if category is not None and category.is_subcategory(Algebras(R)):\n ....: print("Algebras")\n ....: raise TypeError\n sage: from sage.structure.element import Element\n sage: class Foo(Parent):\n ....: def _coerce_map_from_base_ring(self):\n ....: return self._generic_coerce_map(self.base_ring())\n ....: class Element(Element):\n ....: pass\n sage: X = Foo(base=QQ, category=AlgebrasWithHom(QQ))\n sage: H = Hom(X, X, ModulesWithHom(QQ))\n Modules\n '
global _cache
key = (X, Y, category)
try:
H = _cache[key]
except KeyError:
H = None
if (H is not None):
if ((H.domain() is X) and (H.codomain() is Y)):
return H
if (category is None):
category = X.category()._meet_(Y.category())
H = Hom(X, Y, category, check=False)
else:
if check:
if (not isinstance(category, Category)):
raise TypeError('Argument category (= {}) must be a category.'.format(category))
for O in [X, Y]:
try:
category_mismatch = (O not in category)
except Exception:
category_mismatch = True
if (category_mismatch and O._is_category_initialized()):
raise ValueError('{} is not in {}'.format(O, category))
try:
H = X._Hom_(Y, category)
except (AttributeError, TypeError):
if (not isinstance(category, JoinCategory)):
cats = [category]
else:
cats = category.super_categories()
H = None
for C in cats:
try:
H = C.parent_class._Hom_(X, Y, category=category)
break
except (AttributeError, TypeError):
pass
if (H is None):
H = Homset(X, Y, category=category, check=check)
_cache[key] = H
if (isinstance(X, UniqueRepresentation) and isinstance(Y, UniqueRepresentation)):
if (not isinstance(H, WithEqualityById)):
try:
H.__class__ = dynamic_class((H.__class__.__name__ + '_with_equality_by_id'), (WithEqualityById, H.__class__), doccls=H.__class__)
except Exception:
pass
return H
|
def hom(X, Y, f):
'\n Return ``Hom(X,Y)(f)``, where ``f`` is data that defines an element of\n ``Hom(X,Y)``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: phi = hom(R, QQ, [2])\n sage: phi(x^2 + 3)\n 7\n '
return Hom(X, Y)(f)
|
def End(X, category=None):
'\n Create the set of endomorphisms of ``X`` in the category category.\n\n INPUT:\n\n - ``X`` -- anything\n\n - ``category`` -- (optional) category in which to coerce ``X``\n\n OUTPUT:\n\n A set of endomorphisms in category\n\n EXAMPLES::\n\n sage: V = VectorSpace(QQ, 3) # needs sage.modules\n sage: End(V) # needs sage.modules\n Set of Morphisms (Linear Transformations)\n from Vector space of dimension 3 over Rational Field\n to Vector space of dimension 3 over Rational Field\n\n ::\n\n sage: # needs sage.groups\n sage: G = AlternatingGroup(3)\n sage: S = End(G); S\n Set of Morphisms\n from Alternating group of order 3!/2 as a permutation group\n to Alternating group of order 3!/2 as a permutation group\n in Category of finite enumerated permutation groups\n sage: from sage.categories.homset import is_Endset\n sage: is_Endset(S)\n True\n sage: S.domain()\n Alternating group of order 3!/2 as a permutation group\n\n To avoid creating superfluous categories, a homset in a category\n ``Cs()`` is in the homset category of the lowest full super category\n ``Bs()`` of ``Cs()`` that implements ``Bs.Homsets`` (or the join\n thereof if there are several). For example, finite groups form a\n full subcategory of unital magmas: any unital magma morphism\n between two finite groups is a finite group morphism. Since finite\n groups currently implement nothing more than unital magmas about\n their homsets, we have::\n\n sage: # needs sage.groups\n sage: G = GL(3, 3)\n sage: G.category()\n Category of finite groups\n sage: H = Hom(G, G)\n sage: H.homset_category()\n Category of finite groups\n sage: H.category()\n Category of endsets of unital magmas\n\n Similarly, a ring morphism just needs to preserve addition,\n multiplication, zero, and one. Accordingly, and since the category\n of rings implements nothing specific about its homsets, a ring\n homset is currently constructed in the category of homsets of\n unital magmas and unital additive magmas::\n\n sage: H = Hom(ZZ,ZZ,Rings())\n sage: H.category()\n Category of endsets of unital magmas and additive unital additive magmas\n '
return Hom(X, X, category)
|
def end(X, f):
'\n Return ``End(X)(f)``, where ``f`` is data that defines an element of\n ``End(X)``.\n\n EXAMPLES::\n\n sage: R.<x> = QQ[]\n sage: phi = end(R, [x + 1])\n sage: phi\n Ring endomorphism of Univariate Polynomial Ring in x over Rational Field\n Defn: x |--> x + 1\n sage: phi(x^2 + 5)\n x^2 + 2*x + 6\n '
return End(X)(f)
|
class Homset(Set_generic):
"\n The class for collections of morphisms in a category.\n\n EXAMPLES::\n\n sage: H = Hom(QQ^2, QQ^3) # needs sage.modules\n sage: loads(H.dumps()) is H # needs sage.modules\n True\n\n Homsets of unique parents are unique as well::\n\n sage: H = End(AffineSpace(2, names='x,y'))\n sage: loads(dumps(AffineSpace(2, names='x,y'))) is AffineSpace(2, names='x,y')\n True\n sage: loads(dumps(H)) is H\n True\n\n Conversely, homsets of non-unique parents are non-unique::\n\n sage: P11 = ProductProjectiveSpaces(QQ, [1, 1])\n sage: H = End(P11)\n sage: loads(dumps(P11)) is ProductProjectiveSpaces(QQ, [1, 1])\n False\n sage: loads(dumps(P11)) == ProductProjectiveSpaces(QQ, [1, 1])\n True\n sage: loads(dumps(H)) is H\n False\n sage: loads(dumps(H)) == H\n True\n "
def __init__(self, X, Y, category=None, base=None, check=True):
'\n TESTS::\n\n sage: X = ZZ[\'x\']; X.rename("X")\n sage: Y = ZZ[\'y\']; Y.rename("Y")\n sage: f = X.hom([0], Y)\n sage: class MyHomset(Homset):\n ....: def _an_element_(self):\n ....: return sage.categories.morphism.SetMorphism(self, f)\n sage: import __main__; __main__.MyHomset = MyHomset # fakes MyHomset being defined in a Python module\n sage: H = MyHomset(X, Y, category=Monoids(), base = ZZ)\n sage: H\n Set of Morphisms from X to Y in Category of monoids\n sage: TestSuite(H).run()\n\n sage: H = MyHomset(X, Y, category=1, base = ZZ)\n Traceback (most recent call last):\n ...\n TypeError: category (=1) must be a category\n\n sage: H = MyHomset(X, Y, category=1, base = ZZ, check = False)\n Traceback (most recent call last):\n ...\n AttributeError: \'sage.rings.integer.Integer\' object has no attribute \'Homsets\'...\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: f.parent().domain()\n Univariate Polynomial Ring in t over Integer Ring\n sage: f.domain() is f.parent().domain()\n True\n\n Test that ``base_ring`` is initialized properly::\n\n sage: R = QQ[\'x\']\n sage: Hom(R, R).base_ring()\n Rational Field\n sage: Hom(R, R, category=Sets()).base_ring()\n sage: Hom(R, R, category=Modules(QQ)).base_ring()\n Rational Field\n sage: Hom(QQ^3, QQ^3, category=Modules(QQ)).base_ring() # needs sage.modules\n Rational Field\n\n For whatever it\'s worth, the ``base`` arguments takes precedence::\n\n sage: MyHomset(ZZ^3, ZZ^3, base=QQ).base_ring() # needs sage.modules\n Rational Field\n '
self._domain = X
self._codomain = Y
if (category is None):
category = X.category()
self.__category = category
if check:
if (not isinstance(category, Category)):
raise TypeError(('category (=%s) must be a category' % category))
if ((base is None) and hasattr(category, 'WithBasis')):
base = X.base_ring()
Parent.__init__(self, base=base, category=(category.Endsets() if (X is Y) else category.Homsets()))
def __reduce__(self):
"\n Implement pickling by construction for Homsets.\n\n Homsets are unpickled using the function\n :func:`~sage.categories.homset.Hom` which is cached:\n ``Hom(domain, codomain, category, check=False)``.\n\n .. NOTE::\n\n It can happen, that ``Hom(X,X)`` is called during\n unpickling with an uninitialized instance ``X`` of a Python\n class. In some of these cases, testing that ``X in\n category`` can trigger ``X.category()``. This in turn can\n raise a error, or return a too large category (``Sets()``,\n for example) and (worse!) assign this larger category to\n the ``X._category`` cdef attribute, so that it would\n subsequently seem that ``X``'s category was initialised.\n\n Beside speed considerations, this is the main rationale\n for disabling checks upon unpickling.\n\n .. SEEALSO:: :trac:`14793`, :trac:`16275`\n\n EXAMPLES::\n\n sage: H = Hom(QQ^2, QQ^3) # needs sage.modules\n sage: H.__reduce__() # needs sage.modules\n (<function Hom at ...>,\n (Vector space of dimension 2 over Rational Field,\n Vector space of dimension 3 over Rational Field,\n Category of finite dimensional vector spaces with basis over\n (number fields and quotient fields and metric spaces),\n False))\n\n TESTS::\n\n sage: loads(H.dumps()) is H # needs sage.modules\n True\n\n Homsets of non-unique parents are non-unique as well::\n\n sage: # needs sage.groups\n sage: G = PermutationGroup([[(1, 2, 3), (4, 5)], [(3, 4)]])\n sage: G is loads(dumps(G))\n False\n sage: H = Hom(G, G)\n sage: H is loads(dumps(H))\n False\n sage: H == loads(dumps(H))\n True\n "
return (Hom, (self._domain, self._codomain, self.__category, False))
def _repr_(self):
"\n TESTS::\n\n sage: Hom(ZZ^2, QQ, category=Sets())._repr_() # needs sage.modules\n 'Set of Morphisms from Ambient free module of rank 2 over the principal ideal domain Integer Ring to Rational Field in Category of sets'\n "
return 'Set of Morphisms from {} to {} in {}'.format(self._domain, self._codomain, self.__category)
def __hash__(self):
"\n The hash is obtained from domain, codomain and base.\n\n TESTS::\n\n sage: hash(Hom(ZZ, QQ)) == hash((ZZ, QQ, ZZ))\n True\n sage: hash(Hom(QQ, ZZ)) == hash((QQ, ZZ, QQ))\n True\n\n sage: E = EllipticCurve('37a') # needs sage.schemes\n sage: H = E(0).parent(); H # needs sage.schemes\n Abelian group of points on Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field\n sage: hash(H) == hash((H.domain(), H.codomain(), H.base())) # needs sage.schemes\n True\n "
return hash((self._domain, self._codomain, self.base()))
def __bool__(self) -> bool:
'\n TESTS::\n\n sage: bool(Hom(ZZ, QQ))\n True\n '
return True
def homset_category(self):
'\n Return the category that this is a Hom in, i.e., this is typically\n the category of the domain or codomain object.\n\n EXAMPLES::\n\n sage: H = Hom(AlternatingGroup(4), AlternatingGroup(7)) # needs sage.groups\n sage: H.homset_category() # needs sage.groups\n Category of finite enumerated permutation groups\n '
return self.__category
def _element_constructor_(self, x, check=None, **options):
'\n Construct a morphism in this homset from ``x`` if possible.\n\n EXAMPLES::\n\n sage: H = Hom(SymmetricGroup(4), SymmetricGroup(7)) # needs sage.groups\n sage: phi = Hom(SymmetricGroup(5), SymmetricGroup(6)).natural_map() # needs sage.groups\n sage: phi # needs sage.groups\n Coercion morphism:\n From: Symmetric group of order 5! as a permutation group\n To: Symmetric group of order 6! as a permutation group\n\n When converting `\\phi` into `H`, some coerce maps are applied. Note\n that (in contrast to what is stated in the following string\n representation) it is safe to use the resulting map, since a composite\n map prevents the codomains of all constituent maps from garbage\n collection, if there is a strong reference to its domain (which is the\n case here)::\n\n sage: H(phi) # needs sage.groups\n Composite map:\n From: Symmetric group of order 4! as a permutation group\n To: Symmetric group of order 7! as a permutation group\n Defn: (map internal to coercion system -- copy before use)\n Coercion map:\n From: Symmetric group of order 4! as a permutation group\n To: Symmetric group of order 5! as a permutation group\n then\n Coercion morphism:\n From: Symmetric group of order 5! as a permutation group\n To: Symmetric group of order 6! as a permutation group\n then\n (map internal to coercion system -- copy before use)\n Coercion map:\n From: Symmetric group of order 6! as a permutation group\n To: Symmetric group of order 7! as a permutation group\n\n Also note that making a copy of the resulting map will automatically\n make strengthened copies of the composed maps::\n\n sage: copy(H(phi)) # needs sage.groups\n Composite map:\n From: Symmetric group of order 4! as a permutation group\n To: Symmetric group of order 7! as a permutation group\n Defn: Coercion map:\n From: Symmetric group of order 4! as a permutation group\n To: Symmetric group of order 5! as a permutation group\n then\n Coercion morphism:\n From: Symmetric group of order 5! as a permutation group\n To: Symmetric group of order 6! as a permutation group\n then\n Coercion map:\n From: Symmetric group of order 6! as a permutation group\n To: Symmetric group of order 7! as a permutation group\n sage: H = Hom(ZZ, ZZ, Sets())\n sage: f = H( lambda x: x + 1 )\n sage: f.parent()\n Set of Morphisms from Integer Ring to Integer Ring in Category of sets\n sage: f.domain()\n Integer Ring\n sage: f.codomain()\n Integer Ring\n sage: f(1), f(2), f(3)\n (2, 3, 4)\n\n sage: H = Hom(Set([1,2,3]), Set([1,2,3]))\n sage: f = H(lambda x: 4 - x)\n sage: f.parent()\n Set of Morphisms from {1, 2, 3} to {1, 2, 3} in Category of finite enumerated sets\n sage: f(1), f(2), f(3) # todo: not implemented\n\n sage: H = Hom(ZZ, QQ, Sets())\n sage: f = H( ConstantFunction(2/3) )\n sage: f.parent()\n Set of Morphisms from Integer Ring to Rational Field in Category of sets\n sage: f(1), f(2), f(3)\n (2/3, 2/3, 2/3)\n\n By :trac:`14711`, conversion and coerce maps should be copied\n before using them outside of the coercion system::\n\n sage: H = Hom(ZZ,QQ[\'t\'], CommutativeAdditiveGroups())\n sage: P.<t> = ZZ[]\n sage: f = P.hom([2*t])\n sage: phi = H._generic_convert_map(f.parent()); phi\n Conversion map:\n From: Set of Homomorphisms from Univariate Polynomial Ring in t over Integer Ring to Univariate Polynomial Ring in t over Integer Ring\n To: Set of Morphisms from Integer Ring to Univariate Polynomial Ring in t over Rational Field in Category of commutative additive groups\n sage: H._generic_convert_map(f.parent())(f)\n Composite map:\n From: Integer Ring\n To: Univariate Polynomial Ring in t over Rational Field\n Defn: (map internal to coercion system -- copy before use)\n Polynomial base injection morphism:\n From: Integer Ring\n To: Univariate Polynomial Ring in t over Integer Ring\n then\n Ring endomorphism of Univariate Polynomial Ring in t over Integer Ring\n Defn: t |--> 2*t\n then\n (map internal to coercion system -- copy before use)\n Ring morphism:\n From: Univariate Polynomial Ring in t over Integer Ring\n To: Univariate Polynomial Ring in t over Rational Field\n sage: copy(H._generic_convert_map(f.parent())(f))\n Composite map:\n From: Integer Ring\n To: Univariate Polynomial Ring in t over Rational Field\n Defn: Polynomial base injection morphism:\n From: Integer Ring\n To: Univariate Polynomial Ring in t over Integer Ring\n then\n Ring endomorphism of Univariate Polynomial Ring in t over Integer Ring\n Defn: t |--> 2*t\n then\n Ring morphism:\n From: Univariate Polynomial Ring in t over Integer Ring\n To: Univariate Polynomial Ring in t over Rational Field\n Defn: Induced from base ring by\n Natural morphism:\n From: Integer Ring\n To: Rational Field\n\n TESTS::\n\n sage: # needs sage.groups\n sage: G.<x,y,z> = FreeGroup()\n sage: H = Hom(G, G)\n sage: H(H.identity())\n Identity endomorphism of Free Group on generators {x, y, z}\n sage: H()\n Traceback (most recent call last):\n ...\n TypeError: unable to convert 0 to an element of\n Set of Morphisms from Free Group on generators {x, y, z}\n to Free Group on generators {x, y, z} in Category of infinite groups\n sage: H("whatever")\n Traceback (most recent call last):\n ...\n TypeError: unable to convert \'whatever\' to an element of\n Set of Morphisms from Free Group on generators {x, y, z}\n to Free Group on generators {x, y, z} in Category of infinite groups\n sage: HH = Hom(H, H)\n sage: HH(HH.identity(), foo="bar")\n Traceback (most recent call last):\n ...\n NotImplementedError: no keywords are implemented for\n constructing elements of ...\n\n AUTHORS:\n\n - Robert Bradshaw, with changes by Nicolas M. Thiery\n '
if options:
try:
call_with_keywords = self.__call_on_basis__
except AttributeError:
if ('base_map' in options):
raise NotImplementedError('base_map not supported for this Homset; you may need to specify a category')
raise NotImplementedError('no keywords are implemented for constructing elements of {}'.format(self))
options.setdefault('category', self.homset_category())
return call_with_keywords(**options)
if isinstance(x, morphism.Morphism):
if (x.domain() != self.domain()):
mor = x.domain()._internal_coerce_map_from(self.domain())
if (mor is None):
raise TypeError(('Incompatible domains: x (=%s) cannot be an element of %s' % (x, self)))
x = (x * mor)
if (x.codomain() != self.codomain()):
mor = self.codomain()._internal_coerce_map_from(x.codomain())
if (mor is None):
raise TypeError(('Incompatible codomains: x (=%s) cannot be an element of %s' % (x, self)))
x = (mor * x)
return x
if callable(x):
return self.element_class_set_morphism(self, x)
raise TypeError('unable to convert {!r} to an element of {}'.format(x, self))
@lazy_attribute
def _abstract_element_class(self):
"\n An abstract class for the elements of this homset.\n\n This class is built from the element class of the homset\n category and the morphism class of the category. This makes\n it possible for a category to provide code for its morphisms\n and for morphisms of all its subcategories, full or not.\n\n .. NOTE::\n\n The element class of ``C.Homsets()`` will be inherited by\n morphisms in *full* subcategories of ``C``, while the morphism\n class of ``C`` will be inherited by *all* subcategories of\n ``C``. Hence, if some feature of a morphism depends on the\n algebraic properties of the homsets, it should be implemented by\n ``C.Homsets.ElementMethods``, but if it depends only on the\n algebraic properties of domain and codomain, it should be\n implemented in ``C.MorphismMethods``.\n\n At this point, the homset element classes take precedence over the\n morphism classes. But this may be subject to change.\n\n\n .. TODO::\n\n - Make sure this class is shared whenever possible.\n - Flatten join category classes\n\n .. SEEALSO::\n\n - :meth:`Parent._abstract_element_class`\n\n EXAMPLES:\n\n Let's take a homset of finite commutative groups as example; at\n this point this is the simplest one to create (gosh)::\n\n sage: # needs sage.groups\n sage: cat = Groups().Finite().Commutative()\n sage: C3 = PermutationGroup([(1,2,3)])\n sage: C3._refine_category_(cat)\n sage: C2 = PermutationGroup([(1,2)])\n sage: C2._refine_category_(cat)\n sage: H = Hom(C3, C2, cat)\n sage: H.homset_category()\n Category of finite commutative groups\n sage: H.category()\n Category of homsets of unital magmas\n sage: cls = H._abstract_element_class; cls\n <class 'sage.categories.homsets.GroupHomset_libgap_with_category._abstract_element_class'>\n sage: cls.__bases__ == (H.category().element_class, H.homset_category().morphism_class)\n True\n\n A morphism of finite commutative semigroups is also a morphism\n of semigroups, of magmas, ...; it thus inherits code from all\n those categories::\n\n sage: # needs sage.groups\n sage: issubclass(cls, Semigroups().Finite().morphism_class)\n True\n sage: issubclass(cls, Semigroups().morphism_class)\n True\n sage: issubclass(cls, Magmas().Commutative().morphism_class)\n True\n sage: issubclass(cls, Magmas().morphism_class)\n True\n sage: issubclass(cls, Sets().morphism_class)\n True\n\n Recall that FiniteMonoids() is a full subcategory of\n ``Monoids()``, but not of ``FiniteSemigroups()``. Thus::\n\n sage: issubclass(cls, Monoids().Finite().Homsets().element_class) # needs sage.groups\n True\n sage: issubclass(cls, Semigroups().Finite().Homsets().element_class) # needs sage.groups\n False\n "
class_name = ('%s._abstract_element_class' % self.__class__.__name__)
return dynamic_class(class_name, (self.category().element_class, self.homset_category().morphism_class))
@lazy_attribute
def element_class_set_morphism(self):
"\n A base class for elements of this homset which are\n also ``SetMorphism``, i.e. implemented by mean of a\n Python function.\n\n This is currently plain ``SetMorphism``, without inheritance\n from categories.\n\n .. TODO::\n\n Refactor during the upcoming homset cleanup.\n\n EXAMPLES::\n\n sage: H = Hom(ZZ, ZZ)\n sage: H.element_class_set_morphism\n <class 'sage.categories.morphism.SetMorphism'>\n "
return self.__make_element_class__(morphism.SetMorphism)
def __eq__(self, other):
'\n For two homsets, it is tested whether the domain, the codomain and\n the category coincide.\n\n EXAMPLES::\n\n sage: H1 = Hom(ZZ,QQ, CommutativeAdditiveGroups())\n sage: H2 = Hom(ZZ,QQ)\n sage: H1 == H2\n False\n sage: H1 == loads(dumps(H1))\n True\n '
if (not isinstance(other, Homset)):
return False
return ((self._domain == other._domain) and (self._codomain == other._codomain) and (self.__category == other.__category))
def __ne__(self, other):
"\n Check for not-equality of ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: H1 = Hom(ZZ,QQ, CommutativeAdditiveGroups())\n sage: H2 = Hom(ZZ,QQ)\n sage: H3 = Hom(ZZ['t'],QQ, CommutativeAdditiveGroups())\n sage: H4 = Hom(ZZ,QQ['t'], CommutativeAdditiveGroups())\n sage: H1 != H2\n True\n sage: H1 != loads(dumps(H1))\n False\n sage: H1 != H3 != H4 != H1\n True\n "
return (not (self == other))
def __contains__(self, x):
"\n Test whether the parent of the argument is ``self``.\n\n TESTS::\n\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: f in Hom(ZZ['t'],QQ['t']) # indirect doctest\n True\n sage: f in Hom(ZZ['t'],QQ['t'], CommutativeAdditiveGroups()) # indirect doctest\n False\n "
try:
return (x.parent() == self)
except AttributeError:
pass
return False
def natural_map(self):
'\n Return the "natural map" of this homset.\n\n .. NOTE::\n\n By default, a formal coercion morphism is returned.\n\n EXAMPLES::\n\n sage: H = Hom(ZZ[\'t\'],QQ[\'t\'], CommutativeAdditiveGroups())\n sage: H.natural_map()\n Coercion morphism:\n From: Univariate Polynomial Ring in t over Integer Ring\n To: Univariate Polynomial Ring in t over Rational Field\n sage: H = Hom(QQ[\'t\'], GF(3)[\'t\'])\n sage: H.natural_map()\n Traceback (most recent call last):\n ...\n TypeError: natural coercion morphism\n from Univariate Polynomial Ring in t over Rational Field\n to Univariate Polynomial Ring in t over Finite Field of size 3 not defined\n '
return morphism.FormalCoercionMorphism(self)
def identity(self):
'\n The identity map of this homset.\n\n .. NOTE::\n\n Of course, this only exists for sets of endomorphisms.\n\n EXAMPLES::\n\n sage: H = Hom(QQ,QQ)\n sage: H.identity()\n Identity endomorphism of Rational Field\n sage: H = Hom(ZZ,QQ)\n sage: H.identity()\n Traceback (most recent call last):\n ...\n TypeError: identity map only defined for endomorphisms; try natural_map() instead\n sage: H.natural_map()\n Natural morphism:\n From: Integer Ring\n To: Rational Field\n '
if self.is_endomorphism_set():
return morphism.IdentityMorphism(self)
raise TypeError('identity map only defined for endomorphisms; try natural_map() instead')
def one(self):
'\n The identity map of this homset.\n\n .. NOTE::\n\n Of course, this only exists for sets of endomorphisms.\n\n EXAMPLES::\n\n sage: K = GaussianIntegers() # needs sage.rings.number_field\n sage: End(K).one() # needs sage.rings.number_field\n Identity endomorphism of Gaussian Integers in Number Field in I\n with defining polynomial x^2 + 1 with I = 1*I\n '
return self.identity()
def domain(self):
'\n Return the domain of this homset.\n\n EXAMPLES::\n\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: f.parent().domain()\n Univariate Polynomial Ring in t over Integer Ring\n sage: f.domain() is f.parent().domain()\n True\n '
return self._domain
def codomain(self):
'\n Return the codomain of this homset.\n\n EXAMPLES::\n\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: f.parent().codomain()\n Univariate Polynomial Ring in t over Rational Field\n sage: f.codomain() is f.parent().codomain()\n True\n '
return self._codomain
def reversed(self):
"\n Return the corresponding homset, but with the domain and codomain\n reversed.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: H = Hom(ZZ^2, ZZ^3); H\n Set of Morphisms from Ambient free module of rank 2 over\n the principal ideal domain Integer Ring to Ambient free module\n of rank 3 over the principal ideal domain Integer Ring in\n Category of finite dimensional modules with basis over (euclidean\n domains and infinite enumerated sets and metric spaces)\n sage: type(H)\n <class 'sage.modules.free_module_homspace.FreeModuleHomspace_with_category'>\n sage: H.reversed()\n Set of Morphisms from Ambient free module of rank 3 over\n the principal ideal domain Integer Ring to Ambient free module\n of rank 2 over the principal ideal domain Integer Ring in\n Category of finite dimensional modules with basis over (euclidean\n domains and infinite enumerated sets and metric spaces)\n sage: type(H.reversed())\n <class 'sage.modules.free_module_homspace.FreeModuleHomspace_with_category'>\n "
return Hom(self.codomain(), self.domain(), category=self.homset_category())
|
class HomsetWithBase(Homset):
def __init__(self, X, Y, category=None, check=True, base=None):
'\n TESTS::\n\n sage: X = ZZ[\'x\']; X.rename("X")\n sage: Y = ZZ[\'y\']; Y.rename("Y")\n sage: f = X.hom([0], Y)\n sage: class MyHomset(HomsetWithBase):\n ....: def _an_element_(self):\n ....: return sage.categories.morphism.SetMorphism(self, f)\n sage: import __main__; __main__.MyHomset = MyHomset # fakes MyHomset being defined in a Python module\n sage: H = MyHomset(X, Y, category=Monoids())\n sage: H\n Set of Morphisms from X to Y in Category of monoids\n sage: H.base()\n Integer Ring\n sage: TestSuite(H).run()\n '
if (base is None):
base = X.base_ring()
Homset.__init__(self, X, Y, check=check, category=category, base=base)
|
def is_Homset(x):
'\n Return ``True`` if ``x`` is a set of homomorphisms in a category.\n\n EXAMPLES::\n\n sage: from sage.categories.homset import is_Homset\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: is_Homset(f)\n False\n sage: is_Homset(f.category())\n False\n sage: is_Homset(f.parent())\n True\n '
return isinstance(x, Homset)
|
def is_Endset(x):
'\n Return ``True`` if ``x`` is a set of endomorphisms in a category.\n\n EXAMPLES::\n\n sage: from sage.categories.homset import is_Endset\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: is_Endset(f.parent())\n False\n sage: g = P.hom([2*t])\n sage: is_Endset(g.parent())\n True\n '
return (isinstance(x, Homset) and x.is_endomorphism_set())
|
class HomsetsCategory(FunctorialConstructionCategory):
_functor_category = 'Homsets'
@classmethod
def default_super_categories(cls, category):
'\n Return the default super categories of ``category.Homsets()``.\n\n INPUT:\n\n - ``cls`` -- the category class for the functor `F`\n - ``category`` -- a category `Cat`\n\n OUTPUT: a category\n\n As for the other functorial constructions, if ``category``\n implements a nested ``Homsets`` class, this method is used in\n combination with ``category.Homsets().extra_super_categories()``\n to compute the super categories of ``category.Homsets()``.\n\n EXAMPLES:\n\n If ``category`` has one or more full super categories, then\n the join of their respective homsets category is returned. In\n this example, this join consists of a single category::\n\n sage: from sage.categories.homsets import HomsetsCategory\n sage: from sage.categories.additive_groups import AdditiveGroups\n\n sage: C = AdditiveGroups()\n sage: C.full_super_categories()\n [Category of additive inverse additive unital additive magmas,\n Category of additive monoids]\n sage: H = HomsetsCategory.default_super_categories(C); H\n Category of homsets of additive monoids\n sage: type(H)\n <class \'sage.categories.additive_monoids.AdditiveMonoids.Homsets_with_category\'>\n\n and, given that nothing specific is currently implemented for\n homsets of additive groups, ``H`` is directly the category\n thereof::\n\n sage: C.Homsets()\n Category of homsets of additive monoids\n\n Similarly for rings: a ring homset is just a homset of unital\n magmas and additive magmas::\n\n sage: Rings().Homsets()\n Category of homsets of unital magmas and additive unital additive magmas\n\n Otherwise, if ``category`` implements a nested class\n ``Homsets``, this method returns the category of all homsets::\n\n sage: AdditiveMagmas.Homsets\n <class \'sage.categories.additive_magmas.AdditiveMagmas.Homsets\'>\n sage: HomsetsCategory.default_super_categories(AdditiveMagmas())\n Category of homsets\n\n which gives one of the super categories of\n ``category.Homsets()``::\n\n sage: AdditiveMagmas().Homsets().super_categories()\n [Category of additive magmas, Category of homsets]\n sage: AdditiveMagmas().AdditiveUnital().Homsets().super_categories()\n [Category of additive unital additive magmas, Category of homsets]\n\n the other coming from ``category.Homsets().extra_super_categories()``::\n\n sage: AdditiveMagmas().Homsets().extra_super_categories()\n [Category of additive magmas]\n\n Finally, as a last resort, this method returns a stub category\n modelling the homsets of this category::\n\n sage: hasattr(Posets, "Homsets")\n False\n sage: H = HomsetsCategory.default_super_categories(Posets()); H\n Category of homsets of posets\n sage: type(H)\n <class \'sage.categories.homsets.HomsetsOf_with_category\'>\n sage: Posets().Homsets()\n Category of homsets of posets\n\n TESTS::\n\n sage: Objects().Homsets().super_categories()\n [Category of homsets]\n sage: Sets().Homsets().super_categories()\n [Category of homsets]\n sage: (Magmas() & Posets()).Homsets().super_categories()\n [Category of homsets]\n '
if category.full_super_categories():
return Category.join([getattr(cat, cls._functor_category)() for cat in category.full_super_categories()])
else:
functor_category = getattr(category.__class__, cls._functor_category)
if (isinstance(functor_category, type) and issubclass(functor_category, Category)):
return Homsets()
else:
return HomsetsOf(Category.join(category.structure()))
def _test_homsets_category(self, **options):
'\n Run generic tests on this homsets category\n\n .. SEEALSO:: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: Sets().Homsets()._test_homsets_category()\n '
tester = self._tester(**options)
tester.assertTrue(self.is_subcategory(Category.join(self.base_category().structure()).Homsets()))
tester.assertTrue(self.is_subcategory(Homsets()))
@cached_method
def base(self):
'\n If this homsets category is subcategory of a category with a base, return that base.\n\n .. TODO:: Is this really useful?\n\n EXAMPLES::\n\n sage: ModulesWithBasis(ZZ).Homsets().base()\n Integer Ring\n\n '
from sage.categories.category_types import Category_over_base
for C in self._all_super_categories_proper:
if isinstance(C, Category_over_base):
return C.base()
raise AttributeError('This hom category has no base')
|
class HomsetsOf(HomsetsCategory):
"\n Default class for homsets of a category.\n\n This is used when a category `C` defines some additional structure\n but not a homset category of its own. Indeed, unlike for covariant\n functorial constructions, we cannot represent the homset category\n of `C` by just the join of the homset categories of its super\n categories.\n\n EXAMPLES::\n\n sage: C = (Magmas() & Posets()).Homsets(); C\n Category of homsets of magmas and posets\n sage: type(C)\n <class 'sage.categories.homsets.HomsetsOf_with_category'>\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: C = Rings().Homsets()\n sage: TestSuite(C).run(skip=['_test_category_graph'])\n sage: TestSuite(C).run()\n "
_base_category_class = (Category,)
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Semigroups().Homsets()\n Category of homsets of magmas\n sage: (Magmas() & AdditiveMagmas() & Posets()).Homsets()\n Category of homsets of magmas and additive magmas and posets\n sage: Rings().Homsets()\n Category of homsets of unital magmas and additive unital additive magmas\n '
base_category = self.base_category()
try:
object_names = base_category._repr_object_names()
except ValueError:
assert isinstance(base_category, JoinCategory)
object_names = ' and '.join((cat._repr_object_names() for cat in base_category.super_categories()))
return ('homsets of %s' % object_names)
def super_categories(self):
"\n Return the super categories of ``self``.\n\n A stub homset category admits a single super category, namely\n the category of all homsets.\n\n EXAMPLES::\n\n sage: C = (Magmas() & Posets()).Homsets(); C\n Category of homsets of magmas and posets\n sage: type(C)\n <class 'sage.categories.homsets.HomsetsOf_with_category'>\n sage: C.super_categories()\n [Category of homsets]\n "
return [Homsets()]
|
class Homsets(Category_singleton):
'\n The category of all homsets.\n\n EXAMPLES::\n\n sage: from sage.categories.homsets import Homsets\n sage: Homsets()\n Category of homsets\n\n This is a subcategory of ``Sets()``::\n\n sage: Homsets().super_categories()\n [Category of sets]\n\n By this, we assume that all homsets implemented in Sage are sets,\n or equivalently that we only implement locally small categories.\n See :wikipedia:`Category_(mathematics)`.\n\n :trac:`17364`: every homset category shall be a subcategory of the\n category of all homsets::\n\n sage: Schemes().Homsets().is_subcategory(Homsets())\n True\n sage: AdditiveMagmas().Homsets().is_subcategory(Homsets())\n True\n sage: AdditiveMagmas().AdditiveUnital().Homsets().is_subcategory(Homsets())\n True\n\n This is tested in :meth:`HomsetsCategory._test_homsets_category`.\n '
def super_categories(self):
'\n Return the super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.homsets import Homsets\n sage: Homsets()\n Category of homsets\n '
from .sets_cat import Sets
return [Sets()]
class SubcategoryMethods():
def Endset(self):
'\n Return the subcategory of the homsets of ``self`` that are endomorphism sets.\n\n EXAMPLES::\n\n sage: Sets().Homsets().Endset()\n Category of endsets of sets\n\n sage: Posets().Homsets().Endset()\n Category of endsets of posets\n '
return self._with_axiom('Endset')
class Endset(CategoryWithAxiom):
"\n The category of all endomorphism sets.\n\n This category serves too purposes: making sure that the\n ``Endset`` axiom is implemented in the category where it's\n defined, namely ``Homsets``, and specifying that ``Endsets``\n are monoids.\n\n EXAMPLES::\n\n sage: from sage.categories.homsets import Homsets\n sage: Homsets().Endset()\n Category of endsets\n "
def extra_super_categories(self):
'\n Implement the fact that endsets are monoids.\n\n .. SEEALSO:: :meth:`CategoryWithAxiom.extra_super_categories`\n\n EXAMPLES::\n\n sage: from sage.categories.homsets import Homsets\n sage: Homsets().Endset().extra_super_categories()\n [Category of monoids]\n '
from .monoids import Monoids
return [Monoids()]
class ParentMethods():
def is_endomorphism_set(self):
'\n Return ``True`` as ``self`` is in the category\n of ``Endsets``.\n\n EXAMPLES::\n\n sage: P.<t> = ZZ[]\n sage: E = End(P)\n sage: E.is_endomorphism_set()\n True\n '
return True
class ParentMethods():
def is_endomorphism_set(self):
'\n Return ``True`` if the domain and codomain of ``self`` are the same\n object.\n\n EXAMPLES::\n\n sage: P.<t> = ZZ[]\n sage: f = P.hom([1/2*t])\n sage: f.parent().is_endomorphism_set()\n False\n sage: g = P.hom([2*t])\n sage: g.parent().is_endomorphism_set()\n True\n '
sD = self.domain()
sC = self.codomain()
if ((sC is None) or (sD is None)):
raise RuntimeError('Domain or codomain of this homset have been deallocated')
return (sD is sC)
|
class HopfAlgebras(Category_over_base_ring):
'\n The category of Hopf algebras.\n\n EXAMPLES::\n\n sage: HopfAlgebras(QQ)\n Category of Hopf algebras over Rational Field\n sage: HopfAlgebras(QQ).super_categories()\n [Category of bialgebras over Rational Field]\n\n TESTS::\n\n sage: TestSuite(HopfAlgebras(ZZ)).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: HopfAlgebras(QQ).super_categories()\n [Category of bialgebras over Rational Field]\n '
R = self.base_ring()
return [Bialgebras(R)]
def dual(self):
'\n Return the dual category\n\n EXAMPLES:\n\n The category of Hopf algebras over any field is self dual::\n\n sage: C = HopfAlgebras(QQ)\n sage: C.dual()\n Category of Hopf algebras over Rational Field\n '
return self
WithBasis = LazyImport('sage.categories.hopf_algebras_with_basis', 'HopfAlgebrasWithBasis')
class ElementMethods():
def antipode(self):
'\n Return the antipode of self\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: A = HopfAlgebrasWithBasis(QQ).example(); A\n An example of Hopf algebra with basis: the group algebra of the\n Dihedral group of order 6 as a permutation group over Rational Field\n sage: [a,b] = A.algebra_generators()\n sage: a, a.antipode()\n (B[(1,2,3)], B[(1,3,2)])\n sage: b, b.antipode()\n (B[(1,3)], B[(1,3)])\n\n TESTS::\n\n sage: all(x.antipode() * x == A.one() for x in A.basis()) # needs sage.groups\n True\n '
return self.parent().antipode(self)
class ParentMethods():
pass
class Morphism(Category):
'\n The category of Hopf algebra morphisms.\n '
pass
class Super(SuperModulesCategory):
'\n The category of super Hopf algebras.\n\n .. NOTE::\n\n A super Hopf algebra is *not* simply a Hopf\n algebra with a `\\ZZ/2\\ZZ` grading due to the\n signed bialgebra compatibility conditions.\n '
def dual(self):
'\n Return the dual category.\n\n EXAMPLES:\n\n The category of super Hopf algebras over any field is self dual::\n\n sage: C = HopfAlgebras(QQ).Super()\n sage: C.dual()\n Category of super Hopf algebras over Rational Field\n '
return self
class ElementMethods():
def antipode(self):
'\n Return the antipode of ``self``.\n\n EXAMPLES::\n\n sage: A = SteenrodAlgebra(3) # needs sage.combinat sage.modules\n sage: a = A.an_element() # needs sage.combinat sage.modules\n sage: a, a.antipode() # needs sage.combinat sage.modules\n (2 Q_1 Q_3 P(2,1), Q_1 Q_3 P(2,1))\n '
return self.parent().antipode(self)
class TensorProducts(TensorProductsCategory):
'\n The category of Hopf algebras constructed by tensor product of Hopf algebras\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: C = HopfAlgebras(QQ).TensorProducts()\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 over Rational Field,\n Category of tensor products of algebras over Rational Field,\n Category of tensor products of coalgebras over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
pass
class ElementMethods():
pass
class DualCategory(Category_over_base_ring):
'\n The category of Hopf algebras constructed as dual of a Hopf algebra\n '
class ParentMethods():
pass
class Realizations(RealizationsCategory):
class ParentMethods():
def antipode_by_coercion(self, x):
"\n Returns the image of ``x`` by the antipode\n\n This default implementation coerces to the default\n realization, computes the antipode there, and coerces the\n result back.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: N = NonCommutativeSymmetricFunctions(QQ)\n sage: R = N.ribbon()\n sage: R.antipode_by_coercion.__module__\n 'sage.categories.hopf_algebras'\n sage: R.antipode_by_coercion(R[1,3,1])\n -R[2, 1, 2]\n "
R = self.realization_of().a_realization()
return self(R(x).antipode())
|
class HopfAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of Hopf algebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = HopfAlgebrasWithBasis(QQ)\n sage: C\n Category of Hopf algebras with basis over Rational Field\n sage: C.super_categories()\n [Category of Hopf algebras over Rational Field,\n Category of bialgebras with basis over Rational Field]\n\n We now show how to use a simple Hopf algebra, namely the group algebra of the dihedral group\n (see also AlgebrasWithBasis)::\n\n sage: A = C.example(); A # needs sage.groups\n An example of Hopf algebra with basis: the group algebra of the\n Dihedral group of order 6 as a permutation group over Rational Field\n sage: A.rename("A") # needs sage.groups\n sage: A.category() # needs sage.groups\n Category of finite dimensional Hopf algebras with basis over Rational Field\n\n sage: A.one_basis() # needs sage.groups\n ()\n sage: A.one() # needs sage.groups\n B[()]\n\n sage: A.base_ring() # needs sage.groups\n Rational Field\n sage: A.basis().keys() # needs sage.groups\n Dihedral group of order 6 as a permutation group\n\n sage: # needs sage.groups\n sage: [a,b] = A.algebra_generators()\n sage: a, b\n (B[(1,2,3)], B[(1,3)])\n sage: a^3, b^2\n (B[()], B[()])\n sage: a*b\n B[(1,2)]\n\n sage: A.product # todo: not quite ... # needs sage.groups\n <bound method MagmaticAlgebras.WithBasis.ParentMethods._product_from_product_on_basis_multiply of A>\n sage: A.product(b, b) # needs sage.groups\n B[()]\n\n sage: A.zero().coproduct() # needs sage.groups\n 0\n sage: A.zero().coproduct().parent() # needs sage.groups\n A # A\n sage: a.coproduct() # needs sage.groups\n B[(1,2,3)] # B[(1,2,3)]\n\n sage: TestSuite(A).run(verbose=True) # needs sage.groups\n running ._test_additive_associativity() . . . pass\n running ._test_an_element() . . . pass\n running ._test_antipode() . . . pass\n running ._test_associativity() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_characteristic() . . . pass\n running ._test_construction() . . . pass\n running ._test_distributivity() . . . 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 running ._test_zero() . . . pass\n sage: A.__class__ # needs sage.groups\n <class \'sage.categories.examples.hopf_algebras_with_basis.MyGroupAlgebra_with_category\'>\n sage: A.element_class # needs sage.groups\n <class \'sage.categories.examples.hopf_algebras_with_basis.MyGroupAlgebra_with_category.element_class\'>\n\n Let us look at the code for implementing A::\n\n sage: A?? # not implemented # needs sage.groups\n\n TESTS::\n\n sage: TestSuite(A).run() # needs sage.groups\n sage: TestSuite(C).run()\n '
def example(self, G=None):
"\n Returns an example of algebra with basis::\n\n sage: HopfAlgebrasWithBasis(QQ['x']).example() # needs sage.groups\n An example of Hopf algebra with basis: the group algebra of the\n Dihedral group of order 6 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: HopfAlgebrasWithBasis(QQ).example(SymmetricGroup(4)) # needs sage.groups\n An example of Hopf algebra with basis: the group algebra of the\n Symmetric group of order 4! as a permutation group over Rational Field\n "
from sage.categories.examples.hopf_algebras_with_basis import MyGroupAlgebra
from sage.groups.perm_gps.permgroup_named import DihedralGroup
if (G is None):
G = DihedralGroup(3)
return MyGroupAlgebra(self.base_ring(), G)
FiniteDimensional = LazyImport('sage.categories.finite_dimensional_hopf_algebras_with_basis', 'FiniteDimensionalHopfAlgebrasWithBasis')
Filtered = LazyImport('sage.categories.filtered_hopf_algebras_with_basis', 'FilteredHopfAlgebrasWithBasis')
Graded = LazyImport('sage.categories.graded_hopf_algebras_with_basis', 'GradedHopfAlgebrasWithBasis')
Super = LazyImport('sage.categories.super_hopf_algebras_with_basis', 'SuperHopfAlgebrasWithBasis')
class ParentMethods():
@abstract_method(optional=True)
def antipode_on_basis(self, x):
'\n The antipode of the Hopf algebra on the basis (optional)\n\n INPUT:\n\n - ``x`` -- an index of an element of the basis of ``self``\n\n Returns the antipode of the basis element indexed by ``x``.\n\n If this method is implemented, then :meth:`antipode` is defined\n from this by linearity.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: W = A.basis().keys(); W\n Dihedral group of order 6 as a permutation group\n sage: w = W.gen(0); w\n (1,2,3)\n sage: A.antipode_on_basis(w)\n B[(1,3,2)]\n '
@lazy_attribute
def antipode(self):
'\n The antipode of this Hopf algebra.\n\n If :meth:`.antipode_basis` is available, this constructs the\n antipode morphism from ``self`` to ``self`` by extending it by\n linearity. Otherwise, :meth:`self.antipode_by_coercion` is used, if\n available.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: A = HopfAlgebrasWithBasis(ZZ).example(); A\n An example of Hopf algebra with basis: the group algebra of the\n Dihedral group of order 6 as a permutation group over Integer Ring\n sage: A = HopfAlgebrasWithBasis(QQ).example()\n sage: [a,b] = A.algebra_generators()\n sage: a, A.antipode(a)\n (B[(1,2,3)], B[(1,3,2)])\n sage: b, A.antipode(b)\n (B[(1,3)], B[(1,3)])\n\n TESTS::\n\n sage: all(A.antipode(x) * x == A.one() for x in A.basis()) # needs sage.groups\n True\n '
if (self.antipode_on_basis is not NotImplemented):
return self._module_morphism(self.antipode_on_basis, codomain=self)
elif hasattr(self, 'antipode_by_coercion'):
return self.antipode_by_coercion
def _test_antipode(self, **options):
'\n Test the antipode.\n\n An *antipode* `S` of a Hopf algebra is a linear endomorphism of the\n Hopf algebra that satisfies the following conditions (see\n :wikipedia:`HopfAlgebra`).\n\n - If `\\mu` and `\\Delta` denote the product and coproduct of the\n Hopf algebra, respectively, then `S` satisfies\n\n .. MATH::\n\n \\mu \\circ (S \\tensor 1) \\circ \\Delta = unit \\circ counit\n \\mu \\circ (1 \\tensor S) \\circ \\Delta = unit \\circ counit\n\n - `S` is an *anti*-homomorphism\n\n These properties are tested on :meth:`some_elements`.\n\n TESTS::\n\n sage: R = NonCommutativeSymmetricFunctions(QQ).ribbon() # needs sage.combinat sage.modules\n sage: R._test_antipode() # needs sage.combinat sage.modules\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: s._test_antipode() # needs sage.combinat sage.modules\n\n '
tester = self._tester(**options)
S = self.antipode
IS = (lambda x: self.sum((((c * self.monomial(t1)) * S(self.monomial(t2))) for ((t1, t2), c) in x.coproduct())))
SI = (lambda x: self.sum((((c * S(self.monomial(t1))) * self.monomial(t2)) for ((t1, t2), c) in x.coproduct())))
for x in tester.some_elements():
for y in tester.some_elements():
tester.assertEqual((S(x) * S(y)), S((y * x)))
tester.assertEqual(SI(x), (self.counit(x) * self.one()))
tester.assertEqual(IS(x), (self.counit(x) * self.one()))
class ElementMethods():
pass
class TensorProducts(TensorProductsCategory):
'\n The category of Hopf algebras with basis constructed by tensor product of Hopf algebras with basis\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: C = HopfAlgebrasWithBasis(QQ).TensorProducts()\n sage: C.extra_super_categories()\n [Category of Hopf algebras with basis over Rational Field]\n sage: sorted(C.super_categories(), key=str)\n [Category of Hopf algebras with basis over Rational Field,\n Category of tensor products of Hopf algebras over Rational Field,\n Category of tensor products of algebras with basis over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
pass
class ElementMethods():
pass
|
class InfiniteEnumeratedSets(CategoryWithAxiom):
'\n The category of infinite enumerated sets\n\n An infinite enumerated sets is a countable set together with a\n canonical enumeration of its elements.\n\n EXAMPLES::\n\n sage: InfiniteEnumeratedSets()\n Category of infinite enumerated sets\n sage: InfiniteEnumeratedSets().super_categories()\n [Category of enumerated sets, Category of infinite sets]\n sage: InfiniteEnumeratedSets().all_super_categories()\n [Category of infinite enumerated sets,\n Category of enumerated sets,\n Category of infinite sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n TESTS::\n\n sage: C = InfiniteEnumeratedSets()\n sage: TestSuite(C).run()\n '
class ParentMethods():
def random_element(self):
'\n Raise an error because ``self`` is an infinite enumerated set.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN.random_element()\n Traceback (most recent call last):\n ...\n NotImplementedError: infinite set\n\n TODO: should this be an optional abstract_method instead?\n '
raise NotImplementedError('infinite set')
def tuple(self):
'\n Raise an error because ``self`` is an infinite enumerated set.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN.tuple()\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n '
raise NotImplementedError('cannot list an infinite set')
def list(self):
'\n Raise an error because ``self`` is an infinite enumerated set.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN.list()\n Traceback (most recent call last):\n ...\n NotImplementedError: cannot list an infinite set\n '
raise NotImplementedError('cannot list an infinite set')
_list_default = list
def _test_enumerated_set_iter_cardinality(self, **options):
'\n Check that the methods :meth:`.cardinality` and\n :meth:`.__iter__` are consistent.\n\n See also :class:`TestSuite`.\n\n For infinite enumerated sets:\n\n * :meth:`.cardinality` is supposed to return ``infinity``\n\n * :meth:`.list` is supposed to raise a :class:`NotImplementedError`.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN._test_enumerated_set_iter_cardinality()\n '
tester = self._tester(**options)
from sage.rings.infinity import infinity
tester.assertEqual(self.cardinality(), infinity)
tester.assertRaises(NotImplementedError, self.list)
|
class IntegralDomains(CategoryWithAxiom):
'\n The category of integral domains\n\n An integral domain is commutative ring with no zero divisors, or\n equivalently a commutative domain.\n\n EXAMPLES::\n\n sage: C = IntegralDomains(); C\n Category of integral domains\n sage: sorted(C.super_categories(), key=str)\n [Category of commutative rings, Category of domains]\n sage: C is Domains().Commutative()\n True\n sage: C is Rings().Commutative().NoZeroDivisors()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
_base_category_class_and_axiom = (Domains, 'Commutative')
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: GF(4, "a") in IntegralDomains() # needs sage.rings.finite_rings\n True\n sage: QQ in IntegralDomains()\n True\n sage: ZZ in IntegralDomains()\n True\n sage: IntegerModRing(4) in IntegralDomains()\n False\n sage: IntegerModRing(5) in IntegralDomains()\n True\n\n This implementation will not be needed anymore once every\n field in Sage will be properly declared in the category\n :class:`IntegralDomains() <IntegralDomains>`.\n '
try:
return (self._contains_helper(x) or x.is_integral_domain())
except Exception:
return False
@lazy_class_attribute
def _contains_helper(cls):
"\n Helper for containment tests in the category of integral domains.\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 integral domains. There are, however, rings that are initialised\n as plain commutative rings and found out to be integral domains\n only afterwards. Hence, this helper alone is not enough\n for a proper containment test.\n\n TESTS::\n\n sage: R = Zmod(7)\n sage: R.category()\n Join of Category of finite commutative rings\n and Category of subquotients of monoids\n and Category of quotients of semigroups\n and Category of finite enumerated sets\n sage: ID = IntegralDomains()\n sage: ID._contains_helper(R)\n False\n sage: R in ID # This changes the category!\n True\n sage: ID._contains_helper(R)\n True\n "
return Category_contains_method_by_parent_class(cls())
class ParentMethods():
def is_integral_domain(self, proof=True):
'\n Return ``True``, since this in an object of the category\n of integral domains.\n\n EXAMPLES::\n\n sage: QQ.is_integral_domain()\n True\n sage: Parent(QQ, category=IntegralDomains()).is_integral_domain()\n True\n\n sage: L.<z> = LazyLaurentSeriesRing(QQ) # needs sage.combinat\n sage: L.is_integral_domain() # needs sage.combinat\n True\n sage: L.is_integral_domain(proof=True) # needs sage.combinat\n True\n '
return True
def _test_fraction_field(self, **options):
'\n Test that the fraction field, if it is implemented, works\n correctly.\n\n EXAMPLES::\n\n sage: ZZ._test_fraction_field()\n\n '
tester = self._tester(**options)
try:
fraction_field = self.fraction_field()
except (AttributeError, ImportError):
if (self in Fields()):
raise
return
for x in tester.some_elements():
fraction_field.coerce(x)
z = self(x)
tester.assertEqual(x, z)
class ElementMethods():
pass
|
class IsomorphicObjectsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'IsomorphicObjects'
@classmethod
def default_super_categories(cls, category):
"\n Returns the default super categories of ``category.IsomorphicObjects()``\n\n Mathematical meaning: if `A` is the image of `B` by an\n isomorphism in the category `C`, then `A` is both a subobject\n of `B` and a quotient of `B` in the category `C`.\n\n INPUT:\n\n - ``cls`` -- the class ``IsomorphicObjectsCategory``\n - ``category`` -- a category `Cat`\n\n OUTPUT: a (join) category\n\n In practice, this returns ``category.Subobjects()`` and\n ``category.Quotients()``, joined 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`` and\n ``cat.IsomorphicObjects()`` for each ``cat`` in the super\n categories of ``category``).\n\n EXAMPLES:\n\n Consider ``category=Groups()``, which has ``cat=Monoids()`` as\n super category. Then, the image of a group `G'` by a group\n isomorphism is simultaneously a subgroup of `G`, a subquotient\n of `G`, a group by itself, and the image of `G` by a monoid\n isomorphism::\n\n sage: Groups().IsomorphicObjects().super_categories()\n [Category of groups,\n Category of subquotients of monoids,\n Category of quotients of semigroups,\n Category of isomorphic objects of sets]\n\n Mind the last item above: there is indeed currently nothing\n implemented about isomorphic objects of monoids.\n\n This resulted from the following call::\n\n sage: sage.categories.isomorphic_objects.IsomorphicObjectsCategory.default_super_categories(Groups())\n Join of Category of groups and\n Category of subquotients of monoids and\n Category of quotients of semigroups and\n Category of isomorphic objects of sets\n "
return Category.join([category.Subobjects(), category.Quotients(), super().default_super_categories(category)])
|
class JTrivialSemigroups(CategoryWithAxiom):
def extra_super_categories(self):
'\n Implement the fact that a `J`-trivial semigroup is `L` and `R`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().JTrivial().extra_super_categories()\n [Category of l trivial semigroups, Category of r trivial semigroups]\n '
return [Semigroups().LTrivial(), Semigroups().RTrivial()]
|
class KacMoodyAlgebras(Category_over_base_ring):
'\n Category of Kac-Moody algebras.\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.kac_moody_algebras import KacMoodyAlgebras\n sage: KacMoodyAlgebras(QQ).super_categories()\n [Category of Lie algebras over Rational Field]\n '
return [LieAlgebras(self.base_ring())]
def example(self, n=2):
"\n Return an example of a Kac-Moody algebra as per\n :meth:`Category.example <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: from sage.categories.kac_moody_algebras import KacMoodyAlgebras\n sage: KacMoodyAlgebras(QQ).example() # needs sage.combinat sage.modules\n Lie algebra of ['A', 2] in the Chevalley basis\n\n We can specify the rank of the example::\n\n sage: KacMoodyAlgebras(QQ).example(4) # needs sage.combinat sage.modules\n Lie algebra of ['A', 4] in the Chevalley basis\n "
from sage.algebras.lie_algebras.classical_lie_algebra import LieAlgebraChevalleyBasis
return LieAlgebraChevalleyBasis(self.base_ring(), ['A', n])
class ParentMethods():
def cartan_type(self):
"\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebra(QQ, cartan_type=['A', 2]) # needs sage.combinat sage.modules\n sage: L.cartan_type() # needs sage.combinat sage.modules\n ['A', 2]\n "
return self._cartan_type
def weyl_group(self):
"\n Return the Weyl group of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebra(QQ, cartan_type=['A', 2]) # needs sage.combinat sage.modules\n sage: L.weyl_group() # needs sage.combinat sage.modules\n Weyl Group of type ['A', 2] (as a matrix group acting on the ambient space)\n "
from sage.combinat.root_system.weyl_group import WeylGroup
return WeylGroup(self.cartan_type())
|
class LTrivialSemigroups(CategoryWithAxiom):
def extra_super_categories(self):
'\n Implement the fact that a `L`-trivial semigroup is `H`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().LTrivial().extra_super_categories()\n [Category of h trivial semigroups]\n '
return [Semigroups().HTrivial()]
def RTrivial_extra_super_categories(self):
'\n Implement the fact that an `L`-trivial and `R`-trivial semigroup\n is `J`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().LTrivial().RTrivial_extra_super_categories()\n [Category of j trivial magmas]\n\n TESTS::\n\n sage: Semigroups().LTrivial().RTrivial() is Semigroups().JTrivial()\n True\n '
return [Magmas().JTrivial()]
def Commutative_extra_super_categories(self):
'\n Implement the fact that a commutative `R`-trivial semigroup is `J`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().LTrivial().Commutative_extra_super_categories()\n [Category of j trivial semigroups]\n\n TESTS::\n\n sage: Semigroups().LTrivial().Commutative() is Semigroups().JTrivial().Commutative()\n True\n '
return [self.JTrivial()]
|
class LambdaBracketAlgebras(Category_over_base_ring):
'\n The category of Lambda bracket algebras.\n\n This is an abstract base category for Lie conformal algebras and\n super Lie conformal algebras.\n\n '
@staticmethod
def __classcall_private__(cls, R, check=True):
'\n INPUT:\n\n - `R` -- a commutative ring\n - ``check`` -- a boolean (default: ``True``); whether to check\n that `R` is a commutative ring\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QuaternionAlgebra(2)) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ValueError: base must be a commutative ring\n got Quaternion Algebra (-1, -1) with base ring Rational Field\n sage: LieConformalAlgebras(ZZ)\n Category of Lie conformal algebras over Integer Ring\n '
if check:
if (R not in _CommutativeRings):
raise ValueError('base must be a commutative ring got {}'.format(R))
return super().__classcall__(cls, R)
@cached_method
def super_categories(self):
'\n The list of super categories of this category.\n\n EXAMPLES::\n\n sage: from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras\n sage: LambdaBracketAlgebras(QQ).super_categories()\n [Category of vector spaces over Rational Field]\n '
return [Modules(self.base_ring())]
def _repr_object_names(self):
'\n The name of the objects of this category.\n\n EXAMPLES::\n\n sage: from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras\n sage: LambdaBracketAlgebras(QQ)\n Category of Lambda bracket algebras over Rational Field\n '
return 'Lambda bracket algebras over {}'.format(self.base_ring())
class SubcategoryMethods():
def FinitelyGeneratedAsLambdaBracketAlgebra(self):
'\n The category of finitely generated Lambda bracket algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ).FinitelyGenerated()\n Category of finitely generated Lie conformal algebras over Rational Field\n '
return self._with_axiom('FinitelyGeneratedAsLambdaBracketAlgebra')
def FinitelyGenerated(self):
'\n The category of finitely generated Lambda bracket algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ).FinitelyGenerated()\n Category of finitely generated Lie conformal algebras over Rational Field\n '
return self._with_axiom('FinitelyGeneratedAsLambdaBracketAlgebra')
class ParentMethods():
def ideal(self, *gens, **kwds):
'\n The ideal of this Lambda bracket algebra generated by ``gens``.\n\n .. TODO::\n\n Ideals of Lie Conformal Algebras are not implemented yet.\n\n EXAMPLES::\n\n sage: Vir = lie_conformal_algebras.Virasoro(QQ) # needs sage.combinat sage.modules\n sage: Vir.ideal() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: ideals of Lie Conformal algebras are not implemented yet\n '
raise NotImplementedError('ideals of Lie Conformal algebras are not implemented yet')
class ElementMethods():
@coerce_binop
def bracket(self, rhs):
"\n The `\\lambda`-bracket of these two elements.\n\n EXAMPLES:\n\n The brackets of the Virasoro Lie conformal algebra::\n\n sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0 # needs sage.combinat sage.modules\n sage: L.bracket(L) # needs sage.combinat sage.modules\n {0: TL, 1: 2*L, 3: 1/2*C}\n sage: L.bracket(L.T()) # needs sage.combinat sage.modules\n {0: 2*T^(2)L, 1: 3*TL, 2: 4*L, 4: 2*C}\n\n Now with a current algebra::\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: E = V.0; H = V.1; F = V.2\n sage: H.bracket(H)\n {1: 2*B['K']}\n sage: E.bracket(F)\n {0: B[alphacheck[1]], 1: B['K']}\n "
return self._bracket_(rhs)
@abstract_method
def _bracket_(self, rhs):
"\n The `\\lambda`-bracket of these two elements.\n\n .. NOTE::\n\n It is guaranteed that both are elements of the same\n parent.\n\n EXAMPLES:\n\n The brackets of the Virasoro Lie conformal Algebra::\n\n sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0 # needs sage.combinat sage.modules\n sage: L._bracket_(L) # needs sage.combinat sage.modules\n {0: TL, 1: 2*L, 3: 1/2*C}\n sage: L._bracket_(L.T()) # needs sage.combinat sage.modules\n {0: 2*T^(2)L, 1: 3*TL, 2: 4*L, 4: 2*C}\n\n Now with a current algebra::\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: E = V.0; H = V.1; F = V.2\n sage: H._bracket_(H)\n {1: 2*B['K']}\n sage: E._bracket_(F)\n {0: B[alphacheck[1]], 1: B['K']}\n "
@coerce_binop
def nproduct(self, rhs, n):
"\n The ``n``-th product of these two elements.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0\n sage: L.nproduct(L, 3)\n 1/2*C\n sage: L.nproduct(L.T(), 0)\n 2*T^(2)L\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1')\n sage: E = V.0; H = V.1; F = V.2\n sage: E.nproduct(H, 0) == - 2*E\n True\n sage: E.nproduct(F, 1)\n B['K']\n "
return self._nproduct_(rhs, n)
def _nproduct_(self, rhs, n):
"\n The ``n``-th product of these two elements.\n\n .. NOTE::\n\n It is guaranteed that both are elements of the same\n parent.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: Vir = lie_conformal_algebras.Virasoro(QQ); L = Vir.0\n sage: L._nproduct_(L, 3)\n 1/2*C\n sage: L._nproduct_(L.T(), 0)\n 2*T^(2)L\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1')\n sage: E = V.0; H = V.1; F = V.2\n sage: E._nproduct_(H, 0) == - 2*E\n True\n sage: E._nproduct_(F, 1)\n B['K']\n "
if (n >= 0):
return self.bracket(rhs).get(n, self.parent().zero())
else:
raise NotImplementedError('vertex algebras are not implemented')
@abstract_method
def T(self, n=1):
'\n The ``n``-th derivative of ``self``.\n\n INPUT:\n\n - ``n`` -- integer (default:``1``); how many times\n to apply `T` to this element\n\n OUTPUT:\n\n `T^n a` where `a` is this element. Notice that we use the\n *divided powers* notation `T^{(j)} = \\frac{T^j}{j!}`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: Vir = lie_conformal_algebras.Virasoro(QQ)\n sage: Vir.inject_variables()\n Defining L, C\n sage: L.T()\n TL\n sage: L.T(3)\n 6*T^(3)L\n sage: C.T()\n 0\n '
WithBasis = LazyImport('sage.categories.lambda_bracket_algebras_with_basis', 'LambdaBracketAlgebrasWithBasis', 'WithBasis')
FinitelyGeneratedAsLambdaBracketAlgebra = LazyImport('sage.categories.finitely_generated_lambda_bracket_algebras', 'FinitelyGeneratedLambdaBracketAlgebras')
|
class LambdaBracketAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of Lambda bracket algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis() # needs sage.rings.number_field\n Category of Lie conformal algebras with basis over Algebraic Field\n '
class ElementMethods():
def index(self):
"\n The index of this basis element.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: V = lie_conformal_algebras.NeveuSchwarz(QQ)\n sage: V.inject_variables()\n Defining L, G, C\n sage: G.T(3).index()\n ('G', 3)\n sage: v = V.an_element(); v\n L + G + C\n sage: v.index()\n Traceback (most recent call last):\n ...\n ValueError: index can only be computed for monomials, got L + G + C\n "
if self.is_zero():
return None
if (not self.is_monomial()):
raise ValueError('index can only be computed for monomials, got {}'.format(self))
return next(iter(self.monomial_coefficients()))
class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring):
'\n The category of finitely generated lambda bracket algebras with\n basis.\n\n EXAMPLES::\n\n sage: # needs sage.rings.number_field\n sage: C = LieConformalAlgebras(QQbar)\n sage: C1 = C.WithBasis().FinitelyGenerated(); C1\n Category of finitely generated Lie conformal algebras with basis\n over Algebraic Field\n sage: C2 = C.FinitelyGenerated().WithBasis(); C2\n Category of finitely generated Lie conformal algebras with basis\n over Algebraic Field\n sage: C1 is C2\n True\n '
class Graded(GradedModulesCategory):
'\n The category of H-graded finitely generated lambda bracket\n algebras with basis.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar) # needs sage.rings.number_field\n sage: C.WithBasis().FinitelyGenerated().Graded() # needs sage.rings.number_field\n Category of H-graded finitely generated Lie conformal algebras\n with basis over Algebraic Field\n '
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: V = lie_conformal_algebras.Virasoro(QQ) # needs sage.combinat sage.modules\n sage: V.degree_on_basis(('L', 2)) # needs sage.combinat sage.modules\n 4\n "
if (m[0] in self._central_elements):
return 0
return (self._weights[self._index_to_pos[m[0]]] + m[1])
|
class LatticePosets(Category):
"\n The category of lattices, i.e. partially ordered sets in which any\n two elements have a unique supremum (the elements' least upper\n bound; called their *join*) and a unique infimum (greatest lower bound;\n called their *meet*).\n\n EXAMPLES::\n\n sage: LatticePosets()\n Category of lattice posets\n sage: LatticePosets().super_categories()\n [Category of posets]\n sage: LatticePosets().example()\n NotImplemented\n\n .. SEEALSO:: :class:`~sage.categories.posets.Posets`, :class:`FiniteLatticePosets`, :func:`LatticePoset`\n\n TESTS::\n\n sage: C = LatticePosets()\n sage: TestSuite(C).run()\n\n "
@cached_method
def super_categories(self):
'\n Returns a list of the (immediate) super categories of\n ``self``, as per :meth:`Category.super_categories`.\n\n EXAMPLES::\n\n sage: LatticePosets().super_categories()\n [Category of posets]\n '
return [Posets()]
Finite = LazyImport('sage.categories.finite_lattice_posets', 'FiniteLatticePosets')
class ParentMethods():
@abstract_method
def meet(self, x, y):
'\n Returns the meet of `x` and `y` in this lattice\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``\n\n EXAMPLES::\n\n sage: D = LatticePoset((divisors(30), attrcall("divides"))) # needs sage.graphs sage.modules\n sage: D.meet( D(6), D(15) ) # needs sage.graphs sage.modules\n 3\n '
@abstract_method
def join(self, x, y):
'\n Returns the join of `x` and `y` in this lattice\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``\n\n EXAMPLES::\n\n sage: D = LatticePoset((divisors(60), attrcall("divides"))) # needs sage.graphs sage.modules\n sage: D.join( D(6), D(10) ) # needs sage.graphs sage.modules\n 30\n '
|
class LeftModules(Category_over_base_ring):
'\n The category of left modules\n left modules over an rng (ring not necessarily with unit), i.e.\n an abelian group with left multiplication by elements of the rng\n\n EXAMPLES::\n\n sage: LeftModules(ZZ)\n Category of left modules over Integer Ring\n sage: LeftModules(ZZ).super_categories()\n [Category of commutative additive groups]\n\n TESTS::\n\n sage: TestSuite(LeftModules(ZZ)).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: LeftModules(QQ).super_categories()\n [Category of commutative additive groups]\n '
return [CommutativeAdditiveGroups()]
class ParentMethods():
pass
class ElementMethods():
pass
|
class LieAlgebras(Category_over_base_ring):
'\n The category of Lie algebras.\n\n EXAMPLES::\n\n sage: C = LieAlgebras(QQ); C\n Category of Lie algebras over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of vector spaces over Rational Field]\n\n We construct a typical parent in this category, and do some\n computations with it::\n\n sage: A = C.example(); A # needs sage.groups sage.modules\n An example of a Lie algebra: the Lie algebra from the associative\n algebra Symmetric group algebra of order 3 over Rational Field\n generated by ([2, 1, 3], [2, 3, 1])\n\n sage: A.category() # needs sage.groups sage.modules\n Category of Lie algebras over Rational Field\n\n sage: A.base_ring() # needs sage.groups sage.modules\n Rational Field\n\n sage: a, b = A.lie_algebra_generators() # needs sage.groups sage.modules\n sage: a.bracket(b) # needs sage.groups sage.modules\n -[1, 3, 2] + [3, 2, 1]\n sage: b.bracket(2*a + b) # needs sage.groups sage.modules\n 2*[1, 3, 2] - 2*[3, 2, 1]\n\n sage: A.bracket(a, b) # needs sage.groups sage.modules\n -[1, 3, 2] + [3, 2, 1]\n\n Please see the source code of `A` (with ``A??``) for how to\n implement other Lie algebras.\n\n TESTS::\n\n sage: C = LieAlgebras(QQ)\n sage: TestSuite(C).run()\n sage: TestSuite(C.example()).run() # needs sage.combinat sage.modules\n\n .. TODO::\n\n Many of these tests should use Lie algebras that are not the minimal\n example and need to be added after :trac:`16820` (and :trac:`16823`).\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: LieAlgebras(QQ).super_categories()\n [Category of vector spaces over Rational Field]\n '
return [Modules(self.base_ring())]
class SubcategoryMethods():
def Nilpotent(self):
'\n Return the full subcategory of nilpotent objects of ``self``.\n\n A Lie algebra `L` is nilpotent if there exist an integer `s` such\n that all iterated brackets of `L` of length more than `s` vanish.\n The integer `s` is called the nilpotency step.\n For instance any abelian Lie algebra is nilpotent of step 1.\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ).Nilpotent()\n Category of nilpotent Lie algebras over Rational Field\n sage: LieAlgebras(QQ).WithBasis().Nilpotent()\n Category of nilpotent Lie algebras with basis over Rational Field\n '
return self._with_axiom('Nilpotent')
Graded = LazyImport('sage.categories.graded_lie_algebras', 'GradedLieAlgebras', as_name='Graded')
def _repr_object_names(self):
"\n Return the name of the objects of this category.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ)._repr_object_names()\n 'Lie algebras over Rational Field'\n sage: LieAlgebras(Fields())._repr_object_names()\n 'Lie algebras over fields'\n sage: from sage.categories.category import JoinCategory\n sage: from sage.categories.category_with_axiom import Blahs\n sage: LieAlgebras(JoinCategory((Blahs().Flying(), Fields())))\n Category of Lie algebras over (flying unital blahs and fields)\n "
base = self.base()
if isinstance(base, Category):
if isinstance(base, JoinCategory):
name = (('(' + ' and '.join((C._repr_object_names() for C in base.super_categories()))) + ')')
else:
name = base._repr_object_names()
else:
name = base
return 'Lie algebras over {}'.format(name)
def example(self, gens=None):
'\n Return an example of a Lie algebra as per\n :meth:`Category.example <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ).example() # needs sage.groups sage.modules\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\n Another set of generators can be specified as an optional argument::\n\n sage: F.<x,y,z> = FreeAlgebra(QQ) # needs sage.combinat sage.modules\n sage: LieAlgebras(QQ).example(F.gens()) # needs sage.combinat sage.modules\n An example of a Lie algebra: the Lie algebra from the associative algebra\n Free Algebra on 3 generators (x, y, z) over Rational Field\n generated by (x, y, z)\n '
if (gens is None):
from sage.combinat.symmetric_group_algebra import SymmetricGroupAlgebra
from sage.rings.rational_field import QQ
gens = SymmetricGroupAlgebra(QQ, 3).algebra_generators()
from sage.categories.examples.lie_algebras import Example
return Example(gens)
WithBasis = LazyImport('sage.categories.lie_algebras_with_basis', 'LieAlgebrasWithBasis', as_name='WithBasis')
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
WithBasis = LazyImport('sage.categories.finite_dimensional_lie_algebras_with_basis', 'FiniteDimensionalLieAlgebrasWithBasis', as_name='WithBasis')
def extra_super_categories(self):
'\n Implements the fact that a finite dimensional Lie algebra over\n a finite ring is finite.\n\n EXAMPLES::\n\n sage: LieAlgebras(IntegerModRing(4)).FiniteDimensional().extra_super_categories()\n [Category of finite sets]\n sage: LieAlgebras(ZZ).FiniteDimensional().extra_super_categories()\n []\n sage: C = LieAlgebras(GF(5)).FiniteDimensional()\n sage: C.is_subcategory(Sets().Finite())\n True\n sage: C = LieAlgebras(ZZ).FiniteDimensional()\n sage: C.is_subcategory(Sets().Finite())\n False\n sage: C = LieAlgebras(GF(5)).WithBasis().FiniteDimensional()\n sage: C.is_subcategory(Sets().Finite())\n True\n '
if (self.base_ring() in Sets().Finite()):
return [Sets().Finite()]
return []
class Nilpotent(CategoryWithAxiom_over_base_ring):
'\n Category of nilpotent Lie algebras.\n\n TESTS::\n\n sage: C = LieAlgebras(QQ).Nilpotent()\n sage: TestSuite(C).run()\n '
class ParentMethods():
@abstract_method
def step(self):
'\n Return the nilpotency step of ``self``.\n\n EXAMPLES::\n\n sage: h = lie_algebras.Heisenberg(ZZ, oo) # needs sage.combinat sage.modules\n sage: h.step() # needs sage.combinat sage.modules\n 2\n '
def is_nilpotent(self):
'\n Return ``True`` since ``self`` is nilpotent.\n\n EXAMPLES::\n\n sage: h = lie_algebras.Heisenberg(ZZ, oo) # needs sage.combinat sage.modules\n sage: h.is_nilpotent() # needs sage.combinat sage.modules\n True\n '
return True
class ParentMethods():
def bracket(self, lhs, rhs):
'\n Return the Lie bracket ``[lhs, rhs]`` after coercing ``lhs`` and\n ``rhs`` into elements of ``self``.\n\n If ``lhs`` and ``rhs`` are Lie algebras, then this constructs\n the product space, and if only one of them is a Lie algebra,\n then it constructs the corresponding ideal.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).example()\n sage: x, y = L.lie_algebra_generators()\n sage: L.bracket(x, x + y)\n -[1, 3, 2] + [3, 2, 1]\n sage: L.bracket(x, 0)\n 0\n sage: L.bracket(0, x)\n 0\n\n Constructing the product space::\n\n sage: L = lie_algebras.Heisenberg(QQ, 1) # needs sage.combinat sage.modules\n sage: Z = L.bracket(L, L); Z # needs sage.combinat sage.modules\n Ideal (z) of Heisenberg algebra of rank 1 over Rational Field\n sage: L.bracket(L, Z) # needs sage.combinat sage.modules\n Ideal () of Heisenberg algebra of rank 1 over Rational Field\n\n Constructing ideals::\n\n sage: p, q, z = L.basis(); p, q, z # needs sage.combinat sage.modules\n (p1, q1, z)\n sage: L.bracket(3*p, L) # needs sage.combinat sage.modules\n Ideal (3*p1) of Heisenberg algebra of rank 1 over Rational Field\n sage: L.bracket(L, q + p) # needs sage.combinat sage.modules\n Ideal (p1 + q1) of Heisenberg algebra of rank 1 over Rational Field\n '
if (lhs in LieAlgebras):
if (rhs in LieAlgebras):
return lhs.product_space(rhs)
return lhs.ideal(rhs)
elif (rhs in LieAlgebras):
return rhs.ideal(lhs)
return self(lhs)._bracket_(self(rhs))
def universal_enveloping_algebra(self):
"\n Return the universal enveloping algebra of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.universal_enveloping_algebra() # needs sage.combinat sage.modules\n Noncommutative Multivariate Polynomial Ring in b0, b1, b2\n over Rational Field, nc-relations: {}\n\n ::\n\n sage: L = LieAlgebra(QQ, 3, 'x', abelian=True) # needs sage.combinat sage.modules\n sage: L.universal_enveloping_algebra() # needs sage.combinat sage.modules\n Multivariate Polynomial Ring in x0, x1, x2 over Rational Field\n\n .. SEEALSO::\n\n :meth:`lift`\n "
return self.lift.codomain()
@abstract_method(optional=True)
def _construct_UEA(self):
"\n Return the universal enveloping algebra of ``self``.\n\n Unlike :meth:`universal_enveloping_algebra`, this method does not\n (usually) construct the canonical lift morphism from ``self``\n to the universal enveloping algebra (let alone register it\n as a coercion).\n\n One should implement this method and the ``lift`` method for\n the element class to construct the morphism the universal\n enveloping algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L._construct_UEA() # needs sage.combinat sage.modules\n Noncommutative Multivariate Polynomial Ring in b0, b1, b2\n over Rational Field, nc-relations: {}\n\n ::\n\n sage: L = LieAlgebra(QQ, 3, 'x', abelian=True) # needs sage.combinat sage.modules\n sage: L.universal_enveloping_algebra() # indirect doctest # needs sage.combinat sage.modules\n Multivariate Polynomial Ring in x0, x1, x2 over Rational Field\n "
@abstract_method(optional=True)
def module(self):
'\n Return an `R`-module which is isomorphic to the\n underlying `R`-module of ``self``.\n\n The rationale behind this method is to enable linear\n algebraic functionality on ``self`` (such as\n computing the span of a list of vectors in ``self``)\n via an isomorphism from ``self`` to an `R`-module\n (typically, although not always, an `R`-module of\n the form `R^n` for an `n \\in \\NN`) on which such\n functionality already exists. For this method to be\n of any use, it should return an `R`-module which has\n linear algebraic functionality that ``self`` does\n not have.\n\n For instance, if ``self`` has ordered basis\n `(e, f, h)`, then ``self.module()`` will be the\n `R`-module `R^3`, and the elements `e`, `f` and\n `h` of ``self`` will correspond to the basis\n vectors `(1, 0, 0)`, `(0, 1, 0)` and `(0, 0, 1)`\n of ``self.module()``.\n\n This method :meth:`module` needs to be set whenever\n a finite-dimensional Lie algebra with basis is\n intended to support linear algebra (which is, e.g.,\n used in the computation of centralizers and lower\n central series). One then needs to also implement\n the `R`-module isomorphism from ``self`` to\n ``self.module()`` in both directions; that is,\n implement:\n\n * a ``to_vector`` ElementMethod which sends every\n element of ``self`` to the corresponding element of\n ``self.module()``;\n\n * a ``from_vector`` ParentMethod which sends every\n element of ``self.module()`` to an element\n of ``self``.\n\n The ``from_vector`` method will automatically serve\n as an element constructor of ``self`` (that is,\n ``self(v)`` for any ``v`` in ``self.module()`` will\n return ``self.from_vector(v)``).\n\n .. TODO::\n\n Ensure that this is actually so.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.module() # needs sage.modules\n Vector space of dimension 3 over Rational Field\n '
@abstract_method(optional=True)
def from_vector(self, v, order=None, coerce=False):
'\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 the latter 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 '
@lazy_attribute
def lift(self):
'\n Construct the lift morphism from ``self`` to the universal\n enveloping algebra of ``self`` (the latter is implemented\n as :meth:`universal_enveloping_algebra`).\n\n This is a Lie algebra homomorphism. It is injective if\n ``self`` is a free module over its base ring, or if the\n base ring is a `\\QQ`-algebra.\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: lifted = L.lift(2*a + b - c); lifted\n 2*b0 + b1 - b2\n sage: lifted.parent() is L.universal_enveloping_algebra()\n True\n '
M = LiftMorphism(self, self._construct_UEA())
M.register_as_coercion()
return M
def subalgebra(self, gens, names=None, index_set=None, category=None):
'\n Return the subalgebra of ``self`` generated by ``gens``.\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.subalgebra([2*a - c, b + c]) # needs sage.modules\n An example of a finite dimensional Lie algebra with basis:\n the 2-dimensional abelian Lie algebra over Rational Field\n with basis matrix:\n [ 1 0 -1/2]\n [ 0 1 1]\n\n ::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: x,y = L.lie_algebra_generators() # needs sage.combinat sage.modules\n sage: L.subalgebra([x + y]) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: subalgebras not yet implemented: see #17416\n '
raise NotImplementedError('subalgebras not yet implemented: see #17416')
def ideal(self, *gens, **kwds):
'\n Return the ideal of ``self`` generated by ``gens``.\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.ideal([2*a - c, b + c]) # needs sage.modules\n An example of a finite dimensional Lie algebra with basis:\n the 2-dimensional abelian Lie algebra over Rational Field\n with basis matrix:\n [ 1 0 -1/2]\n [ 0 1 1]\n\n ::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: x, y = L.lie_algebra_generators() # needs sage.combinat sage.modules\n sage: L.ideal([x + y]) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: ideals not yet implemented: see #16824\n '
raise NotImplementedError('ideals not yet implemented: see #16824')
def is_ideal(self, A):
'\n Return if ``self`` is an ideal of ``A``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: L.is_ideal(L) # needs sage.combinat sage.modules\n True\n '
if (A == self):
return True
raise NotImplementedError('ideals not yet implemented: see #16824')
@abstract_method(optional=True)
def killing_form(self, x, y):
'\n Return the Killing form of ``x`` and ``y``.\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 + c) # needs sage.modules\n 0\n '
def is_abelian(self):
"\n Return ``True`` if this Lie algebra is abelian.\n\n A Lie algebra `\\mathfrak{g}` is abelian if `[x, y] = 0` for all\n `x, y \\in \\mathfrak{g}`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).example()\n sage: L.is_abelian()\n False\n sage: R = QQ['x,y']\n sage: L = LieAlgebras(QQ).example(R.gens())\n sage: L.is_abelian()\n True\n\n ::\n\n sage: # not implemented, needs sage.combinat sage.modules\n sage: L.<x> = LieAlgebra(QQ, 1)\n sage: L.is_abelian()\n True\n sage: L.<x,y> = LieAlgebra(QQ, 2)\n sage: L.is_abelian()\n False\n "
G = self.lie_algebra_generators()
if (G not in FiniteEnumeratedSets()):
raise NotImplementedError('infinite number of generators')
zero = self.zero()
return all(((x._bracket_(y) == zero) for x in G for y in G))
def is_commutative(self):
'\n Return if ``self`` is commutative. This is equivalent to ``self``\n being abelian.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: L.is_commutative() # needs sage.combinat sage.modules\n False\n\n ::\n\n sage: L.<x> = LieAlgebra(QQ, 1) # not implemented # needs sage.combinat sage.modules\n sage: L.is_commutative() # not implemented # needs sage.combinat sage.modules\n True\n '
return self.is_abelian()
@abstract_method(optional=True)
def is_solvable(self):
'\n Return if ``self`` is a solvable Lie algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.is_solvable() # needs sage.modules\n True\n '
@abstract_method(optional=True)
def is_nilpotent(self):
'\n Return if ``self`` is a nilpotent Lie algebra.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.is_nilpotent() # needs sage.modules\n True\n '
def bch(self, X, Y, prec=None):
'\n Return the element `\\log(\\exp(X)\\exp(Y))`.\n\n The BCH formula is an expression for `\\log(\\exp(X)\\exp(Y))`\n as a sum of Lie brackets of ``X ` and ``Y`` with rational\n coefficients. It is only defined if the base ring of\n ``self`` has a coercion from the rationals.\n\n INPUT:\n\n - ``X`` -- an element of ``self``\n - ``Y`` -- an element of ``self``\n - ``prec`` -- an integer; the maximum length of Lie brackets to be\n considered in the formula\n\n EXAMPLES:\n\n The BCH formula for the generators of a free nilpotent Lie\n algebra of step 4::\n\n sage: L = LieAlgebra(QQ, 2, step=4) # needs sage.combinat sage.modules\n sage: L.inject_variables() # needs sage.combinat sage.modules\n Defining X_1, X_2, X_12, X_112, X_122, X_1112, X_1122, X_1222\n sage: L.bch(X_1, X_2) # needs sage.combinat sage.modules\n X_1 + X_2 + 1/2*X_12 + 1/12*X_112 + 1/12*X_122 + 1/24*X_1122\n\n An example of the BCH formula in a quotient::\n\n sage: Q = L.quotient(X_112 + X_122) # needs sage.combinat sage.modules\n sage: x, y = Q.basis().list()[:2] # needs sage.combinat sage.modules\n sage: Q.bch(x, y) # needs sage.combinat sage.modules\n X_1 + X_2 + 1/2*X_12 - 1/24*X_1112\n\n The BCH formula for a non-nilpotent Lie algebra requires the\n precision to be explicitly stated::\n\n sage: L.<X,Y> = LieAlgebra(QQ) # needs sage.combinat sage.modules\n sage: L.bch(X, Y) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n ValueError: the Lie algebra is not known to be nilpotent,\n so you must specify the precision\n sage: L.bch(X, Y, 4) # needs sage.combinat sage.modules\n X + 1/12*[X, [X, Y]] + 1/24*[X, [[X, Y], Y]]\n + 1/2*[X, Y] + 1/12*[[X, Y], Y] + Y\n\n The BCH formula requires a coercion from the rationals::\n\n sage: L.<X,Y,Z> = LieAlgebra(ZZ, 2, step=2) # needs sage.combinat sage.modules\n sage: L.bch(X, Y) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n TypeError: the BCH formula is not well defined\n since Integer Ring has no coercion from Rational Field\n '
if ((self not in LieAlgebras.Nilpotent) and (prec is None)):
raise ValueError('the Lie algebra is not known to be nilpotent, so you must specify the precision')
from sage.algebras.lie_algebras.bch import bch_iterator
if (prec is None):
return self.sum((Z for Z in bch_iterator(X, Y)))
bch = bch_iterator(X, Y)
return self.sum((next(bch) for k in range(prec)))
baker_campbell_hausdorff = bch
@abstract_method(optional=True)
def lie_group(self, name='G', **kwds):
"\n Return the simply connected Lie group related 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 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 "
def trivial_representation(self):
'\n Return the trivial representation of ``self``.\n\n EXAMPLES::\n\n sage: L = lie_algebras.strictly_upper_triangular_matrices(QQ, 4)\n sage: L.trivial_representation()\n Trivial representation of Lie algebra of 4-dimensional\n strictly upper triangular matrices over Rational Field\n '
from sage.algebras.lie_algebras.representation import TrivialRepresentation
return TrivialRepresentation(self)
def representation(self, f=None, index_set=None, on_basis=False, **kwargs):
"\n Return a representation of ``self``.\n\n If no arguments are given, then this returns the trivial\n representation.\n\n Currently the only implemented method of constructing a\n representation is by explicitly specifying the action of\n\n * the elements of ``self`` by matrices;\n * the basis elements of ``self`` using a ``dict`` or\n a :func:`Family`;\n * a function on basis elements (either passed as ``on_basis``\n or setting ``on_basis=True``).\n\n INPUT:\n\n - ``f`` -- the function that defines the action\n - ``index_set`` -- the index set of the representation\n - ``on_basis`` -- (optional) see above\n\n .. SEEALSO::\n\n :class:`~sage.algebras.lie_algebras.representation.RepresentationByMorphism`\n\n EXAMPLES::\n\n sage: L.<x,y> = LieAlgebra(QQ, {('x','y'): {'y':1}})\n sage: f = {x: Matrix([[1,0],[0,0]]), y: Matrix([[0,1],[0,0]])}\n sage: L.representation(f)\n Representation of Lie algebra on 2 generators (x, y) over Rational Field defined by:\n [1 0]\n x |--> [0 0]\n [0 1]\n y |--> [0 0]\n sage: L.representation()\n Trivial representation of Lie algebra on 2 generators (x, y) over Rational Field\n "
if ((f is None) and (on_basis is False) and (index_set is None)):
return self.trivial_representation(**kwargs)
from sage.algebras.lie_algebras.representation import RepresentationByMorphism
return RepresentationByMorphism(self, f, index_set, on_basis, **kwargs)
def _test_jacobi_identity(self, **options):
'\n Test that the Jacobi identity is satisfied on (not\n necessarily all) elements of this set.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`.\n\n EXAMPLES:\n\n By default, this method runs the tests only on the\n elements returned by ``self.some_elements()``::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: L._test_jacobi_identity() # needs sage.combinat sage.modules\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: x,y = L.lie_algebra_generators() # needs sage.combinat sage.modules\n sage: L._test_jacobi_identity(elements=[x + y, x, 2*y, x.bracket(y)]) # needs sage.combinat sage.modules\n\n See the documentation for :class:`TestSuite` for more information.\n '
tester = self._tester(**options)
elts = tester.some_elements()
jacobi = (lambda x, y, z: ((self.bracket(x, self.bracket(y, z)) + self.bracket(y, self.bracket(z, x))) + self.bracket(z, self.bracket(x, y))))
zero = self.zero()
for x in elts:
for y in elts:
if (x == y):
continue
for z in elts:
tester.assertEqual(jacobi(x, y, z), zero)
def _test_antisymmetry(self, **options):
'\n Test that the antisymmetry axiom is satisfied on (not\n necessarily all) elements of this set.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`.\n\n EXAMPLES:\n\n By default, this method runs the tests only on the\n elements returned by ``self.some_elements()``::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: L._test_antisymmetry() # needs sage.combinat sage.modules\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: x,y = L.lie_algebra_generators() # needs sage.combinat sage.modules\n sage: L._test_antisymmetry(elements=[x + y, x, 2*y, x.bracket(y)]) # needs sage.combinat sage.modules\n\n See the documentation for :class:`TestSuite` for more information.\n '
tester = self._tester(**options)
elts = tester.some_elements()
zero = self.zero()
for x in elts:
tester.assertEqual(self.bracket(x, x), zero)
def _test_distributivity(self, **options):
'\n Test the distributivity of the Lie bracket `[,]` on `+` on (not\n necessarily all) elements of this set.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`.\n\n TESTS::\n\n sage: L = LieAlgebras(QQ).example() # needs sage.combinat sage.modules\n sage: L._test_distributivity() # needs sage.combinat sage.modules\n\n EXAMPLES:\n\n By default, this method runs the tests only on the\n elements returned by ``self.some_elements()``::\n\n sage: L = LieAlgebra(QQ, 3, \'x,y,z\', representation="polynomial") # needs sage.combinat sage.modules\n sage: L.some_elements() # needs sage.combinat sage.modules\n [x + y + z]\n sage: L._test_distributivity() # needs sage.combinat sage.modules\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: # not implemented, needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type=[\'A\', 2])\n sage: h1 = L.gen(0)\n sage: h2 = L.gen(1)\n sage: e2 = L.gen(3)\n sage: L._test_distributivity(elements=[h1, h2, e2])\n\n See the documentation for :class:`TestSuite` for more information.\n '
tester = self._tester(**options)
S = tester.some_elements()
from sage.misc.misc import some_tuples
for (x, y, z) in some_tuples(S, 3, tester._max_runs):
tester.assertEqual(self.bracket(x, (y + z)), (self.bracket(x, y) + self.bracket(x, z)))
tester.assertEqual(self.bracket((x + y), z), (self.bracket(x, z) + self.bracket(y, z)))
class ElementMethods():
@coerce_binop
def bracket(self, rhs):
'\n Return the Lie bracket ``[self, rhs]``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).example()\n sage: x,y = L.lie_algebra_generators()\n sage: x.bracket(y)\n -[1, 3, 2] + [3, 2, 1]\n sage: x.bracket(0)\n 0\n '
return self._bracket_(rhs)
@abstract_method
def _bracket_(self, y):
'\n Return the Lie bracket ``[self, y]``, where ``y`` is an\n element of the same Lie algebra as ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).example()\n sage: x,y = L.lie_algebra_generators()\n sage: x._bracket_(y)\n -[1, 3, 2] + [3, 2, 1]\n sage: y._bracket_(x)\n [1, 3, 2] - [3, 2, 1]\n sage: x._bracket_(x)\n 0\n '
@abstract_method(optional=True)
def to_vector(self, order=None):
'\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:`LieAlgebras.module` 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((1, 0, 0)).to_vector(); u # needs sage.modules\n (1, 0, 0)\n sage: parent(u) # needs sage.modules\n Vector space of dimension 3 over Rational Field\n '
@abstract_method(optional=True)
def lift(self):
'\n Return the image of ``self`` under the canonical lift from the Lie\n algebra to its universal enveloping algebra.\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: elt = 3*a + b - c\n sage: elt.lift()\n 3*b0 + b1 - b2\n\n ::\n\n sage: L.<x,y> = LieAlgebra(QQ, abelian=True) # needs sage.combinat sage.modules\n sage: x.lift() # needs sage.combinat sage.modules\n x\n '
def killing_form(self, x):
'\n Return the Killing form of ``self`` and ``x``.\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: a.killing_form(b) # needs sage.modules\n 0\n '
return self.parent().killing_form(self, x)
def exp(self, lie_group=None):
"\n Return the exponential of ``self`` in ``lie_group``.\n\n INPUT:\n\n - ``lie_group`` -- (optional) the Lie group to map into;\n If ``lie_group`` is not given, the Lie group associated to the\n parent Lie algebra of ``self`` is used.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L.<X,Y,Z> = LieAlgebra(QQ, 2, step=2)\n sage: g = (X + Y + Z).exp(); g # needs sage.symbolic\n exp(X + Y + Z)\n sage: h = X.exp(); h # needs sage.symbolic\n exp(X)\n sage: g.parent() # needs sage.symbolic\n Lie group G of Free Nilpotent Lie algebra on 3 generators (X, Y, Z)\n over Rational Field\n sage: g.parent() is h.parent() # needs sage.symbolic\n True\n\n The Lie group can be specified explicitly::\n\n sage: # needs sage.combinat sage.modules sage.symbolic\n sage: H = L.lie_group('H')\n sage: k = Z.exp(lie_group=H); k\n exp(Z)\n sage: k.parent()\n Lie group H of Free Nilpotent Lie algebra on 3 generators (X, Y, Z)\n over Rational Field\n sage: g.parent() == k.parent()\n False\n "
if (lie_group is None):
lie_group = self.parent().lie_group()
return lie_group.exp(self)
|
class LiftMorphism(Morphism):
'\n The natural lifting morphism from a Lie algebra to its\n enveloping algebra.\n '
def __init__(self, domain, codomain):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: f = L.lift # needs sage.combinat sage.modules\n\n We skip the category test since this is currently not an element of\n a homspace::\n\n sage: TestSuite(f).run(skip="_test_category") # needs sage.combinat sage.modules\n '
Morphism.__init__(self, Hom(domain, codomain))
def _call_(self, x):
'\n Lift ``x`` to the universal enveloping algebra.\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.lift(3*a + b - c) # needs sage.combinat sage.modules\n 3*b0 + b1 - b2\n '
return x.lift()
|
class LieAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n Category of Lie algebras with a basis.\n '
_base_category_class_and_axiom = (LieAlgebras, 'WithBasis')
def example(self, gens=None):
'\n Return an example of a Lie algebra as per\n :meth:`Category.example <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: LieAlgebras(QQ).WithBasis().example() # needs sage.combinat sage.modules\n An example of a Lie algebra: the abelian Lie algebra on the\n generators indexed by Partitions over Rational Field\n\n Another set of generators can be specified as an optional argument::\n\n sage: LieAlgebras(QQ).WithBasis().example(Compositions()) # needs sage.combinat sage.modules\n An example of a Lie algebra: the abelian Lie algebra on the\n generators indexed by Compositions of non-negative integers\n over Rational Field\n '
if (gens is None):
from sage.combinat.partition import Partitions
gens = Partitions()
from sage.categories.examples.lie_algebras_with_basis import Example
return Example(self.base_ring(), gens)
Graded = LazyImport('sage.categories.graded_lie_algebras_with_basis', 'GradedLieAlgebrasWithBasis', as_name='Graded')
class ParentMethods():
def _basis_key(self, x):
'\n Return the key used to compare two basis element indices.\n\n The default is to call the element itself.\n\n TESTS::\n\n sage: L = LieAlgebras(QQ).WithBasis().example() # needs sage.combinat sage.modules\n sage: L._basis_key(Partition([3,1])) # needs sage.combinat sage.modules\n [3, 1]\n '
return x
@abstract_method(optional=True)
def bracket_on_basis(self, x, y):
'\n Return the bracket of basis elements indexed by ``x`` and ``y``\n where ``x < y``. If this is not implemented, then the method\n ``_bracket_()`` for the elements must be overwritten.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example() # needs sage.combinat sage.modules\n sage: L.bracket_on_basis(Partition([3,1]), Partition([2,2,1,1])) # needs sage.combinat sage.modules\n 0\n '
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 EXAMPLES::\n\n sage: L = LieAlgebras(QQ).WithBasis().example() # needs sage.combinat sage.modules\n sage: L.module() # needs sage.combinat sage.modules\n Free module generated by Partitions over Rational Field\n '
from sage.combinat.free_module import CombinatorialFreeModule
try:
return CombinatorialFreeModule(self.base_ring(), self.basis().keys())
except AttributeError:
return CombinatorialFreeModule(self.base_ring(), self.basis())
def from_vector(self, v, order=None, coerce=False):
'\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 '
B = self.basis()
return self.sum(((v[i] * B[i]) for i in v.support()))
def dimension(self):
"\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.dimension() # needs sage.modules\n 3\n\n ::\n\n sage: L = LieAlgebra(QQ, 'x,y', {('x','y'): {'x':1}}) # needs sage.combinat sage.modules\n sage: L.dimension() # needs sage.combinat sage.modules\n 2\n "
return self.basis().cardinality()
def pbw_basis(self, basis_key=None, **kwds):
'\n Return the Poincare-Birkhoff-Witt basis of the universal\n enveloping algebra corresponding to ``self``.\n\n EXAMPLES::\n\n sage: L = lie_algebras.sl(QQ, 2) # needs sage.combinat sage.modules\n sage: PBW = L.pbw_basis() # needs sage.combinat sage.modules\n '
from sage.algebras.lie_algebras.poincare_birkhoff_witt import PoincareBirkhoffWittBasis
return PoincareBirkhoffWittBasis(self, basis_key, **kwds)
poincare_birkhoff_witt_basis = pbw_basis
_construct_UEA = pbw_basis
class ElementMethods():
def _bracket_(self, y):
'\n Return the Lie bracket ``[self, y]``, where ``y`` is an\n element of the same Lie algebra as ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebras(QQ).WithBasis().example()\n sage: G = L.lie_algebra_generators()\n sage: x = G[Partition([4,3,3,1])]\n sage: y = G[Partition([6,1])]\n sage: x.bracket(y)\n 0\n '
P = self.parent()
def term(ml, mr):
key_ml = P._basis_key(ml)
key_mr = P._basis_key(mr)
if (key_ml == key_mr):
return P.zero()
if (key_ml < key_mr):
return P.bracket_on_basis(ml, mr)
return (- P.bracket_on_basis(mr, ml))
return P.sum((((cl * cr) * term(ml, mr)) for (ml, cl) in self for (mr, cr) in y))
def to_vector(self, order=None):
'\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: L = LieAlgebras(QQ).FiniteDimensional().WithBasis().example() # needs sage.modules\n sage: L.an_element().to_vector() # needs sage.modules\n (0, 0, 0)\n\n .. TODO::\n\n Doctest this implementation on an example not overshadowed.\n '
M = self.parent().module()
B = M.basis()
return M.sum(((self[i] * B[i]) for i in self.support()))
def lift(self):
'\n Lift ``self`` to the universal enveloping algebra.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: S = SymmetricGroup(3).algebra(QQ)\n sage: L = LieAlgebra(associative=S)\n sage: x = L.gen(3)\n sage: y = L.gen(1)\n sage: x.lift()\n b3\n sage: y.lift()\n b1\n sage: x * y\n b1*b3 + b4 - b5\n '
P = self.parent()
UEA = P.universal_enveloping_algebra()
try:
gen_dict = UEA.algebra_generators()
except (TypeError, AttributeError):
gen_dict = UEA.gens_dict()
s = UEA.zero()
if (not self):
return s
if hasattr(P, '_UEA_names_map'):
names_map = P._UEA_names_map
for (t, c) in self.monomial_coefficients(copy=False).items():
s += (c * gen_dict[names_map[t]])
else:
for (t, c) in self.monomial_coefficients(copy=False).items():
s += (c * gen_dict[t])
return s
|
class LieConformalAlgebras(Category_over_base_ring):
'\n The category of Lie conformal algebras.\n\n This is the base category for all Lie conformal algebras.\n Subcategories with axioms are ``FinitelyGenerated`` and\n ``WithBasis``. A *finitely generated* Lie conformal algebra is a\n Lie conformal algebra over `R` which is finitely generated as an\n `R[T]`-module. A Lie conformal algebra *with basis* is one with a\n preferred basis as an `R`-module.\n\n EXAMPLES:\n\n The base category::\n\n sage: C = LieConformalAlgebras(QQ); C\n Category of Lie conformal algebras over Rational Field\n sage: C.is_subcategory(VectorSpaces(QQ))\n True\n\n Some subcategories::\n\n sage: LieConformalAlgebras(QQbar).FinitelyGenerated().WithBasis() # needs sage.rings.number_field\n Category of finitely generated Lie conformal algebras with basis\n over Algebraic Field\n\n In addition we support functorial constructions ``Graded`` and\n ``Super``. These functors commute::\n\n sage: CGS = LieConformalAlgebras(AA).Graded().Super(); CGS # needs sage.rings.number_field\n Category of H-graded super Lie conformal algebras over Algebraic Real Field\n sage: CGS is LieConformalAlgebras(AA).Super().Graded() # needs sage.rings.number_field\n True\n\n That is, we only consider gradings on super Lie conformal algebras\n that are compatible with the `\\ZZ/2\\ZZ` grading.\n\n The base ring needs to be a commutative ring::\n\n sage: LieConformalAlgebras(QuaternionAlgebra(2)) # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ValueError: base must be a commutative ring\n got Quaternion Algebra (-1, -1) with base ring Rational Field\n '
@cached_method
def super_categories(self):
'\n The list of super categories of this category.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQ)\n sage: C.super_categories()\n [Category of Lambda bracket algebras over Rational Field]\n sage: C = LieConformalAlgebras(QQ).FinitelyGenerated(); C\n Category of finitely generated Lie conformal algebras over Rational Field\n sage: C.super_categories()\n [Category of finitely generated lambda bracket algebras over Rational Field,\n Category of Lie conformal algebras over Rational Field]\n sage: C.all_super_categories()\n [Category of finitely generated Lie conformal algebras over Rational Field,\n Category of finitely generated lambda bracket algebras over Rational Field,\n Category of Lie conformal algebras over Rational Field,\n Category of Lambda bracket algebras over Rational Field,\n Category of vector spaces over Rational Field,\n Category of modules over Rational Field,\n Category of bimodules over Rational Field on the left and Rational Field on the right,\n Category of right modules over Rational Field,\n Category of left modules over Rational Field,\n Category of commutative additive groups,\n Category of additive groups,\n Category of additive inverse additive unital additive magmas,\n Category of commutative additive monoids,\n Category of additive monoids,\n Category of additive unital additive magmas,\n Category of commutative additive semigroups,\n Category of additive commutative additive magmas,\n Category of additive semigroups,\n Category of additive magmas,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
return [LambdaBracketAlgebras(self.base_ring())]
def example(self):
'\n An example of parent in this category.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ).example() # needs sage.combinat sage.modules\n The Virasoro Lie conformal algebra over Rational Field\n '
from sage.algebras.lie_conformal_algebras.virasoro_lie_conformal_algebra import VirasoroLieConformalAlgebra
return VirasoroLieConformalAlgebra(self.base_ring())
def _repr_object_names(self):
'\n The name of the objects of this category.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ)\n Category of Lie conformal algebras over Rational Field\n '
return 'Lie conformal algebras over {}'.format(self.base_ring())
class ParentMethods():
def _test_jacobi(self, **options):
"\n Test the Jacobi axiom of this Lie conformal algebra.\n\n INPUT:\n\n - ``options`` -- any keyword arguments acceptde by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: V = lie_conformal_algebras.Affine(QQ, 'B2') # needs sage.combinat sage.modules\n sage: V._test_jacobi() # long time (6 seconds) # needs sage.combinat sage.modules\n\n It works for super Lie conformal algebras too::\n\n sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) # needs sage.combinat sage.modules\n sage: V._test_jacobi() # needs sage.combinat sage.modules\n\n We can use specific elements by passing the ``elements``\n keyword argument::\n\n sage: V = lie_conformal_algebras.Affine(QQ, 'A1', # needs sage.combinat sage.modules\n ....: names=('e', 'h', 'f'))\n sage: V.inject_variables() # needs sage.combinat sage.modules\n Defining e, h, f, K\n sage: V._test_jacobi(elements=(e, 2*f+h, 3*h)) # needs sage.combinat sage.modules\n\n TESTS::\n\n sage: wrongdict = {('a', 'a'): {0: {('b', 0): 1}}, ('b', 'a'): {0: {('a', 0): 1}}}\n sage: V = LieConformalAlgebra(QQ, wrongdict, names=('a', 'b'), parity=(1, 0)) # needs sage.combinat sage.modules\n sage: V._test_jacobi() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n AssertionError: {(0, 0): -3*a} != {}\n - {(0, 0): -3*a}\n + {}\n "
tester = self._tester(**options)
S = tester.some_elements()
from sage.arith.misc import binomial
from sage.misc.misc import some_tuples
pz = tester._instance.zero()
for (x, y, z) in some_tuples(S, 3, tester._max_runs):
brxy = x.bracket(y)
brxz = x.bracket(z)
bryz = y.bracket(z)
br1 = {k: x.bracket(v) for (k, v) in bryz.items()}
br2 = {k: v.bracket(z) for (k, v) in brxy.items()}
br3 = {k: y.bracket(v) for (k, v) in brxz.items()}
jac1 = {(j, k): v for k in br1 for (j, v) in br1[k].items()}
jac3 = {(k, j): v for k in br3 for (j, v) in br3[k].items()}
jac2 = {}
for (k, br) in br2.items():
for (j, v) in br.items():
for r in range((j + 1)):
jac2[((k + r), (j - r))] = (jac2.get(((k + r), (j - r)), pz) + (binomial((k + r), r) * v))
for (k, v) in jac2.items():
jac1[k] = (jac1.get(k, pz) - v)
for (k, v) in jac3.items():
jac1[k] = (jac1.get(k, pz) - v)
jacobiator = {k: v for (k, v) in jac1.items() if v}
tester.assertDictEqual(jacobiator, {})
class ElementMethods():
def is_even_odd(self):
'\n Return ``0`` if this element is *even* and ``1`` if it is\n *odd*.\n\n .. NOTE::\n\n This method returns ``0`` by default since every Lie\n conformal algebra can be thought as a purely even Lie\n conformal algebra. In order to\n implement a super Lie conformal algebra, the user\n needs to implement this method.\n\n EXAMPLES::\n\n sage: R = lie_conformal_algebras.NeveuSchwarz(QQ) # needs sage.combinat sage.modules\n sage: R.inject_variables() # needs sage.combinat sage.modules\n Defining L, G, C\n sage: G.is_even_odd() # needs sage.combinat sage.modules\n 1\n '
return 0
Graded = LazyImport('sage.categories.graded_lie_conformal_algebras', 'GradedLieConformalAlgebras', 'Graded')
Super = LazyImport('sage.categories.super_lie_conformal_algebras', 'SuperLieConformalAlgebras', 'Super')
WithBasis = LazyImport('sage.categories.lie_conformal_algebras_with_basis', 'LieConformalAlgebrasWithBasis', 'WithBasis')
FinitelyGeneratedAsLambdaBracketAlgebra = LazyImport('sage.categories.finitely_generated_lie_conformal_algebras', 'FinitelyGeneratedLieConformalAlgebras')
|
class LieConformalAlgebrasWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of Lie conformal algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis() # needs sage.rings.number_field\n Category of Lie conformal algebras with basis over Algebraic Field\n '
class Super(SuperModulesCategory):
'\n The category of super Lie conformal algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(AA).WithBasis().Super() # needs sage.rings.number_field\n Category of super Lie conformal algebras with basis\n over Algebraic Real Field\n '
class ParentMethods():
def _even_odd_on_basis(self, m):
"\n Return the parity of the basis element indexed by ``m``.\n\n OUTPUT:\n\n ``0`` if ``m`` is for an even element or ``1`` if ``m``\n is for an odd element.\n\n EXAMPLES::\n\n sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) # needs sage.combinat sage.modules\n sage: B = V._indices # needs sage.combinat sage.modules\n sage: V._even_odd_on_basis(B(('G', 1))) # needs sage.combinat sage.modules\n 1\n "
return self._parity[self.monomial((m[0], 0))]
class Graded(GradedLieConformalAlgebrasCategory):
'\n The category of H-graded super Lie conformal algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis().Super().Graded() # needs sage.rings.number_field\n Category of H-graded super Lie conformal algebras with basis\n over Algebraic Field\n '
class Graded(GradedLieConformalAlgebrasCategory):
'\n The category of H-graded Lie conformal algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).WithBasis().Graded() # needs sage.rings.number_field\n Category of H-graded Lie conformal algebras with basis over Algebraic Field\n '
class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring):
'\n The category of finitely generated Lie conformal\n algebras with basis.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar) # needs sage.rings.number_field\n sage: CWF = C.WithBasis().FinitelyGenerated(); CWF # needs sage.rings.number_field\n Category of finitely generated Lie conformal algebras with basis\n over Algebraic Field\n sage: CWF is C.FinitelyGenerated().WithBasis() # needs sage.rings.number_field\n True\n '
class Super(SuperModulesCategory):
'\n The category of super finitely generated Lie conformal\n algebras with basis.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(AA).WithBasis().FinitelyGenerated().Super() # needs sage.rings.number_field\n Category of super finitely generated Lie conformal algebras with basis\n over Algebraic Real Field\n '
class Graded(GradedModulesCategory):
'\n The category of H-graded super finitely generated Lie\n conformal algebras with basis.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() # needs sage.rings.number_field\n sage: C.Graded().Super() # needs sage.rings.number_field\n Category of H-graded super finitely generated Lie conformal algebras\n with basis over Algebraic Field\n sage: C.Graded().Super() is C.Super().Graded() # needs sage.rings.number_field\n True\n '
def _repr_object_names(self):
'\n The names of the objects of ``self``.\n\n EXAMPLES::\n\n sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() # needs sage.rings.number_field\n sage: C.Super().Graded() # needs sage.rings.number_field\n Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
class Graded(GradedLieConformalAlgebrasCategory):
'\n The category of H-graded finitely generated Lie conformal\n algebras with basis.\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 '
|
class LieGroups(Category_over_base_ring):
'\n The category of Lie groups.\n\n A Lie group is a topological group with a smooth manifold structure.\n\n EXAMPLES::\n\n sage: from sage.categories.lie_groups import LieGroups\n sage: C = LieGroups(QQ); C\n Category of Lie groups over Rational Field\n\n TESTS::\n\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.lie_groups import LieGroups\n sage: LieGroups(QQ).super_categories()\n [Category of topological groups,\n Category of smooth manifolds over Rational Field]\n '
return [Groups().Topological(), Manifolds(self.base()).Smooth()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of Lie groups defines no new\n structure: a morphism of topological spaces and of smooth\n manifolds is a morphism as Lie groups.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: from sage.categories.lie_groups import LieGroups\n sage: LieGroups(QQ).additional_structure()\n '
return None
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: from sage.categories.lie_groups import LieGroups\n sage: LieGroups(QQ) # indirect doctest\n Category of Lie groups over Rational Field\n '
return 'Lie groups over {}'.format(self.base_ring())
|
class LoopCrystals(Category_singleton):
"\n The category of `U_q'(\\mathfrak{g})`-crystals, where `\\mathfrak{g}`\n is of affine type.\n\n The category is called loop crystals as we can also consider them\n as crystals corresponding to the loop algebra `\\mathfrak{g}_0[t]`,\n where `\\mathfrak{g}_0` is the corresponding classical type.\n\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import LoopCrystals\n sage: C = LoopCrystals()\n sage: C\n Category of loop crystals\n sage: C.super_categories()\n [Category of crystals]\n sage: C.example()\n Kirillov-Reshetikhin crystal of type ['A', 3, 1] with (r,s)=(1,1)\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: B = FiniteCrystals().example()\n sage: TestSuite(B).run()\n "
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import LoopCrystals\n sage: LoopCrystals().super_categories()\n [Category of crystals]\n '
return [Crystals()]
def example(self, n=3):
"\n Return an example of Kirillov-Reshetikhin crystals, as per\n :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import LoopCrystals\n sage: B = LoopCrystals().example(); B\n Kirillov-Reshetikhin crystal of type ['A', 3, 1] with (r,s)=(1,1)\n "
from sage.combinat.crystals.kirillov_reshetikhin import KirillovReshetikhinCrystal
return KirillovReshetikhinCrystal(['A', n, 1], 1, 1)
class ParentMethods():
def weight_lattice_realization(self):
"\n Return the weight lattice realization used to express weights\n of elements in ``self``.\n\n The default is to use the non-extended affine weight lattice.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A', 5])\n sage: C.weight_lattice_realization()\n Ambient space of the Root system of type ['A', 5]\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1, 1)\n sage: K.weight_lattice_realization()\n Weight lattice of the Root system of type ['A', 2, 1]\n "
F = self.cartan_type().root_system()
return F.weight_lattice(extended=False)
def digraph(self, subset=None, index_set=None):
"\n Return the :class:`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 .. SEEALSO::\n\n :meth:`sage.categories.crystals.Crystals.ParentMethods.digraph`\n\n EXAMPLES::\n\n sage: C = crystals.KirillovReshetikhin(['D',4,1], 2, 1)\n sage: G = C.digraph()\n sage: G.latex_options() # optional - dot2tex\n LaTeX options for Digraph on 29 vertices:\n {...'edge_options': <function ... at ...>...}\n sage: view(G, tightpage=True) # optional - dot2tex graphviz, not tested (opens external window)\n "
from sage.graphs.dot2tex_utils import have_dot2tex
G = Crystals().parent_class.digraph(self, subset, index_set)
if have_dot2tex():
def eopt(u_v_label):
return {'backward': (u_v_label[2] == 0)}
G.set_latex_options(edge_options=eopt)
return G
|
class RegularLoopCrystals(Category_singleton):
"\n The category of regular `U_q'(\\mathfrak{g})`-crystals, where\n `\\mathfrak{g}` is of affine type.\n "
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import RegularLoopCrystals\n sage: RegularLoopCrystals().super_categories()\n [Category of regular crystals,\n Category of loop crystals]\n '
return [RegularCrystals(), LoopCrystals()]
class ElementMethods():
def classical_weight(self):
"\n Return the classical weight of ``self``.\n\n EXAMPLES::\n\n sage: R = RootSystem(['A',2,1])\n sage: La = R.weight_space().basis()\n sage: LS = crystals.ProjectedLevelZeroLSPaths(2*La[1])\n sage: hw = LS.classically_highest_weight_vectors()\n sage: [(v.weight(), v.classical_weight()) for v in hw]\n [(-2*Lambda[0] + 2*Lambda[1], (2, 0, 0)),\n (-Lambda[0] + Lambda[2], (1, 1, 0))]\n "
CT = self.cartan_type().classical()
I0 = CT.index_set()
La = CT.root_system().ambient_space().fundamental_weights()
return sum(((La[i] * (self.phi(i) - self.epsilon(i))) for i in I0))
|
class KirillovReshetikhinCrystals(Category_singleton):
'\n Category of Kirillov-Reshetikhin crystals.\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import KirillovReshetikhinCrystals\n sage: KirillovReshetikhinCrystals().super_categories()\n [Category of finite regular loop crystals]\n '
return [RegularLoopCrystals().Finite()]
class ParentMethods():
@abstract_method
def r(self):
"\n Return the value `r` in ``self`` written as `B^{r,s}`.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',3,1], 2,4)\n sage: K.r()\n 2\n "
@abstract_method
def s(self):
"\n Return the value `s` in ``self`` written as `B^{r,s}`.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',3,1], 2,4)\n sage: K.s()\n 4\n "
@abstract_method(optional=True)
def classical_decomposition(self):
"\n Return the classical decomposition of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',3,1], 2,2)\n sage: K.classical_decomposition()\n The crystal of tableaux of type ['A', 3] and shape(s) [[2, 2]]\n "
@cached_method
def classically_highest_weight_vectors(self):
"\n Return the classically highest weight elements of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['E',6,1],1,1)\n sage: K.classically_highest_weight_vectors()\n ([(1,)],)\n "
I0 = self.cartan_type().classical().index_set()
return tuple([x for x in self if x.is_highest_weight(I0)])
def cardinality(self):
"\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['E',6,1], 1,1)\n sage: K.cardinality()\n 27\n sage: K = crystals.KirillovReshetikhin(['C',6,1], 4,3)\n sage: K.cardinality()\n 4736732\n "
CWLR = self.cartan_type().classical().root_system().ambient_space()
return sum((CWLR.weyl_dimension(mg.classical_weight()) for mg in self.classically_highest_weight_vectors()))
@cached_method
def maximal_vector(self):
"\n Return the unique element of classical weight `s \\Lambda_r`\n in ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1],1,2)\n sage: K.maximal_vector()\n [[1, 1]]\n sage: K = crystals.KirillovReshetikhin(['E',6,1],1,1)\n sage: K.maximal_vector()\n [(1,)]\n\n sage: K = crystals.KirillovReshetikhin(['D',4,1],2,1)\n sage: K.maximal_vector()\n [[1], [2]]\n\n TESTS:\n\n Check that :trac:`23028` is fixed::\n\n sage: ct = CartanType(['A',8,2]).dual()\n sage: K = crystals.KirillovReshetikhin(ct, 4, 1)\n sage: K.maximal_vector()\n [[1], [2], [3], [4]]\n sage: K = crystals.KirillovReshetikhin(ct, 4, 2)\n sage: K.maximal_vector()\n [[1, 1], [2, 2], [3, 3], [4, 4]]\n "
R = self.weight_lattice_realization()
Lambda = R.fundamental_weights()
r = self.r()
s = self.s()
if (self.cartan_type().dual().type() == 'BC'):
if ((self.cartan_type().rank() - 1) == r):
weight = (((2 * s) * Lambda[r]) - (s * Lambda[0]))
else:
weight = ((s * Lambda[r]) - (s * Lambda[0]))
else:
weight = ((s * Lambda[r]) - (((s * Lambda[0]) * Lambda[r].level()) / Lambda[0].level()))
for b in self.module_generators:
if (b.weight() == weight):
return b
for b in self:
if ((b not in self.module_generators) and (b.weight() == weight)):
return b
assert False, 'BUG: invalid Kirillov-Reshetikhin crystal'
def module_generator(self):
"\n Return the unique module generator of classical weight\n `s \\Lambda_r` of the Kirillov-Reshetikhin crystal `B^{r,s}`.\n\n EXAMPLES::\n\n sage: La = RootSystem(['G',2,1]).weight_space().fundamental_weights()\n sage: K = crystals.ProjectedLevelZeroLSPaths(La[1])\n sage: K.module_generator()\n (-Lambda[0] + Lambda[1],)\n "
return self.maximal_vector()
def affinization(self):
"\n Return the corresponding affinization crystal of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1, 1)\n sage: K.affinization()\n Affinization of Kirillov-Reshetikhin crystal of type ['A', 2, 1] with (r,s)=(1,1)\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1, 1, model='KR')\n sage: K.affinization()\n Affinization of Kirillov-Reshetikhin tableaux of type ['A', 2, 1] and shape (1, 1)\n "
from sage.combinat.crystals.affinization import AffinizationOfCrystal
return AffinizationOfCrystal(self)
@cached_method
def R_matrix(self, K):
"\n Return the combinatorial `R`-matrix of ``self`` to ``K``.\n\n The *combinatorial* `R`-*matrix* is the affine crystal\n isomorphism `R : L \\otimes K \\to K \\otimes L` which maps\n `u_{L} \\otimes u_K` to `u_K \\otimes u_{L}`, where `u_K`\n is the unique element in `K = B^{r,s}` of weight\n `s\\Lambda_r - s c \\Lambda_0` (see :meth:`maximal_vector`).\n\n INPUT:\n\n - ``self`` -- a crystal `L`\n - ``K`` -- a Kirillov-Reshetikhin crystal of the same type as `L`\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: L = crystals.KirillovReshetikhin(['A',2,1],1,2)\n sage: f = K.R_matrix(L)\n sage: [[b,f(b)] for b in crystals.TensorProduct(K,L)]\n [[[[[1]], [[1, 1]]], [[[1, 1]], [[1]]]],\n [[[[1]], [[1, 2]]], [[[1, 1]], [[2]]]],\n [[[[1]], [[2, 2]]], [[[1, 2]], [[2]]]],\n [[[[1]], [[1, 3]]], [[[1, 1]], [[3]]]],\n [[[[1]], [[2, 3]]], [[[1, 2]], [[3]]]],\n [[[[1]], [[3, 3]]], [[[1, 3]], [[3]]]],\n [[[[2]], [[1, 1]]], [[[1, 2]], [[1]]]],\n [[[[2]], [[1, 2]]], [[[2, 2]], [[1]]]],\n [[[[2]], [[2, 2]]], [[[2, 2]], [[2]]]],\n [[[[2]], [[1, 3]]], [[[2, 3]], [[1]]]],\n [[[[2]], [[2, 3]]], [[[2, 2]], [[3]]]],\n [[[[2]], [[3, 3]]], [[[2, 3]], [[3]]]],\n [[[[3]], [[1, 1]]], [[[1, 3]], [[1]]]],\n [[[[3]], [[1, 2]]], [[[1, 3]], [[2]]]],\n [[[[3]], [[2, 2]]], [[[2, 3]], [[2]]]],\n [[[[3]], [[1, 3]]], [[[3, 3]], [[1]]]],\n [[[[3]], [[2, 3]]], [[[3, 3]], [[2]]]],\n [[[[3]], [[3, 3]]], [[[3, 3]], [[3]]]]]\n\n sage: K = crystals.KirillovReshetikhin(['D',4,1],1,1)\n sage: L = crystals.KirillovReshetikhin(['D',4,1],2,1)\n sage: f = K.R_matrix(L)\n sage: T = crystals.TensorProduct(K,L)\n sage: b = T( K(rows=[[1]]), L(rows=[]) )\n sage: f(b)\n [[[2], [-2]], [[1]]]\n\n Alternatively, one can compute the combinatorial `R`-matrix\n using the isomorphism method of digraphs::\n\n sage: K1 = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: K2 = crystals.KirillovReshetikhin(['A',2,1],2,1)\n sage: T1 = crystals.TensorProduct(K1,K2)\n sage: T2 = crystals.TensorProduct(K2,K1)\n sage: T1.digraph().is_isomorphic(T2.digraph(), edge_labels=True, # todo: not implemented (see #10904 and #10549)\n ....: certificate=True)\n (True, {[[[1]], [[2], [3]]]: [[[1], [3]], [[2]]],\n [[[3]], [[2], [3]]]: [[[2], [3]], [[3]]],\n [[[3]], [[1], [3]]]: [[[1], [3]], [[3]]],\n [[[1]], [[1], [3]]]: [[[1], [3]], [[1]]], [[[1]],\n [[1], [2]]]: [[[1], [2]], [[1]]],\n [[[2]], [[1], [2]]]: [[[1], [2]], [[2]]], [[[3]],\n [[1], [2]]]: [[[2], [3]], [[1]]],\n [[[2]], [[1], [3]]]: [[[1], [2]], [[3]]],\n [[[2]], [[2], [3]]]: [[[2], [3]], [[2]]]})\n "
from sage.combinat.crystals.tensor_product import TensorProductOfCrystals
T1 = TensorProductOfCrystals(self, K)
T2 = TensorProductOfCrystals(K, self)
gen1 = T1(self.maximal_vector(), K.maximal_vector())
gen2 = T2(K.maximal_vector(), self.maximal_vector())
return T1.crystal_morphism({gen1: gen2}, check=False)
@cached_method
def local_energy_function(self, B):
"\n Return the local energy function of ``self`` and ``B``.\n\n See\n :class:`~sage.categories.loop_crystals.LocalEnergyFunction`\n for a definition.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',6,2], 2,1)\n sage: Kp = crystals.KirillovReshetikhin(['A',6,2], 1,1)\n sage: H = K.local_energy_function(Kp); H\n Local energy function of\n Kirillov-Reshetikhin crystal of type ['BC', 3, 2] with (r,s)=(2,1)\n tensor\n Kirillov-Reshetikhin crystal of type ['BC', 3, 2] with (r,s)=(1,1)\n "
return LocalEnergyFunction(self, B)
@cached_method
def b_sharp(self):
"\n Return the element `b^{\\sharp}` of ``self``.\n\n Let `B` be a KR crystal. The element `b^{\\sharp}` is the unique\n element such that `\\varphi(b^{\\sharp}) = \\ell \\Lambda_0` with\n `\\ell = \\min \\{ \\langle c, \\varphi(b) \\rangle \\mid b \\in B \\}`.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',6,2], 2,1)\n sage: K.b_sharp()\n []\n sage: K.b_sharp().Phi()\n Lambda[0]\n\n sage: K = crystals.KirillovReshetikhin(['C',3,1], 1,3)\n sage: K.b_sharp()\n [[-1]]\n sage: K.b_sharp().Phi()\n 2*Lambda[0]\n\n sage: K = crystals.KirillovReshetikhin(['D',6,2], 2,2)\n sage: K.b_sharp() # long time\n []\n sage: K.b_sharp().Phi() # long time\n 2*Lambda[0]\n "
ell = float('inf')
bsharp = None
for b in self:
phi = b.Phi()
if ((list(phi.support()) == [0]) and (phi[0] < ell)):
bsharp = b
ell = phi[0]
return bsharp
def is_perfect(self, ell=None):
"\n Check if ``self`` is a perfect crystal of level ``ell``.\n\n A crystal `\\mathcal{B}` is perfect of level `\\ell` if:\n\n #. `\\mathcal{B}` is isomorphic to the crystal graph of a\n finite-dimensional `U_q'(\\mathfrak{g})`-module.\n #. `\\mathcal{B} \\otimes \\mathcal{B}` is connected.\n #. There exists a `\\lambda\\in X`, such that\n `\\mathrm{wt}(\\mathcal{B}) \\subset \\lambda + \\sum_{i\\in I}\n \\ZZ_{\\le 0} \\alpha_i` and there is a unique element in\n `\\mathcal{B}` of classical weight `\\lambda`.\n #. For all `b \\in \\mathcal{B}`,\n `\\mathrm{level}(\\varepsilon (b)) \\geq \\ell`.\n #. For all `\\Lambda` dominant weights of level `\\ell`, there\n exist unique elements `b_{\\Lambda}, b^{\\Lambda} \\in\n \\mathcal{B}`, such that `\\varepsilon(b_{\\Lambda}) =\n \\Lambda = \\varphi(b^{\\Lambda})`.\n\n Points (1)-(3) are known to hold. This method checks\n points (4) and (5).\n\n If ``self`` is the Kirillov-Reshetikhin crystal `B^{r,s}`,\n then it was proven for non-exceptional types in [FOS2010]_\n that it is perfect if and only if `s/c_r` is an integer\n (where `c_r` is a constant related to the type of the crystal).\n\n It is conjectured this is true for all affine types.\n\n INPUT:\n\n - ``ell`` -- (default: `s / c_r`) integer; the level\n\n REFERENCES:\n\n [FOS2010]_\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1, 1)\n sage: K.is_perfect()\n True\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1], 1, 1)\n sage: K.is_perfect()\n False\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1], 1, 2)\n sage: K.is_perfect()\n True\n\n sage: K = crystals.KirillovReshetikhin(['E',6,1], 1, 3)\n sage: K.is_perfect()\n True\n\n TESTS:\n\n Check that this works correctly for `B^{n,s}`\n of type `A_{2n}^{(2)\\dagger}` (:trac:`24364`)::\n\n sage: K = crystals.KirillovReshetikhin(CartanType(['A',6,2]).dual(), 3, 1)\n sage: K.is_perfect()\n True\n sage: K.is_perfect(1)\n True\n\n .. TODO::\n\n Implement a version for tensor products of KR crystals.\n "
from sage.rings.integer_ring import ZZ
if (ell is None):
if ((self.cartan_type().dual().type() == 'BC') and ((self.cartan_type().rank() - 1) == self.r())):
return True
ell = (self.s() / self.cartan_type().c()[self.r()])
if (ell not in ZZ):
return False
if (ell not in ZZ):
raise ValueError('perfectness not defined for non-integral levels')
if (self.cartan_type().classical().type() not in ['E', 'F', 'G']):
if ((self.cartan_type().dual().type() == 'BC') and ((self.cartan_type().rank() - 1) == self.r())):
return (ell == self.s())
return (ell == (self.s() / self.cartan_type().c()[self.r()]))
MPhi = []
for b in self:
p = b.Phi().level()
assert (p == b.Epsilon().level())
if (p < ell):
return False
if (p == ell):
MPhi += [b]
weights = []
I = self.index_set()
rank = len(I)
La = self.weight_lattice_realization().basis()
from sage.combinat.integer_vector import IntegerVectors
for n in range(1, (ell + 1)):
for c in IntegerVectors(n, rank):
w = sum(((c[i] * La[i]) for i in I))
if (w.level() == ell):
weights.append(w)
return (sorted((b.Phi() for b in MPhi)) == sorted(weights))
def level(self):
"\n Return the level of ``self`` when ``self`` is a perfect crystal.\n\n .. SEEALSO::\n\n :meth:`~sage.categories.loop_crystals.KirillovReshetikhinCrystals.ParentMethods.is_perfect`\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1], 1, 1)\n sage: K.level()\n 1\n sage: K = crystals.KirillovReshetikhin(['C',2,1], 1, 2)\n sage: K.level()\n 1\n sage: K = crystals.KirillovReshetikhin(['D',4,1], 1, 3)\n sage: K.level()\n 3\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1], 1, 1)\n sage: K.level()\n Traceback (most recent call last):\n ...\n ValueError: this crystal is not perfect\n\n TESTS:\n\n Check that this works correctly for `B^{n,s}`\n of type `A_{2n}^{(2)\\dagger}` (:trac:`24364`)::\n\n sage: ct = CartanType(['A',6,2]).dual()\n sage: K1 = crystals.KirillovReshetikhin(ct, 3,1)\n sage: K1.level()\n 1\n sage: K4 = crystals.KirillovReshetikhin(ct, 3,4)\n sage: K4.level()\n 4\n "
if (not self.is_perfect()):
raise ValueError('this crystal is not perfect')
if ((self.cartan_type().dual().type() == 'BC') and ((self.cartan_type().rank() - 1) == self.r())):
return self.s()
return (self.s() / self.cartan_type().c()[self.r()])
def q_dimension(self, q=None, prec=None, use_product=False):
"\n Return the `q`-dimension of ``self``.\n\n The `q`-dimension of a KR crystal is defined as the `q`-dimension of\n the underlying classical crystal.\n\n EXAMPLES::\n\n sage: KRC = crystals.KirillovReshetikhin(['A',2,1], 2,2)\n sage: KRC.q_dimension()\n q^4 + q^3 + 2*q^2 + q + 1\n sage: KRC = crystals.KirillovReshetikhin(['D',4,1], 2,1)\n sage: KRC.q_dimension()\n q^10 + q^9 + 3*q^8 + 3*q^7 + 4*q^6 + 4*q^5 + 4*q^4 + 3*q^3 + 3*q^2 + q + 2\n "
return self.classical_decomposition().q_dimension(q, prec, use_product)
class ElementMethods():
def lusztig_involution(self):
"\n Return the result of the classical Lusztig involution on ``self``.\n\n EXAMPLES::\n\n sage: KRT = crystals.KirillovReshetikhin(['D',4,1], 2, 3, model='KR')\n sage: mg = KRT.module_generators[1]\n sage: mg.lusztig_involution()\n [[-2, -2, 1], [-1, -1, 2]]\n sage: elt = mg.f_string([2,1,3,2]); elt\n [[3, -2, 1], [4, -1, 2]]\n sage: elt.lusztig_involution()\n [[-4, -2, 1], [-3, -1, 2]]\n "
Cl = self.parent().cartan_type().classical()
I = Cl.index_set()
aut = Cl.opposition_automorphism()
hw = self.to_highest_weight(I)[1]
hw.reverse()
return self.to_lowest_weight(I)[0].e_string((aut[i] for i in hw))
@cached_method
def energy_function(self):
"\n Return the energy function of ``self``.\n\n Let `B` be a KR crystal. Let `b^{\\sharp}` denote the unique\n element such that `\\varphi(b^{\\sharp}) = \\ell \\Lambda_0` with\n `\\ell = \\min \\{ \\langle c, \\varphi(b) \\mid b \\in B \\}`. Let\n `u_B` denote the maximal element of `B`. The *energy* of\n `b \\in B` is given by\n\n .. MATH::\n\n D(b) = H(b \\otimes b^{\\sharp}) - H(u_B \\otimes b^{\\sharp}),\n\n where `H` is the :meth:`local energy function\n <sage.categories.loop_crystals.KirillovReshetikhinCrystals.ParentMethods.local_energy_function>`.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['D',4,1], 2,1)\n sage: for x in K.classically_highest_weight_vectors():\n ....: x, x.energy_function()\n ([], 1)\n ([[1], [2]], 0)\n\n sage: K = crystals.KirillovReshetikhin(['D',4,3], 1,2)\n sage: for x in K.classically_highest_weight_vectors():\n ....: x, x.energy_function()\n ([], 2)\n ([[1]], 1)\n ([[1, 1]], 0)\n "
B = self.parent()
bsharp = B.b_sharp()
T = B.tensor(B)
H = B.local_energy_function(B)
return (H(T(self, bsharp)) - H(T(B.maximal_vector(), bsharp)))
class TensorProducts(TensorProductsCategory):
'\n The category of tensor products of Kirillov-Reshetikhin crystals.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.loop_crystals import KirillovReshetikhinCrystals\n sage: KirillovReshetikhinCrystals().TensorProducts().extra_super_categories()\n [Category of finite regular loop crystals]\n '
return [RegularLoopCrystals().Finite()]
class ParentMethods():
@cached_method
def maximal_vector(self):
"\n Return the maximal vector of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K,K)\n sage: T.maximal_vector()\n [[[1]], [[1]], [[1]]]\n "
return self(*[K.maximal_vector() for K in self.crystals])
@cached_method
def classically_highest_weight_vectors(self):
"\n Return the classically highest weight elements of ``self``.\n\n This works by using a backtracking algorithm since if\n `b_2 \\otimes b_1` is classically highest weight then `b_1`\n is classically highest weight.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K,K)\n sage: T.classically_highest_weight_vectors()\n ([[[1]], [[1]], [[1]]],\n [[[2]], [[1]], [[1]]],\n [[[1]], [[2]], [[1]]],\n [[[3]], [[2]], [[1]]])\n "
n = len(self.crystals)
I0 = self.cartan_type().classical().index_set()
it = [iter(self.crystals[(- 1)].classically_highest_weight_vectors())]
path = []
ret = []
while it:
try:
x = next(it[(- 1)])
except StopIteration:
it.pop()
if path:
path.pop(0)
continue
b = self.element_class(self, ([x] + path))
if (not b.is_highest_weight(index_set=I0)):
continue
path.insert(0, x)
if (len(path) == n):
ret.append(b)
path.pop(0)
else:
it.append(iter(self.crystals[((- len(path)) - 1)]))
return tuple(ret)
def cardinality(self):
"\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: RC = RiggedConfigurations(['A', 3, 1], [[3, 2], [1, 2]])\n sage: RC.cardinality()\n 100\n sage: len(RC.list())\n 100\n\n sage: RC = RiggedConfigurations(['E', 7, 1], [[1,1]])\n sage: RC.cardinality()\n 134\n sage: len(RC.list())\n 134\n\n sage: RC = RiggedConfigurations(['B', 3, 1], [[2,2],[1,2]])\n sage: RC.cardinality()\n 5130\n "
CWLR = self.cartan_type().classical().root_system().ambient_space()
return sum((CWLR.weyl_dimension(mg.classical_weight()) for mg in self.classically_highest_weight_vectors()))
def one_dimensional_configuration_sum(self, q=None, group_components=True):
"\n Compute the one-dimensional configuration sum of ``self``.\n\n INPUT:\n\n - ``q`` -- (default: ``None``) a variable or ``None``;\n if ``None``, a variable `q` is set in the code\n - ``group_components`` -- (default: ``True``) boolean; if\n ``True``, then the terms are grouped by classical component\n\n The one-dimensional configuration sum is the sum of the\n weights of all elements in the crystal weighted by the\n energy function.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K)\n sage: T.one_dimensional_configuration_sum()\n B[-2*Lambda[1] + 2*Lambda[2]] + (q+1)*B[-Lambda[1]]\n + (q+1)*B[Lambda[1] - Lambda[2]] + B[2*Lambda[1]]\n + B[-2*Lambda[2]] + (q+1)*B[Lambda[2]]\n sage: R.<t> = ZZ[]\n sage: T.one_dimensional_configuration_sum(t, False)\n B[-2*Lambda[1] + 2*Lambda[2]] + (t+1)*B[-Lambda[1]]\n + (t+1)*B[Lambda[1] - Lambda[2]] + B[2*Lambda[1]]\n + B[-2*Lambda[2]] + (t+1)*B[Lambda[2]]\n\n sage: R = RootSystem(['A',2,1])\n sage: La = R.weight_space().basis()\n sage: LS = crystals.ProjectedLevelZeroLSPaths(2*La[1])\n sage: (LS.one_dimensional_configuration_sum() # long time\n ....: == T.one_dimensional_configuration_sum())\n True\n\n TESTS::\n\n sage: K1 = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: K2 = crystals.KirillovReshetikhin(['A',2,1],2,1)\n sage: T = crystals.TensorProduct(K1,K2)\n sage: T.one_dimensional_configuration_sum() == T.one_dimensional_configuration_sum(group_components=False)\n True\n\n sage: RC = RiggedConfigurations(['A',3,1],[[1,1],[1,2]])\n sage: B = crystals.KirillovReshetikhin(['A',3,1],1,1)\n sage: B1 = crystals.KirillovReshetikhin(['A',3,1],1,2)\n sage: T = crystals.TensorProduct(B,B1)\n sage: RC.fermionic_formula() == T.one_dimensional_configuration_sum()\n True\n "
if (q is None):
from sage.rings.rational_field import QQ
q = QQ['q'].gens()[0]
P0 = self.weight_lattice_realization().classical()
B = P0.algebra(q.parent())
if group_components:
G = self.digraph(index_set=self.cartan_type().classical().index_set())
C = G.connected_components(sort=False)
return B.sum((((q ** c[0].energy_function()) * B.sum((B(P0(b.weight())) for b in c))) for c in C))
return B.sum((((q ** b.energy_function()) * B(P0(b.weight()))) for b in self))
class ElementMethods():
def energy_function(self, algorithm=None):
'\n Return the energy function of ``self``.\n\n ALGORITHM:\n\n .. RUBRIC:: definition\n\n Let `T` be a tensor product of Kirillov-Reshetikhin\n crystals. Let `R_i` and `H_i` be the combinatorial\n `R`-matrix and local energy functions, respectively, acting\n on the `i` and `i+1` factors. Let `D_B` be the energy\n function of a single Kirillov-Reshetikhin crystal. The\n *energy function* is given by\n\n .. MATH::\n\n D = \\sum_{j > i} H_i R_{i+1} R_{i+2} \\cdots R_{j-1}\n + \\sum_j D_B R_1 R_2 \\cdots R_{j-1},\n\n where `D_B` acts on the rightmost factor.\n\n .. RUBRIC:: grading\n\n If ``self`` is an element of `T`, a tensor product of\n perfect crystals of the same level, then use the affine\n grading to determine the energy. Specifically, let `g`\n denote the affine grading of ``self`` and `d` the affine\n grading of the maximal vector in `T`. Then the energy\n of ``self`` is given by `d - g`.\n\n For more details, see Theorem 7.5 in [ST2011]_.\n\n INPUT:\n\n - ``algorithm`` -- (default: ``None``) use one of the\n following algorithms to determine the energy function:\n\n * ``\'definition\'`` - use the definition of the energy\n function;\n * ``\'grading\'`` - use the affine grading;\n\n if not specified, then this uses ``\'grading\'`` if all\n factors are perfect of the same level and otherwise\n this uses ``\'definition\'``\n\n OUTPUT: an integer\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin([\'A\',2,1], 1, 1)\n sage: T = crystals.TensorProduct(K,K,K)\n sage: hw = T.classically_highest_weight_vectors()\n sage: for b in hw:\n ....: print("{} {}".format(b, b.energy_function()))\n [[[1]], [[1]], [[1]]] 0\n [[[2]], [[1]], [[1]]] 1\n [[[1]], [[2]], [[1]]] 2\n [[[3]], [[2]], [[1]]] 3\n\n sage: K = crystals.KirillovReshetikhin([\'C\',2,1], 1, 2)\n sage: T = crystals.TensorProduct(K,K)\n sage: hw = T.classically_highest_weight_vectors()\n sage: for b in hw:\n ....: print("{} {}".format(b, b.energy_function()))\n [[], []] 4\n [[[1, 1]], []] 3\n [[], [[1, 1]]] 1\n [[[1, 1]], [[1, 1]]] 0\n [[[1, 2]], [[1, 1]]] 1\n [[[2, 2]], [[1, 1]]] 2\n [[[-1, -1]], [[1, 1]]] 2\n [[[1, -1]], [[1, 1]]] 2\n [[[2, -1]], [[1, 1]]] 2\n\n sage: K = crystals.KirillovReshetikhin([\'C\',2,1], 1, 1)\n sage: T = crystals.TensorProduct(K)\n sage: t = T.module_generators[0]\n sage: t.energy_function(\'grading\')\n Traceback (most recent call last):\n ...\n NotImplementedError: all crystals in the tensor product\n need to be perfect of the same level\n\n TESTS::\n\n sage: K = crystals.KirillovReshetikhin([\'C\',2,1], 1, 2)\n sage: K2 = crystals.KirillovReshetikhin([\'C\',2,1], 2, 2)\n sage: T = tensor([K, K2])\n sage: hw = T.classically_highest_weight_vectors()\n sage: all(b.energy_function() == b.energy_function(algorithm=\'definition\')\n ....: for b in hw)\n True\n '
from sage.arith.misc import integer_ceil as ceil
C = self.parent().crystals[0]
ell = ceil((C.s() / C.cartan_type().c()[C.r()]))
is_perfect = all(((ell == (K.s() / K.cartan_type().c()[K.r()])) for K in self.parent().crystals))
if (algorithm is None):
if is_perfect:
algorithm = 'grading'
else:
algorithm = 'definition'
if (algorithm == 'grading'):
if (not is_perfect):
raise NotImplementedError('all crystals in the tensor product need to be perfect of the same level')
d = self.parent().maximal_vector().affine_grading()
return (d - self.affine_grading())
if (algorithm == 'definition'):
from sage.rings.integer_ring import ZZ
energy = ZZ.zero()
R_mats = [[K.R_matrix(Kp) for Kp in self.parent().crystals[(i + 1):]] for (i, K) in enumerate(self.parent().crystals)]
H_funcs = [[K.local_energy_function(Kp) for Kp in self.parent().crystals[(i + 1):]] for (i, K) in enumerate(self.parent().crystals)]
for (i, b) in enumerate(self):
for (j, R) in enumerate(R_mats[i]):
H = H_funcs[i][j]
bp = self[((i + j) + 1)]
T = R.domain()
t = T(b, bp)
energy += H(t)
b = R(t)[1]
energy += b.energy_function()
return energy
else:
raise ValueError('invalid algorithm')
def affine_grading(self):
'\n Return the affine grading of ``self``.\n\n The affine grading is calculated by finding a path\n from ``self`` to a ground state path (using the helper method\n :meth:`e_string_to_ground_state`) and counting the number\n of affine Kashiwara operators `e_0` applied on the way.\n\n OUTPUT: an integer\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin([\'A\',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K)\n sage: t = T.module_generators[0]\n sage: t.affine_grading()\n 1\n\n sage: K = crystals.KirillovReshetikhin([\'A\',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K,K)\n sage: hw = T.classically_highest_weight_vectors()\n sage: for b in hw:\n ....: print("{} {}".format(b, b.affine_grading()))\n [[[1]], [[1]], [[1]]] 3\n [[[2]], [[1]], [[1]]] 2\n [[[1]], [[2]], [[1]]] 1\n [[[3]], [[2]], [[1]]] 0\n\n sage: K = crystals.KirillovReshetikhin([\'C\',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K,K)\n sage: hw = T.classically_highest_weight_vectors()\n sage: for b in hw:\n ....: print("{} {}".format(b, b.affine_grading()))\n [[[1]], [[1]], [[1]]] 2\n [[[2]], [[1]], [[1]]] 1\n [[[-1]], [[1]], [[1]]] 1\n [[[1]], [[2]], [[1]]] 1\n [[[-2]], [[2]], [[1]]] 0\n [[[1]], [[-1]], [[1]]] 0\n '
return self.e_string_to_ground_state().count(0)
@cached_method
def e_string_to_ground_state(self):
"\n Return a string of integers in the index set\n `(i_1, \\ldots, i_k)` such that `e_{i_k} \\cdots e_{i_1}`\n of ``self`` is the ground state.\n\n This method calculates a path from ``self`` to a ground\n state path using Demazure arrows as defined in Lemma 7.3\n in [ST2011]_.\n\n OUTPUT: a tuple of integers `(i_1, \\ldots, i_k)`\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K)\n sage: t = T.module_generators[0]\n sage: t.e_string_to_ground_state()\n (0, 2)\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1],1,1)\n sage: T = crystals.TensorProduct(K,K)\n sage: t = T.module_generators[0]; t\n [[[1]], [[1]]]\n sage: t.e_string_to_ground_state()\n (0,)\n sage: x = t.e(0)\n sage: x.e_string_to_ground_state()\n ()\n sage: y = t.f_string([1,2,1,1,0]); y\n [[[2]], [[1]]]\n sage: y.e_string_to_ground_state()\n ()\n\n TESTS:\n\n Check that :trac:`22882` is fixed::\n\n sage: K = crystals.KirillovReshetikhin(CartanType(['A',6,2]).dual(), 1,1)\n sage: T = tensor([K,K,K])\n sage: hw = [x for x in T if x.is_highest_weight([1,2,3])]\n sage: gs = T(K(0), K(0), K(0))\n sage: all(elt.e_string(elt.e_string_to_ground_state()) == gs\n ....: for elt in hw)\n True\n sage: all(elt.energy_function() == elt.energy_function('definition')\n ....: for elt in hw)\n True\n "
from sage.arith.misc import integer_ceil as ceil
ell = max((ceil((K.s() / K.cartan_type().c()[K.r()])) for K in self.parent().crystals))
if (self.cartan_type().dual().type() == 'BC'):
I = self.cartan_type().index_set()
for i in I[:(- 1)]:
if (self.epsilon(i) > 0):
return ((i,) + self.e(i).e_string_to_ground_state())
if (self.epsilon(I[(- 1)]) > ell):
return ((I[(- 1)],) + self.e(I[(- 1)]).e_string_to_ground_state())
return ()
I = self.cartan_type().classical().index_set()
for i in I:
if (self.epsilon(i) > 0):
return ((i,) + self.e(i).e_string_to_ground_state())
if (self.epsilon(0) > ell):
return ((0,) + self.e(0).e_string_to_ground_state())
return ()
|
class LocalEnergyFunction(Map):
"\n The local energy function.\n\n Let `B` and `B'` be Kirillov-Reshetikhin crystals with maximal\n vectors `u_B` and `u_{B'}` respectively. The *local energy function*\n `H : B \\otimes B' \\to \\ZZ` is the function which satisfies\n\n .. MATH::\n\n H(e_0(b \\otimes b')) = H(b \\otimes b') + \\begin{cases}\n 1 & \\text{if } i = 0 \\text{ and LL}, \\\\\n -1 & \\text{if } i = 0 \\text{ and RR}, \\\\\n 0 & \\text{otherwise,}\n \\end{cases}\n\n where LL (resp. RR) denote `e_0` acts on the left (resp. right)\n on both `b \\otimes b'` and `R(b \\otimes b')`, and\n normalized by `H(u_B \\otimes u_{B'}) = 0`.\n\n INPUT:\n\n - ``B`` -- a Kirillov-Reshetikhin crystal\n - ``Bp`` -- a Kirillov-Reshetikhin crystal\n - ``normalization`` -- (default: 0) the normalization value\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['C',2,1], 1,2)\n sage: K2 = crystals.KirillovReshetikhin(['C',2,1], 2,1)\n sage: H = K.local_energy_function(K2)\n sage: T = tensor([K, K2])\n sage: hw = T.classically_highest_weight_vectors()\n sage: for b in hw:\n ....: b, H(b)\n ([[], [[1], [2]]], 1)\n ([[[1, 1]], [[1], [2]]], 0)\n ([[[2, -2]], [[1], [2]]], 1)\n ([[[1, -2]], [[1], [2]]], 1)\n\n REFERENCES:\n\n [KKMMNN1992]_\n "
def __init__(self, B, Bp, normalization=0):
"\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A',7,2], 1,2)\n sage: K2 = crystals.KirillovReshetikhin(['A',7,2], 2,1)\n sage: H = K.local_energy_function(K2)\n sage: TestSuite(H).run(skip=['_test_category', '_test_pickling'])\n\n TESTS:\n\n Check that :trac:`23014` is fixed::\n\n sage: La = RootSystem(['G',2,1]).weight_space().fundamental_weights()\n sage: K = crystals.ProjectedLevelZeroLSPaths(La[1])\n sage: H = K.local_energy_function(K)\n sage: hw = H.domain().classically_highest_weight_vectors()\n sage: [H(x) for x in hw]\n [0, 1, 2, 1]\n "
from sage.rings.integer_ring import ZZ
self._B = B
self._Bp = Bp
self._R_matrix = self._B.R_matrix(self._Bp)
T = B.tensor(Bp)
self._known_values = {T(*[K.maximal_vector() for K in T.crystals]): ZZ(normalization)}
self._I0 = T.cartan_type().classical().index_set()
from sage.categories.homset import Hom
Map.__init__(self, Hom(T, ZZ))
def _repr_(self):
"\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['A', 6, 2], 2, 1)\n sage: Kp = crystals.KirillovReshetikhin(['A', 6, 2], 1, 1)\n sage: H = K.local_energy_function(Kp); H\n Local energy function of\n Kirillov-Reshetikhin crystal of type ['BC', 3, 2] with (r,s)=(2,1)\n tensor\n Kirillov-Reshetikhin crystal of type ['BC', 3, 2] with (r,s)=(1,1)\n "
return 'Local energy function of {} tensor {}'.format(self._B, self._Bp)
def _call_(self, x):
"\n Return the local energy of ``x``.\n\n EXAMPLES::\n\n sage: K = crystals.KirillovReshetikhin(['B',4,1], 1,2)\n sage: K2 = crystals.KirillovReshetikhin(['B',4,1], 2,1)\n sage: H = K.local_energy_function(K2)\n sage: T = tensor([K, K2])\n sage: hw = [x for x in T if x.is_highest_weight([1,2])]\n sage: H(hw[0])\n 1\n "
visited = {x: 0}
check0 = [x]
def to_classical_hw(cur):
for i in self._I0:
b = cur.e(i)
if ((b is not None) and (b not in visited)):
visited[b] = visited[cur]
return b
return None
cur = x
i0 = x.parent().cartan_type().special_node()
while (cur not in self._known_values):
b = to_classical_hw(cur)
while (b is None):
b = check0.pop()
c = b.e(i0)
if ((c is None) or (c in visited)):
b = None
continue
bp = self._R_matrix(b)
cp = bp.e(i0)
if ((b[1] == c[1]) and (bp[1] == cp[1])):
visited[c] = (visited[b] + 1)
elif ((b[0] == c[0]) and (bp[0] == cp[0])):
visited[c] = (visited[b] - 1)
else:
visited[c] = visited[b]
b = c
cur = b
check0.append(b)
baseline = (self._known_values[cur] - visited[cur])
for y in visited:
self._known_values[y] = (baseline + visited[y])
return self._known_values[x]
|
class Magmas(Category_singleton):
'\n The category of (multiplicative) magmas.\n\n A magma is a set with a binary operation `*`.\n\n EXAMPLES::\n\n sage: Magmas()\n Category of magmas\n sage: Magmas().super_categories()\n [Category of sets]\n sage: Magmas().all_super_categories()\n [Category of magmas, Category of sets,\n Category of sets with partial maps, Category of objects]\n\n The following axioms are defined by this category::\n\n sage: Magmas().Associative()\n Category of semigroups\n sage: Magmas().Unital()\n Category of unital magmas\n sage: Magmas().Commutative()\n Category of commutative magmas\n sage: Magmas().Unital().Inverse()\n Category of inverse unital magmas\n sage: Magmas().Associative()\n Category of semigroups\n sage: Magmas().Associative().Unital()\n Category of monoids\n sage: Magmas().Associative().Unital().Inverse()\n Category of groups\n\n TESTS::\n\n sage: C = Magmas()\n sage: TestSuite(C).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: Magmas().super_categories()\n [Category of sets]\n '
return [Sets()]
class SubcategoryMethods():
@cached_method
def Associative(self):
"\n Return the full subcategory of the associative objects\n of ``self``.\n\n A (multiplicative) :class:`magma Magmas` `M` is\n *associative* if, for all `x,y,z\\in M`,\n\n .. MATH:: x * (y * z) = (x * y) * z\n\n .. SEEALSO:: :wikipedia:`Associative_property`\n\n EXAMPLES::\n\n sage: Magmas().Associative()\n Category of semigroups\n\n TESTS::\n\n sage: TestSuite(Magmas().Associative()).run()\n sage: Rings().Associative.__module__\n 'sage.categories.magmas'\n "
return self._with_axiom('Associative')
@cached_method
def Commutative(self):
"\n Return the full subcategory of the commutative objects\n of ``self``.\n\n A (multiplicative) :class:`magma Magmas` `M` is\n *commutative* if, for all `x,y\\in M`,\n\n .. MATH:: x * y = y * x\n\n .. SEEALSO:: :wikipedia:`Commutative_property`\n\n EXAMPLES::\n\n sage: Magmas().Commutative()\n Category of commutative magmas\n sage: Monoids().Commutative()\n Category of commutative monoids\n\n TESTS::\n\n sage: TestSuite(Magmas().Commutative()).run()\n sage: Rings().Commutative.__module__\n 'sage.categories.magmas'\n "
return self._with_axiom('Commutative')
@cached_method
def Unital(self):
"\n Return the subcategory of the unital objects of ``self``.\n\n A (multiplicative) :class:`magma Magmas` `M` is *unital*\n if it admits an element `1`, called *unit*, such that for\n all `x\\in M`,\n\n .. MATH:: 1 * x = x * 1 = x\n\n This element is necessarily unique, and should be provided\n as ``M.one()``.\n\n .. SEEALSO:: :wikipedia:`Unital_magma#unital`\n\n EXAMPLES::\n\n sage: Magmas().Unital()\n Category of unital magmas\n sage: Semigroups().Unital()\n Category of monoids\n sage: Monoids().Unital()\n Category of monoids\n sage: from sage.categories.associative_algebras import AssociativeAlgebras\n sage: AssociativeAlgebras(QQ).Unital()\n Category of algebras over Rational Field\n\n TESTS::\n\n sage: TestSuite(Magmas().Unital()).run()\n sage: Semigroups().Unital.__module__\n 'sage.categories.magmas'\n "
return self._with_axiom('Unital')
@cached_method
def FinitelyGeneratedAsMagma(self):
"\n Return the subcategory of the objects of ``self`` that are\n endowed with a distinguished finite set of\n (multiplicative) magma generators.\n\n A set `S` of elements of a multiplicative magma form a\n *set of generators* if any element of the magma can be\n expressed recursively from elements of `S` and products\n thereof.\n\n It is not imposed that morphisms shall preserve the\n distinguished set of generators; hence this is a full\n subcategory.\n\n .. SEEALSO:: :wikipedia:`Unital_magma#unital`\n\n EXAMPLES::\n\n sage: Magmas().FinitelyGeneratedAsMagma()\n Category of finitely generated magmas\n\n Being finitely generated does depend on the structure: for\n a ring, being finitely generated as a magma, as an\n additive magma, or as a ring are different concepts. Hence\n the name of this axiom is explicit::\n\n sage: Rings().FinitelyGeneratedAsMagma()\n Category of finitely generated as magma enumerated rings\n\n On the other hand, it does not depend on the\n multiplicative structure: for example a group is finitely\n generated if and only if it is finitely generated as a\n magma. A short hand is provided when there is no\n ambiguity, and the output tries to reflect that::\n\n sage: Semigroups().FinitelyGenerated()\n Category of finitely generated semigroups\n sage: Groups().FinitelyGenerated()\n Category of finitely generated enumerated groups\n\n sage: Semigroups().FinitelyGenerated().axioms()\n frozenset({'Associative', 'Enumerated', 'FinitelyGeneratedAsMagma'})\n\n Note that the set of generators may depend on the actual\n category; for example, in a group, one can often use less\n generators since it is allowed to take inverses.\n\n TESTS::\n\n sage: TestSuite(Magmas().FinitelyGeneratedAsMagma()).run()\n sage: Semigroups().FinitelyGeneratedAsMagma.__module__\n 'sage.categories.magmas'\n "
return self._with_axiom('FinitelyGeneratedAsMagma')
@cached_method
def FinitelyGenerated(self):
'\n Return the subcategory of the objects of ``self`` that are\n endowed with a distinguished finite set of\n (multiplicative) magma generators.\n\n EXAMPLES:\n\n This is a shorthand for :meth:`FinitelyGeneratedAsMagma`,\n which see::\n\n sage: Magmas().FinitelyGenerated()\n Category of finitely generated magmas\n sage: Semigroups().FinitelyGenerated()\n Category of finitely generated semigroups\n sage: Groups().FinitelyGenerated()\n Category of finitely generated enumerated groups\n\n An error is raised if this is ambiguous::\n\n sage: (Magmas() & AdditiveMagmas()).FinitelyGenerated()\n Traceback (most recent call last):\n ...\n ValueError: FinitelyGenerated is ambiguous for\n Join of Category of magmas and Category of additive magmas.\n Please use explicitly one of the FinitelyGeneratedAsXXX methods\n\n .. NOTE::\n\n Checking that there is no ambiguity currently assumes\n that all the other "finitely generated" axioms involve\n an additive structure. As of Sage 6.4, this is\n correct.\n\n The use of this shorthand should be reserved for casual\n interactive use or when there is no risk of ambiguity.\n '
from sage.categories.additive_magmas import AdditiveMagmas
if self.is_subcategory(AdditiveMagmas()):
raise ValueError('FinitelyGenerated is ambiguous for {}.\nPlease use explicitly one of the FinitelyGeneratedAsXXX methods'.format(self))
return self.FinitelyGeneratedAsMagma()
@cached_method
def Distributive(self):
"\n Return the full subcategory of the objects of ``self``\n where `*` is distributive on `+`.\n\n INPUT:\n\n - ``self`` -- a subcategory of :class:`Magmas`\n and :class:`AdditiveMagmas`\n\n Given that Sage does not yet know that the category\n :class:`MagmasAndAdditiveMagmas` is the intersection of\n the categories :class:`Magmas` and\n :class:`AdditiveMagmas`, the method\n :meth:`MagmasAndAdditiveMagmas.SubcategoryMethods.Distributive`\n is not available, as would be desirable, for this intersection.\n\n This method is a workaround. It checks that ``self`` is a\n subcategory of both :class:`Magmas` and\n :class:`AdditiveMagmas` and upgrades it to a subcategory\n of :class:`MagmasAndAdditiveMagmas` before applying the\n axiom. It complains otherwise, since the ``Distributive``\n axiom does not make sense for a plain magma.\n\n EXAMPLES::\n\n sage: (Magmas() & AdditiveMagmas()).Distributive()\n Category of distributive magmas and additive magmas\n sage: (Monoids() & CommutativeAdditiveGroups()).Distributive()\n Category of rings\n\n sage: Magmas().Distributive()\n Traceback (most recent call last):\n ...\n ValueError: The distributive axiom only makes sense on a magma\n which is simultaneously an additive magma\n sage: Semigroups().Distributive()\n Traceback (most recent call last):\n ...\n ValueError: The distributive axiom only makes sense on a magma\n which is simultaneously an additive magma\n\n TESTS::\n\n sage: Semigroups().Distributive.__module__\n 'sage.categories.magmas'\n sage: Rings().Distributive.__module__\n 'sage.categories.magmas_and_additive_magmas'\n "
from .additive_magmas import AdditiveMagmas
if (not self.is_subcategory(AdditiveMagmas())):
raise ValueError('The distributive axiom only makes sense on a magma which is simultaneously an additive magma')
from .magmas_and_additive_magmas import MagmasAndAdditiveMagmas
return (self & MagmasAndAdditiveMagmas()).Distributive()
def JTrivial(self):
'\n Return the full subcategory of the `J`-trivial objects of ``self``.\n\n This axiom is in fact only meaningful for\n :class:`semigroups <Semigroups>`. This stub definition is\n here as a workaround for :trac:`20515`, in order to define\n the `J`-trivial axiom as the intersection of the `L` and\n `R`-trivial axioms.\n\n .. SEEALSO:: :meth:`Semigroups.SubcategoryMethods.JTrivial`\n\n TESTS::\n\n sage: Magmas().JTrivial()\n Category of j trivial magmas\n sage: C = Semigroups().RTrivial() & Semigroups().LTrivial()\n sage: C is Semigroups().JTrivial()\n True\n '
return self._with_axiom('JTrivial')
Associative = LazyImport('sage.categories.semigroups', 'Semigroups', at_startup=True)
FinitelyGeneratedAsMagma = LazyImport('sage.categories.finitely_generated_magmas', 'FinitelyGeneratedMagmas')
class JTrivial(CategoryWithAxiom):
pass
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: MCA = Magmas().Commutative().Algebras(QQ)\n sage: MCA.extra_super_categories()\n [Category of commutative magmas]\n\n This implements the fact that the algebra of a commutative\n magma is commutative::\n\n sage: MCA.super_categories()\n [Category of magma algebras over Rational Field,\n Category of commutative magmas]\n\n In particular, commutative monoid algebras are\n commutative algebras::\n\n sage: MoCA = Monoids().Commutative().Algebras(QQ)\n sage: MoCA.is_subcategory(Algebras(QQ).Commutative())\n True\n '
from sage.categories.magmatic_algebras import MagmaticAlgebras
return [MagmaticAlgebras(self.base_ring())]
class ParentMethods():
def is_field(self, proof=True):
'\n Return ``True`` if ``self`` is a field.\n\n For a magma algebra `RS` this is always false unless\n `S` is trivial and the base ring `R`` is a field.\n\n EXAMPLES::\n\n sage: SymmetricGroup(1).algebra(QQ).is_field() # needs sage.groups\n True\n sage: SymmetricGroup(1).algebra(ZZ).is_field() # needs sage.groups\n False\n sage: SymmetricGroup(2).algebra(QQ).is_field() # needs sage.groups\n False\n '
if (not self.base_ring().is_field(proof)):
return False
return (self.basis().keys().cardinality() == 1)
class Commutative(CategoryWithAxiom):
class ParentMethods():
def is_commutative(self):
'\n Return ``True``, since commutative magmas are commutative.\n\n EXAMPLES::\n\n sage: Parent(QQ, category=CommutativeRings()).is_commutative()\n True\n '
return True
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: MCA = Magmas().Commutative().Algebras(QQ)\n sage: MCA.extra_super_categories()\n [Category of commutative magmas]\n\n This implements the fact that the algebra of a commutative\n magma is commutative::\n\n sage: MCA.super_categories()\n [Category of magma algebras over Rational Field,\n Category of commutative magmas]\n\n In particular, commutative monoid algebras are\n commutative algebras::\n\n sage: MoCA = Monoids().Commutative().Algebras(QQ)\n sage: MoCA.is_subcategory(Algebras(QQ).Commutative())\n True\n '
return [Magmas().Commutative()]
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a Cartesian product of commutative\n additive magmas is still a commutative additive magmas.\n\n EXAMPLES::\n\n sage: C = Magmas().Commutative().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of commutative magmas]\n sage: C.axioms()\n frozenset({'Commutative'})\n "
return [Magmas().Commutative()]
class Unital(CategoryWithAxiom):
def additional_structure(self):
'\n Return ``self``.\n\n Indeed, the category of unital magmas defines an\n additional structure, namely the unit of the magma which\n shall be preserved by morphisms.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: Magmas().Unital().additional_structure()\n Category of unital magmas\n '
return self
class ParentMethods():
@cached_method
def one(self):
"\n Return the unit of the monoid, that is the unique neutral\n element for `*`.\n\n .. NOTE::\n\n The default implementation is to coerce `1` into ``self``.\n It is recommended to override this method because the\n coercion from the integers:\n\n - is not always meaningful (except for `1`);\n - often uses ``self.one()``.\n\n EXAMPLES::\n\n sage: M = Monoids().example(); M\n An example of a monoid:\n the free monoid generated by ('a', 'b', 'c', 'd')\n sage: M.one()\n ''\n "
return self(1)
def _test_one(self, **options):
"\n Test that ``self.one()`` is an element of ``self`` and is\n neutral for the operation ``*``.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: S = Monoids().example()\n sage: S._test_one()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: S._test_one(elements = (S('a'), S('b')))\n\n See the documentation for :class:`TestSuite` for more information.\n "
tester = self._tester(**options)
one = self.one()
tester.assertTrue(self.is_parent_of(one))
for x in tester.some_elements():
tester.assertEqual((x * one), x)
tester.assertEqual((one * x), x)
if hasattr(one, 'is_immutable'):
tester.assertTrue(one.is_immutable())
if hasattr(one, 'is_mutable'):
tester.assertFalse(one.is_mutable())
def is_empty(self):
"\n Return whether ``self`` is empty.\n\n Since this set is a unital magma it is not empty and this method\n always return ``False``.\n\n EXAMPLES::\n\n sage: S = SymmetricGroup(2) # needs sage.groups\n sage: S.is_empty() # needs sage.groups\n False\n\n sage: M = Monoids().example()\n sage: M.is_empty()\n False\n\n TESTS::\n\n sage: S.is_empty.__module__ # needs sage.groups\n 'sage.categories.magmas'\n sage: M.is_empty.__module__\n 'sage.categories.magmas'\n "
return False
class ElementMethods():
pass
class SubcategoryMethods():
@cached_method
def Inverse(self):
"\n Return the full subcategory of the inverse objects of ``self``.\n\n An inverse :class:` (multiplicative) magma <Magmas>`\n is a :class:`unital magma <Magmas.Unital>` such that\n every element admits both an inverse on the left and\n on the right. Such a magma is also called a *loop*.\n\n .. SEEALSO::\n\n :wikipedia:`Inverse_element`, :wikipedia:`Quasigroup`\n\n EXAMPLES::\n\n sage: Magmas().Unital().Inverse()\n Category of inverse unital magmas\n sage: Monoids().Inverse()\n Category of groups\n\n TESTS::\n\n sage: TestSuite(Magmas().Unital().Inverse()).run()\n sage: Algebras(QQ).Inverse.__module__\n 'sage.categories.magmas'\n "
return self._with_axiom('Inverse')
class Inverse(CategoryWithAxiom):
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a Cartesian product of magmas with\n inverses is a magma with inverse.\n\n EXAMPLES::\n\n sage: C = Magmas().Unital().Inverse().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of inverse unital magmas]\n sage: sorted(C.axioms())\n ['Inverse', 'Unital']\n "
return [Magmas().Unital().Inverse()]
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a Cartesian product of unital magmas is\n a unital magma\n\n EXAMPLES::\n\n sage: C = Magmas().Unital().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of unital magmas]\n sage: C.axioms()\n frozenset({'Unital'})\n\n sage: Monoids().CartesianProducts().is_subcategory(Monoids())\n True\n "
return [Magmas().Unital()]
class ParentMethods():
@cached_method
def one(self):
'\n Return the unit of this Cartesian product.\n\n It is built from the units for the Cartesian factors of ``self``.\n\n EXAMPLES::\n\n sage: cartesian_product([QQ, ZZ, RR]).one() # needs sage.rings.real_mpfr\n (1, 1, 1.00000000000000)\n '
return self._cartesian_product_of_elements((_.one() for _ in self.cartesian_factors()))
class ElementMethods():
def __invert__(self):
'\n Return the inverse of ``self``, if it exists.\n\n The inverse is computed by inverting each\n Cartesian factor and attempting to convert the\n result back to the original parent.\n\n For example, if one of the Cartesian factor is an\n element ``x`` of `\\ZZ`, the result of ``~x`` is in\n `\\QQ`. So we need to convert it back to `\\ZZ`. As\n a side effect, this checks that ``x`` is indeed\n invertible in `\\ZZ`.\n\n If needed an optimized version without this\n conversion could be implemented in\n :class:`Magmas.Unital.Inverse.ElementMethods`.\n\n EXAMPLES::\n\n sage: C = cartesian_product([QQ, ZZ, RR, GF(5)])\n sage: c = C([2,-1,2,2]); c # needs sage.rings.real_mpfr\n (2, -1, 2.00000000000000, 2)\n sage: ~c # needs sage.rings.real_mpfr\n (1/2, -1, 0.500000000000000, 3)\n\n This fails as soon as one of the entries is not\n invertible::\n\n sage: ~C([0,2,2,2])\n Traceback (most recent call last):\n ...\n ZeroDivisionError: rational division by zero\n\n sage: ~C([2,2,2,2]) # needs sage.rings.real_mpfr\n (1/2, 1/2, 0.500000000000000, 3)\n '
return self.parent()(((~ x) for x in self.cartesian_factors()))
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: MCA = Magmas().Commutative().Algebras(QQ)\n sage: MCA.extra_super_categories()\n [Category of commutative magmas]\n\n This implements the fact that the algebra of a\n commutative magma is commutative::\n\n sage: MCA.super_categories()\n [Category of magma algebras over Rational Field,\n Category of commutative magmas]\n\n In particular, commutative monoid algebras are\n commutative algebras::\n\n sage: MoCA = Monoids().Commutative().Algebras(QQ)\n sage: MoCA.is_subcategory(Algebras(QQ).Commutative())\n True\n '
return [Magmas().Unital()]
class Realizations(RealizationsCategory):
class ParentMethods():
@cached_method
def one(self):
"\n Return the unit element of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups\n sage: from sage.combinat.root_system.extended_affine_weyl_group import ExtendedAffineWeylGroup\n sage: PvW0 = ExtendedAffineWeylGroup(['A',2,1]).PvW0()\n sage: PvW0 in Magmas().Unital().Realizations()\n True\n sage: PvW0.one()\n 1\n "
return self(self.realization_of().a_realization().one())
class ParentMethods():
def product(self, x, y):
'\n The binary multiplication of the magma.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of this magma\n\n OUTPUT:\n\n - an element of the magma (the product of ``x`` and ``y``)\n\n EXAMPLES::\n\n sage: S = Semigroups().example("free")\n sage: x = S(\'a\'); y = S(\'b\')\n sage: S.product(x, y)\n \'ab\'\n\n A parent in ``Magmas()`` must either implement\n :meth:`.product` in the parent class or ``_mul_`` in the\n element class. By default, the addition method on elements\n ``x._mul_(y)`` calls ``S.product(x,y)``, and reciprocally.\n\n As a bonus, ``S.product`` models the binary function from\n ``S`` to ``S``::\n\n sage: bin = S.product\n sage: bin(x,y)\n \'ab\'\n\n Currently, ``S.product`` is just a bound method::\n\n sage: bin\n <bound method FreeSemigroup.product of An example of a semigroup:\n the free semigroup generated by (\'a\', \'b\', \'c\', \'d\')>\n\n When Sage will support multivariate morphisms, it will be\n possible, and in fact recommended, to enrich ``S.product``\n with extra mathematical structure. This will typically be\n implemented using lazy attributes.::\n\n sage: bin # todo: not implemented\n Generic binary morphism:\n From: (S x S)\n To: S\n '
return (x * y)
product_from_element_class_mul = product
def __init_extra__(self):
'\n EXAMPLES::\n\n sage: S = Semigroups().example("free")\n sage: S(\'a\') * S(\'b\') # indirect doctest\n \'ab\'\n sage: S(\'a\').__class__._mul_ == S(\'a\').__class__._mul_parent\n True\n '
if (self.product.__func__ == self.product_from_element_class_mul.__func__):
return
if (not (hasattr(self, 'element_class') and hasattr(self.element_class, '_mul_parent'))):
return
E = self.element_class
E_mul_func = raw_getattr(E, '_mul_')
if (not isinstance(E_mul_func, AbstractMethod)):
C = self.category().element_class
try:
C_mul_func = raw_getattr(C, '_mul_')
except AttributeError:
return
if isinstance(C_mul_func, AbstractMethod):
return
if (E_mul_func is C_mul_func):
E._mul_ = E._mul_parent
else:
E._mul_ = E._mul_parent
def multiplication_table(self, names='letters', elements=None):
"\n Returns a table describing the multiplication operation.\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.list`\n method. The association can also be retrieved with the\n :meth:`~sage.matrix.operation_table.OperationTable.dict`\n method.\n\n INPUT:\n\n - ``names`` - the type of names used\n\n * ``'letters'`` - lowercase ASCII letters are used\n for a base 26 representation of the elements'\n positions in the list given by\n :meth:`~sage.matrix.operation_table.OperationTable.column_keys`,\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 - ``elements`` - default = ``None``. A list of\n elements of the magma, 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 the ``S.list``\n method returns. 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 The multiplication table as an object of the class\n :class:`~sage.matrix.operation_table.OperationTable`\n which defines several methods for manipulating and\n displaying the table. See the documentation there\n for full details to supplement the documentation\n here.\n\n EXAMPLES:\n\n The default is to represent elements as lowercase\n ASCII letters. ::\n\n sage: G = CyclicPermutationGroup(5) # needs sage.groups\n sage: G.multiplication_table() # needs sage.groups\n * a b c d e\n +----------\n a| a b c d e\n b| b c d e a\n c| c d e a b\n d| d e a b c\n e| e a b c d\n\n All that is required is that an algebraic structure\n has a multiplication defined. A\n :class:`~sage.categories.examples.finite_semigroups.LeftRegularBand`\n is an example of a finite semigroup. The ``names`` argument allows\n displaying the elements in different ways. ::\n\n sage: from sage.categories.examples.finite_semigroups import LeftRegularBand\n sage: L = LeftRegularBand(('a', 'b'))\n sage: T = L.multiplication_table(names='digits') # needs sage.modules\n sage: T.column_keys() # needs sage.modules\n ('a', 'ab', 'b', 'ba')\n sage: T # needs sage.modules\n * 0 1 2 3\n +--------\n 0| 0 1 1 1\n 1| 1 1 1 1\n 2| 3 3 2 3\n 3| 3 3 3 3\n\n Specifying the elements in an alternative order can provide\n more insight into how the operation behaves. ::\n\n sage: L = LeftRegularBand(('a', 'b', 'c'))\n sage: elts = sorted(L.list())\n sage: L.multiplication_table(elements=elts) # needs sage.modules\n * a b c d e f g h i j k l m n o\n +------------------------------\n a| a b c d e b b c c c d d e e e\n b| b b c c c b b c c c c c c c c\n c| c c c c c c c c c c c c c c c\n d| d e e d e e e e e e d d e e e\n e| e e e e e e e e e e e e e e e\n f| g g h h h f g h i j i j j i j\n g| g g h h h g g h h h h h h h h\n h| h h h h h h h h h h h h h h h\n i| j j j j j i j j i j i j j i j\n j| j j j j j j j j j j j j j j j\n k| l m m l m n o o n o k l m n o\n l| l m m l m m m m m m l l m m m\n m| m m m m m m m m m m m m m m m\n n| o o o o o n o o n o n o o n o\n o| o o o o o o o o o o o o o o o\n\n The ``elements`` argument can be used to provide\n a subset of the elements of the structure. The subset\n must be closed under the operation. Elements need only\n be in a form that can be coerced into the set. The\n ``names`` argument can also be used to request that\n the elements be represented with their usual string\n representation. ::\n\n sage: L = LeftRegularBand(('a','b','c'))\n sage: elts=['a', 'c', 'ac', 'ca']\n sage: L.multiplication_table(names='elements', elements=elts) # needs sage.modules\n * 'a' 'c' 'ac' 'ca'\n +--------------------\n 'a'| 'a' 'ac' 'ac' 'ac'\n 'c'| 'ca' 'c' 'ca' 'ca'\n 'ac'| 'ac' 'ac' 'ac' 'ac'\n 'ca'| 'ca' 'ca' 'ca' 'ca'\n\n The table returned can be manipulated in various ways. See\n the documentation for\n :class:`~sage.matrix.operation_table.OperationTable` for more\n comprehensive documentation. ::\n\n sage: # needs sage.groups sage.modules\n sage: G = AlternatingGroup(3)\n sage: T = G.multiplication_table()\n sage: T.column_keys()\n ((), (1,2,3), (1,3,2))\n sage: T.translation()\n {'a': (), 'b': (1,2,3), 'c': (1,3,2)}\n sage: T.change_names(['x', 'y', 'z'])\n sage: T.translation()\n {'x': (), 'y': (1,2,3), 'z': (1,3,2)}\n sage: T\n * x y z\n +------\n x| x y z\n y| y z x\n z| z x y\n "
from sage.matrix.operation_table import OperationTable
import operator
return OperationTable(self, operation=operator.mul, names=names, elements=elements)
class ElementMethods():
@abstract_method(optional=True)
def _mul_(self, right):
'\n Product of two elements\n\n INPUT:\n\n - ``self``, ``right`` -- two elements with the same parent\n\n OUTPUT:\n\n - an element of the same parent\n\n EXAMPLES::\n\n sage: S = Semigroups().example("free")\n sage: x = S(\'a\'); y = S(\'b\')\n sage: x._mul_(y)\n \'ab\'\n '
_mul_parent = sage.categories.coercion_methods._mul_parent
def is_idempotent(self):
'\n Test whether ``self`` is idempotent.\n\n EXAMPLES::\n\n sage: S = Semigroups().example("free"); S\n An example of a semigroup:\n the free semigroup generated by (\'a\', \'b\', \'c\', \'d\')\n sage: a = S(\'a\')\n sage: a^2\n \'aa\'\n sage: a.is_idempotent()\n False\n\n ::\n\n sage: L = Semigroups().example("leftzero"); L\n An example of a semigroup: the left zero semigroup\n sage: x = L(\'x\')\n sage: x^2\n \'x\'\n sage: x.is_idempotent()\n True\n\n '
return ((self * self) == self)
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n This implements the fact that a subquotient (and therefore\n a quotient or subobject) of a finite set is finite.\n\n EXAMPLES::\n\n sage: Semigroups().CartesianProducts().extra_super_categories()\n [Category of semigroups]\n sage: Semigroups().CartesianProducts().super_categories()\n [Category of semigroups, Category of Cartesian products of magmas]\n '
return [Magmas()]
def example(self):
"\n Return an example of Cartesian product of magmas.\n\n EXAMPLES::\n\n sage: C = Magmas().CartesianProducts().example(); C\n The Cartesian product of (Rational Field, Integer Ring, Integer Ring)\n sage: C.category()\n Join of Category of Cartesian products of commutative rings and\n Category of Cartesian products of metric spaces\n sage: sorted(C.category().axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Associative', 'Commutative',\n 'Distributive', 'Unital']\n\n sage: TestSuite(C).run()\n "
from .cartesian_product import cartesian_product
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
return cartesian_product([QQ, ZZ, ZZ])
class ParentMethods():
def product(self, left, right):
'\n EXAMPLES::\n\n sage: C = Magmas().CartesianProducts().example(); C\n The Cartesian product of (Rational Field, Integer Ring, Integer Ring)\n sage: x = C.an_element(); x\n (1/2, 1, 1)\n sage: x * x\n (1/4, 1, 1)\n\n sage: # needs sage.groups sage.modules\n sage: A = SymmetricGroupAlgebra(QQ, 3)\n sage: x = cartesian_product([A([1,3,2]), A([2,3,1])])\n sage: y = cartesian_product([A([1,3,2]), A([2,3,1])])\n sage: cartesian_product([A,A]).product(x,y)\n B[(0, [1, 2, 3])] + B[(1, [3, 1, 2])]\n sage: x*y\n B[(0, [1, 2, 3])] + B[(1, [3, 1, 2])]\n '
prods = ((a * b) for (a, b) in zip(left.cartesian_factors(), right.cartesian_factors()))
return self._cartesian_product_of_elements(prods)
class Subquotients(SubquotientsCategory):
'\n The category of subquotient magmas.\n\n See :meth:`Sets.SubcategoryMethods.Subquotients` for the\n general setup for subquotients. In the case of a subquotient\n magma `S` of a magma `G`, the condition that `r` be a\n morphism in ``As`` can be rewritten as follows:\n\n - for any two `a,b \\in S` the identity\n `a \\times_S b = r(l(a) \\times_G l(b))` holds.\n\n This is used by this category to implement the product\n `\\times_S` of `S` from `l` and `r` and the product of `G`.\n\n EXAMPLES::\n\n sage: Semigroups().Subquotients().all_super_categories()\n [Category of subquotients of semigroups, Category of semigroups,\n Category of subquotients of magmas, Category of magmas,\n Category of subquotients of sets, Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
class ParentMethods():
def product(self, x, y):
'\n Return the product of two elements of ``self``.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: S\n An example of a (sub)quotient semigroup:\n a quotient of the left zero semigroup\n sage: S.product(S(19), S(3))\n 19\n\n Here is a more elaborate example involving a sub algebra::\n\n sage: Z = SymmetricGroup(5).algebra(QQ).center() # needs sage.groups\n sage: B = Z.basis() # needs sage.groups\n sage: B[3] * B[2] # needs sage.groups\n 4*B[2] + 6*B[3] + 5*B[6]\n '
assert (x in self)
assert (y in self)
return self.retract((self.lift(x) * self.lift(y)))
class Realizations(RealizationsCategory):
class ParentMethods():
def product_by_coercion(self, left, right):
"\n Default implementation of product for realizations.\n\n This method coerces to the realization specified by\n ``self.realization_of().a_realization()``, computes\n the product in that realization, and then coerces\n back.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: Out = Sets().WithRealizations().example().Out(); Out\n The subset algebra of {1, 2, 3} over Rational Field\n in the Out basis\n sage: Out.product\n <bound method Magmas.Realizations.ParentMethods.product_by_coercion\n of The subset algebra of {1, 2, 3} over Rational Field\n in the Out basis>\n sage: Out.product.__module__\n 'sage.categories.magmas'\n sage: x = Out.an_element()\n sage: y = Out.an_element()\n sage: Out.product(x, y)\n Out[{}] + 4*Out[{1}] + 9*Out[{2}] + Out[{1, 2}]\n\n "
R = self.realization_of().a_realization()
return self((R(left) * R(right)))
|
class MagmasAndAdditiveMagmas(Category_singleton):
"\n The category of sets `(S,+,*)` with an additive operation '+' and\n a multiplicative operation `*`\n\n EXAMPLES::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: C = MagmasAndAdditiveMagmas(); C\n Category of magmas and additive magmas\n\n This is the base category for the categories of rings and their variants::\n\n sage: C.Distributive()\n Category of distributive magmas and additive magmas\n sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().AdditiveInverse()\n Category of rngs\n sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().Unital()\n Category of semirings\n sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().AdditiveInverse().Unital()\n Category of rings\n\n This category is really meant to represent the intersection of the\n categories of :class:`Magmas` and :class:`AdditiveMagmas`; however\n Sage's infrastructure does not allow yet to model this::\n\n sage: Magmas() & AdditiveMagmas()\n Join of Category of magmas and Category of additive magmas\n\n sage: Magmas() & AdditiveMagmas() # todo: not implemented\n Category of magmas and additive magmas\n\n TESTS::\n\n sage: TestSuite(MagmasAndAdditiveMagmas()).run()\n "
class SubcategoryMethods():
@cached_method
def Distributive(self):
"\n Return the full subcategory of the objects of ``self``\n where `*` is distributive on `+`.\n\n A :class:`magma <Magmas>` and :class:`additive magma\n <AdditiveMagmas>` `M` is *distributive* if, for all\n `x,y,z \\in M`,\n\n .. MATH::\n\n x * (y+z) = x*y + x*z \\text{ and } (x+y) * z = x*z + y*z\n\n EXAMPLES::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: C = MagmasAndAdditiveMagmas().Distributive(); C\n Category of distributive magmas and additive magmas\n\n .. NOTE::\n\n Given that Sage does not know that\n :class:`MagmasAndAdditiveMagmas` is the intersection\n of :class:`Magmas` and :class:`AdditiveMagmas`, this\n method is not available for::\n\n sage: Magmas() & AdditiveMagmas()\n Join of Category of magmas and Category of additive magmas\n\n Still, the natural syntax works::\n\n sage: (Magmas() & AdditiveMagmas()).Distributive()\n Category of distributive magmas and additive magmas\n\n thanks to a workaround implemented in\n :meth:`Magmas.SubcategoryMethods.Distributive`::\n\n sage: (Magmas() & AdditiveMagmas()).Distributive.__module__\n 'sage.categories.magmas'\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Fields().Distributive.__module__\n 'sage.categories.magmas_and_additive_magmas'\n "
return self._with_axiom('Distributive')
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: MagmasAndAdditiveMagmas().super_categories()\n [Category of magmas, Category of additive magmas]\n '
return [Magmas(), AdditiveMagmas()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, this category is meant to represent the join of\n :class:`AdditiveMagmas` and :class:`Magmas`. As such, it\n defines no additional structure.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: MagmasAndAdditiveMagmas().additional_structure()\n '
return None
Distributive = LazyImport('sage.categories.distributive_magmas_and_additive_magmas', 'DistributiveMagmasAndAdditiveMagmas', at_startup=True)
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that this structure is stable under Cartesian\n products.\n\n TESTS::\n\n sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas\n sage: MagmasAndAdditiveMagmas().CartesianProducts().extra_super_categories()\n [Category of magmas and additive magmas]\n '
return [MagmasAndAdditiveMagmas()]
|
class MagmaticAlgebras(Category_over_base_ring):
'\n The category of algebras over a given base ring.\n\n An algebra over a ring `R` is a module over `R` endowed with a\n bilinear multiplication.\n\n .. WARNING::\n\n :class:`MagmaticAlgebras` will eventually replace the current\n :class:`Algebras` for consistency with\n e.g. :wikipedia:`Algebras` which assumes neither associativity\n nor the existence of a unit (see :trac:`15043`).\n\n EXAMPLES::\n\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: C = MagmaticAlgebras(ZZ); C\n Category of magmatic algebras over Integer Ring\n sage: C.super_categories()\n [Category of additive commutative additive associative additive\n unital distributive magmas and additive magmas,\n Category of modules over Integer Ring]\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: MA = MagmaticAlgebras(ZZ)\n sage: MA.super_categories()\n [Category of additive commutative additive associative additive\n unital distributive magmas and additive magmas,\n Category of modules over Integer Ring]\n\n sage: from sage.categories.additive_semigroups import AdditiveSemigroups\n sage: MA.is_subcategory((AdditiveSemigroups() & Magmas()).Distributive())\n True\n\n '
R = self.base_ring()
return Category.join([(Magmas() & AdditiveMagmas()).Distributive(), Modules(R)], as_list=True)
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of (magmatic) algebras defines no new\n structure: a morphism of modules and of magmas between two\n (magmatic) algebras is a (magmatic) algebra morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO::\n\n This category should be a\n :class:`~sage.categories.category_with_axiom.CategoryWithAxiom`,\n the axiom specifying the compatibility between the magma and\n module structure.\n\n EXAMPLES::\n\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: MagmaticAlgebras(ZZ).additional_structure()\n '
return None
Associative = LazyImport('sage.categories.associative_algebras', 'AssociativeAlgebras', at_startup=True)
Unital = LazyImport('sage.categories.unital_algebras', 'UnitalAlgebras', at_startup=True)
class ParentMethods():
@abstract_method(optional=True)
def algebra_generators(self):
"\n Return a family of generators of this algebra.\n\n EXAMPLES::\n\n sage: F = AlgebrasWithBasis(QQ).example(); F # needs sage.combinat sage.modules\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: F.algebra_generators() # needs sage.combinat sage.modules\n Family (B[word: a], B[word: b], B[word: c])\n "
class WithBasis(CategoryWithAxiom_over_base_ring):
class ParentMethods():
def algebra_generators(self):
'\n Return generators for this algebra.\n\n This default implementation returns the basis of this algebra.\n\n OUTPUT: a family\n\n .. SEEALSO::\n\n - :meth:`~sage.categories.modules_with_basis.ModulesWithBasis.ParentMethods.basis`\n - :meth:`MagmaticAlgebras.ParentMethods.algebra_generators`\n\n EXAMPLES::\n\n sage: D4 = DescentAlgebra(QQ, 4).B() # needs sage.combinat sage.modules\n sage: D4.algebra_generators() # needs sage.combinat sage.modules\n Lazy family (...)_{i in Compositions of 4}\n\n sage: R.<x> = ZZ[]\n sage: P = PartitionAlgebra(1, x, R) # needs sage.combinat sage.modules\n sage: P.algebra_generators() # needs sage.combinat sage.modules\n Lazy family (Term map\n from Partition diagrams of order 1\n to Partition Algebra of rank 1 with parameter x\n over Univariate Polynomial Ring in x\n over Integer Ring(i))_{i in Partition diagrams of order 1}\n '
return self.basis()
@abstract_method(optional=True)
def product_on_basis(self, i, j):
'\n The product of the algebra on the basis (optional).\n\n INPUT:\n\n - ``i``, ``j`` -- the indices of two elements of the\n basis of ``self``\n\n Return the product of the two corresponding basis elements\n indexed by ``i`` and ``j``.\n\n If implemented, :meth:`product` is defined from\n it by bilinearity.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example() # needs sage.combinat sage.modules\n sage: Word = A.basis().keys() # needs sage.combinat sage.modules\n sage: A.product_on_basis(Word("abc"), Word("cba")) # needs sage.combinat sage.modules\n B[word: abccba]\n '
@lazy_attribute
def product(self):
'\n The product of the algebra, as per\n :meth:`Magmas.ParentMethods.product()\n <sage.categories.magmas.Magmas.ParentMethods.product>`\n\n By default, this is implemented using one of the following\n methods, in the specified order:\n\n - :meth:`.product_on_basis`\n - :meth:`.product_by_coercion`\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example() # needs sage.combinat sage.modules\n sage: a, b, c = A.algebra_generators() # needs sage.combinat sage.modules\n sage: A.product(a + 2*b, 3*c) # needs sage.combinat sage.modules\n 3*B[word: ac] + 6*B[word: bc]\n '
if (self.product_on_basis is not NotImplemented):
return self._product_from_product_on_basis_multiply
elif hasattr(self, 'product_by_coercion'):
return self.product_by_coercion
else:
return NotImplemented
def _product_from_product_on_basis_multiply(self, left, right):
"\n Compute the product of two elements by extending\n bilinearly the method :meth:`product_on_basis`.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example(); A # needs sage.combinat sage.modules\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: a, b, c = A.algebra_generators() # needs sage.combinat sage.modules\n sage: A._product_from_product_on_basis_multiply(a*b + 2*c, a - b) # needs sage.combinat sage.modules\n B[word: aba] - B[word: abb] + 2*B[word: ca] - 2*B[word: cb]\n\n "
return self.linear_combination(((self.product_on_basis(mon_left, mon_right), (coeff_left * coeff_right)) for (mon_left, coeff_left) in left.monomial_coefficients().items() for (mon_right, coeff_right) in right.monomial_coefficients().items()))
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
class ParentMethods():
@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(ab) = 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 Heisenberg Lie algebra as a\n multiplicative algebra::\n\n sage: # needs sage.combinat 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(QQ,\n ....: [p_mult, q_mult, matrix(QQ, 3, 3)], 'p,q,z')\n sage: A.inject_variables()\n Defining p, q, z\n sage: p * q\n z\n sage: q * p\n -z\n sage: A.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 another example using the exterior algebra\n and verify we obtain a derivation::\n\n sage: # needs sage.combinat sage.modules\n sage: A = algebras.Exterior(QQ, 1)\n sage: A.derivations_basis()\n (\n [0 0]\n [0 1]\n )\n sage: D = A.module_morphism(matrix=A.derivations_basis()[0],\n ....: codomain=A)\n sage: one, e = A.basis()\n sage: all(D(a*b) == D(a) * b + a * D(b)\n ....: for a in A.basis() for b in A.basis())\n True\n\n REFERENCES:\n\n :wikipedia:`Derivation_(differential_algebra)`\n "
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 (B[y] * B[i]).monomial_coefficients(copy=False).items()}
zero = R.zero()
data = {}
N = len(keys)
for (ii, i) in enumerate(keys):
for (ij, j) in enumerate(keys):
for (il, l) in enumerate(keys):
row = ((ii + (N * ij)) + ((N ** 2) * il))
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, (ij + (N * ik)))] = (data.get((row, (ij + (N * ik))), zero) - scoeffs.get((l, i, k), zero))
from sage.matrix.constructor import matrix
mat = matrix(R, data, sparse=True)
return tuple([matrix(R, N, N, list(b)) for b in mat.right_kernel().basis()])
|
class Manifolds(Category_over_base_ring):
'\n The category of manifolds over any topological field.\n\n Let `k` be a topological field. A `d`-dimensional `k`-*manifold* `M`\n is a second countable Hausdorff space such that the neighborhood of\n any point `x \\in M` is homeomorphic to `k^d`.\n\n EXAMPLES::\n\n sage: # needs sage.rings.real_mpfr\n sage: from sage.categories.manifolds import Manifolds\n sage: C = Manifolds(RR); C\n Category of manifolds over Real Field with 53 bits of precision\n sage: C.super_categories()\n [Category of topological spaces]\n\n TESTS::\n\n sage: TestSuite(C).run(skip="_test_category_over_bases") # needs sage.rings.real_mpfr\n '
def __init__(self, base, name=None):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: C = Manifolds(RR)\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n '
if (base not in Fields().Topological()):
raise ValueError('base must be a topological field')
Category_over_base_ring.__init__(self, base, name)
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).super_categories()\n [Category of topological spaces]\n '
return [Sets().Topological()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of manifolds defines no new\n structure: a morphism of topological spaces between\n manifolds is a manifold morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).additional_structure()\n '
return None
class ParentMethods():
@abstract_method
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(RR).example()\n sage: M.dimension()\n 3\n '
class SubcategoryMethods():
@cached_method
def Connected(self):
"\n Return the full subcategory of the connected objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Connected() # needs sage.rings.real_mpfr\n Category of connected manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: Manifolds(RR).Connected.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('Connected')
@cached_method
def FiniteDimensional(self):
"\n Return the full subcategory of the finite dimensional\n objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: C = Manifolds(RR).Connected().FiniteDimensional(); C # needs sage.rings.real_mpfr\n Category of finite dimensional connected manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Connected().FiniteDimensional.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('FiniteDimensional')
@cached_method
def Differentiable(self):
"\n Return the subcategory of the differentiable objects\n of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Differentiable() # needs sage.rings.real_mpfr\n Category of differentiable manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Manifolds(RR).Differentiable()).run()\n sage: Manifolds(RR).Differentiable.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('Differentiable')
@cached_method
def Smooth(self):
"\n Return the subcategory of the smooth objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Smooth() # needs sage.rings.real_mpfr\n Category of smooth manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Manifolds(RR).Smooth()).run()\n sage: Manifolds(RR).Smooth.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('Smooth')
@cached_method
def Analytic(self):
"\n Return the subcategory of the analytic objects of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Analytic() # needs sage.rings.real_mpfr\n Category of analytic manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Manifolds(RR).Analytic()).run()\n sage: Manifolds(RR).Analytic.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('Analytic')
@cached_method
def AlmostComplex(self):
"\n Return the subcategory of the almost complex objects\n of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).AlmostComplex() # needs sage.rings.real_mpfr\n Category of almost complex manifolds\n over Real Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Manifolds(RR).AlmostComplex()).run()\n sage: Manifolds(RR).AlmostComplex.__module__\n 'sage.categories.manifolds'\n "
return self._with_axiom('AlmostComplex')
@cached_method
def Complex(self):
"\n Return the subcategory of manifolds over `\\CC` of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(CC).Complex() # needs sage.rings.real_mpfr\n Category of complex manifolds over\n Complex Field with 53 bits of precision\n\n TESTS::\n\n sage: TestSuite(Manifolds(CC).Complex()).run() # needs sage.rings.real_mpfr\n sage: Manifolds(CC).Complex.__module__ # needs sage.rings.real_mpfr\n 'sage.categories.manifolds'\n "
return ComplexManifolds(self.base())._with_axioms(self.axioms())
class Differentiable(CategoryWithAxiom_over_base_ring):
'\n The category of differentiable manifolds.\n\n A differentiable manifold is a manifold with a differentiable atlas.\n '
class Smooth(CategoryWithAxiom_over_base_ring):
'\n The category of smooth manifolds.\n\n A smooth manifold is a manifold with a smooth atlas.\n '
def extra_super_categories(self):
'\n Return the extra super categories of ``self``.\n\n A smooth manifold is differentiable.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Smooth().super_categories() # indirect doctest # needs sage.rings.real_mpfr\n [Category of differentiable manifolds\n over Real Field with 53 bits of precision]\n '
return [Manifolds(self.base()).Differentiable()]
class Analytic(CategoryWithAxiom_over_base_ring):
'\n The category of complex manifolds.\n\n An analytic manifold is a manifold with an analytic atlas.\n '
def extra_super_categories(self):
'\n Return the extra super categories of ``self``.\n\n An analytic manifold is smooth.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).Analytic().super_categories() # indirect doctest # needs sage.rings.real_mpfr\n [Category of smooth manifolds\n over Real Field with 53 bits of precision]\n '
return [Manifolds(self.base()).Smooth()]
class AlmostComplex(CategoryWithAxiom_over_base_ring):
'\n The category of almost complex manifolds.\n\n An *almost complex manifold* `M` is a manifold with a smooth tensor\n field `J` of rank `(1, 1)` such that `J^2 = -1` when regarded as a\n vector bundle isomorphism `J : TM \\to TM` on the tangent bundle.\n The tensor field `J` is called the *almost complex structure* of `M`.\n '
def extra_super_categories(self):
'\n Return the extra super categories of ``self``.\n\n An almost complex manifold is smooth.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).AlmostComplex().super_categories() # indirect doctest # needs sage.rings.real_mpfr\n [Category of smooth manifolds\n over Real Field with 53 bits of precision]\n '
return [Manifolds(self.base()).Smooth()]
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
'\n Category of finite dimensional manifolds.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: C = Manifolds(RR).FiniteDimensional()\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n '
class Connected(CategoryWithAxiom_over_base_ring):
'\n The category of connected manifolds.\n\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: C = Manifolds(RR).Connected()\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n '
|
class ComplexManifolds(Category_over_base_ring):
'\n The category of complex manifolds.\n\n A `d`-dimensional complex manifold is a manifold whose underlying\n vector space is `\\CC^d` and has a holomorphic atlas.\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.manifolds import Manifolds\n sage: Manifolds(RR).super_categories()\n [Category of topological spaces]\n '
return [Manifolds(self.base()).Analytic()]
|
class MatrixAlgebras(Category_over_base_ring):
'\n The category of matrix algebras over a field.\n\n EXAMPLES::\n\n sage: MatrixAlgebras(RationalField())\n Category of matrix algebras over Rational Field\n\n TESTS::\n\n sage: TestSuite(MatrixAlgebras(ZZ)).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: MatrixAlgebras(QQ).super_categories()\n [Category of algebras over Rational Field]\n '
R = self.base_ring()
return [Algebras(R)]
|
class MetricSpacesCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Metric'
@classmethod
def default_super_categories(cls, category):
'\n Return the default super categories of ``category.Metric()``.\n\n Mathematical meaning: if `A` is a metric space in the\n category `C`, then `A` is also a topological space.\n\n INPUT:\n\n - ``cls`` -- the class ``MetricSpaces``\n - ``category`` -- a category `Cat`\n\n OUTPUT:\n\n A (join) category\n\n In practice, this returns ``category.Metric()``, joined\n together with the result of the method\n :meth:`RegressiveCovariantConstructionCategory.default_super_categories()\n <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>`\n (that is the join of ``category`` and ``cat.Metric()`` for\n each ``cat`` in the super categories of ``category``).\n\n EXAMPLES:\n\n Consider ``category=Groups()``. Then, a group `G` with a metric\n is simultaneously a topological group by itself, and a\n metric space::\n\n sage: Groups().Metric().super_categories()\n [Category of topological groups, Category of metric spaces]\n\n This resulted from the following call::\n\n sage: sage.categories.metric_spaces.MetricSpacesCategory.default_super_categories(Groups())\n Join of Category of topological groups and Category of metric spaces\n '
return Category.join([category.Topological(), super().default_super_categories(category)])
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Groups().Metric() # indirect doctest\n Join of Category of topological groups and Category of metric spaces\n '
return 'metric {}'.format(self.base_category()._repr_object_names())
|
class MetricSpaces(MetricSpacesCategory):
'\n The category of metric spaces.\n\n A *metric* on a set `S` is a function `d : S \\times S \\to \\RR`\n such that:\n\n - `d(a, b) \\geq 0`,\n - `d(a, b) = 0` if and only if `a = b`.\n\n A metric space is a set `S` with a distinguished metric.\n\n .. RUBRIC:: Implementation\n\n Objects in this category must implement either a ``dist`` on the parent\n or the elements or ``metric`` on the parent; otherwise this will cause\n an infinite recursion.\n\n .. TODO::\n\n - Implement a general geodesics class.\n - Implement a category for metric additive groups\n and move the generic distance `d(a, b) = |a - b|` there.\n - Incorporate the length of a geodesic as part of the default\n distance cycle.\n\n EXAMPLES::\n\n sage: from sage.categories.metric_spaces import MetricSpaces\n sage: C = MetricSpaces()\n sage: C\n Category of metric spaces\n sage: TestSuite(C).run()\n '
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Sets().Metric() # indirect doctest\n Category of metric spaces\n '
return 'metric spaces'
class ParentMethods():
def _test_metric_function(self, **options):
'\n Test that this metric space has a properly implemented metric.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted\n by :meth:`_tester`\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: UHP = HyperbolicPlane().UHP()\n sage: UHP._test_metric_function()\n sage: elts = [UHP.random_element() for i in range(5)]\n sage: UHP._test_metric_function(some_elements=elts)\n '
tester = self._tester(**options)
S = tester.some_elements()
dist = self.metric_function()
for a in S:
for b in S:
d = dist(a, b)
if (a != b):
tester.assertGreater(d, 0)
else:
tester.assertEqual(d, 0)
def metric_function(self):
'\n Return the metric function of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: UHP = HyperbolicPlane().UHP()\n sage: m = UHP.metric_function()\n sage: p1 = UHP.get_point(5 + 7*I)\n sage: p2 = UHP.get_point(1.0 + I)\n sage: m(p1, p2)\n 2.23230104635820\n '
return (lambda a, b: a.dist(b))
metric = deprecated_function_alias(30062, metric_function)
def dist(self, a, b):
'\n Return the distance between ``a`` and ``b`` in ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: UHP = HyperbolicPlane().UHP()\n sage: p1 = UHP.get_point(5 + 7*I)\n sage: p2 = UHP.get_point(1.0 + I)\n sage: UHP.dist(p1, p2)\n 2.23230104635820\n\n sage: PD = HyperbolicPlane().PD() # needs sage.symbolic\n sage: PD.dist(PD.get_point(0), PD.get_point(I/2)) # needs sage.symbolic\n arccosh(5/3)\n\n TESTS::\n\n sage: RR.dist(-1, pi) # needs sage.rings.real_mpfr sage.symbolic\n 4.14159265358979\n sage: RDF.dist(1, -1/2)\n 1.5\n sage: CC.dist(3, 2) # needs sage.rings.real_mpfr\n 1.00000000000000\n sage: CC.dist(-1, I) # needs sage.rings.real_mpfr sage.symbolic\n 1.41421356237310\n sage: CDF.dist(-1, I) # needs sage.rings.real_mpfr sage.symbolic\n 1.4142135623730951\n '
return (self(a) - self(b)).abs()
class ElementMethods():
def abs(self):
'\n Return the absolute value of ``self``.\n\n EXAMPLES::\n\n sage: CC(I).abs() # needs sage.rings.real_mpfr sage.symbolic\n 1.00000000000000\n '
P = self.parent()
return P.metric()(self, P.zero())
def dist(self, b):
'\n Return the distance between ``self`` and ``other``.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: UHP = HyperbolicPlane().UHP()\n sage: p1 = UHP.get_point(5 + 7*I)\n sage: p2 = UHP.get_point(1 + I)\n sage: p1.dist(p2)\n arccosh(33/7)\n '
return self.parent().dist(self, b)
class Homsets(HomsetsCategory):
'\n The category of homsets of metric spaces\n\n It consists of the metric maps, that is, the Lipschitz functions\n with Lipschitz constant 1.\n '
class ElementMethods():
def _test_metric_map(self, **options):
"\n Test that this metric space morphism is a metric map,\n that is, a Lipschitz function with Lipschitz constant 1.\n\n EXAMPLES::\n\n sage: from sage.categories.metric_spaces import MetricSpaces\n sage: from sage.categories.morphism import SetMorphism\n sage: Q_abs = SetMorphism(Hom(QQ, QQ, MetricSpaces()), operator.__abs__)\n sage: TestSuite(Q_abs).run()\n\n TESTS::\n\n sage: Q_square = SetMorphism(Hom(QQ, QQ, MetricSpaces()), lambda x: x ** 2)\n sage: TestSuite(Q_square).run(skip=['_test_pickling'])\n Failure in _test_metric_map:\n Traceback (most recent call last):\n ...\n AssertionError: ... not less than or equal to ...\n ...\n The following tests failed: _test_metric_map\n "
tester = self._tester(**options)
S = self.domain().some_elements()
for a in S:
for b in S:
tester.assertLessEqual(self(a).dist(self(b)), a.dist(b))
class WithRealizations(WithRealizationsCategory):
class ParentMethods():
def dist(self, a, b):
'\n Return the distance between ``a`` and ``b`` by converting them\n to a realization of ``self`` and doing the computation.\n\n EXAMPLES::\n\n sage: # needs sage.symbolic\n sage: H = HyperbolicPlane()\n sage: PD = H.PD()\n sage: p1 = PD.get_point(0)\n sage: p2 = PD.get_point(I/2)\n sage: H.dist(p1, p2)\n arccosh(5/3)\n '
R = self.a_realization()
return R.dist(R(a), R(b))
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a (finite) Cartesian product of metric spaces is\n a metric space.\n\n EXAMPLES::\n\n sage: from sage.categories.metric_spaces import MetricSpaces\n sage: C = MetricSpaces().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of metric spaces]\n sage: C.super_categories()\n [Category of Cartesian products of topological spaces,\n Category of metric spaces]\n sage: C.axioms()\n frozenset()\n '
return [MetricSpaces()]
class ParentMethods():
def dist(self, a, b):
'\n Return the distance between ``a`` and ``b`` in ``self``.\n\n It is defined as the maximum of the distances within\n the Cartesian factors.\n\n EXAMPLES::\n\n sage: from sage.categories.metric_spaces import MetricSpaces\n sage: Q2 = QQ.cartesian_product(QQ)\n sage: Q2.category()\n Join of\n Category of Cartesian products of commutative rings and\n Category of Cartesian products of metric spaces\n sage: Q2 in MetricSpaces()\n True\n sage: Q2.dist((0, 0), (2, 3))\n 3\n '
return max((x.dist(y) for (x, y) in zip(self(a).cartesian_factors(), self(b).cartesian_factors())))
class SubcategoryMethods():
@cached_method
def Complete(self):
"\n Return the full subcategory of the complete objects of ``self``.\n\n EXAMPLES::\n\n sage: Sets().Metric().Complete()\n Category of complete metric spaces\n\n TESTS::\n\n sage: TestSuite(Sets().Metric().Complete()).run()\n sage: Sets().Metric().Complete.__module__\n 'sage.categories.metric_spaces'\n "
return self._with_axiom('Complete')
class Complete(CategoryWithAxiom):
'\n The category of complete metric spaces.\n '
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a (finite) Cartesian product of complete\n metric spaces is a complete metric space.\n\n EXAMPLES::\n\n sage: from sage.categories.metric_spaces import MetricSpaces\n sage: C = MetricSpaces().Complete().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of complete metric spaces]\n sage: C.super_categories()\n [Category of Cartesian products of metric spaces,\n Category of complete metric spaces]\n sage: C.axioms()\n frozenset({'Complete'})\n\n sage: R2 = RR.cartesian_product(RR)\n sage: R2 in MetricSpaces()\n True\n sage: R2 in MetricSpaces().Complete()\n True\n\n sage: QR = QQ.cartesian_product(RR)\n sage: QR in MetricSpaces()\n True\n sage: QR in MetricSpaces().Complete()\n False\n "
return [MetricSpaces().Complete()]
|
class ModularAbelianVarieties(Category_over_base):
'\n The category of modular abelian varieties over a given field.\n\n EXAMPLES::\n\n sage: ModularAbelianVarieties(QQ)\n Category of modular abelian varieties over Rational Field\n '
def __init__(self, Y):
'\n TESTS::\n\n sage: C = ModularAbelianVarieties(QQ)\n sage: C\n Category of modular abelian varieties over Rational Field\n sage: TestSuite(C).run()\n\n sage: ModularAbelianVarieties(ZZ)\n Traceback (most recent call last):\n ...\n assert Y.is_field()\n AssertionError\n '
assert Y.is_field()
Category_over_base.__init__(self, Y)
def base_field(self):
'\n EXAMPLES::\n\n sage: ModularAbelianVarieties(QQ).base_field()\n Rational Field\n '
return self.base()
def super_categories(self):
'\n EXAMPLES::\n\n sage: ModularAbelianVarieties(QQ).super_categories()\n [Category of sets]\n '
return [Sets()]
class Homsets(HomsetsCategory):
class Endset(CategoryWithAxiom):
def extra_super_categories(self):
'\n Implement the fact that an endset of modular abelian variety is a ring.\n\n EXAMPLES::\n\n sage: ModularAbelianVarieties(QQ).Endsets().extra_super_categories()\n [Category of rings]\n '
return [Rings()]
|
class Modules(Category_module):
"\n The category of all modules over a base ring `R`.\n\n An `R`-module `M` is a left and right `R`-module over a\n commutative ring `R` such that:\n\n .. MATH::\n\n r*(x*s) = (r*x)*s \\qquad \\forall r,s \\in R \\text{ and } x \\in M\n\n INPUT:\n\n - ``base_ring`` -- a ring `R` or subcategory of ``Rings()``\n - ``dispatch`` -- a boolean (for internal use; default: ``True``)\n\n When the base ring is a field, the category of vector spaces is\n returned instead (unless ``dispatch == False``).\n\n .. WARNING::\n\n Outside of the context of symmetric modules over a commutative\n ring, the specifications of this category are fuzzy and not\n yet set in stone (see below). The code in this category and\n its subcategories is therefore prone to bugs or arbitrary\n limitations in this case.\n\n EXAMPLES::\n\n sage: Modules(ZZ)\n Category of modules over Integer Ring\n sage: Modules(QQ)\n Category of vector spaces over Rational Field\n\n sage: Modules(Rings())\n Category of modules over rings\n sage: Modules(FiniteFields())\n Category of vector spaces over finite enumerated fields\n\n sage: Modules(Integers(9))\n Category of modules over Ring of integers modulo 9\n\n sage: Modules(Integers(9)).super_categories()\n [Category of bimodules over Ring of integers modulo 9 on the left\n and Ring of integers modulo 9 on the right]\n\n sage: Modules(ZZ).super_categories()\n [Category of bimodules over Integer Ring on the left\n and Integer Ring on the right]\n\n sage: Modules == RingModules\n True\n\n sage: Modules(ZZ['x']).is_abelian() # see #6081\n True\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ)).run()\n\n .. TODO::\n\n - Clarify the distinction, if any, with ``BiModules(R, R)``.\n In particular, if `R` is a commutative ring (e.g. a field),\n some pieces of the code possibly assume that `M` is a\n *symmetric `R`-`R`-bimodule*:\n\n .. MATH::\n\n r*x = x*r \\qquad \\forall r \\in R \\text{ and } x \\in M\n\n - Make sure that non symmetric modules are properly supported\n by all the code, and advertise it.\n\n - Make sure that non commutative rings are properly supported\n by all the code, and advertise it.\n\n - Add support for base semirings.\n\n - Implement a ``FreeModules(R)`` category, when so prompted by a\n concrete use case: e.g. modeling a free module with several\n bases (using :meth:`Sets.SubcategoryMethods.Realizations`)\n or with an atlas of local maps (see e.g. :trac:`15916`).\n "
@staticmethod
def __classcall_private__(cls, base_ring, dispatch=True):
"\n Implement the dispatching of ``Modules(field)`` to\n ``VectorSpaces(field)``.\n\n This feature will later be extended, probably as a covariant\n functorial construction, to support modules over various kinds\n of rings (principal ideal domains, ...), or even over semirings.\n\n TESTS::\n\n sage: C = Modules(ZZ); C\n Category of modules over Integer Ring\n sage: C is Modules(ZZ, dispatch = False)\n True\n sage: C is Modules(ZZ, dispatch = True)\n True\n sage: C._reduction\n (<class 'sage.categories.modules.Modules'>, (Integer Ring,), {'dispatch': False})\n sage: TestSuite(C).run()\n\n sage: Modules(QQ) is VectorSpaces(QQ)\n True\n sage: Modules(QQ, dispatch = True) is VectorSpaces(QQ)\n True\n\n sage: C = Modules(NonNegativeIntegers()); C # todo: not implemented\n Category of semiring modules over Non negative integers\n\n sage: C = Modules(QQ, dispatch = False); C\n Category of modules over Rational Field\n sage: C._reduction\n (<class 'sage.categories.modules.Modules'>, (Rational Field,), {'dispatch': False})\n sage: TestSuite(C).run()\n "
if dispatch:
if ((base_ring in _Fields) or (isinstance(base_ring, Category) and base_ring.is_subcategory(_Fields))):
from .vector_spaces import VectorSpaces
return VectorSpaces(base_ring, check=False)
result = super().__classcall__(cls, base_ring)
result._reduction[2]['dispatch'] = False
return result
def super_categories(self):
'\n EXAMPLES::\n\n sage: Modules(ZZ).super_categories()\n [Category of bimodules over Integer Ring on the left\n and Integer Ring on the right]\n\n Nota bene::\n\n sage: Modules(QQ)\n Category of vector spaces over Rational Field\n sage: Modules(QQ).super_categories()\n [Category of modules over Rational Field]\n '
R = self.base_ring()
return [Bimodules(R, R)]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of modules defines no additional structure:\n a bimodule morphism between two modules is a module morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`~sage.categories.category_with_axiom.CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: Modules(ZZ).additional_structure()\n '
return None
class SubcategoryMethods():
@cached_method
def base_ring(self):
"\n Return the base ring (category) for ``self``.\n\n This implements a ``base_ring`` method for all\n subcategories of ``Modules(K)``.\n\n EXAMPLES::\n\n sage: C = Modules(QQ) & Semigroups(); C\n Join of Category of semigroups\n and Category of vector spaces over Rational Field\n sage: C.base_ring()\n Rational Field\n sage: C.base_ring.__module__\n 'sage.categories.modules'\n\n sage: C2 = Modules(Rings()) & Semigroups(); C2\n Join of Category of semigroups and Category of modules over rings\n sage: C2.base_ring()\n Category of rings\n sage: C2.base_ring.__module__\n 'sage.categories.modules'\n\n sage: # needs sage.combinat sage.modules\n sage: C3 = DescentAlgebra(QQ,3).B().category()\n sage: C3.base_ring.__module__\n 'sage.categories.modules'\n sage: C3.base_ring()\n Rational Field\n\n sage: # needs sage.combinat sage.modules\n sage: C4 = QuasiSymmetricFunctions(QQ).F().category()\n sage: C4.base_ring.__module__\n 'sage.categories.modules'\n sage: C4.base_ring()\n Rational Field\n "
for C in self.super_categories():
if hasattr(C, 'base_ring'):
return C.base_ring()
assert False, 'some super category of {} should be a category over base ring'.format(self)
def TensorProducts(self):
'\n Return the full subcategory of objects of ``self`` constructed\n as tensor products.\n\n .. SEEALSO::\n\n - :class:`.tensor.TensorProductsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`.\n\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).TensorProducts()\n Category of tensor products of vector spaces with basis over Rational Field\n '
return TensorProductsCategory.category_of(self)
@cached_method
def DualObjects(self):
'\n Return the category of spaces constructed as duals of\n spaces of ``self``.\n\n The *dual* of a vector space `V` is the space consisting of\n all linear functionals on `V` (see :wikipedia:`Dual_space`).\n Additional structure on `V` can endow its dual with\n additional structure; for example, if `V` is a finite\n dimensional algebra, then its dual is a coalgebra.\n\n This returns the category of spaces constructed as dual of\n spaces in ``self``, endowed with the appropriate\n additional structure.\n\n .. WARNING::\n\n - This semantic of ``dual`` and ``DualObject`` is\n imposed on all subcategories, in particular to make\n ``dual`` a covariant functorial construction.\n\n A subcategory that defines a different notion of\n dual needs to use a different name.\n\n - Typically, the category of graded modules should\n define a separate ``graded_dual`` construction (see\n :trac:`15647`). For now the two constructions are\n not distinguished which is an oversimplified model.\n\n .. SEEALSO::\n\n - :class:`.dual.DualObjectsCategory`\n - :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction`.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).DualObjects()\n Category of duals of vector spaces over Rational Field\n\n The dual of a vector space is a vector space::\n\n sage: VectorSpaces(QQ).DualObjects().super_categories()\n [Category of vector spaces over Rational Field]\n\n The dual of an algebra is a coalgebra::\n\n sage: sorted(Algebras(QQ).DualObjects().super_categories(), key=str)\n [Category of coalgebras over Rational Field,\n Category of duals of vector spaces over Rational Field]\n\n The dual of a coalgebra is an algebra::\n\n sage: sorted(Coalgebras(QQ).DualObjects().super_categories(), key=str)\n [Category of algebras over Rational Field,\n Category of duals of vector spaces over Rational Field]\n\n As a shorthand, this category can be accessed with the\n :meth:`~Modules.SubcategoryMethods.dual` method::\n\n sage: VectorSpaces(QQ).dual()\n Category of duals of vector spaces over Rational Field\n\n TESTS::\n\n sage: C = VectorSpaces(QQ).DualObjects()\n sage: C.base_category()\n Category of vector spaces over Rational Field\n sage: C.super_categories()\n [Category of vector spaces over Rational Field]\n sage: latex(C)\n \\mathbf{DualObjects}(\\mathbf{VectorSpaces}_{\\Bold{Q}})\n sage: TestSuite(C).run()\n '
return DualObjectsCategory.category_of(self)
dual = DualObjects
@cached_method
def FiniteDimensional(self):
"\n Return the full subcategory of the finite dimensional objects of ``self``.\n\n EXAMPLES::\n\n sage: Modules(ZZ).FiniteDimensional()\n Category of finite dimensional modules over Integer Ring\n sage: Coalgebras(QQ).FiniteDimensional()\n Category of finite dimensional coalgebras over Rational Field\n sage: AlgebrasWithBasis(QQ).FiniteDimensional()\n Category of finite dimensional algebras with basis over Rational Field\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).FiniteDimensional()).run()\n sage: Coalgebras(QQ).FiniteDimensional.__module__\n 'sage.categories.modules'\n "
return self._with_axiom('FiniteDimensional')
@cached_method
def FinitelyPresented(self):
'\n Return the full subcategory of the finitely presented objects of ``self``.\n\n EXAMPLES::\n\n sage: Modules(ZZ).FinitelyPresented()\n Category of finitely presented modules over Integer Ring\n sage: A = SteenrodAlgebra(2) # needs sage.combinat sage.modules\n sage: from sage.modules.fp_graded.module import FPModule # needs sage.combinat sage.modules\n sage: FPModule(A, [0, 1], [[Sq(2), Sq(1)]]).category() # needs sage.combinat sage.modules\n Category of finitely presented graded modules\n over mod 2 Steenrod algebra, milnor basis\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).FinitelyPresented()).run()\n '
return self._with_axiom('FinitelyPresented')
@cached_method
def Filtered(self, base_ring=None):
"\n Return the subcategory of the filtered objects of ``self``.\n\n INPUT:\n\n - ``base_ring`` -- this is ignored\n\n EXAMPLES::\n\n sage: Modules(ZZ).Filtered()\n Category of filtered modules over Integer Ring\n\n sage: Coalgebras(QQ).Filtered()\n Category of filtered coalgebras over Rational Field\n\n sage: AlgebrasWithBasis(QQ).Filtered()\n Category of filtered algebras with basis over Rational Field\n\n .. TODO::\n\n - Explain why this does not commute with :meth:`WithBasis`\n - Improve the support for covariant functorial\n constructions categories over a base ring so as to\n get rid of the ``base_ring`` argument.\n\n TESTS::\n\n sage: Coalgebras(QQ).Graded.__module__\n 'sage.categories.modules'\n "
assert ((base_ring is None) or (base_ring is self.base_ring()))
from sage.categories.filtered_modules import FilteredModulesCategory
return FilteredModulesCategory.category_of(self)
@cached_method
def Graded(self, base_ring=None):
"\n Return the subcategory of the graded objects of ``self``.\n\n INPUT:\n\n - ``base_ring`` -- this is ignored\n\n EXAMPLES::\n\n sage: Modules(ZZ).Graded()\n Category of graded modules over Integer Ring\n\n sage: Coalgebras(QQ).Graded()\n Category of graded coalgebras over Rational Field\n\n sage: AlgebrasWithBasis(QQ).Graded()\n Category of graded algebras with basis over Rational Field\n\n .. TODO::\n\n - Explain why this does not commute with :meth:`WithBasis`\n - Improve the support for covariant functorial\n constructions categories over a base ring so as to\n get rid of the ``base_ring`` argument.\n\n TESTS::\n\n sage: Coalgebras(QQ).Graded.__module__\n 'sage.categories.modules'\n "
assert ((base_ring is None) or (base_ring is self.base_ring()))
from sage.categories.graded_modules import GradedModulesCategory
return GradedModulesCategory.category_of(self)
@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: Modules(ZZ).Super()\n Category of super modules over Integer Ring\n\n sage: Coalgebras(QQ).Super()\n Category of super coalgebras over Rational Field\n\n sage: AlgebrasWithBasis(QQ).Super()\n Category of super algebras with basis over Rational Field\n\n .. TODO::\n\n - Explain why this does not commute with :meth:`WithBasis`\n - Improve the support for covariant functorial\n constructions categories over a base ring so as to\n get rid of the ``base_ring`` argument.\n\n TESTS::\n\n sage: Coalgebras(QQ).Super.__module__\n 'sage.categories.modules'\n "
assert ((base_ring is None) or (base_ring is self.base_ring()))
from sage.categories.super_modules import SuperModulesCategory
return SuperModulesCategory.category_of(self)
@cached_method
def WithBasis(self):
"\n Return the full subcategory of the objects of ``self`` with\n a distinguished basis.\n\n EXAMPLES::\n\n sage: Modules(ZZ).WithBasis()\n Category of modules with basis over Integer Ring\n sage: Coalgebras(QQ).WithBasis()\n Category of coalgebras with basis over Rational Field\n sage: AlgebrasWithBasis(QQ).WithBasis()\n Category of algebras with basis over Rational Field\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).WithBasis()).run()\n sage: Coalgebras(QQ).WithBasis.__module__\n 'sage.categories.modules'\n "
return self._with_axiom('WithBasis')
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
def extra_super_categories(self):
'\n Implement the fact that a finite dimensional module over a finite\n ring is finite.\n\n EXAMPLES::\n\n sage: Modules(IntegerModRing(4)).FiniteDimensional().extra_super_categories()\n [Category of finite sets]\n sage: Modules(ZZ).FiniteDimensional().extra_super_categories()\n []\n sage: Modules(GF(5)).FiniteDimensional().is_subcategory(Sets().Finite())\n True\n sage: Modules(ZZ).FiniteDimensional().is_subcategory(Sets().Finite())\n False\n\n sage: Modules(Rings().Finite()).FiniteDimensional().is_subcategory(Sets().Finite())\n True\n sage: Modules(Rings()).FiniteDimensional().is_subcategory(Sets().Finite())\n False\n '
base_ring = self.base_ring()
FiniteSets = Sets().Finite()
if ((isinstance(base_ring, Category) and base_ring.is_subcategory(FiniteSets)) or (base_ring in FiniteSets)):
return [FiniteSets]
else:
return []
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: Modules(ZZ).FiniteDimensional().TensorProducts().extra_super_categories()\n [Category of finite dimensional modules over Integer Ring]\n sage: Modules(QQ).FiniteDimensional().TensorProducts().FiniteDimensional()\n Category of tensor products of finite dimensional vector spaces\n over Rational Field\n\n '
return [self.base_category()]
class FinitelyPresented(CategoryWithAxiom_over_base_ring):
def extra_super_categories(self):
'\n Implement the fact that a finitely presented module over a finite\n ring is finite.\n\n EXAMPLES::\n\n sage: Modules(IntegerModRing(4)).FiniteDimensional().extra_super_categories()\n [Category of finite sets]\n sage: Modules(ZZ).FiniteDimensional().extra_super_categories()\n []\n sage: Modules(GF(5)).FiniteDimensional().is_subcategory(Sets().Finite())\n True\n sage: Modules(ZZ).FiniteDimensional().is_subcategory(Sets().Finite())\n False\n\n sage: Modules(Rings().Finite()).FiniteDimensional().is_subcategory(Sets().Finite())\n True\n sage: Modules(Rings()).FiniteDimensional().is_subcategory(Sets().Finite())\n False\n '
base_ring = self.base_ring()
FiniteSets = Sets().Finite()
if ((isinstance(base_ring, Category) and base_ring.is_subcategory(FiniteSets)) or (base_ring in FiniteSets)):
return [FiniteSets]
else:
return []
Filtered = LazyImport('sage.categories.filtered_modules', 'FilteredModules')
Graded = LazyImport('sage.categories.graded_modules', 'GradedModules')
Super = LazyImport('sage.categories.super_modules', 'SuperModules')
WithBasis = LazyImport('sage.categories.modules_with_basis', 'ModulesWithBasis', at_startup=True)
class ParentMethods():
def linear_combination(self, iter_of_elements_coeff, factor_on_left=True):
'\n Return the linear combination `\\lambda_1 v_1 + \\cdots +\n \\lambda_k v_k` (resp. the linear combination `v_1 \\lambda_1 +\n \\cdots + v_k \\lambda_k`) where ``iter_of_elements_coeff`` iterates\n through the sequence `((\\lambda_1, v_1), ..., (\\lambda_k, v_k))`.\n\n INPUT:\n\n - ``iter_of_elements_coeff`` -- iterator of pairs\n ``(element, coeff)`` with ``element`` in ``self`` and\n ``coeff`` in ``self.base_ring()``\n\n - ``factor_on_left`` -- (optional) if ``True``, the coefficients\n are multiplied from the left; if ``False``, the coefficients\n are multiplied from the right\n\n EXAMPLES::\n\n sage: m = matrix([[0,1], [1,1]]) # needs sage.modules\n sage: J.<a,b,c> = JordanAlgebra(m) # needs sage.combinat sage.modules\n sage: J.linear_combination(((a+b, 1), (-2*b + c, -1))) # needs sage.combinat sage.modules\n 1 + (3, -1)\n '
if factor_on_left:
return self.sum(((coeff * element) for (element, coeff) in iter_of_elements_coeff))
else:
return self.sum(((element * coeff) for (element, coeff) in iter_of_elements_coeff))
@cached_method
def tensor_square(self):
'\n Returns the tensor square of ``self``\n\n EXAMPLES::\n\n sage: A = HopfAlgebrasWithBasis(QQ).example() # needs sage.groups sage.modules\n sage: A.tensor_square() # needs sage.groups sage.modules\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field # An example\n of Hopf algebra with basis: the group algebra of the Dihedral\n group of order 6 as a permutation group over Rational Field\n '
return tensor([self, self])
def module_morphism(self, *, function, category=None, codomain, **keywords):
"\n Construct a module morphism from ``self`` to ``codomain``.\n\n Let ``self`` be a module `X` over a ring `R`.\n This constructs a morphism `f: X \\to Y`.\n\n INPUT:\n\n - ``self`` -- a parent `X` in ``Modules(R)``.\n\n - ``function`` -- a function `f` from `X` to `Y`\n\n - ``codomain`` -- the codomain `Y` of the morphism (default:\n ``f.codomain()`` if it's defined; otherwise it must be specified)\n\n - ``category`` -- a category or ``None`` (default: ``None``)\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: V = FiniteRankFreeModule(QQ, 2)\n sage: e = V.basis('e'); e\n Basis (e_0,e_1) on the\n 2-dimensional vector space over the Rational Field\n sage: neg = V.module_morphism(function=operator.neg, codomain=V); neg\n Generic endomorphism of\n 2-dimensional vector space over the Rational Field\n sage: neg(e[0])\n Element -e_0 of the 2-dimensional vector space over the Rational Field\n\n "
if (category is None):
category = Modules(self.base_ring())
return SetMorphism(Hom(self, codomain, category), function)
def quotient(self, submodule, check=True, **kwds):
"\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\n - ``check``, other keyword arguments: passed on to\n :meth:`quotient_module`.\n\n This method just delegates to :meth:`quotient_module`.\n Classes implementing modules should override that method.\n\n Parents in categories with additional structure may override\n :meth:`quotient`. For example, in algebras, :meth:`quotient` will\n be the same as :meth:`quotient_ring`.\n\n EXAMPLES::\n\n sage: C = CombinatorialFreeModule(QQ, ['a','b','c']) # needs sage.modules\n sage: TA = TensorAlgebra(C) # needs sage.combinat sage.modules\n sage: TA.quotient # needs sage.combinat sage.modules\n <bound method Rings.ParentMethods.quotient of\n Tensor Algebra of Free module generated by {'a', 'b', 'c'}\n over Rational Field>\n\n "
return self.quotient_module(submodule, check=check, **kwds)
class ElementMethods():
pass
class Homsets(HomsetsCategory):
'\n The category of homomorphism sets `\\hom(X,Y)` for `X`, `Y` modules.\n '
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Modules(ZZ).Homsets().extra_super_categories()\n [Category of modules over Integer Ring]\n '
return [Modules(self.base_category().base_ring())]
def base_ring(self):
'\n EXAMPLES::\n\n sage: Modules(ZZ).Homsets().base_ring()\n Integer Ring\n\n .. TODO::\n\n Generalize this so that any homset category of a full\n subcategory of modules over a base ring is a category over\n this base ring.\n '
return self.base_category().base_ring()
class ParentMethods():
@cached_method
def base_ring(self):
'\n Return the base ring of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E = CombinatorialFreeModule(ZZ, [1,2,3])\n sage: F = CombinatorialFreeModule(ZZ, [2,3,4])\n sage: H = Hom(E, F)\n sage: H.base_ring()\n Integer Ring\n\n This ``base_ring`` method is actually overridden by\n :meth:`sage.structure.category_object.CategoryObject.base_ring`::\n\n sage: H.base_ring.__module__ # needs sage.modules\n\n Here we call it directly::\n\n sage: method = H.category().parent_class.base_ring # needs sage.modules\n sage: method.__get__(H)() # needs sage.modules\n Integer Ring\n '
return self.domain().base_ring()
@cached_method
def zero(self):
'\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E = CombinatorialFreeModule(ZZ, [1,2,3])\n sage: F = CombinatorialFreeModule(ZZ, [2,3,4])\n sage: H = Hom(E, F)\n sage: f = H.zero()\n sage: f\n Generic morphism:\n From: Free module generated by {1, 2, 3} over Integer Ring\n To: Free module generated by {2, 3, 4} over Integer Ring\n sage: f(E.monomial(2))\n 0\n sage: f(E.monomial(3)) == F.zero()\n True\n\n TESTS:\n\n We check that ``H.zero()`` is picklable::\n\n sage: loads(dumps(f.parent().zero())) # needs sage.modules\n Generic morphism:\n From: Free module generated by {1, 2, 3} over Integer Ring\n To: Free module generated by {2, 3, 4} over Integer Ring\n '
from sage.misc.constant_function import ConstantFunction
return self(ConstantFunction(self.codomain().zero()))
class Endset(CategoryWithAxiom_over_base_ring):
'\n The category of endomorphism sets `End(X)` for `X`\n a module (this is not used yet)\n '
def extra_super_categories(self):
'\n Implement the fact that the endomorphism set of a module is an algebra.\n\n .. SEEALSO:: :meth:`CategoryWithAxiom.extra_super_categories`\n\n EXAMPLES::\n\n sage: Modules(ZZ).Endsets().extra_super_categories()\n [Category of magmatic algebras over Integer Ring]\n\n sage: End(ZZ^3) in Algebras(ZZ) # needs sage.modules\n True\n '
from .magmatic_algebras import MagmaticAlgebras
return [MagmaticAlgebras(self.base_category().base_ring())]
class CartesianProducts(CartesianProductsCategory):
'\n The category of modules constructed as Cartesian products of modules\n\n This construction gives the direct product of modules. The\n implementation is based on the following resources:\n\n - http://groups.google.fr/group/sage-devel/browse_thread/thread/35a72b1d0a2fc77a/348f42ae77a66d16#348f42ae77a66d16\n - :wikipedia:`Direct_product`\n '
def extra_super_categories(self):
'\n A Cartesian product of modules is endowed with a natural\n module structure.\n\n EXAMPLES::\n\n sage: Modules(ZZ).CartesianProducts().extra_super_categories()\n [Category of modules over Integer Ring]\n sage: Modules(ZZ).CartesianProducts().super_categories()\n [Category of Cartesian products of commutative additive groups,\n Category of modules over Integer Ring]\n '
return [self.base_category()]
class ParentMethods():
def __init_extra__(self):
"\n Initialise the base ring of this Cartesian product.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: E = CombinatorialFreeModule(ZZ, [1,2,3])\n sage: F = CombinatorialFreeModule(ZZ, [2,3,4])\n sage: C = cartesian_product([E, F]); C\n Free module generated by {1, 2, 3} over Integer Ring (+)\n Free module generated by {2, 3, 4} over Integer Ring\n sage: C.base_ring()\n Integer Ring\n\n Check that :trac:`29225` is fixed::\n\n sage: M = cartesian_product((ZZ^2, ZZ^3)); M # needs sage.modules\n The Cartesian product of\n (Ambient free module of rank 2 over the principal ideal domain Integer Ring,\n Ambient free module of rank 3 over the principal ideal domain Integer Ring)\n sage: M.category() # needs sage.modules\n Category of Cartesian products of modules with basis\n over (euclidean domains and infinite enumerated sets and metric spaces)\n sage: M.base_ring() # needs sage.modules\n Integer Ring\n\n sage: A = cartesian_product((QQ^2, QQ['x'])); A # needs sage.modules\n The Cartesian product of\n (Vector space of dimension 2 over Rational Field,\n Univariate Polynomial Ring in x over Rational Field)\n sage: A.category() # needs sage.modules\n Category of Cartesian products of vector spaces\n over (number fields and quotient fields and metric spaces)\n sage: A.base_ring() # needs sage.modules\n Rational Field\n\n This currently only works if all factors have the same\n base ring::\n\n sage: B = cartesian_product((ZZ['x'], QQ^3)); B # needs sage.modules\n The Cartesian product of\n (Univariate Polynomial Ring in x over Integer Ring,\n Vector space of dimension 3 over Rational Field)\n sage: B.category() # needs sage.modules\n Category of Cartesian products of commutative additive groups\n sage: B.base_ring() # needs sage.modules\n "
factors = self._sets
if factors:
R = factors[0].base_ring()
if all(((A.base_ring() is R) for A in factors)):
self._base = R
class ElementMethods():
def _lmul_(self, x):
'\n Return the product of `x` with ``self``.\n\n EXAMPLES::\n\n sage: A = FreeModule(ZZ, 2) # needs sage.modules\n sage: B = cartesian_product([A, A]); B # needs sage.modules\n The Cartesian product of\n (Ambient free module of rank 2 over the principal ideal domain Integer Ring,\n Ambient free module of rank 2 over the principal ideal domain Integer Ring)\n sage: 5*B(([1, 2], [3, 4])) # needs sage.modules\n ((5, 10), (15, 20))\n '
return self.parent()._cartesian_product_of_elements(((x * y) for y in self.cartesian_factors()))
class TensorProducts(TensorProductsCategory):
'\n The category of modules constructed by tensor product of modules.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Modules(ZZ).TensorProducts().extra_super_categories()\n [Category of modules over Integer Ring]\n sage: Modules(ZZ).TensorProducts().super_categories()\n [Category of modules over Integer Ring]\n '
return [self.base_category()]
class ParentMethods():
'\n Implement operations on tensor products of modules.\n '
def construction(self):
'\n Return the construction of ``self``.\n\n EXAMPLES::\n\n sage: A = algebras.Free(QQ, 2) # needs sage.combinat sage.modules\n sage: T = A.tensor(A) # needs sage.combinat sage.modules\n sage: T.construction() # needs sage.combinat sage.modules\n (The tensor functorial construction,\n (Free Algebra on 2 generators (None0, None1) over Rational Field,\n Free Algebra on 2 generators (None0, None1) over Rational Field))\n '
try:
factors = self.tensor_factors()
except (TypeError, NotImplementedError):
from sage.misc.superseded import deprecation
deprecation(34393, 'implementations of Modules().TensorProducts() now must define the method tensor_factors')
return None
return (TensorProductFunctor(), factors)
@abstract_method(optional=True)
def tensor_factors(self):
'\n Return the tensor factors of this tensor product.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, [1,2])\n sage: F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [3,4])\n sage: G.rename("G")\n sage: T = tensor([F, G]); T\n F # G\n sage: T.tensor_factors()\n (F, G)\n\n TESTS::\n\n sage: Cat = ModulesWithBasis(ZZ).FiniteDimensional().TensorProducts()\n sage: M = CombinatorialFreeModule(ZZ, ((1, 1), (1, 2), (2, 1), (2, 2)), category=Cat) # needs sage.modules\n sage: M.construction() # needs sage.modules\n doctest:warning...\n DeprecationWarning: implementations of Modules().TensorProducts() now must define the method tensor_factors\n See https://github.com/sagemath/sage/issues/34393 for details.\n (VectorFunctor, Integer Ring)\n '
|
class ModulesWithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of modules with a distinguished basis.\n\n The elements are represented by expanding them in the distinguished basis.\n The morphisms are not required to respect the distinguished basis.\n\n EXAMPLES::\n\n sage: ModulesWithBasis(ZZ)\n Category of modules with basis over Integer Ring\n sage: ModulesWithBasis(ZZ).super_categories()\n [Category of modules over Integer Ring]\n\n If the base ring is actually a field, this constructs instead the\n category of vector spaces with basis::\n\n sage: ModulesWithBasis(QQ)\n Category of vector spaces with basis over Rational Field\n\n sage: ModulesWithBasis(QQ).super_categories()\n [Category of modules with basis over Rational Field,\n Category of vector spaces over Rational Field]\n\n Let `X` and `Y` be two modules with basis. We can build `Hom(X,Y)`::\n\n sage: X = CombinatorialFreeModule(QQ, [1,2]); X.rename("X") # needs sage.modules\n sage: Y = CombinatorialFreeModule(QQ, [3,4]); Y.rename("Y") # needs sage.modules\n sage: H = Hom(X, Y); H # needs sage.modules\n Set of Morphisms from X to Y\n in Category of finite dimensional vector spaces with basis over Rational Field\n\n The simplest morphism is the zero map::\n\n sage: H.zero() # todo: move this test into module once we have an example # needs sage.modules\n Generic morphism:\n From: X\n To: Y\n\n which we can apply to elements of `X`::\n\n sage: x = X.monomial(1) + 3 * X.monomial(2) # needs sage.modules\n sage: H.zero()(x) # needs sage.modules\n 0\n\n EXAMPLES:\n\n We now construct a more interesting morphism by extending a\n function by linearity::\n\n sage: phi = H(on_basis=lambda i: Y.monomial(i + 2)); phi # needs sage.modules\n Generic morphism:\n From: X\n To: Y\n sage: phi(x) # needs sage.modules\n B[3] + 3*B[4]\n\n We can retrieve the function acting on indices of the basis::\n\n sage: f = phi.on_basis() # needs sage.modules\n sage: f(1), f(2) # needs sage.modules\n (B[3], B[4])\n\n `Hom(X,Y)` has a natural module structure (except for the zero,\n the operations are not yet implemented though). However since the\n dimension is not necessarily finite, it is not a module with\n basis; but see :class:`FiniteDimensionalModulesWithBasis` and\n :class:`GradedModulesWithBasis`::\n\n sage: H in ModulesWithBasis(QQ), H in Modules(QQ) # needs sage.modules\n (False, True)\n\n Some more playing around with categories and higher order homsets::\n\n sage: H.category() # needs sage.modules\n Category of homsets of modules with basis over Rational Field\n sage: Hom(H, H).category() # needs sage.modules\n Category of endsets of homsets of modules with basis over Rational Field\n\n .. TODO:: ``End(X)`` is an algebra.\n\n .. NOTE::\n\n This category currently requires an implementation of an\n element method ``support``. Once :trac:`18066` is merged, an\n implementation of an ``items`` method will be required.\n\n TESTS::\n\n sage: f = H.zero().on_basis() # needs sage.modules\n sage: f(1) # needs sage.modules\n 0\n sage: f(2) # needs sage.modules\n 0\n\n sage: TestSuite(ModulesWithBasis(ZZ)).run()\n\n '
def _call_(self, x):
"\n Construct a module with basis (resp. vector space) from the data in ``x``.\n\n EXAMPLES::\n\n sage: CZ = ModulesWithBasis(ZZ); CZ\n Category of modules with basis over Integer Ring\n sage: CQ = ModulesWithBasis(QQ); CQ\n Category of vector spaces with basis over Rational Field\n\n ``x`` is returned unchanged if it is already in this category::\n\n sage: CZ(CombinatorialFreeModule(ZZ, ('a', 'b', 'c'))) # needs sage.modules\n Free module generated by {'a', 'b', 'c'} over Integer Ring\n sage: CZ(ZZ^3) # needs sage.modules\n Ambient free module of rank 3 over the principal ideal domain Integer Ring\n\n If needed (and possible) the base ring is changed appropriately::\n\n sage: CQ(ZZ^3) # indirect doctest # needs sage.modules\n Vector space of dimension 3 over Rational Field\n\n If ``x`` itself is not a module with basis, but there is a\n canonical one associated to it, the latter is returned::\n\n sage: CQ(AbelianVariety(Gamma0(37))) # indirect doctest # needs sage.modular sage.modules\n Vector space of dimension 4 over Rational Field\n "
try:
M = x.free_module()
if (M.base_ring() != self.base_ring()):
M = M.change_ring(self.base_ring())
except (TypeError, AttributeError) as msg:
raise TypeError(('%s\nunable to coerce x (=%s) into %s' % (msg, x, self)))
return M
def is_abelian(self):
'\n Return whether this category is abelian.\n\n This is the case if and only if the base ring is a field.\n\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).is_abelian()\n True\n sage: ModulesWithBasis(ZZ).is_abelian()\n False\n '
return self.base_ring().is_field()
FiniteDimensional = LazyImport('sage.categories.finite_dimensional_modules_with_basis', 'FiniteDimensionalModulesWithBasis', at_startup=True)
Filtered = LazyImport('sage.categories.filtered_modules_with_basis', 'FilteredModulesWithBasis')
Graded = LazyImport('sage.categories.graded_modules_with_basis', 'GradedModulesWithBasis')
Super = LazyImport('sage.categories.super_modules_with_basis', 'SuperModulesWithBasis')
class ParentMethods():
@cached_method
def basis(self):
"\n Return the basis of ``self``.\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c']) # needs sage.modules\n sage: F.basis() # needs sage.modules\n Finite family {'a': B['a'], 'b': B['b'], 'c': B['c']}\n\n ::\n\n sage: QS3 = SymmetricGroupAlgebra(QQ, 3) # needs sage.combinat sage.groups sage.modules\n sage: list(QS3.basis()) # needs sage.combinat sage.groups sage.modules\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n "
from sage.sets.family import Family
return Family(self._indices, self.monomial)
def module_morphism(self, on_basis=None, matrix=None, function=None, diagonal=None, triangular=None, unitriangular=False, **keywords):
'\n Construct a module morphism from ``self`` to ``codomain``.\n\n Let ``self`` be a module `X` with a basis indexed by `I`.\n This constructs a morphism `f: X \\to Y` by linearity from\n a map `I \\to Y` which is to be its restriction to the\n basis `(x_i)_{i \\in I}` of `X`. Some variants are possible\n too.\n\n INPUT:\n\n - ``self`` -- a parent `X` in ``ModulesWithBasis(R)`` with\n basis `x=(x_i)_{i\\in I}`.\n\n Exactly one of the four following options must be\n specified in order to define the morphism:\n\n - ``on_basis`` -- a function `f` from `I` to `Y`\n - ``diagonal`` -- a function `d` from `I` to `R`\n - ``function`` -- a function `f` from `X` to `Y`\n - ``matrix`` -- a matrix of size `\\dim Y \\times \\dim X`\n (if the keyword ``side`` is set to ``\'left\'``) or\n `\\dim Y \\times \\dim X` (if this keyword is ``\'right\'``)\n\n Further options include:\n\n - ``codomain`` -- the codomain `Y` of the morphism (default:\n ``f.codomain()`` if it\'s defined; otherwise it must be specified)\n\n - ``category`` -- a category or ``None`` (default: ``None``)\n\n - ``zero`` -- the zero of the codomain (default: ``codomain.zero()``);\n can be used (with care) to define affine maps.\n Only meaningful with ``on_basis``.\n\n - ``position`` -- a non-negative integer specifying which\n positional argument is used as the input of the function `f`\n (default: 0); this is currently only used with ``on_basis``.\n\n - ``triangular`` -- (default: ``None``) ``"upper"`` or\n ``"lower"`` or ``None``:\n\n * ``"upper"`` - if the\n :meth:`~ModulesWithBasis.ElementMethods.leading_support`\n of the image of the basis vector `x_i` is `i`, or\n\n * ``"lower"`` - if the\n :meth:`~ModulesWithBasis.ElementMethods.trailing_support`\n of the image of the basis vector `x_i` is `i`.\n\n - ``unitriangular`` -- (default: ``False``) a boolean.\n Only meaningful for a triangular morphism.\n As a shorthand, one may use ``unitriangular="lower"``\n for ``triangular="lower", unitriangular=True``.\n\n - ``side`` -- "left" or "right" (default: "left")\n Only meaningful for a morphism built from a matrix.\n\n EXAMPLES:\n\n With the ``on_basis`` option, this returns a function `g`\n obtained by extending `f` by linearity on the\n ``position``-th positional argument. For example, for\n ``position == 1`` and a ternary function `f`, one has:\n\n .. MATH::\n\n g\\left( a,\\ \\sum_i \\lambda_i x_i,\\ c \\right)\n = \\sum_i \\lambda_i f(a, i, c).\n\n ::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X")\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4]); Y.rename("Y")\n sage: def f(i):\n ....: return Y.monomial(i) + 2*Y.monomial(i+1)\n sage: phi = X.module_morphism(f, codomain=Y)\n sage: x = X.basis(); y = Y.basis()\n sage: phi(x[1] + x[3])\n B[1] + 2*B[2] + B[3] + 2*B[4]\n sage: phi\n Generic morphism:\n From: X\n To: Y\n\n By default, the category is the first of\n ``Modules(R).WithBasis().FiniteDimensional()``,\n ``Modules(R).WithBasis()``, ``Modules(R)``, and\n ``CommutativeAdditiveMonoids()`` that contains both the\n domain and the codomain::\n\n sage: phi.category_for() # needs sage.modules\n Category of finite dimensional vector spaces with basis\n over Rational Field\n\n With the ``zero`` argument, one can define affine morphisms::\n\n sage: def f(i):\n ....: return Y.monomial(i) + 2*Y.monomial(i+1)\n sage: phi = X.module_morphism(f, codomain=Y, zero=10*y[1]) # needs sage.modules\n sage: phi(x[1] + x[3]) # needs sage.modules\n 11*B[1] + 2*B[2] + B[3] + 2*B[4]\n\n In this special case, the default category is ``Sets()``::\n\n sage: phi.category_for() # needs sage.modules\n Category of sets\n\n One can construct morphisms with the base ring as codomain::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(ZZ, [1, -1])\n sage: phi = X.module_morphism(on_basis=lambda i: i, codomain=ZZ)\n sage: phi(2 * X.monomial(1) + 3 * X.monomial(-1))\n -1\n sage: phi.category_for()\n Category of commutative additive semigroups\n sage: phi.category_for() # not implemented\n Category of modules over Integer Ring\n\n Or more generally any ring admitting a coercion map from\n the base ring::\n\n sage: # needs sage.modules\n sage: phi = X.module_morphism(on_basis=lambda i: i, codomain=RR)\n sage: phi(2 * X.monomial(1) + 3 * X.monomial(-1))\n -1.00000000000000\n sage: phi.category_for()\n Category of commutative additive semigroups\n sage: phi.category_for() # not implemented\n Category of modules over Integer Ring\n\n sage: phi = X.module_morphism(on_basis=lambda i: i, codomain=Zmod(4)) # needs sage.modules\n sage: phi(2 * X.monomial(1) + 3 * X.monomial(-1)) # needs sage.modules\n 3\n\n sage: phi = Y.module_morphism(on_basis=lambda i: i, codomain=Zmod(4)) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: codomain(=Ring of integers modulo 4) should be a module\n over the base ring of the domain(=Y)\n\n On can also define module morphisms between free modules\n over different base rings; here we implement the natural\n map from `X = \\RR^2` to `Y = \\CC`::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(RR, [\'x\', \'y\'])\n sage: Y = CombinatorialFreeModule(CC, [\'z\'])\n sage: x = X.monomial(\'x\')\n sage: y = X.monomial(\'y\')\n sage: z = Y.monomial(\'z\')\n sage: def on_basis(a):\n ....: if a == \'x\':\n ....: return CC(1) * z\n ....: elif a == \'y\':\n ....: return CC(I) * z\n sage: phi = X.module_morphism(on_basis=on_basis, codomain=Y)\n sage: v = 3 * x + 2 * y; v\n 3.00000000000000*B[\'x\'] + 2.00000000000000*B[\'y\']\n sage: phi(v) # needs sage.symbolic\n (3.00000000000000+2.00000000000000*I)*B[\'z\']\n sage: phi.category_for()\n Category of commutative additive semigroups\n sage: phi.category_for() # not implemented\n Category of vector spaces over Real Field with 53 bits of precision\n\n sage: # needs sage.modules\n sage: Y = CombinatorialFreeModule(CC[\'q\'], [\'z\'])\n sage: z = Y.monomial(\'z\')\n sage: phi = X.module_morphism(on_basis=on_basis, codomain=Y)\n sage: phi(v) # needs sage.symbolic\n (3.00000000000000+2.00000000000000*I)*B[\'z\']\n\n Of course, there should be a coercion between the\n respective base rings of the domain and the codomain for\n this to be meaningful::\n\n sage: Y = CombinatorialFreeModule(QQ, [\'z\']) # needs sage.modules\n sage: phi = X.module_morphism(on_basis=on_basis, codomain=Y) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: codomain(=Free module generated by {\'z\'} over Rational Field)\n should be a module over the base ring of the domain(=Free module\n generated by {\'x\', \'y\'} over Real Field with 53 bits of precision)\n\n sage: Y = CombinatorialFreeModule(RR[\'q\'], [\'z\']) # needs sage.modules\n sage: phi = Y.module_morphism(on_basis=on_basis, codomain=X) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: codomain(=Free module generated by {\'x\', \'y\'}\n over Real Field with 53 bits of precision) should be a module over\n the base ring of the domain(=Free module generated by {\'z\'} over\n Univariate Polynomial Ring in q over Real Field with 53 bits of precision)\n\n\n With the ``diagonal=d`` argument, this constructs the\n module morphism `g` such that\n\n .. MATH::\n\n `g(x_i) = d(i) y_i`.\n\n This assumes that the respective bases `x` and `y` of `X`\n and `Y` have the same index set `I`::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(ZZ, [1, 2, 3]); X.rename("X")\n sage: from sage.arith.misc import factorial\n sage: phi = X.module_morphism(diagonal=factorial, codomain=X)\n sage: x = X.basis()\n sage: phi(x[1]), phi(x[2]), phi(x[3])\n (B[1], 2*B[2], 6*B[3])\n\n See also: :class:`sage.modules.with_basis.morphism.DiagonalModuleMorphism`.\n\n With the ``matrix=m`` argument, this constructs the module\n morphism whose matrix in the distinguished basis of `X`\n and `Y` is `m`::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X")\n sage: x = X.basis()\n sage: Y = CombinatorialFreeModule(ZZ, [3,4]); Y.rename("Y")\n sage: y = Y.basis()\n sage: m = matrix([[0,1,2], [3,5,0]])\n sage: phi = X.module_morphism(matrix=m, codomain=Y)\n sage: phi(x[1])\n 3*B[4]\n sage: phi(x[2])\n B[3] + 5*B[4]\n\n\n See also: :class:`sage.modules.with_basis.morphism.ModuleMorphismFromMatrix`.\n\n With ``triangular="upper"``, the constructed module morphism is\n assumed to be upper triangular; that is its matrix in the\n distinguished basis of `X` and `Y` would be upper triangular with\n invertible elements on its diagonal. This is used to compute\n preimages and to invert the morphism::\n\n sage: # needs sage.modules\n sage: I = list(range(1, 200))\n sage: X = CombinatorialFreeModule(QQ, I); X.rename("X"); x = X.basis()\n sage: Y = CombinatorialFreeModule(QQ, I); Y.rename("Y"); y = Y.basis()\n sage: f = Y.sum_of_monomials * divisors\n sage: phi = X.module_morphism(f, triangular="upper", codomain=Y)\n sage: phi(x[2])\n B[1] + B[2]\n sage: phi(x[6])\n B[1] + B[2] + B[3] + B[6]\n sage: phi(x[30])\n B[1] + B[2] + B[3] + B[5] + B[6] + B[10] + B[15] + B[30]\n sage: phi.preimage(y[2])\n -B[1] + B[2]\n sage: phi.preimage(y[6])\n B[1] - B[2] - B[3] + B[6]\n sage: phi.preimage(y[30])\n -B[1] + B[2] + B[3] + B[5] - B[6] - B[10] - B[15] + B[30]\n sage: (phi^-1)(y[30])\n -B[1] + B[2] + B[3] + B[5] - B[6] - B[10] - B[15] + B[30]\n\n Since :trac:`8678`, one can also define a triangular\n morphism from a function::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [0,1,2,3,4]); x = X.basis()\n sage: from sage.modules.with_basis.morphism import TriangularModuleMorphismFromFunction\n sage: def f(x): return x + X.term(0, sum(x.coefficients()))\n sage: phi = X.module_morphism(function=f, codomain=X,\n ....: triangular="upper")\n sage: phi(x[2] + 3*x[4])\n 4*B[0] + B[2] + 3*B[4]\n sage: phi.preimage(_)\n B[2] + 3*B[4]\n\n For details and further optional arguments, see\n :class:`sage.modules.with_basis.morphism.TriangularModuleMorphism`.\n\n .. WARNING::\n\n As a temporary measure, until multivariate morphisms\n are implemented, the constructed morphism is in\n ``Hom(codomain, domain, category)``. This is only\n correct for unary functions.\n\n .. TODO::\n\n - Should codomain be ``self`` by default in the\n diagonal, triangular, and matrix cases?\n\n - Support for diagonal morphisms between modules not\n sharing the same index set\n\n TESTS::\n\n sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X") # needs sage.modules\n sage: phi = X.module_morphism(codomain=X) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: module_morphism() takes exactly one option\n out of `matrix`, `on_basis`, `function`, `diagonal`\n\n ::\n\n sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X") # needs sage.modules\n sage: phi = X.module_morphism(diagonal=factorial, matrix=matrix(), # needs sage.modules\n ....: codomain=X)\n Traceback (most recent call last):\n ...\n ValueError: module_morphism() takes exactly one option\n out of `matrix`, `on_basis`, `function`, `diagonal`\n\n ::\n\n sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X") # needs sage.modules\n sage: phi = X.module_morphism(matrix=factorial, codomain=X) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: matrix (=...factorial...) should be a matrix\n\n ::\n\n sage: X = CombinatorialFreeModule(ZZ, [1,2,3]); X.rename("X") # needs sage.modules\n sage: phi = X.module_morphism(diagonal=3, codomain=X) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: diagonal (=3) should be a function\n\n '
if (len([x for x in [matrix, on_basis, function, diagonal] if (x is not None)]) != 1):
raise ValueError('module_morphism() takes exactly one option out of `matrix`, `on_basis`, `function`, `diagonal`')
if (matrix is not None):
return ModuleMorphismFromMatrix(domain=self, matrix=matrix, **keywords)
if (diagonal is not None):
return DiagonalModuleMorphism(domain=self, diagonal=diagonal, **keywords)
if ((unitriangular in ['upper', 'lower']) and (triangular is None)):
triangular = unitriangular
unitriangular = True
if (triangular is not None):
if (on_basis is not None):
return TriangularModuleMorphismByLinearity(domain=self, on_basis=on_basis, triangular=triangular, unitriangular=unitriangular, **keywords)
else:
return TriangularModuleMorphismFromFunction(domain=self, function=function, triangular=triangular, unitriangular=unitriangular, **keywords)
if (on_basis is not None):
return ModuleMorphismByLinearity(domain=self, on_basis=on_basis, **keywords)
else:
return ModuleMorphismFromFunction(domain=self, function=function, **keywords)
_module_morphism = module_morphism
def _repr_(self):
'\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: class FooBar(CombinatorialFreeModule): pass\n sage: C = FooBar(QQ, (1,2,3)); C # indirect doctest\n Free module generated by {1, 2, 3} over Rational Field\n sage: C._name = "foobar"; C\n foobar over Rational Field\n sage: C.rename("barfoo"); C\n barfoo\n\n sage: class FooBar(Parent):\n ....: def basis(self): return Family({1: "foo", 2: "bar"})\n ....: def base_ring(self): return QQ\n sage: FooBar(category=ModulesWithBasis(QQ))\n Free module generated by [1, 2] over Rational Field\n '
if hasattr(self, '_name'):
name = self._name
else:
name = 'Free module generated by {}'.format(self.basis().keys())
return (name + ' over {}'.format(self.base_ring()))
def _compute_support_order(self, elements, support_order=None):
"\n Return the support of a set of elements in ``self`` sorted\n in some order.\n\n INPUT:\n\n - ``elements`` -- the list of elements\n - ``support_order`` -- (optional) either something that can\n be converted into a tuple or a key function\n\n EXAMPLES:\n\n A finite dimensional module::\n\n sage: # needs sage.modules\n sage: V = CombinatorialFreeModule(QQ, range(10), prefix='x')\n sage: B = V.basis()\n sage: elts = [B[0] - 2*B[3], B[5] + 2*B[0],\n ....: B[2], B[3], B[1] + B[2] + B[8]]\n sage: V._compute_support_order(elts)\n (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n sage: V._compute_support_order(elts, [1,2,0,4,3,5,9,8,7,6])\n (1, 2, 0, 4, 3, 5, 9, 8, 7, 6)\n sage: V._compute_support_order(elts, lambda x: -x)\n (8, 5, 3, 2, 1, 0)\n\n An infinite dimensional module::\n\n sage: # needs sage.modules\n sage: V = CombinatorialFreeModule(QQ, ZZ, prefix='z')\n sage: B = V.basis()\n sage: elts = [B[0] - 2*B[3], B[5] + 2*B[0],\n ....: B[2], B[3], B[1] + B[2] + B[8]]\n sage: V._compute_support_order(elts)\n (0, 1, 2, 3, 5, 8)\n sage: V._compute_support_order(elts, [1,2,0,4,3,5,9,8,7,6])\n (1, 2, 0, 4, 3, 5, 9, 8, 7, 6)\n sage: V._compute_support_order(elts, lambda x: -x)\n (8, 5, 3, 2, 1, 0)\n "
if (support_order is None):
try:
support_order = self.get_order()
except (ValueError, TypeError, NotImplementedError, AttributeError):
support_order = set()
for y in elements:
support_order.update(y.support())
try:
support_order = sorted(support_order)
except (ValueError, TypeError):
pass
try:
support_order = tuple(support_order)
except (ValueError, TypeError):
support = set()
for y in elements:
support.update(y.support())
support_order = sorted(support, key=support_order)
return tuple(support_order)
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: R.<x,y> = QQ[]\n sage: C = CombinatorialFreeModule(R, ZZ, prefix='z') # needs sage.modules\n sage: z = C.basis() # needs sage.modules\n sage: C.echelon_form([z[0] - z[1], 2*z[1] - 2*z[2], z[0] - z[2]]) # needs sage.libs.singular sage.modules\n [z[0] - z[2], z[1] - z[2]]\n\n TESTS:\n\n We convert the input elements to ``self``::\n\n sage: s = SymmetricFunctions(QQ).s() # needs sage.combinat sage.modules\n sage: s.echelon_form([1, s[1] + 5]) # needs sage.combinat sage.modules\n [s[], s[1]]\n "
elements = [self(y) for y in elements]
order = self._compute_support_order(elements, order)
from sage.matrix.constructor import matrix
mat = matrix(self.base_ring(), [[g[s] for s in 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()
return [self._from_dict({order[i]: c for (i, c) in enumerate(vec) if c}, remove_zeros=False) for vec in mat if vec]
def submodule(self, gens, check=True, already_echelonized=False, unitriangular=False, support_order=None, category=None, *args, **opts):
'\n 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 We construct a submodule of the free `\\QQ`-module generated by\n `x_0, x_1, x_2`. The submodule is spanned by `y_0 = x_0 - x_1` and\n `y_1 - x_1 - x_2`, and its basis elements are indexed by `0` and `1`::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")\n sage: x = X.basis()\n sage: gens = [x[0] - x[1], x[1] - x[2]]; gens\n [x[0] - x[1], x[1] - x[2]]\n sage: Y = X.submodule(gens, already_echelonized=True)\n sage: Y.print_options(prefix=\'y\'); Y\n Free module generated by {0, 1} over Rational Field\n sage: y = Y.basis()\n sage: y[1]\n y[1]\n sage: y[1].lift()\n x[1] - x[2]\n sage: Y.retract(x[0] - x[2])\n y[0] + y[1]\n sage: Y.retract(x[0])\n Traceback (most recent call last):\n ...\n ValueError: x[0] is not in the image\n\n By using a family to specify a basis of the submodule, we obtain a\n submodule whose index set coincides with the index set of the family::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")\n sage: x = X.basis()\n sage: gens = Family({1: x[0] - x[1], 3: x[1] - x[2]}); gens\n Finite family {1: x[0] - x[1], 3: x[1] - x[2]}\n sage: Y = X.submodule(gens, already_echelonized=True)\n sage: Y.print_options(prefix=\'y\'); Y\n Free module generated by {1, 3} over Rational Field\n sage: y = Y.basis()\n sage: y[1]\n y[1]\n sage: y[1].lift()\n x[0] - x[1]\n sage: y[3].lift()\n x[1] - x[2]\n sage: Y.retract(x[0] - x[2])\n y[1] + y[3]\n sage: Y.retract(x[0])\n Traceback (most recent call last):\n ...\n ValueError: x[0] is not in the image\n\n It is not necessary that the generators of the submodule form\n a basis (an explicit basis will be computed)::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")\n sage: x = X.basis()\n sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]; gens\n [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]\n sage: Y = X.submodule(gens, already_echelonized=False)\n sage: Y.print_options(prefix=\'y\')\n sage: Y\n Free module generated by {0, 1} over Rational Field\n sage: [b.lift() for b in Y.basis()]\n [x[0] - x[2], x[1] - x[2]]\n\n We now implement by hand the center of the algebra of the\n symmetric group `S_3`::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: S3 = SymmetricGroup(3)\n sage: S3A = S3.algebra(QQ)\n sage: basis = S3A.annihilator_basis(S3A.algebra_generators(),\n ....: S3A.bracket)\n sage: basis\n ((), (1,2,3) + (1,3,2), (2,3) + (1,2) + (1,3))\n sage: center = S3A.submodule(basis,\n ....: category=AlgebrasWithBasis(QQ).Subobjects(),\n ....: already_echelonized=True)\n sage: center\n Free module generated by {0, 1, 2} over Rational Field\n sage: center in Algebras\n True\n sage: center.print_options(prefix=\'c\')\n sage: c = center.basis()\n sage: c[1].lift()\n (1,2,3) + (1,3,2)\n sage: c[0]^2\n c[0]\n sage: e = 1/6 * (c[0]+c[1]+c[2])\n sage: e.is_idempotent()\n True\n\n Of course, this center is best constructed using::\n\n sage: center = S3A.center() # needs sage.combinat sage.groups sage.modules\n\n We can also automatically construct a basis such that\n the lift morphism is (lower) unitriangular::\n\n sage: # needs sage.modules\n sage: R.<a,b> = QQ[]\n sage: C = CombinatorialFreeModule(R, range(3), prefix=\'x\')\n sage: x = C.basis()\n sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]\n sage: Y = C.submodule(gens, unitriangular=True)\n sage: Y.lift.matrix()\n [ 1 0]\n [ 0 1]\n [-1 -1]\n\n We now construct a (finite-dimensional) submodule of an\n infinite dimensional free module::\n\n sage: # needs sage.modules\n sage: C = CombinatorialFreeModule(QQ, ZZ, prefix=\'z\')\n sage: z = C.basis()\n sage: gens = [z[0] - z[1], 2*z[1] - 2*z[2], z[0] - z[2]]\n sage: Y = C.submodule(gens)\n sage: [Y.lift(b) for b in Y.basis()]\n [z[0] - z[2], z[1] - z[2]]\n\n TESTS::\n\n sage: TestSuite(Y).run() # needs sage.modules\n sage: TestSuite(center).run() # needs sage.combinat sage.groups sage.modules\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)
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\n - ``check``, ``already_echelonized`` -- passed down to\n :meth:`ModulesWithBasis.ParentMethods.submodule`\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.modules\n sage: X = CombinatorialFreeModule(QQ, range(3), prefix="x")\n sage: x = X.basis()\n sage: Y = X.quotient_module([x[0] - x[1], x[1] - x[2]],\n ....: already_echelonized=True)\n sage: Y.print_options(prefix=\'y\'); Y\n Free module generated by {2} over Rational Field\n sage: y = Y.basis()\n sage: y[2]\n y[2]\n sage: y[2].lift()\n x[2]\n sage: Y.retract(x[0] + 2*x[1])\n 3*y[2]\n\n sage: # needs sage.modules\n sage: R.<a,b> = QQ[]\n sage: C = CombinatorialFreeModule(R, range(3), prefix=\'x\')\n sage: x = C.basis()\n sage: gens = [x[0] - x[1], 2*x[1] - 2*x[2], x[0] - x[2]]\n sage: Y = C.quotient_module(gens)\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)
return QuotientModuleWithBasis(submodule, category=category)
def tensor(*parents, **kwargs):
'\n Return the tensor product of the parents.\n\n EXAMPLES::\n\n sage: C = AlgebrasWithBasis(QQ)\n sage: A = C.example(); A.rename("A") # needs sage.combinat sage.modules\n sage: A.tensor(A, A) # needs sage.combinat sage.modules\n A # A # A\n sage: A.rename(None) # needs sage.combinat sage.modules\n '
constructor = kwargs.pop('constructor', tensor)
cat = constructor.category_from_parents(parents)
return parents[0].__class__.Tensor(parents, category=cat)
def cardinality(self):
'\n Return the cardinality of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: S = SymmetricGroupAlgebra(QQ, 4)\n sage: S.cardinality()\n +Infinity\n sage: S = SymmetricGroupAlgebra(GF(2), 4) # not tested\n sage: S.cardinality() # not tested\n 16777216\n sage: S.cardinality().factor() # not tested\n 2^24\n\n sage: # needs sage.modules\n sage: E.<x,y> = ExteriorAlgebra(QQ)\n sage: E.cardinality()\n +Infinity\n sage: E.<x,y> = ExteriorAlgebra(GF(3))\n sage: E.cardinality()\n 81\n\n sage: s = SymmetricFunctions(GF(2)).s() # needs sage.combinat sage.modules\n sage: s.cardinality() # needs sage.combinat sage.modules\n +Infinity\n '
from sage.rings.infinity import Infinity
if (self.dimension() == Infinity):
return Infinity
return (self.base_ring().cardinality() ** self.dimension())
def is_finite(self):
'\n Return whether ``self`` is finite.\n\n This is true if and only if ``self.basis().keys()`` and\n ``self.base_ring()`` are both finite.\n\n EXAMPLES::\n\n sage: GroupAlgebra(SymmetricGroup(2), IntegerModRing(10)).is_finite() # needs sage.combinat sage.groups sage.modules\n True\n sage: GroupAlgebra(SymmetricGroup(2)).is_finite() # needs sage.combinat sage.groups sage.modules\n False\n sage: GroupAlgebra(AbelianGroup(1), IntegerModRing(10)).is_finite() # needs sage.groups sage.modules\n False\n '
return (self.base_ring().is_finite() and self.group().is_finite())
def monomial(self, i):
"\n Return the basis element indexed by ``i``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c']) # needs sage.modules\n sage: F.monomial('a') # needs sage.modules\n B['a']\n\n ``F.monomial`` is in fact (almost) a map::\n\n sage: F.monomial # needs sage.modules\n Term map from {'a', 'b', 'c'}\n to Free module generated by {'a', 'b', 'c'} over Rational Field\n "
return self.basis()[i]
def _sum_of_monomials(self, indices):
'\n TESTS::\n\n sage: R.<x,y> = QQ[]\n sage: W = DifferentialWeylAlgebra(R) # needs sage.modules\n sage: W._sum_of_monomials([((1,0), (1,0)), ((0,0), (0,1))]) # needs sage.modules\n dy + x*dx\n '
return self.sum((self.monomial(index) for index in indices))
@lazy_attribute
def sum_of_monomials(self):
"\n Return the sum of the basis elements with indices in\n ``indices``.\n\n INPUT:\n\n - ``indices`` -- a list (or iterable) of indices of basis\n elements\n\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c']) # needs sage.modules\n sage: F.sum_of_monomials(['a', 'b']) # needs sage.modules\n B['a'] + B['b']\n\n sage: F.sum_of_monomials(['a', 'b', 'a']) # needs sage.modules\n 2*B['a'] + B['b']\n\n ``F.sum_of_monomials`` is in fact (almost) a map::\n\n sage: F.sum_of_monomials # needs sage.modules\n A map to Free module generated by {'a', 'b', 'c'} over Rational Field\n "
return PoorManMap(self._sum_of_monomials, codomain=self)
def monomial_or_zero_if_none(self, i):
"\n EXAMPLES::\n\n sage: F = CombinatorialFreeModule(QQ, ['a', 'b', 'c']) # needs sage.modules\n sage: F.monomial_or_zero_if_none('a') # needs sage.modules\n B['a']\n sage: F.monomial_or_zero_if_none(None) # needs sage.modules\n 0\n "
if (i is None):
return self.zero()
return self.monomial(i)
def term(self, index, coeff=None):
'\n Construct a term in ``self``.\n\n INPUT:\n\n - ``index`` -- the index of a basis element\n - ``coeff`` -- an element of the coefficient ring (default: one)\n\n OUTPUT:\n\n ``coeff * B[index]``, where ``B`` is the basis of ``self``.\n\n EXAMPLES::\n\n sage: m = matrix([[0,1], [1,1]]) # needs sage.modules\n sage: J.<a,b,c> = JordanAlgebra(m) # needs sage.combinat sage.modules\n sage: J.term(1, -2) # needs sage.combinat sage.modules\n 0 + (-2, 0)\n\n Design: should this do coercion on the coefficient ring?\n '
if (coeff is None):
coeff = self.base_ring().one()
return (coeff * self.monomial(index))
def sum_of_terms(self, terms):
'\n Construct a sum of terms of ``self``.\n\n INPUT:\n\n - ``terms`` -- a list (or iterable) of pairs ``(index, coeff)``\n\n OUTPUT:\n\n Sum of ``coeff * B[index]`` over all ``(index, coeff)`` in\n ``terms``, where ``B`` is the basis of ``self``.\n\n EXAMPLES::\n\n sage: m = matrix([[0,1], [1,1]]) # needs sage.modules\n sage: J.<a,b,c> = JordanAlgebra(m) # needs sage.combinat sage.modules\n sage: J.sum_of_terms([(0, 2), (2, -3)]) # needs sage.combinat sage.modules\n 2 + (0, -3)\n '
return self.sum((self.term(index, coeff) for (index, coeff) in terms))
def _apply_module_morphism(self, x, on_basis, codomain=False):
'\n Return the image of ``x`` under the module morphism defined by\n extending :func:`on_basis` by linearity.\n\n INPUT:\n\n - ``x`` -- a element of ``self``\n\n - ``on_basis`` -- a function that takes in an object indexing\n a basis element and returns an element of the codomain\n\n - ``codomain`` -- (optional) the codomain of the morphism (by\n default, it is computed using :func:`on_basis`)\n\n If ``codomain`` is not specified, then the function tries to\n compute the codomain of the module morphism by finding the image\n of one of the elements in the support; hence :func:`on_basis`\n should return an element whose parent is the codomain.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: s = SymmetricFunctions(QQ).schur()\n sage: a = s([3]) + s([2,1]) + s([1,1,1])\n sage: b = 2*a\n sage: f = lambda part: Integer(len(part))\n sage: s._apply_module_morphism(a, f) #1+2+3\n 6\n sage: s._apply_module_morphism(b, f) #2*(1+2+3)\n 12\n sage: s._apply_module_morphism(s(0), f)\n 0\n sage: s._apply_module_morphism(s(1), f)\n 0\n sage: s._apply_module_morphism(s(1), lambda part: len(part), ZZ)\n 0\n sage: s._apply_module_morphism(s(1), lambda part: len(part))\n Traceback (most recent call last):\n ...\n ValueError: codomain could not be determined\n '
if (x == self.zero()):
if (not codomain):
from sage.sets.family import Family
B = Family(self.basis())
try:
z = B.first()
except StopIteration:
raise ValueError('codomain could not be determined')
codomain = on_basis(z).parent()
return codomain.zero()
if (not codomain):
keys = x.support()
key = keys[0]
try:
codomain = on_basis(key).parent()
except Exception:
raise ValueError('codomain could not be determined')
if hasattr(codomain, 'linear_combination'):
mc = x.monomial_coefficients(copy=False)
return codomain.linear_combination(((on_basis(key), coeff) for (key, coeff) in mc.items()))
else:
return_sum = codomain.zero()
mc = x.monomial_coefficients(copy=False)
for (key, coeff) in mc.items():
return_sum += (coeff * on_basis(key))
return return_sum
def _apply_module_endomorphism(self, x, on_basis):
'\n This takes in a function ``on_basis`` from the basis indices\n to the elements of ``self``, and applies it linearly to ``x``.\n\n EXAMPLES::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = lambda part: 2 * s(part.conjugate())\n sage: s._apply_module_endomorphism(s([2,1]) + s([1,1,1]), f) # needs sage.combinat sage.modules\n 2*s[2, 1] + 2*s[3]\n '
mc = x.monomial_coefficients(copy=False)
return self.linear_combination(((on_basis(key), coeff) for (key, coeff) in mc.items()))
def dimension(self):
'\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: A.<x,y> = algebras.DifferentialWeyl(QQ) # needs sage.modules\n sage: A.dimension() # needs sage.modules\n +Infinity\n '
try:
return self.basis().cardinality()
except (AttributeError, TypeError):
from sage.rings.integer_ring import ZZ
return ZZ(len(self.basis()))
def _from_dict(self, d, coerce=True, remove_zeros=True):
'\n Construct an element of ``self`` from the dictionary ``d``.\n\n INPUT:\n\n - ``coerce`` -- boolean; coerce the coefficients to the base ring\n - ``remove_zeroes`` -- boolean; remove zeros from the dictionary\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A.<x,y> = algebras.DifferentialWeyl(QQ)\n sage: K = A.basis().keys()\n sage: d = {K[0]: 3, K[12]: -4/3}\n sage: A._from_dict(d)\n -4/3*dx^2 + 3\n\n sage: R.<x,y> = QQ[]\n sage: d = {K[0]: y, K[12]: -4/3} # needs sage.modules\n sage: A._from_dict(d, coerce=False) # needs sage.modules\n -4/3*dx^2 + y\n sage: A._from_dict(d, coerce=True) # needs sage.modules\n Traceback (most recent call last):\n ...\n TypeError: not a constant polynomial\n '
R = self.base_ring()
B = self.basis()
if coerce:
zero = R.zero()
temp = {}
if remove_zeros:
for k in d:
y = R(d[k])
if (y != zero):
temp[k] = y
else:
for k in d:
temp[k] = R(d[k])
return self.sum(((temp[i] * B[i]) for i in temp))
if remove_zeros:
return self.sum(((d[i] * B[i]) for i in d if (d[i] != 0)))
return self.sum(((d[i] * B[i]) for i in d))
def random_element(self, n=2):
"\n Return a 'random' element of ``self``.\n\n INPUT:\n\n - ``n`` -- integer (default: 2); number of summands\n\n ALGORITHM:\n\n Return a sum of ``n`` terms, each of which is formed by\n multiplying a random element of the base ring by a random\n element of the group.\n\n EXAMPLES::\n\n sage: x = DihedralGroup(6).algebra(QQ).random_element() # needs sage.groups sage.modules\n sage: x.parent() is DihedralGroup(6).algebra(QQ) # needs sage.groups sage.modules\n True\n\n Note, this result can depend on the PRNG state in libgap in a way\n that depends on which packages are loaded, so we must re-seed GAP\n to ensure a consistent result for this example::\n\n sage: libgap.set_seed(0) # needs sage.libs.gap\n 0\n sage: m = SU(2, 13).algebra(QQ).random_element(1) # needs sage.groups sage.libs.pari sage.modules\n sage: m.parent() is SU(2, 13).algebra(QQ) # needs sage.groups sage.libs.pari sage.modules\n True\n sage: p = CombinatorialFreeModule(ZZ, Partitions(4)).random_element() # needs sage.combinat sage.modules\n sage: p.parent() is CombinatorialFreeModule(ZZ, Partitions(4)) # needs sage.combinat sage.modules\n True\n\n TESTS:\n\n Ensure that the two issues reported in :trac:`28327` are\n fixed; that we don't rely unnecessarily on being able to\n coerce the base ring's zero into the algebra, and that\n we can find a random element in a trivial module::\n\n sage: class Foo(CombinatorialFreeModule): # needs sage.modules\n ....: def _element_constructor_(self,x):\n ....: if x in self:\n ....: return x\n ....: else:\n ....: raise ValueError\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: C = MagmaticAlgebras(QQ).WithBasis().Unital()\n sage: F = Foo(QQ, tuple(), category=C) # needs sage.modules\n sage: F.random_element() == F.zero() # needs sage.modules\n True\n\n "
indices = self.basis().keys()
a = self.zero()
if (not indices.is_empty()):
for i in range(n):
a += self.term(indices.random_element(), self.base_ring().random_element())
return a
class ElementMethods():
@abstract_method
def monomial_coefficients(self, copy=True):
"\n Return a dictionary whose keys are indices of basis elements\n in the support of ``self`` and whose values are the\n corresponding coefficients.\n\n INPUT:\n\n - ``copy`` -- (default: ``True``) if ``self`` is internally\n represented by a dictionary ``d``, then make a copy of ``d``;\n if ``False``, then this can cause undesired behavior by\n mutating ``d``\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] + 3*B['c']\n sage: d = f.monomial_coefficients()\n sage: d['a']\n 1\n sage: d['c']\n 3\n\n TESTS:\n\n We check that we make a copy of the coefficient dictionary::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] + 3*B['c']\n sage: d = f.monomial_coefficients()\n sage: d['a'] = 5\n sage: f\n B['a'] + 3*B['c']\n "
def __getitem__(self, m):
'\n Return the coefficient of ``m`` in ``self``.\n\n EXAMPLES::\n\n sage: W.<x,y,z> = DifferentialWeylAlgebra(QQ) # needs sage.modules\n sage: x[((0,0,0), (0,0,0))] # needs sage.modules\n 0\n sage: x[((1,0,0), (0,0,0))] # needs sage.modules\n 1\n '
res = self.monomial_coefficients(copy=False).get(m)
if (res is None):
return self.base_ring().zero()
else:
return res
def coefficient(self, m):
'\n Return the coefficient of ``m`` in ``self`` and raise an error\n if ``m`` is not in the basis indexing set.\n\n INPUT:\n\n - ``m`` -- a basis index of the parent of ``self``\n\n OUTPUT:\n\n The ``B[m]``-coordinate of ``self`` with respect to the basis\n ``B``. Here, ``B`` denotes the given basis of the parent of\n ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: s = CombinatorialFreeModule(QQ, Partitions())\n sage: z = s([4]) - 2*s([2,1]) + s([1,1,1]) + s([1])\n sage: z.coefficient([4])\n 1\n sage: z.coefficient([2,1])\n -2\n sage: z.coefficient(Partition([2,1]))\n -2\n sage: z.coefficient([1,2])\n Traceback (most recent call last):\n ...\n AssertionError: [1, 2] should be an element of Partitions\n sage: z.coefficient(Composition([2,1]))\n Traceback (most recent call last):\n ...\n AssertionError: [2, 1] should be an element of Partitions\n\n Test that ``coefficient`` also works for those parents that do\n not have an ``element_class``::\n\n sage: # needs sage.modules sage.rings.padics\n sage: H = pAdicWeightSpace(3)\n sage: F = CombinatorialFreeModule(QQ, H)\n sage: hasattr(H, "element_class")\n False\n sage: h = H.an_element()\n sage: (2*F.monomial(h)).coefficient(h)\n 2\n '
C = self.parent().basis().keys()
assert (m in C), ('%s should be an element of %s' % (m, C))
if (hasattr(C, 'element_class') and (not isinstance(m, C.element_class))):
m = C(m)
return self[m]
def is_zero(self):
"\n Return ``True`` if and only if ``self == 0``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: f.is_zero()\n False\n sage: F.zero().is_zero()\n True\n\n ::\n\n sage: # needs sage.combinat sage.modules\n sage: s = SymmetricFunctions(QQ).schur()\n sage: s([2,1]).is_zero()\n False\n sage: s(0).is_zero()\n True\n sage: (s([2,1]) - s([2,1])).is_zero()\n True\n "
zero = self.parent().base_ring().zero()
return all(((v == zero) for v in self.monomial_coefficients(copy=False).values()))
def __len__(self):
"\n Return the number of basis elements whose coefficients in\n ``self`` are nonzero.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: len(f)\n 2\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) # needs sage.combinat sage.modules\n sage: len(z) # needs sage.combinat sage.modules\n 4\n "
return len(self.support())
def length(self):
"\n Return the number of basis elements whose coefficients in\n ``self`` are nonzero.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: f.length()\n 2\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) # needs sage.combinat sage.modules\n sage: z.length() # needs sage.combinat sage.modules\n 4\n "
return len(self)
def support(self):
"\n Return an iterable of the objects indexing the basis of\n ``self.parent()`` whose corresponding coefficients of\n ``self`` are non-zero.\n\n This method returns these objects in an arbitrary order.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: sorted(f.support())\n ['a', 'c']\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) # needs sage.combinat sage.modules\n sage: sorted(z.support()) # needs sage.combinat sage.modules\n [[1], [1, 1, 1], [2, 1], [4]]\n "
try:
return self._support_view
except AttributeError:
from sage.structure.support_view import SupportView
zero = self.parent().base_ring().zero()
mc = self.monomial_coefficients(copy=False)
support_view = SupportView(mc, zero=zero)
try:
self._support_view = support_view
except AttributeError:
pass
return support_view
def monomials(self):
"\n Return a list of the monomials of ``self`` (in an arbitrary\n order).\n\n The monomials of an element `a` are defined to be the basis\n elements whose corresponding coefficients of `a` are\n non-zero.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] + 2*B['c']\n sage: f.monomials()\n [B['a'], B['c']]\n\n sage: (F.zero()).monomials() # needs sage.modules\n []\n "
P = self.parent()
return [P.monomial(key) for key in self.support()]
def terms(self):
"\n Return a list of the (non-zero) terms of ``self`` (in an\n arbitrary order).\n\n .. SEEALSO:: :meth:`monomials`\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] + 2*B['c']\n sage: f.terms()\n [B['a'], 2*B['c']]\n "
P = self.parent()
zero = P.base_ring().zero()
return [P.term(key, value) for (key, value) in self.monomial_coefficients(copy=False).items() if (value != zero)]
def coefficients(self, sort=True):
"\n Return a list of the (non-zero) coefficients appearing on\n the basis elements in ``self`` (in an arbitrary order).\n\n INPUT:\n\n - ``sort`` -- (default: ``True``) to sort the coefficients\n based upon the default ordering of the indexing set\n\n .. SEEALSO::\n\n :meth:`~sage.categories.finite_dimensional_modules_with_basis.FiniteDimensionalModulesWithBasis.ElementMethods.dense_coefficient_list`\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: f.coefficients()\n [1, -3]\n sage: f = B['c'] - 3*B['a']\n sage: f.coefficients()\n [-3, 1]\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: z = s([4]) + s([2,1]) + s([1,1,1]) + s([1]) # needs sage.combinat sage.modules\n sage: z.coefficients() # needs sage.combinat sage.modules\n [1, 1, 1, 1]\n "
zero = self.parent().base_ring().zero()
mc = self.monomial_coefficients(copy=False)
if (not sort):
return [value for (key, value) in mc.items() if (value != zero)]
v = sorted([(key, value) for (key, value) in mc.items() if (value != zero)])
return [value for (key, value) in v]
def support_of_term(self):
'\n Return the support of ``self``, where ``self`` is a monomial\n (possibly with coefficient).\n\n EXAMPLES::\n\n sage: X = CombinatorialFreeModule(QQ, [1,2,3,4]); X.rename("X") # needs sage.modules\n sage: X.monomial(2).support_of_term() # needs sage.modules\n 2\n sage: X.term(3, 2).support_of_term() # needs sage.modules\n 3\n\n An exception is raised if ``self`` has more than one term::\n\n sage: (X.monomial(2) + X.monomial(3)).support_of_term() # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: B[2] + B[3] is not a single term\n '
if (len(self) == 1):
return self.support()[0]
else:
raise ValueError('{} is not a single term'.format(self))
def leading_support(self, *args, **kwds):
'\n Return the maximal element of the support of ``self``.\n\n Note that this may not be the term which actually appears\n first when ``self`` is printed.\n\n If the default ordering of the basis elements is not what is\n desired, a comparison key, ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3])\n sage: X.rename("X"); x = X.basis()\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + 4*X.monomial(3)\n sage: x.leading_support()\n 3\n sage: def key(x): return -x\n sage: x.leading_support(key=key)\n 1\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.leading_support() # needs sage.combinat sage.modules\n [3]\n '
return max(self.support(), *args, **kwds)
def leading_item(self, *args, **kwds):
'\n Return the pair ``(k, c)`` where\n\n .. MATH::\n\n c \\cdot (\\mbox{the basis element indexed by } k)\n\n is the leading term of ``self``.\n\n Here \'leading term\' means that the corresponding basis element is\n maximal. Note that this may not be the term which actually appears\n first when ``self`` is printed.\n\n If the default term ordering is not what is desired, a\n comparison function, ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + 4*X.monomial(3)\n sage: x.leading_item()\n (3, 4)\n sage: def key(x): return -x\n sage: x.leading_item(key=key)\n (1, 3)\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.leading_item() # needs sage.combinat sage.modules\n ([3], -5)\n '
k = self.leading_support(*args, **kwds)
return (k, self[k])
def leading_monomial(self, *args, **kwds):
'\n Return the leading monomial of ``self``.\n\n This is the monomial whose corresponding basis element is\n maximal. Note that this may not be the term which actually appears\n first when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key, ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.leading_monomial()\n B[3]\n sage: def key(x): return -x\n sage: x.leading_monomial(key=key)\n B[1]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.leading_monomial() # needs sage.combinat sage.modules\n s[3]\n '
return self.parent().monomial(self.leading_support(*args, **kwds))
def leading_coefficient(self, *args, **kwds):
'\n Return the leading coefficient of ``self``.\n\n This is the coefficient of the term whose corresponding basis element is\n maximal. Note that this may not be the term which actually appears\n first when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key, ``key(x,y)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.leading_coefficient()\n 1\n sage: def key(x): return -x\n sage: x.leading_coefficient(key=key)\n 3\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.leading_coefficient() # needs sage.combinat sage.modules\n -5\n '
return self.leading_item(*args, **kwds)[1]
def leading_term(self, *args, **kwds):
'\n Return the leading term of ``self``.\n\n This is the term whose corresponding basis element is\n maximal. Note that this may not be the term which actually appears\n first when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key, ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.leading_term()\n B[3]\n sage: def key(x): return -x\n sage: x.leading_term(key=key)\n 3*B[1]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.leading_term() # needs sage.combinat sage.modules\n -5*s[3]\n '
return self.parent().term(*self.leading_item(*args, **kwds))
def trailing_support(self, *args, **kwds):
'\n Return the minimal element of the support of ``self``. Note\n that this may not be the term which actually appears last when\n ``self`` is printed.\n\n If the default ordering of the basis elements is not what is\n desired, a comparison key, ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X") # needs sage.modules\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + 4*X.monomial(3) # needs sage.modules\n sage: x.trailing_support() # needs sage.modules\n 1\n\n sage: def key(x): return -x\n sage: x.trailing_support(key=key) # needs sage.modules\n 3\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.trailing_support() # needs sage.combinat sage.modules\n [1]\n '
return min(self.support(), *args, **kwds)
def trailing_item(self, *args, **kwds):
'\n Return the pair ``(c, k)`` where ``c*self.parent().monomial(k)``\n is the trailing term of ``self``.\n\n This is the monomial whose corresponding basis element is\n minimal. Note that this may not be the term which actually appears\n last when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.trailing_item()\n (1, 3)\n sage: def key(x): return -x\n sage: x.trailing_item(key=key)\n (3, 1)\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.trailing_item() # needs sage.combinat sage.modules\n ([1], 2)\n '
k = self.trailing_support(*args, **kwds)
return (k, self[k])
def trailing_monomial(self, *args, **kwds):
'\n Return the trailing monomial of ``self``.\n\n This is the monomial whose corresponding basis element is\n minimal. Note that this may not be the term which actually appears\n last when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.trailing_monomial()\n B[1]\n sage: def key(x): return -x\n sage: x.trailing_monomial(key=key)\n B[3]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.trailing_monomial() # needs sage.combinat sage.modules\n s[1]\n '
return self.parent().monomial(self.trailing_support(*args, **kwds))
def trailing_coefficient(self, *args, **kwds):
'\n Return the trailing coefficient of ``self``.\n\n This is the coefficient of the monomial whose corresponding basis element is\n minimal. Note that this may not be the term which actually appears\n last when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.trailing_coefficient()\n 3\n sage: def key(x): return -x\n sage: x.trailing_coefficient(key=key)\n 1\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.trailing_coefficient() # needs sage.combinat sage.modules\n 2\n '
return self.trailing_item(*args, **kwds)[1]
def trailing_term(self, *args, **kwds):
'\n Return the trailing term of ``self``.\n\n This is the term whose corresponding basis element is\n minimal. Note that this may not be the term which actually appears\n last when ``self`` is printed.\n\n If the default term ordering is not\n what is desired, a comparison key ``key(x)``, can be provided.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1, 2, 3]); X.rename("X")\n sage: x = 3*X.monomial(1) + 2*X.monomial(2) + X.monomial(3)\n sage: x.trailing_term()\n 3*B[1]\n sage: def key(x): return -x\n sage: x.trailing_term(key=key)\n B[3]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = 2*s[1] + 3*s[2,1] - 5*s[3] # needs sage.combinat sage.modules\n sage: f.trailing_term() # needs sage.combinat sage.modules\n 2*s[1]\n '
return self.parent().term(*self.trailing_item(*args, **kwds))
def map_coefficients(self, f):
"\n Mapping a function on coefficients.\n\n INPUT:\n\n - ``f`` -- an endofunction on the coefficient ring of the\n free module\n\n Return a new element of ``self.parent()`` obtained by applying the\n function ``f`` to all of the coefficients of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(QQ, ['a','b','c'])\n sage: B = F.basis()\n sage: f = B['a'] - 3*B['c']\n sage: f.map_coefficients(lambda x: x + 5)\n 6*B['a'] + 2*B['c']\n\n Killed coefficients are handled properly::\n\n sage: f.map_coefficients(lambda x: 0) # needs sage.modules\n 0\n sage: list(f.map_coefficients(lambda x: 0)) # needs sage.modules\n []\n\n ::\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: a = s([2,1]) + 2*s([3,2]) # needs sage.combinat sage.modules\n sage: a.map_coefficients(lambda x: x * 2) # needs sage.combinat sage.modules\n 2*s[2, 1] + 4*s[3, 2]\n "
return self.parent().sum_of_terms(((m, f(c)) for (m, c) in self))
def map_support(self, f):
'\n Mapping a function on the support.\n\n INPUT:\n\n - ``f`` -- an endofunction on the indices of the free module\n\n Return a new element of ``self.parent()`` obtained by\n applying the function ``f`` to all of the objects indexing\n the basis elements.\n\n EXAMPLES::\n\n sage: B = CombinatorialFreeModule(ZZ, [-1, 0, 1]) # needs sage.modules\n sage: x = B.an_element(); x # needs sage.modules\n 2*B[-1] + 2*B[0] + 3*B[1]\n sage: x.map_support(lambda i: -i) # needs sage.modules\n 3*B[-1] + 2*B[0] + 2*B[1]\n\n ``f`` needs not be injective::\n\n sage: x.map_support(lambda i: 1) # needs sage.modules\n 7*B[1]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: a = s([2,1]) + 2*s([3,2]) # needs sage.combinat sage.modules\n sage: a.map_support(lambda x: x.conjugate()) # needs sage.combinat sage.modules\n s[2, 1] + 2*s[2, 2, 1]\n\n TESTS::\n\n sage: B.zero() # This actually failed at some point!!! See #8890 # needs sage.modules\n 0\n\n sage: y = B.zero().map_support(lambda i: i/0); y # needs sage.modules\n 0\n sage: y.parent() is B # needs sage.modules\n True\n '
return self.parent().sum_of_terms(((f(m), c) for (m, c) in self))
def map_support_skip_none(self, f):
'\n Mapping a function on the support.\n\n INPUT:\n\n - ``f`` -- an endofunction on the indices of the free module\n\n Returns a new element of ``self.parent()`` obtained by\n applying the function `f` to all of the objects indexing\n the basis elements.\n\n EXAMPLES::\n\n sage: B = CombinatorialFreeModule(ZZ, [-1, 0, 1]) # needs sage.modules\n sage: x = B.an_element(); x # needs sage.modules\n 2*B[-1] + 2*B[0] + 3*B[1]\n sage: x.map_support_skip_none(lambda i: -i if i else None) # needs sage.modules\n 3*B[-1] + 2*B[1]\n\n ``f`` needs not be injective::\n\n sage: x.map_support_skip_none(lambda i: 1 if i else None) # needs sage.modules\n 5*B[1]\n\n TESTS::\n\n sage: y = x.map_support_skip_none(lambda i: None); y # needs sage.modules\n 0\n sage: y.parent() is B # needs sage.modules\n True\n '
return self.parent().sum_of_terms(((fm, c) for (fm, c) in ((f(m), c) for (m, c) in self) if (fm is not None)))
def map_item(self, f):
'\n Mapping a function on items.\n\n INPUT:\n\n - ``f`` -- a function mapping pairs ``(index, coeff)`` to\n other such pairs\n\n Return a new element of ``self.parent()`` obtained by\n applying the function `f` to all items ``(index, coeff)`` of\n ``self``.\n\n EXAMPLES::\n\n sage: B = CombinatorialFreeModule(ZZ, [-1, 0, 1]) # needs sage.modules\n sage: x = B.an_element(); x # needs sage.modules\n 2*B[-1] + 2*B[0] + 3*B[1]\n sage: x.map_item(lambda i, c: (-i, 2*c)) # needs sage.modules\n 6*B[-1] + 4*B[0] + 4*B[1]\n\n ``f`` needs not be injective::\n\n sage: x.map_item(lambda i, c: (1, 2*c)) # needs sage.modules\n 14*B[1]\n\n sage: s = SymmetricFunctions(QQ).schur() # needs sage.combinat sage.modules\n sage: f = lambda m, c: (m.conjugate(), 2 * c)\n sage: a = s([2,1]) + s([1,1,1]) # needs sage.combinat sage.modules\n sage: a.map_item(f) # needs sage.combinat sage.modules\n 2*s[2, 1] + 2*s[3]\n '
return self.parent().sum_of_terms((f(m, c) for (m, c) in self))
def tensor(*elements):
'\n Return the tensor product of its arguments, as an element of\n the tensor product of the parents of those elements.\n\n EXAMPLES::\n\n sage: C = AlgebrasWithBasis(QQ)\n sage: A = C.example() # needs sage.combinat sage.modules\n sage: a, b, c = A.algebra_generators() # needs sage.combinat sage.modules\n sage: a.tensor(b, c) # needs sage.combinat sage.modules\n B[word: a] # B[word: b] # B[word: c]\n\n FIXME: is this a policy that we want to enforce on all parents?\n '
assert all((isinstance(element, Element) for element in elements))
parents = [parent(element) for element in elements]
return tensor(parents)._tensor_of_elements(elements)
class Homsets(HomsetsCategory):
class ParentMethods():
def __call_on_basis__(self, **options):
'\n Construct a morphism in this homset from a function defined\n on the basis.\n\n INPUT:\n\n - ``on_basis`` -- a function from the indices of the\n basis of the domain of ``self`` to the codomain of\n ``self``\n\n This method simply delegates the work to\n :meth:`ModulesWithBasis.ParentMethods.module_morphism`. It\n is used by :meth:`Homset.__call__` to handle the\n ``on_basis`` argument, and will disappear as soon as\n the logic will be generalized.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X")\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4]); Y.rename("Y")\n sage: H = Hom(X, Y)\n sage: x = X.basis()\n sage: def on_basis(i):\n ....: return Y.monomial(i) + 2*Y.monomial(i + 1)\n sage: phi = H(on_basis=on_basis) # indirect doctest\n sage: phi\n Generic morphism:\n From: X\n To: Y\n sage: phi(x[1] + x[3])\n B[1] + 2*B[2] + B[3] + 2*B[4]\n\n Diagonal functions can be constructed using the ``diagonal`` option::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1,2,3,4]); X.rename("X")\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4],\n ....: key="Y"); Y.rename("Y")\n sage: H = Hom(X, Y)\n sage: x = X.basis()\n sage: phi = H(diagonal=lambda x: x^2)\n sage: phi(x[1] + x[2] + x[3])\n B[1] + 4*B[2] + 9*B[3]\n\n TESTS:\n\n As for usual homsets, the argument can be a Python function::\n\n sage: phi = H(lambda x: Y.zero()); phi # needs sage.modules\n Generic morphism:\n From: X\n To: Y\n sage: phi(x[1] + x[3]) # needs sage.modules\n 0\n\n We check that the homset category is properly set up::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X")\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4]); Y.rename("Y")\n sage: H = Hom(X, Y)\n sage: H.zero().category_for()\n Category of finite dimensional vector spaces with basis over Rational Field\n '
return self.domain().module_morphism(codomain=self.codomain(), **options)
class MorphismMethods():
@cached_method
def on_basis(self):
'\n Return the action of this morphism on basis elements.\n\n OUTPUT:\n\n - a function from the indices of the basis of the domain to\n the codomain\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X")\n sage: Y = CombinatorialFreeModule(QQ, [1,2,3,4]); Y.rename("Y")\n sage: H = Hom(X, Y)\n sage: x = X.basis()\n sage: f = H(lambda x: Y.zero()).on_basis()\n sage: f(2)\n 0\n sage: f = lambda i: Y.monomial(i) + 2*Y.monomial(i+1)\n sage: g = H(on_basis=f).on_basis()\n sage: g(2)\n B[2] + 2*B[3]\n sage: g == f\n True\n '
return self._on_basis
def _on_basis(self, i):
'\n Return the image of ``self`` on the basis element indexed by ``i``.\n\n INPUT:\n\n - ``i`` -- the index of an element of the basis of the domain of ``self``\n\n EXAMPLES::\n\n sage: X = CombinatorialFreeModule(QQ, [1,2,3]); X.rename("X") # needs sage.modules\n sage: phi = End(X)(lambda x: 2*x) # needs sage.modules\n sage: phi._on_basis(3) # needs sage.modules\n 2*B[3]\n '
return self(self.domain().monomial(i))
class CartesianProducts(CartesianProductsCategory):
'\n The category of modules with basis constructed by Cartesian products\n of modules with basis.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).CartesianProducts().extra_super_categories()\n [Category of vector spaces with basis over Rational Field]\n sage: ModulesWithBasis(QQ).CartesianProducts().super_categories()\n [Category of Cartesian products of modules with basis over Rational Field,\n Category of vector spaces with basis over Rational Field,\n Category of Cartesian products of vector spaces over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
def _an_element_(self):
"\n EXAMPLES::\n\n sage: # needs sage.combinat sage.groups sage.modules\n sage: A = AlgebrasWithBasis(QQ).example(); A\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c')\n over Rational Field\n sage: B = HopfAlgebrasWithBasis(QQ).example(); B\n An example of Hopf algebra with basis:\n the group algebra of the Dihedral group of order 6\n as a permutation group over Rational Field\n sage: A.an_element()\n B[word: ] + 2*B[word: a] + 3*B[word: b] + B[word: bab]\n sage: B.an_element()\n B[()] + B[(1,2)] + 3*B[(1,2,3)] + 2*B[(1,3,2)]\n sage: ABA = cartesian_product((A, B, A))\n sage: ABA.an_element() # indirect doctest\n 2*B[(0, word: )] + 2*B[(0, word: a)] + 3*B[(0, word: b)]\n "
from .cartesian_product import cartesian_product
return cartesian_product([module.an_element() for module in self.modules])
class TensorProducts(TensorProductsCategory):
'\n The category of modules with basis constructed by tensor product of\n modules with basis.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).TensorProducts().extra_super_categories()\n [Category of vector spaces with basis over Rational Field]\n sage: ModulesWithBasis(QQ).TensorProducts().super_categories()\n [Category of tensor products of modules with basis over Rational Field,\n Category of vector spaces with basis over Rational Field,\n Category of tensor products of vector spaces over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
'\n Implements operations on tensor products of modules with basis.\n '
pass
class ElementMethods():
'\n Implements operations on elements of tensor products of modules\n with basis.\n '
def apply_multilinear_morphism(self, f, codomain=None):
'\n Return the result of applying the morphism induced by ``f``\n to ``self``.\n\n INPUT:\n\n - ``f`` -- a multilinear morphism from the component\n modules of the parent tensor product to any module\n\n - ``codomain`` -- the codomain of ``f`` (optional)\n\n By the universal property of the tensor product, ``f``\n induces a linear morphism from `self.parent()` to the\n target module. Returns the result of applying that\n morphism to ``self``.\n\n The codomain is used for optimizations purposes\n only. If it\'s not provided, it\'s recovered by calling\n ``f`` on the zero input.\n\n EXAMPLES:\n\n We start with simple (admittedly not so interesting)\n examples, with two modules `A` and `B`::\n\n sage: # needs sage.modules\n sage: A = CombinatorialFreeModule(ZZ, [1,2], prefix="A")\n sage: A.rename("A")\n sage: B = CombinatorialFreeModule(ZZ, [3,4], prefix="B")\n sage: B.rename("B")\n\n and `f` the bilinear morphism `(a,b) \\mapsto b \\otimes a`\n from `A \\times B` to `B \\otimes A`::\n\n sage: def f(a,b):\n ....: return tensor([b,a])\n\n Now, calling applying `f` on `a \\otimes b` returns the same\n as `f(a,b)`::\n\n sage: # needs sage.modules\n sage: a = A.monomial(1) + 2 * A.monomial(2); a\n A[1] + 2*A[2]\n sage: b = B.monomial(3) - 2 * B.monomial(4); b\n B[3] - 2*B[4]\n sage: f(a, b)\n B[3] # A[1] + 2*B[3] # A[2] - 2*B[4] # A[1] - 4*B[4] # A[2]\n sage: tensor([a, b]).apply_multilinear_morphism(f)\n B[3] # A[1] + 2*B[3] # A[2] - 2*B[4] # A[1] - 4*B[4] # A[2]\n\n `f` may be a bilinear morphism to any module over the\n base ring of `A` and `B`. Here the codomain is `\\ZZ`::\n\n sage: def f(a, b):\n ....: return sum(a.coefficients(), 0) * sum(b.coefficients(), 0)\n sage: f(a, b) # needs sage.modules\n -3\n sage: tensor([a, b]).apply_multilinear_morphism(f) # needs sage.modules\n -3\n\n Mind the `0` in the sums above; otherwise `f` would\n not return `0` in `\\ZZ`::\n\n sage: def f(a,b):\n ....: return sum(a.coefficients()) * sum(b.coefficients())\n sage: type(f(A.zero(), B.zero())) # needs sage.modules\n <... \'int\'>\n\n Which would be wrong and break this method::\n\n sage: tensor([a, b]).apply_multilinear_morphism(f) # needs sage.modules\n Traceback (most recent call last):\n ...\n AttributeError: \'int\' object has no attribute \'parent\'...\n\n Here we consider an example where the codomain is a\n module with basis with a different base ring::\n\n sage: # needs sage.modules\n sage: C = CombinatorialFreeModule(QQ, [(1,3),(2,4)], prefix="C")\n sage: C.rename("C")\n sage: def f(a, b):\n ....: return C.sum_of_terms([((1,3), QQ(a[1]*b[3])),\n ....: ((2,4), QQ(a[2]*b[4]))])\n sage: f(a,b)\n C[(1, 3)] - 4*C[(2, 4)]\n sage: tensor([a, b]).apply_multilinear_morphism(f)\n C[(1, 3)] - 4*C[(2, 4)]\n\n We conclude with a real life application, where we\n check that the antipode of the Hopf algebra of\n Symmetric functions on the Schur basis satisfies its\n defining formula::\n\n sage: # needs lrcalc_python sage.combinat sage.modules\n sage: Sym = SymmetricFunctions(QQ)\n sage: s = Sym.schur()\n sage: def f(a, b): return a * b.antipode()\n sage: x = 4 * s.an_element(); x\n 8*s[] + 8*s[1] + 12*s[2]\n sage: x.coproduct().apply_multilinear_morphism(f)\n 8*s[]\n sage: x.coproduct().apply_multilinear_morphism(f) == x.counit()\n True\n\n We recover the constant term of `x`, as desired.\n\n .. TODO::\n\n Extract a method to linearize a multilinear\n morphism, and delegate the work there.\n '
K = self.parent().base_ring()
modules = self.parent()._sets
if (codomain is None):
try:
codomain = f.codomain()
except AttributeError:
codomain = f(*[module.zero() for module in modules]).parent()
if (codomain in ModulesWithBasis(K)):
return codomain.linear_combination(((f(*[module.monomial(t) for (module, t) in zip(modules, m)]), c) for (m, c) in self))
else:
return sum(((c * f(*[module.monomial(t) for (module, t) in zip(modules, m)])) for (m, c) in self), codomain.zero())
class DualObjects(DualObjectsCategory):
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: ModulesWithBasis(ZZ).DualObjects().extra_super_categories()\n [Category of modules over Integer Ring]\n sage: ModulesWithBasis(QQ).DualObjects().super_categories()\n [Category of duals of vector spaces over Rational Field,\n Category of duals of modules with basis over Rational Field]\n '
return [Modules(self.base_category().base_ring())]
|
def MonoidAlgebras(base_ring):
'\n The category of monoid algebras over ``base_ring``.\n\n EXAMPLES::\n\n sage: C = MonoidAlgebras(QQ); C\n Category of monoid algebras over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of bialgebras with basis over Rational Field,\n Category of semigroup algebras over Rational Field,\n Category of unital magma algebras over Rational Field]\n\n This is just an alias for::\n\n sage: C is Monoids().Algebras(QQ)\n True\n\n TESTS::\n\n sage: TestSuite(MonoidAlgebras(ZZ)).run()\n '
from sage.categories.monoids import Monoids
return Monoids().Algebras(base_ring)
|
class Monoids(CategoryWithAxiom):
'\n The category of (multiplicative) monoids.\n\n A *monoid* is a unital :class:`semigroup <Semigroups>`, that is a\n set endowed with a multiplicative binary operation `*` which is\n associative and admits a unit (see :wikipedia:`Monoid`).\n\n EXAMPLES::\n\n sage: Monoids()\n Category of monoids\n sage: Monoids().super_categories()\n [Category of semigroups, Category of unital magmas]\n sage: Monoids().all_super_categories()\n [Category of monoids,\n Category of semigroups,\n Category of unital magmas, Category of magmas,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n sage: Monoids().axioms()\n frozenset({\'Associative\', \'Unital\'})\n sage: Semigroups().Unital()\n Category of monoids\n\n sage: Monoids().example()\n An example of a monoid: the free monoid generated by (\'a\', \'b\', \'c\', \'d\')\n\n TESTS::\n\n sage: C = Monoids()\n sage: TestSuite(C).run()\n\n ::\n\n sage: S = Monoids().example()\n sage: x = S("aa")\n sage: x^0, x^1, x^2, x^3, x^4, x^5\n (\'\', \'aa\', \'aaaa\', \'aaaaaa\', \'aaaaaaaa\', \'aaaaaaaaaa\')\n\n Check for :trac:`31212`::\n\n sage: R = IntegerModRing(15)\n sage: R.submonoid([R.one()]).list() # needs sage.combinat\n [1]\n '
_base_category_class_and_axiom = (Semigroups, 'Unital')
Finite = LazyImport('sage.categories.finite_monoids', 'FiniteMonoids', at_startup=True)
Inverse = LazyImport('sage.categories.groups', 'Groups', at_startup=True)
@staticmethod
def free(index_set=None, names=None, **kwds):
"\n Return a free monoid on `n` generators or with the generators\n indexed by a set `I`.\n\n A free monoid is constructed by specifying either:\n\n - the number of generators and/or the names of the generators\n - the indexing set for the generators\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: Monoids.free(index_set=ZZ) # needs sage.combinat\n Free monoid indexed by Integer Ring\n sage: Monoids().free(ZZ) # needs sage.combinat\n Free monoid indexed by Integer Ring\n sage: F.<x,y,z> = Monoids().free(); F # needs sage.combinat\n Free monoid indexed by {'x', 'y', 'z'}\n "
if (names is not None):
if isinstance(names, str):
from sage.rings.integer_ring import ZZ
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 = names
from sage.monoids.indexed_free_monoid import IndexedFreeMonoid
return IndexedFreeMonoid(index_set, names=names, **kwds)
class ParentMethods():
def semigroup_generators(self):
'\n Return the generators of ``self`` as a semigroup.\n\n The generators of a monoid `M` as a semigroup are the generators\n of `M` as a monoid and the unit.\n\n EXAMPLES::\n\n sage: M = Monoids().free([1,2,3]) # needs sage.combinat\n sage: M.semigroup_generators() # needs sage.combinat\n Family (1, F[1], F[2], F[3])\n '
G = self.monoid_generators()
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
if (G not in FiniteEnumeratedSets()):
raise NotImplementedError('currently only implemented for finitely generated monoids')
from sage.sets.family import Family
return Family(((self.one(),) + tuple(G)))
def prod(self, args):
"\n n-ary product of elements of ``self``.\n\n INPUT:\n\n - ``args`` -- a list (or iterable) of elements of ``self``\n\n Returns the product of the elements in ``args``, as an element of\n ``self``.\n\n EXAMPLES::\n\n sage: S = Monoids().example()\n sage: S.prod([S('a'), S('b')])\n 'ab'\n "
from sage.misc.misc_c import prod
return prod(args, self.one())
def _test_prod(self, **options):
"\n Run basic tests for the product method :meth:`prod` of ``self``.\n\n See the documentation for :class:`TestSuite` for information on\n further options.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: S = Monoids().example()\n sage: S._test_prod()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: S._test_prod(elements = (S('a'), S('b')))\n "
tester = self._tester(**options)
tester.assertEqual(self.prod([]), self.one())
for x in tester.some_elements():
tester.assertEqual(self.prod([x]), x)
tester.assertEqual(self.prod([x, x]), (x ** 2))
tester.assertEqual(self.prod([x, x, x]), (x ** 3))
def submonoid(self, generators, category=None):
'\n Return the multiplicative submonoid generated by ``generators``.\n\n INPUT:\n\n - ``generators`` -- a finite family of elements of\n ``self``, or a list, iterable, ... that can be converted\n into one (see :class:`Family`).\n\n - ``category`` -- a category\n\n This is a shorthand for\n :meth:`Semigroups.ParentMethods.subsemigroup` that\n specifies that this is a submonoid, and in particular that\n the unit is ``self.one()``.\n\n EXAMPLES::\n\n sage: R = IntegerModRing(15)\n sage: M = R.submonoid([R(3), R(5)]); M # needs sage.combinat\n A submonoid of (Ring of integers modulo 15) with 2 generators\n sage: M.list() # needs sage.combinat\n [1, 3, 5, 9, 0, 10, 12, 6]\n\n Not the presence of the unit, unlike in::\n\n sage: S = R.subsemigroup([R(3), R(5)]); S # needs sage.combinat\n A subsemigroup of (Ring of integers modulo 15) with 2 generators\n sage: S.list() # needs sage.combinat\n [3, 5, 9, 0, 10, 12, 6]\n\n This method is really a shorthand for subsemigroup::\n\n sage: M2 = R.subsemigroup([R(3), R(5)], one=R.one()) # needs sage.combinat\n sage: M2 is M # needs sage.combinat\n True\n '
return self.subsemigroup(generators, one=self.one())
class ElementMethods():
def _div_(left, right):
"\n Default implementation of division, multiplying (on the right) by the inverse.\n\n INPUT:\n\n - ``left``, ``right`` -- two elements of the same unital monoid\n\n .. SEEALSO:: :meth:`__div__`\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: G = FreeGroup(2)\n sage: x0, x1 = G.group_generators()\n sage: c1 = cartesian_product([x0, x1])\n sage: c2 = cartesian_product([x1, x0])\n sage: c1._div_(c2)\n (x0*x1^-1, x1*x0^-1)\n\n With this default implementation, division will fail as\n soon as ``right`` is not invertible, even if ``right``\n actually divides ``left``::\n\n sage: x = cartesian_product([2, 0])\n sage: y = cartesian_product([1, 1])\n sage: x / y\n (2, 0)\n sage: y / x\n Traceback (most recent call last):\n ...\n ZeroDivisionError: rational division by zero\n\n TESTS::\n\n sage: c1._div_.__module__ # needs sage.groups\n 'sage.categories.monoids'\n "
return (left * (~ right))
def is_one(self):
'\n Return whether ``self`` is the one of the monoid.\n\n The default implementation is to compare with ``self.one()``.\n\n TESTS::\n\n sage: S = Monoids().example()\n sage: S.one().is_one()\n True\n sage: S("aa").is_one()\n False\n '
return (self == self.parent().one())
def _pow_int(self, n):
'\n Return ``self`` to the `n^{th}` power.\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n EXAMPLES::\n\n sage: S = Monoids().example()\n sage: S("a") ^ 5\n \'aaaaa\'\n '
return generic_power(self, n)
def _pow_naive(self, n):
'\n Return ``self`` to the `n^{th}` power (naive implementation).\n\n INPUT:\n\n - ``n`` -- a nonnegative integer\n\n This naive implementation does not use binary\n exponentiation; there are cases where this is actually\n faster due to size explosion.\n\n EXAMPLES::\n\n sage: S = Monoids().example()\n sage: x = S("aa")\n sage: [x._pow_naive(i) for i in range(6)]\n [\'\', \'aa\', \'aaaa\', \'aaaaaa\', \'aaaaaaaa\', \'aaaaaaaaaa\']\n '
if (not n):
return self.parent().one()
result = self
for i in range((n - 1)):
result *= self
return result
def powers(self, n):
'\n Return the list `[x^0, x^1, \\ldots, x^{n-1}]`.\n\n EXAMPLES::\n\n sage: A = Matrix([[1, 1], [-1, 0]]) # needs sage.modules\n sage: A.powers(6) # needs sage.modules\n [\n [1 0] [ 1 1] [ 0 1] [-1 0] [-1 -1] [ 0 -1]\n [0 1], [-1 0], [-1 -1], [ 0 -1], [ 1 0], [ 1 1]\n ]\n '
if (n < 0):
raise ValueError('negative number of powers requested')
elif (n == 0):
return []
x = self.parent().one()
l = [x]
for i in range((n - 1)):
x = (x * self)
l.append(x)
return l
def __invert__(self):
'\n Return the multiplicative inverse of ``self``.\n\n There is no default implementation, to avoid conflict\n with the default implementation of ``_div_``.\n\n EXAMPLES::\n\n sage: A = Matrix([[1, 0], [1, 1]]) # needs sage.modules\n sage: ~A # needs sage.modules\n [ 1 0]\n [-1 1]\n '
raise NotImplementedError('please implement __invert__')
def inverse(self):
'\n Return the multiplicative inverse of ``self``.\n\n This is an alias for inversion, which can also be invoked\n by ``~x`` for an element ``x``.\n\n Nota Bene: Element classes should implement ``__invert__`` only.\n\n EXAMPLES::\n\n sage: AA(sqrt(~2)).inverse() # needs sage.rings.number_field sage.symbolic\n 1.414213562373095?\n '
return self.__invert__()
class Commutative(CategoryWithAxiom):
'\n Category of commutative (abelian) monoids.\n\n A monoid `M` is *commutative* if `xy = yx` for all `x,y \\in M`.\n '
@staticmethod
def free(index_set=None, names=None, **kwds):
"\n Return a free abelian monoid on `n` generators or with\n the generators indexed by a set `I`.\n\n A free monoid is constructed by specifying either:\n\n - the number of generators and/or the names of the generators, or\n - the indexing set for the generators.\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: Monoids.Commutative.free(index_set=ZZ) # needs sage.combinat\n Free abelian monoid indexed by Integer Ring\n sage: Monoids().Commutative().free(ZZ) # needs sage.combinat\n Free abelian monoid indexed by Integer Ring\n sage: F.<x,y,z> = Monoids().Commutative().free(); F # needs sage.combinat\n Free abelian monoid indexed by {'x', 'y', 'z'}\n "
if (names is not None):
if isinstance(names, str):
from sage.rings.integer_ring import ZZ
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 = names
from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
return IndexedFreeAbelianMonoid(index_set, names=names, **kwds)
class WithRealizations(WithRealizationsCategory):
class ParentMethods():
def one(self):
"\n Return the unit of this monoid.\n\n This default implementation returns the unit of the\n realization of ``self`` given by\n :meth:`~Sets.WithRealizations.ParentMethods.a_realization`.\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.one.__module__ # needs sage.modules\n 'sage.categories.monoids'\n sage: A.one() # needs sage.modules\n F[{}]\n\n TESTS::\n\n sage: A.one() is A.a_realization().one() # needs sage.modules\n True\n sage: A._test_one() # needs sage.modules\n "
return self.a_realization().one()
class Subquotients(SubquotientsCategory):
class ParentMethods():
def one(self):
'\n Returns the multiplicative unit of this monoid,\n obtained by retracting that of the ambient monoid.\n\n EXAMPLES::\n\n sage: S = Monoids().Subquotients().example() # todo: not implemented\n sage: S.one() # todo: not implemented\n '
return self.retract(self.ambient().one())
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n The algebra of a monoid is a bialgebra and a monoid.\n\n EXAMPLES::\n\n sage: C = Monoids().Algebras(QQ)\n sage: C.extra_super_categories()\n [Category of bialgebras over Rational Field,\n Category of monoids]\n sage: Monoids().Algebras(QQ).super_categories()\n [Category of bialgebras with basis over Rational Field,\n Category of semigroup algebras over Rational Field,\n Category of unital magma algebras over Rational Field]\n '
from sage.categories.bialgebras import Bialgebras
return [Bialgebras(self.base_ring()), Monoids()]
class ParentMethods():
@cached_method
def one_basis(self):
"\n Return the unit of the monoid, which indexes the unit of\n this algebra, as per\n :meth:`AlgebrasWithBasis.ParentMethods.one_basis()\n <sage.categories.algebras_with_basis.AlgebrasWithBasis.ParentMethods.one_basis>`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: A = Monoids().example().algebra(ZZ)\n sage: A.one_basis()\n ''\n sage: A.one()\n B['']\n sage: A(3)\n 3*B['']\n "
return self.basis().keys().one()
@cached_method
def algebra_generators(self):
"\n Return generators for this algebra.\n\n For a monoid algebra, the algebra generators are built\n from the monoid generators if available and from the\n semigroup generators otherwise.\n\n .. SEEALSO::\n\n - :meth:`Semigroups.Algebras.ParentMethods.algebra_generators`\n - :meth:`MagmaticAlgebras.ParentMethods.algebra_generators()\n <.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators>`.\n\n EXAMPLES::\n\n sage: M = Monoids().example(); M\n An example of a monoid:\n 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: M.algebra(ZZ).algebra_generators() # needs sage.modules\n Finite family {'a': B['a'], 'b': B['b'], 'c': B['c'], 'd': B['d']}\n\n sage: Z12 = Monoids().Finite().example(); Z12\n An example of a finite multiplicative monoid:\n the integers modulo 12\n sage: Z12.monoid_generators()\n Traceback (most recent call last):\n ...\n AttributeError: 'IntegerModMonoid_with_category' object\n has no attribute 'monoid_generators'...\n sage: Z12.semigroup_generators()\n Family (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)\n sage: Z12.algebra(QQ).algebra_generators() # needs sage.modules\n Family (B[0], B[1], B[2], B[3], B[4], B[5], B[6], B[7], B[8], B[9], B[10], B[11])\n\n\n sage: A10 = AlternatingGroup(10) # needs sage.groups\n sage: GroupAlgebras(QQ).example(A10).algebra_generators() # needs sage.groups sage.modules\n Family ((8,9,10), (1,2,3,4,5,6,7,8,9))\n\n sage: A = DihedralGroup(3).algebra(QQ); A # needs sage.groups sage.modules\n Algebra of Dihedral group of order 6 as a permutation group\n over Rational Field\n sage: A.algebra_generators() # needs sage.groups sage.modules\n Family ((1,2,3), (1,3))\n "
monoid = self.basis().keys()
try:
generators = monoid.monoid_generators()
except AttributeError:
generators = monoid.semigroup_generators()
return generators.map(self.monomial)
class ElementMethods():
def is_central(self):
'\n Return whether the element ``self`` is central.\n\n EXAMPLES::\n\n sage: SG4 = SymmetricGroupAlgebra(ZZ,4) # needs sage.groups sage.modules\n sage: SG4(1).is_central() # needs sage.groups sage.modules\n True\n sage: SG4(Permutation([1,3,2,4])).is_central() # needs sage.groups sage.modules\n False\n\n sage: A = GroupAlgebras(QQ).example(); A # needs sage.groups sage.modules\n Algebra of Dihedral group of order 8\n as a permutation group over Rational Field\n sage: sum(A.basis()).is_central() # needs sage.groups sage.modules\n True\n '
return all((((i * self) == (self * i)) for i in self.parent().algebra_generators()))
class CartesianProducts(CartesianProductsCategory):
'\n The category of monoids constructed as Cartesian products of monoids.\n\n This construction gives the direct product of monoids. See\n :wikipedia:`Direct_product` for more information.\n '
def extra_super_categories(self):
'\n A Cartesian product of monoids is endowed with a natural\n group structure.\n\n EXAMPLES::\n\n sage: C = Monoids().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of monoids]\n sage: sorted(C.super_categories(), key=str)\n [Category of Cartesian products of semigroups,\n Category of Cartesian products of unital magmas,\n Category of monoids]\n '
return [self.base_category()]
class ParentMethods():
@cached_method
def monoid_generators(self):
"\n Return the generators of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: M = Monoids.free([1, 2, 3])\n sage: N = Monoids.free(['a', 'b'])\n sage: C = cartesian_product([M, N])\n sage: C.monoid_generators()\n Family ((F[1], 1), (F[2], 1), (F[3], 1),\n (1, F['a']), (1, F['b']))\n\n An example with an infinitely generated group (a better output\n is needed)::\n\n sage: N = Monoids.free(ZZ) # needs sage.combinat\n sage: C = cartesian_product([M, N]) # needs sage.combinat sage.groups\n sage: C.monoid_generators() # needs sage.combinat sage.groups\n Lazy family (gen(i))_{i in The Cartesian product of (...)}\n "
F = self.cartesian_factors()
ids = tuple((M.one() for M 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((((M.monoid_generators() in cat) or isinstance(M.monoid_generators(), (tuple, list))) for M in F)):
ret = [lift(i, gen) for (i, M) in enumerate(F) for gen in M.monoid_generators()]
return Family(ret)
from sage.categories.cartesian_product import cartesian_product
gens_prod = cartesian_product([Family(M.monoid_generators(), (lambda g: (i, g))) for (i, M) in enumerate(F)])
return Family(gens_prod, lift, name='gen')
class ElementMethods():
def multiplicative_order(self):
'\n Return the multiplicative order of this element.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: G1 = SymmetricGroup(3)\n sage: G2 = SL(2, 3)\n sage: G = cartesian_product([G1, G2])\n sage: G((G1.gen(0), G2.gen(1))).multiplicative_order()\n 12\n '
from sage.rings.infinity import Infinity
orders = [x.multiplicative_order() for x in self.cartesian_factors()]
if any(((o is Infinity) for o in orders)):
return Infinity
else:
from sage.arith.functions import LCM_list
return LCM_list(orders)
def __invert__(self):
'\n Return the inverse.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: a1 = Permutation((4,2,1,3))\n sage: a2 = SL(2, 3)([2,1,1,1])\n sage: h = cartesian_product([a1, a2])\n sage: ~h\n ([2, 4, 1, 3], [1 2]\n [2 2])\n '
build = self.parent()._cartesian_product_of_elements
return build([x.__invert__() for x in self.cartesian_factors()])
|
class NumberFields(Category_singleton):
"\n The category of number fields.\n\n EXAMPLES:\n\n We create the category of number fields::\n\n sage: C = NumberFields()\n sage: C\n Category of number fields\n\n By definition, it is infinite::\n\n sage: NumberFields().Infinite() is NumberFields()\n True\n\n Notice that the rational numbers `\\QQ` *are* considered as\n an object in this category::\n\n sage: RationalField() in C\n True\n\n However, we can define a degree 1 extension of `\\QQ`, which is of\n course also in this category::\n\n sage: x = PolynomialRing(RationalField(), 'x').gen()\n sage: K = NumberField(x - 1, 'a'); K # needs sage.rings.number_field\n Number Field in a with defining polynomial x - 1\n sage: K in C # needs sage.rings.number_field\n True\n\n Number fields all lie in this category, regardless of the name\n of the variable::\n\n sage: K = NumberField(x^2 + 1, 'a') # needs sage.rings.number_field\n sage: K in C # needs sage.rings.number_field\n True\n\n TESTS::\n\n sage: TestSuite(NumberFields()).run()\n "
def super_categories(self):
'\n EXAMPLES::\n\n sage: NumberFields().super_categories()\n [Category of infinite fields]\n '
return [Fields().Infinite()]
def __contains__(self, x):
"\n Return ``True`` if ``x`` is a number field.\n\n EXAMPLES::\n\n sage: x = polygen(QQ, 'x')\n sage: NumberField(x^2 + 1, 'a') in NumberFields() # needs sage.rings.number_field\n True\n sage: QuadraticField(-97, 'theta') in NumberFields() # needs sage.rings.number_field\n True\n sage: CyclotomicField(97) in NumberFields() # needs sage.rings.number_field\n True\n\n Note that the rational numbers QQ are a number field::\n\n sage: QQ in NumberFields()\n True\n sage: ZZ in NumberFields()\n False\n "
from sage.rings.number_field.number_field_base import NumberField
return isinstance(x, NumberField)
def _call_(self, x):
"\n Construct an object in this category from the data in ``x``,\n or raise a :class:`TypeError`.\n\n EXAMPLES::\n\n sage: C = NumberFields()\n sage: x = polygen(QQ, 'x')\n\n sage: C(QQ)\n Rational Field\n\n sage: C(NumberField(x^2 + 1, 'a')) # needs sage.rings.number_field\n Number Field in a with defining polynomial x^2 + 1\n\n sage: C(UnitGroup(NumberField(x^2 + 1, 'a'))) # indirect doctest # needs sage.rings.number_field\n Number Field in a with defining polynomial x^2 + 1\n\n sage: C(ZZ)\n Traceback (most recent call last):\n ...\n TypeError: unable to canonically associate a number field to Integer Ring\n "
try:
return x.number_field()
except AttributeError:
raise TypeError(('unable to canonically associate a number field to %s' % x))
class ParentMethods():
def zeta_function(self, prec=53, max_imaginary_part=0, max_asymp_coeffs=40, algorithm='pari'):
'\n Return the Dedekind zeta function of this number field.\n\n Actually, this returns an interface for computing with the\n Dedekind zeta function `\\zeta_F(s)` of the number field `F`.\n\n INPUT:\n\n - ``prec`` -- optional integer (default 53) bits precision\n\n - ``max_imaginary_part`` -- optional real number (default 0)\n\n - ``max_asymp_coeffs`` -- optional integer (default 40)\n\n - ``algorithm`` -- optional (default "pari") either "gp" or "pari"\n\n OUTPUT: The zeta function of this number field.\n\n If algorithm is "gp", this returns an interface to Tim\n Dokchitser\'s gp script for computing with L-functions.\n\n If algorithm is "pari", this returns instead an interface to Pari\'s\n own general implementation of L-functions.\n\n EXAMPLES::\n\n sage: K.<a> = NumberField(ZZ[\'x\'].0^2 + ZZ[\'x\'].0 - 1) # needs sage.rings.number_field\n sage: Z = K.zeta_function(); Z # needs sage.rings.number_field sage.symbolic\n PARI zeta function associated to Number Field in a\n with defining polynomial x^2 + x - 1\n sage: Z(-1) # needs sage.rings.number_field sage.symbolic\n 0.0333333333333333\n\n sage: x = polygen(QQ, \'x\')\n sage: L.<a, b, c> = NumberField([x^2 - 5, x^2 + 3, x^2 + 1]) # needs sage.rings.number_field\n sage: Z = L.zeta_function() # needs sage.rings.number_field sage.symbolic\n sage: Z(5) # needs sage.rings.number_field sage.symbolic\n 1.00199015670185\n\n Using the algorithm "pari"::\n\n sage: K.<a> = NumberField(ZZ[\'x\'].0^2 + ZZ[\'x\'].0 - 1) # needs sage.rings.number_field\n sage: Z = K.zeta_function(algorithm="pari") # needs sage.rings.number_field sage.symbolic\n sage: Z(-1) # needs sage.rings.number_field sage.symbolic\n 0.0333333333333333\n\n sage: x = polygen(QQ, \'x\')\n sage: L.<a, b, c> = NumberField([x^2 - 5, x^2 + 3, x^2 + 1]) # needs sage.rings.number_field\n sage: Z = L.zeta_function(algorithm="pari") # needs sage.rings.number_field sage.symbolic\n sage: Z(5) # needs sage.rings.number_field sage.symbolic\n 1.00199015670185\n\n TESTS::\n\n sage: QQ.zeta_function() # needs sage.symbolic\n PARI zeta function associated to Rational Field\n '
if (algorithm == 'gp'):
from sage.lfunctions.all import Dokchitser
(r1, r2) = self.signature()
zero = [0]
one = [1]
Z = Dokchitser(conductor=abs(self.absolute_discriminant()), gammaV=(((r1 + r2) * zero) + (r2 * one)), weight=1, eps=1, poles=[1], prec=prec)
s = ('nf = nfinit(%s);' % self.absolute_polynomial())
s += 'dzk = dirzetak(nf,cflength());'
Z.init_coeffs('dzk[k]', pari_precode=s, max_imaginary_part=max_imaginary_part, max_asymp_coeffs=max_asymp_coeffs)
Z.check_functional_equation()
Z.rename(('Dokchitser Zeta function associated to %s' % self))
return Z
if (algorithm == 'pari'):
from sage.lfunctions.pari import lfun_number_field, LFunction
Z = LFunction(lfun_number_field(self), prec=prec)
Z.rename(('PARI zeta function associated to %s' % self))
return Z
raise ValueError('algorithm must be "gp" or "pari"')
def _test_absolute_disc(self, **options):
"\n Run basic tests for the method :meth:`absolute_discriminant` of ``self``.\n\n See the documentation for :class:`TestSuite` for information on\n further options.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES::\n\n sage: x = polygen(ZZ, 'x')\n sage: S = NumberField(x**3 - x - 1, 'a') # needs sage.rings.number_field\n sage: S._test_absolute_disc() # needs sage.rings.number_field\n "
from sage.rings.integer import Integer
tester = self._tester(**options)
tester.assertIsInstance(self.absolute_discriminant(), Integer)
class ElementMethods():
pass
|
class Objects(Category_singleton):
'\n The category of all objects\n the basic category\n\n EXAMPLES::\n\n sage: Objects()\n Category of objects\n sage: Objects().super_categories()\n []\n\n TESTS::\n\n sage: TestSuite(Objects()).run()\n '
def additional_structure(self):
'\n Return ``None``\n\n Indeed, by convention, the category of objects defines no\n additional structure.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n EXAMPLES::\n\n sage: Objects().additional_structure()\n '
return None
def super_categories(self):
'\n EXAMPLES::\n\n sage: Objects().super_categories()\n []\n '
return []
def __contains__(self, x):
'\n Anything is in the category of objects.\n\n EXAMPLES::\n\n sage: int(1) in Objects()\n True\n sage: ZZ in Objects()\n True\n sage: 2/3 in Objects()\n True\n '
return True
class SubcategoryMethods():
@cached_method
def Homsets(self):
"\n Return the category of homsets between objects of this category.\n\n EXAMPLES::\n\n sage: Sets().Homsets()\n Category of homsets of sets\n\n sage: Rings().Homsets()\n Category of homsets of unital magmas and additive unital additive magmas\n\n .. NOTE:: Background\n\n Information, code, documentation, and tests about the\n category of homsets of a category ``Cs`` should go in\n the nested class ``Cs.Homsets``. They will then be\n made available to homsets of any subcategory of\n ``Cs``.\n\n Assume, for example, that homsets of ``Cs`` are ``Cs``\n themselves. This information can be implemented in the\n method ``Cs.Homsets.extra_super_categories`` to make\n ``Cs.Homsets()`` a subcategory of ``Cs()``.\n\n Methods about the homsets themselves should go in the\n nested class ``Cs.Homsets.ParentMethods``.\n\n Methods about the morphisms can go in the nested class\n ``Cs.Homsets.ElementMethods``. However it's generally\n preferable to put them in the nested class\n ``Cs.MorphimMethods``; indeed they will then apply to\n morphisms of all subcategories of ``Cs``, and not only\n full subcategories.\n\n\n .. SEEALSO::\n\n :class:`~.covariant_functorial_construction.FunctorialConstruction`\n\n .. TODO::\n\n - Design a mechanism to specify that an axiom is\n compatible with taking subsets. Examples:\n ``Finite``, ``Associative``, ``Commutative`` (when\n meaningful), but not ``Infinite`` nor ``Unital``.\n\n - Design a mechanism to specify that, when `B` is a\n subcategory of `A`, a `B`-homset is a subset of the\n corresponding `A` homset. And use it to recover all\n the relevant axioms from homsets in super categories.\n\n - For instances of redundant code due to this missing\n feature, see:\n\n - :meth:`AdditiveMonoids.Homsets.extra_super_categories`\n - :meth:`HomsetsCategory.extra_super_categories`\n (slightly different nature)\n - plus plenty of spots where this is not implemented.\n "
return HomsetsCategory.category_of(self)
@cached_method
def Endsets(self):
'\n Return the category of endsets between objects of this category.\n\n EXAMPLES::\n\n sage: Sets().Endsets()\n Category of endsets of sets\n\n sage: Rings().Endsets()\n Category of endsets of unital magmas and additive unital additive magmas\n\n .. SEEALSO::\n\n - :meth:`Homsets`\n '
return self.Homsets()._with_axiom('Endset')
class ParentMethods():
'\n Methods for all category objects\n '
|
class PartiallyOrderedMonoids(Category_singleton):
'\n The category of partially ordered monoids, that is partially ordered sets\n which are also monoids, and such that multiplication preserves the\n ordering: `x \\leq y` implies `x*z < y*z` and `z*x < z*y`.\n\n See :wikipedia:`Ordered_monoid`\n\n EXAMPLES::\n\n sage: PartiallyOrderedMonoids()\n Category of partially ordered monoids\n sage: PartiallyOrderedMonoids().super_categories()\n [Category of posets, Category of monoids]\n\n TESTS::\n\n sage: TestSuite(PartiallyOrderedMonoids()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: PartiallyOrderedMonoids().super_categories()\n [Category of posets, Category of monoids]\n '
return [Posets(), Monoids()]
class ParentMethods():
pass
class ElementMethods():
pass
|
class PermutationGroups(Category):
'\n The category of permutation groups.\n\n A *permutation group* is a group whose elements are concretely\n represented by permutations of some set. In other words, the group\n comes endowed with a distinguished action on some set.\n\n This distinguished action should be preserved by permutation group\n morphisms. For details, see\n :wikipedia:`Permutation_group#Permutation_isomorphic_groups`.\n\n .. TODO:: shall we accept only permutations with finite support or not?\n\n EXAMPLES::\n\n sage: PermutationGroups()\n Category of permutation groups\n sage: PermutationGroups().super_categories()\n [Category of groups]\n\n The category of permutation groups defines additional structure\n that should be preserved by morphisms, namely the distinguished\n action::\n\n sage: PermutationGroups().additional_structure()\n Category of permutation groups\n\n TESTS::\n\n sage: C = PermutationGroups()\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n Return a list of the immediate super categories of ``self``.\n\n EXAMPLES::\n\n sage: PermutationGroups().super_categories()\n [Category of groups]\n '
return [Groups()]
Finite = LazyImport('sage.categories.finite_permutation_groups', 'FinitePermutationGroups')
|
class PointedSets(Category_singleton):
'\n The category of pointed sets.\n\n EXAMPLES::\n\n sage: PointedSets()\n Category of pointed sets\n\n TESTS::\n\n sage: TestSuite(PointedSets()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: PointedSets().super_categories()\n [Category of sets]\n '
return [Sets()]
|
class PolyhedralSets(Category_over_base_ring):
"\n The category of polyhedra over a ring.\n\n EXAMPLES:\n\n We create the category of polyhedra over `\\QQ`::\n\n sage: PolyhedralSets(QQ)\n Category of polyhedral sets over Rational Field\n\n TESTS::\n\n sage: TestSuite(PolyhedralSets(RDF)).run()\n\n sage: # needs sage.geometry.polyhedron\n sage: P = Polyhedron()\n sage: P.parent().category().element_class\n <class 'sage.categories.category.JoinCategory.element_class'>\n sage: P.parent().category().element_class.mro()\n [<class 'sage.categories.category.JoinCategory.element_class'>,\n <class 'sage.categories.polyhedra.PolyhedralSets.element_class'>,\n <class 'sage.categories.magmas.Magmas.Commutative.element_class'>,\n <class 'sage.categories.magmas.Magmas.element_class'>,\n <class 'sage.categories.additive_monoids.AdditiveMonoids.element_class'>,\n <class 'sage.categories.additive_magmas.AdditiveMagmas.AdditiveUnital.element_class'>,\n <class 'sage.categories.additive_semigroups.AdditiveSemigroups.element_class'>,\n <class 'sage.categories.additive_magmas.AdditiveMagmas.element_class'>,\n <class 'sage.categories.finite_enumerated_sets.FiniteEnumeratedSets.element_class'>,\n <class 'sage.categories.enumerated_sets.EnumeratedSets.element_class'>,\n <class 'sage.categories.finite_sets.FiniteSets.element_class'>,\n <class 'sage.categories.sets_cat.Sets.element_class'>,\n <class 'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.element_class'>,\n <class 'sage.categories.objects.Objects.element_class'>,\n <class 'object'>]\n sage: isinstance(P, P.parent().category().element_class)\n True\n "
def __init__(self, R):
'\n TESTS::\n\n sage: PolyhedralSets(AA) # needs sage.rings.number_field\n Category of polyhedral sets over Algebraic Real Field\n '
Category_over_base_ring.__init__(self, R)
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: PolyhedralSets(QQ).super_categories()\n [Category of commutative magmas, Category of additive monoids]\n '
from sage.categories.magmas import Magmas
from sage.categories.additive_monoids import AdditiveMonoids
return [Magmas().Commutative(), AdditiveMonoids()]
|
class PoorManMap(sage.structure.sage_object.SageObject):
'\n A class for maps between sets which are not (yet) modeled by parents\n\n Could possibly disappear when all combinatorial classes / enumerated sets will be parents\n\n INPUT:\n\n - ``function`` -- a callable or an iterable of callables. This represents\n the underlying function used to implement this map. If it is an iterable,\n then the callables will be composed to implement this map.\n\n - ``domain`` -- the domain of this map or ``None`` if the domain is not\n known or should remain unspecified\n\n - ``codomain`` -- the codomain of this map or ``None`` if the codomain is\n not known or should remain unspecified\n\n - ``name`` -- a name for this map or ``None`` if this map has no particular\n name\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(factorial, domain=(1, 2, 3), codomain=(1, 2, 6))\n sage: f\n A map from (1, 2, 3) to (1, 2, 6)\n sage: f(3)\n 6\n\n The composition of several functions can be created by passing in a tuple\n of functions::\n\n sage: i = PoorManMap((factorial, sqrt), domain=(1, 4, 9), codomain=(1, 2, 6))\n\n However, the same effect can also be achieved by just composing maps::\n\n sage: g = PoorManMap(factorial, domain=(1, 2, 3), codomain=(1, 2, 6))\n sage: h = PoorManMap(sqrt, domain=(1, 4, 9), codomain=(1, 2, 3))\n sage: i == g*h\n True\n\n '
def __init__(self, function, domain=None, codomain=None, name=None):
'\n TESTS::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(factorial, domain=(1, 2, 3), codomain=(1, 2, 6))\n sage: g = PoorManMap(sqrt, domain=(1, 4, 9), codomain=(1, 2, 6))\n\n sage: TestSuite(f).run()\n sage: TestSuite(f*g).run()\n\n '
from collections.abc import Iterable
if (not isinstance(function, Iterable)):
function = (function,)
self._functions = tuple(function)
self._domain = domain
self._codomain = codomain
self._name = name
def _repr_(self):
'\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: PoorManMap(lambda x: x+2) # indirect doctest\n A map\n sage: PoorManMap(lambda x: x+2, domain=(1,2,3))\n A map from (1, 2, 3)\n sage: PoorManMap(lambda x: x+2, domain=(1,2,3))\n A map from (1, 2, 3)\n sage: PoorManMap(lambda x: x+2, codomain=(3,4,5))\n A map to (3, 4, 5)\n\n '
return (((self._name if (self._name is not None) else 'A map') + ((' from %s' % (self._domain,)) if (self._domain is not None) else '')) + ((' to %s' % (self._codomain,)) if (self._codomain is not None) else ''))
def domain(self):
'\n Returns the domain of ``self``\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: PoorManMap(lambda x: x+1, domain=(1,2,3), codomain=(2,3,4)).domain()\n (1, 2, 3)\n '
return self._domain
def codomain(self):
'\n Returns the codomain of ``self``\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: PoorManMap(lambda x: x+1, domain=(1,2,3), codomain=(2,3,4)).codomain()\n (2, 3, 4)\n '
return self._codomain
def __eq__(self, other):
'\n Return whether this map is equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: g = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: h1 = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6,8))\n sage: h2 = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6,8))\n sage: h3 = PoorManMap(factorial, domain=(1,2,3,4), codomain=(1,2,6))\n sage: h4 = PoorManMap(lambda x: x, domain=(1,2,3), codomain=(1,2,6))\n sage: f == g, f == h1, f == h2, f == h3, f == h4, f == 1, 1 == f\n (True, False, False, False, False, False, False)\n\n '
if isinstance(other, PoorManMap):
return ((self._functions == other._functions) and (self._domain == other._domain) and (self._codomain == other._codomain) and (self._name == other._name))
else:
return False
def __ne__(self, other):
'\n Return whether this map is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: g = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: h1 = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6,8))\n sage: h2 = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6,8))\n sage: h3 = PoorManMap(factorial, domain=(1,2,3,4), codomain=(1,2,6))\n sage: h4 = PoorManMap(lambda x: x, domain=(1,2,3), codomain=(1,2,6))\n sage: f != g, f != h1, f != h2, f != h3, f != h4, f != 1, 1 != f\n (False, True, True, True, True, True, True)\n\n '
return (not (self == other))
def __hash__(self):
'\n Return a hash value for this map.\n\n TESTS::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: g = PoorManMap(factorial, domain=(1,2,3), codomain=(1,2,6))\n sage: hash(f) == hash(g)\n True\n\n '
return hash((self._functions, self._domain, self._codomain, self._name))
def __mul__(self, other):
'\n Composition\n\n INPUT:\n\n - ``self`` -- a map `f`\n - ``other`` -- a map `g`\n\n Returns the composition map `f\\circ g` of `f`` and `g`\n\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(lambda x: x+1, domain=(1,2,3), codomain=(2,3,4))\n sage: g = PoorManMap(lambda x: -x, domain=(2,3,4), codomain=(-2,-3,-4))\n sage: g*f\n A map from (1, 2, 3) to (-2, -3, -4)\n\n Note that the compatibility of the domains and codomains is for performance\n reasons only checked for proper parents. For example, the incompatibility\n is not detected here::\n\n sage: f*g\n A map from (2, 3, 4) to (2, 3, 4)\n\n But it is detected here::\n\n sage: g = PoorManMap(factorial, domain=ZZ, codomain=ZZ)\n sage: h = PoorManMap(sqrt, domain=RR, codomain=CC) # needs sage.rings.real_mpfr\n sage: g*h # needs sage.rings.real_mpfr\n Traceback (most recent call last):\n ...\n ValueError: the codomain Complex Field with 53 bits of precision\n does not coerce into the domain Integer Ring\n sage: h*g # needs sage.rings.real_mpfr\n A map from Integer Ring to Complex Field with 53 bits of precision\n '
self_domain = self.domain()
try:
other_codomain = other.codomain()
except AttributeError:
other_codomain = None
if ((self_domain is not None) and (other_codomain is not None)):
from sage.structure.parent import is_Parent
if (is_Parent(self_domain) and is_Parent(other_codomain)):
if (not self_domain.has_coerce_map_from(other_codomain)):
raise ValueError(('the codomain %r does not coerce into the domain %r' % (other_codomain, self_domain)))
codomain = self.codomain()
try:
domain = other.domain()
except AttributeError:
domain = None
if isinstance(other, PoorManMap):
other = other._functions
else:
other = (other,)
return PoorManMap((self._functions + other), domain=domain, codomain=codomain)
def __call__(self, *args):
'\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: f = PoorManMap(lambda x: x+1, domain=(1,2,3), codomain=(2,3,4))\n sage: f(2)\n 3\n\n sage: g = PoorManMap(lambda x: -x, domain=(2,3,4), codomain=(-2,-3,-4))\n sage: (g*f)(2)\n -3\n\n '
for function in reversed(self._functions):
args = [function(*args)]
return args[0]
def _sympy_(self):
'\n EXAMPLES::\n\n sage: from sage.categories.poor_man_map import PoorManMap\n sage: h = PoorManMap(sin, domain=RR, codomain=RR)\n sage: h._sympy_() # needs sympy sage.symbolic\n sin\n '
from sympy import Lambda, sympify
if (len(self._functions) == 1):
return sympify(self._functions[0])
raise NotImplementedError
|
class Posets(Category):
'\n The category of posets i.e. sets with a partial order structure.\n\n EXAMPLES::\n\n sage: Posets()\n Category of posets\n sage: Posets().super_categories()\n [Category of sets]\n sage: P = Posets().example(); P\n An example of a poset: sets ordered by inclusion\n\n The partial order is implemented by the mandatory method\n :meth:`~Posets.ParentMethods.le`::\n\n sage: x = P(Set([1,3])); y = P(Set([1,2,3]))\n sage: x, y\n ({1, 3}, {1, 2, 3})\n sage: P.le(x, y)\n True\n sage: P.le(x, x)\n True\n sage: P.le(y, x)\n False\n\n The other comparison methods are called\n :meth:`~Posets.ParentMethods.lt`, :meth:`~Posets.ParentMethods.ge`,\n :meth:`~Posets.ParentMethods.gt`, following Python\'s naming\n convention in :mod:`operator`. Default implementations are\n provided::\n\n sage: P.lt(x, x)\n False\n sage: P.ge(y, x)\n True\n\n Unless the poset is a facade (see :class:`Sets.Facade`), one can\n compare directly its elements using the usual Python operators::\n\n sage: D = Poset((divisors(30), attrcall("divides")), facade = False)\n sage: D(3) <= D(6)\n True\n sage: D(3) <= D(3)\n True\n sage: D(3) <= D(5)\n False\n sage: D(3) < D(3)\n False\n sage: D(10) >= D(5)\n True\n\n At this point, this has to be implemented by hand. Once\n :trac:`10130` will be resolved, this will be automatically\n provided by this category::\n\n sage: # not implemented\n sage: x < y\n True\n sage: x < x\n False\n sage: x <= x\n True\n sage: y >= x\n True\n\n .. SEEALSO:: :func:`Poset`, :class:`FinitePosets`, :class:`LatticePosets`\n\n TESTS::\n\n sage: C = Posets()\n sage: TestSuite(C).run()\n\n '
@cached_method
def super_categories(self):
'\n Return a list of the (immediate) super categories of\n ``self``, as per :meth:`Category.super_categories`.\n\n EXAMPLES::\n\n sage: Posets().super_categories()\n [Category of sets]\n '
return [Sets()]
def example(self, choice=None):
'\n Return examples of objects of ``Posets()``, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Posets().example()\n An example of a poset: sets ordered by inclusion\n\n sage: Posets().example("facade")\n An example of a facade poset:\n the positive integers ordered by divisibility\n '
from sage.categories.examples.posets import FiniteSetsOrderedByInclusion, PositiveIntegersOrderedByDivisibilityFacade
if (choice == 'facade'):
return PositiveIntegersOrderedByDivisibilityFacade()
else:
return FiniteSetsOrderedByInclusion()
def __iter__(self):
'\n Iterator over representatives of the isomorphism classes of\n posets with finitely many vertices.\n\n .. warning:: this feature may become deprecated, since it does\n of course not iterate through all posets.\n\n EXAMPLES::\n\n sage: P = Posets()\n sage: it = iter(P)\n sage: for _ in range(10): print(next(it))\n Finite poset containing 0 elements\n Finite poset containing 1 elements\n Finite poset containing 2 elements\n Finite poset containing 2 elements\n Finite poset containing 3 elements\n Finite poset containing 3 elements\n Finite poset containing 3 elements\n Finite poset containing 3 elements\n Finite poset containing 3 elements\n Finite poset containing 4 elements\n '
from sage.combinat.posets.posets import FinitePosets_n
n = 0
while True:
(yield from FinitePosets_n(n))
n += 1
Finite = LazyImport('sage.categories.finite_posets', 'FinitePosets')
class ParentMethods():
@abstract_method
def le(self, x, y):
'\n Return whether `x \\le y` in the poset ``self``.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.le( 3, 6 )\n True\n sage: D.le( 3, 3 )\n True\n sage: D.le( 3, 5 )\n False\n '
def lt(self, x, y):
'\n Return whether `x < y` in the poset ``self``.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``.\n\n This default implementation delegates the work to :meth:`le`.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.lt( 3, 6 )\n True\n sage: D.lt( 3, 3 )\n False\n sage: D.lt( 3, 5 )\n False\n '
return (self.le(x, y) and (x != y))
def ge(self, x, y):
'\n Return whether `x \\ge y` in the poset ``self``.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``.\n\n This default implementation delegates the work to :meth:`le`.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.ge( 6, 3 )\n True\n sage: D.ge( 3, 3 )\n True\n sage: D.ge( 3, 5 )\n False\n '
return self.le(y, x)
def gt(self, x, y):
'\n Return whether `x > y` in the poset ``self``.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``.\n\n This default implementation delegates the work to :meth:`lt`.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.gt( 3, 6 )\n False\n sage: D.gt( 3, 3 )\n False\n sage: D.gt( 3, 5 )\n False\n '
return self.lt(y, x)
@abstract_method(optional=True)
def upper_covers(self, x):
'\n Return the upper covers of `x`, that is, the elements `y`\n such that `x<y` and there exists no `z` such that `x<z<y`.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.upper_covers(3)\n [6, 15]\n '
@abstract_method(optional=True)
def lower_covers(self, x):
'\n Return the lower covers of `x`, that is, the elements `y`\n such that `y<x` and there exists no `z` such that `y<z<x`.\n\n EXAMPLES::\n\n sage: D = Poset((divisors(30), attrcall("divides")))\n sage: D.lower_covers(15)\n [3, 5]\n '
@abstract_method(optional=True)
def order_ideal(self, elements):
'\n Return the order ideal in ``self`` generated by the elements\n of an iterable ``elements``.\n\n A subset `I` of a poset is said to be an order ideal if, for\n any `x` in `I` and `y` such that `y \\le x`, then `y` is in `I`.\n\n This is also called the lower set generated by these elements.\n\n EXAMPLES::\n\n sage: B = posets.BooleanLattice(4)\n sage: B.order_ideal([7,10])\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]\n '
@abstract_method(optional=True)
def order_filter(self, elements):
'\n Return the order filter generated by a list of elements.\n\n A subset `I` of a poset is said to be an order filter if, for\n any `x` in `I` and `y` such that `y \\ge x`, then `y` is in `I`.\n\n This is also called the upper set generated by these elements.\n\n EXAMPLES::\n\n sage: B = posets.BooleanLattice(4)\n sage: B.order_filter([3,8])\n [3, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n '
def directed_subset(self, elements, direction):
"\n Return the order filter or the order ideal generated by a\n list of elements.\n\n If ``direction`` is 'up', the order filter (upper set) is\n being returned.\n\n If ``direction`` is 'down', the order ideal (lower set) is\n being returned.\n\n INPUT:\n\n - elements -- a list of elements.\n\n - direction -- 'up' or 'down'.\n\n EXAMPLES::\n\n sage: B = posets.BooleanLattice(4)\n sage: B.directed_subset([3, 8], 'up')\n [3, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n sage: B.directed_subset([7, 10], 'down')\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]\n\n TESTS::\n\n sage: B = posets.BooleanLattice(3)\n sage: B.directed_subset([3, 1], 'banana')\n Traceback (most recent call last):\n ...\n ValueError: direction must be either 'up' or 'down'\n "
if (direction == 'up'):
return self.order_filter(elements)
if (direction == 'down'):
return self.order_ideal(elements)
raise ValueError("direction must be either 'up' or 'down'")
def principal_order_ideal(self, x):
'\n Return the order ideal generated by an element ``x``.\n\n This is also called the lower set generated by this element.\n\n EXAMPLES::\n\n sage: B = posets.BooleanLattice(4)\n sage: B.principal_order_ideal(6)\n [0, 2, 4, 6]\n '
return self.order_ideal([x])
principal_lower_set = principal_order_ideal
def principal_order_filter(self, x):
'\n Return the order filter generated by an element ``x``.\n\n This is also called the upper set generated by this element.\n\n EXAMPLES::\n\n sage: B = posets.BooleanLattice(4)\n sage: B.principal_order_filter(2)\n [2, 3, 6, 7, 10, 11, 14, 15]\n '
return self.order_filter([x])
principal_upper_set = principal_order_filter
def order_ideal_toggle(self, I, v):
'\n Return the result of toggling the element ``v`` in the\n order ideal ``I``.\n\n If `v` is an element of a poset `P`, then toggling the\n element `v` is an automorphism of the set `J(P)` of all\n order ideals of `P`. It is defined as follows: If `I`\n is an order ideal of `P`, then the image of `I` under\n toggling the element `v` is\n\n - the set `I \\cup \\{ v \\}`, if `v \\not\\in I` but\n every element of `P` smaller than `v` is in `I`;\n\n - the set `I \\setminus \\{ v \\}`, if `v \\in I` but\n no element of `P` greater than `v` is in `I`;\n\n - `I` otherwise.\n\n This image always is an order ideal of `P`.\n\n EXAMPLES::\n\n sage: P = Poset({1: [2,3], 2: [4], 3: []})\n sage: I = Set({1, 2})\n sage: I in P.order_ideals_lattice() # needs sage.modules\n True\n sage: P.order_ideal_toggle(I, 1)\n {1, 2}\n sage: P.order_ideal_toggle(I, 2)\n {1}\n sage: P.order_ideal_toggle(I, 3)\n {1, 2, 3}\n sage: P.order_ideal_toggle(I, 4)\n {1, 2, 4}\n sage: P4 = Posets(4)\n sage: all(all(all(P.order_ideal_toggle(P.order_ideal_toggle(I, i), i) == I # needs sage.modules\n ....: for i in range(4))\n ....: for I in P.order_ideals_lattice(facade=True))\n ....: for P in P4)\n True\n '
if (v not in I):
if all(((u in I) for u in self.lower_covers(v))):
from sage.sets.set import Set
return I.union(Set({v}))
elif all(((u not in I) for u in self.upper_covers(v))):
from sage.sets.set import Set
return I.difference(Set({v}))
return I
def order_ideal_toggles(self, I, vs):
'\n Return the result of toggling the elements of the list (or\n iterable) ``vs`` (one by one, from left to right) in the order\n ideal ``I``.\n\n See :meth:`order_ideal_toggle` for a definition of toggling.\n\n EXAMPLES::\n\n sage: P = Poset({1: [2,3], 2: [4], 3: []})\n sage: I = Set({1, 2})\n sage: P.order_ideal_toggles(I, [1,2,3,4])\n {1, 3}\n sage: P.order_ideal_toggles(I, (1,2,3,4))\n {1, 3}\n '
for v in vs:
I = self.order_ideal_toggle(I, v)
return I
def is_order_ideal(self, o):
'\n Return whether ``o`` is an order ideal of ``self``, assuming ``self``\n has no infinite descending path.\n\n INPUT:\n\n - ``o`` -- a list (or set, or tuple) containing some elements of ``self``\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")),\n ....: facade=True, linear_extension=True)\n sage: sorted(P.list())\n [1, 2, 3, 4, 6, 12]\n sage: P.is_order_ideal([1, 3])\n True\n sage: P.is_order_ideal([])\n True\n sage: P.is_order_ideal({1, 3})\n True\n sage: P.is_order_ideal([1, 3, 4])\n False\n\n '
return all((((u in self) and all(((x in o) for x in self.lower_covers(u)))) for u in o))
def is_order_filter(self, o):
'\n Return whether ``o`` is an order filter of ``self``, assuming ``self``\n has no infinite ascending path.\n\n INPUT:\n\n - ``o`` -- a list (or set, or tuple) containing some elements of ``self``\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")),\n ....: facade=True, linear_extension=True)\n sage: sorted(P.list())\n [1, 2, 3, 4, 6, 12]\n sage: P.is_order_filter([4, 12])\n True\n sage: P.is_order_filter([])\n True\n sage: P.is_order_filter({3, 4, 12})\n False\n sage: P.is_order_filter({3, 6, 12})\n True\n\n '
return all((((u in self) and all(((x in o) for x in self.upper_covers(u)))) for u in o))
def is_chain_of_poset(self, o, ordered=False):
'\n Return whether an iterable ``o`` is a chain of ``self``,\n including a check for ``o`` being ordered from smallest\n to largest element if the keyword ``ordered`` is set to\n ``True``.\n\n INPUT:\n\n - ``o`` -- an iterable (e. g., list, set, or tuple)\n containing some elements of ``self``\n\n - ``ordered`` -- a Boolean (default: ``False``) which\n decides whether the notion of a chain includes being\n ordered\n\n OUTPUT:\n\n If ``ordered`` is set to ``False``, the truth value of\n the following assertion is returned: The subset of ``self``\n formed by the elements of ``o`` is a chain in ``self``.\n\n If ``ordered`` is set to ``True``, the truth value of\n the following assertion is returned: Every element of the\n list ``o`` is (strictly!) smaller than its successor in\n ``self``. (This makes no sense if ``ordered`` is a set.)\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")),\n ....: facade=True, linear_extension=True)\n sage: sorted(P.list())\n [1, 2, 3, 4, 6, 12]\n sage: P.is_chain_of_poset([1, 3])\n True\n sage: P.is_chain_of_poset([3, 1])\n True\n sage: P.is_chain_of_poset([1, 3], ordered=True)\n True\n sage: P.is_chain_of_poset([3, 1], ordered=True)\n False\n sage: P.is_chain_of_poset([])\n True\n sage: P.is_chain_of_poset([], ordered=True)\n True\n sage: P.is_chain_of_poset((2, 12, 6))\n True\n sage: P.is_chain_of_poset((2, 6, 12), ordered=True)\n True\n sage: P.is_chain_of_poset((2, 12, 6), ordered=True)\n False\n sage: P.is_chain_of_poset((2, 12, 6, 3))\n False\n sage: P.is_chain_of_poset((2, 3))\n False\n\n sage: Q = Poset({2: [3, 1], 3: [4], 1: [4]})\n sage: Q.is_chain_of_poset([1, 2], ordered=True)\n False\n sage: Q.is_chain_of_poset([1, 2])\n True\n sage: Q.is_chain_of_poset([2, 1], ordered=True)\n True\n sage: Q.is_chain_of_poset([2, 1, 1], ordered=True)\n False\n sage: Q.is_chain_of_poset([3])\n True\n sage: Q.is_chain_of_poset([4, 2, 3])\n True\n sage: Q.is_chain_of_poset([4, 2, 3], ordered=True)\n False\n sage: Q.is_chain_of_poset([2, 3, 4], ordered=True)\n True\n\n Examples with infinite posets::\n\n sage: from sage.categories.examples.posets import FiniteSetsOrderedByInclusion\n sage: R = FiniteSetsOrderedByInclusion()\n sage: R.is_chain_of_poset([R(set([3, 1, 2])),\n ....: R(set([1, 4])),\n ....: R(set([4, 5]))])\n False\n sage: R.is_chain_of_poset([R(set([3, 1, 2])),\n ....: R(set([1, 2])),\n ....: R(set([1]))], ordered=True)\n False\n sage: R.is_chain_of_poset([R(set([3, 1, 2])),\n ....: R(set([1, 2])), R(set([1]))])\n True\n\n sage: from sage.categories.examples.posets import PositiveIntegersOrderedByDivisibilityFacade\n sage: T = PositiveIntegersOrderedByDivisibilityFacade()\n sage: T.is_chain_of_poset((T(3), T(4), T(7)))\n False\n sage: T.is_chain_of_poset((T(3), T(6), T(3)))\n True\n sage: T.is_chain_of_poset((T(3), T(6), T(3)), ordered=True)\n False\n sage: T.is_chain_of_poset((T(3), T(3), T(6)))\n True\n sage: T.is_chain_of_poset((T(3), T(3), T(6)), ordered=True)\n False\n sage: T.is_chain_of_poset((T(3), T(6)), ordered=True)\n True\n sage: T.is_chain_of_poset((), ordered=True)\n True\n sage: T.is_chain_of_poset((T(3),), ordered=True)\n True\n sage: T.is_chain_of_poset((T(q) for q in divisors(27)))\n True\n sage: T.is_chain_of_poset((T(q) for q in divisors(18)))\n False\n '
list_o = list(o)
if ordered:
return all((self.lt(a, b) for (a, b) in zip(list_o, list_o[1:])))
else:
for (i, x) in enumerate(list_o):
for y in list_o[:i]:
if ((not self.le(x, y)) and (not self.gt(x, y))):
return False
return True
def is_antichain_of_poset(self, o):
'\n Return whether an iterable ``o`` is an antichain of\n ``self``.\n\n INPUT:\n\n - ``o`` -- an iterable (e. g., list, set, or tuple)\n containing some elements of ``self``\n\n OUTPUT:\n\n ``True`` if the subset of ``self`` consisting of the entries\n of ``o`` is an antichain of ``self``, and ``False`` otherwise.\n\n EXAMPLES::\n\n sage: P = Poset((divisors(12), attrcall("divides")),\n ....: facade=True, linear_extension=True)\n sage: sorted(P.list())\n [1, 2, 3, 4, 6, 12]\n sage: P.is_antichain_of_poset([1, 3])\n False\n sage: P.is_antichain_of_poset([3, 1])\n False\n sage: P.is_antichain_of_poset([1, 1, 3])\n False\n sage: P.is_antichain_of_poset([])\n True\n sage: P.is_antichain_of_poset([1])\n True\n sage: P.is_antichain_of_poset([1, 1])\n True\n sage: P.is_antichain_of_poset([3, 4])\n True\n sage: P.is_antichain_of_poset([3, 4, 12])\n False\n sage: P.is_antichain_of_poset([6, 4])\n True\n sage: P.is_antichain_of_poset(i for i in divisors(12)\n ....: if (2 < i and i < 6))\n True\n sage: P.is_antichain_of_poset(i for i in divisors(12)\n ....: if (2 <= i and i < 6))\n False\n\n sage: Q = Poset({2: [3, 1], 3: [4], 1: [4]})\n sage: Q.is_antichain_of_poset((1, 2))\n False\n sage: Q.is_antichain_of_poset((2, 4))\n False\n sage: Q.is_antichain_of_poset((4, 2))\n False\n sage: Q.is_antichain_of_poset((2, 2))\n True\n sage: Q.is_antichain_of_poset((3, 4))\n False\n sage: Q.is_antichain_of_poset((3, 1))\n True\n sage: Q.is_antichain_of_poset((1, ))\n True\n sage: Q.is_antichain_of_poset(())\n True\n\n An infinite poset::\n\n sage: from sage.categories.examples.posets import FiniteSetsOrderedByInclusion\n sage: R = FiniteSetsOrderedByInclusion()\n sage: R.is_antichain_of_poset([R(set([3, 1, 2])),\n ....: R(set([1, 4])), R(set([4, 5]))])\n True\n sage: R.is_antichain_of_poset([R(set([3, 1, 2, 4])),\n ....: R(set([1, 4])), R(set([4, 5]))])\n False\n '
return all(((not self.lt(x, y)) for x in o for y in o))
CartesianProduct = LazyImport('sage.combinat.posets.cartesian_product', 'CartesianProductPoset')
class ElementMethods():
pass
|
class PrincipalIdealDomains(Category_singleton):
'\n The category of (constructive) principal ideal domains\n\n By constructive, we mean that a single generator can be\n constructively found for any ideal given by a finite set of\n generators. Note that this constructive definition only implies\n that finitely generated ideals are principal. It is not clear what\n we would mean by an infinitely generated ideal.\n\n EXAMPLES::\n\n sage: PrincipalIdealDomains()\n Category of principal ideal domains\n sage: PrincipalIdealDomains().super_categories()\n [Category of unique factorization domains]\n\n See also :wikipedia:`Principal_ideal_domain`\n\n TESTS::\n\n sage: TestSuite(PrincipalIdealDomains()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: PrincipalIdealDomains().super_categories()\n [Category of unique factorization domains]\n '
return [UniqueFactorizationDomains()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of principal ideal domains defines no\n additional structure: a ring morphism between two principal\n ideal domains is a principal ideal domain morphism.\n\n EXAMPLES::\n\n sage: PrincipalIdealDomains().additional_structure()\n '
return None
class ParentMethods():
def _test_gcd_vs_xgcd(self, **options):
"\n Check that gcd and xgcd are compatible if implemented.\n\n This test will prevent things like :trac:`17671` to happen again.\n\n TESTS::\n\n sage: ZZ._test_gcd_vs_xgcd()\n sage: QQ._test_gcd_vs_xgcd()\n sage: QQ['x']._test_gcd_vs_xgcd()\n sage: QQbar['x']._test_gcd_vs_xgcd() # needs sage.rings.number_field\n sage: RR._test_gcd_vs_xgcd()\n sage: RR['x']._test_gcd_vs_xgcd()\n\n A slightly more involved example of polynomial ring with a non UFD\n base ring::\n\n sage: # needs sage.rings.number_field\n sage: K = QuadraticField(5)\n sage: O = K.maximal_order()\n sage: O in UniqueFactorizationDomains()\n False\n sage: R = PolynomialRing(O, 'x')\n sage: F = R.fraction_field()\n sage: F in PrincipalIdealDomains()\n True\n sage: F._test_gcd_vs_xgcd()\n "
tester = self._tester(**options)
elts = list(tester.some_elements())
elts = elts[:10]
pairs = [(x, y) for x in elts for y in elts]
try:
xgcds = [x.xgcd(y) for (x, y) in pairs]
except (AttributeError, NotImplementedError):
return
has_gcd = True
try:
gcds = [x.gcd(y) for (x, y) in pairs]
except (AttributeError, NotImplementedError):
has_gcd = False
tester.assertTrue(has_gcd, 'The ring {} provides a xgcd but no gcd'.format(self))
for ((x, y), gcd, xgcd) in zip(pairs, gcds, xgcds):
tester.assertTrue((gcd.parent() == self), 'The parent of the gcd is {} for element of {}'.format(gcd.parent(), self))
tester.assertTrue(((xgcd[0].parent() == self) and (xgcd[1].parent() == self) and (xgcd[2].parent() == self)), 'The parent of output in xgcd is different from the parent of input for elements in {}'.format(self))
tester.assertTrue((gcd == xgcd[0]), 'The methods gcd and xgcd disagree on {}:\n gcd({},{}) = {}\n xgcd({},{}) = {}\n'.format(self, x, y, gcd, x, y, xgcd))
class ElementMethods():
pass
|
class ConstructionFunctor(Functor):
"\n Base class for construction functors.\n\n A construction functor is a functorial algebraic construction,\n such as the construction of a matrix ring over a given ring\n or the fraction field of a given ring.\n\n In addition to the class :class:`~sage.categories.functor.Functor`,\n construction functors provide rules for combining and merging\n constructions. This is an important part of Sage's coercion model,\n namely the pushout of two constructions: When a polynomial ``p`` in\n a variable ``x`` with integer coefficients is added to a rational\n number ``q``, then Sage finds that the parents ``ZZ['x']`` and\n ``QQ`` are obtained from ``ZZ`` by applying a polynomial ring\n construction respectively the fraction field construction. Each\n construction functor has an attribute ``rank``, and the rank of\n the polynomial ring construction is higher than the rank of the\n fraction field construction. This means that the pushout of ``QQ``\n and ``ZZ['x']``, and thus a common parent in which ``p`` and ``q``\n can be added, is ``QQ['x']``, since the construction functor with\n a lower rank is applied first.\n\n ::\n\n sage: F1, R = QQ.construction()\n sage: F1\n FractionField\n sage: R\n Integer Ring\n sage: F2, R = (ZZ['x']).construction()\n sage: F2\n Poly[x]\n sage: R\n Integer Ring\n sage: F3 = F2.pushout(F1)\n sage: F3\n Poly[x](FractionField(...))\n sage: F3(R)\n Univariate Polynomial Ring in x over Rational Field\n sage: from sage.categories.pushout import pushout\n sage: P.<x> = ZZ[]\n sage: pushout(QQ,P)\n Univariate Polynomial Ring in x over Rational Field\n sage: ((x+1) + 1/2).parent()\n Univariate Polynomial Ring in x over Rational Field\n\n When composing two construction functors, they are sometimes\n merged into one, as is the case in the Quotient construction::\n\n sage: Q15, R = (ZZ.quo(15*ZZ)).construction()\n sage: Q15\n QuotientFunctor\n sage: Q35, R = (ZZ.quo(35*ZZ)).construction()\n sage: Q35\n QuotientFunctor\n sage: Q15.merge(Q35)\n QuotientFunctor\n sage: Q15.merge(Q35)(ZZ)\n Ring of integers modulo 5\n\n Functors can not only be applied to objects, but also to morphisms in the\n respective categories. For example::\n\n sage: P.<x,y> = ZZ[]\n sage: F = P.construction()[0]; F\n MPoly[x,y]\n sage: A.<a,b> = GF(5)[]\n sage: f = A.hom([a + b, a - b], A)\n sage: F(A)\n Multivariate Polynomial Ring in x, y\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n sage: F(f)\n Ring endomorphism of Multivariate Polynomial Ring in x, y\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n Defn: Induced from base ring by\n Ring endomorphism of Multivariate Polynomial Ring in a, b\n over Finite Field of size 5\n Defn: a |--> a + b\n b |--> a - b\n sage: F(f)(F(A)(x)*a)\n (a + b)*x\n\n "
def __mul__(self, other):
"\n Compose ``self`` and ``other`` to a composite construction\n functor, unless one of them is the identity.\n\n .. NOTE::\n\n The product is in functorial notation, i.e., when applying the\n product to an object, the second factor is applied first.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: F*P\n FractionField(Poly[t](...))\n sage: P*F\n Poly[t](FractionField(...))\n sage: (F*P)(ZZ)\n Fraction Field of Univariate Polynomial Ring in t over Integer Ring\n sage: I*P is P\n True\n sage: F*I is F\n True\n\n "
if ((not isinstance(self, ConstructionFunctor)) and (not isinstance(other, ConstructionFunctor))):
raise CoercionException('Non-constructive product')
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(self, IdentityConstructionFunctor):
return other
return CompositeConstructionFunctor(other, self)
def pushout(self, other):
"\n Composition of two construction functors, ordered by their ranks.\n\n .. NOTE::\n\n - This method seems not to be used in the coercion model.\n\n - By default, the functor with smaller rank is applied first.\n\n TESTS::\n\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: F.pushout(P)\n Poly[t](FractionField(...))\n sage: P.pushout(F)\n Poly[t](FractionField(...))\n\n "
if (self.rank > other.rank):
return (self * other)
else:
return (other * self)
def __eq__(self, other):
"\n Equality here means that they are mathematically equivalent, though they may have\n specific implementation data. This method will usually be overloaded in subclasses.\n by default, only the types of the functors are compared. Also see the :meth:`merge` function.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: I == F # indirect doctest\n False\n sage: I == I # indirect doctest\n True\n "
return (type(self) is type(other))
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: I != F # indirect doctest\n True\n sage: I != I # indirect doctest\n False\n "
return (not (self == other))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: F = QQ.construction()[0]\n sage: hash(I) == hash(F)\n False\n sage: hash(I) == hash(I)\n True\n '
return hash(repr(self))
def _repr_(self):
"\n .. NOTE::\n\n By default, it returns the name of the construction\n functor's class. Usually, this method will be overloaded.\n\n TESTS::\n\n sage: F = QQ.construction()[0]\n sage: F # indirect doctest\n FractionField\n sage: Q = ZZ.quo(2).construction()[0]\n sage: Q # indirect doctest\n QuotientFunctor\n\n "
s = str(type(self))
import re
return re.sub("<.*'.*\\.([^.]*)'>", '\\1', s)
def merge(self, other):
"\n Merge ``self`` with another construction functor, or return ``None``.\n\n .. NOTE::\n\n The default is to merge only if the two functors coincide. But this\n may be overloaded for subclasses, such as the quotient functor.\n\n EXAMPLES::\n\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: F.merge(F)\n FractionField\n sage: F.merge(P)\n sage: P.merge(F)\n sage: P.merge(P)\n Poly[t]\n\n "
if (self == other):
return self
else:
return None
def commutes(self, other):
"\n Determine whether ``self`` commutes with another construction functor.\n\n .. NOTE::\n\n By default, ``False`` is returned in all cases (even if the two\n functors are the same, since in this case :meth:`merge` will apply\n anyway). So far there is no construction functor that overloads\n this method. Anyway, this method only becomes relevant if two\n construction functors have the same rank.\n\n EXAMPLES::\n\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: F.commutes(P)\n False\n sage: P.commutes(F)\n False\n sage: F.commutes(F)\n False\n\n "
return False
def expand(self):
"\n Decompose ``self`` into a list of construction functors.\n\n .. NOTE::\n\n The default is to return the list only containing ``self``.\n\n EXAMPLES::\n\n sage: F = QQ.construction()[0]\n sage: F.expand()\n [FractionField]\n sage: Q = ZZ.quo(2).construction()[0]\n sage: Q.expand()\n [QuotientFunctor]\n sage: P = ZZ['t'].construction()[0]\n sage: FP = F*P\n sage: FP.expand()\n [FractionField, Poly[t]]\n\n "
return [self]
coercion_reversed = False
def common_base(self, other_functor, self_bases, other_bases):
'\n This function is called by :func:`pushout` when no common parent\n is found in the construction tower.\n\n .. NOTE::\n\n The main use is for multivariate construction functors,\n which use this function to implement recursion for\n :func:`pushout`.\n\n INPUT:\n\n - ``other_functor`` -- a construction functor.\n\n - ``self_bases`` -- the arguments passed to this functor.\n\n - ``other_bases`` -- the arguments passed to the functor\n ``other_functor``.\n\n OUTPUT:\n\n Nothing, since a\n :class:`~sage.structure.coerce_exceptions.CoercionException`\n is raised.\n\n .. NOTE::\n\n Overload this function in derived class, see\n e.e. :class:`MultivariateConstructionFunctor`.\n\n TESTS::\n\n sage: from sage.categories.pushout import pushout\n sage: pushout(QQ, cartesian_product([ZZ])) # indirect doctest\n Traceback (most recent call last):\n ...\n CoercionException: No common base ("join") found for\n FractionField(Integer Ring) and The cartesian_product functorial construction(Integer Ring).\n '
self._raise_common_base_exception_(other_functor, self_bases, other_bases)
def _raise_common_base_exception_(self, other_functor, self_bases, other_bases, reason=None):
'\n Raise a coercion exception.\n\n INPUT:\n\n - ``other_functor`` -- a functor.\n\n - ``self_bases`` -- the arguments passed to this functor.\n\n - ``other_bases`` -- the arguments passed to the functor\n ``other_functor``.\n\n - ``reason`` -- a string or ``None`` (default).\n\n TESTS::\n\n sage: from sage.categories.pushout import pushout\n sage: pushout(QQ, cartesian_product([QQ])) # indirect doctest\n Traceback (most recent call last):\n ...\n CoercionException: No common base ("join") found for\n FractionField(Integer Ring) and The cartesian_product functorial construction(Rational Field).\n '
if (not isinstance(self_bases, (tuple, list))):
self_bases = (self_bases,)
if (not isinstance(other_bases, (tuple, list))):
other_bases = (other_bases,)
if (reason is None):
reason = '.'
else:
reason = ((': ' + reason) + '.')
raise CoercionException(('No common base ("join") found for %s(%s) and %s(%s)%s' % (self, ', '.join((str(b) for b in self_bases)), other_functor, ', '.join((str(b) for b in other_bases)), reason)))
|
class CompositeConstructionFunctor(ConstructionFunctor):
"\n A Construction Functor composed by other Construction Functors.\n\n INPUT:\n\n ``F1, F2,...``: A list of Construction Functors. The result is the\n composition ``F1`` followed by ``F2`` followed by ...\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0], ZZ['x'].construction()[0],\n ....: QQ.construction()[0], ZZ['y'].construction()[0])\n sage: F\n Poly[y](FractionField(Poly[x](FractionField(...))))\n sage: F == loads(dumps(F))\n True\n sage: F == CompositeConstructionFunctor(*F.all)\n True\n sage: F(GF(2)['t']) # needs sage.libs.ntl\n Univariate Polynomial Ring in y\n over Fraction Field of Univariate Polynomial Ring in x\n over Fraction Field of Univariate Polynomial Ring in t\n over Finite Field of size 2 (using GF2X)\n "
def __init__(self, *args):
"\n TESTS::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0], ZZ['x'].construction()[0],\n ....: QQ.construction()[0], ZZ['y'].construction()[0])\n sage: F\n Poly[y](FractionField(Poly[x](FractionField(...))))\n sage: F == CompositeConstructionFunctor(*F.all)\n True\n\n "
self.all = []
for c in args:
if isinstance(c, list):
self.all += c
elif isinstance(c, CompositeConstructionFunctor):
self.all += c.all
else:
self.all.append(c)
Functor.__init__(self, self.all[0].domain(), self.all[(- 1)].codomain())
def _apply_functor_to_morphism(self, f):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0],QQ.construction()[0],ZZ['y'].construction()[0])\n sage: R.<a,b> = QQ[]\n sage: f = R.hom([a+b, a-b])\n sage: F(f) # indirect doctest\n Ring endomorphism of Univariate Polynomial Ring in y over Fraction Field of Univariate Polynomial Ring in x over Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field\n Defn: Induced from base ring by\n Ring endomorphism of Fraction Field of Univariate Polynomial Ring in x over Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field\n Defn: Induced from base ring by\n Ring endomorphism of Univariate Polynomial Ring in x over Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field\n Defn: Induced from base ring by\n Ring endomorphism of Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field\n Defn: a |--> a + b\n b |--> a - b\n\n "
for c in self.all:
f = c(f)
return f
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0],QQ.construction()[0],ZZ['y'].construction()[0])\n sage: R.<a,b> = QQ[]\n sage: F(R) # indirect doctest\n Univariate Polynomial Ring in y over Fraction Field of Univariate Polynomial Ring in x over Fraction Field of Multivariate Polynomial Ring in a, b over Rational Field\n\n "
for c in self.all:
R = c(R)
return R
def __eq__(self, other):
"\n TESTS::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0],QQ.construction()[0],ZZ['y'].construction()[0])\n sage: F == loads(dumps(F)) # indirect doctest\n True\n "
if isinstance(other, CompositeConstructionFunctor):
return (self.all == other.all)
else:
return (type(self) is type(other))
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0],QQ.construction()[0],ZZ['y'].construction()[0])\n sage: F != loads(dumps(F)) # indirect doctest\n False\n "
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def __mul__(self, other):
"\n Compose construction functors to a composit construction functor, unless one of them is the identity.\n\n .. NOTE::\n\n The product is in functorial notation, i.e., when applying the product to an object\n then the second factor is applied first.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F1 = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0])\n sage: F2 = CompositeConstructionFunctor(QQ.construction()[0],ZZ['y'].construction()[0])\n sage: F1*F2\n Poly[x](FractionField(Poly[y](FractionField(...))))\n\n "
if isinstance(self, CompositeConstructionFunctor):
all = ([other] + self.all)
elif isinstance(other, IdentityConstructionFunctor):
return self
else:
all = (other.all + [self])
return CompositeConstructionFunctor(*all)
def _repr_(self):
"\n TESTS::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],ZZ['x'].construction()[0],QQ.construction()[0],ZZ['y'].construction()[0])\n sage: F # indirect doctest\n Poly[y](FractionField(Poly[x](FractionField(...))))\n\n "
s = '...'
for c in self.all:
s = ('%s(%s)' % (c, s))
return s
def expand(self):
"\n Return expansion of a CompositeConstructionFunctor.\n\n .. NOTE::\n\n The product over the list of components, as returned by\n the ``expand()`` method, is equal to ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import CompositeConstructionFunctor\n sage: F = CompositeConstructionFunctor(QQ.construction()[0],\n ....: ZZ['x'].construction()[0],\n ....: QQ.construction()[0],\n ....: ZZ['y'].construction()[0])\n sage: F\n Poly[y](FractionField(Poly[x](FractionField(...))))\n sage: prod(F.expand()) == F\n True\n\n "
return list(reversed(self.all))
|
class IdentityConstructionFunctor(ConstructionFunctor):
'\n A construction functor that is the identity functor.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: I(RR) is RR\n True\n sage: I == loads(dumps(I))\n True\n\n '
rank = (- 100)
def __init__(self):
'\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: IdentityFunctor(Sets()) == I\n True\n sage: I(RR) is RR\n True\n\n '
from sage.categories.sets_cat import Sets
ConstructionFunctor.__init__(self, Sets(), Sets())
def _apply_functor(self, x):
'\n Return the argument unaltered.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: I(RR) is RR # indirect doctest\n True\n '
return x
def _apply_functor_to_morphism(self, f):
"\n Return the argument unaltered.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: f = ZZ['t'].hom(['x'],QQ['x'])\n sage: I(f) is f # indirect doctest\n True\n "
return f
def __eq__(self, other):
'\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: I == IdentityFunctor(Sets()) # indirect doctest\n True\n sage: I == QQ.construction()[0]\n False\n '
c = (type(self) is type(other))
if (not c):
if isinstance(other, IdentityFunctor_generic):
return True
return c
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: I != IdentityFunctor(Sets()) # indirect doctest\n False\n sage: I != QQ.construction()[0]\n True\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def __mul__(self, other):
"\n Compose construction functors to a composit construction functor, unless one of them is the identity.\n\n .. NOTE::\n\n The product is in functorial notation, i.e., when applying the\n product to an object then the second factor is applied first.\n\n TESTS::\n\n sage: from sage.categories.pushout import IdentityConstructionFunctor\n sage: I = IdentityConstructionFunctor()\n sage: F = QQ.construction()[0]\n sage: P = ZZ['t'].construction()[0]\n sage: I*F is F # indirect doctest\n True\n sage: F*I is F\n True\n sage: I*P is P\n True\n sage: P*I is P\n True\n\n "
if isinstance(self, IdentityConstructionFunctor):
return other
else:
return self
|
class MultivariateConstructionFunctor(ConstructionFunctor):
"\n An abstract base class for functors that take\n multiple inputs (e.g. Cartesian products).\n\n TESTS::\n\n sage: from sage.categories.pushout import pushout\n sage: A = cartesian_product((QQ['z'], QQ))\n sage: B = cartesian_product((ZZ['t']['z'], QQ))\n sage: pushout(A, B)\n The Cartesian product of (Univariate Polynomial Ring in z over\n Univariate Polynomial Ring in t over Rational Field,\n Rational Field)\n sage: A.construction()\n (The cartesian_product functorial construction,\n (Univariate Polynomial Ring in z over Rational Field, Rational Field))\n sage: pushout(A, B)\n The Cartesian product of (Univariate Polynomial Ring in z over Univariate Polynomial Ring in t over Rational Field, Rational Field)\n "
def common_base(self, other_functor, self_bases, other_bases):
'\n This function is called by :func:`pushout` when no common parent\n is found in the construction tower.\n\n INPUT:\n\n - ``other_functor`` -- a construction functor.\n\n - ``self_bases`` -- the arguments passed to this functor.\n\n - ``other_bases`` -- the arguments passed to the functor\n ``other_functor``.\n\n OUTPUT:\n\n A parent.\n\n If no common base is found a :class:`sage.structure.coerce_exceptions.CoercionException`\n is raised.\n\n .. NOTE::\n\n Overload this function in derived class, see\n e.g. :class:`MultivariateConstructionFunctor`.\n\n TESTS::\n\n sage: from sage.categories.pushout import pushout\n sage: pushout(cartesian_product([ZZ]), QQ) # indirect doctest\n Traceback (most recent call last):\n ...\n CoercionException: No common base ("join") found for\n The cartesian_product functorial construction(Integer Ring) and FractionField(Integer Ring):\n (Multivariate) functors are incompatible.\n sage: pushout(cartesian_product([ZZ]), cartesian_product([ZZ, QQ])) # indirect doctest\n Traceback (most recent call last):\n ...\n CoercionException: No common base ("join") found ...\n '
if (self != other_functor):
self._raise_common_base_exception_(other_functor, self_bases, other_bases, '(Multivariate) functors are incompatible')
if (len(self_bases) != len(other_bases)):
self._raise_common_base_exception_(other_functor, self_bases, other_bases, 'Functors need the same number of arguments')
from sage.structure.element import coercion_model
Z_bases = tuple((coercion_model.common_parent(S, O) for (S, O) in zip(self_bases, other_bases)))
return self(Z_bases)
|
class PolynomialFunctor(ConstructionFunctor):
"\n Construction functor for univariate polynomial rings.\n\n EXAMPLES::\n\n sage: P = ZZ['t'].construction()[0]\n sage: P(GF(3))\n Univariate Polynomial Ring in t over Finite Field of size 3\n sage: P == loads(dumps(P))\n True\n sage: R.<x,y> = GF(5)[]\n sage: f = R.hom([x + 2*y, 3*x - y], R)\n sage: P(f)((x+y) * P(R).0)\n (-x + y)*t\n\n By :trac:`9944`, the construction functor distinguishes sparse and\n dense polynomial rings. Before, the following example failed::\n\n sage: R.<x> = PolynomialRing(GF(5), sparse=True)\n sage: F, B = R.construction()\n sage: F(B) is R\n True\n sage: S.<x> = PolynomialRing(ZZ)\n sage: R.has_coerce_map_from(S)\n False\n sage: S.has_coerce_map_from(R)\n False\n sage: S.0 + R.0\n 2*x\n sage: (S.0 + R.0).parent()\n Univariate Polynomial Ring in x over Finite Field of size 5\n sage: (S.0 + R.0).parent().is_sparse()\n False\n\n "
rank = 9
def __init__(self, var, multi_variate=False, sparse=False, implementation=None):
"\n TESTS::\n\n sage: from sage.categories.pushout import PolynomialFunctor\n sage: P = PolynomialFunctor('x')\n sage: P(GF(3))\n Univariate Polynomial Ring in x over Finite Field of size 3\n\n There is an optional parameter ``multi_variate``, but\n apparently it is not used::\n\n sage: Q = PolynomialFunctor('x',multi_variate=True)\n sage: Q(ZZ)\n Univariate Polynomial Ring in x over Integer Ring\n sage: Q == P\n True\n\n "
from .rings import Rings
Functor.__init__(self, Rings(), Rings())
self.var = var
self.multi_variate = multi_variate
self.sparse = sparse
self.implementation = implementation
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: P = ZZ['x'].construction()[0]\n sage: P(GF(3)) # indirect doctest\n Univariate Polynomial Ring in x over Finite Field of size 3\n\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
kwds = {}
if self.implementation:
kwds['implementation'] = self.implementation
return PolynomialRing(R, self.var, sparse=self.sparse, **kwds)
def _apply_functor_to_morphism(self, f):
"\n Apply the functor ``self`` to the morphism `f`.\n\n TESTS::\n\n sage: P = ZZ['x'].construction()[0]\n sage: P(ZZ.hom(GF(3))) # indirect doctest\n Ring morphism:\n From: Univariate Polynomial Ring in x over Integer Ring\n To: Univariate Polynomial Ring in x over Finite Field of size 3\n Defn: Induced from base ring by\n Natural morphism:\n From: Integer Ring\n To: Finite Field of size 3\n "
from sage.rings.polynomial.polynomial_ring_homomorphism import PolynomialRingHomomorphism_from_base
R = self._apply_functor(f.domain())
S = self._apply_functor(f.codomain())
return PolynomialRingHomomorphism_from_base(R.Hom(S), f)
def __eq__(self, other):
"\n TESTS::\n\n sage: from sage.categories.pushout import MultiPolynomialFunctor\n sage: Q = MultiPolynomialFunctor(('x',),'lex')\n sage: P = ZZ['x'].construction()[0]\n sage: P\n Poly[x]\n sage: Q\n MPoly[x]\n sage: P == Q\n True\n sage: P == loads(dumps(P))\n True\n sage: P == QQ.construction()[0]\n False\n "
if isinstance(other, PolynomialFunctor):
return (self.var == other.var)
elif isinstance(other, MultiPolynomialFunctor):
return (other == self)
else:
return False
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import MultiPolynomialFunctor\n sage: Q = MultiPolynomialFunctor(('x',),'lex')\n sage: P = ZZ['x'].construction()[0]\n sage: P != Q\n False\n sage: P != loads(dumps(P))\n False\n sage: P != QQ.construction()[0]\n True\n "
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Merge ``self`` with another construction functor, or return ``None``.\n\n .. NOTE::\n\n Internally, the merging is delegated to the merging of\n multipolynomial construction functors. But in effect,\n this does the same as the default implementation, that\n returns ``None`` unless the to-be-merged functors coincide.\n\n EXAMPLES::\n\n sage: P = ZZ['x'].construction()[0]\n sage: Q = ZZ['y','x'].construction()[0]\n sage: P.merge(Q)\n sage: P.merge(P) is P\n True\n\n "
if isinstance(other, MultiPolynomialFunctor):
return other.merge(self)
elif (self == other):
if (not self.sparse):
return self
return other
else:
return None
def _repr_(self):
"\n TESTS::\n\n sage: P = ZZ['x'].construction()[0]\n sage: P # indirect doctest\n Poly[x]\n\n "
return ('Poly[%s]' % self.var)
|
class MultiPolynomialFunctor(ConstructionFunctor):
'\n A constructor for multivariate polynomial rings.\n\n EXAMPLES::\n\n sage: P.<x,y> = ZZ[]\n sage: F = P.construction()[0]; F\n MPoly[x,y]\n sage: A.<a,b> = GF(5)[]\n sage: F(A)\n Multivariate Polynomial Ring in x, y\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n sage: f = A.hom([a+b, a-b], A)\n sage: F(f)\n Ring endomorphism of Multivariate Polynomial Ring in x, y\n over Multivariate Polynomial Ring in a, b over Finite Field of size 5\n Defn: Induced from base ring by\n Ring endomorphism of Multivariate Polynomial Ring in a, b over Finite Field of size 5\n Defn: a |--> a + b\n b |--> a - b\n sage: F(f)(F(A)(x)*a)\n (a + b)*x\n\n '
rank = 9
def __init__(self, vars, term_order):
"\n EXAMPLES::\n\n sage: F = sage.categories.pushout.MultiPolynomialFunctor(['x','y'], None)\n sage: F\n MPoly[x,y]\n sage: F(ZZ)\n Multivariate Polynomial Ring in x, y over Integer Ring\n sage: F(CC) # needs sage.rings.real_mpfr\n Multivariate Polynomial Ring in x, y over Complex Field with 53 bits of precision\n "
Functor.__init__(self, Rings(), Rings())
self.vars = vars
self.term_order = term_order
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n EXAMPLES::\n\n sage: R.<x,y,z> = QQ[]\n sage: F = R.construction()[0]; F\n MPoly[x,y,z]\n sage: type(F)\n <class 'sage.categories.pushout.MultiPolynomialFunctor'>\n sage: F(ZZ) # indirect doctest\n Multivariate Polynomial Ring in x, y, z over Integer Ring\n sage: F(RR) # indirect doctest # needs sage.rings.real_mpfr\n Multivariate Polynomial Ring in x, y, z over Real Field with 53 bits of precision\n "
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
return PolynomialRing(R, self.vars)
def __eq__(self, other):
"\n EXAMPLES::\n\n sage: F = ZZ['x,y,z'].construction()[0]\n sage: G = QQ['x,y,z'].construction()[0]\n sage: F == G\n True\n sage: G == loads(dumps(G))\n True\n sage: G = ZZ['x,y'].construction()[0]\n sage: F == G\n False\n "
if isinstance(other, MultiPolynomialFunctor):
return ((self.vars == other.vars) and (self.term_order == other.term_order))
elif isinstance(other, PolynomialFunctor):
return (self.vars == (other.var,))
else:
return False
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: F = ZZ['x,y,z'].construction()[0]\n sage: G = QQ['x,y,z'].construction()[0]\n sage: F != G\n False\n sage: G != loads(dumps(G))\n False\n sage: G = ZZ['x,y'].construction()[0]\n sage: F != G\n True\n "
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def __mul__(self, other):
"\n If two MPoly functors are given in a row, form a single MPoly functor\n with all of the variables.\n\n EXAMPLES::\n\n sage: F = sage.categories.pushout.MultiPolynomialFunctor(['x','y'], None)\n sage: G = sage.categories.pushout.MultiPolynomialFunctor(['t'], None)\n sage: G*F\n MPoly[x,y,t]\n "
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, MultiPolynomialFunctor):
if (self.term_order != other.term_order):
raise CoercionException(('Incompatible term orders (%s,%s).' % (self.term_order, other.term_order)))
if set(self.vars).intersection(other.vars):
raise CoercionException(('Overlapping variables (%s,%s)' % (self.vars, other.vars)))
return MultiPolynomialFunctor((other.vars + self.vars), self.term_order)
elif (isinstance(other, CompositeConstructionFunctor) and isinstance(other.all[(- 1)], MultiPolynomialFunctor)):
return CompositeConstructionFunctor(other.all[:(- 1)], (self * other.all[(- 1)]))
else:
return CompositeConstructionFunctor(other, self)
def merge(self, other):
"\n Merge ``self`` with another construction functor, or return ``None``.\n\n EXAMPLES::\n\n sage: F = sage.categories.pushout.MultiPolynomialFunctor(['x','y'], None)\n sage: G = sage.categories.pushout.MultiPolynomialFunctor(['t'], None)\n sage: F.merge(G) is None\n True\n sage: F.merge(F)\n MPoly[x,y]\n "
if (self == other):
return self
else:
return None
def expand(self):
"\n Decompose ``self`` into a list of construction functors.\n\n EXAMPLES::\n\n sage: F = QQ['x,y,z,t'].construction()[0]; F\n MPoly[x,y,z,t]\n sage: F.expand()\n [MPoly[t], MPoly[z], MPoly[y], MPoly[x]]\n\n Now an actual use case::\n\n sage: R.<x,y,z> = ZZ[]\n sage: S.<z,t> = QQ[]\n sage: x+t\n x + t\n sage: parent(x+t)\n Multivariate Polynomial Ring in x, y, z, t over Rational Field\n sage: T.<y,s> = QQ[]\n sage: x + s\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand parent(s) for +:\n 'Multivariate Polynomial Ring in x, y, z over Integer Ring' and\n 'Multivariate Polynomial Ring in y, s over Rational Field'\n sage: R = PolynomialRing(ZZ, 'x', 50)\n sage: S = PolynomialRing(GF(5), 'x', 20)\n sage: R.gen(0) + S.gen(0)\n 2*x0\n "
if (len(self.vars) <= 1):
return [self]
else:
return [MultiPolynomialFunctor((x,), self.term_order) for x in reversed(self.vars)]
def _repr_(self):
"\n TESTS::\n\n sage: QQ['x,y,z,t'].construction()[0]\n MPoly[x,y,z,t]\n "
return ('MPoly[%s]' % ','.join(self.vars))
|
class InfinitePolynomialFunctor(ConstructionFunctor):
'\n A Construction Functor for Infinite Polynomial Rings (see :mod:`~sage.rings.polynomial.infinite_polynomial_ring`).\n\n AUTHOR:\n\n -- Simon King\n\n This construction functor is used to provide uniqueness of infinite polynomial rings as parent structures.\n As usual, the construction functor allows for constructing pushouts.\n\n Another purpose is to avoid name conflicts of variables of the to-be-constructed infinite polynomial ring with\n variables of the base ring, and moreover to keep the internal structure of an Infinite Polynomial Ring as simple\n as possible: If variables `v_1,...,v_n` of the given base ring generate an *ordered* sub-monoid of the monomials\n of the ambient Infinite Polynomial Ring, then they are removed from the base ring and merged with the generators\n of the ambient ring. However, if the orders don\'t match, an error is raised, since there was a name conflict\n without merging.\n\n EXAMPLES::\n\n sage: A.<a,b> = InfinitePolynomialRing(ZZ[\'t\'])\n sage: A.construction()\n [InfPoly{[a,b], "lex", "dense"},\n Univariate Polynomial Ring in t over Integer Ring]\n sage: type(_[0])\n <class \'sage.categories.pushout.InfinitePolynomialFunctor\'>\n sage: B.<x,y,a_3,a_1> = PolynomialRing(QQ, order=\'lex\')\n sage: B.construction()\n (MPoly[x,y,a_3,a_1], Rational Field)\n sage: A.construction()[0] * B.construction()[0]\n InfPoly{[a,b], "lex", "dense"}(MPoly[x,y](...))\n\n Apparently the variables `a_1,a_3` of the polynomial ring are merged with the variables\n `a_0, a_1, a_2, ...` of the infinite polynomial ring; indeed, they form an ordered sub-structure.\n However, if the polynomial ring was given a different ordering, merging would not be allowed,\n resulting in a name conflict::\n\n sage: R = PolynomialRing(QQ, names=[\'x\',\'y\',\'a_3\',\'a_1\'])\n sage: A.construction()[0] * R.construction()[0]\n Traceback (most recent call last):\n ...\n CoercionException: Incompatible term orders lex, degrevlex\n\n In an infinite polynomial ring with generator `a_\\ast`, the variable `a_3` will always be greater\n than the variable `a_1`. Hence, the orders are incompatible in the next example as well::\n\n sage: R = PolynomialRing(QQ, names=[\'x\',\'y\',\'a_1\',\'a_3\'], order=\'lex\')\n sage: A.construction()[0] * R.construction()[0]\n Traceback (most recent call last):\n ...\n CoercionException: Overlapping variables ((\'a\', \'b\'),[\'a_1\', \'a_3\'])\n are incompatible\n\n Another requirement is that after merging the order of the remaining variables must be unique.\n This is not the case in the following example, since it is not clear whether the variables `x,y`\n should be greater or smaller than the variables `b_\\ast`::\n\n sage: R = PolynomialRing(QQ, names=[\'a_3\',\'a_1\',\'x\',\'y\'], order=\'lex\')\n sage: A.construction()[0] * R.construction()[0]\n Traceback (most recent call last):\n ...\n CoercionException: Overlapping variables ((\'a\', \'b\'),[\'a_3\', \'a_1\'])\n are incompatible\n\n Since the construction functors are actually used to construct infinite polynomial rings, the following\n result is no surprise::\n\n sage: C.<a,b> = InfinitePolynomialRing(B); C\n Infinite polynomial ring in a, b\n over Multivariate Polynomial Ring in x, y over Rational Field\n\n There is also an overlap in the next example::\n\n sage: X.<w,x,y> = InfinitePolynomialRing(ZZ)\n sage: Y.<x,y,z> = InfinitePolynomialRing(QQ)\n\n `X` and `Y` have an overlapping generators `x_\\ast, y_\\ast`. Since the default lexicographic order is\n used in both rings, it gives rise to isomorphic sub-monoids in both `X` and `Y`. They are merged in the\n pushout, which also yields a common parent for doing arithmetic::\n\n sage: P = sage.categories.pushout.pushout(Y,X); P\n Infinite polynomial ring in w, x, y, z over Rational Field\n sage: w[2]+z[3]\n w_2 + z_3\n sage: _.parent() is P\n True\n\n '
rank = 9.5
def __init__(self, gens, order, implementation):
'\n TESTS::\n\n sage: F = sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'degrevlex\',\'sparse\'); F # indirect doctest\n InfPoly{[a,b,x], "degrevlex", "sparse"}\n sage: F == loads(dumps(F))\n True\n\n '
if (not gens):
raise ValueError('Infinite Polynomial Rings have at least one generator')
ConstructionFunctor.__init__(self, Rings(), Rings())
self._gens = tuple(gens)
self._order = order
self._imple = implementation
def _apply_functor_to_morphism(self, f):
'\n Morphisms for infinite polynomial rings are not implemented yet.\n\n TESTS::\n\n sage: P.<x,y> = QQ[]\n sage: R.<alpha> = InfinitePolynomialRing(P)\n sage: f = P.hom([x+y,x-y],P)\n sage: R.construction()[0](f) # indirect doctest\n Traceback (most recent call last):\n ...\n NotImplementedError: morphisms for infinite polynomial rings are not implemented yet\n '
raise NotImplementedError('morphisms for infinite polynomial rings are not implemented yet')
def _apply_functor(self, R):
'\n Apply the functor to an object of ``self``\'s domain.\n\n TESTS::\n\n sage: F = sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'degrevlex\',\'sparse\'); F\n InfPoly{[a,b,x], "degrevlex", "sparse"}\n sage: F(QQ[\'t\']) # indirect doctest\n Infinite polynomial ring in a, b, x over Univariate Polynomial Ring in t over Rational Field\n\n '
from sage.rings.polynomial.infinite_polynomial_ring import InfinitePolynomialRing
return InfinitePolynomialRing(R, self._gens, order=self._order, implementation=self._imple)
def _repr_(self):
'\n TESTS::\n\n sage: F = sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'degrevlex\',\'sparse\'); F # indirect doctest\n InfPoly{[a,b,x], "degrevlex", "sparse"}\n\n '
return ('InfPoly{[%s], "%s", "%s"}' % (','.join(self._gens), self._order, self._imple))
def __eq__(self, other):
'\n TESTS::\n\n sage: F = sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'degrevlex\',\'sparse\'); F # indirect doctest\n InfPoly{[a,b,x], "degrevlex", "sparse"}\n sage: F == loads(dumps(F)) # indirect doctest\n True\n sage: F == sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'deglex\',\'sparse\')\n False\n '
if isinstance(other, InfinitePolynomialFunctor):
return ((self._gens == other._gens) and (self._order == other._order) and (self._imple == other._imple))
return False
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: F = sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'degrevlex\',\'sparse\'); F # indirect doctest\n InfPoly{[a,b,x], "degrevlex", "sparse"}\n sage: F != loads(dumps(F)) # indirect doctest\n False\n sage: F != sage.categories.pushout.InfinitePolynomialFunctor([\'a\',\'b\',\'x\'],\'deglex\',\'sparse\')\n True\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def __mul__(self, other):
'\n Compose construction functors to a composite construction functor, unless one of them is the identity.\n\n .. NOTE::\n\n The product is in functorial notation, i.e., when applying the\n product to an object then the second factor is applied first.\n\n TESTS::\n\n sage: F1 = QQ[\'a\',\'x_2\',\'x_1\',\'y_3\',\'y_2\'].construction()[0]; F1\n MPoly[a,x_2,x_1,y_3,y_2]\n sage: F2 = InfinitePolynomialRing(QQ, [\'x\',\'y\'],order=\'degrevlex\').construction()[0]; F2\n InfPoly{[x,y], "degrevlex", "dense"}\n sage: F3 = InfinitePolynomialRing(QQ, [\'x\',\'y\'],order=\'degrevlex\',implementation=\'sparse\').construction()[0]; F3\n InfPoly{[x,y], "degrevlex", "sparse"}\n sage: F2*F1\n InfPoly{[x,y], "degrevlex", "dense"}(Poly[a](...))\n sage: F3*F1\n InfPoly{[x,y], "degrevlex", "sparse"}(Poly[a](...))\n sage: F4 = sage.categories.pushout.FractionField()\n sage: F2*F4\n InfPoly{[x,y], "degrevlex", "dense"}(FractionField(...))\n\n '
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, self.__class__):
INT = set(self._gens).intersection(other._gens)
if INT:
if (other._gens[(- len(INT)):] != self._gens[:len(INT)]):
raise CoercionException(('Overlapping variables (%s,%s) are incompatible' % (self._gens, other._gens)))
OUTGENS = (list(other._gens) + list(self._gens[len(INT):]))
else:
OUTGENS = (list(other._gens) + list(self._gens))
if (self._order != other._order):
return CompositeConstructionFunctor(other, self)
if (self._imple != other._imple):
return CompositeConstructionFunctor(other, self)
return InfinitePolynomialFunctor(OUTGENS, self._order, self._imple)
if isinstance(other, (MultiPolynomialFunctor, PolynomialFunctor)):
if isinstance(other, MultiPolynomialFunctor):
othervars = other.vars
else:
othervars = [other.var]
OverlappingVars = []
RemainingVars = list(othervars)
IsOverlap = False
BadOverlap = False
for x in othervars:
if (x.count('_') == 1):
(g, n) = x.split('_')
if n.isdigit():
if g.isalnum():
if (g in self._gens):
RemainingVars.pop(RemainingVars.index(x))
IsOverlap = True
if OverlappingVars:
(g0, n0) = OverlappingVars[(- 1)].split('_')
i = self._gens.index(g)
i0 = self._gens.index(g0)
if (i < i0):
BadOverlap = True
if ((i == i0) and (int(n) > int(n0))):
BadOverlap = True
OverlappingVars.append(x)
elif IsOverlap:
BadOverlap = True
elif IsOverlap:
BadOverlap = True
elif IsOverlap:
BadOverlap = True
elif IsOverlap:
BadOverlap = True
if BadOverlap:
raise CoercionException(('Overlapping variables (%s,%s) are incompatible' % (self._gens, OverlappingVars)))
if (len(OverlappingVars) > 1):
if (other.term_order.name() != self._order):
raise CoercionException(('Incompatible term orders %s, %s' % (self._order, other.term_order.name())))
if RemainingVars:
if (len(RemainingVars) > 1):
return CompositeConstructionFunctor(MultiPolynomialFunctor(RemainingVars, term_order=other.term_order), self)
return CompositeConstructionFunctor(PolynomialFunctor(RemainingVars[0]), self)
return self
return CompositeConstructionFunctor(other, self)
def merge(self, other):
'\n Merge two construction functors of infinite polynomial rings, regardless of monomial order and implementation.\n\n The purpose is to have a pushout (and thus, arithmetic) even in cases when the parents are isomorphic as\n rings, but not as ordered rings.\n\n EXAMPLES::\n\n sage: X.<x,y> = InfinitePolynomialRing(QQ, implementation=\'sparse\')\n sage: Y.<x,y> = InfinitePolynomialRing(QQ, order=\'degrevlex\')\n sage: X.construction()\n [InfPoly{[x,y], "lex", "sparse"}, Rational Field]\n sage: Y.construction()\n [InfPoly{[x,y], "degrevlex", "dense"}, Rational Field]\n sage: Y.construction()[0].merge(Y.construction()[0])\n InfPoly{[x,y], "degrevlex", "dense"}\n sage: y[3] + X(x[2])\n x_2 + y_3\n sage: _.parent().construction()\n [InfPoly{[x,y], "degrevlex", "dense"}, Rational Field]\n\n '
if (not isinstance(other, InfinitePolynomialFunctor)):
return None
if set(other._gens).issubset(self._gens):
return self
return None
try:
OUT = (self * other)
if (not isinstance(OUT, CompositeConstructionFunctor)):
return OUT
except CoercionException:
pass
if isinstance(other, InfinitePolynomialFunctor):
for g in other._gens:
if (g not in self._gens):
return None
Ind = [self._gens.index(g) for g in other._gens]
if (sorted(Ind) != Ind):
return None
if (self._imple != other._imple):
return InfinitePolynomialFunctor(self._gens, self._order, 'dense')
return self
return None
def expand(self):
'\n Decompose the functor `F` into sub-functors, whose product returns `F`.\n\n EXAMPLES::\n\n sage: A = InfinitePolynomialRing(QQ, [\'x\',\'y\'], order=\'degrevlex\')\n sage: F = A.construction()[0]; F\n InfPoly{[x,y], "degrevlex", "dense"}\n sage: F.expand()\n [InfPoly{[y], "degrevlex", "dense"}, InfPoly{[x], "degrevlex", "dense"}]\n sage: A = InfinitePolynomialRing(QQ, [\'x\',\'y\',\'z\'], order=\'degrevlex\')\n sage: F = A.construction()[0]; F\n InfPoly{[x,y,z], "degrevlex", "dense"}\n sage: F.expand()\n [InfPoly{[z], "degrevlex", "dense"},\n InfPoly{[y], "degrevlex", "dense"},\n InfPoly{[x], "degrevlex", "dense"}]\n sage: prod(F.expand())==F\n True\n\n '
if (len(self._gens) == 1):
return [self]
return [InfinitePolynomialFunctor((x,), self._order, self._imple) for x in reversed(self._gens)]
|
class MatrixFunctor(ConstructionFunctor):
'\n A construction functor for matrices over rings.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(ZZ, 2, 3)\n sage: F = MS.construction()[0]; F\n MatrixFunctor\n sage: MS = MatrixSpace(ZZ, 2)\n sage: F = MS.construction()[0]; F\n MatrixFunctor\n sage: P.<x,y> = QQ[]\n sage: R = F(P); R\n Full MatrixSpace of 2 by 2 dense matrices\n over Multivariate Polynomial Ring in x, y over Rational Field\n sage: f = P.hom([x+y, x-y], P); F(f)\n Ring endomorphism\n of Full MatrixSpace of 2 by 2 dense matrices\n over Multivariate Polynomial Ring in x, y over Rational Field\n Defn: Induced from base ring by\n Ring endomorphism\n of Multivariate Polynomial Ring in x, y over Rational Field\n Defn: x |--> x + y\n y |--> x - y\n sage: M = R([x, y, x*y, x + y])\n sage: F(f)(M)\n [ x + y x - y]\n [x^2 - y^2 2*x]\n\n '
rank = 10
def __init__(self, nrows, ncols, is_sparse=False):
'\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import MatrixFunctor\n sage: F = MatrixFunctor(2, 3)\n sage: F == MatrixSpace(ZZ, 2, 3).construction()[0]\n True\n sage: F.codomain()\n Category of commutative additive groups\n sage: R = MatrixSpace(ZZ, 2, 2).construction()[0]\n sage: R.codomain()\n Category of rings\n sage: F(ZZ)\n Full MatrixSpace of 2 by 3 dense matrices over Integer Ring\n sage: F(ZZ) in F.codomain()\n True\n sage: R(GF(2))\n Full MatrixSpace of 2 by 2 dense matrices over Finite Field of size 2\n sage: R(GF(2)) in R.codomain()\n True\n '
if (nrows == ncols):
Functor.__init__(self, Rings(), Rings())
else:
Functor.__init__(self, Rings(), CommutativeAdditiveGroups())
self.nrows = nrows
self.ncols = ncols
self.is_sparse = is_sparse
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS:\n\n The following is a test against a bug discussed at :trac:`8800`::\n\n sage: F = MatrixSpace(ZZ, 2, 3).construction()[0] # needs sage.modules\n sage: F(RR) # indirect doctest # needs sage.modules\n Full MatrixSpace of 2 by 3 dense matrices over Real Field with 53 bits of precision\n sage: F(RR) in F.codomain() # needs sage.modules\n True\n\n "
from sage.matrix.matrix_space import MatrixSpace
return MatrixSpace(R, self.nrows, self.ncols, sparse=self.is_sparse)
def __eq__(self, other):
'\n TESTS::\n\n sage: F = MatrixSpace(ZZ, 2, 3).construction()[0] # needs sage.modules\n sage: F == loads(dumps(F)) # needs sage.modules\n True\n sage: F == MatrixSpace(ZZ, 2, 2).construction()[0] # needs sage.modules\n False\n '
if isinstance(other, MatrixFunctor):
return ((self.nrows == other.nrows) and (self.ncols == other.ncols))
return False
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: F = MatrixSpace(ZZ, 2, 3).construction()[0] # needs sage.modules\n sage: F != loads(dumps(F)) # needs sage.modules\n False\n sage: F != MatrixSpace(ZZ, 2, 2).construction()[0] # needs sage.modules\n True\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
'\n Merging is only happening if both functors are matrix functors of the same dimension.\n\n The result is sparse if and only if both given functors are sparse.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F1 = MatrixSpace(ZZ, 2, 2).construction()[0]\n sage: F2 = MatrixSpace(ZZ, 2, 3).construction()[0]\n sage: F3 = MatrixSpace(ZZ, 2, 2, sparse=True).construction()[0]\n sage: F1.merge(F2)\n sage: F1.merge(F3)\n MatrixFunctor\n sage: F13 = F1.merge(F3)\n sage: F13.is_sparse\n False\n sage: F1.is_sparse\n False\n sage: F3.is_sparse\n True\n sage: F3.merge(F3).is_sparse\n True\n\n '
if (self != other):
return None
else:
return MatrixFunctor(self.nrows, self.ncols, (self.is_sparse and other.is_sparse))
|
class LaurentPolynomialFunctor(ConstructionFunctor):
'\n Construction functor for Laurent polynomial rings.\n\n EXAMPLES::\n\n sage: L.<t> = LaurentPolynomialRing(ZZ)\n sage: F = L.construction()[0]\n sage: F\n LaurentPolynomialFunctor\n sage: F(QQ)\n Univariate Laurent Polynomial Ring in t over Rational Field\n sage: K.<x> = LaurentPolynomialRing(ZZ)\n sage: F(K)\n Univariate Laurent Polynomial Ring in t\n over Univariate Laurent Polynomial Ring in x over Integer Ring\n sage: P.<x,y> = ZZ[]\n sage: f = P.hom([x + 2*y, 3*x - y],P)\n sage: F(f)\n Ring endomorphism of Univariate Laurent Polynomial Ring in t\n over Multivariate Polynomial Ring in x, y over Integer Ring\n Defn: Induced from base ring by\n Ring endomorphism of Multivariate Polynomial Ring in x, y over Integer Ring\n Defn: x |--> x + 2*y\n y |--> 3*x - y\n sage: F(f)(x*F(P).gen()^-2 + y*F(P).gen()^3)\n (x + 2*y)*t^-2 + (3*x - y)*t^3\n\n '
rank = 9
def __init__(self, var, multi_variate=False):
"\n INPUT:\n\n - ``var``, a string or a list of strings\n - ``multi_variate``, optional bool, default ``False`` if ``var`` is a string\n and ``True`` otherwise: If ``True``, application to a Laurent polynomial\n ring yields a multivariate Laurent polynomial ring.\n\n TESTS::\n\n sage: from sage.categories.pushout import LaurentPolynomialFunctor\n sage: F1 = LaurentPolynomialFunctor('t')\n sage: F2 = LaurentPolynomialFunctor('s', multi_variate=True)\n sage: F3 = LaurentPolynomialFunctor(['s','t'])\n sage: F1(F2(QQ))\n Univariate Laurent Polynomial Ring in t over\n Univariate Laurent Polynomial Ring in s over Rational Field\n sage: F2(F1(QQ)) # needs sage.modules\n Multivariate Laurent Polynomial Ring in t, s over Rational Field\n sage: F3(QQ) # needs sage.modules\n Multivariate Laurent Polynomial Ring in s, t over Rational Field\n\n "
Functor.__init__(self, Rings(), Rings())
if (not isinstance(var, (str, tuple, list))):
raise TypeError('variable name or list of variable names expected')
self.var = var
self.multi_variate = (multi_variate or (not isinstance(var, str)))
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: from sage.categories.pushout import LaurentPolynomialFunctor\n sage: F1 = LaurentPolynomialFunctor('t')\n sage: F2 = LaurentPolynomialFunctor('s', multi_variate=True)\n sage: F3 = LaurentPolynomialFunctor(['s','t'])\n sage: F1(F2(QQ)) # indirect doctest\n Univariate Laurent Polynomial Ring in t over\n Univariate Laurent Polynomial Ring in s over Rational Field\n sage: F2(F1(QQ)) # needs sage.modules\n Multivariate Laurent Polynomial Ring in t, s over Rational Field\n sage: F3(QQ) # needs sage.modules\n Multivariate Laurent Polynomial Ring in s, t over Rational Field\n\n "
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
from sage.rings.polynomial.laurent_polynomial_ring_base import LaurentPolynomialRing_generic
if (self.multi_variate and isinstance(R, LaurentPolynomialRing_generic)):
return LaurentPolynomialRing(R.base_ring(), (list(R.variable_names()) + [self.var]))
else:
return LaurentPolynomialRing(R, self.var)
def __eq__(self, other):
"\n TESTS::\n\n sage: from sage.categories.pushout import LaurentPolynomialFunctor\n sage: F1 = LaurentPolynomialFunctor('t')\n sage: F2 = LaurentPolynomialFunctor('t', multi_variate=True)\n sage: F3 = LaurentPolynomialFunctor(['s','t'])\n sage: F1 == F2\n True\n sage: F1 == loads(dumps(F1))\n True\n sage: F1 == F3\n False\n sage: F1 == QQ.construction()[0]\n False\n "
if isinstance(other, LaurentPolynomialFunctor):
return (self.var == other.var)
return False
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import LaurentPolynomialFunctor\n sage: F1 = LaurentPolynomialFunctor('t')\n sage: F2 = LaurentPolynomialFunctor('t', multi_variate=True)\n sage: F3 = LaurentPolynomialFunctor(['s','t'])\n sage: F1 != F2\n False\n sage: F1 != loads(dumps(F1))\n False\n sage: F1 != F3\n True\n sage: F1 != QQ.construction()[0]\n True\n "
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Two Laurent polynomial construction functors merge if the variable names coincide.\n\n The result is multivariate if one of the arguments is multivariate.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import LaurentPolynomialFunctor\n sage: F1 = LaurentPolynomialFunctor('t')\n sage: F2 = LaurentPolynomialFunctor('t', multi_variate=True)\n sage: F1.merge(F2)\n LaurentPolynomialFunctor\n sage: F1.merge(F2)(LaurentPolynomialRing(GF(2), 'a')) # needs sage.modules\n Multivariate Laurent Polynomial Ring in a, t over Finite Field of size 2\n sage: F1.merge(F1)(LaurentPolynomialRing(GF(2), 'a')) # needs sage.modules\n Univariate Laurent Polynomial Ring in t over\n Univariate Laurent Polynomial Ring in a over Finite Field of size 2\n\n "
if ((self == other) or (isinstance(other, PolynomialFunctor) and (self.var == other.var))):
return LaurentPolynomialFunctor(self.var, (self.multi_variate or other.multi_variate))
else:
return None
|
class VectorFunctor(ConstructionFunctor):
"\n A construction functor for free modules over commutative rings.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = (ZZ^3).construction()[0]\n sage: F\n VectorFunctor\n sage: F(GF(2)['t']) # needs sage.libs.ntl\n Ambient free module of rank 3\n over the principal ideal domain Univariate Polynomial Ring in t\n over Finite Field of size 2 (using GF2X)\n "
rank = 10
def __init__(self, n=None, is_sparse=False, inner_product_matrix=None, *, with_basis='standard', basis_keys=None, name_mapping=None, latex_name_mapping=None):
'\n INPUT:\n\n - ``n``, the rank of the to-be-created modules (non-negative integer)\n - ``is_sparse`` (optional bool, default ``False``), create sparse implementation of modules\n - ``inner_product_matrix``: ``n`` by ``n`` matrix, used to compute inner products in the\n to-be-created modules\n - ``name_mapping``, ``latex_name_mapping``: Dictionaries from base rings to names\n - other keywords: see :func:`~sage.modules.free_module.FreeModule`\n\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import VectorFunctor\n sage: F1 = VectorFunctor(3, inner_product_matrix=Matrix(3, 3, range(9)))\n sage: F1.domain()\n Category of commutative rings\n sage: F1.codomain()\n Category of commutative additive groups\n sage: M1 = F1(ZZ)\n sage: M1.is_sparse()\n False\n sage: v = M1([3, 2, 1])\n sage: v * Matrix(3, 3, range(9)) * v.column()\n (96)\n sage: v.inner_product(v)\n 96\n sage: F2 = VectorFunctor(3, is_sparse=True)\n sage: M2 = F2(QQ); M2; M2.is_sparse()\n Sparse vector space of dimension 3 over Rational Field\n True\n\n '
Functor.__init__(self, CommutativeRings(), CommutativeAdditiveGroups())
self.n = n
self.is_sparse = is_sparse
self.inner_product_matrix = inner_product_matrix
self.with_basis = with_basis
self.basis_keys = basis_keys
if (name_mapping is None):
name_mapping = {}
self.name_mapping = name_mapping
if (latex_name_mapping is None):
latex_name_mapping = {}
self.latex_name_mapping = latex_name_mapping
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import VectorFunctor, pushout\n sage: F1 = VectorFunctor(3, inner_product_matrix=Matrix(3, 3, range(9)))\n sage: M1 = F1(ZZ) # indirect doctest\n sage: M1.is_sparse()\n False\n sage: v = M1([3, 2, 1])\n sage: v * Matrix(3, 3, range(9)) * v.column()\n (96)\n sage: v.inner_product(v)\n 96\n sage: F2 = VectorFunctor(3, is_sparse=True)\n sage: M2 = F2(QQ); M2; M2.is_sparse()\n Sparse vector space of dimension 3 over Rational Field\n True\n sage: v = M2([3, 2, 1])\n sage: v.inner_product(v)\n 14\n\n sage: # needs sage.modules\n sage: M = FreeModule(ZZ, 4, with_basis=None, name='M')\n sage: latex(M)\n M\n sage: M_QQ = pushout(M, QQ)\n sage: latex(M_QQ)\n M \\otimes \\Bold{Q}\n\n "
from sage.modules.free_module import FreeModule
name = self.name_mapping.get(R, None)
latex_name = self.latex_name_mapping.get(R, None)
if (name is None):
for (base_ring, name) in self.name_mapping.items():
name = f'{name}_base_ext'
break
if (latex_name is None):
from sage.misc.latex import latex
for (base_ring, latex_name) in self.latex_name_mapping.items():
latex_name = f'{latex_name} \otimes {latex(R)}'
break
if ((name is None) and (latex_name is None)):
return FreeModule(R, self.n, sparse=self.is_sparse, inner_product_matrix=self.inner_product_matrix, with_basis=self.with_basis, basis_keys=self.basis_keys)
return FreeModule(R, self.n, sparse=self.is_sparse, inner_product_matrix=self.inner_product_matrix, with_basis=self.with_basis, basis_keys=self.basis_keys, name=name, latex_name=latex_name)
def _apply_functor_to_morphism(self, f):
'\n This is not implemented yet.\n\n TESTS::\n\n sage: F = (ZZ^3).construction()[0] # needs sage.modules\n sage: P.<x,y> = ZZ[]\n sage: f = P.hom([x + 2*y, 3*x - y], P)\n sage: F(f) # indirect doctest # needs sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: Cannot create induced morphisms of free modules yet\n '
raise NotImplementedError('Cannot create induced morphisms of free modules yet')
def __eq__(self, other):
'\n The rank and the inner product matrix are compared.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import VectorFunctor\n sage: F1 = VectorFunctor(3, inner_product_matrix=Matrix(3, 3, range(9)))\n sage: F2 = (ZZ^3).construction()[0]\n sage: F1 == F2\n False\n sage: F1(QQ) == F2(QQ)\n False\n sage: F1 == loads(dumps(F1))\n True\n '
if isinstance(other, VectorFunctor):
return ((self.n == other.n) and (self.inner_product_matrix == other.inner_product_matrix) and (self.with_basis == other.with_basis) and (self.basis_keys == other.basis_keys) and (self.name_mapping == other.name_mapping) and (self.latex_name_mapping == other.latex_name_mapping))
return False
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import VectorFunctor\n sage: F1 = VectorFunctor(3, inner_product_matrix=Matrix(3, 3, range(9)))\n sage: F2 = (ZZ^3).construction()[0]\n sage: F1 != F2\n True\n sage: F1(QQ) != F2(QQ)\n True\n sage: F1 != loads(dumps(F1))\n False\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Two constructors of free modules merge, if the module ranks and the inner products coincide. If both\n have explicitly given inner product matrices, they must coincide as well.\n\n EXAMPLES:\n\n Two modules without explicitly given inner product allow coercion::\n\n sage: M1 = QQ^3 # needs sage.modules\n sage: P.<t> = ZZ[]\n sage: M2 = FreeModule(P, 3) # needs sage.modules\n sage: M1([1,1/2,1/3]) + M2([t,t^2+t,3]) # indirect doctest # needs sage.modules\n (t + 1, t^2 + t + 1/2, 10/3)\n\n If only one summand has an explicit inner product, the result will be provided\n with it::\n\n sage: M3 = FreeModule(P, 3, inner_product_matrix=Matrix(3, 3, range(9))) # needs sage.modules\n sage: M1([1,1/2,1/3]) + M3([t,t^2+t,3]) # needs sage.modules\n (t + 1, t^2 + t + 1/2, 10/3)\n sage: (M1([1,1/2,1/3]) + M3([t,t^2+t,3])).parent().inner_product_matrix() # needs sage.modules\n [0 1 2]\n [3 4 5]\n [6 7 8]\n\n If both summands have an explicit inner product (even if it is the standard\n inner product), then the products must coincide. The only difference between\n ``M1`` and ``M4`` in the following example is the fact that the default\n inner product was *explicitly* requested for ``M4``. It is therefore not\n possible to coerce with a different inner product::\n\n sage: # needs sage.modules\n sage: M4 = FreeModule(QQ, 3, inner_product_matrix=Matrix(3, 3, 1))\n sage: M4 == M1\n True\n sage: M4.inner_product_matrix() == M1.inner_product_matrix()\n True\n sage: M4([1,1/2,1/3]) + M3([t,t^2+t,3]) # indirect doctest\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand parent(s) for +:\n 'Ambient quadratic space of dimension 3 over Rational Field\n Inner product matrix:\n [1 0 0]\n [0 1 0]\n [0 0 1]' and\n 'Ambient free quadratic module of rank 3 over the integral domain\n Univariate Polynomial Ring in t over Integer Ring\n Inner product matrix:\n [0 1 2]\n [3 4 5]\n [6 7 8]'\n\n Names are removed when they conflict::\n\n sage: # needs sage.modules\n sage: from sage.categories.pushout import VectorFunctor, pushout\n sage: M_ZZx = FreeModule(ZZ['x'], 4, with_basis=None, name='M_ZZx')\n sage: N_ZZx = FreeModule(ZZ['x'], 4, with_basis=None, name='N_ZZx')\n sage: pushout(M_ZZx, QQ)\n Rank-4 free module M_ZZx_base_ext\n over the Univariate Polynomial Ring in x over Rational Field\n sage: pushout(M_ZZx, N_ZZx)\n Rank-4 free module\n over the Univariate Polynomial Ring in x over Integer Ring\n sage: pushout(pushout(M_ZZx, N_ZZx), QQ)\n Rank-4 free module\n over the Univariate Polynomial Ring in x over Rational Field\n "
if (not isinstance(other, VectorFunctor)):
return None
if (self.with_basis != other.with_basis):
return None
else:
with_basis = self.with_basis
if (self.basis_keys != other.basis_keys):
return None
else:
basis_keys = self.basis_keys
is_sparse = (self.is_sparse and other.is_sparse)
if (self.inner_product_matrix is None):
inner_product_matrix = other.inner_product_matrix
elif (other.inner_product_matrix is None):
inner_product_matrix = self.inner_product_matrix
elif (self.inner_product_matrix != other.inner_product_matrix):
return None
else:
inner_product_matrix = None
if (self.n != other.n):
return None
else:
n = self.n
name_mapping = {}
for (base_ring, name) in self.name_mapping.items():
try:
other_name = other.name_mapping[base_ring]
except KeyError:
name_mapping[base_ring] = name
else:
if (name == other_name):
name_mapping[base_ring] = name
latex_name_mapping = {}
for (base_ring, latex_name) in self.latex_name_mapping.items():
try:
other_latex_name = other.latex_name_mapping[base_ring]
except KeyError:
latex_name_mapping[base_ring] = latex_name
else:
if (latex_name == other_latex_name):
latex_name_mapping[base_ring] = latex_name
return VectorFunctor(n, is_sparse, inner_product_matrix, with_basis=with_basis, basis_keys=basis_keys, name_mapping=name_mapping, latex_name_mapping=latex_name_mapping)
|
class SubspaceFunctor(ConstructionFunctor):
'\n Constructing a subspace of an ambient free module, given by a basis.\n\n .. NOTE::\n\n This construction functor keeps track of the basis. It can only be\n applied to free modules into which this basis coerces.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: M = ZZ^3\n sage: S = M.submodule([(1,2,3), (4,5,6)]); S\n Free module of degree 3 and rank 2 over Integer Ring\n Echelon basis matrix:\n [1 2 3]\n [0 3 6]\n sage: F = S.construction()[0]\n sage: F(GF(2)^3)\n Vector space of degree 3 and dimension 2 over Finite Field of size 2\n User basis matrix:\n [1 0 1]\n [0 1 0]\n\n '
rank = 11
coercion_reversed = True
def __init__(self, basis):
'\n INPUT:\n\n ``basis``: a list of elements of a free module.\n\n TESTS::\n\n sage: from sage.categories.pushout import SubspaceFunctor\n sage: M = ZZ^3 # needs sage.modules\n sage: F = SubspaceFunctor([M([1,2,3]), M([4,5,6])]) # needs sage.modules\n sage: F(GF(5)^3) # needs sage.modules\n Vector space of degree 3 and dimension 2 over Finite Field of size 5\n User basis matrix:\n [1 2 3]\n [4 0 1]\n '
Functor.__init__(self, CommutativeAdditiveGroups(), CommutativeAdditiveGroups())
self.basis = basis
def _apply_functor(self, ambient):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: M = ZZ^3\n sage: S = M.submodule([(1,2,3), (4,5,6)]); S\n Free module of degree 3 and rank 2 over Integer Ring\n Echelon basis matrix:\n [1 2 3]\n [0 3 6]\n sage: F = S.construction()[0]\n sage: F(GF(2)^3) # indirect doctest\n Vector space of degree 3 and dimension 2 over Finite Field of size 2\n User basis matrix:\n [1 0 1]\n [0 1 0]\n "
return ambient.span_of_basis(self.basis)
def _apply_functor_to_morphism(self, f):
'\n This is not implemented yet.\n\n TESTS::\n\n sage: # needs sage.modules\n sage: F = (ZZ^3).span([(1,2,3), (4,5,6)]).construction()[0]\n sage: P.<x,y> = ZZ[]\n sage: f = P.hom([x + 2*y, 3*x - y],P)\n sage: F(f) # indirect doctest\n Traceback (most recent call last):\n ...\n NotImplementedError: Cannot create morphisms of free sub-modules yet\n '
raise NotImplementedError('Cannot create morphisms of free sub-modules yet')
def __eq__(self, other):
'\n TESTS::\n\n sage: # needs sage.modules\n sage: F1 = (GF(5)^3).span([(1,2,3),(4,5,6)]).construction()[0]\n sage: F2 = (ZZ^3).span([(1,2,3),(4,5,6)]).construction()[0]\n sage: F3 = (QQ^3).span([(1,2,3),(4,5,6)]).construction()[0]\n sage: F4 = (ZZ^3).span([(1,0,-1),(0,1,2)]).construction()[0]\n sage: F1 == loads(dumps(F1))\n True\n\n The ``span`` method automatically transforms the given basis into\n echelon form. The bases look like that::\n\n sage: # needs sage.modules\n sage: F1.basis\n [\n (1, 0, 4),\n (0, 1, 2)\n ]\n sage: F2.basis\n [\n (1, 2, 3),\n (0, 3, 6)\n ]\n sage: F3.basis\n [\n (1, 0, -1),\n (0, 1, 2)\n ]\n sage: F4.basis\n [\n (1, 0, -1),\n (0, 1, 2)\n ]\n\n\n The basis of ``F2`` is modulo 5 different from the other bases.\n So, we have::\n\n sage: F1 != F2 != F3 # needs sage.modules\n True\n\n The bases of ``F1``, ``F3`` and ``F4`` are the same modulo 5; however,\n there is no coercion from ``QQ^3`` to ``GF(5)^3``. Therefore, we have::\n\n sage: F1 == F3 # needs sage.modules\n False\n\n But there are coercions from ``ZZ^3`` to ``QQ^3`` and ``GF(5)^3``, thus::\n\n sage: F1 == F4 == F3 # needs sage.modules\n True\n\n '
if (not isinstance(other, SubspaceFunctor)):
return False
L = self.basis.universe()
R = other.basis.universe()
c = (L == R)
if L.has_coerce_map_from(R):
return (tuple(self.basis) == tuple((L(x) for x in other.basis)))
elif R.has_coerce_map_from(L):
return (tuple(other.basis) == tuple((R(x) for x in self.basis)))
return c
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: F1 = (GF(5)^3).span([(1,2,3),(4,5,6)]).construction()[0] # needs sage.modules\n sage: F1 != loads(dumps(F1)) # needs sage.modules\n False\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Two Subspace Functors are merged into a construction functor of the sum of two subspaces.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: M = GF(5)^3\n sage: S1 = M.submodule([(1,2,3),(4,5,6)])\n sage: S2 = M.submodule([(2,2,3)])\n sage: F1 = S1.construction()[0]\n sage: F2 = S2.construction()[0]\n sage: F1.merge(F2)\n SubspaceFunctor\n sage: F1.merge(F2)(GF(5)^3) == S1 + S2\n True\n sage: F1.merge(F2)(GF(5)['t']^3)\n Free module of degree 3 and rank 3\n over Univariate Polynomial Ring in t over Finite Field of size 5\n User basis matrix:\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n TESTS::\n\n sage: # needs sage.modules\n sage: P.<t> = ZZ[]\n sage: S1 = (ZZ^3).submodule([(1,2,3), (4,5,6)])\n sage: S2 = (Frac(P)^3).submodule([(t,t^2,t^3+1), (4*t,0,1)])\n sage: v = S1([0,3,6]) + S2([2,0,1/(2*t)]); v # indirect doctest\n (2, 3, (-12*t - 1)/(-2*t))\n sage: v.parent()\n Vector space of degree 3 and dimension 3\n over Fraction Field of Univariate Polynomial Ring in t over Integer Ring\n User basis matrix:\n [1 0 0]\n [0 1 0]\n [0 0 1]\n\n "
if isinstance(other, SubspaceFunctor):
if (not other.basis):
return self
if (not self.basis):
return other
try:
P = pushout(self.basis[0].parent().ambient_module(), other.basis[0].parent().ambient_module())
except CoercionException:
return None
try:
submodule = P.span
except AttributeError:
return None
S = submodule((self.basis + other.basis)).echelonized_basis()
return SubspaceFunctor(S)
else:
return None
|
class FractionField(ConstructionFunctor):
"\n Construction functor for fraction fields.\n\n EXAMPLES::\n\n sage: F = QQ.construction()[0]\n sage: F\n FractionField\n sage: F.domain()\n Category of integral domains\n sage: F.codomain()\n Category of fields\n sage: F(GF(5)) is GF(5)\n True\n sage: F(ZZ['t'])\n Fraction Field of Univariate Polynomial Ring in t over Integer Ring\n sage: P.<x,y> = QQ[]\n sage: f = P.hom([x+2*y,3*x-y],P)\n sage: F(f)\n Ring endomorphism of\n Fraction Field of Multivariate Polynomial Ring in x, y over Rational Field\n Defn: x |--> x + 2*y\n y |--> 3*x - y\n sage: F(f)(1/x)\n 1/(x + 2*y)\n sage: F == loads(dumps(F))\n True\n\n "
rank = 5
def __init__(self):
"\n TESTS::\n\n sage: from sage.categories.pushout import FractionField\n sage: F = FractionField()\n sage: F\n FractionField\n sage: F(ZZ['t'])\n Fraction Field of Univariate Polynomial Ring in t over Integer Ring\n "
from sage.categories.fields import Fields
from sage.categories.integral_domains import IntegralDomains
Functor.__init__(self, IntegralDomains(), Fields())
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: F = QQ.construction()[0]\n sage: F(GF(5)['t']) # indirect doctest\n Fraction Field of Univariate Polynomial Ring in t\n over Finite Field of size 5\n "
return R.fraction_field()
|
class CompletionFunctor(ConstructionFunctor):
"\n Completion of a ring with respect to a given prime (including infinity).\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: R = Zp(5)\n sage: R\n 5-adic Ring with capped relative precision 20\n sage: F1 = R.construction()[0]\n sage: F1\n Completion[5, prec=20]\n sage: F1(ZZ) is R\n True\n sage: F1(QQ)\n 5-adic Field with capped relative precision 20\n\n sage: F2 = RR.construction()[0]\n sage: F2\n Completion[+Infinity, prec=53]\n sage: F2(QQ) is RR\n True\n\n sage: P.<x> = ZZ[]\n sage: Px = P.completion(x) # currently the only implemented completion of P\n sage: Px\n Power Series Ring in x over Integer Ring\n sage: F3 = Px.construction()[0]\n sage: F3(GF(3)['x'])\n Power Series Ring in x over Finite Field of size 3\n\n TESTS::\n\n sage: # needs sage.rings.padics\n sage: R1.<a> = Zp(5, prec=20)[]\n sage: R2 = Qp(5, prec=40)\n sage: R2(1) + a\n (1 + O(5^20))*a + 1 + O(5^40)\n sage: 1/2 + a\n (1 + O(5^20))*a + 3 + 2*5 + 2*5^2 + 2*5^3 + 2*5^4 + 2*5^5 + 2*5^6 + 2*5^7 + 2*5^8 + 2*5^9 + 2*5^10 + 2*5^11 + 2*5^12 + 2*5^13 + 2*5^14 + 2*5^15 + 2*5^16 + 2*5^17 + 2*5^18 + 2*5^19 + O(5^20)\n\n "
rank = 4
_real_types = ['Interval', 'Ball', 'MPFR', 'RDF', 'RLF', 'RR']
_dvr_types = [None, 'fixed-mod', 'floating-point', 'capped-abs', 'capped-rel', 'lattice-cap', 'lattice-float', 'relaxed']
def __init__(self, p, prec, extras=None):
"\n INPUT:\n\n - ``p``: A prime number, the generator of a univariate polynomial ring, or ``+Infinity``\n\n - ``prec``: an integer, yielding the precision in bits. Note that\n if ``p`` is prime then the ``prec`` is the *capped* precision,\n while it is the *set* precision if ``p`` is ``+Infinity``.\n In the ``lattice-cap`` precision case, ``prec`` will be a tuple instead.\n\n - ``extras`` (optional dictionary): Information on how to print elements, etc.\n If 'type' is given as a key, the corresponding value should be a string among\n the following:\n\n - 'RDF', 'Interval', 'RLF', or 'RR' for completions at infinity\n\n - 'capped-rel', 'capped-abs', 'fixed-mod', 'lattice-cap' or 'lattice-float'\n for completions at a finite place or ideal of a DVR.\n\n TESTS::\n\n sage: from sage.categories.pushout import CompletionFunctor\n sage: F1 = CompletionFunctor(5, 100)\n sage: F1(QQ) # needs sage.rings.padics\n 5-adic Field with capped relative precision 100\n sage: F1(ZZ) # needs sage.rings.padics\n 5-adic Ring with capped relative precision 100\n sage: F1.type is None\n True\n sage: sorted(F1.extras.items())\n []\n sage: F2 = RR.construction()[0]\n sage: F2\n Completion[+Infinity, prec=53]\n sage: F2.type # needs sage.rings.real_mpfr\n 'MPFR'\n sage: F2.extras # needs sage.rings.real_mpfr\n {'rnd': 0, 'sci_not': False}\n "
Functor.__init__(self, Rings(), Rings())
self.p = p
self.prec = prec
if (extras is None):
self.extras = {}
self.type = None
else:
self.extras = dict(extras)
self.type = self.extras.pop('type', None)
from sage.rings.infinity import Infinity
if (self.p == Infinity):
if (self.type not in self._real_types):
raise ValueError(('completion type must be one of %s' % ', '.join(self._real_types)))
elif (self.type not in self._dvr_types):
raise ValueError(('completion type must be one of %s' % ', '.join(self._dvr_types[1:])))
def _repr_(self):
'\n TESTS::\n\n sage: Zp(7).construction() # indirect doctest # needs sage.rings.padics\n (Completion[7, prec=20], Integer Ring)\n\n sage: RR.construction() # indirect doctest\n (Completion[+Infinity, prec=53], Rational Field)\n '
return ('Completion[%s, prec=%s]' % (self.p, self.prec))
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: # needs sage.rings.padics\n sage: R = Zp(5)\n sage: F1 = R.construction()[0]\n sage: F1(ZZ) is R # indirect doctest\n True\n sage: F1(QQ)\n 5-adic Field with capped relative precision 20\n\n "
try:
if (not self.extras):
if (self.type is None):
try:
return R.completion(self.p, self.prec)
except TypeError:
return R.completion(self.p, self.prec, {})
else:
return R.completion(self.p, self.prec, {'type': self.type})
else:
extras = self.extras.copy()
if (self.type is not None):
extras['type'] = self.type
return R.completion(self.p, self.prec, extras)
except (NotImplementedError, AttributeError):
if (R.construction() is None):
raise NotImplementedError(('Completion is not implemented for %s' % R.__class__))
(F, BR) = R.construction()
M = (self.merge(F) or F.merge(self))
if (M is not None):
return M(BR)
if (self.commutes(F) or F.commutes(self)):
return F(self(BR))
raise NotImplementedError(("Don't know how to apply %s to %s" % (repr(self), repr(R))))
def __eq__(self, other):
'\n .. NOTE::\n\n Only the prime used in the completion is relevant to comparison\n of Completion functors, although the resulting rings also take\n the precision into account.\n\n TESTS::\n\n sage: # needs sage.rings.padics\n sage: R1 = Zp(5, prec=30)\n sage: R2 = Zp(5, prec=40)\n sage: F1 = R1.construction()[0]\n sage: F2 = R2.construction()[0]\n sage: F1 == loads(dumps(F1)) # indirect doctest\n True\n sage: F1 == F2\n True\n sage: F1(QQ) == F2(QQ)\n False\n sage: R3 = Zp(7)\n sage: F3 = R3.construction()[0]\n sage: F1 == F3\n False\n '
if isinstance(other, CompletionFunctor):
return (self.p == other.p)
return False
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: R1 = Zp(5, prec=30)\n sage: R2 = Zp(5, prec=40)\n sage: F1 = R1.construction()[0]\n sage: F2 = R2.construction()[0]\n sage: F1 != loads(dumps(F1)) # indirect doctest\n False\n sage: F1 != F2\n False\n sage: F1(QQ) != F2(QQ)\n True\n sage: R3 = Zp(7)\n sage: F3 = R3.construction()[0]\n sage: F1 != F3\n True\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Two Completion functors are merged, if they are equal. If the precisions of\n both functors coincide, then a Completion functor is returned that results\n from updating the ``extras`` dictionary of ``self`` by ``other.extras``.\n Otherwise, if the completion is at infinity then merging does not increase\n the set precision, and if the completion is at a finite prime, merging\n does not decrease the capped precision.\n\n EXAMPLES::\n\n sage: # needs sage.rings.padics\n sage: R1.<a> = Zp(5, prec=20)[]\n sage: R2 = Qp(5, prec=40)\n sage: R2(1) + a # indirect doctest\n (1 + O(5^20))*a + 1 + O(5^40)\n sage: R3 = RealField(30)\n sage: R4 = RealField(50)\n sage: R3(1) + R4(1) # indirect doctest\n 2.0000000\n sage: (R3(1) + R4(1)).parent()\n Real Field with 30 bits of precision\n\n TESTS:\n\n We check that :trac:`12353` has been resolved::\n\n sage: RIF(1) > RR(1) # needs sage.rings.real_interval_field\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand parent(s) for >:\n 'Real Interval Field with 53 bits of precision' and 'Real Field with 53 bits of precision'\n\n We check that various pushouts work::\n\n sage: # needs sage.rings.real_interval_field sage.rings.real_mpfr\n sage: R0 = RealIntervalField(30)\n sage: R1 = RealIntervalField(30, sci_not=True)\n sage: R2 = RealIntervalField(53)\n sage: R3 = RealIntervalField(53, sci_not=True)\n sage: R4 = RealIntervalField(90)\n sage: R5 = RealIntervalField(90, sci_not=True)\n sage: R6 = RealField(30)\n sage: R7 = RealField(30, sci_not=True)\n sage: R8 = RealField(53, rnd='RNDD')\n sage: R9 = RealField(53, sci_not=True, rnd='RNDZ')\n sage: R10 = RealField(53, sci_not=True)\n sage: R11 = RealField(90, sci_not=True, rnd='RNDZ')\n sage: Rlist = [R0,R1,R2,R3,R4,R5,R6,R7,R8,R9,R10,R11]\n sage: from sage.categories.pushout import pushout\n sage: pushouts = [R0,R0,R0,R1,R0,R1,R0,R1,R0,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R1,R0,R1,R2,R2,R2,R3,R0,R1,R2,R3,R3,R3,R1,R1,R3,R3,R3,R3,R1,R1,R3,R3,R3,R3,R0,R1,R2,R3,R4,R4,R0,R1,R2,R3,R3,R5,R1,R1,R3,R3,R5,R5,R1,R1,R3,R3,R3,R5,R0,R1,R0,R1,R0,R1,R6,R6,R6,R7,R7,R7,R1,R1,R1,R1,R1,R1,R7,R7,R7,R7,R7,R7,R0,R1,R2,R3,R2,R3,R6,R7,R8,R9,R10,R9,R1,R1,R3,R3,R3,R3,R7,R7,R9,R9,R10,R9,R1,R1,R3,R3,R3,R3,R7,R7,R10,R10,R10,R10,R1,R1,R3,R3,R5,R5,R7,R7,R9,R9,R10,R11]\n sage: all(R is S for R, S in zip(pushouts, [pushout(a, b) for a in Rlist for b in Rlist]))\n True\n\n ::\n\n sage: # needs sage.rings.padics\n sage: P0 = ZpFM(5, 10)\n sage: P1 = ZpFM(5, 20)\n sage: P2 = ZpCR(5, 10)\n sage: P3 = ZpCR(5, 20)\n sage: P4 = ZpCA(5, 10)\n sage: P5 = ZpCA(5, 20)\n sage: P6 = Qp(5, 10)\n sage: P7 = Qp(5, 20)\n sage: Plist = [P2,P3,P4,P5,P6,P7]\n sage: from sage.categories.pushout import pushout\n sage: pushouts = [P2,P3,P4,P5,P6,P7,P3,P3,P5,P5,P7,P7,P4,P5,P4,P5,P6,P7,\n ....: P5,P5,P5,P5,P7,P7,P6,P7,P6,P7,P6,P7,P7,P7,P7,P7,P7,P7]\n sage: all(P is Q\n ....: for P, Q in zip(pushouts, [pushout(a, b) for a in Plist for b in Plist]))\n True\n "
if (self == other):
from sage.rings.infinity import Infinity
if (self.p == Infinity):
new_prec = min(self.prec, other.prec)
new_type = self._real_types[min(self._real_types.index(self.type), self._real_types.index(other.type))]
new_scinot = max(self.extras.get('sci_not', 0), other.extras.get('sci_not', 0))
new_rnd = min(self.extras.get('rnd', 0), other.extras.get('rnd', 0))
return CompletionFunctor(self.p, new_prec, {'type': new_type, 'sci_not': new_scinot, 'rnd': new_rnd})
else:
new_type = self._dvr_types[min(self._dvr_types.index(self.type), self._dvr_types.index(other.type))]
if (new_type in ('fixed-mod', 'floating-point')):
if (self.type != other.type):
return None
new_prec = min(self.prec, other.prec)
else:
new_prec = max(self.prec, other.prec)
extras = self.extras.copy()
extras.update(other.extras)
extras['type'] = new_type
return CompletionFunctor(self.p, new_prec, extras)
def commutes(self, other):
"\n Completion commutes with fraction fields.\n\n EXAMPLES::\n\n sage: F1 = Zp(5).construction()[0] # needs sage.rings.padics\n sage: F2 = QQ.construction()[0]\n sage: F1.commutes(F2) # needs sage.rings.padics\n True\n\n TESTS:\n\n The fraction field ``R`` in the example below has no completion\n method. But completion commutes with the fraction field functor,\n and so it is tried internally whether applying the construction\n functors in opposite order works. It does::\n\n sage: P.<x> = ZZ[]\n sage: C = P.completion(x).construction()[0]\n sage: R = FractionField(P)\n sage: hasattr(R,'completion')\n False\n sage: C(R) is Frac(C(P))\n True\n sage: F = R.construction()[0]\n sage: (C*F)(ZZ['x']) is (F*C)(ZZ['x'])\n True\n\n The following was fixed in :trac:`15329` (it used to result\n in an infinite recursion. In :trac:`23218` the construction\n of `p`-adic fields changed, so there is no longer an\n Ambiguous base extension error raised)::\n\n sage: from sage.categories.pushout import pushout\n sage: pushout(Qp(7), RLF) # needs sage.rings.padics\n Traceback (most recent call last):\n ...\n CoercionException: Don't know how to\n apply Completion[+Infinity, prec=+Infinity]\n to 7-adic Ring with capped relative precision 20\n "
return isinstance(other, FractionField)
|
class QuotientFunctor(ConstructionFunctor):
"\n Construction functor for quotient rings.\n\n .. NOTE::\n\n The functor keeps track of variable names. Optionally, it may\n keep track of additional properties of the quotient, such as\n its category or its implementation.\n\n EXAMPLES::\n\n sage: P.<x,y> = ZZ[]\n sage: Q = P.quo([x^2 + y^2] * P)\n sage: F = Q.construction()[0]\n sage: F(QQ['x','y'])\n Quotient of Multivariate Polynomial Ring in x, y over Rational Field\n by the ideal (x^2 + y^2)\n sage: F(QQ['x','y']) == QQ['x','y'].quo([x^2 + y^2] * QQ['x','y'])\n True\n sage: F(QQ['x','y','z'])\n Traceback (most recent call last):\n ...\n CoercionException: Cannot apply this quotient functor to\n Multivariate Polynomial Ring in x, y, z over Rational Field\n sage: F(QQ['y','z']) # needs sage.rings.finite_rings\n Traceback (most recent call last):\n ...\n TypeError: Could not find a mapping of the passed element to this ring.\n "
rank = 4.5
def __init__(self, I, names=None, as_field=False, domain=None, codomain=None, **kwds):
"\n INPUT:\n\n - ``I``, an ideal (the modulus)\n - ``names`` (optional string or list of strings), the names for the\n quotient ring generators\n - ``as_field`` (optional bool, default false), return the quotient\n ring as field (if available).\n - ``domain`` (optional category, default ``Rings()``), the domain of\n this functor.\n - ``codomain`` (optional category, default ``Rings()``), the codomain\n of this functor.\n - Further named arguments. In particular, an implementation of the\n quotient can be suggested here. These named arguments are passed to\n the quotient construction.\n\n TESTS::\n\n sage: from sage.categories.pushout import QuotientFunctor\n sage: P.<t> = ZZ[]\n sage: F = QuotientFunctor([5 + t^2] * P)\n sage: F(P) # needs sage.libs.pari\n Univariate Quotient Polynomial Ring in tbar\n over Integer Ring with modulus t^2 + 5\n sage: F(QQ['t']) # needs sage.libs.pari\n Univariate Quotient Polynomial Ring in tbar\n over Rational Field with modulus t^2 + 5\n sage: F = QuotientFunctor([5 + t^2] * P, names='s')\n sage: F(P) # needs sage.libs.pari\n Univariate Quotient Polynomial Ring in s\n over Integer Ring with modulus t^2 + 5\n sage: F(QQ['t']) # needs sage.libs.pari\n Univariate Quotient Polynomial Ring in s\n over Rational Field with modulus t^2 + 5\n sage: F = QuotientFunctor([5] * ZZ, as_field=True)\n sage: F(ZZ)\n Finite Field of size 5\n sage: F = QuotientFunctor([5] * ZZ)\n sage: F(ZZ)\n Ring of integers modulo 5\n\n "
if (domain is None):
domain = Rings()
if (codomain is None):
codomain = Rings()
Functor.__init__(self, domain, codomain)
self.I = I
if (names is None):
self.names = None
elif isinstance(names, str):
self.names = (names,)
else:
self.names = tuple(names)
self.as_field = as_field
self.kwds = kwds
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: P.<x,y> = ZZ[]\n sage: Q = P.quo([2 + x^2, 3*x + y^2])\n sage: F = Q.construction()[0]; F\n QuotientFunctor\n sage: F(QQ['x','y']) # indirect doctest\n Quotient of Multivariate Polynomial Ring in x, y over Rational Field\n by the ideal (x^2 + 2, y^2 + 3*x)\n\n Note that the ``quo()`` method of a field used to return the\n integer zero. That strange behaviour was removed in github\n issue :trac:`9138`. It now returns a trivial quotient ring\n when applied to a field::\n\n sage: F = ZZ.quo([5]*ZZ).construction()[0]\n sage: F(QQ)\n Ring of integers modulo 1\n sage: QQ.quo(5)\n Quotient of Rational Field by the ideal (1)\n "
I = self.I
if (not I.is_zero()):
from sage.categories.fields import Fields
if (R in Fields()):
from sage.rings.finite_rings.integer_mod_ring import Integers
return Integers(1)
if (I.ring() != R):
if I.ring().has_coerce_map_from(R):
R = I.ring()
else:
R = pushout(R, I.ring().base_ring())
I = ([(R.one() * t) for t in I.gens()] * R)
try:
Q = R.quo(I, names=self.names, **self.kwds)
except IndexError:
raise CoercionException(('Cannot apply this quotient functor to %s' % R))
if self.as_field:
try:
Q = Q.field()
except AttributeError:
pass
return Q
def __eq__(self, other):
'\n The types, domain, codomain, names and moduli are compared.\n\n TESTS::\n\n sage: # needs sage.libs.pari\n sage: P.<x> = QQ[]\n sage: F = P.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n sage: F == loads(dumps(F))\n True\n sage: P2.<x,y> = QQ[]\n sage: F == P2.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n False\n sage: P3.<x> = ZZ[]\n sage: F == P3.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n True\n '
if (not isinstance(other, QuotientFunctor)):
return False
return ((type(self) is type(other)) and (self.domain() == other.domain()) and (self.codomain() == other.codomain()) and (self.names == other.names) and (self.I == other.I))
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: P.<x> = QQ[]\n sage: F = P.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n sage: F != loads(dumps(F))\n False\n sage: P2.<x,y> = QQ[]\n sage: F != P2.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n True\n sage: P3.<x> = ZZ[]\n sage: F != P3.quo([(x^2+1)^2*(x^2-3),(x^2+1)^2*(x^5+3)]).construction()[0]\n False\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
'\n Two quotient functors with coinciding names are merged by taking the gcd\n of their moduli, the meet of their domains, and the join of their codomains.\n\n In particular, if one of the functors being merged knows that the quotient\n is going to be a field, then the merged functor will return fields as\n well.\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: P.<x> = QQ[]\n sage: Q1 = P.quo([(x^2+1)^2*(x^2-3)])\n sage: Q2 = P.quo([(x^2+1)^2*(x^5+3)])\n sage: from sage.categories.pushout import pushout\n sage: pushout(Q1,Q2) # indirect doctest\n Univariate Quotient Polynomial Ring in xbar over Rational Field\n with modulus x^4 + 2*x^2 + 1\n\n The following was fixed in :trac:`8800`::\n\n sage: pushout(GF(5), Integers(5)) # needs sage.libs.pari\n Finite Field of size 5\n\n '
if (type(self) is not type(other)):
return None
if (self.names != other.names):
return None
if (self == other):
if (self.as_field == other.as_field):
return self
I = self.I
domain = self.domain()
codomain = self.codomain()
else:
try:
I = (self.I + other.I)
except (TypeError, NotImplementedError):
try:
I = self.I.gcd(other.I)
except (TypeError, NotImplementedError):
return None
domain = self.domain().meet([self.domain(), other.domain()])
codomain = self.codomain().join([self.codomain(), other.codomain()])
as_field = (self.as_field or other.as_field)
kwds = {}
for (k, v) in self.kwds.items():
kwds[k] = v
for (k, v) in other.kwds.items():
if (k == 'category'):
if (kwds[k] is not None):
kwds[k] = v.join([v, kwds[k]])
else:
kwds[k] = v
continue
if ((k in kwds) and (kwds[k] is not None) and (v != kwds[k])):
return None
kwds[k] = v
if (I.is_trivial() and (not I.is_zero())):
raise TypeError('trivial quotient intersection')
return QuotientFunctor(I, names=self.names, as_field=as_field, domain=domain, codomain=codomain, **kwds)
|
class AlgebraicExtensionFunctor(ConstructionFunctor):
"\n Algebraic extension (univariate polynomial ring modulo principal ideal).\n\n EXAMPLES::\n\n sage: x = polygen(QQ, 'x')\n sage: K.<a> = NumberField(x^3 + x^2 + 1) # needs sage.rings.number_field\n sage: F = K.construction()[0] # needs sage.rings.number_field\n sage: F(ZZ['t']) # needs sage.rings.number_field\n Univariate Quotient Polynomial Ring in a\n over Univariate Polynomial Ring in t over Integer Ring\n with modulus a^3 + a^2 + 1\n\n Note that, even if a field is algebraically closed, the algebraic\n extension will be constructed as the quotient of a univariate\n polynomial ring::\n\n sage: F(CC) # needs sage.rings.number_field\n Univariate Quotient Polynomial Ring in a\n over Complex Field with 53 bits of precision\n with modulus a^3 + a^2 + 1.00000000000000\n sage: F(RR) # needs sage.rings.number_field\n Univariate Quotient Polynomial Ring in a\n over Real Field with 53 bits of precision\n with modulus a^3 + a^2 + 1.00000000000000\n\n Note that the construction functor of a number field applied to\n the integers returns an order (not necessarily maximal) of that\n field, similar to the behaviour of ``ZZ.extension(...)``::\n\n sage: F(ZZ) # needs sage.rings.number_field\n Order in Number Field in a with defining polynomial x^3 + x^2 + 1\n\n This also holds for non-absolute number fields::\n\n sage: # needs sage.rings.number_field\n sage: x = polygen(QQ, 'x')\n sage: K.<a,b> = NumberField([x^3 + x^2 + 1, x^2 + x + 1])\n sage: F = K.construction()[0]\n sage: O = F(ZZ); O\n Relative Order in Number Field in a\n with defining polynomial x^3 + x^2 + 1 over its base field\n sage: O.ambient() is K\n True\n\n Special cases are made for cyclotomic fields and residue fields::\n\n sage: # needs sage.rings.number_field\n sage: C = CyclotomicField(8)\n sage: F, R = C.construction()\n sage: F\n AlgebraicExtensionFunctor\n sage: R\n Rational Field\n sage: F(R)\n Cyclotomic Field of order 8 and degree 4\n sage: F(ZZ)\n Maximal Order in Cyclotomic Field of order 8 and degree 4\n\n ::\n\n sage: # needs sage.rings.number_field\n sage: K.<z> = CyclotomicField(7)\n sage: P = K.factor(17)[0][0]\n sage: k = K.residue_field(P)\n sage: F, R = k.construction()\n sage: F\n AlgebraicExtensionFunctor\n sage: R\n Cyclotomic Field of order 7 and degree 6\n sage: F(R) is k\n True\n sage: F(ZZ)\n Residue field of Integers modulo 17\n sage: F(CyclotomicField(49))\n Residue field in zbar of Fractional ideal (17)\n\n "
rank = 3
def __init__(self, polys, names, embeddings=None, structures=None, cyclotomic=None, precs=None, implementations=None, *, residue=None, latex_names=None, **kwds):
"\n INPUT:\n\n - ``polys`` -- list of polynomials (or of integers, for\n finite fields and unramified local extensions)\n\n - ``names`` -- list of strings of the same length as the\n list ``polys``\n\n - ``embeddings`` -- (optional) list of approximate complex\n values, determining an embedding of the generators into the\n complex field, or ``None`` for each generator whose\n embedding is not prescribed.\n\n - ``structures`` -- (optional) list of structural morphisms of\n number fields; see\n :class:`~sage.rings.number_field.structure.NumberFieldStructure`.\n\n - ``cyclotomic`` -- (optional) integer. If it is provided,\n application of the functor to the rational field yields a\n cyclotomic field, rather than just a number field.\n\n - ``precs`` -- (optional) list of integers. If it is provided,\n it is used to determine the precision of p-adic extensions.\n\n - ``implementations`` -- (optional) list of strings.\n If it is provided, it is used to determine an implementation in the\n p-adic case.\n\n - ``residue`` -- (optional) prime ideal of an order in a number\n field, determining a residue field. If it is provided,\n application of the functor to a number field yields the\n residue field with respect to the given prime ideal\n (coerced into the number field).\n\n - ``latex_names`` -- (optional) list of strings of the same length\n as the list ``polys``\n\n - ``**kwds`` -- further keywords; when the functor is applied\n to a ring `R`, these are passed to the ``extension()``\n method of `R`.\n\n REMARK:\n\n Currently, an embedding can only be provided for the last\n generator, and only when the construction functor is applied\n to the rational field. There will be no error when constructing\n the functor, but when applying it.\n\n TESTS::\n\n sage: from sage.categories.pushout import AlgebraicExtensionFunctor\n sage: P.<x> = ZZ[]\n sage: F1 = AlgebraicExtensionFunctor([x^3 - x^2 + 1], ['a'], [None])\n sage: F2 = AlgebraicExtensionFunctor([x^3 - x^2 + 1], ['a'], [0])\n sage: F1 == F2\n False\n sage: F1(QQ) # needs sage.rings.number_field\n Number Field in a with defining polynomial x^3 - x^2 + 1\n sage: F1(QQ).coerce_embedding() # needs sage.rings.number_field\n sage: phi = F2(QQ).coerce_embedding().__copy__(); phi # needs sage.rings.number_field\n Generic morphism:\n From: Number Field in a with defining polynomial x^3 - x^2 + 1\n with a = -0.7548776662466928?\n To: Real Lazy Field\n Defn: a -> -0.7548776662466928?\n sage: F1(QQ) == F2(QQ) # needs sage.rings.number_field\n False\n sage: F1(GF(5)) # needs sage.libs.pari\n Univariate Quotient Polynomial Ring in a over Finite Field of size 5\n with modulus a^3 + 4*a^2 + 1\n sage: F2(GF(5)) # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n NotImplementedError: ring extension with prescribed embedding is not implemented\n\n When applying a number field constructor to the ring of\n integers, an order (not necessarily maximal) of that field is\n returned, similar to the behaviour of ``ZZ.extension``::\n\n sage: F1(ZZ) # needs sage.rings.number_field\n Order in Number Field in a with defining polynomial x^3 - x^2 + 1\n\n The cyclotomic fields form a special case of number fields\n with prescribed embeddings::\n\n sage: # needs sage.rings.number_field\n sage: C = CyclotomicField(8)\n sage: F, R = C.construction()\n sage: F\n AlgebraicExtensionFunctor\n sage: R\n Rational Field\n sage: F(R)\n Cyclotomic Field of order 8 and degree 4\n sage: F(ZZ)\n Maximal Order in Cyclotomic Field of order 8 and degree 4\n\n The data stored in this construction includes structural\n morphisms of number fields (see :trac:`20826`)::\n\n sage: # needs sage.rings.number_field\n sage: R.<x> = ZZ[]\n sage: K.<a> = NumberField(x^2 - 3)\n sage: L0.<b> = K.change_names()\n sage: L0.structure()\n (Isomorphism given by variable name change map:\n From: Number Field in b with defining polynomial x^2 - 3\n To: Number Field in a with defining polynomial x^2 - 3,\n Isomorphism given by variable name change map:\n From: Number Field in a with defining polynomial x^2 - 3\n To: Number Field in b with defining polynomial x^2 - 3)\n sage: L1 = (b*x).parent().base_ring()\n sage: L1 is L0\n True\n "
Functor.__init__(self, Rings(), Rings())
if (not (isinstance(polys, (list, tuple)) and isinstance(names, (list, tuple)))):
raise ValueError('Arguments must be lists or tuples')
n = len(polys)
if (embeddings is None):
embeddings = ([None] * n)
if (structures is None):
structures = ([None] * n)
if (precs is None):
precs = ([None] * n)
if (implementations is None):
implementations = ([None] * n)
if (latex_names is None):
latex_names = ([None] * n)
if (not (len(names) == len(embeddings) == len(structures) == len(latex_names) == n)):
raise ValueError('All arguments must be of the same length')
self.polys = list(polys)
self.names = list(names)
self.embeddings = list(embeddings)
self.structures = list(structures)
self.cyclotomic = (int(cyclotomic) if (cyclotomic is not None) else None)
self.precs = list(precs)
self.implementations = list(implementations)
self.residue = residue
latex_names = list(latex_names)
for (i, name) in enumerate(self.names):
if (latex_names[i] is not None):
from sage.misc.latex import latex_variable_name
if (latex_names[i] == latex_variable_name(name)):
latex_names[i] = None
self.latex_names = latex_names
self.kwds = kwds
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: # needs sage.rings.number_field\n sage: x = polygen(QQ, 'x')\n sage: K.<a> = NumberField(x^3 + x^2 + 1)\n sage: F = K.construction()[0]\n sage: F(ZZ) # indirect doctest\n Order in Number Field in a with defining polynomial x^3 + x^2 + 1\n sage: F(ZZ['t']) # indirect doctest\n Univariate Quotient Polynomial Ring in a over\n Univariate Polynomial Ring in t over Integer Ring with modulus a^3 + a^2 + 1\n sage: F(RR) # indirect doctest\n Univariate Quotient Polynomial Ring in a over\n Real Field with 53 bits of precision with modulus a^3 + a^2 + 1.00000000000000\n\n Check that :trac:`13538` is fixed::\n\n sage: # needs sage.rings.padics\n sage: from sage.categories.pushout import AlgebraicExtensionFunctor\n sage: K = Qp(3, 3)\n sage: R.<a> = K[]\n sage: AEF = AlgebraicExtensionFunctor([a^2 - 3], ['a'], [None])\n sage: AEF(K)\n 3-adic Eisenstein Extension Field in a defined by a^2 - 3\n\n "
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
if self.cyclotomic:
from sage.rings.number_field.number_field import CyclotomicField
if (R == QQ):
return CyclotomicField(self.cyclotomic)
if (R == ZZ):
return CyclotomicField(self.cyclotomic).maximal_order()
elif (self.residue is not None):
return R.residue_field((R * self.residue), names=tuple(self.names))
if (len(self.polys) == 1):
return R.extension(self.polys[0], names=self.names[0], embedding=self.embeddings[0], structure=self.structures[0], prec=self.precs[0], implementation=self.implementations[0], latex_names=self.latex_names[0], **self.kwds)
return R.extension(self.polys, names=self.names, embedding=self.embeddings, structure=self.structures, prec=self.precs, implementation=self.implementations, latex_names=self.latex_names, **self.kwds)
def __eq__(self, other):
"\n Check whether ``self`` is equal to ``other``.\n\n TESTS::\n\n sage: # needs sage.rings.number_field\n sage: x = polygen(QQ, 'x')\n sage: K.<a> = NumberField(x^3 + x^2 + 1)\n sage: F = K.construction()[0]\n sage: F == loads(dumps(F))\n True\n\n sage: K2.<a> = NumberField(x^3 + x^2 + 1, latex_names='a') # needs sage.rings.number_field\n sage: F2 = K2.construction()[0] # needs sage.rings.number_field\n sage: F2 == F # needs sage.rings.number_field\n True\n\n sage: K3.<a> = NumberField(x^3 + x^2 + 1, latex_names='alpha') # needs sage.rings.number_field\n sage: F3 = K3.construction()[0] # needs sage.rings.number_field\n sage: F3 == F # needs sage.rings.number_field\n False\n "
if (not isinstance(other, AlgebraicExtensionFunctor)):
return False
return ((self.polys == other.polys) and (self.embeddings == other.embeddings) and (self.structures == other.structures) and (self.precs == other.precs) and (self.latex_names == other.latex_names))
def __ne__(self, other):
"\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: x = polygen(QQ, 'x')\n sage: K.<a> = NumberField(x^3 + x^2 + 1) # needs sage.rings.number_field\n sage: F = K.construction()[0] # needs sage.rings.number_field\n sage: F != loads(dumps(F)) # needs sage.rings.number_field\n False\n "
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
def merge(self, other):
"\n Merging with another :class:`AlgebraicExtensionFunctor`.\n\n INPUT:\n\n ``other`` -- Construction Functor.\n\n OUTPUT:\n\n - If ``self==other``, ``self`` is returned.\n - If ``self`` and ``other`` are simple extensions\n and both provide an embedding, then it is tested\n whether one of the number fields provided by\n the functors coerces into the other; the functor\n associated with the target of the coercion is\n returned. Otherwise, the construction functor\n associated with the pushout of the codomains\n of the two embeddings is returned, provided that\n it is a number field.\n - If these two extensions are defined by Conway polynomials\n over finite fields, merges them into a single extension of\n degree the lcm of the two degrees.\n - Otherwise, ``None`` is returned.\n\n REMARK:\n\n Algebraic extension with embeddings currently only\n works when applied to the rational field. This is\n why we use the admittedly strange rule above for\n merging.\n\n EXAMPLES:\n\n The following demonstrate coercions for finite fields using Conway or\n pseudo-Conway polynomials::\n\n sage: k = GF(3^2, prefix='z'); a = k.gen() # needs sage.rings.finite_rings\n sage: l = GF(3^3, prefix='z'); b = l.gen() # needs sage.rings.finite_rings\n sage: a + b # indirect doctest # needs sage.rings.finite_rings\n z6^5 + 2*z6^4 + 2*z6^3 + z6^2 + 2*z6 + 1\n\n Note that embeddings are compatible in lattices of such finite fields::\n\n sage: # needs sage.rings.finite_rings\n sage: m = GF(3^5, prefix='z'); c = m.gen()\n sage: (a + b) + c == a + (b + c) # indirect doctest\n True\n sage: from sage.categories.pushout import pushout\n sage: n = pushout(k, l)\n sage: o = pushout(l, m)\n sage: q = pushout(n, o)\n sage: q(o(b)) == q(n(b)) # indirect doctest\n True\n\n Coercion is also available for number fields::\n\n sage: # needs sage.rings.number_field\n sage: P.<x> = QQ[]\n sage: L.<b> = NumberField(x^8 - x^4 + 1, embedding=CDF.0)\n sage: M1.<c1> = NumberField(x^2 + x + 1, embedding=b^4 - 1)\n sage: M2.<c2> = NumberField(x^2 + 1, embedding=-b^6)\n sage: M1.coerce_map_from(M2)\n sage: M2.coerce_map_from(M1)\n sage: c1 + c2; parent(c1 + c2) #indirect doctest\n -b^6 + b^4 - 1\n Number Field in b with defining polynomial x^8 - x^4 + 1\n with b = -0.2588190451025208? + 0.9659258262890683?*I\n sage: pushout(M1['x'], M2['x']) # needs sage.rings.finite_rings\n Univariate Polynomial Ring in x\n over Number Field in b with defining polynomial x^8 - x^4 + 1\n with b = -0.2588190451025208? + 0.9659258262890683?*I\n\n In the previous example, the number field ``L`` becomes the pushout\n of ``M1`` and ``M2`` since both are provided with an embedding into\n ``L``, *and* since ``L`` is a number field. If two number fields\n are embedded into a field that is not a numberfield, no merging\n occurs::\n\n sage: # needs sage.rings.complex_double sage.rings.number_field\n sage: cbrt2 = CDF(2)^(1/3)\n sage: zeta3 = CDF.zeta(3)\n sage: K.<a> = NumberField(x^3 - 2, embedding=cbrt2 * zeta3)\n sage: L.<b> = NumberField(x^6 - 2, embedding=1.1)\n sage: L.coerce_map_from(K)\n sage: K.coerce_map_from(L)\n sage: pushout(K, L) # needs sage.rings.finite_rings\n Traceback (most recent call last):\n ...\n CoercionException: ('Ambiguous Base Extension', Number Field in a with\n defining polynomial x^3 - 2 with a = -0.6299605249474365? + 1.091123635971722?*I,\n Number Field in b with defining polynomial x^6 - 2 with b = 1.122462048309373?)\n\n "
if isinstance(other, AlgebraicClosureFunctor):
return other
elif (not isinstance(other, AlgebraicExtensionFunctor)):
return None
if (self == other):
return self
if (not (len(self.names) == 1 == len(other.names))):
return None
if ((self.embeddings != [None]) and (other.embeddings != [None])):
from sage.rings.rational_field import QQ
KS = self(QQ)
KO = other(QQ)
if KS.has_coerce_map_from(KO):
return self
if KO.has_coerce_map_from(KS):
return other
try:
P = pushout(self.embeddings[0].parent(), other.embeddings[0].parent())
from sage.rings.number_field.number_field_base import NumberField
if isinstance(P, NumberField):
return P.construction()[0]
except CoercionException:
return None
from sage.rings.integer import Integer
kwds_self = dict(self.kwds.items())
if ('impl' in kwds_self):
del kwds_self['impl']
kwds_other = dict(other.kwds.items())
if ('impl' in kwds_other):
del kwds_other['impl']
if (isinstance(self.polys[0], Integer) and isinstance(other.polys[0], Integer) and (self.embeddings == other.embeddings == [None]) and (self.structures == other.structures == [None]) and (kwds_self == kwds_other)):
return AlgebraicExtensionFunctor([self.polys[0].lcm(other.polys[0])], [None], **kwds_self)
def __mul__(self, other):
'\n Compose construction functors to a composite construction functor, unless one of them is the identity.\n\n .. NOTE::\n\n The product is in functorial notation, i.e., when applying the\n product to an object then the second factor is applied first.\n\n TESTS::\n\n sage: # needs sage.rings.number_field\n sage: P.<x> = QQ[]\n sage: K.<a> = NumberField(x^3 - 5, embedding=0)\n sage: L.<b> = K.extension(x^2 + a)\n sage: F, R = L.construction()\n sage: prod(F.expand())(R) == L #indirect doctest\n True\n\n '
if isinstance(other, IdentityConstructionFunctor):
return self
if isinstance(other, AlgebraicExtensionFunctor):
if set(self.names).intersection(other.names):
raise CoercionException(('Overlapping names (%s,%s)' % (self.names, other.names)))
return AlgebraicExtensionFunctor((self.polys + other.polys), (self.names + other.names), (self.embeddings + other.embeddings), (self.structures + other.structures), precs=(self.precs + other.precs), implementations=(self.implementations + other.implementations), latex_names=(self.latex_names + other.latex_names), **self.kwds)
elif (isinstance(other, CompositeConstructionFunctor) and isinstance(other.all[(- 1)], AlgebraicExtensionFunctor)):
return CompositeConstructionFunctor(other.all[:(- 1)], (self * other.all[(- 1)]))
else:
return CompositeConstructionFunctor(other, self)
def expand(self):
"\n Decompose the functor `F` into sub-functors, whose product returns `F`.\n\n EXAMPLES::\n\n sage: # needs sage.rings.number_field\n sage: P.<x> = QQ[]\n sage: K.<a> = NumberField(x^3 - 5, embedding=0)\n sage: L.<b> = K.extension(x^2 + a)\n sage: F, R = L.construction()\n sage: prod(F.expand())(R) == L\n True\n sage: K = NumberField([x^2 - 2, x^2 - 3],'a')\n sage: F, R = K.construction()\n sage: F\n AlgebraicExtensionFunctor\n sage: L = F.expand(); L\n [AlgebraicExtensionFunctor, AlgebraicExtensionFunctor]\n sage: L[-1](QQ)\n Number Field in a1 with defining polynomial x^2 - 3\n "
n = len(self.polys)
if (n == 1):
return [self]
return [AlgebraicExtensionFunctor([self.polys[i]], [self.names[i]], [self.embeddings[i]], [self.structures[i]], precs=[self.precs[i]], implementations=[self.implementations[i]], latex_names=[self.latex_names[i]], **self.kwds) for i in range(n)]
|
class AlgebraicClosureFunctor(ConstructionFunctor):
'\n Algebraic Closure.\n\n EXAMPLES::\n\n sage: # needs sage.rings.complex_double sage.rings.number_field\n sage: F = CDF.construction()[0]\n sage: F(QQ)\n Algebraic Field\n sage: F(RR) # needs sage.rings.real_mpfr\n Complex Field with 53 bits of precision\n sage: F(F(QQ)) is F(QQ)\n True\n\n '
rank = 3
def __init__(self):
'\n TESTS::\n\n sage: from sage.categories.pushout import AlgebraicClosureFunctor\n sage: F = AlgebraicClosureFunctor()\n sage: F(QQ) # needs sage.rings.number_field\n Algebraic Field\n sage: F(RR) # needs sage.rings.real_mpfr\n Complex Field with 53 bits of precision\n sage: F == loads(dumps(F))\n True\n\n '
Functor.__init__(self, Rings(), Rings())
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: F = CDF.construction()[0] # needs sage.rings.complex_double\n sage: F(QQ) # indirect doctest # needs sage.rings.complex_double sage.rings.number_field\n Algebraic Field\n "
try:
c = R.construction()
if ((c is not None) and (c[0] == self)):
return R
except AttributeError:
pass
return R.algebraic_closure()
def merge(self, other):
"\n Mathematically, Algebraic Closure subsumes Algebraic Extension.\n However, it seems that people do want to work with algebraic\n extensions of ``RR``. Therefore, we do not merge with algebraic extension.\n\n TESTS::\n\n sage: x = polygen(QQ, 'x')\n sage: K.<a> = NumberField(x^3 + x^2 + 1) # needs sage.rings.number_field\n sage: CDF.construction()[0].merge(K.construction()[0]) is None # needs sage.rings.number_field\n True\n sage: CDF.construction()[0].merge(CDF.construction()[0]) # needs sage.rings.complex_double\n AlgebraicClosureFunctor\n\n "
if (self == other):
return self
return None
|
class PermutationGroupFunctor(ConstructionFunctor):
rank = 10
def __init__(self, gens, domain):
'\n EXAMPLES::\n\n sage: from sage.categories.pushout import PermutationGroupFunctor\n sage: PF = PermutationGroupFunctor([PermutationGroupElement([(1,2)])], # needs sage.groups\n ....: [1,2]); PF\n PermutationGroupFunctor[(1,2)]\n '
Functor.__init__(self, Groups(), Groups())
self._gens = tuple(gens)
self._domain = domain
def _repr_(self):
'\n EXAMPLES::\n\n sage: P1 = PermutationGroup([[(1,2)]]) # needs sage.groups\n sage: PF, P = P1.construction() # needs sage.groups\n sage: PF # needs sage.groups\n PermutationGroupFunctor[(1,2)]\n '
return ('PermutationGroupFunctor%s' % list(self.gens()))
def __call__(self, R):
'\n EXAMPLES::\n\n sage: P1 = PermutationGroup([[(1,2)]]) # needs sage.groups\n sage: PF, P = P1.construction() # needs sage.groups\n sage: PF(P) # needs sage.groups\n Permutation Group with generators [(1,2)]\n '
from sage.groups.perm_gps.permgroup import PermutationGroup
return PermutationGroup([g for g in (R.gens() + self.gens()) if (not g.is_one())], domain=self._domain)
def gens(self):
'\n EXAMPLES::\n\n sage: P1 = PermutationGroup([[(1,2)]]) # needs sage.groups\n sage: PF, P = P1.construction() # needs sage.groups\n sage: PF.gens() # needs sage.groups\n ((1,2),)\n '
return self._gens
def merge(self, other):
'\n Merge ``self`` with another construction functor, or return ``None``.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: P1 = PermutationGroup([[(1,2)]])\n sage: PF1, P = P1.construction()\n sage: P2 = PermutationGroup([[(1,3)]])\n sage: PF2, P = P2.construction()\n sage: PF1.merge(PF2)\n PermutationGroupFunctor[(1,2), (1,3)]\n '
if (self.__class__ != other.__class__):
return None
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
new_domain = set(self._domain).union(set(other._domain))
try:
new_domain = FiniteEnumeratedSet(sorted(new_domain))
except TypeError:
new_domain = FiniteEnumeratedSet(sorted(new_domain, key=str))
return PermutationGroupFunctor((self.gens() + other.gens()), new_domain)
|
class EquivariantSubobjectConstructionFunctor(ConstructionFunctor):
"\n Constructor for subobjects invariant or equivariant under given semigroup actions.\n\n Let `S` be a semigroup that\n - acts on a parent `X` as `s \\cdot x` (``action``, ``side='left'``) or\n - acts on `X` as `x \\cdot s` (``action``, ``side='right'``),\n and (possibly trivially)\n - acts on `X` as `s * x` (``other_action``, ``other_side='left'``) or\n - acts on `X` as `x * s` (``other_action``, ``other_side='right'``).\n\n The `S`-equivariant subobject is the subobject\n\n .. MATH::\n\n X^S := \\{x \\in X : s \\cdot x = s * x,\\, \\forall s \\in S \\}\n\n when ``side = other_side = 'left'`` and mutatis mutandis for the other values\n of ``side`` and ``other_side``.\n\n When ``other_action`` is trivial, `X^S` is called the `S`-invariant subobject.\n\n EXAMPLES:\n\n Monoterm symmetries of a tensor, here only for matrices: row (index 0),\n column (index 1); the order of the extra element 2 in a permutation determines\n whether it is a symmetry or an antisymmetry::\n\n sage: # needs sage.groups sage.modules\n sage: GSym01 = PermutationGroup([[(0,1),(2,),(3,)]]); GSym01\n Permutation Group with generators [(0,1)]\n sage: GASym01 = PermutationGroup([[(0,1),(2,3)]]); GASym01\n Permutation Group with generators [(0,1)(2,3)]\n sage: from sage.categories.action import Action\n sage: from sage.structure.element import Matrix\n sage: class TensorIndexAction(Action):\n ....: def _act_(self, g, x):\n ....: if isinstance(x, Matrix):\n ....: if g(0) == 1:\n ....: if g(2) == 2:\n ....: return x.transpose()\n ....: else:\n ....: return -x.transpose()\n ....: else:\n ....: return x\n ....: raise NotImplementedError\n sage: M = matrix([[1, 2], [3, 4]]); M\n [1 2]\n [3 4]\n sage: GSym01_action = TensorIndexAction(GSym01, M.parent())\n sage: GASym01_action = TensorIndexAction(GASym01, M.parent())\n sage: GSym01_action.act(GSym01.0, M)\n [1 3]\n [2 4]\n sage: GASym01_action.act(GASym01.0, M)\n [-1 -3]\n [-2 -4]\n sage: Sym01 = M.parent().invariant_module(GSym01, action=GSym01_action); Sym01\n (Permutation Group with generators [(0,1)])-invariant submodule\n of Full MatrixSpace of 2 by 2 dense matrices over Integer Ring\n sage: list(Sym01.basis())\n [B[0], B[1], B[2]]\n sage: list(Sym01.basis().map(Sym01.lift))\n [\n [1 0] [0 1] [0 0]\n [0 0], [1 0], [0 1]\n ]\n sage: ASym01 = M.parent().invariant_module(GASym01, action=GASym01_action)\n sage: ASym01\n (Permutation Group with generators [(0,1)(2,3)])-invariant submodule\n of Full MatrixSpace of 2 by 2 dense matrices over Integer Ring\n sage: list(ASym01.basis())\n [B[0]]\n sage: list(ASym01.basis().map(ASym01.lift))\n [\n [ 0 1]\n [-1 0]\n ]\n sage: from sage.categories.pushout import pushout\n sage: pushout(Sym01, QQ)\n (Permutation Group with generators [(0,1)])-invariant submodule\n of Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n "
def __init__(self, S, action=operator.mul, side='left', other_action=None, other_side='left'):
"\n EXAMPLES::\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.construction()\n (EquivariantSubobjectConstructionFunctor,\n Representation of S3 indexed by {1, 2, 3} over Integer Ring)\n "
from sage.categories.sets_cat import Sets
super().__init__(Sets(), Sets())
self.S = S
self.action = action
self.side = side
self.other_action = other_action
self.other_side = other_side
def _apply_functor(self, X):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: from sage.categories.pushout import EquivariantSubobjectConstructionFunctor\n sage: M2 = MatrixSpace(QQ, 2); M2 # needs sage.modules\n Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n sage: F = EquivariantSubobjectConstructionFunctor(M2, # needs sage.modules\n ....: operator.mul, 'left',\n ....: operator.mul, 'right'); F\n EquivariantSubobjectConstructionFunctor\n sage: F(M2) # needs sage.modules\n Traceback (most recent call last):\n ...\n NotImplementedError: non-trivial other_action=<built-in function mul> is not implemented\n "
other_action = self.other_action
if (other_action is not None):
raise NotImplementedError(f'non-trivial other_action={other_action!r} is not implemented')
return X.invariant_module(self.S, action=self.action, side=self.side)
|
class BlackBoxConstructionFunctor(ConstructionFunctor):
"\n Construction functor obtained from any callable object.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import BlackBoxConstructionFunctor\n sage: FG = BlackBoxConstructionFunctor(gap)\n sage: FS = BlackBoxConstructionFunctor(singular)\n sage: FG\n BlackBoxConstructionFunctor\n sage: FG(ZZ) # needs sage.libs.gap\n Integers\n sage: FG(ZZ).parent() # needs sage.libs.gap\n Gap\n sage: FS(QQ['t']) # needs sage.libs.singular\n polynomial ring, over a field, global ordering\n // coefficients: QQ\n // number of vars : 1\n // block 1 : ordering lp\n // : names t\n // block 2 : ordering C\n sage: FG == FS # needs sage.libs.gap sage.libs.singular\n False\n sage: FG == loads(dumps(FG)) # needs sage.libs.gap\n True\n "
rank = 100
def __init__(self, box):
'\n TESTS::\n\n sage: from sage.categories.pushout import BlackBoxConstructionFunctor\n sage: FG = BlackBoxConstructionFunctor(gap)\n sage: FM = BlackBoxConstructionFunctor(maxima) # needs sage.symbolic\n sage: FM == FG # needs sage.libs.gap sage.symbolic\n False\n sage: FM == loads(dumps(FM)) # needs sage.symbolic\n True\n '
ConstructionFunctor.__init__(self, Objects(), Objects())
if (not callable(box)):
raise TypeError('input must be callable')
self.box = box
def _apply_functor(self, R):
"\n Apply the functor to an object of ``self``'s domain.\n\n TESTS::\n\n sage: from sage.categories.pushout import BlackBoxConstructionFunctor\n sage: f = lambda x: x^2\n sage: F = BlackBoxConstructionFunctor(f)\n sage: F(ZZ) # indirect doctest # needs sage.modules\n Ambient free module of rank 2 over the principal ideal domain Integer Ring\n\n "
return self.box(R)
def __eq__(self, other):
'\n TESTS::\n\n sage: from sage.categories.pushout import BlackBoxConstructionFunctor\n sage: FG = BlackBoxConstructionFunctor(gap)\n sage: FM = BlackBoxConstructionFunctor(maxima) # needs sage.symbolic\n sage: FM == FG # indirect doctest # needs sage.libs.gap sage.symbolic\n False\n sage: FM == loads(dumps(FM)) # needs sage.symbolic\n True\n '
if (not isinstance(other, BlackBoxConstructionFunctor)):
return False
return (self.box == other.box)
def __ne__(self, other):
'\n Check whether ``self`` is not equal to ``other``.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import BlackBoxConstructionFunctor\n sage: FG = BlackBoxConstructionFunctor(gap)\n sage: FM = BlackBoxConstructionFunctor(maxima) # needs sage.symbolic\n sage: FM != FG # indirect doctest # needs sage.libs.gap sage.symbolic\n True\n sage: FM != loads(dumps(FM)) # needs sage.symbolic\n False\n '
return (not (self == other))
__hash__ = ConstructionFunctor.__hash__
|
def pushout(R, S):
'\n Given a pair of objects `R` and `S`, try to construct a\n reasonable object `Y` and return maps such that\n canonically `R \\leftarrow Y \\rightarrow S`.\n\n ALGORITHM:\n\n This incorporates the idea of functors discussed at Sage Days 4.\n Every object `R` can be viewed as an initial object and a series\n of functors (e.g. polynomial, quotient, extension, completion,\n vector/matrix, etc.). Call the series of increasingly simple\n objects (with the associated functors) the "tower" of `R`. The\n construction method is used to create the tower.\n\n Given two objects `R` and `S`, try to find a common initial object\n `Z`. If the towers of `R` and `S` meet, let `Z` be their join.\n Otherwise, see if the top of one coerces naturally into the other.\n\n Now we have an initial object and two ordered lists of functors to\n apply. We wish to merge these in an unambiguous order, popping\n elements off the top of one or the other tower as we apply them to\n `Z`.\n\n - If the functors are of distinct types, there is an absolute\n ordering given by the rank attribute. Use this.\n\n - Otherwise:\n\n - If the tops are equal, we (try to) merge them.\n\n - If exactly one occurs lower in the other tower, we may\n unambiguously apply the other (hoping for a later merge).\n\n - If the tops commute, we can apply either first.\n\n - Otherwise fail due to ambiguity.\n\n The algorithm assumes by default that when a construction `F` is\n applied to an object `X`, the object `F(X)` admits a coercion map\n from `X`. However, the algorithm can also handle the case where\n `F(X)` has a coercion map *to* `X` instead. In this case, the\n attribute ``coercion_reversed`` of the class implementing `F`\n should be set to ``True``.\n\n EXAMPLES:\n\n Here our "towers" are `R = Complete_7(Frac(\\ZZ))` and `Frac(Poly_x(\\ZZ))`,\n which give us `Frac(Poly_x(Complete_7(Frac(\\ZZ))))`::\n\n sage: from sage.categories.pushout import pushout\n sage: pushout(Qp(7), Frac(ZZ[\'x\'])) # needs sage.rings.padics\n Fraction Field of Univariate Polynomial Ring in x\n over 7-adic Field with capped relative precision 20\n\n Note we get the same thing with\n ::\n\n sage: pushout(Zp(7), Frac(QQ[\'x\'])) # needs sage.rings.padics\n Fraction Field of Univariate Polynomial Ring in x\n over 7-adic Field with capped relative precision 20\n sage: pushout(Zp(7)[\'x\'], Frac(QQ[\'x\'])) # needs sage.rings.padics\n Fraction Field of Univariate Polynomial Ring in x\n over 7-adic Field with capped relative precision 20\n\n Note that polynomial variable ordering must be unambiguously determined.\n ::\n\n sage: pushout(ZZ[\'x,y,z\'], QQ[\'w,z,t\'])\n Traceback (most recent call last):\n ...\n CoercionException: (\'Ambiguous Base Extension\',\n Multivariate Polynomial Ring in x, y, z over Integer Ring,\n Multivariate Polynomial Ring in w, z, t over Rational Field)\n sage: pushout(ZZ[\'x,y,z\'], QQ[\'w,x,z,t\'])\n Multivariate Polynomial Ring in w, x, y, z, t over Rational Field\n\n Some other examples::\n\n sage: pushout(Zp(7)[\'y\'], Frac(QQ[\'t\'])[\'x,y,z\']) # needs sage.rings.padics\n Multivariate Polynomial Ring in x, y, z\n over Fraction Field of Univariate Polynomial Ring in t\n over 7-adic Field with capped relative precision 20\n sage: pushout(ZZ[\'x,y,z\'], Frac(ZZ[\'x\'])[\'y\'])\n Multivariate Polynomial Ring in y, z\n over Fraction Field of Univariate Polynomial Ring in x over Integer Ring\n sage: pushout(MatrixSpace(RDF, 2, 2), Frac(ZZ[\'x\'])) # needs sage.modules\n Full MatrixSpace of 2 by 2 dense matrices\n over Fraction Field of Univariate Polynomial Ring in x over Real Double Field\n sage: pushout(ZZ, MatrixSpace(ZZ[[\'x\']], 3, 3)) # needs sage.modules\n Full MatrixSpace of 3 by 3 dense matrices\n over Power Series Ring in x over Integer Ring\n sage: pushout(QQ[\'x,y\'], ZZ[[\'x\']])\n Univariate Polynomial Ring in y\n over Power Series Ring in x over Rational Field\n sage: pushout(Frac(ZZ[\'x\']), QQ[[\'x\']])\n Laurent Series Ring in x over Rational Field\n\n A construction with ``coercion_reversed=True`` (currently only\n the :class:`SubspaceFunctor` construction) is only applied if it\n leads to a valid coercion::\n\n sage: # needs sage.modules\n sage: A = ZZ^2\n sage: V = span([[1, 2]], QQ)\n sage: P = sage.categories.pushout.pushout(A, V)\n sage: P\n Vector space of dimension 2 over Rational Field\n sage: P.has_coerce_map_from(A)\n True\n\n sage: # needs sage.modules\n sage: V = (QQ^3).span([[1, 2, 3/4]])\n sage: A = ZZ^3\n sage: pushout(A, V)\n Vector space of dimension 3 over Rational Field\n sage: B = A.span([[0, 0, 2/3]])\n sage: pushout(B, V)\n Vector space of degree 3 and dimension 2 over Rational Field\n User basis matrix:\n [1 2 0]\n [0 0 1]\n\n Some more tests with ``coercion_reversed=True``::\n\n sage: from sage.categories.pushout import ConstructionFunctor\n sage: class EvenPolynomialRing(type(QQ[\'x\'])):\n ....: def __init__(self, base, var):\n ....: super().__init__(base, var)\n ....: self.register_embedding(base[var])\n ....: def __repr__(self):\n ....: return "Even Power " + super().__repr__()\n ....: def construction(self):\n ....: return EvenPolynomialFunctor(), self.base()[self.variable_name()]\n ....: def _coerce_map_from_(self, R):\n ....: return self.base().has_coerce_map_from(R)\n sage: class EvenPolynomialFunctor(ConstructionFunctor):\n ....: rank = 10\n ....: coercion_reversed = True\n ....: def __init__(self):\n ....: ConstructionFunctor.__init__(self, Rings(), Rings())\n ....: def _apply_functor(self, R):\n ....: return EvenPolynomialRing(R.base(), R.variable_name())\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), ZZ)\n Even Power Univariate Polynomial Ring in x over Rational Field\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), QQ)\n Even Power Univariate Polynomial Ring in x over Rational Field\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), RR) # needs sage.rings.real_mpfr\n Even Power Univariate Polynomial Ring in x over Real Field with 53 bits of precision\n\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), ZZ[\'x\'])\n Univariate Polynomial Ring in x over Rational Field\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), QQ[\'x\'])\n Univariate Polynomial Ring in x over Rational Field\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), RR[\'x\']) # needs sage.rings.real_mpfr\n Univariate Polynomial Ring in x over Real Field with 53 bits of precision\n\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), EvenPolynomialRing(QQ, \'x\'))\n Even Power Univariate Polynomial Ring in x over Rational Field\n sage: pushout(EvenPolynomialRing(QQ, \'x\'), EvenPolynomialRing(RR, \'x\')) # needs sage.rings.real_mpfr\n Even Power Univariate Polynomial Ring in x over Real Field with 53 bits of precision\n\n sage: pushout(EvenPolynomialRing(QQ, \'x\')^2, RR^2) # needs sage.modules sage.rings.real_mpfr\n Ambient free module of rank 2\n over the principal ideal domain Even Power Univariate Polynomial Ring in x\n over Real Field with 53 bits of precision\n sage: pushout(EvenPolynomialRing(QQ, \'x\')^2, RR[\'x\']^2) # needs sage.modules sage.rings.real_mpfr\n Ambient free module of rank 2\n over the principal ideal domain Univariate Polynomial Ring in x\n over Real Field with 53 bits of precision\n\n Some more tests related to univariate/multivariate\n constructions. We consider a generalization of polynomial rings,\n where in addition to the coefficient ring `C` we also specify\n an additive monoid `E` for the exponents of the indeterminate.\n In particular, the elements of such a parent are given by\n\n .. MATH::\n\n \\sum_{i=0}^I c_i X^{e_i}\n\n with `c_i \\in C` and `e_i \\in E`. We define\n ::\n\n sage: class GPolynomialRing(Parent):\n ....: def __init__(self, coefficients, var, exponents):\n ....: self.coefficients = coefficients\n ....: self.var = var\n ....: self.exponents = exponents\n ....: super().__init__(category=Rings())\n ....: def _repr_(self):\n ....: return \'Generalized Polynomial Ring in %s^(%s) over %s\' % (\n ....: self.var, self.exponents, self.coefficients)\n ....: def construction(self):\n ....: return GPolynomialFunctor(self.var, self.exponents), self.coefficients\n ....: def _coerce_map_from_(self, R):\n ....: return self.coefficients.has_coerce_map_from(R)\n\n and\n ::\n\n sage: class GPolynomialFunctor(ConstructionFunctor):\n ....: rank = 10\n ....: def __init__(self, var, exponents):\n ....: self.var = var\n ....: self.exponents = exponents\n ....: ConstructionFunctor.__init__(self, Rings(), Rings())\n ....: def _repr_(self):\n ....: return \'GPoly[%s^(%s)]\' % (self.var, self.exponents)\n ....: def _apply_functor(self, coefficients):\n ....: return GPolynomialRing(coefficients, self.var, self.exponents)\n ....: def merge(self, other):\n ....: if isinstance(other, GPolynomialFunctor) and self.var == other.var:\n ....: exponents = pushout(self.exponents, other.exponents)\n ....: return GPolynomialFunctor(self.var, exponents)\n\n We can construct a parent now in two different ways::\n\n sage: GPolynomialRing(QQ, \'X\', ZZ)\n Generalized Polynomial Ring in X^(Integer Ring) over Rational Field\n sage: GP_ZZ = GPolynomialFunctor(\'X\', ZZ); GP_ZZ\n GPoly[X^(Integer Ring)]\n sage: GP_ZZ(QQ)\n Generalized Polynomial Ring in X^(Integer Ring) over Rational Field\n\n Since the construction\n ::\n\n sage: GP_ZZ(QQ).construction()\n (GPoly[X^(Integer Ring)], Rational Field)\n\n uses the coefficient ring, we have the usual coercion with respect\n to this parameter::\n\n sage: pushout(GP_ZZ(ZZ), GP_ZZ(QQ))\n Generalized Polynomial Ring in X^(Integer Ring) over Rational Field\n sage: pushout(GP_ZZ(ZZ[\'t\']), GP_ZZ(QQ))\n Generalized Polynomial Ring in X^(Integer Ring)\n over Univariate Polynomial Ring in t over Rational Field\n sage: pushout(GP_ZZ(ZZ[\'a,b\']), GP_ZZ(ZZ[\'b,c\']))\n Generalized Polynomial Ring in X^(Integer Ring)\n over Multivariate Polynomial Ring in a, b, c over Integer Ring\n sage: pushout(GP_ZZ(ZZ[\'a,b\']), GP_ZZ(QQ[\'b,c\']))\n Generalized Polynomial Ring in X^(Integer Ring)\n over Multivariate Polynomial Ring in a, b, c over Rational Field\n sage: pushout(GP_ZZ(ZZ[\'a,b\']), GP_ZZ(ZZ[\'c,d\']))\n Traceback (most recent call last):\n ...\n CoercionException: (\'Ambiguous Base Extension\', ...)\n\n ::\n\n sage: GP_QQ = GPolynomialFunctor(\'X\', QQ)\n sage: pushout(GP_ZZ(ZZ), GP_QQ(ZZ))\n Generalized Polynomial Ring in X^(Rational Field) over Integer Ring\n sage: pushout(GP_QQ(ZZ), GP_ZZ(ZZ))\n Generalized Polynomial Ring in X^(Rational Field) over Integer Ring\n\n ::\n\n sage: GP_ZZt = GPolynomialFunctor(\'X\', ZZ[\'t\'])\n sage: pushout(GP_ZZt(ZZ), GP_QQ(ZZ))\n Generalized Polynomial Ring in X^(Univariate Polynomial Ring in t\n over Rational Field) over Integer Ring\n\n ::\n\n sage: pushout(GP_ZZ(ZZ), GP_QQ(QQ))\n Generalized Polynomial Ring in X^(Rational Field) over Rational Field\n sage: pushout(GP_ZZ(QQ), GP_QQ(ZZ))\n Generalized Polynomial Ring in X^(Rational Field) over Rational Field\n sage: pushout(GP_ZZt(QQ), GP_QQ(ZZ))\n Generalized Polynomial Ring in X^(Univariate Polynomial Ring in t\n over Rational Field) over Rational Field\n sage: pushout(GP_ZZt(ZZ), GP_QQ(QQ))\n Generalized Polynomial Ring in X^(Univariate Polynomial Ring in t\n over Rational Field) over Rational Field\n sage: pushout(GP_ZZt(ZZ[\'a,b\']), GP_QQ(ZZ[\'c,d\']))\n Traceback (most recent call last):\n ...\n CoercionException: (\'Ambiguous Base Extension\', ...)\n sage: pushout(GP_ZZt(ZZ[\'a,b\']), GP_QQ(ZZ[\'b,c\']))\n Generalized Polynomial Ring\n in X^(Univariate Polynomial Ring in t over Rational Field)\n over Multivariate Polynomial Ring in a, b, c over Integer Ring\n\n Some tests with Cartesian products::\n\n sage: from sage.sets.cartesian_product import CartesianProduct\n sage: A = CartesianProduct((ZZ[\'x\'], QQ[\'y\'], QQ[\'z\']),\n ....: Sets().CartesianProducts())\n sage: B = CartesianProduct((ZZ[\'x\'], ZZ[\'y\'], ZZ[\'t\'][\'z\']),\n ....: Sets().CartesianProducts())\n sage: A.construction()\n (The cartesian_product functorial construction,\n (Univariate Polynomial Ring in x over Integer Ring,\n Univariate Polynomial Ring in y over Rational Field,\n Univariate Polynomial Ring in z over Rational Field))\n sage: pushout(A, B)\n The Cartesian product of\n (Univariate Polynomial Ring in x over Integer Ring,\n Univariate Polynomial Ring in y over Rational Field,\n Univariate Polynomial Ring in z over\n Univariate Polynomial Ring in t over Rational Field)\n sage: pushout(ZZ, cartesian_product([ZZ, QQ]))\n Traceback (most recent call last):\n ...\n CoercionException: \'NoneType\' object is not iterable\n\n ::\n\n sage: from sage.categories.pushout import PolynomialFunctor\n sage: from sage.sets.cartesian_product import CartesianProduct\n sage: class CartesianProductPoly(CartesianProduct):\n ....: def __init__(self, polynomial_rings):\n ....: sort = sorted(polynomial_rings,\n ....: key=lambda P: P.variable_name())\n ....: super().__init__(sort, Sets().CartesianProducts())\n ....: def vars(self):\n ....: return tuple(P.variable_name()\n ....: for P in self.cartesian_factors())\n ....: def _pushout_(self, other):\n ....: if isinstance(other, CartesianProductPoly):\n ....: s_vars = self.vars()\n ....: o_vars = other.vars()\n ....: if s_vars == o_vars:\n ....: return\n ....: return pushout(CartesianProductPoly(\n ....: self.cartesian_factors() +\n ....: tuple(f for f in other.cartesian_factors()\n ....: if f.variable_name() not in s_vars)),\n ....: CartesianProductPoly(\n ....: other.cartesian_factors() +\n ....: tuple(f for f in self.cartesian_factors()\n ....: if f.variable_name() not in o_vars)))\n ....: C = other.construction()\n ....: if C is None:\n ....: return\n ....: elif isinstance(C[0], PolynomialFunctor):\n ....: return pushout(self, CartesianProductPoly((other,)))\n\n ::\n\n sage: pushout(CartesianProductPoly((ZZ[\'x\'],)),\n ....: CartesianProductPoly((ZZ[\'y\'],)))\n The Cartesian product of\n (Univariate Polynomial Ring in x over Integer Ring,\n Univariate Polynomial Ring in y over Integer Ring)\n sage: pushout(CartesianProductPoly((ZZ[\'x\'], ZZ[\'y\'])),\n ....: CartesianProductPoly((ZZ[\'x\'], ZZ[\'z\'])))\n The Cartesian product of\n (Univariate Polynomial Ring in x over Integer Ring,\n Univariate Polynomial Ring in y over Integer Ring,\n Univariate Polynomial Ring in z over Integer Ring)\n sage: pushout(CartesianProductPoly((QQ[\'a,b\'][\'x\'], QQ[\'y\'])), # needs sage.symbolic\n ....: CartesianProductPoly((ZZ[\'b,c\'][\'x\'], SR[\'z\'])))\n The Cartesian product of\n (Univariate Polynomial Ring in x over\n Multivariate Polynomial Ring in a, b, c over Rational Field,\n Univariate Polynomial Ring in y over Rational Field,\n Univariate Polynomial Ring in z over Symbolic Ring)\n\n ::\n\n sage: pushout(CartesianProductPoly((ZZ[\'x\'],)), ZZ[\'y\'])\n The Cartesian product of\n (Univariate Polynomial Ring in x over Integer Ring,\n Univariate Polynomial Ring in y over Integer Ring)\n sage: pushout(QQ[\'b,c\'][\'y\'], CartesianProductPoly((ZZ[\'a,b\'][\'x\'],)))\n The Cartesian product of\n (Univariate Polynomial Ring in x over\n Multivariate Polynomial Ring in a, b over Integer Ring,\n Univariate Polynomial Ring in y over\n Multivariate Polynomial Ring in b, c over Rational Field)\n\n ::\n\n sage: pushout(CartesianProductPoly((ZZ[\'x\'],)), ZZ)\n Traceback (most recent call last):\n ...\n CoercionException: No common base ("join") found for\n The cartesian_product functorial construction(...) and None(Integer Ring):\n (Multivariate) functors are incompatible.\n\n AUTHORS:\n\n - Robert Bradshaw\n - Peter Bruin\n - Simon King\n - Daniel Krenn\n - David Roe\n '
if ((R is S) or (R == S)):
return R
if hasattr(R, '_pushout_'):
P = R._pushout_(S)
if (P is not None):
return P
if hasattr(S, '_pushout_'):
P = S._pushout_(R)
if (P is not None):
return P
if isinstance(R, type):
R = type_to_parent(R)
if isinstance(S, type):
S = type_to_parent(S)
R_tower = construction_tower(R)
S_tower = construction_tower(S)
Rs = [c[1] for c in R_tower]
Ss = [c[1] for c in S_tower]
from sage.structure.parent import Parent
if (not isinstance(Rs[(- 1)], Parent)):
Rs = Rs[:(- 1)]
if (not isinstance(Ss[(- 1)], Parent)):
Ss = Ss[:(- 1)]
if (R in Ss):
if (not any((c[0].coercion_reversed for c in S_tower[1:]))):
return S
elif (S in Rs):
if (not any((c[0].coercion_reversed for c in R_tower[1:]))):
return R
if (Rs[(- 1)] in Ss):
(Rs, Ss) = (Ss, Rs)
(R_tower, S_tower) = (S_tower, R_tower)
Z = None
if (Ss[(- 1)] in Rs):
if (Rs[(- 1)] == Ss[(- 1)]):
while (Rs and Ss and (Rs[(- 1)] == Ss[(- 1)])):
Rs.pop()
Z = Ss.pop()
else:
Rs = Rs[:Rs.index(Ss[(- 1)])]
Z = Ss.pop()
elif S.has_coerce_map_from(Rs[(- 1)]):
while (not Ss[(- 1)].has_coerce_map_from(Rs[(- 1)])):
Ss.pop()
while (Rs and Ss[(- 1)].has_coerce_map_from(Rs[(- 1)])):
Rs.pop()
Z = Ss.pop()
elif R.has_coerce_map_from(Ss[(- 1)]):
while (not Rs[(- 1)].has_coerce_map_from(Ss[(- 1)])):
Rs.pop()
while (Ss and Rs[(- 1)].has_coerce_map_from(Ss[(- 1)])):
Ss.pop()
Z = Rs.pop()
if ((Z is None) and (R_tower[(- 1)][0] is not None)):
Z = R_tower[(- 1)][0].common_base(S_tower[(- 1)][0], R_tower[(- 1)][1], S_tower[(- 1)][1])
R_tower = expand_tower(R_tower[:len(Rs)])
S_tower = expand_tower(S_tower[:len(Ss)])
else:
R_tower = expand_tower(R_tower[:(len(Rs) + 1)])
S_tower = expand_tower(S_tower[:(len(Ss) + 1)])
Rc = [c[0] for c in R_tower[1:]]
Sc = [c[0] for c in S_tower[1:]]
all = IdentityConstructionFunctor()
def apply_from(Xc):
c = Xc.pop()
if c.coercion_reversed:
Yc = (Sc if (Xc is Rc) else Rc)
Y_tower = (S_tower if (Xc is Rc) else R_tower)
Y_partial = Y_tower[len(Yc)][1]
if (not (c * all)(Z).has_coerce_map_from(Y_partial)):
return all
return (c * all)
try:
while (Rc or Sc):
if (not Sc):
all = apply_from(Rc)
elif (not Rc):
all = apply_from(Sc)
elif (Rc[(- 1)].rank < Sc[(- 1)].rank):
all = apply_from(Rc)
elif (Sc[(- 1)].rank < Rc[(- 1)].rank):
all = apply_from(Sc)
elif (Rc[(- 1)] == Sc[(- 1)]):
cR = Rc.pop()
cS = Sc.pop()
c = (cR.merge(cS) or cS.merge(cR))
if c:
all = (c * all)
else:
raise CoercionException(('Incompatible Base Extension %r, %r (on %r, %r)' % (R, S, cR, cS)))
elif (Rc[(- 1)] in Sc):
if (Sc[(- 1)] in Rc):
raise CoercionException('Ambiguous Base Extension', R, S)
else:
all = apply_from(Sc)
elif (Sc[(- 1)] in Rc):
all = apply_from(Rc)
elif (Rc[(- 1)].commutes(Sc[(- 1)]) or Sc[(- 1)].commutes(Rc[(- 1)])):
all = ((Sc.pop() * Rc.pop()) * all)
else:
cR = Rc.pop()
cS = Sc.pop()
c = (cR.merge(cS) or cS.merge(cR))
if (c is not None):
all = (c * all)
else:
raise CoercionException('Ambiguous Base Extension', R, S)
return all(Z)
except CoercionException:
raise
except (TypeError, ValueError, AttributeError, NotImplementedError) as ex:
raise CoercionException(ex)
|
def pushout_lattice(R, S):
"\n Given a pair of objects `R` and `S`, try to construct a\n reasonable object `Y` and return maps such that\n canonically `R \\leftarrow Y \\rightarrow S`.\n\n ALGORITHM:\n\n This is based on the model that arose from much discussion at\n Sage Days 4. Going up the tower of constructions of `R` and `S`\n (e.g. the reals come from the rationals come from the integers),\n try to find a common parent, and then try to fill in a lattice\n with these two towers as sides with the top as the common ancestor\n and the bottom will be the desired ring.\n\n See the code for a specific worked-out example.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import pushout_lattice\n sage: A, B = pushout_lattice(Qp(7), Frac(ZZ['x'])) # needs sage.rings.padics\n sage: A.codomain() # needs sage.rings.padics\n Fraction Field of Univariate Polynomial Ring in x\n over 7-adic Field with capped relative precision 20\n sage: A.codomain() is B.codomain() # needs sage.rings.padics\n True\n sage: A, B = pushout_lattice(ZZ, MatrixSpace(ZZ[['x']], 3, 3)) # needs sage.modules\n sage: B # needs sage.modules\n Identity endomorphism of Full MatrixSpace of 3 by 3 dense matrices\n over Power Series Ring in x over Integer Ring\n\n AUTHOR:\n\n - Robert Bradshaw\n\n "
R_tower = construction_tower(R)
S_tower = construction_tower(S)
Rs = [c[1] for c in R_tower]
Ss = [c[1] for c in S_tower]
start = None
for Z in Rs:
if (Z in Ss):
start = Z
if (start is None):
return None
R_tower = list(reversed(R_tower[:(Rs.index(start) + 1)]))
S_tower = list(reversed(S_tower[:(Ss.index(start) + 1)]))
Rs = [c[1] for c in R_tower]
Ss = [c[1] for c in S_tower]
Rc = [c[0] for c in R_tower]
Sc = [c[0] for c in S_tower]
lattice = {}
for (i, Rsi) in enumerate(Rs):
lattice[(i, 0)] = Rsi
for (j, Ssj) in enumerate(Ss):
lattice[(0, j)] = Ssj
for i in range((len(Rc) - 1)):
for j in range((len(Sc) - 1)):
try:
if (lattice[(i, (j + 1))] == lattice[((i + 1), j)]):
Rc[i] = Sc[j] = None
lattice[((i + 1), (j + 1))] = lattice[(i, (j + 1))]
elif ((Rc[i] is None) and (Sc[j] is None)):
lattice[((i + 1), (j + 1))] = lattice[(i, (j + 1))]
elif (Rc[i] is None):
lattice[((i + 1), (j + 1))] = Sc[j](lattice[((i + 1), j)])
elif (Sc[j] is None):
lattice[((i + 1), (j + 1))] = Rc[i](lattice[(i, (j + 1))])
elif (Rc[i].rank < Sc[j].rank):
lattice[((i + 1), (j + 1))] = Sc[j](lattice[((i + 1), j)])
Rc[i] = None
else:
lattice[((i + 1), (j + 1))] = Rc[i](lattice[(i, (j + 1))])
Sc[j] = None
except (AttributeError, NameError):
for ni in range(100):
for nj in range(100):
try:
R = lattice[(ni, nj)]
print(ni, nj, R)
except KeyError:
break
raise CoercionException(('%s does not support %s' % (lattice[(ni, nj)], 'F')))
R_loc = (len(Rs) - 1)
S_loc = (len(Ss) - 1)
if (S_loc > 0):
R_map = lattice[(R_loc, 1)].coerce_map_from(R)
for i in range(1, S_loc):
map = lattice[(R_loc, (i + 1))].coerce_map_from(lattice[(R_loc, i)])
R_map = (map * R_map)
else:
R_map = R.coerce_map_from(R)
if (R_loc > 0):
S_map = lattice[(1, S_loc)].coerce_map_from(S)
for i in range(1, R_loc):
map = lattice[((i + 1), S_loc)].coerce_map_from(lattice[(i, S_loc)])
S_map = (map * S_map)
else:
S_map = S.coerce_map_from(S)
return (R_map, S_map)
|
def construction_tower(R):
"\n An auxiliary function that is used in :func:`pushout` and :func:`pushout_lattice`.\n\n INPUT:\n\n An object\n\n OUTPUT:\n\n A constructive description of the object from scratch, by a list of pairs\n of a construction functor and an object to which the construction functor\n is to be applied. The first pair is formed by ``None`` and the given object.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import construction_tower\n sage: construction_tower(MatrixSpace(FractionField(QQ['t']), 2)) # needs sage.modules\n [(None, Full MatrixSpace of 2 by 2 dense matrices over Fraction Field\n of Univariate Polynomial Ring in t over Rational Field),\n (MatrixFunctor, Fraction Field\n of Univariate Polynomial Ring in t over Rational Field),\n (FractionField, Univariate Polynomial Ring in t over Rational Field),\n (Poly[t], Rational Field), (FractionField, Integer Ring)]\n\n "
tower = [(None, R)]
c = R.construction()
from sage.structure.parent import Parent
while (c is not None):
(f, R) = c
if (not isinstance(f, ConstructionFunctor)):
f = BlackBoxConstructionFunctor(f)
tower.append((f, R))
if (not isinstance(R, Parent)):
break
c = R.construction()
return tower
|
def expand_tower(tower):
"\n An auxiliary function that is used in :func:`pushout`.\n\n INPUT:\n\n A construction tower as returned by :func:`construction_tower`.\n\n OUTPUT:\n\n A new construction tower with all the construction functors expanded.\n\n EXAMPLES::\n\n sage: from sage.categories.pushout import construction_tower, expand_tower\n sage: construction_tower(QQ['x,y,z'])\n [(None, Multivariate Polynomial Ring in x, y, z over Rational Field),\n (MPoly[x,y,z], Rational Field),\n (FractionField, Integer Ring)]\n sage: expand_tower(construction_tower(QQ['x,y,z']))\n [(None, Multivariate Polynomial Ring in x, y, z over Rational Field),\n (MPoly[z], Univariate Polynomial Ring in y\n over Univariate Polynomial Ring in x over Rational Field),\n (MPoly[y], Univariate Polynomial Ring in x over Rational Field),\n (MPoly[x], Rational Field),\n (FractionField, Integer Ring)]\n "
new_tower = []
for (f, R) in reversed(tower):
if (f is None):
new_tower.append((f, R))
else:
fs = f.expand()
for ff in reversed(fs[1:]):
new_tower.append((ff, R))
R = ff(R)
new_tower.append((fs[0], R))
return list(reversed(new_tower))
|
def type_to_parent(P):
'\n An auxiliary function that is used in :func:`pushout`.\n\n INPUT:\n\n A type\n\n OUTPUT:\n\n A Sage parent structure corresponding to the given type\n\n TESTS::\n\n sage: from sage.categories.pushout import type_to_parent\n sage: type_to_parent(int)\n Integer Ring\n sage: type_to_parent(float)\n Real Double Field\n sage: type_to_parent(complex) # needs sage.rings.complex_double\n Complex Double Field\n sage: type_to_parent(list)\n Traceback (most recent call last):\n ...\n TypeError: not a scalar type\n '
from sage.structure.coerce import py_scalar_parent
parent = py_scalar_parent(P)
if (parent is None):
raise TypeError('not a scalar type')
return parent
|
class QuantumGroupRepresentations(Category_module):
'\n The category of quantum group representations.\n '
@cached_method
def super_categories(self):
"\n Return the super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.quantum_group_representations import QuantumGroupRepresentations\n sage: QuantumGroupRepresentations(ZZ['q'].fraction_field()).super_categories()\n [Category of vector spaces over\n Fraction Field of Univariate Polynomial Ring in q over Integer Ring]\n "
return [Modules(self.base_ring())]
def example(self):
"\n Return an example of a quantum group representation as per\n :meth:`Category.example <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: from sage.categories.quantum_group_representations import QuantumGroupRepresentations\n sage: Cat = QuantumGroupRepresentations(ZZ['q'].fraction_field())\n sage: Cat.example() # needs sage.combinat sage.modules\n V((2, 1, 0))\n "
from sage.algebras.quantum_groups.representations import AdjointRepresentation
from sage.combinat.crystals.tensor_product import CrystalOfTableaux
T = CrystalOfTableaux(['A', 2], shape=[2, 1])
return AdjointRepresentation(self.base_ring(), T)
class WithBasis(CategoryWithAxiom_over_base_ring):
'\n The category of quantum group representations with a\n distinguished basis.\n '
class TensorProducts(TensorProductsCategory):
'\n The category of quantum group representations with a\n distinguished basis constructed by tensor product of\n quantum group representations with a distinguished basis.\n '
@cached_method
def extra_super_categories(self):
"\n EXAMPLES::\n\n sage: from sage.categories.quantum_group_representations import QuantumGroupRepresentations\n sage: Cat = QuantumGroupRepresentations(ZZ['q'].fraction_field())\n sage: Cat.WithBasis().TensorProducts().extra_super_categories()\n [Category of quantum group representations with basis over\n Fraction Field of Univariate Polynomial Ring in q over Integer Ring]\n "
return [self.base_category()]
class ParentMethods():
def e_on_basis(self, i, b):
"\n Return the action of `e_i` on the basis element\n indexed by ``b``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``b`` -- an element of basis keys\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import (\n ....: MinusculeRepresentation, AdjointRepresentation)\n sage: R = ZZ['q'].fraction_field()\n sage: CM = crystals.Tableaux(['D',4], shape=[1])\n sage: VM = MinusculeRepresentation(R, CM)\n sage: CA = crystals.Tableaux(['D',4], shape=[1,1])\n sage: VA = AdjointRepresentation(R, CA)\n sage: v = tensor([VM.an_element(), VA.an_element()]); v\n 4*B[[[1]]] # B[[[1], [2]]] + 4*B[[[1]]] # B[[[1], [3]]]\n + 6*B[[[1]]] # B[[[2], [3]]] + 4*B[[[2]]] # B[[[1], [2]]]\n + 4*B[[[2]]] # B[[[1], [3]]] + 6*B[[[2]]] # B[[[2], [3]]]\n + 6*B[[[3]]] # B[[[1], [2]]] + 6*B[[[3]]] # B[[[1], [3]]]\n + 9*B[[[3]]] # B[[[2], [3]]]\n sage: v.e(1) # indirect doctest\n 4*B[[[1]]] # B[[[1], [2]]]\n + ((4*q+6)/q)*B[[[1]]] # B[[[1], [3]]]\n + 6*B[[[1]]] # B[[[2], [3]]]\n + 6*q*B[[[2]]] # B[[[1], [3]]]\n + 9*B[[[3]]] # B[[[1], [3]]]\n sage: v.e(2) # indirect doctest\n 4*B[[[1]]] # B[[[1], [2]]]\n + ((6*q+4)/q)*B[[[2]]] # B[[[1], [2]]]\n + 6*B[[[2]]] # B[[[1], [3]]]\n + 9*B[[[2]]] # B[[[2], [3]]]\n + 6*q*B[[[3]]] # B[[[1], [2]]]\n sage: v.e(3) # indirect doctest\n 0\n sage: v.e(4) # indirect doctest\n 0\n "
K_elt = [self._sets[k].K_on_basis(i, elt, (- 1)) for (k, elt) in enumerate(b)]
mon = [self._sets[k].monomial(elt) for (k, elt) in enumerate(b)]
t = self.tensor_constructor(self._sets)
ret = self.zero()
for (k, elt) in enumerate(b):
ret += t(*((K_elt[:k] + [self._sets[k].e_on_basis(i, elt)]) + mon[(k + 1):]))
return ret
def f_on_basis(self, i, b):
"\n Return the action of `f_i` on the basis element\n indexed by ``b``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``b`` -- an element of basis keys\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import (\n ....: MinusculeRepresentation, AdjointRepresentation)\n sage: R = ZZ['q'].fraction_field()\n sage: KM = crystals.KirillovReshetikhin(['B',3,1], 3,1)\n sage: VM = MinusculeRepresentation(R, KM)\n sage: KA = crystals.KirillovReshetikhin(['B',3,1], 2,1)\n sage: VA = AdjointRepresentation(R, KA)\n sage: v = tensor([VM.an_element(), VA.an_element()]); v\n 4*B[[+++, []]] # B[[]] + 4*B[[+++, []]] # B[[[1], [2]]]\n + 6*B[[+++, []]] # B[[[1], [3]]] + 4*B[[++-, []]] # B[[]]\n + 4*B[[++-, []]] # B[[[1], [2]]]\n + 6*B[[++-, []]] # B[[[1], [3]]] + 6*B[[+-+, []]] # B[[]]\n + 6*B[[+-+, []]] # B[[[1], [2]]]\n + 9*B[[+-+, []]] # B[[[1], [3]]]\n sage: v.f(0) # indirect doctest\n ((4*q^4+4)/q^2)*B[[+++, []]] # B[[[1], [2]]]\n + ((4*q^4+4)/q^2)*B[[++-, []]] # B[[[1], [2]]]\n + ((6*q^4+6)/q^2)*B[[+-+, []]] # B[[[1], [2]]]\n sage: v.f(1) # indirect doctest\n 6*B[[+++, []]] # B[[[2], [3]]]\n + 6*B[[++-, []]] # B[[[2], [3]]]\n + 9*B[[+-+, []]] # B[[[2], [3]]]\n + 6*B[[-++, []]] # B[[]]\n + 6*B[[-++, []]] # B[[[1], [2]]]\n + 9*q^2*B[[-++, []]] # B[[[1], [3]]]\n sage: v.f(2) # indirect doctest\n 4*B[[+++, []]] # B[[[1], [3]]]\n + 4*B[[++-, []]] # B[[[1], [3]]]\n + 4*B[[+-+, []]] # B[[]]\n + 4*q^2*B[[+-+, []]] # B[[[1], [2]]]\n + ((6*q^2+6)/q^2)*B[[+-+, []]] # B[[[1], [3]]]\n sage: v.f(3) # indirect doctest\n 6*B[[+++, []]] # B[[[1], [0]]]\n + 4*B[[++-, []]] # B[[]]\n + 4*B[[++-, []]] # B[[[1], [2]]]\n + 6*q^2*B[[++-, []]] # B[[[1], [3]]]\n + 6*B[[++-, []]] # B[[[1], [0]]]\n + 9*B[[+-+, []]] # B[[[1], [0]]]\n + 6*B[[+--, []]] # B[[]]\n + 6*B[[+--, []]] # B[[[1], [2]]]\n + 9*q^2*B[[+--, []]] # B[[[1], [3]]]\n "
K_elt = [self._sets[k].K_on_basis(i, elt, 1) for (k, elt) in enumerate(b)]
mon = [self._sets[k].monomial(elt) for (k, elt) in enumerate(b)]
t = self.tensor_constructor(self._sets)
ret = self.zero()
for (k, elt) in enumerate(b):
ret += t(*((mon[:k] + [self._sets[k].f_on_basis(i, elt)]) + K_elt[(k + 1):]))
return ret
def K_on_basis(self, i, b, power=1):
"\n Return the action of `K_i` on the basis element indexed by ``b``\n to the power ``power``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``b`` -- an element of basis keys\n - ``power`` -- (default: 1) the power of `K_i`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import (\n ....: MinusculeRepresentation, AdjointRepresentation)\n sage: R = ZZ['q'].fraction_field()\n sage: CM = crystals.Tableaux(['A',2], shape=[1])\n sage: VM = MinusculeRepresentation(R, CM)\n sage: CA = crystals.Tableaux(['A',2], shape=[2,1])\n sage: VA = AdjointRepresentation(R, CA)\n sage: v = tensor([sum(VM.basis()), VA.module_generator()]); v\n B[[[1]]] # B[[[1, 1], [2]]]\n + B[[[2]]] # B[[[1, 1], [2]]]\n + B[[[3]]] # B[[[1, 1], [2]]]\n sage: v.K(1) # indirect doctest\n q^2*B[[[1]]] # B[[[1, 1], [2]]]\n + B[[[2]]] # B[[[1, 1], [2]]]\n + q*B[[[3]]] # B[[[1, 1], [2]]]\n sage: v.K(2, -1) # indirect doctest\n 1/q*B[[[1]]] # B[[[1, 1], [2]]]\n + 1/q^2*B[[[2]]] # B[[[1, 1], [2]]]\n + B[[[3]]] # B[[[1, 1], [2]]]\n "
t = self.tensor_constructor(self._sets)
return t(*[self._sets[k].K_on_basis(i, elt, power) for (k, elt) in enumerate(b)])
class ParentMethods():
def tensor(*factors):
"\n Return the tensor product of ``self`` with the\n representations ``factors``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import (\n ....: MinusculeRepresentation, AdjointRepresentation)\n sage: R = ZZ['q'].fraction_field()\n sage: CM = crystals.Tableaux(['D',4], shape=[1])\n sage: CA = crystals.Tableaux(['D',4], shape=[1,1])\n sage: V = MinusculeRepresentation(R, CM)\n sage: V.tensor(V, V)\n V((1, 0, 0, 0)) # V((1, 0, 0, 0)) # V((1, 0, 0, 0))\n sage: A = MinusculeRepresentation(R, CA)\n sage: V.tensor(A)\n V((1, 0, 0, 0)) # V((1, 1, 0, 0))\n sage: B = crystals.Tableaux(['A',2], shape=[1])\n sage: W = MinusculeRepresentation(R, B)\n sage: tensor([W,V])\n Traceback (most recent call last):\n ...\n ValueError: all factors must be of the same Cartan type\n sage: tensor([V,A,W])\n Traceback (most recent call last):\n ...\n ValueError: all factors must be of the same Cartan type\n "
cartan_type = factors[0].cartan_type()
if any(((V.cartan_type() != cartan_type) for V in factors)):
raise ValueError('all factors must be of the same Cartan type')
return factors[0].__class__.Tensor(factors, category=tensor.category_from_parents(factors))
class ElementMethods():
def e(self, i):
"\n Return the action of `e_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import AdjointRepresentation\n sage: C = crystals.Tableaux(['G',2], shape=[1,1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = AdjointRepresentation(R, C)\n sage: v = V.an_element(); v\n 2*B[[[1], [2]]] + 2*B[[[1], [3]]] + 3*B[[[2], [3]]]\n sage: v.e(1)\n ((3*q^4+3*q^2+3)/q^2)*B[[[1], [3]]]\n sage: v.e(2)\n 2*B[[[1], [2]]]\n "
F = self.parent()
mc = self.monomial_coefficients(copy=False)
return F.linear_combination(((F.e_on_basis(i, m), c) for (m, c) in mc.items()))
def f(self, i):
"\n Return the action of `f_i` on ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import AdjointRepresentation\n sage: K = crystals.KirillovReshetikhin(['D',4,1], 2,1)\n sage: R = ZZ['q'].fraction_field()\n sage: V = AdjointRepresentation(R, K)\n sage: v = V.an_element(); v\n 2*B[[]] + 2*B[[[1], [2]]] + 3*B[[[1], [3]]]\n sage: v.f(0)\n ((2*q^2+2)/q)*B[[[1], [2]]]\n sage: v.f(1)\n 3*B[[[2], [3]]]\n sage: v.f(2)\n 2*B[[[1], [3]]]\n sage: v.f(3)\n 3*B[[[1], [4]]]\n sage: v.f(4)\n 3*B[[[1], [-4]]]\n "
F = self.parent()
mc = self.monomial_coefficients(copy=False)
return F.linear_combination(((F.f_on_basis(i, m), c) for (m, c) in mc.items()))
def K(self, i, power=1):
"\n Return the action of `K_i` on ``self`` to the power ``power``.\n\n INPUT:\n\n - ``i`` -- an element of the index set\n - ``power`` -- (default: 1) the power of `K_i`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import AdjointRepresentation\n sage: K = crystals.KirillovReshetikhin(['D',4,2], 1,1)\n sage: R = ZZ['q'].fraction_field()\n sage: V = AdjointRepresentation(R, K)\n sage: v = V.an_element(); v\n 2*B[[]] + 2*B[[[1]]] + 3*B[[[2]]]\n sage: v.K(0)\n 2*B[[]] + 2/q^2*B[[[1]]] + 3*B[[[2]]]\n sage: v.K(1)\n 2*B[[]] + 2*q^2*B[[[1]]] + 3/q^2*B[[[2]]]\n sage: v.K(1, 2)\n 2*B[[]] + 2*q^4*B[[[1]]] + 3/q^4*B[[[2]]]\n sage: v.K(1, -1)\n 2*B[[]] + 2/q^2*B[[[1]]] + 3*q^2*B[[[2]]]\n "
F = self.parent()
mc = self.monomial_coefficients(copy=False)
return F.linear_combination(((F.K_on_basis(i, m, power), c) for (m, c) in mc.items()))
class TensorProducts(TensorProductsCategory):
'\n The category of quantum group representations constructed\n by tensor product of quantum group representations.\n\n .. WARNING::\n\n We use the reversed coproduct in order to match the\n tensor product rule on crystals.\n '
@cached_method
def extra_super_categories(self):
"\n EXAMPLES::\n\n sage: from sage.categories.quantum_group_representations import QuantumGroupRepresentations\n sage: Cat = QuantumGroupRepresentations(ZZ['q'].fraction_field())\n sage: Cat.TensorProducts().extra_super_categories()\n [Category of quantum group representations over\n Fraction Field of Univariate Polynomial Ring in q over Integer Ring]\n "
return [self.base_category()]
class ParentMethods():
def cartan_type(self):
"\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import MinusculeRepresentation\n sage: C = crystals.Tableaux(['C',2], shape=[1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = MinusculeRepresentation(R, C)\n sage: T = tensor([V,V])\n sage: T.cartan_type()\n ['C', 2]\n "
return self._sets[0].cartan_type()
class ParentMethods():
def _test_representation(self, tester=None, **options):
"\n Test the quantum group relations on ``self``.\n\n .. SEEALSO:: :class:`TestSuite`\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import (\n ....: MinusculeRepresentation, AdjointRepresentation)\n sage: C = crystals.Tableaux(['G',2], shape=[1,1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = AdjointRepresentation(R, C)\n sage: V._test_representation()\n\n We verify that ``C`` does not define a minuscule\n representation::\n\n sage: M = MinusculeRepresentation(R, C) # needs sage.combinat sage.modules\n sage: M._test_representation() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n AssertionError: [e,f] = (K-K^-1)/(q_i-q_i^-1) -- i: 1 j: 1\n "
tester = self._tester(**options)
ct = self.cartan_type()
d = ct.symmetrizer()
I = ct.index_set()
A = ct.cartan_matrix()
al = ct.root_system().weight_lattice().simple_roots()
ac = ct.root_system().weight_lattice().simple_coroots()
q = self.q()
from sage.algebras.quantum_groups.q_numbers import q_factorial
def apply_e(d, elt):
for i in d:
elt = elt.e(i)
return elt
def apply_f(d, elt):
for i in d:
elt = elt.f(i)
return elt
count = 0
for x in self.basis():
for i in I:
for j in I:
tester.assertEqual(x.K(j, (- 1)).f(i).K(j, 1), ((q ** (- (al[i].scalar(ac[j]) * d[j]))) * x.f(i)), 'KfK^-1 -- i: {}, j: {}'.format(i, j))
tester.assertEqual(x.K(j, (- 1)).e(i).K(j, 1), ((q ** (al[i].scalar(ac[j]) * d[j])) * x.e(i)), 'KeK^-1 -- i: {}, j: {}'.format(i, j))
if (i == j):
tester.assertEqual((x.f(i).e(i) - x.e(i).f(i)), ((x.K(i, 1) - x.K(i, (- 1))) / ((q ** d[i]) - (q ** (- d[i])))), '[e,f] = (K-K^-1)/(q_i-q_i^-1) -- i: {} j: {}'.format(i, j))
continue
tester.assertEqual((x.f(j).e(i) - x.e(i).f(j)), 0, '[e,f] = 0 -- i: {} j: {}'.format(i, j))
aij = A[(I.index(i), I.index(j))]
tester.assertEqual(0, sum(((((((- 1) ** n) * q_factorial((1 - aij), (q ** d[i]))) / (q_factorial(n, (q ** d[i])) * q_factorial(((1 - aij) - n), (q ** d[i])))) * apply_e(((([i] * ((1 - aij) - n)) + [j]) + ([i] * n)), x)) for n in range(((1 - aij) + 1)))), 'quantum Serre e -- i: {}, j: {}'.format(i, j))
tester.assertEqual(0, sum(((((((- 1) ** n) * q_factorial((1 - aij), (q ** d[i]))) / (q_factorial(n, (q ** d[i])) * q_factorial(((1 - aij) - n), (q ** d[i])))) * apply_f(((([i] * ((1 - aij) - n)) + [j]) + ([i] * n)), x)) for n in range(((1 - aij) + 1)))), 'quantum Serre f -- i: {}, j: {}'.format(i, j))
count += 1
if (count > tester._max_runs):
return
@abstract_method
def cartan_type(self):
"\n Return the Cartan type of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import MinusculeRepresentation\n sage: C = crystals.Tableaux(['C',4], shape=[1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = MinusculeRepresentation(R, C)\n sage: V.cartan_type()\n ['C', 4]\n "
@cached_method
def index_set(self):
"\n Return the index set of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import MinusculeRepresentation\n sage: C = crystals.Tableaux(['C',4], shape=[1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = MinusculeRepresentation(R, C)\n sage: V.index_set()\n (1, 2, 3, 4)\n "
return self.cartan_type().index_set()
def q(self):
"\n Return the quantum parameter `q` of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.algebras.quantum_groups.representations import MinusculeRepresentation\n sage: C = crystals.Tableaux(['C',4], shape=[1])\n sage: R = ZZ['q'].fraction_field()\n sage: V = MinusculeRepresentation(R, C)\n sage: V.q()\n q\n "
return self._q
|
class QuotientFields(Category_singleton):
'\n The category of quotient fields over an integral domain\n\n EXAMPLES::\n\n sage: QuotientFields()\n Category of quotient fields\n sage: QuotientFields().super_categories()\n [Category of fields]\n\n TESTS::\n\n sage: TestSuite(QuotientFields()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: QuotientFields().super_categories()\n [Category of fields]\n '
return [Fields()]
class ParentMethods():
pass
class ElementMethods():
@abstract_method
def numerator(self):
pass
@abstract_method
def denominator(self):
pass
@coerce_binop
def gcd(self, other):
"\n Greatest common divisor\n\n .. NOTE::\n\n In a field, the greatest common divisor is not very informative,\n as it is only determined up to a unit. But in the fraction field\n of an integral domain that provides both gcd and lcm, it is\n possible to be a bit more specific and define the gcd uniquely\n up to a unit of the base ring (rather than in the fraction\n field).\n\n AUTHOR:\n\n - Simon King (2011-02): See :trac:`10771`\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: R.<x> = QQ['x']\n sage: p = (1+x)^3*(1+2*x^2)/(1-x^5)\n sage: q = (1+x)^2*(1+3*x^2)/(1-x^4)\n sage: factor(p)\n (-2) * (x - 1)^-1 * (x + 1)^3 * (x^2 + 1/2) * (x^4 + x^3 + x^2 + x + 1)^-1\n sage: factor(q)\n (-3) * (x - 1)^-1 * (x + 1) * (x^2 + 1)^-1 * (x^2 + 1/3)\n sage: gcd(p, q)\n (x + 1)/(x^7 + x^5 - x^2 - 1)\n sage: factor(gcd(p, q))\n (x - 1)^-1 * (x + 1) * (x^2 + 1)^-1 * (x^4 + x^3 + x^2 + x + 1)^-1\n sage: factor(gcd(p, 1 + x))\n (x - 1)^-1 * (x + 1) * (x^4 + x^3 + x^2 + x + 1)^-1\n sage: factor(gcd(1 + x, q))\n (x - 1)^-1 * (x + 1) * (x^2 + 1)^-1\n\n TESTS:\n\n The following tests that the fraction field returns a correct gcd\n even if the base ring does not provide lcm and gcd::\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: R = ZZ.extension(x^2 + 1, names='i')\n sage: i = R.1\n sage: gcd(5, 3 + 4*i)\n -i - 2\n sage: P.<t> = R[]\n sage: gcd(t, i)\n Traceback (most recent call last):\n ...\n NotImplementedError: Gaussian Integers in Number Field in i with\n defining polynomial x^2 + 1 does not provide a gcd implementation\n for univariate polynomials\n sage: q = t/(t + 1); q.parent()\n Fraction Field of Univariate Polynomial Ring in t over Gaussian\n Integers in Number Field in i with defining polynomial x^2 + 1\n sage: gcd(q, q)\n 1\n sage: q.gcd(0)\n 1\n sage: (q*0).gcd(0)\n 0\n "
P = self.parent()
try:
selfN = self.numerator()
selfD = self.denominator()
selfGCD = selfN.gcd(selfD)
otherN = other.numerator()
otherD = other.denominator()
otherGCD = otherN.gcd(otherD)
selfN = (selfN // selfGCD)
selfD = (selfD // selfGCD)
otherN = (otherN // otherGCD)
otherD = (otherD // otherGCD)
tmp = (P(selfN.gcd(otherN)) / P(selfD.lcm(otherD)))
return tmp
except (AttributeError, NotImplementedError, TypeError, ValueError):
zero = P.zero()
if ((self == zero) and (other == zero)):
return zero
return P.one()
@coerce_binop
def lcm(self, other):
"\n Least common multiple\n\n In a field, the least common multiple is not very informative, as it\n is only determined up to a unit. But in the fraction field of an\n integral domain that provides both gcd and lcm, it is reasonable to\n be a bit more specific and to define the least common multiple so\n that it restricts to the usual least common multiple in the base\n ring and is unique up to a unit of the base ring (rather than up to\n a unit of the fraction field).\n\n The least common multiple is easily described in terms of the\n prime decomposition. A rational number can be written as a product\n of primes with integer (positive or negative) powers in a unique\n way. The least common multiple of two rational numbers `x` and `y`\n can then be defined by specifying that the exponent of every prime\n `p` in `lcm(x,y)` is the supremum of the exponents of `p` in `x`,\n and the exponent of `p` in `y` (where the primes that does not\n appear in the decomposition of `x` or `y` are considered to have\n exponent zero).\n\n\n AUTHOR:\n\n - Simon King (2011-02): See :trac:`10771`\n\n EXAMPLES::\n\n sage: lcm(2/3, 1/5)\n 2\n\n Indeed `2/3 = 2^1 3^{-1} 5^0` and `1/5 = 2^0 3^0\n 5^{-1}`, so `lcm(2/3,1/5)= 2^1 3^0 5^0 = 2`.\n\n sage: lcm(1/3, 1/5)\n 1\n sage: lcm(1/3, 1/6)\n 1/3\n\n Some more involved examples::\n\n sage: # needs sage.libs.pari\n sage: R.<x> = QQ[]\n sage: p = (1+x)^3*(1+2*x^2)/(1-x^5)\n sage: q = (1+x)^2*(1+3*x^2)/(1-x^4)\n sage: factor(p)\n (-2) * (x - 1)^-1 * (x + 1)^3 * (x^2 + 1/2) * (x^4 + x^3 + x^2 + x + 1)^-1\n sage: factor(q)\n (-3) * (x - 1)^-1 * (x + 1) * (x^2 + 1)^-1 * (x^2 + 1/3)\n sage: factor(lcm(p, q))\n (x - 1)^-1 * (x + 1)^3 * (x^2 + 1/3) * (x^2 + 1/2)\n sage: factor(lcm(p, 1 + x))\n (x + 1)^3 * (x^2 + 1/2)\n sage: factor(lcm(1 + x, q))\n (x + 1) * (x^2 + 1/3)\n\n TESTS:\n\n The following tests that the fraction field returns a correct lcm\n even if the base ring does not provide lcm and gcd::\n\n sage: # needs sage.libs.pari sage.rings.number_field\n sage: R = ZZ.extension(x^2+1, names='i')\n sage: i = R.1\n sage: P.<t> = R[]\n sage: lcm(t, i)\n Traceback (most recent call last):\n ...\n NotImplementedError: Gaussian Integers in Number Field in i with\n defining polynomial x^2 + 1 does not provide a gcd implementation\n for univariate polynomials\n sage: q = t/(t + 1); q.parent()\n Fraction Field of Univariate Polynomial Ring in t over Gaussian\n Integers in Number Field in i with defining polynomial x^2 + 1\n sage: lcm(q, q)\n 1\n sage: q.lcm(0)\n 0\n sage: (q*0).lcm(0)\n 0\n\n Check that it is possible to take lcm of a rational and an integer\n (:trac:`17852`)::\n\n sage: (1/2).lcm(2)\n 2\n sage: type((1/2).lcm(2))\n <class 'sage.rings.rational.Rational'>\n "
P = self.parent()
try:
selfN = self.numerator()
selfD = self.denominator()
selfGCD = selfN.gcd(selfD)
otherN = other.numerator()
otherD = other.denominator()
otherGCD = otherN.gcd(otherD)
selfN = (selfN // selfGCD)
selfD = (selfD // selfGCD)
otherN = (otherN // otherGCD)
otherD = (otherD // otherGCD)
return (P(selfN.lcm(otherN)) / P(selfD.gcd(otherD)))
except (AttributeError, NotImplementedError, TypeError, ValueError):
zero = P.zero()
if ((self == zero) or (other == zero)):
return zero
return P.one()
@coerce_binop
def xgcd(self, other):
"\n Return a triple ``(g,s,t)`` of elements of that field such that\n ``g`` is the greatest common divisor of ``self`` and ``other`` and\n ``g = s*self + t*other``.\n\n .. NOTE::\n\n In a field, the greatest common divisor is not very informative,\n as it is only determined up to a unit. But in the fraction field\n of an integral domain that provides both xgcd and lcm, it is\n possible to be a bit more specific and define the gcd uniquely\n up to a unit of the base ring (rather than in the fraction\n field).\n\n EXAMPLES::\n\n sage: QQ(3).xgcd(QQ(2))\n (1, 1, -1)\n sage: QQ(3).xgcd(QQ(1/2))\n (1/2, 0, 1)\n sage: QQ(1/3).xgcd(QQ(2))\n (1/3, 1, 0)\n sage: QQ(3/2).xgcd(QQ(5/2))\n (1/2, 2, -1)\n\n sage: R.<x> = QQ['x']\n sage: p = (1+x)^3*(1+2*x^2)/(1-x^5)\n sage: q = (1+x)^2*(1+3*x^2)/(1-x^4)\n sage: factor(p) # needs sage.libs.pari\n (-2) * (x - 1)^-1 * (x + 1)^3 * (x^2 + 1/2) * (x^4 + x^3 + x^2 + x + 1)^-1\n sage: factor(q) # needs sage.libs.pari\n (-3) * (x - 1)^-1 * (x + 1) * (x^2 + 1)^-1 * (x^2 + 1/3)\n sage: g, s, t = xgcd(p, q)\n sage: g\n (x + 1)/(x^7 + x^5 - x^2 - 1)\n sage: g == s*p + t*q\n True\n\n An example without a well defined gcd or xgcd on its base ring::\n\n sage: # needs sage.rings.number_field\n sage: K = QuadraticField(5)\n sage: O = K.maximal_order()\n sage: R = PolynomialRing(O, 'x')\n sage: F = R.fraction_field()\n sage: x = F.gen(0)\n sage: x.gcd(x+1)\n 1\n sage: x.xgcd(x+1)\n (1, 1/x, 0)\n sage: zero = F.zero()\n sage: zero.gcd(x)\n 1\n sage: zero.xgcd(x)\n (1, 0, 1/x)\n sage: zero.xgcd(zero)\n (0, 0, 0)\n "
P = self.parent()
try:
selfN = self.numerator()
selfD = self.denominator()
selfGCD = selfN.gcd(selfD)
otherN = other.numerator()
otherD = other.denominator()
otherGCD = otherN.gcd(otherD)
selfN = (selfN // selfGCD)
selfD = (selfD // selfGCD)
otherN = (otherN // otherGCD)
otherD = (otherD // otherGCD)
lcmD = selfD.lcm(otherD)
(g, s, t) = selfN.xgcd(otherN)
return ((P(g) / P(lcmD)), (P((s * selfD)) / P(lcmD)), (P((t * otherD)) / P(lcmD)))
except (AttributeError, NotImplementedError, TypeError, ValueError):
zero = self.parent().zero()
one = self.parent().one()
if (self != zero):
return (one, (~ self), zero)
elif (other != zero):
return (one, zero, (~ other))
else:
return (zero, zero, zero)
def factor(self, *args, **kwds):
'\n Return the factorization of ``self`` over the base ring.\n\n INPUT:\n\n - ``*args`` - Arbitrary arguments suitable over the base ring\n - ``**kwds`` - Arbitrary keyword arguments suitable over the base ring\n\n OUTPUT:\n\n - Factorization of ``self`` over the base ring\n\n EXAMPLES::\n\n sage: K.<x> = QQ[]\n sage: f = (x^3+x)/(x-3)\n sage: f.factor() # needs sage.libs.pari\n (x - 3)^-1 * x * (x^2 + 1)\n\n Here is an example to show that :trac:`7868` has been resolved::\n\n sage: R.<x,y> = GF(2)[]\n sage: f = x*y/(x+y)\n sage: f.factor() # needs sage.rings.finite_rings\n (x + y)^-1 * y * x\n '
return (self.numerator().factor(*args, **kwds) / self.denominator().factor(*args, **kwds))
def partial_fraction_decomposition(self, decompose_powers=True):
"\n Decompose fraction field element into a whole part and a list of\n fraction field elements over prime power denominators.\n\n The sum will be equal to the original fraction.\n\n INPUT:\n\n - ``decompose_powers`` -- boolean (default: ``True``);\n whether to decompose prime power denominators as opposed to having\n a single term for each irreducible factor of the denominator\n\n OUTPUT:\n\n Partial fraction decomposition of ``self`` over the base ring.\n\n AUTHORS:\n\n - Robert Bradshaw (2007-05-31)\n\n EXAMPLES::\n\n sage: # needs sage.libs.pari\n sage: S.<t> = QQ[]\n sage: q = 1/(t+1) + 2/(t+2) + 3/(t-3); q\n (6*t^2 + 4*t - 6)/(t^3 - 7*t - 6)\n sage: whole, parts = q.partial_fraction_decomposition(); parts\n [3/(t - 3), 1/(t + 1), 2/(t + 2)]\n sage: sum(parts) == q\n True\n sage: q = 1/(t^3+1) + 2/(t^2+2) + 3/(t-3)^5\n sage: whole, parts = q.partial_fraction_decomposition(); parts\n [1/3/(t + 1), 3/(t^5 - 15*t^4 + 90*t^3 - 270*t^2 + 405*t - 243),\n (-1/3*t + 2/3)/(t^2 - t + 1), 2/(t^2 + 2)]\n sage: sum(parts) == q\n True\n sage: q = 2*t / (t + 3)^2\n sage: q.partial_fraction_decomposition()\n (0, [2/(t + 3), -6/(t^2 + 6*t + 9)])\n sage: for p in q.partial_fraction_decomposition()[1]:\n ....: print(p.factor())\n (2) * (t + 3)^-1\n (-6) * (t + 3)^-2\n sage: q.partial_fraction_decomposition(decompose_powers=False)\n (0, [2*t/(t^2 + 6*t + 9)])\n\n We can decompose over a given algebraic extension::\n\n sage: R.<x> = QQ[sqrt(2)][] # needs sage.rings.number_field sage.symbolic\n sage: r = 1/(x^4+1) # needs sage.rings.number_field sage.symbolic\n sage: r.partial_fraction_decomposition() # needs sage.rings.number_field sage.symbolic\n (0,\n [(-1/4*sqrt2*x + 1/2)/(x^2 - sqrt2*x + 1),\n (1/4*sqrt2*x + 1/2)/(x^2 + sqrt2*x + 1)])\n\n sage: R.<x> = QQ[I][] # of QQ[sqrt(-1)] # needs sage.rings.number_field sage.symbolic\n sage: r = 1/(x^4+1) # needs sage.rings.number_field sage.symbolic\n sage: r.partial_fraction_decomposition() # needs sage.rings.number_field sage.symbolic\n (0, [(-1/2*I)/(x^2 - I), 1/2*I/(x^2 + I)])\n\n We can also ask Sage to find the least extension where the\n denominator factors in linear terms::\n\n sage: # needs sage.rings.number_field\n sage: R.<x> = QQ[]\n sage: r = 1/(x^4+2)\n sage: N = r.denominator().splitting_field('a'); N\n Number Field in a with defining polynomial x^8 - 8*x^6 + 28*x^4 + 16*x^2 + 36\n sage: R1.<x1> = N[]\n sage: r1 = 1/(x1^4+2)\n sage: r1.partial_fraction_decomposition()\n (0,\n [(-1/224*a^6 + 13/448*a^4 - 5/56*a^2 - 25/224)/(x1 - 1/28*a^6 + 13/56*a^4 - 5/7*a^2 - 25/28),\n (1/224*a^6 - 13/448*a^4 + 5/56*a^2 + 25/224)/(x1 + 1/28*a^6 - 13/56*a^4 + 5/7*a^2 + 25/28),\n (-5/1344*a^7 + 43/1344*a^5 - 85/672*a^3 - 31/672*a)/(x1 - 5/168*a^7 + 43/168*a^5 - 85/84*a^3 - 31/84*a),\n (5/1344*a^7 - 43/1344*a^5 + 85/672*a^3 + 31/672*a)/(x1 + 5/168*a^7 - 43/168*a^5 + 85/84*a^3 + 31/84*a)])\n\n Or we may work directly over an algebraically closed field::\n\n sage: R.<x> = QQbar[] # needs sage.rings.number_field\n sage: r = 1/(x^4+1) # needs sage.rings.number_field\n sage: r.partial_fraction_decomposition() # needs sage.rings.number_field\n (0,\n [(-0.1767766952966369? - 0.1767766952966369?*I)/(x - 0.7071067811865475? - 0.7071067811865475?*I),\n (-0.1767766952966369? + 0.1767766952966369?*I)/(x - 0.7071067811865475? + 0.7071067811865475?*I),\n (0.1767766952966369? - 0.1767766952966369?*I)/(x + 0.7071067811865475? - 0.7071067811865475?*I),\n (0.1767766952966369? + 0.1767766952966369?*I)/(x + 0.7071067811865475? + 0.7071067811865475?*I)])\n\n We do the best we can over inexact fields::\n\n sage: # needs sage.rings.number_field sage.rings.real_mpfr\n sage: R.<x> = RealField(20)[]\n sage: q = 1/(x^2 + x + 2)^2 + 1/(x-1); q\n (x^4 + 2.0000*x^3\n + 5.0000*x^2 + 5.0000*x + 3.0000)/(x^5 + x^4 + 3.0000*x^3 - x^2 - 4.0000)\n sage: whole, parts = q.partial_fraction_decomposition(); parts\n [1.0000/(x - 1.0000),\n 1.0000/(x^4 + 2.0000*x^3 + 5.0000*x^2 + 4.0000*x + 4.0000)]\n sage: sum(parts)\n (x^4 + 2.0000*x^3\n + 5.0000*x^2 + 5.0000*x + 3.0000)/(x^5 + x^4 + 3.0000*x^3 - x^2 - 4.0000)\n\n TESTS:\n\n We test partial fraction for irreducible denominators::\n\n sage: R.<x> = ZZ[]\n sage: q = x^2/(x-1)\n sage: q.partial_fraction_decomposition() # needs sage.libs.pari\n (x + 1, [1/(x - 1)])\n sage: q = x^10/(x-1)^5\n sage: whole, parts = q.partial_fraction_decomposition() # needs sage.libs.pari\n sage: whole + sum(parts) == q # needs sage.libs.pari\n True\n\n And also over finite fields (see :trac:`6052`, :trac:`9945`)::\n\n sage: R.<x> = GF(2)[]\n sage: q = (x+1)/(x^3+x+1)\n sage: q.partial_fraction_decomposition() # needs sage.libs.pari\n (0, [(x + 1)/(x^3 + x + 1)])\n\n sage: R.<x> = GF(11)[]\n sage: q = x + 1 + 1/(x+1) + x^2/(x^3 + 2*x + 9)\n sage: q.partial_fraction_decomposition() # needs sage.libs.pari\n (x + 1, [1/(x + 1), x^2/(x^3 + 2*x + 9)])\n\n And even the rationals::\n\n sage: (26/15).partial_fraction_decomposition()\n (1, [1/3, 2/5])\n sage: (26/75).partial_fraction_decomposition()\n (-1, [2/3, 3/5, 2/25])\n\n A larger example::\n\n sage: S.<t> = QQ[]\n sage: r = t / (t^3+1)^5\n sage: r.partial_fraction_decomposition() # needs sage.libs.pari\n (0,\n [-35/729/(t + 1),\n -35/729/(t^2 + 2*t + 1),\n -25/729/(t^3 + 3*t^2 + 3*t + 1),\n -4/243/(t^4 + 4*t^3 + 6*t^2 + 4*t + 1),\n -1/243/(t^5 + 5*t^4 + 10*t^3 + 10*t^2 + 5*t + 1),\n (35/729*t - 35/729)/(t^2 - t + 1),\n (25/729*t - 8/729)/(t^4 - 2*t^3 + 3*t^2 - 2*t + 1),\n (-1/81*t + 5/81)/(t^6 - 3*t^5 + 6*t^4 - 7*t^3 + 6*t^2 - 3*t + 1),\n (-2/27*t + 1/9)/(t^8 - 4*t^7 + 10*t^6 - 16*t^5 + 19*t^4 - 16*t^3 + 10*t^2 - 4*t + 1),\n (-2/27*t + 1/27)/(t^10 - 5*t^9 + 15*t^8 - 30*t^7 + 45*t^6 - 51*t^5 + 45*t^4 - 30*t^3 + 15*t^2 - 5*t + 1)])\n sage: sum(r.partial_fraction_decomposition()[1]) == r # needs sage.libs.pari\n True\n\n Some special cases::\n\n sage: R = Frac(QQ['x']); x = R.gen()\n sage: x.partial_fraction_decomposition()\n (x, [])\n sage: R(0).partial_fraction_decomposition()\n (0, [])\n sage: R(1).partial_fraction_decomposition()\n (1, [])\n sage: (1/x).partial_fraction_decomposition() # needs sage.libs.pari\n (0, [1/x])\n sage: (1/x+1/x^3).partial_fraction_decomposition() # needs sage.libs.pari\n (0, [1/x, 1/x^3])\n\n This was fixed in :trac:`16240`::\n\n sage: # needs sage.libs.pari\n sage: R.<x> = QQ['x']\n sage: p = 1/(-x + 1)\n sage: whole, parts = p.partial_fraction_decomposition()\n sage: p == sum(parts)\n True\n sage: p = 3/(-x^4 + 1)\n sage: whole, parts = p.partial_fraction_decomposition()\n sage: p == sum(parts)\n True\n sage: p = (6*x^2 - 9*x + 5)/(-x^3 + 3*x^2 - 3*x + 1)\n sage: whole, parts = p.partial_fraction_decomposition()\n sage: p == sum(parts)\n True\n "
denom = self.denominator()
(whole, numer) = self.numerator().quo_rem(denom)
factors = denom.factor()
if (not self.parent().is_exact()):
all = {}
for r in factors:
all[r[0]] = 0
for r in factors:
all[r[0]] += r[1]
factors = sorted(all.items())
from sage.rings.fraction_field_element import FractionFieldElement_1poly_field
is_polynomial_over_field = isinstance(self, FractionFieldElement_1poly_field)
running_total = 0
parts = []
for (r, e) in factors:
powers = [1]
for ee in range(e):
powers.append((powers[(- 1)] * r))
d = powers[e]
denom_div_d = (denom // d)
n = (((numer % d) * denom_div_d.inverse_mod(d)) % d)
if (not is_polynomial_over_field):
running_total += (n * denom_div_d)
if decompose_powers:
r_parts = []
for ee in range(e, 0, (- 1)):
(n, n_part) = n.quo_rem(r)
if n_part:
r_parts.append((n_part / powers[ee]))
parts.extend(reversed(r_parts))
else:
parts.append((n / powers[e]))
if (not is_polynomial_over_field):
whole = ((self.numerator() - running_total) // denom)
return (whole, parts)
def derivative(self, *args):
"\n The derivative of this rational function, with respect to variables\n supplied in args.\n\n Multiple variables and iteration counts may be supplied; see\n documentation for the global derivative() function for more\n details.\n\n .. SEEALSO::\n\n :meth:`_derivative`\n\n EXAMPLES::\n\n sage: F.<x> = Frac(QQ['x'])\n sage: (1/x).derivative()\n -1/x^2\n\n ::\n\n sage: (x+1/x).derivative(x, 2)\n 2/x^3\n\n ::\n\n sage: F.<x,y> = Frac(QQ['x,y'])\n sage: (1/(x+y)).derivative(x,y)\n 2/(x^3 + 3*x^2*y + 3*x*y^2 + y^3)\n "
from sage.misc.derivative import multi_derivative
return multi_derivative(self, args)
def _derivative(self, var=None):
"\n Returns the derivative of this rational function with respect to the\n variable ``var``.\n\n Over a ring with a working gcd implementation, the derivative of a\n fraction `f/g`, supposed to be given in lowest terms, is computed as\n `(f'(g/d) - f(g'/d))/(g(g'/d))`, where `d` is a greatest common\n divisor of `f` and `g`.\n\n INPUT:\n\n - ``var`` - Variable with respect to which the derivative is computed\n\n OUTPUT:\n\n - Derivative of ``self`` with respect to ``var``\n\n .. SEEALSO::\n\n :meth:`derivative`\n\n EXAMPLES::\n\n sage: F.<x> = Frac(QQ['x'])\n sage: t = 1/x^2\n sage: t._derivative(x)\n -2/x^3\n sage: t.derivative()\n -2/x^3\n\n ::\n\n sage: F.<x,y> = Frac(QQ['x,y'])\n sage: t = (x*y/(x+y))\n sage: t._derivative(x)\n y^2/(x^2 + 2*x*y + y^2)\n sage: t._derivative(y)\n x^2/(x^2 + 2*x*y + y^2)\n\n TESTS::\n\n sage: F.<t> = Frac(ZZ['t'])\n sage: F(0).derivative()\n 0\n sage: F(2).derivative()\n 0\n sage: t.derivative()\n 1\n sage: (1+t^2).derivative()\n 2*t\n sage: (1/t).derivative()\n -1/t^2\n sage: ((t+2)/(t-1)).derivative()\n -3/(t^2 - 2*t + 1)\n sage: (t/(1+2*t+t^2)).derivative()\n (-t + 1)/(t^3 + 3*t^2 + 3*t + 1)\n "
R = self.parent()
if (var in R.gens()):
var = R.ring()(var)
num = self.numerator()
den = self.denominator()
if num.is_zero():
return R.zero()
if R.is_exact():
try:
numder = num._derivative(var)
dender = den._derivative(var)
d = den.gcd(dender)
den = (den // d)
dender = (dender // d)
tnum = ((numder * den) - (num * dender))
tden = (self.denominator() * den)
if ((not tden.is_one()) and tden.is_unit()):
try:
tnum = (tnum * tden.inverse_of_unit())
tden = R.ring().one()
except AttributeError:
pass
except NotImplementedError:
pass
return self.__class__(R, tnum, tden, coerce=False, reduce=False)
except AttributeError:
pass
except NotImplementedError:
pass
except TypeError:
pass
num = self.numerator()
den = self.denominator()
num = ((num._derivative(var) * den) - (num * den._derivative(var)))
den = (den ** 2)
return self.__class__(R, num, den, coerce=False, reduce=False)
|
class QuotientsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Quotients'
@classmethod
def default_super_categories(cls, category):
'\n Returns the default super categories of ``category.Quotients()``\n\n Mathematical meaning: if `A` is a quotient of `B` in the\n category `C`, then `A` is also a subquotient of `B` in the\n category `C`.\n\n INPUT:\n\n - ``cls`` -- the class ``QuotientsCategory``\n - ``category`` -- a category `Cat`\n\n OUTPUT: a (join) category\n\n In practice, this returns ``category.Subquotients()``, 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`` and ``cat.Quotients()`` for\n each ``cat`` in the super categories of ``category``).\n\n EXAMPLES:\n\n Consider ``category=Groups()``, which has ``cat=Monoids()`` as\n super category. Then, a subgroup of a group `G` is\n simultaneously a subquotient of `G`, a group by itself, and a\n quotient monoid of ``G``::\n\n sage: Groups().Quotients().super_categories()\n [Category of groups, Category of subquotients of monoids, Category of quotients of semigroups]\n\n Mind the last item above: there is indeed currently nothing\n implemented about quotient monoids.\n\n This resulted from the following call::\n\n sage: sage.categories.quotients.QuotientsCategory.default_super_categories(Groups())\n Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups\n '
return Category.join([category.Subquotients(), super().default_super_categories(category)])
|
class RTrivialSemigroups(CategoryWithAxiom):
def extra_super_categories(self):
'\n Implement the fact that a `R`-trivial semigroup is `H`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().RTrivial().extra_super_categories()\n [Category of h trivial semigroups]\n '
return [Semigroups().HTrivial()]
def Commutative_extra_super_categories(self):
'\n Implement the fact that a commutative `R`-trivial semigroup is `J`-trivial.\n\n EXAMPLES::\n\n sage: Semigroups().RTrivial().Commutative_extra_super_categories()\n [Category of j trivial semigroups]\n\n TESTS::\n\n sage: Semigroups().RTrivial().Commutative() is Semigroups().JTrivial().Commutative()\n True\n '
return [self.JTrivial()]
|
class RealizationsCategory(RegressiveCovariantConstructionCategory):
'\n An abstract base class for all categories of realizations category\n\n Relization are implemented as\n :class:`~sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory`.\n See there for the documentation of how the various bindings such\n as ``Sets().Realizations()`` and ``P.Realizations()``, where ``P``\n is a parent, work.\n\n .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`\n\n TESTS::\n\n sage: Sets().Realizations\n <bound method Realizations of Category of sets>\n sage: Sets().Realizations()\n Category of realizations of sets\n sage: Sets().Realizations().super_categories()\n [Category of sets]\n sage: Groups().Realizations().super_categories()\n [Category of groups, Category of realizations of unital magmas]\n '
_functor_category = 'Realizations'
|
def Realizations(self):
'\n Return the category of realizations of the parent ``self`` or of objects\n of the category ``self``\n\n INPUT:\n\n - ``self`` -- a parent or a concrete category\n\n .. NOTE:: this *function* is actually inserted as a *method* in the class\n :class:`~sage.categories.category.Category` (see\n :meth:`~sage.categories.category.Category.Realizations`). It is defined\n here for code locality reasons.\n\n EXAMPLES:\n\n The category of realizations of some algebra::\n\n sage: Algebras(QQ).Realizations()\n Join of Category of algebras over Rational Field\n and Category of realizations of unital magmas\n\n The category of realizations of a given algebra::\n\n sage: A = Sets().WithRealizations().example(); A # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.Realizations() # needs sage.modules\n Category of realizations of\n The subset algebra of {1, 2, 3} over Rational Field\n\n sage: C = GradedHopfAlgebrasWithBasis(QQ).Realizations(); C\n Join of Category of graded Hopf algebras with basis over Rational Field\n and Category of realizations of Hopf algebras over Rational Field\n sage: C.super_categories()\n [Category of graded Hopf algebras with basis over Rational Field,\n Category of realizations of Hopf algebras over Rational Field]\n\n sage: TestSuite(C).run()\n\n .. SEEALSO::\n\n - :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`\n - :class:`ClasscallMetaclass`\n\n .. TODO::\n\n Add an optional argument to allow for::\n\n sage: Realizations(A, category=Blahs()) # todo: not implemented\n '
if isinstance(self, Category):
return RealizationsCategory.category_of(self)
else:
return getattr(self.__class__, 'Realizations')(self)
|
class Category_realization_of_parent(Category_over_base, BindableClass):
'\n An abstract base class for categories of all realizations of a given parent\n\n INPUT:\n\n - ``parent_with_realization`` -- a parent\n\n .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example(); A # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n\n The role of this base class is to implement some technical goodies, like\n the binding ``A.Realizations()`` when a subclass ``Realizations`` is\n implemented as a nested class in ``A``\n (see the :mod:`code of the example <sage.categories.examples.with_realizations.SubsetAlgebra>`)::\n\n sage: C = A.Realizations(); C # needs sage.modules\n Category of realizations of\n The subset algebra of {1, 2, 3} over Rational Field\n\n as well as the name for that category.\n '
def __init__(self, parent_with_realization):
'\n TESTS::\n\n sage: # needs sage.combinat sage.modules\n sage: from sage.categories.realizations import Category_realization_of_parent\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: C = A.Realizations(); C\n Category of realizations of\n The subset algebra of {1, 2, 3} over Rational Field\n sage: isinstance(C, Category_realization_of_parent)\n True\n sage: C.parent_with_realization\n The subset algebra of {1, 2, 3} over Rational Field\n sage: TestSuite(C).run(skip=["_test_category_over_bases"])\n\n .. TODO::\n\n Fix the failing test by making ``C`` a singleton\n category. This will require some fiddling with the\n assertion in :meth:`Category_singleton.__classcall__`\n '
Category_over_base.__init__(self, parent_with_realization)
self.parent_with_realization = parent_with_realization
def _get_name(self):
'\n Return a human readable string specifying which kind of bases this category is for\n\n It is obtained by splitting and lower casing the last part of\n the class name.\n\n EXAMPLES::\n\n sage: from sage.categories.realizations import Category_realization_of_parent\n sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent):\n ....: def super_categories(self): return [Objects()]\n sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") # needs sage.combinat sage.modules\n sage: MultiplicativeBasesOnPrimitiveElements(Sym)._get_name() # needs sage.combinat sage.modules\n \'multiplicative bases on primitive elements\'\n '
import re
return re.sub('.[A-Z]', (lambda s: ((s.group()[0] + ' ') + s.group()[1])), self.__class__.__base__.__name__.split('.')[(- 1)]).lower()
def _repr_object_names(self):
'\n Return the name of the objects of this category.\n\n .. SEEALSO:: :meth:`Category._repr_object_names`\n\n EXAMPLES::\n\n sage: from sage.categories.realizations import Category_realization_of_parent\n sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent):\n ....: def super_categories(self): return [Objects()]\n sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") # needs sage.combinat sage.modules\n sage: C = MultiplicativeBasesOnPrimitiveElements(Sym); C # needs sage.combinat sage.modules\n Category of multiplicative bases on primitive elements of Sym\n sage: C._repr_object_names() # needs sage.combinat sage.modules\n \'multiplicative bases on primitive elements of Sym\'\n '
return '{} of {}'.format(self._get_name(), self.base())
|
class RegularCrystals(Category_singleton):
'\n The category of regular crystals.\n\n A crystal is called *regular* if every vertex `b` satisfies\n\n .. MATH::\n\n \\varepsilon_i(b) = \\max\\{ k \\mid e_i^k(b) \\neq 0 \\} \\quad \\text{and}\n \\quad \\varphi_i(b) = \\max\\{ k \\mid f_i^k(b) \\neq 0 \\}.\n\n .. NOTE::\n\n Regular crystals are sometimes referred to as *normal*. When only one\n of the conditions (on either `\\varphi_i` or `\\varepsilon_i`) holds,\n these crystals are sometimes called *seminormal* or *semiregular*.\n\n EXAMPLES::\n\n sage: C = RegularCrystals()\n sage: C\n Category of regular 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 = RegularCrystals().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 super_categories(self):
'\n EXAMPLES::\n\n sage: RegularCrystals().super_categories()\n [Category of crystals]\n '
return [Crystals()]
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 = RegularCrystals().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)
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of regular crystals defines no new\n structure: it only relates `\\varepsilon_a` and `\\varphi_a` to\n `e_a` and `f_a` respectively.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: RegularCrystals().additional_structure()\n '
return None
class MorphismMethods():
def is_isomorphism(self):
"\n Check if ``self`` is a crystal isomorphism, which is true\n if and only if this is a strict embedding with the same number\n of connected components.\n\n EXAMPLES::\n\n sage: A21 = RootSystem(['A',2,1])\n sage: La = A21.weight_space(extended=True).fundamental_weights()\n sage: B = crystals.LSPaths(La[0])\n sage: La = A21.weight_lattice(extended=True).fundamental_weights()\n sage: C = crystals.GeneralizedYoungWalls(2, La[0])\n sage: H = Hom(B, C)\n sage: from sage.categories.highest_weight_crystals import HighestWeightCrystalMorphism\n sage: class Psi(HighestWeightCrystalMorphism):\n ....: def is_strict(self):\n ....: return True\n sage: psi = Psi(H, C.module_generators); psi\n ['A', 2, 1] Crystal morphism:\n From: The crystal of LS paths of type ['A', 2, 1] and weight Lambda[0]\n To: Highest weight crystal of generalized Young walls\n of Cartan type ['A', 2, 1] and highest weight Lambda[0]\n Defn: (Lambda[0],) |--> []\n sage: psi.is_isomorphism()\n True\n "
return (self.is_strict() and (self.domain().number_of_connected_components() == self.codomain().number_of_connected_components()))
class ParentMethods():
def demazure_operator(self, element, reduced_word):
'\n Returns the application of Demazure operators `D_i` for `i` from\n ``reduced_word`` on ``element``.\n\n INPUT:\n\n - ``element`` -- an element of a free module indexed by the\n underlying crystal\n - ``reduced_word`` -- a reduced word of the Weyl group of the\n same type as the underlying crystal\n\n OUTPUT:\n\n - an element of the free module indexed by the underlying crystal\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux([\'A\',2], shape=[2,1])\n sage: C = CombinatorialFreeModule(QQ, T)\n sage: t = T.highest_weight_vector()\n sage: b = 2*C(t)\n sage: T.demazure_operator(b,[1,2,1])\n 2*B[[[1, 1], [2]]] + 2*B[[[1, 2], [2]]] + 2*B[[[1, 3], [2]]]\n + 2*B[[[1, 1], [3]]] + 2*B[[[1, 2], [3]]] + 2*B[[[1, 3], [3]]]\n + 2*B[[[2, 2], [3]]] + 2*B[[[2, 3], [3]]]\n\n The Demazure operator is idempotent::\n\n sage: T = crystals.Tableaux("A1", shape=[4])\n sage: C = CombinatorialFreeModule(QQ, T)\n sage: b = C(T.module_generators[0]); b\n B[[[1, 1, 1, 1]]]\n sage: e = T.demazure_operator(b,[1]); e\n B[[[1, 1, 1, 1]]] + B[[[1, 1, 1, 2]]] + B[[[1, 1, 2, 2]]]\n + B[[[1, 2, 2, 2]]] + B[[[2, 2, 2, 2]]]\n sage: e == T.demazure_operator(e,[1])\n True\n\n sage: all(T.demazure_operator(T.demazure_operator(C(t),[1]),[1])\n ....: == T.demazure_operator(C(t),[1]) for t in T)\n True\n '
M = element.parent()
for i in reversed(reduced_word):
element = M.linear_combination(((c.demazure_operator_simple(i), coeff) for (c, coeff) in element))
return element
def demazure_subcrystal(self, element, reduced_word, only_support=True):
"\n Return the subcrystal corresponding to the application of\n Demazure operators `D_i` for `i` from ``reduced_word`` on\n ``element``.\n\n INPUT:\n\n - ``element`` -- an element of a free module indexed by the\n underlying crystal\n - ``reduced_word`` -- a reduced word of the Weyl group of the\n same type as the underlying crystal\n - ``only_support`` -- (default: ``True``) only include arrows\n corresponding to the support of ``reduced_word``\n\n OUTPUT:\n\n - the Demazure subcrystal\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T.highest_weight_vector()\n sage: S = T.demazure_subcrystal(t, [1,2])\n sage: list(S)\n [[[1, 1], [2]], [[1, 2], [2]], [[1, 1], [3]],\n [[1, 2], [3]], [[2, 2], [3]]]\n sage: S = T.demazure_subcrystal(t, [2,1])\n sage: list(S)\n [[[1, 1], [2]], [[1, 2], [2]], [[1, 1], [3]],\n [[1, 3], [2]], [[1, 3], [3]]]\n\n We construct an example where we don't only want the arrows\n indicated by the support of the reduced word::\n\n sage: K = crystals.KirillovReshetikhin(['A',1,1], 1, 2)\n sage: mg = K.module_generator()\n sage: S = K.demazure_subcrystal(mg, [1])\n sage: S.digraph().edges(sort=True)\n [([[1, 1]], [[1, 2]], 1), ([[1, 2]], [[2, 2]], 1)]\n sage: S = K.demazure_subcrystal(mg, [1], only_support=False)\n sage: S.digraph().edges(sort=True)\n [([[1, 1]], [[1, 2]], 1),\n ([[1, 2]], [[1, 1]], 0),\n ([[1, 2]], [[2, 2]], 1),\n ([[2, 2]], [[1, 2]], 0)]\n "
from sage.combinat.free_module import CombinatorialFreeModule
from sage.rings.rational_field import QQ
C = CombinatorialFreeModule(QQ, self)
D = self.demazure_operator(C(element), reduced_word)
if only_support:
index_set = tuple(frozenset(reduced_word))
else:
index_set = self.cartan_type().index_set()
return self.subcrystal(contained=D.support(), generators=[element], index_set=index_set)
def _test_stembridge_local_axioms(self, index_set=None, verbose=False, complete=False, **options):
"\n This implements tests for the Stembridge local characterization\n on the finite crystal ``self``.\n\n The current implementation only uses the rules for simply-laced\n types. Crystals of other types should still pass the test, but\n expansion of this test to non-simply laced type would be desirable.\n\n One can specify an index set smaller than the full index set of\n the crystal, using the option ``index_set``.\n\n Running with ``verbose=True`` will print each node for which a\n local axiom test applies.\n\n Running with ``complete=True`` will continue to run the test past\n the first failure of the local axioms. This is probably only\n useful in conjunction with the verbose option, to see all places\n where the local axioms fail.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',3], shape=[2,1])\n sage: T._test_stembridge_local_axioms()\n True\n sage: T._test_stembridge_local_axioms(verbose=True)\n True\n sage: T._test_stembridge_local_axioms(index_set=[1,3])\n True\n\n sage: B = Crystals().example(choice='naive')\n sage: B._test_stembridge_local_axioms()\n Traceback (most recent call last):\n ...\n AssertionError: None\n "
tester = self._tester(**options)
goodness = True
i = 0
for x in self:
goodness = x._test_stembridge_local_axioms(index_set, verbose)
if ((not goodness) and (not complete)):
tester.fail()
i += 1
if (i > tester._max_runs):
return
tester.assertTrue(goodness)
return goodness
def dual_equivalence_graph(self, X=None, index_set=None, directed=True):
"\n Return the dual equivalence graph indexed by ``index_set``\n on the subset ``X`` of ``self``.\n\n Let `b \\in B` be an element of weight `0`, so `\\varepsilon_j(b)\n = \\varphi_j(b)` for all `j \\in I`, where `I` is the indexing\n set. We say `b'` is an `i`-elementary dual equivalence\n transformation of `b` (where `i \\in I`) if\n\n * `\\varepsilon_i(b) = 1` and `\\varepsilon_{i-1}(b) = 0`, and\n * `b' = f_{i-1} f_i e_{i-1} e_i b`.\n\n We can do the inverse procedure by interchanging `i` and `i-1`\n above.\n\n .. NOTE::\n\n If the index set is not an ordered interval, we let\n `i - 1` mean the index appearing before `i` in `I`.\n\n This definition comes from [As2008]_ Section 4 (where our\n `\\varphi_j(b)` and `\\varepsilon_j(b)` are denoted by\n `\\epsilon(b, j)` and `-\\delta(b, j)`, respectively).\n\n The dual equivalence graph of `B` is defined to be the\n colored graph whose vertices are the elements of `B` of\n weight `0`, and whose edges of color `i` (for `i \\in I`)\n connect pairs `\\{ b, b' \\}` such that `b'` is an\n `i`-elementary dual equivalence transformation of `b`.\n\n .. NOTE::\n\n This dual equivalence graph is a generalization of\n `\\mathcal{G}\\left(\\mathcal{X}\\right)` in [As2008]_\n Section 4 except we do not require\n `\\varepsilon_i(b) = 0, 1` for all `i`.\n\n This definition can be generalized by choosing a subset `X`\n of the set of all vertices of `B` of weight `0`, and\n restricting the dual equivalence graph to the vertex set\n `X`.\n\n INPUT:\n\n - ``X`` -- (optional) the vertex set `X` (default:\n the whole set of vertices of ``self`` of weight `0`)\n - ``index_set`` -- (optional) the index set `I`\n (default: the whole index set of ``self``); this has\n to be a subset of the index set of ``self`` (as a list\n or tuple)\n - ``directed`` -- (default: ``True``) whether to have the\n dual equivalence graph be directed, where the head of\n an edge `b - b'` is `b` and the tail is\n `b' = f_{i-1} f_i e_{i-1} e_i b`)\n\n .. SEEALSO::\n\n :meth:`sage.combinat.partition.Partition.dual_equivalence_graph`\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',3], shape=[2,2])\n sage: G = T.dual_equivalence_graph()\n sage: G.edges(sort=True)\n [([[1, 3], [2, 4]], [[1, 2], [3, 4]], 2),\n ([[1, 2], [3, 4]], [[1, 3], [2, 4]], 3)]\n sage: T = crystals.Tableaux(['A',4], shape=[3,2])\n sage: G = T.dual_equivalence_graph()\n sage: G.edges(sort=True)\n [([[1, 3, 5], [2, 4]], [[1, 3, 4], [2, 5]], 4),\n ([[1, 3, 5], [2, 4]], [[1, 2, 5], [3, 4]], 2),\n ([[1, 3, 4], [2, 5]], [[1, 2, 4], [3, 5]], 2),\n ([[1, 2, 5], [3, 4]], [[1, 3, 5], [2, 4]], 3),\n ([[1, 2, 4], [3, 5]], [[1, 2, 3], [4, 5]], 3),\n ([[1, 2, 3], [4, 5]], [[1, 2, 4], [3, 5]], 4)]\n\n sage: T = crystals.Tableaux(['A',4], shape=[3,1])\n sage: G = T.dual_equivalence_graph(index_set=[1,2,3])\n sage: G.vertices(sort=True)\n [[[1, 3, 4], [2]], [[1, 2, 4], [3]], [[1, 2, 3], [4]]]\n sage: G.edges(sort=True)\n [([[1, 3, 4], [2]], [[1, 2, 4], [3]], 2),\n ([[1, 2, 4], [3]], [[1, 2, 3], [4]], 3)]\n\n TESTS::\n\n sage: T = crystals.Tableaux(['A',4], shape=[3,1])\n sage: G = T.dual_equivalence_graph(index_set=[2,3])\n sage: G.edges(sort=True)\n [([[1, 2, 4], [3]], [[1, 2, 3], [4]], 3),\n ([[2, 4, 5], [3]], [[2, 3, 5], [4]], 3)]\n sage: G.vertices(sort=True)\n [[[1, 3, 4], [2]],\n [[1, 2, 4], [3]],\n [[2, 4, 5], [3]],\n [[1, 2, 3], [4]],\n [[2, 3, 5], [4]],\n [[1, 1, 1], [5]],\n [[1, 1, 5], [5]],\n [[1, 5, 5], [5]],\n [[2, 3, 4], [5]]]\n "
if (index_set is None):
index_set = self.index_set()
def wt_zero(x):
for i in index_set:
if (x.epsilon(i) != x.phi(i)):
return False
return True
if (X is None):
X = [x for x in self if wt_zero(x)]
checker = (lambda x: True)
elif any(((not wt_zero(x)) for x in X)):
raise ValueError('the elements are not all weight 0')
else:
checker = (lambda x: (x in X))
edges = []
for x in X:
for (k, i) in enumerate(index_set[1:]):
im = index_set[k]
if ((x.epsilon(i) == 1) and (x.epsilon(im) == 0)):
y = x.e(i).e(im).f(i).f(im)
if checker(y):
edges.append([x, y, i])
from sage.graphs.digraph import DiGraph
G = DiGraph([X, edges], format='vertices_and_edges', immutable=True)
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 epsilon(self, i):
"\n Return `\\varepsilon_i` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).epsilon(1)\n 0\n sage: C(2).epsilon(1)\n 1\n "
assert (i in self.index_set())
x = self.e(i)
eps = 0
while (x is not None):
x = x.e(i)
eps = (eps + 1)
return eps
def phi(self, i):
"\n Return `\\varphi_i` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).phi(1)\n 1\n sage: C(2).phi(1)\n 0\n "
assert (i in self.index_set())
x = self.f(i)
phi = 0
while (x is not None):
x = x.f(i)
phi += 1
return phi
def weight(self):
"\n Return the weight of this crystal element.\n\n EXAMPLES::\n\n sage: C = crystals.Letters(['A',5])\n sage: C(1).weight()\n (1, 0, 0, 0, 0, 0)\n "
return (self.Phi() - self.Epsilon())
def demazure_operator_simple(self, i, ring=None):
"\n Return the Demazure operator `D_i` applied to ``self``.\n\n INPUT:\n\n - ``i`` -- an element of the index set of the underlying crystal\n - ``ring`` -- (default: ``QQ``) a ring\n\n OUTPUT:\n\n An element of the ``ring``-free module indexed by the underlying\n crystal.\n\n Let `r = \\langle \\mathrm{wt}(b), \\alpha^{\\vee}_i \\rangle`, then\n `D_i(b)` is defined as follows:\n\n - If `r \\geq 0`, this returns the sum of the elements obtained\n from ``self`` by application of `f_i^k` for `0 \\leq k \\leq r`.\n - If `r < 0`, this returns the opposite of the sum of the\n elements obtained by application of `e_i^k` for `0 < k < -r`.\n\n REFERENCES:\n\n - [Li1995]_\n\n - [Ka1993]_\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,2],[2]])\n sage: t.demazure_operator_simple(2)\n B[[[1, 2], [2]]] + B[[[1, 3], [2]]] + B[[[1, 3], [3]]]\n sage: t.demazure_operator_simple(2).parent()\n Algebra of The crystal of tableaux of type ['A', 2] and shape(s) [[2, 1]]\n over Integer Ring\n\n sage: t.demazure_operator_simple(1)\n 0\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],2,1)\n sage: t = K(rows=[[3],[2]])\n sage: t.demazure_operator_simple(0)\n B[[[1, 2]]] + B[[[2, 3]]]\n\n TESTS::\n\n sage: K = crystals.KirillovReshetikhin(['A',2,1],1,1)\n sage: x = K.an_element(); x\n [[1]]\n sage: x.demazure_operator_simple(0)\n 0\n sage: x.demazure_operator_simple(0, ring = QQ).parent()\n Algebra of Kirillov-Reshetikhin crystal of type ['A', 2, 1] with (r,s)=(1,1)\n over Rational Field\n "
from sage.rings.integer_ring import ZZ
if (ring is None):
ring = ZZ
C = self.parent().algebra(ring)
r = (self.phi(i) - self.epsilon(i))
if (r >= 0):
l = [self]
element = self
for k in range(r):
element = element.f(i)
l.append(element)
return C.sum_of_monomials(l)
else:
l = []
element = self
for k in range(((- r) - 1)):
element = element.e(i)
l.append(element)
return (- C.sum_of_monomials(l))
def stembridgeDelta_depth(self, i, j):
"\n Return the difference in the `j`-depth of ``self`` and `e_i`\n of ``self``, where `i` and `j` are in the index set of the\n underlying crystal. This function is useful for checking the\n Stembridge local axioms for crystal bases.\n\n The `i`-depth of a crystal node `x` is `-\\varepsilon_i(x)`.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,2],[2]])\n sage: t.stembridgeDelta_depth(1,2)\n 0\n sage: s = T(rows=[[2,3],[3]])\n sage: s.stembridgeDelta_depth(1,2)\n -1\n "
if (self.e(i) is None):
return 0
return ((- self.e(i).epsilon(j)) + self.epsilon(j))
def stembridgeDelta_rise(self, i, j):
"\n Return the difference in the `j`-rise of ``self`` and `e_i` of\n ``self``, where `i` and `j` are in the index set of the\n underlying crystal. This function is useful for checking the\n Stembridge local axioms for crystal bases.\n\n The `i`-rise of a crystal node `x` is `\\varphi_i(x)`.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,2],[2]])\n sage: t.stembridgeDelta_rise(1,2)\n -1\n sage: s = T(rows=[[2,3],[3]])\n sage: s.stembridgeDelta_rise(1,2)\n 0\n "
if (self.e(i) is None):
return 0
return (self.e(i).phi(j) - self.phi(j))
def stembridgeDel_depth(self, i, j):
"\n Return the difference in the `j`-depth of ``self`` and `f_i` of\n ``self``, where `i` and `j` are in the index set of the\n underlying crystal. This function is useful for checking the\n Stembridge local axioms for crystal bases.\n\n The `i`-depth of a crystal node `x` is `\\varepsilon_i(x)`.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,1],[2]])\n sage: t.stembridgeDel_depth(1,2)\n 0\n sage: s = T(rows=[[1,3],[3]])\n sage: s.stembridgeDel_depth(1,2)\n -1\n "
if (self.f(i) is None):
return 0
return ((- self.epsilon(j)) + self.f(i).epsilon(j))
def stembridgeDel_rise(self, i, j):
"\n Return the difference in the `j`-rise of ``self`` and `f_i` of\n ``self``, where `i` and `j` are in the index set of the\n underlying crystal. This function is useful for checking the\n Stembridge local axioms for crystal bases.\n\n The `i`-rise of a crystal node `x` is `\\varphi_i(x)`.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,1],[2]])\n sage: t.stembridgeDel_rise(1,2)\n -1\n sage: s = T(rows=[[1,3],[3]])\n sage: s.stembridgeDel_rise(1,2)\n 0\n "
if (self.f(i) is None):
return 0
return (self.phi(j) - self.f(i).phi(j))
def stembridgeTriple(self, i, j):
"\n Let `A` be the Cartan matrix of the crystal, `x` a crystal element,\n and let `i` and `j` be in the index set of the crystal.\n Further, set\n ``b=stembridgeDelta_depth(x,i,j)``, and\n ``c=stembridgeDelta_rise(x,i,j))``.\n If ``x.e(i)`` is non-empty, this function returns the triple\n `( A_{ij}, b, c )`; otherwise it returns ``None``.\n By the Stembridge local characterization of crystal bases,\n one should have `A_{ij}=b+c`.\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,1],[2]])\n sage: t.stembridgeTriple(1,2)\n sage: s = T(rows=[[1,2],[2]])\n sage: s.stembridgeTriple(1,2)\n (-1, 0, -1)\n\n sage: T = crystals.Tableaux(['B',2], shape=[2,1])\n sage: t = T(rows=[[1,2],[2]])\n sage: t.stembridgeTriple(1,2)\n (-2, 0, -2)\n sage: s = T(rows=[[-1,-1],[0]])\n sage: s.stembridgeTriple(1,2)\n (-2, -2, 0)\n sage: u = T(rows=[[0,2],[1]])\n sage: u.stembridgeTriple(1,2)\n (-2, -1, -1)\n "
if (self.e(i) is None):
return None
b = self.stembridgeDelta_depth(i, j)
c = self.stembridgeDelta_rise(i, j)
dd = self.cartan_type().dynkin_diagram()
a = dd[(j, i)]
return (a, b, c)
def _test_stembridge_local_axioms(self, index_set=None, verbose=False, **options):
"\n This implements tests for the Stembridge local characterization\n on the element of a crystal ``self``.\n\n The current implementation only uses the axioms for simply-laced\n types. Crystals of other types should still pass the test, but\n in non-simply-laced types, passing is not a guarantee that the\n crystal arises from a representation.\n\n One can specify an index set smaller than the full index set of\n the crystal, using the option ``index_set``.\n\n Running with ``verbose=True`` will print warnings when a test fails.\n\n REFERENCES:\n\n - [Ste2003]_\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',2], shape=[2,1])\n sage: t = T(rows=[[1,1],[2]])\n sage: t._test_stembridge_local_axioms()\n True\n sage: t._test_stembridge_local_axioms(index_set=[1,3])\n True\n sage: t._test_stembridge_local_axioms(verbose=True)\n True\n "
tester = self._tester(**options)
goodness = True
if (index_set is None):
index_set = self.index_set()
from sage.combinat.subset import Subsets
for (i, j) in Subsets(index_set, 2):
if ((self.e(i) is not None) and (self.e(j) is not None)):
triple = self.stembridgeTriple(i, j)
if ((not (triple[0] == (triple[1] + triple[2]))) or (triple[1] > 0) or (triple[2] > 0)):
if verbose:
print('Warning: Failed axiom P3 or P4 at vector ', self, 'i,j=', i, j, 'Stembridge triple:', self.stembridgeTriple(i, j))
goodness = False
else:
tester.fail()
if (self.stembridgeDelta_depth(i, j) == 0):
if ((self.e(i).e(j) != self.e(j).e(i)) or (self.e(i).e(j).stembridgeDel_rise(j, i) != 0)):
if verbose:
print('Warning: Failed axiom P5 at: vector ', self, 'i,j=', i, j, 'Stembridge triple:', self.stembridgeTriple(i, j))
goodness = False
else:
tester.fail()
if ((self.stembridgeDelta_depth(i, j) == (- 1)) and (self.stembridgeDelta_depth(j, i) == (- 1))):
y1 = self.e(j).e(i).e(i).e(j)
y2 = self.e(j).e(i).e(i).e(j)
a = y1.stembridgeDel_rise(j, i)
b = y2.stembridgeDel_rise(i, j)
if ((y1 != y2) or (a != (- 1)) or (b != (- 1))):
if verbose:
print('Warning: Failed axiom P6 at: vector ', self, 'i,j=', i, j, 'Stembridge triple:', self.stembridgeTriple(i, j))
goodness = False
else:
tester.fail()
tester.assertTrue(goodness)
return goodness
def dual_equivalence_class(self, index_set=None):
"\n Return the dual equivalence class indexed by ``index_set``\n of ``self``.\n\n The dual equivalence class of an element `b \\in B`\n is the set of all elements of `B` reachable from\n `b` via sequences of `i`-elementary dual equivalence\n relations (i.e., `i`-elementary dual equivalence\n transformations and their inverses) for `i` in the index\n set of `B`.\n\n For this to be well-defined, the element `b` has to be\n of weight `0` with respect to `I`; that is, we need to have\n `\\varepsilon_j(b) = \\varphi_j(b)` for all `j \\in I`.\n\n See [As2008]_. See also :meth:`dual_equivalence_graph` for\n a definition of `i`-elementary dual equivalence\n transformations.\n\n INPUT:\n\n - ``index_set`` -- (optional) the index set `I`\n (default: the whole index set of the crystal); this has\n to be a subset of the index set of the crystal (as a list\n or tuple)\n\n OUTPUT:\n\n The dual equivalence class of ``self`` indexed by the\n subset ``index_set``. This class is returned as an\n undirected edge-colored multigraph. The color of an edge\n is the index `i` of the dual equivalence relation it\n encodes.\n\n .. SEEALSO::\n\n - :meth:`~sage.categories.regular_crystals.RegularCrystals.ParentMethods.dual_equivalence_graph`\n - :meth:`sage.combinat.partition.Partition.dual_equivalence_graph`\n\n EXAMPLES::\n\n sage: T = crystals.Tableaux(['A',3], shape=[2,2])\n sage: G = T(2,1,4,3).dual_equivalence_class()\n sage: G.edges(sort=True)\n [([[1, 3], [2, 4]], [[1, 2], [3, 4]], 2),\n ([[1, 3], [2, 4]], [[1, 2], [3, 4]], 3)]\n sage: T = crystals.Tableaux(['A',4], shape=[3,2])\n sage: G = T(2,1,4,3,5).dual_equivalence_class()\n sage: G.edges(sort=True)\n [([[1, 3, 5], [2, 4]], [[1, 3, 4], [2, 5]], 4),\n ([[1, 3, 5], [2, 4]], [[1, 2, 5], [3, 4]], 2),\n ([[1, 3, 5], [2, 4]], [[1, 2, 5], [3, 4]], 3),\n ([[1, 3, 4], [2, 5]], [[1, 2, 4], [3, 5]], 2),\n ([[1, 2, 4], [3, 5]], [[1, 2, 3], [4, 5]], 3),\n ([[1, 2, 4], [3, 5]], [[1, 2, 3], [4, 5]], 4)]\n "
if (index_set is None):
index_set = self.index_set()
for i in index_set:
if (self.epsilon(i) != self.phi(i)):
raise ValueError('the element is not weight 0')
visited = set()
todo = {self}
edges = []
while todo:
x = todo.pop()
visited.add(x)
for (k, i) in enumerate(index_set[1:]):
im = index_set[k]
if ((x.epsilon(i) == 1) and (x.epsilon(im) == 0)):
y = x.e(i).e(im).f(i).f(im)
if ([y, x, i] not in edges):
edges.append([x, y, i])
if (y not in visited):
todo.add(y)
if ((x.epsilon(i) == 0) and (x.epsilon(im) == 1)):
y = x.e(im).e(i).f(im).f(i)
if ([y, x, i] not in edges):
edges.append([x, y, i])
if (y not in visited):
todo.add(y)
from sage.graphs.graph import Graph
G = Graph([visited, edges], format='vertices_and_edges', immutable=True, multiedges=True)
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 TensorProducts(TensorProductsCategory):
'\n The category of regular crystals constructed by tensor\n product of regular crystals.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: RegularCrystals().TensorProducts().extra_super_categories()\n [Category of regular crystals]\n '
return [self.base_category()]
|
class RegularSuperCrystals(Category_singleton):
"\n The category of crystals for super Lie algebras.\n\n EXAMPLES::\n\n sage: from sage.categories.regular_supercrystals import RegularSuperCrystals\n sage: C = RegularSuperCrystals()\n sage: C\n Category of regular super crystals\n sage: C.super_categories()\n [Category of finite super crystals]\n\n Parents in this category should implement the following methods:\n\n - either an attribute ``_cartan_type`` or a method ``cartan_type``\n\n - ``module_generators``: a list (or container) of distinct elements\n that generate the crystal using `f_i` and `e_i`\n\n Furthermore, their elements ``x`` should implement the following\n methods:\n\n - ``x.e(i)`` (returning `e_i(x)`)\n\n - ``x.f(i)`` (returning `f_i(x)`)\n\n - ``x.weight()`` (returning `\\operatorname{wt}(x)`)\n\n EXAMPLES::\n\n sage: from sage.misc.abstract_method import abstract_methods_of_class\n sage: from sage.categories.regular_supercrystals import RegularSuperCrystals\n sage: abstract_methods_of_class(RegularSuperCrystals().element_class)\n {'optional': [], 'required': ['e', 'f', 'weight']}\n\n TESTS::\n\n sage: from sage.categories.regular_supercrystals import RegularSuperCrystals\n sage: C = RegularSuperCrystals()\n sage: TestSuite(C).run()\n sage: B = crystals.Letters(['A',[1,1]]); B\n The crystal of letters for type ['A', [1, 1]]\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 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 super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.regular_supercrystals import RegularSuperCrystals\n sage: C = RegularSuperCrystals()\n sage: C.super_categories()\n [Category of finite super crystals]\n '
return [SuperCrystals().Finite()]
class ElementMethods():
def epsilon(self, i):
"\n Return `\\varepsilon_i` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux(['A',[1,2]], shape=[2,1])\n sage: c = C.an_element(); c\n [[-2, -2], [-1]]\n sage: c.epsilon(2)\n 0\n sage: c.epsilon(0)\n 0\n sage: c.epsilon(-1)\n 0\n "
string_length = 0
x = self
while True:
x = x.e(i)
if (x is None):
return string_length
else:
string_length += 1
def phi(self, i):
"\n Return `\\varphi_i` of ``self``.\n\n EXAMPLES::\n\n sage: C = crystals.Tableaux(['A',[1,2]], shape=[2,1])\n sage: c = C.an_element(); c\n [[-2, -2], [-1]]\n sage: c.phi(1)\n 0\n sage: c.phi(2)\n 0\n sage: c.phi(0)\n 1\n "
string_length = 0
x = self
while True:
x = x.f(i)
if (x is None):
return string_length
else:
string_length += 1
class TensorProducts(TensorProductsCategory):
'\n The category of regular crystals constructed by tensor\n product of regular crystals.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.regular_supercrystals import RegularSuperCrystals\n sage: RegularSuperCrystals().TensorProducts().extra_super_categories()\n [Category of regular super crystals]\n '
return [self.base_category()]
|
class RightModules(Category_over_base_ring):
'\n The category of right modules\n right modules over an rng (ring not necessarily with unit), i.e.\n an abelian group with right multiplication by elements of the rng\n\n EXAMPLES::\n\n sage: RightModules(QQ)\n Category of right modules over Rational Field\n sage: RightModules(QQ).super_categories()\n [Category of commutative additive groups]\n\n TESTS::\n\n sage: TestSuite(RightModules(ZZ)).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: RightModules(QQ).super_categories()\n [Category of commutative additive groups]\n '
return [CommutativeAdditiveGroups()]
class ParentMethods():
pass
class ElementMethods():
pass
|
class RingIdeals(Category_ideal):
'\n The category of two-sided ideals in a fixed ring.\n\n EXAMPLES::\n\n sage: Ideals(Integers(200))\n Category of ring ideals in Ring of integers modulo 200\n sage: C = Ideals(IntegerRing()); C\n Category of ring ideals in Integer Ring\n sage: I = C([8,12,18])\n sage: I\n Principal ideal (2) of Integer Ring\n\n See also: :class:`CommutativeRingIdeals`.\n\n .. TODO::\n\n - If useful, implement ``RingLeftIdeals`` and ``RingRightIdeals``\n of which ``RingIdeals`` would be a subcategory.\n\n - Make ``RingIdeals(R)``, return ``CommutativeRingIdeals(R)``\n when ``R`` is commutative.\n '
def __init__(self, R):
'\n EXAMPLES::\n\n sage: RingIdeals(ZZ)\n Category of ring ideals in Integer Ring\n sage: RingIdeals(3)\n Traceback (most recent call last):\n ...\n TypeError: R (=3) must be a ring\n\n TESTS::\n\n sage: TestSuite(RingIdeals(ZZ)).run()\n '
if (R not in _Rings):
raise TypeError(('R (=%s) must be a ring' % R))
Category_ideal.__init__(self, R)
def super_categories(self):
'\n EXAMPLES::\n\n sage: RingIdeals(ZZ).super_categories()\n [Category of modules over Integer Ring]\n sage: RingIdeals(QQ).super_categories()\n [Category of vector spaces over Rational Field]\n '
R = self.ring()
return [Modules(R)]
|
class Rings(CategoryWithAxiom):
"\n The category of rings\n\n Associative rings with unit, not necessarily commutative\n\n EXAMPLES::\n\n sage: Rings()\n Category of rings\n sage: sorted(Rings().super_categories(), key=str)\n [Category of rngs, Category of semirings]\n\n sage: sorted(Rings().axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Associative', 'Distributive', 'Unital']\n\n sage: Rings() is (CommutativeAdditiveGroups() & Monoids()).Distributive()\n True\n sage: Rings() is Rngs().Unital()\n True\n sage: Rings() is Semirings().AdditiveInverse()\n True\n\n TESTS::\n\n sage: TestSuite(Rings()).run()\n\n .. TODO::\n\n (see :trac:`sage_trac/wiki/CategoriesRoadMap`)\n\n - Make Rings() into a subcategory or alias of Algebras(ZZ);\n\n - A parent P in the category ``Rings()`` should automatically be\n in the category ``Algebras(P)``.\n "
_base_category_class_and_axiom = (Rngs, 'Unital')
class MorphismMethods():
@cached_method
def is_injective(self) -> bool:
'\n Return whether or not this morphism is injective.\n\n EXAMPLES::\n\n sage: # needs sage.libs.singular\n sage: R.<x,y> = QQ[]\n sage: R.hom([x, y^2], R).is_injective()\n True\n sage: R.hom([x, x^2], R).is_injective()\n False\n sage: S.<u,v> = R.quotient(x^3*y)\n sage: R.hom([v, u], S).is_injective()\n False\n sage: S.hom([-u, v], S).is_injective()\n True\n sage: S.cover().is_injective()\n False\n\n If the domain is a field, the homomorphism is injective::\n\n sage: K.<x> = FunctionField(QQ)\n sage: L.<y> = FunctionField(QQ)\n sage: f = K.hom([y]); f\n Function Field morphism:\n From: Rational function field in x over Rational Field\n To: Rational function field in y over Rational Field\n Defn: x |--> y\n sage: f.is_injective()\n True\n\n Unless the codomain is the zero ring::\n\n sage: codomain = Integers(1)\n sage: f = QQ.hom([Zmod(1)(0)], check=False)\n sage: f.is_injective()\n False\n\n Homomorphism from rings of characteristic zero to rings of positive\n characteristic can not be injective::\n\n sage: R.<x> = ZZ[]\n sage: f = R.hom([GF(3)(1)]); f\n Ring morphism:\n From: Univariate Polynomial Ring in x over Integer Ring\n To: Finite Field of size 3\n Defn: x |--> 1\n sage: f.is_injective()\n False\n\n A morphism whose domain is an order in a number field is injective if\n the codomain has characteristic zero::\n\n sage: K.<x> = FunctionField(QQ)\n sage: f = ZZ.hom(K); f\n Composite map:\n From: Integer Ring\n To: Rational function field in x over Rational Field\n Defn: Conversion via FractionFieldElement_1poly_field map:\n From: Integer Ring\n To: Fraction Field of Univariate Polynomial Ring in x\n over Rational Field\n then\n Isomorphism:\n From: Fraction Field of Univariate Polynomial Ring in x\n over Rational Field\n To: Rational function field in x over Rational Field\n sage: f.is_injective()\n True\n\n A coercion to the fraction field is injective::\n\n sage: R = ZpFM(3) # needs sage.rings.padics\n sage: R.fraction_field().coerce_map_from(R).is_injective()\n True\n\n '
if self.domain().is_zero():
return True
if self.codomain().is_zero():
return False
from sage.categories.fields import Fields
if (self.domain() in Fields()):
return True
try:
ker = self.kernel()
except (NotImplementedError, AttributeError):
pass
else:
return ker.is_zero()
if (self.domain().characteristic() == 0):
if (self.codomain().characteristic() != 0):
return False
else:
from sage.categories.integral_domains import IntegralDomains
if (self.domain() in IntegralDomains()):
from sage.categories.number_fields import NumberFields
if (self.domain().fraction_field() in NumberFields()):
return True
if self._is_coercion:
try:
K = self.domain().fraction_field()
except (TypeError, AttributeError, ValueError):
pass
else:
if (K is self.codomain()):
return True
try:
if (self.domain().cardinality() > self.codomain().cardinality()):
return False
except AttributeError:
pass
raise NotImplementedError
def _is_nonzero(self) -> bool:
'\n Return whether this is not the zero morphism.\n\n .. NOTE::\n\n We can not override ``is_zero()`` from the category framework\n and we can not implement ``__bool__`` because it is a\n special method. That this is why this has a cumbersome name.\n\n EXAMPLES::\n\n sage: ZZ.hom(ZZ)._is_nonzero()\n True\n sage: ZZ.hom(Zmod(1))._is_nonzero()\n False\n '
return bool(self.codomain().one())
def extend_to_fraction_field(self):
'\n Return the extension of this morphism to fraction fields of\n the domain and the codomain.\n\n EXAMPLES::\n\n sage: S.<x> = QQ[]\n sage: f = S.hom([x + 1]); f\n Ring endomorphism of Univariate Polynomial Ring in x over Rational Field\n Defn: x |--> x + 1\n\n sage: g = f.extend_to_fraction_field(); g # needs sage.libs.singular\n Ring endomorphism of Fraction Field of Univariate Polynomial Ring in x\n over Rational Field\n Defn: x |--> x + 1\n sage: g(x) # needs sage.libs.singular\n x + 1\n sage: g(1/x) # needs sage.libs.singular\n 1/(x + 1)\n\n If this morphism is not injective, it does not extend to the fraction\n field and an error is raised::\n\n sage: f = GF(5).coerce_map_from(ZZ)\n sage: f.extend_to_fraction_field()\n Traceback (most recent call last):\n ...\n ValueError: the morphism is not injective\n\n TESTS::\n\n sage: A.<x> = RR[]\n sage: phi = A.hom([x + 1])\n sage: phi.extend_to_fraction_field() # needs sage.libs.singular\n Ring endomorphism of Fraction Field of\n Univariate Polynomial Ring in x over Real Field with 53 bits of precision\n Defn: x |--> x + 1.00000000000000\n '
from sage.rings.morphism import RingHomomorphism_from_fraction_field
if (self.domain().is_field() and self.codomain().is_field()):
return self
try:
if (not self.is_injective()):
raise ValueError('the morphism is not injective')
except (NotImplementedError, TypeError):
pass
domain = self.domain().fraction_field()
codomain = self.codomain().fraction_field()
parent = domain.Hom(codomain)
return RingHomomorphism_from_fraction_field(parent, self)
class SubcategoryMethods():
def NoZeroDivisors(self):
"\n Return the full subcategory of the objects of ``self`` having\n no nonzero zero divisors.\n\n A *zero divisor* in a ring `R` is an element `x \\in R` such\n that there exists a nonzero element `y \\in R` such that\n `x \\cdot y = 0` or `y \\cdot x = 0`\n (see :wikipedia:`Zero_divisor`).\n\n EXAMPLES::\n\n sage: Rings().NoZeroDivisors()\n Category of domains\n\n TESTS::\n\n sage: TestSuite(Rings().NoZeroDivisors()).run()\n sage: Algebras(QQ).NoZeroDivisors.__module__\n 'sage.categories.rings'\n "
return self._with_axiom('NoZeroDivisors')
def Division(self):
"\n Return the full subcategory of the division objects of ``self``.\n\n A ring satisfies the *division axiom* if all non-zero\n elements have multiplicative inverses.\n\n EXAMPLES::\n\n sage: Rings().Division()\n Category of division rings\n sage: Rings().Commutative().Division()\n Category of fields\n\n TESTS::\n\n sage: TestSuite(Rings().Division()).run()\n sage: Algebras(QQ).Division.__module__\n 'sage.categories.rings'\n "
return self._with_axiom('Division')
NoZeroDivisors = LazyImport('sage.categories.domains', 'Domains', at_startup=True)
Division = LazyImport('sage.categories.division_rings', 'DivisionRings', at_startup=True)
Commutative = LazyImport('sage.categories.commutative_rings', 'CommutativeRings', at_startup=True)
class ParentMethods():
def is_ring(self) -> bool:
'\n Return ``True``, since this in an object of the category of rings.\n\n EXAMPLES::\n\n sage: Parent(QQ,category=Rings()).is_ring()\n True\n '
return True
def is_zero(self) -> bool:
'\n Return ``True`` if this is the zero ring.\n\n EXAMPLES::\n\n sage: Integers(1).is_zero()\n True\n sage: Integers(2).is_zero()\n False\n sage: QQ.is_zero()\n False\n sage: R.<x> = ZZ[]\n sage: R.quo(1).is_zero()\n True\n sage: R.<x> = GF(101)[]\n sage: R.quo(77).is_zero()\n True\n sage: R.quo(x^2 + 1).is_zero() # needs sage.libs.pari\n False\n '
return (self.one() == self.zero())
def bracket(self, x, y):
"\n Return the Lie bracket `[x, y] = x y - y x` of `x` and `y`.\n\n INPUT:\n\n - ``x``, ``y`` -- elements of ``self``\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: F = AlgebrasWithBasis(QQ).example()\n sage: F\n An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field\n sage: a, b, c = F.algebra_generators()\n sage: F.bracket(a, b)\n B[word: ab] - B[word: ba]\n\n This measures the default of commutation between `x` and `y`.\n `F` endowed with the bracket operation is a Lie algebra;\n in particular, it satisfies Jacobi's identity::\n\n sage: (F.bracket(F.bracket(a,b), c) + F.bracket(F.bracket(b,c), a) # needs sage.combinat sage.modules\n ....: + F.bracket(F.bracket(c,a), b))\n 0\n "
return ((x * y) - (y * x))
def _Hom_(self, Y, category):
"\n Return the homset from ``self`` to ``Y`` in the category ``category``.\n\n INPUT:\n\n - ``Y`` -- a ring\n - ``category`` -- a subcategory of :class:`Rings()\n <Rings>` or ``None``\n\n The sole purpose of this method is to construct the homset\n as a :class:`~sage.rings.homset.RingHomset`. If\n ``category`` is specified and is not a subcategory of\n :class:`Rings() <Rings>`, 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: H = QQ._Hom_(QQ, category=Rings()); H\n Set of Homomorphisms from Rational Field to Rational Field\n sage: H.__class__\n <class 'sage.rings.homset.RingHomset_generic_with_category'>\n\n TESTS::\n\n sage: Hom(QQ, QQ, category=Rings()).__class__\n <class 'sage.rings.homset.RingHomset_generic_with_category'>\n\n sage: Hom(CyclotomicField(3), QQ, category=Rings()).__class__ # needs sage.rings.number_field\n <class 'sage.rings.number_field.homset.CyclotomicFieldHomset_with_category'>\n\n sage: TestSuite(Hom(QQ, QQ, category=Rings())).run() # indirect doctest\n "
if ((category is not None) and (not category.is_subcategory(Rings()))):
raise TypeError(f'{category} is not a subcategory of Rings()')
if (Y not in Rings()):
raise TypeError(f'{Y} is not a ring')
from sage.rings.homset import RingHomset
return RingHomset(self, Y, category=category)
def _mul_(self, x, switch_sides=False):
'\n Multiplication of rings with, e.g., lists.\n\n .. NOTE::\n\n This method is used to create ideals. It is the same\n as the multiplication method for\n :class:`~sage.rings.ring.Ring`. However, not all\n parents that belong to the category of rings also\n inherits from the base class of rings. Therefore, we\n implemented a ``__mul__`` method for parents, that\n calls a ``_mul_`` method implemented here. See :trac:`7797`.\n\n INPUT:\n\n - `x`, an object to multiply with.\n - `switch_sides` (optional bool): If ``False``,\n the product is ``self*x``; if ``True``, the\n product is ``x*self``.\n\n EXAMPLES:\n\n As we mentioned above, this method is called\n when a ring is involved that does not inherit\n from the base class of rings. This is the case,\n e.g., for matrix algebras::\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(QQ, 2, 2)\n sage: isinstance(MS, Ring)\n False\n sage: MS in Rings()\n True\n sage: MS * 2 # indirect doctest\n Left Ideal\n (\n [2 0]\n [0 2]\n )\n of Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n\n In the next example, the ring and the other factor switch sides\n in the product::\n\n sage: [MS.2] * MS # needs sage.modules\n Right Ideal\n (\n [0 0]\n [1 0]\n )\n of Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n\n AUTHOR:\n\n - Simon King (2011-03-22)\n '
try:
if self.is_commutative():
return self.ideal(x)
except (AttributeError, NotImplementedError):
pass
try:
side = x.side()
except AttributeError:
return self.ideal(x, side=('right' if switch_sides else 'left'))
try:
x = x.gens()
except (AttributeError, NotImplementedError):
pass
if switch_sides:
if (side in ['right', 'twosided']):
return self.ideal(x, side=side)
elif (side == 'left'):
return self.ideal(x, side='twosided')
elif (side in ['left', 'twosided']):
return self.ideal(x, side=side)
elif (side == 'right'):
return self.ideal(x, side='twosided')
raise TypeError(('do not know how to transform %s into an ideal of %s' % (x, self)))
def __pow__(self, n):
'\n Return the free module of rank `n` over this ring. If n is a tuple of\n two elements, creates a matrix space.\n\n EXAMPLES::\n\n sage: QQ^5 # needs sage.modules\n Vector space of dimension 5 over Rational Field\n sage: Integers(20)^1000 # needs sage.modules\n Ambient free module of rank 1000 over Ring of integers modulo 20\n\n sage: QQ^(2, 3) # needs sage.modules\n Full MatrixSpace of 2 by 3 dense matrices over Rational Field\n '
if isinstance(n, tuple):
(m, n) = n
from sage.matrix.matrix_space import MatrixSpace
return MatrixSpace(self, m, n)
else:
from sage.modules.free_module import FreeModule
return FreeModule(self, n)
@cached_method
def ideal_monoid(self):
'\n The monoid of the ideals of this ring.\n\n .. NOTE::\n\n The code is copied from the base class of rings.\n This is since there are rings that do not inherit\n from that class, such as matrix algebras. See\n :trac:`7797`.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(QQ, 2, 2)\n sage: isinstance(MS, Ring)\n False\n sage: MS in Rings()\n True\n sage: MS.ideal_monoid()\n Monoid of ideals of Full MatrixSpace of 2 by 2 dense matrices\n over Rational Field\n\n Note that the monoid is cached::\n\n sage: MS.ideal_monoid() is MS.ideal_monoid() # needs sage.modules\n True\n '
try:
from sage.rings.ideal_monoid import IdealMonoid
return IdealMonoid(self)
except TypeError:
from sage.rings.noncommutative_ideals import IdealMonoid_nc
return IdealMonoid_nc(self)
def characteristic(self):
'\n Return the characteristic of this ring.\n\n EXAMPLES::\n\n sage: QQ.characteristic()\n 0\n sage: GF(19).characteristic()\n 19\n sage: Integers(8).characteristic()\n 8\n sage: Zp(5).characteristic() # needs sage.rings.padics\n 0\n '
from sage.rings.infinity import infinity
from sage.rings.integer_ring import ZZ
order_1 = self.one().additive_order()
return (ZZ.zero() if (order_1 is infinity) else order_1)
def _test_characteristic(self, **options):
'\n Run generic tests on the method :meth:`characteristic`.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: ZZ._test_characteristic()\n '
tester = self._tester(**options)
try:
characteristic = self.characteristic()
except AttributeError:
return
except NotImplementedError:
return
from sage.rings.integer import Integer
tester.assertIsInstance(characteristic, Integer)
def ideal(self, *args, **kwds):
'\n Create an ideal of this ring.\n\n .. NOTE::\n\n The code is copied from the base class\n :class:`~sage.rings.ring.Ring`. This is\n because there are rings that do not inherit\n from that class, such as matrix algebras.\n See :trac:`7797`.\n\n INPUT:\n\n - An element or a list/tuple/sequence of elements.\n - ``coerce`` (optional bool, default ``True``):\n First coerce the elements into this ring.\n - ``side``, optional string, one of ``"twosided"``\n (default), ``"left"``, ``"right"``: determines\n whether the resulting ideal is twosided, a left\n ideal or a right ideal.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(QQ, 2, 2)\n sage: isinstance(MS, Ring)\n False\n sage: MS in Rings()\n True\n sage: MS.ideal(2)\n Twosided Ideal\n (\n [2 0]\n [0 2]\n )\n of Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n sage: MS.ideal([MS.0, MS.1], side=\'right\')\n Right Ideal\n (\n [1 0]\n [0 0],\n <BLANKLINE>\n [0 1]\n [0 0]\n )\n of Full MatrixSpace of 2 by 2 dense matrices over Rational Field\n '
if ('coerce' in kwds):
coerce = kwds['coerce']
del kwds['coerce']
else:
coerce = True
from sage.rings.ideal import Ideal_generic
from types import GeneratorType
if (len(args) == 0):
gens = [self(0)]
else:
gens = args
while (isinstance(gens, (list, tuple, GeneratorType)) and (len(gens) == 1)):
first = gens[0]
if isinstance(first, Ideal_generic):
R = first.ring()
m = self.convert_map_from(R)
if (m is not None):
gens = [m(g) for g in first.gens()]
coerce = False
else:
m = R.convert_map_from(self)
if (m is not None):
raise NotImplementedError
else:
raise TypeError
break
elif isinstance(first, (list, tuple, GeneratorType)):
gens = first
else:
try:
if self.has_coerce_map_from(first):
gens = first.gens()
elif isinstance(first, Element):
gens = [first]
else:
raise ArithmeticError(('there is no coercion from %s to %s' % (first, self)))
except TypeError:
pass
break
if coerce:
gens = [self(g) for g in gens]
from sage.categories.principal_ideal_domains import PrincipalIdealDomains
if (self in PrincipalIdealDomains()):
g = gens[0]
if (len(gens) == 1):
try:
g = g.gcd(g)
except (AttributeError, NotImplementedError):
pass
else:
for h in gens[1:]:
g = g.gcd(h)
gens = [g]
if ('ideal_class' in kwds):
C = kwds['ideal_class']
del kwds['ideal_class']
else:
C = self._ideal_class_(len(gens))
if ((len(gens) == 1) and isinstance(gens[0], (list, tuple))):
gens = gens[0]
return C(self, gens, **kwds)
def _ideal_class_(self, n=0):
"\n Return the class that is used to implement ideals of this ring.\n\n .. NOTE::\n\n We copy the code from :class:`~sage.rings.ring.Ring`. This is\n necessary because not all rings inherit from that class, such\n as matrix algebras.\n\n INPUT:\n\n - ``n`` (optional integer, default 0): The number of generators\n of the ideal to be created.\n\n OUTPUT:\n\n The class that is used to implement ideals of this ring with\n ``n`` generators.\n\n .. NOTE::\n\n Often principal ideals (``n==1``) are implemented via\n a different class.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(QQ, 2, 2) # needs sage.modules\n sage: MS._ideal_class_() # needs sage.modules\n <class 'sage.rings.noncommutative_ideals.Ideal_nc'>\n\n We do not know of a commutative ring in Sage that does not inherit\n from the base class of rings. So, we need to cheat in the next\n example::\n\n sage: super(Ring,QQ)._ideal_class_.__module__\n 'sage.categories.rings'\n sage: super(Ring,QQ)._ideal_class_()\n <class 'sage.rings.ideal.Ideal_generic'>\n sage: super(Ring,QQ)._ideal_class_(1)\n <class 'sage.rings.ideal.Ideal_principal'>\n sage: super(Ring,QQ)._ideal_class_(2)\n <class 'sage.rings.ideal.Ideal_generic'>\n "
from sage.rings.noncommutative_ideals import Ideal_nc
try:
if (not self.is_commutative()):
return Ideal_nc
except (NotImplementedError, AttributeError):
return Ideal_nc
from sage.rings.ideal import Ideal_generic, Ideal_principal
if (n == 1):
return Ideal_principal
return Ideal_generic
def quotient(self, I, names=None, **kwds):
"\n Quotient of a ring by a two-sided ideal.\n\n INPUT:\n\n - ``I`` -- A twosided ideal of this ring.\n - ``names`` -- (optional) names of the generators of the quotient (if\n there are multiple generators, you can specify a single character\n string and the generators are named in sequence starting with 0).\n - further named arguments that may be passed to the\n quotient ring constructor.\n\n EXAMPLES:\n\n Usually, a ring inherits a method :meth:`sage.rings.ring.Ring.quotient`.\n So, we need a bit of effort to make the following example work with the\n category framework::\n\n sage: # needs sage.combinat sage.modules\n sage: F.<x,y,z> = FreeAlgebra(QQ)\n sage: from sage.rings.noncommutative_ideals import Ideal_nc\n sage: from itertools import product\n sage: class PowerIdeal(Ideal_nc):\n ....: def __init__(self, R, n):\n ....: self._power = n\n ....: Ideal_nc.__init__(self, R, [R.prod(m)\n ....: for m in product(R.gens(), repeat=n)])\n ....: def reduce(self, x):\n ....: R = self.ring()\n ....: return add([c*R(m) for m, c in x\n ....: if len(m) < self._power], R(0))\n sage: I = PowerIdeal(F, 3)\n sage: Q = Rings().parent_class.quotient(F, I); Q\n Quotient of Free Algebra on 3 generators (x, y, z) over Rational Field\n by the ideal (x^3, x^2*y, x^2*z, x*y*x, x*y^2, x*y*z, x*z*x,\n x*z*y, x*z^2, y*x^2, y*x*y, y*x*z, y^2*x, y^3,\n y^2*z, y*z*x, y*z*y, y*z^2, z*x^2, z*x*y, z*x*z,\n z*y*x, z*y^2, z*y*z, z^2*x, z^2*y, z^3)\n sage: Q.0\n xbar\n sage: Q.1\n ybar\n sage: Q.2\n zbar\n sage: Q.0*Q.1\n xbar*ybar\n sage: Q.0*Q.1*Q.0\n 0\n\n An example with polynomial rings::\n\n sage: R.<x> = PolynomialRing(ZZ)\n sage: I = R.ideal([4 + 3*x + x^2, 1 + x^2])\n sage: S = R.quotient(I, 'a')\n sage: S.gens()\n (a,)\n\n sage: # needs sage.libs.singular\n sage: R.<x,y> = PolynomialRing(QQ, 2)\n sage: S.<a,b> = R.quotient((x^2, y))\n sage: S\n Quotient of Multivariate Polynomial Ring in x, y over Rational Field\n by the ideal (x^2, y)\n sage: S.gens()\n (a, 0)\n sage: a == b\n False\n "
from sage.rings.quotient_ring import QuotientRing
return QuotientRing(self, I, names=names, **kwds)
def quo(self, I, names=None, **kwds):
"\n Quotient of a ring by a two-sided ideal.\n\n .. NOTE::\n\n This is a synonym for :meth:`quotient`.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(QQ, 2) # needs sage.modules\n sage: I = MS * MS.gens() * MS # needs sage.modules\n\n ``MS`` is not an instance of :class:`~sage.rings.ring.Ring`.\n\n However it is an instance of the parent class of the\n category of rings. The quotient method is inherited from\n there::\n\n sage: isinstance(MS, sage.rings.ring.Ring) # needs sage.modules\n False\n sage: isinstance(MS, Rings().parent_class) # needs sage.modules\n True\n sage: MS.quo(I, names=['a','b','c','d']) # needs sage.modules\n Quotient of Full MatrixSpace of 2 by 2 dense matrices\n over Rational Field by the ideal\n (\n [1 0]\n [0 0],\n <BLANKLINE>\n [0 1]\n [0 0],\n <BLANKLINE>\n [0 0]\n [1 0],\n <BLANKLINE>\n [0 0]\n [0 1]\n )\n\n A test with a subclass of :class:`~sage.rings.ring.Ring`::\n\n sage: # needs sage.libs.singular\n sage: R.<x,y> = PolynomialRing(QQ, 2)\n sage: S.<a,b> = R.quo((x^2, y))\n sage: S\n Quotient of Multivariate Polynomial Ring in x, y over Rational Field\n by the ideal (x^2, y)\n sage: S.gens()\n (a, 0)\n sage: a == b\n False\n "
return self.quotient(I, names=names, **kwds)
def quotient_ring(self, I, names=None, **kwds):
"\n Quotient of a ring by a two-sided ideal.\n\n .. NOTE::\n\n This is a synonym for :meth:`quotient`.\n\n INPUT:\n\n - ``I`` -- an ideal of `R`\n\n - ``names`` -- (optional) names of the generators of the quotient. (If\n there are multiple generators, you can specify a single character\n string and the generators are named in sequence starting with 0.)\n\n - further named arguments that may be passed to the quotient ring\n constructor.\n\n OUTPUT:\n\n - ``R/I`` -- the quotient ring of `R` by the ideal `I`\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(QQ, 2) # needs sage.modules\n sage: I = MS * MS.gens() * MS # needs sage.modules\n\n ``MS`` is not an instance of :class:`~sage.rings.ring.Ring`,\n but it is an instance of the parent class of the category of\n rings. The quotient method is inherited from there::\n\n sage: isinstance(MS, sage.rings.ring.Ring) # needs sage.modules\n False\n sage: isinstance(MS, Rings().parent_class) # needs sage.modules\n True\n sage: MS.quotient_ring(I, names=['a','b','c','d']) # needs sage.modules\n Quotient of Full MatrixSpace of 2 by 2 dense matrices\n over Rational Field by the ideal\n (\n [1 0]\n [0 0],\n <BLANKLINE>\n [0 1]\n [0 0],\n <BLANKLINE>\n [0 0]\n [1 0],\n <BLANKLINE>\n [0 0]\n [0 1]\n )\n\n A test with a subclass of :class:`~sage.rings.ring.Ring`::\n\n sage: R.<x> = PolynomialRing(ZZ)\n sage: I = R.ideal([4 + 3*x + x^2, 1 + x^2])\n sage: S = R.quotient_ring(I, 'a')\n sage: S.gens()\n (a,)\n\n sage: # needs sage.libs.singular\n sage: R.<x,y> = PolynomialRing(QQ,2)\n sage: S.<a,b> = R.quotient_ring((x^2, y))\n sage: S\n Quotient of Multivariate Polynomial Ring in x, y over Rational Field\n by the ideal (x^2, y)\n sage: S.gens()\n (a, 0)\n sage: a == b\n False\n "
return self.quotient(I, names=names, **kwds)
def __truediv__(self, I):
"\n Since assigning generator names would not work properly,\n the construction of a quotient ring using division syntax\n is not supported.\n\n EXAMPLES::\n\n sage: MS = MatrixSpace(QQ, 2) # needs sage.modules\n sage: I = MS * MS.gens() * MS # needs sage.modules\n sage: MS/I # needs sage.modules\n Traceback (most recent call last):\n ...\n TypeError: use self.quotient(I) to construct the quotient ring\n\n sage: QQ['x'] / ZZ\n Traceback (most recent call last):\n ...\n TypeError: use self.quotient(I) to construct the quotient ring\n "
raise TypeError('use self.quotient(I) to construct the quotient ring')
def __getitem__(self, arg):
"\n Extend this ring by one or several elements to create a polynomial\n ring, a power series ring, or an algebraic extension.\n\n This is a convenience method intended primarily for interactive\n use.\n\n .. SEEALSO::\n\n :func:`~sage.rings.polynomial.polynomial_ring_constructor.PolynomialRing`,\n :func:`~sage.rings.power_series_ring.PowerSeriesRing`,\n :meth:`~sage.rings.ring.Ring.extension`,\n :meth:`sage.rings.integer_ring.IntegerRing_class.__getitem__`,\n :meth:`sage.rings.matrix_space.MatrixSpace.__getitem__`,\n :meth:`sage.structure.parent.Parent.__getitem__`\n\n EXAMPLES:\n\n We create several polynomial rings::\n\n sage: ZZ['x']\n Univariate Polynomial Ring in x over Integer Ring\n sage: QQ['x']\n Univariate Polynomial Ring in x over Rational Field\n sage: GF(17)['abc']\n Univariate Polynomial Ring in abc over Finite Field of size 17\n sage: GF(17)['a,b,c']\n Multivariate Polynomial Ring in a, b, c over Finite Field of size 17\n sage: GF(17)['a']['b']\n Univariate Polynomial Ring in b over\n Univariate Polynomial Ring in a over Finite Field of size 17\n\n We can create Ore polynomial rings::\n\n sage: k.<t> = GF(5^3) # needs sage.rings.finite_rings\n sage: Frob = k.frobenius_endomorphism() # needs sage.rings.finite_rings\n sage: k['x', Frob] # needs sage.rings.finite_rings\n Ore Polynomial Ring in x over Finite Field in t of size 5^3\n twisted by t |--> t^5\n\n sage: R.<t> = QQ[]\n sage: der = R.derivation() # needs sage.modules\n sage: R['d', der] # needs sage.modules\n Ore Polynomial Ring in d\n over Univariate Polynomial Ring in t over Rational Field\n twisted by d/dt\n\n We can also create power series rings by using double brackets::\n\n sage: QQ[['t']]\n Power Series Ring in t over Rational Field\n sage: ZZ[['W']]\n Power Series Ring in W over Integer Ring\n\n sage: ZZ[['x,y,z']]\n Multivariate Power Series Ring in x, y, z over Integer Ring\n sage: ZZ[['x','T']]\n Multivariate Power Series Ring in x, T over Integer Ring\n\n Use :func:`~sage.rings.fraction_field.Frac` or\n :meth:`~sage.rings.ring.CommutativeRing.fraction_field` to obtain\n the fields of rational functions and Laurent series::\n\n sage: Frac(QQ['t'])\n Fraction Field of Univariate Polynomial Ring in t over Rational Field\n sage: Frac(QQ[['t']])\n Laurent Series Ring in t over Rational Field\n sage: QQ[['t']].fraction_field()\n Laurent Series Ring in t over Rational Field\n\n Note that the same syntax can be used to create number fields::\n\n sage: QQ[I] # needs sage.rings.number_field sage.symbolic\n Number Field in I with defining polynomial x^2 + 1 with I = 1*I\n sage: QQ[I].coerce_embedding() # needs sage.rings.number_field sage.symbolic\n Generic morphism:\n From: Number Field in I with defining polynomial x^2 + 1 with I = 1*I\n To: Complex Lazy Field\n Defn: I -> 1*I\n\n ::\n\n sage: QQ[sqrt(2)] # needs sage.rings.number_field sage.symbolic\n Number Field in sqrt2 with defining polynomial x^2 - 2\n with sqrt2 = 1.414213562373095?\n sage: QQ[sqrt(2)].coerce_embedding() # needs sage.rings.number_field sage.symbolic\n Generic morphism:\n From: Number Field in sqrt2 with defining polynomial x^2 - 2\n with sqrt2 = 1.414213562373095?\n To: Real Lazy Field\n Defn: sqrt2 -> 1.414213562373095?\n\n ::\n\n sage: QQ[sqrt(2), sqrt(3)] # needs sage.rings.number_field sage.symbolic\n Number Field in sqrt2\n with defining polynomial x^2 - 2 over its base field\n\n and orders in number fields::\n\n sage: ZZ[I] # needs sage.rings.number_field sage.symbolic\n Order in Number Field in I0\n with defining polynomial x^2 + 1 with I0 = 1*I\n sage: ZZ[sqrt(5)] # needs sage.rings.number_field sage.symbolic\n Order in Number Field in sqrt5\n with defining polynomial x^2 - 5 with sqrt5 = 2.236067977499790?\n sage: ZZ[sqrt(2) + sqrt(3)] # needs sage.rings.number_field sage.symbolic\n Order in Number Field in a\n with defining polynomial x^4 - 10*x^2 + 1 with a = 3.146264369941973?\n\n Embeddings are found for simple extensions (when that makes sense)::\n\n sage: QQi.<i> = QuadraticField(-1, 'i') # needs sage.rings.number_field sage.symbolic\n sage: QQ[i].coerce_embedding() # needs sage.rings.number_field sage.symbolic\n Generic morphism:\n From: Number Field in i with defining polynomial x^2 + 1 with i = 1*I\n To: Complex Lazy Field\n Defn: i -> 1*I\n\n TESTS:\n\n A few corner cases::\n\n sage: QQ[()]\n Multivariate Polynomial Ring in no variables over Rational Field\n\n sage: QQ[[]]\n Traceback (most recent call last):\n ...\n TypeError: power series rings must have at least one variable\n\n These kind of expressions do not work::\n\n sage: QQ['a,b','c']\n Traceback (most recent call last):\n ...\n ValueError: variable name 'a,b' is not alphanumeric\n sage: QQ[['a,b','c']]\n Traceback (most recent call last):\n ...\n ValueError: variable name 'a,b' is not alphanumeric\n\n sage: QQ[[['x']]]\n Traceback (most recent call last):\n ...\n TypeError: expected R[...] or R[[...]], not R[[[...]]]\n\n Extension towers are built as follows and use distinct generator names::\n\n sage: # needs sage.rings.number_field sage.symbolic\n sage: K = QQ[2^(1/3), 2^(1/2), 3^(1/3)]\n sage: K\n Number Field in a with defining polynomial x^3 - 2\n over its base field\n sage: K.base_field()\n Number Field in sqrt2 with defining polynomial x^2 - 2\n over its base field\n sage: K.base_field().base_field()\n Number Field in b with defining polynomial x^3 - 3\n\n Embeddings::\n\n sage: # needs sage.rings.number_field sage.symbolic\n sage: a = 10^100; expr = (2*a + sqrt(2))/(2*a^2-1)\n sage: QQ[expr].coerce_embedding() is None\n False\n sage: QQ[sqrt(5)].gen() > 0\n True\n sage: expr = sqrt(2) + I*(cos(pi/4, hold=True) - sqrt(2)/2)\n sage: QQ[expr].coerce_embedding()\n Generic morphism:\n From: Number Field in a with defining polynomial x^2 - 2\n with a = 1.414213562373095?\n To: Real Lazy Field\n Defn: a -> 1.414213562373095?\n "
def normalize_arg(arg):
if isinstance(arg, (tuple, list)):
return tuple(arg)
if isinstance(arg, str):
return tuple(arg.split(','))
return (arg,)
if isinstance(arg, list):
if (not arg):
raise TypeError('power series rings must have at least one variable')
elif (len(arg) == 1):
if isinstance(arg[0], list):
raise TypeError('expected R[...] or R[[...]], not R[[[...]]]')
elts = normalize_arg(arg[0])
else:
elts = normalize_arg(arg)
from sage.rings.power_series_ring import PowerSeriesRing
return PowerSeriesRing(self, elts)
if isinstance(arg, tuple):
from sage.categories.morphism import Morphism
try:
from sage.rings.derivation import RingDerivation
except ImportError:
RingDerivation = ()
if ((len(arg) == 2) and isinstance(arg[1], (Morphism, RingDerivation))):
from sage.rings.polynomial.ore_polynomial_ring import OrePolynomialRing
return OrePolynomialRing(self, arg[1], names=arg[0])
elts = normalize_arg(arg)
try:
minpolys = [a.minpoly() for a in elts]
except (AttributeError, NotImplementedError, ValueError, TypeError):
minpolys = None
if minpolys:
names = tuple(_gen_names(elts))
if (len(elts) == 1):
from sage.rings.cif import CIF
elt = elts[0]
try:
iv = CIF(elt)
except (TypeError, ValueError):
emb = None
else:
from sage.rings.qqbar import AlgebraicNumber, ANRoot
try:
elt = AlgebraicNumber(ANRoot(minpolys[0], iv))
except ValueError:
pass
from sage.rings.real_lazy import CLF, RLF
if (iv.imag().is_zero() or (iv.imag().contains_zero() and elt.imag().is_zero())):
emb = RLF(elt)
else:
emb = CLF(elt)
return self.extension(minpolys[0], names[0], embedding=emb)
try:
return self.extension(minpolys, names)
except (TypeError, ValueError):
return reduce((lambda R, ext: R.extension(*ext)), zip(minpolys, names), self)
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
return PolynomialRing(self, elts)
def free_module(self, base=None, basis=None, map=True):
'\n Return a free module `V` over the specified subring together with maps to and from `V`.\n\n The default implementation only supports the case that the base ring is the ring itself.\n\n INPUT:\n\n - ``base`` -- a subring `R` so that this ring is isomorphic\n to a finite-rank free `R`-module `V`\n\n - ``basis`` -- (optional) a basis for this ring over the base\n\n - ``map`` -- boolean (default ``True``), whether to return\n `R`-linear maps to and from `V`\n\n OUTPUT:\n\n - A finite-rank free `R`-module `V`\n\n - An `R`-module isomorphism from `V` to this ring\n (only included if ``map`` is ``True``)\n\n - An `R`-module isomorphism from this ring to `V`\n (only included if ``map`` is ``True``)\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: R.<x> = QQ[[]]\n sage: V, from_V, to_V = R.free_module(R)\n sage: v = to_V(1 + x); v\n (1 + x)\n sage: from_V(v)\n 1 + x\n sage: W, from_W, to_W = R.free_module(R, basis=(1 - x))\n sage: W is V\n True\n sage: w = to_W(1 + x); w\n (1 - x^2)\n sage: from_W(w)\n 1 + x + O(x^20)\n '
if (base is None):
base = self.base_ring()
if (base is self):
V = (self ** 1)
if (not map):
return V
if (basis is not None):
if isinstance(basis, (list, tuple)):
if (len(basis) != 1):
raise ValueError('basis must have length 1')
basis = basis[0]
basis = self(basis)
if (not basis.is_unit()):
raise ValueError('basis element must be a unit')
from sage.modules.free_module_morphism import BaseIsomorphism1D_from_FM, BaseIsomorphism1D_to_FM
Hfrom = V.Hom(self)
Hto = self.Hom(V)
from_V = Hfrom.__make_element_class__(BaseIsomorphism1D_from_FM)(Hfrom, basis=basis)
to_V = Hto.__make_element_class__(BaseIsomorphism1D_to_FM)(Hto, basis=basis)
return (V, from_V, to_V)
else:
if (not self.has_coerce_map_from(base)):
raise ValueError('base must be a subring of this ring')
raise NotImplementedError
class ElementMethods():
def is_unit(self) -> bool:
'\n Return whether this element is a unit in the ring.\n\n .. NOTE::\n\n This is a generic implementation for (non-commutative) rings\n which only works for the one element, its additive inverse, and\n the zero element. Most rings should provide a more specialized\n implementation.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: MS = MatrixSpace(ZZ, 2)\n sage: MS.one().is_unit()\n True\n sage: MS.zero().is_unit()\n False\n sage: MS([1,2,3,4]).is_unit()\n False\n '
if (self.is_one() or (- self).is_one()):
return True
if self.is_zero():
return False
raise NotImplementedError
def inverse_of_unit(self):
'\n Return the inverse of this element if it is a unit.\n\n OUTPUT:\n\n An element in the same ring as this element.\n\n EXAMPLES::\n\n sage: R.<x> = ZZ[]\n sage: S = R.quo(x^2 + x + 1) # needs sage.libs.pari\n sage: S(1).inverse_of_unit() # needs sage.libs.pari\n 1\n\n This method fails when the element is not a unit::\n\n sage: 2.inverse_of_unit()\n Traceback (most recent call last):\n ...\n ArithmeticError: inverse does not exist\n\n The inverse returned is in the same ring as this element::\n\n sage: a = -1\n sage: a.parent()\n Integer Ring\n sage: a.inverse_of_unit().parent()\n Integer Ring\n\n Note that this is often not the case when computing inverses in other ways::\n\n sage: (~a).parent()\n Rational Field\n sage: (1/a).parent()\n Rational Field\n '
try:
if (not self.is_unit()):
raise ArithmeticError('element is not a unit')
except NotImplementedError:
pass
inverse = (~ self)
if (inverse not in self.parent()):
raise ArithmeticError('element is not a unit')
return self.parent()(inverse)
def _divide_if_possible(self, y):
'\n Divide ``self`` by ``y`` if possible and raise a\n :class:`ValueError` otherwise.\n\n EXAMPLES::\n\n sage: 4._divide_if_possible(2)\n 2\n sage: _.parent()\n Integer Ring\n\n sage: 4._divide_if_possible(3)\n Traceback (most recent call last):\n ...\n ValueError: 4 is not divisible by 3\n '
(q, r) = self.quo_rem(y)
if (r != 0):
raise ValueError(('%s is not divisible by %s' % (self, y)))
return q
|
def _gen_names(elts):
"\n Used to find a name for a generator when rings are created using the\n ``__getitem__`` syntax, e.g. ``ZZ['x']``, ``ZZ[sqrt(2)]``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: from sage.categories.rings import _gen_names\n sage: list(_gen_names([sqrt(5)])) # needs sage.symbolic\n ['sqrt5']\n sage: list(_gen_names([sqrt(-17), 2^(1/3)])) # needs sage.symbolic\n ['a', 'b']\n sage: list(_gen_names((1..27)))[-1]\n 'aa'\n "
import re
from sage.structure.category_object import certify_names
from sage.combinat.words.words import Words
it = iter(Words('abcdefghijklmnopqrstuvwxyz', infinite=False))
next(it)
for x in elts:
name = str(x)
m = re.match('^sqrt\\((\\d+)\\)$', name)
if m:
name = ('sqrt%s' % m.groups()[0])
try:
certify_names([name])
except ValueError:
name = next(it).string_rep()
(yield name)
|
class Rngs(CategoryWithAxiom):
"\n The category of rngs.\n\n An *rng* `(S, +, *)` is similar to a ring but not necessarily\n unital. In other words, it is a combination of a commutative\n additive group `(S, +)` and a multiplicative semigroup `(S, *)`,\n where `*` distributes over `+`.\n\n EXAMPLES::\n\n sage: C = Rngs(); C\n Category of rngs\n sage: sorted(C.super_categories(), key=str)\n [Category of associative additive commutative additive associative additive unital distributive magmas and additive magmas,\n Category of commutative additive groups]\n\n sage: sorted(C.axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse',\n 'AdditiveUnital', 'Associative', 'Distributive']\n\n sage: C is (CommutativeAdditiveGroups() & Semigroups()).Distributive()\n True\n sage: C.Unital()\n Category of rings\n\n TESTS::\n\n sage: TestSuite(C).run()\n "
_base_category_class_and_axiom = (MagmasAndAdditiveMagmas.Distributive.AdditiveAssociative.AdditiveCommutative.AdditiveUnital.Associative, 'AdditiveInverse')
Unital = LazyImport('sage.categories.rings', 'Rings', at_startup=True)
|
class Schemes(Category):
'\n The category of all schemes.\n\n EXAMPLES::\n\n sage: Schemes()\n Category of schemes\n\n ``Schemes`` can also be used to construct the category of schemes\n over a given base::\n\n sage: Schemes(Spec(ZZ))\n Category of schemes over Integer Ring\n\n sage: Schemes(ZZ)\n Category of schemes over Integer Ring\n\n .. TODO::\n\n Make ``Schemes()`` a singleton category (and remove\n :class:`Schemes` from the workaround in\n :meth:`.category_types.Category_over_base._test_category_over_bases`).\n\n This is currently incompatible with the dispatching below.\n\n TESTS::\n\n sage: TestSuite(Schemes()).run()\n\n Check that Hom sets of schemes are in the correct category::\n\n sage: Schemes().Homsets().super_categories()\n [Category of homsets]\n '
@staticmethod
def __classcall_private__(cls, X=None):
'\n Implement the dispatching ``Schemes(ZZ)`` -> ``Schemes_over_base``.\n\n EXAMPLES::\n\n sage: Schemes()\n Category of schemes\n\n sage: Schemes(Spec(ZZ))\n Category of schemes over Integer Ring\n\n sage: Schemes(ZZ)\n Category of schemes over Integer Ring\n '
if (X is not None):
from sage.schemes.generic.scheme import is_Scheme
if (not is_Scheme(X)):
X = Schemes()(X)
return Schemes_over_base(X)
return super().__classcall__(cls)
def super_categories(self):
'\n EXAMPLES::\n\n sage: Schemes().super_categories()\n [Category of sets]\n '
return [Sets()]
def _call_(self, x):
'\n Construct a scheme from the data in ``x``\n\n EXAMPLES:\n\n Let us first construct the category of schemes::\n\n sage: S = Schemes(); S\n Category of schemes\n\n We create a scheme from a ring::\n\n sage: X = S(ZZ); X # indirect doctest\n Spectrum of Integer Ring\n\n We create a scheme from a scheme (do nothing)::\n\n sage: S(X)\n Spectrum of Integer Ring\n\n We create a scheme morphism from a ring homomorphism.x::\n\n sage: phi = ZZ.hom(QQ); phi\n Natural morphism:\n From: Integer Ring\n To: Rational Field\n sage: f = S(phi); f # indirect doctest\n Affine Scheme morphism:\n From: Spectrum of Rational Field\n To: Spectrum of Integer Ring\n Defn: Natural morphism:\n From: Integer Ring\n To: Rational Field\n\n sage: f.domain()\n Spectrum of Rational Field\n sage: f.codomain()\n Spectrum of Integer Ring\n sage: S(f) # indirect doctest\n Affine Scheme morphism:\n From: Spectrum of Rational Field\n To: Spectrum of Integer Ring\n Defn: Natural morphism:\n From: Integer Ring\n To: Rational Field\n\n '
from sage.schemes.generic.scheme import is_Scheme
if is_Scheme(x):
return x
from sage.schemes.generic.morphism import is_SchemeMorphism
if is_SchemeMorphism(x):
return x
from sage.categories.commutative_rings import CommutativeRings
from sage.schemes.generic.spec import Spec
from sage.categories.map import Map
from sage.categories.rings import Rings
if (x in CommutativeRings()):
return Spec(x)
elif (isinstance(x, Map) and x.category_for().is_subcategory(Rings())):
A = Spec(x.codomain())
return A.hom(x)
else:
raise TypeError(('No way to create an object or morphism in %s from %s' % (self, x)))
|
class Schemes_over_base(Category_over_base):
'\n The category of schemes over a given base scheme.\n\n EXAMPLES::\n\n sage: Schemes(Spec(ZZ))\n Category of schemes over Integer Ring\n\n TESTS::\n\n sage: C = Schemes(ZZ)\n sage: TestSuite(C).run()\n '
def base_scheme(self):
'\n EXAMPLES::\n\n sage: Schemes(Spec(ZZ)).base_scheme()\n Spectrum of Integer Ring\n '
return self.base()
def super_categories(self):
'\n EXAMPLES::\n\n sage: Schemes(Spec(ZZ)).super_categories()\n [Category of schemes]\n '
return [Schemes()]
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Schemes(Spec(ZZ)) # indirect doctest\n Category of schemes over Integer Ring\n '
from sage.schemes.generic.scheme import is_AffineScheme
if is_AffineScheme(self.base_scheme()):
return ('schemes over %s' % self.base_scheme().coordinate_ring())
else:
return ('schemes over %s' % self.base_scheme())
|
class Semigroups(CategoryWithAxiom):
"\n The category of (multiplicative) semigroups.\n\n A *semigroup* is an associative :class:`magma <Magmas>`, that is a\n set endowed with a multiplicative binary operation `*` which is\n associative (see :wikipedia:`Semigroup`).\n\n The operation `*` is not required to have a neutral element. A\n semigroup for which such an element exists is a :class:`monoid\n <sage.categories.monoids.Monoids>`.\n\n EXAMPLES::\n\n sage: C = Semigroups(); C\n Category of semigroups\n sage: C.super_categories()\n [Category of magmas]\n sage: C.all_super_categories()\n [Category of semigroups, Category of magmas,\n Category of sets, Category of sets with partial maps, Category of objects]\n sage: C.axioms()\n frozenset({'Associative'})\n sage: C.example()\n An example of a semigroup: the left zero semigroup\n\n TESTS::\n\n sage: TestSuite(C).run()\n "
_base_category_class_and_axiom = (Magmas, 'Associative')
def example(self, choice='leftzero', **kwds):
"\n Returns an example of a semigroup, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n INPUT:\n\n - ``choice`` -- str (default: 'leftzero'). Can be either 'leftzero'\n for the left zero semigroup, or 'free' for the free semigroup.\n - ``**kwds`` -- keyword arguments passed onto the constructor for the\n chosen semigroup.\n\n EXAMPLES::\n\n sage: Semigroups().example(choice='leftzero')\n An example of a semigroup: the left zero semigroup\n sage: Semigroups().example(choice='free')\n An example of a semigroup: the free semigroup generated by ('a', 'b', 'c', 'd')\n sage: Semigroups().example(choice='free', alphabet=('a','b'))\n An example of a semigroup: the free semigroup generated by ('a', 'b')\n\n "
import sage.categories.examples.semigroups as examples
if (choice == 'leftzero'):
return examples.LeftZeroSemigroup(**kwds)
else:
return examples.FreeSemigroup(**kwds)
class ParentMethods():
def _test_associativity(self, **options):
"\n Test associativity for (not necessarily all) elements of this\n semigroup.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted by :meth:`_tester`\n\n EXAMPLES:\n\n By default, this method tests only the elements returned by\n ``self.some_elements()``::\n\n sage: L = Semigroups().example(choice='leftzero')\n sage: L._test_associativity()\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument::\n\n sage: L._test_associativity(elements = (L(1), L(2), L(3)))\n\n See the documentation for :class:`TestSuite` for more information.\n\n "
tester = self._tester(**options)
S = tester.some_elements()
from sage.misc.misc import some_tuples
for (x, y, z) in some_tuples(S, 3, tester._max_runs):
tester.assertEqual(((x * y) * z), (x * (y * z)))
@abstract_method(optional=True)
def semigroup_generators(self):
'\n Return distinguished semigroup generators for ``self``.\n\n OUTPUT: a family\n\n This method is optional.\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 sage: S.semigroup_generators()\n Family (\'a\', \'b\', \'c\', \'d\')\n '
def magma_generators(self):
'\n An alias for :meth:`semigroup_generators`.\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 sage: S.magma_generators()\n Family (\'a\', \'b\', \'c\', \'d\')\n sage: S.semigroup_generators()\n Family (\'a\', \'b\', \'c\', \'d\')\n '
return self.semigroup_generators()
def prod(self, args):
'\n Return the product of the list of elements ``args``\n inside ``self``.\n\n EXAMPLES::\n\n sage: S = Semigroups().example("free")\n sage: S.prod([S(\'a\'), S(\'b\'), S(\'c\')])\n \'abc\'\n sage: S.prod([])\n Traceback (most recent call last):\n ...\n AssertionError: Cannot compute an empty product in a semigroup\n '
from sage.misc.misc_c import prod
assert (len(args) > 0), 'Cannot compute an empty product in a semigroup'
return prod(args[1:], args[0])
def cayley_graph(self, side='right', simple=False, elements=None, generators=None, connecting_set=None):
'\n Return the Cayley graph for this finite semigroup.\n\n INPUT:\n\n - ``side`` -- "left", "right", or "twosided":\n the side on which the generators act (default:"right")\n - ``simple`` -- boolean (default:False):\n if True, returns a simple graph (no loops, no labels,\n no multiple edges)\n - ``generators`` -- a list, tuple, or family of elements\n of ``self`` (default: ``self.semigroup_generators()``)\n - ``connecting_set`` -- alias for ``generators``; deprecated\n - ``elements`` -- a list (or iterable) of elements of ``self``\n\n OUTPUT:\n\n - :class:`DiGraph`\n\n EXAMPLES:\n\n We start with the (right) Cayley graphs of some classical groups::\n\n sage: # needs sage.graphs sage.groups\n sage: D4 = DihedralGroup(4); D4\n Dihedral group of order 8 as a permutation group\n sage: G = D4.cayley_graph()\n sage: show(G, color_by_label=True, edge_labels=True) # needs sage.plot\n sage: A5 = AlternatingGroup(5); A5\n Alternating group of order 5!/2 as a permutation group\n sage: G = A5.cayley_graph()\n sage: G.show3d(color_by_label=True, edge_size=0.01, # needs sage.plot\n ....: edge_size2=0.02, vertex_size=0.03)\n sage: G.show3d(vertex_size=0.03, # long time (less than a minute), needs sage.plot\n ....: edge_size=0.01, edge_size2=0.02,\n ....: vertex_colors={(1,1,1): G.vertices(sort=True)},\n ....: bgcolor=(0,0,0), color_by_label=True,\n ....: xres=700, yres=700, iterations=200)\n sage: G.num_edges()\n 120\n\n sage: # needs sage.combinat sage.graphs sage.groups\n sage: w = WeylGroup([\'A\', 3])\n sage: d = w.cayley_graph(); d\n Digraph on 24 vertices\n sage: d.show3d(color_by_label=True, edge_size=0.01, vertex_size=0.03) # needs sage.plot\n\n Alternative generators may be specified::\n\n sage: # needs sage.graphs sage.groups\n sage: G = A5.cayley_graph(generators=[A5.gens()[0]])\n sage: G.num_edges()\n 60\n sage: g = PermutationGroup([(i + 1, j + 1)\n ....: for i in range(5)\n ....: for j in range(5) if j != i])\n sage: g.cayley_graph(generators=[(1,2), (2,3)])\n Digraph on 120 vertices\n\n If ``elements`` is specified, then only the subgraph\n induced and those elements is returned. Here we use it to\n display the Cayley graph of the free monoid truncated on\n the elements of length at most 3::\n\n sage: # needs sage.combinat sage.graphs\n sage: M = Monoids().example(); M\n An example of a monoid:\n the free monoid generated by (\'a\', \'b\', \'c\', \'d\')\n sage: elements = [M.prod(w)\n ....: for w in sum((list(Words(M.semigroup_generators(), k))\n ....: for k in range(4)), [])]\n sage: G = M.cayley_graph(elements=elements)\n sage: G.num_verts(), G.num_edges()\n (85, 84)\n sage: G.show3d(color_by_label=True, edge_size=0.001, vertex_size=0.01) # needs sage.plot\n\n We now illustrate the ``side`` and ``simple`` options on\n a semigroup::\n\n sage: S = FiniteSemigroups().example(alphabet=(\'a\', \'b\'))\n sage: g = S.cayley_graph(simple=True) # needs sage.graphs\n sage: g.vertices(sort=True) # needs sage.graphs\n [\'a\', \'ab\', \'b\', \'ba\']\n sage: g.edges(sort=True) # needs sage.graphs\n [(\'a\', \'ab\', None), (\'b\', \'ba\', None)]\n\n ::\n\n sage: g = S.cayley_graph(side="left", simple=True) # needs sage.graphs\n sage: g.vertices(sort=True) # needs sage.graphs\n [\'a\', \'ab\', \'b\', \'ba\']\n sage: g.edges(sort=True) # needs sage.graphs\n [(\'a\', \'ba\', None), (\'ab\', \'ba\', None), (\'b\', \'ab\', None),\n (\'ba\', \'ab\', None)]\n\n ::\n\n sage: g = S.cayley_graph(side="twosided", simple=True) # needs sage.graphs\n sage: g.vertices(sort=True) # needs sage.graphs\n [\'a\', \'ab\', \'b\', \'ba\']\n sage: g.edges(sort=True) # needs sage.graphs\n [(\'a\', \'ab\', None), (\'a\', \'ba\', None), (\'ab\', \'ba\', None),\n (\'b\', \'ab\', None), (\'b\', \'ba\', None), (\'ba\', \'ab\', None)]\n\n ::\n\n sage: g = S.cayley_graph(side="twosided") # needs sage.graphs\n sage: g.vertices(sort=True) # needs sage.graphs\n [\'a\', \'ab\', \'b\', \'ba\']\n sage: g.edges(sort=True) # needs sage.graphs\n [(\'a\', \'a\', (0, \'left\')), (\'a\', \'a\', (0, \'right\')), (\'a\', \'ab\', (1, \'right\')), (\'a\', \'ba\', (1, \'left\')), (\'ab\', \'ab\', (0, \'left\')), (\'ab\', \'ab\', (0, \'right\')), (\'ab\', \'ab\', (1, \'right\')), (\'ab\', \'ba\', (1, \'left\')), (\'b\', \'ab\', (0, \'left\')), (\'b\', \'b\', (1, \'left\')), (\'b\', \'b\', (1, \'right\')), (\'b\', \'ba\', (0, \'right\')), (\'ba\', \'ab\', (0, \'left\')), (\'ba\', \'ba\', (0, \'right\')), (\'ba\', \'ba\', (1, \'left\')), (\'ba\', \'ba\', (1, \'right\'))]\n\n ::\n\n sage: s1 = SymmetricGroup(1); s = s1.cayley_graph() # needs sage.graphs sage.groups\n sage: s.vertices(sort=False) # needs sage.graphs sage.groups\n [()]\n\n TESTS::\n\n sage: SymmetricGroup(2).cayley_graph(side="both") # needs sage.graphs sage.groups\n Traceback (most recent call last):\n ...\n ValueError: option \'side\' must be \'left\', \'right\' or \'twosided\'\n\n .. TODO::\n\n - Add more options for constructing subgraphs of the\n Cayley graph, handling the standard use cases when\n exploring large/infinite semigroups (a predicate,\n generators of an ideal, a maximal length in term of the\n generators)\n\n - Specify good default layout/plot/latex options in the graph\n\n - Generalize to combinatorial modules with module generators / operators\n\n AUTHORS:\n\n - Bobby Moretti (2007-08-10)\n - Robert Miller (2008-05-01): editing\n - Nicolas M. Thiery (2008-12): extension to semigroups,\n ``side``, ``simple``, and ``elements`` options, ...\n '
from sage.graphs.digraph import DiGraph
from .monoids import Monoids
from .groups import Groups
if (side not in ['left', 'right', 'twosided']):
raise ValueError("option 'side' must be 'left', 'right' or 'twosided'")
if (elements is None):
assert self.is_finite(), 'elements should be specified for infinite semigroups'
elements = self
else:
elements = set(elements)
if (simple or (self in Groups())):
result = DiGraph()
else:
result = DiGraph(multiedges=True, loops=True)
result.add_vertices(elements)
if (connecting_set is not None):
generators = connecting_set
if (generators is None):
if ((self in Monoids) and hasattr(self, 'monoid_generators')):
generators = self.monoid_generators()
else:
generators = self.semigroup_generators()
if isinstance(generators, (list, tuple)):
generators = {self(g): self(g) for g in generators}
left = ((side == 'left') or (side == 'twosided'))
right = ((side == 'right') or (side == 'twosided'))
def add_edge(source, target, label, side_label):
'\n Skips edges whose targets are not in elements\n Return an appropriate edge given the options\n '
if ((elements is not self) and (target not in elements)):
return
if simple:
if (source != target):
result.add_edge([source, target])
elif (side == 'twosided'):
result.add_edge([source, target, (label, side_label)])
else:
result.add_edge([source, target, label])
for x in elements:
for i in generators.keys():
if left:
add_edge(x, (generators[i] * x), i, 'left')
if right:
add_edge(x, (x * generators[i]), i, 'right')
return result
def subsemigroup(self, generators, one=None, category=None):
'\n Return the multiplicative subsemigroup generated by ``generators``.\n\n INPUT:\n\n - ``generators`` -- a finite family of elements of\n ``self``, or a list, iterable, ... that can be converted\n into one (see :class:`Family`).\n\n - ``one`` -- a unit for the subsemigroup, or ``None``.\n\n - ``category`` -- a category\n\n This implementation lazily constructs all the elements of\n the semigroup, and the right Cayley graph relations\n between them, and uses the latter as an automaton.\n\n See :class:`~sage.sets.monoids.AutomaticSemigroup` for details.\n\n EXAMPLES::\n\n sage: R = IntegerModRing(15)\n sage: M = R.subsemigroup([R(3), R(5)]); M # needs sage.combinat\n A subsemigroup of (Ring of integers modulo 15) with 2 generators\n sage: M.list() # needs sage.combinat\n [3, 5, 9, 0, 10, 12, 6]\n\n By default, `M` is just in the category of subsemigroups::\n\n sage: M in Semigroups().Subobjects() # needs sage.combinat\n True\n\n In the following example, we specify that `M` is a\n submonoid of the finite monoid `R` (it shares the same\n unit), and a group by itself::\n\n sage: M = R.subsemigroup([R(-1)], # needs sage.combinat\n ....: category=Monoids().Finite().Subobjects() & Groups()); M\n A submonoid of (Ring of integers modulo 15) with 1 generators\n sage: M.list() # needs sage.combinat\n [1, 14]\n sage: M.one() # needs sage.combinat\n 1\n\n In the following example, `M` is a group; however, its unit\n does not coincide with that of `R`, so `M` is only a\n subsemigroup, and we need to specify its unit explicitly::\n\n sage: M = R.subsemigroup([R(5)], # needs sage.combinat\n ....: category=Semigroups().Finite().Subobjects() & Groups()); M\n Traceback (most recent call last):\n ...\n ValueError: For a monoid which is just a subsemigroup,\n the unit should be specified\n\n sage: # needs sage.groups\n sage: M = R.subsemigroup([R(5)], one=R(10),\n ....: category=Semigroups().Finite().Subobjects() & Groups()); M\n A subsemigroup of (Ring of integers modulo 15) with 1 generators\n sage: M in Groups()\n True\n sage: M.list()\n [10, 5]\n sage: M.one()\n 10\n\n TESTS::\n\n sage: TestSuite(M).run() # needs sage.combinat\n Failure in _test_inverse:\n Traceback (most recent call last):\n ...\n The following tests failed: _test_inverse\n\n .. TODO::\n\n - Fix the failure in TESTS by providing a default\n implementation of ``__invert__`` for finite groups\n (or even finite monoids).\n - Provide a default implementation of ``one`` for a\n finite monoid, so that we would not need to specify\n it explicitly?\n '
from sage.monoids.automatic_semigroup import AutomaticSemigroup
return AutomaticSemigroup(generators, ambient=self, one=one, category=category)
def trivial_representation(self, base_ring=None, side='twosided'):
'\n Return the trivial representation of ``self`` over ``base_ring``.\n\n INPUT:\n\n - ``base_ring`` -- (optional) the base ring; the default is `\\ZZ`\n - ``side`` -- ignored\n\n EXAMPLES::\n\n sage: G = groups.permutation.Dihedral(4) # needs sage.groups\n sage: G.trivial_representation() # needs sage.groups\n Trivial representation of Dihedral group of order 8\n as a permutation group over Integer Ring\n '
if (base_ring is None):
from sage.rings.integer_ring import ZZ
base_ring = ZZ
from sage.modules.with_basis.representation import TrivialRepresentation
return TrivialRepresentation(self, base_ring)
def regular_representation(self, base_ring=None, side='left'):
'\n Return the regular representation of ``self`` over ``base_ring``.\n\n - ``side`` -- (default: ``"left"``) whether this is the\n ``"left"`` or ``"right"`` regular representation\n\n EXAMPLES::\n\n sage: G = groups.permutation.Dihedral(4) # needs sage.groups\n sage: G.regular_representation() # needs sage.groups\n Left Regular Representation of Dihedral group of order 8\n as a permutation group over Integer Ring\n '
if (base_ring is None):
from sage.rings.integer_ring import ZZ
base_ring = ZZ
from sage.modules.with_basis.representation import RegularRepresentation
return RegularRepresentation(self, base_ring, side)
class ElementMethods():
def _pow_int(self, n):
'\n Return ``self`` to the `n^{th}` power.\n\n INPUT:\n\n - ``n`` -- a positive integer\n\n EXAMPLES::\n\n sage: S = Semigroups().example("leftzero")\n sage: x = S("x")\n sage: x^1, x^2, x^3, x^4, x^5\n (\'x\', \'x\', \'x\', \'x\', \'x\')\n sage: x^0\n Traceback (most recent call last):\n ...\n ArithmeticError: only positive powers are supported in a semigroup\n\n TESTS::\n\n sage: x._pow_int(17)\n \'x\'\n '
if (n <= 0):
raise ArithmeticError('only positive powers are supported in a semigroup')
return generic_power(self, n)
class SubcategoryMethods():
@cached_method
def LTrivial(self):
"\n Return the full subcategory of the `L`-trivial objects of ``self``.\n\n Let `S` be (multiplicative) :class:`semigroup <Semigroups>`.\n The `L`-*preorder* `\\leq_L` on `S` is defined by:\n\n .. MATH::\n\n x\\leq_L y \\qquad \\Longleftrightarrow \\qquad x \\in Sy\n\n The `L`-*classes* are the equivalence classes for the\n associated equivalence relation. The semigroup `S` is\n `L`-*trivial* if all its `L`-classes are trivial (that is\n of cardinality `1`), or equivalently if the `L`-preorder is\n in fact a partial order.\n\n EXAMPLES::\n\n sage: C = Semigroups().LTrivial(); C\n Category of l trivial semigroups\n\n A `L`-trivial semigroup is `H`-trivial::\n\n sage: sorted(C.axioms())\n ['Associative', 'HTrivial', 'LTrivial']\n\n .. SEEALSO::\n\n - :wikipedia:`Green%27s_relations`\n - :class:`Semigroups.SubcategoryMethods.RTrivial`\n - :class:`Semigroups.SubcategoryMethods.JTrivial`\n - :class:`Semigroups.SubcategoryMethods.HTrivial`\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Rings().LTrivial.__module__\n 'sage.categories.semigroups'\n sage: C # todo: not implemented\n Category of L-trivial semigroups\n "
return self._with_axiom('LTrivial')
@cached_method
def RTrivial(self):
"\n Return the full subcategory of the `R`-trivial objects of ``self``.\n\n Let `S` be (multiplicative) :class:`semigroup <Semigroups>`.\n The `R`-*preorder* `\\leq_R` on `S` is defined by:\n\n .. MATH::\n\n x\\leq_R y \\qquad \\Longleftrightarrow \\qquad x \\in yS\n\n The `R`-*classes* are the equivalence classes for the\n associated equivalence relation. The semigroup `S` is\n `R`-*trivial* if all its `R`-classes are trivial (that is\n of cardinality `1`), or equivalently if the `R`-preorder is\n in fact a partial order.\n\n EXAMPLES::\n\n sage: C = Semigroups().RTrivial(); C\n Category of r trivial semigroups\n\n An `R`-trivial semigroup is `H`-trivial::\n\n sage: sorted(C.axioms())\n ['Associative', 'HTrivial', 'RTrivial']\n\n .. SEEALSO::\n\n - :wikipedia:`Green%27s_relations`\n - :class:`Semigroups.SubcategoryMethods.LTrivial`\n - :class:`Semigroups.SubcategoryMethods.JTrivial`\n - :class:`Semigroups.SubcategoryMethods.HTrivial`\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Rings().RTrivial.__module__\n 'sage.categories.semigroups'\n sage: C # todo: not implemented\n Category of R-trivial semigroups\n "
return self._with_axiom('RTrivial')
@cached_method
def JTrivial(self):
"\n Return the full subcategory of the `J`-trivial objects of ``self``.\n\n Let `S` be (multiplicative) :class:`semigroup <Semigroups>`.\n The `J`-*preorder* `\\leq_J` on `S` is defined by:\n\n .. MATH::\n\n x\\leq_J y \\qquad \\Longleftrightarrow \\qquad x \\in SyS\n\n The `J`-*classes* are the equivalence classes for the\n associated equivalence relation. The semigroup `S` is\n `J`-*trivial* if all its `J`-classes are trivial (that is\n of cardinality `1`), or equivalently if the `J`-preorder is\n in fact a partial order.\n\n EXAMPLES::\n\n sage: C = Semigroups().JTrivial(); C\n Category of j trivial semigroups\n\n A semigroup is `J`-trivial if and only if it is\n `L`-trivial and `R`-trivial::\n\n sage: sorted(C.axioms())\n ['Associative', 'HTrivial', 'JTrivial', 'LTrivial', 'RTrivial']\n sage: Semigroups().LTrivial().RTrivial()\n Category of j trivial semigroups\n\n For a commutative semigroup, all three axioms are\n equivalent::\n\n sage: Semigroups().Commutative().LTrivial()\n Category of commutative j trivial semigroups\n sage: Semigroups().Commutative().RTrivial()\n Category of commutative j trivial semigroups\n\n .. SEEALSO::\n\n - :wikipedia:`Green%27s_relations`\n - :class:`Semigroups.SubcategoryMethods.LTrivial`\n - :class:`Semigroups.SubcategoryMethods.RTrivial`\n - :class:`Semigroups.SubcategoryMethods.HTrivial`\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Rings().JTrivial.__module__\n 'sage.categories.semigroups'\n sage: C # todo: not implemented\n Category of J-trivial semigroups\n "
return self._with_axiom('JTrivial')
@cached_method
def HTrivial(self):
"\n Return the full subcategory of the `H`-trivial objects of ``self``.\n\n Let `S` be (multiplicative) :class:`semigroup <Semigroups>`.\n Two elements of `S` are in the same `H`-class if they are\n in the same `L`-class and in the same `R`-class.\n\n The semigroup `S` is `H`-*trivial* if all its `H`-classes\n are trivial (that is of cardinality `1`).\n\n EXAMPLES::\n\n sage: C = Semigroups().HTrivial(); C\n Category of h trivial semigroups\n sage: Semigroups().HTrivial().Finite().example()\n NotImplemented\n\n .. SEEALSO::\n\n - :wikipedia:`Green%27s_relations`\n - :class:`Semigroups.SubcategoryMethods.RTrivial`\n - :class:`Semigroups.SubcategoryMethods.LTrivial`\n - :class:`Semigroups.SubcategoryMethods.JTrivial`\n - :class:`Semigroups.SubcategoryMethods.Aperiodic`\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Rings().HTrivial.__module__\n 'sage.categories.semigroups'\n sage: C # todo: not implemented\n Category of H-trivial semigroups\n "
return self._with_axiom('HTrivial')
@cached_method
def Aperiodic(self):
"\n Return the full subcategory of the aperiodic objects of ``self``.\n\n A (multiplicative) :class:`semigroup <Semigroups>` `S` is\n *aperiodic* if for any element `s\\in S`, the sequence\n `s,s^2,s^3,...` eventually stabilizes.\n\n In terms of variety, this can be described by the equation\n `s^\\omega s = s`.\n\n EXAMPLES::\n\n sage: Semigroups().Aperiodic()\n Category of aperiodic semigroups\n\n An aperiodic semigroup is `H`-trivial::\n\n sage: Semigroups().Aperiodic().axioms()\n frozenset({'Aperiodic', 'Associative', 'HTrivial'})\n\n In the finite case, the two notions coincide::\n\n sage: Semigroups().Aperiodic().Finite() is Semigroups().HTrivial().Finite()\n True\n\n TESTS::\n\n sage: C = Monoids().Aperiodic().Finite()\n sage: TestSuite(C).run()\n\n .. SEEALSO::\n\n - :wikipedia:`Aperiodic_semigroup`\n - :class:`Semigroups.SubcategoryMethods.RTrivial`\n - :class:`Semigroups.SubcategoryMethods.LTrivial`\n - :class:`Semigroups.SubcategoryMethods.JTrivial`\n - :class:`Semigroups.SubcategoryMethods.Aperiodic`\n\n TESTS::\n\n sage: TestSuite(C).run()\n sage: Rings().Aperiodic.__module__\n 'sage.categories.semigroups'\n "
return self._with_axiom('Aperiodic')
Finite = LazyImport('sage.categories.finite_semigroups', 'FiniteSemigroups', at_startup=True)
FinitelyGeneratedAsMagma = LazyImport('sage.categories.finitely_generated_semigroups', 'FinitelyGeneratedSemigroups')
Unital = LazyImport('sage.categories.monoids', 'Monoids', at_startup=True)
LTrivial = LazyImport('sage.categories.l_trivial_semigroups', 'LTrivialSemigroups')
RTrivial = LazyImport('sage.categories.r_trivial_semigroups', 'RTrivialSemigroups')
JTrivial = LazyImport('sage.categories.j_trivial_semigroups', 'JTrivialSemigroups')
HTrivial = LazyImport('sage.categories.h_trivial_semigroups', 'HTrivialSemigroups')
Aperiodic = LazyImport('sage.categories.aperiodic_semigroups', 'AperiodicSemigroups')
class Subquotients(SubquotientsCategory):
'\n The category of subquotient semi-groups.\n\n EXAMPLES::\n\n sage: Semigroups().Subquotients().all_super_categories()\n [Category of subquotients of semigroups,\n Category of semigroups,\n Category of subquotients of magmas,\n Category of magmas,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n [Category of subquotients of semigroups,\n Category of semigroups,\n Category of subquotients of magmas,\n Category of magmas,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
def example(self):
'\n Returns an example of subquotient of a semigroup, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Semigroups().Subquotients().example()\n An example of a (sub)quotient semigroup: a quotient of the left zero semigroup\n '
from sage.categories.examples.semigroups import QuotientOfLeftZeroSemigroup
return QuotientOfLeftZeroSemigroup(category=self.Subquotients())
class Quotients(QuotientsCategory):
def example(self):
'\n Return an example of quotient of a semigroup, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Semigroups().Quotients().example()\n An example of a (sub)quotient semigroup: a quotient of the left zero semigroup\n '
from sage.categories.examples.semigroups import QuotientOfLeftZeroSemigroup
return QuotientOfLeftZeroSemigroup()
class ParentMethods():
def semigroup_generators(self):
'\n Return semigroup generators for ``self`` by\n retracting the semigroup generators of the ambient\n semigroup.\n\n EXAMPLES::\n\n sage: S = FiniteSemigroups().Quotients().example().semigroup_generators() # todo: not implemented\n '
return self.ambient().semigroup_generators().map(self.retract)
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a Cartesian product of semigroups is a\n semigroup.\n\n EXAMPLES::\n\n sage: Semigroups().CartesianProducts().extra_super_categories()\n [Category of semigroups]\n sage: Semigroups().CartesianProducts().super_categories()\n [Category of semigroups, Category of Cartesian products of magmas]\n '
return [Semigroups()]
class Algebras(AlgebrasCategory):
'\n TESTS::\n\n sage: TestSuite(Semigroups().Algebras(QQ)).run()\n sage: TestSuite(Semigroups().Finite().Algebras(QQ)).run()\n '
def extra_super_categories(self):
'\n Implement the fact that the algebra of a semigroup is indeed\n a (not necessarily unital) algebra.\n\n EXAMPLES::\n\n sage: Semigroups().Algebras(QQ).extra_super_categories()\n [Category of semigroups]\n sage: Semigroups().Algebras(QQ).super_categories()\n [Category of associative algebras over Rational Field,\n Category of magma algebras over Rational Field]\n '
return [Semigroups()]
class ParentMethods():
@cached_method
def algebra_generators(self):
"\n The generators of this algebra, as per\n :meth:`MagmaticAlgebras.ParentMethods.algebra_generators()\n <.magmatic_algebras.MagmaticAlgebras.ParentMethods.algebra_generators>`.\n\n They correspond to the generators of the semigroup.\n\n EXAMPLES::\n\n sage: M = FiniteSemigroups().example(); M\n An example of a finite semigroup:\n the left regular band generated by ('a', 'b', 'c', 'd')\n sage: M.semigroup_generators()\n Family ('a', 'b', 'c', 'd')\n sage: M.algebra(ZZ).algebra_generators() # needs sage.modules\n Family (B['a'], B['b'], B['c'], B['d'])\n "
return self.basis().keys().semigroup_generators().map(self.monomial)
def gens(self):
'\n Return the generators of ``self``.\n\n EXAMPLES::\n\n sage: a, b = SL2Z.algebra(ZZ).gens(); a, b # needs sage.groups sage.modules\n ([ 0 -1]\n [ 1 0],\n [1 1]\n [0 1])\n sage: 2*a + b # needs sage.groups sage.modules\n 2*[ 0 -1]\n [ 1 0]\n +\n [1 1]\n [0 1]\n '
return tuple((self.monomial(g) for g in self.basis().keys().gens()))
def ngens(self):
'\n Return the number of generators of ``self``.\n\n EXAMPLES::\n\n sage: SL2Z.algebra(ZZ).ngens() # needs sage.groups sage.modules\n 2\n sage: DihedralGroup(4).algebra(RR).ngens() # needs sage.groups sage.modules\n 2\n '
return self.basis().keys().ngens()
def gen(self, i=0):
'\n Return the ``i``-th generator of ``self``.\n\n EXAMPLES::\n\n sage: A = GL(3, GF(7)).algebra(ZZ) # needs sage.modules\n sage: A.gen(0) # needs sage.groups sage.libs.pari sage.modules\n [3 0 0]\n [0 1 0]\n [0 0 1]\n '
return self.monomial(self.basis().keys().gen(i))
def product_on_basis(self, g1, g2):
"\n Product, on basis elements, as per\n :meth:`MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis()\n <.magmatic_algebras.MagmaticAlgebras.WithBasis.ParentMethods.product_on_basis>`.\n\n The product of two basis elements is induced by the\n product of the corresponding elements of the group.\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 sage: A = S.algebra(QQ) # needs sage.modules\n sage: a, b, c, d = A.algebra_generators() # needs sage.modules\n sage: a * b + b * d * c * d # needs sage.modules\n B['ab'] + B['bdc']\n "
return self.monomial((g1 * g2))
def trivial_representation(self, side='twosided'):
'\n Return the trivial representation of ``self``.\n\n INPUT:\n\n - ``side`` -- ignored\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: G = groups.permutation.Dihedral(4)\n sage: A = G.algebra(QQ) # needs sage.modules\n sage: V = A.trivial_representation() # needs sage.modules\n sage: V == G.trivial_representation(QQ) # needs sage.modules\n True\n '
S = self.basis().keys()
return S.trivial_representation(self.base_ring())
def regular_representation(self, side='left'):
'\n Return the regular representation of ``self``.\n\n INPUT:\n\n - ``side`` -- (default: ``"left"``) whether this is the\n ``"left"`` or ``"right"`` regular representation\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: G = groups.permutation.Dihedral(4)\n sage: A = G.algebra(QQ) # needs sage.modules\n sage: V = A.regular_representation() # needs sage.modules\n sage: V == G.regular_representation(QQ) # needs sage.modules\n True\n '
S = self.basis().keys()
return S.regular_representation(self.base_ring(), side)
|
class Semirings(CategoryWithAxiom):
"\n The category of semirings.\n\n A semiring `(S,+,*)` is similar to a ring, but without the\n requirement that each element must have an additive inverse. In\n other words, it is a combination of a commutative additive monoid\n `(S,+)` and a multiplicative monoid `(S,*)`, where `*` distributes\n over `+`.\n\n .. SEEALSO::\n\n :wikipedia:`Semiring`\n\n EXAMPLES::\n\n sage: Semirings()\n Category of semirings\n sage: Semirings().super_categories()\n [Category of associative additive commutative additive associative additive unital distributive magmas and additive magmas,\n Category of monoids]\n\n sage: sorted(Semirings().axioms())\n ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveUnital', 'Associative', 'Distributive', 'Unital']\n\n sage: Semirings() is (CommutativeAdditiveMonoids() & Monoids()).Distributive()\n True\n\n sage: Semirings().AdditiveInverse()\n Category of rings\n\n\n TESTS::\n\n sage: TestSuite(Semirings()).run()\n "
_base_category_class_and_axiom = (MagmasAndAdditiveMagmas.Distributive.AdditiveAssociative.AdditiveCommutative.AdditiveUnital.Associative, 'Unital')
|
class SemisimpleAlgebras(Category_over_base_ring):
'\n The category of semisimple algebras over a given base ring.\n\n EXAMPLES::\n\n sage: from sage.categories.semisimple_algebras import SemisimpleAlgebras\n sage: C = SemisimpleAlgebras(QQ); C\n Category of semisimple algebras over Rational Field\n\n This category is best constructed as::\n\n sage: D = Algebras(QQ).Semisimple(); D\n Category of semisimple algebras over Rational Field\n sage: D is C\n True\n\n sage: C.super_categories()\n [Category of algebras over Rational Field]\n\n Typically, finite group algebras are semisimple::\n\n sage: DihedralGroup(5).algebra(QQ) in SemisimpleAlgebras # needs sage.groups\n True\n\n Unless the characteristic of the field divides the order of the group::\n\n sage: DihedralGroup(5).algebra(IntegerModRing(5)) in SemisimpleAlgebras # needs sage.groups\n False\n\n sage: DihedralGroup(5).algebra(IntegerModRing(7)) in SemisimpleAlgebras # needs sage.groups\n True\n\n .. SEEALSO:: :wikipedia:`Semisimple_algebra`\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@staticmethod
def __classget__(cls, base_category, base_category_class):
"\n Implement the shorthand ``Algebras(K).Semisimple()`` for ``SemisimpleAlgebras(K)``.\n\n This magic mimics the syntax of axioms for a smooth transition\n if ``Semisimple`` becomes one.\n\n EXAMPLES::\n\n sage: Algebras(QQ).Semisimple()\n Category of semisimple algebras over Rational Field\n sage: Algebras.Semisimple\n <class 'sage.categories.semisimple_algebras.SemisimpleAlgebras'>\n "
if (base_category is None):
return cls
return BoundClass(cls, base_category.base_ring())
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: Algebras(QQ).Semisimple().super_categories()\n [Category of algebras over Rational Field]\n '
R = self.base_ring()
return [Algebras(R)]
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\n sage: A.radical_basis() # needs sage.groups\n ()\n\n TESTS::\n\n sage: A.radical_basis.__module__ # needs sage.groups\n 'sage.categories.finite_dimensional_semisimple_algebras_with_basis'\n "
return ()
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
WithBasis = LazyImport('sage.categories.finite_dimensional_semisimple_algebras_with_basis', 'FiniteDimensionalSemisimpleAlgebrasWithBasis')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.