code stringlengths 17 6.64M |
|---|
def print_compare(x, y):
'\n Helper method used in\n :meth:`Sets.ParentMethods._test_elements_eq_symmetric`,\n :meth:`Sets.ParentMethods._test_elements_eq_tranisitive`.\n\n INPUT:\n\n - ``x`` -- an element\n\n - ``y`` -- an element\n\n EXAMPLES::\n\n sage: from sage.categories.sets_cat import print_compare\n sage: print_compare(1,2)\n 1 != 2\n sage: print_compare(1,1)\n 1 == 1\n\n '
if (x == y):
return (LazyFormat('%s == %s') % (x, y))
else:
return (LazyFormat('%s != %s') % (x, y))
|
class EmptySetError(ValueError):
'\n Exception raised when some operation can\'t be performed on the empty set.\n\n EXAMPLES::\n\n sage: def first_element(st):\n ....: if not st: raise EmptySetError("no elements")\n ....: else: return st[0]\n sage: first_element(Set((1,2,3)))\n 1\n sage: first_element(Set([]))\n Traceback (most recent call last):\n ...\n EmptySetError: no elements\n '
pass
|
class Sets(Category_singleton):
'\n The category of sets.\n\n The base category for collections of elements with = (equality).\n\n This is also the category whose objects are all parents.\n\n EXAMPLES::\n\n sage: Sets()\n Category of sets\n sage: Sets().super_categories()\n [Category of sets with partial maps]\n sage: Sets().all_super_categories()\n [Category of sets, Category of sets with partial maps, Category of objects]\n\n Let us consider an example of set::\n\n sage: P = Sets().example("inherits")\n sage: P\n Set of prime numbers\n\n See ``P??`` for the code.\n\n\n P is in the category of sets::\n\n sage: P.category()\n Category of sets\n\n and therefore gets its methods from the following classes::\n\n sage: for cl in P.__class__.mro(): print(cl)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category\'>\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits\'>\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Abstract\'>\n <class \'sage.structure.unique_representation.UniqueRepresentation\'>\n <class \'sage.structure.unique_representation.CachedRepresentation\'>\n <class \'sage.misc.fast_methods.WithEqualityById\'>\n <class \'sage.structure.parent.Parent\'>\n <class \'sage.structure.category_object.CategoryObject\'>\n <class \'sage.structure.sage_object.SageObject\'>\n <class \'sage.categories.sets_cat.Sets.parent_class\'>\n <class \'sage.categories.sets_with_partial_maps.SetsWithPartialMaps.parent_class\'>\n <class \'sage.categories.objects.Objects.parent_class\'>\n <... \'object\'>\n\n We run some generic checks on P::\n\n sage: TestSuite(P).run(verbose=True) # needs sage.libs.pari\n running ._test_an_element() . . . pass\n running ._test_cardinality() . . . pass\n running ._test_category() . . . pass\n running ._test_construction() . . . pass\n running ._test_elements() . . .\n Running the test suite of self.an_element()\n running ._test_category() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n pass\n running ._test_elements_eq_reflexive() . . . pass\n running ._test_elements_eq_symmetric() . . . pass\n running ._test_elements_eq_transitive() . . . pass\n running ._test_elements_neq() . . . pass\n running ._test_eq() . . . pass\n running ._test_new() . . . pass\n running ._test_not_implemented_methods() . . . pass\n running ._test_pickling() . . . pass\n running ._test_some_elements() . . . pass\n\n Now, we manipulate some elements of P::\n\n sage: P.an_element()\n 47\n sage: x = P(3)\n sage: x.parent()\n Set of prime numbers\n sage: x in P, 4 in P\n (True, False)\n sage: x.is_prime()\n True\n\n They get their methods from the following classes::\n\n sage: for cl in x.__class__.mro(): print(cl)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class\'>\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits.Element\'>\n <class \'sage.rings.integer.IntegerWrapper\'>\n <class \'sage.rings.integer.Integer\'>\n <class \'sage.structure.element.EuclideanDomainElement\'>\n <class \'sage.structure.element.PrincipalIdealDomainElement\'>\n <class \'sage.structure.element.DedekindDomainElement\'>\n <class \'sage.structure.element.IntegralDomainElement\'>\n <class \'sage.structure.element.CommutativeRingElement\'>\n <class \'sage.structure.element.RingElement\'>\n <class \'sage.structure.element.ModuleElement\'>\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Abstract.Element\'>\n <class \'sage.structure.element.Element\'>\n <class \'sage.structure.sage_object.SageObject\'>\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 <... \'object\'>\n\n FIXME: Objects.element_class is not very meaningful ...\n\n\n TESTS::\n\n sage: TestSuite(Sets()).run()\n\n '
def super_categories(self):
'\n We include SetsWithPartialMaps between Sets and Objects so that we\n can define morphisms between sets that are only partially defined.\n This is also to have the Homset constructor not complain that\n SetsWithPartialMaps is not a supercategory of Fields, for example.\n\n EXAMPLES::\n\n sage: Sets().super_categories()\n [Category of sets with partial maps]\n '
return [SetsWithPartialMaps()]
def _call_(self, X, enumerated_set=False):
'\n Construct an object in this category from the data ``X``.\n\n INPUT:\n\n - ``X`` -- an object to be converted into a set\n\n - ``enumerated_set`` -- if set to ``True`` and the input is either a\n Python tuple or a Python list then the output will be a finite\n enumerated set.\n\n EXAMPLES::\n\n sage: Sets()(ZZ)\n Integer Ring\n sage: Sets()([1, 2, 3])\n {1, 2, 3}\n\n sage: S = Sets()([1, 2, 3]); S.category()\n Category of finite enumerated sets\n sage: S = Sets()([1, 2, 3], enumerated_set=True); S.category()\n Category of facade finite enumerated sets\n\n .. NOTE::\n\n Using ``Sets()(A)`` used to implement some sort of forgetful functor\n into the ``Sets()`` category. This feature has been removed, because\n it was not consistent with the semantic of :meth:`Category.__call__`.\n Proper forgetful functors will eventually be implemented, with\n another syntax.\n '
if (enumerated_set and (type(X) in (tuple, list, range))):
from sage.categories.enumerated_sets import EnumeratedSets
return EnumeratedSets()(X)
from sage.sets.set import Set
return Set(X)
def example(self, choice=None):
'\n Return examples of objects of ``Sets()``, as per\n :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Sets().example()\n Set of prime numbers (basic implementation)\n\n sage: Sets().example("inherits")\n Set of prime numbers\n\n sage: Sets().example("facade")\n Set of prime numbers (facade implementation)\n\n sage: Sets().example("wrapper")\n Set of prime numbers (wrapper implementation)\n '
if (choice is None):
from sage.categories.examples.sets_cat import PrimeNumbers
return PrimeNumbers()
elif (choice == 'inherits'):
from sage.categories.examples.sets_cat import PrimeNumbers_Inherits
return PrimeNumbers_Inherits()
elif (choice == 'facade'):
from sage.categories.examples.sets_cat import PrimeNumbers_Facade
return PrimeNumbers_Facade()
elif (choice == 'wrapper'):
from sage.categories.examples.sets_cat import PrimeNumbers_Wrapper
return PrimeNumbers_Wrapper()
else:
raise ValueError('unknown choice')
class SubcategoryMethods():
@cached_method
def CartesianProducts(self):
'\n Return the full subcategory of the objects of ``self``\n constructed as Cartesian products.\n\n .. SEEALSO::\n\n - :class:`.cartesian_product.CartesianProductFunctor`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`\n\n EXAMPLES::\n\n sage: Sets().CartesianProducts()\n Category of Cartesian products of sets\n sage: Semigroups().CartesianProducts()\n Category of Cartesian products of semigroups\n sage: EuclideanDomains().CartesianProducts()\n Category of Cartesian products of commutative rings\n '
return CartesianProductsCategory.category_of(self)
@cached_method
def Subquotients(self):
'\n Return the full subcategory of the objects of ``self``\n constructed as subquotients.\n\n Given a concrete category ``self == As()`` (i.e. a subcategory\n of ``Sets()``), ``As().Subquotients()`` returns the category\n of objects of ``As()`` endowed with a distinguished\n description as subquotient of some other object of ``As()``.\n\n EXAMPLES::\n\n sage: Monoids().Subquotients()\n Category of subquotients of monoids\n\n A parent `A` in ``As()`` is further in\n ``As().Subquotients()`` if there is a distinguished parent\n `B` in ``As()``, called the *ambient set*, a subobject\n `B\'` of `B`, and a pair of maps:\n\n .. MATH::\n\n l: A \\to B\' \\text{ and } r: B\' \\to A\n\n called respectively the *lifting map* and *retract map*\n such that `r \\circ l` is the identity of `A` and `r` is a\n morphism in ``As()``.\n\n .. TODO:: Draw the typical commutative diagram.\n\n It follows that, for each operation `op` of the category,\n we have some property like:\n\n .. MATH::\n\n op_A(e) = r(op_B(l(e))), \\text{ for all } e\\in A\n\n This allows for implementing the operations on `A` from\n those on `B`.\n\n The two most common use cases are:\n\n - *homomorphic images* (or *quotients*), when `B\'=B`,\n `r` is an homomorphism from `B` to `A` (typically a\n canonical quotient map), and `l` a section of it (not\n necessarily a homomorphism); see :meth:`Quotients`;\n\n - *subobjects* (up to an isomorphism), when `l` is an\n embedding from `A` into `B`; in this case, `B\'` is\n typically isomorphic to `A` through the inverse\n isomorphisms `r` and `l`; see :meth:`Subobjects`;\n\n .. NOTE::\n\n - The usual definition of "subquotient"\n (:wikipedia:`Subquotient`) does not involve the\n lifting map `l`. This map is required in Sage\'s\n context to make the definition constructive. It is\n only used in computations and does not affect their\n results. This is relatively harmless since the\n category is a concrete category (i.e., its objects\n are sets and its morphisms are set maps).\n\n - In mathematics, especially in the context of\n quotients, the retract map `r` is often referred to\n as a *projection map* instead.\n\n - Since `B\'` is not specified explicitly, it is\n possible to abuse the framework with situations\n where `B\'` is not quite a subobject and `r` not\n quite a morphism, as long as the lifting and retract\n maps can be used as above to compute all the\n operations in `A`. Use at your own risk!\n\n Assumptions:\n\n - For any category ``As()``, ``As().Subquotients()`` is a\n subcategory of ``As()``.\n\n Example: a subquotient of a group is a group (e.g., a left\n or right quotient of a group by a non-normal subgroup is\n not in this category).\n\n - This construction is covariant: if ``As()`` is a\n subcategory of ``Bs()``, then ``As().Subquotients()`` is a\n subcategory of ``Bs().Subquotients()``.\n\n Example: if `A` is a subquotient of `B` in the category of\n groups, then it is also a subquotient of `B` in the category\n of monoids.\n\n - If the user (or a program) calls ``As().Subquotients()``,\n then it is assumed that subquotients are well defined in\n this category. This is not checked, and probably never will\n be. Note that, if a category ``As()`` does not specify\n anything about its subquotients, then its subquotient\n category looks like this::\n\n sage: EuclideanDomains().Subquotients()\n Join of Category of euclidean domains\n and Category of subquotients of monoids\n\n Interface: the ambient set `B` of `A` is given by\n ``A.ambient()``. The subset `B\'` needs not be specified, so\n the retract map is handled as a partial map from `B` to `A`.\n\n The lifting and retract map are implemented\n respectively as methods ``A.lift(a)`` and ``A.retract(b)``.\n As a shorthand for the former, one can use alternatively\n ``a.lift()``::\n\n sage: S = Semigroups().Subquotients().example(); S\n An example of a (sub)quotient semigroup: a quotient of the left zero semigroup\n sage: S.ambient()\n An example of a semigroup: the left zero semigroup\n sage: S(3).lift().parent()\n An example of a semigroup: the left zero semigroup\n sage: S(3) * S(1) == S.retract( S(3).lift() * S(1).lift() )\n True\n\n See ``S?`` for more.\n\n .. TODO:: use a more interesting example, like `\\ZZ/n\\ZZ`.\n\n .. SEEALSO::\n\n - :meth:`Quotients`, :meth:`Subobjects`, :meth:`IsomorphicObjects`\n - :class:`.subquotients.SubquotientsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`\n\n TESTS::\n\n sage: TestSuite(Sets().Subquotients()).run()\n '
return SubquotientsCategory.category_of(self)
@cached_method
def Quotients(self):
'\n Return the full subcategory of the objects of ``self``\n constructed as quotients.\n\n Given a concrete category ``As()`` (i.e. a subcategory of\n ``Sets()``), ``As().Quotients()`` returns the category of\n objects of ``As()`` endowed with a distinguished\n description as quotient (in fact homomorphic image) of\n some other object of ``As()``.\n\n Implementing an object of ``As().Quotients()`` is done in\n the same way as for ``As().Subquotients()``; namely by\n providing an ambient space and a lift and a retract\n map. See :meth:`Subquotients` for detailed instructions.\n\n .. SEEALSO::\n\n - :meth:`Subquotients` for background\n - :class:`.quotients.QuotientsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`\n\n EXAMPLES::\n\n sage: C = Semigroups().Quotients(); C\n Category of quotients of semigroups\n sage: C.super_categories()\n [Category of subquotients of semigroups, Category of quotients of sets]\n sage: C.all_super_categories()\n [Category of quotients of semigroups,\n Category of subquotients of semigroups,\n Category of semigroups,\n Category of subquotients of magmas,\n Category of magmas,\n Category of quotients of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n The caller is responsible for checking that the given category\n admits a well defined category of quotients::\n\n sage: EuclideanDomains().Quotients()\n Join of Category of euclidean domains\n and Category of subquotients of monoids\n and Category of quotients of semigroups\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
return QuotientsCategory.category_of(self)
@cached_method
def Subobjects(self):
'\n Return the full subcategory of the objects of ``self``\n constructed as subobjects.\n\n Given a concrete category ``As()`` (i.e. a subcategory of\n ``Sets()``), ``As().Subobjects()`` returns the category of\n objects of ``As()`` endowed with a distinguished embedding\n into some other object of ``As()``.\n\n Implementing an object of ``As().Subobjects()`` is done in\n the same way as for ``As().Subquotients()``; namely by\n providing an ambient space and a lift and a retract\n map. In the case of a trivial embedding, the two maps will\n typically be identity maps that just change the parent of\n their argument. See :meth:`Subquotients` for detailed\n instructions.\n\n .. SEEALSO::\n\n - :meth:`Subquotients` for background\n - :class:`.subobjects.SubobjectsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`\n\n EXAMPLES::\n\n sage: C = Sets().Subobjects(); C\n Category of subobjects of sets\n\n sage: C.super_categories()\n [Category of subquotients of sets]\n\n sage: C.all_super_categories()\n [Category of subobjects of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n Unless something specific about subobjects is implemented for this\n category, one actually gets an optimized super category::\n\n sage: C = Semigroups().Subobjects(); C\n Join of Category of subquotients of semigroups\n and Category of subobjects of sets\n\n The caller is responsible for checking that the given category\n admits a well defined category of subobjects.\n\n TESTS::\n\n sage: Semigroups().Subobjects().is_subcategory(Semigroups().Subquotients())\n True\n sage: TestSuite(C).run()\n\n '
return SubobjectsCategory.category_of(self)
@cached_method
def IsomorphicObjects(self):
'\n Return the full subcategory of the objects of ``self``\n constructed by isomorphism.\n\n Given a concrete category ``As()`` (i.e. a subcategory of\n ``Sets()``), ``As().IsomorphicObjects()`` returns the category of\n objects of ``As()`` endowed with a distinguished description as\n the image of some other object of ``As()`` by an isomorphism in\n this category.\n\n See :meth:`Subquotients` for background.\n\n EXAMPLES:\n\n In the following example, `A` is defined as the image by `x\\mapsto\n x^2` of the finite set `B = \\{1,2,3\\}`::\n\n sage: A = FiniteEnumeratedSets().IsomorphicObjects().example(); A\n The image by some isomorphism of An example of a finite enumerated set: {1,2,3}\n\n Since `B` is a finite enumerated set, so is `A`::\n\n sage: A in FiniteEnumeratedSets()\n True\n sage: A.cardinality()\n 3\n sage: A.list()\n [1, 4, 9]\n\n The isomorphism from `B` to `A` is available as::\n\n sage: A.retract(3)\n 9\n\n and its inverse as::\n\n sage: A.lift(9)\n 3\n\n It often is natural to declare those morphisms as coercions so\n that one can do ``A(b)`` and ``B(a)`` to go back and forth between\n `A` and `B` (TODO: refer to a category example where the maps are\n declared as a coercion). This is not done by default. Indeed, in\n many cases one only wants to transport part of the structure of\n `B` to `A`. Assume for example, that one wants to construct the\n set of integers `B=ZZ`, endowed with ``max`` as addition, and\n ``+`` as multiplication instead of the usual ``+`` and ``*``. One\n can construct `A` as isomorphic to `B` as an infinite enumerated\n set. However `A` is *not* isomorphic to `B` as a ring; for\n example, for `a\\in A` and `a\\in B`, the expressions `a+A(b)` and\n `B(a)+b` give completely different results; hence we would not want\n the expression `a+b` to be implicitly resolved to any one of above\n two, as the coercion mechanism would do.\n\n Coercions also cannot be used with facade parents (see\n :class:`Sets.Facade`) like in the example above.\n\n\n We now look at a category of isomorphic objects::\n\n sage: C = Sets().IsomorphicObjects(); C\n Category of isomorphic objects of sets\n\n sage: C.super_categories()\n [Category of subobjects of sets, Category of quotients of sets]\n\n sage: C.all_super_categories()\n [Category of isomorphic objects of sets,\n Category of subobjects of sets,\n Category of quotients of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n Unless something specific about isomorphic objects is implemented\n for this category, one actually get an optimized super category::\n\n sage: C = Semigroups().IsomorphicObjects(); C\n Join of Category of quotients of semigroups\n and Category of isomorphic objects of sets\n\n .. SEEALSO::\n\n - :meth:`Subquotients` for background\n - :class:`.isomorphic_objects.IsomorphicObjectsCategory`\n - :class:`~.covariant_functorial_construction.RegressiveCovariantFunctorialConstruction`\n\n TESTS::\n\n sage: TestSuite(Sets().IsomorphicObjects()).run()\n '
return IsomorphicObjectsCategory.category_of(self)
@cached_method
def Topological(self):
'\n Return the subcategory of the topological objects of ``self``.\n\n TESTS::\n\n sage: TestSuite(Sets().Topological()).run()\n '
from sage.categories.topological_spaces import TopologicalSpacesCategory
return TopologicalSpacesCategory.category_of(self)
@cached_method
def Metric(self):
'\n Return the subcategory of the metric objects of ``self``.\n\n TESTS::\n\n sage: TestSuite(Sets().Metric()).run()\n '
from sage.categories.metric_spaces import MetricSpacesCategory
return MetricSpacesCategory.category_of(self)
@cached_method
def Algebras(self, base_ring):
'\n Return the category of objects constructed as algebras of\n objects of ``self`` over ``base_ring``.\n\n INPUT:\n\n - ``base_ring`` -- a ring\n\n See :meth:`Sets.ParentMethods.algebra` for the precise\n meaning in Sage of the *algebra of an object*.\n\n EXAMPLES::\n\n sage: Monoids().Algebras(QQ)\n Category of monoid algebras over Rational Field\n\n sage: Groups().Algebras(QQ)\n Category of group algebras over Rational Field\n\n sage: AdditiveMagmas().AdditiveAssociative().Algebras(QQ)\n Category of additive semigroup algebras over Rational Field\n\n sage: Monoids().Algebras(Rings())\n Category of monoid algebras over Category of rings\n\n .. SEEALSO::\n\n - :class:`.algebra_functor.AlgebrasCategory`\n - :class:`~.covariant_functorial_construction.CovariantFunctorialConstruction`\n\n TESTS::\n\n sage: TestSuite(Groups().Finite().Algebras(QQ)).run()\n '
from sage.categories.rings import Rings
assert ((base_ring in Rings()) or (isinstance(base_ring, Category) and base_ring.is_subcategory(Rings())))
return AlgebrasCategory.category_of(self, base_ring)
@cached_method
def Finite(self):
"\n Return the full subcategory of the finite objects of ``self``.\n\n EXAMPLES::\n\n sage: Sets().Finite()\n Category of finite sets\n sage: Rings().Finite()\n Category of finite rings\n\n TESTS::\n\n sage: TestSuite(Sets().Finite()).run()\n sage: Rings().Finite.__module__\n 'sage.categories.sets_cat'\n "
return self._with_axiom('Finite')
@cached_method
def Infinite(self):
"\n Return the full subcategory of the infinite objects of ``self``.\n\n EXAMPLES::\n\n sage: Sets().Infinite()\n Category of infinite sets\n sage: Rings().Infinite()\n Category of infinite rings\n\n TESTS::\n\n sage: TestSuite(Sets().Infinite()).run()\n sage: Rings().Infinite.__module__\n 'sage.categories.sets_cat'\n "
return self._with_axiom('Infinite')
@cached_method
def Enumerated(self):
"\n Return the full subcategory of the enumerated objects of ``self``.\n\n An enumerated object can be iterated to get its elements.\n\n EXAMPLES::\n\n sage: Sets().Enumerated()\n Category of enumerated sets\n sage: Rings().Finite().Enumerated()\n Category of finite enumerated rings\n sage: Rings().Infinite().Enumerated()\n Category of infinite enumerated rings\n\n TESTS::\n\n sage: TestSuite(Sets().Enumerated()).run()\n sage: Rings().Enumerated.__module__\n 'sage.categories.sets_cat'\n "
return self._with_axiom('Enumerated')
def Facade(self):
'\n Return the full subcategory of the facade objects of ``self``.\n\n .. _facade-sets:\n\n .. RUBRIC:: What is a facade set?\n\n Recall that, in Sage, :ref:`sets are modelled by *parents*\n <category-primer-parents-elements-categories>`, and their\n elements know which distinguished set they belong to. For\n example, the ring of integers `\\ZZ` is modelled by the\n parent :obj:`ZZ`, and integers know that they belong to\n this set::\n\n sage: ZZ\n Integer Ring\n sage: 42.parent()\n Integer Ring\n\n Sometimes, it is convenient to represent the elements of a\n parent ``P`` by elements of some other parent. For\n example, the elements of the set of prime numbers are\n represented by plain integers::\n\n sage: Primes()\n Set of all prime numbers: 2, 3, 5, 7, ...\n sage: p = Primes().an_element(); p\n 43\n sage: p.parent()\n Integer Ring\n\n In this case, ``P`` is called a *facade set*.\n\n This feature is advertised through the category of `P`::\n\n sage: Primes().category()\n Category of facade infinite enumerated sets\n sage: Sets().Facade()\n Category of facade sets\n\n Typical use cases include modeling a subset of an existing\n parent::\n\n sage: Set([4,6,9]) # random\n {4, 6, 9}\n sage: Sets().Facade().example()\n An example of facade set: the monoid of positive integers\n\n or the union of several parents::\n\n sage: Sets().Facade().example("union")\n An example of a facade set: the integers completed by +-infinity\n\n or endowing an existing parent with more (or less!)\n structure::\n\n sage: Posets().example("facade")\n An example of a facade poset: the positive integers ordered by divisibility\n\n Let us investigate in detail a close variant of this last\n example: let `P` be set of divisors of `12` partially\n ordered by divisibility. There are two options for\n representing its elements:\n\n 1. as plain integers::\n\n sage: P = Poset((divisors(12), attrcall("divides")), facade=True) # needs sage.graphs\n\n 2. as integers, modified to be aware that their parent is `P`::\n\n sage: Q = Poset((divisors(12), attrcall("divides")), facade=False) # needs sage.graphs\n\n The advantage of option 1. is that one needs not do\n conversions back and forth between `P` and `\\ZZ`. The\n disadvantage is that this introduces an ambiguity when\n writing `2 < 3`: does this compare `2` and `3` w.r.t. the\n natural order on integers or w.r.t. divisibility?::\n\n sage: 2 < 3\n True\n\n To raise this ambiguity, one needs to explicitly specify\n the underlying poset as in `2 <_P 3`::\n\n sage: P = Posets().example("facade")\n sage: P.lt(2,3)\n False\n\n On the other hand, with option 2. and once constructed,\n the elements know unambiguously how to compare\n themselves::\n\n sage: Q(2) < Q(3) # needs sage.graphs\n False\n sage: Q(2) < Q(6) # needs sage.graphs\n True\n\n Beware that ``P(2)`` is still the integer `2`. Therefore\n ``P(2) < P(3)`` still compares `2` and `3` as integers!::\n\n sage: P(2) < P(3)\n True\n\n In short `P` being a facade parent is one of the programmatic\n counterparts (with e.g. coercions) of the usual mathematical idiom:\n "for ease of notation, we identify an element of `P` with the\n corresponding integer". Too many identifications lead to\n confusion; the lack thereof leads to heavy, if not obfuscated,\n notations. Finding the right balance is an art, and even though\n there are common guidelines, it is ultimately up to the writer to\n choose which identifications to do. This is no different in code.\n\n .. SEEALSO::\n\n The following examples illustrate various ways to\n implement subsets like the set of prime numbers; look\n at their code for details::\n\n sage: Sets().example("facade")\n Set of prime numbers (facade implementation)\n sage: Sets().example("inherits")\n Set of prime numbers\n sage: Sets().example("wrapper")\n Set of prime numbers (wrapper implementation)\n\n .. RUBRIC:: Specifications\n\n A parent which is a facade must either:\n\n - call :meth:`Parent.__init__` using the ``facade`` parameter to\n specify a parent, or tuple thereof.\n - overload the method :meth:`~Sets.Facade.ParentMethods.facade_for`.\n\n .. NOTE::\n\n The concept of facade parents was originally introduced\n in the computer algebra system MuPAD.\n\n TESTS:\n\n Check that multiple categories initialisation\n works (:trac:`13801`)::\n\n sage: class A(Parent):\n ....: def __init__(self):\n ....: Parent.__init__(self, category=(FiniteEnumeratedSets(),Monoids()), facade=True)\n sage: a = A()\n\n sage: Posets().Facade()\n Category of facade posets\n sage: Posets().Facade().Finite() is Posets().Finite().Facade()\n True\n '
return self._with_axiom('Facade')
class ParentMethods():
@lazy_attribute
def _element_constructor_(self):
"\n TESTS::\n\n sage: S = Sets().example()\n sage: S._element_constructor_(17)\n 17\n sage: S(17) # indirect doctest\n 17\n\n sage: A = FreeModule(QQ, 3) # needs sage.modules\n sage: A.element_class # needs sage.modules\n <class 'sage.modules.vector_rational_dense.Vector_rational_dense'>\n sage: A._element_constructor_ # needs sage.modules\n <bound method FreeModule_ambient_field._element_constructor_\n of Vector space of dimension 3 over Rational Field>\n\n sage: B = SymmetricGroup(3).algebra(ZZ) # needs sage.groups sage.modules\n sage: B.element_class # needs sage.groups sage.modules\n <...SymmetricGroupAlgebra_n_with_category.element_class'>\n sage: B._element_constructor_ # needs sage.groups sage.modules\n <bound method SymmetricGroupAlgebra_n._element_constructor_\n of Symmetric group algebra of order 3 over Integer Ring>\n "
if hasattr(self, 'element_class'):
return self._element_constructor_from_element_class
else:
return NotImplemented
def _element_constructor_from_element_class(self, *args, **keywords):
'\n The default constructor for elements of this parent ``self``.\n\n Among other things, it is called upon ``self(data)`` when\n the coercion model did not find a way to coerce ``data`` into\n this parent.\n\n This default implementation for\n :meth:`_element_constructor_` calls the constructor of the\n element class, passing ``self`` as first argument.\n\n EXAMPLES::\n\n sage: S = Sets().example("inherits")\n sage: s = S._element_constructor_from_element_class(17); s\n 17\n sage: type(s)\n <class \'sage.categories.examples.sets_cat.PrimeNumbers_Inherits_with_category.element_class\'>\n '
return self.element_class(self, *args, **keywords)
def is_parent_of(self, element):
'\n Return whether ``self`` is the parent of ``element``.\n\n INPUT:\n\n - ``element`` -- any object\n\n EXAMPLES::\n\n sage: S = ZZ\n sage: S.is_parent_of(1)\n True\n sage: S.is_parent_of(2/1)\n False\n\n This method differs from :meth:`__contains__` because it\n does not attempt any coercion::\n\n sage: 2/1 in S, S.is_parent_of(2/1)\n (True, False)\n sage: int(1) in S, S.is_parent_of(int(1))\n (True, False)\n '
from sage.structure.element import parent
return (parent(element) == self)
@abstract_method
def __contains__(self, x):
'\n Test whether the set ``self`` contains the object ``x``.\n\n All parents in the category ``Sets()`` should implement this method.\n\n EXAMPLES::\n\n sage: P = Sets().example(); P\n Set of prime numbers (basic implementation)\n sage: 12 in P\n False\n sage: P(5) in P\n True\n '
@cached_method
def an_element(self):
"\n Return a (preferably typical) element of this parent.\n\n This is used both for illustration and testing purposes. If the\n set ``self`` is empty, :meth:`an_element` should raise the exception\n :class:`EmptySetError`.\n\n This default implementation calls :meth:`_an_element_` and\n caches the result. Any parent should implement either\n :meth:`an_element` or :meth:`_an_element_`.\n\n EXAMPLES::\n\n sage: CDF.an_element() # needs sage.rings.complex_double\n 1.0*I\n sage: ZZ[['t']].an_element()\n t\n "
return self._an_element_()
def _test_an_element(self, **options):
'\n Run generic tests on the method :meth:`.an_element`.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_an_element()\n\n Let us now write a broken :meth:`.an_element` method::\n\n sage: from sage.categories.examples.sets_cat import PrimeNumbers\n sage: class CCls(PrimeNumbers):\n ....: def an_element(self):\n ....: return 18\n sage: CC = CCls()\n sage: CC._test_an_element()\n Traceback (most recent call last):\n ...\n AssertionError: self.an_element() is not in self\n\n TESTS::\n\n sage: FiniteEnumeratedSet([])._test_an_element()\n '
tester = self._tester(**options)
try:
an_element = self.an_element()
except EmptySetError:
return
tester.assertIn(an_element, self, 'self.an_element() is not in self')
if self.is_parent_of(an_element):
tester.assertEqual(self(an_element), an_element, 'element construction is not idempotent')
else:
try:
rebuilt_element = self(an_element)
except NotImplementedError:
tester.info("\n The set doesn't seems to implement __call__; skipping test of construction idempotency")
else:
tester.assertEqual(rebuilt_element, an_element, 'element construction is not idempotent')
def _test_elements(self, tester=None, **options):
'\n Run generic tests on element(s) of ``self``.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_elements(verbose = True)\n <BLANKLINE>\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 <BLANKLINE>\n\n Debugging tip: in case of failure of this test, run instead::\n\n sage: TestSuite(C.an_element()).run()\n\n Let us now implement a parent whose elements cannot be pickled::\n\n sage: from sage.categories.examples.sets_cat import PrimeNumbers\n sage: class Bla(SageObject): pass\n sage: class CCls(PrimeNumbers):\n ....: def an_element(self):\n ....: return Bla()\n sage: CC = CCls()\n sage: CC._test_elements()\n Failure in _test_pickling:\n ...\n The following tests failed: _test_pickling\n '
is_sub_testsuite = (tester is not None)
tester = self._tester(tester=tester, **options)
try:
an_element = self.an_element()
except EmptySetError:
return
tester.info('\n Running the test suite of self.an_element()')
TestSuite(an_element).run(verbose=tester._verbose, prefix=(tester._prefix + ' '), raise_on_failure=is_sub_testsuite)
tester.info((tester._prefix + ' '), newline=False)
def _test_elements_eq_reflexive(self, **options):
'\n Run generic tests on the equality of elements.\n\n Test that ``==`` is reflexive.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_elements_eq_reflexive()\n\n We try a non-reflexive equality::\n\n sage: P = Sets().example("wrapper")\n sage: P._test_elements_eq_reflexive() # needs sage.libs.pari\n sage: eq = P.element_class.__eq__\n\n sage: P.element_class.__eq__ = (lambda x, y:\n ....: False if eq(x, P(47)) and eq(y, P(47)) else eq(x, y))\n sage: P._test_elements_eq_reflexive() # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n AssertionError: 47 != 47\n\n We restore ``P.element_class`` in a proper state for further tests::\n\n sage: P.element_class.__eq__ = eq\n\n '
tester = self._tester(**options)
S = (list(tester.some_elements()) + [None, 0])
for x in S:
tester.assertEqual(x, x)
def _test_elements_eq_symmetric(self, **options):
'\n Run generic tests on the equality of elements.\n\n This tests that ``==`` is symmetric.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_elements_eq_symmetric()\n\n We test a non symmetric equality::\n\n sage: P = Sets().example("wrapper")\n sage: P._test_elements_eq_symmetric() # needs sage.libs.pari\n sage: eq = P.element_class.__eq__\n\n sage: def non_sym_eq(x, y):\n ....: if not y in P: return False\n ....: elif eq(x, P(47)) and eq(y, P(53)): return True\n ....: else: return eq(x, y)\n sage: P.element_class.__eq__ = non_sym_eq\n sage: P._test_elements_eq_symmetric() # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n AssertionError: non symmetric equality: 47 == 53 but 53 != 47\n\n We restore ``P.element_class`` in a proper state for further tests::\n\n sage: P.element_class.__eq__ = eq\n\n '
tester = self._tester(**options)
S = (list(tester.some_elements()) + [None, 0])
from sage.misc.misc import some_tuples
for (x, y) in some_tuples(S, 2, tester._max_runs):
tester.assertEqual((x == y), (y == x), (LazyFormat('non symmetric equality: %s but %s') % (print_compare(x, y), print_compare(y, x))))
def _test_elements_eq_transitive(self, **options):
'\n Run generic tests on the equality of elements.\n\n Test that ``==`` is transitive.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_elements_eq_transitive()\n\n We test a non transitive equality::\n\n sage: R = Zp(3) # needs sage.rings.padics\n sage: test = raw_getattr(Sets().ParentMethods, "_test_elements_eq_transitive")\n sage: test(R, elements=[R(3,2), R(3,1), R(0)]) # needs sage.rings.padics\n Traceback (most recent call last):\n ...\n AssertionError: non transitive equality:\n 3 + O(3^2) == O(3) and O(3) == 0 but 3 + O(3^2) != 0\n\n '
tester = self._tester(**options)
S = list(tester.some_elements())
n = max(tester._max_runs, 8)
if (((len(S) + 2) ** 3) <= n):
S = (list(S) + [None, 0])
else:
from random import sample
from sage.rings.integer import Integer
S = (sample(S, (Integer(n).nth_root(3, truncate_mode=1)[0] - 2)) + [None, 0])
for x in S:
for y in S:
if (not (x == y)):
continue
for z in S:
if (not (y == z)):
continue
tester.assertEqual(x, z, (LazyFormat('non transitive equality:\n%s and %s but %s') % (print_compare(x, y), print_compare(y, z), print_compare(x, z))))
def _test_elements_neq(self, **options):
'\n Run generic tests on the equality of elements.\n\n Test that ``==`` and ``!=`` are consistent.\n\n See also: :class:`TestSuite`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_elements_neq()\n\n We try a broken inequality::\n\n sage: P = Sets().example("wrapper")\n sage: P._test_elements_neq() # needs sage.libs.pari\n sage: ne = P.element_class.__ne__\n sage: eq = P.element_class.__eq__\n\n sage: P.element_class.__ne__ = lambda x, y: False\n sage: P._test_elements_neq() # needs sage.libs.pari\n Traceback (most recent call last):\n ...\n AssertionError: __eq__ and __ne__ inconsistency:\n 47 == 53 returns False but 47 != 53 returns False\n\n sage: P.element_class.__ne__ = lambda x, y: not(x == y)\n\n We restore ``P.element_class`` in a proper state for further tests::\n\n sage: P.element_class.__ne__ = ne\n sage: P.element_class.__eq__ = eq\n '
tester = self._tester(**options)
S = (list(tester.some_elements()) + [None, 0])
from sage.misc.misc import some_tuples
for (x, y) in some_tuples(S, 2, tester._max_runs):
tester.assertNotEqual((x == y), (x != y), (LazyFormat('__eq__ and __ne__ inconsistency:\n %s == %s returns %s but %s != %s returns %s') % (x, y, (x == y), x, y, (x != y))))
def some_elements(self):
'\n Return a list (or iterable) of elements of ``self``.\n\n This is typically used for running generic tests\n (see :class:`TestSuite`).\n\n This default implementation calls :meth:`.an_element`.\n\n EXAMPLES::\n\n sage: S = Sets().example(); S\n Set of prime numbers (basic implementation)\n sage: S.an_element()\n 47\n sage: S.some_elements()\n [47]\n sage: S = Set([])\n sage: list(S.some_elements())\n []\n\n This method should return an iterable, *not* an iterator.\n '
try:
return [self.an_element()]
except EmptySetError:
return []
def _test_some_elements(self, **options):
'\n Run generic tests on the method :meth:`.some_elements`.\n\n .. SEEALSO:: :class:`TestSuite`\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_some_elements()\n\n Let us now write a broken :meth:`.some_elements` method::\n\n sage: from sage.categories.examples.sets_cat import *\n sage: class CCls(PrimeNumbers):\n ....: def some_elements(self):\n ....: return [self(17), 32]\n sage: CC = CCls()\n sage: CC._test_some_elements()\n Traceback (most recent call last):\n ...\n AssertionError: the object 32 in self.some_elements() is not in self\n '
tester = self._tester(**options)
elements = self.some_elements()
for x in elements:
tester.assertIn(x, self, (LazyFormat('the object %s in self.some_elements() is not in self') % (x,)))
def _test_cardinality(self, **options):
"\n Run generic test on the method :meth:`.cardinality`.\n\n EXAMPLES::\n\n sage: C = Sets().example()\n sage: C._test_cardinality()\n\n Let us now write a broken :meth:`cardinality` method::\n\n sage: from sage.categories.examples.sets_cat import *\n sage: class CCls(PrimeNumbers):\n ....: def cardinality(self):\n ....: return int(5)\n sage: CC = CCls()\n sage: CC._test_cardinality()\n Traceback (most recent call last):\n ...\n AssertionError: the output of the method cardinality must either\n be a Sage integer or infinity. Not <... 'int'>.\n "
try:
cardinality = self.cardinality()
except (AttributeError, NotImplementedError):
return
from sage.structure.element import parent
from sage.rings.infinity import Infinity
from sage.rings.integer_ring import ZZ
tester = self._tester(**options)
tester.assertTrue(((cardinality is Infinity) or (parent(cardinality) is ZZ)), 'the output of the method cardinality must either be a Sage integer or infinity. Not {}.'.format(type(cardinality)))
def construction(self):
"\n Return a pair ``(functor, parent)`` such that\n ``functor(parent)`` returns ``self``. If ``self`` does\n not have a functorial construction, return ``None``.\n\n EXAMPLES::\n\n sage: QQ.construction()\n (FractionField, Integer Ring)\n sage: f, R = QQ['x'].construction()\n sage: f\n Poly[x]\n sage: R\n Rational Field\n sage: f(R)\n Univariate Polynomial Ring in x over Rational Field\n "
return None
def _test_construction(self, **options):
"\n Test that the construction returned by ``self`` really yields ``self``.\n\n :meth:`construction` either returns None or a pair ``(F, O)``,\n and if it returns the latter, then it is supposed that ``F(O) == self``.\n The test verifies this assumption.\n\n EXAMPLES:\n\n We create a parent that returns a wrong construction (its construction\n returns the rational field rather than the parent itself)::\n\n sage: class P(Parent):\n ....: Element = ElementWrapper\n ....: def __init__(self):\n ....: Parent.__init__(self, category=Sets())\n ....: def __eq__(self, P):\n ....: return type(self) == type(P)\n ....: def __hash__(self):\n ....: return hash(type(self))\n ....: def construction(self):\n ....: return sage.categories.pushout.FractionField(), ZZ\n ....:\n sage: import __main__\n sage: __main__.P = P # this is to enable pickling in doctests\n sage: p = P()\n sage: F,R = p.construction()\n sage: F(R)\n Rational Field\n sage: TestSuite(p).run()\n Failure in _test_construction:\n Traceback (most recent call last):\n ...\n AssertionError: the object's construction does not recreate this object\n ...\n The following tests failed: _test_construction\n\n If the parent returns the empty construction, the test will not complain::\n\n sage: ZZ.construction() is None\n True\n sage: TestSuite(ZZ).run() # indirect doctest\n\n If the construction works as expected, the test will not complain\n either::\n\n sage: F,R = QQ.construction()\n sage: F(R) == QQ\n True\n sage: TestSuite(QQ).run() # indirect doctest\n\n "
tester = self._tester(**options)
FO = self.construction()
if (FO is None):
return
tester.assertEqual(FO[0](FO[1]), self, "the object's construction does not recreate this object")
CartesianProduct = CartesianProduct
def cartesian_product(*parents, **kwargs):
'\n Return the Cartesian product of the parents.\n\n INPUT:\n\n - ``parents`` -- a list (or other iterable) of parents.\n\n - ``category`` -- (default: ``None``) the category the\n Cartesian product belongs to. If ``None`` is passed,\n then\n :meth:`~sage.categories.covariant_functorial_construction.CovariantFactorialConstruction.category_from_parents`\n is used to determine the category.\n\n - ``extra_category`` -- (default: ``None``) a category\n that is added to the Cartesian product in addition\n to the categories obtained from the parents.\n\n - other keyword arguments will passed on to the class used\n for this Cartesian product (see also\n :class:`~sage.sets.cartesian_product.CartesianProduct`).\n\n OUTPUT:\n\n The Cartesian product.\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.cartesian_product(A, A) # needs sage.combinat sage.modules\n A (+) A (+) A\n sage: ZZ.cartesian_product(GF(2), FiniteEnumeratedSet([1,2,3]))\n The Cartesian product of (Integer Ring,\n Finite Field of size 2, {1, 2, 3})\n\n sage: C = ZZ.cartesian_product(A); C # needs sage.combinat sage.modules\n The Cartesian product of (Integer Ring, A)\n\n TESTS::\n\n sage: type(C) # needs sage.combinat sage.modules\n <class \'sage.sets.cartesian_product.CartesianProduct_with_category\'>\n sage: C.category() # needs sage.combinat sage.modules\n Join of Category of rings and ...\n and Category of Cartesian products of commutative additive groups\n\n ::\n\n sage: cartesian_product([ZZ, ZZ], category=Sets()).category()\n Category of sets\n sage: cartesian_product([ZZ, ZZ]).category()\n Join of\n Category of Cartesian products of commutative rings and\n Category of Cartesian products of metric spaces and\n Category of Cartesian products of enumerated sets\n sage: cartesian_product([ZZ, ZZ], extra_category=Posets()).category()\n Join of\n Category of Cartesian products of commutative rings and\n Category of posets and\n Category of Cartesian products of metric spaces and\n Category of Cartesian products of enumerated sets\n '
category = kwargs.pop('category', None)
extra_category = kwargs.pop('extra_category', None)
category = (category or cartesian_product.category_from_parents(parents))
if extra_category:
if isinstance(category, (list, tuple)):
category = (tuple(category) + (extra_category,))
else:
category = (category & extra_category)
return parents[0].CartesianProduct(parents, category=category, **kwargs)
def algebra(self, base_ring, category=None, **kwds):
"\n Return the algebra of ``self`` over ``base_ring``.\n\n INPUT:\n\n - ``self`` -- a parent `S`\n - ``base_ring`` -- a ring `K`\n - ``category`` -- a super category of the category\n of `S`, or ``None``\n\n This returns the space of formal linear combinations of\n elements of `S` with coefficients in `K`, endowed with\n whatever structure can be induced from that of `S`.\n See the documentation of\n :mod:`sage.categories.algebra_functor` for details.\n\n EXAMPLES:\n\n If `S` is a :class:`group <Groups>`, the result is its\n group algebra `KS`::\n\n sage: # needs sage.groups sage.modules\n sage: S = DihedralGroup(4); S\n Dihedral group of order 8 as a permutation group\n sage: A = S.algebra(QQ); A\n Algebra of Dihedral group of order 8 as a permutation group\n over Rational Field\n sage: A.category()\n Category of finite group algebras over Rational Field\n sage: a = A.an_element(); a\n () + (1,3) + 2*(1,3)(2,4) + 3*(1,4,3,2)\n\n This space is endowed with an algebra structure, obtained\n by extending by bilinearity the multiplication of `G` to a\n multiplication on `RG`::\n\n sage: a * a # needs sage.groups sage.modules\n 6*() + 4*(2,4) + 3*(1,2)(3,4) + 12*(1,2,3,4) + 2*(1,3)\n + 13*(1,3)(2,4) + 6*(1,4,3,2) + 3*(1,4)(2,3)\n\n If `S` is a :class:`monoid <Monoids>`, the result is its\n monoid algebra `KS`::\n\n sage: S = Monoids().example(); S\n An example of a monoid:\n the free monoid generated by ('a', 'b', 'c', 'd')\n sage: A = S.algebra(QQ); A # needs sage.modules\n Algebra of\n An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd')\n over Rational Field\n sage: A.category() # needs sage.modules\n Category of monoid algebras over Rational Field\n\n Similarly, we can construct algebras for additive magmas,\n monoids, and groups.\n\n One may specify for which category one takes the algebra;\n here we build the algebra of the additive group `GF_3`::\n\n sage: # needs sage.modules\n sage: from sage.categories.additive_groups import AdditiveGroups\n sage: S = GF(7)\n sage: A = S.algebra(QQ, category=AdditiveGroups()); A\n Algebra of Finite Field of size 7 over Rational Field\n sage: A.category()\n Category of finite dimensional additive group algebras\n over Rational Field\n sage: a = A(S(1))\n sage: a\n 1\n sage: 1 + a * a * a\n 0 + 3\n\n Note that the ``category`` keyword needs to be fed with\n the structure on `S` to be used, not the induced structure\n on the result.\n "
if (category is None):
category = self.category()
from sage.categories.semigroups import Semigroups
from sage.categories.commutative_additive_semigroups import CommutativeAdditiveSemigroups
if (category.is_subcategory(Semigroups()) and category.is_subcategory(CommutativeAdditiveSemigroups())):
raise TypeError(' `S = {}` is both an additive and a multiplicative semigroup.\nConstructing its algebra is ambiguous.\nPlease use, e.g., S.algebra(QQ, category=Semigroups())'.format(self))
from sage.categories.groups import Groups
from sage.categories.additive_groups import AdditiveGroups
from sage.algebras.group_algebra import GroupAlgebra_class
algebra_category = category.Algebras(base_ring)
if (category.is_subcategory(Groups()) or category.is_subcategory(AdditiveGroups())):
from sage.categories.modules_with_basis import ModulesWithBasis
if (self not in ModulesWithBasis):
if ('prefix' not in kwds):
kwds['prefix'] = ''
if ('bracket' not in kwds):
kwds['bracket'] = False
result = GroupAlgebra_class(base_ring, self, category=algebra_category, **kwds)
result.__doc__ = Sets.ParentMethods.algebra.__doc__
return result
def _sympy_(self):
'\n Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``.\n\n The default implementation creates an instance of\n :class:`~sage.interfaces.sympy_wrapper`.\n\n EXAMPLES::\n\n sage: # needs sympy\n sage: F = FiniteEnumeratedSets().example(); F\n An example of a finite enumerated set: {1,2,3}\n sage: sF = F._sympy_(); sF\n SageSet(An example of a finite enumerated set: {1,2,3})\n sage: sF.is_finite_set\n True\n sage: bool(sF)\n True\n sage: len(sF)\n 3\n sage: list(sF)\n [1, 2, 3]\n sage: from sympy import FiniteSet\n sage: FiniteSet.fromiter(sF) # random - this output is sympy >= 1.9\n FiniteSet(1, 2, 3)\n\n sage: RR._sympy_().is_finite_set # needs sympy\n False\n\n sage: F = Family([1, 2])\n sage: F is Family([1, 2])\n False\n sage: sF = F._sympy_(); sF # needs sympy\n SageSet(Family (1, 2))\n sage: sF._sage_() is F # needs sympy\n True\n '
from sage.interfaces.sympy_wrapper import SageSet
from sage.interfaces.sympy import sympy_init
sympy_init()
return SageSet(self)
class ElementMethods():
_dummy_attribute = None
def cartesian_product(*elements):
'\n Return the Cartesian product of its arguments, as an element of\n the Cartesian 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.cartesian_product(b, c) # needs sage.combinat sage.modules\n B[(0, word: a)] + B[(1, word: b)] + B[(2, word: c)]\n\n FIXME: is this a policy that we want to enforce on all parents?\n '
from sage.structure.element import parent, Element
assert all((isinstance(element, Element) for element in elements))
parents = [parent(element) for element in elements]
return cartesian_product(parents)._cartesian_product_of_elements(elements)
class MorphismMethods():
@abstract_method(optional=True)
def __invert__(self):
'\n Return the inverse morphism, or raise an error.\n\n The error may either state that the morphism is not\n invertible, or that Sage cannot invert it.\n\n EXAMPLES::\n\n sage: i = End(QQ).identity(); i\n Identity endomorphism of Rational Field\n sage: i.__invert__()\n Identity endomorphism of Rational Field\n\n This method is meant to be used with the Python inversion\n operator `~`::\n\n sage: ~i\n Identity endomorphism of Rational Field\n\n We now try to inverse a couple of morphisms defined by a matrix::\n\n sage: H = End(QQ^2) # needs sage.modules\n sage: phi = H(matrix([[1,1], [0,1]])); phi # needs sage.modules\n Vector space morphism represented by the matrix:\n [1 1]\n [0 1]\n Domain: Vector space of dimension 2 over Rational Field\n Codomain: Vector space of dimension 2 over Rational Field\n sage: ~phi # needs sage.modules\n Vector space morphism represented by the matrix:\n [ 1 -1]\n [ 0 1]\n Domain: Vector space of dimension 2 over Rational Field\n Codomain: Vector space of dimension 2 over Rational Field\n\n sage: phi = H(matrix([[1,1], [1,1]])) # needs sage.modules\n sage: ~phi # needs sage.modules\n Traceback (most recent call last):\n ...\n ZeroDivisionError: matrix morphism not invertible\n\n .. NOTE::\n\n This is an optional method. A default implementation\n raising :class:`NotImplementedError` could be provided instead.\n '
def is_injective(self):
'\n Return whether this map is injective.\n\n EXAMPLES::\n\n sage: f = ZZ.hom(GF(3)); f\n Natural morphism:\n From: Integer Ring\n To: Finite Field of size 3\n sage: f.is_injective()\n False\n '
if (self.domain().cardinality() <= 1):
return True
if (self.domain().cardinality() > self.codomain().cardinality()):
return False
raise NotImplementedError
def image(self, domain_subset=None):
'\n Return the image of the domain or of ``domain_subset``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat\n sage: P = Partitions(6)\n sage: H = Hom(P, ZZ)\n sage: f = H(ZZ.sum)\n sage: X = f.image() # needs sage.libs.flint\n sage: list(X) # needs sage.libs.flint\n [6]\n '
D = self.domain()
if (D is None):
raise ValueError('this map became defunct by garbage collection')
if ((domain_subset is None) or (domain_subset == D)):
try:
if self.is_surjective():
return D
except NotImplementedError:
pass
domain_subset = D
from sage.sets.set import Set_base
from sage.sets.image_set import ImageSubobject, ImageSet
if isinstance(domain_subset, Set_base):
cls = ImageSet
else:
cls = ImageSubobject
return cls(self, domain_subset)
Enumerated = LazyImport('sage.categories.enumerated_sets', 'EnumeratedSets', at_startup=True)
Finite = LazyImport('sage.categories.finite_sets', 'FiniteSets', at_startup=True)
Topological = LazyImport('sage.categories.topological_spaces', 'TopologicalSpaces', 'Topological', at_startup=True)
Metric = LazyImport('sage.categories.metric_spaces', 'MetricSpaces', 'Metric', at_startup=True)
from sage.categories.facade_sets import FacadeSets as Facade
class Infinite(CategoryWithAxiom):
class ParentMethods():
def is_finite(self):
'\n Return whether this set is finite.\n\n Since this set is infinite this always returns ``False``.\n\n EXAMPLES::\n\n sage: C = InfiniteEnumeratedSets().example()\n sage: C.is_finite()\n False\n\n TESTS::\n\n sage: C.is_finite.__func__ is sage.categories.sets_cat.Sets.Infinite.ParentMethods.is_finite\n True\n '
return False
def is_empty(self):
'\n Return whether this set is empty.\n\n Since this set is infinite this always returns ``False``.\n\n EXAMPLES::\n\n sage: C = InfiniteEnumeratedSets().example()\n sage: C.is_empty()\n False\n '
return False
def cardinality(self):
'\n Count the elements of the enumerated set.\n\n EXAMPLES::\n\n sage: NN = InfiniteEnumeratedSets().example()\n sage: NN.cardinality()\n +Infinity\n '
from sage.rings.infinity import infinity
return infinity
class Subquotients(SubquotientsCategory):
'\n A category for subquotients of sets.\n\n .. SEEALSO:: :meth:`Sets().Subquotients`\n\n EXAMPLES::\n\n sage: Sets().Subquotients()\n Category of subquotients of sets\n sage: Sets().Subquotients().all_super_categories()\n [Category of subquotients of sets, Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
class ParentMethods():
def _repr_(self):
"\n EXAMPLES::\n\n sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup\n sage: S = IncompleteSubquotientSemigroup()\n sage: S._repr_()\n 'A subquotient of An example of a semigroup: the left zero semigroup'\n "
return ('A subquotient of %s' % self.ambient())
@abstract_method
def ambient(self):
'\n Return the ambient space for ``self``.\n\n EXAMPLES::\n\n sage: Semigroups().Subquotients().example().ambient()\n An example of a semigroup: the left zero semigroup\n\n .. SEEALSO::\n\n :meth:`Sets.SubcategoryMethods.Subquotients` for the\n specifications and :meth:`.lift` and :meth:`.retract`.\n '
@abstract_method
def lift(self, x):
'\n Lift `x` to the ambient space for ``self``.\n\n INPUT:\n\n - ``x`` -- an element of ``self``\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: s = S.an_element()\n sage: s, s.parent()\n (42, An example of a (sub)quotient semigroup:\n a quotient of the left zero semigroup)\n sage: S.lift(s), S.lift(s).parent()\n (42, An example of a semigroup: the left zero semigroup)\n sage: s.lift(), s.lift().parent()\n (42, An example of a semigroup: the left zero semigroup)\n\n .. SEEALSO::\n\n :class:`Sets.SubcategoryMethods.Subquotients` for\n the specifications, :meth:`.ambient`, :meth:`.retract`,\n and also :meth:`Sets.Subquotients.ElementMethods.lift`.\n '
@abstract_method
def retract(self, x):
'\n Retract ``x`` to ``self``.\n\n INPUT:\n\n - ``x`` -- an element of the ambient space for ``self``\n\n .. SEEALSO::\n\n :class:`Sets.SubcategoryMethods.Subquotients` for\n the specifications, :meth:`.ambient`, :meth:`.retract`,\n and also :meth:`Sets.Subquotients.ElementMethods.retract`.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: s = S.ambient().an_element()\n sage: s, s.parent()\n (42, An example of a semigroup: the left zero semigroup)\n sage: S.retract(s), S.retract(s).parent()\n (42, An example of a (sub)quotient semigroup:\n a quotient of the left zero semigroup)\n '
class ElementMethods():
def lift(self):
'\n Lift ``self`` to the ambient space for its parent.\n\n EXAMPLES::\n\n sage: S = Semigroups().Subquotients().example()\n sage: s = S.an_element()\n sage: s, s.parent()\n (42, An example of a (sub)quotient semigroup:\n a quotient of the left zero semigroup)\n sage: S.lift(s), S.lift(s).parent()\n (42, An example of a semigroup: the left zero semigroup)\n sage: s.lift(), s.lift().parent()\n (42, An example of a semigroup: the left zero semigroup)\n '
return self.parent().lift(self)
class Quotients(QuotientsCategory):
'\n A category for quotients of sets.\n\n .. SEEALSO:: :meth:`Sets().Quotients`\n\n EXAMPLES::\n\n sage: Sets().Quotients()\n Category of quotients of sets\n sage: Sets().Quotients().all_super_categories()\n [Category of quotients of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
class ParentMethods():
def _repr_(self):
"\n EXAMPLES::\n\n sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup\n sage: S = IncompleteSubquotientSemigroup(category=Semigroups().Quotients())\n sage: S._repr_()\n 'A quotient of An example of a semigroup: the left zero semigroup'\n "
return 'A quotient of {}'.format(self.ambient())
def _an_element_(self):
'\n Return an element of ``self``, as per\n :meth:`Sets.ParentMethods.an_element`\n\n EXAMPLES::\n\n sage: S = FiniteEnumeratedSets().IsomorphicObjects().example()\n sage: S.an_element() # indirect doctest\n 1\n '
return self.retract(self.ambient().an_element())
class Subobjects(SubobjectsCategory):
'\n A category for subobjects of sets.\n\n .. SEEALSO:: :meth:`Sets().Subobjects`\n\n EXAMPLES::\n\n sage: Sets().Subobjects()\n Category of subobjects of sets\n sage: Sets().Subobjects().all_super_categories()\n [Category of subobjects of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
class ParentMethods():
def _repr_(self):
"\n EXAMPLES::\n\n sage: from sage.categories.examples.semigroups import IncompleteSubquotientSemigroup\n sage: S = IncompleteSubquotientSemigroup(category=Semigroups().Subobjects())\n sage: S._repr_()\n 'A subobject of An example of a semigroup: the left zero semigroup'\n "
return 'A subobject of {}'.format(self.ambient())
class IsomorphicObjects(IsomorphicObjectsCategory):
'\n A category for isomorphic objects of sets.\n\n EXAMPLES::\n\n sage: Sets().IsomorphicObjects()\n Category of isomorphic objects of sets\n sage: Sets().IsomorphicObjects().all_super_categories()\n [Category of isomorphic objects of sets,\n Category of subobjects of sets, Category of quotients of sets,\n Category of subquotients of sets,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n '
class ParentMethods():
def _repr_(self):
"\n EXAMPLES::\n\n sage: S = FiniteEnumeratedSets().IsomorphicObjects().example()\n sage: S._repr_()\n 'The image by some isomorphism of An example of a finite enumerated set: {1,2,3}'\n "
return ('The image by some isomorphism of %s' % self.ambient())
class CartesianProducts(CartesianProductsCategory):
'\n EXAMPLES::\n\n sage: C = Sets().CartesianProducts().example()\n sage: C\n The Cartesian product of (Set of prime numbers (basic implementation),\n An example of an infinite enumerated set: the non negative integers,\n An example of a finite enumerated set: {1,2,3})\n sage: C.category()\n Category of Cartesian products of sets\n sage: C.categories()\n [Category of Cartesian products of sets, Category of sets,\n Category of sets with partial maps,\n Category of objects]\n sage: TestSuite(C).run()\n '
def extra_super_categories(self):
'\n A Cartesian product of sets is a set.\n\n EXAMPLES::\n\n sage: Sets().CartesianProducts().extra_super_categories()\n [Category of sets]\n sage: Sets().CartesianProducts().super_categories()\n [Category of sets]\n '
return [Sets()]
def example(self):
'\n EXAMPLES::\n\n sage: Sets().CartesianProducts().example()\n The Cartesian product of (Set of prime numbers (basic implementation),\n An example of an infinite enumerated set: the non negative integers,\n An example of a finite enumerated set: {1,2,3})\n '
from .finite_enumerated_sets import FiniteEnumeratedSets
from .infinite_enumerated_sets import InfiniteEnumeratedSets
from .cartesian_product import cartesian_product
S1 = Sets().example()
S2 = InfiniteEnumeratedSets().example()
S3 = FiniteEnumeratedSets().example()
return cartesian_product([S1, S2, S3])
class ParentMethods():
def __iter__(self):
'\n Return an iterator for the elements of this Cartesian product.\n\n If all factors (except possibly the first factor) are known to be finite,\n it uses the lexicographic order.\n\n Otherwise, the iterator enumerates the elements in increasing\n order of sum-of-ranks, refined by the reverse lexicographic order\n (see :func:`~sage.misc.mrange.cantor_product`).\n\n EXAMPLES:\n\n Sets are intrinsically unordered::\n\n sage: for x,y in cartesian_product([Set([1,2]), Set([\'a\',\'b\'])]): # random\n ....: print((x, y))\n (1, \'b\')\n (1, \'a\')\n (2, \'b\')\n (2, \'a\')\n\n sage: A = FiniteEnumeratedSets()(["a", "b"])\n sage: B = FiniteEnumeratedSets().example(); B\n An example of a finite enumerated set: {1,2,3}\n sage: C = cartesian_product([A, B, A]); C\n The Cartesian product of ({\'a\', \'b\'}, An example of a finite enumerated set: {1,2,3}, {\'a\', \'b\'})\n sage: C in FiniteEnumeratedSets()\n True\n sage: list(C)\n [(\'a\', 1, \'a\'), (\'a\', 1, \'b\'), (\'a\', 2, \'a\'), (\'a\', 2, \'b\'), (\'a\', 3, \'a\'), (\'a\', 3, \'b\'),\n (\'b\', 1, \'a\'), (\'b\', 1, \'b\'), (\'b\', 2, \'a\'), (\'b\', 2, \'b\'), (\'b\', 3, \'a\'), (\'b\', 3, \'b\')]\n sage: C.__iter__.__module__\n \'sage.categories.sets_cat\'\n\n sage: F22 = GF(2).cartesian_product(GF(2))\n sage: list(F22)\n [(0, 0), (0, 1), (1, 0), (1, 1)]\n\n sage: # needs sage.combinat\n sage: C = cartesian_product([Permutations(10)]*4)\n sage: it = iter(C)\n sage: next(it)\n ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n sage: next(it)\n ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [1, 2, 3, 4, 5, 6, 7, 8, 10, 9])\n\n When all factors (except possibly the first factor) are known to be finite, it\n uses the lexicographic order::\n\n sage: it = iter(cartesian_product([ZZ, GF(2)]))\n sage: [next(it) for _ in range(10)]\n [(0, 0), (0, 1),\n (1, 0), (1, 1),\n (-1, 0), (-1, 1),\n (2, 0), (2, 1),\n (-2, 0), (-2, 1)]\n\n When other factors are infinite (or not known to be finite), it enumerates\n the elements in increasing order of sum-of-ranks::\n\n sage: NN = NonNegativeIntegers()\n sage: it = iter(cartesian_product([NN, NN]))\n sage: [next(it) for _ in range(10)]\n [(0, 0),\n (1, 0), (0, 1),\n (2, 0), (1, 1), (0, 2),\n (3, 0), (2, 1), (1, 2), (0, 3)]\n\n An example with the first factor finite, the second infinite::\n\n sage: it = iter(cartesian_product([GF(2), ZZ]))\n sage: [next(it) for _ in range(11)]\n [(0, 0),\n (1, 0), (0, 1),\n (1, 1), (0, -1),\n (1, -1), (0, 2),\n (1, 2), (0, -2),\n (1, -2), (0, 3)]\n\n .. NOTE::\n\n Here it would be faster to use :func:`itertools.product` for sets\n of small size. But the latter expands all factor in memory!\n So we can not reasonably use it in general.\n\n ALGORITHM:\n\n The lexicographic enumeration follows Recipe 19.9 in the Python Cookbook\n by Alex Martelli and David Ascher.\n '
factors = list(self.cartesian_factors())
if any(((f not in Sets().Finite()) for f in factors[1:])):
from sage.misc.mrange import cantor_product
for t in cantor_product(*factors):
(yield self._cartesian_product_of_elements(t))
return
wheels = [iter(f) for f in factors]
try:
digits = [next(it) for it in wheels]
except StopIteration:
return
while True:
(yield self._cartesian_product_of_elements(digits))
for i in range((len(digits) - 1), (- 1), (- 1)):
try:
digits[i] = next(wheels[i])
break
except StopIteration:
wheels[i] = iter(factors[i])
try:
digits[i] = next(wheels[i])
except StopIteration:
return
else:
break
@cached_method
def an_element(self):
'\n EXAMPLES::\n\n sage: C = Sets().CartesianProducts().example(); C\n The Cartesian product of (Set of prime numbers (basic implementation),\n An example of an infinite enumerated set: the non negative integers,\n An example of a finite enumerated set: {1,2,3})\n sage: C.an_element()\n (47, 42, 1)\n '
return self._cartesian_product_of_elements((s.an_element() for s in self._sets))
def is_empty(self):
'\n Return whether this set is empty.\n\n EXAMPLES::\n\n\n sage: S1 = FiniteEnumeratedSet([1,2,3])\n sage: S2 = Set([])\n sage: cartesian_product([S1,ZZ]).is_empty()\n False\n sage: cartesian_product([S1,S2,S1]).is_empty()\n True\n '
return any((c.is_empty() for c in self.cartesian_factors()))
def is_finite(self):
'\n Return whether this set is finite.\n\n EXAMPLES::\n\n sage: E = FiniteEnumeratedSet([1,2,3])\n sage: C = cartesian_product([E, SymmetricGroup(4)]) # needs sage.groups\n sage: C.is_finite() # needs sage.groups\n True\n\n sage: cartesian_product([ZZ,ZZ]).is_finite()\n False\n sage: cartesian_product([ZZ, Set(), ZZ]).is_finite()\n True\n '
f = self.cartesian_factors()
try:
test = any((c.is_empty() for c in f))
except (AttributeError, NotImplementedError):
pass
else:
if test:
return test
return all((c.is_finite() for c in f))
def cardinality(self):
'\n Return the cardinality of self.\n\n EXAMPLES::\n\n sage: E = FiniteEnumeratedSet([1,2,3])\n sage: C = cartesian_product([E, SymmetricGroup(4)]) # needs sage.groups\n sage: C.cardinality() # needs sage.groups\n 72\n\n sage: E = FiniteEnumeratedSet([])\n sage: C = cartesian_product([E, ZZ, QQ])\n sage: C.cardinality()\n 0\n\n sage: C = cartesian_product([ZZ, QQ])\n sage: C.cardinality()\n +Infinity\n\n sage: cartesian_product([GF(5), Permutations(10)]).cardinality()\n 18144000\n sage: cartesian_product([GF(71)]*20).cardinality() == 71**20\n True\n '
f = self.cartesian_factors()
try:
is_empty = any((c.is_empty() for c in f))
except (AttributeError, NotImplementedError):
pass
else:
if is_empty:
from sage.rings.integer_ring import ZZ
return ZZ.zero()
elif any(((c in Sets().Infinite()) for c in f)):
from sage.rings.infinity import Infinity
return Infinity
from sage.misc.misc_c import prod
return prod((c.cardinality() for c in f))
def random_element(self, *args):
'\n Return a random element of this Cartesian product.\n\n The extra arguments are passed down to each of the\n factors of the Cartesian product.\n\n EXAMPLES::\n\n sage: C = cartesian_product([Permutations(10)]*5)\n sage: C.random_element() # random\n ([2, 9, 4, 7, 1, 8, 6, 10, 5, 3],\n [8, 6, 5, 7, 1, 4, 9, 3, 10, 2],\n [5, 10, 3, 8, 2, 9, 1, 4, 7, 6],\n [9, 6, 10, 3, 2, 1, 5, 8, 7, 4],\n [8, 5, 2, 9, 10, 3, 7, 1, 4, 6])\n\n sage: C = cartesian_product([ZZ]*10)\n sage: c1 = C.random_element()\n sage: c1 # random\n (3, 1, 4, 1, 1, -3, 0, -4, -17, 2)\n sage: c2 = C.random_element(4,7)\n sage: c2 # random\n (6, 5, 6, 4, 5, 6, 6, 4, 5, 5)\n sage: all(4 <= i < 7 for i in c2)\n True\n '
return self._cartesian_product_of_elements((c.random_element(*args) for c in self.cartesian_factors()))
@abstract_method
def _sets_keys(self):
'\n Return the indices of the Cartesian factors of ``self``.\n\n EXAMPLES::\n\n sage: cartesian_product([QQ, ZZ, ZZ])._sets_keys()\n {0, 1, 2}\n '
@abstract_method
def cartesian_factors(self):
'\n Return the Cartesian factors of ``self``.\n\n EXAMPLES::\n\n sage: cartesian_product([QQ, ZZ, ZZ]).cartesian_factors()\n (Rational Field, Integer Ring, Integer Ring)\n '
@abstract_method
def cartesian_projection(self, i):
'\n Return the natural projection onto the `i`-th\n Cartesian factor of ``self``.\n\n INPUT:\n\n - ``i`` -- the index of a Cartesian factor of ``self``\n\n EXAMPLES::\n\n sage: C = Sets().CartesianProducts().example(); C\n The Cartesian product of (Set of prime numbers (basic implementation),\n An example of an infinite enumerated set: the non negative integers,\n An example of a finite enumerated set: {1,2,3})\n sage: x = C.an_element(); x\n (47, 42, 1)\n sage: pi = C.cartesian_projection(1)\n sage: pi(x)\n 42\n '
def construction(self):
'\n The construction functor and the list of Cartesian factors.\n\n EXAMPLES::\n\n sage: C = cartesian_product([QQ, ZZ, ZZ])\n sage: C.construction()\n (The cartesian_product functorial construction,\n (Rational Field, Integer Ring, Integer Ring))\n '
return (cartesian_product, self.cartesian_factors())
@abstract_method
def _cartesian_product_of_elements(self, elements):
'\n Return the Cartesian product of the given ``elements``.\n\n This method should accept any iterable.\n\n INPUT:\n\n - ``elements`` -- an iterable (e.g. a tuple or a list) of\n elements of each Cartesian factor of ``self``\n\n EXAMPLES::\n\n sage: S1 = Sets().example()\n sage: S2 = InfiniteEnumeratedSets().example()\n sage: X = [S2, S1, S2]\n sage: C = cartesian_product(X)\n sage: C._cartesian_product_of_elements([S.an_element() for S in X])\n (42, 47, 42)\n sage: C._cartesian_product_of_elements(S.an_element() for S in X)\n (42, 47, 42)\n '
def _sympy_(self):
'\n Return a SymPy ``ProductSet`` corresponding to ``self``.\n\n EXAMPLES::\n\n sage: ZZ3 = cartesian_product([ZZ, ZZ, ZZ])\n sage: sZZ3 = ZZ3._sympy_(); sZZ3 # needs sympy\n ProductSet(Integers, Integers, Integers)\n sage: (1, 2, 3) in sZZ3 # needs sympy\n True\n '
from sympy import ProductSet
from sage.interfaces.sympy import sympy_init
sympy_init()
return ProductSet(*self.cartesian_factors())
class ElementMethods():
def cartesian_projection(self, i):
'\n Return the projection of ``self`` onto the `i`-th\n factor of the Cartesian product.\n\n INPUT:\n\n - ``i`` -- the index of a factor of the Cartesian product\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: S = cartesian_product([F, G])\n sage: x = (S.monomial((0,4)) + 2 * S.monomial((0,5))\n ....: + 3 * S.monomial((1,6)))\n sage: x.cartesian_projection(0)\n B[4] + 2*B[5]\n sage: x.cartesian_projection(1)\n 3*B[6]\n '
return self.parent().cartesian_projection(i)(self)
def cartesian_factors(self):
'\n Return the Cartesian factors of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: F = CombinatorialFreeModule(ZZ, [4,5]); F.rename("F")\n sage: G = CombinatorialFreeModule(ZZ, [4,6]); G.rename("G")\n sage: H = CombinatorialFreeModule(ZZ, [4,7]); H.rename("H")\n sage: S = cartesian_product([F, G, H])\n sage: x = (S.monomial((0,4)) + 2 * S.monomial((0,5))\n ....: + 3 * S.monomial((1,6)) + 4 * S.monomial((2,4))\n ....: + 5 * S.monomial((2,7)))\n sage: x.cartesian_factors()\n (B[4] + 2*B[5], 3*B[6], 4*B[4] + 5*B[7])\n sage: [s.parent() for s in x.cartesian_factors()]\n [F, G, H]\n sage: S.zero().cartesian_factors()\n (0, 0, 0)\n sage: [s.parent() for s in S.zero().cartesian_factors()]\n [F, G, H]\n '
return tuple((self.cartesian_projection(i) for i in self.parent()._sets_keys()))
class Algebras(AlgebrasCategory):
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Sets().Algebras(ZZ).super_categories()\n [Category of modules with basis over Integer Ring]\n\n sage: Sets().Algebras(QQ).extra_super_categories()\n [Category of vector spaces with basis over Rational Field]\n\n sage: Sets().example().algebra(ZZ).categories() # needs sage.modules\n [Category of set algebras over Integer Ring,\n Category of modules with basis over Integer Ring,\n ...\n Category of objects]\n\n '
from sage.categories.modules_with_basis import ModulesWithBasis
return [ModulesWithBasis(self.base_ring())]
class ParentMethods():
def construction(self):
"\n Return the functorial construction of ``self``.\n\n EXAMPLES::\n\n sage: A = GroupAlgebra(KleinFourGroup(), QQ) # needs sage.groups sage.modules\n sage: F, arg = A.construction(); F, arg # needs sage.groups sage.modules\n (GroupAlgebraFunctor, Rational Field)\n sage: F(arg) is A # needs sage.groups sage.modules\n True\n\n This also works for structures such as monoid algebras (see\n :trac:`27937`)::\n\n sage: A = FreeAbelianMonoid('x,y').algebra(QQ) # needs sage.groups sage.modules\n sage: F, arg = A.construction(); F, arg # needs sage.groups sage.modules\n (The algebra functorial construction,\n Free abelian monoid on 2 generators (x, y))\n sage: F(arg) is A # needs sage.groups sage.modules\n True\n "
from sage.categories.algebra_functor import GroupAlgebraFunctor, AlgebraFunctor
try:
group = self.group()
except AttributeError:
return (AlgebraFunctor(self.base_ring()), self.basis().keys())
return (GroupAlgebraFunctor(group), self.base_ring())
def _repr_(self):
'\n Return the string representation of `self`.\n\n EXAMPLES::\n\n sage: # needs sage.groups sage.modules\n sage: A = Groups().example().algebra(QQ); A\n Algebra of General Linear Group of degree 4 over Rational Field\n over Rational Field\n sage: A._name = "foo"\n sage: A\n foo over Rational Field\n sage: A = KleinFourGroup().algebra(ZZ)\n sage: A\n Algebra of The Klein 4 group of order 4, as a permutation group\n over Integer Ring\n '
if hasattr(self, '_name'):
return (self._name + ' over {}'.format(self.base_ring()))
else:
return 'Algebra of {} over {}'.format(self.basis().keys(), self.base_ring())
class WithRealizations(WithRealizationsCategory):
def extra_super_categories(self):
'\n A set with multiple realizations is a facade parent.\n\n EXAMPLES::\n\n sage: Sets().WithRealizations().extra_super_categories()\n [Category of facade sets]\n sage: Sets().WithRealizations().super_categories()\n [Category of facade sets]\n '
return [Sets().Facade()]
def example(self, base_ring=None, set=None):
'\n Return an example of set with multiple realizations, as\n per :meth:`Category.example`.\n\n EXAMPLES::\n\n sage: Sets().WithRealizations().example() # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n\n sage: Sets().WithRealizations().example(ZZ, Set([1,2])) # needs sage.modules\n The subset algebra of {1, 2} over Integer Ring\n '
from sage.rings.rational_field import QQ
from sage.sets.set import Set
if (base_ring is None):
base_ring = QQ
if (set is None):
set = Set([1, 2, 3])
from sage.categories.examples.with_realizations import SubsetAlgebra
return SubsetAlgebra(base_ring, set)
class ParentMethods():
def _test_with_realizations(self, **options):
'\n Test that this parent with realizations is\n properly implemented.\n\n INPUT:\n\n - ``options`` -- any keyword arguments accepted\n by :meth:`_tester`\n\n EXAMPLES::\n\n sage: A = Sets().WithRealizations().example() # needs sage.modules\n sage: A._test_with_realizations() # needs sage.modules\n\n See the documentation for :class:`TestSuite`\n for more information.\n '
tester = self._tester(**options)
for R in self.realizations():
tester.assertIn(R, self.Realizations())
@lazy_attribute
def _realizations(self):
'\n This lazily initializes the attribute\n ``_realizations`` the first time it is needed.\n\n TESTS::\n\n sage: class MyParent(Parent):\n ....: pass\n sage: P = MyParent(category = Sets().WithRealizations())\n sage: P._realizations\n []\n '
return []
def _register_realization(self, realization):
"\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = Sets().WithRealizations().example(QQ['x']); A\n The subset algebra of {1, 2, 3}\n over Univariate Polynomial Ring in x over Rational Field\n sage: class ANewRealizationOfA(CombinatorialFreeModule):\n ....: pass\n sage: category = A.Realizations() & Algebras(QQ['x']).WithBasis()\n sage: R = ANewRealizationOfA(A.base_ring(), A.F().basis().keys(),\n ....: category=category)\n sage: R in A.realizations() # indirect doctest\n True\n\n Note: the test above uses ``QQ[x]`` to not interfer\n with other tests.\n "
assert (realization.realization_of() is self)
self._realizations.append(realization)
def inject_shorthands(self, shorthands=None, verbose=True):
'\n Import standard shorthands into the global namespace.\n\n INPUT:\n\n - ``shorthands`` -- a list (or iterable) of strings (default: ``self._shorthands``)\n or ``"all"`` (for ``self._shorthands_all``)\n - ``verbose`` -- boolean (default ``True``);\n whether to print the defined shorthands\n\n EXAMPLES:\n\n When computing with a set with multiple realizations,\n like :class:`SymmetricFunctions` or\n :class:`~sage.categories.examples.with_realizations.SubsetAlgebra`,\n it is convenient to define shorthands for the various\n realizations, but cumbersome to do it by hand::\n\n sage: S = SymmetricFunctions(ZZ); S # needs sage.combinat sage.modules\n Symmetric Functions over Integer Ring\n sage: s = S.s(); s # needs sage.combinat sage.modules\n Symmetric Functions over Integer Ring in the Schur basis\n sage: e = S.e(); e # needs sage.combinat sage.modules\n Symmetric Functions over Integer Ring in the elementary basis\n\n This method automates the process::\n\n sage: # needs sage.combinat sage.modules\n sage: S.inject_shorthands()\n Defining e as shorthand for\n Symmetric Functions over Integer Ring in the elementary basis\n Defining f as shorthand for\n Symmetric Functions over Integer Ring in the forgotten basis\n Defining h as shorthand for\n Symmetric Functions over Integer Ring in the homogeneous basis\n Defining m as shorthand for\n Symmetric Functions over Integer Ring in the monomial basis\n Defining p as shorthand for\n Symmetric Functions over Integer Ring in the powersum basis\n Defining s as shorthand for\n Symmetric Functions over Integer Ring in the Schur basis\n sage: s[1] + e[2] * p[1,1] + 2*h[3] + m[2,1]\n s[1] - 2*s[1, 1, 1] + s[1, 1, 1, 1] + s[2, 1]\n + 2*s[2, 1, 1] + s[2, 2] + 2*s[3] + s[3, 1]\n sage: e\n Symmetric Functions over Integer Ring in the elementary basis\n sage: p\n Symmetric Functions over Integer Ring in the powersum basis\n sage: s\n Symmetric Functions over Integer Ring in the Schur basis\n\n Sometimes, like for symmetric functions, one can\n request for all shorthands to be defined, including\n less common ones::\n\n sage: S.inject_shorthands("all") # needs sage.combinat sage.modules\n Defining e as shorthand for\n Symmetric Functions over Integer Ring in the elementary basis\n Defining f as shorthand for\n Symmetric Functions over Integer Ring in the forgotten basis\n Defining h as shorthand for\n Symmetric Functions over Integer Ring in the homogeneous basis\n Defining ht as shorthand for\n Symmetric Functions over Integer Ring in the\n induced trivial symmetric group character basis\n Defining m as shorthand for\n Symmetric Functions over Integer Ring in the monomial basis\n Defining o as shorthand for\n Symmetric Functions over Integer Ring in the orthogonal basis\n Defining p as shorthand for\n Symmetric Functions over Integer Ring in the powersum basis\n Defining s as shorthand for\n Symmetric Functions over Integer Ring in the Schur basis\n Defining sp as shorthand for\n Symmetric Functions over Integer Ring in the symplectic basis\n Defining st as shorthand for\n Symmetric Functions over Integer Ring in the\n irreducible symmetric group character basis\n Defining w as shorthand for\n Symmetric Functions over Integer Ring in the Witt basis\n\n The messages can be silenced by setting ``verbose=False``::\n\n sage: # needs sage.combinat sage.modules\n sage: Q = QuasiSymmetricFunctions(ZZ)\n sage: Q.inject_shorthands(verbose=False)\n sage: F[1,2,1] + 5*M[1,3] + F[2]^2\n 5*F[1, 1, 1, 1] - 5*F[1, 1, 2] - 3*F[1, 2, 1] + 6*F[1, 3] +\n 2*F[2, 2] + F[3, 1] + F[4]\n sage: F\n Quasisymmetric functions over the Integer Ring in the\n Fundamental basis\n sage: M\n Quasisymmetric functions over the Integer Ring in the\n Monomial basis\n\n One can also just import a subset of the shorthands::\n\n sage: # needs sage.combinat sage.modules\n sage: SQ = SymmetricFunctions(QQ)\n sage: SQ.inject_shorthands([\'p\', \'s\'], verbose=False)\n sage: p\n Symmetric Functions over Rational Field in the powersum basis\n sage: s\n Symmetric Functions over Rational Field in the Schur basis\n\n Note that ``e`` is left unchanged::\n\n sage: e # needs sage.combinat sage.modules\n Symmetric Functions over Integer Ring in the elementary basis\n\n TESTS::\n\n sage: e == S.e(), h == S.h(), m == S.m(), p == SQ.p(), s == SQ.s() # needs sage.combinat sage.modules\n (True, True, True, True, True)\n '
from sage.misc.misc import inject_variable
if (shorthands == 'all'):
shorthands = getattr(self, '_shorthands_all', None)
if (shorthands is None):
shorthands = getattr(self, '_shorthands', None)
if (shorthands is None):
raise NotImplementedError('no shorthands defined for {}'.format(self))
for shorthand in shorthands:
realization = getattr(self, shorthand)()
if verbose:
print('Defining {} as shorthand for {}'.format(shorthand, realization))
inject_variable(shorthand, realization, warn=False)
@abstract_method(optional=True)
def a_realization(self):
'\n Return a realization of ``self``.\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.a_realization() # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n in the Fundamental basis\n '
def realizations(self):
'\n Return all the realizations of ``self`` that ``self``\n is aware of.\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.realizations() # needs sage.modules\n [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis,\n The subset algebra of {1, 2, 3} over Rational Field in the In basis,\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis]\n\n .. NOTE::\n\n Constructing a parent ``P`` in the category\n ``A.Realizations()`` automatically adds ``P`` to\n this list by calling ``A._register_realization(A)``\n '
return self._realizations
def facade_for(self):
'\n Return the parents ``self`` is a facade for, that is\n the realizations of ``self``\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.facade_for() # needs sage.modules\n [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis,\n The subset algebra of {1, 2, 3} over Rational Field in the In basis,\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis]\n\n sage: # needs sage.combinat sage.modules\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: f = A.F().an_element(); f\n F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}]\n sage: i = A.In().an_element(); i\n In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}]\n sage: o = A.Out().an_element(); o\n Out[{}] + 2*Out[{1}] + 3*Out[{2}] + Out[{1, 2}]\n sage: f in A, i in A, o in A\n (True, True, True)\n '
return self.realizations()
class Realizations(Category_realization_of_parent):
def super_categories(self):
'\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.Realizations().super_categories() # needs sage.modules\n [Category of realizations of sets]\n '
return [Sets().Realizations()]
def _an_element_(self):
'\n Return an element of some realization of ``self``.\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.an_element() # indirect doctest # needs sage.modules\n F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}]\n\n TESTS:\n\n Check that we are consistent no matter which basis is\n created first::\n\n sage: M = posets.BooleanLattice(4).moebius_algebra(QQ) # needs sage.combinat sage.graphs sage.modules\n sage: I = M.I() # needs sage.combinat sage.graphs sage.modules\n sage: M._an_element_() # needs sage.combinat sage.graphs sage.modules\n 2*E[0] + 2*E[1] + 3*E[2]\n '
return self.a_realization().an_element()
def __contains__(self, x):
"\n Test whether ``x`` is in ``self``, that is if it is an\n element of some realization of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = Sets().WithRealizations().example(); A\n The subset algebra of {1, 2, 3} over Rational Field\n sage: A.an_element() in A\n True\n sage: A.In().an_element() in A\n True\n sage: A.F().an_element() in A\n True\n sage: A.Out().an_element() in A\n True\n sage: 1 in A\n True\n sage: QQ['x'].an_element() in A\n False\n "
return any(((x in realization) for realization in self.realizations()))
class Realizations(RealizationsCategory):
class ParentMethods():
def __init_extra__(self):
'\n Register ``self`` as a realization of ``self.realization_of``.\n\n TESTS::\n\n sage: A = Sets().WithRealizations().example() # needs sage.modules\n sage: A.realizations() # indirect doctest # needs sage.modules\n [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis,\n The subset algebra of {1, 2, 3} over Rational Field in the In basis,\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis]\n '
self.realization_of()._register_realization(self)
@cached_method
def realization_of(self):
'\n Return the parent this is a realization of.\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: In = A.In(); In # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: In.realization_of() # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n '
for category in self.categories():
if isinstance(category, Category_realization_of_parent):
return category.base()
def _realization_name(self):
"\n Return the name of this realization.\n\n In this default implementation, this is guessed from\n the name of its class.\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: In = A.In(); In # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: In._realization_name() # needs sage.modules\n 'In'\n "
return self.__class__.__base__.__name__.split('.')[(- 1)]
def _repr_(self):
'\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: In = A.In(); In # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n\n In the example above, :meth:`repr` was overridden by\n the category ``A.Realizations()``. We now add a new\n (fake) realization which is not in\n ``A.Realizations()`` to actually exercise this\n method::\n\n sage: from sage.categories.realizations import Realizations\n sage: class Blah(Parent):\n ....: pass\n sage: C = Sets.WithRealizations.ParentMethods.Realizations(A) # needs sage.modules\n sage: P = Blah(category=C) # needs sage.modules\n sage: P # indirect doctest # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field in the realization Blah\n '
return '{} in the realization {}'.format(self.realization_of(), self._realization_name())
|
class SetsWithGrading(Category):
'\n The category of sets with a grading.\n\n A *set with a grading* is a set `S` equipped with a\n grading by some other set `I` (by default the set `\\NN` of the\n non-negative integers):\n\n .. MATH::\n\n S = \\biguplus_{i\\in I} S_i\n\n where the *graded components* `S_i` are (usually finite)\n sets. The *grading* function maps each element `s` of\n `S` to its *grade* `i`, so that `s\\in S_i`.\n\n From implementation point of view, if the graded set is enumerated then\n each graded component should be enumerated (there is a check in the method\n :meth:`~SetsWithGrading.ParentMethods._test_graded_components`). The\n contrary needs not be true.\n\n To implement this category, a parent must either implement\n :meth:`~SetsWithGrading.ParentMethods.graded_component()` or\n :meth:`~SetsWithGrading.ParentMethods.subset()`. If only\n :meth:`~SetsWithGrading.ParentMethods.subset()` is implemented, the first\n argument must be the grading for compatibility with\n :meth:`~SetsWithGrading.ParentMethods.graded_component()`. Additionally\n either the parent must implement\n :meth:`~SetsWithGrading.ParentMethods.grading()` or its elements must\n implement a method ``grade()``. See the example\n :class:`sage.categories.examples.sets_with_grading.NonNegativeIntegers`.\n\n Finally, if the graded set is enumerated (see\n :class:`~sage.categories.enumerated_sets.EnumeratedSets`) then each graded\n component should be enumerated. The contrary needs not be true.\n\n EXAMPLES:\n\n A typical example of a set with a grading is the set of non-negative\n integers graded by themselves::\n\n sage: N = SetsWithGrading().example(); N\n Non negative integers\n sage: N.category()\n Category of facade infinite sets with grading\n sage: N.grading_set()\n Non negative integers\n\n The *grading function* is given by ``N.grading``::\n\n sage: N.grading(4)\n 4\n\n The graded component `N_i` is the set with one element `i`::\n\n sage: N.graded_component(grade=5)\n {5}\n sage: N.graded_component(grade=42)\n {42}\n\n Here are some information about this category::\n\n sage: SetsWithGrading()\n Category of sets with grading\n sage: SetsWithGrading().super_categories()\n [Category of sets]\n sage: SetsWithGrading().all_super_categories()\n [Category of sets with grading,\n Category of sets,\n Category of sets with partial maps,\n Category of objects]\n\n .. TODO::\n\n - This should be moved to ``Sets().WithGrading()``.\n - Should the grading set be a parameter for this category?\n - Does the enumeration need to be compatible with the grading? Be\n careful that the fact that graded components are allowed to be finite\n or infinite make the answer complicated.\n\n TESTS::\n\n sage: C = SetsWithGrading()\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: SetsWithGrading().super_categories()\n [Category of sets]\n '
return [Sets()]
class ParentMethods():
def _test_graded_components(self, **options):
'\n Test that some graded components of ``self`` are parent with\n initialized category and that the parent has a properly implemented\n ``grading()`` method.\n\n EXAMPLES::\n\n sage: SetsWithGrading().example()._test_graded_components()\n '
tester = self._tester(**options)
for grade in self.grading_set().some_elements():
G = self.graded_component(grade)
if (self in EnumeratedSets()):
tester.assertIn(G, EnumeratedSets())
else:
tester.assertIn(G, Sets())
for elt in G.some_elements():
tester.assertEqual(self.grading(elt), grade)
def grading_set(self):
'\n Return the set ``self`` is graded by. By default, this is\n the set of non-negative integers.\n\n EXAMPLES::\n\n sage: SetsWithGrading().example().grading_set()\n Non negative integers\n '
from sage.sets.non_negative_integers import NonNegativeIntegers
return NonNegativeIntegers()
@abstract_method(optional=True)
def subset(self, *args, **options):
'\n Return the subset of ``self`` described by the given parameters.\n\n .. SEEALSO::\n\n -:meth:`graded_component()`\n\n EXAMPLES::\n\n sage: W = WeightedIntegerVectors([3,2,1]); W # needs sage.combinat\n Integer vectors weighted by [3, 2, 1]\n sage: W.subset(4) # needs sage.combinat\n Integer vectors of 4 weighted by [3, 2, 1]\n '
def graded_component(self, grade):
'\n Return the graded component of ``self`` with grade ``grade``.\n\n The default implementation just calls the method :meth:`subset()`\n with the first argument ``grade``.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example(); N\n Non negative integers\n sage: N.graded_component(3)\n {3}\n '
return self.subset(grade)
def grading(self, elt):
'\n Return the grading of the element ``elt`` of ``self``.\n\n This default implementation calls ``elt.grade()``.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example(); N\n Non negative integers\n sage: N.grading(4)\n 4\n '
return elt.grade()
def generating_series(self):
'\n Default implementation for generating series.\n\n OUTPUT:\n\n A series, indexed by the grading set.\n\n EXAMPLES::\n\n sage: N = SetsWithGrading().example(); N\n Non negative integers\n sage: N.generating_series()\n 1/(-z + 1)\n\n sage: Permutations().generating_series() # needs sage.combinat\n 1 + z + 2*z^2 + 6*z^3 + 24*z^4 + 120*z^5 + 720*z^6 + O(z^7)\n\n .. TODO::\n\n - Very likely, this should always return a lazy power series.\n '
from sage.rings.integer_ring import ZZ
from sage.rings.lazy_series_ring import LazyPowerSeriesRing
from sage.sets.non_negative_integers import NonNegativeIntegers
if isinstance(self.grading_set(), NonNegativeIntegers):
R = LazyPowerSeriesRing(ZZ, names='z')
return R((lambda n: self.graded_component(n).cardinality()))
raise NotImplementedError
|
class SetsWithPartialMaps(Category_singleton):
'\n The category whose objects are sets and whose morphisms are\n maps that are allowed to raise a :class:`ValueError` on some inputs.\n\n This category is equivalent to the category of pointed sets,\n via the equivalence sending an object X to X union {error},\n a morphism f to the morphism of pointed sets that sends x\n to f(x) if f does not raise an error on x, or to error if it\n does.\n\n EXAMPLES::\n\n sage: SetsWithPartialMaps()\n Category of sets with partial maps\n\n sage: SetsWithPartialMaps().super_categories()\n [Category of objects]\n\n TESTS::\n\n sage: TestSuite(SetsWithPartialMaps()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: SetsWithPartialMaps().super_categories()\n [Category of objects]\n '
return [Objects()]
|
class ShephardGroups(Category_singleton):
'\n The category of Shephard groups.\n\n EXAMPLES::\n\n sage: from sage.categories.shephard_groups import ShephardGroups\n sage: C = ShephardGroups(); C\n Category of shephard groups\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.shephard_groups import ShephardGroups\n sage: ShephardGroups().super_categories()\n [Category of finite generalized Coxeter groups]\n '
return [GeneralizedCoxeterGroups().Finite()]
|
class SignedTensorProductFunctor(CovariantFunctorialConstruction):
'\n A singleton class for the signed tensor functor.\n\n This functor takes a collection of graded algebras (possibly with\n basis) and constructs the signed tensor product of those algebras.\n If this algebra is in a subcategory, say that of\n ``Algebras(QQ).Graded()``, it is automatically endowed with\n its natural algebra structure, thanks to the category\n ``Algebras(QQ).Graded().SignedTensorProducts()`` of signed tensor\n products of graded algebras. For elements, it constructs the natural\n tensor product element in the corresponding tensor product of their\n parents.\n\n The signed tensor functor is covariant: if ``A`` is a subcategory\n of ``B``, then ``A.SignedTensorProducts()`` is a subcategory of\n ``B.SignedTensorProducts()`` (see also\n :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`). Hence,\n the role of ``Algebras(QQ).Graded().SignedTensorProducts()`` is solely\n to provide mathematical information and algorithms which are relevant to\n signed tensor product of graded algebras.\n\n Those are implemented in the nested class\n :class:`~sage.categories.algebras.Algebras.SignedTensorProducts`\n of ``Algebras(QQ).Graded()``. This nested class is itself a subclass of\n :class:`~sage.categories.signed_tensor.SignedTensorProductsCategory`.\n\n EXAMPLES::\n\n sage: tensor_signed\n The signed tensor functorial construction\n\n TESTS::\n\n sage: TestSuite(tensor_signed).run()\n '
_functor_name = 'tensor'
_functor_category = 'SignedTensorProducts'
symbol = ' # '
unicode_symbol = f' {unicode_otimes} '
def _repr_(self):
'\n EXAMPLES::\n\n sage: tensor_signed\n The signed tensor functorial construction\n '
return 'The signed tensor functorial construction'
|
class SignedTensorProductsCategory(CovariantConstructionCategory):
"\n An abstract base class for all SignedTensorProducts's categories.\n\n TESTS::\n\n sage: C = AlgebrasWithBasis(QQ).Graded().SignedTensorProducts()\n sage: C\n Category of signed tensor products of graded algebras with basis over Rational Field\n sage: C.base_category()\n Category of graded algebras with basis over Rational Field\n sage: latex(C)\n \\mathbf{SignedTensorProducts}(\\mathbf{GradedAlgebrasWithBasis}(\\mathbf{AlgebrasWithBasis}_{\\Bold{Q}}))\n sage: TestSuite(C).run()\n "
_functor_category = 'SignedTensorProducts'
def SignedTensorProducts(self):
"\n Return the category of signed tensor products of objects of ``self``.\n\n By associativity of signed tensor products, this is ``self`` (a tensor\n product of signed tensor products of `Cat`'s is a tensor product of\n `Cat`'s with the same twisting morphism)\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Graded().SignedTensorProducts().SignedTensorProducts()\n Category of signed tensor products of graded algebras with basis\n over Rational Field\n "
return self
def base(self):
'\n The base of a signed tensor product is the base (usually a ring)\n of the underlying category.\n\n EXAMPLES::\n\n sage: AlgebrasWithBasis(ZZ).Graded().SignedTensorProducts().base()\n Integer Ring\n '
return self.base_category().base()
|
class SimplicialComplexes(Category_singleton):
'\n The category of abstract simplicial complexes.\n\n An abstract simplicial complex `A` is a collection of sets `X`\n such that:\n\n - `\\emptyset \\in A`,\n - if `X \\subset Y \\in A`, then `X \\in A`.\n\n .. TODO::\n\n Implement the category of simplicial complexes considered\n as :class:`CW complexes <sage.categories.cw_complexes.CWComplexes>`\n and rename this to the category of ``AbstractSimplicialComplexes``\n with appropriate functors.\n\n EXAMPLES::\n\n sage: from sage.categories.simplicial_complexes import SimplicialComplexes\n sage: C = SimplicialComplexes(); C\n Category of simplicial complexes\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n Return the super categories of ``self``.\n\n EXAMPLES::\n\n sage: from sage.categories.simplicial_complexes import SimplicialComplexes\n sage: SimplicialComplexes().super_categories()\n [Category of sets]\n '
return [Sets()]
class Finite(CategoryWithAxiom):
'\n Category of finite simplicial complexes.\n '
class ParentMethods():
@cached_method
def dimension(self):
'\n Return the dimension of ``self``.\n\n EXAMPLES::\n\n sage: S = SimplicialComplex([[1,3,4], [1,2],[2,5],[4,5]]) # needs sage.graphs\n sage: S.dimension() # needs sage.graphs\n 2\n '
return max((c.dimension() for c in self.facets()))
class ParentMethods():
@abstract_method
def facets(self):
'\n Return the facets of ``self``.\n\n EXAMPLES::\n\n sage: S = SimplicialComplex([[1,3,4], [1,2],[2,5],[4,5]]) # needs sage.graphs\n sage: sorted(S.facets()) # needs sage.graphs\n [(1, 2), (1, 3, 4), (2, 5), (4, 5)]\n '
@abstract_method
def faces(self):
'\n Return the faces of ``self``.\n\n EXAMPLES::\n\n sage: S = SimplicialComplex([[1,3,4], [1,2],[2,5],[4,5]]) # needs sage.graphs\n sage: S.faces() # needs sage.graphs\n {-1: {()},\n 0: {(1,), (2,), (3,), (4,), (5,)},\n 1: {(1, 2), (1, 3), (1, 4), (2, 5), (3, 4), (4, 5)},\n 2: {(1, 3, 4)}}\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.simplicial_complexes import SimplicialComplexes\n sage: SimplicialComplexes().Connected()\n Category of connected simplicial complexes\n\n TESTS::\n\n sage: SimplicialComplexes().Connected.__module__\n 'sage.categories.simplicial_complexes'\n "
return self._with_axiom('Connected')
class Connected(CategoryWithAxiom):
'\n The category of connected simplicial complexes.\n\n EXAMPLES::\n\n sage: from sage.categories.simplicial_complexes import SimplicialComplexes\n sage: C = SimplicialComplexes().Connected()\n sage: TestSuite(C).run()\n '
|
class SimplicialSets(Category_singleton):
'\n The category of simplicial sets.\n\n A simplicial set `X` is a collection of sets `X_i`, indexed by\n the non-negative integers, together with maps\n\n .. math::\n\n d_i: X_n \\to X_{n-1}, \\quad 0 \\leq i \\leq n \\quad \\text{(face maps)} \\\\\n s_j: X_n \\to X_{n+1}, \\quad 0 \\leq j \\leq n \\quad \\text{(degeneracy maps)}\n\n satisfying the *simplicial identities*:\n\n .. math::\n\n d_i d_j &= d_{j-1} d_i \\quad \\text{if } i<j \\\\\n d_i s_j &= s_{j-1} d_i \\quad \\text{if } i<j \\\\\n d_j s_j &= 1 = d_{j+1} s_j \\\\\n d_i s_j &= s_{j} d_{i-1} \\quad \\text{if } i>j+1 \\\\\n s_i s_j &= s_{j+1} s_{i} \\quad \\text{if } i \\leq j\n\n Morphisms are sequences of maps `f_i : X_i \\to Y_i` which commute\n with the face and degeneracy maps.\n\n EXAMPLES::\n\n sage: from sage.categories.simplicial_sets import SimplicialSets\n sage: C = SimplicialSets(); C\n Category of simplicial sets\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.simplicial_sets import SimplicialSets\n sage: SimplicialSets().super_categories()\n [Category of sets]\n '
return [Sets()]
class ParentMethods():
def is_finite(self):
'\n Return ``True`` if this simplicial set is finite, i.e., has a\n finite number of nondegenerate simplices.\n\n EXAMPLES::\n\n sage: simplicial_sets.Torus().is_finite() # needs sage.graphs\n True\n sage: C5 = groups.misc.MultiplicativeAbelian([5]) # needs sage.graphs sage.groups\n sage: simplicial_sets.ClassifyingSpace(C5).is_finite() # needs sage.graphs sage.groups\n False\n '
return (SimplicialSets.Finite() in self.categories())
def is_pointed(self):
'\n Return ``True`` if this simplicial set is pointed, i.e., has a\n base point.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet\n sage: v = AbstractSimplex(0)\n sage: w = AbstractSimplex(0)\n sage: e = AbstractSimplex(1)\n sage: X = SimplicialSet({e: (v, w)})\n sage: Y = SimplicialSet({e: (v, w)}, base_point=w)\n sage: X.is_pointed()\n False\n sage: Y.is_pointed()\n True\n '
return (SimplicialSets.Pointed() in self.categories())
def set_base_point(self, point):
'\n Return a copy of this simplicial set in which the base point is\n set to ``point``.\n\n INPUT:\n\n - ``point`` -- a 0-simplex in this simplicial set\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet\n sage: v = AbstractSimplex(0, name=\'v_0\')\n sage: w = AbstractSimplex(0, name=\'w_0\')\n sage: e = AbstractSimplex(1)\n sage: X = SimplicialSet({e: (v, w)})\n sage: Y = SimplicialSet({e: (v, w)}, base_point=w)\n sage: Y.base_point()\n w_0\n sage: X_star = X.set_base_point(w)\n sage: X_star.base_point()\n w_0\n sage: Y_star = Y.set_base_point(v)\n sage: Y_star.base_point()\n v_0\n\n TESTS::\n\n sage: X.set_base_point(e) # needs sage.graphs\n Traceback (most recent call last):\n ...\n ValueError: the "point" is not a zero-simplex\n sage: pt = AbstractSimplex(0) # needs sage.graphs\n sage: X.set_base_point(pt) # needs sage.graphs\n Traceback (most recent call last):\n ...\n ValueError: the point is not a simplex in this simplicial set\n '
from sage.topology.simplicial_set import SimplicialSet
if (point.dimension() != 0):
raise ValueError('the "point" is not a zero-simplex')
if (point not in self._simplices):
raise ValueError('the point is not a simplex in this simplicial set')
return SimplicialSet(self.face_data(), base_point=point)
class Homsets(HomsetsCategory):
class Endset(CategoryWithAxiom):
class ParentMethods():
def one(self):
'\n Return the identity morphism in `\\operatorname{Hom}(S, S)`.\n\n EXAMPLES::\n\n sage: T = simplicial_sets.Torus() # needs sage.graphs\n sage: Hom(T, T).identity() # needs sage.graphs\n Simplicial set endomorphism of Torus\n Defn: Identity map\n '
from sage.topology.simplicial_set_morphism import SimplicialSetMorphism
return SimplicialSetMorphism(domain=self.domain(), codomain=self.codomain(), identity=True)
class Finite(CategoryWithAxiom):
'\n Category of finite simplicial sets.\n\n The objects are simplicial sets with finitely many\n non-degenerate simplices.\n '
pass
class SubcategoryMethods():
def Pointed(self):
'\n A simplicial set is *pointed* if it has a distinguished base\n point.\n\n EXAMPLES::\n\n sage: from sage.categories.simplicial_sets import SimplicialSets\n sage: SimplicialSets().Pointed().Finite()\n Category of finite pointed simplicial sets\n sage: SimplicialSets().Finite().Pointed()\n Category of finite pointed simplicial sets\n '
return self._with_axiom('Pointed')
class Pointed(CategoryWithAxiom):
class ParentMethods():
def base_point(self):
"\n Return this simplicial set's base point\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet\n sage: v = AbstractSimplex(0, name='*')\n sage: e = AbstractSimplex(1)\n sage: S1 = SimplicialSet({e: (v, v)}, base_point=v)\n sage: S1.is_pointed()\n True\n sage: S1.base_point()\n *\n "
return self._basepoint
def base_point_map(self, domain=None):
'\n Return a map from a one-point space to this one, with image the\n base point.\n\n This raises an error if this simplicial set does not have a\n base point.\n\n INPUT:\n\n - ``domain`` -- optional, default ``None``. Use\n this to specify a particular one-point space as\n the domain. The default behavior is to use the\n :func:`sage.topology.simplicial_set.Point`\n function to use a standard one-point space.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: T = simplicial_sets.Torus()\n sage: f = T.base_point_map(); f\n Simplicial set morphism:\n From: Point\n To: Torus\n Defn: Constant map at (v_0, v_0)\n sage: S3 = simplicial_sets.Sphere(3)\n sage: g = S3.base_point_map()\n sage: f.domain() == g.domain()\n True\n sage: RP3 = simplicial_sets.RealProjectiveSpace(3) # needs sage.groups\n sage: temp = simplicial_sets.Simplex(0)\n sage: pt = temp.set_base_point(temp.n_cells(0)[0])\n sage: h = RP3.base_point_map(domain=pt) # needs sage.groups\n sage: f.domain() == h.domain() # needs sage.groups\n False\n\n sage: C5 = groups.misc.MultiplicativeAbelian([5]) # needs sage.graphs sage.groups\n sage: BC5 = simplicial_sets.ClassifyingSpace(C5) # needs sage.graphs sage.groups\n sage: BC5.base_point_map() # needs sage.graphs sage.groups\n Simplicial set morphism:\n From: Point\n To: Classifying space of Multiplicative Abelian group isomorphic to C5\n Defn: Constant map at 1\n '
from sage.topology.simplicial_set_examples import Point
if (domain is None):
domain = Point()
elif (len(domain._simplices) > 1):
raise ValueError('domain has more than one nondegenerate simplex')
target = self.base_point()
return domain.Hom(self).constant_map(point=target)
def fundamental_group(self, simplify=True):
"\n Return the fundamental group of this pointed simplicial set.\n\n INPUT:\n\n - ``simplify`` (bool, optional ``True``) -- if\n ``False``, then return a presentation of the group\n in terms of generators and relations. If ``True``,\n the default, simplify as much as GAP is able to.\n\n Algorithm: we compute the edge-path group -- see\n Section 19 of [Kan1958]_ and\n :wikipedia:`Fundamental_group`. Choose a spanning tree\n for the connected component of the 1-skeleton\n containing the base point, and then the group's\n generators are given by the non-degenerate\n edges. There are two types of relations: `e=1` if `e`\n is in the spanning tree, and for every 2-simplex, if\n its faces are `e_0`, `e_1`, and `e_2`, then we impose\n the relation `e_0 e_1^{-1} e_2 = 1`, where we first\n set `e_i=1` if `e_i` is degenerate.\n\n EXAMPLES::\n\n sage: S1 = simplicial_sets.Sphere(1) # needs sage.graphs\n sage: eight = S1.wedge(S1) # needs sage.graphs\n sage: eight.fundamental_group() # free group on 2 generators # needs sage.graphs sage.groups\n Finitely presented group < e0, e1 | >\n\n The fundamental group of a disjoint union of course depends on\n the choice of base point::\n\n sage: T = simplicial_sets.Torus() # needs sage.graphs\n sage: K = simplicial_sets.KleinBottle() # needs sage.graphs\n sage: X = T.disjoint_union(K) # needs sage.graphs\n\n sage: # needs sage.graphs\n sage: X_0 = X.set_base_point(X.n_cells(0)[0])\n sage: X_0.fundamental_group().is_abelian() # needs sage.groups\n True\n sage: X_1 = X.set_base_point(X.n_cells(0)[1])\n sage: X_1.fundamental_group().is_abelian() # needs sage.groups\n False\n\n sage: RP3 = simplicial_sets.RealProjectiveSpace(3) # needs sage.graphs sage.groups\n sage: RP3.fundamental_group() # needs sage.graphs sage.groups\n Finitely presented group < e | e^2 >\n\n Compute the fundamental group of some classifying spaces::\n\n sage: C5 = groups.misc.MultiplicativeAbelian([5]) # needs sage.graphs sage.groups\n sage: BC5 = C5.nerve() # needs sage.graphs sage.groups\n sage: BC5.fundamental_group() # needs sage.graphs sage.groups\n Finitely presented group < e0 | e0^5 >\n\n sage: # needs sage.graphs sage.groups\n sage: Sigma3 = groups.permutation.Symmetric(3)\n sage: BSigma3 = Sigma3.nerve()\n sage: pi = BSigma3.fundamental_group(); pi\n Finitely presented group < e1, e2 | e2^2, e1^3, (e2*e1)^2 >\n sage: pi.order()\n 6\n sage: pi.is_abelian()\n False\n\n The sphere has a trivial fundamental group::\n\n sage: S2 = simplicial_sets.Sphere(2) # needs sage.graphs\n sage: S2.fundamental_group() # needs sage.graphs sage.groups\n Finitely presented group < | >\n "
from sage.groups.free_group import FreeGroup
if (not self.n_cells(1)):
return FreeGroup([]).quotient([])
FG = self._universal_cover_dict()[0]
if simplify:
return FG.simplified()
else:
return FG
def _universal_cover_dict(self):
'\n Return the fundamental group and dictionary sending each edge to\n the corresponding group element\n\n TESTS::\n\n sage: RP2 = simplicial_sets.RealProjectiveSpace(2) # needs sage.groups\n sage: RP2._universal_cover_dict() # needs sage.groups\n (Finitely presented group < e | e^2 >, {f: e})\n sage: RP2.nondegenerate_simplices() # needs sage.groups\n [1, f, f * f]\n '
from sage.groups.free_group import FreeGroup
graph = self.graph()
if (not self.is_connected()):
graph = graph.subgraph(self.base_point())
edges = [e[2] for e in graph.edges(sort=False)]
spanning_tree = [e[2] for e in graph.min_spanning_tree()]
gens = [e for e in edges if (e not in spanning_tree)]
gens_dict = dict(zip(gens, range(len(gens))))
FG = FreeGroup(len(gens), 'e')
rels = []
for f in self.n_cells(2):
z = {}
for (i, sigma) in enumerate(self.faces(f)):
if (sigma in spanning_tree):
z[i] = FG.one()
elif sigma.is_degenerate():
z[i] = FG.one()
elif (sigma in edges):
z[i] = FG.gen(gens_dict[sigma])
else:
z[i] = FG.one()
rels.append(((z[0] * z[1].inverse()) * z[2]))
G = FG.quotient(rels)
char = {g: G.gen(i) for (i, g) in enumerate(gens)}
for e in edges:
if (e not in gens):
char[e] = G.one()
return (G, char)
def universal_cover_map(self):
'\n Return the universal covering map of the simplicial set.\n\n It requires the fundamental group to be finite.\n\n EXAMPLES::\n\n sage: RP2 = simplicial_sets.RealProjectiveSpace(2) # needs sage.groups\n sage: phi = RP2.universal_cover_map(); phi # needs sage.groups\n Simplicial set morphism:\n From: Simplicial set with 6 non-degenerate simplices\n To: RP^2\n Defn: [(1, 1), (1, e), (f, 1), (f, e), (f * f, 1), (f * f, e)]\n --> [1, 1, f, f, f * f, f * f]\n sage: phi.domain().face_data() # needs sage.groups\n {(1, 1): None,\n (1, e): None,\n (f, 1): ((1, e), (1, 1)),\n (f, e): ((1, 1), (1, e)),\n (f * f, 1): ((f, e), s_0 (1, 1), (f, 1)),\n (f * f, e): ((f, 1), s_0 (1, e), (f, e))}\n\n '
edges = self.n_cells(1)
if (not edges):
return self.identity()
(G, char) = self._universal_cover_dict()
return self.covering_map(char)
def covering_map(self, character):
'\n Return the covering map associated to a character.\n\n The character is represented by a dictionary that assigns an\n element of a finite group to each nondegenerate 1-dimensional\n cell. It should correspond to an epimorphism from the fundamental\n group.\n\n INPUT:\n\n - ``character`` -- a dictionary\n\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: S1 = simplicial_sets.Sphere(1)\n sage: W = S1.wedge(S1)\n sage: G = CyclicPermutationGroup(3)\n sage: a, b = W.n_cells(1)\n sage: C = W.covering_map({a : G.gen(0), b : G.one()}); C\n Simplicial set morphism:\n From: Simplicial set with 9 non-degenerate simplices\n To: Wedge: (S^1 v S^1)\n Defn: [(*, ()), (*, (1,2,3)), (*, (1,3,2)), (sigma_1, ()),\n (sigma_1, ()), (sigma_1, (1,2,3)), (sigma_1, (1,2,3)),\n (sigma_1, (1,3,2)), (sigma_1, (1,3,2))]\n --> [*, *, *, sigma_1, sigma_1, sigma_1, sigma_1, sigma_1, sigma_1]\n sage: C.domain()\n Simplicial set with 9 non-degenerate simplices\n sage: C.domain().face_data()\n {(*, ()): None,\n (*, (1,2,3)): None,\n (*, (1,3,2)): None,\n (sigma_1, ()): ((*, (1,2,3)), (*, ())),\n (sigma_1, ()): ((*, ()), (*, ())),\n (sigma_1, (1,2,3)): ((*, (1,3,2)), (*, (1,2,3))),\n (sigma_1, (1,2,3)): ((*, (1,2,3)), (*, (1,2,3))),\n (sigma_1, (1,3,2)): ((*, ()), (*, (1,3,2))),\n (sigma_1, (1,3,2)): ((*, (1,3,2)), (*, (1,3,2)))}\n '
from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet
from sage.topology.simplicial_set_morphism import SimplicialSetMorphism
char = dict(character.items())
G = list(char.values())[0].parent()
if (not G.is_finite()):
raise NotImplementedError('can only compute universal covers of spaces with finite fundamental group')
cells_dict = {}
faces_dict = {}
for s in self.n_cells(0):
for g in G:
cell = AbstractSimplex(0, name='({}, {})'.format(s, g))
cells_dict[(s, g)] = cell
char[s] = G.one()
for d in range(1, (self.dimension() + 1)):
for s in self.n_cells(d):
if (s not in char.keys()):
if ((d == 1) and s.is_degenerate()):
char[s] = G.one()
elif s.is_degenerate():
if (0 in s.degeneracies()):
char[s] = G.one()
else:
char[s] = char[s.nondegenerate()]
else:
char[s] = char[self.face(s, d)]
if s.is_nondegenerate():
for g in G:
cell = AbstractSimplex(d, name='({}, {})'.format(s, g))
cells_dict[(s, g)] = cell
fd = []
faces = self.faces(s)
f0 = faces[0]
for h in G:
if (h == (g * char[s])):
lifted = h
break
grelems = [cells_dict[(f0.nondegenerate(), lifted)].apply_degeneracies(*f0.degeneracies())]
for f in faces[1:]:
grelems.append(cells_dict[(f.nondegenerate(), g)].apply_degeneracies(*f.degeneracies()))
faces_dict[cell] = grelems
cover = SimplicialSet(faces_dict, base_point=cells_dict[(self.base_point(), G.one())])
cover_map_data = {c: s[0] for (s, c) in cells_dict.items()}
return SimplicialSetMorphism(data=cover_map_data, domain=cover, codomain=self)
def cover(self, character):
'\n Return the cover of the simplicial set associated to a character\n of the fundamental group.\n\n The character is represented by a dictionary, that assigns an\n element of a finite group to each nondegenerate 1-dimensional\n cell. It should correspond to an epimorphism from the fundamental\n group.\n\n INPUT:\n\n - ``character`` -- a dictionary\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: S1 = simplicial_sets.Sphere(1)\n sage: W = S1.wedge(S1)\n sage: G = CyclicPermutationGroup(3)\n sage: (a, b) = W.n_cells(1)\n sage: C = W.cover({a : G.gen(0), b : G.gen(0)^2})\n sage: C.face_data()\n {(*, ()): None,\n (*, (1,2,3)): None,\n (*, (1,3,2)): None,\n (sigma_1, ()): ((*, (1,2,3)), (*, ())),\n (sigma_1, ()): ((*, (1,3,2)), (*, ())),\n (sigma_1, (1,2,3)): ((*, (1,3,2)), (*, (1,2,3))),\n (sigma_1, (1,2,3)): ((*, ()), (*, (1,2,3))),\n (sigma_1, (1,3,2)): ((*, ()), (*, (1,3,2))),\n (sigma_1, (1,3,2)): ((*, (1,2,3)), (*, (1,3,2)))}\n sage: C.homology(1) # needs sage.modules\n Z x Z x Z x Z\n sage: C.fundamental_group()\n Finitely presented group < e0, e1, e2, e3 | >\n '
return self.covering_map(character).domain()
def universal_cover(self):
'\n Return the universal cover of the simplicial set.\n The fundamental group must be finite in order to ensure that the\n universal cover is a simplicial set of finite type.\n\n EXAMPLES::\n\n sage: # needs sage.groups\n sage: RP3 = simplicial_sets.RealProjectiveSpace(3)\n sage: C = RP3.universal_cover(); C\n Simplicial set with 8 non-degenerate simplices\n sage: C.face_data()\n {(1, 1): None,\n (1, e): None,\n (f, 1): ((1, e), (1, 1)),\n (f, e): ((1, 1), (1, e)),\n (f * f, 1): ((f, e), s_0 (1, 1), (f, 1)),\n (f * f, e): ((f, 1), s_0 (1, e), (f, e)),\n (f * f * f, 1): ((f * f, e), s_0 (f, 1), s_1 (f, 1), (f * f, 1)),\n (f * f * f, e): ((f * f, 1), s_0 (f, e), s_1 (f, e), (f * f, e))}\n sage: C.fundamental_group()\n Finitely presented group < | >\n '
return self.universal_cover_map().domain()
def _canonical_twisting_operator(self):
'\n The canonical twisting operator corresponds to the abelianization of the fundamental\n group. It assigns each edge to the corresponding element in the algebra of the\n abelianization of the fundamental group, which is a quotient of a Laurent polynomial\n ring.\n\n EXAMPLES::\n\n sage: X = simplicial_sets.Torus()\n sage: d = X._canonical_twisting_operator()\n sage: d\n {(s_0 v_0, sigma_1): f3, (sigma_1, s_0 v_0): f2*f3^-1, (sigma_1, sigma_1): f2}\n sage: list(d.values())[0].parent()\n Multivariate Laurent Polynomial Ring in f2, f3 over Integer Ring\n sage: Y = simplicial_sets.RealProjectiveSpace(2)\n sage: d2 = Y._canonical_twisting_operator()\n sage: d2\n {f: F1bar}\n sage: list(d2.values())[0].parent()\n Quotient of Univariate Laurent Polynomial Ring in F1 over Integer Ring by the ideal (-1 + F1^2)\n\n '
(G, d) = self._universal_cover_dict()
phi = G.abelianization_map()
(abelG, R, I, images) = G.abelianization_to_algebra(ZZ)
QRP = R.quotient_ring(I)
res = {}
for (s, el) in d.items():
res[s] = QRP(prod(((images[(abs(a) - 1)] ** sign(a)) for a in el.Tietze())))
return res
def twisted_chain_complex(self, twisting_operator=None, dimensions=None, augmented=False, cochain=False, verbose=False, subcomplex=None, check=False):
'\n Return the normalized chain complex twisted by some operator.\n\n A twisting operator is a map from the set of simplices to some algebra.\n The differentials are then twisted by this operator.\n\n INPUT:\n\n - ``twisting_operator`` -- a dictionary, associating the twist of each\n simplex. If it is not given, the canonical one (associated to the\n laurent polynomial ring abelianization of the fundamental group, ignoring\n torsion) is used.\n\n - ``dimensions`` -- if ``None``, compute the chain complex in all\n dimensions. If a list or tuple of integers, compute the\n chain complex in those dimensions, setting the chain groups\n in all other dimensions to zero.\n\n - ``augmented`` (optional, default ``False``) -- if ``True``,\n return the augmented chain complex (that is, include a class\n in dimension `-1` corresponding to the empty cell).\n\n - ``cochain`` (optional, default ``False``) -- if ``True``,\n return the cochain complex (that is, the dual of the chain\n complex).\n\n - ``verbose`` (optional, default ``False``) -- ignored.\n\n - ``subcomplex`` (optional, default ``None``) -- if present,\n compute the chain complex relative to this subcomplex.\n\n - ``check`` (optional, default ``False``) -- If ``True``, make\n sure that the chain complex is actually a chain complex:\n the differentials are composable and their product is zero.\n\n The normalized chain complex of a simplicial set is isomorphic\n to the chain complex obtained by modding out by degenerate\n simplices, and the latter is what is actually constructed\n here.\n\n EXAMPLES::\n\n sage: W = simplicial_sets.Sphere(1).wedge(simplicial_sets.Sphere(2))\n sage: W.nondegenerate_simplices()\n [*, sigma_1, sigma_2]\n sage: s1 = W.nondegenerate_simplices()[1]\n sage: L.<t> = LaurentPolynomialRing(QQ)\n sage: tw = {s1:t}\n sage: ChC = W.twisted_chain_complex(tw)\n sage: ChC.differential(1)\n [-1 + t]\n sage: ChC.differential(2)\n [0]\n\n ::\n\n sage: X = simplicial_sets.Torus()\n sage: C = X.twisted_chain_complex()\n sage: C.differential(1)\n [ f3 - 1 f2*f3^-1 - 1 f2 - 1]\n sage: C.differential(2)\n [ 1 f2*f3^-1]\n [ f3 1]\n [ -1 -1]\n sage: C.differential(3)\n []\n\n ::\n\n sage: Y = simplicial_sets.RealProjectiveSpace(2)\n sage: C = Y.twisted_chain_complex()\n sage: C.differential(1)\n [-1 + F1]\n sage: C.differential(2)\n [1 + F1]\n sage: C.differential(3)\n []\n\n '
from sage.homology.chain_complex import ChainComplex
from sage.structure.element import get_coercion_model
cm = get_coercion_model()
if twisting_operator:
twop = twisting_operator
else:
di = self._canonical_twisting_operator()
if hasattr(list(di.values())[0], 'lift'):
twop = {a: b.lift() for (a, b) in di.items()}
else:
twop = di
def twist(s):
if (s in twop):
return twop[s]
if (s.dimension() > 1):
return twist(self.face(s, s.dimension()))
return 1
base_ring = cm.common_parent(*twop.values())
if (dimensions is None):
if (not self.cells()):
if cochain:
return ChainComplex({(- 1): matrix(base_ring, 0, 0)}, degree_of_differential=1)
return ChainComplex({0: matrix(base_ring, 0, 0)}, degree_of_differential=(- 1))
dimensions = list(range((self.dimension() + 1)))
else:
if (not isinstance(dimensions, (list, tuple, range))):
dimensions = list(range((dimensions - 1), (dimensions + 2)))
else:
dimensions = [n for n in dimensions if (n >= 0)]
if (not dimensions):
if cochain:
return ChainComplex(base_ring=base_ring, degree=1)
else:
return ChainComplex(base_ring=base_ring, degree=(- 1))
differentials = {}
if subcomplex:
X = self.quotient(subcomplex)
face_data = X.face_data()
nondegens = X.nondegenerate_simplices()
else:
face_data = self.face_data()
nondegens = self.nondegenerate_simplices()
simplices = {}
for sigma in nondegens:
if (sigma.dimension() in simplices):
simplices[sigma.dimension()].append(sigma)
else:
simplices[sigma.dimension()] = [sigma]
first = dimensions.pop(0)
if (first in simplices):
rank = len(simplices[first])
current = sorted(simplices[first])
else:
rank = 0
current = []
if (augmented and (first == 0)):
differentials[(first - 1)] = matrix(base_ring, 0, 1)
differentials[first] = matrix(base_ring, 1, rank, ([1] * rank))
else:
differentials[first] = matrix(base_ring, 0, rank)
for d in dimensions:
old_rank = rank
faces = {_[1]: _[0] for _ in enumerate(current)}
if (d in simplices):
current = sorted(simplices[d])
rank = len(current)
if (not faces):
differentials[d] = matrix(base_ring, old_rank, rank)
else:
matrix_data = {}
for (col, sigma) in enumerate(current):
sign = 1
twists = (len(face_data[sigma]) * [1])
twists[0] = twist(sigma)
for (ch, tau) in zip(twists, face_data[sigma]):
if tau.is_nondegenerate():
row = faces[tau]
if ((row, col) in matrix_data):
matrix_data[(row, col)] += (sign * ch)
else:
matrix_data[(row, col)] = (sign * ch)
sign *= (- 1)
differentials[d] = matrix(base_ring, old_rank, rank, matrix_data, sparse=False)
else:
rank = 0
current = []
differentials[d] = matrix(base_ring, old_rank, rank, sparse=False)
if cochain:
new_diffs = {}
for d in differentials:
new_diffs[(d - 1)] = differentials[d].transpose()
return ChainComplex(new_diffs, degree_of_differential=1, check=check)
return ChainComplex(differentials, degree_of_differential=(- 1), check=check)
def twisted_homology(self, n, reduced=False):
'\n The `n`-th twisted homology module of the simplicial set with respect to\n the abelianization of the fundamental_group.\n\n It is a module over a polynomial ring, including relations to make some\n variables the multiplicative inverses of others.\n\n INPUT:\n\n - ``n`` - a positive integer.\n\n - ``reduced`` - (default: False) if set to True, the presentation matrix\n will be reduced.\n\n EXAMPLES::\n\n sage: X = simplicial_sets.Sphere(1).wedge(simplicial_sets.Sphere(2))\n sage: X.twisted_homology(1)\n Quotient module by Submodule of Ambient free module of rank 0 over the integral domain Multivariate Polynomial Ring in f1, f1inv over Integer Ring\n Generated by the rows of the matrix:\n []\n sage: X.twisted_homology(2)\n Quotient module by Submodule of Ambient free module of rank 1 over the integral domain Multivariate Polynomial Ring in f1, f1inv over Integer Ring\n Generated by the rows of the matrix:\n [f1*f1inv - 1]\n\n ::\n\n sage: Y = simplicial_sets.Torus()\n sage: Y.twisted_homology(1)\n Quotient module by Submodule of Ambient free module of rank 5 over the integral domain Multivariate Polynomial Ring in f2, f2inv, f3, f3inv over Integer Ring\n Generated by the rows of the matrix:\n [ 1 0 0 0 0]\n [ 0 1 0 0 0]\n [ 0 0 1 0 0]\n [ 0 0 0 1 0]\n [ 0 0 0 0 1]\n [f2*f2inv - 1 0 0 0 0]\n [ 0 f2*f2inv - 1 0 0 0]\n [ 0 0 f2*f2inv - 1 0 0]\n [ 0 0 0 f2*f2inv - 1 0]\n [ 0 0 0 0 f2*f2inv - 1]\n [f3*f3inv - 1 0 0 0 0]\n [ 0 f3*f3inv - 1 0 0 0]\n [ 0 0 f3*f3inv - 1 0 0]\n [ 0 0 0 f3*f3inv - 1 0]\n [ 0 0 0 0 f3*f3inv - 1]\n sage: Y.twisted_homology(2)\n Quotient module by Submodule of Ambient free module of rank 0 over the integral domain Multivariate Polynomial Ring in f2, f2inv, f3, f3inv over Integer Ring\n Generated by the rows of the matrix:\n []\n sage: Y.twisted_homology(1, reduced=True)\n Quotient module by Submodule of Ambient free module of rank 5 over the integral domain Multivariate Polynomial Ring in f2, f2inv, f3, f3inv over Integer Ring\n Generated by the rows of the matrix:\n [1 0 0 0 0]\n [0 1 0 0 0]\n [0 0 1 0 0]\n [0 0 0 1 0]\n [0 0 0 0 1]\n\n TESTS::\n\n sage: X = simplicial_sets.PresentationComplex(groups.presentation.FGAbelian((3,2)))\n sage: TW2 = X.twisted_homology(2, reduced=True)\n sage: M = TW2.relations_matrix()\n sage: from sage.libs.singular.function import singular_function\n sage: vdim = singular_function("vdim")\n sage: vdim(M.T, ring=M.base_ring())\n // ** considering the image in Q[...]\n // ** _ is no standard basis\n 5\n sage: X.universal_cover().homology(2)\n Z^5\n sage: from sage.libs.singular.function import singular_function\n\n '
from sage.libs.singular.function import singular_function
from sage.libs.singular.option import opt_verb
opt_verb['not_warn_sb'] = True
singstd = singular_function('std')
singsyz = singular_function('syz')
singred = singular_function('reduce')
singlift = singular_function('lift')
(G, d) = self._universal_cover_dict()
phi = G.abelianization_map()
(abelG, R, I, images) = G.abelianization_to_algebra(ZZ)
CC = self.twisted_chain_complex()
M1 = CC.differential(n).T
M2 = CC.differential((n + 1)).T
def convert_to_polynomial(p):
if hasattr(p, 'lift'):
return p.lift()._as_extended_polynomial()
else:
return p._as_extended_polynomial()
M1 = M1.apply_map(convert_to_polynomial)
M2 = M2.apply_map(convert_to_polynomial)
RP = R._extended_ring
IP = RP.ideal([convert_to_polynomial(g) for g in I])
JP = R._extended_ring_ideal
GB = (IP + JP).groebner_basis()
GBI = RP.ideal(GB)
def reduce_laurent(a):
return singred(a, GBI, ring=RP)
def group_to_polynomial(el, RP):
res = RP.one()
for a in el.Tietze():
if (a > 0):
res *= RP.gen(((2 * a) - 2))
else:
res *= RP.gen((((- 2) * a) - 1))
return res
def mkernel(M):
if (M.nrows() == 0):
return matrix(M.base_ring(), 0, 0)
if (M.ncols() == 0):
return M.T
res = M
n = res.ncols()
for g in (IP + JP).gens():
res = res.stack((g * identity_matrix(n)))
syz = matrix(singsyz(res.T, ring=res.base_ring())).T
trimmed = syz.T.submatrix(0, 0, syz.ncols(), M.nrows())
trimmed = trimmed.apply_map(reduce_laurent)
to_delete = [i for (i, r) in enumerate(trimmed.rows()) if (not r)]
return trimmed.delete_rows(to_delete)
def lift_to_submodule(S, M):
if ((S.nrows() == 0) or (S.ncols() == 0)):
return S
res = M
for g in GB:
res = res.stack((g * identity_matrix(M.ncols())))
singres = matrix(singlift(res.T, S.T, ring=res.base_ring()))
return singres.submatrix(0, 0, M.nrows(), S.nrows())
def mgb(M):
if ((M.nrows() == 0) or (M.ncols() == 0)):
return M
res = M
for g in GB:
res = res.stack((g * identity_matrix(M.ncols())))
sres = matrix(singstd(res.T, ring=RP))
to_delete = [i for (i, r) in enumerate(sres.apply_map(reduce_laurent)) if (not r)]
return sres.delete_rows(to_delete)
M2 = border_matrix((n + 1))
if (M1.nrows() == 0):
opt_verb.reset_default()
return (RP ** 0).quotient_module([])
K = mkernel(M1)
DK = mkernel(K)
if (M2.nrows() > 0):
S = lift_to_submodule(M2, K)
if ((S.nrows() > 0) and (S.ncols() > 0)):
res = mgb(DK.stack(S.T))
else:
res = DK
else:
res = mgb(DK)
resmat = mgb(res.apply_map(reduce_laurent))
AM = (RP ** K.nrows())
if (resmat.ncols() == 0):
SM = AM.submodule([])
opt_verb.reset_default()
return AM.quotient_module(SM)
for g in (IP + JP).gens():
resmat = resmat.stack((g * identity_matrix(resmat.ncols())))
if reduced:
resmat = matrix(singstd(resmat.T, ring=RP))
SM = AM.submodule(resmat)
opt_verb.reset_default()
return AM.quotient_module(SM)
def is_simply_connected(self):
'\n Return ``True`` if this pointed simplicial set is simply connected.\n\n .. WARNING::\n\n Determining simple connectivity is not always\n possible, because it requires determining when a\n group, as given by generators and relations, is\n trivial. So this conceivably may give a false\n negative in some cases.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: T = simplicial_sets.Torus()\n sage: T.is_simply_connected()\n False\n sage: T.suspension().is_simply_connected()\n True\n sage: simplicial_sets.KleinBottle().is_simply_connected()\n False\n\n sage: # needs sage.graphs\n sage: S2 = simplicial_sets.Sphere(2)\n sage: S3 = simplicial_sets.Sphere(3)\n sage: (S2.wedge(S3)).is_simply_connected() # needs sage.groups\n True\n sage: X = S2.disjoint_union(S3)\n sage: X = X.set_base_point(X.n_cells(0)[0])\n sage: X.is_simply_connected()\n False\n\n sage: C3 = groups.misc.MultiplicativeAbelian([3]) # needs sage.graphs sage.groups\n sage: BC3 = simplicial_sets.ClassifyingSpace(C3) # needs sage.graphs sage.groups\n sage: BC3.is_simply_connected() # needs sage.graphs sage.groups\n False\n '
if (not self.is_connected()):
return False
try:
if (not self.is_pointed()):
space = self.set_base_point(self.n_cells(0)[0])
else:
space = self
return bool(space.fundamental_group().IsTrivial())
except AttributeError:
try:
return (space.fundamental_group().order() == 1)
except (NotImplementedError, RuntimeError):
raise ValueError('unable to determine if the fundamental group is trivial')
def connectivity(self, max_dim=None):
'\n Return the connectivity of this pointed simplicial set.\n\n INPUT:\n\n - ``max_dim`` -- specify a maximum dimension through\n which to check. This is required if this simplicial\n set is simply connected and not finite.\n\n The dimension of the first nonzero homotopy group. If\n simply connected, this is the same as the dimension of\n the first nonzero homology group.\n\n .. WARNING::\n\n See the warning for the :meth:`is_simply_connected` method.\n\n The connectivity of a contractible space is ``+Infinity``.\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: simplicial_sets.Sphere(3).connectivity()\n 2\n sage: simplicial_sets.Sphere(0).connectivity()\n -1\n sage: K = simplicial_sets.Simplex(4)\n sage: K = K.set_base_point(K.n_cells(0)[0])\n sage: K.connectivity()\n +Infinity\n sage: X = simplicial_sets.Torus().suspension(2)\n sage: X.connectivity()\n 2\n\n sage: C2 = groups.misc.MultiplicativeAbelian([2]) # needs sage.graphs sage.groups\n sage: BC2 = simplicial_sets.ClassifyingSpace(C2) # needs sage.graphs sage.groups\n sage: BC2.connectivity() # needs sage.graphs sage.groups\n 0\n '
if (not self.is_connected()):
return Integer((- 1))
if (not self.is_simply_connected()):
return Integer(0)
if (max_dim is None):
if self.is_finite():
max_dim = self.dimension()
else:
raise ValueError('this simplicial set may be infinite, so specify a maximum dimension through which to check')
H = self.homology(range(2, (max_dim + 1)))
for i in range(2, (max_dim + 1)):
if ((i in H) and (H[i].order() != 1)):
return (i - 1)
return Infinity
class Finite(CategoryWithAxiom):
class ParentMethods():
def unset_base_point(self):
"\n Return a copy of this simplicial set in which the base point has\n been forgotten.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet\n sage: v = AbstractSimplex(0, name='v_0')\n sage: w = AbstractSimplex(0, name='w_0')\n sage: e = AbstractSimplex(1)\n sage: Y = SimplicialSet({e: (v, w)}, base_point=w)\n sage: Y.is_pointed()\n True\n sage: Y.base_point()\n w_0\n sage: Z = Y.unset_base_point()\n sage: Z.is_pointed()\n False\n "
from sage.topology.simplicial_set import SimplicialSet
return SimplicialSet(self.face_data())
def fat_wedge(self, n):
'\n Return the `n`-th fat wedge of this pointed simplicial set.\n\n This is the subcomplex of the `n`-fold product `X^n`\n consisting of those points in which at least one\n factor is the base point. Thus when `n=2`, this is the\n wedge of the simplicial set with itself, but when `n`\n is larger, the fat wedge is larger than the `n`-fold\n wedge.\n\n EXAMPLES::\n\n sage: # needs sage.graphs\n sage: S1 = simplicial_sets.Sphere(1)\n sage: S1.fat_wedge(0)\n Point\n sage: S1.fat_wedge(1)\n S^1\n sage: S1.fat_wedge(2).fundamental_group() # needs sage.groups\n Finitely presented group < e0, e1 | >\n sage: S1.fat_wedge(4).homology() # needs sage.modules\n {0: 0, 1: Z x Z x Z x Z, 2: Z^6, 3: Z x Z x Z x Z}\n '
from sage.topology.simplicial_set_examples import Point
if (n == 0):
return Point()
if (n == 1):
return self
return self.product(*([self] * (n - 1))).fat_wedge_as_subset()
def smash_product(self, *others):
'\n Return the smash product of this simplicial set with ``others``.\n\n INPUT:\n\n - ``others`` -- one or several simplicial sets\n\n EXAMPLES::\n\n sage: # needs sage.graphs sage.groups\n sage: S1 = simplicial_sets.Sphere(1)\n sage: RP2 = simplicial_sets.RealProjectiveSpace(2)\n sage: X = S1.smash_product(RP2)\n sage: X.homology(base_ring=GF(2)) # needs sage.modules\n {0: Vector space of dimension 0 over Finite Field of size 2,\n 1: Vector space of dimension 0 over Finite Field of size 2,\n 2: Vector space of dimension 1 over Finite Field of size 2,\n 3: Vector space of dimension 1 over Finite Field of size 2}\n\n sage: T = S1.product(S1) # needs sage.graphs sage.groups\n sage: X = T.smash_product(S1) # needs sage.graphs sage.groups\n sage: X.homology(reduced=False) # needs sage.graphs sage.groups sage.modules\n {0: Z, 1: 0, 2: Z x Z, 3: Z}\n '
from sage.topology.simplicial_set_constructions import SmashProductOfSimplicialSets_finite
return SmashProductOfSimplicialSets_finite(((self,) + others))
|
class SubobjectsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Subobjects'
@classmethod
def default_super_categories(cls, category):
'\n Returns the default super categories of ``category.Subobjects()``\n\n Mathematical meaning: if `A` is a subobject 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 ``SubobjectsCategory``\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.Subobjects()`` 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 submonoid of `G`::\n\n sage: Groups().Subobjects().super_categories()\n [Category of groups, Category of subquotients of monoids, Category of subobjects of sets]\n\n Mind the last item above: there is indeed currently nothing\n implemented about submonoids.\n\n This resulted from the following call::\n\n sage: sage.categories.subobjects.SubobjectsCategory.default_super_categories(Groups())\n Join of Category of groups and Category of subquotients of monoids and Category of subobjects of sets\n '
return Category.join([category.Subquotients(), super().default_super_categories(category)])
|
class SubquotientsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Subquotients'
|
class SuperAlgebras(SuperModulesCategory):
'\n The category of super algebras.\n\n An `R`-*super algebra* is an `R`-super module `A` endowed with an\n `R`-algebra structure satisfying\n\n .. MATH::\n\n A_0 A_0 \\subseteq A_0, \\qquad\n A_0 A_1 \\subseteq A_1, \\qquad\n A_1 A_0 \\subseteq A_1, \\qquad\n A_1 A_1 \\subseteq A_0\n\n and `1 \\in A_0`.\n\n EXAMPLES::\n\n sage: Algebras(ZZ).Super()\n Category of super algebras over Integer Ring\n\n TESTS::\n\n sage: TestSuite(Algebras(ZZ).Super()).run()\n '
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Algebras(ZZ).Super().super_categories() # indirect doctest\n [Category of graded algebras over Integer Ring,\n Category of super modules over Integer Ring]\n '
return [self.base_category().Graded()]
Supercommutative = LazyImport('sage.categories.supercommutative_algebras', 'SupercommutativeAlgebras')
class ParentMethods():
def graded_algebra(self):
'\n Return the associated graded algebra to ``self``.\n\n .. WARNING::\n\n Because a super module `M` is naturally `\\ZZ / 2 \\ZZ`-graded, and\n graded modules have a natural filtration induced by the grading, if\n `M` has a different filtration, then the associated graded module\n `\\operatorname{gr} M \\neq M`. This is most apparent with super\n algebras, such as the :class:`differential Weyl algebra\n <sage.algebras.weyl_algebra.DifferentialWeylAlgebra>`, and the\n multiplication may not coincide.\n '
raise NotImplementedError
def tensor(*parents, **kwargs):
'\n Return the tensor product of the parents.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A.<x,y,z> = ExteriorAlgebra(ZZ); A.rename("A")\n sage: T = A.tensor(A,A); T\n A # A # A\n sage: T in Algebras(ZZ).Graded().SignedTensorProducts()\n True\n sage: T in Algebras(ZZ).Graded().TensorProducts()\n False\n sage: A.rename(None)\n\n This also works when the other elements do not have\n a signed tensor product (:trac:`31266`)::\n\n sage: # needs sage.combinat sage.modules\n sage: a = SteenrodAlgebra(3).an_element()\n sage: M = CombinatorialFreeModule(GF(3), [\'s\', \'t\', \'u\'])\n sage: s = M.basis()[\'s\']\n sage: tensor([a, s]) # needs sage.rings.finite_rings\n 2*Q_1 Q_3 P(2,1) # B[\'s\']\n '
constructor = kwargs.pop('constructor', tensor_signed)
try:
cat = constructor.category_from_parents(parents)
except AttributeError:
cat = tensor.category_from_parents(parents)
return parents[0].__class__.Tensor(parents, category=cat)
class SubcategoryMethods():
@cached_method
def Supercommutative(self):
'\n Return the full subcategory of the supercommutative objects\n of ``self``.\n\n A super algebra `M` is *supercommutative* if, for all\n homogeneous `x,y\\in M`,\n\n .. MATH::\n\n x \\cdot y = (-1)^{|x||y|} y \\cdot x.\n\n REFERENCES:\n\n :wikipedia:`Supercommutative_algebra`\n\n EXAMPLES::\n\n sage: Algebras(ZZ).Super().Supercommutative()\n Category of supercommutative algebras over Integer Ring\n sage: Algebras(ZZ).Super().WithBasis().Supercommutative()\n Category of supercommutative algebras with basis over Integer Ring\n '
return self._with_axiom('Supercommutative')
class SignedTensorProducts(SignedTensorProductsCategory):
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Coalgebras(QQ).Graded().SignedTensorProducts().extra_super_categories()\n [Category of graded coalgebras over Rational Field]\n sage: Coalgebras(QQ).Graded().SignedTensorProducts().super_categories()\n [Category of graded coalgebras over Rational Field]\n\n Meaning: a signed tensor product of coalgebras is a coalgebra\n '
return [self.base_category()]
|
class SuperAlgebrasWithBasis(SuperModulesCategory):
'\n The category of super algebras with a distinguished basis\n\n EXAMPLES::\n\n sage: C = Algebras(ZZ).WithBasis().Super(); C\n Category of super algebras with basis over Integer Ring\n\n TESTS::\n\n sage: TestSuite(C).run()\n '
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: C = Algebras(ZZ).WithBasis().Super()\n sage: sorted(C.super_categories(), key=str) # indirect doctest\n [Category of graded algebras with basis over Integer Ring,\n Category of super algebras over Integer Ring,\n Category of super modules with basis over Integer Ring]\n '
return [self.base_category().Graded()]
class ParentMethods():
def graded_algebra(self):
'\n Return the associated graded module to ``self``.\n\n See :class:`~sage.algebras.associated_graded.AssociatedGradedAlgebra`\n for the definition and the properties of this.\n\n .. SEEALSO::\n\n :meth:`~sage.categories.filtered_modules_with_basis.ParentMethods.graded_algebra`\n\n EXAMPLES::\n\n sage: W.<x,y> = algebras.DifferentialWeyl(QQ) # needs sage.modules\n sage: W.graded_algebra() # needs sage.combinat sage.modules\n Graded Algebra of Differential Weyl algebra of\n polynomials in x, y over Rational Field\n '
from sage.algebras.associated_graded import AssociatedGradedAlgebra
return AssociatedGradedAlgebra(self)
class ElementMethods():
def supercommutator(self, x):
'\n Return the supercommutator of ``self`` and ``x``.\n\n Let `A` be a superalgebra. The *supercommutator* of homogeneous\n elements `x, y \\in A` is defined by\n\n .. MATH::\n\n [x, y\\} = x y - (-1)^{|x| |y|} y x\n\n and extended to all elements by linearity.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(ZZ, 3, [1,2,3,4,5,6])\n sage: Cl.<x,y,z> = CliffordAlgebra(Q)\n sage: a = x*y - z\n sage: b = x - y + y*z\n sage: a.supercommutator(b)\n -5*x*y + 8*x*z - 2*y*z - 6*x + 12*y - 5*z\n sage: a.supercommutator(Cl.one())\n 0\n sage: Cl.one().supercommutator(a)\n 0\n sage: Cl.zero().supercommutator(a)\n 0\n sage: a.supercommutator(Cl.zero())\n 0\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(ZZ, 2, [-1,1,-3])\n sage: Cl.<x,y> = CliffordAlgebra(Q)\n sage: [a.supercommutator(b) for a in Cl.basis() for b in Cl.basis()]\n [0, 0, 0, 0, 0, -2, 1, -x - 2*y, 0, 1,\n -6, 6*x + y, 0, x + 2*y, -6*x - y, 0]\n sage: [a*b-b*a for a in Cl.basis() for b in Cl.basis()]\n [0, 0, 0, 0, 0, 0, 2*x*y - 1, -x - 2*y, 0,\n -2*x*y + 1, 0, 6*x + y, 0, x + 2*y, -6*x - y, 0]\n\n Exterior algebras inherit from Clifford algebras, so\n supercommutators work as well. We verify the exterior algebra\n is supercommutative::\n\n sage: E.<x,y,z,w> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: all(b1.supercommutator(b2) == 0 # needs sage.modules\n ....: for b1 in E.basis() for b2 in E.basis())\n True\n '
P = self.parent()
ret = P.zero()
for (ms, cs) in self:
term_s = P.term(ms, cs)
sign_s = ((- 1) ** P.degree_on_basis(ms))
for (mx, cx) in x:
ret += (term_s * P.term(mx, cx))
s = (sign_s ** P.degree_on_basis(mx))
ret -= ((s * P.term(mx, cx)) * term_s)
return ret
class SignedTensorProducts(SignedTensorProductsCategory):
'\n The category of super algebras with basis constructed by tensor\n product of super algebras with basis.\n '
@cached_method
def extra_super_categories(self):
'\n EXAMPLES::\n\n sage: Algebras(QQ).Super().SignedTensorProducts().extra_super_categories()\n [Category of super algebras over Rational Field]\n sage: Algebras(QQ).Super().SignedTensorProducts().super_categories()\n [Category of signed tensor products of graded algebras over Rational Field,\n Category of super algebras over Rational Field]\n\n Meaning: a signed tensor product of super algebras is a super algebra\n '
return [self.base_category()]
|
class SuperHopfAlgebrasWithBasis(SuperModulesCategory):
'\n The category of super Hopf algebras with a distinguished basis.\n\n EXAMPLES::\n\n sage: C = HopfAlgebras(ZZ).WithBasis().Super(); C\n Category of super Hopf algebras with basis over Integer Ring\n sage: sorted(C.super_categories(), key=str)\n [Category of super Hopf algebras over Integer Ring,\n Category of super algebras with basis over Integer Ring,\n Category of super coalgebras with basis over Integer Ring]\n\n TESTS::\n\n sage: C = HopfAlgebras(ZZ).WithBasis().Super()\n sage: TestSuite(C).run()\n '
class ParentMethods():
@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,\n if available.\n\n EXAMPLES::\n\n sage: A = SteenrodAlgebra(7) # needs sage.combinat sage.modules\n sage: a = A.an_element() # needs sage.combinat sage.modules\n sage: a, A.antipode(a) # needs sage.combinat sage.modules\n (6 Q_1 Q_3 P(2,1), Q_1 Q_3 P(2,1))\n\n TESTS::\n\n sage: E.<x,y> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: [b.antipode() for b in E.basis()] # needs sage.modules\n [1, -x, -y, x*y]\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 (super) Hopf algebra is a linear\n endomorphism of the Hopf algebra that satisfies the\n following conditions (see :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 .. MATH::\n\n S(ab) = (-1)^{\\deg a \\deg b} S(b) S(a)\n\n for homogeneous `a` and `b`.\n\n These properties are tested on :meth:`some_elements`.\n\n TESTS::\n\n sage: A = SteenrodAlgebra(7) # needs sage.combinat sage.modules\n sage: A._test_antipode() # long time # needs sage.combinat sage.modules\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():
x_even = x.even_component()
x_odd = x.odd_component()
for y in tester.some_elements():
y_even = y.even_component()
y_odd = y.odd_component()
tester.assertEqual((S(x_even) * S(y_even)), S((y_even * x_even)))
tester.assertEqual((S(x_even) * S(y_odd)), S((y_odd * x_even)))
tester.assertEqual((S(x_odd) * S(y_even)), S((y_even * x_odd)))
tester.assertEqual((S(x_odd) * S(y_odd)), (- S((y_odd * x_odd))))
tester.assertEqual(SI(x), (self.counit(x) * self.one()))
tester.assertEqual(IS(x), (self.counit(x) * self.one()))
|
class SuperLieConformalAlgebras(SuperModulesCategory):
"\n The category of super Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(AA).Super() # needs sage.rings.number_field\n Category of super Lie conformal algebras over Algebraic Real Field\n\n Notice that we can force to have a *purely even* super Lie\n conformal algebra::\n\n sage: bosondict = {('a','a'): {1:{('K',0):1}}}\n sage: R = LieConformalAlgebra(QQ, bosondict, names=('a',), # needs sage.combinat sage.modules\n ....: central_elements=('K',), super=True)\n sage: [g.is_even_odd() for g in R.gens()] # needs sage.combinat sage.modules\n [0, 0]\n "
def extra_super_categories(self):
'\n The extra super categories of ``self``.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ).Super().super_categories()\n [Category of super modules over Rational Field,\n Category of Lambda bracket algebras over Rational Field]\n '
return [LambdaBracketAlgebras(self.base_ring())]
def example(self):
'\n An example parent in this category.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQ).Super().example() # needs sage.combinat sage.modules\n The Neveu-Schwarz super Lie conformal algebra over Rational Field\n '
from sage.algebras.lie_conformal_algebras.neveu_schwarz_lie_conformal_algebra import NeveuSchwarzLieConformalAlgebra
return NeveuSchwarzLieConformalAlgebra(self.base_ring())
class ParentMethods():
def _test_jacobi(self, **options):
"\n Test the Jacobi axiom of this super 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}},\n ....: ('b', 'a'): {0: {('a', 0): 1}}}\n sage: V = LieConformalAlgebra(QQ, wrongdict, # needs sage.combinat sage.modules\n ....: names=('a', 'b'), parity=(1, 0))\n sage: V._test_jacobi() # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n AssertionError: {(0, 0): -3*a} != {} - {(0, 0): -3*a} + {}\n "
tester = self._tester(**options)
S = tester.some_elements()
elements = []
for s in S:
try:
s.is_even_odd()
except ValueError:
try:
elements.extend([s.even_component(), s.odd_component()])
except (AttributeError, ValueError):
pass
continue
elements.append(s)
S = elements
from sage.misc.misc import some_tuples
from sage.arith.misc import binomial
pz = tester._instance.zero()
for (x, y, z) in some_tuples(S, 3, tester._max_runs):
if (x.is_zero() or y.is_zero()):
sgn = 1
elif (x.is_even_odd() * y.is_even_odd()):
sgn = (- 1)
else:
sgn = 1
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) - (sgn * v))
jacobiator = {k: v for (k, v) in jac1.items() if v}
tester.assertDictEqual(jacobiator, {})
class ElementMethods():
@abstract_method
def is_even_odd(self):
'\n Return ``0`` if this element is *even* and ``1`` if it is\n *odd*.\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 '
class Graded(GradedModulesCategory):
'\n The category of H-graded super Lie conformal algebras.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(AA).Super().Graded() # needs sage.rings.number_field\n Category of H-graded super Lie conformal algebras over Algebraic Real Field\n '
def _repr_object_names(self):
'\n The names of the objects of this category.\n\n EXAMPLES::\n\n sage: LieConformalAlgebras(QQbar).Graded() # needs sage.rings.number_field\n Category of H-graded Lie conformal algebras over Algebraic Field\n '
return 'H-graded {}'.format(self.base_category()._repr_object_names())
|
class SuperModulesCategory(CovariantConstructionCategory, Category_over_base_ring):
@classmethod
def default_super_categories(cls, category, *args):
'\n Return the default super categories of `F_{Cat}(A,B,...)` for\n `A,B,...` parents in `Cat`.\n\n INPUT:\n\n - ``cls`` -- the category class for the functor `F`\n - ``category`` -- a category `Cat`\n - ``*args`` -- further arguments for the functor\n\n OUTPUT:\n\n A join category.\n\n This implements the property that subcategories constructed by\n the set of whitelisted axioms is a subcategory.\n\n EXAMPLES::\n\n sage: HopfAlgebras(ZZ).WithBasis().FiniteDimensional().Super() # indirect doctest\n Category of finite dimensional super Hopf algebras with basis over Integer Ring\n '
axioms = axiom_whitelist.intersection(category.axioms())
C = super().default_super_categories(category, *args)
return C._with_axioms(axioms)
def __init__(self, base_category):
'\n EXAMPLES::\n\n sage: C = Algebras(QQ).Super()\n sage: C\n Category of super algebras over Rational Field\n sage: C.base_category()\n Category of algebras over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of graded algebras over Rational Field,\n Category of super modules over Rational Field]\n\n sage: AlgebrasWithBasis(QQ).Super().base_ring()\n Rational Field\n sage: HopfAlgebrasWithBasis(QQ).Super().base_ring()\n Rational Field\n '
super().__init__(base_category, base_category.base_ring())
_functor_category = 'Super'
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: AlgebrasWithBasis(QQ).Super() # indirect doctest\n Category of super algebras with basis over Rational Field\n '
return 'super {}'.format(self.base_category()._repr_object_names())
|
class SuperModules(SuperModulesCategory):
'\n The category of super modules.\n\n An `R`-*super module* (where `R` is a ring) is an `R`-module `M` equipped\n with a decomposition `M = M_0 \\oplus M_1` into two `R`-submodules\n `M_0` and `M_1` (called the *even part* and the *odd part* of `M`,\n respectively).\n\n Thus, an `R`-super module automatically becomes a `\\ZZ / 2 \\ZZ`-graded\n `R`-module, with `M_0` being the degree-`0` component and `M_1` being the\n degree-`1` component.\n\n EXAMPLES::\n\n sage: Modules(ZZ).Super()\n Category of super modules over Integer Ring\n sage: Modules(ZZ).Super().super_categories()\n [Category of graded modules over Integer Ring]\n\n The category of super modules defines the super structure which\n shall be preserved by morphisms::\n\n sage: Modules(ZZ).Super().additional_structure()\n Category of super modules over Integer Ring\n\n TESTS::\n\n sage: TestSuite(Modules(ZZ).Super()).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: Modules(ZZ).Super().super_categories()\n [Category of graded modules over Integer Ring]\n\n Nota bene::\n\n sage: Modules(QQ).Super()\n Category of super modules over Rational Field\n sage: Modules(QQ).Super().super_categories()\n [Category of graded modules over Rational Field]\n '
return [self.base_category().Graded()]
def extra_super_categories(self):
"\n Adds :class:`VectorSpaces` to the super categories of ``self`` if\n the base ring is a field.\n\n EXAMPLES::\n\n sage: Modules(QQ).Super().extra_super_categories()\n [Category of vector spaces over Rational Field]\n sage: Modules(ZZ).Super().extra_super_categories()\n []\n\n This makes sure that ``Modules(QQ).Super()`` returns an\n instance of :class:`SuperModules` and not a join category of\n an instance of this class and of ``VectorSpaces(QQ)``::\n\n sage: type(Modules(QQ).Super())\n <class 'sage.categories.super_modules.SuperModules_with_category'>\n\n .. TODO::\n\n Get rid of this workaround once there is a more systematic\n approach for the alias ``Modules(QQ)`` -> ``VectorSpaces(QQ)``.\n Probably the latter should be a category with axiom, and\n covariant constructions should play well with axioms.\n "
from sage.categories.modules import Modules
from sage.categories.fields import Fields
base_ring = self.base_ring()
if (base_ring in Fields()):
return [Modules(base_ring)]
else:
return []
class ParentMethods():
pass
class ElementMethods():
def is_even_odd(self):
'\n Return ``0`` if ``self`` is an even element or ``1``\n if an odd element.\n\n .. NOTE::\n\n The default implementation assumes that the even/odd is\n determined by the parity of :meth:`degree`.\n\n Overwrite this method if the even/odd behavior is desired\n to be independent.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: cat = Algebras(QQ).WithBasis().Super()\n sage: C = CombinatorialFreeModule(QQ, Partitions(), category=cat)\n sage: C.degree_on_basis = sum\n sage: C.basis()[2,2,1].is_even_odd()\n 1\n sage: C.basis()[2,2].is_even_odd()\n 0\n '
return (self.degree() % 2)
def is_even(self):
'\n Return if ``self`` is an even element.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: cat = Algebras(QQ).WithBasis().Super()\n sage: C = CombinatorialFreeModule(QQ, Partitions(), category=cat)\n sage: C.degree_on_basis = sum\n sage: C.basis()[2,2,1].is_even()\n False\n sage: C.basis()[2,2].is_even()\n True\n '
return (self.is_even_odd() == 0)
def is_odd(self):
'\n Return if ``self`` is an odd element.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: cat = Algebras(QQ).WithBasis().Super()\n sage: C = CombinatorialFreeModule(QQ, Partitions(), category=cat)\n sage: C.degree_on_basis = sum\n sage: C.basis()[2,2,1].is_odd()\n True\n sage: C.basis()[2,2].is_odd()\n False\n '
return (self.is_even_odd() == 1)
|
class SuperModulesWithBasis(SuperModulesCategory):
'\n The category of super modules with a distinguished basis.\n\n An `R`-*super module with a distinguished basis* is an\n `R`-super module equipped with an `R`-module basis whose elements are\n homogeneous.\n\n EXAMPLES::\n\n sage: C = GradedModulesWithBasis(QQ); C\n Category of graded vector spaces with basis over Rational Field\n sage: sorted(C.super_categories(), key=str)\n [Category of filtered vector spaces with basis over Rational Field,\n Category of graded modules with basis over Rational Field,\n Category of graded vector spaces over Rational Field]\n sage: C is ModulesWithBasis(QQ).Graded()\n True\n\n TESTS::\n\n sage: TestSuite(C).run()\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 .. NOTE::\n\n The default implementation assumes that the even/odd is\n determined by the parity of :meth:`degree`.\n\n Overwrite this method if the even/odd behavior is desired\n to be independent.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(QQ, 2, [1,2,3])\n sage: C.<x,y> = CliffordAlgebra(Q)\n sage: C._even_odd_on_basis((0,))\n 1\n sage: C._even_odd_on_basis((0,1))\n 0\n '
return (self.degree_on_basis(m) % 2)
class ElementMethods():
def is_super_homogeneous(self):
'\n Return whether this element is homogeneous, in the sense\n of a super module (i.e., is even or odd).\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(QQ, 2, [1,2,3])\n sage: C.<x,y> = CliffordAlgebra(Q)\n sage: a = x + y\n sage: a.is_super_homogeneous()\n True\n sage: a = x*y + 4\n sage: a.is_super_homogeneous()\n True\n sage: a = x*y + x - 3*y + 4\n sage: a.is_super_homogeneous()\n False\n\n The exterior algebra has a `\\ZZ` grading, which induces the\n `\\ZZ / 2\\ZZ` grading. However the definition of homogeneous\n elements differs because of the different gradings::\n\n sage: # needs sage.combinat sage.modules\n sage: E.<x,y> = ExteriorAlgebra(QQ)\n sage: a = x*y + 4\n sage: a.is_super_homogeneous()\n True\n sage: a.is_homogeneous()\n False\n '
even_odd = self.parent()._even_odd_on_basis
degree = None
for m in self.support():
if (degree is None):
degree = even_odd(m)
elif (degree != even_odd(m)):
return False
return True
def is_even_odd(self):
'\n Return ``0`` if ``self`` is an even element and ``1`` if\n ``self`` is an odd element.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(QQ, 2, [1,2,3])\n sage: C.<x,y> = CliffordAlgebra(Q)\n sage: a = x + y\n sage: a.is_even_odd()\n 1\n sage: a = x*y + 4\n sage: a.is_even_odd()\n 0\n sage: a = x + 4\n sage: a.is_even_odd()\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n\n sage: E.<x,y> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: (x*y).is_even_odd() # needs sage.modules\n 0\n '
if (not self.support()):
raise ValueError('the zero element does not have a well-defined degree')
if (not self.is_super_homogeneous()):
raise ValueError('element is not homogeneous')
return self.parent()._even_odd_on_basis(self.leading_support())
def even_component(self):
'\n Return the even component of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(QQ, 2, [1,2,3])\n sage: C.<x,y> = CliffordAlgebra(Q)\n sage: a = x*y + x - 3*y + 4\n sage: a.even_component()\n x*y + 4\n\n TESTS:\n\n Check that this really return ``A.zero()`` and not a plain ``0``::\n\n sage: a = x + y # needs sage.modules\n sage: a.even_component().parent() is C # needs sage.modules\n True\n '
even_odd = self.parent()._even_odd_on_basis
return self.parent().sum_of_terms(((i, c) for (i, c) in self if (even_odd(i) == 0)))
def odd_component(self):
'\n Return the odd component of ``self``.\n\n EXAMPLES::\n\n sage: # needs sage.modules\n sage: Q = QuadraticForm(QQ, 2, [1,2,3])\n sage: C.<x,y> = CliffordAlgebra(Q)\n sage: a = x*y + x - 3*y + 4\n sage: a.odd_component()\n x - 3*y\n\n TESTS:\n\n Check that this really return ``A.zero()`` and not a plain ``0``::\n\n sage: a = x*y # needs sage.modules\n sage: a.odd_component().parent() is C # needs sage.modules\n True\n '
even_odd = self.parent()._even_odd_on_basis
return self.parent().sum_of_terms(((i, c) for (i, c) in self if (even_odd(i) == 1)))
|
class SupercommutativeAlgebras(CategoryWithAxiom_over_base_ring):
"\n The category of supercommutative algebras.\n\n An `R`-*supercommutative algebra* is an `R`-super algebra\n `A = A_0 \\oplus A_1` endowed with an `R`-super algebra structure\n satisfying:\n\n .. MATH::\n\n x_0 x'_0 = x'_0 x_0, \\qquad\n x_1 x'_1 = -x'_1 x_1, \\qquad\n x_0 x_1 = x_1 x_0,\n\n for all `x_0, x'_0 \\in A_0` and `x_1, x'_1 \\in A_1`.\n\n EXAMPLES::\n\n sage: Algebras(ZZ).Supercommutative()\n Category of supercommutative algebras over Integer Ring\n\n TESTS::\n\n sage: TestSuite(Algebras(ZZ).Supercommutative()).run()\n "
_base_category_class_and_axiom = (SuperAlgebras, 'Supercommutative')
class SignedTensorProducts(SignedTensorProductsCategory):
@cached_method
def extra_super_categories(self):
'\n Return the extra super categories of ``self``.\n\n A signed tensor product of supercommutative algebras is a\n supercommutative algebra.\n\n EXAMPLES::\n\n sage: C = Algebras(ZZ).Supercommutative().SignedTensorProducts()\n sage: C.extra_super_categories()\n [Category of supercommutative algebras over Integer Ring]\n '
return [self.base_category()]
class WithBasis(CategoryWithAxiom_over_base_ring):
class ParentMethods():
def _test_supercommutativity(self, **options):
'\n Test supercommutativity for (not necessarily all) elements\n of this supercommutative algebra.\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: E.<x,y,z> = ExteriorAlgebra(QQ) # needs sage.modules\n sage: E._test_supercommutativity() # needs sage.modules\n\n However, the elements tested can be customized with the\n ``elements`` keyword argument, but the elements must be\n homogeneous::\n\n sage: E._test_supercommutativity(elements=[x+y, x*y-3*y*z, x*y*z]) # needs sage.modules\n sage: E._test_supercommutativity(elements=[x+x*y]) # needs sage.modules\n Traceback (most recent call last):\n ...\n ValueError: element is not homogeneous\n\n See the documentation for :class:`TestSuite` for more information.\n '
elements = options.pop('elements', self.basis())
tester = self._tester(**options)
from sage.misc.misc import some_tuples
for (x, y) in some_tuples(elements, 2, tester._max_runs):
tester.assertEqual((x * y), (((- 1) ** (x.is_even_odd() * y.is_even_odd())) * (y * x)))
|
class SuperCrystals(Category_singleton):
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.supercrystals import SuperCrystals\n sage: C = SuperCrystals()\n sage: C.super_categories()\n [Category of crystals]\n '
return [Crystals()]
class ParentMethods():
def tensor(self, *crystals, **options):
"\n Return the tensor product of ``self`` with the crystals ``B``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A',[1,2]])\n sage: C = crystals.Tableaux(['A',[1,2]], shape = [2,1])\n sage: T = C.tensor(B); T\n Full tensor product of the crystals\n [Crystal of BKK tableaux of shape [2, 1] of gl(2|3),\n The crystal of letters for type ['A', [1, 2]]]\n sage: S = B.tensor(C); S\n Full tensor product of the crystals\n [The crystal of letters for type ['A', [1, 2]],\n Crystal of BKK tableaux of shape [2, 1] of gl(2|3)]\n sage: G = T.digraph()\n sage: H = S.digraph()\n sage: G.is_isomorphic(H, edge_labels= True)\n True\n "
cartan_type = self.cartan_type()
if any(((c.cartan_type() != cartan_type) for c in crystals)):
raise ValueError('all crystals must be of the same Cartan type')
if (cartan_type.letter == 'Q'):
from sage.combinat.crystals.tensor_product import FullTensorProductOfQueerSuperCrystals
return FullTensorProductOfQueerSuperCrystals(((self,) + tuple(crystals)), **options)
else:
from sage.combinat.crystals.tensor_product import FullTensorProductOfSuperCrystals
return FullTensorProductOfSuperCrystals(((self,) + tuple(crystals)), **options)
class Finite(CategoryWithAxiom):
class ParentMethods():
@cached_method(key=(lambda s, i: (tuple(i) if (i is not None) else s.index_set())))
def digraph(self, index_set=None):
"\n Return the :class:`DiGraph` associated to ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,3]])\n sage: G = B.digraph(); G\n Multi-digraph on 6 vertices\n sage: Q = crystals.Letters(['Q',3])\n sage: G = Q.digraph(); G\n Multi-digraph on 3 vertices\n sage: G.edges(sort=True)\n [(1, 2, -1), (1, 2, 1), (2, 3, -2), (2, 3, 2)]\n\n The edges of the crystal graph are by default colored using\n blue for edge 1, red for edge 2, green for edge 3, and dashed with\n the corresponding color for barred edges. Edge 0 is dotted black::\n\n sage: view(G) # optional - dot2tex graphviz, not tested (opens external window)\n "
from sage.graphs.digraph import DiGraph
from sage.misc.latex import LatexExpr
from sage.combinat.root_system.cartan_type import CartanType
if (index_set is None):
index_set = self.index_set()
G = DiGraph(multiedges=True)
G.add_vertices(self)
for i in index_set:
for x in G:
y = x.f(i)
if (y is not None):
G.add_edge(x, y, i)
def edge_options(data):
(u, v, l) = data
edge_opts = {'edge_string': '->', 'color': 'black'}
if (l > 0):
edge_opts['color'] = CartanType._colors.get(l, 'black')
edge_opts['label'] = LatexExpr(str(l))
elif (l < 0):
edge_opts['color'] = ('dashed,' + CartanType._colors.get((- l), 'black'))
edge_opts['label'] = LatexExpr(('\\overline{%s}' % str((- l))))
else:
edge_opts['color'] = ('dotted,' + CartanType._colors.get(l, 'black'))
edge_opts['label'] = LatexExpr(str(l))
return edge_opts
G.set_latex_options(format='dot2tex', edge_labels=True, edge_options=edge_options)
return G
def genuine_highest_weight_vectors(self):
"\n Return the tuple of genuine highest weight elements of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B.genuine_highest_weight_vectors()\n (-2,)\n\n sage: T = B.tensor(B)\n sage: T.genuine_highest_weight_vectors()\n ([-2, -1], [-2, -2])\n sage: s1, s2 = T.connected_components()\n sage: s = s1 + s2\n sage: s.genuine_highest_weight_vectors()\n ([-2, -1], [-2, -2])\n "
return tuple([x[0] for x in self._genuine_highest_lowest_weight_vectors()])
connected_components_generators = genuine_highest_weight_vectors
def connected_components(self):
"\n Return the connected components of ``self`` as subcrystals.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B.connected_components()\n [Subcrystal of The crystal of letters for type ['A', [1, 2]]]\n\n sage: T = B.tensor(B)\n sage: T.connected_components()\n [Subcrystal of Full tensor product of the crystals\n [The crystal of letters for type ['A', [1, 2]],\n The crystal of letters for type ['A', [1, 2]]],\n Subcrystal of Full tensor product of the crystals\n [The crystal of letters for type ['A', [1, 2]],\n The crystal of letters for type ['A', [1, 2]]]]\n "
category = SuperCrystals()
from sage.categories.regular_supercrystals import RegularSuperCrystals
if (self in RegularSuperCrystals()):
category = RegularSuperCrystals()
index_set = self.index_set()
cartan_type = self.cartan_type()
CCs = []
for mg in self.connected_components_generators():
if (not isinstance(mg, tuple)):
mg = (mg,)
subcrystal = self.subcrystal(generators=mg, index_set=index_set, cartan_type=cartan_type, category=category)
CCs.append(subcrystal)
return CCs
def genuine_lowest_weight_vectors(self):
"\n Return the tuple of genuine lowest weight elements of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B.genuine_lowest_weight_vectors()\n (3,)\n\n sage: T = B.tensor(B)\n sage: T.genuine_lowest_weight_vectors()\n ([3, 3], [3, 2])\n sage: s1, s2 = T.connected_components()\n sage: s = s1 + s2\n sage: s.genuine_lowest_weight_vectors()\n ([3, 3], [3, 2])\n "
return tuple([x[1] for x in self._genuine_highest_lowest_weight_vectors()])
@cached_method
def _genuine_highest_lowest_weight_vectors(self):
"\n Return the genuine lowest and highest weight elements of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B._genuine_highest_lowest_weight_vectors()\n ((-2, 3),)\n\n sage: T = B.tensor(B)\n sage: T._genuine_highest_lowest_weight_vectors()\n (([-2, -1], [3, 3]), ([-2, -2], [3, 2]))\n sage: s1, s2 = T.connected_components()\n sage: s = s1 + s2\n sage: s._genuine_highest_lowest_weight_vectors()\n (([-2, -1], [3, 3]), ([-2, -2], [3, 2]))\n\n An example with fake highest/lowest weight elements\n from [BKK2000]_::\n\n sage: B = crystals.Tableaux(['A', [1,1]], shape=[3,2,1])\n sage: B._genuine_highest_lowest_weight_vectors()\n (([[-2, -2, -2], [-1, -1], [1]], [[-1, 1, 2], [1, 2], [2]]),)\n "
X = []
for G in self.digraph().connected_components_subgraphs():
src = G.sources()
sinks = G.sinks()
max_dist = (- 1)
pair = None
for s in src:
for t in sinks:
d = G.distance(s, t)
if ((d < float('inf')) and (d > max_dist)):
pair = (s, t)
max_dist = d
X.append(pair)
return tuple(X)
def character(self):
"\n Return the character of ``self``.\n\n .. TODO::\n\n Once the `WeylCharacterRing` is implemented, make this\n consistent with the implementation in\n :meth:`sage.categories.classical_crystals.ClassicalCrystals.ParentMethods.character`.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A',[1,2]])\n sage: B.character()\n B[(1, 0, 0, 0, 0)] + B[(0, 1, 0, 0, 0)] + B[(0, 0, 1, 0, 0)]\n + B[(0, 0, 0, 1, 0)] + B[(0, 0, 0, 0, 1)]\n "
from sage.rings.integer_ring import ZZ
A = self.weight_lattice_realization().algebra(ZZ)
return A.sum((A(x.weight()) for x in self))
@cached_method
def highest_weight_vectors(self):
"\n Return the highest weight vectors of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B.highest_weight_vectors()\n (-2,)\n\n sage: T = B.tensor(B)\n sage: T.highest_weight_vectors()\n ([-2, -2], [-2, -1])\n\n We give an example from [BKK2000]_ that has fake\n highest weight vectors::\n\n sage: B = crystals.Tableaux(['A', [1,1]], shape=[3,2,1])\n sage: B.highest_weight_vectors()\n ([[-2, -2, -2], [-1, -1], [1]],\n [[-2, -2, -2], [-1, 2], [1]],\n [[-2, -2, 2], [-1, -1], [1]])\n sage: B.genuine_highest_weight_vectors()\n ([[-2, -2, -2], [-1, -1], [1]],)\n "
return tuple(self.digraph().sources())
@cached_method
def lowest_weight_vectors(self):
"\n Return the lowest weight vectors of ``self``.\n\n EXAMPLES::\n\n sage: B = crystals.Letters(['A', [1,2]])\n sage: B.lowest_weight_vectors()\n (3,)\n\n sage: T = B.tensor(B)\n sage: sorted(T.lowest_weight_vectors())\n [[3, 2], [3, 3]]\n\n We give an example from [BKK2000]_ that has fake\n lowest weight vectors::\n\n sage: B = crystals.Tableaux(['A', [1,1]], shape=[3,2,1])\n sage: sorted(B.lowest_weight_vectors())\n [[[-2, 1, 2], [-1, 2], [1]],\n [[-2, 1, 2], [-1, 2], [2]],\n [[-1, 1, 2], [1, 2], [2]]]\n sage: B.genuine_lowest_weight_vectors()\n ([[-1, 1, 2], [1, 2], [2]],)\n "
return tuple(self.digraph().sinks())
class ElementMethods():
def is_genuine_highest_weight(self, index_set=None):
'\n Return whether ``self`` is a genuine highest weight element.\n\n INPUT:\n\n - ``index_set`` -- (optional) the index set of the (sub)crystal\n on which to check\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux([\'A\', [1,1]], shape=[3,2,1])\n sage: for b in B.highest_weight_vectors():\n ....: print("{} {}".format(b, b.is_genuine_highest_weight()))\n [[-2, -2, -2], [-1, -1], [1]] True\n [[-2, -2, -2], [-1, 2], [1]] False\n [[-2, -2, 2], [-1, -1], [1]] False\n sage: [b for b in B if b.is_genuine_highest_weight([-1,0])]\n [[[-2, -2, -2], [-1, -1], [1]],\n [[-2, -2, -2], [-1, -1], [2]],\n [[-2, -2, -2], [-1, 2], [2]],\n [[-2, -2, 2], [-1, -1], [2]],\n [[-2, -2, 2], [-1, 2], [2]],\n [[-2, -2, -2], [-1, 2], [1]],\n [[-2, -2, 2], [-1, -1], [1]],\n [[-2, -2, 2], [-1, 2], [1]]]\n '
P = self.parent()
if ((index_set is None) or (set(index_set) == set(P.index_set()))):
return (self in P.genuine_highest_weight_vectors())
S = P.subcrystal(generators=P, index_set=index_set, category=P.category())
return any(((self == x.value) for x in S.genuine_highest_weight_vectors()))
def is_genuine_lowest_weight(self, index_set=None):
'\n Return whether ``self`` is a genuine lowest weight element.\n\n INPUT:\n\n - ``index_set`` -- (optional) the index set of the (sub)crystal\n on which to check\n\n EXAMPLES::\n\n sage: B = crystals.Tableaux([\'A\', [1,1]], shape=[3,2,1])\n sage: for b in sorted(B.lowest_weight_vectors()):\n ....: print("{} {}".format(b, b.is_genuine_lowest_weight()))\n [[-2, 1, 2], [-1, 2], [1]] False\n [[-2, 1, 2], [-1, 2], [2]] False\n [[-1, 1, 2], [1, 2], [2]] True\n sage: [b for b in B if b.is_genuine_lowest_weight([-1,0])]\n [[[-2, -1, 1], [-1, 1], [1]],\n [[-2, -1, 1], [-1, 1], [2]],\n [[-2, 1, 2], [-1, 1], [2]],\n [[-2, 1, 2], [-1, 1], [1]],\n [[-1, -1, 1], [1, 2], [2]],\n [[-1, -1, 1], [1, 2], [1]],\n [[-1, 1, 2], [1, 2], [2]],\n [[-1, 1, 2], [1, 2], [1]]]\n '
P = self.parent()
if ((index_set is None) or (set(index_set) == set(P.index_set()))):
return (self in P.genuine_lowest_weight_vectors())
S = P.subcrystal(generators=P, index_set=index_set, category=P.category())
return any(((self == x.value) for x in S.genuine_lowest_weight_vectors()))
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.supercrystals import SuperCrystals\n sage: SuperCrystals().TensorProducts().extra_super_categories()\n [Category of super crystals]\n '
return [self.base_category()]
|
class TensorProductFunctor(CovariantFunctorialConstruction):
'\n A singleton class for the tensor functor.\n\n This functor takes a collection of vector spaces (or modules with\n basis), and constructs the tensor product of those vector spaces.\n If this vector space is in a subcategory, say that of\n ``Algebras(QQ)``, it is automatically endowed with its natural\n algebra structure, thanks to the category\n ``Algebras(QQ).TensorProducts()`` of tensor products of algebras.\n For elements, it constructs the natural tensor product element in the\n corresponding tensor product of their parents.\n\n The tensor functor is covariant: if ``A`` is a subcategory of ``B``, then\n ``A.TensorProducts()`` is a subcategory of ``B.TensorProducts()`` (see\n also\n :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`). Hence,\n the role of ``Algebras(QQ).TensorProducts()`` is solely to provide\n mathematical information and algorithms which are relevant to tensor\n product of algebras.\n\n Those are implemented in the nested class\n :class:`~sage.categories.algebras.Algebras.TensorProducts`\n of ``Algebras(QQ)``. This nested class is itself a subclass of\n :class:`~sage.categories.tensor.TensorProductsCategory`.\n\n\n TESTS::\n\n sage: TestSuite(tensor).run()\n '
_functor_name = 'tensor'
_functor_category = 'TensorProducts'
symbol = ' # '
unicode_symbol = f' {unicode_otimes} '
|
class TensorProductsCategory(CovariantConstructionCategory):
"\n An abstract base class for all TensorProducts's categories\n\n TESTS::\n\n sage: C = ModulesWithBasis(QQ).TensorProducts()\n sage: C\n Category of tensor products of vector spaces with basis over Rational Field\n sage: C.base_category()\n Category of vector spaces with basis over Rational Field\n sage: latex(C)\n \\mathbf{TensorProducts}(\\mathbf{WithBasis}_{\\Bold{Q}})\n sage: TestSuite(C).run()\n "
_functor_category = 'TensorProducts'
def TensorProducts(self):
"\n Returns the category of tensor products of objects of ``self``\n\n By associativity of tensor products, this is ``self`` (a tensor\n product of tensor products of `Cat`'s is a tensor product of `Cat`'s)\n\n EXAMPLES::\n\n sage: ModulesWithBasis(QQ).TensorProducts().TensorProducts()\n Category of tensor products of vector spaces with basis over Rational Field\n "
return self
def base(self):
'\n The base of a tensor product is the base (usually a ring) of the underlying category.\n\n EXAMPLES::\n\n sage: ModulesWithBasis(ZZ).TensorProducts().base()\n Integer Ring\n '
return self.base_category().base()
|
class TopologicalSpacesCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Topological'
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Groups().Topological() # indirect doctest\n Category of topological groups\n '
return 'topological {}'.format(self.base_category()._repr_object_names())
|
class TopologicalSpaces(TopologicalSpacesCategory):
'\n The category of topological spaces.\n\n EXAMPLES::\n\n sage: Sets().Topological()\n Category of topological spaces\n sage: Sets().Topological().super_categories()\n [Category of sets]\n\n The category of topological spaces defines the topological structure,\n which shall be preserved by morphisms::\n\n sage: Sets().Topological().additional_structure()\n Category of topological spaces\n\n TESTS::\n\n sage: TestSuite(Sets().Topological()).run()\n '
_base_category_class = (Sets,)
def _repr_object_names(self):
'\n EXAMPLES::\n\n sage: Sets().Topological() # indirect doctest\n Category of topological spaces\n '
return 'topological spaces'
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a (finite) Cartesian product of topological spaces is\n a topological space.\n\n EXAMPLES::\n\n sage: from sage.categories.topological_spaces import TopologicalSpaces\n sage: C = TopologicalSpaces().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of topological spaces]\n sage: C.super_categories()\n [Category of Cartesian products of sets, Category of topological spaces]\n sage: C.axioms()\n frozenset()\n '
return [TopologicalSpaces()]
class SubcategoryMethods():
@cached_method
def Connected(self):
"\n Return the full subcategory of the connected objects of ``self``.\n\n EXAMPLES::\n\n sage: Sets().Topological().Connected()\n Category of connected topological spaces\n\n TESTS::\n\n sage: TestSuite(Sets().Topological().Connected()).run()\n sage: Sets().Topological().Connected.__module__\n 'sage.categories.topological_spaces'\n "
return self._with_axiom('Connected')
@cached_method
def Compact(self):
"\n Return the subcategory of the compact objects of ``self``.\n\n EXAMPLES::\n\n sage: Sets().Topological().Compact()\n Category of compact topological spaces\n\n TESTS::\n\n sage: TestSuite(Sets().Topological().Compact()).run()\n sage: Sets().Topological().Compact.__module__\n 'sage.categories.topological_spaces'\n "
return self._with_axiom('Compact')
class Connected(CategoryWithAxiom):
'\n The category of connected topological spaces.\n '
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a (finite) Cartesian product of connected\n topological spaces is connected.\n\n EXAMPLES::\n\n sage: from sage.categories.topological_spaces import TopologicalSpaces\n sage: C = TopologicalSpaces().Connected().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of connected topological spaces]\n sage: C.super_categories()\n [Category of Cartesian products of topological spaces,\n Category of connected topological spaces]\n sage: C.axioms()\n frozenset({'Connected'})\n "
return [TopologicalSpaces().Connected()]
class Compact(CategoryWithAxiom):
'\n The category of compact topological spaces.\n '
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
"\n Implement the fact that a (finite) Cartesian product of compact\n topological spaces is compact.\n\n EXAMPLES::\n\n sage: from sage.categories.topological_spaces import TopologicalSpaces\n sage: C = TopologicalSpaces().Compact().CartesianProducts()\n sage: C.extra_super_categories()\n [Category of compact topological spaces]\n sage: C.super_categories()\n [Category of Cartesian products of topological spaces,\n Category of compact topological spaces]\n sage: C.axioms()\n frozenset({'Compact'})\n "
return [TopologicalSpaces().Compact()]
|
class TriangularKacMoodyAlgebras(Category_over_base_ring):
'\n Category of Kac-Moody algebras with a distinguished basis that\n respects the triangular decomposition.\n\n We require that the grading group is the root lattice of the\n appropriate Cartan type.\n '
@cached_method
def super_categories(self):
'\n EXAMPLES::\n\n sage: from sage.categories.triangular_kac_moody_algebras import TriangularKacMoodyAlgebras\n sage: TriangularKacMoodyAlgebras(QQ).super_categories()\n [Join of Category of graded Lie algebras with basis over Rational Field\n and Category of kac moody algebras over Rational Field]\n\n '
return [KacMoodyAlgebras(self.base_ring()).WithBasis().Graded()]
class ParentMethods():
def _part_on_basis(self, m):
'\n Return whether the basis element indexed by ``m`` is\n in the lower, zero, or upper part of ``self``.\n\n OUTPUT:\n\n `-1` if ``m`` is a negative root, `0` if zero, or `1`\n if ``m`` is a positive root\n\n EXAMPLES::\n\n sage: L = lie_algebras.so(QQ, 5) # needs sage.combinat sage.modules\n sage: L.f() # needs sage.combinat sage.modules\n Finite family {1: E[-alpha[1]], 2: E[-alpha[2]]}\n sage: L.f(1) # needs sage.combinat sage.modules\n E[-alpha[1]]\n '
deg = self.degree_on_basis(m)
if (not deg):
return 0
return (1 if deg.is_positive_root() else (- 1))
@cached_method
def _part_generators(self, positive=False):
"\n Return the Lie algebra generators for the positive or\n negative half of ``self``.\n\n .. NOTE::\n\n If the positive/negative generators correspond to the\n generators with (negative) simple roots, then this method\n will find them. If they do not, then this method *must*\n be overwritten. One should also overwrite this method in\n object classes when there is a better method to obtain them.\n Furthermore, this assumes that :meth:`lie_algebra_generators`\n is a finite set.\n\n INPUT:\n\n - ``positive`` -- boolean (default: ``False``); if ``True``\n then return positive part generators, otherwise the return\n the negative part generators\n\n OUTPUT:\n\n A :func:`~sage.sets.family.Family` whose keys are the\n index set of ``self``.\n\n EXAMPLES::\n\n sage: L = LieAlgebra(QQ, cartan_type=['E', 6]) # needs sage.combinat sage.modules\n sage: list(L._part_generators(False)) # needs sage.combinat sage.modules\n [E[-alpha[1]], E[-alpha[2]], E[-alpha[3]],\n E[-alpha[4]], E[-alpha[5]], E[-alpha[6]]]\n "
I = self._cartan_type.index_set()
P = self._cartan_type.root_system().root_lattice()
ali = P.simple_roots().inverse_family()
if positive:
d = {ali[g.degree()]: g for g in self.lie_algebra_generators() if (self._part(g) > 0)}
if (not positive):
d = {ali[(- g.degree())]: g for g in self.lie_algebra_generators() if (self._part(g) < 0)}
from sage.sets.family import Family
return Family(I, d.__getitem__)
def e(self, i=None):
'\n Return the generators `e` of ``self``.\n\n INPUT:\n\n - ``i`` -- (optional) if specified, return just the\n generator `e_i`\n\n EXAMPLES::\n\n sage: L = lie_algebras.so(QQ, 5) # needs sage.combinat sage.modules\n sage: L.e() # needs sage.combinat sage.modules\n Finite family {1: E[alpha[1]], 2: E[alpha[2]]}\n sage: L.e(1) # needs sage.combinat sage.modules\n E[alpha[1]]\n '
E = self._part_generators(True)
if (i is None):
return E
return E[i]
def f(self, i=None):
'\n Return the generators `f` of ``self``.\n\n INPUT:\n\n - ``i`` -- (optional) if specified, return just the\n generator `f_i`\n\n EXAMPLES::\n\n sage: L = lie_algebras.so(QQ, 5) # needs sage.combinat sage.modules\n sage: L.f() # needs sage.combinat sage.modules\n Finite family {1: E[-alpha[1]], 2: E[-alpha[2]]}\n sage: L.f(1) # needs sage.combinat sage.modules\n E[-alpha[1]]\n '
F = self._part_generators(False)
if (i is None):
return F
return F[i]
@abstract_method
def _negative_half_index_set(self):
'\n Return an indexing set for the negative half of ``self``.\n\n EXAMPLES::\n\n sage: L = lie_algebras.so(QQ, 5) # needs sage.combinat sage.modules\n sage: L._negative_half_index_set() # needs sage.combinat sage.modules\n [-alpha[2], -alpha[1], -alpha[1] - alpha[2],\n -alpha[1] - 2*alpha[2]]\n '
@abstract_method
def _weight_action(self, m, wt):
'\n Return the action of the basis element indexed by ``m`` on ``wt``.\n\n INPUT:\n\n - ``m`` -- an index of a basis element of the Cartan subalgebra\n - ``wt`` -- a weight\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.sp(QQ, 6)\n sage: La = L.cartan_type().root_system().weight_space().fundamental_weights()\n sage: mu = La[1] - 3/5*La[2]\n sage: ac = L.cartan_type().root_system().coroot_lattice().simple_roots()\n sage: L._weight_action(ac[1], mu)\n 1\n sage: L._weight_action(ac[2], mu)\n -3/5\n sage: L._weight_action(ac[3], mu)\n 0\n '
def verma_module(self, la, basis_key=None, **kwds):
"\n Return the Verma module with highest weight ``la``\n over ``self``.\n\n INPUT:\n\n - ``basis_key`` -- (optional) a key function for the indexing\n set of the basis elements of ``self``\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = lie_algebras.sl(QQ, 3)\n sage: P = L.cartan_type().root_system().weight_lattice()\n sage: La = P.fundamental_weights()\n sage: M = L.verma_module(La[1] + La[2])\n sage: M\n Verma module with highest weight Lambda[1] + Lambda[2]\n of Lie algebra of ['A', 2] in the Chevalley basis\n "
from sage.algebras.lie_algebras.verma_module import VermaModule
return VermaModule(self, la, basis_key=basis_key, **kwds)
class ElementMethods():
def part(self):
'\n Return whether the element ``v`` is in the lower,\n zero, or upper part of ``self``.\n\n OUTPUT:\n\n `-1` if ``v`` is in the lower part, `0` if in the\n zero part, or `1` if in the upper part\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: L = LieAlgebra(QQ, cartan_type="F4")\n sage: L.inject_variables()\n Defining e1, e2, e3, e4, f1, f2, f3, f4, h1, h2, h3, h4\n sage: e1.part()\n 1\n sage: f4.part()\n -1\n sage: (h2 + h3).part()\n 0\n sage: (f1.bracket(f2) + 4*f4).part()\n -1\n sage: (e1 + f1).part()\n Traceback (most recent call last):\n ...\n ValueError: element is not in one part\n '
P = self.parent()
S = [P._part_on_basis(m) for m in self.support()]
if all(((k < 0) for k in S)):
return (- 1)
if all(((k > 0) for k in S)):
return 1
if all(((k == 0) for k in S)):
return 0
raise ValueError('element is not in one part')
|
class UniqueFactorizationDomains(Category_singleton):
'\n The category of (constructive) unique factorization domains.\n\n In a constructive unique factorization domain we can\n constructively factor members into a product of a finite number\n of irreducible elements.\n\n EXAMPLES::\n\n sage: UniqueFactorizationDomains()\n Category of unique factorization domains\n sage: UniqueFactorizationDomains().super_categories()\n [Category of gcd domains]\n\n TESTS::\n\n sage: TestSuite(UniqueFactorizationDomains()).run()\n\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: UniqueFactorizationDomains().super_categories()\n [Category of gcd domains]\n '
return [GcdDomains()]
def additional_structure(self):
'\n Return whether ``self`` is a structure category.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n The category of unique factorization domains does not define\n additional structure: a ring morphism between unique factorization\n domains is a unique factorization domain morphism.\n\n EXAMPLES::\n\n sage: UniqueFactorizationDomains().additional_structure()\n '
return None
def __contains__(self, x):
'\n EXAMPLES::\n\n sage: GF(4, "a") in UniqueFactorizationDomains() # needs sage.rings.finite_rings\n True\n sage: QQ in UniqueFactorizationDomains()\n True\n sage: ZZ in UniqueFactorizationDomains()\n True\n sage: IntegerModRing(4) in UniqueFactorizationDomains()\n False\n sage: IntegerModRing(5) in UniqueFactorizationDomains()\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:`UniqueFactorizationDomains() <UniqueFactorizationDomains>`.\n '
try:
return (self._contains_helper(x) or x.is_unique_factorization_domain())
except Exception:
return False
@lazy_class_attribute
def _contains_helper(cls):
"\n Helper for containment tests in the category of unique\n factorization 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 unique factorization domains. There are, however, rings that\n are initialised as plain commutative rings and found out to be\n unique factorization domains only afterwards. Hence, this helper\n alone is not enough 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 = UniqueFactorizationDomains()\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_unique_factorization_domain(self, proof=True):
'\n Return True, since this in an object of the category of unique factorization domains.\n\n EXAMPLES::\n\n sage: UFD = UniqueFactorizationDomains()\n sage: Parent(QQ, category=UFD).is_unique_factorization_domain()\n True\n\n '
return True
def _gcd_univariate_polynomial(self, f, g):
'\n Return the greatest common divisor of ``f`` and ``g``.\n\n INPUT:\n\n - ``f``, ``g`` -- two polynomials defined over this UFD.\n\n .. NOTE::\n\n This is a helper method for\n :meth:`sage.rings.polynomial.polynomial_element.Polynomial.gcd`.\n\n ALGORITHM:\n\n Algorithm 3.3.1 in [Coh1993]_, based on pseudo-division.\n\n EXAMPLES::\n\n sage: R.<x> = PolynomialRing(ZZ, sparse=True)\n sage: S.<T> = R[]\n sage: p = (-3*x^2 - x)*T^3 - 3*x*T^2 + (x^2 - x)*T + 2*x^2 + 3*x - 2\n sage: q = (-x^2 - 4*x - 5)*T^2 + (6*x^2 + x + 1)*T + 2*x^2 - x\n sage: quo,rem=p.pseudo_quo_rem(q); quo,rem\n ((3*x^4 + 13*x^3 + 19*x^2 + 5*x)*T + 18*x^4 + 12*x^3 + 16*x^2 + 16*x,\n (-113*x^6 - 106*x^5 - 133*x^4 - 101*x^3 - 42*x^2 - 41*x)*T\n - 34*x^6 + 13*x^5 + 54*x^4 + 126*x^3 + 134*x^2 - 5*x - 50)\n sage: (-x^2 - 4*x - 5)^(3-2+1) * p == quo*q + rem\n True\n\n Check that :trac:`23620` has been resolved::\n\n sage: # needs sage.rings.padics\n sage: R.<x> = ZpFM(2)[]\n sage: f = 2*x + 2\n sage: g = 4*x + 2\n sage: f.gcd(g).parent() is R\n True\n\n '
if (f.degree() < g.degree()):
(A, B) = (g, f)
else:
(A, B) = (f, g)
if B.is_zero():
return A
a = b = self.zero()
for c in A.coefficients():
a = a.gcd(c)
if a.is_one():
break
for c in B.coefficients():
b = b.gcd(c)
if b.is_one():
break
d = a.gcd(b)
A = (A // a)
B = (B // b)
g = h = 1
delta = (A.degree() - B.degree())
(_, R) = A.pseudo_quo_rem(B)
while (R.degree() > 0):
A = B
B = (R // (g * (h ** delta)))
g = A.leading_coefficient()
h = ((h * (g ** delta)) // (h ** delta))
delta = (A.degree() - B.degree())
(_, R) = A.pseudo_quo_rem(B)
if R.is_zero():
b = self.zero()
for c in B.coefficients():
b = b.gcd(c)
if b.is_one():
break
return ((d * B) // b)
return f.parent()(d)
class ElementMethods():
def radical(self, *args, **kwds):
'\n Return the radical of this element, i.e. the product of its\n irreducible factors.\n\n This default implementation calls ``squarefree_decomposition`` if\n available, and ``factor`` otherwise.\n\n .. SEEALSO:: :meth:`squarefree_part`\n\n EXAMPLES::\n\n sage: Pol.<x> = QQ[]\n sage: (x^2*(x-1)^3).radical()\n x^2 - x\n sage: pol = 37 * (x-1)^3 * (x-2)^2 * (x-1/3)^7 * (x-3/7)\n sage: pol.radical()\n 37*x^4 - 2923/21*x^3 + 1147/7*x^2 - 1517/21*x + 74/7\n\n sage: Integer(10).radical()\n 10\n sage: Integer(-100).radical()\n 10\n sage: Integer(0).radical()\n Traceback (most recent call last):\n ...\n ArithmeticError: radical of 0 is not defined\n\n The next example shows how to compute the radical of a number,\n assuming no prime > 100000 has exponent > 1 in the factorization::\n\n sage: n = 2^1000-1; n / radical(n, limit=100000)\n 125\n\n TESTS::\n\n sage: radical(pol)\n 37*x^4 - 2923/21*x^3 + 1147/7*x^2 - 1517/21*x + 74/7\n\n sage: Integer(20).radical()\n 10\n '
if self.is_zero():
raise ArithmeticError('radical of 0 is not defined')
try:
decomp = self.squarefree_decomposition()
except AttributeError:
return self.factor(*args, **kwds).radical_value()
else:
return prod((fac for (fac, mult) in decomp))
def squarefree_part(self):
'\n Return the square-free part of this element, i.e. the product\n of its irreducible factors appearing with odd multiplicity.\n\n This default implementation calls ``squarefree_decomposition``.\n\n .. SEEALSO:: :meth:`radical`\n\n EXAMPLES::\n\n sage: Pol.<x> = QQ[]\n sage: (x^2*(x-1)^3).squarefree_part()\n x - 1\n sage: pol = 37 * (x-1)^3 * (x-2)^2 * (x-1/3)^7 * (x-3/7)\n sage: pol.squarefree_part()\n 37*x^3 - 1369/21*x^2 + 703/21*x - 37/7\n\n TESTS::\n\n sage: squarefree_part(pol)\n 37*x^3 - 1369/21*x^2 + 703/21*x - 37/7\n\n '
decomp = self.squarefree_decomposition()
return prod((fac for (fac, mult) in decomp if ((mult % 2) == 1)))
|
class UnitalAlgebras(CategoryWithAxiom_over_base_ring):
'\n The category of non-associative algebras over a given base ring.\n\n A non-associative algebra over a ring `R` is a module over `R`\n which is also a unital magma.\n\n .. WARNING::\n\n Until :trac:`15043` is implemented, :class:`Algebras` is the\n category of associative unital algebras; thus, unlike the name\n suggests, :class:`UnitalAlgebras` is not a subcategory of\n :class:`Algebras` but of\n :class:`~.magmatic_algebras.MagmaticAlgebras`.\n\n EXAMPLES::\n\n sage: from sage.categories.unital_algebras import UnitalAlgebras\n sage: C = UnitalAlgebras(ZZ); C\n Category of unital algebras over Integer Ring\n\n TESTS::\n\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: C is MagmaticAlgebras(ZZ).Unital()\n True\n sage: TestSuite(C).run()\n '
_base_category_class_and_axiom = (MagmaticAlgebras, 'Unital')
class ParentMethods():
def from_base_ring(self, r):
"\n Return the canonical embedding of ``r`` into ``self``.\n\n INPUT:\n\n - ``r`` -- an element of ``self.base_ring()``\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.from_base_ring(1) # needs sage.combinat sage.modules\n B[word: ]\n "
return self.one()._lmul_(r)
def __init_extra__(self):
"\n Declare the canonical coercion from ``self.base_ring()``\n to ``self``, if there has been none before.\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: coercion_model = sage.structure.element.get_coercion_model()\n sage: coercion_model.discover_coercion(QQ, A) # needs sage.combinat sage.modules\n ((map internal to coercion system -- copy before use)\n Generic morphism:\n From: Rational Field\n To: An example of an algebra with basis:\n the free algebra on the generators ('a', 'b', 'c') over Rational Field,\n None)\n sage: A(1) # indirect doctest # needs sage.combinat sage.modules\n B[word: ]\n\n TESTS:\n\n Ensure that :trac:`28328` is fixed and that non-associative\n algebras are supported::\n\n sage: # needs sage.modules\n sage: class Foo(CombinatorialFreeModule):\n ....: def one(self):\n ....: return self.monomial(0)\n sage: from sage.categories.magmatic_algebras import MagmaticAlgebras\n sage: C = MagmaticAlgebras(QQ).WithBasis().Unital()\n sage: F = Foo(QQ, (1,), category=C)\n sage: F(0)\n 0\n sage: F(3)\n 3*B[0]\n\n sage: class Bar(Parent):\n ....: _no_generic_basering_coercion = True\n sage: Bar(category=Algebras(QQ))\n doctest:warning...:\n DeprecationWarning: the attribute _no_generic_basering_coercion is deprecated, implement _coerce_map_from_base_ring() instead\n See https://github.com/sagemath/sage/issues/19225 for details.\n <__main__.Bar_with_category object at 0x...>\n "
if getattr(self, '_no_generic_basering_coercion', False):
from sage.misc.superseded import deprecation
deprecation(19225, 'the attribute _no_generic_basering_coercion is deprecated, implement _coerce_map_from_base_ring() instead')
return
base_ring = self.base_ring()
if (base_ring is self):
return
if self._is_coercion_cached(base_ring):
return
if (base_ring is None):
return
mor = self._coerce_map_from_base_ring()
if (mor is not None):
mor._make_weak_references()
try:
self.register_coercion(mor)
except AssertionError:
pass
def _coerce_map_from_(self, other):
"\n Return a coercion map from ``other`` to ``self``, or ``None``.\n\n TESTS:\n\n Check that :trac:`19225` is solved::\n\n sage: A = cartesian_product((QQ['z'],)); A\n The Cartesian product of (Univariate Polynomial Ring in z over Rational Field,)\n sage: A.coerce_map_from(ZZ)\n Composite map:\n From: Integer Ring\n To: The Cartesian product of (Univariate Polynomial Ring in z over Rational Field,)\n Defn: Natural morphism:\n From: Integer Ring\n To: Rational Field\n then\n Generic morphism:\n From: Rational Field\n To: The Cartesian product of (Univariate Polynomial Ring in z over Rational Field,)\n sage: A(1)\n (1,)\n "
if (other is self.base_ring()):
return self._coerce_map_from_base_ring()
else:
return self._coerce_map_via([self.base_ring()], other)
def _coerce_map_from_base_ring(self):
"\n Return a suitable coercion map from the base ring of ``self``.\n\n TESTS::\n\n sage: A = cartesian_product((QQ['z'],)); A\n The Cartesian product of (Univariate Polynomial Ring in z over Rational Field,)\n sage: A.base_ring()\n Rational Field\n sage: A._coerce_map_from_base_ring()\n Generic morphism:\n From: Rational Field\n To: The Cartesian product of (Univariate Polynomial Ring in z over Rational Field,)\n\n Check that :trac:`29312` is fixed::\n\n sage: F.<x,y,z> = FreeAlgebra(QQ, implementation='letterplace') # needs sage.combinat sage.modules\n sage: F._coerce_map_from_base_ring() # needs sage.combinat sage.modules\n Generic morphism:\n From: Rational Field\n To: Free Associative Unital Algebra on 3 generators (x, y, z) over Rational Field\n "
base_ring = self.base_ring()
if (self in Rings()):
H = Hom(base_ring, self, Rings())
else:
cat = Magmas().Unital()
cat = Category.join([cat, CommutativeAdditiveGroups()])
cat = cat.Distributive()
H = Hom(base_ring, self, cat)
generic_from_base_ring = self.category().parent_class.from_base_ring
from_base_ring = self.from_base_ring
if (from_base_ring.__func__ != generic_from_base_ring):
use_from_base_ring = True
elif isinstance(generic_from_base_ring, lazy_attribute):
use_from_base_ring = True
else:
try:
one = self.one()
use_from_base_ring = False
except (NotImplementedError, AttributeError, TypeError):
use_from_base_ring = True
mor = None
if use_from_base_ring:
mor = SetMorphism(function=from_base_ring, parent=H)
else:
try:
if (one._lmul_(base_ring.an_element()) is not None):
mor = SetMorphism(function=one._lmul_, parent=H)
except (NotImplementedError, AttributeError, TypeError):
pass
return mor
class WithBasis(CategoryWithAxiom_over_base_ring):
class ParentMethods():
@abstract_method(optional=True)
def one_basis(self):
'\n When the one of an algebra with basis is an element of\n this basis, this optional method can return the index of\n this element. This is used to provide a default\n implementation of :meth:`.one`, and an optimized default\n implementation of :meth:`.from_base_ring`.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).example()\n sage: A.one_basis()\n word:\n sage: A.one()\n B[word: ]\n sage: A.from_base_ring(4)\n 4*B[word: ]\n '
@cached_method
def one_from_one_basis(self):
"\n Return the one of the algebra, as per\n :meth:`Monoids.ParentMethods.one()\n <sage.categories.monoids.Monoids.ParentMethods.one>`\n\n By default, this is implemented from\n :meth:`.one_basis`, if available.\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).example()\n sage: A.one_basis()\n word:\n sage: A.one_from_one_basis()\n B[word: ]\n sage: A.one()\n B[word: ]\n\n TESTS:\n\n Try to check that :trac:`5843` Heisenbug is fixed::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).example()\n sage: B = AlgebrasWithBasis(QQ).example(('a', 'c'))\n sage: A == B\n False\n sage: Aone = A.one_from_one_basis\n sage: Bone = B.one_from_one_basis\n sage: Aone is Bone\n False\n\n Even if called in the wrong order, they should returns their\n respective one::\n\n sage: Bone().parent() is B # needs sage.combinat sage.modules\n True\n sage: Aone().parent() is A # needs sage.combinat sage.modules\n True\n "
return self.monomial(self.one_basis())
@lazy_attribute
def one(self):
'\n Return the multiplicative unit element.\n\n EXAMPLES::\n\n sage: A = AlgebrasWithBasis(QQ).example() # needs sage.combinat sage.modules\n sage: A.one_basis() # needs sage.combinat sage.modules\n word:\n sage: A.one() # needs sage.combinat sage.modules\n B[word: ]\n '
if (self.one_basis is NotImplemented):
return NotImplemented
return self.one_from_one_basis
@lazy_attribute
def from_base_ring(self):
'\n TESTS::\n\n sage: A = AlgebrasWithBasis(QQ).example() # needs sage.combinat sage.modules\n sage: A.from_base_ring(3) # needs sage.combinat sage.modules\n 3*B[word: ]\n '
if (self.one_basis is NotImplemented):
return NotImplemented
return self.from_base_ring_from_one_basis
def from_base_ring_from_one_basis(self, r):
'\n Implement the canonical embedding from the ground ring.\n\n INPUT:\n\n - ``r`` -- an element of the coefficient ring\n\n EXAMPLES::\n\n sage: # needs sage.combinat sage.modules\n sage: A = AlgebrasWithBasis(QQ).example()\n sage: A.from_base_ring_from_one_basis(3)\n 3*B[word: ]\n sage: A.from_base_ring(3)\n 3*B[word: ]\n sage: A(3)\n 3*B[word: ]\n '
return self.term(self.one_basis(), r)
class CartesianProducts(CartesianProductsCategory):
'\n The category of unital algebras constructed as Cartesian products\n of unital algebras.\n\n This construction gives the direct product of algebras. See\n discussion on:\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 algebras is endowed with a natural\n unital algebra structure.\n\n EXAMPLES::\n\n sage: from sage.categories.unital_algebras import UnitalAlgebras\n sage: C = UnitalAlgebras(QQ).CartesianProducts()\n sage: C.extra_super_categories()\n [Category of unital algebras over Rational Field]\n sage: sorted(C.super_categories(), key=str)\n [Category of Cartesian products of distributive magmas and additive magmas,\n Category of Cartesian products of unital magmas,\n Category of Cartesian products of vector spaces over Rational Field,\n Category of unital algebras over Rational Field]\n '
return [self.base_category()]
class ParentMethods():
@cached_method
def one(self):
'\n Return the multiplicative unit element.\n\n EXAMPLES::\n\n sage: S2 = simplicial_complexes.Sphere(2)\n sage: H = S2.cohomology_ring(QQ)\n sage: C = cartesian_product([H, H])\n sage: one = C.one()\n sage: one\n B[(0, (0, 0))] + B[(1, (0, 0))]\n sage: one == one * one\n True\n sage: all(b == b * one for b in C.basis())\n True\n '
data = enumerate(self.cartesian_factors())
return self._cartesian_product_of_elements([C.one() for (i, C) in data])
|
class VectorBundles(Category_over_base_ring):
'\n The category of vector bundles over any base space and base field.\n\n .. SEEALSO:: :class:`~sage.manifolds.vector_bundle.TopologicalVectorBundle`\n\n EXAMPLES::\n\n sage: M = Manifold(2, \'M\', structure=\'top\')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: C = VectorBundles(M, RR); C\n Category of vector bundles over Real Field with 53 bits of precision\n with base space 2-dimensional topological manifold M\n sage: C.super_categories()\n [Category of topological spaces]\n\n TESTS::\n\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n\n '
def __init__(self, base_space, base_field, name=None):
'\n Initialize ``self``.\n\n EXAMPLES::\n\n sage: M = Manifold(2, \'M\')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: C = VectorBundles(M, RR)\n sage: TestSuite(C).run(skip="_test_category_over_bases")\n\n '
if (base_field not in Fields().Topological()):
raise ValueError('base field must be a topological field')
self._base_space = base_space
Category_over_base_ring.__init__(self, base_field, name)
@cached_method
def super_categories(self):
"\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: VectorBundles(M, RR).super_categories()\n [Category of topological spaces]\n\n "
return [Sets().Topological()]
def base_space(self):
"\n Return the base space of this category.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M', structure='top')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: VectorBundles(M, RR).base_space()\n 2-dimensional topological manifold M\n\n "
return self._base_space
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: M = Manifold(2, 'M')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: VectorBundles(M, RR)._repr_object_names()\n 'vector bundles over Real Field with 53 bits of precision with base\n space 2-dimensional differentiable manifold M'\n\n "
base_space = self._base_space
return (Category_over_base_ring._repr_object_names(self) + (' with base space %s' % base_space))
class SubcategoryMethods():
@cached_method
def Differentiable(self):
"\n Return the subcategory of the differentiable objects\n of ``self``.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: VectorBundles(M, RR).Differentiable()\n Category of differentiable vector bundles over Real Field with\n 53 bits of precision with base space 2-dimensional\n differentiable manifold M\n\n TESTS::\n\n sage: TestSuite(VectorBundles(M, RR).Differentiable()).run()\n sage: VectorBundles(M, RR).Differentiable.__module__\n 'sage.categories.vector_bundles'\n\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: M = Manifold(2, 'M')\n sage: from sage.categories.vector_bundles import VectorBundles\n sage: VectorBundles(M, RR).Smooth()\n Category of smooth vector bundles over Real Field with 53 bits\n of precision with base space 2-dimensional differentiable\n manifold M\n\n TESTS::\n\n sage: TestSuite(VectorBundles(M, RR).Smooth()).run()\n sage: VectorBundles(M, RR).Smooth.__module__\n 'sage.categories.vector_bundles'\n "
return self._with_axiom('Smooth')
class Differentiable(CategoryWithAxiom_over_base_ring):
'\n The category of differentiable vector bundles.\n\n A differentiable vector bundle is a differentiable manifold with\n differentiable surjective projection on a differentiable base space.\n '
class Smooth(CategoryWithAxiom_over_base_ring):
'\n The category of smooth vector bundles.\n\n A smooth vector bundle is a smooth manifold with\n smooth surjective projection on a smooth base space.\n '
|
class VectorSpaces(Category_module):
'\n The category of (abstract) vector spaces over a given field\n\n ??? with an embedding in an ambient vector space ???\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ)\n Category of vector spaces over Rational Field\n sage: VectorSpaces(QQ).super_categories()\n [Category of modules over Rational Field]\n '
@staticmethod
def __classcall_private__(cls, K, check=True):
'\n INPUT:\n\n - `K` -- a field\n - ``check`` -- a boolean (default: True) whether to check that `K` is a field.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ) is VectorSpaces(QQ, check=False)\n True\n\n By default, it is checked that ``K`` is a field::\n\n sage: VectorSpaces(ZZ)\n Traceback (most recent call last):\n ...\n ValueError: base must be a field or a subcategory of Fields(); got Integer Ring\n\n With ``check=False``, the check is disabled, possibly enabling\n incorrect inputs::\n\n sage: VectorSpaces(ZZ, check=False)\n Category of vector spaces over Integer Ring\n '
if check:
if (not ((K in _Fields) or (isinstance(K, Category) and K.is_subcategory(_Fields)))):
raise ValueError(('base must be a field or a subcategory of Fields();' + ' got {}'.format(K)))
return super().__classcall__(cls, K)
def __init__(self, K):
'\n EXAMPLES::\n\n sage: VectorSpaces(QQ)\n Category of vector spaces over Rational Field\n sage: VectorSpaces(ZZ)\n Traceback (most recent call last):\n ...\n ValueError: base must be a field or a subcategory of Fields(); got Integer Ring\n\n TESTS::\n\n sage: C = QQ^10 # vector space # needs sage.modules\n sage: TestSuite(C).run() # needs sage.modules\n sage: TestSuite(VectorSpaces(QQ)).run()\n '
Category_module.__init__(self, K)
def _call_(self, x):
'\n Try to coerce ``x`` into an object of this category\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ)(ZZ^3) # needs sage.modules\n Vector space of dimension 3 over Rational Field\n\n TESTS:\n\n Check whether :trac:`30174` is fixed::\n\n sage: Q3 = FiniteRankFreeModule(QQ, 3) # needs sage.modules\n sage: Modules(QQ)(Q3) is Q3 # needs sage.modules\n True\n\n '
try:
V = x.vector_space(self.base_field())
if (V.base_field() != self.base_field()):
V = V.change_ring(self.base_field())
except (TypeError, AttributeError) as msg:
raise TypeError(('%s\nunable to coerce x (=%s) into %s' % (msg, x, self)))
return V
def base_field(self):
'\n Returns the base field over which the vector spaces of this\n category are all defined.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).base_field()\n Rational Field\n '
return self.base_ring()
def super_categories(self):
'\n EXAMPLES::\n\n sage: VectorSpaces(QQ).super_categories()\n [Category of modules over Rational Field]\n '
R = self.base_field()
return [Modules(R, dispatch=False)]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of vector spaces defines no additional\n structure: a bimodule morphism between two vector spaces is a\n vector space morphism.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).additional_structure()\n '
return None
class ParentMethods():
def dimension(self):
'\n Return the dimension of this vector space.\n\n EXAMPLES::\n\n sage: M = FreeModule(FiniteField(19), 100) # needs sage.modules\n sage: W = M.submodule([M.gen(50)]) # needs sage.modules\n sage: W.dimension() # needs sage.modules\n 1\n\n sage: M = FiniteRankFreeModule(QQ, 3) # needs sage.modules\n sage: M.dimension() # needs sage.modules\n 3\n sage: M.tensor_module(1, 2).dimension() # needs sage.modules\n 27\n\n '
return self.rank()
class ElementMethods():
pass
class WithBasis(CategoryWithAxiom_over_base_ring):
_call_ = ModulesWithBasis.__dict__['_call_']
def is_abelian(self):
'\n Return whether this category is abelian.\n\n This is always ``True`` since the base ring is a field.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).WithBasis().is_abelian()\n True\n '
return True
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n The category of vector spaces with basis is closed under Cartesian products::\n\n sage: C = VectorSpaces(QQ).WithBasis()\n sage: C.CartesianProducts()\n Category of Cartesian products of vector spaces with basis over Rational Field\n sage: C in C.CartesianProducts().super_categories()\n True\n '
return [self.base_category()]
class TensorProducts(TensorProductsCategory):
def extra_super_categories(self):
'\n The category of vector spaces with basis is closed under tensor products::\n\n sage: C = VectorSpaces(QQ).WithBasis()\n sage: C.TensorProducts()\n Category of tensor products of vector spaces with basis over Rational Field\n sage: C in C.TensorProducts().super_categories()\n True\n '
return [self.base_category()]
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
class TensorProducts(TensorProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a (finite) tensor product of\n finite dimensional vector spaces is a finite dimensional vector space.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).WithBasis().FiniteDimensional().TensorProducts().extra_super_categories()\n [Category of finite dimensional vector spaces with basis over Rational Field]\n sage: VectorSpaces(QQ).WithBasis().FiniteDimensional().TensorProducts().FiniteDimensional()\n Category of tensor products of finite dimensional vector spaces with basis over Rational Field\n\n '
return [self.base_category()]
class Graded(GradedModulesCategory):
'\n Category of graded vector spaces with basis.\n '
def example(self, base_ring=None):
'\n Return an example of a graded vector space with basis,\n as per :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Modules(QQ).WithBasis().Graded().example() # needs sage.combinat sage.modules\n An example of a graded module with basis:\n the free module on partitions over Rational Field\n '
from sage.categories.examples.graded_modules_with_basis import GradedPartitionModule
if (base_ring is None):
base_ring = self.base_ring()
return GradedPartitionModule(base_ring=base_ring)
class Filtered(FilteredModulesCategory):
'\n Category of filtered vector spaces with basis.\n '
def example(self, base_ring=None):
'\n Return an example of a graded vector space with basis,\n as per :meth:`Category.example()\n <sage.categories.category.Category.example>`.\n\n EXAMPLES::\n\n sage: Modules(QQ).WithBasis().Graded().example() # needs sage.combinat sage.modules\n An example of a graded module with basis:\n the free module on partitions over Rational Field\n '
from sage.categories.examples.filtered_modules_with_basis import FilteredPartitionModule
if (base_ring is None):
base_ring = self.base_ring()
return FilteredPartitionModule(base_ring=base_ring)
class FiniteDimensional(CategoryWithAxiom_over_base_ring):
class TensorProducts(TensorProductsCategory):
def extra_super_categories(self):
'\n Implement the fact that a (finite) tensor product of\n finite dimensional vector spaces is a finite dimensional vector space.\n\n EXAMPLES::\n\n sage: VectorSpaces(QQ).FiniteDimensional().TensorProducts().extra_super_categories()\n [Category of finite dimensional vector spaces over Rational Field]\n sage: VectorSpaces(QQ).FiniteDimensional().TensorProducts().FiniteDimensional()\n Category of tensor products of finite dimensional vector spaces over Rational Field\n\n '
return [self.base_category()]
class DualObjects(DualObjectsCategory):
def extra_super_categories(self):
'\n Returns the dual category\n\n EXAMPLES:\n\n The category of algebras over the Rational Field is dual\n to the category of coalgebras over the same field::\n\n sage: C = VectorSpaces(QQ)\n sage: C.dual()\n Category of duals of vector spaces over Rational Field\n sage: C.dual().super_categories() # indirect doctest\n [Category of vector spaces over Rational Field]\n '
return [self.base_category()]
class CartesianProducts(CartesianProductsCategory):
def extra_super_categories(self):
'\n The category of vector spaces is closed under Cartesian products::\n\n sage: C = VectorSpaces(QQ)\n sage: C.CartesianProducts()\n Category of Cartesian products of vector spaces over Rational Field\n sage: C in C.CartesianProducts().super_categories()\n True\n '
return [self.base_category()]
class TensorProducts(TensorProductsCategory):
def extra_super_categories(self):
'\n The category of vector spaces is closed under tensor products::\n\n sage: C = VectorSpaces(QQ)\n sage: C.TensorProducts()\n Category of tensor products of vector spaces over Rational Field\n sage: C in C.TensorProducts().super_categories()\n True\n '
return [self.base_category()]
class Filtered(FilteredModulesCategory):
'\n Category of filtered vector spaces.\n '
class Graded(GradedModulesCategory):
'\n Category of graded vector spaces.\n '
|
class WeylGroups(Category_singleton):
'\n The category of Weyl groups\n\n See the :wikipedia:`Wikipedia page of Weyl Groups <Weyl_group>`.\n\n EXAMPLES::\n\n sage: WeylGroups()\n Category of Weyl groups\n sage: WeylGroups().super_categories()\n [Category of Coxeter groups]\n\n Here are some examples::\n\n sage: WeylGroups().example() # todo: not implemented\n sage: FiniteWeylGroups().example()\n The symmetric group on {0, ..., 3}\n sage: AffineWeylGroups().example() # todo: not implemented\n sage: WeylGroup(["B", 3])\n Weyl Group of type [\'B\', 3] (as a matrix group acting on the ambient space)\n\n This one will eventually be also in this category::\n\n sage: SymmetricGroup(4)\n Symmetric group of order 4! as a permutation group\n\n TESTS::\n\n sage: C = WeylGroups()\n sage: TestSuite(C).run()\n '
def super_categories(self):
'\n EXAMPLES::\n\n sage: WeylGroups().super_categories()\n [Category of Coxeter groups]\n '
return [CoxeterGroups()]
def additional_structure(self):
'\n Return ``None``.\n\n Indeed, the category of Weyl groups defines no additional\n structure: Weyl groups are a special class of Coxeter groups.\n\n .. SEEALSO:: :meth:`Category.additional_structure`\n\n .. TODO:: Should this category be a :class:`CategoryWithAxiom`?\n\n EXAMPLES::\n\n sage: WeylGroups().additional_structure()\n '
return None
Finite = LazyImport('sage.categories.finite_weyl_groups', 'FiniteWeylGroups')
class ParentMethods():
def coxeter_matrix(self):
"\n Return the Coxeter matrix associated to ``self``.\n\n EXAMPLES::\n\n sage: G = WeylGroup(['A',3])\n sage: G.coxeter_matrix()\n [1 3 2]\n [3 1 3]\n [2 3 1]\n "
return self.cartan_type().coxeter_matrix()
def pieri_factors(self, *args, **keywords):
"\n Returns the set of Pieri factors in this Weyl group.\n\n For any type, the set of Pieri factors forms a lower ideal\n in Bruhat order, generated by all the conjugates of some\n special element of the Weyl group. In type `A_n`, this\n special element is `s_n\\cdots s_1`, and the conjugates are\n obtained by rotating around this reduced word.\n\n These are used to compute Stanley symmetric functions.\n\n .. SEEALSO::\n\n * :meth:`WeylGroups.ElementMethods.stanley_symmetric_function`\n * :mod:`sage.combinat.root_system.pieri_factors`\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',5,1])\n sage: PF = W.pieri_factors()\n sage: PF.cardinality()\n 63\n\n sage: W = WeylGroup(['B',3])\n sage: PF = W.pieri_factors()\n sage: sorted([w.reduced_word() for w in PF])\n [[],\n [1],\n [1, 2],\n [1, 2, 1],\n [1, 2, 3],\n [1, 2, 3, 1],\n [1, 2, 3, 2],\n [1, 2, 3, 2, 1],\n [2],\n [2, 1],\n [2, 3],\n [2, 3, 1],\n [2, 3, 2],\n [2, 3, 2, 1],\n [3],\n [3, 1],\n [3, 1, 2],\n [3, 1, 2, 1],\n [3, 2],\n [3, 2, 1]]\n sage: W = WeylGroup(['C',4,1])\n sage: PF = W.pieri_factors()\n sage: W.from_reduced_word([3,2,0]) in PF\n True\n "
import sage.combinat.root_system.pieri_factors
assert sage.combinat.root_system.pieri_factors
ct = self.cartan_type()
if hasattr(ct, 'PieriFactors'):
return ct.PieriFactors(self, *args, **keywords)
raise NotImplementedError('Pieri factors for type {}'.format(ct))
def bruhat_cone(self, x, y, side='upper', backend='cdd'):
"\n Return the (upper or lower) Bruhat cone associated to the interval ``[x,y]``.\n\n To a cover relation `v \\prec w` in strong Bruhat order you can assign a positive\n root `\\beta` given by the unique reflection `s_\\beta` such that `s_\\beta v = w`.\n\n The upper Bruhat cone of the interval `[x,y]` is the non-empty, polyhedral cone generated\n by the roots corresponding to `x \\prec a` for all atoms `a` in the interval.\n The lower Bruhat cone of the interval `[x,y]` is the non-empty, polyhedral cone generated\n by the roots corresponding to `c \\prec y` for all coatoms `c` in the interval.\n\n INPUT:\n\n - ``x`` - an element in the group `W`\n\n - ``y`` - an element in the group `W`\n\n - ``side`` (default: ``'upper'``) -- must be one of the following:\n\n * ``'upper'`` - return the upper Bruhat cone of the interval [``x``, ``y``]\n * ``'lower'`` - return the lower Bruhat cone of the interval [``x``, ``y``]\n\n - ``backend`` -- string (default: ``'cdd'``); the backend to use to create the polyhedron\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',2])\n sage: x = W.from_reduced_word([1])\n sage: y = W.w0\n sage: W.bruhat_cone(x, y)\n A 2-dimensional polyhedron in QQ^3\n defined as the convex hull of 1 vertex and 2 rays\n\n sage: W = WeylGroup(['E',6])\n sage: x = W.one()\n sage: y = W.w0\n sage: W.bruhat_cone(x, y, side='lower')\n A 6-dimensional polyhedron in QQ^8\n defined as the convex hull of 1 vertex and 6 rays\n\n TESTS::\n\n sage: W = WeylGroup(['A',2])\n sage: x = W.one()\n sage: y = W.w0\n sage: W.bruhat_cone(x, y, side='nonsense')\n Traceback (most recent call last):\n ...\n ValueError: side must be either 'upper' or 'lower'\n\n REFERENCES:\n\n - [Dy1994]_\n - [JS2021]_\n "
from sage.modules.free_module_element import vector
if (side == 'upper'):
roots = [vector(((x * r) * x.inverse()).reflection_to_root().to_ambient()) for (z, r) in x.bruhat_upper_covers_reflections() if z.bruhat_le(y)]
elif (side == 'lower'):
roots = [vector(((y * r) * y.inverse()).reflection_to_root().to_ambient()) for (z, r) in y.bruhat_lower_covers_reflections() if x.bruhat_le(z)]
else:
raise ValueError("side must be either 'upper' or 'lower'")
from sage.geometry.polyhedron.constructor import Polyhedron
return Polyhedron(vertices=[vector(([0] * self.degree()))], rays=roots, ambient_dim=self.degree(), backend=backend)
@cached_method
def quantum_bruhat_graph(self, index_set=()):
'\n Return the quantum Bruhat graph of the quotient of the Weyl\n group by a parabolic subgroup `W_J`.\n\n INPUT:\n\n - ``index_set`` -- (default: ()) a tuple `J` of nodes of\n the Dynkin diagram\n\n By default, the value for ``index_set`` indicates that the\n subgroup is trivial and the quotient is the full Weyl group.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], prefix="s")\n sage: g = W.quantum_bruhat_graph((1,3))\n sage: g\n Parabolic Quantum Bruhat Graph of Weyl Group of type [\'A\', 3]\n (as a matrix group acting on the ambient space)\n for nodes (1, 3): Digraph on 6 vertices\n sage: g.vertices(sort=True)\n [s2*s3*s1*s2, s3*s1*s2, s1*s2, s3*s2, s2, 1]\n sage: g.edges(sort=True)\n [(s2*s3*s1*s2, s2, alpha[2]),\n (s3*s1*s2, s2*s3*s1*s2, alpha[1] + alpha[2] + alpha[3]),\n (s3*s1*s2, 1, alpha[2]),\n (s1*s2, s3*s1*s2, alpha[2] + alpha[3]),\n (s3*s2, s3*s1*s2, alpha[1] + alpha[2]),\n (s2, s1*s2, alpha[1] + alpha[2]),\n (s2, s3*s2, alpha[2] + alpha[3]),\n (1, s2, alpha[2])]\n sage: W = WeylGroup([\'A\',3,1], prefix="s")\n sage: g = W.quantum_bruhat_graph()\n Traceback (most recent call last):\n ...\n ValueError: the Cartan type [\'A\', 3, 1] is not finite\n '
if (not self.cartan_type().is_finite()):
raise ValueError('the Cartan type {} is not finite'.format(self.cartan_type()))
lattice = self.cartan_type().root_system().root_lattice()
NPR = lattice.nonparabolic_positive_roots(index_set)
NPR_sum = sum(NPR)
NPR_data = {}
double_rho = lattice.sum(lattice.positive_roots())
for alpha in NPR:
ref = alpha.associated_reflection()
alphacheck = alpha.associated_coroot()
NPR_data[alpha] = [self.from_reduced_word(ref), (len(ref) == (double_rho.scalar(alphacheck) - 1)), NPR_sum.scalar(alphacheck)]
visited = {}
todo = {self.one()}
len_cache = {}
def length(x):
if (x in len_cache):
return len_cache[x]
len_cache[x] = x.length()
return len_cache[x]
while todo:
x = todo.pop()
w_length_plus_one = (length(x) + 1)
adj = {}
for alpha in NPR:
(elt, is_quantum, scalar) = NPR_data[alpha]
wr = (x * elt)
wrc = wr.coset_representative(index_set)
if ((wrc is wr) and (length(wrc) == w_length_plus_one)):
if (wrc not in visited):
todo.add(wrc)
adj[wr] = alpha
elif (is_quantum and (length(wrc) == (w_length_plus_one - scalar))):
if (wrc not in visited):
todo.add(wrc)
adj[wrc] = alpha
visited[x] = adj
from sage.graphs.digraph import DiGraph
return DiGraph(visited, name=('Parabolic Quantum Bruhat Graph of %s for nodes %s' % (self, index_set)), format='dict_of_dicts', data_structure='static_sparse')
class ElementMethods():
def is_pieri_factor(self):
"\n Returns whether ``self`` is a Pieri factor, as used for\n computing Stanley symmetric functions.\n\n .. SEEALSO::\n\n * :meth:`stanley_symmetric_function`\n * :meth:`WeylGroups.ParentMethods.pieri_factors`\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',5,1])\n sage: W.from_reduced_word([3,2,5]).is_pieri_factor()\n True\n sage: W.from_reduced_word([3,2,4,5]).is_pieri_factor()\n False\n\n sage: W = WeylGroup(['C',4,1])\n sage: W.from_reduced_word([0,2,1]).is_pieri_factor()\n True\n sage: W.from_reduced_word([0,2,1,0]).is_pieri_factor()\n False\n\n sage: W = WeylGroup(['B',3])\n sage: W.from_reduced_word([3,2,3]).is_pieri_factor()\n False\n sage: W.from_reduced_word([2,1,2]).is_pieri_factor()\n True\n "
return (self in self.parent().pieri_factors())
def left_pieri_factorizations(self, max_length=None):
"\n Returns all factorizations of ``self`` as `uv`, where `u`\n is a Pieri factor and `v` is an element of the Weyl group.\n\n .. SEEALSO::\n\n * :meth:`WeylGroups.ParentMethods.pieri_factors`\n * :mod:`sage.combinat.root_system.pieri_factors`\n\n EXAMPLES:\n\n If we take `w = w_0` the maximal element of a strict parabolic\n subgroup of type `A_{n_1} \\times \\cdots \\times A_{n_k}`, then the Pieri\n factorizations are in correspondence with all Pieri factors, and\n there are `\\prod 2^{n_i}` of them::\n\n sage: W = WeylGroup(['A', 4, 1])\n sage: W.from_reduced_word([]).left_pieri_factorizations().cardinality()\n 1\n sage: W.from_reduced_word([1]).left_pieri_factorizations().cardinality()\n 2\n sage: W.from_reduced_word([1,2,1]).left_pieri_factorizations().cardinality()\n 4\n sage: W.from_reduced_word([1,2,3,1,2,1]).left_pieri_factorizations().cardinality()\n 8\n\n sage: W.from_reduced_word([1,3]).left_pieri_factorizations().cardinality()\n 4\n sage: W.from_reduced_word([1,3,4,3]).left_pieri_factorizations().cardinality()\n 8\n\n sage: W.from_reduced_word([2,1]).left_pieri_factorizations().cardinality()\n 3\n sage: W.from_reduced_word([1,2]).left_pieri_factorizations().cardinality()\n 2\n sage: [W.from_reduced_word([1,2]).left_pieri_factorizations(max_length=i).cardinality()\n ....: for i in [-1, 0, 1, 2]]\n [0, 1, 2, 2]\n\n sage: W = WeylGroup(['C',4,1])\n sage: w = W.from_reduced_word([0,3,2,1,0])\n sage: w.left_pieri_factorizations().cardinality()\n 7\n sage: [(u.reduced_word(),v.reduced_word())\n ....: for (u,v) in w.left_pieri_factorizations()]\n [([], [3, 2, 0, 1, 0]),\n ([0], [3, 2, 1, 0]),\n ([3], [2, 0, 1, 0]),\n ([3, 0], [2, 1, 0]),\n ([3, 2], [0, 1, 0]),\n ([3, 2, 0], [1, 0]),\n ([3, 2, 0, 1], [0])]\n\n sage: W = WeylGroup(['B',4,1])\n sage: W.from_reduced_word([0,2,1,0]).left_pieri_factorizations().cardinality()\n 6\n "
if (max_length is None):
from sage.rings.infinity import infinity
max_length = infinity
pieri_factors = self.parent().pieri_factors()
def predicate(u):
return ((u in pieri_factors) and (u.length() <= max_length))
return self.binary_factorizations(predicate)
@cached_in_parent_method
def stanley_symmetric_function_as_polynomial(self, max_length=None):
"\n Returns a multivariate generating function for the number\n of factorizations of a Weyl group element into Pieri\n factors of decreasing length, weighted by a statistic on\n Pieri factors.\n\n .. SEEALSO::\n\n * :meth:`stanley_symmetric_function`\n * :meth:`WeylGroups.ParentMethods.pieri_factors`\n * :mod:`sage.combinat.root_system.pieri_factors`\n\n INPUT:\n\n - ``self`` -- an element `w` of a Weyl group `W`\n - ``max_length`` -- a non negative integer or infinity (default: infinity)\n\n Returns the generating series for the Pieri factorizations\n `w = u_1 \\cdots u_k`, where `u_i` is a Pieri factor for\n all `i`, `l(w) = \\sum_{i=1}^k l(u_i)` and\n ``max_length`` `\\geq l(u_1) \\geq \\cdots \\geq l(u_k)`.\n\n A factorization `u_1 \\cdots u_k` contributes a monomial of\n the form `\\prod_i x_{l(u_i)}`, with coefficient given by\n `\\prod_i 2^{c(u_i)}`, where `c` is a type-dependent\n statistic on Pieri factors, as returned by the method\n ``u[i].stanley_symm_poly_weight()``.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3, 1])\n sage: W.from_reduced_word([]).stanley_symmetric_function_as_polynomial()\n 1\n sage: W.from_reduced_word([1]).stanley_symmetric_function_as_polynomial()\n x1\n sage: W.from_reduced_word([1,2]).stanley_symmetric_function_as_polynomial()\n x1^2\n sage: W.from_reduced_word([2,1]).stanley_symmetric_function_as_polynomial()\n x1^2 + x2\n sage: W.from_reduced_word([1,2,1]).stanley_symmetric_function_as_polynomial()\n 2*x1^3 + x1*x2\n sage: W.from_reduced_word([1,2,1,0]).stanley_symmetric_function_as_polynomial()\n 3*x1^4 + 2*x1^2*x2 + x2^2 + x1*x3\n sage: x = W.from_reduced_word([1,2,3,1,2,1,0])\n sage: x.stanley_symmetric_function_as_polynomial() # long time\n 22*x1^7 + 11*x1^5*x2 + 5*x1^3*x2^2 + 3*x1^4*x3 + 2*x1*x2^3 + x1^2*x2*x3\n sage: y = W.from_reduced_word([3,1,2,0,3,1,0])\n sage: y.stanley_symmetric_function_as_polynomial() # long time\n 8*x1^7 + 4*x1^5*x2 + 2*x1^3*x2^2 + x1*x2^3\n\n sage: W = WeylGroup(['C',3,1])\n sage: W.from_reduced_word([0,2,1,0]).stanley_symmetric_function_as_polynomial()\n 32*x1^4 + 16*x1^2*x2 + 8*x2^2 + 4*x1*x3\n\n sage: W = WeylGroup(['B',3,1])\n sage: W.from_reduced_word([3,2,1]).stanley_symmetric_function_as_polynomial()\n 2*x1^3 + x1*x2 + 1/2*x3\n\n Algorithm: Induction on the left Pieri factors. Note that\n this induction preserves subsets of `W` which are stable\n by taking right factors, and in particular Grassmanian\n elements.\n "
if (max_length is None):
from sage.rings.infinity import infinity
max_length = infinity
W = self.parent()
pieri_factors = W.pieri_factors()
from sage.rings.rational_field import QQ
R = QQ[','.join((('x%s' % l) for l in range(1, (pieri_factors.max_length() + 1))))]
x = R.gens()
if self.is_one():
return R.one()
return R(sum(((((2 ** pieri_factors.stanley_symm_poly_weight(u)) * x[(u.length() - 1)]) * v.stanley_symmetric_function_as_polynomial(max_length=u.length())) for (u, v) in self.left_pieri_factorizations(max_length) if (u != W.one()))))
def stanley_symmetric_function(self):
"\n Return the affine Stanley symmetric function indexed by ``self``.\n\n INPUT:\n\n - ``self`` -- an element `w` of a Weyl group\n\n Returns the affine Stanley symmetric function indexed by\n `w`. Stanley symmetric functions are defined as generating\n series of the factorizations of `w` into Pieri factors and\n weighted by a statistic on Pieri factors.\n\n .. SEEALSO::\n\n * :meth:`stanley_symmetric_function_as_polynomial`\n * :meth:`WeylGroups.ParentMethods.pieri_factors`\n * :mod:`sage.combinat.root_system.pieri_factors`\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A', 3, 1])\n sage: W.from_reduced_word([3,1,2,0,3,1,0]).stanley_symmetric_function()\n 8*m[1, 1, 1, 1, 1, 1, 1] + 4*m[2, 1, 1, 1, 1, 1]\n + 2*m[2, 2, 1, 1, 1] + m[2, 2, 2, 1]\n sage: A = AffinePermutationGroup(['A',3,1])\n sage: A.from_reduced_word([3,1,2,0,3,1,0]).stanley_symmetric_function()\n 8*m[1, 1, 1, 1, 1, 1, 1] + 4*m[2, 1, 1, 1, 1, 1]\n + 2*m[2, 2, 1, 1, 1] + m[2, 2, 2, 1]\n\n sage: W = WeylGroup(['C',3,1])\n sage: W.from_reduced_word([0,2,1,0]).stanley_symmetric_function()\n 32*m[1, 1, 1, 1] + 16*m[2, 1, 1] + 8*m[2, 2] + 4*m[3, 1]\n\n sage: W = WeylGroup(['B',3,1])\n sage: W.from_reduced_word([3,2,1]).stanley_symmetric_function()\n 2*m[1, 1, 1] + m[2, 1] + 1/2*m[3]\n\n sage: W = WeylGroup(['B',4])\n sage: w = W.from_reduced_word([3,2,3,1])\n sage: w.stanley_symmetric_function() # long time (6s on sage.math, 2011)\n 48*m[1, 1, 1, 1] + 24*m[2, 1, 1] + 12*m[2, 2] + 8*m[3, 1] + 2*m[4]\n\n sage: A = AffinePermutationGroup(['A',4,1])\n sage: a = A([-2,0,1,4,12])\n sage: a.stanley_symmetric_function()\n 6*m[1, 1, 1, 1, 1, 1, 1, 1] + 5*m[2, 1, 1, 1, 1, 1, 1]\n + 4*m[2, 2, 1, 1, 1, 1] + 3*m[2, 2, 2, 1, 1] + 2*m[2, 2, 2, 2]\n + 4*m[3, 1, 1, 1, 1, 1] + 3*m[3, 2, 1, 1, 1] + 2*m[3, 2, 2, 1]\n + 2*m[3, 3, 1, 1] + m[3, 3, 2] + 3*m[4, 1, 1, 1, 1]\n + 2*m[4, 2, 1, 1] + m[4, 2, 2] + m[4, 3, 1]\n\n One more example (:trac:`14095`)::\n\n sage: G = SymmetricGroup(4)\n sage: w = G.from_reduced_word([3,2,3,1])\n sage: w.stanley_symmetric_function()\n 3*m[1, 1, 1, 1] + 2*m[2, 1, 1] + m[2, 2] + m[3, 1]\n\n REFERENCES:\n\n - [BH1994]_\n\n - [Lam2008]_\n\n - [LSS2009]_\n\n - [Pon2010]_\n "
import sage.combinat.sf
from sage.rings.rational_field import QQ
m = sage.combinat.sf.sf.SymmetricFunctions(QQ).monomial()
return m.from_polynomial_exp(self.stanley_symmetric_function_as_polynomial())
@cached_in_parent_method
def reflection_to_root(self):
'\n Return the root associated with the reflection ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'C\',2],prefix="s")\n sage: W.from_reduced_word([1,2,1]).reflection_to_root()\n 2*alpha[1] + alpha[2]\n sage: W.from_reduced_word([1,2]).reflection_to_root()\n Traceback (most recent call last):\n ...\n ValueError: s1*s2 is not a reflection\n sage: W.long_element().reflection_to_root()\n Traceback (most recent call last):\n ...\n ValueError: s2*s1*s2*s1 is not a reflection\n '
i = self.first_descent()
if (i is None):
raise ValueError('{} is not a reflection'.format(self))
if (self == self.parent().simple_reflection(i)):
return self.parent().cartan_type().root_system().root_lattice().simple_root(i)
rsi = self.apply_simple_reflection(i)
if (not rsi.has_descent(i, side='left')):
raise ValueError('{} is not a reflection'.format(self))
return rsi.apply_simple_reflection(i, side='left').reflection_to_root().simple_reflection(i)
@cached_in_parent_method
def reflection_to_coroot(self):
'\n Return the coroot associated with the reflection ``self``.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'C\',2],prefix="s")\n sage: W.from_reduced_word([1,2,1]).reflection_to_coroot()\n alphacheck[1] + alphacheck[2]\n sage: W.from_reduced_word([1,2]).reflection_to_coroot()\n Traceback (most recent call last):\n ...\n ValueError: s1*s2 is not a reflection\n sage: W.long_element().reflection_to_coroot()\n Traceback (most recent call last):\n ...\n ValueError: s2*s1*s2*s1 is not a reflection\n '
i = self.first_descent()
if (i is None):
raise ValueError('{} is not a reflection'.format(self))
if (self == self.parent().simple_reflection(i)):
return self.parent().cartan_type().root_system().root_lattice().simple_coroot(i)
rsi = self.apply_simple_reflection(i)
if (not rsi.has_descent(i, side='left')):
raise ValueError('{} is not a reflection'.format(self))
return rsi.apply_simple_reflection(i, side='left').reflection_to_coroot().simple_reflection(i)
def inversions(self, side='right', inversion_type='reflections'):
'\n Return the set of inversions of ``self``.\n\n INPUT:\n\n - ``side`` -- \'right\' (default) or \'left\'\n - ``inversion_type`` -- \'reflections\' (default), \'roots\', or \'coroots\'\n\n OUTPUT:\n\n For reflections, the set of reflections r in the Weyl group such that\n ``self`` ``r`` < ``self``. For (co)roots, the set of positive (co)roots that are sent\n by ``self`` to negative (co)roots; their associated reflections are described above.\n\n If ``side`` is \'left\', the inverse Weyl group element is used.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'C\',2], prefix="s")\n sage: w = W.from_reduced_word([1,2])\n sage: w.inversions()\n [s2, s2*s1*s2]\n sage: w.inversions(inversion_type = \'reflections\')\n [s2, s2*s1*s2]\n sage: w.inversions(inversion_type = \'roots\')\n [alpha[2], alpha[1] + alpha[2]]\n sage: w.inversions(inversion_type = \'coroots\')\n [alphacheck[2], alphacheck[1] + 2*alphacheck[2]]\n sage: w.inversions(side = \'left\')\n [s1, s1*s2*s1]\n sage: w.inversions(side = \'left\', inversion_type = \'roots\')\n [alpha[1], 2*alpha[1] + alpha[2]]\n sage: w.inversions(side = \'left\', inversion_type = \'coroots\')\n [alphacheck[1], alphacheck[1] + alphacheck[2]]\n '
if (side == 'left'):
self = self.inverse()
reflections = self.inversions_as_reflections()
if (inversion_type == 'reflections'):
return reflections
if (inversion_type == 'roots'):
return [r.reflection_to_root() for r in reflections]
if (inversion_type == 'coroots'):
return [r.reflection_to_coroot() for r in reflections]
raise ValueError(f'inversion_type {inversion_type} is invalid')
def inversion_arrangement(self, side='right'):
"\n Return the inversion hyperplane arrangement of ``self``.\n\n INPUT:\n\n - ``side`` -- ``'right'`` (default) or ``'left'``\n\n OUTPUT:\n\n A (central) hyperplane arrangement whose hyperplanes correspond\n to the inversions of ``self`` given as roots.\n\n The ``side`` parameter determines on which side\n to compute the inversions.\n\n EXAMPLES::\n\n sage: W = WeylGroup(['A',3])\n sage: w = W.from_reduced_word([1, 2, 3, 1, 2])\n sage: A = w.inversion_arrangement(); A\n Arrangement of 5 hyperplanes of dimension 3 and rank 3\n sage: A.hyperplanes()\n (Hyperplane 0*a1 + 0*a2 + a3 + 0,\n Hyperplane 0*a1 + a2 + 0*a3 + 0,\n Hyperplane 0*a1 + a2 + a3 + 0,\n Hyperplane a1 + a2 + 0*a3 + 0,\n Hyperplane a1 + a2 + a3 + 0)\n\n The identity element gives the empty arrangement::\n\n sage: W = WeylGroup(['A',3])\n sage: W.one().inversion_arrangement()\n Empty hyperplane arrangement of dimension 3\n "
inv = self.inversions(side=side, inversion_type='roots')
from sage.geometry.hyperplane_arrangement.arrangement import HyperplaneArrangements
I = self.parent().cartan_type().index_set()
from sage.rings.rational_field import QQ
H = HyperplaneArrangements(QQ, tuple(['a{}'.format(i) for i in I]))
gens = H.gens()
if (not inv):
return H()
return H([sum(((c * gens[I.index(i)]) for (i, c) in root)) for root in inv])
def bruhat_lower_covers_coroots(self):
'\n Return all 2-tuples (``v``, `\\alpha`) where ``v`` is covered\n by ``self`` and `\\alpha` is the positive coroot such that\n ``self`` = ``v`` `s_\\alpha` where `s_\\alpha` is\n the reflection orthogonal to `\\alpha`.\n\n ALGORITHM:\n\n See :meth:`.bruhat_lower_covers` and\n :meth:`.bruhat_lower_covers_reflections` for Coxeter groups.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], prefix="s")\n sage: w = W.from_reduced_word([3,1,2,1])\n sage: w.bruhat_lower_covers_coroots()\n [(s1*s2*s1, alphacheck[1] + alphacheck[2] + alphacheck[3]),\n (s3*s2*s1, alphacheck[2]), (s3*s1*s2, alphacheck[1])]\n '
return [(x[0], x[1].reflection_to_coroot()) for x in self.bruhat_lower_covers_reflections()]
def bruhat_upper_covers_coroots(self):
'\n Returns all 2-tuples (``v``, `\\alpha`) where ``v`` is covers ``self`` and `\\alpha`\n is the positive coroot such that ``self`` = ``v`` `s_\\alpha` where `s_\\alpha` is\n the reflection orthogonal to `\\alpha`.\n\n ALGORITHM:\n\n See :meth:`~CoxeterGroups.ElementMethods.bruhat_upper_covers` and :meth:`.bruhat_upper_covers_reflections` for Coxeter groups.\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',4], prefix="s")\n sage: w = W.from_reduced_word([3,1,2,1])\n sage: w.bruhat_upper_covers_coroots()\n [(s1*s2*s3*s2*s1, alphacheck[3]),\n (s2*s3*s1*s2*s1, alphacheck[2] + alphacheck[3]),\n (s3*s4*s1*s2*s1, alphacheck[4]),\n (s4*s3*s1*s2*s1, alphacheck[1] + alphacheck[2] + alphacheck[3] + alphacheck[4])]\n '
return [(x[0], x[1].reflection_to_coroot()) for x in self.bruhat_upper_covers_reflections()]
def quantum_bruhat_successors(self, index_set=None, roots=False, quantum_only=False):
'\n Return the successors of ``self`` in the quantum Bruhat graph\n on the parabolic quotient of the Weyl group determined by the\n subset of Dynkin nodes ``index_set``.\n\n INPUT:\n\n - ``self`` -- a Weyl group element, which is assumed to\n be of minimum length in its coset with respect to the\n parabolic subgroup\n\n - ``index_set`` -- (default: ``None``) indicates the set of\n simple reflections used to generate the parabolic subgroup;\n the default value indicates that the subgroup is the identity\n\n - ``roots`` -- (default: ``False``) if ``True``, returns the\n list of 2-tuples (``w``, `\\alpha`) where ``w`` is a successor\n and `\\alpha` is the positive root associated with the\n successor relation\n\n - ``quantum_only`` -- (default: ``False``) if ``True``, returns\n only the quantum successors\n\n EXAMPLES::\n\n sage: W = WeylGroup([\'A\',3], prefix="s")\n sage: w = W.from_reduced_word([3,1,2])\n sage: w.quantum_bruhat_successors([1], roots = True)\n [(s3, alpha[2]), (s1*s2*s3*s2, alpha[3]),\n (s2*s3*s1*s2, alpha[1] + alpha[2] + alpha[3])]\n sage: w.quantum_bruhat_successors([1,3])\n [1, s2*s3*s1*s2]\n sage: w.quantum_bruhat_successors(roots = True)\n [(s3*s1*s2*s1, alpha[1]),\n (s3*s1, alpha[2]),\n (s1*s2*s3*s2, alpha[3]),\n (s2*s3*s1*s2, alpha[1] + alpha[2] + alpha[3])]\n sage: w.quantum_bruhat_successors()\n [s3*s1*s2*s1, s3*s1, s1*s2*s3*s2, s2*s3*s1*s2]\n sage: w.quantum_bruhat_successors(quantum_only = True)\n [s3*s1]\n sage: w = W.from_reduced_word([2,3])\n sage: w.quantum_bruhat_successors([1,3])\n Traceback (most recent call last):\n ...\n ValueError: s2*s3 is not of minimum length in its coset\n of the parabolic subgroup generated by the reflections (1, 3)\n '
W = self.parent()
if (not W.cartan_type().is_finite()):
raise ValueError('the Cartan type {} is not finite'.format(W.cartan_type()))
if (index_set is None):
index_set = []
else:
index_set = list(index_set)
index_set = tuple(index_set)
if (self != self.coset_representative(index_set)):
raise ValueError('{} is not of minimum length in its coset of the parabolic subgroup generated by the reflections {}'.format(self, index_set))
lattice = W.cartan_type().root_system().root_lattice()
w_length_plus_one = (self.length() + 1)
successors = []
for alpha in lattice.nonparabolic_positive_roots(index_set):
wr = (self * W.from_reduced_word(alpha.associated_reflection()))
wrc = wr.coset_representative(index_set)
if ((wrc == wr) and (wr.length() == w_length_plus_one) and (not quantum_only)):
if roots:
successors.append((wr, alpha))
else:
successors.append(wr)
elif (alpha.quantum_root() and (wrc.length() == (w_length_plus_one - lattice.nonparabolic_positive_root_sum(index_set).scalar(alpha.associated_coroot())))):
if roots:
successors.append((wrc, alpha))
else:
successors.append(wrc)
return successors
|
def WithRealizations(self):
"\n Return the category of parents in ``self`` endowed with multiple realizations.\n\n INPUT:\n\n - ``self`` -- a category\n\n .. SEEALSO::\n\n - The documentation and code\n (:mod:`sage.categories.examples.with_realizations`) of\n ``Sets().WithRealizations().example()`` for more on how to use and\n implement a parent with several realizations.\n\n - Various use cases:\n\n - :class:`SymmetricFunctions`\n - :class:`QuasiSymmetricFunctions`\n - :class:`NonCommutativeSymmetricFunctions`\n - :class:`SymmetricFunctionsNonCommutingVariables`\n - :class:`DescentAlgebra`\n - :class:`algebras.Moebius`\n - :class:`IwahoriHeckeAlgebra`\n - :class:`ExtendedAffineWeylGroup`\n\n - The `Implementing Algebraic Structures\n <../../../../../thematic_tutorials/tutorial-implementing-algebraic-structures>`_\n thematic tutorial.\n\n - :mod:`sage.categories.realizations`\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.WithRealizations`). It is defined\n here for code locality reasons.\n\n EXAMPLES::\n\n sage: Sets().WithRealizations()\n Category of sets with realizations\n\n .. RUBRIC:: Parent with realizations\n\n Let us now explain the concept of realizations. A *parent with\n realizations* is a facade parent (see :class:`Sets.Facade`)\n admitting multiple concrete realizations where its elements are\n represented. Consider for example an algebra `A` which admits\n several natural bases::\n\n sage: A = Sets().WithRealizations().example(); A # needs sage.modules\n The subset algebra of {1, 2, 3} over Rational Field\n\n For each such basis `B` one implements a parent `P_B` which\n realizes `A` with its elements represented by expanding them on\n the basis `B`::\n\n sage: # needs sage.modules\n sage: A.F()\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n sage: A.Out()\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n sage: A.In()\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n sage: A.an_element()\n F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}]\n\n If `B` and `B'` are two bases, then the change of basis from `B`\n to `B'` is implemented by a canonical coercion between `P_B` and\n `P_{B'}`::\n\n sage: # needs sage.combinat sage.modules\n sage: F = A.F(); In = A.In(); Out = A.Out()\n sage: i = In.an_element(); i\n In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}]\n sage: F(i)\n 7*F[{}] + 3*F[{1}] + 4*F[{2}] + F[{1, 2}]\n sage: F.coerce_map_from(Out)\n Generic morphism:\n From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n\n allowing for mixed arithmetic::\n\n sage: (1 + Out.from_set(1)) * In.from_set(2,3) # needs sage.combinat sage.modules\n Out[{}] + 2*Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}]\n + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}]\n\n In our example, there are three realizations::\n\n sage: A.realizations() # needs sage.modules\n [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis,\n The subset algebra of {1, 2, 3} over Rational Field in the In basis,\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis]\n\n Instead of manually defining the shorthands ``F``, ``In``, and\n ``Out``, as above one can just do::\n\n sage: A.inject_shorthands() # needs sage.combinat sage.modules\n Defining F as shorthand for\n The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis\n Defining In as shorthand for\n The subset algebra of {1, 2, 3} over Rational Field in the In basis\n Defining Out as shorthand for\n The subset algebra of {1, 2, 3} over Rational Field in the Out basis\n\n .. RUBRIC:: Rationale\n\n Besides some goodies described below, the role of `A` is threefold:\n\n - To provide, as illustrated above, a single entry point for the\n algebra as a whole: documentation, access to its properties and\n different realizations, etc.\n\n - To provide a natural location for the initialization of the\n bases and the coercions between, and other methods that are\n common to all bases.\n\n - To let other objects refer to `A` while allowing elements to be\n represented in any of the realizations.\n\n We now illustrate this second point by defining the polynomial\n ring with coefficients in `A`::\n\n sage: P = A['x']; P # needs sage.modules\n Univariate Polynomial Ring in x over\n The subset algebra of {1, 2, 3} over Rational Field\n sage: x = P.gen() # needs sage.modules\n\n In the following examples, the coefficients turn out to be all\n represented in the `F` basis::\n\n sage: P.one() # needs sage.modules\n F[{}]\n sage: (P.an_element() + 1)^2 # needs sage.modules\n F[{}]*x^2 + 2*F[{}]*x + F[{}]\n\n However we can create a polynomial with mixed coefficients, and\n compute with it::\n\n sage: p = P([1, In[{1}], Out[{2}] ]); p # needs sage.combinat sage.modules\n Out[{2}]*x^2 + In[{1}]*x + F[{}]\n sage: p^2 # needs sage.combinat sage.modules\n Out[{2}]*x^4\n + (-8*In[{}] + 4*In[{1}] + 8*In[{2}] + 4*In[{3}]\n - 4*In[{1, 2}] - 2*In[{1, 3}] - 4*In[{2, 3}] + 2*In[{1, 2, 3}])*x^3\n + (F[{}] + 3*F[{1}] + 2*F[{2}] - 2*F[{1, 2}] - 2*F[{2, 3}] + 2*F[{1, 2, 3}])*x^2\n + (2*F[{}] + 2*F[{1}])*x\n + F[{}]\n\n Note how each coefficient involves a single basis which need not\n be that of the other coefficients. Which basis is used depends on\n how coercion happened during mixed arithmetic and needs not be\n deterministic.\n\n One can easily coerce all coefficient to a given basis with::\n\n sage: p.map_coefficients(In) # needs sage.combinat sage.modules\n (-4*In[{}] + 2*In[{1}] + 4*In[{2}] + 2*In[{3}]\n - 2*In[{1, 2}] - In[{1, 3}] - 2*In[{2, 3}] + In[{1, 2, 3}])*x^2\n + In[{1}]*x + In[{}]\n\n Alas, the natural notation for constructing such polynomials does\n not yet work::\n\n sage: In[{1}] * x # needs sage.combinat sage.modules\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand parent(s) for *:\n 'The subset algebra of {1, 2, 3} over Rational Field in the In basis'\n and 'Univariate Polynomial Ring in x over\n The subset algebra of {1, 2, 3} over Rational Field'\n\n .. RUBRIC:: The category of realizations of `A`\n\n The set of all realizations of `A`, together with the coercion morphisms\n is a category (whose class inherits from\n :class:`~sage.categories.realizations.Category_realization_of_parent`)::\n\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 The various parent realizing `A` belong to this category::\n\n sage: A.F() in A.Realizations() # needs sage.modules\n True\n\n `A` itself is in the category of algebras with realizations::\n\n sage: A in Algebras(QQ).WithRealizations() # needs sage.modules\n True\n\n The (mostly technical) ``WithRealizations`` categories are the\n analogs of the ``*WithSeveralBases`` categories in\n MuPAD-Combinat. They provide support tools for handling the\n different realizations and the morphisms between them.\n\n Typically, ``VectorSpaces(QQ).FiniteDimensional().WithRealizations()``\n will eventually be in charge, whenever a coercion `\\phi: A\\mapsto B` is\n registered, to register `\\phi^{-1}` as coercion `B \\mapsto A`\n if there is none defined yet. To achieve this,\n ``FiniteDimensionalVectorSpaces`` would provide a nested class\n ``WithRealizations`` implementing the appropriate logic.\n\n ``WithRealizations`` is a :mod:`regressive covariant functorial\n construction <sage.categories.covariant_functorial_construction>`.\n On our example, this simply means that `A` is automatically in the\n category of rings with realizations (covariance)::\n\n sage: A in Rings().WithRealizations() # needs sage.modules\n True\n\n and in the category of algebras (regressiveness)::\n\n sage: A in Algebras(QQ) # needs sage.modules\n True\n\n .. NOTE::\n\n For ``C`` a category, ``C.WithRealizations()`` in fact calls\n ``sage.categories.with_realizations.WithRealizations(C)``. The\n later is responsible for building the hierarchy of the\n categories with realizations in parallel to that of their base\n categories, optimizing away those categories that do not\n provide a ``WithRealizations`` nested class. See\n :mod:`sage.categories.covariant_functorial_construction` for\n the technical details.\n\n .. NOTE::\n\n Design question: currently ``WithRealizations`` is a\n regressive construction. That is ``self.WithRealizations()``\n is a subcategory of ``self`` by default::\n\n sage: Algebras(QQ).WithRealizations().super_categories()\n [Category of algebras over Rational Field,\n Category of monoids with realizations,\n Category of additive unital additive magmas with realizations]\n\n Is this always desirable? For example,\n ``AlgebrasWithBasis(QQ).WithRealizations()`` should certainly\n be a subcategory of ``Algebras(QQ)``, but not of\n ``AlgebrasWithBasis(QQ)``. This is because\n ``AlgebrasWithBasis(QQ)`` is specifying something about the\n concrete realization.\n\n TESTS::\n\n sage: Semigroups().WithRealizations()\n Join of Category of semigroups and Category of sets with realizations\n sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C\n Category of graded Hopf algebras with basis over Rational Field with realizations\n sage: C.super_categories()\n [Join of Category of Hopf algebras over Rational Field\n and Category of graded algebras over Rational Field\n and Category of graded coalgebras over Rational Field]\n sage: TestSuite(Semigroups().WithRealizations()).run()\n "
return WithRealizationsCategory.category_of(self)
|
class WithRealizationsCategory(RegressiveCovariantConstructionCategory):
'\n An abstract base class for all categories of parents with multiple\n realizations.\n\n .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>`\n\n The role of this base class is to implement some technical goodies, such\n as the name for that category.\n '
_functor_category = 'WithRealizations'
def _repr_(self):
'\n String representation.\n\n EXAMPLES::\n\n sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C #indirect doctest\n Category of graded Hopf algebras with basis over Rational Field with realizations\n '
s = repr(self.base_category())
return (s + ' with realizations')
|
def _explain_constructor(cl):
'\n Internal function for use error messages when constructing encoders and decoders.\n\n EXAMPLES::\n\n sage: from sage.coding.linear_code import LinearCodeSyndromeDecoder\n sage: from sage.coding.abstract_code import _explain_constructor\n sage: cl = LinearCodeSyndromeDecoder\n sage: _explain_constructor(cl)\n "The constructor requires no arguments.\\nIt takes the optional\n arguments [\'maximum_error_weight\'].\\nSee the documentation of\n sage.coding.linear_code.LinearCodeSyndromeDecoder for more details."\n\n sage: from sage.coding.information_set_decoder import LinearCodeInformationSetDecoder\n sage: cl = LinearCodeInformationSetDecoder\n sage: _explain_constructor(cl)\n "The constructor requires the arguments [\'number_errors\'].\\nIt takes the optional arguments [\'algorithm\'].\\nIt accepts unspecified arguments as well.\\nSee the documentation of sage.coding.information_set_decoder.LinearCodeInformationSetDecoder for more details."\n '
if inspect.isclass(cl):
argspec = sage_getargspec(cl.__init__)
skip = 2
else:
argspec = sage_getargspec(cl)
skip = 1
if argspec.defaults:
args = argspec.args[skip:(- len(argspec.defaults))]
kwargs = argspec.args[(- len(argspec.defaults)):]
opts = 'It takes the optional arguments {}.'.format(kwargs)
else:
args = argspec.args[skip:]
opts = 'It takes no optional arguments.'
if args:
reqs = 'The constructor requires the arguments {}.'.format(args)
else:
reqs = 'The constructor requires no arguments.'
if (argspec.varargs or argspec.varkw):
var = 'It accepts unspecified arguments as well.\n'
else:
var = ''
return '{}\n{}\n{}See the documentation of {}.{} for more details.'.format(reqs, opts, var, cl.__module__, cl.__name__)
|
class AbstractCode(Parent):
'\n Abstract class for codes.\n\n This class contains all the methods that can be used on any code\n and on any code family. As opposed to\n :class:`sage.coding.linear_code.AbstractLinearCode`, this class makes no\n assumptions about linearity, metric, finiteness or the number of alphabets.\n\n The abstract notion of "code" that is implicitly used for this class is any\n enumerable subset of a cartesian product `A_1 \\times A_2 \\times \\ldots\n \\times A_n` for some sets `A_i`. Note that this class makes no attempt to\n directly represent the code in this fashion, allowing subclasses to make the\n appropriate choices. The notion of metric is also not mathematically\n enforced in any way, and is simply stored as a string value.\n\n Every code-related class should inherit from this abstract class.\n\n To implement a code, you need to:\n\n - inherit from :class:`AbstractCode`\n\n - call :class:`AbstractCode` ``__init__`` method in the subclass constructor.\n Example: ``super().__init__(length, "EncoderName",\n "DecoderName", "metric")``. "EncoderName" and "DecoderName" are set to\n ``None`` by default, a generic code class such as AbstractCode does\n not necessarily have to have general encoders/decoders. However, if you\n want to use the encoding/decoding methods, you have to add these.\n\n - since this class does not specify any category, it is highly recommended\n to set up the category framework in the subclass. To do this, use the\n ``Parent.__init__(self, base, facade, category)`` function in the subclass\n constructor. A good example is in\n :class:`sage.coding.linear_code.AbstractLinearCode`.\n\n - it is also recommended to override the ``ambient_space`` method, which is\n required by ``__call__``\n\n - to use the encoder/decoder framework, one has to set up the category and\n related functions ``__iter__`` and ``__contains__``. A good example is in\n :class:`sage.coding.linear_code.AbstractLinearCode`.\n\n - add the following two lines on the class level::\n\n _registered_encoders = {}\n _registered_decoders = {}\n\n\n - fill the dictionary of its encoders in ``sage.coding.__init__.py`` file.\n Example: I want to link the encoder ``MyEncoderClass`` to ``MyNewCodeClass``\n under the name ``MyEncoderName``.\n All I need to do is to write this line in the ``__init__.py`` file:\n ``MyNewCodeClass._registered_encoders["NameOfMyEncoder"] = MyEncoderClass``\n and all instances of ``MyNewCodeClass`` will be able to use instances of\n ``MyEncoderClass``.\n\n - fill the dictionary of its decoders in ``sage.coding.__init__`` file.\n Example: I want to link the encoder ``MyDecoderClass`` to ``MyNewCodeClass``\n under the name ``MyDecoderName``.\n All I need to do is to write this line in the ``__init__.py`` file:\n ``MyNewCodeClass._registered_decoders["NameOfMyDecoder"] = MyDecoderClass``\n and all instances of ``MyNewCodeClass`` will be able to use instances of\n ``MyDecoderClass``.\n\n\n As the class :class:`AbstractCode` is not designed to be instantiated, it\n does not have any representation methods. You should implement ``_repr_``\n and ``_latex_`` methods in the subclass.\n '
def __init__(self, length, default_encoder_name=None, default_decoder_name=None, metric='Hamming'):
'\n Initializes mandatory parameters that any code shares.\n\n This method only exists for inheritance purposes as it initializes\n parameters that need to be known by every code. The class\n :class:`sage.coding.abstract_code.AbstractCode` should never be\n directly instantiated.\n\n INPUT:\n\n - ``length`` -- the length of ``self`` (a Python int or a Sage Integer,\n must be > 0)\n\n - ``default_encoder_name`` -- (default: ``None``) the name of\n the default encoder of ``self``\n\n - ``default_decoder_name`` -- (default: ``None``) the name of\n the default decoder of ``self``\n\n - ``metric`` -- (default: ``Hamming``) the name of the metric of ``self``\n\n EXAMPLES:\n\n The following example demonstrates how to use a subclass of ``AbstractCode``\n for representing a new family of codes::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCodeFamily(AbstractCode):\n ....: def __init__(self, length):\n ....: super().__init__(length)\n ....: def __iter__(self):\n ....: for i in range(self.length() + 1):\n ....: yield vector([1 for j in range(i)] + [0 for k in range(i, self.length())])\n ....: def __contains__(self, word):\n ....: return word in list(self)\n ....: def _repr_(self):\n ....: return "Dummy code of length {}".format(self.length())\n\n We now instantiate a member of our newly made code family::\n\n sage: C = MyCodeFamily(6)\n\n We can check its existence and parameters::\n\n sage: C\n Dummy code of length 6\n\n We can list its elements and check if an element is in the code::\n\n sage: list(C)\n [(0, 0, 0, 0, 0, 0),\n (1, 0, 0, 0, 0, 0),\n (1, 1, 0, 0, 0, 0),\n (1, 1, 1, 0, 0, 0),\n (1, 1, 1, 1, 0, 0),\n (1, 1, 1, 1, 1, 0),\n (1, 1, 1, 1, 1, 1)]\n sage: vector((0, 1, 0, 0, 0, 1)) in C\n False\n sage: vector((1, 1, 1, 0, 0, 0)) in C\n True\n\n And coming from AbstractCode code::\n\n sage: C.metric()\n \'Hamming\'\n\n TESTS:\n\n If the length field is neither a Python int nor a Sage Integer, it will\n raise a exception::\n\n sage: C = MyCodeFamily(10.0)\n Traceback (most recent call last):\n ...\n ValueError: length must be a Python int or a Sage Integer\n\n If the length of the code is not a non-zero positive integer\n (See :trac:`21326`), it will raise an exception::\n\n sage: C = MyCodeFamily(0)\n Traceback (most recent call last):\n ...\n ValueError: length must be a non-zero positive integer\n '
if (not isinstance(length, (int, Integer))):
raise ValueError('length must be a Python int or a Sage Integer')
if (length <= 0):
raise ValueError('length must be a non-zero positive integer')
self._length = length
self._metric = metric
self._default_decoder_name = default_decoder_name
self._default_encoder_name = default_encoder_name
if (not self._default_decoder_name):
self._registered_encoders = {}
if (not self._default_encoder_name):
self._registered_decoders = {}
def __getstate__(self):
"\n Used for pickling codes.\n\n TESTS::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: '_registered_encoders' in C.__getstate__()\n True\n "
d = super().__getstate__()
d['_registered_encoders'] = self._registered_encoders
d['_registered_decoders'] = self._registered_decoders
return d
def __iter__(self):
"\n Return an error message requiring to override ``__iter__`` in ``self``.\n\n As one has to implement specific category related methods (`__iter__` and\n `__contains__`) when writing a new code class which inherits from\n :class:`AbstractCode`, the generic call to `__iter__` has to fail.\n\n EXAMPLES:\n\n We create a new code class::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCode(AbstractCode):\n ....: def __init__(self):\n ....: super().__init__(10)\n\n We check we get a sensible error message while asking for an\n iterator over the elements of our new class::\n\n sage: C = MyCode()\n sage: list(C)\n Traceback (most recent call last):\n ...\n RuntimeError: Please override __iter__ in the implementation of <class '__main__.MyCode'>\n "
raise RuntimeError('Please override __iter__ in the implementation of {}'.format(self.parent()))
def __contains__(self, c):
"\n Return an error message requiring to override ``__contains__`` in ``self``.\n\n As one has to implement specific category related methods (`__iter__` and\n `__contains__`) when writing a new code class which inherits from\n :class:`AbstractCode`, the generic call to `__contains__` has to fail.\n\n EXAMPLES:\n\n We create a new code class::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCode(AbstractCode):\n ....: def __init__(self, length):\n ....: super().__init__(length)\n\n We check we get a sensible error message while asking if an element is\n in our new class::\n\n sage: C = MyCode(3)\n sage: vector((1, 0, 0, 0, 0, 1, 1)) in C\n Traceback (most recent call last):\n ...\n RuntimeError: Please override __contains__ in the implementation of <class '__main__.MyCode'>\n "
raise RuntimeError('Please override __contains__ in the implementation of {}'.format(self.parent()))
def ambient_space(self):
'\n Return an error stating ``ambient_space`` of ``self`` is not implemented.\n\n This method is required by :meth:`__call__`.\n\n EXAMPLES::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCode(AbstractCode):\n ....: def __init__(self, length):\n ....: super().__init__(length)\n sage: C = MyCode(3)\n sage: C.ambient_space()\n Traceback (most recent call last):\n ...\n NotImplementedError: No ambient space implemented for this code.\n '
raise NotImplementedError('No ambient space implemented for this code.')
def __call__(self, m):
"\n Returns either ``m`` if it is a codeword or ``self.encode(m)``\n if it is an element of the message space of the encoder used by\n ``encode``.\n\n This implementation depends on :meth:`ambient_space`.\n\n INPUT:\n\n - ``m`` -- a vector whose length equals to code's length or an element\n of the message space used by ``encode``\n\n - ``**kwargs`` -- extra arguments are forwarded to ``encode``\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector((0, 1, 1, 0))\n sage: C(word)\n (1, 1, 0, 0, 1, 1, 0)\n\n sage: c = C.random_element()\n sage: C(c) == c\n True\n\n TESTS:\n\n If one passes a vector which belongs to the ambient space, it has to be a codeword.\n Otherwise, an exception is raised::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector((0, 1, 1, 0, 0, 1, 0))\n sage: C(word)\n Traceback (most recent call last):\n ...\n ValueError: If the input is a vector which belongs to the ambient space, it has to be a codeword\n "
if (m in self.ambient_space()):
if (m in self):
return m
else:
raise ValueError('If the input is a vector which belongs to the ambient space, it has to be a codeword')
else:
return self.encode(m)
def _repr_(self):
"\n Return an error message requiring to override ``_repr_`` in ``self``.\n\n As one has to implement specific representation methods (`_repr_` and\n `_latex_`) when writing a new code class which inherits from\n :class:`AbstractCode`, the generic call to `_repr_` has to fail.\n\n EXAMPLES:\n\n We create a new code class::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCode(AbstractCode):\n ....: def __init__(self):\n ....: super().__init__(10)\n\n We check we get a sensible error message while asking for a string\n representation of an instance of our new class::\n\n sage: C = MyCode()\n sage: C #random\n Traceback (most recent call last):\n ...\n RuntimeError: Please override _repr_ in the implementation of <class '__main__.MyCode'>\n "
raise RuntimeError('Please override _repr_ in the implementation of {}'.format(self.parent()))
def _latex_(self):
"\n Return an error message requiring to override ``_latex_`` in ``self``.\n\n As one has to implement specific representation methods (`_repr_` and\n `_latex_`) when writing a new code class which inherits from\n :class:`AbstractCode`, the generic call to `_latex_` has to fail.\n\n EXAMPLES:\n\n We create a new code class::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCode(AbstractCode):\n ....: def __init__(self):\n ....: super().__init__(10)\n\n We check we get a sensible error message while asking for a string\n representation of an instance of our new class::\n\n sage: C = MyCode()\n sage: latex(C)\n Traceback (most recent call last):\n ...\n RuntimeError: Please override _latex_ in the implementation of <class '__main__.MyCode'>\n "
raise RuntimeError('Please override _latex_ in the implementation of {}'.format(self.parent()))
def list(self):
'\n Return a list of all elements of this code.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: Clist = C.list()\n sage: Clist[5]; Clist[5] in C\n (1, 0, 1, 0, 1, 0, 1)\n True\n '
return list(self)
def length(self):
'\n Returns the length of this code.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.length()\n 7\n '
return self._length
def metric(self):
"\n Return the metric of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3)\n sage: C.metric()\n 'Hamming'\n "
return self._metric
def add_decoder(self, name, decoder):
'\n Adds an decoder to the list of registered decoders of ``self``.\n\n .. NOTE::\n\n This method only adds ``decoder`` to ``self``, and not to any member of the class\n of ``self``. To know how to add an :class:`sage.coding.decoder.Decoder`, please refer\n to the documentation of :class:`AbstractCode`.\n\n INPUT:\n\n - ``name`` -- the string name for the decoder\n\n - ``decoder`` -- the class name of the decoder\n\n EXAMPLES:\n\n First of all, we create a (very basic) new decoder::\n\n sage: class MyDecoder(sage.coding.decoder.Decoder):\n ....: def __init__(self, code):\n ....: super().__init__(code)\n ....: def _repr_(self):\n ....: return "MyDecoder decoder with associated code %s" % self.code()\n\n We now create a new code::\n\n sage: C = codes.HammingCode(GF(2), 3)\n\n We can add our new decoder to the list of available decoders of C::\n\n sage: C.add_decoder("MyDecoder", MyDecoder)\n sage: sorted(C.decoders_available())\n [\'InformationSet\', \'MyDecoder\', \'NearestNeighbor\', \'Syndrome\']\n\n We can verify that any new code will not know MyDecoder::\n\n sage: C2 = codes.HammingCode(GF(2), 3)\n sage: sorted(C2.decoders_available())\n [\'InformationSet\', \'NearestNeighbor\', \'Syndrome\']\n\n TESTS:\n\n It is impossible to use a name which is in the dictionary of available decoders::\n\n sage: C.add_decoder("Syndrome", MyDecoder)\n Traceback (most recent call last):\n ...\n ValueError: There is already a registered decoder with this name\n '
if (self._registered_decoders == self.__class__._registered_decoders):
self._registered_decoders = copy(self._registered_decoders)
reg_dec = self._registered_decoders
if (name in reg_dec):
raise ValueError('There is already a registered decoder with this name')
reg_dec[name] = decoder
else:
if (name in self._registered_decoders):
raise ValueError('There is already a registered decoder with this name')
reg_dec[name] = decoder
def add_encoder(self, name, encoder):
'\n Adds an encoder to the list of registered encoders of ``self``.\n\n .. NOTE::\n\n This method only adds ``encoder`` to ``self``, and not to any member of the class\n of ``self``. To know how to add an :class:`sage.coding.encoder.Encoder`, please refer\n to the documentation of :class:`AbstractCode`.\n\n INPUT:\n\n - ``name`` -- the string name for the encoder\n\n - ``encoder`` -- the class name of the encoder\n\n EXAMPLES:\n\n First of all, we create a (very basic) new encoder::\n\n sage: class MyEncoder(sage.coding.encoder.Encoder):\n ....: def __init__(self, code):\n ....: super().__init__(code)\n ....: def _repr_(self):\n ....: return "MyEncoder encoder with associated code %s" % self.code()\n\n We now create a new code::\n\n sage: C = codes.HammingCode(GF(2), 3)\n\n We can add our new encoder to the list of available encoders of C::\n\n sage: C.add_encoder("MyEncoder", MyEncoder)\n sage: sorted(C.encoders_available())\n [\'MyEncoder\', \'Systematic\']\n\n We can verify that any new code will not know MyEncoder::\n\n sage: C2 = codes.HammingCode(GF(2), 3)\n sage: sorted(C2.encoders_available())\n [\'Systematic\']\n\n TESTS:\n\n It is impossible to use a name which is in the dictionary of available encoders::\n\n sage: C.add_encoder("Systematic", MyEncoder)\n Traceback (most recent call last):\n ...\n ValueError: There is already a registered encoder with this name\n '
if (self._registered_encoders == self.__class__._registered_encoders):
self._registered_encoders = copy(self._registered_encoders)
reg_enc = self._registered_encoders
if (name in reg_enc):
raise ValueError('There is already a registered encoder with this name')
reg_enc[name] = encoder
else:
if (name in self._registered_encoders):
raise ValueError('There is already a registered encoder with this name')
reg_enc[name] = encoder
def decode_to_code(self, word, decoder_name=None, *args, **kwargs):
"\n Correct the errors in ``word`` and returns a codeword.\n\n INPUT:\n\n - ``word`` -- an element in the ambient space as ``self``\n\n - ``decoder_name`` -- (default: ``None``) Name of the decoder which will be used\n to decode ``word``. The default decoder of ``self`` will be used if\n default value is kept.\n\n - ``args``, ``kwargs`` -- all additional arguments are forwarded to :meth:`decoder`\n\n OUTPUT:\n\n - A vector of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0))\n sage: C.decode_to_code(w_err)\n (1, 1, 0, 0, 1, 1, 0)\n\n It is possible to manually choose the decoder amongst the list of the available ones::\n\n sage: sorted(C.decoders_available())\n ['InformationSet', 'NearestNeighbor', 'Syndrome']\n sage: C.decode_to_code(w_err, 'NearestNeighbor')\n (1, 1, 0, 0, 1, 1, 0)\n "
D = self.decoder(decoder_name, *args, **kwargs)
return D.decode_to_code(word)
def decode_to_message(self, word, decoder_name=None, *args, **kwargs):
"\n Correct the errors in word and decodes it to the message space.\n\n INPUT:\n\n - ``word`` -- an element in the ambient space as ``self``\n\n - ``decoder_name`` -- (default: ``None``) Name of the decoder which will be used\n to decode ``word``. The default decoder of ``self`` will be used if\n default value is kept.\n\n - ``args``, ``kwargs`` -- all additional arguments are forwarded to :meth:`decoder`\n\n OUTPUT:\n\n - A vector of the message space of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: C.decode_to_message(word)\n (0, 1, 1, 0)\n\n It is possible to manually choose the decoder amongst the list of the available ones::\n\n sage: sorted(C.decoders_available())\n ['InformationSet', 'NearestNeighbor', 'Syndrome']\n sage: C.decode_to_message(word, 'NearestNeighbor')\n (0, 1, 1, 0)\n "
return self.unencode(self.decode_to_code(word, decoder_name, *args, **kwargs), **kwargs)
@cached_method
def decoder(self, decoder_name=None, *args, **kwargs):
'\n Return a decoder of ``self``.\n\n INPUT:\n\n - ``decoder_name`` -- (default: ``None``) name of the decoder which will be\n returned. The default decoder of ``self`` will be used if\n default value is kept.\n\n - ``args``, ``kwargs`` -- all additional arguments will be forwarded to the constructor of the decoder\n that will be returned by this method\n\n OUTPUT:\n\n - a decoder object\n\n Besides creating the decoder and returning it, this method also stores\n the decoder in a cache. With this behaviour, each decoder will be created\n at most one time for ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.decoder()\n Syndrome decoder for [7, 4] linear code over GF(2) handling errors of weight up to 1\n\n If there is no decoder for the code, we return an error::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCodeFamily(AbstractCode):\n ....: def __init__(self, length, field):\n ....: sage.coding.abstract_code.AbstractCode.__init__(self, length)\n ....: Parent.__init__(self, base=field, facade=False, category=Sets())\n ....: self._field = field\n ....: def field(self):\n ....: return self._field\n ....: def _repr_(self):\n ....: return "%d dummy code over GF(%s)" % (self.length(), self.field().cardinality())\n sage: D = MyCodeFamily(5, GF(2))\n sage: D.decoder()\n Traceback (most recent call last):\n ...\n NotImplementedError: No decoder implemented for this code.\n\n If the name of a decoder which is not known by ``self`` is passed,\n an exception will be raised::\n\n sage: sorted(C.decoders_available())\n [\'InformationSet\', \'NearestNeighbor\', \'Syndrome\']\n sage: C.decoder(\'Try\')\n Traceback (most recent call last):\n ...\n ValueError: There is no Decoder named \'Try\'.\n The known Decoders are: [\'InformationSet\', \'NearestNeighbor\', \'Syndrome\']\n\n Some decoders take extra arguments. If the user forgets to supply these,\n the error message attempts to be helpful::\n\n sage: C.decoder(\'InformationSet\')\n Traceback (most recent call last):\n ...\n ValueError: Constructing the InformationSet decoder failed,\n possibly due to missing or incorrect parameters.\n The constructor requires the arguments [\'number_errors\'].\n It takes the optional arguments [\'algorithm\'].\n It accepts unspecified arguments as well. See the documentation of\n sage.coding.information_set_decoder.LinearCodeInformationSetDecoder\n for more details.\n\n '
if (not self._default_decoder_name):
raise NotImplementedError('No decoder implemented for this code.')
if (decoder_name is None):
decoder_name = self._default_decoder_name
if (decoder_name in self._registered_decoders):
decClass = self._registered_decoders[decoder_name]
try:
return decClass(self, *args, **kwargs)
except TypeError:
raise ValueError('Constructing the {0} decoder failed, possibly due to missing or incorrect parameters.\n{1}'.format(decoder_name, _explain_constructor(decClass)))
else:
raise ValueError("There is no Decoder named '{0}'. The known Decoders are: {1}".format(decoder_name, self.decoders_available()))
def decoders_available(self, classes=False):
"\n Returns a list of the available decoders' names for ``self``.\n\n INPUT:\n\n - ``classes`` -- (default: ``False``) if ``classes`` is set to ``True``,\n return instead a :class:`dict` mapping available decoder name to the\n associated decoder class.\n\n OUTPUT: a list of strings, or a :class:`dict` mapping strings to classes.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.decoders_available()\n ['InformationSet', 'NearestNeighbor', 'Syndrome']\n\n sage: dictionary = C.decoders_available(True)\n sage: sorted(dictionary.keys())\n ['InformationSet', 'NearestNeighbor', 'Syndrome']\n sage: dictionary['NearestNeighbor']\n <class 'sage.coding.linear_code.LinearCodeNearestNeighborDecoder'>\n "
if classes:
return copy(self._registered_decoders)
return sorted(self._registered_decoders)
def encode(self, word, encoder_name=None, *args, **kwargs):
"\n Transforms an element of a message space into a codeword.\n\n INPUT:\n\n - ``word`` -- an element of a message space of the code\n\n - ``encoder_name`` -- (default: ``None``) Name of the encoder which will be used\n to encode ``word``. The default encoder of ``self`` will be used if\n default value is kept.\n\n - ``args``, ``kwargs`` -- all additional arguments are forwarded to the construction of the\n encoder that is used..\n\n One can use the following shortcut to encode a word ::\n\n C(word)\n\n OUTPUT:\n\n - a vector of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector((0, 1, 1, 0))\n sage: C.encode(word)\n (1, 1, 0, 0, 1, 1, 0)\n sage: C(word)\n (1, 1, 0, 0, 1, 1, 0)\n\n It is possible to manually choose the encoder amongst the list of the available ones::\n\n sage: sorted(C.encoders_available())\n ['GeneratorMatrix', 'Systematic']\n sage: word = vector((0, 1, 1, 0))\n sage: C.encode(word, 'GeneratorMatrix')\n (1, 1, 0, 0, 1, 1, 0)\n "
E = self.encoder(encoder_name, *args, **kwargs)
return E.encode(word)
@cached_method
def encoder(self, encoder_name=None, *args, **kwargs):
'\n Returns an encoder of ``self``.\n\n The returned encoder provided by this method is cached.\n\n This methods creates a new instance of the encoder subclass designated by ``encoder_name``.\n While it is also possible to do the same by directly calling the subclass\' constructor,\n it is strongly advised to use this method to take advantage of the caching mechanism.\n\n INPUT:\n\n - ``encoder_name`` -- (default: ``None``) name of the encoder which will be\n returned. The default encoder of ``self`` will be used if\n default value is kept.\n\n - ``args``, ``kwargs`` -- all additional arguments are forwarded to the constructor of the encoder\n this method will return.\n\n OUTPUT:\n\n - an Encoder object.\n\n .. NOTE::\n\n The default encoder always has `F^{k}` as message space, with `k` the dimension\n of ``self`` and `F` the base ring of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.encoder()\n Generator matrix-based encoder for [7, 4] linear code over GF(2)\n\n If there is no encoder for the code, we return an error::\n\n sage: from sage.coding.abstract_code import AbstractCode\n sage: class MyCodeFamily(AbstractCode):\n ....: def __init__(self, length, field):\n ....: sage.coding.abstract_code.AbstractCode.__init__(self, length)\n ....: Parent.__init__(self, base=field, facade=False, category=Sets())\n ....: self._field = field\n ....: def field(self):\n ....: return self._field\n ....: def _repr_(self):\n ....: return "%d dummy code over GF(%s)" % (self.length(),\n ....: self.field().cardinality())\n sage: D = MyCodeFamily(5, GF(2))\n sage: D.encoder()\n Traceback (most recent call last):\n ...\n NotImplementedError: No encoder implemented for this code.\n\n We check that the returned encoder is cached::\n\n sage: C.encoder.is_in_cache()\n True\n\n If the name of an encoder which is not known by ``self`` is passed,\n an exception will be raised::\n\n sage: sorted(C.encoders_available())\n [\'GeneratorMatrix\', \'Systematic\']\n sage: C.encoder(\'NonExistingEncoder\')\n Traceback (most recent call last):\n ...\n ValueError: There is no Encoder named \'NonExistingEncoder\'.\n The known Encoders are: [\'GeneratorMatrix\', \'Systematic\']\n\n Some encoders take extra arguments. If the user incorrectly supplies\n these, the error message attempts to be helpful::\n\n sage: C.encoder(\'Systematic\', strange_parameter=True)\n Traceback (most recent call last):\n ...\n ValueError: Constructing the Systematic encoder failed,\n possibly due to missing or incorrect parameters.\n The constructor requires no arguments. It takes the optional\n arguments [\'systematic_positions\']. See the documentation of\n sage.coding.linear_code_no_metric.LinearCodeSystematicEncoder\n for more details.\n '
if (not self._default_encoder_name):
raise NotImplementedError('No encoder implemented for this code.')
if (encoder_name is None):
encoder_name = self._default_encoder_name
if (encoder_name in self._registered_encoders):
encClass = self._registered_encoders[encoder_name]
try:
return encClass(self, *args, **kwargs)
except TypeError:
raise ValueError('Constructing the {0} encoder failed, possibly due to missing or incorrect parameters.\n{1}'.format(encoder_name, _explain_constructor(encClass)))
else:
raise ValueError("There is no Encoder named '{0}'. The known Encoders are: {1}".format(encoder_name, self.encoders_available()))
def encoders_available(self, classes=False):
"\n Returns a list of the available encoders' names for ``self``.\n\n INPUT:\n\n - ``classes`` -- (default: ``False``) if ``classes`` is set to ``True``,\n return instead a :class:`dict` mapping available encoder name to the\n associated encoder class.\n\n OUTPUT: a list of strings, or a :class:`dict` mapping strings to classes.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: C.encoders_available()\n ['GeneratorMatrix', 'Systematic']\n sage: dictionary = C.encoders_available(True)\n sage: sorted(dictionary.items())\n [('GeneratorMatrix', <class 'sage.coding.linear_code.LinearCodeGeneratorMatrixEncoder'>),\n ('Systematic', <class 'sage.coding.linear_code_no_metric.LinearCodeSystematicEncoder'>)]\n "
if classes:
return copy(self._registered_encoders)
return sorted(self._registered_encoders)
def unencode(self, c, encoder_name=None, nocheck=False, **kwargs):
'\n Returns the message corresponding to ``c``.\n\n This is the inverse of :meth:`encode`.\n\n INPUT:\n\n - ``c`` -- a codeword of ``self``.\n\n - ``encoder_name`` -- (default: ``None``) name of the decoder which will be used\n to decode ``word``. The default decoder of ``self`` will be used if\n default value is kept.\n\n - ``nocheck`` -- (default: ``False``) checks if ``c`` is in ``self``. You might set\n this to ``True`` to disable the check for saving computation. Note that if ``c`` is\n not in ``self`` and ``nocheck = True``, then the output of :meth:`unencode` is\n not defined (except that it will be in the message space of ``self``).\n\n - ``kwargs`` -- all additional arguments are forwarded to the construction of the\n encoder that is used.\n\n OUTPUT:\n\n - an element of the message space of ``encoder_name`` of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: c = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: C.unencode(c)\n (0, 1, 1, 0)\n '
E = self.encoder(encoder_name, **kwargs)
return E.unencode(c, nocheck)
def random_element(self, *args, **kwds):
"\n Returns a random codeword; passes other positional and keyword\n arguments to ``random_element()`` method of vector space.\n\n OUTPUT:\n\n - Random element of the vector space of this code\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(4,'a'), 3)\n sage: C.random_element() # random test\n (1, 0, 0, a + 1, 1, a, a, a + 1, a + 1, 1, 1, 0, a + 1, a, 0, a, a, 0, a, a, 1)\n\n Passes extra positional or keyword arguments through::\n\n sage: C.random_element(prob=.5, distribution='1/n') # random test\n (1, 0, a, 0, 0, 0, 0, a + 1, 0, 0, 0, 0, 0, 0, 0, 0, a + 1, a + 1, 1, 0, 0)\n\n TESTS:\n\n Test that the codeword returned is immutable (see :trac:`16469`)::\n\n sage: c = C.random_element()\n sage: c.is_immutable()\n True\n\n Test that codeword returned has the same parent as any non-random codeword\n (see :trac:`19653`)::\n\n sage: C = codes.random_linear_code(GF(16, 'a'), 10, 4)\n sage: c1 = C.random_element()\n sage: c2 = C[1]\n sage: c1.parent() == c2.parent()\n True\n "
E = self.encoder()
M = E.message_space()
m = M.random_element(*args, **kwds)
c = E.encode(m)
c.set_immutable()
return c
|
class AGCode(AbstractLinearCode):
'\n Base class of algebraic geometry codes.\n\n A subclass of this class is required to define ``_function_field``\n attribute that refers to an abstract functiom field or the function field\n of the underlying curve used to construct a code of the class.\n '
def base_function_field(self):
'\n Return the function field used to construct the code.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: p = C([0,0])\n sage: Q, = p.places()\n sage: pls.remove(Q)\n sage: G = 5*Q\n sage: code = codes.EvaluationAGCode(pls, G)\n sage: code.base_function_field()\n Function field in y defined by y^2 + y + x^3\n '
return self._function_field
|
class EvaluationAGCode(AGCode):
'\n Evaluation AG code defined by rational places ``pls`` and a divisor ``G``.\n\n INPUT:\n\n - ``pls`` -- a list of rational places of a function field\n\n - ``G`` -- a divisor whose support is disjoint from ``pls``\n\n If ``G`` is a place, then it is regarded as a prime divisor.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: G = 5*Q\n sage: codes.EvaluationAGCode(pls, G)\n [8, 5] evaluation AG code over GF(4)\n\n sage: G = F.get_place(5)\n sage: codes.EvaluationAGCode(pls, G)\n [8, 5] evaluation AG code over GF(4)\n '
_registered_encoders = {}
_registered_decoders = {}
def __init__(self, pls, G):
'\n Initialize.\n\n TESTS::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls = [pl for pl in pls if pl != Q]\n sage: G = 5*Q\n sage: code = codes.EvaluationAGCode(pls, G)\n sage: TestSuite(code).run()\n '
if issubclass(type(G), FunctionFieldPlace):
G = G.divisor()
F = G.parent().function_field()
K = F.constant_base_field()
n = len(pls)
if any(((p.degree() > 1) for p in pls)):
raise ValueError('there is a nonrational place among the places')
if any(((p in pls) for p in G.support())):
raise ValueError('the support of the divisor is not disjoint from the places')
self._registered_encoders['evaluation'] = EvaluationAGCodeEncoder
self._registered_decoders['K'] = EvaluationAGCodeUniqueDecoder
super().__init__(K, n, default_encoder_name='evaluation', default_decoder_name='K')
basis_functions = G.basis_function_space()
m = matrix([vector(K, [b.evaluate(p) for p in pls]) for b in basis_functions])
I = MatrixSpace(K, m.nrows()).identity_matrix()
mI = m.augment(I)
mI.echelonize()
M = mI.submatrix(0, 0, m.nrows(), m.ncols())
T = mI.submatrix(0, m.ncols())
r = M.rank()
self._generator_matrix = M.submatrix(0, 0, r)
self._basis_functions = [sum(((c * b) for (c, b) in zip(T[i], basis_functions))) for i in range(r)]
self._pls = tuple(pls)
self._G = G
self._function_field = F
def __eq__(self, other):
'\n Test equality of ``self`` with ``other``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: codes.EvaluationAGCode(pls, 5*Q) == codes.EvaluationAGCode(pls, 6*Q)\n False\n '
if (self is other):
return True
if (not isinstance(other, EvaluationAGCode)):
return False
return ((self._pls == other._pls) and (self._G == other._G))
def __hash__(self):
'\n Return the hash value of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.EvaluationAGCode(pls, 5*Q)\n sage: {code: 1}\n {[8, 5] evaluation AG code over GF(4): 1}\n '
return hash((self._pls, self._G))
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: codes.EvaluationAGCode(pls, 7*Q)\n [8, 7] evaluation AG code over GF(4)\n '
return '[{}, {}] evaluation AG code over GF({})'.format(self.length(), self.dimension(), self.base_field().cardinality())
def _latex_(self):
'\n Return the latex representation of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.EvaluationAGCode(pls, 3*Q)\n sage: latex(code)\n [8, 3]\\text{ evaluation AG code over }\\Bold{F}_{2^{2}}\n '
return '[{}, {}]\\text{{ evaluation AG code over }}{}'.format(self.length(), self.dimension(), self.base_field()._latex_())
def basis_functions(self):
'\n Return the basis functions associated with the generator matrix.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.EvaluationAGCode(pls, 3*Q)\n sage: code.basis_functions()\n (y + a*x + 1, y + x, (a + 1)*x)\n sage: matrix([[f.evaluate(p) for p in pls] for f in code.basis_functions()])\n [ 1 0 0 1 a a + 1 1 0]\n [ 0 1 0 1 1 0 a + 1 a]\n [ 0 0 1 1 a a a + 1 a + 1]\n '
return tuple(self._basis_functions)
def generator_matrix(self):
'\n Return a generator matrix of the code.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.EvaluationAGCode(pls, 3*Q)\n sage: code.generator_matrix()\n [ 1 0 0 1 a a + 1 1 0]\n [ 0 1 0 1 1 0 a + 1 a]\n [ 0 0 1 1 a a a + 1 a + 1]\n '
return self._generator_matrix
def designed_distance(self):
'\n Return the designed distance of the AG code.\n\n If the code is of dimension zero, then a :class:`ValueError` is raised.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.EvaluationAGCode(pls, 3*Q)\n sage: code.designed_distance()\n 5\n '
if (self.dimension() == 0):
raise ValueError('not defined for zero code')
d = (self.length() - self._G.degree())
return (d if (d > 0) else 1)
|
class DifferentialAGCode(AGCode):
'\n Differential AG code defined by rational places ``pls`` and a divisor ``G``\n\n INPUT:\n\n - ``pls`` -- a list of rational places of a function field\n\n - ``G`` -- a divisor whose support is disjoint from ``pls``\n\n If ``G`` is a place, then it is regarded as a prime divisor.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = A.curve(y^3 + y - x^4)\n sage: Q = C.places_at_infinity()[0]\n sage: O = C([0,0]).place()\n sage: pls = [p for p in C.places() if p not in [O, Q]]\n sage: G = -O + 3*Q\n sage: codes.DifferentialAGCode(pls, -O + Q)\n [3, 2] differential AG code over GF(4)\n\n sage: F = C.function_field()\n sage: G = F.get_place(1)\n sage: codes.DifferentialAGCode(pls, G)\n [3, 1] differential AG code over GF(4)\n '
_registered_encoders = {}
_registered_decoders = {}
def __init__(self, pls, G):
'\n Initialize.\n\n TESTS::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: TestSuite(code).run()\n '
if issubclass(type(G), FunctionFieldPlace):
G = G.divisor()
F = G.parent().function_field()
K = F.constant_base_field()
n = len(pls)
if any(((p.degree() > 1) for p in pls)):
raise ValueError('there is a nonrational place among the places')
if any(((p in pls) for p in G.support())):
raise ValueError('the support of the divisor is not disjoint from the places')
self._registered_encoders['residue'] = DifferentialAGCodeEncoder
self._registered_decoders['K'] = DifferentialAGCodeUniqueDecoder
super().__init__(K, n, default_encoder_name='residue', default_decoder_name='K')
basis_differentials = ((- sum(pls)) + G).basis_differential_space()
m = matrix([vector(K, [w.residue(p) for p in pls]) for w in basis_differentials])
I = MatrixSpace(K, m.nrows()).identity_matrix()
mI = m.augment(I)
mI.echelonize()
M = mI.submatrix(0, 0, m.nrows(), m.ncols())
T = mI.submatrix(0, m.ncols())
r = M.rank()
self._generator_matrix = M.submatrix(0, 0, r)
self._basis_differentials = [sum(((c * w) for (c, w) in zip(T[i], basis_differentials))) for i in range(r)]
self._pls = tuple(pls)
self._G = G
self._function_field = F
def __eq__(self, other):
'\n Test equality of ``self`` with ``other``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: c1 = codes.DifferentialAGCode(pls, 3*Q)\n sage: c2 = codes.DifferentialAGCode(pls, 3*Q)\n sage: c1 is c2\n False\n sage: c1 == c2\n True\n '
if (self is other):
return True
if (not isinstance(other, DifferentialAGCode)):
return False
return ((self._pls == other._pls) and (self._G == other._G))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: {code: 1}\n {[8, 5] differential AG code over GF(4): 1}\n '
return hash((self._pls, self._G))
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: codes.DifferentialAGCode(pls, 3*Q)\n [8, 5] differential AG code over GF(4)\n '
return '[{}, {}] differential AG code over GF({})'.format(self.length(), self.dimension(), self.base_field().cardinality())
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: latex(code)\n [8, 5]\\text{ differential AG code over }\\Bold{F}_{2^{2}}\n '
return '[{}, {}]\\text{{ differential AG code over }}{}'.format(self.length(), self.dimension(), self.base_field()._latex_())
def basis_differentials(self):
'\n Return the basis differentials associated with the generator matrix.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: matrix([[w.residue(p) for p in pls]\n ....: for w in code.basis_differentials()])\n [ 1 0 0 0 0 a + 1 a + 1 1]\n [ 0 1 0 0 0 a + 1 a 0]\n [ 0 0 1 0 0 a 1 a]\n [ 0 0 0 1 0 a 0 a + 1]\n [ 0 0 0 0 1 1 1 1]\n '
return tuple(self._basis_differentials)
def generator_matrix(self):
'\n Return a generator matrix of the code.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: code.generator_matrix()\n [ 1 0 0 0 0 a + 1 a + 1 1]\n [ 0 1 0 0 0 a + 1 a 0]\n [ 0 0 1 0 0 a 1 a]\n [ 0 0 0 1 0 a 0 a + 1]\n [ 0 0 0 0 1 1 1 1]\n '
return self._generator_matrix
def designed_distance(self):
'\n Return the designed distance of the differential AG code.\n\n If the code is of dimension zero, then a :class:`ValueError` is raised.\n\n EXAMPLES::\n\n sage: k.<a> = GF(4)\n sage: A.<x,y> = AffineSpace(k, 2)\n sage: C = Curve(y^2 + y - x^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Q, = C.places_at_infinity()\n sage: pls.remove(Q)\n sage: code = codes.DifferentialAGCode(pls, 3*Q)\n sage: code.designed_distance()\n 3\n '
if (self.dimension() == 0):
raise ValueError('not defined for zero code')
d = ((self._G.degree() - (2 * self._function_field.genus())) + 2)
return (d if (d > 0) else 1)
|
class CartierCode(AGCode):
'\n Cartier code defined by rational places ``pls`` and a divisor ``G`` of a function field.\n\n INPUT:\n\n - ``pls`` -- a list of rational places\n\n - ``G`` -- a divisor whose support is disjoint from ``pls``\n\n - ``r`` -- integer (default: 1)\n\n - ``name`` -- string; name of the generator of the subfield `\\GF{p^r}`\n\n OUTPUT: Cartier code over `\\GF{p^r}` where `p` is the characteristic of the\n base constant field of the function field\n\n Note that if ``r`` is 1 the default, then ``name`` can be omitted.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: code.minimum_distance() # long time\n 2\n '
def __init__(self, pls, G, r=1, name=None):
'\n Initialize.\n\n TESTS::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: TestSuite(code).run() # long time\n '
F = G.parent().function_field()
K = F.constant_base_field()
if any(((p.degree() > 1) for p in pls)):
raise ValueError('there is a nonrational place among the places')
if any(((p in pls) for p in G.support())):
raise ValueError('the support of the divisor is not disjoint from the places')
if ((K.degree() % r) != 0):
raise ValueError('{} does not divide the degree of the constant base field'.format(r))
n = len(pls)
D = sum(pls)
p = K.characteristic()
subfield = K.subfield(r, name=name)
E = (G - D)
Grp = E.parent()
(V, fr_V, to_V) = E.differential_space()
EE = Grp(0)
dic = E.dict()
for place in dic:
mul = dic[place]
if (mul > 0):
mul = (mul // (p ** r))
EE += (mul * place)
(W, fr_W, to_W) = EE.differential_space()
a = K.gen()
field_basis = [(a ** i) for i in range(K.degree())]
basis = E.basis_differential_space()
m = []
for w in basis:
for c in field_basis:
cw = (F(c) * w)
carcw = cw
for i in range(r):
carcw = carcw.cartier()
m.append([f for e in to_W((carcw - cw)) for f in vector(e)])
ker = matrix(m).kernel()
R = []
s = len(field_basis)
ncols = (s * len(basis))
for row in ker.basis():
v = vector([K(row[d:(d + s)]) for d in range(0, ncols, s)])
R.append(fr_V(v))
m = []
col_index = D.support()
for w in R:
row = []
for p in col_index:
res = w.residue(p).trace()
c = subfield(res)
row.append(c)
m.append(row)
self._generator_matrix = matrix(m).row_space().basis_matrix()
self._pls = tuple(pls)
self._G = G
self._r = r
self._function_field = F
self._registered_encoders['GeneratorMatrix'] = LinearCodeGeneratorMatrixEncoder
self._registered_decoders['Syndrome'] = LinearCodeSyndromeDecoder
super().__init__(subfield, n, default_encoder_name='GeneratorMatrix', default_decoder_name='Syndrome')
def __eq__(self, other):
'\n Test equality of ``self`` with ``other``.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: c1 = codes.CartierCode(pls, 3*Z) # long time\n sage: c2 = codes.CartierCode(pls, 1*Z) # long time\n sage: c1 == c2 # long time\n False\n '
if (self is other):
return True
if (not isinstance(other, CartierCode)):
return False
return ((self._pls == other._pls) and (self._G == other._G) and (self._r == other._r))
def __hash__(self):
'\n Return the hash of ``self``.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: {code: 1} # long time\n {[9, 4] Cartier code over GF(3): 1}\n '
return hash((self._pls, self._G, self._r))
def _repr_(self):
'\n Return the string representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: codes.CartierCode(pls, G) # long time\n [9, 4] Cartier code over GF(3)\n '
return '[{}, {}] Cartier code over GF({})'.format(self.length(), self.dimension(), self.base_field().cardinality())
def _latex_(self):
'\n Return the latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: latex(code) # long time\n [9, 4]\\text{ Cartier code over }\\Bold{F}_{3}\n '
return '[{}, {}]\\text{{ Cartier code over }}{}'.format(self.length(), self.dimension(), self.base_field()._latex_())
def generator_matrix(self):
'\n Return a generator matrix of the Cartier code.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: code.generator_matrix() # long time\n [1 0 0 2 2 0 2 2 0]\n [0 1 0 2 2 0 2 2 0]\n [0 0 1 0 0 0 0 0 2]\n [0 0 0 0 0 1 0 0 2]\n '
return self._generator_matrix
def designed_distance(self):
'\n Return the designed distance of the Cartier code.\n\n The designed distance is that of the differential code of which the\n Cartier code is a subcode.\n\n EXAMPLES::\n\n sage: F.<a> = GF(9)\n sage: P.<x,y,z> = ProjectiveSpace(F, 2);\n sage: C = Curve(x^3*y + y^3*z + x*z^3)\n sage: F = C.function_field()\n sage: pls = F.places()\n sage: Z, = C(0,0,1).places()\n sage: pls.remove(Z)\n sage: G = 3*Z\n sage: code = codes.CartierCode(pls, G) # long time\n sage: code.designed_distance() # long time\n 1\n '
if (self.dimension() == 0):
raise ValueError('not defined for zero code')
d = ((self._G.degree() - (2 * self._function_field.genus())) + 2)
return (d if (d > 0) else 1)
|
class BCHCode(CyclicCode):
'\n Representation of a BCH code seen as a cyclic code.\n\n INPUT:\n\n - ``base_field`` -- the base field for this code\n\n - ``length`` -- the length of the code\n\n - ``designed_distance`` -- the designed minimum distance of the code\n\n - ``primitive_root`` -- (default: ``None``) the primitive root to use when\n creating the set of roots for the generating polynomial over the\n splitting field. It has to be of multiplicative order ``length`` over\n this field. If the splitting field is not ``field``, it also has to be a\n polynomial in ``zx``, where ``x`` is the degree of the extension field.\n For instance, over `\\GF{16}`, it has to be a polynomial in ``z4``.\n\n - ``offset`` -- (default: ``1``) the first element in the defining set\n\n - ``jump_size`` -- (default: ``1``) the jump size between two elements of\n the defining set. It must be coprime with the multiplicative order of\n ``primitive_root``.\n\n - ``b`` -- (default: ``0``) is exactly the same as ``offset``. It is only\n here for retro-compatibility purposes with the old signature of\n :meth:`codes.BCHCode` and will be removed soon.\n\n EXAMPLES:\n\n As explained above, BCH codes can be built through various parameters::\n\n sage: C = codes.BCHCode(GF(2), 15, 7, offset=1)\n sage: C\n [15, 5] BCH Code over GF(2) with designed distance 7\n sage: C.generator_polynomial()\n x^10 + x^8 + x^5 + x^4 + x^2 + x + 1\n\n sage: C = codes.BCHCode(GF(2), 15, 4, offset=1, jump_size=8)\n sage: C\n [15, 7] BCH Code over GF(2) with designed distance 4\n sage: C.generator_polynomial()\n x^8 + x^7 + x^6 + x^4 + 1\n\n BCH codes are cyclic, and can be interfaced into the :class:`CyclicCode` class.\n The smallest GRS code which contains a given BCH code can also be computed,\n and these two codes may be equal::\n\n sage: C = codes.BCHCode(GF(16), 15, 7)\n sage: R = C.bch_to_grs()\n sage: codes.CyclicCode(code=R) == codes.CyclicCode(code=C)\n True\n\n The `\\delta = 15, 1` cases (trivial codes) also work::\n\n sage: C = codes.BCHCode(GF(16), 15, 1)\n sage: C.dimension()\n 15\n sage: C.defining_set()\n []\n sage: C.generator_polynomial()\n 1\n sage: C = codes.BCHCode(GF(16), 15, 15)\n sage: C.dimension()\n 1\n '
def __init__(self, base_field, length, designed_distance, primitive_root=None, offset=1, jump_size=1, b=0):
'\n TESTS:\n\n ``designed_distance`` must be between 1 and ``length`` (inclusive),\n otherwise an exception is raised::\n\n sage: C = codes.BCHCode(GF(2), 15, 16)\n Traceback (most recent call last):\n ...\n ValueError: designed_distance must belong to [1, n]\n '
if (not (0 < designed_distance <= length)):
raise ValueError('designed_distance must belong to [1, n]')
if ((base_field not in Fields()) or (not base_field.is_finite())):
raise ValueError('base_field has to be a finite field')
q = base_field.cardinality()
s = Zmod(length)(q).multiplicative_order()
if (gcd(jump_size, ((q ** s) - 1)) != 1):
raise ValueError('jump_size must be coprime with the order of the multiplicative group of the splitting field')
D = [((offset + (jump_size * i)) % length) for i in range((designed_distance - 1))]
super().__init__(field=base_field, length=length, D=D, primitive_root=primitive_root)
self._default_decoder_name = 'UnderlyingGRS'
self._jump_size = jump_size
self._offset = offset
self._designed_distance = designed_distance
def __eq__(self, other):
"\n Tests equality between BCH Code objects.\n\n EXAMPLES::\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: C1 = codes.BCHCode(F, n, 2)\n sage: C2 = codes.BCHCode(F, n, 2)\n sage: C1 == C2\n True\n "
return (isinstance(other, BCHCode) and (self.length() == other.length()) and (self.jump_size() == other.jump_size()) and (self.offset() == other.offset()) and (self.primitive_root() == other.primitive_root()))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 7)\n sage: C\n [15, 5] BCH Code over GF(2) with designed distance 7\n '
return ('[%s, %s] BCH Code over GF(%s) with designed distance %d' % (self.length(), self.dimension(), self.base_field().cardinality(), self.designed_distance()))
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 7)\n sage: latex(C)\n [15, 5] \\textnormal{ BCH Code over } \\Bold{F}_{2} \\textnormal{ with designed distance } 7\n '
return ('[%s, %s] \\textnormal{ BCH Code over } %s \\textnormal{ with designed distance } %s' % (self.length(), self.dimension(), self.base_field()._latex_(), self.designed_distance()))
def jump_size(self):
'\n Return the jump size between two consecutive elements of the defining\n set of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 4, jump_size = 2)\n sage: C.jump_size()\n 2\n '
return self._jump_size
def offset(self):
'\n Return the offset which was used to compute the elements in\n the defining set of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 4, offset = 1)\n sage: C.offset()\n 1\n '
return self._offset
def designed_distance(self):
'\n Return the designed distance of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 4)\n sage: C.designed_distance()\n 4\n '
return self._designed_distance
def bch_to_grs(self):
'\n Return the underlying GRS code from which ``self`` was derived.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 3)\n sage: RS = C.bch_to_grs()\n sage: RS\n [15, 13, 3] Reed-Solomon Code over GF(16)\n sage: C.generator_matrix() * RS.parity_check_matrix().transpose() == 0\n True\n '
l = self.jump_size()
b = self.offset()
n = self.length()
designed_distance = self.designed_distance()
grs_dim = ((n - designed_distance) + 1)
alpha = self.primitive_root()
alpha_l = (alpha ** l)
alpha_b = (alpha ** b)
evals = [(alpha_l ** i) for i in range(n)]
pcm = [(alpha_b ** i) for i in range(n)]
multipliers_product = [(1 / prod([(evals[i] - evals[h]) for h in range(n) if (h != i)])) for i in range(n)]
column_multipliers = [(multipliers_product[i] / pcm[i]) for i in range(n)]
return GeneralizedReedSolomonCode(evals, grs_dim, column_multipliers)
|
class BCHUnderlyingGRSDecoder(Decoder):
'\n A decoder which decodes through the underlying\n :class:`sage.coding.grs_code.GeneralizedReedSolomonCode` code of the provided\n BCH code.\n\n INPUT:\n\n - ``code`` -- The associated code of this decoder.\n\n - ``grs_decoder`` -- The string name of the decoder to use over the\n underlying GRS code\n\n - ``**kwargs`` -- All extra arguments are forwarded to the GRS decoder\n '
def __init__(self, code, grs_decoder='KeyEquationSyndrome', **kwargs):
"\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: D\n Decoder through the underlying GRS code of [15, 11] BCH Code over GF(4) with designed distance 3\n "
self._grs_code = code.bch_to_grs()
self._grs_decoder = self._grs_code.decoder(grs_decoder, **kwargs)
self._decoder_type = copy(self._grs_decoder.decoder_type())
super().__init__(code, code.ambient_space(), 'Vector')
def _repr_(self):
"\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: D\n Decoder through the underlying GRS code of [15, 11] BCH Code over GF(4) with designed distance 3\n "
return ('Decoder through the underlying GRS code of %s' % self.code())
def _latex_(self):
"\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: latex(D)\n \\textnormal{Decoder through the underlying GRS code of } [15, 11] \\textnormal{ BCH Code over } \\Bold{F}_{2^{2}} \\textnormal{ with designed distance } 3\n "
return ('\\textnormal{Decoder through the underlying GRS code of } %s' % self.code()._latex_())
def grs_code(self):
"\n Return the underlying GRS code of :meth:`sage.coding.decoder.Decoder.code`.\n\n .. NOTE::\n\n Let us explain what is the underlying GRS code of a BCH code of\n length `n` over `F` with parameters `b, \\delta, \\ell`. Let\n `c \\in F^n` and `\\alpha` a primitive root of the splitting field.\n We know:\n\n\n .. MATH::\n\n \\begin{aligned}\n c \\in \\mathrm{BCH} &\\iff \\sum_{i=0}^{n-1} c_i (\\alpha^{b + \\ell j})^i =0, \\quad j=0,\\dots,\\delta-2\\\\\n & \\iff H c = 0\n \\end{aligned}\n\n\n where `H = A \\times D` with:\n\n .. MATH::\n\n \\begin{aligned}\n A = &\\, \\begin{pmatrix}\n 1 & \\dots & 1 \\\\\n ~ & ~ & ~ \\\\\n (\\alpha^{0 \\times \\ell})^{\\delta-2} & \\dots & (\\alpha^{(n-1) \\ell})^{\\delta-2}\n \\end{pmatrix}\\\\\n D =&\\, \\begin{pmatrix}\n 1 & 0 & \\dots & 0 \\\\\n 0 & \\alpha^b & ~ & ~ \\\\\n \\dots & & \\dots & 0 \\\\\n 0 & \\dots & 0 & \\alpha^{b(n-1)} \\end{pmatrix}\n \\end{aligned}\n\n The BCH code is orthogonal to the GRS code `C'` of dimension\n `\\delta - 1` with evaluation points\n `\\{1 = \\alpha^{0 \\times \\ell}, \\dots, \\alpha^{(n-1) \\ell} \\}`\n and associated multipliers\n `\\{1 = \\alpha^{0 \\times b}, \\dots, \\alpha^{(n-1) b} \\}`.\n The underlying GRS code is the dual code of `C'`.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 3)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: D.grs_code()\n [15, 13, 3] Reed-Solomon Code over GF(16)\n "
return self._grs_code
def grs_decoder(self):
"\n Return the decoder used to decode words of :meth:`grs_code`.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: D.grs_decoder()\n Key equation decoder for [15, 13, 3] Generalized Reed-Solomon Code over GF(16)\n "
return self._grs_decoder
def bch_word_to_grs(self, c):
'\n Return ``c`` converted as a codeword of :meth:`grs_code`.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(2), 15, 3)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: c = C.random_element()\n sage: y = D.bch_word_to_grs(c)\n sage: y.parent()\n Vector space of dimension 15 over Finite Field in z4 of size 2^4\n sage: y in D.grs_code()\n True\n '
phi = self.code().field_embedding()
return vector([phi(x) for x in c])
def grs_word_to_bch(self, c):
"\n Return ``c`` converted as a codeword of :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: Cgrs = D.grs_code()\n sage: Fgrs = Cgrs.base_field()\n sage: b = Fgrs.gen()\n sage: c = vector(Fgrs, [0, b^2 + b, 1, b^2 + b, 0, 1, 1, 1,\n ....: b^2 + b, 0, 0, b^2 + b + 1, b^2 + b, 0, 1])\n sage: D.grs_word_to_bch(c)\n (0, a, 1, a, 0, 1, 1, 1, a, 0, 0, a + 1, a, 0, 1)\n "
C = self.code()
sec = C.field_embedding().section()
return vector([sec(x) for x in c])
def decode_to_code(self, y):
'\n Decodes ``y`` to a codeword in :meth:`sage.coding.decoder.Decoder.code`.\n\n EXAMPLES::\n\n sage: F = GF(4, \'a\')\n sage: a = F.gen()\n sage: C = codes.BCHCode(F, 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: y = vector(F, [a, a + 1, 1, a + 1, 1, a, a + 1,\n ....: a + 1, 0, 1, a + 1, 1, 1, 1, a])\n sage: D.decode_to_code(y)\n (a, a + 1, 1, a + 1, 1, a, a + 1, a + 1, 0, 1, a + 1, 1, 1, 1, a)\n sage: D.decode_to_code(y) in C\n True\n\n We check that it still works when, while list-decoding, the GRS decoder\n output some words which do not lie in the BCH code::\n\n sage: C = codes.BCHCode(GF(2), 31, 15)\n sage: C\n [31, 6] BCH Code over GF(2) with designed distance 15\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C, "GuruswamiSudan", tau=8)\n sage: Dgrs = D.grs_decoder()\n sage: c = vector(GF(2), [1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0,\n ....: 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0])\n sage: y = vector(GF(2), [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1,\n ....: 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0])\n sage: print (c in C and (c-y).hamming_weight() == 8)\n True\n sage: Dgrs.decode_to_code(y)\n [(1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1,\n 0, 1, 1, 0, 1, 0, 0),\n (1, z5^3 + z5^2 + z5 + 1, z5^4 + z5^2 + z5, z5^4 + z5^3 + z5^2 + 1, 0, 0,\n z5^4 + z5 + 1, 1, z5^4 + z5^2 + z5, 0, 1, z5^4 + z5, 1, 0, 1, 1, 1, 0,\n 0, z5^4 + z5^3 + 1, 1, 0, 1, 1, 1, 1, z5^4 + z5^3 + z5 + 1, 1, 1, 0, 0)]\n sage: D.decode_to_code(y) == [c]\n True\n '
D = self.grs_decoder()
ygrs = self.bch_word_to_grs(y)
cgrs = D.decode_to_code(ygrs)
if ('list-decoder' in D.decoder_type()):
l = []
for c in cgrs:
try:
c_bch = self.grs_word_to_bch(c)
if (c_bch in self.code()):
l.append(c_bch)
except ValueError:
pass
return l
return self.grs_word_to_bch(cgrs)
def decoding_radius(self):
"\n Return maximal number of errors that ``self`` can decode.\n\n EXAMPLES::\n\n sage: C = codes.BCHCode(GF(4, 'a'), 15, 3, jump_size=2)\n sage: D = codes.decoders.BCHUnderlyingGRSDecoder(C)\n sage: D.decoding_radius()\n 1\n "
return self.grs_decoder().decoding_radius()
|
def random_error_vector(n, F, error_positions):
'\n Return a vector of length ``n`` over ``F`` filled with random non-zero coefficients\n at the positions given by ``error_positions``.\n\n .. NOTE::\n\n This is a helper function, which should only be used when implementing new channels.\n\n INPUT:\n\n - ``n`` -- the length of the vector\n\n - ``F`` -- the field over which the vector is defined\n\n - ``error_positions`` -- the non-zero positions of the vector\n\n OUTPUT:\n\n - a vector of ``F``\n\n AUTHORS:\n\n This function is taken from codinglib (https://bitbucket.org/jsrn/codinglib/)\n and was written by Johan Nielsen.\n\n EXAMPLES::\n\n sage: from sage.coding.channel import random_error_vector\n sage: random_error_vector(5, GF(2), [1,3])\n (0, 1, 0, 1, 0)\n '
vect = ([F.zero()] * n)
for i in error_positions:
vect[i] = F._random_nonzero_element()
return vector(F, vect)
|
def format_interval(t):
"\n Return a formatted string representation of ``t``.\n\n This method should be called by any representation function in Channel classes.\n\n .. NOTE::\n\n This is a helper function, which should only be used when implementing new channels.\n\n INPUT:\n\n - ``t`` -- a list or a tuple\n\n OUTPUT:\n\n - a string\n\n TESTS::\n\n sage: from sage.coding.channel import format_interval\n sage: t = (5, 5)\n sage: format_interval(t)\n '5'\n\n sage: t = (2, 10)\n sage: format_interval(t)\n 'between 2 and 10'\n\n "
return (str(t[0]) if (t[0] == t[1]) else ('between %s and %s' % (t[0], t[1])))
|
class Channel(SageObject):
'\n Abstract top-class for Channel objects.\n\n All channel objects must inherit from this class. To implement a channel subclass, one should\n do the following:\n\n - inherit from this class,\n\n - call the super constructor,\n\n - override :meth:`transmit_unsafe`.\n\n While not being mandatory, it might be useful to reimplement representation methods (``_repr_`` and\n ``_latex_``).\n\n This abstract class provides the following parameters:\n\n - ``input_space`` -- the space of the words to transmit\n\n - ``output_space`` -- the space of the transmitted words\n '
def __init__(self, input_space, output_space):
'\n Initializes parameters for a Channel object.\n\n This is a private method, which should be called by the constructor\n of every encoder, as it automatically initializes the mandatory\n parameters of a Channel object.\n\n INPUT:\n\n - ``input_space`` -- the space of the words to transmit\n\n - ``output_space`` -- the space of the transmitted words\n\n EXAMPLES:\n\n We first create a new Channel subclass::\n\n sage: from sage.coding.channel import Channel\n sage: class ChannelExample(Channel):\n ....: def __init__(self, input_space, output_space):\n ....: super().__init__(input_space, output_space)\n\n We now create a member of our newly made class::\n\n sage: input = VectorSpace(GF(7), 6)\n sage: output = VectorSpace(GF(7), 5)\n sage: Chan = ChannelExample(input, output)\n\n We can check its parameters::\n\n sage: Chan.input_space()\n Vector space of dimension 6 over Finite Field of size 7\n sage: Chan.output_space()\n Vector space of dimension 5 over Finite Field of size 7\n '
self._input_space = input_space
self._output_space = output_space
def transmit(self, message):
'\n Return ``message``, modified accordingly with the algorithm of the channel it was\n transmitted through.\n\n Checks if ``message`` belongs to the input space, and returns an exception if not.\n Note that ``message`` itself is never modified by the channel.\n\n INPUT:\n\n - ``message`` -- a vector\n\n OUTPUT:\n\n - a vector of the output space of ``self``\n\n EXAMPLES::\n\n sage: F = GF(59)^6\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(F, n_err)\n sage: msg = F((4, 8, 15, 16, 23, 42))\n sage: set_random_seed(10)\n sage: Chan.transmit(msg)\n (4, 8, 4, 16, 23, 53)\n\n We can check that the input ``msg`` is not modified::\n\n sage: msg\n (4, 8, 15, 16, 23, 42)\n\n If we transmit a vector which is not in the input space of ``self``::\n\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^6, n_err)\n sage: msg = (4, 8, 15, 16, 23, 42)\n sage: Chan.transmit(msg)\n Traceback (most recent call last):\n ...\n TypeError: Message must be an element of the input space for the given channel\n\n .. NOTE::\n\n One can also call directly ``Chan(message)``, which does the same as ``Chan.transmit(message)``\n '
if (message in self.input_space()):
return self.transmit_unsafe(message)
else:
raise TypeError('Message must be an element of the input space for the given channel')
__call__ = transmit
def input_space(self):
'\n Return the input space of ``self``.\n\n EXAMPLES::\n\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^6, n_err)\n sage: Chan.input_space()\n Vector space of dimension 6 over Finite Field of size 59\n\n '
return self._input_space
def output_space(self):
'\n Return the output space of ``self``.\n\n EXAMPLES::\n\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^6, n_err)\n sage: Chan.output_space()\n Vector space of dimension 6 over Finite Field of size 59\n '
return self._output_space
@abstract_method
def transmit_unsafe(self, message):
'\n Return ``message``, modified accordingly with the algorithm of the channel it was\n transmitted through.\n\n This method does not check if ``message`` belongs to the input space of ``self``.\n\n This is an abstract method which should be reimplemented in all the subclasses of\n Channel.\n\n EXAMPLES::\n\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^6, n_err)\n sage: v = Chan.input_space().random_element()\n sage: Chan.transmit_unsafe(v) # random\n (1, 33, 46, 18, 20, 49)\n '
|
class StaticErrorRateChannel(Channel):
'\n Channel which adds a static number of errors to each message it transmits.\n\n The input space and the output space of this channel are the same.\n\n INPUT:\n\n - ``space`` -- the space of both input and output\n\n - ``number_errors`` -- the number of errors added to each transmitted message\n It can be either an integer of a tuple. If a tuple is passed as\n argument, the number of errors will be a random integer between the\n two bounds of the tuple.\n\n EXAMPLES:\n\n We construct a :class:`StaticErrorRateChannel` which adds 2 errors\n to any transmitted message::\n\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^40, n_err)\n sage: Chan\n Static error rate channel creating 2 errors, of input and output space\n Vector space of dimension 40 over Finite Field of size 59\n\n We can also pass a tuple for the number of errors::\n\n sage: n_err = (1, 10)\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^40, n_err)\n sage: Chan\n Static error rate channel creating between 1 and 10 errors,\n of input and output space Vector space of dimension 40 over Finite Field of size 59\n '
def __init__(self, space, number_errors):
'\n TESTS:\n\n If the number of errors exceeds the dimension of the input space,\n it will return an error::\n\n sage: n_err = 42\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^40, n_err)\n Traceback (most recent call last):\n ...\n ValueError: There might be more errors than the dimension of the input space\n '
if isinstance(number_errors, (Integer, int)):
number_errors = (number_errors, number_errors)
if (not isinstance(number_errors, (tuple, list))):
raise ValueError('number_errors must be a tuple, a list, an Integer or a Python int')
super().__init__(space, space)
if (number_errors[1] > space.dimension()):
raise ValueError('There might be more errors than the dimension of the input space')
self._number_errors = number_errors
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: n_err = 42\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^50, n_err)\n sage: Chan\n Static error rate channel creating 42 errors, of input and output space\n Vector space of dimension 50 over Finite Field of size 59\n '
no_err = self.number_errors()
return ('Static error rate channel creating %s errors, of input and output space %s' % (format_interval(no_err), self.input_space()))
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: n_err = 42\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^50, n_err)\n sage: latex(Chan)\n \\textnormal{Static error rate channel creating 42 errors, of\n input and output space Vector space of dimension 50 over Finite Field of size 59}\n '
no_err = self.number_errors()
return ('\\textnormal{Static error rate channel creating %s errors, of input and output space %s}' % (format_interval(no_err), self.input_space()))
def transmit_unsafe(self, message):
'\n Return ``message`` with as many errors as ``self._number_errors`` in it.\n\n If ``self._number_errors`` was passed as a tuple for the number of errors, it will\n pick a random integer between the bounds of the tuple and use it as the number of errors.\n\n This method does not check if ``message`` belongs to the input space of ``self``.\n\n INPUT:\n\n - ``message`` -- a vector\n\n OUTPUT:\n\n - a vector of the output space\n\n EXAMPLES::\n\n sage: F = GF(59)^6\n sage: n_err = 2\n sage: Chan = channels.StaticErrorRateChannel(F, n_err)\n sage: msg = F((4, 8, 15, 16, 23, 42))\n sage: set_random_seed(10)\n sage: Chan.transmit_unsafe(msg)\n (4, 8, 4, 16, 23, 53)\n\n This checks that :trac:`19863` is fixed::\n\n sage: V = VectorSpace(GF(2), 1000)\n sage: Chan = channels.StaticErrorRateChannel(V, 367)\n sage: c = V.random_element()\n sage: (c - Chan(c)).hamming_weight()\n 367\n '
w = copy(message)
number_errors = randint(*self.number_errors())
V = self.input_space()
R = V.base_ring()
for i in sample(range(V.dimension()), number_errors):
err = R.random_element()
while (w[i] == err):
err = R.random_element()
w[i] = err
return w
def number_errors(self):
'\n Return the number of errors created by ``self``.\n\n EXAMPLES::\n\n sage: n_err = 3\n sage: Chan = channels.StaticErrorRateChannel(GF(59)^6, n_err)\n sage: Chan.number_errors()\n (3, 3)\n '
return self._number_errors
|
class ErrorErasureChannel(Channel):
'\n Channel which adds errors and erases several positions in any message it transmits.\n\n The output space of this channel is a Cartesian product between its input\n space and a VectorSpace of the same dimension over `\\GF{2}`.\n\n INPUT:\n\n - ``space`` -- the input and output space\n\n - ``number_errors`` -- the number of errors created in each transmitted\n message. It can be either an integer of a tuple. If a tuple is passed as\n an argument, the number of errors will be a random integer between the\n two bounds of this tuple.\n\n - ``number_erasures`` -- the number of erasures created in each transmitted\n message. It can be either an integer of a tuple. If a tuple is passed as an\n argument, the number of erasures will be a random integer between the\n two bounds of this tuple.\n\n EXAMPLES:\n\n We construct a ErrorErasureChannel which adds 2 errors\n and 2 erasures to any transmitted message::\n\n sage: n_err, n_era = 2, 2\n sage: Chan = channels.ErrorErasureChannel(GF(59)^40, n_err, n_era)\n sage: Chan\n Error-and-erasure channel creating 2 errors and 2 erasures\n of input space Vector space of dimension 40 over Finite Field of size 59\n and output space The Cartesian product of (Vector space of dimension 40\n over Finite Field of size 59, Vector space of dimension 40 over Finite Field of size 2)\n\n We can also pass the number of errors and erasures as a couple of integers::\n\n sage: n_err, n_era = (1, 10), (1, 10)\n sage: Chan = channels.ErrorErasureChannel(GF(59)^40, n_err, n_era)\n sage: Chan\n Error-and-erasure channel creating between 1 and 10 errors and\n between 1 and 10 erasures of input space Vector space of dimension 40\n over Finite Field of size 59 and output space The Cartesian product of\n (Vector space of dimension 40 over Finite Field of size 59,\n Vector space of dimension 40 over Finite Field of size 2)\n '
def __init__(self, space, number_errors, number_erasures):
'\n\n\n TESTS:\n\n If the sum of number of errors and number of erasures\n exceeds (or may exceed, in the case of tuples) the dimension of the input space,\n it will return an error::\n\n sage: n_err, n_era = 21, 21\n sage: Chan = channels.ErrorErasureChannel(GF(59)^40, n_err, n_era)\n Traceback (most recent call last):\n ...\n ValueError: The total number of errors and erasures cannot exceed the dimension of the input space\n '
if isinstance(number_errors, (Integer, int)):
number_errors = (number_errors, number_errors)
if (not isinstance(number_errors, (tuple, list))):
raise ValueError('number_errors must be a tuple, a list, an Integer or a Python int')
if isinstance(number_erasures, (Integer, int)):
number_erasures = (number_erasures, number_erasures)
if (not isinstance(number_erasures, (tuple, list))):
raise ValueError('number_erasures must be a tuple, a list, an Integer or a Python int')
output_space = cartesian_product([space, VectorSpace(GF(2), space.dimension())])
super().__init__(space, output_space)
if ((number_errors[1] + number_erasures[1]) > space.dimension()):
raise ValueError('The total number of errors and erasures cannot exceed the dimension of the input space')
self._number_errors = number_errors
self._number_erasures = number_erasures
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: n_err, n_era = 21, 21\n sage: Chan = channels.ErrorErasureChannel(GF(59)^50, n_err, n_era)\n sage: Chan\n Error-and-erasure channel creating 21 errors and 21 erasures\n of input space Vector space of dimension 50 over Finite Field of size 59\n and output space The Cartesian product of (Vector space of dimension 50\n over Finite Field of size 59, Vector space of dimension 50 over Finite Field of size 2)\n '
no_err = self.number_errors()
no_era = self.number_erasures()
return ('Error-and-erasure channel creating %s errors and %s erasures of input space %s and output space %s' % (format_interval(no_err), format_interval(no_era), self.input_space(), self.output_space()))
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: n_err, n_era = 21, 21\n sage: Chan = channels.ErrorErasureChannel(GF(59)^50, n_err, n_era)\n sage: latex(Chan)\n \\textnormal{Error-and-erasure channel creating 21 errors and 21 erasures\n of input space Vector space of dimension 50 over Finite Field of size 59\n and output space The Cartesian product of (Vector space of dimension 50\n over Finite Field of size 59, Vector space of dimension 50 over Finite Field of size 2)}\n '
no_err = self.number_errors()
no_era = self.number_erasures()
return ('\\textnormal{Error-and-erasure channel creating %s errors and %s erasures of input space %s and output space %s}' % (format_interval(no_err), format_interval(no_era), self.input_space(), self.output_space()))
def transmit_unsafe(self, message):
'\n Return ``message`` with as many errors as ``self._number_errors`` in it,\n and as many erasures as ``self._number_erasures`` in it.\n\n If ``self._number_errors`` was passed as a tuple for the number of errors, it will\n pick a random integer between the bounds of the tuple and use it as the number of errors.\n It does the same with ``self._number_erasures``.\n\n All erased positions are set to 0 in the transmitted message.\n It is guaranteed that the erasures and the errors will never overlap:\n the received message will always contains exactly as many errors and erasures\n as expected.\n\n This method does not check if ``message`` belongs to the input space of ``self``.\n\n INPUT:\n\n - ``message`` -- a vector\n\n OUTPUT:\n\n - a couple of vectors, namely:\n\n - the transmitted message, which is ``message`` with erroneous and\n erased positions\n - the erasure vector, which contains ``1`` at the erased positions of\n the transmitted message and ``0`` elsewhere.\n\n EXAMPLES::\n\n sage: F = GF(59)^11\n sage: n_err, n_era = 2, 2\n sage: Chan = channels.ErrorErasureChannel(F, n_err, n_era)\n sage: msg = F((3, 14, 15, 9, 26, 53, 58, 9, 7, 9, 3))\n sage: set_random_seed(10)\n sage: Chan.transmit_unsafe(msg)\n ((31, 0, 15, 9, 38, 53, 58, 9, 0, 9, 3), (0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0))\n '
number_errors = randint(*self.number_errors())
number_erasures = randint(*self.number_erasures())
V = self.input_space()
n = V.dimension()
zero = V.base_ring().zero()
errors = sample(range(n), (number_errors + number_erasures))
error_positions = errors[:number_errors]
erasure_positions = errors[number_errors:]
error_vector = random_error_vector(n, V.base_ring(), error_positions)
erasure_vector = random_error_vector(n, GF(2), erasure_positions)
message = (message + error_vector)
for i in erasure_positions:
message[i] = zero
return (message, erasure_vector)
def number_errors(self):
'\n Return the number of errors created by ``self``.\n\n EXAMPLES::\n\n sage: n_err, n_era = 3, 0\n sage: Chan = channels.ErrorErasureChannel(GF(59)^6, n_err, n_era)\n sage: Chan.number_errors()\n (3, 3)\n '
return self._number_errors
def number_erasures(self):
'\n Return the number of erasures created by ``self``.\n\n EXAMPLES::\n\n sage: n_err, n_era = 0, 3\n sage: Chan = channels.ErrorErasureChannel(GF(59)^6, n_err, n_era)\n sage: Chan.number_erasures()\n (3, 3)\n '
return self._number_erasures
|
class QarySymmetricChannel(Channel):
'\n The `q`-ary symmetric, memoryless communication channel.\n\n Given an alphabet `\\Sigma` with `|\\Sigma| = q` and an error probability\n `\\epsilon`, a `q`-ary symmetric channel sends an element of `\\Sigma` into the\n same element with probability `1 - \\epsilon`, and any one of the other `q -\n 1` elements with probability `\\frac{\\epsilon}{q - 1}`. This implementation\n operates over vectors in `\\Sigma^n`, and "transmits" each element of the\n vector independently in the above manner.\n\n Though `\\Sigma` is usually taken to be a finite field, this implementation\n allows any structure for which Sage can represent `\\Sigma^n` and for which\n `\\Sigma` has a ``random_element()`` method. However, beware that if `\\Sigma`\n is infinite, errors will not be uniformly distributed (since\n ``random_element()`` does not draw uniformly at random).\n\n The input space and the output space of this channel are the same:\n `\\Sigma^n`.\n\n INPUT:\n\n - ``space`` -- the input and output space of the channel. It has to be\n `\\GF{q}^n` for some finite field `\\GF{q}`.\n\n - ``epsilon`` -- the transmission error probability of the individual elements.\n\n EXAMPLES:\n\n We construct a :class:`QarySymmetricChannel` which corrupts 30% of all\n transmitted symbols::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: Chan\n q-ary symmetric channel with error probability 0.300000000000000,\n of input and output space\n Vector space of dimension 50 over Finite Field of size 59\n '
def __init__(self, space, epsilon):
'\n TESTS:\n\n If ``space`` is not a vector space, an error is raised::\n\n sage: epsilon = 0.42\n sage: Chan = channels.QarySymmetricChannel(GF(59), epsilon)\n Traceback (most recent call last):\n ...\n ValueError: space has to be of the form Sigma^n, where Sigma has a random_element() method\n\n If ``epsilon`` is not between 0 and 1, an error is raised::\n\n sage: epsilon = 42\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n Traceback (most recent call last):\n ...\n ValueError: Error probability must be between 0 and 1\n '
if ((epsilon >= 1) or (epsilon <= 0)):
raise ValueError('Error probability must be between 0 and 1')
super().__init__(space, space)
self._epsilon = epsilon
try:
self.transmit_unsafe(space.random_element())
except Exception:
raise ValueError('space has to be of the form Sigma^n, where Sigma has a random_element() method')
def __repr__(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: Chan\n q-ary symmetric channel with error probability 0.300000000000000,\n of input and output space Vector space of dimension 50 over Finite Field of size 59\n '
return ('q-ary symmetric channel with error probability %s, of input and output space %s' % (self.error_probability(), self.input_space()))
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: latex(Chan)\n \\textnormal{q-ary symmetric channel with error probability 0.300000000000000,\n of input and output space Vector space of dimension 50 over Finite Field of size 59}\n '
return ('\\textnormal{q-ary symmetric channel with error probability %s, of input and output space %s}' % (self.error_probability(), self.input_space()))
def transmit_unsafe(self, message):
'\n Return ``message`` where each of the symbols has been changed to another from the alphabet with\n probability :meth:`error_probability`.\n\n This method does not check if ``message`` belongs to the input space of ``self``.\n\n INPUT:\n\n - ``message`` -- a vector\n\n EXAMPLES::\n\n sage: F = GF(59)^11\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(F, epsilon)\n sage: msg = F((3, 14, 15, 9, 26, 53, 58, 9, 7, 9, 3))\n sage: set_random_seed(10)\n sage: Chan.transmit_unsafe(msg)\n (3, 14, 15, 53, 12, 53, 58, 9, 55, 9, 3)\n '
epsilon = self.error_probability()
V = self.input_space()
F = V.base_ring()
msg = copy(message.list())
for i in range(len(msg)):
if (random() <= epsilon):
a = F.random_element()
while (a == msg[i]):
a = F.random_element()
msg[i] = a
return V(msg)
def error_probability(self):
'\n Return the error probability of a single symbol transmission of\n ``self``.\n\n EXAMPLES::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: Chan.error_probability()\n 0.300000000000000\n '
return self._epsilon
def probability_of_exactly_t_errors(self, t):
'\n Return the probability ``self`` has to return\n exactly ``t`` errors.\n\n INPUT:\n\n - ``t`` -- an integer\n\n EXAMPLES::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: Chan.probability_of_exactly_t_errors(15)\n 0.122346861835401\n '
n = self.input_space().dimension()
epsilon = self.error_probability()
return ((binomial(n, t) * (epsilon ** t)) * ((1 - epsilon) ** (n - t)))
def probability_of_at_most_t_errors(self, t):
'\n Return the probability ``self`` has to return\n at most ``t`` errors.\n\n INPUT:\n\n - ``t`` -- an integer\n\n EXAMPLES::\n\n sage: epsilon = 0.3\n sage: Chan = channels.QarySymmetricChannel(GF(59)^50, epsilon)\n sage: Chan.probability_of_at_most_t_errors(20)\n 0.952236164579467\n '
return sum((self.probability_of_exactly_t_errors(i) for i in range((t + 1))))
|
def _check_n_q_d(n, q, d, field_based=True):
'\n Check that the length `n`, alphabet size `q` and minimum distance `d` type\n check and make sense for a code over a field.\n\n More precisely, this checks that the parameters are positive\n integers, that `q` is a prime power for codes over a field, or,\n more generally, that `q` is of size at least 2, and that `n >= d`.\n This raises a :class:`ValueError` otherwise.\n\n TESTS::\n\n sage: from sage.coding.code_bounds import _check_n_q_d\n sage: _check_n_q_d(20, 16, 5)\n True\n sage: _check_n_q_d(20, 16, 6, field_based=False)\n True\n sage: _check_n_q_d(20, 21, 16)\n Traceback (most recent call last):\n ...\n ValueError: The alphabet size does not make sense for a code over a field\n sage: _check_n_q_d(20, -21, 16)\n Traceback (most recent call last):\n ...\n ValueError: The alphabet size must be an integer >1\n sage: _check_n_q_d(20, 2, 26)\n Traceback (most recent call last):\n ...\n ValueError: The length or minimum distance does not make sense\n '
if ((q not in ZZ) or (q < 2)):
raise ValueError('The alphabet size must be an integer >1')
if (field_based and (not is_prime_power(q))):
raise ValueError('The alphabet size does not make sense for a code over a field')
if (not ((0 < d <= n) and (n in ZZ) and (d in ZZ))):
raise ValueError('The length or minimum distance does not make sense')
return True
|
def codesize_upper_bound(n, d, q, algorithm=None):
'\n Return an upper bound on the number of codewords in a (possibly non-linear)\n code.\n\n This function computes the minimum value of the upper bounds of Singleton,\n Hamming, Plotkin, and Elias.\n\n If ``algorithm="gap"``, then this returns the best known upper\n bound `A(n,d)=A_q(n,d)` for the size of a code of length `n`,\n minimum distance `d` over a field of size `q`. The function first\n checks for trivial cases (like `d=1` or `n=d`), and if the value\n is in the built-in table. Then it calculates the minimum value\n of the upper bound using the algorithms of Singleton, Hamming,\n Johnson, Plotkin and Elias. If the code is binary,\n `A(n, 2\\ell-1) = A(n+1,2\\ell)`, so the function\n takes the minimum of the values obtained from all algorithms for the\n parameters `(n, 2\\ell-1)` and `(n+1, 2\\ell)`. This\n wraps GUAVA\'s (i.e. GAP\'s package Guava) ``UpperBound(n, d, q)``.\n\n If ``algorithm="LP"``, then this returns the Delsarte (a.k.a. Linear\n Programming) upper bound.\n\n EXAMPLES::\n\n sage: codes.bounds.codesize_upper_bound(10,3,2)\n 93\n sage: codes.bounds.codesize_upper_bound(24,8,2,algorithm="LP")\n 4096\n sage: codes.bounds.codesize_upper_bound(10,3,2,algorithm="gap") # optional - gap_package_guava\n 85\n sage: codes.bounds.codesize_upper_bound(11,3,4,algorithm=None)\n 123361\n sage: codes.bounds.codesize_upper_bound(11,3,4,algorithm="gap") # optional - gap_package_guava\n 123361\n sage: codes.bounds.codesize_upper_bound(11,3,4,algorithm="LP")\n 109226\n\n TESTS:\n\n Make sure :trac:`22961` is fixed::\n\n sage: codes.bounds.codesize_upper_bound(19,10,2)\n 20\n sage: codes.bounds.codesize_upper_bound(19,10,2,algorithm="gap") # optional - gap_package_guava\n 20\n\n Meaningless parameters are rejected::\n\n sage: codes.bounds.codesize_upper_bound(10, -20, 6)\n Traceback (most recent call last):\n ...\n ValueError: The length or minimum distance does not make sense\n '
_check_n_q_d(n, q, d, field_based=False)
if (algorithm == 'gap'):
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
return int(libgap.UpperBound(n, d, q))
if (algorithm == 'LP'):
return int(delsarte_bound_hamming_space(n, d, q))
else:
eub = elias_upper_bound(n, q, d)
hub = hamming_upper_bound(n, q, d)
pub = plotkin_upper_bound(n, q, d)
sub = singleton_upper_bound(n, q, d)
return min([eub, hub, pub, sub])
|
def dimension_upper_bound(n, d, q, algorithm=None):
'\n Return an upper bound for the dimension of a linear code.\n\n Return an upper bound `B(n,d) = B_q(n,d)` for the\n dimension of a linear code of length `n`, minimum distance `d` over a\n field of size `q`.\n\n Parameter ``algorithm`` has the same meaning as in\n :func:`codesize_upper_bound`\n\n EXAMPLES::\n\n sage: codes.bounds.dimension_upper_bound(10,3,2)\n 6\n sage: codes.bounds.dimension_upper_bound(30,15,4)\n 13\n sage: codes.bounds.dimension_upper_bound(30,15,4,algorithm="LP")\n 12\n\n TESTS:\n\n Meaningless code parameters are rejected::\n\n sage: codes.bounds.dimension_upper_bound(13,3,6)\n Traceback (most recent call last):\n ...\n ValueError: The alphabet size does not make sense for a code over a field\n '
_check_n_q_d(n, q, d)
q = ZZ(q)
if (algorithm == 'LP'):
return delsarte_bound_additive_hamming_space(n, d, q)
return int(ZZ(codesize_upper_bound(n, d, q, algorithm=algorithm)).log(q))
|
def volume_hamming(n, q, r):
'\n Return the number of elements in a Hamming ball.\n\n Return the number of elements in a Hamming ball of radius `r` in\n `\\GF{q}^n`.\n\n EXAMPLES::\n\n sage: codes.bounds.volume_hamming(10,2,3)\n 176\n '
return sum([(binomial(n, i) * ((q - 1) ** i)) for i in range((r + 1))])
|
def gilbert_lower_bound(n, q, d):
'\n Return the Gilbert-Varshamov lower bound.\n\n Return the Gilbert-Varshamov lower bound for number of elements in a largest code of\n minimum distance d in `\\GF{q}^n`. See :wikipedia:`Gilbert-Varshamov_bound`\n\n EXAMPLES::\n\n sage: codes.bounds.gilbert_lower_bound(10,2,3)\n 128/7\n '
_check_n_q_d(n, q, d, field_based=False)
ans = ((q ** n) / volume_hamming(n, q, (d - 1)))
return ans
|
def plotkin_upper_bound(n, q, d, algorithm=None):
'\n Return the Plotkin upper bound.\n\n Return the Plotkin upper bound for the number of elements in a largest\n code of minimum distance `d` in `\\GF{q}^n`.\n More precisely this is a generalization of Plotkin\'s result for `q=2`\n to bigger `q` due to Berlekamp.\n\n The ``algorithm="gap"`` option wraps Guava\'s ``UpperBoundPlotkin``.\n\n EXAMPLES::\n\n sage: codes.bounds.plotkin_upper_bound(10,2,3)\n 192\n sage: codes.bounds.plotkin_upper_bound(10,2,3,algorithm="gap") # optional - gap_package_guava\n 192\n '
_check_n_q_d(n, q, d, field_based=False)
if (algorithm == 'gap'):
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
return QQ(libgap.UpperBoundPlotkin(n, d, q))
else:
t = (1 - (1 / q))
if ((q == 2) and (n == (2 * d)) and ((d % 2) == 0)):
return (4 * d)
elif ((q == 2) and (n == ((2 * d) + 1)) and ((d % 2) == 1)):
return ((4 * d) + 4)
elif (d > (t * n)):
return int((d / (d - (t * n))))
elif (d < ((t * n) + 1)):
fact = ((d - 1) / t)
from sage.rings.real_mpfr import RR
if (RR(fact) == RR(int(fact))):
fact = (int(fact) + 1)
return (int((d / (d - (t * fact)))) * (q ** (n - fact)))
|
def griesmer_upper_bound(n, q, d, algorithm=None):
'\n Return the Griesmer upper bound.\n\n Return the Griesmer upper bound for the number of elements in a\n largest linear code of minimum distance `d` in `\\GF{q}^n`, cf. [HP2003]_.\n If the method is "gap", it wraps GAP\'s ``UpperBoundGriesmer``.\n\n The bound states:\n\n .. MATH::\n\n `n\\geq \\sum_{i=0}^{k-1} \\lceil d/q^i \\rceil.`\n\n\n EXAMPLES:\n\n The bound is reached for the ternary Golay codes::\n\n sage: codes.bounds.griesmer_upper_bound(12,3,6)\n 729\n sage: codes.bounds.griesmer_upper_bound(11,3,5)\n 729\n\n ::\n\n sage: codes.bounds.griesmer_upper_bound(10,2,3)\n 128\n sage: codes.bounds.griesmer_upper_bound(10,2,3,algorithm="gap") # optional - gap_package_guava\n 128\n\n TESTS::\n\n sage: codes.bounds.griesmer_upper_bound(11,3,6)\n 243\n sage: codes.bounds.griesmer_upper_bound(11,3,6)\n 243\n '
_check_n_q_d(n, q, d)
if (algorithm == 'gap'):
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
return QQ(libgap.UpperBoundGriesmer(n, d, q))
else:
from sage.functions.other import ceil
den = 1
s = 0
k = 0
while (s <= n):
s += ceil((d / den))
den *= q
k = (k + 1)
return (q ** (k - 1))
|
def elias_upper_bound(n, q, d, algorithm=None):
'\n Return the Elias upper bound.\n\n Return the Elias upper bound for number of elements in the largest\n code of minimum distance `d` in `\\GF{q}^n`, cf. [HP2003]_.\n If ``algorithm="gap"``, it wraps GAP\'s ``UpperBoundElias``.\n\n EXAMPLES::\n\n sage: codes.bounds.elias_upper_bound(10,2,3)\n 232\n sage: codes.bounds.elias_upper_bound(10,2,3,algorithm="gap") # optional - gap_package_guava\n 232\n '
_check_n_q_d(n, q, d, field_based=False)
r = (1 - (1 / q))
if (algorithm == 'gap'):
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
return QQ(libgap.UpperBoundElias(n, d, q))
else:
def ff(n, d, w, q):
return ((((r * n) * d) * (q ** n)) / ((((w ** 2) - (((2 * r) * n) * w)) + ((r * n) * d)) * volume_hamming(n, q, w)))
def get_list(n, d, q):
I = []
for i in range(1, (int((r * n)) + 1)):
if ((((i ** 2) - (((2 * r) * n) * i)) + ((r * n) * d)) > 0):
I.append(i)
return I
I = get_list(n, d, q)
bnd = min([ff(n, d, w, q) for w in I])
return int(bnd)
|
def hamming_upper_bound(n, q, d):
'\n Return the Hamming upper bound.\n\n Return the Hamming upper bound for number of elements in the\n largest code of length `n` and minimum distance `d` over alphabet\n of size `q`.\n\n The Hamming bound (also known as the sphere packing bound) returns\n an upper bound on the size of a code of length `n`, minimum distance\n `d`, over an alphabet of size `q`. The Hamming bound is obtained by\n dividing the contents of the entire Hamming space\n `q^n` by the contents of a ball with radius\n `floor((d-1)/2)`. As all these balls are disjoint, they can never\n contain more than the whole vector space.\n\n\n .. MATH::\n\n M \\leq \\frac{q^n}{V(n,e)},\n\n\n\n where `M` is the maximum number of codewords and `V(n,e)` is\n equal to the contents of a ball of radius `e`. This bound is useful\n for small values of `d`. Codes for which equality holds are called\n perfect. See e.g. [HP2003]_.\n\n EXAMPLES::\n\n sage: codes.bounds.hamming_upper_bound(10,2,3)\n 93\n '
_check_n_q_d(n, q, d, field_based=False)
return int(((q ** n) / volume_hamming(n, q, int(((d - 1) / 2)))))
|
def singleton_upper_bound(n, q, d):
'\n Return the Singleton upper bound.\n\n Return the Singleton upper bound for number of elements in a\n largest code of minimum distance `d` in `\\GF{q}^n`.\n\n This bound is based on the shortening of codes. By shortening an\n `(n, M, d)` code `d-1` times, an `(n-d+1,M,1)` code\n results, with `M \\leq q^n-d+1`. Thus\n\n\n .. MATH::\n\n M \\leq q^{n-d+1}.\n\n\n Codes that meet this bound are called maximum distance separable\n (MDS).\n\n EXAMPLES::\n\n sage: codes.bounds.singleton_upper_bound(10,2,3)\n 256\n '
_check_n_q_d(n, q, d, field_based=False)
return (q ** ((n - d) + 1))
|
def gv_info_rate(n, delta, q):
'\n The Gilbert-Varshamov lower bound for information rate.\n\n The Gilbert-Varshamov lower bound for information rate of a `q`-ary code of\n length `n` and minimum distance `n\\delta`.\n\n EXAMPLES::\n\n sage: RDF(codes.bounds.gv_info_rate(100,1/4,3)) # abs tol 1e-15\n 0.36704992608261894\n '
q = ZZ(q)
return (log(gilbert_lower_bound(n, q, int((n * delta))), q) / n)
|
def entropy(x, q=2):
'\n Compute the entropy at `x` on the `q`-ary symmetric channel.\n\n INPUT:\n\n - ``x`` -- real number in the interval `[0, 1]`.\n\n - ``q`` -- (default: 2) integer greater than 1. This is the base of the\n logarithm.\n\n EXAMPLES::\n\n sage: codes.bounds.entropy(0, 2)\n 0\n sage: codes.bounds.entropy(1/5,4).factor() # optional - sage.symbolic\n 1/10*(log(3) - 4*log(4/5) - log(1/5))/log(2)\n sage: codes.bounds.entropy(1, 3) # optional - sage.symbolic\n log(2)/log(3)\n\n Check that values not within the limits are properly handled::\n\n sage: codes.bounds.entropy(1.1, 2)\n Traceback (most recent call last):\n ...\n ValueError: The entropy function is defined only for x in the interval [0, 1]\n sage: codes.bounds.entropy(1, 1)\n Traceback (most recent call last):\n ...\n ValueError: The value q must be an integer greater than 1\n '
if ((x < 0) or (x > 1)):
raise ValueError('The entropy function is defined only for x in the interval [0, 1]')
q = ZZ(q)
if (q < 2):
raise ValueError('The value q must be an integer greater than 1')
if (x == 0):
return 0
if (x == 1):
return log((q - 1), q)
H = (((x * log((q - 1), q)) - (x * log(x, q))) - ((1 - x) * log((1 - x), q)))
return H
|
def entropy_inverse(x, q=2):
'\n Find the inverse of the `q`-ary entropy function at the point ``x``.\n\n INPUT:\n\n - ``x`` -- real number in the interval `[0, 1]`.\n\n - ``q`` - (default: 2) integer greater than 1. This is the base of the\n logarithm.\n\n OUTPUT:\n\n Real number in the interval `[0, 1-1/q]`. The function has multiple\n values if we include the entire interval `[0, 1]`; hence only the\n values in the above interval is returned.\n\n EXAMPLES::\n\n sage: from sage.coding.code_bounds import entropy_inverse\n sage: entropy_inverse(0.1)\n 0.012986862055...\n sage: entropy_inverse(1)\n 1/2\n sage: entropy_inverse(0, 3)\n 0\n sage: entropy_inverse(1, 3)\n 2/3\n '
if ((x < 0) or (x > 1)):
raise ValueError('The inverse entropy function is defined only for x in the interval [0, 1]')
q = ZZ(q)
if (q < 2):
raise ValueError('The value q must be an integer greater than 1')
eps = 4.5e-16
ymax = (1 - (1 / q))
if (x <= eps):
return 0
if (x >= (1 - eps)):
return ymax
from sage.numerical.optimize import find_root
f = (lambda y: (entropy(y, q) - x))
return find_root(f, 0, ymax)
|
def gv_bound_asymp(delta, q):
'\n The asymptotic Gilbert-Varshamov bound for the information rate, R.\n\n EXAMPLES::\n\n sage: RDF(codes.bounds.gv_bound_asymp(1/4,2))\n 0.18872187554086...\n sage: f = lambda x: codes.bounds.gv_bound_asymp(x,2)\n sage: plot(f,0,1)\n Graphics object consisting of 1 graphics primitive\n '
return (1 - entropy(delta, q))
|
def hamming_bound_asymp(delta, q):
'\n The asymptotic Hamming bound for the information rate.\n\n EXAMPLES::\n\n sage: RDF(codes.bounds.hamming_bound_asymp(1/4,2))\n 0.456435556800...\n sage: f = lambda x: codes.bounds.hamming_bound_asymp(x,2)\n sage: plot(f,0,1)\n Graphics object consisting of 1 graphics primitive\n '
return (1 - entropy((delta / 2), q))
|
def singleton_bound_asymp(delta, q):
'\n The asymptotic Singleton bound for the information rate.\n\n EXAMPLES::\n\n sage: codes.bounds.singleton_bound_asymp(1/4,2)\n 3/4\n sage: f = lambda x: codes.bounds.singleton_bound_asymp(x,2)\n sage: plot(f,0,1)\n Graphics object consisting of 1 graphics primitive\n '
return (1 - delta)
|
def plotkin_bound_asymp(delta, q):
'\n The asymptotic Plotkin bound for the information rate.\n\n This only makes sense when `0 < \\delta < 1-1/q`.\n\n EXAMPLES::\n\n sage: codes.bounds.plotkin_bound_asymp(1/4,2)\n 1/2\n '
r = (1 - (1 / q))
return (1 - (delta / r))
|
def elias_bound_asymp(delta, q):
'\n The asymptotic Elias bound for the information rate.\n\n This only makes sense when `0 < \\delta < 1-1/q`.\n\n EXAMPLES::\n\n sage: codes.bounds.elias_bound_asymp(1/4,2)\n 0.39912396330...\n '
r = (1 - (1 / q))
return RDF((1 - entropy((r - sqrt((r * (r - delta)))), q)))
|
def mrrw1_bound_asymp(delta, q):
'\n The first asymptotic McEliese-Rumsey-Rodemich-Welsh bound.\n\n This only makes sense when `0 < \\delta < 1-1/q`.\n\n EXAMPLES::\n\n sage: codes.bounds.mrrw1_bound_asymp(1/4,2) # abs tol 4e-16\n 0.3545789026652697\n '
return RDF(entropy(((((q - 1) - (delta * (q - 2))) - (2 * sqrt((((q - 1) * delta) * (1 - delta))))) / q), q))
|
def _is_a_splitting(S1, S2, n, return_automorphism=False):
'\n Check whether ``(S1,S2)`` is a splitting of `\\ZZ/n\\ZZ`.\n\n A splitting of `R = \\ZZ/n\\ZZ` is a pair of subsets of `R` which is a\n partition of `R \\\\backslash \\{0\\}` and such that there exists an element `r`\n of `R` such that `r S_1 = S_2` and `r S_2 = S_1` (where `r S` is the\n point-wise multiplication of the elements of `S` by `r`).\n\n Splittings are useful for computing idempotents in the quotient\n ring `Q = GF(q)[x]/(x^n-1)`.\n\n INPUT:\n\n - ``S1, S2`` -- disjoint sublists partitioning ``[1, 2, ..., n-1]``\n\n - ``n`` (integer)\n\n - ``return_automorphism`` (boolean) -- whether to return the automorphism\n exchanging `S_1` and `S_2`.\n\n OUTPUT:\n\n If ``return_automorphism is False`` (default) the function returns boolean values.\n\n Otherwise, it returns a pair ``(b, r)`` where ``b`` is a boolean indicating\n whether `S1`, `S2` is a splitting of `n`, and `r` is such that `r S_1 = S_2`\n and `r S_2 = S_1` (if `b` is ``False``, `r` is equal to ``None``).\n\n EXAMPLES::\n\n sage: from sage.coding.code_constructions import _is_a_splitting\n sage: _is_a_splitting([1,2],[3,4],5)\n True\n sage: _is_a_splitting([1,2],[3,4],5,return_automorphism=True)\n (True, 4)\n\n sage: _is_a_splitting([1,3],[2,4,5,6],7)\n False\n sage: _is_a_splitting([1,3,4],[2,5,6],7)\n False\n\n sage: for P in SetPartitions(6,[3,3]):\n ....: res,aut= _is_a_splitting(P[0],P[1],7,return_automorphism=True)\n ....: if res:\n ....: print((aut, P))\n (3, {{1, 2, 4}, {3, 5, 6}})\n (6, {{1, 2, 3}, {4, 5, 6}})\n (6, {{1, 3, 5}, {2, 4, 6}})\n (6, {{1, 4, 5}, {2, 3, 6}})\n\n We illustrate now how to find idempotents in quotient rings::\n\n sage: n = 11; q = 3\n sage: C = Zmod(n).cyclotomic_cosets(q); C\n [[0], [1, 3, 4, 5, 9], [2, 6, 7, 8, 10]]\n sage: S1 = C[1]\n sage: S2 = C[2]\n sage: _is_a_splitting(S1,S2,11)\n True\n sage: F = GF(q)\n sage: P.<x> = PolynomialRing(F,"x")\n sage: I = Ideal(P,[x^n-1])\n sage: Q.<x> = QuotientRing(P,I)\n sage: i1 = -sum([x^i for i in S1]); i1\n 2*x^9 + 2*x^5 + 2*x^4 + 2*x^3 + 2*x\n sage: i2 = -sum([x^i for i in S2]); i2\n 2*x^10 + 2*x^8 + 2*x^7 + 2*x^6 + 2*x^2\n sage: i1^2 == i1\n True\n sage: i2^2 == i2\n True\n sage: (1-i1)^2 == 1-i1\n True\n sage: (1-i2)^2 == 1-i2\n True\n\n We return to dealing with polynomials (rather than elements of\n quotient rings), so we can construct cyclic codes::\n\n sage: P.<x> = PolynomialRing(F,"x")\n sage: i1 = -sum([x^i for i in S1])\n sage: i2 = -sum([x^i for i in S2])\n sage: i1_sqrd = (i1^2).quo_rem(x^n-1)[1]\n sage: i1_sqrd == i1\n True\n sage: i2_sqrd = (i2^2).quo_rem(x^n-1)[1]\n sage: i2_sqrd == i2\n True\n sage: C1 = codes.CyclicCode(length = n, generator_pol = gcd(i1, x^n - 1))\n sage: C2 = codes.CyclicCode(length = n, generator_pol = gcd(1-i2, x^n - 1))\n sage: C1.dual_code().systematic_generator_matrix() == C2.systematic_generator_matrix()\n True\n\n This is a special case of Theorem 6.4.3 in [HP2003]_.\n '
R = IntegerModRing(n)
S1 = {R(x) for x in S1}
S2 = {R(x) for x in S2}
if (((len(S1) + len(S2)) != (n - 1)) or (len(S1) != len(S2)) or (R.zero() in S1) or (R.zero() in S2) or (not S1.isdisjoint(S2))):
if return_automorphism:
return (False, None)
else:
return False
for b in Integer(n).coprime_integers(n):
if ((b >= 2) and all((((b * x) in S2) for x in S1))):
if return_automorphism:
return (True, b)
else:
return True
if return_automorphism:
return (False, None)
else:
return False
|
def _lift2smallest_field(a):
'\n INPUT: a is an element of a finite field GF(q)\n\n OUTPUT: the element b of the smallest subfield F of GF(q) for\n which F(b)=a.\n\n EXAMPLES::\n\n sage: from sage.coding.code_constructions import _lift2smallest_field\n sage: FF.<z> = GF(3^4,"z")\n sage: a = z^10\n sage: _lift2smallest_field(a)\n (2*z + 1, Finite Field in z of size 3^2)\n sage: a = z^40\n sage: _lift2smallest_field(a)\n (2, Finite Field of size 3)\n\n AUTHORS:\n\n - John Cremona\n '
FF = a.parent()
k = FF.degree()
if (k == 1):
return (a, FF)
pol = a.minimal_polynomial()
d = pol.degree()
if (d == k):
return (a, FF)
p = FF.characteristic()
F = GF((p, d), 'z')
b = pol.roots(F, multiplicities=False)[0]
return (b, F)
|
def permutation_action(g, v):
'\n Returns permutation of rows `g * v`.\n\n Works on lists, matrices,\n sequences and vectors (by permuting coordinates). The code requires\n switching from `i` to `i+1` (and back again) since the :class:`SymmetricGroup`\n is, by convention, the symmetric group on the "letters" `1`, `2`, ...,\n `n` (not `0`, `1`, ..., `n-1`).\n\n EXAMPLES::\n\n sage: V = VectorSpace(GF(3),5)\n sage: v = V([0,1,2,0,1])\n sage: G = SymmetricGroup(5) # optional - sage.groups\n sage: g = G([(1,2,3)]) # optional - sage.groups\n sage: permutation_action(g,v) # optional - sage.groups\n (1, 2, 0, 0, 1)\n sage: g = G([()]) # optional - sage.groups\n sage: permutation_action(g,v) # optional - sage.groups\n (0, 1, 2, 0, 1)\n sage: g = G([(1,2,3,4,5)]) # optional - sage.groups\n sage: permutation_action(g,v) # optional - sage.groups\n (1, 2, 0, 1, 0)\n sage: L = Sequence([1,2,3,4,5])\n sage: permutation_action(g,L) # optional - sage.groups\n [2, 3, 4, 5, 1]\n sage: MS = MatrixSpace(GF(3),3,7)\n sage: A = MS([[1,0,0,0,1,1,0],[0,1,0,1,0,1,0],[0,0,0,0,0,0,1]])\n sage: S5 = SymmetricGroup(5) # optional - sage.groups\n sage: g = S5([(1,2,3)]) # optional - sage.groups\n sage: A\n [1 0 0 0 1 1 0]\n [0 1 0 1 0 1 0]\n [0 0 0 0 0 0 1]\n sage: permutation_action(g,A) # optional - sage.groups\n [0 1 0 1 0 1 0]\n [0 0 0 0 0 0 1]\n [1 0 0 0 1 1 0]\n\n It also works on lists and is a "left action"::\n\n sage: v = [0,1,2,0,1]\n sage: G = SymmetricGroup(5) # optional - sage.groups\n sage: g = G([(1,2,3)]) # optional - sage.groups\n sage: gv = permutation_action(g,v); gv # optional - sage.groups\n [1, 2, 0, 0, 1]\n sage: permutation_action(g,v) == g(v) # optional - sage.groups\n True\n sage: h = G([(3,4)]) # optional - sage.groups\n sage: gv = permutation_action(g,v) # optional - sage.groups\n sage: hgv = permutation_action(h,gv) # optional - sage.groups\n sage: hgv == permutation_action(h*g,v) # optional - sage.groups\n True\n\n AUTHORS:\n\n - David Joyner, licensed under the GPL v2 or greater.\n '
v_type_list = False
if isinstance(v, list):
v_type_list = True
v = Sequence(v)
if isinstance(v, Sequence_generic):
V = v.universe()
else:
V = v.parent()
n = len(list(v))
gv = []
for i in range(n):
gv.append(v[(g((i + 1)) - 1)])
if v_type_list:
return gv
return V(gv)
|
def walsh_matrix(m0):
'\n This is the generator matrix of a Walsh code. The matrix of\n codewords correspond to a Hadamard matrix.\n\n EXAMPLES::\n\n sage: walsh_matrix(2)\n [0 0 1 1]\n [0 1 0 1]\n sage: walsh_matrix(3)\n [0 0 0 0 1 1 1 1]\n [0 0 1 1 0 0 1 1]\n [0 1 0 1 0 1 0 1]\n sage: C = LinearCode(walsh_matrix(4)); C\n [16, 4] linear code over GF(2)\n sage: C.spectrum()\n [1, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0]\n\n This last code has minimum distance 8.\n\n REFERENCES:\n\n - :wikipedia:`Hadamard_matrix`\n '
m = int(m0)
if (m == 1):
return matrix(GF(2), 1, 2, [0, 1])
if (m > 1):
row2 = [x.list() for x in walsh_matrix((m - 1)).augment(walsh_matrix((m - 1))).rows()]
return matrix(GF(2), m, (2 ** m), ([(([0] * (2 ** (m - 1))) + ([1] * (2 ** (m - 1))))] + row2))
raise ValueError(('%s must be an integer > 0.' % m0))
|
def DuadicCodeEvenPair(F, S1, S2):
'\n Constructs the "even pair" of duadic codes associated to the\n "splitting" (see the docstring for ``_is_a_splitting``\n for the definition) S1, S2 of n.\n\n .. warning::\n\n Maybe the splitting should be associated to a sum of\n q-cyclotomic cosets mod n, where q is a *prime*.\n\n EXAMPLES::\n\n sage: from sage.coding.code_constructions import _is_a_splitting\n sage: n = 11; q = 3\n sage: C = Zmod(n).cyclotomic_cosets(q); C\n [[0], [1, 3, 4, 5, 9], [2, 6, 7, 8, 10]]\n sage: S1 = C[1]\n sage: S2 = C[2]\n sage: _is_a_splitting(S1,S2,11)\n True\n sage: codes.DuadicCodeEvenPair(GF(q),S1,S2)\n ([11, 5] Cyclic Code over GF(3),\n [11, 5] Cyclic Code over GF(3))\n '
from sage.misc.stopgap import stopgap
stopgap('The function DuadicCodeEvenPair has several issues which may cause wrong results', 25896)
from .cyclic_code import CyclicCode
n = ((len(S1) + len(S2)) + 1)
if (not _is_a_splitting(S1, S2, n)):
raise TypeError(('%s, %s must be a splitting of %s.' % (S1, S2, n)))
q = F.order()
k = Mod(q, n).multiplicative_order()
FF = GF((q ** k), 'z')
z = FF.gen()
zeta = (z ** (((q ** k) - 1) / n))
P1 = PolynomialRing(FF, 'x')
x = P1.gen()
g1 = prod([(x - (zeta ** i)) for i in (S1 + [0])])
g2 = prod([(x - (zeta ** i)) for i in (S2 + [0])])
P2 = PolynomialRing(F, 'x')
x = P2.gen()
gg1 = P2([_lift2smallest_field(c)[0] for c in g1.coefficients(sparse=False)])
gg2 = P2([_lift2smallest_field(c)[0] for c in g2.coefficients(sparse=False)])
C1 = CyclicCode(length=n, generator_pol=gg1)
C2 = CyclicCode(length=n, generator_pol=gg2)
return (C1, C2)
|
def DuadicCodeOddPair(F, S1, S2):
'\n Constructs the "odd pair" of duadic codes associated to the\n "splitting" S1, S2 of n.\n\n .. warning::\n\n Maybe the splitting should be associated to a sum of\n q-cyclotomic cosets mod n, where q is a *prime*.\n\n EXAMPLES::\n\n sage: from sage.coding.code_constructions import _is_a_splitting\n sage: n = 11; q = 3\n sage: C = Zmod(n).cyclotomic_cosets(q); C\n [[0], [1, 3, 4, 5, 9], [2, 6, 7, 8, 10]]\n sage: S1 = C[1]\n sage: S2 = C[2]\n sage: _is_a_splitting(S1,S2,11)\n True\n sage: codes.DuadicCodeOddPair(GF(q),S1,S2)\n ([11, 6] Cyclic Code over GF(3),\n [11, 6] Cyclic Code over GF(3))\n\n This is consistent with Theorem 6.1.3 in [HP2003]_.\n '
from sage.misc.stopgap import stopgap
stopgap('The function DuadicCodeOddPair has several issues which may cause wrong results', 25896)
from .cyclic_code import CyclicCode
n = ((len(S1) + len(S2)) + 1)
if (not _is_a_splitting(S1, S2, n)):
raise TypeError(('%s, %s must be a splitting of %s.' % (S1, S2, n)))
q = F.order()
k = Mod(q, n).multiplicative_order()
FF = GF((q ** k), 'z')
z = FF.gen()
zeta = (z ** (((q ** k) - 1) / n))
P1 = PolynomialRing(FF, 'x')
x = P1.gen()
g1 = prod([(x - (zeta ** i)) for i in (S1 + [0])])
g2 = prod([(x - (zeta ** i)) for i in (S2 + [0])])
j = sum([((x ** i) / n) for i in range(n)])
P2 = PolynomialRing(F, 'x')
x = P2.gen()
coeffs1 = [_lift2smallest_field(c)[0] for c in (g1 + j).coefficients(sparse=False)]
coeffs2 = [_lift2smallest_field(c)[0] for c in (g2 + j).coefficients(sparse=False)]
gg1 = P2(coeffs1)
gg2 = P2(coeffs2)
gg1 = gcd(gg1, ((x ** n) - 1))
gg2 = gcd(gg2, ((x ** n) - 1))
C1 = CyclicCode(length=n, generator_pol=gg1)
C2 = CyclicCode(length=n, generator_pol=gg2)
return (C1, C2)
|
def ExtendedQuadraticResidueCode(n, F):
'\n The extended quadratic residue code (or XQR code) is obtained from\n a QR code by adding a check bit to the last coordinate. (These\n codes have very remarkable properties such as large automorphism\n groups and duality properties - see [HP2003]_, Section 6.6.3-6.6.4.)\n\n INPUT:\n\n\n - ``n`` -- an odd prime\n\n - ``F`` -- a finite prime field whose order must be a\n quadratic residue modulo `n`.\n\n\n OUTPUT: Returns an extended quadratic residue code.\n\n EXAMPLES::\n\n sage: C1 = codes.QuadraticResidueCode(7, GF(2))\n sage: C2 = C1.extended_code()\n sage: C3 = codes.ExtendedQuadraticResidueCode(7, GF(2)); C3\n Extension of [7, 4] Cyclic Code over GF(2)\n sage: C2 == C3\n True\n sage: C = codes.ExtendedQuadraticResidueCode(17, GF(2))\n sage: C\n Extension of [17, 9] Cyclic Code over GF(2)\n sage: C3 = codes.QuadraticResidueCodeOddPair(7, GF(2))[0]\n sage: C3x = C3.extended_code()\n sage: C4 = codes.ExtendedQuadraticResidueCode(7, GF(2))\n sage: C3x == C4\n True\n\n AUTHORS:\n\n - David Joyner (07-2006)\n '
C = QuadraticResidueCodeOddPair(n, F)[0]
return C.extended_code()
|
def from_parity_check_matrix(H):
'\n Return the linear code that has ``H`` as a parity check matrix.\n\n If ``H`` has dimensions `h \\times n` then the linear code will have\n dimension `n-h` and length `n`.\n\n EXAMPLES::\n\n sage: C = codes.HammingCode(GF(2), 3); C\n [7, 4] Hamming Code over GF(2)\n sage: H = C.parity_check_matrix(); H\n [1 0 1 0 1 0 1]\n [0 1 1 0 0 1 1]\n [0 0 0 1 1 1 1]\n sage: C2 = codes.from_parity_check_matrix(H); C2\n [7, 4] linear code over GF(2)\n sage: C2.systematic_generator_matrix() == C.systematic_generator_matrix()\n True\n '
Cd = LinearCode(H)
return Cd.dual_code()
|
def QuadraticResidueCode(n, F):
"\n A quadratic residue code (or QR code) is a cyclic code whose\n generator polynomial is the product of the polynomials\n `x-\\alpha^i` (`\\alpha` is a primitive\n `n`'th root of unity; `i` ranges over the set of\n quadratic residues modulo `n`).\n\n See :class:`QuadraticResidueCodeEvenPair` and\n :class:`QuadraticResidueCodeOddPair` for a more general construction.\n\n INPUT:\n\n\n - ``n`` -- an odd prime\n\n - ``F`` -- a finite prime field whose order must be a\n quadratic residue modulo `n`.\n\n\n OUTPUT: Returns a quadratic residue code.\n\n EXAMPLES::\n\n sage: C = codes.QuadraticResidueCode(7, GF(2))\n sage: C\n [7, 4] Cyclic Code over GF(2)\n sage: C = codes.QuadraticResidueCode(17, GF(2))\n sage: C\n [17, 9] Cyclic Code over GF(2)\n sage: C1 = codes.QuadraticResidueCodeOddPair(7, GF(2))[0]\n sage: C2 = codes.QuadraticResidueCode(7, GF(2))\n sage: C1 == C2\n True\n sage: C1 = codes.QuadraticResidueCodeOddPair(17, GF(2))[0]\n sage: C2 = codes.QuadraticResidueCode(17, GF(2))\n sage: C1 == C2\n True\n\n AUTHORS:\n\n - David Joyner (11-2005)\n "
return QuadraticResidueCodeOddPair(n, F)[0]
|
def QuadraticResidueCodeEvenPair(n, F):
'\n Quadratic residue codes of a given odd prime length and base ring\n either don\'t exist at all or occur as 4-tuples - a pair of\n "odd-like" codes and a pair of "even-like" codes. If `n > 2` is prime\n then (Theorem 6.6.2 in [HP2003]_) a QR code exists over `\\GF{q}` iff q is a\n quadratic residue mod `n`.\n\n They are constructed as "even-like" duadic codes associated the\n splitting `(Q,N)` mod `n`, where `Q` is the set of non-zero quadratic\n residues and `N` is the non-residues.\n\n EXAMPLES::\n\n sage: codes.QuadraticResidueCodeEvenPair(17, GF(13)) # known bug (#25896)\n ([17, 8] Cyclic Code over GF(13),\n [17, 8] Cyclic Code over GF(13))\n sage: codes.QuadraticResidueCodeEvenPair(17, GF(2))\n ([17, 8] Cyclic Code over GF(2),\n [17, 8] Cyclic Code over GF(2))\n sage: codes.QuadraticResidueCodeEvenPair(13, GF(9,"z")) # known bug (#25896)\n ([13, 6] Cyclic Code over GF(9),\n [13, 6] Cyclic Code over GF(9))\n sage: C1,C2 = codes.QuadraticResidueCodeEvenPair(7, GF(2))\n sage: C1.is_self_orthogonal()\n True\n sage: C2.is_self_orthogonal()\n True\n sage: C3 = codes.QuadraticResidueCodeOddPair(17, GF(2))[0]\n sage: C4 = codes.QuadraticResidueCodeEvenPair(17, GF(2))[1]\n sage: C3.systematic_generator_matrix() == C4.dual_code().systematic_generator_matrix()\n True\n\n This is consistent with Theorem 6.6.9 and Exercise 365 in [HP2003]_.\n\n TESTS::\n\n sage: codes.QuadraticResidueCodeEvenPair(14,Zmod(4))\n Traceback (most recent call last):\n ...\n ValueError: the argument F must be a finite field\n sage: codes.QuadraticResidueCodeEvenPair(14, GF(2))\n Traceback (most recent call last):\n ...\n ValueError: the argument n must be an odd prime\n sage: codes.QuadraticResidueCodeEvenPair(5, GF(2))\n Traceback (most recent call last):\n ...\n ValueError: the order of the finite field must be a quadratic residue modulo n\n '
from sage.arith.srange import srange
from sage.categories.finite_fields import FiniteFields
if (F not in FiniteFields()):
raise ValueError('the argument F must be a finite field')
q = F.order()
n = Integer(n)
if ((n <= 2) or (not n.is_prime())):
raise ValueError('the argument n must be an odd prime')
Q = quadratic_residues(n)
Q.remove(0)
N = [x for x in srange(1, n) if (x not in Q)]
if (q not in Q):
raise ValueError('the order of the finite field must be a quadratic residue modulo n')
return DuadicCodeEvenPair(F, Q, N)
|
def QuadraticResidueCodeOddPair(n, F):
'\n Quadratic residue codes of a given odd prime length and base ring\n either don\'t exist at all or occur as 4-tuples - a pair of\n "odd-like" codes and a pair of "even-like" codes. If n 2 is prime\n then (Theorem 6.6.2 in [HP2003]_) a QR code exists over `\\GF{q} iff `q` is a\n quadratic residue mod `n`.\n\n They are constructed as "odd-like" duadic codes associated the\n splitting `(Q,N)` mod `n`, where `Q` is the set of non-zero quadratic\n residues and `N` is the non-residues.\n\n EXAMPLES::\n\n sage: codes.QuadraticResidueCodeOddPair(17, GF(13)) # known bug (#25896)\n ([17, 9] Cyclic Code over GF(13),\n [17, 9] Cyclic Code over GF(13))\n sage: codes.QuadraticResidueCodeOddPair(17, GF(2))\n ([17, 9] Cyclic Code over GF(2),\n [17, 9] Cyclic Code over GF(2))\n sage: codes.QuadraticResidueCodeOddPair(13, GF(9,"z")) # known bug (#25896)\n ([13, 7] Cyclic Code over GF(9),\n [13, 7] Cyclic Code over GF(9))\n sage: C1 = codes.QuadraticResidueCodeOddPair(17, GF(2))[1]\n sage: C1x = C1.extended_code()\n sage: C2 = codes.QuadraticResidueCodeOddPair(17, GF(2))[0]\n sage: C2x = C2.extended_code()\n sage: C2x.spectrum(); C1x.spectrum()\n [1, 0, 0, 0, 0, 0, 102, 0, 153, 0, 153, 0, 102, 0, 0, 0, 0, 0, 1]\n [1, 0, 0, 0, 0, 0, 102, 0, 153, 0, 153, 0, 102, 0, 0, 0, 0, 0, 1]\n sage: C3 = codes.QuadraticResidueCodeOddPair(7, GF(2))[0]\n sage: C3x = C3.extended_code()\n sage: C3x.spectrum()\n [1, 0, 0, 0, 14, 0, 0, 0, 1]\n\n This is consistent with Theorem 6.6.14 in [HP2003]_.\n\n TESTS::\n\n sage: codes.QuadraticResidueCodeOddPair(9, GF(2))\n Traceback (most recent call last):\n ...\n ValueError: the argument n must be an odd prime\n '
from sage.arith.srange import srange
from sage.categories.finite_fields import FiniteFields
if (F not in FiniteFields()):
raise ValueError('the argument F must be a finite field')
q = F.order()
n = Integer(n)
if ((n <= 2) or (not n.is_prime())):
raise ValueError('the argument n must be an odd prime')
Q = quadratic_residues(n)
Q.remove(0)
N = [x for x in srange(1, n) if (x not in Q)]
if (q not in Q):
raise ValueError('the order of the finite field must be a quadratic residue modulo n')
return DuadicCodeOddPair(F, Q, N)
|
def random_linear_code(F, length, dimension):
'\n Generate a random linear code of length ``length``, dimension ``dimension``\n and over the field ``F``.\n\n This function is Las Vegas probabilistic: always correct, usually fast.\n Random matrices over the ``F`` are drawn until one with full rank is hit.\n\n If ``F`` is infinite, the distribution of the elements in the random\n generator matrix will be random according to the distribution of\n ``F.random_element()``.\n\n EXAMPLES::\n\n sage: C = codes.random_linear_code(GF(2), 10, 3)\n sage: C\n [10, 3] linear code over GF(2)\n sage: C.generator_matrix().rank()\n 3\n '
while True:
G = random_matrix(F, dimension, length)
if (G.rank() == dimension):
return LinearCode(G)
|
def ToricCode(P, F):
'\n Let `P` denote a list of lattice points in\n `\\ZZ^d` and let `T` denote the set of all\n points in `(F^x)^d` (ordered in some fixed way). Put\n `n=|T|` and let `k` denote the dimension of the\n vector space of functions `V = \\mathrm{Span}\\{x^e \\ |\\ e \\in P\\}`.\n The associated toric code `C` is the evaluation code which\n is the image of the evaluation map\n\n .. MATH::\n\n \\operatorname{eval}_T : V \\rightarrow F^n,\n\n\n where `x^e` is the multi-index notation\n (`x=(x_1,...,x_d)`, `e=(e_1,...,e_d)`, and\n `x^e = x_1^{e_1}...x_d^{e_d}`), where\n `\\operatorname{eval}_T (f(x)) = (f(t_1),...,f(t_n))`, and where\n `T=\\{t_1,...,t_n\\}`. This function returns the toric\n codes discussed in [Joy2004]_.\n\n INPUT:\n\n\n - ``P`` -- all the integer lattice points in a polytope\n defining the toric variety.\n\n - ``F`` -- a finite field.\n\n\n OUTPUT: Returns toric code with length n = , dimension k over field\n F.\n\n EXAMPLES::\n\n sage: C = codes.ToricCode([[0,0],[1,0],[2,0],[0,1],[1,1]], GF(7))\n sage: C\n [36, 5] linear code over GF(7)\n sage: C.minimum_distance()\n 24\n sage: C.minimum_distance(algorithm="guava") # optional - gap_package_guava\n ...24\n sage: C = codes.ToricCode([[-2,-2],[-1,-2],[-1,-1],[-1,0],\n ....: [0,-1],[0,0],[0,1],[1,-1],[1,0]], GF(5))\n sage: C\n [16, 9] linear code over GF(5)\n sage: C.minimum_distance()\n 6\n sage: C.minimum_distance(algorithm="guava") # optional - gap_package_guava\n 6\n sage: C = codes.ToricCode([[0,0],[1,1],[1,2],[1,3],[1,4],[2,1],\n ....: [2,2],[2,3],[3,1],[3,2],[4,1]], GF(8,"a"))\n sage: C\n [49, 11] linear code over GF(8)\n\n This is in fact a [49,11,28] code over `\\GF{8}`. If you type next\n ``C.minimum_distance()`` and wait overnight (!), you\n should get 28.\n\n AUTHOR:\n\n - David Joyner (07-2006)\n '
from sage.combinat.tuple import Tuples
mset = [x for x in F if (x != 0)]
d = len(P[0])
pts = Tuples(mset, d).list()
n = len(pts)
k = len(P)
e = P[0]
B = []
for e in P:
tmpvar = [prod([(t[i] ** e[i]) for i in range(d)]) for t in pts]
B.append(tmpvar)
MS = MatrixSpace(F, k, n)
return LinearCode(MS(B))
|
def WalshCode(m):
"\n Return the binary Walsh code of length `2^m`.\n\n The matrix\n of codewords correspond to a Hadamard matrix. This is a (constant\n rate) binary linear `[2^m,m,2^{m-1}]` code.\n\n EXAMPLES::\n\n sage: C = codes.WalshCode(4); C\n [16, 4] linear code over GF(2)\n sage: C = codes.WalshCode(3); C\n [8, 3] linear code over GF(2)\n sage: C.spectrum()\n [1, 0, 0, 0, 7, 0, 0, 0, 0]\n sage: C.minimum_distance()\n 4\n sage: C.minimum_distance(algorithm='gap') # check d=2^(m-1)\n 4\n\n REFERENCES:\n\n - :wikipedia:`Hadamard_matrix`\n\n - :wikipedia:`Walsh_code`\n "
return LinearCode(walsh_matrix(m), d=(2 ** (m - 1)))
|
def find_generator_polynomial(code, check=True):
"\n Return a possible generator polynomial for ``code``.\n\n If the code is cyclic, the generator polynomial is the gcd of all the\n polynomial forms of the codewords. Conversely, if this gcd exactly\n generates the code ``code``, then ``code`` is cyclic.\n\n If ``check`` is set to ``True``, then it also checks that the code is\n indeed cyclic. Otherwise it doesn't.\n\n INPUT:\n\n - ``code`` -- a linear code\n\n - ``check`` -- whether the cyclicity should be checked\n\n OUTPUT:\n\n - the generator polynomial of ``code`` (if the code is cyclic).\n\n EXAMPLES::\n\n sage: from sage.coding.cyclic_code import find_generator_polynomial\n sage: C = codes.GeneralizedReedSolomonCode(GF(8, 'a').list()[1:], 4)\n sage: find_generator_polynomial(C)\n x^3 + (a^2 + 1)*x^2 + a*x + a^2 + 1\n "
G = code.generator_matrix()
F = code.base_ring()
R = F['x']
g = gcd((R(row.list()) for row in G))
if check:
n = code.length()
k = code.dimension()
if (g.degree() != (n - k)):
raise ValueError('The code is not cyclic.')
c = _to_complete_list(g, n)
if any(((vector((c[i:] + c[:i])) not in code) for i in range(n))):
raise ValueError('The code is not cyclic.')
return g.monic()
|
def _to_complete_list(poly, length):
"\n Return the vector of length exactly ``length`` corresponding to the\n coefficients of the provided polynomial. If needed, zeros are added.\n\n INPUT:\n\n - ``poly`` -- a polynomial\n\n - ``length`` -- an integer\n\n OUTPUT:\n\n - the list of coefficients\n\n EXAMPLES::\n\n sage: R = PolynomialRing(GF(2), 'X')\n sage: X = R.gen()\n sage: poly = X**4 + X + 1\n sage: sage.coding.cyclic_code._to_complete_list(poly, 7)\n [1, 1, 0, 0, 1, 0, 0]\n "
L = poly.coefficients(sparse=False)
return (L + ([poly.base_ring().zero()] * (length - len(L))))
|
def bch_bound(n, D, arithmetic=False):
'\n Return the BCH bound obtained for a cyclic code of length ``n`` and\n defining set ``D``.\n\n Consider a cyclic code `C`, with defining set `D`, length `n`, and minimum\n distance `d`. We have the following bound, called BCH bound, on `d`:\n `d \\geq \\delta + 1`, where `\\delta` is the length of the longest arithmetic\n sequence (modulo `n`) of elements in `D`.\n\n That is, if `\\exists c, \\gcd(c,n) = 1` such that\n `\\{l, l+c, \\dots, l + (\\delta - 1) \\times c\\} \\subseteq D`,\n then `d \\geq \\delta + 1` [1]\n\n The BCH bound is often known in the particular case `c = 1`. The user can\n specify by setting ``arithmetic = False``.\n\n .. NOTE::\n\n As this is a specific use case of the BCH bound, it is *not* available\n in the global namespace.\n Call it by using ``sage.coding.cyclic_code.bch_bound``. You can also\n load it into the global namespace by typing\n ``from sage.coding.cyclic_code import bch_bound``.\n\n INPUT:\n\n - ``n`` -- an integer\n\n - ``D`` -- a list of integers\n\n - ``arithmetic`` -- (default: ``False``), if it is set to ``True``, then it\n computes the BCH bound using the longest arithmetic sequence definition\n\n OUTPUT:\n\n - ``(delta + 1, (l, c))`` -- such that ``delta + 1`` is the BCH bound, and\n ``l, c`` are the parameters of the longest arithmetic sequence\n (see below)\n\n EXAMPLES::\n\n sage: n = 15\n sage: D = [14,1,2,11,12]\n sage: sage.coding.cyclic_code.bch_bound(n, D)\n (3, (1, 1))\n\n sage: n = 15\n sage: D = [14,1,2,11,12]\n sage: sage.coding.cyclic_code.bch_bound(n, D, True)\n (4, (2, 12))\n '
def longest_streak(step):
max_len = 1
max_offset = 0
j = 0
while (j < n):
h = j
while isD[((h * step) % n)]:
h += 1
if ((h - j) > max_len):
max_offset = ((j * step) % n)
max_len = (h - j)
j = (h + 1)
return (max_len, max_offset)
isD = ([0] * n)
for d in D:
try:
isD[d] = 1
except IndexError:
raise ValueError(('%s must contains integers between 0 and %s' % (D, (n - 1))))
if (0 not in isD):
return ((n + 1), (1, 0))
if (not arithmetic):
(one_len, offset) = longest_streak(1)
return ((one_len + 1), (1, offset))
else:
n = Integer(n)
longest_streak_list = [(longest_streak(step), step) for step in n.coprime_integers(((n // 2) + 1)) if (step >= 1)]
((max_len, offset), step) = max(longest_streak_list)
return ((max_len + 1), (step, offset))
|
class CyclicCode(AbstractLinearCode):
"\n Representation of a cyclic code.\n\n We propose three different ways to create a new :class:`CyclicCode`, either by\n providing:\n\n - the generator polynomial and the length (1)\n - an existing linear code. In that case, a generator polynomial will be\n computed from the provided linear code's parameters (2)\n - (a subset of) the defining set of the cyclic code (3)\n\n For now, only single-root cyclic codes are implemented. That is, only\n cyclic codes such that its length `n` and field order `q` are coprimes.\n\n Depending on which behaviour you want, you need to specify the names of the\n arguments to :class:`CyclicCode`. See EXAMPLES section below for details.\n\n INPUT:\n\n - ``generator_pol`` -- (default: ``None``) the generator polynomial\n of ``self``. That is, the highest-degree monic polynomial which divides\n every polynomial representation of a codeword in ``self``.\n\n - ``length`` -- (default: ``None``) the length of ``self``. It has to be\n bigger than the degree of ``generator_pol``.\n\n - ``code`` -- (default: ``None``) a linear code.\n\n - ``check`` -- (default: ``False``) a boolean representing whether the\n cyclicity of ``self`` must be checked while finding the generator\n polynomial. See :meth:`find_generator_polynomial` for details.\n\n - ``D`` -- (default: ``None``) a list of integers between ``0`` and\n ``length-1``, corresponding to (a subset of) the defining set of the code.\n Will be modified if it is not cyclotomic-closed.\n\n - ``field`` -- (default: ``None``) the base field of ``self``.\n\n - ``primitive_root`` -- (default: ``None``) the primitive root of\n the splitting field which contains the roots of the generator polynomial.\n It has to be of multiplicative order ``length`` over this field.\n If the splitting field is not ``field``, it also have to be a polynomial\n in ``zx``, where ``x`` is the degree of the extension over the prime\n field. For instance, over ``GF(16)``, it must be a polynomial in ``z4``.\n\n EXAMPLES:\n\n We can construct a :class:`CyclicCode` object using three different methods.\n First (1), we provide a generator polynomial and a code length::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C\n [7, 4] Cyclic Code over GF(2)\n\n We can also provide a code (2). In that case, the program will try to\n extract a generator polynomial (see :meth:`find_generator_polynomial`\n for details)::\n\n sage: C = codes.GeneralizedReedSolomonCode(GF(8, 'a').list()[1:], 4)\n sage: Cc = codes.CyclicCode(code = C)\n sage: Cc\n [7, 4] Cyclic Code over GF(8)\n\n Finally, we can give (a subset of) a defining set for the code (3).\n In this case, the generator polynomial will be computed::\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: Cc = codes.CyclicCode(length=n, field=F, D = [1,2])\n sage: Cc\n [15, 13] Cyclic Code over GF(16)\n "
_registered_encoders = {}
_registered_decoders = {}
def __init__(self, generator_pol=None, length=None, code=None, check=True, D=None, field=None, primitive_root=None):
"\n TESTS:\n\n If one provides a generator polynomial and a length, we check that\n the length is bigger than the degree of the polynomial::\n\n sage: F.<x> = GF(2)[]\n sage: n = 2\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n Traceback (most recent call last):\n ...\n ValueError: Only cyclic codes whose length and field order are coprimes are implemented.\n\n We also check that the polynomial is defined over a finite field::\n\n sage: F.<x> = RR[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n Traceback (most recent call last):\n ...\n ValueError: The generator polynomial must be defined over a finite field.\n\n And we check that the generator polynomial divides `x^{n} - 1`,\n where `n` is provided length::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 2 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n Traceback (most recent call last):\n ...\n ValueError: Provided polynomial must divide x^n - 1, where n is the provided length.\n\n In the case of a code is passed as argument, if it's not possible\n to extract a generator polynomial, an exception is raised::\n\n sage: G = matrix(GF(2), [[1, 1, 1], [0, 1, 1]])\n sage: C = codes.LinearCode(G)\n sage: Cc = codes.CyclicCode(code=C)\n Traceback (most recent call last):\n ...\n ValueError: The code is not cyclic.\n\n If the ``primitive_root`` does not lie in an extension of ``field``,\n or is not a primitive `n`-th root of unity, then\n an exception is raised::\n\n sage: F = GF(2)\n sage: n = 15\n sage: Dset = [1, 2, 4, 8]\n sage: alpha = GF(3).one()\n sage: Cc = codes.CyclicCode(D=Dset, field=F, length=n, primitive_root=alpha)\n Traceback (most recent call last):\n ...\n ValueError: primitive_root must belong to an extension of the base field\n sage: alpha = GF(16).one()\n sage: Cc = codes.CyclicCode(D=Dset, field=F, length=n, primitive_root=alpha)\n Traceback (most recent call last):\n ...\n ValueError: primitive_root must be a primitive n-th root of unity\n sage: alpha = GF(32).gen()\n sage: Cc = codes.CyclicCode(D=Dset, field=F, length=n, primitive_root=alpha)\n Traceback (most recent call last):\n ...\n ValueError: primitive_root must be a primitive n-th root of unity\n "
if ((generator_pol is not None) and (length is not None) and (code is None) and (D is None) and (field is None) and (primitive_root is None)):
F = generator_pol.base_ring()
if ((not F.is_finite()) or (not F.is_field())):
raise ValueError('The generator polynomial must be defined over a finite field.')
q = F.cardinality()
if (not (gcd(length, q) == 1)):
raise ValueError('Only cyclic codes whose length and field order are coprimes are implemented.')
R = generator_pol.parent()
deg = generator_pol.degree()
if (not isinstance(length, Integer)):
length = Integer(length)
if (not generator_pol.divides(((R.gen() ** length) - 1))):
raise ValueError('Provided polynomial must divide x^n - 1, where n is the provided length.')
self._polynomial_ring = R
self._dimension = (length - deg)
if (not generator_pol.is_monic()):
self._generator_polynomial = generator_pol.monic()
else:
self._generator_polynomial = generator_pol
super().__init__(F, length, 'Vector', 'Syndrome')
elif ((code is not None) and (generator_pol is None) and (length is None) and (D is None) and (field is None) and (primitive_root is None)):
if (not isinstance(code, AbstractLinearCode)):
raise ValueError('code must be an AbstractLinearCode')
F = code.base_ring()
q = F.cardinality()
n = code.length()
if (not (gcd(n, q) == 1)):
raise ValueError('Only cyclic codes whose length and field order are coprimes are implemented.')
g = find_generator_polynomial(code, check)
self._polynomial_ring = g.parent()
self._generator_polynomial = g
self._dimension = code.dimension()
super().__init__(code.base_ring(), n, 'Vector', 'Syndrome')
elif ((D is not None) and (length is not None) and (field is not None) and (generator_pol is None) and (code is None)):
F = field
if ((not F.is_finite()) or (not F.is_field())):
raise ValueError('You must provide a finite field.')
n = length
q = F.cardinality()
if (not (gcd(n, q) == 1)):
raise ValueError('Only cyclic codes whose length and field order are coprimes are implemented.')
R = F['x']
s = Zmod(n)(q).multiplicative_order()
if (primitive_root is not None):
Fsplit = primitive_root.parent()
try:
FE = Hom(F, Fsplit)[0]
except Exception:
raise ValueError('primitive_root must belong to an extension of the base field')
extension_degree = (Fsplit.degree() // F.degree())
if ((extension_degree != s) or (primitive_root.multiplicative_order() != n)):
raise ValueError('primitive_root must be a primitive n-th root of unity')
alpha = primitive_root
else:
(Fsplit, FE) = F.extension(Integer(s), map=True)
alpha = Fsplit.zeta(n)
Rsplit = Fsplit['xx']
xx = Rsplit.gen()
cosets = Zmod(n).cyclotomic_cosets(q, D)
pows = [item for l in cosets for item in l]
sec = FE.section()
g = R.one()
for J in cosets:
pol = Rsplit.one()
for j in J:
pol *= (xx - (alpha ** j))
g *= R([sec(coeff) for coeff in pol])
self._field_embedding = FE
self._primitive_root = alpha
self._defining_set = sorted(pows)
self._polynomial_ring = R
self._generator_polynomial = g
self._dimension = (n - g.degree())
super().__init__(F, n, 'Vector', 'SurroundingBCH')
else:
raise AttributeError('You must provide either a code, or a list of powers and the length and the field, or a generator polynomial and the code length')
def __contains__(self, word):
'\n Return ``True`` if ``word`` belongs to ``self``, ``False`` otherwise.\n\n INPUT:\n\n - ``word`` -- the word to test\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: c = vector(GF(2), (1, 1, 1, 0, 0, 1, 0))\n sage: c in C\n True\n '
g = self.generator_polynomial()
R = self._polynomial_ring
return (g.divides(R(word.list())) and (word in self.ambient_space()))
def __eq__(self, other):
'\n Tests equality between CyclicCode objects.\n\n INPUT:\n\n - ``other`` -- the code to test\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C1 = codes.CyclicCode(generator_pol=g, length=n)\n sage: C2 = codes.CyclicCode(generator_pol=g, length=n)\n sage: C1 == C2\n True\n '
if (not isinstance(other, CyclicCode)):
return False
else:
R = self._polynomial_ring
return ((self.base_field() == other.base_field()) and (self.length() == other.length()) and (self.generator_polynomial() == R(other.generator_polynomial())))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C\n [7, 4] Cyclic Code over GF(2)\n '
return ('[%s, %s] Cyclic Code over GF(%s)' % (self.length(), self.dimension(), self.base_field().cardinality()))
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: latex(C)\n [7, 4] \\textnormal{ Cyclic Code over } \\Bold{F}_{2}\n '
return ('[%s, %s] \\textnormal{ Cyclic Code over } %s' % (self.length(), self.dimension(), self.base_field()._latex_()))
def generator_polynomial(self):
'\n Return the generator polynomial of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C.generator_polynomial()\n x^3 + x + 1\n '
return self._generator_polynomial
def field_embedding(self):
'\n Return the base field embedding into the splitting field.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C.field_embedding()\n Ring morphism:\n From: Finite Field of size 2\n To: Finite Field in z3 of size 2^3\n Defn: 1 |--> 1\n '
if (not hasattr(self, '_field_embedding')):
self.defining_set()
return self._field_embedding
def defining_set(self, primitive_root=None):
"\n Return the set of exponents of the roots of ``self``'s generator\n polynomial over the extension field. Of course, it depends on the\n choice of the primitive root of the splitting field.\n\n\n INPUT:\n\n - ``primitive_root`` (optional) -- a primitive root of the extension\n field\n\n EXAMPLES:\n\n We provide a defining set at construction time::\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: C = codes.CyclicCode(length=n, field=F, D=[1,2])\n sage: C.defining_set()\n [1, 2]\n\n If the defining set was provided by the user, it might have been\n expanded at construction time. In this case, the expanded defining set\n will be returned::\n\n sage: C = codes.CyclicCode(length=13, field=F, D=[1, 2])\n sage: C.defining_set()\n [1, 2, 3, 5, 6, 9]\n\n If a generator polynomial was passed at construction time,\n the defining set is computed using this polynomial::\n\n sage: R.<x> = F[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C.defining_set()\n [1, 2, 4]\n\n Both operations give the same result::\n\n sage: C1 = codes.CyclicCode(length=n, field=F, D=[1, 2, 4])\n sage: C1.generator_polynomial() == g\n True\n\n Another one, in a reversed order::\n\n sage: n = 13\n sage: C1 = codes.CyclicCode(length=n, field=F, D=[1, 2])\n sage: g = C1.generator_polynomial()\n sage: C2 = codes.CyclicCode(generator_pol=g, length=n)\n sage: C1.defining_set() == C2.defining_set()\n True\n "
if (hasattr(self, '_defining_set') and ((primitive_root is None) or (primitive_root == self._primitive_root))):
return self._defining_set
else:
F = self.base_field()
n = self.length()
q = F.cardinality()
g = self.generator_polynomial()
s = Zmod(n)(q).multiplicative_order()
if (primitive_root is None):
(Fsplit, FE) = F.extension(Integer(s), map=True)
alpha = Fsplit.zeta(n)
else:
try:
alpha = primitive_root
Fsplit = alpha.parent()
FE = Hom(Fsplit, F)[0]
except ValueError:
raise ValueError('primitive_root does not belong to the right splitting field')
if (alpha.multiplicative_order() != n):
raise ValueError('primitive_root must have multiplicative order equal to the code length')
Rsplit = Fsplit['xx']
gsplit = Rsplit([FE(coeff) for coeff in g])
roots = gsplit.roots(multiplicities=False)
D = [root.log(alpha) for root in roots]
self._field_embedding = FE
self._primitive_root = alpha
self._defining_set = sorted(D)
return self._defining_set
def primitive_root(self):
"\n Return the primitive root of the splitting field that is used\n to build the defining set of the code.\n\n If it has not been specified by the user, it is set by default with the\n output of the ``zeta`` method of the splitting field.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C.primitive_root()\n z3\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: a = F.gen()\n sage: Cc = codes.CyclicCode(length=n, field=F, D=[1,2],\n ....: primitive_root=a^2 + 1)\n sage: Cc.primitive_root()\n a^2 + 1\n "
if hasattr(self, '_primitive_root'):
return self._primitive_root
else:
self.defining_set()
return self._primitive_root
@cached_method
def check_polynomial(self):
"\n Return the check polynomial of ``self``.\n\n Let `C` be a cyclic code of length `n` and `g` its generator\n polynomial. The following: `h = \\frac{x^n - 1}{g(x)}` is called `C`'s\n check polynomial.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: h = C.check_polynomial()\n sage: h == (x**n - 1)/C.generator_polynomial()\n True\n "
R = self._polynomial_ring
n = self.length()
self._check_polynomial = (((R.gen() ** n) - 1) // self.generator_polynomial())
return self._check_polynomial
@cached_method
def parity_check_matrix(self):
'\n Return the parity check matrix of ``self``.\n\n The parity check matrix of a linear code `C` corresponds to the\n generator matrix of the dual code of `C`.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: C.parity_check_matrix()\n [1 0 1 1 1 0 0]\n [0 1 0 1 1 1 0]\n [0 0 1 0 1 1 1]\n '
k = self.dimension()
n = self.length()
h = self.check_polynomial().reverse()
l = _to_complete_list(h, n)
M = matrix([(l[(- i):] + l[:(- i)]) for i in range((n - k))])
M.set_immutable()
return M
def bch_bound(self, arithmetic=False):
"\n Return the BCH bound of ``self`` which is a bound on ``self``\n minimum distance.\n\n See :meth:`sage.coding.cyclic_code.bch_bound` for details.\n\n INPUT:\n\n - ``arithmetic`` -- (default: ``False``), if it is set to ``True``,\n then it computes the BCH bound using the longest arithmetic sequence\n definition\n\n OUTPUT:\n\n - ``(delta + 1, (l, c))`` -- such that ``delta + 1`` is the BCH bound,\n and ``l, c`` are the parameters of the largest arithmetic sequence\n\n EXAMPLES::\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: D = [14,1,2,11,12]\n sage: C = codes.CyclicCode(field=F, length=n, D = D)\n sage: C.bch_bound()\n (3, (1, 1))\n\n sage: F = GF(16, 'a')\n sage: n = 15\n sage: D = [14,1,2,11,12]\n sage: C = codes.CyclicCode(field=F, length=n, D = D)\n sage: C.bch_bound(True)\n (4, (2, 12))\n "
return bch_bound(self.length(), self.defining_set(), arithmetic)
def surrounding_bch_code(self):
'\n Return the surrounding BCH code of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(2), length=63, D=[1, 7, 17])\n sage: C.dimension()\n 45\n sage: CC = C.surrounding_bch_code()\n sage: CC\n [63, 51] BCH Code over GF(2) with designed distance 3\n sage: all(r in CC for r in C.generator_matrix())\n True\n '
from .bch_code import BCHCode
(delta, params) = self.bch_bound(arithmetic=True)
return BCHCode(self.base_field(), self.length(), delta, offset=params[1], jump_size=params[0])
|
class CyclicCodePolynomialEncoder(Encoder):
'\n An encoder encoding polynomials into codewords.\n\n Let `C` be a cyclic code over some finite field `F`,\n and let `g` be its generator polynomial.\n\n This encoder encodes any polynomial `p \\in F[x]_{<k}` by computing\n `c = p g` and returning the vector of its coefficients.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E\n Polynomial-style encoder for [7, 4] Cyclic Code over GF(2)\n '
def __init__(self, code):
'\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E\n Polynomial-style encoder for [7, 4] Cyclic Code over GF(2)\n '
if (not isinstance(code, CyclicCode)):
raise ValueError('code has to be a CyclicCode')
self._polynomial_ring = code._polynomial_ring
super().__init__(code)
def __eq__(self, other):
'\n Tests equality between CyclicCodePolynomialEncoder objects.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E1 = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E2 = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E1 == E2\n True\n '
return (isinstance(other, CyclicCodePolynomialEncoder) and (self.code() == other.code()))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E\n Polynomial-style encoder for [7, 4] Cyclic Code over GF(2)\n '
return ('Polynomial-style encoder for %s' % self.code())
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: latex(E)\n \\textnormal{Polynomial-style encoder for }[7, 4] \\textnormal{ Cyclic Code over } \\Bold{F}_{2}\n '
return ('\\textnormal{Polynomial-style encoder for }%s' % self.code()._latex_())
def encode(self, p):
'\n Transforms ``p`` into an element of the associated code of ``self``.\n\n INPUT:\n\n - ``p`` -- A polynomial from ``self`` message space\n\n OUTPUT:\n\n - A codeword in associated code of ``self``\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: m = x ** 2 + 1\n sage: E.encode(m)\n (1, 1, 1, 0, 0, 1, 0)\n '
C = self.code()
k = C.dimension()
n = C.length()
if (p.degree() >= k):
raise ValueError((('Degree of the message must be at most %s' % k) - 1))
res = _to_complete_list((p * C.generator_polynomial()), n)
return vector(C.base_field(), res)
def unencode_nocheck(self, c):
'\n Return the message corresponding to ``c``.\n Does not check if ``c`` belongs to the code.\n\n INPUT:\n\n - ``c`` -- A vector with the same length as the code\n\n OUTPUT:\n\n - An element of the message space\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: c = vector(GF(2), (1, 1, 1, 0, 0, 1, 0))\n sage: E.unencode_nocheck(c)\n x^2 + 1\n '
R = self.message_space()
g = self.code().generator_polynomial()
p = R(c.list())
return (p // g)
def message_space(self):
'\n Return the message space of ``self``\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodePolynomialEncoder(C)\n sage: E.message_space()\n Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X)\n '
return self._polynomial_ring
|
class CyclicCodeVectorEncoder(Encoder):
'\n An encoder which can encode vectors into codewords.\n\n Let `C` be a cyclic code over some finite field `F`,\n and let `g` be its generator polynomial.\n\n Let `m = (m_1, m_2, \\dots, m_k)` be a vector in `F^{k}`.\n This codeword can be seen as a polynomial over `F[x]`, as follows:\n `P_m = \\Sigma_{i=0}^{k-1} m_i \\times x^i`.\n\n To encode `m`, this encoder does the multiplication `P_m g`.\n\n INPUT:\n\n - ``code`` -- The associated code of this encoder\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E\n Vector-style encoder for [7, 4] Cyclic Code over GF(2)\n '
def __init__(self, code):
'\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E\n Vector-style encoder for [7, 4] Cyclic Code over GF(2)\n '
if (not isinstance(code, CyclicCode)):
raise ValueError('code has to be a CyclicCode')
self._polynomial_ring = code._polynomial_ring
super().__init__(code)
def __eq__(self, other):
'\n Tests equality between CyclicCodeVectorEncoder objects.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E1 = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E2 = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E1 == E2\n True\n '
return (isinstance(other, CyclicCodeVectorEncoder) and (self.code() == other.code()))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E\n Vector-style encoder for [7, 4] Cyclic Code over GF(2)\n '
return ('Vector-style encoder for %s' % self.code())
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: latex(E)\n \\textnormal{Vector-style encoder for }[7, 4] \\textnormal{ Cyclic Code over } \\Bold{F}_{2}\n '
return ('\\textnormal{Vector-style encoder for }%s' % self.code()._latex_())
def encode(self, m):
"\n Transforms ``m`` into an element of the associated code of ``self``.\n\n INPUT:\n\n - ``m`` -- an element from ``self``'s message space\n\n OUTPUT:\n\n - A codeword in the associated code of ``self``\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: m = vector(GF(2), (1, 0, 1, 0))\n sage: E.encode(m)\n (1, 1, 1, 0, 0, 1, 0)\n "
if (self.generator_matrix.cache is not None):
return super().encode(m)
k = self.code().dimension()
n = self.code().length()
F = self.code().base_field()
R = self._polynomial_ring
p = R(m.list())
if (p.degree() >= k):
raise ValueError((('Degree of the message must be at most %s' % k) - 1))
res = _to_complete_list((p * self.code().generator_polynomial()), n)
return vector(F, res)
def unencode_nocheck(self, c):
'\n Return the message corresponding to ``c``.\n Does not check if ``c`` belongs to the code.\n\n INPUT:\n\n - ``c`` -- A vector with the same length as the code\n\n OUTPUT:\n\n - An element of the message space\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: c = vector(GF(2), (1, 1, 1, 0, 0, 1, 0))\n sage: E.unencode_nocheck(c)\n (1, 0, 1, 0)\n '
R = self._polynomial_ring
g = self.code().generator_polynomial()
p = R(c.list())
l = _to_complete_list((p // g), self.message_space().dimension())
return vector(self.code().base_field(), l)
@cached_method
def generator_matrix(self):
'\n Return a generator matrix of ``self``\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E.generator_matrix()\n [1 1 0 1 0 0 0]\n [0 1 1 0 1 0 0]\n [0 0 1 1 0 1 0]\n [0 0 0 1 1 0 1]\n '
C = self.code()
k = C.dimension()
n = C.length()
l = _to_complete_list(C.generator_polynomial(), n)
M = matrix([(l[(- i):] + l[:(- i)]) for i in range(k)])
M.set_immutable()
return M
def message_space(self):
'\n Return the message space of ``self``\n\n EXAMPLES::\n\n sage: F.<x> = GF(2)[]\n sage: n = 7\n sage: g = x ** 3 + x + 1\n sage: C = codes.CyclicCode(generator_pol=g, length=n)\n sage: E = codes.encoders.CyclicCodeVectorEncoder(C)\n sage: E.message_space()\n Vector space of dimension 4 over Finite Field of size 2\n '
return (self.code().base_ring() ** self.code().dimension())
|
class CyclicCodeSurroundingBCHDecoder(Decoder):
'\n A decoder which decodes through the surrounding BCH code of the cyclic\n code.\n\n INPUT:\n\n - ``code`` -- The associated code of this decoder.\n\n - ``**kwargs`` -- All extra arguments are forwarded to the BCH decoder\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D\n Decoder through the surrounding BCH code of the [15, 10] Cyclic Code over GF(16)\n '
def __init__(self, code, **kwargs):
'\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D\n Decoder through the surrounding BCH code of the [15, 10] Cyclic Code over GF(16)\n '
self._bch_code = code.surrounding_bch_code()
self._bch_decoder = self._bch_code.decoder(**kwargs)
self._decoder_type = copy(self._bch_decoder.decoder_type())
super().__init__(code, code.ambient_space(), 'Vector')
def __eq__(self, other):
'\n Tests equality between CyclicCodeSurroundingBCHDecoder objects.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D1 = C.decoder()\n sage: D2 = C.decoder()\n sage: D1 == D2\n True\n '
return (isinstance(other, CyclicCodeSurroundingBCHDecoder) and (self.code() == other.code()) and (self.bch_decoder() == other.bch_decoder()))
def _repr_(self):
'\n Return a string representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D\n Decoder through the surrounding BCH code of the [15, 10] Cyclic Code over GF(16)\n '
return ('Decoder through the surrounding BCH code of the %s' % self.code())
def _latex_(self):
'\n Return a latex representation of ``self``.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: latex(D)\n \\textnormal{Decoder through the surrounding BCH code of the }[15, 10] \\textnormal{ Cyclic Code over } \\Bold{F}_{2^{4}}\n '
return ('\\textnormal{Decoder through the surrounding BCH code of the }%s' % self.code()._latex_())
def bch_code(self):
'\n Return the surrounding BCH code of\n :meth:`sage.coding.encoder.Encoder.code`.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D.bch_code()\n [15, 12] BCH Code over GF(16) with designed distance 4\n '
return self._bch_code
def bch_decoder(self):
'\n Return the decoder that will be used over the surrounding BCH code.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D.bch_decoder()\n Decoder through the underlying GRS code of [15, 12] BCH Code\n over GF(16) with designed distance 4\n '
return self._bch_decoder
def decode_to_code(self, y):
"\n Decodes ``r`` to an element in :meth:`sage.coding.encoder.Encoder.code`.\n\n EXAMPLES::\n\n sage: F = GF(16, 'a')\n sage: C = codes.CyclicCode(field=F, length=15, D=[14, 1, 2, 11, 12])\n sage: a = F.gen()\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: y = vector(F, [0, a^3, a^3 + a^2 + a, 1, a^2 + 1, a^3 + a^2 + 1,\n ....: a^3 + a^2 + a, a^3 + a^2 + a, a^2 + a, a^2 + 1,\n ....: a^2 + a + 1, a^3 + 1, a^2, a^3 + a, a^3 + a])\n sage: D.decode_to_code(y) in C\n True\n "
return self.bch_code().decode_to_code(y)
def decoding_radius(self):
'\n Return maximal number of errors that ``self`` can decode.\n\n EXAMPLES::\n\n sage: C = codes.CyclicCode(field=GF(16), length=15, D=[14, 1, 2, 11, 12])\n sage: D = codes.decoders.CyclicCodeSurroundingBCHDecoder(C)\n sage: D.decoding_radius()\n 1\n '
return self._bch_decoder.decoding_radius()
|
def best_linear_code_in_guava(n, k, F):
"\n Return the linear code of length ``n``, dimension ``k`` over field ``F``\n with the maximal minimum distance which is known to the GAP package GUAVA.\n\n The function uses the tables described in :func:`bounds_on_minimum_distance_in_guava` to\n construct this code. This requires the optional GAP package GUAVA.\n\n INPUT:\n\n - ``n`` -- the length of the code to look up\n\n - ``k`` -- the dimension of the code to look up\n\n - ``F`` -- the base field of the code to look up\n\n OUTPUT:\n\n A :class:`LinearCode` which is a best linear code of the given parameters known to GUAVA.\n\n EXAMPLES::\n\n sage: codes.databases.best_linear_code_in_guava(10,5,GF(2)) # long time; optional - gap_package_guava\n [10, 5] linear code over GF(2)\n sage: libgap.LoadPackage('guava') # long time; optional - gap_package_guava\n ...\n sage: libgap.BestKnownLinearCode(10,5,libgap.GF(2)) # long time; optional - gap_package_guava\n a linear [10,5,4]2..4 shortened code\n\n This means that the best possible binary linear code of length 10 and\n dimension 5 is a code with minimum distance 4 and covering radius s somewhere\n between 2 and 4. Use ``bounds_on_minimum_distance_in_guava(10,5,GF(2))``\n for further details.\n "
from .linear_code import LinearCode
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
C = libgap.BestKnownLinearCode(n, k, F)
return LinearCode(C.GeneratorMat()._matrix_(F))
|
def bounds_on_minimum_distance_in_guava(n, k, F):
'\n Compute a lower and upper bound on the greatest minimum distance of a\n `[n,k]` linear code over the field ``F``.\n\n This function requires the optional GAP package GUAVA.\n\n The function returns a GAP record with the two bounds and an explanation for\n each bound. The method ``Display`` can be used to show the explanations.\n\n The values for the lower and upper bound are obtained from a table\n constructed by Cen Tjhai for GUAVA, derived from the table of\n Brouwer. See http://www.codetables.de/ for the most recent data.\n These tables contain lower and upper bounds for `q=2` (when ``n <= 257``),\n `q=3` (when ``n <= 243``), `q=4` (``n <= 256``). (Current as of\n 11 May 2006.) For codes over other fields and for larger word lengths,\n trivial bounds are used.\n\n INPUT:\n\n - ``n`` -- the length of the code to look up\n\n - ``k`` -- the dimension of the code to look up\n\n - ``F`` -- the base field of the code to look up\n\n OUTPUT:\n\n - A GAP record object. See below for an example.\n\n EXAMPLES::\n\n sage: gap_rec = codes.databases.bounds_on_minimum_distance_in_guava(10,5,GF(2)) # optional - gap_package_guava\n sage: gap_rec.Display() # optional - gap_package_guava\n rec(\n construction := [ <Operation "ShortenedCode">,\n [ [ <Operation "UUVCode">,\n [ [ <Operation "DualCode">,\n [ [ <Operation "RepetitionCode">, [ 8, 2 ] ] ] ],\n [ <Operation "UUVCode">, [ [ <Operation "DualCode">,\n [ [ <Operation "RepetitionCode">, [ 4, 2 ] ] ] ],\n [ <Operation "RepetitionCode">, [ 4, 2 ] ] ] ] ] ],\n [ 1, 2, 3, 4, 5, 6 ] ] ],\n k := 5,\n lowerBound := 4,\n lowerBoundExplanation := ...\n n := 10,\n q := 2,\n references := rec(\n ),\n upperBound := 4,\n upperBoundExplanation := ... )\n '
GapPackage('guava', spkg='gap_packages').require()
libgap.load_package('guava')
return libgap.BoundsMinimumDistance(n, k, F)
|
def best_linear_code_in_codetables_dot_de(n, k, F, verbose=False):
'\n Return the best linear code and its construction as per the web database\n http://www.codetables.de/\n\n INPUT:\n\n - ``n`` - Integer, the length of the code\n\n - ``k`` - Integer, the dimension of the code\n\n - ``F`` - Finite field, of order 2, 3, 4, 5, 7, 8, or 9\n\n - ``verbose`` - Bool (default: ``False``)\n\n OUTPUT:\n\n - An unparsed text explaining the construction of the code.\n\n EXAMPLES::\n\n sage: L = codes.databases.best_linear_code_in_codetables_dot_de(72, 36, GF(2)) # optional - internet\n sage: print(L) # optional - internet\n Construction of a linear code\n [72,36,15] over GF(2):\n [1]: [73, 36, 16] Cyclic Linear Code over GF(2)\n CyclicCode of length 73 with generating polynomial x^37 + x^36 + x^34 +\n x^33 + x^32 + x^27 + x^25 + x^24 + x^22 + x^21 + x^19 + x^18 + x^15 + x^11 +\n x^10 + x^8 + x^7 + x^5 + x^3 + 1\n [2]: [72, 36, 15] Linear Code over GF(2)\n Puncturing of [1] at 1\n <BLANKLINE>\n last modified: 2002-03-20\n\n This function raises an :class:`IOError` if an error occurs downloading data or\n parsing it. It raises a :class:`ValueError` if the ``q`` input is invalid.\n\n AUTHORS:\n\n - Steven Sivek (2005-11-14)\n - David Joyner (2008-03)\n '
from urllib.request import urlopen
from sage.cpython.string import bytes_to_str
q = F.order()
if (q not in [2, 3, 4, 5, 7, 8, 9]):
raise ValueError(('q (=%s) must be in [2,3,4,5,7,8,9]' % q))
n = int(n)
k = int(k)
param = ('?q=%s&n=%s&k=%s' % (q, n, k)).replace('L', '')
url = (('http://www.codetables.de/' + 'BKLC/BKLC.php') + param)
if verbose:
print(('Looking up the bounds at %s' % url))
with urlopen(url) as f:
s = f.read()
s = bytes_to_str(s)
i = s.find('<PRE>')
j = s.find('</PRE>')
if ((i == (- 1)) or (j == (- 1))):
raise OSError('Error parsing data (missing pre tags).')
return s[(i + 5):j].strip()
|
def self_orthogonal_binary_codes(n, k, b=2, parent=None, BC=None, equal=False, in_test=None):
'\n Returns a Python iterator which generates a complete set of\n representatives of all permutation equivalence classes of\n self-orthogonal binary linear codes of length in ``[1..n]`` and\n dimension in ``[1..k]``.\n\n INPUT:\n\n - ``n`` -- Integer, maximal length\n\n - ``k`` -- Integer, maximal dimension\n\n - ``b`` -- Integer, requires that the generators all have weight divisible\n by ``b`` (if ``b=2``, all self-orthogonal codes are generated, and if\n ``b=4``, all doubly even codes are generated). Must be an even positive\n integer.\n\n - ``parent``- - Used in recursion (default: ``None``)\n\n - ``BC`` -- Used in recursion (default: ``None``)\n\n - ``equal`` -- If ``True``, generates only [n, k] codes (default: ``False``)\n\n - ``in_test`` -- Used in recursion (default: ``None``)\n\n EXAMPLES:\n\n Generate all self-orthogonal codes of length up to 7 and dimension up\n to 3::\n\n sage: for B in codes.databases.self_orthogonal_binary_codes(7,3):\n ....: print(B)\n [2, 1] linear code over GF(2)\n [4, 2] linear code over GF(2)\n [6, 3] linear code over GF(2)\n [4, 1] linear code over GF(2)\n [6, 2] linear code over GF(2)\n [6, 2] linear code over GF(2)\n [7, 3] linear code over GF(2)\n [6, 1] linear code over GF(2)\n\n Generate all doubly-even codes of length up to 7 and dimension up\n to 3::\n\n sage: for B in codes.databases.self_orthogonal_binary_codes(7,3,4):\n ....: print(B); print(B.generator_matrix())\n [4, 1] linear code over GF(2)\n [1 1 1 1]\n [6, 2] linear code over GF(2)\n [1 1 1 1 0 0]\n [0 1 0 1 1 1]\n [7, 3] linear code over GF(2)\n [1 0 1 1 0 1 0]\n [0 1 0 1 1 1 0]\n [0 0 1 0 1 1 1]\n\n Generate all doubly-even codes of length up to 7 and dimension up\n to 2::\n\n sage: for B in codes.databases.self_orthogonal_binary_codes(7,2,4):\n ....: print(B); print(B.generator_matrix())\n [4, 1] linear code over GF(2)\n [1 1 1 1]\n [6, 2] linear code over GF(2)\n [1 1 1 1 0 0]\n [0 1 0 1 1 1]\n\n Generate all self-orthogonal codes of length equal to 8 and\n dimension equal to 4::\n\n sage: for B in codes.databases.self_orthogonal_binary_codes(8, 4, equal=True):\n ....: print(B); print(B.generator_matrix())\n [8, 4] linear code over GF(2)\n [1 0 0 1 0 0 0 0]\n [0 1 0 0 1 0 0 0]\n [0 0 1 0 0 1 0 0]\n [0 0 0 0 0 0 1 1]\n [8, 4] linear code over GF(2)\n [1 0 0 1 1 0 1 0]\n [0 1 0 1 1 1 0 0]\n [0 0 1 0 1 1 1 0]\n [0 0 0 1 0 1 1 1]\n\n Since all the codes will be self-orthogonal, b must be divisible by\n 2::\n\n sage: list(codes.databases.self_orthogonal_binary_codes(8, 4, 1, equal=True))\n Traceback (most recent call last):\n ...\n ValueError: b (1) must be a positive even integer.\n '
from sage.rings.finite_rings.finite_field_constructor import FiniteField
from sage.matrix.constructor import Matrix
d = int(b)
if ((d != b) or ((d % 2) == 1) or (d <= 0)):
raise ValueError(('b (%s) must be a positive even integer.' % b))
from .linear_code import LinearCode
from .binary_code import BinaryCode, BinaryCodeClassifier
if ((k < 1) or (n < 2)):
return
if equal:
in_test = (lambda M: ((M.ncols() - M.nrows()) <= (n - k)))
out_test = (lambda C: ((C.dimension() == k) and (C.length() == n)))
else:
in_test = (lambda M: True)
out_test = (lambda C: True)
if (BC is None):
BC = BinaryCodeClassifier()
if (parent is None):
for j in range(d, (n + 1), d):
M = Matrix(FiniteField(2), [([1] * j)])
if in_test(M):
for N in self_orthogonal_binary_codes(n, k, d, M, BC, in_test=in_test):
if out_test(N):
(yield N)
else:
C = LinearCode(parent)
if out_test(C):
(yield C)
if (k == parent.nrows()):
return
for nn in range((parent.ncols() + 1), (n + 1)):
if in_test(parent):
for child in BC.generate_children(BinaryCode(parent), nn, d):
for N in self_orthogonal_binary_codes(n, k, d, child, BC, in_test=in_test):
if out_test(N):
(yield N)
|
class Decoder(SageObject):
'\n Abstract top-class for :class:`Decoder` objects.\n\n Every decoder class for linear codes (of any metric) should inherit from\n this abstract class.\n\n To implement a decoder, you need to:\n\n - inherit from :class:`Decoder`\n\n - call ``Decoder.__init__`` in the subclass constructor.\n Example: ``super().__init__(code, input_space, connected_encoder_name)``.\n By doing that, your subclass will have all the parameters described above initialized.\n\n - Then, you need to override one of decoding methods, either :meth:`decode_to_code` or\n :meth:`decode_to_message`. You can also override the optional method :meth:`decoding_radius`.\n\n - By default, comparison of :class:`Decoder` (using methods ``__eq__`` and ``__ne__`` ) are\n by memory reference: if you build the same decoder twice, they will be different. If you\n need something more clever, override ``__eq__`` and ``__ne__`` in your subclass.\n\n - As :class:`Decoder` is not designed to be instantiated, it does not have any representation\n methods. You should implement ``_repr_`` and ``_latex_`` methods in the subclass.\n '
@classmethod
def decoder_type(cls):
"\n Returns the set of types of ``self``.\n\n This method can be called on both an uninstantiated decoder class,\n or on an instance of a decoder class.\n\n The types of a decoder are a set of labels commonly associated with\n decoders which describe the nature and behaviour of the decoding\n algorithm. It should be considered as an informal descriptor but\n can be coarsely relied upon for e.g. program logic.\n\n The following are the most common types and a brief definition:\n\n ====================== ================================================\n Decoder type Definition\n ====================== ================================================\n always-succeed The decoder always returns a closest codeword if\n the number of errors is up to the decoding\n radius.\n bounded-distance Any vector with Hamming distance at most\n ``decoding_radius()`` to a codeword is\n decodable to some codeword. If ``might-fail`` is\n also a type, then this is not a guarantee but an\n expectancy.\n complete The decoder decodes every word in the ambient\n space of the code.\n dynamic Some of the decoder's types will only be\n determined at construction time\n (depends on the parameters).\n half-minimum-distance The decoder corrects up to half the minimum\n distance, or a specific lower bound thereof.\n hard-decision The decoder uses no information on which\n positions are more likely to be in error or not.\n list-decoder The decoder outputs a list of likely codewords,\n instead of just a single codeword.\n might-fail The decoder can fail at decoding even within its\n usual promises, e.g. bounded distance.\n not-always-closest The decoder does not guarantee to always return a\n closest codeword.\n probabilistic The decoder has internal randomness which can affect\n running time and the decoding result.\n soft-decision As part of the input, the decoder takes\n reliability information on which positions are\n more likely to be in error. Such a decoder only\n works for specific channels.\n ====================== ================================================\n\n\n EXAMPLES:\n\n We call it on a class::\n\n sage: codes.decoders.LinearCodeSyndromeDecoder.decoder_type()\n {'dynamic', 'hard-decision'}\n\n We can also call it on a instance of a :class:`Decoder` class::\n\n sage: G = Matrix(GF(2), [[1, 0, 0, 1], [0, 1, 1, 1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.decoder_type()\n {'complete', 'hard-decision', 'might-error'}\n "
return cls._decoder_type
def _instance_decoder_type(self):
"\n See the documentation of :meth:`decoder_type`.\n\n EXAMPLES:\n\n Test to satisfy the doc-testing framework::\n\n sage: G = Matrix(GF(2), [[1, 0, 0, 1], [0, 1, 1, 1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.decoder_type() #indirect doctest\n {'complete', 'hard-decision', 'might-error'}\n "
return self._decoder_type
def __init__(self, code, input_space, connected_encoder_name):
'\n Initializes mandatory parameters for :class:`Decoder` objects.\n\n This method only exists for inheritance purposes as it initializes\n parameters that need to be known by every decoder. An abstract\n decoder object should never be created.\n\n INPUT:\n\n - ``code`` -- the associated code of ``self``\n\n - ``input_space`` -- the input space of ``self``, which is the ambient space\n of ``self``\'s ``code``\n\n - ``connected_encoder_name`` -- the associated encoder, which will be\n used by ``self`` to recover elements from the message space\n\n EXAMPLES:\n\n We first create a new :class:`Decoder` subclass::\n\n sage: from sage.coding.decoder import Decoder\n sage: class DecoderExample(Decoder):\n ....: def __init__(self, code):\n ....: in_space = code.ambient_space()\n ....: connected_enc = "GeneratorMatrix"\n ....: super().__init__(code, in_space, connected_enc)\n\n We now create a member of our brand new class::\n\n sage: G = Matrix(GF(2), [[1, 0, 0, 1], [0, 1, 1, 1]])\n sage: C = LinearCode(G)\n sage: D = DecoderExample(C)\n\n We can check its parameters::\n\n sage: D.input_space()\n Vector space of dimension 4 over Finite Field of size 2\n sage: D.connected_encoder()\n Generator matrix-based encoder for [4, 2] linear code over GF(2)\n sage: D.code()\n [4, 2] linear code over GF(2)\n '
self.decoder_type = self._instance_decoder_type
self._code = code
self._input_space = input_space
self._connected_encoder_name = connected_encoder_name
def __hash__(self):
'\n Returns the hash value of ``self``.\n\n This is a generic implementation which should be overwritten on decoders\n with extra arguments.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: hash(D) #random\n 7575380076354998465\n '
C = self.code()
Str = str(C)
return ((hash((C, Str)) ^ hash(Str)) ^ hash(C))
def __ne__(self, other):
'\n Tests inequality of ``self`` and ``other``.\n\n This is a generic implementation, which returns the inverse of ``__eq__`` for self.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])\n sage: D1 = LinearCode(G).decoder()\n sage: D2 = LinearCode(G).decoder()\n sage: D1 != D2\n False\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,1,1]])\n sage: D2 = LinearCode(G).decoder()\n sage: D1 != D2\n True\n '
return (not (self == other))
def decode_to_code(self, r):
'\n Correct the errors in ``r`` and return a codeword.\n\n This is a default implementation which assumes that the method\n :meth:`decode_to_message` has been implemented, else it returns an exception.\n\n INPUT:\n\n - ``r`` -- a element of the input space of ``self``.\n\n OUTPUT:\n\n - a vector of :meth:`code`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: word in C\n True\n sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0))\n sage: w_err in C\n False\n sage: D = C.decoder()\n sage: D.decode_to_code(w_err)\n (1, 1, 0, 0, 1, 1, 0)\n '
if hasattr(self, 'defaulting_decode_to_message'):
raise NotImplementedError
else:
word = self.decode_to_message(r)
return self.connected_encoder().encode(word)
def connected_encoder(self):
'\n Return the connected encoder of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.connected_encoder()\n Generator matrix-based encoder for [7, 4] linear code over GF(2)\n '
return self.code().encoder(encoder_name=self._connected_encoder_name)
def decode_to_message(self, r):
'\n Decode ``r`` to the message space of :meth:`connected_encoder`.\n\n This is a default implementation, which assumes that the\n method :meth:`decode_to_code` has been implemented, else it\n returns an exception.\n\n INPUT:\n\n - ``r`` -- a element of the input space of ``self``.\n\n OUTPUT:\n\n - a vector of :meth:`message_space`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: word = vector(GF(2), (1, 1, 0, 0, 1, 1, 0))\n sage: w_err = word + vector(GF(2), (1, 0, 0, 0, 0, 0, 0))\n sage: D = C.decoder()\n sage: D.decode_to_message(w_err)\n (0, 1, 1, 0)\n '
self.defaulting_decode_to_message = True
return self.code().unencode(self.decode_to_code(r))
def code(self):
'\n Return the code for this :class:`Decoder`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.code()\n [7, 4] linear code over GF(2)\n '
return self._code
def message_space(self):
"\n Return the message space of ``self``'s :meth:`connected_encoder`.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.message_space()\n Vector space of dimension 4 over Finite Field of size 2\n "
return self.connected_encoder().message_space()
def input_space(self):
'\n Return the input space of ``self``.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = C.decoder()\n sage: D.input_space()\n Vector space of dimension 7 over Finite Field of size 2\n '
if hasattr(self, '_input_space'):
return self._input_space
else:
raise NotImplementedError('Decoder does not have an _input_space parameter')
@abstract_method(optional=True)
def decoding_radius(self, **kwargs):
'\n Return the maximal number of errors that ``self`` is able to correct.\n\n This is an abstract method and it should be implemented in subclasses.\n\n EXAMPLES::\n\n sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0], [1,0,0,1,1,0,0],\n ....: [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]])\n sage: C = LinearCode(G)\n sage: D = codes.decoders.LinearCodeSyndromeDecoder(C)\n sage: D.decoding_radius()\n 1\n '
raise NotImplementedError
|
class DecodingError(Exception):
'\n Special exception class to indicate an error during decoding.\n '
pass
|
def krawtchouk(n, q, l, x, check=True):
'\n Compute `K^{n,q}_l(x)`, the Krawtchouk (a.k.a. Kravchuk) polynomial.\n\n See :wikipedia:`Kravchuk_polynomials`.\n\n It is defined by the generating function\n\n .. MATH::\n\n (1+(q-1)z)^{n-x}(1-z)^x=\\sum_{l} K^{n,q}_l(x)z^l\n\n and is equal to\n\n .. MATH::\n\n K^{n,q}_l(x)=\\sum_{j=0}^l (-1)^j (q-1)^{(l-j)} \\binom{x}{j} \\binom{n-x}{l-j}.\n\n INPUT:\n\n - ``n, q, x`` -- arbitrary numbers\n\n - ``l`` -- a nonnegative integer\n\n - ``check`` -- check the input for correctness. ``True`` by\n default. Otherwise, pass it as it is. Use ``check=False`` at\n your own risk.\n\n .. SEEALSO::\n\n :class:`Symbolic Krawtchouk polynomials\n <sage.functions.orthogonal_polys.Func_krawtchouk>` `\\tilde{K}_l(x; n, p)`\n which are related by\n\n .. MATH::\n\n (-q)^l K^{n,q^{-1}}_l(x) = \\tilde{K}_l(x; n, 1-q).\n\n EXAMPLES::\n\n sage: codes.bounds.krawtchouk(24,2,5,4)\n 2224\n sage: codes.bounds.krawtchouk(12300,4,5,6)\n 567785569973042442072\n\n TESTS:\n\n Check that the bug reported on :trac:`19561` is fixed::\n\n sage: codes.bounds.krawtchouk(3,2,3,3)\n -1\n sage: codes.bounds.krawtchouk(int(3),int(2),int(3),int(3))\n -1\n sage: codes.bounds.krawtchouk(int(3),int(2),int(3),int(3),check=False)\n -1.0\n sage: codes.bounds.krawtchouk(24,2,5,4)\n 2224\n\n Other unusual inputs::\n\n sage: codes.bounds.krawtchouk(sqrt(5),1-I*sqrt(3),3,55.3).n()\n 211295.892797... + 1186.42763...*I\n sage: codes.bounds.krawtchouk(-5/2,7*I,3,-1/10)\n 480053/250*I - 357231/400\n sage: codes.bounds.krawtchouk(1,1,-1,1)\n Traceback (most recent call last):\n ...\n ValueError: l must be a nonnegative integer\n sage: codes.bounds.krawtchouk(1,1,3/2,1)\n Traceback (most recent call last):\n ...\n TypeError: no conversion of this rational to integer\n '
from sage.arith.misc import binomial
from sage.arith.srange import srange
if check:
from sage.rings.integer_ring import ZZ
l0 = ZZ(l)
if ((l0 != l) or (l0 < 0)):
raise ValueError('l must be a nonnegative integer')
l = l0
kraw = jth_term = (((q - 1) ** l) * binomial(n, l))
for j in srange(1, (l + 1)):
jth_term *= ((((- q) * ((l - j) + 1)) * ((x - j) + 1)) / (((q - 1) * j) * ((n - j) + 1)))
kraw += jth_term
return kraw
|
def eberlein(n, w, k, u, check=True):
'\n Compute `E^{w,n}_k(x)`, the Eberlein polynomial.\n\n See :wikipedia:`Eberlein_polynomials`.\n\n It is defined as:\n\n .. MATH::\n\n E^{w,n}_k(u)=\\sum_{j=0}^k (-1)^j \\binom{u}{j} \\binom{w-u}{k-j}\n \\binom{n-w-u}{k-j},\n\n INPUT:\n\n - ``w, k, x`` -- arbitrary numbers\n\n - ``n`` -- a nonnegative integer\n\n - ``check`` -- check the input for correctness. ``True`` by\n default. Otherwise, pass it as it is. Use ``check=False`` at\n your own risk.\n\n EXAMPLES::\n\n sage: codes.bounds.eberlein(24,10,2,6)\n -9\n\n TESTS:\n\n check normal inputs (various formats for arguments) ::\n\n sage: codes.bounds.eberlein(24,10,2,6)\n -9\n sage: codes.bounds.eberlein(int(24),int(10),int(2),int(6))\n -9\n sage: codes.bounds.eberlein(int(24),int(10),int(2),int(6),check=False)\n -9\n\n unusual inputs ::\n\n sage: codes.bounds.eberlein(-1,1,1,1)\n Traceback (most recent call last):\n ...\n ValueError: l must be a nonnegative integer\n sage: codes.bounds.eberlein(1,1,3/2,1)\n Traceback (most recent call last):\n ...\n TypeError: either m or x-m must be an integer\n '
from sage.arith.misc import binomial
from sage.arith.srange import srange
if ((2 * w) > n):
return eberlein(n, (n - w), k, u)
if check:
from sage.rings.integer_ring import ZZ
n0 = ZZ(n)
if ((n0 != n) or (n0 < 0)):
raise ValueError('l must be a nonnegative integer')
n = n0
return sum([(((((- 1) ** j) * binomial(u, j)) * binomial((w - u), (k - j))) * binomial(((n - w) - u), (k - j))) for j in srange((k + 1))])
|
def _delsarte_LP_building(n, d, d_star, q, isinteger, solver, maxc=0):
'\n LP builder - common for the two functions; not exported.\n\n EXAMPLES::\n\n sage: from sage.coding.delsarte_bounds import _delsarte_LP_building\n sage: _,p=_delsarte_LP_building(7, 3, 0, 2, False, "PPL")\n sage: p.show()\n Maximization:\n x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7\n Constraints:\n constraint_0: 1 <= x_0 <= 1\n constraint_1: 0 <= x_1 <= 0\n constraint_2: 0 <= x_2 <= 0\n constraint_3: -7 x_0 - 5 x_1 - 3 x_2 - x_3 + x_4 + 3 x_5 + 5 x_6 + 7 x_7 <= 0\n constraint_4: -7 x_0 - 5 x_1 - 3 x_2 - x_3 + x_4 + 3 x_5 + 5 x_6 + 7 x_7 <= 0\n ...\n constraint_16: - x_0 + x_1 - x_2 + x_3 - x_4 + x_5 - x_6 + x_7 <= 0\n Variables:\n x_0 is a continuous variable (min=0, max=+oo)\n ...\n x_7 is a continuous variable (min=0, max=+oo)\n '
from sage.numerical.mip import MixedIntegerLinearProgram
p = MixedIntegerLinearProgram(maximization=True, solver=solver)
A = p.new_variable(integer=isinteger, nonnegative=True)
p.set_objective(sum([A[r] for r in range((n + 1))]))
p.add_constraint((A[0] == 1))
for i in range(1, d):
p.add_constraint((A[i] == 0))
for j in range(1, (n + 1)):
rhs = sum([(krawtchouk(n, q, j, r, check=False) * A[r]) for r in range((n + 1))])
p.add_constraint((0 <= rhs))
if (j >= d_star):
p.add_constraint((0 <= rhs))
else:
p.add_constraint((0 == rhs))
if (maxc > 0):
p.add_constraint(sum([A[r] for r in range((n + 1))]), max=maxc)
return (A, p)
|
def _delsarte_cwc_LP_building(n, d, w, solver, isinteger):
'\n LP builder for Delsarte\'s LP for constant weight codes\n\n It is used in :func:`delsarte_bound_constant_weight_code`; not exported.\n\n INPUT:\n\n - ``n`` -- the code length\n\n - ``w`` -- the weight of the code\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to\n ``PPL``. It is arbitrary precision, thus there will be no\n rounding errors. With other solvers (see\n :class:`MixedIntegerLinearProgram` for the list), you are on\n your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver\n (ILP), rather that an LP solver. Can be very slow if set to\n ``True``.\n\n EXAMPLES::\n\n sage: from sage.coding.delsarte_bounds import _delsarte_cwc_LP_building\n sage: _,p=_delsarte_cwc_LP_building(17, 4, 3, "PPL", False)\n sage: p.show()\n Maximization:\n x_0 + x_1 + 1\n Constraints:\n constraint_0: -1 <= 4/21 x_0 - 3/14 x_1\n constraint_1: -1 <= -23/273 x_0 + 3/91 x_1\n constraint_2: -1 <= 1/91 x_0 - 1/364 x_1\n Variables:\n x_0 is a continuous variable (min=0, max=+oo)\n x_1 is a continuous variable (min=0, max=+oo)\n '
from sage.arith.misc import binomial
from sage.numerical.mip import MixedIntegerLinearProgram
p = MixedIntegerLinearProgram(maximization=True, solver=solver)
A = p.new_variable(integer=isinteger, nonnegative=True)
p.set_objective((sum([A[(2 * r)] for r in range((d // 2), (w + 1))]) + 1))
def _q(k, i):
mu_i = 1
v_i = (binomial(w, i) * binomial((n - w), i))
return ((mu_i * eberlein(n, w, i, k)) / v_i)
for k in range(1, (w + 1)):
p.add_constraint(sum([(A[(2 * i)] * _q(k, i)) for i in range((d // 2), (w + 1))]), min=(- 1))
return (A, p)
|
def delsarte_bound_constant_weight_code(n, d, w, return_data=False, solver='PPL', isinteger=False):
'\n Find the Delsarte bound on a constant weight code.\n\n Find the Delsarte bound on a constant weight code of weight ``w``, length\n ``n``, lower bound on minimal distance ``d``.\n\n INPUT:\n\n - ``n`` -- the code length\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``w`` -- the weight of the code\n\n - ``return_data`` -- if ``True``, return a triple\n ``(W,LP,bound)``, where ``W`` is a weights vector, and ``LP``\n the Delsarte upper bound LP; both of them are Sage LP data.\n ``W`` need not be a weight distribution of a code.\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to\n ``PPL``. It is arbitrary precision, thus there will be no\n rounding errors. With other solvers (see\n :class:`MixedIntegerLinearProgram` for the list), you are on\n your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver\n (ILP), rather that an LP solver. Can be very slow if set to\n ``True``.\n\n EXAMPLES:\n\n The bound on the size of codes of length 17, weight 3, and minimal distance 4::\n\n sage: codes.bounds.delsarte_bound_constant_weight_code(17, 4, 3)\n 45\n sage: a, p, val = codes.bounds.delsarte_bound_constant_weight_code(17, 4, 3, return_data=True)\n sage: [j for i,j in p.get_values(a).items()]\n [21, 70/3]\n\n The stricter bound (using ILP) on codes of length 17, weight 3, and minimal\n distance 4::\n\n sage: codes.bounds.delsarte_bound_constant_weight_code(17, 4, 3, isinteger=True)\n 43\n '
from sage.numerical.mip import MIPSolverException
if (d < 4):
raise ValueError('Violated constraint d>=4 for Binary Constant Weight Codes')
if ((d >= (2 * w)) or ((2 * w) > n)):
raise ValueError('Violated constraint d<2w<=n for Binary Constant Weight Codes')
if (d % 2):
d += 1
(A, p) = _delsarte_cwc_LP_building(n, d, w, solver, isinteger)
try:
bd = p.solve()
except MIPSolverException as exc:
print(f'Solver exception: {exc}')
return ((A, p, False) if return_data else False)
return ((A, p, bd) if return_data else int(bd))
|
def delsarte_bound_hamming_space(n, d, q, return_data=False, solver='PPL', isinteger=False):
"\n Find the Delsarte bound on codes in ``H_q^n`` of minimal distance ``d``\n\n Find the Delsarte bound [De1973]_ on the size of codes in\n the Hamming space ``H_q^n`` of minimal distance ``d``.\n\n INPUT:\n\n - ``n`` -- the code length\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``q`` -- the size of the alphabet\n\n - ``return_data`` -- if ``True``, return a triple\n ``(W,LP,bound)``, where ``W`` is a weights vector, and ``LP``\n the Delsarte upper bound LP; both of them are Sage LP data.\n ``W`` need not be a weight distribution of a code.\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to\n ``PPL``. It is arbitrary precision, thus there will be no\n rounding errors. With other solvers (see\n :class:`MixedIntegerLinearProgram` for the list), you are on\n your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver\n (ILP), rather that an LP solver. Can be very slow if set to\n ``True``.\n\n EXAMPLES:\n\n The bound on the size of the `\\GF{2}`-codes of length 11 and minimal distance 6::\n\n sage: codes.bounds.delsarte_bound_hamming_space(11, 6, 2)\n 12\n sage: a, p, val = codes.bounds.delsarte_bound_hamming_space(11, 6, 2, return_data=True)\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0]\n\n The bound on the size of the `\\GF{2}`-codes of length 24 and minimal distance\n 8, i.e. parameters of the extended binary Golay code::\n\n sage: a,p,x = codes.bounds.delsarte_bound_hamming_space(24,8,2,return_data=True)\n sage: x\n 4096\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 0, 0, 759, 0, 0, 0, 2576, 0, 0, 0, 759, 0, 0, 0, 0, 0, 0, 0, 1]\n\n The bound on the size of `\\GF{4}`-codes of length 11 and minimal distance 3::\n\n sage: codes.bounds.delsarte_bound_hamming_space(11,3,4)\n 327680/3\n\n An improvement of a known upper bound (150) from https://www.win.tue.nl/~aeb/codes/binary-1.html ::\n\n sage: a,p,x = codes.bounds.delsarte_bound_hamming_space(23,10,2,return_data=True,isinteger=True); x # long time\n 148\n sage: [j for i,j in p.get_values(a).items()] # long time\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 2, 0, 36, 0, 14, 0, 0, 0, 0, 0, 0, 0]\n\n Note that a usual LP, without integer variables, won't do the trick ::\n\n sage: codes.bounds.delsarte_bound_hamming_space(23,10,2).n(20)\n 151.86\n\n Such an input is invalid::\n\n sage: codes.bounds.delsarte_bound_hamming_space(11,3,-4)\n Solver exception: PPL : There is no feasible solution\n False\n "
from sage.numerical.mip import MIPSolverException
(A, p) = _delsarte_LP_building(n, d, 0, q, isinteger, solver)
try:
bd = p.solve()
except MIPSolverException as exc:
print(f'Solver exception: {exc}')
return ((A, p, False) if return_data else False)
return ((A, p, bd) if return_data else bd)
|
def delsarte_bound_additive_hamming_space(n, d, q, d_star=1, q_base=0, return_data=False, solver='PPL', isinteger=False):
"\n Find a modified Delsarte bound on additive codes in Hamming space `H_q^n` of minimal distance `d`.\n\n Find the Delsarte LP bound on ``F_{q_base}``-dimension of additive\n codes in Hamming space `H_q^n` of minimal distance ``d`` with\n minimal distance of the dual code at least ``d_star``. If\n ``q_base`` is set to non-zero, then ``q`` is a power of\n ``q_base``, and the code is, formally, linear over\n ``F_{q_base}``. Otherwise it is assumed that ``q_base==q``.\n\n INPUT:\n\n - ``n`` -- the code length\n\n - ``d`` -- the (lower bound on) minimal distance of the code\n\n - ``q`` -- the size of the alphabet\n\n - ``d_star`` -- the (lower bound on) minimal distance of the dual code;\n only makes sense for additive codes.\n\n - ``q_base`` -- if ``0``, the code is assumed to be linear. Otherwise,\n ``q=q_base^m`` and the code is linear over ``F_{q_base}``.\n\n - ``return_data`` -- if ``True``, return a triple ``(W,LP,bound)``,\n where ``W`` is a weights vector, and ``LP`` the Delsarte bound\n LP; both of them are Sage LP data. ``W`` need not be a weight\n distribution of a code, or, if ``isinteger==False``, even have\n integer entries.\n\n - ``solver`` -- the LP/ILP solver to be used. Defaults to ``'PPL'``. It is\n arbitrary precision, thus there will be no rounding errors. With\n other solvers (see :class:`MixedIntegerLinearProgram` for the\n list), you are on your own!\n\n - ``isinteger`` -- if ``True``, uses an integer programming solver (ILP),\n rather that an LP solver. Can be very slow if set to ``True``.\n\n EXAMPLES:\n\n The bound on dimension of linear `\\GF{2}`-codes of length 11 and minimal distance 6::\n\n sage: codes.bounds.delsarte_bound_additive_hamming_space(11, 6, 2)\n 3\n sage: a,p,val = codes.bounds.delsarte_bound_additive_hamming_space(\\\n 11, 6, 2, return_data=True)\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0]\n\n The bound on the dimension of linear `\\GF{4}`-codes of length 11 and minimal distance 3::\n\n sage: codes.bounds.delsarte_bound_additive_hamming_space(11,3,4)\n 8\n\n The bound on the `\\GF{2}`-dimension of additive `\\GF{4}`-codes of length 11 and minimal\n distance 3::\n\n sage: codes.bounds.delsarte_bound_additive_hamming_space(11,3,4,q_base=2)\n 16\n\n Such a ``d_star`` is not possible::\n\n sage: codes.bounds.delsarte_bound_additive_hamming_space(11,3,4,d_star=9)\n Solver exception: PPL : There is no feasible solution\n False\n\n TESTS::\n\n sage: a,p,x = codes.bounds.delsarte_bound_additive_hamming_space(\\\n 19,15,7,return_data=True,isinteger=True)\n sage: [j for i,j in p.get_values(a).items()]\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 307, 0, 0, 1, 34]\n sage: codes.bounds.delsarte_bound_additive_hamming_space(19,15,7,solver='glpk')\n 3\n sage: codes.bounds.delsarte_bound_additive_hamming_space(\\\n 19,15,7, isinteger=True, solver='glpk')\n 3\n "
from sage.numerical.mip import MIPSolverException
if (q_base == 0):
q_base = q
kk = 0
while ((q_base ** kk) < q):
kk += 1
if ((q_base ** kk) != q):
print('Wrong q_base=', q_base, ' for q=', q, kk)
return False
m = (kk * n)
bd = ((q ** n) + 1)
while ((q_base ** m) < bd):
(A, p) = _delsarte_LP_building(n, d, d_star, q, isinteger, solver, (q_base ** m))
try:
bd = p.solve()
except MIPSolverException as exc:
print('Solver exception:', exc)
return ((A, p, False) if return_data else False)
m = (- 1)
while ((q_base ** (m + 1)) < bd):
m += 1
if ((q_base ** (m + 1)) == bd):
m += 1
return ((A, p, m) if return_data else m)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.