code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
from __future__ import absolute_import import inspect import sys import six from sagemaker_training import mapping def matching_args(fn, dictionary): """Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None} args = functions.matching_args(train, dictionary) # {'channel_dirs': {}, 'model_dir': '/opt/ml/model'} train(**args) Args: fn (function): A function. dictionary (dict): The dictionary with the keys to compare against the function arguments. Returns: (dict) A dictionary with only matching arguments. """ arg_spec = getargspec(fn) if arg_spec.keywords: return dictionary return mapping.split_by_criteria(dictionary, arg_spec.args).included def getargspec(fn): # pylint: disable=inconsistent-return-statements """Get the names and default values of a function's arguments. Args: fn (function): A function. Returns: `inspect.ArgSpec`: A collections.namedtuple with the following attributes: * Args: args (list): A list of the argument names (it may contain nested lists). varargs (str): Name of the * argument or None. keywords (str): Names of the ** argument or None. defaults (tuple): An n-tuple of the default values of the last n arguments. """ full_arg_spec = inspect.getfullargspec(fn) return inspect.ArgSpec( full_arg_spec.args, full_arg_spec.varargs, full_arg_spec.varkw, full_arg_spec.defaults ) def error_wrapper(fn, error_class): """Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): Function to be wrapped. error_class (Exception): Error class to be re-raised. Returns: (object): Function wrapped in a try catch. """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: # pylint: disable=broad-except six.reraise(error_class, error_class(e), sys.exc_info()[2]) return wrapper
/sagemaker_training-4.7.0.tar.gz/sagemaker_training-4.7.0/src/sagemaker_training/functions.py
0.674694
0.373304
functions.py
pypi
from sage.misc.cachefunc import cached_method from sage.categories.category_singleton import Category_singleton from sage.categories.category_with_axiom import CategoryWithAxiom from sage.categories.sets_cat import Sets from sage.categories.homsets import HomsetsCategory from sage.rings.infinity import Infinity from sage.rings.integer import Integer class SimplicialSets(Category_singleton): r""" The category of simplicial sets. A simplicial set `X` is a collection of sets `X_i`, indexed by the non-negative integers, together with maps .. math:: d_i: X_n \to X_{n-1}, \quad 0 \leq i \leq n \quad \text{(face maps)} \\ s_j: X_n \to X_{n+1}, \quad 0 \leq j \leq n \quad \text{(degeneracy maps)} satisfying the *simplicial identities*: .. math:: d_i d_j &= d_{j-1} d_i \quad \text{if } i<j \\ d_i s_j &= s_{j-1} d_i \quad \text{if } i<j \\ d_j s_j &= 1 = d_{j+1} s_j \\ d_i s_j &= s_{j} d_{i-1} \quad \text{if } i>j+1 \\ s_i s_j &= s_{j+1} s_{i} \quad \text{if } i \leq j Morphisms are sequences of maps `f_i : X_i \to Y_i` which commute with the face and degeneracy maps. EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: C = SimplicialSets(); C Category of simplicial sets TESTS:: sage: TestSuite(C).run() """ @cached_method def super_categories(self): """ EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: SimplicialSets().super_categories() [Category of sets] """ return [Sets()] class ParentMethods: def is_finite(self): """ Return ``True`` if this simplicial set is finite, i.e., has a finite number of nondegenerate simplices. EXAMPLES:: sage: simplicial_sets.Torus().is_finite() True sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: simplicial_sets.ClassifyingSpace(C5).is_finite() False """ return SimplicialSets.Finite() in self.categories() def is_pointed(self): """ Return ``True`` if this simplicial set is pointed, i.e., has a base point. EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0) sage: w = AbstractSimplex(0) sage: e = AbstractSimplex(1) sage: X = SimplicialSet({e: (v, w)}) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: X.is_pointed() False sage: Y.is_pointed() True """ return SimplicialSets.Pointed() in self.categories() def set_base_point(self, point): """ Return a copy of this simplicial set in which the base point is set to ``point``. INPUT: - ``point`` -- a 0-simplex in this simplicial set EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='v_0') sage: w = AbstractSimplex(0, name='w_0') sage: e = AbstractSimplex(1) sage: X = SimplicialSet({e: (v, w)}) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: Y.base_point() w_0 sage: X_star = X.set_base_point(w) sage: X_star.base_point() w_0 sage: Y_star = Y.set_base_point(v) sage: Y_star.base_point() v_0 TESTS:: sage: X.set_base_point(e) Traceback (most recent call last): ... ValueError: the "point" is not a zero-simplex sage: pt = AbstractSimplex(0) sage: X.set_base_point(pt) Traceback (most recent call last): ... ValueError: the point is not a simplex in this simplicial set """ 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): r""" Return the identity morphism in `\operatorname{Hom}(S, S)`. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: Hom(T, T).identity() Simplicial set endomorphism of Torus Defn: Identity map """ from sage.topology.simplicial_set_morphism import SimplicialSetMorphism return SimplicialSetMorphism(domain=self.domain(), codomain=self.codomain(), identity=True) class Finite(CategoryWithAxiom): """ Category of finite simplicial sets. The objects are simplicial sets with finitely many non-degenerate simplices. """ pass class SubcategoryMethods: def Pointed(self): """ A simplicial set is *pointed* if it has a distinguished base point. EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: SimplicialSets().Pointed().Finite() Category of finite pointed simplicial sets sage: SimplicialSets().Finite().Pointed() Category of finite pointed simplicial sets """ return self._with_axiom("Pointed") class Pointed(CategoryWithAxiom): class ParentMethods: def base_point(self): """ Return this simplicial set's base point EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='*') sage: e = AbstractSimplex(1) sage: S1 = SimplicialSet({e: (v, v)}, base_point=v) sage: S1.is_pointed() True sage: S1.base_point() * """ return self._basepoint def base_point_map(self, domain=None): """ Return a map from a one-point space to this one, with image the base point. This raises an error if this simplicial set does not have a base point. INPUT: - ``domain`` -- optional, default ``None``. Use this to specify a particular one-point space as the domain. The default behavior is to use the :func:`sage.topology.simplicial_set.Point` function to use a standard one-point space. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: f = T.base_point_map(); f Simplicial set morphism: From: Point To: Torus Defn: Constant map at (v_0, v_0) sage: S3 = simplicial_sets.Sphere(3) sage: g = S3.base_point_map() sage: f.domain() == g.domain() True sage: RP3 = simplicial_sets.RealProjectiveSpace(3) sage: temp = simplicial_sets.Simplex(0) sage: pt = temp.set_base_point(temp.n_cells(0)[0]) sage: h = RP3.base_point_map(domain=pt) sage: f.domain() == h.domain() False sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: BC5 = simplicial_sets.ClassifyingSpace(C5) sage: BC5.base_point_map() Simplicial set morphism: From: Point To: Classifying space of Multiplicative Abelian group isomorphic to C5 Defn: Constant map at 1 """ from sage.topology.simplicial_set_examples import Point if domain is None: domain = Point() else: if 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): r""" Return the fundamental group of this pointed simplicial set. INPUT: - ``simplify`` (bool, optional ``True``) -- if ``False``, then return a presentation of the group in terms of generators and relations. If ``True``, the default, simplify as much as GAP is able to. Algorithm: we compute the edge-path group -- see Section 19 of [Kan1958]_ and :wikipedia:`Fundamental_group`. Choose a spanning tree for the connected component of the 1-skeleton containing the base point, and then the group's generators are given by the non-degenerate edges. There are two types of relations: `e=1` if `e` is in the spanning tree, and for every 2-simplex, if its faces are `e_0`, `e_1`, and `e_2`, then we impose the relation `e_0 e_1^{-1} e_2 = 1`, where we first set `e_i=1` if `e_i` is degenerate. EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: eight = S1.wedge(S1) sage: eight.fundamental_group() # free group on 2 generators Finitely presented group < e0, e1 | > The fundamental group of a disjoint union of course depends on the choice of base point:: sage: T = simplicial_sets.Torus() sage: K = simplicial_sets.KleinBottle() sage: X = T.disjoint_union(K) sage: X_0 = X.set_base_point(X.n_cells(0)[0]) sage: X_0.fundamental_group().is_abelian() True sage: X_1 = X.set_base_point(X.n_cells(0)[1]) sage: X_1.fundamental_group().is_abelian() False sage: RP3 = simplicial_sets.RealProjectiveSpace(3) sage: RP3.fundamental_group() Finitely presented group < e | e^2 > Compute the fundamental group of some classifying spaces:: sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: BC5 = C5.nerve() sage: BC5.fundamental_group() Finitely presented group < e0 | e0^5 > sage: Sigma3 = groups.permutation.Symmetric(3) sage: BSigma3 = Sigma3.nerve() sage: pi = BSigma3.fundamental_group(); pi Finitely presented group < e0, e1 | e0^2, e1^3, (e0*e1^-1)^2 > sage: pi.order() 6 sage: pi.is_abelian() False The sphere has a trivial fundamental group:: sage: S2 = simplicial_sets.Sphere(2) sage: S2.fundamental_group() Finitely presented group < | > """ # Import this here to prevent importing libgap upon startup. from sage.groups.free_group import FreeGroup skel = self.n_skeleton(2) graph = skel.graph() if not skel.is_connected(): graph = graph.subgraph(skel.base_point()) edges = [e[2] for e in graph.edges(sort=True)] spanning_tree = [e[2] for e in graph.min_spanning_tree()] gens = [e for e in edges if e not in spanning_tree] if not gens: return FreeGroup([]).quotient([]) gens_dict = dict(zip(gens, range(len(gens)))) FG = FreeGroup(len(gens), 'e') rels = [] for f in skel.n_cells(2): z = dict() for i, sigma in enumerate(skel.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: # sigma is not in the correct connected component. z[i] = FG.one() rels.append(z[0]*z[1].inverse()*z[2]) if simplify: return FG.quotient(rels).simplified() else: return FG.quotient(rels) def is_simply_connected(self): """ Return ``True`` if this pointed simplicial set is simply connected. .. WARNING:: Determining simple connectivity is not always possible, because it requires determining when a group, as given by generators and relations, is trivial. So this conceivably may give a false negative in some cases. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: T.is_simply_connected() False sage: T.suspension().is_simply_connected() True sage: simplicial_sets.KleinBottle().is_simply_connected() False sage: S2 = simplicial_sets.Sphere(2) sage: S3 = simplicial_sets.Sphere(3) sage: (S2.wedge(S3)).is_simply_connected() True sage: X = S2.disjoint_union(S3) sage: X = X.set_base_point(X.n_cells(0)[0]) sage: X.is_simply_connected() False sage: C3 = groups.misc.MultiplicativeAbelian([3]) sage: BC3 = simplicial_sets.ClassifyingSpace(C3) sage: BC3.is_simply_connected() False """ 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): # I don't know of any simplicial sets for which the # code reaches this point, but there are certainly # groups for which these errors are raised. 'IsTrivial' # works for all of the examples I've seen, though. raise ValueError('unable to determine if the fundamental ' 'group is trivial') def connectivity(self, max_dim=None): """ Return the connectivity of this pointed simplicial set. INPUT: - ``max_dim`` -- specify a maximum dimension through which to check. This is required if this simplicial set is simply connected and not finite. The dimension of the first nonzero homotopy group. If simply connected, this is the same as the dimension of the first nonzero homology group. .. WARNING:: See the warning for the :meth:`is_simply_connected` method. The connectivity of a contractible space is ``+Infinity``. EXAMPLES:: sage: simplicial_sets.Sphere(3).connectivity() 2 sage: simplicial_sets.Sphere(0).connectivity() -1 sage: K = simplicial_sets.Simplex(4) sage: K = K.set_base_point(K.n_cells(0)[0]) sage: K.connectivity() +Infinity sage: X = simplicial_sets.Torus().suspension(2) sage: X.connectivity() 2 sage: C2 = groups.misc.MultiplicativeAbelian([2]) sage: BC2 = simplicial_sets.ClassifyingSpace(C2) sage: BC2.connectivity() 0 """ 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: # Note: at the moment, this will never be reached, # because our only examples (so far) of infinite # simplicial sets are not simply connected. 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): """ Return a copy of this simplicial set in which the base point has been forgotten. EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='v_0') sage: w = AbstractSimplex(0, name='w_0') sage: e = AbstractSimplex(1) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: Y.is_pointed() True sage: Y.base_point() w_0 sage: Z = Y.unset_base_point() sage: Z.is_pointed() False """ from sage.topology.simplicial_set import SimplicialSet return SimplicialSet(self.face_data()) def fat_wedge(self, n): """ Return the `n`-th fat wedge of this pointed simplicial set. This is the subcomplex of the `n`-fold product `X^n` consisting of those points in which at least one factor is the base point. Thus when `n=2`, this is the wedge of the simplicial set with itself, but when `n` is larger, the fat wedge is larger than the `n`-fold wedge. EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: S1.fat_wedge(0) Point sage: S1.fat_wedge(1) S^1 sage: S1.fat_wedge(2).fundamental_group() Finitely presented group < e0, e1 | > sage: S1.fat_wedge(4).homology() {0: 0, 1: Z x Z x Z x Z, 2: Z^6, 3: Z x Z x Z x Z} """ 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): """ Return the smash product of this simplicial set with ``others``. INPUT: - ``others`` -- one or several simplicial sets EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: RP2 = simplicial_sets.RealProjectiveSpace(2) sage: X = S1.smash_product(RP2) sage: X.homology(base_ring=GF(2)) {0: Vector space of dimension 0 over Finite Field of size 2, 1: Vector space of dimension 0 over Finite Field of size 2, 2: Vector space of dimension 1 over Finite Field of size 2, 3: Vector space of dimension 1 over Finite Field of size 2} sage: T = S1.product(S1) sage: X = T.smash_product(S1) sage: X.homology(reduced=False) {0: Z, 1: 0, 2: Z x Z, 3: Z} """ from sage.topology.simplicial_set_constructions import SmashProductOfSimplicialSets_finite return SmashProductOfSimplicialSets_finite((self,) + others)
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/simplicial_sets.py
0.90287
0.627666
simplicial_sets.py
pypi
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring from sage.categories.graded_modules import GradedModulesCategory class LambdaBracketAlgebrasWithBasis(CategoryWithAxiom_over_base_ring): """ The category of Lambda bracket algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis() Category of Lie conformal algebras with basis over Algebraic Field """ class ElementMethods: def index(self): """ The index of this basis element. EXAMPLES:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: V.inject_variables() Defining L, G, C sage: G.T(3).index() ('G', 3) sage: v = V.an_element(); v L + G + C sage: v.index() Traceback (most recent call last): ... ValueError: index can only be computed for monomials, got L + G + C """ if self.is_zero(): return None if not self.is_monomial(): raise ValueError("index can only be computed for " "monomials, got {}".format(self)) return next(iter(self.monomial_coefficients())) class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring): """ The category of finitely generated lambda bracket algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar) sage: C.WithBasis().FinitelyGenerated() Category of finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis() True """ class Graded(GradedModulesCategory): """ The category of H-graded finitely generated lambda bracket algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field """ class ParentMethods: def degree_on_basis(self, m): r""" Return the degree of the basis element indexed by ``m`` in ``self``. EXAMPLES:: sage: V = lie_conformal_algebras.Virasoro(QQ) sage: V.degree_on_basis(('L',2)) 4 """ if m[0] in self._central_elements: return 0 return self._weights[self._index_to_pos[m[0]]] + m[1]
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/lambda_bracket_algebras_with_basis.py
0.807043
0.406067
lambda_bracket_algebras_with_basis.py
pypi
r""" Sage categories quickref - ``sage.categories.primer?`` a primer on Elements, Parents, and Categories - ``sage.categories.tutorial?`` a tutorial on Elements, Parents, and Categories - ``Category?`` technical background on categories - ``Sets()``, ``Semigroups()``, ``Algebras(QQ)`` some categories - ``SemiGroups().example()??`` sample implementation of a semigroup - ``Hom(A, B)``, ``End(A, Algebras())`` homomorphisms sets - ``tensor``, ``cartesian_product`` functorial constructions Module layout: - :mod:`sage.categories.basic` the basic categories - :mod:`sage.categories.all` all categories - :mod:`sage.categories.semigroups` the ``Semigroups()`` category - :mod:`sage.categories.examples.semigroups` the example of ``Semigroups()`` - :mod:`sage.categories.homset` morphisms, ... - :mod:`sage.categories.map` - :mod:`sage.categories.morphism` - :mod:`sage.categories.functors` - :mod:`sage.categories.cartesian_product` functorial constructions - :mod:`sage.categories.tensor` - :mod:`sage.categories.dual` """ # install the docstring of this module to the containing package from sage.misc.namespace_package import install_doc install_doc(__package__, __doc__) from . import primer from sage.misc.lazy_import import lazy_import from .all__sagemath_objects import * from .basic import * from .chain_complexes import ChainComplexes, HomologyFunctor from .simplicial_complexes import SimplicialComplexes from .tensor import tensor from .signed_tensor import tensor_signed from .g_sets import GSets from .pointed_sets import PointedSets from .sets_with_grading import SetsWithGrading from .groupoid import Groupoid from .permutation_groups import PermutationGroups # enumerated sets from .finite_sets import FiniteSets from .enumerated_sets import EnumeratedSets from .finite_enumerated_sets import FiniteEnumeratedSets from .infinite_enumerated_sets import InfiniteEnumeratedSets # posets from .posets import Posets from .finite_posets import FinitePosets from .lattice_posets import LatticePosets from .finite_lattice_posets import FiniteLatticePosets # finite groups/... from .finite_semigroups import FiniteSemigroups from .finite_monoids import FiniteMonoids from .finite_groups import FiniteGroups from .finite_permutation_groups import FinitePermutationGroups # fields from .number_fields import NumberFields from .function_fields import FunctionFields # modules from .left_modules import LeftModules from .right_modules import RightModules from .bimodules import Bimodules from .modules import Modules RingModules = Modules from .vector_spaces import VectorSpaces # (hopf) algebra structures from .algebras import Algebras from .commutative_algebras import CommutativeAlgebras from .coalgebras import Coalgebras from .bialgebras import Bialgebras from .hopf_algebras import HopfAlgebras from .lie_algebras import LieAlgebras # specific algebras from .monoid_algebras import MonoidAlgebras from .group_algebras import GroupAlgebras from .matrix_algebras import MatrixAlgebras # ideals from .ring_ideals import RingIdeals Ideals = RingIdeals from .commutative_ring_ideals import CommutativeRingIdeals from .algebra_modules import AlgebraModules from .algebra_ideals import AlgebraIdeals from .commutative_algebra_ideals import CommutativeAlgebraIdeals # schemes and varieties from .modular_abelian_varieties import ModularAbelianVarieties from .schemes import Schemes # * with basis from .modules_with_basis import ModulesWithBasis FreeModules = ModulesWithBasis from .hecke_modules import HeckeModules from .algebras_with_basis import AlgebrasWithBasis from .coalgebras_with_basis import CoalgebrasWithBasis from .bialgebras_with_basis import BialgebrasWithBasis from .hopf_algebras_with_basis import HopfAlgebrasWithBasis # finite dimensional * with basis from .finite_dimensional_modules_with_basis import FiniteDimensionalModulesWithBasis from .finite_dimensional_algebras_with_basis import FiniteDimensionalAlgebrasWithBasis from .finite_dimensional_coalgebras_with_basis import FiniteDimensionalCoalgebrasWithBasis from .finite_dimensional_bialgebras_with_basis import FiniteDimensionalBialgebrasWithBasis from .finite_dimensional_hopf_algebras_with_basis import FiniteDimensionalHopfAlgebrasWithBasis # graded * from .graded_modules import GradedModules from .graded_algebras import GradedAlgebras from .graded_coalgebras import GradedCoalgebras from .graded_bialgebras import GradedBialgebras from .graded_hopf_algebras import GradedHopfAlgebras # graded * with basis from .graded_modules_with_basis import GradedModulesWithBasis from .graded_algebras_with_basis import GradedAlgebrasWithBasis from .graded_coalgebras_with_basis import GradedCoalgebrasWithBasis from .graded_bialgebras_with_basis import GradedBialgebrasWithBasis from .graded_hopf_algebras_with_basis import GradedHopfAlgebrasWithBasis # Coxeter groups from .coxeter_groups import CoxeterGroups lazy_import('sage.categories.finite_coxeter_groups', 'FiniteCoxeterGroups') from .weyl_groups import WeylGroups from .finite_weyl_groups import FiniteWeylGroups from .affine_weyl_groups import AffineWeylGroups # crystal bases from .crystals import Crystals from .highest_weight_crystals import HighestWeightCrystals from .regular_crystals import RegularCrystals from .finite_crystals import FiniteCrystals from .classical_crystals import ClassicalCrystals # polyhedra lazy_import('sage.categories.polyhedra', 'PolyhedralSets') # lie conformal algebras lazy_import('sage.categories.lie_conformal_algebras', 'LieConformalAlgebras')
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/all.py
0.839701
0.540318
all.py
pypi
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring from sage.categories.graded_lie_conformal_algebras import GradedLieConformalAlgebrasCategory from sage.categories.graded_modules import GradedModulesCategory from sage.categories.super_modules import SuperModulesCategory class LieConformalAlgebrasWithBasis(CategoryWithAxiom_over_base_ring): """ The category of Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis() Category of Lie conformal algebras with basis over Algebraic Field """ class Super(SuperModulesCategory): """ The category of super Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(AA).WithBasis().Super() Category of super Lie conformal algebras with basis over Algebraic Real Field """ class ParentMethods: def _even_odd_on_basis(self, m): """ Return the parity of the basis element indexed by ``m``. OUTPUT: ``0`` if ``m`` is for an even element or ``1`` if ``m`` is for an odd element. EXAMPLES:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: B = V._indices sage: V._even_odd_on_basis(B(('G',1))) 1 """ return self._parity[self.monomial((m[0],0))] class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded super Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().Super().Graded() Category of H-graded super Lie conformal algebras with basis over Algebraic Field """ class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().Graded() Category of H-graded Lie conformal algebras with basis over Algebraic Field """ class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring): """ The category of finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar) sage: C.WithBasis().FinitelyGenerated() Category of finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis() True """ class Super(SuperModulesCategory): """ The category of super finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(AA).WithBasis().FinitelyGenerated().Super() Category of super finitely generated Lie conformal algebras with basis over Algebraic Real Field """ class Graded(GradedModulesCategory): """ The category of H-graded super finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() sage: C.Graded().Super() Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.Graded().Super() is C.Super().Graded() True """ def _repr_object_names(self): """ The names of the objects of ``self``. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() sage: C.Super().Graded() Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field """ return "H-graded {}".format(self.base_category()._repr_object_names()) class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field """
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/lie_conformal_algebras_with_basis.py
0.845942
0.462594
lie_conformal_algebras_with_basis.py
pypi
from sage.misc.abstract_method import abstract_method from sage.misc.cachefunc import cached_method from sage.categories.category_singleton import Category_singleton from sage.categories.category_with_axiom import CategoryWithAxiom from sage.categories.simplicial_complexes import SimplicialComplexes from sage.categories.sets_cat import Sets class Graphs(Category_singleton): r""" The category of graphs. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs(); C Category of graphs TESTS:: sage: TestSuite(C).run() """ @cached_method def super_categories(self): """ EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: Graphs().super_categories() [Category of simplicial complexes] """ return [SimplicialComplexes()] class ParentMethods: @abstract_method def vertices(self): """ Return the vertices of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.vertices() [0, 1, 2, 3, 4] """ @abstract_method def edges(self): """ Return the edges of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.edges() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ def dimension(self): """ Return the dimension of ``self`` as a CW complex. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.dimension() 1 """ if self.edges(): return 1 return 0 def facets(self): """ Return the facets of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.facets() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return self.edges() def faces(self): """ Return the faces of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: sorted(C.faces(), key=lambda x: (x.dimension(), x.value)) [0, 1, 2, 3, 4, (0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return set(self.edges()).union(self.vertices()) class Connected(CategoryWithAxiom): """ The category of connected graphs. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().Connected() sage: TestSuite(C).run() """ def extra_super_categories(self): """ Return the extra super categories of ``self``. A connected graph is also a metric space. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: Graphs().Connected().super_categories() # indirect doctest [Category of connected topological spaces, Category of connected simplicial complexes, Category of graphs, Category of metric spaces] """ return [Sets().Metric()]
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/graphs.py
0.920683
0.562026
graphs.py
pypi
r""" Coxeter Group Algebras """ import functools from sage.misc.cachefunc import cached_method from sage.categories.algebra_functor import AlgebrasCategory class CoxeterGroupAlgebras(AlgebrasCategory): class ParentMethods: def demazure_lusztig_operator_on_basis(self, w, i, q1, q2, side="right"): r""" Return the result of applying the `i`-th Demazure Lusztig operator on ``w``. INPUT: - ``w`` -- an element of the Coxeter group - ``i`` -- an element of the index set - ``q1,q2`` -- two elements of the ground ring - ``bar`` -- a boolean (default ``False``) See :meth:`demazure_lusztig_operators` for details. EXAMPLES:: sage: W = WeylGroup(["B",3]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'] sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: w = W.an_element() sage: KW.demazure_lusztig_operator_on_basis(w, 0, q1, q2) (-q2)*323123 + (q1+q2)*123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, q1, q2) q1*1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, q1, q2) q1*1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, q1, q2) (q1+q2)*123 + (-q2)*12 At `q_1=1` and `q_2=0` we recover the action of the isobaric divided differences `\pi_i`:: sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, 0) 123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, 0) 1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, 0) 1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, 0) 123 At `q_1=1` and `q_2=-1` we recover the action of the simple reflection `s_i`:: sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, -1) 323123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, -1) 1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, -1) 1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, -1) 12 """ return (q1+q2) * self.monomial(w.apply_simple_projection(i,side=side)) - self.term(w.apply_simple_reflection(i, side=side), q2) def demazure_lusztig_operators(self, q1, q2, side="right", affine=True): r""" Return the Demazure Lusztig operators acting on ``self``. INPUT: - ``q1,q2`` -- two elements of the ground ring `K` - ``side`` -- ``"left"`` or ``"right"`` (default: ``"right"``); which side to act upon - ``affine`` -- a boolean (default: ``True``) The Demazure-Lusztig operator `T_i` is the linear map `R \to R` obtained by interpolating between the simple projection `\pi_i` (see :meth:`CoxeterGroups.ElementMethods.simple_projection`) and the simple reflection `s_i` so that `T_i` has eigenvalues `q_1` and `q_2`: .. MATH:: (q_1 + q_2) \pi_i - q_2 s_i. The Demazure-Lusztig operators give the usual representation of the operators `T_i` of the `q_1,q_2` Hecke algebra associated to the Coxeter group. For a finite Coxeter group, and if ``affine=True``, the Demazure-Lusztig operators `T_1,\dots,T_n` are completed by `T_0` to implement the level `0` action of the affine Hecke algebra. EXAMPLES:: sage: W = WeylGroup(["B",3]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'] sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: T = KW.demazure_lusztig_operators(q1, q2, affine=True) sage: x = KW.monomial(W.an_element()); x 123 sage: T[0](x) (-q2)*323123 + (q1+q2)*123 sage: T[1](x) q1*1231 sage: T[2](x) q1*1232 sage: T[3](x) (q1+q2)*123 + (-q2)*12 sage: T._test_relations() .. NOTE:: For a finite Weyl group `W`, the level 0 action of the affine Weyl group `\tilde W` only depends on the Coxeter diagram of the affinization, not its Dynkin diagram. Hence it is possible to explore all cases using only untwisted affinizations. """ from sage.combinat.root_system.hecke_algebra_representation import HeckeAlgebraRepresentation W = self.basis().keys() cartan_type = W.cartan_type() if affine and cartan_type.is_finite(): cartan_type = cartan_type.affine() T_on_basis = functools.partial(self.demazure_lusztig_operator_on_basis, q1=q1, q2=q2, side=side) return HeckeAlgebraRepresentation(self, T_on_basis, cartan_type, q1, q2) @cached_method def demazure_lusztig_eigenvectors(self, q1, q2): r""" Return the family of eigenvectors for the Cherednik operators. INPUT: - ``self`` -- a finite Coxeter group `W` - ``q1,q2`` -- two elements of the ground ring `K` The affine Hecke algebra `H_{q_1,q_2}(\tilde W)` acts on the group algebra of `W` through the Demazure-Lusztig operators `T_i`. Its Cherednik operators `Y^\lambda` can be simultaneously diagonalized as long as `q_1/q_2` is not a small root of unity [HST2008]_. This method returns the family of joint eigenvectors, indexed by `W`. .. SEEALSO:: - :meth:`demazure_lusztig_operators` - :class:`sage.combinat.root_system.hecke_algebra_representation.CherednikOperatorsEigenvectors` EXAMPLES:: sage: W = WeylGroup(["B",2]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'].fraction_field() sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: E = KW.demazure_lusztig_eigenvectors(q1,q2) sage: E.keys() Weyl Group of type ['B', 2] (as a matrix group acting on the ambient space) sage: w = W.an_element() sage: E[w] (q2/(-q1+q2))*2121 + ((-q2)/(-q1+q2))*121 - 212 + 12 """ W = self.basis().keys() if not W.cartan_type().is_finite(): raise ValueError("the Demazure-Lusztig eigenvectors are only defined for finite Coxeter groups") result = self.demazure_lusztig_operators(q1, q2, affine=True).Y_eigenvectors() w0 = W.long_element() result.affine_lift = w0._mul_ result.affine_retract = w0._mul_ return result
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/coxeter_group_algebras.py
0.910212
0.508605
coxeter_group_algebras.py
pypi
from sage.categories.graded_modules import GradedModulesCategory from sage.categories.super_modules import SuperModulesCategory from sage.misc.abstract_method import abstract_method from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras class SuperLieConformalAlgebras(SuperModulesCategory): r""" The category of super Lie conformal algebras. EXAMPLES:: sage: LieConformalAlgebras(AA).Super() Category of super Lie conformal algebras over Algebraic Real Field Notice that we can force to have a *purely even* super Lie conformal algebra:: sage: bosondict = {('a','a'):{1:{('K',0):1}}} sage: R = LieConformalAlgebra(QQ,bosondict,names=('a',), ....: central_elements=('K',), super=True) sage: [g.is_even_odd() for g in R.gens()] [0, 0] """ def extra_super_categories(self): """ The extra super categories of ``self``. EXAMPLES:: sage: LieConformalAlgebras(QQ).Super().super_categories() [Category of super modules over Rational Field, Category of Lambda bracket algebras over Rational Field] """ return [LambdaBracketAlgebras(self.base_ring())] def example(self): """ An example parent in this category. EXAMPLES:: sage: LieConformalAlgebras(QQ).Super().example() The Neveu-Schwarz super Lie conformal algebra over Rational Field """ 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): """ Test the Jacobi axiom of this super Lie conformal algebra. INPUT: - ``options`` -- any keyword arguments acceptde by :meth:`_tester` EXAMPLES: By default, this method tests only the elements returned by ``self.some_elements()``:: sage: V = lie_conformal_algebras.Affine(QQ, 'B2') sage: V._test_jacobi() # long time (6 seconds) It works for super Lie conformal algebras too:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: V._test_jacobi() We can use specific elements by passing the ``elements`` keyword argument:: sage: V = lie_conformal_algebras.Affine(QQ, 'A1', names=('e', 'h', 'f')) sage: V.inject_variables() Defining e, h, f, K sage: V._test_jacobi(elements=(e, 2*f+h, 3*h)) TESTS:: sage: wrongdict = {('a', 'a'): {0: {('b', 0): 1}}, ('b', 'a'): {0: {('a', 0): 1}}} sage: V = LieConformalAlgebra(QQ, wrongdict, names=('a', 'b'), parity=(1, 0)) sage: V._test_jacobi() Traceback (most recent call last): ... AssertionError: {(0, 0): -3*a} != {} - {(0, 0): -3*a} + {} """ tester = self._tester(**options) S = tester.some_elements() # Try our best to avoid non-homogeneous 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): """ Return ``0`` if this element is *even* and ``1`` if it is *odd*. EXAMPLES:: sage: R = lie_conformal_algebras.NeveuSchwarz(QQ); sage: R.inject_variables() Defining L, G, C sage: G.is_even_odd() 1 """ class Graded(GradedModulesCategory): """ The category of H-graded super Lie conformal algebras. EXAMPLES:: sage: LieConformalAlgebras(AA).Super().Graded() Category of H-graded super Lie conformal algebras over Algebraic Real Field """ def _repr_object_names(self): """ The names of the objects of this category. EXAMPLES:: sage: LieConformalAlgebras(QQbar).Graded() Category of H-graded Lie conformal algebras over Algebraic Field """ return "H-graded {}".format(self.base_category()._repr_object_names())
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/super_lie_conformal_algebras.py
0.777553
0.36625
super_lie_conformal_algebras.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.graphs import Graphs class Cycle(UniqueRepresentation, Parent): r""" An example of a graph: the cycle of length `n`. This class illustrates a minimal implementation of a graph. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example(); C An example of a graph: the 5-cycle sage: C.category() Category of graphs We conclude by running systematic tests on this graph:: sage: TestSuite(C).run() """ def __init__(self, n=5): r""" EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example(6); C An example of a graph: the 6-cycle TESTS:: sage: TestSuite(C).run() """ self._n = n Parent.__init__(self, category=Graphs()) def _repr_(self): r""" TESTS:: sage: from sage.categories.graphs import Graphs sage: Graphs().example() An example of a graph: the 5-cycle """ return "An example of a graph: the {}-cycle".format(self._n) def an_element(self): r""" Return an element of the graph, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.an_element() 0 """ return self(0) def vertices(self): """ Return the vertices of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.vertices() [0, 1, 2, 3, 4] """ return [self(i) for i in range(self._n)] def edges(self): """ Return the edges of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.edges() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return [self( (i, (i+1) % self._n) ) for i in range(self._n)] class Element(ElementWrapper): def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: e = C.edges()[0] sage: e.dimension() 2 sage: v = C.vertices()[0] sage: v.dimension() 1 """ if isinstance(self.value, tuple): return 2 return 1 Example = Cycle
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/graphs.py
0.935328
0.674771
graphs.py
pypi
r""" Example of a set with grading """ from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.sets_with_grading import SetsWithGrading from sage.rings.integer_ring import IntegerRing from sage.sets.finite_enumerated_set import FiniteEnumeratedSet class NonNegativeIntegers(UniqueRepresentation, Parent): r""" Non negative integers graded by themselves. EXAMPLES:: sage: E = SetsWithGrading().example(); E Non negative integers sage: E in Sets().Infinite() True sage: E.graded_component(0) {0} sage: E.graded_component(100) {100} """ def __init__(self): r""" TESTS:: sage: TestSuite(SetsWithGrading().example()).run() """ Parent.__init__(self, category=SetsWithGrading().Infinite(), facade=IntegerRing()) def an_element(self): r""" Return 0. EXAMPLES:: sage: SetsWithGrading().example().an_element() 0 """ return 0 def _repr_(self): r""" TESTS:: sage: SetsWithGrading().example() # indirect example Non negative integers """ return "Non negative integers" def graded_component(self, grade): r""" Return the component with grade ``grade``. EXAMPLES:: sage: N = SetsWithGrading().example() sage: N.graded_component(65) {65} """ return FiniteEnumeratedSet([grade]) def grading(self, elt): r""" Return the grade of ``elt``. EXAMPLES:: sage: N = SetsWithGrading().example() sage: N.grading(10) 10 """ return elt def generating_series(self, var='z'): r""" Return `1 / (1-z)`. EXAMPLES:: sage: N = SetsWithGrading().example(); N Non negative integers sage: f = N.generating_series(); f 1/(-z + 1) sage: LaurentSeriesRing(ZZ,'z')(f) 1 + z + z^2 + z^3 + z^4 + z^5 + z^6 + z^7 + z^8 + z^9 + z^10 + z^11 + z^12 + z^13 + z^14 + z^15 + z^16 + z^17 + z^18 + z^19 + O(z^20) """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.integer import Integer R = PolynomialRing(IntegerRing(), var) z = R.gen() return Integer(1) / (Integer(1) - z) Example = NonNegativeIntegers
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/sets_with_grading.py
0.938131
0.656383
sets_with_grading.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.all import Posets from sage.structure.element_wrapper import ElementWrapper from sage.sets.set import Set, Set_object_enumerated from sage.sets.positive_integers import PositiveIntegers class FiniteSetsOrderedByInclusion(UniqueRepresentation, Parent): r""" An example of a poset: finite sets ordered by inclusion This class provides a minimal implementation of a poset EXAMPLES:: sage: P = Posets().example(); P An example of a poset: sets ordered by inclusion We conclude by running systematic tests on this poset:: sage: TestSuite(P).run(verbose = True) running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self): r""" EXAMPLES:: sage: P = Posets().example(); P An example of a poset: sets ordered by inclusion sage: P.category() Category of posets sage: type(P) <class 'sage.categories.examples.posets.FiniteSetsOrderedByInclusion_with_category'> sage: TestSuite(P).run() """ Parent.__init__(self, category=Posets()) def _repr_(self): r""" TESTS:: sage: S = Posets().example() sage: S._repr_() 'An example of a poset: sets ordered by inclusion' """ return "An example of a poset: sets ordered by inclusion" def le(self, x, y): r""" Returns whether `x` is a subset of `y` EXAMPLES:: sage: P = Posets().example() sage: P.le( P(Set([1,3])), P(Set([1,2,3])) ) True sage: P.le( P(Set([1,3])), P(Set([1,3])) ) True sage: P.le( P(Set([1,2])), P(Set([1,3])) ) False """ return x.value.issubset(y.value) def an_element(self): r""" Returns an element of this poset EXAMPLES:: sage: B = Posets().example() sage: B.an_element() {1, 4, 6} """ return self(Set([1,4,6])) class Element(ElementWrapper): wrapped_class = Set_object_enumerated class PositiveIntegersOrderedByDivisibilityFacade(UniqueRepresentation, Parent): r""" An example of a facade poset: the positive integers ordered by divisibility This class provides a minimal implementation of a facade poset EXAMPLES:: sage: P = Posets().example("facade"); P An example of a facade poset: the positive integers ordered by divisibility sage: P(5) 5 sage: P(0) Traceback (most recent call last): ... ValueError: Can't coerce `0` in any parent `An example of a facade poset: the positive integers ordered by divisibility` is a facade for sage: 3 in P True sage: 0 in P False """ element_class = type(Set([])) def __init__(self): r""" EXAMPLES:: sage: P = Posets().example("facade"); P An example of a facade poset: the positive integers ordered by divisibility sage: P.category() Category of facade posets sage: type(P) <class 'sage.categories.examples.posets.PositiveIntegersOrderedByDivisibilityFacade_with_category'> sage: TestSuite(P).run() """ Parent.__init__(self, facade=(PositiveIntegers(),), category=Posets()) def _repr_(self): r""" TESTS:: sage: S = Posets().example("facade") sage: S._repr_() 'An example of a facade poset: the positive integers ordered by divisibility' """ return "An example of a facade poset: the positive integers ordered by divisibility" def le(self, x, y): r""" Returns whether `x` is divisible by `y` EXAMPLES:: sage: P = Posets().example("facade") sage: P.le(3, 6) True sage: P.le(3, 3) True sage: P.le(3, 7) False """ return x.divides(y)
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/posets.py
0.934739
0.481271
posets.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.manifolds import Manifolds class Plane(UniqueRepresentation, Parent): r""" An example of a manifold: the `n`-dimensional plane. This class illustrates a minimal implementation of a manifold. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example(); M An example of a Rational Field manifold: the 3-dimensional plane sage: M.category() Category of manifolds over Rational Field We conclude by running systematic tests on this manifold:: sage: TestSuite(M).run() """ def __init__(self, n=3, base_ring=None): r""" EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example(6); M An example of a Rational Field manifold: the 6-dimensional plane TESTS:: sage: TestSuite(M).run() """ self._n = n Parent.__init__(self, base=base_ring, category=Manifolds(base_ring)) def _repr_(self): r""" TESTS:: sage: from sage.categories.manifolds import Manifolds sage: Manifolds(QQ).example() An example of a Rational Field manifold: the 3-dimensional plane """ return "An example of a {} manifold: the {}-dimensional plane".format( self.base_ring(), self._n) def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example() sage: M.dimension() 3 """ return self._n def an_element(self): r""" Return an element of the manifold, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example() sage: M.an_element() (0, 0, 0) """ zero = self.base_ring().zero() return self(tuple([zero]*self._n)) Element = ElementWrapper Example = Plane
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/manifolds.py
0.926748
0.512937
manifolds.py
pypi
from sage.misc.cachefunc import cached_method from sage.structure.parent import Parent from sage.categories.all import CommutativeAdditiveMonoids from .commutative_additive_semigroups import FreeCommutativeAdditiveSemigroup class FreeCommutativeAdditiveMonoid(FreeCommutativeAdditiveSemigroup): r""" An example of a commutative additive monoid: the free commutative monoid This class illustrates a minimal implementation of a commutative monoid. EXAMPLES:: sage: S = CommutativeAdditiveMonoids().example(); S An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd') sage: S.category() Category of commutative additive monoids This is the free semigroup generated by:: sage: S.additive_semigroup_generators() Family (a, b, c, d) with product rule given by `a \times b = a` for all `a, b`:: sage: (a,b,c,d) = S.additive_semigroup_generators() We conclude by running systematic tests on this commutative monoid:: sage: TestSuite(S).run(verbose = True) running ._test_additive_associativity() . . . pass running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_nonzero_equal() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass running ._test_zero() . . . pass """ def __init__(self, alphabet=('a','b','c','d')): r""" The free commutative monoid INPUT: - ``alphabet`` -- a tuple of strings: the generators of the monoid EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')); M An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c') TESTS:: sage: TestSuite(M).run() """ self.alphabet = alphabet Parent.__init__(self, category=CommutativeAdditiveMonoids()) def _repr_(self): r""" TESTS:: sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')) sage: M._repr_() "An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c')" """ return "An example of a commutative monoid: the free commutative monoid generated by %s"%(self.alphabet,) @cached_method def zero(self): r""" Returns the zero of this additive monoid, as per :meth:`CommutativeAdditiveMonoids.ParentMethods.zero`. EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example(); M An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd') sage: M.zero() 0 """ return self(()) class Element(FreeCommutativeAdditiveSemigroup.Element): def __bool__(self) -> bool: """ Check if ``self`` is not the zero of the monoid EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example() sage: bool(M.zero()) False sage: [bool(m) for m in M.additive_semigroup_generators()] [True, True, True, True] """ return any(x for x in self.value.values()) Example = FreeCommutativeAdditiveMonoid
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/commutative_additive_monoids.py
0.923756
0.439928
commutative_additive_monoids.py
pypi
from sage.misc.cachefunc import cached_method from sage.sets.family import Family from sage.categories.semigroups import Semigroups from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper class LeftRegularBand(UniqueRepresentation, Parent): r""" An example of a finite semigroup This class provides a minimal implementation of a finite semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example(); S An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd') This is the semigroup generated by:: sage: S.semigroup_generators() Family ('a', 'b', 'c', 'd') such that `x^2 = x` and `x y x = xy` for any `x` and `y` in `S`:: sage: S('dab') 'dab' sage: S('dab') * S('acb') 'dabc' It follows that the elements of `S` are strings without repetitions over the alphabet `a`, `b`, `c`, `d`:: sage: sorted(S.list()) ['a', 'ab', 'abc', 'abcd', 'abd', 'abdc', 'ac', 'acb', 'acbd', 'acd', 'acdb', 'ad', 'adb', 'adbc', 'adc', 'adcb', 'b', 'ba', 'bac', 'bacd', 'bad', 'badc', 'bc', 'bca', 'bcad', 'bcd', 'bcda', 'bd', 'bda', 'bdac', 'bdc', 'bdca', 'c', 'ca', 'cab', 'cabd', 'cad', 'cadb', 'cb', 'cba', 'cbad', 'cbd', 'cbda', 'cd', 'cda', 'cdab', 'cdb', 'cdba', 'd', 'da', 'dab', 'dabc', 'dac', 'dacb', 'db', 'dba', 'dbac', 'dbc', 'dbca', 'dc', 'dca', 'dcab', 'dcb', 'dcba'] It also follows that there are finitely many of them:: sage: S.cardinality() 64 Indeed:: sage: 4 * ( 1 + 3 * (1 + 2 * (1 + 1))) 64 As expected, all the elements of `S` are idempotents:: sage: all( x.is_idempotent() for x in S ) True Now, let us look at the structure of the semigroup:: sage: S = FiniteSemigroups().example(alphabet = ('a','b','c')) sage: S.cayley_graph(side="left", simple=True).plot() Graphics object consisting of 60 graphics primitives sage: S.j_transversal_of_idempotents() # random (arbitrary choice) ['acb', 'ac', 'ab', 'bc', 'a', 'c', 'b'] We conclude by running systematic tests on this semigroup:: sage: TestSuite(S).run(verbose = True) running ._test_an_element() . . . pass running ._test_associativity() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self, alphabet=('a','b','c','d')): r""" A left regular band. EXAMPLES:: sage: S = FiniteSemigroups().example(); S An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd') sage: S = FiniteSemigroups().example(alphabet=('x','y')); S An example of a finite semigroup: the left regular band generated by ('x', 'y') sage: TestSuite(S).run() """ self.alphabet = alphabet Parent.__init__(self, category=Semigroups().Finite().FinitelyGenerated()) def _repr_(self): r""" TESTS:: sage: S = FiniteSemigroups().example() sage: S._repr_() "An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')" """ return "An example of a finite semigroup: the left regular band generated by %s"%(self.alphabet,) def product(self, x, y): r""" Returns the product of two elements of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example() sage: S('a') * S('b') 'ab' sage: S('a') * S('b') * S('a') 'ab' sage: S('a') * S('a') 'a' """ assert x in self assert y in self x = x.value y = y.value return self(x + ''.join(c for c in y if c not in x)) @cached_method def semigroup_generators(self): r""" Returns the generators of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example(alphabet=('x','y')) sage: S.semigroup_generators() Family ('x', 'y') """ return Family([self(i) for i in self.alphabet]) def an_element(self): r""" Returns an element of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example() sage: S.an_element() 'cdab' sage: S = FiniteSemigroups().example(("b")) sage: S.an_element() 'b' """ return self(''.join(self.alphabet[2:]+self.alphabet[0:2])) class Element (ElementWrapper): wrapped_class = str __lt__ = ElementWrapper._lt_by_value Example = LeftRegularBand
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/finite_semigroups.py
0.895306
0.496643
finite_semigroups.py
pypi
from sage.misc.cachefunc import cached_method from sage.sets.family import Family from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.all import Monoids from sage.rings.integer import Integer from sage.rings.integer_ring import ZZ class IntegerModMonoid(UniqueRepresentation, Parent): r""" An example of a finite monoid: the integers mod `n` This class illustrates a minimal implementation of a finite monoid. EXAMPLES:: sage: S = FiniteMonoids().example(); S An example of a finite multiplicative monoid: the integers modulo 12 sage: S.category() Category of finitely generated finite enumerated monoids We conclude by running systematic tests on this monoid:: sage: TestSuite(S).run(verbose = True) running ._test_an_element() . . . pass running ._test_associativity() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_one() . . . pass running ._test_pickling() . . . pass running ._test_prod() . . . pass running ._test_some_elements() . . . pass """ def __init__(self, n=12): r""" EXAMPLES:: sage: M = FiniteMonoids().example(6); M An example of a finite multiplicative monoid: the integers modulo 6 TESTS:: sage: TestSuite(M).run() """ self.n = n Parent.__init__(self, category=Monoids().Finite().FinitelyGenerated()) def _repr_(self): r""" TESTS:: sage: M = FiniteMonoids().example() sage: M._repr_() 'An example of a finite multiplicative monoid: the integers modulo 12' """ return "An example of a finite multiplicative monoid: the integers modulo %s"%self.n def semigroup_generators(self): r""" Returns a set of generators for ``self``, as per :meth:`Semigroups.ParentMethods.semigroup_generators`. Currently this returns all integers mod `n`, which is of course far from optimal! EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.semigroup_generators() Family (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) """ return Family(tuple(self(ZZ(i)) for i in range(self.n))) @cached_method def one(self): r""" Return the one of the monoid, as per :meth:`Monoids.ParentMethods.one`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.one() 1 """ return self(ZZ.one()) def product(self, x, y): r""" Return the product of two elements `x` and `y` of the monoid, as per :meth:`Semigroups.ParentMethods.product`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.product(M(3), M(5)) 3 """ return self((x.value * y.value) % self.n) def an_element(self): r""" Returns an element of the monoid, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.an_element() 6 """ return self(ZZ(42) % self.n) class Element (ElementWrapper): wrapped_class = Integer Example = IntegerModMonoid
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/finite_monoids.py
0.937676
0.447762
finite_monoids.py
pypi
from sage.structure.parent import Parent from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.structure.unique_representation import UniqueRepresentation from sage.rings.integer import Integer class NonNegativeIntegers(UniqueRepresentation, Parent): r""" An example of infinite enumerated set: the non negative integers This class provides a minimal implementation of an infinite enumerated set. EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN An example of an infinite enumerated set: the non negative integers sage: NN.cardinality() +Infinity sage: NN.list() Traceback (most recent call last): ... NotImplementedError: cannot list an infinite set sage: NN.element_class <class 'sage.rings.integer.Integer'> sage: it = iter(NN) sage: [next(it), next(it), next(it), next(it), next(it)] [0, 1, 2, 3, 4] sage: x = next(it); type(x) <class 'sage.rings.integer.Integer'> sage: x.parent() Integer Ring sage: x+3 8 sage: NN(15) 15 sage: NN.first() 0 This checks that the different methods of `NN` return consistent results:: sage: TestSuite(NN).run(verbose = True) running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_nonzero_equal() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self): """ TESTS:: sage: NN = InfiniteEnumeratedSets().example() sage: NN An example of an infinite enumerated set: the non negative integers sage: NN.category() Category of infinite enumerated sets sage: TestSuite(NN).run() """ Parent.__init__(self, category=InfiniteEnumeratedSets()) def _repr_(self): """ TESTS:: sage: InfiniteEnumeratedSets().example() # indirect doctest An example of an infinite enumerated set: the non negative integers """ return "An example of an infinite enumerated set: the non negative integers" def __contains__(self, elt): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: 1 in NN True sage: -1 in NN False """ return Integer(elt) >= Integer(0) def __iter__(self): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: g = iter(NN) sage: next(g), next(g), next(g), next(g) (0, 1, 2, 3) """ i = Integer(0) while True: yield self._element_constructor_(i) i += 1 def __call__(self, elt): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN(3) # indirect doctest 3 sage: NN(3).parent() Integer Ring sage: NN(-1) Traceback (most recent call last): ... ValueError: Value -1 is not a non negative integer. """ if elt in self: return self._element_constructor_(elt) raise ValueError("Value %s is not a non negative integer." % (elt)) def an_element(self): """ EXAMPLES:: sage: InfiniteEnumeratedSets().example().an_element() 42 """ return self._element_constructor_(Integer(42)) def next(self, o): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN.next(3) 4 """ return self._element_constructor_(o+1) def _element_constructor_(self, i): """ The default implementation of _element_constructor_ assumes that the constructor of the element class takes the parent as parameter. This is not the case for ``Integer``, so we need to provide an implementation. TESTS:: sage: NN = InfiniteEnumeratedSets().example() sage: x = NN(42); x 42 sage: type(x) <class 'sage.rings.integer.Integer'> sage: x.parent() Integer Ring """ return self.element_class(i) Element = Integer Example = NonNegativeIntegers
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/infinite_enumerated_sets.py
0.912062
0.535706
infinite_enumerated_sets.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element import Element from sage.categories.cw_complexes import CWComplexes from sage.sets.family import Family class Surface(UniqueRepresentation, Parent): r""" An example of a CW complex: a (2-dimensional) surface. This class illustrates a minimal implementation of a CW complex. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example(); X An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2) sage: X.category() Category of finite finite dimensional CW complexes We conclude by running systematic tests on this manifold:: sage: TestSuite(X).run() """ def __init__(self, bdy=(1, 2, 1, 2)): r""" EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example((1, 2)); X An example of a CW complex: the surface given by the boundary map (1, 2) TESTS:: sage: TestSuite(X).run() """ self._bdy = bdy self._edges = frozenset(bdy) Parent.__init__(self, category=CWComplexes().Finite()) def _repr_(self): r""" TESTS:: sage: from sage.categories.cw_complexes import CWComplexes sage: CWComplexes().example() An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2) """ return "An example of a CW complex: the surface given by the boundary map {}".format(self._bdy) def cells(self): """ Return the cells of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: C = X.cells() sage: sorted((d, C[d]) for d in C.keys()) [(0, (0-cell v,)), (1, (0-cell e1, 0-cell e2)), (2, (2-cell f,))] """ d = {0: (self.element_class(self, 0, 'v'),)} d[1] = tuple([self.element_class(self, 0, 'e'+str(e)) for e in self._edges]) d[2] = (self.an_element(),) return Family(d) def an_element(self): r""" Return an element of the CW complex, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: X.an_element() 2-cell f """ return self.element_class(self, 2, 'f') class Element(Element): """ A cell in a CW complex. """ def __init__(self, parent, dim, name): """ Initialize ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: TestSuite(f).run() """ Element.__init__(self, parent) self._dim = dim self._name = name def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: X.an_element() 2-cell f """ return "{}-cell {}".format(self._dim, self._name) def __eq__(self, other): """ Check equality. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: f == X(2, 'f') True sage: e1 = X(1, 'e1') sage: e1 == f False """ return (isinstance(other, Surface.Element) and self.parent() is other.parent() and self._dim == other._dim and self._name == other._name) def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: f.dimension() 2 """ return self._dim Example = Surface
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/categories/examples/cw_complexes.py
0.955992
0.673975
cw_complexes.py
pypi
import unicodedata from sage.structure.sage_object import SageObject class CompoundSymbol(SageObject): def __init__(self, character, top, extension, bottom, middle=None, middle_top=None, middle_bottom=None, top_2=None, bottom_2=None): """ A multi-character (ascii/unicode art) symbol INPUT: Instead of string, each of these can be unicode in Python 2: - ``character`` -- string. The single-line version of the symbol. - ``top`` -- string. The top line of a multi-line symbol. - ``extension`` -- string. The extension line of a multi-line symbol (will be repeated). - ``bottom`` -- string. The bottom line of a multi-line symbol. - ``middle`` -- optional string. The middle part, for example in curly braces. Will be used only once for the symbol, and only if its height is odd. - ``middle_top`` -- optional string. The upper half of the 2-line middle part if the height of the symbol is even. Will be used only once for the symbol. - ``middle_bottom`` -- optional string. The lower half of the 2-line middle part if the height of the symbol is even. Will be used only once for the symbol. - ``top_2`` -- optional string. The upper half of a 2-line symbol. - ``bottom_2`` -- optional string. The lower half of a 2-line symbol. EXAMPLES:: sage: from sage.typeset.symbols import CompoundSymbol sage: i = CompoundSymbol('I', '+', '|', '+', '|') sage: i.print_to_stdout(1) I sage: i.print_to_stdout(3) + | + """ self.character = character self.top = top self.extension = extension self.bottom = bottom self.middle = middle or extension self.middle_top = middle_top or extension self.middle_bottom = middle_bottom or extension self.top_2 = top_2 or top self.bottom_2 = bottom_2 or bottom def _repr_(self): """ Return string representation EXAMPLES:: sage: from sage.typeset.symbols import unicode_left_parenthesis sage: unicode_left_parenthesis multi_line version of "(" """ return 'multi_line version of "{0}"'.format(self.character) def __call__(self, num_lines): r""" Return the lines for a multi-line symbol INPUT: - ``num_lines`` -- integer. The total number of lines. OUTPUT: List of strings / unicode strings. EXAMPLES:: sage: from sage.typeset.symbols import unicode_left_parenthesis sage: unicode_left_parenthesis(4) ['\u239b', '\u239c', '\u239c', '\u239d'] """ if num_lines <= 0: raise ValueError('number of lines must be positive') elif num_lines == 1: return [self.character] elif num_lines == 2: return [self.top_2, self.bottom_2] elif num_lines == 3: return [self.top, self.middle, self.bottom] elif num_lines % 2 == 0: ext = [self.extension] * ((num_lines - 4) // 2) return [self.top] + ext + [self.middle_top, self.middle_bottom] + ext + [self.bottom] else: # num_lines %2 == 1 ext = [self.extension] * ((num_lines - 3) // 2) return [self.top] + ext + [self.middle] + ext + [self.bottom] def print_to_stdout(self, num_lines): """ Print the multi-line symbol This method is for testing purposes. INPUT: - ``num_lines`` -- integer. The total number of lines. EXAMPLES:: sage: from sage.typeset.symbols import * sage: unicode_integral.print_to_stdout(1) ∫ sage: unicode_integral.print_to_stdout(2) ⌠ ⌡ sage: unicode_integral.print_to_stdout(3) ⌠ ⎮ ⌡ sage: unicode_integral.print_to_stdout(4) ⌠ ⎮ ⎮ ⌡ """ print('\n'.join(self(num_lines))) class CompoundAsciiSymbol(CompoundSymbol): def character_art(self, num_lines): """ Return the ASCII art of the symbol EXAMPLES:: sage: from sage.typeset.symbols import * sage: ascii_left_curly_brace.character_art(3) { { { """ from sage.typeset.ascii_art import AsciiArt return AsciiArt(self(num_lines)) class CompoundUnicodeSymbol(CompoundSymbol): def character_art(self, num_lines): """ Return the unicode art of the symbol EXAMPLES:: sage: from sage.typeset.symbols import * sage: unicode_left_curly_brace.character_art(3) ⎧ ⎨ ⎩ """ from sage.typeset.unicode_art import UnicodeArt return UnicodeArt(self(num_lines)) ascii_integral = CompoundAsciiSymbol( 'int', r' /\\', r' | ', r'\\/ ', ) unicode_integral = CompoundUnicodeSymbol( unicodedata.lookup('INTEGRAL'), unicodedata.lookup('TOP HALF INTEGRAL'), unicodedata.lookup('INTEGRAL EXTENSION'), unicodedata.lookup('BOTTOM HALF INTEGRAL'), ) ascii_left_parenthesis = CompoundAsciiSymbol( '(', '(', '(', '(', ) ascii_right_parenthesis = CompoundAsciiSymbol( ')', ')', ')', ')', ) unicode_left_parenthesis = CompoundUnicodeSymbol( unicodedata.lookup('LEFT PARENTHESIS'), unicodedata.lookup('LEFT PARENTHESIS UPPER HOOK'), unicodedata.lookup('LEFT PARENTHESIS EXTENSION'), unicodedata.lookup('LEFT PARENTHESIS LOWER HOOK'), ) unicode_right_parenthesis = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT PARENTHESIS'), unicodedata.lookup('RIGHT PARENTHESIS UPPER HOOK'), unicodedata.lookup('RIGHT PARENTHESIS EXTENSION'), unicodedata.lookup('RIGHT PARENTHESIS LOWER HOOK'), ) ascii_left_square_bracket = CompoundAsciiSymbol( '[', '[', '[', '[', ) ascii_right_square_bracket = CompoundAsciiSymbol( ']', ']', ']', ']', ) unicode_left_square_bracket = CompoundUnicodeSymbol( unicodedata.lookup('LEFT SQUARE BRACKET'), unicodedata.lookup('LEFT SQUARE BRACKET UPPER CORNER'), unicodedata.lookup('LEFT SQUARE BRACKET EXTENSION'), unicodedata.lookup('LEFT SQUARE BRACKET LOWER CORNER'), ) unicode_right_square_bracket = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT SQUARE BRACKET'), unicodedata.lookup('RIGHT SQUARE BRACKET UPPER CORNER'), unicodedata.lookup('RIGHT SQUARE BRACKET EXTENSION'), unicodedata.lookup('RIGHT SQUARE BRACKET LOWER CORNER'), ) ascii_left_curly_brace = CompoundAsciiSymbol( '{', '{', '{', '{', ) ascii_right_curly_brace = CompoundAsciiSymbol( '}', '}', '}', '}', ) unicode_left_curly_brace = CompoundUnicodeSymbol( unicodedata.lookup('LEFT CURLY BRACKET'), unicodedata.lookup('LEFT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('CURLY BRACKET EXTENSION'), unicodedata.lookup('LEFT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('LEFT CURLY BRACKET MIDDLE PIECE'), unicodedata.lookup('RIGHT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('RIGHT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION'), unicodedata.lookup('UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION'), ) unicode_right_curly_brace = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT CURLY BRACKET'), unicodedata.lookup('RIGHT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('CURLY BRACKET EXTENSION'), unicodedata.lookup('RIGHT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('RIGHT CURLY BRACKET MIDDLE PIECE'), unicodedata.lookup('LEFT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('LEFT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION'), unicodedata.lookup('UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION'), )
/sagemath-categories-10.0b1.tar.gz/sagemath-categories-10.0b1/sage/typeset/symbols.py
0.885179
0.489076
symbols.py
pypi
r""" Features for testing the presence of Python modules in the Sage library """ from . import PythonModule, StaticFile from .join_feature import JoinFeature class sagemath_doc_html(StaticFile): r""" A :class:`Feature` which describes the presence of the documentation of the Sage library in HTML format. EXAMPLES:: sage: from sage.features.sagemath import sagemath_doc_html sage: sagemath_doc_html().is_present() # optional - sagemath_doc_html FeatureTestResult('sagemath_doc_html', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sagemath_doc_html sage: isinstance(sagemath_doc_html(), sagemath_doc_html) True """ from sage.env import SAGE_DOC StaticFile.__init__(self, 'sagemath_doc_html', filename='html', search_path=(SAGE_DOC,), spkg='sagemath_doc_html') class sage__combinat(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.combinat`. EXAMPLES:: sage: from sage.features.sagemath import sage__combinat sage: sage__combinat().is_present() # optional - sage.combinat FeatureTestResult('sage.combinat', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__combinat sage: isinstance(sage__combinat(), sage__combinat) True """ # sage.combinat will be a namespace package. # Testing whether sage.combinat itself can be imported is meaningless. # Hence, we test a Python module within the package. JoinFeature.__init__(self, 'sage.combinat', [PythonModule('sage.combinat.combination')]) class sage__geometry__polyhedron(PythonModule): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.geometry.polyhedron`. EXAMPLES:: sage: from sage.features.sagemath import sage__geometry__polyhedron sage: sage__geometry__polyhedron().is_present() # optional - sage.geometry.polyhedron FeatureTestResult('sage.geometry.polyhedron', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__geometry__polyhedron sage: isinstance(sage__geometry__polyhedron(), sage__geometry__polyhedron) True """ PythonModule.__init__(self, 'sage.geometry.polyhedron') class sage__graphs(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.graphs`. EXAMPLES:: sage: from sage.features.sagemath import sage__graphs sage: sage__graphs().is_present() # optional - sage.graphs FeatureTestResult('sage.graphs', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__graphs sage: isinstance(sage__graphs(), sage__graphs) True """ JoinFeature.__init__(self, 'sage.graphs', [PythonModule('sage.graphs.graph')]) class sage__groups(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.groups``. EXAMPLES:: sage: from sage.features.sagemath import sage__groups sage: sage__groups().is_present() # optional - sage.groups FeatureTestResult('sage.groups', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__groups sage: isinstance(sage__groups(), sage__groups) True """ JoinFeature.__init__(self, 'sage.groups', [PythonModule('sage.groups.perm_gps.permgroup')]) class sage__plot(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.plot`. EXAMPLES:: sage: from sage.features.sagemath import sage__plot sage: sage__plot().is_present() # optional - sage.plot FeatureTestResult('sage.plot', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__plot sage: isinstance(sage__plot(), sage__plot) True """ JoinFeature.__init__(self, 'sage.plot', [PythonModule('sage.plot.plot')]) class sage__rings__number_field(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.rings.number_field`. EXAMPLES:: sage: from sage.features.sagemath import sage__rings__number_field sage: sage__rings__number_field().is_present() # optional - sage.rings.number_field FeatureTestResult('sage.rings.number_field', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__rings__number_field sage: isinstance(sage__rings__number_field(), sage__rings__number_field) True """ JoinFeature.__init__(self, 'sage.rings.number_field', [PythonModule('sage.rings.number_field.number_field_element')]) class sage__rings__padics(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.rings.padics``. EXAMPLES:: sage: from sage.features.sagemath import sage__rings__padics sage: sage__rings__padics().is_present() # optional - sage.rings.padics FeatureTestResult('sage.rings.padics', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__rings__padics sage: isinstance(sage__rings__padics(), sage__rings__padics) True """ JoinFeature.__init__(self, 'sage.rings.padics', [PythonModule('sage.rings.padics.factory')]) class sage__rings__real_double(PythonModule): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.rings.real_double`. EXAMPLES:: sage: from sage.features.sagemath import sage__rings__real_double sage: sage__rings__real_double().is_present() # optional - sage.rings.real_double FeatureTestResult('sage.rings.real_double', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__rings__real_double sage: isinstance(sage__rings__real_double(), sage__rings__real_double) True """ PythonModule.__init__(self, 'sage.rings.real_double') class sage__symbolic(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of :mod:`sage.symbolic`. EXAMPLES:: sage: from sage.features.sagemath import sage__symbolic sage: sage__symbolic().is_present() # optional - sage.symbolic FeatureTestResult('sage.symbolic', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__symbolic sage: isinstance(sage__symbolic(), sage__symbolic) True """ JoinFeature.__init__(self, 'sage.symbolic', [PythonModule('sage.symbolic.expression')], spkg="sagemath_symbolics") def all_features(): r""" Return features corresponding to parts of the Sage library. These features are named after Python packages/modules (e.g., :mod:`sage.symbolic`), not distribution packages (**sagemath-symbolics**). This design is motivated by a separation of concerns: The author of a module that depends on some functionality provided by a Python module usually already knows the name of the Python module, so we do not want to force the author to also know about the distribution package that provides the Python module. Instead, we associate distribution packages to Python modules in :mod:`sage.features.sagemath` via the ``spkg`` parameter of :class:`~sage.features.Feature`. EXAMPLES:: sage: from sage.features.sagemath import all_features sage: list(all_features()) [...Feature('sage.combinat'), ...] """ return [sagemath_doc_html(), sage__combinat(), sage__geometry__polyhedron(), sage__graphs(), sage__groups(), sage__plot(), sage__rings__number_field(), sage__rings__padics(), sage__rings__real_double(), sage__symbolic()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/sagemath.py
0.893733
0.495911
sagemath.py
pypi
r""" Feature for testing the presence of ``csdp`` """ import os import re import subprocess from . import Executable, FeatureTestResult class CSDP(Executable): r""" A :class:`~sage.features.Feature` which checks for the ``theta`` binary of CSDP. EXAMPLES:: sage: from sage.features.csdp import CSDP sage: CSDP().is_present() # optional - csdp FeatureTestResult('csdp', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.csdp import CSDP sage: isinstance(CSDP(), CSDP) True """ Executable.__init__(self, name="csdp", spkg="csdp", executable="theta", url="https://github.com/dimpase/csdp") def is_functional(self): r""" Check whether ``theta`` works on a trivial example. EXAMPLES:: sage: from sage.features.csdp import CSDP sage: CSDP().is_functional() # optional - csdp FeatureTestResult('csdp', True) """ from sage.misc.temporary_file import tmp_filename from sage.cpython.string import bytes_to_str tf_name = tmp_filename() with open(tf_name, 'wb') as tf: tf.write("2\n1\n1 1".encode()) with open(os.devnull, 'wb') as devnull: command = ['theta', tf_name] try: lines = subprocess.check_output(command, stderr=devnull) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call to `{command}` failed with exit code {e.returncode}." .format(command=" ".join(command), e=e)) result = bytes_to_str(lines).strip().split('\n')[-1] match = re.match("^The Lovasz Theta Number is (.*)$", result) if match is None: return FeatureTestResult(self, False, reason="Last line of the output of `{command}` did not have the expected format." .format(command=" ".join(command))) return FeatureTestResult(self, True) def all_features(): return [CSDP()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/csdp.py
0.764276
0.471892
csdp.py
pypi
r""" Features for testing the presence of :class:`MixedIntegerLinearProgram` backends """ from . import Feature, PythonModule, FeatureTestResult from .join_feature import JoinFeature class MIPBackend(Feature): r""" A :class:`~sage.features.Feature` describing whether a :class:`MixedIntegerLinearProgram` backend is available. """ def _is_present(self): r""" Test for the presence of a :class:`MixedIntegerLinearProgram` backend. EXAMPLES:: sage: from sage.features.mip_backends import CPLEX sage: CPLEX()._is_present() # optional - cplex FeatureTestResult('cplex', True) """ try: from sage.numerical.mip import MixedIntegerLinearProgram MixedIntegerLinearProgram(solver=self.name) return FeatureTestResult(self, True) except Exception: return FeatureTestResult(self, False) class CPLEX(MIPBackend): r""" A :class:`~sage.features.Feature` describing whether the :class:`MixedIntegerLinearProgram` backend ``CPLEX`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import CPLEX sage: CPLEX()._is_present() # optional - cplex FeatureTestResult('cplex', True) """ MIPBackend.__init__(self, 'cplex', spkg='sage_numerical_backends_cplex') class Gurobi(MIPBackend): r""" A :class:`~sage.features.Feature` describing whether the :class:`MixedIntegerLinearProgram` backend ``Gurobi`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import Gurobi sage: Gurobi()._is_present() # optional - gurobi FeatureTestResult('gurobi', True) """ MIPBackend.__init__(self, 'gurobi', spkg='sage_numerical_backends_gurobi') class COIN(JoinFeature): r""" A :class:`~sage.features.Feature` describing whether the :class:`MixedIntegerLinearProgram` backend ``COIN`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import COIN sage: COIN()._is_present() # optional - sage_numerical_backends_coin FeatureTestResult('sage_numerical_backends_coin', True) """ JoinFeature.__init__(self, 'sage_numerical_backends_coin', [MIPBackend('coin')], spkg='sage_numerical_backends_coin') class CVXOPT(JoinFeature): r""" A :class:`~sage.features.Feature` describing whether the :class:`MixedIntegerLinearProgram` backend ``CVXOPT`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import CVXOPT sage: CVXOPT()._is_present() # optional - cvxopt FeatureTestResult('cvxopt', True) """ JoinFeature.__init__(self, 'cvxopt', [MIPBackend('CVXOPT'), PythonModule('cvxopt')], spkg='cvxopt') def all_features(): return [CPLEX(), Gurobi(), COIN(), CVXOPT()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/mip_backends.py
0.89431
0.572454
mip_backends.py
pypi
r""" Features for testing the presence of package systems """ from . import Feature class PackageSystem(Feature): r""" A :class:`Feature` describing a system package manager. EXAMPLES:: sage: from sage.features.pkg_systems import PackageSystem sage: PackageSystem('conda') Feature('conda') """ def _is_present(self): r""" Test whether ``self`` appears in the list of available package systems. EXAMPLES:: sage: from sage.features.pkg_systems import PackageSystem sage: debian = PackageSystem('debian') sage: debian.is_present() # indirect doctest, random True """ from . import package_systems return self in package_systems() def spkg_installation_hint(self, spkgs, *, prompt=" !", feature=None): r""" Return a string that explains how to install ``feature``. EXAMPLES:: sage: from sage.features.pkg_systems import PackageSystem sage: homebrew = PackageSystem('homebrew') sage: homebrew.spkg_installation_hint('openblas') # optional - SAGE_ROOT 'To install openblas using the homebrew package manager, you can try to run:\n!brew install openblas' """ if isinstance(spkgs, (tuple, list)): spkgs = ' '.join(spkgs) if feature is None: feature = spkgs return self._spkg_installation_hint(spkgs, prompt, feature) def _spkg_installation_hint(self, spkgs, prompt, feature): r""" Return a string that explains how to install ``feature``. Override this method in derived classes. EXAMPLES:: sage: from sage.features.pkg_systems import PackageSystem sage: fedora = PackageSystem('fedora') sage: fedora.spkg_installation_hint('openblas') # optional - SAGE_ROOT 'To install openblas using the fedora package manager, you can try to run:\n!sudo yum install openblas-devel' """ from subprocess import run, CalledProcessError, PIPE lines = [] system = self.name try: proc = run(f'sage-get-system-packages {system} {spkgs}', shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True, check=True) system_packages = proc.stdout.strip() print_sys = f'sage-print-system-package-command {system} --verbose --sudo --prompt="{prompt}"' command = f'{print_sys} update && {print_sys} install {system_packages}' proc = run(command, shell=True, stdout=PIPE, stderr=PIPE, universal_newlines=True, check=True) command = proc.stdout.strip() if command: lines.append(f'To install {feature} using the {system} package manager, you can try to run:') lines.append(command) return '\n'.join(lines) except CalledProcessError: pass return f'No equivalent system packages for {system} are known to Sage.' class SagePackageSystem(PackageSystem): r""" A :class:`Feature` describing the package manager of the SageMath distribution. EXAMPLES:: sage: from sage.features.pkg_systems import SagePackageSystem sage: SagePackageSystem() Feature('sage_spkg') """ @staticmethod def __classcall__(cls): r""" Normalize initargs. TESTS:: sage: from sage.features.pkg_systems import SagePackageSystem sage: SagePackageSystem() is SagePackageSystem() # indirect doctest True """ return PackageSystem.__classcall__(cls, "sage_spkg") def _is_present(self): r""" Test whether ``sage-spkg`` is available. EXAMPLES:: sage: from sage.features.pkg_systems import SagePackageSystem sage: bool(SagePackageSystem().is_present()) # indirect doctest, optional - sage_spkg True """ from subprocess import run, DEVNULL, CalledProcessError try: # "sage -p" is a fast way of checking whether sage-spkg is available. run('sage -p', shell=True, stdout=DEVNULL, stderr=DEVNULL, check=True) except CalledProcessError: return False # Check if there are any installation records. try: from sage.misc.package import installed_packages except ImportError: return False for pkg in installed_packages(exclude_pip=True): return True return False def _spkg_installation_hint(self, spkgs, prompt, feature): r""" Return a string that explains how to install ``feature``. EXAMPLES:: sage: from sage.features.pkg_systems import SagePackageSystem sage: print(SagePackageSystem().spkg_installation_hint(['foo', 'bar'], prompt="### ", feature='foobarability')) # indirect doctest To install foobarability using the Sage package manager, you can try to run: ### sage -i foo bar """ lines = [] lines.append(f'To install {feature} using the Sage package manager, you can try to run:') lines.append(f'{prompt}sage -i {spkgs}') return '\n'.join(lines) class PipPackageSystem(PackageSystem): r""" A :class:`Feature` describing the Pip package manager. EXAMPLES:: sage: from sage.features.pkg_systems import PipPackageSystem sage: PipPackageSystem() Feature('pip') """ @staticmethod def __classcall__(cls): r""" Normalize initargs. TESTS:: sage: from sage.features.pkg_systems import PipPackageSystem sage: PipPackageSystem() is PipPackageSystem() # indirect doctest True """ return PackageSystem.__classcall__(cls, "pip") def _is_present(self): r""" Test whether ``pip`` is available. EXAMPLES:: sage: from sage.features.pkg_systems import PipPackageSystem sage: bool(PipPackageSystem().is_present()) # indirect doctest True """ from subprocess import run, DEVNULL, CalledProcessError try: run('sage -pip --version', shell=True, stdout=DEVNULL, stderr=DEVNULL, check=True) return True except CalledProcessError: return False
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/pkg_systems.py
0.830319
0.465509
pkg_systems.py
pypi
r""" Features for testing the presence of various databases """ from . import StaticFile, PythonModule from sage.env import ( CONWAY_POLYNOMIALS_DATA_DIR, CREMONA_MINI_DATA_DIR, CREMONA_LARGE_DATA_DIR, POLYTOPE_DATA_DIR) class DatabaseConwayPolynomials(StaticFile): r""" A :class:`~sage.features.Feature` which describes the presence of Frank Luebeck's database of Conway polynomials. EXAMPLES:: sage: from sage.features.databases import DatabaseConwayPolynomials sage: DatabaseConwayPolynomials().is_present() FeatureTestResult('conway_polynomials', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseConwayPolynomials sage: isinstance(DatabaseConwayPolynomials(), DatabaseConwayPolynomials) True """ if CONWAY_POLYNOMIALS_DATA_DIR: search_path = [CONWAY_POLYNOMIALS_DATA_DIR] else: search_path = [] StaticFile.__init__(self, "conway_polynomials", filename='conway_polynomials.p', search_path=search_path, spkg='conway_polynomials', description="Frank Luebeck's database of Conway polynomials") CREMONA_DATA_DIRS = set([CREMONA_MINI_DATA_DIR, CREMONA_LARGE_DATA_DIR]) class DatabaseCremona(StaticFile): r""" A :class:`~sage.features.Feature` which describes the presence of John Cremona's database of elliptic curves. INPUT: - ``name`` -- either ``'cremona'`` (the default) for the full large database or ``'cremona_mini'`` for the small database. EXAMPLES:: sage: from sage.features.databases import DatabaseCremona sage: DatabaseCremona('cremona_mini').is_present() FeatureTestResult('database_cremona_mini_ellcurve', True) sage: DatabaseCremona().is_present() # optional - database_cremona_ellcurve FeatureTestResult('database_cremona_ellcurve', True) """ def __init__(self, name="cremona", spkg="database_cremona_ellcurve"): r""" TESTS:: sage: from sage.features.databases import DatabaseCremona sage: isinstance(DatabaseCremona(), DatabaseCremona) True """ StaticFile.__init__(self, f"database_{name}_ellcurve", filename='{}.db'.format(name.replace(' ', '_')), search_path=CREMONA_DATA_DIRS, spkg=spkg, url="https://github.com/JohnCremona/ecdata", description="Cremona's database of elliptic curves") class DatabaseJones(StaticFile): r""" A :class:`~sage.features.Feature` which describes the presence of John Jones's tables of number fields. EXAMPLES:: sage: from sage.features.databases import DatabaseJones sage: bool(DatabaseJones().is_present()) # optional - database_jones_numfield True """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseJones sage: isinstance(DatabaseJones(), DatabaseJones) True """ StaticFile.__init__(self, "database_jones_numfield", filename='jones/jones.sobj', spkg="database_jones_numfield", description="John Jones's tables of number fields") class DatabaseKnotInfo(PythonModule): r""" A :class:`~sage.features.Feature` which describes the presence of the databases at the web-pages `KnotInfo <https://knotinfo.math.indiana.edu/>`__ and `LinkInfo <https://linkinfo.sitehost.iu.edu>`__. EXAMPLES:: sage: from sage.features.databases import DatabaseKnotInfo sage: DatabaseKnotInfo().is_present() # optional - database_knotinfo FeatureTestResult('database_knotinfo', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseKnotInfo sage: isinstance(DatabaseKnotInfo(), DatabaseKnotInfo) True """ PythonModule.__init__(self, 'database_knotinfo', spkg='database_knotinfo') class DatabaseCubicHecke(PythonModule): r""" A :class:`~sage.features.Feature` which describes the presence of the databases at the web-page `Cubic Hecke algebra on 4 strands <http://www.lamfa.u-picardie.fr/marin/representationH4-en.html>`__ of Ivan Marin. EXAMPLES:: sage: from sage.features.databases import DatabaseCubicHecke sage: DatabaseCubicHecke().is_present() # optional - database_cubic_hecke FeatureTestResult('database_cubic_hecke', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseCubicHecke sage: isinstance(DatabaseCubicHecke(), DatabaseCubicHecke) True """ PythonModule.__init__(self, 'database_cubic_hecke', spkg='database_cubic_hecke') class DatabaseReflexivePolytopes(StaticFile): r""" A :class:`~sage.features.Feature` which describes the presence of the PALP database of reflexive lattice polytopes. EXAMPLES:: sage: from sage.features.databases import DatabaseReflexivePolytopes sage: bool(DatabaseReflexivePolytopes().is_present()) # optional - polytopes_db True sage: bool(DatabaseReflexivePolytopes('polytopes_db_4d', 'Hodge4d').is_present()) # optional - polytopes_db_4d True """ def __init__(self, name='polytopes_db', dirname='Full3D'): """ TESTS:: sage: from sage.features.databases import DatabaseReflexivePolytopes sage: isinstance(DatabaseReflexivePolytopes(), DatabaseReflexivePolytopes) True """ StaticFile.__init__(self, name, dirname, search_path=[POLYTOPE_DATA_DIR]) def all_features(): return [DatabaseConwayPolynomials(), DatabaseCremona(), DatabaseCremona('cremona_mini'), DatabaseJones(), DatabaseKnotInfo(), DatabaseCubicHecke(), DatabaseReflexivePolytopes(), DatabaseReflexivePolytopes('polytopes_db_4d', 'Hodge4d')]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/databases.py
0.868395
0.528351
databases.py
pypi
r""" Join features """ from . import Feature, FeatureTestResult class JoinFeature(Feature): r""" Join of several :class:`~sage.features.Feature` instances. This creates a new feature as the union of the given features. Typically these are executables of an SPKG. For an example, see :class:`~sage.features.rubiks.Rubiks`. Furthermore, this can be the union of a single feature. This is used to map the given feature to a more convenient name to be used in ``optional`` tags of doctests. Thus you can equip a feature such as a :class:`~sage.features.PythonModule` with a tag name that differs from the systematic tag name. As an example for this use case, see :class:`~sage.features.meataxe.Meataxe`. EXAMPLES:: sage: from sage.features import Executable sage: from sage.features.join_feature import JoinFeature sage: F = JoinFeature("shell-boolean", ....: (Executable('shell-true', 'true'), ....: Executable('shell-false', 'false'))) sage: F.is_present() FeatureTestResult('shell-boolean', True) sage: F = JoinFeature("asdfghjkl", ....: (Executable('shell-true', 'true'), ....: Executable('xxyyyy', 'xxyyyy-does-not-exist'))) sage: F.is_present() FeatureTestResult('xxyyyy', False) """ def __init__(self, name, features, spkg=None, url=None, description=None): """ TESTS: The empty join feature is present:: sage: from sage.features.join_feature import JoinFeature sage: JoinFeature("empty", ()).is_present() FeatureTestResult('empty', True) """ if spkg is None: spkgs = set(f.spkg for f in features if f.spkg) if len(spkgs) > 1: raise ValueError('given features have more than one spkg; provide spkg argument') elif len(spkgs) == 1: spkg = next(iter(spkgs)) if url is None: urls = set(f.url for f in features if f.url) if len(urls) > 1: raise ValueError('given features have more than one url; provide url argument') elif len(urls) == 1: url = next(iter(urls)) super().__init__(name, spkg=spkg, url=url, description=description) self._features = features def _is_present(self): r""" Test for the presence of the join feature. EXAMPLES:: sage: from sage.features.latte import Latte sage: Latte()._is_present() # optional - latte_int FeatureTestResult('latte_int', True) """ for f in self._features: test = f._is_present() if not test: return test return FeatureTestResult(self, True) def is_functional(self): r""" Test whether the join feature is functional. This method is deprecated. Use :meth:`Feature.is_present` instead. EXAMPLES:: sage: from sage.features.latte import Latte sage: Latte().is_functional() # optional - latte_int doctest:warning... DeprecationWarning: method JoinFeature.is_functional; use is_present instead See https://github.com/sagemath/sage/issues/33114 for details. FeatureTestResult('latte_int', True) """ try: from sage.misc.superseded import deprecation except ImportError: # The import can fail because sage.misc.superseded is provided by # the distribution sagemath-objects, which is not an # install-requires of the distribution sagemath-environment. pass else: deprecation(33114, 'method JoinFeature.is_functional; use is_present instead') for f in self._features: test = f.is_functional() if not test: return test return FeatureTestResult(self, True)
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/join_feature.py
0.88239
0.578508
join_feature.py
pypi
r""" Feature for testing the presence of ``lrslib`` """ import subprocess from . import Executable, FeatureTestResult from .join_feature import JoinFeature class Lrs(Executable): r""" A :class:`~sage.features.Feature` describing the presence of the ``lrs`` binary which comes as a part of ``lrslib``. EXAMPLES:: sage: from sage.features.lrs import Lrs sage: Lrs().is_present() # optional - lrslib FeatureTestResult('lrs', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.lrs import Lrs sage: isinstance(Lrs(), Lrs) True """ Executable.__init__(self, "lrs", executable="lrs", spkg="lrslib", url="http://cgm.cs.mcgill.ca/~avis/C/lrs.html") def is_functional(self): r""" Test whether ``lrs`` works on a trivial input. EXAMPLES:: sage: from sage.features.lrs import Lrs sage: Lrs().is_functional() # optional - lrslib FeatureTestResult('lrs', True) """ from sage.misc.temporary_file import tmp_filename tf_name = tmp_filename() with open(tf_name, 'w') as tf: tf.write("V-representation\nbegin\n 1 1 rational\n 1 \nend\nvolume") command = [self.absolute_filename(), tf_name] try: result = subprocess.run(command, capture_output=True, text=True) except OSError as e: return FeatureTestResult(self, False, reason='Running command "{}" ' 'raised an OSError "{}" '.format(' '.join(command), e)) if result.returncode: return FeatureTestResult(self, False, reason="Call to `{command}` failed with exit code {result.returncode}.".format(command=" ".join(command), result=result)) expected_list = ["Volume= 1", "Volume=1"] if all(result.stdout.find(expected) == -1 for expected in expected_list): return FeatureTestResult(self, False, reason="Output of `{command}` did not contain the expected result {expected}; output: {result.stdout}".format( command=" ".join(command), expected=" or ".join(expected_list), result=result)) return FeatureTestResult(self, True) class LrsNash(Executable): r""" A :class:`~sage.features.Feature` describing the presence of the ``lrsnash`` binary which comes as a part of ``lrslib``. EXAMPLES:: sage: from sage.features.lrs import LrsNash sage: LrsNash().is_present() # optional - lrslib FeatureTestResult('lrsnash', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.lrs import LrsNash sage: isinstance(LrsNash(), LrsNash) True """ Executable.__init__(self, "lrsnash", executable="lrsnash", spkg="lrslib", url="http://cgm.cs.mcgill.ca/~avis/C/lrs.html") def is_functional(self): r""" Test whether ``lrsnash`` works on a trivial input. EXAMPLES:: sage: from sage.features.lrs import LrsNash sage: LrsNash().is_functional() # optional - lrslib FeatureTestResult('lrsnash', True) """ from sage.misc.temporary_file import tmp_filename # Checking whether `lrsnash` can handle the new input format # This test is currently done in build/pkgs/lrslib/spkg-configure.m4 tf_name = tmp_filename() with open(tf_name, 'w') as tf: tf.write("1 1\n \n 0\n \n 0\n") command = [self.absolute_filename(), tf_name] try: result = subprocess.run(command, capture_output=True, text=True) except OSError as e: return FeatureTestResult(self, False, reason='Running command "{}" ' 'raised an OSError "{}" '.format(' '.join(command), e)) if result.returncode: return FeatureTestResult(self, False, reason='Running command "{}" ' 'returned non-zero exit status "{}" with stderr ' '"{}" and stdout "{}".'.format(' '.join(result.args), result.returncode, result.stderr.strip(), result.stdout.strip())) return FeatureTestResult(self, True) class Lrslib(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of the executables which comes as a part of ``lrslib``. EXAMPLES:: sage: from sage.features.lrs import Lrslib sage: Lrslib().is_present() # optional - lrslib FeatureTestResult('lrslib', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.lrs import Lrslib sage: isinstance(Lrslib(), Lrslib) True """ JoinFeature.__init__(self, "lrslib", (Lrs(), LrsNash())) def all_features(): return [Lrslib()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/lrs.py
0.837354
0.560583
lrs.py
pypi
r""" Features for testing the presence of ``rubiks`` """ # **************************************************************************** # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** from sage.env import RUBIKS_BINS_PREFIX from . import Executable from .join_feature import JoinFeature class cu2(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``cu2`` EXAMPLES:: sage: from sage.features.rubiks import cu2 sage: cu2().is_present() # optional - rubiks FeatureTestResult('cu2', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import cu2 sage: isinstance(cu2(), cu2) True """ Executable.__init__(self, "cu2", executable=RUBIKS_BINS_PREFIX + "cu2", spkg="rubiks") class size222(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``size222`` EXAMPLES:: sage: from sage.features.rubiks import size222 sage: size222().is_present() # optional - rubiks FeatureTestResult('size222', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import size222 sage: isinstance(size222(), size222) True """ Executable.__init__(self, "size222", executable=RUBIKS_BINS_PREFIX + "size222", spkg="rubiks") class optimal(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``optimal`` EXAMPLES:: sage: from sage.features.rubiks import optimal sage: optimal().is_present() # optional - rubiks FeatureTestResult('optimal', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import optimal sage: isinstance(optimal(), optimal) True """ Executable.__init__(self, "optimal", executable=RUBIKS_BINS_PREFIX + "optimal", spkg="rubiks") class mcube(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``mcube`` EXAMPLES:: sage: from sage.features.rubiks import mcube sage: mcube().is_present() # optional - rubiks FeatureTestResult('mcube', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import mcube sage: isinstance(mcube(), mcube) True """ Executable.__init__(self, "mcube", executable=RUBIKS_BINS_PREFIX + "mcube", spkg="rubiks") class dikcube(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``dikcube`` EXAMPLES:: sage: from sage.features.rubiks import dikcube sage: dikcube().is_present() # optional - rubiks FeatureTestResult('dikcube', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import dikcube sage: isinstance(dikcube(), dikcube) True """ Executable.__init__(self, "dikcube", executable=RUBIKS_BINS_PREFIX + "dikcube", spkg="rubiks") class cubex(Executable): r""" A :class:`~sage.features.Feature` describing the presence of ``cubex`` EXAMPLES:: sage: from sage.features.rubiks import cubex sage: cubex().is_present() # optional - rubiks FeatureTestResult('cubex', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import cubex sage: isinstance(cubex(), cubex) True """ Executable.__init__(self, "cubex", executable=RUBIKS_BINS_PREFIX + "cubex", spkg="rubiks") class Rubiks(JoinFeature): r""" A :class:`~sage.features.Feature` describing the presence of ``cu2``, ``cubex``, ``dikcube``, ``mcube``, ``optimal``, and ``size222``. EXAMPLES:: sage: from sage.features.rubiks import Rubiks sage: Rubiks().is_present() # optional - rubiks FeatureTestResult('rubiks', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import Rubiks sage: isinstance(Rubiks(), Rubiks) True """ JoinFeature.__init__(self, "rubiks", [cu2(), size222(), optimal(), mcube(), dikcube(), cubex()], spkg="rubiks") def all_features(): return [Rubiks()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/rubiks.py
0.795102
0.330613
rubiks.py
pypi
r""" Features for testing the presence of various graph generator programs """ import os import subprocess from . import Executable, FeatureTestResult class Plantri(Executable): r""" A :class:`~sage.features.Feature` which checks for the ``plantri`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Plantri sage: Plantri().is_present() # optional - plantri FeatureTestResult('plantri', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Plantri sage: isinstance(Plantri(), Plantri) True """ Executable.__init__(self, name="plantri", spkg="plantri", executable="plantri", url="http://users.cecs.anu.edu.au/~bdm/plantri/") def is_functional(self): r""" Check whether ``plantri`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Plantri sage: Plantri().is_functional() # optional - plantri FeatureTestResult('plantri', True) """ command = ["plantri", "4"] try: lines = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b"1 triangulations written" if lines.find(expected) == -1: return FeatureTestResult(self, False, reason="Call `{command}` did not produce output which contains `{expected}`".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True) class Buckygen(Executable): r""" A :class:`~sage.features.Feature` which checks for the ``buckygen`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Buckygen sage: Buckygen().is_present() # optional - buckygen FeatureTestResult('buckygen', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Buckygen sage: isinstance(Buckygen(), Buckygen) True """ Executable.__init__(self, name="buckygen", spkg="buckygen", executable="buckygen", url="http://caagt.ugent.be/buckygen/") def is_functional(self): r""" Check whether ``buckygen`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Buckygen sage: Buckygen().is_functional() # optional - buckygen FeatureTestResult('buckygen', True) """ command = ["buckygen", "-d", "22d"] try: lines = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b"Number of fullerenes generated with 13 vertices: 0" if lines.find(expected) == -1: return FeatureTestResult(self, False, reason="Call `{command}` did not produce output which contains `{expected}`".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True) class Benzene(Executable): r""" A :class:`~sage.features.Feature` which checks for the ``benzene`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Benzene sage: Benzene().is_present() # optional - benzene FeatureTestResult('benzene', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Benzene sage: isinstance(Benzene(), Benzene) True """ Executable.__init__(self, name="benzene", spkg="benzene", executable="benzene", url="http://www.grinvin.org/") def is_functional(self): r""" Check whether ``benzene`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Benzene sage: Benzene().is_functional() # optional - benzene FeatureTestResult('benzene', True) """ devnull = open(os.devnull, 'wb') command = ["benzene", "2", "p"] try: lines = subprocess.check_output(command, stderr=devnull) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b">>planar_code<<" if not lines.startswith(expected): return FeatureTestResult(self, False, reason="Call `{command}` did not produce output that started with `{expected}`.".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True) def all_features(): return [Plantri(), Buckygen(), Benzene()]
/sagemath-environment-10.0b1.tar.gz/sagemath-environment-10.0b1/sage/features/graph_generators.py
0.829803
0.513425
graph_generators.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class SubobjectsCategory(RegressiveCovariantConstructionCategory): _functor_category = "Subobjects" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.Subobjects()`` Mathematical meaning: if `A` is a subobject of `B` in the category `C`, then `A` is also a subquotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``SubobjectsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subquotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.Subobjects()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, a subgroup of a group `G` is simultaneously a subquotient of `G`, a group by itself, and a submonoid of `G`:: sage: Groups().Subobjects().super_categories() [Category of groups, Category of subquotients of monoids, Category of subobjects of sets] Mind the last item above: there is indeed currently nothing implemented about submonoids. This resulted from the following call:: sage: sage.categories.subobjects.SubobjectsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of subobjects of sets """ return Category.join([category.Subquotients(), super().default_super_categories(category)])
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/subobjects.py
0.909975
0.476519
subobjects.py
pypi
from sage.misc.lazy_import import lazy_import from sage.categories.covariant_functorial_construction import CovariantFunctorialConstruction, CovariantConstructionCategory from sage.categories.pushout import MultivariateConstructionFunctor native_python_containers = set([tuple, list, set, frozenset, range]) class CartesianProductFunctor(CovariantFunctorialConstruction, MultivariateConstructionFunctor): """ The Cartesian product functor. EXAMPLES:: sage: cartesian_product The cartesian_product functorial construction ``cartesian_product`` takes a finite collection of sets, and constructs the Cartesian product of those sets:: sage: A = FiniteEnumeratedSet(['a','b','c']) sage: B = FiniteEnumeratedSet([1,2]) sage: C = cartesian_product([A, B]); C The Cartesian product of ({'a', 'b', 'c'}, {1, 2}) sage: C.an_element() ('a', 1) sage: C.list() # todo: not implemented [['a', 1], ['a', 2], ['b', 1], ['b', 2], ['c', 1], ['c', 2]] If those sets are endowed with more structure, say they are monoids (hence in the category ``Monoids()``), then the result is automatically endowed with its natural monoid structure:: sage: M = Monoids().example() sage: M An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd') sage: M.rename('M') sage: C = cartesian_product([M, ZZ, QQ]) sage: C The Cartesian product of (M, Integer Ring, Rational Field) sage: C.an_element() ('abcd', 1, 1/2) sage: C.an_element()^2 ('abcdabcd', 1, 1/4) sage: C.category() Category of Cartesian products of monoids sage: Monoids().CartesianProducts() Category of Cartesian products of monoids The Cartesian product functor is covariant: if ``A`` is a subcategory of ``B``, then ``A.CartesianProducts()`` is a subcategory of ``B.CartesianProducts()`` (see also :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`):: sage: C.categories() [Category of Cartesian products of monoids, Category of monoids, Category of Cartesian products of semigroups, Category of semigroups, Category of Cartesian products of unital magmas, Category of Cartesian products of magmas, Category of unital magmas, Category of magmas, Category of Cartesian products of sets, Category of sets, ...] [Category of Cartesian products of monoids, Category of monoids, Category of Cartesian products of semigroups, Category of semigroups, Category of Cartesian products of magmas, Category of unital magmas, Category of magmas, Category of Cartesian products of sets, Category of sets, Category of sets with partial maps, Category of objects] Hence, the role of ``Monoids().CartesianProducts()`` is solely to provide mathematical information and algorithms which are relevant to Cartesian product of monoids. For example, it specifies that the result is again a monoid, and that its multiplicative unit is the Cartesian product of the units of the underlying sets:: sage: C.one() ('', 1, 1) Those are implemented in the nested class :class:`Monoids.CartesianProducts <sage.categories.monoids.Monoids.CartesianProducts>` of ``Monoids(QQ)``. This nested class is itself a subclass of :class:`CartesianProductsCategory`. """ _functor_name = "cartesian_product" _functor_category = "CartesianProducts" symbol = " (+) " def __init__(self, category=None): r""" Constructor. See :class:`CartesianProductFunctor` for details. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: CartesianProductFunctor() The cartesian_product functorial construction """ CovariantFunctorialConstruction.__init__(self) self._forced_category = category from sage.categories.sets_cat import Sets if self._forced_category is not None: codomain = self._forced_category else: codomain = Sets() MultivariateConstructionFunctor.__init__(self, Sets(), codomain) def __call__(self, args, **kwds): r""" Functorial construction application. This specializes the generic ``__call__`` from :class:`CovariantFunctorialConstruction` to: - handle the following plain Python containers as input: :class:`frozenset`, :class:`list`, :class:`set`, :class:`tuple`, and :class:`xrange` (Python3 ``range``). - handle the empty list of factors. See the examples below. EXAMPLES:: sage: cartesian_product([[0,1], ('a','b','c')]) The Cartesian product of ({0, 1}, {'a', 'b', 'c'}) sage: _.category() Category of Cartesian products of finite enumerated sets sage: cartesian_product([set([0,1,2]), [0,1]]) The Cartesian product of ({0, 1, 2}, {0, 1}) sage: _.category() Category of Cartesian products of finite enumerated sets Check that the empty product is handled correctly: sage: C = cartesian_product([]) sage: C The Cartesian product of () sage: C.cardinality() 1 sage: C.an_element() () sage: C.category() Category of Cartesian products of sets Check that Python3 ``range`` is handled correctly:: sage: C = cartesian_product([range(2), range(2)]) sage: list(C) [(0, 0), (0, 1), (1, 0), (1, 1)] sage: C.category() Category of Cartesian products of finite enumerated sets """ if any(type(arg) in native_python_containers for arg in args): from sage.categories.sets_cat import Sets S = Sets() args = [S(a, enumerated_set=True) for a in args] elif not args: if self._forced_category is None: from sage.categories.sets_cat import Sets cat = Sets().CartesianProducts() else: cat = self._forced_category from sage.sets.cartesian_product import CartesianProduct return CartesianProduct((), cat) elif self._forced_category is not None: return super().__call__(args, category=self._forced_category, **kwds) return super().__call__(args, **kwds) def __eq__(self, other): r""" Comparison ignores the ``category`` parameter. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: cartesian_product([ZZ, ZZ]).construction()[0] == CartesianProductFunctor() True """ return isinstance(other, CartesianProductFunctor) def __ne__(self, other): r""" Comparison ignores the ``category`` parameter. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: cartesian_product([ZZ, ZZ]).construction()[0] != CartesianProductFunctor() False """ return not (self == other) class CartesianProductsCategory(CovariantConstructionCategory): r""" An abstract base class for all ``CartesianProducts`` categories. TESTS:: sage: C = Sets().CartesianProducts() sage: C Category of Cartesian products of sets sage: C.base_category() Category of sets sage: latex(C) \mathbf{CartesianProducts}(\mathbf{Sets}) """ _functor_category = "CartesianProducts" def _repr_object_names(self): """ EXAMPLES:: sage: ModulesWithBasis(QQ).CartesianProducts() # indirect doctest Category of Cartesian products of vector spaces with basis over Rational Field """ # This method is only required for the capital `C` return "Cartesian products of %s"%(self.base_category()._repr_object_names()) def CartesianProducts(self): """ Return the category of (finite) Cartesian products of objects of ``self``. By associativity of Cartesian products, this is ``self`` (a Cartesian product of Cartesian products of `A`'s is a Cartesian product of `A`'s). EXAMPLES:: sage: ModulesWithBasis(QQ).CartesianProducts().CartesianProducts() Category of Cartesian products of vector spaces with basis over Rational Field """ return self def base_ring(self): """ The base ring of a Cartesian product is the base ring of the underlying category. EXAMPLES:: sage: Algebras(ZZ).CartesianProducts().base_ring() Integer Ring """ return self.base_category().base_ring() # Moved to avoid circular imports lazy_import('sage.categories.sets_cat', 'cartesian_product') """ The Cartesian product functorial construction See :class:`CartesianProductFunctor` for more information EXAMPLES:: sage: cartesian_product The cartesian_product functorial construction """
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/cartesian_product.py
0.711331
0.521106
cartesian_product.py
pypi
from sage.misc.bindable_class import BindableClass from sage.categories.category import Category from sage.categories.category_types import Category_over_base from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class RealizationsCategory(RegressiveCovariantConstructionCategory): """ An abstract base class for all categories of realizations category Relization are implemented as :class:`~sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory`. See there for the documentation of how the various bindings such as ``Sets().Realizations()`` and ``P.Realizations()``, where ``P`` is a parent, work. .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` TESTS:: sage: Sets().Realizations <bound method Realizations of Category of sets> sage: Sets().Realizations() Category of realizations of sets sage: Sets().Realizations().super_categories() [Category of sets] sage: Groups().Realizations().super_categories() [Category of groups, Category of realizations of unital magmas] """ _functor_category = "Realizations" def Realizations(self): """ Return the category of realizations of the parent ``self`` or of objects of the category ``self`` INPUT: - ``self`` -- a parent or a concrete category .. NOTE:: this *function* is actually inserted as a *method* in the class :class:`~sage.categories.category.Category` (see :meth:`~sage.categories.category.Category.Realizations`). It is defined here for code locality reasons. EXAMPLES: The category of realizations of some algebra:: sage: Algebras(QQ).Realizations() Join of Category of algebras over Rational Field and Category of realizations of unital magmas The category of realizations of a given algebra:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field sage: A.Realizations() Category of realizations of The subset algebra of {1, 2, 3} over Rational Field sage: C = GradedHopfAlgebrasWithBasis(QQ).Realizations(); C Join of Category of graded hopf algebras with basis over Rational Field and Category of realizations of hopf algebras over Rational Field sage: C.super_categories() [Category of graded hopf algebras with basis over Rational Field, Category of realizations of hopf algebras over Rational Field] sage: TestSuite(C).run() .. SEEALSO:: - :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` - :class:`ClasscallMetaclass` .. TODO:: Add an optional argument to allow for:: sage: Realizations(A, category = Blahs()) # todo: not implemented """ if isinstance(self, Category): return RealizationsCategory.category_of(self) else: return getattr(self.__class__, "Realizations")(self) Category.Realizations = Realizations class Category_realization_of_parent(Category_over_base, BindableClass): """ An abstract base class for categories of all realizations of a given parent INPUT: - ``parent_with_realization`` -- a parent .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` EXAMPLES:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field The role of this base class is to implement some technical goodies, like the binding ``A.Realizations()`` when a subclass ``Realizations`` is implemented as a nested class in ``A`` (see the :mod:`code of the example <sage.categories.examples.with_realizations.SubsetAlgebra>`):: sage: C = A.Realizations(); C Category of realizations of The subset algebra of {1, 2, 3} over Rational Field as well as the name for that category. """ def __init__(self, parent_with_realization): """ TESTS:: sage: from sage.categories.realizations import Category_realization_of_parent sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field sage: C = A.Realizations(); C Category of realizations of The subset algebra of {1, 2, 3} over Rational Field sage: isinstance(C, Category_realization_of_parent) True sage: C.parent_with_realization The subset algebra of {1, 2, 3} over Rational Field sage: TestSuite(C).run(skip=["_test_category_over_bases"]) .. TODO:: Fix the failing test by making ``C`` a singleton category. This will require some fiddling with the assertion in :meth:`Category_singleton.__classcall__` """ Category_over_base.__init__(self, parent_with_realization) self.parent_with_realization = parent_with_realization def _get_name(self): """ Return a human readable string specifying which kind of bases this category is for It is obtained by splitting and lower casing the last part of the class name. EXAMPLES:: sage: from sage.categories.realizations import Category_realization_of_parent sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent): ....: def super_categories(self): return [Objects()] sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") sage: MultiplicativeBasesOnPrimitiveElements(Sym)._get_name() 'multiplicative bases on primitive elements' """ import re return re.sub(".[A-Z]", lambda s: s.group()[0]+" "+s.group()[1], self.__class__.__base__.__name__.split(".")[-1]).lower() def _repr_object_names(self): """ Return the name of the objects of this category. .. SEEALSO:: :meth:`Category._repr_object_names` EXAMPLES:: sage: from sage.categories.realizations import Category_realization_of_parent sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent): ....: def super_categories(self): return [Objects()] sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") sage: C = MultiplicativeBasesOnPrimitiveElements(Sym); C Category of multiplicative bases on primitive elements of Sym sage: C._repr_object_names() 'multiplicative bases on primitive elements of Sym' """ return "{} of {}".format(self._get_name(), self.base())
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/realizations.py
0.836187
0.606571
realizations.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class QuotientsCategory(RegressiveCovariantConstructionCategory): _functor_category = "Quotients" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.Quotients()`` Mathematical meaning: if `A` is a quotient of `B` in the category `C`, then `A` is also a subquotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``QuotientsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subquotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.Quotients()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, a subgroup of a group `G` is simultaneously a subquotient of `G`, a group by itself, and a quotient monoid of ``G``:: sage: Groups().Quotients().super_categories() [Category of groups, Category of subquotients of monoids, Category of quotients of semigroups] Mind the last item above: there is indeed currently nothing implemented about quotient monoids. This resulted from the following call:: sage: sage.categories.quotients.QuotientsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups """ return Category.join([category.Subquotients(), super().default_super_categories(category)])
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/quotients.py
0.915207
0.565359
quotients.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory def WithRealizations(self): r""" Return the category of parents in ``self`` endowed with multiple realizations. INPUT: - ``self`` -- a category .. SEEALSO:: - The documentation and code (:mod:`sage.categories.examples.with_realizations`) of ``Sets().WithRealizations().example()`` for more on how to use and implement a parent with several realizations. - Various use cases: - :class:`SymmetricFunctions` - :class:`QuasiSymmetricFunctions` - :class:`NonCommutativeSymmetricFunctions` - :class:`SymmetricFunctionsNonCommutingVariables` - :class:`DescentAlgebra` - :class:`algebras.Moebius` - :class:`IwahoriHeckeAlgebra` - :class:`ExtendedAffineWeylGroup` - The `Implementing Algebraic Structures <../../../../../thematic_tutorials/tutorial-implementing-algebraic-structures>`_ thematic tutorial. - :mod:`sage.categories.realizations` .. NOTE:: this *function* is actually inserted as a *method* in the class :class:`~sage.categories.category.Category` (see :meth:`~sage.categories.category.Category.WithRealizations`). It is defined here for code locality reasons. EXAMPLES:: sage: Sets().WithRealizations() Category of sets with realizations .. RUBRIC:: Parent with realizations Let us now explain the concept of realizations. A *parent with realizations* is a facade parent (see :class:`Sets.Facade`) admitting multiple concrete realizations where its elements are represented. Consider for example an algebra `A` which admits several natural bases:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field For each such basis `B` one implements a parent `P_B` which realizes `A` with its elements represented by expanding them on the basis `B`:: sage: A.F() The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis sage: A.Out() The subset algebra of {1, 2, 3} over Rational Field in the Out basis sage: A.In() The subset algebra of {1, 2, 3} over Rational Field in the In basis sage: A.an_element() F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}] If `B` and `B'` are two bases, then the change of basis from `B` to `B'` is implemented by a canonical coercion between `P_B` and `P_{B'}`:: sage: F = A.F(); In = A.In(); Out = A.Out() sage: i = In.an_element(); i In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}] sage: F(i) 7*F[{}] + 3*F[{1}] + 4*F[{2}] + F[{1, 2}] sage: F.coerce_map_from(Out) Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis allowing for mixed arithmetic:: sage: (1 + Out.from_set(1)) * In.from_set(2,3) Out[{}] + 2*Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}] + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}] In our example, there are three realizations:: sage: A.realizations() [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis, The subset algebra of {1, 2, 3} over Rational Field in the In basis, The subset algebra of {1, 2, 3} over Rational Field in the Out basis] Instead of manually defining the shorthands ``F``, ``In``, and ``Out``, as above one can just do:: sage: A.inject_shorthands() Defining F as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis Defining In as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the In basis Defining Out as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Out basis .. RUBRIC:: Rationale Besides some goodies described below, the role of `A` is threefold: - To provide, as illustrated above, a single entry point for the algebra as a whole: documentation, access to its properties and different realizations, etc. - To provide a natural location for the initialization of the bases and the coercions between, and other methods that are common to all bases. - To let other objects refer to `A` while allowing elements to be represented in any of the realizations. We now illustrate this second point by defining the polynomial ring with coefficients in `A`:: sage: P = A['x']; P Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field sage: x = P.gen() In the following examples, the coefficients turn out to be all represented in the `F` basis:: sage: P.one() F[{}] sage: (P.an_element() + 1)^2 F[{}]*x^2 + 2*F[{}]*x + F[{}] However we can create a polynomial with mixed coefficients, and compute with it:: sage: p = P([1, In[{1}], Out[{2}] ]); p Out[{2}]*x^2 + In[{1}]*x + F[{}] sage: p^2 Out[{2}]*x^4 + (-8*In[{}] + 4*In[{1}] + 8*In[{2}] + 4*In[{3}] - 4*In[{1, 2}] - 2*In[{1, 3}] - 4*In[{2, 3}] + 2*In[{1, 2, 3}])*x^3 + (F[{}] + 3*F[{1}] + 2*F[{2}] - 2*F[{1, 2}] - 2*F[{2, 3}] + 2*F[{1, 2, 3}])*x^2 + (2*F[{}] + 2*F[{1}])*x + F[{}] Note how each coefficient involves a single basis which need not be that of the other coefficients. Which basis is used depends on how coercion happened during mixed arithmetic and needs not be deterministic. One can easily coerce all coefficient to a given basis with:: sage: p.map_coefficients(In) (-4*In[{}] + 2*In[{1}] + 4*In[{2}] + 2*In[{3}] - 2*In[{1, 2}] - In[{1, 3}] - 2*In[{2, 3}] + In[{1, 2, 3}])*x^2 + In[{1}]*x + In[{}] Alas, the natural notation for constructing such polynomials does not yet work:: sage: In[{1}] * x Traceback (most recent call last): ... TypeError: unsupported operand parent(s) for *: 'The subset algebra of {1, 2, 3} over Rational Field in the In basis' and 'Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field' .. RUBRIC:: The category of realizations of `A` The set of all realizations of `A`, together with the coercion morphisms is a category (whose class inherits from :class:`~sage.categories.realizations.Category_realization_of_parent`):: sage: A.Realizations() Category of realizations of The subset algebra of {1, 2, 3} over Rational Field The various parent realizing `A` belong to this category:: sage: A.F() in A.Realizations() True `A` itself is in the category of algebras with realizations:: sage: A in Algebras(QQ).WithRealizations() True The (mostly technical) ``WithRealizations`` categories are the analogs of the ``*WithSeveralBases`` categories in MuPAD-Combinat. They provide support tools for handling the different realizations and the morphisms between them. Typically, ``VectorSpaces(QQ).FiniteDimensional().WithRealizations()`` will eventually be in charge, whenever a coercion `\phi: A\mapsto B` is registered, to register `\phi^{-1}` as coercion `B \mapsto A` if there is none defined yet. To achieve this, ``FiniteDimensionalVectorSpaces`` would provide a nested class ``WithRealizations`` implementing the appropriate logic. ``WithRealizations`` is a :mod:`regressive covariant functorial construction <sage.categories.covariant_functorial_construction>`. On our example, this simply means that `A` is automatically in the category of rings with realizations (covariance):: sage: A in Rings().WithRealizations() True and in the category of algebras (regressiveness):: sage: A in Algebras(QQ) True .. NOTE:: For ``C`` a category, ``C.WithRealizations()`` in fact calls ``sage.categories.with_realizations.WithRealizations(C)``. The later is responsible for building the hierarchy of the categories with realizations in parallel to that of their base categories, optimizing away those categories that do not provide a ``WithRealizations`` nested class. See :mod:`sage.categories.covariant_functorial_construction` for the technical details. .. NOTE:: Design question: currently ``WithRealizations`` is a regressive construction. That is ``self.WithRealizations()`` is a subcategory of ``self`` by default:: sage: Algebras(QQ).WithRealizations().super_categories() [Category of algebras over Rational Field, Category of monoids with realizations, Category of additive unital additive magmas with realizations] Is this always desirable? For example, ``AlgebrasWithBasis(QQ).WithRealizations()`` should certainly be a subcategory of ``Algebras(QQ)``, but not of ``AlgebrasWithBasis(QQ)``. This is because ``AlgebrasWithBasis(QQ)`` is specifying something about the concrete realization. TESTS:: sage: Semigroups().WithRealizations() Join of Category of semigroups and Category of sets with realizations sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C Category of graded hopf algebras with basis over Rational Field with realizations sage: C.super_categories() [Join of Category of hopf algebras over Rational Field and Category of graded algebras over Rational Field and Category of graded coalgebras over Rational Field] sage: TestSuite(Semigroups().WithRealizations()).run() """ return WithRealizationsCategory.category_of(self) Category.WithRealizations = WithRealizations class WithRealizationsCategory(RegressiveCovariantConstructionCategory): """ An abstract base class for all categories of parents with multiple realizations. .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` The role of this base class is to implement some technical goodies, such as the name for that category. """ _functor_category = "WithRealizations" def _repr_(self): """ String representation. EXAMPLES:: sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C #indirect doctest Category of graded hopf algebras with basis over Rational Field with realizations """ s = repr(self.base_category()) return s+" with realizations"
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/with_realizations.py
0.946621
0.796372
with_realizations.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class IsomorphicObjectsCategory(RegressiveCovariantConstructionCategory): _functor_category = "IsomorphicObjects" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.IsomorphicObjects()`` Mathematical meaning: if `A` is the image of `B` by an isomorphism in the category `C`, then `A` is both a subobject of `B` and a quotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``IsomorphicObjectsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subobjects()`` and ``category.Quotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.IsomorphicObjects()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, the image of a group `G'` by a group isomorphism is simultaneously a subgroup of `G`, a subquotient of `G`, a group by itself, and the image of `G` by a monoid isomorphism:: sage: Groups().IsomorphicObjects().super_categories() [Category of groups, Category of subquotients of monoids, Category of quotients of semigroups, Category of isomorphic objects of sets] Mind the last item above: there is indeed currently nothing implemented about isomorphic objects of monoids. This resulted from the following call:: sage: sage.categories.isomorphic_objects.IsomorphicObjectsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups and Category of isomorphic objects of sets """ return Category.join([category.Subobjects(), category.Quotients(), super().default_super_categories(category)])
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/categories/isomorphic_objects.py
0.90881
0.620995
isomorphic_objects.py
pypi
"IntegerFactorization objects" from sage.structure.factorization import Factorization from sage.rings.integer_ring import ZZ class IntegerFactorization(Factorization): """ A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` object upon initialization. However, for the typical use of integer factorization via the ``Integer.factor()`` method in ``sage.rings.integer`` this is noticeably too much overhead, slowing down the factorization of integers of up to about 40 bits by a factor of around 10. Moreover, the initialization done in the ``Factorization`` class is typically unnecessary: the caller can guarantee that the list contains pairs of an ``Integer`` and an ``int``, as well as that the list is sorted. AUTHOR: - Sebastian Pancratz (2010-01-10) """ def __init__(self, x, unit=None, cr=False, sort=True, simplify=True, unsafe=False): """ Set ``self`` to the factorization object with list ``x``, which must be a sorted list of pairs, where each pair contains a factor and an exponent. If the flag ``unsafe`` is set to ``False`` this method delegates the initialization to the parent class, which means that a rather lenient and careful way of initialization is chosen. For example, elements are coerced or converted into the right parents, multiple occurrences of the same factor are collected (in the commutative case), the list is sorted (unless ``sort`` is ``False``) etc. However, if the flag is set to ``True``, no error handling is carried out. The list ``x`` is assumed to list of pairs. The type of the factors is assumed to be constant across all factors: either ``Integer`` (the generic case) or ``int`` (as supported by the flag ``int_`` of the ``factor()`` method). The type of the exponents is assumed to be ``int``. The list ``x`` itself will be referenced in this factorization object and hence the caller is responsible for not changing the list after creating the factorization. The unit is assumed to be either ``None`` or of type ``Integer``, taking one of the values `+1` or `-1`. EXAMPLES:: sage: factor(15) 3 * 5 We check that :trac:`13139` is fixed:: sage: from sage.structure.factorization_integer import IntegerFactorization sage: IntegerFactorization([(3, 1)], unsafe=True) 3 """ if unsafe: if unit is None: self._Factorization__unit = ZZ._one_element else: self._Factorization__unit = unit self._Factorization__x = x self._Factorization__universe = ZZ self._Factorization__cr = cr if sort: self.sort() if simplify: self.simplify() else: super().__init__(x, unit=unit, cr=cr, sort=sort, simplify=simplify) def __sort__(self, key=None): """ Sort the factors in this factorization. INPUT: - ``key`` -- (default: ``None``) comparison key EXAMPLES:: sage: F = factor(15) sage: F.sort(key=lambda x: -x[0]) sage: F 5 * 3 """ if key is not None: self.__x.sort(key=key) else: self.__x.sort()
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/structure/factorization_integer.py
0.918845
0.720848
factorization_integer.py
pypi
r""" Iterable of the keys of a Mapping associated with nonzero values """ from collections.abc import MappingView, Sequence, Set from sage.misc.superseded import deprecation class SupportView(MappingView, Sequence, Set): r""" Dynamic view of the set of keys of a dictionary that are associated with nonzero values It behaves like the objects returned by the :meth:`keys`, :meth:`values`, :meth:`items` of a dictionary (or other :class:`collections.abc.Mapping` classes). INPUT: - ``mapping`` -- a :class:`dict` or another :class:`collections.abc.Mapping`. - ``zero`` -- (optional) test for zeroness by comparing with this value. EXAMPLES:: sage: d = {'a': 47, 'b': 0, 'c': 11} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({'a': 47, 'b': 0, 'c': 11}) sage: 'a' in supp, 'b' in supp, 'z' in supp (True, False, False) sage: len(supp) 2 sage: list(supp) ['a', 'c'] sage: supp[0], supp[1] ('a', 'c') sage: supp[-1] 'c' sage: supp[:] ('a', 'c') It reflects changes to the underlying dictionary:: sage: d['b'] = 815 sage: len(supp) 3 """ def __init__(self, mapping, *, zero=None): r""" TESTS:: sage: from sage.structure.support_view import SupportView sage: supp = SupportView({'a': 'b', 'c': ''}, zero='') sage: len(supp) 1 """ self._mapping = mapping self._zero = zero def __len__(self): r""" TESTS:: sage: d = {'a': 47, 'b': 0, 'c': 11} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({'a': 47, 'b': 0, 'c': 11}) sage: len(supp) 2 """ length = 0 for key in self: length += 1 return length def __getitem__(self, index): r""" TESTS:: sage: d = {'a': 47, 'b': 0, 'c': 11} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({'a': 47, 'b': 0, 'c': 11}) sage: supp[2] Traceback (most recent call last): ... IndexError """ if isinstance(index, slice): return tuple(self)[index] if index < 0: return tuple(self)[index] for i, key in enumerate(self): if i == index: return key raise IndexError def __iter__(self): r""" TESTS:: sage: d = {'a': 47, 'b': 0, 'c': 11} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({'a': 47, 'b': 0, 'c': 11}) sage: iter(supp) <generator object SupportView.__iter__ at ...> """ zero = self._zero if zero is None: for key, value in self._mapping.items(): if value: yield key else: for key, value in self._mapping.items(): if value != zero: yield key def __contains__(self, key): r""" TESTS:: sage: d = {'a': 47, 'b': 0, 'c': 11} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({'a': 47, 'b': 0, 'c': 11}) sage: 'a' in supp, 'b' in supp, 'z' in supp (True, False, False) """ try: value = self._mapping[key] except KeyError: return False zero = self._zero if zero is None: return bool(value) return value != zero def __eq__(self, other): r""" TESTS:: sage: d = {1: 17, 2: 0} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({1: 17, 2: 0}) sage: supp == [1] doctest:warning... DeprecationWarning: comparing a SupportView with a list is deprecated See https://github.com/sagemath/sage/issues/34509 for details. True """ if isinstance(other, list): deprecation(34509, 'comparing a SupportView with a list is deprecated') return list(self) == other return NotImplemented def __ne__(self, other): r""" TESTS:: sage: d = {1: 17, 2: 0} sage: from sage.structure.support_view import SupportView sage: supp = SupportView(d); supp SupportView({1: 17, 2: 0}) sage: supp != [1] doctest:warning... DeprecationWarning: comparing a SupportView with a list is deprecated See https://github.com/sagemath/sage/issues/34509 for details. False """ if isinstance(other, list): deprecation(34509, 'comparing a SupportView with a list is deprecated') return list(self) != other return NotImplemented
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/structure/support_view.py
0.914133
0.74269
support_view.py
pypi
import os from sage.misc.temporary_file import tmp_filename from sage.misc.superseded import deprecation from sage.structure.sage_object import SageObject import sage.doctest deprecation(32988, 'the module sage.structure.graphics_file is deprecated') class Mime(): TEXT = 'text/plain' HTML = 'text/html' LATEX = 'text/latex' JSON = 'application/json' JAVASCRIPT = 'application/javascript' PDF = 'application/pdf' PNG = 'image/png' JPG = 'image/jpeg' SVG = 'image/svg+xml' JMOL = 'application/jmol' @classmethod def validate(cls, value): """ Check that input is known mime type INPUT: - ``value`` -- string. OUTPUT: Unicode string of that mime type. A ``ValueError`` is raised if input is incorrect / unknown. EXAMPLES:: sage: from sage.structure.graphics_file import Mime doctest:warning... DeprecationWarning: the module sage.structure.graphics_file is deprecated See https://github.com/sagemath/sage/issues/32988 for details. sage: Mime.validate('image/png') 'image/png' sage: Mime.validate('foo/bar') Traceback (most recent call last): ... ValueError: unknown mime type """ value = str(value).lower() for k, v in cls.__dict__.items(): if isinstance(v, str) and v == value: return v raise ValueError('unknown mime type') @classmethod def extension(cls, mime_type): """ Return file extension. INPUT: - ``mime_type`` -- mime type as string. OUTPUT: String containing the usual file extension for that type of file. Excludes ``os.extsep``. EXAMPLES:: sage: from sage.structure.graphics_file import Mime sage: Mime.extension('image/png') 'png' """ try: return preferred_filename_ext[mime_type] except KeyError: raise ValueError('no known extension for mime type') preferred_filename_ext = { Mime.TEXT: 'txt', Mime.HTML: 'html', Mime.LATEX: 'tex', Mime.JSON: 'json', Mime.JAVASCRIPT: 'js', Mime.PDF: 'pdf', Mime.PNG: 'png', Mime.JPG: 'jpg', Mime.SVG: 'svg', Mime.JMOL: 'spt.zip', } mimetype_for_ext = dict( (value, key) for (key, value) in preferred_filename_ext.items() ) class GraphicsFile(SageObject): def __init__(self, filename, mime_type=None): """ Wrapper around a graphics file. """ self._filename = filename if mime_type is None: mime_type = self._guess_mime_type(filename) self._mime = Mime.validate(mime_type) def _guess_mime_type(self, filename): """ Guess mime type from file extension """ ext = os.path.splitext(filename)[1] ext = ext.lstrip(os.path.extsep) try: return mimetype_for_ext[ext] except KeyError: raise ValueError('unknown file extension, please specify mime type') def _repr_(self): """ Return a string representation. """ return 'Graphics file {0}'.format(self.mime()) def filename(self): return self._filename def save_as(self, filename): """ Make the file available under a new filename. INPUT: - ``filename`` -- string. The new filename. The newly-created ``filename`` will be a hardlink if possible. If not, an independent copy is created. """ try: os.link(self.filename(), filename) except OSError: import shutil shutil.copy2(self.filename(), filename) def mime(self): return self._mime def data(self): """ Return a byte string containing the image file. """ with open(self._filename, 'rb') as f: return f.read() def launch_viewer(self): """ Launch external viewer for the graphics file. .. note:: Does not actually launch a new process when doctesting. EXAMPLES:: sage: from sage.structure.graphics_file import GraphicsFile sage: g = GraphicsFile('/tmp/test.png', 'image/png') sage: g.launch_viewer() """ if sage.doctest.DOCTEST_MODE: return if self.mime() == Mime.JMOL: return self._launch_jmol() from sage.misc.viewer import viewer command = viewer(preferred_filename_ext[self.mime()]) os.system('{0} {1} 2>/dev/null 1>/dev/null &' .format(command, self.filename())) # TODO: keep track of opened processes... def _launch_jmol(self): launch_script = tmp_filename(ext='.spt') with open(launch_script, 'w') as f: f.write('set defaultdirectory "{0}"\n'.format(self.filename())) f.write('script SCRIPT\n') os.system('jmol {0} 2>/dev/null 1>/dev/null &' .format(launch_script)) def graphics_from_save(save_function, preferred_mime_types, allowed_mime_types=None, figsize=None, dpi=None): """ Helper function to construct a graphics file. INPUT: - ``save_function`` -- callable that can save graphics to a file and accepts options like :meth:`sage.plot.graphics.Graphics.save`. - ``preferred_mime_types`` -- list of mime types. The graphics output mime types in order of preference (i.e. best quality to worst). - ``allowed_mime_types`` -- set of mime types (as strings). The graphics types that we can display. Output, if any, will be one of those. - ``figsize`` -- pair of integers (optional). The desired graphics size in pixels. Suggested, but need not be respected by the output. - ``dpi`` -- integer (optional). The desired resolution in dots per inch. Suggested, but need not be respected by the output. OUTPUT: Return an instance of :class:`sage.structure.graphics_file.GraphicsFile` encapsulating a suitable image file. Image is one of the ``preferred_mime_types``. If ``allowed_mime_types`` is specified, the resulting file format matches one of these. Alternatively, this function can return ``None`` to indicate that textual representation is preferable and/or no graphics with the desired mime type can be generated. """ # Figure out best mime type mime = None if allowed_mime_types is None: mime = Mime.PNG else: # order of preference for m in preferred_mime_types: if m in allowed_mime_types: mime = m break if mime is None: return None # don't know how to generate suitable graphics # Generate suitable temp file filename = tmp_filename(ext=os.path.extsep + Mime.extension(mime)) # Call the save_function with the right arguments kwds = {} if figsize is not None: kwds['figsize'] = figsize if dpi is not None: kwds['dpi'] = dpi save_function(filename, **kwds) return GraphicsFile(filename, mime)
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/structure/graphics_file.py
0.548674
0.236401
graphics_file.py
pypi
def arithmetic(t=None): """ Controls the default proof strategy for integer arithmetic algorithms (such as primality testing). INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires integer arithmetic operations to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows integer arithmetic operations to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the integer arithmetic proof status. EXAMPLES:: sage: proof.arithmetic() True sage: proof.arithmetic(False) sage: proof.arithmetic() False sage: proof.arithmetic(True) sage: proof.arithmetic() True """ from .proof import _proof_prefs return _proof_prefs.arithmetic(t) def elliptic_curve(t=None): """ Controls the default proof strategy for elliptic curve algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires elliptic curve algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows elliptic curve algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current elliptic curve proof status. EXAMPLES:: sage: proof.elliptic_curve() True sage: proof.elliptic_curve(False) sage: proof.elliptic_curve() False sage: proof.elliptic_curve(True) sage: proof.elliptic_curve() True """ from .proof import _proof_prefs return _proof_prefs.elliptic_curve(t) def linear_algebra(t=None): """ Controls the default proof strategy for linear algebra algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires linear algebra algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows linear algebra algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current linear algebra proof status. EXAMPLES:: sage: proof.linear_algebra() True sage: proof.linear_algebra(False) sage: proof.linear_algebra() False sage: proof.linear_algebra(True) sage: proof.linear_algebra() True """ from .proof import _proof_prefs return _proof_prefs.linear_algebra(t) def number_field(t=None): """ Controls the default proof strategy for number field algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires number field algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows number field algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current number field proof status. EXAMPLES:: sage: proof.number_field() True sage: proof.number_field(False) sage: proof.number_field() False sage: proof.number_field(True) sage: proof.number_field() True """ from .proof import _proof_prefs return _proof_prefs.number_field(t) def polynomial(t=None): """ Controls the default proof strategy for polynomial algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires polynomial algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows polynomial algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current polynomial proof status. EXAMPLES:: sage: proof.polynomial() True sage: proof.polynomial(False) sage: proof.polynomial() False sage: proof.polynomial(True) sage: proof.polynomial() True """ from .proof import _proof_prefs return _proof_prefs.polynomial(t) def all(t=None): """ Controls the default proof strategy throughout Sage. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires Sage algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows Sage algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current global Sage proof status. EXAMPLES:: sage: proof.all() {'arithmetic': True, 'elliptic_curve': True, 'linear_algebra': True, 'number_field': True, 'other': True, 'polynomial': True} sage: proof.number_field(False) sage: proof.number_field() False sage: proof.all() {'arithmetic': True, 'elliptic_curve': True, 'linear_algebra': True, 'number_field': False, 'other': True, 'polynomial': True} sage: proof.number_field(True) sage: proof.number_field() True """ from .proof import _proof_prefs if t is None: return _proof_prefs._require_proof.copy() for s in _proof_prefs._require_proof: _proof_prefs._require_proof[s] = bool(t) from .proof import WithProof
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/structure/proof/all.py
0.919566
0.865338
all.py
pypi
"Global proof preferences" from sage.structure.sage_object import SageObject class _ProofPref(SageObject): """ An object that holds global proof preferences. For now these are merely True/False flags for various parts of Sage that use probabilistic algorithms. A True flag means that the subsystem (such as linear algebra or number fields) should return results that are true unconditionally: the correctness should not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. A False flag means that the subsystem can use faster methods to return answers that have a very small probability of being wrong. """ def __init__(self, proof = True): self._require_proof = {} self._require_proof["arithmetic"] = proof self._require_proof["elliptic_curve"] = proof self._require_proof["linear_algebra"] = proof self._require_proof["number_field"] = proof self._require_proof["polynomial"] = proof self._require_proof["other"] = proof def arithmetic(self, t = None): """ Controls the default proof strategy for integer arithmetic algorithms (such as primality testing). INPUT: t -- boolean or None OUTPUT: If t == True, requires integer arithmetic operations to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows integer arithmetic operations to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the integer arithmetic proof status. EXAMPLES:: sage: proof.arithmetic() True sage: proof.arithmetic(False) sage: proof.arithmetic() False sage: proof.arithmetic(True) sage: proof.arithmetic() True """ if t is None: return self._require_proof["arithmetic"] self._require_proof["arithmetic"] = bool(t) def elliptic_curve(self, t = None): """ Controls the default proof strategy for elliptic curve algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires elliptic curve algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows elliptic curve algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current elliptic curve proof status. EXAMPLES:: sage: proof.elliptic_curve() True sage: proof.elliptic_curve(False) sage: proof.elliptic_curve() False sage: proof.elliptic_curve(True) sage: proof.elliptic_curve() True """ if t is None: return self._require_proof["elliptic_curve"] self._require_proof["elliptic_curve"] = bool(t) def linear_algebra(self, t = None): """ Controls the default proof strategy for linear algebra algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires linear algebra algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows linear algebra algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current linear algebra proof status. EXAMPLES:: sage: proof.linear_algebra() True sage: proof.linear_algebra(False) sage: proof.linear_algebra() False sage: proof.linear_algebra(True) sage: proof.linear_algebra() True """ if t is None: return self._require_proof["linear_algebra"] self._require_proof["linear_algebra"] = bool(t) def number_field(self, t = None): """ Controls the default proof strategy for number field algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires number field algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows number field algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current number field proof status. EXAMPLES:: sage: proof.number_field() True sage: proof.number_field(False) sage: proof.number_field() False sage: proof.number_field(True) sage: proof.number_field() True """ if t is None: return self._require_proof["number_field"] self._require_proof["number_field"] = bool(t) def polynomial(self, t = None): """ Controls the default proof strategy for polynomial algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires polynomial algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows polynomial algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current polynomial proof status. EXAMPLES:: sage: proof.polynomial() True sage: proof.polynomial(False) sage: proof.polynomial() False sage: proof.polynomial(True) sage: proof.polynomial() True """ if t is None: return self._require_proof["polynomial"] self._require_proof["polynomial"] = bool(t) _proof_prefs = _ProofPref(True) #Creates the global object that stores proof preferences. def get_flag(t = None, subsystem = None): """ Used for easily determining the correct proof flag to use. EXAMPLES:: sage: from sage.structure.proof.proof import get_flag sage: get_flag(False) False sage: get_flag(True) True sage: get_flag() True sage: proof.all(False) sage: get_flag() False """ if t is None: if subsystem in ["arithmetic", "elliptic_curve", "linear_algebra", "number_field","polynomial"]: return _proof_prefs._require_proof[subsystem] else: return _proof_prefs._require_proof["other"] return t class WithProof(): """ Use WithProof to temporarily set the value of one of the proof systems for a block of code, with a guarantee that it will be set back to how it was before after the block is done, even if there is an error. EXAMPLES:: sage: proof.arithmetic(True) sage: with proof.WithProof('arithmetic',False): # this would hang "forever" if attempted with proof=True ....: print((10^1000 + 453).is_prime()) ....: print(1/0) Traceback (most recent call last): ... ZeroDivisionError: rational division by zero sage: proof.arithmetic() True """ def __init__(self, subsystem, t): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False); P <sage.structure.proof.proof.WithProof object at ...> sage: P._subsystem 'arithmetic' sage: P._t False sage: P._t_orig True """ self._subsystem = str(subsystem) self._t = bool(t) self._t_orig = _proof_prefs._require_proof[subsystem] def __enter__(self): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False) sage: P.__enter__() sage: proof.arithmetic() False sage: proof.arithmetic(True) """ _proof_prefs._require_proof[self._subsystem] = self._t def __exit__(self, *args): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False) sage: P.__enter__() sage: proof.arithmetic() False sage: P.__exit__() sage: proof.arithmetic() True """ _proof_prefs._require_proof[self._subsystem] = self._t_orig
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/structure/proof/proof.py
0.89219
0.614365
proof.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.richcmp import richcmp_method, rich_to_bool class UnknownError(TypeError): """ Raised whenever :class:`Unknown` is used in a boolean operation. EXAMPLES:: sage: not Unknown Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context """ pass @richcmp_method class UnknownClass(UniqueRepresentation): """ The Unknown truth value The ``Unknown`` object is used in Sage in several places as return value in addition to ``True`` and ``False``, in order to signal uncertainty about or inability to compute the result. ``Unknown`` can be identified using ``is``, or by catching :class:`UnknownError` from a boolean operation. .. WARNING:: Calling ``bool()`` with ``Unknown`` as argument will throw an ``UnknownError``. This also means that applying ``and``, ``not``, and ``or`` to ``Unknown`` might fail. TESTS:: sage: TestSuite(Unknown).run() """ def __repr__(self): """ TESTS:: sage: Unknown Unknown """ return "Unknown" def __bool__(self): """ When evaluated in a boolean context ``Unknown`` raises a ``UnknownError``. EXAMPLES:: sage: bool(Unknown) Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context sage: not Unknown Traceback (most recent call last): ... UnknownError: Unknown does not evaluate in boolean context """ raise UnknownError('Unknown does not evaluate in boolean context') def __and__(self, other): """ The ``&`` logical operation. EXAMPLES:: sage: Unknown & False False sage: Unknown & Unknown Unknown sage: Unknown & True Unknown sage: Unknown.__or__(3) NotImplemented """ if other is False: return False elif other is True or other is Unknown: return self else: return NotImplemented def __or__(self, other): """ The ``|`` logical connector. EXAMPLES:: sage: Unknown | False Unknown sage: Unknown | Unknown Unknown sage: Unknown | True True sage: Unknown.__or__(3) NotImplemented """ if other is True: return True elif other is False or other is Unknown: return self else: return NotImplemented def __richcmp__(self, other, op): """ Comparison of truth value. EXAMPLES:: sage: l = [False, Unknown, True] sage: for a in l: print([a < b for b in l]) [False, True, True] [False, False, True] [False, False, False] sage: for a in l: print([a <= b for b in l]) [True, True, True] [False, True, True] [False, False, True] """ if other is self: return rich_to_bool(op, 0) if not isinstance(other, bool): return NotImplemented if other: return rich_to_bool(op, -1) else: return rich_to_bool(op, +1) Unknown = UnknownClass()
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/unknown.py
0.890847
0.523177
unknown.py
pypi
from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES) from copy import copy from sage.misc.sageinspect import (sage_getsource, sage_getsourcelines, sage_getargspec) from inspect import FullArgSpec def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): r""" Decorator factory which should be used in decorators for making sure that meta-information on the decorated callables are retained through the decorator, such that the introspection functions of ``sage.misc.sageinspect`` retrieves them correctly. This includes documentation string, source, and argument specification. This is an extension of the Python standard library decorator functools.wraps. That the argument specification is retained from the decorated functions implies, that if one uses ``sage_wraps`` in a decorator which intentionally changes the argument specification, one should add this information to the special attribute ``_sage_argspec_`` of the wrapping function (for an example, see e.g. ``@options`` decorator in this module). EXAMPLES: Demonstrate that documentation string and source are retained from the decorated function:: sage: def square(f): ....: @sage_wraps(f) ....: def new_f(x): ....: return f(x)*f(x) ....: return new_f sage: @square ....: def g(x): ....: "My little function" ....: return x sage: g(2) 4 sage: g(x) x^2 sage: g.__doc__ 'My little function' sage: from sage.misc.sageinspect import sage_getsource, sage_getsourcelines, sage_getfile sage: sage_getsource(g) '@square...def g(x)...' Demonstrate that the argument description are retained from the decorated function through the special method (when left unchanged) (see :trac:`9976`):: sage: def diff_arg_dec(f): ....: @sage_wraps(f) ....: def new_f(y, some_def_arg=2): ....: return f(y+some_def_arg) ....: return new_f sage: @diff_arg_dec ....: def g(x): ....: return x sage: g(1) 3 sage: g(1, some_def_arg=4) 5 sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(g) FullArgSpec(args=['x'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) Demonstrate that it correctly gets the source lines and the source file, which is essential for interactive code edition; note that we do not test the line numbers, as they may easily change:: sage: P.<x,y> = QQ[] sage: I = P*[x,y] sage: sage_getfile(I.interreduced_basis) # known bug '.../sage/rings/polynomial/multi_polynomial_ideal.py' sage: sage_getsourcelines(I.interreduced_basis) ([' @handle_AA_and_QQbar\n', ' @singular_gb_standard_options\n', ' @libsingular_gb_standard_options\n', ' def interreduced_basis(self):\n', ... ' return self.basis.reduced()\n'], ...) The ``f`` attribute of the decorated function refers to the original function:: sage: foo = object() sage: @sage_wraps(foo) ....: def func(): ....: pass sage: wrapped = sage_wraps(foo)(func) sage: wrapped.f is foo True Demonstrate that sage_wraps works for non-function callables (:trac:`9919`):: sage: def square_for_met(f): ....: @sage_wraps(f) ....: def new_f(self, x): ....: return f(self,x)*f(self,x) ....: return new_f sage: class T: ....: @square_for_met ....: def g(self, x): ....: "My little method" ....: return x sage: t = T() sage: t.g(2) 4 sage: t.g.__doc__ 'My little method' The bug described in :trac:`11734` is fixed:: sage: def square(f): ....: @sage_wraps(f) ....: def new_f(x): ....: return f(x)*f(x) ....: return new_f sage: f = lambda x:x^2 sage: g = square(f) sage: g(3) # this line used to fail for some people if these command were manually entered on the sage prompt 81 """ #TRAC 9919: Workaround for bug in @update_wrapper when used with #non-function callables. assigned = set(assigned).intersection(set(dir(wrapped))) #end workaround def f(wrapper, assigned=assigned, updated=updated): update_wrapper(wrapper, wrapped, assigned=assigned, updated=updated) # For backwards-compatibility with old versions of sage_wraps wrapper.f = wrapped # For forwards-compatibility with functools.wraps on Python 3 wrapper.__wrapped__ = wrapped wrapper._sage_src_ = lambda: sage_getsource(wrapped) wrapper._sage_src_lines_ = lambda: sage_getsourcelines(wrapped) #Getting the signature right in documentation by Sphinx (Issue 9976) #The attribute _sage_argspec_() is read by Sphinx if present and used #as the argspec of the function instead of using reflection. wrapper._sage_argspec_ = lambda: sage_getargspec(wrapped) return wrapper return f # Infix operator decorator class infix_operator(): """ A decorator for functions which allows for a hack that makes the function behave like an infix operator. This decorator exists as a convenience for interactive use. EXAMPLES: An infix dot product operator:: sage: @infix_operator('multiply') ....: def dot(a, b): ....: '''Dot product.''' ....: return a.dot_product(b) sage: u = vector([1, 2, 3]) sage: v = vector([5, 4, 3]) sage: u *dot* v 22 An infix element-wise addition operator:: sage: @infix_operator('add') ....: def eadd(a, b): ....: return a.parent([i + j for i, j in zip(a, b)]) sage: u = vector([1, 2, 3]) sage: v = vector([5, 4, 3]) sage: u +eadd+ v (6, 6, 6) sage: 2*u +eadd+ v (7, 8, 9) A hack to simulate a postfix operator:: sage: @infix_operator('or') ....: def thendo(a, b): ....: return b(a) sage: x |thendo| cos |thendo| (lambda x: x^2) cos(x)^2 """ operators = { 'add': {'left': '__add__', 'right': '__radd__'}, 'multiply': {'left': '__mul__', 'right': '__rmul__'}, 'or': {'left': '__or__', 'right': '__ror__'}, } def __init__(self, precedence): """ INPUT: - ``precedence`` -- one of ``'add'``, ``'multiply'``, or ``'or'`` indicating the new operator's precedence in the order of operations. """ self.precedence = precedence def __call__(self, func): """Returns a function which acts as an inline operator.""" left_meth = self.operators[self.precedence]['left'] right_meth = self.operators[self.precedence]['right'] wrapper_name = func.__name__ wrapper_members = { 'function': staticmethod(func), left_meth: _infix_wrapper._left, right_meth: _infix_wrapper._right, '_sage_src_': lambda: sage_getsource(func) } for attr in WRAPPER_ASSIGNMENTS: try: wrapper_members[attr] = getattr(func, attr) except AttributeError: pass wrapper = type(wrapper_name, (_infix_wrapper,), wrapper_members) wrapper_inst = wrapper() wrapper_inst.__dict__.update(getattr(func, '__dict__', {})) return wrapper_inst class _infix_wrapper(): function = None def __init__(self, left=None, right=None): """ Initialize the actual infix object, with possibly a specified left and/or right operand. """ self.left = left self.right = right def __call__(self, *args, **kwds): """Call the passed function.""" return self.function(*args, **kwds) def _left(self, right): """The function for the operation on the left (e.g., __add__).""" if self.left is None: if self.right is None: new = copy(self) new.right = right return new else: raise SyntaxError("Infix operator already has its " "right argument") else: return self.function(self.left, right) def _right(self, left): """The function for the operation on the right (e.g., __radd__).""" if self.right is None: if self.left is None: new = copy(self) new.left = left return new else: raise SyntaxError("Infix operator already has its " "left argument") else: return self.function(left, self.right) def decorator_defaults(func): """ This function allows a decorator to have default arguments. Normally, a decorator can be called with or without arguments. However, the two cases call for different types of return values. If a decorator is called with no parentheses, it should be run directly on the function. However, if a decorator is called with parentheses (i.e., arguments), then it should return a function that is then in turn called with the defined function as an argument. This decorator allows us to have these default arguments without worrying about the return type. EXAMPLES:: sage: from sage.misc.decorators import decorator_defaults sage: @decorator_defaults ....: def my_decorator(f,*args,**kwds): ....: print(kwds) ....: print(args) ....: print(f.__name__) sage: @my_decorator ....: def my_fun(a,b): ....: return a,b {} () my_fun sage: @my_decorator(3,4,c=1,d=2) ....: def my_fun(a,b): ....: return a,b {'c': 1, 'd': 2} (3, 4) my_fun """ @sage_wraps(func) def my_wrap(*args, **kwds): if len(kwds) == 0 and len(args) == 1: # call without parentheses return func(*args) else: return lambda f: func(f, *args, **kwds) return my_wrap class suboptions(): def __init__(self, name, **options): """ A decorator for functions which collects all keywords starting with ``name+'_'`` and collects them into a dictionary which will be passed on to the wrapped function as a dictionary called ``name_options``. The keyword arguments passed into the constructor are taken to be default for the ``name_options`` dictionary. EXAMPLES:: sage: from sage.misc.decorators import suboptions sage: s = suboptions('arrow', size=2) sage: s.name 'arrow_' sage: s.options {'size': 2} """ self.name = name + "_" self.options = options def __call__(self, func): """ Returns a wrapper around func EXAMPLES:: sage: from sage.misc.decorators import suboptions sage: def f(*args, **kwds): print(sorted(kwds.items())) sage: f = suboptions('arrow', size=2)(f) sage: f(size=2) [('arrow_options', {'size': 2}), ('size', 2)] sage: f(arrow_size=3) [('arrow_options', {'size': 3})] sage: f(arrow_options={'size':4}) [('arrow_options', {'size': 4})] sage: f(arrow_options={'size':4}, arrow_size=5) [('arrow_options', {'size': 5})] Demonstrate that the introspected argument specification of the wrapped function is updated (see :trac:`9976`). sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(f) FullArgSpec(args=['arrow_size'], varargs='args', varkw='kwds', defaults=(2,), kwonlyargs=[], kwonlydefaults=None, annotations={}) """ @sage_wraps(func) def wrapper(*args, **kwds): suboptions = copy(self.options) suboptions.update(kwds.pop(self.name+"options", {})) # Collect all the relevant keywords in kwds # and put them in suboptions for key, value in list(kwds.items()): if key.startswith(self.name): suboptions[key[len(self.name):]] = value del kwds[key] kwds[self.name + "options"] = suboptions return func(*args, **kwds) # Add the options specified by @options to the signature of the wrapped # function in the Sphinx-generated documentation (Issue 9976), using the # special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) def argspec(): argspec = sage_getargspec(func) def listForNone(l): return l if l is not None else [] newArgs = [self.name + opt for opt in self.options.keys()] args = (argspec.args if argspec.args is not None else []) + newArgs defaults = (argspec.defaults if argspec.defaults is not None else ()) \ + tuple(self.options.values()) # Note: argspec.defaults is not always a tuple for some reason return FullArgSpec(args, argspec.varargs, argspec.varkw, defaults, kwonlyargs=[], kwonlydefaults=None, annotations={}) wrapper._sage_argspec_ = argspec return wrapper class options(): def __init__(self, **options): """ A decorator for functions which allows for default options to be set and reset by the end user. Additionally, if one needs to, one can get at the original keyword arguments passed into the decorator. TESTS:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: o.options {'rgbcolor': (0, 0, 1)} sage: o = options(rgbcolor=(0,0,1), __original_opts=True) sage: o.original_opts True sage: loads(dumps(o)).options {'rgbcolor': (0, 0, 1)} Demonstrate that the introspected argument specification of the wrapped function is updated (see :trac:`9976`):: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f1 = o(f) sage: from sage.misc.sageinspect import sage_getargspec sage: sage_getargspec(f1) FullArgSpec(args=['rgbcolor'], varargs='args', varkw='kwds', defaults=((0, 0, 1),), kwonlyargs=[], kwonlydefaults=None, annotations={}) """ self.options = options self.original_opts = options.pop('__original_opts', False) def __call__(self, func): """ EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f1 = o(f) sage: f1() () [('rgbcolor', (0, 0, 1))] sage: f1(rgbcolor=1) () [('rgbcolor', 1)] sage: o = options(rgbcolor=(0,0,1), __original_opts=True) sage: f2 = o(f) sage: f2(alpha=1) () [('__original_opts', {'alpha': 1}), ('alpha', 1), ('rgbcolor', (0, 0, 1))] """ @sage_wraps(func) def wrapper(*args, **kwds): options = copy(wrapper.options) if self.original_opts: options['__original_opts'] = kwds options.update(kwds) return func(*args, **options) #Add the options specified by @options to the signature of the wrapped #function in the Sphinx-generated documentation (Issue 9976), using the #special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) def argspec(): argspec = sage_getargspec(func) args = ((argspec.args if argspec.args is not None else []) + list(self.options)) defaults = (argspec.defaults or ()) + tuple(self.options.values()) # Note: argspec.defaults is not always a tuple for some reason return FullArgSpec(args, argspec.varargs, argspec.varkw, defaults, kwonlyargs=[], kwonlydefaults=None, annotations={}) wrapper._sage_argspec_ = argspec def defaults(): """ Return the default options. EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f = o(f) sage: f.options['rgbcolor']=(1,1,1) sage: f.defaults() {'rgbcolor': (0, 0, 1)} """ return copy(self.options) def reset(): """ Reset the options to the defaults. EXAMPLES:: sage: from sage.misc.decorators import options sage: o = options(rgbcolor=(0,0,1)) sage: def f(*args, **kwds): ....: print("{} {}".format(args, sorted(kwds.items()))) sage: f = o(f) sage: f.options {'rgbcolor': (0, 0, 1)} sage: f.options['rgbcolor']=(1,1,1) sage: f.options {'rgbcolor': (1, 1, 1)} sage: f() () [('rgbcolor', (1, 1, 1))] sage: f.reset() sage: f.options {'rgbcolor': (0, 0, 1)} sage: f() () [('rgbcolor', (0, 0, 1))] """ wrapper.options = copy(self.options) wrapper.options = copy(self.options) wrapper.reset = reset wrapper.reset.__doc__ = """ Reset the options to the defaults. Defaults: %s """ % self.options wrapper.defaults = defaults wrapper.defaults.__doc__ = """ Return the default options. Defaults: %s """ % self.options return wrapper class rename_keyword(): def __init__(self, deprecated=None, deprecation=None, **renames): """ A decorator which renames keyword arguments and optionally deprecates the new keyword. INPUT: - ``deprecation`` -- integer. The github issue number where the deprecation was introduced. - the rest of the arguments is a list of keyword arguments in the form ``renamed_option='existing_option'``. This will have the effect of renaming ``renamed_option`` so that the function only sees ``existing_option``. If both ``renamed_option`` and ``existing_option`` are passed to the function, ``existing_option`` will override the ``renamed_option`` value. EXAMPLES:: sage: from sage.misc.decorators import rename_keyword sage: r = rename_keyword(color='rgbcolor') sage: r.renames {'color': 'rgbcolor'} sage: loads(dumps(r)).renames {'color': 'rgbcolor'} To deprecate an old keyword:: sage: r = rename_keyword(deprecation=13109, color='rgbcolor') """ assert deprecated is None, 'Use @rename_keyword(deprecation=<issue_number>, ...)' self.renames = renames self.deprecation = deprecation def __call__(self, func): """ Rename keywords. EXAMPLES:: sage: from sage.misc.decorators import rename_keyword sage: r = rename_keyword(color='rgbcolor') sage: def f(*args, **kwds): ....: print("{} {}".format(args, kwds)) sage: f = r(f) sage: f() () {} sage: f(alpha=1) () {'alpha': 1} sage: f(rgbcolor=1) () {'rgbcolor': 1} sage: f(color=1) () {'rgbcolor': 1} We can also deprecate the renamed keyword:: sage: r = rename_keyword(deprecation=13109, deprecated_option='new_option') sage: def f(*args, **kwds): ....: print("{} {}".format(args, kwds)) sage: f = r(f) sage: f() () {} sage: f(alpha=1) () {'alpha': 1} sage: f(new_option=1) () {'new_option': 1} sage: f(deprecated_option=1) doctest:...: DeprecationWarning: use the option 'new_option' instead of 'deprecated_option' See https://github.com/sagemath/sage/issues/13109 for details. () {'new_option': 1} """ @sage_wraps(func) def wrapper(*args, **kwds): for old_name, new_name in self.renames.items(): if old_name in kwds and new_name not in kwds: if self.deprecation is not None: from sage.misc.superseded import deprecation deprecation(self.deprecation, "use the option " "%r instead of %r" % (new_name, old_name)) kwds[new_name] = kwds[old_name] del kwds[old_name] return func(*args, **kwds) return wrapper class specialize: r""" A decorator generator that returns a decorator that in turn returns a specialized function for function ``f``. In other words, it returns a function that acts like ``f`` with arguments ``*args`` and ``**kwargs`` supplied. INPUT: - ``*args``, ``**kwargs`` -- arguments to specialize the function for. OUTPUT: - a decorator that accepts a function ``f`` and specializes it with ``*args`` and ``**kwargs`` EXAMPLES:: sage: f = specialize(5)(lambda x, y: x+y) sage: f(10) 15 sage: f(5) 10 sage: @specialize("Bon Voyage") ....: def greet(greeting, name): ....: print("{0}, {1}!".format(greeting, name)) sage: greet("Monsieur Jean Valjean") Bon Voyage, Monsieur Jean Valjean! sage: greet(name = 'Javert') Bon Voyage, Javert! """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, f): return sage_wraps(f)(partial(f, *self.args, **self.kwargs)) def decorator_keywords(func): r""" A decorator for decorators with optional keyword arguments. EXAMPLES:: sage: from sage.misc.decorators import decorator_keywords sage: @decorator_keywords ....: def preprocess(f=None, processor=None): ....: def wrapper(*args, **kwargs): ....: if processor is not None: ....: args, kwargs = processor(*args, **kwargs) ....: return f(*args, **kwargs) ....: return wrapper This decorator can be called with and without arguments:: sage: @preprocess ....: def foo(x): return x sage: foo(None) sage: foo(1) 1 sage: def normalize(x): return ((0,),{}) if x is None else ((x,),{}) sage: @preprocess(processor=normalize) ....: def foo(x): return x sage: foo(None) 0 sage: foo(1) 1 """ @sage_wraps(func) def wrapped(f=None, **kwargs): if f is None: return sage_wraps(func)(lambda f:func(f, **kwargs)) else: return func(f, **kwargs) return wrapped
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/decorators.py
0.774839
0.310139
decorators.py
pypi
import types def abstract_method(f=None, optional=False): r""" Abstract methods INPUT: - ``f`` -- a function - ``optional`` -- a boolean; defaults to ``False`` The decorator :obj:`abstract_method` can be used to declare methods that should be implemented by all concrete derived classes. This declaration should typically include documentation for the specification for this method. The purpose is to enforce a consistent and visual syntax for such declarations. It is used by the Sage categories for automated tests (see ``Sets.Parent.test_not_implemented``). EXAMPLES: We create a class with an abstract method:: sage: class A(): ....: ....: @abstract_method ....: def my_method(self): ....: ''' ....: The method :meth:`my_method` computes my_method ....: ....: EXAMPLES:: ....: ....: ''' ....: pass sage: A.my_method <abstract method my_method at ...> The current policy is that a ``NotImplementedError`` is raised when accessing the method through an instance, even before the method is called:: sage: x = A() sage: x.my_method Traceback (most recent call last): ... NotImplementedError: <abstract method my_method at ...> It is also possible to mark abstract methods as optional:: sage: class A(): ....: ....: @abstract_method(optional = True) ....: def my_method(self): ....: ''' ....: The method :meth:`my_method` computes my_method ....: ....: EXAMPLES:: ....: ....: ''' ....: pass sage: A.my_method <optional abstract method my_method at ...> sage: x = A() sage: x.my_method NotImplemented The official mantra for testing whether an optional abstract method is implemented is:: sage: if x.my_method is not NotImplemented: ....: x.my_method() ....: else: ....: print("x.my_method is not available.") x.my_method is not available. .. rubric:: Discussion The policy details are not yet fixed. The purpose of this first implementation is to let developers experiment with it and give feedback on what's most practical. The advantage of the current policy is that attempts at using a non implemented methods are caught as early as possible. On the other hand, one cannot use introspection directly to fetch the documentation:: sage: x.my_method? # todo: not implemented Instead one needs to do:: sage: A._my_method? # todo: not implemented This could probably be fixed in :mod:`sage.misc.sageinspect`. .. TODO:: what should be the recommended mantra for existence testing from the class? .. TODO:: should extra information appear in the output? The name of the class? That of the super class where the abstract method is defined? .. TODO:: look for similar decorators on the web, and merge .. rubric:: Implementation details Technically, an abstract_method is a non-data descriptor (see Invoking Descriptors in the Python reference manual). The syntax ``@abstract_method`` w.r.t. @abstract_method(optional = True) is achieved by a little trick which we test here:: sage: abstract_method(optional = True) <function abstract_method.<locals>.<lambda> at ...> sage: abstract_method(optional = True)(banner) <optional abstract method banner at ...> sage: abstract_method(banner, optional = True) <optional abstract method banner at ...> """ if f is None: return lambda f: AbstractMethod(f, optional=optional) else: return AbstractMethod(f, optional) class AbstractMethod(): def __init__(self, f, optional=False): """ Constructor for abstract methods EXAMPLES:: sage: def f(x): ....: "doc of f" ....: return 1 sage: x = abstract_method(f); x <abstract method f at ...> sage: x.__doc__ 'doc of f' sage: x.__name__ 'f' sage: x.__module__ '__main__' """ assert (isinstance(f, types.FunctionType) or getattr(type(f), '__name__', None) == 'cython_function_or_method') assert isinstance(optional, bool) self._f = f self._optional = optional self.__doc__ = f.__doc__ self.__name__ = f.__name__ try: self.__module__ = f.__module__ except AttributeError: pass def __repr__(self): """ EXAMPLES:: sage: abstract_method(banner) <abstract method banner at ...> sage: abstract_method(banner, optional = True) <optional abstract method banner at ...> """ return "<" + ("optional " if self._optional else "") + "abstract method %s at %s>" % (self.__name__, hex(id(self._f))) def _sage_src_lines_(self): r""" Returns the source code location for the wrapped function. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getsourcelines sage: g = abstract_method(banner) sage: (src, lines) = sage_getsourcelines(g) sage: src[0] 'def banner():\n' sage: lines 89 """ from sage.misc.sageinspect import sage_getsourcelines return sage_getsourcelines(self._f) def __get__(self, instance, cls): """ Implements the attribute access protocol. EXAMPLES:: sage: class A: pass sage: def f(x): return 1 sage: f = abstract_method(f) sage: f.__get__(A(), A) Traceback (most recent call last): ... NotImplementedError: <abstract method f at ...> """ if instance is None: return self elif self._optional: return NotImplemented else: raise NotImplementedError(repr(self)) def is_optional(self): """ Returns whether an abstract method is optional or not. EXAMPLES:: sage: class AbstractClass: ....: @abstract_method ....: def required(): pass ....: ....: @abstract_method(optional = True) ....: def optional(): pass sage: AbstractClass.required.is_optional() False sage: AbstractClass.optional.is_optional() True """ return self._optional def abstract_methods_of_class(cls): """ Returns the required and optional abstract methods of the class EXAMPLES:: sage: class AbstractClass: ....: @abstract_method ....: def required1(): pass ....: ....: @abstract_method(optional = True) ....: def optional2(): pass ....: ....: @abstract_method(optional = True) ....: def optional1(): pass ....: ....: @abstract_method ....: def required2(): pass sage: sage.misc.abstract_method.abstract_methods_of_class(AbstractClass) {'optional': ['optional1', 'optional2'], 'required': ['required1', 'required2']} """ result = {"required": [], "optional": []} for name in dir(cls): entry = getattr(cls, name) if not isinstance(entry, AbstractMethod): continue if entry.is_optional(): result["optional"].append(name) else: result["required"].append(name) return result
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/abstract_method.py
0.715424
0.492798
abstract_method.py
pypi
class LazyFormat(str): """ Lazy format strings .. NOTE:: We recommend to use :func:`sage.misc.lazy_string.lazy_string` instead, which is both faster and more flexible. An instance of :class:`LazyFormat` behaves like a usual format string, except that the evaluation of the ``__repr__`` method of the formatted arguments it postponed until actual printing. EXAMPLES: Under normal circumstances, :class:`Lazyformat` strings behave as usual:: sage: from sage.misc.lazy_format import LazyFormat sage: LazyFormat("Got `%s`; expected a list")%3 Got `3`; expected a list sage: LazyFormat("Got `%s`; expected %s")%(3, 2/3) Got `3`; expected 2/3 To demonstrate the lazyness, let us build an object with a broken ``__repr__`` method:: sage: class IDontLikeBeingPrinted(): ....: def __repr__(self): ....: raise ValueError("do not ever try to print me") There is no error when binding a lazy format with the broken object:: sage: lf = LazyFormat("<%s>")%IDontLikeBeingPrinted() The error only occurs upon printing:: sage: lf <repr(<sage.misc.lazy_format.LazyFormat at 0x...>) failed: ValueError: do not ever try to print me> .. rubric:: Common use case: Most of the time, ``__repr__`` methods are only called during user interaction, and therefore need not be fast; and indeed there are objects ``x`` in Sage such ``x.__repr__()`` is time consuming. There are however some uses cases where many format strings are constructed but not actually printed. This includes error handling messages in :mod:`unittest` or :class:`TestSuite` executions:: sage: QQ._tester().assertIn(0, QQ, ....: "%s doesn't contain 0"%QQ) In the above ``QQ.__repr__()`` has been called, and the result immediately discarded. To demonstrate this we replace ``QQ`` in the format string argument with our broken object:: sage: QQ._tester().assertTrue(True, ....: "%s doesn't contain 0"%IDontLikeBeingPrinted()) Traceback (most recent call last): ... ValueError: do not ever try to print me This behavior can induce major performance penalties when testing. Note that this issue does not impact the usual assert:: sage: assert True, "%s is wrong"%IDontLikeBeingPrinted() We now check that :class:`LazyFormat` indeed solves the assertion problem:: sage: QQ._tester().assertTrue(True, ....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted()) sage: QQ._tester().assertTrue(False, ....: LazyFormat("%s is wrong")%IDontLikeBeingPrinted()) Traceback (most recent call last): ... AssertionError: ... """ def __mod__(self, args): """ Binds the lazy format string with its parameters EXAMPLES:: sage: from sage.misc.lazy_format import LazyFormat sage: form = LazyFormat("<%s>") sage: form unbound LazyFormat("<%s>") sage: form%"params" <params> """ if hasattr(self, "_args"): # self is already bound... self = LazyFormat(""+self) self._args = args return self def __repr__(self): """ TESTS:: sage: from sage.misc.lazy_format import LazyFormat sage: form = LazyFormat("<%s>") sage: form unbound LazyFormat("<%s>") sage: print(form) unbound LazyFormat("<%s>") sage: form%"toto" <toto> sage: print(form % "toto") <toto> sage: print(str(form % "toto")) <toto> sage: print((form % "toto").__repr__()) <toto> """ try: args = self._args except AttributeError: return "unbound LazyFormat(\""+self+"\")" else: return str.__mod__(self, args) __str__ = __repr__
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/lazy_format.py
0.745491
0.682243
lazy_format.py
pypi
r""" Random Numbers with Python API AUTHORS: -- Carl Witty (2008-03): new file This module has the same functions as the Python standard module \module{random}, but uses the current \sage random number state from \module{sage.misc.randstate} (so that it can be controlled by the same global random number seeds). The functions here are less efficient than the functions in \module{random}, because they look up the current random number state on each call. If you are going to be creating many random numbers in a row, it is better to use the functions in \module{sage.misc.randstate} directly. Here is an example: (The imports on the next two lines are not necessary, since \function{randrange} and \function{current_randstate} are both available by default at the \code{sage:} prompt; but you would need them to run these examples inside a module.) :: sage: from sage.misc.prandom import randrange sage: from sage.misc.randstate import current_randstate sage: def test1(): ....: return sum([randrange(100) for i in range(100)]) sage: def test2(): ....: randrange = current_randstate().python_random().randrange ....: return sum([randrange(100) for i in range(100)]) Test2 will be slightly faster than test1, but they give the same answer:: sage: with seed(0): test1() 5169 sage: with seed(0): test2() 5169 sage: with seed(1): test1() 5097 sage: with seed(1): test2() 5097 sage: timeit('test1()') # random 625 loops, best of 3: 590 us per loop sage: timeit('test2()') # random 625 loops, best of 3: 460 us per loop The docstrings for the functions in this file are mostly copied from Python's \file{random.py}, so those docstrings are "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; All Rights Reserved" and are available under the terms of the Python Software Foundation License Version 2. """ # We deliberately omit "seed" and several other seed-related functions... # setting seeds should only be done through sage.misc.randstate . from sage.misc.randstate import current_randstate def _pyrand(): r""" A tiny private helper function to return an instance of random.Random from the current \sage random number state. Only for use in prandom.py; other modules should use current_randstate().python_random(). EXAMPLES:: sage: set_random_seed(0) sage: from sage.misc.prandom import _pyrand sage: _pyrand() <...random.Random object at 0x...> sage: _pyrand().getrandbits(10) 114 """ return current_randstate().python_random() def getrandbits(k): r""" getrandbits(k) -> x. Generates a long int with k random bits. EXAMPLES:: sage: getrandbits(10) in range(2^10) True sage: getrandbits(200) in range(2^200) True sage: getrandbits(4) in range(2^4) True """ return _pyrand().getrandbits(k) def randrange(start, stop=None, step=1): r""" Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. EXAMPLES:: sage: s = randrange(0, 100, 11) sage: 0 <= s < 100 True sage: s % 11 0 sage: 5000 <= randrange(5000, 5100) < 5100 True sage: s = [randrange(0, 2) for i in range(15)] sage: all(t in [0, 1] for t in s) True sage: s = randrange(0, 1000000, 1000) sage: 0 <= s < 1000000 True sage: s % 1000 0 sage: -100 <= randrange(-100, 10) < 10 True """ return _pyrand().randrange(start, stop, step) def randint(a, b): r""" Return random integer in range [a, b], including both end points. EXAMPLES:: sage: s = [randint(0, 2) for i in range(15)]; s # random [0, 1, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 0, 2, 2] sage: all(t in [0, 1, 2] for t in s) True sage: -100 <= randint(-100, 10) <= 10 True """ return _pyrand().randint(a, b) def choice(seq): r""" Choose a random element from a non-empty sequence. EXAMPLES:: sage: s = [choice(list(primes(10, 100))) for i in range(5)]; s # random [17, 47, 11, 31, 47] sage: all(t in primes(10, 100) for t in s) True """ return _pyrand().choice(seq) def shuffle(x): r""" x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the sage.misc.random.random. EXAMPLES:: sage: shuffle([1 .. 10]) """ return _pyrand().shuffle(x) def sample(population, k): r""" Choose k unique random elements from a population sequence. Return a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument (in Python 2) or range (in Python 3). This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) EXAMPLES:: sage: from sage.misc.misc import is_sublist sage: l = ["Here", "I", "come", "to", "save", "the", "day"] sage: s = sample(l, 3); s # random ['Here', 'to', 'day'] sage: is_sublist(sorted(s), sorted(l)) True sage: len(s) 3 sage: s = sample(range(2^30), 7); s # random [357009070, 558990255, 196187132, 752551188, 85926697, 954621491, 624802848] sage: len(s) 7 sage: all(t in range(2^30) for t in s) True """ return _pyrand().sample(population, k) def random(): r""" Get the next random number in the range [0.0, 1.0). EXAMPLES:: sage: sample = [random() for i in [1 .. 4]]; sample # random [0.111439293741037, 0.5143475134191677, 0.04468968524815642, 0.332490606442413] sage: all(0.0 <= s <= 1.0 for s in sample) True """ return _pyrand().random() def uniform(a, b): r""" Get a random number in the range [a, b). Equivalent to \code{a + (b-a) * random()}. EXAMPLES:: sage: s = uniform(0, 1); s # random 0.111439293741037 sage: 0.0 <= s <= 1.0 True sage: s = uniform(e, pi); s # random 0.5143475134191677*pi + 0.48565248658083227*e sage: bool(e <= s <= pi) True """ return _pyrand().uniform(a, b) def betavariate(alpha, beta): r""" Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. EXAMPLES:: sage: s = betavariate(0.1, 0.9); s # random 9.75087916621299e-9 sage: 0.0 <= s <= 1.0 True sage: s = betavariate(0.9, 0.1); s # random 0.941890400939253 sage: 0.0 <= s <= 1.0 True """ return _pyrand().betavariate(alpha, beta) def expovariate(lambd): r""" Exponential distribution. lambd is 1.0 divided by the desired mean. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity. EXAMPLES:: sage: sample = [expovariate(0.001) for i in range(3)]; sample # random [118.152309288166, 722.261959038118, 45.7190543690470] sage: all(s >= 0.0 for s in sample) True sage: sample = [expovariate(1.0) for i in range(3)]; sample # random [0.404201816061304, 0.735220464997051, 0.201765578600627] sage: all(s >= 0.0 for s in sample) True sage: sample = [expovariate(1000) for i in range(3)]; sample # random [0.0012068700332283973, 8.340929747302108e-05, 0.00219877067980605] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().expovariate(lambd) def gammavariate(alpha, beta): r""" Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. EXAMPLES:: sage: sample = gammavariate(1.0, 3.0); sample # random 6.58282586130638 sage: sample > 0 True sage: sample = gammavariate(3.0, 1.0); sample # random 3.07801512341612 sage: sample > 0 True """ return _pyrand().gammavariate(alpha, beta) def gauss(mu, sigma): r""" Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function, but is not thread-safe. EXAMPLES:: sage: [gauss(0, 1) for i in range(3)] # random [0.9191011757657915, 0.7744526756246484, 0.8638996866800877] sage: [gauss(0, 100) for i in range(3)] # random [24.916051749154448, -62.99272061579273, -8.1993122536718...] sage: [gauss(1000, 10) for i in range(3)] # random [998.7590700045661, 996.1087338511692, 1010.1256817458031] """ return _pyrand().gauss(mu, sigma) def lognormvariate(mu, sigma): r""" Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. EXAMPLES:: sage: [lognormvariate(100, 10) for i in range(3)] # random [2.9410355688290246e+37, 2.2257548162070125e+38, 4.142299451717446e+43] """ return _pyrand().lognormvariate(mu, sigma) def normalvariate(mu, sigma): r""" Normal distribution. mu is the mean, and sigma is the standard deviation. EXAMPLES:: sage: [normalvariate(0, 1) for i in range(3)] # random [-1.372558980559407, -1.1701670364898928, 0.04324100555110143] sage: [normalvariate(0, 100) for i in range(3)] # random [37.45695875041769, 159.6347743233298, 124.1029321124009] sage: [normalvariate(1000, 10) for i in range(3)] # random [1008.5303090383741, 989.8624892644895, 985.7728921150242] """ return _pyrand().normalvariate(mu, sigma) def vonmisesvariate(mu, kappa): r""" Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. EXAMPLES:: sage: sample = [vonmisesvariate(1.0r, 3.0r) for i in range(1, 5)]; sample # random [0.898328639355427, 0.6718030007041281, 2.0308777524813393, 1.714325253725145] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().vonmisesvariate(mu, kappa) def paretovariate(alpha): r""" Pareto distribution. alpha is the shape parameter. EXAMPLES:: sage: sample = [paretovariate(3) for i in range(1, 5)]; sample # random [1.0401699394233033, 1.2722080162636495, 1.0153564009379579, 1.1442323078983077] sage: all(s >= 1.0 for s in sample) True """ return _pyrand().paretovariate(alpha) def weibullvariate(alpha, beta): r""" Weibull distribution. alpha is the scale parameter and beta is the shape parameter. EXAMPLES:: sage: sample = [weibullvariate(1, 3) for i in range(1, 5)]; sample # random [0.49069775546342537, 0.8972185564611213, 0.357573846531942, 0.739377255516847] sage: all(s >= 0.0 for s in sample) True """ return _pyrand().weibullvariate(alpha, beta)
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/prandom.py
0.812198
0.794982
prandom.py
pypi
"Flatten nested lists" import sys def flatten(in_list, ltypes=(list, tuple), max_level=sys.maxsize): """ Flatten a nested list. INPUT: - ``in_list`` -- a list or tuple - ``ltypes`` -- optional list of particular types to flatten - ``max_level`` -- the maximum level to flatten OUTPUT: a flat list of the entries of ``in_list`` EXAMPLES:: sage: flatten([[1,1],[1],2]) [1, 1, 1, 2] sage: flatten([[1,2,3], (4,5), [[[1],[2]]]]) [1, 2, 3, 4, 5, 1, 2] sage: flatten([[1,2,3], (4,5), [[[1],[2]]]],max_level=1) [1, 2, 3, 4, 5, [[1], [2]]] sage: flatten([[[3],[]]],max_level=0) [[[3], []]] sage: flatten([[[3],[]]],max_level=1) [[3], []] sage: flatten([[[3],[]]],max_level=2) [3] In the following example, the vector is not flattened because it is not given in the ``ltypes`` input. :: sage: flatten((['Hi',2,vector(QQ,[1,2,3])],(4,5,6))) ['Hi', 2, (1, 2, 3), 4, 5, 6] We give the vector type and then even the vector gets flattened:: sage: tV = sage.modules.vector_rational_dense.Vector_rational_dense sage: flatten((['Hi',2,vector(QQ,[1,2,3])], (4,5,6)), ....: ltypes=(list, tuple, tV)) ['Hi', 2, 1, 2, 3, 4, 5, 6] We flatten a finite field. :: sage: flatten(GF(5)) [0, 1, 2, 3, 4] sage: flatten([GF(5)]) [Finite Field of size 5] sage: tGF = type(GF(5)) sage: flatten([GF(5)], ltypes = (list, tuple, tGF)) [0, 1, 2, 3, 4] Degenerate cases:: sage: flatten([[],[]]) [] sage: flatten([[[]]]) [] """ index = 0 current_level = 0 new_list = [x for x in in_list] level_list = [0] * len(in_list) while index < len(new_list): len_v = True while isinstance(new_list[index], ltypes) and current_level < max_level: v = list(new_list[index]) len_v = len(v) new_list[index : index + 1] = v old_level = level_list[index] level_list[index : index + 1] = [0] * len_v if len_v: current_level += 1 level_list[index + len_v - 1] = old_level + 1 else: current_level -= old_level index -= 1 break # If len_v == 0, then index points to a previous element, so we # do not need to do anything. if len_v: current_level -= level_list[index] index += 1 return new_list
/sagemath-objects-10.0b1.tar.gz/sagemath-objects-10.0b1/sage/misc/flatten.py
0.563138
0.576959
flatten.py
pypi
from sage.matrix.constructor import matrix from sage.rings.integer_ring import ZZ # Function below could be replicated into # sage.matrix.matrix_integer_dense.Matrix_integer_dense.is_LLL_reduced # which is its only current use (2011-02-26). Then this could # be deprecated and this file removed. def gram_schmidt(B): r""" Return the Gram-Schmidt orthogonalization of the entries in the list B of vectors, along with the matrix mu of Gram-Schmidt coefficients. Note that the output vectors need not have unit length. We do this to avoid having to extract square roots. .. note:: Use of this function is discouraged. It fails on linearly dependent input and its output format is not as natural as it could be. Instead, see :meth:`sage.matrix.matrix2.Matrix2.gram_schmidt` which is safer and more general-purpose. EXAMPLES:: sage: B = [vector([1,2,1/5]), vector([1,2,3]), vector([-1,0,0])] sage: from sage.modules.misc import gram_schmidt sage: G, mu = gram_schmidt(B) sage: G [(1, 2, 1/5), (-1/9, -2/9, 25/9), (-4/5, 2/5, 0)] sage: G[0] * G[1] 0 sage: G[0] * G[2] 0 sage: G[1] * G[2] 0 sage: mu [ 0 0 0] [ 10/9 0 0] [-25/126 1/70 0] sage: a = matrix([]) sage: a.gram_schmidt() ([], []) sage: a = matrix([[],[],[],[]]) sage: a.gram_schmidt() ([], []) Linearly dependent input leads to a zero dot product in a denominator. This shows that :trac:`10791` is fixed. :: sage: from sage.modules.misc import gram_schmidt sage: V = [vector(ZZ,[1,1]), vector(ZZ,[2,2]), vector(ZZ,[1,2])] sage: gram_schmidt(V) Traceback (most recent call last): ... ValueError: linearly dependent input for module version of Gram-Schmidt """ import sage.modules.free_module_element if len(B) == 0 or len(B[0]) == 0: return B, matrix(ZZ,0,0,[]) n = len(B) Bstar = [B[0]] K = B[0].base_ring().fraction_field() zero = sage.modules.free_module_element.vector(K, len(B[0])) if Bstar[0] == zero: raise ValueError("linearly dependent input for module version of Gram-Schmidt") mu = matrix(K, n, n) for i in range(1,n): for j in range(i): mu[i,j] = B[i].dot_product(Bstar[j]) / (Bstar[j].dot_product(Bstar[j])) Bstar.append(B[i] - sum(mu[i,j]*Bstar[j] for j in range(i))) if Bstar[i] == zero: raise ValueError("linearly dependent input for module version of Gram-Schmidt") return Bstar, mu
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/modules/misc.py
0.838217
0.728338
misc.py
pypi
r""" Morphisms defined by a matrix A matrix morphism is a morphism that is defined by multiplication by a matrix. Elements of domain must either have a method ``vector()`` that returns a vector that the defining matrix can hit from the left, or be coercible into vector space of appropriate dimension. EXAMPLES:: sage: from sage.modules.matrix_morphism import MatrixMorphism, is_MatrixMorphism sage: V = QQ^3 sage: T = End(V) sage: M = MatrixSpace(QQ,3) sage: I = M.identity_matrix() sage: m = MatrixMorphism(T, I); m Morphism defined by the matrix [1 0 0] [0 1 0] [0 0 1] sage: is_MatrixMorphism(m) True sage: m.charpoly('x') x^3 - 3*x^2 + 3*x - 1 sage: m.base_ring() Rational Field sage: m.det() 1 sage: m.fcp('x') (x - 1)^3 sage: m.matrix() [1 0 0] [0 1 0] [0 0 1] sage: m.rank() 3 sage: m.trace() 3 AUTHOR: - William Stein: initial versions - David Joyner (2005-12-17): added examples - William Stein (2005-01-07): added __reduce__ - Craig Citro (2008-03-18): refactored MatrixMorphism class - Rob Beezer (2011-07-15): additional methods, bug fixes, documentation """ import sage.categories.morphism import sage.categories.homset from sage.structure.all import Sequence, parent from sage.structure.richcmp import richcmp, op_NE, op_EQ def is_MatrixMorphism(x): """ Return True if x is a Matrix morphism of free modules. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1]) sage: sage.modules.matrix_morphism.is_MatrixMorphism(phi) True sage: sage.modules.matrix_morphism.is_MatrixMorphism(3) False """ return isinstance(x, MatrixMorphism_abstract) class MatrixMorphism_abstract(sage.categories.morphism.Morphism): def __init__(self, parent, side='left'): """ INPUT: - ``parent`` - a homspace - ``A`` - matrix EXAMPLES:: sage: from sage.modules.matrix_morphism import MatrixMorphism sage: T = End(ZZ^3) sage: M = MatrixSpace(ZZ,3) sage: I = M.identity_matrix() sage: A = MatrixMorphism(T, I) sage: loads(A.dumps()) == A True """ if not sage.categories.homset.is_Homset(parent): raise TypeError("parent must be a Hom space") if side not in ["left", "right"]: raise ValueError("the argument side must be either 'left' or 'right'") self._side = side sage.categories.morphism.Morphism.__init__(self, parent) def _richcmp_(self, other, op): """ Rich comparison of morphisms. EXAMPLES:: sage: V = ZZ^2 sage: phi = V.hom([3*V.0, 2*V.1]) sage: psi = V.hom([5*V.0, 5*V.1]) sage: id = V.hom([V.0, V.1]) sage: phi == phi True sage: phi == psi False sage: psi == End(V)(5) True sage: psi == 5 * id True sage: psi == 5 # no coercion False sage: id == End(V).identity() True """ if not isinstance(other, MatrixMorphism) or op not in (op_EQ, op_NE): # Generic comparison return sage.categories.morphism.Morphism._richcmp_(self, other, op) return richcmp(self.matrix(), other.matrix(), op) def _call_(self, x): """ Evaluate this matrix morphism at an element of the domain. .. NOTE:: Coercion is done in the generic :meth:`__call__` method, which calls this method. EXAMPLES:: sage: V = QQ^3; W = QQ^2 sage: H = Hom(V, W); H Set of Morphisms (Linear Transformations) from Vector space of dimension 3 over Rational Field to Vector space of dimension 2 over Rational Field sage: phi = H(matrix(QQ, 3, 2, range(6))); phi Vector space morphism represented by the matrix: [0 1] [2 3] [4 5] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 2 over Rational Field sage: phi(V.0) (0, 1) sage: phi(V([1, 2, 3])) (16, 22) Last, we have a situation where coercion occurs:: sage: U = V.span([[3,2,1]]) sage: U.0 (1, 2/3, 1/3) sage: phi(2*U.0) (16/3, 28/3) TESTS:: sage: V = QQ^3; W = span([[1,2,3],[-1,2,5/3]], QQ) sage: phi = V.hom(matrix(QQ,3,[1..9])) We compute the image of some elements:: sage: phi(V.0) #indirect doctest (1, 2, 3) sage: phi(V.1) (4, 5, 6) sage: phi(V.0 - 1/4*V.1) (0, 3/4, 3/2) We restrict ``phi`` to ``W`` and compute the image of an element:: sage: psi = phi.restrict_domain(W) sage: psi(W.0) == phi(W.0) True sage: psi(W.1) == phi(W.1) True """ try: if parent(x) is not self.domain(): x = self.domain()(x) except TypeError: raise TypeError("%s must be coercible into %s"%(x,self.domain())) if self.domain().is_ambient(): x = x.element() else: x = self.domain().coordinate_vector(x) C = self.codomain() if self.side() == "left": v = x.change_ring(C.base_ring()) * self.matrix() else: v = self.matrix() * x.change_ring(C.base_ring()) if not C.is_ambient(): v = C.linear_combination_of_basis(v) # The call method of parents uses (coercion) morphisms. # Hence, in order to avoid recursion, we call the element # constructor directly; after all, we already know the # coordinates. return C._element_constructor_(v) def _call_with_args(self, x, args=(), kwds={}): """ Like :meth:`_call_`, but takes optional and keyword arguments. EXAMPLES:: sage: V = RR^2 sage: f = V.hom(V.gens()) sage: f._matrix *= I # f is now invalid sage: f((1, 0)) Traceback (most recent call last): ... TypeError: Unable to coerce entries (=[1.00000000000000*I, 0.000000000000000]) to coefficients in Real Field with 53 bits of precision sage: f((1, 0), coerce=False) (1.00000000000000*I, 0.000000000000000) """ if self.domain().is_ambient(): x = x.element() else: x = self.domain().coordinate_vector(x) C = self.codomain() v = x.change_ring(C.base_ring()) * self.matrix() if not C.is_ambient(): v = C.linear_combination_of_basis(v) # The call method of parents uses (coercion) morphisms. # Hence, in order to avoid recursion, we call the element # constructor directly; after all, we already know the # coordinates. return C._element_constructor_(v, *args, **kwds) def __invert__(self): """ Invert this matrix morphism. EXAMPLES:: sage: V = QQ^2; phi = V.hom([3*V.0, 2*V.1]) sage: phi^(-1) Vector space morphism represented by the matrix: [1/3 0] [ 0 1/2] Domain: Vector space of dimension 2 over Rational Field Codomain: Vector space of dimension 2 over Rational Field Check that a certain non-invertible morphism isn't invertible:: sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1]) sage: phi^(-1) Traceback (most recent call last): ... ZeroDivisionError: matrix morphism not invertible """ try: B = ~(self.matrix()) except ZeroDivisionError: raise ZeroDivisionError("matrix morphism not invertible") try: return self.parent().reversed()(B, side=self.side()) except TypeError: raise ZeroDivisionError("matrix morphism not invertible") def side(self): """ Return the side of vectors acted on, relative to the matrix. EXAMPLES:: sage: m = matrix(2, [1, 1, 0, 1]) sage: V = ZZ^2 sage: h1 = V.hom(m); h2 = V.hom(m, side="right") sage: h1.side() 'left' sage: h1([1, 0]) (1, 1) sage: h2.side() 'right' sage: h2([1, 0]) (1, 0) """ return self._side def side_switch(self): """ Return the same morphism, acting on vectors on the opposite side EXAMPLES:: sage: m = matrix(2, [1,1,0,1]); m [1 1] [0 1] sage: V = ZZ^2 sage: h = V.hom(m); h.side() 'left' sage: h2 = h.side_switch(); h2 Free module morphism defined as left-multiplication by the matrix [1 0] [1 1] Domain: Ambient free module of rank 2 over the principal ideal domain Integer Ring Codomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring sage: h2.side() 'right' sage: h2.side_switch().matrix() [1 1] [0 1] """ side = "left" if self.side() == "right" else "right" return self.parent()(self.matrix().transpose(), side=side) def inverse(self): r""" Return the inverse of this matrix morphism, if the inverse exists. Raises a ``ZeroDivisionError`` if the inverse does not exist. EXAMPLES: An invertible morphism created as a restriction of a non-invertible morphism, and which has an unequal domain and codomain. :: sage: V = QQ^4 sage: W = QQ^3 sage: m = matrix(QQ, [[2, 0, 3], [-6, 1, 4], [1, 2, -4], [1, 0, 1]]) sage: phi = V.hom(m, W) sage: rho = phi.restrict_domain(V.span([V.0, V.3])) sage: zeta = rho.restrict_codomain(W.span([W.0, W.2])) sage: x = vector(QQ, [2, 0, 0, -7]) sage: y = zeta(x); y (-3, 0, -1) sage: inv = zeta.inverse(); inv Vector space morphism represented by the matrix: [-1 3] [ 1 -2] Domain: Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [1 0 0] [0 0 1] Codomain: Vector space of degree 4 and dimension 2 over Rational Field Basis matrix: [1 0 0 0] [0 0 0 1] sage: inv(y) == x True An example of an invertible morphism between modules, (rather than between vector spaces). :: sage: M = ZZ^4 sage: p = matrix(ZZ, [[ 0, -1, 1, -2], ....: [ 1, -3, 2, -3], ....: [ 0, 4, -3, 4], ....: [-2, 8, -4, 3]]) sage: phi = M.hom(p, M) sage: x = vector(ZZ, [1, -3, 5, -2]) sage: y = phi(x); y (1, 12, -12, 21) sage: rho = phi.inverse(); rho Free module morphism defined by the matrix [ -5 3 -1 1] [ -9 4 -3 2] [-20 8 -7 4] [ -6 2 -2 1] Domain: Ambient free module of rank 4 over the principal ideal domain ... Codomain: Ambient free module of rank 4 over the principal ideal domain ... sage: rho(y) == x True A non-invertible morphism, despite having an appropriate domain and codomain. :: sage: V = QQ^2 sage: m = matrix(QQ, [[1, 2], [20, 40]]) sage: phi = V.hom(m, V) sage: phi.is_bijective() False sage: phi.inverse() Traceback (most recent call last): ... ZeroDivisionError: matrix morphism not invertible The matrix representation of this morphism is invertible over the rationals, but not over the integers, thus the morphism is not invertible as a map between modules. It is easy to notice from the definition that every vector of the image will have a second entry that is an even integer. :: sage: V = ZZ^2 sage: q = matrix(ZZ, [[1, 2], [3, 4]]) sage: phi = V.hom(q, V) sage: phi.matrix().change_ring(QQ).inverse() [ -2 1] [ 3/2 -1/2] sage: phi.is_bijective() False sage: phi.image() Free module of degree 2 and rank 2 over Integer Ring Echelon basis matrix: [1 0] [0 2] sage: phi.lift(vector(ZZ, [1, 1])) Traceback (most recent call last): ... ValueError: element is not in the image sage: phi.inverse() Traceback (most recent call last): ... ZeroDivisionError: matrix morphism not invertible The unary invert operator (~, tilde, "wiggle") is synonymous with the ``inverse()`` method (and a lot easier to type). :: sage: V = QQ^2 sage: r = matrix(QQ, [[4, 3], [-2, 5]]) sage: phi = V.hom(r, V) sage: rho = phi.inverse() sage: zeta = ~phi sage: rho.is_equal_function(zeta) True TESTS:: sage: V = QQ^2 sage: W = QQ^3 sage: U = W.span([W.0, W.1]) sage: m = matrix(QQ, [[2, 1], [3, 4]]) sage: phi = V.hom(m, U) sage: inv = phi.inverse() sage: (inv*phi).is_identity() True sage: (phi*inv).is_identity() True """ return ~self def __rmul__(self, left): """ EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: 2*phi Free module morphism defined by the matrix [2 2] [0 4]... sage: phi*2 Free module morphism defined by the matrix [2 2] [0 4]... """ R = self.base_ring() return self.parent()(R(left) * self.matrix(), side=self.side()) def __mul__(self, right): r""" Composition of morphisms, denoted by \*. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi*phi Free module morphism defined by the matrix [1 3] [0 4] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: V = QQ^3 sage: E = V.endomorphism_ring() sage: phi = E(Matrix(QQ,3,range(9))) ; phi Vector space morphism represented by the matrix: [0 1 2] [3 4 5] [6 7 8] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 3 over Rational Field sage: phi*phi Vector space morphism represented by the matrix: [ 15 18 21] [ 42 54 66] [ 69 90 111] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 3 over Rational Field sage: phi.matrix()**2 [ 15 18 21] [ 42 54 66] [ 69 90 111] :: sage: W = QQ**4 sage: E_VW = V.Hom(W) sage: psi = E_VW(Matrix(QQ,3,4,range(12))) ; psi Vector space morphism represented by the matrix: [ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 4 over Rational Field sage: psi*phi Vector space morphism represented by the matrix: [ 20 23 26 29] [ 56 68 80 92] [ 92 113 134 155] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 4 over Rational Field sage: phi*psi Traceback (most recent call last): ... TypeError: Incompatible composition of morphisms: domain of left morphism must be codomain of right. sage: phi.matrix()*psi.matrix() [ 20 23 26 29] [ 56 68 80 92] [ 92 113 134 155] Composite maps can be formed with matrix morphisms:: sage: K.<a> = NumberField(x^2 + 23) sage: V, VtoK, KtoV = K.vector_space() sage: f = V.hom([V.0 - V.1, V.0 + V.1])*KtoV; f Composite map: From: Number Field in a with defining polynomial x^2 + 23 To: Vector space of dimension 2 over Rational Field Defn: Isomorphism map: From: Number Field in a with defining polynomial x^2 + 23 To: Vector space of dimension 2 over Rational Field then Vector space morphism represented by the matrix: [ 1 -1] [ 1 1] Domain: Vector space of dimension 2 over Rational Field Codomain: Vector space of dimension 2 over Rational Field sage: f(a) (1, 1) sage: V.hom([V.0 - V.1, V.0 + V.1], side="right")*KtoV Composite map: From: Number Field in a with defining polynomial x^2 + 23 To: Vector space of dimension 2 over Rational Field Defn: Isomorphism map: From: Number Field in a with defining polynomial x^2 + 23 To: Vector space of dimension 2 over Rational Field then Vector space morphism represented as left-multiplication by the matrix: [ 1 1] [-1 1] Domain: Vector space of dimension 2 over Rational Field Codomain: Vector space of dimension 2 over Rational Field We can test interraction between morphisms with different ``side``:: sage: V = ZZ^2 sage: m = matrix(2, [1,1,0,1]) sage: hl = V.hom(m) sage: hr = V.hom(m, side="right") sage: hl * hl Free module morphism defined by the matrix [1 2] [0 1]... sage: hl * hr Free module morphism defined by the matrix [1 1] [1 2]... sage: hl * hl.side_switch() Free module morphism defined by the matrix [1 2] [0 1]... sage: hr * hl Free module morphism defined by the matrix [2 1] [1 1]... sage: hl * hl Free module morphism defined by the matrix [1 2] [0 1]... sage: hr / hl Free module morphism defined by the matrix [ 0 -1] [ 1 1]... sage: hr / hr.side_switch() Free module morphism defined by the matrix [1 0] [0 1]... sage: hl / hl Free module morphism defined by the matrix [1 0] [0 1]... sage: hr / hr Free module morphism defined as left-multiplication by the matrix [1 0] [0 1]... .. WARNING:: Matrix morphisms can be defined by either left or right-multiplication. The composite morphism always applies the morphism on the right of \* first. The matrix of the composite morphism of two morphisms given by right-multiplication is not the morphism given by the product of their respective matrices. If the two morphisms act on different sides, then the side of the resulting morphism is the default one. """ if not isinstance(right, MatrixMorphism): if isinstance(right, (sage.categories.morphism.Morphism, sage.categories.map.Map)): return sage.categories.map.Map.__mul__(self, right) R = self.base_ring() return self.parent()(self.matrix() * R(right)) H = right.domain().Hom(self.codomain()) if self.domain() != right.codomain(): raise TypeError("Incompatible composition of morphisms: domain of left morphism must be codomain of right.") if self.side() == "left": if right.side() == "left": return H(right.matrix() * self.matrix(), side=self.side()) else: return H(right.matrix().transpose() * self.matrix(), side=self.side()) else: if right.side() == "right": return H(self.matrix() * right.matrix(), side=self.side()) else: return H(right.matrix() * self.matrix().transpose(), side="left") def __add__(self, right): """ Sum of morphisms, denoted by +. EXAMPLES:: sage: phi = (ZZ**2).endomorphism_ring()(Matrix(ZZ,2,[2..5])) ; phi Free module morphism defined by the matrix [2 3] [4 5] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: phi + 3 Free module morphism defined by the matrix [5 3] [4 8] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: phi + phi Free module morphism defined by the matrix [ 4 6] [ 8 10] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: psi = (ZZ**3).endomorphism_ring()(Matrix(ZZ,3,[22..30])) ; psi Free module morphism defined by the matrix [22 23 24] [25 26 27] [28 29 30] Domain: Ambient free module of rank 3 over the principal ideal domain ... Codomain: Ambient free module of rank 3 over the principal ideal domain ... sage: phi + psi Traceback (most recent call last): ... ValueError: inconsistent number of rows: should be 2 but got 3 :: sage: V = ZZ^2 sage: m = matrix(2, [1,1,0,1]) sage: hl = V.hom(m) sage: hr = V.hom(m, side="right") sage: hl + hl Free module morphism defined by the matrix [2 2] [0 2]... sage: hr + hr Free module morphism defined as left-multiplication by the matrix [2 2] [0 2]... sage: hr + hl Free module morphism defined by the matrix [2 1] [1 2]... sage: hl + hr Free module morphism defined by the matrix [2 1] [1 2]... .. WARNING:: If the two morphisms do not share the same ``side`` attribute, then the resulting morphism will be defined with the default value. """ # TODO: move over to any coercion model! if not isinstance(right, MatrixMorphism): R = self.base_ring() return self.parent()(self.matrix() + R(right)) if not right.parent() == self.parent(): right = self.parent()(right, side=right.side()) if self.side() == "left": if right.side() == "left": return self.parent()(self.matrix() + right.matrix(), side=self.side()) elif right.side() == "right": return self.parent()(self.matrix() + right.matrix().transpose(), side="left") if self.side() == "right": if right.side() == "right": return self.parent()(self.matrix() + right.matrix(), side=self.side()) elif right.side() == "left": return self.parent()(self.matrix().transpose() + right.matrix(), side="left") def __neg__(self): """ EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: -phi Free module morphism defined by the matrix [-1 -1] [ 0 -2]... sage: phi2 = phi.side_switch(); -phi2 Free module morphism defined as left-multiplication by the matrix [-1 0] [-1 -2]... """ return self.parent()(-self.matrix(), side=self.side()) def __sub__(self, other): """ EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi - phi Free module morphism defined by the matrix [0 0] [0 0]... :: sage: V = ZZ^2 sage: m = matrix(2, [1,1,0,1]) sage: hl = V.hom(m) sage: hr = V.hom(m, side="right") sage: hl - hr Free module morphism defined by the matrix [ 0 1] [-1 0]... sage: hl - hl Free module morphism defined by the matrix [0 0] [0 0]... sage: hr - hr Free module morphism defined as left-multiplication by the matrix [0 0] [0 0]... sage: hr-hl Free module morphism defined by the matrix [ 0 -1] [ 1 0]... .. WARNING:: If the two morphisms do not share the same ``side`` attribute, then the resulting morphism will be defined with the default value. """ # TODO: move over to any coercion model! if not isinstance(other, MatrixMorphism): R = self.base_ring() return self.parent()(self.matrix() - R(other), side=self.side()) if not other.parent() == self.parent(): other = self.parent()(other, side=other.side()) if self.side() == "left": if other.side() == "left": return self.parent()(self.matrix() - other.matrix(), side=self.side()) elif other.side() == "right": return self.parent()(self.matrix() - other.matrix().transpose(), side="left") if self.side() == "right": if other.side() == "right": return self.parent()(self.matrix() - other.matrix(), side=self.side()) elif other.side() == "left": return self.parent()(self.matrix().transpose() - other.matrix(), side="left") def base_ring(self): """ Return the base ring of self, that is, the ring over which self is given by a matrix. EXAMPLES:: sage: sage.modules.matrix_morphism.MatrixMorphism((ZZ**2).endomorphism_ring(), Matrix(ZZ,2,[3..6])).base_ring() Integer Ring """ return self.domain().base_ring() def characteristic_polynomial(self, var='x'): r""" Return the characteristic polynomial of this endomorphism. ``characteristic_polynomial`` and ``char_poly`` are the same method. INPUT: - var -- variable EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi.characteristic_polynomial() x^2 - 3*x + 2 sage: phi.charpoly() x^2 - 3*x + 2 sage: phi.matrix().charpoly() x^2 - 3*x + 2 sage: phi.charpoly('T') T^2 - 3*T + 2 """ if not self.is_endomorphism(): raise ArithmeticError("charpoly only defined for endomorphisms " +\ "(i.e., domain = range)") return self.matrix().charpoly(var) charpoly = characteristic_polynomial def decomposition(self, *args, **kwds): """ Return decomposition of this endomorphism, i.e., sequence of subspaces obtained by finding invariant subspaces of self. See the documentation for self.matrix().decomposition for more details. All inputs to this function are passed onto the matrix one. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi.decomposition() [ Free module of degree 2 and rank 1 over Integer Ring Echelon basis matrix: [0 1], Free module of degree 2 and rank 1 over Integer Ring Echelon basis matrix: [ 1 -1] ] sage: phi2 = V.hom(phi.matrix(), side="right") sage: phi2.decomposition() [ Free module of degree 2 and rank 1 over Integer Ring Echelon basis matrix: [1 1], Free module of degree 2 and rank 1 over Integer Ring Echelon basis matrix: [1 0] ] """ if not self.is_endomorphism(): raise ArithmeticError("Matrix morphism must be an endomorphism.") D = self.domain() if self.side() == "left": E = self.matrix().decomposition(*args,**kwds) else: E = self.matrix().transpose().decomposition(*args,**kwds) if D.is_ambient(): return Sequence([D.submodule(V, check=False) for V, _ in E], cr=True, check=False) else: B = D.basis_matrix() R = D.base_ring() return Sequence([D.submodule((V.basis_matrix() * B).row_module(R), check=False) for V, _ in E], cr=True, check=False) def trace(self): r""" Return the trace of this endomorphism. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi.trace() 3 """ return self._matrix.trace() def det(self): """ Return the determinant of this endomorphism. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi.det() 2 """ if not self.is_endomorphism(): raise ArithmeticError("Matrix morphism must be an endomorphism.") return self.matrix().determinant() def fcp(self, var='x'): """ Return the factorization of the characteristic polynomial. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1]) sage: phi.fcp() (x - 2) * (x - 1) sage: phi.fcp('T') (T - 2) * (T - 1) """ return self.charpoly(var).factor() def kernel(self): """ Compute the kernel of this morphism. EXAMPLES:: sage: V = VectorSpace(QQ,3) sage: id = V.Hom(V)(identity_matrix(QQ,3)) sage: null = V.Hom(V)(0*identity_matrix(QQ,3)) sage: id.kernel() Vector space of degree 3 and dimension 0 over Rational Field Basis matrix: [] sage: phi = V.Hom(V)(matrix(QQ,3,range(9))) sage: phi.kernel() Vector space of degree 3 and dimension 1 over Rational Field Basis matrix: [ 1 -2 1] sage: hom(CC^2, CC^2, matrix(CC, [[1,0], [0,1]])).kernel() Vector space of degree 2 and dimension 0 over Complex Field with 53 bits of precision Basis matrix: [] sage: m = matrix(3, [1, 0, 0, 1, 0, 0, 0, 0, 1]); m [1 0 0] [1 0 0] [0 0 1] sage: f1 = V.hom(m) sage: f2 = V.hom(m, side="right") sage: f1.kernel() Vector space of degree 3 and dimension 1 over Rational Field Basis matrix: [ 1 -1 0] sage: f2.kernel() Vector space of degree 3 and dimension 1 over Rational Field Basis matrix: [0 1 0] """ if self.side() == "left": V = self.matrix().left_kernel() else: V = self.matrix().right_kernel() D = self.domain() if not D.is_ambient(): # Transform V to ambient space # This is a matrix multiply: we take the linear combinations of the basis for # D given by the elements of the basis for V. B = V.basis_matrix() * D.basis_matrix() V = B.row_module(D.base_ring()) return self.domain().submodule(V, check=False) def image(self): """ Compute the image of this morphism. EXAMPLES:: sage: V = VectorSpace(QQ,3) sage: phi = V.Hom(V)(matrix(QQ, 3, range(9))) sage: phi.image() Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [ 1 0 -1] [ 0 1 2] sage: hom(GF(7)^3, GF(7)^2, zero_matrix(GF(7), 3, 2)).image() Vector space of degree 2 and dimension 0 over Finite Field of size 7 Basis matrix: [] sage: m = matrix(3, [1, 0, 0, 1, 0, 0, 0, 0, 1]); m [1 0 0] [1 0 0] [0 0 1] sage: f1 = V.hom(m) sage: f2 = V.hom(m, side="right") sage: f1.image() Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [1 0 0] [0 0 1] sage: f2.image() Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [1 1 0] [0 0 1] Compute the image of the identity map on a ZZ-submodule:: sage: V = (ZZ^2).span([[1,2],[3,4]]) sage: phi = V.Hom(V)(identity_matrix(ZZ,2)) sage: phi(V.0) == V.0 True sage: phi(V.1) == V.1 True sage: phi.image() Free module of degree 2 and rank 2 over Integer Ring Echelon basis matrix: [1 0] [0 2] sage: phi.image() == V True """ if self.side() == 'left': V = self.matrix().row_space() else: V = self.matrix().column_space() C = self.codomain() if not C.is_ambient(): # Transform V to ambient space # This is a matrix multiply: we take the linear combinations of the basis for # D given by the elements of the basis for V. B = V.basis_matrix() * C.basis_matrix() V = B.row_module(self.domain().base_ring()) return self.codomain().submodule(V, check=False) def matrix(self): """ EXAMPLES:: sage: V = ZZ^2; phi = V.hom(V.basis()) sage: phi.matrix() [1 0] [0 1] sage: sage.modules.matrix_morphism.MatrixMorphism_abstract.matrix(phi) Traceback (most recent call last): ... NotImplementedError: this method must be overridden in the extension class """ raise NotImplementedError("this method must be overridden in the extension class") def _matrix_(self): """ EXAMPLES: Check that this works with the :func:`matrix` function (:trac:`16844`):: sage: H = Hom(ZZ^2, ZZ^3) sage: x = H.an_element() sage: matrix(x) [0 0 0] [0 0 0] TESTS: ``matrix(x)`` is immutable:: sage: H = Hom(QQ^3, QQ^2) sage: phi = H(matrix(QQ, 3, 2, list(reversed(range(6))))); phi Vector space morphism represented by the matrix: [5 4] [3 2] [1 0] Domain: Vector space of dimension 3 over Rational Field Codomain: Vector space of dimension 2 over Rational Field sage: A = phi.matrix() sage: A[1, 1] = 19 Traceback (most recent call last): ... ValueError: matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M). """ return self.matrix() def rank(self): r""" Returns the rank of the matrix representing this morphism. EXAMPLES:: sage: V = ZZ^2; phi = V.hom(V.basis()) sage: phi.rank() 2 sage: V = ZZ^2; phi = V.hom([V.0, V.0]) sage: phi.rank() 1 """ return self.matrix().rank() def nullity(self): r""" Returns the nullity of the matrix representing this morphism, which is the dimension of its kernel. EXAMPLES:: sage: V = ZZ^2; phi = V.hom(V.basis()) sage: phi.nullity() 0 sage: V = ZZ^2; phi = V.hom([V.0, V.0]) sage: phi.nullity() 1 :: sage: m = matrix(2, [1, 2]) sage: V = ZZ^2 sage: h1 = V.hom(m) sage: h1.nullity() 1 sage: W = ZZ^1 sage: h2 = W.hom(m, side="right") sage: h2.nullity() 0 """ if self.side() == "left": return self._matrix.left_nullity() else: return self._matrix.right_nullity() def is_bijective(self): r""" Tell whether ``self`` is bijective. EXAMPLES: Two morphisms that are obviously not bijective, simply on considerations of the dimensions. However, each fullfills half of the requirements to be a bijection. :: sage: V1 = QQ^2 sage: V2 = QQ^3 sage: m = matrix(QQ, [[1, 2, 3], [4, 5, 6]]) sage: phi = V1.hom(m, V2) sage: phi.is_injective() True sage: phi.is_bijective() False sage: rho = V2.hom(m.transpose(), V1) sage: rho.is_surjective() True sage: rho.is_bijective() False We construct a simple bijection between two one-dimensional vector spaces. :: sage: V1 = QQ^3 sage: V2 = QQ^2 sage: phi = V1.hom(matrix(QQ, [[1, 2], [3, 4], [5, 6]]), V2) sage: x = vector(QQ, [1, -1, 4]) sage: y = phi(x); y (18, 22) sage: rho = phi.restrict_domain(V1.span([x])) sage: zeta = rho.restrict_codomain(V2.span([y])) sage: zeta.is_bijective() True AUTHOR: - Rob Beezer (2011-06-28) """ return self.is_injective() and self.is_surjective() def is_identity(self): r""" Determines if this morphism is an identity function or not. EXAMPLES: A homomorphism that cannot possibly be the identity due to an unequal domain and codomain. :: sage: V = QQ^3 sage: W = QQ^2 sage: m = matrix(QQ, [[1, 2], [3, 4], [5, 6]]) sage: phi = V.hom(m, W) sage: phi.is_identity() False A bijection, but not the identity. :: sage: V = QQ^3 sage: n = matrix(QQ, [[3, 1, -8], [5, -4, 6], [1, 1, -5]]) sage: phi = V.hom(n, V) sage: phi.is_bijective() True sage: phi.is_identity() False A restriction that is the identity. :: sage: V = QQ^3 sage: p = matrix(QQ, [[1, 0, 0], [5, 8, 3], [0, 0, 1]]) sage: phi = V.hom(p, V) sage: rho = phi.restrict(V.span([V.0, V.2])) sage: rho.is_identity() True An identity linear transformation that is defined with a domain and codomain with wildly different bases, so that the matrix representation is not simply the identity matrix. :: sage: A = matrix(QQ, [[1, 1, 0], [2, 3, -4], [2, 4, -7]]) sage: B = matrix(QQ, [[2, 7, -2], [-1, -3, 1], [-1, -6, 2]]) sage: U = (QQ^3).subspace_with_basis(A.rows()) sage: V = (QQ^3).subspace_with_basis(B.rows()) sage: H = Hom(U, V) sage: id = lambda x: x sage: phi = H(id) sage: phi([203, -179, 34]) (203, -179, 34) sage: phi.matrix() [ 1 0 1] [ -9 -18 -2] [-17 -31 -5] sage: phi.is_identity() True TESTS:: sage: V = QQ^10 sage: H = Hom(V, V) sage: id = H.identity() sage: id.is_identity() True AUTHOR: - Rob Beezer (2011-06-28) """ if self.domain() != self.codomain(): return False # testing for the identity matrix will only work for # endomorphisms which have the same basis for domain and codomain # so we test equality on a basis, which is sufficient return all( self(u) == u for u in self.domain().basis() ) def is_zero(self): r""" Determines if this morphism is a zero function or not. EXAMPLES: A zero morphism created from a function. :: sage: V = ZZ^5 sage: W = ZZ^3 sage: z = lambda x: zero_vector(ZZ, 3) sage: phi = V.hom(z, W) sage: phi.is_zero() True An image list that just barely makes a non-zero morphism. :: sage: V = ZZ^4 sage: W = ZZ^6 sage: z = zero_vector(ZZ, 6) sage: images = [z, z, W.5, z] sage: phi = V.hom(images, W) sage: phi.is_zero() False TESTS:: sage: V = QQ^10 sage: W = QQ^3 sage: H = Hom(V, W) sage: rho = H.zero() sage: rho.is_zero() True AUTHOR: - Rob Beezer (2011-07-15) """ # any nonzero entry in any matrix representation # disqualifies the morphism as having totally zero outputs return self._matrix.is_zero() def is_equal_function(self, other): r""" Determines if two morphisms are equal functions. INPUT: - ``other`` - a morphism to compare with ``self`` OUTPUT: Returns ``True`` precisely when the two morphisms have equal domains and codomains (as sets) and produce identical output when given the same input. Otherwise returns ``False``. This is useful when ``self`` and ``other`` may have different representations. Sage's default comparison of matrix morphisms requires the domains to have the same bases and the codomains to have the same bases, and then compares the matrix representations. This notion of equality is more permissive (it will return ``True`` "more often"), but is more correct mathematically. EXAMPLES: Three morphisms defined by combinations of different bases for the domain and codomain and different functions. Two are equal, the third is different from both of the others. :: sage: B = matrix(QQ, [[-3, 5, -4, 2], ....: [-1, 2, -1, 4], ....: [ 4, -6, 5, -1], ....: [-5, 7, -6, 1]]) sage: U = (QQ^4).subspace_with_basis(B.rows()) sage: C = matrix(QQ, [[-1, -6, -4], ....: [ 3, -5, 6], ....: [ 1, 2, 3]]) sage: V = (QQ^3).subspace_with_basis(C.rows()) sage: H = Hom(U, V) sage: D = matrix(QQ, [[-7, -2, -5, 2], ....: [-5, 1, -4, -8], ....: [ 1, -1, 1, 4], ....: [-4, -1, -3, 1]]) sage: X = (QQ^4).subspace_with_basis(D.rows()) sage: E = matrix(QQ, [[ 4, -1, 4], ....: [ 5, -4, -5], ....: [-1, 0, -2]]) sage: Y = (QQ^3).subspace_with_basis(E.rows()) sage: K = Hom(X, Y) sage: f = lambda x: vector(QQ, [x[0]+x[1], 2*x[1]-4*x[2], 5*x[3]]) sage: g = lambda x: vector(QQ, [x[0]-x[2], 2*x[1]-4*x[2], 5*x[3]]) sage: rho = H(f) sage: phi = K(f) sage: zeta = H(g) sage: rho.is_equal_function(phi) True sage: phi.is_equal_function(rho) True sage: zeta.is_equal_function(rho) False sage: phi.is_equal_function(zeta) False TESTS:: sage: H = Hom(ZZ^2, ZZ^2) sage: phi = H(matrix(ZZ, 2, range(4))) sage: phi.is_equal_function('junk') Traceback (most recent call last): ... TypeError: can only compare to a matrix morphism, not junk AUTHOR: - Rob Beezer (2011-07-15) """ if not is_MatrixMorphism(other): msg = 'can only compare to a matrix morphism, not {0}' raise TypeError(msg.format(other)) if self.domain() != other.domain(): return False if self.codomain() != other.codomain(): return False # check agreement on any basis of the domain return all( self(u) == other(u) for u in self.domain().basis() ) def restrict_domain(self, sub): """ Restrict this matrix morphism to a subspace sub of the domain. The subspace sub should have a basis() method and elements of the basis should be coercible into domain. The resulting morphism has the same codomain as before, but a new domain. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1]) sage: phi.restrict_domain(V.span([V.0])) Free module morphism defined by the matrix [3 0] Domain: Free module of degree 2 and rank 1 over Integer Ring Echelon ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: phi.restrict_domain(V.span([V.1])) Free module morphism defined by the matrix [0 2]... sage: m = matrix(2, range(1,5)) sage: f1 = V.hom(m); f2 = V.hom(m, side="right") sage: SV = V.span([V.0]) sage: f1.restrict_domain(SV) Free module morphism defined by the matrix [1 2]... sage: f2.restrict_domain(SV) Free module morphism defined as left-multiplication by the matrix [1] [3]... """ D = self.domain() if hasattr(D, 'coordinate_module'): # We only have to do this in case the module supports # alternative basis. Some modules do, some modules don't. V = D.coordinate_module(sub) else: V = sub.free_module() if self.side() == "right": A = self.matrix().transpose().restrict_domain(V).transpose() else: A = self.matrix().restrict_domain(V) H = sub.Hom(self.codomain()) try: return H(A, side=self.side()) except: return H(A) def restrict_codomain(self, sub): """ Restrict this matrix morphism to a subspace sub of the codomain. The resulting morphism has the same domain as before, but a new codomain. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([4*(V.0+V.1),0]) sage: W = V.span([2*(V.0+V.1)]) sage: phi Free module morphism defined by the matrix [4 4] [0 0] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Ambient free module of rank 2 over the principal ideal domain ... sage: psi = phi.restrict_codomain(W); psi Free module morphism defined by the matrix [2] [0] Domain: Ambient free module of rank 2 over the principal ideal domain ... Codomain: Free module of degree 2 and rank 1 over Integer Ring Echelon ... sage: phi2 = phi.side_switch(); phi2.restrict_codomain(W) Free module morphism defined as left-multiplication by the matrix [2 0] Domain: Ambient free module of rank 2 over the principal ideal domain Integer Ring Codomain: Free module of degree 2 and rank 1 over Integer Ring Echelon ... An example in which the codomain equals the full ambient space, but with a different basis:: sage: V = QQ^2 sage: W = V.span_of_basis([[1,2],[3,4]]) sage: phi = V.hom(matrix(QQ,2,[1,0,2,0]),W) sage: phi.matrix() [1 0] [2 0] sage: phi(V.0) (1, 2) sage: phi(V.1) (2, 4) sage: X = V.span([[1,2]]); X Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [1 2] sage: phi(V.0) in X True sage: phi(V.1) in X True sage: psi = phi.restrict_codomain(X); psi Vector space morphism represented by the matrix: [1] [2] Domain: Vector space of dimension 2 over Rational Field Codomain: Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [1 2] sage: psi(V.0) (1, 2) sage: psi(V.1) (2, 4) sage: psi(V.0).parent() is X True """ H = self.domain().Hom(sub) C = self.codomain() if hasattr(C, 'coordinate_module'): # We only have to do this in case the module supports # alternative basis. Some modules do, some modules don't. V = C.coordinate_module(sub) else: V = sub.free_module() try: if self.side() == "right": return H(self.matrix().transpose().restrict_codomain(V).transpose(), side="right") else: return H(self.matrix().restrict_codomain(V)) except: return H(self.matrix().restrict_codomain(V)) def restrict(self, sub): """ Restrict this matrix morphism to a subspace sub of the domain. The codomain and domain of the resulting matrix are both sub. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1]) sage: phi.restrict(V.span([V.0])) Free module morphism defined by the matrix [3] Domain: Free module of degree 2 and rank 1 over Integer Ring Echelon ... Codomain: Free module of degree 2 and rank 1 over Integer Ring Echelon ... sage: V = (QQ^2).span_of_basis([[1,2],[3,4]]) sage: phi = V.hom([V.0+V.1, 2*V.1]) sage: phi(V.1) == 2*V.1 True sage: W = span([V.1]) sage: phi(W) Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [ 1 4/3] sage: psi = phi.restrict(W); psi Vector space morphism represented by the matrix: [2] Domain: Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [ 1 4/3] Codomain: Vector space of degree 2 and dimension 1 over Rational Field Basis matrix: [ 1 4/3] sage: psi.domain() == W True sage: psi(W.0) == 2*W.0 True :: sage: V = ZZ^3 sage: h1 = V.hom([V.0, V.1+V.2, -V.1+V.2]) sage: h2 = h1.side_switch() sage: SV = V.span([2*V.1,2*V.2]) sage: h1.restrict(SV) Free module morphism defined by the matrix [ 1 1] [-1 1] Domain: Free module of degree 3 and rank 2 over Integer Ring Echelon basis matrix: [0 2 0] [0 0 2] Codomain: Free module of degree 3 and rank 2 over Integer Ring Echelon basis matrix: [0 2 0] [0 0 2] sage: h2.restrict(SV) Free module morphism defined as left-multiplication by the matrix [ 1 -1] [ 1 1] Domain: Free module of degree 3 and rank 2 over Integer Ring Echelon basis matrix: [0 2 0] [0 0 2] Codomain: Free module of degree 3 and rank 2 over Integer Ring Echelon basis matrix: [0 2 0] [0 0 2] """ if not self.is_endomorphism(): raise ArithmeticError("matrix morphism must be an endomorphism") D = self.domain() C = self.codomain() if D is not C and (D.basis() != C.basis()): # Tricky case when two bases for same space return self.restrict_domain(sub).restrict_codomain(sub) if hasattr(D, 'coordinate_module'): # We only have to do this in case the module supports # alternative basis. Some modules do, some modules don't. V = D.coordinate_module(sub) else: V = sub.free_module() if self.side() == "right": A = self.matrix().transpose().restrict(V).transpose() else: A = self.matrix().restrict(V) H = sage.categories.homset.End(sub, self.domain().category()) return H(A, side=self.side()) class MatrixMorphism(MatrixMorphism_abstract): """ A morphism defined by a matrix. INPUT: - ``parent`` -- a homspace - ``A`` -- matrix or a :class:`MatrixMorphism_abstract` instance - ``copy_matrix`` -- (default: ``True``) make an immutable copy of the matrix ``A`` if it is mutable; if ``False``, then this makes ``A`` immutable """ def __init__(self, parent, A, copy_matrix=True, side='left'): """ Initialize ``self``. EXAMPLES:: sage: from sage.modules.matrix_morphism import MatrixMorphism sage: T = End(ZZ^3) sage: M = MatrixSpace(ZZ,3) sage: I = M.identity_matrix() sage: A = MatrixMorphism(T, I) sage: loads(A.dumps()) == A True """ if parent is None: raise ValueError("no parent given when creating this matrix morphism") if isinstance(A, MatrixMorphism_abstract): A = A.matrix() if side == "left": if A.nrows() != parent.domain().rank(): raise ArithmeticError("number of rows of matrix (={}) must equal rank of domain (={})".format(A.nrows(), parent.domain().rank())) if A.ncols() != parent.codomain().rank(): raise ArithmeticError("number of columns of matrix (={}) must equal rank of codomain (={})".format(A.ncols(), parent.codomain().rank())) if side == "right": if A.nrows() != parent.codomain().rank(): raise ArithmeticError("number of rows of matrix (={}) must equal rank of codomain (={})".format(A.nrows(), parent.domain().rank())) if A.ncols() != parent.domain().rank(): raise ArithmeticError("number of columns of matrix (={}) must equal rank of domain (={})".format(A.ncols(), parent.codomain().rank())) if A.is_mutable(): if copy_matrix: from copy import copy A = copy(A) A.set_immutable() self._matrix = A MatrixMorphism_abstract.__init__(self, parent, side) def matrix(self, side=None): r""" Return a matrix that defines this morphism. INPUT: - ``side`` -- (default: ``'None'``) the side of the matrix where a vector is placed to effect the morphism (function) OUTPUT: A matrix which represents the morphism, relative to bases for the domain and codomain. If the modules are provided with user bases, then the representation is relative to these bases. Internally, Sage represents a matrix morphism with the matrix multiplying a row vector placed to the left of the matrix. If the option ``side='right'`` is used, then a matrix is returned that acts on a vector to the right of the matrix. These two matrices are just transposes of each other and the difference is just a preference for the style of representation. EXAMPLES:: sage: V = ZZ^2; W = ZZ^3 sage: m = column_matrix([3*V.0 - 5*V.1, 4*V.0 + 2*V.1, V.0 + V.1]) sage: phi = V.hom(m, W) sage: phi.matrix() [ 3 4 1] [-5 2 1] sage: phi.matrix(side='right') [ 3 -5] [ 4 2] [ 1 1] TESTS:: sage: V = ZZ^2 sage: phi = V.hom([3*V.0, 2*V.1]) sage: phi.matrix(side='junk') Traceback (most recent call last): ... ValueError: side must be 'left' or 'right', not junk """ if side not in ['left', 'right', None]: raise ValueError("side must be 'left' or 'right', not {0}".format(side)) if side == self.side() or side is None: return self._matrix return self._matrix.transpose() def is_injective(self): """ Tell whether ``self`` is injective. EXAMPLES:: sage: V1 = QQ^2 sage: V2 = QQ^3 sage: phi = V1.hom(Matrix([[1,2,3],[4,5,6]]),V2) sage: phi.is_injective() True sage: psi = V2.hom(Matrix([[1,2],[3,4],[5,6]]),V1) sage: psi.is_injective() False AUTHOR: -- Simon King (2010-05) """ if self.side() == 'left': ker = self._matrix.left_kernel() else: ker = self._matrix.right_kernel() return ker.dimension() == 0 def is_surjective(self): r""" Tell whether ``self`` is surjective. EXAMPLES:: sage: V1 = QQ^2 sage: V2 = QQ^3 sage: phi = V1.hom(Matrix([[1,2,3],[4,5,6]]), V2) sage: phi.is_surjective() False sage: psi = V2.hom(Matrix([[1,2],[3,4],[5,6]]), V1) sage: psi.is_surjective() True An example over a PID that is not `\ZZ`. :: sage: R = PolynomialRing(QQ, 'x') sage: A = R^2 sage: B = R^2 sage: H = A.hom([B([x^2-1, 1]), B([x^2, 1])]) sage: H.image() Free module of degree 2 and rank 2 over Univariate Polynomial Ring in x over Rational Field Echelon basis matrix: [ 1 0] [ 0 -1] sage: H.is_surjective() True This tests if :trac:`11552` is fixed. :: sage: V = ZZ^2 sage: m = matrix(ZZ, [[1,2],[0,2]]) sage: phi = V.hom(m, V) sage: phi.lift(vector(ZZ, [0, 1])) Traceback (most recent call last): ... ValueError: element is not in the image sage: phi.is_surjective() False AUTHORS: - Simon King (2010-05) - Rob Beezer (2011-06-28) """ # Testing equality of free modules over PIDs is unreliable # see Trac #11579 for explanation and status # We test if image equals codomain with two inclusions # reverse inclusion of below is trivially true return self.codomain().is_submodule(self.image()) def _repr_(self): r""" Return string representation of this matrix morphism. This will typically be overloaded in a derived class. EXAMPLES:: sage: V = ZZ^2; phi = V.hom([3*V.0, 2*V.1]) sage: sage.modules.matrix_morphism.MatrixMorphism._repr_(phi) 'Morphism defined by the matrix\n[3 0]\n[0 2]' sage: phi._repr_() 'Free module morphism defined by the matrix\n[3 0]\n[0 2]\nDomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring\nCodomain: Ambient free module of rank 2 over the principal ideal domain Integer Ring' """ rep = "Morphism defined by the matrix\n{0}".format(self.matrix()) if self._side == 'right': rep += " acting by multiplication on the left" return rep
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/modules/matrix_morphism.py
0.839273
0.742492
matrix_morphism.py
pypi
from sage.geometry.polyhedron.constructor import Polyhedron from sage.matrix.constructor import matrix, identity_matrix from sage.modules.free_module_element import vector from math import sqrt, floor, ceil def plane_inequality(v): """ Return the inequality for points on the same side as the origin with respect to the plane through ``v`` normal to ``v``. EXAMPLES:: sage: from sage.modules.diamond_cutting import plane_inequality sage: ieq = plane_inequality([1, -1]); ieq [2, -1, 1] sage: ieq[0] + vector(ieq[1:]) * vector([1, -1]) 0 """ v = vector(v) c = -v * v if c < 0: c, v = -c, -v return [c] + list(v) def jacobi(M): r""" Compute the upper-triangular part of the Cholesky/Jacobi decomposition of the symmetric matrix ``M``. Let `M` be a symmetric `n \times n`-matrix over a field `F`. Let `m_{i,j}` denote the `(i,j)`-th entry of `M` for any `1 \leq i \leq n` and `1 \leq j \leq n`. Then, the upper-triangular part computed by this method is the upper-triangular `n \times n`-matrix `Q` whose `(i,j)`-th entry `q_{i,j}` satisfies .. MATH:: q_{i,j} = \begin{cases} \frac{1}{q_{i,i}} \left( m_{i,j} - \sum_{r<i} q_{r,r} q_{r,i} q_{r,j} \right) & i < j, \\ a_{i,j} - \sum_{r<i} q_{r,r} q_{r,i}^2 & i = j, \\ 0 & i > j, \end{cases} for all `1 \leq i \leq n` and `1 \leq j \leq n`. (These equalities determine the entries of `Q` uniquely by recursion.) This matrix `Q` is defined for all `M` in a certain Zariski-dense open subset of the set of all `n \times n`-matrices. .. NOTE:: This should be a method of matrices. EXAMPLES:: sage: from sage.modules.diamond_cutting import jacobi sage: jacobi(identity_matrix(3) * 4) [4 0 0] [0 4 0] [0 0 4] sage: def testall(M): ....: Q = jacobi(M) ....: for j in range(3): ....: for i in range(j): ....: if Q[i,j] * Q[i,i] != M[i,j] - sum(Q[r,i] * Q[r,j] * Q[r,r] for r in range(i)): ....: return False ....: for i in range(3): ....: if Q[i,i] != M[i,i] - sum(Q[r,i] ** 2 * Q[r,r] for r in range(i)): ....: return False ....: for j in range(i): ....: if Q[i,j] != 0: ....: return False ....: return True sage: M = Matrix(QQ, [[8,1,5], [1,6,0], [5,0,3]]) sage: Q = jacobi(M); Q [ 8 1/8 5/8] [ 0 47/8 -5/47] [ 0 0 -9/47] sage: testall(M) True sage: M = Matrix(QQ, [[3,6,-1,7],[6,9,8,5],[-1,8,2,4],[7,5,4,0]]) sage: testall(M) True """ if not M.is_square(): raise ValueError("the matrix must be square") dim = M.nrows() q = [list(row) for row in M] for i in range(dim - 1): for j in range(i + 1, dim): q[j][i] = q[i][j] q[i][j] = q[i][j] / q[i][i] for k in range(i + 1, dim): for l in range(k, dim): q[k][l] -= q[k][i] * q[i][l] for i in range(1, dim): for j in range(i): q[i][j] = 0 return matrix(q) def diamond_cut(V, GM, C, verbose=False): r""" Perform diamond cutting on polyhedron ``V`` with basis matrix ``GM`` and radius ``C``. INPUT: - ``V`` -- polyhedron to cut from - ``GM`` -- half of the basis matrix of the lattice - ``C`` -- radius to use in cutting algorithm - ``verbose`` -- (default: ``False``) whether to print debug information OUTPUT: A :class:`Polyhedron` instance. EXAMPLES:: sage: from sage.modules.diamond_cutting import diamond_cut sage: V = Polyhedron([[0], [2]]) sage: GM = matrix([2]) sage: V = diamond_cut(V, GM, 4) sage: V.vertices() (A vertex at (2), A vertex at (0)) """ if verbose: print("Cut\n{}\nwith radius {}".format(GM, C)) dim = GM.dimensions() if dim[0] != dim[1]: raise ValueError("the matrix must be square") dim = dim[0] T = [0] * dim U = [0] * dim x = [0] * dim L = [0] * dim # calculate the Gram matrix q = matrix([[sum(GM[i][k] * GM[j][k] for k in range(dim)) for j in range(dim)] for i in range(dim)]) if verbose: print("q:\n{}".format(q.n())) # apply Cholesky/Jacobi decomposition q = jacobi(q) if verbose: print("q:\n{}".format(q.n())) i = dim - 1 T[i] = C U[i] = 0 new_dimension = True cut_count = 0 inequalities = [] while True: if verbose: print("Dimension: {}".format(i)) if new_dimension: Z = sqrt(T[i] / q[i][i]) if verbose: print("Z: {}".format(Z)) L[i] = int(floor(Z - U[i])) if verbose: print("L: {}".format(L)) x[i] = int(ceil(-Z - U[i]) - 1) new_dimension = False x[i] += 1 if verbose: print("x: {}".format(x)) if x[i] > L[i]: i += 1 elif i > 0: T[i - 1] = T[i] - q[i][i] * (x[i] + U[i]) ** 2 i -= 1 U[i] = 0 for j in range(i + 1, dim): U[i] += q[i][j] * x[j] new_dimension = True else: if all(elmt == 0 for elmt in x): break hv = [0] * dim for k in range(dim): for j in range(dim): hv[k] += x[j] * GM[j][k] hv = vector(hv) for hv in [hv, -hv]: cut_count += 1 if verbose: print("\n%d) Cut using normal vector %s" % (cut_count, hv)) inequalities.append(plane_inequality(hv)) if verbose: print("Final cut") cut = Polyhedron(ieqs=inequalities) V = V.intersection(cut) if verbose: print("End") return V def calculate_voronoi_cell(basis, radius=None, verbose=False): """ Calculate the Voronoi cell of the lattice defined by basis INPUT: - ``basis`` -- embedded basis matrix of the lattice - ``radius`` -- radius of basis vectors to consider - ``verbose`` -- whether to print debug information OUTPUT: A :class:`Polyhedron` instance. EXAMPLES:: sage: from sage.modules.diamond_cutting import calculate_voronoi_cell sage: V = calculate_voronoi_cell(matrix([[1, 0], [0, 1]])) sage: V.volume() 1 """ dim = basis.dimensions() artificial_length = None if dim[0] < dim[1]: # introduce "artificial" basis points (representing infinity) def approx_norm(v): r,r1 = (v.inner_product(v)).sqrtrem() return r + (r1 > 0) artificial_length = max(approx_norm(v) for v in basis) * 2 additional_vectors = identity_matrix(dim[1]) * artificial_length basis = basis.stack(additional_vectors) # LLL-reduce to get quadratic matrix basis = basis.LLL() basis = matrix([v for v in basis if v]) dim = basis.dimensions() if dim[0] != dim[1]: raise ValueError("invalid matrix") basis = basis / 2 ieqs = [] for v in basis: ieqs.append(plane_inequality(v)) ieqs.append(plane_inequality(-v)) Q = Polyhedron(ieqs=ieqs) # twice the length of longest vertex in Q is a safe choice if radius is None: radius = 2 * max(v.inner_product(v) for v in basis) V = diamond_cut(Q, basis, radius, verbose=verbose) if artificial_length is not None: # remove inequalities introduced by artificial basis points H = V.Hrepresentation() H = [v for v in H if all(not V._is_zero(v.A() * w / 2 - v.b()) and not V._is_zero(v.A() * (-w) / 2 - v.b()) for w in additional_vectors)] V = Polyhedron(ieqs=H) return V
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/modules/diamond_cutting.py
0.880277
0.769643
diamond_cutting.py
pypi
from sage.misc.abstract_method import abstract_method from sage.structure.element import Element from sage.combinat.free_module import CombinatorialFreeModule from sage.categories.modules import Modules class Representation_abstract(CombinatorialFreeModule): """ Abstract base class for representations of semigroups. INPUT: - ``semigroup`` -- a semigroup - ``base_ring`` -- a commutative ring """ def __init__(self, semigroup, base_ring, *args, **opts): """ Initialize ``self``. EXAMPLES:: sage: G = FreeGroup(3) sage: T = G.trivial_representation() sage: TestSuite(T).run() """ self._semigroup = semigroup self._semigroup_algebra = semigroup.algebra(base_ring) CombinatorialFreeModule.__init__(self, base_ring, *args, **opts) def semigroup(self): """ Return the semigroup whose representation ``self`` is. EXAMPLES:: sage: G = SymmetricGroup(4) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, g.sign()) sage: R = Representation(G, M, on_basis) sage: R.semigroup() Symmetric group of order 4! as a permutation group """ return self._semigroup def semigroup_algebra(self): """ Return the semigroup algebra whose representation ``self`` is. EXAMPLES:: sage: G = SymmetricGroup(4) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, g.sign()) sage: R = Representation(G, M, on_basis) sage: R.semigroup_algebra() Symmetric group algebra of order 4 over Rational Field """ return self._semigroup_algebra @abstract_method def side(self): """ Return whether ``self`` is a left, right, or two-sided representation. OUTPUT: - the string ``"left"``, ``"right"``, or ``"twosided"`` EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation() sage: R.side() 'left' """ def invariant_module(self, S=None, **kwargs): r""" Return the submodule of ``self`` invariant under the action of ``S``. For a semigroup `S` acting on a module `M`, the invariant submodule is given by .. MATH:: M^S = \{m \in M : s \cdot m = m \forall s \in S\}. INPUT: - ``S`` -- a finitely-generated semigroup (default: the semigroup this is a representation of) - ``action`` -- a function (default: :obj:`operator.mul`) - ``side`` -- ``'left'`` or ``'right'`` (default: :meth:`side()`); which side of ``self`` the elements of ``S`` acts .. NOTE:: Two sided actions are considered as left actions for the invariant module. OUTPUT: - :class:`~sage.modules.with_basis.invariant.FiniteDimensionalInvariantModule` EXAMPLES:: sage: S3 = SymmetricGroup(3) sage: M = S3.regular_representation() sage: I = M.invariant_module() sage: [I.lift(b) for b in I.basis()] [() + (2,3) + (1,2) + (1,2,3) + (1,3,2) + (1,3)] We build the `D_4`-invariant representation inside of the regular representation of `S_4`:: sage: D4 = groups.permutation.Dihedral(4) sage: S4 = SymmetricGroup(4) sage: R = S4.regular_representation() sage: I = R.invariant_module(D4) sage: [I.lift(b) for b in I.basis()] [() + (2,4) + (1,2)(3,4) + (1,2,3,4) + (1,3) + (1,3)(2,4) + (1,4,3,2) + (1,4)(2,3), (3,4) + (2,3,4) + (1,2) + (1,2,4) + (1,3,2) + (1,3,2,4) + (1,4,3) + (1,4,2,3), (2,3) + (2,4,3) + (1,2,3) + (1,2,4,3) + (1,3,4,2) + (1,3,4) + (1,4,2) + (1,4)] """ if S is None: S = self.semigroup() side = kwargs.pop('side', self.side()) if side == "twosided": side = "left" return super().invariant_module(S, side=side, **kwargs) def twisted_invariant_module(self, chi, G=None, **kwargs): r""" Create the isotypic component of the action of ``G`` on ``self`` with irreducible character given by ``chi``. .. SEEALSO:: - :class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule` INPUT: - ``chi`` -- a list/tuple of character values or an instance of :class:`~sage.groups.class_function.ClassFunction_gap` - ``G`` -- a finitely-generated semigroup (default: the semigroup this is a representation of) This also accepts the group to be the first argument to be the group. OUTPUT: - :class:`~sage.modules.with_basis.invariant.FiniteDimensionalTwistedInvariantModule` EXAMPLES:: sage: G = SymmetricGroup(3) sage: R = G.regular_representation(QQ) sage: T = R.twisted_invariant_module([2,0,-1]) sage: T.basis() Finite family {0: B[0], 1: B[1], 2: B[2], 3: B[3]} sage: [T.lift(b) for b in T.basis()] [() - (1,2,3), -(1,2,3) + (1,3,2), (2,3) - (1,2), -(1,2) + (1,3)] We check the different inputs work sage: R.twisted_invariant_module([2,0,-1], G) is T True sage: R.twisted_invariant_module(G, [2,0,-1]) is T True """ from sage.categories.groups import Groups if G is None: G = self.semigroup() elif chi in Groups(): G, chi = chi, G side = kwargs.pop('side', self.side()) if side == "twosided": side = "left" return super().twisted_invariant_module(G, chi, side=side, **kwargs) class Representation(Representation_abstract): """ Representation of a semigroup. INPUT: - ``semigroup`` -- a semigroup - ``module`` -- a module with a basis - ``on_basis`` -- function which takes as input ``g``, ``m``, where ``g`` is an element of the semigroup and ``m`` is an element of the indexing set for the basis, and returns the result of ``g`` acting on ``m`` - ``side`` -- (default: ``"left"``) whether this is a ``"left"`` or ``"right"`` representation EXAMPLES: We construct the sign representation of a symmetric group:: sage: G = SymmetricGroup(4) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, g.sign()) sage: R = Representation(G, M, on_basis) sage: x = R.an_element(); x 2*B['v'] sage: c,s = G.gens() sage: c,s ((1,2,3,4), (1,2)) sage: c * x -2*B['v'] sage: s * x -2*B['v'] sage: c * s * x 2*B['v'] sage: (c * s) * x 2*B['v'] This extends naturally to the corresponding group algebra:: sage: A = G.algebra(QQ) sage: s,c = A.algebra_generators() sage: c,s ((1,2,3,4), (1,2)) sage: c * x -2*B['v'] sage: s * x -2*B['v'] sage: c * s * x 2*B['v'] sage: (c * s) * x 2*B['v'] sage: (c + s) * x -4*B['v'] REFERENCES: - :wikipedia:`Group_representation` """ def __init__(self, semigroup, module, on_basis, side="left", **kwargs): """ Initialize ``self``. EXAMPLES:: sage: G = SymmetricGroup(4) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, g.sign()) sage: R = Representation(G, M, on_basis) sage: R._test_representation() sage: G = CyclicPermutationGroup(3) sage: M = algebras.Exterior(QQ, 'x', 3) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.prod([M.monomial((g(j+1)-1,)) for j in m]) #cyclically permute generators sage: from sage.categories.algebras import Algebras sage: R = Representation(G, M, on_basis, category=Algebras(QQ).WithBasis().FiniteDimensional()) sage: r = R.an_element(); r 1 + 2*x0 + x0*x1 + 3*x1 sage: r*r 1 + 4*x0 + 2*x0*x1 + 6*x1 sage: x0, x1, x2 = M.gens() sage: s = R(x0*x1) sage: g = G.an_element() sage: g*s x1*x2 sage: g*R(x1*x2) -x0*x2 sage: g*r 1 + 2*x1 + x1*x2 + 3*x2 sage: g^2*r 1 + 3*x0 - x0*x2 + 2*x2 sage: G = SymmetricGroup(4) sage: A = SymmetricGroup(4).algebra(QQ) sage: from sage.categories.algebras import Algebras sage: from sage.modules.with_basis.representation import Representation sage: action = lambda g,x: A.monomial(g*x) sage: category = Algebras(QQ).WithBasis().FiniteDimensional() sage: R = Representation(G, A, action, 'left', category=category) sage: r = R.an_element(); r () + (2,3,4) + 2*(1,3)(2,4) + 3*(1,4)(2,3) sage: r^2 14*() + 2*(2,3,4) + (2,4,3) + 12*(1,2)(3,4) + 3*(1,2,4) + 2*(1,3,2) + 4*(1,3)(2,4) + 5*(1,4,3) + 6*(1,4)(2,3) sage: g = G.an_element(); g (2,3,4) sage: g*r (2,3,4) + (2,4,3) + 2*(1,3,2) + 3*(1,4,3) """ try: self.product_on_basis = module.product_on_basis except AttributeError: pass category = kwargs.pop('category', Modules(module.base_ring()).WithBasis()) if side not in ["left", "right"]: raise ValueError('side must be "left" or "right"') self._left_repr = (side == "left") self._on_basis = on_basis self._module = module indices = module.basis().keys() if 'FiniteDimensional' in module.category().axioms(): category = category.FiniteDimensional() Representation_abstract.__init__(self, semigroup, module.base_ring(), indices, category=category, **module.print_options()) def _test_representation(self, **options): """ Check (on some elements) that ``self`` is a representation of the given semigroup. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation() sage: R._test_representation() sage: G = CoxeterGroup(['A',4,1], base_ring=ZZ) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, (-1)**g.length()) sage: R = Representation(G, M, on_basis, side="right") sage: R._test_representation(max_runs=500) """ from sage.misc.functional import sqrt tester = self._tester(**options) S = tester.some_elements() L = [] max_len = int(sqrt(tester._max_runs)) + 1 for i,x in enumerate(self._semigroup): L.append(x) if i >= max_len: break for x in L: for y in L: for elt in S: if self._left_repr: tester.assertEqual(x*(y*elt), (x*y)*elt) else: tester.assertEqual((elt*y)*x, elt*(y*x)) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: P = Permutations(4) sage: M = CombinatorialFreeModule(QQ, ['v']) sage: from sage.modules.with_basis.representation import Representation sage: on_basis = lambda g,m: M.term(m, g.sign()) sage: Representation(P, M, on_basis) Representation of Standard permutations of 4 indexed by {'v'} over Rational Field """ return "Representation of {} indexed by {} over {}".format( self._semigroup, self.basis().keys(), self.base_ring()) def _repr_term(self, b): """ Return a string representation of a basis index ``b`` of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: R = SGA.regular_representation() sage: all(R._repr_term(b) == SGA._repr_term(b) for b in SGA.basis().keys()) True """ return self._module._repr_term(b) def _latex_term(self, b): """ Return a LaTeX representation of a basis index ``b`` of ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: R = SGA.regular_representation() sage: all(R._latex_term(b) == SGA._latex_term(b) for b in SGA.basis().keys()) True """ return self._module._latex_term(b) def _element_constructor_(self, x): """ Construct an element of ``self`` from ``x``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: A = G.algebra(ZZ) sage: R = A.regular_representation() sage: x = A.an_element(); x () + (1,3) + 2*(1,3)(2,4) + 3*(1,4,3,2) sage: R(x) () + (1,3) + 2*(1,3)(2,4) + 3*(1,4,3,2) """ if isinstance(x, Element) and x.parent() is self._module: return self._from_dict(x.monomial_coefficients(copy=False), remove_zeros=False) return super(Representation, self)._element_constructor_(x) def product_by_coercion(self, left, right): """ Return the product of ``left`` and ``right`` by passing to ``self._module`` and then building a new element of ``self``. EXAMPLES:: sage: G = groups.permutation.KleinFour() sage: E = algebras.Exterior(QQ,'e',4) sage: on_basis = lambda g,m: E.monomial(m) # the trivial representation sage: from sage.modules.with_basis.representation import Representation sage: R = Representation(G, E, on_basis) sage: r = R.an_element(); r 1 + 2*e0 + 3*e1 + e1*e2 sage: g = G.an_element(); sage: g*r == r True sage: r*r Traceback (most recent call last): ... TypeError: unsupported operand parent(s) for *: 'Representation of The Klein 4 group of order 4, as a permutation group indexed by Subsets of {0, 1, 2, 3} over Rational Field' and 'Representation of The Klein 4 group of order 4, as a permutation group indexed by Subsets of {0, 1, 2, 3} over Rational Field' sage: from sage.categories.algebras import Algebras sage: category = Algebras(QQ).FiniteDimensional().WithBasis() sage: T = Representation(G, E, on_basis, category=category) sage: t = T.an_element(); t 1 + 2*e0 + 3*e1 + e1*e2 sage: g*t == t True sage: t*t 1 + 4*e0 + 4*e0*e1*e2 + 6*e1 + 2*e1*e2 """ M = self._module # Multiply in self._module p = M._from_dict(left._monomial_coefficients, False, False) * M._from_dict(right._monomial_coefficients, False, False) # Convert from a term in self._module to a term in self return self._from_dict(p.monomial_coefficients(copy=False), False, False) def side(self): """ Return whether ``self`` is a left or a right representation. OUTPUT: - the string ``"left"`` or ``"right"`` EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation() sage: R.side() 'left' sage: S = G.regular_representation(side="right") sage: S.side() 'right' """ return "left" if self._left_repr else "right" class Element(CombinatorialFreeModule.Element): def _acted_upon_(self, scalar, self_on_left=False): """ Return the action of ``scalar`` on ``self``. EXAMPLES:: sage: G = groups.misc.WeylGroup(['B',2], prefix='s') sage: R = G.regular_representation() sage: s1,s2 = G.gens() sage: x = R.an_element(); x 2*s2*s1*s2 + s1*s2 + 3*s2 + 1 sage: 2 * x 4*s2*s1*s2 + 2*s1*s2 + 6*s2 + 2 sage: s1 * x 2*s2*s1*s2*s1 + 3*s1*s2 + s1 + s2 sage: s2 * x s2*s1*s2 + 2*s1*s2 + s2 + 3 sage: G = groups.misc.WeylGroup(['B',2], prefix='s') sage: R = G.regular_representation(side="right") sage: s1,s2 = G.gens() sage: x = R.an_element(); x 2*s2*s1*s2 + s1*s2 + 3*s2 + 1 sage: x * s1 2*s2*s1*s2*s1 + s1*s2*s1 + 3*s2*s1 + s1 sage: x * s2 2*s2*s1 + s1 + s2 + 3 sage: G = groups.misc.WeylGroup(['B',2], prefix='s') sage: R = G.regular_representation() sage: R.base_ring() Integer Ring sage: A = G.algebra(ZZ) sage: s1,s2 = A.algebra_generators() sage: x = R.an_element(); x 2*s2*s1*s2 + s1*s2 + 3*s2 + 1 sage: s1 * x 2*s2*s1*s2*s1 + 3*s1*s2 + s1 + s2 sage: s2 * x s2*s1*s2 + 2*s1*s2 + s2 + 3 sage: (2*s1 - s2) * x 4*s2*s1*s2*s1 - s2*s1*s2 + 4*s1*s2 + 2*s1 + s2 - 3 sage: (3*s1 + s2) * R.zero() 0 sage: A = G.algebra(QQ) sage: s1,s2 = A.algebra_generators() sage: a = 1/2 * s1 sage: a * x Traceback (most recent call last): ... TypeError: unsupported operand parent(s) for *: 'Algebra of Weyl Group of type ['B', 2] ... over Rational Field' and 'Left Regular Representation of Weyl Group of type ['B', 2] ... over Integer Ring' Check that things that coerce into the group (algebra) also have an action:: sage: D4 = groups.permutation.Dihedral(4) sage: S4 = SymmetricGroup(4) sage: S4.has_coerce_map_from(D4) True sage: R = S4.regular_representation() sage: D4.an_element() * R.an_element() 2*(2,4) + 3*(1,2,3,4) + (1,3) + (1,4,2,3) """ if isinstance(scalar, Element): P = self.parent() sP = scalar.parent() if sP is P._semigroup: if not self: return self if self_on_left == P._left_repr: scalar = ~scalar return P.linear_combination(((P._on_basis(scalar, m), c) for m,c in self), not self_on_left) if sP is P._semigroup_algebra: if not self: return self ret = P.zero() for ms,cs in scalar: if self_on_left == P._left_repr: ms = ~ms ret += P.linear_combination(((P._on_basis(ms, m), cs*c) for m,c in self), not self_on_left) return ret if P._semigroup.has_coerce_map_from(sP): scalar = P._semigroup(scalar) return self._acted_upon_(scalar, self_on_left) # Check for scalars first before general coercion to the semigroup algebra. # This will result in a faster action for the scalars. ret = CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left) if ret is not None: return ret if P._semigroup_algebra.has_coerce_map_from(sP): scalar = P._semigroup_algebra(scalar) return self._acted_upon_(scalar, self_on_left) return None return CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left) class RegularRepresentation(Representation): r""" The regular representation of a semigroup. The left regular representation of a semigroup `S` over a commutative ring `R` is the semigroup ring `R[S]` equipped with the left `S`-action `x b_y = b_{xy}`, where `(b_z)_{z \in S}` is the natural basis of `R[S]` and `x,y \in S`. INPUT: - ``semigroup`` -- a semigroup - ``base_ring`` -- the base ring for the representation - ``side`` -- (default: ``"left"``) whether this is a ``"left"`` or ``"right"`` representation REFERENCES: - :wikipedia:`Regular_representation` """ def __init__(self, semigroup, base_ring, side="left"): """ Initialize ``self``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation() sage: TestSuite(R).run() """ if side == "left": on_basis = self._left_on_basis else: on_basis = self._right_on_basis module = semigroup.algebra(base_ring) Representation.__init__(self, semigroup, module, on_basis, side) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: G.regular_representation() Left Regular Representation of Dihedral group of order 8 as a permutation group over Integer Ring sage: G.regular_representation(side="right") Right Regular Representation of Dihedral group of order 8 as a permutation group over Integer Ring """ if self._left_repr: base = "Left Regular Representation" else: base = "Right Regular Representation" return base + " of {} over {}".format(self._semigroup, self.base_ring()) def _left_on_basis(self, g, m): """ Return the left action of ``g`` on ``m``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation() sage: R._test_representation() # indirect doctest """ return self.monomial(g*m) def _right_on_basis(self, g, m): """ Return the right action of ``g`` on ``m``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.regular_representation(side="right") sage: R._test_representation() # indirect doctest """ return self.monomial(m*g) class TrivialRepresentation(Representation_abstract): """ The trivial representation of a semigroup. The trivial representation of a semigroup `S` over a commutative ring `R` is the `1`-dimensional `R`-module on which every element of `S` acts by the identity. This is simultaneously a left and right representation. INPUT: - ``semigroup`` -- a semigroup - ``base_ring`` -- the base ring for the representation REFERENCES: - :wikipedia:`Trivial_representation` """ def __init__(self, semigroup, base_ring): """ Initialize ``self``. EXAMPLES:: sage: G = groups.permutation.PGL(2, 3) sage: V = G.trivial_representation() sage: TestSuite(V).run() """ cat = Modules(base_ring).WithBasis().FiniteDimensional() Representation_abstract.__init__(self, semigroup, base_ring, ['v'], category=cat) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: G.trivial_representation() Trivial representation of Dihedral group of order 8 as a permutation group over Integer Ring """ return "Trivial representation of {} over {}".format(self._semigroup, self.base_ring()) def side(self): """ Return that ``self`` is a two-sided representation. OUTPUT: - the string ``"twosided"`` EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.trivial_representation() sage: R.side() 'twosided' """ return "twosided" class Element(CombinatorialFreeModule.Element): def _acted_upon_(self, scalar, self_on_left=False): """ Return the action of ``scalar`` on ``self``. EXAMPLES:: sage: SGA = SymmetricGroupAlgebra(QQ, 3) sage: V = SGA.trivial_representation() sage: x = V.an_element() sage: 2 * x 4*B['v'] sage: all(x * b == x for b in SGA.basis()) True sage: all(b * x == x for b in SGA.basis()) True sage: z = V.zero() sage: all(b * z == z for b in SGA.basis()) True sage: H = groups.permutation.Dihedral(5) sage: G = SymmetricGroup(5) sage: G.has_coerce_map_from(H) True sage: R = G.trivial_representation(QQ) sage: H.an_element() * R.an_element() 2*B['v'] sage: AG = G.algebra(QQ) sage: AG.an_element() * R.an_element() 14*B['v'] sage: AH = H.algebra(ZZ) sage: AG.has_coerce_map_from(AH) True sage: AH.an_element() * R.an_element() 14*B['v'] """ if isinstance(scalar, Element): P = self.parent() if P._semigroup.has_coerce_map_from(scalar.parent()): return self if P._semigroup_algebra.has_coerce_map_from(scalar.parent()): if not self: return self scalar = P._semigroup_algebra(scalar) d = self.monomial_coefficients(copy=True) d['v'] *= sum(scalar.coefficients()) return P._from_dict(d) return CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left) class SignRepresentation_abstract(Representation_abstract): """ Generic implementation of a sign representation. The sign representation of a semigroup `S` over a commutative ring `R` is the `1`-dimensional `R`-module on which every element of `S` acts by 1 if order of element is even (including 0) or -1 if order of element if odd. This is simultaneously a left and right representation. INPUT: - ``permgroup`` -- a permgroup - ``base_ring`` -- the base ring for the representation - ``sign_function`` -- a function which returns 1 or -1 depending on the elements sign REFERENCES: - :wikipedia:`Representation_theory_of_the_symmetric_group` """ def __init__(self, group, base_ring, sign_function=None): """ Initialize ``self``. EXAMPLES:: sage: G = groups.permutation.PGL(2, 3) sage: V = G.sign_representation() sage: TestSuite(V).run() """ self.sign_function = sign_function if sign_function is None: try: self.sign_function = self._default_sign except AttributeError: raise TypeError("a sign function must be given") cat = Modules(base_ring).WithBasis().FiniteDimensional() Representation_abstract.__init__(self, group, base_ring, ["v"], category=cat) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: G.sign_representation() Sign representation of Dihedral group of order 8 as a permutation group over Integer Ring """ return "Sign representation of {} over {}".format( self._semigroup, self.base_ring() ) def side(self): """ Return that ``self`` is a two-sided representation. OUTPUT: - the string ``"twosided"`` EXAMPLES:: sage: G = groups.permutation.Dihedral(4) sage: R = G.sign_representation() sage: R.side() 'twosided' """ return "twosided" class Element(CombinatorialFreeModule.Element): def _acted_upon_(self, scalar, self_on_left=False): """ Return the action of ``scalar`` on ``self``. EXAMPLES:: sage: G = PermutationGroup(gens=[(1,2,3), (1,2)]) sage: S = G.sign_representation() sage: x = S.an_element(); x 2*B['v'] sage: s,c = G.gens(); c (1,2,3) sage: s*x -2*B['v'] sage: s*x*s 2*B['v'] sage: s*x*s*s*c -2*B['v'] sage: A = G.algebra(ZZ) sage: s,c = A.algebra_generators() sage: c (1,2,3) sage: s (1,2) sage: c*x 2*B['v'] sage: c*c*x 2*B['v'] sage: c*x*s -2*B['v'] sage: c*x*s*s 2*B['v'] sage: (c+s)*x 0 sage: (c-s)*x 4*B['v'] sage: H = groups.permutation.Dihedral(4) sage: G = SymmetricGroup(4) sage: G.has_coerce_map_from(H) True sage: R = G.sign_representation() sage: H.an_element() * R.an_element() -2*B['v'] sage: AG = G.algebra(ZZ) sage: AH = H.algebra(ZZ) sage: AG.has_coerce_map_from(AH) True sage: AH.an_element() * R.an_element() -2*B['v'] """ if isinstance(scalar, Element): P = self.parent() if P._semigroup.has_coerce_map_from(scalar.parent()): scalar = P._semigroup(scalar) return self if P.sign_function(scalar) > 0 else -self # We need to check for scalars first ret = CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left) if ret is not None: return ret if P._semigroup_algebra.has_coerce_map_from(scalar.parent()): if not self: return self sum_scalar_coeff = 0 scalar = P._semigroup_algebra(scalar) for ms, cs in scalar: sum_scalar_coeff += P.sign_function(ms) * cs return sum_scalar_coeff * self return None return CombinatorialFreeModule.Element._acted_upon_( self, scalar, self_on_left ) class SignRepresentationPermgroup(SignRepresentation_abstract): """ The sign representation for a permutation group. EXAMPLES:: sage: G = groups.permutation.PGL(2, 3) sage: V = G.sign_representation() sage: TestSuite(V).run() """ def _default_sign(self, elem): """ Return the sign of the element INPUT: - ``elem`` -- the element of the group EXAMPLES:: sage: G = groups.permutation.PGL(2, 3) sage: V = G.sign_representation() sage: elem = G.an_element() sage: elem (1,2,4,3) sage: V._default_sign(elem) -1 """ return elem.sign() class SignRepresentationMatrixGroup(SignRepresentation_abstract): """ The sign representation for a matrix group. EXAMPLES:: sage: G = groups.permutation.PGL(2, 3) sage: V = G.sign_representation() sage: TestSuite(V).run() """ def _default_sign(self, elem): """ Return the sign of the element INPUT: - ``elem`` -- the element of the group EXAMPLES:: sage: G = GL(2, QQ) sage: V = G.sign_representation() sage: m = G.an_element() sage: m [1 0] [0 1] sage: V._default_sign(m) 1 """ return 1 if elem.matrix().det() > 0 else -1 class SignRepresentationCoxeterGroup(SignRepresentation_abstract): """ The sign representation for a Coxeter group. EXAMPLES:: sage: G = WeylGroup(["A", 1, 1]) sage: V = G.sign_representation() sage: TestSuite(V).run() """ def _default_sign(self, elem): """ Return the sign of the element INPUT: - ``elem`` -- the element of the group EXAMPLES:: sage: G = WeylGroup(["A", 1, 1]) sage: elem = G.an_element() sage: V = G.sign_representation() sage: V._default_sign(elem) 1 """ return -1 if elem.length() % 2 else 1
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/modules/with_basis/representation.py
0.902609
0.437824
representation.py
pypi
from sage.misc.cachefunc import cached_method from sage.categories.category_singleton import Category_singleton from sage.categories.category_with_axiom import CategoryWithAxiom from sage.categories.sets_cat import Sets from sage.categories.homsets import HomsetsCategory from sage.rings.infinity import Infinity from sage.rings.integer import Integer class SimplicialSets(Category_singleton): r""" The category of simplicial sets. A simplicial set `X` is a collection of sets `X_i`, indexed by the non-negative integers, together with maps .. math:: d_i: X_n \to X_{n-1}, \quad 0 \leq i \leq n \quad \text{(face maps)} \\ s_j: X_n \to X_{n+1}, \quad 0 \leq j \leq n \quad \text{(degeneracy maps)} satisfying the *simplicial identities*: .. math:: d_i d_j &= d_{j-1} d_i \quad \text{if } i<j \\ d_i s_j &= s_{j-1} d_i \quad \text{if } i<j \\ d_j s_j &= 1 = d_{j+1} s_j \\ d_i s_j &= s_{j} d_{i-1} \quad \text{if } i>j+1 \\ s_i s_j &= s_{j+1} s_{i} \quad \text{if } i \leq j Morphisms are sequences of maps `f_i : X_i \to Y_i` which commute with the face and degeneracy maps. EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: C = SimplicialSets(); C Category of simplicial sets TESTS:: sage: TestSuite(C).run() """ @cached_method def super_categories(self): """ EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: SimplicialSets().super_categories() [Category of sets] """ return [Sets()] class ParentMethods: def is_finite(self): """ Return ``True`` if this simplicial set is finite, i.e., has a finite number of nondegenerate simplices. EXAMPLES:: sage: simplicial_sets.Torus().is_finite() True sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: simplicial_sets.ClassifyingSpace(C5).is_finite() False """ return SimplicialSets.Finite() in self.categories() def is_pointed(self): """ Return ``True`` if this simplicial set is pointed, i.e., has a base point. EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0) sage: w = AbstractSimplex(0) sage: e = AbstractSimplex(1) sage: X = SimplicialSet({e: (v, w)}) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: X.is_pointed() False sage: Y.is_pointed() True """ return SimplicialSets.Pointed() in self.categories() def set_base_point(self, point): """ Return a copy of this simplicial set in which the base point is set to ``point``. INPUT: - ``point`` -- a 0-simplex in this simplicial set EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='v_0') sage: w = AbstractSimplex(0, name='w_0') sage: e = AbstractSimplex(1) sage: X = SimplicialSet({e: (v, w)}) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: Y.base_point() w_0 sage: X_star = X.set_base_point(w) sage: X_star.base_point() w_0 sage: Y_star = Y.set_base_point(v) sage: Y_star.base_point() v_0 TESTS:: sage: X.set_base_point(e) Traceback (most recent call last): ... ValueError: the "point" is not a zero-simplex sage: pt = AbstractSimplex(0) sage: X.set_base_point(pt) Traceback (most recent call last): ... ValueError: the point is not a simplex in this simplicial set """ 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): r""" Return the identity morphism in `\operatorname{Hom}(S, S)`. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: Hom(T, T).identity() Simplicial set endomorphism of Torus Defn: Identity map """ from sage.topology.simplicial_set_morphism import SimplicialSetMorphism return SimplicialSetMorphism(domain=self.domain(), codomain=self.codomain(), identity=True) class Finite(CategoryWithAxiom): """ Category of finite simplicial sets. The objects are simplicial sets with finitely many non-degenerate simplices. """ pass class SubcategoryMethods: def Pointed(self): """ A simplicial set is *pointed* if it has a distinguished base point. EXAMPLES:: sage: from sage.categories.simplicial_sets import SimplicialSets sage: SimplicialSets().Pointed().Finite() Category of finite pointed simplicial sets sage: SimplicialSets().Finite().Pointed() Category of finite pointed simplicial sets """ return self._with_axiom("Pointed") class Pointed(CategoryWithAxiom): class ParentMethods: def base_point(self): """ Return this simplicial set's base point EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='*') sage: e = AbstractSimplex(1) sage: S1 = SimplicialSet({e: (v, v)}, base_point=v) sage: S1.is_pointed() True sage: S1.base_point() * """ return self._basepoint def base_point_map(self, domain=None): """ Return a map from a one-point space to this one, with image the base point. This raises an error if this simplicial set does not have a base point. INPUT: - ``domain`` -- optional, default ``None``. Use this to specify a particular one-point space as the domain. The default behavior is to use the :func:`sage.topology.simplicial_set.Point` function to use a standard one-point space. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: f = T.base_point_map(); f Simplicial set morphism: From: Point To: Torus Defn: Constant map at (v_0, v_0) sage: S3 = simplicial_sets.Sphere(3) sage: g = S3.base_point_map() sage: f.domain() == g.domain() True sage: RP3 = simplicial_sets.RealProjectiveSpace(3) sage: temp = simplicial_sets.Simplex(0) sage: pt = temp.set_base_point(temp.n_cells(0)[0]) sage: h = RP3.base_point_map(domain=pt) sage: f.domain() == h.domain() False sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: BC5 = simplicial_sets.ClassifyingSpace(C5) sage: BC5.base_point_map() Simplicial set morphism: From: Point To: Classifying space of Multiplicative Abelian group isomorphic to C5 Defn: Constant map at 1 """ from sage.topology.simplicial_set_examples import Point if domain is None: domain = Point() else: if 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): r""" Return the fundamental group of this pointed simplicial set. INPUT: - ``simplify`` (bool, optional ``True``) -- if ``False``, then return a presentation of the group in terms of generators and relations. If ``True``, the default, simplify as much as GAP is able to. Algorithm: we compute the edge-path group -- see Section 19 of [Kan1958]_ and :wikipedia:`Fundamental_group`. Choose a spanning tree for the connected component of the 1-skeleton containing the base point, and then the group's generators are given by the non-degenerate edges. There are two types of relations: `e=1` if `e` is in the spanning tree, and for every 2-simplex, if its faces are `e_0`, `e_1`, and `e_2`, then we impose the relation `e_0 e_1^{-1} e_2 = 1`, where we first set `e_i=1` if `e_i` is degenerate. EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: eight = S1.wedge(S1) sage: eight.fundamental_group() # free group on 2 generators Finitely presented group < e0, e1 | > The fundamental group of a disjoint union of course depends on the choice of base point:: sage: T = simplicial_sets.Torus() sage: K = simplicial_sets.KleinBottle() sage: X = T.disjoint_union(K) sage: X_0 = X.set_base_point(X.n_cells(0)[0]) sage: X_0.fundamental_group().is_abelian() True sage: X_1 = X.set_base_point(X.n_cells(0)[1]) sage: X_1.fundamental_group().is_abelian() False sage: RP3 = simplicial_sets.RealProjectiveSpace(3) sage: RP3.fundamental_group() Finitely presented group < e | e^2 > Compute the fundamental group of some classifying spaces:: sage: C5 = groups.misc.MultiplicativeAbelian([5]) sage: BC5 = C5.nerve() sage: BC5.fundamental_group() Finitely presented group < e0 | e0^5 > sage: Sigma3 = groups.permutation.Symmetric(3) sage: BSigma3 = Sigma3.nerve() sage: pi = BSigma3.fundamental_group(); pi Finitely presented group < e0, e1 | e0^2, e1^3, (e0*e1^-1)^2 > sage: pi.order() 6 sage: pi.is_abelian() False The sphere has a trivial fundamental group:: sage: S2 = simplicial_sets.Sphere(2) sage: S2.fundamental_group() Finitely presented group < | > """ # Import this here to prevent importing libgap upon startup. from sage.groups.free_group import FreeGroup skel = self.n_skeleton(2) graph = skel.graph() if not skel.is_connected(): graph = graph.subgraph(skel.base_point()) edges = [e[2] for e in graph.edges()] spanning_tree = [e[2] for e in graph.min_spanning_tree()] gens = [e for e in edges if e not in spanning_tree] if not gens: return FreeGroup([]).quotient([]) gens_dict = dict(zip(gens, range(len(gens)))) FG = FreeGroup(len(gens), 'e') rels = [] for f in skel.n_cells(2): z = dict() for i, sigma in enumerate(skel.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: # sigma is not in the correct connected component. z[i] = FG.one() rels.append(z[0]*z[1].inverse()*z[2]) if simplify: return FG.quotient(rels).simplified() else: return FG.quotient(rels) def is_simply_connected(self): """ Return ``True`` if this pointed simplicial set is simply connected. .. WARNING:: Determining simple connectivity is not always possible, because it requires determining when a group, as given by generators and relations, is trivial. So this conceivably may give a false negative in some cases. EXAMPLES:: sage: T = simplicial_sets.Torus() sage: T.is_simply_connected() False sage: T.suspension().is_simply_connected() True sage: simplicial_sets.KleinBottle().is_simply_connected() False sage: S2 = simplicial_sets.Sphere(2) sage: S3 = simplicial_sets.Sphere(3) sage: (S2.wedge(S3)).is_simply_connected() True sage: X = S2.disjoint_union(S3) sage: X = X.set_base_point(X.n_cells(0)[0]) sage: X.is_simply_connected() False sage: C3 = groups.misc.MultiplicativeAbelian([3]) sage: BC3 = simplicial_sets.ClassifyingSpace(C3) sage: BC3.is_simply_connected() False """ 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): # I don't know of any simplicial sets for which the # code reaches this point, but there are certainly # groups for which these errors are raised. 'IsTrivial' # works for all of the examples I've seen, though. raise ValueError('unable to determine if the fundamental ' 'group is trivial') def connectivity(self, max_dim=None): """ Return the connectivity of this pointed simplicial set. INPUT: - ``max_dim`` -- specify a maximum dimension through which to check. This is required if this simplicial set is simply connected and not finite. The dimension of the first nonzero homotopy group. If simply connected, this is the same as the dimension of the first nonzero homology group. .. WARNING:: See the warning for the :meth:`is_simply_connected` method. The connectivity of a contractible space is ``+Infinity``. EXAMPLES:: sage: simplicial_sets.Sphere(3).connectivity() 2 sage: simplicial_sets.Sphere(0).connectivity() -1 sage: K = simplicial_sets.Simplex(4) sage: K = K.set_base_point(K.n_cells(0)[0]) sage: K.connectivity() +Infinity sage: X = simplicial_sets.Torus().suspension(2) sage: X.connectivity() 2 sage: C2 = groups.misc.MultiplicativeAbelian([2]) sage: BC2 = simplicial_sets.ClassifyingSpace(C2) sage: BC2.connectivity() 0 """ 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: # Note: at the moment, this will never be reached, # because our only examples (so far) of infinite # simplicial sets are not simply connected. 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): """ Return a copy of this simplicial set in which the base point has been forgotten. EXAMPLES:: sage: from sage.topology.simplicial_set import AbstractSimplex, SimplicialSet sage: v = AbstractSimplex(0, name='v_0') sage: w = AbstractSimplex(0, name='w_0') sage: e = AbstractSimplex(1) sage: Y = SimplicialSet({e: (v, w)}, base_point=w) sage: Y.is_pointed() True sage: Y.base_point() w_0 sage: Z = Y.unset_base_point() sage: Z.is_pointed() False """ from sage.topology.simplicial_set import SimplicialSet return SimplicialSet(self.face_data()) def fat_wedge(self, n): """ Return the $n$-th fat wedge of this pointed simplicial set. This is the subcomplex of the $n$-fold product `X^n` consisting of those points in which at least one factor is the base point. Thus when $n=2$, this is the wedge of the simplicial set with itself, but when $n$ is larger, the fat wedge is larger than the $n$-fold wedge. EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: S1.fat_wedge(0) Point sage: S1.fat_wedge(1) S^1 sage: S1.fat_wedge(2).fundamental_group() Finitely presented group < e0, e1 | > sage: S1.fat_wedge(4).homology() {0: 0, 1: Z x Z x Z x Z, 2: Z^6, 3: Z x Z x Z x Z} """ 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): """ Return the smash product of this simplicial set with ``others``. INPUT: - ``others`` -- one or several simplicial sets EXAMPLES:: sage: S1 = simplicial_sets.Sphere(1) sage: RP2 = simplicial_sets.RealProjectiveSpace(2) sage: X = S1.smash_product(RP2) sage: X.homology(base_ring=GF(2)) {0: Vector space of dimension 0 over Finite Field of size 2, 1: Vector space of dimension 0 over Finite Field of size 2, 2: Vector space of dimension 1 over Finite Field of size 2, 3: Vector space of dimension 1 over Finite Field of size 2} sage: T = S1.product(S1) sage: X = T.smash_product(S1) sage: X.homology(reduced=False) {0: Z, 1: 0, 2: Z x Z, 3: Z} """ from sage.topology.simplicial_set_constructions import SmashProductOfSimplicialSets_finite return SmashProductOfSimplicialSets_finite((self,) + others)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/simplicial_sets.py
0.90287
0.627666
simplicial_sets.py
pypi
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring from sage.categories.graded_modules import GradedModulesCategory class LambdaBracketAlgebrasWithBasis(CategoryWithAxiom_over_base_ring): """ The category of Lambda bracket algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis() Category of Lie conformal algebras with basis over Algebraic Field """ class ElementMethods: def index(self): """ The index of this basis element. EXAMPLES:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: V.inject_variables() Defining L, G, C sage: G.T(3).index() ('G', 3) sage: v = V.an_element(); v L + G + C sage: v.index() Traceback (most recent call last): ... ValueError: index can only be computed for monomials, got L + G + C """ if self.is_zero(): return None if not self.is_monomial(): raise ValueError ("index can only be computed for " "monomials, got {}".format(self)) return next(iter(self.monomial_coefficients())) class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring): """ The category of finitely generated lambda bracket algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar) sage: C.WithBasis().FinitelyGenerated() Category of finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis() True """ class Graded(GradedModulesCategory): """ The category of H-graded finitely generated lambda bracket algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field """ class ParentMethods: def degree_on_basis(self, m): r""" Return the degree of the basis element indexed by ``m`` in ``self``. EXAMPLES:: sage: V = lie_conformal_algebras.Virasoro(QQ) sage: V.degree_on_basis(('L',2)) 4 """ if m[0] in self._central_elements: return 0 return self._weights[self._index_to_pos[m[0]]] + m[1]
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/lambda_bracket_algebras_with_basis.py
0.806167
0.406479
lambda_bracket_algebras_with_basis.py
pypi
r""" Sage categories quickref - ``sage.categories.primer?`` a primer on Elements, Parents, and Categories - ``sage.categories.tutorial?`` a tutorial on Elements, Parents, and Categories - ``Category?`` technical background on categories - ``Sets()``, ``Semigroups()``, ``Algebras(QQ)`` some categories - ``SemiGroups().example()??`` sample implementation of a semigroup - ``Hom(A, B)``, ``End(A, Algebras())`` homomorphisms sets - ``tensor``, ``cartesian_product`` functorial constructions Module layout: - :mod:`sage.categories.basic` the basic categories - :mod:`sage.categories.all` all categories - :mod:`sage.categories.semigroups` the ``Semigroups()`` category - :mod:`sage.categories.examples.semigroups` the example of ``Semigroups()`` - :mod:`sage.categories.homset` morphisms, ... - :mod:`sage.categories.map` - :mod:`sage.categories.morphism` - :mod:`sage.categories.functors` - :mod:`sage.categories.cartesian_product` functorial constructions - :mod:`sage.categories.tensor` - :mod:`sage.categories.dual` """ # install the docstring of this module to the containing package from sage.misc.namespace_package import install_doc install_doc(__package__, __doc__) from . import primer from sage.misc.lazy_import import lazy_import from .all__sagemath_objects import * from .basic import * from .chain_complexes import ChainComplexes, HomologyFunctor from .simplicial_complexes import SimplicialComplexes from .tensor import tensor from .signed_tensor import tensor_signed from .g_sets import GSets from .pointed_sets import PointedSets from .sets_with_grading import SetsWithGrading from .groupoid import Groupoid from .permutation_groups import PermutationGroups # enumerated sets from .finite_sets import FiniteSets from .enumerated_sets import EnumeratedSets from .finite_enumerated_sets import FiniteEnumeratedSets from .infinite_enumerated_sets import InfiniteEnumeratedSets # posets from .posets import Posets from .finite_posets import FinitePosets from .lattice_posets import LatticePosets from .finite_lattice_posets import FiniteLatticePosets # finite groups/... from .finite_semigroups import FiniteSemigroups from .finite_monoids import FiniteMonoids from .finite_groups import FiniteGroups from .finite_permutation_groups import FinitePermutationGroups # fields from .number_fields import NumberFields from .function_fields import FunctionFields # modules from .left_modules import LeftModules from .right_modules import RightModules from .bimodules import Bimodules from .modules import Modules RingModules = Modules from .vector_spaces import VectorSpaces # (hopf) algebra structures from .algebras import Algebras from .commutative_algebras import CommutativeAlgebras from .coalgebras import Coalgebras from .bialgebras import Bialgebras from .hopf_algebras import HopfAlgebras from .lie_algebras import LieAlgebras # specific algebras from .monoid_algebras import MonoidAlgebras from .group_algebras import GroupAlgebras from .matrix_algebras import MatrixAlgebras # ideals from .ring_ideals import RingIdeals Ideals = RingIdeals from .commutative_ring_ideals import CommutativeRingIdeals from .algebra_modules import AlgebraModules from .algebra_ideals import AlgebraIdeals from .commutative_algebra_ideals import CommutativeAlgebraIdeals # schemes and varieties from .modular_abelian_varieties import ModularAbelianVarieties from .schemes import Schemes # * with basis from .modules_with_basis import ModulesWithBasis FreeModules = ModulesWithBasis from .hecke_modules import HeckeModules from .algebras_with_basis import AlgebrasWithBasis from .coalgebras_with_basis import CoalgebrasWithBasis from .bialgebras_with_basis import BialgebrasWithBasis from .hopf_algebras_with_basis import HopfAlgebrasWithBasis # finite dimensional * with basis from .finite_dimensional_modules_with_basis import FiniteDimensionalModulesWithBasis from .finite_dimensional_algebras_with_basis import FiniteDimensionalAlgebrasWithBasis from .finite_dimensional_coalgebras_with_basis import FiniteDimensionalCoalgebrasWithBasis from .finite_dimensional_bialgebras_with_basis import FiniteDimensionalBialgebrasWithBasis from .finite_dimensional_hopf_algebras_with_basis import FiniteDimensionalHopfAlgebrasWithBasis # graded * from .graded_modules import GradedModules from .graded_algebras import GradedAlgebras from .graded_coalgebras import GradedCoalgebras from .graded_bialgebras import GradedBialgebras from .graded_hopf_algebras import GradedHopfAlgebras # graded * with basis from .graded_modules_with_basis import GradedModulesWithBasis from .graded_algebras_with_basis import GradedAlgebrasWithBasis from .graded_coalgebras_with_basis import GradedCoalgebrasWithBasis from .graded_bialgebras_with_basis import GradedBialgebrasWithBasis from .graded_hopf_algebras_with_basis import GradedHopfAlgebrasWithBasis # Coxeter groups from .coxeter_groups import CoxeterGroups lazy_import('sage.categories.finite_coxeter_groups', 'FiniteCoxeterGroups') from .weyl_groups import WeylGroups from .finite_weyl_groups import FiniteWeylGroups from .affine_weyl_groups import AffineWeylGroups # crystal bases from .crystals import Crystals from .highest_weight_crystals import HighestWeightCrystals from .regular_crystals import RegularCrystals from .finite_crystals import FiniteCrystals from .classical_crystals import ClassicalCrystals # polyhedra lazy_import('sage.categories.polyhedra', 'PolyhedralSets') # lie conformal algebras lazy_import('sage.categories.lie_conformal_algebras', 'LieConformalAlgebras')
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/all.py
0.839701
0.540318
all.py
pypi
from sage.categories.category_with_axiom import CategoryWithAxiom_over_base_ring from sage.categories.graded_lie_conformal_algebras import GradedLieConformalAlgebrasCategory from sage.categories.graded_modules import GradedModulesCategory from sage.categories.super_modules import SuperModulesCategory class LieConformalAlgebrasWithBasis(CategoryWithAxiom_over_base_ring): """ The category of Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis() Category of Lie conformal algebras with basis over Algebraic Field """ class Super(SuperModulesCategory): """ The category of super Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(AA).WithBasis().Super() Category of super Lie conformal algebras with basis over Algebraic Real Field """ class ParentMethods: def _even_odd_on_basis(self, m): """ Return the parity of the basis element indexed by ``m``. OUTPUT: ``0`` if ``m`` is for an even element or ``1`` if ``m`` is for an odd element. EXAMPLES:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: B = V._indices sage: V._even_odd_on_basis(B(('G',1))) 1 """ return self._parity[self.monomial((m[0],0))] class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded super Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().Super().Graded() Category of H-graded super Lie conformal algebras with basis over Algebraic Field """ class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().Graded() Category of H-graded Lie conformal algebras with basis over Algebraic Field """ class FinitelyGeneratedAsLambdaBracketAlgebra(CategoryWithAxiom_over_base_ring): """ The category of finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar) sage: C.WithBasis().FinitelyGenerated() Category of finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.WithBasis().FinitelyGenerated() is C.FinitelyGenerated().WithBasis() True """ class Super(SuperModulesCategory): """ The category of super finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(AA).WithBasis().FinitelyGenerated().Super() Category of super finitely generated Lie conformal algebras with basis over Algebraic Real Field """ class Graded(GradedModulesCategory): """ The category of H-graded super finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() sage: C.Graded().Super() Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field sage: C.Graded().Super() is C.Super().Graded() True """ def _repr_object_names(self): """ The names of the objects of ``self``. EXAMPLES:: sage: C = LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated() sage: C.Super().Graded() Category of H-graded super finitely generated Lie conformal algebras with basis over Algebraic Field """ return "H-graded {}".format(self.base_category()._repr_object_names()) class Graded(GradedLieConformalAlgebrasCategory): """ The category of H-graded finitely generated Lie conformal algebras with basis. EXAMPLES:: sage: LieConformalAlgebras(QQbar).WithBasis().FinitelyGenerated().Graded() Category of H-graded finitely generated Lie conformal algebras with basis over Algebraic Field """
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/lie_conformal_algebras_with_basis.py
0.845942
0.462594
lie_conformal_algebras_with_basis.py
pypi
from sage.misc.abstract_method import abstract_method from sage.misc.cachefunc import cached_method from sage.categories.category_singleton import Category_singleton from sage.categories.category_with_axiom import CategoryWithAxiom from sage.categories.simplicial_complexes import SimplicialComplexes from sage.categories.sets_cat import Sets class Graphs(Category_singleton): r""" The category of graphs. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs(); C Category of graphs TESTS:: sage: TestSuite(C).run() """ @cached_method def super_categories(self): """ EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: Graphs().super_categories() [Category of simplicial complexes] """ return [SimplicialComplexes()] class ParentMethods: @abstract_method def vertices(self): """ Return the vertices of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.vertices() [0, 1, 2, 3, 4] """ @abstract_method def edges(self): """ Return the edges of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.edges() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ def dimension(self): """ Return the dimension of ``self`` as a CW complex. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.dimension() 1 """ if self.edges(): return 1 return 0 def facets(self): """ Return the facets of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.facets() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return self.edges() def faces(self): """ Return the faces of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: sorted(C.faces(), key=lambda x: (x.dimension(), x.value)) [0, 1, 2, 3, 4, (0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return set(self.edges()).union(self.vertices()) class Connected(CategoryWithAxiom): """ The category of connected graphs. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().Connected() sage: TestSuite(C).run() """ def extra_super_categories(self): """ Return the extra super categories of ``self``. A connected graph is also a metric space. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: Graphs().Connected().super_categories() # indirect doctest [Category of connected topological spaces, Category of connected simplicial complexes, Category of graphs, Category of metric spaces] """ return [Sets().Metric()]
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/graphs.py
0.920683
0.562026
graphs.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class SubobjectsCategory(RegressiveCovariantConstructionCategory): _functor_category = "Subobjects" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.Subobjects()`` Mathematical meaning: if `A` is a subobject of `B` in the category `C`, then `A` is also a subquotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``SubobjectsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subquotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.Subobjects()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, a subgroup of a group `G` is simultaneously a subquotient of `G`, a group by itself, and a submonoid of `G`:: sage: Groups().Subobjects().super_categories() [Category of groups, Category of subquotients of monoids, Category of subobjects of sets] Mind the last item above: there is indeed currently nothing implemented about submonoids. This resulted from the following call:: sage: sage.categories.subobjects.SubobjectsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of subobjects of sets """ return Category.join([category.Subquotients(), super(SubobjectsCategory, cls).default_super_categories(category)])
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/subobjects.py
0.91195
0.472257
subobjects.py
pypi
from sage.misc.lazy_import import lazy_import from sage.categories.covariant_functorial_construction import CovariantFunctorialConstruction, CovariantConstructionCategory from sage.categories.pushout import MultivariateConstructionFunctor native_python_containers = set([tuple, list, set, frozenset, range]) class CartesianProductFunctor(CovariantFunctorialConstruction, MultivariateConstructionFunctor): """ The Cartesian product functor. EXAMPLES:: sage: cartesian_product The cartesian_product functorial construction ``cartesian_product`` takes a finite collection of sets, and constructs the Cartesian product of those sets:: sage: A = FiniteEnumeratedSet(['a','b','c']) sage: B = FiniteEnumeratedSet([1,2]) sage: C = cartesian_product([A, B]); C The Cartesian product of ({'a', 'b', 'c'}, {1, 2}) sage: C.an_element() ('a', 1) sage: C.list() # todo: not implemented [['a', 1], ['a', 2], ['b', 1], ['b', 2], ['c', 1], ['c', 2]] If those sets are endowed with more structure, say they are monoids (hence in the category ``Monoids()``), then the result is automatically endowed with its natural monoid structure:: sage: M = Monoids().example() sage: M An example of a monoid: the free monoid generated by ('a', 'b', 'c', 'd') sage: M.rename('M') sage: C = cartesian_product([M, ZZ, QQ]) sage: C The Cartesian product of (M, Integer Ring, Rational Field) sage: C.an_element() ('abcd', 1, 1/2) sage: C.an_element()^2 ('abcdabcd', 1, 1/4) sage: C.category() Category of Cartesian products of monoids sage: Monoids().CartesianProducts() Category of Cartesian products of monoids The Cartesian product functor is covariant: if ``A`` is a subcategory of ``B``, then ``A.CartesianProducts()`` is a subcategory of ``B.CartesianProducts()`` (see also :class:`~sage.categories.covariant_functorial_construction.CovariantFunctorialConstruction`):: sage: C.categories() [Category of Cartesian products of monoids, Category of monoids, Category of Cartesian products of semigroups, Category of semigroups, Category of Cartesian products of unital magmas, Category of Cartesian products of magmas, Category of unital magmas, Category of magmas, Category of Cartesian products of sets, Category of sets, ...] [Category of Cartesian products of monoids, Category of monoids, Category of Cartesian products of semigroups, Category of semigroups, Category of Cartesian products of magmas, Category of unital magmas, Category of magmas, Category of Cartesian products of sets, Category of sets, Category of sets with partial maps, Category of objects] Hence, the role of ``Monoids().CartesianProducts()`` is solely to provide mathematical information and algorithms which are relevant to Cartesian product of monoids. For example, it specifies that the result is again a monoid, and that its multiplicative unit is the Cartesian product of the units of the underlying sets:: sage: C.one() ('', 1, 1) Those are implemented in the nested class :class:`Monoids.CartesianProducts <sage.categories.monoids.Monoids.CartesianProducts>` of ``Monoids(QQ)``. This nested class is itself a subclass of :class:`CartesianProductsCategory`. """ _functor_name = "cartesian_product" _functor_category = "CartesianProducts" symbol = " (+) " def __init__(self, category=None): r""" Constructor. See :class:`CartesianProductFunctor` for details. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: CartesianProductFunctor() The cartesian_product functorial construction """ CovariantFunctorialConstruction.__init__(self) self._forced_category = category from sage.categories.sets_cat import Sets if self._forced_category is not None: codomain = self._forced_category else: codomain = Sets() MultivariateConstructionFunctor.__init__(self, Sets(), codomain) def __call__(self, args, **kwds): r""" Functorial construction application. This specializes the generic ``__call__`` from :class:`CovariantFunctorialConstruction` to: - handle the following plain Python containers as input: :class:`frozenset`, :class:`list`, :class:`set`, :class:`tuple`, and :class:`xrange` (Python3 ``range``). - handle the empty list of factors. See the examples below. EXAMPLES:: sage: cartesian_product([[0,1], ('a','b','c')]) The Cartesian product of ({0, 1}, {'a', 'b', 'c'}) sage: _.category() Category of Cartesian products of finite enumerated sets sage: cartesian_product([set([0,1,2]), [0,1]]) The Cartesian product of ({0, 1, 2}, {0, 1}) sage: _.category() Category of Cartesian products of sets Check that the empty product is handled correctly: sage: C = cartesian_product([]) sage: C The Cartesian product of () sage: C.cardinality() 1 sage: C.an_element() () sage: C.category() Category of Cartesian products of sets Check that Python3 ``range`` is handled correctly:: sage: C = cartesian_product([range(2), range(2)]) sage: list(C) [(0, 0), (0, 1), (1, 0), (1, 1)] sage: C.category() Category of Cartesian products of finite enumerated sets """ if any(type(arg) in native_python_containers for arg in args): from sage.categories.sets_cat import Sets S = Sets() args = [S(a, enumerated_set=True) for a in args] elif not args: if self._forced_category is None: from sage.categories.sets_cat import Sets cat = Sets().CartesianProducts() else: cat = self._forced_category from sage.sets.cartesian_product import CartesianProduct return CartesianProduct((), cat) elif self._forced_category is not None: return super(CartesianProductFunctor, self).__call__(args, category=self._forced_category, **kwds) return super(CartesianProductFunctor, self).__call__(args, **kwds) def __eq__(self, other): r""" Comparison ignores the ``category`` parameter. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: cartesian_product([ZZ, ZZ]).construction()[0] == CartesianProductFunctor() True """ return isinstance(other, CartesianProductFunctor) def __ne__(self, other): r""" Comparison ignores the ``category`` parameter. TESTS:: sage: from sage.categories.cartesian_product import CartesianProductFunctor sage: cartesian_product([ZZ, ZZ]).construction()[0] != CartesianProductFunctor() False """ return not (self == other) class CartesianProductsCategory(CovariantConstructionCategory): r""" An abstract base class for all ``CartesianProducts`` categories. TESTS:: sage: C = Sets().CartesianProducts() sage: C Category of Cartesian products of sets sage: C.base_category() Category of sets sage: latex(C) \mathbf{CartesianProducts}(\mathbf{Sets}) """ _functor_category = "CartesianProducts" def _repr_object_names(self): """ EXAMPLES:: sage: ModulesWithBasis(QQ).CartesianProducts() # indirect doctest Category of Cartesian products of vector spaces with basis over Rational Field """ # This method is only required for the capital `C` return "Cartesian products of %s"%(self.base_category()._repr_object_names()) def CartesianProducts(self): """ Return the category of (finite) Cartesian products of objects of ``self``. By associativity of Cartesian products, this is ``self`` (a Cartesian product of Cartesian products of `A`'s is a Cartesian product of `A`'s). EXAMPLES:: sage: ModulesWithBasis(QQ).CartesianProducts().CartesianProducts() Category of Cartesian products of vector spaces with basis over Rational Field """ return self def base_ring(self): """ The base ring of a Cartesian product is the base ring of the underlying category. EXAMPLES:: sage: Algebras(ZZ).CartesianProducts().base_ring() Integer Ring """ return self.base_category().base_ring() # Moved to avoid circular imports lazy_import('sage.categories.sets_cat', 'cartesian_product') """ The Cartesian product functorial construction See :class:`CartesianProductFunctor` for more information EXAMPLES:: sage: cartesian_product The cartesian_product functorial construction """
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/cartesian_product.py
0.719975
0.612252
cartesian_product.py
pypi
from sage.misc.bindable_class import BindableClass from sage.categories.category import Category from sage.categories.category_types import Category_over_base from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class RealizationsCategory(RegressiveCovariantConstructionCategory): """ An abstract base class for all categories of realizations category Relization are implemented as :class:`~sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory`. See there for the documentation of how the various bindings such as ``Sets().Realizations()`` and ``P.Realizations()``, where ``P`` is a parent, work. .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` TESTS:: sage: Sets().Realizations <bound method Sets_with_category.Realizations of Category of sets> sage: Sets().Realizations() Category of realizations of sets sage: Sets().Realizations().super_categories() [Category of sets] sage: Groups().Realizations().super_categories() [Category of groups, Category of realizations of unital magmas] """ _functor_category = "Realizations" def Realizations(self): """ Return the category of realizations of the parent ``self`` or of objects of the category ``self`` INPUT: - ``self`` -- a parent or a concrete category .. NOTE:: this *function* is actually inserted as a *method* in the class :class:`~sage.categories.category.Category` (see :meth:`~sage.categories.category.Category.Realizations`). It is defined here for code locality reasons. EXAMPLES: The category of realizations of some algebra:: sage: Algebras(QQ).Realizations() Join of Category of algebras over Rational Field and Category of realizations of unital magmas The category of realizations of a given algebra:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field sage: A.Realizations() Category of realizations of The subset algebra of {1, 2, 3} over Rational Field sage: C = GradedHopfAlgebrasWithBasis(QQ).Realizations(); C Join of Category of graded hopf algebras with basis over Rational Field and Category of realizations of hopf algebras over Rational Field sage: C.super_categories() [Category of graded hopf algebras with basis over Rational Field, Category of realizations of hopf algebras over Rational Field] sage: TestSuite(C).run() .. SEEALSO:: - :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` - :class:`ClasscallMetaclass` .. TODO:: Add an optional argument to allow for:: sage: Realizations(A, category = Blahs()) # todo: not implemented """ if isinstance(self, Category): return RealizationsCategory.category_of(self) else: return getattr(self.__class__, "Realizations")(self) Category.Realizations = Realizations class Category_realization_of_parent(Category_over_base, BindableClass): """ An abstract base class for categories of all realizations of a given parent INPUT: - ``parent_with_realization`` -- a parent .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` EXAMPLES:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field The role of this base class is to implement some technical goodies, like the binding ``A.Realizations()`` when a subclass ``Realizations`` is implemented as a nested class in ``A`` (see the :mod:`code of the example <sage.categories.examples.with_realizations.SubsetAlgebra>`):: sage: C = A.Realizations(); C Category of realizations of The subset algebra of {1, 2, 3} over Rational Field as well as the name for that category. """ def __init__(self, parent_with_realization): """ TESTS:: sage: from sage.categories.realizations import Category_realization_of_parent sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field sage: C = A.Realizations(); C Category of realizations of The subset algebra of {1, 2, 3} over Rational Field sage: isinstance(C, Category_realization_of_parent) True sage: C.parent_with_realization The subset algebra of {1, 2, 3} over Rational Field sage: TestSuite(C).run(skip=["_test_category_over_bases"]) .. TODO:: Fix the failing test by making ``C`` a singleton category. This will require some fiddling with the assertion in :meth:`Category_singleton.__classcall__` """ Category_over_base.__init__(self, parent_with_realization) self.parent_with_realization = parent_with_realization def _get_name(self): """ Return a human readable string specifying which kind of bases this category is for It is obtained by splitting and lower casing the last part of the class name. EXAMPLES:: sage: from sage.categories.realizations import Category_realization_of_parent sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent): ....: def super_categories(self): return [Objects()] sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") sage: MultiplicativeBasesOnPrimitiveElements(Sym)._get_name() 'multiplicative bases on primitive elements' """ import re return re.sub(".[A-Z]", lambda s: s.group()[0]+" "+s.group()[1], self.__class__.__base__.__name__.split(".")[-1]).lower() def _repr_object_names(self): """ Return the name of the objects of this category. .. SEEALSO:: :meth:`Category._repr_object_names` EXAMPLES:: sage: from sage.categories.realizations import Category_realization_of_parent sage: class MultiplicativeBasesOnPrimitiveElements(Category_realization_of_parent): ....: def super_categories(self): return [Objects()] sage: Sym = SymmetricFunctions(QQ); Sym.rename("Sym") sage: C = MultiplicativeBasesOnPrimitiveElements(Sym); C Category of multiplicative bases on primitive elements of Sym sage: C._repr_object_names() 'multiplicative bases on primitive elements of Sym' """ return "{} of {}".format(self._get_name(), self.base())
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/realizations.py
0.8398
0.600803
realizations.py
pypi
r""" Coxeter Group Algebras """ import functools from sage.misc.cachefunc import cached_method from sage.categories.algebra_functor import AlgebrasCategory class CoxeterGroupAlgebras(AlgebrasCategory): class ParentMethods: def demazure_lusztig_operator_on_basis(self, w, i, q1, q2, side="right"): r""" Return the result of applying the `i`-th Demazure Lusztig operator on ``w``. INPUT: - ``w`` -- an element of the Coxeter group - ``i`` -- an element of the index set - ``q1,q2`` -- two elements of the ground ring - ``bar`` -- a boolean (default ``False``) See :meth:`demazure_lusztig_operators` for details. EXAMPLES:: sage: W = WeylGroup(["B",3]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'] sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: w = W.an_element() sage: KW.demazure_lusztig_operator_on_basis(w, 0, q1, q2) (-q2)*323123 + (q1+q2)*123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, q1, q2) q1*1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, q1, q2) q1*1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, q1, q2) (q1+q2)*123 + (-q2)*12 At `q_1=1` and `q_2=0` we recover the action of the isobaric divided differences `\pi_i`:: sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, 0) 123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, 0) 1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, 0) 1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, 0) 123 At `q_1=1` and `q_2=-1` we recover the action of the simple reflection `s_i`:: sage: KW.demazure_lusztig_operator_on_basis(w, 0, 1, -1) 323123 sage: KW.demazure_lusztig_operator_on_basis(w, 1, 1, -1) 1231 sage: KW.demazure_lusztig_operator_on_basis(w, 2, 1, -1) 1232 sage: KW.demazure_lusztig_operator_on_basis(w, 3, 1, -1) 12 """ return (q1+q2) * self.monomial(w.apply_simple_projection(i,side=side)) - self.term(w.apply_simple_reflection(i, side=side), q2) def demazure_lusztig_operators(self, q1, q2, side="right", affine=True): r""" Return the Demazure Lusztig operators acting on ``self``. INPUT: - ``q1,q2`` -- two elements of the ground ring `K` - ``side`` -- ``"left"`` or ``"right"`` (default: ``"right"``); which side to act upon - ``affine`` -- a boolean (default: ``True``) The Demazure-Lusztig operator `T_i` is the linear map `R \to R` obtained by interpolating between the simple projection `\pi_i` (see :meth:`CoxeterGroups.ElementMethods.simple_projection`) and the simple reflection `s_i` so that `T_i` has eigenvalues `q_1` and `q_2`: .. MATH:: (q_1 + q_2) \pi_i - q_2 s_i. The Demazure-Lusztig operators give the usual representation of the operators `T_i` of the `q_1,q_2` Hecke algebra associated to the Coxeter group. For a finite Coxeter group, and if ``affine=True``, the Demazure-Lusztig operators `T_1,\dots,T_n` are completed by `T_0` to implement the level `0` action of the affine Hecke algebra. EXAMPLES:: sage: W = WeylGroup(["B",3]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'] sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: T = KW.demazure_lusztig_operators(q1, q2, affine=True) sage: x = KW.monomial(W.an_element()); x 123 sage: T[0](x) (-q2)*323123 + (q1+q2)*123 sage: T[1](x) q1*1231 sage: T[2](x) q1*1232 sage: T[3](x) (q1+q2)*123 + (-q2)*12 sage: T._test_relations() .. NOTE:: For a finite Weyl group `W`, the level 0 action of the affine Weyl group `\tilde W` only depends on the Coxeter diagram of the affinization, not its Dynkin diagram. Hence it is possible to explore all cases using only untwisted affinizations. """ from sage.combinat.root_system.hecke_algebra_representation import HeckeAlgebraRepresentation W = self.basis().keys() cartan_type = W.cartan_type() if affine and cartan_type.is_finite(): cartan_type = cartan_type.affine() T_on_basis = functools.partial(self.demazure_lusztig_operator_on_basis, q1=q1, q2=q2, side=side) return HeckeAlgebraRepresentation(self, T_on_basis, cartan_type, q1, q2) @cached_method def demazure_lusztig_eigenvectors(self, q1, q2): r""" Return the family of eigenvectors for the Cherednik operators. INPUT: - ``self`` -- a finite Coxeter group `W` - ``q1,q2`` -- two elements of the ground ring `K` The affine Hecke algebra `H_{q_1,q_2}(\tilde W)` acts on the group algebra of `W` through the Demazure-Lusztig operators `T_i`. Its Cherednik operators `Y^\lambda` can be simultaneously diagonalized as long as `q_1/q_2` is not a small root of unity [HST2008]_. This method returns the family of joint eigenvectors, indexed by `W`. .. SEEALSO:: - :meth:`demazure_lusztig_operators` - :class:`sage.combinat.root_system.hecke_algebra_representation.CherednikOperatorsEigenvectors` EXAMPLES:: sage: W = WeylGroup(["B",2]) sage: W.element_class._repr_=lambda x: "".join(str(i) for i in x.reduced_word()) sage: K = QQ['q1,q2'].fraction_field() sage: q1, q2 = K.gens() sage: KW = W.algebra(K) sage: E = KW.demazure_lusztig_eigenvectors(q1,q2) sage: E.keys() Weyl Group of type ['B', 2] (as a matrix group acting on the ambient space) sage: w = W.an_element() sage: E[w] (q2/(-q1+q2))*2121 + ((-q2)/(-q1+q2))*121 - 212 + 12 """ W = self.basis().keys() if not W.cartan_type().is_finite(): raise ValueError("the Demazure-Lusztig eigenvectors are only defined for finite Coxeter groups") result = self.demazure_lusztig_operators(q1, q2, affine=True).Y_eigenvectors() w0 = W.long_element() result.affine_lift = w0._mul_ result.affine_retract = w0._mul_ return result
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/coxeter_group_algebras.py
0.910212
0.508605
coxeter_group_algebras.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class QuotientsCategory(RegressiveCovariantConstructionCategory): _functor_category = "Quotients" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.Quotients()`` Mathematical meaning: if `A` is a quotient of `B` in the category `C`, then `A` is also a subquotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``QuotientsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subquotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.Quotients()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, a subgroup of a group `G` is simultaneously a subquotient of `G`, a group by itself, and a quotient monoid of ``G``:: sage: Groups().Quotients().super_categories() [Category of groups, Category of subquotients of monoids, Category of quotients of semigroups] Mind the last item above: there is indeed currently nothing implemented about quotient monoids. This resulted from the following call:: sage: sage.categories.quotients.QuotientsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups """ return Category.join([category.Subquotients(), super(QuotientsCategory, cls).default_super_categories(category)])
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/quotients.py
0.91259
0.566528
quotients.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory def WithRealizations(self): r""" Return the category of parents in ``self`` endowed with multiple realizations. INPUT: - ``self`` -- a category .. SEEALSO:: - The documentation and code (:mod:`sage.categories.examples.with_realizations`) of ``Sets().WithRealizations().example()`` for more on how to use and implement a parent with several realizations. - Various use cases: - :class:`SymmetricFunctions` - :class:`QuasiSymmetricFunctions` - :class:`NonCommutativeSymmetricFunctions` - :class:`SymmetricFunctionsNonCommutingVariables` - :class:`DescentAlgebra` - :class:`algebras.Moebius` - :class:`IwahoriHeckeAlgebra` - :class:`ExtendedAffineWeylGroup` - The `Implementing Algebraic Structures <../../../../../thematic_tutorials/tutorial-implementing-algebraic-structures>`_ thematic tutorial. - :mod:`sage.categories.realizations` .. NOTE:: this *function* is actually inserted as a *method* in the class :class:`~sage.categories.category.Category` (see :meth:`~sage.categories.category.Category.WithRealizations`). It is defined here for code locality reasons. EXAMPLES:: sage: Sets().WithRealizations() Category of sets with realizations .. RUBRIC:: Parent with realizations Let us now explain the concept of realizations. A *parent with realizations* is a facade parent (see :class:`Sets.Facade`) admitting multiple concrete realizations where its elements are represented. Consider for example an algebra `A` which admits several natural bases:: sage: A = Sets().WithRealizations().example(); A The subset algebra of {1, 2, 3} over Rational Field For each such basis `B` one implements a parent `P_B` which realizes `A` with its elements represented by expanding them on the basis `B`:: sage: A.F() The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis sage: A.Out() The subset algebra of {1, 2, 3} over Rational Field in the Out basis sage: A.In() The subset algebra of {1, 2, 3} over Rational Field in the In basis sage: A.an_element() F[{}] + 2*F[{1}] + 3*F[{2}] + F[{1, 2}] If `B` and `B'` are two bases, then the change of basis from `B` to `B'` is implemented by a canonical coercion between `P_B` and `P_{B'}`:: sage: F = A.F(); In = A.In(); Out = A.Out() sage: i = In.an_element(); i In[{}] + 2*In[{1}] + 3*In[{2}] + In[{1, 2}] sage: F(i) 7*F[{}] + 3*F[{1}] + 4*F[{2}] + F[{1, 2}] sage: F.coerce_map_from(Out) Generic morphism: From: The subset algebra of {1, 2, 3} over Rational Field in the Out basis To: The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis allowing for mixed arithmetic:: sage: (1 + Out.from_set(1)) * In.from_set(2,3) Out[{}] + 2*Out[{1}] + 2*Out[{2}] + 2*Out[{3}] + 2*Out[{1, 2}] + 2*Out[{1, 3}] + 4*Out[{2, 3}] + 4*Out[{1, 2, 3}] In our example, there are three realizations:: sage: A.realizations() [The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis, The subset algebra of {1, 2, 3} over Rational Field in the In basis, The subset algebra of {1, 2, 3} over Rational Field in the Out basis] Instead of manually defining the shorthands ``F``, ``In``, and ``Out``, as above one can just do:: sage: A.inject_shorthands() Defining F as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Fundamental basis Defining In as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the In basis Defining Out as shorthand for The subset algebra of {1, 2, 3} over Rational Field in the Out basis .. RUBRIC:: Rationale Besides some goodies described below, the role of `A` is threefold: - To provide, as illustrated above, a single entry point for the algebra as a whole: documentation, access to its properties and different realizations, etc. - To provide a natural location for the initialization of the bases and the coercions between, and other methods that are common to all bases. - To let other objects refer to `A` while allowing elements to be represented in any of the realizations. We now illustrate this second point by defining the polynomial ring with coefficients in `A`:: sage: P = A['x']; P Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field sage: x = P.gen() In the following examples, the coefficients turn out to be all represented in the `F` basis:: sage: P.one() F[{}] sage: (P.an_element() + 1)^2 F[{}]*x^2 + 2*F[{}]*x + F[{}] However we can create a polynomial with mixed coefficients, and compute with it:: sage: p = P([1, In[{1}], Out[{2}] ]); p Out[{2}]*x^2 + In[{1}]*x + F[{}] sage: p^2 Out[{2}]*x^4 + (-8*In[{}] + 4*In[{1}] + 8*In[{2}] + 4*In[{3}] - 4*In[{1, 2}] - 2*In[{1, 3}] - 4*In[{2, 3}] + 2*In[{1, 2, 3}])*x^3 + (F[{}] + 3*F[{1}] + 2*F[{2}] - 2*F[{1, 2}] - 2*F[{2, 3}] + 2*F[{1, 2, 3}])*x^2 + (2*F[{}] + 2*F[{1}])*x + F[{}] Note how each coefficient involves a single basis which need not be that of the other coefficients. Which basis is used depends on how coercion happened during mixed arithmetic and needs not be deterministic. One can easily coerce all coefficient to a given basis with:: sage: p.map_coefficients(In) (-4*In[{}] + 2*In[{1}] + 4*In[{2}] + 2*In[{3}] - 2*In[{1, 2}] - In[{1, 3}] - 2*In[{2, 3}] + In[{1, 2, 3}])*x^2 + In[{1}]*x + In[{}] Alas, the natural notation for constructing such polynomials does not yet work:: sage: In[{1}] * x Traceback (most recent call last): ... TypeError: unsupported operand parent(s) for *: 'The subset algebra of {1, 2, 3} over Rational Field in the In basis' and 'Univariate Polynomial Ring in x over The subset algebra of {1, 2, 3} over Rational Field' .. RUBRIC:: The category of realizations of `A` The set of all realizations of `A`, together with the coercion morphisms is a category (whose class inherits from :class:`~sage.categories.realizations.Category_realization_of_parent`):: sage: A.Realizations() Category of realizations of The subset algebra of {1, 2, 3} over Rational Field The various parent realizing `A` belong to this category:: sage: A.F() in A.Realizations() True `A` itself is in the category of algebras with realizations:: sage: A in Algebras(QQ).WithRealizations() True The (mostly technical) ``WithRealizations`` categories are the analogs of the ``*WithSeveralBases`` categories in MuPAD-Combinat. They provide support tools for handling the different realizations and the morphisms between them. Typically, ``VectorSpaces(QQ).FiniteDimensional().WithRealizations()`` will eventually be in charge, whenever a coercion `\phi: A\mapsto B` is registered, to register `\phi^{-1}` as coercion `B \mapsto A` if there is none defined yet. To achieve this, ``FiniteDimensionalVectorSpaces`` would provide a nested class ``WithRealizations`` implementing the appropriate logic. ``WithRealizations`` is a :mod:`regressive covariant functorial construction <sage.categories.covariant_functorial_construction>`. On our example, this simply means that `A` is automatically in the category of rings with realizations (covariance):: sage: A in Rings().WithRealizations() True and in the category of algebras (regressiveness):: sage: A in Algebras(QQ) True .. NOTE:: For ``C`` a category, ``C.WithRealizations()`` in fact calls ``sage.categories.with_realizations.WithRealizations(C)``. The later is responsible for building the hierarchy of the categories with realizations in parallel to that of their base categories, optimizing away those categories that do not provide a ``WithRealizations`` nested class. See :mod:`sage.categories.covariant_functorial_construction` for the technical details. .. NOTE:: Design question: currently ``WithRealizations`` is a regressive construction. That is ``self.WithRealizations()`` is a subcategory of ``self`` by default:: sage: Algebras(QQ).WithRealizations().super_categories() [Category of algebras over Rational Field, Category of monoids with realizations, Category of additive unital additive magmas with realizations] Is this always desirable? For example, ``AlgebrasWithBasis(QQ).WithRealizations()`` should certainly be a subcategory of ``Algebras(QQ)``, but not of ``AlgebrasWithBasis(QQ)``. This is because ``AlgebrasWithBasis(QQ)`` is specifying something about the concrete realization. TESTS:: sage: Semigroups().WithRealizations() Join of Category of semigroups and Category of sets with realizations sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C Category of graded hopf algebras with basis over Rational Field with realizations sage: C.super_categories() [Join of Category of hopf algebras over Rational Field and Category of graded algebras over Rational Field and Category of graded coalgebras over Rational Field] sage: TestSuite(Semigroups().WithRealizations()).run() """ return WithRealizationsCategory.category_of(self) Category.WithRealizations = WithRealizations class WithRealizationsCategory(RegressiveCovariantConstructionCategory): """ An abstract base class for all categories of parents with multiple realizations. .. SEEALSO:: :func:`Sets().WithRealizations <sage.categories.with_realizations.WithRealizations>` The role of this base class is to implement some technical goodies, such as the name for that category. """ _functor_category = "WithRealizations" def _repr_(self): """ String representation. EXAMPLES:: sage: C = GradedHopfAlgebrasWithBasis(QQ).WithRealizations(); C #indirect doctest Category of graded hopf algebras with basis over Rational Field with realizations """ s = repr(self.base_category()) return s+" with realizations"
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/with_realizations.py
0.946621
0.796372
with_realizations.py
pypi
from sage.categories.graded_modules import GradedModulesCategory from sage.categories.super_modules import SuperModulesCategory from sage.misc.abstract_method import abstract_method from sage.categories.lambda_bracket_algebras import LambdaBracketAlgebras class SuperLieConformalAlgebras(SuperModulesCategory): r""" The category of super Lie conformal algebras. EXAMPLES:: sage: LieConformalAlgebras(AA).Super() Category of super Lie conformal algebras over Algebraic Real Field Notice that we can force to have a *purely even* super Lie conformal algebra:: sage: bosondict = {('a','a'):{1:{('K',0):1}}} sage: R = LieConformalAlgebra(QQ,bosondict,names=('a',), ....: central_elements=('K',), super=True) sage: [g.is_even_odd() for g in R.gens()] [0, 0] """ def extra_super_categories(self): """ The extra super categories of ``self``. EXAMPLES:: sage: LieConformalAlgebras(QQ).Super().super_categories() [Category of super modules over Rational Field, Category of Lambda bracket algebras over Rational Field] """ return [LambdaBracketAlgebras(self.base_ring())] def example(self): """ An example parent in this category. EXAMPLES:: sage: LieConformalAlgebras(QQ).Super().example() The Neveu-Schwarz super Lie conformal algebra over Rational Field """ 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): """ Test the Jacobi axiom of this super Lie conformal algebra. INPUT: - ``options`` -- any keyword arguments acceptde by :meth:`_tester` EXAMPLES: By default, this method tests only the elements returned by ``self.some_elements()``:: sage: V = lie_conformal_algebras.Affine(QQ, 'B2') sage: V._test_jacobi() # long time (6 seconds) It works for super Lie conformal algebras too:: sage: V = lie_conformal_algebras.NeveuSchwarz(QQ) sage: V._test_jacobi() We can use specific elements by passing the ``elements`` keyword argument:: sage: V = lie_conformal_algebras.Affine(QQ, 'A1', names=('e', 'h', 'f')) sage: V.inject_variables() Defining e, h, f, K sage: V._test_jacobi(elements=(e, 2*f+h, 3*h)) TESTS:: sage: wrongdict = {('a', 'a'): {0: {('b', 0): 1}}, ('b', 'a'): {0: {('a', 0): 1}}} sage: V = LieConformalAlgebra(QQ, wrongdict, names=('a', 'b'), parity=(1, 0)) sage: V._test_jacobi() Traceback (most recent call last): ... AssertionError: {(0, 0): -3*a} != {} - {(0, 0): -3*a} + {} """ tester = self._tester(**options) S = tester.some_elements() # Try our best to avoid non-homogeneous 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): """ Return ``0`` if this element is *even* and ``1`` if it is *odd*. EXAMPLES:: sage: R = lie_conformal_algebras.NeveuSchwarz(QQ); sage: R.inject_variables() Defining L, G, C sage: G.is_even_odd() 1 """ class Graded(GradedModulesCategory): """ The category of H-graded super Lie conformal algebras. EXAMPLES:: sage: LieConformalAlgebras(AA).Super().Graded() Category of H-graded super Lie conformal algebras over Algebraic Real Field """ def _repr_object_names(self): """ The names of the objects of this category. EXAMPLES:: sage: LieConformalAlgebras(QQbar).Graded() Category of H-graded Lie conformal algebras over Algebraic Field """ return "H-graded {}".format(self.base_category()._repr_object_names())
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/super_lie_conformal_algebras.py
0.777215
0.364891
super_lie_conformal_algebras.py
pypi
from sage.categories.category import Category from sage.categories.covariant_functorial_construction import RegressiveCovariantConstructionCategory class IsomorphicObjectsCategory(RegressiveCovariantConstructionCategory): _functor_category = "IsomorphicObjects" @classmethod def default_super_categories(cls, category): """ Returns the default super categories of ``category.IsomorphicObjects()`` Mathematical meaning: if `A` is the image of `B` by an isomorphism in the category `C`, then `A` is both a subobject of `B` and a quotient of `B` in the category `C`. INPUT: - ``cls`` -- the class ``IsomorphicObjectsCategory`` - ``category`` -- a category `Cat` OUTPUT: a (join) category In practice, this returns ``category.Subobjects()`` and ``category.Quotients()``, joined together with the result of the method :meth:`RegressiveCovariantConstructionCategory.default_super_categories() <sage.categories.covariant_functorial_construction.RegressiveCovariantConstructionCategory.default_super_categories>` (that is the join of ``category`` and ``cat.IsomorphicObjects()`` for each ``cat`` in the super categories of ``category``). EXAMPLES: Consider ``category=Groups()``, which has ``cat=Monoids()`` as super category. Then, the image of a group `G'` by a group isomorphism is simultaneously a subgroup of `G`, a subquotient of `G`, a group by itself, and the image of `G` by a monoid isomorphism:: sage: Groups().IsomorphicObjects().super_categories() [Category of groups, Category of subquotients of monoids, Category of quotients of semigroups, Category of isomorphic objects of sets] Mind the last item above: there is indeed currently nothing implemented about isomorphic objects of monoids. This resulted from the following call:: sage: sage.categories.isomorphic_objects.IsomorphicObjectsCategory.default_super_categories(Groups()) Join of Category of groups and Category of subquotients of monoids and Category of quotients of semigroups and Category of isomorphic objects of sets """ return Category.join([category.Subobjects(), category.Quotients(), super(IsomorphicObjectsCategory, cls).default_super_categories(category)])
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/isomorphic_objects.py
0.910244
0.616835
isomorphic_objects.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.graphs import Graphs class Cycle(UniqueRepresentation, Parent): r""" An example of a graph: the cycle of length `n`. This class illustrates a minimal implementation of a graph. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example(); C An example of a graph: the 5-cycle sage: C.category() Category of graphs We conclude by running systematic tests on this graph:: sage: TestSuite(C).run() """ def __init__(self, n=5): r""" EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example(6); C An example of a graph: the 6-cycle TESTS:: sage: TestSuite(C).run() """ self._n = n Parent.__init__(self, category=Graphs()) def _repr_(self): r""" TESTS:: sage: from sage.categories.graphs import Graphs sage: Graphs().example() An example of a graph: the 5-cycle """ return "An example of a graph: the {}-cycle".format(self._n) def an_element(self): r""" Return an element of the graph, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.an_element() 0 """ return self(0) def vertices(self): """ Return the vertices of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.vertices() [0, 1, 2, 3, 4] """ return [self(i) for i in range(self._n)] def edges(self): """ Return the edges of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: C.edges() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] """ return [self( (i, (i+1) % self._n) ) for i in range(self._n)] class Element(ElementWrapper): def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.graphs import Graphs sage: C = Graphs().example() sage: e = C.edges()[0] sage: e.dimension() 2 sage: v = C.vertices()[0] sage: v.dimension() 1 """ if isinstance(self.value, tuple): return 2 return 1 Example = Cycle
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/graphs.py
0.935328
0.674771
graphs.py
pypi
r""" Example of a set with grading """ from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.sets_with_grading import SetsWithGrading from sage.rings.integer_ring import IntegerRing from sage.sets.finite_enumerated_set import FiniteEnumeratedSet class NonNegativeIntegers(UniqueRepresentation, Parent): r""" Non negative integers graded by themselves. EXAMPLES:: sage: E = SetsWithGrading().example(); E Non negative integers sage: E in Sets().Infinite() True sage: E.graded_component(0) {0} sage: E.graded_component(100) {100} """ def __init__(self): r""" TESTS:: sage: TestSuite(SetsWithGrading().example()).run() """ Parent.__init__(self, category=SetsWithGrading().Infinite(), facade=IntegerRing()) def an_element(self): r""" Return 0. EXAMPLES:: sage: SetsWithGrading().example().an_element() 0 """ return 0 def _repr_(self): r""" TESTS:: sage: SetsWithGrading().example() # indirect example Non negative integers """ return "Non negative integers" def graded_component(self, grade): r""" Return the component with grade ``grade``. EXAMPLES:: sage: N = SetsWithGrading().example() sage: N.graded_component(65) {65} """ return FiniteEnumeratedSet([grade]) def grading(self, elt): r""" Return the grade of ``elt``. EXAMPLES:: sage: N = SetsWithGrading().example() sage: N.grading(10) 10 """ return elt def generating_series(self, var='z'): r""" Return `1 / (1-z)`. EXAMPLES:: sage: N = SetsWithGrading().example(); N Non negative integers sage: f = N.generating_series(); f 1/(-z + 1) sage: LaurentSeriesRing(ZZ,'z')(f) 1 + z + z^2 + z^3 + z^4 + z^5 + z^6 + z^7 + z^8 + z^9 + z^10 + z^11 + z^12 + z^13 + z^14 + z^15 + z^16 + z^17 + z^18 + z^19 + O(z^20) """ from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.integer import Integer R = PolynomialRing(IntegerRing(), var) z = R.gen() return Integer(1) / (Integer(1) - z) Example = NonNegativeIntegers
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/sets_with_grading.py
0.938131
0.656383
sets_with_grading.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.categories.all import Posets from sage.structure.element_wrapper import ElementWrapper from sage.sets.set import Set, Set_object_enumerated from sage.sets.positive_integers import PositiveIntegers class FiniteSetsOrderedByInclusion(UniqueRepresentation, Parent): r""" An example of a poset: finite sets ordered by inclusion This class provides a minimal implementation of a poset EXAMPLES:: sage: P = Posets().example(); P An example of a poset: sets ordered by inclusion We conclude by running systematic tests on this poset:: sage: TestSuite(P).run(verbose = True) running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self): r""" EXAMPLES:: sage: P = Posets().example(); P An example of a poset: sets ordered by inclusion sage: P.category() Category of posets sage: type(P) <class 'sage.categories.examples.posets.FiniteSetsOrderedByInclusion_with_category'> sage: TestSuite(P).run() """ Parent.__init__(self, category = Posets()) def _repr_(self): r""" TESTS:: sage: S = Posets().example() sage: S._repr_() 'An example of a poset: sets ordered by inclusion' """ return "An example of a poset: sets ordered by inclusion" def le(self, x, y): r""" Returns whether `x` is a subset of `y` EXAMPLES:: sage: P = Posets().example() sage: P.le( P(Set([1,3])), P(Set([1,2,3])) ) True sage: P.le( P(Set([1,3])), P(Set([1,3])) ) True sage: P.le( P(Set([1,2])), P(Set([1,3])) ) False """ return x.value.issubset(y.value) def an_element(self): r""" Returns an element of this poset EXAMPLES:: sage: B = Posets().example() sage: B.an_element() {1, 4, 6} """ return self(Set([1,4,6])) class Element(ElementWrapper): wrapped_class = Set_object_enumerated class PositiveIntegersOrderedByDivisibilityFacade(UniqueRepresentation, Parent): r""" An example of a facade poset: the positive integers ordered by divisibility This class provides a minimal implementation of a facade poset EXAMPLES:: sage: P = Posets().example("facade"); P An example of a facade poset: the positive integers ordered by divisibility sage: P(5) 5 sage: P(0) Traceback (most recent call last): ... ValueError: Can't coerce `0` in any parent `An example of a facade poset: the positive integers ordered by divisibility` is a facade for sage: 3 in P True sage: 0 in P False """ element_class = type(Set([])) def __init__(self): r""" EXAMPLES:: sage: P = Posets().example("facade"); P An example of a facade poset: the positive integers ordered by divisibility sage: P.category() Category of facade posets sage: type(P) <class 'sage.categories.examples.posets.PositiveIntegersOrderedByDivisibilityFacade_with_category'> sage: TestSuite(P).run() """ Parent.__init__(self, facade = (PositiveIntegers(),), category = Posets()) def _repr_(self): r""" TESTS:: sage: S = Posets().example("facade") sage: S._repr_() 'An example of a facade poset: the positive integers ordered by divisibility' """ return "An example of a facade poset: the positive integers ordered by divisibility" def le(self, x, y): r""" Returns whether `x` is divisible by `y` EXAMPLES:: sage: P = Posets().example("facade") sage: P.le(3, 6) True sage: P.le(3, 3) True sage: P.le(3, 7) False """ return x.divides(y)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/posets.py
0.934582
0.479626
posets.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.manifolds import Manifolds class Plane(UniqueRepresentation, Parent): r""" An example of a manifold: the `n`-dimensional plane. This class illustrates a minimal implementation of a manifold. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example(); M An example of a Rational Field manifold: the 3-dimensional plane sage: M.category() Category of manifolds over Rational Field We conclude by running systematic tests on this manifold:: sage: TestSuite(M).run() """ def __init__(self, n=3, base_ring=None): r""" EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example(6); M An example of a Rational Field manifold: the 6-dimensional plane TESTS:: sage: TestSuite(M).run() """ self._n = n Parent.__init__(self, base=base_ring, category=Manifolds(base_ring)) def _repr_(self): r""" TESTS:: sage: from sage.categories.manifolds import Manifolds sage: Manifolds(QQ).example() An example of a Rational Field manifold: the 3-dimensional plane """ return "An example of a {} manifold: the {}-dimensional plane".format( self.base_ring(), self._n) def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example() sage: M.dimension() 3 """ return self._n def an_element(self): r""" Return an element of the manifold, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.manifolds import Manifolds sage: M = Manifolds(QQ).example() sage: M.an_element() (0, 0, 0) """ zero = self.base_ring().zero() return self(tuple([zero]*self._n)) Element = ElementWrapper Example = Plane
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/manifolds.py
0.926748
0.512937
manifolds.py
pypi
from sage.misc.cachefunc import cached_method from sage.structure.parent import Parent from sage.categories.all import CommutativeAdditiveMonoids from .commutative_additive_semigroups import FreeCommutativeAdditiveSemigroup class FreeCommutativeAdditiveMonoid(FreeCommutativeAdditiveSemigroup): r""" An example of a commutative additive monoid: the free commutative monoid This class illustrates a minimal implementation of a commutative monoid. EXAMPLES:: sage: S = CommutativeAdditiveMonoids().example(); S An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd') sage: S.category() Category of commutative additive monoids This is the free semigroup generated by:: sage: S.additive_semigroup_generators() Family (a, b, c, d) with product rule given by $a \times b = a$ for all $a, b$:: sage: (a,b,c,d) = S.additive_semigroup_generators() We conclude by running systematic tests on this commutative monoid:: sage: TestSuite(S).run(verbose = True) running ._test_additive_associativity() . . . pass running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_nonzero_equal() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass running ._test_zero() . . . pass """ def __init__(self, alphabet=('a','b','c','d')): r""" The free commutative monoid INPUT: - ``alphabet`` -- a tuple of strings: the generators of the monoid EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')); M An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c') TESTS:: sage: TestSuite(M).run() """ self.alphabet = alphabet Parent.__init__(self, category = CommutativeAdditiveMonoids()) def _repr_(self): r""" TESTS:: sage: M = CommutativeAdditiveMonoids().example(alphabet=('a','b','c')) sage: M._repr_() "An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c')" """ return "An example of a commutative monoid: the free commutative monoid generated by %s"%(self.alphabet,) @cached_method def zero(self): r""" Returns the zero of this additive monoid, as per :meth:`CommutativeAdditiveMonoids.ParentMethods.zero`. EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example(); M An example of a commutative monoid: the free commutative monoid generated by ('a', 'b', 'c', 'd') sage: M.zero() 0 """ return self(()) class Element(FreeCommutativeAdditiveSemigroup.Element): def __bool__(self): """ Check if ``self`` is not the zero of the monoid EXAMPLES:: sage: M = CommutativeAdditiveMonoids().example() sage: bool(M.zero()) False sage: [bool(m) for m in M.additive_semigroup_generators()] [True, True, True, True] """ return any(x for x in self.value.values()) __nonzero__ = __bool__ Example = FreeCommutativeAdditiveMonoid
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/commutative_additive_monoids.py
0.91695
0.423995
commutative_additive_monoids.py
pypi
from sage.misc.cachefunc import cached_method from sage.sets.family import Family from sage.categories.semigroups import Semigroups from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper class LeftRegularBand(UniqueRepresentation, Parent): r""" An example of a finite semigroup This class provides a minimal implementation of a finite semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example(); S An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd') This is the semigroup generated by:: sage: S.semigroup_generators() Family ('a', 'b', 'c', 'd') such that `x^2 = x` and `x y x = xy` for any `x` and `y` in `S`:: sage: S('dab') 'dab' sage: S('dab') * S('acb') 'dabc' It follows that the elements of `S` are strings without repetitions over the alphabet `a`, `b`, `c`, `d`:: sage: sorted(S.list()) ['a', 'ab', 'abc', 'abcd', 'abd', 'abdc', 'ac', 'acb', 'acbd', 'acd', 'acdb', 'ad', 'adb', 'adbc', 'adc', 'adcb', 'b', 'ba', 'bac', 'bacd', 'bad', 'badc', 'bc', 'bca', 'bcad', 'bcd', 'bcda', 'bd', 'bda', 'bdac', 'bdc', 'bdca', 'c', 'ca', 'cab', 'cabd', 'cad', 'cadb', 'cb', 'cba', 'cbad', 'cbd', 'cbda', 'cd', 'cda', 'cdab', 'cdb', 'cdba', 'd', 'da', 'dab', 'dabc', 'dac', 'dacb', 'db', 'dba', 'dbac', 'dbc', 'dbca', 'dc', 'dca', 'dcab', 'dcb', 'dcba'] It also follows that there are finitely many of them:: sage: S.cardinality() 64 Indeed:: sage: 4 * ( 1 + 3 * (1 + 2 * (1 + 1))) 64 As expected, all the elements of `S` are idempotents:: sage: all( x.is_idempotent() for x in S ) True Now, let us look at the structure of the semigroup:: sage: S = FiniteSemigroups().example(alphabet = ('a','b','c')) sage: S.cayley_graph(side="left", simple=True).plot() Graphics object consisting of 60 graphics primitives sage: S.j_transversal_of_idempotents() # random (arbitrary choice) ['acb', 'ac', 'ab', 'bc', 'a', 'c', 'b'] We conclude by running systematic tests on this semigroup:: sage: TestSuite(S).run(verbose = True) running ._test_an_element() . . . pass running ._test_associativity() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self, alphabet=('a','b','c','d')): r""" A left regular band. EXAMPLES:: sage: S = FiniteSemigroups().example(); S An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd') sage: S = FiniteSemigroups().example(alphabet=('x','y')); S An example of a finite semigroup: the left regular band generated by ('x', 'y') sage: TestSuite(S).run() """ self.alphabet = alphabet Parent.__init__(self, category = Semigroups().Finite().FinitelyGenerated()) def _repr_(self): r""" TESTS:: sage: S = FiniteSemigroups().example() sage: S._repr_() "An example of a finite semigroup: the left regular band generated by ('a', 'b', 'c', 'd')" """ return "An example of a finite semigroup: the left regular band generated by %s"%(self.alphabet,) def product(self, x, y): r""" Returns the product of two elements of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example() sage: S('a') * S('b') 'ab' sage: S('a') * S('b') * S('a') 'ab' sage: S('a') * S('a') 'a' """ assert x in self assert y in self x = x.value y = y.value return self(x + ''.join(c for c in y if c not in x)) @cached_method def semigroup_generators(self): r""" Returns the generators of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example(alphabet=('x','y')) sage: S.semigroup_generators() Family ('x', 'y') """ return Family([self(i) for i in self.alphabet]) def an_element(self): r""" Returns an element of the semigroup. EXAMPLES:: sage: S = FiniteSemigroups().example() sage: S.an_element() 'cdab' sage: S = FiniteSemigroups().example(("b")) sage: S.an_element() 'b' """ return self(''.join(self.alphabet[2:]+self.alphabet[0:2])) class Element (ElementWrapper): wrapped_class = str __lt__ = ElementWrapper._lt_by_value Example = LeftRegularBand
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/finite_semigroups.py
0.895614
0.497803
finite_semigroups.py
pypi
from sage.misc.cachefunc import cached_method from sage.sets.family import Family from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element_wrapper import ElementWrapper from sage.categories.all import Monoids from sage.rings.integer import Integer from sage.rings.integer_ring import ZZ class IntegerModMonoid(UniqueRepresentation, Parent): r""" An example of a finite monoid: the integers mod `n` This class illustrates a minimal implementation of a finite monoid. EXAMPLES:: sage: S = FiniteMonoids().example(); S An example of a finite multiplicative monoid: the integers modulo 12 sage: S.category() Category of finitely generated finite enumerated monoids We conclude by running systematic tests on this monoid:: sage: TestSuite(S).run(verbose = True) running ._test_an_element() . . . pass running ._test_associativity() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_one() . . . pass running ._test_pickling() . . . pass running ._test_prod() . . . pass running ._test_some_elements() . . . pass """ def __init__(self, n = 12): r""" EXAMPLES:: sage: M = FiniteMonoids().example(6); M An example of a finite multiplicative monoid: the integers modulo 6 TESTS:: sage: TestSuite(M).run() """ self.n = n Parent.__init__(self, category=Monoids().Finite().FinitelyGenerated()) def _repr_(self): r""" TESTS:: sage: M = FiniteMonoids().example() sage: M._repr_() 'An example of a finite multiplicative monoid: the integers modulo 12' """ return "An example of a finite multiplicative monoid: the integers modulo %s"%self.n def semigroup_generators(self): r""" Returns a set of generators for ``self``, as per :meth:`Semigroups.ParentMethods.semigroup_generators`. Currently this returns all integers mod `n`, which is of course far from optimal! EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.semigroup_generators() Family (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) """ return Family(tuple(self(ZZ(i)) for i in range(self.n))) @cached_method def one(self): r""" Return the one of the monoid, as per :meth:`Monoids.ParentMethods.one`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.one() 1 """ return self(ZZ.one()) def product(self, x, y): r""" Return the product of two elements `x` and `y` of the monoid, as per :meth:`Semigroups.ParentMethods.product`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.product(M(3), M(5)) 3 """ return self((x.value * y.value) % self.n) def an_element(self): r""" Returns an element of the monoid, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: M = FiniteMonoids().example() sage: M.an_element() 6 """ return self(ZZ(42) % self.n) class Element (ElementWrapper): wrapped_class = Integer Example = IntegerModMonoid
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/finite_monoids.py
0.937225
0.445469
finite_monoids.py
pypi
from sage.structure.parent import Parent from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets from sage.structure.unique_representation import UniqueRepresentation from sage.rings.integer import Integer class NonNegativeIntegers(UniqueRepresentation, Parent): r""" An example of infinite enumerated set: the non negative integers This class provides a minimal implementation of an infinite enumerated set. EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN An example of an infinite enumerated set: the non negative integers sage: NN.cardinality() +Infinity sage: NN.list() Traceback (most recent call last): ... NotImplementedError: cannot list an infinite set sage: NN.element_class <class 'sage.rings.integer.Integer'> sage: it = iter(NN) sage: [next(it), next(it), next(it), next(it), next(it)] [0, 1, 2, 3, 4] sage: x = next(it); type(x) <class 'sage.rings.integer.Integer'> sage: x.parent() Integer Ring sage: x+3 8 sage: NN(15) 15 sage: NN.first() 0 This checks that the different methods of `NN` return consistent results:: sage: TestSuite(NN).run(verbose = True) running ._test_an_element() . . . pass running ._test_cardinality() . . . pass running ._test_category() . . . pass running ._test_construction() . . . pass running ._test_elements() . . . Running the test suite of self.an_element() running ._test_category() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_nonzero_equal() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass pass running ._test_elements_eq_reflexive() . . . pass running ._test_elements_eq_symmetric() . . . pass running ._test_elements_eq_transitive() . . . pass running ._test_elements_neq() . . . pass running ._test_enumerated_set_contains() . . . pass running ._test_enumerated_set_iter_cardinality() . . . pass running ._test_enumerated_set_iter_list() . . . pass running ._test_eq() . . . pass running ._test_new() . . . pass running ._test_not_implemented_methods() . . . pass running ._test_pickling() . . . pass running ._test_some_elements() . . . pass """ def __init__(self): """ TESTS:: sage: NN = InfiniteEnumeratedSets().example() sage: NN An example of an infinite enumerated set: the non negative integers sage: NN.category() Category of infinite enumerated sets sage: TestSuite(NN).run() """ Parent.__init__(self, category = InfiniteEnumeratedSets()) def _repr_(self): """ TESTS:: sage: InfiniteEnumeratedSets().example() # indirect doctest An example of an infinite enumerated set: the non negative integers """ return "An example of an infinite enumerated set: the non negative integers" def __contains__(self, elt): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: 1 in NN True sage: -1 in NN False """ return Integer(elt) >= Integer(0) def __iter__(self): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: g = iter(NN) sage: next(g), next(g), next(g), next(g) (0, 1, 2, 3) """ i = Integer(0) while True: yield self._element_constructor_(i) i += 1 def __call__(self, elt): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN(3) # indirect doctest 3 sage: NN(3).parent() Integer Ring sage: NN(-1) Traceback (most recent call last): ... ValueError: Value -1 is not a non negative integer. """ if elt in self: return self._element_constructor_(elt) raise ValueError("Value %s is not a non negative integer." % (elt)) def an_element(self): """ EXAMPLES:: sage: InfiniteEnumeratedSets().example().an_element() 42 """ return self._element_constructor_(Integer(42)) def next(self, o): """ EXAMPLES:: sage: NN = InfiniteEnumeratedSets().example() sage: NN.next(3) 4 """ return self._element_constructor_(o+1) def _element_constructor_(self, i): """ The default implementation of _element_constructor_ assumes that the constructor of the element class takes the parent as parameter. This is not the case for ``Integer``, so we need to provide an implementation. TESTS:: sage: NN = InfiniteEnumeratedSets().example() sage: x = NN(42); x 42 sage: type(x) <class 'sage.rings.integer.Integer'> sage: x.parent() Integer Ring """ return self.element_class(i) Element = Integer Example = NonNegativeIntegers
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/infinite_enumerated_sets.py
0.912086
0.536313
infinite_enumerated_sets.py
pypi
from sage.structure.parent import Parent from sage.structure.unique_representation import UniqueRepresentation from sage.structure.element import Element from sage.categories.cw_complexes import CWComplexes from sage.sets.family import Family class Surface(UniqueRepresentation, Parent): r""" An example of a CW complex: a (2-dimensional) surface. This class illustrates a minimal implementation of a CW complex. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example(); X An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2) sage: X.category() Category of finite finite dimensional CW complexes We conclude by running systematic tests on this manifold:: sage: TestSuite(X).run() """ def __init__(self, bdy=(1, 2, 1, 2)): r""" EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example((1, 2)); X An example of a CW complex: the surface given by the boundary map (1, 2) TESTS:: sage: TestSuite(X).run() """ self._bdy = bdy self._edges = frozenset(bdy) Parent.__init__(self, category=CWComplexes().Finite()) def _repr_(self): r""" TESTS:: sage: from sage.categories.cw_complexes import CWComplexes sage: CWComplexes().example() An example of a CW complex: the surface given by the boundary map (1, 2, 1, 2) """ return "An example of a CW complex: the surface given by the boundary map {}".format(self._bdy) def cells(self): """ Return the cells of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: C = X.cells() sage: sorted((d, C[d]) for d in C.keys()) [(0, (0-cell v,)), (1, (0-cell e1, 0-cell e2)), (2, (2-cell f,))] """ d = {0: (self.element_class(self, 0, 'v'),)} d[1] = tuple([self.element_class(self, 0, 'e'+str(e)) for e in self._edges]) d[2] = (self.an_element(),) return Family(d) def an_element(self): r""" Return an element of the CW complex, as per :meth:`Sets.ParentMethods.an_element`. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: X.an_element() 2-cell f """ return self.element_class(self, 2, 'f') class Element(Element): """ A cell in a CW complex. """ def __init__(self, parent, dim, name): """ Initialize ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: TestSuite(f).run() """ Element.__init__(self, parent) self._dim = dim self._name = name def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: X.an_element() 2-cell f """ return "{}-cell {}".format(self._dim, self._name) def __eq__(self, other): """ Check equality. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: f == X(2, 'f') True sage: e1 = X(1, 'e1') sage: e1 == f False """ return (isinstance(other, Surface.Element) and self.parent() is other.parent() and self._dim == other._dim and self._name == other._name) def dimension(self): """ Return the dimension of ``self``. EXAMPLES:: sage: from sage.categories.cw_complexes import CWComplexes sage: X = CWComplexes().example() sage: f = X.an_element() sage: f.dimension() 2 """ return self._dim Example = Surface
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/categories/examples/cw_complexes.py
0.955992
0.673975
cw_complexes.py
pypi
r""" Signed and Unsigned Infinities The unsigned infinity "ring" is the set of two elements 1. infinity 2. A number less than infinity The rules for arithmetic are that the unsigned infinity ring does not canonically coerce to any other ring, and all other rings canonically coerce to the unsigned infinity ring, sending all elements to the single element "a number less than infinity" of the unsigned infinity ring. Arithmetic and comparisons then take place in the unsigned infinity ring, where all arithmetic operations that are well-defined are defined. The infinity "ring" is the set of five elements 1. plus infinity 2. a positive finite element 3. zero 4. a negative finite element 5. negative infinity The infinity ring coerces to the unsigned infinity ring, sending the infinite elements to infinity and the non-infinite elements to "a number less than infinity." Any ordered ring coerces to the infinity ring in the obvious way. .. NOTE:: The shorthand ``oo`` is predefined in Sage to be the same as ``+Infinity`` in the infinity ring. It is considered equal to, but not the same as ``Infinity`` in the :class:`UnsignedInfinityRing<UnsignedInfinityRing_class>`. EXAMPLES: We fetch the unsigned infinity ring and create some elements:: sage: P = UnsignedInfinityRing; P The Unsigned Infinity Ring sage: P(5) A number less than infinity sage: P.ngens() 1 sage: unsigned_oo = P.0; unsigned_oo Infinity We compare finite numbers with infinity:: sage: 5 < unsigned_oo True sage: 5 > unsigned_oo False sage: unsigned_oo < 5 False sage: unsigned_oo > 5 True Demonstrating the shorthand ``oo`` versus ``Infinity``:: sage: oo +Infinity sage: oo is InfinityRing.0 True sage: oo is UnsignedInfinityRing.0 False sage: oo == UnsignedInfinityRing.0 True We do arithmetic:: sage: unsigned_oo + 5 Infinity We make ``1 / unsigned_oo`` return the integer 0 so that arithmetic of the following type works:: sage: (1/unsigned_oo) + 2 2 sage: 32/5 - (2.439/unsigned_oo) 32/5 Note that many operations are not defined, since the result is not well-defined:: sage: unsigned_oo/0 Traceback (most recent call last): ... ValueError: quotient of number < oo by number < oo not defined What happened above is that 0 is canonically coerced to "A number less than infinity" in the unsigned infinity ring. Next, Sage tries to divide by multiplying with its inverse. Finally, this inverse is not well-defined. :: sage: 0/unsigned_oo 0 sage: unsigned_oo * 0 Traceback (most recent call last): ... ValueError: unsigned oo times smaller number not defined sage: unsigned_oo/unsigned_oo Traceback (most recent call last): ... ValueError: unsigned oo times smaller number not defined In the infinity ring, we can negate infinity, multiply positive numbers by infinity, etc. :: sage: P = InfinityRing; P The Infinity Ring sage: P(5) A positive finite number The symbol ``oo`` is predefined as a shorthand for ``+Infinity``:: sage: oo +Infinity We compare finite and infinite elements:: sage: 5 < oo True sage: P(-5) < P(5) True sage: P(2) < P(3) False sage: -oo < oo True We can do more arithmetic than in the unsigned infinity ring:: sage: 2 * oo +Infinity sage: -2 * oo -Infinity sage: 1 - oo -Infinity sage: 1 / oo 0 sage: -1 / oo 0 We make ``1 / oo`` and ``1 / -oo`` return the integer 0 instead of the infinity ring Zero so that arithmetic of the following type works:: sage: (1/oo) + 2 2 sage: 32/5 - (2.439/-oo) 32/5 If we try to subtract infinities or multiply infinity by zero we still get an error:: sage: oo - oo Traceback (most recent call last): ... SignError: cannot add infinity to minus infinity sage: 0 * oo Traceback (most recent call last): ... SignError: cannot multiply infinity by zero sage: P(2) + P(-3) Traceback (most recent call last): ... SignError: cannot add positive finite value to negative finite value Signed infinity can also be represented by RR / RDF elements. But unsigned infinity cannot:: sage: oo in RR, oo in RDF (True, True) sage: unsigned_infinity in RR, unsigned_infinity in RDF (False, False) TESTS:: sage: P = InfinityRing sage: P == loads(dumps(P)) True :: sage: P(2) == loads(dumps(P(2))) True The following is assumed in a lot of code (i.e., "is" is used for testing whether something is infinity), so make sure it is satisfied:: sage: loads(dumps(infinity)) is infinity True We check that :trac:`17990` is fixed:: sage: m = Matrix([Infinity]) sage: m.rows() [(+Infinity)] """ #***************************************************************************** # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from sys import maxsize from sage.rings.ring import Ring from sage.structure.element import RingElement, InfinityElement from sage.structure.richcmp import rich_to_bool, richcmp from sage.misc.fast_methods import Singleton import sage.rings.abc import sage.rings.integer import sage.rings.rational import sage.rings.integer_ring _obj = {} class _uniq(object): def __new__(cls, *args): """ This ensures uniqueness of these objects. EXAMPLES:: sage: sage.rings.infinity.UnsignedInfinityRing_class() is sage.rings.infinity.UnsignedInfinityRing_class() True """ if cls in _obj: return _obj[cls] _obj[cls] = O = cls.__bases__[-1].__new__(cls, *args) return O class AnInfinity(object): """ TESTS:: sage: oo == oo True sage: oo < oo False sage: -oo < oo True sage: -oo < 3 < oo True sage: unsigned_infinity == 3 False sage: unsigned_infinity == unsigned_infinity True sage: unsigned_infinity == oo True """ def _repr_(self): """ Return a string representation of ``self``. TESTS:: sage: [x._repr_() for x in [unsigned_infinity, oo, -oo]] ['Infinity', '+Infinity', '-Infinity'] """ return self._sign_char + "Infinity" def _giac_init_(self): """ TESTS:: sage: [x._giac_init_() for x in [unsigned_infinity, oo, -oo]] ['infinity', '+infinity', '-infinity'] """ return self._sign_char + "infinity" def _maxima_init_(self): """ TESTS:: sage: maxima(-oo) minf sage: [x._maxima_init_() for x in [unsigned_infinity, oo, -oo]] ['inf', 'inf', 'minf'] """ if self._sign < 0: return 'minf' else: return 'inf' def _fricas_init_(self): """ TESTS:: sage: fricas(-oo) # optional - fricas - infinity sage: [x._fricas_init_() for x in [unsigned_infinity, oo, -oo]] # optional - fricas ['%infinity', '%plusInfinity', '%minusInfinity'] sage: [fricas(x) for x in [unsigned_infinity, oo, -oo]] # optional - fricas [infinity, + infinity, - infinity] """ if self._sign_char == '': return r"%infinity" elif self._sign > 0: return r"%plusInfinity" else: return r"%minusInfinity" def __pari__(self): """ Convert ``self`` to a Pari object. EXAMPLES:: sage: pari(-oo) -oo sage: pari(oo) +oo """ # For some reason, it seems problematic to import sage.libs.all.pari, # so we call it directly. if self._sign >= 0: return sage.libs.all.pari('oo') else: return sage.libs.all.pari('-oo') def _latex_(self): r""" Return a latex representation of ``self``. EXAMPLES:: sage: latex(oo) # indirect doctest +\infty sage: [x._latex_() for x in [unsigned_infinity, oo, -oo]] ['\\infty', '+\\infty', '-\\infty'] """ return self._sign_char + "\\infty" def __abs__(self): """ EXAMPLES:: sage: [abs(x) for x in [UnsignedInfinityRing.gen(), oo, -oo]] [Infinity, +Infinity, +Infinity] """ return -self if self._sign < 0 else self def _add_(self, other): """ Add ``self`` to ``other``. EXAMPLES:: sage: -oo + -oo # indirect doctest -Infinity sage: -oo + 3 -Infinity sage: oo + -100 +Infinity sage: oo + -oo Traceback (most recent call last): ... SignError: cannot add infinity to minus infinity sage: unsigned_infinity = UnsignedInfinityRing.gen() sage: unsigned_infinity + unsigned_infinity Traceback (most recent call last): ... SignError: cannot add unsigned infinities sage: unsigned_infinity + oo*i Traceback (most recent call last): ... SignError: cannot add unsigned infinities sage: unsigned_infinity + 88/3 Infinity """ if isinstance(other, AnInfinity): if self._sign == 0: # just like oo - oo is undefined raise SignError("cannot add unsigned infinities") if self._sign != other._sign: raise SignError("cannot add infinity to minus infinity") return self def _sub_(self, other): """ EXAMPLES:: sage: -oo - oo # indirect doctest -Infinity sage: oo - -oo +Infinity sage: oo - 4 +Infinity sage: -oo - 1 -Infinity sage: oo - oo Traceback (most recent call last): ... SignError: cannot add infinity to minus infinity sage: unsigned_infinity - 4 Infinity sage: unsigned_infinity - unsigned_infinity Traceback (most recent call last): ... SignError: cannot subtract unsigned infinities sage: unsigned_infinity - oo*i Traceback (most recent call last): ... SignError: cannot subtract unsigned infinities """ if isinstance(other, AnInfinity): if self._sign == 0: raise SignError("cannot subtract unsigned infinities") elif self._sign == other._sign: raise SignError("cannot add infinity to minus infinity") return self def _mul_(self, other): """ EXAMPLES:: sage: oo * 19 # indirect doctest +Infinity sage: oo * oo +Infinity sage: -oo * oo -Infinity sage: -oo * 4 -Infinity sage: -oo * -2/3 +Infinity sage: -oo * 0 Traceback (most recent call last): ... SignError: cannot multiply infinity by zero """ if other < 0: return -self if other > 0: return self raise SignError("cannot multiply infinity by zero") def _div_(self, other): """ EXAMPLES:: sage: 1.5 / oo # indirect doctest 0 sage: oo / -4 -Infinity sage: oo / oo Traceback (most recent call last): ... SignError: cannot multiply infinity by zero Check that :trac:`14857` is fixed:: sage: infinity / unsigned_infinity Traceback (most recent call last): ... ValueError: unsigned oo times smaller number not defined sage: SR(infinity) / unsigned_infinity Traceback (most recent call last): ... RuntimeError: indeterminate expression: 0 * infinity encountered. """ return self * ~other def __float__(self): r""" Generate a floating-point infinity. The printing of floating-point infinity varies across platforms. EXAMPLES:: sage: RDF(infinity) +infinity sage: float(infinity) # random +infinity sage: CDF(infinity) +infinity sage: infinity.__float__() # random +infinity sage: RDF(-infinity) -infinity sage: float(-infinity) # random -inf sage: CDF(-infinity) -infinity sage: (-infinity).__float__() # random -inf sage: float(unsigned_infinity) Traceback (most recent call last): ... ValueError: unsigned infinity cannot be represented in a float """ if self._sign == 0: raise ValueError('unsigned infinity cannot be represented in a float') return float(self._sign_char + 'inf') def lcm(self, x): """ Return the least common multiple of ``oo`` and ``x``, which is by definition oo unless ``x`` is 0. EXAMPLES:: sage: oo.lcm(0) 0 sage: oo.lcm(oo) +Infinity sage: oo.lcm(-oo) +Infinity sage: oo.lcm(10) +Infinity sage: (-oo).lcm(10) +Infinity """ if x == 0: return x else: return abs(self) def _sage_input_(self, sib, coerced): """ Produce an expression which will reproduce this value when evaluated. TESTS:: sage: sage_input(-oo) -oo sage: sage_input(oo) oo sage: sage_input(unsigned_infinity) unsigned_infinity """ if self._sign == 0: return sib.name('unsigned_infinity') elif self._sign > 0: return sib.name('oo') else: return -sib.name('oo') class UnsignedInfinityRing_class(Singleton, Ring): def __init__(self): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.UnsignedInfinityRing_class() is sage.rings.infinity.UnsignedInfinityRing_class() is UnsignedInfinityRing True Sage can understand SymPy's complex infinity (:trac:`17493`):: sage: import sympy sage: SR(sympy.zoo) Infinity Some equality checks:: sage: infinity == UnsignedInfinityRing.gen() True sage: UnsignedInfinityRing(3) == UnsignedInfinityRing(-19.5) True """ Ring.__init__(self, self, names=('oo',), normalize=False) def ngens(self): """ The unsigned infinity ring has one "generator." EXAMPLES:: sage: UnsignedInfinityRing.ngens() 1 sage: len(UnsignedInfinityRing.gens()) 1 """ return 1 def fraction_field(self): """ The unsigned infinity ring isn't an integral domain. EXAMPLES:: sage: UnsignedInfinityRing.fraction_field() Traceback (most recent call last): ... TypeError: infinity 'ring' has no fraction field """ raise TypeError("infinity 'ring' has no fraction field") def gen(self, n=0): """ The "generator" of ``self`` is the infinity object. EXAMPLES:: sage: UnsignedInfinityRing.gen() Infinity sage: UnsignedInfinityRing.gen(1) Traceback (most recent call last): ... IndexError: UnsignedInfinityRing only has one generator """ if n == 0: try: return self._gen except AttributeError: self._gen = UnsignedInfinity() return self._gen else: raise IndexError("UnsignedInfinityRing only has one generator") def gens(self): """ The "generator" of ``self`` is the infinity object. EXAMPLES:: sage: UnsignedInfinityRing.gens() [Infinity] """ return [self.gen()] def less_than_infinity(self): """ This is the element that represents a finite value. EXAMPLES:: sage: UnsignedInfinityRing.less_than_infinity() A number less than infinity sage: UnsignedInfinityRing(5) is UnsignedInfinityRing.less_than_infinity() True """ try: return self._less_than_infinity except AttributeError: self._less_than_infinity = LessThanInfinity(self) return self._less_than_infinity def _repr_(self): """ Return a string representation of ``self``. TESTS:: sage: UnsignedInfinityRing._repr_() 'The Unsigned Infinity Ring' """ return "The Unsigned Infinity Ring" def _element_constructor_(self, x): """ The element constructor TESTS:: sage: UnsignedInfinityRing(2) # indirect doctest A number less than infinity sage: UnsignedInfinityRing(I) A number less than infinity sage: UnsignedInfinityRing(unsigned_infinity) Infinity sage: UnsignedInfinityRing(oo) Infinity sage: UnsignedInfinityRing(-oo) Infinity sage: K.<a> = QuadraticField(3) sage: UnsignedInfinityRing(a) A number less than infinity sage: UnsignedInfinityRing(a - 2) A number less than infinity sage: UnsignedInfinityRing(RDF(oo)), UnsignedInfinityRing(RDF(-oo)) (Infinity, Infinity) sage: UnsignedInfinityRing(RR(oo)), UnsignedInfinityRing(RR(-oo)) (Infinity, Infinity) sage: UnsignedInfinityRing(CDF(oo)), UnsignedInfinityRing(CDF(-oo)) (Infinity, Infinity) sage: UnsignedInfinityRing(CC(oo)), UnsignedInfinityRing(CC(-oo)) (Infinity, Infinity) sage: UnsignedInfinityRing(RIF(oo)), UnsignedInfinityRing(RIF(-oo)) (Infinity, Infinity) sage: UnsignedInfinityRing(float('+inf')), UnsignedInfinityRing(float('-inf')) (Infinity, Infinity) sage: UnsignedInfinityRing(SR(oo)), UnsignedInfinityRing(SR(-oo)) (Infinity, Infinity) The following rings have a ``is_infinity`` method:: sage: RR(oo).is_infinity() True sage: SR(oo).is_infinity() True """ # Lazy elements can wrap infinity or not, unwrap first try: from sage.rings.real_lazy import LazyWrapper except ImportError: pass else: if isinstance(x, LazyWrapper): x = x._value # Handle all ways to represent infinity first if isinstance(x, InfinityElement): return self.gen() elif isinstance(x, float): if x in [float('+inf'), float('-inf')]: return self.gen() elif isinstance(x, RingElement) and isinstance(x.parent(), sage.rings.abc.RealIntervalField): if x.upper().is_infinity() or x.lower().is_infinity(): return self.gen() else: try: # For example, RealField() implements this if x.is_infinity(): return self.gen() except AttributeError: pass # If we got here then x is not infinite return self.less_than_infinity() def _coerce_map_from_(self, R): """ EXAMPLES:: sage: UnsignedInfinityRing.has_coerce_map_from(int) # indirect doctest True sage: UnsignedInfinityRing.has_coerce_map_from(CC) True sage: UnsignedInfinityRing.has_coerce_map_from(QuadraticField(-163, 'a')) True sage: UnsignedInfinityRing.has_coerce_map_from(QQ^3) False sage: UnsignedInfinityRing.has_coerce_map_from(SymmetricGroup(13)) False """ return isinstance(R, Ring) or R in (int, float, complex) UnsignedInfinityRing = UnsignedInfinityRing_class() class LessThanInfinity(_uniq, RingElement): def __init__(self, parent=UnsignedInfinityRing): """ Initialize ``self``. EXAMPLES:: sage: sage.rings.infinity.LessThanInfinity() is UnsignedInfinityRing(5) True """ RingElement.__init__(self, parent) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: UnsignedInfinityRing(5)._repr_() 'A number less than infinity' """ return "A number less than infinity" def _latex_(self): """ Return a latex representation of ``self``. EXAMPLES:: sage: UnsignedInfinityRing(5)._latex_() '(<\\infty)' """ return "(<\\infty)" def _add_(self, other): """ EXAMPLES:: sage: UnsignedInfinityRing(5) + UnsignedInfinityRing(-3) # indirect doctest A number less than infinity sage: UnsignedInfinityRing(5) + unsigned_infinity Infinity """ if isinstance(other, UnsignedInfinity): return other return self def _sub_(self, other): """ EXAMPLES:: sage: UnsignedInfinityRing(5) - UnsignedInfinityRing(-3) # indirect doctest A number less than infinity sage: UnsignedInfinityRing(5) - unsigned_infinity Infinity """ if isinstance(other, UnsignedInfinity): return other return self def _mul_(self, other): """ EXAMPLES:: sage: UnsignedInfinityRing(4) * UnsignedInfinityRing(-3) # indirect doctest A number less than infinity sage: 5 * unsigned_infinity Traceback (most recent call last): ... ValueError: oo times number < oo not defined sage: unsigned_infinity * unsigned_infinity Infinity """ if isinstance(other, UnsignedInfinity): raise ValueError("oo times number < oo not defined") return self def _div_(self, other): """ Can't eliminate possibility of zero division.... EXAMPLES:: sage: UnsignedInfinityRing(2) / UnsignedInfinityRing(5) # indirect doctest Traceback (most recent call last): ... ValueError: quotient of number < oo by number < oo not defined sage: 1 / unsigned_infinity 0 """ if isinstance(other, UnsignedInfinity): return sage.rings.integer_ring.ZZ(0) raise ValueError("quotient of number < oo by number < oo not defined") def _richcmp_(self, other, op): """ Compare ``self`` to ``other``. EXAMPLES:: sage: 1 == unsigned_infinity False """ if isinstance(other, UnsignedInfinity): return rich_to_bool(op, -1) return rich_to_bool(op, 0) def sign(self): """ Raise an error because the sign of self is not well defined. EXAMPLES:: sage: sign(UnsignedInfinityRing(2)) Traceback (most recent call last): ... NotImplementedError: sign of number < oo is not well defined sage: sign(UnsignedInfinityRing(0)) Traceback (most recent call last): ... NotImplementedError: sign of number < oo is not well defined sage: sign(UnsignedInfinityRing(-2)) Traceback (most recent call last): ... NotImplementedError: sign of number < oo is not well defined """ raise NotImplementedError("sign of number < oo is not well defined") class UnsignedInfinity(_uniq, AnInfinity, InfinityElement): _sign = 0 _sign_char = '' def __init__(self): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.UnsignedInfinity() is sage.rings.infinity.UnsignedInfinity() is unsigned_infinity True """ InfinityElement.__init__(self, UnsignedInfinityRing) def __hash__(self): r""" TESTS:: sage: hash(unsigned_infinity) 9223372036854775806 # 64-bit 2147483646 # 32-bit """ return maxsize-1 def _mul_(self, other): """ Can't rule out an attempt at multiplication by 0. EXAMPLES:: sage: unsigned_infinity * unsigned_infinity # indirect doctest Infinity sage: unsigned_infinity * 0 Traceback (most recent call last): ... ValueError: unsigned oo times smaller number not defined sage: unsigned_infinity * 3 Traceback (most recent call last): ... ValueError: unsigned oo times smaller number not defined """ if isinstance(other, UnsignedInfinity): return self raise ValueError("unsigned oo times smaller number not defined") def _sympy_(self): """ Converts ``unsigned_infinity`` to sympy ``zoo``. EXAMPLES:: sage: import sympy sage: SR(unsigned_infinity)._sympy_() zoo sage: gamma(-3)._sympy_() is sympy.factorial(-2) True sage: gamma(-3) is sympy.factorial(-2)._sage_() True """ import sympy return sympy.zoo def _richcmp_(self, other, op): """ Compare ``self`` to ``other``. EXAMPLES:: sage: 1 == unsigned_infinity False """ if isinstance(other, LessThanInfinity): return rich_to_bool(op, 1) return rich_to_bool(op, 0) unsigned_infinity = UnsignedInfinityRing.gen(0) less_than_infinity = UnsignedInfinityRing.less_than_infinity() def is_Infinite(x): """ This is a type check for infinity elements. EXAMPLES:: sage: sage.rings.infinity.is_Infinite(oo) True sage: sage.rings.infinity.is_Infinite(-oo) True sage: sage.rings.infinity.is_Infinite(unsigned_infinity) True sage: sage.rings.infinity.is_Infinite(3) False sage: sage.rings.infinity.is_Infinite(RR(infinity)) False sage: sage.rings.infinity.is_Infinite(ZZ) False """ return isinstance(x, InfinityElement) class SignError(ArithmeticError): """ Sign error exception. """ pass class InfinityRing_class(Singleton, Ring): def __init__(self): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.InfinityRing_class() is sage.rings.infinity.InfinityRing_class() is InfinityRing True Comparison tests:: sage: InfinityRing == InfinityRing True sage: InfinityRing == UnsignedInfinityRing False """ Ring.__init__(self, self, names=('oo',), normalize=False) def fraction_field(self): """ This isn't really a ring, let alone an integral domain. TESTS:: sage: InfinityRing.fraction_field() Traceback (most recent call last): ... TypeError: infinity 'ring' has no fraction field """ raise TypeError("infinity 'ring' has no fraction field") def ngens(self): """ The two generators are plus and minus infinity. EXAMPLES:: sage: InfinityRing.ngens() 2 sage: len(InfinityRing.gens()) 2 """ return 2 def gen(self, n=0): """ The two generators are plus and minus infinity. EXAMPLES:: sage: InfinityRing.gen(0) +Infinity sage: InfinityRing.gen(1) -Infinity sage: InfinityRing.gen(2) Traceback (most recent call last): ... IndexError: n must be 0 or 1 """ try: if n == 0: return self._gen0 elif n == 1: return self._gen1 else: raise IndexError("n must be 0 or 1") except AttributeError: if n == 0: self._gen0 = PlusInfinity() return self._gen0 elif n == 1: self._gen1 = MinusInfinity() return self._gen1 def gens(self): """ The two generators are plus and minus infinity. EXAMPLES:: sage: InfinityRing.gens() [+Infinity, -Infinity] """ return [self.gen(0), self.gen(1)] def is_zero(self): """ The Infinity Ring is not zero EXAMPLES:: sage: InfinityRing.is_zero() False """ return False def is_commutative(self): """ The Infinity Ring is commutative EXAMPLES:: sage: InfinityRing.is_commutative() True """ return True def _repr_(self): """ Return a string representation of ``self``. TESTS:: sage: InfinityRing._repr_() 'The Infinity Ring' """ return "The Infinity Ring" def _element_constructor_(self, x): """ The element constructor TESTS:: sage: InfinityRing(-oo) # indirect doctest -Infinity sage: InfinityRing(3) A positive finite number sage: InfinityRing(-1.5) A negative finite number sage: [InfinityRing(a) for a in [-2..2]] [A negative finite number, A negative finite number, Zero, A positive finite number, A positive finite number] sage: K.<a> = QuadraticField(3) sage: InfinityRing(a) A positive finite number sage: InfinityRing(a - 2) A negative finite number sage: InfinityRing(RDF(oo)), InfinityRing(RDF(-oo)) (+Infinity, -Infinity) sage: InfinityRing(RR(oo)), InfinityRing(RR(-oo)) (+Infinity, -Infinity) sage: InfinityRing(RIF(oo)), InfinityRing(RIF(-oo)) (+Infinity, -Infinity) sage: InfinityRing(float('+inf')), InfinityRing(float('-inf')) (+Infinity, -Infinity) sage: InfinityRing(SR(oo)), InfinityRing(SR(-oo)) (+Infinity, -Infinity) The following rings have ``is_positive_infinity`` / ``is_negative_infinity`` methods:: sage: RR(oo).is_positive_infinity(), RR(-oo).is_negative_infinity() (True, True) sage: SR(oo).is_positive_infinity(), SR(-oo).is_negative_infinity() (True, True) Complex infinity raises an exception. This is fine (there is no coercion, so there is no promise of functoriality):: sage: i_infinity = CC(0, oo) sage: InfinityRing(CC(oo)), InfinityRing(CC(-oo)) (+Infinity, -Infinity) sage: InfinityRing(i_infinity) Traceback (most recent call last): ... ValueError: infinite but not with +/- phase sage: InfinityRing(CDF(oo)), InfinityRing(CDF(-oo)) (+Infinity, -Infinity) sage: InfinityRing(CDF(i_infinity)) Traceback (most recent call last): ... ValueError: infinite but not with +/- phase """ # Lazy elements can wrap infinity or not, unwrap first try: from sage.rings.real_lazy import LazyWrapper except ImportError: pass else: if isinstance(x, LazyWrapper): x = x._value # Handle all ways to represent infinity first if isinstance(x, InfinityElement): if x < 0: return self.gen(1) else: return self.gen(0) elif isinstance(x, float): if x == float('+inf'): return self.gen(0) if x == float('-inf'): return self.gen(1) elif isinstance(x, RingElement) and isinstance(x.parent(), sage.rings.abc.RealIntervalField): if x.upper().is_positive_infinity(): return self.gen(0) if x.lower().is_negative_infinity(): return self.gen(1) else: try: # For example, RealField() implements this if x.is_positive_infinity(): return self.gen(0) if x.is_negative_infinity(): return self.gen(1) if x.is_infinity(): raise ValueError('infinite but not with +/- phase') except AttributeError: pass # If we got here then x is not infinite c = int(bool(x > 0)) - int(bool(x < 0)) return FiniteNumber(self, c) def _coerce_map_from_(self, R): r""" There is a coercion from anything that has a coercion into the reals. The way Sage works is that everything that should be comparable with infinity can be coerced into the infinity ring, so if you ever compare with infinity the comparison is done there. If you don't have a coercion then you will get undesirable answers from the fallback comparison (likely memory location). EXAMPLES:: sage: InfinityRing.has_coerce_map_from(int) # indirect doctest True sage: InfinityRing.has_coerce_map_from(AA) True sage: InfinityRing.has_coerce_map_from(RDF) True sage: InfinityRing.has_coerce_map_from(RIF) True As explained above, comparison works by coercing to the infinity ring:: sage: cm = get_coercion_model() sage: cm.explain(AA(3), oo, operator.lt) Coercion on left operand via Coercion map: From: Algebraic Real Field To: The Infinity Ring Arithmetic performed after coercions. Result lives in The Infinity Ring The Infinity Ring The symbolic ring does not coerce to the infinity ring, so symbolic comparisons with infinities all happen in the symbolic ring:: sage: SR.has_coerce_map_from(InfinityRing) True sage: InfinityRing.has_coerce_map_from(SR) False Complex numbers do not coerce into the infinity ring (what would `i \infty` coerce to?). This is fine since they can not be compared, so we do not have to enforce consistency when comparing with infinity either:: sage: InfinityRing.has_coerce_map_from(CDF) False sage: InfinityRing.has_coerce_map_from(CC) False sage: CC(0, oo) < CC(1) # does not coerce to infinity ring True """ from sage.structure.coerce import parent_is_real_numerical if parent_is_real_numerical(R): return True if isinstance(R, (sage.rings.abc.RealIntervalField, sage.rings.abc.RealBallField)): return True return False def _pushout_(self, other): r""" EXAMPLES:: sage: QQbar(-2*i)*infinity (-I)*Infinity """ from sage.symbolic.ring import SR if SR.has_coerce_map_from(other): return SR class FiniteNumber(RingElement): def __init__(self, parent, x): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.FiniteNumber(InfinityRing, 1) A positive finite number sage: sage.rings.infinity.FiniteNumber(InfinityRing, -1) A negative finite number sage: sage.rings.infinity.FiniteNumber(InfinityRing, 0) Zero """ RingElement.__init__(self, parent) self.value = x def _richcmp_(self, other, op): """ Compare ``self`` and ``other``. EXAMPLES:: sage: P = InfinityRing sage: -oo < P(-5) < P(0) < P(1.5) < oo True sage: P(1) < P(100) False sage: P(-1) == P(-100) True """ if isinstance(other, PlusInfinity): return rich_to_bool(op, -1) if isinstance(other, MinusInfinity): return rich_to_bool(op, 1) return richcmp(self.value, other.value, op) def _add_(self, other): """ EXAMPLES:: sage: P = InfinityRing sage: 4 + oo # indirect doctest +Infinity sage: P(4) + P(2) A positive finite number sage: P(-1) + P(1) Traceback (most recent call last): ... SignError: cannot add positive finite value to negative finite value Subtraction is implemented by adding the negative:: sage: P = InfinityRing sage: 4 - oo # indirect doctest -Infinity sage: 5 - -oo +Infinity sage: P(44) - P(4) Traceback (most recent call last): ... SignError: cannot add positive finite value to negative finite value sage: P(44) - P(-1) A positive finite number """ if isinstance(other, InfinityElement): return other if self.value * other.value < 0: raise SignError("cannot add positive finite value to negative finite value") return FiniteNumber(self.parent(), self.value) def _mul_(self, other): """ EXAMPLES:: sage: P = InfinityRing sage: 0 * oo # indirect doctest Traceback (most recent call last): ... SignError: cannot multiply infinity by zero sage: -1 * oo -Infinity sage: -2 * oo -Infinity sage: 3 * oo +Infinity sage: -oo * oo -Infinity sage: P(0) * 3 0 sage: P(-3) * P(2/3) A negative finite number """ if other.is_zero(): if isinstance(self, InfinityElement): raise SignError("cannot multiply infinity by zero") return sage.rings.integer_ring.ZZ(0) if self.value < 0: if isinstance(other, InfinityElement): return -other return FiniteNumber(self.parent(), self.value * other.value) if self.value > 0: if isinstance(other, InfinityElement): return other return FiniteNumber(self.parent(), self.value * other.value) if self.value == 0: if isinstance(other, InfinityElement): raise SignError("cannot multiply infinity by zero") return sage.rings.integer_ring.ZZ(0) def _div_(self, other): """ EXAMPLES:: sage: P = InfinityRing sage: 1 / oo # indirect doctest 0 sage: oo / 4 +Infinity sage: oo / -4 -Infinity sage: P(1) / P(-4) A negative finite number """ return self * ~other def __invert__(self): """ EXAMPLES:: sage: P = InfinityRing sage: ~P(2) A positive finite number sage: ~P(-7) A negative finite number sage: ~P(0) Traceback (most recent call last): ... ZeroDivisionError: Cannot divide by zero """ if self.value == 0: raise ZeroDivisionError("Cannot divide by zero") return self def _neg_(self): """ EXAMPLES:: sage: a = InfinityRing(5); a A positive finite number sage: -a # indirect doctest A negative finite number sage: -(-a) == a True sage: -InfinityRing(0) Zero """ return FiniteNumber(self.parent(), -self.value) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: InfinityRing(-2)._repr_() 'A negative finite number' sage: InfinityRing(7)._repr_() 'A positive finite number' sage: InfinityRing(0)._repr_() 'Zero' """ if self.value < 0: return "A negative finite number" if self.value > 0: return "A positive finite number" return "Zero" def _latex_(self): """ Return a latex representation of ``self``. TESTS:: sage: a = InfinityRing(pi); a A positive finite number sage: a._latex_() 'A positive finite number' sage: [latex(InfinityRing(a)) for a in [-2..2]] [A negative finite number, A negative finite number, Zero, A positive finite number, A positive finite number] """ return self._repr_() def __abs__(self): """ EXAMPLES:: sage: abs(InfinityRing(-3)) A positive finite number sage: abs(InfinityRing(3)) A positive finite number sage: abs(InfinityRing(0)) Zero """ if self.value == 0: return FiniteNumber(self.parent(), 0) return FiniteNumber(self.parent(), 1) def sign(self): """ Return the sign of self. EXAMPLES:: sage: sign(InfinityRing(2)) 1 sage: sign(InfinityRing(0)) 0 sage: sign(InfinityRing(-2)) -1 TESTS:: sage: sgn(InfinityRing(7)) 1 sage: sgn(InfinityRing(0)) 0 sage: sgn(InfinityRing(-7)) -1 """ if self.value == 0: return 0 if self.value > 0: return 1 return -1 def sqrt(self): """ EXAMPLES:: sage: InfinityRing(7).sqrt() A positive finite number sage: InfinityRing(0).sqrt() Zero sage: InfinityRing(-.001).sqrt() Traceback (most recent call last): ... SignError: cannot take square root of a negative number """ if self.value < 0: raise SignError("cannot take square root of a negative number") return self class MinusInfinity(_uniq, AnInfinity, InfinityElement): _sign = -1 _sign_char = '-' def __init__(self): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.MinusInfinity() is sage.rings.infinity.MinusInfinity() is -oo True """ InfinityElement.__init__(self, InfinityRing) def __hash__(self): r""" TESTS:: sage: hash(-infinity) -9223372036854775808 # 64-bit -2147483648 # 32-bit """ return ~maxsize def _richcmp_(self, other, op): """ Compare ``self`` and ``other``. EXAMPLES:: sage: P = InfinityRing sage: -oo < P(-5) < P(0) < P(1.5) < oo True sage: P(1) < P(100) False sage: P(-1) == P(-100) True """ if isinstance(other, MinusInfinity): return rich_to_bool(op, 0) return rich_to_bool(op, -1) def _neg_(self): """ EXAMPLES:: sage: -(-oo) # indirect doctest +Infinity """ return self.parent().gen(0) def sqrt(self): """ EXAMPLES:: sage: (-oo).sqrt() Traceback (most recent call last): ... SignError: cannot take square root of negative infinity """ raise SignError("cannot take square root of negative infinity") def _sympy_(self): """ Converts ``-oo`` to sympy ``-oo``. Then you don't have to worry which ``oo`` you use, like in these examples: EXAMPLES:: sage: import sympy sage: bool(-oo == -sympy.oo) True sage: bool(SR(-oo) == -sympy.oo) True sage: bool((-oo)._sympy_() == -sympy.oo) True """ import sympy return -sympy.oo def _gap_init_(self): r""" Conversion to gap and libgap. EXAMPLES:: sage: gap(-Infinity) -infinity sage: libgap(-Infinity) -infinity """ return '-infinity' class PlusInfinity(_uniq, AnInfinity, InfinityElement): _sign = 1 _sign_char = '+' def __init__(self): """ Initialize ``self``. TESTS:: sage: sage.rings.infinity.PlusInfinity() is sage.rings.infinity.PlusInfinity() is oo True """ InfinityElement.__init__(self, InfinityRing) def __hash__(self): r""" TESTS:: sage: hash(+infinity) 9223372036854775807 # 64-bit 2147483647 # 32-bit """ return maxsize def _richcmp_(self, other, op): """ Compare ``self`` and ``other``. EXAMPLES:: sage: P = InfinityRing sage: -oo < P(-5) < P(0) < P(1.5) < oo True sage: P(1) < P(100) False sage: P(-1) == P(-100) True """ if isinstance(other, PlusInfinity): return rich_to_bool(op, 0) return rich_to_bool(op, 1) def _neg_(self): """ TESTS:: sage: -oo # indirect doctest -Infinity """ return self.parent().gen(1) def sqrt(self): """ The square root of ``self``. The square root of infinity is infinity. EXAMPLES:: sage: oo.sqrt() +Infinity """ return self def _sympy_(self): """ Converts ``oo`` to sympy ``oo``. Then you don't have to worry which ``oo`` you use, like in these examples: EXAMPLES:: sage: import sympy sage: bool(oo == sympy.oo) # indirect doctest True sage: bool(SR(oo) == sympy.oo) True """ import sympy return sympy.oo def _gap_init_(self): r""" Conversion to gap and libgap. EXAMPLES:: sage: gap(+Infinity) infinity sage: libgap(+Infinity) infinity """ return 'infinity' InfinityRing = InfinityRing_class() infinity = InfinityRing.gen(0) Infinity = infinity minus_infinity = InfinityRing.gen(1) def test_comparison(ring): """ Check comparison with infinity INPUT: - ``ring`` -- a sub-ring of the real numbers OUTPUT: Various attempts are made to generate elements of ``ring``. An assertion is triggered if one of these elements does not compare correctly with plus/minus infinity. EXAMPLES:: sage: from sage.rings.infinity import test_comparison sage: rings = [ZZ, QQ, RR, RealField(200), RDF, RLF, AA, RIF] sage: for R in rings: ....: print('testing {}'.format(R)) ....: test_comparison(R) testing Integer Ring testing Rational Field testing Real Field with 53 bits of precision testing Real Field with 200 bits of precision testing Real Double Field testing Real Lazy Field testing Algebraic Real Field testing Real Interval Field with 53 bits of precision Comparison with number fields does not work:: sage: K.<sqrt3> = NumberField(x^2-3) sage: (-oo < 1+sqrt3) and (1+sqrt3 < oo) # known bug False The symbolic ring handles its own infinities, but answers ``False`` (meaning: cannot decide) already for some very elementary comparisons:: sage: test_comparison(SR) # known bug Traceback (most recent call last): ... AssertionError: testing -1000.0 in Symbolic Ring: id = ... """ from sage.symbolic.ring import SR from sage.rings.rational_field import QQ elements = [-1e3, 99.9999, -SR(2).sqrt(), 0, 1, 3 ** (-QQ.one()/3), SR.pi(), 100000] elements.append(ring.an_element()) elements.extend(ring.some_elements()) for z in elements: try: z = ring(z) except (ValueError, TypeError): continue # ignore if z is not in ring msg = 'testing {} in {}: id = {}, {}, {}'.format(z, ring, id(z), id(infinity), id(minus_infinity)) assert minus_infinity < z, msg assert z > minus_infinity, msg assert z < infinity, msg assert infinity > z, msg assert minus_infinity <= z, msg assert z >= minus_infinity, msg assert z <= infinity, msg assert infinity >= z, msg def test_signed_infinity(pos_inf): """ Test consistency of infinity representations. There are different possible representations of infinity in Sage. These are all consistent with the infinity ring, that is, compare with infinity in the expected way. See also :trac:`14045` INPUT: - ``pos_inf`` -- a representation of positive infinity. OUTPUT: An assertion error is raised if the representation is not consistent with the infinity ring. Check that :trac:`14045` is fixed:: sage: InfinityRing(float('+inf')) +Infinity sage: InfinityRing(float('-inf')) -Infinity sage: oo > float('+inf') False sage: oo == float('+inf') True EXAMPLES:: sage: from sage.rings.infinity import test_signed_infinity sage: for pos_inf in [oo, float('+inf'), RLF(oo), RIF(oo), SR(oo)]: ....: test_signed_infinity(pos_inf) """ msg = 'testing {} ({})'.format(pos_inf, type(pos_inf)) assert InfinityRing(pos_inf) is infinity, msg assert InfinityRing(-pos_inf) is minus_infinity, msg assert infinity == pos_inf, msg assert not(infinity > pos_inf), msg assert not(infinity < pos_inf), msg assert minus_infinity == -pos_inf, msg assert not(minus_infinity > -pos_inf), msg assert not(minus_infinity < -pos_inf), msg assert pos_inf > -pos_inf, msg assert infinity > -pos_inf, msg assert pos_inf > minus_infinity, msg
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/rings/infinity.py
0.884539
0.668691
infinity.py
pypi
from sage.structure.parent import Parent import sage.rings.integer_ring from . import ideal from sage.categories.monoids import Monoids def IdealMonoid(R): r""" Return the monoid of ideals in the ring ``R``. EXAMPLES:: sage: R = QQ['x'] sage: sage.rings.ideal_monoid.IdealMonoid(R) Monoid of ideals of Univariate Polynomial Ring in x over Rational Field """ return IdealMonoid_c(R) class IdealMonoid_c(Parent): r""" The monoid of ideals in a commutative ring. TESTS:: sage: R = QQ['x'] sage: M = sage.rings.ideal_monoid.IdealMonoid(R) sage: TestSuite(M).run() Failure in _test_category: ... The following tests failed: _test_elements (The "_test_category" test fails but I haven't the foggiest idea why.) """ Element = ideal.Ideal_generic # this doesn't seem to do anything def __init__(self, R): r""" Initialize ``self``. TESTS:: sage: R = QuadraticField(-23, 'a') sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M # indirect doctest Monoid of ideals of Number Field in a with defining polynomial x^2 + 23 with a = 4.795831523312720?*I sage: id = QQ.ideal(6) sage: id.parent().category() Category of commutative monoids sage: MS = MatrixSpace(QQ,3,3) sage: MS.ideal(MS.one()).parent().category() Category of monoids """ self.__R = R cat = Monoids() if R.is_commutative(): cat = cat.Commutative() Parent.__init__(self, base=sage.rings.integer_ring.ZZ, category=cat) self._populate_coercion_lists_() def _repr_(self): r""" Return a string representation of ``self``. TESTS:: sage: R = QuadraticField(-23, 'a') sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M._repr_() 'Monoid of ideals of Number Field in a with defining polynomial x^2 + 23 with a = 4.795831523312720?*I' """ return "Monoid of ideals of %s" % self.__R def ring(self): r""" Return the ring of which this is the ideal monoid. EXAMPLES:: sage: R = QuadraticField(-23, 'a') sage: M = sage.rings.ideal_monoid.IdealMonoid(R); M.ring() is R True """ return self.__R def _element_constructor_(self, x): r""" Create an ideal in this monoid from ``x``. EXAMPLES:: sage: R.<a> = QuadraticField(-23) sage: M = sage.rings.ideal_monoid.IdealMonoid(R) sage: M(a) # indirect doctest Fractional ideal (a) sage: M([a-4, 13]) Fractional ideal (13, 1/2*a + 9/2) """ try: side = x.side() except (AttributeError, TypeError): side = None try: x = x.gens() except AttributeError: pass if side is None: y = self.__R.ideal(x) else: y = self.__R.ideal(x, side=side) y._set_parent(self) return y def _coerce_map_from_(self, x): r""" Used by coercion framework. EXAMPLES:: sage: R = QuadraticField(-23, 'a') sage: M = R.ideal_monoid() sage: M.has_coerce_map_from(R) # indirect doctest True sage: M.has_coerce_map_from(QQ.ideal_monoid()) True sage: M.has_coerce_map_from(Zmod(6)) False sage: M.has_coerce_map_from(loads(dumps(M))) True """ if isinstance(x, IdealMonoid_c): return self.ring().has_coerce_map_from(x.ring()) else: return self.ring().has_coerce_map_from(x) def __eq__(self, other): r""" Check whether ``self`` is not equal to ``other``. EXAMPLES:: sage: R = QuadraticField(-23, 'a') sage: M = R.ideal_monoid() sage: M == QQ False sage: M == 17 False sage: M == R.ideal_monoid() True """ if not isinstance(other, IdealMonoid_c): return False else: return self.ring() == other.ring() def __ne__(self, other): r""" Check whether ``self`` is not equal to ``other``. EXAMPLES:: sage: R = QuadraticField(-23, 'a') sage: M = R.ideal_monoid() sage: M != QQ True sage: M != 17 True sage: M != R.ideal_monoid() False """ return not (self == other) def __hash__(self): """ Return the hash of ``self``. EXAMPLES:: sage: R = QuadraticField(-23, 'a') sage: M = R.ideal_monoid() sage: hash(M) == hash(QQ) False sage: hash(M) == 17 False sage: hash(M) == hash(R.ideal_monoid()) True """ # uses a random number, to have a distinct hash return hash((1580963238588124931699, self.ring()))
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/rings/ideal_monoid.py
0.872605
0.676206
ideal_monoid.py
pypi
from sage.categories.homset import HomsetWithBase from sage.categories.rings import Rings _Rings = Rings() from . import morphism from . import quotient_ring def is_RingHomset(H): """ Return ``True`` if ``H`` is a space of homomorphisms between two rings. EXAMPLES:: sage: from sage.rings.homset import is_RingHomset as is_RH sage: is_RH(Hom(ZZ, QQ)) True sage: is_RH(ZZ) False sage: is_RH(Hom(RR, CC)) True sage: is_RH(Hom(FreeModule(ZZ,1), FreeModule(QQ,1))) False """ return isinstance(H, RingHomset_generic) def RingHomset(R, S, category = None): """ Construct a space of homomorphisms between the rings ``R`` and ``S``. For more on homsets, see :func:`Hom()`. EXAMPLES:: sage: Hom(ZZ, QQ) # indirect doctest Set of Homomorphisms from Integer Ring to Rational Field """ if quotient_ring.is_QuotientRing(R): return RingHomset_quo_ring(R, S, category = category) return RingHomset_generic(R, S, category = category) class RingHomset_generic(HomsetWithBase): """ A generic space of homomorphisms between two rings. EXAMPLES:: sage: Hom(ZZ, QQ) Set of Homomorphisms from Integer Ring to Rational Field sage: QQ.Hom(ZZ) Set of Homomorphisms from Rational Field to Integer Ring """ Element = morphism.RingHomomorphism def __init__(self, R, S, category = None): """ Initialize ``self``. EXAMPLES:: sage: Hom(ZZ, QQ) Set of Homomorphisms from Integer Ring to Rational Field """ if category is None: category = _Rings HomsetWithBase.__init__(self, R, S, category) def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: Hom(ZZ, QQ) # indirect doctest Set of Homomorphisms from Integer Ring to Rational Field """ return "Set of Homomorphisms from %s to %s"%(self.domain(), self.codomain()) def has_coerce_map_from(self, x): """ The default for coercion maps between ring homomorphism spaces is very restrictive (until more implementation work is done). Currently this checks if the domains and the codomains are equal. EXAMPLES:: sage: H = Hom(ZZ, QQ) sage: H2 = Hom(QQ, ZZ) sage: H.has_coerce_map_from(H2) False """ return (x.domain() == self.domain() and x.codomain() == self.codomain()) def _element_constructor_(self, x, check=True, base_map=None): """ Construct an element of ``self`` from ``x``. EXAMPLES:: sage: H = Hom(ZZ, QQ) sage: phi = H([1]); phi Ring morphism: From: Integer Ring To: Rational Field Defn: 1 |--> 1 sage: H2 = Hom(QQ, QQ) sage: phi2 = H2(phi); phi2 Ring endomorphism of Rational Field Defn: 1 |--> 1 sage: H(phi2) Ring morphism: From: Integer Ring To: Rational Field Defn: 1 |--> 1 You can provide a morphism on the base:: sage: k = GF(9) sage: z2 = k.gen() sage: cc = k.frobenius_endomorphism() sage: R.<x> = k[] sage: H = Hom(R, R) sage: phi = H([x^2], base_map=cc); phi Ring endomorphism of Univariate Polynomial Ring in x over Finite Field in z2 of size 3^2 Defn: x |--> x^2 with map of base ring sage: phi(z2*x) == z2^3 * x^2 True sage: R.<x> = ZZ[] sage: K.<a> = GF(7^2) sage: L.<u> = K.extension(x^3 - 3) sage: phi = L.hom([u^7], base_map=K.frobenius_endomorphism()) sage: phi(u) == u^7 True sage: phi(a) == a^7 True TESTS:: sage: H = Hom(ZZ, QQ) sage: H == loads(dumps(H)) True """ from sage.categories.map import Map # Case 0: the homomorphism is given by images of generators if not (isinstance(x, Map) and x.category_for().is_subcategory(Rings())): return morphism.RingHomomorphism_im_gens(self, x, base_map=base_map, check=check) if base_map is not None: raise ValueError("cannot specify base_map when providing a map") # Case 1: the parent fits if x.parent() == self: if isinstance(x, morphism.RingHomomorphism_im_gens): return morphism.RingHomomorphism_im_gens(self, x.im_gens()) elif isinstance(x, morphism.RingHomomorphism_cover): return morphism.RingHomomorphism_cover(self) elif isinstance(x, morphism.RingHomomorphism_from_base): return morphism.RingHomomorphism_from_base(self, x.underlying_map()) # Case 2: unique extension via fraction field try: if (isinstance(x, morphism.RingHomomorphism_im_gens) and x.domain().fraction_field().has_coerce_map_from(self.domain())): return morphism.RingHomomorphism_im_gens(self, x.im_gens()) except (TypeError, ValueError): pass # Case 3: the homomorphism can be extended by coercion try: return x.extend_codomain(self.codomain()).extend_domain(self.domain()) except (TypeError, ValueError): pass # Case 4: the homomorphism is induced from the base ring if (self.domain() != self.domain().base() or self.codomain() != self.codomain().base()): x = self.domain().base().Hom(self.codomain().base())(x) return morphism.RingHomomorphism_from_base(self, x) raise ValueError('cannot convert {} to an element of {}'.format(x, self)) def natural_map(self): """ Returns the natural map from the domain to the codomain. The natural map is the coercion map from the domain ring to the codomain ring. EXAMPLES:: sage: H = Hom(ZZ, QQ) sage: H.natural_map() Natural morphism: From: Integer Ring To: Rational Field """ f = self.codomain().coerce_map_from(self.domain()) if f is None: raise TypeError("natural coercion morphism from %s to %s not defined"%(self.domain(), self.codomain())) return f def zero(self): r""" Return the zero element of this homset. EXAMPLES: Since a ring homomorphism maps 1 to 1, there can only be a zero morphism when mapping to the trivial ring:: sage: Hom(ZZ, Zmod(1)).zero() Ring morphism: From: Integer Ring To: Ring of integers modulo 1 Defn: 1 |--> 0 sage: Hom(ZZ, Zmod(2)).zero() Traceback (most recent call last): ... ValueError: homset has no zero element """ if not self.codomain().is_zero(): raise ValueError("homset has no zero element") # there is only one map in this homset return self.an_element() class RingHomset_quo_ring(RingHomset_generic): """ Space of ring homomorphisms where the domain is a (formal) quotient ring. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: phi = S.hom([b,a]); phi Ring endomorphism of Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) Defn: a |--> b b |--> a sage: phi(a) b sage: phi(b) a TESTS: We test pickling of a homset from a quotient. :: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: H = S.Hom(R) sage: H == loads(dumps(H)) True We test pickling of actual homomorphisms in a quotient:: sage: phi = S.hom([b,a]) sage: phi == loads(dumps(phi)) True """ Element = morphism.RingHomomorphism_from_quotient def _element_constructor_(self, x, base_map=None, check=True): """ Construct an element of ``self`` from ``x``. EXAMPLES:: sage: R.<x,y> = PolynomialRing(QQ, 2) sage: S.<a,b> = R.quotient(x^2 + y^2) sage: H = S.Hom(R) sage: phi = H([b, a]); phi Ring morphism: From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) To: Multivariate Polynomial Ring in x, y over Rational Field Defn: a |--> b b |--> a sage: R2.<x,y> = PolynomialRing(ZZ, 2) sage: H2 = Hom(R2, S) sage: H2(phi) Composite map: From: Multivariate Polynomial Ring in x, y over Integer Ring To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) Defn: Coercion map: From: Multivariate Polynomial Ring in x, y over Integer Ring To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) then Ring morphism: From: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) To: Multivariate Polynomial Ring in x, y over Rational Field Defn: a |--> b b |--> a then Coercion map: From: Multivariate Polynomial Ring in x, y over Rational Field To: Quotient of Multivariate Polynomial Ring in x, y over Rational Field by the ideal (x^2 + y^2) """ if isinstance(x, morphism.RingHomomorphism_from_quotient): phi = x._phi() else: pi = self.domain().cover() phi = pi.domain().hom(x, base_map=base_map, check=check) return self.element_class(self, phi)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/rings/homset.py
0.877254
0.537102
homset.py
pypi
r""" Matrices over an arbitrary ring AUTHORS: - William Stein - Martin Albrecht: conversion to Pyrex - Jaap Spies: various functions - Gary Zablackis: fixed a sign bug in generic determinant. - William Stein and Robert Bradshaw - complete restructuring. - Rob Beezer - refactor kernel functions. Elements of matrix spaces are of class ``Matrix`` (or a class derived from Matrix). They can be either sparse or dense, and can be defined over any base ring. EXAMPLES: We create the `2\times 3` matrix .. MATH:: \left(\begin{matrix} 1&2&3\\4&5&6 \end{matrix}\right) as an element of a matrix space over `\QQ`:: sage: M = MatrixSpace(QQ,2,3) sage: A = M([1,2,3, 4,5,6]); A [1 2 3] [4 5 6] sage: A.parent() Full MatrixSpace of 2 by 3 dense matrices over Rational Field Alternatively, we could create A more directly as follows (which would completely avoid having to create the matrix space):: sage: A = matrix(QQ, 2, [1,2,3, 4,5,6]); A [1 2 3] [4 5 6] We next change the top-right entry of `A`. Note that matrix indexing is `0`-based in Sage, so the top right entry is `(0,2)`, which should be thought of as "row number `0`, column number `2`". :: sage: A[0,2] = 389 sage: A [ 1 2 389] [ 4 5 6] Also notice how matrices print. All columns have the same width and entries in a given column are right justified. Next we compute the reduced row echelon form of `A`. :: sage: A.rref() [ 1 0 -1933/3] [ 0 1 1550/3] Indexing ======== Sage has quite flexible ways of extracting elements or submatrices from a matrix:: sage: m=[(1, -2, -1, -1,9), (1, 8, 6, 2,2), (1, 1, -1, 1,4), (-1, 2, -2, -1,4)] ; M = matrix(m) sage: M [ 1 -2 -1 -1 9] [ 1 8 6 2 2] [ 1 1 -1 1 4] [-1 2 -2 -1 4] Get the 2 x 2 submatrix of M, starting at row index and column index 1:: sage: M[1:3,1:3] [ 8 6] [ 1 -1] Get the 2 x 3 submatrix of M starting at row index and column index 1:: sage: M[1:3,[1..3]] [ 8 6 2] [ 1 -1 1] Get the second column of M:: sage: M[:,1] [-2] [ 8] [ 1] [ 2] Get the first row of M:: sage: M[0,:] [ 1 -2 -1 -1 9] Get the last row of M (negative numbers count from the end):: sage: M[-1,:] [-1 2 -2 -1 4] More examples:: sage: M[range(2),:] [ 1 -2 -1 -1 9] [ 1 8 6 2 2] sage: M[range(2),4] [9] [2] sage: M[range(3),range(5)] [ 1 -2 -1 -1 9] [ 1 8 6 2 2] [ 1 1 -1 1 4] sage: M[3,range(5)] [-1 2 -2 -1 4] sage: M[3,:] [-1 2 -2 -1 4] sage: M[3,4] 4 sage: M[-1,:] [-1 2 -2 -1 4] sage: A = matrix(ZZ,3,4, [3, 2, -5, 0, 1, -1, 1, -4, 1, 0, 1, -3]); A [ 3 2 -5 0] [ 1 -1 1 -4] [ 1 0 1 -3] A series of three numbers, separated by colons, like ``n:m:s``, means numbers from ``n`` up to (but not including) ``m``, in steps of ``s``. So ``0:5:2`` means the sequence ``[0,2,4]``:: sage: A[:,0:4:2] [ 3 -5] [ 1 1] [ 1 1] sage: A[1:,0:4:2] [1 1] [1 1] sage: A[2::-1,:] [ 1 0 1 -3] [ 1 -1 1 -4] [ 3 2 -5 0] sage: A[1:,3::-1] [-4 1 -1 1] [-3 1 0 1] sage: A[1:,3::-2] [-4 -1] [-3 0] sage: A[2::-1,3:1:-1] [-3 1] [-4 1] [ 0 -5] We can also change submatrices using these indexing features:: sage: M=matrix([(1, -2, -1, -1,9), (1, 8, 6, 2,2), (1, 1, -1, 1,4), (-1, 2, -2, -1,4)]); M [ 1 -2 -1 -1 9] [ 1 8 6 2 2] [ 1 1 -1 1 4] [-1 2 -2 -1 4] Set the 2 x 2 submatrix of M, starting at row index and column index 1:: sage: M[1:3,1:3] = [[1,0],[0,1]]; M [ 1 -2 -1 -1 9] [ 1 1 0 2 2] [ 1 0 1 1 4] [-1 2 -2 -1 4] Set the 2 x 3 submatrix of M starting at row index and column index 1:: sage: M[1:3,[1..3]] = M[2:4,0:3]; M [ 1 -2 -1 -1 9] [ 1 1 0 1 2] [ 1 -1 2 -2 4] [-1 2 -2 -1 4] Set part of the first column of M:: sage: M[1:,0]=[[2],[3],[4]]; M [ 1 -2 -1 -1 9] [ 2 1 0 1 2] [ 3 -1 2 -2 4] [ 4 2 -2 -1 4] Or do a similar thing with a vector:: sage: M[1:,0]=vector([-2,-3,-4]); M [ 1 -2 -1 -1 9] [-2 1 0 1 2] [-3 -1 2 -2 4] [-4 2 -2 -1 4] Or a constant:: sage: M[1:,0]=30; M [ 1 -2 -1 -1 9] [30 1 0 1 2] [30 -1 2 -2 4] [30 2 -2 -1 4] Set the first row of M:: sage: M[0,:]=[[20,21,22,23,24]]; M [20 21 22 23 24] [30 1 0 1 2] [30 -1 2 -2 4] [30 2 -2 -1 4] sage: M[0,:]=vector([0,1,2,3,4]); M [ 0 1 2 3 4] [30 1 0 1 2] [30 -1 2 -2 4] [30 2 -2 -1 4] sage: M[0,:]=-3; M [-3 -3 -3 -3 -3] [30 1 0 1 2] [30 -1 2 -2 4] [30 2 -2 -1 4] sage: A = matrix(ZZ,3,4, [3, 2, -5, 0, 1, -1, 1, -4, 1, 0, 1, -3]); A [ 3 2 -5 0] [ 1 -1 1 -4] [ 1 0 1 -3] We can use the step feature of slices to set every other column:: sage: A[:,0:3:2] = 5; A [ 5 2 5 0] [ 5 -1 5 -4] [ 5 0 5 -3] sage: A[1:,0:4:2] = [[100,200],[300,400]]; A [ 5 2 5 0] [100 -1 200 -4] [300 0 400 -3] We can also count backwards to flip the matrix upside down:: sage: A[::-1,:]=A; A [300 0 400 -3] [100 -1 200 -4] [ 5 2 5 0] sage: A[1:,3::-1]=[[2,3,0,1],[9,8,7,6]]; A [300 0 400 -3] [ 1 0 3 2] [ 6 7 8 9] sage: A[1:,::-2] = A[1:,::2]; A [300 0 400 -3] [ 1 3 3 1] [ 6 8 8 6] sage: A[::-1,3:1:-1] = [[4,3],[1,2],[-1,-2]]; A [300 0 -2 -1] [ 1 3 2 1] [ 6 8 3 4] We save and load a matrix:: sage: A = matrix(Integers(8),3,range(9)) sage: loads(dumps(A)) == A True MUTABILITY: Matrices are either immutable or not. When initially created, matrices are typically mutable, so one can change their entries. Once a matrix `A` is made immutable using ``A.set_immutable()`` the entries of `A` cannot be changed, and `A` can never be made mutable again. However, properties of `A` such as its rank, characteristic polynomial, etc., are all cached so computations involving `A` may be more efficient. Once `A` is made immutable it cannot be changed back. However, one can obtain a mutable copy of `A` using ``copy(A)``. EXAMPLES:: sage: A = matrix(RR,2,[1,10,3.5,2]) sage: A.set_immutable() sage: copy(A) is A False The echelon form method always returns immutable matrices with known rank. EXAMPLES:: sage: A = matrix(Integers(8),3,range(9)) sage: A.determinant() 0 sage: A[0,0] = 5 sage: A.determinant() 1 sage: A.set_immutable() sage: A[0,0] = 5 Traceback (most recent call last): ... ValueError: matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M). Implementation and Design ------------------------- Class Diagram (an x means that class is currently supported):: x Matrix x Matrix_sparse x Matrix_generic_sparse x Matrix_integer_sparse x Matrix_rational_sparse Matrix_cyclo_sparse x Matrix_modn_sparse Matrix_RR_sparse Matrix_CC_sparse Matrix_RDF_sparse Matrix_CDF_sparse x Matrix_dense x Matrix_generic_dense x Matrix_integer_dense x Matrix_rational_dense Matrix_cyclo_dense -- idea: restrict scalars to QQ, compute charpoly there, then factor x Matrix_modn_dense Matrix_RR_dense Matrix_CC_dense x Matrix_real_double_dense x Matrix_complex_double_dense x Matrix_complex_ball_dense The corresponding files in the sage/matrix library code directory are named :: [matrix] [base ring] [dense or sparse]. :: New matrices types can only be implemented in Cython. *********** LEVEL 1 ********** NON-OPTIONAL For each base field it is *absolutely* essential to completely implement the following functionality for that base ring: * __cinit__ -- should use check_allocarray from cysignals.memory (only needed if allocate memory) * __init__ -- this signature: 'def __init__(self, parent, entries, copy, coerce)' * __dealloc__ -- use sig_free (only needed if allocate memory) * set_unsafe(self, size_t i, size_t j, x) -- doesn't do bounds or any other checks; assumes x is in self._base_ring * get_unsafe(self, size_t i, size_t j) -- doesn't do checks * __richcmp__ -- always the same (I don't know why its needed -- bug in PYREX). Note that the __init__ function must construct the all zero matrix if ``entries == None``. *********** LEVEL 2 ********** IMPORTANT (and *highly* recommended): After getting the special class with all level 1 functionality to work, implement all of the following (they should not change functionality, except speed (always faster!) in any way): * def _pickle(self): return data, version * def _unpickle(self, data, int version) reconstruct matrix from given data and version; may assume _parent, _nrows, and _ncols are set. Use version numbers >= 0 so if you change the pickle strategy then old objects still unpickle. * cdef _list -- list of underlying elements (need not be a copy) * cdef _dict -- sparse dictionary of underlying elements * cdef _add_ -- add two matrices with identical parents * _matrix_times_matrix_c_impl -- multiply two matrices with compatible dimensions and identical base rings (both sparse or both dense) * cpdef _richcmp_ -- compare two matrices with identical parents * cdef _lmul_c_impl -- multiply this matrix on the right by a scalar, i.e., self * scalar * cdef _rmul_c_impl -- multiply this matrix on the left by a scalar, i.e., scalar * self * __copy__ * __neg__ The list and dict returned by _list and _dict will *not* be changed by any internal algorithms and are not accessible to the user. *********** LEVEL 3 ********** OPTIONAL: * cdef _sub_ * __invert__ * _multiply_classical * __deepcopy__ Further special support: * Matrix windows -- to support Strassen multiplication for a given base ring. * Other functions, e.g., transpose, for which knowing the specific representation can be helpful. .. note:: - For caching, use self.fetch and self.cache. - Any method that can change the matrix should call ``check_mutability()`` first. There are also many fast cdef'd bounds checking methods. - Kernels of matrices Implement only a left_kernel() or right_kernel() method, whichever requires the least overhead (usually meaning little or no transposing). Let the methods in the matrix2 class handle left, right, generic kernel distinctions. """
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/matrix/docs.py
0.895027
0.884639
docs.py
pypi
import sage.rings.rational_field def berlekamp_massey(a): r""" Use the Berlekamp-Massey algorithm to find the minimal polynomial of a linear recurrence sequence `a`. The minimal polynomial of a linear recurrence `\{a_r\}` is by definition the unique monic polynomial `g`, such that if `\{a_r\}` satisfies a linear recurrence `a_{j+k} + b_{j-1} a_{j-1+k} + \cdots + b_0 a_k=0` (for all `k\geq 0`), then `g` divides the polynomial `x^j + \sum_{i=0}^{j-1} b_i x^i`. INPUT: - ``a`` -- a list of even length of elements of a field (or domain) OUTPUT: the minimal polynomial of the sequence, as a polynomial over the field in which the entries of `a` live .. WARNING:: The result is only guaranteed to be correct on the full sequence if there exists a linear recurrence of length less than half the length of `a`. EXAMPLES:: sage: from sage.matrix.berlekamp_massey import berlekamp_massey sage: berlekamp_massey([1,2,1,2,1,2]) x^2 - 1 sage: berlekamp_massey([GF(7)(1),19,1,19]) x^2 + 6 sage: berlekamp_massey([2,2,1,2,1,191,393,132]) x^4 - 36727/11711*x^3 + 34213/5019*x^2 + 7024942/35133*x - 335813/1673 sage: berlekamp_massey(prime_range(2,38)) x^6 - 14/9*x^5 - 7/9*x^4 + 157/54*x^3 - 25/27*x^2 - 73/18*x + 37/9 TESTS:: sage: berlekamp_massey("banana") Traceback (most recent call last): ... TypeError: argument must be a list or tuple sage: berlekamp_massey([1,2,5]) Traceback (most recent call last): ... ValueError: argument must have an even number of terms """ if not isinstance(a, (list, tuple)): raise TypeError("argument must be a list or tuple") if len(a) % 2: raise ValueError("argument must have an even number of terms") M = len(a) // 2 try: K = a[0].parent().fraction_field() except AttributeError: K = sage.rings.rational_field.RationalField() R = K['x'] x = R.gen() f = {-1: R(a), 0: x**(2 * M)} s = {-1: 1, 0: 0} j = 0 while f[j].degree() >= M: j += 1 qj, f[j] = f[j - 2].quo_rem(f[j - 1]) s[j] = s[j - 2] - qj * s[j - 1] t = s[j].reverse() return ~(t[t.degree()]) * t # make monic (~ is inverse in python)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/matrix/berlekamp_massey.py
0.710126
0.674865
berlekamp_massey.py
pypi
from sage.categories.fields import Fields _Fields = Fields() def row_iterator(A): for i in range(A.nrows()): yield A.row(i) def prm_mul(p1, p2, mask_free, prec): """ Return the product of ``p1`` and ``p2``, putting free variables in ``mask_free`` to `1`. This function is mainly use as a subroutine of :func:`permanental_minor_polynomial`. INPUT: - `p1,p2` -- polynomials as dictionaries - `mask_free` -- an integer mask that give the list of free variables (the `i`-th variable is free if the `i`-th bit of ``mask_free`` is `1`) - `prec` -- if `prec` is not None, truncate the product at precision `prec` EXAMPLES:: sage: from sage.matrix.matrix_misc import prm_mul sage: t = polygen(ZZ, 't') sage: p1 = {0: 1, 1: t, 4: t} sage: p2 = {0: 1, 1: t, 2: t} sage: prm_mul(p1, p2, 1, None) {0: 2*t + 1, 2: t^2 + t, 4: t^2 + t, 6: t^2} """ p = {} if not p2: return p for exp1, v1 in p1.items(): if v1.is_zero(): continue for exp2, v2 in p2.items(): if exp1 & exp2: continue v = v1 * v2 if prec is not None: v._unsafe_mutate(prec, 0) exp = exp1 | exp2 exp = exp ^ (exp & mask_free) if exp not in p: p[exp] = v else: p[exp] += v return p def permanental_minor_polynomial(A, permanent_only=False, var='t', prec=None): r""" Return the polynomial of the sums of permanental minors of ``A``. INPUT: - `A` -- a matrix - `permanent_only` -- if True, return only the permanent of `A` - `var` -- name of the polynomial variable - `prec` -- if prec is not None, truncate the polynomial at precision `prec` The polynomial of the sums of permanental minors is .. MATH:: \sum_{i=0}^{min(nrows, ncols)} p_i(A) x^i where `p_i(A)` is the `i`-th permanental minor of `A` (that can also be obtained through the method :meth:`~sage.matrix.matrix2.Matrix.permanental_minor` via ``A.permanental_minor(i)``). The algorithm implemented by that function has been developed by P. Butera and M. Pernici, see [BP2015]_. Its complexity is `O(2^n m^2 n)` where `m` and `n` are the number of rows and columns of `A`. Moreover, if `A` is a banded matrix with width `w`, that is `A_{ij}=0` for `|i - j| > w` and `w < n/2`, then the complexity of the algorithm is `O(4^w (w+1) n^2)`. INPUT: - ``A`` -- matrix - ``permanent_only`` -- optional boolean. If ``True``, only the permanent is computed (might be faster). - ``var`` -- a variable name EXAMPLES:: sage: from sage.matrix.matrix_misc import permanental_minor_polynomial sage: m = matrix([[1,1],[1,2]]) sage: permanental_minor_polynomial(m) 3*t^2 + 5*t + 1 sage: permanental_minor_polynomial(m, permanent_only=True) 3 sage: permanental_minor_polynomial(m, prec=2) 5*t + 1 :: sage: M = MatrixSpace(ZZ,4,4) sage: A = M([1,0,1,0,1,0,1,0,1,0,10,10,1,0,1,1]) sage: permanental_minor_polynomial(A) 84*t^3 + 114*t^2 + 28*t + 1 sage: [A.permanental_minor(i) for i in range(5)] [1, 28, 114, 84, 0] An example over `\QQ`:: sage: M = MatrixSpace(QQ,2,2) sage: A = M([1/5,2/7,3/2,4/5]) sage: permanental_minor_polynomial(A, True) 103/175 An example with polynomial coefficients:: sage: R.<a> = PolynomialRing(ZZ) sage: A = MatrixSpace(R,2)([[a,1], [a,a+1]]) sage: permanental_minor_polynomial(A, True) a^2 + 2*a A usage of the ``var`` argument:: sage: m = matrix(ZZ,4,[0,1,2,3,1,2,3,0,2,3,0,1,3,0,1,2]) sage: permanental_minor_polynomial(m, var='x') 164*x^4 + 384*x^3 + 172*x^2 + 24*x + 1 ALGORITHM: The permanent `perm(A)` of a `n \times n` matrix `A` is the coefficient of the `x_1 x_2 \ldots x_n` monomial in .. MATH:: \prod_{i=1}^n \left( \sum_{j=1}^n A_{ij} x_j \right) Evaluating this product one can neglect `x_i^2`, that is `x_i` can be considered to be nilpotent of order `2`. To formalize this procedure, consider the algebra `R = K[\eta_1, \eta_2, \ldots, \eta_n]` where the `\eta_i` are commuting, nilpotent of order `2` (i.e. `\eta_i^2 = 0`). Formally it is the quotient ring of the polynomial ring in `\eta_1, \eta_2, \ldots, \eta_n` quotiented by the ideal generated by the `\eta_i^2`. We will mostly consider the ring `R[t]` of polynomials over `R`. We denote a generic element of `R[t]` by `p(\eta_1, \ldots, \eta_n)` or `p(\eta_{i_1}, \ldots, \eta_{i_k})` if we want to emphasize that some monomials in the `\eta_i` are missing. Introduce an "integration" operation `\langle p \rangle` over `R` and `R[t]` consisting in the sum of the coefficients of the non-vanishing monomials in `\eta_i` (i.e. the result of setting all variables `\eta_i` to `1`). Let us emphasize that this is *not* a morphism of algebras as `\langle \eta_1 \rangle^2 = 1` while `\langle \eta_1^2 \rangle = 0`! Let us consider an example of computation. Let `p_1 = 1 + t \eta_1 + t \eta_2` and `p_2 = 1 + t \eta_1 + t \eta_3`. Then .. MATH:: p_1 p_2 = 1 + 2t \eta_1 + t (\eta_2 + \eta_3) + t^2 (\eta_1 \eta_2 + \eta_1 \eta_3 + \eta_2 \eta_3) and .. MATH:: \langle p_1 p_2 \rangle = 1 + 4t + 3t^2 In this formalism, the permanent is just .. MATH:: perm(A) = \langle \prod_{i=1}^n \sum_{j=1}^n A_{ij} \eta_j \rangle A useful property of `\langle . \rangle` which makes this algorithm efficient for band matrices is the following: let `p_1(\eta_1, \ldots, \eta_n)` and `p_2(\eta_j, \ldots, \eta_n)` be polynomials in `R[t]` where `j \ge 1`. Then one has .. MATH:: \langle p_1(\eta_1, \ldots, \eta_n) p_2 \rangle = \langle p_1(1, \ldots, 1, \eta_j, \ldots, \eta_n) p_2 \rangle where `\eta_1,..,\eta_{j-1}` are replaced by `1` in `p_1`. Informally, we can "integrate" these variables *before* performing the product. More generally, if a monomial `\eta_i` is missing in one of the terms of a product of two terms, then it can be integrated in the other term. Now let us consider an `m \times n` matrix with `m \leq n`. The *sum of permanental `k`-minors of `A`* is .. MATH:: perm(A, k) = \sum_{r,c} perm(A_{r,c}) where the sum is over the `k`-subsets `r` of rows and `k`-subsets `c` of columns and `A_{r,c}` is the submatrix obtained from `A` by keeping only the rows `r` and columns `c`. Of course `perm(A, \min(m,n)) = perm(A)` and note that `perm(A,1)` is just the sum of all entries of the matrix. The generating function of these sums of permanental minors is .. MATH:: g(t) = \left\langle \prod_{i=1}^m \left(1 + t \sum_{j=1}^n A_{ij} \eta_j\right) \right\rangle In fact the `t^k` coefficient of `g(t)` corresponds to choosing `k` rows of `A`; `\eta_i` is associated to the i-th column; nilpotency avoids having twice the same column in a product of `A`'s. For more details, see the article [BP2015]_. From a technical point of view, the product in `K[\eta_1, \ldots, \eta_n][t]` is implemented as a subroutine in :func:`prm_mul`. The indices of the rows and columns actually start at `0`, so the variables are `\eta_0, \ldots, \eta_{n-1}`. Polynomials are represented in dictionary form: to a variable `\eta_i` is associated the key `2^i` (or in Python ``1 << i``). The keys associated to products are obtained by considering the development in base `2`: to the monomial `\eta_{i_1} \ldots \eta_{i_k}` is associated the key `2^{i_1} + \ldots + 2^{i_k}`. So the product `\eta_1 \eta_2` corresponds to the key `6 = (110)_2` while `\eta_0 \eta_3` has key `9 = (1001)_2`. In particular all operations on monomials are implemented via bitwise operations on the keys. """ if permanent_only: prec = None elif prec is not None: prec = int(prec) if prec == 0: raise ValueError('the argument `prec` must be a positive integer') from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing K = PolynomialRing(A.base_ring(), var) nrows = A.nrows() ncols = A.ncols() A = A.rows() p = {0: K.one()} t = K.gen() vars_to_do = list(range(ncols)) for i in range(nrows): # build the polynomial p1 = 1 + t sum A_{ij} eta_j if permanent_only: p1 = {} else: p1 = {0: K.one()} a = A[i] # the i-th row of A for j in range(len(a)): if a[j]: p1[1<<j] = a[j] * t # make the product with the preceding polynomials, taking care of # variables that can be integrated mask_free = 0 j = 0 while j < len(vars_to_do): jj = vars_to_do[j] if all(A[k][jj] == 0 for k in range(i+1, nrows)): mask_free += 1 << jj vars_to_do.remove(jj) else: j += 1 p = prm_mul(p, p1, mask_free, prec) if not p: return K.zero() if len(p) != 1 or 0 not in p: raise RuntimeError("Something is wrong! Certainly a problem in the" " algorithm... please contact sage-devel@googlegroups.com") p = p[0] return p[min(nrows,ncols)] if permanent_only else p
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/matrix/matrix_misc.py
0.870487
0.739069
matrix_misc.py
pypi
from sage.misc.latex import latex from sage.misc.prandom import choice from sage.misc.cachefunc import cached_method from sage.structure.category_object import CategoryObject from sage.structure.element import Element from sage.structure.parent import Parent, Set_generic from sage.structure.richcmp import richcmp_method, richcmp, rich_to_bool from sage.misc.classcall_metaclass import ClasscallMetaclass from sage.categories.sets_cat import Sets from sage.categories.enumerated_sets import EnumeratedSets import sage.rings.infinity def has_finite_length(obj): """ Return ``True`` if ``obj`` is known to have finite length. This is mainly meant for pure Python types, so we do not call any Sage-specific methods. EXAMPLES:: sage: from sage.sets.set import has_finite_length sage: has_finite_length(tuple(range(10))) True sage: has_finite_length(list(range(10))) True sage: has_finite_length(set(range(10))) True sage: has_finite_length(iter(range(10))) False sage: has_finite_length(GF(17^127)) True sage: has_finite_length(ZZ) False """ try: len(obj) except OverflowError: return True except Exception: return False else: return True def Set(X=None): r""" Create the underlying set of ``X``. If ``X`` is a list, tuple, Python set, or ``X.is_finite()`` is ``True``, this returns a wrapper around Python's enumerated immutable ``frozenset`` type with extra functionality. Otherwise it returns a more formal wrapper. If you need the functionality of mutable sets, use Python's builtin set type. EXAMPLES:: sage: X = Set(GF(9,'a')) sage: X {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} sage: type(X) <class 'sage.sets.set.Set_object_enumerated_with_category'> sage: Y = X.union(Set(QQ)) sage: Y Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field sage: type(Y) <class 'sage.sets.set.Set_object_union_with_category'> Usually sets can be used as dictionary keys. :: sage: d={Set([2*I,1+I]):10} sage: d # key is randomly ordered {{I + 1, 2*I}: 10} sage: d[Set([1+I,2*I])] 10 sage: d[Set((1+I,2*I))] 10 The original object is often forgotten. :: sage: v = [1,2,3] sage: X = Set(v) sage: X {1, 2, 3} sage: v.append(5) sage: X {1, 2, 3} sage: 5 in X False Set also accepts iterators, but be careful to only give *finite* sets:: sage: sorted(Set(range(1,6))) [1, 2, 3, 4, 5] sage: sorted(Set(list(range(1,6)))) [1, 2, 3, 4, 5] sage: sorted(Set(iter(range(1,6)))) [1, 2, 3, 4, 5] We can also create sets from different types:: sage: sorted(Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])]), key=str) [5, Rational Field, [3, 1, 1], [3, 1]] Sets with unhashable objects work, but with less functionality:: sage: A = Set([QQ, (3, 1), 5]) # hashable sage: sorted(A.list(), key=repr) [(3, 1), 5, Rational Field] sage: type(A) <class 'sage.sets.set.Set_object_enumerated_with_category'> sage: B = Set([QQ, [3, 1], 5]) # unhashable sage: sorted(B.list(), key=repr) Traceback (most recent call last): ... AttributeError: 'Set_object_with_category' object has no attribute 'list' sage: type(B) <class 'sage.sets.set.Set_object_with_category'> TESTS:: sage: Set(Primes()) Set of all prime numbers: 2, 3, 5, 7, ... sage: Set(Subsets([1,2,3])).cardinality() 8 sage: S = Set(iter([1,2,3])); S {1, 2, 3} sage: type(S) <class 'sage.sets.set.Set_object_enumerated_with_category'> sage: S = Set([]) sage: TestSuite(S).run() Check that :trac:`16090` is fixed:: sage: Set() {} """ if X is None: X = [] elif isinstance(X, CategoryObject): if isinstance(X, Set_generic): return X elif X in Sets().Finite(): return Set_object_enumerated(X) else: return Set_object(X) if isinstance(X, Element) and not isinstance(X, Set_base): raise TypeError("Element has no defined underlying set") try: X = frozenset(X) except TypeError: return Set_object(X) else: return Set_object_enumerated(X) class Set_base(): r""" Abstract base class for sets, not necessarily parents. """ def union(self, X): """ Return the union of ``self`` and ``X``. EXAMPLES:: sage: Set(QQ).union(Set(ZZ)) Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring sage: Set(QQ) + Set(ZZ) Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring sage: X = Set(QQ).union(Set(GF(3))); X Set-theoretic union of Set of elements of Rational Field and {0, 1, 2} sage: 2/3 in X True sage: GF(3)(2) in X True sage: GF(5)(2) in X False sage: sorted(Set(GF(7)) + Set(GF(3)), key=int) [0, 0, 1, 1, 2, 2, 3, 4, 5, 6] """ if isinstance(X, (Set_generic, Set_base)): if self is X: return self return Set_object_union(self, X) raise TypeError("X (=%s) must be a Set" % X) def intersection(self, X): r""" Return the intersection of ``self`` and ``X``. EXAMPLES:: sage: X = Set(ZZ).intersection(Primes()) sage: 4 in X False sage: 3 in X True sage: 2/1 in X True sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'c'))) sage: X {} sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'b'))) sage: X {} """ if isinstance(X, (Set_generic, Set_base)): if self is X: return self return Set_object_intersection(self, X) raise TypeError("X (=%s) must be a Set" % X) def difference(self, X): r""" Return the set difference ``self - X``. EXAMPLES:: sage: X = Set(ZZ).difference(Primes()) sage: 4 in X True sage: 3 in X False sage: 4/1 in X True sage: X = Set(GF(9,'b')).difference(Set(GF(27,'c'))) sage: X {0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2} sage: X = Set(GF(9,'b')).difference(Set(GF(27,'b'))) sage: X {0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2} """ if isinstance(X, (Set_generic, Set_base)): if self is X: return Set([]) return Set_object_difference(self, X) raise TypeError("X (=%s) must be a Set" % X) def symmetric_difference(self, X): r""" Returns the symmetric difference of ``self`` and ``X``. EXAMPLES:: sage: X = Set([1,2,3]).symmetric_difference(Set([3,4])) sage: X {1, 2, 4} """ if isinstance(X, (Set_generic, Set_base)): if self is X: return Set([]) return Set_object_symmetric_difference(self, X) raise TypeError("X (=%s) must be a Set" % X) def _test_as_set_object(self, tester=None, **options): r""" Run the test suite of ``Set(self)`` unless it is identical to ``self``. EXAMPLES: Nothing is tested for instances of :class`Set_generic` (constructed with the :func:`Set` constructor):: sage: Set(ZZ)._test_as_set_object(verbose=True) Instances of other subclasses of :class:`Set_base` run this method:: sage: Polyhedron()._test_as_set_object(verbose=True) Running the test suite of Set(self) running ._test_an_element() . . . pass ... running ._test_some_elements() . . . pass """ if tester is None: tester = self._tester(**options) set_self = Set(self) if set_self is not self: from sage.misc.sage_unittest import TestSuite tester.info("\n Running the test suite of Set(self)") TestSuite(set_self).run(skip="_test_pickling", # see Trac #32025 verbose=tester._verbose, prefix=tester._prefix + " ") tester.info(tester._prefix + " ", newline=False) class Set_boolean_operators: r""" Mix-in class providing the Boolean operators ``__or__``, ``__and__``, ``__xor__``. The operators delegate to the methods ``union``, ``intersection``, and ``symmetric_difference``, which need to be implemented by the class. """ def __or__(self, X): """ Return the union of ``self`` and ``X``. EXAMPLES:: sage: Set([2,3]) | Set([3,4]) {2, 3, 4} sage: Set(ZZ) | Set(QQ) Set-theoretic union of Set of elements of Integer Ring and Set of elements of Rational Field """ return self.union(X) def __and__(self, X): """ Returns the intersection of ``self`` and ``X``. EXAMPLES:: sage: Set([2,3]) & Set([3,4]) {3} sage: Set(ZZ) & Set(QQ) Set-theoretic intersection of Set of elements of Integer Ring and Set of elements of Rational Field """ return self.intersection(X) def __xor__(self, X): """ Returns the symmetric difference of ``self`` and ``X``. EXAMPLES:: sage: X = Set([1,2,3,4]) sage: Y = Set([1,2]) sage: X.symmetric_difference(Y) {3, 4} sage: X.__xor__(Y) {3, 4} """ return self.symmetric_difference(X) class Set_add_sub_operators: r""" Mix-in class providing the operators ``__add__`` and ``__sub__``. The operators delegate to the methods ``union`` and ``intersection``, which need to be implemented by the class. """ def __add__(self, X): """ Return the union of ``self`` and ``X``. EXAMPLES:: sage: Set(RealField()) + Set(QQ^5) Set-theoretic union of Set of elements of Real Field with 53 bits of precision and Set of elements of Vector space of dimension 5 over Rational Field sage: Set(GF(3)) + Set(GF(2)) {0, 1, 2, 0, 1} sage: Set(GF(2)) + Set(GF(4,'a')) {0, 1, a, a + 1} sage: sorted(Set(GF(8,'b')) + Set(GF(4,'a')), key=str) [0, 0, 1, 1, a, a + 1, b, b + 1, b^2, b^2 + 1, b^2 + b, b^2 + b + 1] """ return self.union(X) def __sub__(self, X): """ Return the difference of ``self`` and ``X``. EXAMPLES:: sage: X = Set(ZZ).difference(Primes()) sage: Y = Set(ZZ) - Primes() sage: X == Y True """ return self.difference(X) @richcmp_method class Set_object(Set_generic, Set_base, Set_boolean_operators, Set_add_sub_operators): r""" A set attached to an almost arbitrary object. EXAMPLES:: sage: K = GF(19) sage: Set(K) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18} sage: S = Set(K) sage: latex(S) \left\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\right\} sage: TestSuite(S).run() sage: latex(Set(ZZ)) \Bold{Z} TESTS: See :trac:`14486`:: sage: 0 == Set([1]), Set([1]) == 0 (False, False) sage: 1 == Set([0]), Set([0]) == 1 (False, False) """ def __init__(self, X, category=None): """ Create a Set_object This function is called by the Set function; users shouldn't call this directly. EXAMPLES:: sage: type(Set(QQ)) <class 'sage.sets.set.Set_object_with_category'> sage: Set(QQ).category() Category of sets TESTS:: sage: _a, _b = get_coercion_model().canonical_coercion(Set([0]), 0) Traceback (most recent call last): ... TypeError: no common canonical parent for objects with parents: '<class 'sage.sets.set.Set_object_enumerated_with_category'>' and 'Integer Ring' """ from sage.rings.integer import is_Integer if isinstance(X, int) or is_Integer(X): # The coercion model will try to call Set_object(0) raise ValueError('underlying object cannot be an integer') if category is None: category = Sets() Parent.__init__(self, category=category) self.__object = X def __hash__(self): """ Return the hash value of ``self``. EXAMPLES:: sage: hash(Set(QQ)) == hash(QQ) True """ return hash(self.__object) def _latex_(self): r""" Return latex representation of this set. This is often the same as the latex representation of this object when the object is infinite. EXAMPLES:: sage: latex(Set(QQ)) \Bold{Q} When the object is finite or a special set then the latex representation can be more interesting. :: sage: print(latex(Primes())) \text{\texttt{Set{ }of{ }all{ }prime{ }numbers:{ }2,{ }3,{ }5,{ }7,{ }...}} sage: print(latex(Set([1,1,1,5,6]))) \left\{1, 5, 6\right\} """ return latex(self.__object) def _repr_(self): """ Print representation of this set. EXAMPLES:: sage: X = Set(ZZ) sage: X Set of elements of Integer Ring sage: X.rename('{ integers }') sage: X { integers } """ return "Set of elements of " + repr(self.__object) def __iter__(self): """ Iterate over the elements of this set. EXAMPLES:: sage: X = Set(ZZ) sage: I = X.__iter__() sage: next(I) 0 sage: next(I) 1 sage: next(I) -1 sage: next(I) 2 """ return iter(self.__object) _an_element_from_iterator = EnumeratedSets.ParentMethods.__dict__['_an_element_from_iterator'] def _an_element_(self): """ Return an element of ``self``. EXAMPLES:: sage: R = Set(RR) sage: R.an_element() # indirect doctest 1.00000000000000 sage: F = Set([1, 2, 3]) sage: F.an_element() 1 """ if self.__object is not self: try: return self.__object.an_element() except (AttributeError, NotImplementedError): pass return self._an_element_from_iterator() def __contains__(self, x): """ Return ``True`` if `x` is in ``self``. EXAMPLES:: sage: X = Set(ZZ) sage: 5 in X True sage: GF(7)(3) in X True sage: 2/1 in X True sage: 2/1 in ZZ True sage: 2/3 in X False Finite fields better illustrate the difference between ``__contains__`` for objects and their underlying sets. sage: X = Set(GF(7)) sage: X {0, 1, 2, 3, 4, 5, 6} sage: 5/3 in X False sage: 5/3 in GF(7) False sage: sorted(Set(GF(7)).union(Set(GF(5))), key=int) [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6] sage: Set(GF(7)).intersection(Set(GF(5))) {} """ return x in self.__object def __richcmp__(self, right, op): r""" Compare ``self`` and ``right``. If ``right`` is not a :class:`Set_object`, return ``NotImplemented``. If ``right`` is also a :class:`Set_object`, returns comparison on the underlying objects. .. NOTE:: If `X < Y` is true this does *not* necessarily mean that `X` is a subset of `Y`. Also, any two sets can be compared still, but the result need not be meaningful if they are not equal. EXAMPLES:: sage: Set(ZZ) == Set(QQ) False sage: Set(ZZ) < Set(QQ) True sage: Primes() == Set(QQ) False """ if not isinstance(right, Set_object): return NotImplemented return richcmp(self.__object, right.__object, op) def cardinality(self): """ Return the cardinality of this set, which is either an integer or ``Infinity``. EXAMPLES:: sage: Set(ZZ).cardinality() +Infinity sage: Primes().cardinality() +Infinity sage: Set(GF(5)).cardinality() 5 sage: Set(GF(5^2,'a')).cardinality() 25 """ if not self.is_finite(): return sage.rings.infinity.infinity if self is not self.__object: try: return self.__object.cardinality() except (AttributeError, NotImplementedError): pass from sage.rings.integer import Integer try: return Integer(len(self.__object)) except TypeError: pass raise NotImplementedError("computation of cardinality of %s not yet implemented" % self.__object) def is_empty(self): """ Return boolean representing emptiness of the set. OUTPUT: True if the set is empty, False if otherwise. EXAMPLES:: sage: Set([]).is_empty() True sage: Set([0]).is_empty() False sage: Set([1..100]).is_empty() False sage: Set(SymmetricGroup(2).list()).is_empty() False sage: Set(ZZ).is_empty() False TESTS:: sage: Set([]).is_empty() True sage: Set([1,2,3]).is_empty() False sage: Set([1..100]).is_empty() False sage: Set(DihedralGroup(4).list()).is_empty() False sage: Set(QQ).is_empty() False """ return not self def is_finite(self): """ Return ``True`` if ``self`` is finite. EXAMPLES:: sage: Set(QQ).is_finite() False sage: Set(GF(250037)).is_finite() True sage: Set(Integers(2^1000000)).is_finite() True sage: Set([1,'a',ZZ]).is_finite() True """ obj = self.__object try: is_finite = obj.is_finite except AttributeError: return has_finite_length(obj) else: return is_finite() def object(self): """ Return underlying object. EXAMPLES:: sage: X = Set(QQ) sage: X.object() Rational Field sage: X = Primes() sage: X.object() Set of all prime numbers: 2, 3, 5, 7, ... """ return self.__object def subsets(self, size=None): """ Return the :class:`Subsets` object representing the subsets of a set. If size is specified, return the subsets of that size. EXAMPLES:: sage: X = Set([1, 2, 3]) sage: list(X.subsets()) [{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] sage: list(X.subsets(2)) [{1, 2}, {1, 3}, {2, 3}] """ from sage.combinat.subset import Subsets return Subsets(self, size) def subsets_lattice(self): """ Return the lattice of subsets ordered by containment. EXAMPLES:: sage: X = Set([1,2,3]) sage: X.subsets_lattice() Finite lattice containing 8 elements sage: Y = Set() sage: Y.subsets_lattice() Finite lattice containing 1 elements """ if not self.is_finite(): raise NotImplementedError( "this method is only implemented for finite sets") from sage.combinat.posets.lattices import FiniteLatticePoset from sage.graphs.graph import DiGraph from sage.rings.integer import Integer n = self.cardinality() # list, contains at position 0 <= i < 2^n # the i-th subset of self subset_of_index = [Set([self[i] for i in range(n) if v & (1 << i)]) for v in range(2**n)] # list, contains at position 0 <= i < 2^n # the list of indices of all immediate supersets upper_covers = [[Integer(x | (1 << y)) for y in range(n) if not x & (1 << y)] for x in range(2**n)] # DiGraph, every subset points to all immediate supersets D = DiGraph({subset_of_index[v]: [subset_of_index[w] for w in upper_covers[v]] for v in range(2**n)}) # Lattice poset, defined by hasse diagram D L = FiniteLatticePoset(hasse_diagram=D) return L @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set(ZZ); X Set of elements of Integer Ring sage: X._sympy_() Integers """ from sage.interfaces.sympy import sympy_init sympy_init() return self.__object._sympy_() class Set_object_enumerated(Set_object): """ A finite enumerated set. """ def __init__(self, X): r""" Initialize ``self``. EXAMPLES:: sage: S = Set(GF(19)); S {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18} sage: S.category() Category of finite sets sage: print(latex(S)) \left\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\right\} sage: TestSuite(S).run() """ Set_object.__init__(self, X, category=Sets().Finite()) def random_element(self): r""" Return a random element in this set. EXAMPLES:: sage: Set([1,2,3]).random_element() # random 2 """ try: return self.object().random_element() except AttributeError: # TODO: this very slow! return choice(self.list()) def is_finite(self): r""" Return ``True`` as this is a finite set. EXAMPLES:: sage: Set(GF(19)).is_finite() True """ return True def cardinality(self): """ Return the cardinality of ``self``. EXAMPLES:: sage: Set([1,1]).cardinality() 1 """ from sage.rings.integer import Integer return Integer(len(self.set())) def __len__(self): """ EXAMPLES:: sage: len(Set([1,1])) 1 """ return len(self.set()) def __iter__(self): r""" Iterating through the elements of ``self``. EXAMPLES:: sage: S = Set(GF(19)) sage: I = iter(S) sage: next(I) 0 sage: next(I) 1 sage: next(I) 2 sage: next(I) 3 """ return iter(self.set()) def _latex_(self): r""" Return the LaTeX representation of ``self``. EXAMPLES:: sage: S = Set(GF(2)) sage: latex(S) \left\{0, 1\right\} """ return '\\left\\{' + ', '.join(latex(x) for x in self.set()) + '\\right\\}' def _repr_(self): r""" Return the string representation of ``self``. EXAMPLES:: sage: S = Set(GF(2)) sage: S {0, 1} TESTS:: sage: Set() {} """ py_set = self.set() if not py_set: return "{}" return repr(py_set) def list(self): """ Return the elements of ``self``, as a list. EXAMPLES:: sage: X = Set(GF(8,'c')) sage: X {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: X.list() [0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1] sage: type(X.list()) <... 'list'> .. TODO:: FIXME: What should be the order of the result? That of ``self.object()``? Or the order given by ``set(self.object())``? Note that :meth:`__getitem__` is currently implemented in term of this list method, which is really inefficient ... """ return list(set(self.object())) def set(self): """ Return the Python set object associated to this set. Python has a notion of finite set, and often Sage sets have an associated Python set. This function returns that set. EXAMPLES:: sage: X = Set(GF(8,'c')) sage: X {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: X.set() {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: type(X.set()) <... 'set'> sage: type(X) <class 'sage.sets.set.Set_object_enumerated_with_category'> """ return set(self.object()) def frozenset(self): """ Return the Python frozenset object associated to this set, which is an immutable set (hence hashable). EXAMPLES:: sage: X = Set(GF(8,'c')) sage: X {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: s = X.set(); s {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: hash(s) Traceback (most recent call last): ... TypeError: unhashable type: 'set' sage: s = X.frozenset(); s frozenset({0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}) sage: hash(s) != hash(tuple(X.set())) True sage: type(s) <... 'frozenset'> """ return frozenset(self.object()) def __hash__(self): """ Return the hash of ``self`` (as a ``frozenset``). EXAMPLES:: sage: s = Set(GF(8,'c')) sage: hash(s) == hash(s) True """ return hash(self.frozenset()) def __richcmp__(self, other, op): """ Compare the sets ``self`` and ``other``. EXAMPLES:: sage: X = Set(GF(8,'c')) sage: X == Set(GF(8,'c')) True sage: X == Set(GF(4,'a')) False sage: Set(QQ) == Set(ZZ) False sage: Set([1]) == set([1]) True """ if not isinstance(other, Set_object_enumerated): if isinstance(other, (set, frozenset)): return self.set() == other return NotImplemented if self.set() == other.set(): return rich_to_bool(op, 0) return rich_to_bool(op, -1) def issubset(self, other): r""" Return whether ``self`` is a subset of ``other``. INPUT: - ``other`` -- a finite Set EXAMPLES:: sage: X = Set([1,3,5]) sage: Y = Set([0,1,2,3,5,7]) sage: X.issubset(Y) True sage: Y.issubset(X) False sage: X.issubset(X) True TESTS:: sage: len([Z for Z in Y.subsets() if Z.issubset(X)]) 8 """ if not isinstance(other, Set_object_enumerated): raise NotImplementedError return self.set().issubset(other.set()) def issuperset(self, other): r""" Return whether ``self`` is a superset of ``other``. INPUT: - ``other`` -- a finite Set EXAMPLES:: sage: X = Set([1,3,5]) sage: Y = Set([0,1,2,3,5]) sage: X.issuperset(Y) False sage: Y.issuperset(X) True sage: X.issuperset(X) True TESTS:: sage: len([Z for Z in Y.subsets() if Z.issuperset(X)]) 4 """ if not isinstance(other, Set_object_enumerated): raise NotImplementedError return self.set().issuperset(other.set()) def union(self, other): """ Return the union of ``self`` and ``other``. EXAMPLES:: sage: X = Set(GF(8,'c')) sage: Y = Set([GF(8,'c').0, 1, 2, 3]) sage: X {0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1} sage: sorted(Y) [1, 2, 3, c] sage: sorted(X.union(Y), key=str) [0, 1, 2, 3, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1] """ if not isinstance(other, Set_object_enumerated): return Set_object.union(self, other) return Set_object_enumerated(self.set().union(other.set())) def intersection(self, other): """ Return the intersection of ``self`` and ``other``. EXAMPLES:: sage: X = Set(GF(8,'c')) sage: Y = Set([GF(8,'c').0, 1, 2, 3]) sage: X.intersection(Y) {1, c} """ if not isinstance(other, Set_object_enumerated): return Set_object.intersection(self, other) return Set_object_enumerated(self.set().intersection(other.set())) def difference(self, other): """ Return the set difference ``self - other``. EXAMPLES:: sage: X = Set([1,2,3,4]) sage: Y = Set([1,2]) sage: X.difference(Y) {3, 4} sage: Z = Set(ZZ) sage: W = Set([2.5, 4, 5, 6]) sage: W.difference(Z) {2.50000000000000} """ if not isinstance(other, Set_object_enumerated): return Set([x for x in self if x not in other]) return Set_object_enumerated(self.set().difference(other.set())) def symmetric_difference(self, other): """ Return the symmetric difference of ``self`` and ``other``. EXAMPLES:: sage: X = Set([1,2,3,4]) sage: Y = Set([1,2]) sage: X.symmetric_difference(Y) {3, 4} sage: Z = Set(ZZ) sage: W = Set([2.5, 4, 5, 6]) sage: U = W.symmetric_difference(Z) sage: 2.5 in U True sage: 4 in U False sage: V = Z.symmetric_difference(W) sage: V == U True sage: 2.5 in V True sage: 6 in V False """ if not isinstance(other, Set_object_enumerated): return Set_object.symmetric_difference(self, other) return Set_object_enumerated(self.set().symmetric_difference(other.set())) @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set({1, 2, 3}); X {1, 2, 3} sage: sX = X._sympy_(); sX Set(1, 2, 3) sage: sX.is_empty is None True sage: Empty = Set([]); Empty {} sage: sEmpty = Empty._sympy_(); sEmpty EmptySet sage: sEmpty.is_empty True """ from sympy import Set, EmptySet from sage.interfaces.sympy import sympy_init sympy_init() if self.is_empty(): return EmptySet return Set(*[x._sympy_() for x in self]) class Set_object_binary(Set_object, metaclass=ClasscallMetaclass): r""" An abstract common base class for sets defined by a binary operation (ex. :class:`Set_object_union`, :class:`Set_object_intersection`, :class:`Set_object_difference`, and :class:`Set_object_symmetric_difference`). INPUT: - ``X``, ``Y`` -- sets, the operands to ``op`` - ``op`` -- a string describing the binary operation - ``latex_op`` -- a string used for rendering this object in LaTeX EXAMPLES:: sage: X = Set(QQ^2) sage: Y = Set(ZZ) sage: from sage.sets.set import Set_object_binary sage: S = Set_object_binary(X, Y, "union", "\\cup"); S Set-theoretic union of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring """ @staticmethod def __classcall__(cls, X, Y, *args, **kwds): r""" Convert the operands to instances of :class:`Set_object` if necessary. TESTS:: sage: from sage.sets.set import Set_object_binary sage: X = QQ^2 sage: Y = ZZ sage: Set_object_binary(X, Y, "union", "\\cup") Set-theoretic union of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring """ if not isinstance(X, Set_object): X = Set(X) if not isinstance(Y, Set_object): Y = Set(Y) return type.__call__(cls, X, Y, *args, **kwds) def __init__(self, X, Y, op, latex_op): r""" Initialization. TESTS:: sage: from sage.sets.set import Set_object_binary sage: X = Set(QQ^2) sage: Y = Set(ZZ) sage: S = Set_object_binary(X, Y, "union", "\\cup") sage: type(S) <class 'sage.sets.set.Set_object_binary_with_category'> """ self._X = X self._Y = Y self._op = op self._latex_op = latex_op Set_object.__init__(self, self) def _repr_(self): r""" Return a string representation of this set. EXAMPLES:: sage: Set(ZZ).union(Set(GF(5))) Set-theoretic union of Set of elements of Integer Ring and {0, 1, 2, 3, 4} """ return "Set-theoretic {} of {} and {}".format(self._op, self._X, self._Y) def _latex_(self): r""" Return a latex representation of this set. EXAMPLES:: sage: latex(Set(ZZ).union(Set(GF(5)))) \Bold{Z} \cup \left\{0, 1, 2, 3, 4\right\} """ return latex(self._X) + self._latex_op + latex(self._Y) def __hash__(self): """ The hash value of this set. EXAMPLES: The hash values of equal sets are in general not equal since it is not decidable whether two sets are equal:: sage: X = Set(GF(13)).intersection(Set(ZZ)) sage: Y = Set(ZZ).intersection(Set(GF(13))) sage: hash(X) == hash(Y) False TESTS: Test that :trac:`14432` has been resolved:: sage: S = Set(ZZ).union(Set([infinity])) sage: T = Set(ZZ).union(Set([infinity])) sage: hash(S) == hash(T) True """ return hash((self._X, self._Y, self._op)) class Set_object_union(Set_object_binary): """ A formal union of two sets. """ def __init__(self, X, Y): r""" Initialize ``self``. EXAMPLES:: sage: S = Set(QQ^2) sage: T = Set(ZZ) sage: X = S.union(T); X Set-theoretic union of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring sage: latex(X) \Bold{Q}^{2} \cup \Bold{Z} sage: TestSuite(X).run() """ Set_object_binary.__init__(self, X, Y, "union", "\\cup") def is_finite(self): r""" Return whether this set is finite. EXAMPLES:: sage: X = Set(range(10)) sage: Y = Set(range(-10,0)) sage: Z = Set(Primes()) sage: X.union(Y).is_finite() True sage: X.union(Z).is_finite() False """ return self._X.is_finite() and self._Y.is_finite() def __richcmp__(self, right, op): r""" Try to compare ``self`` and ``right``. .. NOTE:: Comparison is basically not implemented, or rather it could say sets are not equal even though they are. I don't know how one could implement this for a generic union of sets in a meaningful manner. So be careful when using this. EXAMPLES:: sage: Y = Set(ZZ^2).union(Set(ZZ^3)) sage: X = Set(ZZ^3).union(Set(ZZ^2)) sage: X == Y True sage: Y == X True This illustrates that equality testing for formal unions can be misleading in general. :: sage: Set(ZZ).union(Set(QQ)) == Set(QQ) False """ if not isinstance(right, Set_generic): return rich_to_bool(op, -1) if not isinstance(right, Set_object_union): return rich_to_bool(op, -1) if self._X == right._X and self._Y == right._Y or \ self._X == right._Y and self._Y == right._X: return rich_to_bool(op, 0) return rich_to_bool(op, -1) def __iter__(self): """ Return iterator over the elements of ``self``. EXAMPLES:: sage: [x for x in Set(GF(3)).union(Set(GF(2)))] [0, 1, 2, 0, 1] """ for x in self._X: yield x for y in self._Y: yield y def __contains__(self, x): """ Return ``True`` if ``x`` is an element of ``self``. EXAMPLES:: sage: X = Set(GF(3)).union(Set(GF(2))) sage: GF(5)(1) in X False sage: GF(3)(2) in X True sage: GF(2)(0) in X True sage: GF(5)(0) in X False """ return x in self._X or x in self._Y def cardinality(self): """ Return the cardinality of this set. EXAMPLES:: sage: X = Set(GF(3)).union(Set(GF(2))) sage: X {0, 1, 2, 0, 1} sage: X.cardinality() 5 sage: X = Set(GF(3)).union(Set(ZZ)) sage: X.cardinality() +Infinity """ return self._X.cardinality() + self._Y.cardinality() @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set(ZZ).union(Set([1/2])); X Set-theoretic union of Set of elements of Integer Ring and {1/2} sage: X._sympy_() Union(Integers, Set(1/2)) """ from sympy import Union from sage.interfaces.sympy import sympy_init sympy_init() return Union(self._X._sympy_(), self._Y._sympy_()) class Set_object_intersection(Set_object_binary): """ Formal intersection of two sets. """ def __init__(self, X, Y): r""" Initialize ``self``. EXAMPLES:: sage: S = Set(QQ^2) sage: T = Set(ZZ) sage: X = S.intersection(T); X Set-theoretic intersection of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring sage: latex(X) \Bold{Q}^{2} \cap \Bold{Z} sage: X = Set(IntegerRange(100)).intersection(Primes()) sage: X.is_finite() True sage: TestSuite(X).run() """ Set_object_binary.__init__(self, X, Y, "intersection", "\\cap") def is_finite(self): r""" Return whether this set is finite. EXAMPLES:: sage: X = Set(IntegerRange(100)) sage: Y = Set(ZZ) sage: X.intersection(Y).is_finite() True sage: Y.intersection(X).is_finite() True sage: Y.intersection(Set(QQ)).is_finite() Traceback (most recent call last): ... NotImplementedError """ if self._X.is_finite(): return True elif self._Y.is_finite(): return True raise NotImplementedError def __richcmp__(self, right, op): r""" Try to compare ``self`` and ``right``. .. NOTE:: Comparison is basically not implemented, or rather it could say sets are not equal even though they are. I don't know how one could implement this for a generic intersection of sets in a meaningful manner. So be careful when using this. EXAMPLES:: sage: Y = Set(ZZ).intersection(Set(QQ)) sage: X = Set(QQ).intersection(Set(ZZ)) sage: X == Y True sage: Y == X True This illustrates that equality testing for formal unions can be misleading in general. :: sage: Set(ZZ).intersection(Set(QQ)) == Set(QQ) False """ if not isinstance(right, Set_generic): return rich_to_bool(op, -1) if not isinstance(right, Set_object_intersection): return rich_to_bool(op, -1) if self._X == right._X and self._Y == right._Y or \ self._X == right._Y and self._Y == right._X: return rich_to_bool(op, 0) return rich_to_bool(op, -1) def __iter__(self): """ Return iterator through elements of ``self``. ``self`` is a formal intersection of `X` and `Y` and this function is implemented by iterating through the elements of `X` and for each checking if it is in `Y`, and if yielding it. EXAMPLES:: sage: X = Set(ZZ).intersection(Primes()) sage: I = X.__iter__() sage: next(I) 2 Check that known finite intersections have finite iterators (see :trac:`18159`):: sage: P = Set(ZZ).intersection(Set(range(10,20))) sage: list(P) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] """ X = self._X Y = self._Y if not self._X.is_finite() and self._Y.is_finite(): X, Y = Y, X for x in X: if x in Y: yield x def __contains__(self, x): """ Return ``True`` if ``self`` contains ``x``. Since ``self`` is a formal intersection of `X` and `Y` this function returns ``True`` if both `X` and `Y` contains ``x``. EXAMPLES:: sage: X = Set(QQ).intersection(Set(RR)) sage: 5 in X True sage: ComplexField().0 in X False Any specific floating-point number in Sage is to finite precision, hence it is rational:: sage: RR(sqrt(2)) in X True Real constants are not rational:: sage: pi in X False """ return x in self._X and x in self._Y @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set(ZZ).intersection(RealSet([3/2, 11/2])); X Set-theoretic intersection of Set of elements of Integer Ring and Set of elements of [3/2, 11/2] sage: X._sympy_() Range(2, 6, 1) """ from sympy import Intersection from sage.interfaces.sympy import sympy_init sympy_init() return Intersection(self._X._sympy_(), self._Y._sympy_()) class Set_object_difference(Set_object_binary): """ Formal difference of two sets. """ def __init__(self, X, Y): r""" Initialize ``self``. EXAMPLES:: sage: S = Set(QQ) sage: T = Set(ZZ) sage: X = S.difference(T); X Set-theoretic difference of Set of elements of Rational Field and Set of elements of Integer Ring sage: latex(X) \Bold{Q} - \Bold{Z} sage: TestSuite(X).run() """ Set_object_binary.__init__(self, X, Y, "difference", "-") def is_finite(self): r""" Return whether this set is finite. EXAMPLES:: sage: X = Set(range(10)) sage: Y = Set(range(-10,5)) sage: Z = Set(QQ) sage: X.difference(Y).is_finite() True sage: X.difference(Z).is_finite() True sage: Z.difference(X).is_finite() False sage: Z.difference(Set(ZZ)).is_finite() Traceback (most recent call last): ... NotImplementedError """ if self._X.is_finite(): return True elif self._Y.is_finite(): return False raise NotImplementedError def __richcmp__(self, right, op): r""" Try to compare ``self`` and ``right``. .. NOTE:: Comparison is basically not implemented, or rather it could say sets are not equal even though they are. I don't know how one could implement this for a generic intersection of sets in a meaningful manner. So be careful when using this. EXAMPLES:: sage: Y = Set(ZZ).difference(Set(QQ)) sage: Y == Set([]) False sage: X = Set(QQ).difference(Set(ZZ)) sage: Y == X False sage: Z = X.difference(Set(ZZ)) sage: Z == X False This illustrates that equality testing for formal unions can be misleading in general. :: sage: X == Set(QQ).difference(Set(ZZ)) True """ if not isinstance(right, Set_generic): return rich_to_bool(op, -1) if not isinstance(right, Set_object_difference): return rich_to_bool(op, -1) if self._X == right._X and self._Y == right._Y: return rich_to_bool(op, 0) return rich_to_bool(op, -1) def __iter__(self): """ Return iterator through elements of ``self``. ``self`` is a formal difference of `X` and `Y` and this function is implemented by iterating through the elements of `X` and for each checking if it is not in `Y`, and if yielding it. EXAMPLES:: sage: X = Set(ZZ).difference(Primes()) sage: I = X.__iter__() sage: next(I) 0 sage: next(I) 1 sage: next(I) -1 sage: next(I) -2 sage: next(I) -3 """ for x in self._X: if x not in self._Y: yield x def __contains__(self, x): """ Return ``True`` if ``self`` contains ``x``. Since ``self`` is a formal intersection of `X` and `Y` this function returns ``True`` if both `X` and `Y` contains ``x``. EXAMPLES:: sage: X = Set(QQ).difference(Set(ZZ)) sage: 5 in X False sage: ComplexField().0 in X False sage: sqrt(2) in X # since sqrt(2) is not a numerical approx False sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is a numerical approx True sage: 5/2 in X True """ return x in self._X and x not in self._Y @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set(QQ).difference(Set(ZZ)); X Set-theoretic difference of Set of elements of Rational Field and Set of elements of Integer Ring sage: X._sympy_() Complement(Rationals, Integers) sage: X = Set(ZZ).difference(Set(QQ)); X Set-theoretic difference of Set of elements of Integer Ring and Set of elements of Rational Field sage: X._sympy_() EmptySet """ from sympy import Complement from sage.interfaces.sympy import sympy_init sympy_init() return Complement(self._X._sympy_(), self._Y._sympy_()) class Set_object_symmetric_difference(Set_object_binary): """ Formal symmetric difference of two sets. """ def __init__(self, X, Y): r""" Initialize ``self``. EXAMPLES:: sage: S = Set(QQ) sage: T = Set(ZZ) sage: X = S.symmetric_difference(T); X Set-theoretic symmetric difference of Set of elements of Rational Field and Set of elements of Integer Ring sage: latex(X) \Bold{Q} \bigtriangleup \Bold{Z} sage: TestSuite(X).run() """ Set_object_binary.__init__(self, X, Y, "symmetric difference", "\\bigtriangleup") def is_finite(self): r""" Return whether this set is finite. EXAMPLES:: sage: X = Set(range(10)) sage: Y = Set(range(-10,5)) sage: Z = Set(QQ) sage: X.symmetric_difference(Y).is_finite() True sage: X.symmetric_difference(Z).is_finite() False sage: Z.symmetric_difference(X).is_finite() False sage: Z.symmetric_difference(Set(ZZ)).is_finite() Traceback (most recent call last): ... NotImplementedError """ if self._X.is_finite(): return self._Y.is_finite() elif self._Y.is_finite(): return False raise NotImplementedError def __richcmp__(self, right, op): r""" Try to compare ``self`` and ``right``. .. NOTE:: Comparison is basically not implemented, or rather it could say sets are not equal even though they are. I don't know how one could implement this for a generic symmetric difference of sets in a meaningful manner. So be careful when using this. EXAMPLES:: sage: Y = Set(ZZ).symmetric_difference(Set(QQ)) sage: X = Set(QQ).symmetric_difference(Set(ZZ)) sage: X == Y True sage: Y == X True """ if not isinstance(right, Set_generic): return rich_to_bool(op, -1) if not isinstance(right, Set_object_symmetric_difference): return rich_to_bool(op, -1) if self._X == right._X and self._Y == right._Y or \ self._X == right._Y and self._Y == right._X: return rich_to_bool(op, 0) return rich_to_bool(op, -1) def __iter__(self): """ Return iterator through elements of ``self``. This function is implemented by first iterating through the elements of `X` and yielding it if it is not in `Y`. Then it will iterate throw all the elements of `Y` and yielding it if it is not in `X`. EXAMPLES:: sage: X = Set(ZZ).symmetric_difference(Primes()) sage: I = X.__iter__() sage: next(I) 0 sage: next(I) 1 sage: next(I) -1 sage: next(I) -2 sage: next(I) -3 """ for x in self._X: if x not in self._Y: yield x for y in self._Y: if y not in self._X: yield y def __contains__(self, x): """ Return ``True`` if ``self`` contains ``x``. Since ``self`` is the formal symmetric difference of `X` and `Y` this function returns ``True`` if either `X` or `Y` (but not both) contains ``x``. EXAMPLES:: sage: X = Set(QQ).symmetric_difference(Primes()) sage: 4 in X True sage: ComplexField().0 in X False sage: sqrt(2) in X # since sqrt(2) is currently symbolic False sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is currently approximated True sage: pi in X False sage: 5/2 in X True sage: 3 in X False """ return ((x in self._X and x not in self._Y) or (x in self._Y and x not in self._X)) @cached_method def _sympy_(self): """ Return an instance of a subclass of SymPy ``Set`` corresponding to ``self``. EXAMPLES:: sage: X = Set(ZZ).symmetric_difference(Set(srange(0, 3, 1/3))); X Set-theoretic symmetric difference of Set of elements of Integer Ring and {0, 1, 2, 1/3, 2/3, 4/3, 5/3, 7/3, 8/3} sage: X._sympy_() Union(Complement(Integers, Set(0, 1, 2, 1/3, 2/3, 4/3, 5/3, 7/3, 8/3)), Complement(Set(0, 1, 2, 1/3, 2/3, 4/3, 5/3, 7/3, 8/3), Integers)) """ from sympy import SymmetricDifference from sage.interfaces.sympy import sympy_init sympy_init() return SymmetricDifference(self._X._sympy_(), self._Y._sympy_())
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/sets/set.py
0.832577
0.477432
set.py
pypi
r""" Check for SageMath Python modules """ from . import PythonModule from .join_feature import JoinFeature class sage__combinat(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.combinat``. EXAMPLES:: sage: from sage.features.sagemath import sage__combinat sage: sage__combinat().is_present() # optional - sage.combinat FeatureTestResult('sage.combinat', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__combinat sage: isinstance(sage__combinat(), sage__combinat) True """ # sage.combinat will be a namespace package. # Testing whether sage.combinat itself can be imported is meaningless. # Hence, we test a Python module within the package. JoinFeature.__init__(self, 'sage.combinat', [PythonModule('sage.combinat.combination')]) class sage__geometry__polyhedron(PythonModule): r""" A :class:`sage.features.Feature` describing the presence of ``sage.geometry.polyhedron``. EXAMPLES:: sage: from sage.features.sagemath import sage__geometry__polyhedron sage: sage__geometry__polyhedron().is_present() # optional - sage.geometry.polyhedron FeatureTestResult('sage.geometry.polyhedron', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__geometry__polyhedron sage: isinstance(sage__geometry__polyhedron(), sage__geometry__polyhedron) True """ PythonModule.__init__(self, 'sage.geometry.polyhedron') class sage__graphs(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.graphs``. EXAMPLES:: sage: from sage.features.sagemath import sage__graphs sage: sage__graphs().is_present() # optional - sage.graphs FeatureTestResult('sage.graphs', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__graphs sage: isinstance(sage__graphs(), sage__graphs) True """ JoinFeature.__init__(self, 'sage.graphs', [PythonModule('sage.graphs.graph')]) class sage__plot(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.plot``. EXAMPLES:: sage: from sage.features.sagemath import sage__plot sage: sage__plot().is_present() # optional - sage.plot FeatureTestResult('sage.plot', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__plot sage: isinstance(sage__plot(), sage__plot) True """ JoinFeature.__init__(self, 'sage.plot', [PythonModule('sage.plot.plot')]) class sage__rings__number_field(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.rings.number_field``. EXAMPLES:: sage: from sage.features.sagemath import sage__rings__number_field sage: sage__rings__number_field().is_present() # optional - sage.rings.number_field FeatureTestResult('sage.rings.number_field', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__rings__number_field sage: isinstance(sage__rings__number_field(), sage__rings__number_field) True """ JoinFeature.__init__(self, 'sage.rings.number_field', [PythonModule('sage.rings.number_field.number_field_element')]) class sage__rings__real_double(PythonModule): r""" A :class:`sage.features.Feature` describing the presence of ``sage.rings.real_double``. EXAMPLES:: sage: from sage.features.sagemath import sage__rings__real_double sage: sage__rings__real_double().is_present() # optional - sage.rings.real_double FeatureTestResult('sage.rings.real_double', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__rings__real_double sage: isinstance(sage__rings__real_double(), sage__rings__real_double) True """ PythonModule.__init__(self, 'sage.rings.real_double') class sage__symbolic(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``sage.symbolic``. EXAMPLES:: sage: from sage.features.sagemath import sage__symbolic sage: sage__symbolic().is_present() # optional - sage.symbolic FeatureTestResult('sage.symbolic', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.sagemath import sage__symbolic sage: isinstance(sage__symbolic(), sage__symbolic) True """ JoinFeature.__init__(self, 'sage.symbolic', [PythonModule('sage.symbolic.expression')], spkg="sagemath_symbolics") def sage_features(logger=None): """ Return features corresponding to parts of the Sage library. These tags are named after Python packages/modules (e.g., :mod:`~sage.symbolic`), not distribution packages (``sagemath-symbolics``). This design is motivated by a separation of concerns: The author of a module that depends on some functionality provided by a Python module usually already knows the name of the Python module, so we do not want to force the author to also know about the distribution package that provides the Python module. Instead, we associate distribution packages to Python modules in :mod:`sage.features.sagemath` via the ``spkg`` parameter of :class:`Feature`. EXAMPLES:: sage: from sage.features.sagemath import sage_features sage: list(sage_features()) # random [Feature('sage.graphs'), Feature('sage.plot'), Feature('sage.rings.number_field'), Feature('sage.rings.real_double')] """ for feature in [sage__combinat(), sage__geometry__polyhedron(), sage__graphs(), sage__plot(), sage__rings__number_field(), sage__rings__real_double(), sage__symbolic()]: result = feature.is_present() if logger: logger.write(f'{result}, reason: {result.reason}\n') if result: yield feature
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/sagemath.py
0.945437
0.55097
sagemath.py
pypi
r""" Testing for CSDP at runtime """ import os import re import subprocess from sage.cpython.string import bytes_to_str from . import Executable, FeatureTestResult class CSDP(Executable): r""" A :class:`sage.features.Feature` which checks for the ``theta`` binary of CSDP. EXAMPLES:: sage: from sage.features.csdp import CSDP sage: CSDP().is_present() # optional: csdp FeatureTestResult('csdp', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.csdp import CSDP sage: isinstance(CSDP(), CSDP) True """ Executable.__init__(self, name="csdp", spkg="csdp", executable="theta", url="https://github.com/dimpase/csdp") def is_functional(self): r""" Check whether ``theta`` works on a trivial example. EXAMPLES:: sage: from sage.features.csdp import CSDP sage: CSDP().is_functional() # optional: csdp FeatureTestResult('csdp', True) """ from sage.misc.temporary_file import tmp_filename tf_name = tmp_filename() with open(tf_name, 'wb') as tf: tf.write("2\n1\n1 1".encode()) with open(os.devnull, 'wb') as devnull: command = ['theta', tf_name] try: lines = subprocess.check_output(command, stderr=devnull) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call to `{command}` failed with exit code {e.returncode}." .format(command=" ".join(command), e=e)) result = bytes_to_str(lines).strip().split('\n')[-1] match = re.match("^The Lovasz Theta Number is (.*)$", result) if match is None: return FeatureTestResult(self, False, reason="Last line of the output of `{command}` did not have the expected format." .format(command=" ".join(command))) return FeatureTestResult(self, True)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/csdp.py
0.743541
0.403978
csdp.py
pypi
from . import Feature, FeatureTestResult from .join_feature import JoinFeature class MIPBackend(Feature): r""" A feature describing whether a :class:`MixedIntegerLinearProgram` backend is available. """ def _is_present(self): r""" Test for the presence of a :class:`MixedIntegerLinearProgram` backend. EXAMPLES:: sage: from sage.features.mip_backends import CPLEX sage: CPLEX()._is_present() # optional - cplex FeatureTestResult('cplex', True) """ try: from sage.numerical.mip import MixedIntegerLinearProgram MixedIntegerLinearProgram(solver=self.name) return FeatureTestResult(self, True) except Exception: return FeatureTestResult(self, False) class CPLEX(MIPBackend): r""" A feature describing whether a :class:`MixedIntegerLinearProgram` backend ``CPLEX`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import CPLEX sage: CPLEX()._is_present() # optional - cplex FeatureTestResult('cplex', True) """ MIPBackend.__init__(self, 'cplex', spkg='sage_numerical_backends_cplex') class Gurobi(MIPBackend): r""" A feature describing whether a :class:`MixedIntegerLinearProgram` backend ``Gurobi`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import Gurobi sage: Gurobi()._is_present() # optional - gurobi FeatureTestResult('gurobi', True) """ MIPBackend.__init__(self, 'gurobi', spkg='sage_numerical_backends_gurobi') class COIN(JoinFeature): r""" A feature describing whether a :class:`MixedIntegerLinearProgram` backend ``COIN`` is available. """ def __init__(self): r""" TESTS:: sage: from sage.features.mip_backends import COIN sage: COIN()._is_present() # optional - sage_numerical_backends_coin FeatureTestResult('sage_numerical_backends_coin', True) """ JoinFeature.__init__(self, 'sage_numerical_backends_coin', [MIPBackend('coin')], spkg='sage_numerical_backends_coin')
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/mip_backends.py
0.870143
0.486575
mip_backends.py
pypi
r""" Checks for FES """ from . import CythonFeature, PythonModule from .join_feature import JoinFeature TEST_CODE = """ # distutils: libraries=fes from libc.stdint cimport uint64_t cdef extern from "<fes_interface.h>": ctypedef int (*solution_callback_t)(void *, uint64_t) void exhaustive_search_wrapper(int n, int n_eqs, int degree, int ***coeffs, solution_callback_t callback, void* callback_state, int verbose) solutions = 0 class InternalState: verbose = False sols = [] max_sols = 0 cdef int report_solution(void *_state, uint64_t i): global solutions solutions += 1 return 0 sig_on() cdef int ***coeffs = <int ***> sig_calloc(1, sizeof(int **)) coeffs[0] = <int **> sig_calloc(3, sizeof(int *)) coeffs[0][0] = <int *> sig_calloc(1, sizeof(int)) coeffs[0][1] = <int *> sig_calloc(2, sizeof(int)) coeffs[0][2] = <int *> sig_calloc(1, sizeof(int)) coeffs[0][2][0] = 1 # x*y = 0 internal_state = InternalState() exhaustive_search_wrapper(2, 1, 2, coeffs, report_solution, <void *>internal_state, 0) sig_free(coeffs[0][2]) sig_free(coeffs[0][1]) sig_free(coeffs[0][0]) sig_free(coeffs[0]) sig_free(coeffs) sig_off() if solutions != 3: raise AssertionError("libFES did not find three solutions for x*y = 0") """ class LibFESLibrary(CythonFeature): r""" A :class:`Feature` which describes whether the FES library is present and functional. EXAMPLES:: sage: from sage.features.fes import LibFESLibrary sage: LibFESLibrary().require() # optional: fes """ def __init__(self): r""" TESTS:: sage: from sage.features.fes import LibFESLibrary sage: isinstance(LibFESLibrary(), LibFESLibrary) True """ CythonFeature.__init__(self, "LibFES", test_code=TEST_CODE, spkg="fes", url="http://www.lifl.fr/~bouillag/fes/") class LibFES(JoinFeature): r""" A :class:`Feature` which describes whether the :mod:`sage.libs.fes` module has been enabled for this build of Sage and is functional. EXAMPLES:: sage: from sage.features.fes import LibFES sage: LibFES().require() # optional: fes """ def __init__(self): r""" TESTS:: sage: from sage.features.fes import LibFES sage: isinstance(LibFES(), LibFES) True """ JoinFeature.__init__(self, 'fes', [PythonModule("sage.libs.fes")], spkg="fes", url="http://www.lifl.fr/~bouillag/fes/")
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/fes.py
0.707304
0.280327
fes.py
pypi
r""" Testing for databases at runtime """ from . import StaticFile, PythonModule from sage.env import ( CONWAY_POLYNOMIALS_DATA_DIR, CREMONA_MINI_DATA_DIR, CREMONA_LARGE_DATA_DIR) class DatabaseConwayPolynomials(StaticFile): r""" A :class:`Feature` which describes the presence of Frank Luebeck's database of Conway polynomials. EXAMPLES:: sage: from sage.features.databases import DatabaseConwayPolynomials sage: DatabaseConwayPolynomials().is_present() FeatureTestResult('conway_polynomials', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseConwayPolynomials sage: isinstance(DatabaseConwayPolynomials(), DatabaseConwayPolynomials) True """ if CONWAY_POLYNOMIALS_DATA_DIR: search_path = [CONWAY_POLYNOMIALS_DATA_DIR] else: search_path = [] StaticFile.__init__(self, "conway_polynomials", filename='conway_polynomials.p', search_path=search_path, spkg='conway_polynomials', description="Frank Luebeck's database of Conway polynomials") CREMONA_DATA_DIRS = set([CREMONA_MINI_DATA_DIR, CREMONA_LARGE_DATA_DIR]) class DatabaseCremona(StaticFile): r""" A :class:`Feature` which describes the presence of John Cremona's database of elliptic curves. INPUT: - ``name`` -- either ``'cremona'`` (the default) for the full large database or ``'cremona_mini'`` for the small database. EXAMPLES:: sage: from sage.features.databases import DatabaseCremona sage: DatabaseCremona('cremona_mini').is_present() FeatureTestResult('database_cremona_mini_ellcurve', True) sage: DatabaseCremona().is_present() # optional: database_cremona_ellcurve FeatureTestResult('database_cremona_ellcurve', True) """ def __init__(self, name="cremona", spkg="database_cremona_ellcurve"): r""" TESTS:: sage: from sage.features.databases import DatabaseCremona sage: isinstance(DatabaseCremona(), DatabaseCremona) True """ StaticFile.__init__(self, f"database_{name}_ellcurve", filename='{}.db'.format(name.replace(' ', '_')), search_path=CREMONA_DATA_DIRS, spkg=spkg, url="https://github.com/JohnCremona/ecdata", description="Cremona's database of elliptic curves") class DatabaseJones(StaticFile): r""" A :class:`Feature` which describes the presence of John Jones's tables of number fields. EXAMPLES:: sage: from sage.features.databases import DatabaseJones sage: bool(DatabaseJones().is_present()) # optional: database_jones_numfield True """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseJones sage: isinstance(DatabaseJones(), DatabaseJones) True """ StaticFile.__init__(self, "database_jones_numfield", filename='jones/jones.sobj', spkg="database_jones_numfield", description="John Jones's tables of number fields") class DatabaseKnotInfo(PythonModule): r""" A :class:`Feature` which describes the presence of the databases at the web-pages `KnotInfo <https://knotinfo.math.indiana.edu/>`__ and `LinkInfo <https://linkinfo.sitehost.iu.edu>`__. EXAMPLES:: sage: from sage.features.databases import DatabaseKnotInfo sage: DatabaseKnotInfo().is_present() # optional: database_knotinfo FeatureTestResult('database_knotinfo', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.databases import DatabaseKnotInfo sage: isinstance(DatabaseKnotInfo(), DatabaseKnotInfo) True """ PythonModule.__init__(self, 'database_knotinfo', spkg='database_knotinfo')
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/databases.py
0.863046
0.542803
databases.py
pypi
r""" Join features """ from . import Feature, FeatureTestResult class JoinFeature(Feature): r""" Join of several :class:`sage.features.Feature` instances. EXAMPLES:: sage: from sage.features import Executable sage: from sage.features.join_feature import JoinFeature sage: F = JoinFeature("shell-boolean", ....: (Executable('shell-true', 'true'), ....: Executable('shell-false', 'false'))) sage: F.is_present() FeatureTestResult('shell-boolean', True) sage: F = JoinFeature("asdfghjkl", ....: (Executable('shell-true', 'true'), ....: Executable('xxyyyy', 'xxyyyy-does-not-exist'))) sage: F.is_present() FeatureTestResult('xxyyyy', False) """ def __init__(self, name, features, spkg=None, url=None, description=None): """ TESTS: The empty join feature is present:: sage: from sage.features.join_feature import JoinFeature sage: JoinFeature("empty", ()).is_present() FeatureTestResult('empty', True) """ if spkg is None: spkgs = set(f.spkg for f in features if f.spkg) if len(spkgs) > 1: raise ValueError('given features have more than one spkg; provide spkg argument') elif len(spkgs) == 1: spkg = next(iter(spkgs)) if url is None: urls = set(f.url for f in features if f.url) if len(urls) > 1: raise ValueError('given features have more than one url; provide url argument') elif len(urls) == 1: url = next(iter(urls)) super().__init__(name, spkg=spkg, url=url, description=description) self._features = features def _is_present(self): r""" Test for the presence of the join feature. EXAMPLES:: sage: from sage.features.latte import Latte sage: Latte()._is_present() # optional - latte_int FeatureTestResult('latte_int', True) """ for f in self._features: test = f._is_present() if not test: return test return FeatureTestResult(self, True) def is_functional(self): r""" Test whether the join feature is functional. EXAMPLES:: sage: from sage.features.latte import Latte sage: Latte().is_functional() # optional - latte_int FeatureTestResult('latte_int', True) """ for f in self._features: test = f.is_functional() if not test: return test return FeatureTestResult(self, True)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/join_feature.py
0.813905
0.420778
join_feature.py
pypi
r""" Check for lrs """ import os import subprocess from . import Executable, FeatureTestResult from sage.cpython.string import str_to_bytes, bytes_to_str class Lrs(Executable): r""" A :class:`sage.features.Feature` describing the presence of the ``lrs`` binary which comes as a part of ``lrslib``. EXAMPLES:: sage: from sage.features.lrs import Lrs sage: Lrs().is_present() # optional: lrslib FeatureTestResult('lrslib', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.lrs import Lrs sage: isinstance(Lrs(), Lrs) True """ Executable.__init__(self, "lrslib", executable="lrs", spkg="lrslib", url="http://cgm.cs.mcgill.ca/~avis/C/lrs.html") def is_functional(self): r""" Test whether ``lrs`` works on a trivial input. EXAMPLES:: sage: from sage.features.lrs import Lrs sage: Lrs().is_functional() # optional: lrslib FeatureTestResult('lrslib', True) """ from sage.misc.temporary_file import tmp_filename tf_name = tmp_filename() with open(tf_name, 'wb') as tf: tf.write(str_to_bytes("V-representation\nbegin\n 1 1 rational\n 1 \nend\nvolume")) devnull = open(os.devnull, 'wb') command = ['lrs', tf_name] try: lines = bytes_to_str(subprocess.check_output(command, stderr=devnull)) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call to `{command}` failed with exit code {e.returncode}.".format(command=" ".join(command), e=e)) expected_list = ["Volume= 1", "Volume=1"] if all(lines.find(expected) == -1 for expected in expected_list): print(lines) return FeatureTestResult(self, False, reason="Output of `{command}` did not contain the expected result {expected}.".format( command=" ".join(command), expected=" or ".join(expected_list))) return FeatureTestResult(self, True)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/lrs.py
0.704465
0.382343
lrs.py
pypi
r""" Check for rubiks """ # **************************************************************************** # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # https://www.gnu.org/licenses/ # **************************************************************************** from . import Executable from .join_feature import JoinFeature class cu2(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``cu2`` EXAMPLES:: sage: from sage.features.rubiks import cu2 sage: cu2().is_present() # optional: rubiks FeatureTestResult('cu2', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import cu2 sage: isinstance(cu2(), cu2) True """ Executable.__init__(self, "cu2", executable="cu2", spkg="rubiks") class size222(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``size222`` EXAMPLES:: sage: from sage.features.rubiks import size222 sage: size222().is_present() # optional: rubiks FeatureTestResult('size222', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import size222 sage: isinstance(size222(), size222) True """ Executable.__init__(self, "size222", executable="size222", spkg="rubiks") class optimal(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``optimal`` EXAMPLES:: sage: from sage.features.rubiks import optimal sage: optimal().is_present() # optional: rubiks FeatureTestResult('optimal', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import optimal sage: isinstance(optimal(), optimal) True """ Executable.__init__(self, "optimal", executable="optimal", spkg="rubiks") class mcube(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``mcube`` EXAMPLES:: sage: from sage.features.rubiks import mcube sage: mcube().is_present() # optional: rubiks FeatureTestResult('mcube', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import mcube sage: isinstance(mcube(), mcube) True """ Executable.__init__(self, "mcube", executable="mcube", spkg="rubiks") class dikcube(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``dikcube`` EXAMPLES:: sage: from sage.features.rubiks import dikcube sage: dikcube().is_present() # optional: rubiks FeatureTestResult('dikcube', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import dikcube sage: isinstance(dikcube(), dikcube) True """ Executable.__init__(self, "dikcube", executable="dikcube", spkg="rubiks") class cubex(Executable): r""" A :class:`sage.features.Executable` describing the presence of ``cubex`` EXAMPLES:: sage: from sage.features.rubiks import cubex sage: cubex().is_present() # optional: rubiks FeatureTestResult('cubex', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import cubex sage: isinstance(cubex(), cubex) True """ Executable.__init__(self, "cubex", executable="cubex", spkg="rubiks") class Rubiks(JoinFeature): r""" A :class:`sage.features.Feature` describing the presence of ``cu2``, ``cubex``, ``dikcube``, ``mcube``, ``optimal``, and ``size222``. EXAMPLES:: sage: from sage.features.rubiks import Rubiks sage: Rubiks().is_present() # optional: rubiks FeatureTestResult('rubiks', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.rubiks import Rubiks sage: isinstance(Rubiks(), Rubiks) True """ JoinFeature.__init__(self, "rubiks", [cu2(), size222(), optimal(), mcube(), dikcube(), cubex()], spkg="rubiks")
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/rubiks.py
0.733261
0.371479
rubiks.py
pypi
r""" Check various graph generator programs """ import os import subprocess from . import Executable, FeatureTestResult class Plantri(Executable): r""" A :class:`sage.features.graph_generators.Feature` which checks for the ``plantri`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Plantri sage: Plantri().is_present() # optional: plantri FeatureTestResult('plantri', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Plantri sage: isinstance(Plantri(), Plantri) True """ Executable.__init__(self, name="plantri", spkg="plantri", executable="plantri", url="http://users.cecs.anu.edu.au/~bdm/plantri/") def is_functional(self): r""" Check whether ``plantri`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Plantri sage: Plantri().is_functional() # optional: plantri FeatureTestResult('plantri', True) """ command = ["plantri", "4"] try: lines = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b"1 triangulations written" if lines.find(expected) == -1: return FeatureTestResult(self, False, reason="Call `{command}` did not produce output which contains `{expected}`".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True) class Buckygen(Executable): r""" A :class:`sage.features.graph_generators.Feature` which checks for the ``buckygen`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Buckygen sage: Buckygen().is_present() # optional: buckygen FeatureTestResult('buckygen', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Buckygen sage: isinstance(Buckygen(), Buckygen) True """ Executable.__init__(self, name="buckygen", spkg="buckygen", executable="buckygen", url="http://caagt.ugent.be/buckygen/") def is_functional(self): r""" Check whether ``buckygen`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Buckygen sage: Buckygen().is_functional() # optional: buckygen FeatureTestResult('buckygen', True) """ command = ["buckygen", "-d", "22d"] try: lines = subprocess.check_output(command, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b"Number of fullerenes generated with 13 vertices: 0" if lines.find(expected) == -1: return FeatureTestResult(self, False, reason="Call `{command}` did not produce output which contains `{expected}`".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True) class Benzene(Executable): r""" A :class:`sage.features.graph_generators.Feature` which checks for the ``benzene`` binary. EXAMPLES:: sage: from sage.features.graph_generators import Benzene sage: Benzene().is_present() # optional: benzene FeatureTestResult('benzene', True) """ def __init__(self): r""" TESTS:: sage: from sage.features.graph_generators import Benzene sage: isinstance(Benzene(), Benzene) True """ Executable.__init__(self, name="benzene", spkg="benzene", executable="benzene", url="http://www.grinvin.org/") def is_functional(self): r""" Check whether ``benzene`` works on trivial input. EXAMPLES:: sage: from sage.features.graph_generators import Benzene sage: Benzene().is_functional() # optional: benzene FeatureTestResult('benzene', True) """ devnull = open(os.devnull, 'wb') command = ["benzene", "2", "p"] try: lines = subprocess.check_output(command, stderr=devnull) except subprocess.CalledProcessError as e: return FeatureTestResult(self, False, reason="Call `{command}` failed with exit code {e.returncode}".format(command=" ".join(command), e=e)) expected = b">>planar_code<<" if not lines.startswith(expected): return FeatureTestResult(self, False, reason="Call `{command}` did not produce output that started with `{expected}`.".format(command=" ".join(command), expected=expected)) return FeatureTestResult(self, True)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/features/graph_generators.py
0.817101
0.449332
graph_generators.py
pypi
"IntegerFactorization objects" from sage.structure.factorization import Factorization from sage.rings.integer_ring import ZZ class IntegerFactorization(Factorization): """ A lightweight class for an ``IntegerFactorization`` object, inheriting from the more general ``Factorization`` class. In the ``Factorization`` class the user has to create a list containing the factorization data, which is then passed to the actual ``Factorization`` object upon initialization. However, for the typical use of integer factorization via the ``Integer.factor()`` method in ``sage.rings.integer`` this is noticeably too much overhead, slowing down the factorization of integers of up to about 40 bits by a factor of around 10. Moreover, the initialization done in the ``Factorization`` class is typically unnecessary: the caller can guarantee that the list contains pairs of an ``Integer`` and an ``int``, as well as that the list is sorted. AUTHOR: - Sebastian Pancratz (2010-01-10) """ def __init__(self, x, unit=None, cr=False, sort=True, simplify=True, unsafe=False): """ Set ``self`` to the factorization object with list ``x``, which must be a sorted list of pairs, where each pair contains a factor and an exponent. If the flag ``unsafe`` is set to ``False`` this method delegates the initialization to the parent class, which means that a rather lenient and careful way of initialization is chosen. For example, elements are coerced or converted into the right parents, multiple occurrences of the same factor are collected (in the commutative case), the list is sorted (unless ``sort`` is ``False``) etc. However, if the flag is set to ``True``, no error handling is carried out. The list ``x`` is assumed to list of pairs. The type of the factors is assumed to be constant across all factors: either ``Integer`` (the generic case) or ``int`` (as supported by the flag ``int_`` of the ``factor()`` method). The type of the exponents is assumed to be ``int``. The list ``x`` itself will be referenced in this factorization object and hence the caller is responsible for not changing the list after creating the factorization. The unit is assumed to be either ``None`` or of type ``Integer``, taking one of the values `+1` or `-1`. EXAMPLES:: sage: factor(15) 3 * 5 We check that :trac:`13139` is fixed:: sage: from sage.structure.factorization_integer import IntegerFactorization sage: IntegerFactorization([(3, 1)], unsafe=True) 3 """ if unsafe: if unit is None: self._Factorization__unit = ZZ._one_element else: self._Factorization__unit = unit self._Factorization__x = x self._Factorization__universe = ZZ self._Factorization__cr = cr if sort: self.sort() if simplify: self.simplify() else: super(IntegerFactorization, self).__init__(x, unit=unit, cr=cr, sort=sort, simplify=simplify) def __sort__(self, key=None): """ Sort the factors in this factorization. INPUT: - ``key`` -- (default: ``None``) comparison key EXAMPLES:: sage: F = factor(15) sage: F.sort(key=lambda x: -x[0]) sage: F 5 * 3 """ if key is not None: self.__x.sort(key=key) else: self.__x.sort()
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/structure/factorization_integer.py
0.918132
0.722967
factorization_integer.py
pypi
import os from sage.misc.temporary_file import tmp_filename from sage.structure.sage_object import SageObject import sage.doctest class Mime(object): TEXT = u'text/plain' HTML = u'text/html' LATEX = u'text/latex' JSON = u'application/json' JAVASCRIPT = u'application/javascript' PDF = u'application/pdf' PNG = u'image/png' JPG = u'image/jpeg' SVG = u'image/svg+xml' JMOL = u'application/jmol' @classmethod def validate(cls, value): """ Check that input is known mime type INPUT: - ``value`` -- string. OUTPUT: Unicode string of that mime type. A ``ValueError`` is raised if input is incorrect / unknown. EXAMPLES:: sage: from sage.structure.graphics_file import Mime sage: Mime.validate('image/png') u'image/png' sage: Mime.validate('foo/bar') Traceback (most recent call last): ... ValueError: unknown mime type """ value = str(value).lower() for k, v in cls.__dict__.items(): if isinstance(v, str) and v == value: return v raise ValueError('unknown mime type') @classmethod def extension(cls, mime_type): """ Return file extension. INPUT: - ``mime_type`` -- mime type as string. OUTPUT: String containing the usual file extension for that type of file. Excludes ``os.extsep``. EXAMPLES:: sage: from sage.structure.graphics_file import Mime sage: Mime.extension('image/png') 'png' """ try: return preferred_filename_ext[mime_type] except KeyError: raise ValueError('no known extension for mime type') preferred_filename_ext = { Mime.TEXT: 'txt', Mime.HTML: 'html', Mime.LATEX: 'tex', Mime.JSON: 'json', Mime.JAVASCRIPT: 'js', Mime.PDF: 'pdf', Mime.PNG: 'png', Mime.JPG: 'jpg', Mime.SVG: 'svg', Mime.JMOL: 'spt.zip', } mimetype_for_ext = dict( (value, key) for (key, value) in preferred_filename_ext.items() ) class GraphicsFile(SageObject): def __init__(self, filename, mime_type=None): """ Wrapper around a graphics file. """ self._filename = filename if mime_type is None: mime_type = self._guess_mime_type(filename) self._mime = Mime.validate(mime_type) def _guess_mime_type(self, filename): """ Guess mime type from file extension """ ext = os.path.splitext(filename)[1] ext = ext.lstrip(os.path.extsep) try: return mimetype_for_ext[ext] except KeyError: raise ValueError('unknown file extension, please specify mime type') def _repr_(self): """ Return a string representation. """ return 'Graphics file {0}'.format(self.mime()) def filename(self): return self._filename def save_as(self, filename): """ Make the file available under a new filename. INPUT: - ``filename`` -- string. The new filename. The newly-created ``filename`` will be a hardlink if possible. If not, an independent copy is created. """ try: os.link(self.filename(), filename) except OSError: import shutil shutil.copy2(self.filename(), filename) def mime(self): return self._mime def data(self): """ Return a byte string containing the image file. """ with open(self._filename, 'rb') as f: return f.read() def launch_viewer(self): """ Launch external viewer for the graphics file. .. note:: Does not actually launch a new process when doctesting. EXAMPLES:: sage: from sage.structure.graphics_file import GraphicsFile sage: g = GraphicsFile('/tmp/test.png', 'image/png') sage: g.launch_viewer() """ if sage.doctest.DOCTEST_MODE: return if self.mime() == Mime.JMOL: return self._launch_jmol() from sage.misc.viewer import viewer command = viewer(preferred_filename_ext[self.mime()]) os.system('{0} {1} 2>/dev/null 1>/dev/null &' .format(command, self.filename())) # TODO: keep track of opened processes... def _launch_jmol(self): launch_script = tmp_filename(ext='.spt') with open(launch_script, 'w') as f: f.write('set defaultdirectory "{0}"\n'.format(self.filename())) f.write('script SCRIPT\n') os.system('jmol {0} 2>/dev/null 1>/dev/null &' .format(launch_script)) def graphics_from_save(save_function, preferred_mime_types, allowed_mime_types=None, figsize=None, dpi=None): """ Helper function to construct a graphics file. INPUT: - ``save_function`` -- callable that can save graphics to a file and accepts options like :meth:`sage.plot.graphics.Graphics.save`. - ``preferred_mime_types`` -- list of mime types. The graphics output mime types in order of preference (i.e. best quality to worst). - ``allowed_mime_types`` -- set of mime types (as strings). The graphics types that we can display. Output, if any, will be one of those. - ``figsize`` -- pair of integers (optional). The desired graphics size in pixels. Suggested, but need not be respected by the output. - ``dpi`` -- integer (optional). The desired resolution in dots per inch. Suggested, but need not be respected by the output. OUTPUT: Return an instance of :class:`sage.structure.graphics_file.GraphicsFile` encapsulating a suitable image file. Image is one of the ``preferred_mime_types``. If ``allowed_mime_types`` is specified, the resulting file format matches one of these. Alternatively, this function can return ``None`` to indicate that textual representation is preferable and/or no graphics with the desired mime type can be generated. """ # Figure out best mime type mime = None if allowed_mime_types is None: mime = Mime.PNG else: # order of preference for m in preferred_mime_types: if m in allowed_mime_types: mime = m break if mime is None: return None # don't know how to generate suitable graphics # Generate suitable temp file filename = tmp_filename(ext=os.path.extsep + Mime.extension(mime)) # Call the save_function with the right arguments kwds = {} if figsize is not None: kwds['figsize'] = figsize if dpi is not None: kwds['dpi'] = dpi save_function(filename, **kwds) return GraphicsFile(filename, mime)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/structure/graphics_file.py
0.525125
0.183612
graphics_file.py
pypi
r""" Precision management for non-exact objects Manage the default precision for non-exact objects such as power series rings or laurent series rings. EXAMPLES:: sage: R.<x> = PowerSeriesRing(QQ) sage: R.default_prec() 20 sage: cos(x) 1 - 1/2*x^2 + 1/24*x^4 - 1/720*x^6 + 1/40320*x^8 - 1/3628800*x^10 + 1/479001600*x^12 - 1/87178291200*x^14 + 1/20922789888000*x^16 - 1/6402373705728000*x^18 + O(x^20) :: sage: R.<x> = PowerSeriesRing(QQ, default_prec=10) sage: R.default_prec() 10 sage: cos(x) 1 - 1/2*x^2 + 1/24*x^4 - 1/720*x^6 + 1/40320*x^8 + O(x^10) .. NOTE:: Subclasses of :class:`Nonexact` which require to change the default precision should implement a method `set_default_prec`. """ from sage.rings.integer import Integer class Nonexact: r""" A non-exact object with default precision. INPUT: - ``prec`` -- a non-negative integer representing the default precision of ``self`` (default: ``20``) """ def __init__(self, prec=20): if prec < 0: raise ValueError(f"prec (= {prec}) must be non-negative") self._default_prec = Integer(prec) def default_prec(self): r""" Return the default precision for ``self``. EXAMPLES:: sage: R = QQ[[x]] sage: R.default_prec() 20 :: sage: R.<x> = PowerSeriesRing(QQ, default_prec=10) sage: R.default_prec() 10 """ try: return self._default_prec except AttributeError: self._default_prec = 20 return self._default_prec def set_default_prec(self, prec): r""" Set the default precision for ``self`` .. WARNING:: This method is outdated. If a subclass of class:`Nonexact` requires this method, please overload it instead. """ # TODO: remove in Sage 9.4 from sage.misc.superseded import deprecation msg = "The method set_default_prec() is deprecated and will be removed " msg += "in a future version of Sage. The default precision is set " msg += "during construction." deprecation(18416, msg) self._default_prec = Integer(prec)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/structure/nonexact.py
0.779783
0.508666
nonexact.py
pypi
def arithmetic(t=None): """ Controls the default proof strategy for integer arithmetic algorithms (such as primality testing). INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires integer arithmetic operations to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows integer arithmetic operations to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the integer arithmetic proof status. EXAMPLES:: sage: proof.arithmetic() True sage: proof.arithmetic(False) sage: proof.arithmetic() False sage: proof.arithmetic(True) sage: proof.arithmetic() True """ from .proof import _proof_prefs return _proof_prefs.arithmetic(t) def elliptic_curve(t=None): """ Controls the default proof strategy for elliptic curve algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires elliptic curve algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows elliptic curve algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current elliptic curve proof status. EXAMPLES:: sage: proof.elliptic_curve() True sage: proof.elliptic_curve(False) sage: proof.elliptic_curve() False sage: proof.elliptic_curve(True) sage: proof.elliptic_curve() True """ from .proof import _proof_prefs return _proof_prefs.elliptic_curve(t) def linear_algebra(t=None): """ Controls the default proof strategy for linear algebra algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires linear algebra algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows linear algebra algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current linear algebra proof status. EXAMPLES:: sage: proof.linear_algebra() True sage: proof.linear_algebra(False) sage: proof.linear_algebra() False sage: proof.linear_algebra(True) sage: proof.linear_algebra() True """ from .proof import _proof_prefs return _proof_prefs.linear_algebra(t) def number_field(t=None): """ Controls the default proof strategy for number field algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires number field algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows number field algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current number field proof status. EXAMPLES:: sage: proof.number_field() True sage: proof.number_field(False) sage: proof.number_field() False sage: proof.number_field(True) sage: proof.number_field() True """ from .proof import _proof_prefs return _proof_prefs.number_field(t) def polynomial(t=None): """ Controls the default proof strategy for polynomial algorithms. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires polynomial algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows polynomial algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current polynomial proof status. EXAMPLES:: sage: proof.polynomial() True sage: proof.polynomial(False) sage: proof.polynomial() False sage: proof.polynomial(True) sage: proof.polynomial() True """ from .proof import _proof_prefs return _proof_prefs.polynomial(t) def all(t=None): """ Controls the default proof strategy throughout Sage. INPUT: t -- boolean or ``None`` OUTPUT: If t is ``True``, requires Sage algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t is ``False``, allows Sage algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is ``None``, returns the current global Sage proof status. EXAMPLES:: sage: proof.all() {'arithmetic': True, 'elliptic_curve': True, 'linear_algebra': True, 'number_field': True, 'other': True, 'polynomial': True} sage: proof.number_field(False) sage: proof.number_field() False sage: proof.all() {'arithmetic': True, 'elliptic_curve': True, 'linear_algebra': True, 'number_field': False, 'other': True, 'polynomial': True} sage: proof.number_field(True) sage: proof.number_field() True """ from .proof import _proof_prefs if t is None: return _proof_prefs._require_proof.copy() for s in _proof_prefs._require_proof: _proof_prefs._require_proof[s] = bool(t) from .proof import WithProof
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/structure/proof/all.py
0.919566
0.865338
all.py
pypi
"Global proof preferences" from sage.structure.sage_object import SageObject class _ProofPref(SageObject): """ An object that holds global proof preferences. For now these are merely True/False flags for various parts of Sage that use probabilistic algorithms. A True flag means that the subsystem (such as linear algebra or number fields) should return results that are true unconditionally: the correctness should not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. A False flag means that the subsystem can use faster methods to return answers that have a very small probability of being wrong. """ def __init__(self, proof = True): self._require_proof = {} self._require_proof["arithmetic"] = proof self._require_proof["elliptic_curve"] = proof self._require_proof["linear_algebra"] = proof self._require_proof["number_field"] = proof self._require_proof["polynomial"] = proof self._require_proof["other"] = proof def arithmetic(self, t = None): """ Controls the default proof strategy for integer arithmetic algorithms (such as primality testing). INPUT: t -- boolean or None OUTPUT: If t == True, requires integer arithmetic operations to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows integer arithmetic operations to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the integer arithmetic proof status. EXAMPLES:: sage: proof.arithmetic() True sage: proof.arithmetic(False) sage: proof.arithmetic() False sage: proof.arithmetic(True) sage: proof.arithmetic() True """ if t is None: return self._require_proof["arithmetic"] self._require_proof["arithmetic"] = bool(t) def elliptic_curve(self, t = None): """ Controls the default proof strategy for elliptic curve algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires elliptic curve algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows elliptic curve algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current elliptic curve proof status. EXAMPLES:: sage: proof.elliptic_curve() True sage: proof.elliptic_curve(False) sage: proof.elliptic_curve() False sage: proof.elliptic_curve(True) sage: proof.elliptic_curve() True """ if t is None: return self._require_proof["elliptic_curve"] self._require_proof["elliptic_curve"] = bool(t) def linear_algebra(self, t = None): """ Controls the default proof strategy for linear algebra algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires linear algebra algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows linear algebra algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current linear algebra proof status. EXAMPLES:: sage: proof.linear_algebra() True sage: proof.linear_algebra(False) sage: proof.linear_algebra() False sage: proof.linear_algebra(True) sage: proof.linear_algebra() True """ if t is None: return self._require_proof["linear_algebra"] self._require_proof["linear_algebra"] = bool(t) def number_field(self, t = None): """ Controls the default proof strategy for number field algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires number field algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows number field algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current number field proof status. EXAMPLES:: sage: proof.number_field() True sage: proof.number_field(False) sage: proof.number_field() False sage: proof.number_field(True) sage: proof.number_field() True """ if t is None: return self._require_proof["number_field"] self._require_proof["number_field"] = bool(t) def polynomial(self, t = None): """ Controls the default proof strategy for polynomial algorithms. INPUT: t -- boolean or None OUTPUT: If t == True, requires polynomial algorithms to (by default) return results that are true unconditionally: the correctness will not depend on an algorithm with a nonzero probability of returning an incorrect answer or on the truth of any unproven conjectures. If t == False, allows polynomial algorithms to (by default) return results that may depend on unproven conjectures or on probabilistic algorithms. Such algorithms often have a substantial speed improvement over those requiring proof. If t is None, returns the current polynomial proof status. EXAMPLES:: sage: proof.polynomial() True sage: proof.polynomial(False) sage: proof.polynomial() False sage: proof.polynomial(True) sage: proof.polynomial() True """ if t is None: return self._require_proof["polynomial"] self._require_proof["polynomial"] = bool(t) _proof_prefs = _ProofPref(True) #Creates the global object that stores proof preferences. def get_flag(t = None, subsystem = None): """ Used for easily determining the correct proof flag to use. EXAMPLES:: sage: from sage.structure.proof.proof import get_flag sage: get_flag(False) False sage: get_flag(True) True sage: get_flag() True sage: proof.all(False) sage: get_flag() False """ if t is None: if subsystem in ["arithmetic", "elliptic_curve", "linear_algebra", "number_field","polynomial"]: return _proof_prefs._require_proof[subsystem] else: return _proof_prefs._require_proof["other"] return t class WithProof(object): """ Use WithProof to temporarily set the value of one of the proof systems for a block of code, with a guarantee that it will be set back to how it was before after the block is done, even if there is an error. EXAMPLES:: sage: proof.arithmetic(True) sage: with proof.WithProof('arithmetic',False): # this would hang "forever" if attempted with proof=True ....: print((10^1000 + 453).is_prime()) ....: print(1/0) Traceback (most recent call last): ... ZeroDivisionError: rational division by zero sage: proof.arithmetic() True """ def __init__(self, subsystem, t): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False); P <sage.structure.proof.proof.WithProof object at ...> sage: P._subsystem 'arithmetic' sage: P._t False sage: P._t_orig True """ self._subsystem = str(subsystem) self._t = bool(t) self._t_orig = _proof_prefs._require_proof[subsystem] def __enter__(self): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False) sage: P.__enter__() sage: proof.arithmetic() False sage: proof.arithmetic(True) """ _proof_prefs._require_proof[self._subsystem] = self._t def __exit__(self, *args): """ TESTS:: sage: proof.arithmetic(True) sage: P = proof.WithProof('arithmetic',False) sage: P.__enter__() sage: proof.arithmetic() False sage: P.__exit__() sage: proof.arithmetic() True """ _proof_prefs._require_proof[self._subsystem] = self._t_orig
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/structure/proof/proof.py
0.899968
0.564819
proof.py
pypi
import unicodedata from sage.structure.sage_object import SageObject class CompoundSymbol(SageObject): def __init__(self, character, top, extension, bottom, middle=None, middle_top=None, middle_bottom=None, top_2=None, bottom_2=None): """ A multi-character (ascii/unicode art) symbol INPUT: Instead of string, each of these can be unicode in Python 2: - ``character`` -- string. The single-line version of the symbol. - ``top`` -- string. The top line of a multi-line symbol. - ``extension`` -- string. The extension line of a multi-line symbol (will be repeated). - ``bottom`` -- string. The bottom line of a multi-line symbol. - ``middle`` -- optional string. The middle part, for example in curly braces. Will be used only once for the symbol, and only if its height is odd. - ``middle_top`` -- optional string. The upper half of the 2-line middle part if the height of the symbol is even. Will be used only once for the symbol. - ``middle_bottom`` -- optional string. The lower half of the 2-line middle part if the height of the symbol is even. Will be used only once for the symbol. - ``top_2`` -- optional string. The upper half of a 2-line symbol. - ``bottom_2`` -- optional string. The lower half of a 2-line symbol. EXAMPLES:: sage: from sage.typeset.symbols import CompoundSymbol sage: i = CompoundSymbol('I', '+', '|', '+', '|') sage: i.print_to_stdout(1) I sage: i.print_to_stdout(3) + | + """ self.character = character self.top = top self.extension = extension self.bottom = bottom self.middle = middle or extension self.middle_top = middle_top or extension self.middle_bottom = middle_bottom or extension self.top_2 = top_2 or top self.bottom_2 = bottom_2 or bottom def _repr_(self): """ Return string representation EXAMPLES:: sage: from sage.typeset.symbols import unicode_left_parenthesis sage: unicode_left_parenthesis multi_line version of "(" """ return u'multi_line version of "{0}"'.format(self.character) def __call__(self, num_lines): r""" Return the lines for a multi-line symbol INPUT: - ``num_lines`` -- integer. The total number of lines. OUTPUT: List of strings / unicode strings. EXAMPLES:: sage: from sage.typeset.symbols import unicode_left_parenthesis sage: unicode_left_parenthesis(4) [u'\u239b', u'\u239c', u'\u239c', u'\u239d'] """ if num_lines <= 0: raise ValueError('number of lines must be positive') elif num_lines == 1: return [self.character] elif num_lines == 2: return [self.top_2, self.bottom_2] elif num_lines == 3: return [self.top, self.middle, self.bottom] elif num_lines % 2 == 0: ext = [self.extension] * ((num_lines - 4) // 2) return [self.top] + ext + [self.middle_top, self.middle_bottom] + ext + [self.bottom] else: # num_lines %2 == 1 ext = [self.extension] * ((num_lines - 3) // 2) return [self.top] + ext + [self.middle] + ext + [self.bottom] def print_to_stdout(self, num_lines): """ Print the multi-line symbol This method is for testing purposes. INPUT: - ``num_lines`` -- integer. The total number of lines. EXAMPLES:: sage: from sage.typeset.symbols import * sage: unicode_integral.print_to_stdout(1) ∫ sage: unicode_integral.print_to_stdout(2) ⌠ ⌡ sage: unicode_integral.print_to_stdout(3) ⌠ ⎮ ⌡ sage: unicode_integral.print_to_stdout(4) ⌠ ⎮ ⎮ ⌡ """ print(u'\n'.join(self(num_lines))) class CompoundAsciiSymbol(CompoundSymbol): def character_art(self, num_lines): """ Return the ASCII art of the symbol EXAMPLES:: sage: from sage.typeset.symbols import * sage: ascii_left_curly_brace.character_art(3) { { { """ from sage.typeset.ascii_art import AsciiArt return AsciiArt(self(num_lines)) class CompoundUnicodeSymbol(CompoundSymbol): def character_art(self, num_lines): """ Return the unicode art of the symbol EXAMPLES:: sage: from sage.typeset.symbols import * sage: unicode_left_curly_brace.character_art(3) ⎧ ⎨ ⎩ """ from sage.typeset.unicode_art import UnicodeArt return UnicodeArt(self(num_lines)) ascii_integral = CompoundAsciiSymbol( 'int', r' /\\', r' | ', r'\\/ ', ) unicode_integral = CompoundUnicodeSymbol( unicodedata.lookup('INTEGRAL'), unicodedata.lookup('TOP HALF INTEGRAL'), unicodedata.lookup('INTEGRAL EXTENSION'), unicodedata.lookup('BOTTOM HALF INTEGRAL'), ) ascii_left_parenthesis = CompoundAsciiSymbol( '(', '(', '(', '(', ) ascii_right_parenthesis = CompoundAsciiSymbol( ')', ')', ')', ')', ) unicode_left_parenthesis = CompoundUnicodeSymbol( unicodedata.lookup('LEFT PARENTHESIS'), unicodedata.lookup('LEFT PARENTHESIS UPPER HOOK'), unicodedata.lookup('LEFT PARENTHESIS EXTENSION'), unicodedata.lookup('LEFT PARENTHESIS LOWER HOOK'), ) unicode_right_parenthesis = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT PARENTHESIS'), unicodedata.lookup('RIGHT PARENTHESIS UPPER HOOK'), unicodedata.lookup('RIGHT PARENTHESIS EXTENSION'), unicodedata.lookup('RIGHT PARENTHESIS LOWER HOOK'), ) ascii_left_square_bracket = CompoundAsciiSymbol( '[', '[', '[', '[', ) ascii_right_square_bracket = CompoundAsciiSymbol( ']', ']', ']', ']', ) unicode_left_square_bracket = CompoundUnicodeSymbol( unicodedata.lookup('LEFT SQUARE BRACKET'), unicodedata.lookup('LEFT SQUARE BRACKET UPPER CORNER'), unicodedata.lookup('LEFT SQUARE BRACKET EXTENSION'), unicodedata.lookup('LEFT SQUARE BRACKET LOWER CORNER'), ) unicode_right_square_bracket = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT SQUARE BRACKET'), unicodedata.lookup('RIGHT SQUARE BRACKET UPPER CORNER'), unicodedata.lookup('RIGHT SQUARE BRACKET EXTENSION'), unicodedata.lookup('RIGHT SQUARE BRACKET LOWER CORNER'), ) ascii_left_curly_brace = CompoundAsciiSymbol( '{', '{', '{', '{', ) ascii_right_curly_brace = CompoundAsciiSymbol( '}', '}', '}', '}', ) unicode_left_curly_brace = CompoundUnicodeSymbol( unicodedata.lookup('LEFT CURLY BRACKET'), unicodedata.lookup('LEFT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('CURLY BRACKET EXTENSION'), unicodedata.lookup('LEFT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('LEFT CURLY BRACKET MIDDLE PIECE'), unicodedata.lookup('RIGHT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('RIGHT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION'), unicodedata.lookup('UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION'), ) unicode_right_curly_brace = CompoundUnicodeSymbol( unicodedata.lookup('RIGHT CURLY BRACKET'), unicodedata.lookup('RIGHT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('CURLY BRACKET EXTENSION'), unicodedata.lookup('RIGHT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('RIGHT CURLY BRACKET MIDDLE PIECE'), unicodedata.lookup('LEFT CURLY BRACKET LOWER HOOK'), unicodedata.lookup('LEFT CURLY BRACKET UPPER HOOK'), unicodedata.lookup('UPPER RIGHT OR LOWER LEFT CURLY BRACKET SECTION'), unicodedata.lookup('UPPER LEFT OR LOWER RIGHT CURLY BRACKET SECTION'), )
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/typeset/symbols.py
0.88173
0.447521
symbols.py
pypi
from sage.rings.integer_ring import ZZ from sage.matrix.constructor import column_matrix, matrix from sage.geometry.cone import Cone class FanNotIsomorphicError(Exception): """ Exception to return if there is no fan isomorphism """ pass def fan_isomorphic_necessary_conditions(fan1, fan2): """ Check necessary (but not sufficient) conditions for the fans to be isomorphic. INPUT: - ``fan1``, ``fan2`` -- two fans. OUTPUT: Boolean. ``False`` if the two fans cannot be isomorphic. ``True`` if the two fans may be isomorphic. EXAMPLES:: sage: fan1 = toric_varieties.P2().fan() sage: fan2 = toric_varieties.dP8().fan() sage: from sage.geometry.fan_isomorphism import fan_isomorphic_necessary_conditions sage: fan_isomorphic_necessary_conditions(fan1, fan2) False """ if fan1.lattice_dim() != fan2.lattice_dim(): return False if fan1.dim() != fan2.dim(): return False if fan1.nrays() != fan2.nrays(): return False if fan1.ngenerating_cones() != fan2.ngenerating_cones(): return False if fan1.is_complete() != fan2.is_complete(): return False return True def fan_isomorphism_generator(fan1, fan2): """ Iterate over the isomorphisms from ``fan1`` to ``fan2``. ALGORITHM: The :meth:`sage.geometry.fan.Fan.vertex_graph` of the two fans is compared. For each graph isomorphism, we attempt to lift it to an actual isomorphism of fans. INPUT: - ``fan1``, ``fan2`` -- two fans. OUTPUT: Yields the fan isomorphisms as matrices acting from the right on rays. EXAMPLES:: sage: fan = toric_varieties.P2().fan() sage: from sage.geometry.fan_isomorphism import fan_isomorphism_generator sage: sorted(fan_isomorphism_generator(fan, fan)) [ [-1 -1] [-1 -1] [ 0 1] [0 1] [ 1 0] [1 0] [ 0 1], [ 1 0], [-1 -1], [1 0], [-1 -1], [0 1] ] sage: m1 = matrix([(1, 0), (0, -5), (-3, 4)]) sage: m2 = matrix([(3, 0), (1, 0), (-2, 1)]) sage: m1.elementary_divisors() == m2.elementary_divisors() == [1,1,0] True sage: fan1 = Fan([Cone([m1*vector([23, 14]), m1*vector([ 3,100])]), ....: Cone([m1*vector([-1,-14]), m1*vector([-100, -5])])]) sage: fan2 = Fan([Cone([m2*vector([23, 14]), m2*vector([ 3,100])]), ....: Cone([m2*vector([-1,-14]), m2*vector([-100, -5])])]) sage: sorted(fan_isomorphism_generator(fan1, fan2)) [ [-12 1 -5] [ -4 0 -1] [ -5 0 -1] ] sage: m0 = identity_matrix(ZZ, 2) sage: m1 = matrix([(1, 0), (0, -5), (-3, 4)]) sage: m2 = matrix([(3, 0), (1, 0), (-2, 1)]) sage: m1.elementary_divisors() == m2.elementary_divisors() == [1,1,0] True sage: fan0 = Fan([Cone([m0*vector([1,0]), m0*vector([1,1])]), ....: Cone([m0*vector([1,1]), m0*vector([0,1])])]) sage: fan1 = Fan([Cone([m1*vector([1,0]), m1*vector([1,1])]), ....: Cone([m1*vector([1,1]), m1*vector([0,1])])]) sage: fan2 = Fan([Cone([m2*vector([1,0]), m2*vector([1,1])]), ....: Cone([m2*vector([1,1]), m2*vector([0,1])])]) sage: sorted(fan_isomorphism_generator(fan0, fan0)) [ [0 1] [1 0] [1 0], [0 1] ] sage: sorted(fan_isomorphism_generator(fan1, fan1)) [ [ -3 -20 28] [1 0 0] [ -1 -4 7] [0 1 0] [ -1 -5 8], [0 0 1] ] sage: sorted(fan_isomorphism_generator(fan1, fan2)) [ [-24 -3 7] [-12 1 -5] [ -7 -1 2] [ -4 0 -1] [ -8 -1 2], [ -5 0 -1] ] sage: sorted(fan_isomorphism_generator(fan2, fan1)) [ [ 0 1 -1] [ 0 1 -1] [ 1 -13 8] [ 2 -8 1] [ 0 -5 4], [ 1 0 -3] ] """ if not fan_isomorphic_necessary_conditions(fan1, fan2): return graph1 = fan1.vertex_graph() graph2 = fan2.vertex_graph() graph_iso = graph1.is_isomorphic(graph2, edge_labels=True, certificate=True) if not graph_iso[0]: return graph_iso = graph_iso[1] # Pick a basis of rays in fan1 max_cone = fan1(fan1.dim())[0] fan1_pivot_rays = max_cone.rays() fan1_basis = fan1_pivot_rays + fan1.virtual_rays() # A QQ-basis for N_1 fan1_pivot_cones = [ fan1.embed(Cone([r])) for r in fan1_pivot_rays ] # The fan2 cones as set(set(ray indices)) fan2_cones = frozenset( frozenset(cone.ambient_ray_indices()) for cone in fan2.generating_cones() ) # iterate over all graph isomorphisms graph1 -> graph2 for perm in graph2.automorphism_group(edge_labels=True): # find a candidate m that maps fan1_basis to the image rays under the graph isomorphism fan2_pivot_cones = [ perm(graph_iso[c]) for c in fan1_pivot_cones ] fan2_pivot_rays = fan2.rays([ c.ambient_ray_indices()[0] for c in fan2_pivot_cones ]) fan2_basis = fan2_pivot_rays + fan2.virtual_rays() try: m = matrix(ZZ, fan1_basis).solve_right(matrix(ZZ, fan2_basis)) m = m.change_ring(ZZ) except (ValueError, TypeError): continue # no solution # check that the candidate m lifts the vertex graph homomorphism graph_image_ray_indices = [ perm(graph_iso[c]).ambient_ray_indices()[0] for c in fan1(1) ] try: matrix_image_ray_indices = [ fan2.rays().index(r*m) for r in fan1.rays() ] except ValueError: continue if graph_image_ray_indices != matrix_image_ray_indices: continue # check that the candidate m maps generating cone to generating cone image_cones = frozenset( # The image(fan1) cones as set(set(integers) frozenset(graph_image_ray_indices[i] for i in cone.ambient_ray_indices()) for cone in fan1.generating_cones() ) if image_cones == fan2_cones: m.set_immutable() yield m def find_isomorphism(fan1, fan2, check=False): """ Find an isomorphism of the two fans. INPUT: - ``fan1``, ``fan2`` -- two fans. - ``check`` -- boolean (default: False). Passed to the fan morphism constructor, see :func:`~sage.geometry.fan_morphism.FanMorphism`. OUTPUT: A fan isomorphism. If the fans are not isomorphic, a :class:`FanNotIsomorphicError` is raised. EXAMPLES:: sage: rays = ((1, 1), (0, 1), (-1, -1), (3, 1)) sage: cones = [(0,1), (1,2), (2,3), (3,0)] sage: fan1 = Fan(cones, rays) sage: m = matrix([[-2,3],[1,-1]]) sage: m.det() == -1 True sage: fan2 = Fan(cones, [vector(r)*m for r in rays]) sage: from sage.geometry.fan_isomorphism import find_isomorphism sage: find_isomorphism(fan1, fan2, check=True) Fan morphism defined by the matrix [-2 3] [ 1 -1] Domain fan: Rational polyhedral fan in 2-d lattice N Codomain fan: Rational polyhedral fan in 2-d lattice N sage: find_isomorphism(fan1, toric_varieties.P2().fan()) Traceback (most recent call last): ... FanNotIsomorphicError sage: fan1 = Fan(cones=[[1,3,4,5],[0,1,2,3],[2,3,4],[0,1,5]], ....: rays=[(-1,-1,0),(-1,-1,3),(-1,1,-1),(-1,3,-1),(0,2,-1),(1,-1,1)]) sage: fan2 = Fan(cones=[[0,2,3,5],[0,1,4,5],[0,1,2],[3,4,5]], ....: rays=[(-1,-1,-1),(-1,-1,0),(-1,1,-1),(0,2,-1),(1,-1,1),(3,-1,-1)]) sage: fan1.is_isomorphic(fan2) True """ generator = fan_isomorphism_generator(fan1, fan2) try: m = next(generator) except StopIteration: raise FanNotIsomorphicError from sage.geometry.fan_morphism import FanMorphism return FanMorphism(m, domain_fan=fan1, codomain=fan2, check=check) def fan_2d_cyclically_ordered_rays(fan): """ Return the rays of a 2-dimensional ``fan`` in cyclic order. INPUT: - ``fan`` -- a 2-dimensional fan. OUTPUT: A :class:`~sage.geometry.point_collection.PointCollection` containing the rays in one particular cyclic order. EXAMPLES:: sage: rays = ((1, 1), (-1, -1), (-1, 1), (1, -1)) sage: cones = [(0,2), (2,1), (1,3), (3,0)] sage: fan = Fan(cones, rays) sage: fan.rays() N( 1, 1), N(-1, -1), N(-1, 1), N( 1, -1) in 2-d lattice N sage: from sage.geometry.fan_isomorphism import fan_2d_cyclically_ordered_rays sage: fan_2d_cyclically_ordered_rays(fan) N(-1, -1), N(-1, 1), N( 1, 1), N( 1, -1) in 2-d lattice N TESTS:: sage: fan = Fan(cones=[], rays=[], lattice=ZZ^2) sage: from sage.geometry.fan_isomorphism import fan_2d_cyclically_ordered_rays sage: fan_2d_cyclically_ordered_rays(fan) Empty collection in Ambient free module of rank 2 over the principal ideal domain Integer Ring """ assert fan.lattice_dim() == 2 import math rays = [ (math.atan2(r[0],r[1]), r) for r in fan.rays() ] rays = [ r[1] for r in sorted(rays) ] from sage.geometry.point_collection import PointCollection return PointCollection(rays, fan.lattice()) def fan_2d_echelon_forms(fan): """ Return echelon forms of all cyclically ordered ray matrices. Note that the echelon form of the ordered ray matrices are unique up to different cyclic orderings. INPUT: - ``fan`` -- a fan. OUTPUT: A set of matrices. The set of all echelon forms for all different cyclic orderings. EXAMPLES:: sage: fan = toric_varieties.P2().fan() sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_forms sage: fan_2d_echelon_forms(fan) frozenset({[ 1 0 -1] [ 0 1 -1]}) sage: fan = toric_varieties.dP7().fan() sage: sorted(fan_2d_echelon_forms(fan)) [ [ 1 0 -1 -1 0] [ 1 0 -1 -1 0] [ 1 0 -1 -1 1] [ 1 0 -1 0 1] [ 0 1 0 -1 -1], [ 0 1 1 0 -1], [ 0 1 1 0 -1], [ 0 1 0 -1 -1], <BLANKLINE> [ 1 0 -1 0 1] [ 0 1 1 -1 -1] ] TESTS:: sage: rays = [(1, 1), (-1, -1), (-1, 1), (1, -1)] sage: cones = [(0,2), (2,1), (1,3), (3,0)] sage: fan1 = Fan(cones, rays) sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_form, fan_2d_echelon_forms sage: echelon_forms = fan_2d_echelon_forms(fan1) sage: S4 = CyclicPermutationGroup(4) sage: rays.reverse() sage: cones = [(3,1), (1,2), (2,0), (0,3)] sage: for i in range(100): ....: m = random_matrix(ZZ,2,2) ....: if abs(det(m)) != 1: continue ....: perm = S4.random_element() ....: perm_cones = [ (perm(c[0]+1)-1, perm(c[1]+1)-1) for c in cones ] ....: perm_rays = [ rays[perm(i+1)-1] for i in range(len(rays)) ] ....: fan2 = Fan(perm_cones, rays=[m*vector(r) for r in perm_rays]) ....: assert fan_2d_echelon_form(fan2) in echelon_forms The trivial case was fixed in :trac:`18613`:: sage: fan = Fan([], lattice=ToricLattice(2)) sage: fan_2d_echelon_forms(fan) frozenset({[]}) sage: parent(list(_)[0]) Full MatrixSpace of 2 by 0 dense matrices over Integer Ring """ if fan.nrays() == 0: return frozenset([fan_2d_echelon_form(fan)]) rays = list(fan_2d_cyclically_ordered_rays(fan)) echelon_forms = [] for i in range(2): for j in range(len(rays)): echelon_forms.append(column_matrix(rays).echelon_form()) first = rays.pop(0) rays.append(first) rays.reverse() return frozenset(echelon_forms) def fan_2d_echelon_form(fan): """ Return echelon form of a cyclically ordered ray matrix. INPUT: - ``fan`` -- a fan. OUTPUT: A matrix. The echelon form of the rays in one particular cyclic order. EXAMPLES:: sage: fan = toric_varieties.P2().fan() sage: from sage.geometry.fan_isomorphism import fan_2d_echelon_form sage: fan_2d_echelon_form(fan) [ 1 0 -1] [ 0 1 -1] """ ray_matrix = fan_2d_cyclically_ordered_rays(fan).column_matrix() return ray_matrix.echelon_form()
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/fan_isomorphism.py
0.69946
0.648828
fan_isomorphism.py
pypi
from sage.graphs.digraph import DiGraph from sage.combinat.posets.lattices import FiniteLatticePoset def lattice_from_incidences(atom_to_coatoms, coatom_to_atoms, face_constructor=None, required_atoms=None, key=None, **kwds): r""" Compute an atomic and coatomic lattice from the incidence between atoms and coatoms. INPUT: - ``atom_to_coatoms`` -- list, ``atom_to_coatom[i]`` should list all coatoms over the ``i``-th atom; - ``coatom_to_atoms`` -- list, ``coatom_to_atom[i]`` should list all atoms under the ``i``-th coatom; - ``face_constructor`` -- function or class taking as the first two arguments sorted :class:`tuple` of integers and any keyword arguments. It will be called to construct a face over atoms passed as the first argument and under coatoms passed as the second argument. Default implementation will just return these two tuples as a tuple; - ``required_atoms`` -- list of atoms (default:None). Each non-empty "face" requires at least one of the specified atoms present. Used to ensure that each face has a vertex. - ``key`` -- any hashable value (default: None). It is passed down to :class:`~sage.combinat.posets.posets.FinitePoset`. - all other keyword arguments will be passed to ``face_constructor`` on each call. OUTPUT: - :class:`finite poset <sage.combinat.posets.posets.FinitePoset>` with elements constructed by ``face_constructor``. .. NOTE:: In addition to the specified partial order, finite posets in Sage have internal total linear order of elements which extends the partial one. This function will try to make this internal order to start with the bottom and atoms in the order corresponding to ``atom_to_coatoms`` and to finish with coatoms in the order corresponding to ``coatom_to_atoms`` and the top. This may not be possible if atoms and coatoms are the same, in which case the preference is given to the first list. ALGORITHM: The detailed description of the used algorithm is given in [KP2002]_. The code of this function follows the pseudo-code description in the section 2.5 of the paper, although it is mostly based on frozen sets instead of sorted lists - this makes the implementation easier and should not cost a big performance penalty. (If one wants to make this function faster, it should be probably written in Cython.) While the title of the paper mentions only polytopes, the algorithm (and the implementation provided here) is applicable to any atomic and coatomic lattice if both incidences are given, see Section 3.4. In particular, this function can be used for strictly convex cones and complete fans. REFERENCES: [KP2002]_ AUTHORS: - Andrey Novoseltsev (2010-05-13) with thanks to Marshall Hampton for the reference. EXAMPLES: Let us construct the lattice of subsets of {0, 1, 2}. Our atoms are {0}, {1}, and {2}, while our coatoms are {0,1}, {0,2}, and {1,2}. Then incidences are :: sage: atom_to_coatoms = [(0,1), (0,2), (1,2)] sage: coatom_to_atoms = [(0,1), (0,2), (1,2)] and we can compute the lattice as :: sage: from sage.geometry.cone import lattice_from_incidences sage: L = lattice_from_incidences( ....: atom_to_coatoms, coatom_to_atoms) sage: L Finite lattice containing 8 elements with distinguished linear extension sage: for level in L.level_sets(): print(level) [((), (0, 1, 2))] [((0,), (0, 1)), ((1,), (0, 2)), ((2,), (1, 2))] [((0, 1), (0,)), ((0, 2), (1,)), ((1, 2), (2,))] [((0, 1, 2), ())] For more involved examples see the *source code* of :meth:`sage.geometry.cone.ConvexRationalPolyhedralCone.face_lattice` and :meth:`sage.geometry.fan.RationalPolyhedralFan._compute_cone_lattice`. """ def default_face_constructor(atoms, coatoms, **kwds): return (atoms, coatoms) if face_constructor is None: face_constructor = default_face_constructor atom_to_coatoms = [frozenset(atc) for atc in atom_to_coatoms] A = frozenset(range(len(atom_to_coatoms))) # All atoms coatom_to_atoms = [frozenset(cta) for cta in coatom_to_atoms] C = frozenset(range(len(coatom_to_atoms))) # All coatoms # Comments with numbers correspond to steps in Section 2.5 of the article L = DiGraph(1) # 3: initialize L faces = {} atoms = frozenset() coatoms = C faces[atoms, coatoms] = 0 next_index = 1 Q = [(atoms, coatoms)] # 4: initialize Q with the empty face while Q: # 5 q_atoms, q_coatoms = Q.pop() # 6: remove some q from Q q = faces[q_atoms, q_coatoms] # 7: compute H = {closure(q+atom) : atom not in atoms of q} H = {} candidates = set(A.difference(q_atoms)) for atom in candidates: coatoms = q_coatoms.intersection(atom_to_coatoms[atom]) atoms = A for coatom in coatoms: atoms = atoms.intersection(coatom_to_atoms[coatom]) H[atom] = (atoms, coatoms) # 8: compute the set G of minimal sets in H minimals = set([]) while candidates: candidate = candidates.pop() atoms = H[candidate][0] if atoms.isdisjoint(candidates) and atoms.isdisjoint(minimals): minimals.add(candidate) # Now G == {H[atom] : atom in minimals} for atom in minimals: # 9: for g in G: g_atoms, g_coatoms = H[atom] if not required_atoms is None: if g_atoms.isdisjoint(required_atoms): continue if (g_atoms, g_coatoms) in faces: g = faces[g_atoms, g_coatoms] else: # 11: if g was newly created g = next_index faces[g_atoms, g_coatoms] = g next_index += 1 Q.append((g_atoms, g_coatoms)) # 12 L.add_edge(q, g) # 14 # End of algorithm, now construct a FiniteLatticePoset. # In principle, it is recommended to use Poset or in this case perhaps # even LatticePoset, but it seems to take several times more time # than the above computation, makes unnecessary copies, and crashes. # So for now we will mimic the relevant code from Poset. # Enumeration of graph vertices must be a linear extension of the poset new_order = L.topological_sort() # Make sure that coatoms are in the end in proper order tail = [faces[atomes, frozenset([coatom])] for coatom, atomes in enumerate(coatom_to_atoms)] tail.append(faces[A, frozenset()]) new_order = [n for n in new_order if n not in tail] + tail # Make sure that atoms are in the beginning in proper order head = [0] # We know that the empty face has index 0 head.extend(faces[frozenset([atom]), coatoms] for atom, coatoms in enumerate(atom_to_coatoms) if required_atoms is None or atom in required_atoms) new_order = head + [n for n in new_order if n not in head] # "Invert" this list to a dictionary labels = {} for new, old in enumerate(new_order): labels[old] = new L.relabel(labels) # Construct the actual poset elements elements = [None] * next_index for face, index in faces.items(): atoms, coatoms = face elements[labels[index]] = face_constructor( tuple(sorted(atoms)), tuple(sorted(coatoms)), **kwds) D = {i: f for i, f in enumerate(elements)} L.relabel(D) return FiniteLatticePoset(L, elements, key=key)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/hasse_diagram.py
0.902554
0.766731
hasse_diagram.py
pypi
from sage.structure.parent import Parent from sage.structure.richcmp import richcmp from sage.structure.element import ModuleElement from sage.structure.unique_representation import UniqueRepresentation from sage.misc.cachefunc import cached_method class LinearExpression(ModuleElement): """ A linear expression. A linear expression is just a linear polynomial in some (fixed) variables. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: m = L([1, 2, 3], 4); m x + 2*y + 3*z + 4 sage: m2 = L([(1, 2, 3), 4]); m2 x + 2*y + 3*z + 4 sage: m3 = L([4, 1, 2, 3]); m3 # note: constant is first in single-tuple notation x + 2*y + 3*z + 4 sage: m == m2 True sage: m2 == m3 True sage: L.zero() 0*x + 0*y + 0*z + 0 sage: a = L([12, 2/3, -1], -2) sage: a - m 11*x - 4/3*y - 4*z - 6 sage: LZ.<x,y,z> = LinearExpressionModule(ZZ) sage: a - LZ([2, -1, 3], 1) 10*x + 5/3*y - 4*z - 3 """ def __init__(self, parent, coefficients, constant, check=True): """ Initialize ``self``. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4) # indirect doctest sage: linear.parent() is L True sage: TestSuite(linear).run() """ super(LinearExpression, self).__init__(parent) self._coeffs = coefficients self._const = constant if check: if self._coeffs.parent() is not self.parent().ambient_module(): raise ValueError("coefficients are not in the ambient module") if not self._coeffs.is_immutable(): raise ValueError("coefficients are not immutable") if self._const.parent() is not self.parent().base_ring(): raise ValueError("the constant is not in the base ring") def A(self): """ Return the coefficient vector. OUTPUT: The coefficient vector of the linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.A() (1, 2, 3) sage: linear.b() 4 """ return self._coeffs def b(self): """ Return the constant term. OUTPUT: The constant term of the linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.A() (1, 2, 3) sage: linear.b() 4 """ return self._const constant_term = b def coefficients(self): """ Return all coefficients. OUTPUT: The constant (as first entry) and coefficients of the linear terms (as subsequent entries) in a list. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4); linear x + 2*y + 3*z + 4 sage: linear.coefficients() [4, 1, 2, 3] """ return [self._const] + list(self._coeffs) dense_coefficient_list = coefficients def monomial_coefficients(self, copy=True): """ Return a dictionary whose keys are indices of basis elements in the support of ``self`` and whose values are the corresponding coefficients. INPUT: - ``copy`` -- ignored EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: linear = L([1, 2, 3], 4) sage: sorted(linear.monomial_coefficients().items(), key=lambda x: str(x[0])) [(0, 1), (1, 2), (2, 3), ('b', 4)] """ zero = self.parent().base_ring().zero() d = {i: v for i, v in enumerate(self._coeffs) if v != zero} if self._const != zero: d['b'] = self._const return d def _repr_vector(self, variable='x'): """ Return a string representation. INPUT: - ``variable`` -- string; the name of the variable vector EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 2, 3], 4)._repr_vector() '(1, 2, 3) x + 4 = 0' sage: L([-1, -2, -3], -4)._repr_vector('u') '(-1, -2, -3) u - 4 = 0' """ atomic_repr = self.parent().base_ring()._repr_option('element_is_atomic') constant = repr(self._const) if not atomic_repr: constant = '({0})'.format(constant) constant = '+ {0}'.format(constant).replace('+ -', '- ') return '{0} {1} {2} = 0'.format(repr(self._coeffs), variable, constant) def _repr_linear(self, include_zero=True, include_constant=True, multiplication='*'): """ Return a representation as a linear polynomial. INPUT: - ``include_zero`` -- whether to include terms with zero coefficient - ``include_constant`` -- whether to include the constant term - ``multiplication`` -- string (optional, default: ``*``); the multiplication symbol to use OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 2, 3], 4)._repr_linear() 'x + 2*y + 3*z + 4' sage: L([-1, -2, -3], -4)._repr_linear() '-x - 2*y - 3*z - 4' sage: L([0, 0, 0], 1)._repr_linear() '0*x + 0*y + 0*z + 1' sage: L([0, 0, 0], 0)._repr_linear() '0*x + 0*y + 0*z + 0' sage: R.<u,v> = QQ[] sage: L.<x,y,z> = LinearExpressionModule(R) sage: L([-u+v+1, -3*u-2, 3], -4*u+v)._repr_linear() '(-u + v + 1)*x + (-3*u - 2)*y + 3*z - 4*u + v' sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L([1, 0, 3], 0)._repr_linear() 'x + 0*y + 3*z + 0' sage: L([1, 0, 3], 0)._repr_linear(include_zero=False) 'x + 3*z' sage: L([1, 0, 3], 1)._repr_linear(include_constant=False, multiplication='.') 'x + 0.y + 3.z' sage: L([1, 0, 3], 1)._repr_linear(include_zero=False, include_constant=False) 'x + 3*z' sage: L([0, 0, 0], 0)._repr_linear(include_zero=False) '0' """ atomic_repr = self.parent().base_ring()._repr_option('element_is_atomic') names = [multiplication + n for n in self.parent()._names] terms = list(zip(self._coeffs, names)) if include_constant: terms += [(self._const, '')] if not include_zero: terms = [t for t in terms if t[0] != 0] if len(terms) == 0: return '0' summands = [] for coeff, name in terms: coeff = str(coeff) if not atomic_repr and name != '' and any(c in coeff for c in ['+', '-']): coeff = '({0})'.format(coeff) summands.append(coeff + name) s = ' ' + ' + '.join(summands) s = s.replace(' + -', ' - ') s = s.replace(' 1' + multiplication, ' ') s = s.replace(' -1' + multiplication, ' -') return s[1:] _repr_ = _repr_linear def _add_(self, other): """ Add two linear expressions. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = L([1, 2, 3], 4) sage: b = L([-1, 3, -3], 0) sage: a + b 0*x + 5*y + 0*z + 4 sage: a - b 2*x - y + 6*z + 4 """ const = self._const + other._const coeffs = self._coeffs + other._coeffs coeffs.set_immutable() return self.__class__(self.parent(), coeffs, const) def _lmul_(self, scalar): """ Multiply a linear expression by a scalar. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = L([1, 2, 3], 4); a x + 2*y + 3*z + 4 sage: 2 * a 2*x + 4*y + 6*z + 8 sage: a * 2 2*x + 4*y + 6*z + 8 sage: -a -x - 2*y - 3*z - 4 sage: RDF(1) * a 1.0*x + 2.0*y + 3.0*z + 4.0 TESTS:: sage: a._lmul_(2) 2*x + 4*y + 6*z + 8 """ const = scalar * self._const coeffs = scalar * self._coeffs coeffs.set_immutable() return self.__class__(self.parent(), coeffs, const) def _acted_upon_(self, scalar, self_on_left): """ Action by scalars that do not live in the base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = x + 2*y + 3*z + 4 sage: a * RDF(3) 3.0*x + 6.0*y + 9.0*z + 12.0 """ base_ring = scalar.base_ring() parent = self.parent().change_ring(base_ring) changed = parent(self) return changed._rmul_(scalar) def change_ring(self, base_ring): """ Change the base ring of this linear expression. INPUT: - ``base_ring`` -- a ring; the new base ring OUTPUT: A new linear expression over the new base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: a = x + 2*y + 3*z + 4; a x + 2*y + 3*z + 4 sage: a.change_ring(RDF) 1.0*x + 2.0*y + 3.0*z + 4.0 """ P = self.parent() if P.base_ring() is base_ring: return self return P.change_ring(base_ring)(self) def __hash__(self): r""" TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: hash(L([0,1])) == hash((1,)) True """ return hash(self._coeffs) ^ hash(self._const) def _richcmp_(self, other, op): """ Compare two linear expressions. INPUT: - ``other`` -- another linear expression (will be enforced by the coercion framework) EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: x == L([0, 1]) True sage: x == x + 1 False sage: M.<x> = LinearExpressionModule(ZZ) sage: L.gen(0) == M.gen(0) # because there is a conversion True sage: L.gen(0) == L(M.gen(0)) # this is the conversion True sage: x == 'test' False """ return richcmp((self._coeffs, self._const), (other._coeffs, other._const), op) def evaluate(self, point): """ Evaluate the linear expression. INPUT: - ``point`` -- list/tuple/iterable of coordinates; the coordinates of a point OUTPUT: The linear expression `Ax + b` evaluated at the point `x`. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y> = LinearExpressionModule(QQ) sage: ex = 2*x + 3* y + 4 sage: ex.evaluate([1,1]) 9 sage: ex([1,1]) # syntactic sugar 9 sage: ex([pi, e]) 2*pi + 3*e + 4 """ try: point = self.parent().ambient_module()(point) except TypeError: from sage.matrix.constructor import vector point = vector(point) return self._coeffs * point + self._const __call__ = evaluate class LinearExpressionModule(Parent, UniqueRepresentation): """ The module of linear expressions. This is the module of linear polynomials which is the parent for linear expressions. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L Module of linear expressions in variables x, y, z over Rational Field sage: L.an_element() x + 0*y + 0*z + 0 """ Element = LinearExpression def __init__(self, base_ring, names=tuple()): """ Initialize ``self``. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: type(L) <class 'sage.geometry.linear_expression.LinearExpressionModule_with_category'> sage: L.base_ring() Rational Field sage: TestSuite(L).run() sage: L = LinearExpressionModule(QQ) sage: TestSuite(L).run() """ from sage.categories.modules import Modules super(LinearExpressionModule, self).__init__(base_ring, category=Modules(base_ring).WithBasis().FiniteDimensional()) self._names = names @cached_method def basis(self): """ Return a basis of ``self``. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: list(L.basis()) [x + 0*y + 0*z + 0, 0*x + y + 0*z + 0, 0*x + 0*y + z + 0, 0*x + 0*y + 0*z + 1] """ from sage.sets.family import Family gens = self.gens() d = {i: g for i, g in enumerate(gens)} d['b'] = self.element_class(self, self.ambient_module().zero(), self.base_ring().one()) return Family(list(range(len(gens))) + ['b'], lambda i: d[i]) @cached_method def ngens(self): """ Return the number of linear variables. OUTPUT: An integer. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ngens() 3 """ return len(self._names) @cached_method def gens(self): """ Return the generators of ``self``. OUTPUT: A tuple of linear expressions, one for each linear variable. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.gens() (x + 0*y + 0*z + 0, 0*x + y + 0*z + 0, 0*x + 0*y + z + 0) """ from sage.matrix.constructor import identity_matrix identity = identity_matrix(self.base_ring(), self.ngens()) return tuple(self(e, 0) for e in identity.rows()) def gen(self, i): """ Return the `i`-th generator. INPUT: - ``i`` -- integer OUTPUT: A linear expression. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.gen(0) x + 0*y + 0*z + 0 """ return self.gens()[i] def _element_constructor_(self, arg0, arg1=None): """ The element constructor. This is part of the Sage parent/element framework. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) Construct from coefficients and constant term:: sage: L._element_constructor_([1, 2, 3], 4) x + 2*y + 3*z + 4 sage: L._element_constructor_(vector(ZZ, [1, 2, 3]), 4) x + 2*y + 3*z + 4 Construct constant linear expression term:: sage: L._element_constructor_(4) 0*x + 0*y + 0*z + 4 Construct from list/tuple/iterable:: sage: L._element_constructor_(vector([4, 1, 2, 3])) x + 2*y + 3*z + 4 Construct from a pair ``(coefficients, constant)``:: sage: L([(1, 2, 3), 4]) x + 2*y + 3*z + 4 Construct from linear expression:: sage: M = LinearExpressionModule(ZZ, ('u', 'v', 'w')) sage: m = M([1, 2, 3], 4) sage: L._element_constructor_(m) x + 2*y + 3*z + 4 """ R = self.base_ring() if arg1 is None: if arg0 in R: const = arg0 coeffs = self.ambient_module().zero() elif isinstance(arg0, LinearExpression): # Construct from linear expression const = arg0.b() coeffs = arg0.A() elif isinstance(arg0, (list, tuple)) and len(arg0) == 2 and isinstance(arg0[0], (list, tuple)): # Construct from pair coeffs = arg0[0] const = arg0[1] else: # Construct from list/tuple/iterable:: try: arg0 = arg0.dense_coefficient_list() except AttributeError: arg0 = list(arg0) const = arg0[0] coeffs = arg0[1:] else: # arg1 is not None, construct from coefficients and constant term coeffs = list(arg0) const = arg1 coeffs = self.ambient_module()(coeffs) coeffs.set_immutable() const = R(const) return self.element_class(self, coeffs, const) def random_element(self): """ Return a random element. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x,y,z> = LinearExpressionModule(QQ) sage: L.random_element() in L True """ A = self.ambient_module().random_element() b = self.base_ring().random_element() return self(A, b) @cached_method def ambient_module(self): """ Return the ambient module. .. SEEALSO:: :meth:`ambient_vector_space` OUTPUT: The domain of the linear expressions as a free module over the base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ambient_module() Vector space of dimension 3 over Rational Field sage: M = LinearExpressionModule(ZZ, ('r', 's')) sage: M.ambient_module() Ambient free module of rank 2 over the principal ideal domain Integer Ring sage: M.ambient_vector_space() Vector space of dimension 2 over Rational Field """ from sage.modules.free_module import FreeModule return FreeModule(self.base_ring(), self.ngens()) @cached_method def ambient_vector_space(self): """ Return the ambient vector space. .. SEEALSO:: :meth:`ambient_module` OUTPUT: The vector space (over the fraction field of the base ring) where the linear expressions live. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L = LinearExpressionModule(QQ, ('x', 'y', 'z')) sage: L.ambient_vector_space() Vector space of dimension 3 over Rational Field sage: M = LinearExpressionModule(ZZ, ('r', 's')) sage: M.ambient_module() Ambient free module of rank 2 over the principal ideal domain Integer Ring sage: M.ambient_vector_space() Vector space of dimension 2 over Rational Field """ from sage.modules.free_module import VectorSpace field = self.base_ring().fraction_field() return VectorSpace(field, self.ngens()) def _coerce_map_from_(self, P): """ Return whether there is a coercion. TESTS:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ) sage: M.<y> = LinearExpressionModule(ZZ) sage: L.coerce_map_from(M) Coercion map: From: Module of linear expressions in variable y over Integer Ring To: Module of linear expressions in variable x over Rational Field sage: M.coerce_map_from(L) sage: M.coerce_map_from(ZZ) Coercion map: From: Integer Ring To: Module of linear expressions in variable y over Integer Ring sage: M.coerce_map_from(QQ) """ if self.base().has_coerce_map_from(P): return True try: return self.ngens() == P.ngens() and \ self.base().has_coerce_map_from(P.base()) except AttributeError: pass return super(LinearExpressionModule, self)._coerce_map_from_(P) def _repr_(self): """ Return a string representation. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ); L Module of linear expressions in variable x over Rational Field """ return 'Module of linear expressions in variable{2} {0} over {1}'.format( ', '.join(self._names), self.base_ring(), 's' if self.ngens() > 1 else '') def change_ring(self, base_ring): """ Return a new module with a changed base ring. INPUT: - ``base_ring`` -- a ring; the new base ring OUTPUT: A new linear expression over the new base ring. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: M.<y> = LinearExpressionModule(ZZ) sage: L = M.change_ring(QQ); L Module of linear expressions in variable y over Rational Field TESTS:: sage: L.change_ring(QQ) is L True """ return LinearExpressionModule(base_ring, self._names)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/linear_expression.py
0.919163
0.626324
linear_expression.py
pypi
from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.structure.element import Element from sage.structure.richcmp import op_EQ, op_NE, op_LE, op_GE, op_LT from sage.misc.cachefunc import cached_method from sage.rings.infinity import Infinity from sage.geometry.polyhedron.constructor import Polyhedron from sage.geometry.polyhedron.base import is_Polyhedron class NewtonPolygon_element(Element): """ Class for infinite Newton polygons with last slope. """ def __init__(self, polyhedron, parent): """ Initialize a Newton polygon. INPUT: - polyhedron -- a polyhedron defining the Newton polygon TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon([ (0,0), (1,1), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) ending by an infinite line of slope 3 :: sage: TestSuite(NewtonPolygon).run() """ Element.__init__(self, parent) self._polyhedron = polyhedron self._vertices = None if polyhedron.is_mutable(): polyhedron._add_dependent_object(self) def _repr_(self): """ Return a string representation of this Newton polygon. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5) sage: NP._repr_() 'Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5)' """ vertices = self.vertices() length = len(vertices) if self.last_slope() is Infinity: if length == 0: return "Empty Newton polygon" elif length == 1: return "Finite Newton polygon with 1 vertex: %s" % str(vertices[0]) else: return "Finite Newton polygon with %s vertices: %s" % (length, str(vertices)[1:-1]) else: if length == 1: return "Newton Polygon consisting of a unique infinite line of slope %s starting at %s" % (self.last_slope(), str(vertices[0])) else: return "Infinite Newton polygon with %s vertices: %s ending by an infinite line of slope %s" % (length, str(vertices)[1:-1], self.last_slope()) def vertices(self, copy=True): """ Returns the list of vertices of this Newton polygon INPUT: - ``copy`` -- a boolean (default: ``True``) OUTPUT: The list of vertices of this Newton polygon (or a copy of it if ``copy`` is set to True) EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5) sage: v = NP.vertices(); v [(0, 0), (1, 1), (2, 5)] TESTS: sage: del v[0] sage: v [(1, 1), (2, 5)] sage: NP.vertices() [(0, 0), (1, 1), (2, 5)] """ if self._vertices is None: self._vertices = [ tuple(v) for v in self._polyhedron.vertices() ] self._vertices.sort() if copy: return list(self._vertices) else: return self._vertices @cached_method def last_slope(self): """ Returns the last (infinite) slope of this Newton polygon if it is infinite and ``+Infinity`` otherwise. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) sage: NP1.last_slope() 3 sage: NP2 = NewtonPolygon([ (0,0), (1,1), (2,5) ]) sage: NP2.last_slope() +Infinity We check that the last slope of a sum (resp. a product) is the minimum of the last slopes of the summands (resp. the factors):: sage: (NP1 + NP2).last_slope() 3 sage: (NP1 * NP2).last_slope() 3 """ rays = self._polyhedron.rays() for r in rays: if r[0] > 0: return r[1]/r[0] return Infinity def slopes(self, repetition=True): """ Returns the slopes of this Newton polygon INPUT: - ``repetition`` -- a boolean (default: ``True``) OUTPUT: The consecutive slopes (not including the last slope if the polygon is infinity) of this Newton polygon. If ``repetition`` is True, each slope is repeated a number of times equal to its length. Otherwise, it appears only one time. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (3,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 6) sage: NP.slopes() [1, 5/2, 5/2] sage: NP.slopes(repetition=False) [1, 5/2] """ slopes = [ ] vertices = self.vertices(copy=False) for i in range(1,len(vertices)): dx = vertices[i][0] - vertices[i-1][0] dy = vertices[i][1] - vertices[i-1][1] slope = dy/dx if repetition: slopes.extend(dx * [slope]) else: slopes.append(slope) return slopes def _add_(self, other): """ Returns the convex hull of ``self`` and ``other`` INPUT: - ``other`` -- a Newton polygon OUTPUT: The Newton polygon, which is the convex hull of this Newton polygon and ``other`` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP1 Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2); NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 3/2) ending by an infinite line of slope 2 sage: NP1 + NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 1) ending by an infinite line of slope 2 """ polyhedron = self._polyhedron.convex_hull(other._polyhedron) return self.parent()(polyhedron) def _mul_(self, other): """ Returns the Minkowski sum of ``self`` and ``other`` INPUT: - ``other`` -- a Newton polygon OUTPUT: The Newton polygon, which is the Minkowski sum of this Newton polygon and ``other``. .. NOTE:: If ``self`` and ``other`` are respective Newton polygons of some polynomials `f` and `g` the self*other is the Newton polygon of the product `fg` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP1 Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2); NP2 Infinite Newton polygon with 2 vertices: (0, 0), (1, 3/2) ending by an infinite line of slope 2 sage: NP = NP1 * NP2; NP Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 5/2) ending by an infinite line of slope 2 The slopes of ``NP`` is the union of those of ``NP1`` and those of ``NP2`` which are less than the last slope:: sage: NP1.slopes() [1, 5] sage: NP2.slopes() [3/2] sage: NP.slopes() [1, 3/2] """ polyhedron = self._polyhedron.minkowski_sum(other._polyhedron) return self.parent()(polyhedron) def __pow__(self, exp, ignored=None): """ Returns ``self`` dilated by ``exp`` INPUT: - ``exp`` -- a positive integer OUTPUT: This Newton polygon scaled by a factor ``exp``. NOTE:: If ``self`` is the Newton polygon of a polynomial `f`, then ``self^exp`` is the Newton polygon of `f^{exp}`. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP^10 Finite Newton polygon with 3 vertices: (0, 0), (10, 10), (20, 60) """ polyhedron = self._polyhedron.dilation(exp) return self.parent()(polyhedron) def __lshift__(self, i): """ Returns ``self`` shifted by `(0,i)` INPUT: - ``i`` -- a rational number OUTPUT: This Newton polygon shifted by the vector `(0,i)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP << 2 Finite Newton polygon with 3 vertices: (0, 2), (1, 3), (2, 8) """ polyhedron = self._polyhedron.translation((0,i)) return self.parent()(polyhedron) def __rshift__(self, i): """ Returns ``self`` shifted by `(0,-i)` INPUT: - ``i`` -- a rational number OUTPUT: This Newton polygon shifted by the vector `(0,-i)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (2, 6) sage: NP >> 2 Finite Newton polygon with 3 vertices: (0, -2), (1, -1), (2, 4) """ polyhedron = self._polyhedron.translation((0,-i)) return self.parent()(polyhedron) def __call__(self, x): """ Returns `self(x)` INPUT: - ``x`` -- a real number OUTPUT: The value of this Newton polygon at abscissa `x` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (3,6) ]); NP Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 6) sage: [ NP(i) for i in range(4) ] [0, 1, 7/2, 6] """ # complexity: O(log(n)) vertices = self.vertices() lastslope = self.last_slope() if len(vertices) == 0 or x < vertices[0][0]: return Infinity if x == vertices[0][0]: return vertices[0][1] if x == vertices[-1][0]: return vertices[-1][1] if x > vertices[-1][0]: return vertices[-1][1] + lastslope * (x - vertices[-1][0]) a = 0 b = len(vertices) while b - a > 1: c = (a + b) // 2 if vertices[c][0] < x: a = c else: b = c xg, yg = vertices[a] xd, yd = vertices[b] return ((x-xg)*yd + (xd-x)*yg) / (xd-xg) def _richcmp_(self, other, op): r""" Comparisons of two Newton polygons. TESTS:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP1 = NewtonPolygon([ (0,0), (1,1), (3,6) ]) sage: NP2 = NewtonPolygon([ (0,0), (1,1), (2,6), (3,6) ]) sage: NP1 == NP2 True sage: NP1 != NP2 False sage: NP1 >= NP1 and NP2 >= NP2 True sage: NP1 > NP1 or NP2 > NP2 False sage: NP1 = NewtonPolygon([ (0,0), (1,1), (2,6) ]) sage: NP2 = NewtonPolygon([ (0,0), (1,3/2) ], last_slope=2) sage: NP3 = NP1 + NP2 sage: NP1 <= NP2 False sage: NP3 <= NP1 True sage: NP3 <= NP2 True sage: NP1 < NP1 False sage: NP1 < NP2 False sage: NP1 >= NP2 False sage: NP1 >= NP3 True sage: NP1 > NP1 False sage: NP1 > NP2 False sage: NP1 >= NP3 and NP2 >= NP3 and NP3 <= NP1 and NP3 <= NP2 True sage: NP1 > NP3 and NP2 > NP3 True sage: NP3 < NP2 and NP3 < NP1 True """ if self._polyhedron == other._polyhedron: return op == op_EQ or op == op_LE or op == op_GE elif op == op_NE: return True elif op == op_EQ: return False if op == op_LT or op == op_LE: if self.last_slope() > other.last_slope(): return False return all(v in self._polyhedron for v in other.vertices()) else: if self.last_slope() < other.last_slope(): return False return all(v in other._polyhedron for v in self.vertices()) def plot(self, **kwargs): """ Plot this Newton polygon. .. NOTE:: All usual rendering options (color, thickness, etc.) are available. EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,6) ]) sage: polygon = NP.plot() # optional - sage.plot """ vertices = self.vertices() if len(vertices) == 0: from sage.plot.graphics import Graphics return Graphics() else: from sage.plot.line import line (xstart,ystart) = vertices[0] (xend,yend) = vertices[-1] if self.last_slope() is Infinity: return line([(xstart, ystart+1), (xstart,ystart+0.5)], linestyle="--", **kwargs) \ + line([(xstart, ystart+0.5)] + vertices + [(xend, yend+0.5)], **kwargs) \ + line([(xend, yend+0.5), (xend, yend+1)], linestyle="--", **kwargs) else: return line([(xstart, ystart+1), (xstart,ystart+0.5)], linestyle="--", **kwargs) \ + line([(xstart, ystart+0.5)] + vertices + [(xend+0.5, yend + 0.5*self.last_slope())], **kwargs) \ + line([(xend+0.5, yend + 0.5*self.last_slope()), (xend+1, yend+self.last_slope())], linestyle="--", **kwargs) def reverse(self, degree=None): r""" Returns the symmetric of ``self`` INPUT: - ``degree`` -- an integer (default: the top right abscissa of this Newton polygon) OUTPUT: The image this Newton polygon under the symmetry '(x,y) \mapsto (degree-x, y)` EXAMPLES:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NP = NewtonPolygon([ (0,0), (1,1), (2,5) ]) sage: NP2 = NP.reverse(); NP2 Finite Newton polygon with 3 vertices: (0, 5), (1, 1), (2, 0) We check that the slopes of the symmetric Newton polygon are the opposites of the slopes of the original Newton polygon:: sage: NP.slopes() [1, 4] sage: NP2.slopes() [-4, -1] """ if self.last_slope() is not Infinity: raise ValueError("Can only reverse *finite* Newton polygons") if degree is None: degree = self.vertices()[-1][0] vertices = [ (degree-x,y) for (x,y) in self.vertices() ] vertices.reverse() parent = self.parent() polyhedron = Polyhedron(base_ring=parent.base_ring(), vertices=vertices, rays=[(0,1)]) return parent(polyhedron) class ParentNewtonPolygon(Parent, UniqueRepresentation): r""" Construct a Newton polygon. INPUT: - ``arg`` -- a list/tuple/iterable of vertices or of slopes. Currently, slopes must be rational numbers. - ``sort_slopes`` -- boolean (default: ``True``). Specifying whether slopes must be first sorted - ``last_slope`` -- rational or infinity (default: ``Infinity``). The last slope of the Newton polygon OUTPUT: The corresponding Newton polygon. .. note:: By convention, a Newton polygon always contains the point at infinity `(0, \infty)`. These polygons are attached to polynomials or series over discrete valuation rings (e.g. padics). EXAMPLES: We specify here a Newton polygon by its vertices:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon([ (0,0), (1,1), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) We note that the convex hull of the vertices is automatically computed:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ]) Finite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) Note that the value ``+Infinity`` is allowed as the second coordinate of a vertex:: sage: NewtonPolygon([ (0,0), (1,Infinity), (2,8), (3,5) ]) Finite Newton polygon with 2 vertices: (0, 0), (3, 5) If last_slope is set, the returned Newton polygon is infinite and ends with an infinite line having the specified slope:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3) Infinite Newton polygon with 3 vertices: (0, 0), (1, 1), (3, 5) ending by an infinite line of slope 3 Specifying a last slope may discard some vertices:: sage: NewtonPolygon([ (0,0), (1,1), (2,8), (3,5) ], last_slope=3/2) Infinite Newton polygon with 2 vertices: (0, 0), (1, 1) ending by an infinite line of slope 3/2 Next, we define a Newton polygon by its slopes:: sage: NP = NewtonPolygon([0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1]) sage: NP Finite Newton polygon with 5 vertices: (0, 0), (1, 0), (3, 1), (6, 3), (8, 5) sage: NP.slopes() [0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1] By default, slopes are automatically sorted:: sage: NP2 = NewtonPolygon([0, 1, 1/2, 2/3, 1/2, 2/3, 1, 2/3]) sage: NP2 Finite Newton polygon with 5 vertices: (0, 0), (1, 0), (3, 1), (6, 3), (8, 5) sage: NP == NP2 True except if the contrary is explicitly mentioned:: sage: NewtonPolygon([0, 1, 1/2, 2/3, 1/2, 2/3, 1, 2/3], sort_slopes=False) Finite Newton polygon with 4 vertices: (0, 0), (1, 0), (6, 10/3), (8, 5) Slopes greater that or equal last_slope (if specified) are discarded:: sage: NP = NewtonPolygon([0, 1/2, 1/2, 2/3, 2/3, 2/3, 1, 1], last_slope=2/3) sage: NP Infinite Newton polygon with 3 vertices: (0, 0), (1, 0), (3, 1) ending by an infinite line of slope 2/3 sage: NP.slopes() [0, 1/2, 1/2] Be careful, do not confuse Newton polygons provided by this class with Newton polytopes. Compare:: sage: NP = NewtonPolygon([ (0,0), (1,45), (3,6) ]); NP Finite Newton polygon with 2 vertices: (0, 0), (3, 6) sage: x, y = polygen(QQ,'x, y') sage: p = 1 + x*y**45 + x**3*y**6 sage: p.newton_polytope() A 2-dimensional polyhedron in ZZ^2 defined as the convex hull of 3 vertices sage: p.newton_polytope().vertices() (A vertex at (0, 0), A vertex at (1, 45), A vertex at (3, 6)) """ Element = NewtonPolygon_element def __init__(self): """ Parent class for all Newton polygons. sage: from sage.geometry.newton_polygon import ParentNewtonPolygon sage: ParentNewtonPolygon() Parent for Newton polygons TESTS: This class is a singleton. sage: ParentNewtonPolygon() is ParentNewtonPolygon() True :: sage: TestSuite(ParentNewtonPolygon()).run() """ from sage.categories.semirings import Semirings from sage.rings.rational_field import QQ Parent.__init__(self, category=Semirings(), base=QQ) def _repr_(self): """ Returns the string representation of this parent, which is ``Parent for Newton polygons`` TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon Parent for Newton polygons sage: NewtonPolygon._repr_() 'Parent for Newton polygons' """ return "Parent for Newton polygons" def _an_element_(self): """ Returns a Newton polygon (which is the empty one) TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon._an_element_() Empty Newton polygon """ return self(Polyhedron(base_ring=self.base_ring(), ambient_dim=2)) def _element_constructor_(self, arg, sort_slopes=True, last_slope=Infinity): r""" INPUT: - ``arg`` -- an argument describing the Newton polygon - ``sort_slopes`` -- boolean (default: ``True``). Specifying whether slopes must be first sorted - ``last_slope`` -- rational or infinity (default: ``Infinity``). The last slope of the Newton polygon The first argument ``arg`` can be either: - a polyhedron in `\QQ^2` - the element ``0`` (corresponding to the empty Newton polygon) - the element ``1`` (corresponding to the Newton polygon of the constant polynomial equal to 1) - a list/tuple/iterable of vertices - a list/tuple/iterable of slopes OUTPUT: The corresponding Newton polygon. For more informations, see :class:`ParentNewtonPolygon`. TESTS: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: NewtonPolygon(0) Empty Newton polygon sage: NewtonPolygon(1) Finite Newton polygon with 1 vertex: (0, 0) """ if is_Polyhedron(arg): return self.element_class(arg, parent=self) if arg == 0: polyhedron = Polyhedron(base_ring=self.base_ring(), ambient_dim=2) return self.element_class(polyhedron, parent=self) if arg == 1: polyhedron = Polyhedron(base_ring=self.base_ring(), vertices=[(0,0)], rays=[(0,1)]) return self.element_class(polyhedron, parent=self) if not isinstance(arg, list): try: arg = list(arg) except TypeError: raise TypeError("argument must be a list of coordinates or a list of (rational) slopes") if arg and arg[0] in self.base_ring(): if sort_slopes: arg.sort() x = y = 0 vertices = [(x, y)] for slope in arg: if not slope in self.base_ring(): raise TypeError("argument must be a list of coordinates or a list of (rational) slopes") x += 1 y += slope vertices.append((x, y)) else: vertices = [(x, y) for (x, y) in arg if y is not Infinity] if len(vertices) == 0: polyhedron = Polyhedron(base_ring=self.base_ring(), ambient_dim=2) else: rays = [(0, 1)] if last_slope is not Infinity: rays.append((1, last_slope)) polyhedron = Polyhedron(base_ring=self.base_ring(), vertices=vertices, rays=rays) return self.element_class(polyhedron, parent=self) NewtonPolygon = ParentNewtonPolygon()
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/newton_polygon.py
0.944836
0.541227
newton_polygon.py
pypi
from sage.structure.sage_object import SageObject from sage.matrix.constructor import vector class AffineSubspace(SageObject): """ An affine subspace. INPUT: - ``p`` -- list/tuple/iterable representing a point on the affine space - ``V`` -- vector subspace OUTPUT: Affine subspace parallel to ``V`` and passing through ``p``. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: a Affine space p + W where: p = (1, 0, 0, 0) W = Vector space of dimension 4 over Rational Field """ def __init__(self, p, V): r""" Construct an :class:`AffineSubspace`. TESTS:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: TestSuite(a).run() sage: AffineSubspace(0, VectorSpace(QQ,4)).point() (0, 0, 0, 0) """ R = V.base_ring() from sage.categories.fields import Fields if R not in Fields(): R = R.fraction_field() V = V.change_ring(R) self._base_ring = R self._linear_part = V p = V.ambient_vector_space()(p) p.set_immutable() self._point = p def __hash__(self): """ Return a hash value. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0], VectorSpace(QQ,4)) sage: a.__hash__() # random output -3713096828371451969 """ # note that the point is not canonically chosen, but the linear part is return hash(self._linear_part) def _repr_(self): r""" String representation for an :class:`AffineSubspace`. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0],VectorSpace(QQ,4)) sage: a Affine space p + W where: p = (1, 0, 0, 0) W = Vector space of dimension 4 over Rational Field """ return "Affine space p + W where:\n p = "+str(self._point)+"\n W = "+str(self._linear_part) def __eq__(self, other): r""" Test whether ``self`` is equal to ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0], matrix([[1,0,0]]).right_kernel()) sage: b = AffineSubspace([2,0,0], matrix([[1,0,0]]).right_kernel()) sage: c = AffineSubspace([1,1,0], matrix([[1,0,0]]).right_kernel()) sage: a == b False sage: a == c True """ V = self._linear_part W = other._linear_part return V == W and self._point - other._point in V def __ne__(self, other): r""" Test whether ``self`` is not equal to ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0],matrix([[1,0,0]]).right_kernel()) sage: b = AffineSubspace([2,0,0],matrix([[1,0,0]]).right_kernel()) sage: a == b False sage: a != b True sage: a != a False """ return not self == other def __le__(self, other): r""" Test whether ``self`` is an affine subspace of ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ, 3) sage: W1 = V.subspace([[1,0,0],[0,1,0]]) sage: W2 = V.subspace([[1,0,0]]) sage: a = AffineSubspace([1,2,3], W1) sage: b = AffineSubspace([1,2,3], W2) sage: a <= b False sage: a <= a True sage: b <= a True """ V = self._linear_part W = other._linear_part return V.is_subspace(W) and self._point-other._point in W def __lt__(self, other): r""" Test whether ``self`` is a proper affine subspace of ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ, 3) sage: W1 = V.subspace([[1,0,0], [0,1,0]]) sage: W2 = V.subspace([[1,0,0]]) sage: a = AffineSubspace([1,2,3], W1) sage: b = AffineSubspace([1,2,3], W2) sage: a < b False sage: a < a False sage: b < a True """ if self._linear_part == other._linear_part: return False return self <= other def __contains__(self, q): r""" Test whether the point ``q`` is in the affine space. INPUT: - ``q`` -- point as a list/tuple/iterable OUTPUT: A boolean. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0], matrix([[1,0,0]]).right_kernel()) sage: (1,1,0) in a True sage: (0,0,0) in a False """ q = vector(self._base_ring, q) return self._point - q in self._linear_part def linear_part(self): r""" Return the linear part of the affine space. OUTPUT: A vector subspace of the ambient space. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: A = AffineSubspace([2,3,1], matrix(QQ, [[1,2,3]]).right_kernel()) sage: A.linear_part() Vector space of degree 3 and dimension 2 over Rational Field Basis matrix: [ 1 0 -1/3] [ 0 1 -2/3] sage: A.linear_part().ambient_vector_space() Vector space of dimension 3 over Rational Field """ return self._linear_part def point(self): r""" Return a point ``p`` in the affine space. OUTPUT: A point of the affine space as a vector in the ambient space. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: A = AffineSubspace([2,3,1], VectorSpace(QQ,3)) sage: A.point() (2, 3, 1) """ return self._point def dimension(self): r""" Return the dimension of the affine space. OUTPUT: An integer. EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: a = AffineSubspace([1,0,0,0],VectorSpace(QQ,4)) sage: a.dimension() 4 """ return self.linear_part().dimension() def intersection(self, other): r""" Return the intersection of ``self`` with ``other``. INPUT: - ``other`` -- an :class:`AffineSubspace` OUTPUT: A new affine subspace, (or ``None`` if the intersection is empty). EXAMPLES:: sage: from sage.geometry.hyperplane_arrangement.affine_subspace import AffineSubspace sage: V = VectorSpace(QQ,3) sage: U = V.subspace([(1,0,0), (0,1,0)]) sage: W = V.subspace([(0,1,0), (0,0,1)]) sage: A = AffineSubspace((0,0,0), U) sage: B = AffineSubspace((1,1,1), W) sage: A.intersection(B) Affine space p + W where: p = (1, 1, 0) W = Vector space of degree 3 and dimension 1 over Rational Field Basis matrix: [0 1 0] sage: C = AffineSubspace((0,0,1), U) sage: A.intersection(C) sage: C = AffineSubspace((7,8,9), U.complement()) sage: A.intersection(C) Affine space p + W where: p = (7, 8, 0) W = Vector space of degree 3 and dimension 0 over Rational Field Basis matrix: [] sage: A.intersection(C).intersection(B) sage: D = AffineSubspace([1,2,3], VectorSpace(GF(5),3)) sage: E = AffineSubspace([3,4,5], VectorSpace(GF(5),3)) sage: D.intersection(E) Affine space p + W where: p = (3, 4, 0) W = Vector space of dimension 3 over Finite Field of size 5 """ if self.linear_part().ambient_vector_space() != \ other.linear_part().ambient_vector_space(): raise ValueError('incompatible ambient vector spaces') m = self.linear_part().matrix() n = other.linear_part().matrix() p = self.point() q = other.point() M = m.stack(n) v = q - p try: t = M.solve_left(v) except ValueError: return None # empty intersection new_p = p + t[:m.nrows()]*m new_V = self.linear_part().intersection(other._linear_part) return AffineSubspace(new_p, new_V)
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/hyperplane_arrangement/affine_subspace.py
0.94651
0.628336
affine_subspace.py
pypi
from copy import copy from colorsys import hsv_to_rgb from sage.plot.plot3d.parametric_plot3d import parametric_plot3d from sage.plot.plot3d.shapes2 import text3d from sage.plot.graphics import Graphics from sage.plot.line import line from sage.plot.text import text from sage.plot.point import point from sage.plot.plot import parametric_plot from sage.symbolic.ring import SR def plot(hyperplane_arrangement, **kwds): r""" Return a plot of the hyperplane arrangement. If the arrangement is in 4 dimensions but inessential, a plot of the essentialization is returned. .. NOTE:: This function is available as the :meth:`~sage.geometry.hyperplane_arrangement.arrangement.HyperplaneArrangementElement.plot` method of hyperplane arrangements. You should not call this function directly, only through the method. INPUT: - ``hyperplane_arrangement`` -- the hyperplane arrangement to plot - ``**kwds`` -- plot options: see :mod:`sage.geometry.hyperplane_arrangement.plot`. OUTPUT: A graphics object of the plot. EXAMPLES:: sage: B = hyperplane_arrangements.semiorder(4) sage: B.plot() # optional - sage.plot Displaying the essentialization. Graphics3d Object """ N = len(hyperplane_arrangement) dim = hyperplane_arrangement.dimension() if hyperplane_arrangement.base_ring().characteristic() != 0: raise NotImplementedError('must be a field of characteristic 0') elif dim == 4: if not hyperplane_arrangement.is_essential(): print('Displaying the essentialization.') hyperplane_arrangement = hyperplane_arrangement.essentialization() elif dim not in [1,2,3]: # revise to handle 4d return # silently # handle extra keywords if 'hyperplane_colors' in kwds: hyp_colors = kwds.pop('hyperplane_colors') if not isinstance(hyp_colors, list): # we assume its a single color then hyp_colors = [hyp_colors] * N else: HSV_tuples = [(i*1.0/N, 0.8, 0.9) for i in range(N)] hyp_colors = [hsv_to_rgb(*x) for x in HSV_tuples] if 'hyperplane_labels' in kwds: hyp_labels = kwds.pop('hyperplane_labels') has_hyp_label = True if not isinstance(hyp_labels, list): # we assume its a boolean then hyp_labels = [hyp_labels] * N relabeled = [] for i in range(N): if hyp_labels[i] in [True,'long']: relabeled.append(True) else: relabeled.append(str(i)) hyp_labels = relabeled else: has_hyp_label = False if 'label_colors' in kwds: label_colors = kwds.pop('label_colors') has_label_color = True if not isinstance(label_colors, list): # we assume its a single color then label_colors = [label_colors] * N else: has_label_color = False if 'label_fontsize' in kwds: label_fontsize = kwds.pop('label_fontsize') has_label_fontsize = True if not isinstance(label_fontsize, list): # we assume its a single size then label_fontsize = [label_fontsize] * N else: has_label_fontsize = False if 'label_offsets' in kwds: has_offsets = True offsets = kwds.pop('label_offsets') else: has_offsets = False # give default values below hyperplane_legend = kwds.pop('hyperplane_legend', 'long' if dim < 3 else False) if 'hyperplane_opacities' in kwds: hyperplane_opacities = kwds.pop('hyperplane_opacities') has_opacity = True if not isinstance(hyperplane_opacities, list): # we assume a single number then hyperplane_opacities = [hyperplane_opacities] * N else: has_opacity = False point_sizes = kwds.pop('point_sizes', 50) if not isinstance(point_sizes, list): point_sizes = [point_sizes] * N if 'ranges' in kwds: ranges_set = True ranges = kwds.pop('ranges') if not type(ranges) in [list,tuple]: # ranges is a single number ranges = [ranges] * N # So ranges is some type of list. elif dim == 2: # arrangement of lines in the plane if not type(ranges[0]) in [list,tuple]: # a single interval ranges = [ranges] * N elif dim == 3: # arrangement of planes in 3-space if not type(ranges[0][0]) in [list,tuple]: ranges = [ranges] * N elif dim not in [2,3]: # ranges is not an option unless dim is 2 or 3 ranges_set = False else: # a list of intervals, one for each hyperplane is given pass # ranges does not need to be modified else: ranges_set = False # give default values below # the extra keywords have now been handled # now handle the legend if dim in [1,2]: # points on a line or lines in the plane if hyperplane_legend in [True,'long']: hyps = hyperplane_arrangement.hyperplanes() legend_labels = [hyps[i]._latex_() for i in range(N)] elif hyperplane_legend == 'short' : legend_labels = [str(i) for i in range(N)] else: # dim==3, arrangement of planes in 3-space if hyperplane_legend in [True, 'long']: legend3d = legend_3d(hyperplane_arrangement, hyp_colors, 'long') elif hyperplane_legend == 'short': legend3d = legend_3d(hyperplane_arrangement, hyp_colors, 'short') ## done handling the legend ## now create the plot p = Graphics() for i in range(N): newk = copy(kwds) if has_hyp_label: newk['hyperplane_label'] = hyp_labels[i] if has_offsets: if not isinstance(offsets, list): newk['label_offset'] = offsets else: newk['label_offset'] = offsets[i] else: newk['hyperplane_label'] = False if has_label_color: newk['label_color'] = label_colors[i] if has_label_fontsize: newk['label_fontsize'] = label_fontsize[i] if has_opacity: newk['opacity'] = hyperplane_opacities[i] if dim == 1: newk['point_size'] = point_sizes[i] if dim in [1,2] and hyperplane_legend: # more options than T/F newk['legend_label'] = legend_labels[i] if ranges_set: newk['ranges'] = ranges[i] p += plot_hyperplane(hyperplane_arrangement[i], rgbcolor=hyp_colors[i], **newk) if dim == 1: if hyperplane_legend: # there are more options than T/F p.legend(True) return p elif dim == 2: if hyperplane_legend: # there are more options than T/F p.legend(True) return p else: # dim==3 if hyperplane_legend: # there are more options than T/F return p, legend3d else: return p def plot_hyperplane(hyperplane, **kwds): r""" Return the plot of a single hyperplane. INPUT: - ``**kwds`` -- plot options: see below OUTPUT: A graphics object of the plot. .. RUBRIC:: Plot Options Beside the usual plot options (enter ``plot?``), the plot command for hyperplanes includes the following: - ``hyperplane_label`` -- Boolean value or string (default: ``True``). If ``True``, the hyperplane is labeled with its equation, if a string, it is labeled by that string, otherwise it is not labeled. - ``label_color`` -- (Default: ``'black'``) Color for hyperplane_label. - ``label_fontsize`` -- Size for ``hyperplane_label`` font (default: 14) (does not work in 3d, yet). - ``label_offset`` -- (Default: 0-dim: 0.1, 1-dim: (0,1), 2-dim: (0,0,0.2)) Amount by which label is offset from ``hyperplane.point()``. - ``point_size`` -- (Default: 50) Size of points in a zero-dimensional arrangement or of an arrangement over a finite field. - ``ranges`` -- Range for the parameters for the parametric plot of the hyperplane. If a single positive number ``r`` is given for the value of ``ranges``, then the ranges for all parameters are set to `[-r, r]`. Otherwise, for a line in the plane, ``ranges`` has the form ``[a, b]`` (default: [-3,3]), and for a plane in 3-space, the ``ranges`` has the form ``[[a, b], [c, d]]`` (default: [[-3,3],[-3,3]]). (The ranges are centered around ``hyperplane.point()``.) EXAMPLES:: sage: H1.<x> = HyperplaneArrangements(QQ) sage: a = 3*x + 4 sage: a.plot() # indirect doctest # optional - sage.plot Graphics object consisting of 3 graphics primitives sage: a.plot(point_size=100,hyperplane_label='hello') # optional - sage.plot Graphics object consisting of 3 graphics primitives sage: H2.<x,y> = HyperplaneArrangements(QQ) sage: b = 3*x + 4*y + 5 sage: b.plot() # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: b.plot(ranges=(1,5),label_offset=(2,-1)) # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: opts = {'hyperplane_label':True, 'label_color':'green', ....: 'label_fontsize':24, 'label_offset':(0,1.5)} sage: b.plot(**opts) # optional - sage.plot Graphics object consisting of 2 graphics primitives sage: H3.<x,y,z> = HyperplaneArrangements(QQ) sage: c = 2*x + 3*y + 4*z + 5 sage: c.plot() # optional - sage.plot Graphics3d Object sage: c.plot(label_offset=(1,0,1), color='green', label_color='red', frame=False) # optional - sage.plot Graphics3d Object sage: d = -3*x + 2*y + 2*z + 3 sage: d.plot(opacity=0.8) # optional - sage.plot Graphics3d Object sage: e = 4*x + 2*z + 3 sage: e.plot(ranges=[[-1,1],[0,8]], label_offset=(2,2,1), aspect_ratio=1) # optional - sage.plot Graphics3d Object """ if hyperplane.base_ring().characteristic(): raise NotImplementedError('base field must have characteristic zero') elif hyperplane.dimension() not in [0, 1, 2]: # dimension of hyperplane, not ambient space raise ValueError('can only plot hyperplanes in dimensions 1, 2, 3') # handle extra keywords if 'hyperplane_label' in kwds: hyp_label = kwds.pop('hyperplane_label') if not hyp_label: has_hyp_label = False else: has_hyp_label = True else: # default hyp_label = True has_hyp_label = True if has_hyp_label: if hyp_label: # then label hyperplane with its equation if hyperplane.dimension() == 2: # jmol does not like latex label = hyperplane._repr_linear(include_zero=False) else: label = hyperplane._latex_() else: label = hyp_label # a string if 'label_color' in kwds: label_color = kwds.pop('label_color') else: label_color = 'black' if 'label_fontsize' in kwds: label_fontsize = kwds.pop('label_fontsize') else: label_fontsize = 14 if 'label_offset' in kwds: has_offset = True label_offset = kwds.pop('label_offset') else: has_offset = False # give default values below if 'point_size' in kwds: pt_size = kwds.pop('point_size') else: pt_size = 50 if 'ranges' in kwds: ranges_set = True ranges = kwds.pop('ranges') else: ranges_set = False # give default values below # the extra keywords have now been handled # now create the plot if hyperplane.dimension() == 0: # a point on a line x, = hyperplane.A() d = hyperplane.b() p = point((d/x,0), size = pt_size, **kwds) if has_hyp_label: if not has_offset: label_offset = 0.1 p += text(label, (d/x,label_offset), color=label_color,fontsize=label_fontsize) p += text('',(d/x,label_offset+0.4)) # add space at top if 'ymax' not in kwds: kwds['ymax'] = 0.5 elif hyperplane.dimension() == 1: # a line in the plane pnt = hyperplane.point() w = hyperplane.linear_part().matrix() t = SR.var('t') if ranges_set: if isinstance(ranges, (list, tuple)): t0, t1 = ranges else: # ranges should be a single positive number t0, t1 = -ranges, ranges else: # default t0, t1 = -3, 3 p = parametric_plot(pnt + t * w[0], (t, t0, t1), **kwds) if has_hyp_label: if has_offset: b0, b1 = label_offset else: b0, b1 = 0, 0.2 label = text(label,(pnt[0] + b0, pnt[1] + b1), color=label_color,fontsize=label_fontsize) p += label elif hyperplane.dimension() == 2: # a plane in 3-space pnt = hyperplane.point() w = hyperplane.linear_part().matrix() s, t = SR.var('s t') if ranges_set: if isinstance(ranges, (list, tuple)): s0, s1 = ranges[0] t0, t1 = ranges[1] else: # ranges should be a single positive integers s0, s1 = -ranges, ranges t0, t1 = -ranges, ranges else: # default s0, s1 = -3, 3 t0, t1 = -3, 3 p = parametric_plot3d(pnt+s*w[0]+t*w[1], (s,s0,s1), (t,t0,t1), **kwds) if has_hyp_label: if has_offset: b0, b1, b2 = label_offset else: b0, b1, b2 = 0, 0, 0 label = text3d(label,(pnt[0]+b0, pnt[1]+b1, pnt[2]+b2), color=label_color, fontsize=label_fontsize) p += label return p def legend_3d(hyperplane_arrangement, hyperplane_colors, length): r""" Create plot of a 3d legend for an arrangement of planes in 3-space. The ``length`` parameter determines whether short or long labels are used in the legend. INPUT: - ``hyperplane_arrangement`` -- a hyperplane arrangement - ``hyperplane_colors`` -- list of colors - ``length`` -- either ``'short'`` or ``'long'`` OUTPUT: - A graphics object. EXAMPLES:: sage: a = hyperplane_arrangements.semiorder(3) sage: from sage.geometry.hyperplane_arrangement.plot import legend_3d sage: legend_3d(a, list(colors.values())[:6],length='long') Graphics object consisting of 6 graphics primitives sage: b = hyperplane_arrangements.semiorder(4) sage: c = b.essentialization() sage: legend_3d(c, list(colors.values())[:12], length='long') Graphics object consisting of 12 graphics primitives sage: legend_3d(c, list(colors.values())[:12], length='short') Graphics object consisting of 12 graphics primitives sage: p = legend_3d(c, list(colors.values())[:12], length='short') sage: p.set_legend_options(ncol=4) sage: type(p) <class 'sage.plot.graphics.Graphics'> """ if hyperplane_arrangement.dimension() != 3: raise ValueError('arrangements must be in 3-space') hyps = hyperplane_arrangement.hyperplanes() N = len(hyperplane_arrangement) if length == 'short': labels = [' ' + str(i) for i in range(N)] else: labels = [' ' + hyps[i]._repr_linear(include_zero=False) for i in range(N)] p = Graphics() for i in range(N): p += line([(0,0),(0,0)], color=hyperplane_colors[i], thickness=8, legend_label=labels[i], axes=False) p.set_legend_options(title='Hyperplanes', loc='center', labelspacing=0.4, fancybox=True, font_size='x-large', ncol=2) p.legend(True) return p
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/hyperplane_arrangement/plot.py
0.848282
0.535888
plot.py
pypi
r""" Base class for mutable polyhedra. Just like vectors and matrices they can be set immutable. The constructor does this by default. """ from .base import Polyhedron_base class Polyhedron_mutable(Polyhedron_base): """ Base class for polyhedra that allow mutability. This should not be used directly. """ def __hash__(self): r""" TESTS:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: set([p]) Traceback (most recent call last): ... TypeError: mutable polyhedra are unhashable sage: p.set_immutable() sage: set([p]) {A 0-dimensional polyhedron in ZZ^2 defined as the convex hull of 1 vertex} """ if self._is_mutable: raise TypeError("mutable polyhedra are unhashable") return Polyhedron_base.__hash__(self) def _clear_cache(self): r""" Clear the Vrepresentation and Hrepresentation data of ``self``. TESTS:: sage: p = polytopes.permutahedron(4) sage: P = p.parent() sage: q = P._element_constructor_(p, mutable=True) sage: TestSuite(q).run() sage: q._clear_cache() sage: TestSuite(q).run() :: sage: q.set_immutable() sage: q._clear_cache() Traceback (most recent call last): ... TypeError: cannot clear cache of immutable polyhedra """ if not self._is_mutable: raise TypeError("cannot clear cache of immutable polyhedra") # Invalidate object pointing towards this polyhedron (faces etc.). for ob in self._dependent_objects: ob._polyhedron = None backend_object = self.__dict__["_" + self._backend_object_name] del self.__dict__ self.__dict__["_" + self._backend_object_name] = backend_object self._is_mutable = True self._dependent_objects = [] def _add_dependent_object(self, ob): r""" Add an object that has ``self`` has attribute ``_polyhedron``. When ``self`` is modified, we delete this attribute to invalidate those objects. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: class foo: ....: def __init__(self, p): ....: self._polyhedron = p ....: sage: a = foo(p) sage: a.__dict__ {'_polyhedron': A 0-dimensional polyhedron in ZZ^2 defined as the convex hull of 1 vertex} sage: p._add_dependent_object(a) sage: p._clear_cache() sage: a.__dict__ {'_polyhedron': None} TESTS:: sage: from sage.geometry.newton_polygon import NewtonPolygon sage: p = Polyhedron([[1, 1]], mutable=True) sage: n = NewtonPolygon(p) sage: n Finite Newton polygon with 1 vertex: (1, 1) sage: n = NewtonPolygon(p) sage: p._clear_cache() sage: n <repr(<sage.geometry.newton_polygon.ParentNewtonPolygon_with_category.element_class at ...>) failed: AttributeError: 'NoneType' object has no attribute 'vertices'> :: sage: f = p.faces(0)[0]; f A 0-dimensional face of a Polyhedron in ZZ^2 defined as the convex hull of 1 vertex sage: p._clear_cache() sage: f <repr(<sage.geometry.polyhedron.face.PolyhedronFace at ...>) failed: AttributeError: 'NoneType' object has no attribute 'parent'> :: sage: v = p.vertices()[0] sage: p = Polyhedron([[1, 1]], mutable=True) sage: v = p.Vrepresentation(0); v A vertex at (1, 1) sage: h = p.Hrepresentation(0); h An equation (0, 1) x - 1 == 0 sage: p._clear_cache() sage: v.polyhedron() is None True sage: h.polyhedron() is None True :: sage: p = Polyhedron([[1, 0], [0, 1]], mutable=True) sage: r = p.relative_interior() sage: p._clear_cache() sage: r Relative interior of None """ if not ob._polyhedron is self: raise ValueError self._dependent_objects.append(ob) def is_mutable(self): r""" Return True if the polyhedron is mutable, i.e. it can be modified in place. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: p.is_mutable() True sage: p = Polyhedron([[1, 1]], mutable=False) sage: p.is_mutable() False """ return self._is_mutable def is_immutable(self): r""" Return True if the polyhedron is immutable, i.e. it cannot be modified in place. EXAMPLES:: sage: p = Polyhedron([[1, 1]], mutable=True) sage: p.is_immutable() False sage: p = Polyhedron([[1, 1]], mutable=False) sage: p.is_immutable() True """ return not self._is_mutable def set_immutable(self): r""" Make this polyhedron immutable. This operation cannot be undone. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.set_immutable(p) Traceback (most recent call last): ... NotImplementedError: a derived class must implement this """ raise NotImplementedError("a derived class must implement this") def Vrepresentation(self): r""" A derived class must overwrite such that it restores Vrepresentation after clearing it. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.Vrepresentation(p) Traceback (most recent call last): ... NotImplementedError: a derived class must implement this """ # A derived class must implemented it to recalculate, if necessary. raise NotImplementedError("a derived class must implement this") def Hrepresentation(self): r""" A derived class must overwrite such that it restores Hrepresentation after clearing it. TESTS:: sage: from sage.geometry.polyhedron.base_mutable import Polyhedron_mutable sage: p = polytopes.cube() sage: Polyhedron_mutable.Hrepresentation(p) Traceback (most recent call last): ... NotImplementedError: a derived class must implement this """ # A derived class must implemented it to recalculate, if necessary. raise NotImplementedError("a derived class must implement this")
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/polyhedron/base_mutable.py
0.852522
0.614886
base_mutable.py
pypi
from .base import Polyhedron_base class Polyhedron_field(Polyhedron_base): """ Polyhedra over all fields supported by Sage INPUT: - ``Vrep`` -- a list ``[vertices, rays, lines]`` or ``None``. - ``Hrep`` -- a list ``[ieqs, eqns]`` or ``None``. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,0),(AA(2).sqrt(),0),(0,AA(3).sqrt())], # optional - sage.rings.number_field ....: rays=[(1,1)], lines=[], backend='field', base_ring=AA) sage: TestSuite(p).run() # optional - sage.rings.number_field TESTS:: sage: K.<sqrt3> = QuadraticField(3) # optional - sage.rings.number_field sage: p = Polyhedron([(0,0), (1,0), (1/2, sqrt3/2)]) # optional - sage.rings.number_field sage: TestSuite(p).run() # optional - sage.rings.number_field Check that :trac:`19013` is fixed:: sage: K.<phi> = NumberField(x^2-x-1, embedding=1.618) # optional - sage.rings.number_field sage: P1 = Polyhedron([[0,1],[1,1],[1,-phi+1]]) # optional - sage.rings.number_field sage: P2 = Polyhedron(ieqs=[[-1,-phi,0]]) # optional - sage.rings.number_field sage: P1.intersection(P2) # optional - sage.rings.number_field The empty polyhedron in (Number Field in phi with defining polynomial x^2 - x - 1 with phi = 1.618033988749895?)^2 Check that :trac:`28654` is fixed:: sage: Polyhedron(lines=[[1]], backend='field') A 1-dimensional polyhedron in QQ^1 defined as the convex hull of 1 vertex and 1 line """ def _is_zero(self, x): """ Test whether ``x`` is zero. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_zero(0) # optional - sage.rings.number_field True sage: p._is_zero(1/100000) # optional - sage.rings.number_field False """ return x == 0 def _is_nonneg(self, x): """ Test whether ``x`` is nonnegative. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_nonneg(1) # optional - sage.rings.number_field True sage: p._is_nonneg(-1/100000) # optional - sage.rings.number_field False """ return x >= 0 def _is_positive(self, x): """ Test whether ``x`` is positive. INPUT: - ``x`` -- a number in the base ring. OUTPUT: Boolean. EXAMPLES:: sage: p = Polyhedron([(sqrt(3),sqrt(2))], base_ring=AA) # optional - sage.rings.number_field sage: p._is_positive(1) # optional - sage.rings.number_field True sage: p._is_positive(0) # optional - sage.rings.number_field False """ return x > 0 def _init_from_Vrepresentation_and_Hrepresentation(self, Vrep, Hrep): """ Construct polyhedron from V-representation and H-representation data. See :class:`Polyhedron_base` for a description of ``Vrep`` and ``Hrep``. .. WARNING:: The representation is assumed to be correct. It is not checked. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p # optional - sage.rings.number_field A 1-dimensional polyhedron in AA^1 defined as the convex hull of 2 vertices """ self._init_Vrepresentation(*Vrep) self._init_Hrepresentation(*Hrep) def _init_from_Vrepresentation(self, vertices, rays, lines, minimize=True, verbose=False): """ Construct polyhedron from V-representation data. INPUT: - ``vertices`` -- list of points. Each point can be specified as any iterable container of :meth:`~sage.geometry.polyhedron.base.base_ring` elements. - ``rays`` -- list of rays. Each ray can be specified as any iterable container of :meth:`~sage.geometry.polyhedron.base.base_ring` elements. - ``lines`` -- list of lines. Each line can be specified as any iterable container of :meth:`~sage.geometry.polyhedron.base.base_ring` elements. - ``verbose`` -- boolean (default: ``False``). Whether to print verbose output for debugging purposes. EXAMPLES:: sage: p = Polyhedron(ambient_dim=2, backend='field') sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: Polyhedron_field._init_from_Vrepresentation(p, [(0,0)], [], []) """ from sage.geometry.polyhedron.double_description_inhomogeneous import Hrep2Vrep, Vrep2Hrep H = Vrep2Hrep(self.base_ring(), self.ambient_dim(), vertices, rays, lines) V = Hrep2Vrep(self.base_ring(), self.ambient_dim(), H.inequalities, H.equations) self._init_Vrepresentation_backend(V) self._init_Hrepresentation_backend(H) def _init_from_Hrepresentation(self, ieqs, eqns, minimize=True, verbose=False): """ Construct polyhedron from H-representation data. INPUT: - ``ieqs`` -- list of inequalities. Each line can be specified as any iterable container of :meth:`~sage.geometry.polyhedron.base.base_ring` elements. - ``eqns`` -- list of equalities. Each line can be specified as any iterable container of :meth:`~sage.geometry.polyhedron.base.base_ring` elements. - ``verbose`` -- boolean (default: ``False``). Whether to print verbose output for debugging purposes. TESTS:: sage: p = Polyhedron(ambient_dim=2, backend='field') sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: Polyhedron_field._init_from_Hrepresentation(p, [(1, 2, 3)], []) """ from sage.geometry.polyhedron.double_description_inhomogeneous import Hrep2Vrep, Vrep2Hrep V = Hrep2Vrep(self.base_ring(), self.ambient_dim(), ieqs, eqns) H = Vrep2Hrep(self.base_ring(), self.ambient_dim(), V.vertices, V.rays, V.lines) self._init_Vrepresentation_backend(V) self._init_Hrepresentation_backend(H) def _init_Vrepresentation(self, vertices, rays, lines): """ Create the Vrepresentation objects from the given minimal data. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p.vertices_list() # optional - sage.rings.number_field [[0], [1]] """ self._Vrepresentation = [] parent = self.parent() for v in vertices: parent._make_Vertex(self, v) for r in rays: parent._make_Ray(self, r) for l in lines: parent._make_Line(self, l) self._Vrepresentation = tuple(self._Vrepresentation) def _init_Vrepresentation_backend(self, Vrep): """ Create the V-representation objects from the double description. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,1/sqrt(2)),(sqrt(2),0),(4,sqrt(5)/6)], # optional - sage.rings.number_field ....: base_ring=AA, backend='field') # indirect doctest sage: p.Hrepresentation() # optional - sage.rings.number_field (An inequality (-0.1582178750233332?, 1.097777812326429?) x + 0.2237538646678492? >= 0, An inequality (-0.1419794359520263?, -1.698172434277148?) x + 1.200789243901438? >= 0, An inequality (0.3001973109753594?, 0.600394621950719?) x - 0.4245431085692869? >= 0) sage: p.Vrepresentation() # optional - sage.rings.number_field (A vertex at (0.?e-15, 0.707106781186548?), A vertex at (1.414213562373095?, 0), A vertex at (4.000000000000000?, 0.372677996249965?)) """ self._init_Vrepresentation(Vrep.vertices, Vrep.rays, Vrep.lines) def _init_Hrepresentation(self, inequalities, equations): """ Create the Vrepresentation objects from the given minimal data. EXAMPLES:: sage: from sage.geometry.polyhedron.parent import Polyhedra_field sage: from sage.geometry.polyhedron.backend_field import Polyhedron_field sage: parent = Polyhedra_field(AA, 1, 'field') # optional - sage.rings.number_field sage: Vrep = [[[0], [1]], [], []] sage: Hrep = [[[0, 1], [1, -1]], []] sage: p = Polyhedron_field(parent, Vrep, Hrep, # indirect doctest # optional - sage.rings.number_field ....: Vrep_minimal=True, Hrep_minimal=True) sage: p.inequalities_list() # optional - sage.rings.number_field [[0, 1], [1, -1]] """ self._Hrepresentation = [] parent = self.parent() for ieq in inequalities: parent._make_Inequality(self, ieq) for eqn in equations: parent._make_Equation(self, eqn) self._Hrepresentation = tuple(self._Hrepresentation) def _init_Hrepresentation_backend(self, Hrep): """ Create the H-representation objects from the double description. EXAMPLES:: sage: p = Polyhedron(vertices=[(0,1/sqrt(2)),(sqrt(2),0),(4,sqrt(5)/6)], # optional - sage.rings.number_field ....: base_ring=AA, backend='field') # indirect doctest sage: p.Hrepresentation() # optional - sage.rings.number_field (An inequality (-0.1582178750233332?, 1.097777812326429?) x + 0.2237538646678492? >= 0, An inequality (-0.1419794359520263?, -1.698172434277148?) x + 1.200789243901438? >= 0, An inequality (0.3001973109753594?, 0.600394621950719?) x - 0.4245431085692869? >= 0) sage: p.Vrepresentation() # optional - sage.rings.number_field (A vertex at (0.?e-15, 0.707106781186548?), A vertex at (1.414213562373095?, 0), A vertex at (4.000000000000000?, 0.372677996249965?)) """ self._init_Hrepresentation(Hrep.inequalities, Hrep.equations) def _init_empty_polyhedron(self): """ Initializes an empty polyhedron. TESTS:: sage: empty = Polyhedron(backend='field', base_ring=AA); empty # optional - sage.rings.number_field The empty polyhedron in AA^0 sage: empty.Vrepresentation() # optional - sage.rings.number_field () sage: empty.Hrepresentation() # optional - sage.rings.number_field (An equation -1 == 0,) sage: Polyhedron(vertices=[], backend='field') The empty polyhedron in QQ^0 sage: Polyhedron(backend='field')._init_empty_polyhedron() """ super(Polyhedron_field, self)._init_empty_polyhedron()
/sagemath-polyhedra-9.5b6.tar.gz/sagemath-polyhedra-9.5b6/sage/geometry/polyhedron/backend_field.py
0.937318
0.556641
backend_field.py
pypi